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