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