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