org-list: small refactoring and comments improvements
[org-mode/org-mode-NeilSmithlineMods.git] / lisp / org-list.el
blob91467ce00f0a56fd29294d925857c189e56db51c
1 ;;; org-list.el --- Plain lists for Org-mode
2 ;;
3 ;; Copyright (C) 2004, 2005, 2006, 2007, 2008, 2009, 2010
4 ;; Free Software Foundation, Inc.
5 ;;
6 ;; Author: Carsten Dominik <carsten at orgmode dot org>
7 ;; Bastien Guerry <bzg AT altern DOT org>
8 ;; Keywords: outlines, hypermedia, calendar, wp
9 ;; Homepage: http://orgmode.org
10 ;; Version: 7.4
12 ;; This file is part of GNU Emacs.
14 ;; GNU Emacs is free software: you can redistribute it and/or modify
15 ;; it under the terms of the GNU General Public License as published by
16 ;; the Free Software Foundation, either version 3 of the License, or
17 ;; (at your option) any later version.
19 ;; GNU Emacs is distributed in the hope that it will be useful,
20 ;; but WITHOUT ANY WARRANTY; without even the implied warranty of
21 ;; MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
22 ;; GNU General Public License for more details.
24 ;; You should have received a copy of the GNU General Public License
25 ;; along with GNU Emacs. If not, see <http://www.gnu.org/licenses/>.
26 ;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;
28 ;;; Commentary:
30 ;; This file contains the code dealing with plain lists in Org-mode.
32 ;; The fundamental idea behind lists work is to use structures. A
33 ;; structure is a snapshot of the list, in the shape of data tree (see
34 ;; `org-list-struct').
36 ;; Once the list structure is stored, it is possible to make changes
37 ;; directly on it or get useful information on the list, with helper
38 ;; functions `org-list-struct-parent-alist' and
39 ;; `org-list-struct-prev-alist', and using accessors provided in the
40 ;; file.
42 ;; Structure is repaired with `org-list-struct-fix-struct'. Then
43 ;; changes are applied to buffer with `org-list-struct-apply-struct'.
45 ;; So any function working on plain lists should follow this template:
46 ;; 1. Verify point is in a list and grab item beginning (with the same
47 ;; function `org-in-item-p') ;
48 ;; 2. Get list structure ;
49 ;; 3. Compute one, or both, helper functions depending on required
50 ;; accessors ;
51 ;; 4. Proceed with the modifications ;
52 ;; 5. Then fix the structure one last time and apply it on buffer.
54 ;; It is usally a bad idea to use directly an interactive function
55 ;; inside a function, as those read the whole list structure another
56 ;; time.
58 ;;; Code:
60 (eval-when-compile
61 (require 'cl))
62 (require 'org-macs)
63 (require 'org-compat)
65 (defvar org-blank-before-new-entry)
66 (defvar org-M-RET-may-split-line)
67 (defvar org-complex-heading-regexp)
68 (defvar org-odd-levels-only)
69 (defvar org-outline-regexp)
70 (defvar org-ts-regexp)
71 (defvar org-ts-regexp-both)
73 (declare-function org-at-heading-p "org" (&optional ignored))
74 (declare-function org-back-over-empty-lines "org" ())
75 (declare-function org-back-to-heading "org" (&optional invisible-ok))
76 (declare-function org-combine-plists "org" (&rest plists))
77 (declare-function org-entry-get "org"
78 (pom property &optional inherit literal-nil))
79 (declare-function org-get-indentation "org" (&optional line))
80 (declare-function org-icompleting-read "org" (&rest args))
81 (declare-function org-in-regexps-block-p "org"
82 (start-re end-re &optional bound))
83 (declare-function org-inlinetask-goto-beginning "org-inlinetask" ())
84 (declare-function org-inlinetask-goto-end "org-inlinetask" ())
85 (declare-function org-inlinetask-in-task-p "org-inlinetask" ())
86 (declare-function org-invisible-p "org" ())
87 (declare-function org-level-increment "org" ())
88 (declare-function org-narrow-to-subtree "org" ())
89 (declare-function org-on-heading-p "org" (&optional invisible-ok))
90 (declare-function org-remove-if "org" (predicate seq))
91 (declare-function org-show-subtree "org" ())
92 (declare-function org-time-string-to-seconds "org" (s))
93 (declare-function org-timer-hms-to-secs "org-timer" (hms))
94 (declare-function org-timer-item "org-timer" (&optional arg))
95 (declare-function org-trim "org" (s))
96 (declare-function org-uniquify "org" (list))
97 (declare-function outline-next-heading "outline" ())
98 (declare-function outline-previous-heading "outline" ())
100 (defgroup org-plain-lists nil
101 "Options concerning plain lists in Org-mode."
102 :tag "Org Plain lists"
103 :group 'org-structure)
105 (defcustom org-cycle-include-plain-lists t
106 "When t, make TAB cycle visibility on plain list items.
107 Cycling plain lists works only when the cursor is on a plain list
108 item. When the cursor is on an outline heading, plain lists are
109 treated as text. This is the most stable way of handling this,
110 which is why it is the default.
112 When this is the symbol `integrate', then during cycling, plain
113 list items will *temporarily* be interpreted as outline headlines
114 with a level given by 1000+i where i is the indentation of the
115 bullet. This setting can lead to strange effects when switching
116 visibility to `children', because the first \"child\" in a
117 subtree decides what children should be listed. If that first
118 \"child\" is a plain list item with an implied large level
119 number, all true children and grand children of the outline
120 heading will be exposed in a children' view."
121 :group 'org-plain-lists
122 :type '(choice
123 (const :tag "Never" nil)
124 (const :tag "With cursor in plain list (recommended)" t)
125 (const :tag "As children of outline headings" integrate)))
127 (defcustom org-list-demote-modify-bullet nil
128 "Default bullet type installed when demoting an item.
129 This is an association list, for each bullet type, this alist will point
130 to the bullet that should be used when this item is demoted.
131 For example,
133 (setq org-list-demote-modify-bullet
134 '((\"+\" . \"-\") (\"-\" . \"+\") (\"*\" . \"+\")))
136 will make
138 + Movies
139 + Silence of the Lambs
140 + My Cousin Vinny
141 + Books
142 + The Hunt for Red October
143 + The Road to Omaha
145 into
147 + Movies
148 - Silence of the Lambs
149 - My Cousin Vinny
150 + Books
151 - The Hunt for Red October
152 - The Road to Omaha"
153 :group 'org-plain-lists
154 :type '(repeat
155 (cons
156 (choice :tag "If the current bullet is "
157 (const "-")
158 (const "+")
159 (const "*")
160 (const "1.")
161 (const "1)"))
162 (choice :tag "demotion will change it to"
163 (const "-")
164 (const "+")
165 (const "*")
166 (const "1.")
167 (const "1)")))))
169 (defcustom org-plain-list-ordered-item-terminator t
170 "The character that makes a line with leading number an ordered list item.
171 Valid values are ?. and ?\). To get both terminators, use t. While
172 ?. may look nicer, it creates the danger that a line with leading
173 number may be incorrectly interpreted as an item. ?\) therefore is
174 the safe choice."
175 :group 'org-plain-lists
176 :type '(choice (const :tag "dot like in \"2.\"" ?.)
177 (const :tag "paren like in \"2)\"" ?\))
178 (const :tab "both" t)))
180 (defcustom org-alphabetical-lists nil
181 "Non-nil means single character alphabetical bullets are allowed.
182 Both uppercase and lowercase are handled. Lists with more than 26
183 items will fallback to standard numbering."
184 :group 'org-plain-lists
185 :type 'boolean)
187 (defcustom org-list-two-spaces-after-bullet-regexp nil
188 "A regular expression matching bullets that should have 2 spaces after them.
189 When nil, no bullet will have two spaces after them.
190 When a string, it will be used as a regular expression. When the
191 bullet type of a list is changed, the new bullet type will be
192 matched against this regexp. If it matches, there will be two
193 spaces instead of one after the bullet in each item of the list."
194 :group 'org-plain-lists
195 :type '(choice
196 (const :tag "never" nil)
197 (regexp)))
199 (defcustom org-list-ending-method 'both
200 "Determine where plain lists should end.
201 Valid values are: `regexp', `indent' or `both'.
203 When set to `regexp', Org will look into two variables,
204 `org-empty-line-terminates-plain-lists' and the more general
205 `org-list-end-regexp', to determine what will end lists.
207 When set to `indent', a list will end whenever a line following
208 an item, but not starting one, is less or equally indented than
209 the first item of the list.
211 When set to `both', each of the preceding methods is applied to
212 determine lists endings. This is the default method."
213 :group 'org-plain-lists
214 :type '(choice
215 (const :tag "With a regexp defining ending" regexp)
216 (const :tag "With indentation of regular (no bullet) text" indent)
217 (const :tag "With both methods" both)))
219 (defcustom org-empty-line-terminates-plain-lists nil
220 "Non-nil means an empty line ends all plain list levels.
221 This variable only makes sense if `org-list-ending-method' is set
222 to `regexp' or `both'. This is then equivalent to set
223 `org-list-end-regexp' to \"^[ \\t]*$\"."
224 :group 'org-plain-lists
225 :type 'boolean)
227 (defcustom org-list-end-regexp "^[ \t]*\n[ \t]*\n"
228 "Regexp matching the end of all plain list levels.
229 It must start with \"^\" and end with \"\\n\". It defaults to 2
230 blank lines. `org-empty-line-terminates-plain-lists' has
231 precedence over it."
232 :group 'org-plain-lists
233 :type 'string)
235 (defcustom org-list-automatic-rules '((bullet . t)
236 (checkbox . t)
237 (indent . t))
238 "Non-nil means apply set of rules when acting on lists.
239 By default, automatic actions are taken when using
240 \\[org-meta-return], \\[org-metaright], \\[org-metaleft],
241 \\[org-shiftmetaright], \\[org-shiftmetaleft],
242 \\[org-ctrl-c-minus], \\[org-toggle-checkbox] or
243 \\[org-insert-todo-heading]. You can disable individually these
244 rules by setting them to nil. Valid rules are:
246 bullet when non-nil, cycling bullet do not allow lists at
247 column 0 to have * as a bullet and descriptions lists
248 to be numbered.
249 checkbox when non-nil, checkbox statistics is updated each time
250 you either insert a new checkbox or toggle a checkbox.
251 It also prevents from inserting a checkbox in a
252 description item.
253 indent when non-nil, indenting or outdenting list top-item
254 with its subtree will move the whole list and
255 outdenting a list whose bullet is * to column 0 will
256 change that bullet to \"-\"."
257 :group 'org-plain-lists
258 :type '(alist :tag "Sets of rules"
259 :key-type
260 (choice
261 (const :tag "Bullet" bullet)
262 (const :tag "Checkbox" checkbox)
263 (const :tag "Indent" indent)
264 (const :tag "Insert" insert))
265 :value-type
266 (boolean :tag "Activate" :value t)))
268 (defcustom org-hierarchical-checkbox-statistics t
269 "Non-nil means checkbox statistics counts only the state of direct children.
270 When nil, all boxes below the cookie are counted.
271 This can be set to nil on a per-node basis using a COOKIE_DATA property
272 with the word \"recursive\" in the value."
273 :group 'org-plain-lists
274 :type 'boolean)
276 (defcustom org-description-max-indent 20
277 "Maximum indentation for the second line of a description list.
278 When the indentation would be larger than this, it will become
279 5 characters instead."
280 :group 'org-plain-lists
281 :type 'integer)
283 (defcustom org-list-radio-list-templates
284 '((latex-mode "% BEGIN RECEIVE ORGLST %n
285 % END RECEIVE ORGLST %n
286 \\begin{comment}
287 #+ORGLST: SEND %n org-list-to-latex
289 \\end{comment}\n")
290 (texinfo-mode "@c BEGIN RECEIVE ORGLST %n
291 @c END RECEIVE ORGLST %n
292 @ignore
293 #+ORGLST: SEND %n org-list-to-texinfo
295 @end ignore\n")
296 (html-mode "<!-- BEGIN RECEIVE ORGLST %n -->
297 <!-- END RECEIVE ORGLST %n -->
298 <!--
299 #+ORGLST: SEND %n org-list-to-html
301 -->\n"))
302 "Templates for radio lists in different major modes.
303 All occurrences of %n in a template will be replaced with the name of the
304 list, obtained by prompting the user."
305 :group 'org-plain-lists
306 :type '(repeat
307 (list (symbol :tag "Major mode")
308 (string :tag "Format"))))
310 (defvar org-list-forbidden-blocks '("example" "verse" "src")
311 "Names of blocks where lists are not allowed.
312 Names must be in lower case.")
314 (defvar org-list-export-context '(block inlinetask)
315 "Context types where lists will be interpreted during export.
317 Valid types are `drawer', `inlinetask' and `block'. More
318 specifically, type `block' is determined by the variable
319 `org-list-forbidden-blocks'.")
321 ;;; Internal functions
323 (defconst org-list-end-re (if org-empty-line-terminates-plain-lists
324 "^[ \t]*\n"
325 org-list-end-regexp)
326 "Regex corresponding to the end of a list.
327 It depends on `org-empty-line-terminates-plain-lists'.")
329 (defun org-item-re ()
330 "Return the correct regular expression for plain lists."
331 (let ((term (cond
332 ((eq org-plain-list-ordered-item-terminator t) "[.)]")
333 ((= org-plain-list-ordered-item-terminator ?\)) ")")
334 ((= org-plain-list-ordered-item-terminator ?.) "\\.")
335 (t "[.)]")))
336 (alpha (if org-alphabetical-lists "\\|[A-Za-z]" "")))
337 (concat "\\([ \t]*\\([-+]\\|\\(\\([0-9]+" alpha "\\)" term
338 "\\)\\)\\|[ \t]+\\*\\)\\([ \t]+\\|$\\)")))
340 (defun org-item-beginning-re ()
341 "Regexp matching the beginning of a plain list item."
342 (concat "^" (org-item-re)))
344 (defconst org-list-full-item-re
345 (concat "^[ \t]*\\(\\(?:[-+*]\\|\\(?:[0-9]+\\|[A-Za-z]\\)[.)]\\)[ \t]+\\)"
346 "\\(?:\\[@\\(?:start:\\)?\\([0-9]+\\|[A-Za-z]\\)\\]\\)?"
347 "\\(?:\\(\\[[ X-]\\]\\)[ \t]+\\)?"
348 "\\(?:\\(.*\\)[ \t]+::[ \t]+\\)?")
349 "Matches a list item and puts everything into groups:
350 group 1: bullet
351 group 2: counter
352 group 3: checkbox
353 group 4: description tag")
355 (defun org-list-context ()
356 "Determine context, and its boundaries, around point.
358 Context will be an alist like (MIN MAX CONTEXT) where MIN and MAX
359 are boundaries and CONTEXT is a symbol among `drawer', `block',
360 `invalid', `inlinetask' and nil.
362 Contexts `block' and `invalid' refer to `org-list-forbidden-blocks'."
363 (save-match-data
364 (save-excursion
365 (beginning-of-line)
366 (let* ((outline-regexp (org-get-limited-outline-regexp))
367 ;; Can't use org-drawers-regexp as this function might be
368 ;; called in buffers not in Org mode
369 (drawers-re (concat "^[ \t]*:\\("
370 (mapconcat 'regexp-quote org-drawers "\\|")
371 "\\):[ \t]*$"))
372 (case-fold-search t)
373 ;; Compute position of surrounding headings. This is the
374 ;; default context.
375 (heading
376 (save-excursion
377 (list
378 (or (and (org-at-heading-p) (point-at-bol))
379 (outline-previous-heading)
380 (point-min))
381 (or (outline-next-heading)
382 (point-max))
383 nil)))
384 (prev-head (car heading))
385 (next-head (nth 1 heading))
386 ;; Is point inside a drawer?
387 (drawerp
388 (when (and (org-in-regexps-block-p
389 drawers-re "^[ \t]*:END:" prev-head)
390 (save-excursion
391 (beginning-of-line)
392 (and (not (looking-at drawers-re))
393 (not (looking-at "^[ \t]*:END:")))))
394 (save-excursion
395 (list
396 (progn
397 (re-search-backward drawers-re prev-head t)
398 (1+ (point-at-eol)))
399 (if (re-search-forward "^[ \t]*:END:" next-head t)
400 (1- (point-at-bol))
401 next-head)
402 'drawer))))
403 ;; Is point strictly in a block, and of which type?
404 (blockp
405 (save-excursion
406 (when (and (org-in-regexps-block-p
407 "^[ \t]*#\\+begin_" "^[ \t]*#\\+end_" prev-head)
408 (save-excursion
409 (beginning-of-line)
410 (not (looking-at
411 "^[ \t]*#\\+\\(begin\\|end\\)_"))))
412 (list
413 (progn
414 (re-search-backward
415 "^[ \t]*#\\+begin_\\(\\S-+\\)" prev-head t)
416 (1+ (point-at-eol)))
417 (save-match-data
418 (if (re-search-forward "^[ \t]*#\\+end_" next-head t)
419 (1- (point-at-bol))
420 next-head))
421 (if (member (downcase (match-string 1))
422 org-list-forbidden-blocks)
423 'invalid
424 'block)))))
425 ;; Is point in an inlinetask?
426 (inlinetaskp
427 (when (and (featurep 'org-inlinetask)
428 (org-inlinetask-in-task-p)
429 (not (looking-at "^\\*+")))
430 (save-excursion
431 (list
432 (progn (org-inlinetask-goto-beginning)
433 (1+ (point-at-eol)))
434 (progn
435 (org-inlinetask-goto-end)
436 (forward-line -1)
437 (1- (point-at-bol)))
438 'inlinetask))))
439 ;; List actual candidates
440 (context-list
441 (delq nil (list heading drawerp blockp inlinetaskp))))
442 ;; Return the closest context around
443 (assq (apply 'max (mapcar 'car context-list)) context-list)))))
445 (defun org-list-search-generic (search re bound noerr)
446 "Search a string in valid contexts for lists.
447 Arguments SEARCH, RE, BOUND and NOERR are similar to those in
448 `re-search-forward'."
449 (catch 'exit
450 (let ((origin (point)))
451 (while t
452 ;; 1. No match: return to origin or bound, depending on NOERR.
453 (unless (funcall search re bound noerr)
454 (throw 'exit (and (goto-char (if (memq noerr '(t nil)) origin bound))
455 nil)))
456 ;; 2. Match in an `invalid' context: continue searching. Else,
457 ;; return point.
458 (unless (eq (org-list-context) 'invalid) (throw 'exit (point)))))))
460 (defun org-list-search-backward (regexp &optional bound noerror)
461 "Like `re-search-backward' but stop only where lists are recognized.
462 Arguments REGEXP, BOUND and NOERROR are similar to those used in
463 `re-search-backward'."
464 (org-list-search-generic #'re-search-backward
465 regexp (or bound (point-min)) noerror))
467 (defun org-list-search-forward (regexp &optional bound noerror)
468 "Like `re-search-forward' but stop only where lists are recognized.
469 Arguments REGEXP, BOUND and NOERROR are similar to those used in
470 `re-search-forward'."
471 (org-list-search-generic #'re-search-forward
472 regexp (or bound (point-max)) noerror))
474 (defun org-list-at-regexp-after-bullet-p (regexp)
475 "Is point at a list item with REGEXP after bullet?"
476 (and (org-at-item-p)
477 (save-excursion
478 (goto-char (match-end 0))
479 ;; Ignore counter if any
480 (when (looking-at "\\(?:\\[@\\(?:start:\\)?[0-9]+\\][ \t]*\\)?")
481 (goto-char (match-end 0)))
482 (looking-at regexp))))
484 (defun org-list-separating-blank-lines-number (pos struct prevs)
485 "Return number of blank lines that should separate items in list.
486 POS is the position at item beginning to be considered. STRUCT is
487 the list structure. PREVS is the alist of previous items. See
488 `org-list-struct-prev-alist'.
490 Assume point is at item's beginning. If the item is alone, apply
491 some heuristics to guess the result."
492 (save-excursion
493 (let ((insert-blank-p
494 (cdr (assq 'plain-list-item org-blank-before-new-entry)))
495 usr-blank)
496 (cond
497 ;; Trivial cases where there should be none.
498 ((or (and (not (eq org-list-ending-method 'indent))
499 org-empty-line-terminates-plain-lists)
500 (not insert-blank-p)) 0)
501 ;; When `org-blank-before-new-entry' says so, it is 1.
502 ((eq insert-blank-p t) 1)
503 ;; plain-list-item is 'auto. Count blank lines separating
504 ;; neighbours items in list.
505 (t (let ((next-p (org-list-get-next-item (point) struct prevs)))
506 (cond
507 ;; Is there a next item?
508 (next-p (goto-char next-p)
509 (org-back-over-empty-lines))
510 ;; Is there a previous item?
511 ((org-list-get-prev-item (point) struct prevs)
512 (org-back-over-empty-lines))
513 ;; User inserted blank lines, trust him
514 ((and (> pos (org-list-get-item-end-before-blank pos struct))
515 (> (save-excursion
516 (goto-char pos)
517 (skip-chars-backward " \t")
518 (setq usr-blank (org-back-over-empty-lines))) 0))
519 usr-blank)
520 ;; Are there blank lines inside the item ?
521 ((save-excursion
522 (org-list-search-forward
523 "^[ \t]*$" (org-list-get-item-end-before-blank pos struct) t))
525 ;; No parent: no blank line.
526 (t 0))))))))
528 (defun org-list-insert-item-generic (pos &optional checkbox after-bullet)
529 "Insert a new list item at POS.
530 If POS is before first character after bullet of the item, the
531 new item will be created before the current one.
533 Insert a checkbox if CHECKBOX is non-nil, and string AFTER-BULLET
534 after the bullet. Cursor will be after this text once the
535 function ends."
536 (let ((case-fold-search t))
537 ;; 1. Get information about list: structure, usual helper
538 ;; functions, position of point with regards to item start
539 ;; (BEFOREP), blank lines number separating items (BLANK-NB),
540 ;; position of split (POS) if we're allowed to (SPLIT-LINE-P).
541 (let* ((pos (point))
542 (item (goto-char (org-list-get-item-begin)))
543 (struct (org-list-struct))
544 (prevs (org-list-struct-prev-alist struct))
545 (item-end (org-list-get-item-end item struct))
546 (item-end-no-blank (org-list-get-item-end-before-blank item struct))
547 (beforep (and (looking-at org-list-full-item-re)
548 (<= pos (match-end 0))))
549 (split-line-p (org-get-alist-option org-M-RET-may-split-line 'item))
550 (blank-nb (org-list-separating-blank-lines-number
551 item struct prevs))
552 ;; 2. Build the new item to be created. Concatenate same
553 ;; bullet as item, checkbox, text AFTER-BULLET if
554 ;; provided, and text cut from point to end of item
555 ;; (TEXT-CUT) to form item's BODY. TEXT-CUT depends on
556 ;; BEFOREP and SPLIT-LINE-P. The difference of size
557 ;; between what was cut and what was inserted in buffer
558 ;; is stored in SIZE-OFFSET.
559 (ind (org-list-get-ind item struct))
560 (bullet (org-list-bullet-string (org-list-get-bullet item struct)))
561 (box (when checkbox "[ ]"))
562 (text-cut
563 (and (not beforep) split-line-p
564 (progn
565 (goto-char pos)
566 (skip-chars-backward " \r\t\n")
567 (setq pos (point))
568 (delete-and-extract-region pos item-end-no-blank))))
569 (body (concat bullet (when box (concat box " ")) after-bullet
570 (or (and text-cut
571 (if (string-match "\\`[ \t]+" text-cut)
572 (replace-match "" t t text-cut)
573 text-cut))
574 "")))
575 (item-sep (make-string (1+ blank-nb) ?\n))
576 (item-size (+ ind (length body) (length item-sep)))
577 (size-offset (- item-size (length text-cut))))
578 ;; 4. Insert effectively item into buffer
579 (goto-char item)
580 (org-indent-to-column ind)
581 (insert body)
582 (insert item-sep)
583 ;; 5. Add new item to STRUCT.
584 (mapc (lambda (e)
585 (let ((p (car e))
586 (end (nth 6 e)))
587 (cond
588 ;; Before inserted item, positions don't change but
589 ;; an item ending after insertion has its end shifted
590 ;; by SIZE-OFFSET.
591 ((< p item)
592 (when (> end item) (setcar (nthcdr 6 e) (+ end size-offset))))
593 ;; Trivial cases where current item isn't split in
594 ;; two. Just shift every item after new one by
595 ;; ITEM-SIZE.
596 ((or beforep (not split-line-p))
597 (setcar e (+ p item-size))
598 (setcar (nthcdr 6 e) (+ end item-size)))
599 ;; Item is split in two: elements before POS are just
600 ;; shifted by ITEM-SIZE. In the case item would end
601 ;; after split POS, ending is only shifted by
602 ;; SIZE-OFFSET.
603 ((< p pos)
604 (setcar e (+ p item-size))
605 (if (< end pos)
606 (setcar (nthcdr 6 e) (+ end item-size))
607 (setcar (nthcdr 6 e) (+ end size-offset))))
608 ;; Elements after POS are moved into new item. Length
609 ;; of ITEM-SEP has to be removed as ITEM-SEP
610 ;; doesn't appear in buffer yet.
611 ((< p item-end)
612 (setcar e (+ p size-offset (- item pos (length item-sep))))
613 (if (= end item-end)
614 (setcar (nthcdr 6 e) (+ item item-size))
615 (setcar (nthcdr 6 e)
616 (+ end size-offset
617 (- item pos (length item-sep))))))
618 ;; Elements at ITEM-END or after are only shifted by
619 ;; SIZE-OFFSET.
620 (t (setcar e (+ p size-offset))
621 (setcar (nthcdr 6 e) (+ end size-offset))))))
622 struct)
623 (setq struct (sort
624 (cons (list item ind bullet nil box nil (+ item item-size))
625 struct)
626 (lambda (e1 e2) (< (car e1) (car e2)))))
627 ;; 6. If not BEFOREP, new item must appear after ITEM, so
628 ;; exchange ITEM with the next item in list. Position cursor
629 ;; after bullet, counter, checkbox, and label.
630 (if beforep
631 (goto-char item)
632 (setq struct (org-list-exchange-items item (+ item item-size) struct))
633 (goto-char (org-list-get-next-item
634 item struct (org-list-struct-prev-alist struct))))
635 (org-list-struct-fix-struct struct (org-list-struct-parent-alist struct))
636 (when checkbox (org-update-checkbox-count-maybe))
637 (looking-at org-list-full-item-re)
638 (goto-char (match-end 0))
639 t)))
641 (defvar org-last-indent-begin-marker (make-marker))
642 (defvar org-last-indent-end-marker (make-marker))
644 (defun org-list-indent-item-generic (arg no-subtree struct)
645 "Indent a local list item including its children.
646 When number ARG is a negative, item will be outdented, otherwise
647 it will be indented.
649 If a region is active, all items inside will be moved.
651 If NO-SUBTREE is non-nil, only indent the item itself, not its
652 children.
654 STRUCT is the list structure. Return t if successful."
655 (save-excursion
656 (beginning-of-line)
657 (let* ((regionp (org-region-active-p))
658 (rbeg (and regionp (region-beginning)))
659 (rend (and regionp (region-end)))
660 (top (org-list-get-top-point struct))
661 (parents (org-list-struct-parent-alist struct))
662 (prevs (org-list-struct-prev-alist struct))
663 ;; Are we going to move the whole list?
664 (specialp
665 (and (= top (point))
666 (cdr (assq 'indent org-list-automatic-rules))
667 (if no-subtree
668 (error
669 "First item of list cannot move without its subtree")
670 t))))
671 ;; Determine begin and end points of zone to indent. If moving
672 ;; more than one item, save them for subsequent moves.
673 (unless (and (memq last-command '(org-shiftmetaright org-shiftmetaleft))
674 (memq this-command '(org-shiftmetaright org-shiftmetaleft)))
675 (if regionp
676 (progn
677 (set-marker org-last-indent-begin-marker rbeg)
678 (set-marker org-last-indent-end-marker rend))
679 (set-marker org-last-indent-begin-marker (point))
680 (set-marker org-last-indent-end-marker
681 (cond
682 (specialp (org-list-get-bottom-point struct))
683 (no-subtree (1+ (point)))
684 (t (org-list-get-item-end (point) struct))))))
685 (let* ((beg (marker-position org-last-indent-begin-marker))
686 (end (marker-position org-last-indent-end-marker)))
687 (cond
688 ;; Special case: moving top-item with indent rule
689 (specialp
690 (let* ((level-skip (org-level-increment))
691 (offset (if (< arg 0) (- level-skip) level-skip))
692 (top-ind (org-list-get-ind beg struct))
693 (old-struct (mapcar (lambda (e) (copy-alist e)) struct)))
694 (if (< (+ top-ind offset) 0)
695 (error "Cannot outdent beyond margin")
696 ;; Change bullet if necessary
697 (when (and (= (+ top-ind offset) 0)
698 (string-match "*"
699 (org-list-get-bullet beg struct)))
700 (org-list-set-bullet beg struct
701 (org-list-bullet-string "-")))
702 ;; Shift every item by OFFSET and fix bullets. Then
703 ;; apply changes to buffer.
704 (mapc (lambda (e)
705 (let ((ind (org-list-get-ind (car e) struct)))
706 (org-list-set-ind (car e) struct (+ ind offset))))
707 struct)
708 (org-list-struct-fix-bul struct prevs)
709 (org-list-struct-apply-struct struct old-struct))))
710 ;; Forbidden move:
711 ((and (< arg 0)
712 ;; If only one item is moved, it mustn't have a child
713 (or (and no-subtree
714 (not regionp)
715 (org-list-has-child-p beg struct))
716 ;; If a subtree or region is moved, the last item
717 ;; of the subtree mustn't have a child
718 (let ((last-item (caar
719 (reverse
720 (org-remove-if
721 (lambda (e) (>= (car e) end))
722 struct)))))
723 (org-list-has-child-p last-item struct))))
724 (error "Cannot outdent an item without its children"))
725 ;; Normal shifting
727 (let* ((new-parents
728 (if (< arg 0)
729 (org-list-struct-outdent beg end struct parents)
730 (org-list-struct-indent beg end struct parents prevs))))
731 (org-list-struct-fix-struct struct new-parents))
732 (org-update-checkbox-count-maybe))))))
735 ;;; Predicates
737 (defun org-in-item-p ()
738 "Return item beginning position when in a plain list, nil otherwise.
739 This checks `org-list-ending-method'."
740 (save-excursion
741 (beginning-of-line)
742 (unless (or (let ((outline-regexp org-outline-regexp)) (org-at-heading-p))
743 (and (not (eq org-list-ending-method 'indent))
744 (looking-at org-list-end-re)
745 (progn (forward-line -1) (looking-at org-list-end-re))))
746 (or (and (org-at-item-p) (point-at-bol))
747 (let* ((case-fold-search t)
748 (context (org-list-context))
749 (lim-up (car context))
750 (inlinetask-re (and (featurep 'org-inlinetask)
751 (org-inlinetask-outline-regexp)))
752 (ind-ref (if (looking-at "^[ \t]*$")
753 10000
754 (org-get-indentation))))
755 (catch 'exit
756 (while t
757 (let ((ind (org-get-indentation)))
758 (cond
759 ((<= (point) lim-up)
760 (throw 'exit (and (org-at-item-p) (< ind ind-ref) (point))))
761 ((and (not (eq org-list-ending-method 'indent))
762 (looking-at org-list-end-re))
763 (throw 'exit nil))
764 ;; Skip blocks, drawers, inline-tasks, blank lines
765 ((looking-at "^[ \t]*#\\+end_")
766 (re-search-backward "^[ \t]*#\\+begin_" nil t))
767 ((looking-at "^[ \t]*:END:")
768 (re-search-backward org-drawer-regexp nil t)
769 (beginning-of-line))
770 ((and inlinetask-re (looking-at inlinetask-re))
771 (org-inlinetask-goto-beginning)
772 (forward-line -1))
773 ((looking-at "^[ \t]*$")
774 (forward-line -1))
775 ((< ind ind-ref)
776 (if (org-at-item-p)
777 (throw 'exit (point))
778 (setq ind-ref ind)
779 (forward-line -1)))
780 (t (if (and (eq org-list-ending-method 'regexp)
781 (org-at-item-p))
782 (throw 'exit (point))
783 (forward-line -1))))))))))))
785 (defun org-at-item-p ()
786 "Is point in a line starting a hand-formatted item?"
787 (save-excursion (beginning-of-line) (looking-at (org-item-beginning-re))))
789 (defun org-at-item-bullet-p ()
790 "Is point at the bullet of a plain list item?"
791 (and (org-at-item-p)
792 (not (member (char-after) '(?\ ?\t)))
793 (< (point) (match-end 0))))
795 (defun org-at-item-timer-p ()
796 "Is point at a line starting a plain list item with a timer?"
797 (org-list-at-regexp-after-bullet-p
798 "\\([0-9]+:[0-9]+:[0-9]+\\)[ \t]+::[ \t]+"))
800 (defun org-at-item-description-p ()
801 "Is point at a description list item?"
802 (org-list-at-regexp-after-bullet-p "\\(\\S-.+\\)[ \t]+::[ \t]+"))
804 (defun org-at-item-checkbox-p ()
805 "Is point at a line starting a plain-list item with a checklet?"
806 (org-list-at-regexp-after-bullet-p "\\(\\[[- X]\\]\\)[ \t]+"))
808 (defun org-at-item-counter-p ()
809 "Is point at a line starting a plain-list item with a counter?"
810 (and (org-at-item-p)
811 (looking-at org-list-full-item-re)
812 (match-string 2)))
814 ;;; Navigate
816 (defalias 'org-list-get-item-begin 'org-in-item-p)
818 (defun org-beginning-of-item ()
819 "Go to the beginning of the current hand-formatted item.
820 If the cursor is not in an item, throw an error."
821 (interactive)
822 (let ((begin (org-in-item-p)))
823 (if begin (goto-char begin) (error "Not in an item"))))
825 (defun org-beginning-of-item-list ()
826 "Go to the beginning item of the current list or sublist.
827 Return an error if not in a list."
828 (interactive)
829 (let ((begin (org-in-item-p)))
830 (if (not begin)
831 (error "Not in an item")
832 (goto-char begin)
833 (let* ((struct (org-list-struct))
834 (prevs (org-list-struct-prev-alist struct)))
835 (goto-char (org-list-get-list-begin begin struct prevs))))))
837 (defun org-end-of-item-list ()
838 "Go to the end of the current list or sublist.
839 If the cursor in not in an item, throw an error."
840 (interactive)
841 (let ((begin (org-in-item-p)))
842 (if (not begin)
843 (error "Not in an item")
844 (goto-char begin)
845 (let* ((struct (org-list-struct))
846 (prevs (org-list-struct-prev-alist struct)))
847 (goto-char (org-list-get-list-end begin struct prevs))))))
849 (defun org-end-of-item ()
850 "Go to the end of the current hand-formatted item.
851 If the cursor is not in an item, throw an error."
852 (interactive)
853 (let ((begin (org-in-item-p)))
854 (if (not begin)
855 (error "Not in an item")
856 (goto-char begin)
857 (let ((struct (org-list-struct)))
858 (goto-char (org-list-get-item-end begin struct))))))
860 (defun org-previous-item ()
861 "Move to the beginning of the previous item.
862 Item is at the same level in the current plain list. Error if not
863 in a plain list, or if this is the first item in the list."
864 (interactive)
865 (let ((begin (org-in-item-p)))
866 (if (not begin)
867 (error "Not in an item")
868 (goto-char begin)
869 (let* ((struct (org-list-struct))
870 (prevs (org-list-struct-prev-alist struct))
871 (prevp (org-list-get-prev-item begin struct prevs)))
872 (if prevp (goto-char prevp) (error "On first item"))))))
874 (defun org-next-item ()
875 "Move to the beginning of the next item.
876 Item is at the same level in the current plain list. Error if not
877 in a plain list, or if this is the last item in the list."
878 (interactive)
879 (let ((begin (org-in-item-p)))
880 (if (not begin)
881 (error "Not in an item")
882 (goto-char begin)
883 (let* ((struct (org-list-struct))
884 (prevs (org-list-struct-prev-alist struct))
885 (prevp (org-list-get-next-item begin struct prevs)))
886 (if prevp (goto-char prevp) (error "On last item"))))))
888 ;;; Manipulate
890 (defun org-list-exchange-items (beg-A beg-B struct)
891 "Swap item starting at BEG-A with item starting at BEG-B in STRUCT.
892 Blank lines at the end of items are left in place. Return the new
893 structure after the changes.
895 Assume BEG-A is lesser than BEG-B and that BEG-A and BEG-B belong
896 to the same sub-list.
898 This function modifies STRUCT."
899 (save-excursion
900 (let* ((end-A-no-blank (org-list-get-item-end-before-blank beg-A struct))
901 (end-B-no-blank (org-list-get-item-end-before-blank beg-B struct))
902 (end-A (org-list-get-item-end beg-A struct))
903 (end-B (org-list-get-item-end beg-B struct))
904 (size-A (- end-A-no-blank beg-A))
905 (size-B (- end-B-no-blank beg-B))
906 (body-A (buffer-substring beg-A end-A-no-blank))
907 (body-B (buffer-substring beg-B end-B-no-blank))
908 (between-A-no-blank-and-B (buffer-substring end-A-no-blank beg-B))
909 (sub-A (cons beg-A (org-list-get-subtree beg-A struct)))
910 (sub-B (cons beg-B (org-list-get-subtree beg-B struct))))
911 ;; 1. Move effectively items in buffer.
912 (goto-char beg-A)
913 (delete-region beg-A end-B-no-blank)
914 (insert (concat body-B between-A-no-blank-and-B body-A))
915 ;; 2. Now modify struct. No need to re-read the list, the
916 ;; transformation is just a shift of positions. Some special
917 ;; attention is required for items ending at END-A and END-B
918 ;; as empty spaces are not moved there. In others words, item
919 ;; BEG-A will end with whitespaces that were at the end of
920 ;; BEG-B and the same applies to BEG-B.
921 (mapc (lambda (e)
922 (let ((pos (car e)))
923 (cond
924 ((< pos beg-A))
925 ((memq pos sub-A)
926 (let ((end-e (nth 6 e)))
927 (setcar e (+ pos (- end-B-no-blank end-A-no-blank)))
928 (setcar (nthcdr 6 e)
929 (+ end-e (- end-B-no-blank end-A-no-blank)))
930 (when (= end-e end-A) (setcar (nthcdr 6 e) end-B))))
931 ((memq pos sub-B)
932 (let ((end-e (nth 6 e)))
933 (setcar e (- (+ pos beg-A) beg-B))
934 (setcar (nthcdr 6 e) (+ end-e (- beg-A beg-B)))
935 (when (= end-e end-B)
936 (setcar (nthcdr 6 e)
937 (+ beg-A size-B (- end-A end-A-no-blank))))))
938 ((< pos beg-B)
939 (let ((end-e (nth 6 e)))
940 (setcar e (+ pos (- size-B size-A)))
941 (setcar (nthcdr 6 e) (+ end-e (- size-B size-A))))))))
942 struct)
943 (sort struct (lambda (e1 e2) (< (car e1) (car e2)))))))
945 (defun org-move-item-down ()
946 "Move the plain list item at point down, i.e. swap with following item.
947 Subitems (items with larger indentation) are considered part of the item,
948 so this really moves item trees."
949 (interactive)
950 (unless (org-at-item-p) (error "Not at an item"))
951 (let* ((pos (point))
952 (col (current-column))
953 (actual-item (point-at-bol))
954 (struct (org-list-struct))
955 (prevs (org-list-struct-prev-alist struct))
956 (next-item (org-list-get-next-item (point-at-bol) struct prevs)))
957 (if (not next-item)
958 (progn
959 (goto-char pos)
960 (error "Cannot move this item further down"))
961 (setq struct
962 (org-list-exchange-items actual-item next-item struct))
963 ;; Use a short variation of `org-list-struct-fix-struct' as
964 ;; there's no need to go through all the steps.
965 (let ((old-struct (mapcar (lambda (e) (copy-alist e)) struct))
966 (prevs (org-list-struct-prev-alist struct))
967 (parents (org-list-struct-parent-alist struct)))
968 (org-list-struct-fix-bul struct prevs)
969 (org-list-struct-fix-ind struct parents)
970 (org-list-struct-apply-struct struct old-struct)
971 (goto-char (org-list-get-next-item (point-at-bol) struct prevs)))
972 (org-move-to-column col))))
974 (defun org-move-item-up ()
975 "Move the plain list item at point up, i.e. swap with previous item.
976 Subitems (items with larger indentation) are considered part of the item,
977 so this really moves item trees."
978 (interactive)
979 (unless (org-at-item-p) (error "Not at an item"))
980 (let* ((pos (point))
981 (col (current-column))
982 (actual-item (point-at-bol))
983 (struct (org-list-struct))
984 (prevs (org-list-struct-prev-alist struct))
985 (prev-item (org-list-get-prev-item (point-at-bol) struct prevs)))
986 (if (not prev-item)
987 (progn
988 (goto-char pos)
989 (error "Cannot move this item further up"))
990 (setq struct
991 (org-list-exchange-items prev-item actual-item struct))
992 ;; Use a short variation of `org-list-struct-fix-struct' as
993 ;; there's no need to go through all the steps.
994 (let ((old-struct (mapcar (lambda (e) (copy-alist e)) struct))
995 (prevs (org-list-struct-prev-alist struct))
996 (parents (org-list-struct-parent-alist struct)))
997 (org-list-struct-fix-bul struct prevs)
998 (org-list-struct-fix-ind struct parents)
999 (org-list-struct-apply-struct struct old-struct))
1000 (org-move-to-column col))))
1002 (defun org-insert-item (&optional checkbox)
1003 "Insert a new item at the current level.
1004 If cursor is before first character after bullet of the item, the
1005 new item will be created before the current one.
1007 If CHECKBOX is non-nil, add a checkbox next to the bullet.
1009 Return t when things worked, nil when we are not in an item, or
1010 item is invisible."
1011 (let ((itemp (org-in-item-p)))
1012 (unless (or (not itemp)
1013 (save-excursion
1014 (goto-char itemp)
1015 (org-invisible-p)))
1016 (if (save-excursion
1017 (goto-char itemp)
1018 (org-at-item-timer-p))
1019 ;; Timer list: delegate to `org-timer-item'.
1020 (progn (org-timer-item) t)
1021 ;; if we're in a description list, ask for the new term.
1022 (let ((desc-text (when (save-excursion
1023 (and (goto-char itemp)
1024 (org-at-item-description-p)))
1025 (concat (read-string "Term: ") " :: "))))
1026 ;; Don't insert a checkbox if checkbox rule is applied and it
1027 ;; is a description item.
1028 (org-list-insert-item-generic
1029 (point) (and checkbox
1030 (or (not desc-text)
1031 (not (cdr (assq 'checkbox org-list-automatic-rules)))))
1032 desc-text))))))
1035 ;;; Structures
1037 (defun org-list-struct ()
1038 "Return structure of list at point.
1040 A list structure is an alist where keys is point at item, and
1041 values are:
1042 1. indentation,
1043 2. bullet with trailing whitespace,
1044 3. bullet counter, if any,
1045 4. checkbox, if any,
1046 5. position at item end,
1047 6. description tag, if any.
1049 Thus the following list, where numbers in parens are
1050 point-at-bol:
1052 - [X] first item (1)
1053 1. sub-item 1 (18)
1054 5. [@5] sub-item 2 (34)
1055 some other text belonging to first item (55)
1056 - last item (97)
1057 + tag :: description (109)
1058 (131)
1060 will get the following structure:
1062 \(\(1 0 \"- \" nil [X] nil 97)
1063 \(18 2 \"1. \" nil nil nil 34\)
1064 \(34 2 \"5. \" \"5\" nil nil 55\)
1065 \(97 0 \"- \" nil nil nil 131\)
1066 \(109 2 \"+ \" nil nil \"tag\" 131\)
1068 Assume point is at an item."
1069 (save-excursion
1070 (beginning-of-line)
1071 (let* ((case-fold-search t)
1072 (context (org-list-context))
1073 (lim-up (car context))
1074 (lim-down (nth 1 context))
1075 (text-min-ind 10000)
1076 (drawers-re (concat "^[ \t]*:\\("
1077 (mapconcat 'regexp-quote org-drawers "\\|")
1078 "\\):[ \t]*$"))
1079 (inlinetask-re (and (featurep 'org-inlinetask)
1080 (org-inlinetask-outline-regexp)))
1081 (beg-cell (cons (point) (org-get-indentation)))
1082 ind itm-lst itm-lst-2 end-lst end-lst-2 struct
1083 (assoc-at-point
1084 ;; Return an association whose key is point and values are
1085 ;; indentation, bullet string, bullet counter, and
1086 ;; checkbox.
1087 (function
1088 (lambda (ind)
1089 (looking-at org-list-full-item-re)
1090 (list (point)
1092 (match-string-no-properties 1) ; bullet
1093 (match-string-no-properties 2) ; counter
1094 (match-string-no-properties 3) ; checkbox
1095 (match-string-no-properties 4))))) ; description tag
1096 (end-before-blank
1097 ;; Ensure list ends at the first blank line.
1098 (function
1099 (lambda ()
1100 (skip-chars-backward " \r\t\n")
1101 (min (1+ (point-at-eol)) lim-down)))))
1102 ;; 1. Read list from starting item to its beginning, and save
1103 ;; top item position and indentation in BEG-CELL. Also store
1104 ;; ending position of items in END-LST.
1105 (save-excursion
1106 (catch 'exit
1107 (while t
1108 (let ((ind (+ (or (get-text-property (point) 'original-indentation) 0)
1109 (org-get-indentation))))
1110 (cond
1111 ((<= (point) lim-up)
1112 ;; At upward limit: if we ended at an item, store it,
1113 ;; else dimiss useless data recorded above BEG-CELL.
1114 ;; Jump to part 2.
1115 (throw 'exit
1116 (setq itm-lst
1117 (if (not (org-at-item-p))
1118 (memq (assq (car beg-cell) itm-lst) itm-lst)
1119 (setq beg-cell (cons (point) ind))
1120 (cons (funcall assoc-at-point ind) itm-lst)))))
1121 ((and (not (eq org-list-ending-method 'indent))
1122 (looking-at org-list-end-re))
1123 ;; Looking at a list ending regexp. Dismiss useless
1124 ;; data recorded above BEG-CELL. Jump to part 2.
1125 (throw 'exit
1126 (setq itm-lst
1127 (memq (assq (car beg-cell) itm-lst) itm-lst))))
1128 ;; Skip blocks, drawers, inline tasks, blank lines
1129 ;; along the way.
1130 ((looking-at "^[ \t]*#\\+end_")
1131 (re-search-backward "^[ \t]*#\\+begin_" nil t))
1132 ((looking-at "^[ \t]*:END:")
1133 (re-search-backward drawers-re nil t)
1134 (beginning-of-line))
1135 ((and inlinetask-re (looking-at inlinetask-re))
1136 (org-inlinetask-goto-beginning)
1137 (forward-line -1))
1138 ((looking-at "^[ \t]*$")
1139 (forward-line -1))
1140 ((org-at-item-p)
1141 ;; Point is at an item. Add data to ITM-LST. It may
1142 ;; also end a previous item: save it in END-LST. If
1143 ;; ind is less or equal than BEG-CELL and there is no
1144 ;; end at this ind or lesser, this item becomes the
1145 ;; new BEG-CELL.
1146 (push (funcall assoc-at-point ind) itm-lst)
1147 (push (cons ind (point-at-bol)) end-lst)
1148 (when (or (and (eq org-list-ending-method 'regexp)
1149 (<= ind (cdr beg-cell)))
1150 (< ind text-min-ind))
1151 (setq beg-cell (cons (point-at-bol) ind)))
1152 (forward-line -1))
1154 ;; Point is not at an item. Unless ending method is
1155 ;; `regexp', interpret line's indentation:
1157 ;; - text at column 0 is necessarily out of any list.
1158 ;; Dismiss data recorded above BEG-CELL. Jump to
1159 ;; part 2.
1161 ;; - any other case, it can possibly be an ending
1162 ;; position for an item above. Save it and proceed.
1163 (cond
1164 ((eq org-list-ending-method 'regexp))
1165 ((= ind 0)
1166 (throw 'exit
1167 (setq itm-lst
1168 (memq (assq (car beg-cell) itm-lst) itm-lst))))
1170 (when (< ind text-min-ind) (setq text-min-ind ind))
1171 (push (cons ind (point-at-bol)) end-lst)))
1172 (forward-line -1)))))))
1173 ;; 2. Read list from starting point to its end, that is until we
1174 ;; get out of context, or a non-item line is less or equally
1175 ;; indented that BEG-CELL's cdr. Also store ending position
1176 ;; of items in END-LST-2.
1177 (catch 'exit
1178 (while t
1179 (let ((ind (+ (or (get-text-property (point) 'original-indentation) 0)
1180 (org-get-indentation))))
1181 (cond
1182 ((>= (point) lim-down)
1183 ;; At downward limit: this is de facto the end of the
1184 ;; list. Save point as an ending position, and jump to
1185 ;; part 3.
1186 (throw 'exit
1187 (push (cons 0 (funcall end-before-blank)) end-lst-2)))
1188 ((and (not (eq org-list-ending-method 'indent))
1189 (looking-at org-list-end-re))
1190 ;; Looking at a list ending regexp. Save point as an
1191 ;; ending position and jump to part 3.
1192 (throw 'exit (push (cons 0 (point-at-bol)) end-lst-2)))
1193 ;; Skip blocks, drawers, inline tasks and blank lines
1194 ;; along the way
1195 ((looking-at "^[ \t]*#\\+begin_")
1196 (re-search-forward "^[ \t]*#\\+end_")
1197 (forward-line 1))
1198 ((looking-at drawers-re)
1199 (re-search-forward "^[ \t]*:END:" nil t)
1200 (forward-line 1))
1201 ((and inlinetask-re (looking-at inlinetask-re))
1202 (org-inlinetask-goto-end))
1203 ((looking-at "^[ \t]*$")
1204 (forward-line 1))
1205 ((org-at-item-p)
1206 ;; Point is at an item. Add data to ITM-LST-2. It may also
1207 ;; end a previous item, so save it in END-LST-2.
1208 (push (funcall assoc-at-point ind) itm-lst-2)
1209 (push (cons ind (point-at-bol)) end-lst-2)
1210 (forward-line 1))
1212 ;; Point is not at an item. If ending method is not
1213 ;; `regexp', two situations are of interest:
1215 ;; - ind is lesser or equal than BEG-CELL's. The list is
1216 ;; over. Store point as an ending position and jump to
1217 ;; part 3.
1219 ;; - ind is lesser or equal than previous item's. This
1220 ;; is an ending position. Store it and proceed.
1221 (cond
1222 ((eq org-list-ending-method 'regexp))
1223 ((<= ind (cdr beg-cell))
1224 (push (cons ind (funcall end-before-blank)) end-lst-2)
1225 (throw 'exit nil))
1226 ((<= ind (nth 1 (car itm-lst-2)))
1227 (push (cons ind (point-at-bol)) end-lst-2)))
1228 (forward-line 1))))))
1229 (setq struct (append itm-lst (cdr (nreverse itm-lst-2))))
1230 (setq end-lst (append end-lst (cdr (nreverse end-lst-2))))
1231 ;; 3. Correct ill-formed lists by making sure top item has the
1232 ;; least indentation of the list
1233 (let ((min-ind (nth 1 (car struct))))
1234 (mapc (lambda (item)
1235 (let ((ind (nth 1 item)))
1236 (when (< ind min-ind) (setcar (cdr item) min-ind))))
1237 struct))
1238 ;; 4. Associate each item to its end pos.
1239 (org-list-struct-assoc-end struct end-lst)
1240 ;; 5. Return STRUCT
1241 struct)))
1243 (defun org-list-struct-assoc-end (struct end-list)
1244 "Associate proper ending point to items in STRUCT.
1246 END-LIST is a pseudo-alist where car is indentation and cdr is
1247 ending position.
1249 This function modifies STRUCT."
1250 (let ((endings end-list))
1251 (mapc
1252 (lambda (elt)
1253 (let ((pos (car elt))
1254 (ind (nth 1 elt)))
1255 ;; Remove end candidates behind current item
1256 (while (or (<= (cdar endings) pos))
1257 (pop endings))
1258 ;; Add end position to item assoc
1259 (let ((old-end (nthcdr 6 elt))
1260 (new-end (assoc-default ind endings '<=)))
1261 (if old-end
1262 (setcar old-end new-end)
1263 (setcdr elt (append (cdr elt) (list new-end)))))))
1264 struct)))
1266 (defun org-list-struct-prev-alist (struct)
1267 "Return alist between item and previous item in STRUCT."
1268 (let ((item-end-alist (mapcar (lambda (e) (cons (car e) (nth 6 e)))
1269 struct)))
1270 (mapcar (lambda (e)
1271 (let ((prev (car (rassq (car e) item-end-alist))))
1272 (cons (car e) prev)))
1273 struct)))
1275 (defun org-list-struct-parent-alist (struct)
1276 "Return alist between item and parent in STRUCT."
1277 (let ((ind-to-ori (list (list (nth 1 (car struct)))))
1278 (prev-pos (list (caar struct))))
1279 (cons prev-pos
1280 (mapcar (lambda (item)
1281 (let ((pos (car item))
1282 (ind (nth 1 item))
1283 (prev-ind (caar ind-to-ori)))
1284 (push pos prev-pos)
1285 (cond
1286 ((> prev-ind ind)
1287 (setq ind-to-ori
1288 (member (assq ind ind-to-ori) ind-to-ori))
1289 (cons pos (cdar ind-to-ori)))
1290 ((< prev-ind ind)
1291 (let ((origin (nth 1 prev-pos)))
1292 (push (cons ind origin) ind-to-ori)
1293 (cons pos origin)))
1294 (t (cons pos (cdar ind-to-ori))))))
1295 (cdr struct)))))
1297 (defun org-list-get-parent (item struct parents)
1298 "Return parent of ITEM in STRUCT, or nil.
1299 PARENTS is the alist of items' parent. See
1300 `org-list-struct-parent-alist'."
1301 (let ((parents (or parents (org-list-struct-parent-alist struct))))
1302 (cdr (assq item parents))))
1304 (defun org-list-has-child-p (item struct)
1305 "Return a non-nil value if ITEM in STRUCT has a child.
1306 Value returned is the position of the first child of ITEM."
1307 (let ((ind (org-list-get-ind item struct))
1308 (child-maybe (car (nth 1 (member (assq item struct) struct)))))
1309 (when (and child-maybe
1310 (< ind (org-list-get-ind child-maybe struct)))
1311 child-maybe)))
1313 (defun org-list-get-next-item (item struct prevs)
1314 "Return next item in same sub-list as ITEM in STRUCT, or nil.
1315 PREVS is the alist of previous items. See
1316 `org-list-struct-prev-alist'."
1317 (car (rassq item prevs)))
1319 (defun org-list-get-prev-item (item struct prevs)
1320 "Return previous item in same sub-list as ITEM in STRUCT, or nil.
1321 PREVS is the alist of previous items. See
1322 `org-list-struct-prev-alist'."
1323 (cdr (assq item prevs)))
1325 (defun org-list-get-subtree (item struct)
1326 "Return all items with ITEM as a common ancestor or nil.
1327 STRUCT is the list structure considered."
1328 (let* ((item-end (org-list-get-item-end item struct))
1329 (sub-struct (cdr (member (assq item struct) struct)))
1330 subtree)
1331 (catch 'exit
1332 (mapc (lambda (e)
1333 (let ((pos (car e)))
1334 (if (< pos item-end) (push pos subtree) (throw 'exit nil))))
1335 sub-struct))
1336 (nreverse subtree)))
1338 (defun org-list-get-all-items (item struct prevs)
1339 "List of items in the same sub-list as ITEM in STRUCT.
1340 PREVS is the alist of previous items. See
1341 `org-list-struct-prev-alist'."
1342 (let ((prev-item item)
1343 (next-item item)
1344 before-item after-item)
1345 (while (setq prev-item (org-list-get-prev-item prev-item struct prevs))
1346 (push prev-item before-item))
1347 (while (setq next-item (org-list-get-next-item next-item struct prevs))
1348 (push next-item after-item))
1349 (append before-item (list item) (nreverse after-item))))
1351 (defun org-list-get-children (item struct parents)
1352 "List all children of ITEM in STRUCT, or nil.
1353 PARENTS is the alist of items' parent. See
1354 `org-list-struct-parent-alist'."
1355 (let (all)
1356 (while (setq child (car (rassq item parents)))
1357 (setq parents (cdr (member (assq child parents) parents)))
1358 (push child all))
1359 (nreverse all)))
1361 (defun org-list-get-top-point (struct)
1362 "Return point at beginning of list.
1363 STRUCT is the structure of the list."
1364 (caar struct))
1366 (defun org-list-get-bottom-point (struct)
1367 "Return point at bottom of list.
1368 STRUCT is the structure of the list."
1369 (apply 'max
1370 (mapcar (lambda (e) (org-list-get-item-end (car e) struct)) struct)))
1372 (defun org-list-get-list-begin (item struct prevs)
1373 "Return point at beginning of sub-list ITEM belongs.
1374 STRUCT is the structure of the list. PREVS is the alist of
1375 previous items. See `org-list-struct-prev-alist'."
1376 (let ((first-item item) prev-item)
1377 (while (setq prev-item (org-list-get-prev-item first-item struct prevs))
1378 (setq first-item prev-item))
1379 first-item))
1381 (defalias 'org-list-get-first-item 'org-list-get-list-begin)
1383 (defun org-list-get-last-item (item struct prevs)
1384 "Return point at last item of sub-list ITEM belongs.
1385 STRUCT is the structure of the list. PREVS is the alist of
1386 previous items. See `org-list-struct-prev-alist'."
1387 (let ((last-item item) next-item)
1388 (while (setq next-item (org-list-get-next-item last-item struct prevs))
1389 (setq last-item next-item))
1390 last-item))
1392 (defun org-list-get-list-end (item struct prevs)
1393 "Return point at end of sub-list ITEM belongs.
1394 STRUCT is the structure of the list. PREVS is the alist of
1395 previous items. See `org-list-struct-prev-alist'."
1396 (org-list-get-item-end (org-list-get-last-item item struct prevs) struct))
1398 (defun org-list-get-list-type (item struct prevs)
1399 "Return the type of the list containing ITEM as a symbol.
1401 STRUCT is the structure of the list, as returned by
1402 `org-list-struct'. PREVS is the alist of previous items. See
1403 `org-list-struct-prev-alist'.
1405 Possible types are `descriptive', `ordered' and `unordered'. The
1406 type is determined by the first item of the list."
1407 (let ((first (org-list-get-list-begin item struct prevs)))
1408 (cond
1409 ((org-list-get-tag first struct) 'descriptive)
1410 ((string-match "[[:alnum:]]" (org-list-get-bullet first struct)) 'ordered)
1411 (t 'unordered))))
1413 (defun org-list-get-nth (n key struct)
1414 "Return the Nth value of KEY in STRUCT."
1415 (nth n (assq key struct)))
1417 (defun org-list-set-nth (n key struct new)
1418 "Set the Nth value of KEY in STRUCT to NEW.
1419 \nThis function modifies STRUCT."
1420 (setcar (nthcdr n (assq key struct)) new))
1422 (defun org-list-get-ind (item struct)
1423 "Return indentation of ITEM in STRUCT."
1424 (org-list-get-nth 1 item struct))
1426 (defun org-list-set-ind (item struct ind)
1427 "Set indentation of ITEM in STRUCT to IND.
1428 \nThis function modifies STRUCT."
1429 (org-list-set-nth 1 item struct ind))
1431 (defun org-list-get-bullet (item struct)
1432 "Return bullet of ITEM in STRUCT."
1433 (org-list-get-nth 2 item struct))
1435 (defun org-list-set-bullet (item struct bullet)
1436 "Set bullet of ITEM in STRUCT to BULLET.
1437 \nThis function modifies STRUCT."
1438 (org-list-set-nth 2 item struct bullet))
1440 (defun org-list-get-counter (item struct)
1441 "Return counter of ITEM in STRUCT."
1442 (org-list-get-nth 3 item struct))
1444 (defun org-list-get-checkbox (item struct)
1445 "Return checkbox of ITEM in STRUCT or nil."
1446 (org-list-get-nth 4 item struct))
1448 (defun org-list-set-checkbox (item struct checkbox)
1449 "Set checkbox of ITEM in STRUCT to CHECKBOX.
1450 \nThis function modifies STRUCT."
1451 (org-list-set-nth 4 item struct checkbox))
1453 (defun org-list-get-tag (item struct)
1454 "Return end position of ITEM in STRUCT."
1455 (org-list-get-nth 5 item struct))
1457 (defun org-list-get-item-end (item struct)
1458 "Return end position of ITEM in STRUCT."
1459 (org-list-get-nth 6 item struct))
1461 (defun org-list-get-item-end-before-blank (item struct)
1462 "Return point at end of ITEM in STRUCT, before any blank line.
1463 Point returned is at end of line."
1464 (save-excursion
1465 (goto-char (org-list-get-item-end item struct))
1466 (skip-chars-backward " \r\t\n")
1467 (point-at-eol)))
1469 (defun org-list-struct-fix-bul (struct prevs)
1470 "Verify and correct bullets for every association in STRUCT.
1471 PREVS is the alist of previous items. See
1472 `org-list-struct-prev-alist'.
1474 This function modifies STRUCT."
1475 (let ((case-fold-search nil)
1476 (fix-bul
1477 (function
1478 ;; Set bullet of ITEM in STRUCT, depending on the type of
1479 ;; first item of the list, the previous bullet and counter
1480 ;; if any.
1481 (lambda (item)
1482 (let* ((prev (org-list-get-prev-item item struct prevs))
1483 (prev-bul (and prev (org-list-get-bullet prev struct)))
1484 (counter (org-list-get-counter item struct))
1485 (bullet (org-list-get-bullet item struct))
1486 (alphap (and (not prev)
1487 (org-list-use-alpha-bul-p item struct prevs))))
1488 (org-list-set-bullet
1489 item struct
1490 (org-list-bullet-string
1491 (cond
1492 ;; Alpha counter in alpha list: use counter.
1493 ((and prev counter
1494 (string-match "[a-zA-Z]" counter)
1495 (string-match "[a-zA-Z]" prev-bul))
1496 ;; Use cond to be sure `string-match' is used in
1497 ;; both cases.
1498 (let ((real-count
1499 (cond
1500 ((string-match "[a-z]" prev-bul) (downcase counter))
1501 ((string-match "[A-Z]" prev-bul) (upcase counter)))))
1502 (replace-match real-count nil nil prev-bul)))
1503 ;; Num counter in a num list: use counter.
1504 ((and prev counter
1505 (string-match "[0-9]+" counter)
1506 (string-match "[0-9]+" prev-bul))
1507 (replace-match counter nil nil prev-bul))
1508 ;; No counter: increase, if needed, previous bullet.
1509 (prev
1510 (org-list-inc-bullet-maybe (org-list-get-bullet prev struct)))
1511 ;; Alpha counter at first item: use counter.
1512 ((and counter (org-list-use-alpha-bul-p item struct prevs)
1513 (string-match "[A-Za-z]" counter)
1514 (string-match "[A-Za-z]" bullet))
1515 (let ((real-count
1516 (cond
1517 ((string-match "[a-z]" bullet) (downcase counter))
1518 ((string-match "[A-Z]" bullet) (upcase counter)))))
1519 (replace-match real-count nil nil bullet)))
1520 ;; Num counter at first item: use counter.
1521 ((and counter
1522 (string-match "[0-9]+" counter)
1523 (string-match "[0-9]+" bullet))
1524 (replace-match counter nil nil bullet))
1525 ;; First bullet is alpha uppercase: use "A".
1526 ((and alphap (string-match "[A-Z]" bullet))
1527 (replace-match "A" nil nil bullet))
1528 ;; First bullet is alpha lowercase: use "a".
1529 ((and alphap (string-match "[a-z]" bullet))
1530 (replace-match "a" nil nil bullet))
1531 ;; First bullet is num: use "1".
1532 ((string-match "\\([0-9]+\\|[A-Za-z]\\)" bullet)
1533 (replace-match "1" nil nil bullet))
1534 ;; Not an ordered list: keep bullet.
1535 (t bullet)))))))))
1536 (mapc fix-bul (mapcar 'car struct))))
1538 (defun org-list-struct-fix-ind (struct parents &optional bullet-size)
1539 "Verify and correct indentation for every association in STRUCT.
1541 PARENTS is the alist of items' parents. See
1542 `org-list-struct-parent-alist'.
1544 If numeric optional argument BULLET-SIZE is set, assume all
1545 bullets in list have this length to determine new indentation.
1547 This function modifies STRUCT."
1548 (let* ((ancestor (org-list-get-top-point struct))
1549 (top-ind (org-list-get-ind ancestor struct))
1550 (new-ind
1551 (lambda (item)
1552 (let ((parent (org-list-get-parent item struct parents)))
1553 (if parent
1554 ;; Indent like parent + length of parent's bullet
1555 (org-list-set-ind
1556 item struct (+ (or bullet-size
1557 (length
1558 (org-list-get-bullet parent struct)))
1559 (org-list-get-ind parent struct)))
1560 ;; If no parent, indent like top-point
1561 (org-list-set-ind item struct top-ind))))))
1562 (mapc new-ind (mapcar 'car (cdr struct)))))
1564 (defun org-list-struct-fix-box (struct parents prevs &optional ordered)
1565 "Verify and correct checkboxes for every association in STRUCT.
1567 PARENTS is the alist of items' parents. See
1568 `org-list-struct-parent-alist'. PREVS is the alist of previous
1569 items. See `org-list-struct-prev-alist.
1571 If ORDERED is non-nil, a checkbox can only be checked when every
1572 checkbox before it is checked too. If there was an attempt to
1573 break this rule, the function will return the blocking item. In
1574 all others cases, the return value will be nil.
1576 This function modifies STRUCT."
1577 (let ((all-items (mapcar 'car struct))
1578 (set-parent-box
1579 (function
1580 (lambda (item)
1581 (let* ((box-list
1582 (mapcar (lambda (child)
1583 (org-list-get-checkbox child struct))
1584 (org-list-get-children item struct parents))))
1585 (org-list-set-checkbox
1586 item struct
1587 (cond
1588 ((and (member "[ ]" box-list) (member "[X]" box-list)) "[-]")
1589 ((member "[-]" box-list) "[-]")
1590 ((member "[X]" box-list) "[X]")
1591 ((member "[ ]" box-list) "[ ]")
1592 ;; parent has no boxed child: leave box as-is
1593 (t (org-list-get-checkbox item struct))))))))
1594 parent-list)
1595 ;; 1. List all parents with a checkbox
1596 (mapc
1597 (lambda (e)
1598 (let* ((parent (org-list-get-parent e struct parents))
1599 (parent-box-p (org-list-get-checkbox parent struct)))
1600 (when (and parent-box-p (not (memq parent parent-list)))
1601 (push parent parent-list))))
1602 all-items)
1603 ;; 2. Sort those parents by decreasing indentation
1604 (setq parent-list (sort parent-list
1605 (lambda (e1 e2)
1606 (> (org-list-get-ind e1 struct)
1607 (org-list-get-ind e2 struct)))))
1608 ;; 3. For each parent, get all children's checkboxes to determine
1609 ;; and set its checkbox accordingly
1610 (mapc set-parent-box parent-list)
1611 ;; 4. If ORDERED is set, see if we need to uncheck some boxes
1612 (when ordered
1613 (let* ((box-list
1614 (mapcar (lambda (e) (org-list-get-checkbox e struct)) all-items))
1615 (after-unchecked (member "[ ]" box-list)))
1616 ;; there are boxes checked after an unchecked one: fix that
1617 (when (member "[X]" after-unchecked)
1618 (let ((index (- (length struct) (length after-unchecked))))
1619 (mapc (lambda (e) (org-list-set-checkbox e struct "[ ]"))
1620 (nthcdr index all-items))
1621 ;; Verify once again the structure, without ORDERED
1622 (org-list-struct-fix-box struct parents prevs nil)
1623 ;; return blocking item
1624 (nth index all-items)))))))
1626 (defun org-list-struct-fix-struct (struct parents)
1627 "Return STRUCT with correct bullets and indentation.
1628 PARENTS is the alist of items' parents. See
1629 `org-list-struct-parent-alist'."
1630 ;; Order of functions matters here: checkboxes and endings need
1631 ;; correct indentation to be set, and indentation needs correct
1632 ;; bullets.
1634 ;; 0. Save a copy of structure before modifications
1635 (let ((old-struct (mapcar (lambda (e) (copy-alist e)) struct)))
1636 ;; 1. Set a temporary, but coherent with PARENTS, indentation in
1637 ;; order to get items endings and bullets properly
1638 (org-list-struct-fix-ind struct parents 2)
1639 ;; 2. Get pseudo-alist of ending positions and sort it by position.
1640 ;; Then associate them to the structure.
1641 (let (end-list acc-end)
1642 (mapc (lambda (e)
1643 (let* ((pos (car e))
1644 (ind-pos (org-list-get-ind pos struct))
1645 (end-pos (org-list-get-item-end pos struct)))
1646 (unless (assq end-pos struct)
1647 ;; to determine real ind of an ending position that is
1648 ;; not at an item, we have to find the item it belongs
1649 ;; to: it is the last item (ITEM-UP), whose ending is
1650 ;; further than the position we're interested in.
1651 (let ((item-up (assoc-default end-pos acc-end '>)))
1652 (push (cons
1653 ;; else part is for the bottom point
1654 (if item-up (+ (org-list-get-ind item-up struct) 2) 0)
1655 end-pos)
1656 end-list)))
1657 (push (cons ind-pos pos) end-list)
1658 (push (cons end-pos pos) acc-end)))
1659 struct)
1660 (setq end-list (sort end-list (lambda (e1 e2) (< (cdr e1) (cdr e2)))))
1661 (org-list-struct-assoc-end struct end-list))
1662 ;; 3. Get bullets right
1663 (let ((prevs (org-list-struct-prev-alist struct)))
1664 (org-list-struct-fix-bul struct prevs)
1665 ;; 4. Now get real indentation
1666 (org-list-struct-fix-ind struct parents)
1667 ;; 5. Eventually fix checkboxes
1668 (org-list-struct-fix-box struct parents prevs))
1669 ;; 6. Apply structure modifications to buffer
1670 (org-list-struct-apply-struct struct old-struct)))
1672 (defun org-list-struct-outdent (start end struct parents)
1673 "Outdent items between START and END in structure STRUCT.
1675 PARENTS is the alist of items' parents. See
1676 `org-list-struct-parent-alist'.
1678 START is included, END excluded."
1679 (let* (acc
1680 (out (lambda (cell)
1681 (let* ((item (car cell))
1682 (parent (cdr cell)))
1683 (cond
1684 ;; Item not yet in zone: keep association
1685 ((< item start) cell)
1686 ;; Item out of zone: follow associations in acc
1687 ((>= item end)
1688 (let ((convert (and parent (assq parent acc))))
1689 (if convert (cons item (cdr convert)) cell)))
1690 ;; Item has no parent: error
1691 ((not parent)
1692 (error "Cannot outdent top-level items"))
1693 ;; Parent is outdented: keep association
1694 ((>= parent start)
1695 (push (cons parent item) acc) cell)
1697 ;; Parent isn't outdented: reparent to grand-parent
1698 (let ((grand-parent (org-list-get-parent
1699 parent struct parents)))
1700 (push (cons parent item) acc)
1701 (cons item grand-parent))))))))
1702 (mapcar out parents)))
1704 (defun org-list-struct-indent (start end struct parents prevs)
1705 "Indent items between START and END in structure STRUCT.
1707 PARENTS is the alist of parents. See
1708 `org-list-struct-parent-alist'. PREVS is the alist of previous
1709 items. See `org-list-struct-prev-alist'.
1711 START is included and END excluded.
1713 STRUCT may be modified if `org-list-demote-modify-bullet' matches
1714 bullets between START and END."
1715 (let* (acc
1716 (set-assoc (lambda (cell) (push cell acc) cell))
1717 (change-bullet-maybe
1718 (function
1719 (lambda (item)
1720 (let* ((bul (org-trim (org-list-get-bullet item struct)))
1721 (new-bul-p (cdr (assoc bul org-list-demote-modify-bullet))))
1722 (when new-bul-p (org-list-set-bullet item struct new-bul-p))))))
1723 (ind
1724 (lambda (cell)
1725 (let* ((item (car cell))
1726 (parent (cdr cell)))
1727 (cond
1728 ;; Item not yet in zone: keep association
1729 ((< item start) cell)
1730 ((>= item end)
1731 ;; Item out of zone: follow associations in acc
1732 (let ((convert (assq parent acc)))
1733 (if convert (cons item (cdr convert)) cell)))
1735 ;; Item is in zone...
1736 (let ((prev (org-list-get-prev-item item struct prevs)))
1737 ;; Check if bullet needs to be changed
1738 (funcall change-bullet-maybe item)
1739 (cond
1740 ;; First item indented but not parent: error
1741 ((and (not prev) (< parent start))
1742 (error "Cannot indent the first item of a list"))
1743 ;; First item and parent indented: keep same parent
1744 ((not prev) (funcall set-assoc cell))
1745 ;; Previous item not indented: reparent to it
1746 ((< prev start) (funcall set-assoc (cons item prev)))
1747 ;; Previous item indented: reparent like it
1749 (funcall set-assoc
1750 (cons item (cdr (assq prev acc)))))))))))))
1751 (mapcar ind parents)))
1753 (defun org-list-struct-apply-struct (struct old-struct)
1754 "Apply modifications to list so it mirrors STRUCT.
1756 OLD-STRUCT is the structure before any modifications. Thus, the
1757 function is smart enough to modify only parts of buffer which
1758 have changed.
1760 Initial position of cursor is restored after the changes."
1761 (let* ((pos (copy-marker (point)))
1762 (shift-body-ind
1763 (function
1764 ;; Shift the indentation between END and BEG by DELTA.
1765 ;; Start from the line before END.
1766 (lambda (end beg delta)
1767 (unless (= delta 0)
1768 (goto-char end)
1769 (forward-line -1)
1770 (while (or (> (point) beg)
1771 (and (= (point) beg) (not (org-at-item-p))))
1772 (when (org-looking-at-p "^[ \t]*\\S-")
1773 (let ((i (org-get-indentation)))
1774 (org-indent-line-to (+ i delta))))
1775 (forward-line -1))))))
1776 (modify-item
1777 (function
1778 ;; Replace item first line elements with new elements from
1779 ;; STRUCT, if appropriate.
1780 (lambda (item)
1781 (goto-char item)
1782 (let* ((new-ind (org-list-get-ind item struct))
1783 (old-ind (org-list-get-ind item old-struct))
1784 (new-bul (org-list-bullet-string
1785 (org-list-get-bullet item struct)))
1786 (old-bul (org-list-get-bullet item old-struct))
1787 (new-box (org-list-get-checkbox item struct)))
1788 (looking-at org-list-full-item-re)
1789 ;; a. Replace bullet
1790 (unless (equal old-bul new-bul)
1791 (replace-match new-bul nil nil nil 1))
1792 ;; b. Replace checkbox
1793 (cond
1794 ((and new-box
1795 (save-match-data (org-at-item-description-p))
1796 (cdr (assq 'checkbox org-list-automatic-rules)))
1797 (message "Cannot add a checkbox to a description list item"))
1798 ((equal (match-string 3) new-box))
1799 ((and (match-string 3) new-box)
1800 (replace-match new-box nil nil nil 3))
1801 ((match-string 3)
1802 (goto-char (or (match-end 2) (match-end 1)))
1803 (looking-at "\\[[ X-]\\][ \t]+")
1804 (replace-match ""))
1805 (t (goto-char (or (match-end 2) (match-end 1)))
1806 (insert (concat new-box " "))))
1807 ;; c. Indent item to appropriate column
1808 (unless (= new-ind old-ind)
1809 (delete-region (goto-char (point-at-bol))
1810 (progn (skip-chars-forward " \t") (point)))
1811 (indent-to new-ind)))))))
1812 ;; 1. First get list of items and position endings. We maintain
1813 ;; two alists: ITM-SHIFT, determining indentation shift needed
1814 ;; at item, and END-POS, a pseudo-alist where key is ending
1815 ;; position and value point
1816 (let (end-list acc-end itm-shift all-ends sliced-struct)
1817 (mapc (lambda (e)
1818 (let* ((pos (car e))
1819 (ind-pos (org-list-get-ind pos struct))
1820 (ind-old (org-list-get-ind pos old-struct))
1821 (bul-pos (org-list-get-bullet pos struct))
1822 (bul-old (org-list-get-bullet pos old-struct))
1823 (ind-shift (- (+ ind-pos (length bul-pos))
1824 (+ ind-old (length bul-old))))
1825 (end-pos (org-list-get-item-end pos old-struct)))
1826 (push (cons pos ind-shift) itm-shift)
1827 (unless (assq end-pos old-struct)
1828 ;; To determine real ind of an ending position that is
1829 ;; not at an item, we have to find the item it belongs
1830 ;; to: it is the last item (ITEM-UP), whose ending is
1831 ;; further than the position we're interested in.
1832 (let ((item-up (assoc-default end-pos acc-end '>)))
1833 (push (cons end-pos item-up) end-list)))
1834 (push (cons end-pos pos) acc-end)))
1835 old-struct)
1836 ;; 2. Slice the items into parts that should be shifted by the
1837 ;; same amount of indentation. The slices are returned in
1838 ;; reverse order so changes modifying buffer do not change
1839 ;; positions they refer to.
1840 (setq all-ends (sort (append (mapcar 'car itm-shift)
1841 (org-uniquify (mapcar 'car end-list)))
1842 '<))
1843 (while (cdr all-ends)
1844 (let* ((up (pop all-ends))
1845 (down (car all-ends))
1846 (ind (if (assq up struct)
1847 (cdr (assq up itm-shift))
1848 (cdr (assq (cdr (assq up end-list)) itm-shift)))))
1849 (push (list down up ind) sliced-struct)))
1850 ;; 3. Modify each slice in buffer, from end to beginning, with a
1851 ;; special action when beginning is at item start.
1852 (mapc (lambda (e)
1853 (apply shift-body-ind e)
1854 (let ((beg (nth 1 e)))
1855 (when (assq beg struct)
1856 (funcall modify-item beg))))
1857 sliced-struct))
1858 ;; 4. Go back to initial position
1859 (goto-char pos)))
1861 ;;; Indentation
1863 (defun org-outdent-item ()
1864 "Outdent a local list item, but not its children.
1865 If a region is active, all items inside will be moved."
1866 (interactive)
1867 (if (org-at-item-p)
1868 (let ((struct (org-list-struct)))
1869 (org-list-indent-item-generic -1 t struct))
1870 (error "Not at an item")))
1872 (defun org-indent-item ()
1873 "Indent a local list item, but not its children.
1874 If a region is active, all items inside will be moved."
1875 (interactive)
1876 (if (org-at-item-p)
1877 (let ((struct (org-list-struct)))
1878 (org-list-indent-item-generic 1 t struct))
1879 (error "Not at an item")))
1881 (defun org-outdent-item-tree ()
1882 "Outdent a local list item including its children.
1883 If a region is active, all items inside will be moved."
1884 (interactive)
1885 (let ((regionp (org-region-active-p)))
1886 (cond
1887 ((or (org-at-item-p)
1888 (and (org-region-active-p)
1889 (goto-char (region-beginning))
1890 (org-at-item-p)))
1891 (let ((struct (org-list-struct)))
1892 (org-list-indent-item-generic -1 nil struct)))
1893 (regionp (error "Region not starting at an item"))
1894 (t (error "Not at an item")))))
1896 (defun org-indent-item-tree ()
1897 "Indent a local list item including its children.
1898 If a region is active, all items inside will be moved."
1899 (interactive)
1900 (let ((regionp (org-region-active-p)))
1901 (cond
1902 ((or (org-at-item-p)
1903 (and (org-region-active-p)
1904 (goto-char (region-beginning))
1905 (org-at-item-p)))
1906 (let ((struct (org-list-struct)))
1907 (org-list-indent-item-generic 1 nil struct)))
1908 (regionp (error "Region not starting at an item"))
1909 (t (error "Not at an item")))))
1911 (defvar org-tab-ind-state)
1912 (defun org-cycle-item-indentation ()
1913 "Cycle levels of indentation of an empty item.
1914 The first run indents the item, if applicable. Subsequents runs
1915 outdent it at meaningful levels in the list. When done, item is
1916 put back at its original position with its original bullet.
1918 Return t at each successful move."
1919 (when (org-at-item-p)
1920 (let* ((org-adapt-indentation nil)
1921 (struct (org-list-struct))
1922 (ind (org-list-get-ind (point-at-bol) struct)))
1923 ;; Check that item is really empty
1924 (when (and (save-excursion
1925 (beginning-of-line)
1926 (looking-at org-list-full-item-re))
1927 (>= (match-end 0) (save-excursion
1928 (goto-char (org-list-get-item-end
1929 (point-at-bol) struct))
1930 (skip-chars-backward " \r\t\n")
1931 (point))))
1932 (setq this-command 'org-cycle-item-indentation)
1933 ;; When in the middle of the cycle, try to outdent first. If it
1934 ;; fails, and point is still at initial position, indent. Else,
1935 ;; go back to original position.
1936 (if (eq last-command 'org-cycle-item-indentation)
1937 (cond
1938 ((ignore-errors (org-list-indent-item-generic -1 t struct)))
1939 ((and (= ind (car org-tab-ind-state))
1940 (ignore-errors (org-list-indent-item-generic 1 t struct))))
1941 (t (back-to-indentation)
1942 (org-indent-to-column (car org-tab-ind-state))
1943 (looking-at "\\S-+")
1944 (replace-match (cdr org-tab-ind-state))
1945 (end-of-line)
1946 ;; Break cycle
1947 (setq this-command 'identity)))
1948 ;; If a cycle is starting, remember indentation and bullet,
1949 ;; then try to indent. If it fails, try to outdent.
1950 (setq org-tab-ind-state (cons ind (org-get-bullet)))
1951 (cond
1952 ((ignore-errors (org-list-indent-item-generic 1 t struct)))
1953 ((ignore-errors (org-list-indent-item-generic -1 t struct)))
1954 (t (error "Cannot move item"))))
1955 t))))
1957 ;;; Bullets
1959 (defun org-get-bullet ()
1960 "Return the bullet of the item at point.
1961 Assume cursor is at an item."
1962 (save-excursion
1963 (beginning-of-line)
1964 (and (looking-at "[ \t]*\\(\\S-+\\)") (match-string 1))))
1966 (defun org-list-bullet-string (bullet)
1967 "Return BULLET with the correct number of whitespaces.
1968 It determines the number of whitespaces to append by looking at
1969 `org-list-two-spaces-after-bullet-regexp'."
1970 (save-match-data
1971 (string-match "\\S-+\\([ \t]*\\)" bullet)
1972 (replace-match
1973 (save-match-data
1974 (concat
1976 ;; Do we need to concat another white space ?
1977 (when (and org-list-two-spaces-after-bullet-regexp
1978 (string-match org-list-two-spaces-after-bullet-regexp bullet))
1979 " ")))
1980 nil nil bullet 1)))
1982 (defun org-list-use-alpha-bul-p (first struct prevs)
1983 "Can list starting at FIRST use alphabetical bullets?
1985 STRUCT is list structure. See `org-list-struct'. PREVS is the
1986 alist of previous items. See `org-list-struct-prev-alist'."
1987 (and org-alphabetical-lists
1988 (catch 'exit
1989 (let ((item first) (ascii 64) (case-fold-search nil))
1990 ;; Pretend that bullets are uppercase and checked if
1991 ;; alphabet is sufficient, taking counters into account.
1992 (while item
1993 (let ((bul (org-list-get-bullet item struct))
1994 (count (org-list-get-counter item struct)))
1995 ;; Virtually determine current bullet
1996 (if (and count (string-match "[a-zA-Z]" count))
1997 ;; Counters are not case-sensitive.
1998 (setq ascii (string-to-char (upcase count)))
1999 (setq ascii (1+ ascii)))
2000 ;; Test if bullet would be over z or Z.
2001 (if (> ascii 90)
2002 (throw 'exit nil)
2003 (setq item (org-list-get-next-item item struct prevs)))))
2004 ;; All items checked. All good.
2005 t))))
2007 (defun org-list-inc-bullet-maybe (bullet)
2008 "Increment BULLET if applicable."
2009 (let ((case-fold-search nil))
2010 (cond
2011 ;; Num bullet: increment it.
2012 ((string-match "[0-9]+" bullet)
2013 (replace-match
2014 (number-to-string (1+ (string-to-number (match-string 0 bullet))))
2015 nil nil bullet))
2016 ;; Alpha bullet: increment it.
2017 ((string-match "[A-Za-z]" bullet)
2018 (replace-match
2019 (char-to-string (1+ (string-to-char (match-string 0 bullet))))
2020 nil nil bullet))
2021 ;; Unordered bullet: leave it.
2022 (t bullet))))
2024 (defun org-list-repair ()
2025 "Make sure all items are correctly indented, with the right bullet.
2026 This function scans the list at point, along with any sublist."
2027 (interactive)
2028 (unless (org-at-item-p) (error "This is not a list"))
2029 (let* ((struct (org-list-struct))
2030 (parents (org-list-struct-parent-alist struct)))
2031 (org-list-struct-fix-struct struct parents)))
2033 (defun org-cycle-list-bullet (&optional which)
2034 "Cycle through the different itemize/enumerate bullets.
2035 This cycle the entire list level through the sequence:
2037 `-' -> `+' -> `*' -> `1.' -> `1)'
2039 If WHICH is a valid string, use that as the new bullet. If WHICH
2040 is an integer, 0 means `-', 1 means `+' etc. If WHICH is
2041 `previous', cycle backwards."
2042 (interactive "P")
2043 (unless (org-at-item-p) (error "This is not a list"))
2044 (save-excursion
2045 (beginning-of-line)
2046 (let* ((struct (org-list-struct))
2047 (parents (org-list-struct-parent-alist struct))
2048 (prevs (org-list-struct-prev-alist struct))
2049 (list-beg (org-list-get-first-item (point) struct prevs))
2050 (bullet (org-list-get-bullet list-beg struct))
2051 (bullet-rule-p (cdr (assq 'bullet org-list-automatic-rules)))
2052 (alpha-p (org-list-use-alpha-bul-p list-beg struct prevs))
2053 (case-fold-search nil)
2054 (current (cond
2055 ((string-match "[a-z]\\." bullet) "a.")
2056 ((string-match "[a-z])" bullet) "a)")
2057 ((string-match "[A-Z]\\." bullet) "A.")
2058 ((string-match "[A-Z])" bullet) "A)")
2059 ((string-match "\\." bullet) "1.")
2060 ((string-match ")" bullet) "1)")
2061 (t (org-trim bullet))))
2062 ;; Compute list of possible bullets, depending on context
2063 (bullet-list
2064 (append '("-" "+" )
2065 ;; *-bullets are not allowed at column 0
2066 (unless (and bullet-rule-p
2067 (looking-at "\\S-")) '("*"))
2068 ;; Description items cannot be numbered
2069 (unless (or (eq org-plain-list-ordered-item-terminator ?\))
2070 (and bullet-rule-p (org-at-item-description-p)))
2071 '("1."))
2072 (unless (or (eq org-plain-list-ordered-item-terminator ?.)
2073 (and bullet-rule-p (org-at-item-description-p)))
2074 '("1)"))
2075 (unless (or (not alpha-p)
2076 (eq org-plain-list-ordered-item-terminator ?\))
2077 (and bullet-rule-p (org-at-item-description-p)))
2078 '("a." "A."))
2079 (unless (or (not alpha-p)
2080 (eq org-plain-list-ordered-item-terminator ?.)
2081 (and bullet-rule-p (org-at-item-description-p)))
2082 '("a)" "A)"))))
2083 (len (length bullet-list))
2084 (item-index (- len (length (member current bullet-list))))
2085 (get-value (lambda (index) (nth (mod index len) bullet-list)))
2086 (new (cond
2087 ((member which bullet-list) which)
2088 ((numberp which) (funcall get-value which))
2089 ((eq 'previous which) (funcall get-value (1- item-index)))
2090 (t (funcall get-value (1+ item-index))))))
2091 ;; Use a short variation of `org-list-struct-fix-struct' as
2092 ;; there's no need to go through all the steps.
2093 (let ((old-struct (mapcar (lambda (e) (copy-alist e)) struct)))
2094 (org-list-set-bullet list-beg struct (org-list-bullet-string new))
2095 (org-list-struct-fix-bul struct prevs)
2096 (org-list-struct-fix-ind struct parents)
2097 (org-list-struct-apply-struct struct old-struct)))))
2099 ;;; Checkboxes
2101 (defun org-toggle-checkbox (&optional toggle-presence)
2102 "Toggle the checkbox in the current line.
2103 With prefix arg TOGGLE-PRESENCE, add or remove checkboxes. With
2104 double prefix, set checkbox to [-].
2106 When there is an active region, toggle status or presence of the
2107 first checkbox there, and make every item inside have the
2108 same status or presence, respectively.
2110 If the cursor is in a headline, apply this to all checkbox items
2111 in the text below the heading, taking as reference the first item
2112 in subtree, ignoring drawers."
2113 (interactive "P")
2114 (save-excursion
2115 (let* (singlep
2116 block-item
2117 lim-up
2118 lim-down
2119 (orderedp (ignore-errors (org-entry-get nil "ORDERED")))
2120 (bounds
2121 ;; In a region, start at first item in region
2122 (cond
2123 ((org-region-active-p)
2124 (let ((limit (region-end)))
2125 (goto-char (region-beginning))
2126 (if (org-list-search-forward (org-item-beginning-re) limit t)
2127 (setq lim-up (point-at-bol))
2128 (error "No item in region"))
2129 (setq lim-down (copy-marker limit))))
2130 ((org-on-heading-p)
2131 ;; On an heading, start at first item after drawers
2132 (let ((limit (save-excursion (outline-next-heading) (point))))
2133 (forward-line 1)
2134 (when (looking-at org-drawer-regexp)
2135 (re-search-forward "^[ \t]*:END:" limit nil))
2136 (if (org-list-search-forward (org-item-beginning-re) limit t)
2137 (setq lim-up (point-at-bol))
2138 (error "No item in subtree"))
2139 (setq lim-down (copy-marker limit))))
2140 ;; Just one item: set singlep flag
2141 ((org-at-item-p)
2142 (setq singlep t)
2143 (setq lim-up (point-at-bol)
2144 lim-down (point-at-eol)))
2145 (t (error "Not at an item or heading, and no active region"))))
2146 ;; Determine the checkbox going to be applied to all items
2147 ;; within bounds
2148 (ref-checkbox
2149 (progn
2150 (goto-char lim-up)
2151 (let ((cbox (and (org-at-item-checkbox-p) (match-string 1))))
2152 (cond
2153 ((equal toggle-presence '(16)) "[-]")
2154 ((equal toggle-presence '(4))
2155 (unless cbox "[ ]"))
2156 ((equal "[ ]" cbox) "[X]")
2157 (t "[ ]"))))))
2158 ;; When an item is found within bounds, grab the full list at
2159 ;; point structure, then: 1. set checkbox of all its items
2160 ;; within bounds to ref-checkbox; 2. fix checkboxes of the whole
2161 ;; list; 3. move point after the list.
2162 (goto-char lim-up)
2163 (while (and (< (point) lim-down)
2164 (org-list-search-forward (org-item-beginning-re)
2165 lim-down 'move))
2166 (let* ((struct (org-list-struct))
2167 (struct-copy (mapcar (lambda (e) (copy-alist e)) struct))
2168 (parents (org-list-struct-parent-alist struct))
2169 (prevs (org-list-struct-prev-alist struct))
2170 (bottom (copy-marker (org-list-get-bottom-point struct)))
2171 (items-to-toggle (org-remove-if
2172 (lambda (e) (or (< e lim-up) (> e lim-down)))
2173 (mapcar 'car (cdr struct)))))
2174 (mapc (lambda (e) (org-list-set-checkbox
2175 e struct
2176 ;; if there is no box at item, leave as-is
2177 ;; unless function was called with C-u prefix
2178 (let ((cur-box (org-list-get-checkbox e struct)))
2179 (if (or cur-box (equal toggle-presence '(4)))
2180 ref-checkbox
2181 cur-box))))
2182 items-to-toggle)
2183 (setq block-item (org-list-struct-fix-box
2184 struct parents prevs orderedp))
2185 ;; Report some problems due to ORDERED status of subtree. If
2186 ;; only one box was being checked, throw an error, else,
2187 ;; only signal problems.
2188 (cond
2189 ((and singlep block-item (> lim-up block-item))
2190 (error
2191 "Checkbox blocked because of unchecked box at line %d"
2192 (org-current-line block-item)))
2193 (block-item
2194 (message
2195 "Checkboxes were removed due to unchecked box at line %d"
2196 (org-current-line block-item))))
2197 (goto-char bottom)
2198 (org-list-struct-apply-struct struct struct-copy))))
2199 (org-update-checkbox-count-maybe)))
2201 (defun org-reset-checkbox-state-subtree ()
2202 "Reset all checkboxes in an entry subtree."
2203 (interactive "*")
2204 (save-restriction
2205 (save-excursion
2206 (org-narrow-to-subtree)
2207 (org-show-subtree)
2208 (goto-char (point-min))
2209 (let ((end (point-max)))
2210 (while (< (point) end)
2211 (when (org-at-item-checkbox-p)
2212 (replace-match "[ ]" t t nil 1))
2213 (beginning-of-line 2))))
2214 (org-update-checkbox-count-maybe)))
2216 (defvar org-checkbox-statistics-hook nil
2217 "Hook that is run whenever Org thinks checkbox statistics should be updated.
2218 This hook runs even if checkbox rule in
2219 `org-list-automatic-rules' does not apply, so it can be used to
2220 implement alternative ways of collecting statistics
2221 information.")
2223 (defun org-update-checkbox-count-maybe ()
2224 "Update checkbox statistics unless turned off by user."
2225 (when (cdr (assq 'checkbox org-list-automatic-rules))
2226 (org-update-checkbox-count))
2227 (run-hooks 'org-checkbox-statistics-hook))
2229 (defun org-update-checkbox-count (&optional all)
2230 "Update the checkbox statistics in the current section.
2231 This will find all statistic cookies like [57%] and [6/12] and
2232 update them with the current numbers.
2234 With optional prefix argument ALL, do this for the whole buffer."
2235 (interactive "P")
2236 (save-excursion
2237 (let ((cookie-re "\\(\\(\\[[0-9]*%\\]\\)\\|\\(\\[[0-9]*/[0-9]*\\]\\)\\)")
2238 (box-re "^[ \t]*\\([-+*]\\|\\([0-9]+\\|[A-Za-z]\\)[.)]\\)[ \t]+\\(?:\\[@\\(?:start:\\)?\\([0-9]+\\|[A-Za-z]\\)\\][ \t]*\\)?\\(\\[[- X]\\]\\)")
2239 (recursivep
2240 (or (not org-hierarchical-checkbox-statistics)
2241 (string-match "\\<recursive\\>"
2242 (or (ignore-errors
2243 (org-entry-get nil "COOKIE_DATA"))
2244 ""))))
2245 (bounds (if all
2246 (cons (point-min) (point-max))
2247 (cons (or (ignore-errors (org-back-to-heading) (point))
2248 (point-min))
2249 (save-excursion (outline-next-heading) (point)))))
2250 (count-boxes
2251 (function
2252 ;; Return number of checked boxes and boxes of all types
2253 ;; in all structures in STRUCTS. If RECURSIVEP is non-nil,
2254 ;; also count boxes in sub-lists. If ITEM is nil, count
2255 ;; across the whole structure, else count only across
2256 ;; subtree whose ancestor is ITEM.
2257 (lambda (item structs recursivep)
2258 (let ((c-on 0) (c-all 0))
2259 (mapc
2260 (lambda (s)
2261 (let* ((pre (org-list-struct-prev-alist s))
2262 (par (org-list-struct-parent-alist s))
2263 (items
2264 (cond
2265 ((and recursivep item) (org-list-get-subtree item s))
2266 (recursivep (mapcar 'car s))
2267 (item (org-list-get-children item s par))
2268 (t (org-list-get-all-items
2269 (org-list-get-top-point s) s pre))))
2270 (cookies (delq nil (mapcar
2271 (lambda (e)
2272 (org-list-get-checkbox e s))
2273 items))))
2274 (setq c-all (+ (length cookies) c-all)
2275 c-on (+ (org-count "[X]" cookies) c-on))))
2276 structs)
2277 (cons c-on c-all)))))
2278 (backup-end 1)
2279 cookies-list structs-bak box-num)
2280 (goto-char (car bounds))
2281 ;; 1. Build an alist for each cookie found within BOUNDS. The
2282 ;; key will be position at beginning of cookie and values
2283 ;; ending position, format of cookie, and a cell whose car is
2284 ;; number of checked boxes to report, and cdr total number of
2285 ;; boxes.
2286 (while (re-search-forward cookie-re (cdr bounds) t)
2287 (catch 'skip
2288 (save-excursion
2289 (push
2290 (list
2291 (match-beginning 1) ; cookie start
2292 (match-end 1) ; cookie end
2293 (match-string 2) ; percent?
2294 (cond ; boxes count
2295 ;; Cookie is at an heading, but specifically for todo,
2296 ;; not for checkboxes: skip it.
2297 ((and (org-on-heading-p)
2298 (string-match "\\<todo\\>"
2299 (downcase
2300 (or (org-entry-get nil "COOKIE_DATA") ""))))
2301 (throw 'skip nil))
2302 ;; Cookie is at an heading, but all lists before next
2303 ;; heading already have been read. Use data collected
2304 ;; in STRUCTS-BAK. This should only happen when heading
2305 ;; has more than one cookie on it.
2306 ((and (org-on-heading-p)
2307 (<= (save-excursion (outline-next-heading) (point))
2308 backup-end))
2309 (funcall count-boxes nil structs-bak recursivep))
2310 ;; Cookie is at a fresh heading. Grab structure of
2311 ;; every list containing a checkbox between point and
2312 ;; next headline, and save them in STRUCTS-BAK.
2313 ((org-on-heading-p)
2314 (setq backup-end (save-excursion
2315 (outline-next-heading) (point)))
2316 (while (org-list-search-forward box-re backup-end 'move)
2317 (let* ((struct (org-list-struct))
2318 (bottom (org-list-get-bottom-point struct)))
2319 (push struct structs-bak)
2320 (goto-char bottom)))
2321 (funcall count-boxes nil structs-bak recursivep))
2322 ;; Cookie is at an item, and we already have list
2323 ;; structure stored in STRUCTS-BAK.
2324 ((and (org-at-item-p)
2325 (< (point-at-bol) backup-end))
2326 (funcall count-boxes (point-at-bol) structs-bak recursivep))
2327 ;; Cookie is at an item, but we need to compute list
2328 ;; structure.
2329 ((org-at-item-p)
2330 (let ((struct (org-list-struct)))
2331 (setq backup-end (org-list-get-bottom-point struct)
2332 structs-bak (list struct)))
2333 (funcall count-boxes (point-at-bol) structs-bak recursivep))
2334 ;; Else, cookie found is at a wrong place. Skip it.
2335 (t (throw 'skip nil))))
2336 cookies-list))))
2337 ;; 2. Apply alist to buffer, in reverse order so positions stay
2338 ;; unchanged after cookie modifications.
2339 (mapc (lambda (cookie)
2340 (let* ((beg (car cookie))
2341 (end (nth 1 cookie))
2342 (percentp (nth 2 cookie))
2343 (checked (car (nth 3 cookie)))
2344 (total (cdr (nth 3 cookie)))
2345 (new (if percentp
2346 (format "[%d%%]" (/ (* 100 checked)
2347 (max 1 total)))
2348 (format "[%d/%d]" checked total))))
2349 (goto-char beg)
2350 (insert new)
2351 (delete-region (point) (+ (point) (- end beg)))))
2352 cookies-list))))
2354 (defun org-get-checkbox-statistics-face ()
2355 "Select the face for checkbox statistics.
2356 The face will be `org-done' when all relevant boxes are checked.
2357 Otherwise it will be `org-todo'."
2358 (if (match-end 1)
2359 (if (equal (match-string 1) "100%")
2360 'org-checkbox-statistics-done
2361 'org-checkbox-statistics-todo)
2362 (if (and (> (match-end 2) (match-beginning 2))
2363 (equal (match-string 2) (match-string 3)))
2364 'org-checkbox-statistics-done
2365 'org-checkbox-statistics-todo)))
2367 ;;; Misc Tools
2369 (defun org-apply-on-list (function init-value &rest args)
2370 "Call FUNCTION on each item of the list at point.
2371 FUNCTION must be called with at least one argument: INIT-VALUE,
2372 that will contain the value returned by the function at the
2373 previous item, plus ARGS extra arguments.
2375 FUNCTION is applied on items in reverse order.
2377 As an example, (org-apply-on-list (lambda (result) (1+ result)) 0)
2378 will return the number of items in the current list.
2380 Sublists of the list are skipped. Cursor is always at the
2381 beginning of the item."
2382 (let* ((struct (org-list-struct))
2383 (prevs (org-list-struct-prev-alist struct))
2384 (item (copy-marker (point-at-bol)))
2385 (all (org-list-get-all-items (marker-position item) struct prevs))
2386 (value init-value))
2387 (mapc (lambda (e)
2388 (goto-char e)
2389 (setq value (apply function value args)))
2390 (nreverse all))
2391 (goto-char item)
2392 value))
2394 (defun org-sort-list (&optional with-case sorting-type getkey-func compare-func)
2395 "Sort plain list items.
2396 The cursor may be at any item of the list that should be sorted.
2397 Sublists are not sorted. Checkboxes, if any, are ignored.
2399 Sorting can be alphabetically, numerically, by date/time as given by
2400 a time stamp, by a property or by priority.
2402 Comparing entries ignores case by default. However, with an
2403 optional argument WITH-CASE, the sorting considers case as well.
2405 The command prompts for the sorting type unless it has been given
2406 to the function through the SORTING-TYPE argument, which needs to
2407 be a character, \(?n ?N ?a ?A ?t ?T ?f ?F). Here is the precise
2408 meaning of each character:
2410 n Numerically, by converting the beginning of the item to a number.
2411 a Alphabetically. Only the first line of item is checked.
2412 t By date/time, either the first active time stamp in the entry, if
2413 any, or by the first inactive one. In a timer list, sort the timers.
2415 Capital letters will reverse the sort order.
2417 If the SORTING-TYPE is ?f or ?F, then GETKEY-FUNC specifies a
2418 function to be called with point at the beginning of the record.
2419 It must return either a string or a number that should serve as
2420 the sorting key for that record. It will then use COMPARE-FUNC to
2421 compare entries."
2422 (interactive "P")
2423 (let* ((case-func (if with-case 'identity 'downcase))
2424 (struct (org-list-struct))
2425 (prevs (org-list-struct-prev-alist struct))
2426 (start (org-list-get-list-begin (point-at-bol) struct prevs))
2427 (end (org-list-get-list-end (point-at-bol) struct prevs))
2428 (sorting-type
2429 (progn
2430 (message
2431 "Sort plain list: [a]lpha [n]umeric [t]ime [f]unc A/N/T/F means reversed:")
2432 (read-char-exclusive)))
2433 (getkey-func (and (= (downcase sorting-type) ?f)
2434 (org-icompleting-read "Sort using function: "
2435 obarray 'fboundp t nil nil)
2436 (intern getkey-func))))
2437 (message "Sorting items...")
2438 (save-restriction
2439 (narrow-to-region start end)
2440 (goto-char (point-min))
2441 (let* ((dcst (downcase sorting-type))
2442 (case-fold-search nil)
2443 (now (current-time))
2444 (sort-func (cond
2445 ((= dcst ?a) 'string<)
2446 ((= dcst ?f) compare-func)
2447 ((= dcst ?t) '<)
2448 (t nil)))
2449 (next-record (lambda ()
2450 (skip-chars-forward " \r\t\n")
2451 (beginning-of-line)))
2452 (end-record (lambda ()
2453 (goto-char (org-list-get-item-end-before-blank
2454 (point) struct))))
2455 (value-to-sort
2456 (lambda ()
2457 (when (looking-at "[ \t]*[-+*0-9.)]+\\([ \t]+\\[[- X]\\]\\)?[ \t]+")
2458 (cond
2459 ((= dcst ?n)
2460 (string-to-number (buffer-substring (match-end 0)
2461 (point-at-eol))))
2462 ((= dcst ?a)
2463 (buffer-substring (match-end 0) (point-at-eol)))
2464 ((= dcst ?t)
2465 (cond
2466 ;; If it is a timer list, convert timer to seconds
2467 ((org-at-item-timer-p)
2468 (org-timer-hms-to-secs (match-string 1)))
2469 ((or (re-search-forward org-ts-regexp (point-at-eol) t)
2470 (re-search-forward org-ts-regexp-both
2471 (point-at-eol) t))
2472 (org-time-string-to-seconds (match-string 0)))
2473 (t (org-float-time now))))
2474 ((= dcst ?f)
2475 (if getkey-func
2476 (let ((value (funcall getkey-func)))
2477 (if (stringp value)
2478 (funcall case-func value)
2479 value))
2480 (error "Invalid key function `%s'" getkey-func)))
2481 (t (error "Invalid sorting type `%c'" sorting-type)))))))
2482 (sort-subr (/= dcst sorting-type)
2483 next-record
2484 end-record
2485 value-to-sort
2487 sort-func)
2488 ;; Read and fix list again, as `sort-subr' probably destroyed
2489 ;; its structure.
2490 (org-list-repair)
2491 (run-hooks 'org-after-sorting-entries-or-items-hook)
2492 (message "Sorting items...done")))))
2494 ;;; Send and receive lists
2495 (defun org-list-parse-list (&optional delete)
2496 "Parse the list at point and maybe DELETE it.
2498 Return a list whose car is a symbol of list type, among
2499 `ordered', `unordered' and `descriptive'. Then, each item is a
2500 list whose car is counter, and cdr are strings and other
2501 sub-lists. Inside strings, checkboxes are replaced by \"[CBON]\"
2502 and \"[CBOFF]\".
2504 For example, the following list:
2506 1. first item
2507 + sub-item one
2508 + [X] sub-item two
2509 more text in first item
2510 2. [@3] last item
2512 will be parsed as:
2514 \(ordered
2515 \(nil \"first item\"
2516 \(unordered
2517 \(nil \"sub-item one\"\)
2518 \(nil \"[CBON] sub-item two\"\)\)
2519 \"more text in first item\"\)
2520 \(3 \"last item\"\)\)
2522 Point is left at list end."
2523 (let* ((struct (org-list-struct))
2524 (prevs (org-list-struct-prev-alist struct))
2525 (parents (org-list-struct-parent-alist struct))
2526 (top (org-list-get-top-point struct))
2527 (bottom (org-list-get-bottom-point struct))
2529 (get-text
2530 (function
2531 ;; Return text between BEG and END, trimmed, with
2532 ;; checkboxes replaced.
2533 (lambda (beg end)
2534 (let ((text (org-trim (buffer-substring beg end))))
2535 (if (string-match "\\`\\[\\([xX ]\\)\\]" text)
2536 (replace-match
2537 (if (equal (match-string 1 text) " ") "CBOFF" "CBON")
2538 t nil text 1)
2539 text)))))
2540 (parse-sublist
2541 (function
2542 ;; Return a list whose car is list type and cdr a list of
2543 ;; items' body.
2544 (lambda (e)
2545 (cons (org-list-get-list-type (car e) struct prevs)
2546 (mapcar parse-item e)))))
2547 (parse-item
2548 (function
2549 ;; Return a list containing conter of item, if any, text
2550 ;; and any sublist inside it.
2551 (lambda (e)
2552 (let ((start (save-excursion
2553 (goto-char e)
2554 (or (org-at-item-counter-p) (org-at-item-p))
2555 (match-end 0)))
2556 ;; Get counter number. For alphabetic counter, get
2557 ;; its position in the alphabet.
2558 (counter (let ((c (org-list-get-counter e struct)))
2559 (cond
2560 ((not c) nil)
2561 ((string-match "[A-Za-z]" c)
2562 (- (string-to-char (upcase (match-string 0 c)))
2563 64))
2564 ((string-match "[0-9]+" c)
2565 (string-to-number (match-string 0 c))))))
2566 (childp (org-list-has-child-p e struct))
2567 (end (org-list-get-item-end e struct)))
2568 ;; If item has a child, store text between bullet and
2569 ;; next child, then recursively parse all sublists. At
2570 ;; the end of each sublist, check for the presence of
2571 ;; text belonging to the original item.
2572 (if childp
2573 (let* ((children (org-list-get-children e struct parents))
2574 (body (list (funcall get-text start childp))))
2575 (while children
2576 (let* ((first (car children))
2577 (sub (org-list-get-all-items first struct prevs))
2578 (last-c (car (last sub)))
2579 (last-end (org-list-get-item-end last-c struct)))
2580 (push (funcall parse-sublist sub) body)
2581 ;; Remove children from the list just parsed.
2582 (setq children (cdr (member last-c children)))
2583 ;; There is a chunk of text belonging to the
2584 ;; item if last child doesn't end where next
2585 ;; child starts or where item ends.
2586 (unless (= (or (car children) end) last-end)
2587 (push (funcall get-text
2588 last-end (or (car children) end))
2589 body))))
2590 (cons counter (nreverse body)))
2591 (list counter (funcall get-text start end))))))))
2592 ;; Store output, take care of cursor position and deletion of
2593 ;; list, then return output.
2594 (setq out (funcall parse-sublist (org-list-get-all-items top struct prevs)))
2595 (goto-char top)
2596 (when delete
2597 (delete-region top bottom)
2598 (when (and (not (eq org-list-ending-method 'indent))
2599 (looking-at org-list-end-re))
2600 (replace-match "\n")))
2601 out))
2603 (defun org-list-make-subtree ()
2604 "Convert the plain list at point into a subtree."
2605 (interactive)
2606 (if (not (ignore-errors (goto-char (org-in-item-p))))
2607 (error "Not in a list")
2608 (let ((list (org-list-parse-list t)) nstars)
2609 (save-excursion
2610 (if (ignore-errors (org-back-to-heading))
2611 (progn (looking-at org-complex-heading-regexp)
2612 (setq nstars (length (match-string 1))))
2613 (setq nstars 0)))
2614 (org-list-make-subtrees list (1+ nstars)))))
2616 (defun org-list-make-subtrees (list level)
2617 "Convert LIST into subtrees starting at LEVEL."
2618 (if (symbolp (car list))
2619 (org-list-make-subtrees (cdr list) level)
2620 (mapcar (lambda (item)
2621 (if (stringp item)
2622 (insert (make-string
2623 (if org-odd-levels-only
2624 (1- (* 2 level)) level) ?*) " " item "\n")
2625 (org-list-make-subtrees item (1+ level))))
2626 list)))
2628 (defun org-list-insert-radio-list ()
2629 "Insert a radio list template appropriate for this major mode."
2630 (interactive)
2631 (let* ((e (assq major-mode org-list-radio-list-templates))
2632 (txt (nth 1 e))
2633 name pos)
2634 (unless e (error "No radio list setup defined for %s" major-mode))
2635 (setq name (read-string "List name: "))
2636 (while (string-match "%n" txt)
2637 (setq txt (replace-match name t t txt)))
2638 (or (bolp) (insert "\n"))
2639 (setq pos (point))
2640 (insert txt)
2641 (goto-char pos)))
2643 (defun org-list-send-list (&optional maybe)
2644 "Send a transformed version of this list to the receiver position.
2645 With argument MAYBE, fail quietly if no transformation is defined for
2646 this list."
2647 (interactive)
2648 (catch 'exit
2649 (unless (org-at-item-p) (error "Not at a list item"))
2650 (save-excursion
2651 (re-search-backward "#\\+ORGLST" nil t)
2652 (unless (looking-at "[ \t]*#\\+ORGLST[: \t][ \t]*SEND[ \t]+\\([^ \t\r\n]+\\)[ \t]+\\([^ \t\r\n]+\\)\\([ \t]+.*\\)?")
2653 (if maybe
2654 (throw 'exit nil)
2655 (error "Don't know how to transform this list"))))
2656 (let* ((name (match-string 1))
2657 (transform (intern (match-string 2)))
2658 (bottom-point
2659 (save-excursion
2660 (re-search-forward
2661 "\\(\\\\end{comment}\\|@end ignore\\|-->\\)" nil t)
2662 (match-beginning 0)))
2663 (top-point
2664 (progn
2665 (re-search-backward "#\\+ORGLST" nil t)
2666 (re-search-forward (org-item-beginning-re) bottom-point t)
2667 (match-beginning 0)))
2668 (list (save-restriction
2669 (narrow-to-region top-point bottom-point)
2670 (org-list-parse-list)))
2671 beg txt)
2672 (unless (fboundp transform)
2673 (error "No such transformation function %s" transform))
2674 (let ((txt (funcall transform list)))
2675 ;; Find the insertion place
2676 (save-excursion
2677 (goto-char (point-min))
2678 (unless (re-search-forward
2679 (concat "BEGIN RECEIVE ORGLST +"
2680 name
2681 "\\([ \t]\\|$\\)") nil t)
2682 (error "Don't know where to insert translated list"))
2683 (goto-char (match-beginning 0))
2684 (beginning-of-line 2)
2685 (setq beg (point))
2686 (unless (re-search-forward (concat "END RECEIVE ORGLST +" name) nil t)
2687 (error "Cannot find end of insertion region"))
2688 (delete-region beg (point-at-bol))
2689 (goto-char beg)
2690 (insert txt "\n")))
2691 (message "List converted and installed at receiver location"))))
2693 (defun org-list-to-generic (list params)
2694 "Convert a LIST parsed through `org-list-parse-list' to other formats.
2695 Valid parameters PARAMS are
2697 :ustart String to start an unordered list
2698 :uend String to end an unordered list
2700 :ostart String to start an ordered list
2701 :oend String to end an ordered list
2703 :dstart String to start a descriptive list
2704 :dend String to end a descriptive list
2705 :dtstart String to start a descriptive term
2706 :dtend String to end a descriptive term
2707 :ddstart String to start a description
2708 :ddend String to end a description
2710 :splice When set to t, return only list body lines, don't wrap
2711 them into :[u/o]start and :[u/o]end. Default is nil.
2713 :istart String to start a list item.
2714 :icount String to start an item with a counter.
2715 :iend String to end a list item
2716 :isep String to separate items
2717 :lsep String to separate sublists
2719 :cboff String to insert for an unchecked checkbox
2720 :cbon String to insert for a checked checkbox
2722 Alternatively, each parameter can also be a form returning a
2723 string. These sexp can use keywords `counter' and `depth',
2724 reprensenting respectively counter associated to the current
2725 item, and depth of the current sub-list, starting at 0.
2726 Obviously, `counter' is only available for parameters applying to
2727 items."
2728 (interactive)
2729 (let* ((p params)
2730 (splicep (plist-get p :splice))
2731 (ostart (plist-get p :ostart))
2732 (oend (plist-get p :oend))
2733 (ustart (plist-get p :ustart))
2734 (uend (plist-get p :uend))
2735 (dstart (plist-get p :dstart))
2736 (dend (plist-get p :dend))
2737 (dtstart (plist-get p :dtstart))
2738 (dtend (plist-get p :dtend))
2739 (ddstart (plist-get p :ddstart))
2740 (ddend (plist-get p :ddend))
2741 (istart (plist-get p :istart))
2742 (icount (plist-get p :icount))
2743 (iend (plist-get p :iend))
2744 (isep (plist-get p :isep))
2745 (lsep (plist-get p :lsep))
2746 (cbon (plist-get p :cbon))
2747 (cboff (plist-get p :cboff))
2748 (export-item
2749 (function
2750 ;; Export an item ITEM of type TYPE, at DEPTH. First string
2751 ;; in item is treated in a special way as it can bring
2752 ;; extra information that needs to be processed.
2753 (lambda (item type depth)
2754 (let* ((counter (pop item))
2755 (fmt (cond
2756 ((eq type 'descriptive)
2757 (mapconcat 'eval `(,(org-trim istart)
2758 "%s" ,ddend ,iend ,isep) ""))
2759 ((and counter (eq type 'ordered))
2760 (mapconcat 'eval `(,icount "%s" ,iend ,isep) ""))
2761 (t (mapconcat 'eval `(,istart "%s" ,iend ,isep) ""))))
2762 (first (car item)))
2763 ;; Replace checkbox if any is found.
2764 (cond
2765 ((string-match "\\[CBON\\]" first)
2766 (setq first (replace-match cbon t t first)))
2767 ((string-match "\\[CBOFF\\]" first)
2768 (setq first (replace-match cboff t t first)))
2769 ((string-match "\\[-\\]" first)
2770 (setq first (replace-match "$\\boxminus$" t t first))))
2771 ;; Insert descriptive term if TYPE is `descriptive'.
2772 (when (and (eq type 'descriptive)
2773 (string-match "^\\(.*\\)[ \t]+::" first))
2774 (setq first (mapconcat
2775 'eval
2776 `(,dtstart ,(org-trim (match-string 1 first)) ,dtend
2777 ,ddstart ,(org-trim (substring first (match-end 0)))))))
2778 (setcar item first)
2779 (format fmt
2780 (mapconcat (lambda (e)
2781 (if (stringp e) e
2782 (funcall export-sublist e (1+ depth))))
2783 item isep))))))
2784 (export-sublist
2785 (function
2786 ;; Export sublist SUB at DEPTH
2787 (lambda (sub depth)
2788 (let* ((type (car sub))
2789 (items (cdr sub))
2790 (fmt (cond
2791 (splicep "%s")
2792 ((eq type 'ordered)
2793 (mapconcat 'eval `(,ostart "\n%s" ,oend) ""))
2794 ((eq type 'descriptive)
2795 (mapconcat 'eval `(,dstart "\n%s" ,dend) ""))
2796 (t (mapconcat 'eval `(,ustart "\n%s" ,uend) "")))))
2797 (format fmt (mapconcat (lambda (e)
2798 (funcall export-item e type depth))
2799 items lsep)))))))
2800 (concat (funcall export-sublist list 0) "\n")))
2802 (defun org-list-to-latex (list &optional params)
2803 "Convert LIST into a LaTeX list.
2804 LIST is as returned by `org-list-parse-list'. PARAMS is a property list
2805 with overruling parameters for `org-list-to-generic'."
2806 (org-list-to-generic
2807 list
2808 (org-combine-plists
2809 '(:splicep nil :ostart "\\begin{enumerate}" :oend "\\end{enumerate}"
2810 :ustart "\\begin{itemize}" :uend "\\end{itemize}"
2811 :dstart "\\begin{description}" :dend "\\end{description}"
2812 :dtstart "[" :dtend "] "
2813 :ddstart "" :ddend ""
2814 :istart "\\item " :iend ""
2815 :icount (let ((enum (nth depth '("i" "ii" "iii" "iv"))))
2816 (if enum
2817 (format "\\setcounter{enum%s}{%s}\n\\item "
2818 enum counter)
2819 "\\item "))
2820 :isep "\n" :lsep "\n"
2821 :cbon "\\texttt{[X]}" :cboff "\\texttt{[ ]}")
2822 params)))
2824 (defun org-list-to-html (list &optional params)
2825 "Convert LIST into a HTML list.
2826 LIST is as returned by `org-list-parse-list'. PARAMS is a property list
2827 with overruling parameters for `org-list-to-generic'."
2828 (org-list-to-generic
2829 list
2830 (org-combine-plists
2831 '(:splicep nil :ostart "<ol>" :oend "</ol>"
2832 :ustart "<ul>" :uend "</ul>"
2833 :dstart "<dl>" :dend "</dl>"
2834 :dtstart "<dt>" :dtend "</dt>"
2835 :ddstart "<dd>" :ddend "</dd>"
2836 :istart "<li>" :iend "</li>"
2837 :icount (format "<li value=\"%s\">" counter)
2838 :isep "\n" :lsep "\n"
2839 :cbon "<code>[X]</code>" :cboff "<code>[ ]</code>")
2840 params)))
2842 (defun org-list-to-texinfo (list &optional params)
2843 "Convert LIST into a Texinfo list.
2844 LIST is as returned by `org-list-parse-list'. PARAMS is a property list
2845 with overruling parameters for `org-list-to-generic'."
2846 (org-list-to-generic
2847 list
2848 (org-combine-plists
2849 '(:splicep nil :ostart "@itemize @minus" :oend "@end itemize"
2850 :ustart "@enumerate" :uend "@end enumerate"
2851 :dstart "@table @asis" :dend "@end table"
2852 :dtstart " " :dtend "\n"
2853 :ddstart "" :ddend ""
2854 :istart "@item\n" :iend ""
2855 :icount "@item\n"
2856 :isep "\n" :lsep "\n"
2857 :cbon "@code{[X]}" :cboff "@code{[ ]}")
2858 params)))
2860 (provide 'org-list)
2862 ;; arch-tag: 73cf50c1-200f-4d1d-8a53-4e842a5b11c8
2863 ;;; org-list.el ends here