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