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