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