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