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