]> code.delx.au - gnu-emacs/blob - lisp/calendar/todo-mode.el
* calendar/todo-mode.el: Add command to rename todo files.
[gnu-emacs] / lisp / calendar / todo-mode.el
1 ;;; todo-mode.el --- facilities for making and maintaining todo lists
2
3 ;; Copyright (C) 1997, 1999, 2001-2013 Free Software Foundation, Inc.
4
5 ;; Author: Oliver Seidel <privat@os10000.net>
6 ;; Stephen Berman <stephen.berman@gmx.net>
7 ;; Maintainer: Stephen Berman <stephen.berman@gmx.net>
8 ;; Keywords: calendar, todo
9
10 ;; This file is part of GNU Emacs.
11
12 ;; GNU Emacs is free software: you can redistribute it and/or modify
13 ;; it under the terms of the GNU General Public License as published by
14 ;; the Free Software Foundation, either version 3 of the License, or
15 ;; (at your option) any later version.
16
17 ;; GNU Emacs is distributed in the hope that it will be useful,
18 ;; but WITHOUT ANY WARRANTY; without even the implied warranty of
19 ;; MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
20 ;; GNU General Public License for more details.
21
22 ;; You should have received a copy of the GNU General Public License
23 ;; along with GNU Emacs. If not, see <http://www.gnu.org/licenses/>.
24
25 ;;; Commentary:
26
27 ;; This package provides facilities for making, displaying, navigating
28 ;; and editing todo lists, which are prioritized lists of todo items.
29 ;; Todo lists are identified with named categories, so you can group
30 ;; together and separately prioritize thematically related todo items.
31 ;; Each category is stored in a file, which thus provides a further
32 ;; level of organization. You can create as many todo files, and in
33 ;; each as many categories, as you want.
34
35 ;; With Todo mode you can navigate among the items of a category, and
36 ;; between categories in the same and in different todo files. You
37 ;; can edit todo items, reprioritize them within their category, move
38 ;; them to another category, delete them, or mark items as done and
39 ;; store them separately from the not yet done items in a category.
40 ;; You can add new todo files, edit and delete them. You can add new
41 ;; categories, rename and delete them, move categories to another file
42 ;; and merge the items of two categories. You can also reorder the
43 ;; sequence of categories in a todo file for the purpose of
44 ;; navigation. You can display summary tables of the categories in a
45 ;; file and the types of items they contain. And you can compile
46 ;; lists of existing items from multiple categories in one or more
47 ;; todo files, which are filtered by various criteria.
48
49 ;; To get started, load this package and type `M-x todo-show'. This
50 ;; will prompt you for the name of the first todo file, its first
51 ;; category and the category's first item, create these and display
52 ;; them in Todo mode. Now you can insert further items into the list
53 ;; (i.e., the category) and assign them priorities by typing `i i'.
54
55 ;; You will probably find it convenient to give `todo-show' a global
56 ;; key binding in your init file, since it is one of the entry points
57 ;; to Todo mode; a good choice is `C-c t', since `todo-show' is
58 ;; bound to `t' in Todo mode.
59
60 ;; To see a list of all Todo mode commands and their key bindings,
61 ;; including other entry points, type `C-h m' in Todo mode. Consult
62 ;; the documentation strings of the commands for details of their use.
63 ;; The `todo' customization group and its subgroups list the options
64 ;; you can set to alter the behavior of many commands and various
65 ;; aspects of the display.
66
67 ;; This package is a new version of Oliver Seidel's todo-mode.el.
68 ;; While it retains the same basic organization and handling of todo
69 ;; lists and the basic UI, it significantly extends these and adds
70 ;; many features. This required also making changes to the internals,
71 ;; including the file format. If you have a todo file in old format,
72 ;; then the first time you invoke `todo-show' (i.e., before you have
73 ;; created any todo file in the current format), it will ask you
74 ;; whether to convert that file and show it. If you choose not to
75 ;; convert the old-style file at this time, you can do so later by
76 ;; calling the command `todo-convert-legacy-files'.
77
78 ;;; Code:
79
80 (require 'diary-lib)
81 ;; For cl-remove-duplicates (in todo-insertion-commands-args) and
82 ;; cl-oddp.
83 (require 'cl-lib)
84
85 ;; -----------------------------------------------------------------------------
86 ;;; Setting up todo files, categories, and items
87 ;; -----------------------------------------------------------------------------
88
89 (defcustom todo-directory (locate-user-emacs-file "todo/")
90 "Directory where user's todo files are saved."
91 :type 'directory
92 :group 'todo)
93
94 (defun todo-files (&optional archives)
95 "Default value of `todo-files-function'.
96 This returns the case-insensitive alphabetically sorted list of
97 file truenames in `todo-directory' with the extension
98 \".todo\". With non-nil ARCHIVES return the list of archive file
99 truenames (those with the extension \".toda\")."
100 (let ((files (if (file-exists-p todo-directory)
101 (mapcar 'file-truename
102 (directory-files todo-directory t
103 (if archives "\.toda$" "\.todo$") t)))))
104 (sort files (lambda (s1 s2) (let ((cis1 (upcase s1))
105 (cis2 (upcase s2)))
106 (string< cis1 cis2))))))
107
108 (defcustom todo-files-function 'todo-files
109 "Function returning the value of the variable `todo-files'.
110 This function should take an optional argument that, if non-nil,
111 makes it return the value of the variable `todo-archives'."
112 :type 'function
113 :group 'todo)
114
115 (defvar todo-files (funcall todo-files-function)
116 "List of truenames of user's todo files.")
117
118 (defvar todo-archives (funcall todo-files-function t)
119 "List of truenames of user's todo archives.")
120
121 (defvar todo-visited nil
122 "List of todo files visited in this session by `todo-show'.
123 Used to determine initial display according to the value of
124 `todo-show-first'.")
125
126 (defvar todo-file-buffers nil
127 "List of file names of live Todo mode buffers.")
128
129 (defvar todo-global-current-todo-file nil
130 "Variable holding name of current todo file.
131 Used by functions called from outside of Todo mode to visit the
132 current todo file rather than the default todo file (i.e. when
133 users option `todo-show-current-file' is non-nil).")
134
135 (defvar todo-current-todo-file nil
136 "Variable holding the name of the currently active todo file.")
137
138 (defvar todo-categories nil
139 "Alist of categories in the current todo file.
140 The elements are cons cells whose car is a category name and
141 whose cdr is a vector of the category's item counts. These are,
142 in order, the numbers of todo items, of todo items included in
143 the Diary, of done items and of archived items.")
144
145 (defvar todo-category-number 1
146 "Variable holding the number of the current todo category.
147 Todo categories are numbered starting from 1.")
148
149 (defvar todo-categories-with-marks nil
150 "Alist of categories and number of marked items they contain.")
151
152 (defconst todo-category-beg "--==-- "
153 "String marking beginning of category (inserted with its name).")
154
155 (defconst todo-category-done "==--== DONE "
156 "String marking beginning of category's done items.")
157
158 (defcustom todo-done-separator-string "="
159 "String determining the value of variable `todo-done-separator'.
160 If the string consists of a single character,
161 `todo-done-separator' will be the string made by repeating this
162 character for the width of the window, and the length is
163 automatically recalculated when the window width changes. If the
164 string consists of more (or less) than one character, it will be
165 the value of `todo-done-separator'."
166 :type 'string
167 :initialize 'custom-initialize-default
168 :set 'todo-reset-done-separator-string
169 :group 'todo-display)
170
171 (defun todo-done-separator ()
172 "Return string used as value of variable `todo-done-separator'."
173 (let ((sep todo-done-separator-string))
174 (propertize (if (= 1 (length sep))
175 (make-string (window-width) (string-to-char sep))
176 todo-done-separator-string)
177 'face 'todo-done-sep)))
178
179 (defvar todo-done-separator (todo-done-separator)
180 "String used to visually separate done from not done items.
181 Displayed as an overlay instead of `todo-category-done' when
182 done items are shown. Its value is determined by user option
183 `todo-done-separator-string'.")
184
185 (defvar todo-show-done-only nil
186 "If non-nil display only done items in current category.
187 Set by the command `todo-toggle-view-done-only' and used by
188 `todo-category-select'.")
189
190 (defcustom todo-nondiary-marker '("[" "]")
191 "List of strings surrounding item date to block diary inclusion.
192 The first string is inserted before the item date and must be a
193 non-empty string that does not match a diary date in order to
194 have its intended effect. The second string is inserted after
195 the diary date."
196 :type '(list string string)
197 :group 'todo-edit
198 :initialize 'custom-initialize-default
199 :set 'todo-reset-nondiary-marker)
200
201 (defconst todo-nondiary-start (nth 0 todo-nondiary-marker)
202 "String inserted before item date to block diary inclusion.")
203
204 (defconst todo-nondiary-end (nth 1 todo-nondiary-marker)
205 "String inserted after item date matching `todo-nondiary-start'.")
206
207 (defconst todo-month-name-array
208 (vconcat calendar-month-name-array (vector "*"))
209 "Array of month names, in order.
210 The final element is \"*\", indicating an unspecified month.")
211
212 (defconst todo-month-abbrev-array
213 (vconcat calendar-month-abbrev-array (vector "*"))
214 "Array of abbreviated month names, in order.
215 The final element is \"*\", indicating an unspecified month.")
216
217 (defconst todo-date-pattern
218 (let ((dayname (diary-name-pattern calendar-day-name-array nil t)))
219 (concat "\\(?4:\\(?5:" dayname "\\)\\|"
220 (let ((dayname)
221 (monthname (format "\\(?6:%s\\)" (diary-name-pattern
222 todo-month-name-array
223 todo-month-abbrev-array)))
224 (month "\\(?7:[0-9]+\\|\\*\\)")
225 (day "\\(?8:[0-9]+\\|\\*\\)")
226 (year "-?\\(?9:[0-9]+\\|\\*\\)"))
227 (mapconcat 'eval calendar-date-display-form ""))
228 "\\)"))
229 "Regular expression matching a todo item date header.")
230
231 ;; By itself this matches anything, because of the `?'; however, it's only
232 ;; used in the context of `todo-date-pattern' (but Emacs Lisp lacks
233 ;; lookahead).
234 (defconst todo-date-string-start
235 (concat "^\\(" (regexp-quote todo-nondiary-start) "\\|"
236 (regexp-quote diary-nonmarking-symbol) "\\)?")
237 "Regular expression matching part of item header before the date.")
238
239 (defcustom todo-done-string "DONE "
240 "Identifying string appended to the front of done todo items."
241 :type 'string
242 :initialize 'custom-initialize-default
243 :set 'todo-reset-done-string
244 :group 'todo-edit)
245
246 (defconst todo-done-string-start
247 (concat "^\\[" (regexp-quote todo-done-string))
248 "Regular expression matching start of done item.")
249
250 (defconst todo-item-start (concat "\\(" todo-date-string-start "\\|"
251 todo-done-string-start "\\)"
252 todo-date-pattern)
253 "String identifying start of a todo item.")
254
255 ;; -----------------------------------------------------------------------------
256 ;;; Todo mode display options
257 ;; -----------------------------------------------------------------------------
258
259 (defcustom todo-prefix ""
260 "String prefixed to todo items for visual distinction."
261 :type '(string :validate
262 (lambda (widget)
263 (when (string= (widget-value widget) todo-item-mark)
264 (widget-put
265 widget :error
266 "Invalid value: must be distinct from `todo-item-mark'")
267 widget)))
268 :initialize 'custom-initialize-default
269 :set 'todo-reset-prefix
270 :group 'todo-display)
271
272 (defcustom todo-number-prefix t
273 "Non-nil to prefix items with consecutively increasing integers.
274 These reflect the priorities of the items in each category."
275 :type 'boolean
276 :initialize 'custom-initialize-default
277 :set 'todo-reset-prefix
278 :group 'todo-display)
279
280 (defun todo-mode-line-control (cat)
281 "Return a mode line control for todo or archive file buffers.
282 Argument CAT is the name of the current todo category.
283 This function is the value of the user variable
284 `todo-mode-line-function'."
285 (let ((file (todo-short-file-name todo-current-todo-file)))
286 (format "%s category %d: %s" file todo-category-number cat)))
287
288 (defcustom todo-mode-line-function 'todo-mode-line-control
289 "Function that returns a mode line control for Todo mode buffers.
290 The function expects one argument holding the name of the current
291 todo category. The resulting control becomes the local value of
292 `mode-line-buffer-identification' in each Todo mode buffer."
293 :type 'function
294 :group 'todo-display)
295
296 (defcustom todo-highlight-item nil
297 "Non-nil means highlight items at point."
298 :type 'boolean
299 :initialize 'custom-initialize-default
300 :set 'todo-reset-highlight-item
301 :group 'todo-display)
302
303 (defcustom todo-wrap-lines t
304 "Non-nil to activate Visual Line mode and use wrap prefix."
305 :type 'boolean
306 :group 'todo-display)
307
308 (defcustom todo-indent-to-here 3
309 "Number of spaces to indent continuation lines of items.
310 This must be a positive number to ensure such items are fully
311 shown in the Fancy Diary display."
312 :type '(integer :validate
313 (lambda (widget)
314 (unless (> (widget-value widget) 0)
315 (widget-put widget :error
316 "Invalid value: must be a positive integer")
317 widget)))
318 :group 'todo-display)
319
320 (defun todo-indent ()
321 "Indent from point to `todo-indent-to-here'."
322 (indent-to todo-indent-to-here todo-indent-to-here))
323
324 (defcustom todo-show-with-done nil
325 "Non-nil to display done items in all categories."
326 :type 'boolean
327 :group 'todo-display)
328
329 ;; -----------------------------------------------------------------------------
330 ;;; Faces
331 ;; -----------------------------------------------------------------------------
332
333 (defface todo-mark
334 ;; '((t :inherit font-lock-warning-face))
335 '((((class color)
336 (min-colors 88)
337 (background light))
338 (:weight bold :foreground "Red1"))
339 (((class color)
340 (min-colors 88)
341 (background dark))
342 (:weight bold :foreground "Pink"))
343 (((class color)
344 (min-colors 16)
345 (background light))
346 (:weight bold :foreground "Red1"))
347 (((class color)
348 (min-colors 16)
349 (background dark))
350 (:weight bold :foreground "Pink"))
351 (((class color)
352 (min-colors 8))
353 (:foreground "red"))
354 (t
355 (:weight bold :inverse-video t)))
356 "Face for marks on marked items."
357 :group 'todo-faces)
358
359 (defface todo-prefix-string
360 ;; '((t :inherit font-lock-constant-face))
361 '((((class grayscale) (background light))
362 (:foreground "LightGray" :weight bold :underline t))
363 (((class grayscale) (background dark))
364 (:foreground "Gray50" :weight bold :underline t))
365 (((class color) (min-colors 88) (background light)) (:foreground "dark cyan"))
366 (((class color) (min-colors 88) (background dark)) (:foreground "Aquamarine"))
367 (((class color) (min-colors 16) (background light)) (:foreground "CadetBlue"))
368 (((class color) (min-colors 16) (background dark)) (:foreground "Aquamarine"))
369 (((class color) (min-colors 8)) (:foreground "magenta"))
370 (t (:weight bold :underline t)))
371 "Face for todo item prefix or numerical priority string."
372 :group 'todo-faces)
373
374 (defface todo-top-priority
375 ;; bold font-lock-comment-face
376 '((default :weight bold)
377 (((class grayscale) (background light)) :foreground "DimGray" :slant italic)
378 (((class grayscale) (background dark)) :foreground "LightGray" :slant italic)
379 (((class color) (min-colors 88) (background light)) :foreground "Firebrick")
380 (((class color) (min-colors 88) (background dark)) :foreground "chocolate1")
381 (((class color) (min-colors 16) (background light)) :foreground "red")
382 (((class color) (min-colors 16) (background dark)) :foreground "red1")
383 (((class color) (min-colors 8) (background light)) :foreground "red")
384 (((class color) (min-colors 8) (background dark)) :foreground "yellow")
385 (t :slant italic))
386 "Face for top priority todo item numerical priority string.
387 The item's priority number string has this face if the number is
388 less than or equal the category's top priority setting."
389 :group 'todo-faces)
390
391 (defface todo-nondiary
392 ;; '((t :inherit font-lock-type-face))
393 '((((class grayscale) (background light)) :foreground "Gray90" :weight bold)
394 (((class grayscale) (background dark)) :foreground "DimGray" :weight bold)
395 (((class color) (min-colors 88) (background light)) :foreground "ForestGreen")
396 (((class color) (min-colors 88) (background dark)) :foreground "PaleGreen")
397 (((class color) (min-colors 16) (background light)) :foreground "ForestGreen")
398 (((class color) (min-colors 16) (background dark)) :foreground "PaleGreen")
399 (((class color) (min-colors 8)) :foreground "green")
400 (t :weight bold :underline t))
401 "Face for non-diary markers around todo item date/time header."
402 :group 'todo-faces)
403
404 (defface todo-date
405 '((t :inherit diary))
406 "Face for the date string of a todo item."
407 :group 'todo-faces)
408
409 (defface todo-time
410 '((t :inherit diary-time))
411 "Face for the time string of a todo item."
412 :group 'todo-faces)
413
414 (defface todo-diary-expired
415 ;; Doesn't contrast enough with todo-date (= diary) face.
416 ;; ;; '((t :inherit warning))
417 ;; '((default :weight bold)
418 ;; (((class color) (min-colors 16)) :foreground "DarkOrange")
419 ;; (((class color)) :foreground "yellow"))
420 ;; bold font-lock-function-name-face
421 '((default :weight bold)
422 (((class color) (min-colors 88) (background light)) :foreground "Blue1")
423 (((class color) (min-colors 88) (background dark)) :foreground "LightSkyBlue")
424 (((class color) (min-colors 16) (background light)) :foreground "Blue")
425 (((class color) (min-colors 16) (background dark)) :foreground "LightSkyBlue")
426 (((class color) (min-colors 8)) :foreground "blue")
427 (t :inverse-video t))
428 "Face for expired dates of diary items."
429 :group 'todo-faces)
430
431 (defface todo-done-sep
432 ;; '((t :inherit font-lock-builtin-face))
433 '((((class grayscale) (background light)) :foreground "LightGray" :weight bold)
434 (((class grayscale) (background dark)) :foreground "DimGray" :weight bold)
435 (((class color) (min-colors 88) (background light)) :foreground "dark slate blue")
436 (((class color) (min-colors 88) (background dark)) :foreground "LightSteelBlue")
437 (((class color) (min-colors 16) (background light)) :foreground "Orchid")
438 (((class color) (min-colors 16) (background dark)) :foreground "LightSteelBlue")
439 (((class color) (min-colors 8)) :foreground "blue" :weight bold)
440 (t :weight bold))
441 "Face for separator string between done and not done todo items."
442 :group 'todo-faces)
443
444 (defface todo-done
445 ;; '((t :inherit font-lock-keyword-face))
446 '((((class grayscale) (background light)) :foreground "LightGray" :weight bold)
447 (((class grayscale) (background dark)) :foreground "DimGray" :weight bold)
448 (((class color) (min-colors 88) (background light)) :foreground "Purple")
449 (((class color) (min-colors 88) (background dark)) :foreground "Cyan1")
450 (((class color) (min-colors 16) (background light)) :foreground "Purple")
451 (((class color) (min-colors 16) (background dark)) :foreground "Cyan")
452 (((class color) (min-colors 8)) :foreground "cyan" :weight bold)
453 (t :weight bold))
454 "Face for done todo item header string."
455 :group 'todo-faces)
456
457 (defface todo-comment
458 ;; '((t :inherit font-lock-comment-face))
459 '((((class grayscale) (background light))
460 :foreground "DimGray" :weight bold :slant italic)
461 (((class grayscale) (background dark))
462 :foreground "LightGray" :weight bold :slant italic)
463 (((class color) (min-colors 88) (background light))
464 :foreground "Firebrick")
465 (((class color) (min-colors 88) (background dark))
466 :foreground "chocolate1")
467 (((class color) (min-colors 16) (background light))
468 :foreground "red")
469 (((class color) (min-colors 16) (background dark))
470 :foreground "red1")
471 (((class color) (min-colors 8) (background light))
472 :foreground "red")
473 (((class color) (min-colors 8) (background dark))
474 :foreground "yellow")
475 (t :weight bold :slant italic))
476 "Face for comments appended to done todo items."
477 :group 'todo-faces)
478
479 (defface todo-search
480 ;; '((t :inherit match))
481 '((((class color)
482 (min-colors 88)
483 (background light))
484 (:background "yellow1"))
485 (((class color)
486 (min-colors 88)
487 (background dark))
488 (:background "RoyalBlue3"))
489 (((class color)
490 (min-colors 8)
491 (background light))
492 (:foreground "black" :background "yellow"))
493 (((class color)
494 (min-colors 8)
495 (background dark))
496 (:foreground "white" :background "blue"))
497 (((type tty)
498 (class mono))
499 (:inverse-video t))
500 (t
501 (:background "gray")))
502 "Face for matches found by `todo-search'."
503 :group 'todo-faces)
504
505 (defface todo-button
506 ;; '((t :inherit widget-field))
507 '((((type tty))
508 (:foreground "black" :background "yellow3"))
509 (((class grayscale color)
510 (background light))
511 (:background "gray85"))
512 (((class grayscale color)
513 (background dark))
514 (:background "dim gray"))
515 (t
516 (:slant italic)))
517 "Face for buttons in table of categories."
518 :group 'todo-faces)
519
520 (defface todo-sorted-column
521 '((((type tty))
522 (:inverse-video t))
523 (((class color)
524 (background light))
525 (:background "grey85"))
526 (((class color)
527 (background dark))
528 (:background "grey85" :foreground "grey10"))
529 (t
530 (:background "gray")))
531 "Face for sorted column in table of categories."
532 :group 'todo-faces)
533
534 (defface todo-archived-only
535 ;; '((t (:inherit (shadow))))
536 '((((class color)
537 (background light))
538 (:foreground "grey50"))
539 (((class color)
540 (background dark))
541 (:foreground "grey70"))
542 (t
543 (:foreground "gray")))
544 "Face for archived-only category names in table of categories."
545 :group 'todo-faces)
546
547 (defface todo-category-string
548 ;; '((t :inherit font-lock-type-face))
549 '((((class grayscale) (background light)) :foreground "Gray90" :weight bold)
550 (((class grayscale) (background dark)) :foreground "DimGray" :weight bold)
551 (((class color) (min-colors 88) (background light)) :foreground "ForestGreen")
552 (((class color) (min-colors 88) (background dark)) :foreground "PaleGreen")
553 (((class color) (min-colors 16) (background light)) :foreground "ForestGreen")
554 (((class color) (min-colors 16) (background dark)) :foreground "PaleGreen")
555 (((class color) (min-colors 8)) :foreground "green")
556 (t :weight bold :underline t))
557 "Face for category-file header in Todo Filtered Items mode."
558 :group 'todo-faces)
559
560 ;; -----------------------------------------------------------------------------
561 ;;; Entering and exiting
562 ;; -----------------------------------------------------------------------------
563
564 (defcustom todo-visit-files-commands (list 'find-file 'dired-find-file)
565 "List of file finding commands for `todo-display-as-todo-file'.
566 Invoking these commands to visit a todo file or todo archive file
567 calls `todo-show' or `todo-find-archive', so that the file is
568 displayed correctly."
569 :type '(repeat function)
570 :group 'todo)
571
572 (defun todo-short-file-name (file)
573 "Return the short form of todo file FILE's name.
574 This lacks the extension and directory components."
575 (when (stringp file)
576 (file-name-sans-extension (file-name-nondirectory file))))
577
578 (defcustom todo-default-todo-file (todo-short-file-name
579 (car (funcall todo-files-function)))
580 "Todo file visited by first session invocation of `todo-show'."
581 :type (when todo-files
582 `(radio ,@(mapcar (lambda (f) (list 'const f))
583 (mapcar 'todo-short-file-name
584 (funcall todo-files-function)))))
585 :group 'todo)
586
587 (defcustom todo-show-current-file t
588 "Non-nil to make `todo-show' visit the current todo file.
589 Otherwise, `todo-show' always visits `todo-default-todo-file'."
590 :type 'boolean
591 :initialize 'custom-initialize-default
592 :set 'todo-set-show-current-file
593 :group 'todo)
594
595 (defcustom todo-show-first 'first
596 "What action to take on first use of `todo-show' on a file."
597 :type '(choice (const :tag "Show first category" first)
598 (const :tag "Show table of categories" table)
599 (const :tag "Show top priorities" top)
600 (const :tag "Show diary items" diary)
601 (const :tag "Show regexp items" regexp))
602 :group 'todo)
603
604 (defcustom todo-add-item-if-new-category t
605 "Non-nil to prompt for an item after adding a new category."
606 :type 'boolean
607 :group 'todo-edit)
608
609 (defcustom todo-initial-file "Todo"
610 "Default file name offered on adding first todo file."
611 :type 'string
612 :group 'todo)
613
614 (defcustom todo-initial-category "Todo"
615 "Default category name offered on initializing a new todo file."
616 :type 'string
617 :group 'todo)
618
619 (defcustom todo-category-completions-files nil
620 "List of files for building `todo-read-category' completions."
621 :type `(set ,@(mapcar (lambda (f) (list 'const f))
622 (mapcar 'todo-short-file-name
623 (funcall todo-files-function))))
624 :group 'todo)
625
626 (defcustom todo-completion-ignore-case nil
627 "Non-nil means case is ignored by `todo-read-*' functions."
628 :type 'boolean
629 :group 'todo)
630
631 ;;;###autoload
632 (defun todo-show (&optional solicit-file interactive)
633 "Visit a todo file and display one of its categories.
634
635 When invoked in Todo mode, prompt for which todo file to visit.
636 When invoked outside of Todo mode with non-nil prefix argument
637 SOLICIT-FILE prompt for which todo file to visit; otherwise visit
638 `todo-default-todo-file'. Subsequent invocations from outside
639 of Todo mode revisit this file or, with option
640 `todo-show-current-file' non-nil (the default), whichever todo
641 file was last visited.
642
643 If you call this command before you have created any todo file in
644 the current format, and you have an todo file in old format, it
645 will ask you whether to convert that file and show it.
646 Otherwise, calling this command before any todo file exists
647 prompts for a file name and an initial category (defaulting to
648 `todo-initial-file' and `todo-initial-category'), creates both of
649 these, visits the file and displays the category, and if option
650 `todo-add-item-if-new-category' is non-nil (the default), prompts
651 for the first item.
652
653 The first invocation of this command on an existing todo file
654 interacts with the option `todo-show-first': if its value is
655 `first' (the default), show the first category in the file; if
656 its value is `table', show the table of categories in the file;
657 if its value is one of `top', `diary' or `regexp', show the
658 corresponding saved top priorities, diary items, or regexp items
659 file, if any. Subsequent invocations always show the file's
660 current (i.e., last displayed) category.
661
662 In Todo mode just the category's unfinished todo items are shown
663 by default. The done items are hidden, but typing
664 `\\[todo-toggle-view-done-items]' displays them below the todo
665 items. With non-nil user option `todo-show-with-done' both todo
666 and done items are always shown on visiting a category.
667
668 Invoking this command in Todo Archive mode visits the
669 corresponding todo file, displaying the corresponding category."
670 (interactive "P\np")
671 (when todo-default-todo-file
672 (todo-check-file (todo-absolute-file-name todo-default-todo-file)))
673 (catch 'shown
674 ;; Before initializing the first todo first, check if there is a
675 ;; legacy todo file and if so, offer to convert to the current
676 ;; format and make it the first new todo file.
677 (unless todo-default-todo-file
678 (let ((legacy-todo-file (if (boundp 'todo-file-do)
679 todo-file-do
680 (locate-user-emacs-file "todo-do" ".todo-do"))))
681 (when (and (file-exists-p legacy-todo-file)
682 (y-or-n-p (concat "Do you want to convert a copy of your "
683 "old todo file to the new format? ")))
684 (when (todo-convert-legacy-files)
685 (throw 'shown nil)))))
686 (catch 'end
687 (let* ((cat)
688 (show-first todo-show-first)
689 (file (cond ((or solicit-file
690 (and interactive
691 (memq major-mode '(todo-mode
692 todo-archive-mode
693 todo-filtered-items-mode))))
694 (if (funcall todo-files-function)
695 (todo-read-file-name "Choose a todo file to visit: "
696 nil t)
697 (user-error "There are no todo files")))
698 ((and (eq major-mode 'todo-archive-mode)
699 ;; Called noninteractively via todo-quit
700 ;; to jump to corresponding category in
701 ;; todo file.
702 (not interactive))
703 (setq cat (todo-current-category))
704 (concat (file-name-sans-extension
705 todo-current-todo-file) ".todo"))
706 (t
707 (or todo-current-todo-file
708 (and todo-show-current-file
709 todo-global-current-todo-file)
710 (todo-absolute-file-name todo-default-todo-file)
711 (todo-add-file)))))
712 add-item first-file)
713 (unless todo-default-todo-file
714 ;; We just initialized the first todo file, so make it the default.
715 (setq todo-default-todo-file (todo-short-file-name file)
716 first-file t)
717 (todo-reevaluate-default-file-defcustom))
718 (unless (member file todo-visited)
719 ;; Can't setq t-c-t-f here, otherwise wrong file shown when
720 ;; todo-show is called from todo-show-categories-table.
721 (let ((todo-current-todo-file file))
722 (cond ((eq todo-show-first 'table)
723 (todo-show-categories-table))
724 ((memq todo-show-first '(top diary regexp))
725 (let* ((shortf (todo-short-file-name file))
726 (fi-file (todo-absolute-file-name
727 shortf todo-show-first)))
728 (when (eq todo-show-first 'regexp)
729 (let ((rxfiles (directory-files todo-directory t
730 ".*\\.todr$" t)))
731 (when (and rxfiles (> (length rxfiles) 1))
732 (let ((rxf (mapcar 'todo-short-file-name rxfiles)))
733 (setq fi-file (todo-absolute-file-name
734 (completing-read
735 "Choose a regexp items file: "
736 rxf) 'regexp))))))
737 (if (file-exists-p fi-file)
738 (set-window-buffer
739 (selected-window)
740 (set-buffer (find-file-noselect fi-file 'nowarn)))
741 (message "There is no %s file for %s"
742 (cond ((eq todo-show-first 'top)
743 "top priorities")
744 ((eq todo-show-first 'diary)
745 "diary items")
746 ((eq todo-show-first 'regexp)
747 "regexp items"))
748 shortf)
749 (setq todo-show-first 'first)))))))
750 (when (or (member file todo-visited)
751 (eq todo-show-first 'first))
752 (unless (todo-check-file file) (throw 'end nil))
753 (set-window-buffer (selected-window)
754 (set-buffer (find-file-noselect file 'nowarn)))
755 ;; When quitting an archive file, show the corresponding
756 ;; category in the corresponding todo file, if it exists.
757 (when (assoc cat todo-categories)
758 (setq todo-category-number (todo-category-number cat)))
759 ;; If this is a new todo file, add its first category.
760 (when (zerop (buffer-size))
761 (let (cat-added)
762 (unwind-protect
763 (setq todo-category-number
764 (todo-add-category todo-current-todo-file "")
765 add-item todo-add-item-if-new-category
766 cat-added t)
767 (if cat-added
768 ;; If the category was added, save the file now, so we
769 ;; don't risk having an empty todo file, which would
770 ;; signal an error if we tried to visit it later,
771 ;; since doing that looks for category boundaries.
772 (save-buffer 0)
773 ;; If user cancels before adding the category, clean up
774 ;; and exit, so we have a fresh slate the next time.
775 (delete-file file)
776 ;; (setq todo-files (funcall todo-files-function))
777 (setq todo-files (delete file todo-files))
778 (when first-file
779 (setq todo-default-todo-file nil
780 todo-current-todo-file nil)
781 (todo-reevaluate-default-file-defcustom))
782 (kill-buffer)
783 (keyboard-quit)))))
784 (save-excursion (todo-category-select))
785 (when add-item (todo-basic-insert-item)))
786 (setq todo-show-first show-first)
787 (add-to-list 'todo-visited file)))))
788
789 (defun todo-save ()
790 "Save the current todo file."
791 (interactive)
792 (cond ((eq major-mode 'todo-filtered-items-mode)
793 (todo-check-filtered-items-file)
794 (todo-save-filtered-items-buffer))
795 (t
796 (save-buffer))))
797
798 (defvar todo-descending-counts)
799
800 (defun todo-quit ()
801 "Exit the current Todo-related buffer.
802 Depending on the specific mode, this either kills the buffer or
803 buries it and restores state as needed."
804 (interactive)
805 (let ((buf (current-buffer)))
806 (cond ((eq major-mode 'todo-categories-mode)
807 ;; Postpone killing buffer till after calling todo-show, to
808 ;; prevent killing todo-mode buffer.
809 (setq todo-descending-counts nil)
810 ;; Ensure todo-show calls todo-show-categories-table only on
811 ;; first invocation per file.
812 (when (eq todo-show-first 'table)
813 (add-to-list 'todo-visited todo-current-todo-file))
814 (todo-show)
815 (kill-buffer buf))
816 ((eq major-mode 'todo-filtered-items-mode)
817 (kill-buffer)
818 (unless (eq major-mode 'todo-mode) (todo-show)))
819 ((eq major-mode 'todo-archive-mode)
820 ;; Have to write a newly created archive to file to avoid
821 ;; subsequent errors.
822 (todo-save)
823 (let ((todo-file (concat todo-directory
824 (todo-short-file-name todo-current-todo-file)
825 ".todo")))
826 (if (todo-check-file todo-file)
827 (todo-show)
828 (message "There is no todo file for this archive")))
829 ;; When todo-check-file runs in todo-show, it kills the
830 ;; buffer if the archive file was deleted externally.
831 (when (buffer-live-p buf) (bury-buffer buf)))
832 ((eq major-mode 'todo-mode)
833 (todo-save)
834 ;; If we just quit archive mode, just burying the buffer
835 ;; in todo-mode would return to archive.
836 (set-window-buffer (selected-window)
837 (set-buffer (other-buffer)))
838 (bury-buffer buf)))))
839
840 ;; -----------------------------------------------------------------------------
841 ;;; Navigation between and within categories
842 ;; -----------------------------------------------------------------------------
843
844 (defcustom todo-skip-archived-categories nil
845 "Non-nil to handle categories with only archived items specially.
846
847 Sequential category navigation using \\[todo-forward-category]
848 or \\[todo-backward-category] skips categories that contain only
849 archived items. Other commands still recognize these categories.
850 In Todo Categories mode (\\[todo-show-categories-table]) these
851 categories shown in `todo-archived-only' face and pressing the
852 category button visits the category in the archive instead of the
853 todo file."
854 :type 'boolean
855 :group 'todo-display)
856
857 (defun todo-forward-category (&optional back)
858 "Visit the numerically next category in this todo file.
859 If the current category is the highest numbered, visit the first
860 category. With non-nil argument BACK, visit the numerically
861 previous category (the highest numbered one, if the current
862 category is the first)."
863 (interactive)
864 (setq todo-category-number
865 (1+ (mod (- todo-category-number (if back 2 0))
866 (length todo-categories))))
867 (when todo-skip-archived-categories
868 (while (and (zerop (todo-get-count 'todo))
869 (zerop (todo-get-count 'done))
870 (not (zerop (todo-get-count 'archived))))
871 (setq todo-category-number
872 (apply (if back '1- '1+) (list todo-category-number)))))
873 (todo-category-select)
874 (goto-char (point-min)))
875
876 (defun todo-backward-category ()
877 "Visit the numerically previous category in this todo file.
878 If the current category is the highest numbered, visit the first
879 category."
880 (interactive)
881 (todo-forward-category t))
882
883 (defvar todo-categories-buffer)
884
885 (defun todo-jump-to-category (&optional file where)
886 "Prompt for a category in a todo file and jump to it.
887
888 With non-nil FILE (interactively a prefix argument), prompt for a
889 specific todo file and choose (with TAB completion) a category
890 in it to jump to; otherwise, choose and jump to any category in
891 either the current todo file or a file in
892 `todo-category-completions-files'.
893
894 Also accept a non-existing category name and ask whether to add a
895 new category by that name; on confirmation, add it and jump to
896 that category, and if option `todo-add-item-if-new-category' is
897 non-nil (the default), then prompt for the first item.
898
899 In noninteractive calls non-nil WHERE specifies either the goal
900 category or its file. If its value is `archive', the choice of
901 categories is restricted to the current archive file or the
902 archive you were prompted to choose; this is used by
903 `todo-jump-to-archive-category'. If its value is the name of a
904 category, jump directly to that category; this is used in Todo
905 Categories mode."
906 (interactive "P")
907 ;; If invoked outside of Todo mode and there is not yet any Todo
908 ;; file, initialize one.
909 (if (null (funcall todo-files-function))
910 (todo-show)
911 (let* ((archive (eq where 'archive))
912 (cat (unless archive where))
913 (file0 (when cat ; We're in Todo Categories mode.
914 ;; With non-nil `todo-skip-archived-categories'
915 ;; jump to archive file of a category with only
916 ;; archived items.
917 (if (and todo-skip-archived-categories
918 (zerop (todo-get-count 'todo cat))
919 (zerop (todo-get-count 'done cat))
920 (not (zerop (todo-get-count 'archived cat))))
921 (concat (file-name-sans-extension
922 todo-current-todo-file) ".toda")
923 ;; Otherwise, jump to current todo file.
924 todo-current-todo-file)))
925 (len (length todo-categories))
926 (cat+file (unless cat
927 (todo-read-category "Jump to category: "
928 (if archive 'archive) file)))
929 (add-item (and todo-add-item-if-new-category
930 (> (length todo-categories) len)))
931 (category (or cat (car cat+file))))
932 (unless cat (setq file0 (cdr cat+file)))
933 (with-current-buffer (find-file-noselect file0 'nowarn)
934 (setq todo-current-todo-file file0)
935 ;; If called from Todo Categories mode, clean up before jumping.
936 (if (string= (buffer-name) todo-categories-buffer)
937 (kill-buffer))
938 (set-window-buffer (selected-window)
939 (set-buffer (find-buffer-visiting file0)))
940 (unless todo-global-current-todo-file
941 (setq todo-global-current-todo-file todo-current-todo-file))
942 (todo-category-number category)
943 (todo-category-select)
944 (goto-char (point-min))
945 (when add-item (todo-basic-insert-item))))))
946
947 (defun todo-next-item (&optional count)
948 "Move point down to the beginning of the next item.
949 With positive numerical prefix COUNT, move point COUNT items
950 downward.
951
952 If the category's done items are hidden, this command also moves
953 point to the empty line below the last todo item from any higher
954 item in the category, i.e., when invoked with or without a prefix
955 argument. If the category's done items are visible, this command
956 called with a prefix argument only moves point to a lower item,
957 e.g., with point on the last todo item and called with prefix 1,
958 it moves point to the first done item; but if called with point
959 on the last todo item without a prefix argument, it moves point
960 the the empty line above the done items separator."
961 (interactive "p")
962 ;; It's not worth the trouble to allow prefix arg value < 1, since
963 ;; we have the corresponding command.
964 (cond ((and current-prefix-arg (< count 1))
965 (user-error "The prefix argument must be a positive number"))
966 (current-prefix-arg
967 (todo-forward-item count))
968 (t
969 (todo-forward-item))))
970
971 (defun todo-previous-item (&optional count)
972 "Move point up to start of item with next higher priority.
973 With positive numerical prefix COUNT, move point COUNT items
974 upward.
975
976 If the category's done items are visible, this command called
977 with a prefix argument only moves point to a higher item, e.g.,
978 with point on the first done item and called with prefix 1, it
979 moves to the last todo item; but if called with point on the
980 first done item without a prefix argument, it moves point the the
981 empty line above the done items separator."
982 (interactive "p")
983 ;; Avoid moving to bob if on the first item but not at bob.
984 (when (> (line-number-at-pos) 1)
985 ;; It's not worth the trouble to allow prefix arg value < 1, since
986 ;; we have the corresponding command.
987 (cond ((and current-prefix-arg (< count 1))
988 (user-error "The prefix argument must be a positive number"))
989 (current-prefix-arg
990 (todo-backward-item count))
991 (t
992 (todo-backward-item)))))
993
994 ;; -----------------------------------------------------------------------------
995 ;;; Display toggle commands
996 ;; -----------------------------------------------------------------------------
997
998 (defun todo-toggle-prefix-numbers ()
999 "Hide item numbering if shown, show if hidden."
1000 (interactive)
1001 (save-excursion
1002 (save-restriction
1003 (goto-char (point-min))
1004 (let* ((ov (todo-get-overlay 'prefix))
1005 (show-done (re-search-forward todo-done-string-start nil t))
1006 (todo-show-with-done show-done)
1007 (todo-number-prefix (not (equal (overlay-get ov 'before-string)
1008 "1 "))))
1009 (if (eq major-mode 'todo-filtered-items-mode)
1010 (todo-prefix-overlays)
1011 (todo-category-select))))))
1012
1013 (defun todo-toggle-view-done-items ()
1014 "Show hidden or hide visible done items in current category."
1015 (interactive)
1016 (if (zerop (todo-get-count 'done (todo-current-category)))
1017 (message "There are no done items in this category.")
1018 (let ((opoint (point)))
1019 (goto-char (point-min))
1020 (let* ((shown (re-search-forward todo-done-string-start nil t))
1021 (todo-show-with-done (not shown)))
1022 (todo-category-select)
1023 (goto-char opoint)
1024 ;; If start of done items sections is below the bottom of the
1025 ;; window, make it visible.
1026 (unless shown
1027 (setq shown (progn
1028 (goto-char (point-min))
1029 (re-search-forward todo-done-string-start nil t)))
1030 (if (not (pos-visible-in-window-p shown))
1031 (recenter)
1032 (goto-char opoint)))))))
1033
1034 (defun todo-toggle-view-done-only ()
1035 "Switch between displaying only done or only todo items."
1036 (interactive)
1037 (setq todo-show-done-only (not todo-show-done-only))
1038 (todo-category-select))
1039
1040 (defun todo-toggle-item-highlighting ()
1041 "Highlight or unhighlight the todo item the cursor is on."
1042 (interactive)
1043 (eval-when-compile (require 'hl-line))
1044 (when (memq major-mode
1045 '(todo-mode todo-archive-mode todo-filtered-items-mode))
1046 (if hl-line-mode
1047 (hl-line-mode -1)
1048 (hl-line-mode 1))))
1049
1050 (defun todo-toggle-item-header ()
1051 "Hide or show item date-time headers in the current file.
1052 With done items, this hides only the done date-time string, not
1053 the the original date-time string."
1054 (interactive)
1055 (save-excursion
1056 (save-restriction
1057 (goto-char (point-min))
1058 (let ((ov (todo-get-overlay 'header)))
1059 (if ov
1060 (remove-overlays 1 (1+ (buffer-size)) 'todo 'header)
1061 (widen)
1062 (goto-char (point-min))
1063 (while (not (eobp))
1064 (when (re-search-forward
1065 (concat todo-item-start
1066 "\\( " diary-time-regexp "\\)?"
1067 (regexp-quote todo-nondiary-end) "? ")
1068 nil t)
1069 (setq ov (make-overlay (match-beginning 0) (match-end 0) nil t))
1070 (overlay-put ov 'todo 'header)
1071 (overlay-put ov 'display ""))
1072 (todo-forward-item)))))))
1073
1074 ;; -----------------------------------------------------------------------------
1075 ;;; File and category editing
1076 ;; -----------------------------------------------------------------------------
1077
1078 (defun todo-add-file ()
1079 "Name and initialize a new todo file.
1080 Interactively, prompt for a category and display it, and if
1081 option `todo-add-item-if-new-category' is non-nil (the default),
1082 prompt for the first item.
1083 Noninteractively, return the name of the new file."
1084 (interactive)
1085 (let* ((prompt (concat "Enter name of new todo file "
1086 "(TAB or SPC to see current names): "))
1087 (file (todo-read-file-name prompt)))
1088 (with-current-buffer (get-buffer-create file)
1089 (erase-buffer)
1090 (write-region (point-min) (point-max) file nil 'nomessage nil t)
1091 (kill-buffer file))
1092 (setq todo-files (funcall todo-files-function))
1093 (todo-reevaluate-filelist-defcustoms)
1094 (if (called-interactively-p 'any)
1095 (progn
1096 (set-window-buffer (selected-window)
1097 (set-buffer (find-file-noselect file)))
1098 (setq todo-current-todo-file file)
1099 (todo-show))
1100 file)))
1101
1102 (defun todo-rename-file (&optional arg)
1103 "Rename the current todo file.
1104 With prefix ARG, prompt for a todo file and rename it.
1105 If there are corresponding archive or filtered items files,
1106 rename these accordingly. If there are live buffers visiting
1107 these files, also rename them accordingly."
1108 (interactive "P")
1109 (let* ((oname (or (and arg
1110 (todo-read-file-name "Choose a file to rename: "
1111 nil t))
1112 (buffer-file-name)))
1113 (soname (todo-short-file-name oname))
1114 (nname (todo-read-file-name "New name for this file: "))
1115 (snname (todo-short-file-name nname))
1116 (files (directory-files todo-directory t
1117 (concat ".*" (regexp-quote soname)
1118 ".*\.tod[aorty]$") t)))
1119 (dolist (f files)
1120 (let ((sfname (todo-short-file-name f))
1121 (fext (file-name-extension f t))
1122 (fbuf (find-buffer-visiting f)))
1123 (when (string-match (regexp-quote soname) sfname)
1124 (let* ((snfname (replace-match snname t t sfname))
1125 (nfname (concat todo-directory snfname fext)))
1126 (rename-file f nfname)
1127 (when fbuf
1128 (with-current-buffer fbuf
1129 (set-visited-file-name nfname t t)
1130 (cond ((member fext '(".todo" ".toda"))
1131 (setq todo-current-todo-file (buffer-file-name))
1132 (setq mode-line-buffer-identification
1133 (funcall todo-mode-line-function
1134 (todo-current-category))))
1135 (t
1136 (rename-buffer
1137 (replace-regexp-in-string
1138 (regexp-quote soname) snfname))))))))))))
1139
1140 (defun todo-delete-file ()
1141 "Delete the current todo, archive or filtered items file.
1142 If the todo file has a corresponding archive file, or vice versa,
1143 prompt whether to delete that as well. Also kill the buffers
1144 visiting the deleted files."
1145 (interactive)
1146 (let* ((file1 (buffer-file-name))
1147 (todo (eq major-mode 'todo-mode))
1148 (archive (eq major-mode 'todo-archive-mode))
1149 (filtered (eq major-mode 'todo-filtered-items-mode))
1150 (file1-sn (todo-short-file-name file1))
1151 (file2 (concat todo-directory file1-sn (cond (todo ".toda")
1152 (archive ".todo"))))
1153 (buf1 (current-buffer))
1154 (buf2 (when file2 (find-buffer-visiting file2)))
1155 (prompt1 (concat "Delete " (cond (todo "todo")
1156 (archive "archive")
1157 (filtered "filtered items"))
1158 " file \"%s\"? "))
1159 (prompt2 (concat "Also delete the corresponding "
1160 (cond (todo "archive") (archive "todo")) " file "
1161 (when buf2 "and kill the buffer visiting it? ")))
1162 (delete1 (yes-or-no-p (format prompt1 file1-sn)))
1163 (delete2 (when (and delete1 (or (file-exists-p file2) buf2))
1164 (yes-or-no-p prompt2))))
1165 (when delete1
1166 (when (file-exists-p file1) (delete-file file1))
1167 (setq todo-visited (delete file1 todo-visited))
1168 (kill-buffer buf1)
1169 (when delete2
1170 (when (file-exists-p file2) (delete-file file2))
1171 (setq todo-visited (delete file2 todo-visited))
1172 (and buf2 (kill-buffer buf2)))
1173 (setq todo-files (funcall todo-files-function)
1174 todo-archives (funcall todo-files-function t))
1175 (when (or (string= file1-sn todo-default-todo-file)
1176 (and delete2 (string= file1-sn todo-default-todo-file)))
1177 (setq todo-default-todo-file (todo-short-file-name (car todo-files))))
1178 (when (or (string= file1 todo-global-current-todo-file)
1179 (and delete2 (string= file2 todo-global-current-todo-file)))
1180 (setq todo-global-current-todo-file nil))
1181 (todo-reevaluate-filelist-defcustoms)
1182 (message (concat (cond (todo "Todo") (archive "Archive")) " file \"%s\" "
1183 (when delete2
1184 (concat "and its "
1185 (cond (todo "archive") (archive "todo"))
1186 " file "))
1187 "deleted") file1-sn))))
1188
1189 (defvar todo-edit-buffer "*Todo Edit*"
1190 "Name of current buffer in Todo Edit mode.")
1191
1192 (defun todo-edit-file ()
1193 "Put current buffer in `todo-edit-mode'.
1194 This makes the entire file visible and the buffer writeable and
1195 you can use the self-insertion keys and standard Emacs editing
1196 commands to make changes. To return to Todo mode, type
1197 \\[todo-edit-quit]. This runs a file format check, signaling
1198 an error if the format has become invalid. However, this check
1199 cannot tell if the number of items changed, which could result in
1200 the file containing inconsistent information. For this reason
1201 this command should be used with caution."
1202 (interactive)
1203 (widen)
1204 (todo-edit-mode)
1205 (remove-overlays)
1206 (message "%s" (substitute-command-keys
1207 (concat "Type \\[todo-edit-quit] to check file format "
1208 "validity and return to Todo mode.\n"))))
1209
1210 (defun todo-add-category (&optional file cat)
1211 "Add a new category to a todo file.
1212
1213 Called interactively with prefix argument FILE, prompt for a file
1214 and then for a new category to add to that file, otherwise prompt
1215 just for a category to add to the current todo file. After
1216 adding the category, visit it in Todo mode and if option
1217 `todo-add-item-if-new-category' is non-nil (the default), prompt
1218 for the first item.
1219
1220 Non-interactively, add category CAT to file FILE; if FILE is nil,
1221 add CAT to the current todo file. After adding the category,
1222 return the new category number."
1223 (interactive "P")
1224 (let (catfil file0)
1225 ;; If cat is passed from caller, don't prompt, unless it is "",
1226 ;; which means the file was just added and has no category yet.
1227 (if (and cat (> (length cat) 0))
1228 (setq file0 (or (and (stringp file) file)
1229 todo-current-todo-file))
1230 (setq catfil (todo-read-category "Enter a new category name: "
1231 'add (when (called-interactively-p 'any)
1232 file))
1233 cat (car catfil)
1234 file0 (if (called-interactively-p 'any)
1235 (cdr catfil)
1236 file)))
1237 (find-file file0)
1238 (let ((counts (make-vector 4 0)) ; [todo diary done archived]
1239 (num (1+ (length todo-categories)))
1240 (buffer-read-only nil))
1241 (setq todo-current-todo-file file0)
1242 (setq todo-categories (append todo-categories
1243 (list (cons cat counts))))
1244 (widen)
1245 (goto-char (point-max))
1246 (save-excursion ; Save point for todo-category-select.
1247 (insert todo-category-beg cat "\n\n" todo-category-done "\n"))
1248 (todo-update-categories-sexp)
1249 ;; If invoked by user, display the newly added category, if
1250 ;; called programmatically return the category number to the
1251 ;; caller.
1252 (if (called-interactively-p 'any)
1253 (progn
1254 (setq todo-category-number num)
1255 (todo-category-select)
1256 (when todo-add-item-if-new-category
1257 (todo-basic-insert-item)))
1258 num))))
1259
1260 (defun todo-rename-category ()
1261 "Rename current todo category.
1262 If this file has an archive containing this category, rename the
1263 category there as well."
1264 (interactive)
1265 (let* ((cat (todo-current-category))
1266 (new (read-from-minibuffer
1267 (format "Rename category \"%s\" to: " cat))))
1268 (setq new (todo-validate-name new 'category))
1269 (let* ((ofile todo-current-todo-file)
1270 (archive (concat (file-name-sans-extension ofile) ".toda"))
1271 (buffers (append (list ofile)
1272 (unless (zerop (todo-get-count 'archived cat))
1273 (list archive)))))
1274 (dolist (buf buffers)
1275 (with-current-buffer (find-file-noselect buf)
1276 (let (buffer-read-only)
1277 (setq todo-categories (todo-set-categories))
1278 (save-excursion
1279 (save-restriction
1280 (setcar (assoc cat todo-categories) new)
1281 (widen)
1282 (goto-char (point-min))
1283 (todo-update-categories-sexp)
1284 (re-search-forward (concat (regexp-quote todo-category-beg)
1285 "\\(" (regexp-quote cat) "\\)\n")
1286 nil t)
1287 (replace-match new t t nil 1)))))))
1288 (force-mode-line-update))
1289 (save-excursion (todo-category-select)))
1290
1291 (defun todo-delete-category (&optional arg)
1292 "Delete current todo category provided it contains no items.
1293 With prefix ARG delete the category even if it does contain
1294 todo or done items."
1295 (interactive "P")
1296 (let* ((file todo-current-todo-file)
1297 (cat (todo-current-category))
1298 (todo (todo-get-count 'todo cat))
1299 (done (todo-get-count 'done cat))
1300 (archived (todo-get-count 'archived cat)))
1301 (if (and (not arg)
1302 (or (> todo 0) (> done 0)))
1303 (message "%s" (substitute-command-keys
1304 (concat "To delete a non-empty category, "
1305 "type C-u \\[todo-delete-category].")))
1306 (when (cond ((= (length todo-categories) 1)
1307 (todo-y-or-n-p
1308 (concat "This is the only category in this file; "
1309 "deleting it will also delete the file.\n"
1310 "Do you want to proceed? ")))
1311 ((> archived 0)
1312 (todo-y-or-n-p (concat "This category has archived items; "
1313 "the archived category will remain\n"
1314 "after deleting the todo category. "
1315 "Do you still want to delete it\n"
1316 "(see `todo-skip-archived-categories' "
1317 "for another option)? ")))
1318 (t
1319 (todo-y-or-n-p (concat "Permanently remove category \"" cat
1320 "\"" (and arg " and all its entries")
1321 "? "))))
1322 (widen)
1323 (let ((buffer-read-only)
1324 (beg (re-search-backward
1325 (concat "^" (regexp-quote (concat todo-category-beg cat))
1326 "\n") nil t))
1327 (end (if (re-search-forward
1328 (concat "\n\\(" (regexp-quote todo-category-beg)
1329 ".*\n\\)") nil t)
1330 (match-beginning 1)
1331 (point-max))))
1332 (remove-overlays beg end)
1333 (delete-region beg end)
1334 (if (= (length todo-categories) 1)
1335 ;; If deleted category was the only one, delete the file.
1336 (progn
1337 (todo-reevaluate-filelist-defcustoms)
1338 ;; Skip confirming killing the archive buffer if it has been
1339 ;; modified and not saved.
1340 (set-buffer-modified-p nil)
1341 (delete-file file)
1342 (kill-buffer)
1343 (message "Deleted todo file %s." file))
1344 (setq todo-categories (delete (assoc cat todo-categories)
1345 todo-categories))
1346 (todo-update-categories-sexp)
1347 (setq todo-category-number
1348 (1+ (mod todo-category-number (length todo-categories))))
1349 (todo-category-select)
1350 (goto-char (point-min))
1351 (message "Deleted category %s." cat)))))))
1352
1353 (defun todo-move-category ()
1354 "Move current category to a different todo file.
1355 If current category has archived items, also move those to the
1356 archive of the file moved to, creating it if it does not exist."
1357 (interactive)
1358 (when (or (> (length todo-categories) 1)
1359 (todo-y-or-n-p (concat "This is the only category in this file; "
1360 "moving it will also delete the file.\n"
1361 "Do you want to proceed? ")))
1362 (let* ((ofile todo-current-todo-file)
1363 (cat (todo-current-category))
1364 (nfile (todo-read-file-name
1365 "Choose a todo file to move this category to: " nil t))
1366 (archive (concat (file-name-sans-extension ofile) ".toda"))
1367 (buffers (append (list ofile)
1368 (unless (zerop (todo-get-count 'archived cat))
1369 (list archive))))
1370 new)
1371 (while (equal (file-truename nfile) (file-truename ofile))
1372 (setq nfile (todo-read-file-name
1373 "Choose a file distinct from this file: " nil t)))
1374 (dolist (buf buffers)
1375 (with-current-buffer (find-file-noselect buf)
1376 (widen)
1377 (goto-char (point-max))
1378 (let* ((beg (re-search-backward
1379 (concat "^"
1380 (regexp-quote (concat todo-category-beg cat))
1381 "$")
1382 nil t))
1383 (end (if (re-search-forward
1384 (concat "^" (regexp-quote todo-category-beg))
1385 nil t 2)
1386 (match-beginning 0)
1387 (point-max)))
1388 (content (buffer-substring-no-properties beg end))
1389 (counts (cdr (assoc cat todo-categories)))
1390 buffer-read-only)
1391 ;; Move the category to the new file. Also update or create
1392 ;; archive file if necessary.
1393 (with-current-buffer
1394 (find-file-noselect
1395 ;; Regenerate todo-archives in case there
1396 ;; is a newly created archive.
1397 (if (member buf (funcall todo-files-function t))
1398 (concat (file-name-sans-extension nfile) ".toda")
1399 nfile))
1400 (let* ((nfile-short (todo-short-file-name nfile))
1401 (prompt (concat
1402 (format "Todo file \"%s\" already has "
1403 nfile-short)
1404 (format "the category \"%s\";\n" cat)
1405 "enter a new category name: "))
1406 buffer-read-only)
1407 (widen)
1408 (goto-char (point-max))
1409 (insert content)
1410 ;; If the file moved to has a category with the same
1411 ;; name, rename the moved category.
1412 (when (assoc cat todo-categories)
1413 (unless (member (file-truename (buffer-file-name))
1414 (funcall todo-files-function t))
1415 (setq new (read-from-minibuffer prompt))
1416 (setq new (todo-validate-name new 'category))))
1417 ;; Replace old with new name in todo and archive files.
1418 (when new
1419 (goto-char (point-max))
1420 (re-search-backward
1421 (concat "^" (regexp-quote todo-category-beg)
1422 "\\(" (regexp-quote cat) "\\)$") nil t)
1423 (replace-match new nil nil nil 1)))
1424 (setq todo-categories
1425 (append todo-categories (list (cons new counts))))
1426 (todo-update-categories-sexp)
1427 ;; If archive was just created, save it to avoid "File
1428 ;; <xyz> no longer exists!" message on invoking
1429 ;; `todo-view-archived-items'.
1430 (unless (file-exists-p (buffer-file-name))
1431 (save-buffer))
1432 (todo-category-number (or new cat))
1433 (todo-category-select))
1434 ;; Delete the category from the old file, and if that was the
1435 ;; last category, delete the file. Also handle archive file
1436 ;; if necessary.
1437 (remove-overlays beg end)
1438 (delete-region beg end)
1439 (goto-char (point-min))
1440 ;; Put point after todo-categories sexp.
1441 (forward-line)
1442 (if (eobp) ; Aside from sexp, file is empty.
1443 (progn
1444 ;; Skip confirming killing the archive buffer.
1445 (set-buffer-modified-p nil)
1446 (delete-file todo-current-todo-file)
1447 (kill-buffer)
1448 (when (member todo-current-todo-file todo-files)
1449 (todo-reevaluate-filelist-defcustoms)))
1450 (setq todo-categories (delete (assoc cat todo-categories)
1451 todo-categories))
1452 (todo-update-categories-sexp)
1453 (todo-category-select)))))
1454 (set-window-buffer (selected-window)
1455 (set-buffer (find-file-noselect nfile)))
1456 (todo-category-number (or new cat))
1457 (todo-category-select))))
1458
1459 (defun todo-merge-category (&optional file)
1460 "Merge current category into another existing category.
1461
1462 With prefix argument FILE, prompt for a specific todo file and
1463 choose (with TAB completion) a category in it to merge into;
1464 otherwise, choose and merge into a category in either the
1465 current todo file or a file in `todo-category-completions-files'.
1466
1467 After merging, the current category's todo and done items are
1468 appended to the chosen goal category's todo and done items,
1469 respectively. The goal category becomes the current category,
1470 and the previous current category is deleted.
1471
1472 If both the first and goal categories also have archived items,
1473 the former are merged to the latter. If only the first category
1474 has archived items, the archived category is renamed to the goal
1475 category."
1476 (interactive "P")
1477 (let* ((tfile todo-current-todo-file)
1478 (cat (todo-current-category))
1479 (cat+file (todo-read-category "Merge into category: " 'todo file))
1480 (goal (car cat+file))
1481 (gfile (cdr cat+file))
1482 (archive (concat (file-name-sans-extension (if file gfile tfile))
1483 ".toda"))
1484 archived-count here)
1485 ;; Merge in todo file.
1486 (with-current-buffer (get-buffer (find-file-noselect tfile))
1487 (widen)
1488 (let* ((buffer-read-only nil)
1489 (cbeg (progn
1490 (re-search-backward
1491 (concat "^" (regexp-quote todo-category-beg)) nil t)
1492 (point-marker)))
1493 (tbeg (progn (forward-line) (point-marker)))
1494 (dbeg (progn
1495 (re-search-forward
1496 (concat "^" (regexp-quote todo-category-done)) nil t)
1497 (forward-line) (point-marker)))
1498 ;; Omit empty line between todo and done items.
1499 (tend (progn (forward-line -2) (point-marker)))
1500 (cend (progn
1501 (if (re-search-forward
1502 (concat "^" (regexp-quote todo-category-beg)) nil t)
1503 (progn
1504 (goto-char (match-beginning 0))
1505 (point-marker))
1506 (point-max-marker))))
1507 (todo (buffer-substring-no-properties tbeg tend))
1508 (done (buffer-substring-no-properties dbeg cend)))
1509 (goto-char (point-min))
1510 ;; Merge any todo items.
1511 (unless (zerop (length todo))
1512 (re-search-forward
1513 (concat "^" (regexp-quote (concat todo-category-beg goal)) "$")
1514 nil t)
1515 (re-search-forward
1516 (concat "^" (regexp-quote todo-category-done)) nil t)
1517 (forward-line -1)
1518 (setq here (point-marker))
1519 (insert todo)
1520 (todo-update-count 'todo (todo-get-count 'todo cat) goal))
1521 ;; Merge any done items.
1522 (unless (zerop (length done))
1523 (goto-char (if (re-search-forward
1524 (concat "^" (regexp-quote todo-category-beg)) nil t)
1525 (match-beginning 0)
1526 (point-max)))
1527 (when (zerop (length todo)) (setq here (point-marker)))
1528 (insert done)
1529 (todo-update-count 'done (todo-get-count 'done cat) goal))
1530 (remove-overlays cbeg cend)
1531 (delete-region cbeg cend)
1532 (setq todo-categories (delete (assoc cat todo-categories)
1533 todo-categories))
1534 (todo-update-categories-sexp)
1535 (mapc (lambda (m) (set-marker m nil)) (list cbeg tbeg dbeg tend cend))))
1536 (when (file-exists-p archive)
1537 ;; Merge in archive file.
1538 (with-current-buffer (get-buffer (find-file-noselect archive))
1539 (widen)
1540 (goto-char (point-min))
1541 (let ((buffer-read-only nil)
1542 (cbeg (save-excursion
1543 (when (re-search-forward
1544 (concat "^" (regexp-quote
1545 (concat todo-category-beg cat)) "$")
1546 nil t)
1547 (goto-char (match-beginning 0))
1548 (point-marker))))
1549 (gbeg (save-excursion
1550 (when (re-search-forward
1551 (concat "^" (regexp-quote
1552 (concat todo-category-beg goal)) "$")
1553 nil t)
1554 (goto-char (match-beginning 0))
1555 (point-marker))))
1556 cend carch)
1557 (when cbeg
1558 (setq archived-count (todo-get-count 'done cat))
1559 (setq cend (save-excursion
1560 (if (re-search-forward
1561 (concat "^" (regexp-quote todo-category-beg))
1562 nil t)
1563 (match-beginning 0)
1564 (point-max))))
1565 (setq carch (save-excursion (goto-char cbeg) (forward-line)
1566 (buffer-substring-no-properties (point) cend)))
1567 ;; If both categories of the merge have archived items, merge the
1568 ;; source items to the goal items, else "merge" by renaming the
1569 ;; source category to goal.
1570 (if gbeg
1571 (progn
1572 (goto-char (if (re-search-forward
1573 (concat "^" (regexp-quote todo-category-beg))
1574 nil t)
1575 (match-beginning 0)
1576 (point-max)))
1577 (insert carch)
1578 (remove-overlays cbeg cend)
1579 (delete-region cbeg cend))
1580 (goto-char cbeg)
1581 (search-forward cat)
1582 (replace-match goal))
1583 (setq todo-categories (todo-make-categories-list t))
1584 (todo-update-categories-sexp)))))
1585 (with-current-buffer (get-file-buffer tfile)
1586 (when archived-count
1587 (unless (zerop archived-count)
1588 (todo-update-count 'archived archived-count goal)
1589 (todo-update-categories-sexp)))
1590 (todo-category-number goal)
1591 ;; If there are only merged done items, show them.
1592 (let ((todo-show-with-done (zerop (todo-get-count 'todo goal))))
1593 (todo-category-select)
1594 ;; Put point on the first merged item.
1595 (goto-char here)))
1596 (set-marker here nil)))
1597
1598 ;; -----------------------------------------------------------------------------
1599 ;;; Item editing
1600 ;; -----------------------------------------------------------------------------
1601
1602 (defcustom todo-include-in-diary nil
1603 "Non-nil to allow new todo items to be included in the diary."
1604 :type 'boolean
1605 :group 'todo-edit)
1606
1607 (defcustom todo-diary-nonmarking nil
1608 "Non-nil to insert new todo diary items as nonmarking by default.
1609 This appends `diary-nonmarking-symbol' to the front of an item on
1610 insertion provided it doesn't begin with `todo-nondiary-marker'."
1611 :type 'boolean
1612 :group 'todo-edit)
1613
1614 (defcustom todo-always-add-time-string nil
1615 "Non-nil adds current time to a new item's date header by default.
1616 When the todo insertion commands have a non-nil \"maybe-notime\"
1617 argument, this reverses the effect of
1618 `todo-always-add-time-string': if t, these commands omit the
1619 current time, if nil, they include it."
1620 :type 'boolean
1621 :group 'todo-edit)
1622
1623 (defcustom todo-use-only-highlighted-region t
1624 "Non-nil to enable inserting only highlighted region as new item."
1625 :type 'boolean
1626 :group 'todo-edit)
1627
1628 (defcustom todo-item-mark "*"
1629 "String used to mark items.
1630 To ensure item marking works, change the value of this option
1631 only when no items are marked."
1632 :type '(string :validate
1633 (lambda (widget)
1634 (when (string= (widget-value widget) todo-prefix)
1635 (widget-put
1636 widget :error
1637 "Invalid value: must be distinct from `todo-prefix'")
1638 widget)))
1639 :set (lambda (symbol value)
1640 (custom-set-default symbol (propertize value 'face 'todo-mark)))
1641 :group 'todo-edit)
1642
1643 (defcustom todo-comment-string "COMMENT"
1644 "String inserted before optional comment appended to done item."
1645 :type 'string
1646 :initialize 'custom-initialize-default
1647 :set 'todo-reset-comment-string
1648 :group 'todo-edit)
1649
1650 (defcustom todo-undo-item-omit-comment 'ask
1651 "Whether to omit done item comment on undoing the item.
1652 Nil means never omit the comment, t means always omit it, `ask'
1653 means prompt user and omit comment only on confirmation."
1654 :type '(choice (const :tag "Never" nil)
1655 (const :tag "Always" t)
1656 (const :tag "Ask" ask))
1657 :group 'todo-edit)
1658
1659 (defun todo-toggle-mark-item (&optional n)
1660 "Mark item with `todo-item-mark' if unmarked, otherwise unmark it.
1661 With a positive numerical prefix argument N, change the
1662 marking of the next N items."
1663 (interactive "p")
1664 (when (todo-item-string)
1665 (unless (> n 1) (setq n 1))
1666 (dotimes (i n)
1667 (let* ((cat (todo-current-category))
1668 (marks (assoc cat todo-categories-with-marks))
1669 (ov (progn
1670 (unless (looking-at todo-item-start)
1671 (todo-item-start))
1672 (todo-get-overlay 'prefix)))
1673 (pref (overlay-get ov 'before-string)))
1674 (if (todo-marked-item-p)
1675 (progn
1676 (overlay-put ov 'before-string (substring pref 1))
1677 (if (= (cdr marks) 1) ; Deleted last mark in this category.
1678 (setq todo-categories-with-marks
1679 (assq-delete-all cat todo-categories-with-marks))
1680 (setcdr marks (1- (cdr marks)))))
1681 (overlay-put ov 'before-string (concat todo-item-mark pref))
1682 (if marks
1683 (setcdr marks (1+ (cdr marks)))
1684 (push (cons cat 1) todo-categories-with-marks))))
1685 (todo-forward-item))))
1686
1687 (defun todo-mark-category ()
1688 "Mark all visible items in this category with `todo-item-mark'."
1689 (interactive)
1690 (let* ((cat (todo-current-category))
1691 (marks (assoc cat todo-categories-with-marks)))
1692 (save-excursion
1693 (goto-char (point-min))
1694 (while (not (eobp))
1695 (let* ((ov (todo-get-overlay 'prefix))
1696 (pref (overlay-get ov 'before-string)))
1697 (unless (todo-marked-item-p)
1698 (overlay-put ov 'before-string (concat todo-item-mark pref))
1699 (if marks
1700 (setcdr marks (1+ (cdr marks)))
1701 (push (cons cat 1) todo-categories-with-marks))))
1702 (todo-forward-item)))))
1703
1704 (defun todo-unmark-category ()
1705 "Remove `todo-item-mark' from all visible items in this category."
1706 (interactive)
1707 (let* ((cat (todo-current-category))
1708 (marks (assoc cat todo-categories-with-marks)))
1709 (save-excursion
1710 (goto-char (point-min))
1711 (while (not (eobp))
1712 (let* ((ov (todo-get-overlay 'prefix))
1713 ;; No overlay on empty line between todo and done items.
1714 (pref (when ov (overlay-get ov 'before-string))))
1715 (when (todo-marked-item-p)
1716 (overlay-put ov 'before-string (substring pref 1)))
1717 (todo-forward-item))))
1718 (setq todo-categories-with-marks
1719 (delq marks todo-categories-with-marks))))
1720
1721 (defvar todo-date-from-calendar nil
1722 "Helper variable for setting item date from the Emacs Calendar.")
1723
1724 (defun todo-basic-insert-item (&optional arg diary nonmarking date-type time
1725 region-or-here)
1726 "Insert a new todo item into a category.
1727 This is the function from which the generated Todo mode item
1728 insertion commands derive.
1729
1730 The generated commands have mnemonic key bindings based on the
1731 arguments' values and their order in the command's argument list,
1732 as follows: (1) for DIARY `d', (2) for NONMARKING `k', (3) for
1733 DATE-TYPE either `c' for calendar or `d' for date or `n' for
1734 weekday name, (4) for TIME `t', (5) for REGION-OR-HERE either `r'
1735 for region or `h' for here. Sequences of these keys are appended
1736 to the insertion prefix key `i'. Keys that allow a following
1737 key (i.e., any but `r' or `h') must be doubled when used finally.
1738 For example, the command bound to the key sequence `i y h' will
1739 insert a new item with today's date, marked according to the
1740 DIARY argument described below, and with priority according to
1741 the HERE argument; `i y y' does the same except that the priority
1742 is not given by HERE but by prompting.
1743
1744 In command invocations, ARG is passed as a prefix argument as
1745 follows. With no prefix argument, add the item to the current
1746 category; with one prefix argument (`C-u'), prompt for a category
1747 from the current todo file; with two prefix arguments (`C-u C-u'),
1748 first prompt for a todo file, then a category in that file. If
1749 a non-existing category is entered, ask whether to add it to the
1750 todo file; if answered affirmatively, add the category and
1751 insert the item there.
1752
1753 The remaining arguments are set or left nil by the generated item
1754 insertion commands; their meanings are described in the follows
1755 paragraphs.
1756
1757 When argument DIARY is non-nil, this overrides the intent of the
1758 user option `todo-include-in-diary' for this item: if
1759 `todo-include-in-diary' is nil, include the item in the Fancy
1760 Diary display, and if it is non-nil, exclude the item from the
1761 Fancy Diary display. When DIARY is nil, `todo-include-in-diary'
1762 has its intended effect.
1763
1764 When the item is included in the Fancy Diary display and the
1765 argument NONMARKING is non-nil, this overrides the intent of the
1766 user option `todo-diary-nonmarking' for this item: if
1767 `todo-diary-nonmarking' is nil, append `diary-nonmarking-symbol'
1768 to the item, and if it is non-nil, omit `diary-nonmarking-symbol'.
1769
1770 The argument DATE-TYPE determines the content of the item's
1771 mandatory date header string and how it is added:
1772 - If DATE-TYPE is the symbol `calendar', the Calendar pops up and
1773 when the user puts the cursor on a date and hits RET, that
1774 date, in the format set by `calendar-date-display-form',
1775 becomes the date in the header.
1776 - If DATE-TYPE is a string matching the regexp
1777 `todo-date-pattern', that string becomes the date in the
1778 header. This case is for the command
1779 `todo-insert-item-from-calendar' which is called from the
1780 Calendar.
1781 - If DATE-TYPE is the symbol `date', the header contains the date
1782 in the format set by `calendar-date-display-form', with year,
1783 month and day individually prompted for (month with tab
1784 completion).
1785 - If DATE-TYPE is the symbol `dayname' the header contains a
1786 weekday name instead of a date, prompted for with tab
1787 completion.
1788 - If DATE-TYPE has any other value (including nil or none) the
1789 header contains the current date (in the format set by
1790 `calendar-date-display-form').
1791
1792 With non-nil argument TIME prompt for a time string, which must
1793 match `diary-time-regexp'. Typing `<return>' at the prompt
1794 returns the current time, if the user option
1795 `todo-always-add-time-string' is non-nil, otherwise the empty
1796 string (i.e., no time string). If TIME is absent or nil, add or
1797 omit the current time string according as
1798 `todo-always-add-time-string' is non-nil or nil, respectively.
1799
1800 The argument REGION-OR-HERE determines the source and location of
1801 the new item:
1802 - If the REGION-OR-HERE is the symbol `here', prompt for the text of
1803 the new item and, if the command was invoked with point in the todo
1804 items section of the current category, give the new item the
1805 priority of the item at point, lowering the latter's priority and
1806 the priority of the remaining items. If point is in the done items
1807 section of the category, insert the new item as the first todo item
1808 in the category. Likewise, if the command with `here' is invoked
1809 outside of the current category, jump to the chosen category and
1810 insert the new item as the first item in the category.
1811 - If REGION-OR-HERE is the symbol `region', use the region of the
1812 current buffer as the text of the new item, depending on the
1813 value of user option `todo-use-only-highlighted-region': if
1814 this is non-nil, then use the region only when it is
1815 highlighted; otherwise, use the region regardless of
1816 highlighting. An error is signalled if there is no region in
1817 the current buffer. Prompt for the item's priority in the
1818 category (an integer between 1 and one more than the number of
1819 items in the category), and insert the item accordingly.
1820 - If REGION-OR-HERE has any other value (in particular, nil or
1821 none), prompt for the text and the item's priority, and insert
1822 the item accordingly."
1823 ;; If invoked outside of Todo mode and there is not yet any Todo
1824 ;; file, initialize one.
1825 (if (null (funcall todo-files-function))
1826 (todo-show)
1827 (let ((region (eq region-or-here 'region))
1828 (here (eq region-or-here 'here)))
1829 (when region
1830 (let (use-empty-active-region)
1831 (unless (and todo-use-only-highlighted-region (use-region-p))
1832 (user-error "There is no active region"))))
1833 (let* ((obuf (current-buffer))
1834 (ocat (todo-current-category))
1835 (opoint (point))
1836 (todo-mm (eq major-mode 'todo-mode))
1837 (cat+file (cond ((equal arg '(4))
1838 (todo-read-category "Insert in category: "))
1839 ((equal arg '(16))
1840 (todo-read-category "Insert in category: "
1841 nil 'file))
1842 (t
1843 (cons (todo-current-category)
1844 (or todo-current-todo-file
1845 (and todo-show-current-file
1846 todo-global-current-todo-file)
1847 (todo-absolute-file-name
1848 todo-default-todo-file))))))
1849 (cat (car cat+file))
1850 (file (cdr cat+file))
1851 (new-item (if region
1852 (buffer-substring-no-properties
1853 (region-beginning) (region-end))
1854 (read-from-minibuffer "Todo item: ")))
1855 (date-string (cond
1856 ((eq date-type 'date)
1857 (todo-read-date))
1858 ((eq date-type 'dayname)
1859 (todo-read-dayname))
1860 ((eq date-type 'calendar)
1861 (setq todo-date-from-calendar t)
1862 (or (todo-set-date-from-calendar)
1863 ;; If user exits Calendar before choosing
1864 ;; a date, cancel item insertion.
1865 (keyboard-quit)))
1866 ((and (stringp date-type)
1867 (string-match todo-date-pattern date-type))
1868 (setq todo-date-from-calendar date-type)
1869 (todo-set-date-from-calendar))
1870 (t
1871 (calendar-date-string
1872 (calendar-current-date) t t))))
1873 (time-string (or (and time (todo-read-time))
1874 (and todo-always-add-time-string
1875 (substring (current-time-string) 11 16)))))
1876 (setq todo-date-from-calendar nil)
1877 (find-file-noselect file 'nowarn)
1878 (set-window-buffer (selected-window)
1879 (set-buffer (find-buffer-visiting file)))
1880 ;; If this command was invoked outside of a Todo mode buffer,
1881 ;; the call to todo-current-category above returned nil. If
1882 ;; we just entered Todo mode now, then cat was set to the
1883 ;; file's first category, but if todo-mode was already
1884 ;; enabled, cat did not get set, so we have to do that.
1885 (unless cat
1886 (setq cat (todo-current-category)))
1887 (setq todo-current-todo-file file)
1888 (unless todo-global-current-todo-file
1889 (setq todo-global-current-todo-file todo-current-todo-file))
1890 (let ((buffer-read-only nil)
1891 (called-from-outside (not (and todo-mm (equal cat ocat))))
1892 done-only item-added)
1893 (setq new-item
1894 ;; Add date, time and diary marking as required.
1895 (concat (if (not (and diary (not todo-include-in-diary)))
1896 todo-nondiary-start
1897 (when (and nonmarking (not todo-diary-nonmarking))
1898 diary-nonmarking-symbol))
1899 date-string (when (and time-string ; Can be empty.
1900 (not (zerop (length
1901 time-string))))
1902 (concat " " time-string))
1903 (when (not (and diary (not todo-include-in-diary)))
1904 todo-nondiary-end)
1905 " " new-item))
1906 ;; Indent newlines inserted by C-q C-j if nonspace char follows.
1907 (setq new-item (replace-regexp-in-string "\\(\n\\)[^[:blank:]]"
1908 "\n\t" new-item nil nil 1))
1909 (unwind-protect
1910 (progn
1911 ;; Make sure the correct category is selected. There
1912 ;; are two cases: (i) we just visited the file, so no
1913 ;; category is selected yet, or (ii) we invoked
1914 ;; insertion "here" from outside the category we want
1915 ;; to insert in (with priority insertion, category
1916 ;; selection is done by todo-set-item-priority).
1917 (when (or (= (- (point-max) (point-min)) (buffer-size))
1918 (and here called-from-outside))
1919 (todo-category-number cat)
1920 (todo-category-select))
1921 ;; If only done items are displayed in category,
1922 ;; toggle to todo items before inserting new item.
1923 (when (save-excursion
1924 (goto-char (point-min))
1925 (looking-at todo-done-string-start))
1926 (setq done-only t)
1927 (todo-toggle-view-done-only))
1928 (if here
1929 (progn
1930 ;; If command was invoked with point in done
1931 ;; items section or outside of the current
1932 ;; category, can't insert "here", so to be
1933 ;; useful give new item top priority.
1934 (when (or (todo-done-item-section-p)
1935 called-from-outside
1936 done-only)
1937 (goto-char (point-min)))
1938 (todo-insert-with-overlays new-item))
1939 (todo-set-item-priority new-item cat t))
1940 (setq item-added t))
1941 ;; If user cancels before setting priority, restore
1942 ;; display.
1943 (unless item-added
1944 (if ocat
1945 (progn
1946 (unless (equal cat ocat)
1947 (todo-category-number ocat)
1948 (todo-category-select))
1949 (and done-only (todo-toggle-view-done-only)))
1950 (set-window-buffer (selected-window) (set-buffer obuf)))
1951 (goto-char opoint))
1952 ;; If the todo items section is not visible when the
1953 ;; insertion command is called (either because only done
1954 ;; items were shown or because the category was not in the
1955 ;; current buffer), then if the item is inserted at the
1956 ;; end of the category, point is at eob and eob at
1957 ;; window-start, so that higher priority todo items are
1958 ;; out of view. So we recenter to make sure the todo
1959 ;; items are displayed in the window.
1960 (when item-added (recenter)))
1961 (todo-update-count 'todo 1)
1962 (if (or diary todo-include-in-diary) (todo-update-count 'diary 1))
1963 (todo-update-categories-sexp))))))
1964
1965 (defun todo-set-date-from-calendar ()
1966 "Return string of date chosen from Calendar."
1967 (cond ((and (stringp todo-date-from-calendar)
1968 (string-match todo-date-pattern todo-date-from-calendar))
1969 todo-date-from-calendar)
1970 (todo-date-from-calendar
1971 (let (calendar-view-diary-initially-flag)
1972 (calendar)) ; *Calendar* is now current buffer.
1973 (define-key calendar-mode-map [remap newline] 'exit-recursive-edit)
1974 ;; If user exits Calendar before choosing a date, clean up properly.
1975 (define-key calendar-mode-map
1976 [remap calendar-exit] (lambda ()
1977 (interactive)
1978 (progn
1979 (calendar-exit)
1980 (exit-recursive-edit))))
1981 (message "Put cursor on a date and type <return> to set it.")
1982 (recursive-edit)
1983 (unwind-protect
1984 (when (equal (buffer-name) calendar-buffer)
1985 (setq todo-date-from-calendar
1986 (calendar-date-string (calendar-cursor-to-date t) t t))
1987 (calendar-exit)
1988 todo-date-from-calendar)
1989 (define-key calendar-mode-map [remap newline] nil)
1990 (define-key calendar-mode-map [remap calendar-exit] nil)
1991 (unless (zerop (recursion-depth)) (exit-recursive-edit))
1992 (when (stringp todo-date-from-calendar)
1993 todo-date-from-calendar)))))
1994
1995 (defun todo-insert-item-from-calendar (&optional arg)
1996 "Prompt for and insert a new item with date selected from calendar.
1997 Invoked without prefix argument ARG, insert the item into the
1998 current category, without one prefix argument, prompt for the
1999 category from the current todo file or from one listed in
2000 `todo-category-completions-files'; with two prefix arguments,
2001 prompt for a todo file and then for a category in it."
2002 (interactive "P")
2003 (setq todo-date-from-calendar
2004 (calendar-date-string (calendar-cursor-to-date t) t t))
2005 (calendar-exit)
2006 (todo-basic-insert-item arg nil nil todo-date-from-calendar))
2007
2008 (define-key calendar-mode-map "it" 'todo-insert-item-from-calendar)
2009
2010 (defun todo-copy-item ()
2011 "Copy item at point and insert the copy as a new item."
2012 (interactive)
2013 (unless (or (todo-done-item-p) (looking-at "^$"))
2014 (let ((copy (todo-item-string))
2015 (diary-item (todo-diary-item-p)))
2016 (todo-set-item-priority copy (todo-current-category) t)
2017 (todo-update-count 'todo 1)
2018 (when diary-item (todo-update-count 'diary 1))
2019 (todo-update-categories-sexp))))
2020
2021 (defun todo-delete-item ()
2022 "Delete at least one item in this category.
2023 If there are marked items, delete all of these; otherwise, delete
2024 the item at point."
2025 (interactive)
2026 (let (ov)
2027 (unwind-protect
2028 (let* ((cat (todo-current-category))
2029 (marked (assoc cat todo-categories-with-marks))
2030 (item (unless marked (todo-item-string)))
2031 (answer (if marked
2032 (todo-y-or-n-p
2033 "Permanently delete all marked items? ")
2034 (when item
2035 (setq ov (make-overlay
2036 (save-excursion (todo-item-start))
2037 (save-excursion (todo-item-end))))
2038 (overlay-put ov 'face 'todo-search)
2039 (todo-y-or-n-p "Permanently delete this item? "))))
2040 buffer-read-only)
2041 (when answer
2042 (and marked (goto-char (point-min)))
2043 (catch 'done
2044 (while (not (eobp))
2045 (if (or (and marked (todo-marked-item-p)) item)
2046 (progn
2047 (if (todo-done-item-p)
2048 (todo-update-count 'done -1)
2049 (todo-update-count 'todo -1 cat)
2050 (and (todo-diary-item-p)
2051 (todo-update-count 'diary -1)))
2052 (if ov (delete-overlay ov))
2053 (todo-remove-item)
2054 ;; Don't leave point below last item.
2055 (and item (bolp) (eolp) (< (point-min) (point-max))
2056 (todo-backward-item))
2057 (when item
2058 (throw 'done (setq item nil))))
2059 (todo-forward-item))))
2060 (when marked
2061 (setq todo-categories-with-marks
2062 (assq-delete-all cat todo-categories-with-marks)))
2063 (todo-update-categories-sexp)
2064 (todo-prefix-overlays)))
2065 (if ov (delete-overlay ov)))))
2066
2067 (defun todo-edit-item (&optional arg)
2068 "Edit the todo item at point.
2069 With non-nil prefix argument ARG, include the item's date/time
2070 header, making it also editable; otherwise, include only the item
2071 content.
2072
2073 If the item consists of only one logical line, edit it in the
2074 minibuffer; otherwise, edit it in Todo Edit mode."
2075 (interactive "P")
2076 (when (todo-item-string)
2077 (let* ((opoint (point))
2078 (start (todo-item-start))
2079 (item-beg (progn
2080 (re-search-forward
2081 (concat todo-date-string-start todo-date-pattern
2082 "\\( " diary-time-regexp "\\)?"
2083 (regexp-quote todo-nondiary-end) "?")
2084 (line-end-position) t)
2085 (1+ (- (point) start))))
2086 (header (substring (todo-item-string) 0 item-beg))
2087 (item (if arg (todo-item-string)
2088 (substring (todo-item-string) item-beg)))
2089 (multiline (> (length (split-string item "\n")) 1))
2090 (buffer-read-only nil))
2091 (if multiline
2092 (todo-edit-multiline-item)
2093 (let ((new (concat (if arg "" header)
2094 (read-string "Edit: " (if arg
2095 (cons item item-beg)
2096 (cons item 0))))))
2097 (when arg
2098 (while (not (string-match (concat todo-date-string-start
2099 todo-date-pattern) new))
2100 (setq new (read-from-minibuffer
2101 "Item must start with a date: " new))))
2102 ;; Ensure lines following hard newlines are indented.
2103 (setq new (replace-regexp-in-string "\\(\n\\)[^[:blank:]]"
2104 "\n\t" new nil nil 1))
2105 ;; If user moved point during editing, make sure it moves back.
2106 (goto-char opoint)
2107 (todo-remove-item)
2108 (todo-insert-with-overlays new)
2109 (move-to-column item-beg))))))
2110
2111 (defun todo-edit-multiline-item ()
2112 "Edit current todo item in Todo Edit mode.
2113 Use of newlines invokes `todo-indent' to insure compliance with
2114 the format of Diary entries."
2115 (interactive)
2116 (when (todo-item-string)
2117 (let ((buf todo-edit-buffer))
2118 (set-window-buffer (selected-window)
2119 (set-buffer (make-indirect-buffer (buffer-name) buf)))
2120 (narrow-to-region (todo-item-start) (todo-item-end))
2121 (todo-edit-mode)
2122 (message "%s" (substitute-command-keys
2123 (concat "Type \\[todo-edit-quit] "
2124 "to return to Todo mode.\n"))))))
2125
2126 (defun todo-edit-quit ()
2127 "Return from Todo Edit mode to Todo mode.
2128 If the item contains hard line breaks, make sure the following
2129 lines are indented by `todo-indent-to-here' to conform to diary
2130 format.
2131
2132 If the whole file was in Todo Edit mode, check before returning
2133 whether the file is still a valid todo file and if so, also
2134 recalculate the todo file's categories sexp, in case changes were
2135 made in the number or names of categories."
2136 (interactive)
2137 (if (> (buffer-size) (- (point-max) (point-min)))
2138 ;; We got here via `e m'.
2139 (let ((item (buffer-string))
2140 (regex "\\(\n\\)[^[:blank:]]")
2141 (buf (buffer-base-buffer)))
2142 (while (not (string-match (concat todo-date-string-start
2143 todo-date-pattern) item))
2144 (setq item (read-from-minibuffer
2145 "Item must start with a date: " item)))
2146 ;; Ensure lines following hard newlines are indented.
2147 (when (string-match regex (buffer-string))
2148 (setq item (replace-regexp-in-string regex "\n\t" item nil nil 1))
2149 (delete-region (point-min) (point-max))
2150 (insert item))
2151 (kill-buffer)
2152 (unless (eq (current-buffer) buf)
2153 (set-window-buffer (selected-window) (set-buffer buf))))
2154 ;; We got here via `F e'.
2155 (when (todo-check-format)
2156 ;; FIXME: separate out sexp check?
2157 ;; If manual editing makes e.g. item counts change, have to
2158 ;; call this to update todo-categories, but it restores
2159 ;; category order to list order.
2160 ;; (todo-repair-categories-sexp)
2161 ;; Compare (todo-make-categories-list t) with sexp and if
2162 ;; different ask (todo-update-categories-sexp) ?
2163 (todo-mode)
2164 (let* ((cat-beg (concat "^" (regexp-quote todo-category-beg)
2165 "\\(.*\\)$"))
2166 (curline (buffer-substring-no-properties
2167 (line-beginning-position) (line-end-position)))
2168 (cat (cond ((string-match cat-beg curline)
2169 (match-string-no-properties 1 curline))
2170 ((or (re-search-backward cat-beg nil t)
2171 (re-search-forward cat-beg nil t))
2172 (match-string-no-properties 1)))))
2173 (todo-category-number cat)
2174 (todo-category-select)
2175 (goto-char (point-min))))))
2176
2177 (defun todo-basic-edit-item-header (what &optional inc)
2178 "Function underlying commands to edit item date/time header.
2179
2180 The argument WHAT (passed by invoking commands) specifies what
2181 part of the header to edit; possible values are these symbols:
2182 `date', to edit the year, month, and day of the date string;
2183 `time', to edit just the time string; `calendar', to select the
2184 date from the Calendar; `today', to set the date to today's date;
2185 `dayname', to set the date string to the name of a day or to
2186 change the day name; and `year', `month' or `day', to edit only
2187 these respective parts of the date string (`day' is the number of
2188 the given day of the month, and `month' is either the name of the
2189 given month or its number, depending on the value of
2190 `calendar-date-display-form').
2191
2192 The optional argument INC is a positive or negative integer
2193 \(passed by invoking commands as a numerical prefix argument)
2194 that in conjunction with the WHAT values `year', `month' or
2195 `day', increments or decrements the specified date string
2196 component by the specified number of suitable units, i.e., years,
2197 months, or days, with automatic adjustment of the other date
2198 string components as necessary.
2199
2200 If there are marked items, apply the same edit to all of these;
2201 otherwise, edit just the item at point."
2202 (let* ((cat (todo-current-category))
2203 (marked (assoc cat todo-categories-with-marks))
2204 (first t)
2205 (todo-date-from-calendar t)
2206 (buffer-read-only nil)
2207 ndate ntime year monthname month day
2208 dayname) ; Needed by calendar-date-display-form.
2209 (save-excursion
2210 (or (and marked (goto-char (point-min))) (todo-item-start))
2211 (catch 'end
2212 (while (not (eobp))
2213 (and marked
2214 (while (not (todo-marked-item-p))
2215 (todo-forward-item)
2216 (and (eobp) (throw 'end nil))))
2217 (re-search-forward (concat todo-date-string-start "\\(?1:"
2218 todo-date-pattern
2219 "\\)\\(?2: " diary-time-regexp "\\)?"
2220 (regexp-quote todo-nondiary-end) "?")
2221 (line-end-position) t)
2222 (let* ((odate (match-string-no-properties 1))
2223 (otime (match-string-no-properties 2))
2224 (odayname (match-string-no-properties 5))
2225 (omonthname (match-string-no-properties 6))
2226 (omonth (match-string-no-properties 7))
2227 (oday (match-string-no-properties 8))
2228 (oyear (match-string-no-properties 9))
2229 (tmn-array todo-month-name-array)
2230 (mlist (append tmn-array nil))
2231 (tma-array todo-month-abbrev-array)
2232 (mablist (append tma-array nil))
2233 (yy (and oyear (unless (string= oyear "*")
2234 (string-to-number oyear))))
2235 (mm (or (and omonth (unless (string= omonth "*")
2236 (string-to-number omonth)))
2237 (1+ (- (length mlist)
2238 (length (or (member omonthname mlist)
2239 (member omonthname mablist)))))))
2240 (dd (and oday (unless (string= oday "*")
2241 (string-to-number oday)))))
2242 ;; If there are marked items, use only the first to set
2243 ;; header changes, and apply these to all marked items.
2244 (when first
2245 (cond
2246 ((eq what 'date)
2247 (setq ndate (todo-read-date)))
2248 ((eq what 'calendar)
2249 (setq ndate (save-match-data (todo-set-date-from-calendar))))
2250 ((eq what 'today)
2251 (setq ndate (calendar-date-string (calendar-current-date) t t)))
2252 ((eq what 'dayname)
2253 (setq ndate (todo-read-dayname)))
2254 ((eq what 'time)
2255 (setq ntime (save-match-data (todo-read-time)))
2256 (when (> (length ntime) 0)
2257 (setq ntime (concat " " ntime))))
2258 ;; When date string consists only of a day name,
2259 ;; passing other date components is a noop.
2260 ((and odayname (memq what '(year month day))))
2261 ((eq what 'year)
2262 (setq day oday
2263 monthname omonthname
2264 month omonth
2265 year (cond ((not current-prefix-arg)
2266 (todo-read-date 'year))
2267 ((string= oyear "*")
2268 (user-error "Cannot increment *"))
2269 (t
2270 (number-to-string (+ yy inc))))))
2271 ((eq what 'month)
2272 (setf day oday
2273 year oyear
2274 (if (memq 'month calendar-date-display-form)
2275 month
2276 monthname)
2277 (cond ((not current-prefix-arg)
2278 (todo-read-date 'month))
2279 ((or (string= omonth "*") (= mm 13))
2280 (user-error "Cannot increment *"))
2281 (t
2282 (let ((mminc (+ mm inc)))
2283 ;; Increment or decrement month by INC
2284 ;; modulo 12.
2285 (setq mm (% mminc 12))
2286 ;; If result is 0, make month December.
2287 (setq mm (if (= mm 0) 12 (abs mm)))
2288 ;; Adjust year if necessary.
2289 (setq year (or (and (cond ((> mminc 12)
2290 (+ yy (/ mminc 12)))
2291 ((< mminc 1)
2292 (- yy (/ mminc 12) 1))
2293 (t yy))
2294 (number-to-string yy))
2295 oyear)))
2296 ;; Return the changed numerical month as
2297 ;; a string or the corresponding month name.
2298 (if omonth
2299 (number-to-string mm)
2300 (aref tma-array (1- mm))))))
2301 (let ((yy (string-to-number year)) ; 0 if year is "*".
2302 ;; When mm is 13 (corresponding to "*" as value
2303 ;; of month), this raises an args-out-of-range
2304 ;; error in calendar-last-day-of-month, so use 1
2305 ;; (corresponding to January) to get 31 days.
2306 (mm (if (= mm 13) 1 mm)))
2307 (if (> (string-to-number day)
2308 (calendar-last-day-of-month mm yy))
2309 (user-error "%s %s does not have %s days"
2310 (aref tmn-array (1- mm))
2311 (if (= mm 2) yy "") day))))
2312 ((eq what 'day)
2313 (setq year oyear
2314 month omonth
2315 monthname omonthname
2316 day (cond
2317 ((not current-prefix-arg)
2318 (todo-read-date 'day mm oyear))
2319 ((string= oday "*")
2320 (user-error "Cannot increment *"))
2321 ((or (string= omonth "*") (string= omonthname "*"))
2322 (setq dd (+ dd inc))
2323 (if (> dd 31)
2324 (user-error "A month cannot have more than 31 days")
2325 (number-to-string dd)))
2326 ;; Increment or decrement day by INC,
2327 ;; adjusting month and year if necessary
2328 ;; (if year is "*" assume current year to
2329 ;; calculate adjustment).
2330 (t
2331 (let* ((yy (or yy (calendar-extract-year
2332 (calendar-current-date))))
2333 (date (calendar-gregorian-from-absolute
2334 (+ (calendar-absolute-from-gregorian
2335 (list mm dd yy)) inc)))
2336 (adjmm (nth 0 date)))
2337 ;; Set year and month(name) to adjusted values.
2338 (unless (string= year "*")
2339 (setq year (number-to-string (nth 2 date))))
2340 (if month
2341 (setq month (number-to-string adjmm))
2342 (setq monthname (aref tma-array (1- adjmm))))
2343 ;; Return changed numerical day as a string.
2344 (number-to-string (nth 1 date)))))))))
2345 (unless odayname
2346 ;; If year, month or day date string components were
2347 ;; changed, rebuild the date string.
2348 (when (memq what '(year month day))
2349 (setq ndate (mapconcat 'eval calendar-date-display-form ""))))
2350 (when ndate (replace-match ndate nil nil nil 1))
2351 ;; Add new time string to the header, if it was supplied.
2352 (when ntime
2353 (if otime
2354 (replace-match ntime nil nil nil 2)
2355 (goto-char (match-end 1))
2356 (insert ntime)))
2357 (setq todo-date-from-calendar nil)
2358 (setq first nil))
2359 ;; Apply the changes to the first marked item header to the
2360 ;; remaining marked items. If there are no marked items,
2361 ;; we're finished.
2362 (if marked
2363 (todo-forward-item)
2364 (goto-char (point-max))))))))
2365
2366 (defun todo-edit-item-header ()
2367 "Interactively edit at least the date of item's date/time header.
2368 If user option `todo-always-add-time-string' is non-nil, also
2369 edit item's time string."
2370 (interactive)
2371 (todo-basic-edit-item-header 'date)
2372 (when todo-always-add-time-string
2373 (todo-edit-item-time)))
2374
2375 (defun todo-edit-item-time ()
2376 "Interactively edit the time string of item's date/time header."
2377 (interactive)
2378 (todo-basic-edit-item-header 'time))
2379
2380 (defun todo-edit-item-date-from-calendar ()
2381 "Interactively edit item's date using the Calendar."
2382 (interactive)
2383 (todo-basic-edit-item-header 'calendar))
2384
2385 (defun todo-edit-item-date-to-today ()
2386 "Set item's date to today's date."
2387 (interactive)
2388 (todo-basic-edit-item-header 'today))
2389
2390 (defun todo-edit-item-date-day-name ()
2391 "Replace item's date with the name of a day of the week."
2392 (interactive)
2393 (todo-basic-edit-item-header 'dayname))
2394
2395 (defun todo-edit-item-date-year (&optional inc)
2396 "Interactively edit the year of item's date string.
2397 With prefix argument INC a positive or negative integer,
2398 increment or decrement the year by INC."
2399 (interactive "p")
2400 (todo-basic-edit-item-header 'year inc))
2401
2402 (defun todo-edit-item-date-month (&optional inc)
2403 "Interactively edit the month of item's date string.
2404 With prefix argument INC a positive or negative integer,
2405 increment or decrement the month by INC."
2406 (interactive "p")
2407 (todo-basic-edit-item-header 'month inc))
2408
2409 (defun todo-edit-item-date-day (&optional inc)
2410 "Interactively edit the day of the month of item's date string.
2411 With prefix argument INC a positive or negative integer,
2412 increment or decrement the day by INC."
2413 (interactive "p")
2414 (todo-basic-edit-item-header 'day inc))
2415
2416 (defun todo-edit-item-diary-inclusion ()
2417 "Change diary status of one or more todo items in this category.
2418 That is, insert `todo-nondiary-marker' if the candidate items
2419 lack this marking; otherwise, remove it.
2420
2421 If there are marked todo items, change the diary status of all
2422 and only these, otherwise change the diary status of the item at
2423 point."
2424 (interactive)
2425 (let ((buffer-read-only)
2426 (marked (assoc (todo-current-category)
2427 todo-categories-with-marks)))
2428 (catch 'stop
2429 (save-excursion
2430 (when marked (goto-char (point-min)))
2431 (while (not (eobp))
2432 (if (todo-done-item-p)
2433 (throw 'stop (message "Done items cannot be edited"))
2434 (unless (and marked (not (todo-marked-item-p)))
2435 (let* ((beg (todo-item-start))
2436 (lim (save-excursion (todo-item-end)))
2437 (end (save-excursion
2438 (or (todo-time-string-matcher lim)
2439 (todo-date-string-matcher lim)))))
2440 (if (looking-at (regexp-quote todo-nondiary-start))
2441 (progn
2442 (replace-match "")
2443 (search-forward todo-nondiary-end (1+ end) t)
2444 (replace-match "")
2445 (todo-update-count 'diary 1))
2446 (when end
2447 (insert todo-nondiary-start)
2448 (goto-char (1+ end))
2449 (insert todo-nondiary-end)
2450 (todo-update-count 'diary -1)))))
2451 (unless marked (throw 'stop nil))
2452 (todo-forward-item)))))
2453 (todo-update-categories-sexp)))
2454
2455 (defun todo-edit-category-diary-inclusion (arg)
2456 "Make all items in this category diary items.
2457 With prefix ARG, make all items in this category non-diary
2458 items."
2459 (interactive "P")
2460 (save-excursion
2461 (goto-char (point-min))
2462 (let ((todo-count (todo-get-count 'todo))
2463 (diary-count (todo-get-count 'diary))
2464 (buffer-read-only))
2465 (catch 'stop
2466 (while (not (eobp))
2467 (if (todo-done-item-p) ; We've gone too far.
2468 (throw 'stop nil)
2469 (let* ((beg (todo-item-start))
2470 (lim (save-excursion (todo-item-end)))
2471 (end (save-excursion
2472 (or (todo-time-string-matcher lim)
2473 (todo-date-string-matcher lim)))))
2474 (if arg
2475 (unless (looking-at (regexp-quote todo-nondiary-start))
2476 (insert todo-nondiary-start)
2477 (goto-char (1+ end))
2478 (insert todo-nondiary-end))
2479 (when (looking-at (regexp-quote todo-nondiary-start))
2480 (replace-match "")
2481 (search-forward todo-nondiary-end (1+ end) t)
2482 (replace-match "")))))
2483 (todo-forward-item))
2484 (unless (if arg (zerop diary-count) (= diary-count todo-count))
2485 (todo-update-count 'diary (if arg
2486 (- diary-count)
2487 (- todo-count diary-count))))
2488 (todo-update-categories-sexp)))))
2489
2490 (defun todo-edit-item-diary-nonmarking ()
2491 "Change non-marking of one or more diary items in this category.
2492 That is, insert `diary-nonmarking-symbol' if the candidate items
2493 lack this marking; otherwise, remove it.
2494
2495 If there are marked todo items, change the non-marking status of
2496 all and only these, otherwise change the non-marking status of
2497 the item at point."
2498 (interactive)
2499 (let ((buffer-read-only)
2500 (marked (assoc (todo-current-category)
2501 todo-categories-with-marks)))
2502 (catch 'stop
2503 (save-excursion
2504 (when marked (goto-char (point-min)))
2505 (while (not (eobp))
2506 (if (todo-done-item-p)
2507 (throw 'stop (message "Done items cannot be edited"))
2508 (unless (and marked (not (todo-marked-item-p)))
2509 (todo-item-start)
2510 (unless (looking-at (regexp-quote todo-nondiary-start))
2511 (if (looking-at (regexp-quote diary-nonmarking-symbol))
2512 (replace-match "")
2513 (insert diary-nonmarking-symbol))))
2514 (unless marked (throw 'stop nil))
2515 (todo-forward-item)))))))
2516
2517 (defun todo-edit-category-diary-nonmarking (arg)
2518 "Add `diary-nonmarking-symbol' to all diary items in this category.
2519 With prefix ARG, remove `diary-nonmarking-symbol' from all diary
2520 items in this category."
2521 (interactive "P")
2522 (save-excursion
2523 (goto-char (point-min))
2524 (let (buffer-read-only)
2525 (catch 'stop
2526 (while (not (eobp))
2527 (if (todo-done-item-p) ; We've gone too far.
2528 (throw 'stop nil)
2529 (unless (looking-at (regexp-quote todo-nondiary-start))
2530 (if arg
2531 (when (looking-at (regexp-quote diary-nonmarking-symbol))
2532 (replace-match ""))
2533 (unless (looking-at (regexp-quote diary-nonmarking-symbol))
2534 (insert diary-nonmarking-symbol))))
2535 (todo-forward-item)))))))
2536
2537 (defun todo-set-item-priority (&optional item cat new arg)
2538 "Prompt for and set ITEM's priority in CATegory.
2539
2540 Interactively, ITEM is the todo item at point, CAT is the current
2541 category, and the priority is a number between 1 and the number
2542 of items in the category. Non-interactively, non-nil NEW means
2543 ITEM is a new item and the lowest priority is one more than the
2544 number of items in CAT.
2545
2546 The new priority is set either interactively by prompt or by a
2547 numerical prefix argument, or noninteractively by argument ARG,
2548 whose value can be either of the symbols `raise' or `lower',
2549 meaning to raise or lower the item's priority by one."
2550 (interactive)
2551 (unless (and (called-interactively-p 'any)
2552 (or (todo-done-item-p) (looking-at "^$")))
2553 (let* ((item (or item (todo-item-string)))
2554 (marked (todo-marked-item-p))
2555 (cat (or cat (cond ((eq major-mode 'todo-mode)
2556 (todo-current-category))
2557 ((eq major-mode 'todo-filtered-items-mode)
2558 (let* ((regexp1
2559 (concat todo-date-string-start
2560 todo-date-pattern
2561 "\\( " diary-time-regexp "\\)?"
2562 (regexp-quote todo-nondiary-end)
2563 "?\\(?1: \\[\\(.+:\\)?.+\\]\\)")))
2564 (save-excursion
2565 (re-search-forward regexp1 nil t)
2566 (match-string-no-properties 1)))))))
2567 curnum
2568 (todo (cond ((or (eq arg 'raise) (eq arg 'lower)
2569 (eq major-mode 'todo-filtered-items-mode))
2570 (save-excursion
2571 (let ((curstart (todo-item-start))
2572 (count 0))
2573 (goto-char (point-min))
2574 (while (looking-at todo-item-start)
2575 (setq count (1+ count))
2576 (when (= (point) curstart) (setq curnum count))
2577 (todo-forward-item))
2578 count)))
2579 ((eq major-mode 'todo-mode)
2580 (todo-get-count 'todo cat))))
2581 (maxnum (if new (1+ todo) todo))
2582 (prompt (format "Set item priority (1-%d): " maxnum))
2583 (priority (cond ((and (not arg) (numberp current-prefix-arg))
2584 current-prefix-arg)
2585 ((and (eq arg 'raise) (>= curnum 1))
2586 (1- curnum))
2587 ((and (eq arg 'lower) (<= curnum maxnum))
2588 (1+ curnum))))
2589 candidate
2590 buffer-read-only)
2591 (unless (and priority
2592 (or (and (eq arg 'raise) (zerop priority))
2593 (and (eq arg 'lower) (> priority maxnum))))
2594 ;; When moving item to another category, show the category before
2595 ;; prompting for its priority.
2596 (unless (or arg (called-interactively-p 'any))
2597 (todo-category-number cat)
2598 ;; If done items in category are visible, keep them visible.
2599 (let ((done todo-show-with-done))
2600 (when (> (buffer-size) (- (point-max) (point-min)))
2601 (save-excursion
2602 (goto-char (point-min))
2603 (setq done (re-search-forward todo-done-string-start nil t))))
2604 (let ((todo-show-with-done done))
2605 (todo-category-select)
2606 ;; Keep top of category in view while setting priority.
2607 (goto-char (point-min)))))
2608 ;; Prompt for priority only when the category has at least one
2609 ;; todo item.
2610 (when (> maxnum 1)
2611 (while (not priority)
2612 (setq candidate (read-number prompt))
2613 (setq prompt (when (or (< candidate 1) (> candidate maxnum))
2614 (format "Priority must be an integer between 1 and %d.\n"
2615 maxnum)))
2616 (unless prompt (setq priority candidate))))
2617 ;; In Top Priorities buffer, an item's priority can be changed
2618 ;; wrt items in another category, but not wrt items in the same
2619 ;; category.
2620 (when (eq major-mode 'todo-filtered-items-mode)
2621 (let* ((regexp2 (concat todo-date-string-start todo-date-pattern
2622 "\\( " diary-time-regexp "\\)?"
2623 (regexp-quote todo-nondiary-end)
2624 "?\\(?1:" (regexp-quote cat) "\\)"))
2625 (end (cond ((< curnum priority)
2626 (save-excursion (todo-item-end)))
2627 ((> curnum priority)
2628 (save-excursion (todo-item-start)))))
2629 (match (save-excursion
2630 (cond ((< curnum priority)
2631 (todo-forward-item (1+ (- priority curnum)))
2632 (when (re-search-backward regexp2 end t)
2633 (match-string-no-properties 1)))
2634 ((> curnum priority)
2635 (todo-backward-item (- curnum priority))
2636 (when (re-search-forward regexp2 end t)
2637 (match-string-no-properties 1)))))))
2638 (when match
2639 (user-error (concat "Cannot reprioritize items from the same "
2640 "category in this mode, only in Todo mode")))))
2641 ;; Interactively or with non-nil ARG, relocate the item within its
2642 ;; category.
2643 (when (or arg (called-interactively-p 'any))
2644 (todo-remove-item))
2645 (goto-char (point-min))
2646 (when priority
2647 (unless (= priority 1)
2648 (todo-forward-item (1- priority))
2649 ;; When called from todo-item-undone and the highest priority
2650 ;; is chosen, this advances point to the first done item, so
2651 ;; move it up to the empty line above the done items
2652 ;; separator.
2653 (when (looking-back (concat "^"
2654 (regexp-quote todo-category-done)
2655 "\n"))
2656 (todo-backward-item))))
2657 (todo-insert-with-overlays item)
2658 ;; If item was marked, restore the mark.
2659 (and marked
2660 (let* ((ov (todo-get-overlay 'prefix))
2661 (pref (overlay-get ov 'before-string)))
2662 (overlay-put ov 'before-string
2663 (concat todo-item-mark pref))))))))
2664
2665 (defun todo-raise-item-priority ()
2666 "Raise priority of current item by moving it up by one item."
2667 (interactive)
2668 (todo-set-item-priority nil nil nil 'raise))
2669
2670 (defun todo-lower-item-priority ()
2671 "Lower priority of current item by moving it down by one item."
2672 (interactive)
2673 (todo-set-item-priority nil nil nil 'lower))
2674
2675 (defun todo-move-item (&optional file)
2676 "Move at least one todo or done item to another category.
2677 If there are marked items, move all of these; otherwise, move
2678 the item at point.
2679
2680 With prefix argument FILE, prompt for a specific todo file and
2681 choose (with TAB completion) a category in it to move the item or
2682 items to; otherwise, choose and move to any category in either
2683 the current todo file or one of the files in
2684 `todo-category-completions-files'. If the chosen category is
2685 not an existing categories, then it is created and the item(s)
2686 become(s) the first entry/entries in that category.
2687
2688 With moved todo items, prompt to set the priority in the category
2689 moved to (with multiple todo items, the one that had the highest
2690 priority in the category moved from gets the new priority and the
2691 rest of the moved todo items are inserted in sequence below it).
2692 Moved done items are appended to the top of the done items
2693 section in the category moved to."
2694 (interactive "P")
2695 (let* ((cat1 (todo-current-category))
2696 (marked (assoc cat1 todo-categories-with-marks)))
2697 ;; Noop if point is not on an item and there are no marked items.
2698 (unless (and (looking-at "^$")
2699 (not marked))
2700 (let* ((buffer-read-only)
2701 (file1 todo-current-todo-file)
2702 (num todo-category-number)
2703 (item (todo-item-string))
2704 (diary-item (todo-diary-item-p))
2705 (done-item (and (todo-done-item-p) (concat item "\n")))
2706 (omark (save-excursion (todo-item-start) (point-marker)))
2707 (todo 0)
2708 (diary 0)
2709 (done 0)
2710 ov cat2 file2 moved nmark todo-items done-items)
2711 (unwind-protect
2712 (progn
2713 (unless marked
2714 (setq ov (make-overlay (save-excursion (todo-item-start))
2715 (save-excursion (todo-item-end))))
2716 (overlay-put ov 'face 'todo-search))
2717 (let* ((pl (if (and marked (> (cdr marked) 1)) "s" ""))
2718 (cat+file (todo-read-category (concat "Move item" pl
2719 " to category: ")
2720 nil file)))
2721 (while (and (equal (car cat+file) cat1)
2722 (equal (cdr cat+file) file1))
2723 (setq cat+file (todo-read-category
2724 "Choose a different category: ")))
2725 (setq cat2 (car cat+file)
2726 file2 (cdr cat+file))))
2727 (if ov (delete-overlay ov)))
2728 (set-buffer (find-buffer-visiting file1))
2729 (if marked
2730 (progn
2731 (goto-char (point-min))
2732 (while (not (eobp))
2733 (when (todo-marked-item-p)
2734 (if (todo-done-item-p)
2735 (setq done-items (concat done-items
2736 (todo-item-string) "\n")
2737 done (1+ done))
2738 (setq todo-items (concat todo-items
2739 (todo-item-string) "\n")
2740 todo (1+ todo))
2741 (when (todo-diary-item-p)
2742 (setq diary (1+ diary)))))
2743 (todo-forward-item))
2744 ;; Chop off last newline of multiple todo item string,
2745 ;; since it will be reinserted when setting priority
2746 ;; (but with done items priority is not set, so keep
2747 ;; last newline).
2748 (and todo-items
2749 (setq todo-items (substring todo-items 0 -1))))
2750 (if (todo-done-item-p)
2751 (setq done 1)
2752 (setq todo 1)
2753 (when (todo-diary-item-p) (setq diary 1))))
2754 (set-window-buffer (selected-window)
2755 (set-buffer (find-file-noselect file2 'nowarn)))
2756 (unwind-protect
2757 (progn
2758 (when (or todo-items (and item (not done-item)))
2759 (todo-set-item-priority (or todo-items item) cat2 t))
2760 ;; Move done items en bloc to top of done items section.
2761 (when (or done-items done-item)
2762 (todo-category-number cat2)
2763 (widen)
2764 (goto-char (point-min))
2765 (re-search-forward
2766 (concat "^" (regexp-quote (concat todo-category-beg cat2))
2767 "$") nil t)
2768 (re-search-forward
2769 (concat "^" (regexp-quote todo-category-done)) nil t)
2770 (forward-line)
2771 (insert (or done-items done-item)))
2772 (setq moved t))
2773 (cond
2774 ;; Move succeeded, so remove item from starting category,
2775 ;; update item counts and display the category containing
2776 ;; the moved item.
2777 (moved
2778 (setq nmark (point-marker))
2779 (when todo (todo-update-count 'todo todo))
2780 (when diary (todo-update-count 'diary diary))
2781 (when done (todo-update-count 'done done))
2782 (todo-update-categories-sexp)
2783 (with-current-buffer (find-buffer-visiting file1)
2784 (save-excursion
2785 (save-restriction
2786 (widen)
2787 (goto-char omark)
2788 (if marked
2789 (let (beg end)
2790 (setq item nil)
2791 (re-search-backward
2792 (concat "^" (regexp-quote todo-category-beg)) nil t)
2793 (forward-line)
2794 (setq beg (point))
2795 (setq end (if (re-search-forward
2796 (concat "^" (regexp-quote
2797 todo-category-beg)) nil t)
2798 (match-beginning 0)
2799 (point-max)))
2800 (goto-char beg)
2801 (while (< (point) end)
2802 (if (todo-marked-item-p)
2803 (todo-remove-item)
2804 (todo-forward-item)))
2805 (setq todo-categories-with-marks
2806 (assq-delete-all cat1 todo-categories-with-marks)))
2807 (if ov (delete-overlay ov))
2808 (todo-remove-item))))
2809 (when todo (todo-update-count 'todo (- todo) cat1))
2810 (when diary (todo-update-count 'diary (- diary) cat1))
2811 (when done (todo-update-count 'done (- done) cat1))
2812 (todo-update-categories-sexp))
2813 (set-window-buffer (selected-window)
2814 (set-buffer (find-file-noselect file2 'nowarn)))
2815 (setq todo-category-number (todo-category-number cat2))
2816 (let ((todo-show-with-done (or done-items done-item)))
2817 (todo-category-select))
2818 (goto-char nmark)
2819 ;; If item is moved to end of (just first?) category, make
2820 ;; sure the items above it are displayed in the window.
2821 (recenter))
2822 ;; User quit before setting priority of todo item(s), so
2823 ;; return to starting category.
2824 (t
2825 (set-window-buffer (selected-window)
2826 (set-buffer (find-file-noselect file1 'nowarn)))
2827 (todo-category-number cat1)
2828 (todo-category-select)
2829 (goto-char omark))))))))
2830
2831 (defun todo-item-done (&optional arg)
2832 "Tag a todo item in this category as done and relocate it.
2833
2834 With prefix argument ARG prompt for a comment and append it to
2835 the done item; this is only possible if there are no marked
2836 items. If there are marked items, tag all of these with
2837 `todo-done-string' plus the current date and, if
2838 `todo-always-add-time-string' is non-nil, the current time;
2839 otherwise, just tag the item at point. Items tagged as done are
2840 relocated to the category's (by default hidden) done section. If
2841 done items are visible on invoking this command, they remain
2842 visible."
2843 (interactive "P")
2844 (let* ((cat (todo-current-category))
2845 (marked (assoc cat todo-categories-with-marks)))
2846 (when marked
2847 (save-excursion
2848 (save-restriction
2849 (goto-char (point-max))
2850 (todo-backward-item)
2851 (unless (todo-done-item-p)
2852 (widen)
2853 (unless (re-search-forward
2854 (concat "^" (regexp-quote todo-category-beg)) nil t)
2855 (goto-char (point-max)))
2856 (forward-line -1))
2857 (while (todo-done-item-p)
2858 (when (todo-marked-item-p)
2859 (user-error "This command does not apply to done items"))
2860 (todo-backward-item)))))
2861 (unless (and (not marked)
2862 (or (todo-done-item-p)
2863 ;; Point is between todo and done items.
2864 (looking-at "^$")))
2865 (let* ((date-string (calendar-date-string (calendar-current-date) t t))
2866 (time-string (if todo-always-add-time-string
2867 (concat " " (substring (current-time-string)
2868 11 16))
2869 ""))
2870 (done-prefix (concat "[" todo-done-string date-string time-string
2871 "] "))
2872 (comment (and arg (read-string "Enter a comment: ")))
2873 (item-count 0)
2874 (diary-count 0)
2875 (show-done (save-excursion
2876 (goto-char (point-min))
2877 (re-search-forward todo-done-string-start nil t)))
2878 (buffer-read-only nil)
2879 item done-item opoint)
2880 ;; Don't add empty comment to done item.
2881 (setq comment (unless (zerop (length comment))
2882 (concat " [" todo-comment-string ": " comment "]")))
2883 (and marked (goto-char (point-min)))
2884 (catch 'done
2885 ;; Stop looping when we hit the empty line below the last
2886 ;; todo item (this is eobp if only done items are hidden).
2887 (while (not (looking-at "^$"))
2888 (if (or (not marked) (and marked (todo-marked-item-p)))
2889 (progn
2890 (setq item (todo-item-string))
2891 (setq done-item (concat done-item done-prefix item
2892 comment (and marked "\n")))
2893 (setq item-count (1+ item-count))
2894 (when (todo-diary-item-p)
2895 (setq diary-count (1+ diary-count)))
2896 (todo-remove-item)
2897 (unless marked (throw 'done nil)))
2898 (todo-forward-item))))
2899 (when marked
2900 ;; Chop off last newline of done item string.
2901 (setq done-item (substring done-item 0 -1))
2902 (setq todo-categories-with-marks
2903 (assq-delete-all cat todo-categories-with-marks)))
2904 (save-excursion
2905 (widen)
2906 (re-search-forward
2907 (concat "^" (regexp-quote todo-category-done)) nil t)
2908 (forward-char)
2909 (when show-done (setq opoint (point)))
2910 (insert done-item "\n"))
2911 (todo-update-count 'todo (- item-count))
2912 (todo-update-count 'done item-count)
2913 (todo-update-count 'diary (- diary-count))
2914 (todo-update-categories-sexp)
2915 (let ((todo-show-with-done show-done))
2916 (todo-category-select)
2917 ;; When done items are shown, put cursor on first just done item.
2918 (when opoint (goto-char opoint)))))))
2919
2920 (defun todo-edit-done-item-comment (&optional arg)
2921 "Add a comment to this done item or edit an existing comment.
2922 With prefix ARG delete an existing comment."
2923 (interactive "P")
2924 (when (todo-done-item-p)
2925 (let ((item (todo-item-string))
2926 (opoint (point))
2927 (end (save-excursion (todo-item-end)))
2928 comment buffer-read-only)
2929 (save-excursion
2930 (todo-item-start)
2931 (if (re-search-forward (concat " \\["
2932 (regexp-quote todo-comment-string)
2933 ": \\([^]]+\\)\\]") end t)
2934 (if arg
2935 (when (todo-y-or-n-p "Delete comment? ")
2936 (delete-region (match-beginning 0) (match-end 0)))
2937 (setq comment (read-string "Edit comment: "
2938 (cons (match-string 1) 1)))
2939 (replace-match comment nil nil nil 1))
2940 (setq comment (read-string "Enter a comment: "))
2941 ;; If user moved point during editing, make sure it moves back.
2942 (goto-char opoint)
2943 (todo-item-end)
2944 (insert " [" todo-comment-string ": " comment "]"))))))
2945
2946 (defun todo-item-undone ()
2947 "Restore at least one done item to this category's todo section.
2948 Prompt for the new priority. If there are marked items, undo all
2949 of these, giving the first undone item the new priority and the
2950 rest following directly in sequence; otherwise, undo just the
2951 item at point.
2952
2953 If the done item has a comment, ask whether to omit the comment
2954 from the restored item. With multiple marked done items with
2955 comments, only ask once, and if affirmed, omit subsequent
2956 comments without asking."
2957 (interactive)
2958 (let* ((cat (todo-current-category))
2959 (marked (assoc cat todo-categories-with-marks))
2960 (pl (if (and marked (> (cdr marked) 1)) "s" "")))
2961 (when (or marked (todo-done-item-p))
2962 (let ((buffer-read-only)
2963 (opoint (point))
2964 (omark (point-marker))
2965 (first 'first)
2966 (item-count 0)
2967 (diary-count 0)
2968 start end item ov npoint undone)
2969 (and marked (goto-char (point-min)))
2970 (catch 'done
2971 (while (not (eobp))
2972 (when (or (not marked) (and marked (todo-marked-item-p)))
2973 (if (not (todo-done-item-p))
2974 (user-error "Only done items can be undone")
2975 (todo-item-start)
2976 (unless marked
2977 (setq ov (make-overlay (save-excursion (todo-item-start))
2978 (save-excursion (todo-item-end))))
2979 (overlay-put ov 'face 'todo-search))
2980 ;; Find the end of the date string added upon tagging item as
2981 ;; done.
2982 (setq start (search-forward "] "))
2983 (setq item-count (1+ item-count))
2984 (unless (looking-at (regexp-quote todo-nondiary-start))
2985 (setq diary-count (1+ diary-count)))
2986 (setq end (save-excursion (todo-item-end)))
2987 ;; Ask (once) whether to omit done item's comment. If
2988 ;; affirmed, omit subsequent comments without asking.
2989 (when (re-search-forward
2990 (concat " \\[" (regexp-quote todo-comment-string)
2991 ": [^]]+\\]") end t)
2992 (unwind-protect
2993 (if (eq first 'first)
2994 (setq first
2995 (if (eq todo-undo-item-omit-comment 'ask)
2996 (when (todo-y-or-n-p
2997 (concat "Omit comment" pl
2998 " from restored item"
2999 pl "? "))
3000 'omit)
3001 (when todo-undo-item-omit-comment 'omit)))
3002 t)
3003 (when (and (eq first 'first) ov) (delete-overlay ov)))
3004 (when (eq first 'omit)
3005 (setq end (match-beginning 0))))
3006 (setq item (concat item
3007 (buffer-substring-no-properties start end)
3008 (when marked "\n")))
3009 (unless marked (throw 'done nil))))
3010 (todo-forward-item)))
3011 (unwind-protect
3012 (progn
3013 ;; Chop off last newline of multiple items string, since
3014 ;; it will be reinserted on setting priority.
3015 (and marked (setq item (substring item 0 -1)))
3016 (todo-set-item-priority item cat t)
3017 (setq npoint (point))
3018 (setq undone t))
3019 (when ov (delete-overlay ov))
3020 (if (not undone)
3021 (goto-char opoint)
3022 (if marked
3023 (progn
3024 (setq item nil)
3025 (re-search-forward
3026 (concat "^" (regexp-quote todo-category-done)) nil t)
3027 (while (not (eobp))
3028 (if (todo-marked-item-p)
3029 (todo-remove-item)
3030 (todo-forward-item)))
3031 (setq todo-categories-with-marks
3032 (assq-delete-all cat todo-categories-with-marks)))
3033 (goto-char omark)
3034 (todo-remove-item))
3035 (todo-update-count 'todo item-count)
3036 (todo-update-count 'done (- item-count))
3037 (when diary-count (todo-update-count 'diary diary-count))
3038 (todo-update-categories-sexp)
3039 (let ((todo-show-with-done (> (todo-get-count 'done) 0)))
3040 (todo-category-select))
3041 ;; Put cursor on undone item.
3042 (goto-char npoint)))
3043 (set-marker omark nil)))))
3044
3045 ;; -----------------------------------------------------------------------------
3046 ;;; Done item archives
3047 ;; -----------------------------------------------------------------------------
3048
3049 (defun todo-find-archive (&optional ask)
3050 "Visit the archive of the current todo category, if it exists.
3051 If the category has no archived items, prompt to visit the
3052 archive anyway. If there is no archive for this file or with
3053 non-nil argument ASK, prompt to visit another archive.
3054
3055 The buffer showing the archive is in Todo Archive mode. The
3056 first visit in a session displays the first category in the
3057 archive, subsequent visits return to the last category
3058 displayed."
3059 (interactive)
3060 (if (null (funcall todo-files-function t))
3061 (message "There are no archive files")
3062 (let* ((cat (todo-current-category))
3063 (count (todo-get-count 'archived cat))
3064 (archive (concat (file-name-sans-extension todo-current-todo-file)
3065 ".toda"))
3066 (place (cond (ask 'other-archive)
3067 ((file-exists-p archive) 'this-archive)
3068 (t (when (todo-y-or-n-p
3069 (concat "This file has no archive; "
3070 "visit another archive? "))
3071 'other-archive)))))
3072 (when (eq place 'other-archive)
3073 (setq archive (todo-read-file-name "Choose a todo archive: " t t)))
3074 (when (and (eq place 'this-archive) (zerop count))
3075 (setq place (when (todo-y-or-n-p
3076 (concat "This category has no archived items;"
3077 " visit archive anyway? "))
3078 'other-cat)))
3079 (when place
3080 (set-window-buffer (selected-window)
3081 (set-buffer (find-file-noselect archive)))
3082 (if (member place '(other-archive other-cat))
3083 (setq todo-category-number 1)
3084 (todo-category-number cat))
3085 (todo-category-select)))))
3086
3087 (defun todo-choose-archive ()
3088 "Choose an archive and visit it."
3089 (interactive)
3090 (todo-find-archive t))
3091
3092 (defun todo-archive-done-item (&optional all)
3093 "Archive at least one done item in this category.
3094
3095 With prefix argument ALL, prompt whether to archive all done
3096 items in this category and on confirmation archive them.
3097 Otherwise, if there are marked done items (and no marked todo
3098 items), archive all of these; otherwise, archive the done item at
3099 point.
3100
3101 If the archive of this file does not exist, it is created. If
3102 this category does not exist in the archive, it is created."
3103 (interactive "P")
3104 (when (eq major-mode 'todo-mode)
3105 (if (and all (zerop (todo-get-count 'done)))
3106 (message "No done items in this category")
3107 (catch 'end
3108 (let* ((cat (todo-current-category))
3109 (tbuf (current-buffer))
3110 (marked (assoc cat todo-categories-with-marks))
3111 (afile (concat (file-name-sans-extension
3112 todo-current-todo-file) ".toda"))
3113 (archive (find-file-noselect afile t))
3114 (item (and (todo-done-item-p)
3115 (concat (todo-item-string) "\n")))
3116 (count 0)
3117 (opoint (unless (todo-done-item-p) (point)))
3118 marked-items beg end all-done
3119 buffer-read-only)
3120 (cond
3121 (all
3122 (if (todo-y-or-n-p "Archive all done items in this category? ")
3123 (save-excursion
3124 (save-restriction
3125 (goto-char (point-min))
3126 (widen)
3127 (setq beg (progn
3128 (re-search-forward todo-done-string-start
3129 nil t)
3130 (match-beginning 0))
3131 end (if (re-search-forward
3132 (concat "^"
3133 (regexp-quote todo-category-beg))
3134 nil t)
3135 (match-beginning 0)
3136 (point-max))
3137 all-done (buffer-substring-no-properties beg end)
3138 count (todo-get-count 'done))
3139 ;; Restore starting point, unless it was on a done
3140 ;; item, since they will all be deleted.
3141 (when opoint (goto-char opoint))))
3142 (throw 'end nil)))
3143 (marked
3144 (save-excursion
3145 (goto-char (point-min))
3146 (while (not (eobp))
3147 (when (todo-marked-item-p)
3148 (if (not (todo-done-item-p))
3149 (throw 'end (message "Only done items can be archived"))
3150 (setq marked-items
3151 (concat marked-items (todo-item-string) "\n"))
3152 (setq count (1+ count))))
3153 (todo-forward-item)))))
3154 (if (not (or marked all item))
3155 (throw 'end (message "Only done items can be archived"))
3156 (with-current-buffer archive
3157 (let (buffer-read-only)
3158 (widen)
3159 (goto-char (point-min))
3160 (if (and (re-search-forward
3161 (concat "^" (regexp-quote
3162 (concat todo-category-beg cat)) "$")
3163 nil t)
3164 (re-search-forward (regexp-quote todo-category-done)
3165 nil t))
3166 ;; Start of done items section in existing category.
3167 (forward-char)
3168 (todo-add-category nil cat)
3169 ;; Start of done items section in new category.
3170 (goto-char (point-max)))
3171 (insert (cond (marked marked-items)
3172 (all all-done)
3173 (item)))
3174 (todo-update-count 'done (if (or marked all) count 1) cat)
3175 (todo-update-categories-sexp)
3176 ;; If archive is new, save to file now (with
3177 ;; write-region to avoid prompt for file to save to)
3178 ;; to update todo-archives, and to let auto-mode-alist
3179 ;; take effect below on visiting the archive.
3180 (unless (nth 7 (file-attributes afile))
3181 (write-region nil nil afile t t)
3182 (setq todo-archives (funcall todo-files-function t))
3183 (kill-buffer))))
3184 (with-current-buffer tbuf
3185 (cond
3186 (all
3187 (save-excursion
3188 (save-restriction
3189 ;; Make sure done items are accessible.
3190 (widen)
3191 (remove-overlays beg end)
3192 (delete-region beg end)
3193 (todo-update-count 'done (- count))
3194 (todo-update-count 'archived count))))
3195 ((or marked
3196 ;; If we're archiving all done items, can't
3197 ;; first archive item point was on, since
3198 ;; that will short-circuit the rest.
3199 (and item (not all)))
3200 (and marked (goto-char (point-min)))
3201 (catch 'done
3202 (while (not (eobp))
3203 (if (or (and marked (todo-marked-item-p)) item)
3204 (progn
3205 (todo-remove-item)
3206 (todo-update-count 'done -1)
3207 (todo-update-count 'archived 1)
3208 ;; Don't leave point below last item.
3209 (and item (bolp) (eolp) (< (point-min) (point-max))
3210 (todo-backward-item))
3211 (when item
3212 (throw 'done (setq item nil))))
3213 (todo-forward-item))))))
3214 (when marked
3215 (setq todo-categories-with-marks
3216 (assq-delete-all cat todo-categories-with-marks)))
3217 (todo-update-categories-sexp)
3218 (todo-prefix-overlays)))
3219 (find-file afile)
3220 (todo-category-number cat)
3221 (todo-category-select)
3222 (split-window-below)
3223 (set-window-buffer (selected-window) tbuf)
3224 ;; Make todo file current to select category.
3225 (find-file (buffer-file-name tbuf))
3226 ;; Make sure done item separator is hidden (if done items
3227 ;; were initially visible).
3228 (let (todo-show-with-done) (todo-category-select)))))))
3229
3230 (defun todo-unarchive-items ()
3231 "Unarchive at least one item in this archive category.
3232 If there are marked items, unarchive all of these; otherwise,
3233 unarchive the item at point.
3234
3235 Unarchived items are restored as done items to the corresponding
3236 category in the todo file, inserted at the top of done items
3237 section. If all items in the archive category have been
3238 restored, the category is deleted from the archive. If this was
3239 the only category in the archive, the archive file is deleted."
3240 (interactive)
3241 (when (eq major-mode 'todo-archive-mode)
3242 (let* ((cat (todo-current-category))
3243 (tbuf (find-file-noselect
3244 (concat (file-name-sans-extension todo-current-todo-file)
3245 ".todo") t))
3246 (marked (assoc cat todo-categories-with-marks))
3247 (item (concat (todo-item-string) "\n"))
3248 (marked-count 0)
3249 marked-items
3250 buffer-read-only)
3251 (when marked
3252 (save-excursion
3253 (goto-char (point-min))
3254 (while (not (eobp))
3255 (when (todo-marked-item-p)
3256 (setq marked-items (concat marked-items (todo-item-string) "\n"))
3257 (setq marked-count (1+ marked-count)))
3258 (todo-forward-item))))
3259 ;; Restore items to top of category's done section and update counts.
3260 (with-current-buffer tbuf
3261 (let (buffer-read-only newcat)
3262 (widen)
3263 (goto-char (point-min))
3264 ;; Find the corresponding todo category, or if there isn't
3265 ;; one, add it.
3266 (unless (re-search-forward
3267 (concat "^" (regexp-quote (concat todo-category-beg cat))
3268 "$") nil t)
3269 (todo-add-category nil cat)
3270 (setq newcat t))
3271 ;; Go to top of category's done section.
3272 (re-search-forward
3273 (concat "^" (regexp-quote todo-category-done)) nil t)
3274 (forward-line)
3275 (cond (marked
3276 (insert marked-items)
3277 (todo-update-count 'done marked-count cat)
3278 (unless newcat ; Newly added category has no archive.
3279 (todo-update-count 'archived (- marked-count) cat)))
3280 (t
3281 (insert item)
3282 (todo-update-count 'done 1 cat)
3283 (unless newcat ; Newly added category has no archive.
3284 (todo-update-count 'archived -1 cat))))
3285 (todo-update-categories-sexp)))
3286 ;; Delete restored items from archive.
3287 (when marked
3288 (setq item nil)
3289 (goto-char (point-min)))
3290 (catch 'done
3291 (while (not (eobp))
3292 (if (or (todo-marked-item-p) item)
3293 (progn
3294 (todo-remove-item)
3295 (when item
3296 (throw 'done (setq item nil))))
3297 (todo-forward-item))))
3298 (todo-update-count 'done (if marked (- marked-count) -1) cat)
3299 ;; If that was the last category in the archive, delete the whole file.
3300 (if (= (length todo-categories) 1)
3301 (progn
3302 (delete-file todo-current-todo-file)
3303 ;; Kill the archive buffer silently.
3304 (set-buffer-modified-p nil)
3305 (kill-buffer))
3306 ;; Otherwise, if the archive category is now empty, delete it.
3307 (when (eq (point-min) (point-max))
3308 (widen)
3309 (let ((beg (re-search-backward
3310 (concat "^" (regexp-quote todo-category-beg) cat "$")
3311 nil t))
3312 (end (if (re-search-forward
3313 (concat "^" (regexp-quote todo-category-beg))
3314 nil t 2)
3315 (match-beginning 0)
3316 (point-max))))
3317 (remove-overlays beg end)
3318 (delete-region beg end)
3319 (setq todo-categories (delete (assoc cat todo-categories)
3320 todo-categories))
3321 (todo-update-categories-sexp))))
3322 ;; Visit category in todo file and show restored done items.
3323 (let ((tfile (buffer-file-name tbuf))
3324 (todo-show-with-done t))
3325 (set-window-buffer (selected-window)
3326 (set-buffer (find-file-noselect tfile)))
3327 (todo-category-number cat)
3328 (todo-category-select)
3329 (message "Items unarchived.")))))
3330
3331 (defun todo-jump-to-archive-category (&optional file)
3332 "Prompt for a category in a todo archive and jump to it.
3333 With prefix argument FILE, prompt for an archive and choose (with
3334 TAB completion) a category in it to jump to; otherwise, choose
3335 and jump to any category in the current archive."
3336 (interactive "P")
3337 (todo-jump-to-category file 'archive))
3338
3339 ;; -----------------------------------------------------------------------------
3340 ;;; Displaying and sorting tables of categories
3341 ;; -----------------------------------------------------------------------------
3342
3343 (defcustom todo-categories-category-label "Category"
3344 "Category button label in Todo Categories mode."
3345 :type 'string
3346 :group 'todo-categories)
3347
3348 (defcustom todo-categories-todo-label "Todo"
3349 "Todo button label in Todo Categories mode."
3350 :type 'string
3351 :group 'todo-categories)
3352
3353 (defcustom todo-categories-diary-label "Diary"
3354 "Diary button label in Todo Categories mode."
3355 :type 'string
3356 :group 'todo-categories)
3357
3358 (defcustom todo-categories-done-label "Done"
3359 "Done button label in Todo Categories mode."
3360 :type 'string
3361 :group 'todo-categories)
3362
3363 (defcustom todo-categories-archived-label "Archived"
3364 "Archived button label in Todo Categories mode."
3365 :type 'string
3366 :group 'todo-categories)
3367
3368 (defcustom todo-categories-totals-label "Totals"
3369 "String to label total item counts in Todo Categories mode."
3370 :type 'string
3371 :group 'todo-categories)
3372
3373 (defcustom todo-categories-number-separator " | "
3374 "String between number and category in Todo Categories mode.
3375 This separates the number from the category name in the default
3376 categories display according to priority."
3377 :type 'string
3378 :group 'todo-categories)
3379
3380 (defcustom todo-categories-align 'center
3381 "Alignment of category names in Todo Categories mode."
3382 :type '(radio (const left) (const center) (const right))
3383 :group 'todo-categories)
3384
3385 (defun todo-show-categories-table ()
3386 "Display a table of the current file's categories and item counts.
3387
3388 In the initial display the lines of the table are numbered,
3389 indicating the current order of the categories when sequentially
3390 navigating through the todo file with `\\[todo-forward-category]'
3391 and `\\[todo-backward-category]'. You can reorder the lines, and
3392 hence the category sequence, by typing `\\[todo-raise-category]'
3393 or `\\[todo-lower-category]' to raise or lower the category at
3394 point, or by typing `\\[todo-set-category-number]' and entering a
3395 number at the prompt or by typing `\\[todo-set-category-number]'
3396 with a numeric prefix. If you save the todo file after
3397 reordering the categories, the new order persists in subsequent
3398 Emacs sessions.
3399
3400 The labels above the category names and item counts are buttons,
3401 and clicking these changes the display: sorted by category name
3402 or by the respective item counts (alternately descending or
3403 ascending). In these displays the categories are not numbered
3404 and `\\[todo-set-category-number]', `\\[todo-raise-category]' and
3405 `\\[todo-lower-category]' are disabled. (Programmatically, the
3406 sorting is triggered by passing a non-nil SORTKEY argument.)
3407
3408 In addition, the lines with the category names and item counts
3409 are buttonized, and pressing one of these button jumps to the
3410 category in Todo mode (or Todo Archive mode, for categories
3411 containing only archived items, provided user option
3412 `todo-skip-archived-categories' is non-nil. These categories
3413 are shown in `todo-archived-only' face."
3414 (interactive)
3415 (todo-display-categories)
3416 (let (sortkey)
3417 (todo-update-categories-display sortkey)))
3418
3419 (defun todo-next-button (n)
3420 "Move point to the Nth next button in the table of categories."
3421 (interactive "p")
3422 (forward-button n 'wrap 'display-message)
3423 (and (bolp) (button-at (point))
3424 ;; Align with beginning of category label.
3425 (forward-char (+ 4 (length todo-categories-number-separator)))))
3426
3427 (defun todo-previous-button (n)
3428 "Move point to the Nth previous button in the table of categories."
3429 (interactive "p")
3430 (backward-button n 'wrap 'display-message)
3431 (and (bolp) (button-at (point))
3432 ;; Align with beginning of category label.
3433 (forward-char (+ 4 (length todo-categories-number-separator)))))
3434
3435 (defun todo-set-category-number (&optional arg)
3436 "Change number of category at point in the table of categories.
3437
3438 With ARG nil, prompt for the new number. Alternatively, the
3439 enter the new number with numerical prefix ARG. Otherwise, if
3440 ARG is either of the symbols `raise' or `lower', raise or lower
3441 the category line in the table by one, respectively, thereby
3442 decreasing or increasing its number."
3443 (interactive "P")
3444 (let ((curnum (save-excursion
3445 ;; Get the number representing the priority of the category
3446 ;; on the current line.
3447 (forward-line 0) (skip-chars-forward " ") (number-at-point))))
3448 (when curnum ; Do nothing if we're not on a category line.
3449 (let* ((maxnum (length todo-categories))
3450 (prompt (format "Set category priority (1-%d): " maxnum))
3451 (col (current-column))
3452 (buffer-read-only nil)
3453 (priority (cond ((and (eq arg 'raise) (> curnum 1))
3454 (1- curnum))
3455 ((and (eq arg 'lower) (< curnum maxnum))
3456 (1+ curnum))))
3457 candidate)
3458 (while (not priority)
3459 (setq candidate (or arg (read-number prompt)))
3460 (setq arg nil)
3461 (setq prompt
3462 (cond ((or (< candidate 1) (> candidate maxnum))
3463 (format "Priority must be an integer between 1 and %d: "
3464 maxnum))
3465 ((= candidate curnum)
3466 "Choose a different priority than the current one: ")))
3467 (unless prompt (setq priority candidate)))
3468 (let* ((lower (< curnum priority)) ; Priority is being lowered.
3469 (head (butlast todo-categories
3470 (apply (if lower 'identity '1+)
3471 (list (- maxnum priority)))))
3472 (tail (nthcdr (apply (if lower 'identity '1-) (list priority))
3473 todo-categories))
3474 ;; Category's name and items counts list.
3475 (catcons (nth (1- curnum) todo-categories))
3476 (todo-categories (nconc head (list catcons) tail))
3477 newcats)
3478 (when lower (setq todo-categories (nreverse todo-categories)))
3479 (setq todo-categories (delete-dups todo-categories))
3480 (when lower (setq todo-categories (nreverse todo-categories)))
3481 (setq newcats todo-categories)
3482 (kill-buffer)
3483 (with-current-buffer (find-buffer-visiting todo-current-todo-file)
3484 (setq todo-categories newcats)
3485 (todo-update-categories-sexp))
3486 (todo-show-categories-table)
3487 (forward-line (1+ priority))
3488 (forward-char col))))))
3489
3490 (defun todo-raise-category ()
3491 "Raise priority of category at point in the table of categories."
3492 (interactive)
3493 (todo-set-category-number 'raise))
3494
3495 (defun todo-lower-category ()
3496 "Lower priority of category at point in the table of categories."
3497 (interactive)
3498 (todo-set-category-number 'lower))
3499
3500 (defun todo-sort-categories-alphabetically-or-numerically ()
3501 "Sort table of categories alphabetically or numerically."
3502 (interactive)
3503 (save-excursion
3504 (goto-char (point-min))
3505 (forward-line 2)
3506 (if (member 'alpha todo-descending-counts)
3507 (progn
3508 (todo-update-categories-display nil)
3509 (setq todo-descending-counts
3510 (delete 'alpha todo-descending-counts)))
3511 (todo-update-categories-display 'alpha))))
3512
3513 (defun todo-sort-categories-by-todo ()
3514 "Sort table of categories by number of todo items."
3515 (interactive)
3516 (save-excursion
3517 (goto-char (point-min))
3518 (forward-line 2)
3519 (todo-update-categories-display 'todo)))
3520
3521 (defun todo-sort-categories-by-diary ()
3522 "Sort table of categories by number of diary items."
3523 (interactive)
3524 (save-excursion
3525 (goto-char (point-min))
3526 (forward-line 2)
3527 (todo-update-categories-display 'diary)))
3528
3529 (defun todo-sort-categories-by-done ()
3530 "Sort table of categories by number of non-archived done items."
3531 (interactive)
3532 (save-excursion
3533 (goto-char (point-min))
3534 (forward-line 2)
3535 (todo-update-categories-display 'done)))
3536
3537 (defun todo-sort-categories-by-archived ()
3538 "Sort table of categories by number of archived items."
3539 (interactive)
3540 (save-excursion
3541 (goto-char (point-min))
3542 (forward-line 2)
3543 (todo-update-categories-display 'archived)))
3544
3545 (defvar todo-categories-buffer "*Todo Categories*"
3546 "Name of buffer in Todo Categories mode.")
3547
3548 (defun todo-longest-category-name-length (categories)
3549 "Return the length of the longest name in list CATEGORIES."
3550 (let ((longest 0))
3551 (dolist (c categories longest)
3552 (setq longest (max longest (length c))))))
3553
3554 (defun todo-adjusted-category-label-length ()
3555 "Return adjusted length of category label button.
3556 The adjustment ensures proper tabular alignment in Todo
3557 Categories mode."
3558 (let* ((categories (mapcar 'car todo-categories))
3559 (longest (todo-longest-category-name-length categories))
3560 (catlablen (length todo-categories-category-label))
3561 (lc-diff (- longest catlablen)))
3562 (if (and (natnump lc-diff) (cl-oddp lc-diff))
3563 (1+ longest)
3564 (max longest catlablen))))
3565
3566 (defun todo-padded-string (str)
3567 "Return category name or label string STR padded with spaces.
3568 The placement of the padding is determined by the value of user
3569 option `todo-categories-align'."
3570 (let* ((len (todo-adjusted-category-label-length))
3571 (strlen (length str))
3572 (strlen-odd (eq (logand strlen 1) 1))
3573 (padding (max 0 (/ (- len strlen) 2)))
3574 (padding-left (cond ((eq todo-categories-align 'left) 0)
3575 ((eq todo-categories-align 'center) padding)
3576 ((eq todo-categories-align 'right)
3577 (if strlen-odd (1+ (* padding 2)) (* padding 2)))))
3578 (padding-right (cond ((eq todo-categories-align 'left)
3579 (if strlen-odd (1+ (* padding 2)) (* padding 2)))
3580 ((eq todo-categories-align 'center)
3581 (if strlen-odd (1+ padding) padding))
3582 ((eq todo-categories-align 'right) 0))))
3583 (concat (make-string padding-left 32) str (make-string padding-right 32))))
3584
3585 (defvar todo-descending-counts nil
3586 "List of keys for category counts sorted in descending order.")
3587
3588 (defun todo-sort (list &optional key)
3589 "Return a copy of LIST, possibly sorted according to KEY."
3590 (let* ((l (copy-sequence list))
3591 (fn (if (eq key 'alpha)
3592 (lambda (x) (upcase x)) ; Alphabetize case insensitively.
3593 (lambda (x) (todo-get-count key x))))
3594 ;; Keep track of whether the last sort by key was descending or
3595 ;; ascending.
3596 (descending (member key todo-descending-counts))
3597 (cmp (if (eq key 'alpha)
3598 'string<
3599 (if descending '< '>)))
3600 (pred (lambda (s1 s2) (let ((t1 (funcall fn (car s1)))
3601 (t2 (funcall fn (car s2))))
3602 (funcall cmp t1 t2)))))
3603 (when key
3604 (setq l (sort l pred))
3605 ;; Switch between descending and ascending sort order.
3606 (if descending
3607 (setq todo-descending-counts
3608 (delete key todo-descending-counts))
3609 (push key todo-descending-counts)))
3610 l))
3611
3612 (defun todo-display-sorted (type)
3613 "Keep point on the TYPE count sorting button just clicked."
3614 (let ((opoint (point)))
3615 (todo-update-categories-display type)
3616 (goto-char opoint)))
3617
3618 (defun todo-label-to-key (label)
3619 "Return symbol for sort key associated with LABEL."
3620 (let (key)
3621 (cond ((string= label todo-categories-category-label)
3622 (setq key 'alpha))
3623 ((string= label todo-categories-todo-label)
3624 (setq key 'todo))
3625 ((string= label todo-categories-diary-label)
3626 (setq key 'diary))
3627 ((string= label todo-categories-done-label)
3628 (setq key 'done))
3629 ((string= label todo-categories-archived-label)
3630 (setq key 'archived)))
3631 key))
3632
3633 (defun todo-insert-sort-button (label)
3634 "Insert button for displaying categories sorted by item counts.
3635 LABEL determines which type of count is sorted."
3636 (let* ((str (if (string= label todo-categories-category-label)
3637 (todo-padded-string label)
3638 label))
3639 (beg (point))
3640 (end (+ beg (length str)))
3641 ov)
3642 (insert-button str 'face nil
3643 'action
3644 `(lambda (button)
3645 (let ((key (todo-label-to-key ,label)))
3646 (if (and (member key todo-descending-counts)
3647 (eq key 'alpha))
3648 (progn
3649 ;; If display is alphabetical, switch back to
3650 ;; category priority order.
3651 (todo-display-sorted nil)
3652 (setq todo-descending-counts
3653 (delete key todo-descending-counts)))
3654 (todo-display-sorted key)))))
3655 (setq ov (make-overlay beg end))
3656 (overlay-put ov 'face 'todo-button)))
3657
3658 (defun todo-total-item-counts ()
3659 "Return a list of total item counts for the current file."
3660 (mapcar (lambda (i) (apply '+ (mapcar (lambda (l) (aref l i))
3661 (mapcar 'cdr todo-categories))))
3662 (list 0 1 2 3)))
3663
3664 (defvar todo-categories-category-number 0
3665 "Variable for numbering categories in Todo Categories mode.")
3666
3667 (defun todo-insert-category-line (cat &optional nonum)
3668 "Insert button with category CAT's name and item counts.
3669 With non-nil argument NONUM show only these; otherwise, insert a
3670 number in front of the button indicating the category's priority.
3671 The number and the category name are separated by the string
3672 which is the value of the user option
3673 `todo-categories-number-separator'."
3674 (let ((archive (member todo-current-todo-file todo-archives))
3675 (num todo-categories-category-number)
3676 (str (todo-padded-string cat))
3677 (opoint (point)))
3678 (setq num (1+ num) todo-categories-category-number num)
3679 (insert-button
3680 (concat (if nonum
3681 (make-string (+ 4 (length todo-categories-number-separator))
3682 32)
3683 (format " %3d%s" num todo-categories-number-separator))
3684 str
3685 (mapconcat (lambda (elt)
3686 (concat
3687 (make-string (1+ (/ (length (car elt)) 2)) 32) ; label
3688 (format "%3d" (todo-get-count (cdr elt) cat)) ; count
3689 ;; Add an extra space if label length is odd.
3690 (when (cl-oddp (length (car elt))) " ")))
3691 (if archive
3692 (list (cons todo-categories-done-label 'done))
3693 (list (cons todo-categories-todo-label 'todo)
3694 (cons todo-categories-diary-label 'diary)
3695 (cons todo-categories-done-label 'done)
3696 (cons todo-categories-archived-label
3697 'archived)))
3698 "")
3699 " ") ; Make highlighting on last column look better.
3700 'face (if (and todo-skip-archived-categories
3701 (zerop (todo-get-count 'todo cat))
3702 (zerop (todo-get-count 'done cat))
3703 (not (zerop (todo-get-count 'archived cat))))
3704 'todo-archived-only
3705 nil)
3706 'action `(lambda (button) (let ((buf (current-buffer)))
3707 (todo-jump-to-category nil ,cat)
3708 (kill-buffer buf))))
3709 ;; Highlight the sorted count column.
3710 (let* ((beg (+ opoint 7 (length str)))
3711 end ovl)
3712 (cond ((eq nonum 'todo)
3713 (setq beg (+ beg 1 (/ (length todo-categories-todo-label) 2))))
3714 ((eq nonum 'diary)
3715 (setq beg (+ beg 1 (length todo-categories-todo-label)
3716 2 (/ (length todo-categories-diary-label) 2))))
3717 ((eq nonum 'done)
3718 (setq beg (+ beg 1 (length todo-categories-todo-label)
3719 2 (length todo-categories-diary-label)
3720 2 (/ (length todo-categories-done-label) 2))))
3721 ((eq nonum 'archived)
3722 (setq beg (+ beg 1 (length todo-categories-todo-label)
3723 2 (length todo-categories-diary-label)
3724 2 (length todo-categories-done-label)
3725 2 (/ (length todo-categories-archived-label) 2)))))
3726 (unless (= beg (+ opoint 7 (length str))) ; Don't highlight categories.
3727 (setq end (+ beg 4))
3728 (setq ovl (make-overlay beg end))
3729 (overlay-put ovl 'face 'todo-sorted-column)))
3730 (newline)))
3731
3732 (defun todo-display-categories ()
3733 "Prepare buffer for displaying table of categories and item counts."
3734 (unless (eq major-mode 'todo-categories-mode)
3735 (setq todo-global-current-todo-file
3736 (or todo-current-todo-file
3737 (todo-absolute-file-name todo-default-todo-file)))
3738 (set-window-buffer (selected-window)
3739 (set-buffer (get-buffer-create todo-categories-buffer)))
3740 (kill-all-local-variables)
3741 (todo-categories-mode)
3742 (let ((archive (member todo-current-todo-file todo-archives))
3743 buffer-read-only)
3744 (erase-buffer)
3745 (insert (format (concat "Category counts for todo "
3746 (if archive "archive" "file")
3747 " \"%s\".")
3748 (todo-short-file-name todo-current-todo-file)))
3749 (newline 2)
3750 ;; Make space for the column of category numbers.
3751 (insert (make-string (+ 4 (length todo-categories-number-separator)) 32))
3752 ;; Add the category and item count buttons (if this is the list of
3753 ;; categories in an archive, show only done item counts).
3754 (todo-insert-sort-button todo-categories-category-label)
3755 (if archive
3756 (progn
3757 (insert (make-string 3 32))
3758 (todo-insert-sort-button todo-categories-done-label))
3759 (insert (make-string 3 32))
3760 (todo-insert-sort-button todo-categories-todo-label)
3761 (insert (make-string 2 32))
3762 (todo-insert-sort-button todo-categories-diary-label)
3763 (insert (make-string 2 32))
3764 (todo-insert-sort-button todo-categories-done-label)
3765 (insert (make-string 2 32))
3766 (todo-insert-sort-button todo-categories-archived-label))
3767 (newline 2))))
3768
3769 (defun todo-update-categories-display (sortkey)
3770 "Populate table of categories and sort by SORTKEY."
3771 (let* ((cats0 todo-categories)
3772 (cats (todo-sort cats0 sortkey))
3773 (archive (member todo-current-todo-file todo-archives))
3774 (todo-categories-category-number 0)
3775 ;; Find start of Category button if we just entered Todo Categories
3776 ;; mode.
3777 (pt (if (eq (point) (point-max))
3778 (save-excursion
3779 (forward-line -2)
3780 (goto-char (next-single-char-property-change
3781 (point) 'face nil (line-end-position))))))
3782 (buffer-read-only))
3783 (forward-line 2)
3784 (delete-region (point) (point-max))
3785 ;; Fill in the table with buttonized lines, each showing a category and
3786 ;; its item counts.
3787 (mapc (lambda (cat) (todo-insert-category-line cat sortkey))
3788 (mapcar 'car cats))
3789 (newline)
3790 ;; Add a line showing item count totals.
3791 (insert (make-string (+ 4 (length todo-categories-number-separator)) 32)
3792 (todo-padded-string todo-categories-totals-label)
3793 (mapconcat
3794 (lambda (elt)
3795 (concat
3796 (make-string (1+ (/ (length (car elt)) 2)) 32)
3797 (format "%3d" (nth (cdr elt) (todo-total-item-counts)))
3798 ;; Add an extra space if label length is odd.
3799 (when (cl-oddp (length (car elt))) " ")))
3800 (if archive
3801 (list (cons todo-categories-done-label 2))
3802 (list (cons todo-categories-todo-label 0)
3803 (cons todo-categories-diary-label 1)
3804 (cons todo-categories-done-label 2)
3805 (cons todo-categories-archived-label 3)))
3806 ""))
3807 ;; Put cursor on Category button initially.
3808 (if pt (goto-char pt))
3809 (setq buffer-read-only t)))
3810
3811 ;; -----------------------------------------------------------------------------
3812 ;;; Searching and item filtering
3813 ;; -----------------------------------------------------------------------------
3814
3815 (defun todo-search ()
3816 "Search for a regular expression in this todo file.
3817 The search runs through the whole file and encompasses all and
3818 only todo and done items; it excludes category names. Multiple
3819 matches are shown sequentially, highlighted in `todo-search'
3820 face."
3821 (interactive)
3822 (let ((regex (read-from-minibuffer "Enter a search string (regexp): "))
3823 (opoint (point))
3824 matches match cat in-done ov mlen msg)
3825 (widen)
3826 (goto-char (point-min))
3827 (while (not (eobp))
3828 (setq match (re-search-forward regex nil t))
3829 (goto-char (line-beginning-position))
3830 (unless (or (equal (point) 1)
3831 (looking-at (concat "^" (regexp-quote todo-category-beg))))
3832 (if match (push match matches)))
3833 (forward-line))
3834 (setq matches (reverse matches))
3835 (if matches
3836 (catch 'stop
3837 (while matches
3838 (setq match (pop matches))
3839 (goto-char match)
3840 (todo-item-start)
3841 (when (looking-at todo-done-string-start)
3842 (setq in-done t))
3843 (re-search-backward (concat "^" (regexp-quote todo-category-beg)
3844 "\\(.*\\)\n") nil t)
3845 (setq cat (match-string-no-properties 1))
3846 (todo-category-number cat)
3847 (todo-category-select)
3848 (if in-done
3849 (unless todo-show-with-done (todo-toggle-view-done-items)))
3850 (goto-char match)
3851 (setq ov (make-overlay (- (point) (length regex)) (point)))
3852 (overlay-put ov 'face 'todo-search)
3853 (when matches
3854 (setq mlen (length matches))
3855 (if (todo-y-or-n-p
3856 (if (> mlen 1)
3857 (format "There are %d more matches; go to next match? "
3858 mlen)
3859 "There is one more match; go to it? "))
3860 (widen)
3861 (throw 'stop (setq msg (if (> mlen 1)
3862 (format "There are %d more matches."
3863 mlen)
3864 "There is one more match."))))))
3865 (setq msg "There are no more matches."))
3866 (todo-category-select)
3867 (goto-char opoint)
3868 (message "No match for \"%s\"" regex))
3869 (when msg
3870 (if (todo-y-or-n-p (concat msg "\nUnhighlight matches? "))
3871 (todo-clear-matches)
3872 (message "You can unhighlight the matches later by typing %s"
3873 (key-description (car (where-is-internal
3874 'todo-clear-matches))))))))
3875
3876 (defun todo-clear-matches ()
3877 "Remove highlighting on matches found by todo-search."
3878 (interactive)
3879 (remove-overlays 1 (1+ (buffer-size)) 'face 'todo-search))
3880
3881 (defcustom todo-top-priorities-overrides nil
3882 "List of rules specifying number of top priority items to show.
3883 These rules override `todo-top-priorities' on invocations of
3884 `\\[todo-filter-top-priorities]' and
3885 `\\[todo-filter-top-priorities-multifile]'. Each rule is a list
3886 of the form (FILE NUM ALIST), where FILE is a member of
3887 `todo-files', NUM is a number specifying the default number of
3888 top priority items for each category in that file, and ALIST,
3889 when non-nil, consists of conses of a category name in FILE and a
3890 number specifying the default number of top priority items in
3891 that category, which overrides NUM.
3892
3893 This variable should be set interactively by
3894 `\\[todo-set-top-priorities-in-file]' or
3895 `\\[todo-set-top-priorities-in-category]'."
3896 :type 'sexp
3897 :group 'todo-filtered)
3898
3899 (defcustom todo-top-priorities 1
3900 "Default number of top priorities shown by `todo-filter-top-priorities'."
3901 :type 'integer
3902 :group 'todo-filtered)
3903
3904 (defcustom todo-filter-files nil
3905 "List of default files for multifile item filtering."
3906 :type `(set ,@(mapcar (lambda (f) (list 'const f))
3907 (mapcar 'todo-short-file-name
3908 (funcall todo-files-function))))
3909 :group 'todo-filtered)
3910
3911 (defcustom todo-filter-done-items nil
3912 "Non-nil to include done items when processing regexp filters.
3913 Done items from corresponding archive files are also included."
3914 :type 'boolean
3915 :group 'todo-filtered)
3916
3917 (defun todo-set-top-priorities-in-file ()
3918 "Set number of top priorities for this file.
3919 See `todo-set-top-priorities' for more details."
3920 (interactive)
3921 (todo-set-top-priorities))
3922
3923 (defun todo-set-top-priorities-in-category ()
3924 "Set number of top priorities for this category.
3925 See `todo-set-top-priorities' for more details."
3926 (interactive)
3927 (todo-set-top-priorities t))
3928
3929 (defun todo-filter-top-priorities (&optional arg)
3930 "Display a list of top priority items from different categories.
3931 The categories can be any of those in the current todo file.
3932
3933 With numerical prefix ARG show at most ARG top priority items
3934 from each category. With `C-u' as prefix argument show the
3935 numbers of top priority items specified by category in
3936 `todo-top-priorities-overrides', if this has an entry for the file(s);
3937 otherwise show `todo-top-priorities' items per category in the
3938 file(s). With no prefix argument, if a top priorities file for
3939 the current todo file has previously been saved (see
3940 `todo-save-filtered-items-buffer'), visit this file; if there is
3941 no such file, build the list as with prefix argument `C-u'.
3942
3943 The prefix ARG regulates how many top priorities from
3944 each category to show, as described above."
3945 (interactive "P")
3946 (todo-filter-items 'top arg))
3947
3948 (defun todo-filter-top-priorities-multifile (&optional arg)
3949 "Display a list of top priority items from different categories.
3950 The categories are a subset of the categories in the files listed
3951 in `todo-filter-files', or if this nil, in the files chosen from
3952 a file selection dialog that pops up in this case.
3953
3954 With numerical prefix ARG show at most ARG top priority items
3955 from each category in each file. With `C-u' as prefix argument
3956 show the numbers of top priority items specified in
3957 `todo-top-priorities-overrides', if this is non-nil; otherwise show
3958 `todo-top-priorities' items per category. With no prefix
3959 argument, if a top priorities file for the chosen todo files
3960 exists (see `todo-save-filtered-items-buffer'), visit this file;
3961 if there is no such file, do the same as with prefix argument
3962 `C-u'."
3963 (interactive "P")
3964 (todo-filter-items 'top arg t))
3965
3966 (defun todo-filter-diary-items (&optional arg)
3967 "Display a list of todo diary items from different categories.
3968 The categories can be any of those in the current todo file.
3969
3970 Called with no prefix ARG, if a diary items file for the current
3971 todo file has previously been saved (see
3972 `todo-save-filtered-items-buffer'), visit this file; if there is
3973 no such file, build the list of diary items. Called with a
3974 prefix argument, build the list even if there is a saved file of
3975 diary items."
3976 (interactive "P")
3977 (todo-filter-items 'diary arg))
3978
3979 (defun todo-filter-diary-items-multifile (&optional arg)
3980 "Display a list of todo diary items from different categories.
3981 The categories are a subset of the categories in the files listed
3982 in `todo-filter-files', or if this nil, in the files chosen from
3983 a file selection dialog that pops up in this case.
3984
3985 Called with no prefix ARG, if a diary items file for the chosen
3986 todo files has previously been saved (see
3987 `todo-save-filtered-items-buffer'), visit this file; if there is
3988 no such file, build the list of diary items. Called with a
3989 prefix argument, build the list even if there is a saved file of
3990 diary items."
3991 (interactive "P")
3992 (todo-filter-items 'diary arg t))
3993
3994 (defun todo-filter-regexp-items (&optional arg)
3995 "Prompt for a regular expression and display items that match it.
3996 The matches can be from any categories in the current todo file
3997 and with non-nil option `todo-filter-done-items', can include
3998 not only todo items but also done items, including those in
3999 Archive files.
4000
4001 Called with no prefix ARG, if a regexp items file for the current
4002 todo file has previously been saved (see
4003 `todo-save-filtered-items-buffer'), visit this file; if there is
4004 no such file, build the list of regexp items. Called with a
4005 prefix argument, build the list even if there is a saved file of
4006 regexp items."
4007 (interactive "P")
4008 (todo-filter-items 'regexp arg))
4009
4010 (defun todo-filter-regexp-items-multifile (&optional arg)
4011 "Prompt for a regular expression and display items that match it.
4012 The matches can be from any categories in the files listed in
4013 `todo-filter-files', or if this nil, in the files chosen from a
4014 file selection dialog that pops up in this case. With non-nil
4015 option `todo-filter-done-items', the matches can include not
4016 only todo items but also done items, including those in Archive
4017 files.
4018
4019 Called with no prefix ARG, if a regexp items file for the current
4020 todo file has previously been saved (see
4021 `todo-save-filtered-items-buffer'), visit this file; if there is
4022 no such file, build the list of regexp items. Called with a
4023 prefix argument, build the list even if there is a saved file of
4024 regexp items."
4025 (interactive "P")
4026 (todo-filter-items 'regexp arg t))
4027
4028 (defun todo-find-filtered-items-file ()
4029 "Choose a filtered items file and visit it."
4030 (interactive)
4031 (let ((files (directory-files todo-directory t "\.tod[rty]$" t))
4032 falist file)
4033 (dolist (f files)
4034 (let ((type (cond ((equal (file-name-extension f) "todr") "regexp")
4035 ((equal (file-name-extension f) "todt") "top")
4036 ((equal (file-name-extension f) "tody") "diary"))))
4037 (push (cons (concat (todo-short-file-name f) " (" type ")") f)
4038 falist)))
4039 (setq file (completing-read "Choose a filtered items file: "
4040 falist nil t nil nil (car falist)))
4041 (setq file (cdr (assoc-string file falist)))
4042 (find-file file)))
4043
4044 (defun todo-go-to-source-item ()
4045 "Display the file and category of the filtered item at point."
4046 (interactive)
4047 (let* ((str (todo-item-string))
4048 (buf (current-buffer))
4049 (res (todo-find-item str))
4050 (found (nth 0 res))
4051 (file (nth 1 res))
4052 (cat (nth 2 res)))
4053 (if (not found)
4054 (message "Category %s does not contain this item." cat)
4055 (kill-buffer buf)
4056 (set-window-buffer (selected-window)
4057 (set-buffer (find-buffer-visiting file)))
4058 (setq todo-current-todo-file file)
4059 (setq todo-category-number (todo-category-number cat))
4060 (let ((todo-show-with-done (if (or todo-filter-done-items
4061 (eq (cdr found) 'done))
4062 t
4063 todo-show-with-done)))
4064 (todo-category-select))
4065 (goto-char (car found)))))
4066
4067 (defvar todo-multiple-filter-files nil
4068 "List of files selected from `todo-multiple-filter-files' widget.")
4069
4070 (defvar todo-multiple-filter-files-widget nil
4071 "Variable holding widget created by `todo-multiple-filter-files'.")
4072
4073 (defun todo-multiple-filter-files ()
4074 "Pop to a buffer with a widget for choosing multiple filter files."
4075 (require 'widget)
4076 (eval-when-compile
4077 (require 'wid-edit))
4078 (with-current-buffer (get-buffer-create "*Todo Filter Files*")
4079 (pop-to-buffer (current-buffer))
4080 (erase-buffer)
4081 (kill-all-local-variables)
4082 (widget-insert "Select files for generating the top priorities list.\n\n")
4083 (setq todo-multiple-filter-files-widget
4084 (widget-create
4085 `(set ,@(mapcar (lambda (x) (list 'const x))
4086 (mapcar 'todo-short-file-name
4087 (funcall todo-files-function))))))
4088 (widget-insert "\n")
4089 (widget-create 'push-button
4090 :notify (lambda (widget &rest ignore)
4091 (setq todo-multiple-filter-files 'quit)
4092 (quit-window t)
4093 (exit-recursive-edit))
4094 "Cancel")
4095 (widget-insert " ")
4096 (widget-create 'push-button
4097 :notify (lambda (&rest ignore)
4098 (setq todo-multiple-filter-files
4099 (mapcar (lambda (f)
4100 (file-truename
4101 (concat todo-directory
4102 f ".todo")))
4103 (widget-value
4104 todo-multiple-filter-files-widget)))
4105 (quit-window t)
4106 (exit-recursive-edit))
4107 "Apply")
4108 (use-local-map widget-keymap)
4109 (widget-setup))
4110 (message "Click \"Apply\" after selecting files.")
4111 (recursive-edit))
4112
4113 (defconst todo-filtered-items-buffer "Todo filtered items"
4114 "Initial name of buffer in Todo Filter Items mode.")
4115
4116 (defconst todo-top-priorities-buffer "Todo top priorities"
4117 "Buffer type string for `todo-filter-items'.")
4118
4119 (defconst todo-diary-items-buffer "Todo diary items"
4120 "Buffer type string for `todo-filter-items'.")
4121
4122 (defconst todo-regexp-items-buffer "Todo regexp items"
4123 "Buffer type string for `todo-filter-items'.")
4124
4125 (defun todo-filter-items (filter &optional new multifile)
4126 "Display a list of items filtered by FILTER.
4127 The values of FILTER can be `top' for top priority items, a cons
4128 of `top' and a number passed by the caller, `diary' for diary
4129 items, or `regexp' for items matching a regular expression
4130 entered by the user. The items can come from any categories in
4131 the current todo file or, with non-nil MULTIFILE, from several
4132 files. If NEW is nil, visit an appropriate file containing the
4133 list of filtered items; if there is no such file, or with non-nil
4134 NEW, build the list and display it.
4135
4136 See the documentation strings of the commands
4137 `todo-filter-top-priorities', `todo-filter-diary-items',
4138 `todo-filter-regexp-items', and those of the corresponding
4139 multifile commands for further details."
4140 (let* ((top (eq filter 'top))
4141 (diary (eq filter 'diary))
4142 (regexp (eq filter 'regexp))
4143 (buf (cond (top todo-top-priorities-buffer)
4144 (diary todo-diary-items-buffer)
4145 (regexp todo-regexp-items-buffer)))
4146 (flist (if multifile
4147 (or todo-filter-files
4148 (progn (todo-multiple-filter-files)
4149 todo-multiple-filter-files))
4150 (list todo-current-todo-file)))
4151 (multi (> (length flist) 1))
4152 (fname (if (equal flist 'quit)
4153 ;; Pressed `cancel' in t-m-f-f file selection dialog.
4154 (keyboard-quit)
4155 (concat todo-directory
4156 (mapconcat 'todo-short-file-name flist "-")
4157 (cond (top ".todt")
4158 (diary ".tody")
4159 (regexp ".todr")))))
4160 (rxfiles (when regexp
4161 (directory-files todo-directory t ".*\\.todr$" t)))
4162 (file-exists (or (file-exists-p fname) rxfiles)))
4163 (cond ((and top new (natnump new))
4164 (todo-filter-items-1 (cons 'top new) flist))
4165 ((and (not new) file-exists)
4166 (when (and rxfiles (> (length rxfiles) 1))
4167 (let ((rxf (mapcar 'todo-short-file-name rxfiles)))
4168 (setq fname (todo-absolute-file-name
4169 (completing-read "Choose a regexp items file: "
4170 rxf) 'regexp))))
4171 (find-file fname)
4172 (todo-prefix-overlays)
4173 (todo-check-filtered-items-file))
4174 (t
4175 (todo-filter-items-1 filter flist)))
4176 (setq fname (replace-regexp-in-string "-" ", "
4177 (todo-short-file-name fname)))
4178 (rename-buffer (format (concat "%s for file" (if multi "s" "")
4179 " \"%s\"") buf fname))))
4180
4181 (defun todo-filter-items-1 (filter file-list)
4182 "Build a list of items by applying FILTER to FILE-LIST.
4183 Internal subroutine called by `todo-filter-items', which passes
4184 the values of FILTER and FILE-LIST."
4185 (let ((num (if (consp filter) (cdr filter) todo-top-priorities))
4186 (buf (get-buffer-create todo-filtered-items-buffer))
4187 (multifile (> (length file-list) 1))
4188 regexp fname bufstr cat beg end done)
4189 (if (null file-list)
4190 (user-error "No files have been chosen for filtering")
4191 (with-current-buffer buf
4192 (erase-buffer)
4193 (kill-all-local-variables)
4194 (todo-filtered-items-mode))
4195 (when (eq filter 'regexp)
4196 (setq regexp (read-string "Enter a regular expression: ")))
4197 (save-current-buffer
4198 (dolist (f file-list)
4199 ;; Before inserting file contents into temp buffer, save a modified
4200 ;; buffer visiting it.
4201 (let ((bf (find-buffer-visiting f)))
4202 (when (buffer-modified-p bf)
4203 (with-current-buffer bf (save-buffer))))
4204 (setq fname (todo-short-file-name f))
4205 (with-temp-buffer
4206 (when (and todo-filter-done-items (eq filter 'regexp))
4207 ;; If there is a corresponding archive file for the
4208 ;; todo file, insert it first and add identifiers for
4209 ;; todo-go-to-source-item.
4210 (let ((arch (concat (file-name-sans-extension f) ".toda")))
4211 (when (file-exists-p arch)
4212 (insert-file-contents arch)
4213 ;; Delete todo archive file's categories sexp.
4214 (delete-region (line-beginning-position)
4215 (1+ (line-end-position)))
4216 (save-excursion
4217 (while (not (eobp))
4218 (when (re-search-forward
4219 (concat (if todo-filter-done-items
4220 (concat "\\(?:" todo-done-string-start
4221 "\\|" todo-date-string-start
4222 "\\)")
4223 todo-date-string-start)
4224 todo-date-pattern "\\(?: "
4225 diary-time-regexp "\\)?"
4226 (if todo-filter-done-items
4227 "\\]"
4228 (regexp-quote todo-nondiary-end)) "?")
4229 nil t)
4230 (insert "(archive) "))
4231 (forward-line))))))
4232 (insert-file-contents f)
4233 ;; Delete todo file's categories sexp.
4234 (delete-region (line-beginning-position) (1+ (line-end-position)))
4235 (let (fnum)
4236 ;; Unless the number of top priorities to show was
4237 ;; passed by the caller, the file-wide value from
4238 ;; `todo-top-priorities-overrides', if non-nil, overrides
4239 ;; `todo-top-priorities'.
4240 (unless (consp filter)
4241 (setq fnum (or (nth 1 (assoc f todo-top-priorities-overrides))
4242 todo-top-priorities)))
4243 (while (re-search-forward
4244 (concat "^" (regexp-quote todo-category-beg)
4245 "\\(.+\\)\n") nil t)
4246 (setq cat (match-string 1))
4247 (let (cnum)
4248 ;; Unless the number of top priorities to show was
4249 ;; passed by the caller, the category-wide value
4250 ;; from `todo-top-priorities-overrides', if non-nil,
4251 ;; overrides a non-nil file-wide value from
4252 ;; `todo-top-priorities-overrides' as well as
4253 ;; `todo-top-priorities'.
4254 (unless (consp filter)
4255 (let ((cats (nth 2 (assoc f todo-top-priorities-overrides))))
4256 (setq cnum (or (cdr (assoc cat cats)) fnum))))
4257 (delete-region (match-beginning 0) (match-end 0))
4258 (setq beg (point)) ; First item in the current category.
4259 (setq end (if (re-search-forward
4260 (concat "^" (regexp-quote todo-category-beg))
4261 nil t)
4262 (match-beginning 0)
4263 (point-max)))
4264 (goto-char beg)
4265 (setq done
4266 (if (re-search-forward
4267 (concat "\n" (regexp-quote todo-category-done))
4268 end t)
4269 (match-beginning 0)
4270 end))
4271 (unless (and todo-filter-done-items (eq filter 'regexp))
4272 ;; Leave done items.
4273 (delete-region done end)
4274 (setq end done))
4275 (narrow-to-region beg end) ; Process only current category.
4276 (goto-char (point-min))
4277 ;; Apply the filter.
4278 (cond ((eq filter 'diary)
4279 (while (not (eobp))
4280 (if (looking-at (regexp-quote todo-nondiary-start))
4281 (todo-remove-item)
4282 (todo-forward-item))))
4283 ((eq filter 'regexp)
4284 (while (not (eobp))
4285 (if (looking-at todo-item-start)
4286 (if (string-match regexp (todo-item-string))
4287 (todo-forward-item)
4288 (todo-remove-item))
4289 ;; Kill lines that aren't part of a todo or done
4290 ;; item (empty or todo-category-done).
4291 (delete-region (line-beginning-position)
4292 (1+ (line-end-position))))
4293 ;; If last todo item in file matches regexp and
4294 ;; there are no following done items,
4295 ;; todo-category-done string is left dangling,
4296 ;; because todo-forward-item jumps over it.
4297 (if (and (eobp)
4298 (looking-back
4299 (concat (regexp-quote todo-done-string)
4300 "\n")))
4301 (delete-region (point) (progn
4302 (forward-line -2)
4303 (point))))))
4304 (t ; Filter top priority items.
4305 (setq num (or cnum fnum num))
4306 (unless (zerop num)
4307 (todo-forward-item num))))
4308 (setq beg (point))
4309 ;; Delete non-top-priority items.
4310 (unless (member filter '(diary regexp))
4311 (delete-region beg end))
4312 (goto-char (point-min))
4313 ;; Add file (if using multiple files) and category tags to
4314 ;; item.
4315 (while (not (eobp))
4316 (when (re-search-forward
4317 (concat (if todo-filter-done-items
4318 (concat "\\(?:" todo-done-string-start
4319 "\\|" todo-date-string-start
4320 "\\)")
4321 todo-date-string-start)
4322 todo-date-pattern "\\(?: " diary-time-regexp
4323 "\\)?" (if todo-filter-done-items
4324 "\\]"
4325 (regexp-quote todo-nondiary-end))
4326 "?")
4327 nil t)
4328 (insert " [")
4329 (when (looking-at "(archive) ") (goto-char (match-end 0)))
4330 (insert (if multifile (concat fname ":") "") cat "]"))
4331 (forward-line))
4332 (widen)))
4333 (setq bufstr (buffer-string))
4334 (with-current-buffer buf
4335 (let (buffer-read-only)
4336 (insert bufstr)))))))
4337 (set-window-buffer (selected-window) (set-buffer buf))
4338 (todo-prefix-overlays)
4339 (goto-char (point-min)))))
4340
4341 (defun todo-set-top-priorities (&optional arg)
4342 "Set number of top priorities shown by `todo-filter-top-priorities'.
4343 With non-nil ARG, set the number only for the current Todo
4344 category; otherwise, set the number for all categories in the
4345 current todo file.
4346
4347 Calling this function via either of the commands
4348 `todo-set-top-priorities-in-file' or
4349 `todo-set-top-priorities-in-category' is the recommended way to
4350 set the user customizable option `todo-top-priorities-overrides'."
4351 (let* ((cat (todo-current-category))
4352 (file todo-current-todo-file)
4353 (rules todo-top-priorities-overrides)
4354 (frule (assoc-string file rules))
4355 (crule (assoc-string cat (nth 2 frule)))
4356 (crules (nth 2 frule))
4357 (cur (or (if arg (cdr crule) (nth 1 frule))
4358 todo-top-priorities))
4359 (prompt (if arg (concat "Number of top priorities in this category"
4360 " (currently %d): ")
4361 (concat "Default number of top priorities per category"
4362 " in this file (currently %d): ")))
4363 (new -1)
4364 nrule)
4365 (while (< new 0)
4366 (let ((cur0 cur))
4367 (setq new (read-number (format prompt cur0))
4368 prompt "Enter a non-negative number: "
4369 cur0 nil)))
4370 (setq nrule (if arg
4371 (append (delete crule crules) (list (cons cat new)))
4372 (append (list file new) (list crules))))
4373 (setq rules (cons (if arg
4374 (list file cur nrule)
4375 nrule)
4376 (delete frule rules)))
4377 (customize-save-variable 'todo-top-priorities-overrides rules)
4378 (todo-prefix-overlays)))
4379
4380 (defun todo-find-item (str)
4381 "Search for filtered item STR in its saved todo file.
4382 Return the list (FOUND FILE CAT), where CAT and FILE are the
4383 item's category and file, and FOUND is a cons cell if the search
4384 succeeds, whose car is the start of the item in FILE and whose
4385 cdr is `done', if the item is now a done item, `changed', if its
4386 text was truncated or augmented or, for a top priority item, if
4387 its priority has changed, and `same' otherwise."
4388 (string-match (concat (if todo-filter-done-items
4389 (concat "\\(?:" todo-done-string-start "\\|"
4390 todo-date-string-start "\\)")
4391 todo-date-string-start)
4392 todo-date-pattern "\\(?: " diary-time-regexp "\\)?"
4393 (if todo-filter-done-items
4394 "\\]"
4395 (regexp-quote todo-nondiary-end)) "?"
4396 "\\(?4: \\[\\(?3:(archive) \\)?\\(?2:.*:\\)?"
4397 "\\(?1:.*\\)\\]\\).*$") str)
4398 (let ((cat (match-string 1 str))
4399 (file (match-string 2 str))
4400 (archive (string= (match-string 3 str) "(archive) "))
4401 (filcat (match-string 4 str))
4402 (tpriority 1)
4403 (tpbuf (save-match-data (string-match "top" (buffer-name))))
4404 found)
4405 (setq str (replace-match "" nil nil str 4))
4406 (when tpbuf
4407 ;; Calculate priority of STR wrt its category.
4408 (save-excursion
4409 (while (search-backward filcat nil t)
4410 (setq tpriority (1+ tpriority)))))
4411 (setq file (if file
4412 (concat todo-directory (substring file 0 -1)
4413 (if archive ".toda" ".todo"))
4414 (if archive
4415 (concat (file-name-sans-extension
4416 todo-global-current-todo-file) ".toda")
4417 todo-global-current-todo-file)))
4418 (find-file-noselect file)
4419 (with-current-buffer (find-buffer-visiting file)
4420 (save-restriction
4421 (widen)
4422 (goto-char (point-min))
4423 (let ((beg (re-search-forward
4424 (concat "^" (regexp-quote (concat todo-category-beg cat))
4425 "$")
4426 nil t))
4427 (done (save-excursion
4428 (re-search-forward
4429 (concat "^" (regexp-quote todo-category-done)) nil t)))
4430 (end (save-excursion
4431 (or (re-search-forward
4432 (concat "^" (regexp-quote todo-category-beg))
4433 nil t)
4434 (point-max)))))
4435 (setq found (when (search-forward str end t)
4436 (goto-char (match-beginning 0))))
4437 (when found
4438 (setq found
4439 (cons found (if (> (point) done)
4440 'done
4441 (let ((cpriority 1))
4442 (when tpbuf
4443 (save-excursion
4444 ;; Not top item in category.
4445 (while (> (point) (1+ beg))
4446 (let ((opoint (point)))
4447 (todo-backward-item)
4448 ;; Can't move backward beyond
4449 ;; first item in file.
4450 (unless (= (point) opoint)
4451 (setq cpriority (1+ cpriority)))))))
4452 (if (and (= tpriority cpriority)
4453 ;; Proper substring is not the same.
4454 (string= (todo-item-string)
4455 str))
4456 'same
4457 'changed)))))))))
4458 (list found file cat)))
4459
4460 (defun todo-check-filtered-items-file ()
4461 "Check if filtered items file is up to date and a show suitable message."
4462 ;; (catch 'old
4463 (let ((count 0))
4464 (while (not (eobp))
4465 (let* ((item (todo-item-string))
4466 (found (car (todo-find-item item))))
4467 (unless (eq (cdr found) 'same)
4468 (save-excursion
4469 (overlay-put (make-overlay (todo-item-start) (todo-item-end))
4470 'face 'todo-search))
4471 (setq count (1+ count))))
4472 ;; (throw 'old (message "The marked item is not up to date.")))
4473 (todo-forward-item))
4474 (if (zerop count)
4475 (message "Filtered items file is up to date.")
4476 (message (concat "The highlighted item" (if (= count 1) " is " "s are ")
4477 "not up to date."
4478 ;; "\nType <return> on item for details."
4479 )))))
4480
4481 (defun todo-filter-items-filename ()
4482 "Return absolute file name for saving this Filtered Items buffer."
4483 (let ((bufname (buffer-name)))
4484 (string-match "\"\\([^\"]+\\)\"" bufname)
4485 (let* ((filename-str (substring bufname (match-beginning 1) (match-end 1)))
4486 (filename-base (replace-regexp-in-string ", " "-" filename-str))
4487 (top-priorities (string-match "top priorities" bufname))
4488 (diary-items (string-match "diary items" bufname))
4489 (regexp-items (string-match "regexp items" bufname)))
4490 (when regexp-items
4491 (let ((prompt (concat "Enter a short identifying string"
4492 " to make this file name unique: ")))
4493 (setq filename-base (concat filename-base "-" (read-string prompt)))))
4494 (concat todo-directory filename-base
4495 (cond (top-priorities ".todt")
4496 (diary-items ".tody")
4497 (regexp-items ".todr"))))))
4498
4499 (defun todo-save-filtered-items-buffer ()
4500 "Save current Filtered Items buffer to a file.
4501 If the file already exists, overwrite it only on confirmation."
4502 (let ((filename (or (buffer-file-name) (todo-filter-items-filename))))
4503 (write-file filename t)))
4504
4505 ;; -----------------------------------------------------------------------------
4506 ;;; Printing Todo mode buffers
4507 ;; -----------------------------------------------------------------------------
4508
4509 (defcustom todo-print-buffer-function 'ps-print-buffer-with-faces
4510 "Function called by the command `todo-print-buffer'."
4511 :type 'symbol
4512 :group 'todo)
4513
4514 (defvar todo-print-buffer "*Todo Print*"
4515 "Name of buffer with printable version of Todo mode buffer.")
4516
4517 (defun todo-print-buffer (&optional to-file)
4518 "Produce a printable version of the current Todo mode buffer.
4519 This converts overlays and soft line wrapping and, depending on
4520 the value of `todo-print-buffer-function', includes faces. With
4521 non-nil argument TO-FILE write the printable version to a file;
4522 otherwise, send it to the default printer."
4523 (interactive)
4524 (let ((buf todo-print-buffer)
4525 (header (cond
4526 ((eq major-mode 'todo-mode)
4527 (concat "Todo File: "
4528 (todo-short-file-name todo-current-todo-file)
4529 "\nCategory: " (todo-current-category)))
4530 ((eq major-mode 'todo-filtered-items-mode)
4531 (buffer-name))))
4532 (prefix (propertize (concat todo-prefix " ")
4533 'face 'todo-prefix-string))
4534 (num 0)
4535 (fill-prefix (make-string todo-indent-to-here 32))
4536 (content (buffer-string))
4537 file)
4538 (with-current-buffer (get-buffer-create buf)
4539 (insert content)
4540 (goto-char (point-min))
4541 (while (not (eobp))
4542 (let ((beg (point))
4543 (end (save-excursion (todo-item-end))))
4544 (when todo-number-prefix
4545 (setq num (1+ num))
4546 (setq prefix (propertize (concat (number-to-string num) " ")
4547 'face 'todo-prefix-string)))
4548 (insert prefix)
4549 (fill-region beg end))
4550 ;; Calling todo-forward-item infloops at todo-item-start due to
4551 ;; non-overlay prefix, so search for item start instead.
4552 (if (re-search-forward todo-item-start nil t)
4553 (beginning-of-line)
4554 (goto-char (point-max))))
4555 (if (re-search-backward (concat "^" (regexp-quote todo-category-done))
4556 nil t)
4557 (replace-match todo-done-separator))
4558 (goto-char (point-min))
4559 (insert header)
4560 (newline 2)
4561 (if to-file
4562 (let ((file (read-file-name "Print to file: ")))
4563 (funcall todo-print-buffer-function file))
4564 (funcall todo-print-buffer-function)))
4565 (kill-buffer buf)))
4566
4567 (defun todo-print-buffer-to-file ()
4568 "Save printable version of this Todo mode buffer to a file."
4569 (interactive)
4570 (todo-print-buffer t))
4571
4572 ;; -----------------------------------------------------------------------------
4573 ;;; Legacy Todo mode files
4574 ;; -----------------------------------------------------------------------------
4575
4576 (defcustom todo-legacy-date-time-regexp
4577 (concat "\\(?1:[0-9]\\{4\\}\\)-\\(?2:[0-9]\\{2\\}\\)-"
4578 "\\(?3:[0-9]\\{2\\}\\) \\(?4:[0-9]\\{2\\}:[0-9]\\{2\\}\\)")
4579 "Regexp matching legacy todo-mode.el item date-time strings.
4580 In order for `todo-convert-legacy-files' to correctly convert
4581 this string to the current Todo mode format, the regexp must
4582 contain four explicitly numbered groups (see `(elisp) Regexp
4583 Backslash'), where group 1 matches a string for the year, group 2
4584 a string for the month, group 3 a string for the day and group 4
4585 a string for the time. The default value converts date-time
4586 strings built using the default value of
4587 `todo-time-string-format' from todo-mode.el."
4588 :type 'regexp
4589 :group 'todo)
4590
4591 (defun todo-convert-legacy-date-time ()
4592 "Return converted date-time string.
4593 Helper function for `todo-convert-legacy-files'."
4594 (let* ((year (match-string 1))
4595 (month (match-string 2))
4596 (monthname (calendar-month-name (string-to-number month) t))
4597 (day (match-string 3))
4598 (time (match-string 4))
4599 dayname)
4600 (replace-match "")
4601 (insert (mapconcat 'eval calendar-date-display-form "")
4602 (when time (concat " " time)))))
4603
4604 (defun todo-convert-legacy-files ()
4605 "Convert legacy todo files to the current Todo mode format.
4606 The old-style files named by the variables `todo-file-do' and
4607 `todo-file-done' from the old package are converted to the new
4608 format and saved (the latter as a todo archive file) with a new
4609 name in `todo-directory'. See also the documentation string of
4610 `todo-legacy-date-time-regexp' for further details."
4611 (interactive)
4612 ;; If there are user customizations of legacy options, use them,
4613 ;; otherwise use the legacy default values.
4614 (let ((todo-file-do-tem (if (boundp 'todo-file-do)
4615 todo-file-do
4616 (locate-user-emacs-file "todo-do" ".todo-do")))
4617 (todo-file-done-tem (if (boundp 'todo-file-done)
4618 todo-file-done
4619 (locate-user-emacs-file "todo-done" ".todo-done")))
4620 (todo-initials-tem (and (boundp 'todo-initials) todo-initials))
4621 (todo-entry-prefix-function-tem (and (boundp 'todo-entry-prefix-function)
4622 todo-entry-prefix-function))
4623 todo-prefix-tem)
4624 ;; Convert `todo-file-do'.
4625 (if (not (file-exists-p todo-file-do-tem))
4626 (message "No legacy todo file exists")
4627 (let ((default "todo-do-conv")
4628 file archive-sexp)
4629 (with-temp-buffer
4630 (insert-file-contents todo-file-do-tem)
4631 ;; Eliminate old-style local variables list in first line.
4632 (delete-region (line-beginning-position) (1+ (line-end-position)))
4633 (search-forward " --- " nil t) ; Legacy todo-category-beg.
4634 (setq todo-prefix-tem (buffer-substring-no-properties
4635 (line-beginning-position) (match-beginning 0)))
4636 (goto-char (point-min))
4637 (while (not (eobp))
4638 (cond
4639 ;; Old-style category start delimiter.
4640 ((looking-at (regexp-quote (concat todo-prefix-tem " --- ")))
4641 (replace-match todo-category-beg))
4642 ;; Old-style category end delimiter.
4643 ((looking-at (regexp-quote "--- End"))
4644 (replace-match ""))
4645 ;; Old-style category separator.
4646 ((looking-at (regexp-quote
4647 (concat todo-prefix-tem " "
4648 (make-string 75 ?-))))
4649 (replace-match todo-category-done))
4650 ;; Old-style item header (date/time/initials).
4651 ((looking-at (concat (regexp-quote todo-prefix-tem) " "
4652 (if todo-entry-prefix-function-tem
4653 (funcall todo-entry-prefix-function-tem)
4654 (concat todo-legacy-date-time-regexp " "
4655 (if todo-initials-tem
4656 (regexp-quote todo-initials-tem)
4657 "[^:]*")
4658 ":"))))
4659 (todo-convert-legacy-date-time)))
4660 (forward-line))
4661 (setq file (concat todo-directory
4662 (read-string
4663 (format "Save file as (default \"%s\"): " default)
4664 nil nil default)
4665 ".todo"))
4666 (unless (file-exists-p todo-directory)
4667 (make-directory todo-directory))
4668 (write-region (point-min) (point-max) file nil 'nomessage nil t))
4669 (with-temp-buffer
4670 (insert-file-contents file)
4671 (let ((todo-categories (todo-make-categories-list t)))
4672 (todo-update-categories-sexp)
4673 (todo-check-format))
4674 (write-region (point-min) (point-max) file nil 'nomessage))
4675 (setq todo-files (funcall todo-files-function))
4676 ;; Convert `todo-file-done'.
4677 (when (file-exists-p todo-file-done-tem)
4678 (with-temp-buffer
4679 (insert-file-contents todo-file-done-tem)
4680 (let ((beg (make-marker))
4681 (end (make-marker))
4682 cat cats comment item)
4683 (while (not (eobp))
4684 (when (looking-at todo-legacy-date-time-regexp)
4685 (set-marker beg (point))
4686 (todo-convert-legacy-date-time)
4687 (set-marker end (point))
4688 (goto-char beg)
4689 (insert "[" todo-done-string)
4690 (goto-char end)
4691 (insert "]")
4692 (forward-char)
4693 (when (looking-at todo-legacy-date-time-regexp)
4694 (todo-convert-legacy-date-time))
4695 (when (looking-at (concat " " (if todo-initials-tem
4696 (regexp-quote
4697 todo-initials-tem)
4698 "[^:]*")
4699 ":"))
4700 (replace-match "")))
4701 (if (re-search-forward
4702 (concat "^" todo-legacy-date-time-regexp) nil t)
4703 (goto-char (match-beginning 0))
4704 (goto-char (point-max)))
4705 (backward-char)
4706 (when (looking-back "\\[\\([^][]+\\)\\]")
4707 (setq cat (match-string 1))
4708 (goto-char (match-beginning 0))
4709 (replace-match ""))
4710 ;; If the item ends with a non-comment parenthesis not
4711 ;; followed by a period, we lose (but we inherit that
4712 ;; problem from the legacy code).
4713 (when (looking-back "(\\(.*\\)) ")
4714 (setq comment (match-string 1))
4715 (replace-match "")
4716 (insert "[" todo-comment-string ": " comment "]"))
4717 (set-marker end (point))
4718 (if (member cat cats)
4719 ;; If item is already in its category, leave it there.
4720 (unless (save-excursion
4721 (re-search-backward
4722 (concat "^" (regexp-quote todo-category-beg)
4723 "\\(.*\\)$") nil t)
4724 (string= (match-string 1) cat))
4725 ;; Else move it to its category.
4726 (setq item (buffer-substring-no-properties beg end))
4727 (delete-region beg (1+ end))
4728 (set-marker beg (point))
4729 (re-search-backward
4730 (concat "^"
4731 (regexp-quote (concat todo-category-beg cat))
4732 "$")
4733 nil t)
4734 (forward-line)
4735 (if (re-search-forward
4736 (concat "^" (regexp-quote todo-category-beg)
4737 "\\(.*\\)$") nil t)
4738 (progn (goto-char (match-beginning 0))
4739 (newline)
4740 (forward-line -1))
4741 (goto-char (point-max)))
4742 (insert item "\n")
4743 (goto-char beg))
4744 (push cat cats)
4745 (goto-char beg)
4746 (insert todo-category-beg cat "\n\n"
4747 todo-category-done "\n"))
4748 (forward-line))
4749 (set-marker beg nil)
4750 (set-marker end nil))
4751 (setq file (concat (file-name-sans-extension file) ".toda"))
4752 (write-region (point-min) (point-max) file nil 'nomessage nil t))
4753 (with-temp-buffer
4754 (insert-file-contents file)
4755 (let* ((todo-categories (todo-make-categories-list t)))
4756 (todo-update-categories-sexp)
4757 (todo-check-format))
4758 (write-region (point-min) (point-max) file nil 'nomessage)
4759 (setq archive-sexp (read (buffer-substring-no-properties
4760 (line-beginning-position)
4761 (line-end-position)))))
4762 (setq file (concat (file-name-sans-extension file) ".todo"))
4763 ;; Update categories sexp of converted todo file again, adding
4764 ;; counts of archived items.
4765 (with-temp-buffer
4766 (insert-file-contents file)
4767 (let ((sexp (read (buffer-substring-no-properties
4768 (line-beginning-position)
4769 (line-end-position)))))
4770 (dolist (cat sexp)
4771 (let ((archive-cat (assoc (car cat) archive-sexp)))
4772 (if archive-cat
4773 (aset (cdr cat) 3 (aref (cdr archive-cat) 2)))))
4774 (delete-region (line-beginning-position) (line-end-position))
4775 (prin1 sexp (current-buffer)))
4776 (write-region (point-min) (point-max) file nil 'nomessage))
4777 (setq todo-archives (funcall todo-files-function t)))
4778 (todo-reevaluate-filelist-defcustoms)
4779 (when (y-or-n-p (concat "Format conversion done; do you want to "
4780 "visit the converted file now? "))
4781 (setq todo-current-todo-file file)
4782 (unless todo-default-todo-file
4783 ;; We just initialized the first todo file, so make it the
4784 ;; default now to avoid an infinite recursion with todo-show.
4785 (setq todo-default-todo-file (todo-short-file-name file)))
4786 (todo-show))))))
4787
4788 ;; -----------------------------------------------------------------------------
4789 ;;; Utility functions for todo files, categories and items
4790 ;; -----------------------------------------------------------------------------
4791
4792 (defun todo-absolute-file-name (name &optional type)
4793 "Return the absolute file name of short todo file NAME.
4794 With TYPE `archive' or `top' return the absolute file name of the
4795 short todo archive or top priorities file name, respectively."
4796 ;; No-op if there is no todo file yet (i.e. don't concatenate nil).
4797 (when name
4798 (file-truename
4799 (concat todo-directory name
4800 (cond ((eq type 'archive) ".toda")
4801 ((eq type 'top) ".todt")
4802 ((eq type 'diary) ".tody")
4803 ((eq type 'regexp) ".todr")
4804 (t ".todo"))))))
4805
4806 (defun todo-check-file (file)
4807 "Check the state associated with FILE and update it if necessary.
4808 If FILE exists, return t. If it does not exist and there is no
4809 live buffer with its content, return nil; if there is such a
4810 buffer and the user tries to show it, ask whether to restore
4811 FILE, and if confirmed, do so and return t; else delete the
4812 buffer, clean up the state and return nil."
4813 (setq todo-files (funcall todo-files-function))
4814 (setq todo-archives (funcall todo-files-function t))
4815 (if (file-exists-p file)
4816 t
4817 (setq todo-visited (delete file todo-visited))
4818 (let ((buf (find-buffer-visiting file)))
4819 (if (and buf
4820 (y-or-n-p
4821 (concat
4822 (format (concat "Todo file \"%s\" has been deleted but "
4823 "its content is still in a buffer!\n")
4824 (todo-short-file-name file))
4825 "Save that buffer and restore the todo file? ")))
4826 (progn
4827 (with-current-buffer buf (save-buffer))
4828 (setq todo-files (funcall todo-files-function))
4829 (setq todo-archives (funcall todo-files-function t))
4830 t)
4831 (let* ((files (append todo-files todo-archives))
4832 (tctf todo-current-todo-file)
4833 (tgctf todo-global-current-todo-file)
4834 (tdtf (todo-absolute-file-name todo-default-todo-file)))
4835 (unless (or (not todo-current-todo-file)
4836 (member todo-current-todo-file files))
4837 (setq todo-current-todo-file nil))
4838 (unless (or (not todo-global-current-todo-file)
4839 (member todo-global-current-todo-file files))
4840 (setq todo-global-current-todo-file nil))
4841 (unless (or (not todo-default-todo-file)
4842 (member todo-default-todo-file files))
4843 (setq todo-default-todo-file (todo-short-file-name
4844 (car todo-files))))
4845 (todo-reevaluate-filelist-defcustoms)
4846 (when buf (kill-buffer buf))
4847 nil)))))
4848
4849 (defun todo-category-number (cat)
4850 "Return the number of category CAT in this todo file.
4851 The buffer-local variable `todo-category-number' holds this
4852 number as its value."
4853 (let ((categories (mapcar 'car todo-categories)))
4854 (setq todo-category-number
4855 ;; Increment by one, so that the number of the first
4856 ;; category is one rather than zero.
4857 (1+ (- (length categories)
4858 (length (member cat categories)))))))
4859
4860 (defun todo-current-category ()
4861 "Return the name of the current category."
4862 (car (nth (1- todo-category-number) todo-categories)))
4863
4864 (defun todo-category-select ()
4865 "Display the current category correctly."
4866 (let ((name (todo-current-category))
4867 cat-begin cat-end done-start done-sep-start done-end)
4868 (widen)
4869 (goto-char (point-min))
4870 (re-search-forward
4871 (concat "^" (regexp-quote (concat todo-category-beg name)) "$") nil t)
4872 (setq cat-begin (1+ (line-end-position)))
4873 (setq cat-end (if (re-search-forward
4874 (concat "^" (regexp-quote todo-category-beg)) nil t)
4875 (match-beginning 0)
4876 (point-max)))
4877 (setq mode-line-buffer-identification
4878 (funcall todo-mode-line-function name))
4879 (narrow-to-region cat-begin cat-end)
4880 (todo-prefix-overlays)
4881 (goto-char (point-min))
4882 (if (re-search-forward (concat "\n\\(" (regexp-quote todo-category-done)
4883 "\\)") nil t)
4884 (progn
4885 (setq done-start (match-beginning 0))
4886 (setq done-sep-start (match-beginning 1))
4887 (setq done-end (match-end 0)))
4888 (error "Category %s is missing todo-category-done string" name))
4889 (if todo-show-done-only
4890 (narrow-to-region (1+ done-end) (point-max))
4891 (when (and todo-show-with-done
4892 (re-search-forward todo-done-string-start nil t))
4893 ;; Now we want to see the done items, so reset displayed end to end of
4894 ;; done items.
4895 (setq done-start cat-end)
4896 ;; Make display overlay for done items separator string, unless there
4897 ;; already is one.
4898 (let* ((done-sep todo-done-separator)
4899 (ov (progn (goto-char done-sep-start)
4900 (todo-get-overlay 'separator))))
4901 (unless ov
4902 (setq ov (make-overlay done-sep-start done-end))
4903 (overlay-put ov 'todo 'separator)
4904 (overlay-put ov 'display done-sep))))
4905 (narrow-to-region (point-min) done-start)
4906 ;; Loading this from todo-mode, or adding it to the mode hook, causes
4907 ;; Emacs to hang in todo-item-start, at (looking-at todo-item-start).
4908 (when todo-highlight-item
4909 (require 'hl-line)
4910 (hl-line-mode 1)))))
4911
4912 (defun todo-get-count (type &optional category)
4913 "Return count of TYPE items in CATEGORY.
4914 If CATEGORY is nil, default to the current category."
4915 (let* ((cat (or category (todo-current-category)))
4916 (counts (cdr (assoc cat todo-categories)))
4917 (idx (cond ((eq type 'todo) 0)
4918 ((eq type 'diary) 1)
4919 ((eq type 'done) 2)
4920 ((eq type 'archived) 3))))
4921 (aref counts idx)))
4922
4923 (defun todo-update-count (type increment &optional category)
4924 "Change count of TYPE items in CATEGORY by integer INCREMENT.
4925 With nil or omitted CATEGORY, default to the current category."
4926 (let* ((cat (or category (todo-current-category)))
4927 (counts (cdr (assoc cat todo-categories)))
4928 (idx (cond ((eq type 'todo) 0)
4929 ((eq type 'diary) 1)
4930 ((eq type 'done) 2)
4931 ((eq type 'archived) 3))))
4932 (aset counts idx (+ increment (aref counts idx)))))
4933
4934 (defun todo-set-categories ()
4935 "Set `todo-categories' from the sexp at the top of the file."
4936 ;; New archive files created by `todo-move-category' are empty, which would
4937 ;; make the sexp test fail and raise an error, so in this case we skip it.
4938 (unless (zerop (buffer-size))
4939 (save-excursion
4940 (save-restriction
4941 (widen)
4942 (goto-char (point-min))
4943 (setq todo-categories
4944 (if (looking-at "\(\(\"")
4945 (read (buffer-substring-no-properties
4946 (line-beginning-position)
4947 (line-end-position)))
4948 (error "Invalid or missing todo-categories sexp")))))))
4949
4950 (defun todo-update-categories-sexp ()
4951 "Update the `todo-categories' sexp at the top of the file."
4952 (let (buffer-read-only)
4953 (save-excursion
4954 (save-restriction
4955 (widen)
4956 (goto-char (point-min))
4957 (if (looking-at (concat "^" (regexp-quote todo-category-beg)))
4958 (progn (newline) (goto-char (point-min)) ; Make space for sexp.
4959 (setq todo-categories (todo-make-categories-list t)))
4960 (delete-region (line-beginning-position) (line-end-position)))
4961 (prin1 todo-categories (current-buffer))))))
4962
4963 (defun todo-make-categories-list (&optional force)
4964 "Return an alist of todo categories and their item counts.
4965 With non-nil argument FORCE parse the entire file to build the
4966 list; otherwise, get the value by reading the sexp at the top of
4967 the file."
4968 (setq todo-categories nil)
4969 (save-excursion
4970 (save-restriction
4971 (widen)
4972 (goto-char (point-min))
4973 (let (counts cat archive)
4974 ;; If the file is a todo file and has archived items, identify the
4975 ;; archive, in order to count its items. But skip this with
4976 ;; `todo-convert-legacy-files', since that converts filed items to
4977 ;; archived items.
4978 (when buffer-file-name ; During conversion there is no file yet.
4979 ;; If the file is an archive, it doesn't have an archive.
4980 (unless (member (file-truename buffer-file-name)
4981 (funcall todo-files-function t))
4982 (setq archive (concat (file-name-sans-extension
4983 todo-current-todo-file) ".toda"))))
4984 (while (not (eobp))
4985 (cond ((looking-at (concat (regexp-quote todo-category-beg)
4986 "\\(.*\\)\n"))
4987 (setq cat (match-string-no-properties 1))
4988 ;; Counts for each category: [todo diary done archive]
4989 (setq counts (make-vector 4 0))
4990 (setq todo-categories
4991 (append todo-categories (list (cons cat counts))))
4992 ;; Add archived item count to the todo file item counts.
4993 ;; Make sure to include newly created archives, e.g. due to
4994 ;; todo-move-category.
4995 (when (member archive (funcall todo-files-function t))
4996 (let ((archive-count 0))
4997 (with-current-buffer (find-file-noselect archive)
4998 (widen)
4999 (goto-char (point-min))
5000 (when (re-search-forward
5001 (concat "^" (regexp-quote todo-category-beg)
5002 cat "$")
5003 (point-max) t)
5004 (forward-line)
5005 (while (not (or (looking-at
5006 (concat
5007 (regexp-quote todo-category-beg)
5008 "\\(.*\\)\n"))
5009 (eobp)))
5010 (when (looking-at todo-done-string-start)
5011 (setq archive-count (1+ archive-count)))
5012 (forward-line))))
5013 (todo-update-count 'archived archive-count cat))))
5014 ((looking-at todo-done-string-start)
5015 (todo-update-count 'done 1 cat))
5016 ((looking-at (concat "^\\("
5017 (regexp-quote diary-nonmarking-symbol)
5018 "\\)?" todo-date-pattern))
5019 (todo-update-count 'diary 1 cat)
5020 (todo-update-count 'todo 1 cat))
5021 ((looking-at (concat todo-date-string-start todo-date-pattern))
5022 (todo-update-count 'todo 1 cat))
5023 ;; If first line is todo-categories list, use it and end loop
5024 ;; -- unless FORCEd to scan whole file.
5025 ((bobp)
5026 (unless force
5027 (setq todo-categories (read (buffer-substring-no-properties
5028 (line-beginning-position)
5029 (line-end-position))))
5030 (goto-char (1- (point-max))))))
5031 (forward-line)))))
5032 todo-categories)
5033
5034 (defun todo-repair-categories-sexp ()
5035 "Repair corrupt todo file categories sexp.
5036 This should only be needed as a consequence of careless manual
5037 editing or a bug in todo.el.
5038
5039 *Warning*: Calling this command restores the category order to
5040 the list element order in the todo file categories sexp, so any
5041 order changes made in Todo Categories mode will have to be made
5042 again."
5043 (interactive)
5044 (let ((todo-categories (todo-make-categories-list t)))
5045 (todo-update-categories-sexp)))
5046
5047 (defun todo-check-format ()
5048 "Signal an error if the current todo file is ill-formatted.
5049 Otherwise return t. Display a message if the file is well-formed
5050 but the categories sexp differs from the current value of
5051 `todo-categories'."
5052 (save-excursion
5053 (save-restriction
5054 (widen)
5055 (goto-char (point-min))
5056 (let* ((cats (prin1-to-string todo-categories))
5057 (ssexp (buffer-substring-no-properties (line-beginning-position)
5058 (line-end-position)))
5059 (sexp (read ssexp)))
5060 ;; Check the first line for `todo-categories' sexp.
5061 (dolist (c sexp)
5062 (let ((v (cdr c)))
5063 (unless (and (stringp (car c))
5064 (vectorp v)
5065 (= 4 (length v)))
5066 (user-error "Invalid or missing todo-categories sexp"))))
5067 (forward-line)
5068 ;; Check well-formedness of categories.
5069 (let ((legit (concat
5070 "\\(^" (regexp-quote todo-category-beg) "\\)"
5071 "\\|\\(" todo-date-string-start todo-date-pattern "\\)"
5072 "\\|\\(^[ \t]+[^ \t]*\\)"
5073 "\\|^$"
5074 "\\|\\(^" (regexp-quote todo-category-done) "\\)"
5075 "\\|\\(" todo-done-string-start "\\)")))
5076 (while (not (eobp))
5077 (unless (looking-at legit)
5078 (user-error "Illegitimate todo file format at line %d"
5079 (line-number-at-pos (point))))
5080 (forward-line)))
5081 ;; Warn user if categories sexp has changed.
5082 (unless (string= ssexp cats)
5083 (message (concat "The sexp at the beginning of the file differs "
5084 "from the value of `todo-categories.\n"
5085 "If the sexp is wrong, you can fix it with "
5086 "M-x todo-repair-categories-sexp,\n"
5087 "but note this reverts any changes you have "
5088 "made in the order of the categories."))))))
5089 t)
5090
5091 (defun todo-item-start ()
5092 "Move to start of current todo item and return its position."
5093 (unless (or
5094 ;; Buffer is empty (invocation possible e.g. via todo-forward-item
5095 ;; from todo-filter-items when processing category with no todo
5096 ;; items).
5097 (eq (point-min) (point-max))
5098 ;; Point is on the empty line below category's last todo item...
5099 (and (looking-at "^$")
5100 (or (eobp) ; ...and done items are hidden...
5101 (save-excursion ; ...or done items are visible.
5102 (forward-line)
5103 (looking-at (concat "^"
5104 (regexp-quote todo-category-done))))))
5105 ;; Buffer is widened.
5106 (looking-at (regexp-quote todo-category-beg)))
5107 (goto-char (line-beginning-position))
5108 (while (not (looking-at todo-item-start))
5109 (forward-line -1))
5110 (point)))
5111
5112 (defun todo-item-end ()
5113 "Move to end of current todo item and return its position."
5114 ;; Items cannot end with a blank line.
5115 (unless (looking-at "^$")
5116 (let* ((done (todo-done-item-p))
5117 (to-lim nil)
5118 ;; For todo items, end is before the done items section, for done
5119 ;; items, end is before the next category. If these limits are
5120 ;; missing or inaccessible, end it before the end of the buffer.
5121 (lim (if (save-excursion
5122 (re-search-forward
5123 (concat "^" (regexp-quote (if done
5124 todo-category-beg
5125 todo-category-done)))
5126 nil t))
5127 (progn (setq to-lim t) (match-beginning 0))
5128 (point-max))))
5129 (when (bolp) (forward-char)) ; Find start of next item.
5130 (goto-char (if (re-search-forward todo-item-start lim t)
5131 (match-beginning 0)
5132 (if to-lim lim (point-max))))
5133 ;; For last todo item, skip back over the empty line before the done
5134 ;; items section, else just back to the end of the previous line.
5135 (backward-char (when (and to-lim (not done) (eq (point) lim)) 2))
5136 (point))))
5137
5138 (defun todo-item-string ()
5139 "Return bare text of current item as a string."
5140 (let ((opoint (point))
5141 (start (todo-item-start))
5142 (end (todo-item-end)))
5143 (goto-char opoint)
5144 (and start end (buffer-substring-no-properties start end))))
5145
5146 (defun todo-forward-item (&optional count)
5147 "Move point COUNT items down (by default, move down by one item)."
5148 (let* ((not-done (not (or (todo-done-item-p) (looking-at "^$"))))
5149 (start (line-end-position)))
5150 (goto-char start)
5151 (if (re-search-forward todo-item-start nil t (or count 1))
5152 (goto-char (match-beginning 0))
5153 (goto-char (point-max)))
5154 ;; If points advances by one from a todo to a done item, go back
5155 ;; to the space above todo-done-separator, since that is a
5156 ;; legitimate place to insert an item. But skip this space if
5157 ;; count > 1, since that should only stop on an item.
5158 (when (and not-done (todo-done-item-p) (not count))
5159 ;; (if (or (not count) (= count 1))
5160 (re-search-backward "^$" start t))));)
5161 ;; The preceding sexp is insufficient when buffer is not narrowed,
5162 ;; since there could be no done items in this category, so the
5163 ;; search puts us on first todo item of next category. Does this
5164 ;; ever happen? If so:
5165 ;; (let ((opoint) (point))
5166 ;; (forward-line -1)
5167 ;; (when (or (not count) (= count 1))
5168 ;; (cond ((looking-at (concat "^" (regexp-quote todo-category-beg)))
5169 ;; (forward-line -2))
5170 ;; ((looking-at (concat "^" (regexp-quote todo-category-done)))
5171 ;; (forward-line -1))
5172 ;; (t
5173 ;; (goto-char opoint)))))))
5174
5175 (defun todo-backward-item (&optional count)
5176 "Move point up to start of item with next higher priority.
5177 With positive numerical prefix COUNT, move point COUNT items
5178 upward.
5179
5180 If the category's done items are visible, this command called
5181 with a prefix argument only moves point to a higher item, e.g.,
5182 with point on the first done item and called with prefix 1, it
5183 moves to the last todo item; but if called with point on the
5184 first done item without a prefix argument, it moves point the the
5185 empty line above the done items separator."
5186 (let* ((done (todo-done-item-p)))
5187 (todo-item-start)
5188 (unless (bobp)
5189 (re-search-backward todo-item-start nil t (or count 1)))
5190 ;; Unless this is a regexp filtered items buffer (which can contain
5191 ;; intermixed todo and done items), if points advances by one from a
5192 ;; done to a todo item, go back to the space above
5193 ;; todo-done-separator, since that is a legitimate place to insert an
5194 ;; item. But skip this space if count > 1, since that should only
5195 ;; stop on an item.
5196 (when (and done (not (todo-done-item-p)) (not count)
5197 ;(or (not count) (= count 1))
5198 (not (equal (buffer-name) todo-regexp-items-buffer)))
5199 (re-search-forward (concat "^" (regexp-quote todo-category-done))
5200 nil t)
5201 (forward-line -1))))
5202
5203 (defun todo-remove-item ()
5204 "Internal function called in editing, deleting or moving items."
5205 (let* ((end (progn (todo-item-end) (1+ (point))))
5206 (beg (todo-item-start))
5207 (ov (todo-get-overlay 'prefix)))
5208 (when ov (delete-overlay ov))
5209 (delete-region beg end)))
5210
5211 (defun todo-diary-item-p ()
5212 "Return non-nil if item at point has diary entry format."
5213 (save-excursion
5214 (when (todo-item-string) ; Exclude empty lines.
5215 (todo-item-start)
5216 (not (looking-at (regexp-quote todo-nondiary-start))))))
5217
5218 ;; This duplicates the item locating code from diary-goto-entry, but
5219 ;; without the marker code, to test whether the latter is dispensable.
5220 ;; If it is, diary-goto-entry can be simplified. The code duplication
5221 ;; here can also be eliminated, leaving only the widening and category
5222 ;; selection, and instead of :override advice :around can be used.
5223
5224 (defun todo-diary-goto-entry (button)
5225 "Jump to the diary entry for the BUTTON at point.
5226 If the entry is a todo item, display its category properly.
5227 Overrides `diary-goto-entry'."
5228 ;; Locate the diary item in its source file.
5229 (let* ((locator (button-get button 'locator))
5230 (file (cadr locator))
5231 (date (regexp-quote (nth 2 locator)))
5232 (content (regexp-quote (nth 3 locator))))
5233 (if (not (and (file-exists-p file)
5234 (find-file-other-window file)))
5235 (message "Unable to locate this diary entry")
5236 (when (eq major-mode 'todo-mode) (widen))
5237 (goto-char (point-min))
5238 (when (re-search-forward (format "%s.*\\(%s\\)" date content) nil t)
5239 (goto-char (match-beginning 1)))
5240 ;; If it's a todo item, determine its category and display the
5241 ;; category properly.
5242 (when (eq major-mode 'todo-mode)
5243 (let ((opoint (point)))
5244 (re-search-backward (concat "^" (regexp-quote todo-category-beg)
5245 "\\(.*\\)\n") nil t)
5246 (todo-category-number (match-string 1))
5247 (todo-category-select)
5248 (goto-char opoint))))))
5249
5250 (add-function :override diary-goto-entry-function #'todo-diary-goto-entry)
5251
5252 (defun todo-done-item-p ()
5253 "Return non-nil if item at point is a done item."
5254 (save-excursion
5255 (todo-item-start)
5256 (looking-at todo-done-string-start)))
5257
5258 (defun todo-done-item-section-p ()
5259 "Return non-nil if point is in category's done items section."
5260 (save-excursion
5261 (or (re-search-backward (concat "^" (regexp-quote todo-category-done))
5262 nil t)
5263 (progn (goto-char (point-min))
5264 (looking-at todo-done-string-start)))))
5265
5266 (defun todo-reset-done-separator (sep)
5267 "Replace existing overlays of done items separator string SEP."
5268 (save-excursion
5269 (save-restriction
5270 (widen)
5271 (goto-char (point-min))
5272 (while (re-search-forward
5273 (concat "\n\\(" (regexp-quote todo-category-done) "\\)") nil t)
5274 (let* ((beg (match-beginning 1))
5275 (end (match-end 0))
5276 (ov (progn (goto-char beg)
5277 (todo-get-overlay 'separator)))
5278 (old-sep (when ov (overlay-get ov 'display)))
5279 new-ov)
5280 (when old-sep
5281 (unless (string= old-sep sep)
5282 (setq new-ov (make-overlay beg end))
5283 (overlay-put new-ov 'todo 'separator)
5284 (overlay-put new-ov 'display todo-done-separator)
5285 (delete-overlay ov))))))))
5286
5287 (defun todo-get-overlay (val)
5288 "Return the overlay at point whose `todo' property has value VAL."
5289 ;; Use overlays-in to find prefix overlays and check over two
5290 ;; positions to find done separator overlay.
5291 (let ((ovs (overlays-in (point) (1+ (point))))
5292 ov)
5293 (catch 'done
5294 (while ovs
5295 (setq ov (pop ovs))
5296 (when (eq (overlay-get ov 'todo) val)
5297 (throw 'done ov))))))
5298
5299 (defun todo-marked-item-p ()
5300 "Non-nil if this item begins with `todo-item-mark'.
5301 In that case, return the item's prefix overlay."
5302 (let* ((ov (todo-get-overlay 'prefix))
5303 ;; If an item insertion command is called on a todo file
5304 ;; before it is visited, it has no prefix overlays yet, so
5305 ;; check for this.
5306 (pref (when ov (overlay-get ov 'before-string)))
5307 (marked (when pref
5308 (string-match (concat "^" (regexp-quote todo-item-mark))
5309 pref))))
5310 (when marked ov)))
5311
5312 (defun todo-insert-with-overlays (item)
5313 "Insert ITEM at point and update prefix/priority number overlays."
5314 (todo-item-start)
5315 ;; Insertion pushes item down but not its prefix overlay. When the
5316 ;; overlay includes a mark, this would now mark the inserted ITEM,
5317 ;; so move it to the pushed down item.
5318 (let ((ov (todo-get-overlay 'prefix))
5319 (marked (todo-marked-item-p)))
5320 (insert item "\n")
5321 (when marked (move-overlay ov (point) (point))))
5322 (todo-backward-item)
5323 (todo-prefix-overlays))
5324
5325 (defun todo-prefix-overlays ()
5326 "Update the prefix overlays of the current category's items.
5327 The overlay's value is the string `todo-prefix' or with non-nil
5328 `todo-number-prefix' an integer in the sequence from 1 to
5329 the number of todo or done items in the category indicating the
5330 item's priority. Todo and done items are numbered independently
5331 of each other."
5332 (let ((num 0)
5333 (cat-tp (or (cdr (assoc-string
5334 (todo-current-category)
5335 (nth 2 (assoc-string todo-current-todo-file
5336 todo-top-priorities-overrides))))
5337 todo-top-priorities))
5338 done prefix)
5339 (save-excursion
5340 (goto-char (point-min))
5341 (while (not (eobp))
5342 (when (or (todo-date-string-matcher (line-end-position))
5343 (todo-done-string-matcher (line-end-position)))
5344 (goto-char (match-beginning 0))
5345 (setq num (1+ num))
5346 ;; Reset number to 1 for first done item.
5347 (when (and (eq major-mode 'todo-mode)
5348 (looking-at todo-done-string-start)
5349 (looking-back (concat "^"
5350 (regexp-quote todo-category-done)
5351 "\n")))
5352 (setq num 1
5353 done t))
5354 (setq prefix (concat (propertize
5355 (if todo-number-prefix
5356 (number-to-string num)
5357 todo-prefix)
5358 'face
5359 ;; Prefix of top priority items has a
5360 ;; distinct face in Todo mode.
5361 (if (and (eq major-mode 'todo-mode)
5362 (not done)
5363 (<= num cat-tp))
5364 'todo-top-priority
5365 'todo-prefix-string))
5366 " "))
5367 (let ((ov (todo-get-overlay 'prefix))
5368 (marked (todo-marked-item-p)))
5369 ;; Prefix overlay must be at a single position so its
5370 ;; bounds aren't changed when (re)moving an item.
5371 (unless ov (setq ov (make-overlay (point) (point))))
5372 (overlay-put ov 'todo 'prefix)
5373 (overlay-put ov 'before-string (if marked
5374 (concat todo-item-mark prefix)
5375 prefix))))
5376 (forward-line)))))
5377
5378 ;; -----------------------------------------------------------------------------
5379 ;;; Utilities for generating item insertion commands and key bindings
5380 ;; -----------------------------------------------------------------------------
5381
5382 ;; Wolfgang Jenkner posted this powerset definition to emacs-devel
5383 ;; (http://lists.gnu.org/archive/html/emacs-devel/2013-06/msg00423.html)
5384 ;; and kindly gave me permission to use it.
5385
5386 (defun todo-powerset (list)
5387 "Return the powerset of LIST."
5388 (let ((powerset (list nil)))
5389 (dolist (elt list (mapcar 'reverse powerset))
5390 (nconc powerset (mapcar (apply-partially 'cons elt) powerset)))))
5391
5392 (defun todo-gen-arglists (arglist)
5393 "Return list of lists of non-nil atoms produced from ARGLIST.
5394 The elements of ARGLIST may be atoms or lists."
5395 (let (arglists)
5396 (while arglist
5397 (let ((arg (pop arglist)))
5398 (cond ((symbolp arg)
5399 (setq arglists (if arglists
5400 (mapcar (lambda (l) (push arg l)) arglists)
5401 (list (push arg arglists)))))
5402 ((listp arg)
5403 (setq arglists
5404 (mapcar (lambda (a)
5405 (if (= 1 (length arglists))
5406 (apply (lambda (l) (push a l)) arglists)
5407 (mapcar (lambda (l) (push a l)) arglists)))
5408 arg))))))
5409 (setq arglists (mapcar 'reverse (apply 'append (mapc 'car arglists))))))
5410
5411 (defvar todo-insertion-commands-args-genlist
5412 '(diary nonmarking (calendar date dayname) time (here region))
5413 "Generator list for argument lists of item insertion commands.")
5414
5415 (defvar todo-insertion-commands-args
5416 (let ((arglist (todo-gen-arglists todo-insertion-commands-args-genlist))
5417 res new)
5418 (setq res (cl-remove-duplicates
5419 (apply 'append (mapcar 'todo-powerset arglist)) :test 'equal))
5420 (dolist (l res)
5421 (unless (= 5 (length l))
5422 (let ((v (make-vector 5 nil)) elt)
5423 (while l
5424 (setq elt (pop l))
5425 (cond ((eq elt 'diary)
5426 (aset v 0 elt))
5427 ((eq elt 'nonmarking)
5428 (aset v 1 elt))
5429 ((or (eq elt 'calendar)
5430 (eq elt 'date)
5431 (eq elt 'dayname))
5432 (aset v 2 elt))
5433 ((eq elt 'time)
5434 (aset v 3 elt))
5435 ((or (eq elt 'here)
5436 (eq elt 'region))
5437 (aset v 4 elt))))
5438 (setq l (append v nil))))
5439 (setq new (append new (list l))))
5440 new)
5441 "List of all argument lists for Todo mode item insertion commands.")
5442
5443 (defun todo-insertion-command-name (arglist)
5444 "Generate Todo mode item insertion command name from ARGLIST."
5445 (replace-regexp-in-string
5446 "-\\_>" ""
5447 (replace-regexp-in-string
5448 "-+" "-"
5449 (concat "todo-insert-item-"
5450 (mapconcat (lambda (e) (if e (symbol-name e))) arglist "-")))))
5451
5452 (defvar todo-insertion-commands-names
5453 (mapcar (lambda (l)
5454 (todo-insertion-command-name l))
5455 todo-insertion-commands-args)
5456 "List of names of Todo mode item insertion commands.")
5457
5458 (defmacro todo-define-insertion-command (&rest args)
5459 "Generate Todo mode item insertion command definitions from ARGS."
5460 (let ((name (intern (todo-insertion-command-name args)))
5461 (arg0 (nth 0 args))
5462 (arg1 (nth 1 args))
5463 (arg2 (nth 2 args))
5464 (arg3 (nth 3 args))
5465 (arg4 (nth 4 args)))
5466 `(defun ,name (&optional arg &rest args)
5467 "Todo mode item insertion command generated from ARGS.
5468 For descriptions of the individual arguments, their values, and
5469 their relation to key bindings, see `todo-basic-insert-item'."
5470 (interactive (list current-prefix-arg))
5471 (todo-basic-insert-item arg ',arg0 ',arg1 ',arg2 ',arg3 ',arg4))))
5472
5473 (defvar todo-insertion-commands
5474 (mapcar (lambda (c)
5475 (eval `(todo-define-insertion-command ,@c)))
5476 todo-insertion-commands-args)
5477 "List of Todo mode item insertion commands.")
5478
5479 (defvar todo-insertion-commands-arg-key-list
5480 '(("diary" "y" "yy")
5481 ("nonmarking" "k" "kk")
5482 ("calendar" "c" "cc")
5483 ("date" "d" "dd")
5484 ("dayname" "n" "nn")
5485 ("time" "t" "tt")
5486 ("here" "h" "h")
5487 ("region" "r" "r"))
5488 "List of mappings of item insertion command arguments to key sequences.")
5489
5490 (defun todo-insertion-key-bindings (map)
5491 "Generate key binding definitions for item insertion keymap MAP."
5492 (dolist (c todo-insertion-commands)
5493 (let* ((key "")
5494 (cname (symbol-name c)))
5495 (mapc (lambda (l)
5496 (let ((arg (nth 0 l))
5497 (key1 (nth 1 l))
5498 (key2 (nth 2 l)))
5499 (if (string-match (concat (regexp-quote arg) "\\_>") cname)
5500 (setq key (concat key key2)))
5501 (if (string-match (concat (regexp-quote arg) ".+") cname)
5502 (setq key (concat key key1)))))
5503 todo-insertion-commands-arg-key-list)
5504 (if (string-match (concat (regexp-quote "todo-insert-item") "\\_>") cname)
5505 (setq key (concat key "i")))
5506 (define-key map key c))))
5507
5508 ;; -----------------------------------------------------------------------------
5509 ;;; Todo minibuffer utilities
5510 ;; -----------------------------------------------------------------------------
5511
5512 (defcustom todo-y-with-space nil
5513 "Non-nil means allow SPC to affirm a \"y or n\" question."
5514 :type 'boolean
5515 :group 'todo)
5516
5517 (defun todo-y-or-n-p (prompt)
5518 "Ask \"y or n\" question PROMPT and return t if answer is \"y\".
5519 Also return t if answer is \"Y\", but unlike `y-or-n-p', allow
5520 SPC to affirm the question only if option `todo-y-with-space' is
5521 non-nil."
5522 (unless todo-y-with-space
5523 (define-key query-replace-map " " 'ignore))
5524 (prog1
5525 (y-or-n-p prompt)
5526 (define-key query-replace-map " " 'act)))
5527
5528 (defun todo-category-completions (&optional archive)
5529 "Return a list of completions for `todo-read-category'.
5530 Each element of the list is a cons of a category name and the
5531 file or list of files (as short file names) it is in. The files
5532 are either the current (or if there is none, the default) todo
5533 file plus the files listed in `todo-category-completions-files',
5534 or, with non-nil ARCHIVE, the current archive file.
5535
5536 Before calculating the completions, update the value of
5537 `todo-category-completions-files' in case any files named in it
5538 have been removed."
5539 (let (deleted)
5540 (dolist (f todo-category-completions-files)
5541 (unless (file-exists-p (todo-absolute-file-name f))
5542 (setq todo-category-completions-files
5543 (delete f todo-category-completions-files))
5544 (push f deleted)))
5545 (when deleted
5546 (let ((pl (> (length deleted) 1))
5547 (names (mapconcat (lambda (f) (concat "\"" f "\"")) deleted ", ")))
5548 (message (concat "File" (if pl "s" "") " " names " ha" (if pl "ve" "s")
5549 " been deleted and removed from\n"
5550 "the list of category completion files")))
5551 (todo-reevaluate-category-completions-files-defcustom)
5552 (custom-set-default 'todo-category-completions-files
5553 (symbol-value 'todo-category-completions-files))
5554 (sleep-for 1.5)))
5555 (let* ((curfile (or todo-current-todo-file
5556 (and todo-show-current-file
5557 todo-global-current-todo-file)
5558 (todo-absolute-file-name todo-default-todo-file)))
5559 (files (or (unless archive
5560 (mapcar 'todo-absolute-file-name
5561 todo-category-completions-files))
5562 (list curfile)))
5563 listall listf)
5564 ;; If file was just added, it has no category completions.
5565 (unless (zerop (buffer-size (find-buffer-visiting curfile)))
5566 (unless (member curfile todo-archives)
5567 (add-to-list 'files curfile))
5568 (dolist (f files listall)
5569 (with-current-buffer (find-file-noselect f 'nowarn)
5570 ;; Ensure category is properly displayed in case user
5571 ;; switches to file via a non-Todo mode command. And if
5572 ;; done items in category are visible, keep them visible.
5573 (let ((done todo-show-with-done))
5574 (when (> (buffer-size) (- (point-max) (point-min)))
5575 (save-excursion
5576 (goto-char (point-min))
5577 (setq done (re-search-forward todo-done-string-start nil t))))
5578 (let ((todo-show-with-done done))
5579 (save-excursion (todo-category-select))))
5580 (save-excursion
5581 (save-restriction
5582 (widen)
5583 (goto-char (point-min))
5584 (setq listf (read (buffer-substring-no-properties
5585 (line-beginning-position)
5586 (line-end-position)))))))
5587 (mapc (lambda (elt) (let* ((cat (car elt))
5588 (la-elt (assoc cat listall)))
5589 (if la-elt
5590 (setcdr la-elt (append (list (cdr la-elt))
5591 (list f)))
5592 (push (cons cat f) listall))))
5593 listf)))))
5594
5595 (defun todo-read-file-name (prompt &optional archive mustmatch)
5596 "Choose and return the name of a todo file, prompting with PROMPT.
5597
5598 Show completions with TAB or SPC; the names are shown in short
5599 form but the absolute truename is returned. With non-nil ARCHIVE
5600 return the absolute truename of a todo archive file. With non-nil
5601 MUSTMATCH the name of an existing file must be chosen;
5602 otherwise, a new file name is allowed."
5603 (let* ((completion-ignore-case todo-completion-ignore-case)
5604 (files (mapcar 'todo-short-file-name
5605 ;; (funcall todo-files-function archive)))
5606 (if archive todo-archives todo-files)))
5607 (file (completing-read prompt files nil mustmatch nil nil
5608 (if files
5609 ;; If user hit RET without
5610 ;; choosing a file, default to
5611 ;; current or default file.
5612 (todo-short-file-name
5613 (or todo-current-todo-file
5614 (and todo-show-current-file
5615 todo-global-current-todo-file)
5616 (todo-absolute-file-name
5617 todo-default-todo-file)))
5618 ;; Trigger prompt for initial file.
5619 ""))))
5620 (unless (file-exists-p todo-directory)
5621 (make-directory todo-directory))
5622 (unless mustmatch
5623 (setq file (todo-validate-name file 'file)))
5624 (setq file (file-truename (concat todo-directory file
5625 (if archive ".toda" ".todo"))))))
5626
5627 (defun todo-read-category (prompt &optional match-type file)
5628 "Choose and return a category name, prompting with PROMPT.
5629 Show completions for existing categories with TAB or SPC.
5630
5631 The argument MATCH-TYPE specifies the matching requirements on
5632 the category name: with the value `todo' or `archive' the name
5633 must complete to that of an existing todo or archive category,
5634 respectively; with the value `add' the name must not be that of
5635 an existing category; with all other values both existing and new
5636 valid category names are accepted.
5637
5638 With non-nil argument FILE prompt for a file and complete only
5639 against categories in that file; otherwise complete against all
5640 categories from `todo-category-completions-files'."
5641 ;; Allow SPC to insert spaces, for adding new category names.
5642 (let ((map minibuffer-local-completion-map))
5643 (define-key map " " nil)
5644 (let* ((add (eq match-type 'add))
5645 (archive (eq match-type 'archive))
5646 (file0 (when (and file (> (length todo-files) 1))
5647 (todo-read-file-name (concat "Choose a" (if archive
5648 "n archive"
5649 " todo")
5650 " file: ") archive t)))
5651 (completions (unless file0 (todo-category-completions archive)))
5652 (categories (cond (file0
5653 (with-current-buffer
5654 (find-file-noselect file0 'nowarn)
5655 (let ((todo-current-todo-file file0))
5656 todo-categories)))
5657 ((and add (not file))
5658 (with-current-buffer
5659 (find-file-noselect todo-current-todo-file)
5660 todo-categories))
5661 (t
5662 completions)))
5663 (completion-ignore-case todo-completion-ignore-case)
5664 (cat (completing-read prompt categories nil
5665 (eq match-type 'todo) nil nil
5666 ;; Unless we're adding a category via
5667 ;; todo-add-category, set default
5668 ;; for existing categories to the
5669 ;; current category of the chosen
5670 ;; file or else of the current file.
5671 (if (and categories (not add))
5672 (with-current-buffer
5673 (find-file-noselect
5674 (or file0
5675 todo-current-todo-file
5676 (todo-absolute-file-name
5677 todo-default-todo-file)))
5678 (todo-current-category))
5679 ;; Trigger prompt for initial category.
5680 "")))
5681 (catfil (cdr (assoc cat completions)))
5682 (str "Category \"%s\" from which file (TAB for choices)? "))
5683 ;; If we do category completion and the chosen category name
5684 ;; occurs in more than one file, prompt to choose one file.
5685 (unless (or file0 add (not catfil))
5686 (setq file0 (file-truename
5687 (if (atom catfil)
5688 catfil
5689 (todo-absolute-file-name
5690 (let ((files (mapcar 'todo-short-file-name catfil)))
5691 (completing-read (format str cat) files)))))))
5692 ;; Default to the current file.
5693 (unless file0 (setq file0 todo-current-todo-file))
5694 ;; First validate only a name passed interactively from
5695 ;; todo-add-category, which must be of a nonexistent category.
5696 (unless (and (assoc cat categories) (not add))
5697 ;; Validate only against completion categories.
5698 (let ((todo-categories categories))
5699 (setq cat (todo-validate-name cat 'category)))
5700 ;; When user enters a nonexistent category name by jumping or
5701 ;; moving, confirm that it should be added, then validate.
5702 (unless add
5703 (if (todo-y-or-n-p (format "Add new category \"%s\" to file \"%s\"? "
5704 cat (todo-short-file-name file0)))
5705 (progn
5706 (when (assoc cat categories)
5707 (let ((todo-categories categories))
5708 (setq cat (todo-validate-name cat 'category))))
5709 ;; Restore point and narrowing after adding new
5710 ;; category, to avoid moving to beginning of file when
5711 ;; moving marked items to a new category
5712 ;; (todo-move-item).
5713 (save-excursion
5714 (save-restriction
5715 (todo-add-category file0 cat))))
5716 ;; If we decide not to add a category, exit without returning.
5717 (keyboard-quit))))
5718 (cons cat file0))))
5719
5720 (defun todo-validate-name (name type)
5721 "Prompt for new NAME for TYPE until it is valid, then return it.
5722 TYPE can be either of the symbols `file' or `category'."
5723 (let ((categories todo-categories)
5724 (files (mapcar 'todo-short-file-name todo-files))
5725 prompt)
5726 (while
5727 (and
5728 (cond ((string= "" name)
5729 (setq prompt
5730 (cond ((eq type 'file)
5731 (if files
5732 "Enter a non-empty file name: "
5733 ;; Empty string passed by todo-show to
5734 ;; prompt for initial todo file.
5735 (concat "Initial file name ["
5736 todo-initial-file "]: ")))
5737 ((eq type 'category)
5738 (if categories
5739 "Enter a non-empty category name: "
5740 ;; Empty string passed by todo-show to
5741 ;; prompt for initial category of a new
5742 ;; todo file.
5743 (concat "Initial category name ["
5744 todo-initial-category "]: "))))))
5745 ((string-match "\\`\\s-+\\'" name)
5746 (setq prompt
5747 "Enter a name that does not contain only white space: "))
5748 ((and (eq type 'file) (member name files))
5749 (setq prompt "Enter a non-existing file name: "))
5750 ((and (eq type 'category) (assoc name categories))
5751 (setq prompt "Enter a non-existing category name: ")))
5752 (setq name (if (or (and (eq type 'file) files)
5753 (and (eq type 'category) categories))
5754 (completing-read prompt (cond ((eq type 'file)
5755 files)
5756 ((eq type 'category)
5757 categories)))
5758 ;; Offer default initial name.
5759 (completing-read prompt (if (eq type 'file)
5760 files
5761 categories)
5762 nil nil (if (eq type 'file)
5763 todo-initial-file
5764 todo-initial-category))))))
5765 name))
5766
5767 ;; Adapted from calendar-read-date and calendar-date-string.
5768 (defun todo-read-date (&optional arg mo yr)
5769 "Prompt for Gregorian date and return it in the current format.
5770
5771 With non-nil ARG, prompt for and return only the date component
5772 specified by ARG, which can be one of these symbols:
5773 `month' (prompt for name, return name or number according to
5774 value of `calendar-date-display-form'), `day' of month, or
5775 `year'. The value of each of these components can be `*',
5776 indicating an unspecified month, day, or year.
5777
5778 When ARG is `day', non-nil arguments MO and YR determine the
5779 number of the last the day of the month."
5780 (let (year monthname month day
5781 dayname) ; Needed by calendar-date-display-form.
5782 (when (or (not arg) (eq arg 'year))
5783 (while (if (natnump year) (< year 1) (not (eq year '*)))
5784 (setq year (read-from-minibuffer
5785 "Year (>0 or RET for this year or * for any year): "
5786 nil nil t nil (number-to-string
5787 (calendar-extract-year
5788 (calendar-current-date)))))))
5789 (when (or (not arg) (eq arg 'month))
5790 (let* ((marray todo-month-name-array)
5791 (mlist (append marray nil))
5792 (mabarray todo-month-abbrev-array)
5793 (mablist (append mabarray nil))
5794 (completion-ignore-case todo-completion-ignore-case))
5795 (setq monthname (completing-read
5796 "Month name (RET for current month, * for any month): "
5797 mlist nil t nil nil
5798 (calendar-month-name (calendar-extract-month
5799 (calendar-current-date)) t))
5800 month (1+ (- (length mlist)
5801 (length (or (member monthname mlist)
5802 (member monthname mablist))))))
5803 (setq monthname (aref mabarray (1- month)))))
5804 (when (or (not arg) (eq arg 'day))
5805 (let ((last (let ((mm (or month mo))
5806 (yy (or year yr)))
5807 ;; If month is unspecified, use a month with 31
5808 ;; days for checking day of month input. Does
5809 ;; Calendar do anything special when * is
5810 ;; currently a shorter month?
5811 (if (= mm 13) (setq mm 1))
5812 ;; If year is unspecified, use a leap year to
5813 ;; allow Feb. 29.
5814 (if (eq year '*) (setq yy 2012))
5815 (calendar-last-day-of-month mm yy))))
5816 (while (if (natnump day) (or (< day 1) (> day last)) (not (eq day '*)))
5817 (setq day (read-from-minibuffer
5818 (format "Day (1-%d or RET for today or * for any day): "
5819 last)
5820 nil nil t nil (number-to-string
5821 (calendar-extract-day
5822 (calendar-current-date))))))))
5823 ;; Stringify read values (monthname is already a string).
5824 (and year (setq year (if (eq year '*)
5825 (symbol-name '*)
5826 (number-to-string year))))
5827 (and day (setq day (if (eq day '*)
5828 (symbol-name '*)
5829 (number-to-string day))))
5830 (and month (setq month (if (eq month '*)
5831 (symbol-name '*)
5832 (number-to-string month))))
5833 (if arg
5834 (cond ((eq arg 'year) year)
5835 ((eq arg 'day) day)
5836 ((eq arg 'month)
5837 (if (memq 'month calendar-date-display-form)
5838 month
5839 monthname)))
5840 (mapconcat 'eval calendar-date-display-form ""))))
5841
5842 (defun todo-read-dayname ()
5843 "Choose name of a day of the week with completion and return it."
5844 (let ((completion-ignore-case todo-completion-ignore-case))
5845 (completing-read "Enter a day name: "
5846 (append calendar-day-name-array nil)
5847 nil t)))
5848
5849 (defun todo-read-time ()
5850 "Prompt for and return a valid clock time as a string.
5851
5852 Valid time strings are those matching `diary-time-regexp'.
5853 Typing `<return>' at the prompt returns the current time, if the
5854 user option `todo-always-add-time-string' is non-nil, otherwise
5855 the empty string (i.e., no time string)."
5856 (let (valid answer)
5857 (while (not valid)
5858 (setq answer (read-string "Enter a clock time: " nil nil
5859 (when todo-always-add-time-string
5860 (substring (current-time-string) 11 16))))
5861 (when (or (string= "" answer)
5862 (string-match diary-time-regexp answer))
5863 (setq valid t)))
5864 answer))
5865
5866 ;; -----------------------------------------------------------------------------
5867 ;;; Customization groups and utilities
5868 ;; -----------------------------------------------------------------------------
5869
5870 (defgroup todo nil
5871 "Create and maintain categorized lists of todo items."
5872 :link '(emacs-commentary-link "todo")
5873 :version "24.4"
5874 :group 'calendar)
5875
5876 (defgroup todo-edit nil
5877 "User options for adding and editing todo items."
5878 :version "24.4"
5879 :group 'todo)
5880
5881 (defgroup todo-categories nil
5882 "User options for Todo Categories mode."
5883 :version "24.4"
5884 :group 'todo)
5885
5886 (defgroup todo-filtered nil
5887 "User options for Todo Filter Items mode."
5888 :version "24.4"
5889 :group 'todo)
5890
5891 (defgroup todo-display nil
5892 "User display options for Todo mode."
5893 :version "24.4"
5894 :group 'todo)
5895
5896 (defgroup todo-faces nil
5897 "Faces for the Todo modes."
5898 :version "24.4"
5899 :group 'todo)
5900
5901 (defun todo-set-show-current-file (symbol value)
5902 "The :set function for user option `todo-show-current-file'."
5903 (custom-set-default symbol value)
5904 (if value
5905 (add-hook 'pre-command-hook 'todo-show-current-file nil t)
5906 (remove-hook 'pre-command-hook 'todo-show-current-file t)))
5907
5908 (defun todo-reset-prefix (symbol value)
5909 "The :set function for `todo-prefix' and `todo-number-prefix'."
5910 (let ((oldvalue (symbol-value symbol))
5911 (files todo-file-buffers))
5912 (custom-set-default symbol value)
5913 (when (not (equal value oldvalue))
5914 (dolist (f files)
5915 (with-current-buffer (find-file-noselect f)
5916 ;; Activate the new setting in the current category.
5917 (save-excursion (todo-category-select)))))))
5918
5919 (defun todo-reset-nondiary-marker (symbol value)
5920 "The :set function for user option `todo-nondiary-marker'."
5921 (let ((oldvalue (symbol-value symbol))
5922 (files (append todo-files todo-archives)))
5923 (custom-set-default symbol value)
5924 ;; Need to reset these to get font-locking right.
5925 (setq todo-nondiary-start (nth 0 todo-nondiary-marker)
5926 todo-nondiary-end (nth 1 todo-nondiary-marker)
5927 todo-date-string-start
5928 ;; See comment in defvar of `todo-date-string-start'.
5929 (concat "^\\(" (regexp-quote todo-nondiary-start) "\\|"
5930 (regexp-quote diary-nonmarking-symbol) "\\)?"))
5931 (when (not (equal value oldvalue))
5932 (dolist (f files)
5933 (with-current-buffer (find-file-noselect f)
5934 (let (buffer-read-only)
5935 (widen)
5936 (goto-char (point-min))
5937 (while (not (eobp))
5938 (if (re-search-forward
5939 (concat "^\\(" todo-done-string-start "[^][]+] \\)?"
5940 "\\(?1:" (regexp-quote (car oldvalue))
5941 "\\)" todo-date-pattern "\\( "
5942 diary-time-regexp "\\)?\\(?2:"
5943 (regexp-quote (cadr oldvalue)) "\\)")
5944 nil t)
5945 (progn
5946 (replace-match (nth 0 value) t t nil 1)
5947 (replace-match (nth 1 value) t t nil 2))
5948 (forward-line)))
5949 (todo-category-select)))))))
5950
5951 (defun todo-reset-done-separator-string (symbol value)
5952 "The :set function for `todo-done-separator-string'."
5953 (let ((oldvalue (symbol-value symbol))
5954 (files todo-file-buffers)
5955 (sep todo-done-separator))
5956 (custom-set-default symbol value)
5957 (when (not (equal value oldvalue))
5958 (dolist (f files)
5959 (with-current-buffer (find-file-noselect f)
5960 (let (buffer-read-only)
5961 (setq todo-done-separator (todo-done-separator))
5962 (when (= 1 (length value))
5963 (todo-reset-done-separator sep)))
5964 (todo-category-select))))))
5965
5966 (defun todo-reset-done-string (symbol value)
5967 "The :set function for user option `todo-done-string'."
5968 (let ((oldvalue (symbol-value symbol))
5969 (files (append todo-files todo-archives)))
5970 (custom-set-default symbol value)
5971 ;; Need to reset this to get font-locking right.
5972 (setq todo-done-string-start
5973 (concat "^\\[" (regexp-quote todo-done-string)))
5974 (when (not (equal value oldvalue))
5975 (dolist (f files)
5976 (with-current-buffer (find-file-noselect f)
5977 (let (buffer-read-only)
5978 (widen)
5979 (goto-char (point-min))
5980 (while (not (eobp))
5981 (if (re-search-forward
5982 (concat "^" (regexp-quote todo-nondiary-start)
5983 "\\(" (regexp-quote oldvalue) "\\)")
5984 nil t)
5985 (replace-match value t t nil 1)
5986 (forward-line)))
5987 (todo-category-select)))))))
5988
5989 (defun todo-reset-comment-string (symbol value)
5990 "The :set function for user option `todo-comment-string'."
5991 (let ((oldvalue (symbol-value symbol))
5992 (files (append todo-files todo-archives)))
5993 (custom-set-default symbol value)
5994 (when (not (equal value oldvalue))
5995 (dolist (f files)
5996 (with-current-buffer (find-file-noselect f)
5997 (let (buffer-read-only)
5998 (save-excursion
5999 (widen)
6000 (goto-char (point-min))
6001 (while (not (eobp))
6002 (if (re-search-forward
6003 (concat
6004 "\\[\\(" (regexp-quote oldvalue) "\\): [^]]*\\]")
6005 nil t)
6006 (replace-match value t t nil 1)
6007 (forward-line)))
6008 (todo-category-select))))))))
6009
6010 (defun todo-reset-highlight-item (symbol value)
6011 "The :set function for `todo-toggle-item-highlighting'."
6012 (let ((oldvalue (symbol-value symbol))
6013 (files (append todo-files todo-archives)))
6014 (custom-set-default symbol value)
6015 (when (not (equal value oldvalue))
6016 (dolist (f files)
6017 (let ((buf (find-buffer-visiting f)))
6018 (when buf
6019 (with-current-buffer buf
6020 (require 'hl-line)
6021 (if value
6022 (hl-line-mode 1)
6023 (hl-line-mode -1)))))))))
6024
6025 (defun todo-reevaluate-filelist-defcustoms ()
6026 "Reevaluate defcustoms that provide choice list of todo files."
6027 (custom-set-default 'todo-default-todo-file
6028 (symbol-value 'todo-default-todo-file))
6029 (todo-reevaluate-default-file-defcustom)
6030 (custom-set-default 'todo-filter-files (symbol-value 'todo-filter-files))
6031 (todo-reevaluate-filter-files-defcustom)
6032 (custom-set-default 'todo-category-completions-files
6033 (symbol-value 'todo-category-completions-files))
6034 (todo-reevaluate-category-completions-files-defcustom))
6035
6036 (defun todo-reevaluate-default-file-defcustom ()
6037 "Reevaluate defcustom of `todo-default-todo-file'.
6038 Called after adding or deleting a todo file. If the value of
6039 `todo-default-todo-file' before calling this function was
6040 associated with an existing file, keep that value."
6041 ;; (let ((curval todo-default-todo-file))
6042 (eval
6043 (defcustom todo-default-todo-file (todo-short-file-name
6044 (car (funcall todo-files-function)))
6045 "Todo file visited by first session invocation of `todo-show'."
6046 :type (when todo-files
6047 `(radio ,@(mapcar (lambda (f) (list 'const f))
6048 (mapcar 'todo-short-file-name
6049 (funcall todo-files-function)))))
6050 :group 'todo))
6051 ;; (when (and curval (file-exists-p (todo-absolute-file-name curval)))
6052 ;; (custom-set-default 'todo-default-todo-file curval)
6053 ;; ;; (custom-reevaluate-setting 'todo-default-todo-file)
6054 ;; )))
6055 )
6056
6057 (defun todo-reevaluate-category-completions-files-defcustom ()
6058 "Reevaluate defcustom of `todo-category-completions-files'.
6059 Called after adding or deleting a todo file."
6060 (eval (defcustom todo-category-completions-files nil
6061 "List of files for building `todo-read-category' completions."
6062 :type `(set ,@(mapcar (lambda (f) (list 'const f))
6063 (mapcar 'todo-short-file-name
6064 (funcall todo-files-function))))
6065 :group 'todo)))
6066
6067 (defun todo-reevaluate-filter-files-defcustom ()
6068 "Reevaluate defcustom of `todo-filter-files'.
6069 Called after adding or deleting a todo file."
6070 (eval (defcustom todo-filter-files nil
6071 "List of files for multifile item filtering."
6072 :type `(set ,@(mapcar (lambda (f) (list 'const f))
6073 (mapcar 'todo-short-file-name
6074 (funcall todo-files-function))))
6075 :group 'todo)))
6076
6077 ;; -----------------------------------------------------------------------------
6078 ;;; Font locking
6079 ;; -----------------------------------------------------------------------------
6080
6081 (defun todo-nondiary-marker-matcher (lim)
6082 "Search for todo item nondiary markers within LIM for font-locking."
6083 (re-search-forward (concat "^\\(?1:" (regexp-quote todo-nondiary-start) "\\)"
6084 todo-date-pattern "\\(?: " diary-time-regexp
6085 "\\)?\\(?2:" (regexp-quote todo-nondiary-end) "\\)")
6086 lim t))
6087
6088 (defun todo-diary-nonmarking-matcher (lim)
6089 "Search for diary nonmarking symbol within LIM for font-locking."
6090 (re-search-forward (concat "^\\(?1:" (regexp-quote diary-nonmarking-symbol)
6091 "\\)" todo-date-pattern) lim t))
6092
6093 (defun todo-date-string-matcher (lim)
6094 "Search for todo item date string within LIM for font-locking."
6095 (re-search-forward
6096 (concat todo-date-string-start "\\(?1:" todo-date-pattern "\\)") lim t))
6097
6098 (defun todo-time-string-matcher (lim)
6099 "Search for todo item time string within LIM for font-locking."
6100 (re-search-forward (concat todo-date-string-start todo-date-pattern
6101 " \\(?1:" diary-time-regexp "\\)") lim t))
6102
6103 (defun todo-diary-expired-matcher (lim)
6104 "Search for expired diary item date within LIM for font-locking."
6105 (when (re-search-forward (concat "^\\(?:"
6106 (regexp-quote diary-nonmarking-symbol)
6107 "\\)?\\(?1:" todo-date-pattern "\\) \\(?2:"
6108 diary-time-regexp "\\)?") lim t)
6109 (let* ((date (match-string-no-properties 1))
6110 (time (match-string-no-properties 2))
6111 ;; Function days-between requires a non-empty time string.
6112 (date-time (concat date " " (or time "00:00"))))
6113 (or (and (not (string-match ".+day\\|\\*" date))
6114 (< (days-between date-time (current-time-string)) 0))
6115 (todo-diary-expired-matcher lim)))))
6116
6117 (defun todo-done-string-matcher (lim)
6118 "Search for done todo item header within LIM for font-locking."
6119 (re-search-forward (concat todo-done-string-start
6120 "[^][]+]")
6121 lim t))
6122
6123 (defun todo-comment-string-matcher (lim)
6124 "Search for done todo item comment within LIM for font-locking."
6125 (re-search-forward (concat "\\[\\(?1:" todo-comment-string "\\):")
6126 lim t))
6127
6128 (defun todo-category-string-matcher-1 (lim)
6129 "Search for todo category name within LIM for font-locking.
6130 This is for fontifying category and file names appearing in Todo
6131 Filtered Items mode following done items."
6132 (if (eq major-mode 'todo-filtered-items-mode)
6133 (re-search-forward (concat todo-done-string-start todo-date-pattern
6134 "\\(?: " diary-time-regexp
6135 ;; Use non-greedy operator to prevent
6136 ;; capturing possible following non-diary
6137 ;; date string.
6138 "\\)?] \\(?1:\\[.+?\\]\\)")
6139 lim t)))
6140
6141 (defun todo-category-string-matcher-2 (lim)
6142 "Search for todo category name within LIM for font-locking.
6143 This is for fontifying category and file names appearing in Todo
6144 Filtered Items mode following todo (not done) items."
6145 (if (eq major-mode 'todo-filtered-items-mode)
6146 (re-search-forward (concat todo-date-string-start todo-date-pattern
6147 "\\(?: " diary-time-regexp "\\)?\\(?:"
6148 (regexp-quote todo-nondiary-end)
6149 "\\)? \\(?1:\\[.+\\]\\)")
6150 lim t)))
6151
6152 (defvar todo-nondiary-face 'todo-nondiary)
6153 (defvar todo-date-face 'todo-date)
6154 (defvar todo-time-face 'todo-time)
6155 (defvar todo-diary-expired-face 'todo-diary-expired)
6156 (defvar todo-done-sep-face 'todo-done-sep)
6157 (defvar todo-done-face 'todo-done)
6158 (defvar todo-comment-face 'todo-comment)
6159 (defvar todo-category-string-face 'todo-category-string)
6160 (defvar todo-font-lock-keywords
6161 (list
6162 '(todo-nondiary-marker-matcher 1 todo-nondiary-face t)
6163 '(todo-nondiary-marker-matcher 2 todo-nondiary-face t)
6164 ;; diary-lib.el uses font-lock-constant-face for diary-nonmarking-symbol.
6165 '(todo-diary-nonmarking-matcher 1 font-lock-constant-face t)
6166 '(todo-date-string-matcher 1 todo-date-face t)
6167 '(todo-time-string-matcher 1 todo-time-face t)
6168 '(todo-done-string-matcher 0 todo-done-face t)
6169 '(todo-comment-string-matcher 1 todo-comment-face t)
6170 '(todo-category-string-matcher-1 1 todo-category-string-face t t)
6171 '(todo-category-string-matcher-2 1 todo-category-string-face t t)
6172 '(todo-diary-expired-matcher 1 todo-diary-expired-face t)
6173 '(todo-diary-expired-matcher 2 todo-diary-expired-face t t)
6174 )
6175 "Font-locking for Todo modes.")
6176
6177 ;; -----------------------------------------------------------------------------
6178 ;;; Key binding
6179 ;; -----------------------------------------------------------------------------
6180
6181 (defvar todo-insertion-map
6182 (let ((map (make-keymap)))
6183 (todo-insertion-key-bindings map)
6184 (define-key map "p" 'todo-copy-item)
6185 map)
6186 "Keymap for Todo mode item insertion commands.")
6187
6188 (defvar todo-key-bindings-t
6189 `(
6190 ("Af" todo-find-archive)
6191 ("Ac" todo-choose-archive)
6192 ("Ad" todo-archive-done-item)
6193 ("Cv" todo-toggle-view-done-items)
6194 ("v" todo-toggle-view-done-items)
6195 ("Ca" todo-add-category)
6196 ("Cr" todo-rename-category)
6197 ("Cg" todo-merge-category)
6198 ("Cm" todo-move-category)
6199 ("Ck" todo-delete-category)
6200 ("Cts" todo-set-top-priorities-in-category)
6201 ("Cey" todo-edit-category-diary-inclusion)
6202 ("Cek" todo-edit-category-diary-nonmarking)
6203 ("Fa" todo-add-file)
6204 ("Fr" todo-rename-file)
6205 ("Ff" todo-find-filtered-items-file)
6206 ("FV" todo-toggle-view-done-only)
6207 ("V" todo-toggle-view-done-only)
6208 ("Ftt" todo-filter-top-priorities)
6209 ("Ftm" todo-filter-top-priorities-multifile)
6210 ("Fts" todo-set-top-priorities-in-file)
6211 ("Fyy" todo-filter-diary-items)
6212 ("Fym" todo-filter-diary-items-multifile)
6213 ("Fxx" todo-filter-regexp-items)
6214 ("Fxm" todo-filter-regexp-items-multifile)
6215 ("ee" todo-edit-item)
6216 ("em" todo-edit-multiline-item)
6217 ("edt" todo-edit-item-header)
6218 ("edc" todo-edit-item-date-from-calendar)
6219 ("eda" todo-edit-item-date-to-today)
6220 ("edn" todo-edit-item-date-day-name)
6221 ("edy" todo-edit-item-date-year)
6222 ("edm" todo-edit-item-date-month)
6223 ("edd" todo-edit-item-date-day)
6224 ("et" todo-edit-item-time)
6225 ("eyy" todo-edit-item-diary-inclusion)
6226 ("eyk" todo-edit-item-diary-nonmarking)
6227 ("ec" todo-edit-done-item-comment)
6228 ("d" todo-item-done)
6229 ("i" ,todo-insertion-map)
6230 ("k" todo-delete-item)
6231 ("m" todo-move-item)
6232 ("u" todo-item-undone)
6233 ([remap newline] newline-and-indent)
6234 )
6235 "List of key bindings for Todo mode only.")
6236
6237 (defvar todo-key-bindings-t+a+f
6238 `(
6239 ("C*" todo-mark-category)
6240 ("Cu" todo-unmark-category)
6241 ("Fh" todo-toggle-item-header)
6242 ("h" todo-toggle-item-header)
6243 ("Fk" todo-delete-file)
6244 ("Fe" todo-edit-file)
6245 ("FH" todo-toggle-item-highlighting)
6246 ("H" todo-toggle-item-highlighting)
6247 ("FN" todo-toggle-prefix-numbers)
6248 ("N" todo-toggle-prefix-numbers)
6249 ("PB" todo-print-buffer)
6250 ("PF" todo-print-buffer-to-file)
6251 ("b" todo-backward-category)
6252 ("d" todo-item-done)
6253 ("f" todo-forward-category)
6254 ("j" todo-jump-to-category)
6255 ("n" todo-next-item)
6256 ("p" todo-previous-item)
6257 ("q" todo-quit)
6258 ("s" todo-save)
6259 ("t" todo-show)
6260 )
6261 "List of key bindings for Todo, Archive, and Filtered Items modes.")
6262
6263 (defvar todo-key-bindings-t+a
6264 `(
6265 ("Fc" todo-show-categories-table)
6266 ("S" todo-search)
6267 ("X" todo-clear-matches)
6268 ("*" todo-toggle-mark-item)
6269 )
6270 "List of key bindings for Todo and Todo Archive modes.")
6271
6272 (defvar todo-key-bindings-t+f
6273 `(
6274 ("l" todo-lower-item-priority)
6275 ("r" todo-raise-item-priority)
6276 ("#" todo-set-item-priority)
6277 )
6278 "List of key bindings for Todo and Todo Filtered Items modes.")
6279
6280 (defvar todo-mode-map
6281 (let ((map (make-keymap)))
6282 ;; Don't suppress digit keys, so they can supply prefix arguments.
6283 (suppress-keymap map)
6284 (dolist (kb todo-key-bindings-t)
6285 (define-key map (nth 0 kb) (nth 1 kb)))
6286 (dolist (kb todo-key-bindings-t+a+f)
6287 (define-key map (nth 0 kb) (nth 1 kb)))
6288 (dolist (kb todo-key-bindings-t+a)
6289 (define-key map (nth 0 kb) (nth 1 kb)))
6290 (dolist (kb todo-key-bindings-t+f)
6291 (define-key map (nth 0 kb) (nth 1 kb)))
6292 map)
6293 "Todo mode keymap.")
6294
6295 (defvar todo-archive-mode-map
6296 (let ((map (make-sparse-keymap)))
6297 (suppress-keymap map)
6298 (dolist (kb todo-key-bindings-t+a+f)
6299 (define-key map (nth 0 kb) (nth 1 kb)))
6300 (dolist (kb todo-key-bindings-t+a)
6301 (define-key map (nth 0 kb) (nth 1 kb)))
6302 (define-key map "a" 'todo-jump-to-archive-category)
6303 (define-key map "u" 'todo-unarchive-items)
6304 map)
6305 "Todo Archive mode keymap.")
6306
6307 (defvar todo-edit-mode-map
6308 (let ((map (make-sparse-keymap)))
6309 (define-key map "\C-x\C-q" 'todo-edit-quit)
6310 (define-key map [remap newline] 'newline-and-indent)
6311 map)
6312 "Todo Edit mode keymap.")
6313
6314 (defvar todo-categories-mode-map
6315 (let ((map (make-sparse-keymap)))
6316 (suppress-keymap map)
6317 (define-key map "c" 'todo-sort-categories-alphabetically-or-numerically)
6318 (define-key map "t" 'todo-sort-categories-by-todo)
6319 (define-key map "y" 'todo-sort-categories-by-diary)
6320 (define-key map "d" 'todo-sort-categories-by-done)
6321 (define-key map "a" 'todo-sort-categories-by-archived)
6322 (define-key map "#" 'todo-set-category-number)
6323 (define-key map "l" 'todo-lower-category)
6324 (define-key map "r" 'todo-raise-category)
6325 (define-key map "n" 'todo-next-button)
6326 (define-key map "p" 'todo-previous-button)
6327 (define-key map [tab] 'todo-next-button)
6328 (define-key map [backtab] 'todo-previous-button)
6329 (define-key map "q" 'todo-quit)
6330 map)
6331 "Todo Categories mode keymap.")
6332
6333 (defvar todo-filtered-items-mode-map
6334 (let ((map (make-sparse-keymap)))
6335 (suppress-keymap map)
6336 (dolist (kb todo-key-bindings-t+a+f)
6337 (define-key map (nth 0 kb) (nth 1 kb)))
6338 (dolist (kb todo-key-bindings-t+f)
6339 (define-key map (nth 0 kb) (nth 1 kb)))
6340 (define-key map "g" 'todo-go-to-source-item)
6341 (define-key map [remap newline] 'todo-go-to-source-item)
6342 map)
6343 "Todo Filtered Items mode keymap.")
6344
6345 ;; FIXME: Is it worth having a menu and if so, which commands?
6346 ;; (easy-menu-define
6347 ;; todo-menu todo-mode-map "Todo Menu"
6348 ;; '("Todo"
6349 ;; ("Navigation"
6350 ;; ["Next Item" todo-forward-item t]
6351 ;; ["Previous Item" todo-backward-item t]
6352 ;; "---"
6353 ;; ["Next Category" todo-forward-category t]
6354 ;; ["Previous Category" todo-backward-category t]
6355 ;; ["Jump to Category" todo-jump-to-category t]
6356 ;; "---"
6357 ;; ["Search Todo File" todo-search t]
6358 ;; ["Clear Highlighting on Search Matches" todo-category-done t])
6359 ;; ("Display"
6360 ;; ["List Current Categories" todo-show-categories-table t]
6361 ;; ;; ["List Categories Alphabetically" todo-display-categories-alphabetically t]
6362 ;; ["Turn Item Highlighting on/off" todo-toggle-item-highlighting t]
6363 ;; ["Turn Item Numbering on/off" todo-toggle-prefix-numbers t]
6364 ;; ["Turn Item Time Stamp on/off" todo-toggle-item-header t]
6365 ;; ["View/Hide Done Items" todo-toggle-view-done-items t]
6366 ;; "---"
6367 ;; ["View Diary Items" todo-filter-diary-items t]
6368 ;; ["View Top Priority Items" todo-filter-top-priorities t]
6369 ;; ["View Multifile Top Priority Items" todo-filter-top-priorities-multifile t]
6370 ;; "---"
6371 ;; ["Print Category" todo-print-buffer t])
6372 ;; ("Editing"
6373 ;; ["Insert New Item" todo-insert-item t]
6374 ;; ["Insert Item Here" todo-insert-item-here t]
6375 ;; ("More Insertion Commands")
6376 ;; ["Edit Item" todo-edit-item t]
6377 ;; ["Edit Multiline Item" todo-edit-multiline-item t]
6378 ;; ["Edit Item Header" todo-edit-item-header t]
6379 ;; ["Edit Item Date" todo-edit-item-date t]
6380 ;; ["Edit Item Time" todo-edit-item-time t]
6381 ;; "---"
6382 ;; ["Lower Item Priority" todo-lower-item-priority t]
6383 ;; ["Raise Item Priority" todo-raise-item-priority t]
6384 ;; ["Set Item Priority" todo-set-item-priority t]
6385 ;; ["Move (Recategorize) Item" todo-move-item t]
6386 ;; ["Delete Item" todo-delete-item t]
6387 ;; ["Undo Done Item" todo-item-undone t]
6388 ;; ["Mark/Unmark Item for Diary" todo-toggle-item-diary-inclusion t]
6389 ;; ["Mark/Unmark Items for Diary" todo-edit-item-diary-inclusion t]
6390 ;; ["Mark & Hide Done Item" todo-item-done t]
6391 ;; ["Archive Done Items" todo-archive-category-done-items t]
6392 ;; "---"
6393 ;; ["Add New Todo File" todo-add-file t]
6394 ;; ["Add New Category" todo-add-category t]
6395 ;; ["Delete Current Category" todo-delete-category t]
6396 ;; ["Rename Current Category" todo-rename-category t]
6397 ;; "---"
6398 ;; ["Save Todo File" todo-save t]
6399 ;; )
6400 ;; "---"
6401 ;; ["Quit" todo-quit t]
6402 ;; ))
6403
6404 ;; -----------------------------------------------------------------------------
6405 ;;; Hook functions and mode definitions
6406 ;; -----------------------------------------------------------------------------
6407
6408 (defun todo-show-current-file ()
6409 "Visit current instead of default todo file with `todo-show'.
6410 Added to `pre-command-hook' in Todo mode when user option
6411 `todo-show-current-file' is set to non-nil."
6412 (setq todo-global-current-todo-file todo-current-todo-file))
6413
6414 (defun todo-display-as-todo-file ()
6415 "Show todo files correctly when visited from outside of Todo mode.
6416 Added to `find-file-hook' in Todo mode and Todo Archive mode."
6417 (and (member this-command todo-visit-files-commands)
6418 (= (- (point-max) (point-min)) (buffer-size))
6419 (member major-mode '(todo-mode todo-archive-mode))
6420 (todo-category-select)))
6421
6422 (defun todo-add-to-buffer-list ()
6423 "Add name of just visited todo file to `todo-file-buffers'.
6424 This function is added to `find-file-hook' in Todo mode."
6425 (let ((filename (file-truename (buffer-file-name))))
6426 (when (member filename todo-files)
6427 (add-to-list 'todo-file-buffers filename))))
6428
6429 (defun todo-update-buffer-list ()
6430 "Make current Todo mode buffer file car of `todo-file-buffers'.
6431 This function is added to `post-command-hook' in Todo mode."
6432 (let ((filename (file-truename (buffer-file-name))))
6433 (unless (eq (car todo-file-buffers) filename)
6434 (setq todo-file-buffers
6435 (cons filename (delete filename todo-file-buffers))))))
6436
6437 (defun todo-reset-global-current-todo-file ()
6438 "Update the value of `todo-global-current-todo-file'.
6439 This becomes the latest existing todo file or, if there is none,
6440 the value of `todo-default-todo-file'.
6441 This function is added to `kill-buffer-hook' in Todo mode."
6442 (let ((filename (file-truename (buffer-file-name))))
6443 (setq todo-file-buffers (delete filename todo-file-buffers))
6444 (setq todo-global-current-todo-file
6445 (or (car todo-file-buffers)
6446 (todo-absolute-file-name todo-default-todo-file)))))
6447
6448 (defun todo-reset-and-enable-done-separator ()
6449 "Show resized done items separator overlay after window change.
6450 Added to `window-configuration-change-hook' in Todo mode."
6451 (when (= 1 (length todo-done-separator-string))
6452 (let ((sep todo-done-separator))
6453 (setq todo-done-separator (todo-done-separator))
6454 (save-match-data (todo-reset-done-separator sep)))))
6455
6456 (defun todo-modes-set-1 ()
6457 "Make some settings that apply to multiple Todo modes."
6458 (setq-local font-lock-defaults '(todo-font-lock-keywords t))
6459 (setq-local tab-width todo-indent-to-here)
6460 (setq-local indent-line-function 'todo-indent)
6461 (when todo-wrap-lines
6462 (visual-line-mode)
6463 (setq wrap-prefix (make-string todo-indent-to-here 32))))
6464
6465 (defun todo-modes-set-2 ()
6466 "Make some settings that apply to multiple Todo modes."
6467 (add-to-invisibility-spec 'todo)
6468 (setq buffer-read-only t)
6469 (when (boundp 'hl-line-range-function)
6470 (setq-local hl-line-range-function
6471 (lambda() (save-excursion
6472 (when (todo-item-end)
6473 (cons (todo-item-start)
6474 (todo-item-end))))))))
6475
6476 (defun todo-modes-set-3 ()
6477 "Make some settings that apply to multiple Todo modes."
6478 (setq-local todo-categories (todo-set-categories))
6479 (setq-local todo-category-number 1)
6480 (add-hook 'find-file-hook 'todo-display-as-todo-file nil t))
6481
6482 (put 'todo-mode 'mode-class 'special)
6483
6484 (define-derived-mode todo-mode special-mode "Todo"
6485 "Major mode for displaying, navigating and editing todo lists.
6486
6487 \\{todo-mode-map}"
6488 ;; (easy-menu-add todo-menu)
6489 (todo-modes-set-1)
6490 (todo-modes-set-2)
6491 (todo-modes-set-3)
6492 ;; Initialize todo-current-todo-file.
6493 (when (member (file-truename (buffer-file-name))
6494 (funcall todo-files-function))
6495 (setq-local todo-current-todo-file (file-truename (buffer-file-name))))
6496 (setq-local todo-show-done-only nil)
6497 (setq-local todo-categories-with-marks nil)
6498 (add-hook 'find-file-hook 'todo-add-to-buffer-list nil t)
6499 (add-hook 'post-command-hook 'todo-update-buffer-list nil t)
6500 (when todo-show-current-file
6501 (add-hook 'pre-command-hook 'todo-show-current-file nil t))
6502 (add-hook 'window-configuration-change-hook
6503 'todo-reset-and-enable-done-separator nil t)
6504 (add-hook 'kill-buffer-hook 'todo-reset-global-current-todo-file nil t))
6505
6506 (put 'todo-archive-mode 'mode-class 'special)
6507
6508 ;; If todo-mode is parent, all todo-mode key bindings appear to be
6509 ;; available in todo-archive-mode (e.g. shown by C-h m).
6510 (define-derived-mode todo-archive-mode special-mode "Todo-Arch"
6511 "Major mode for archived todo categories.
6512
6513 \\{todo-archive-mode-map}"
6514 (todo-modes-set-1)
6515 (todo-modes-set-2)
6516 (todo-modes-set-3)
6517 (setq-local todo-current-todo-file (file-truename (buffer-file-name)))
6518 (setq-local todo-show-done-only t))
6519
6520 (defun todo-mode-external-set ()
6521 "Set `todo-categories' externally to `todo-current-todo-file'."
6522 (setq-local todo-current-todo-file todo-global-current-todo-file)
6523 (let ((cats (with-current-buffer
6524 ;; Can't use find-buffer-visiting when
6525 ;; `todo-show-categories-table' is called on first
6526 ;; invocation of `todo-show', since there is then
6527 ;; no buffer visiting the current file.
6528 (find-file-noselect todo-current-todo-file 'nowarn)
6529 (or todo-categories
6530 ;; In Todo Edit mode todo-categories is now nil
6531 ;; since it uses same buffer as Todo mode but
6532 ;; doesn't have the latter's local variables.
6533 (save-excursion
6534 (goto-char (point-min))
6535 (read (buffer-substring-no-properties
6536 (line-beginning-position)
6537 (line-end-position))))))))
6538 (setq-local todo-categories cats)))
6539
6540 (define-derived-mode todo-edit-mode text-mode "Todo-Ed"
6541 "Major mode for editing multiline todo items.
6542
6543 \\{todo-edit-mode-map}"
6544 (todo-modes-set-1)
6545 (todo-mode-external-set)
6546 (setq buffer-read-only nil))
6547
6548 (put 'todo-categories-mode 'mode-class 'special)
6549
6550 (define-derived-mode todo-categories-mode special-mode "Todo-Cats"
6551 "Major mode for displaying and editing todo categories.
6552
6553 \\{todo-categories-mode-map}"
6554 (todo-mode-external-set))
6555
6556 (put 'todo-filtered-items-mode 'mode-class 'special)
6557
6558 (define-derived-mode todo-filtered-items-mode special-mode "Todo-Fltr"
6559 "Mode for displaying and reprioritizing top priority Todo.
6560
6561 \\{todo-filtered-items-mode-map}"
6562 (todo-modes-set-1)
6563 (todo-modes-set-2))
6564
6565 (add-to-list 'auto-mode-alist '("\\.todo\\'" . todo-mode))
6566 (add-to-list 'auto-mode-alist '("\\.toda\\'" . todo-archive-mode))
6567 (add-to-list 'auto-mode-alist '("\\.tod[tyr]\\'" . todo-filtered-items-mode))
6568
6569 ;; -----------------------------------------------------------------------------
6570 (provide 'todo-mode)
6571
6572 ;;; todo-mode.el ends here