org-habit: Fix 6652baa39db26df8a8ac5dbbe40f3de91bf1a6b1
[org-mode.git] / lisp / org-list.el
blob1525c2c5a0ba4684c29ed77406c8e080f05d5868
1 ;;; org-list.el --- Plain lists for Org-mode
2 ;;
3 ;; Copyright (C) 2004-2015 Free Software Foundation, Inc.
4 ;;
5 ;; Author: Carsten Dominik <carsten at orgmode dot org>
6 ;; Bastien Guerry <bzg@gnu.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-odd-levels-only)
92 (defvar org-scheduled-string)
93 (defvar org-ts-regexp)
94 (defvar org-ts-regexp-both)
95 (defvar org-drawer-regexp)
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.
216 This variable needs to be set before org.el is loaded. If you
217 need to make a change while Emacs is running, use the customize
218 interface or run the following code after updating it:
220 \\[org-element-update-syntax]"
221 :group 'org-plain-lists
222 :type '(choice (const :tag "dot like in \"2.\"" ?.)
223 (const :tag "paren like in \"2)\"" ?\))
224 (const :tag "both" t))
225 :set (lambda (var val) (set var val)
226 (when (featurep 'org-element) (org-element-update-syntax))))
228 (define-obsolete-variable-alias 'org-alphabetical-lists
229 'org-list-allow-alphabetical "24.4") ; Since 8.0
230 (defcustom org-list-allow-alphabetical nil
231 "Non-nil means single character alphabetical bullets are allowed.
233 Both uppercase and lowercase are handled. Lists with more than
234 26 items will fallback to standard numbering. Alphabetical
235 counters like \"[@c]\" will be recognized.
237 This variable needs to be set before org.el is loaded. If you
238 need to make a change while Emacs is running, use the customize
239 interface or run the following code after updating it:
241 \\[org-element-update-syntax]"
242 :group 'org-plain-lists
243 :version "24.1"
244 :type 'boolean
245 :set (lambda (var val) (set var val)
246 (when (featurep 'org-element) (org-element-update-syntax))))
248 (defcustom org-list-two-spaces-after-bullet-regexp nil
249 "A regular expression matching bullets that should have 2 spaces after them.
250 When nil, no bullet will have two spaces after them. When
251 a string, it will be used as a regular expression. When the
252 bullet type of a list is changed, the new bullet type will be
253 matched against this regexp. If it matches, there will be two
254 spaces instead of one after the bullet in each item of the list."
255 :group 'org-plain-lists
256 :type '(choice
257 (const :tag "never" nil)
258 (regexp)))
260 (define-obsolete-variable-alias 'org-empty-line-terminates-plain-lists
261 'org-list-empty-line-terminates-plain-lists "24.4") ;; Since 8.0
262 (defcustom org-list-empty-line-terminates-plain-lists nil
263 "Non-nil means an empty line ends all plain list levels.
264 Otherwise, two of them will be necessary."
265 :group 'org-plain-lists
266 :type 'boolean)
268 (defcustom org-list-automatic-rules '((checkbox . t)
269 (indent . t))
270 "Non-nil means apply set of rules when acting on lists.
271 By default, automatic actions are taken when using
272 \\[org-meta-return], \\[org-metaright], \\[org-metaleft],
273 \\[org-shiftmetaright], \\[org-shiftmetaleft],
274 \\[org-ctrl-c-minus], \\[org-toggle-checkbox] or
275 \\[org-insert-todo-heading]. You can disable individually these
276 rules by setting them to nil. Valid rules are:
278 checkbox when non-nil, checkbox statistics is updated each time
279 you either insert a new checkbox or toggle a checkbox.
280 indent when non-nil, indenting or outdenting list top-item
281 with its subtree will move the whole list and
282 outdenting a list whose bullet is * to column 0 will
283 change that bullet to \"-\"."
284 :group 'org-plain-lists
285 :version "24.1"
286 :type '(alist :tag "Sets of rules"
287 :key-type
288 (choice
289 (const :tag "Checkbox" checkbox)
290 (const :tag "Indent" indent))
291 :value-type
292 (boolean :tag "Activate" :value t)))
294 (defcustom org-list-use-circular-motion nil
295 "Non-nil means commands implying motion in lists should be cyclic.
297 In that case, the item following the last item is the first one,
298 and the item preceding the first item is the last one.
300 This affects the behavior of \\[org-move-item-up],
301 \\[org-move-item-down], \\[org-next-item] and
302 \\[org-previous-item]."
303 :group 'org-plain-lists
304 :version "24.1"
305 :type 'boolean)
307 (defvar org-checkbox-statistics-hook nil
308 "Hook that is run whenever Org thinks checkbox statistics should be updated.
309 This hook runs even if checkbox rule in
310 `org-list-automatic-rules' does not apply, so it can be used to
311 implement alternative ways of collecting statistics
312 information.")
314 (define-obsolete-variable-alias 'org-hierarchical-checkbox-statistics
315 'org-checkbox-hierarchical-statistics "24.4") ;; Since 8.0
316 (defcustom org-checkbox-hierarchical-statistics t
317 "Non-nil means checkbox statistics counts only the state of direct children.
318 When nil, all boxes below the cookie are counted.
319 This can be set to nil on a per-node basis using a COOKIE_DATA property
320 with the word \"recursive\" in the value."
321 :group 'org-plain-lists
322 :type 'boolean)
324 (org-defvaralias 'org-description-max-indent
325 'org-list-description-max-indent) ;; Since 8.0
326 (defcustom org-list-description-max-indent 20
327 "Maximum indentation for the second line of a description list.
328 When the indentation would be larger than this, it will become
329 5 characters instead."
330 :group 'org-plain-lists
331 :type 'integer)
333 (defcustom org-list-indent-offset 0
334 "Additional indentation for sub-items in a list.
335 By setting this to a small number, usually 1 or 2, one can more
336 clearly distinguish sub-items in a list."
337 :group 'org-plain-lists
338 :version "24.1"
339 :type 'integer)
341 (defcustom org-list-radio-list-templates
342 '((latex-mode "% BEGIN RECEIVE ORGLST %n
343 % END RECEIVE ORGLST %n
344 \\begin{comment}
345 #+ORGLST: SEND %n org-list-to-latex
347 \\end{comment}\n")
348 (texinfo-mode "@c BEGIN RECEIVE ORGLST %n
349 @c END RECEIVE ORGLST %n
350 @ignore
351 #+ORGLST: SEND %n org-list-to-texinfo
353 @end ignore\n")
354 (html-mode "<!-- BEGIN RECEIVE ORGLST %n -->
355 <!-- END RECEIVE ORGLST %n -->
356 <!--
357 #+ORGLST: SEND %n org-list-to-html
359 -->\n"))
360 "Templates for radio lists in different major modes.
361 All occurrences of %n in a template will be replaced with the name of the
362 list, obtained by prompting the user."
363 :group 'org-plain-lists
364 :type '(repeat
365 (list (symbol :tag "Major mode")
366 (string :tag "Format"))))
368 (defvar org-list-forbidden-blocks '("example" "verse" "src" "ascii" "beamer"
369 "html" "latex" "odt")
370 "Names of blocks where lists are not allowed.
371 Names must be in lower case.")
373 (defvar org-list-export-context '(block inlinetask)
374 "Context types where lists will be interpreted during export.
376 Valid types are `drawer', `inlinetask' and `block'. More
377 specifically, type `block' is determined by the variable
378 `org-list-forbidden-blocks'.")
382 ;;; Predicates and regexps
384 (defconst org-list-end-re (if org-list-empty-line-terminates-plain-lists "^[ \t]*\n"
385 "^[ \t]*\n[ \t]*\n")
386 "Regex corresponding to the end of a list.
387 It depends on `org-list-empty-line-terminates-plain-lists'.")
389 (defconst org-list-full-item-re
390 (concat "^[ \t]*\\(\\(?:[-+*]\\|\\(?:[0-9]+\\|[A-Za-z]\\)[.)]\\)\\(?:[ \t]+\\|$\\)\\)"
391 "\\(?:\\[@\\(?:start:\\)?\\([0-9]+\\|[A-Za-z]\\)\\][ \t]*\\)?"
392 "\\(?:\\(\\[[ X-]\\]\\)\\(?:[ \t]+\\|$\\)\\)?"
393 "\\(?:\\(.*\\)[ \t]+::\\(?:[ \t]+\\|$\\)\\)?")
394 "Matches a list item and puts everything into groups:
395 group 1: bullet
396 group 2: counter
397 group 3: checkbox
398 group 4: description tag")
400 (defun org-item-re ()
401 "Return the correct regular expression for plain lists."
402 (let ((term (cond
403 ((eq org-plain-list-ordered-item-terminator t) "[.)]")
404 ((= org-plain-list-ordered-item-terminator ?\)) ")")
405 ((= org-plain-list-ordered-item-terminator ?.) "\\.")
406 (t "[.)]")))
407 (alpha (if org-list-allow-alphabetical "\\|[A-Za-z]" "")))
408 (concat "\\([ \t]*\\([-+]\\|\\(\\([0-9]+" alpha "\\)" term
409 "\\)\\)\\|[ \t]+\\*\\)\\([ \t]+\\|$\\)")))
411 (defsubst org-item-beginning-re ()
412 "Regexp matching the beginning of a plain list item."
413 (concat "^" (org-item-re)))
415 (defun org-list-at-regexp-after-bullet-p (regexp)
416 "Is point at a list item with REGEXP after bullet?"
417 (and (org-at-item-p)
418 (save-excursion
419 (goto-char (match-end 0))
420 (let ((counter-re (concat "\\(?:\\[@\\(?:start:\\)?"
421 (if org-list-allow-alphabetical
422 "\\([0-9]+\\|[A-Za-z]\\)"
423 "[0-9]+")
424 "\\][ \t]*\\)")))
425 ;; Ignore counter if any
426 (when (looking-at counter-re) (goto-char (match-end 0))))
427 (looking-at regexp))))
429 (defun org-list-in-valid-context-p ()
430 "Is point in a context where lists are allowed?"
431 (not (org-in-block-p org-list-forbidden-blocks)))
433 (defun org-in-item-p ()
434 "Return item beginning position when in a plain list, nil otherwise."
435 (save-excursion
436 (beginning-of-line)
437 (let* ((case-fold-search t)
438 (context (org-list-context))
439 (lim-up (car context))
440 (inlinetask-re (and (featurep 'org-inlinetask)
441 (org-inlinetask-outline-regexp)))
442 (item-re (org-item-re))
443 ;; Indentation isn't meaningful when point starts at an empty
444 ;; line or an inline task.
445 (ind-ref (if (or (looking-at "^[ \t]*$")
446 (and inlinetask-re (looking-at inlinetask-re)))
447 10000
448 (org-get-indentation))))
449 (cond
450 ((eq (nth 2 context) 'invalid) nil)
451 ((looking-at item-re) (point))
453 ;; Detect if cursor in amidst `org-list-end-re'. First, count
454 ;; number HL of hard lines it takes, then call `org-in-regexp'
455 ;; to compute its boundaries END-BOUNDS. When point is
456 ;; in-between, move cursor before regexp beginning.
457 (let ((hl 0) (i -1) end-bounds)
458 (when (and (progn
459 (while (setq i (string-match
460 "[\r\n]" org-list-end-re (1+ i)))
461 (setq hl (1+ hl)))
462 (setq end-bounds (org-in-regexp org-list-end-re hl)))
463 (>= (point) (car end-bounds))
464 (< (point) (cdr end-bounds)))
465 (goto-char (car end-bounds))
466 (forward-line -1)))
467 ;; Look for an item, less indented that reference line.
468 (catch 'exit
469 (while t
470 (let ((ind (org-get-indentation)))
471 (cond
472 ;; This is exactly what we want.
473 ((and (looking-at item-re) (< ind ind-ref))
474 (throw 'exit (point)))
475 ;; At upper bound of search or looking at the end of a
476 ;; previous list: search is over.
477 ((<= (point) lim-up) (throw 'exit nil))
478 ((looking-at org-list-end-re) (throw 'exit nil))
479 ;; Skip blocks, drawers, inline-tasks, blank lines
480 ((and (looking-at "^[ \t]*#\\+end_")
481 (re-search-backward "^[ \t]*#\\+begin_" lim-up t)))
482 ((and (looking-at "^[ \t]*:END:")
483 (re-search-backward org-drawer-regexp lim-up t))
484 (beginning-of-line))
485 ((and inlinetask-re (looking-at inlinetask-re))
486 (org-inlinetask-goto-beginning)
487 (forward-line -1))
488 ((looking-at "^[ \t]*$") (forward-line -1))
489 ;; Text at column 0 cannot belong to a list: stop.
490 ((zerop ind) (throw 'exit nil))
491 ;; Normal text less indented than reference line, take
492 ;; it as new reference.
493 ((< ind ind-ref)
494 (setq ind-ref ind)
495 (forward-line -1))
496 (t (forward-line -1)))))))))))
498 (defun org-at-item-p ()
499 "Is point in a line starting a hand-formatted item?"
500 (save-excursion
501 (beginning-of-line)
502 (and (looking-at (org-item-re)) (org-list-in-valid-context-p))))
504 (defun org-at-item-bullet-p ()
505 "Is point at the bullet of a plain list item?"
506 (and (org-at-item-p)
507 (not (member (char-after) '(?\ ?\t)))
508 (< (point) (match-end 0))))
510 (defun org-at-item-timer-p ()
511 "Is point at a line starting a plain list item with a timer?"
512 (org-list-at-regexp-after-bullet-p
513 "\\([0-9]+:[0-9]+:[0-9]+\\)[ \t]+::[ \t]+"))
515 (defun org-at-item-description-p ()
516 "Is point at a description list item?"
517 (org-list-at-regexp-after-bullet-p "\\(\\S-.+\\)[ \t]+::\\([ \t]+\\|$\\)"))
519 (defun org-at-item-checkbox-p ()
520 "Is point at a line starting a plain-list item with a checklet?"
521 (org-list-at-regexp-after-bullet-p "\\(\\[[- X]\\]\\)[ \t]+"))
523 (defun org-at-item-counter-p ()
524 "Is point at a line starting a plain-list item with a counter?"
525 (and (org-at-item-p)
526 (looking-at org-list-full-item-re)
527 (match-string 2)))
531 ;;; Structures and helper functions
533 (defun org-list-context ()
534 "Determine context, and its boundaries, around point.
536 Context will be a cell like (MIN MAX CONTEXT) where MIN and MAX
537 are boundaries and CONTEXT is a symbol among `drawer', `block',
538 `invalid', `inlinetask' and nil.
540 Contexts `block' and `invalid' refer to `org-list-forbidden-blocks'."
541 (save-match-data
542 (save-excursion
543 (org-with-limited-levels
544 (beginning-of-line)
545 (let ((case-fold-search t) (pos (point)) beg end context-type
546 ;; Get positions of surrounding headings. This is the
547 ;; default context.
548 (lim-up (or (save-excursion (and (ignore-errors (org-back-to-heading t))
549 (point)))
550 (point-min)))
551 (lim-down (or (save-excursion (outline-next-heading)) (point-max))))
552 ;; Is point inside a drawer?
553 (let ((end-re "^[ \t]*:END:")
554 (beg-re org-drawer-regexp))
555 (when (save-excursion
556 (and (not (looking-at beg-re))
557 (not (looking-at end-re))
558 (setq beg (and (re-search-backward beg-re lim-up t)
559 (1+ (point-at-eol))))
560 (setq end (or (and (re-search-forward end-re lim-down t)
561 (1- (match-beginning 0)))
562 lim-down))
563 (>= end pos)))
564 (setq lim-up beg lim-down end context-type 'drawer)))
565 ;; Is point strictly in a block, and of which type?
566 (let ((block-re "^[ \t]*#\\+\\(begin\\|end\\)_") type)
567 (when (save-excursion
568 (and (not (looking-at block-re))
569 (setq beg (and (re-search-backward block-re lim-up t)
570 (1+ (point-at-eol))))
571 (looking-at "^[ \t]*#\\+begin_\\(\\S-+\\)")
572 (setq type (downcase (match-string 1)))
573 (goto-char beg)
574 (setq end (or (and (re-search-forward block-re lim-down t)
575 (1- (point-at-bol)))
576 lim-down))
577 (>= end pos)
578 (equal (downcase (match-string 1)) "end")))
579 (setq lim-up beg lim-down end
580 context-type (if (member type org-list-forbidden-blocks)
581 'invalid 'block))))
582 ;; Is point in an inlinetask?
583 (when (and (featurep 'org-inlinetask)
584 (save-excursion
585 (let* ((beg-re (org-inlinetask-outline-regexp))
586 (end-re (concat beg-re "END[ \t]*$")))
587 (and (not (looking-at "^\\*+"))
588 (setq beg (and (re-search-backward beg-re lim-up t)
589 (1+ (point-at-eol))))
590 (not (looking-at end-re))
591 (setq end (and (re-search-forward end-re lim-down t)
592 (1- (match-beginning 0))))
593 (> (point) pos)))))
594 (setq lim-up beg lim-down end context-type 'inlinetask))
595 ;; Return context boundaries and type.
596 (list lim-up lim-down context-type))))))
598 (defun org-list-struct ()
599 "Return structure of list at point.
601 A list structure is an alist where key is point at item, and
602 values are:
603 1. indentation,
604 2. bullet with trailing whitespace,
605 3. bullet counter, if any,
606 4. checkbox, if any,
607 5. description tag, if any,
608 6. position at item end.
610 Thus the following list, where numbers in parens are
611 point-at-bol:
613 - [X] first item (1)
614 1. sub-item 1 (18)
615 5. [@5] sub-item 2 (34)
616 some other text belonging to first item (55)
617 - last item (97)
618 + tag :: description (109)
619 (131)
621 will get the following structure:
623 \(\(1 0 \"- \" nil \"[X]\" nil 97\)
624 \(18 2 \"1. \" nil nil nil 34\)
625 \(34 2 \"5. \" \"5\" nil nil 55\)
626 \(97 0 \"- \" nil nil nil 131\)
627 \(109 2 \"+ \" nil nil \"tag\" 131\)
629 Assume point is at an item."
630 (save-excursion
631 (beginning-of-line)
632 (let* ((case-fold-search t)
633 (context (org-list-context))
634 (lim-up (car context))
635 (lim-down (nth 1 context))
636 (text-min-ind 10000)
637 (item-re (org-item-re))
638 (inlinetask-re (and (featurep 'org-inlinetask)
639 (org-inlinetask-outline-regexp)))
640 (beg-cell (cons (point) (org-get-indentation)))
641 ind itm-lst itm-lst-2 end-lst end-lst-2 struct
642 (assoc-at-point
643 (function
644 ;; Return association at point.
645 (lambda (ind)
646 (looking-at org-list-full-item-re)
647 (let ((bullet (match-string-no-properties 1)))
648 (list (point)
650 bullet
651 (match-string-no-properties 2) ; counter
652 (match-string-no-properties 3) ; checkbox
653 ;; Description tag.
654 (and (save-match-data (string-match "[-+*]" bullet))
655 (match-string-no-properties 4)))))))
656 (end-before-blank
657 (function
658 ;; Ensure list ends at the first blank line.
659 (lambda ()
660 (skip-chars-backward " \r\t\n")
661 (min (1+ (point-at-eol)) lim-down)))))
662 ;; 1. Read list from starting item to its beginning, and save
663 ;; top item position and indentation in BEG-CELL. Also store
664 ;; ending position of items in END-LST.
665 (save-excursion
666 (catch 'exit
667 (while t
668 (let ((ind (org-get-indentation)))
669 (cond
670 ((<= (point) lim-up)
671 ;; At upward limit: if we ended at an item, store it,
672 ;; else dismiss useless data recorded above BEG-CELL.
673 ;; Jump to part 2.
674 (throw 'exit
675 (setq itm-lst
676 (if (not (looking-at item-re))
677 (memq (assq (car beg-cell) itm-lst) itm-lst)
678 (setq beg-cell (cons (point) ind))
679 (cons (funcall assoc-at-point ind) itm-lst)))))
680 ;; Looking at a list ending regexp. Dismiss useless
681 ;; data recorded above BEG-CELL. Jump to part 2.
682 ((looking-at org-list-end-re)
683 (throw 'exit
684 (setq itm-lst
685 (memq (assq (car beg-cell) itm-lst) itm-lst))))
686 ;; Point is at an item. Add data to ITM-LST. It may
687 ;; also end a previous item: save it in END-LST. If
688 ;; ind is less or equal than BEG-CELL and there is no
689 ;; end at this ind or lesser, this item becomes the new
690 ;; BEG-CELL.
691 ((looking-at item-re)
692 (push (funcall assoc-at-point ind) itm-lst)
693 (push (cons ind (point)) end-lst)
694 (when (< ind text-min-ind) (setq beg-cell (cons (point) ind)))
695 (forward-line -1))
696 ;; Skip blocks, drawers, inline tasks, blank lines.
697 ((and (looking-at "^[ \t]*#\\+end_")
698 (re-search-backward "^[ \t]*#\\+begin_" lim-up t)))
699 ((and (looking-at "^[ \t]*:END:")
700 (re-search-backward org-drawer-regexp lim-up t))
701 (beginning-of-line))
702 ((and inlinetask-re (looking-at inlinetask-re))
703 (org-inlinetask-goto-beginning)
704 (forward-line -1))
705 ((looking-at "^[ \t]*$")
706 (forward-line -1))
707 ;; From there, point is not at an item. Interpret
708 ;; line's indentation:
709 ;; - text at column 0 is necessarily out of any list.
710 ;; Dismiss data recorded above BEG-CELL. Jump to
711 ;; part 2.
712 ;; - any other case may be an ending position for an
713 ;; hypothetical item above. Store it and proceed.
714 ((zerop ind)
715 (throw 'exit
716 (setq itm-lst
717 (memq (assq (car beg-cell) itm-lst) itm-lst))))
719 (when (< ind text-min-ind) (setq text-min-ind ind))
720 (push (cons ind (point)) end-lst)
721 (forward-line -1)))))))
722 ;; 2. Read list from starting point to its end, that is until we
723 ;; get out of context, or that a non-item line is less or
724 ;; equally indented than BEG-CELL's cdr. Also, store ending
725 ;; position of items in END-LST-2.
726 (catch 'exit
727 (while t
728 (let ((ind (org-get-indentation)))
729 (cond
730 ((>= (point) lim-down)
731 ;; At downward limit: this is de facto the end of the
732 ;; list. Save point as an ending position, and jump to
733 ;; part 3.
734 (throw 'exit
735 (push (cons 0 (funcall end-before-blank)) end-lst-2)))
736 ;; Looking at a list ending regexp. Save point as an
737 ;; ending position and jump to part 3.
738 ((looking-at org-list-end-re)
739 (throw 'exit (push (cons 0 (point)) end-lst-2)))
740 ((looking-at item-re)
741 ;; Point is at an item. Add data to ITM-LST-2. It may
742 ;; also end a previous item, so save it in END-LST-2.
743 (push (funcall assoc-at-point ind) itm-lst-2)
744 (push (cons ind (point)) end-lst-2)
745 (forward-line 1))
746 ;; Skip inline tasks and blank lines along the way
747 ((and inlinetask-re (looking-at inlinetask-re))
748 (org-inlinetask-goto-end))
749 ((looking-at "^[ \t]*$")
750 (forward-line 1))
751 ;; Ind is lesser or equal than BEG-CELL's. The list is
752 ;; over: store point as an ending position and jump to
753 ;; part 3.
754 ((<= ind (cdr beg-cell))
755 (throw 'exit
756 (push (cons 0 (funcall end-before-blank)) end-lst-2)))
757 ;; Else, if ind is lesser or equal than previous item's,
758 ;; this is an ending position: store it. In any case,
759 ;; skip block or drawer at point, and move to next line.
761 (when (<= ind (nth 1 (car itm-lst-2)))
762 (push (cons ind (point)) end-lst-2))
763 (cond
764 ((and (looking-at "^[ \t]*#\\+begin_")
765 (re-search-forward "^[ \t]*#\\+end_" lim-down t)))
766 ((and (looking-at org-drawer-regexp)
767 (re-search-forward "^[ \t]*:END:" lim-down t))))
768 (forward-line 1))))))
769 (setq struct (append itm-lst (cdr (nreverse itm-lst-2)))
770 end-lst (append end-lst (cdr (nreverse end-lst-2))))
771 ;; 3. Associate each item to its end position.
772 (org-list-struct-assoc-end struct end-lst)
773 ;; 4. Return STRUCT
774 struct)))
776 (defun org-list-struct-assoc-end (struct end-list)
777 "Associate proper ending point to items in STRUCT.
779 END-LIST is a pseudo-alist where car is indentation and cdr is
780 ending position.
782 This function modifies STRUCT."
783 (let ((endings end-list))
784 (mapc
785 (lambda (elt)
786 (let ((pos (car elt))
787 (ind (nth 1 elt)))
788 ;; Remove end candidates behind current item.
789 (while (or (<= (cdar endings) pos))
790 (pop endings))
791 ;; Add end position to item assoc.
792 (let ((old-end (nthcdr 6 elt))
793 (new-end (assoc-default ind endings '<=)))
794 (if old-end
795 (setcar old-end new-end)
796 (setcdr elt (append (cdr elt) (list new-end)))))))
797 struct)))
799 (defun org-list-prevs-alist (struct)
800 "Return alist between item and previous item in STRUCT."
801 (let ((item-end-alist (mapcar (lambda (e) (cons (car e) (nth 6 e)))
802 struct)))
803 (mapcar (lambda (e)
804 (let ((prev (car (rassq (car e) item-end-alist))))
805 (cons (car e) prev)))
806 struct)))
808 (defun org-list-parents-alist (struct)
809 "Return alist between item and parent in STRUCT."
810 (let* ((ind-to-ori (list (list (nth 1 (car struct)))))
811 (top-item (org-list-get-top-point struct))
812 (prev-pos (list top-item)))
813 (cons prev-pos
814 (mapcar (lambda (item)
815 (let ((pos (car item))
816 (ind (nth 1 item))
817 (prev-ind (caar ind-to-ori)))
818 (push pos prev-pos)
819 (cond
820 ((> prev-ind ind)
821 ;; A sub-list is over. Find the associated
822 ;; origin in IND-TO-ORI. If it cannot be
823 ;; found (ill-formed list), set its parent as
824 ;; the first item less indented. If there is
825 ;; none, make it a top-level item.
826 (setq ind-to-ori
827 (or (member (assq ind ind-to-ori) ind-to-ori)
828 (catch 'exit
829 (mapc
830 (lambda (e)
831 (when (< (car e) ind)
832 (throw 'exit (member e ind-to-ori))))
833 ind-to-ori)
834 (list (list ind)))))
835 (cons pos (cdar ind-to-ori)))
836 ;; A sub-list starts. Every item at IND will
837 ;; have previous item as its parent.
838 ((< prev-ind ind)
839 (let ((origin (nth 1 prev-pos)))
840 (push (cons ind origin) ind-to-ori)
841 (cons pos origin)))
842 ;; Another item in the same sub-list: it shares
843 ;; the same parent as the previous item.
844 (t (cons pos (cdar ind-to-ori))))))
845 (cdr struct)))))
849 ;;; Accessors
851 (defsubst org-list-get-nth (n key struct)
852 "Return the Nth value of KEY in STRUCT."
853 (nth n (assq key struct)))
855 (defun org-list-set-nth (n key struct new)
856 "Set the Nth value of KEY in STRUCT to NEW.
857 \nThis function modifies STRUCT."
858 (setcar (nthcdr n (assq key struct)) new))
860 (defsubst org-list-get-ind (item struct)
861 "Return indentation of ITEM in STRUCT."
862 (org-list-get-nth 1 item struct))
864 (defun org-list-set-ind (item struct ind)
865 "Set indentation of ITEM in STRUCT to IND.
866 \nThis function modifies STRUCT."
867 (org-list-set-nth 1 item struct ind))
869 (defsubst org-list-get-bullet (item struct)
870 "Return bullet of ITEM in STRUCT."
871 (org-list-get-nth 2 item struct))
873 (defun org-list-set-bullet (item struct bullet)
874 "Set bullet of ITEM in STRUCT to BULLET.
875 \nThis function modifies STRUCT."
876 (org-list-set-nth 2 item struct bullet))
878 (defsubst org-list-get-counter (item struct)
879 "Return counter of ITEM in STRUCT."
880 (org-list-get-nth 3 item struct))
882 (defsubst org-list-get-checkbox (item struct)
883 "Return checkbox of ITEM in STRUCT or nil."
884 (org-list-get-nth 4 item struct))
886 (defun org-list-set-checkbox (item struct checkbox)
887 "Set checkbox of ITEM in STRUCT to CHECKBOX.
888 \nThis function modifies STRUCT."
889 (org-list-set-nth 4 item struct checkbox))
891 (defsubst org-list-get-tag (item struct)
892 "Return end position of ITEM in STRUCT."
893 (org-list-get-nth 5 item struct))
895 (defun org-list-get-item-end (item struct)
896 "Return end position of ITEM in STRUCT."
897 (org-list-get-nth 6 item struct))
899 (defun org-list-get-item-end-before-blank (item struct)
900 "Return point at end of ITEM in STRUCT, before any blank line.
901 Point returned is at end of line."
902 (save-excursion
903 (goto-char (org-list-get-item-end item struct))
904 (skip-chars-backward " \r\t\n")
905 (point-at-eol)))
907 (defun org-list-get-parent (item struct parents)
908 "Return parent of ITEM or nil.
909 STRUCT is the list structure. PARENTS is the alist of parents,
910 as returned by `org-list-parents-alist'."
911 (let ((parents (or parents (org-list-parents-alist struct))))
912 (cdr (assq item parents))))
914 (defun org-list-has-child-p (item struct)
915 "Non-nil if ITEM has a child.
917 STRUCT is the list structure.
919 Value returned is the position of the first child of ITEM."
920 (let ((ind (org-list-get-ind item struct))
921 (child-maybe (car (nth 1 (member (assq item struct) struct)))))
922 (when (and child-maybe
923 (< ind (org-list-get-ind child-maybe struct)))
924 child-maybe)))
926 (defun org-list-get-next-item (item struct prevs)
927 "Return next item in same sub-list as ITEM, or nil.
928 STRUCT is the list structure. PREVS is the alist of previous
929 items, as returned by `org-list-prevs-alist'."
930 (car (rassq item prevs)))
932 (defun org-list-get-prev-item (item struct prevs)
933 "Return previous item in same sub-list as ITEM, or nil.
934 STRUCT is the list structure. PREVS is the alist of previous
935 items, as returned by `org-list-prevs-alist'."
936 (cdr (assq item prevs)))
938 (defun org-list-get-subtree (item struct)
939 "List all items having ITEM as a common ancestor, or nil.
940 STRUCT is the list structure."
941 (let* ((item-end (org-list-get-item-end item struct))
942 (sub-struct (cdr (member (assq item struct) struct)))
943 subtree)
944 (catch 'exit
945 (mapc (lambda (e)
946 (let ((pos (car e)))
947 (if (< pos item-end) (push pos subtree) (throw 'exit nil))))
948 sub-struct))
949 (nreverse subtree)))
951 (defun org-list-get-all-items (item struct prevs)
952 "List all items in the same sub-list as ITEM.
953 STRUCT is the list structure. PREVS is the alist of previous
954 items, as returned by `org-list-prevs-alist'."
955 (let ((prev-item item)
956 (next-item item)
957 before-item after-item)
958 (while (setq prev-item (org-list-get-prev-item prev-item struct prevs))
959 (push prev-item before-item))
960 (while (setq next-item (org-list-get-next-item next-item struct prevs))
961 (push next-item after-item))
962 (append before-item (list item) (nreverse after-item))))
964 (defun org-list-get-children (item struct parents)
965 "List all children of ITEM, or nil.
966 STRUCT is the list structure. PARENTS is the alist of parents,
967 as returned by `org-list-parents-alist'."
968 (let (all child)
969 (while (setq child (car (rassq item parents)))
970 (setq parents (cdr (member (assq child parents) parents)))
971 (push child all))
972 (nreverse all)))
974 (defun org-list-get-top-point (struct)
975 "Return point at beginning of list.
976 STRUCT is the list structure."
977 (caar struct))
979 (defun org-list-get-bottom-point (struct)
980 "Return point at bottom of list.
981 STRUCT is the list structure."
982 (apply 'max
983 (mapcar (lambda (e) (org-list-get-item-end (car e) struct)) struct)))
985 (defun org-list-get-list-begin (item struct prevs)
986 "Return point at beginning of sub-list ITEM belongs.
987 STRUCT is the list structure. PREVS is the alist of previous
988 items, as returned by `org-list-prevs-alist'."
989 (let ((first-item item) prev-item)
990 (while (setq prev-item (org-list-get-prev-item first-item struct prevs))
991 (setq first-item prev-item))
992 first-item))
994 (defalias 'org-list-get-first-item 'org-list-get-list-begin)
996 (defun org-list-get-last-item (item struct prevs)
997 "Return point at last item of sub-list ITEM belongs.
998 STRUCT is the list structure. PREVS is the alist of previous
999 items, as returned by `org-list-prevs-alist'."
1000 (let ((last-item item) next-item)
1001 (while (setq next-item (org-list-get-next-item last-item struct prevs))
1002 (setq last-item next-item))
1003 last-item))
1005 (defun org-list-get-list-end (item struct prevs)
1006 "Return point at end of sub-list ITEM belongs.
1007 STRUCT is the list structure. PREVS is the alist of previous
1008 items, as returned by `org-list-prevs-alist'."
1009 (org-list-get-item-end (org-list-get-last-item item struct prevs) struct))
1011 (defun org-list-get-list-type (item struct prevs)
1012 "Return the type of the list containing ITEM, as a symbol.
1014 STRUCT is the list structure. PREVS is the alist of previous
1015 items, as returned by `org-list-prevs-alist'.
1017 Possible types are `descriptive', `ordered' and `unordered'. The
1018 type is determined by the first item of the list."
1019 (let ((first (org-list-get-list-begin item struct prevs)))
1020 (cond
1021 ((string-match "[[:alnum:]]" (org-list-get-bullet first struct)) 'ordered)
1022 ((org-list-get-tag first struct) 'descriptive)
1023 (t 'unordered))))
1025 (defun org-list-get-item-number (item struct prevs parents)
1026 "Return ITEM's sequence number.
1028 STRUCT is the list structure. PREVS is the alist of previous
1029 items, as returned by `org-list-prevs-alist'. PARENTS is the
1030 alist of ancestors, as returned by `org-list-parents-alist'.
1032 Return value is a list of integers. Counters have an impact on
1033 that value."
1034 (let ((get-relative-number
1035 (function
1036 (lambda (item struct prevs)
1037 ;; Return relative sequence number of ITEM in the sub-list
1038 ;; it belongs. STRUCT is the list structure. PREVS is
1039 ;; the alist of previous items.
1040 (let ((seq 0) (pos item) counter)
1041 (while (and (not (setq counter (org-list-get-counter pos struct)))
1042 (setq pos (org-list-get-prev-item pos struct prevs)))
1043 (incf seq))
1044 (if (not counter) (1+ seq)
1045 (cond
1046 ((string-match "[A-Za-z]" counter)
1047 (+ (- (string-to-char (upcase (match-string 0 counter))) 64)
1048 seq))
1049 ((string-match "[0-9]+" counter)
1050 (+ (string-to-number (match-string 0 counter)) seq))
1051 (t (1+ seq)))))))))
1052 ;; Cons each parent relative number into return value (OUT).
1053 (let ((out (list (funcall get-relative-number item struct prevs)))
1054 (parent item))
1055 (while (setq parent (org-list-get-parent parent struct parents))
1056 (push (funcall get-relative-number parent struct prevs) out))
1057 ;; Return value.
1058 out)))
1062 ;;; Searching
1064 (defun org-list-search-generic (search re bound noerr)
1065 "Search a string in valid contexts for lists.
1066 Arguments SEARCH, RE, BOUND and NOERR are similar to those used
1067 in `re-search-forward'."
1068 (catch 'exit
1069 (let ((origin (point)))
1070 (while t
1071 ;; 1. No match: return to origin or bound, depending on NOERR.
1072 (unless (funcall search re bound noerr)
1073 (throw 'exit (and (goto-char (if (memq noerr '(t nil)) origin bound))
1074 nil)))
1075 ;; 2. Match in valid context: return point. Else, continue
1076 ;; searching.
1077 (when (org-list-in-valid-context-p) (throw 'exit (point)))))))
1079 (defun org-list-search-backward (regexp &optional bound noerror)
1080 "Like `re-search-backward' but stop only where lists are recognized.
1081 Arguments REGEXP, BOUND and NOERROR are similar to those used in
1082 `re-search-backward'."
1083 (org-list-search-generic #'re-search-backward
1084 regexp (or bound (point-min)) noerror))
1086 (defun org-list-search-forward (regexp &optional bound noerror)
1087 "Like `re-search-forward' but stop only where lists are recognized.
1088 Arguments REGEXP, BOUND and NOERROR are similar to those used in
1089 `re-search-forward'."
1090 (org-list-search-generic #'re-search-forward
1091 regexp (or bound (point-max)) noerror))
1095 ;;; Methods on structures
1097 (defsubst org-list-bullet-string (bullet)
1098 "Return BULLET with the correct number of whitespaces.
1099 It determines the number of whitespaces to append by looking at
1100 `org-list-two-spaces-after-bullet-regexp'."
1101 (save-match-data
1102 (let ((spaces (if (and org-list-two-spaces-after-bullet-regexp
1103 (string-match
1104 org-list-two-spaces-after-bullet-regexp bullet))
1106 " ")))
1107 (if (string-match "\\S-+\\([ \t]*\\)" bullet)
1108 (replace-match spaces nil nil bullet 1)
1109 bullet))))
1111 (defun org-list-swap-items (beg-A beg-B struct)
1112 "Swap item starting at BEG-A with item starting at BEG-B in STRUCT.
1114 Blank lines at the end of items are left in place. Item
1115 visibility is preserved. Return the new structure after the
1116 changes.
1118 Assume BEG-A is lesser than BEG-B and that BEG-A and BEG-B belong
1119 to the same sub-list.
1121 This function modifies STRUCT."
1122 (save-excursion
1123 (let* ((end-A-no-blank (org-list-get-item-end-before-blank beg-A struct))
1124 (end-B-no-blank (org-list-get-item-end-before-blank beg-B struct))
1125 (end-A (org-list-get-item-end beg-A struct))
1126 (end-B (org-list-get-item-end beg-B struct))
1127 (size-A (- end-A-no-blank beg-A))
1128 (size-B (- end-B-no-blank beg-B))
1129 (body-A (buffer-substring beg-A end-A-no-blank))
1130 (body-B (buffer-substring beg-B end-B-no-blank))
1131 (between-A-no-blank-and-B (buffer-substring end-A-no-blank beg-B))
1132 (sub-A (cons beg-A (org-list-get-subtree beg-A struct)))
1133 (sub-B (cons beg-B (org-list-get-subtree beg-B struct)))
1134 ;; Store overlays responsible for visibility status. We
1135 ;; also need to store their boundaries as they will be
1136 ;; removed from buffer.
1137 (overlays
1138 (cons
1139 (delq nil
1140 (mapcar (lambda (o)
1141 (and (>= (overlay-start o) beg-A)
1142 (<= (overlay-end o) end-A)
1143 (list o (overlay-start o) (overlay-end o))))
1144 (overlays-in beg-A end-A)))
1145 (delq nil
1146 (mapcar (lambda (o)
1147 (and (>= (overlay-start o) beg-B)
1148 (<= (overlay-end o) end-B)
1149 (list o (overlay-start o) (overlay-end o))))
1150 (overlays-in beg-B end-B))))))
1151 ;; 1. Move effectively items in buffer.
1152 (goto-char beg-A)
1153 (delete-region beg-A end-B-no-blank)
1154 (insert (concat body-B between-A-no-blank-and-B body-A))
1155 ;; 2. Now modify struct. No need to re-read the list, the
1156 ;; transformation is just a shift of positions. Some special
1157 ;; attention is required for items ending at END-A and END-B
1158 ;; as empty spaces are not moved there. In others words,
1159 ;; item BEG-A will end with whitespaces that were at the end
1160 ;; of BEG-B and the same applies to BEG-B.
1161 (dolist (e struct)
1162 (let ((pos (car e)))
1163 (cond
1164 ((< pos beg-A))
1165 ((memq pos sub-A)
1166 (let ((end-e (nth 6 e)))
1167 (setcar e (+ pos (- end-B-no-blank end-A-no-blank)))
1168 (setcar (nthcdr 6 e)
1169 (+ end-e (- end-B-no-blank end-A-no-blank)))
1170 (when (= end-e end-A) (setcar (nthcdr 6 e) end-B))))
1171 ((memq pos sub-B)
1172 (let ((end-e (nth 6 e)))
1173 (setcar e (- (+ pos beg-A) beg-B))
1174 (setcar (nthcdr 6 e) (+ end-e (- beg-A beg-B)))
1175 (when (= end-e end-B)
1176 (setcar (nthcdr 6 e)
1177 (+ beg-A size-B (- end-A end-A-no-blank))))))
1178 ((< pos beg-B)
1179 (let ((end-e (nth 6 e)))
1180 (setcar e (+ pos (- size-B size-A)))
1181 (setcar (nthcdr 6 e) (+ end-e (- size-B size-A))))))))
1182 (setq struct (sort struct #'car-less-than-car))
1183 ;; Restore visibility status, by moving overlays to their new
1184 ;; position.
1185 (dolist (ov (car overlays))
1186 (move-overlay
1187 (car ov)
1188 (+ (nth 1 ov) (- (+ beg-B (- size-B size-A)) beg-A))
1189 (+ (nth 2 ov) (- (+ beg-B (- size-B size-A)) beg-A))))
1190 (dolist (ov (cdr overlays))
1191 (move-overlay (car ov)
1192 (+ (nth 1 ov) (- beg-A beg-B))
1193 (+ (nth 2 ov) (- beg-A beg-B))))
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 ;; neighbors' 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 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 inner overlays (to preserve visibility).
1478 (overlays (org-remove-if (lambda (o) (or (< (overlay-start o) item)
1479 (> (overlay-end o) item)))
1480 (overlays-in item item-end))))
1481 (cond
1482 ((eq dest 'delete) (org-list-delete-item item struct))
1483 ((eq dest 'kill)
1484 (kill-new body)
1485 (org-list-delete-item item struct))
1486 ((and (integerp dest) (/= item ins-point))
1487 (setq item (copy-marker item))
1488 (setq struct (org-list-insert-item ins-point struct prevs nil body))
1489 ;; 1. Structure returned by `org-list-insert-item' may not be
1490 ;; accurate, as it cannot see sub-items included in BODY.
1491 ;; Thus, first compute the real structure so far.
1492 (let ((moved-items
1493 (cons (marker-position item)
1494 (org-list-get-subtree (marker-position item) struct)))
1495 (new-end (org-list-get-item-end (point) struct))
1496 (old-end (org-list-get-item-end (marker-position item) struct))
1497 (new-item (point))
1498 (shift (- (point) item)))
1499 ;; 1.1. Remove the item just created in structure.
1500 (setq struct (delete (assq new-item struct) struct))
1501 ;; 1.2. Copy ITEM and any of its sub-items at NEW-ITEM.
1502 (setq struct (sort
1503 (append
1504 struct
1505 (mapcar (lambda (e)
1506 (let* ((cell (assq e struct))
1507 (pos (car cell))
1508 (end (nth 6 cell)))
1509 (cons (+ pos shift)
1510 (append (butlast (cdr cell))
1511 (list (if (= end old-end)
1512 new-end
1513 (+ end shift)))))))
1514 moved-items))
1515 #'car-less-than-car)))
1516 ;; 2. Restore inner overlays.
1517 (dolist (o overlays)
1518 (move-overlay o
1519 (+ (overlay-start o) (- (point) item))
1520 (+ (overlay-end o) (- (point) item))))
1521 ;; 3. Eventually delete extra copy of the item and clean marker.
1522 (prog1 (org-list-delete-item (marker-position item) struct)
1523 (move-marker item nil)))
1524 (t struct))))
1526 (defun org-list-struct-outdent (start end struct parents)
1527 "Outdent items between positions START and END.
1529 STRUCT is the list structure. PARENTS is the alist of items'
1530 parents, as returned by `org-list-parents-alist'.
1532 START is included, END excluded."
1533 (let* (acc
1534 (out (lambda (cell)
1535 (let* ((item (car cell))
1536 (parent (cdr cell)))
1537 (cond
1538 ;; Item not yet in zone: keep association.
1539 ((< item start) cell)
1540 ;; Item out of zone: follow associations in ACC.
1541 ((>= item end)
1542 (let ((convert (and parent (assq parent acc))))
1543 (if convert (cons item (cdr convert)) cell)))
1544 ;; Item has no parent: error
1545 ((not parent)
1546 (error "Cannot outdent top-level items"))
1547 ;; Parent is outdented: keep association.
1548 ((>= parent start)
1549 (push (cons parent item) acc) cell)
1551 ;; Parent isn't outdented: reparent to grand-parent.
1552 (let ((grand-parent (org-list-get-parent
1553 parent struct parents)))
1554 (push (cons parent item) acc)
1555 (cons item grand-parent))))))))
1556 (mapcar out parents)))
1558 (defun org-list-struct-indent (start end struct parents prevs)
1559 "Indent items between positions START and END.
1561 STRUCT is the list structure. PARENTS is the alist of parents
1562 and PREVS is the alist of previous items, returned by,
1563 respectively, `org-list-parents-alist' and
1564 `org-list-prevs-alist'.
1566 START is included and END excluded.
1568 STRUCT may be modified if `org-list-demote-modify-bullet' matches
1569 bullets between START and END."
1570 (let* (acc
1571 (set-assoc (lambda (cell) (push cell acc) cell))
1572 (change-bullet-maybe
1573 (function
1574 (lambda (item)
1575 (let ((new-bul-p
1576 (cdr (assoc
1577 ;; Normalize ordered bullets.
1578 (let ((bul (org-trim
1579 (org-list-get-bullet item struct))))
1580 (cond ((string-match "[A-Z]\\." bul) "A.")
1581 ((string-match "[A-Z])" bul) "A)")
1582 ((string-match "[a-z]\\." bul) "a.")
1583 ((string-match "[a-z])" bul) "a)")
1584 ((string-match "[0-9]\\." bul) "1.")
1585 ((string-match "[0-9])" bul) "1)")
1586 (t bul)))
1587 org-list-demote-modify-bullet))))
1588 (when new-bul-p (org-list-set-bullet item struct new-bul-p))))))
1589 (ind
1590 (lambda (cell)
1591 (let* ((item (car cell))
1592 (parent (cdr cell)))
1593 (cond
1594 ;; Item not yet in zone: keep association.
1595 ((< item start) cell)
1596 ((>= item end)
1597 ;; Item out of zone: follow associations in ACC.
1598 (let ((convert (assq parent acc)))
1599 (if convert (cons item (cdr convert)) cell)))
1601 ;; Item is in zone...
1602 (let ((prev (org-list-get-prev-item item struct prevs)))
1603 ;; Check if bullet needs to be changed.
1604 (funcall change-bullet-maybe item)
1605 (cond
1606 ;; First item indented but not parent: error
1607 ((and (not prev) (< parent start))
1608 (error "Cannot indent the first item of a list"))
1609 ;; First item and parent indented: keep same
1610 ;; parent.
1611 ((not prev) (funcall set-assoc cell))
1612 ;; Previous item not indented: reparent to it.
1613 ((< prev start) (funcall set-assoc (cons item prev)))
1614 ;; Previous item indented: reparent like it.
1616 (funcall set-assoc
1617 (cons item (cdr (assq prev acc)))))))))))))
1618 (mapcar ind parents)))
1622 ;;; Repairing structures
1624 (defun org-list-use-alpha-bul-p (first struct prevs)
1625 "Non-nil if list starting at FIRST can have alphabetical bullets.
1627 STRUCT is list structure. PREVS is the alist of previous items,
1628 as returned by `org-list-prevs-alist'."
1629 (and org-list-allow-alphabetical
1630 (catch 'exit
1631 (let ((item first) (ascii 64) (case-fold-search nil))
1632 ;; Pretend that bullets are uppercase and check if alphabet
1633 ;; is sufficient, taking counters into account.
1634 (while item
1635 (let ((bul (org-list-get-bullet item struct))
1636 (count (org-list-get-counter item struct)))
1637 ;; Virtually determine current bullet
1638 (if (and count (string-match "[a-zA-Z]" count))
1639 ;; Counters are not case-sensitive.
1640 (setq ascii (string-to-char (upcase count)))
1641 (setq ascii (1+ ascii)))
1642 ;; Test if bullet would be over z or Z.
1643 (if (> ascii 90)
1644 (throw 'exit nil)
1645 (setq item (org-list-get-next-item item struct prevs)))))
1646 ;; All items checked. All good.
1647 t))))
1649 (defun org-list-inc-bullet-maybe (bullet)
1650 "Increment BULLET if applicable."
1651 (let ((case-fold-search nil))
1652 (cond
1653 ;; Num bullet: increment it.
1654 ((string-match "[0-9]+" bullet)
1655 (replace-match
1656 (number-to-string (1+ (string-to-number (match-string 0 bullet))))
1657 nil nil bullet))
1658 ;; Alpha bullet: increment it.
1659 ((string-match "[A-Za-z]" bullet)
1660 (replace-match
1661 (char-to-string (1+ (string-to-char (match-string 0 bullet))))
1662 nil nil bullet))
1663 ;; Unordered bullet: leave it.
1664 (t bullet))))
1666 (defun org-list-struct-fix-bul (struct prevs)
1667 "Verify and correct bullets in STRUCT.
1668 PREVS is the alist of previous items, as returned by
1669 `org-list-prevs-alist'.
1671 This function modifies STRUCT."
1672 (let ((case-fold-search nil)
1673 (fix-bul
1674 (function
1675 ;; Set bullet of ITEM in STRUCT, depending on the type of
1676 ;; first item of the list, the previous bullet and counter
1677 ;; if any.
1678 (lambda (item)
1679 (let* ((prev (org-list-get-prev-item item struct prevs))
1680 (prev-bul (and prev (org-list-get-bullet prev struct)))
1681 (counter (org-list-get-counter item struct))
1682 (bullet (org-list-get-bullet item struct))
1683 (alphap (and (not prev)
1684 (org-list-use-alpha-bul-p item struct prevs))))
1685 (org-list-set-bullet
1686 item struct
1687 (org-list-bullet-string
1688 (cond
1689 ;; Alpha counter in alpha list: use counter.
1690 ((and prev counter
1691 (string-match "[a-zA-Z]" counter)
1692 (string-match "[a-zA-Z]" prev-bul))
1693 ;; Use cond to be sure `string-match' is used in
1694 ;; both cases.
1695 (let ((real-count
1696 (cond
1697 ((string-match "[a-z]" prev-bul) (downcase counter))
1698 ((string-match "[A-Z]" prev-bul) (upcase counter)))))
1699 (replace-match real-count nil nil prev-bul)))
1700 ;; Num counter in a num list: use counter.
1701 ((and prev counter
1702 (string-match "[0-9]+" counter)
1703 (string-match "[0-9]+" prev-bul))
1704 (replace-match counter nil nil prev-bul))
1705 ;; No counter: increase, if needed, previous bullet.
1706 (prev
1707 (org-list-inc-bullet-maybe (org-list-get-bullet prev struct)))
1708 ;; Alpha counter at first item: use counter.
1709 ((and counter (org-list-use-alpha-bul-p item struct prevs)
1710 (string-match "[A-Za-z]" counter)
1711 (string-match "[A-Za-z]" bullet))
1712 (let ((real-count
1713 (cond
1714 ((string-match "[a-z]" bullet) (downcase counter))
1715 ((string-match "[A-Z]" bullet) (upcase counter)))))
1716 (replace-match real-count nil nil bullet)))
1717 ;; Num counter at first item: use counter.
1718 ((and counter
1719 (string-match "[0-9]+" counter)
1720 (string-match "[0-9]+" bullet))
1721 (replace-match counter nil nil bullet))
1722 ;; First bullet is alpha uppercase: use "A".
1723 ((and alphap (string-match "[A-Z]" bullet))
1724 (replace-match "A" nil nil bullet))
1725 ;; First bullet is alpha lowercase: use "a".
1726 ((and alphap (string-match "[a-z]" bullet))
1727 (replace-match "a" nil nil bullet))
1728 ;; First bullet is num: use "1".
1729 ((string-match "\\([0-9]+\\|[A-Za-z]\\)" bullet)
1730 (replace-match "1" nil nil bullet))
1731 ;; Not an ordered list: keep bullet.
1732 (t bullet)))))))))
1733 (mapc fix-bul (mapcar 'car struct))))
1735 (defun org-list-struct-fix-ind (struct parents &optional bullet-size)
1736 "Verify and correct indentation in STRUCT.
1738 PARENTS is the alist of parents, as returned by
1739 `org-list-parents-alist'.
1741 If numeric optional argument BULLET-SIZE is set, assume all
1742 bullets in list have this length to determine new indentation.
1744 This function modifies STRUCT."
1745 (let* ((ancestor (org-list-get-top-point struct))
1746 (top-ind (org-list-get-ind ancestor struct))
1747 (new-ind
1748 (lambda (item)
1749 (let ((parent (org-list-get-parent item struct parents)))
1750 (if parent
1751 ;; Indent like parent + length of parent's bullet +
1752 ;; sub-list offset.
1753 (org-list-set-ind
1754 item struct (+ (or bullet-size
1755 (length
1756 (org-list-get-bullet parent struct)))
1757 (org-list-get-ind parent struct)
1758 org-list-indent-offset))
1759 ;; If no parent, indent like top-point.
1760 (org-list-set-ind item struct top-ind))))))
1761 (mapc new-ind (mapcar 'car (cdr struct)))))
1763 (defun org-list-struct-fix-box (struct parents prevs &optional ordered)
1764 "Verify and correct checkboxes in STRUCT.
1766 PARENTS is the alist of parents and PREVS is the alist of
1767 previous items, as returned by, respectively,
1768 `org-list-parents-alist' and `org-list-prevs-alist'.
1770 If ORDERED is non-nil, a checkbox can only be checked when every
1771 checkbox before it is checked too. If there was an attempt to
1772 break this rule, the function will return the blocking item. In
1773 all others cases, the return value will be nil.
1775 This function modifies STRUCT."
1776 (let ((all-items (mapcar 'car struct))
1777 (set-parent-box
1778 (function
1779 (lambda (item)
1780 (let* ((box-list
1781 (mapcar (lambda (child)
1782 (org-list-get-checkbox child struct))
1783 (org-list-get-children item struct parents))))
1784 (org-list-set-checkbox
1785 item struct
1786 (cond
1787 ((and (member "[ ]" box-list) (member "[X]" box-list)) "[-]")
1788 ((member "[-]" box-list) "[-]")
1789 ((member "[X]" box-list) "[X]")
1790 ((member "[ ]" box-list) "[ ]")
1791 ;; Parent has no boxed child: leave box as-is.
1792 (t (org-list-get-checkbox item struct))))))))
1793 parent-list)
1794 ;; 1. List all parents with a checkbox.
1795 (mapc
1796 (lambda (e)
1797 (let* ((parent (org-list-get-parent e struct parents))
1798 (parent-box-p (org-list-get-checkbox parent struct)))
1799 (when (and parent-box-p (not (memq parent parent-list)))
1800 (push parent parent-list))))
1801 all-items)
1802 ;; 2. Sort those parents by decreasing indentation.
1803 (setq parent-list (sort parent-list
1804 (lambda (e1 e2)
1805 (> (org-list-get-ind e1 struct)
1806 (org-list-get-ind e2 struct)))))
1807 ;; 3. For each parent, get all children's checkboxes to determine
1808 ;; and set its checkbox accordingly.
1809 (mapc set-parent-box parent-list)
1810 ;; 4. If ORDERED is set, see if we need to uncheck some boxes.
1811 (when ordered
1812 (let* ((box-list
1813 (mapcar (lambda (e) (org-list-get-checkbox e struct)) all-items))
1814 (after-unchecked (member "[ ]" box-list)))
1815 ;; There are boxes checked after an unchecked one: fix that.
1816 (when (member "[X]" after-unchecked)
1817 (let ((index (- (length struct) (length after-unchecked))))
1818 (mapc (lambda (e)
1819 (when (org-list-get-checkbox e struct)
1820 (org-list-set-checkbox e struct "[ ]")))
1821 (nthcdr index all-items))
1822 ;; Verify once again the structure, without ORDERED.
1823 (org-list-struct-fix-box struct parents prevs nil)
1824 ;; Return blocking item.
1825 (nth index all-items)))))))
1827 (defun org-list-struct-fix-item-end (struct)
1828 "Verify and correct each item end position in STRUCT.
1830 This function modifies STRUCT."
1831 (let (end-list acc-end)
1832 (mapc (lambda (e)
1833 (let* ((pos (car e))
1834 (ind-pos (org-list-get-ind pos struct))
1835 (end-pos (org-list-get-item-end pos struct)))
1836 (unless (assq end-pos struct)
1837 ;; To determine real ind of an ending position that is
1838 ;; not at an item, we have to find the item it belongs
1839 ;; to: it is the last item (ITEM-UP), whose ending is
1840 ;; further than the position we're interested in.
1841 (let ((item-up (assoc-default end-pos acc-end '>)))
1842 (push (cons
1843 ;; Else part is for the bottom point.
1844 (if item-up (+ (org-list-get-ind item-up struct) 2) 0)
1845 end-pos)
1846 end-list)))
1847 (push (cons ind-pos pos) end-list)
1848 (push (cons end-pos pos) acc-end)))
1849 struct)
1850 (setq end-list (sort end-list (lambda (e1 e2) (< (cdr e1) (cdr e2)))))
1851 (org-list-struct-assoc-end struct end-list)))
1853 (defun org-list-struct-apply-struct (struct old-struct)
1854 "Apply set difference between STRUCT and OLD-STRUCT to the buffer.
1856 OLD-STRUCT is the structure before any modifications, and STRUCT
1857 the structure to be applied. The function will only modify parts
1858 of the list which have changed.
1860 Initial position of cursor is restored after the changes."
1861 (let* ((origin (point-marker))
1862 (inlinetask-re (and (featurep 'org-inlinetask)
1863 (org-inlinetask-outline-regexp)))
1864 (item-re (org-item-re))
1865 (shift-body-ind
1866 (function
1867 ;; Shift the indentation between END and BEG by DELTA.
1868 ;; Start from the line before END.
1869 (lambda (end beg delta)
1870 (goto-char end)
1871 (skip-chars-backward " \r\t\n")
1872 (beginning-of-line)
1873 (while (or (> (point) beg)
1874 (and (= (point) beg)
1875 (not (looking-at item-re))))
1876 (cond
1877 ;; Skip inline tasks.
1878 ((and inlinetask-re (looking-at inlinetask-re))
1879 (org-inlinetask-goto-beginning))
1880 ;; Shift only non-empty lines.
1881 ((org-looking-at-p "^[ \t]*\\S-")
1882 (org-indent-line-to (+ (org-get-indentation) 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-LIST, 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 (dolist (e old-struct)
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 ;; 2. Slice the items into parts that should be shifted by the
1941 ;; same amount of indentation. Each slice follow the pattern
1942 ;; (END BEG DELTA). Slices are returned in reverse order.
1943 (setq all-ends (sort (append (mapcar #'car itm-shift)
1944 (org-uniquify (mapcar #'car end-list)))
1945 #'<)
1946 acc-end (nreverse acc-end))
1947 (while (cdr all-ends)
1948 (let* ((up (pop all-ends))
1949 (down (car all-ends))
1950 (itemp (assq up struct))
1951 (delta
1952 (if itemp (cdr (assq up itm-shift))
1953 ;; If we're not at an item, there's a child of the
1954 ;; item point belongs to above. Make sure the less
1955 ;; indented line in this slice has the same column
1956 ;; as that child.
1957 (let* ((child (cdr (assq up acc-end)))
1958 (ind (org-list-get-ind child struct))
1959 (min-ind most-positive-fixnum))
1960 (save-excursion
1961 (goto-char up)
1962 (while (< (point) down)
1963 ;; Ignore empty lines. Also ignore blocks and
1964 ;; drawers contents.
1965 (unless (org-looking-at-p "[ \t]*$")
1966 (setq min-ind (min (org-get-indentation) min-ind))
1967 (cond
1968 ((and (looking-at "#\\+BEGIN\\(:\\|_\\S-+\\)")
1969 (re-search-forward
1970 (format "^[ \t]*#\\+END%s[ \t]*$"
1971 (match-string 1))
1972 down t)))
1973 ((and (looking-at org-drawer-regexp)
1974 (re-search-forward "^[ \t]*:END:[ \t]*$"
1975 down t)))))
1976 (forward-line)))
1977 (- ind min-ind)))))
1978 (push (list down up delta) sliced-struct)))
1979 ;; 3. Shift each slice in buffer, provided delta isn't 0, from
1980 ;; end to beginning. Take a special action when beginning is
1981 ;; at item bullet.
1982 (dolist (e sliced-struct)
1983 (unless (zerop (nth 2 e)) (apply shift-body-ind e))
1984 (let* ((beg (nth 1 e))
1985 (cell (assq beg struct)))
1986 (unless (or (not cell) (equal cell (assq beg old-struct)))
1987 (funcall modify-item beg)))))
1988 ;; 4. Go back to initial position and clean marker.
1989 (goto-char origin)
1990 (move-marker origin nil)))
1992 (defun org-list-write-struct (struct parents &optional old-struct)
1993 "Correct bullets, checkboxes and indentation in list at point.
1995 STRUCT is the list structure. PARENTS is the alist of parents,
1996 as returned by `org-list-parents-alist'.
1998 When non-nil, optional argument OLD-STRUCT is the reference
1999 structure of the list. It should be provided whenever STRUCT
2000 doesn't correspond anymore to the real list in buffer."
2001 ;; Order of functions matters here: checkboxes and endings need
2002 ;; correct indentation to be set, and indentation needs correct
2003 ;; bullets.
2005 ;; 0. Save a copy of structure before modifications
2006 (let ((old-struct (or old-struct (copy-tree struct))))
2007 ;; 1. Set a temporary, but coherent with PARENTS, indentation in
2008 ;; order to get items endings and bullets properly
2009 (org-list-struct-fix-ind struct parents 2)
2010 ;; 2. Fix each item end to get correct prevs alist.
2011 (org-list-struct-fix-item-end struct)
2012 ;; 3. Get bullets right.
2013 (let ((prevs (org-list-prevs-alist struct)))
2014 (org-list-struct-fix-bul struct prevs)
2015 ;; 4. Now get real indentation.
2016 (org-list-struct-fix-ind struct parents)
2017 ;; 5. Eventually fix checkboxes.
2018 (org-list-struct-fix-box struct parents prevs))
2019 ;; 6. Apply structure modifications to buffer.
2020 (org-list-struct-apply-struct struct old-struct)))
2024 ;;; Misc Tools
2026 (defun org-apply-on-list (function init-value &rest args)
2027 "Call FUNCTION on each item of the list at point.
2028 FUNCTION must be called with at least one argument: INIT-VALUE,
2029 that will contain the value returned by the function at the
2030 previous item, plus ARGS extra arguments.
2032 FUNCTION is applied on items in reverse order.
2034 As an example, \(org-apply-on-list \(lambda \(result\) \(1+ result\)\) 0\)
2035 will return the number of items in the current list.
2037 Sublists of the list are skipped. Cursor is always at the
2038 beginning of the item."
2039 (let* ((struct (org-list-struct))
2040 (prevs (org-list-prevs-alist struct))
2041 (item (copy-marker (point-at-bol)))
2042 (all (org-list-get-all-items (marker-position item) struct prevs))
2043 (value init-value))
2044 (mapc (lambda (e)
2045 (goto-char e)
2046 (setq value (apply function value args)))
2047 (nreverse all))
2048 (goto-char item)
2049 (move-marker item nil)
2050 value))
2052 (defun org-list-set-item-visibility (item struct view)
2053 "Set visibility of ITEM in STRUCT to VIEW.
2055 Possible values are: `folded', `children' or `subtree'. See
2056 `org-cycle' for more information."
2057 (cond
2058 ((eq view 'folded)
2059 (let ((item-end (org-list-get-item-end-before-blank item struct)))
2060 ;; Hide from eol
2061 (outline-flag-region (save-excursion (goto-char item) (point-at-eol))
2062 item-end t)))
2063 ((eq view 'children)
2064 ;; First show everything.
2065 (org-list-set-item-visibility item struct 'subtree)
2066 ;; Then fold every child.
2067 (let* ((parents (org-list-parents-alist struct))
2068 (children (org-list-get-children item struct parents)))
2069 (mapc (lambda (e)
2070 (org-list-set-item-visibility e struct 'folded))
2071 children)))
2072 ((eq view 'subtree)
2073 ;; Show everything
2074 (let ((item-end (org-list-get-item-end item struct)))
2075 (outline-flag-region item item-end nil)))))
2077 (defun org-list-item-body-column (item)
2078 "Return column at which body of ITEM should start."
2079 (save-excursion
2080 (goto-char item)
2081 (looking-at "[ \t]*\\(\\S-+\\)\\(.*[ \t]+::\\)?\\([ \t]+\\|$\\)")
2082 (if (match-beginning 2)
2083 (let ((start (1+ (match-end 2)))
2084 (ind (org-get-indentation)))
2085 (if (> start (+ ind org-description-max-indent)) (+ ind 5) start))
2086 (+ (progn (goto-char (match-end 1)) (current-column))
2087 (if (and org-list-two-spaces-after-bullet-regexp
2088 (org-string-match-p org-list-two-spaces-after-bullet-regexp
2089 (match-string 1)))
2091 1)))))
2095 ;;; Interactive functions
2097 (defalias 'org-list-get-item-begin 'org-in-item-p)
2099 (defun org-beginning-of-item ()
2100 "Go to the beginning of the current item.
2101 Throw an error when not in a list."
2102 (interactive)
2103 (let ((begin (org-in-item-p)))
2104 (if begin (goto-char begin) (error "Not in an item"))))
2106 (defun org-beginning-of-item-list ()
2107 "Go to the beginning item of the current list or sublist.
2108 Throw an error when not in a list."
2109 (interactive)
2110 (let ((begin (org-in-item-p)))
2111 (if (not begin)
2112 (error "Not in an item")
2113 (goto-char begin)
2114 (let* ((struct (org-list-struct))
2115 (prevs (org-list-prevs-alist struct)))
2116 (goto-char (org-list-get-list-begin begin struct prevs))))))
2118 (defun org-end-of-item-list ()
2119 "Go to the end of the current list or sublist.
2120 Throw an error when not in a list."
2121 (interactive)
2122 (let ((begin (org-in-item-p)))
2123 (if (not begin)
2124 (error "Not in an item")
2125 (goto-char begin)
2126 (let* ((struct (org-list-struct))
2127 (prevs (org-list-prevs-alist struct)))
2128 (goto-char (org-list-get-list-end begin struct prevs))))))
2130 (defun org-end-of-item ()
2131 "Go to the end of the current item.
2132 Throw an error when not in a list."
2133 (interactive)
2134 (let ((begin (org-in-item-p)))
2135 (if (not begin)
2136 (error "Not in an item")
2137 (goto-char begin)
2138 (let ((struct (org-list-struct)))
2139 (goto-char (org-list-get-item-end begin struct))))))
2141 (defun org-previous-item ()
2142 "Move to the beginning of the previous item.
2143 Throw an error when not in a list. Also throw an error when at
2144 first item, unless `org-list-use-circular-motion' is non-nil."
2145 (interactive)
2146 (let ((item (org-in-item-p)))
2147 (if (not item)
2148 (error "Not in an item")
2149 (goto-char item)
2150 (let* ((struct (org-list-struct))
2151 (prevs (org-list-prevs-alist struct))
2152 (prevp (org-list-get-prev-item item struct prevs)))
2153 (cond
2154 (prevp (goto-char prevp))
2155 (org-list-use-circular-motion
2156 (goto-char (org-list-get-last-item item struct prevs)))
2157 (t (error "On first item")))))))
2159 (defun org-next-item ()
2160 "Move to the beginning of the next item.
2161 Throw an error when not in a list. Also throw an error when at
2162 last item, unless `org-list-use-circular-motion' is non-nil."
2163 (interactive)
2164 (let ((item (org-in-item-p)))
2165 (if (not item)
2166 (error "Not in an item")
2167 (goto-char item)
2168 (let* ((struct (org-list-struct))
2169 (prevs (org-list-prevs-alist struct))
2170 (prevp (org-list-get-next-item item struct prevs)))
2171 (cond
2172 (prevp (goto-char prevp))
2173 (org-list-use-circular-motion
2174 (goto-char (org-list-get-first-item item struct prevs)))
2175 (t (error "On last item")))))))
2177 (defun org-move-item-down ()
2178 "Move the item at point down, i.e. swap with following item.
2179 Sub-items (items with larger indentation) are considered part of
2180 the item, so this really moves item trees."
2181 (interactive)
2182 (unless (org-at-item-p) (error "Not at an item"))
2183 (let* ((col (current-column))
2184 (item (point-at-bol))
2185 (struct (org-list-struct))
2186 (prevs (org-list-prevs-alist struct))
2187 (next-item (org-list-get-next-item (point-at-bol) struct prevs)))
2188 (unless (or next-item org-list-use-circular-motion)
2189 (user-error "Cannot move this item further down"))
2190 (if (not next-item)
2191 (setq struct (org-list-send-item item 'begin struct))
2192 (setq struct (org-list-swap-items item next-item struct))
2193 (goto-char
2194 (org-list-get-next-item item struct (org-list-prevs-alist struct))))
2195 (org-list-write-struct struct (org-list-parents-alist struct))
2196 (org-move-to-column col)))
2198 (defun org-move-item-up ()
2199 "Move the item at point up, i.e. swap with previous item.
2200 Sub-items (items with larger indentation) are considered part of
2201 the item, so this really moves item trees."
2202 (interactive)
2203 (unless (org-at-item-p) (error "Not at an item"))
2204 (let* ((col (current-column))
2205 (item (point-at-bol))
2206 (struct (org-list-struct))
2207 (prevs (org-list-prevs-alist struct))
2208 (prev-item (org-list-get-prev-item (point-at-bol) struct prevs)))
2209 (unless (or prev-item org-list-use-circular-motion)
2210 (user-error "Cannot move this item further up"))
2211 (if (not prev-item)
2212 (setq struct (org-list-send-item item 'end struct))
2213 (setq struct (org-list-swap-items prev-item item struct)))
2214 (org-list-write-struct struct (org-list-parents-alist struct))
2215 (org-move-to-column col)))
2217 (defun org-insert-item (&optional checkbox)
2218 "Insert a new item at the current level.
2219 If cursor is before first character after bullet of the item, the
2220 new item will be created before the current one.
2222 If CHECKBOX is non-nil, add a checkbox next to the bullet.
2224 Return t when things worked, nil when we are not in an item, or
2225 item is invisible."
2226 (let ((itemp (org-in-item-p))
2227 (pos (point)))
2228 ;; If cursor isn't is a list or if list is invisible, return nil.
2229 (unless (or (not itemp)
2230 (save-excursion
2231 (goto-char itemp)
2232 (outline-invisible-p)))
2233 (if (save-excursion
2234 (goto-char itemp)
2235 (org-at-item-timer-p))
2236 ;; Timer list: delegate to `org-timer-item'.
2237 (progn (org-timer-item) t)
2238 (let* ((struct (save-excursion (goto-char itemp)
2239 (org-list-struct)))
2240 (prevs (org-list-prevs-alist struct))
2241 ;; If we're in a description list, ask for the new term.
2242 (desc (when (eq (org-list-get-list-type itemp struct prevs)
2243 'descriptive)
2244 " :: ")))
2245 (setq struct (org-list-insert-item pos struct prevs checkbox desc))
2246 (org-list-write-struct struct (org-list-parents-alist struct))
2247 (when checkbox (org-update-checkbox-count-maybe))
2248 (looking-at org-list-full-item-re)
2249 (goto-char (if (and (match-beginning 4)
2250 (save-match-data
2251 (string-match "[.)]" (match-string 1))))
2252 (match-beginning 4)
2253 (match-end 0)))
2254 (if desc (backward-char 1))
2255 t)))))
2257 (defun org-list-repair ()
2258 "Fix indentation, bullets and checkboxes in the list at point."
2259 (interactive)
2260 (unless (org-at-item-p) (error "This is not a list"))
2261 (let* ((struct (org-list-struct))
2262 (parents (org-list-parents-alist struct)))
2263 (org-list-write-struct struct parents)))
2265 (defun org-cycle-list-bullet (&optional which)
2266 "Cycle through the different itemize/enumerate bullets.
2267 This cycle the entire list level through the sequence:
2269 `-' -> `+' -> `*' -> `1.' -> `1)'
2271 If WHICH is a valid string, use that as the new bullet. If WHICH
2272 is an integer, 0 means `-', 1 means `+' etc. If WHICH is
2273 `previous', cycle backwards."
2274 (interactive "P")
2275 (unless (org-at-item-p) (error "Not at an item"))
2276 (save-excursion
2277 (beginning-of-line)
2278 (let* ((struct (org-list-struct))
2279 (parents (org-list-parents-alist struct))
2280 (prevs (org-list-prevs-alist struct))
2281 (list-beg (org-list-get-first-item (point) struct prevs))
2282 (bullet (org-list-get-bullet list-beg struct))
2283 (alpha-p (org-list-use-alpha-bul-p list-beg struct prevs))
2284 (case-fold-search nil)
2285 (current (cond
2286 ((string-match "[a-z]\\." bullet) "a.")
2287 ((string-match "[a-z])" bullet) "a)")
2288 ((string-match "[A-Z]\\." bullet) "A.")
2289 ((string-match "[A-Z])" bullet) "A)")
2290 ((string-match "\\." bullet) "1.")
2291 ((string-match ")" bullet) "1)")
2292 (t (org-trim bullet))))
2293 ;; Compute list of possible bullets, depending on context.
2294 (bullet-list
2295 (append '("-" "+" )
2296 ;; *-bullets are not allowed at column 0.
2297 (unless (looking-at "\\S-") '("*"))
2298 ;; Description items cannot be numbered.
2299 (unless (or (eq org-plain-list-ordered-item-terminator ?\))
2300 (org-at-item-description-p))
2301 '("1."))
2302 (unless (or (eq org-plain-list-ordered-item-terminator ?.)
2303 (org-at-item-description-p))
2304 '("1)"))
2305 (unless (or (not alpha-p)
2306 (eq org-plain-list-ordered-item-terminator ?\))
2307 (org-at-item-description-p))
2308 '("a." "A."))
2309 (unless (or (not alpha-p)
2310 (eq org-plain-list-ordered-item-terminator ?.)
2311 (org-at-item-description-p))
2312 '("a)" "A)"))))
2313 (len (length bullet-list))
2314 (item-index (- len (length (member current bullet-list))))
2315 (get-value (lambda (index) (nth (mod index len) bullet-list)))
2316 (new (cond
2317 ((member which bullet-list) which)
2318 ((numberp which) (funcall get-value which))
2319 ((eq 'previous which) (funcall get-value (1- item-index)))
2320 (t (funcall get-value (1+ item-index))))))
2321 ;; Use a short variation of `org-list-write-struct' as there's
2322 ;; no need to go through all the steps.
2323 (let ((old-struct (copy-tree struct)))
2324 (org-list-set-bullet list-beg struct (org-list-bullet-string new))
2325 (org-list-struct-fix-bul struct prevs)
2326 (org-list-struct-fix-ind struct parents)
2327 (org-list-struct-apply-struct struct old-struct)))))
2329 (defun org-toggle-checkbox (&optional toggle-presence)
2330 "Toggle the checkbox in the current line.
2331 With prefix arg TOGGLE-PRESENCE, add or remove checkboxes. With
2332 double prefix, set checkbox to [-].
2334 When there is an active region, toggle status or presence of the
2335 first checkbox there, and make every item inside have the same
2336 status or presence, respectively.
2338 If the cursor is in a headline, apply this to all checkbox items
2339 in the text below the heading, taking as reference the first item
2340 in subtree, ignoring drawers."
2341 (interactive "P")
2342 (save-excursion
2343 (let* (singlep
2344 block-item
2345 lim-up
2346 lim-down
2347 (keyword-re (concat "^[ \t]*\\<\\(" org-scheduled-string
2348 "\\|" org-deadline-string
2349 "\\|" org-closed-string
2350 "\\|" org-clock-string "\\)"
2351 " *[[<]\\([^]>]+\\)[]>]"))
2352 (orderedp (org-entry-get nil "ORDERED"))
2353 (bounds
2354 ;; In a region, start at first item in region.
2355 (cond
2356 ((org-region-active-p)
2357 (let ((limit (region-end)))
2358 (goto-char (region-beginning))
2359 (if (org-list-search-forward (org-item-beginning-re) limit t)
2360 (setq lim-up (point-at-bol))
2361 (error "No item in region"))
2362 (setq lim-down (copy-marker limit))))
2363 ((org-at-heading-p)
2364 ;; On an heading, start at first item after drawers and
2365 ;; time-stamps (scheduled, etc.).
2366 (let ((limit (save-excursion (outline-next-heading) (point))))
2367 (forward-line 1)
2368 (while (or (looking-at org-drawer-regexp)
2369 (looking-at keyword-re))
2370 (if (looking-at keyword-re)
2371 (forward-line 1)
2372 (re-search-forward "^[ \t]*:END:" limit nil)))
2373 (if (org-list-search-forward (org-item-beginning-re) limit t)
2374 (setq lim-up (point-at-bol))
2375 (error "No item in subtree"))
2376 (setq lim-down (copy-marker limit))))
2377 ;; Just one item: set SINGLEP flag.
2378 ((org-at-item-p)
2379 (setq singlep t)
2380 (setq lim-up (point-at-bol)
2381 lim-down (copy-marker (point-at-eol))))
2382 (t (error "Not at an item or heading, and no active region"))))
2383 ;; Determine the checkbox going to be applied to all items
2384 ;; within bounds.
2385 (ref-checkbox
2386 (progn
2387 (goto-char lim-up)
2388 (let ((cbox (and (org-at-item-checkbox-p) (match-string 1))))
2389 (cond
2390 ((equal toggle-presence '(16)) "[-]")
2391 ((equal toggle-presence '(4))
2392 (unless cbox "[ ]"))
2393 ((equal "[X]" cbox) "[ ]")
2394 (t "[X]"))))))
2395 ;; When an item is found within bounds, grab the full list at
2396 ;; point structure, then: (1) set check-box of all its items
2397 ;; within bounds to REF-CHECKBOX, (2) fix check-boxes of the
2398 ;; whole list, (3) move point after the list.
2399 (goto-char lim-up)
2400 (while (and (< (point) lim-down)
2401 (org-list-search-forward (org-item-beginning-re)
2402 lim-down 'move))
2403 (let* ((struct (org-list-struct))
2404 (struct-copy (copy-tree struct))
2405 (parents (org-list-parents-alist struct))
2406 (prevs (org-list-prevs-alist struct))
2407 (bottom (copy-marker (org-list-get-bottom-point struct)))
2408 (items-to-toggle (org-remove-if
2409 (lambda (e) (or (< e lim-up) (> e lim-down)))
2410 (mapcar 'car struct))))
2411 (mapc (lambda (e) (org-list-set-checkbox
2412 e struct
2413 ;; If there is no box at item, leave as-is
2414 ;; unless function was called with C-u prefix.
2415 (let ((cur-box (org-list-get-checkbox e struct)))
2416 (if (or cur-box (equal toggle-presence '(4)))
2417 ref-checkbox
2418 cur-box))))
2419 items-to-toggle)
2420 (setq block-item (org-list-struct-fix-box
2421 struct parents prevs orderedp))
2422 ;; Report some problems due to ORDERED status of subtree.
2423 ;; If only one box was being checked, throw an error, else,
2424 ;; only signal problems.
2425 (cond
2426 ((and singlep block-item (> lim-up block-item))
2427 (error
2428 "Checkbox blocked because of unchecked box at line %d"
2429 (org-current-line block-item)))
2430 (block-item
2431 (message
2432 "Checkboxes were removed due to unchecked box at line %d"
2433 (org-current-line block-item))))
2434 (goto-char bottom)
2435 (move-marker bottom nil)
2436 (org-list-struct-apply-struct struct struct-copy)))
2437 (move-marker lim-down nil)))
2438 (org-update-checkbox-count-maybe))
2440 (defun org-reset-checkbox-state-subtree ()
2441 "Reset all checkboxes in an entry subtree."
2442 (interactive "*")
2443 (if (org-before-first-heading-p)
2444 (error "Not inside a tree")
2445 (save-restriction
2446 (save-excursion
2447 (org-narrow-to-subtree)
2448 (org-show-subtree)
2449 (goto-char (point-min))
2450 (let ((end (point-max)))
2451 (while (< (point) end)
2452 (when (org-at-item-checkbox-p)
2453 (replace-match "[ ]" t t nil 1))
2454 (beginning-of-line 2)))
2455 (org-update-checkbox-count-maybe 'all)))))
2457 (defun org-update-checkbox-count (&optional all)
2458 "Update the checkbox statistics in the current section.
2459 This will find all statistic cookies like [57%] and [6/12] and
2460 update them with the current numbers.
2462 With optional prefix argument ALL, do this for the whole buffer."
2463 (interactive "P")
2464 (save-excursion
2465 (let ((cookie-re "\\(\\(\\[[0-9]*%\\]\\)\\|\\(\\[[0-9]*/[0-9]*\\]\\)\\)")
2466 (box-re "^[ \t]*\\([-+*]\\|\\([0-9]+\\|[A-Za-z]\\)[.)]\\)[ \t]+\\(?:\\[@\\(?:start:\\)?\\([0-9]+\\|[A-Za-z]\\)\\][ \t]*\\)?\\(\\[[- X]\\]\\)")
2467 (recursivep
2468 (or (not org-checkbox-hierarchical-statistics)
2469 (string-match "\\<recursive\\>"
2470 (or (org-entry-get nil "COOKIE_DATA") ""))))
2471 (bounds (if all
2472 (cons (point-min) (point-max))
2473 (cons (or (ignore-errors (org-back-to-heading t) (point))
2474 (point-min))
2475 (save-excursion (outline-next-heading) (point)))))
2476 (count-boxes
2477 (function
2478 ;; Return number of checked boxes and boxes of all types
2479 ;; in all structures in STRUCTS. If RECURSIVEP is
2480 ;; non-nil, also count boxes in sub-lists. If ITEM is
2481 ;; nil, count across the whole structure, else count only
2482 ;; across subtree whose ancestor is ITEM.
2483 (lambda (item structs recursivep)
2484 (let ((c-on 0) (c-all 0))
2485 (mapc
2486 (lambda (s)
2487 (let* ((pre (org-list-prevs-alist s))
2488 (par (org-list-parents-alist s))
2489 (items
2490 (cond
2491 ((and recursivep item) (org-list-get-subtree item s))
2492 (recursivep (mapcar 'car s))
2493 (item (org-list-get-children item s par))
2494 (t (org-list-get-all-items
2495 (org-list-get-top-point s) s pre))))
2496 (cookies (delq nil (mapcar
2497 (lambda (e)
2498 (org-list-get-checkbox e s))
2499 items))))
2500 (setq c-all (+ (length cookies) c-all)
2501 c-on (+ (org-count "[X]" cookies) c-on))))
2502 structs)
2503 (cons c-on c-all)))))
2504 (backup-end 1)
2505 cookies-list structs-bak box-num)
2506 (goto-char (car bounds))
2507 ;; 1. Build an alist for each cookie found within BOUNDS. The
2508 ;; key will be position at beginning of cookie and values
2509 ;; ending position, format of cookie, and a cell whose car is
2510 ;; number of checked boxes to report, and cdr total number of
2511 ;; boxes.
2512 (while (re-search-forward cookie-re (cdr bounds) t)
2513 (catch 'skip
2514 (save-excursion
2515 (push
2516 (list
2517 (match-beginning 1) ; cookie start
2518 (match-end 1) ; cookie end
2519 (match-string 2) ; percent?
2520 (cond ; boxes count
2521 ;; Cookie is at an heading, but specifically for todo,
2522 ;; not for checkboxes: skip it.
2523 ((and (org-at-heading-p)
2524 (string-match "\\<todo\\>"
2525 (downcase
2526 (or (org-entry-get nil "COOKIE_DATA") ""))))
2527 (throw 'skip nil))
2528 ;; Cookie is at an heading, but all lists before next
2529 ;; heading already have been read. Use data collected
2530 ;; in STRUCTS-BAK. This should only happen when
2531 ;; heading has more than one cookie on it.
2532 ((and (org-at-heading-p)
2533 (<= (save-excursion (outline-next-heading) (point))
2534 backup-end))
2535 (funcall count-boxes nil structs-bak recursivep))
2536 ;; Cookie is at a fresh heading. Grab structure of
2537 ;; every list containing a checkbox between point and
2538 ;; next headline, and save them in STRUCTS-BAK.
2539 ((org-at-heading-p)
2540 (setq backup-end (save-excursion
2541 (outline-next-heading) (point))
2542 structs-bak nil)
2543 (while (org-list-search-forward box-re backup-end 'move)
2544 (let* ((struct (org-list-struct))
2545 (bottom (org-list-get-bottom-point struct)))
2546 (push struct structs-bak)
2547 (goto-char bottom)))
2548 (funcall count-boxes nil structs-bak recursivep))
2549 ;; Cookie is at an item, and we already have list
2550 ;; structure stored in STRUCTS-BAK.
2551 ((and (org-at-item-p)
2552 (< (point-at-bol) backup-end)
2553 ;; Only lists in no special context are stored.
2554 (not (nth 2 (org-list-context))))
2555 (funcall count-boxes (point-at-bol) structs-bak recursivep))
2556 ;; Cookie is at an item, but we need to compute list
2557 ;; structure.
2558 ((org-at-item-p)
2559 (let ((struct (org-list-struct)))
2560 (setq backup-end (org-list-get-bottom-point struct)
2561 structs-bak (list struct)))
2562 (funcall count-boxes (point-at-bol) structs-bak recursivep))
2563 ;; Else, cookie found is at a wrong place. Skip it.
2564 (t (throw 'skip nil))))
2565 cookies-list))))
2566 ;; 2. Apply alist to buffer, in reverse order so positions stay
2567 ;; unchanged after cookie modifications.
2568 (mapc (lambda (cookie)
2569 (let* ((beg (car cookie))
2570 (end (nth 1 cookie))
2571 (percentp (nth 2 cookie))
2572 (checked (car (nth 3 cookie)))
2573 (total (cdr (nth 3 cookie)))
2574 (new (if percentp
2575 (format "[%d%%]" (/ (* 100 checked)
2576 (max 1 total)))
2577 (format "[%d/%d]" checked total))))
2578 (goto-char beg)
2579 (insert new)
2580 (delete-region (point) (+ (point) (- end beg)))
2581 (when org-auto-align-tags (org-fix-tags-on-the-fly))))
2582 cookies-list))))
2584 (defun org-get-checkbox-statistics-face ()
2585 "Select the face for checkbox statistics.
2586 The face will be `org-done' when all relevant boxes are checked.
2587 Otherwise it will be `org-todo'."
2588 (if (match-end 1)
2589 (if (equal (match-string 1) "100%")
2590 'org-checkbox-statistics-done
2591 'org-checkbox-statistics-todo)
2592 (if (and (> (match-end 2) (match-beginning 2))
2593 (equal (match-string 2) (match-string 3)))
2594 'org-checkbox-statistics-done
2595 'org-checkbox-statistics-todo)))
2597 (defun org-update-checkbox-count-maybe (&optional all)
2598 "Update checkbox statistics unless turned off by user.
2599 With an optional argument ALL, update them in the whole buffer."
2600 (when (cdr (assq 'checkbox org-list-automatic-rules))
2601 (org-update-checkbox-count all))
2602 (run-hooks 'org-checkbox-statistics-hook))
2604 (defvar org-last-indent-begin-marker (make-marker))
2605 (defvar org-last-indent-end-marker (make-marker))
2606 (defun org-list-indent-item-generic (arg no-subtree struct)
2607 "Indent a local list item including its children.
2608 When number ARG is a negative, item will be outdented, otherwise
2609 it will be indented.
2611 If a region is active, all items inside will be moved.
2613 If NO-SUBTREE is non-nil, only indent the item itself, not its
2614 children.
2616 STRUCT is the list structure.
2618 Return t if successful."
2619 (save-excursion
2620 (let* ((regionp (org-region-active-p))
2621 (rbeg (and regionp (region-beginning)))
2622 (rend (and regionp (region-end)))
2623 (top (org-list-get-top-point struct))
2624 (parents (org-list-parents-alist struct))
2625 (prevs (org-list-prevs-alist struct))
2626 ;; Are we going to move the whole list?
2627 (specialp
2628 (and (not regionp)
2629 (= top (point-at-bol))
2630 (cdr (assq 'indent org-list-automatic-rules))
2631 (if no-subtree
2632 (error
2633 "First item of list cannot move without its subtree")
2634 t))))
2635 ;; Determine begin and end points of zone to indent. If moving
2636 ;; more than one item, save them for subsequent moves.
2637 (unless (and (memq last-command '(org-shiftmetaright org-shiftmetaleft))
2638 (memq this-command '(org-shiftmetaright org-shiftmetaleft)))
2639 (if regionp
2640 (progn
2641 (set-marker org-last-indent-begin-marker rbeg)
2642 (set-marker org-last-indent-end-marker rend))
2643 (set-marker org-last-indent-begin-marker (point-at-bol))
2644 (set-marker org-last-indent-end-marker
2645 (cond
2646 (specialp (org-list-get-bottom-point struct))
2647 (no-subtree (1+ (point-at-bol)))
2648 (t (org-list-get-item-end (point-at-bol) struct))))))
2649 (let* ((beg (marker-position org-last-indent-begin-marker))
2650 (end (marker-position org-last-indent-end-marker)))
2651 (cond
2652 ;; Special case: moving top-item with indent rule.
2653 (specialp
2654 (let* ((level-skip (org-level-increment))
2655 (offset (if (< arg 0) (- level-skip) level-skip))
2656 (top-ind (org-list-get-ind beg struct))
2657 (old-struct (copy-tree struct)))
2658 (if (< (+ top-ind offset) 0)
2659 (error "Cannot outdent beyond margin")
2660 ;; Change bullet if necessary.
2661 (when (and (= (+ top-ind offset) 0)
2662 (string-match "*"
2663 (org-list-get-bullet beg struct)))
2664 (org-list-set-bullet beg struct
2665 (org-list-bullet-string "-")))
2666 ;; Shift every item by OFFSET and fix bullets. Then
2667 ;; apply changes to buffer.
2668 (mapc (lambda (e)
2669 (let ((ind (org-list-get-ind (car e) struct)))
2670 (org-list-set-ind (car e) struct (+ ind offset))))
2671 struct)
2672 (org-list-struct-fix-bul struct prevs)
2673 (org-list-struct-apply-struct struct old-struct))))
2674 ;; Forbidden move:
2675 ((and (< arg 0)
2676 ;; If only one item is moved, it mustn't have a child.
2677 (or (and no-subtree
2678 (not regionp)
2679 (org-list-has-child-p beg struct))
2680 ;; If a subtree or region is moved, the last item
2681 ;; of the subtree mustn't have a child.
2682 (let ((last-item (caar
2683 (reverse
2684 (org-remove-if
2685 (lambda (e) (>= (car e) end))
2686 struct)))))
2687 (org-list-has-child-p last-item struct))))
2688 (error "Cannot outdent an item without its children"))
2689 ;; Normal shifting
2691 (let* ((new-parents
2692 (if (< arg 0)
2693 (org-list-struct-outdent beg end struct parents)
2694 (org-list-struct-indent beg end struct parents prevs))))
2695 (org-list-write-struct struct new-parents))
2696 (org-update-checkbox-count-maybe))))))
2699 (defun org-outdent-item ()
2700 "Outdent a local list item, but not its children.
2701 If a region is active, all items inside will be moved."
2702 (interactive)
2703 (let ((regionp (org-region-active-p)))
2704 (cond
2705 ((or (org-at-item-p)
2706 (and regionp
2707 (save-excursion (goto-char (region-beginning))
2708 (org-at-item-p))))
2709 (let ((struct (if (not regionp) (org-list-struct)
2710 (save-excursion (goto-char (region-beginning))
2711 (org-list-struct)))))
2712 (org-list-indent-item-generic -1 t struct)))
2713 (regionp (error "Region not starting at an item"))
2714 (t (error "Not at an item")))))
2716 (defun org-indent-item ()
2717 "Indent a local list item, but not its children.
2718 If a region is active, all items inside will be moved."
2719 (interactive)
2720 (let ((regionp (org-region-active-p)))
2721 (cond
2722 ((or (org-at-item-p)
2723 (and regionp
2724 (save-excursion (goto-char (region-beginning))
2725 (org-at-item-p))))
2726 (let ((struct (if (not regionp) (org-list-struct)
2727 (save-excursion (goto-char (region-beginning))
2728 (org-list-struct)))))
2729 (org-list-indent-item-generic 1 t struct)))
2730 (regionp (error "Region not starting at an item"))
2731 (t (error "Not at an item")))))
2733 (defun org-outdent-item-tree ()
2734 "Outdent a local list item including its children.
2735 If a region is active, all items inside will be moved."
2736 (interactive)
2737 (let ((regionp (org-region-active-p)))
2738 (cond
2739 ((or (org-at-item-p)
2740 (and regionp
2741 (save-excursion (goto-char (region-beginning))
2742 (org-at-item-p))))
2743 (let ((struct (if (not regionp) (org-list-struct)
2744 (save-excursion (goto-char (region-beginning))
2745 (org-list-struct)))))
2746 (org-list-indent-item-generic -1 nil struct)))
2747 (regionp (error "Region not starting at an item"))
2748 (t (error "Not at an item")))))
2750 (defun org-indent-item-tree ()
2751 "Indent a local list item including its children.
2752 If a region is active, all items inside will be moved."
2753 (interactive)
2754 (let ((regionp (org-region-active-p)))
2755 (cond
2756 ((or (org-at-item-p)
2757 (and regionp
2758 (save-excursion (goto-char (region-beginning))
2759 (org-at-item-p))))
2760 (let ((struct (if (not regionp) (org-list-struct)
2761 (save-excursion (goto-char (region-beginning))
2762 (org-list-struct)))))
2763 (org-list-indent-item-generic 1 nil struct)))
2764 (regionp (error "Region not starting at an item"))
2765 (t (error "Not at an item")))))
2767 (defvar org-tab-ind-state)
2768 (defun org-cycle-item-indentation ()
2769 "Cycle levels of indentation of an empty item.
2770 The first run indents the item, if applicable. Subsequent runs
2771 outdent it at meaningful levels in the list. When done, item is
2772 put back at its original position with its original bullet.
2774 Return t at each successful move."
2775 (when (org-at-item-p)
2776 (let* ((org-adapt-indentation nil)
2777 (struct (org-list-struct))
2778 (ind (org-list-get-ind (point-at-bol) struct))
2779 (bullet (org-trim (buffer-substring (point-at-bol) (point-at-eol)))))
2780 ;; Accept empty items or if cycle has already started.
2781 (when (or (eq last-command 'org-cycle-item-indentation)
2782 (and (save-excursion
2783 (beginning-of-line)
2784 (looking-at org-list-full-item-re))
2785 (>= (match-end 0) (save-excursion
2786 (goto-char (org-list-get-item-end
2787 (point-at-bol) struct))
2788 (skip-chars-backward " \r\t\n")
2789 (point)))))
2790 (setq this-command 'org-cycle-item-indentation)
2791 ;; When in the middle of the cycle, try to outdent first. If
2792 ;; it fails, and point is still at initial position, indent.
2793 ;; Else, re-create it at its original position.
2794 (if (eq last-command 'org-cycle-item-indentation)
2795 (cond
2796 ((ignore-errors (org-list-indent-item-generic -1 t struct)))
2797 ((and (= ind (car org-tab-ind-state))
2798 (ignore-errors (org-list-indent-item-generic 1 t struct))))
2799 (t (delete-region (point-at-bol) (point-at-eol))
2800 (org-indent-to-column (car org-tab-ind-state))
2801 (insert (cdr org-tab-ind-state) " ")
2802 ;; Break cycle
2803 (setq this-command 'identity)))
2804 ;; If a cycle is starting, remember indentation and bullet,
2805 ;; then try to indent. If it fails, try to outdent.
2806 (setq org-tab-ind-state (cons ind bullet))
2807 (cond
2808 ((ignore-errors (org-list-indent-item-generic 1 t struct)))
2809 ((ignore-errors (org-list-indent-item-generic -1 t struct)))
2810 (t (user-error "Cannot move item"))))
2811 t))))
2813 (defun org-sort-list (&optional with-case sorting-type getkey-func compare-func)
2814 "Sort list items.
2815 The cursor may be at any item of the list that should be sorted.
2816 Sublists are not sorted. Checkboxes, if any, are ignored.
2818 Sorting can be alphabetically, numerically, by date/time as given
2819 by a time stamp, by a property or by priority.
2821 Comparing entries ignores case by default. However, with an
2822 optional argument WITH-CASE, the sorting considers case as well.
2824 The command prompts for the sorting type unless it has been given
2825 to the function through the SORTING-TYPE argument, which needs to
2826 be a character, \(?n ?N ?a ?A ?t ?T ?f ?F ?x ?X). Here is the
2827 detailed meaning of each character:
2829 n Numerically, by converting the beginning of the item to a number.
2830 a Alphabetically. Only the first line of item is checked.
2831 t By date/time, either the first active time stamp in the entry, if
2832 any, or by the first inactive one. In a timer list, sort the timers.
2833 x By \"checked\" status of a check list.
2835 Capital letters will reverse the sort order.
2837 If the SORTING-TYPE is ?f or ?F, then GETKEY-FUNC specifies
2838 a function to be called with point at the beginning of the
2839 record. It must return either a string or a number that should
2840 serve as the sorting key for that record. It will then use
2841 COMPARE-FUNC to compare entries.
2843 Sorting is done against the visible part of the headlines, it
2844 ignores hidden links."
2845 (interactive "P")
2846 (let* ((case-func (if with-case 'identity 'downcase))
2847 (struct (org-list-struct))
2848 (prevs (org-list-prevs-alist struct))
2849 (start (org-list-get-list-begin (point-at-bol) struct prevs))
2850 (end (org-list-get-list-end (point-at-bol) struct prevs))
2851 (sorting-type
2852 (or sorting-type
2853 (progn
2854 (message
2855 "Sort plain list: [a]lpha [n]umeric [t]ime [f]unc [x]checked A/N/T/F/X means reversed:")
2856 (read-char-exclusive))))
2857 (getkey-func
2858 (or getkey-func
2859 (and (= (downcase sorting-type) ?f)
2860 (intern (org-icompleting-read "Sort using function: "
2861 obarray 'fboundp t nil nil))))))
2862 (message "Sorting items...")
2863 (save-restriction
2864 (narrow-to-region start end)
2865 (goto-char (point-min))
2866 (let* ((dcst (downcase sorting-type))
2867 (case-fold-search nil)
2868 (now (current-time))
2869 (sort-func (cond
2870 ((= dcst ?a) 'string<)
2871 ((= dcst ?f) compare-func)
2872 ((= dcst ?t) '<)
2873 ((= dcst ?x) 'string<)))
2874 (next-record (lambda ()
2875 (skip-chars-forward " \r\t\n")
2876 (or (eobp) (beginning-of-line))))
2877 (end-record (lambda ()
2878 (goto-char (org-list-get-item-end-before-blank
2879 (point) struct))))
2880 (value-to-sort
2881 (lambda ()
2882 (when (looking-at "[ \t]*[-+*0-9.)]+\\([ \t]+\\[[- X]\\]\\)?[ \t]+")
2883 (cond
2884 ((= dcst ?n)
2885 (string-to-number
2886 (org-sort-remove-invisible
2887 (buffer-substring (match-end 0) (point-at-eol)))))
2888 ((= dcst ?a)
2889 (funcall case-func
2890 (org-sort-remove-invisible
2891 (buffer-substring
2892 (match-end 0) (point-at-eol)))))
2893 ((= dcst ?t)
2894 (cond
2895 ;; If it is a timer list, convert timer to seconds
2896 ((org-at-item-timer-p)
2897 (org-timer-hms-to-secs (match-string 1)))
2898 ((or (save-excursion
2899 (re-search-forward org-ts-regexp (point-at-eol) t))
2900 (save-excursion (re-search-forward org-ts-regexp-both
2901 (point-at-eol) t)))
2902 (org-time-string-to-seconds (match-string 0)))
2903 (t (org-float-time now))))
2904 ((= dcst ?x) (or (and (stringp (match-string 1))
2905 (match-string 1))
2906 ""))
2907 ((= dcst ?f)
2908 (if getkey-func
2909 (let ((value (funcall getkey-func)))
2910 (if (stringp value)
2911 (funcall case-func value)
2912 value))
2913 (error "Invalid key function `%s'" getkey-func)))
2914 (t (error "Invalid sorting type `%c'" sorting-type)))))))
2915 (sort-subr (/= dcst sorting-type)
2916 next-record
2917 end-record
2918 value-to-sort
2920 sort-func)
2921 ;; Read and fix list again, as `sort-subr' probably destroyed
2922 ;; its structure.
2923 (org-list-repair)
2924 (run-hooks 'org-after-sorting-entries-or-items-hook)
2925 (message "Sorting items...done")))))
2929 ;;; Send and receive lists
2931 (defun org-list-parse-list (&optional delete)
2932 "Parse the list at point and maybe DELETE it.
2934 Return a list whose car is a symbol of list type, among
2935 `ordered', `unordered' and `descriptive'. Then, each item is
2936 a list whose car is counter, and cdr are strings and other
2937 sub-lists. Inside strings, check-boxes are replaced by
2938 \"[CBON]\", \"[CBOFF]\" and \"[CBTRANS]\".
2940 For example, the following list:
2942 1. first item
2943 + sub-item one
2944 + [X] sub-item two
2945 more text in first item
2946 2. [@3] last item
2948 will be parsed as:
2950 \(ordered
2951 \(nil \"first item\"
2952 \(unordered
2953 \(nil \"sub-item one\"\)
2954 \(nil \"[CBON] sub-item two\"\)\)
2955 \"more text in first item\"\)
2956 \(3 \"last item\"\)\)
2958 Point is left at list end."
2959 (let* ((struct (org-list-struct))
2960 (prevs (org-list-prevs-alist struct))
2961 (parents (org-list-parents-alist struct))
2962 (top (org-list-get-top-point struct))
2963 (bottom (org-list-get-bottom-point struct))
2965 parse-item ; for byte-compiler
2966 (get-text
2967 (function
2968 ;; Return text between BEG and END, trimmed, with
2969 ;; checkboxes replaced.
2970 (lambda (beg end)
2971 (let ((text (org-trim (buffer-substring beg end))))
2972 (if (string-match "\\`\\[\\([-X ]\\)\\]" text)
2973 (replace-match
2974 (let ((box (match-string 1 text)))
2975 (cond
2976 ((equal box " ") "CBOFF")
2977 ((equal box "-") "CBTRANS")
2978 (t "CBON")))
2979 t nil text 1)
2980 text)))))
2981 (parse-sublist
2982 (function
2983 ;; Return a list whose car is list type and cdr a list of
2984 ;; items' body.
2985 (lambda (e)
2986 (cons (org-list-get-list-type (car e) struct prevs)
2987 (mapcar parse-item e)))))
2988 (parse-item
2989 (function
2990 ;; Return a list containing counter of item, if any, text
2991 ;; and any sublist inside it.
2992 (lambda (e)
2993 (let ((start (save-excursion
2994 (goto-char e)
2995 (looking-at "[ \t]*\\S-+\\([ \t]+\\[@\\(start:\\)?\\([0-9]+\\|[a-zA-Z]\\)\\]\\)?[ \t]*")
2996 (match-end 0)))
2997 ;; Get counter number. For alphabetic counter, get
2998 ;; its position in the alphabet.
2999 (counter (let ((c (org-list-get-counter e struct)))
3000 (cond
3001 ((not c) nil)
3002 ((string-match "[A-Za-z]" c)
3003 (- (string-to-char (upcase (match-string 0 c)))
3004 64))
3005 ((string-match "[0-9]+" c)
3006 (string-to-number (match-string 0 c))))))
3007 (childp (org-list-has-child-p e struct))
3008 (end (org-list-get-item-end e struct)))
3009 ;; If item has a child, store text between bullet and
3010 ;; next child, then recursively parse all sublists. At
3011 ;; the end of each sublist, check for the presence of
3012 ;; text belonging to the original item.
3013 (if childp
3014 (let* ((children (org-list-get-children e struct parents))
3015 (body (list (funcall get-text start childp))))
3016 (while children
3017 (let* ((first (car children))
3018 (sub (org-list-get-all-items first struct prevs))
3019 (last-c (car (last sub)))
3020 (last-end (org-list-get-item-end last-c struct)))
3021 (push (funcall parse-sublist sub) body)
3022 ;; Remove children from the list just parsed.
3023 (setq children (cdr (member last-c children)))
3024 ;; There is a chunk of text belonging to the
3025 ;; item if last child doesn't end where next
3026 ;; child starts or where item ends.
3027 (unless (= (or (car children) end) last-end)
3028 (push (funcall get-text
3029 last-end (or (car children) end))
3030 body))))
3031 (cons counter (nreverse body)))
3032 (list counter (funcall get-text start end))))))))
3033 ;; Store output, take care of cursor position and deletion of
3034 ;; list, then return output.
3035 (setq out (funcall parse-sublist (org-list-get-all-items top struct prevs)))
3036 (goto-char top)
3037 (when delete
3038 (delete-region top bottom)
3039 (when (and (not (looking-at "[ \t]*$")) (looking-at org-list-end-re))
3040 (replace-match "")))
3041 out))
3043 (defun org-list-make-subtree ()
3044 "Convert the plain list at point into a subtree."
3045 (interactive)
3046 (if (not (ignore-errors (goto-char (org-in-item-p))))
3047 (error "Not in a list")
3048 (let ((list (save-excursion (org-list-parse-list t))))
3049 (insert (org-list-to-subtree list)))))
3051 (defun org-list-insert-radio-list ()
3052 "Insert a radio list template appropriate for this major mode."
3053 (interactive)
3054 (let* ((e (assq major-mode org-list-radio-list-templates))
3055 (txt (nth 1 e))
3056 name pos)
3057 (unless e (error "No radio list setup defined for %s" major-mode))
3058 (setq name (read-string "List name: "))
3059 (while (string-match "%n" txt)
3060 (setq txt (replace-match name t t txt)))
3061 (or (bolp) (insert "\n"))
3062 (setq pos (point))
3063 (insert txt)
3064 (goto-char pos)))
3066 (defun org-list-send-list (&optional maybe)
3067 "Send a transformed version of this list to the receiver position.
3068 With argument MAYBE, fail quietly if no transformation is defined
3069 for this list."
3070 (interactive)
3071 (catch 'exit
3072 (unless (org-at-item-p) (error "Not at a list item"))
3073 (save-excursion
3074 (re-search-backward "#\\+ORGLST" nil t)
3075 (unless (looking-at "\\(?:[ \t]\\)?#\\+ORGLST:[ \t]+SEND[ \t]+\\(\\S-+\\)[ \t]+\\(\\S-+\\)")
3076 (if maybe (throw 'exit nil)
3077 (error "Don't know how to transform this list"))))
3078 (let* ((name (match-string 1))
3079 (transform (intern (match-string 2)))
3080 (bottom-point
3081 (save-excursion
3082 (re-search-forward
3083 "\\(\\\\end{comment}\\|@end ignore\\|-->\\)" nil t)
3084 (match-beginning 0)))
3085 (top-point
3086 (progn
3087 (re-search-backward "#\\+ORGLST" nil t)
3088 (re-search-forward (org-item-beginning-re) bottom-point t)
3089 (match-beginning 0)))
3090 (plain-list (buffer-substring-no-properties top-point bottom-point))
3091 beg txt)
3092 (unless (fboundp transform)
3093 (error "No such transformation function %s" transform))
3094 (let ((txt (funcall transform plain-list)))
3095 ;; Find the insertion place
3096 (save-excursion
3097 (goto-char (point-min))
3098 (unless (re-search-forward
3099 (concat "BEGIN RECEIVE ORGLST +"
3100 name
3101 "\\([ \t]\\|$\\)") nil t)
3102 (error "Don't know where to insert translated list"))
3103 (goto-char (match-beginning 0))
3104 (beginning-of-line 2)
3105 (setq beg (point))
3106 (unless (re-search-forward (concat "END RECEIVE ORGLST +" name) nil t)
3107 (error "Cannot find end of insertion region"))
3108 (delete-region beg (point-at-bol))
3109 (goto-char beg)
3110 (insert txt "\n")))
3111 (message "List converted and installed at receiver location"))))
3113 (defsubst org-list-item-trim-br (item)
3114 "Trim line breaks in a list ITEM."
3115 (setq item (replace-regexp-in-string "\n +" " " item)))
3117 (defun org-list-to-generic (list params)
3118 "Convert a LIST parsed through `org-list-parse-list' to other formats.
3119 Valid parameters PARAMS are:
3121 :ustart String to start an unordered list
3122 :uend String to end an unordered list
3124 :ostart String to start an ordered list
3125 :oend String to end an ordered list
3127 :dstart String to start a descriptive list
3128 :dend String to end a descriptive list
3129 :dtstart String to start a descriptive term
3130 :dtend String to end a descriptive term
3131 :ddstart String to start a description
3132 :ddend String to end a description
3134 :splice When set to t, return only list body lines, don't wrap
3135 them into :[u/o]start and :[u/o]end. Default is nil.
3137 :istart String to start a list item.
3138 :icount String to start an item with a counter.
3139 :iend String to end a list item
3140 :isep String to separate items
3141 :lsep String to separate sublists
3142 :csep String to separate text from a sub-list
3144 :cboff String to insert for an unchecked check-box
3145 :cbon String to insert for a checked check-box
3146 :cbtrans String to insert for a check-box in transitional state
3148 :nobr Non-nil means remove line breaks in lists items.
3150 Alternatively, each parameter can also be a form returning
3151 a string. These sexp can use keywords `counter' and `depth',
3152 representing respectively counter associated to the current
3153 item, and depth of the current sub-list, starting at 0.
3154 Obviously, `counter' is only available for parameters applying to
3155 items."
3156 (interactive)
3157 (let* ((p params)
3158 (splicep (plist-get p :splice))
3159 (ostart (plist-get p :ostart))
3160 (oend (plist-get p :oend))
3161 (ustart (plist-get p :ustart))
3162 (uend (plist-get p :uend))
3163 (dstart (plist-get p :dstart))
3164 (dend (plist-get p :dend))
3165 (dtstart (plist-get p :dtstart))
3166 (dtend (plist-get p :dtend))
3167 (ddstart (plist-get p :ddstart))
3168 (ddend (plist-get p :ddend))
3169 (istart (plist-get p :istart))
3170 (icount (plist-get p :icount))
3171 (iend (plist-get p :iend))
3172 (isep (plist-get p :isep))
3173 (lsep (plist-get p :lsep))
3174 (csep (plist-get p :csep))
3175 (cbon (plist-get p :cbon))
3176 (cboff (plist-get p :cboff))
3177 (cbtrans (plist-get p :cbtrans))
3178 (nobr (plist-get p :nobr))
3179 export-sublist ; for byte-compiler
3180 (export-item
3181 (function
3182 ;; Export an item ITEM of type TYPE, at DEPTH. First
3183 ;; string in item is treated in a special way as it can
3184 ;; bring extra information that needs to be processed.
3185 (lambda (item type depth)
3186 (let* ((counter (pop item))
3187 (fmt (concat
3188 (cond
3189 ((eq type 'descriptive)
3190 ;; Stick DTSTART to ISTART by
3191 ;; left-trimming the latter.
3192 (concat (let ((s (eval istart)))
3193 (or (and (string-match "[ \t\n\r]+\\'" s)
3194 (replace-match "" t t s))
3195 istart))
3196 "%s" (eval ddend)))
3197 ((and counter (eq type 'ordered))
3198 (concat (eval icount) "%s"))
3199 (t (concat (eval istart) "%s")))
3200 (eval iend)))
3201 (first (car item)))
3202 ;; Replace checkbox if any is found.
3203 (cond
3204 ((string-match "\\[CBON\\]" first)
3205 (setq first (replace-match cbon t t first)))
3206 ((string-match "\\[CBOFF\\]" first)
3207 (setq first (replace-match cboff t t first)))
3208 ((string-match "\\[CBTRANS\\]" first)
3209 (setq first (replace-match cbtrans t t first))))
3210 ;; Replace line breaks if required
3211 (when nobr (setq first (org-list-item-trim-br first)))
3212 ;; Insert descriptive term if TYPE is `descriptive'.
3213 (when (eq type 'descriptive)
3214 (let* ((complete (string-match "^\\(.*\\)[ \t]+::" first))
3215 (term (if complete
3216 (save-match-data
3217 (org-trim (match-string 1 first)))
3218 "???"))
3219 (desc (if complete
3220 (org-trim (substring first (match-end 0)))
3221 first)))
3222 (setq first (concat (eval dtstart) term (eval dtend)
3223 (eval ddstart) desc))))
3224 (setcar item first)
3225 (format fmt
3226 (mapconcat (lambda (e)
3227 (if (stringp e) e
3228 (funcall export-sublist e (1+ depth))))
3229 item (or (eval csep) "")))))))
3230 (export-sublist
3231 (function
3232 ;; Export sublist SUB at DEPTH.
3233 (lambda (sub depth)
3234 (let* ((type (car sub))
3235 (items (cdr sub))
3236 (fmt (concat (cond
3237 (splicep "%s")
3238 ((eq type 'ordered)
3239 (concat (eval ostart) "%s" (eval oend)))
3240 ((eq type 'descriptive)
3241 (concat (eval dstart) "%s" (eval dend)))
3242 (t (concat (eval ustart) "%s" (eval uend))))
3243 (eval lsep))))
3244 (format fmt (mapconcat (lambda (e)
3245 (funcall export-item e type depth))
3246 items (or (eval isep) ""))))))))
3247 (concat (funcall export-sublist list 0) "\n")))
3249 (defun org-list-to-latex (list &optional params)
3250 "Convert LIST into a LaTeX list.
3251 LIST is as string representing the list to transform, as Org
3252 syntax. Return converted list as a string."
3253 (require 'ox-latex)
3254 (org-export-string-as list 'latex t))
3256 (defun org-list-to-html (list)
3257 "Convert LIST into a HTML list.
3258 LIST is as string representing the list to transform, as Org
3259 syntax. Return converted list as a string."
3260 (require 'ox-html)
3261 (org-export-string-as list 'html t))
3263 (defun org-list-to-texinfo (list &optional params)
3264 "Convert LIST into a Texinfo list.
3265 LIST is as string representing the list to transform, as Org
3266 syntax. Return converted list as a string."
3267 (require 'ox-texinfo)
3268 (org-export-string-as list 'texinfo t))
3270 (defun org-list-to-subtree (list &optional params)
3271 "Convert LIST into an Org subtree.
3272 LIST is as returned by `org-list-parse-list'. PARAMS is a property list
3273 with overruling parameters for `org-list-to-generic'."
3274 (let* ((rule (cdr (assq 'heading org-blank-before-new-entry)))
3275 (level (org-reduced-level (or (org-current-level) 0)))
3276 (blankp (or (eq rule t)
3277 (and (eq rule 'auto)
3278 (save-excursion
3279 (outline-previous-heading)
3280 (org-previous-line-empty-p)))))
3281 (get-stars
3282 (function
3283 ;; Return the string for the heading, depending on depth D
3284 ;; of current sub-list.
3285 (lambda (d)
3286 (let ((oddeven-level (+ level d 1)))
3287 (concat (make-string (if org-odd-levels-only
3288 (1- (* 2 oddeven-level))
3289 oddeven-level)
3291 " "))))))
3292 (org-list-to-generic
3293 list
3294 (org-combine-plists
3295 '(:splice t
3296 :dtstart " " :dtend " "
3297 :istart (funcall get-stars depth)
3298 :icount (funcall get-stars depth)
3299 :isep (if blankp "\n\n" "\n")
3300 :csep (if blankp "\n\n" "\n")
3301 :cbon "DONE" :cboff "TODO" :cbtrans "TODO")
3302 params))))
3304 (provide 'org-list)
3306 ;;; org-list.el ends here