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