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