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