Merge from trunk
[bpt/emacs.git] / lisp / org / org-list.el
1 ;;; org-list.el --- Plain lists for Org-mode
2 ;;
3 ;; Copyright (C) 2004, 2005, 2006, 2007, 2008, 2009, 2010
4 ;; Free Software Foundation, Inc.
5 ;;
6 ;; Author: Carsten Dominik <carsten at orgmode dot org>
7 ;; Bastien Guerry <bzg AT altern DOT org>
8 ;; Keywords: outlines, hypermedia, calendar, wp
9 ;; Homepage: http://orgmode.org
10 ;; Version: 7.3
11 ;;
12 ;; This file is part of GNU Emacs.
13 ;;
14 ;; GNU Emacs is free software: you can redistribute it and/or modify
15 ;; it under the terms of the GNU General Public License as published by
16 ;; the Free Software Foundation, either version 3 of the License, or
17 ;; (at your option) any later version.
18
19 ;; GNU Emacs is distributed in the hope that it will be useful,
20 ;; but WITHOUT ANY WARRANTY; without even the implied warranty of
21 ;; MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
22 ;; GNU General Public License for more details.
23
24 ;; You should have received a copy of the GNU General Public License
25 ;; along with GNU Emacs. If not, see <http://www.gnu.org/licenses/>.
26 ;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;
27 ;;
28 ;;; Commentary:
29
30 ;; This file contains the code dealing with plain lists in Org-mode.
31
32 ;;; Code:
33
34 (eval-when-compile
35 (require 'cl))
36 (require 'org-macs)
37 (require 'org-compat)
38
39 (defvar org-blank-before-new-entry)
40 (defvar org-M-RET-may-split-line)
41 (defvar org-complex-heading-regexp)
42 (defvar org-odd-levels-only)
43 (defvar org-outline-regexp)
44 (defvar org-ts-regexp)
45 (defvar org-ts-regexp-both)
46
47 (declare-function org-invisible-p "org" ())
48 (declare-function org-on-heading-p "org" (&optional invisible-ok))
49 (declare-function outline-next-heading "outline" ())
50 (declare-function org-back-to-heading "org" (&optional invisible-ok))
51 (declare-function org-back-over-empty-lines "org" ())
52 (declare-function org-trim "org" (s))
53 (declare-function org-get-indentation "org" (&optional line))
54 (declare-function org-timer-item "org-timer" (&optional arg))
55 (declare-function org-timer-hms-to-secs "org-timer" (hms))
56 (declare-function org-combine-plists "org" (&rest plists))
57 (declare-function org-entry-get "org"
58 (pom property &optional inherit literal-nil))
59 (declare-function org-narrow-to-subtree "org" ())
60 (declare-function org-show-subtree "org" ())
61 (declare-function org-in-regexps-block-p "org"
62 (start-re end-re &optional bound))
63 (declare-function org-level-increment "org" ())
64 (declare-function org-at-heading-p "org" (&optional ignored))
65 (declare-function outline-previous-heading "outline" ())
66 (declare-function org-icompleting-read "org" (&rest args))
67 (declare-function org-time-string-to-seconds "org" (s))
68
69 (defgroup org-plain-lists nil
70 "Options concerning plain lists in Org-mode."
71 :tag "Org Plain lists"
72 :group 'org-structure)
73
74 (defcustom org-cycle-include-plain-lists t
75 "When t, make TAB cycle visibility on plain list items.
76 Cycling plain lists works only when the cursor is on a plain list
77 item. When the cursor is on an outline heading, plain lists are
78 treated as text. This is the most stable way of handling this,
79 which is why it is the default.
80
81 When this is the symbol `integrate', then during cycling, plain
82 list items will *temporarily* be interpreted as outline headlines
83 with a level given by 1000+i where i is the indentation of the
84 bullet. This setting can lead to strange effects when switching
85 visibility to `children', because the first \"child\" in a
86 subtree decides what children should be listed. If that first
87 \"child\" is a plain list item with an implied large level
88 number, all true children and grand children of the outline
89 heading will be exposed in a children' view."
90 :group 'org-plain-lists
91 :type '(choice
92 (const :tag "Never" nil)
93 (const :tag "With cursor in plain list (recommended)" t)
94 (const :tag "As children of outline headings" integrate)))
95
96 (defcustom org-list-demote-modify-bullet nil
97 "Default bullet type installed when demoting an item.
98 This is an association list, for each bullet type, this alist will point
99 to the bullet that should be used when this item is demoted.
100 For example,
101
102 (setq org-list-demote-modify-bullet
103 '((\"+\" . \"-\") (\"-\" . \"+\") (\"*\" . \"+\")))
104
105 will make
106
107 + Movies
108 + Silence of the Lambs
109 + My Cousin Vinny
110 + Books
111 + The Hunt for Red October
112 + The Road to Omaha
113
114 into
115
116 + Movies
117 - Silence of the Lambs
118 - My Cousin Vinny
119 + Books
120 - The Hunt for Red October
121 - The Road to Omaha"
122 :group 'org-plain-lists
123 :type '(repeat
124 (cons
125 (choice :tag "If the current bullet is "
126 (const "-")
127 (const "+")
128 (const "*")
129 (const "1.")
130 (const "1)"))
131 (choice :tag "demotion will change it to"
132 (const "-")
133 (const "+")
134 (const "*")
135 (const "1.")
136 (const "1)")))))
137
138 (defcustom org-plain-list-ordered-item-terminator t
139 "The character that makes a line with leading number an ordered list item.
140 Valid values are ?. and ?\). To get both terminators, use t. While
141 ?. may look nicer, it creates the danger that a line with leading
142 number may be incorrectly interpreted as an item. ?\) therefore is
143 the safe choice."
144 :group 'org-plain-lists
145 :type '(choice (const :tag "dot like in \"2.\"" ?.)
146 (const :tag "paren like in \"2)\"" ?\))
147 (const :tab "both" t)))
148
149 (defcustom org-list-two-spaces-after-bullet-regexp nil
150 "A regular expression matching bullets that should have 2 spaces after them.
151 When nil, no bullet will have two spaces after them.
152 When a string, it will be used as a regular expression. When the
153 bullet type of a list is changed, the new bullet type will be
154 matched against this regexp. If it matches, there will be two
155 spaces instead of one after the bullet in each item of the list."
156 :group 'org-plain-lists
157 :type '(choice
158 (const :tag "never" nil)
159 (regexp)))
160
161 (defcustom org-list-ending-method 'both
162 "Determine where plain lists should end.
163 Valid values are: `regexp', `indent' or `both'.
164
165 When set to `regexp', Org will look into two variables,
166 `org-empty-line-terminates-plain-lists' and the more general
167 `org-list-end-regexp', to determine what will end lists. This is
168 the fastest method.
169
170 When set to `indent', a list will end whenever a line following
171 an item, but not starting one, is less or equally indented than
172 it.
173
174 When set to `both', each of the preceding methods is applied to
175 determine lists endings. This is the default method."
176 :group 'org-plain-lists
177 :type '(choice
178 (const :tag "With a regexp defining ending" regexp)
179 (const :tag "With indentation of regular (no bullet) text" indent)
180 (const :tag "With both methods" both)))
181
182 (defcustom org-empty-line-terminates-plain-lists nil
183 "Non-nil means an empty line ends all plain list levels.
184 This variable only makes sense if `org-list-ending-method' is set
185 to `regexp' or `both'. This is then equivalent to set
186 `org-list-end-regexp' to \"^[ \\t]*$\"."
187 :group 'org-plain-lists
188 :type 'boolean)
189
190 (defcustom org-list-end-regexp "^[ \t]*\n[ \t]*\n"
191 "Regexp matching the end of all plain list levels.
192 It must start with \"^\" and end with \"\\n\". It defaults to 2
193 blank lines. `org-empty-line-terminates-plain-lists' has
194 precedence over it."
195 :group 'org-plain-lists
196 :type 'string)
197
198 (defcustom org-list-automatic-rules '((bullet . t)
199 (checkbox . t)
200 (indent . t)
201 (insert . t))
202 "Non-nil means apply set of rules when acting on lists.
203 By default, automatic actions are taken when using
204 \\[org-meta-return], \\[org-metaright], \\[org-metaleft],
205 \\[org-shiftmetaright], \\[org-shiftmetaleft],
206 \\[org-ctrl-c-minus], \\[org-toggle-checkbox] or
207 \\[org-insert-todo-heading]. You can disable individually these
208 rules by setting them to nil. Valid rules are:
209
210 bullet when non-nil, cycling bullet do not allow lists at
211 column 0 to have * as a bullet and descriptions lists
212 to be numbered.
213 checkbox when non-nil, checkbox statistics is updated each time
214 you either insert a new checkbox or toggle a checkbox.
215 It also prevents from inserting a checkbox in a
216 description item.
217 indent when non-nil, indenting or outdenting list top-item
218 with its subtree will move the whole list and
219 outdenting a list whose bullet is * to column 0 will
220 change that bullet to -
221 insert when non-nil, trying to insert an item inside a block
222 will insert it right before the block instead of
223 throwing an error."
224 :group 'org-plain-lists
225 :type '(alist :tag "Sets of rules"
226 :key-type
227 (choice
228 (const :tag "Bullet" bullet)
229 (const :tag "Checkbox" checkbox)
230 (const :tag "Indent" indent)
231 (const :tag "Insert" insert))
232 :value-type
233 (boolean :tag "Activate" :value t)))
234
235 (defcustom org-hierarchical-checkbox-statistics t
236 "Non-nil means checkbox statistics counts only the state of direct children.
237 When nil, all boxes below the cookie are counted.
238 This can be set to nil on a per-node basis using a COOKIE_DATA property
239 with the word \"recursive\" in the value."
240 :group 'org-plain-lists
241 :type 'boolean)
242
243 (defcustom org-description-max-indent 20
244 "Maximum indentation for the second line of a description list.
245 When the indentation would be larger than this, it will become
246 5 characters instead."
247 :group 'org-plain-lists
248 :type 'integer)
249
250 (defcustom org-list-radio-list-templates
251 '((latex-mode "% BEGIN RECEIVE ORGLST %n
252 % END RECEIVE ORGLST %n
253 \\begin{comment}
254 #+ORGLST: SEND %n org-list-to-latex
255 -
256 \\end{comment}\n")
257 (texinfo-mode "@c BEGIN RECEIVE ORGLST %n
258 @c END RECEIVE ORGLST %n
259 @ignore
260 #+ORGLST: SEND %n org-list-to-texinfo
261 -
262 @end ignore\n")
263 (html-mode "<!-- BEGIN RECEIVE ORGLST %n -->
264 <!-- END RECEIVE ORGLST %n -->
265 <!--
266 #+ORGLST: SEND %n org-list-to-html
267 -
268 -->\n"))
269 "Templates for radio lists in different major modes.
270 All occurrences of %n in a template will be replaced with the name of the
271 list, obtained by prompting the user."
272 :group 'org-plain-lists
273 :type '(repeat
274 (list (symbol :tag "Major mode")
275 (string :tag "Format"))))
276
277 ;;; Internal functions
278
279 (defun org-list-end-re ()
280 "Return the regex corresponding to the end of a list.
281 It depends on `org-empty-line-terminates-plain-lists'."
282 (if org-empty-line-terminates-plain-lists
283 "^[ \t]*\n"
284 org-list-end-regexp))
285
286 (defun org-item-re (&optional general)
287 "Return the correct regular expression for plain lists.
288 If GENERAL is non-nil, return the general regexp independent of the value
289 of `org-plain-list-ordered-item-terminator'."
290 (cond
291 ((or general (eq org-plain-list-ordered-item-terminator t))
292 "\\([ \t]*\\([-+]\\|\\([0-9]+[.)]\\)\\)\\|[ \t]+\\*\\)\\([ \t]+\\|$\\)")
293 ((= org-plain-list-ordered-item-terminator ?.)
294 "\\([ \t]*\\([-+]\\|\\([0-9]+\\.\\)\\)\\|[ \t]+\\*\\)\\([ \t]+\\|$\\)")
295 ((= org-plain-list-ordered-item-terminator ?\))
296 "\\([ \t]*\\([-+]\\|\\([0-9]+)\\)\\)\\|[ \t]+\\*\\)\\([ \t]+\\|$\\)")
297 (t (error "Invalid value of `org-plain-list-ordered-item-terminator'"))))
298
299 (defconst org-item-beginning-re (concat "^" (org-item-re))
300 "Regexp matching the beginning of a plain list item.")
301
302 (defun org-list-ending-between (min max &optional firstp)
303 "Find the position of a list ending between MIN and MAX, or nil.
304 This function looks for `org-list-end-re' outside a block.
305
306 If FIRSTP in non-nil, return the point at the beginning of the
307 nearest valid terminator from MIN. Otherwise, return the point at
308 the end of the nearest terminator from MAX."
309 (save-excursion
310 (let* ((start (if firstp min max))
311 (end (if firstp max min))
312 (search-fun (if firstp
313 #'org-search-forward-unenclosed
314 #'org-search-backward-unenclosed))
315 (list-end-p (progn
316 (goto-char start)
317 (funcall search-fun (org-list-end-re) end t))))
318 ;; Is there a valid list ending somewhere ?
319 (and list-end-p
320 ;; we want to be on the first line of the list ender
321 (match-beginning 0)))))
322
323 (defun org-list-maybe-skip-block (search limit)
324 "Return non-nil value if point is in a block, skipping it on the way.
325 It looks for the boundary of the block in SEARCH direction,
326 stopping at LIMIT."
327 (save-match-data
328 (let ((case-fold-search t)
329 (boundary (if (eq search 're-search-forward) 3 5)))
330 (when (save-excursion
331 (and (funcall search "^[ \t]*#\\+\\(begin\\|end\\)_" limit t)
332 (= (length (match-string 1)) boundary)))
333 ;; We're in a block: get out of it
334 (goto-char (match-beginning 0))))))
335
336 (defun org-list-search-unenclosed-generic (search re bound noerr)
337 "Search a string outside blocks and protected places.
338 Arguments SEARCH, RE, BOUND and NOERR are similar to those in
339 `search-forward', `search-backward', `re-search-forward' and
340 `re-search-backward'."
341 (catch 'exit
342 (let ((origin (point)))
343 (while t
344 ;; 1. No match: return to origin or bound, depending on NOERR.
345 (unless (funcall search re bound noerr)
346 (throw 'exit (and (goto-char (if (memq noerr '(t nil)) origin bound))
347 nil)))
348 ;; 2. Match not in block or protected: return point. Else
349 ;; skip the block and carry on.
350 (unless (or (get-text-property (match-beginning 0) 'org-protected)
351 (org-list-maybe-skip-block search bound))
352 (throw 'exit (point)))))))
353
354 (defun org-search-backward-unenclosed (regexp &optional bound noerror)
355 "Like `re-search-backward' but don't stop inside blocks or protected places.
356 Arguments REGEXP, BOUND and NOERROR are similar to those used in
357 `re-search-backward'."
358 (org-list-search-unenclosed-generic
359 #'re-search-backward regexp (or bound (point-min)) noerror))
360
361 (defun org-search-forward-unenclosed (regexp &optional bound noerror)
362 "Like `re-search-forward' but don't stop inside blocks or protected places.
363 Arguments REGEXP, BOUND and NOERROR are similar to those used in
364 `re-search-forward'."
365 (org-list-search-unenclosed-generic
366 #'re-search-forward regexp (or bound (point-max)) noerror))
367
368 (defun org-list-in-item-p-with-indent (limit)
369 "Is the cursor inside a plain list?
370 Plain lists are considered ending when a non-blank line is less
371 indented than the previous item within LIMIT."
372 (save-excursion
373 (beginning-of-line)
374 (cond
375 ;; do not start searching inside a block...
376 ((org-list-maybe-skip-block #'re-search-backward limit))
377 ;; ... or at a blank line
378 ((looking-at "^[ \t]*$")
379 (skip-chars-backward " \r\t\n")
380 (beginning-of-line)))
381 (beginning-of-line)
382 (or (org-at-item-p)
383 (let* ((case-fold-search t)
384 (ind-ref (org-get-indentation))
385 ;; Ensure there is at least an item above
386 (up-item-p (save-excursion
387 (org-search-backward-unenclosed
388 org-item-beginning-re limit t))))
389 (and up-item-p
390 (catch 'exit
391 (while t
392 (cond
393 ((org-at-item-p)
394 (throw 'exit (< (org-get-indentation) ind-ref)))
395 ((looking-at "^[ \t]*$")
396 (skip-chars-backward " \r\t\n")
397 (beginning-of-line))
398 ((looking-at "^[ \t]*#\\+end_")
399 (re-search-backward "^[ \t]*#\\+begin_"))
400 (t
401 (setq ind-ref (min (org-get-indentation) ind-ref))
402 (forward-line -1))))))))))
403
404 (defun org-list-in-item-p-with-regexp (limit)
405 "Is the cursor inside a plain list?
406 Plain lists end when `org-list-end-regexp' is matched, or at a
407 blank line if `org-empty-line-terminates-plain-lists' is true.
408
409 Argument LIMIT specifies the upper-bound of the search."
410 (save-excursion
411 (let* ((actual-pos (goto-char (point-at-eol)))
412 ;; Moved to eol so current line can be matched by
413 ;; `org-item-re'.
414 (last-item-start (save-excursion
415 (org-search-backward-unenclosed
416 org-item-beginning-re limit t)))
417 (list-ender (org-list-ending-between
418 last-item-start actual-pos)))
419 ;; We are in a list when we are on an item line or when we can
420 ;; find an item before point and there is no valid list ender
421 ;; between it and the point.
422 (and last-item-start (not list-ender)))))
423
424 (defun org-list-top-point-with-regexp (limit)
425 "Return point at the top level item in a list.
426 Argument LIMIT specifies the upper-bound of the search.
427
428 List ending is determined by regexp. See
429 `org-list-ending-method'. for more information."
430 (save-excursion
431 (let ((pos (point-at-eol)))
432 ;; Is there some list above this one ? If so, go to its ending.
433 ;; Otherwise, go back to the heading above or bob.
434 (goto-char (or (org-list-ending-between limit pos) limit))
435 ;; From there, search down our list.
436 (org-search-forward-unenclosed org-item-beginning-re pos t)
437 (point-at-bol))))
438
439 (defun org-list-bottom-point-with-regexp (limit)
440 "Return point just before list ending.
441 Argument LIMIT specifies the lower-bound of the search.
442
443 List ending is determined by regexp. See
444 `org-list-ending-method'. for more information."
445 (save-excursion
446 (let ((pos (org-get-item-beginning)))
447 ;; The list ending is either first point matching
448 ;; `org-list-end-re', point at first white-line before next
449 ;; heading, or eob.
450 (or (org-list-ending-between (min pos limit) limit t) limit))))
451
452 (defun org-list-top-point-with-indent (limit)
453 "Return point at the top level in a list.
454 Argument LIMIT specifies the upper-bound of the search.
455
456 List ending is determined by indentation of text. See
457 `org-list-ending-method'. for more information."
458 (save-excursion
459 (let ((case-fold-search t))
460 (let ((item-ref (goto-char (org-get-item-beginning)))
461 (ind-ref 10000))
462 (forward-line -1)
463 (catch 'exit
464 (while t
465 (let ((ind (org-get-indentation)))
466 (cond
467 ((looking-at "^[ \t]*:END:")
468 (throw 'exit item-ref))
469 ((<= (point) limit)
470 (throw 'exit
471 (if (and (org-at-item-p) (< ind ind-ref))
472 (point-at-bol)
473 item-ref)))
474 ((looking-at "^[ \t]*$")
475 (skip-chars-backward " \r\t\n")
476 (beginning-of-line))
477 ((looking-at "^[ \t]*#\\+end_")
478 (re-search-backward "^[ \t]*#\\+begin_"))
479 ((not (org-at-item-p))
480 (setq ind-ref (min ind ind-ref))
481 (forward-line -1))
482 ((>= ind ind-ref)
483 (throw 'exit item-ref))
484 (t
485 (setq item-ref (point-at-bol) ind-ref 10000)
486 (forward-line -1))))))))))
487
488 (defun org-list-bottom-point-with-indent (limit)
489 "Return point just before list ending or nil if not in a list.
490 Argument LIMIT specifies the lower-bound of the search.
491
492 List ending is determined by the indentation of text. See
493 `org-list-ending-method' for more information."
494 (save-excursion
495 (let ((ind-ref (progn
496 (goto-char (org-get-item-beginning))
497 (org-get-indentation)))
498 (case-fold-search t))
499 ;; do not start inside a block
500 (org-list-maybe-skip-block #'re-search-forward limit)
501 (beginning-of-line)
502 (catch 'exit
503 (while t
504 (skip-chars-forward " \t")
505 (let ((ind (org-get-indentation)))
506 (cond
507 ((or (>= (point) limit)
508 (looking-at ":END:"))
509 (throw 'exit (progn
510 ;; Ensure bottom is just after a
511 ;; non-blank line.
512 (skip-chars-backward " \r\t\n")
513 (min (point-max) (1+ (point-at-eol))))))
514 ((= (point) (point-at-eol))
515 (skip-chars-forward " \r\t\n")
516 (beginning-of-line))
517 ((org-at-item-p)
518 (setq ind-ref ind)
519 (forward-line 1))
520 ((<= ind ind-ref)
521 (throw 'exit (point-at-bol)))
522 ((looking-at "#\\+begin_")
523 (re-search-forward "[ \t]*#\\+end_")
524 (forward-line 1))
525 (t (forward-line 1)))))))))
526
527 (defun org-list-at-regexp-after-bullet-p (regexp)
528 "Is point at a list item with REGEXP after bullet?"
529 (and (org-at-item-p)
530 (save-excursion
531 (goto-char (match-end 0))
532 ;; Ignore counter if any
533 (when (looking-at "\\(?:\\[@\\(?:start:\\)?[0-9]+\\][ \t]*\\)?")
534 (goto-char (match-end 0)))
535 (looking-at regexp))))
536
537 (defun org-list-get-item-same-level (search-fun pos limit pre-move)
538 "Return point at the beginning of next item at the same level.
539 Search items using function SEARCH-FUN, from POS to LIMIT. It
540 uses PRE-MOVE before search. Return nil if no item was found."
541 (save-excursion
542 (goto-char pos)
543 (let* ((start (org-get-item-beginning))
544 (ind (progn (goto-char start) (org-get-indentation))))
545 ;; We don't want to match the current line.
546 (funcall pre-move)
547 ;; Skip any sublist on the way
548 (while (and (funcall search-fun org-item-beginning-re limit t)
549 (> (org-get-indentation) ind)))
550 (when (and (/= (point-at-bol) start) ; Have we moved ?
551 (= (org-get-indentation) ind))
552 (point-at-bol)))))
553
554 (defun org-list-separating-blank-lines-number (pos top bottom)
555 "Return number of blank lines that should separate items in list.
556 POS is the position of point to be considered.
557
558 TOP and BOTTOM are respectively position of list beginning and
559 list ending.
560
561 Assume point is at item's beginning. If the item is alone, apply
562 some heuristics to guess the result."
563 (save-excursion
564 (let ((insert-blank-p
565 (cdr (assq 'plain-list-item org-blank-before-new-entry)))
566 usr-blank)
567 (cond
568 ;; Trivial cases where there should be none.
569 ((or (and (not (eq org-list-ending-method 'indent))
570 org-empty-line-terminates-plain-lists)
571 (not insert-blank-p)) 0)
572 ;; When `org-blank-before-new-entry' says so, it is 1.
573 ((eq insert-blank-p t) 1)
574 ;; plain-list-item is 'auto. Count blank lines separating
575 ;; neighbours items in list.
576 (t (let ((next-p (org-get-next-item (point) bottom)))
577 (cond
578 ;; Is there a next item?
579 (next-p (goto-char next-p)
580 (org-back-over-empty-lines))
581 ;; Is there a previous item?
582 ((org-get-previous-item (point) top)
583 (org-back-over-empty-lines))
584 ;; User inserted blank lines, trust him
585 ((and (> pos (org-end-of-item-before-blank bottom))
586 (> (save-excursion
587 (goto-char pos)
588 (skip-chars-backward " \t")
589 (setq usr-blank (org-back-over-empty-lines))) 0))
590 usr-blank)
591 ;; Are there blank lines inside the item ?
592 ((save-excursion
593 (org-search-forward-unenclosed
594 "^[ \t]*$" (org-end-of-item-before-blank bottom) t)) 1)
595 ;; No parent: no blank line.
596 (t 0))))))))
597
598 (defun org-list-insert-item-generic (pos &optional checkbox after-bullet)
599 "Insert a new list item at POS.
600 If POS is before first character after bullet of the item, the
601 new item will be created before the current one.
602
603 Insert a checkbox if CHECKBOX is non-nil, and string AFTER-BULLET
604 after the bullet. Cursor will be after this text once the
605 function ends."
606 (goto-char pos)
607 ;; Is point in a special block?
608 (when (org-in-regexps-block-p
609 "^[ \t]*#\\+\\(begin\\|BEGIN\\)_\\([a-zA-Z0-9_]+\\)"
610 '(concat "^[ \t]*#\\+\\(end\\|END\\)_" (match-string 2)))
611 (if (not (cdr (assq 'insert org-list-automatic-rules)))
612 ;; Rule in `org-list-automatic-rules' forbids insertion.
613 (error "Cannot insert item inside a block")
614 ;; Else, move before it prior to add a new item.
615 (end-of-line)
616 (re-search-backward "^[ \t]*#\\+\\(begin\\|BEGIN\\)_" nil t)
617 (end-of-line 0)))
618 (let* ((true-pos (point))
619 (top (org-list-top-point))
620 (bottom (copy-marker (org-list-bottom-point)))
621 (bullet (and (goto-char (org-get-item-beginning))
622 (org-list-bullet-string (org-get-bullet))))
623 (ind (org-get-indentation))
624 (before-p (progn
625 ;; Description item: text starts after colons.
626 (or (org-at-item-description-p)
627 ;; At a checkbox: text starts after it.
628 (org-at-item-checkbox-p)
629 ;; Otherwise, text starts after bullet.
630 (org-at-item-p))
631 (<= true-pos (match-end 0))))
632 (blank-lines-nb (org-list-separating-blank-lines-number
633 true-pos top bottom))
634 (insert-fun
635 (lambda (text)
636 ;; insert bullet above item in order to avoid bothering
637 ;; with possible blank lines ending last item.
638 (goto-char (org-get-item-beginning))
639 (indent-to-column ind)
640 (insert (concat bullet (when checkbox "[ ] ") after-bullet))
641 ;; Stay between after-bullet and before text.
642 (save-excursion
643 (insert (concat text (make-string (1+ blank-lines-nb) ?\n))))
644 (unless before-p
645 ;; store bottom: exchanging items doesn't change list
646 ;; bottom point but will modify marker anyway
647 (setq bottom (marker-position bottom))
648 (let ((col (current-column)))
649 (org-list-exchange-items
650 (org-get-item-beginning) (org-get-next-item (point) bottom)
651 bottom)
652 ;; recompute next-item: last sexp modified list
653 (goto-char (org-get-next-item (point) bottom))
654 (org-move-to-column col)))
655 ;; checkbox update might modify bottom point, so use a
656 ;; marker here
657 (setq bottom (copy-marker bottom))
658 (when checkbox (org-update-checkbox-count-maybe))
659 (org-list-repair nil top bottom))))
660 (goto-char true-pos)
661 (cond
662 (before-p (funcall insert-fun nil) t)
663 ;; Can't split item: insert bullet at the end of item.
664 ((not (org-get-alist-option org-M-RET-may-split-line 'item))
665 (funcall insert-fun nil) t)
666 ;; else, insert a new bullet along with everything from point
667 ;; down to last non-blank line of item.
668 (t
669 (delete-horizontal-space)
670 ;; Get pos again in case previous command modified line.
671 (let* ((pos (point))
672 (end-before-blank (org-end-of-item-before-blank bottom))
673 (after-text
674 (when (< pos end-before-blank)
675 (prog1
676 (delete-and-extract-region pos end-before-blank)
677 ;; delete any blank line at and before point.
678 (beginning-of-line)
679 (while (looking-at "^[ \t]*$")
680 (delete-region (point-at-bol) (1+ (point-at-eol)))
681 (beginning-of-line 0))))))
682 (funcall insert-fun after-text) t)))))
683
684 (defvar org-last-indent-begin-marker (make-marker))
685 (defvar org-last-indent-end-marker (make-marker))
686
687 (defun org-list-indent-item-generic (arg no-subtree top bottom)
688 "Indent a local list item including its children.
689 When number ARG is a negative, item will be outdented, otherwise
690 it will be indented.
691
692 If a region is active, all items inside will be moved.
693
694 If NO-SUBTREE is non-nil, only indent the item itself, not its
695 children.
696
697 TOP and BOTTOM are respectively position at item beginning and at
698 item ending.
699
700 Return t if successful."
701 (let* ((regionp (org-region-active-p))
702 (rbeg (and regionp (region-beginning)))
703 (rend (and regionp (region-end))))
704 (cond
705 ((and regionp
706 (goto-char rbeg)
707 (not (org-search-forward-unenclosed org-item-beginning-re rend t)))
708 (error "No item in region"))
709 ((not (org-at-item-p))
710 (error "Not on an item"))
711 (t
712 ;; Are we going to move the whole list?
713 (let* ((specialp (and (cdr (assq 'indent org-list-automatic-rules))
714 (not no-subtree)
715 (= top (point-at-bol)))))
716 ;; Determine begin and end points of zone to indent. If moving
717 ;; more than one item, ensure we keep them on subsequent moves.
718 (unless (and (memq last-command '(org-shiftmetaright org-shiftmetaleft))
719 (memq this-command '(org-shiftmetaright org-shiftmetaleft)))
720 (if regionp
721 (progn
722 (set-marker org-last-indent-begin-marker rbeg)
723 (set-marker org-last-indent-end-marker rend))
724 (set-marker org-last-indent-begin-marker (point-at-bol))
725 (set-marker org-last-indent-end-marker
726 (save-excursion
727 (cond
728 (specialp bottom)
729 (no-subtree (org-end-of-item-or-at-child bottom))
730 (t (org-get-end-of-item bottom)))))))
731 ;; Get everything ready
732 (let* ((beg (marker-position org-last-indent-begin-marker))
733 (end (marker-position org-last-indent-end-marker))
734 (struct (org-list-struct
735 beg end top (if specialp end bottom) (< arg 0)))
736 (origins (org-list-struct-origins struct))
737 (beg-item (assq beg struct)))
738 (cond
739 ;; Special case: moving top-item with indent rule
740 (specialp
741 (let* ((level-skip (org-level-increment))
742 (offset (if (< arg 0) (- level-skip) level-skip))
743 (top-ind (nth 1 beg-item)))
744 (if (< (+ top-ind offset) 0)
745 (error "Cannot outdent beyond margin")
746 ;; Change bullet if necessary
747 (when (and (= (+ top-ind offset) 0)
748 (string-match "*" (nth 2 beg-item)))
749 (setcdr beg-item (list (nth 1 beg-item)
750 (org-list-bullet-string "-"))))
751 ;; Shift ancestor
752 (let ((anc (car struct)))
753 (setcdr anc (list (+ (nth 1 anc) offset) "" nil)))
754 (org-list-struct-fix-struct struct origins)
755 (org-list-struct-apply-struct struct end))))
756 ;; Forbidden move
757 ((and (< arg 0)
758 (or (and no-subtree
759 (not regionp)
760 (org-list-struct-get-child beg-item struct))
761 (let ((last-item (save-excursion
762 (goto-char end)
763 (skip-chars-backward " \r\t\n")
764 (goto-char (org-get-item-beginning))
765 (org-list-struct-assoc-at-point))))
766 (org-list-struct-get-child last-item struct))))
767 (error "Cannot outdent an item without its children"))
768 ;; Normal shifting
769 (t
770 (let* ((shifted-ori (if (< arg 0)
771 (org-list-struct-outdent beg end origins)
772 (org-list-struct-indent beg end origins struct))))
773 (org-list-struct-fix-struct struct shifted-ori)
774 (org-list-struct-apply-struct struct bottom))))))))))
775
776 ;;; Predicates
777
778 (defun org-in-item-p ()
779 "Is the cursor inside a plain list?
780 This checks `org-list-ending-method'."
781 (unless (let ((outline-regexp org-outline-regexp)) (org-at-heading-p))
782 (let* ((prev-head (save-excursion (outline-previous-heading)))
783 (bound (if prev-head
784 (or (save-excursion
785 (let ((case-fold-search t))
786 (re-search-backward "^[ \t]*:END:" prev-head t)))
787 prev-head)
788 (point-min))))
789 (cond
790 ((eq org-list-ending-method 'regexp)
791 (org-list-in-item-p-with-regexp bound))
792 ((eq org-list-ending-method 'indent)
793 (org-list-in-item-p-with-indent bound))
794 (t (and (org-list-in-item-p-with-regexp bound)
795 (org-list-in-item-p-with-indent bound)))))))
796
797 (defun org-list-first-item-p (top)
798 "Is this item the first item in a plain list?
799 Assume point is at an item.
800
801 TOP is the position of list's top-item."
802 (save-excursion
803 (beginning-of-line)
804 (let ((ind (org-get-indentation)))
805 (or (not (org-search-backward-unenclosed org-item-beginning-re top t))
806 (< (org-get-indentation) ind)))))
807
808 (defun org-at-item-p ()
809 "Is point in a line starting a hand-formatted item?"
810 (save-excursion
811 (beginning-of-line) (looking-at org-item-beginning-re)))
812
813 (defun org-at-item-bullet-p ()
814 "Is point at the bullet of a plain list item?"
815 (and (org-at-item-p)
816 (not (member (char-after) '(?\ ?\t)))
817 (< (point) (match-end 0))))
818
819 (defun org-at-item-timer-p ()
820 "Is point at a line starting a plain list item with a timer?"
821 (org-list-at-regexp-after-bullet-p
822 "\\([0-9]+:[0-9]+:[0-9]+\\)[ \t]+::[ \t]+"))
823
824 (defun org-at-item-description-p ()
825 "Is point at a description list item?"
826 (org-list-at-regexp-after-bullet-p "\\(\\S-.+\\)[ \t]+::[ \t]+"))
827
828 (defun org-at-item-checkbox-p ()
829 "Is point at a line starting a plain-list item with a checklet?"
830 (org-list-at-regexp-after-bullet-p "\\(\\[[- X]\\]\\)[ \t]+"))
831
832 (defun org-checkbox-blocked-p ()
833 "Is the current checkbox blocked from for being checked now?
834 A checkbox is blocked if all of the following conditions are fulfilled:
835
836 1. The checkbox is not checked already.
837 2. The current entry has the ORDERED property set.
838 3. There is an unchecked checkbox in this entry before the current line."
839 (catch 'exit
840 (save-match-data
841 (save-excursion
842 (unless (org-at-item-checkbox-p) (throw 'exit nil))
843 (when (equal (match-string 1) "[X]")
844 ;; the box is already checked!
845 (throw 'exit nil))
846 (let ((end (point-at-bol)))
847 (condition-case nil (org-back-to-heading t)
848 (error (throw 'exit nil)))
849 (unless (org-entry-get nil "ORDERED") (throw 'exit nil))
850 (when (org-search-forward-unenclosed
851 "^[ \t]*[-+*0-9.)]+[ \t]+\\(\\[@\\(?:start:\\)?[0-9]+\\][ \t]*\\)?\\[[- ]\\]" end t)
852 (org-current-line)))))))
853
854 ;;; Navigate
855
856 ;; Every interactive navigation function is derived from a
857 ;; non-interactive one, which doesn't move point, assumes point is
858 ;; already in a list and doesn't compute list boundaries.
859
860 ;; If you plan to use more than one org-list function is some code,
861 ;; you should therefore first check if point is in a list with
862 ;; `org-in-item-p' or `org-at-item-p', then compute list boundaries
863 ;; with `org-list-top-point' and `org-list-bottom-point', and make use
864 ;; of non-interactive forms.
865
866 (defun org-list-top-point ()
867 "Return point at the top level in a list.
868 Assume point is in a list."
869 (let* ((prev-head (save-excursion (outline-previous-heading)))
870 (bound (if prev-head
871 (or (save-excursion
872 (let ((case-fold-search t))
873 (re-search-backward "^[ \t]*:END:" prev-head t)))
874 prev-head)
875 (point-min))))
876 (cond
877 ((eq org-list-ending-method 'regexp)
878 (org-list-top-point-with-regexp bound))
879 ((eq org-list-ending-method 'indent)
880 (org-list-top-point-with-indent bound))
881 (t (let ((top-re (org-list-top-point-with-regexp bound)))
882 (org-list-top-point-with-indent (or top-re bound)))))))
883
884 (defun org-list-bottom-point ()
885 "Return point just before list ending.
886 Assume point is in a list."
887 (let* ((next-head (save-excursion
888 (and (let ((outline-regexp org-outline-regexp))
889 ;; Use default regexp because folding
890 ;; changes OUTLINE-REGEXP.
891 (outline-next-heading)))))
892 (limit (or (save-excursion
893 (and (re-search-forward "^[ \t]*:END:" next-head t)
894 (point-at-bol)))
895 next-head
896 (point-max))))
897 (cond
898 ((eq org-list-ending-method 'regexp)
899 (org-list-bottom-point-with-regexp limit))
900 ((eq org-list-ending-method 'indent)
901 (org-list-bottom-point-with-indent limit))
902 (t (let ((bottom-re (org-list-bottom-point-with-regexp limit)))
903 (org-list-bottom-point-with-indent (or bottom-re limit)))))))
904
905 (defun org-get-item-beginning ()
906 "Return position of current item beginning."
907 (save-excursion
908 ;; possibly match current line
909 (end-of-line)
910 (org-search-backward-unenclosed org-item-beginning-re nil t)
911 (point-at-bol)))
912
913 (defun org-beginning-of-item ()
914 "Go to the beginning of the current hand-formatted item.
915 If the cursor is not in an item, throw an error."
916 (interactive)
917 (if (org-in-item-p)
918 (goto-char (org-get-item-beginning))
919 (error "Not in an item")))
920
921 (defun org-get-beginning-of-list (top)
922 "Return position of the first item of the current list or sublist.
923 TOP is the position at list beginning."
924 (save-excursion
925 (let (prev-p)
926 (while (setq prev-p (org-get-previous-item (point) top))
927 (goto-char prev-p))
928 (point-at-bol))))
929
930 (defun org-beginning-of-item-list ()
931 "Go to the beginning item of the current list or sublist.
932 Return an error if not in a list."
933 (interactive)
934 (if (org-in-item-p)
935 (goto-char (org-get-beginning-of-list (org-list-top-point)))
936 (error "Not in an item")))
937
938 (defun org-get-end-of-list (bottom)
939 "Return position at the end of the current list or sublist.
940 BOTTOM is the position at list ending."
941 (save-excursion
942 (goto-char (org-get-item-beginning))
943 (let ((ind (org-get-indentation)))
944 (while (and (/= (point) bottom)
945 (>= (org-get-indentation) ind))
946 (org-search-forward-unenclosed org-item-beginning-re bottom 'move))
947 (if (= (point) bottom) bottom (point-at-bol)))))
948
949 (defun org-end-of-item-list ()
950 "Go to the end of the current list or sublist.
951 If the cursor in not in an item, throw an error."
952 (interactive)
953 (if (org-in-item-p)
954 (goto-char (org-get-end-of-list (org-list-bottom-point)))
955 (error "Not in an item")))
956
957 (defun org-get-end-of-item (bottom)
958 "Return position at the end of the current item.
959 BOTTOM is the position at list ending."
960 (or (org-get-next-item (point) bottom)
961 (org-get-end-of-list bottom)))
962
963 (defun org-end-of-item ()
964 "Go to the end of the current hand-formatted item.
965 If the cursor is not in an item, throw an error."
966 (interactive)
967 (if (org-in-item-p)
968 (goto-char (org-get-end-of-item (org-list-bottom-point)))
969 (error "Not in an item")))
970
971 (defun org-end-of-item-or-at-child (bottom)
972 "Move to the end of the item, stops before the first child if any.
973 BOTTOM is the position at list ending."
974 (end-of-line)
975 (goto-char
976 (if (org-search-forward-unenclosed org-item-beginning-re bottom t)
977 (point-at-bol)
978 (org-get-end-of-item bottom))))
979
980 (defun org-end-of-item-before-blank (bottom)
981 "Return point at end of item, before any blank line.
982 Point returned is at eol.
983
984 BOTTOM is the position at list ending."
985 (save-excursion
986 (goto-char (org-get-end-of-item bottom))
987 (skip-chars-backward " \r\t\n")
988 (point-at-eol)))
989
990 (defun org-get-previous-item (pos limit)
991 "Return point of the previous item at the same level as POS.
992 Stop searching at LIMIT. Return nil if no item is found."
993 (org-list-get-item-same-level
994 #'org-search-backward-unenclosed pos limit #'beginning-of-line))
995
996 (defun org-previous-item ()
997 "Move to the beginning of the previous item.
998 Item is at the same level in the current plain list. Error if not
999 in a plain list, or if this is the first item in the list."
1000 (interactive)
1001 (if (not (org-in-item-p))
1002 (error "Not in an item")
1003 (let ((prev-p (org-get-previous-item (point) (org-list-top-point))))
1004 (if prev-p (goto-char prev-p) (error "On first item")))))
1005
1006 (defun org-get-next-item (pos limit)
1007 "Return point of the next item at the same level as POS.
1008 Stop searching at LIMIT. Return nil if no item is found."
1009 (org-list-get-item-same-level
1010 #'org-search-forward-unenclosed pos limit #'end-of-line))
1011
1012 (defun org-next-item ()
1013 "Move to the beginning of the next item.
1014 Item is at the same level in the current plain list. Error if not
1015 in a plain list, or if this is the last item in the list."
1016 (interactive)
1017 (if (not (org-in-item-p))
1018 (error "Not in an item")
1019 (let ((next-p (org-get-next-item (point) (org-list-bottom-point))))
1020 (if next-p (goto-char next-p) (error "On last item")))))
1021
1022 ;;; Manipulate
1023
1024 (defun org-list-exchange-items (beg-A beg-B bottom)
1025 "Swap item starting at BEG-A with item starting at BEG-B.
1026 Blank lines at the end of items are left in place. Assume BEG-A
1027 is lesser than BEG-B.
1028
1029 BOTTOM is the position at list ending."
1030 (save-excursion
1031 (let* ((end-of-item-no-blank
1032 (lambda (pos)
1033 (goto-char pos)
1034 (goto-char (org-end-of-item-before-blank bottom))))
1035 (end-A-no-blank (funcall end-of-item-no-blank beg-A))
1036 (end-B-no-blank (funcall end-of-item-no-blank beg-B))
1037 (body-A (buffer-substring beg-A end-A-no-blank))
1038 (body-B (buffer-substring beg-B end-B-no-blank))
1039 (between-A-no-blank-and-B (buffer-substring end-A-no-blank beg-B)))
1040 (goto-char beg-A)
1041 (delete-region beg-A end-B-no-blank)
1042 (insert (concat body-B between-A-no-blank-and-B body-A)))))
1043
1044 (defun org-move-item-down ()
1045 "Move the plain list item at point down, i.e. swap with following item.
1046 Subitems (items with larger indentation) are considered part of the item,
1047 so this really moves item trees."
1048 (interactive)
1049 (if (not (org-at-item-p))
1050 (error "Not at an item")
1051 (let* ((pos (point))
1052 (col (current-column))
1053 (bottom (org-list-bottom-point))
1054 (actual-item (goto-char (org-get-item-beginning)))
1055 (next-item (org-get-next-item (point) bottom)))
1056 (if (not next-item)
1057 (progn
1058 (goto-char pos)
1059 (error "Cannot move this item further down"))
1060 (org-list-exchange-items actual-item next-item bottom)
1061 (org-list-repair nil nil bottom)
1062 (goto-char (org-get-next-item (point) bottom))
1063 (move-to-column col)))))
1064
1065 (defun org-move-item-up ()
1066 "Move the plain list item at point up, i.e. swap with previous item.
1067 Subitems (items with larger indentation) are considered part of the item,
1068 so this really moves item trees."
1069 (interactive)
1070 (if (not (org-at-item-p))
1071 (error "Not at an item")
1072 (let* ((pos (point))
1073 (col (current-column))
1074 (top (org-list-top-point))
1075 (bottom (org-list-bottom-point))
1076 (actual-item (goto-char (org-get-item-beginning)))
1077 (prev-item (org-get-previous-item (point) top)))
1078 (if (not prev-item)
1079 (progn
1080 (goto-char pos)
1081 (error "Cannot move this item further up"))
1082 (org-list-exchange-items prev-item actual-item bottom)
1083 (org-list-repair nil top bottom)
1084 (move-to-column col)))))
1085
1086 (defun org-insert-item (&optional checkbox)
1087 "Insert a new item at the current level.
1088 If cursor is before first character after bullet of the item, the
1089 new item will be created before the current one.
1090
1091 If CHECKBOX is non-nil, add a checkbox next to the bullet.
1092
1093 Return t when things worked, nil when we are not in an item, or
1094 item is invisible."
1095 (unless (or (not (org-in-item-p))
1096 (save-excursion
1097 (goto-char (org-get-item-beginning))
1098 (org-invisible-p)))
1099 (if (save-excursion
1100 (goto-char (org-get-item-beginning))
1101 (org-at-item-timer-p))
1102 ;; Timer list: delegate to `org-timer-item'.
1103 (progn (org-timer-item) t)
1104 ;; if we're in a description list, ask for the new term.
1105 (let ((desc-text (when (save-excursion
1106 (and (goto-char (org-get-item-beginning))
1107 (org-at-item-description-p)))
1108 (concat (read-string "Term: ") " :: "))))
1109 ;; Don't insert a checkbox if checkbox rule is applied and it
1110 ;; is a description item.
1111 (org-list-insert-item-generic
1112 (point) (and checkbox
1113 (or (not desc-text)
1114 (not (cdr (assq 'checkbox org-list-automatic-rules)))))
1115 desc-text)))))
1116
1117 ;;; Structures
1118
1119 ;; The idea behind structures is to avoid moving back and forth in the
1120 ;; buffer on costly operations like indenting or fixing bullets.
1121
1122 ;; It achieves this by taking a snapshot of an interesting part of the
1123 ;; list, in the shape of an alist, using `org-list-struct'.
1124
1125 ;; It then proceeds to changes directly on the alist, with the help of
1126 ;; and `org-list-struct-origins'. When those are done,
1127 ;; `org-list-struct-apply-struct' applies the changes to the buffer.
1128
1129 (defun org-list-struct-assoc-at-point ()
1130 "Return the structure association at point.
1131 It is a cons-cell whose key is point and values are indentation,
1132 bullet string and bullet counter, if any."
1133 (save-excursion
1134 (beginning-of-line)
1135 (list (point-at-bol)
1136 (org-get-indentation)
1137 (progn
1138 (looking-at "^[ \t]*\\([-+*0-9.)]+[ \t]+\\)")
1139 (match-string 1))
1140 (progn
1141 (goto-char (match-end 0))
1142 (and (looking-at "\\[@\\(?:start:\\)?\\([0-9]+\\)\\]")
1143 (match-string 1))))))
1144
1145 (defun org-list-struct (begin end top bottom &optional outdent)
1146 "Return the structure containing the list between BEGIN and END.
1147 A structure is an alist where key is point of item and values
1148 are, in that order, indentation, bullet string and value of
1149 counter, if any. A structure contains every list and sublist that
1150 has items between BEGIN and END along with their common ancestor.
1151 If no such ancestor can be found, the function will add a virtual
1152 ancestor at position 0.
1153
1154 TOP and BOTTOM are respectively the position of list beginning
1155 and list ending.
1156
1157 If OUTDENT is non-nil, it will also grab all of the parent list
1158 and the grand-parent. Setting OUTDENT to t is mandatory when next
1159 change is an outdent."
1160 (save-excursion
1161 (let* (struct
1162 (extend
1163 (lambda (struct)
1164 (let* ((ind-min (apply 'min (mapcar 'cadr struct)))
1165 (begin (caar struct))
1166 (end (caar (last struct)))
1167 pre-list post-list)
1168 (goto-char begin)
1169 ;; Find beginning of most outdented list (min list)
1170 (while (and (org-search-backward-unenclosed
1171 org-item-beginning-re top t)
1172 (>= (org-get-indentation) ind-min))
1173 (setq pre-list (cons (org-list-struct-assoc-at-point)
1174 pre-list)))
1175 ;; Now get the parent. If none, add a virtual ancestor
1176 (if (< (org-get-indentation) ind-min)
1177 (setq pre-list (cons (org-list-struct-assoc-at-point)
1178 pre-list))
1179 (setq pre-list (cons (list 0 (org-get-indentation) "" nil)
1180 pre-list)))
1181 ;; Find end of min list
1182 (goto-char end)
1183 (end-of-line)
1184 (while (and (org-search-forward-unenclosed
1185 org-item-beginning-re bottom 'move)
1186 (>= (org-get-indentation) ind-min))
1187 (setq post-list (cons (org-list-struct-assoc-at-point)
1188 post-list)))
1189 ;; Is list is malformed? If some items are less
1190 ;; indented that top-item, add them anyhow.
1191 (when (and (= (caar pre-list) 0) (< (point) bottom))
1192 (beginning-of-line)
1193 (while (org-search-forward-unenclosed
1194 org-item-beginning-re bottom t)
1195 (setq post-list (cons (org-list-struct-assoc-at-point)
1196 post-list))))
1197 (append pre-list struct (reverse post-list))))))
1198 ;; Here we start: first get the core zone...
1199 (goto-char end)
1200 (while (org-search-backward-unenclosed org-item-beginning-re begin t)
1201 (setq struct (cons (org-list-struct-assoc-at-point) struct)))
1202 ;; ... then, extend it to make it a structure...
1203 (let ((extended (funcall extend struct)))
1204 ;; ... twice when OUTDENT is non-nil and struct still can be
1205 ;; extended
1206 (if (and outdent (> (caar extended) 0))
1207 (funcall extend extended)
1208 extended)))))
1209
1210 (defun org-list-struct-origins (struct)
1211 "Return an alist where key is item's position and value parent's.
1212 STRUCT is the list's structure looked up."
1213 (let* ((struct-rev (reverse struct))
1214 (acc (list (cons (nth 1 (car struct)) 0)))
1215 (prev-item (lambda (item)
1216 (car (nth 1 (member (assq item struct) struct-rev)))))
1217 (get-origins
1218 (lambda (item)
1219 (let* ((item-pos (car item))
1220 (ind (nth 1 item))
1221 (prev-ind (caar acc)))
1222 (cond
1223 ;; List closing.
1224 ((> prev-ind ind)
1225 (let ((current-origin (or (member (assq ind acc) acc)
1226 ;; needed if top-point is
1227 ;; not the most outdented
1228 (last acc))))
1229 (setq acc current-origin)
1230 (cons item-pos (cdar acc))))
1231 ;; New list
1232 ((< prev-ind ind)
1233 (let ((origin (funcall prev-item item-pos)))
1234 (setq acc (cons (cons ind origin) acc))
1235 (cons item-pos origin)))
1236 ;; Current list going on
1237 (t (cons item-pos (cdar acc))))))))
1238 (cons '(0 . 0) (mapcar get-origins (cdr struct)))))
1239
1240 (defun org-list-struct-get-parent (item struct origins)
1241 "Return parent association of ITEM in STRUCT or nil.
1242 ORIGINS is the alist of parents. See `org-list-struct-origins'."
1243 (let* ((parent-pos (cdr (assq (car item) origins))))
1244 (when (> parent-pos 0) (assq parent-pos struct))))
1245
1246 (defun org-list-struct-get-child (item struct)
1247 "Return child association of ITEM in STRUCT or nil."
1248 (let ((ind (nth 1 item))
1249 (next-item (cadr (member item struct))))
1250 (when (and next-item (> (nth 1 next-item) ind)) next-item)))
1251
1252 (defun org-list-struct-fix-bul (struct origins)
1253 "Verify and correct bullets for every association in STRUCT.
1254 ORIGINS is the alist of parents. See `org-list-struct-origins'.
1255
1256 This function modifies STRUCT."
1257 (let* (acc
1258 (init-bul (lambda (item)
1259 (let ((counter (nth 3 item))
1260 (bullet (org-list-bullet-string (nth 2 item))))
1261 (cond
1262 ((and (string-match "[0-9]+" bullet) counter)
1263 (replace-match counter nil nil bullet))
1264 ((string-match "[0-9]+" bullet)
1265 (replace-match "1" nil nil bullet))
1266 (t bullet)))))
1267 (set-bul (lambda (item bullet)
1268 (setcdr item (list (nth 1 item) bullet (nth 3 item)))))
1269 (get-bul (lambda (item bullet)
1270 (let* ((counter (nth 3 item)))
1271 (if (and counter (string-match "[0-9]+" bullet))
1272 (replace-match counter nil nil bullet)
1273 bullet))))
1274 (fix-bul
1275 (lambda (item) struct
1276 (let* ((parent (cdr (assq (car item) origins)))
1277 (orig-ref (assq parent acc)))
1278 (if orig-ref
1279 ;; Continuing previous list
1280 (let* ((prev-bul (cdr orig-ref))
1281 (new-bul (funcall get-bul item prev-bul)))
1282 (setcdr orig-ref (org-list-inc-bullet-maybe new-bul))
1283 (funcall set-bul item new-bul))
1284 ;; A new list is starting
1285 (let ((new-bul (funcall init-bul item)))
1286 (funcall set-bul item new-bul)
1287 (setq acc (cons (cons parent
1288 (org-list-inc-bullet-maybe new-bul))
1289 acc))))))))
1290 (mapc fix-bul (cdr struct))))
1291
1292 (defun org-list-struct-fix-ind (struct origins)
1293 "Verify and correct indentation for every association in STRUCT.
1294 ORIGINS is the alist of parents. See `org-list-struct-origins'.
1295
1296 This function modifies STRUCT."
1297 (let* ((headless (cdr struct))
1298 (ancestor (car struct))
1299 (top-ind (+ (nth 1 ancestor) (length (nth 2 ancestor))))
1300 (new-ind
1301 (lambda (item)
1302 (let* ((parent (org-list-struct-get-parent item headless origins)))
1303 (if parent
1304 ;; Indent like parent + length of parent's bullet
1305 (setcdr item (cons (+ (length (nth 2 parent)) (nth 1 parent))
1306 (cddr item)))
1307 ;; If no parent, indent like top-point
1308 (setcdr item (cons top-ind (cddr item))))))))
1309 (mapc new-ind headless)))
1310
1311 (defun org-list-struct-fix-struct (struct origins)
1312 "Return STRUCT with correct bullets and indentation.
1313 ORIGINS is the alist of parents. See `org-list-struct-origins'.
1314
1315 Only elements of STRUCT that have changed are returned."
1316 (let ((old (copy-alist struct)))
1317 (org-list-struct-fix-bul struct origins)
1318 (org-list-struct-fix-ind struct origins)
1319 (delq nil (mapcar (lambda (e) (when (not (equal (pop old) e)) e)) struct))))
1320
1321 (defun org-list-struct-outdent (start end origins)
1322 "Outdent items in a structure.
1323 Items are indented when their key is between START, included, and
1324 END, excluded.
1325
1326 ORIGINS is the alist of parents. See `org-list-struct-origins'.
1327
1328 STRUCT is the concerned structure."
1329 (let* (acc
1330 (out (lambda (cell)
1331 (let* ((item (car cell))
1332 (parent (cdr cell)))
1333 (cond
1334 ;; Item not yet in zone: keep association
1335 ((< item start) cell)
1336 ;; Item out of zone: follow associations in acc
1337 ((>= item end)
1338 (let ((convert (assq parent acc)))
1339 (if convert (cons item (cdr convert)) cell)))
1340 ;; Item has no parent: error
1341 ((<= parent 0)
1342 (error "Cannot outdent top-level items"))
1343 ;; Parent is outdented: keep association
1344 ((>= parent start)
1345 (setq acc (cons (cons parent item) acc)) cell)
1346 (t
1347 ;; Parent isn't outdented: reparent to grand-parent
1348 (let ((grand-parent (cdr (assq parent origins))))
1349 (setq acc (cons (cons parent item) acc))
1350 (cons item grand-parent))))))))
1351 (mapcar out origins)))
1352
1353 (defun org-list-struct-indent (start end origins struct)
1354 "Indent items in a structure.
1355 Items are indented when their key is between START, included, and
1356 END, excluded.
1357
1358 ORIGINS is the alist of parents. See `org-list-struct-origins'.
1359
1360 STRUCT is the concerned structure. It may be modified if
1361 `org-list-demote-modify-bullet' matches bullets between START and
1362 END."
1363 (let* (acc
1364 (orig-rev (reverse origins))
1365 (get-prev-item
1366 (lambda (cell parent)
1367 (car (rassq parent (cdr (memq cell orig-rev))))))
1368 (set-assoc
1369 (lambda (cell)
1370 (setq acc (cons cell acc)) cell))
1371 (change-bullet-maybe
1372 (lambda (item)
1373 (let* ((full-item (assq item struct))
1374 (item-bul (org-trim (nth 2 full-item)))
1375 (new-bul-p (cdr (assoc item-bul org-list-demote-modify-bullet))))
1376 (when new-bul-p
1377 ;; new bullet is stored without space to ensure item
1378 ;; will be modified
1379 (setcdr full-item
1380 (list (nth 1 full-item)
1381 new-bul-p
1382 (nth 3 full-item)))))))
1383 (ind
1384 (lambda (cell)
1385 (let* ((item (car cell))
1386 (parent (cdr cell)))
1387 (cond
1388 ;; Item not yet in zone: keep association
1389 ((< item start) cell)
1390 ((>= item end)
1391 ;; Item out of zone: follow associations in acc
1392 (let ((convert (assq parent acc)))
1393 (if convert (cons item (cdr convert)) cell)))
1394 (t
1395 ;; Item is in zone...
1396 (let ((prev (funcall get-prev-item cell parent)))
1397 ;; Check if bullet needs to be changed
1398 (funcall change-bullet-maybe item)
1399 (cond
1400 ;; First item indented but not parent: error
1401 ((and (or (not prev) (= prev 0)) (< parent start))
1402 (error "Cannot indent the first item of a list"))
1403 ;; First item and parent indented: keep same parent
1404 ((or (not prev) (= prev 0))
1405 (funcall set-assoc cell))
1406 ;; Previous item not indented: reparent to it
1407 ((< prev start)
1408 (funcall set-assoc (cons item prev)))
1409 ;; Previous item indented: reparent like it
1410 (t
1411 (funcall set-assoc (cons item
1412 (cdr (assq prev acc)))))))))))))
1413 (mapcar ind origins)))
1414
1415 (defun org-list-struct-apply-struct (struct bottom)
1416 "Apply modifications to list so it mirrors STRUCT.
1417 BOTTOM is position at list ending.
1418
1419 Initial position is restored after the changes."
1420 (let* ((pos (copy-marker (point)))
1421 (ancestor (caar struct))
1422 (modify
1423 (lambda (item)
1424 (goto-char (car item))
1425 (let* ((new-ind (nth 1 item))
1426 (new-bul (org-list-bullet-string (nth 2 item)))
1427 (old-ind (org-get-indentation))
1428 (old-bul (progn
1429 (looking-at "[ \t]*\\(\\S-+[ \t]*\\)")
1430 (match-string 1)))
1431 (old-body-ind (+ (length old-bul) old-ind))
1432 (new-body-ind (+ (length new-bul) new-ind)))
1433 ;; 1. Shift item's body
1434 (unless (= old-body-ind new-body-ind)
1435 (org-shift-item-indentation
1436 (- new-body-ind old-body-ind) bottom))
1437 ;; 2. Replace bullet
1438 (unless (equal new-bul old-bul)
1439 (save-excursion
1440 (looking-at "[ \t]*\\(\\S-+[ \t]*\\)")
1441 (replace-match new-bul nil nil nil 1)))
1442 ;; 3. Indent item to appropriate column
1443 (unless (= new-ind old-ind)
1444 (delete-region (point-at-bol)
1445 (progn
1446 (skip-chars-forward " \t")
1447 (point)))
1448 (indent-to new-ind)))))
1449 ;; Remove ancestor if it is left.
1450 (struct-to-apply (if (or (not ancestor) (= 0 ancestor))
1451 (cdr struct)
1452 struct)))
1453 ;; Apply changes from bottom to top
1454 (mapc modify (nreverse struct-to-apply))
1455 (goto-char pos)))
1456
1457 ;;; Indentation
1458
1459 (defun org-get-string-indentation (s)
1460 "What indentation has S due to SPACE and TAB at the beginning of the string?"
1461 (let ((n -1) (i 0) (w tab-width) c)
1462 (catch 'exit
1463 (while (< (setq n (1+ n)) (length s))
1464 (setq c (aref s n))
1465 (cond ((= c ?\ ) (setq i (1+ i)))
1466 ((= c ?\t) (setq i (* (/ (+ w i) w) w)))
1467 (t (throw 'exit t)))))
1468 i))
1469
1470 (defun org-shift-item-indentation (delta bottom)
1471 "Shift the indentation in current item by DELTA.
1472 Sub-items are not moved.
1473
1474 BOTTOM is position at list ending."
1475 (save-excursion
1476 (let ((beg (point-at-bol))
1477 (end (org-end-of-item-or-at-child bottom)))
1478 (beginning-of-line (unless (eolp) 0))
1479 (while (> (point) beg)
1480 (when (looking-at "[ \t]*\\S-")
1481 ;; this is not an empty line
1482 (let ((i (org-get-indentation)))
1483 (when (and (> i 0) (> (+ i delta) 0))
1484 (indent-line-to (+ i delta)))))
1485 (beginning-of-line 0)))))
1486
1487 (defun org-outdent-item ()
1488 "Outdent a local list item, but not its children.
1489 If a region is active, all items inside will be moved."
1490 (interactive)
1491 (org-list-indent-item-generic
1492 -1 t (org-list-top-point) (org-list-bottom-point)))
1493
1494 (defun org-indent-item ()
1495 "Indent a local list item, but not its children.
1496 If a region is active, all items inside will be moved."
1497 (interactive)
1498 (org-list-indent-item-generic
1499 1 t (org-list-top-point) (org-list-bottom-point)))
1500
1501 (defun org-outdent-item-tree ()
1502 "Outdent a local list item including its children.
1503 If a region is active, all items inside will be moved."
1504 (interactive)
1505 (org-list-indent-item-generic
1506 -1 nil (org-list-top-point) (org-list-bottom-point)))
1507
1508 (defun org-indent-item-tree ()
1509 "Indent a local list item including its children.
1510 If a region is active, all items inside will be moved."
1511 (interactive)
1512 (org-list-indent-item-generic
1513 1 nil (org-list-top-point) (org-list-bottom-point)))
1514
1515 (defvar org-tab-ind-state)
1516 (defun org-cycle-item-indentation ()
1517 "Cycle levels of indentation of an empty item.
1518 The first run indent the item, if applicable. Subsequents runs
1519 outdent it at meaningful levels in the list. When done, item is
1520 put back at its original position with its original bullet.
1521
1522 Return t at each successful move."
1523 (let ((org-adapt-indentation nil)
1524 (ind (org-get-indentation))
1525 (bottom (and (org-at-item-p) (org-list-bottom-point))))
1526 (when (and (or (org-at-item-description-p)
1527 (org-at-item-checkbox-p)
1528 (org-at-item-p))
1529 ;; Check that item is really empty
1530 (>= (match-end 0) (save-excursion
1531 (org-end-of-item-or-at-child bottom)
1532 (skip-chars-backward " \r\t\n")
1533 (point))))
1534 (setq this-command 'org-cycle-item-indentation)
1535 (let ((top (org-list-top-point)))
1536 ;; When in the middle of the cycle, try to outdent first. If it
1537 ;; fails, and point is still at initial position, indent. Else,
1538 ;; go back to original position.
1539 (if (eq last-command 'org-cycle-item-indentation)
1540 (cond
1541 ((ignore-errors (org-list-indent-item-generic -1 t top bottom)))
1542 ((and (= (org-get-indentation) (car org-tab-ind-state))
1543 (ignore-errors
1544 (org-list-indent-item-generic 1 t top bottom))))
1545 (t (back-to-indentation)
1546 (indent-to-column (car org-tab-ind-state))
1547 (end-of-line)
1548 (org-list-repair (cdr org-tab-ind-state))
1549 ;; Break cycle
1550 (setq this-command 'identity)))
1551 ;; If a cycle is starting, remember indentation and bullet,
1552 ;; then try to indent. If it fails, try to outdent.
1553 (setq org-tab-ind-state (cons ind (org-get-bullet)))
1554 (cond
1555 ((ignore-errors (org-list-indent-item-generic 1 t top bottom)))
1556 ((ignore-errors (org-list-indent-item-generic -1 t top bottom)))
1557 (t (error "Cannot move item")))))
1558 t)))
1559
1560 ;;; Bullets
1561
1562 (defun org-get-bullet ()
1563 "Return the bullet of the item at point.
1564 Assume cursor is at an item."
1565 (save-excursion
1566 (beginning-of-line)
1567 (and (looking-at "[ \t]*\\(\\S-+\\)") (match-string 1))))
1568
1569 (defun org-list-bullet-string (bullet)
1570 "Return BULLET with the correct number of whitespaces.
1571 It determines the number of whitespaces to append by looking at
1572 `org-list-two-spaces-after-bullet-regexp'."
1573 (save-match-data
1574 (string-match "\\S-+\\([ \t]*\\)" bullet)
1575 (replace-match
1576 (save-match-data
1577 (concat
1578 " "
1579 ;; Do we need to concat another white space ?
1580 (when (and org-list-two-spaces-after-bullet-regexp
1581 (string-match org-list-two-spaces-after-bullet-regexp bullet))
1582 " ")))
1583 nil nil bullet 1)))
1584
1585 (defun org-list-inc-bullet-maybe (bullet)
1586 "Increment BULLET if applicable."
1587 (if (string-match "[0-9]+" bullet)
1588 (replace-match
1589 (number-to-string (1+ (string-to-number (match-string 0 bullet))))
1590 nil nil bullet)
1591 bullet))
1592
1593 (defun org-list-repair (&optional force-bullet top bottom)
1594 "Make sure all items are correctly indented, with the right bullet.
1595 This function scans the list at point, along with any sublist.
1596
1597 If FORCE-BULLET is a string, ensure all items in list share this
1598 bullet, or a logical successor in the case of an ordered list.
1599
1600 When non-nil, TOP and BOTTOM specify respectively position of
1601 list beginning and list ending.
1602
1603 Item's body is not indented, only shifted with the bullet."
1604 (interactive)
1605 (unless (org-at-item-p) (error "This is not a list"))
1606 (let* ((bottom (or bottom (org-list-bottom-point)))
1607 (struct (org-list-struct
1608 (point-at-bol) (point-at-eol)
1609 (or top (org-list-top-point)) bottom))
1610 (origins (org-list-struct-origins struct))
1611 fixed-struct)
1612 (if (stringp force-bullet)
1613 (let ((begin (nth 1 struct)))
1614 (setcdr begin (list (nth 1 begin)
1615 (org-list-bullet-string force-bullet)
1616 (nth 3 begin)))
1617 (setq fixed-struct
1618 (cons begin (org-list-struct-fix-struct struct origins))))
1619 (setq fixed-struct (org-list-struct-fix-struct struct origins)))
1620 (org-list-struct-apply-struct fixed-struct bottom)))
1621
1622 (defun org-cycle-list-bullet (&optional which)
1623 "Cycle through the different itemize/enumerate bullets.
1624 This cycle the entire list level through the sequence:
1625
1626 `-' -> `+' -> `*' -> `1.' -> `1)'
1627
1628 If WHICH is a valid string, use that as the new bullet. If WHICH
1629 is an integer, 0 means `-', 1 means `+' etc. If WHICH is
1630 'previous, cycle backwards."
1631 (interactive "P")
1632 (let* ((top (org-list-top-point))
1633 (bullet (save-excursion
1634 (goto-char (org-get-beginning-of-list top))
1635 (org-get-bullet)))
1636 (current (cond
1637 ((string-match "\\." bullet) "1.")
1638 ((string-match ")" bullet) "1)")
1639 (t bullet)))
1640 (bullet-rule-p (cdr (assq 'bullet org-list-automatic-rules)))
1641 (bullet-list (append '("-" "+" )
1642 ;; *-bullets are not allowed at column 0
1643 (unless (and bullet-rule-p
1644 (looking-at "\\S-")) '("*"))
1645 ;; Description items cannot be numbered
1646 (unless (and bullet-rule-p
1647 (or (eq org-plain-list-ordered-item-terminator ?\))
1648 (org-at-item-description-p))) '("1."))
1649 (unless (and bullet-rule-p
1650 (or (eq org-plain-list-ordered-item-terminator ?.)
1651 (org-at-item-description-p))) '("1)"))))
1652 (len (length bullet-list))
1653 (item-index (- len (length (member current bullet-list))))
1654 (get-value (lambda (index) (nth (mod index len) bullet-list)))
1655 (new (cond
1656 ((member which bullet-list) which)
1657 ((numberp which) (funcall get-value which))
1658 ((eq 'previous which) (funcall get-value (1- item-index)))
1659 (t (funcall get-value (1+ item-index))))))
1660 (org-list-repair new top)))
1661
1662 ;;; Checkboxes
1663
1664 (defun org-toggle-checkbox (&optional toggle-presence)
1665 "Toggle the checkbox in the current line.
1666 With prefix arg TOGGLE-PRESENCE, add or remove checkboxes. With
1667 double prefix, set checkbox to [-].
1668
1669 When there is an active region, toggle status or presence of the
1670 first checkbox there, and make every item inside have the
1671 same status or presence, respectively.
1672
1673 If the cursor is in a headline, apply this to all checkbox items
1674 in the text below the heading, taking as reference the first item
1675 in subtree, ignoring drawers."
1676 (interactive "P")
1677 ;; Bounds is a list of type (beg end single-p) where single-p is t
1678 ;; when `org-toggle-checkbox' is applied to a single item. Only
1679 ;; toggles on single items will return errors.
1680 (let* ((bounds
1681 (cond
1682 ((org-region-active-p)
1683 (let ((rbeg (region-beginning))
1684 (rend (region-end)))
1685 (save-excursion
1686 (goto-char rbeg)
1687 (if (org-search-forward-unenclosed org-item-beginning-re rend 'move)
1688 (list (point-at-bol) rend nil)
1689 (error "No item in region")))))
1690 ((org-on-heading-p)
1691 ;; In this case, reference line is the first item in
1692 ;; subtree outside drawers
1693 (let ((pos (point))
1694 (limit (save-excursion (outline-next-heading) (point))))
1695 (save-excursion
1696 (goto-char limit)
1697 (org-search-backward-unenclosed ":END:" pos 'move)
1698 (org-search-forward-unenclosed
1699 org-item-beginning-re limit 'move)
1700 (list (point) limit nil))))
1701 ((org-at-item-p)
1702 (list (point-at-bol) (1+ (point-at-eol)) t))
1703 (t (error "Not at an item or heading, and no active region"))))
1704 (beg (car bounds))
1705 ;; marker is needed because deleting or inserting checkboxes
1706 ;; will change bottom point
1707 (end (copy-marker (nth 1 bounds)))
1708 (single-p (nth 2 bounds))
1709 (ref-presence (save-excursion
1710 (goto-char beg)
1711 (org-at-item-checkbox-p)))
1712 (ref-status (equal (match-string 1) "[X]"))
1713 (act-on-item
1714 (lambda (ref-pres ref-stat)
1715 (if (equal toggle-presence '(4))
1716 (cond
1717 ((and ref-pres (org-at-item-checkbox-p))
1718 (replace-match ""))
1719 ((and (not ref-pres)
1720 (not (org-at-item-checkbox-p))
1721 (org-at-item-p))
1722 (goto-char (match-end 0))
1723 ;; Ignore counter, if any
1724 (when (looking-at "\\(?:\\[@\\(?:start:\\)?[0-9]+\\][ \t]*\\)?")
1725 (goto-char (match-end 0)))
1726 (let ((desc-p (and (org-at-item-description-p)
1727 (cdr (assq 'checkbox org-list-automatic-rules)))))
1728 (cond
1729 ((and single-p desc-p)
1730 (error "Cannot add a checkbox in a description list"))
1731 ((not desc-p) (insert "[ ] "))))))
1732 (let ((blocked (org-checkbox-blocked-p)))
1733 (cond
1734 ((and blocked single-p)
1735 (error "Checkbox blocked because of unchecked box in line %d" blocked))
1736 (blocked nil)
1737 ((org-at-item-checkbox-p)
1738 (replace-match
1739 (cond ((equal toggle-presence '(16)) "[-]")
1740 (ref-stat "[ ]")
1741 (t "[X]"))
1742 t t nil 1))))))))
1743 (save-excursion
1744 (goto-char beg)
1745 (while (< (point) end)
1746 (funcall act-on-item ref-presence ref-status)
1747 (org-search-forward-unenclosed org-item-beginning-re end 'move)))
1748 (org-update-checkbox-count-maybe)))
1749
1750 (defun org-reset-checkbox-state-subtree ()
1751 "Reset all checkboxes in an entry subtree."
1752 (interactive "*")
1753 (save-restriction
1754 (save-excursion
1755 (org-narrow-to-subtree)
1756 (org-show-subtree)
1757 (goto-char (point-min))
1758 (let ((end (point-max)))
1759 (while (< (point) end)
1760 (when (org-at-item-checkbox-p)
1761 (replace-match "[ ]" t t nil 1))
1762 (beginning-of-line 2))))
1763 (org-update-checkbox-count-maybe)))
1764
1765 (defvar org-checkbox-statistics-hook nil
1766 "Hook that is run whenever Org thinks checkbox statistics should be updated.
1767 This hook runs even if checkbox rule in
1768 `org-list-automatic-rules' does not apply, so it can be used to
1769 implement alternative ways of collecting statistics
1770 information.")
1771
1772 (defun org-update-checkbox-count-maybe ()
1773 "Update checkbox statistics unless turned off by user."
1774 (when (cdr (assq 'checkbox org-list-automatic-rules))
1775 (org-update-checkbox-count))
1776 (run-hooks 'org-checkbox-statistics-hook))
1777
1778 (defun org-update-checkbox-count (&optional all)
1779 "Update the checkbox statistics in the current section.
1780 This will find all statistic cookies like [57%] and [6/12] and update them
1781 with the current numbers. With optional prefix argument ALL, do this for
1782 the whole buffer."
1783 (interactive "P")
1784 (save-excursion
1785 (let ((cstat 0))
1786 (catch 'exit
1787 (while t
1788 (let* ((buffer-invisibility-spec (org-inhibit-invisibility)) ; Emacs 21
1789 (beg (condition-case nil
1790 (progn (org-back-to-heading) (point))
1791 (error (point-min))))
1792 (end (copy-marker (save-excursion
1793 (outline-next-heading) (point))))
1794 (re-cookie "\\(\\(\\[[0-9]*%\\]\\)\\|\\(\\[[0-9]*/[0-9]*\\]\\)\\)")
1795 (re-box "^[ \t]*\\([-+*]\\|[0-9]+[.)]\\)[ \t]+\\(?:\\[@\\(?:start:\\)?[0-9]+\\][ \t]*\\)?\\(\\[[- X]\\]\\)")
1796 beg-cookie end-cookie is-percent c-on c-off lim new
1797 curr-ind next-ind continue-from startsearch list-beg list-end
1798 (recursive
1799 (or (not org-hierarchical-checkbox-statistics)
1800 (string-match "\\<recursive\\>"
1801 (or (ignore-errors
1802 (org-entry-get nil "COOKIE_DATA"))
1803 "")))))
1804 (goto-char end)
1805 ;; find each statistics cookie
1806 (while (and (org-search-backward-unenclosed re-cookie beg 'move)
1807 (not (save-match-data
1808 (and (org-on-heading-p)
1809 (string-match "\\<todo\\>"
1810 (downcase
1811 (or (org-entry-get
1812 nil "COOKIE_DATA")
1813 "")))))))
1814 (setq beg-cookie (match-beginning 1)
1815 end-cookie (match-end 1)
1816 cstat (+ cstat (if end-cookie 1 0))
1817 startsearch (point-at-eol)
1818 continue-from (match-beginning 0)
1819 is-percent (match-beginning 2)
1820 lim (cond
1821 ((org-on-heading-p) (outline-next-heading) (point))
1822 ;; Ensure many cookies in the same list won't imply
1823 ;; computing list boundaries as many times.
1824 ((org-at-item-p)
1825 (unless (and list-beg (>= (point) list-beg))
1826 (setq list-beg (org-list-top-point)
1827 list-end (copy-marker
1828 (org-list-bottom-point))))
1829 (org-get-end-of-item list-end))
1830 (t nil))
1831 c-on 0
1832 c-off 0)
1833 (when lim
1834 ;; find first checkbox for this cookie and gather
1835 ;; statistics from all that are at this indentation level
1836 (goto-char startsearch)
1837 (if (org-search-forward-unenclosed re-box lim t)
1838 (progn
1839 (beginning-of-line)
1840 (setq curr-ind (org-get-indentation))
1841 (setq next-ind curr-ind)
1842 (while (and (bolp) (org-at-item-p)
1843 (if recursive
1844 (<= curr-ind next-ind)
1845 (= curr-ind next-ind)))
1846 (when (org-at-item-checkbox-p)
1847 (if (member (match-string 1) '("[ ]" "[-]"))
1848 (setq c-off (1+ c-off))
1849 (setq c-on (1+ c-on))))
1850 (if (not recursive)
1851 ;; org-get-next-item goes through list-enders
1852 ;; with proper limit.
1853 (goto-char (or (org-get-next-item (point) lim) lim))
1854 (end-of-line)
1855 (when (org-search-forward-unenclosed
1856 org-item-beginning-re lim t)
1857 (beginning-of-line)))
1858 (setq next-ind (org-get-indentation)))))
1859 (goto-char continue-from)
1860 ;; update cookie
1861 (when end-cookie
1862 (setq new (if is-percent
1863 (format "[%d%%]" (/ (* 100 c-on)
1864 (max 1 (+ c-on c-off))))
1865 (format "[%d/%d]" c-on (+ c-on c-off))))
1866 (goto-char beg-cookie)
1867 (insert new)
1868 (delete-region (point) (+ (point) (- end-cookie beg-cookie))))
1869 ;; update items checkbox if it has one
1870 (when (and (org-at-item-checkbox-p)
1871 (> (+ c-on c-off) 0))
1872 (setq beg-cookie (match-beginning 1)
1873 end-cookie (match-end 1))
1874 (delete-region beg-cookie end-cookie)
1875 (goto-char beg-cookie)
1876 (cond ((= c-off 0) (insert "[X]"))
1877 ((= c-on 0) (insert "[ ]"))
1878 (t (insert "[-]")))))
1879 (goto-char continue-from)))
1880 (unless (and all (outline-next-heading)) (throw 'exit nil))))
1881 (when (interactive-p)
1882 (message "Checkbox statistics updated %s (%d places)"
1883 (if all "in entire file" "in current outline entry") cstat)))))
1884
1885 (defun org-get-checkbox-statistics-face ()
1886 "Select the face for checkbox statistics.
1887 The face will be `org-done' when all relevant boxes are checked.
1888 Otherwise it will be `org-todo'."
1889 (if (match-end 1)
1890 (if (equal (match-string 1) "100%")
1891 'org-checkbox-statistics-done
1892 'org-checkbox-statistics-todo)
1893 (if (and (> (match-end 2) (match-beginning 2))
1894 (equal (match-string 2) (match-string 3)))
1895 'org-checkbox-statistics-done
1896 'org-checkbox-statistics-todo)))
1897
1898 ;;; Misc Tools
1899
1900 (defun org-apply-on-list (function init-value &rest args)
1901 "Call FUNCTION on each item of the list at point.
1902 FUNCTION must be called with at least one argument: INIT-VALUE,
1903 that will contain the value returned by the function at the
1904 previous item, plus ARGS extra arguments.
1905
1906 As an example, (org-apply-on-list (lambda (result) (1+ result)) 0)
1907 will return the number of items in the current list.
1908
1909 Sublists of the list are skipped. Cursor is always at the
1910 beginning of the item."
1911 (let* ((pos (copy-marker (point)))
1912 (end (copy-marker (org-list-bottom-point)))
1913 (next-p (copy-marker (org-get-beginning-of-list (org-list-top-point))))
1914 (value init-value))
1915 (while (< next-p end)
1916 (goto-char next-p)
1917 (set-marker next-p (or (org-get-next-item (point) end) end))
1918 (setq value (apply function value args)))
1919 (goto-char pos)
1920 value))
1921
1922 (defun org-sort-list (&optional with-case sorting-type getkey-func compare-func)
1923 "Sort plain list items.
1924 The cursor may be at any item of the list that should be sorted.
1925 Sublists are not sorted. Checkboxes, if any, are ignored.
1926
1927 Sorting can be alphabetically, numerically, by date/time as given by
1928 a time stamp, by a property or by priority.
1929
1930 Comparing entries ignores case by default. However, with an
1931 optional argument WITH-CASE, the sorting considers case as well.
1932
1933 The command prompts for the sorting type unless it has been given
1934 to the function through the SORTING-TYPE argument, which needs to
1935 be a character, \(?n ?N ?a ?A ?t ?T ?f ?F). Here is the precise
1936 meaning of each character:
1937
1938 n Numerically, by converting the beginning of the item to a number.
1939 a Alphabetically. Only the first line of item is checked.
1940 t By date/time, either the first active time stamp in the entry, if
1941 any, or by the first inactive one. In a timer list, sort the timers.
1942
1943 Capital letters will reverse the sort order.
1944
1945 If the SORTING-TYPE is ?f or ?F, then GETKEY-FUNC specifies a
1946 function to be called with point at the beginning of the record.
1947 It must return either a string or a number that should serve as
1948 the sorting key for that record. It will then use COMPARE-FUNC to
1949 compare entries."
1950 (interactive "P")
1951 (let* ((case-func (if with-case 'identity 'downcase))
1952 (top (org-list-top-point))
1953 (bottom (org-list-bottom-point))
1954 (start (org-get-beginning-of-list top))
1955 (end (org-get-end-of-list bottom))
1956 (sorting-type
1957 (progn
1958 (message
1959 "Sort plain list: [a]lpha [n]umeric [t]ime [f]unc A/N/T/F means reversed:")
1960 (read-char-exclusive)))
1961 (getkey-func (and (= (downcase sorting-type) ?f)
1962 (org-icompleting-read "Sort using function: "
1963 obarray 'fboundp t nil nil)
1964 (intern getkey-func))))
1965 (message "Sorting items...")
1966 (save-restriction
1967 (narrow-to-region start end)
1968 (goto-char (point-min))
1969 (let* ((dcst (downcase sorting-type))
1970 (case-fold-search nil)
1971 (now (current-time))
1972 (sort-func (cond
1973 ((= dcst ?a) 'string<)
1974 ((= dcst ?f) compare-func)
1975 ((= dcst ?t) '<)
1976 (t nil)))
1977 (begin-record (lambda ()
1978 (skip-chars-forward " \r\t\n")
1979 (beginning-of-line)))
1980 (end-record (lambda ()
1981 (goto-char (org-end-of-item-before-blank end))))
1982 (value-to-sort
1983 (lambda ()
1984 (when (looking-at "[ \t]*[-+*0-9.)]+\\([ \t]+\\[[- X]\\]\\)?[ \t]+")
1985 (cond
1986 ((= dcst ?n)
1987 (string-to-number (buffer-substring (match-end 0)
1988 (point-at-eol))))
1989 ((= dcst ?a)
1990 (buffer-substring (match-end 0) (point-at-eol)))
1991 ((= dcst ?t)
1992 (cond
1993 ;; If it is a timer list, convert timer to seconds
1994 ((org-at-item-timer-p)
1995 (org-timer-hms-to-secs (match-string 1)))
1996 ((or (org-search-forward-unenclosed org-ts-regexp
1997 (point-at-eol) t)
1998 (org-search-forward-unenclosed org-ts-regexp-both
1999 (point-at-eol) t))
2000 (org-time-string-to-seconds (match-string 0)))
2001 (t (org-float-time now))))
2002 ((= dcst ?f)
2003 (if getkey-func
2004 (let ((value (funcall getkey-func)))
2005 (if (stringp value)
2006 (funcall case-func value)
2007 value))
2008 (error "Invalid key function `%s'" getkey-func)))
2009 (t (error "Invalid sorting type `%c'" sorting-type)))))))
2010 (sort-subr (/= dcst sorting-type)
2011 begin-record
2012 end-record
2013 value-to-sort
2014 nil
2015 sort-func)
2016 (org-list-repair nil top bottom)
2017 (run-hooks 'org-after-sorting-entries-or-items-hook)
2018 (message "Sorting items...done")))))
2019
2020 ;;; Send and receive lists
2021
2022 (defun org-list-parse-list (&optional delete)
2023 "Parse the list at point and maybe DELETE it.
2024 Return a list containing first level items as strings and
2025 sublevels as a list of strings."
2026 (let* ((start (goto-char (org-list-top-point)))
2027 (end (org-list-bottom-point))
2028 output itemsep ltype)
2029 (while (org-search-forward-unenclosed org-item-beginning-re end t)
2030 (save-excursion
2031 (beginning-of-line)
2032 (setq ltype (cond ((looking-at-p "^[ \t]*[0-9]") 'ordered)
2033 ((org-at-item-description-p) 'descriptive)
2034 (t 'unordered))))
2035 (let* ((indent1 (org-get-indentation))
2036 (nextitem (or (org-get-next-item (point) end) end))
2037 (item (org-trim (buffer-substring (point)
2038 (org-end-of-item-or-at-child end))))
2039 (nextindent (if (= (point) end) 0 (org-get-indentation)))
2040 (item (if (string-match
2041 "^\\(?:\\[@\\(?:start:\\)?[0-9]+\\][ \t]*\\)?\\[\\([xX ]\\)\\]"
2042 item)
2043 (replace-match (if (equal (match-string 1 item) " ")
2044 "CBOFF"
2045 "CBON")
2046 t nil item 1)
2047 item)))
2048 (push item output)
2049 (when (> nextindent indent1)
2050 (save-restriction
2051 (narrow-to-region (point) nextitem)
2052 (push (org-list-parse-list) output)))))
2053 (when delete
2054 (delete-region start end)
2055 (save-match-data
2056 (when (and (not (eq org-list-ending-method 'indent))
2057 (looking-at (org-list-end-re)))
2058 (replace-match "\n"))))
2059 (setq output (nreverse output))
2060 (push ltype output)))
2061
2062 (defun org-list-make-subtree ()
2063 "Convert the plain list at point into a subtree."
2064 (interactive)
2065 (if (not (org-in-item-p))
2066 (error "Not in a list")
2067 (let ((list (org-list-parse-list t)) nstars)
2068 (save-excursion
2069 (if (ignore-errors
2070 (org-back-to-heading))
2071 (progn (looking-at org-complex-heading-regexp)
2072 (setq nstars (length (match-string 1))))
2073 (setq nstars 0)))
2074 (org-list-make-subtrees list (1+ nstars)))))
2075
2076 (defun org-list-make-subtrees (list level)
2077 "Convert LIST into subtrees starting at LEVEL."
2078 (if (symbolp (car list))
2079 (org-list-make-subtrees (cdr list) level)
2080 (mapcar (lambda (item)
2081 (if (stringp item)
2082 (insert (make-string
2083 (if org-odd-levels-only
2084 (1- (* 2 level)) level) ?*) " " item "\n")
2085 (org-list-make-subtrees item (1+ level))))
2086 list)))
2087
2088 (defun org-list-insert-radio-list ()
2089 "Insert a radio list template appropriate for this major mode."
2090 (interactive)
2091 (let* ((e (assq major-mode org-list-radio-list-templates))
2092 (txt (nth 1 e))
2093 name pos)
2094 (unless e (error "No radio list setup defined for %s" major-mode))
2095 (setq name (read-string "List name: "))
2096 (while (string-match "%n" txt)
2097 (setq txt (replace-match name t t txt)))
2098 (or (bolp) (insert "\n"))
2099 (setq pos (point))
2100 (insert txt)
2101 (goto-char pos)))
2102
2103 (defun org-list-send-list (&optional maybe)
2104 "Send a transformed version of this list to the receiver position.
2105 With argument MAYBE, fail quietly if no transformation is defined for
2106 this list."
2107 (interactive)
2108 (catch 'exit
2109 (unless (org-at-item-p) (error "Not at a list item"))
2110 (save-excursion
2111 (re-search-backward "#\\+ORGLST" nil t)
2112 (unless (looking-at "[ \t]*#\\+ORGLST[: \t][ \t]*SEND[ \t]+\\([^ \t\r\n]+\\)[ \t]+\\([^ \t\r\n]+\\)\\([ \t]+.*\\)?")
2113 (if maybe
2114 (throw 'exit nil)
2115 (error "Don't know how to transform this list"))))
2116 (let* ((name (match-string 1))
2117 (transform (intern (match-string 2)))
2118 (bottom-point
2119 (save-excursion
2120 (re-search-forward
2121 "\\(\\\\end{comment}\\|@end ignore\\|-->\\)" nil t)
2122 (match-beginning 0)))
2123 (top-point
2124 (progn
2125 (re-search-backward "#\\+ORGLST" nil t)
2126 (re-search-forward org-item-beginning-re bottom-point t)
2127 (match-beginning 0)))
2128 (list (save-restriction
2129 (narrow-to-region top-point bottom-point)
2130 (org-list-parse-list)))
2131 beg txt)
2132 (unless (fboundp transform)
2133 (error "No such transformation function %s" transform))
2134 (let ((txt (funcall transform list)))
2135 ;; Find the insertion place
2136 (save-excursion
2137 (goto-char (point-min))
2138 (unless (re-search-forward
2139 (concat "BEGIN RECEIVE ORGLST +"
2140 name
2141 "\\([ \t]\\|$\\)") nil t)
2142 (error "Don't know where to insert translated list"))
2143 (goto-char (match-beginning 0))
2144 (beginning-of-line 2)
2145 (setq beg (point))
2146 (unless (re-search-forward (concat "END RECEIVE ORGLST +" name) nil t)
2147 (error "Cannot find end of insertion region"))
2148 (delete-region beg (point-at-bol))
2149 (goto-char beg)
2150 (insert txt "\n")))
2151 (message "List converted and installed at receiver location"))))
2152
2153 (defun org-list-to-generic (list params)
2154 "Convert a LIST parsed through `org-list-parse-list' to other formats.
2155 Valid parameters PARAMS are
2156
2157 :ustart String to start an unordered list
2158 :uend String to end an unordered list
2159
2160 :ostart String to start an ordered list
2161 :oend String to end an ordered list
2162
2163 :dstart String to start a descriptive list
2164 :dend String to end a descriptive list
2165 :dtstart String to start a descriptive term
2166 :dtend String to end a descriptive term
2167 :ddstart String to start a description
2168 :ddend String to end a description
2169
2170 :splice When set to t, return only list body lines, don't wrap
2171 them into :[u/o]start and :[u/o]end. Default is nil.
2172
2173 :istart String to start a list item
2174 :iend String to end a list item
2175 :isep String to separate items
2176 :lsep String to separate sublists
2177
2178 :cboff String to insert for an unchecked checkbox
2179 :cbon String to insert for a checked checkbox"
2180 (interactive)
2181 (let* ((p params) sublist
2182 (splicep (plist-get p :splice))
2183 (ostart (plist-get p :ostart))
2184 (oend (plist-get p :oend))
2185 (ustart (plist-get p :ustart))
2186 (uend (plist-get p :uend))
2187 (dstart (plist-get p :dstart))
2188 (dend (plist-get p :dend))
2189 (dtstart (plist-get p :dtstart))
2190 (dtend (plist-get p :dtend))
2191 (ddstart (plist-get p :ddstart))
2192 (ddend (plist-get p :ddend))
2193 (istart (plist-get p :istart))
2194 (iend (plist-get p :iend))
2195 (isep (plist-get p :isep))
2196 (lsep (plist-get p :lsep))
2197 (cbon (plist-get p :cbon))
2198 (cboff (plist-get p :cboff)))
2199 (let ((wrapper
2200 (cond ((eq (car list) 'ordered)
2201 (concat ostart "\n%s" oend "\n"))
2202 ((eq (car list) 'unordered)
2203 (concat ustart "\n%s" uend "\n"))
2204 ((eq (car list) 'descriptive)
2205 (concat dstart "\n%s" dend "\n"))))
2206 rtn term defstart defend)
2207 (while (setq sublist (pop list))
2208 (cond ((symbolp sublist) nil)
2209 ((stringp sublist)
2210 (when (string-match "^\\(.*\\)[ \t]+::" sublist)
2211 (setq term (org-trim (format (concat dtstart "%s" dtend)
2212 (match-string 1 sublist))))
2213 (setq sublist (concat ddstart
2214 (org-trim (substring sublist
2215 (match-end 0)))
2216 ddend)))
2217 (if (string-match "\\[CBON\\]" sublist)
2218 (setq sublist (replace-match cbon t t sublist)))
2219 (if (string-match "\\[CBOFF\\]" sublist)
2220 (setq sublist (replace-match cboff t t sublist)))
2221 (if (string-match "\\[-\\]" sublist)
2222 (setq sublist (replace-match "$\\boxminus$" t t sublist)))
2223 (setq rtn (concat rtn istart term sublist iend isep)))
2224 (t (setq rtn (concat rtn ;; previous list
2225 lsep ;; list separator
2226 (org-list-to-generic sublist p)
2227 lsep ;; list separator
2228 )))))
2229 (format wrapper rtn))))
2230
2231 (defun org-list-to-latex (list &optional params)
2232 "Convert LIST into a LaTeX list.
2233 LIST is as returned by `org-list-parse-list'. PARAMS is a property list
2234 with overruling parameters for `org-list-to-generic'."
2235 (org-list-to-generic
2236 list
2237 (org-combine-plists
2238 '(:splicep nil :ostart "\\begin{enumerate}" :oend "\\end{enumerate}"
2239 :ustart "\\begin{itemize}" :uend "\\end{itemize}"
2240 :dstart "\\begin{description}" :dend "\\end{description}"
2241 :dtstart "[" :dtend "]"
2242 :ddstart "" :ddend ""
2243 :istart "\\item " :iend ""
2244 :isep "\n" :lsep "\n"
2245 :cbon "\\texttt{[X]}" :cboff "\\texttt{[ ]}")
2246 params)))
2247
2248 (defun org-list-to-html (list &optional params)
2249 "Convert LIST into a HTML list.
2250 LIST is as returned by `org-list-parse-list'. PARAMS is a property list
2251 with overruling parameters for `org-list-to-generic'."
2252 (org-list-to-generic
2253 list
2254 (org-combine-plists
2255 '(:splicep nil :ostart "<ol>" :oend "</ol>"
2256 :ustart "<ul>" :uend "</ul>"
2257 :dstart "<dl>" :dend "</dl>"
2258 :dtstart "<dt>" :dtend "</dt>"
2259 :ddstart "<dd>" :ddend "</dd>"
2260 :istart "<li>" :iend "</li>"
2261 :isep "\n" :lsep "\n"
2262 :cbon "<code>[X]</code>" :cboff "<code>[ ]</code>")
2263 params)))
2264
2265 (defun org-list-to-texinfo (list &optional params)
2266 "Convert LIST into a Texinfo list.
2267 LIST is as returned by `org-list-parse-list'. PARAMS is a property list
2268 with overruling parameters for `org-list-to-generic'."
2269 (org-list-to-generic
2270 list
2271 (org-combine-plists
2272 '(:splicep nil :ostart "@itemize @minus" :oend "@end itemize"
2273 :ustart "@enumerate" :uend "@end enumerate"
2274 :dstart "@table" :dend "@end table"
2275 :dtstart "@item " :dtend "\n"
2276 :ddstart "" :ddend ""
2277 :istart "@item\n" :iend ""
2278 :isep "\n" :lsep "\n"
2279 :cbon "@code{[X]}" :cboff "@code{[ ]}")
2280 params)))
2281
2282 (provide 'org-list)
2283
2284 ;; arch-tag: 73cf50c1-200f-4d1d-8a53-4e842a5b11c8
2285 ;;; org-list.el ends here