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