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