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