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