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