Merge branch 'origin-maint'
[org-mode.git] / lisp / org-list.el
blob531cdd5244cc2a0ff605a0185f9a467b0a7164b5
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 :tab "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* ((bul (org-trim (org-list-get-bullet item struct)))
1522 (new-bul-p (cdr (assoc bul org-list-demote-modify-bullet))))
1523 (when new-bul-p (org-list-set-bullet item struct new-bul-p))))))
1524 (ind
1525 (lambda (cell)
1526 (let* ((item (car cell))
1527 (parent (cdr cell)))
1528 (cond
1529 ;; Item not yet in zone: keep association.
1530 ((< item start) cell)
1531 ((>= item end)
1532 ;; Item out of zone: follow associations in ACC.
1533 (let ((convert (assq parent acc)))
1534 (if convert (cons item (cdr convert)) cell)))
1536 ;; Item is in zone...
1537 (let ((prev (org-list-get-prev-item item struct prevs)))
1538 ;; Check if bullet needs to be changed.
1539 (funcall change-bullet-maybe item)
1540 (cond
1541 ;; First item indented but not parent: error
1542 ((and (not prev) (< parent start))
1543 (error "Cannot indent the first item of a list"))
1544 ;; First item and parent indented: keep same
1545 ;; parent.
1546 ((not prev) (funcall set-assoc cell))
1547 ;; Previous item not indented: reparent to it.
1548 ((< prev start) (funcall set-assoc (cons item prev)))
1549 ;; Previous item indented: reparent like it.
1551 (funcall set-assoc
1552 (cons item (cdr (assq prev acc)))))))))))))
1553 (mapcar ind parents)))
1557 ;;; Repairing structures
1559 (defun org-list-use-alpha-bul-p (first struct prevs)
1560 "Non-nil if list starting at FIRST can have alphabetical bullets.
1562 STRUCT is list structure. PREVS is the alist of previous items,
1563 as returned by `org-list-prevs-alist'."
1564 (and org-alphabetical-lists
1565 (catch 'exit
1566 (let ((item first) (ascii 64) (case-fold-search nil))
1567 ;; Pretend that bullets are uppercase and check if alphabet
1568 ;; is sufficient, taking counters into account.
1569 (while item
1570 (let ((bul (org-list-get-bullet item struct))
1571 (count (org-list-get-counter item struct)))
1572 ;; Virtually determine current bullet
1573 (if (and count (string-match "[a-zA-Z]" count))
1574 ;; Counters are not case-sensitive.
1575 (setq ascii (string-to-char (upcase count)))
1576 (setq ascii (1+ ascii)))
1577 ;; Test if bullet would be over z or Z.
1578 (if (> ascii 90)
1579 (throw 'exit nil)
1580 (setq item (org-list-get-next-item item struct prevs)))))
1581 ;; All items checked. All good.
1582 t))))
1584 (defun org-list-inc-bullet-maybe (bullet)
1585 "Increment BULLET if applicable."
1586 (let ((case-fold-search nil))
1587 (cond
1588 ;; Num bullet: increment it.
1589 ((string-match "[0-9]+" bullet)
1590 (replace-match
1591 (number-to-string (1+ (string-to-number (match-string 0 bullet))))
1592 nil nil bullet))
1593 ;; Alpha bullet: increment it.
1594 ((string-match "[A-Za-z]" bullet)
1595 (replace-match
1596 (char-to-string (1+ (string-to-char (match-string 0 bullet))))
1597 nil nil bullet))
1598 ;; Unordered bullet: leave it.
1599 (t bullet))))
1601 (defun org-list-struct-fix-bul (struct prevs)
1602 "Verify and correct bullets in STRUCT.
1603 PREVS is the alist of previous items, as returned by
1604 `org-list-prevs-alist'.
1606 This function modifies STRUCT."
1607 (let ((case-fold-search nil)
1608 (fix-bul
1609 (function
1610 ;; Set bullet of ITEM in STRUCT, depending on the type of
1611 ;; first item of the list, the previous bullet and counter
1612 ;; if any.
1613 (lambda (item)
1614 (let* ((prev (org-list-get-prev-item item struct prevs))
1615 (prev-bul (and prev (org-list-get-bullet prev struct)))
1616 (counter (org-list-get-counter item struct))
1617 (bullet (org-list-get-bullet item struct))
1618 (alphap (and (not prev)
1619 (org-list-use-alpha-bul-p item struct prevs))))
1620 (org-list-set-bullet
1621 item struct
1622 (org-list-bullet-string
1623 (cond
1624 ;; Alpha counter in alpha list: use counter.
1625 ((and prev counter
1626 (string-match "[a-zA-Z]" counter)
1627 (string-match "[a-zA-Z]" prev-bul))
1628 ;; Use cond to be sure `string-match' is used in
1629 ;; both cases.
1630 (let ((real-count
1631 (cond
1632 ((string-match "[a-z]" prev-bul) (downcase counter))
1633 ((string-match "[A-Z]" prev-bul) (upcase counter)))))
1634 (replace-match real-count nil nil prev-bul)))
1635 ;; Num counter in a num list: use counter.
1636 ((and prev counter
1637 (string-match "[0-9]+" counter)
1638 (string-match "[0-9]+" prev-bul))
1639 (replace-match counter nil nil prev-bul))
1640 ;; No counter: increase, if needed, previous bullet.
1641 (prev
1642 (org-list-inc-bullet-maybe (org-list-get-bullet prev struct)))
1643 ;; Alpha counter at first item: use counter.
1644 ((and counter (org-list-use-alpha-bul-p item struct prevs)
1645 (string-match "[A-Za-z]" counter)
1646 (string-match "[A-Za-z]" bullet))
1647 (let ((real-count
1648 (cond
1649 ((string-match "[a-z]" bullet) (downcase counter))
1650 ((string-match "[A-Z]" bullet) (upcase counter)))))
1651 (replace-match real-count nil nil bullet)))
1652 ;; Num counter at first item: use counter.
1653 ((and counter
1654 (string-match "[0-9]+" counter)
1655 (string-match "[0-9]+" bullet))
1656 (replace-match counter nil nil bullet))
1657 ;; First bullet is alpha uppercase: use "A".
1658 ((and alphap (string-match "[A-Z]" bullet))
1659 (replace-match "A" nil nil bullet))
1660 ;; First bullet is alpha lowercase: use "a".
1661 ((and alphap (string-match "[a-z]" bullet))
1662 (replace-match "a" nil nil bullet))
1663 ;; First bullet is num: use "1".
1664 ((string-match "\\([0-9]+\\|[A-Za-z]\\)" bullet)
1665 (replace-match "1" nil nil bullet))
1666 ;; Not an ordered list: keep bullet.
1667 (t bullet)))))))))
1668 (mapc fix-bul (mapcar 'car struct))))
1670 (defun org-list-struct-fix-ind (struct parents &optional bullet-size)
1671 "Verify and correct indentation in STRUCT.
1673 PARENTS is the alist of parents, as returned by
1674 `org-list-parents-alist'.
1676 If numeric optional argument BULLET-SIZE is set, assume all
1677 bullets in list have this length to determine new indentation.
1679 This function modifies STRUCT."
1680 (let* ((ancestor (org-list-get-top-point struct))
1681 (top-ind (org-list-get-ind ancestor struct))
1682 (new-ind
1683 (lambda (item)
1684 (let ((parent (org-list-get-parent item struct parents)))
1685 (if parent
1686 ;; Indent like parent + length of parent's bullet +
1687 ;; sub-list offset.
1688 (org-list-set-ind
1689 item struct (+ (or bullet-size
1690 (length
1691 (org-list-get-bullet parent struct)))
1692 (org-list-get-ind parent struct)
1693 org-list-indent-offset))
1694 ;; If no parent, indent like top-point.
1695 (org-list-set-ind item struct top-ind))))))
1696 (mapc new-ind (mapcar 'car (cdr struct)))))
1698 (defun org-list-struct-fix-box (struct parents prevs &optional ordered)
1699 "Verify and correct checkboxes in STRUCT.
1701 PARENTS is the alist of parents and PREVS is the alist of
1702 previous items, as returned by, respectively,
1703 `org-list-parents-alist' and `org-list-prevs-alist'.
1705 If ORDERED is non-nil, a checkbox can only be checked when every
1706 checkbox before it is checked too. If there was an attempt to
1707 break this rule, the function will return the blocking item. In
1708 all others cases, the return value will be nil.
1710 This function modifies STRUCT."
1711 (let ((all-items (mapcar 'car struct))
1712 (set-parent-box
1713 (function
1714 (lambda (item)
1715 (let* ((box-list
1716 (mapcar (lambda (child)
1717 (org-list-get-checkbox child struct))
1718 (org-list-get-children item struct parents))))
1719 (org-list-set-checkbox
1720 item struct
1721 (cond
1722 ((and (member "[ ]" box-list) (member "[X]" box-list)) "[-]")
1723 ((member "[-]" box-list) "[-]")
1724 ((member "[X]" box-list) "[X]")
1725 ((member "[ ]" box-list) "[ ]")
1726 ;; Parent has no boxed child: leave box as-is.
1727 (t (org-list-get-checkbox item struct))))))))
1728 parent-list)
1729 ;; 1. List all parents with a checkbox.
1730 (mapc
1731 (lambda (e)
1732 (let* ((parent (org-list-get-parent e struct parents))
1733 (parent-box-p (org-list-get-checkbox parent struct)))
1734 (when (and parent-box-p (not (memq parent parent-list)))
1735 (push parent parent-list))))
1736 all-items)
1737 ;; 2. Sort those parents by decreasing indentation.
1738 (setq parent-list (sort parent-list
1739 (lambda (e1 e2)
1740 (> (org-list-get-ind e1 struct)
1741 (org-list-get-ind e2 struct)))))
1742 ;; 3. For each parent, get all children's checkboxes to determine
1743 ;; and set its checkbox accordingly.
1744 (mapc set-parent-box parent-list)
1745 ;; 4. If ORDERED is set, see if we need to uncheck some boxes.
1746 (when ordered
1747 (let* ((box-list
1748 (mapcar (lambda (e) (org-list-get-checkbox e struct)) all-items))
1749 (after-unchecked (member "[ ]" box-list)))
1750 ;; There are boxes checked after an unchecked one: fix that.
1751 (when (member "[X]" after-unchecked)
1752 (let ((index (- (length struct) (length after-unchecked))))
1753 (mapc (lambda (e) (org-list-set-checkbox e struct "[ ]"))
1754 (nthcdr index all-items))
1755 ;; Verify once again the structure, without ORDERED.
1756 (org-list-struct-fix-box struct parents prevs nil)
1757 ;; Return blocking item.
1758 (nth index all-items)))))))
1760 (defun org-list-struct-fix-item-end (struct)
1761 "Verify and correct each item end position in STRUCT.
1763 This function modifies STRUCT."
1764 (let (end-list acc-end)
1765 (mapc (lambda (e)
1766 (let* ((pos (car e))
1767 (ind-pos (org-list-get-ind pos struct))
1768 (end-pos (org-list-get-item-end pos struct)))
1769 (unless (assq end-pos struct)
1770 ;; To determine real ind of an ending position that is
1771 ;; not at an item, we have to find the item it belongs
1772 ;; to: it is the last item (ITEM-UP), whose ending is
1773 ;; further than the position we're interested in.
1774 (let ((item-up (assoc-default end-pos acc-end '>)))
1775 (push (cons
1776 ;; Else part is for the bottom point.
1777 (if item-up (+ (org-list-get-ind item-up struct) 2) 0)
1778 end-pos)
1779 end-list)))
1780 (push (cons ind-pos pos) end-list)
1781 (push (cons end-pos pos) acc-end)))
1782 struct)
1783 (setq end-list (sort end-list (lambda (e1 e2) (< (cdr e1) (cdr e2)))))
1784 (org-list-struct-assoc-end struct end-list)))
1786 (defun org-list-struct-apply-struct (struct old-struct)
1787 "Apply set difference between STRUCT and OLD-STRUCT to the buffer.
1789 OLD-STRUCT is the structure before any modifications, and STRUCT
1790 the structure to be applied. The function will only modify parts
1791 of the list which have changed.
1793 Initial position of cursor is restored after the changes."
1794 (let* ((origin (point-marker))
1795 (inlinetask-re (and (featurep 'org-inlinetask)
1796 (org-inlinetask-outline-regexp)))
1797 (item-re (org-item-re))
1798 (box-rule-p (cdr (assq 'checkbox org-list-automatic-rules)))
1799 (shift-body-ind
1800 (function
1801 ;; Shift the indentation between END and BEG by DELTA.
1802 ;; Start from the line before END.
1803 (lambda (end beg delta)
1804 (goto-char end)
1805 (skip-chars-backward " \r\t\n")
1806 (beginning-of-line)
1807 (while (or (> (point) beg)
1808 (and (= (point) beg)
1809 (not (looking-at item-re))))
1810 (cond
1811 ;; Skip inline tasks.
1812 ((and inlinetask-re (looking-at inlinetask-re))
1813 (org-inlinetask-goto-beginning))
1814 ;; Shift only non-empty lines.
1815 ((org-looking-at-p "^[ \t]*\\S-")
1816 (let ((i (org-get-indentation)))
1817 (org-indent-line-to (+ i delta)))))
1818 (forward-line -1)))))
1819 (modify-item
1820 (function
1821 ;; Replace ITEM first line elements with new elements from
1822 ;; STRUCT, if appropriate.
1823 (lambda (item)
1824 (goto-char item)
1825 (let* ((new-ind (org-list-get-ind item struct))
1826 (old-ind (org-get-indentation))
1827 (new-bul (org-list-bullet-string
1828 (org-list-get-bullet item struct)))
1829 (old-bul (org-list-get-bullet item old-struct))
1830 (new-box (org-list-get-checkbox item struct)))
1831 (looking-at org-list-full-item-re)
1832 ;; a. Replace bullet
1833 (unless (equal old-bul new-bul)
1834 (replace-match new-bul nil nil nil 1))
1835 ;; b. Replace checkbox.
1836 (cond
1837 ((and new-box box-rule-p
1838 (save-match-data (org-at-item-description-p)))
1839 (message "Cannot add a checkbox to a description list item"))
1840 ((equal (match-string 3) new-box))
1841 ((and (match-string 3) new-box)
1842 (replace-match new-box nil nil nil 3))
1843 ((match-string 3)
1844 (looking-at ".*?\\([ \t]*\\[[ X-]\\]\\)")
1845 (replace-match "" nil nil nil 1))
1846 (t (let ((counterp (match-end 2)))
1847 (goto-char (if counterp (1+ counterp) (match-end 1)))
1848 (insert (concat new-box (unless counterp " "))))))
1849 ;; c. Indent item to appropriate column.
1850 (unless (= new-ind old-ind)
1851 (delete-region (goto-char (point-at-bol))
1852 (progn (skip-chars-forward " \t") (point)))
1853 (indent-to new-ind)))))))
1854 ;; 1. First get list of items and position endings. We maintain
1855 ;; two alists: ITM-SHIFT, determining indentation shift needed
1856 ;; at item, and END-POS, a pseudo-alist where key is ending
1857 ;; position and value point.
1858 (let (end-list acc-end itm-shift all-ends sliced-struct)
1859 (mapc (lambda (e)
1860 (let* ((pos (car e))
1861 (ind-pos (org-list-get-ind pos struct))
1862 (ind-old (org-list-get-ind pos old-struct))
1863 (bul-pos (org-list-get-bullet pos struct))
1864 (bul-old (org-list-get-bullet pos old-struct))
1865 (ind-shift (- (+ ind-pos (length bul-pos))
1866 (+ ind-old (length bul-old))))
1867 (end-pos (org-list-get-item-end pos old-struct)))
1868 (push (cons pos ind-shift) itm-shift)
1869 (unless (assq end-pos old-struct)
1870 ;; To determine real ind of an ending position that
1871 ;; is not at an item, we have to find the item it
1872 ;; belongs to: it is the last item (ITEM-UP), whose
1873 ;; ending is further than the position we're
1874 ;; interested in.
1875 (let ((item-up (assoc-default end-pos acc-end '>)))
1876 (push (cons end-pos item-up) end-list)))
1877 (push (cons end-pos pos) acc-end)))
1878 old-struct)
1879 ;; 2. Slice the items into parts that should be shifted by the
1880 ;; same amount of indentation. The slices are returned in
1881 ;; reverse order so changes modifying buffer do not change
1882 ;; positions they refer to.
1883 (setq all-ends (sort (append (mapcar 'car itm-shift)
1884 (org-uniquify (mapcar 'car end-list)))
1885 '<))
1886 (while (cdr all-ends)
1887 (let* ((up (pop all-ends))
1888 (down (car all-ends))
1889 (ind (if (assq up struct)
1890 (cdr (assq up itm-shift))
1891 (cdr (assq (cdr (assq up end-list)) itm-shift)))))
1892 (push (list down up ind) sliced-struct)))
1893 ;; 3. Shift each slice in buffer, provided delta isn't 0, from
1894 ;; end to beginning. Take a special action when beginning is
1895 ;; at item bullet.
1896 (mapc (lambda (e)
1897 (unless (zerop (nth 2 e)) (apply shift-body-ind e))
1898 (let* ((beg (nth 1 e))
1899 (cell (assq beg struct)))
1900 (unless (or (not cell) (equal cell (assq beg old-struct)))
1901 (funcall modify-item beg))))
1902 sliced-struct))
1903 ;; 4. Go back to initial position and clean marker.
1904 (goto-char origin)
1905 (move-marker origin nil)))
1907 (defun org-list-write-struct (struct parents &optional old-struct)
1908 "Correct bullets, checkboxes and indentation in list at point.
1910 STRUCT is the list structure. PARENTS is the alist of parents,
1911 as returned by `org-list-parents-alist'.
1913 When non-nil, optional argument OLD-STRUCT is the reference
1914 structure of the list. It should be provided whenever STRUCT
1915 doesn't correspond anymore to the real list in buffer."
1916 ;; Order of functions matters here: checkboxes and endings need
1917 ;; correct indentation to be set, and indentation needs correct
1918 ;; bullets.
1920 ;; 0. Save a copy of structure before modifications
1921 (let ((old-struct (or old-struct (copy-tree struct))))
1922 ;; 1. Set a temporary, but coherent with PARENTS, indentation in
1923 ;; order to get items endings and bullets properly
1924 (org-list-struct-fix-ind struct parents 2)
1925 ;; 2. Fix each item end to get correct prevs alist.
1926 (org-list-struct-fix-item-end struct)
1927 ;; 3. Get bullets right.
1928 (let ((prevs (org-list-prevs-alist struct)))
1929 (org-list-struct-fix-bul struct prevs)
1930 ;; 4. Now get real indentation.
1931 (org-list-struct-fix-ind struct parents)
1932 ;; 5. Eventually fix checkboxes.
1933 (org-list-struct-fix-box struct parents prevs))
1934 ;; 6. Apply structure modifications to buffer.
1935 (org-list-struct-apply-struct struct old-struct)))
1939 ;;; Misc Tools
1941 (defun org-apply-on-list (function init-value &rest args)
1942 "Call FUNCTION on each item of the list at point.
1943 FUNCTION must be called with at least one argument: INIT-VALUE,
1944 that will contain the value returned by the function at the
1945 previous item, plus ARGS extra arguments.
1947 FUNCTION is applied on items in reverse order.
1949 As an example, \(org-apply-on-list \(lambda \(result\) \(1+ result\)\) 0\)
1950 will return the number of items in the current list.
1952 Sublists of the list are skipped. Cursor is always at the
1953 beginning of the item."
1954 (let* ((struct (org-list-struct))
1955 (prevs (org-list-prevs-alist struct))
1956 (item (copy-marker (point-at-bol)))
1957 (all (org-list-get-all-items (marker-position item) struct prevs))
1958 (value init-value))
1959 (mapc (lambda (e)
1960 (goto-char e)
1961 (setq value (apply function value args)))
1962 (nreverse all))
1963 (goto-char item)
1964 (move-marker item nil)
1965 value))
1967 (defun org-list-set-item-visibility (item struct view)
1968 "Set visibility of ITEM in STRUCT to VIEW.
1970 Possible values are: `folded', `children' or `subtree'. See
1971 `org-cycle' for more information."
1972 (cond
1973 ((eq view 'folded)
1974 (let ((item-end (org-list-get-item-end-before-blank item struct)))
1975 ;; Hide from eol
1976 (outline-flag-region (save-excursion (goto-char item) (point-at-eol))
1977 item-end t)))
1978 ((eq view 'children)
1979 ;; First show everything.
1980 (org-list-set-item-visibility item struct 'subtree)
1981 ;; Then fold every child.
1982 (let* ((parents (org-list-parents-alist struct))
1983 (children (org-list-get-children item struct parents)))
1984 (mapc (lambda (e)
1985 (org-list-set-item-visibility e struct 'folded))
1986 children)))
1987 ((eq view 'subtree)
1988 ;; Show everything
1989 (let ((item-end (org-list-get-item-end item struct)))
1990 (outline-flag-region item item-end nil)))))
1992 (defun org-list-item-body-column (item)
1993 "Return column at which body of ITEM should start."
1994 (let (bpos bcol tpos tcol)
1995 (save-excursion
1996 (goto-char item)
1997 (looking-at "[ \t]*\\(\\S-+\\)\\(.*[ \t]+::\\)?[ \t]+")
1998 (setq bpos (match-beginning 1) tpos (match-end 0)
1999 bcol (progn (goto-char bpos) (current-column))
2000 tcol (progn (goto-char tpos) (current-column)))
2001 (when (> tcol (+ bcol org-description-max-indent))
2002 (setq tcol (+ bcol 5))))
2003 tcol))
2007 ;;; Interactive functions
2009 (defalias 'org-list-get-item-begin 'org-in-item-p)
2011 (defun org-beginning-of-item ()
2012 "Go to the beginning of the current item.
2013 Throw an error when not in a list."
2014 (interactive)
2015 (let ((begin (org-in-item-p)))
2016 (if begin (goto-char begin) (error "Not in an item"))))
2018 (defun org-beginning-of-item-list ()
2019 "Go to the beginning item of the current list or sublist.
2020 Throw an error when not in a list."
2021 (interactive)
2022 (let ((begin (org-in-item-p)))
2023 (if (not begin)
2024 (error "Not in an item")
2025 (goto-char begin)
2026 (let* ((struct (org-list-struct))
2027 (prevs (org-list-prevs-alist struct)))
2028 (goto-char (org-list-get-list-begin begin struct prevs))))))
2030 (defun org-end-of-item-list ()
2031 "Go to the end of the current list or sublist.
2032 Throw an error when not in a list."
2033 (interactive)
2034 (let ((begin (org-in-item-p)))
2035 (if (not begin)
2036 (error "Not in an item")
2037 (goto-char begin)
2038 (let* ((struct (org-list-struct))
2039 (prevs (org-list-prevs-alist struct)))
2040 (goto-char (org-list-get-list-end begin struct prevs))))))
2042 (defun org-end-of-item ()
2043 "Go to the end of the current item.
2044 Throw an error when not in a list."
2045 (interactive)
2046 (let ((begin (org-in-item-p)))
2047 (if (not begin)
2048 (error "Not in an item")
2049 (goto-char begin)
2050 (let ((struct (org-list-struct)))
2051 (goto-char (org-list-get-item-end begin struct))))))
2053 (defun org-previous-item ()
2054 "Move to the beginning of the previous item.
2055 Throw an error when not in a list. Also throw an error when at
2056 first item, unless `org-list-use-circular-motion' is non-nil."
2057 (interactive)
2058 (let ((item (org-in-item-p)))
2059 (if (not item)
2060 (error "Not in an item")
2061 (goto-char item)
2062 (let* ((struct (org-list-struct))
2063 (prevs (org-list-prevs-alist struct))
2064 (prevp (org-list-get-prev-item item struct prevs)))
2065 (cond
2066 (prevp (goto-char prevp))
2067 (org-list-use-circular-motion
2068 (goto-char (org-list-get-last-item item struct prevs)))
2069 (t (error "On first item")))))))
2071 (defun org-next-item ()
2072 "Move to the beginning of the next item.
2073 Throw an error when not in a list. Also throw an error when at
2074 last item, unless `org-list-use-circular-motion' is non-nil."
2075 (interactive)
2076 (let ((item (org-in-item-p)))
2077 (if (not item)
2078 (error "Not in an item")
2079 (goto-char item)
2080 (let* ((struct (org-list-struct))
2081 (prevs (org-list-prevs-alist struct))
2082 (prevp (org-list-get-next-item item struct prevs)))
2083 (cond
2084 (prevp (goto-char prevp))
2085 (org-list-use-circular-motion
2086 (goto-char (org-list-get-first-item item struct prevs)))
2087 (t (error "On last item")))))))
2089 (defun org-move-item-down ()
2090 "Move the item at point down, i.e. swap with following item.
2091 Sub-items (items with larger indentation) are considered part of
2092 the item, so this really moves item trees."
2093 (interactive)
2094 (unless (org-at-item-p) (error "Not at an item"))
2095 (let* ((col (current-column))
2096 (item (point-at-bol))
2097 (struct (org-list-struct))
2098 (prevs (org-list-prevs-alist struct))
2099 (next-item (org-list-get-next-item (point-at-bol) struct prevs)))
2100 (unless (or next-item org-list-use-circular-motion)
2101 (error "Cannot move this item further down"))
2102 (if (not next-item)
2103 (setq struct (org-list-send-item item 'begin struct))
2104 (setq struct (org-list-swap-items item next-item struct))
2105 (goto-char
2106 (org-list-get-next-item item struct (org-list-prevs-alist struct))))
2107 (org-list-write-struct struct (org-list-parents-alist struct))
2108 (org-move-to-column col)))
2110 (defun org-move-item-up ()
2111 "Move the item at point up, i.e. swap with previous item.
2112 Sub-items (items with larger indentation) are considered part of
2113 the item, so this really moves item trees."
2114 (interactive)
2115 (unless (org-at-item-p) (error "Not at an item"))
2116 (let* ((col (current-column))
2117 (item (point-at-bol))
2118 (struct (org-list-struct))
2119 (prevs (org-list-prevs-alist struct))
2120 (prev-item (org-list-get-prev-item (point-at-bol) struct prevs)))
2121 (unless (or prev-item org-list-use-circular-motion)
2122 (error "Cannot move this item further up"))
2123 (if (not prev-item)
2124 (setq struct (org-list-send-item item 'end struct))
2125 (setq struct (org-list-swap-items prev-item item struct)))
2126 (org-list-write-struct struct (org-list-parents-alist struct))
2127 (org-move-to-column col)))
2129 (defun org-insert-item (&optional checkbox)
2130 "Insert a new item at the current level.
2131 If cursor is before first character after bullet of the item, the
2132 new item will be created before the current one.
2134 If CHECKBOX is non-nil, add a checkbox next to the bullet.
2136 Return t when things worked, nil when we are not in an item, or
2137 item is invisible."
2138 (let ((itemp (org-in-item-p))
2139 (pos (point)))
2140 ;; If cursor isn't is a list or if list is invisible, return nil.
2141 (unless (or (not itemp)
2142 (save-excursion
2143 (goto-char itemp)
2144 (outline-invisible-p)))
2145 (if (save-excursion
2146 (goto-char itemp)
2147 (org-at-item-timer-p))
2148 ;; Timer list: delegate to `org-timer-item'.
2149 (progn (org-timer-item) t)
2150 (let* ((struct (save-excursion (goto-char itemp)
2151 (org-list-struct)))
2152 (prevs (org-list-prevs-alist struct))
2153 ;; If we're in a description list, ask for the new term.
2154 (desc (when (org-list-get-tag itemp struct)
2155 (concat (read-string "Term: ") " :: ")))
2156 ;; Don't insert a checkbox if checkbox rule is applied
2157 ;; and it is a description item.
2158 (checkp (and checkbox
2159 (or (not desc)
2160 (not (cdr (assq 'checkbox
2161 org-list-automatic-rules)))))))
2162 (setq struct
2163 (org-list-insert-item pos struct prevs checkp desc))
2164 (org-list-write-struct struct (org-list-parents-alist struct))
2165 (when checkp (org-update-checkbox-count-maybe))
2166 (looking-at org-list-full-item-re)
2167 (goto-char (match-end 0))
2168 t)))))
2170 (defun org-mark-list ()
2171 "Mark the current list.
2172 If this is a sublist, only mark the sublist."
2173 (interactive)
2174 (let* ((item (org-list-get-item-begin))
2175 (struct (org-list-struct))
2176 (prevs (org-list-prevs-alist struct))
2177 (lbeg (org-list-get-list-begin item struct prevs))
2178 (lend (org-list-get-list-end item struct prevs)))
2179 (push-mark lend nil t)
2180 (goto-char lbeg)))
2182 (defun org-list-repair ()
2183 "Fix indentation, bullets and checkboxes is the list at point."
2184 (interactive)
2185 (unless (org-at-item-p) (error "This is not a list"))
2186 (let* ((struct (org-list-struct))
2187 (parents (org-list-parents-alist struct)))
2188 (org-list-write-struct struct parents)))
2190 (defun org-cycle-list-bullet (&optional which)
2191 "Cycle through the different itemize/enumerate bullets.
2192 This cycle the entire list level through the sequence:
2194 `-' -> `+' -> `*' -> `1.' -> `1)'
2196 If WHICH is a valid string, use that as the new bullet. If WHICH
2197 is an integer, 0 means `-', 1 means `+' etc. If WHICH is
2198 `previous', cycle backwards."
2199 (interactive "P")
2200 (unless (org-at-item-p) (error "Not at an item"))
2201 (save-excursion
2202 (beginning-of-line)
2203 (let* ((struct (org-list-struct))
2204 (parents (org-list-parents-alist struct))
2205 (prevs (org-list-prevs-alist struct))
2206 (list-beg (org-list-get-first-item (point) struct prevs))
2207 (bullet (org-list-get-bullet list-beg struct))
2208 (bullet-rule-p (cdr (assq 'bullet org-list-automatic-rules)))
2209 (alpha-p (org-list-use-alpha-bul-p list-beg struct prevs))
2210 (case-fold-search nil)
2211 (current (cond
2212 ((string-match "[a-z]\\." bullet) "a.")
2213 ((string-match "[a-z])" bullet) "a)")
2214 ((string-match "[A-Z]\\." bullet) "A.")
2215 ((string-match "[A-Z])" bullet) "A)")
2216 ((string-match "\\." bullet) "1.")
2217 ((string-match ")" bullet) "1)")
2218 (t (org-trim bullet))))
2219 ;; Compute list of possible bullets, depending on context.
2220 (bullet-list
2221 (append '("-" "+" )
2222 ;; *-bullets are not allowed at column 0.
2223 (unless (and bullet-rule-p
2224 (looking-at "\\S-")) '("*"))
2225 ;; Description items cannot be numbered.
2226 (unless (or (eq org-plain-list-ordered-item-terminator ?\))
2227 (and bullet-rule-p (org-at-item-description-p)))
2228 '("1."))
2229 (unless (or (eq org-plain-list-ordered-item-terminator ?.)
2230 (and bullet-rule-p (org-at-item-description-p)))
2231 '("1)"))
2232 (unless (or (not alpha-p)
2233 (eq org-plain-list-ordered-item-terminator ?\))
2234 (and bullet-rule-p (org-at-item-description-p)))
2235 '("a." "A."))
2236 (unless (or (not alpha-p)
2237 (eq org-plain-list-ordered-item-terminator ?.)
2238 (and bullet-rule-p (org-at-item-description-p)))
2239 '("a)" "A)"))))
2240 (len (length bullet-list))
2241 (item-index (- len (length (member current bullet-list))))
2242 (get-value (lambda (index) (nth (mod index len) bullet-list)))
2243 (new (cond
2244 ((member which bullet-list) which)
2245 ((numberp which) (funcall get-value which))
2246 ((eq 'previous which) (funcall get-value (1- item-index)))
2247 (t (funcall get-value (1+ item-index))))))
2248 ;; Use a short variation of `org-list-write-struct' as there's
2249 ;; no need to go through all the steps.
2250 (let ((old-struct (copy-tree struct)))
2251 (org-list-set-bullet list-beg struct (org-list-bullet-string new))
2252 (org-list-struct-fix-bul struct prevs)
2253 (org-list-struct-fix-ind struct parents)
2254 (org-list-struct-apply-struct struct old-struct)))))
2256 (defun org-toggle-checkbox (&optional toggle-presence)
2257 "Toggle the checkbox in the current line.
2258 With prefix arg TOGGLE-PRESENCE, add or remove checkboxes. With
2259 double prefix, set checkbox to [-].
2261 When there is an active region, toggle status or presence of the
2262 first checkbox there, and make every item inside have the same
2263 status or presence, respectively.
2265 If the cursor is in a headline, apply this to all checkbox items
2266 in the text below the heading, taking as reference the first item
2267 in subtree, ignoring drawers."
2268 (interactive "P")
2269 (save-excursion
2270 (let* (singlep
2271 block-item
2272 lim-up
2273 lim-down
2274 (drawer-re (concat "^[ \t]*:\\("
2275 (mapconcat 'regexp-quote org-drawers "\\|")
2276 "\\):[ \t]*$"))
2277 (keyword-re (concat "^[ \t]*\\<\\(" org-scheduled-string
2278 "\\|" org-deadline-string
2279 "\\|" org-closed-string
2280 "\\|" org-clock-string "\\)"
2281 " *[[<]\\([^]>]+\\)[]>]"))
2282 (orderedp (org-entry-get nil "ORDERED"))
2283 (bounds
2284 ;; In a region, start at first item in region.
2285 (cond
2286 ((org-region-active-p)
2287 (let ((limit (region-end)))
2288 (goto-char (region-beginning))
2289 (if (org-list-search-forward (org-item-beginning-re) limit t)
2290 (setq lim-up (point-at-bol))
2291 (error "No item in region"))
2292 (setq lim-down (copy-marker limit))))
2293 ((org-at-heading-p)
2294 ;; On an heading, start at first item after drawers and
2295 ;; time-stamps (scheduled, etc.).
2296 (let ((limit (save-excursion (outline-next-heading) (point))))
2297 (forward-line 1)
2298 (while (or (looking-at drawer-re) (looking-at keyword-re))
2299 (if (looking-at keyword-re)
2300 (forward-line 1)
2301 (re-search-forward "^[ \t]*:END:" limit nil)))
2302 (if (org-list-search-forward (org-item-beginning-re) limit t)
2303 (setq lim-up (point-at-bol))
2304 (error "No item in subtree"))
2305 (setq lim-down (copy-marker limit))))
2306 ;; Just one item: set SINGLEP flag.
2307 ((org-at-item-p)
2308 (setq singlep t)
2309 (setq lim-up (point-at-bol)
2310 lim-down (copy-marker (point-at-eol))))
2311 (t (error "Not at an item or heading, and no active region"))))
2312 ;; Determine the checkbox going to be applied to all items
2313 ;; within bounds.
2314 (ref-checkbox
2315 (progn
2316 (goto-char lim-up)
2317 (let ((cbox (and (org-at-item-checkbox-p) (match-string 1))))
2318 (cond
2319 ((equal toggle-presence '(16)) "[-]")
2320 ((equal toggle-presence '(4))
2321 (unless cbox "[ ]"))
2322 ((equal "[X]" cbox) "[ ]")
2323 (t "[X]"))))))
2324 ;; When an item is found within bounds, grab the full list at
2325 ;; point structure, then: (1) set check-box of all its items
2326 ;; within bounds to REF-CHECKBOX, (2) fix check-boxes of the
2327 ;; whole list, (3) move point after the list.
2328 (goto-char lim-up)
2329 (while (and (< (point) lim-down)
2330 (org-list-search-forward (org-item-beginning-re)
2331 lim-down 'move))
2332 (let* ((struct (org-list-struct))
2333 (struct-copy (copy-tree struct))
2334 (parents (org-list-parents-alist struct))
2335 (prevs (org-list-prevs-alist struct))
2336 (bottom (copy-marker (org-list-get-bottom-point struct)))
2337 (items-to-toggle (org-remove-if
2338 (lambda (e) (or (< e lim-up) (> e lim-down)))
2339 (mapcar 'car struct))))
2340 (mapc (lambda (e) (org-list-set-checkbox
2341 e struct
2342 ;; If there is no box at item, leave as-is
2343 ;; unless function was called with C-u prefix.
2344 (let ((cur-box (org-list-get-checkbox e struct)))
2345 (if (or cur-box (equal toggle-presence '(4)))
2346 ref-checkbox
2347 cur-box))))
2348 items-to-toggle)
2349 (setq block-item (org-list-struct-fix-box
2350 struct parents prevs orderedp))
2351 ;; Report some problems due to ORDERED status of subtree.
2352 ;; If only one box was being checked, throw an error, else,
2353 ;; only signal problems.
2354 (cond
2355 ((and singlep block-item (> lim-up block-item))
2356 (error
2357 "Checkbox blocked because of unchecked box at line %d"
2358 (org-current-line block-item)))
2359 (block-item
2360 (message
2361 "Checkboxes were removed due to unchecked box at line %d"
2362 (org-current-line block-item))))
2363 (goto-char bottom)
2364 (move-marker bottom nil)
2365 (org-list-struct-apply-struct struct struct-copy)))
2366 (move-marker lim-down nil)))
2367 (org-update-checkbox-count-maybe))
2369 (defun org-reset-checkbox-state-subtree ()
2370 "Reset all checkboxes in an entry subtree."
2371 (interactive "*")
2372 (if (org-before-first-heading-p)
2373 (error "Not inside a tree")
2374 (save-restriction
2375 (save-excursion
2376 (org-narrow-to-subtree)
2377 (org-show-subtree)
2378 (goto-char (point-min))
2379 (let ((end (point-max)))
2380 (while (< (point) end)
2381 (when (org-at-item-checkbox-p)
2382 (replace-match "[ ]" t t nil 1))
2383 (beginning-of-line 2)))
2384 (org-update-checkbox-count-maybe 'all)))))
2386 (defun org-update-checkbox-count (&optional all)
2387 "Update the checkbox statistics in the current section.
2388 This will find all statistic cookies like [57%] and [6/12] and
2389 update them with the current numbers.
2391 With optional prefix argument ALL, do this for the whole buffer."
2392 (interactive "P")
2393 (save-excursion
2394 (let ((cookie-re "\\(\\(\\[[0-9]*%\\]\\)\\|\\(\\[[0-9]*/[0-9]*\\]\\)\\)")
2395 (box-re "^[ \t]*\\([-+*]\\|\\([0-9]+\\|[A-Za-z]\\)[.)]\\)[ \t]+\\(?:\\[@\\(?:start:\\)?\\([0-9]+\\|[A-Za-z]\\)\\][ \t]*\\)?\\(\\[[- X]\\]\\)")
2396 (recursivep
2397 (or (not org-hierarchical-checkbox-statistics)
2398 (string-match "\\<recursive\\>"
2399 (or (org-entry-get nil "COOKIE_DATA") ""))))
2400 (bounds (if all
2401 (cons (point-min) (point-max))
2402 (cons (or (ignore-errors (org-back-to-heading t) (point))
2403 (point-min))
2404 (save-excursion (outline-next-heading) (point)))))
2405 (count-boxes
2406 (function
2407 ;; Return number of checked boxes and boxes of all types
2408 ;; in all structures in STRUCTS. If RECURSIVEP is
2409 ;; non-nil, also count boxes in sub-lists. If ITEM is
2410 ;; nil, count across the whole structure, else count only
2411 ;; across subtree whose ancestor is ITEM.
2412 (lambda (item structs recursivep)
2413 (let ((c-on 0) (c-all 0))
2414 (mapc
2415 (lambda (s)
2416 (let* ((pre (org-list-prevs-alist s))
2417 (par (org-list-parents-alist s))
2418 (items
2419 (cond
2420 ((and recursivep item) (org-list-get-subtree item s))
2421 (recursivep (mapcar 'car s))
2422 (item (org-list-get-children item s par))
2423 (t (org-list-get-all-items
2424 (org-list-get-top-point s) s pre))))
2425 (cookies (delq nil (mapcar
2426 (lambda (e)
2427 (org-list-get-checkbox e s))
2428 items))))
2429 (setq c-all (+ (length cookies) c-all)
2430 c-on (+ (org-count "[X]" cookies) c-on))))
2431 structs)
2432 (cons c-on c-all)))))
2433 (backup-end 1)
2434 cookies-list structs-bak box-num)
2435 (goto-char (car bounds))
2436 ;; 1. Build an alist for each cookie found within BOUNDS. The
2437 ;; key will be position at beginning of cookie and values
2438 ;; ending position, format of cookie, and a cell whose car is
2439 ;; number of checked boxes to report, and cdr total number of
2440 ;; boxes.
2441 (while (re-search-forward cookie-re (cdr bounds) t)
2442 (catch 'skip
2443 (save-excursion
2444 (push
2445 (list
2446 (match-beginning 1) ; cookie start
2447 (match-end 1) ; cookie end
2448 (match-string 2) ; percent?
2449 (cond ; boxes count
2450 ;; Cookie is at an heading, but specifically for todo,
2451 ;; not for checkboxes: skip it.
2452 ((and (org-at-heading-p)
2453 (string-match "\\<todo\\>"
2454 (downcase
2455 (or (org-entry-get nil "COOKIE_DATA") ""))))
2456 (throw 'skip nil))
2457 ;; Cookie is at an heading, but all lists before next
2458 ;; heading already have been read. Use data collected
2459 ;; in STRUCTS-BAK. This should only happen when
2460 ;; heading has more than one cookie on it.
2461 ((and (org-at-heading-p)
2462 (<= (save-excursion (outline-next-heading) (point))
2463 backup-end))
2464 (funcall count-boxes nil structs-bak recursivep))
2465 ;; Cookie is at a fresh heading. Grab structure of
2466 ;; every list containing a checkbox between point and
2467 ;; next headline, and save them in STRUCTS-BAK.
2468 ((org-at-heading-p)
2469 (setq backup-end (save-excursion
2470 (outline-next-heading) (point))
2471 structs-bak nil)
2472 (while (org-list-search-forward box-re backup-end 'move)
2473 (let* ((struct (org-list-struct))
2474 (bottom (org-list-get-bottom-point struct)))
2475 (push struct structs-bak)
2476 (goto-char bottom)))
2477 (funcall count-boxes nil structs-bak recursivep))
2478 ;; Cookie is at an item, and we already have list
2479 ;; structure stored in STRUCTS-BAK.
2480 ((and (org-at-item-p)
2481 (< (point-at-bol) backup-end)
2482 ;; Only lists in no special context are stored.
2483 (not (nth 2 (org-list-context))))
2484 (funcall count-boxes (point-at-bol) structs-bak recursivep))
2485 ;; Cookie is at an item, but we need to compute list
2486 ;; structure.
2487 ((org-at-item-p)
2488 (let ((struct (org-list-struct)))
2489 (setq backup-end (org-list-get-bottom-point struct)
2490 structs-bak (list struct)))
2491 (funcall count-boxes (point-at-bol) structs-bak recursivep))
2492 ;; Else, cookie found is at a wrong place. Skip it.
2493 (t (throw 'skip nil))))
2494 cookies-list))))
2495 ;; 2. Apply alist to buffer, in reverse order so positions stay
2496 ;; unchanged after cookie modifications.
2497 (mapc (lambda (cookie)
2498 (let* ((beg (car cookie))
2499 (end (nth 1 cookie))
2500 (percentp (nth 2 cookie))
2501 (checked (car (nth 3 cookie)))
2502 (total (cdr (nth 3 cookie)))
2503 (new (if percentp
2504 (format "[%d%%]" (/ (* 100 checked)
2505 (max 1 total)))
2506 (format "[%d/%d]" checked total))))
2507 (goto-char beg)
2508 (insert new)
2509 (delete-region (point) (+ (point) (- end beg)))
2510 (when org-auto-align-tags (org-fix-tags-on-the-fly))))
2511 cookies-list))))
2513 (defun org-get-checkbox-statistics-face ()
2514 "Select the face for checkbox statistics.
2515 The face will be `org-done' when all relevant boxes are checked.
2516 Otherwise it will be `org-todo'."
2517 (if (match-end 1)
2518 (if (equal (match-string 1) "100%")
2519 'org-checkbox-statistics-done
2520 'org-checkbox-statistics-todo)
2521 (if (and (> (match-end 2) (match-beginning 2))
2522 (equal (match-string 2) (match-string 3)))
2523 'org-checkbox-statistics-done
2524 'org-checkbox-statistics-todo)))
2526 (defun org-update-checkbox-count-maybe (&optional all)
2527 "Update checkbox statistics unless turned off by user.
2528 With an optional argument ALL, update them in the whole buffer."
2529 (when (cdr (assq 'checkbox org-list-automatic-rules))
2530 (org-update-checkbox-count all))
2531 (run-hooks 'org-checkbox-statistics-hook))
2533 (defvar org-last-indent-begin-marker (make-marker))
2534 (defvar org-last-indent-end-marker (make-marker))
2535 (defun org-list-indent-item-generic (arg no-subtree struct)
2536 "Indent a local list item including its children.
2537 When number ARG is a negative, item will be outdented, otherwise
2538 it will be indented.
2540 If a region is active, all items inside will be moved.
2542 If NO-SUBTREE is non-nil, only indent the item itself, not its
2543 children.
2545 STRUCT is the list structure.
2547 Return t if successful."
2548 (save-excursion
2549 (beginning-of-line)
2550 (let* ((regionp (org-region-active-p))
2551 (rbeg (and regionp (region-beginning)))
2552 (rend (and regionp (region-end)))
2553 (top (org-list-get-top-point struct))
2554 (parents (org-list-parents-alist struct))
2555 (prevs (org-list-prevs-alist struct))
2556 ;; Are we going to move the whole list?
2557 (specialp
2558 (and (= top (point))
2559 (cdr (assq 'indent org-list-automatic-rules))
2560 (if no-subtree
2561 (error
2562 "First item of list cannot move without its subtree")
2563 t))))
2564 ;; Determine begin and end points of zone to indent. If moving
2565 ;; more than one item, save them for subsequent moves.
2566 (unless (and (memq last-command '(org-shiftmetaright org-shiftmetaleft))
2567 (memq this-command '(org-shiftmetaright org-shiftmetaleft)))
2568 (if regionp
2569 (progn
2570 (set-marker org-last-indent-begin-marker rbeg)
2571 (set-marker org-last-indent-end-marker rend))
2572 (set-marker org-last-indent-begin-marker (point))
2573 (set-marker org-last-indent-end-marker
2574 (cond
2575 (specialp (org-list-get-bottom-point struct))
2576 (no-subtree (1+ (point)))
2577 (t (org-list-get-item-end (point) struct))))))
2578 (let* ((beg (marker-position org-last-indent-begin-marker))
2579 (end (marker-position org-last-indent-end-marker)))
2580 (cond
2581 ;; Special case: moving top-item with indent rule.
2582 (specialp
2583 (let* ((level-skip (org-level-increment))
2584 (offset (if (< arg 0) (- level-skip) level-skip))
2585 (top-ind (org-list-get-ind beg struct))
2586 (old-struct (copy-tree struct)))
2587 (if (< (+ top-ind offset) 0)
2588 (error "Cannot outdent beyond margin")
2589 ;; Change bullet if necessary.
2590 (when (and (= (+ top-ind offset) 0)
2591 (string-match "*"
2592 (org-list-get-bullet beg struct)))
2593 (org-list-set-bullet beg struct
2594 (org-list-bullet-string "-")))
2595 ;; Shift every item by OFFSET and fix bullets. Then
2596 ;; apply changes to buffer.
2597 (mapc (lambda (e)
2598 (let ((ind (org-list-get-ind (car e) struct)))
2599 (org-list-set-ind (car e) struct (+ ind offset))))
2600 struct)
2601 (org-list-struct-fix-bul struct prevs)
2602 (org-list-struct-apply-struct struct old-struct))))
2603 ;; Forbidden move:
2604 ((and (< arg 0)
2605 ;; If only one item is moved, it mustn't have a child.
2606 (or (and no-subtree
2607 (not regionp)
2608 (org-list-has-child-p beg struct))
2609 ;; If a subtree or region is moved, the last item
2610 ;; of the subtree mustn't have a child.
2611 (let ((last-item (caar
2612 (reverse
2613 (org-remove-if
2614 (lambda (e) (>= (car e) end))
2615 struct)))))
2616 (org-list-has-child-p last-item struct))))
2617 (error "Cannot outdent an item without its children"))
2618 ;; Normal shifting
2620 (let* ((new-parents
2621 (if (< arg 0)
2622 (org-list-struct-outdent beg end struct parents)
2623 (org-list-struct-indent beg end struct parents prevs))))
2624 (org-list-write-struct struct new-parents))
2625 (org-update-checkbox-count-maybe))))))
2628 (defun org-outdent-item ()
2629 "Outdent a local list item, but not its children.
2630 If a region is active, all items inside will be moved."
2631 (interactive)
2632 (if (org-at-item-p)
2633 (let ((struct (org-list-struct)))
2634 (org-list-indent-item-generic -1 t struct))
2635 (error "Not at an item")))
2637 (defun org-indent-item ()
2638 "Indent a local list item, but not its children.
2639 If a region is active, all items inside will be moved."
2640 (interactive)
2641 (if (org-at-item-p)
2642 (let ((struct (org-list-struct)))
2643 (org-list-indent-item-generic 1 t struct))
2644 (error "Not at an item")))
2646 (defun org-outdent-item-tree ()
2647 "Outdent a local list item including its children.
2648 If a region is active, all items inside will be moved."
2649 (interactive)
2650 (let ((regionp (org-region-active-p)))
2651 (cond
2652 ((or (org-at-item-p)
2653 (and (org-region-active-p)
2654 (goto-char (region-beginning))
2655 (org-at-item-p)))
2656 (let ((struct (org-list-struct)))
2657 (org-list-indent-item-generic -1 nil struct)))
2658 (regionp (error "Region not starting at an item"))
2659 (t (error "Not at an item")))))
2661 (defun org-indent-item-tree ()
2662 "Indent a local list item including its children.
2663 If a region is active, all items inside will be moved."
2664 (interactive)
2665 (let ((regionp (org-region-active-p)))
2666 (cond
2667 ((or (org-at-item-p)
2668 (and (org-region-active-p)
2669 (goto-char (region-beginning))
2670 (org-at-item-p)))
2671 (let ((struct (org-list-struct)))
2672 (org-list-indent-item-generic 1 nil struct)))
2673 (regionp (error "Region not starting at an item"))
2674 (t (error "Not at an item")))))
2676 (defvar org-tab-ind-state)
2677 (defun org-cycle-item-indentation ()
2678 "Cycle levels of indentation of an empty item.
2679 The first run indents the item, if applicable. Subsequent runs
2680 outdent it at meaningful levels in the list. When done, item is
2681 put back at its original position with its original bullet.
2683 Return t at each successful move."
2684 (when (org-at-item-p)
2685 (let* ((org-adapt-indentation nil)
2686 (struct (org-list-struct))
2687 (ind (org-list-get-ind (point-at-bol) struct))
2688 (bullet (org-trim (buffer-substring (point-at-bol) (point-at-eol)))))
2689 ;; Accept empty items or if cycle has already started.
2690 (when (or (eq last-command 'org-cycle-item-indentation)
2691 (and (save-excursion
2692 (beginning-of-line)
2693 (looking-at org-list-full-item-re))
2694 (>= (match-end 0) (save-excursion
2695 (goto-char (org-list-get-item-end
2696 (point-at-bol) struct))
2697 (skip-chars-backward " \r\t\n")
2698 (point)))))
2699 (setq this-command 'org-cycle-item-indentation)
2700 ;; When in the middle of the cycle, try to outdent first. If
2701 ;; it fails, and point is still at initial position, indent.
2702 ;; Else, re-create it at its original position.
2703 (if (eq last-command 'org-cycle-item-indentation)
2704 (cond
2705 ((ignore-errors (org-list-indent-item-generic -1 t struct)))
2706 ((and (= ind (car org-tab-ind-state))
2707 (ignore-errors (org-list-indent-item-generic 1 t struct))))
2708 (t (delete-region (point-at-bol) (point-at-eol))
2709 (org-indent-to-column (car org-tab-ind-state))
2710 (insert (cdr org-tab-ind-state) " ")
2711 ;; Break cycle
2712 (setq this-command 'identity)))
2713 ;; If a cycle is starting, remember indentation and bullet,
2714 ;; then try to indent. If it fails, try to outdent.
2715 (setq org-tab-ind-state (cons ind bullet))
2716 (cond
2717 ((ignore-errors (org-list-indent-item-generic 1 t struct)))
2718 ((ignore-errors (org-list-indent-item-generic -1 t struct)))
2719 (t (error "Cannot move item"))))
2720 t))))
2722 (defun org-sort-list (&optional with-case sorting-type getkey-func compare-func)
2723 "Sort list items.
2724 The cursor may be at any item of the list that should be sorted.
2725 Sublists are not sorted. Checkboxes, if any, are ignored.
2727 Sorting can be alphabetically, numerically, by date/time as given
2728 by a time stamp, by a property or by priority.
2730 Comparing entries ignores case by default. However, with an
2731 optional argument WITH-CASE, the sorting considers case as well.
2733 The command prompts for the sorting type unless it has been given
2734 to the function through the SORTING-TYPE argument, which needs to
2735 be a character, \(?n ?N ?a ?A ?t ?T ?f ?F). Here is the precise
2736 meaning of each character:
2738 n Numerically, by converting the beginning of the item to a number.
2739 a Alphabetically. Only the first line of item is checked.
2740 t By date/time, either the first active time stamp in the entry, if
2741 any, or by the first inactive one. In a timer list, sort the timers.
2743 Capital letters will reverse the sort order.
2745 If the SORTING-TYPE is ?f or ?F, then GETKEY-FUNC specifies
2746 a function to be called with point at the beginning of the
2747 record. It must return either a string or a number that should
2748 serve as the sorting key for that record. It will then use
2749 COMPARE-FUNC to compare entries."
2750 (interactive "P")
2751 (let* ((case-func (if with-case 'identity 'downcase))
2752 (struct (org-list-struct))
2753 (prevs (org-list-prevs-alist struct))
2754 (start (org-list-get-list-begin (point-at-bol) struct prevs))
2755 (end (org-list-get-list-end (point-at-bol) struct prevs))
2756 (sorting-type
2757 (progn
2758 (message
2759 "Sort plain list: [a]lpha [n]umeric [t]ime [f]unc A/N/T/F means reversed:")
2760 (read-char-exclusive)))
2761 (getkey-func (and (= (downcase sorting-type) ?f)
2762 (intern (org-icompleting-read "Sort using function: "
2763 obarray 'fboundp t nil nil)))))
2764 (message "Sorting items...")
2765 (save-restriction
2766 (narrow-to-region start end)
2767 (goto-char (point-min))
2768 (let* ((dcst (downcase sorting-type))
2769 (case-fold-search nil)
2770 (now (current-time))
2771 (sort-func (cond
2772 ((= dcst ?a) 'string<)
2773 ((= dcst ?f) compare-func)
2774 ((= dcst ?t) '<)
2775 (t nil)))
2776 (next-record (lambda ()
2777 (skip-chars-forward " \r\t\n")
2778 (beginning-of-line)))
2779 (end-record (lambda ()
2780 (goto-char (org-list-get-item-end-before-blank
2781 (point) struct))))
2782 (value-to-sort
2783 (lambda ()
2784 (when (looking-at "[ \t]*[-+*0-9.)]+\\([ \t]+\\[[- X]\\]\\)?[ \t]+")
2785 (cond
2786 ((= dcst ?n)
2787 (string-to-number (buffer-substring (match-end 0)
2788 (point-at-eol))))
2789 ((= dcst ?a)
2790 (funcall case-func
2791 (buffer-substring (match-end 0) (point-at-eol))))
2792 ((= dcst ?t)
2793 (cond
2794 ;; If it is a timer list, convert timer to seconds
2795 ((org-at-item-timer-p)
2796 (org-timer-hms-to-secs (match-string 1)))
2797 ((or (re-search-forward org-ts-regexp (point-at-eol) t)
2798 (re-search-forward org-ts-regexp-both
2799 (point-at-eol) t))
2800 (org-time-string-to-seconds (match-string 0)))
2801 (t (org-float-time now))))
2802 ((= dcst ?f)
2803 (if getkey-func
2804 (let ((value (funcall getkey-func)))
2805 (if (stringp value)
2806 (funcall case-func value)
2807 value))
2808 (error "Invalid key function `%s'" getkey-func)))
2809 (t (error "Invalid sorting type `%c'" sorting-type)))))))
2810 (sort-subr (/= dcst sorting-type)
2811 next-record
2812 end-record
2813 value-to-sort
2815 sort-func)
2816 ;; Read and fix list again, as `sort-subr' probably destroyed
2817 ;; its structure.
2818 (org-list-repair)
2819 (run-hooks 'org-after-sorting-entries-or-items-hook)
2820 (message "Sorting items...done")))))
2824 ;;; Send and receive lists
2826 (defun org-list-parse-list (&optional delete)
2827 "Parse the list at point and maybe DELETE it.
2829 Return a list whose car is a symbol of list type, among
2830 `ordered', `unordered' and `descriptive'. Then, each item is
2831 a list whose car is counter, and cdr are strings and other
2832 sub-lists. Inside strings, check-boxes are replaced by
2833 \"[CBON]\", \"[CBOFF]\" and \"[CBTRANS]\".
2835 For example, the following list:
2837 1. first item
2838 + sub-item one
2839 + [X] sub-item two
2840 more text in first item
2841 2. [@3] last item
2843 will be parsed as:
2845 \(ordered
2846 \(nil \"first item\"
2847 \(unordered
2848 \(nil \"sub-item one\"\)
2849 \(nil \"[CBON] sub-item two\"\)\)
2850 \"more text in first item\"\)
2851 \(3 \"last item\"\)\)
2853 Point is left at list end."
2854 (let* ((struct (org-list-struct))
2855 (prevs (org-list-prevs-alist struct))
2856 (parents (org-list-parents-alist struct))
2857 (top (org-list-get-top-point struct))
2858 (bottom (org-list-get-bottom-point struct))
2860 parse-item ; for byte-compiler
2861 (get-text
2862 (function
2863 ;; Return text between BEG and END, trimmed, with
2864 ;; checkboxes replaced.
2865 (lambda (beg end)
2866 (let ((text (org-trim (buffer-substring beg end))))
2867 (if (string-match "\\`\\[\\([-X ]\\)\\]" text)
2868 (replace-match
2869 (let ((box (match-string 1 text)))
2870 (cond
2871 ((equal box " ") "CBOFF")
2872 ((equal box "-") "CBTRANS")
2873 (t "CBON")))
2874 t nil text 1)
2875 text)))))
2876 (parse-sublist
2877 (function
2878 ;; Return a list whose car is list type and cdr a list of
2879 ;; items' body.
2880 (lambda (e)
2881 (cons (org-list-get-list-type (car e) struct prevs)
2882 (mapcar parse-item e)))))
2883 (parse-item
2884 (function
2885 ;; Return a list containing counter of item, if any, text
2886 ;; and any sublist inside it.
2887 (lambda (e)
2888 (let ((start (save-excursion
2889 (goto-char e)
2890 (looking-at "[ \t]*\\S-+\\([ \t]+\\[@\\(start:\\)?\\([0-9]+\\|[a-zA-Z]\\)\\]\\)?[ \t]*")
2891 (match-end 0)))
2892 ;; Get counter number. For alphabetic counter, get
2893 ;; its position in the alphabet.
2894 (counter (let ((c (org-list-get-counter e struct)))
2895 (cond
2896 ((not c) nil)
2897 ((string-match "[A-Za-z]" c)
2898 (- (string-to-char (upcase (match-string 0 c)))
2899 64))
2900 ((string-match "[0-9]+" c)
2901 (string-to-number (match-string 0 c))))))
2902 (childp (org-list-has-child-p e struct))
2903 (end (org-list-get-item-end e struct)))
2904 ;; If item has a child, store text between bullet and
2905 ;; next child, then recursively parse all sublists. At
2906 ;; the end of each sublist, check for the presence of
2907 ;; text belonging to the original item.
2908 (if childp
2909 (let* ((children (org-list-get-children e struct parents))
2910 (body (list (funcall get-text start childp))))
2911 (while children
2912 (let* ((first (car children))
2913 (sub (org-list-get-all-items first struct prevs))
2914 (last-c (car (last sub)))
2915 (last-end (org-list-get-item-end last-c struct)))
2916 (push (funcall parse-sublist sub) body)
2917 ;; Remove children from the list just parsed.
2918 (setq children (cdr (member last-c children)))
2919 ;; There is a chunk of text belonging to the
2920 ;; item if last child doesn't end where next
2921 ;; child starts or where item ends.
2922 (unless (= (or (car children) end) last-end)
2923 (push (funcall get-text
2924 last-end (or (car children) end))
2925 body))))
2926 (cons counter (nreverse body)))
2927 (list counter (funcall get-text start end))))))))
2928 ;; Store output, take care of cursor position and deletion of
2929 ;; list, then return output.
2930 (setq out (funcall parse-sublist (org-list-get-all-items top struct prevs)))
2931 (goto-char top)
2932 (when delete
2933 (delete-region top bottom)
2934 (when (and (not (looking-at "[ \t]*$")) (looking-at org-list-end-re))
2935 (replace-match "")))
2936 out))
2938 (defun org-list-make-subtree ()
2939 "Convert the plain list at point into a subtree."
2940 (interactive)
2941 (if (not (ignore-errors (goto-char (org-in-item-p))))
2942 (error "Not in a list")
2943 (let ((list (save-excursion (org-list-parse-list t))))
2944 (insert (org-list-to-subtree list)))))
2946 (defun org-list-insert-radio-list ()
2947 "Insert a radio list template appropriate for this major mode."
2948 (interactive)
2949 (let* ((e (assq major-mode org-list-radio-list-templates))
2950 (txt (nth 1 e))
2951 name pos)
2952 (unless e (error "No radio list setup defined for %s" major-mode))
2953 (setq name (read-string "List name: "))
2954 (while (string-match "%n" txt)
2955 (setq txt (replace-match name t t txt)))
2956 (or (bolp) (insert "\n"))
2957 (setq pos (point))
2958 (insert txt)
2959 (goto-char pos)))
2961 (defun org-list-send-list (&optional maybe)
2962 "Send a transformed version of this list to the receiver position.
2963 With argument MAYBE, fail quietly if no transformation is defined
2964 for this list."
2965 (interactive)
2966 (catch 'exit
2967 (unless (org-at-item-p) (error "Not at a list item"))
2968 (save-excursion
2969 (re-search-backward "#\\+ORGLST" nil t)
2970 (unless (looking-at "[ \t]*#\\+ORGLST[: \t][ \t]*SEND[ \t]+\\([^ \t\r\n]+\\)[ \t]+\\([^ \t\r\n]+\\)\\([ \t]+.*\\)?")
2971 (if maybe
2972 (throw 'exit nil)
2973 (error "Don't know how to transform this list"))))
2974 (let* ((name (match-string 1))
2975 (transform (intern (match-string 2)))
2976 (bottom-point
2977 (save-excursion
2978 (re-search-forward
2979 "\\(\\\\end{comment}\\|@end ignore\\|-->\\)" nil t)
2980 (match-beginning 0)))
2981 (top-point
2982 (progn
2983 (re-search-backward "#\\+ORGLST" nil t)
2984 (re-search-forward (org-item-beginning-re) bottom-point t)
2985 (match-beginning 0)))
2986 (list (save-restriction
2987 (narrow-to-region top-point bottom-point)
2988 (org-list-parse-list)))
2989 beg txt)
2990 (unless (fboundp transform)
2991 (error "No such transformation function %s" transform))
2992 (let ((txt (funcall transform list)))
2993 ;; Find the insertion place
2994 (save-excursion
2995 (goto-char (point-min))
2996 (unless (re-search-forward
2997 (concat "BEGIN RECEIVE ORGLST +"
2998 name
2999 "\\([ \t]\\|$\\)") nil t)
3000 (error "Don't know where to insert translated list"))
3001 (goto-char (match-beginning 0))
3002 (beginning-of-line 2)
3003 (setq beg (point))
3004 (unless (re-search-forward (concat "END RECEIVE ORGLST +" name) nil t)
3005 (error "Cannot find end of insertion region"))
3006 (delete-region beg (point-at-bol))
3007 (goto-char beg)
3008 (insert txt "\n")))
3009 (message "List converted and installed at receiver location"))))
3011 (defsubst org-list-item-trim-br (item)
3012 "Trim line breaks in a list ITEM."
3013 (setq item (replace-regexp-in-string "\n +" " " item)))
3015 (defun org-list-to-generic (list params)
3016 "Convert a LIST parsed through `org-list-parse-list' to other formats.
3017 Valid parameters PARAMS are:
3019 :ustart String to start an unordered list
3020 :uend String to end an unordered list
3022 :ostart String to start an ordered list
3023 :oend String to end an ordered list
3025 :dstart String to start a descriptive list
3026 :dend String to end a descriptive list
3027 :dtstart String to start a descriptive term
3028 :dtend String to end a descriptive term
3029 :ddstart String to start a description
3030 :ddend String to end a description
3032 :splice When set to t, return only list body lines, don't wrap
3033 them into :[u/o]start and :[u/o]end. Default is nil.
3035 :istart String to start a list item.
3036 :icount String to start an item with a counter.
3037 :iend String to end a list item
3038 :isep String to separate items
3039 :lsep String to separate sublists
3040 :csep String to separate text from a sub-list
3042 :cboff String to insert for an unchecked check-box
3043 :cbon String to insert for a checked check-box
3044 :cbtrans String to insert for a check-box in transitional state
3046 :nobr Non-nil means remove line breaks in lists items.
3048 Alternatively, each parameter can also be a form returning
3049 a string. These sexp can use keywords `counter' and `depth',
3050 representing respectively counter associated to the current
3051 item, and depth of the current sub-list, starting at 0.
3052 Obviously, `counter' is only available for parameters applying to
3053 items."
3054 (interactive)
3055 (let* ((p params)
3056 (splicep (plist-get p :splice))
3057 (ostart (plist-get p :ostart))
3058 (oend (plist-get p :oend))
3059 (ustart (plist-get p :ustart))
3060 (uend (plist-get p :uend))
3061 (dstart (plist-get p :dstart))
3062 (dend (plist-get p :dend))
3063 (dtstart (plist-get p :dtstart))
3064 (dtend (plist-get p :dtend))
3065 (ddstart (plist-get p :ddstart))
3066 (ddend (plist-get p :ddend))
3067 (istart (plist-get p :istart))
3068 (icount (plist-get p :icount))
3069 (iend (plist-get p :iend))
3070 (isep (plist-get p :isep))
3071 (lsep (plist-get p :lsep))
3072 (csep (plist-get p :csep))
3073 (cbon (plist-get p :cbon))
3074 (cboff (plist-get p :cboff))
3075 (cbtrans (plist-get p :cbtrans))
3076 (nobr (plist-get p :nobr))
3077 export-sublist ; for byte-compiler
3078 (export-item
3079 (function
3080 ;; Export an item ITEM of type TYPE, at DEPTH. First
3081 ;; string in item is treated in a special way as it can
3082 ;; bring extra information that needs to be processed.
3083 (lambda (item type depth)
3084 (let* ((counter (pop item))
3085 (fmt (concat
3086 (cond
3087 ((eq type 'descriptive)
3088 ;; Stick DTSTART to ISTART by
3089 ;; left-trimming the latter.
3090 (concat (let ((s (eval istart)))
3091 (or (and (string-match "[ \t\n\r]+\\'" s)
3092 (replace-match "" t t s))
3093 istart))
3094 "%s" (eval ddend)))
3095 ((and counter (eq type 'ordered))
3096 (concat (eval icount) "%s"))
3097 (t (concat (eval istart) "%s")))
3098 (eval iend)))
3099 (first (car item)))
3100 ;; Replace checkbox if any is found.
3101 (cond
3102 ((string-match "\\[CBON\\]" first)
3103 (setq first (replace-match cbon t t first)))
3104 ((string-match "\\[CBOFF\\]" first)
3105 (setq first (replace-match cboff t t first)))
3106 ((string-match "\\[CBTRANS\\]" first)
3107 (setq first (replace-match cbtrans t t first))))
3108 ;; Replace line breaks if required
3109 (when nobr (setq first (org-list-item-trim-br first)))
3110 ;; Insert descriptive term if TYPE is `descriptive'.
3111 (when (eq type 'descriptive)
3112 (let* ((complete (string-match "^\\(.*\\)[ \t]+::" first))
3113 (term (if complete
3114 (save-match-data
3115 (org-trim (match-string 1 first)))
3116 "???"))
3117 (desc (if complete
3118 (org-trim (substring first (match-end 0)))
3119 first)))
3120 (setq first (concat (eval dtstart) term (eval dtend)
3121 (eval ddstart) desc))))
3122 (setcar item first)
3123 (format fmt
3124 (mapconcat (lambda (e)
3125 (if (stringp e) e
3126 (funcall export-sublist e (1+ depth))))
3127 item (or (eval csep) "")))))))
3128 (export-sublist
3129 (function
3130 ;; Export sublist SUB at DEPTH.
3131 (lambda (sub depth)
3132 (let* ((type (car sub))
3133 (items (cdr sub))
3134 (fmt (concat (cond
3135 (splicep "%s")
3136 ((eq type 'ordered)
3137 (concat (eval ostart) "%s" (eval oend)))
3138 ((eq type 'descriptive)
3139 (concat (eval dstart) "%s" (eval dend)))
3140 (t (concat (eval ustart) "%s" (eval uend))))
3141 (eval lsep))))
3142 (format fmt (mapconcat (lambda (e)
3143 (funcall export-item e type depth))
3144 items (or (eval isep) ""))))))))
3145 (concat (funcall export-sublist list 0) "\n")))
3147 (defun org-list-to-latex (list &optional params)
3148 "Convert LIST into a LaTeX list.
3149 LIST is as returned by `org-list-parse-list'. PARAMS is a property list
3150 with overruling parameters for `org-list-to-generic'."
3151 (org-list-to-generic
3152 list
3153 (org-combine-plists
3154 '(:splice nil :ostart "\\begin{enumerate}\n" :oend "\\end{enumerate}"
3155 :ustart "\\begin{itemize}\n" :uend "\\end{itemize}"
3156 :dstart "\\begin{description}\n" :dend "\\end{description}"
3157 :dtstart "[" :dtend "] "
3158 :istart "\\item " :iend "\n"
3159 :icount (let ((enum (nth depth '("i" "ii" "iii" "iv"))))
3160 (if enum
3161 ;; LaTeX increments counter just before
3162 ;; using it, so set it to the desired
3163 ;; value, minus one.
3164 (format "\\setcounter{enum%s}{%s}\n\\item "
3165 enum (1- counter))
3166 "\\item "))
3167 :csep "\n"
3168 :cbon "\\texttt{[X]}" :cboff "\\texttt{[ ]}"
3169 :cbtrans "\\texttt{[-]}")
3170 params)))
3172 (defun org-list-to-html (list &optional params)
3173 "Convert LIST into a HTML list.
3174 LIST is as returned by `org-list-parse-list'. PARAMS is a property list
3175 with overruling parameters for `org-list-to-generic'."
3176 (org-list-to-generic
3177 list
3178 (org-combine-plists
3179 '(:splice nil :ostart "<ol>\n" :oend "\n</ol>"
3180 :ustart "<ul>\n" :uend "\n</ul>"
3181 :dstart "<dl>\n" :dend "\n</dl>"
3182 :dtstart "<dt>" :dtend "</dt>\n"
3183 :ddstart "<dd>" :ddend "</dd>"
3184 :istart "<li>" :iend "</li>"
3185 :icount (format "<li value=\"%s\">" counter)
3186 :isep "\n" :lsep "\n" :csep "\n"
3187 :cbon "<code>[X]</code>" :cboff "<code>[ ]</code>"
3188 :cbtrans "<code>[-]</code>")
3189 params)))
3191 (defun org-list-to-texinfo (list &optional params)
3192 "Convert LIST into a Texinfo list.
3193 LIST is as returned by `org-list-parse-list'. PARAMS is a property list
3194 with overruling parameters for `org-list-to-generic'."
3195 (org-list-to-generic
3196 list
3197 (org-combine-plists
3198 '(:splice nil :ostart "@itemize @minus\n" :oend "@end itemize"
3199 :ustart "@enumerate\n" :uend "@end enumerate"
3200 :dstart "@table @asis\n" :dend "@end table"
3201 :dtstart " " :dtend "\n"
3202 :istart "@item\n" :iend "\n"
3203 :icount "@item\n"
3204 :csep "\n"
3205 :cbon "@code{[X]}" :cboff "@code{[ ]}"
3206 :cbtrans "@code{[-]}")
3207 params)))
3209 (defun org-list-to-subtree (list &optional params)
3210 "Convert LIST into an Org subtree.
3211 LIST is as returned by `org-list-parse-list'. PARAMS is a property list
3212 with overruling parameters for `org-list-to-generic'."
3213 (let* ((rule (cdr (assq 'heading org-blank-before-new-entry)))
3214 (level (org-reduced-level (or (org-current-level) 0)))
3215 (blankp (or (eq rule t)
3216 (and (eq rule 'auto)
3217 (save-excursion
3218 (outline-previous-heading)
3219 (org-previous-line-empty-p)))))
3220 (get-stars
3221 (function
3222 ;; Return the string for the heading, depending on depth D
3223 ;; of current sub-list.
3224 (lambda (d)
3225 (let ((oddeven-level (+ level d 1)))
3226 (concat (make-string (if org-odd-levels-only
3227 (1- (* 2 oddeven-level))
3228 oddeven-level)
3230 " "))))))
3231 (org-list-to-generic
3232 list
3233 (org-combine-plists
3234 '(:splice t
3235 :dtstart " " :dtend " "
3236 :istart (funcall get-stars depth)
3237 :icount (funcall get-stars depth)
3238 :isep (if blankp "\n\n" "\n")
3239 :csep (if blankp "\n\n" "\n")
3240 :cbon "DONE" :cboff "TODO" :cbtrans "TODO")
3241 params))))
3243 (provide 'org-list)
3245 ;;; org-list.el ends here