org-list: Remove fancy description list indentation
[org-mode/org-tableheadings.git] / lisp / org-list.el
blob88fcc6e96d1bb6b0aa335d7e30cb16467e37bac7
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 (function
1557 (lambda (item)
1558 (let ((new-bul-p
1559 (cdr (assoc
1560 ;; Normalize ordered bullets.
1561 (let ((bul (org-trim
1562 (org-list-get-bullet item struct))))
1563 (cond ((string-match "[A-Z]\\." bul) "A.")
1564 ((string-match "[A-Z])" bul) "A)")
1565 ((string-match "[a-z]\\." bul) "a.")
1566 ((string-match "[a-z])" bul) "a)")
1567 ((string-match "[0-9]\\." bul) "1.")
1568 ((string-match "[0-9])" bul) "1)")
1569 (t bul)))
1570 org-list-demote-modify-bullet))))
1571 (when new-bul-p (org-list-set-bullet item struct new-bul-p))))))
1572 (ind
1573 (lambda (cell)
1574 (let* ((item (car cell))
1575 (parent (cdr cell)))
1576 (cond
1577 ;; Item not yet in zone: keep association.
1578 ((< item start) cell)
1579 ((>= item end)
1580 ;; Item out of zone: follow associations in ACC.
1581 (let ((convert (assq parent acc)))
1582 (if convert (cons item (cdr convert)) cell)))
1584 ;; Item is in zone...
1585 (let ((prev (org-list-get-prev-item item struct prevs)))
1586 ;; Check if bullet needs to be changed.
1587 (funcall change-bullet-maybe item)
1588 (cond
1589 ;; First item indented but not parent: error
1590 ((and (not prev) (or (not parent) (< parent start)))
1591 (user-error "Cannot indent the first item of a list"))
1592 ;; First item and parent indented: keep same
1593 ;; parent.
1594 ((not prev) (funcall set-assoc cell))
1595 ;; Previous item not indented: reparent to it.
1596 ((< prev start) (funcall set-assoc (cons item prev)))
1597 ;; Previous item indented: reparent like it.
1599 (funcall set-assoc
1600 (cons item (cdr (assq prev acc)))))))))))))
1601 (mapcar ind parents)))
1605 ;;; Repairing structures
1607 (defun org-list-use-alpha-bul-p (first struct prevs)
1608 "Non-nil if list starting at FIRST can have alphabetical bullets.
1610 STRUCT is list structure. PREVS is the alist of previous items,
1611 as returned by `org-list-prevs-alist'."
1612 (and org-list-allow-alphabetical
1613 (catch 'exit
1614 (let ((item first) (ascii 64) (case-fold-search nil))
1615 ;; Pretend that bullets are uppercase and check if alphabet
1616 ;; is sufficient, taking counters into account.
1617 (while item
1618 (let ((count (org-list-get-counter item struct)))
1619 ;; Virtually determine current bullet
1620 (if (and count (string-match-p "[a-zA-Z]" count))
1621 ;; Counters are not case-sensitive.
1622 (setq ascii (string-to-char (upcase count)))
1623 (setq ascii (1+ ascii)))
1624 ;; Test if bullet would be over z or Z.
1625 (if (> ascii 90)
1626 (throw 'exit nil)
1627 (setq item (org-list-get-next-item item struct prevs)))))
1628 ;; All items checked. All good.
1629 t))))
1631 (defun org-list-inc-bullet-maybe (bullet)
1632 "Increment BULLET if applicable."
1633 (let ((case-fold-search nil))
1634 (cond
1635 ;; Num bullet: increment it.
1636 ((string-match "[0-9]+" bullet)
1637 (replace-match
1638 (number-to-string (1+ (string-to-number (match-string 0 bullet))))
1639 nil nil bullet))
1640 ;; Alpha bullet: increment it.
1641 ((string-match "[A-Za-z]" bullet)
1642 (replace-match
1643 (char-to-string (1+ (string-to-char (match-string 0 bullet))))
1644 nil nil bullet))
1645 ;; Unordered bullet: leave it.
1646 (t bullet))))
1648 (defun org-list-struct-fix-bul (struct prevs)
1649 "Verify and correct bullets in STRUCT.
1650 PREVS is the alist of previous items, as returned by
1651 `org-list-prevs-alist'.
1653 This function modifies STRUCT."
1654 (let ((case-fold-search nil)
1655 (fix-bul
1656 (function
1657 ;; Set bullet of ITEM in STRUCT, depending on the type of
1658 ;; first item of the list, the previous bullet and counter
1659 ;; if any.
1660 (lambda (item)
1661 (let* ((prev (org-list-get-prev-item item struct prevs))
1662 (prev-bul (and prev (org-list-get-bullet prev struct)))
1663 (counter (org-list-get-counter item struct))
1664 (bullet (org-list-get-bullet item struct))
1665 (alphap (and (not prev)
1666 (org-list-use-alpha-bul-p item struct prevs))))
1667 (org-list-set-bullet
1668 item struct
1669 (org-list-bullet-string
1670 (cond
1671 ;; Alpha counter in alpha list: use counter.
1672 ((and prev counter
1673 (string-match "[a-zA-Z]" counter)
1674 (string-match "[a-zA-Z]" prev-bul))
1675 ;; Use cond to be sure `string-match' is used in
1676 ;; both cases.
1677 (let ((real-count
1678 (cond
1679 ((string-match "[a-z]" prev-bul) (downcase counter))
1680 ((string-match "[A-Z]" prev-bul) (upcase counter)))))
1681 (replace-match real-count nil nil prev-bul)))
1682 ;; Num counter in a num list: use counter.
1683 ((and prev counter
1684 (string-match "[0-9]+" counter)
1685 (string-match "[0-9]+" prev-bul))
1686 (replace-match counter nil nil prev-bul))
1687 ;; No counter: increase, if needed, previous bullet.
1688 (prev
1689 (org-list-inc-bullet-maybe (org-list-get-bullet prev struct)))
1690 ;; Alpha counter at first item: use counter.
1691 ((and counter (org-list-use-alpha-bul-p item struct prevs)
1692 (string-match "[A-Za-z]" counter)
1693 (string-match "[A-Za-z]" bullet))
1694 (let ((real-count
1695 (cond
1696 ((string-match "[a-z]" bullet) (downcase counter))
1697 ((string-match "[A-Z]" bullet) (upcase counter)))))
1698 (replace-match real-count nil nil bullet)))
1699 ;; Num counter at first item: use counter.
1700 ((and counter
1701 (string-match "[0-9]+" counter)
1702 (string-match "[0-9]+" bullet))
1703 (replace-match counter nil nil bullet))
1704 ;; First bullet is alpha uppercase: use "A".
1705 ((and alphap (string-match "[A-Z]" bullet))
1706 (replace-match "A" nil nil bullet))
1707 ;; First bullet is alpha lowercase: use "a".
1708 ((and alphap (string-match "[a-z]" bullet))
1709 (replace-match "a" nil nil bullet))
1710 ;; First bullet is num: use "1".
1711 ((string-match "\\([0-9]+\\|[A-Za-z]\\)" bullet)
1712 (replace-match "1" nil nil bullet))
1713 ;; Not an ordered list: keep bullet.
1714 (t bullet)))))))))
1715 (mapc fix-bul (mapcar #'car struct))))
1717 (defun org-list-struct-fix-ind (struct parents &optional bullet-size)
1718 "Verify and correct indentation in STRUCT.
1720 PARENTS is the alist of parents, as returned by
1721 `org-list-parents-alist'.
1723 If numeric optional argument BULLET-SIZE is set, assume all
1724 bullets in list have this length to determine new indentation.
1726 This function modifies STRUCT."
1727 (let* ((ancestor (org-list-get-top-point struct))
1728 (top-ind (org-list-get-ind ancestor struct))
1729 (new-ind
1730 (lambda (item)
1731 (let ((parent (org-list-get-parent item struct parents)))
1732 (if parent
1733 ;; Indent like parent + length of parent's bullet +
1734 ;; sub-list offset.
1735 (org-list-set-ind
1736 item struct (+ (or bullet-size
1737 (length
1738 (org-list-get-bullet parent struct)))
1739 (org-list-get-ind parent struct)
1740 org-list-indent-offset))
1741 ;; If no parent, indent like top-point.
1742 (org-list-set-ind item struct top-ind))))))
1743 (mapc new-ind (mapcar #'car (cdr struct)))))
1745 (defun org-list-struct-fix-box (struct parents prevs &optional ordered)
1746 "Verify and correct checkboxes in STRUCT.
1748 PARENTS is the alist of parents and PREVS is the alist of
1749 previous items, as returned by, respectively,
1750 `org-list-parents-alist' and `org-list-prevs-alist'.
1752 If ORDERED is non-nil, a checkbox can only be checked when every
1753 checkbox before it is checked too. If there was an attempt to
1754 break this rule, the function will return the blocking item. In
1755 all others cases, the return value will be nil.
1757 This function modifies STRUCT."
1758 (let ((all-items (mapcar #'car struct))
1759 (set-parent-box
1760 (function
1761 (lambda (item)
1762 (let* ((box-list
1763 (mapcar (lambda (child)
1764 (org-list-get-checkbox child struct))
1765 (org-list-get-children item struct parents))))
1766 (org-list-set-checkbox
1767 item struct
1768 (cond
1769 ((and (member "[ ]" box-list) (member "[X]" box-list)) "[-]")
1770 ((member "[-]" box-list) "[-]")
1771 ((member "[X]" box-list) "[X]")
1772 ((member "[ ]" box-list) "[ ]")
1773 ;; Parent has no boxed child: leave box as-is.
1774 (t (org-list-get-checkbox item struct))))))))
1775 parent-list)
1776 ;; 1. List all parents with a checkbox.
1777 (mapc
1778 (lambda (e)
1779 (let* ((parent (org-list-get-parent e struct parents))
1780 (parent-box-p (org-list-get-checkbox parent struct)))
1781 (when (and parent-box-p (not (memq parent parent-list)))
1782 (push parent parent-list))))
1783 all-items)
1784 ;; 2. Sort those parents by decreasing indentation.
1785 (setq parent-list (sort parent-list
1786 (lambda (e1 e2)
1787 (> (org-list-get-ind e1 struct)
1788 (org-list-get-ind e2 struct)))))
1789 ;; 3. For each parent, get all children's checkboxes to determine
1790 ;; and set its checkbox accordingly.
1791 (mapc set-parent-box parent-list)
1792 ;; 4. If ORDERED is set, see if we need to uncheck some boxes.
1793 (when ordered
1794 (let* ((box-list
1795 (mapcar (lambda (e) (org-list-get-checkbox e struct)) all-items))
1796 (after-unchecked (member "[ ]" box-list)))
1797 ;; There are boxes checked after an unchecked one: fix that.
1798 (when (member "[X]" after-unchecked)
1799 (let ((index (- (length struct) (length after-unchecked))))
1800 (mapc (lambda (e)
1801 (when (org-list-get-checkbox e struct)
1802 (org-list-set-checkbox e struct "[ ]")))
1803 (nthcdr index all-items))
1804 ;; Verify once again the structure, without ORDERED.
1805 (org-list-struct-fix-box struct parents prevs nil)
1806 ;; Return blocking item.
1807 (nth index all-items)))))))
1809 (defun org-list-struct-fix-item-end (struct)
1810 "Verify and correct each item end position in STRUCT.
1812 This function modifies STRUCT."
1813 (let (end-list acc-end)
1814 (mapc (lambda (e)
1815 (let* ((pos (car e))
1816 (ind-pos (org-list-get-ind pos struct))
1817 (end-pos (org-list-get-item-end pos struct)))
1818 (unless (assq end-pos struct)
1819 ;; To determine real ind of an ending position that is
1820 ;; not at an item, we have to find the item it belongs
1821 ;; to: it is the last item (ITEM-UP), whose ending is
1822 ;; further than the position we're interested in.
1823 (let ((item-up (assoc-default end-pos acc-end '>)))
1824 (push (cons
1825 ;; Else part is for the bottom point.
1826 (if item-up (+ (org-list-get-ind item-up struct) 2) 0)
1827 end-pos)
1828 end-list)))
1829 (push (cons ind-pos pos) end-list)
1830 (push (cons end-pos pos) acc-end)))
1831 struct)
1832 (setq end-list (sort end-list (lambda (e1 e2) (< (cdr e1) (cdr e2)))))
1833 (org-list-struct-assoc-end struct end-list)))
1835 (defun org-list-struct-apply-struct (struct old-struct)
1836 "Apply set difference between STRUCT and OLD-STRUCT to the buffer.
1838 OLD-STRUCT is the structure before any modifications, and STRUCT
1839 the structure to be applied. The function will only modify parts
1840 of the list which have changed.
1842 Initial position of cursor is restored after the changes."
1843 (let* ((origin (point-marker))
1844 (inlinetask-re (and (featurep 'org-inlinetask)
1845 (org-inlinetask-outline-regexp)))
1846 (item-re (org-item-re))
1847 (shift-body-ind
1848 (function
1849 ;; Shift the indentation between END and BEG by DELTA.
1850 ;; Start from the line before END.
1851 (lambda (end beg delta)
1852 (goto-char end)
1853 (skip-chars-backward " \r\t\n")
1854 (beginning-of-line)
1855 (while (or (> (point) beg)
1856 (and (= (point) beg)
1857 (not (looking-at item-re))))
1858 (cond
1859 ;; Skip inline tasks.
1860 ((and inlinetask-re (looking-at inlinetask-re))
1861 (org-inlinetask-goto-beginning))
1862 ;; Shift only non-empty lines.
1863 ((looking-at-p "^[ \t]*\\S-")
1864 (indent-line-to (+ (current-indentation) delta))))
1865 (forward-line -1)))))
1866 (modify-item
1867 (function
1868 ;; Replace ITEM first line elements with new elements from
1869 ;; STRUCT, if appropriate.
1870 (lambda (item)
1871 (goto-char item)
1872 (let* ((new-ind (org-list-get-ind item struct))
1873 (old-ind (current-indentation))
1874 (new-bul (org-list-bullet-string
1875 (org-list-get-bullet item struct)))
1876 (old-bul (org-list-get-bullet item old-struct))
1877 (new-box (org-list-get-checkbox item struct)))
1878 (looking-at org-list-full-item-re)
1879 ;; a. Replace bullet
1880 (unless (equal old-bul new-bul)
1881 (replace-match new-bul nil nil nil 1))
1882 ;; b. Replace checkbox.
1883 (cond
1884 ((equal (match-string 3) new-box))
1885 ((and (match-string 3) new-box)
1886 (replace-match new-box nil nil nil 3))
1887 ((match-string 3)
1888 (looking-at ".*?\\([ \t]*\\[[ X-]\\]\\)")
1889 (replace-match "" nil nil nil 1))
1890 (t (let ((counterp (match-end 2)))
1891 (goto-char (if counterp (1+ counterp) (match-end 1)))
1892 (insert (concat new-box (unless counterp " "))))))
1893 ;; c. Indent item to appropriate column.
1894 (unless (= new-ind old-ind)
1895 (delete-region (goto-char (point-at-bol))
1896 (progn (skip-chars-forward " \t") (point)))
1897 (indent-to new-ind)))))))
1898 ;; 1. First get list of items and position endings. We maintain
1899 ;; two alists: ITM-SHIFT, determining indentation shift needed
1900 ;; at item, and END-LIST, a pseudo-alist where key is ending
1901 ;; position and value point.
1902 (let (end-list acc-end itm-shift all-ends sliced-struct)
1903 (dolist (e old-struct)
1904 (let* ((pos (car e))
1905 (ind-pos (org-list-get-ind pos struct))
1906 (ind-old (org-list-get-ind pos old-struct))
1907 (bul-pos (org-list-get-bullet pos struct))
1908 (bul-old (org-list-get-bullet pos old-struct))
1909 (ind-shift (- (+ ind-pos (length bul-pos))
1910 (+ ind-old (length bul-old))))
1911 (end-pos (org-list-get-item-end pos old-struct)))
1912 (push (cons pos ind-shift) itm-shift)
1913 (unless (assq end-pos old-struct)
1914 ;; To determine real ind of an ending position that
1915 ;; is not at an item, we have to find the item it
1916 ;; belongs to: it is the last item (ITEM-UP), whose
1917 ;; ending is further than the position we're
1918 ;; interested in.
1919 (let ((item-up (assoc-default end-pos acc-end #'>)))
1920 (push (cons end-pos item-up) end-list)))
1921 (push (cons end-pos pos) acc-end)))
1922 ;; 2. Slice the items into parts that should be shifted by the
1923 ;; same amount of indentation. Each slice follow the pattern
1924 ;; (END BEG DELTA). Slices are returned in reverse order.
1925 (setq all-ends (sort (append (mapcar #'car itm-shift)
1926 (org-uniquify (mapcar #'car end-list)))
1927 #'<)
1928 acc-end (nreverse acc-end))
1929 (while (cdr all-ends)
1930 (let* ((up (pop all-ends))
1931 (down (car all-ends))
1932 (itemp (assq up struct))
1933 (delta
1934 (if itemp (cdr (assq up itm-shift))
1935 ;; If we're not at an item, there's a child of the
1936 ;; item point belongs to above. Make sure the less
1937 ;; indented line in this slice has the same column
1938 ;; as that child.
1939 (let* ((child (cdr (assq up acc-end)))
1940 (ind (org-list-get-ind child struct))
1941 (min-ind most-positive-fixnum))
1942 (save-excursion
1943 (goto-char up)
1944 (while (< (point) down)
1945 ;; Ignore empty lines. Also ignore blocks and
1946 ;; drawers contents.
1947 (unless (looking-at-p "[ \t]*$")
1948 (setq min-ind (min (current-indentation) min-ind))
1949 (cond
1950 ((and (looking-at "#\\+BEGIN\\(:\\|_\\S-+\\)")
1951 (re-search-forward
1952 (format "^[ \t]*#\\+END%s[ \t]*$"
1953 (match-string 1))
1954 down t)))
1955 ((and (looking-at org-drawer-regexp)
1956 (re-search-forward "^[ \t]*:END:[ \t]*$"
1957 down t)))))
1958 (forward-line)))
1959 (- ind min-ind)))))
1960 (push (list down up delta) sliced-struct)))
1961 ;; 3. Shift each slice in buffer, provided delta isn't 0, from
1962 ;; end to beginning. Take a special action when beginning is
1963 ;; at item bullet.
1964 (dolist (e sliced-struct)
1965 (unless (zerop (nth 2 e)) (apply shift-body-ind e))
1966 (let* ((beg (nth 1 e))
1967 (cell (assq beg struct)))
1968 (unless (or (not cell) (equal cell (assq beg old-struct)))
1969 (funcall modify-item beg)))))
1970 ;; 4. Go back to initial position and clean marker.
1971 (goto-char origin)
1972 (move-marker origin nil)))
1974 (defun org-list-write-struct (struct parents &optional old-struct)
1975 "Correct bullets, checkboxes and indentation in list at point.
1977 STRUCT is the list structure. PARENTS is the alist of parents,
1978 as returned by `org-list-parents-alist'.
1980 When non-nil, optional argument OLD-STRUCT is the reference
1981 structure of the list. It should be provided whenever STRUCT
1982 doesn't correspond anymore to the real list in buffer."
1983 ;; Order of functions matters here: checkboxes and endings need
1984 ;; correct indentation to be set, and indentation needs correct
1985 ;; bullets.
1987 ;; 0. Save a copy of structure before modifications
1988 (let ((old-struct (or old-struct (copy-tree struct))))
1989 ;; 1. Set a temporary, but coherent with PARENTS, indentation in
1990 ;; order to get items endings and bullets properly
1991 (org-list-struct-fix-ind struct parents 2)
1992 ;; 2. Fix each item end to get correct prevs alist.
1993 (org-list-struct-fix-item-end struct)
1994 ;; 3. Get bullets right.
1995 (let ((prevs (org-list-prevs-alist struct)))
1996 (org-list-struct-fix-bul struct prevs)
1997 ;; 4. Now get real indentation.
1998 (org-list-struct-fix-ind struct parents)
1999 ;; 5. Eventually fix checkboxes.
2000 (org-list-struct-fix-box struct parents prevs))
2001 ;; 6. Apply structure modifications to buffer.
2002 (org-list-struct-apply-struct struct old-struct))
2003 ;; 7. Return the updated structure
2004 struct)
2008 ;;; Misc Tools
2010 (defun org-apply-on-list (function init-value &rest args)
2011 "Call FUNCTION on each item of the list at point.
2012 FUNCTION must be called with at least one argument: INIT-VALUE,
2013 that will contain the value returned by the function at the
2014 previous item, plus ARGS extra arguments.
2016 FUNCTION is applied on items in reverse order.
2018 As an example, \(org-apply-on-list \(lambda \(result) \(1+ result)) 0)
2019 will return the number of items in the current list.
2021 Sublists of the list are skipped. Cursor is always at the
2022 beginning of the item."
2023 (let* ((struct (org-list-struct))
2024 (prevs (org-list-prevs-alist struct))
2025 (item (copy-marker (point-at-bol)))
2026 (all (org-list-get-all-items (marker-position item) struct prevs))
2027 (value init-value))
2028 (mapc (lambda (e)
2029 (goto-char e)
2030 (setq value (apply function value args)))
2031 (nreverse all))
2032 (goto-char item)
2033 (move-marker item nil)
2034 value))
2036 (defun org-list-set-item-visibility (item struct view)
2037 "Set visibility of ITEM in STRUCT to VIEW.
2039 Possible values are: `folded', `children' or `subtree'. See
2040 `org-cycle' for more information."
2041 (cond
2042 ((eq view 'folded)
2043 (let ((item-end (org-list-get-item-end-before-blank item struct)))
2044 ;; Hide from eol
2045 (org-flag-region (save-excursion (goto-char item) (line-end-position))
2046 item-end t 'outline)))
2047 ((eq view 'children)
2048 ;; First show everything.
2049 (org-list-set-item-visibility item struct 'subtree)
2050 ;; Then fold every child.
2051 (let* ((parents (org-list-parents-alist struct))
2052 (children (org-list-get-children item struct parents)))
2053 (mapc (lambda (e)
2054 (org-list-set-item-visibility e struct 'folded))
2055 children)))
2056 ((eq view 'subtree)
2057 ;; Show everything
2058 (let ((item-end (org-list-get-item-end item struct)))
2059 (org-flag-region item item-end nil 'outline)))))
2061 (defun org-list-item-body-column (item)
2062 "Return column at which body of ITEM should start."
2063 (save-excursion
2064 (goto-char item)
2065 (looking-at "[ \t]*\\(\\S-+\\)")
2066 (+ (progn (goto-char (match-end 1)) (current-column))
2067 (if (and org-list-two-spaces-after-bullet-regexp
2068 (string-match-p org-list-two-spaces-after-bullet-regexp
2069 (match-string 1)))
2071 1))))
2075 ;;; Interactive functions
2077 (defalias 'org-list-get-item-begin 'org-in-item-p)
2079 (defun org-beginning-of-item ()
2080 "Go to the beginning of the current item.
2081 Throw an error when not in a list."
2082 (interactive)
2083 (let ((begin (org-in-item-p)))
2084 (if begin (goto-char begin) (error "Not in an item"))))
2086 (defun org-beginning-of-item-list ()
2087 "Go to the beginning item of the current list or sublist.
2088 Throw an error when not in a list."
2089 (interactive)
2090 (let ((begin (org-in-item-p)))
2091 (if (not begin)
2092 (error "Not in an item")
2093 (goto-char begin)
2094 (let* ((struct (org-list-struct))
2095 (prevs (org-list-prevs-alist struct)))
2096 (goto-char (org-list-get-list-begin begin struct prevs))))))
2098 (defun org-end-of-item-list ()
2099 "Go to the end of the current list or sublist.
2100 Throw an error when not in a list."
2101 (interactive)
2102 (let ((begin (org-in-item-p)))
2103 (if (not begin)
2104 (error "Not in an item")
2105 (goto-char begin)
2106 (let* ((struct (org-list-struct))
2107 (prevs (org-list-prevs-alist struct)))
2108 (goto-char (org-list-get-list-end begin struct prevs))))))
2110 (defun org-end-of-item ()
2111 "Go to the end of the current item.
2112 Throw an error when not in a list."
2113 (interactive)
2114 (let ((begin (org-in-item-p)))
2115 (if (not begin)
2116 (error "Not in an item")
2117 (goto-char begin)
2118 (let ((struct (org-list-struct)))
2119 (goto-char (org-list-get-item-end begin struct))))))
2121 (defun org-previous-item ()
2122 "Move to the beginning of the previous item.
2123 Throw an error when not in a list. Also throw an error when at
2124 first item, unless `org-list-use-circular-motion' is non-nil."
2125 (interactive)
2126 (let ((item (org-in-item-p)))
2127 (if (not item)
2128 (error "Not in an item")
2129 (goto-char item)
2130 (let* ((struct (org-list-struct))
2131 (prevs (org-list-prevs-alist struct))
2132 (prevp (org-list-get-prev-item item struct prevs)))
2133 (cond
2134 (prevp (goto-char prevp))
2135 (org-list-use-circular-motion
2136 (goto-char (org-list-get-last-item item struct prevs)))
2137 (t (error "On first item")))))))
2139 (defun org-next-item ()
2140 "Move to the beginning of the next item.
2141 Throw an error when not in a list. Also throw an error when at
2142 last item, unless `org-list-use-circular-motion' is non-nil."
2143 (interactive)
2144 (let ((item (org-in-item-p)))
2145 (if (not item)
2146 (error "Not in an item")
2147 (goto-char item)
2148 (let* ((struct (org-list-struct))
2149 (prevs (org-list-prevs-alist struct))
2150 (prevp (org-list-get-next-item item struct prevs)))
2151 (cond
2152 (prevp (goto-char prevp))
2153 (org-list-use-circular-motion
2154 (goto-char (org-list-get-first-item item struct prevs)))
2155 (t (error "On last item")))))))
2157 (defun org-move-item-down ()
2158 "Move the item at point down, i.e. swap with following item.
2159 Sub-items (items with larger indentation) are considered part of
2160 the item, so this really moves item trees."
2161 (interactive)
2162 (unless (org-at-item-p) (error "Not at an item"))
2163 (let* ((col (current-column))
2164 (item (point-at-bol))
2165 (struct (org-list-struct))
2166 (prevs (org-list-prevs-alist struct))
2167 (next-item (org-list-get-next-item (point-at-bol) struct prevs)))
2168 (unless (or next-item org-list-use-circular-motion)
2169 (user-error "Cannot move this item further down"))
2170 (if (not next-item)
2171 (setq struct (org-list-send-item item 'begin struct))
2172 (setq struct (org-list-swap-items item next-item struct))
2173 (goto-char
2174 (org-list-get-next-item item struct (org-list-prevs-alist struct))))
2175 (org-list-write-struct struct (org-list-parents-alist struct))
2176 (org-move-to-column col)))
2178 (defun org-move-item-up ()
2179 "Move the item at point up, i.e. swap with previous item.
2180 Sub-items (items with larger indentation) are considered part of
2181 the item, so this really moves item trees."
2182 (interactive)
2183 (unless (org-at-item-p) (error "Not at an item"))
2184 (let* ((col (current-column))
2185 (item (point-at-bol))
2186 (struct (org-list-struct))
2187 (prevs (org-list-prevs-alist struct))
2188 (prev-item (org-list-get-prev-item (point-at-bol) struct prevs)))
2189 (unless (or prev-item org-list-use-circular-motion)
2190 (user-error "Cannot move this item further up"))
2191 (if (not prev-item)
2192 (setq struct (org-list-send-item item 'end struct))
2193 (setq struct (org-list-swap-items prev-item item struct)))
2194 (org-list-write-struct struct (org-list-parents-alist struct))
2195 (org-move-to-column col)))
2197 (defun org-insert-item (&optional checkbox)
2198 "Insert a new item at the current level.
2199 If cursor is before first character after bullet of the item, the
2200 new item will be created before the current one.
2202 If CHECKBOX is non-nil, add a checkbox next to the bullet.
2204 Return t when things worked, nil when we are not in an item, or
2205 item is invisible."
2206 (interactive "P")
2207 (let ((itemp (org-in-item-p))
2208 (pos (point)))
2209 ;; If cursor isn't is a list or if list is invisible, return nil.
2210 (unless (or (not itemp)
2211 (save-excursion
2212 (goto-char itemp)
2213 (org-invisible-p)))
2214 (if (save-excursion
2215 (goto-char itemp)
2216 (org-at-item-timer-p))
2217 ;; Timer list: delegate to `org-timer-item'.
2218 (progn (org-timer-item) t)
2219 (let* ((struct (save-excursion (goto-char itemp)
2220 (org-list-struct)))
2221 (prevs (org-list-prevs-alist struct))
2222 ;; If we're in a description list, ask for the new term.
2223 (desc (when (eq (org-list-get-list-type itemp struct prevs)
2224 'descriptive)
2225 " :: ")))
2226 (setq struct (org-list-insert-item pos struct prevs checkbox desc))
2227 (org-list-write-struct struct (org-list-parents-alist struct))
2228 (when checkbox (org-update-checkbox-count-maybe))
2229 (looking-at org-list-full-item-re)
2230 (goto-char (if (and (match-beginning 4)
2231 (save-match-data
2232 (string-match "[.)]" (match-string 1))))
2233 (match-beginning 4)
2234 (match-end 0)))
2235 (when desc (backward-char 1))
2236 t)))))
2238 (defun org-list-repair ()
2239 "Fix indentation, bullets and checkboxes in the list at point."
2240 (interactive)
2241 (unless (org-at-item-p) (error "This is not a list"))
2242 (let* ((struct (org-list-struct))
2243 (parents (org-list-parents-alist struct)))
2244 (org-list-write-struct struct parents)))
2246 (defun org-cycle-list-bullet (&optional which)
2247 "Cycle through the different itemize/enumerate bullets.
2248 This cycle the entire list level through the sequence:
2250 `-' -> `+' -> `*' -> `1.' -> `1)'
2252 If WHICH is a valid string, use that as the new bullet. If WHICH
2253 is an integer, 0 means `-', 1 means `+' etc. If WHICH is
2254 `previous', cycle backwards."
2255 (interactive "P")
2256 (unless (org-at-item-p) (error "Not at an item"))
2257 (save-excursion
2258 (beginning-of-line)
2259 (let* ((struct (org-list-struct))
2260 (parents (org-list-parents-alist struct))
2261 (prevs (org-list-prevs-alist struct))
2262 (list-beg (org-list-get-first-item (point) struct prevs))
2263 (bullet (org-list-get-bullet list-beg struct))
2264 (alpha-p (org-list-use-alpha-bul-p list-beg struct prevs))
2265 (case-fold-search nil)
2266 (current (cond
2267 ((string-match "[a-z]\\." bullet) "a.")
2268 ((string-match "[a-z])" bullet) "a)")
2269 ((string-match "[A-Z]\\." bullet) "A.")
2270 ((string-match "[A-Z])" bullet) "A)")
2271 ((string-match "\\." bullet) "1.")
2272 ((string-match ")" bullet) "1)")
2273 (t (org-trim bullet))))
2274 ;; Compute list of possible bullets, depending on context.
2275 (bullet-list
2276 (append '("-" "+" )
2277 ;; *-bullets are not allowed at column 0.
2278 (unless (looking-at "\\S-") '("*"))
2279 ;; Description items cannot be numbered.
2280 (unless (or (eq org-plain-list-ordered-item-terminator ?\))
2281 (org-at-item-description-p))
2282 '("1."))
2283 (unless (or (eq org-plain-list-ordered-item-terminator ?.)
2284 (org-at-item-description-p))
2285 '("1)"))
2286 (unless (or (not alpha-p)
2287 (eq org-plain-list-ordered-item-terminator ?\))
2288 (org-at-item-description-p))
2289 '("a." "A."))
2290 (unless (or (not alpha-p)
2291 (eq org-plain-list-ordered-item-terminator ?.)
2292 (org-at-item-description-p))
2293 '("a)" "A)"))))
2294 (len (length bullet-list))
2295 (item-index (- len (length (member current bullet-list))))
2296 (get-value (lambda (index) (nth (mod index len) bullet-list)))
2297 (new (cond
2298 ((member which bullet-list) which)
2299 ((numberp which) (funcall get-value which))
2300 ((eq 'previous which) (funcall get-value (1- item-index)))
2301 (t (funcall get-value (1+ item-index))))))
2302 ;; Use a short variation of `org-list-write-struct' as there's
2303 ;; no need to go through all the steps.
2304 (let ((old-struct (copy-tree struct)))
2305 (org-list-set-bullet list-beg struct (org-list-bullet-string new))
2306 (org-list-struct-fix-bul struct prevs)
2307 (org-list-struct-fix-ind struct parents)
2308 (org-list-struct-apply-struct struct old-struct)))))
2310 (defun org-toggle-checkbox (&optional toggle-presence)
2311 "Toggle the checkbox in the current line.
2313 With prefix argument TOGGLE-PRESENCE, add or remove checkboxes.
2314 With a double prefix argument, set the checkbox to \"[-]\".
2316 When there is an active region, toggle status or presence of the
2317 first checkbox there, and make every item inside have the same
2318 status or presence, respectively.
2320 If point is on a headline, apply this to all checkbox items in
2321 the text below the heading, taking as reference the first item in
2322 subtree, ignoring planning line and any drawer following it."
2323 (interactive "P")
2324 (save-excursion
2325 (let* (singlep
2326 block-item
2327 lim-up
2328 lim-down
2329 (orderedp (org-entry-get nil "ORDERED"))
2330 (_bounds
2331 ;; In a region, start at first item in region.
2332 (cond
2333 ((org-region-active-p)
2334 (let ((limit (region-end)))
2335 (goto-char (region-beginning))
2336 (if (org-list-search-forward (org-item-beginning-re) limit t)
2337 (setq lim-up (point-at-bol))
2338 (error "No item in region"))
2339 (setq lim-down (copy-marker limit))))
2340 ((org-at-heading-p)
2341 ;; On a heading, start at first item after drawers and
2342 ;; time-stamps (scheduled, etc.).
2343 (let ((limit (save-excursion (outline-next-heading) (point))))
2344 (org-end-of-meta-data t)
2345 (if (org-list-search-forward (org-item-beginning-re) limit t)
2346 (setq lim-up (point-at-bol))
2347 (error "No item in subtree"))
2348 (setq lim-down (copy-marker limit))))
2349 ;; Just one item: set SINGLEP flag.
2350 ((org-at-item-p)
2351 (setq singlep t)
2352 (setq lim-up (point-at-bol)
2353 lim-down (copy-marker (point-at-eol))))
2354 (t (error "Not at an item or heading, and no active region"))))
2355 ;; Determine the checkbox going to be applied to all items
2356 ;; within bounds.
2357 (ref-checkbox
2358 (progn
2359 (goto-char lim-up)
2360 (let ((cbox (and (org-at-item-checkbox-p) (match-string 1))))
2361 (cond
2362 ((equal toggle-presence '(16)) "[-]")
2363 ((equal toggle-presence '(4))
2364 (unless cbox "[ ]"))
2365 ((equal "[X]" cbox) "[ ]")
2366 (t "[X]"))))))
2367 ;; When an item is found within bounds, grab the full list at
2368 ;; point structure, then: (1) set check-box of all its items
2369 ;; within bounds to REF-CHECKBOX, (2) fix check-boxes of the
2370 ;; whole list, (3) move point after the list.
2371 (goto-char lim-up)
2372 (while (and (< (point) lim-down)
2373 (org-list-search-forward (org-item-beginning-re)
2374 lim-down 'move))
2375 (let* ((struct (org-list-struct))
2376 (struct-copy (copy-tree struct))
2377 (parents (org-list-parents-alist struct))
2378 (prevs (org-list-prevs-alist struct))
2379 (bottom (copy-marker (org-list-get-bottom-point struct)))
2380 (items-to-toggle (cl-remove-if
2381 (lambda (e) (or (< e lim-up) (> e lim-down)))
2382 (mapcar #'car struct))))
2383 (mapc (lambda (e) (org-list-set-checkbox
2384 e struct
2385 ;; If there is no box at item, leave as-is
2386 ;; unless function was called with C-u prefix.
2387 (let ((cur-box (org-list-get-checkbox e struct)))
2388 (if (or cur-box (equal toggle-presence '(4)))
2389 ref-checkbox
2390 cur-box))))
2391 items-to-toggle)
2392 (setq block-item (org-list-struct-fix-box
2393 struct parents prevs orderedp))
2394 ;; Report some problems due to ORDERED status of subtree.
2395 ;; If only one box was being checked, throw an error, else,
2396 ;; only signal problems.
2397 (cond
2398 ((and singlep block-item (> lim-up block-item))
2399 (error
2400 "Checkbox blocked because of unchecked box at line %d"
2401 (org-current-line block-item)))
2402 (block-item
2403 (message
2404 "Checkboxes were removed due to unchecked box at line %d"
2405 (org-current-line block-item))))
2406 (goto-char bottom)
2407 (move-marker bottom nil)
2408 (org-list-struct-apply-struct struct struct-copy)))
2409 (move-marker lim-down nil)))
2410 (org-update-checkbox-count-maybe))
2412 (defun org-reset-checkbox-state-subtree ()
2413 "Reset all checkboxes in an entry subtree."
2414 (interactive "*")
2415 (if (org-before-first-heading-p)
2416 (error "Not inside a tree")
2417 (save-restriction
2418 (save-excursion
2419 (org-narrow-to-subtree)
2420 (org-show-subtree)
2421 (goto-char (point-min))
2422 (let ((end (point-max)))
2423 (while (< (point) end)
2424 (when (org-at-item-checkbox-p)
2425 (replace-match "[ ]" t t nil 1))
2426 (beginning-of-line 2)))
2427 (org-update-checkbox-count-maybe 'all)))))
2429 (defun org-update-checkbox-count (&optional all)
2430 "Update the checkbox statistics in the current section.
2432 This will find all statistic cookies like [57%] and [6/12] and
2433 update them with the current numbers.
2435 With optional prefix argument ALL, do this for the whole buffer."
2436 (interactive "P")
2437 (org-with-wide-buffer
2438 (let* ((cookie-re "\\(\\(\\[[0-9]*%\\]\\)\\|\\(\\[[0-9]*/[0-9]*\\]\\)\\)")
2439 (box-re "^[ \t]*\\([-+*]\\|\\([0-9]+\\|[A-Za-z]\\)[.)]\\)[ \t]+\
2440 \\(?:\\[@\\(?:start:\\)?\\([0-9]+\\|[A-Za-z]\\)\\][ \t]*\\)?\\(\\[[- X]\\]\\)")
2441 (recursivep
2442 (or (not org-checkbox-hierarchical-statistics)
2443 (string-match "\\<recursive\\>"
2444 (or (org-entry-get nil "COOKIE_DATA") ""))))
2445 (within-inlinetask (and (not all)
2446 (featurep 'org-inlinetask)
2447 (org-inlinetask-in-task-p)))
2448 (end (cond (all (point-max))
2449 (within-inlinetask
2450 (save-excursion (outline-next-heading) (point)))
2451 (t (save-excursion
2452 (org-with-limited-levels (outline-next-heading))
2453 (point)))))
2454 (count-boxes
2455 (lambda (item structs recursivep)
2456 ;; Return number of checked boxes and boxes of all types
2457 ;; in all structures in STRUCTS. If RECURSIVEP is
2458 ;; non-nil, also count boxes in sub-lists. If ITEM is
2459 ;; nil, count across the whole structure, else count only
2460 ;; across subtree whose ancestor is ITEM.
2461 (let ((c-on 0) (c-all 0))
2462 (dolist (s structs (list c-on c-all))
2463 (let* ((pre (org-list-prevs-alist s))
2464 (par (org-list-parents-alist s))
2465 (items
2466 (cond
2467 ((and recursivep item) (org-list-get-subtree item s))
2468 (recursivep (mapcar #'car s))
2469 (item (org-list-get-children item s par))
2470 (t (org-list-get-all-items
2471 (org-list-get-top-point s) s pre))))
2472 (cookies (delq nil (mapcar
2473 (lambda (e)
2474 (org-list-get-checkbox e s))
2475 items))))
2476 (cl-incf c-all (length cookies))
2477 (cl-incf c-on (cl-count "[X]" cookies :test #'equal)))))))
2478 cookies-list cache)
2479 ;; Move to start.
2480 (cond (all (goto-char (point-min)))
2481 (within-inlinetask (org-back-to-heading t))
2482 (t (org-with-limited-levels (outline-previous-heading))))
2483 ;; Build an alist for each cookie found. The key is the position
2484 ;; at beginning of cookie and values ending position, format of
2485 ;; cookie, number of checked boxes to report and total number of
2486 ;; boxes.
2487 (while (re-search-forward cookie-re end t)
2488 (let ((context (save-excursion (backward-char)
2489 (save-match-data (org-element-context)))))
2490 (when (eq (org-element-type context) 'statistics-cookie)
2491 (push
2492 (append
2493 (list (match-beginning 1) (match-end 1) (match-end 2))
2494 (let* ((container
2495 (org-element-lineage
2496 context
2497 '(drawer center-block dynamic-block inlinetask item
2498 quote-block special-block verse-block)))
2499 (beg (if container
2500 (org-element-property :contents-begin container)
2501 (save-excursion
2502 (org-with-limited-levels
2503 (outline-previous-heading))
2504 (point)))))
2505 (or (cdr (assq beg cache))
2506 (save-excursion
2507 (goto-char beg)
2508 (let ((end
2509 (if container
2510 (org-element-property :contents-end container)
2511 (save-excursion
2512 (org-with-limited-levels (outline-next-heading))
2513 (point))))
2514 structs)
2515 (while (re-search-forward box-re end t)
2516 (let ((element (org-element-at-point)))
2517 (when (eq (org-element-type element) 'item)
2518 (push (org-element-property :structure element)
2519 structs)
2520 ;; Skip whole list since we have its
2521 ;; structure anyway.
2522 (while (setq element (org-element-lineage
2523 element '(plain-list)))
2524 (goto-char
2525 (min (org-element-property :end element)
2526 end))))))
2527 ;; Cache count for cookies applying to the same
2528 ;; area. Then return it.
2529 (let ((count
2530 (funcall count-boxes
2531 (and (eq (org-element-type container)
2532 'item)
2533 (org-element-property
2534 :begin container))
2535 structs
2536 recursivep)))
2537 (push (cons beg count) cache)
2538 count))))))
2539 cookies-list))))
2540 ;; Apply alist to buffer.
2541 (dolist (cookie cookies-list)
2542 (let* ((beg (car cookie))
2543 (end (nth 1 cookie))
2544 (percent (nth 2 cookie))
2545 (checked (nth 3 cookie))
2546 (total (nth 4 cookie)))
2547 (goto-char beg)
2548 (insert
2549 (if percent (format "[%d%%]" (floor (* 100.0 checked)
2550 (max 1 total)))
2551 (format "[%d/%d]" checked total)))
2552 (delete-region (point) (+ (point) (- end beg)))
2553 (when org-auto-align-tags (org-fix-tags-on-the-fly)))))))
2555 (defun org-get-checkbox-statistics-face ()
2556 "Select the face for checkbox statistics.
2557 The face will be `org-done' when all relevant boxes are checked.
2558 Otherwise it will be `org-todo'."
2559 (if (match-end 1)
2560 (if (equal (match-string 1) "100%")
2561 'org-checkbox-statistics-done
2562 'org-checkbox-statistics-todo)
2563 (if (and (> (match-end 2) (match-beginning 2))
2564 (equal (match-string 2) (match-string 3)))
2565 'org-checkbox-statistics-done
2566 'org-checkbox-statistics-todo)))
2568 (defun org-update-checkbox-count-maybe (&optional all)
2569 "Update checkbox statistics unless turned off by user.
2570 With an optional argument ALL, update them in the whole buffer."
2571 (when (cdr (assq 'checkbox org-list-automatic-rules))
2572 (org-update-checkbox-count all))
2573 (run-hooks 'org-checkbox-statistics-hook))
2575 (defvar org-last-indent-begin-marker (make-marker))
2576 (defvar org-last-indent-end-marker (make-marker))
2577 (defun org-list-indent-item-generic (arg no-subtree struct)
2578 "Indent a local list item including its children.
2579 When number ARG is a negative, item will be outdented, otherwise
2580 it will be indented.
2582 If a region is active, all items inside will be moved.
2584 If NO-SUBTREE is non-nil, only indent the item itself, not its
2585 children.
2587 STRUCT is the list structure.
2589 Return t if successful."
2590 (save-excursion
2591 (let* ((regionp (org-region-active-p))
2592 (rbeg (and regionp (region-beginning)))
2593 (rend (and regionp (region-end)))
2594 (top (org-list-get-top-point struct))
2595 (parents (org-list-parents-alist struct))
2596 (prevs (org-list-prevs-alist struct))
2597 ;; Are we going to move the whole list?
2598 (specialp
2599 (and (not regionp)
2600 (= top (point-at-bol))
2601 (cdr (assq 'indent org-list-automatic-rules))
2602 (if no-subtree
2603 (user-error
2604 "At first item: use S-M-<left/right> to move the whole list")
2605 t))))
2606 ;; Determine begin and end points of zone to indent. If moving
2607 ;; more than one item, save them for subsequent moves.
2608 (unless (and (memq last-command '(org-shiftmetaright org-shiftmetaleft))
2609 (memq this-command '(org-shiftmetaright org-shiftmetaleft)))
2610 (if regionp
2611 (progn
2612 (set-marker org-last-indent-begin-marker rbeg)
2613 (set-marker org-last-indent-end-marker rend))
2614 (set-marker org-last-indent-begin-marker (point-at-bol))
2615 (set-marker org-last-indent-end-marker
2616 (cond
2617 (specialp (org-list-get-bottom-point struct))
2618 (no-subtree (1+ (point-at-bol)))
2619 (t (org-list-get-item-end (point-at-bol) struct))))))
2620 (let* ((beg (marker-position org-last-indent-begin-marker))
2621 (end (marker-position org-last-indent-end-marker)))
2622 (cond
2623 ;; Special case: moving top-item with indent rule.
2624 (specialp
2625 (let* ((level-skip (org-level-increment))
2626 (offset (if (< arg 0) (- level-skip) level-skip))
2627 (top-ind (org-list-get-ind beg struct))
2628 (old-struct (copy-tree struct)))
2629 (if (< (+ top-ind offset) 0)
2630 (error "Cannot outdent beyond margin")
2631 ;; Change bullet if necessary.
2632 (when (and (= (+ top-ind offset) 0)
2633 (string-match "*"
2634 (org-list-get-bullet beg struct)))
2635 (org-list-set-bullet beg struct
2636 (org-list-bullet-string "-")))
2637 ;; Shift every item by OFFSET and fix bullets. Then
2638 ;; apply changes to buffer.
2639 (mapc (lambda (e)
2640 (let ((ind (org-list-get-ind (car e) struct)))
2641 (org-list-set-ind (car e) struct (+ ind offset))))
2642 struct)
2643 (org-list-struct-fix-bul struct prevs)
2644 (org-list-struct-apply-struct struct old-struct))))
2645 ;; Forbidden move:
2646 ((and (< arg 0)
2647 ;; If only one item is moved, it mustn't have a child.
2648 (or (and no-subtree
2649 (not regionp)
2650 (org-list-has-child-p beg struct))
2651 ;; If a subtree or region is moved, the last item
2652 ;; of the subtree mustn't have a child.
2653 (let ((last-item (caar
2654 (reverse
2655 (cl-remove-if
2656 (lambda (e) (>= (car e) end))
2657 struct)))))
2658 (org-list-has-child-p last-item struct))))
2659 (error "Cannot outdent an item without its children"))
2660 ;; Normal shifting
2662 (let* ((new-parents
2663 (if (< arg 0)
2664 (org-list-struct-outdent beg end struct parents)
2665 (org-list-struct-indent beg end struct parents prevs))))
2666 (org-list-write-struct struct new-parents))
2667 (org-update-checkbox-count-maybe))))))
2670 (defun org-outdent-item ()
2671 "Outdent a local list item, but not its children.
2672 If a region is active, all items inside will be moved."
2673 (interactive)
2674 (let ((regionp (org-region-active-p)))
2675 (cond
2676 ((or (org-at-item-p)
2677 (and regionp
2678 (save-excursion (goto-char (region-beginning))
2679 (org-at-item-p))))
2680 (let ((struct (if (not regionp) (org-list-struct)
2681 (save-excursion (goto-char (region-beginning))
2682 (org-list-struct)))))
2683 (org-list-indent-item-generic -1 t struct)))
2684 (regionp (error "Region not starting at an item"))
2685 (t (error "Not at an item")))))
2687 (defun org-indent-item ()
2688 "Indent a local list item, but not its children.
2689 If a region is active, all items inside will be moved."
2690 (interactive)
2691 (let ((regionp (org-region-active-p)))
2692 (cond
2693 ((or (org-at-item-p)
2694 (and regionp
2695 (save-excursion (goto-char (region-beginning))
2696 (org-at-item-p))))
2697 (let ((struct (if (not regionp) (org-list-struct)
2698 (save-excursion (goto-char (region-beginning))
2699 (org-list-struct)))))
2700 (org-list-indent-item-generic 1 t struct)))
2701 (regionp (error "Region not starting at an item"))
2702 (t (error "Not at an item")))))
2704 (defun org-outdent-item-tree ()
2705 "Outdent a local list item including its children.
2706 If a region is active, all items inside will be moved."
2707 (interactive)
2708 (let ((regionp (org-region-active-p)))
2709 (cond
2710 ((or (org-at-item-p)
2711 (and regionp
2712 (save-excursion (goto-char (region-beginning))
2713 (org-at-item-p))))
2714 (let ((struct (if (not regionp) (org-list-struct)
2715 (save-excursion (goto-char (region-beginning))
2716 (org-list-struct)))))
2717 (org-list-indent-item-generic -1 nil struct)))
2718 (regionp (error "Region not starting at an item"))
2719 (t (error "Not at an item")))))
2721 (defun org-indent-item-tree ()
2722 "Indent a local list item including its children.
2723 If a region is active, all items inside will be moved."
2724 (interactive)
2725 (let ((regionp (org-region-active-p)))
2726 (cond
2727 ((or (org-at-item-p)
2728 (and regionp
2729 (save-excursion (goto-char (region-beginning))
2730 (org-at-item-p))))
2731 (let ((struct (if (not regionp) (org-list-struct)
2732 (save-excursion (goto-char (region-beginning))
2733 (org-list-struct)))))
2734 (org-list-indent-item-generic 1 nil struct)))
2735 (regionp (error "Region not starting at an item"))
2736 (t (error "Not at an item")))))
2738 (defvar org-tab-ind-state)
2739 (defvar org-adapt-indentation)
2740 (defun org-cycle-item-indentation ()
2741 "Cycle levels of indentation of an empty item.
2742 The first run indents the item, if applicable. Subsequent runs
2743 outdent it at meaningful levels in the list. When done, item is
2744 put back at its original position with its original bullet.
2746 Return t at each successful move."
2747 (when (org-at-item-p)
2748 (let* ((org-adapt-indentation nil)
2749 (struct (org-list-struct))
2750 (ind (org-list-get-ind (point-at-bol) struct))
2751 (bullet (org-trim (buffer-substring (point-at-bol) (point-at-eol)))))
2752 ;; Accept empty items or if cycle has already started.
2753 (when (or (eq last-command 'org-cycle-item-indentation)
2754 (and (save-excursion
2755 (beginning-of-line)
2756 (looking-at org-list-full-item-re))
2757 (>= (match-end 0) (save-excursion
2758 (goto-char (org-list-get-item-end
2759 (point-at-bol) struct))
2760 (skip-chars-backward " \r\t\n")
2761 (point)))))
2762 (setq this-command 'org-cycle-item-indentation)
2763 ;; When in the middle of the cycle, try to outdent first. If
2764 ;; it fails, and point is still at initial position, indent.
2765 ;; Else, re-create it at its original position.
2766 (if (eq last-command 'org-cycle-item-indentation)
2767 (cond
2768 ((ignore-errors (org-list-indent-item-generic -1 t struct)))
2769 ((and (= ind (car org-tab-ind-state))
2770 (ignore-errors (org-list-indent-item-generic 1 t struct))))
2771 (t (delete-region (point-at-bol) (point-at-eol))
2772 (indent-to-column (car org-tab-ind-state))
2773 (insert (cdr org-tab-ind-state) " ")
2774 ;; Break cycle
2775 (setq this-command 'identity)))
2776 ;; If a cycle is starting, remember indentation and bullet,
2777 ;; then try to indent. If it fails, try to outdent.
2778 (setq org-tab-ind-state (cons ind bullet))
2779 (cond
2780 ((ignore-errors (org-list-indent-item-generic 1 t struct)))
2781 ((ignore-errors (org-list-indent-item-generic -1 t struct)))
2782 (t (user-error "Cannot move item"))))
2783 t))))
2785 (defun org-sort-list
2786 (&optional with-case sorting-type getkey-func compare-func interactive?)
2787 "Sort list items.
2788 The cursor may be at any item of the list that should be sorted.
2789 Sublists are not sorted. Checkboxes, if any, are ignored.
2791 Sorting can be alphabetically, numerically, by date/time as given
2792 by a time stamp, by a property or by priority.
2794 Comparing entries ignores case by default. However, with an
2795 optional argument WITH-CASE, the sorting considers case as well,
2796 if the current locale allows for it.
2798 The command prompts for the sorting type unless it has been given
2799 to the function through the SORTING-TYPE argument, which needs to
2800 be a character, \(?n ?N ?a ?A ?t ?T ?f ?F ?x ?X). Here is the
2801 detailed meaning of each character:
2803 n Numerically, by converting the beginning of the item to a number.
2804 a Alphabetically. Only the first line of item is checked.
2805 t By date/time, either the first active time stamp in the entry, if
2806 any, or by the first inactive one. In a timer list, sort the timers.
2807 x By \"checked\" status of a check list.
2809 Capital letters will reverse the sort order.
2811 If the SORTING-TYPE is ?f or ?F, then GETKEY-FUNC specifies
2812 a function to be called with point at the beginning of the
2813 record. It must return a value that is compatible with COMPARE-FUNC,
2814 the function used to compare entries.
2816 Sorting is done against the visible part of the headlines, it
2817 ignores hidden links.
2819 A non-nil value for INTERACTIVE? is used to signal that this
2820 function is being called interactively."
2821 (interactive (list current-prefix-arg nil nil nil t))
2822 (let* ((case-func (if with-case 'identity 'downcase))
2823 (struct (org-list-struct))
2824 (prevs (org-list-prevs-alist struct))
2825 (start (org-list-get-list-begin (point-at-bol) struct prevs))
2826 (end (org-list-get-list-end (point-at-bol) struct prevs))
2827 (sorting-type
2828 (or sorting-type
2829 (progn
2830 (message
2831 "Sort plain list: [a]lpha [n]umeric [t]ime [f]unc [x]checked A/N/T/F/X means reversed:")
2832 (read-char-exclusive))))
2833 (dcst (downcase sorting-type))
2834 (getkey-func
2835 (and (= dcst ?f)
2836 (or getkey-func
2837 (and interactive?
2838 (org-read-function "Function for extracting keys: "))
2839 (error "Missing key extractor"))))
2840 (sort-func
2841 (cond
2842 ((= dcst ?a) #'org-string-collate-lessp)
2843 ((= dcst ?f)
2844 (or compare-func
2845 (and interactive?
2846 (org-read-function
2847 (concat "Function for comparing keys "
2848 "(empty for default `sort-subr' predicate): ")
2849 'allow-empty))))
2850 ((= dcst ?t) #'<)
2851 ((= dcst ?x) #'string<))))
2852 (message "Sorting items...")
2853 (save-restriction
2854 (narrow-to-region start end)
2855 (goto-char (point-min))
2856 (let* ((case-fold-search nil)
2857 (now (current-time))
2858 (next-record (lambda ()
2859 (skip-chars-forward " \r\t\n")
2860 (or (eobp) (beginning-of-line))))
2861 (end-record (lambda ()
2862 (goto-char (org-list-get-item-end-before-blank
2863 (point) struct))))
2864 (value-to-sort
2865 (lambda ()
2866 (when (looking-at "[ \t]*[-+*0-9.)]+\\([ \t]+\\[[- X]\\]\\)?[ \t]+")
2867 (cond
2868 ((= dcst ?n)
2869 (string-to-number
2870 (org-sort-remove-invisible
2871 (buffer-substring (match-end 0) (point-at-eol)))))
2872 ((= dcst ?a)
2873 (funcall case-func
2874 (org-sort-remove-invisible
2875 (buffer-substring
2876 (match-end 0) (point-at-eol)))))
2877 ((= dcst ?t)
2878 (cond
2879 ;; If it is a timer list, convert timer to seconds
2880 ((org-at-item-timer-p)
2881 (org-timer-hms-to-secs (match-string 1)))
2882 ((or (save-excursion
2883 (re-search-forward org-ts-regexp (point-at-eol) t))
2884 (save-excursion (re-search-forward org-ts-regexp-both
2885 (point-at-eol) t)))
2886 (org-time-string-to-seconds (match-string 0)))
2887 (t (float-time now))))
2888 ((= dcst ?x) (or (and (stringp (match-string 1))
2889 (match-string 1))
2890 ""))
2891 ((= dcst ?f)
2892 (if getkey-func
2893 (let ((value (funcall getkey-func)))
2894 (if (stringp value)
2895 (funcall case-func value)
2896 value))
2897 (error "Invalid key function `%s'" getkey-func)))
2898 (t (error "Invalid sorting type `%c'" sorting-type)))))))
2899 (sort-subr (/= dcst sorting-type)
2900 next-record
2901 end-record
2902 value-to-sort
2904 sort-func)
2905 ;; Read and fix list again, as `sort-subr' probably destroyed
2906 ;; its structure.
2907 (org-list-repair)
2908 (run-hooks 'org-after-sorting-entries-or-items-hook)
2909 (message "Sorting items...done")))))
2911 (defun org-toggle-item (arg)
2912 "Convert headings or normal lines to items, items to normal lines.
2913 If there is no active region, only the current line is considered.
2915 If the first non blank line in the region is a headline, convert
2916 all headlines to items, shifting text accordingly.
2918 If it is an item, convert all items to normal lines.
2920 If it is normal text, change region into a list of items.
2921 With a prefix argument ARG, change the region in a single item."
2922 (interactive "P")
2923 (let ((shift-text
2924 (lambda (ind end)
2925 ;; Shift text in current section to IND, from point to END.
2926 ;; The function leaves point to END line.
2927 (let ((min-i 1000) (end (copy-marker end)))
2928 ;; First determine the minimum indentation (MIN-I) of
2929 ;; the text.
2930 (save-excursion
2931 (catch 'exit
2932 (while (< (point) end)
2933 (let ((i (current-indentation)))
2934 (cond
2935 ;; Skip blank lines and inline tasks.
2936 ((looking-at "^[ \t]*$"))
2937 ((looking-at org-outline-regexp-bol))
2938 ;; We can't find less than 0 indentation.
2939 ((zerop i) (throw 'exit (setq min-i 0)))
2940 ((< i min-i) (setq min-i i))))
2941 (forward-line))))
2942 ;; Then indent each line so that a line indented to
2943 ;; MIN-I becomes indented to IND. Ignore blank lines
2944 ;; and inline tasks in the process.
2945 (let ((delta (- ind min-i)))
2946 (while (< (point) end)
2947 (unless (or (looking-at "^[ \t]*$")
2948 (looking-at org-outline-regexp-bol))
2949 (indent-line-to (+ (current-indentation) delta)))
2950 (forward-line))))))
2951 (skip-blanks
2952 (lambda (pos)
2953 ;; Return beginning of first non-blank line, starting from
2954 ;; line at POS.
2955 (save-excursion
2956 (goto-char pos)
2957 (skip-chars-forward " \r\t\n")
2958 (point-at-bol))))
2959 beg end)
2960 ;; Determine boundaries of changes.
2961 (if (org-region-active-p)
2962 (setq beg (funcall skip-blanks (region-beginning))
2963 end (copy-marker (region-end)))
2964 (setq beg (funcall skip-blanks (point-at-bol))
2965 end (copy-marker (point-at-eol))))
2966 ;; Depending on the starting line, choose an action on the text
2967 ;; between BEG and END.
2968 (org-with-limited-levels
2969 (save-excursion
2970 (goto-char beg)
2971 (cond
2972 ;; Case 1. Start at an item: de-itemize. Note that it only
2973 ;; happens when a region is active: `org-ctrl-c-minus'
2974 ;; would call `org-cycle-list-bullet' otherwise.
2975 ((org-at-item-p)
2976 (while (< (point) end)
2977 (when (org-at-item-p)
2978 (skip-chars-forward " \t")
2979 (delete-region (point) (match-end 0)))
2980 (forward-line)))
2981 ;; Case 2. Start at an heading: convert to items.
2982 ((org-at-heading-p)
2983 ;; Remove metadata
2984 (let (org-loop-over-headlines-in-active-region)
2985 (org-list--delete-metadata))
2986 (let* ((bul (org-list-bullet-string "-"))
2987 (bul-len (length bul))
2988 ;; Indentation of the first heading. It should be
2989 ;; relative to the indentation of its parent, if any.
2990 (start-ind (save-excursion
2991 (cond
2992 ((not org-adapt-indentation) 0)
2993 ((not (outline-previous-heading)) 0)
2994 (t (length (match-string 0))))))
2995 ;; Level of first heading. Further headings will be
2996 ;; compared to it to determine hierarchy in the list.
2997 (ref-level (org-reduced-level (org-outline-level))))
2998 (while (< (point) end)
2999 (let* ((level (org-reduced-level (org-outline-level)))
3000 (delta (max 0 (- level ref-level)))
3001 (todo-state (org-get-todo-state)))
3002 ;; If current headline is less indented than the first
3003 ;; one, set it as reference, in order to preserve
3004 ;; subtrees.
3005 (when (< level ref-level) (setq ref-level level))
3006 ;; Remove metadata
3007 (let (org-loop-over-headlines-in-active-region)
3008 (org-list--delete-metadata))
3009 ;; Remove stars and TODO keyword.
3010 (let ((case-fold-search nil)) (looking-at org-todo-line-regexp))
3011 (delete-region (point) (or (match-beginning 3)
3012 (line-end-position)))
3013 (insert bul)
3014 (indent-line-to (+ start-ind (* delta bul-len)))
3015 ;; Turn TODO keyword into a check box.
3016 (when todo-state
3017 (let* ((struct (org-list-struct))
3018 (old (copy-tree struct)))
3019 (org-list-set-checkbox
3020 (line-beginning-position)
3021 struct
3022 (if (member todo-state org-done-keywords)
3023 "[X]"
3024 "[ ]"))
3025 (org-list-write-struct struct
3026 (org-list-parents-alist struct)
3027 old)))
3028 ;; Ensure all text down to END (or SECTION-END) belongs
3029 ;; to the newly created item.
3030 (let ((section-end (save-excursion
3031 (or (outline-next-heading) (point)))))
3032 (forward-line)
3033 (funcall shift-text
3034 (+ start-ind (* (1+ delta) bul-len))
3035 (min end section-end)))))))
3036 ;; Case 3. Normal line with ARG: make the first line of region
3037 ;; an item, and shift indentation of others lines to
3038 ;; set them as item's body.
3039 (arg (let* ((bul (org-list-bullet-string "-"))
3040 (bul-len (length bul))
3041 (ref-ind (current-indentation)))
3042 (skip-chars-forward " \t")
3043 (insert bul)
3044 (forward-line)
3045 (while (< (point) end)
3046 ;; Ensure that lines less indented than first one
3047 ;; still get included in item body.
3048 (funcall shift-text
3049 (+ ref-ind bul-len)
3050 (min end (save-excursion (or (outline-next-heading)
3051 (point)))))
3052 (forward-line))))
3053 ;; Case 4. Normal line without ARG: turn each non-item line
3054 ;; into an item.
3056 (while (< (point) end)
3057 (unless (or (org-at-heading-p) (org-at-item-p))
3058 (when (looking-at "\\([ \t]*\\)\\(\\S-\\)")
3059 (replace-match
3060 (concat "\\1" (org-list-bullet-string "-") "\\2"))))
3061 (forward-line))))))))
3064 ;;; Send and receive lists
3066 (defun org-list-to-lisp (&optional delete)
3067 "Parse the list at point and maybe DELETE it.
3069 Return a list whose car is a symbol of list type, among
3070 `ordered', `unordered' and `descriptive'. Then, each item is
3071 a list of strings and other sub-lists.
3073 For example, the following list:
3075 1. first item
3076 + sub-item one
3077 + [X] sub-item two
3078 more text in first item
3079 2. [@3] last item
3081 is parsed as
3083 (ordered
3084 (\"first item\"
3085 (unordered
3086 (\"sub-item one\")
3087 (\"[X] sub-item two\"))
3088 \"more text in first item\")
3089 (\"[@3] last item\"))
3091 Point is left at list's end."
3092 (letrec ((struct (org-list-struct))
3093 (prevs (org-list-prevs-alist struct))
3094 (parents (org-list-parents-alist struct))
3095 (top (org-list-get-top-point struct))
3096 (bottom (org-list-get-bottom-point struct))
3097 (trim
3098 (lambda (text)
3099 ;; Remove indentation and final newline from TEXT.
3100 (org-remove-indentation
3101 (if (string-match-p "\n\\'" text)
3102 (substring text 0 -1)
3103 text))))
3104 (parse-sublist
3105 (lambda (e)
3106 ;; Return a list whose car is list type and cdr a list
3107 ;; of items' body.
3108 (cons (org-list-get-list-type (car e) struct prevs)
3109 (mapcar parse-item e))))
3110 (parse-item
3111 (lambda (e)
3112 ;; Return a list containing counter of item, if any,
3113 ;; text and any sublist inside it.
3114 (let* ((end (org-list-get-item-end e struct))
3115 (children (org-list-get-children e struct parents))
3116 (body
3117 (save-excursion
3118 (goto-char e)
3119 (looking-at "[ \t]*\\S-+[ \t]*")
3120 (list
3121 (funcall
3122 trim
3123 (concat
3124 (make-string (string-width (match-string 0)) ?\s)
3125 (buffer-substring-no-properties
3126 (match-end 0) (or (car children) end))))))))
3127 (while children
3128 (let* ((child (car children))
3129 (sub (org-list-get-all-items child struct prevs))
3130 (last-in-sub (car (last sub))))
3131 (push (funcall parse-sublist sub) body)
3132 ;; Remove whole sub-list from children.
3133 (setq children (cdr (memq last-in-sub children)))
3134 ;; There is a chunk of text belonging to the item
3135 ;; if last child doesn't end where next child
3136 ;; starts or where item ends.
3137 (let ((sub-end (org-list-get-item-end last-in-sub struct))
3138 (next (or (car children) end)))
3139 (when (/= sub-end next)
3140 (push (funcall
3141 trim
3142 (buffer-substring-no-properties sub-end next))
3143 body)))))
3144 (nreverse body)))))
3145 ;; Store output, take care of cursor position and deletion of
3146 ;; list, then return output.
3147 (prog1 (funcall parse-sublist (org-list-get-all-items top struct prevs))
3148 (goto-char top)
3149 (when delete
3150 (delete-region top bottom)
3151 (when (and (not (looking-at "[ \t]*$")) (looking-at org-list-end-re))
3152 (replace-match ""))))))
3154 (defun org-list-make-subtree ()
3155 "Convert the plain list at point into a subtree."
3156 (interactive)
3157 (if (not (ignore-errors (goto-char (org-in-item-p))))
3158 (error "Not in a list")
3159 (let ((list (save-excursion (org-list-to-lisp t))))
3160 (insert (org-list-to-subtree list)))))
3162 (defun org-list-to-generic (list params)
3163 "Convert a LIST parsed through `org-list-to-lisp' to a custom format.
3165 LIST is a list as returned by `org-list-to-lisp', which see.
3166 PARAMS is a property list of parameters used to tweak the output
3167 format.
3169 Valid parameters are:
3171 :backend, :raw
3173 Export back-end used as a basis to transcode elements of the
3174 list, when no specific parameter applies to it. It is also
3175 used to translate its contents. You can prevent this by
3176 setting :raw property to a non-nil value.
3178 :splice
3180 When non-nil, only export the contents of the top most plain
3181 list, effectively ignoring its opening and closing lines.
3183 :ustart, :uend
3185 Strings to start and end an unordered list. They can also be
3186 set to a function returning a string or nil, which will be
3187 called with the depth of the list, counting from 1.
3189 :ostart, :oend
3191 Strings to start and end an ordered list. They can also be set
3192 to a function returning a string or nil, which will be called
3193 with the depth of the list, counting from 1.
3195 :dstart, :dend
3197 Strings to start and end a descriptive list. They can also be
3198 set to a function returning a string or nil, which will be
3199 called with the depth of the list, counting from 1.
3201 :dtstart, :dtend, :ddstart, :ddend
3203 Strings to start and end a descriptive term.
3205 :istart, :iend
3207 Strings to start or end a list item, and to start a list item
3208 with a counter. They can also be set to a function returning
3209 a string or nil, which will be called with two arguments: the
3210 type of list and the depth of the item, counting from 1.
3212 :icount
3214 Strings to start a list item with a counter. It can also be
3215 set to a function returning a string or nil, which will be
3216 called with three arguments: the type of list, the depth of the
3217 item, counting from 1, and the counter. Its value, when
3218 non-nil, has precedence over `:istart'.
3220 :isep
3222 String used to separate items. It can also be set to
3223 a function returning a string or nil, which will be called with
3224 two arguments: the type of list and the depth of the item,
3225 counting from 1. It always start on a new line.
3227 :ifmt
3229 Function to be applied to the contents of every item. It is
3230 called with two arguments: the type of list and the contents.
3232 :cbon, :cboff, :cbtrans
3234 String to insert, respectively, an un-checked check-box,
3235 a checked check-box and a check-box in transitional state."
3236 (require 'ox)
3237 (let* ((backend (plist-get params :backend))
3238 (custom-backend
3239 (org-export-create-backend
3240 :parent (or backend 'org)
3241 :transcoders
3242 `((plain-list . ,(org-list--to-generic-plain-list params))
3243 (item . ,(org-list--to-generic-item params))
3244 (macro . (lambda (m c i) (org-element-macro-interpreter m nil))))))
3245 data info)
3246 ;; Write LIST back into Org syntax and parse it.
3247 (with-temp-buffer
3248 (let ((org-inhibit-startup t)) (org-mode))
3249 (letrec ((insert-list
3250 (lambda (l)
3251 (dolist (i (cdr l))
3252 (funcall insert-item i (car l)))))
3253 (insert-item
3254 (lambda (i type)
3255 (let ((start (point)))
3256 (insert (if (eq type 'ordered) "1. " "- "))
3257 (dolist (e i)
3258 (if (consp e) (funcall insert-list e)
3259 (insert e)
3260 (insert "\n")))
3261 (beginning-of-line)
3262 (save-excursion
3263 (let ((ind (if (eq type 'ordered) 3 2)))
3264 (while (> (point) start)
3265 (unless (looking-at-p "[ \t]*$")
3266 (indent-to ind))
3267 (forward-line -1))))))))
3268 (funcall insert-list list))
3269 (setf data
3270 (org-element-map (org-element-parse-buffer) 'plain-list
3271 #'identity nil t))
3272 (setf info (org-export-get-environment backend nil params)))
3273 (when (and backend (symbolp backend) (not (org-export-get-backend backend)))
3274 (user-error "Unknown :backend value"))
3275 (unless backend (require 'ox-org))
3276 ;; When`:raw' property has a non-nil value, turn all objects back
3277 ;; into Org syntax.
3278 (when (and backend (plist-get params :raw))
3279 (org-element-map data org-element-all-objects
3280 (lambda (object)
3281 (org-element-set-element
3282 object (org-element-interpret-data object)))))
3283 ;; We use a low-level mechanism to export DATA so as to skip all
3284 ;; usual pre-processing and post-processing, i.e., hooks, filters,
3285 ;; Babel code evaluation, include keywords and macro expansion,
3286 ;; and filters.
3287 (let ((output (org-export-data-with-backend data custom-backend info)))
3288 ;; Remove final newline.
3289 (if (org-string-nw-p output) (substring-no-properties output 0 -1) ""))))
3291 (defun org-list--depth (element)
3292 "Return the level of ELEMENT within current plain list.
3293 ELEMENT is either an item or a plain list."
3294 (cl-count-if (lambda (ancestor) (eq (org-element-type ancestor) 'plain-list))
3295 (org-element-lineage element nil t)))
3297 (defun org-list--trailing-newlines (string)
3298 "Return the number of trailing newlines in STRING."
3299 (with-temp-buffer
3300 (insert string)
3301 (skip-chars-backward " \t\n")
3302 (count-lines (line-beginning-position 2) (point-max))))
3304 (defun org-list--generic-eval (value &rest args)
3305 "Evaluate VALUE according to its type.
3306 VALUE is either nil, a string or a function. In the latter case,
3307 it is called with arguments ARGS."
3308 (cond ((null value) nil)
3309 ((stringp value) value)
3310 ((functionp value) (apply value args))
3311 (t (error "Wrong value: %s" value))))
3313 (defun org-list--to-generic-plain-list (params)
3314 "Return a transcoder for `plain-list' elements.
3315 PARAMS is a plist used to tweak the behavior of the transcoder."
3316 (let ((ustart (plist-get params :ustart))
3317 (uend (plist-get params :uend))
3318 (ostart (plist-get params :ostart))
3319 (oend (plist-get params :oend))
3320 (dstart (plist-get params :dstart))
3321 (dend (plist-get params :dend))
3322 (splice (plist-get params :splice))
3323 (backend (plist-get params :backend)))
3324 (lambda (plain-list contents info)
3325 (let* ((type (org-element-property :type plain-list))
3326 (depth (org-list--depth plain-list))
3327 (start (and (not splice)
3328 (org-list--generic-eval
3329 (pcase type
3330 (`ordered ostart)
3331 (`unordered ustart)
3332 (_ dstart))
3333 depth)))
3334 (end (and (not splice)
3335 (org-list--generic-eval
3336 (pcase type
3337 (`ordered oend)
3338 (`unordered uend)
3339 (_ dend))
3340 depth))))
3341 ;; Make sure trailing newlines in END appear in the output by
3342 ;; setting `:post-blank' property to their number.
3343 (when end
3344 (org-element-put-property
3345 plain-list :post-blank (org-list--trailing-newlines end)))
3346 ;; Build output.
3347 (concat (and start (concat start "\n"))
3348 (if (or start end splice (not backend))
3349 contents
3350 (org-export-with-backend backend plain-list contents info))
3351 end)))))
3353 (defun org-list--to-generic-item (params)
3354 "Return a transcoder for `item' elements.
3355 PARAMS is a plist used to tweak the behavior of the transcoder."
3356 (let ((backend (plist-get params :backend))
3357 (istart (plist-get params :istart))
3358 (iend (plist-get params :iend))
3359 (isep (plist-get params :isep))
3360 (icount (plist-get params :icount))
3361 (ifmt (plist-get params :ifmt))
3362 (cboff (plist-get params :cboff))
3363 (cbon (plist-get params :cbon))
3364 (cbtrans (plist-get params :cbtrans))
3365 (dtstart (plist-get params :dtstart))
3366 (dtend (plist-get params :dtend))
3367 (ddstart (plist-get params :ddstart))
3368 (ddend (plist-get params :ddend)))
3369 (lambda (item contents info)
3370 (let* ((type
3371 (org-element-property :type (org-element-property :parent item)))
3372 (tag (org-element-property :tag item))
3373 (depth (org-list--depth item))
3374 (separator (and (org-export-get-next-element item info)
3375 (org-list--generic-eval isep type depth)))
3376 (closing (pcase (org-list--generic-eval iend type depth)
3377 ((or `nil "") "\n")
3378 ((and (guard separator) s)
3379 (if (equal (substring s -1) "\n") s (concat s "\n")))
3380 (s s))))
3381 ;; When a closing line or a separator is provided, make sure
3382 ;; its trailing newlines are taken into account when building
3383 ;; output. This is done by setting `:post-blank' property to
3384 ;; the number of such lines in the last line to be added.
3385 (let ((last-string (or separator closing)))
3386 (when last-string
3387 (org-element-put-property
3388 item
3389 :post-blank
3390 (max (1- (org-list--trailing-newlines last-string)) 0))))
3391 ;; Build output.
3392 (concat
3393 (let ((c (org-element-property :counter item)))
3394 (if (and c icount) (org-list--generic-eval icount type depth c)
3395 (org-list--generic-eval istart type depth)))
3396 (let ((body
3397 (if (or istart iend icount ifmt cbon cboff cbtrans (not backend)
3398 (and (eq type 'descriptive)
3399 (or dtstart dtend ddstart ddend)))
3400 (concat
3401 (pcase (org-element-property :checkbox item)
3402 (`on cbon)
3403 (`off cboff)
3404 (`trans cbtrans))
3405 (and tag
3406 (concat dtstart
3407 (if backend
3408 (org-export-data-with-backend
3409 tag backend info)
3410 (org-element-interpret-data tag))
3411 dtend))
3412 (and tag ddstart)
3413 (let ((contents
3414 (if (= (length contents) 0) ""
3415 (substring contents 0 -1))))
3416 (if ifmt (org-list--generic-eval ifmt type contents)
3417 contents))
3418 (and tag ddend))
3419 (org-export-with-backend backend item contents info))))
3420 ;; Remove final newline.
3421 (if (equal body "") ""
3422 (substring (org-element-normalize-string body) 0 -1)))
3423 closing
3424 separator)))))
3426 (defun org-list-to-latex (list &optional params)
3427 "Convert LIST into a LaTeX list.
3428 LIST is a parsed plain list, as returned by `org-list-to-lisp'.
3429 PARAMS is a property list with overruling parameters for
3430 `org-list-to-generic'. Return converted list as a string."
3431 (require 'ox-latex)
3432 (org-list-to-generic list (org-combine-plists '(:backend latex) params)))
3434 (defun org-list-to-html (list &optional params)
3435 "Convert LIST into a HTML list.
3436 LIST is a parsed plain list, as returned by `org-list-to-lisp'.
3437 PARAMS is a property list with overruling parameters for
3438 `org-list-to-generic'. Return converted list as a string."
3439 (require 'ox-html)
3440 (org-list-to-generic list (org-combine-plists '(:backend html) params)))
3442 (defun org-list-to-texinfo (list &optional params)
3443 "Convert LIST into a Texinfo list.
3444 LIST is a parsed plain list, as returned by `org-list-to-lisp'.
3445 PARAMS is a property list with overruling parameters for
3446 `org-list-to-generic'. Return converted list as a string."
3447 (require 'ox-texinfo)
3448 (org-list-to-generic list (org-combine-plists '(:backend texinfo) params)))
3450 (defun org-list-to-org (list &optional params)
3451 "Convert LIST into an Org plain list.
3452 LIST is as returned by `org-list-parse-list'. PARAMS is a property list
3453 with overruling parameters for `org-list-to-generic'."
3454 (let* ((make-item
3455 (lambda (type _depth &optional c)
3456 (concat (if (eq type 'ordered) "1. " "- ")
3457 (and c (format "[@%d] " c)))))
3458 (defaults
3459 (list :istart make-item
3460 :icount make-item
3461 :ifmt (lambda (_type contents)
3462 (replace-regexp-in-string "\n" "\n " contents))
3463 :dtend " :: "
3464 :cbon "[X] "
3465 :cboff "[ ] "
3466 :cbtrans "[-] ")))
3467 (org-list-to-generic list (org-combine-plists defaults params))))
3469 (defun org-list-to-subtree (list &optional params)
3470 "Convert LIST into an Org subtree.
3471 LIST is as returned by `org-list-to-lisp'. PARAMS is a property
3472 list with overruling parameters for `org-list-to-generic'."
3473 (let* ((blank (pcase (cdr (assq 'heading org-blank-before-new-entry))
3474 (`t t)
3475 (`auto (save-excursion
3476 (org-with-limited-levels (outline-previous-heading))
3477 (org-previous-line-empty-p)))))
3478 (level (org-reduced-level (or (org-current-level) 0)))
3479 (make-stars
3480 (lambda (_type depth &optional _count)
3481 ;; Return the string for the heading, depending on DEPTH
3482 ;; of current sub-list.
3483 (let ((oddeven-level (+ level depth)))
3484 (concat (make-string (if org-odd-levels-only
3485 (1- (* 2 oddeven-level))
3486 oddeven-level)
3488 " ")))))
3489 (org-list-to-generic
3490 list
3491 (org-combine-plists
3492 (list :splice t
3493 :istart make-stars
3494 :icount make-stars
3495 :dtstart " " :dtend " "
3496 :isep (if blank "\n\n" "\n")
3497 :cbon "DONE " :cboff "TODO " :cbtrans "TODO ")
3498 params))))
3500 (provide 'org-list)
3502 ;;; org-list.el ends here