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