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