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