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