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