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