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