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