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