org-list: small corrections to sort list
[org-mode/org-mode-NeilSmithlineMods.git] / lisp / org-list.el
blob4485a423f3497e13f5ce5fea6e05159252292bf9
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.4
12 ;; This file is part of GNU Emacs.
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.
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.
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 ;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;
28 ;;; Commentary:
30 ;; This file contains the code dealing with plain lists in Org-mode.
32 ;; The fundamental idea behind lists work is to use structures. A
33 ;; structure is a snapshot of the list, in the shape of data tree (see
34 ;; `org-list-struct').
36 ;; Once the list structure is stored, it is possible to make changes
37 ;; directly on it or get useful information on the list, with helper
38 ;; functions `org-list-struct-parent-alist' and
39 ;; `org-list-struct-prev-alist', and using accessors provided in the
40 ;; file.
42 ;; Structure is repaired with `org-list-struct-fix-struct'. Then
43 ;; changes are applied to buffer with `org-list-struct-apply-struct'.
45 ;; So any function working on plain lists should follow this template:
46 ;; 1. Verify point is in a list and grab item beginning (with the same
47 ;; function `org-in-item-p') ;
48 ;; 2. Get list structure ;
49 ;; 3. Compute one, or both, helper functions depending on required
50 ;; accessors ;
51 ;; 4. Proceed with the modifications ;
52 ;; 5. Then fix the structure one last time and apply it on buffer.
54 ;; It is usally a bad idea to use directly an interactive function
55 ;; inside a function, as those read the whole list structure another
56 ;; time.
58 ;;; Code:
60 (eval-when-compile
61 (require 'cl))
62 (require 'org-macs)
63 (require 'org-compat)
65 (defvar org-blank-before-new-entry)
66 (defvar org-M-RET-may-split-line)
67 (defvar org-complex-heading-regexp)
68 (defvar org-odd-levels-only)
69 (defvar org-outline-regexp)
70 (defvar org-ts-regexp)
71 (defvar org-ts-regexp-both)
73 (declare-function org-at-heading-p "org" (&optional ignored))
74 (declare-function org-back-over-empty-lines "org" ())
75 (declare-function org-back-to-heading "org" (&optional invisible-ok))
76 (declare-function org-combine-plists "org" (&rest plists))
77 (declare-function org-entry-get "org"
78 (pom property &optional inherit literal-nil))
79 (declare-function org-get-indentation "org" (&optional line))
80 (declare-function org-icompleting-read "org" (&rest args))
81 (declare-function org-in-regexps-block-p "org"
82 (start-re end-re &optional bound))
83 (declare-function org-inlinetask-goto-beginning "org-inlinetask" ())
84 (declare-function org-inlinetask-goto-end "org-inlinetask" ())
85 (declare-function org-inlinetask-in-task-p "org-inlinetask" ())
86 (declare-function org-invisible-p "org" ())
87 (declare-function org-level-increment "org" ())
88 (declare-function org-narrow-to-subtree "org" ())
89 (declare-function org-on-heading-p "org" (&optional invisible-ok))
90 (declare-function org-remove-if "org" (predicate seq))
91 (declare-function org-show-subtree "org" ())
92 (declare-function org-time-string-to-seconds "org" (s))
93 (declare-function org-timer-hms-to-secs "org-timer" (hms))
94 (declare-function org-timer-item "org-timer" (&optional arg))
95 (declare-function org-trim "org" (s))
96 (declare-function org-uniquify "org" (list))
97 (declare-function outline-next-heading "outline" ())
98 (declare-function outline-previous-heading "outline" ())
100 (defgroup org-plain-lists nil
101 "Options concerning plain lists in Org-mode."
102 :tag "Org Plain lists"
103 :group 'org-structure)
105 (defcustom org-cycle-include-plain-lists t
106 "When t, make TAB cycle visibility on plain list items.
107 Cycling plain lists works only when the cursor is on a plain list
108 item. When the cursor is on an outline heading, plain lists are
109 treated as text. This is the most stable way of handling this,
110 which is why it is the default.
112 When this is the symbol `integrate', then during cycling, plain
113 list items will *temporarily* be interpreted as outline headlines
114 with a level given by 1000+i where i is the indentation of the
115 bullet. This setting can lead to strange effects when switching
116 visibility to `children', because the first \"child\" in a
117 subtree decides what children should be listed. If that first
118 \"child\" is a plain list item with an implied large level
119 number, all true children and grand children of the outline
120 heading will be exposed in a children' view."
121 :group 'org-plain-lists
122 :type '(choice
123 (const :tag "Never" nil)
124 (const :tag "With cursor in plain list (recommended)" t)
125 (const :tag "As children of outline headings" integrate)))
127 (defcustom org-list-demote-modify-bullet nil
128 "Default bullet type installed when demoting an item.
129 This is an association list, for each bullet type, this alist will point
130 to the bullet that should be used when this item is demoted.
131 For example,
133 (setq org-list-demote-modify-bullet
134 '((\"+\" . \"-\") (\"-\" . \"+\") (\"*\" . \"+\")))
136 will make
138 + Movies
139 + Silence of the Lambs
140 + My Cousin Vinny
141 + Books
142 + The Hunt for Red October
143 + The Road to Omaha
145 into
147 + Movies
148 - Silence of the Lambs
149 - My Cousin Vinny
150 + Books
151 - The Hunt for Red October
152 - The Road to Omaha"
153 :group 'org-plain-lists
154 :type '(repeat
155 (cons
156 (choice :tag "If the current bullet is "
157 (const "-")
158 (const "+")
159 (const "*")
160 (const "1.")
161 (const "1)"))
162 (choice :tag "demotion will change it to"
163 (const "-")
164 (const "+")
165 (const "*")
166 (const "1.")
167 (const "1)")))))
169 (defcustom org-plain-list-ordered-item-terminator t
170 "The character that makes a line with leading number an ordered list item.
171 Valid values are ?. and ?\). To get both terminators, use t. While
172 ?. may look nicer, it creates the danger that a line with leading
173 number may be incorrectly interpreted as an item. ?\) therefore is
174 the safe choice."
175 :group 'org-plain-lists
176 :type '(choice (const :tag "dot like in \"2.\"" ?.)
177 (const :tag "paren like in \"2)\"" ?\))
178 (const :tab "both" t)))
180 (defcustom org-list-two-spaces-after-bullet-regexp nil
181 "A regular expression matching bullets that should have 2 spaces after them.
182 When nil, no bullet will have two spaces after them.
183 When a string, it will be used as a regular expression. When the
184 bullet type of a list is changed, the new bullet type will be
185 matched against this regexp. If it matches, there will be two
186 spaces instead of one after the bullet in each item of the list."
187 :group 'org-plain-lists
188 :type '(choice
189 (const :tag "never" nil)
190 (regexp)))
192 (defcustom org-list-ending-method 'both
193 "Determine where plain lists should end.
194 Valid values are: `regexp', `indent' or `both'.
196 When set to `regexp', Org will look into two variables,
197 `org-empty-line-terminates-plain-lists' and the more general
198 `org-list-end-regexp', to determine what will end lists.
200 When set to `indent', a list will end whenever a line following
201 an item, but not starting one, is less or equally indented than
202 the first item of the list.
204 When set to `both', each of the preceding methods is applied to
205 determine lists endings. This is the default method."
206 :group 'org-plain-lists
207 :type '(choice
208 (const :tag "With a regexp defining ending" regexp)
209 (const :tag "With indentation of regular (no bullet) text" indent)
210 (const :tag "With both methods" both)))
212 (defcustom org-empty-line-terminates-plain-lists nil
213 "Non-nil means an empty line ends all plain list levels.
214 This variable only makes sense if `org-list-ending-method' is set
215 to `regexp' or `both'. This is then equivalent to set
216 `org-list-end-regexp' to \"^[ \\t]*$\"."
217 :group 'org-plain-lists
218 :type 'boolean)
220 (defcustom org-list-end-regexp "^[ \t]*\n[ \t]*\n"
221 "Regexp matching the end of all plain list levels.
222 It must start with \"^\" and end with \"\\n\". It defaults to 2
223 blank lines. `org-empty-line-terminates-plain-lists' has
224 precedence over it."
225 :group 'org-plain-lists
226 :type 'string)
228 (defcustom org-list-automatic-rules '((bullet . t)
229 (checkbox . t)
230 (indent . t)
231 (insert . t))
232 "Non-nil means apply set of rules when acting on lists.
233 By default, automatic actions are taken when using
234 \\[org-meta-return], \\[org-metaright], \\[org-metaleft],
235 \\[org-shiftmetaright], \\[org-shiftmetaleft],
236 \\[org-ctrl-c-minus], \\[org-toggle-checkbox] or
237 \\[org-insert-todo-heading]. You can disable individually these
238 rules by setting them to nil. Valid rules are:
240 bullet when non-nil, cycling bullet do not allow lists at
241 column 0 to have * as a bullet and descriptions lists
242 to be numbered.
243 checkbox when non-nil, checkbox statistics is updated each time
244 you either insert a new checkbox or toggle a checkbox.
245 It also prevents from inserting a checkbox in a
246 description item.
247 indent when non-nil, indenting or outdenting list top-item
248 with its subtree will move the whole list and
249 outdenting a list whose bullet is * to column 0 will
250 change that bullet to -
251 insert when non-nil, trying to insert an item inside a block
252 will insert it right before the block instead of
253 throwing an error."
254 :group 'org-plain-lists
255 :type '(alist :tag "Sets of rules"
256 :key-type
257 (choice
258 (const :tag "Bullet" bullet)
259 (const :tag "Checkbox" checkbox)
260 (const :tag "Indent" indent)
261 (const :tag "Insert" insert))
262 :value-type
263 (boolean :tag "Activate" :value t)))
265 (defcustom org-hierarchical-checkbox-statistics t
266 "Non-nil means checkbox statistics counts only the state of direct children.
267 When nil, all boxes below the cookie are counted.
268 This can be set to nil on a per-node basis using a COOKIE_DATA property
269 with the word \"recursive\" in the value."
270 :group 'org-plain-lists
271 :type 'boolean)
273 (defcustom org-description-max-indent 20
274 "Maximum indentation for the second line of a description list.
275 When the indentation would be larger than this, it will become
276 5 characters instead."
277 :group 'org-plain-lists
278 :type 'integer)
280 (defcustom org-list-radio-list-templates
281 '((latex-mode "% BEGIN RECEIVE ORGLST %n
282 % END RECEIVE ORGLST %n
283 \\begin{comment}
284 #+ORGLST: SEND %n org-list-to-latex
286 \\end{comment}\n")
287 (texinfo-mode "@c BEGIN RECEIVE ORGLST %n
288 @c END RECEIVE ORGLST %n
289 @ignore
290 #+ORGLST: SEND %n org-list-to-texinfo
292 @end ignore\n")
293 (html-mode "<!-- BEGIN RECEIVE ORGLST %n -->
294 <!-- END RECEIVE ORGLST %n -->
295 <!--
296 #+ORGLST: SEND %n org-list-to-html
298 -->\n"))
299 "Templates for radio lists in different major modes.
300 All occurrences of %n in a template will be replaced with the name of the
301 list, obtained by prompting the user."
302 :group 'org-plain-lists
303 :type '(repeat
304 (list (symbol :tag "Major mode")
305 (string :tag "Format"))))
307 (defvar org-list-forbidden-blocks '("example" "verse" "src")
308 "Names of blocks where lists are not allowed.
309 Names must be in lower case.")
311 (defvar org-list-export-context '(block inlinetask)
312 "Context types where lists will be interpreted during export.
314 Valid types are `drawer', `inlinetask' and `block'. More
315 specifically, type `block' is determined by the variable
316 `org-list-forbidden-blocks'.")
318 ;;; Internal functions
320 (defun org-list-end-re ()
321 "Return the regex corresponding to the end of a list.
322 It depends on `org-empty-line-terminates-plain-lists'."
323 (if org-empty-line-terminates-plain-lists
324 "^[ \t]*\n"
325 org-list-end-regexp))
327 (defun org-item-re (&optional general)
328 "Return the correct regular expression for plain lists.
329 If GENERAL is non-nil, return the general regexp independent of the value
330 of `org-plain-list-ordered-item-terminator'."
331 (cond
332 ((or general (eq org-plain-list-ordered-item-terminator t))
333 "\\([ \t]*\\([-+]\\|\\([0-9]+[.)]\\)\\)\\|[ \t]+\\*\\)\\([ \t]+\\|$\\)")
334 ((= org-plain-list-ordered-item-terminator ?.)
335 "\\([ \t]*\\([-+]\\|\\([0-9]+\\.\\)\\)\\|[ \t]+\\*\\)\\([ \t]+\\|$\\)")
336 ((= org-plain-list-ordered-item-terminator ?\))
337 "\\([ \t]*\\([-+]\\|\\([0-9]+)\\)\\)\\|[ \t]+\\*\\)\\([ \t]+\\|$\\)")
338 (t (error "Invalid value of `org-plain-list-ordered-item-terminator'"))))
340 (defconst org-item-beginning-re (concat "^" (org-item-re))
341 "Regexp matching the beginning of a plain list item.")
343 (defconst org-list-full-item-re
344 (concat "^[ \t]*\\(\\(?:[-+*]\\|[0-9]+[.)]\\)[ \t]+\\)"
345 "\\(?:\\[@\\(?:start:\\)?\\([0-9]+\\)\\]\\)?"
346 "\\(?:\\(\\[[ X-]\\]\\)[ \t]+\\)?"
347 "\\(?:\\(.*\\)[ \t]+::[ \t]+\\)?")
348 "Matches a list item and puts everything into groups:
349 group 1: bullet
350 group 2: counter
351 group 3: checkbox
352 group 4: description tag")
354 (defun org-list-context ()
355 "Determine context, and its boundaries, around point.
357 Context will be an alist like (MIN MAX CONTEXT) where MIN and MAX
358 are boundaries and CONTEXT is a symbol among `drawer', `block',
359 `invalid', `inlinetask' and nil.
361 Contexts `block' and `invalid' refer to `org-list-forbidden-blocks'."
362 (save-match-data
363 (save-excursion
364 (beginning-of-line)
365 (let* ((outline-regexp (org-get-limited-outline-regexp))
366 ;; can't use org-drawers-regexp as this function might be
367 ;; called in buffers not in Org mode
368 (drawers-re (concat "^[ \t]*:\\("
369 (mapconcat 'regexp-quote org-drawers "\\|")
370 "\\):[ \t]*$"))
371 (case-fold-search t)
372 ;; compute position of surrounding headings. this is the
373 ;; default context.
374 (heading
375 (save-excursion
376 (list
377 (or (and (org-at-heading-p) (point-at-bol))
378 (outline-previous-heading)
379 (point-min))
380 (or (outline-next-heading)
381 (point-max))
382 nil)))
383 (prev-head (car heading))
384 (next-head (nth 1 heading))
385 ;; Are we strictly inside a drawer?
386 (drawerp
387 (when (and (org-in-regexps-block-p
388 drawers-re "^[ \t]*:END:" prev-head)
389 (save-excursion
390 (beginning-of-line)
391 (and (not (looking-at drawers-re))
392 (not (looking-at "^[ \t]*:END:")))))
393 (save-excursion
394 (list
395 (progn
396 (re-search-backward drawers-re prev-head t)
397 (1+ (point-at-eol)))
398 (if (re-search-forward "^[ \t]*:END:" next-head t)
399 (1- (point-at-bol))
400 next-head)
401 'drawer))))
402 ;; Are we strictly in a block, and of which type?
403 (blockp
404 (save-excursion
405 (when (and (org-in-regexps-block-p
406 "^[ \t]*#\\+begin_" "^[ \t]*#\\+end_" prev-head)
407 (save-excursion
408 (beginning-of-line)
409 (not (looking-at
410 "^[ \t]*#\\+\\(begin\\|end\\)_"))))
411 (list
412 (progn
413 (re-search-backward
414 "^[ \t]*#\\+begin_\\(\\S-+\\)" prev-head t)
415 (1+ (point-at-eol)))
416 (save-match-data
417 (if (re-search-forward "^[ \t]*#\\+end_" next-head t)
418 (1- (point-at-bol))
419 next-head))
420 (if (member (downcase (match-string 1))
421 org-list-forbidden-blocks)
422 'invalid
423 'block)))))
424 ;; Are we in an inlinetask?
425 (inlinetaskp
426 (when (and (featurep 'org-inlinetask)
427 (org-inlinetask-in-task-p)
428 (not (looking-at "^\\*+")))
429 (save-excursion
430 (list
431 (progn (org-inlinetask-goto-beginning)
432 (1+ (point-at-eol)))
433 (progn
434 (org-inlinetask-goto-end)
435 (forward-line -1)
436 (1- (point-at-bol)))
437 'inlinetask))))
438 ;; list actual candidates
439 (context-list
440 (delq nil (list heading drawerp blockp inlinetaskp))))
441 ;; Return the closest context around
442 (assq (apply 'max (mapcar 'car context-list)) context-list)))))
444 (defun org-list-search-generic (search re bound noerr)
445 "Search a string in valid contexts for lists.
446 Arguments SEARCH, RE, BOUND and NOERR are similar to those in
447 `re-search-forward'."
448 (catch 'exit
449 (let ((origin (point)))
450 (while t
451 ;; 1. No match: return to origin or bound, depending on NOERR.
452 (unless (funcall search re bound noerr)
453 (throw 'exit (and (goto-char (if (memq noerr '(t nil)) origin bound))
454 nil)))
455 ;; 2. Match in an `invalid' context: continue searching. Else,
456 ;; return point.
457 (unless (eq (org-list-context) 'invalid) (throw 'exit (point)))))))
459 (defun org-list-search-backward (regexp &optional bound noerror)
460 "Like `re-search-backward' but stop only where lists are recognized.
461 Arguments REGEXP, BOUND and NOERROR are similar to those used in
462 `re-search-backward'."
463 (org-list-search-generic #'re-search-backward
464 regexp (or bound (point-min)) noerror))
466 (defun org-list-search-forward (regexp &optional bound noerror)
467 "Like `re-search-forward' but stop only where lists are recognized.
468 Arguments REGEXP, BOUND and NOERROR are similar to those used in
469 `re-search-forward'."
470 (org-list-search-generic #'re-search-forward
471 regexp (or bound (point-max)) noerror))
473 (defun org-list-at-regexp-after-bullet-p (regexp)
474 "Is point at a list item with REGEXP after bullet?"
475 (and (org-at-item-p)
476 (save-excursion
477 (goto-char (match-end 0))
478 ;; Ignore counter if any
479 (when (looking-at "\\(?:\\[@\\(?:start:\\)?[0-9]+\\][ \t]*\\)?")
480 (goto-char (match-end 0)))
481 (looking-at regexp))))
483 (defun org-list-separating-blank-lines-number (pos struct prevs)
484 "Return number of blank lines that should separate items in list.
485 POS is the position at item beginning to be considered. STRUCT is
486 the list structure. PREVS is the alist of previous items. See
487 `org-list-struct-prev-alist'.
489 Assume point is at item's beginning. If the item is alone, apply
490 some heuristics to guess the result."
491 (save-excursion
492 (let ((insert-blank-p
493 (cdr (assq 'plain-list-item org-blank-before-new-entry)))
494 usr-blank)
495 (cond
496 ;; Trivial cases where there should be none.
497 ((or (and (not (eq org-list-ending-method 'indent))
498 org-empty-line-terminates-plain-lists)
499 (not insert-blank-p)) 0)
500 ;; When `org-blank-before-new-entry' says so, it is 1.
501 ((eq insert-blank-p t) 1)
502 ;; plain-list-item is 'auto. Count blank lines separating
503 ;; neighbours items in list.
504 (t (let ((next-p (org-list-get-next-item (point) struct prevs)))
505 (cond
506 ;; Is there a next item?
507 (next-p (goto-char next-p)
508 (org-back-over-empty-lines))
509 ;; Is there a previous item?
510 ((org-list-get-prev-item (point) struct prevs)
511 (org-back-over-empty-lines))
512 ;; User inserted blank lines, trust him
513 ((and (> pos (org-list-get-item-end-before-blank pos struct))
514 (> (save-excursion
515 (goto-char pos)
516 (skip-chars-backward " \t")
517 (setq usr-blank (org-back-over-empty-lines))) 0))
518 usr-blank)
519 ;; Are there blank lines inside the item ?
520 ((save-excursion
521 (org-list-search-forward
522 "^[ \t]*$" (org-list-get-item-end-before-blank pos struct) t))
524 ;; No parent: no blank line.
525 (t 0))))))))
527 (defun org-list-insert-item-generic (pos &optional checkbox after-bullet)
528 "Insert a new list item at POS.
529 If POS is before first character after bullet of the item, the
530 new item will be created before the current one.
532 Insert a checkbox if CHECKBOX is non-nil, and string AFTER-BULLET
533 after the bullet. Cursor will be after this text once the
534 function ends."
535 (let ((case-fold-search t))
536 (goto-char pos)
537 ;; 1. Check if a new item can be inserted at point: are we in an
538 ;; invalid block ? Move outside it if `org-list-automatic'
539 ;; rules says so.
540 (when (or (eq (nth 2 (org-list-context)) 'invalid)
541 (save-excursion
542 (beginning-of-line)
543 (or (looking-at "^[ \t]*#\\+\\(begin\\|end\\)_")
544 (looking-at (concat
545 "\\("
546 org-drawer-regexp
547 "\\|^[ \t]*:END:[ \t]*$\\)"))
548 (and (featurep 'org-inlinetask)
549 (looking-at (org-inlinetask-outline-regexp))))))
550 (if (not (cdr (assq 'insert org-list-automatic-rules)))
551 (error "Cannot insert item inside a block")
552 (end-of-line)
553 (if (string-match "^\\*+[ \t]+" (match-string 0))
554 (org-inlinetask-goto-beginning)
555 (let ((block-start (if (string-match "#\\+" (match-string 0))
556 "^[ \t]*#\\+begin_"
557 org-drawer-regexp)))
558 (re-search-backward block-start nil t)))
559 (end-of-line 0)))
560 ;; 2. Get information about list: structure, usual helper
561 ;; functions, position of point with regards to item start
562 ;; (BEFOREP), blank lines number separating items (BLANK-NB),
563 ;; position of split (POS) if we're allowed to (SPLIT-LINE-P).
564 (let* ((pos (point))
565 (item (goto-char (org-list-get-item-begin)))
566 (struct (org-list-struct))
567 (prevs (org-list-struct-prev-alist struct))
568 (item-end (org-list-get-item-end item struct))
569 (item-end-no-blank (org-list-get-item-end-before-blank item struct))
570 (beforep (and (looking-at org-list-full-item-re)
571 (<= pos (match-end 0))))
572 (split-line-p (org-get-alist-option org-M-RET-may-split-line 'item))
573 (blank-nb (org-list-separating-blank-lines-number
574 item struct prevs))
575 ;; 3. Build the new item to be created. Concatenate same
576 ;; bullet as item, checkbox, text AFTER-BULLET if
577 ;; provided, and text cut from point to end of item
578 ;; (TEXT-CUT) to form item's BODY. TEXT-CUT depends on
579 ;; BEFOREP and SPLIT-LINE-P. The difference of size
580 ;; between what was cut and what was inserted in buffer
581 ;; is stored in SIZE-OFFSET.
582 (ind (org-list-get-ind item struct))
583 (bullet (org-list-bullet-string (org-list-get-bullet item struct)))
584 (box (when checkbox "[ ]"))
585 (text-cut
586 (and (not beforep) split-line-p
587 (progn
588 (goto-char pos)
589 (skip-chars-backward " \r\t\n")
590 (setq pos (point))
591 (delete-and-extract-region pos item-end-no-blank))))
592 (body (concat bullet (when box (concat box " ")) after-bullet
593 (or (and text-cut
594 (if (string-match "\\`[ \t]+" text-cut)
595 (replace-match "" t t text-cut)
596 text-cut))
597 "")))
598 (item-sep (make-string (1+ blank-nb) ?\n))
599 (item-size (+ ind (length body) (length item-sep)))
600 (size-offset (- item-size (length text-cut))))
601 ;; 4. Insert effectively item into buffer
602 (goto-char item)
603 (org-indent-to-column ind)
604 (insert body)
605 (insert item-sep)
606 ;; 5. Add new item to STRUCT.
607 (mapc (lambda (e)
608 (let ((p (car e))
609 (end (nth 6 e)))
610 (cond
611 ;; Before inserted item, positions don't change but
612 ;; an item ending after insertion has its end shifted
613 ;; by SIZE-OFFSET.
614 ((< p item)
615 (when (> end item) (setcar (nthcdr 6 e) (+ end size-offset))))
616 ;; Trivial cases where current item isn't split in
617 ;; two. Just shift every item after new one by
618 ;; ITEM-SIZE.
619 ((or beforep (not split-line-p))
620 (setcar e (+ p item-size))
621 (setcar (nthcdr 6 e) (+ end item-size)))
622 ;; Item is split in two: elements before POS are just
623 ;; shifted by ITEM-SIZE. In the case item would end
624 ;; after split POS, ending is only shifted by
625 ;; SIZE-OFFSET.
626 ((< p pos)
627 (setcar e (+ p item-size))
628 (if (< end pos)
629 (setcar (nthcdr 6 e) (+ end item-size))
630 (setcar (nthcdr 6 e) (+ end size-offset))))
631 ;; Elements after POS are moved into new item. Length
632 ;; of ITEM-SEP has to be removed as ITEM-SEP
633 ;; doesn't appear in buffer yet.
634 ((< p item-end)
635 (setcar e (+ p size-offset (- item pos (length item-sep))))
636 (if (= end item-end)
637 (setcar (nthcdr 6 e) (+ item item-size))
638 (setcar (nthcdr 6 e)
639 (+ end size-offset
640 (- item pos (length item-sep))))))
641 ;; Elements at ITEM-END or after are only shifted by
642 ;; SIZE-OFFSET.
643 (t (setcar e (+ p size-offset))
644 (setcar (nthcdr 6 e) (+ end size-offset))))))
645 struct)
646 (setq struct (sort
647 (cons (list item ind bullet nil box nil (+ item item-size))
648 struct)
649 (lambda (e1 e2) (< (car e1) (car e2)))))
650 ;; 6. If not BEFOREP, new item must appear after ITEM, so
651 ;; exchange ITEM with the next item in list. Position cursor
652 ;; after bullet, counter, checkbox, and label.
653 (if beforep
654 (goto-char item)
655 (setq struct (org-list-exchange-items item (+ item item-size) struct))
656 (goto-char (org-list-get-next-item
657 item struct (org-list-struct-prev-alist struct))))
658 (org-list-struct-fix-struct struct (org-list-struct-parent-alist struct))
659 (when checkbox (org-update-checkbox-count-maybe))
660 (looking-at org-list-full-item-re)
661 (goto-char (match-end 0))
662 t)))
664 (defvar org-last-indent-begin-marker (make-marker))
665 (defvar org-last-indent-end-marker (make-marker))
667 (defun org-list-indent-item-generic (arg no-subtree struct)
668 "Indent a local list item including its children.
669 When number ARG is a negative, item will be outdented, otherwise
670 it will be indented.
672 If a region is active, all items inside will be moved.
674 If NO-SUBTREE is non-nil, only indent the item itself, not its
675 children.
677 STRUCT is the list structure. Return t if successful."
678 (save-excursion
679 (beginning-of-line)
680 (let* ((regionp (org-region-active-p))
681 (rbeg (and regionp (region-beginning)))
682 (rend (and regionp (region-end)))
683 (top (org-list-get-top-point struct))
684 (parents (org-list-struct-parent-alist struct))
685 (prevs (org-list-struct-prev-alist struct))
686 ;; Are we going to move the whole list?
687 (specialp
688 (and (= top (point))
689 (cdr (assq 'indent org-list-automatic-rules))
690 (if no-subtree
691 (error
692 "First item of list cannot move without its subtree")
693 t))))
694 ;; Determine begin and end points of zone to indent. If moving
695 ;; more than one item, save them for subsequent moves.
696 (unless (and (memq last-command '(org-shiftmetaright org-shiftmetaleft))
697 (memq this-command '(org-shiftmetaright org-shiftmetaleft)))
698 (if regionp
699 (progn
700 (set-marker org-last-indent-begin-marker rbeg)
701 (set-marker org-last-indent-end-marker rend))
702 (set-marker org-last-indent-begin-marker (point))
703 (set-marker org-last-indent-end-marker
704 (cond
705 (specialp (org-list-get-bottom-point struct))
706 (no-subtree (1+ (point)))
707 (t (org-list-get-item-end (point) struct))))))
708 (let* ((beg (marker-position org-last-indent-begin-marker))
709 (end (marker-position org-last-indent-end-marker)))
710 (cond
711 ;; Special case: moving top-item with indent rule
712 (specialp
713 (let* ((level-skip (org-level-increment))
714 (offset (if (< arg 0) (- level-skip) level-skip))
715 (top-ind (org-list-get-ind beg struct))
716 (old-struct (mapcar (lambda (e) (copy-alist e)) struct)))
717 (if (< (+ top-ind offset) 0)
718 (error "Cannot outdent beyond margin")
719 ;; Change bullet if necessary
720 (when (and (= (+ top-ind offset) 0)
721 (string-match "*"
722 (org-list-get-bullet beg struct)))
723 (org-list-set-bullet beg struct
724 (org-list-bullet-string "-")))
725 ;; Shift every item by OFFSET and fix bullets. Then
726 ;; apply changes to buffer.
727 (mapc (lambda (e)
728 (let ((ind (org-list-get-ind (car e) struct)))
729 (org-list-set-ind (car e) struct (+ ind offset))))
730 struct)
731 (org-list-struct-fix-bul struct prevs)
732 (org-list-struct-apply-struct struct old-struct))))
733 ;; Forbidden move:
734 ((and (< arg 0)
735 ;; If only one item is moved, it mustn't have a child
736 (or (and no-subtree
737 (not regionp)
738 (org-list-has-child-p beg struct))
739 ;; If a subtree or region is moved, the last item
740 ;; of the subtree mustn't have a child
741 (let ((last-item (caar
742 (reverse
743 (org-remove-if
744 (lambda (e) (>= (car e) end))
745 struct)))))
746 (org-list-has-child-p last-item struct))))
747 (error "Cannot outdent an item without its children"))
748 ;; Normal shifting
750 (let* ((new-parents
751 (if (< arg 0)
752 (org-list-struct-outdent beg end struct parents)
753 (org-list-struct-indent beg end struct parents prevs))))
754 (org-list-struct-fix-struct struct new-parents))
755 (org-update-checkbox-count-maybe))))))
758 ;;; Predicates
760 (defun org-in-item-p ()
761 "Return item beginning position when in a plain list, nil otherwise.
762 This checks `org-list-ending-method'."
763 (save-excursion
764 (beginning-of-line)
765 (unless (or (let ((outline-regexp org-outline-regexp)) (org-at-heading-p))
766 (and (not (eq org-list-ending-method 'indent))
767 (looking-at (org-list-end-re))
768 (progn (forward-line -1) (looking-at (org-list-end-re)))))
769 (or (and (org-at-item-p) (point-at-bol))
770 (let* ((case-fold-search t)
771 (context (org-list-context))
772 (lim-up (car context))
773 (inlinetask-re (and (featurep 'org-inlinetask)
774 (org-inlinetask-outline-regexp)))
775 (ind-ref (if (looking-at "^[ \t]*$")
776 10000
777 (org-get-indentation))))
778 (catch 'exit
779 (while t
780 (let ((ind (org-get-indentation)))
781 (cond
782 ((<= (point) lim-up)
783 (throw 'exit (and (org-at-item-p) (< ind ind-ref) (point))))
784 ((and (not (eq org-list-ending-method 'indent))
785 (looking-at (org-list-end-re)))
786 (throw 'exit nil))
787 ;; Skip blocks, drawers, inline-tasks, blank lines
788 ((looking-at "^[ \t]*#\\+end_")
789 (re-search-backward "^[ \t]*#\\+begin_" nil t))
790 ((looking-at "^[ \t]*:END:")
791 (re-search-backward org-drawer-regexp nil t)
792 (beginning-of-line))
793 ((and inlinetask-re (looking-at inlinetask-re))
794 (org-inlinetask-goto-beginning)
795 (forward-line -1))
796 ((looking-at "^[ \t]*$")
797 (forward-line -1))
798 ((< ind ind-ref)
799 (if (org-at-item-p)
800 (throw 'exit (point))
801 (setq ind-ref ind)
802 (forward-line -1)))
803 (t (if (and (eq org-list-ending-method 'regexp)
804 (org-at-item-p))
805 (throw 'exit (point))
806 (forward-line -1))))))))))))
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)))
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))))
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]+"))
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]+"))
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]+"))
832 ;;; Navigate
834 (defalias 'org-list-get-item-begin 'org-in-item-p)
836 (defun org-beginning-of-item ()
837 "Go to the beginning of the current hand-formatted item.
838 If the cursor is not in an item, throw an error."
839 (interactive)
840 (let ((begin (org-in-item-p)))
841 (if begin (goto-char begin) (error "Not in an item"))))
843 (defun org-beginning-of-item-list ()
844 "Go to the beginning item of the current list or sublist.
845 Return an error if not in a list."
846 (interactive)
847 (let ((begin (org-in-item-p)))
848 (if (not begin)
849 (error "Not in an item")
850 (goto-char begin)
851 (let ((struct (org-list-struct)))
852 (goto-char (org-list-get-list-begin begin (org-list-struct)))))))
854 (defun org-end-of-item-list ()
855 "Go to the end of the current list or sublist.
856 If the cursor in not in an item, throw an error."
857 (interactive)
858 (let ((begin (org-in-item-p)))
859 (if (not begin)
860 (error "Not in an item")
861 (goto-char begin)
862 (let ((struct (org-list-struct)))
863 (goto-char (org-list-get-list-end begin (org-list-struct)))))))
865 (defun org-end-of-item ()
866 "Go to the end of the current hand-formatted item.
867 If the cursor is not in an item, throw an error."
868 (interactive)
869 (let ((begin (org-in-item-p)))
870 (if (not begin)
871 (error "Not in an item")
872 (goto-char begin)
873 (let ((struct (org-list-struct)))
874 (goto-char (org-list-get-item-end begin struct))))))
876 (defun org-previous-item ()
877 "Move to the beginning of the previous item.
878 Item is at the same level in the current plain list. Error if not
879 in a plain list, or if this is the first item in the list."
880 (interactive)
881 (let ((begin (org-in-item-p)))
882 (if (not begin)
883 (error "Not in an item")
884 (goto-char begin)
885 (let* ((struct (org-list-struct))
886 (prevs (org-list-struct-prev-alist struct))
887 (prevp (org-list-get-prev-item begin struct prevs)))
888 (if prevp (goto-char prevp) (error "On first item"))))))
890 (defun org-next-item ()
891 "Move to the beginning of the next item.
892 Item is at the same level in the current plain list. Error if not
893 in a plain list, or if this is the last item in the list."
894 (interactive)
895 (let ((begin (org-in-item-p)))
896 (if (not begin)
897 (error "Not in an item")
898 (goto-char begin)
899 (let* ((struct (org-list-struct))
900 (prevs (org-list-struct-prev-alist struct))
901 (prevp (org-list-get-next-item begin struct prevs)))
902 (if prevp (goto-char prevp) (error "On last item"))))))
904 ;;; Manipulate
906 (defun org-list-exchange-items (beg-A beg-B struct)
907 "Swap item starting at BEG-A with item starting at BEG-B in STRUCT.
908 Blank lines at the end of items are left in place. Return the new
909 structure after the changes.
911 Assume BEG-A is lesser than BEG-B and that BEG-A and BEG-B belong
912 to the same sub-list.
914 This function modifies STRUCT."
915 (save-excursion
916 (let* ((end-A-no-blank (org-list-get-item-end-before-blank beg-A struct))
917 (end-B-no-blank (org-list-get-item-end-before-blank beg-B struct))
918 (end-A (org-list-get-item-end beg-A struct))
919 (end-B (org-list-get-item-end beg-B struct))
920 (size-A (- end-A-no-blank beg-A))
921 (size-B (- end-B-no-blank beg-B))
922 (body-A (buffer-substring beg-A end-A-no-blank))
923 (body-B (buffer-substring beg-B end-B-no-blank))
924 (between-A-no-blank-and-B (buffer-substring end-A-no-blank beg-B))
925 (sub-A (cons beg-A (org-list-get-subtree beg-A struct)))
926 (sub-B (cons beg-B (org-list-get-subtree beg-B struct))))
927 ;; 1. Move effectively items in buffer.
928 (goto-char beg-A)
929 (delete-region beg-A end-B-no-blank)
930 (insert (concat body-B between-A-no-blank-and-B body-A))
931 ;; 2. Now modify struct. No need to re-read the list, the
932 ;; transformation is just a shift of positions. Some special
933 ;; attention is required for items ending at END-A and END-B
934 ;; as empty spaces are not moved there. In others words, item
935 ;; BEG-A will end with whitespaces that were at the end of
936 ;; BEG-B and the same applies to BEG-B.
937 (mapc (lambda (e)
938 (let ((pos (car e)))
939 (cond
940 ((< pos beg-A))
941 ((memq pos sub-A)
942 (let ((end-e (nth 6 e)))
943 (setcar e (+ pos (- end-B-no-blank end-A-no-blank)))
944 (setcar (nthcdr 6 e)
945 (+ end-e (- end-B-no-blank end-A-no-blank)))
946 (when (= end-e end-A) (setcar (nthcdr 6 e) end-B))))
947 ((memq pos sub-B)
948 (let ((end-e (nth 6 e)))
949 (setcar e (- (+ pos beg-A) beg-B))
950 (setcar (nthcdr 6 e) (+ end-e (- beg-A beg-B)))
951 (when (= end-e end-B)
952 (setcar (nthcdr 6 e)
953 (+ beg-A size-B (- end-A end-A-no-blank))))))
954 ((< pos beg-B)
955 (let ((end-e (nth 6 e)))
956 (setcar e (+ pos (- size-B size-A)))
957 (setcar (nthcdr 6 e) (+ end-e (- size-B size-A))))))))
958 struct)
959 (sort struct (lambda (e1 e2) (< (car e1) (car e2)))))))
961 (defun org-move-item-down ()
962 "Move the plain list item at point down, i.e. swap with following item.
963 Subitems (items with larger indentation) are considered part of the item,
964 so this really moves item trees."
965 (interactive)
966 (unless (org-at-item-p) (error "Not at an item"))
967 (let* ((pos (point))
968 (col (current-column))
969 (actual-item (point-at-bol))
970 (struct (org-list-struct))
971 (prevs (org-list-struct-prev-alist struct))
972 (next-item (org-list-get-next-item (point-at-bol) struct prevs)))
973 (if (not next-item)
974 (progn
975 (goto-char pos)
976 (error "Cannot move this item further down"))
977 (setq struct
978 (org-list-exchange-items actual-item next-item struct))
979 ;; Use a short variation of `org-list-struct-fix-struct' as
980 ;; there's no need to go through all the steps.
981 (let ((old-struct (mapcar (lambda (e) (copy-alist e)) struct))
982 (prevs (org-list-struct-prev-alist struct))
983 (parents (org-list-struct-parent-alist struct)))
984 (org-list-struct-fix-bul struct prevs)
985 (org-list-struct-fix-ind struct parents)
986 (org-list-struct-apply-struct struct old-struct)
987 (goto-char (org-list-get-next-item (point-at-bol) struct prevs)))
988 (org-move-to-column col))))
990 (defun org-move-item-up ()
991 "Move the plain list item at point up, i.e. swap with previous item.
992 Subitems (items with larger indentation) are considered part of the item,
993 so this really moves item trees."
994 (interactive)
995 (unless (org-at-item-p) (error "Not at an item"))
996 (let* ((pos (point))
997 (col (current-column))
998 (actual-item (point-at-bol))
999 (struct (org-list-struct))
1000 (prevs (org-list-struct-prev-alist struct))
1001 (prev-item (org-list-get-prev-item (point-at-bol) struct prevs)))
1002 (if (not prev-item)
1003 (progn
1004 (goto-char pos)
1005 (error "Cannot move this item further up"))
1006 (setq struct
1007 (org-list-exchange-items prev-item actual-item struct))
1008 ;; Use a short variation of `org-list-struct-fix-struct' as
1009 ;; there's no need to go through all the steps.
1010 (let ((old-struct (mapcar (lambda (e) (copy-alist e)) struct))
1011 (prevs (org-list-struct-prev-alist struct))
1012 (parents (org-list-struct-parent-alist struct)))
1013 (org-list-struct-fix-bul struct prevs)
1014 (org-list-struct-fix-ind struct parents)
1015 (org-list-struct-apply-struct struct old-struct))
1016 (org-move-to-column col))))
1018 (defun org-insert-item (&optional checkbox)
1019 "Insert a new item at the current level.
1020 If cursor is before first character after bullet of the item, the
1021 new item will be created before the current one.
1023 If CHECKBOX is non-nil, add a checkbox next to the bullet.
1025 Return t when things worked, nil when we are not in an item, or
1026 item is invisible."
1027 (let ((itemp (org-in-item-p)))
1028 (unless (or (not itemp)
1029 (save-excursion
1030 (goto-char itemp)
1031 (org-invisible-p)))
1032 (if (save-excursion
1033 (goto-char itemp)
1034 (org-at-item-timer-p))
1035 ;; Timer list: delegate to `org-timer-item'.
1036 (progn (org-timer-item) t)
1037 ;; if we're in a description list, ask for the new term.
1038 (let ((desc-text (when (save-excursion
1039 (and (goto-char itemp)
1040 (org-at-item-description-p)))
1041 (concat (read-string "Term: ") " :: "))))
1042 ;; Don't insert a checkbox if checkbox rule is applied and it
1043 ;; is a description item.
1044 (org-list-insert-item-generic
1045 (point) (and checkbox
1046 (or (not desc-text)
1047 (not (cdr (assq 'checkbox org-list-automatic-rules)))))
1048 desc-text))))))
1051 ;;; Structures
1053 (defun org-list-struct ()
1054 "Return structure of list at point.
1056 A list structure is an alist where keys is point at item, and
1057 values are:
1058 1. indentation,
1059 2. bullet with trailing whitespace,
1060 3. bullet counter, if any,
1061 4. checkbox, if any,
1062 5. position at item end,
1063 6. description tag, if any.
1065 Thus the following list, where numbers in parens are
1066 point-at-bol:
1068 - [X] first item (1)
1069 1. sub-item 1 (18)
1070 5. [@5] sub-item 2 (34)
1071 some other text belonging to first item (55)
1072 - last item (97)
1073 + tag :: description (109)
1074 (131)
1076 will get the following structure:
1078 \(\(1 0 \"- \" nil [X] nil 97)
1079 \(18 2 \"1. \" nil nil nil 34\)
1080 \(34 2 \"5. \" \"5\" nil nil 55\)
1081 \(97 0 \"- \" nil nil nil 131\)
1082 \(109 2 \"+ \" nil nil \"tag\" 131\)
1084 Assume point is at an item."
1085 (save-excursion
1086 (beginning-of-line)
1087 (let* ((case-fold-search t)
1088 (context (org-list-context))
1089 (lim-up (car context))
1090 (lim-down (nth 1 context))
1091 (text-min-ind 10000)
1092 (drawers-re (concat "^[ \t]*:\\("
1093 (mapconcat 'regexp-quote org-drawers "\\|")
1094 "\\):[ \t]*$"))
1095 (inlinetask-re (and (featurep 'org-inlinetask)
1096 (org-inlinetask-outline-regexp)))
1097 (beg-cell (cons (point) (org-get-indentation)))
1098 ind itm-lst itm-lst-2 end-lst end-lst-2 struct
1099 (assoc-at-point
1100 ;; Return an association whose key is point and values are
1101 ;; indentation, bullet string, bullet counter, and
1102 ;; checkbox.
1103 (function
1104 (lambda (ind)
1105 (looking-at org-list-full-item-re)
1106 (list (point)
1108 (match-string-no-properties 1) ; bullet
1109 (match-string-no-properties 2) ; counter
1110 (match-string-no-properties 3) ; checkbox
1111 (match-string-no-properties 4))))) ; description tag
1112 (end-before-blank
1113 ;; Ensure list ends at the first blank line.
1114 (function
1115 (lambda ()
1116 (skip-chars-backward " \r\t\n")
1117 (min (1+ (point-at-eol)) lim-down)))))
1118 ;; 1. Read list from starting item to its beginning, and save
1119 ;; top item position and indentation in BEG-CELL. Also store
1120 ;; ending position of items in END-LST.
1121 (save-excursion
1122 (catch 'exit
1123 (while t
1124 (let ((ind (+ (or (get-text-property (point) 'original-indentation) 0)
1125 (org-get-indentation))))
1126 (cond
1127 ((<= (point) lim-up)
1128 ;; At upward limit: if we ended at an item, store it,
1129 ;; else dimiss useless data recorded above BEG-CELL.
1130 ;; Jump to part 2.
1131 (throw 'exit
1132 (setq itm-lst
1133 (if (not (org-at-item-p))
1134 (memq (assq (car beg-cell) itm-lst) itm-lst)
1135 (setq beg-cell (cons (point) ind))
1136 (cons (funcall assoc-at-point ind) itm-lst)))))
1137 ((and (not (eq org-list-ending-method 'indent))
1138 (looking-at (org-list-end-re)))
1139 ;; Looking at a list ending regexp. Dismiss useless
1140 ;; data recorded above BEG-CELL. Jump to part 2.
1141 (throw 'exit
1142 (setq itm-lst
1143 (memq (assq (car beg-cell) itm-lst) itm-lst))))
1144 ;; Skip blocks, drawers, inline tasks, blank lines
1145 ;; along the way.
1146 ((looking-at "^[ \t]*#\\+end_")
1147 (re-search-backward "^[ \t]*#\\+begin_" nil t))
1148 ((looking-at "^[ \t]*:END:")
1149 (re-search-backward drawers-re nil t)
1150 (beginning-of-line))
1151 ((and inlinetask-re (looking-at inlinetask-re))
1152 (org-inlinetask-goto-beginning)
1153 (forward-line -1))
1154 ((looking-at "^[ \t]*$")
1155 (forward-line -1))
1156 ((org-at-item-p)
1157 ;; Point is at an item. Add data to ITM-LST. It may
1158 ;; also end a previous item: save it in END-LST. If
1159 ;; ind is less or equal than BEG-CELL and there is no
1160 ;; end at this ind or lesser, this item becomes the
1161 ;; new BEG-CELL.
1162 (push (funcall assoc-at-point ind) itm-lst)
1163 (push (cons ind (point-at-bol)) end-lst)
1164 (when (or (and (eq org-list-ending-method 'regexp)
1165 (<= ind (cdr beg-cell)))
1166 (< ind text-min-ind))
1167 (setq beg-cell (cons (point-at-bol) ind)))
1168 (forward-line -1))
1170 ;; Point is not at an item. Unless ending method is
1171 ;; `regexp', interpret line's indentation:
1173 ;; - text at column 0 is necessarily out of any list.
1174 ;; Dismiss data recorded above BEG-CELL. Jump to
1175 ;; part 2.
1177 ;; - any other case, it can possibly be an ending
1178 ;; position for an item above. Save it and proceed.
1179 (cond
1180 ((eq org-list-ending-method 'regexp))
1181 ((= ind 0)
1182 (throw 'exit
1183 (setq itm-lst
1184 (memq (assq (car beg-cell) itm-lst) itm-lst))))
1186 (when (< ind text-min-ind) (setq text-min-ind ind))
1187 (push (cons ind (point-at-bol)) end-lst)))
1188 (forward-line -1)))))))
1189 ;; 2. Read list from starting point to its end, that is until we
1190 ;; get out of context, or a non-item line is less or equally
1191 ;; indented that BEG-CELL's cdr. Also store ending position
1192 ;; of items in END-LST-2.
1193 (catch 'exit
1194 (while t
1195 (let ((ind (+ (or (get-text-property (point) 'original-indentation) 0)
1196 (org-get-indentation))))
1197 (cond
1198 ((>= (point) lim-down)
1199 ;; At downward limit: this is de facto the end of the
1200 ;; list. Save point as an ending position, and jump to
1201 ;; part 3.
1202 (throw 'exit
1203 (push (cons 0 (funcall end-before-blank)) end-lst-2)))
1204 ((and (not (eq org-list-ending-method 'regexp))
1205 (looking-at (org-list-end-re)))
1206 ;; Looking at a list ending regexp. Save point as an
1207 ;; ending position and jump to part 3.
1208 (throw 'exit (push (cons ind (point-at-bol)) end-lst-2)))
1209 ;; Skip blocks, drawers, inline tasks and blank lines
1210 ;; along the way
1211 ((looking-at "^[ \t]*#\\+begin_")
1212 (re-search-forward "^[ \t]*#\\+end_")
1213 (forward-line 1))
1214 ((looking-at drawers-re)
1215 (re-search-forward "^[ \t]*:END:" nil t)
1216 (forward-line 1))
1217 ((and inlinetask-re (looking-at inlinetask-re))
1218 (org-inlinetask-goto-end)
1219 (forward-line 1))
1220 ((looking-at "^[ \t]*$")
1221 (forward-line 1))
1222 ((org-at-item-p)
1223 ;; Point is at an item. Add data to ITM-LST-2. It may also
1224 ;; end a previous item, so save it in END-LST-2.
1225 (push (funcall assoc-at-point ind) itm-lst-2)
1226 (push (cons ind (point-at-bol)) end-lst-2)
1227 (forward-line 1))
1229 ;; Point is not at an item. If ending method is not
1230 ;; `regexp', two situations are of interest:
1232 ;; - ind is lesser or equal than BEG-CELL's. The list is
1233 ;; over. Store point as an ending position and jump to
1234 ;; part 3.
1236 ;; - ind is lesser or equal than previous item's. This
1237 ;; is an ending position. Store it and proceed.
1238 (cond
1239 ((eq org-list-ending-method 'regexp))
1240 ((<= ind (cdr beg-cell))
1241 (push (cons ind (funcall end-before-blank)) end-lst-2)
1242 (throw 'exit nil))
1243 ((<= ind (nth 1 (car itm-lst-2)))
1244 (push (cons ind (point-at-bol)) end-lst-2)))
1245 (forward-line 1))))))
1246 (setq struct (append itm-lst (cdr (nreverse itm-lst-2))))
1247 (setq end-lst (append end-lst (cdr (nreverse end-lst-2))))
1248 ;; 3. Correct ill-formed lists by making sure top item has the
1249 ;; least indentation of the list
1250 (let ((min-ind (nth 1 (car struct))))
1251 (mapc (lambda (item)
1252 (let ((ind (nth 1 item)))
1253 (when (< ind min-ind) (setcar (cdr item) min-ind))))
1254 struct))
1255 ;; 4. Associate each item to its end pos.
1256 (org-list-struct-assoc-end struct end-lst)
1257 ;; 5. Return STRUCT
1258 struct)))
1260 (defun org-list-struct-assoc-end (struct end-list)
1261 "Associate proper ending point to items in STRUCT.
1263 END-LIST is a pseudo-alist where car is indentation and cdr is
1264 ending position.
1266 This function modifies STRUCT."
1267 (let ((endings end-list))
1268 (mapc
1269 (lambda (elt)
1270 (let ((pos (car elt))
1271 (ind (nth 1 elt)))
1272 ;; remove end candidates behind current item
1273 (while (or (<= (cdar endings) pos))
1274 (pop endings))
1275 ;; add end position to item assoc
1276 (let ((old-end (nthcdr 6 elt))
1277 (new-end (assoc-default ind endings '<=)))
1278 (if old-end
1279 (setcar old-end new-end)
1280 (setcdr elt (append (cdr elt) (list new-end)))))))
1281 struct)))
1283 (defun org-list-struct-prev-alist (struct)
1284 "Return alist between item and previous item in STRUCT."
1285 (let ((item-end-alist (mapcar (lambda (e) (cons (car e) (nth 6 e)))
1286 struct)))
1287 (mapcar (lambda (e)
1288 (let ((prev (car (rassq (car e) item-end-alist))))
1289 (cons (car e) prev)))
1290 struct)))
1292 (defun org-list-struct-parent-alist (struct)
1293 "Return alist between item and parent in STRUCT."
1294 (let ((ind-to-ori (list (list (nth 1 (car struct)))))
1295 (prev-pos (list (caar struct))))
1296 (cons prev-pos
1297 (mapcar (lambda (item)
1298 (let ((pos (car item))
1299 (ind (nth 1 item))
1300 (prev-ind (caar ind-to-ori)))
1301 (push pos prev-pos)
1302 (cond
1303 ((> prev-ind ind)
1304 (setq ind-to-ori
1305 (member (assq ind ind-to-ori) ind-to-ori))
1306 (cons pos (cdar ind-to-ori)))
1307 ((< prev-ind ind)
1308 (let ((origin (nth 1 prev-pos)))
1309 (push (cons ind origin) ind-to-ori)
1310 (cons pos origin)))
1311 (t (cons pos (cdar ind-to-ori))))))
1312 (cdr struct)))))
1314 (defun org-list-get-parent (item struct parents)
1315 "Return parent of ITEM in STRUCT, or nil.
1316 PARENTS is the alist of items' parent. See
1317 `org-list-struct-parent-alist'."
1318 (let ((parents (or parents (org-list-struct-parent-alist struct))))
1319 (cdr (assq item parents))))
1321 (defun org-list-has-child-p (item struct)
1322 "Return a non-nil value if ITEM in STRUCT has a child.
1323 Value returned is the position of the first child of ITEM."
1324 (let ((ind (org-list-get-ind item struct))
1325 (child-maybe (car (nth 1 (member (assq item struct) struct)))))
1326 (when (and child-maybe
1327 (< ind (org-list-get-ind child-maybe struct)))
1328 child-maybe)))
1330 (defun org-list-get-next-item (item struct prevs)
1331 "Return next item in same sub-list as ITEM in STRUCT, or nil.
1332 PREVS is the alist of previous items. See
1333 `org-list-struct-prev-alist'."
1334 (car (rassq item prevs)))
1336 (defun org-list-get-prev-item (item struct prevs)
1337 "Return previous item in same sub-list as ITEM in STRUCT, or nil.
1338 PREVS is the alist of previous items. See
1339 `org-list-struct-prev-alist'."
1340 (cdr (assq item prevs)))
1342 (defun org-list-get-subtree (item struct)
1343 "Return all items with ITEM as a common ancestor or nil.
1344 STRUCT is the list structure considered."
1345 (let* ((item-end (org-list-get-item-end item struct))
1346 (sub-struct (cdr (member (assq item struct) struct)))
1347 subtree)
1348 (catch 'exit
1349 (mapc (lambda (e)
1350 (let ((pos (car e)))
1351 (if (< pos item-end) (push pos subtree) (throw 'exit nil))))
1352 sub-struct))
1353 (nreverse subtree)))
1355 (defun org-list-get-all-items (item struct prevs)
1356 "List of items in the same sub-list as ITEM in STRUCT.
1357 PREVS, when provided, is the alist of previous items. See
1358 `org-list-struct-prev-alist'."
1359 (let ((prev-item item)
1360 (next-item item)
1361 before-item after-item)
1362 (while (setq prev-item (org-list-get-prev-item prev-item struct prevs))
1363 (push prev-item before-item))
1364 (while (setq next-item (org-list-get-next-item next-item struct prevs))
1365 (push next-item after-item))
1366 (append before-item (list item) (nreverse after-item))))
1368 (defun org-list-get-children (item struct parents)
1369 "List all children of ITEM in STRUCT, or nil.
1370 PARENTS is the alist of items' parent. See
1371 `org-list-struct-parent-alist'."
1372 (let (all)
1373 (while (setq child (car (rassq item parents)))
1374 (setq parents (cdr (member (assq child parents) parents)))
1375 (push child all))
1376 (nreverse all)))
1378 (defun org-list-get-top-point (struct)
1379 "Return point at beginning of list.
1380 STRUCT is the structure of the list."
1381 (caar struct))
1383 (defun org-list-get-bottom-point (struct)
1384 "Return point at bottom of list.
1385 STRUCT is the structure of the list."
1386 (apply 'max
1387 (mapcar (lambda (e) (org-list-get-item-end (car e) struct)) struct)))
1389 (defun org-list-get-list-begin (item struct prevs)
1390 "Return point at beginning of sub-list ITEM belongs.
1391 STRUCT is the structure of the list. PREVS is the alist of
1392 previous items. See `org-list-struct-prev-alist'."
1393 (let ((first-item item) prev-item)
1394 (while (setq prev-item (org-list-get-prev-item first-item struct prevs))
1395 (setq first-item prev-item))
1396 first-item))
1398 (defalias 'org-list-get-first-item 'org-list-get-list-begin)
1400 (defun org-list-get-last-item (item struct prevs)
1401 "Return point at last item of sub-list ITEM belongs.
1402 STRUCT is the structure of the list. PREVS is the alist of
1403 previous items. See `org-list-struct-prev-alist'."
1404 (let ((last-item item) next-item)
1405 (while (setq next-item (org-list-get-next-item last-item struct prevs))
1406 (setq last-item next-item))
1407 last-item))
1409 (defun org-list-get-list-end (item struct prevs)
1410 "Return point at end of sub-list ITEM belongs.
1411 STRUCT is the structure of the list. PREVS is the alist of
1412 previous items. See `org-list-struct-prev-alist'."
1413 (org-list-get-item-end (org-list-get-last-item item struct prevs) struct))
1415 (defun org-list-get-nth (n key struct)
1416 "Return the Nth value of KEY in STRUCT."
1417 (nth n (assq key struct)))
1419 (defun org-list-set-nth (n key struct new)
1420 "Set the Nth value of KEY in STRUCT to NEW.
1421 \nThis function modifies STRUCT."
1422 (setcar (nthcdr n (assq key struct)) new))
1424 (defun org-list-get-ind (item struct)
1425 "Return indentation of ITEM in STRUCT."
1426 (org-list-get-nth 1 item struct))
1428 (defun org-list-set-ind (item struct ind)
1429 "Set indentation of ITEM in STRUCT to IND.
1430 \nThis function modifies STRUCT."
1431 (org-list-set-nth 1 item struct ind))
1433 (defun org-list-get-bullet (item struct)
1434 "Return bullet of ITEM in STRUCT."
1435 (org-list-get-nth 2 item struct))
1437 (defun org-list-set-bullet (item struct bullet)
1438 "Set bullet of ITEM in STRUCT to BULLET.
1439 \nThis function modifies STRUCT."
1440 (org-list-set-nth 2 item struct bullet))
1442 (defun org-list-get-counter (item struct)
1443 "Return counter of ITEM in STRUCT."
1444 (org-list-get-nth 3 item struct))
1446 (defun org-list-get-checkbox (item struct)
1447 "Return checkbox of ITEM in STRUCT or nil."
1448 (org-list-get-nth 4 item struct))
1450 (defun org-list-set-checkbox (item struct checkbox)
1451 "Set checkbox of ITEM in STRUCT to CHECKBOX.
1452 \nThis function modifies STRUCT."
1453 (org-list-set-nth 4 item struct checkbox))
1455 (defun org-list-get-tag (item struct)
1456 "Return end position of ITEM in STRUCT."
1457 (org-list-get-nth 5 item struct))
1459 (defun org-list-get-item-end (item struct)
1460 "Return end position of ITEM in STRUCT."
1461 (org-list-get-nth 6 item struct))
1463 (defun org-list-get-item-end-before-blank (item struct)
1464 "Return point at end of ITEM in STRUCT, before any blank line.
1465 Point returned is at end of line."
1466 (save-excursion
1467 (goto-char (org-list-get-item-end item struct))
1468 (skip-chars-backward " \r\t\n")
1469 (point-at-eol)))
1471 (defun org-list-struct-fix-bul (struct prevs)
1472 "Verify and correct bullets for every association in STRUCT.
1473 PREVS is the alist of previous items. See
1474 `org-list-struct-prev-alist'.
1476 This function modifies STRUCT."
1477 (let ((fix-bul
1478 (function
1479 (lambda (item)
1480 (let* ((prev (org-list-get-prev-item item struct prevs))
1481 (prev-bul (and prev (org-list-get-bullet prev struct)))
1482 (counter (org-list-get-counter item struct))
1483 (bullet (org-list-get-bullet item struct)))
1484 (org-list-set-bullet
1485 item struct
1486 (org-list-bullet-string
1487 (cond
1488 ((and prev (string-match "[0-9]+" prev-bul) counter)
1489 (replace-match counter nil nil prev-bul))
1490 (prev
1491 (org-list-inc-bullet-maybe (org-list-get-bullet prev struct)))
1492 ((and (string-match "[0-9]+" bullet) counter)
1493 (replace-match counter nil nil bullet))
1494 ((string-match "[0-9]+" bullet)
1495 (replace-match "1" nil nil bullet))
1496 (t bullet)))))))))
1497 (mapc fix-bul (mapcar 'car struct))))
1499 (defun org-list-struct-fix-ind (struct parents &optional bullet-size)
1500 "Verify and correct indentation for every association in STRUCT.
1502 PARENTS is the alist of items' parents. See
1503 `org-list-struct-parent-alist'.
1505 If numeric optional argument BULLET-SIZE is set, assume all
1506 bullets in list have this length to determine new indentation.
1508 This function modifies STRUCT."
1509 (let* ((ancestor (org-list-get-top-point struct))
1510 (top-ind (org-list-get-ind ancestor struct))
1511 (new-ind
1512 (lambda (item)
1513 (let ((parent (org-list-get-parent item struct parents)))
1514 (if parent
1515 ;; Indent like parent + length of parent's bullet
1516 (org-list-set-ind
1517 item struct (+ (or bullet-size
1518 (length
1519 (org-list-get-bullet parent struct)))
1520 (org-list-get-ind parent struct)))
1521 ;; If no parent, indent like top-point
1522 (org-list-set-ind item struct top-ind))))))
1523 (mapc new-ind (mapcar 'car (cdr struct)))))
1525 (defun org-list-struct-fix-box (struct parents prevs &optional ordered)
1526 "Verify and correct checkboxes for every association in STRUCT.
1528 PARENTS is the alist of items' parents. See
1529 `org-list-struct-parent-alist'. PREVS is the alist of previous
1530 items. See `org-list-struct-prev-alist.
1532 If ORDERED is non-nil, a checkbox can only be checked when every
1533 checkbox before it is checked too. If there was an attempt to
1534 break this rule, the function will return the blocking item. In
1535 all others cases, the return value will be nil.
1537 This function modifies STRUCT."
1538 (let ((all-items (mapcar 'car struct))
1539 (set-parent-box
1540 (function
1541 (lambda (item)
1542 (let* ((box-list
1543 (mapcar (lambda (child)
1544 (org-list-get-checkbox child struct))
1545 (org-list-get-children item struct parents))))
1546 (org-list-set-checkbox
1547 item struct
1548 (cond
1549 ((and (member "[ ]" box-list) (member "[X]" box-list)) "[-]")
1550 ((member "[-]" box-list) "[-]")
1551 ((member "[X]" box-list) "[X]")
1552 ((member "[ ]" box-list) "[ ]")
1553 ;; parent has no boxed child: leave box as-is
1554 (t (org-list-get-checkbox item struct))))))))
1555 parent-list)
1556 ;; 1. List all parents with a checkbox
1557 (mapc
1558 (lambda (e)
1559 (let* ((parent (org-list-get-parent e struct parents))
1560 (parent-box-p (org-list-get-checkbox parent struct)))
1561 (when (and parent-box-p (not (memq parent parent-list)))
1562 (push parent parent-list))))
1563 all-items)
1564 ;; 2. Sort those parents by decreasing indentation
1565 (setq parent-list (sort parent-list
1566 (lambda (e1 e2)
1567 (> (org-list-get-ind e1 struct)
1568 (org-list-get-ind e2 struct)))))
1569 ;; 3. For each parent, get all children's checkboxes to determine
1570 ;; and set its checkbox accordingly
1571 (mapc set-parent-box parent-list)
1572 ;; 4. If ORDERED is set, see if we need to uncheck some boxes
1573 (when ordered
1574 (let* ((box-list
1575 (mapcar (lambda (e) (org-list-get-checkbox e struct)) all-items))
1576 (after-unchecked (member "[ ]" box-list)))
1577 ;; there are boxes checked after an unchecked one: fix that
1578 (when (member "[X]" after-unchecked)
1579 (let ((index (- (length struct) (length after-unchecked))))
1580 (mapc (lambda (e) (org-list-set-checkbox e struct "[ ]"))
1581 (nthcdr index all-items))
1582 ;; Verify once again the structure, without ORDERED
1583 (org-list-struct-fix-box struct parents prevs nil)
1584 ;; return blocking item
1585 (nth index all-items)))))))
1587 (defun org-list-struct-fix-struct (struct parents)
1588 "Return STRUCT with correct bullets and indentation.
1589 PARENTS is the alist of items' parents. See
1590 `org-list-struct-parent-alist'."
1591 ;; Order of functions matters here: checkboxes and endings need
1592 ;; correct indentation to be set, and indentation needs correct
1593 ;; bullets.
1595 ;; 0. Save a copy of structure before modifications
1596 (let ((old-struct (mapcar (lambda (e) (copy-alist e)) struct)))
1597 ;; 1. Set a temporary, but coherent with PARENTS, indentation in
1598 ;; order to get items endings and bullets properly
1599 (org-list-struct-fix-ind struct parents 2)
1600 ;; 2. Get pseudo-alist of ending positions and sort it by position.
1601 ;; Then associate them to the structure.
1602 (let (end-list acc-end)
1603 (mapc (lambda (e)
1604 (let* ((pos (car e))
1605 (ind-pos (org-list-get-ind pos struct))
1606 (end-pos (org-list-get-item-end pos struct)))
1607 (unless (assq end-pos struct)
1608 ;; to determine real ind of an ending position that is
1609 ;; not at an item, we have to find the item it belongs
1610 ;; to: it is the last item (ITEM-UP), whose ending is
1611 ;; further than the position we're interested in.
1612 (let ((item-up (assoc-default end-pos acc-end '>)))
1613 (push (cons
1614 ;; else part is for the bottom point
1615 (if item-up (+ (org-list-get-ind item-up struct) 2) 0)
1616 end-pos)
1617 end-list)))
1618 (push (cons ind-pos pos) end-list)
1619 (push (cons end-pos pos) acc-end)))
1620 struct)
1621 (setq end-list (sort end-list (lambda (e1 e2) (< (cdr e1) (cdr e2)))))
1622 (org-list-struct-assoc-end struct end-list))
1623 ;; 3. Get bullets right
1624 (let ((prevs (org-list-struct-prev-alist struct)))
1625 (org-list-struct-fix-bul struct prevs)
1626 ;; 4. Now get real indentation
1627 (org-list-struct-fix-ind struct parents)
1628 ;; 5. Eventually fix checkboxes
1629 (org-list-struct-fix-box struct parents prevs))
1630 ;; 6. Apply structure modifications to buffer
1631 (org-list-struct-apply-struct struct old-struct)))
1633 (defun org-list-struct-outdent (start end struct parents)
1634 "Outdent items between START and END in structure STRUCT.
1636 PARENTS is the alist of items' parents. See
1637 `org-list-struct-parent-alist'.
1639 START is included, END excluded."
1640 (let* (acc
1641 (out (lambda (cell)
1642 (let* ((item (car cell))
1643 (parent (cdr cell)))
1644 (cond
1645 ;; Item not yet in zone: keep association
1646 ((< item start) cell)
1647 ;; Item out of zone: follow associations in acc
1648 ((>= item end)
1649 (let ((convert (and parent (assq parent acc))))
1650 (if convert (cons item (cdr convert)) cell)))
1651 ;; Item has no parent: error
1652 ((not parent)
1653 (error "Cannot outdent top-level items"))
1654 ;; Parent is outdented: keep association
1655 ((>= parent start)
1656 (push (cons parent item) acc) cell)
1658 ;; Parent isn't outdented: reparent to grand-parent
1659 (let ((grand-parent (org-list-get-parent
1660 parent struct parents)))
1661 (push (cons parent item) acc)
1662 (cons item grand-parent))))))))
1663 (mapcar out parents)))
1665 (defun org-list-struct-indent (start end struct parents prevs)
1666 "Indent items between START and END in structure STRUCT.
1668 PARENTS is the alist of parents. See
1669 `org-list-struct-parent-alist'. PREVS is the alist of previous
1670 items. See `org-list-struct-prev-alist'.
1672 START is included and END excluded.
1674 STRUCT may be modified if `org-list-demote-modify-bullet' matches
1675 bullets between START and END."
1676 (let* (acc
1677 (set-assoc (lambda (cell) (push cell acc) cell))
1678 (change-bullet-maybe
1679 (function
1680 (lambda (item)
1681 (let* ((bul (org-trim (org-list-get-bullet item struct)))
1682 (new-bul-p (cdr (assoc bul org-list-demote-modify-bullet))))
1683 (when new-bul-p (org-list-set-bullet item struct new-bul-p))))))
1684 (ind
1685 (lambda (cell)
1686 (let* ((item (car cell))
1687 (parent (cdr cell)))
1688 (cond
1689 ;; Item not yet in zone: keep association
1690 ((< item start) cell)
1691 ((>= item end)
1692 ;; Item out of zone: follow associations in acc
1693 (let ((convert (assq parent acc)))
1694 (if convert (cons item (cdr convert)) cell)))
1696 ;; Item is in zone...
1697 (let ((prev (org-list-get-prev-item item struct prevs)))
1698 ;; Check if bullet needs to be changed
1699 (funcall change-bullet-maybe item)
1700 (cond
1701 ;; First item indented but not parent: error
1702 ((and (not prev) (< parent start))
1703 (error "Cannot indent the first item of a list"))
1704 ;; First item and parent indented: keep same parent
1705 ((not prev) (funcall set-assoc cell))
1706 ;; Previous item not indented: reparent to it
1707 ((< prev start) (funcall set-assoc (cons item prev)))
1708 ;; Previous item indented: reparent like it
1710 (funcall set-assoc
1711 (cons item (cdr (assq prev acc)))))))))))))
1712 (mapcar ind parents)))
1714 (defun org-list-struct-apply-struct (struct old-struct)
1715 "Apply modifications to list so it mirrors STRUCT.
1717 OLD-STRUCT is the structure before any modifications. Thus, the
1718 function is smart enough to modify only parts of buffer which
1719 have changed.
1721 Initial position of cursor is restored after the changes."
1722 (let* ((pos (copy-marker (point)))
1723 (shift-body-ind
1724 (function
1725 ;; Shift the indentation between END and BEG by DELTA.
1726 ;; Start from the line before END.
1727 (lambda (end beg delta)
1728 (unless (= delta 0)
1729 (goto-char end)
1730 (forward-line -1)
1731 (while (or (> (point) beg)
1732 (and (= (point) beg) (not (org-at-item-p))))
1733 (when (org-looking-at-p "^[ \t]*\\S-")
1734 (let ((i (org-get-indentation)))
1735 (org-indent-line-to (+ i delta))))
1736 (forward-line -1))))))
1737 (modify-item
1738 (function
1739 ;; Replace item first line elements with new elements from
1740 ;; STRUCT, if appropriate.
1741 (lambda (item)
1742 (goto-char item)
1743 (let* ((new-ind (org-list-get-ind item struct))
1744 (old-ind (org-list-get-ind item old-struct))
1745 (new-bul (org-list-bullet-string
1746 (org-list-get-bullet item struct)))
1747 (old-bul (org-list-get-bullet item old-struct))
1748 (new-box (org-list-get-checkbox item struct)))
1749 (looking-at org-list-full-item-re)
1750 ;; a. Replace bullet
1751 (unless (equal old-bul new-bul)
1752 (replace-match new-bul nil nil nil 1))
1753 ;; b. Replace checkbox
1754 (cond
1755 ((and new-box
1756 (save-match-data (org-at-item-description-p))
1757 (cdr (assq 'checkbox org-list-automatic-rules)))
1758 (message "Cannot add a checkbox to a description list item"))
1759 ((equal (match-string 3) new-box))
1760 ((and (match-string 3) new-box)
1761 (replace-match new-box nil nil nil 3))
1762 ((match-string 3)
1763 (goto-char (or (match-end 2) (match-end 1)))
1764 (looking-at "\\[[ X-]\\][ \t]+")
1765 (replace-match ""))
1766 (t (goto-char (or (match-end 2) (match-end 1)))
1767 (insert (concat new-box " "))))
1768 ;; c. Indent item to appropriate column
1769 (unless (= new-ind old-ind)
1770 (delete-region (goto-char (point-at-bol))
1771 (progn (skip-chars-forward " \t") (point)))
1772 (indent-to new-ind)))))))
1773 ;; 1. First get list of items and position endings. We maintain
1774 ;; two alists: ITM-SHIFT, determining indentation shift needed
1775 ;; at item, and END-POS, a pseudo-alist where key is ending
1776 ;; position and value point
1777 (let (end-list acc-end itm-shift all-ends sliced-struct)
1778 (mapc (lambda (e)
1779 (let* ((pos (car e))
1780 (ind-pos (org-list-get-ind pos struct))
1781 (ind-old (org-list-get-ind pos old-struct))
1782 (bul-pos (org-list-get-bullet pos struct))
1783 (bul-old (org-list-get-bullet pos old-struct))
1784 (ind-shift (- (+ ind-pos (length bul-pos))
1785 (+ ind-old (length bul-old))))
1786 (end-pos (org-list-get-item-end pos old-struct)))
1787 (push (cons pos ind-shift) itm-shift)
1788 (unless (assq end-pos old-struct)
1789 ;; To determine real ind of an ending position that is
1790 ;; not at an item, we have to find the item it belongs
1791 ;; to: it is the last item (ITEM-UP), whose ending is
1792 ;; further than the position we're interested in.
1793 (let ((item-up (assoc-default end-pos acc-end '>)))
1794 (push (cons end-pos item-up) end-list)))
1795 (push (cons end-pos pos) acc-end)))
1796 old-struct)
1797 ;; 2. Slice the items into parts that should be shifted by the
1798 ;; same amount of indentation. The slices are returned in
1799 ;; reverse order so changes modifying buffer do not change
1800 ;; positions they refer to.
1801 (setq all-ends (sort (append (mapcar 'car itm-shift)
1802 (org-uniquify (mapcar 'car end-list)))
1803 '<))
1804 (while (cdr all-ends)
1805 (let* ((up (pop all-ends))
1806 (down (car all-ends))
1807 (ind (if (assq up struct)
1808 (cdr (assq up itm-shift))
1809 (cdr (assq (cdr (assq up end-list)) itm-shift)))))
1810 (push (list down up ind) sliced-struct)))
1811 ;; 3. Modify each slice in buffer, from end to beginning, with a
1812 ;; special action when beginning is at item start.
1813 (mapc (lambda (e)
1814 (apply shift-body-ind e)
1815 (let ((beg (nth 1 e)))
1816 (when (assq beg struct)
1817 (funcall modify-item beg))))
1818 sliced-struct))
1819 ;; 4. Go back to initial position
1820 (goto-char pos)))
1822 ;;; Indentation
1824 (defun org-outdent-item ()
1825 "Outdent a local list item, but not its children.
1826 If a region is active, all items inside will be moved."
1827 (interactive)
1828 (if (org-at-item-p)
1829 (let ((struct (org-list-struct)))
1830 (org-list-indent-item-generic -1 t struct))
1831 (error "Not at an item")))
1833 (defun org-indent-item ()
1834 "Indent a local list item, but not its children.
1835 If a region is active, all items inside will be moved."
1836 (interactive)
1837 (if (org-at-item-p)
1838 (let ((struct (org-list-struct)))
1839 (org-list-indent-item-generic 1 t struct))
1840 (error "Not at an item")))
1842 (defun org-outdent-item-tree ()
1843 "Outdent a local list item including its children.
1844 If a region is active, all items inside will be moved."
1845 (interactive)
1846 (let ((regionp (org-region-active-p)))
1847 (cond
1848 ((or (org-at-item-p)
1849 (and (org-region-active-p)
1850 (goto-char (region-beginning))
1851 (org-at-item-p)))
1852 (let ((struct (org-list-struct)))
1853 (org-list-indent-item-generic -1 nil struct)))
1854 (regionp (error "Region not starting at an item"))
1855 (t (error "Not at an item")))))
1857 (defun org-indent-item-tree ()
1858 "Indent a local list item including its children.
1859 If a region is active, all items inside will be moved."
1860 (interactive)
1861 (interactive)
1862 (let ((regionp (org-region-active-p)))
1863 (cond
1864 ((or (org-at-item-p)
1865 (and (org-region-active-p)
1866 (goto-char (region-beginning))
1867 (org-at-item-p)))
1868 (let ((struct (org-list-struct)))
1869 (org-list-indent-item-generic 1 nil struct)))
1870 (regionp (error "Region not starting at an item"))
1871 (t (error "Not at an item")))))
1873 (defvar org-tab-ind-state)
1874 (defun org-cycle-item-indentation ()
1875 "Cycle levels of indentation of an empty item.
1876 The first run indents the item, if applicable. Subsequents runs
1877 outdent it at meaningful levels in the list. When done, item is
1878 put back at its original position with its original bullet.
1880 Return t at each successful move."
1881 (when (org-at-item-p)
1882 (let* ((org-adapt-indentation nil)
1883 (struct (org-list-struct))
1884 (ind (org-list-get-ind (point-at-bol) struct)))
1885 ;; Check that item is really empty
1886 (when (and (save-excursion
1887 (beginning-of-line)
1888 (looking-at org-list-full-item-re))
1889 (>= (match-end 0) (save-excursion
1890 (goto-char (org-list-get-item-end
1891 (point-at-bol) struct))
1892 (skip-chars-backward " \r\t\n")
1893 (point))))
1894 (setq this-command 'org-cycle-item-indentation)
1895 ;; When in the middle of the cycle, try to outdent first. If it
1896 ;; fails, and point is still at initial position, indent. Else,
1897 ;; go back to original position.
1898 (if (eq last-command 'org-cycle-item-indentation)
1899 (cond
1900 ((ignore-errors (org-list-indent-item-generic -1 t struct)))
1901 ((and (= ind (car org-tab-ind-state))
1902 (ignore-errors (org-list-indent-item-generic 1 t struct))))
1903 (t (back-to-indentation)
1904 (org-indent-to-column (car org-tab-ind-state))
1905 (looking-at "\\S-+")
1906 (replace-match (cdr org-tab-ind-state))
1907 (end-of-line)
1908 ;; Break cycle
1909 (setq this-command 'identity)))
1910 ;; If a cycle is starting, remember indentation and bullet,
1911 ;; then try to indent. If it fails, try to outdent.
1912 (setq org-tab-ind-state (cons ind (org-get-bullet)))
1913 (cond
1914 ((ignore-errors (org-list-indent-item-generic 1 t struct)))
1915 ((ignore-errors (org-list-indent-item-generic -1 t struct)))
1916 (t (error "Cannot move item"))))
1917 t))))
1919 ;;; Bullets
1921 (defun org-get-bullet ()
1922 "Return the bullet of the item at point.
1923 Assume cursor is at an item."
1924 (save-excursion
1925 (beginning-of-line)
1926 (and (looking-at "[ \t]*\\(\\S-+\\)") (match-string 1))))
1928 (defun org-list-bullet-string (bullet)
1929 "Return BULLET with the correct number of whitespaces.
1930 It determines the number of whitespaces to append by looking at
1931 `org-list-two-spaces-after-bullet-regexp'."
1932 (save-match-data
1933 (string-match "\\S-+\\([ \t]*\\)" bullet)
1934 (replace-match
1935 (save-match-data
1936 (concat
1938 ;; Do we need to concat another white space ?
1939 (when (and org-list-two-spaces-after-bullet-regexp
1940 (string-match org-list-two-spaces-after-bullet-regexp bullet))
1941 " ")))
1942 nil nil bullet 1)))
1944 (defun org-list-inc-bullet-maybe (bullet)
1945 "Increment BULLET if applicable."
1946 (if (string-match "[0-9]+" bullet)
1947 (replace-match
1948 (number-to-string (1+ (string-to-number (match-string 0 bullet))))
1949 nil nil bullet)
1950 bullet))
1952 (defun org-list-repair ()
1953 "Make sure all items are correctly indented, with the right bullet.
1954 This function scans the list at point, along with any sublist."
1955 (interactive)
1956 (unless (org-at-item-p) (error "This is not a list"))
1957 (let* ((struct (org-list-struct))
1958 (parents (org-list-struct-parent-alist struct)))
1959 (org-list-struct-fix-struct struct parents)))
1961 (defun org-cycle-list-bullet (&optional which)
1962 "Cycle through the different itemize/enumerate bullets.
1963 This cycle the entire list level through the sequence:
1965 `-' -> `+' -> `*' -> `1.' -> `1)'
1967 If WHICH is a valid string, use that as the new bullet. If WHICH
1968 is an integer, 0 means `-', 1 means `+' etc. If WHICH is
1969 `previous', cycle backwards."
1970 (interactive "P")
1971 (unless (org-at-item-p) (error "This is not a list"))
1972 (save-excursion
1973 (beginning-of-line)
1974 (let* ((struct (org-list-struct))
1975 (parents (org-list-struct-parent-alist struct))
1976 (prevs (org-list-struct-prev-alist struct))
1977 (list-beg (org-list-get-list-begin (point) struct prevs))
1978 (bullet (org-list-get-bullet list-beg struct))
1979 (current (cond
1980 ((string-match "\\." bullet) "1.")
1981 ((string-match ")" bullet) "1)")
1982 (t (org-trim bullet))))
1983 (bullet-rule-p (cdr (assq 'bullet org-list-automatic-rules)))
1984 ;; Compute list of possible bullets, depending on context
1985 (bullet-list (append '("-" "+" )
1986 ;; *-bullets are not allowed at column 0
1987 (unless (and bullet-rule-p
1988 (looking-at "\\S-")) '("*"))
1989 ;; Description items cannot be numbered
1990 (unless (and bullet-rule-p
1991 (or (eq org-plain-list-ordered-item-terminator ?\))
1992 (org-at-item-description-p))) '("1."))
1993 (unless (and bullet-rule-p
1994 (or (eq org-plain-list-ordered-item-terminator ?.)
1995 (org-at-item-description-p))) '("1)"))))
1996 (len (length bullet-list))
1997 (item-index (- len (length (member current bullet-list))))
1998 (get-value (lambda (index) (nth (mod index len) bullet-list)))
1999 (new (cond
2000 ((member which bullet-list) which)
2001 ((numberp which) (funcall get-value which))
2002 ((eq 'previous which) (funcall get-value (1- item-index)))
2003 (t (funcall get-value (1+ item-index))))))
2004 ;; Use a short variation of `org-list-struct-fix-struct' as
2005 ;; there's no need to go through all the steps.
2006 (let ((old-struct (mapcar (lambda (e) (copy-alist e)) struct)))
2007 (org-list-set-bullet list-beg struct (org-list-bullet-string new))
2008 (org-list-struct-fix-bul struct prevs)
2009 (org-list-struct-fix-ind struct parents)
2010 (org-list-struct-apply-struct struct old-struct)))))
2012 ;;; Checkboxes
2014 (defun org-toggle-checkbox (&optional toggle-presence)
2015 "Toggle the checkbox in the current line.
2016 With prefix arg TOGGLE-PRESENCE, add or remove checkboxes. With
2017 double prefix, set checkbox to [-].
2019 When there is an active region, toggle status or presence of the
2020 first checkbox there, and make every item inside have the
2021 same status or presence, respectively.
2023 If the cursor is in a headline, apply this to all checkbox items
2024 in the text below the heading, taking as reference the first item
2025 in subtree, ignoring drawers."
2026 (interactive "P")
2027 (save-excursion
2028 (let* (singlep
2029 block-item
2030 lim-up
2031 lim-down
2032 (orderedp (ignore-errors (org-entry-get nil "ORDERED")))
2033 (bounds
2034 ;; In a region, start at first item in region
2035 (cond
2036 ((org-region-active-p)
2037 (let ((limit (region-end)))
2038 (goto-char (region-beginning))
2039 (if (org-list-search-forward org-item-beginning-re limit t)
2040 (setq lim-up (point-at-bol))
2041 (error "No item in region"))
2042 (setq lim-down (copy-marker limit))))
2043 ((org-on-heading-p)
2044 ;; On an heading, start at first item after drawers
2045 (let ((limit (save-excursion (outline-next-heading) (point))))
2046 (forward-line 1)
2047 (when (looking-at org-drawer-regexp)
2048 (re-search-forward "^[ \t]*:END:" limit nil))
2049 (if (org-list-search-forward org-item-beginning-re limit t)
2050 (setq lim-up (point-at-bol))
2051 (error "No item in subtree"))
2052 (setq lim-down (copy-marker limit))))
2053 ;; Just one item: set singlep flag
2054 ((org-at-item-p)
2055 (setq singlep t)
2056 (setq lim-up (point-at-bol)
2057 lim-down (point-at-eol)))
2058 (t (error "Not at an item or heading, and no active region"))))
2059 ;; determine the checkbox going to be applied to all items
2060 ;; within bounds
2061 (ref-checkbox
2062 (progn
2063 (goto-char lim-up)
2064 (let ((cbox (and (org-at-item-checkbox-p) (match-string 1))))
2065 (cond
2066 ((equal toggle-presence '(16)) "[-]")
2067 ((equal toggle-presence '(4))
2068 (unless cbox "[ ]"))
2069 ((equal "[ ]" cbox) "[X]")
2070 (t "[ ]"))))))
2071 ;; When an item is found within bounds, grab the full list at
2072 ;; point structure, then: 1. set checkbox of all its items
2073 ;; within bounds to ref-checkbox; 2. fix checkboxes of the whole
2074 ;; list; 3. move point after the list.
2075 (goto-char lim-up)
2076 (while (and (< (point) lim-down)
2077 (org-list-search-forward org-item-beginning-re
2078 lim-down 'move))
2079 (let* ((struct (org-list-struct))
2080 (struct-copy (mapcar (lambda (e) (copy-alist e)) struct))
2081 (parents (org-list-struct-parent-alist struct))
2082 (prevs (org-list-struct-prev-alist struct))
2083 (bottom (copy-marker (org-list-get-bottom-point struct)))
2084 (items-to-toggle (org-remove-if
2085 (lambda (e) (or (< e lim-up) (> e lim-down)))
2086 (mapcar 'car (cdr struct)))))
2087 (mapc (lambda (e) (org-list-set-checkbox
2088 e struct
2089 ;; if there is no box at item, leave as-is
2090 ;; unless function was called with C-u prefix
2091 (let ((cur-box (org-list-get-checkbox e struct)))
2092 (if (or cur-box (equal toggle-presence '(4)))
2093 ref-checkbox
2094 cur-box))))
2095 items-to-toggle)
2096 (setq block-item (org-list-struct-fix-box
2097 struct parents prevs orderedp))
2098 ;; Report some problems due to ORDERED status of subtree. If
2099 ;; only one box was being checked, throw an error, else,
2100 ;; only signal problems.
2101 (cond
2102 ((and singlep block-item (> lim-up block-item))
2103 (error
2104 "Checkbox blocked because of unchecked box at line %d"
2105 (org-current-line block-item)))
2106 (block-item
2107 (message
2108 "Checkboxes were removed due to unchecked box at line %d"
2109 (org-current-line block-item))))
2110 (goto-char bottom)
2111 (org-list-struct-apply-struct struct struct-copy))))
2112 (org-update-checkbox-count-maybe)))
2114 (defun org-reset-checkbox-state-subtree ()
2115 "Reset all checkboxes in an entry subtree."
2116 (interactive "*")
2117 (save-restriction
2118 (save-excursion
2119 (org-narrow-to-subtree)
2120 (org-show-subtree)
2121 (goto-char (point-min))
2122 (let ((end (point-max)))
2123 (while (< (point) end)
2124 (when (org-at-item-checkbox-p)
2125 (replace-match "[ ]" t t nil 1))
2126 (beginning-of-line 2))))
2127 (org-update-checkbox-count-maybe)))
2129 (defvar org-checkbox-statistics-hook nil
2130 "Hook that is run whenever Org thinks checkbox statistics should be updated.
2131 This hook runs even if checkbox rule in
2132 `org-list-automatic-rules' does not apply, so it can be used to
2133 implement alternative ways of collecting statistics
2134 information.")
2136 (defun org-update-checkbox-count-maybe ()
2137 "Update checkbox statistics unless turned off by user."
2138 (when (cdr (assq 'checkbox org-list-automatic-rules))
2139 (org-update-checkbox-count))
2140 (run-hooks 'org-checkbox-statistics-hook))
2142 (defun org-update-checkbox-count (&optional all)
2143 "Update the checkbox statistics in the current section.
2144 This will find all statistic cookies like [57%] and [6/12] and
2145 update them with the current numbers.
2147 With optional prefix argument ALL, do this for the whole buffer."
2148 (interactive "P")
2149 (save-excursion
2150 (let ((cookie-re "\\(\\(\\[[0-9]*%\\]\\)\\|\\(\\[[0-9]*/[0-9]*\\]\\)\\)")
2151 (box-re "^[ \t]*\\([-+*]\\|[0-9]+[.)]\\)[ \t]+\\(?:\\[@\\(?:start:\\)?[0-9]+\\][ \t]*\\)?\\(\\[[- X]\\]\\)")
2152 (recursivep
2153 (or (not org-hierarchical-checkbox-statistics)
2154 (string-match "\\<recursive\\>"
2155 (or (ignore-errors
2156 (org-entry-get nil "COOKIE_DATA"))
2157 ""))))
2158 (bounds (if all
2159 (cons (point-min) (point-max))
2160 (cons (or (ignore-errors (org-back-to-heading) (point))
2161 (point-min))
2162 (save-excursion (outline-next-heading) (point)))))
2163 (count-boxes
2164 (function
2165 ;; add checked boxes and boxes of all types in all
2166 ;; structures in STRUCTS to c-on and c-all, respectively.
2167 ;; This looks at RECURSIVEP value. If ITEM is nil, count
2168 ;; across the whole structure, else count only across
2169 ;; subtree whose ancestor is ITEM.
2170 (lambda (item structs)
2171 (mapc
2172 (lambda (s)
2173 (let* ((pre (org-list-struct-prev-alist s))
2174 (par (org-list-struct-parent-alist s))
2175 (items
2176 (cond
2177 ((and recursivep item) (org-list-get-subtree item s))
2178 (recursivep (mapcar 'car s))
2179 (item (org-list-get-children item s par))
2180 (t (org-list-get-all-items
2181 (org-list-get-top-point s) s pre))))
2182 (cookies (delq nil (mapcar
2183 (lambda (e)
2184 (org-list-get-checkbox e s))
2185 items))))
2186 (setq c-all (+ (length cookies) c-all)
2187 c-on (+ (org-count "[X]" cookies) c-on))))
2188 structs))))
2189 cookies-list backup-end structs-backup)
2190 (goto-char (car bounds))
2191 ;; 1. Build an alist for each cookie found within BOUNDS. The
2192 ;; key will be position at beginning of cookie and values
2193 ;; ending position, format of cookie, number of checked boxes
2194 ;; to report, and total number of boxes.
2195 (while (re-search-forward cookie-re (cdr bounds) t)
2196 (save-excursion
2197 (let ((c-on 0) (c-all 0))
2198 (save-match-data
2199 ;; There are two types of cookies: those at headings and those
2200 ;; at list items.
2201 (cond
2202 ((and (org-on-heading-p)
2203 (string-match "\\<todo\\>"
2204 (downcase
2205 (or (org-entry-get nil "COOKIE_DATA") "")))))
2206 ;; This cookie is at an heading, but specifically for
2207 ;; todo, not for checkboxes: skip it.
2208 ((org-on-heading-p)
2209 (setq backup-end (save-excursion
2210 (outline-next-heading) (point)))
2211 ;; This cookie is at an heading. Grab structure of
2212 ;; every list containing a checkbox between point and
2213 ;; next headline, and save them in STRUCTS-BACKUP
2214 (while (org-list-search-forward box-re backup-end 'move)
2215 (let* ((struct (org-list-struct))
2216 (bottom (org-list-get-bottom-point struct)))
2217 (push struct structs-backup)
2218 (goto-char bottom)))
2219 (funcall count-boxes nil structs-backup))
2220 ((org-at-item-p)
2221 ;; This cookie is at an item. Look in STRUCTS-BACKUP
2222 ;; to see if we have the structure of list at point in
2223 ;; it. Else compute the structure.
2224 (let ((item (point-at-bol)))
2225 (if (and backup-end (< item backup-end))
2226 (funcall count-boxes item structs-backup)
2227 (let ((struct (org-list-struct)))
2228 (setq backup-end (org-list-get-bottom-point struct)
2229 structs-backup (list struct)))
2230 (funcall count-boxes item structs-backup))))))
2231 ;; Build the cookies list, with appropriate information
2232 (push (list (match-beginning 1) ; cookie start
2233 (match-end 1) ; cookie end
2234 (match-beginning 2) ; percent?
2235 c-on ; checked boxes
2236 c-all) ; total boxes
2237 cookies-list))))
2238 ;; 2. Apply alist to buffer, in reverse order so positions stay
2239 ;; unchanged after cookie modifications.
2240 (mapc (lambda (cookie)
2241 (let* ((beg (car cookie))
2242 (end (nth 1 cookie))
2243 (percentp (nth 2 cookie))
2244 (checked (nth 3 cookie))
2245 (total (nth 4 cookie))
2246 (new (if percentp
2247 (format "[%d%%]" (/ (* 100 checked)
2248 (max 1 total)))
2249 (format "[%d/%d]" checked total))))
2250 (goto-char beg)
2251 (insert new)
2252 (delete-region (point) (+ (point) (- end beg)))))
2253 cookies-list))))
2255 (defun org-get-checkbox-statistics-face ()
2256 "Select the face for checkbox statistics.
2257 The face will be `org-done' when all relevant boxes are checked.
2258 Otherwise it will be `org-todo'."
2259 (if (match-end 1)
2260 (if (equal (match-string 1) "100%")
2261 'org-checkbox-statistics-done
2262 'org-checkbox-statistics-todo)
2263 (if (and (> (match-end 2) (match-beginning 2))
2264 (equal (match-string 2) (match-string 3)))
2265 'org-checkbox-statistics-done
2266 'org-checkbox-statistics-todo)))
2268 ;;; Misc Tools
2270 (defun org-apply-on-list (function init-value &rest args)
2271 "Call FUNCTION on each item of the list at point.
2272 FUNCTION must be called with at least one argument: INIT-VALUE,
2273 that will contain the value returned by the function at the
2274 previous item, plus ARGS extra arguments.
2276 FUNCTION is applied on items in reverse order.
2278 As an example, (org-apply-on-list (lambda (result) (1+ result)) 0)
2279 will return the number of items in the current list.
2281 Sublists of the list are skipped. Cursor is always at the
2282 beginning of the item."
2283 (let* ((struct (org-list-struct))
2284 (prevs (org-list-struct-prev-alist struct))
2285 (item (copy-marker (point-at-bol)))
2286 (all (org-list-get-all-items (marker-position item) struct prevs))
2287 (value init-value))
2288 (mapc (lambda (e)
2289 (goto-char e)
2290 (setq value (apply function value args)))
2291 (nreverse all))
2292 (goto-char item)
2293 value))
2295 (defun org-sort-list (&optional with-case sorting-type getkey-func compare-func)
2296 "Sort plain list items.
2297 The cursor may be at any item of the list that should be sorted.
2298 Sublists are not sorted. Checkboxes, if any, are ignored.
2300 Sorting can be alphabetically, numerically, by date/time as given by
2301 a time stamp, by a property or by priority.
2303 Comparing entries ignores case by default. However, with an
2304 optional argument WITH-CASE, the sorting considers case as well.
2306 The command prompts for the sorting type unless it has been given
2307 to the function through the SORTING-TYPE argument, which needs to
2308 be a character, \(?n ?N ?a ?A ?t ?T ?f ?F). Here is the precise
2309 meaning of each character:
2311 n Numerically, by converting the beginning of the item to a number.
2312 a Alphabetically. Only the first line of item is checked.
2313 t By date/time, either the first active time stamp in the entry, if
2314 any, or by the first inactive one. In a timer list, sort the timers.
2316 Capital letters will reverse the sort order.
2318 If the SORTING-TYPE is ?f or ?F, then GETKEY-FUNC specifies a
2319 function to be called with point at the beginning of the record.
2320 It must return either a string or a number that should serve as
2321 the sorting key for that record. It will then use COMPARE-FUNC to
2322 compare entries."
2323 (interactive "P")
2324 (let* ((case-func (if with-case 'identity 'downcase))
2325 (struct (org-list-struct))
2326 (prevs (org-list-struct-prev-alist struct))
2327 (start (org-list-get-list-begin (point-at-bol) struct prevs))
2328 (end (org-list-get-list-end (point-at-bol) struct prevs))
2329 (sorting-type
2330 (progn
2331 (message
2332 "Sort plain list: [a]lpha [n]umeric [t]ime [f]unc A/N/T/F means reversed:")
2333 (read-char-exclusive)))
2334 (getkey-func (and (= (downcase sorting-type) ?f)
2335 (org-icompleting-read "Sort using function: "
2336 obarray 'fboundp t nil nil)
2337 (intern getkey-func))))
2338 (message "Sorting items...")
2339 (save-restriction
2340 (narrow-to-region start end)
2341 (goto-char (point-min))
2342 (let* ((dcst (downcase sorting-type))
2343 (case-fold-search nil)
2344 (now (current-time))
2345 (sort-func (cond
2346 ((= dcst ?a) 'string<)
2347 ((= dcst ?f) compare-func)
2348 ((= dcst ?t) '<)
2349 (t nil)))
2350 (next-record (lambda ()
2351 (skip-chars-forward " \r\t\n")
2352 (beginning-of-line)))
2353 (end-record (lambda ()
2354 (goto-char (org-list-get-item-end-before-blank
2355 (point) struct))))
2356 (value-to-sort
2357 (lambda ()
2358 (when (looking-at "[ \t]*[-+*0-9.)]+\\([ \t]+\\[[- X]\\]\\)?[ \t]+")
2359 (cond
2360 ((= dcst ?n)
2361 (string-to-number (buffer-substring (match-end 0)
2362 (point-at-eol))))
2363 ((= dcst ?a)
2364 (buffer-substring (match-end 0) (point-at-eol)))
2365 ((= dcst ?t)
2366 (cond
2367 ;; If it is a timer list, convert timer to seconds
2368 ((org-at-item-timer-p)
2369 (org-timer-hms-to-secs (match-string 1)))
2370 ((or (re-search-forward org-ts-regexp (point-at-eol) t)
2371 (re-search-forward org-ts-regexp-both
2372 (point-at-eol) t))
2373 (org-time-string-to-seconds (match-string 0)))
2374 (t (org-float-time now))))
2375 ((= dcst ?f)
2376 (if getkey-func
2377 (let ((value (funcall getkey-func)))
2378 (if (stringp value)
2379 (funcall case-func value)
2380 value))
2381 (error "Invalid key function `%s'" getkey-func)))
2382 (t (error "Invalid sorting type `%c'" sorting-type)))))))
2383 (sort-subr (/= dcst sorting-type)
2384 next-record
2385 end-record
2386 value-to-sort
2388 sort-func)
2389 ;; Read and fix list again, as `sort-subr' probably destroyed
2390 ;; its structure.
2391 (org-list-repair)
2392 (run-hooks 'org-after-sorting-entries-or-items-hook)
2393 (message "Sorting items...done")))))
2395 ;;; Send and receive lists
2396 (defun org-list-parse-list (&optional delete)
2397 "Parse the list at point and maybe DELETE it.
2399 Return a list whose car is a symbol of list type, among
2400 `ordered', `unordered' and `descriptive'. Then, each item is a
2401 list whose elements are strings and other sub-lists. Inside
2402 strings, checkboxes are replaced by \"[CBON]\" and \"[CBOFF]\".
2404 For example, the following list:
2406 1. first item
2407 + sub-item one
2408 + [X] sub-item two
2409 more text in first item
2410 2. last item
2412 will be parsed as:
2414 \(ordered \(\"first item\"
2415 \(unordered \(\"sub-item one\"\) \(\"[CBON] sub-item two\"\)\)
2416 \"more text in first item\"\)
2417 \(\"last item\"\)\)
2419 Point is left at list end."
2420 (let* ((struct (org-list-struct))
2421 (prevs (org-list-struct-prev-alist struct))
2422 (parents (org-list-struct-parent-alist struct))
2423 (top (org-list-get-top-point struct))
2424 (bottom (org-list-get-bottom-point struct))
2426 (get-list-type
2427 (function
2428 ;; determine type of list by getting info on item POS in
2429 ;; STRUCT.
2430 (lambda (pos struct)
2431 (cond ((string-match "[0-9]" (org-list-get-bullet pos struct))
2432 'ordered)
2433 ((org-list-get-tag pos struct) 'descriptive)
2434 (t 'unordered)))))
2435 (parse-sublist
2436 (function
2437 ;; return a list whose car is list type and cdr a list of
2438 ;; items' body.
2439 (lambda (e)
2440 (cons (funcall get-list-type (car e) struct)
2441 (mapcar parse-item e)))))
2442 (parse-item
2443 (function
2444 ;; return a list containing text and any sublist inside
2445 ;; item.
2446 (lambda (e)
2447 (let ((start (save-excursion
2448 (goto-char e)
2449 (looking-at org-item-beginning-re)
2450 (match-end 0)))
2451 (childp (org-list-has-child-p e struct))
2452 (end (org-list-get-item-end e struct)))
2453 (if childp
2454 (let* ((children (org-list-get-children e struct parents))
2455 (body (list (funcall get-text start childp t))))
2456 (while children
2457 (let* ((first (car children))
2458 (sub (org-list-get-all-items first struct prevs))
2459 (last-c (car (last sub)))
2460 (last-end (org-list-get-item-end last-c struct)))
2461 (push (funcall parse-sublist sub) body)
2462 (setq children (cdr (member last-c children)))
2463 (unless (= (or (car children) end) last-end)
2464 (push (funcall get-text last-end (or (car children) end) nil)
2465 body))))
2466 (nreverse body))
2467 (list (funcall get-text start end t)))))))
2468 (get-text
2469 (function
2470 ;; return text between BEG and END, trimmed, with
2471 ;; checkboxes replaced if BOX is true.
2472 (lambda (beg end box)
2473 (let ((text (org-trim (buffer-substring beg end))))
2474 (if (and box
2475 (string-match
2476 "^\\(?:\\[@\\(?:start:\\)?[0-9]+\\][ \t]*\\)?\\[\\([xX ]\\)\\]"
2477 text))
2478 (replace-match
2479 (if (equal (match-string 1 text) " ") "CBOFF" "CBON")
2480 t nil text 1)
2481 text))))))
2482 ;; store output, take care of cursor position and deletion of
2483 ;; list, then return output.
2484 (setq out (funcall parse-sublist (org-list-get-all-items top struct prevs)))
2485 (goto-char top)
2486 (when delete
2487 (delete-region top bottom)
2488 (when (and (not (eq org-list-ending-method 'indent))
2489 (looking-at (org-list-end-re)))
2490 (replace-match "\n")))
2491 out))
2493 (defun org-list-make-subtree ()
2494 "Convert the plain list at point into a subtree."
2495 (interactive)
2496 (if (not (org-in-item-p))
2497 (error "Not in a list")
2498 (let ((list (org-list-parse-list t)) nstars)
2499 (save-excursion
2500 (if (ignore-errors
2501 (org-back-to-heading))
2502 (progn (looking-at org-complex-heading-regexp)
2503 (setq nstars (length (match-string 1))))
2504 (setq nstars 0)))
2505 (org-list-make-subtrees list (1+ nstars)))))
2507 (defun org-list-make-subtrees (list level)
2508 "Convert LIST into subtrees starting at LEVEL."
2509 (if (symbolp (car list))
2510 (org-list-make-subtrees (cdr list) level)
2511 (mapcar (lambda (item)
2512 (if (stringp item)
2513 (insert (make-string
2514 (if org-odd-levels-only
2515 (1- (* 2 level)) level) ?*) " " item "\n")
2516 (org-list-make-subtrees item (1+ level))))
2517 list)))
2519 (defun org-list-insert-radio-list ()
2520 "Insert a radio list template appropriate for this major mode."
2521 (interactive)
2522 (let* ((e (assq major-mode org-list-radio-list-templates))
2523 (txt (nth 1 e))
2524 name pos)
2525 (unless e (error "No radio list setup defined for %s" major-mode))
2526 (setq name (read-string "List name: "))
2527 (while (string-match "%n" txt)
2528 (setq txt (replace-match name t t txt)))
2529 (or (bolp) (insert "\n"))
2530 (setq pos (point))
2531 (insert txt)
2532 (goto-char pos)))
2534 (defun org-list-send-list (&optional maybe)
2535 "Send a transformed version of this list to the receiver position.
2536 With argument MAYBE, fail quietly if no transformation is defined for
2537 this list."
2538 (interactive)
2539 (catch 'exit
2540 (unless (org-at-item-p) (error "Not at a list item"))
2541 (save-excursion
2542 (re-search-backward "#\\+ORGLST" nil t)
2543 (unless (looking-at "[ \t]*#\\+ORGLST[: \t][ \t]*SEND[ \t]+\\([^ \t\r\n]+\\)[ \t]+\\([^ \t\r\n]+\\)\\([ \t]+.*\\)?")
2544 (if maybe
2545 (throw 'exit nil)
2546 (error "Don't know how to transform this list"))))
2547 (let* ((name (match-string 1))
2548 (transform (intern (match-string 2)))
2549 (bottom-point
2550 (save-excursion
2551 (re-search-forward
2552 "\\(\\\\end{comment}\\|@end ignore\\|-->\\)" nil t)
2553 (match-beginning 0)))
2554 (top-point
2555 (progn
2556 (re-search-backward "#\\+ORGLST" nil t)
2557 (re-search-forward org-item-beginning-re bottom-point t)
2558 (match-beginning 0)))
2559 (list (save-restriction
2560 (narrow-to-region top-point bottom-point)
2561 (org-list-parse-list)))
2562 beg txt)
2563 (unless (fboundp transform)
2564 (error "No such transformation function %s" transform))
2565 (let ((txt (funcall transform list)))
2566 ;; Find the insertion place
2567 (save-excursion
2568 (goto-char (point-min))
2569 (unless (re-search-forward
2570 (concat "BEGIN RECEIVE ORGLST +"
2571 name
2572 "\\([ \t]\\|$\\)") nil t)
2573 (error "Don't know where to insert translated list"))
2574 (goto-char (match-beginning 0))
2575 (beginning-of-line 2)
2576 (setq beg (point))
2577 (unless (re-search-forward (concat "END RECEIVE ORGLST +" name) nil t)
2578 (error "Cannot find end of insertion region"))
2579 (delete-region beg (point-at-bol))
2580 (goto-char beg)
2581 (insert txt "\n")))
2582 (message "List converted and installed at receiver location"))))
2584 (defun org-list-to-generic (list params)
2585 "Convert a LIST parsed through `org-list-parse-list' to other formats.
2586 Valid parameters PARAMS are
2588 :ustart String to start an unordered list
2589 :uend String to end an unordered list
2591 :ostart String to start an ordered list
2592 :oend String to end an ordered list
2594 :dstart String to start a descriptive list
2595 :dend String to end a descriptive list
2596 :dtstart String to start a descriptive term
2597 :dtend String to end a descriptive term
2598 :ddstart String to start a description
2599 :ddend String to end a description
2601 :splice When set to t, return only list body lines, don't wrap
2602 them into :[u/o]start and :[u/o]end. Default is nil.
2604 :istart String to start a list item
2605 :iend String to end a list item
2606 :isep String to separate items
2607 :lsep String to separate sublists
2609 :cboff String to insert for an unchecked checkbox
2610 :cbon String to insert for a checked checkbox"
2611 (interactive)
2612 (let* ((p params) sublist
2613 (splicep (plist-get p :splice))
2614 (ostart (plist-get p :ostart))
2615 (oend (plist-get p :oend))
2616 (ustart (plist-get p :ustart))
2617 (uend (plist-get p :uend))
2618 (dstart (plist-get p :dstart))
2619 (dend (plist-get p :dend))
2620 (dtstart (plist-get p :dtstart))
2621 (dtend (plist-get p :dtend))
2622 (ddstart (plist-get p :ddstart))
2623 (ddend (plist-get p :ddend))
2624 (istart (plist-get p :istart))
2625 (iend (plist-get p :iend))
2626 (isep (plist-get p :isep))
2627 (lsep (plist-get p :lsep))
2628 (cbon (plist-get p :cbon))
2629 (cboff (plist-get p :cboff))
2630 (export-item
2631 (function
2632 ;; Export an item ITEM of type TYPE. First string in item
2633 ;; is treated in a special way as it can bring extra
2634 ;; information that needs to be processed.
2635 (lambda (item type)
2636 (let ((fmt (if (eq type 'descriptive)
2637 (concat (org-trim istart) "%s" ddend iend isep)
2638 (concat istart "%s" iend isep)))
2639 (first (car item)))
2640 ;; Replace checkbox if any is found.
2641 (cond
2642 ((string-match "\\[CBON\\]" first)
2643 (setq first (replace-match cbon t t first)))
2644 ((string-match "\\[CBOFF\\]" first)
2645 (setq first (replace-match cboff t t first)))
2646 ((string-match "\\[-\\]" first)
2647 (setq first (replace-match "$\\boxminus$" t t first))))
2648 ;; Insert descriptive term if TYPE is `descriptive'.
2649 (when (and (eq type 'descriptive)
2650 (string-match "^\\(.*\\)[ \t]+::" first))
2651 (setq first (concat
2652 dtstart (org-trim (match-string 1 first)) dtend
2653 ddstart (org-trim (substring first (match-end 0))))))
2654 (setcar item first)
2655 (format fmt (mapconcat
2656 (lambda (e)
2657 (if (stringp e) e (funcall export-sublist e)))
2658 item isep))))))
2659 (export-sublist
2660 (function
2661 ;; Export sublist SUB
2662 (lambda (sub)
2663 (let* ((type (car sub))
2664 (items (cdr sub))
2665 (fmt (cond
2666 (splicep "%s")
2667 ((eq type 'ordered)
2668 (concat ostart "\n%s" oend))
2669 ((eq type 'descriptive)
2670 (concat dstart "\n%s" dend))
2671 (t (concat ustart "\n%s" uend)))))
2672 (format fmt (mapconcat
2673 (lambda (e) (funcall export-item e type))
2674 items lsep)))))))
2675 (concat (funcall export-sublist list) "\n")))
2677 (defun org-list-to-latex (list &optional params)
2678 "Convert LIST into a LaTeX list.
2679 LIST is as returned by `org-list-parse-list'. PARAMS is a property list
2680 with overruling parameters for `org-list-to-generic'."
2681 (org-list-to-generic
2682 list
2683 (org-combine-plists
2684 '(:splicep nil :ostart "\\begin{enumerate}" :oend "\\end{enumerate}"
2685 :ustart "\\begin{itemize}" :uend "\\end{itemize}"
2686 :dstart "\\begin{description}" :dend "\\end{description}"
2687 :dtstart "[" :dtend "] "
2688 :ddstart "" :ddend ""
2689 :istart "\\item " :iend ""
2690 :isep "\n" :lsep "\n"
2691 :cbon "\\texttt{[X]}" :cboff "\\texttt{[ ]}")
2692 params)))
2694 (defun org-list-to-html (list &optional params)
2695 "Convert LIST into a HTML list.
2696 LIST is as returned by `org-list-parse-list'. PARAMS is a property list
2697 with overruling parameters for `org-list-to-generic'."
2698 (org-list-to-generic
2699 list
2700 (org-combine-plists
2701 '(:splicep nil :ostart "<ol>" :oend "</ol>"
2702 :ustart "<ul>" :uend "</ul>"
2703 :dstart "<dl>" :dend "</dl>"
2704 :dtstart "<dt>" :dtend "</dt>"
2705 :ddstart "<dd>" :ddend "</dd>"
2706 :istart "<li>" :iend "</li>"
2707 :isep "\n" :lsep "\n"
2708 :cbon "<code>[X]</code>" :cboff "<code>[ ]</code>")
2709 params)))
2711 (defun org-list-to-texinfo (list &optional params)
2712 "Convert LIST into a Texinfo list.
2713 LIST is as returned by `org-list-parse-list'. PARAMS is a property list
2714 with overruling parameters for `org-list-to-generic'."
2715 (org-list-to-generic
2716 list
2717 (org-combine-plists
2718 '(:splicep nil :ostart "@itemize @minus" :oend "@end itemize"
2719 :ustart "@enumerate" :uend "@end enumerate"
2720 :dstart "@table @asis" :dend "@end table"
2721 :dtstart " " :dtend "\n"
2722 :ddstart "" :ddend ""
2723 :istart "@item\n" :iend ""
2724 :isep "\n" :lsep "\n"
2725 :cbon "@code{[X]}" :cboff "@code{[ ]}")
2726 params)))
2728 (provide 'org-list)
2730 ;; arch-tag: 73cf50c1-200f-4d1d-8a53-4e842a5b11c8
2731 ;;; org-list.el ends here