org-element: Parse contents of DATE keyword
[org-mode.git] / lisp / org-list.el
blobc6dcb79c4b5a1c272f38d5e4a1ff8225caa26f63
1 ;;; org-list.el --- Plain lists for Org-mode
2 ;;
3 ;; Copyright (C) 2004-2012 Free Software Foundation, Inc.
4 ;;
5 ;; Author: Carsten Dominik <carsten at orgmode dot org>
6 ;; Bastien Guerry <bzg AT gnu DOT org>
7 ;; Keywords: outlines, hypermedia, calendar, wp
8 ;; Homepage: http://orgmode.org
9 ;;
10 ;; This file is part of GNU Emacs.
12 ;; GNU Emacs is free software: you can redistribute it and/or modify
13 ;; it under the terms of the GNU General Public License as published by
14 ;; the Free Software Foundation, either version 3 of the License, or
15 ;; (at your option) any later version.
17 ;; GNU Emacs is distributed in the hope that it will be useful,
18 ;; but WITHOUT ANY WARRANTY; without even the implied warranty of
19 ;; MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
20 ;; GNU General Public License for more details.
22 ;; You should have received a copy of the GNU General Public License
23 ;; along with GNU Emacs. If not, see <http://www.gnu.org/licenses/>.
24 ;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;
26 ;;; Commentary:
28 ;; This file contains the code dealing with plain lists in Org-mode.
30 ;; The core concept behind lists is their structure. A structure is
31 ;; a snapshot of the list, in the shape of a data tree (see
32 ;; `org-list-struct').
34 ;; Once the list structure is stored, it is possible to make changes
35 ;; on it that will be mirrored to the real list or to get information
36 ;; about the list, using accessors and methods provided in the
37 ;; library. Most of them require the use of one or two helper
38 ;; functions, namely `org-list-parents-alist' and
39 ;; `org-list-prevs-alist'.
41 ;; Structure is eventually applied to the buffer with
42 ;; `org-list-write-struct'. This function repairs (bullets,
43 ;; indentation, checkboxes) the list in the process. It should be
44 ;; called near the end of any function working on structures.
46 ;; Thus, a function applying to lists should usually follow this
47 ;; template:
49 ;; 1. Verify point is in a list and grab item beginning (with the same
50 ;; function `org-in-item-p'). If the function requires the cursor
51 ;; to be at item's bullet, `org-at-item-p' is more selective. It
52 ;; is also possible to move point to the closest item with
53 ;; `org-list-search-backward', or `org-list-search-forward',
54 ;; applied to the function `org-item-beginning-re'.
56 ;; 2. Get list structure with `org-list-struct'.
58 ;; 3. Compute one, or both, helper functions,
59 ;; (`org-list-parents-alist', `org-list-prevs-alist') depending on
60 ;; needed accessors.
62 ;; 4. Proceed with the modifications, using methods and accessors.
64 ;; 5. Verify and apply structure to buffer, using
65 ;; `org-list-write-struct'.
67 ;; 6. If changes made to the list might have modified check-boxes,
68 ;; call `org-update-checkbox-count-maybe'.
70 ;; Computing a structure can be a costly operation on huge lists (a
71 ;; few thousand lines long). Thus, code should follow the rule:
72 ;; "collect once, use many". As a corollary, it is usually a bad idea
73 ;; to use directly an interactive function inside the code, as those,
74 ;; being independent entities, read the whole list structure another
75 ;; time.
77 ;;; Code:
79 (eval-when-compile
80 (require 'cl))
81 (require 'org-macs)
82 (require 'org-compat)
84 (defvar org-M-RET-may-split-line)
85 (defvar org-auto-align-tags)
86 (defvar org-blank-before-new-entry)
87 (defvar org-clock-string)
88 (defvar org-closed-string)
89 (defvar org-deadline-string)
90 (defvar org-description-max-indent)
91 (defvar org-drawers)
92 (defvar org-odd-levels-only)
93 (defvar org-scheduled-string)
94 (defvar org-ts-regexp)
95 (defvar org-ts-regexp-both)
97 (declare-function org-at-heading-p "org" (&optional ignored))
98 (declare-function org-before-first-heading-p "org" ())
99 (declare-function org-back-to-heading "org" (&optional invisible-ok))
100 (declare-function org-combine-plists "org" (&rest plists))
101 (declare-function org-count "org" (cl-item cl-seq))
102 (declare-function org-current-level "org" ())
103 (declare-function org-entry-get "org"
104 (pom property &optional inherit literal-nil))
105 (declare-function org-fix-tags-on-the-fly "org" ())
106 (declare-function org-get-indentation "org" (&optional line))
107 (declare-function org-icompleting-read "org" (&rest args))
108 (declare-function org-in-block-p "org" (names))
109 (declare-function org-in-regexp "org" (re &optional nlines visually))
110 (declare-function org-inlinetask-goto-beginning "org-inlinetask" ())
111 (declare-function org-inlinetask-goto-end "org-inlinetask" ())
112 (declare-function org-inlinetask-in-task-p "org-inlinetask" ())
113 (declare-function org-inlinetask-outline-regexp "org-inlinetask" ())
114 (declare-function org-level-increment "org" ())
115 (declare-function org-narrow-to-subtree "org" ())
116 (declare-function org-at-heading-p "org" (&optional invisible-ok))
117 (declare-function org-previous-line-empty-p "org" ())
118 (declare-function org-remove-if "org" (predicate seq))
119 (declare-function org-reduced-level "org" (L))
120 (declare-function org-show-subtree "org" ())
121 (declare-function org-time-string-to-seconds "org" (s))
122 (declare-function org-timer-hms-to-secs "org-timer" (hms))
123 (declare-function org-timer-item "org-timer" (&optional arg))
124 (declare-function org-trim "org" (s))
125 (declare-function org-uniquify "org" (list))
126 (declare-function outline-invisible-p "outline" (&optional pos))
127 (declare-function outline-flag-region "outline" (from to flag))
128 (declare-function outline-next-heading "outline" ())
129 (declare-function outline-previous-heading "outline" ())
133 ;;; Configuration variables
135 (defgroup org-plain-lists nil
136 "Options concerning plain lists in Org-mode."
137 :tag "Org Plain lists"
138 :group 'org-structure)
140 (defcustom org-cycle-include-plain-lists t
141 "When t, make TAB cycle visibility on plain list items.
142 Cycling plain lists works only when the cursor is on a plain list
143 item. When the cursor is on an outline heading, plain lists are
144 treated as text. This is the most stable way of handling this,
145 which is why it is the default.
147 When this is the symbol `integrate', then during cycling, plain
148 list items will *temporarily* be interpreted as outline headlines
149 with a level given by 1000+i where i is the indentation of the
150 bullet. This setting can lead to strange effects when switching
151 visibility to `children', because the first \"child\" in a
152 subtree decides what children should be listed. If that first
153 \"child\" is a plain list item with an implied large level
154 number, all true children and grand children of the outline
155 heading will be exposed in a children' view."
156 :group 'org-plain-lists
157 :type '(choice
158 (const :tag "Never" nil)
159 (const :tag "With cursor in plain list (recommended)" t)
160 (const :tag "As children of outline headings" integrate)))
162 (defcustom org-list-demote-modify-bullet nil
163 "Default bullet type installed when demoting an item.
164 This is an association list, for each bullet type, this alist will point
165 to the bullet that should be used when this item is demoted.
166 For example,
168 (setq org-list-demote-modify-bullet
169 '((\"+\" . \"-\") (\"-\" . \"+\") (\"*\" . \"+\")))
171 will make
173 + Movies
174 + Silence of the Lambs
175 + My Cousin Vinny
176 + Books
177 + The Hunt for Red October
178 + The Road to Omaha
180 into
182 + Movies
183 - Silence of the Lambs
184 - My Cousin Vinny
185 + Books
186 - The Hunt for Red October
187 - The Road to Omaha"
188 :group 'org-plain-lists
189 :type '(repeat
190 (cons
191 (choice :tag "If the current bullet is "
192 (const "-")
193 (const "+")
194 (const "*")
195 (const "1.")
196 (const "1)"))
197 (choice :tag "demotion will change it to"
198 (const "-")
199 (const "+")
200 (const "*")
201 (const "1.")
202 (const "1)")))))
204 (defcustom org-plain-list-ordered-item-terminator t
205 "The character that makes a line with leading number an ordered list item.
206 Valid values are ?. and ?\). To get both terminators, use t."
207 :group 'org-plain-lists
208 :type '(choice (const :tag "dot like in \"2.\"" ?.)
209 (const :tag "paren like in \"2)\"" ?\))
210 (const :tag "both" t)))
212 (defcustom org-alphabetical-lists nil
213 "Non-nil means single character alphabetical bullets are allowed.
214 Both uppercase and lowercase are handled. Lists with more than
215 26 items will fallback to standard numbering. Alphabetical
216 counters like \"[@c]\" will be recognized."
217 :group 'org-plain-lists
218 :version "24.1"
219 :type 'boolean)
221 (defcustom org-list-two-spaces-after-bullet-regexp nil
222 "A regular expression matching bullets that should have 2 spaces after them.
223 When nil, no bullet will have two spaces after them. When
224 a string, it will be used as a regular expression. When the
225 bullet type of a list is changed, the new bullet type will be
226 matched against this regexp. If it matches, there will be two
227 spaces instead of one after the bullet in each item of the list."
228 :group 'org-plain-lists
229 :type '(choice
230 (const :tag "never" nil)
231 (regexp)))
233 (defcustom org-empty-line-terminates-plain-lists nil
234 "Non-nil means an empty line ends all plain list levels.
235 Otherwise, two of them will be necessary."
236 :group 'org-plain-lists
237 :type 'boolean)
239 (defcustom org-list-automatic-rules '((bullet . t)
240 (checkbox . t)
241 (indent . t))
242 "Non-nil means apply set of rules when acting on lists.
243 By default, automatic actions are taken when using
244 \\[org-meta-return], \\[org-metaright], \\[org-metaleft],
245 \\[org-shiftmetaright], \\[org-shiftmetaleft],
246 \\[org-ctrl-c-minus], \\[org-toggle-checkbox] or
247 \\[org-insert-todo-heading]. You can disable individually these
248 rules by setting them to nil. Valid rules are:
250 bullet when non-nil, cycling bullet do not allow lists at
251 column 0 to have * as a bullet and descriptions lists
252 to be numbered.
253 checkbox when non-nil, checkbox statistics is updated each time
254 you either insert a new checkbox or toggle a checkbox.
255 indent when non-nil, indenting or outdenting list top-item
256 with its subtree will move the whole list and
257 outdenting a list whose bullet is * to column 0 will
258 change that bullet to \"-\"."
259 :group 'org-plain-lists
260 :version "24.1"
261 :type '(alist :tag "Sets of rules"
262 :key-type
263 (choice
264 (const :tag "Bullet" bullet)
265 (const :tag "Checkbox" checkbox)
266 (const :tag "Indent" indent))
267 :value-type
268 (boolean :tag "Activate" :value t)))
270 (defcustom org-list-use-circular-motion nil
271 "Non-nil means commands implying motion in lists should be cyclic.
273 In that case, the item following the last item is the first one,
274 and the item preceding the first item is the last one.
276 This affects the behavior of \\[org-move-item-up],
277 \\[org-move-item-down], \\[org-next-item] and
278 \\[org-previous-item]."
279 :group 'org-plain-lists
280 :version "24.1"
281 :type 'boolean)
283 (defvar org-checkbox-statistics-hook nil
284 "Hook that is run whenever Org thinks checkbox statistics should be updated.
285 This hook runs even if checkbox rule in
286 `org-list-automatic-rules' does not apply, so it can be used to
287 implement alternative ways of collecting statistics
288 information.")
290 (defcustom org-hierarchical-checkbox-statistics t
291 "Non-nil means checkbox statistics counts only the state of direct children.
292 When nil, all boxes below the cookie are counted.
293 This can be set to nil on a per-node basis using a COOKIE_DATA property
294 with the word \"recursive\" in the value."
295 :group 'org-plain-lists
296 :type 'boolean)
298 (defcustom org-description-max-indent 20
299 "Maximum indentation for the second line of a description list.
300 When the indentation would be larger than this, it will become
301 5 characters instead."
302 :group 'org-plain-lists
303 :type 'integer)
305 (defcustom org-list-indent-offset 0
306 "Additional indentation for sub-items in a list.
307 By setting this to a small number, usually 1 or 2, one can more
308 clearly distinguish sub-items in a list."
309 :group 'org-plain-lists
310 :version "24.1"
311 :type 'integer)
313 (defcustom org-list-radio-list-templates
314 '((latex-mode "% BEGIN RECEIVE ORGLST %n
315 % END RECEIVE ORGLST %n
316 \\begin{comment}
317 #+ORGLST: SEND %n org-list-to-latex
319 \\end{comment}\n")
320 (texinfo-mode "@c BEGIN RECEIVE ORGLST %n
321 @c END RECEIVE ORGLST %n
322 @ignore
323 #+ORGLST: SEND %n org-list-to-texinfo
325 @end ignore\n")
326 (html-mode "<!-- BEGIN RECEIVE ORGLST %n -->
327 <!-- END RECEIVE ORGLST %n -->
328 <!--
329 #+ORGLST: SEND %n org-list-to-html
331 -->\n"))
332 "Templates for radio lists in different major modes.
333 All occurrences of %n in a template will be replaced with the name of the
334 list, obtained by prompting the user."
335 :group 'org-plain-lists
336 :type '(repeat
337 (list (symbol :tag "Major mode")
338 (string :tag "Format"))))
340 (defvar org-list-forbidden-blocks '("example" "verse" "src" "ascii" "beamer"
341 "docbook" "html" "latex" "odt")
342 "Names of blocks where lists are not allowed.
343 Names must be in lower case.")
345 (defvar org-list-export-context '(block inlinetask)
346 "Context types where lists will be interpreted during export.
348 Valid types are `drawer', `inlinetask' and `block'. More
349 specifically, type `block' is determined by the variable
350 `org-list-forbidden-blocks'.")
354 ;;; Predicates and regexps
356 (defconst org-list-end-re (if org-empty-line-terminates-plain-lists "^[ \t]*\n"
357 "^[ \t]*\n[ \t]*\n")
358 "Regex corresponding to the end of a list.
359 It depends on `org-empty-line-terminates-plain-lists'.")
361 (defconst org-list-full-item-re
362 (concat "^[ \t]*\\(\\(?:[-+*]\\|\\(?:[0-9]+\\|[A-Za-z]\\)[.)]\\)\\(?:[ \t]+\\|$\\)\\)"
363 "\\(?:\\[@\\(?:start:\\)?\\([0-9]+\\|[A-Za-z]\\)\\][ \t]*\\)?"
364 "\\(?:\\(\\[[ X-]\\]\\)\\(?:[ \t]+\\|$\\)\\)?"
365 "\\(?:\\(.*\\)[ \t]+::\\(?:[ \t]+\\|$\\)\\)?")
366 "Matches a list item and puts everything into groups:
367 group 1: bullet
368 group 2: counter
369 group 3: checkbox
370 group 4: description tag")
372 (defun org-item-re ()
373 "Return the correct regular expression for plain lists."
374 (let ((term (cond
375 ((eq org-plain-list-ordered-item-terminator t) "[.)]")
376 ((= org-plain-list-ordered-item-terminator ?\)) ")")
377 ((= org-plain-list-ordered-item-terminator ?.) "\\.")
378 (t "[.)]")))
379 (alpha (if org-alphabetical-lists "\\|[A-Za-z]" "")))
380 (concat "\\([ \t]*\\([-+]\\|\\(\\([0-9]+" alpha "\\)" term
381 "\\)\\)\\|[ \t]+\\*\\)\\([ \t]+\\|$\\)")))
383 (defsubst org-item-beginning-re ()
384 "Regexp matching the beginning of a plain list item."
385 (concat "^" (org-item-re)))
387 (defun org-list-at-regexp-after-bullet-p (regexp)
388 "Is point at a list item with REGEXP after bullet?"
389 (and (org-at-item-p)
390 (save-excursion
391 (goto-char (match-end 0))
392 (let ((counter-re (concat "\\(?:\\[@\\(?:start:\\)?"
393 (if org-alphabetical-lists
394 "\\([0-9]+\\|[A-Za-z]\\)"
395 "[0-9]+")
396 "\\][ \t]*\\)")))
397 ;; Ignore counter if any
398 (when (looking-at counter-re) (goto-char (match-end 0))))
399 (looking-at regexp))))
401 (defun org-list-in-valid-context-p ()
402 "Is point in a context where lists are allowed?"
403 (not (org-in-block-p org-list-forbidden-blocks)))
405 (defun org-in-item-p ()
406 "Return item beginning position when in a plain list, nil otherwise."
407 (save-excursion
408 (beginning-of-line)
409 (let* ((case-fold-search t)
410 (context (org-list-context))
411 (lim-up (car context))
412 (drawers-re (concat "^[ \t]*:\\("
413 (mapconcat 'regexp-quote org-drawers "\\|")
414 "\\):[ \t]*$"))
415 (inlinetask-re (and (featurep 'org-inlinetask)
416 (org-inlinetask-outline-regexp)))
417 (item-re (org-item-re))
418 ;; Indentation isn't meaningful when point starts at an empty
419 ;; line or an inline task.
420 (ind-ref (if (or (looking-at "^[ \t]*$")
421 (and inlinetask-re (looking-at inlinetask-re)))
422 10000
423 (org-get-indentation))))
424 (cond
425 ((eq (nth 2 context) 'invalid) nil)
426 ((looking-at item-re) (point))
428 ;; Detect if cursor in amidst `org-list-end-re'. First, count
429 ;; number HL of hard lines it takes, then call `org-in-regexp'
430 ;; to compute its boundaries END-BOUNDS. When point is
431 ;; in-between, move cursor before regexp beginning.
432 (let ((hl 0) (i -1) end-bounds)
433 (when (and (progn
434 (while (setq i (string-match
435 "[\r\n]" org-list-end-re (1+ i)))
436 (setq hl (1+ hl)))
437 (setq end-bounds (org-in-regexp org-list-end-re hl)))
438 (>= (point) (car end-bounds))
439 (< (point) (cdr end-bounds)))
440 (goto-char (car end-bounds))
441 (forward-line -1)))
442 ;; Look for an item, less indented that reference line.
443 (catch 'exit
444 (while t
445 (let ((ind (org-get-indentation)))
446 (cond
447 ;; This is exactly what we want.
448 ((and (looking-at item-re) (< ind ind-ref))
449 (throw 'exit (point)))
450 ;; At upper bound of search or looking at the end of a
451 ;; previous list: search is over.
452 ((<= (point) lim-up) (throw 'exit nil))
453 ((looking-at org-list-end-re) (throw 'exit nil))
454 ;; Skip blocks, drawers, inline-tasks, blank lines
455 ((and (looking-at "^[ \t]*#\\+end_")
456 (re-search-backward "^[ \t]*#\\+begin_" lim-up t)))
457 ((and (looking-at "^[ \t]*:END:")
458 (re-search-backward drawers-re lim-up t))
459 (beginning-of-line))
460 ((and inlinetask-re (looking-at inlinetask-re))
461 (org-inlinetask-goto-beginning)
462 (forward-line -1))
463 ((looking-at "^[ \t]*$") (forward-line -1))
464 ;; Text at column 0 cannot belong to a list: stop.
465 ((zerop ind) (throw 'exit nil))
466 ;; Normal text less indented than reference line, take
467 ;; it as new reference.
468 ((< ind ind-ref)
469 (setq ind-ref ind)
470 (forward-line -1))
471 (t (forward-line -1)))))))))))
473 (defun org-at-item-p ()
474 "Is point in a line starting a hand-formatted item?"
475 (save-excursion
476 (beginning-of-line)
477 (and (looking-at (org-item-re)) (org-list-in-valid-context-p))))
479 (defun org-at-item-bullet-p ()
480 "Is point at the bullet of a plain list item?"
481 (and (org-at-item-p)
482 (not (member (char-after) '(?\ ?\t)))
483 (< (point) (match-end 0))))
485 (defun org-at-item-timer-p ()
486 "Is point at a line starting a plain list item with a timer?"
487 (org-list-at-regexp-after-bullet-p
488 "\\([0-9]+:[0-9]+:[0-9]+\\)[ \t]+::[ \t]+"))
490 (defun org-at-item-description-p ()
491 "Is point at a description list item?"
492 (org-list-at-regexp-after-bullet-p "\\(\\S-.+\\)[ \t]+::\\([ \t]+\\|$\\)"))
494 (defun org-at-item-checkbox-p ()
495 "Is point at a line starting a plain-list item with a checklet?"
496 (org-list-at-regexp-after-bullet-p "\\(\\[[- X]\\]\\)[ \t]+"))
498 (defun org-at-item-counter-p ()
499 "Is point at a line starting a plain-list item with a counter?"
500 (and (org-at-item-p)
501 (looking-at org-list-full-item-re)
502 (match-string 2)))
506 ;;; Structures and helper functions
508 (defun org-list-context ()
509 "Determine context, and its boundaries, around point.
511 Context will be a cell like (MIN MAX CONTEXT) where MIN and MAX
512 are boundaries and CONTEXT is a symbol among `drawer', `block',
513 `invalid', `inlinetask' and nil.
515 Contexts `block' and `invalid' refer to `org-list-forbidden-blocks'."
516 (save-match-data
517 (save-excursion
518 (org-with-limited-levels
519 (beginning-of-line)
520 (let ((case-fold-search t) (pos (point)) beg end context-type
521 ;; Get positions of surrounding headings. This is the
522 ;; default context.
523 (lim-up (or (save-excursion (and (ignore-errors (org-back-to-heading t))
524 (point)))
525 (point-min)))
526 (lim-down (or (save-excursion (outline-next-heading)) (point-max))))
527 ;; Is point inside a drawer?
528 (let ((end-re "^[ \t]*:END:")
529 ;; Can't use org-drawers-regexp as this function might
530 ;; be called in buffers not in Org mode.
531 (beg-re (concat "^[ \t]*:\\("
532 (mapconcat 'regexp-quote org-drawers "\\|")
533 "\\):[ \t]*$")))
534 (when (save-excursion
535 (and (not (looking-at beg-re))
536 (not (looking-at end-re))
537 (setq beg (and (re-search-backward beg-re lim-up t)
538 (1+ (point-at-eol))))
539 (setq end (or (and (re-search-forward end-re lim-down t)
540 (1- (match-beginning 0)))
541 lim-down))
542 (>= end pos)))
543 (setq lim-up beg lim-down end context-type 'drawer)))
544 ;; Is point strictly in a block, and of which type?
545 (let ((block-re "^[ \t]*#\\+\\(begin\\|end\\)_") type)
546 (when (save-excursion
547 (and (not (looking-at block-re))
548 (setq beg (and (re-search-backward block-re lim-up t)
549 (1+ (point-at-eol))))
550 (looking-at "^[ \t]*#\\+begin_\\(\\S-+\\)")
551 (setq type (downcase (match-string 1)))
552 (goto-char beg)
553 (setq end (or (and (re-search-forward block-re lim-down t)
554 (1- (point-at-bol)))
555 lim-down))
556 (>= end pos)
557 (equal (downcase (match-string 1)) "end")))
558 (setq lim-up beg lim-down end
559 context-type (if (member type org-list-forbidden-blocks)
560 'invalid 'block))))
561 ;; Is point in an inlinetask?
562 (when (and (featurep 'org-inlinetask)
563 (save-excursion
564 (let* ((beg-re (org-inlinetask-outline-regexp))
565 (end-re (concat beg-re "END[ \t]*$")))
566 (and (not (looking-at "^\\*+"))
567 (setq beg (and (re-search-backward beg-re lim-up t)
568 (1+ (point-at-eol))))
569 (not (looking-at end-re))
570 (setq end (and (re-search-forward end-re lim-down t)
571 (1- (match-beginning 0))))
572 (> (point) pos)))))
573 (setq lim-up beg lim-down end context-type 'inlinetask))
574 ;; Return context boundaries and type.
575 (list lim-up lim-down context-type))))))
577 (defun org-list-struct ()
578 "Return structure of list at point.
580 A list structure is an alist where key is point at item, and
581 values are:
582 1. indentation,
583 2. bullet with trailing whitespace,
584 3. bullet counter, if any,
585 4. checkbox, if any,
586 5. description tag, if any,
587 6. position at item end.
589 Thus the following list, where numbers in parens are
590 point-at-bol:
592 - [X] first item (1)
593 1. sub-item 1 (18)
594 5. [@5] sub-item 2 (34)
595 some other text belonging to first item (55)
596 - last item (97)
597 + tag :: description (109)
598 (131)
600 will get the following structure:
602 \(\(1 0 \"- \" nil \"[X]\" nil 97\)
603 \(18 2 \"1. \" nil nil nil 34\)
604 \(34 2 \"5. \" \"5\" nil nil 55\)
605 \(97 0 \"- \" nil nil nil 131\)
606 \(109 2 \"+ \" nil nil \"tag\" 131\)
608 Assume point is at an item."
609 (save-excursion
610 (beginning-of-line)
611 (let* ((case-fold-search t)
612 (context (org-list-context))
613 (lim-up (car context))
614 (lim-down (nth 1 context))
615 (text-min-ind 10000)
616 (item-re (org-item-re))
617 (drawers-re (concat "^[ \t]*:\\("
618 (mapconcat 'regexp-quote org-drawers "\\|")
619 "\\):[ \t]*$"))
620 (inlinetask-re (and (featurep 'org-inlinetask)
621 (org-inlinetask-outline-regexp)))
622 (beg-cell (cons (point) (org-get-indentation)))
623 ind itm-lst itm-lst-2 end-lst end-lst-2 struct
624 (assoc-at-point
625 (function
626 ;; Return association at point.
627 (lambda (ind)
628 (looking-at org-list-full-item-re)
629 (list (point)
631 (match-string-no-properties 1) ; bullet
632 (match-string-no-properties 2) ; counter
633 (match-string-no-properties 3) ; checkbox
634 (match-string-no-properties 4))))) ; description tag
635 (end-before-blank
636 (function
637 ;; Ensure list ends at the first blank line.
638 (lambda ()
639 (skip-chars-backward " \r\t\n")
640 (min (1+ (point-at-eol)) lim-down)))))
641 ;; 1. Read list from starting item to its beginning, and save
642 ;; top item position and indentation in BEG-CELL. Also store
643 ;; ending position of items in END-LST.
644 (save-excursion
645 (catch 'exit
646 (while t
647 (let ((ind (+ (or (get-text-property (point) 'original-indentation) 0)
648 (org-get-indentation))))
649 (cond
650 ((<= (point) lim-up)
651 ;; At upward limit: if we ended at an item, store it,
652 ;; else dismiss useless data recorded above BEG-CELL.
653 ;; Jump to part 2.
654 (throw 'exit
655 (setq itm-lst
656 (if (or (not (looking-at item-re))
657 (get-text-property (point) 'org-example))
658 (memq (assq (car beg-cell) itm-lst) itm-lst)
659 (setq beg-cell (cons (point) ind))
660 (cons (funcall assoc-at-point ind) itm-lst)))))
661 ;; At a verbatim block, go before its beginning. Move
662 ;; from eol to ensure `previous-single-property-change'
663 ;; will return a value.
664 ((get-text-property (point) 'org-example)
665 (goto-char (previous-single-property-change
666 (point-at-eol) 'org-example nil lim-up))
667 (forward-line -1))
668 ;; Looking at a list ending regexp. Dismiss useless
669 ;; data recorded above BEG-CELL. Jump to part 2.
670 ((looking-at org-list-end-re)
671 (throw 'exit
672 (setq itm-lst
673 (memq (assq (car beg-cell) itm-lst) itm-lst))))
674 ;; Point is at an item. Add data to ITM-LST. It may
675 ;; also end a previous item: save it in END-LST. If
676 ;; ind is less or equal than BEG-CELL and there is no
677 ;; end at this ind or lesser, this item becomes the new
678 ;; BEG-CELL.
679 ((looking-at item-re)
680 (push (funcall assoc-at-point ind) itm-lst)
681 (push (cons ind (point)) end-lst)
682 (when (< ind text-min-ind) (setq beg-cell (cons (point) ind)))
683 (forward-line -1))
684 ;; Skip blocks, drawers, inline tasks, blank lines.
685 ((and (looking-at "^[ \t]*#\\+end_")
686 (re-search-backward "^[ \t]*#\\+begin_" lim-up t)))
687 ((and (looking-at "^[ \t]*:END:")
688 (re-search-backward drawers-re lim-up t))
689 (beginning-of-line))
690 ((and inlinetask-re (looking-at inlinetask-re))
691 (org-inlinetask-goto-beginning)
692 (forward-line -1))
693 ((looking-at "^[ \t]*$")
694 (forward-line -1))
695 ;; From there, point is not at an item. Interpret
696 ;; line's indentation:
697 ;; - text at column 0 is necessarily out of any list.
698 ;; Dismiss data recorded above BEG-CELL. Jump to
699 ;; part 2.
700 ;; - any other case may be an ending position for an
701 ;; hypothetical item above. Store it and proceed.
702 ((zerop ind)
703 (throw 'exit
704 (setq itm-lst
705 (memq (assq (car beg-cell) itm-lst) itm-lst))))
707 (when (< ind text-min-ind) (setq text-min-ind ind))
708 (push (cons ind (point)) end-lst)
709 (forward-line -1)))))))
710 ;; 2. Read list from starting point to its end, that is until we
711 ;; get out of context, or that a non-item line is less or
712 ;; equally indented than BEG-CELL's cdr. Also, store ending
713 ;; position of items in END-LST-2.
714 (catch 'exit
715 (while t
716 (let ((ind (+ (or (get-text-property (point) 'original-indentation) 0)
717 (org-get-indentation))))
718 (cond
719 ((>= (point) lim-down)
720 ;; At downward limit: this is de facto the end of the
721 ;; list. Save point as an ending position, and jump to
722 ;; part 3.
723 (throw 'exit
724 (push (cons 0 (funcall end-before-blank)) end-lst-2)))
725 ;; At a verbatim block, move to its end. Point is at bol
726 ;; and 'org-example property is set by whole lines:
727 ;; `next-single-property-change' always return a value.
728 ((get-text-property (point) 'org-example)
729 (goto-char
730 (next-single-property-change (point) 'org-example nil lim-down)))
731 ;; Looking at a list ending regexp. Save point as an
732 ;; ending position and jump to part 3.
733 ((looking-at org-list-end-re)
734 (throw 'exit (push (cons 0 (point)) end-lst-2)))
735 ((looking-at item-re)
736 ;; Point is at an item. Add data to ITM-LST-2. It may
737 ;; also end a previous item, so save it in END-LST-2.
738 (push (funcall assoc-at-point ind) itm-lst-2)
739 (push (cons ind (point)) end-lst-2)
740 (forward-line 1))
741 ;; Skip inline tasks and blank lines along the way
742 ((and inlinetask-re (looking-at inlinetask-re))
743 (org-inlinetask-goto-end))
744 ((looking-at "^[ \t]*$")
745 (forward-line 1))
746 ;; Ind is lesser or equal than BEG-CELL's. The list is
747 ;; over: store point as an ending position and jump to
748 ;; part 3.
749 ((<= ind (cdr beg-cell))
750 (throw 'exit
751 (push (cons 0 (funcall end-before-blank)) end-lst-2)))
752 ;; Else, if ind is lesser or equal than previous item's,
753 ;; this is an ending position: store it. In any case,
754 ;; skip block or drawer at point, and move to next line.
756 (when (<= ind (nth 1 (car itm-lst-2)))
757 (push (cons ind (point)) end-lst-2))
758 (cond
759 ((and (looking-at "^[ \t]*#\\+begin_")
760 (re-search-forward "^[ \t]*#\\+end_" lim-down t)))
761 ((and (looking-at drawers-re)
762 (re-search-forward "^[ \t]*:END:" lim-down t))))
763 (forward-line 1))))))
764 (setq struct (append itm-lst (cdr (nreverse itm-lst-2)))
765 end-lst (append end-lst (cdr (nreverse end-lst-2))))
766 ;; 3. Associate each item to its end position.
767 (org-list-struct-assoc-end struct end-lst)
768 ;; 4. Return STRUCT
769 struct)))
771 (defun org-list-struct-assoc-end (struct end-list)
772 "Associate proper ending point to items in STRUCT.
774 END-LIST is a pseudo-alist where car is indentation and cdr is
775 ending position.
777 This function modifies STRUCT."
778 (let ((endings end-list))
779 (mapc
780 (lambda (elt)
781 (let ((pos (car elt))
782 (ind (nth 1 elt)))
783 ;; Remove end candidates behind current item.
784 (while (or (<= (cdar endings) pos))
785 (pop endings))
786 ;; Add end position to item assoc.
787 (let ((old-end (nthcdr 6 elt))
788 (new-end (assoc-default ind endings '<=)))
789 (if old-end
790 (setcar old-end new-end)
791 (setcdr elt (append (cdr elt) (list new-end)))))))
792 struct)))
794 (defun org-list-prevs-alist (struct)
795 "Return alist between item and previous item in STRUCT."
796 (let ((item-end-alist (mapcar (lambda (e) (cons (car e) (nth 6 e)))
797 struct)))
798 (mapcar (lambda (e)
799 (let ((prev (car (rassq (car e) item-end-alist))))
800 (cons (car e) prev)))
801 struct)))
803 (defun org-list-parents-alist (struct)
804 "Return alist between item and parent in STRUCT."
805 (let* ((ind-to-ori (list (list (nth 1 (car struct)))))
806 (top-item (org-list-get-top-point struct))
807 (prev-pos (list top-item)))
808 (cons prev-pos
809 (mapcar (lambda (item)
810 (let ((pos (car item))
811 (ind (nth 1 item))
812 (prev-ind (caar ind-to-ori)))
813 (push pos prev-pos)
814 (cond
815 ((> prev-ind ind)
816 ;; A sub-list is over. Find the associated
817 ;; origin in IND-TO-ORI. If it cannot be
818 ;; found (ill-formed list), set its parent as
819 ;; the first item less indented. If there is
820 ;; none, make it a top-level item.
821 (setq ind-to-ori
822 (or (member (assq ind ind-to-ori) ind-to-ori)
823 (catch 'exit
824 (mapc
825 (lambda (e)
826 (when (< (car e) ind)
827 (throw 'exit (member e ind-to-ori))))
828 ind-to-ori)
829 (list (list ind)))))
830 (cons pos (cdar ind-to-ori)))
831 ;; A sub-list starts. Every item at IND will
832 ;; have previous item as its parent.
833 ((< prev-ind ind)
834 (let ((origin (nth 1 prev-pos)))
835 (push (cons ind origin) ind-to-ori)
836 (cons pos origin)))
837 ;; Another item in the same sub-list: it shares
838 ;; the same parent as the previous item.
839 (t (cons pos (cdar ind-to-ori))))))
840 (cdr struct)))))
844 ;;; Accessors
846 (defsubst org-list-get-nth (n key struct)
847 "Return the Nth value of KEY in STRUCT."
848 (nth n (assq key struct)))
850 (defun org-list-set-nth (n key struct new)
851 "Set the Nth value of KEY in STRUCT to NEW.
852 \nThis function modifies STRUCT."
853 (setcar (nthcdr n (assq key struct)) new))
855 (defsubst org-list-get-ind (item struct)
856 "Return indentation of ITEM in STRUCT."
857 (org-list-get-nth 1 item struct))
859 (defun org-list-set-ind (item struct ind)
860 "Set indentation of ITEM in STRUCT to IND.
861 \nThis function modifies STRUCT."
862 (org-list-set-nth 1 item struct ind))
864 (defsubst org-list-get-bullet (item struct)
865 "Return bullet of ITEM in STRUCT."
866 (org-list-get-nth 2 item struct))
868 (defun org-list-set-bullet (item struct bullet)
869 "Set bullet of ITEM in STRUCT to BULLET.
870 \nThis function modifies STRUCT."
871 (org-list-set-nth 2 item struct bullet))
873 (defsubst org-list-get-counter (item struct)
874 "Return counter of ITEM in STRUCT."
875 (org-list-get-nth 3 item struct))
877 (defsubst org-list-get-checkbox (item struct)
878 "Return checkbox of ITEM in STRUCT or nil."
879 (org-list-get-nth 4 item struct))
881 (defun org-list-set-checkbox (item struct checkbox)
882 "Set checkbox of ITEM in STRUCT to CHECKBOX.
883 \nThis function modifies STRUCT."
884 (org-list-set-nth 4 item struct checkbox))
886 (defsubst org-list-get-tag (item struct)
887 "Return end position of ITEM in STRUCT."
888 (org-list-get-nth 5 item struct))
890 (defun org-list-get-item-end (item struct)
891 "Return end position of ITEM in STRUCT."
892 (org-list-get-nth 6 item struct))
894 (defun org-list-get-item-end-before-blank (item struct)
895 "Return point at end of ITEM in STRUCT, before any blank line.
896 Point returned is at end of line."
897 (save-excursion
898 (goto-char (org-list-get-item-end item struct))
899 (skip-chars-backward " \r\t\n")
900 (point-at-eol)))
902 (defun org-list-get-parent (item struct parents)
903 "Return parent of ITEM or nil.
904 STRUCT is the list structure. PARENTS is the alist of parents,
905 as returned by `org-list-parents-alist'."
906 (let ((parents (or parents (org-list-parents-alist struct))))
907 (cdr (assq item parents))))
909 (defun org-list-has-child-p (item struct)
910 "Non-nil if ITEM has a child.
912 STRUCT is the list structure.
914 Value returned is the position of the first child of ITEM."
915 (let ((ind (org-list-get-ind item struct))
916 (child-maybe (car (nth 1 (member (assq item struct) struct)))))
917 (when (and child-maybe
918 (< ind (org-list-get-ind child-maybe struct)))
919 child-maybe)))
921 (defun org-list-get-next-item (item struct prevs)
922 "Return next item in same sub-list as ITEM, or nil.
923 STRUCT is the list structure. PREVS is the alist of previous
924 items, as returned by `org-list-prevs-alist'."
925 (car (rassq item prevs)))
927 (defun org-list-get-prev-item (item struct prevs)
928 "Return previous item in same sub-list as ITEM, or nil.
929 STRUCT is the list structure. PREVS is the alist of previous
930 items, as returned by `org-list-prevs-alist'."
931 (cdr (assq item prevs)))
933 (defun org-list-get-subtree (item struct)
934 "List all items having ITEM as a common ancestor, or nil.
935 STRUCT is the list structure."
936 (let* ((item-end (org-list-get-item-end item struct))
937 (sub-struct (cdr (member (assq item struct) struct)))
938 subtree)
939 (catch 'exit
940 (mapc (lambda (e)
941 (let ((pos (car e)))
942 (if (< pos item-end) (push pos subtree) (throw 'exit nil))))
943 sub-struct))
944 (nreverse subtree)))
946 (defun org-list-get-all-items (item struct prevs)
947 "List all items in the same sub-list as ITEM.
948 STRUCT is the list structure. PREVS is the alist of previous
949 items, as returned by `org-list-prevs-alist'."
950 (let ((prev-item item)
951 (next-item item)
952 before-item after-item)
953 (while (setq prev-item (org-list-get-prev-item prev-item struct prevs))
954 (push prev-item before-item))
955 (while (setq next-item (org-list-get-next-item next-item struct prevs))
956 (push next-item after-item))
957 (append before-item (list item) (nreverse after-item))))
959 (defun org-list-get-children (item struct parents)
960 "List all children of ITEM, or nil.
961 STRUCT is the list structure. PARENTS is the alist of parents,
962 as returned by `org-list-parents-alist'."
963 (let (all child)
964 (while (setq child (car (rassq item parents)))
965 (setq parents (cdr (member (assq child parents) parents)))
966 (push child all))
967 (nreverse all)))
969 (defun org-list-get-top-point (struct)
970 "Return point at beginning of list.
971 STRUCT is the list structure."
972 (caar struct))
974 (defun org-list-get-bottom-point (struct)
975 "Return point at bottom of list.
976 STRUCT is the list structure."
977 (apply 'max
978 (mapcar (lambda (e) (org-list-get-item-end (car e) struct)) struct)))
980 (defun org-list-get-list-begin (item struct prevs)
981 "Return point at beginning of sub-list ITEM belongs.
982 STRUCT is the list structure. PREVS is the alist of previous
983 items, as returned by `org-list-prevs-alist'."
984 (let ((first-item item) prev-item)
985 (while (setq prev-item (org-list-get-prev-item first-item struct prevs))
986 (setq first-item prev-item))
987 first-item))
989 (defalias 'org-list-get-first-item 'org-list-get-list-begin)
991 (defun org-list-get-last-item (item struct prevs)
992 "Return point at last item of sub-list ITEM belongs.
993 STRUCT is the list structure. PREVS is the alist of previous
994 items, as returned by `org-list-prevs-alist'."
995 (let ((last-item item) next-item)
996 (while (setq next-item (org-list-get-next-item last-item struct prevs))
997 (setq last-item next-item))
998 last-item))
1000 (defun org-list-get-list-end (item struct prevs)
1001 "Return point at end of sub-list ITEM belongs.
1002 STRUCT is the list structure. PREVS is the alist of previous
1003 items, as returned by `org-list-prevs-alist'."
1004 (org-list-get-item-end (org-list-get-last-item item struct prevs) struct))
1006 (defun org-list-get-list-type (item struct prevs)
1007 "Return the type of the list containing ITEM, as a symbol.
1009 STRUCT is the list structure. PREVS is the alist of previous
1010 items, as returned by `org-list-prevs-alist'.
1012 Possible types are `descriptive', `ordered' and `unordered'. The
1013 type is determined by the first item of the list."
1014 (let ((first (org-list-get-list-begin item struct prevs)))
1015 (cond
1016 ((org-list-get-tag first struct) 'descriptive)
1017 ((string-match "[[:alnum:]]" (org-list-get-bullet first struct)) 'ordered)
1018 (t 'unordered))))
1020 (defun org-list-get-item-number (item struct prevs parents)
1021 "Return ITEM's sequence number.
1023 STRUCT is the list structure. PREVS is the alist of previous
1024 items, as returned by `org-list-prevs-alist'. PARENTS is the
1025 alist of ancestors, as returned by `org-list-parents-alist'.
1027 Return value is a list of integers. Counters have an impact on
1028 that value."
1029 (let ((get-relative-number
1030 (function
1031 (lambda (item struct prevs)
1032 ;; Return relative sequence number of ITEM in the sub-list
1033 ;; it belongs. STRUCT is the list structure. PREVS is
1034 ;; the alist of previous items.
1035 (let ((seq 0) (pos item) counter)
1036 (while (and (not (setq counter (org-list-get-counter pos struct)))
1037 (setq pos (org-list-get-prev-item pos struct prevs)))
1038 (incf seq))
1039 (if (not counter) (1+ seq)
1040 (cond
1041 ((string-match "[A-Za-z]" counter)
1042 (+ (- (string-to-char (upcase (match-string 0 counter))) 64)
1043 seq))
1044 ((string-match "[0-9]+" counter)
1045 (+ (string-to-number (match-string 0 counter)) seq))
1046 (t (1+ seq)))))))))
1047 ;; Cons each parent relative number into return value (OUT).
1048 (let ((out (list (funcall get-relative-number item struct prevs)))
1049 (parent item))
1050 (while (setq parent (org-list-get-parent parent struct parents))
1051 (push (funcall get-relative-number parent struct prevs) out))
1052 ;; Return value.
1053 out)))
1057 ;;; Searching
1059 (defun org-list-search-generic (search re bound noerr)
1060 "Search a string in valid contexts for lists.
1061 Arguments SEARCH, RE, BOUND and NOERR are similar to those used
1062 in `re-search-forward'."
1063 (catch 'exit
1064 (let ((origin (point)))
1065 (while t
1066 ;; 1. No match: return to origin or bound, depending on NOERR.
1067 (unless (funcall search re bound noerr)
1068 (throw 'exit (and (goto-char (if (memq noerr '(t nil)) origin bound))
1069 nil)))
1070 ;; 2. Match in valid context: return point. Else, continue
1071 ;; searching.
1072 (when (org-list-in-valid-context-p) (throw 'exit (point)))))))
1074 (defun org-list-search-backward (regexp &optional bound noerror)
1075 "Like `re-search-backward' but stop only where lists are recognized.
1076 Arguments REGEXP, BOUND and NOERROR are similar to those used in
1077 `re-search-backward'."
1078 (org-list-search-generic #'re-search-backward
1079 regexp (or bound (point-min)) noerror))
1081 (defun org-list-search-forward (regexp &optional bound noerror)
1082 "Like `re-search-forward' but stop only where lists are recognized.
1083 Arguments REGEXP, BOUND and NOERROR are similar to those used in
1084 `re-search-forward'."
1085 (org-list-search-generic #'re-search-forward
1086 regexp (or bound (point-max)) noerror))
1090 ;;; Methods on structures
1092 (defsubst org-list-bullet-string (bullet)
1093 "Return BULLET with the correct number of whitespaces.
1094 It determines the number of whitespaces to append by looking at
1095 `org-list-two-spaces-after-bullet-regexp'."
1096 (save-match-data
1097 (let ((spaces (if (and org-list-two-spaces-after-bullet-regexp
1098 (string-match
1099 org-list-two-spaces-after-bullet-regexp bullet))
1101 " ")))
1102 (string-match "\\S-+\\([ \t]*\\)" bullet)
1103 (replace-match spaces nil nil bullet 1))))
1105 (defun org-list-swap-items (beg-A beg-B struct)
1106 "Swap item starting at BEG-A with item starting at BEG-B in STRUCT.
1108 Blank lines at the end of items are left in place. Item
1109 visibility is preserved. Return the new structure after the
1110 changes.
1112 Assume BEG-A is lesser than BEG-B and that BEG-A and BEG-B belong
1113 to the same sub-list.
1115 This function modifies STRUCT."
1116 (save-excursion
1117 (let* ((end-A-no-blank (org-list-get-item-end-before-blank beg-A struct))
1118 (end-B-no-blank (org-list-get-item-end-before-blank beg-B struct))
1119 (end-A (org-list-get-item-end beg-A struct))
1120 (end-B (org-list-get-item-end beg-B struct))
1121 (size-A (- end-A-no-blank beg-A))
1122 (size-B (- end-B-no-blank beg-B))
1123 (body-A (buffer-substring beg-A end-A-no-blank))
1124 (body-B (buffer-substring beg-B end-B-no-blank))
1125 (between-A-no-blank-and-B (buffer-substring end-A-no-blank beg-B))
1126 (sub-A (cons beg-A (org-list-get-subtree beg-A struct)))
1127 (sub-B (cons beg-B (org-list-get-subtree beg-B struct)))
1128 ;; Store overlays responsible for visibility status. We
1129 ;; also need to store their boundaries as they will be
1130 ;; removed from buffer.
1131 (overlays (cons
1132 (mapcar (lambda (ov)
1133 (list ov (overlay-start ov) (overlay-end ov)))
1134 (overlays-in beg-A end-A))
1135 (mapcar (lambda (ov)
1136 (list ov (overlay-start ov) (overlay-end ov)))
1137 (overlays-in beg-B end-B)))))
1138 ;; 1. Move effectively items in buffer.
1139 (goto-char beg-A)
1140 (delete-region beg-A end-B-no-blank)
1141 (insert (concat body-B between-A-no-blank-and-B body-A))
1142 ;; 2. Now modify struct. No need to re-read the list, the
1143 ;; transformation is just a shift of positions. Some special
1144 ;; attention is required for items ending at END-A and END-B
1145 ;; as empty spaces are not moved there. In others words,
1146 ;; item BEG-A will end with whitespaces that were at the end
1147 ;; of BEG-B and the same applies to BEG-B.
1148 (mapc (lambda (e)
1149 (let ((pos (car e)))
1150 (cond
1151 ((< pos beg-A))
1152 ((memq pos sub-A)
1153 (let ((end-e (nth 6 e)))
1154 (setcar e (+ pos (- end-B-no-blank end-A-no-blank)))
1155 (setcar (nthcdr 6 e)
1156 (+ end-e (- end-B-no-blank end-A-no-blank)))
1157 (when (= end-e end-A) (setcar (nthcdr 6 e) end-B))))
1158 ((memq pos sub-B)
1159 (let ((end-e (nth 6 e)))
1160 (setcar e (- (+ pos beg-A) beg-B))
1161 (setcar (nthcdr 6 e) (+ end-e (- beg-A beg-B)))
1162 (when (= end-e end-B)
1163 (setcar (nthcdr 6 e)
1164 (+ beg-A size-B (- end-A end-A-no-blank))))))
1165 ((< pos beg-B)
1166 (let ((end-e (nth 6 e)))
1167 (setcar e (+ pos (- size-B size-A)))
1168 (setcar (nthcdr 6 e) (+ end-e (- size-B size-A))))))))
1169 struct)
1170 (setq struct (sort struct (lambda (e1 e2) (< (car e1) (car e2)))))
1171 ;; Restore visibility status, by moving overlays to their new
1172 ;; position.
1173 (mapc (lambda (ov)
1174 (move-overlay
1175 (car ov)
1176 (+ (nth 1 ov) (- (+ beg-B (- size-B size-A)) beg-A))
1177 (+ (nth 2 ov) (- (+ beg-B (- size-B size-A)) beg-A))))
1178 (car overlays))
1179 (mapc (lambda (ov)
1180 (move-overlay (car ov)
1181 (+ (nth 1 ov) (- beg-A beg-B))
1182 (+ (nth 2 ov) (- beg-A beg-B))))
1183 (cdr overlays))
1184 ;; Return structure.
1185 struct)))
1187 (defun org-list-separating-blank-lines-number (pos struct prevs)
1188 "Return number of blank lines that should separate items in list.
1190 POS is the position of point where `org-list-insert-item' was called.
1192 STRUCT is the list structure. PREVS is the alist of previous
1193 items, as returned by `org-list-prevs-alist'.
1195 Assume point is at item's beginning. If the item is alone, apply
1196 some heuristics to guess the result."
1197 (save-excursion
1198 (let ((item (point))
1199 (insert-blank-p
1200 (cdr (assq 'plain-list-item org-blank-before-new-entry)))
1201 usr-blank
1202 (count-blanks
1203 (function
1204 (lambda ()
1205 ;; Count blank lines above beginning of line.
1206 (save-excursion
1207 (count-lines (goto-char (point-at-bol))
1208 (progn (skip-chars-backward " \r\t\n")
1209 (forward-line)
1210 (point))))))))
1211 (cond
1212 ;; Trivial cases where there should be none.
1213 ((or org-empty-line-terminates-plain-lists (not insert-blank-p)) 0)
1214 ;; When `org-blank-before-new-entry' says so, it is 1.
1215 ((eq insert-blank-p t) 1)
1216 ;; `plain-list-item' is 'auto. Count blank lines separating
1217 ;; neighbours items in list.
1218 (t (let ((next-p (org-list-get-next-item item struct prevs)))
1219 (cond
1220 ;; Is there a next item?
1221 (next-p (goto-char next-p)
1222 (funcall count-blanks))
1223 ;; Is there a previous item?
1224 ((org-list-get-prev-item item struct prevs)
1225 (funcall count-blanks))
1226 ;; User inserted blank lines, trust him.
1227 ((and (> pos (org-list-get-item-end-before-blank item struct))
1228 (> (save-excursion (goto-char pos)
1229 (setq usr-blank (funcall count-blanks)))
1231 usr-blank)
1232 ;; Are there blank lines inside the list so far?
1233 ((save-excursion
1234 (goto-char (org-list-get-top-point struct))
1235 (org-list-search-forward
1236 "^[ \t]*$" (org-list-get-item-end-before-blank item struct) t))
1238 ;; Default choice: no blank line.
1239 (t 0))))))))
1241 (defun org-list-insert-item (pos struct prevs &optional checkbox after-bullet)
1242 "Insert a new list item at POS and return the new structure.
1243 If POS is before first character after bullet of the item, the
1244 new item will be created before the current one.
1246 STRUCT is the list structure. PREVS is the the alist of previous
1247 items, as returned by `org-list-prevs-alist'.
1249 Insert a checkbox if CHECKBOX is non-nil, and string AFTER-BULLET
1250 after the bullet. Cursor will be after this text once the
1251 function ends.
1253 This function modifies STRUCT."
1254 (let ((case-fold-search t))
1255 ;; 1. Get information about list: position of point with regards
1256 ;; to item start (BEFOREP), blank lines number separating items
1257 ;; (BLANK-NB), if we're allowed to (SPLIT-LINE-P).
1258 (let* ((item (progn (goto-char pos) (goto-char (org-list-get-item-begin))))
1259 (item-end (org-list-get-item-end item struct))
1260 (item-end-no-blank (org-list-get-item-end-before-blank item struct))
1261 (beforep (and (looking-at org-list-full-item-re)
1262 (<= pos (match-end 0))))
1263 (split-line-p (org-get-alist-option org-M-RET-may-split-line 'item))
1264 (blank-nb (org-list-separating-blank-lines-number
1265 pos struct prevs))
1266 ;; 2. Build the new item to be created. Concatenate same
1267 ;; bullet as item, checkbox, text AFTER-BULLET if
1268 ;; provided, and text cut from point to end of item
1269 ;; (TEXT-CUT) to form item's BODY. TEXT-CUT depends on
1270 ;; BEFOREP and SPLIT-LINE-P. The difference of size
1271 ;; between what was cut and what was inserted in buffer
1272 ;; is stored in SIZE-OFFSET.
1273 (ind (org-list-get-ind item struct))
1274 (ind-size (if indent-tabs-mode
1275 (+ (/ ind tab-width) (mod ind tab-width))
1276 ind))
1277 (bullet (org-list-bullet-string (org-list-get-bullet item struct)))
1278 (box (when checkbox "[ ]"))
1279 (text-cut
1280 (and (not beforep) split-line-p
1281 (progn
1282 (goto-char pos)
1283 ;; If POS is greater than ITEM-END, then point is
1284 ;; in some white lines after the end of the list.
1285 ;; Those must be removed, or they will be left,
1286 ;; stacking up after the list.
1287 (when (< item-end pos)
1288 (delete-region (1- item-end) (point-at-eol)))
1289 (skip-chars-backward " \r\t\n")
1290 (setq pos (point))
1291 (delete-and-extract-region pos item-end-no-blank))))
1292 (body (concat bullet (when box (concat box " ")) after-bullet
1293 (and text-cut
1294 (if (string-match "\\`[ \t]+" text-cut)
1295 (replace-match "" t t text-cut)
1296 text-cut))))
1297 (item-sep (make-string (1+ blank-nb) ?\n))
1298 (item-size (+ ind-size (length body) (length item-sep)))
1299 (size-offset (- item-size (length text-cut))))
1300 ;; 4. Insert effectively item into buffer.
1301 (goto-char item)
1302 (org-indent-to-column ind)
1303 (insert body item-sep)
1304 ;; 5. Add new item to STRUCT.
1305 (mapc (lambda (e)
1306 (let ((p (car e)) (end (nth 6 e)))
1307 (cond
1308 ;; Before inserted item, positions don't change but
1309 ;; an item ending after insertion has its end shifted
1310 ;; by SIZE-OFFSET.
1311 ((< p item)
1312 (when (> end item) (setcar (nthcdr 6 e) (+ end size-offset))))
1313 ;; Trivial cases where current item isn't split in
1314 ;; two. Just shift every item after new one by
1315 ;; ITEM-SIZE.
1316 ((or beforep (not split-line-p))
1317 (setcar e (+ p item-size))
1318 (setcar (nthcdr 6 e) (+ end item-size)))
1319 ;; Item is split in two: elements before POS are just
1320 ;; shifted by ITEM-SIZE. In the case item would end
1321 ;; after split POS, ending is only shifted by
1322 ;; SIZE-OFFSET.
1323 ((< p pos)
1324 (setcar e (+ p item-size))
1325 (if (< end pos)
1326 (setcar (nthcdr 6 e) (+ end item-size))
1327 (setcar (nthcdr 6 e) (+ end size-offset))))
1328 ;; Elements after POS are moved into new item.
1329 ;; Length of ITEM-SEP has to be removed as ITEM-SEP
1330 ;; doesn't appear in buffer yet.
1331 ((< p item-end)
1332 (setcar e (+ p size-offset (- item pos (length item-sep))))
1333 (if (= end item-end)
1334 (setcar (nthcdr 6 e) (+ item item-size))
1335 (setcar (nthcdr 6 e)
1336 (+ end size-offset
1337 (- item pos (length item-sep))))))
1338 ;; Elements at ITEM-END or after are only shifted by
1339 ;; SIZE-OFFSET.
1340 (t (setcar e (+ p size-offset))
1341 (setcar (nthcdr 6 e) (+ end size-offset))))))
1342 struct)
1343 (push (list item ind bullet nil box nil (+ item item-size)) struct)
1344 (setq struct (sort struct (lambda (e1 e2) (< (car e1) (car e2)))))
1345 ;; 6. If not BEFOREP, new item must appear after ITEM, so
1346 ;; exchange ITEM with the next item in list. Position cursor
1347 ;; after bullet, counter, checkbox, and label.
1348 (if beforep
1349 (goto-char item)
1350 (setq struct (org-list-swap-items item (+ item item-size) struct))
1351 (goto-char (org-list-get-next-item
1352 item struct (org-list-prevs-alist struct))))
1353 struct)))
1355 (defun org-list-delete-item (item struct)
1356 "Remove ITEM from the list and return the new structure.
1358 STRUCT is the list structure."
1359 (let* ((end (org-list-get-item-end item struct))
1360 (beg (if (= (org-list-get-bottom-point struct) end)
1361 ;; If ITEM ends with the list, delete blank lines
1362 ;; before it.
1363 (save-excursion
1364 (goto-char item)
1365 (skip-chars-backward " \r\t\n")
1366 (min (1+ (point-at-eol)) (point-max)))
1367 item)))
1368 ;; Remove item from buffer.
1369 (delete-region beg end)
1370 ;; Remove item from structure and shift others items accordingly.
1371 ;; Don't forget to shift also ending position when appropriate.
1372 (let ((size (- end beg)))
1373 (delq nil (mapcar (lambda (e)
1374 (let ((pos (car e)))
1375 (cond
1376 ((< pos item)
1377 (let ((end-e (nth 6 e)))
1378 (cond
1379 ((< end-e item) e)
1380 ((= end-e item)
1381 (append (butlast e) (list beg)))
1383 (append (butlast e) (list (- end-e size)))))))
1384 ((< pos end) nil)
1386 (cons (- pos size)
1387 (append (butlast (cdr e))
1388 (list (- (nth 6 e) size))))))))
1389 struct)))))
1391 (defun org-list-send-item (item dest struct)
1392 "Send ITEM to destination DEST.
1394 STRUCT is the list structure.
1396 DEST can have various values.
1398 If DEST is a buffer position, the function will assume it points
1399 to another item in the same list as ITEM, and will move the
1400 latter just before the former.
1402 If DEST is `begin' (respectively `end'), ITEM will be moved at
1403 the beginning (respectively end) of the list it belongs to.
1405 If DEST is a string like \"N\", where N is an integer, ITEM will
1406 be moved at the Nth position in the list.
1408 If DEST is `kill', ITEM will be deleted and its body will be
1409 added to the kill-ring.
1411 If DEST is `delete', ITEM will be deleted.
1413 Visibility of item is preserved.
1415 This function returns, destructively, the new list structure."
1416 (let* ((prevs (org-list-prevs-alist struct))
1417 (item-end (org-list-get-item-end item struct))
1418 ;; Grab full item body minus its bullet.
1419 (body (org-trim
1420 (buffer-substring
1421 (save-excursion
1422 (goto-char item)
1423 (looking-at
1424 (concat "[ \t]*"
1425 (regexp-quote (org-list-get-bullet item struct))))
1426 (match-end 0))
1427 item-end)))
1428 ;; Change DEST into a buffer position. A trick is needed
1429 ;; when ITEM is meant to be sent at the end of the list.
1430 ;; Indeed, by setting locally `org-M-RET-may-split-line' to
1431 ;; nil and insertion point (INS-POINT) to the first line's
1432 ;; end of the last item, we ensure the new item will be
1433 ;; inserted after the last item, and not after any of its
1434 ;; hypothetical sub-items.
1435 (ins-point (cond
1436 ((or (eq dest 'kill) (eq dest 'delete)))
1437 ((eq dest 'begin)
1438 (setq dest (org-list-get-list-begin item struct prevs)))
1439 ((eq dest 'end)
1440 (setq dest (org-list-get-list-end item struct prevs))
1441 (save-excursion
1442 (goto-char (org-list-get-last-item item struct prevs))
1443 (point-at-eol)))
1444 ((string-match "\\`[0-9]+\\'" dest)
1445 (let* ((all (org-list-get-all-items item struct prevs))
1446 (len (length all))
1447 (index (mod (string-to-number dest) len)))
1448 (if (not (zerop index))
1449 (setq dest (nth (1- index) all))
1450 ;; Send ITEM at the end of the list.
1451 (setq dest (org-list-get-list-end item struct prevs))
1452 (save-excursion
1453 (goto-char
1454 (org-list-get-last-item item struct prevs))
1455 (point-at-eol)))))
1456 (t dest)))
1457 (org-M-RET-may-split-line nil)
1458 ;; Store visibility.
1459 (visibility (overlays-in item item-end)))
1460 (cond
1461 ((eq dest 'delete) (org-list-delete-item item struct))
1462 ((eq dest 'kill)
1463 (kill-new body)
1464 (org-list-delete-item item struct))
1465 ((and (integerp dest) (/= item ins-point))
1466 (setq item (copy-marker item))
1467 (setq struct (org-list-insert-item ins-point struct prevs nil body))
1468 ;; 1. Structure returned by `org-list-insert-item' may not be
1469 ;; accurate, as it cannot see sub-items included in BODY.
1470 ;; Thus, first compute the real structure so far.
1471 (let ((moved-items
1472 (cons (marker-position item)
1473 (org-list-get-subtree (marker-position item) struct)))
1474 (new-end (org-list-get-item-end (point) struct))
1475 (old-end (org-list-get-item-end (marker-position item) struct))
1476 (new-item (point))
1477 (shift (- (point) item)))
1478 ;; 1.1. Remove the item just created in structure.
1479 (setq struct (delete (assq new-item struct) struct))
1480 ;; 1.2. Copy ITEM and any of its sub-items at NEW-ITEM.
1481 (setq struct (sort
1482 (append
1483 struct
1484 (mapcar (lambda (e)
1485 (let* ((cell (assq e struct))
1486 (pos (car cell))
1487 (end (nth 6 cell)))
1488 (cons (+ pos shift)
1489 (append (butlast (cdr cell))
1490 (list (if (= end old-end)
1491 new-end
1492 (+ end shift)))))))
1493 moved-items))
1494 (lambda (e1 e2) (< (car e1) (car e2))))))
1495 ;; 2. Restore visibility.
1496 (mapc (lambda (ov)
1497 (move-overlay ov
1498 (+ (overlay-start ov) (- (point) item))
1499 (+ (overlay-end ov) (- (point) item))))
1500 visibility)
1501 ;; 3. Eventually delete extra copy of the item and clean marker.
1502 (prog1 (org-list-delete-item (marker-position item) struct)
1503 (move-marker item nil)))
1504 (t struct))))
1506 (defun org-list-struct-outdent (start end struct parents)
1507 "Outdent items between positions START and END.
1509 STRUCT is the list structure. PARENTS is the alist of items'
1510 parents, as returned by `org-list-parents-alist'.
1512 START is included, END excluded."
1513 (let* (acc
1514 (out (lambda (cell)
1515 (let* ((item (car cell))
1516 (parent (cdr cell)))
1517 (cond
1518 ;; Item not yet in zone: keep association.
1519 ((< item start) cell)
1520 ;; Item out of zone: follow associations in ACC.
1521 ((>= item end)
1522 (let ((convert (and parent (assq parent acc))))
1523 (if convert (cons item (cdr convert)) cell)))
1524 ;; Item has no parent: error
1525 ((not parent)
1526 (error "Cannot outdent top-level items"))
1527 ;; Parent is outdented: keep association.
1528 ((>= parent start)
1529 (push (cons parent item) acc) cell)
1531 ;; Parent isn't outdented: reparent to grand-parent.
1532 (let ((grand-parent (org-list-get-parent
1533 parent struct parents)))
1534 (push (cons parent item) acc)
1535 (cons item grand-parent))))))))
1536 (mapcar out parents)))
1538 (defun org-list-struct-indent (start end struct parents prevs)
1539 "Indent items between positions START and END.
1541 STRUCT is the list structure. PARENTS is the alist of parents
1542 and PREVS is the alist of previous items, returned by,
1543 respectively, `org-list-parents-alist' and
1544 `org-list-prevs-alist'.
1546 START is included and END excluded.
1548 STRUCT may be modified if `org-list-demote-modify-bullet' matches
1549 bullets between START and END."
1550 (let* (acc
1551 (set-assoc (lambda (cell) (push cell acc) cell))
1552 (change-bullet-maybe
1553 (function
1554 (lambda (item)
1555 (let ((new-bul-p
1556 (cdr (assoc
1557 ;; Normalize ordered bullets.
1558 (let ((bul (org-trim
1559 (org-list-get-bullet item struct))))
1560 (cond ((string-match "[A-Z]\\." bul) "A.")
1561 ((string-match "[A-Z])" bul) "A)")
1562 ((string-match "[a-z]\\." bul) "a.")
1563 ((string-match "[a-z])" bul) "a)")
1564 ((string-match "[0-9]\\." bul) "1.")
1565 ((string-match "[0-9])" bul) "1)")
1566 (t bul)))
1567 org-list-demote-modify-bullet))))
1568 (when new-bul-p (org-list-set-bullet item struct new-bul-p))))))
1569 (ind
1570 (lambda (cell)
1571 (let* ((item (car cell))
1572 (parent (cdr cell)))
1573 (cond
1574 ;; Item not yet in zone: keep association.
1575 ((< item start) cell)
1576 ((>= item end)
1577 ;; Item out of zone: follow associations in ACC.
1578 (let ((convert (assq parent acc)))
1579 (if convert (cons item (cdr convert)) cell)))
1581 ;; Item is in zone...
1582 (let ((prev (org-list-get-prev-item item struct prevs)))
1583 ;; Check if bullet needs to be changed.
1584 (funcall change-bullet-maybe item)
1585 (cond
1586 ;; First item indented but not parent: error
1587 ((and (not prev) (< parent start))
1588 (error "Cannot indent the first item of a list"))
1589 ;; First item and parent indented: keep same
1590 ;; parent.
1591 ((not prev) (funcall set-assoc cell))
1592 ;; Previous item not indented: reparent to it.
1593 ((< prev start) (funcall set-assoc (cons item prev)))
1594 ;; Previous item indented: reparent like it.
1596 (funcall set-assoc
1597 (cons item (cdr (assq prev acc)))))))))))))
1598 (mapcar ind parents)))
1602 ;;; Repairing structures
1604 (defun org-list-use-alpha-bul-p (first struct prevs)
1605 "Non-nil if list starting at FIRST can have alphabetical bullets.
1607 STRUCT is list structure. PREVS is the alist of previous items,
1608 as returned by `org-list-prevs-alist'."
1609 (and org-alphabetical-lists
1610 (catch 'exit
1611 (let ((item first) (ascii 64) (case-fold-search nil))
1612 ;; Pretend that bullets are uppercase and check if alphabet
1613 ;; is sufficient, taking counters into account.
1614 (while item
1615 (let ((bul (org-list-get-bullet item struct))
1616 (count (org-list-get-counter item struct)))
1617 ;; Virtually determine current bullet
1618 (if (and count (string-match "[a-zA-Z]" count))
1619 ;; Counters are not case-sensitive.
1620 (setq ascii (string-to-char (upcase count)))
1621 (setq ascii (1+ ascii)))
1622 ;; Test if bullet would be over z or Z.
1623 (if (> ascii 90)
1624 (throw 'exit nil)
1625 (setq item (org-list-get-next-item item struct prevs)))))
1626 ;; All items checked. All good.
1627 t))))
1629 (defun org-list-inc-bullet-maybe (bullet)
1630 "Increment BULLET if applicable."
1631 (let ((case-fold-search nil))
1632 (cond
1633 ;; Num bullet: increment it.
1634 ((string-match "[0-9]+" bullet)
1635 (replace-match
1636 (number-to-string (1+ (string-to-number (match-string 0 bullet))))
1637 nil nil bullet))
1638 ;; Alpha bullet: increment it.
1639 ((string-match "[A-Za-z]" bullet)
1640 (replace-match
1641 (char-to-string (1+ (string-to-char (match-string 0 bullet))))
1642 nil nil bullet))
1643 ;; Unordered bullet: leave it.
1644 (t bullet))))
1646 (defun org-list-struct-fix-bul (struct prevs)
1647 "Verify and correct bullets in STRUCT.
1648 PREVS is the alist of previous items, as returned by
1649 `org-list-prevs-alist'.
1651 This function modifies STRUCT."
1652 (let ((case-fold-search nil)
1653 (fix-bul
1654 (function
1655 ;; Set bullet of ITEM in STRUCT, depending on the type of
1656 ;; first item of the list, the previous bullet and counter
1657 ;; if any.
1658 (lambda (item)
1659 (let* ((prev (org-list-get-prev-item item struct prevs))
1660 (prev-bul (and prev (org-list-get-bullet prev struct)))
1661 (counter (org-list-get-counter item struct))
1662 (bullet (org-list-get-bullet item struct))
1663 (alphap (and (not prev)
1664 (org-list-use-alpha-bul-p item struct prevs))))
1665 (org-list-set-bullet
1666 item struct
1667 (org-list-bullet-string
1668 (cond
1669 ;; Alpha counter in alpha list: use counter.
1670 ((and prev counter
1671 (string-match "[a-zA-Z]" counter)
1672 (string-match "[a-zA-Z]" prev-bul))
1673 ;; Use cond to be sure `string-match' is used in
1674 ;; both cases.
1675 (let ((real-count
1676 (cond
1677 ((string-match "[a-z]" prev-bul) (downcase counter))
1678 ((string-match "[A-Z]" prev-bul) (upcase counter)))))
1679 (replace-match real-count nil nil prev-bul)))
1680 ;; Num counter in a num list: use counter.
1681 ((and prev counter
1682 (string-match "[0-9]+" counter)
1683 (string-match "[0-9]+" prev-bul))
1684 (replace-match counter nil nil prev-bul))
1685 ;; No counter: increase, if needed, previous bullet.
1686 (prev
1687 (org-list-inc-bullet-maybe (org-list-get-bullet prev struct)))
1688 ;; Alpha counter at first item: use counter.
1689 ((and counter (org-list-use-alpha-bul-p item struct prevs)
1690 (string-match "[A-Za-z]" counter)
1691 (string-match "[A-Za-z]" bullet))
1692 (let ((real-count
1693 (cond
1694 ((string-match "[a-z]" bullet) (downcase counter))
1695 ((string-match "[A-Z]" bullet) (upcase counter)))))
1696 (replace-match real-count nil nil bullet)))
1697 ;; Num counter at first item: use counter.
1698 ((and counter
1699 (string-match "[0-9]+" counter)
1700 (string-match "[0-9]+" bullet))
1701 (replace-match counter nil nil bullet))
1702 ;; First bullet is alpha uppercase: use "A".
1703 ((and alphap (string-match "[A-Z]" bullet))
1704 (replace-match "A" nil nil bullet))
1705 ;; First bullet is alpha lowercase: use "a".
1706 ((and alphap (string-match "[a-z]" bullet))
1707 (replace-match "a" nil nil bullet))
1708 ;; First bullet is num: use "1".
1709 ((string-match "\\([0-9]+\\|[A-Za-z]\\)" bullet)
1710 (replace-match "1" nil nil bullet))
1711 ;; Not an ordered list: keep bullet.
1712 (t bullet)))))))))
1713 (mapc fix-bul (mapcar 'car struct))))
1715 (defun org-list-struct-fix-ind (struct parents &optional bullet-size)
1716 "Verify and correct indentation in STRUCT.
1718 PARENTS is the alist of parents, as returned by
1719 `org-list-parents-alist'.
1721 If numeric optional argument BULLET-SIZE is set, assume all
1722 bullets in list have this length to determine new indentation.
1724 This function modifies STRUCT."
1725 (let* ((ancestor (org-list-get-top-point struct))
1726 (top-ind (org-list-get-ind ancestor struct))
1727 (new-ind
1728 (lambda (item)
1729 (let ((parent (org-list-get-parent item struct parents)))
1730 (if parent
1731 ;; Indent like parent + length of parent's bullet +
1732 ;; sub-list offset.
1733 (org-list-set-ind
1734 item struct (+ (or bullet-size
1735 (length
1736 (org-list-get-bullet parent struct)))
1737 (org-list-get-ind parent struct)
1738 org-list-indent-offset))
1739 ;; If no parent, indent like top-point.
1740 (org-list-set-ind item struct top-ind))))))
1741 (mapc new-ind (mapcar 'car (cdr struct)))))
1743 (defun org-list-struct-fix-box (struct parents prevs &optional ordered)
1744 "Verify and correct checkboxes in STRUCT.
1746 PARENTS is the alist of parents and PREVS is the alist of
1747 previous items, as returned by, respectively,
1748 `org-list-parents-alist' and `org-list-prevs-alist'.
1750 If ORDERED is non-nil, a checkbox can only be checked when every
1751 checkbox before it is checked too. If there was an attempt to
1752 break this rule, the function will return the blocking item. In
1753 all others cases, the return value will be nil.
1755 This function modifies STRUCT."
1756 (let ((all-items (mapcar 'car struct))
1757 (set-parent-box
1758 (function
1759 (lambda (item)
1760 (let* ((box-list
1761 (mapcar (lambda (child)
1762 (org-list-get-checkbox child struct))
1763 (org-list-get-children item struct parents))))
1764 (org-list-set-checkbox
1765 item struct
1766 (cond
1767 ((and (member "[ ]" box-list) (member "[X]" box-list)) "[-]")
1768 ((member "[-]" box-list) "[-]")
1769 ((member "[X]" box-list) "[X]")
1770 ((member "[ ]" box-list) "[ ]")
1771 ;; Parent has no boxed child: leave box as-is.
1772 (t (org-list-get-checkbox item struct))))))))
1773 parent-list)
1774 ;; 1. List all parents with a checkbox.
1775 (mapc
1776 (lambda (e)
1777 (let* ((parent (org-list-get-parent e struct parents))
1778 (parent-box-p (org-list-get-checkbox parent struct)))
1779 (when (and parent-box-p (not (memq parent parent-list)))
1780 (push parent parent-list))))
1781 all-items)
1782 ;; 2. Sort those parents by decreasing indentation.
1783 (setq parent-list (sort parent-list
1784 (lambda (e1 e2)
1785 (> (org-list-get-ind e1 struct)
1786 (org-list-get-ind e2 struct)))))
1787 ;; 3. For each parent, get all children's checkboxes to determine
1788 ;; and set its checkbox accordingly.
1789 (mapc set-parent-box parent-list)
1790 ;; 4. If ORDERED is set, see if we need to uncheck some boxes.
1791 (when ordered
1792 (let* ((box-list
1793 (mapcar (lambda (e) (org-list-get-checkbox e struct)) all-items))
1794 (after-unchecked (member "[ ]" box-list)))
1795 ;; There are boxes checked after an unchecked one: fix that.
1796 (when (member "[X]" after-unchecked)
1797 (let ((index (- (length struct) (length after-unchecked))))
1798 (mapc (lambda (e) (org-list-set-checkbox e struct "[ ]"))
1799 (nthcdr index all-items))
1800 ;; Verify once again the structure, without ORDERED.
1801 (org-list-struct-fix-box struct parents prevs nil)
1802 ;; Return blocking item.
1803 (nth index all-items)))))))
1805 (defun org-list-struct-fix-item-end (struct)
1806 "Verify and correct each item end position in STRUCT.
1808 This function modifies STRUCT."
1809 (let (end-list acc-end)
1810 (mapc (lambda (e)
1811 (let* ((pos (car e))
1812 (ind-pos (org-list-get-ind pos struct))
1813 (end-pos (org-list-get-item-end pos struct)))
1814 (unless (assq end-pos struct)
1815 ;; To determine real ind of an ending position that is
1816 ;; not at an item, we have to find the item it belongs
1817 ;; to: it is the last item (ITEM-UP), whose ending is
1818 ;; further than the position we're interested in.
1819 (let ((item-up (assoc-default end-pos acc-end '>)))
1820 (push (cons
1821 ;; Else part is for the bottom point.
1822 (if item-up (+ (org-list-get-ind item-up struct) 2) 0)
1823 end-pos)
1824 end-list)))
1825 (push (cons ind-pos pos) end-list)
1826 (push (cons end-pos pos) acc-end)))
1827 struct)
1828 (setq end-list (sort end-list (lambda (e1 e2) (< (cdr e1) (cdr e2)))))
1829 (org-list-struct-assoc-end struct end-list)))
1831 (defun org-list-struct-apply-struct (struct old-struct)
1832 "Apply set difference between STRUCT and OLD-STRUCT to the buffer.
1834 OLD-STRUCT is the structure before any modifications, and STRUCT
1835 the structure to be applied. The function will only modify parts
1836 of the list which have changed.
1838 Initial position of cursor is restored after the changes."
1839 (let* ((origin (point-marker))
1840 (inlinetask-re (and (featurep 'org-inlinetask)
1841 (org-inlinetask-outline-regexp)))
1842 (item-re (org-item-re))
1843 (shift-body-ind
1844 (function
1845 ;; Shift the indentation between END and BEG by DELTA.
1846 ;; Start from the line before END.
1847 (lambda (end beg delta)
1848 (goto-char end)
1849 (skip-chars-backward " \r\t\n")
1850 (beginning-of-line)
1851 (while (or (> (point) beg)
1852 (and (= (point) beg)
1853 (not (looking-at item-re))))
1854 (cond
1855 ;; Skip inline tasks.
1856 ((and inlinetask-re (looking-at inlinetask-re))
1857 (org-inlinetask-goto-beginning))
1858 ;; Shift only non-empty lines.
1859 ((org-looking-at-p "^[ \t]*\\S-")
1860 (let ((i (org-get-indentation)))
1861 (org-indent-line-to (+ i delta)))))
1862 (forward-line -1)))))
1863 (modify-item
1864 (function
1865 ;; Replace ITEM first line elements with new elements from
1866 ;; STRUCT, if appropriate.
1867 (lambda (item)
1868 (goto-char item)
1869 (let* ((new-ind (org-list-get-ind item struct))
1870 (old-ind (org-get-indentation))
1871 (new-bul (org-list-bullet-string
1872 (org-list-get-bullet item struct)))
1873 (old-bul (org-list-get-bullet item old-struct))
1874 (new-box (org-list-get-checkbox item struct)))
1875 (looking-at org-list-full-item-re)
1876 ;; a. Replace bullet
1877 (unless (equal old-bul new-bul)
1878 (replace-match new-bul nil nil nil 1))
1879 ;; b. Replace checkbox.
1880 (cond
1881 ((equal (match-string 3) new-box))
1882 ((and (match-string 3) new-box)
1883 (replace-match new-box nil nil nil 3))
1884 ((match-string 3)
1885 (looking-at ".*?\\([ \t]*\\[[ X-]\\]\\)")
1886 (replace-match "" nil nil nil 1))
1887 (t (let ((counterp (match-end 2)))
1888 (goto-char (if counterp (1+ counterp) (match-end 1)))
1889 (insert (concat new-box (unless counterp " "))))))
1890 ;; c. Indent item to appropriate column.
1891 (unless (= new-ind old-ind)
1892 (delete-region (goto-char (point-at-bol))
1893 (progn (skip-chars-forward " \t") (point)))
1894 (indent-to new-ind)))))))
1895 ;; 1. First get list of items and position endings. We maintain
1896 ;; two alists: ITM-SHIFT, determining indentation shift needed
1897 ;; at item, and END-POS, a pseudo-alist where key is ending
1898 ;; position and value point.
1899 (let (end-list acc-end itm-shift all-ends sliced-struct)
1900 (mapc (lambda (e)
1901 (let* ((pos (car e))
1902 (ind-pos (org-list-get-ind pos struct))
1903 (ind-old (org-list-get-ind pos old-struct))
1904 (bul-pos (org-list-get-bullet pos struct))
1905 (bul-old (org-list-get-bullet pos old-struct))
1906 (ind-shift (- (+ ind-pos (length bul-pos))
1907 (+ ind-old (length bul-old))))
1908 (end-pos (org-list-get-item-end pos old-struct)))
1909 (push (cons pos ind-shift) itm-shift)
1910 (unless (assq end-pos old-struct)
1911 ;; To determine real ind of an ending position that
1912 ;; is not at an item, we have to find the item it
1913 ;; belongs to: it is the last item (ITEM-UP), whose
1914 ;; ending is further than the position we're
1915 ;; interested in.
1916 (let ((item-up (assoc-default end-pos acc-end '>)))
1917 (push (cons end-pos item-up) end-list)))
1918 (push (cons end-pos pos) acc-end)))
1919 old-struct)
1920 ;; 2. Slice the items into parts that should be shifted by the
1921 ;; same amount of indentation. The slices are returned in
1922 ;; reverse order so changes modifying buffer do not change
1923 ;; positions they refer to.
1924 (setq all-ends (sort (append (mapcar 'car itm-shift)
1925 (org-uniquify (mapcar 'car end-list)))
1926 '<))
1927 (while (cdr all-ends)
1928 (let* ((up (pop all-ends))
1929 (down (car all-ends))
1930 (ind (if (assq up struct)
1931 (cdr (assq up itm-shift))
1932 (cdr (assq (cdr (assq up end-list)) itm-shift)))))
1933 (push (list down up ind) sliced-struct)))
1934 ;; 3. Shift each slice in buffer, provided delta isn't 0, from
1935 ;; end to beginning. Take a special action when beginning is
1936 ;; at item bullet.
1937 (mapc (lambda (e)
1938 (unless (zerop (nth 2 e)) (apply shift-body-ind e))
1939 (let* ((beg (nth 1 e))
1940 (cell (assq beg struct)))
1941 (unless (or (not cell) (equal cell (assq beg old-struct)))
1942 (funcall modify-item beg))))
1943 sliced-struct))
1944 ;; 4. Go back to initial position and clean marker.
1945 (goto-char origin)
1946 (move-marker origin nil)))
1948 (defun org-list-write-struct (struct parents &optional old-struct)
1949 "Correct bullets, checkboxes and indentation in list at point.
1951 STRUCT is the list structure. PARENTS is the alist of parents,
1952 as returned by `org-list-parents-alist'.
1954 When non-nil, optional argument OLD-STRUCT is the reference
1955 structure of the list. It should be provided whenever STRUCT
1956 doesn't correspond anymore to the real list in buffer."
1957 ;; Order of functions matters here: checkboxes and endings need
1958 ;; correct indentation to be set, and indentation needs correct
1959 ;; bullets.
1961 ;; 0. Save a copy of structure before modifications
1962 (let ((old-struct (or old-struct (copy-tree struct))))
1963 ;; 1. Set a temporary, but coherent with PARENTS, indentation in
1964 ;; order to get items endings and bullets properly
1965 (org-list-struct-fix-ind struct parents 2)
1966 ;; 2. Fix each item end to get correct prevs alist.
1967 (org-list-struct-fix-item-end struct)
1968 ;; 3. Get bullets right.
1969 (let ((prevs (org-list-prevs-alist struct)))
1970 (org-list-struct-fix-bul struct prevs)
1971 ;; 4. Now get real indentation.
1972 (org-list-struct-fix-ind struct parents)
1973 ;; 5. Eventually fix checkboxes.
1974 (org-list-struct-fix-box struct parents prevs))
1975 ;; 6. Apply structure modifications to buffer.
1976 (org-list-struct-apply-struct struct old-struct)))
1980 ;;; Misc Tools
1982 (defun org-apply-on-list (function init-value &rest args)
1983 "Call FUNCTION on each item of the list at point.
1984 FUNCTION must be called with at least one argument: INIT-VALUE,
1985 that will contain the value returned by the function at the
1986 previous item, plus ARGS extra arguments.
1988 FUNCTION is applied on items in reverse order.
1990 As an example, \(org-apply-on-list \(lambda \(result\) \(1+ result\)\) 0\)
1991 will return the number of items in the current list.
1993 Sublists of the list are skipped. Cursor is always at the
1994 beginning of the item."
1995 (let* ((struct (org-list-struct))
1996 (prevs (org-list-prevs-alist struct))
1997 (item (copy-marker (point-at-bol)))
1998 (all (org-list-get-all-items (marker-position item) struct prevs))
1999 (value init-value))
2000 (mapc (lambda (e)
2001 (goto-char e)
2002 (setq value (apply function value args)))
2003 (nreverse all))
2004 (goto-char item)
2005 (move-marker item nil)
2006 value))
2008 (defun org-list-set-item-visibility (item struct view)
2009 "Set visibility of ITEM in STRUCT to VIEW.
2011 Possible values are: `folded', `children' or `subtree'. See
2012 `org-cycle' for more information."
2013 (cond
2014 ((eq view 'folded)
2015 (let ((item-end (org-list-get-item-end-before-blank item struct)))
2016 ;; Hide from eol
2017 (outline-flag-region (save-excursion (goto-char item) (point-at-eol))
2018 item-end t)))
2019 ((eq view 'children)
2020 ;; First show everything.
2021 (org-list-set-item-visibility item struct 'subtree)
2022 ;; Then fold every child.
2023 (let* ((parents (org-list-parents-alist struct))
2024 (children (org-list-get-children item struct parents)))
2025 (mapc (lambda (e)
2026 (org-list-set-item-visibility e struct 'folded))
2027 children)))
2028 ((eq view 'subtree)
2029 ;; Show everything
2030 (let ((item-end (org-list-get-item-end item struct)))
2031 (outline-flag-region item item-end nil)))))
2033 (defun org-list-item-body-column (item)
2034 "Return column at which body of ITEM should start."
2035 (let (bpos bcol tpos tcol)
2036 (save-excursion
2037 (goto-char item)
2038 (looking-at "[ \t]*\\(\\S-+\\)\\(.*[ \t]+::\\)?\\([ \t]+\\|$\\)")
2039 (setq bpos (match-beginning 1) tpos (match-end 0)
2040 bcol (progn (goto-char bpos) (current-column))
2041 tcol (progn (goto-char tpos) (current-column)))
2042 (when (> tcol (+ bcol org-description-max-indent))
2043 (setq tcol (+ bcol 5))))
2044 tcol))
2048 ;;; Interactive functions
2050 (defalias 'org-list-get-item-begin 'org-in-item-p)
2052 (defun org-beginning-of-item ()
2053 "Go to the beginning of the current item.
2054 Throw an error when not in a list."
2055 (interactive)
2056 (let ((begin (org-in-item-p)))
2057 (if begin (goto-char begin) (error "Not in an item"))))
2059 (defun org-beginning-of-item-list ()
2060 "Go to the beginning item of the current list or sublist.
2061 Throw an error when not in a list."
2062 (interactive)
2063 (let ((begin (org-in-item-p)))
2064 (if (not begin)
2065 (error "Not in an item")
2066 (goto-char begin)
2067 (let* ((struct (org-list-struct))
2068 (prevs (org-list-prevs-alist struct)))
2069 (goto-char (org-list-get-list-begin begin struct prevs))))))
2071 (defun org-end-of-item-list ()
2072 "Go to the end of the current list or sublist.
2073 Throw an error when not in a list."
2074 (interactive)
2075 (let ((begin (org-in-item-p)))
2076 (if (not begin)
2077 (error "Not in an item")
2078 (goto-char begin)
2079 (let* ((struct (org-list-struct))
2080 (prevs (org-list-prevs-alist struct)))
2081 (goto-char (org-list-get-list-end begin struct prevs))))))
2083 (defun org-end-of-item ()
2084 "Go to the end of the current item.
2085 Throw an error when not in a list."
2086 (interactive)
2087 (let ((begin (org-in-item-p)))
2088 (if (not begin)
2089 (error "Not in an item")
2090 (goto-char begin)
2091 (let ((struct (org-list-struct)))
2092 (goto-char (org-list-get-item-end begin struct))))))
2094 (defun org-previous-item ()
2095 "Move to the beginning of the previous item.
2096 Throw an error when not in a list. Also throw an error when at
2097 first item, unless `org-list-use-circular-motion' is non-nil."
2098 (interactive)
2099 (let ((item (org-in-item-p)))
2100 (if (not item)
2101 (error "Not in an item")
2102 (goto-char item)
2103 (let* ((struct (org-list-struct))
2104 (prevs (org-list-prevs-alist struct))
2105 (prevp (org-list-get-prev-item item struct prevs)))
2106 (cond
2107 (prevp (goto-char prevp))
2108 (org-list-use-circular-motion
2109 (goto-char (org-list-get-last-item item struct prevs)))
2110 (t (error "On first item")))))))
2112 (defun org-next-item ()
2113 "Move to the beginning of the next item.
2114 Throw an error when not in a list. Also throw an error when at
2115 last item, unless `org-list-use-circular-motion' is non-nil."
2116 (interactive)
2117 (let ((item (org-in-item-p)))
2118 (if (not item)
2119 (error "Not in an item")
2120 (goto-char item)
2121 (let* ((struct (org-list-struct))
2122 (prevs (org-list-prevs-alist struct))
2123 (prevp (org-list-get-next-item item struct prevs)))
2124 (cond
2125 (prevp (goto-char prevp))
2126 (org-list-use-circular-motion
2127 (goto-char (org-list-get-first-item item struct prevs)))
2128 (t (error "On last item")))))))
2130 (defun org-move-item-down ()
2131 "Move the item at point down, i.e. swap with following item.
2132 Sub-items (items with larger indentation) are considered part of
2133 the item, so this really moves item trees."
2134 (interactive)
2135 (unless (org-at-item-p) (error "Not at an item"))
2136 (let* ((col (current-column))
2137 (item (point-at-bol))
2138 (struct (org-list-struct))
2139 (prevs (org-list-prevs-alist struct))
2140 (next-item (org-list-get-next-item (point-at-bol) struct prevs)))
2141 (unless (or next-item org-list-use-circular-motion)
2142 (error "Cannot move this item further down"))
2143 (if (not next-item)
2144 (setq struct (org-list-send-item item 'begin struct))
2145 (setq struct (org-list-swap-items item next-item struct))
2146 (goto-char
2147 (org-list-get-next-item item struct (org-list-prevs-alist struct))))
2148 (org-list-write-struct struct (org-list-parents-alist struct))
2149 (org-move-to-column col)))
2151 (defun org-move-item-up ()
2152 "Move the item at point up, i.e. swap with previous item.
2153 Sub-items (items with larger indentation) are considered part of
2154 the item, so this really moves item trees."
2155 (interactive)
2156 (unless (org-at-item-p) (error "Not at an item"))
2157 (let* ((col (current-column))
2158 (item (point-at-bol))
2159 (struct (org-list-struct))
2160 (prevs (org-list-prevs-alist struct))
2161 (prev-item (org-list-get-prev-item (point-at-bol) struct prevs)))
2162 (unless (or prev-item org-list-use-circular-motion)
2163 (error "Cannot move this item further up"))
2164 (if (not prev-item)
2165 (setq struct (org-list-send-item item 'end struct))
2166 (setq struct (org-list-swap-items prev-item item struct)))
2167 (org-list-write-struct struct (org-list-parents-alist struct))
2168 (org-move-to-column col)))
2170 (defun org-insert-item (&optional checkbox)
2171 "Insert a new item at the current level.
2172 If cursor is before first character after bullet of the item, the
2173 new item will be created before the current one.
2175 If CHECKBOX is non-nil, add a checkbox next to the bullet.
2177 Return t when things worked, nil when we are not in an item, or
2178 item is invisible."
2179 (let ((itemp (org-in-item-p))
2180 (pos (point)))
2181 ;; If cursor isn't is a list or if list is invisible, return nil.
2182 (unless (or (not itemp)
2183 (save-excursion
2184 (goto-char itemp)
2185 (outline-invisible-p)))
2186 (if (save-excursion
2187 (goto-char itemp)
2188 (org-at-item-timer-p))
2189 ;; Timer list: delegate to `org-timer-item'.
2190 (progn (org-timer-item) t)
2191 (let* ((struct (save-excursion (goto-char itemp)
2192 (org-list-struct)))
2193 (prevs (org-list-prevs-alist struct))
2194 ;; If we're in a description list, ask for the new term.
2195 (desc (when (org-list-get-tag itemp struct)
2196 (concat (read-string "Term: ") " :: "))))
2197 (setq struct
2198 (org-list-insert-item pos struct prevs checkbox desc))
2199 (org-list-write-struct struct (org-list-parents-alist struct))
2200 (when checkbox (org-update-checkbox-count-maybe))
2201 (looking-at org-list-full-item-re)
2202 (goto-char (match-end 0))
2203 t)))))
2205 (defun org-mark-list ()
2206 "Mark the current list.
2207 If this is a sublist, only mark the sublist."
2208 (interactive)
2209 (if (not (org-at-item-p))
2210 (error "Not on a list")
2211 (let* ((item (org-list-get-item-begin))
2212 (struct (org-list-struct))
2213 (prevs (org-list-prevs-alist struct))
2214 (lbeg (org-list-get-list-begin item struct prevs))
2215 (lend (org-list-get-list-end item struct prevs)))
2216 (push-mark lend nil t)
2217 (goto-char lbeg))))
2219 (defun org-list-repair ()
2220 "Fix indentation, bullets and checkboxes is the list at point."
2221 (interactive)
2222 (unless (org-at-item-p) (error "This is not a list"))
2223 (let* ((struct (org-list-struct))
2224 (parents (org-list-parents-alist struct)))
2225 (org-list-write-struct struct parents)))
2227 (defun org-cycle-list-bullet (&optional which)
2228 "Cycle through the different itemize/enumerate bullets.
2229 This cycle the entire list level through the sequence:
2231 `-' -> `+' -> `*' -> `1.' -> `1)'
2233 If WHICH is a valid string, use that as the new bullet. If WHICH
2234 is an integer, 0 means `-', 1 means `+' etc. If WHICH is
2235 `previous', cycle backwards."
2236 (interactive "P")
2237 (unless (org-at-item-p) (error "Not at an item"))
2238 (save-excursion
2239 (beginning-of-line)
2240 (let* ((struct (org-list-struct))
2241 (parents (org-list-parents-alist struct))
2242 (prevs (org-list-prevs-alist struct))
2243 (list-beg (org-list-get-first-item (point) struct prevs))
2244 (bullet (org-list-get-bullet list-beg struct))
2245 (bullet-rule-p (cdr (assq 'bullet org-list-automatic-rules)))
2246 (alpha-p (org-list-use-alpha-bul-p list-beg struct prevs))
2247 (case-fold-search nil)
2248 (current (cond
2249 ((string-match "[a-z]\\." bullet) "a.")
2250 ((string-match "[a-z])" bullet) "a)")
2251 ((string-match "[A-Z]\\." bullet) "A.")
2252 ((string-match "[A-Z])" bullet) "A)")
2253 ((string-match "\\." bullet) "1.")
2254 ((string-match ")" bullet) "1)")
2255 (t (org-trim bullet))))
2256 ;; Compute list of possible bullets, depending on context.
2257 (bullet-list
2258 (append '("-" "+" )
2259 ;; *-bullets are not allowed at column 0.
2260 (unless (and bullet-rule-p
2261 (looking-at "\\S-")) '("*"))
2262 ;; Description items cannot be numbered.
2263 (unless (or (eq org-plain-list-ordered-item-terminator ?\))
2264 (and bullet-rule-p (org-at-item-description-p)))
2265 '("1."))
2266 (unless (or (eq org-plain-list-ordered-item-terminator ?.)
2267 (and bullet-rule-p (org-at-item-description-p)))
2268 '("1)"))
2269 (unless (or (not alpha-p)
2270 (eq org-plain-list-ordered-item-terminator ?\))
2271 (and bullet-rule-p (org-at-item-description-p)))
2272 '("a." "A."))
2273 (unless (or (not alpha-p)
2274 (eq org-plain-list-ordered-item-terminator ?.)
2275 (and bullet-rule-p (org-at-item-description-p)))
2276 '("a)" "A)"))))
2277 (len (length bullet-list))
2278 (item-index (- len (length (member current bullet-list))))
2279 (get-value (lambda (index) (nth (mod index len) bullet-list)))
2280 (new (cond
2281 ((member which bullet-list) which)
2282 ((numberp which) (funcall get-value which))
2283 ((eq 'previous which) (funcall get-value (1- item-index)))
2284 (t (funcall get-value (1+ item-index))))))
2285 ;; Use a short variation of `org-list-write-struct' as there's
2286 ;; no need to go through all the steps.
2287 (let ((old-struct (copy-tree struct)))
2288 (org-list-set-bullet list-beg struct (org-list-bullet-string new))
2289 (org-list-struct-fix-bul struct prevs)
2290 (org-list-struct-fix-ind struct parents)
2291 (org-list-struct-apply-struct struct old-struct)))))
2293 (defun org-toggle-checkbox (&optional toggle-presence)
2294 "Toggle the checkbox in the current line.
2295 With prefix arg TOGGLE-PRESENCE, add or remove checkboxes. With
2296 double prefix, set checkbox to [-].
2298 When there is an active region, toggle status or presence of the
2299 first checkbox there, and make every item inside have the same
2300 status or presence, respectively.
2302 If the cursor is in a headline, apply this to all checkbox items
2303 in the text below the heading, taking as reference the first item
2304 in subtree, ignoring drawers."
2305 (interactive "P")
2306 (save-excursion
2307 (let* (singlep
2308 block-item
2309 lim-up
2310 lim-down
2311 (drawer-re (concat "^[ \t]*:\\("
2312 (mapconcat 'regexp-quote org-drawers "\\|")
2313 "\\):[ \t]*$"))
2314 (keyword-re (concat "^[ \t]*\\<\\(" org-scheduled-string
2315 "\\|" org-deadline-string
2316 "\\|" org-closed-string
2317 "\\|" org-clock-string "\\)"
2318 " *[[<]\\([^]>]+\\)[]>]"))
2319 (orderedp (org-entry-get nil "ORDERED"))
2320 (bounds
2321 ;; In a region, start at first item in region.
2322 (cond
2323 ((org-region-active-p)
2324 (let ((limit (region-end)))
2325 (goto-char (region-beginning))
2326 (if (org-list-search-forward (org-item-beginning-re) limit t)
2327 (setq lim-up (point-at-bol))
2328 (error "No item in region"))
2329 (setq lim-down (copy-marker limit))))
2330 ((org-at-heading-p)
2331 ;; On an heading, start at first item after drawers and
2332 ;; time-stamps (scheduled, etc.).
2333 (let ((limit (save-excursion (outline-next-heading) (point))))
2334 (forward-line 1)
2335 (while (or (looking-at drawer-re) (looking-at keyword-re))
2336 (if (looking-at keyword-re)
2337 (forward-line 1)
2338 (re-search-forward "^[ \t]*:END:" limit nil)))
2339 (if (org-list-search-forward (org-item-beginning-re) limit t)
2340 (setq lim-up (point-at-bol))
2341 (error "No item in subtree"))
2342 (setq lim-down (copy-marker limit))))
2343 ;; Just one item: set SINGLEP flag.
2344 ((org-at-item-p)
2345 (setq singlep t)
2346 (setq lim-up (point-at-bol)
2347 lim-down (copy-marker (point-at-eol))))
2348 (t (error "Not at an item or heading, and no active region"))))
2349 ;; Determine the checkbox going to be applied to all items
2350 ;; within bounds.
2351 (ref-checkbox
2352 (progn
2353 (goto-char lim-up)
2354 (let ((cbox (and (org-at-item-checkbox-p) (match-string 1))))
2355 (cond
2356 ((equal toggle-presence '(16)) "[-]")
2357 ((equal toggle-presence '(4))
2358 (unless cbox "[ ]"))
2359 ((equal "[X]" cbox) "[ ]")
2360 (t "[X]"))))))
2361 ;; When an item is found within bounds, grab the full list at
2362 ;; point structure, then: (1) set check-box of all its items
2363 ;; within bounds to REF-CHECKBOX, (2) fix check-boxes of the
2364 ;; whole list, (3) move point after the list.
2365 (goto-char lim-up)
2366 (while (and (< (point) lim-down)
2367 (org-list-search-forward (org-item-beginning-re)
2368 lim-down 'move))
2369 (let* ((struct (org-list-struct))
2370 (struct-copy (copy-tree struct))
2371 (parents (org-list-parents-alist struct))
2372 (prevs (org-list-prevs-alist struct))
2373 (bottom (copy-marker (org-list-get-bottom-point struct)))
2374 (items-to-toggle (org-remove-if
2375 (lambda (e) (or (< e lim-up) (> e lim-down)))
2376 (mapcar 'car struct))))
2377 (mapc (lambda (e) (org-list-set-checkbox
2378 e struct
2379 ;; If there is no box at item, leave as-is
2380 ;; unless function was called with C-u prefix.
2381 (let ((cur-box (org-list-get-checkbox e struct)))
2382 (if (or cur-box (equal toggle-presence '(4)))
2383 ref-checkbox
2384 cur-box))))
2385 items-to-toggle)
2386 (setq block-item (org-list-struct-fix-box
2387 struct parents prevs orderedp))
2388 ;; Report some problems due to ORDERED status of subtree.
2389 ;; If only one box was being checked, throw an error, else,
2390 ;; only signal problems.
2391 (cond
2392 ((and singlep block-item (> lim-up block-item))
2393 (error
2394 "Checkbox blocked because of unchecked box at line %d"
2395 (org-current-line block-item)))
2396 (block-item
2397 (message
2398 "Checkboxes were removed due to unchecked box at line %d"
2399 (org-current-line block-item))))
2400 (goto-char bottom)
2401 (move-marker bottom nil)
2402 (org-list-struct-apply-struct struct struct-copy)))
2403 (move-marker lim-down nil)))
2404 (org-update-checkbox-count-maybe))
2406 (defun org-reset-checkbox-state-subtree ()
2407 "Reset all checkboxes in an entry subtree."
2408 (interactive "*")
2409 (if (org-before-first-heading-p)
2410 (error "Not inside a tree")
2411 (save-restriction
2412 (save-excursion
2413 (org-narrow-to-subtree)
2414 (org-show-subtree)
2415 (goto-char (point-min))
2416 (let ((end (point-max)))
2417 (while (< (point) end)
2418 (when (org-at-item-checkbox-p)
2419 (replace-match "[ ]" t t nil 1))
2420 (beginning-of-line 2)))
2421 (org-update-checkbox-count-maybe 'all)))))
2423 (defun org-update-checkbox-count (&optional all)
2424 "Update the checkbox statistics in the current section.
2425 This will find all statistic cookies like [57%] and [6/12] and
2426 update them with the current numbers.
2428 With optional prefix argument ALL, do this for the whole buffer."
2429 (interactive "P")
2430 (save-excursion
2431 (let ((cookie-re "\\(\\(\\[[0-9]*%\\]\\)\\|\\(\\[[0-9]*/[0-9]*\\]\\)\\)")
2432 (box-re "^[ \t]*\\([-+*]\\|\\([0-9]+\\|[A-Za-z]\\)[.)]\\)[ \t]+\\(?:\\[@\\(?:start:\\)?\\([0-9]+\\|[A-Za-z]\\)\\][ \t]*\\)?\\(\\[[- X]\\]\\)")
2433 (recursivep
2434 (or (not org-hierarchical-checkbox-statistics)
2435 (string-match "\\<recursive\\>"
2436 (or (org-entry-get nil "COOKIE_DATA") ""))))
2437 (bounds (if all
2438 (cons (point-min) (point-max))
2439 (cons (or (ignore-errors (org-back-to-heading t) (point))
2440 (point-min))
2441 (save-excursion (outline-next-heading) (point)))))
2442 (count-boxes
2443 (function
2444 ;; Return number of checked boxes and boxes of all types
2445 ;; in all structures in STRUCTS. If RECURSIVEP is
2446 ;; non-nil, also count boxes in sub-lists. If ITEM is
2447 ;; nil, count across the whole structure, else count only
2448 ;; across subtree whose ancestor is ITEM.
2449 (lambda (item structs recursivep)
2450 (let ((c-on 0) (c-all 0))
2451 (mapc
2452 (lambda (s)
2453 (let* ((pre (org-list-prevs-alist s))
2454 (par (org-list-parents-alist s))
2455 (items
2456 (cond
2457 ((and recursivep item) (org-list-get-subtree item s))
2458 (recursivep (mapcar 'car s))
2459 (item (org-list-get-children item s par))
2460 (t (org-list-get-all-items
2461 (org-list-get-top-point s) s pre))))
2462 (cookies (delq nil (mapcar
2463 (lambda (e)
2464 (org-list-get-checkbox e s))
2465 items))))
2466 (setq c-all (+ (length cookies) c-all)
2467 c-on (+ (org-count "[X]" cookies) c-on))))
2468 structs)
2469 (cons c-on c-all)))))
2470 (backup-end 1)
2471 cookies-list structs-bak box-num)
2472 (goto-char (car bounds))
2473 ;; 1. Build an alist for each cookie found within BOUNDS. The
2474 ;; key will be position at beginning of cookie and values
2475 ;; ending position, format of cookie, and a cell whose car is
2476 ;; number of checked boxes to report, and cdr total number of
2477 ;; boxes.
2478 (while (re-search-forward cookie-re (cdr bounds) t)
2479 (catch 'skip
2480 (save-excursion
2481 (push
2482 (list
2483 (match-beginning 1) ; cookie start
2484 (match-end 1) ; cookie end
2485 (match-string 2) ; percent?
2486 (cond ; boxes count
2487 ;; Cookie is at an heading, but specifically for todo,
2488 ;; not for checkboxes: skip it.
2489 ((and (org-at-heading-p)
2490 (string-match "\\<todo\\>"
2491 (downcase
2492 (or (org-entry-get nil "COOKIE_DATA") ""))))
2493 (throw 'skip nil))
2494 ;; Cookie is at an heading, but all lists before next
2495 ;; heading already have been read. Use data collected
2496 ;; in STRUCTS-BAK. This should only happen when
2497 ;; heading has more than one cookie on it.
2498 ((and (org-at-heading-p)
2499 (<= (save-excursion (outline-next-heading) (point))
2500 backup-end))
2501 (funcall count-boxes nil structs-bak recursivep))
2502 ;; Cookie is at a fresh heading. Grab structure of
2503 ;; every list containing a checkbox between point and
2504 ;; next headline, and save them in STRUCTS-BAK.
2505 ((org-at-heading-p)
2506 (setq backup-end (save-excursion
2507 (outline-next-heading) (point))
2508 structs-bak nil)
2509 (while (org-list-search-forward box-re backup-end 'move)
2510 (let* ((struct (org-list-struct))
2511 (bottom (org-list-get-bottom-point struct)))
2512 (push struct structs-bak)
2513 (goto-char bottom)))
2514 (funcall count-boxes nil structs-bak recursivep))
2515 ;; Cookie is at an item, and we already have list
2516 ;; structure stored in STRUCTS-BAK.
2517 ((and (org-at-item-p)
2518 (< (point-at-bol) backup-end)
2519 ;; Only lists in no special context are stored.
2520 (not (nth 2 (org-list-context))))
2521 (funcall count-boxes (point-at-bol) structs-bak recursivep))
2522 ;; Cookie is at an item, but we need to compute list
2523 ;; structure.
2524 ((org-at-item-p)
2525 (let ((struct (org-list-struct)))
2526 (setq backup-end (org-list-get-bottom-point struct)
2527 structs-bak (list struct)))
2528 (funcall count-boxes (point-at-bol) structs-bak recursivep))
2529 ;; Else, cookie found is at a wrong place. Skip it.
2530 (t (throw 'skip nil))))
2531 cookies-list))))
2532 ;; 2. Apply alist to buffer, in reverse order so positions stay
2533 ;; unchanged after cookie modifications.
2534 (mapc (lambda (cookie)
2535 (let* ((beg (car cookie))
2536 (end (nth 1 cookie))
2537 (percentp (nth 2 cookie))
2538 (checked (car (nth 3 cookie)))
2539 (total (cdr (nth 3 cookie)))
2540 (new (if percentp
2541 (format "[%d%%]" (/ (* 100 checked)
2542 (max 1 total)))
2543 (format "[%d/%d]" checked total))))
2544 (goto-char beg)
2545 (insert new)
2546 (delete-region (point) (+ (point) (- end beg)))
2547 (when org-auto-align-tags (org-fix-tags-on-the-fly))))
2548 cookies-list))))
2550 (defun org-get-checkbox-statistics-face ()
2551 "Select the face for checkbox statistics.
2552 The face will be `org-done' when all relevant boxes are checked.
2553 Otherwise it will be `org-todo'."
2554 (if (match-end 1)
2555 (if (equal (match-string 1) "100%")
2556 'org-checkbox-statistics-done
2557 'org-checkbox-statistics-todo)
2558 (if (and (> (match-end 2) (match-beginning 2))
2559 (equal (match-string 2) (match-string 3)))
2560 'org-checkbox-statistics-done
2561 'org-checkbox-statistics-todo)))
2563 (defun org-update-checkbox-count-maybe (&optional all)
2564 "Update checkbox statistics unless turned off by user.
2565 With an optional argument ALL, update them in the whole buffer."
2566 (when (cdr (assq 'checkbox org-list-automatic-rules))
2567 (org-update-checkbox-count all))
2568 (run-hooks 'org-checkbox-statistics-hook))
2570 (defvar org-last-indent-begin-marker (make-marker))
2571 (defvar org-last-indent-end-marker (make-marker))
2572 (defun org-list-indent-item-generic (arg no-subtree struct)
2573 "Indent a local list item including its children.
2574 When number ARG is a negative, item will be outdented, otherwise
2575 it will be indented.
2577 If a region is active, all items inside will be moved.
2579 If NO-SUBTREE is non-nil, only indent the item itself, not its
2580 children.
2582 STRUCT is the list structure.
2584 Return t if successful."
2585 (save-excursion
2586 (let* ((regionp (org-region-active-p))
2587 (rbeg (and regionp (region-beginning)))
2588 (rend (and regionp (region-end)))
2589 (top (org-list-get-top-point struct))
2590 (parents (org-list-parents-alist struct))
2591 (prevs (org-list-prevs-alist struct))
2592 ;; Are we going to move the whole list?
2593 (specialp
2594 (and (not regionp)
2595 (= top (point-at-bol))
2596 (cdr (assq 'indent org-list-automatic-rules))
2597 (if no-subtree
2598 (error
2599 "First item of list cannot move without its subtree")
2600 t))))
2601 ;; Determine begin and end points of zone to indent. If moving
2602 ;; more than one item, save them for subsequent moves.
2603 (unless (and (memq last-command '(org-shiftmetaright org-shiftmetaleft))
2604 (memq this-command '(org-shiftmetaright org-shiftmetaleft)))
2605 (if regionp
2606 (progn
2607 (set-marker org-last-indent-begin-marker rbeg)
2608 (set-marker org-last-indent-end-marker rend))
2609 (set-marker org-last-indent-begin-marker (point-at-bol))
2610 (set-marker org-last-indent-end-marker
2611 (cond
2612 (specialp (org-list-get-bottom-point struct))
2613 (no-subtree (1+ (point-at-bol)))
2614 (t (org-list-get-item-end (point-at-bol) struct))))))
2615 (let* ((beg (marker-position org-last-indent-begin-marker))
2616 (end (marker-position org-last-indent-end-marker)))
2617 (cond
2618 ;; Special case: moving top-item with indent rule.
2619 (specialp
2620 (let* ((level-skip (org-level-increment))
2621 (offset (if (< arg 0) (- level-skip) level-skip))
2622 (top-ind (org-list-get-ind beg struct))
2623 (old-struct (copy-tree struct)))
2624 (if (< (+ top-ind offset) 0)
2625 (error "Cannot outdent beyond margin")
2626 ;; Change bullet if necessary.
2627 (when (and (= (+ top-ind offset) 0)
2628 (string-match "*"
2629 (org-list-get-bullet beg struct)))
2630 (org-list-set-bullet beg struct
2631 (org-list-bullet-string "-")))
2632 ;; Shift every item by OFFSET and fix bullets. Then
2633 ;; apply changes to buffer.
2634 (mapc (lambda (e)
2635 (let ((ind (org-list-get-ind (car e) struct)))
2636 (org-list-set-ind (car e) struct (+ ind offset))))
2637 struct)
2638 (org-list-struct-fix-bul struct prevs)
2639 (org-list-struct-apply-struct struct old-struct))))
2640 ;; Forbidden move:
2641 ((and (< arg 0)
2642 ;; If only one item is moved, it mustn't have a child.
2643 (or (and no-subtree
2644 (not regionp)
2645 (org-list-has-child-p beg struct))
2646 ;; If a subtree or region is moved, the last item
2647 ;; of the subtree mustn't have a child.
2648 (let ((last-item (caar
2649 (reverse
2650 (org-remove-if
2651 (lambda (e) (>= (car e) end))
2652 struct)))))
2653 (org-list-has-child-p last-item struct))))
2654 (error "Cannot outdent an item without its children"))
2655 ;; Normal shifting
2657 (let* ((new-parents
2658 (if (< arg 0)
2659 (org-list-struct-outdent beg end struct parents)
2660 (org-list-struct-indent beg end struct parents prevs))))
2661 (org-list-write-struct struct new-parents))
2662 (org-update-checkbox-count-maybe))))))
2665 (defun org-outdent-item ()
2666 "Outdent a local list item, but not its children.
2667 If a region is active, all items inside will be moved."
2668 (interactive)
2669 (let ((regionp (org-region-active-p)))
2670 (cond
2671 ((or (org-at-item-p)
2672 (and regionp
2673 (save-excursion (goto-char (region-beginning))
2674 (org-at-item-p))))
2675 (let ((struct (if (not regionp) (org-list-struct)
2676 (save-excursion (goto-char (region-beginning))
2677 (org-list-struct)))))
2678 (org-list-indent-item-generic -1 t struct)))
2679 (regionp (error "Region not starting at an item"))
2680 (t (error "Not at an item")))))
2682 (defun org-indent-item ()
2683 "Indent a local list item, but not its children.
2684 If a region is active, all items inside will be moved."
2685 (interactive)
2686 (let ((regionp (org-region-active-p)))
2687 (cond
2688 ((or (org-at-item-p)
2689 (and regionp
2690 (save-excursion (goto-char (region-beginning))
2691 (org-at-item-p))))
2692 (let ((struct (if (not regionp) (org-list-struct)
2693 (save-excursion (goto-char (region-beginning))
2694 (org-list-struct)))))
2695 (org-list-indent-item-generic 1 t struct)))
2696 (regionp (error "Region not starting at an item"))
2697 (t (error "Not at an item")))))
2699 (defun org-outdent-item-tree ()
2700 "Outdent a local list item including its children.
2701 If a region is active, all items inside will be moved."
2702 (interactive)
2703 (let ((regionp (org-region-active-p)))
2704 (cond
2705 ((or (org-at-item-p)
2706 (and regionp
2707 (save-excursion (goto-char (region-beginning))
2708 (org-at-item-p))))
2709 (let ((struct (if (not regionp) (org-list-struct)
2710 (save-excursion (goto-char (region-beginning))
2711 (org-list-struct)))))
2712 (org-list-indent-item-generic -1 nil struct)))
2713 (regionp (error "Region not starting at an item"))
2714 (t (error "Not at an item")))))
2716 (defun org-indent-item-tree ()
2717 "Indent a local list item including its children.
2718 If a region is active, all items inside will be moved."
2719 (interactive)
2720 (let ((regionp (org-region-active-p)))
2721 (cond
2722 ((or (org-at-item-p)
2723 (and regionp
2724 (save-excursion (goto-char (region-beginning))
2725 (org-at-item-p))))
2726 (let ((struct (if (not regionp) (org-list-struct)
2727 (save-excursion (goto-char (region-beginning))
2728 (org-list-struct)))))
2729 (org-list-indent-item-generic 1 nil struct)))
2730 (regionp (error "Region not starting at an item"))
2731 (t (error "Not at an item")))))
2733 (defvar org-tab-ind-state)
2734 (defun org-cycle-item-indentation ()
2735 "Cycle levels of indentation of an empty item.
2736 The first run indents the item, if applicable. Subsequent runs
2737 outdent it at meaningful levels in the list. When done, item is
2738 put back at its original position with its original bullet.
2740 Return t at each successful move."
2741 (when (org-at-item-p)
2742 (let* ((org-adapt-indentation nil)
2743 (struct (org-list-struct))
2744 (ind (org-list-get-ind (point-at-bol) struct))
2745 (bullet (org-trim (buffer-substring (point-at-bol) (point-at-eol)))))
2746 ;; Accept empty items or if cycle has already started.
2747 (when (or (eq last-command 'org-cycle-item-indentation)
2748 (and (save-excursion
2749 (beginning-of-line)
2750 (looking-at org-list-full-item-re))
2751 (>= (match-end 0) (save-excursion
2752 (goto-char (org-list-get-item-end
2753 (point-at-bol) struct))
2754 (skip-chars-backward " \r\t\n")
2755 (point)))))
2756 (setq this-command 'org-cycle-item-indentation)
2757 ;; When in the middle of the cycle, try to outdent first. If
2758 ;; it fails, and point is still at initial position, indent.
2759 ;; Else, re-create it at its original position.
2760 (if (eq last-command 'org-cycle-item-indentation)
2761 (cond
2762 ((ignore-errors (org-list-indent-item-generic -1 t struct)))
2763 ((and (= ind (car org-tab-ind-state))
2764 (ignore-errors (org-list-indent-item-generic 1 t struct))))
2765 (t (delete-region (point-at-bol) (point-at-eol))
2766 (org-indent-to-column (car org-tab-ind-state))
2767 (insert (cdr org-tab-ind-state) " ")
2768 ;; Break cycle
2769 (setq this-command 'identity)))
2770 ;; If a cycle is starting, remember indentation and bullet,
2771 ;; then try to indent. If it fails, try to outdent.
2772 (setq org-tab-ind-state (cons ind bullet))
2773 (cond
2774 ((ignore-errors (org-list-indent-item-generic 1 t struct)))
2775 ((ignore-errors (org-list-indent-item-generic -1 t struct)))
2776 (t (error "Cannot move item"))))
2777 t))))
2779 (defun org-sort-list (&optional with-case sorting-type getkey-func compare-func)
2780 "Sort list items.
2781 The cursor may be at any item of the list that should be sorted.
2782 Sublists are not sorted. Checkboxes, if any, are ignored.
2784 Sorting can be alphabetically, numerically, by date/time as given
2785 by a time stamp, by a property or by priority.
2787 Comparing entries ignores case by default. However, with an
2788 optional argument WITH-CASE, the sorting considers case as well.
2790 The command prompts for the sorting type unless it has been given
2791 to the function through the SORTING-TYPE argument, which needs to
2792 be a character, \(?n ?N ?a ?A ?t ?T ?f ?F). Here is the precise
2793 meaning of each character:
2795 n Numerically, by converting the beginning of the item to a number.
2796 a Alphabetically. Only the first line of item is checked.
2797 t By date/time, either the first active time stamp in the entry, if
2798 any, or by the first inactive one. In a timer list, sort the timers.
2800 Capital letters will reverse the sort order.
2802 If the SORTING-TYPE is ?f or ?F, then GETKEY-FUNC specifies
2803 a function to be called with point at the beginning of the
2804 record. It must return either a string or a number that should
2805 serve as the sorting key for that record. It will then use
2806 COMPARE-FUNC to compare entries."
2807 (interactive "P")
2808 (let* ((case-func (if with-case 'identity 'downcase))
2809 (struct (org-list-struct))
2810 (prevs (org-list-prevs-alist struct))
2811 (start (org-list-get-list-begin (point-at-bol) struct prevs))
2812 (end (org-list-get-list-end (point-at-bol) struct prevs))
2813 (sorting-type
2814 (progn
2815 (message
2816 "Sort plain list: [a]lpha [n]umeric [t]ime [f]unc A/N/T/F means reversed:")
2817 (read-char-exclusive)))
2818 (getkey-func (and (= (downcase sorting-type) ?f)
2819 (intern (org-icompleting-read "Sort using function: "
2820 obarray 'fboundp t nil nil)))))
2821 (message "Sorting items...")
2822 (save-restriction
2823 (narrow-to-region start end)
2824 (goto-char (point-min))
2825 (let* ((dcst (downcase sorting-type))
2826 (case-fold-search nil)
2827 (now (current-time))
2828 (sort-func (cond
2829 ((= dcst ?a) 'string<)
2830 ((= dcst ?f) compare-func)
2831 ((= dcst ?t) '<)
2832 (t nil)))
2833 (next-record (lambda ()
2834 (skip-chars-forward " \r\t\n")
2835 (beginning-of-line)))
2836 (end-record (lambda ()
2837 (goto-char (org-list-get-item-end-before-blank
2838 (point) struct))))
2839 (value-to-sort
2840 (lambda ()
2841 (when (looking-at "[ \t]*[-+*0-9.)]+\\([ \t]+\\[[- X]\\]\\)?[ \t]+")
2842 (cond
2843 ((= dcst ?n)
2844 (string-to-number (buffer-substring (match-end 0)
2845 (point-at-eol))))
2846 ((= dcst ?a)
2847 (funcall case-func
2848 (buffer-substring (match-end 0) (point-at-eol))))
2849 ((= dcst ?t)
2850 (cond
2851 ;; If it is a timer list, convert timer to seconds
2852 ((org-at-item-timer-p)
2853 (org-timer-hms-to-secs (match-string 1)))
2854 ((or (re-search-forward org-ts-regexp (point-at-eol) t)
2855 (re-search-forward org-ts-regexp-both
2856 (point-at-eol) t))
2857 (org-time-string-to-seconds (match-string 0)))
2858 (t (org-float-time now))))
2859 ((= dcst ?f)
2860 (if getkey-func
2861 (let ((value (funcall getkey-func)))
2862 (if (stringp value)
2863 (funcall case-func value)
2864 value))
2865 (error "Invalid key function `%s'" getkey-func)))
2866 (t (error "Invalid sorting type `%c'" sorting-type)))))))
2867 (sort-subr (/= dcst sorting-type)
2868 next-record
2869 end-record
2870 value-to-sort
2872 sort-func)
2873 ;; Read and fix list again, as `sort-subr' probably destroyed
2874 ;; its structure.
2875 (org-list-repair)
2876 (run-hooks 'org-after-sorting-entries-or-items-hook)
2877 (message "Sorting items...done")))))
2881 ;;; Send and receive lists
2883 (defun org-list-parse-list (&optional delete)
2884 "Parse the list at point and maybe DELETE it.
2886 Return a list whose car is a symbol of list type, among
2887 `ordered', `unordered' and `descriptive'. Then, each item is
2888 a list whose car is counter, and cdr are strings and other
2889 sub-lists. Inside strings, check-boxes are replaced by
2890 \"[CBON]\", \"[CBOFF]\" and \"[CBTRANS]\".
2892 For example, the following list:
2894 1. first item
2895 + sub-item one
2896 + [X] sub-item two
2897 more text in first item
2898 2. [@3] last item
2900 will be parsed as:
2902 \(ordered
2903 \(nil \"first item\"
2904 \(unordered
2905 \(nil \"sub-item one\"\)
2906 \(nil \"[CBON] sub-item two\"\)\)
2907 \"more text in first item\"\)
2908 \(3 \"last item\"\)\)
2910 Point is left at list end."
2911 (let* ((struct (org-list-struct))
2912 (prevs (org-list-prevs-alist struct))
2913 (parents (org-list-parents-alist struct))
2914 (top (org-list-get-top-point struct))
2915 (bottom (org-list-get-bottom-point struct))
2917 parse-item ; for byte-compiler
2918 (get-text
2919 (function
2920 ;; Return text between BEG and END, trimmed, with
2921 ;; checkboxes replaced.
2922 (lambda (beg end)
2923 (let ((text (org-trim (buffer-substring beg end))))
2924 (if (string-match "\\`\\[\\([-X ]\\)\\]" text)
2925 (replace-match
2926 (let ((box (match-string 1 text)))
2927 (cond
2928 ((equal box " ") "CBOFF")
2929 ((equal box "-") "CBTRANS")
2930 (t "CBON")))
2931 t nil text 1)
2932 text)))))
2933 (parse-sublist
2934 (function
2935 ;; Return a list whose car is list type and cdr a list of
2936 ;; items' body.
2937 (lambda (e)
2938 (cons (org-list-get-list-type (car e) struct prevs)
2939 (mapcar parse-item e)))))
2940 (parse-item
2941 (function
2942 ;; Return a list containing counter of item, if any, text
2943 ;; and any sublist inside it.
2944 (lambda (e)
2945 (let ((start (save-excursion
2946 (goto-char e)
2947 (looking-at "[ \t]*\\S-+\\([ \t]+\\[@\\(start:\\)?\\([0-9]+\\|[a-zA-Z]\\)\\]\\)?[ \t]*")
2948 (match-end 0)))
2949 ;; Get counter number. For alphabetic counter, get
2950 ;; its position in the alphabet.
2951 (counter (let ((c (org-list-get-counter e struct)))
2952 (cond
2953 ((not c) nil)
2954 ((string-match "[A-Za-z]" c)
2955 (- (string-to-char (upcase (match-string 0 c)))
2956 64))
2957 ((string-match "[0-9]+" c)
2958 (string-to-number (match-string 0 c))))))
2959 (childp (org-list-has-child-p e struct))
2960 (end (org-list-get-item-end e struct)))
2961 ;; If item has a child, store text between bullet and
2962 ;; next child, then recursively parse all sublists. At
2963 ;; the end of each sublist, check for the presence of
2964 ;; text belonging to the original item.
2965 (if childp
2966 (let* ((children (org-list-get-children e struct parents))
2967 (body (list (funcall get-text start childp))))
2968 (while children
2969 (let* ((first (car children))
2970 (sub (org-list-get-all-items first struct prevs))
2971 (last-c (car (last sub)))
2972 (last-end (org-list-get-item-end last-c struct)))
2973 (push (funcall parse-sublist sub) body)
2974 ;; Remove children from the list just parsed.
2975 (setq children (cdr (member last-c children)))
2976 ;; There is a chunk of text belonging to the
2977 ;; item if last child doesn't end where next
2978 ;; child starts or where item ends.
2979 (unless (= (or (car children) end) last-end)
2980 (push (funcall get-text
2981 last-end (or (car children) end))
2982 body))))
2983 (cons counter (nreverse body)))
2984 (list counter (funcall get-text start end))))))))
2985 ;; Store output, take care of cursor position and deletion of
2986 ;; list, then return output.
2987 (setq out (funcall parse-sublist (org-list-get-all-items top struct prevs)))
2988 (goto-char top)
2989 (when delete
2990 (delete-region top bottom)
2991 (when (and (not (looking-at "[ \t]*$")) (looking-at org-list-end-re))
2992 (replace-match "")))
2993 out))
2995 (defun org-list-make-subtree ()
2996 "Convert the plain list at point into a subtree."
2997 (interactive)
2998 (if (not (ignore-errors (goto-char (org-in-item-p))))
2999 (error "Not in a list")
3000 (let ((list (save-excursion (org-list-parse-list t))))
3001 (insert (org-list-to-subtree list)))))
3003 (defun org-list-insert-radio-list ()
3004 "Insert a radio list template appropriate for this major mode."
3005 (interactive)
3006 (let* ((e (assq major-mode org-list-radio-list-templates))
3007 (txt (nth 1 e))
3008 name pos)
3009 (unless e (error "No radio list setup defined for %s" major-mode))
3010 (setq name (read-string "List name: "))
3011 (while (string-match "%n" txt)
3012 (setq txt (replace-match name t t txt)))
3013 (or (bolp) (insert "\n"))
3014 (setq pos (point))
3015 (insert txt)
3016 (goto-char pos)))
3018 (defun org-list-send-list (&optional maybe)
3019 "Send a transformed version of this list to the receiver position.
3020 With argument MAYBE, fail quietly if no transformation is defined
3021 for this list."
3022 (interactive)
3023 (catch 'exit
3024 (unless (org-at-item-p) (error "Not at a list item"))
3025 (save-excursion
3026 (re-search-backward "#\\+ORGLST" nil t)
3027 (unless (looking-at "[ \t]*#\\+ORGLST[: \t][ \t]*SEND[ \t]+\\([^ \t\r\n]+\\)[ \t]+\\([^ \t\r\n]+\\)\\([ \t]+.*\\)?")
3028 (if maybe
3029 (throw 'exit nil)
3030 (error "Don't know how to transform this list"))))
3031 (let* ((name (match-string 1))
3032 (transform (intern (match-string 2)))
3033 (bottom-point
3034 (save-excursion
3035 (re-search-forward
3036 "\\(\\\\end{comment}\\|@end ignore\\|-->\\)" nil t)
3037 (match-beginning 0)))
3038 (top-point
3039 (progn
3040 (re-search-backward "#\\+ORGLST" nil t)
3041 (re-search-forward (org-item-beginning-re) bottom-point t)
3042 (match-beginning 0)))
3043 (list (save-restriction
3044 (narrow-to-region top-point bottom-point)
3045 (org-list-parse-list)))
3046 beg txt)
3047 (unless (fboundp transform)
3048 (error "No such transformation function %s" transform))
3049 (let ((txt (funcall transform list)))
3050 ;; Find the insertion place
3051 (save-excursion
3052 (goto-char (point-min))
3053 (unless (re-search-forward
3054 (concat "BEGIN RECEIVE ORGLST +"
3055 name
3056 "\\([ \t]\\|$\\)") nil t)
3057 (error "Don't know where to insert translated list"))
3058 (goto-char (match-beginning 0))
3059 (beginning-of-line 2)
3060 (setq beg (point))
3061 (unless (re-search-forward (concat "END RECEIVE ORGLST +" name) nil t)
3062 (error "Cannot find end of insertion region"))
3063 (delete-region beg (point-at-bol))
3064 (goto-char beg)
3065 (insert txt "\n")))
3066 (message "List converted and installed at receiver location"))))
3068 (defsubst org-list-item-trim-br (item)
3069 "Trim line breaks in a list ITEM."
3070 (setq item (replace-regexp-in-string "\n +" " " item)))
3072 (defun org-list-to-generic (list params)
3073 "Convert a LIST parsed through `org-list-parse-list' to other formats.
3074 Valid parameters PARAMS are:
3076 :ustart String to start an unordered list
3077 :uend String to end an unordered list
3079 :ostart String to start an ordered list
3080 :oend String to end an ordered list
3082 :dstart String to start a descriptive list
3083 :dend String to end a descriptive list
3084 :dtstart String to start a descriptive term
3085 :dtend String to end a descriptive term
3086 :ddstart String to start a description
3087 :ddend String to end a description
3089 :splice When set to t, return only list body lines, don't wrap
3090 them into :[u/o]start and :[u/o]end. Default is nil.
3092 :istart String to start a list item.
3093 :icount String to start an item with a counter.
3094 :iend String to end a list item
3095 :isep String to separate items
3096 :lsep String to separate sublists
3097 :csep String to separate text from a sub-list
3099 :cboff String to insert for an unchecked check-box
3100 :cbon String to insert for a checked check-box
3101 :cbtrans String to insert for a check-box in transitional state
3103 :nobr Non-nil means remove line breaks in lists items.
3105 Alternatively, each parameter can also be a form returning
3106 a string. These sexp can use keywords `counter' and `depth',
3107 representing respectively counter associated to the current
3108 item, and depth of the current sub-list, starting at 0.
3109 Obviously, `counter' is only available for parameters applying to
3110 items."
3111 (interactive)
3112 (let* ((p params)
3113 (splicep (plist-get p :splice))
3114 (ostart (plist-get p :ostart))
3115 (oend (plist-get p :oend))
3116 (ustart (plist-get p :ustart))
3117 (uend (plist-get p :uend))
3118 (dstart (plist-get p :dstart))
3119 (dend (plist-get p :dend))
3120 (dtstart (plist-get p :dtstart))
3121 (dtend (plist-get p :dtend))
3122 (ddstart (plist-get p :ddstart))
3123 (ddend (plist-get p :ddend))
3124 (istart (plist-get p :istart))
3125 (icount (plist-get p :icount))
3126 (iend (plist-get p :iend))
3127 (isep (plist-get p :isep))
3128 (lsep (plist-get p :lsep))
3129 (csep (plist-get p :csep))
3130 (cbon (plist-get p :cbon))
3131 (cboff (plist-get p :cboff))
3132 (cbtrans (plist-get p :cbtrans))
3133 (nobr (plist-get p :nobr))
3134 export-sublist ; for byte-compiler
3135 (export-item
3136 (function
3137 ;; Export an item ITEM of type TYPE, at DEPTH. First
3138 ;; string in item is treated in a special way as it can
3139 ;; bring extra information that needs to be processed.
3140 (lambda (item type depth)
3141 (let* ((counter (pop item))
3142 (fmt (concat
3143 (cond
3144 ((eq type 'descriptive)
3145 ;; Stick DTSTART to ISTART by
3146 ;; left-trimming the latter.
3147 (concat (let ((s (eval istart)))
3148 (or (and (string-match "[ \t\n\r]+\\'" s)
3149 (replace-match "" t t s))
3150 istart))
3151 "%s" (eval ddend)))
3152 ((and counter (eq type 'ordered))
3153 (concat (eval icount) "%s"))
3154 (t (concat (eval istart) "%s")))
3155 (eval iend)))
3156 (first (car item)))
3157 ;; Replace checkbox if any is found.
3158 (cond
3159 ((string-match "\\[CBON\\]" first)
3160 (setq first (replace-match cbon t t first)))
3161 ((string-match "\\[CBOFF\\]" first)
3162 (setq first (replace-match cboff t t first)))
3163 ((string-match "\\[CBTRANS\\]" first)
3164 (setq first (replace-match cbtrans t t first))))
3165 ;; Replace line breaks if required
3166 (when nobr (setq first (org-list-item-trim-br first)))
3167 ;; Insert descriptive term if TYPE is `descriptive'.
3168 (when (eq type 'descriptive)
3169 (let* ((complete (string-match "^\\(.*\\)[ \t]+::" first))
3170 (term (if complete
3171 (save-match-data
3172 (org-trim (match-string 1 first)))
3173 "???"))
3174 (desc (if complete
3175 (org-trim (substring first (match-end 0)))
3176 first)))
3177 (setq first (concat (eval dtstart) term (eval dtend)
3178 (eval ddstart) desc))))
3179 (setcar item first)
3180 (format fmt
3181 (mapconcat (lambda (e)
3182 (if (stringp e) e
3183 (funcall export-sublist e (1+ depth))))
3184 item (or (eval csep) "")))))))
3185 (export-sublist
3186 (function
3187 ;; Export sublist SUB at DEPTH.
3188 (lambda (sub depth)
3189 (let* ((type (car sub))
3190 (items (cdr sub))
3191 (fmt (concat (cond
3192 (splicep "%s")
3193 ((eq type 'ordered)
3194 (concat (eval ostart) "%s" (eval oend)))
3195 ((eq type 'descriptive)
3196 (concat (eval dstart) "%s" (eval dend)))
3197 (t (concat (eval ustart) "%s" (eval uend))))
3198 (eval lsep))))
3199 (format fmt (mapconcat (lambda (e)
3200 (funcall export-item e type depth))
3201 items (or (eval isep) ""))))))))
3202 (concat (funcall export-sublist list 0) "\n")))
3204 (defun org-list-to-latex (list &optional params)
3205 "Convert LIST into a LaTeX list.
3206 LIST is as returned by `org-list-parse-list'. PARAMS is a property list
3207 with overruling parameters for `org-list-to-generic'."
3208 (org-list-to-generic
3209 list
3210 (org-combine-plists
3211 '(:splice nil :ostart "\\begin{enumerate}\n" :oend "\\end{enumerate}"
3212 :ustart "\\begin{itemize}\n" :uend "\\end{itemize}"
3213 :dstart "\\begin{description}\n" :dend "\\end{description}"
3214 :dtstart "[" :dtend "] "
3215 :istart "\\item " :iend "\n"
3216 :icount (let ((enum (nth depth '("i" "ii" "iii" "iv"))))
3217 (if enum
3218 ;; LaTeX increments counter just before
3219 ;; using it, so set it to the desired
3220 ;; value, minus one.
3221 (format "\\setcounter{enum%s}{%s}\n\\item "
3222 enum (1- counter))
3223 "\\item "))
3224 :csep "\n"
3225 :cbon "\\texttt{[X]}" :cboff "\\texttt{[ ]}"
3226 :cbtrans "\\texttt{[-]}")
3227 params)))
3229 (defun org-list-to-html (list &optional params)
3230 "Convert LIST into a HTML list.
3231 LIST is as returned by `org-list-parse-list'. PARAMS is a property list
3232 with overruling parameters for `org-list-to-generic'."
3233 (org-list-to-generic
3234 list
3235 (org-combine-plists
3236 '(:splice nil :ostart "<ol>\n" :oend "\n</ol>"
3237 :ustart "<ul>\n" :uend "\n</ul>"
3238 :dstart "<dl>\n" :dend "\n</dl>"
3239 :dtstart "<dt>" :dtend "</dt>\n"
3240 :ddstart "<dd>" :ddend "</dd>"
3241 :istart "<li>" :iend "</li>"
3242 :icount (format "<li value=\"%s\">" counter)
3243 :isep "\n" :lsep "\n" :csep "\n"
3244 :cbon "<code>[X]</code>" :cboff "<code>[ ]</code>"
3245 :cbtrans "<code>[-]</code>")
3246 params)))
3248 (defun org-list-to-texinfo (list &optional params)
3249 "Convert LIST into a Texinfo list.
3250 LIST is as returned by `org-list-parse-list'. PARAMS is a property list
3251 with overruling parameters for `org-list-to-generic'."
3252 (org-list-to-generic
3253 list
3254 (org-combine-plists
3255 '(:splice nil :ostart "@itemize @minus\n" :oend "@end itemize"
3256 :ustart "@enumerate\n" :uend "@end enumerate"
3257 :dstart "@table @asis\n" :dend "@end table"
3258 :dtstart " " :dtend "\n"
3259 :istart "@item\n" :iend "\n"
3260 :icount "@item\n"
3261 :csep "\n"
3262 :cbon "@code{[X]}" :cboff "@code{[ ]}"
3263 :cbtrans "@code{[-]}")
3264 params)))
3266 (defun org-list-to-subtree (list &optional params)
3267 "Convert LIST into an Org subtree.
3268 LIST is as returned by `org-list-parse-list'. PARAMS is a property list
3269 with overruling parameters for `org-list-to-generic'."
3270 (let* ((rule (cdr (assq 'heading org-blank-before-new-entry)))
3271 (level (org-reduced-level (or (org-current-level) 0)))
3272 (blankp (or (eq rule t)
3273 (and (eq rule 'auto)
3274 (save-excursion
3275 (outline-previous-heading)
3276 (org-previous-line-empty-p)))))
3277 (get-stars
3278 (function
3279 ;; Return the string for the heading, depending on depth D
3280 ;; of current sub-list.
3281 (lambda (d)
3282 (let ((oddeven-level (+ level d 1)))
3283 (concat (make-string (if org-odd-levels-only
3284 (1- (* 2 oddeven-level))
3285 oddeven-level)
3287 " "))))))
3288 (org-list-to-generic
3289 list
3290 (org-combine-plists
3291 '(:splice t
3292 :dtstart " " :dtend " "
3293 :istart (funcall get-stars depth)
3294 :icount (funcall get-stars depth)
3295 :isep (if blankp "\n\n" "\n")
3296 :csep (if blankp "\n\n" "\n")
3297 :cbon "DONE" :cboff "TODO" :cbtrans "TODO")
3298 params))))
3300 (provide 'org-list)
3302 ;;; org-list.el ends here