]> code.delx.au - gnu-emacs/blob - lisp/calendar/todos.el
* calendar/todos.el: Further comment revision.
[gnu-emacs] / lisp / calendar / todos.el
1 ;;; Todos.el --- facilities for making and maintaining Todo lists
2
3 ;; Copyright (C) 1997, 1999, 2001-2012 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 ;; Created: 2 Aug 1997
9 ;; Keywords: calendar, todo
10
11 ;; This file is [not yet] part of GNU Emacs.
12
13 ;; GNU Emacs is free software: you can redistribute it and/or modify
14 ;; it under the terms of the GNU General Public License as published by
15 ;; the Free Software Foundation, either version 3 of the License, or
16 ;; (at your option) any later version.
17
18 ;; GNU Emacs is distributed in the hope that it will be useful,
19 ;; but WITHOUT ANY WARRANTY; without even the implied warranty of
20 ;; MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
21 ;; GNU General Public License for more details.
22
23 ;; You should have received a copy of the GNU General Public License
24 ;; along with GNU Emacs. If not, see <http://www.gnu.org/licenses/>.
25
26 ;;; Commentary:
27
28 ;;; Code:
29
30 (require 'diary-lib)
31 ;; For remove-duplicates in todos-insertion-commands-args.
32 (eval-when-compile (require 'cl))
33
34 ;; ---------------------------------------------------------------------------
35 ;;; User options
36
37 (defgroup todos nil
38 "Create and maintain categorized lists of todo items."
39 :link '(emacs-commentary-link "todos")
40 :version "24.2"
41 :group 'calendar)
42
43 (defcustom todos-files-directory (locate-user-emacs-file "todos/")
44 "Directory where user's Todos files are saved."
45 :type 'directory
46 :group 'todos)
47
48 (defun todos-files (&optional archives)
49 "Default value of `todos-files-function'.
50 This returns the case-insensitive alphabetically sorted list of
51 file truenames in `todos-files-directory' with the extension
52 \".todo\". With non-nil ARCHIVES return the list of archive file
53 truenames (those with the extension \".toda\")."
54 (let ((files (if (file-exists-p todos-files-directory)
55 (mapcar 'file-truename
56 (directory-files todos-files-directory t
57 (if archives "\.toda$" "\.todo$") t)))))
58 (sort files (lambda (s1 s2) (let ((cis1 (upcase s1))
59 (cis2 (upcase s2)))
60 (string< cis1 cis2))))))
61
62 (defcustom todos-files-function 'todos-files
63 "Function returning the value of the variable `todos-files'.
64 This function should take an optional argument that, if non-nil,
65 makes it return the value of the variable `todos-archives'."
66 :type 'function
67 :group 'todos)
68
69 (defun todos-short-file-name (file)
70 "Return short form of Todos FILE.
71 This lacks the extension and directory components."
72 (file-name-sans-extension (file-name-nondirectory file)))
73
74 (defcustom todos-default-todos-file (car (funcall todos-files-function))
75 "Todos file visited by first session invocation of `todos-show'."
76 :type `(radio ,@(mapcar (lambda (f) (list 'const f))
77 (mapcar 'todos-short-file-name
78 (funcall todos-files-function))))
79 :group 'todos)
80
81 ;; FIXME: is there a better alternative to this?
82 (defun todos-reevaluate-default-file-defcustom ()
83 "Reevaluate defcustom of `todos-default-todos-file'.
84 Called after adding or deleting a Todos file."
85 (eval (defcustom todos-default-todos-file (car (funcall todos-files-function))
86 "Todos file visited by first session invocation of `todos-show'."
87 :type `(radio ,@(mapcar (lambda (f) (list 'const f))
88 (mapcar 'todos-short-file-name
89 (funcall todos-files-function))))
90 :group 'todos)))
91
92 (defcustom todos-show-current-file t
93 "Non-nil to make `todos-show' visit the current Todos file.
94 Otherwise, `todos-show' always visits `todos-default-todos-file'."
95 :type 'boolean
96 :initialize 'custom-initialize-default
97 :set 'todos-set-show-current-file
98 :group 'todos)
99
100 (defun todos-set-show-current-file (symbol value)
101 "The :set function for user option `todos-show-current-file'."
102 (custom-set-default symbol value)
103 (if value
104 (add-hook 'pre-command-hook 'todos-show-current-file nil t)
105 (remove-hook 'pre-command-hook 'todos-show-current-file t)))
106
107 (defcustom todos-visit-files-commands (list 'find-file 'dired-find-file)
108 "List of file finding commands for `todos-display-as-todos-file'.
109 Invoking these commands to visit a Todos or Todos Archive file
110 calls `todos-show' or `todos-show-archive', so that the file is
111 displayed correctly."
112 :type '(repeat function)
113 :group 'todos)
114
115 (defcustom todos-initial-file "Todo"
116 "Default file name offered on adding first Todos file."
117 :type 'string
118 :group 'todos)
119
120 (defcustom todos-initial-category "Todo"
121 "Default category name offered on initializing a new Todos file."
122 :type 'string
123 :group 'todos)
124
125 (defcustom todos-display-categories-first nil
126 "Non-nil to display category list on first visit to a Todos file."
127 :type 'boolean
128 :group 'todos)
129
130 (defcustom todos-prefix ""
131 "String prefixed to todo items for visual distinction."
132 :type 'string
133 :initialize 'custom-initialize-default
134 :set 'todos-reset-prefix
135 :group 'todos)
136
137 (defcustom todos-number-priorities t
138 "Non-nil to prefix items with consecutively increasing integers.
139 These reflect the priorities of the items in each category."
140 :type 'boolean
141 :initialize 'custom-initialize-default
142 :set 'todos-reset-prefix
143 :group 'todos)
144
145 (defun todos-reset-prefix (symbol value)
146 "The :set function for `todos-prefix' and `todos-number-priorities'."
147 (let ((oldvalue (symbol-value symbol))
148 (files (append todos-files todos-archives)))
149 (custom-set-default symbol value)
150 (when (not (equal value oldvalue))
151 (dolist (f files)
152 (with-current-buffer (find-file-noselect f)
153 (save-window-excursion
154 (todos-show)
155 (save-excursion
156 (widen)
157 (goto-char (point-min))
158 (while (not (eobp))
159 (remove-overlays (point) (point)); 'before-string prefix)
160 (forward-line)))
161 ;; Activate the new setting (save-restriction does not help).
162 (save-excursion (todos-category-select))))))))
163
164 (defcustom todos-done-separator-string "_"
165 "String for generating `todos-done-separator'.
166
167 If the string consists of a single character,
168 `todos-done-separator' will be the string made by repeating this
169 character for the width of the window, and the length is
170 automatically recalculated when the window width changes. If the
171 string consists of more (or less) than one character, it will be
172 the value of `todos-done-separator'."
173 :type 'string
174 :initialize 'custom-initialize-default
175 :set 'todos-reset-done-separator-string
176 :group 'todos)
177
178 (defun todos-reset-done-separator-string (symbol value)
179 "The :set function for `todos-done-separator-string'."
180 (let ((oldvalue (symbol-value symbol))
181 (files todos-file-buffers)
182 (sep todos-done-separator))
183 (custom-set-default symbol value)
184 (setq todos-done-separator (todos-done-separator))
185 (when (= 1 (length value))
186 (todos-reset-done-separator sep))))
187
188 (defcustom todos-done-string "DONE "
189 "Identifying string appended to the front of done todos items."
190 :type 'string
191 :initialize 'custom-initialize-default
192 :set 'todos-reset-done-string
193 :group 'todos)
194
195 (defun todos-reset-done-string (symbol value)
196 "The :set function for user option `todos-done-string'."
197 (let ((oldvalue (symbol-value symbol))
198 (files (append todos-files todos-archives)))
199 (custom-set-default symbol value)
200 ;; Need to reset this to get font-locking right.
201 (setq todos-done-string-start
202 (concat "^\\[" (regexp-quote todos-done-string)))
203 (when (not (equal value oldvalue))
204 (dolist (f files)
205 (with-current-buffer (find-file-noselect f)
206 (let (buffer-read-only)
207 (widen)
208 (goto-char (point-min))
209 (while (not (eobp))
210 (if (re-search-forward
211 (concat "^" (regexp-quote todos-nondiary-start)
212 "\\(" (regexp-quote oldvalue) "\\)")
213 nil t)
214 (replace-match value t t nil 1)
215 (forward-line)))
216 (todos-category-select)))))))
217
218 (defcustom todos-comment-string "COMMENT"
219 "String inserted before optional comment appended to done item."
220 :type 'string
221 :initialize 'custom-initialize-default
222 :set 'todos-reset-comment-string
223 :group 'todos)
224
225 (defun todos-reset-comment-string (symbol value)
226 "The :set function for user option `todos-comment-string'."
227 (let ((oldvalue (symbol-value symbol))
228 (files (append todos-files todos-archives)))
229 (custom-set-default symbol value)
230 (when (not (equal value oldvalue))
231 (dolist (f files)
232 (with-current-buffer (find-file-noselect f)
233 (let (buffer-read-only)
234 (save-excursion
235 (widen)
236 (goto-char (point-min))
237 (while (not (eobp))
238 (if (re-search-forward
239 (concat
240 "\\[\\(" (regexp-quote oldvalue) "\\): [^]]*\\]")
241 nil t)
242 (replace-match value t t nil 1)
243 (forward-line)))
244 (todos-category-select))))))))
245
246 (defcustom todos-show-with-done nil
247 "Non-nil to display done items in all categories."
248 :type 'boolean
249 :group 'todos)
250
251 (defun todos-mode-line-control (cat)
252 "Return a mode line control for Todos buffers.
253 Argument CAT is the name of the current Todos category.
254 This function is the value of the user variable
255 `todos-mode-line-function'."
256 (let ((file (todos-short-file-name todos-current-todos-file)))
257 (format "%s category %d: %s" file todos-category-number cat)))
258
259 (defcustom todos-mode-line-function 'todos-mode-line-control
260 "Function that returns a mode line control for Todos buffers.
261 The function expects one argument holding the name of the current
262 Todos category. The resulting control becomes the local value of
263 `mode-line-buffer-identification' in each Todos buffer."
264 :type 'function
265 :group 'todos)
266
267 (defcustom todos-skip-archived-categories nil
268 "Non-nil to skip categories with only archived items when browsing.
269
270 Moving by category todos or archive file (with
271 \\[todos-forward-category] and \\[todos-backward-category]) skips
272 categories that contain only archived items. Other commands
273 still recognize these categories. In Todos Categories
274 mode (reached with \\[todos-display-categories]) these categories
275 shown in `todos-archived-only' face and clicking them in Todos
276 Categories mode visits the archived categories."
277 :type 'boolean
278 :group 'todos)
279
280 (defcustom todos-use-only-highlighted-region t
281 "Non-nil to enable inserting only highlighted region as new item."
282 :type 'boolean
283 :group 'todos)
284
285 (defcustom todos-include-in-diary nil
286 "Non-nil to allow new Todo items to be included in the diary."
287 :type 'boolean
288 :group 'todos)
289
290 (defcustom todos-diary-nonmarking nil
291 "Non-nil to insert new Todo diary items as nonmarking by default.
292 This appends `diary-nonmarking-symbol' to the front of an item on
293 insertion provided it doesn't begin with `todos-nondiary-marker'."
294 :type 'boolean
295 :group 'todos)
296
297 (defcustom todos-nondiary-marker '("[" "]")
298 "List of strings surrounding item date to block diary inclusion.
299 The first string is inserted before the item date and must be a
300 non-empty string that does not match a diary date in order to
301 have its intended effect. The second string is inserted after
302 the diary date."
303 :type '(list string string)
304 :group 'todos
305 :initialize 'custom-initialize-default
306 :set 'todos-reset-nondiary-marker)
307
308 (defun todos-reset-nondiary-marker (symbol value)
309 "The :set function for user option `todos-nondiary-marker'."
310 (let ((oldvalue (symbol-value symbol))
311 (files (append todos-files todos-archives)))
312 (custom-set-default symbol value)
313 ;; Need to reset these to get font-locking right.
314 (setq todos-nondiary-start (nth 0 todos-nondiary-marker)
315 todos-nondiary-end (nth 1 todos-nondiary-marker)
316 todos-date-string-start
317 ;; See comment in defvar of `todos-date-string-start'.
318 (concat "^\\(" (regexp-quote todos-nondiary-start) "\\|"
319 (regexp-quote diary-nonmarking-symbol) "\\)?"))
320 (when (not (equal value oldvalue))
321 (dolist (f files)
322 (with-current-buffer (find-file-noselect f)
323 (let (buffer-read-only)
324 (widen)
325 (goto-char (point-min))
326 (while (not (eobp))
327 (if (re-search-forward
328 (concat "^\\(" todos-done-string-start "[^][]+] \\)?"
329 "\\(?1:" (regexp-quote (car oldvalue))
330 "\\)" todos-date-pattern "\\( "
331 diary-time-regexp "\\)?\\(?2:"
332 (regexp-quote (cadr oldvalue)) "\\)")
333 nil t)
334 (progn
335 (replace-match (nth 0 value) t t nil 1)
336 (replace-match (nth 1 value) t t nil 2))
337 (forward-line)))
338 (todos-category-select)))))))
339
340 (defcustom todos-always-add-time-string nil
341 "Non-nil adds current time to a new item's date header by default.
342 When the Todos insertion commands have a non-nil \"maybe-notime\"
343 argument, this reverses the effect of
344 `todos-always-add-time-string': if t, these commands omit the
345 current time, if nil, they include it."
346 :type 'boolean
347 :group 'todos)
348
349 (defcustom todos-completion-ignore-case nil
350 "Non-nil means case of user input in `todos-read-*' is ignored."
351 :type 'boolean
352 :group 'todos)
353
354 (defcustom todos-highlight-item nil
355 "Non-nil means highlight items at point."
356 :type 'boolean
357 :initialize 'custom-initialize-default
358 :set 'todos-reset-highlight-item
359 :group 'todos)
360
361 (defun todos-reset-highlight-item (symbol value)
362 "The :set function for `todos-highlight-item'."
363 (let ((oldvalue (symbol-value symbol))
364 (files (append todos-files todos-archives)))
365 (custom-set-default symbol value)
366 (when (not (equal value oldvalue))
367 (dolist (f files)
368 (let ((buf (find-buffer-visiting f)))
369 (when buf
370 (with-current-buffer buf
371 (require 'hl-line)
372 (if value
373 (hl-line-mode 1)
374 (hl-line-mode -1)))))))))
375
376 (defcustom todos-wrap-lines t
377 "Non-nil to wrap long lines via `todos-line-wrapping-function'."
378 :group 'todos
379 :type 'boolean)
380
381 (defcustom todos-line-wrapping-function 'todos-wrap-and-indent
382 "Line wrapping function used with non-nil `todos-wrap-lines'."
383 :group 'todos
384 :type 'function)
385
386 (defun todos-wrap-and-indent ()
387 "Use word wrapping on long lines and indent with a wrap prefix.
388 The amount of indentation is given by user option
389 `todos-indent-to-here'."
390 (set (make-local-variable 'word-wrap) t)
391 (set (make-local-variable 'wrap-prefix) (make-string todos-indent-to-here 32))
392 (unless (member '(continuation) fringe-indicator-alist)
393 (push '(continuation) fringe-indicator-alist)))
394
395 ;; FIXME: :set function to refill items with hard newlines and to immediately
396 ;; update wrapped prefix display
397 (defcustom todos-indent-to-here 6
398 "Number of spaces `todos-line-wrapping-function' indents to."
399 :type '(integer :validate
400 (lambda (widget)
401 (unless (> (widget-value widget) 0)
402 (widget-put widget :error
403 "Invalid value: must be a positive integer")
404 widget)))
405 :group 'todos)
406
407 (defun todos-indent ()
408 "Indent from point to `todos-indent-to-here'."
409 (indent-to todos-indent-to-here todos-indent-to-here))
410
411 (defcustom todos-todo-mode-date-time-regexp
412 (concat "\\(?1:[0-9]\\{4\\}\\)-\\(?2:[0-9]\\{2\\}\\)-"
413 "\\(?3:[0-9]\\{2\\}\\) \\(?4:[0-9]\\{2\\}:[0-9]\\{2\\}\\)")
414 "Regexp matching legacy todo-mode.el item date-time strings.
415 In order for `todos-convert-legacy-files' to correctly convert this
416 string to the current Todos format, the regexp must contain four
417 explicitly numbered groups (see `(elisp) Regexp Backslash'),
418 where group 1 matches a string for the year, group 2 a string for
419 the month, group 3 a string for the day and group 4 a string for
420 the time. The default value converts date-time strings built
421 using the default value of `todo-time-string-format' from
422 todo-mode.el."
423 :type 'regexp
424 :group 'todos)
425
426 (defcustom todos-print-function 'ps-print-buffer-with-faces
427 "Function called to print buffer content; see `todos-print'."
428 :type 'symbol
429 :group 'todos)
430
431 (defgroup todos-filtered nil
432 "User options for Todos Filter Items mode."
433 :version "24.2"
434 :group 'todos)
435
436 (defcustom todos-filtered-items-buffer "Todos filtered items"
437 "Initial name of buffer in Todos Filter Items mode."
438 :type 'string
439 :group 'todos-filtered)
440
441 (defcustom todos-top-priorities-buffer "Todos top priorities"
442 "Buffer type string for `todos-filtered-buffer-name'."
443 :type 'string
444 :group 'todos-filtered)
445
446 (defcustom todos-diary-items-buffer "Todos diary items"
447 "Buffer type string for `todos-filtered-buffer-name'."
448 :type 'string
449 :group 'todos-filtered)
450
451 (defcustom todos-regexp-items-buffer "Todos regexp items"
452 "Buffer type string for `todos-filtered-buffer-name'."
453 :type 'string
454 :group 'todos-filtered)
455
456 (defcustom todos-priorities-rules nil
457 "List of rules giving how many items `todos-top-priorities' shows.
458 This variable should be set interactively by
459 `\\[todos-set-top-priorities-in-file]' or
460 `\\[todos-set-top-priorities-in-category]'.
461
462 Each rule is a list of the form (FILE NUM ALIST), where FILE is a
463 member of `todos-files', NUM is a number specifying the default
464 number of top priority items for each category in that file, and
465 ALIST, when non-nil, consists of conses of a category name in
466 FILE and a number specifying the default number of top priority
467 items in that category, which overrides NUM."
468 :type 'list
469 :group 'todos-filtered)
470
471 (defcustom todos-show-priorities 1
472 "Default number of top priorities shown by `todos-top-priorities'."
473 :type 'integer
474 :group 'todos-filtered)
475
476 (defcustom todos-filter-files nil
477 "List of default files for multifile item filtering."
478 :type `(set ,@(mapcar (lambda (f) (list 'const f))
479 (mapcar 'todos-short-file-name
480 (funcall todos-files-function))))
481 :group 'todos-filtered)
482
483 ;; FIXME: is there a better alternative to this?
484 (defun todos-reevaluate-filter-files-defcustom ()
485 "Reevaluate defcustom of `todos-filter-files'.
486 Called after adding or deleting a Todos file."
487 (eval (defcustom todos-filter-files nil
488 "List of files for multifile item filtering."
489 :type `(set ,@(mapcar (lambda (f) (list 'const f))
490 (mapcar 'todos-short-file-name
491 (funcall todos-files-function))))
492 :group 'todos)))
493
494 (defcustom todos-filter-done-items nil
495 "Non-nil to include done items when processing regexp filters.
496 Done items from corresponding archive files are also included."
497 :type 'boolean
498 :group 'todos-filtered)
499
500 (defgroup todos-categories nil
501 "User options for Todos Categories mode."
502 :version "24.2"
503 :group 'todos)
504
505 (defcustom todos-categories-category-label "Category"
506 "Category button label in Todos Categories mode."
507 :type 'string
508 :group 'todos-categories)
509
510 (defcustom todos-categories-todo-label "Todo"
511 "Todo button label in Todos Categories mode."
512 :type 'string
513 :group 'todos-categories)
514
515 (defcustom todos-categories-diary-label "Diary"
516 "Diary button label in Todos Categories mode."
517 :type 'string
518 :group 'todos-categories)
519
520 (defcustom todos-categories-done-label "Done"
521 "Done button label in Todos Categories mode."
522 :type 'string
523 :group 'todos-categories)
524
525 (defcustom todos-categories-archived-label "Archived"
526 "Archived button label in Todos Categories mode."
527 :type 'string
528 :group 'todos-categories)
529
530 (defcustom todos-categories-totals-label "Totals"
531 "String to label total item counts in Todos Categories mode."
532 :type 'string
533 :group 'todos-categories)
534
535 (defcustom todos-categories-number-separator " | "
536 "String between number and category in Todos Categories mode.
537 This separates the number from the category name in the default
538 categories display according to priority."
539 :type 'string
540 :group 'todos-categories)
541
542 (defcustom todos-categories-align 'center
543 "Alignment of category names in Todos Categories mode."
544 :type '(radio (const left) (const center) (const right))
545 :group 'todos-categories)
546
547 ;; ---------------------------------------------------------------------------
548 ;;; Faces and font-locking
549
550 (defgroup todos-faces nil
551 "Faces for the Todos modes."
552 :version "24.2"
553 :group 'todos)
554
555 (defface todos-prefix-string
556 ;; '((t :inherit font-lock-constant-face))
557 '((((class grayscale) (background light))
558 (:foreground "LightGray" :weight bold :underline t))
559 (((class grayscale) (background dark))
560 (:foreground "Gray50" :weight bold :underline t))
561 (((class color) (min-colors 88) (background light)) (:foreground "dark cyan"))
562 (((class color) (min-colors 88) (background dark)) (:foreground "Aquamarine"))
563 (((class color) (min-colors 16) (background light)) (:foreground "CadetBlue"))
564 (((class color) (min-colors 16) (background dark)) (:foreground "Aquamarine"))
565 (((class color) (min-colors 8)) (:foreground "magenta"))
566 (t (:weight bold :underline t)))
567 "Face for Todos prefix string."
568 :group 'todos-faces)
569
570 (defface todos-mark
571 ;; '((t :inherit font-lock-warning-face))
572 '((((class color)
573 (min-colors 88)
574 (background light))
575 (:weight bold :foreground "Red1"))
576 (((class color)
577 (min-colors 88)
578 (background dark))
579 (:weight bold :foreground "Pink"))
580 (((class color)
581 (min-colors 16)
582 (background light))
583 (:weight bold :foreground "Red1"))
584 (((class color)
585 (min-colors 16)
586 (background dark))
587 (:weight bold :foreground "Pink"))
588 (((class color)
589 (min-colors 8))
590 (:foreground "red"))
591 (t
592 (:weight bold :inverse-video t)))
593 "Face for marks on Todos items."
594 :group 'todos-faces)
595
596 (defface todos-button
597 ;; '((t :inherit widget-field))
598 '((((type tty))
599 (:foreground "black" :background "yellow3"))
600 (((class grayscale color)
601 (background light))
602 (:background "gray85"))
603 (((class grayscale color)
604 (background dark))
605 (:background "dim gray"))
606 (t
607 (:slant italic)))
608 "Face for buttons in todos-display-categories."
609 :group 'todos-faces)
610
611 (defface todos-sorted-column
612 '((((type tty))
613 (:inverse-video t))
614 (((class color)
615 (background light))
616 (:background "grey85"))
617 (((class color)
618 (background dark))
619 (:background "grey85" :foreground "grey10"))
620 (t
621 (:background "gray")))
622 "Face for buttons in todos-display-categories."
623 :group 'todos-faces)
624
625 (defface todos-archived-only
626 ;; '((t (:inherit (shadow))))
627 '((((class color)
628 (background light))
629 (:foreground "grey50"))
630 (((class color)
631 (background dark))
632 (:foreground "grey70"))
633 (t
634 (:foreground "gray")))
635 "Face for archived-only categories in todos-display-categories."
636 :group 'todos-faces)
637
638 (defface todos-search
639 ;; '((t :inherit match))
640 '((((class color)
641 (min-colors 88)
642 (background light))
643 (:background "yellow1"))
644 (((class color)
645 (min-colors 88)
646 (background dark))
647 (:background "RoyalBlue3"))
648 (((class color)
649 (min-colors 8)
650 (background light))
651 (:foreground "black" :background "yellow"))
652 (((class color)
653 (min-colors 8)
654 (background dark))
655 (:foreground "white" :background "blue"))
656 (((type tty)
657 (class mono))
658 (:inverse-video t))
659 (t
660 (:background "gray")))
661 "Face for matches found by todos-search."
662 :group 'todos-faces)
663
664 (defface todos-diary-expired
665 ;; '((t :inherit font-lock-warning-face))
666 '((((class color)
667 (min-colors 16))
668 (:weight bold :foreground "DarkOrange"))
669 (((class color))
670 (:weight bold :foreground "yellow"))
671 (t
672 (:weight bold)))
673 "Face for expired dates of diary items."
674 :group 'todos-faces)
675 (defvar todos-diary-expired-face 'todos-diary-expired)
676
677 (defface todos-date
678 '((t :inherit diary))
679 "Face for the date string of a Todos item."
680 :group 'todos-faces)
681 (defvar todos-date-face 'todos-date)
682
683 (defface todos-time
684 '((t :inherit diary-time))
685 "Face for the time string of a Todos item."
686 :group 'todos-faces)
687 (defvar todos-time-face 'todos-time)
688
689 (defface todos-done
690 ;; '((t :inherit font-lock-comment-face))
691 '((((class grayscale)
692 (background light))
693 (:slant italic :weight bold :foreground "DimGray"))
694 (((class grayscale)
695 (background dark))
696 (:slant italic :weight bold :foreground "LightGray"))
697 (((class color)
698 (min-colors 88)
699 (background light))
700 (:foreground "Firebrick"))
701 (((class color)
702 (min-colors 88)
703 (background dark))
704 (:foreground "chocolate1"))
705 (((class color)
706 (min-colors 16)
707 (background light))
708 (:foreground "red"))
709 (((class color)
710 (min-colors 16)
711 (background dark))
712 (:foreground "red1"))
713 (((class color)
714 (min-colors 8)
715 (background light))
716 (:foreground "red"))
717 (((class color)
718 (min-colors 8)
719 (background dark))
720 (:foreground "yellow"))
721 (t
722 (:slant italic :weight bold)))
723 "Face for done Todos item header string."
724 :group 'todos-faces)
725 (defvar todos-done-face 'todos-done)
726
727 (defface todos-comment
728 '((t :inherit todos-done))
729 "Face for comments appended to done Todos items."
730 :group 'todos-faces)
731 (defvar todos-comment-face 'todos-comment)
732
733 (defface todos-done-sep
734 ;; '((t :inherit font-lock-type-face))
735 '((((class grayscale)
736 (background light))
737 (:weight bold :foreground "Gray90"))
738 (((class grayscale)
739 (background dark))
740 (:weight bold :foreground "DimGray"))
741 (((class color)
742 (min-colors 88)
743 (background light))
744 (:foreground "ForestGreen"))
745 (((class color)
746 (min-colors 88)
747 (background dark))
748 (:foreground "PaleGreen"))
749 (((class color)
750 (min-colors 16)
751 (background light))
752 (:foreground "ForestGreen"))
753 (((class color)
754 (min-colors 16)
755 (background dark))
756 (:foreground "PaleGreen"))
757 (((class color)
758 (min-colors 8))
759 (:foreground "green"))
760 (t
761 (:underline t :weight bold)))
762 "Face for separator string bewteen done and not done Todos items."
763 :group 'todos-faces)
764 (defvar todos-done-sep-face 'todos-done-sep)
765
766 (defun todos-date-string-matcher (lim)
767 "Search for Todos date string within LIM for font-locking."
768 (re-search-forward
769 (concat todos-date-string-start "\\(?1:" todos-date-pattern "\\)") lim t))
770
771 (defun todos-time-string-matcher (lim)
772 "Search for Todos time string within LIM for font-locking."
773 (re-search-forward (concat todos-date-string-start todos-date-pattern
774 " \\(?1:" diary-time-regexp "\\)") lim t))
775
776 (defun todos-nondiary-marker-matcher (lim)
777 "Search for Todos nondiary markers within LIM for font-locking."
778 (re-search-forward (concat "^\\(?1:" (regexp-quote todos-nondiary-start) "\\)"
779 todos-date-pattern "\\(?: " diary-time-regexp
780 "\\)?\\(?2:" (regexp-quote todos-nondiary-end) "\\)")
781 lim t))
782
783 (defun todos-diary-nonmarking-matcher (lim)
784 "Search for diary nonmarking symbol within LIM for font-locking."
785 (re-search-forward (concat "^\\(?1:" (regexp-quote diary-nonmarking-symbol)
786 "\\)" todos-date-pattern) lim t))
787
788 (defun todos-diary-expired-matcher (lim)
789 "Search for expired diary item date within LIM for font-locking."
790 (when (re-search-forward (concat "^\\(?:"
791 (regexp-quote diary-nonmarking-symbol)
792 "\\)?\\(?1:" todos-date-pattern "\\) \\(?2:"
793 diary-time-regexp "\\)?") lim t)
794 (let* ((date (match-string-no-properties 1))
795 (time (match-string-no-properties 2))
796 ;; Function days-between requires a non-empty time string.
797 (date-time (concat date " " (or time "00:00"))))
798 (or (and (not (string-match ".+day\\|\\*" date))
799 (< (days-between date-time (current-time-string)) 0))
800 (todos-diary-expired-matcher lim)))))
801
802 (defun todos-done-string-matcher (lim)
803 "Search for Todos done header within LIM for font-locking."
804 (re-search-forward (concat todos-done-string-start
805 "[^][]+]")
806 lim t))
807
808 (defun todos-comment-string-matcher (lim)
809 "Search for Todos done comment within LIM for font-locking."
810 (re-search-forward (concat "\\[\\(?1:" todos-comment-string "\\):")
811 lim t))
812
813 ;; (defun todos-category-string-matcher (lim)
814 ;; "Search for Todos category name within LIM for font-locking.
815 ;; This is for fontifying category names appearing in Todos filter
816 ;; mode."
817 ;; (if (eq major-mode 'todos-filtered-items-mode)
818 ;; (re-search-forward
819 ;; (concat "^\\(?:" todos-date-string-start "\\)?" todos-date-pattern
820 ;; "\\(?: " diary-time-regexp "\\)?\\(?:"
821 ;; (regexp-quote todos-nondiary-end) "\\)? \\(?1:\\[.+\\]\\)")
822 ;; lim t)))
823
824 (defun todos-category-string-matcher-1 (lim)
825 "Search for Todos category name within LIM for font-locking.
826 This is for fontifying category names appearing in Todos filter
827 mode following done items."
828 (if (eq major-mode 'todos-filtered-items-mode)
829 (re-search-forward (concat todos-done-string-start todos-date-pattern
830 "\\(?: " diary-time-regexp
831 ;; Use non-greedy operator to prevent
832 ;; capturing possible following non-diary
833 ;; date string.
834 "\\)?] \\(?1:\\[.+?\\]\\)")
835 lim t)))
836
837 (defun todos-category-string-matcher-2 (lim)
838 "Search for Todos category name within LIM for font-locking.
839 This is for fontifying category names appearing in Todos filter
840 mode following todo (not done) items."
841 (if (eq major-mode 'todos-filtered-items-mode)
842 (re-search-forward (concat todos-date-string-start todos-date-pattern
843 "\\(?: " diary-time-regexp "\\)?\\(?:"
844 (regexp-quote todos-nondiary-end)
845 "\\)? \\(?1:\\[.+\\]\\)")
846 lim t)))
847
848 (defvar todos-font-lock-keywords
849 (list
850 '(todos-nondiary-marker-matcher 1 todos-done-sep-face t)
851 '(todos-nondiary-marker-matcher 2 todos-done-sep-face t)
852 ;; This is the face used by diary-lib.el.
853 '(todos-diary-nonmarking-matcher 1 font-lock-constant-face t)
854 '(todos-date-string-matcher 1 todos-date-face t)
855 '(todos-time-string-matcher 1 todos-time-face t)
856 '(todos-done-string-matcher 0 todos-done-face t)
857 '(todos-comment-string-matcher 1 todos-done-face t)
858 ;; '(todos-category-string-matcher 1 todos-done-sep-face t)
859 '(todos-category-string-matcher-1 1 todos-done-sep-face t t)
860 '(todos-category-string-matcher-2 1 todos-done-sep-face t t)
861 '(todos-diary-expired-matcher 1 todos-diary-expired-face t)
862 '(todos-diary-expired-matcher 2 todos-diary-expired-face t t)
863 )
864 "Font-locking for Todos modes.")
865
866 ;; ---------------------------------------------------------------------------
867 ;;; Todos mode local variables and hook functions
868
869 (defvar todos-current-todos-file nil
870 "Variable holding the name of the currently active Todos file.")
871
872 (defun todos-show-current-file ()
873 "Visit current instead of default Todos file with `todos-show'.
874 This function is added to `pre-command-hook' when user option
875 `todos-show-current-file' is set to non-nil."
876 (setq todos-global-current-todos-file todos-current-todos-file))
877
878 (defun todos-display-as-todos-file ()
879 "Show Todos files correctly when visited from outside of Todos mode."
880 (and (member this-command todos-visit-files-commands)
881 (= (- (point-max) (point-min)) (buffer-size))
882 (member major-mode '(todos-mode todos-archive-mode))
883 (todos-category-select)))
884
885 (defun todos-add-to-buffer-list ()
886 "Add name of just visited Todos file to `todos-file-buffers'.
887 This function is added to `find-file-hook' in Todos mode."
888 (let ((filename (file-truename (buffer-file-name))))
889 (when (member filename todos-files)
890 (add-to-list 'todos-file-buffers filename))))
891
892 (defun todos-update-buffer-list ()
893 "Make current Todos mode buffer file car of `todos-file-buffers'.
894 This function is added to `post-command-hook' in Todos mode."
895 (let ((filename (file-truename (buffer-file-name))))
896 (unless (eq (car todos-file-buffers) filename)
897 (setq todos-file-buffers
898 (cons filename (delete filename todos-file-buffers))))))
899
900 (defun todos-reset-global-current-todos-file ()
901 "Update the value of `todos-global-current-todos-file'.
902 This becomes the latest existing Todos file or, if there is none,
903 the value of `todos-default-todos-file'.
904 This function is added to `kill-buffer-hook' in Todos mode."
905 (let ((filename (file-truename (buffer-file-name))))
906 (setq todos-file-buffers (delete filename todos-file-buffers))
907 (setq todos-global-current-todos-file (or (car todos-file-buffers)
908 todos-default-todos-file))))
909
910 (defvar todos-categories nil
911 "Alist of categories in the current Todos file.
912 The elements are cons cells whose car is a category name and
913 whose cdr is a vector of the category's item counts. These are,
914 in order, the numbers of todo items, of todo items included in
915 the Diary, of done items and of archived items.")
916
917 (defvar todos-categories-with-marks nil
918 "Alist of categories and number of marked items they contain.")
919
920 (defvar todos-category-number 1
921 "Variable holding the number of the current Todos category.
922 Todos categories are numbered starting from 1.")
923
924 (defvar todos-first-visit t
925 "Non-nil if first display of this file in the current session.
926 See `todos-display-categories-first'.")
927
928 (defvar todos-show-done-only nil
929 "If non-nil display only done items in current category.
930 Set by the command `todos-show-done-only' and used by
931 `todos-category-select'.")
932
933 ;; ---------------------------------------------------------------------------
934 ;;; Global variables and helper functions
935
936 (defvar todos-files (funcall todos-files-function)
937 "List of truenames of user's Todos files.")
938
939 (defvar todos-archives (funcall todos-files-function t)
940 "List of truenames of user's Todos archives.")
941
942 (defvar todos-file-buffers nil
943 "List of file names of live Todos mode buffers.")
944
945 (defvar todos-global-current-todos-file nil
946 "Variable holding name of current Todos file.
947 Used by functions called from outside of Todos mode to visit the
948 current Todos file rather than the default Todos file (i.e. when
949 users option `todos-show-current-file' is non-nil).")
950
951 (defun todos-reevaluate-defcustoms ()
952 "Reevaluate defcustoms that provide choice list of Todos files."
953 (custom-set-default 'todos-default-todos-file
954 (symbol-value 'todos-default-todos-file))
955 (todos-reevaluate-default-file-defcustom)
956 (custom-set-default 'todos-filter-files (symbol-value 'todos-filter-files))
957 (todos-reevaluate-filter-files-defcustom))
958
959 (defvar todos-edit-buffer "*Todos Edit*"
960 "Name of current buffer in Todos Edit mode.")
961
962 (defvar todos-categories-buffer "*Todos Categories*"
963 "Name of buffer in Todos Categories mode.")
964
965 (defvar todos-print-buffer "*Todos Print*"
966 "Name of buffer containing printable Todos text.")
967
968 (defvar todos-date-pattern
969 (let ((dayname (diary-name-pattern calendar-day-name-array nil t)))
970 (concat "\\(?:" dayname "\\|"
971 (let ((dayname)
972 ;; FIXME: how to choose between abbreviated and unabbreviated
973 ;; month name?
974 (monthname (format "\\(?:%s\\|\\*\\)"
975 (diary-name-pattern
976 calendar-month-name-array
977 calendar-month-abbrev-array t)))
978 (month "\\(?:[0-9]+\\|\\*\\)")
979 (day "\\(?:[0-9]+\\|\\*\\)")
980 (year "-?\\(?:[0-9]+\\|\\*\\)"))
981 (mapconcat 'eval calendar-date-display-form ""))
982 "\\)"))
983 "Regular expression matching a Todos date header.")
984
985 (defvar todos-nondiary-start (nth 0 todos-nondiary-marker)
986 "String inserted before item date to block diary inclusion.")
987
988 (defvar todos-nondiary-end (nth 1 todos-nondiary-marker)
989 "String inserted after item date matching `todos-nondiary-start'.")
990
991 ;; By itself this matches anything, because of the `?'; however, it's only
992 ;; used in the context of `todos-date-pattern' (but Emacs Lisp lacks
993 ;; lookahead).
994 (defvar todos-date-string-start
995 (concat "^\\(" (regexp-quote todos-nondiary-start) "\\|"
996 (regexp-quote diary-nonmarking-symbol) "\\)?")
997 "Regular expression matching part of item header before the date.")
998
999 (defvar todos-done-string-start
1000 (concat "^\\[" (regexp-quote todos-done-string))
1001 "Regular expression matching start of done item.")
1002
1003 (defun todos-category-number (cat)
1004 "Return the number of category CAT in this Todos file.
1005 The buffer-local variable `todos-category-number' holds this
1006 number as its value."
1007 (let ((categories (mapcar 'car todos-categories)))
1008 (setq todos-category-number
1009 ;; Increment by one, so that the highest priority category in Todos
1010 ;; Categories mode is numbered one rather than zero.
1011 (1+ (- (length categories)
1012 (length (member cat categories)))))))
1013
1014 (defun todos-current-category ()
1015 "Return the name of the current category."
1016 (car (nth (1- todos-category-number) todos-categories)))
1017
1018 (defconst todos-category-beg "--==-- "
1019 "String marking beginning of category (inserted with its name).")
1020
1021 (defconst todos-category-done "==--== DONE "
1022 "String marking beginning of category's done items.")
1023
1024 (defun todos-done-separator ()
1025 "Return string used as value of variable `todos-done-separator'."
1026 (let ((sep todos-done-separator-string))
1027 (if (= 1 (length sep))
1028 (make-string (window-width) (string-to-char sep))
1029 todos-done-separator-string)))
1030
1031 (defvar todos-done-separator (todos-done-separator)
1032 "String used to visually separate done from not done items.
1033 Displayed as an overlay instead of `todos-category-done' when
1034 done items are shown. Its value is determined by user option
1035 `todos-done-separator-string'.")
1036
1037 (defun todos-reset-done-separator (sep)
1038 "Replace any existing overlays of separator string SEP."
1039 (save-excursion
1040 (save-restriction
1041 (widen)
1042 (goto-char (point-min))
1043 (while (re-search-forward
1044 (concat "\n\\(" (regexp-quote todos-category-done) "\\)") nil t)
1045 (let* ((beg (match-beginning 1))
1046 (end (match-end 0))
1047 (ovs (overlays-at beg))
1048 old-sep new-sep)
1049 (and ovs
1050 (setq old-sep (overlay-get (car ovs) 'display))
1051 (string= old-sep sep)
1052 (delete-overlay (car ovs))
1053 (setq new-sep (make-overlay beg end))
1054 (overlay-put new-sep 'display
1055 todos-done-separator)))))))
1056
1057 (defun todos-reset-and-enable-done-separator ()
1058 "Hook function for activating new separator overlay.
1059 Added to `window-configuration-change-hook' in `todos-mode'."
1060 (when (= 1 (length todos-done-separator-string))
1061 (let ((sep todos-done-separator))
1062 (setq todos-done-separator (todos-done-separator))
1063 (save-match-data (todos-reset-done-separator sep)))
1064 ;; If the separator overlay is now shown, we have to hide and then show it
1065 ;; again in order to let the change in length take effect.
1066 ;; FIXME: But this breaks e.g. (widen) when edebugging. But how to
1067 ;; restrict it?
1068 ;; (save-excursion
1069 ;; (goto-char (point-min))
1070 ;; (when (re-search-forward todos-done-string-start nil t)
1071 ;; (let ((todos-show-with-done nil))
1072 ;; (todos-category-select))
1073 ;; (let ((todos-show-with-done t))
1074 ;; (todos-category-select))))
1075 ))
1076
1077 (defun todos-category-select ()
1078 "Display the current category correctly."
1079 (let ((name (todos-current-category))
1080 cat-begin cat-end done-start done-sep-start done-end)
1081 (widen)
1082 (goto-char (point-min))
1083 (re-search-forward
1084 (concat "^" (regexp-quote (concat todos-category-beg name)) "$") nil t)
1085 (setq cat-begin (1+ (line-end-position)))
1086 (setq cat-end (if (re-search-forward
1087 (concat "^" (regexp-quote todos-category-beg)) nil t)
1088 (match-beginning 0)
1089 (point-max)))
1090 (setq mode-line-buffer-identification
1091 (funcall todos-mode-line-function name))
1092 (narrow-to-region cat-begin cat-end)
1093 (todos-prefix-overlays)
1094 (goto-char (point-min))
1095 (if (re-search-forward (concat "\n\\(" (regexp-quote todos-category-done)
1096 "\\)") nil t)
1097 (progn
1098 (setq done-start (match-beginning 0))
1099 (setq done-sep-start (match-beginning 1))
1100 (setq done-end (match-end 0)))
1101 (error "Category %s is missing todos-category-done string" name))
1102 (if todos-show-done-only
1103 (narrow-to-region (1+ done-end) (point-max))
1104 (when (and todos-show-with-done
1105 (re-search-forward todos-done-string-start nil t))
1106 ;; Now we want to see the done items, so reset displayed end to end of
1107 ;; done items.
1108 (setq done-start cat-end)
1109 ;; Make display overlay for done items separator string, unless there
1110 ;; already is one.
1111 (let* ((done-sep todos-done-separator)
1112 (ovs (overlays-at done-sep-start))
1113 ov-sep)
1114 ;; There should never be more than one overlay here, so car suffices.
1115 (unless (and ovs (string= (overlay-get (car ovs) 'display) done-sep))
1116 (setq ov-sep (make-overlay done-sep-start done-end))
1117 (overlay-put ov-sep 'display done-sep))))
1118 (narrow-to-region (point-min) done-start)
1119 ;; Loading this from todos-mode, or adding it to the mode hook, causes
1120 ;; Emacs to hang in todos-item-start, at (looking-at todos-item-start).
1121 (when todos-highlight-item
1122 (require 'hl-line)
1123 (hl-line-mode 1)))))
1124
1125 (defun todos-get-count (type &optional category)
1126 "Return count of TYPE items in CATEGORY.
1127 If CATEGORY is nil, default to the current category."
1128 (let* ((cat (or category (todos-current-category)))
1129 (counts (cdr (assoc cat todos-categories)))
1130 (idx (cond ((eq type 'todo) 0)
1131 ((eq type 'diary) 1)
1132 ((eq type 'done) 2)
1133 ((eq type 'archived) 3))))
1134 (aref counts idx)))
1135
1136 (defun todos-update-count (type increment &optional category)
1137 "Change count of TYPE items in CATEGORY by integer INCREMENT.
1138 With nil or omitted CATEGORY, default to the current category."
1139 (let* ((cat (or category (todos-current-category)))
1140 (counts (cdr (assoc cat todos-categories)))
1141 (idx (cond ((eq type 'todo) 0)
1142 ((eq type 'diary) 1)
1143 ((eq type 'done) 2)
1144 ((eq type 'archived) 3))))
1145 (aset counts idx (+ increment (aref counts idx)))))
1146
1147 (defun todos-set-categories ()
1148 "Set `todos-categories' from the sexp at the top of the file."
1149 ;; New archive files created by `todos-move-category' are empty, which would
1150 ;; make the sexp test fail and raise an error, so in this case we skip it.
1151 (unless (zerop (buffer-size))
1152 (save-excursion
1153 (save-restriction
1154 (widen)
1155 (goto-char (point-min))
1156 (setq todos-categories
1157 (if (looking-at "\(\(\"")
1158 (read (buffer-substring-no-properties
1159 (line-beginning-position)
1160 (line-end-position)))
1161 (error "Invalid or missing todos-categories sexp")))))))
1162
1163 (defun todos-update-categories-sexp ()
1164 "Update the `todos-categories' sexp at the top of the file."
1165 (let (buffer-read-only)
1166 (save-excursion
1167 (save-restriction
1168 (widen)
1169 (goto-char (point-min))
1170 (if (looking-at (concat "^" (regexp-quote todos-category-beg)))
1171 (progn (newline) (goto-char (point-min)) ; Make space for sexp.
1172 ;; No categories sexp means the first item was just added
1173 ;; to this file, so have to initialize Todos file and
1174 ;; categories variables in order e.g. to enable categories
1175 ;; display.
1176 (setq todos-default-todos-file (buffer-file-name))
1177 (setq todos-categories (todos-make-categories-list t)))
1178 ;; With empty buffer (e.g. with new archive in
1179 ;; `todos-move-category') `kill-line' signals end of buffer.
1180 (kill-region (line-beginning-position) (line-end-position)))
1181 (prin1 todos-categories (current-buffer))))))
1182
1183 (defun todos-make-categories-list (&optional force)
1184 "Return an alist of Todos categories and their item counts.
1185 With non-nil argument FORCE parse the entire file to build the
1186 list; otherwise, get the value by reading the sexp at the top of
1187 the file."
1188 (setq todos-categories nil)
1189 (save-excursion
1190 (save-restriction
1191 (widen)
1192 (goto-char (point-min))
1193 (let (counts cat archive)
1194 ;; If the file is a todo file and has archived items, identify the
1195 ;; archive, in order to count its items. But skip this with
1196 ;; `todos-convert-legacy-files', since that converts filed items to
1197 ;; archived items.
1198 (when buffer-file-name ; During conversion there is no file yet.
1199 ;; If the file is an archive, it doesn't have an archive.
1200 (unless (member (file-truename buffer-file-name)
1201 (funcall todos-files-function t))
1202 (setq archive (concat (file-name-sans-extension
1203 todos-current-todos-file) ".toda"))))
1204 (while (not (eobp))
1205 (cond ((looking-at (concat (regexp-quote todos-category-beg)
1206 "\\(.*\\)\n"))
1207 (setq cat (match-string-no-properties 1))
1208 ;; Counts for each category: [todo diary done archive]
1209 (setq counts (make-vector 4 0))
1210 (setq todos-categories
1211 (append todos-categories (list (cons cat counts))))
1212 ;; Add archived item count to the todo file item counts.
1213 ;; Make sure to include newly created archives, e.g. due to
1214 ;; todos-move-category.
1215 (when (member archive (funcall todos-files-function t))
1216 (let ((archive-count 0))
1217 (with-current-buffer (find-file-noselect archive)
1218 (widen)
1219 (goto-char (point-min))
1220 (when (re-search-forward
1221 (concat (regexp-quote todos-category-beg) cat)
1222 (point-max) t)
1223 (forward-line)
1224 (while (not (or (looking-at
1225 (concat
1226 (regexp-quote todos-category-beg)
1227 "\\(.*\\)\n"))
1228 (eobp)))
1229 (when (looking-at todos-done-string-start)
1230 (setq archive-count (1+ archive-count)))
1231 (forward-line))))
1232 (todos-update-count 'archived archive-count cat))))
1233 ((looking-at todos-done-string-start)
1234 (todos-update-count 'done 1 cat))
1235 ((looking-at (concat "^\\("
1236 (regexp-quote diary-nonmarking-symbol)
1237 "\\)?" todos-date-pattern))
1238 (todos-update-count 'diary 1 cat)
1239 (todos-update-count 'todo 1 cat))
1240 ((looking-at (concat todos-date-string-start todos-date-pattern))
1241 (todos-update-count 'todo 1 cat))
1242 ;; If first line is todos-categories list, use it and end loop
1243 ;; -- unless FORCEd to scan whole file.
1244 ((bobp)
1245 (unless force
1246 (setq todos-categories (read (buffer-substring-no-properties
1247 (line-beginning-position)
1248 (line-end-position))))
1249 (goto-char (1- (point-max))))))
1250 (forward-line)))))
1251 todos-categories)
1252
1253 (defun todos-check-format ()
1254 "Signal an error if the current Todos file is ill-formatted.
1255 Otherwise return t. The error message gives the line number
1256 where the invalid formatting was found."
1257 (save-excursion
1258 (save-restriction
1259 (widen)
1260 (goto-char (point-min))
1261 ;; Check for `todos-categories' sexp as the first line
1262 (let ((cats (prin1-to-string todos-categories)))
1263 (unless (looking-at (regexp-quote cats))
1264 (error "Invalid or missing todos-categories sexp")))
1265 (forward-line)
1266 (let ((legit (concat "\\(^" (regexp-quote todos-category-beg) "\\)"
1267 "\\|\\(" todos-date-string-start todos-date-pattern "\\)"
1268 "\\|\\(^[ \t]+[^ \t]*\\)"
1269 "\\|^$"
1270 "\\|\\(^" (regexp-quote todos-category-done) "\\)"
1271 "\\|\\(" todos-done-string-start "\\)")))
1272 (while (not (eobp))
1273 (unless (looking-at legit)
1274 (error "Illegitimate Todos file format at line %d"
1275 (line-number-at-pos (point))))
1276 (forward-line)))))
1277 ;; (message "This Todos file is well-formatted.")
1278 t)
1279
1280 (defun todos-repair-categories-sexp ()
1281 "Repair corrupt Todos categories sexp.
1282 This should only be needed as a consequence of careless manual
1283 editing or a bug in todos.el."
1284 (interactive)
1285 (let ((todos-categories (todos-make-categories-list t)))
1286 (todos-update-categories-sexp)))
1287
1288 (defun todos-convert-legacy-date-time ()
1289 "Return converted date-time string.
1290 Helper function for `todos-convert-legacy-files'."
1291 (let* ((year (match-string 1))
1292 (month (match-string 2))
1293 (monthname (calendar-month-name (string-to-number month) t))
1294 (day (match-string 3))
1295 (time (match-string 4))
1296 dayname)
1297 (replace-match "")
1298 (insert (mapconcat 'eval calendar-date-display-form "")
1299 (when time (concat " " time)))))
1300
1301 (defvar todos-item-start (concat "\\(" todos-date-string-start "\\|"
1302 todos-done-string-start "\\)"
1303 todos-date-pattern)
1304 "String identifying start of a Todos item.")
1305
1306 (defun todos-item-start ()
1307 "Move to start of current Todos item and return its position."
1308 (unless (or
1309 ;; Buffer is empty (invocation possible e.g. via todos-forward-item
1310 ;; from todos-filter-items when processing category with no todo
1311 ;; items).
1312 (eq (point-min) (point-max))
1313 ;; Point is on the empty line below category's last todo item...
1314 (and (looking-at "^$")
1315 (or (eobp) ; ...and done items are hidden...
1316 (save-excursion ; ...or done items are visible.
1317 (forward-line)
1318 (looking-at (concat "^"
1319 (regexp-quote todos-category-done))))))
1320 ;; Buffer is widened.
1321 (looking-at (regexp-quote todos-category-beg)))
1322 (goto-char (line-beginning-position))
1323 (while (not (looking-at todos-item-start))
1324 (forward-line -1))
1325 (point)))
1326
1327 (defun todos-item-end ()
1328 "Move to end of current Todos item and return its position."
1329 ;; Items cannot end with a blank line.
1330 (unless (looking-at "^$")
1331 (let* ((done (todos-done-item-p))
1332 (to-lim nil)
1333 ;; For todo items, end is before the done items section, for done
1334 ;; items, end is before the next category. If these limits are
1335 ;; missing or inaccessible, end it before the end of the buffer.
1336 (lim (if (save-excursion
1337 (re-search-forward
1338 (concat "^" (regexp-quote (if done
1339 todos-category-beg
1340 todos-category-done)))
1341 nil t))
1342 (progn (setq to-lim t) (match-beginning 0))
1343 (point-max))))
1344 (when (bolp) (forward-char)) ; Find start of next item.
1345 (goto-char (if (re-search-forward todos-item-start lim t)
1346 (match-beginning 0)
1347 (if to-lim lim (point-max))))
1348 ;; For last todo item, skip back over the empty line before the done
1349 ;; items section, else just back to the end of the previous line.
1350 (backward-char (when (and to-lim (not done) (eq (point) lim)) 2))
1351 (point))))
1352
1353 (defun todos-item-string ()
1354 "Return bare text of current item as a string."
1355 (let ((opoint (point))
1356 (start (todos-item-start))
1357 (end (todos-item-end)))
1358 (goto-char opoint)
1359 (and start end (buffer-substring-no-properties start end))))
1360
1361 (defun todos-remove-item ()
1362 "Internal function called in editing, deleting or moving items."
1363 (let* ((beg (todos-item-start))
1364 (end (progn (todos-item-end) (1+ (point))))
1365 (ovs (overlays-in beg beg)))
1366 ;; There can be both prefix/number and mark overlays.
1367 (while ovs (delete-overlay (car ovs)) (pop ovs))
1368 (delete-region beg end)))
1369
1370 (defun todos-diary-item-p ()
1371 "Return non-nil if item at point has diary entry format."
1372 (save-excursion
1373 (todos-item-start)
1374 (not (looking-at (regexp-quote todos-nondiary-start)))))
1375
1376 (defun todos-done-item-p ()
1377 "Return non-nil if item at point is a done item."
1378 (save-excursion
1379 (todos-item-start)
1380 (looking-at todos-done-string-start)))
1381
1382 (defvar todos-item-mark (propertize (if (equal todos-prefix "*") "@" "*")
1383 'face 'todos-mark)
1384 "String used to mark items.")
1385
1386 (defun todos-marked-item-p ()
1387 "If this item begins with `todos-item-mark', return mark overlay."
1388 (let ((ovs (overlays-in (line-beginning-position) (line-beginning-position)))
1389 (mark todos-item-mark)
1390 ov marked)
1391 (catch 'stop
1392 (while ovs
1393 (setq ov (pop ovs))
1394 (and (equal (overlay-get ov 'before-string) mark)
1395 (throw 'stop (setq marked t)))))
1396 (when marked ov)))
1397
1398 (defun todos-insert-with-overlays (item)
1399 "Insert ITEM at point and update prefix/priority number overlays."
1400 (todos-item-start)
1401 (insert item "\n")
1402 (todos-backward-item)
1403 (todos-prefix-overlays))
1404
1405 (defun todos-prefix-overlays ()
1406 "Put before-string overlay in front of this category's items.
1407 The overlay's value is the string `todos-prefix' or with non-nil
1408 `todos-number-priorities' an integer in the sequence from 1 to
1409 the number of todo or done items in the category indicating the
1410 item's priority. Todo and done items are numbered independently
1411 of each other."
1412 (when (or todos-number-priorities
1413 (not (string-match "^[[:space:]]*$" todos-prefix)))
1414 (let ((prefix (propertize (concat todos-prefix " ")
1415 'face 'todos-prefix-string))
1416 (num 0))
1417 (save-excursion
1418 (goto-char (point-min))
1419 (while (not (eobp))
1420 (when (or (todos-date-string-matcher (line-end-position))
1421 (todos-done-string-matcher (line-end-position)))
1422 (goto-char (match-beginning 0))
1423 (when todos-number-priorities
1424 (setq num (1+ num))
1425 ;; Reset number to 1 for first done item.
1426 (when (and (looking-at todos-done-string-start)
1427 (looking-back (concat "^"
1428 (regexp-quote todos-category-done)
1429 "\n")))
1430 (setq num 1))
1431 (setq prefix (propertize (concat (number-to-string num) " ")
1432 'face 'todos-prefix-string)))
1433 (let ((ovs (overlays-in (point) (point)))
1434 marked ov-pref)
1435 (if ovs
1436 (dolist (ov ovs)
1437 (let ((val (overlay-get ov 'before-string)))
1438 (if (equal val "*")
1439 (setq marked t)
1440 (setq ov-pref val)))))
1441 (unless (equal ov-pref prefix)
1442 ;; Why doesn't this work?
1443 ;; (remove-overlays (point) (point) 'before-string)
1444 (remove-overlays (point) (point))
1445 (overlay-put (make-overlay (point) (point))
1446 'before-string prefix)
1447 (and marked (overlay-put (make-overlay (point) (point))
1448 'before-string todos-item-mark)))))
1449 (forward-line))))))
1450
1451 ;; ---------------------------------------------------------------------------
1452 ;;; Functions for user input with prompting and completion
1453
1454 (defun todos-read-file-name (prompt &optional archive mustmatch)
1455 "Choose and return the name of a Todos file, prompting with PROMPT.
1456
1457 Show completions with TAB or SPC; the names are shown in short
1458 form but the absolute truename is returned. With non-nil ARCHIVE
1459 return the absolute truename of a Todos archive file. With non-nil
1460 MUSTMATCH the name of an existing file must be chosen;
1461 otherwise, a new file name is allowed."
1462 (let* ((completion-ignore-case todos-completion-ignore-case)
1463 (files (mapcar 'todos-short-file-name
1464 (if archive todos-archives todos-files)))
1465 (file (completing-read prompt files nil mustmatch nil nil
1466 (unless files
1467 ;; Trigger prompt for initial file.
1468 ""))))
1469 (unless (file-exists-p todos-files-directory)
1470 (make-directory todos-files-directory))
1471 (unless mustmatch
1472 (setq file (todos-validate-name file 'file)))
1473 (setq file (file-truename (concat todos-files-directory file
1474 (if archive ".toda" ".todo"))))))
1475
1476 (defun todos-read-category (prompt &optional mustmatch added)
1477 "Choose and return a category name, prompting with PROMPT.
1478 Show completions with TAB or SPC. With non-nil MUSTMATCH the
1479 name must be that of an existing category; otherwise, a new
1480 category name is allowed, after checking its validity. Non-nil
1481 argument ADDED means the caller is todos-add-category, so don't
1482 ask whether to add the category."
1483 ;; Allow SPC to insert spaces, for adding new category names.
1484 (let ((map minibuffer-local-completion-map))
1485 (define-key map " " nil)
1486 ;; Make a copy of todos-categories in case history-delete-duplicates is
1487 ;; non-nil, which makes completing-read alter todos-categories.
1488 (let* ((categories (copy-sequence todos-categories))
1489 (history (cons 'todos-categories (1+ todos-category-number)))
1490 (completion-ignore-case todos-completion-ignore-case)
1491 (cat (completing-read prompt todos-categories nil
1492 mustmatch nil history
1493 ;; Default for existing categories is the
1494 ;; current category.
1495 (if todos-categories
1496 (todos-current-category)
1497 ;; Trigger prompt for initial category.
1498 ""))))
1499 (unless (or mustmatch (assoc cat todos-categories))
1500 (todos-validate-name cat 'category)
1501 (unless added
1502 (if (y-or-n-p (format (concat "There is no category \"%s\" in "
1503 "this file; add it? ") cat))
1504 (todos-add-category cat)
1505 (keyboard-quit))))
1506 ;; Restore the original value of todos-categories unless a new category
1507 ;; was added (since todos-add-category changes todos-categories).
1508 (unless added (setq todos-categories categories))
1509 cat)))
1510
1511 (defun todos-validate-name (name type)
1512 "Prompt for new NAME for TYPE until it is valid, then return it.
1513 TYPE can be either a file or a category"
1514 (let ((categories todos-categories)
1515 (files (mapcar 'todos-short-file-name todos-files))
1516 prompt)
1517 (while
1518 (and (cond ((string= "" name)
1519 (setq prompt
1520 (cond ((eq type 'file)
1521 (if todos-files
1522 "Enter a non-empty file name: "
1523 ;; Empty string passed by todos-show to
1524 ;; prompt for initial Todos file.
1525 (concat "Initial file name ["
1526 todos-initial-file "]: ")))
1527 ((eq type 'category)
1528 (if todos-categories
1529 "Enter a non-empty category name: "
1530 ;; Empty string passed by todos-show to
1531 ;; prompt for initial category of a new
1532 ;; Todos file.
1533 (concat "Initial category name ["
1534 todos-initial-category "]: "))))))
1535 ((string-match "\\`\\s-+\\'" name)
1536 (setq prompt
1537 "Enter a name that does not contain only white space: "))
1538 ((and (eq type 'file) (member name todos-files))
1539 (setq prompt "Enter a non-existing file name: "))
1540 ((and (eq type 'category) (assoc name todos-categories))
1541 (setq prompt "Enter a non-existing category name: ")))
1542 (setq name (if (or (and (eq type 'file) todos-files)
1543 (and (eq type 'category) todos-categories))
1544 (completing-read prompt (cond ((eq type 'file)
1545 todos-files)
1546 ((eq type 'category)
1547 todos-categories)))
1548 ;; Offer default initial name.
1549 (completing-read prompt (if (eq type 'file)
1550 todos-files
1551 todos-categories)
1552 nil nil (if (eq type 'file)
1553 todos-initial-file
1554 todos-initial-category))))))
1555 name))
1556
1557 ;; Adapted from calendar-read-date and calendar-date-string.
1558 (defun todos-read-date ()
1559 "Prompt for Gregorian date and return it in the current format.
1560 Also accepts `*' as an unspecified month, day, or year."
1561 (let* ((year (let (x)
1562 (while (if (numberp x) (< x 0) (not (eq x '*)))
1563 (setq x (read-from-minibuffer
1564 "Year (>0 or RET for this year or * for any year): "
1565 nil nil t nil (number-to-string
1566 (calendar-extract-year
1567 (calendar-current-date))))))
1568 x))
1569 (month-array (vconcat calendar-month-name-array (vector "*")))
1570 (abbrevs (vconcat calendar-month-abbrev-array (vector "*")))
1571 (completion-ignore-case todos-completion-ignore-case)
1572 (monthname (completing-read
1573 "Month name (RET for current month, * for any month): "
1574 (mapcar 'list (append month-array nil))
1575 nil t nil nil
1576 (calendar-month-name (calendar-extract-month
1577 (calendar-current-date)) t)))
1578 (month (cdr (assoc-string
1579 monthname (calendar-make-alist month-array nil nil
1580 abbrevs))))
1581 (last (if (= month 13)
1582 ;; Use longest possible month for checking day number
1583 ;; input. Does Calendar do anything special when * is
1584 ;; currently a shorter month?
1585 31
1586 (let ((yr (if (eq year '*)
1587 ;; Use a leap year to allow Feb. 29.
1588 2012
1589 year)))
1590 (calendar-last-day-of-month month yr))))
1591 (day (let (x)
1592 (while (if (numberp x) (or (< x 0) (< last x)) (not (eq x '*)))
1593 (setq x (read-from-minibuffer
1594 (format
1595 "Day (1-%d or RET for today or * for any day): "
1596 last) nil nil t nil (number-to-string
1597 (calendar-extract-day
1598 (calendar-current-date))))))
1599 x))
1600 dayname) ; Needed by calendar-date-display-form.
1601 (setq year (if (eq year '*) (symbol-name '*) (number-to-string year)))
1602 (setq day (if (eq day '*) (symbol-name '*) (number-to-string day)))
1603 ;; FIXME: make abbreviation customizable
1604 (setq monthname
1605 (or (and (= month 13) "*")
1606 (calendar-month-name (calendar-extract-month (list month day year))
1607 t)))
1608 (mapconcat 'eval calendar-date-display-form "")))
1609
1610 (defun todos-read-dayname ()
1611 "Choose name of a day of the week with completion and return it."
1612 (let ((completion-ignore-case todos-completion-ignore-case))
1613 (completing-read "Enter a day name: "
1614 (append calendar-day-name-array nil)
1615 nil t)))
1616
1617 (defun todos-read-time ()
1618 "Prompt for and return a valid clock time as a string.
1619
1620 Valid time strings are those matching `diary-time-regexp'.
1621 Typing `<return>' at the prompt returns the current time, if the
1622 user option `todos-always-add-time-string' is non-nil, otherwise
1623 the empty string (i.e., no time string)."
1624 (let (valid answer)
1625 (while (not valid)
1626 (setq answer (read-string "Enter a clock time: " nil nil
1627 (when todos-always-add-time-string
1628 (substring (current-time-string) 11 16))))
1629 (when (or (string= "" answer)
1630 (string-match diary-time-regexp answer))
1631 (setq valid t)))
1632 answer))
1633
1634 ;; ---------------------------------------------------------------------------
1635 ;;; Item filtering
1636
1637 (defvar todos-multiple-filter-files nil
1638 "List of files selected from `todos-multiple-filter-files' widget.")
1639
1640 (defvar todos-multiple-filter-files-widget nil
1641 "Variable holding widget created by `todos-multiple-filter-files'.")
1642
1643 (defun todos-multiple-filter-files ()
1644 "Pop to a buffer with a widget for choosing multiple filter files."
1645 (require 'widget)
1646 (eval-when-compile
1647 (require 'wid-edit))
1648 (with-current-buffer (get-buffer-create "*Todos Filter Files*")
1649 (pop-to-buffer (current-buffer))
1650 (erase-buffer)
1651 (kill-all-local-variables)
1652 (widget-insert "Select files for generating the top priorities list.\n\n")
1653 (setq todos-multiple-filter-files-widget
1654 (widget-create
1655 `(set ,@(mapcar (lambda (x) (list 'const x))
1656 (mapcar 'todos-short-file-name
1657 (funcall todos-files-function))))))
1658 (widget-insert "\n")
1659 (widget-create 'push-button
1660 :notify (lambda (widget &rest ignore)
1661 (setq todos-multiple-filter-files 'quit)
1662 (quit-window t)
1663 (exit-recursive-edit))
1664 "Cancel")
1665 (widget-insert " ")
1666 (widget-create 'push-button
1667 :notify (lambda (&rest ignore)
1668 (setq todos-multiple-filter-files
1669 (mapcar (lambda (f)
1670 (concat todos-files-directory
1671 f ".todo"))
1672 (widget-value
1673 todos-multiple-filter-files-widget)))
1674 (quit-window t)
1675 (exit-recursive-edit))
1676 "Apply")
1677 (use-local-map widget-keymap)
1678 (widget-setup))
1679 (message "Click \"Apply\" after selecting files.")
1680 (recursive-edit))
1681
1682 (defun todos-filter-items (filter &optional multifile)
1683 "Build and display a list of items from different categories.
1684
1685 The items are selected according to the value of FILTER, which
1686 can be `top' for top priority items, `diary' for diary items,
1687 `regexp' for items matching a regular expresion entered by the
1688 user, or a cons cell of one of these symbols and a number set by
1689 the calling command, which overrides `todos-show-priorities'.
1690
1691 With non-nil argument MULTIFILE list top priorities of multiple
1692 Todos files, by default those in `todos-filter-files'."
1693 (let ((num (if (consp filter) (cdr filter) todos-show-priorities))
1694 (buf (get-buffer-create todos-filtered-items-buffer))
1695 (files (list todos-current-todos-file))
1696 regexp fname bufstr cat beg end done)
1697 (when multifile
1698 (setq files (or todos-multiple-filter-files ; Passed from todos-*-multifile.
1699 (if (or (consp filter)
1700 (null todos-filter-files))
1701 (progn (todos-multiple-filter-files)
1702 todos-multiple-filter-files)
1703 todos-filter-files))
1704 todos-multiple-filter-files nil))
1705 (if (eq files 'quit) (keyboard-quit))
1706 (if (null files)
1707 (error "No files have been chosen for filtering")
1708 (with-current-buffer buf
1709 (erase-buffer)
1710 (kill-all-local-variables)
1711 (todos-filtered-items-mode))
1712 (when (eq filter 'regexp)
1713 (setq regexp (read-string "Enter a regular expression: ")))
1714 (save-current-buffer
1715 (dolist (f files)
1716 ;; Before inserting file contents into temp buffer, save a modified
1717 ;; buffer visiting it.
1718 (let ((bf (find-buffer-visiting f)))
1719 (when (buffer-modified-p bf)
1720 (with-current-buffer bf (save-buffer))))
1721 (setq fname (todos-short-file-name f))
1722 (with-temp-buffer
1723 (when (and todos-filter-done-items (eq filter 'regexp))
1724 ;; If there is a corresponding archive file for the Todos file,
1725 ;; insert it first and add identifiers for todos-jump-to-item.
1726 (let ((arch (concat (file-name-sans-extension f) ".toda")))
1727 (when (file-exists-p arch)
1728 (insert-file-contents arch)
1729 ;; Delete Todos archive file categories sexp.
1730 (delete-region (line-beginning-position)
1731 (1+ (line-end-position)))
1732 (save-excursion
1733 (while (not (eobp))
1734 (when (re-search-forward
1735 (concat (if todos-filter-done-items
1736 (concat "\\(?:" todos-done-string-start
1737 "\\|" todos-date-string-start
1738 "\\)")
1739 todos-date-string-start)
1740 todos-date-pattern "\\(?: "
1741 diary-time-regexp "\\)?"
1742 (if todos-filter-done-items
1743 "\\]"
1744 (regexp-quote todos-nondiary-end)) "?")
1745 nil t)
1746 (insert "(archive) "))
1747 (forward-line))))))
1748 (insert-file-contents f)
1749 ;; Delete Todos file categories sexp.
1750 (delete-region (line-beginning-position) (1+ (line-end-position)))
1751 (let (fnum)
1752 ;; Unless the number of items to show was supplied by prefix
1753 ;; argument of caller, the file-wide value from
1754 ;; `todos-priorities-rules', if non-nil, overrides
1755 ;; `todos-show-priorities'.
1756 (unless (consp filter)
1757 (setq fnum (nth 1 (assoc f todos-priorities-rules))))
1758 (while (re-search-forward
1759 (concat "^" (regexp-quote todos-category-beg) "\\(.+\\)\n")
1760 nil t)
1761 (setq cat (match-string 1))
1762 (let (cnum)
1763 ;; Unless the number of items to show was supplied by prefix
1764 ;; argument of caller, the category-wide value from
1765 ;; `todos-priorities-rules', if non-nil, overrides a non-nil
1766 ;; file-wide value from `todos-priorities-rules' as well as
1767 ;; `todos-show-priorities'.
1768 (unless (consp filter)
1769 (let ((cats (nth 2 (assoc f todos-priorities-rules))))
1770 (setq cnum (or (cdr (assoc cat cats)) fnum))))
1771 (delete-region (match-beginning 0) (match-end 0))
1772 (setq beg (point)) ; First item in the current category.
1773 (setq end (if (re-search-forward
1774 (concat "^" (regexp-quote todos-category-beg))
1775 nil t)
1776 (match-beginning 0)
1777 (point-max)))
1778 (goto-char beg)
1779 (setq done
1780 (if (re-search-forward
1781 (concat "\n" (regexp-quote todos-category-done))
1782 end t)
1783 (match-beginning 0)
1784 end))
1785 (unless (and todos-filter-done-items (eq filter 'regexp))
1786 ;; Leave done items.
1787 (delete-region done end)
1788 (setq end done))
1789 (narrow-to-region beg end) ; Process only current category.
1790 (goto-char (point-min))
1791 ;; Apply the filter.
1792 (cond ((eq filter 'diary)
1793 (while (not (eobp))
1794 (if (looking-at (regexp-quote todos-nondiary-start))
1795 (todos-remove-item)
1796 (todos-forward-item))))
1797 ((eq filter 'regexp)
1798 (while (not (eobp))
1799 (if (looking-at todos-item-start)
1800 (if (string-match regexp (todos-item-string))
1801 (todos-forward-item)
1802 (todos-remove-item))
1803 ;; Kill lines that aren't part of a todo or done
1804 ;; item (empty or todos-category-done).
1805 (delete-region (line-beginning-position)
1806 (1+ (line-end-position))))
1807 ;; If last todo item in file matches regexp and
1808 ;; there are no following done items,
1809 ;; todos-category-done string is left dangling,
1810 ;; because todos-forward-item jumps over it.
1811 (if (and (eobp)
1812 (looking-back
1813 (concat (regexp-quote todos-done-string)
1814 "\n")))
1815 (delete-region (point) (progn
1816 (forward-line -2)
1817 (point))))))
1818 (t ; Filter top priority items.
1819 (setq num (or cnum fnum num))
1820 (unless (zerop num)
1821 (todos-forward-item num))))
1822 (setq beg (point))
1823 ;; Delete non-top-priority items.
1824 (unless (member filter '(diary regexp))
1825 (delete-region beg end))
1826 (goto-char (point-min))
1827 ;; Add file (if using multiple files) and category tags to
1828 ;; item.
1829 (while (not (eobp))
1830 (when (re-search-forward
1831 (concat (if todos-filter-done-items
1832 (concat "\\(?:" todos-done-string-start
1833 "\\|" todos-date-string-start
1834 "\\)")
1835 todos-date-string-start)
1836 todos-date-pattern "\\(?: " diary-time-regexp
1837 "\\)?" (if todos-filter-done-items
1838 "\\]"
1839 (regexp-quote todos-nondiary-end))
1840 "?")
1841 nil t)
1842 (insert " [")
1843 (when (looking-at "(archive) ") (goto-char (match-end 0)))
1844 (insert (if multifile (concat fname ":") "") cat "]"))
1845 (forward-line))
1846 (widen)))
1847 (setq bufstr (buffer-string))
1848 (with-current-buffer buf
1849 (let (buffer-read-only)
1850 (insert bufstr)))))))
1851 (set-window-buffer (selected-window) (set-buffer buf))
1852 (todos-prefix-overlays)
1853 (goto-char (point-min)))))
1854
1855 (defun todos-set-top-priorities (&optional arg)
1856 "Set number of top priorities shown by `todos-top-priorities'.
1857 With non-nil ARG, set the number only for the current Todos
1858 category; otherwise, set the number for all categories in the
1859 current Todos file.
1860
1861 Calling this function via either of the commands
1862 `todos-set-top-priorities-in-file' or
1863 `todos-set-top-priorities-in-category' is the recommended way to
1864 set the user customizable option `todos-priorities-rules'."
1865 (let* ((cat (todos-current-category))
1866 (file todos-current-todos-file)
1867 (rules todos-priorities-rules)
1868 (frule (assoc-string file rules))
1869 (crule (assoc-string cat (nth 2 frule)))
1870 (cur (or (if arg (cdr crule) (nth 1 frule))
1871 todos-show-priorities))
1872 (prompt (concat "Current number of top priorities in this "
1873 (if arg "category" "file") ": %d; "
1874 "enter new number: "))
1875 (new "-1")
1876 nrule)
1877 ;; FIXME: use read-number
1878 (while (or (not (string-match "[0-9]+" new)) ; Don't accept "" or "bla".
1879 (< (string-to-number new) 0))
1880 (let ((cur0 cur))
1881 (setq new (read-string (format prompt cur0) nil nil cur0)
1882 prompt "Enter a non-negative number: "
1883 cur0 nil)))
1884 (setq new (string-to-number new))
1885 (setq nrule (if arg
1886 (append (nth 2 (delete crule frule)) (list (cons cat new)))
1887 (append (list file new) (list (nth 2 frule)))))
1888 (setq rules (cons (if arg
1889 (list file cur nrule)
1890 nrule)
1891 (delete frule rules)))
1892 (customize-save-variable 'todos-priorities-rules rules)))
1893
1894 (defun todos-filtered-buffer-name (buffer-type file-list)
1895 "Rename Todos filtered buffer using BUFFER-TYPE and FILE-LIST.
1896
1897 The new name is constructed from the string BUFFER-TYPE, which
1898 refers to one of the top priorities, diary or regexp item
1899 filters, and the names of the filtered files in FILE-LIST. Used
1900 in Todos Filter Items mode."
1901 (let* ((flist (if (listp file-list) file-list (list file-list)))
1902 (multi (> (length flist) 1))
1903 (fnames (mapconcat (lambda (f) (todos-short-file-name f))
1904 flist ", ")))
1905 (rename-buffer (format (concat "%s for file" (if multi "s" "")
1906 " \"%s\"") buffer-type fnames))))
1907
1908 ;; ---------------------------------------------------------------------------
1909 ;;; Sorting and display routines for Todos Categories mode.
1910
1911 (defun todos-longest-category-name-length (categories)
1912 "Return the length of the longest name in list CATEGORIES."
1913 (let ((longest 0))
1914 (dolist (c categories longest)
1915 (setq longest (max longest (length c))))))
1916
1917 (defun todos-padded-string (str)
1918 "Return string STR padded with spaces.
1919 The placement of the padding is determined by the value of user
1920 option `todos-categories-align'."
1921 (let* ((categories (mapcar 'car todos-categories))
1922 (len (max (todos-longest-category-name-length categories)
1923 (length todos-categories-category-label)))
1924 (strlen (length str))
1925 (strlen-odd (eq (logand strlen 1) 1)) ; oddp from cl.el
1926 (padding (max 0 (/ (- len strlen) 2)))
1927 (padding-left (cond ((eq todos-categories-align 'left) 0)
1928 ((eq todos-categories-align 'center) padding)
1929 ((eq todos-categories-align 'right)
1930 (if strlen-odd (1+ (* padding 2)) (* padding 2)))))
1931 (padding-right (cond ((eq todos-categories-align 'left)
1932 (if strlen-odd (1+ (* padding 2)) (* padding 2)))
1933 ((eq todos-categories-align 'center)
1934 (if strlen-odd (1+ padding) padding))
1935 ((eq todos-categories-align 'right) 0))))
1936 (concat (make-string padding-left 32) str (make-string padding-right 32))))
1937
1938 (defvar todos-descending-counts nil
1939 "List of keys for category counts sorted in descending order.")
1940
1941 (defun todos-sort (list &optional key)
1942 "Return a copy of LIST, possibly sorted according to KEY."
1943 (let* ((l (copy-sequence list))
1944 (fn (if (eq key 'alpha)
1945 (lambda (x) (upcase x)) ; Alphabetize case insensitively.
1946 (lambda (x) (todos-get-count key x))))
1947 ;; Keep track of whether the last sort by key was descending or
1948 ;; ascending.
1949 (descending (member key todos-descending-counts))
1950 (cmp (if (eq key 'alpha)
1951 'string<
1952 (if descending '< '>)))
1953 (pred (lambda (s1 s2) (let ((t1 (funcall fn (car s1)))
1954 (t2 (funcall fn (car s2))))
1955 (funcall cmp t1 t2)))))
1956 (when key
1957 (setq l (sort l pred))
1958 ;; Switch between descending and ascending sort order.
1959 (if descending
1960 (setq todos-descending-counts
1961 (delete key todos-descending-counts))
1962 (push key todos-descending-counts)))
1963 l))
1964
1965 (defun todos-display-sorted (type)
1966 "Keep point on the TYPE count sorting button just clicked."
1967 (let ((opoint (point)))
1968 (todos-update-categories-display type)
1969 (goto-char opoint)))
1970
1971 (defun todos-label-to-key (label)
1972 "Return symbol for sort key associated with LABEL."
1973 (let (key)
1974 (cond ((string= label todos-categories-category-label)
1975 (setq key 'alpha))
1976 ((string= label todos-categories-todo-label)
1977 (setq key 'todo))
1978 ((string= label todos-categories-diary-label)
1979 (setq key 'diary))
1980 ((string= label todos-categories-done-label)
1981 (setq key 'done))
1982 ((string= label todos-categories-archived-label)
1983 (setq key 'archived)))
1984 key))
1985
1986 (defun todos-insert-sort-button (label)
1987 "Insert button for displaying categories sorted by item counts.
1988 LABEL determines which type of count is sorted."
1989 (setq str (if (string= label todos-categories-category-label)
1990 (todos-padded-string label)
1991 label))
1992 (setq beg (point))
1993 (setq end (+ beg (length str)))
1994 (insert-button str 'face nil
1995 'action
1996 `(lambda (button)
1997 (let ((key (todos-label-to-key ,label)))
1998 (if (and (member key todos-descending-counts)
1999 (eq key 'alpha))
2000 (progn
2001 ;; If display is alphabetical, switch back to
2002 ;; category priority order.
2003 (todos-display-sorted nil)
2004 (setq todos-descending-counts
2005 (delete key todos-descending-counts)))
2006 (todos-display-sorted key)))))
2007 (setq ovl (make-overlay beg end))
2008 (overlay-put ovl 'face 'todos-button))
2009
2010 (defun todos-total-item-counts ()
2011 "Return a list of total item counts for the current file."
2012 (mapcar (lambda (i) (apply '+ (mapcar (lambda (l) (aref l i))
2013 (mapcar 'cdr todos-categories))))
2014 (list 0 1 2 3)))
2015
2016 (defvar todos-categories-category-number 0
2017 "Variable for numbering categories in Todos Categories mode.")
2018
2019 (defun todos-insert-category-line (cat &optional nonum)
2020 "Insert button with category CAT's name and item counts.
2021 With non-nil argument NONUM show only these; otherwise, insert a
2022 number in front of the button indicating the category's priority.
2023 The number and the category name are separated by the string
2024 which is the value of the user option
2025 `todos-categories-number-separator'."
2026 (let ((archive (member todos-current-todos-file todos-archives))
2027 (num todos-categories-category-number)
2028 (str (todos-padded-string cat))
2029 (opoint (point)))
2030 (setq num (1+ num) todos-categories-category-number num)
2031 (insert-button
2032 (concat (if nonum
2033 (make-string (+ 4 (length todos-categories-number-separator))
2034 32)
2035 (format " %3d%s" num todos-categories-number-separator))
2036 str
2037 (mapconcat (lambda (elt)
2038 (concat
2039 (make-string (1+ (/ (length (car elt)) 2)) 32) ; label
2040 (format "%3d" (todos-get-count (cdr elt) cat)) ; count
2041 ;; Add an extra space if label length is odd
2042 ;; (using def of oddp from cl.el).
2043 (if (eq (logand (length (car elt)) 1) 1) " ")))
2044 (if archive
2045 (list (cons todos-categories-done-label 'done))
2046 (list (cons todos-categories-todo-label 'todo)
2047 (cons todos-categories-diary-label 'diary)
2048 (cons todos-categories-done-label 'done)
2049 (cons todos-categories-archived-label
2050 'archived)))
2051 "")
2052 " ") ; So highlighting of last column is consistent with the others.
2053 'face (if (and todos-skip-archived-categories
2054 (zerop (todos-get-count 'todo cat))
2055 (zerop (todos-get-count 'done cat))
2056 (not (zerop (todos-get-count 'archived cat))))
2057 'todos-archived-only
2058 nil)
2059 'action `(lambda (button) (let ((buf (current-buffer)))
2060 (todos-jump-to-category ,cat)
2061 (kill-buffer buf))))
2062 ;; Highlight the sorted count column.
2063 (let* ((beg (+ opoint 7 (length str)))
2064 end ovl)
2065 (cond ((eq nonum 'todo)
2066 (setq beg (+ beg 1 (/ (length todos-categories-todo-label) 2))))
2067 ((eq nonum 'diary)
2068 (setq beg (+ beg 1 (length todos-categories-todo-label)
2069 2 (/ (length todos-categories-diary-label) 2))))
2070 ((eq nonum 'done)
2071 (setq beg (+ beg 1 (length todos-categories-todo-label)
2072 2 (length todos-categories-diary-label)
2073 2 (/ (length todos-categories-done-label) 2))))
2074 ((eq nonum 'archived)
2075 (setq beg (+ beg 1 (length todos-categories-todo-label)
2076 2 (length todos-categories-diary-label)
2077 2 (length todos-categories-done-label)
2078 2 (/ (length todos-categories-archived-label) 2)))))
2079 (unless (= beg (+ opoint 7 (length str))) ; Don't highlight categories.
2080 (setq end (+ beg 4))
2081 (setq ovl (make-overlay beg end))
2082 (overlay-put ovl 'face 'todos-sorted-column)))
2083 (newline)))
2084
2085 (defun todos-display-categories-1 ()
2086 "Prepare buffer for displaying table of categories and item counts."
2087 (unless (eq major-mode 'todos-categories-mode)
2088 (setq todos-global-current-todos-file (or todos-current-todos-file
2089 todos-default-todos-file))
2090 (set-window-buffer (selected-window)
2091 (set-buffer (get-buffer-create todos-categories-buffer)))
2092 (kill-all-local-variables)
2093 (todos-categories-mode)
2094 (let ((archive (member todos-current-todos-file todos-archives))
2095 buffer-read-only)
2096 (erase-buffer)
2097 ;; FIXME: add usage tips?
2098 (insert (format (concat "Category counts for Todos "
2099 (if archive "archive" "file")
2100 " \"%s\".")
2101 (todos-short-file-name todos-current-todos-file)))
2102 (newline 2)
2103 ;; Make space for the column of category numbers.
2104 (insert (make-string (+ 4 (length todos-categories-number-separator)) 32))
2105 ;; Add the category and item count buttons (if this is the list of
2106 ;; categories in an archive, show only done item counts).
2107 (todos-insert-sort-button todos-categories-category-label)
2108 (if archive
2109 (progn
2110 (insert (make-string 3 32))
2111 (todos-insert-sort-button todos-categories-done-label))
2112 (insert (make-string 3 32))
2113 (todos-insert-sort-button todos-categories-todo-label)
2114 (insert (make-string 2 32))
2115 (todos-insert-sort-button todos-categories-diary-label)
2116 (insert (make-string 2 32))
2117 (todos-insert-sort-button todos-categories-done-label)
2118 (insert (make-string 2 32))
2119 (todos-insert-sort-button todos-categories-archived-label))
2120 (newline 2))))
2121
2122 (defun todos-update-categories-display (sortkey)
2123 ""
2124 (let* ((cats0 todos-categories)
2125 (cats (todos-sort cats0 sortkey))
2126 (archive (member todos-current-todos-file todos-archives))
2127 (todos-categories-category-number 0)
2128 ;; Find start of Category button if we just entered Todos Categories
2129 ;; mode.
2130 (pt (if (eq (point) (point-max))
2131 (save-excursion
2132 (forward-line -2)
2133 (goto-char (next-single-char-property-change
2134 (point) 'face nil (line-end-position))))))
2135 (buffer-read-only))
2136 (forward-line 2)
2137 (delete-region (point) (point-max))
2138 ;; Fill in the table with buttonized lines, each showing a category and
2139 ;; its item counts.
2140 (mapc (lambda (cat) (todos-insert-category-line cat sortkey))
2141 (mapcar 'car cats))
2142 (newline)
2143 ;; Add a line showing item count totals.
2144 (insert (make-string (+ 4 (length todos-categories-number-separator)) 32)
2145 (todos-padded-string todos-categories-totals-label)
2146 (mapconcat
2147 (lambda (elt)
2148 (concat
2149 (make-string (1+ (/ (length (car elt)) 2)) 32)
2150 (format "%3d" (nth (cdr elt) (todos-total-item-counts)))
2151 ;; Add an extra space if label length is odd (using
2152 ;; definition of oddp from cl.el).
2153 (if (eq (logand (length (car elt)) 1) 1) " ")))
2154 (if archive
2155 (list (cons todos-categories-done-label 2))
2156 (list (cons todos-categories-todo-label 0)
2157 (cons todos-categories-diary-label 1)
2158 (cons todos-categories-done-label 2)
2159 (cons todos-categories-archived-label 3)))
2160 ""))
2161 ;; Put cursor on Category button initially.
2162 (if pt (goto-char pt))
2163 (setq buffer-read-only t)))
2164
2165 ;; ---------------------------------------------------------------------------
2166 ;;; Routines for generating Todos insertion commands and key bindings
2167
2168 ;; Can either of these be included in Emacs? The originals are GFDL'd.
2169
2170 ;; Slightly reformulated from
2171 ;; http://rosettacode.org/wiki/Power_set#Common_Lisp.
2172 (defun powerset-recursive (l)
2173 (cond ((null l)
2174 (list nil))
2175 (t
2176 (let ((prev (powerset-recursive (cdr l))))
2177 (append (mapcar (lambda (elt) (cons (car l) elt))
2178 prev)
2179 prev)))))
2180
2181 ;; Elisp implementation of http://rosettacode.org/wiki/Power_set#C
2182 (defun powerset-bitwise (l)
2183 (let ((binnum (lsh 1 (length l)))
2184 pset elt)
2185 (dotimes (i binnum)
2186 (let ((bits i)
2187 (ll l))
2188 (while (not (zerop bits))
2189 (let ((arg (pop ll)))
2190 (unless (zerop (logand bits 1))
2191 (setq elt (append elt (list arg))))
2192 (setq bits (lsh bits -1))))
2193 (setq pset (append pset (list elt)))
2194 (setq elt nil)))
2195 pset))
2196
2197 ;; (defalias 'todos-powerset 'powerset-recursive)
2198 (defalias 'todos-powerset 'powerset-bitwise)
2199
2200 ;; Return list of lists of non-nil atoms produced from ARGLIST. The elements
2201 ;; of ARGLIST may be atoms or lists.
2202 (defun todos-gen-arglists (arglist)
2203 (let (arglists)
2204 (while arglist
2205 (let ((arg (pop arglist)))
2206 (cond ((symbolp arg)
2207 (setq arglists (if arglists
2208 (mapcar (lambda (l) (push arg l)) arglists)
2209 (list (push arg arglists)))))
2210 ((listp arg)
2211 (setq arglists
2212 (mapcar (lambda (a)
2213 (if (= 1 (length arglists))
2214 (apply (lambda (l) (push a l)) arglists)
2215 (mapcar (lambda (l) (push a l)) arglists)))
2216 arg))))))
2217 (setq arglists (mapcar 'reverse (apply 'append (mapc 'car arglists))))))
2218
2219 (defvar todos-insertion-commands-args-genlist
2220 '(diary nonmarking (calendar date dayname) time (here region))
2221 "Generator list for argument lists of Todos insertion commands.")
2222
2223 (defvar todos-insertion-commands-args
2224 (let ((argslist (todos-gen-arglists todos-insertion-commands-args-genlist))
2225 res new)
2226 (setq res (remove-duplicates
2227 (apply 'append (mapcar 'todos-powerset argslist)) :test 'equal))
2228 (dolist (l res)
2229 (unless (= 5 (length l))
2230 (let ((v (make-vector 5 nil)) elt)
2231 (while l
2232 (setq elt (pop l))
2233 (cond ((eq elt 'diary)
2234 (aset v 0 elt))
2235 ((eq elt 'nonmarking)
2236 (aset v 1 elt))
2237 ((or (eq elt 'calendar)
2238 (eq elt 'date)
2239 (eq elt 'dayname))
2240 (aset v 2 elt))
2241 ((eq elt 'time)
2242 (aset v 3 elt))
2243 ((or (eq elt 'here)
2244 (eq elt 'region))
2245 (aset v 4 elt))))
2246 (setq l (append v nil))))
2247 (setq new (append new (list l))))
2248 new)
2249 "List of all argument lists for Todos insertion commands.")
2250
2251 (defun todos-insertion-command-name (arglist)
2252 "Generate Todos insertion command name from ARGLIST."
2253 (replace-regexp-in-string
2254 "-\\_>" ""
2255 (replace-regexp-in-string
2256 "-+" "-"
2257 (concat "todos-item-insert-"
2258 (mapconcat (lambda (e) (if e (symbol-name e))) arglist "-")))))
2259
2260 (defvar todos-insertion-commands-names
2261 (mapcar (lambda (l)
2262 (todos-insertion-command-name l))
2263 todos-insertion-commands-args)
2264 "List of names of Todos insertion commands.")
2265
2266 (defmacro todos-define-insertion-command (&rest args)
2267 (let ((name (intern (todos-insertion-command-name args)))
2268 (arg0 (nth 0 args))
2269 (arg1 (nth 1 args))
2270 (arg2 (nth 2 args))
2271 (arg3 (nth 3 args))
2272 (arg4 (nth 4 args)))
2273 `(defun ,name (&optional arg)
2274 "Todos item insertion command generated from ARGS."
2275 (interactive)
2276 (todos-insert-item arg ',arg0 ',arg1 ',arg2 ',arg3 ',arg4))))
2277
2278 (defvar todos-insertion-commands
2279 (mapcar (lambda (c)
2280 (eval `(todos-define-insertion-command ,@c)))
2281 todos-insertion-commands-args)
2282 "List of Todos insertion commands.")
2283
2284 (defvar todos-insertion-commands-arg-key-list
2285 '(("diary" "y" "yy")
2286 ("nonmarking" "k" "kk")
2287 ("calendar" "c" "cc")
2288 ("date" "d" "dd")
2289 ("dayname" "n" "nn")
2290 ("time" "t" "tt")
2291 ("here" "h" "h")
2292 ("region" "r" "r"))
2293 "")
2294
2295 (defun todos-insertion-key-bindings (map)
2296 ""
2297 (dolist (c todos-insertion-commands)
2298 (let* ((key "")
2299 (cname (symbol-name c)))
2300 (mapc (lambda (l)
2301 (let ((arg (nth 0 l))
2302 (key1 (nth 1 l))
2303 (key2 (nth 2 l)))
2304 (if (string-match (concat (regexp-quote arg) "\\_>") cname)
2305 (setq key (concat key key2)))
2306 (if (string-match (concat (regexp-quote arg) ".+") cname)
2307 (setq key (concat key key1)))))
2308 todos-insertion-commands-arg-key-list)
2309 (if (string-match (concat (regexp-quote "todos-item-insert") "\\_>") cname)
2310 (setq key (concat key "i")))
2311 (define-key map key c))))
2312
2313 (defvar todos-insertion-map
2314 (let ((map (make-keymap)))
2315 (todos-insertion-key-bindings map)
2316 map)
2317 "Keymap for Todos mode insertion commands.")
2318
2319 ;; ---------------------------------------------------------------------------
2320 ;;; Key maps and menus
2321
2322 (defvar todos-key-bindings
2323 `(
2324 ;; display
2325 ("Cd" . todos-display-categories) ;FIXME: Cs todos-show-categories?
2326 ;("" . todos-display-categories-alphabetically)
2327 ("H" . todos-highlight-item)
2328 ("N" . todos-hide-show-item-numbering)
2329 ("D" . todos-hide-show-date-time)
2330 ("*" . todos-mark-unmark-item)
2331 ("C*" . todos-mark-category)
2332 ("Cu" . todos-unmark-category)
2333 ("PP" . todos-print)
2334 ("PF" . todos-print-to-file)
2335 ("v" . todos-hide-show-done-items)
2336 ("V" . todos-show-done-only)
2337 ("As" . todos-show-archive)
2338 ("Ac" . todos-choose-archive)
2339 ("Y" . todos-diary-items)
2340 ("Fe" . todos-edit-multiline)
2341 ("Fh" . todos-highlight-item)
2342 ("Fn" . todos-hide-show-item-numbering)
2343 ("Fd" . todos-hide-show-date-time)
2344 ("Ftt" . todos-top-priorities)
2345 ("Ftm" . todos-top-priorities-multifile)
2346 ("Fts" . todos-set-top-priorities-in-file)
2347 ("Cts" . todos-set-top-priorities-in-category)
2348 ("Fyy" . todos-diary-items)
2349 ("Fym" . todos-diary-items-multifile)
2350 ("Fxx" . todos-regexp-items)
2351 ("Fxm" . todos-regexp-items-multifile)
2352 ;; navigation
2353 ("f" . todos-forward-category)
2354 ("b" . todos-backward-category)
2355 ("j" . todos-jump-to-category)
2356 ("J" . todos-jump-to-category-other-file)
2357 ("n" . todos-forward-item)
2358 ("p" . todos-backward-item)
2359 ("S" . todos-search)
2360 ("X" . todos-clear-matches)
2361 ;; editing
2362 ("Fa" . todos-add-file)
2363 ("Ca" . todos-add-category)
2364 ("Cr" . todos-rename-category)
2365 ("Cg" . todos-merge-category)
2366 ("Cm" . todos-move-category)
2367 ("Ck" . todos-delete-category)
2368 ("d" . todos-item-done)
2369 ("ee" . todos-edit-item)
2370 ("em" . todos-edit-multiline-item)
2371 ("eh" . todos-edit-item-header)
2372 ("edd" . todos-edit-item-date)
2373 ("edc" . todos-edit-item-date-from-calendar)
2374 ("edt" . todos-edit-item-date-is-today)
2375 ("et" . todos-edit-item-time)
2376 ("eyy" . todos-edit-item-diary-inclusion)
2377 ;; ("" . todos-edit-category-diary-inclusion)
2378 ("eyn" . todos-edit-item-diary-nonmarking)
2379 ;;("" . todos-edit-category-diary-nonmarking)
2380 ("ec" . todos-done-item-add-edit-or-delete-comment)
2381 ("i" . ,todos-insertion-map)
2382 ("k" . todos-delete-item) ;FIXME: not single letter?
2383 ("m" . todos-move-item)
2384 ("M" . todos-move-item-to-file)
2385 ("r" . todos-raise-item-priority)
2386 ("l" . todos-lower-item-priority)
2387 ("#" . todos-set-item-priority)
2388 ("u" . todos-item-undo)
2389 ("Ad" . todos-archive-done-item) ;FIXME: ad
2390 ("AD" . todos-archive-category-done-items) ;FIXME: aD or C-u ad ?
2391 ("s" . todos-save)
2392 ("q" . todos-quit)
2393 ([remap newline] . newline-and-indent)
2394 )
2395 "Alist pairing keys defined in Todos modes and their bindings.")
2396
2397 (defvar todos-mode-map
2398 (let ((map (make-keymap)))
2399 ;; Don't suppress digit keys, so they can supply prefix arguments.
2400 (suppress-keymap map)
2401 (dolist (ck todos-key-bindings)
2402 (define-key map (car ck) (cdr ck)))
2403 map)
2404 "Todos mode keymap.")
2405
2406 ;; FIXME
2407 (easy-menu-define
2408 todos-menu todos-mode-map "Todos Menu"
2409 '("Todos"
2410 ("Navigation"
2411 ["Next Item" todos-forward-item t]
2412 ["Previous Item" todos-backward-item t]
2413 "---"
2414 ["Next Category" todos-forward-category t]
2415 ["Previous Category" todos-backward-category t]
2416 ["Jump to Category" todos-jump-to-category t]
2417 ["Jump to Category in Other File" todos-jump-to-category-other-file t]
2418 "---"
2419 ["Search Todos File" todos-search t]
2420 ["Clear Highlighting on Search Matches" todos-category-done t])
2421 ("Display"
2422 ["List Current Categories" todos-display-categories t]
2423 ;; ["List Categories Alphabetically" todos-display-categories-alphabetically t]
2424 ["Turn Item Highlighting on/off" todos-highlight-item t]
2425 ["Turn Item Numbering on/off" todos-hide-show-item-numbering t]
2426 ["Turn Item Time Stamp on/off" todos-hide-show-date-time t]
2427 ["View/Hide Done Items" todos-hide-show-done-items t]
2428 "---"
2429 ["View Diary Items" todos-diary-items t]
2430 ["View Top Priority Items" todos-top-priorities t]
2431 ["View Multifile Top Priority Items" todos-top-priorities-multifile t]
2432 "---"
2433 ["Print Category" todos-print t])
2434 ("Editing"
2435 ["Insert New Item" todos-insert-item t]
2436 ["Insert Item Here" todos-insert-item-here t]
2437 ("More Insertion Commands")
2438 ["Edit Item" todos-edit-item t]
2439 ["Edit Multiline Item" todos-edit-multiline t]
2440 ["Edit Item Header" todos-edit-item-header t]
2441 ["Edit Item Date" todos-edit-item-date t]
2442 ["Edit Item Time" todos-edit-item-time t]
2443 "---"
2444 ["Lower Item Priority" todos-lower-item-priority t]
2445 ["Raise Item Priority" todos-raise-item-priority t]
2446 ["Set Item Priority" todos-set-item-priority t]
2447 ["Move (Recategorize) Item" todos-move-item t]
2448 ["Delete Item" todos-delete-item t]
2449 ["Undo Done Item" todos-item-undo t]
2450 ["Mark/Unmark Item for Diary" todos-toggle-item-diary-inclusion t]
2451 ["Mark/Unmark Items for Diary" todos-edit-item-diary-inclusion t]
2452 ["Mark & Hide Done Item" todos-item-done t]
2453 ["Archive Done Items" todos-archive-category-done-items t]
2454 "---"
2455 ["Add New Todos File" todos-add-file t]
2456 ["Add New Category" todos-add-category t]
2457 ["Delete Current Category" todos-delete-category t]
2458 ["Rename Current Category" todos-rename-category t]
2459 "---"
2460 ["Save Todos File" todos-save t]
2461 )
2462 "---"
2463 ["Quit" todos-quit t]
2464 ))
2465
2466 (defvar todos-archive-mode-map
2467 (let ((map (make-sparse-keymap)))
2468 (suppress-keymap map t)
2469 ;; navigation commands
2470 (define-key map "f" 'todos-forward-category)
2471 (define-key map "b" 'todos-backward-category)
2472 (define-key map "j" 'todos-jump-to-category)
2473 (define-key map "n" 'todos-forward-item)
2474 (define-key map "p" 'todos-backward-item)
2475 ;; display commands
2476 (define-key map "C" 'todos-display-categories)
2477 (define-key map "H" 'todos-highlight-item)
2478 (define-key map "N" 'todos-hide-show-item-numbering)
2479 ;; (define-key map "" 'todos-hide-show-date-time)
2480 (define-key map "P" 'todos-print)
2481 (define-key map "q" 'todos-quit)
2482 (define-key map "s" 'todos-save)
2483 (define-key map "S" 'todos-search)
2484 (define-key map "t" 'todos-show)
2485 (define-key map "u" 'todos-unarchive-items)
2486 (define-key map "U" 'todos-unarchive-category)
2487 map)
2488 "Todos Archive mode keymap.")
2489
2490 (defvar todos-edit-mode-map
2491 (let ((map (make-sparse-keymap)))
2492 (define-key map "\C-x\C-q" 'todos-edit-quit)
2493 (define-key map [remap newline] 'newline-and-indent)
2494 map)
2495 "Todos Edit mode keymap.")
2496
2497 (defvar todos-categories-mode-map
2498 (let ((map (make-sparse-keymap)))
2499 (suppress-keymap map t)
2500 (define-key map "c" 'todos-display-categories-alphabetically-or-by-priority)
2501 (define-key map "t" 'todos-display-categories-sorted-by-todo)
2502 (define-key map "y" 'todos-display-categories-sorted-by-diary)
2503 (define-key map "d" 'todos-display-categories-sorted-by-done)
2504 (define-key map "a" 'todos-display-categories-sorted-by-archived)
2505 (define-key map "l" 'todos-lower-category-priority)
2506 (define-key map "+" 'todos-lower-category-priority)
2507 (define-key map "r" 'todos-raise-category-priority)
2508 (define-key map "-" 'todos-raise-category-priority)
2509 (define-key map "n" 'forward-button)
2510 (define-key map "p" 'backward-button)
2511 (define-key map [tab] 'forward-button)
2512 (define-key map [backtab] 'backward-button)
2513 (define-key map "q" 'todos-quit)
2514 ;; (define-key map "A" 'todos-add-category)
2515 ;; (define-key map "D" 'todos-delete-category)
2516 ;; (define-key map "R" 'todos-rename-category)
2517 map)
2518 "Todos Categories mode keymap.")
2519
2520 (defvar todos-filtered-items-mode-map
2521 (let ((map (make-keymap)))
2522 (suppress-keymap map t)
2523 ;; navigation commands
2524 (define-key map "j" 'todos-jump-to-item)
2525 (define-key map [remap newline] 'todos-jump-to-item)
2526 (define-key map "n" 'todos-forward-item)
2527 (define-key map "p" 'todos-backward-item)
2528 (define-key map "H" 'todos-highlight-item)
2529 (define-key map "N" 'todos-hide-show-item-numbering)
2530 (define-key map "D" 'todos-hide-show-date-time)
2531 (define-key map "P" 'todos-print)
2532 (define-key map "q" 'todos-quit)
2533 (define-key map "s" 'todos-save)
2534 ;; editing commands
2535 (define-key map "l" 'todos-lower-item-priority)
2536 (define-key map "r" 'todos-raise-item-priority)
2537 (define-key map "#" 'todos-set-item-priority)
2538 map)
2539 "Todos Top Priorities mode keymap.")
2540
2541 ;; ---------------------------------------------------------------------------
2542 ;;; Mode definitions
2543
2544 (defun todos-modes-set-1 ()
2545 ""
2546 (set (make-local-variable 'font-lock-defaults) '(todos-font-lock-keywords t))
2547 (set (make-local-variable 'indent-line-function) 'todos-indent)
2548 (when todos-wrap-lines (funcall todos-line-wrapping-function)))
2549
2550 (defun todos-modes-set-2 ()
2551 ""
2552 (add-to-invisibility-spec 'todos)
2553 (setq buffer-read-only t)
2554 (set (make-local-variable 'hl-line-range-function)
2555 (lambda() (when (todos-item-end)
2556 (cons (todos-item-start) (todos-item-end))))))
2557
2558 (defun todos-modes-set-3 ()
2559 ""
2560 (set (make-local-variable 'todos-categories) (todos-set-categories))
2561 (set (make-local-variable 'todos-category-number) 1)
2562 (set (make-local-variable 'todos-first-visit) t)
2563 (add-hook 'find-file-hook 'todos-display-as-todos-file nil t))
2564
2565 (put 'todos-mode 'mode-class 'special)
2566
2567 (define-derived-mode todos-mode special-mode "Todos"
2568 "Major mode for displaying, navigating and editing Todo lists.
2569
2570 \\{todos-mode-map}"
2571 (easy-menu-add todos-menu)
2572 (todos-modes-set-1)
2573 (todos-modes-set-2)
2574 (todos-modes-set-3)
2575 ;; Initialize todos-current-todos-file.
2576 (when (member (file-truename (buffer-file-name))
2577 (funcall todos-files-function))
2578 (set (make-local-variable 'todos-current-todos-file)
2579 (file-truename (buffer-file-name))))
2580 (set (make-local-variable 'todos-first-visit) t)
2581 (set (make-local-variable 'todos-show-done-only) nil)
2582 (set (make-local-variable 'todos-categories-with-marks) nil)
2583 (add-hook 'find-file-hook 'todos-add-to-buffer-list nil t)
2584 (add-hook 'post-command-hook 'todos-update-buffer-list nil t)
2585 (when todos-show-current-file
2586 (add-hook 'pre-command-hook 'todos-show-current-file nil t))
2587 (add-hook 'window-configuration-change-hook
2588 'todos-reset-and-enable-done-separator nil t)
2589 (add-hook 'kill-buffer-hook 'todos-reset-global-current-todos-file nil t))
2590
2591 (defun todos-unload-hook ()
2592 ""
2593 (remove-hook 'pre-command-hook 'todos-show-current-file t)
2594 (remove-hook 'post-command-hook 'todos-update-buffer-list t)
2595 (remove-hook 'find-file-hook 'todos-display-as-todos-file t)
2596 (remove-hook 'find-file-hook 'todos-add-to-buffer-list t)
2597 (remove-hook 'window-configuration-change-hook
2598 'todos-reset-and-enable-done-separator t)
2599 (remove-hook 'kill-buffer-hook 'todos-reset-global-current-todos-file t))
2600
2601 (put 'todos-archive-mode 'mode-class 'special)
2602
2603 ;; If todos-mode is parent, all todos-mode key bindings appear to be
2604 ;; available in todos-archive-mode (e.g. shown by C-h m).
2605 (define-derived-mode todos-archive-mode special-mode "Todos-Arch"
2606 "Major mode for archived Todos categories.
2607
2608 \\{todos-archive-mode-map}"
2609 (todos-modes-set-1)
2610 (todos-modes-set-2)
2611 (todos-modes-set-3)
2612 (set (make-local-variable 'todos-current-todos-file)
2613 (file-truename (buffer-file-name)))
2614 (set (make-local-variable 'todos-show-done-only) t))
2615
2616 (defun todos-mode-external-set ()
2617 ""
2618 (set (make-local-variable 'todos-current-todos-file)
2619 todos-global-current-todos-file)
2620 (let ((cats (with-current-buffer
2621 (find-buffer-visiting todos-current-todos-file)
2622 todos-categories)))
2623 (set (make-local-variable 'todos-categories) cats)))
2624
2625 (define-derived-mode todos-edit-mode text-mode "Todos-Ed"
2626 "Major mode for editing multiline Todo items.
2627
2628 \\{todos-edit-mode-map}"
2629 (todos-modes-set-1)
2630 (todos-mode-external-set))
2631
2632 (put 'todos-categories-mode 'mode-class 'special)
2633
2634 (define-derived-mode todos-categories-mode special-mode "Todos-Cats"
2635 "Major mode for displaying and editing Todos categories.
2636
2637 \\{todos-categories-mode-map}"
2638 (todos-mode-external-set))
2639
2640 (put 'todos-filter-mode 'mode-class 'special)
2641
2642 (define-derived-mode todos-filtered-items-mode special-mode "Todos-Fltr"
2643 "Mode for displaying and reprioritizing top priority Todos.
2644
2645 \\{todos-filtered-items-mode-map}"
2646 (todos-modes-set-1)
2647 (todos-modes-set-2))
2648
2649 ;; ---------------------------------------------------------------------------
2650 ;;; Todos Commands
2651
2652 ;; ---------------------------------------------------------------------------
2653 ;;; Entering and Exiting
2654
2655 ;;;###autoload
2656 (defun todos-show (&optional solicit-file)
2657 "Visit the current Todos file and display one of its categories.
2658 With non-nil prefix argument SOLICIT-FILE prompt for which todo
2659 file to visit.
2660
2661 Without a prefix argument, the first invocation of this command
2662 in a session visits `todos-default-todos-file' (creating it if it
2663 does not yet exist); subsequent invocations from outside of Todos
2664 mode revisit this file or, if the user option
2665 `todos-show-current-file' is non-nil, whichever Todos file
2666 \(either a todo or an archive file) was visited last.
2667
2668 The category displayed on initial invocation is the first member
2669 of `todos-categories' for the current Todos file, on subsequent
2670 invocations whichever category was displayed last. If
2671 `todos-display-categories-first' is non-nil, then the first
2672 invocation of `todos-show' displays a clickable listing of the
2673 categories in the current Todos file.
2674
2675 In Todos mode just the category's unfinished todo items are shown
2676 by default. The done items are hidden, but typing
2677 `\\[todos-hide-show-done-items]' displays them below the todo
2678 items. With non-nil user option `todos-show-with-done' both todo
2679 and done items are always shown on visiting a category.
2680
2681 If this command is invoked in Todos Archive mode, it visits the
2682 corresponding Todos file, displaying the corresponding category."
2683 (interactive "P")
2684 (let* ((cat)
2685 (file (cond (solicit-file
2686 (if (funcall todos-files-function)
2687 (todos-read-file-name "Choose a Todos file to visit: "
2688 nil t)
2689 (error "There are no Todos files")))
2690 ((and (eq major-mode 'todos-archive-mode)
2691 ;; Called noninteractively via todos-quit from
2692 ;; Todos Categories mode to return to archive file.
2693 (called-interactively-p 'any))
2694 (setq cat (todos-current-category))
2695 (concat (file-name-sans-extension todos-current-todos-file)
2696 ".todo"))
2697 (t
2698 (or todos-current-todos-file
2699 (and todos-show-current-file
2700 todos-global-current-todos-file)
2701 todos-default-todos-file
2702 (todos-add-file))))))
2703 (if (and todos-first-visit todos-display-categories-first)
2704 (todos-display-categories)
2705 (set-window-buffer (selected-window)
2706 (set-buffer (find-file-noselect file)))
2707 ;; If called from archive file, show corresponding category in Todos
2708 ;; file, if it exists.
2709 (when (assoc cat todos-categories)
2710 (setq todos-category-number (todos-category-number cat)))
2711 ;; If no Todos file exists, initialize one.
2712 (when (zerop (buffer-size))
2713 ;; Call with empty category name to get initial prompt.
2714 (setq todos-category-number (todos-add-category "")))
2715 (save-excursion (todos-category-select)))
2716 (setq todos-first-visit nil)))
2717
2718 (defun todos-display-categories ()
2719 "Display a table of the current file's categories and item counts.
2720
2721 In the initial display the categories are numbered, indicating
2722 their current order for navigating by \\[todos-forward-category]
2723 and \\[todos-backward-category]. You can persistantly change the
2724 order of the category at point by typing
2725 \\[todos-raise-category-priority] or
2726 \\[todos-lower-category-priority].
2727
2728 The labels above the category names and item counts are buttons,
2729 and clicking these changes the display: sorted by category name
2730 or by the respective item counts (alternately descending or
2731 ascending). In these displays the categories are not numbered
2732 and \\[todos-raise-category-priority] and
2733 \\[todos-lower-category-priority] are
2734 disabled. (Programmatically, the sorting is triggered by passing
2735 a non-nil SORTKEY argument.)
2736
2737 In addition, the lines with the category names and item counts
2738 are buttonized, and pressing one of these button jumps to the
2739 category in Todos mode (or Todos Archive mode, for categories
2740 containing only archived items, provided user option
2741 `todos-skip-archived-categories' is non-nil. These categories
2742 are shown in `todos-archived-only' face."
2743 (interactive)
2744 (todos-display-categories-1)
2745 (let (sortkey)
2746 (todos-update-categories-display sortkey)))
2747
2748 (defun todos-display-categories-alphabetically-or-by-priority ()
2749 ""
2750 (interactive)
2751 (save-excursion
2752 (goto-char (point-min))
2753 (forward-line 2)
2754 (if (member 'alpha todos-descending-counts)
2755 (progn
2756 (todos-update-categories-display nil)
2757 (setq todos-descending-counts
2758 (delete 'alpha todos-descending-counts)))
2759 (todos-update-categories-display 'alpha))))
2760
2761 (defun todos-display-categories-sorted-by-todo ()
2762 ""
2763 (interactive)
2764 (save-excursion
2765 (goto-char (point-min))
2766 (forward-line 2)
2767 (todos-update-categories-display 'todo)))
2768
2769 (defun todos-display-categories-sorted-by-diary ()
2770 ""
2771 (interactive)
2772 (save-excursion
2773 (goto-char (point-min))
2774 (forward-line 2)
2775 (todos-update-categories-display 'diary)))
2776
2777 (defun todos-display-categories-sorted-by-done ()
2778 ""
2779 (interactive)
2780 (save-excursion
2781 (goto-char (point-min))
2782 (forward-line 2)
2783 (todos-update-categories-display 'done)))
2784
2785 (defun todos-display-categories-sorted-by-archived ()
2786 ""
2787 (interactive)
2788 (save-excursion
2789 (goto-char (point-min))
2790 (forward-line 2)
2791 (todos-update-categories-display 'archived)))
2792
2793 (defun todos-show-archive (&optional ask)
2794 "Visit the archive of the current Todos category, if it exists.
2795 If the category has no archived items, prompt to visit the
2796 archive anyway. If there is no archive for this file or with
2797 non-nil argument ASK, prompt to visit another archive.
2798
2799 The buffer showing the archive is in Todos Archive mode. The
2800 first visit in a session displays the first category in the
2801 archive, subsequent visits return to the last category
2802 displayed."
2803 (interactive)
2804 (let* ((cat (todos-current-category))
2805 (count (todos-get-count 'archived cat))
2806 (archive (concat (file-name-sans-extension todos-current-todos-file)
2807 ".toda"))
2808 place)
2809 (setq place (cond (ask 'other-archive)
2810 ((file-exists-p archive) 'this-archive)
2811 (t (when (y-or-n-p (concat "This file has no archive; "
2812 "visit another archive? "))
2813 'other-archive))))
2814 (when (eq place 'other-archive)
2815 (setq archive (todos-read-file-name "Choose a Todos archive: " t t)))
2816 (when (and (eq place 'this-archive) (zerop count))
2817 (setq place (when (y-or-n-p
2818 (concat "This category has no archived items;"
2819 " visit archive anyway? "))
2820 'other-cat)))
2821 (when place
2822 (set-window-buffer (selected-window)
2823 (set-buffer (find-file-noselect archive)))
2824 (if (member place '(other-archive other-cat))
2825 (setq todos-category-number 1)
2826 (todos-category-number cat))
2827 (todos-category-select))))
2828
2829 (defun todos-choose-archive ()
2830 "Choose an archive and visit it."
2831 (interactive)
2832 (todos-show-archive t))
2833
2834 ;; FIXME: need this?
2835 (defun todos-save ()
2836 "Save the current Todos file."
2837 (interactive)
2838 (save-buffer))
2839
2840 (defun todos-quit ()
2841 "Exit the current Todos-related buffer.
2842 Depending on the specific mode, this either kills the buffer or
2843 buries it and restores state as needed."
2844 (interactive)
2845 (cond ((eq major-mode 'todos-categories-mode)
2846 (kill-buffer)
2847 (setq todos-descending-counts nil)
2848 (todos-show))
2849 ((eq major-mode 'todos-filtered-items-mode)
2850 (kill-buffer)
2851 (todos-show))
2852 ((member major-mode (list 'todos-mode 'todos-archive-mode))
2853 ;; Have to write previously nonexistant archives to file, and might
2854 ;; as well save Todos file also.
2855 (todos-save)
2856 (bury-buffer))))
2857
2858 (defun todos-print (&optional to-file)
2859 "Produce a printable version of the current Todos buffer.
2860 This converts overlays and soft line wrapping and, depending on
2861 the value of `todos-print-function', includes faces. With
2862 non-nil argument TO-FILE write the printable version to a file;
2863 otherwise, send it to the default printer."
2864 (interactive)
2865 (let ((buf todos-print-buffer)
2866 (header (cond
2867 ((eq major-mode 'todos-mode)
2868 (concat "Todos File: "
2869 (todos-short-file-name todos-current-todos-file)
2870 "\nCategory: " (todos-current-category)))
2871 ((eq major-mode 'todos-filtered-items-mode)
2872 "Todos Top Priorities")))
2873 (prefix (propertize (concat todos-prefix " ")
2874 'face 'todos-prefix-string))
2875 (num 0)
2876 (fill-prefix (make-string todos-indent-to-here 32))
2877 (content (buffer-string))
2878 file)
2879 (with-current-buffer (get-buffer-create buf)
2880 (insert content)
2881 (goto-char (point-min))
2882 (while (not (eobp))
2883 (let ((beg (point))
2884 (end (save-excursion (todos-item-end))))
2885 (when todos-number-priorities
2886 (setq num (1+ num))
2887 (setq prefix (propertize (concat (number-to-string num) " ")
2888 'face 'todos-prefix-string)))
2889 (insert prefix)
2890 (fill-region beg end))
2891 ;; Calling todos-forward-item infloops at todos-item-start due to
2892 ;; non-overlay prefix, so search for item start instead.
2893 (if (re-search-forward todos-item-start nil t)
2894 (beginning-of-line)
2895 (goto-char (point-max))))
2896 (if (re-search-backward (concat "^" (regexp-quote todos-category-done))
2897 nil t)
2898 (replace-match todos-done-separator))
2899 (goto-char (point-min))
2900 (insert header)
2901 (newline 2)
2902 (if to-file
2903 (let ((file (read-file-name "Print to file: ")))
2904 (funcall todos-print-function file))
2905 (funcall todos-print-function)))
2906 (kill-buffer buf)))
2907
2908 (defun todos-print-to-file ()
2909 "Save printable version of this Todos buffer to a file."
2910 (interactive)
2911 (todos-print t))
2912
2913 (defun todos-convert-legacy-files ()
2914 "Convert legacy Todo files to the current Todos format.
2915 The files `todo-file-do' and `todo-file-done' are converted and
2916 saved (the latter as a Todos Archive file) with a new name in
2917 `todos-files-directory'. See also the documentation string of
2918 `todos-todo-mode-date-time-regexp' for further details."
2919 (interactive)
2920 (if (fboundp 'todo-mode)
2921 (require 'todo-mode)
2922 (error "Void function `todo-mode'"))
2923 ;; Convert `todo-file-do'.
2924 (if (file-exists-p todo-file-do)
2925 (let ((default "todo-do-conv")
2926 file archive-sexp)
2927 (with-temp-buffer
2928 (insert-file-contents todo-file-do)
2929 (let ((end (search-forward ")" (line-end-position) t))
2930 (beg (search-backward "(" (line-beginning-position) t)))
2931 (setq todo-categories
2932 (read (buffer-substring-no-properties beg end))))
2933 (todo-mode)
2934 (delete-region (line-beginning-position) (1+ (line-end-position)))
2935 (while (not (eobp))
2936 (cond
2937 ((looking-at (regexp-quote (concat todo-prefix todo-category-beg)))
2938 (replace-match todos-category-beg))
2939 ((looking-at (regexp-quote todo-category-end))
2940 (replace-match ""))
2941 ((looking-at (regexp-quote (concat todo-prefix " "
2942 todo-category-sep)))
2943 (replace-match todos-category-done))
2944 ((looking-at (concat (regexp-quote todo-prefix) " "
2945 todos-todo-mode-date-time-regexp " "
2946 (regexp-quote todo-initials) ":"))
2947 (todos-convert-legacy-date-time)))
2948 (forward-line))
2949 (setq file (concat todos-files-directory
2950 (read-string
2951 (format "Save file as (default \"%s\"): " default)
2952 nil nil default)
2953 ".todo"))
2954 (write-region (point-min) (point-max) file nil 'nomessage nil t))
2955 (with-temp-buffer
2956 (insert-file-contents file)
2957 (let ((todos-categories (todos-make-categories-list t)))
2958 (todos-update-categories-sexp))
2959 (write-region (point-min) (point-max) file nil 'nomessage))
2960 ;; Convert `todo-file-done'.
2961 (when (file-exists-p todo-file-done)
2962 (with-temp-buffer
2963 (insert-file-contents todo-file-done)
2964 (let ((beg (make-marker))
2965 (end (make-marker))
2966 cat cats comment item)
2967 (while (not (eobp))
2968 (when (looking-at todos-todo-mode-date-time-regexp)
2969 (set-marker beg (point))
2970 (todos-convert-legacy-date-time)
2971 (set-marker end (point))
2972 (goto-char beg)
2973 (insert "[" todos-done-string)
2974 (goto-char end)
2975 (insert "]")
2976 (forward-char)
2977 (when (looking-at todos-todo-mode-date-time-regexp)
2978 (todos-convert-legacy-date-time))
2979 (when (looking-at (concat " " (regexp-quote todo-initials) ":"))
2980 (replace-match "")))
2981 (if (re-search-forward
2982 (concat "^" todos-todo-mode-date-time-regexp) nil t)
2983 (goto-char (match-beginning 0))
2984 (goto-char (point-max)))
2985 (backward-char)
2986 (when (looking-back "\\[\\([^][]+\\)\\]")
2987 (setq cat (match-string 1))
2988 (goto-char (match-beginning 0))
2989 (replace-match ""))
2990 ;; If the item ends with a non-comment parenthesis not
2991 ;; followed by a period, we lose (but we inherit that problem
2992 ;; from todo-mode.el).
2993 (when (looking-back "(\\(.*\\)) ")
2994 (setq comment (match-string 1))
2995 (replace-match "")
2996 (insert "[" todos-comment-string ": " comment "]"))
2997 (set-marker end (point))
2998 (if (member cat cats)
2999 ;; If item is already in its category, leave it there.
3000 (unless (save-excursion
3001 (re-search-backward
3002 (concat "^" (regexp-quote todos-category-beg)
3003 "\\(.*\\)$") nil t)
3004 (string= (match-string 1) cat))
3005 ;; Else move it to its category.
3006 (setq item (buffer-substring-no-properties beg end))
3007 (delete-region beg (1+ end))
3008 (set-marker beg (point))
3009 (re-search-backward
3010 (concat "^" (regexp-quote (concat todos-category-beg cat)))
3011 nil t)
3012 (forward-line)
3013 (if (re-search-forward
3014 (concat "^" (regexp-quote todos-category-beg)
3015 "\\(.*\\)$") nil t)
3016 (progn (goto-char (match-beginning 0))
3017 (newline)
3018 (forward-line -1))
3019 (goto-char (point-max)))
3020 (insert item "\n")
3021 (goto-char beg))
3022 (push cat cats)
3023 (goto-char beg)
3024 (insert todos-category-beg cat "\n\n" todos-category-done "\n"))
3025 (forward-line))
3026 (set-marker beg nil)
3027 (set-marker end nil))
3028 (setq file (concat (file-name-sans-extension file) ".toda"))
3029 (write-region (point-min) (point-max) file nil 'nomessage nil t))
3030 (with-temp-buffer
3031 (insert-file-contents file)
3032 (let ((todos-categories (todos-make-categories-list t)))
3033 (todos-update-categories-sexp))
3034 (write-region (point-min) (point-max) file nil 'nomessage)
3035 (setq archive-sexp (read (buffer-substring-no-properties
3036 (line-beginning-position)
3037 (line-end-position)))))
3038 (setq file (concat (file-name-sans-extension file) ".todo"))
3039 ;; Update categories sexp of converted Todos file again, adding
3040 ;; counts of archived items.
3041 (with-temp-buffer
3042 (insert-file-contents file)
3043 (let ((sexp (read (buffer-substring-no-properties
3044 (line-beginning-position)
3045 (line-end-position)))))
3046 (dolist (cat sexp)
3047 (let ((archive-cat (assoc (car cat) archive-sexp)))
3048 (if archive-cat
3049 (aset (cdr cat) 3 (aref (cdr archive-cat) 2)))))
3050 (delete-region (line-beginning-position) (line-end-position))
3051 (prin1 sexp (current-buffer)))
3052 (write-region (point-min) (point-max) file nil 'nomessage)))
3053 (todos-reevaluate-defcustoms)
3054 (message "Format conversion done."))
3055 (error "No legacy Todo file exists")))
3056
3057 ;; ---------------------------------------------------------------------------
3058 ;;; Navigation Commands
3059
3060 (defun todos-forward-category (&optional back)
3061 "Visit the numerically next category in this Todos file.
3062 If the current category is the highest numbered, visit the first
3063 category. With non-nil argument BACK, visit the numerically
3064 previous category (the highest numbered one, if the current
3065 category is the first)."
3066 (interactive)
3067 (setq todos-category-number
3068 (1+ (mod (- todos-category-number (if back 2 0))
3069 (length todos-categories))))
3070 (when todos-skip-archived-categories
3071 (while (and (zerop (todos-get-count 'todo))
3072 (zerop (todos-get-count 'done))
3073 (not (zerop (todos-get-count 'archive))))
3074 (setq todos-category-number
3075 (apply (if back '1- '1+) (list todos-category-number)))))
3076 (todos-category-select)
3077 (goto-char (point-min)))
3078
3079 (defun todos-backward-category ()
3080 "Visit the numerically previous category in this Todos file.
3081 If the current category is the highest numbered, visit the first
3082 category."
3083 (interactive)
3084 (todos-forward-category t))
3085
3086 (defun todos-jump-to-category (&optional cat other-file)
3087 "Jump to a category in this or another Todos file.
3088
3089 Programmatically, optional argument CAT provides the category
3090 name. When nil (as in interactive calls), prompt for the
3091 category, with TAB completion on existing categories. If a
3092 non-existing category name is entered, ask whether to add a new
3093 category with this name; if affirmed, add it, then jump to that
3094 category. With non-nil argument OTHER-FILE, prompt for a Todos
3095 file, otherwise jump within the current Todos file."
3096 (interactive)
3097 (let ((file (or (and other-file
3098 (todos-read-file-name "Choose a Todos file: " nil t))
3099 ;; Jump to archived-only Categories from Todos Categories
3100 ;; mode.
3101 (and cat
3102 todos-skip-archived-categories
3103 (zerop (todos-get-count 'todo cat))
3104 (zerop (todos-get-count 'done cat))
3105 (not (zerop (todos-get-count 'archived cat)))
3106 (concat (file-name-sans-extension
3107 todos-current-todos-file) ".toda"))
3108 todos-current-todos-file
3109 ;; If invoked from outside of Todos mode before
3110 ;; todos-show...
3111 todos-default-todos-file)))
3112 (with-current-buffer (find-file-noselect file)
3113 (and other-file (setq todos-current-todos-file file))
3114 (let ((category (or (and (assoc cat todos-categories) cat)
3115 (todos-read-category "Jump to category: "))))
3116 ;; Clean up after selecting category in Todos Categories mode.
3117 (if (string= (buffer-name) todos-categories-buffer)
3118 (kill-buffer))
3119 (if (or cat other-file)
3120 (set-window-buffer (selected-window)
3121 (set-buffer (find-buffer-visiting file))))
3122 (unless todos-global-current-todos-file
3123 (setq todos-global-current-todos-file todos-current-todos-file))
3124 (todos-category-number category) ; (1+ (length t-c)) if new category.
3125 ;; (if (> todos-category-number (length todos-categories))
3126 ;; (setq todos-category-number (todos-add-category category)))
3127 (todos-category-select)
3128 (goto-char (point-min))))))
3129
3130 (defun todos-jump-to-category-other-file ()
3131 "Jump to a category in another Todos file.
3132 The category is chosen by prompt, with TAB completion."
3133 (interactive)
3134 (todos-jump-to-category nil t))
3135
3136 (defun todos-jump-to-item ()
3137 "Jump to the file and category of the filtered item at point."
3138 (interactive)
3139 (let ((str (todos-item-string))
3140 (buf (current-buffer))
3141 cat file archive beg)
3142 (string-match (concat (if todos-filter-done-items
3143 (concat "\\(?:" todos-done-string-start "\\|"
3144 todos-date-string-start "\\)")
3145 todos-date-string-start)
3146 todos-date-pattern "\\(?: " diary-time-regexp "\\)?"
3147 (if todos-filter-done-items
3148 "\\]"
3149 (regexp-quote todos-nondiary-end)) "?"
3150 "\\(?4: \\[\\(?3:(archive) \\)?\\(?2:.*:\\)?"
3151 "\\(?1:.*\\)\\]\\).*$") str)
3152 (setq cat (match-string 1 str))
3153 (setq file (match-string 2 str))
3154 (setq archive (string= (match-string 3 str) "(archive) "))
3155 (setq str (replace-match "" nil nil str 4))
3156 (setq file (if file
3157 (concat todos-files-directory (substring file 0 -1)
3158 (if archive ".toda" ".todo"))
3159 (if archive
3160 (concat (file-name-sans-extension
3161 todos-global-current-todos-file) ".toda")
3162 todos-global-current-todos-file)))
3163 (find-file-noselect file)
3164 (with-current-buffer (find-buffer-visiting file)
3165 (widen)
3166 (goto-char (point-min))
3167 (re-search-forward
3168 (concat "^" (regexp-quote (concat todos-category-beg cat))) nil t)
3169 (search-forward str)
3170 (setq beg (match-beginning 0)))
3171 (kill-buffer buf)
3172 (set-window-buffer (selected-window) (set-buffer (find-buffer-visiting file)))
3173 (setq todos-current-todos-file file)
3174 (setq todos-category-number (todos-category-number cat))
3175 (let ((todos-show-with-done (if todos-filter-done-items t
3176 todos-show-with-done)))
3177 (todos-category-select))
3178 (goto-char beg)))
3179
3180 (defun todos-forward-item (&optional count)
3181 "Move point down to start of item with next lower priority.
3182 With positive numerical prefix COUNT, move point COUNT items
3183 downward."
3184 (interactive "P")
3185 ;; It's not worth the trouble to allow prefix arg value < 1, since we have
3186 ;; the corresponding command.
3187 (if (and count (> 1 count))
3188 (error "This command only accepts a positive numerical prefix argument")
3189 (let* ((not-done (not (or (todos-done-item-p) (looking-at "^$"))))
3190 (start (line-end-position)))
3191 (goto-char start)
3192 (if (re-search-forward todos-item-start nil t (or count 1))
3193 (goto-char (match-beginning 0))
3194 (goto-char (point-max)))
3195 ;; If points advances by one from a todo to a done item, go back to the
3196 ;; space above todos-done-separator, since that is a legitimate place to
3197 ;; insert an item. But skip this space if count > 1, since that should
3198 ;; only stop on an item.
3199 (when (and not-done (todos-done-item-p))
3200 (if (or (not count) (= count 1))
3201 (re-search-backward "^$" start t))))))
3202 ;; FIXME: The preceding sexp is insufficient when buffer is not narrowed,
3203 ;; since there could be no done items in this category, so the search puts
3204 ;; us on first todo item of next category. Does this ever happen? If so:
3205 ;; (let ((opoint) (point))
3206 ;; (forward-line -1)
3207 ;; (when (or (not count) (= count 1))
3208 ;; (cond ((looking-at (concat "^" (regexp-quote todos-category-beg)))
3209 ;; (forward-line -2))
3210 ;; ((looking-at (concat "^" (regexp-quote todos-category-done)))
3211 ;; (forward-line -1))
3212 ;; (t
3213 ;; (goto-char opoint)))))))
3214
3215 (defun todos-backward-item (&optional count)
3216 "Move point up to start of item with next higher priority.
3217 With positive numerical prefix COUNT, move point COUNT items
3218 upward."
3219 (interactive "P")
3220 ;; Avoid moving to bob if on the first item but not at bob.
3221 (when (> (line-number-at-pos) 1)
3222 ;; It's not worth the trouble to allow prefix arg value < 1, since we have
3223 ;; the corresponding command.
3224 (if (and count (> 1 count))
3225 (error "This command only accepts a positive numerical prefix argument")
3226 (let* ((done (todos-done-item-p)))
3227 (todos-item-start)
3228 (unless (bobp)
3229 (re-search-backward todos-item-start nil t (or count 1)))
3230 ;; Unless this is a regexp filtered items buffer (which can contain
3231 ;; intermixed todo and done items), if points advances by one from a
3232 ;; done to a todo item, go back to the space above
3233 ;; todos-done-separator, since that is a legitimate place to insert an
3234 ;; item. But skip this space if count > 1, since that should only
3235 ;; stop on an item.
3236 (when (and done (not (todos-done-item-p)) (or (not count) (= count 1))
3237 (not (equal (buffer-name) todos-regexp-items-buffer)))
3238 (re-search-forward (concat "^" (regexp-quote todos-category-done))
3239 nil t)
3240 (forward-line -1))))))
3241
3242 ;; FIXME: (i) Extend search to other Todos files. (ii) Allow navigating among
3243 ;; hits. (But these features are effectively available with
3244 ;; todos-regexp-items-multifile, so maybe it's not worth the trouble here.)
3245 (defun todos-search ()
3246 "Search for a regular expression in this Todos file.
3247 The search runs through the whole file and encompasses all and
3248 only todo and done items; it excludes category names. Multiple
3249 matches are shown sequentially, highlighted in `todos-search'
3250 face."
3251 (interactive)
3252 (let ((regex (read-from-minibuffer "Enter a search string (regexp): "))
3253 (opoint (point))
3254 matches match cat in-done ov mlen msg)
3255 (widen)
3256 (goto-char (point-min))
3257 (while (not (eobp))
3258 (setq match (re-search-forward regex nil t))
3259 (goto-char (line-beginning-position))
3260 (unless (or (equal (point) 1)
3261 (looking-at (concat "^" (regexp-quote todos-category-beg))))
3262 (if match (push match matches)))
3263 (forward-line))
3264 (setq matches (reverse matches))
3265 (if matches
3266 (catch 'stop
3267 (while matches
3268 (setq match (pop matches))
3269 (goto-char match)
3270 (todos-item-start)
3271 (when (looking-at todos-done-string-start)
3272 (setq in-done t))
3273 (re-search-backward (concat "^" (regexp-quote todos-category-beg)
3274 "\\(.*\\)\n") nil t)
3275 (setq cat (match-string-no-properties 1))
3276 (todos-category-number cat)
3277 (todos-category-select)
3278 (if in-done
3279 (unless todos-show-with-done (todos-hide-show-done-items)))
3280 (goto-char match)
3281 (setq ov (make-overlay (- (point) (length regex)) (point)))
3282 (overlay-put ov 'face 'todos-search)
3283 (when matches
3284 (setq mlen (length matches))
3285 (if (y-or-n-p
3286 (if (> mlen 1)
3287 (format "There are %d more matches; go to next match? "
3288 mlen)
3289 "There is one more match; go to it? "))
3290 (widen)
3291 (throw 'stop (setq msg (if (> mlen 1)
3292 (format "There are %d more matches."
3293 mlen)
3294 "There is one more match."))))))
3295 (setq msg "There are no more matches."))
3296 (todos-category-select)
3297 (goto-char opoint)
3298 (message "No match for \"%s\"" regex))
3299 (when msg
3300 (if (y-or-n-p (concat msg "\nUnhighlight matches? "))
3301 (todos-clear-matches)
3302 (message "You can unhighlight the matches later by typing %s"
3303 (key-description (car (where-is-internal
3304 'todos-clear-matches))))))))
3305
3306 (defun todos-clear-matches ()
3307 "Remove highlighting on matches found by todos-search."
3308 (interactive)
3309 (remove-overlays 1 (1+ (buffer-size)) 'face 'todos-search))
3310
3311 ;; ---------------------------------------------------------------------------
3312 ;;; Display Commands
3313
3314 (defun todos-hide-show-item-numbering ()
3315 ""
3316 (interactive)
3317 (todos-reset-prefix 'todos-number-priorities (not todos-number-priorities)))
3318
3319 (defun todos-hide-show-done-items ()
3320 "Show hidden or hide visible done items in current category."
3321 (interactive)
3322 (if (zerop (todos-get-count 'done (todos-current-category)))
3323 (message "There are no done items in this category.")
3324 (save-excursion
3325 (goto-char (point-min))
3326 (let ((todos-show-with-done (not (re-search-forward
3327 todos-done-string-start nil t))))
3328 (todos-category-select)))))
3329
3330 (defun todos-show-done-only ()
3331 "Switch between displaying only done or only todo items."
3332 (interactive)
3333 (setq todos-show-done-only (not todos-show-done-only))
3334 (todos-category-select))
3335
3336 (defun todos-highlight-item ()
3337 "Highlight or unhighlight the todo item the cursor is on."
3338 (interactive)
3339 (require 'hl-line)
3340 (if hl-line-mode
3341 (hl-line-mode -1)
3342 (hl-line-mode 1)))
3343
3344 (defun todos-hide-show-date-time ()
3345 "Hide or show date-time header of todo items in the current file."
3346 (interactive)
3347 (save-excursion
3348 (save-restriction
3349 (goto-char (point-min))
3350 (let ((ovs (overlays-in (point) (1+ (point))))
3351 ov hidden)
3352 (while ovs
3353 (setq ov (pop ovs))
3354 (if (equal (overlay-get ov 'display) "")
3355 (setq ovs nil hidden t)))
3356 (widen)
3357 (goto-char (point-min))
3358 (if hidden
3359 (remove-overlays (point-min) (point-max) 'display "")
3360 (while (not (eobp))
3361 (when (re-search-forward
3362 (concat todos-date-string-start todos-date-pattern
3363 "\\( " diary-time-regexp "\\)?"
3364 (regexp-quote todos-nondiary-end) "? ")
3365 nil t)
3366 (unless (save-match-data (todos-done-item-p))
3367 (setq ov (make-overlay (match-beginning 0) (match-end 0) nil t))
3368 (overlay-put ov 'display "")))
3369 (todos-forward-item)))))))
3370
3371 (defun todos-mark-unmark-item (&optional n all)
3372 "Mark item at point if unmarked, or unmark it if marked.
3373
3374 With a positive numerical prefix argument N, change the
3375 markedness of the next N items. With non-nil argument ALL, mark
3376 all visible items in the category (depending on visibility, all
3377 todo and done items, or just todo or just done items).
3378
3379 The mark is the character \"*\" inserted in front of the item's
3380 priority number or the `todos-prefix' string; if `todos-prefix'
3381 is \"*\", then the mark is \"@\"."
3382 (interactive "p")
3383 (if all (goto-char (point-min)))
3384 (unless (> n 0) (setq n 1))
3385 (let ((i 0))
3386 (while (or (and all (not (eobp)))
3387 (< i n))
3388 (let* ((cat (todos-current-category))
3389 (ov (todos-marked-item-p))
3390 (marked (assoc cat todos-categories-with-marks)))
3391 (if (and ov (not all))
3392 (progn
3393 (delete-overlay ov)
3394 (if (= (cdr marked) 1) ; Deleted last mark in this category.
3395 (setq todos-categories-with-marks
3396 (assq-delete-all cat todos-categories-with-marks))
3397 (setcdr marked (1- (cdr marked)))))
3398 (when (todos-item-start)
3399 (unless (and all (todos-marked-item-p))
3400 (setq ov (make-overlay (point) (point)))
3401 (overlay-put ov 'before-string todos-item-mark)
3402 (if marked
3403 (setcdr marked (1+ (cdr marked)))
3404 (push (cons cat 1) todos-categories-with-marks))))))
3405 (todos-forward-item)
3406 (setq i (1+ i)))))
3407
3408 (defun todos-mark-category ()
3409 "Put the \"*\" mark on all items in this category.
3410 \(If `todos-prefix' is \"*\", then the mark is \"@\".)"
3411 (interactive)
3412 (todos-mark-unmark-item 0 t))
3413
3414 (defun todos-unmark-category ()
3415 "Remove the \"*\" mark from all items in this category.
3416 \(If `todos-prefix' is \"*\", then the mark is \"@\".)"
3417 (interactive)
3418 (remove-overlays (point-min) (point-max) 'before-string todos-item-mark)
3419 (setq todos-categories-with-marks
3420 (delq (assoc (todos-current-category) todos-categories-with-marks)
3421 todos-categories-with-marks)))
3422
3423 ;; ---------------------------------------------------------------------------
3424 ;;; Item filtering commands
3425
3426 (defun todos-set-top-priorities-in-file ()
3427 "Set number of top priorities for this file.
3428 See `todos-set-top-priorities' for more details."
3429 (interactive)
3430 (todos-set-top-priorities))
3431
3432 (defun todos-set-top-priorities-in-category ()
3433 "Set number of top priorities for this category.
3434 See `todos-set-top-priorities' for more details."
3435 (interactive)
3436 (todos-set-top-priorities t))
3437
3438 (defun todos-top-priorities (&optional num)
3439 "List top priorities of each category in `todos-filter-files'.
3440 Number of entries for each category is given by NUM, which
3441 defaults to `todos-show-priorities'."
3442 (interactive "P")
3443 (let ((arg (if num (cons 'top num) 'top))
3444 (buf todos-top-priorities-buffer)
3445 (file todos-current-todos-file))
3446 (todos-filter-items arg)
3447 (todos-filtered-buffer-name buf file)))
3448
3449 (defun todos-top-priorities-multifile (&optional arg)
3450 "List top priorities of each category in `todos-filter-files'.
3451
3452 If the prefix argument ARG is a number, this is the maximum
3453 number of top priorities to list in each category. If the prefix
3454 argument is `C-u', prompt for which files to filter and use
3455 `todos-show-priorities' as the number of top priorities to list
3456 in each category. If the prefix argument is `C-uC-u', prompt
3457 both for which files to filter and for how many top priorities to
3458 list in each category."
3459 (interactive "P")
3460 (let* ((buf todos-top-priorities-buffer)
3461 files
3462 (pref (if (numberp arg)
3463 (cons 'top arg)
3464 (setq files (if (or (consp arg)
3465 (null todos-filter-files))
3466 (progn (todos-multiple-filter-files)
3467 todos-multiple-filter-files)
3468 todos-filter-files))
3469 (if (equal arg '(16))
3470 (cons 'top (read-number
3471 "Enter number of top priorities to show: "
3472 todos-show-priorities))
3473 'top))))
3474 (todos-filter-items pref t)
3475 (todos-filtered-buffer-name buf files)))
3476
3477 (defun todos-diary-items ()
3478 "Display todo items for diary inclusion in this Todos file."
3479 (interactive)
3480 (let ((buf todos-diary-items-buffer)
3481 (file todos-current-todos-file))
3482 (todos-filter-items 'diary)
3483 (todos-filtered-buffer-name buf file)))
3484
3485 (defun todos-diary-items-multifile (&optional arg)
3486 "Display todo items for diary inclusion in one or more Todos file.
3487 The files are those listed in `todos-filter-files'."
3488 (interactive "P")
3489 (let ((buf todos-diary-items-buffer)
3490 (files (if (or arg (null todos-filter-files))
3491 (progn (todos-multiple-filter-files)
3492 todos-multiple-filter-files)
3493 todos-filter-files)))
3494 (todos-filter-items 'diary t)
3495 (todos-filtered-buffer-name buf files)))
3496
3497 (defun todos-regexp-items ()
3498 "Display todo items matching a user-entered regular expression.
3499 The items are those in the current Todos file."
3500 (interactive)
3501 (let ((buf todos-regexp-items-buffer)
3502 (file todos-current-todos-file))
3503 (todos-filter-items 'regexp)
3504 (todos-filtered-buffer-name buf file)))
3505
3506 (defun todos-regexp-items-multifile (&optional arg)
3507 "Display todo items matching a user-entered regular expression.
3508 The items are those in the files listed in `todos-filter-files'."
3509 (interactive "P")
3510 (let ((buf todos-regexp-items-buffer)
3511 (files (if (or arg (null todos-filter-files))
3512 (progn (todos-multiple-filter-files)
3513 todos-multiple-filter-files)
3514 todos-filter-files)))
3515 (todos-filter-items 'regexp t)
3516 (todos-filtered-buffer-name buf files)))
3517
3518 ;;; Editing Commands
3519
3520 (defun todos-add-file ()
3521 "Name and add a new Todos file.
3522 Interactively, prompt for a category and display it.
3523 Noninteractively, return the name of the new file."
3524 (interactive)
3525 (let ((prompt (concat "Enter name of new Todos file "
3526 "(TAB or SPC to see current names): "))
3527 file)
3528 (setq file (todos-read-file-name prompt))
3529 (with-current-buffer (get-buffer-create file)
3530 (erase-buffer)
3531 (write-region (point-min) (point-max) file nil 'nomessage nil t)
3532 (kill-buffer file))
3533 (todos-reevaluate-defcustoms)
3534 (if (called-interactively-p)
3535 (progn
3536 (set-window-buffer (selected-window)
3537 (set-buffer (find-file-noselect file)))
3538 (setq todos-current-todos-file file)
3539 (todos-show))
3540 file)))
3541
3542 ;; ---------------------------------------------------------------------------
3543 ;;; Category editing commands
3544
3545 (defun todos-add-category (&optional cat)
3546 "Add a new category to the current Todos file.
3547 Called interactively, prompts for category name, then visits the
3548 category in Todos mode. Non-interactively, argument CAT provides
3549 the category name and the return value is the category number."
3550 (interactive)
3551 (let* ((buffer-read-only)
3552 (num (1+ (length todos-categories)))
3553 (counts (make-vector 4 0))) ; [todo diary done archived]
3554 (unless cat
3555 (setq cat (todos-read-category "Enter new category name: " nil t)))
3556 (setq todos-categories (append todos-categories (list (cons cat counts))))
3557 (widen)
3558 (goto-char (point-max))
3559 (save-excursion ; Save point for todos-category-select.
3560 (insert todos-category-beg cat "\n\n" todos-category-done "\n"))
3561 (todos-update-categories-sexp)
3562 ;; If invoked by user, display the newly added category, if called
3563 ;; programmatically return the category number to the caller.
3564 (if (called-interactively-p 'any)
3565 (progn
3566 (setq todos-category-number num)
3567 (todos-category-select))
3568 num)))
3569
3570 (defun todos-rename-category ()
3571 "Rename current Todos category.
3572 If this file has an archive containing this category, rename the
3573 category there as well."
3574 (interactive)
3575 (let* ((cat (todos-current-category))
3576 (new (read-from-minibuffer (format "Rename category \"%s\" to: " cat))))
3577 (setq new (todos-validate-name new 'category))
3578 (let* ((ofile todos-current-todos-file)
3579 (archive (concat (file-name-sans-extension ofile) ".toda"))
3580 (buffers (append (list ofile)
3581 (unless (zerop (todos-get-count 'archived cat))
3582 (list archive)))))
3583 (dolist (buf buffers)
3584 (with-current-buffer (find-file-noselect buf)
3585 (let (buffer-read-only)
3586 (setq todos-categories (todos-set-categories))
3587 (save-excursion
3588 (save-restriction
3589 (setcar (assoc cat todos-categories) new)
3590 (widen)
3591 (goto-char (point-min))
3592 (todos-update-categories-sexp)
3593 (re-search-forward (concat (regexp-quote todos-category-beg)
3594 "\\(" (regexp-quote cat) "\\)\n")
3595 nil t)
3596 (replace-match new t t nil 1)))))))
3597 (force-mode-line-update))
3598 (save-excursion (todos-category-select)))
3599
3600 (defun todos-delete-category (&optional arg)
3601 "Delete current Todos category provided it is empty.
3602 With ARG non-nil delete the category unconditionally,
3603 i.e. including all existing todo and done items."
3604 (interactive "P")
3605 (let* ((file todos-current-todos-file)
3606 (cat (todos-current-category))
3607 (todo (todos-get-count 'todo cat))
3608 (done (todos-get-count 'done cat))
3609 (archived (todos-get-count 'archived cat)))
3610 (if (and (not arg)
3611 (or (> todo 0) (> done 0)))
3612 (message "%s" (substitute-command-keys
3613 (concat "To delete a non-empty category, "
3614 "type C-u \\[todos-delete-category].")))
3615 (when (cond ((= (length todos-categories) 1)
3616 (y-or-n-p (concat "This is the only category in this file; "
3617 "deleting it will also delete the file.\n"
3618 "Do you want to proceed? ")))
3619 ((> archived 0)
3620 (y-or-n-p (concat "This category has archived items; "
3621 "the archived category will remain\n"
3622 "after deleting the todo category. "
3623 "Do you still want to delete it\n"
3624 "(see 'todos-skip-archived-categories' "
3625 "for another option)? ")))
3626 (t
3627 (y-or-n-p (concat "Permanently remove category \"" cat
3628 "\"" (and arg " and all its entries")
3629 "? "))))
3630 (widen)
3631 (let ((buffer-read-only)
3632 (beg (re-search-backward
3633 (concat "^" (regexp-quote (concat todos-category-beg cat))
3634 "\n") nil t))
3635 (end (if (re-search-forward
3636 (concat "\n\\(" (regexp-quote todos-category-beg)
3637 ".*\n\\)") nil t)
3638 (match-beginning 1)
3639 (point-max))))
3640 (remove-overlays beg end)
3641 (delete-region beg end)
3642 (if (= (length todos-categories) 1)
3643 ;; If deleted category was the only one, delete the file.
3644 (progn
3645 (todos-reevaluate-defcustoms)
3646 ;; Skip confirming killing the archive buffer if it has been
3647 ;; modified and not saved.
3648 (set-buffer-modified-p nil)
3649 (delete-file file)
3650 (kill-buffer)
3651 (message "Deleted Todos file %s." file))
3652 (setq todos-categories (delete (assoc cat todos-categories)
3653 todos-categories))
3654 (todos-update-categories-sexp)
3655 (setq todos-category-number
3656 (1+ (mod todos-category-number (length todos-categories))))
3657 (todos-category-select)
3658 (goto-char (point-min))
3659 (message "Deleted category %s." cat)))))))
3660
3661 (defun todos-move-category ()
3662 "Move current category to a different Todos file.
3663 If current category has archived items, also move those to the
3664 archive of the file moved to, creating it if it does not exist."
3665 (interactive)
3666 (when (or (> (length todos-categories) 1)
3667 (y-or-n-p (concat "This is the only category in this file; "
3668 "moving it will also delete the file.\n"
3669 "Do you want to proceed? ")))
3670 (let* ((ofile todos-current-todos-file)
3671 (cat (todos-current-category))
3672 (nfile (todos-read-file-name
3673 "Choose a Todos file to move this category to: " nil t))
3674 (archive (concat (file-name-sans-extension ofile) ".toda"))
3675 (buffers (append (list ofile)
3676 (unless (zerop (todos-get-count 'archived cat))
3677 (list archive))))
3678 new)
3679 (while (equal (file-truename nfile) (file-truename ofile))
3680 (setq nfile (todos-read-file-name
3681 "Choose a file distinct from this file: " nil t)))
3682 (dolist (buf buffers)
3683 (with-current-buffer (find-file-noselect buf)
3684 (widen)
3685 (goto-char (point-max))
3686 (let* ((beg (re-search-backward
3687 (concat "^"
3688 (regexp-quote (concat todos-category-beg cat)))
3689 nil t))
3690 (end (if (re-search-forward
3691 (concat "^" (regexp-quote todos-category-beg))
3692 nil t 2)
3693 (match-beginning 0)
3694 (point-max)))
3695 (content (buffer-substring-no-properties beg end))
3696 (counts (cdr (assoc cat todos-categories)))
3697 buffer-read-only)
3698 ;; Move the category to the new file. Also update or create
3699 ;; archive file if necessary.
3700 (with-current-buffer
3701 (find-file-noselect
3702 ;; Regenerate todos-archives in case there
3703 ;; is a newly created archive.
3704 (if (member buf (funcall todos-files-function t))
3705 (concat (file-name-sans-extension nfile) ".toda")
3706 nfile))
3707 (let* ((nfile-short (todos-short-file-name nfile))
3708 (prompt (concat
3709 (format "Todos file \"%s\" already has "
3710 nfile-short)
3711 (format "the category \"%s\";\n" cat)
3712 "enter a new category name: "))
3713 buffer-read-only)
3714 (widen)
3715 (goto-char (point-max))
3716 (insert content)
3717 ;; If the file moved to has a category with the same
3718 ;; name, rename the moved category.
3719 (when (assoc cat todos-categories)
3720 (unless (member (file-truename (buffer-file-name))
3721 (funcall todos-files-function t))
3722 (setq new (read-from-minibuffer prompt))
3723 (setq new (todos-validate-name new 'category))))
3724 ;; Replace old with new name in Todos and archive files.
3725 (when new
3726 (goto-char (point-max))
3727 (re-search-backward
3728 (concat "^" (regexp-quote todos-category-beg)
3729 "\\(" (regexp-quote cat) "\\)") nil t)
3730 (replace-match new nil nil nil 1)))
3731 (setq todos-categories
3732 (append todos-categories (list (cons new counts))))
3733 (todos-update-categories-sexp)
3734 ;; If archive was just created, save it to avoid "File <xyz> no
3735 ;; longer exists!" message on invoking
3736 ;; `todos-view-archived-items'. FIXME: maybe better to save
3737 ;; unconditionally?
3738 (unless (file-exists-p (buffer-file-name))
3739 (save-buffer))
3740 (todos-category-number (or new cat))
3741 (todos-category-select))
3742 ;; Delete the category from the old file, and if that was the
3743 ;; last category, delete the file. Also handle archive file
3744 ;; if necessary.
3745 (remove-overlays beg end)
3746 (delete-region beg end)
3747 (goto-char (point-min))
3748 ;; Put point after todos-categories sexp.
3749 (forward-line)
3750 (if (eobp) ; Aside from sexp, file is empty.
3751 (progn
3752 ;; Skip confirming killing the archive buffer.
3753 (set-buffer-modified-p nil)
3754 (delete-file todos-current-todos-file)
3755 (kill-buffer)
3756 (when (member todos-current-todos-file todos-files)
3757 (todos-reevaluate-defcustoms)))
3758 (setq todos-categories (delete (assoc cat todos-categories)
3759 todos-categories))
3760 (todos-update-categories-sexp)
3761 (todos-category-select)))))
3762 (set-window-buffer (selected-window)
3763 (set-buffer (find-file-noselect nfile)))
3764 (todos-category-number (or new cat))
3765 (todos-category-select))))
3766
3767 (defun todos-merge-category ()
3768 "Merge current category into another category in this file.
3769 The current category's todo and done items are appended to the
3770 chosen category's todo and done items, respectively, which
3771 becomes the current category, and the category moved from is
3772 deleted."
3773 (interactive)
3774 (let ((buffer-read-only nil)
3775 (cat (todos-current-category))
3776 (goal (todos-read-category "Category to merge to: " t)))
3777 (widen)
3778 ;; FIXME: check if cat has archived items and merge those too
3779 (let* ((cbeg (progn
3780 (re-search-backward
3781 (concat "^" (regexp-quote todos-category-beg)) nil t)
3782 (point)))
3783 (tbeg (progn (forward-line) (point)))
3784 (dbeg (progn
3785 (re-search-forward
3786 (concat "^" (regexp-quote todos-category-done)) nil t)
3787 (forward-line) (point)))
3788 (tend (progn (forward-line -2) (point)))
3789 (cend (progn
3790 (if (re-search-forward
3791 (concat "^" (regexp-quote todos-category-beg)) nil t)
3792 (match-beginning 0)
3793 (point-max))))
3794 (todo (buffer-substring-no-properties tbeg tend))
3795 (done (buffer-substring-no-properties dbeg cend))
3796 here)
3797 (goto-char (point-min))
3798 (re-search-forward
3799 (concat "^" (regexp-quote (concat todos-category-beg goal))) nil t)
3800 (re-search-forward
3801 (concat "^" (regexp-quote todos-category-done)) nil t)
3802 (forward-line -1)
3803 (setq here (point))
3804 (insert todo)
3805 (goto-char (if (re-search-forward
3806 (concat "^" (regexp-quote todos-category-beg)) nil t)
3807 (match-beginning 0)
3808 (point-max)))
3809 (insert done)
3810 (remove-overlays cbeg cend)
3811 (delete-region cbeg cend)
3812 (todos-update-count 'todo (todos-get-count 'todo cat) goal)
3813 (todos-update-count 'done (todos-get-count 'done cat) goal)
3814 (setq todos-categories (delete (assoc cat todos-categories)
3815 todos-categories))
3816 (todos-update-categories-sexp)
3817 (todos-category-number goal)
3818 (todos-category-select)
3819 ;; Put point at the start of the merged todo items.
3820 ;; FIXME: what if there are no merged todo items but only done items?
3821 (goto-char here))))
3822
3823 (defun todos-set-category-priority (&optional arg)
3824 "Change priority of category at point in Todos Categories buffer.
3825
3826 With ARG nil, prompt for the new priority number. Alternatively,
3827 the new priority can be provided by a numerical prefix ARG.
3828 Otherwise, if ARG is either of the symbols `raise' or `lower',
3829 raise or lower the category's priority by one."
3830 (interactive "P")
3831 (let ((curnum (save-excursion
3832 ;; Get the number representing the priority of the category
3833 ;; on the current line.
3834 (forward-line 0) (skip-chars-forward " ") (number-at-point))))
3835 (when curnum ; Do nothing if we're not on a category line.
3836 (let* ((maxnum (length todos-categories))
3837 (prompt (format "Set category priority (1-%d): " maxnum))
3838 (col (current-column))
3839 (buffer-read-only nil)
3840 (priority (cond ((and (eq arg 'raise) (> curnum 1))
3841 (1- curnum))
3842 ((and (eq arg 'lower) (< curnum maxnum))
3843 (1+ curnum))))
3844 candidate)
3845 (while (not priority)
3846 (setq candidate (or arg (read-number prompt)))
3847 (setq arg nil)
3848 (setq prompt
3849 (cond ((or (< candidate 1) (> candidate maxnum))
3850 (format "Priority must be an integer between 1 and %d: "
3851 maxnum))
3852 ((= candidate curnum)
3853 "Choose a different priority than the current one: ")))
3854 (unless prompt (setq priority candidate)))
3855 (let* ((lower (< curnum priority)) ; Priority is being lowered.
3856 (head (butlast todos-categories
3857 (apply (if lower 'identity '1+)
3858 (list (- maxnum priority)))))
3859 (tail (nthcdr (apply (if lower 'identity '1-) (list priority))
3860 todos-categories))
3861 ;; Category's name and items counts list.
3862 (catcons (nth (1- curnum) todos-categories))
3863 (todos-categories (nconc head (list catcons) tail))
3864 newcats)
3865 (when lower (setq todos-categories (nreverse todos-categories)))
3866 (setq todos-categories (delete-dups todos-categories))
3867 (when lower (setq todos-categories (nreverse todos-categories)))
3868 (setq newcats todos-categories)
3869 (kill-buffer)
3870 (with-current-buffer (find-buffer-visiting todos-current-todos-file)
3871 (setq todos-categories newcats)
3872 (todos-update-categories-sexp))
3873 (todos-display-categories)
3874 (forward-line (1+ priority))
3875 (forward-char col))))))
3876
3877 (defun todos-raise-category-priority ()
3878 "Raise priority of category at point in Todos Categories buffer."
3879 (interactive)
3880 (todos-set-category-priority 'raise))
3881
3882 (defun todos-lower-category-priority ()
3883 "Lower priority of category at point in Todos Categories buffer."
3884 (interactive)
3885 (todos-set-category-priority 'lower))
3886
3887 ;; ---------------------------------------------------------------------------
3888 ;;; Item editing commands
3889
3890 ;; FIXME: make insertion options customizable per category?
3891 ;;;###autoload
3892 (defun todos-insert-item (&optional arg diary nonmarking date-type time
3893 region-or-here)
3894 "Add a new Todo item to a category.
3895 \(See the note at the end of this document string about key
3896 bindings and convenience commands derived from this command.)
3897
3898 With no (or nil) prefix argument ARG, add the item to the current
3899 category; with one prefix argument (C-u), prompt for a category
3900 from the current Todos file; with two prefix arguments (C-u C-u),
3901 first prompt for a Todos file, then a category in that file. If
3902 a non-existing category is entered, ask whether to add it to the
3903 Todos file; if answered affirmatively, add the category and
3904 insert the item there.
3905
3906 When argument DIARY is non-nil, this overrides the intent of the
3907 user option `todos-include-in-diary' for this item: if
3908 `todos-include-in-diary' is nil, include the item in the Fancy
3909 Diary display, and if it is non-nil, exclude the item from the
3910 Fancy Diary display. When DIARY is nil, `todos-include-in-diary'
3911 has its intended effect.
3912
3913 When the item is included in the Fancy Diary display and the
3914 argument NONMARKING is non-nil, this overrides the intent of the
3915 user option `todos-diary-nonmarking' for this item: if
3916 `todos-diary-nonmarking' is nil, append `diary-nonmarking-symbol'
3917 to the item, and if it is non-nil, omit `diary-nonmarking-symbol'.
3918
3919 The argument DATE-TYPE determines the content of the item's
3920 mandatory date header string and how it is added:
3921 - If DATE-TYPE is the symbol `calendar', the Calendar pops up and
3922 when the user puts the cursor on a date and hits RET, that
3923 date, in the format set by `calendar-date-display-form',
3924 becomes the date in the header.
3925 - If DATE-TYPE is the symbol `date', the header contains the date
3926 in the format set by `calendar-date-display-form', with year,
3927 month and day individually prompted for (month with tab
3928 completion).
3929 - If DATE-TYPE is the symbol `dayname' the header contains a
3930 weekday name instead of a date, prompted for with tab
3931 completion.
3932 - If DATE-TYPE has any other value (including nil or none) the
3933 header contains the current date (in the format set by
3934 `calendar-date-display-form').
3935
3936 With non-nil argument TIME prompt for a time string, which must
3937 match `diary-time-regexp'. Typing `<return>' at the prompt
3938 returns the current time, if the user option
3939 `todos-always-add-time-string' is non-nil, otherwise the empty
3940 string (i.e., no time string). If TIME is absent or nil, add or
3941 omit the current time string according as
3942 `todos-always-add-time-string' is non-nil or nil, respectively.
3943
3944 The argument REGION-OR-HERE determines the source and location of
3945 the new item:
3946 - If the REGION-OR-HERE is the symbol `here', prompt for the text
3947 of the new item and insert it directly above the todo item at
3948 point (hence lowering the priority of the remaining items), or
3949 if point is on the empty line below the last todo item, insert
3950 the new item there. An error is signalled if
3951 `todos-insert-item' is invoked with `here' outside of the
3952 current category.
3953 - If REGION-OR-HERE is the symbol `region', use the region of the
3954 current buffer as the text of the new item, depending on the
3955 value of user option `todos-use-only-highlighted-region': if
3956 this is non-nil, then use the region only when it is
3957 highlighted; otherwise, use the region regardless of
3958 highlighting. An error is signalled if there is no region in
3959 the current buffer. Prompt for the item's priority in the
3960 category (an integer between 1 and one more than the number of
3961 items in the category), and insert the item accordingly.
3962 - If REGION-OR-HERE has any other value (in particular, nil or
3963 none), prompt for the text and the item's priority, and insert
3964 the item accordingly.
3965
3966 To facilitate using these arguments when inserting a new todo
3967 item, convenience commands have been defined for all admissible
3968 combinations together with mnenomic key bindings based on on the
3969 name of the arguments and their order in the command's argument
3970 list: diar_y_ - nonmar_k_ing - _c_alendar or _d_ate or day_n_ame
3971 - _t_ime - _r_egion or _h_ere. These key combinations are
3972 appended to the basic insertion key (i) and keys that allow a
3973 following key must be doubled when used finally. For example,
3974 `iyh' will insert a new item with today's date, marked according
3975 to the DIARY argument described above, and with priority
3976 according to the HERE argument; while `iyy' does the same except
3977 the priority is not given by HERE but by prompting."
3978 ;; An alternative interface for customizing key
3979 ;; binding is also provided with the function
3980 ;; `todos-insertion-bindings'." ;FIXME
3981 (interactive "P")
3982 (let ((region (eq region-or-here 'region))
3983 (here (eq region-or-here 'here)))
3984 (when region
3985 (let (use-empty-active-region)
3986 (unless (and todos-use-only-highlighted-region (use-region-p))
3987 (error "There is no active region"))))
3988 (let* ((buf (current-buffer))
3989 (new-item (if region
3990 ;; FIXME: or keep properties?
3991 (buffer-substring-no-properties
3992 (region-beginning) (region-end))
3993 (read-from-minibuffer "Todo item: ")))
3994 (date-string (cond
3995 ((eq date-type 'date)
3996 (todos-read-date))
3997 ((eq date-type 'dayname)
3998 (todos-read-dayname))
3999 ((eq date-type 'calendar)
4000 (setq todos-date-from-calendar t)
4001 (todos-set-date-from-calendar))
4002 (t (calendar-date-string (calendar-current-date) t t))))
4003 (time-string (or (and time (todos-read-time))
4004 (and todos-always-add-time-string
4005 (substring (current-time-string) 11 16)))))
4006 (setq todos-date-from-calendar nil)
4007 (cond ((equal arg '(16)) ; FIXME: cf. set-mark-command
4008 (todos-jump-to-category nil t)
4009 (set-window-buffer
4010 (selected-window)
4011 (set-buffer (find-buffer-visiting todos-global-current-todos-file))))
4012 ((equal arg '(4)) ; FIXME: just arg?
4013 (todos-jump-to-category)
4014 (set-window-buffer
4015 (selected-window)
4016 (set-buffer (find-buffer-visiting todos-global-current-todos-file))))
4017 (t
4018 (when (not (derived-mode-p 'todos-mode)) (todos-show))))
4019 (let (buffer-read-only)
4020 (setq new-item
4021 ;; Add date, time and diary marking as required.
4022 (concat (if (not (and diary (not todos-include-in-diary)))
4023 todos-nondiary-start
4024 (when (and nonmarking (not todos-diary-nonmarking))
4025 diary-nonmarking-symbol))
4026 date-string (when (and time-string ; Can be empty string.
4027 (not (zerop (length time-string))))
4028 (concat " " time-string))
4029 (when (not (and diary (not todos-include-in-diary)))
4030 todos-nondiary-end)
4031 " " new-item))
4032 ;; Indent newlines inserted by C-q C-j if nonspace char follows.
4033 (setq new-item (replace-regexp-in-string
4034 "\\(\n\\)[^[:blank:]]"
4035 (concat "\n" (make-string todos-indent-to-here 32))
4036 new-item nil nil 1))
4037 (if here
4038 (cond ((not (eq major-mode 'todos-mode))
4039 (error "Cannot insert a todo item here outside of Todos mode"))
4040 ((not (eq buf (current-buffer)))
4041 (error "Cannot insert an item here after changing buffer"))
4042 ((or (todos-done-item-p)
4043 ;; Point on last blank line.
4044 (save-excursion (forward-line -1) (todos-done-item-p)))
4045 (error "Cannot insert a new item in the done item section"))
4046 (t
4047 (todos-insert-with-overlays new-item)))
4048 (todos-set-item-priority new-item (todos-current-category) t))
4049 (todos-update-count 'todo 1)
4050 (if (or diary todos-include-in-diary) (todos-update-count 'diary 1))
4051 (todos-update-categories-sexp)))))
4052
4053 (defvar todos-date-from-calendar nil
4054 "Helper variable for setting item date from the Emacs Calendar.")
4055
4056 (defun todos-set-date-from-calendar ()
4057 "Return string of date chosen from Calendar."
4058 (when todos-date-from-calendar
4059 (let (calendar-view-diary-initially-flag)
4060 (calendar))
4061 ;; *Calendar* is now current buffer.
4062 (local-set-key (kbd "RET") 'exit-recursive-edit)
4063 (message "Put cursor on a date and type <return> to set it.")
4064 ;; FIXME: is there a better way than recursive-edit? Use unwind-protect?
4065 ;; Check recursive-depth?
4066 (recursive-edit)
4067 (setq todos-date-from-calendar
4068 (calendar-date-string (calendar-cursor-to-date t) t t))
4069 (calendar-exit)
4070 todos-date-from-calendar))
4071
4072 (defun todos-delete-item ()
4073 "Delete at least one item in this category.
4074
4075 If there are marked items, delete all of these; otherwise, delete
4076 the item at point."
4077 (interactive)
4078 (let* ((cat (todos-current-category))
4079 (marked (assoc cat todos-categories-with-marks))
4080 (item (unless marked (todos-item-string)))
4081 (ov (make-overlay (save-excursion (todos-item-start))
4082 (save-excursion (todos-item-end))))
4083 ;; FIXME: make confirmation an option?
4084 (answer (if marked
4085 (y-or-n-p "Permanently delete all marked items? ")
4086 (when item
4087 (overlay-put ov 'face 'todos-search)
4088 (y-or-n-p (concat "Permanently delete this item? ")))))
4089 (opoint (point))
4090 buffer-read-only)
4091 (when answer
4092 (and marked (goto-char (point-min)))
4093 (catch 'done
4094 (while (not (eobp))
4095 (if (or (and marked (todos-marked-item-p)) item)
4096 (progn
4097 (if (todos-done-item-p)
4098 (todos-update-count 'done -1)
4099 (todos-update-count 'todo -1 cat)
4100 (and (todos-diary-item-p) (todos-update-count 'diary -1)))
4101 (delete-overlay ov)
4102 (todos-remove-item)
4103 ;; Don't leave point below last item.
4104 (and item (bolp) (eolp) (< (point-min) (point-max))
4105 (todos-backward-item))
4106 (when item
4107 (throw 'done (setq item nil))))
4108 (todos-forward-item))))
4109 (when marked
4110 (remove-overlays (point-min) (point-max) 'before-string todos-item-mark)
4111 (setq todos-categories-with-marks
4112 (assq-delete-all cat todos-categories-with-marks))
4113 (goto-char opoint))
4114 (todos-update-categories-sexp)
4115 (todos-prefix-overlays))
4116 (if ov (delete-overlay ov))))
4117
4118 (defun todos-edit-item ()
4119 "Edit the Todo item at point.
4120 If the item consists of only one logical line, edit it in the
4121 minibuffer; otherwise, edit it in Todos Edit mode."
4122 (interactive)
4123 (when (todos-item-string)
4124 (let* ((buffer-read-only)
4125 (start (todos-item-start))
4126 (item-beg (progn
4127 (re-search-forward
4128 (concat todos-date-string-start todos-date-pattern
4129 "\\( " diary-time-regexp "\\)?"
4130 (regexp-quote todos-nondiary-end) "?")
4131 (line-end-position) t)
4132 (1+ (- (point) start))))
4133 (item (todos-item-string))
4134 (multiline (> (length (split-string item "\n")) 1))
4135 (opoint (point)))
4136 (if multiline
4137 (todos-edit-multiline t)
4138 (let ((new (read-string "Edit: " (cons item item-beg))))
4139 (while (not (string-match
4140 (concat todos-date-string-start todos-date-pattern) new))
4141 (setq new (read-from-minibuffer
4142 "Item must start with a date: " new)))
4143 ;; Indent newlines inserted by C-q C-j if nonspace char follows.
4144 (setq new (replace-regexp-in-string
4145 "\\(\n\\)[^[:blank:]]"
4146 (concat "\n" (make-string todos-indent-to-here 32)) new
4147 nil nil 1))
4148 ;; If user moved point during editing, make sure it moves back.
4149 (goto-char opoint)
4150 (todos-remove-item)
4151 (todos-insert-with-overlays new)
4152 (move-to-column item-beg))))))
4153
4154 (defun todos-edit-multiline-item ()
4155 "Edit current Todo item in Todos Edit mode.
4156 Use of newlines invokes `todos-indent' to insure compliance with
4157 the format of Diary entries."
4158 (interactive)
4159 (todos-edit-multiline t))
4160
4161 (defun todos-edit-multiline (&optional item)
4162 ""
4163 (interactive)
4164 ;; FIXME: should there be only one live Todos Edit buffer?
4165 ;; (let ((buffer-name todos-edit-buffer))
4166 (let ((buffer-name (generate-new-buffer-name todos-edit-buffer)))
4167 (set-window-buffer
4168 (selected-window)
4169 (set-buffer (make-indirect-buffer
4170 (file-name-nondirectory todos-current-todos-file)
4171 buffer-name)))
4172 (if item
4173 (narrow-to-region (todos-item-start) (todos-item-end))
4174 (widen))
4175 (todos-edit-mode)
4176 (message "%s" (substitute-command-keys
4177 (concat "Type \\[todos-edit-quit] to check file format "
4178 "validity and return to Todos mode.\n")))))
4179
4180 (defun todos-edit-quit ()
4181 "Return from Todos Edit mode to Todos mode.
4182
4183 If the whole file was in Todos Edit mode, check before returning
4184 whether the file is still a valid Todos file and if so, also
4185 recalculate the Todos categories sexp, in case changes were made
4186 in the number or names of categories."
4187 (interactive)
4188 ;; FIXME: should do only if file was actually changed -- but how to tell?
4189 (when (eq (buffer-size) (- (point-max) (point-min)))
4190 (when (todos-check-format) (todos-repair-categories-sexp)))
4191 (kill-buffer)
4192 ;; In case next buffer is not the one holding todos-current-todos-file.
4193 (todos-show))
4194
4195 (defun todos-edit-item-header (&optional what)
4196 "Edit date/time header of at least one item.
4197
4198 Interactively, ask whether to edit year, month and day or day of
4199 the week, as well as time. If there are marked items, apply the
4200 changes to all of these; otherwise, edit just the item at point.
4201
4202 Non-interactively, argument WHAT specifies whether to set the
4203 date from the Calendar or to today, or whether to edit only the
4204 date or day, or only the time."
4205 (interactive)
4206 (let* ((cat (todos-current-category))
4207 (marked (assoc cat todos-categories-with-marks))
4208 (first t) ; Match only first of marked items.
4209 (todos-date-from-calendar t)
4210 ndate ntime nheader)
4211 (save-excursion
4212 (or (and marked (goto-char (point-min))) (todos-item-start))
4213 (catch 'stop
4214 (while (not (eobp))
4215 (and marked
4216 (while (not (todos-marked-item-p))
4217 (todos-forward-item)
4218 (and (eobp) (throw 'stop nil))))
4219 (re-search-forward (concat todos-date-string-start "\\(?1:"
4220 todos-date-pattern
4221 "\\)\\(?2: " diary-time-regexp "\\)?")
4222 (line-end-position) t)
4223 (let* ((odate (match-string-no-properties 1))
4224 (otime (match-string-no-properties 2))
4225 (buffer-read-only))
4226 (cond ((eq what 'today)
4227 (progn
4228 (setq ndate (calendar-date-string
4229 (calendar-current-date) t t))
4230 (replace-match ndate nil nil nil 1)))
4231 ((eq what 'calendar)
4232 (setq ndate (save-match-data (todos-set-date-from-calendar)))
4233 (replace-match ndate nil nil nil 1))
4234 (t
4235 (unless (eq what 'timeonly)
4236 (when first
4237 (setq ndate (if (save-match-data
4238 (string-match "[0-9]+" odate))
4239 (if (y-or-n-p "Change date? ")
4240 (todos-read-date)
4241 (todos-read-dayname))
4242 (if (y-or-n-p "Change day? ")
4243 (todos-read-dayname)
4244 (todos-read-date)))))
4245 (replace-match ndate nil nil nil 1))
4246 (unless (eq what 'dateonly)
4247 (when first
4248 (setq ntime (save-match-data (todos-read-time)))
4249 (when (< 0 (length ntime))
4250 (setq ntime (concat " " ntime))))
4251 (if otime
4252 (replace-match ntime nil nil nil 2)
4253 (goto-char (match-end 1))
4254 (insert ntime)))))
4255 (setq todos-date-from-calendar nil)
4256 (setq first nil))
4257 (if marked
4258 (todos-forward-item)
4259 (goto-char (point-max))))))))
4260
4261 (defun todos-edit-item-date ()
4262 "Prompt for and apply changes to current item's date."
4263 (interactive)
4264 (todos-edit-item-header 'dateonly))
4265
4266 (defun todos-edit-item-date-from-calendar ()
4267 "Prompt for changes to current item's date and apply from Calendar."
4268 (interactive)
4269 (todos-edit-item-header 'calendar))
4270
4271 (defun todos-edit-item-date-is-today ()
4272 "Set item date to today's date."
4273 (interactive)
4274 (todos-edit-item-header 'today))
4275
4276 (defun todos-edit-item-time ()
4277 "Prompt For and apply changes to current item's time."
4278 (interactive)
4279 (todos-edit-item-header 'timeonly))
4280
4281 (defun todos-edit-item-diary-inclusion ()
4282 "Change diary status of one or more todo items in this category.
4283 That is, insert `todos-nondiary-marker' if the candidate items
4284 lack this marking; otherwise, remove it.
4285
4286 If there are marked todo items, change the diary status of all
4287 and only these, otherwise change the diary status of the item at
4288 point."
4289 (interactive)
4290 (let ((buffer-read-only)
4291 (marked (assoc (todos-current-category)
4292 todos-categories-with-marks)))
4293 (catch 'stop
4294 (save-excursion
4295 (when marked (goto-char (point-min)))
4296 (while (not (eobp))
4297 (if (todos-done-item-p)
4298 (throw 'stop (message "Done items cannot be edited"))
4299 (unless (and marked (not (todos-marked-item-p)))
4300 (let* ((beg (todos-item-start))
4301 (lim (save-excursion (todos-item-end)))
4302 (end (save-excursion
4303 (or (todos-time-string-matcher lim)
4304 (todos-date-string-matcher lim)))))
4305 (if (looking-at (regexp-quote todos-nondiary-start))
4306 (progn
4307 (replace-match "")
4308 (search-forward todos-nondiary-end (1+ end) t)
4309 (replace-match "")
4310 (todos-update-count 'diary 1))
4311 (when end
4312 (insert todos-nondiary-start)
4313 (goto-char (1+ end))
4314 (insert todos-nondiary-end)
4315 (todos-update-count 'diary -1)))))
4316 (unless marked (throw 'stop nil))
4317 (todos-forward-item)))))
4318 (todos-update-categories-sexp)))
4319
4320 (defun todos-edit-category-diary-inclusion (arg)
4321 "Make all items in this category diary items.
4322 With prefix ARG, make all items in this category non-diary
4323 items."
4324 (interactive "P")
4325 (save-excursion
4326 (goto-char (point-min))
4327 (let ((todo-count (todos-get-count 'todo))
4328 (diary-count (todos-get-count 'diary))
4329 (buffer-read-only))
4330 (catch 'stop
4331 (while (not (eobp))
4332 (if (todos-done-item-p) ; We've gone too far.
4333 (throw 'stop nil)
4334 (let* ((beg (todos-item-start))
4335 (lim (save-excursion (todos-item-end)))
4336 (end (save-excursion
4337 (or (todos-time-string-matcher lim)
4338 (todos-date-string-matcher lim)))))
4339 (if arg
4340 (unless (looking-at (regexp-quote todos-nondiary-start))
4341 (insert todos-nondiary-start)
4342 (goto-char (1+ end))
4343 (insert todos-nondiary-end))
4344 (when (looking-at (regexp-quote todos-nondiary-start))
4345 (replace-match "")
4346 (search-forward todos-nondiary-end (1+ end) t)
4347 (replace-match "")))))
4348 (todos-forward-item))
4349 (unless (if arg (zerop diary-count) (= diary-count todo-count))
4350 (todos-update-count 'diary (if arg
4351 (- diary-count)
4352 (- todo-count diary-count))))
4353 (todos-update-categories-sexp)))))
4354
4355 (defun todos-edit-item-diary-nonmarking ()
4356 "Change non-marking of one or more diary items in this category.
4357 That is, insert `diary-nonmarking-symbol' if the candidate items
4358 lack this marking; otherwise, remove it.
4359
4360 If there are marked todo items, change the non-marking status of
4361 all and only these, otherwise change the non-marking status of
4362 the item at point."
4363 (interactive)
4364 (let ((buffer-read-only)
4365 (marked (assoc (todos-current-category)
4366 todos-categories-with-marks)))
4367 (catch 'stop
4368 (save-excursion
4369 (when marked (goto-char (point-min)))
4370 (while (not (eobp))
4371 (if (todos-done-item-p)
4372 (throw 'stop (message "Done items cannot be edited"))
4373 (unless (and marked (not (todos-marked-item-p)))
4374 (todos-item-start)
4375 (unless (looking-at (regexp-quote todos-nondiary-start))
4376 (if (looking-at (regexp-quote diary-nonmarking-symbol))
4377 (replace-match "")
4378 (insert diary-nonmarking-symbol))))
4379 (unless marked (throw 'stop nil))
4380 (todos-forward-item)))))))
4381
4382 (defun todos-edit-category-diary-nonmarking (arg)
4383 "Add `diary-nonmarking-symbol' to all diary items in this category.
4384 With prefix ARG, remove `diary-nonmarking-symbol' from all diary
4385 items in this category."
4386 (interactive "P")
4387 (save-excursion
4388 (goto-char (point-min))
4389 (let (buffer-read-only)
4390 (catch 'stop
4391 (while (not (eobp))
4392 (if (todos-done-item-p) ; We've gone too far.
4393 (throw 'stop nil)
4394 (unless (looking-at (regexp-quote todos-nondiary-start))
4395 (if arg
4396 (when (looking-at (regexp-quote diary-nonmarking-symbol))
4397 (replace-match ""))
4398 (unless (looking-at (regexp-quote diary-nonmarking-symbol))
4399 (insert diary-nonmarking-symbol))))
4400 (todos-forward-item)))))))
4401
4402 (defun todos-set-item-priority (&optional item cat new arg)
4403 "Set todo ITEM's priority in CATegory and move item accordingly.
4404
4405 Interactively, ITEM defaults to the item at point, CAT to the
4406 current category in Todos mode, and the priority is a number
4407 between 1 and the number of items in the category.
4408 Non-interactively, non-nil NEW means ITEM is a new item and the
4409 lowest priority is one more than the number of items in CAT.
4410
4411 The new priority is set either interactively by prompt or by a
4412 numerical prefix argument, or noninteractively by argument ARG,
4413 whose value can be either of the symbols `raise' or `lower',
4414 meaning to raise or lower the item's priority by one."
4415 (interactive)
4416 (let* ((item (or item (todos-item-string)))
4417 (marked (todos-marked-item-p))
4418 (cat (or cat (cond ((eq major-mode 'todos-mode)
4419 (todos-current-category))
4420 ((eq major-mode 'todos-filtered-items-mode)
4421 (let* ((regexp1
4422 (concat todos-date-string-start
4423 todos-date-pattern
4424 "\\( " diary-time-regexp "\\)?"
4425 (regexp-quote todos-nondiary-end)
4426 "?\\(?1: \\[\\(.+:\\)?.+\\]\\)")))
4427 (save-excursion
4428 (re-search-forward regexp1 nil t)
4429 (match-string-no-properties 1)))))))
4430 curnum
4431 (todo (cond ((or (eq arg 'raise) (eq arg 'lower)
4432 (eq major-mode 'todos-filtered-items-mode))
4433 (save-excursion
4434 (let ((curstart (todos-item-start))
4435 (count 0))
4436 (goto-char (point-min))
4437 (while (looking-at todos-item-start)
4438 (setq count (1+ count))
4439 (when (= (point) curstart) (setq curnum count))
4440 (todos-forward-item))
4441 count)))
4442 ((eq major-mode 'todos-mode)
4443 (todos-get-count 'todo cat))))
4444 (maxnum (if new (1+ todo) todo))
4445 (prompt (format "Set item priority (1-%d): " maxnum))
4446 (priority (cond ((numberp current-prefix-arg)
4447 current-prefix-arg)
4448 ((and (eq arg 'raise) (>= curnum 1))
4449 (1- curnum))
4450 ((and (eq arg 'lower) (<= curnum maxnum))
4451 (1+ curnum))))
4452 candidate
4453 buffer-read-only)
4454 (unless (and priority
4455 (or (and (eq arg 'raise) (zerop priority))
4456 (and (eq arg 'lower) (> priority maxnum))))
4457 ;; When moving item to another category, show the category before
4458 ;; prompting for its priority.
4459 (unless (or arg (called-interactively-p t))
4460 (todos-category-number cat)
4461 (todos-category-select))
4462 (while (not priority)
4463 (setq candidate (read-number prompt))
4464 (setq prompt (when (or (< candidate 1) (> candidate maxnum))
4465 (format "Priority must be an integer between 1 and %d.\n"
4466 maxnum)))
4467 (unless prompt (setq priority candidate)))
4468 ;; In Top Priorities buffer, an item's priority can be changed
4469 ;; wrt items in another category, but not wrt items in the same
4470 ;; category.
4471 (when (eq major-mode 'todos-filtered-items-mode)
4472 (let* ((regexp2 (concat todos-date-string-start todos-date-pattern
4473 "\\( " diary-time-regexp "\\)?"
4474 (regexp-quote todos-nondiary-end)
4475 "?\\(?1:" (regexp-quote cat) "\\)"))
4476 (end (cond ((< curnum priority)
4477 (save-excursion (todos-item-end)))
4478 ((> curnum priority)
4479 (save-excursion (todos-item-start)))))
4480 (match (save-excursion
4481 (cond ((< curnum priority)
4482 (todos-forward-item (1+ (- priority curnum)))
4483 (when (re-search-backward regexp2 end t)
4484 (match-string-no-properties 1)))
4485 ((> curnum priority)
4486 (todos-backward-item (- curnum priority))
4487 (when (re-search-forward regexp2 end t)
4488 (match-string-no-properties 1)))))))
4489 (when match
4490 (error (concat "Cannot reprioritize items from the same "
4491 "category in this mode, only in Todos mode")))))
4492 ;; Interactively or with non-nil ARG, relocate the item within its
4493 ;; category.
4494 (when (or arg (called-interactively-p))
4495 (todos-remove-item))
4496 (goto-char (point-min))
4497 (unless (= priority 1) (todos-forward-item (1- priority)))
4498 (todos-insert-with-overlays item)
4499 ;; If item was marked, restore the mark.
4500 (and marked (overlay-put (make-overlay (point) (point))
4501 'before-string todos-item-mark)))))
4502
4503 (defun todos-raise-item-priority ()
4504 "Raise priority of current item by moving it up by one item."
4505 (interactive)
4506 (todos-set-item-priority nil nil nil 'raise))
4507
4508 (defun todos-lower-item-priority ()
4509 "Lower priority of current item by moving it down by one item."
4510 (interactive)
4511 (todos-set-item-priority nil nil nil 'lower))
4512
4513 (defun todos-move-item (&optional file)
4514 "Move at least one todo item to another category.
4515
4516 If there are marked items, move all of these; otherwise, move
4517 the item at point.
4518
4519 With non-nil argument FILE, first prompt for another Todos file and
4520 then a category in that file to move the item or items to.
4521
4522 If the chosen category is not one of the existing categories,
4523 then it is created and the item(s) become(s) the first
4524 entry/entries in that category."
4525 (interactive)
4526 (unless (or (todos-done-item-p)
4527 ;; Point is between todo and done items.
4528 (looking-at "^$"))
4529 (let* ((buffer-read-only)
4530 (file1 todos-current-todos-file)
4531 (cat1 (todos-current-category))
4532 (marked (assoc cat1 todos-categories-with-marks))
4533 (num todos-category-number)
4534 (item (todos-item-string))
4535 (diary-item (todos-diary-item-p))
4536 (omark (save-excursion (todos-item-start) (point-marker)))
4537 (file2 (if file
4538 (todos-read-file-name "Choose a Todos file: " nil t)
4539 file1))
4540 (count 0)
4541 (count-diary 0)
4542 cat2 nmark)
4543 (set-buffer (find-file-noselect file2))
4544 (setq cat2 (let* ((pl (if (and marked (> (cdr marked) 1)) "s" ""))
4545 (name (todos-read-category
4546 (concat "Move item" pl " to category: ")))
4547 (prompt (concat "Choose a different category than "
4548 "the current one\n(type `"
4549 (key-description
4550 (car (where-is-internal
4551 'todos-set-item-priority)))
4552 "' to reprioritize item "
4553 "within the same category): ")))
4554 (while (equal name cat1)
4555 (setq name (todos-read-category prompt)))
4556 name))
4557 (set-buffer (find-buffer-visiting file1))
4558 (if marked
4559 (progn
4560 (setq item nil)
4561 (goto-char (point-min))
4562 (while (not (eobp))
4563 (when (todos-marked-item-p)
4564 (setq item (concat item (todos-item-string) "\n"))
4565 (setq count (1+ count))
4566 (when (todos-diary-item-p)
4567 (setq count-diary (1+ count-diary))))
4568 (todos-forward-item))
4569 ;; Chop off last newline.
4570 (setq item (substring item 0 -1)))
4571 (setq count 1)
4572 (when (todos-diary-item-p) (setq count-diary 1)))
4573 (set-window-buffer (selected-window)
4574 (set-buffer (find-file-noselect file2)))
4575 (unless (assoc cat2 todos-categories) (todos-add-category cat2))
4576 (todos-set-item-priority item cat2 t)
4577 (setq nmark (point-marker))
4578 (todos-update-count 'todo count)
4579 (todos-update-count 'diary count-diary)
4580 (todos-update-categories-sexp)
4581 (with-current-buffer (find-buffer-visiting file1)
4582 (save-excursion
4583 (save-restriction
4584 (widen)
4585 (goto-char omark)
4586 (if marked
4587 (let (beg end)
4588 (setq item nil)
4589 (re-search-backward
4590 (concat "^" (regexp-quote todos-category-beg)) nil t)
4591 (forward-line)
4592 (setq beg (point))
4593 (re-search-forward
4594 (concat "^" (regexp-quote todos-category-done)) nil t)
4595 (setq end (match-beginning 0))
4596 (goto-char beg)
4597 (while (< (point) end)
4598 (if (todos-marked-item-p)
4599 (todos-remove-item)
4600 (todos-forward-item))))
4601 (todos-remove-item))))
4602 (todos-update-count 'todo (- count) cat1)
4603 (todos-update-count 'diary (- count-diary) cat1)
4604 (todos-update-categories-sexp))
4605 (set-window-buffer (selected-window)
4606 (set-buffer (find-file-noselect file2)))
4607 (setq todos-category-number (todos-category-number cat2))
4608 (todos-category-select)
4609 (goto-char nmark))))
4610
4611 (defun todos-move-item-to-file ()
4612 "Move the current todo item to a category in another Todos file."
4613 (interactive)
4614 (todos-move-item t))
4615
4616 ;; (defun todos-move-item-to-diary ()
4617 ;; "Move one or more items in current category to the diary file.
4618 ;;
4619 ;; If there are marked items, move all of these; otherwise, move
4620 ;; the item at point."
4621 ;; (interactive)
4622 ;; ;; FIXME
4623 ;; )
4624
4625 ;; FIXME: make adding date customizable, and make this and time customization
4626 ;; overridable via double prefix arg ??
4627 (defun todos-item-done (&optional arg)
4628 "Tag at least one item in this category as done and hide it.
4629
4630 With prefix argument ARG prompt for a comment and append it to
4631 the done item; this is only possible if there are no marked
4632 items. If there are marked items, tag all of these with
4633 `todos-done-string' plus the current date and, if
4634 `todos-always-add-time-string' is non-nil, the current time;
4635 otherwise, just tag the item at point. Items tagged as done are
4636 relocated to the category's (by default hidden) done section."
4637 (interactive "P")
4638 (let* ((cat (todos-current-category))
4639 (marked (assoc cat todos-categories-with-marks)))
4640 (unless (or (todos-done-item-p)
4641 (and (looking-at "^$") (not marked)))
4642 (let* ((date-string (calendar-date-string (calendar-current-date) t t))
4643 (time-string (if todos-always-add-time-string
4644 (concat " " (substring (current-time-string) 11 16))
4645 ""))
4646 (done-prefix (concat "[" todos-done-string date-string time-string
4647 "] "))
4648 (comment (and arg (not marked) (read-string "Enter a comment: ")))
4649 (item-count 0)
4650 (diary-count 0)
4651 item done-item
4652 (buffer-read-only))
4653 (and marked (goto-char (point-min)))
4654 (catch 'done
4655 (while (not (eobp))
4656 (if (or (not marked) (and marked (todos-marked-item-p)))
4657 (progn
4658 (setq item (todos-item-string))
4659 (setq done-item (cond (marked
4660 (concat done-item done-prefix item "\n"))
4661 (comment
4662 (concat done-prefix item " ["
4663 todos-comment-string
4664 ": " comment "]"))
4665 (t
4666 (concat done-prefix item))))
4667 (setq item-count (1+ item-count))
4668 (when (todos-diary-item-p)
4669 (setq diary-count (1+ diary-count)))
4670 (todos-remove-item)
4671 (unless marked (throw 'done nil)))
4672 (todos-forward-item))))
4673 (when marked
4674 ;; Chop off last newline of done item string.
4675 (setq done-item (substring done-item 0 -1))
4676 (remove-overlays (point-min) (point-max) 'before-string todos-item-mark)
4677 (setq todos-categories-with-marks
4678 (assq-delete-all cat todos-categories-with-marks)))
4679 (save-excursion
4680 (widen)
4681 (re-search-forward
4682 (concat "^" (regexp-quote todos-category-done)) nil t)
4683 (forward-char)
4684 (insert done-item "\n"))
4685 (todos-update-count 'todo (- item-count))
4686 (todos-update-count 'done item-count)
4687 (todos-update-count 'diary (- diary-count))
4688 (todos-update-categories-sexp)
4689 (save-excursion (todos-category-select))))))
4690
4691 (defun todos-done-item-add-edit-or-delete-comment (&optional arg)
4692 "Add a comment to this done item or edit an existing comment.
4693 With prefix ARG delete an existing comment."
4694 (interactive "P")
4695 (when (todos-done-item-p)
4696 (let ((item (todos-item-string))
4697 (end (save-excursion (todos-item-end)))
4698 comment buffer-read-only)
4699 (save-excursion
4700 (todos-item-start)
4701 (if (re-search-forward (concat " \\["
4702 (regexp-quote todos-comment-string)
4703 ": \\([^]]+\\)\\]") end t)
4704 (if arg
4705 (when (y-or-n-p "Delete comment? ")
4706 (delete-region (match-beginning 0) (match-end 0)))
4707 (setq comment (read-string "Edit comment: "
4708 (cons (match-string 1) 1)))
4709 (replace-match comment nil nil nil 1))
4710 (setq comment (read-string "Enter a comment: "))
4711 (todos-item-end)
4712 (insert " [" todos-comment-string ": " comment "]"))))))
4713
4714 ;; FIXME: also with marked items
4715 ;; FIXME: delete comment from restored item or just leave it up to user?
4716 (defun todos-item-undo ()
4717 "Restore this done item to the todo section of this category.
4718 If done item has a comment, ask whether to omit the comment from
4719 the restored item."
4720 (interactive)
4721 (when (todos-done-item-p)
4722 (let* ((buffer-read-only)
4723 (done-item (todos-item-string))
4724 (opoint (point))
4725 (orig-mrk (progn (todos-item-start) (point-marker)))
4726 ;; Find the end of the date string added upon tagging item as done.
4727 (start (search-forward "] "))
4728 (end (save-excursion (todos-item-end)))
4729 item undone)
4730 (todos-item-start)
4731 (when (and (re-search-forward (concat " \\["
4732 (regexp-quote todos-comment-string)
4733 ": \\([^]]+\\)\\]") end t)
4734 (y-or-n-p "Omit comment from restored item? "))
4735 (delete-region (match-beginning 0) (match-end 0)))
4736 (setq item (buffer-substring start end))
4737 (todos-remove-item)
4738 ;; If user cancels before setting new priority, then leave the done item
4739 ;; unchanged.
4740 (unwind-protect
4741 (progn
4742 (todos-set-item-priority item (todos-current-category) t)
4743 (setq undone t)
4744 (todos-update-count 'todo 1)
4745 (todos-update-count 'done -1)
4746 (and (todos-diary-item-p) (todos-update-count 'diary 1))
4747 (todos-update-categories-sexp))
4748 (unless undone
4749 (widen)
4750 (goto-char orig-mrk)
4751 (todos-insert-with-overlays done-item)
4752 (let ((todos-show-with-done t))
4753 (todos-category-select)
4754 (goto-char opoint)))
4755 (set-marker orig-mrk nil)))))
4756
4757 (defun todos-archive-done-item (&optional all)
4758 "Archive at least one done item in this category.
4759
4760 If there are marked done items (and no marked todo items),
4761 archive all of these; otherwise, with non-nil argument ALL,
4762 archive all done items in this category; otherwise, archive the
4763 done item at point.
4764
4765 If the archive of this file does not exist, it is created. If
4766 this category does not exist in the archive, it is created."
4767 (interactive)
4768 (when (eq major-mode 'todos-mode)
4769 (if (and all (zerop (todos-get-count 'done)))
4770 (message "No done items in this category")
4771 (catch 'end
4772 (let* ((cat (todos-current-category))
4773 (tbuf (current-buffer))
4774 (marked (assoc cat todos-categories-with-marks))
4775 (afile (concat (file-name-sans-extension
4776 todos-current-todos-file) ".toda"))
4777 (archive (if (file-exists-p afile)
4778 (find-file-noselect afile t)
4779 (get-buffer-create afile)))
4780 (item (and (todos-done-item-p) (concat (todos-item-string) "\n")))
4781 (count 0)
4782 marked-items beg end all-done
4783 buffer-read-only)
4784 (cond
4785 (marked
4786 (save-excursion
4787 (goto-char (point-min))
4788 (while (not (eobp))
4789 (when (todos-marked-item-p)
4790 (if (not (todos-done-item-p))
4791 (throw 'end (message "Only done items can be archived"))
4792 (setq marked-items
4793 (concat marked-items (todos-item-string) "\n"))
4794 (setq count (1+ count))))
4795 (todos-forward-item))))
4796 (all
4797 (if (y-or-n-p "Archive all done items in this category? ")
4798 (save-excursion
4799 (save-restriction
4800 (goto-char (point-min))
4801 (widen)
4802 (setq beg (progn
4803 (re-search-forward todos-done-string-start nil t)
4804 (match-beginning 0))
4805 end (if (re-search-forward
4806 (concat "^" (regexp-quote todos-category-beg))
4807 nil t)
4808 (match-beginning 0)
4809 (point-max))
4810 all-done (buffer-substring beg end)
4811 count (todos-get-count 'done))))
4812 (throw 'end nil))))
4813 (when (or marked all item)
4814 (with-current-buffer archive
4815 (unless buffer-file-name (erase-buffer))
4816 (let (buffer-read-only)
4817 (widen)
4818 (goto-char (point-min))
4819 (if (and (re-search-forward (concat "^"
4820 (regexp-quote
4821 (concat todos-category-beg
4822 cat)))
4823 nil t)
4824 (re-search-forward (regexp-quote todos-category-done)
4825 nil t))
4826 ;; Start of done items section in existing category.
4827 (forward-char)
4828 (todos-add-category cat)
4829 ;; Start of done items section in new category.
4830 (goto-char (point-max)))
4831 (insert (cond (marked marked-items)
4832 (all all-done)
4833 (item)))
4834 (todos-update-count 'done (if (or marked all) count 1) cat)
4835 (todos-update-categories-sexp)
4836 ;; If archive is new, save to file now (using write-region in
4837 ;; order not to get prompted for file to save to), to let
4838 ;; auto-mode-alist take effect below.
4839 (unless buffer-file-name
4840 (write-region nil nil afile)
4841 (kill-buffer))))
4842 (with-current-buffer tbuf
4843 (cond ((or marked item)
4844 (and marked (goto-char (point-min)))
4845 (catch 'done
4846 (while (not (eobp))
4847 (if (or (and marked (todos-marked-item-p)) item)
4848 (progn
4849 (todos-remove-item)
4850 (todos-update-count 'done -1)
4851 (todos-update-count 'archived 1)
4852 ;; Don't leave point below last item.
4853 (and item (bolp) (eolp) (< (point-min) (point-max))
4854 (todos-backward-item))
4855 (when item
4856 (throw 'done (setq item nil))))
4857 (todos-forward-item)))))
4858 (all
4859 (remove-overlays beg end)
4860 (delete-region beg end)
4861 (todos-update-count 'done (- count))
4862 (todos-update-count 'archived count)))
4863 (when marked
4864 (remove-overlays (point-min) (point-max)
4865 'before-string todos-item-mark)
4866 (setq todos-categories-with-marks
4867 (assq-delete-all cat todos-categories-with-marks)))
4868 (todos-update-categories-sexp)
4869 (todos-prefix-overlays)))
4870 (find-file afile)
4871 (todos-category-number cat)
4872 (todos-category-select)
4873 (split-window-below)
4874 (set-window-buffer (selected-window) tbuf))))))
4875
4876 (defun todos-archive-category-done-items ()
4877 "Move all done items in this category to its archive."
4878 (interactive)
4879 (todos-archive-done-item t))
4880
4881 (defun todos-unarchive-items (&optional all)
4882 "Unarchive at least one item in this archive category.
4883
4884 If there are marked items, unarchive all of these; otherwise,
4885 with non-nil argument ALL, unarchive all items in this category;
4886 otherwise, unarchive the item at point.
4887
4888 Unarchived items are restored as done items to the corresponding
4889 category in the Todos file, inserted at the end of done section.
4890 If all items in the archive category were restored, the category
4891 is deleted from the archive. If this was the only category in the
4892 archive, the archive file is deleted."
4893 (interactive)
4894 (when (eq major-mode 'todos-archive-mode)
4895 (catch 'end
4896 (let* ((cat (todos-current-category))
4897 (tbuf (find-file-noselect
4898 (concat (file-name-sans-extension todos-current-todos-file)
4899 ".todo") t))
4900 (marked (assoc cat todos-categories-with-marks))
4901 (item (concat (todos-item-string) "\n"))
4902 (all-items (when all (buffer-substring (point-min) (point-max))))
4903 (all-count (when all (todos-get-count 'done)))
4904 marked-items marked-count
4905 buffer-read-only)
4906 (when marked
4907 (save-excursion
4908 (goto-char (point-min))
4909 (while (not (eobp))
4910 (when (todos-marked-item-p)
4911 (concat marked-items (todos-item-string) "\n")
4912 (setq marked-count (1+ marked-count)))
4913 (todos-forward-item))))
4914 ;; Restore items to end of category's done section and update counts.
4915 (with-current-buffer tbuf
4916 (let (buffer-read-only)
4917 (widen)
4918 (goto-char (point-min))
4919 (re-search-forward (concat "^" (regexp-quote
4920 (concat todos-category-beg cat)))
4921 nil t)
4922 ;; Go to end of category's done section.
4923 (if (re-search-forward (concat "^" (regexp-quote todos-category-beg))
4924 nil t)
4925 (goto-char (match-beginning 0))
4926 (goto-char (point-max)))
4927 (cond (marked
4928 (insert marked-items)
4929 (todos-update-count 'done marked-count cat)
4930 (todos-update-count 'archived (- marked-count) cat))
4931 (all
4932 (insert all-items)
4933 (todos-update-count 'done all-count cat)
4934 (todos-update-count 'archived (- all-count) cat))
4935 (t
4936 (insert item)
4937 (todos-update-count 'done 1 cat)
4938 (todos-update-count 'archived -1 cat)))
4939 (todos-update-categories-sexp)))
4940 ;; Delete restored items from archive.
4941 (cond ((or marked item)
4942 (and marked (goto-char (point-min)))
4943 (catch 'done
4944 (while (not (eobp))
4945 (if (or (and marked (todos-marked-item-p)) item)
4946 (progn
4947 (todos-remove-item)
4948 ;; Don't leave point below last item.
4949 (and item (bolp) (eolp) (< (point-min) (point-max))
4950 (todos-backward-item))
4951 (when item
4952 (throw 'done (setq item nil))))
4953 (todos-forward-item))))
4954 (todos-update-count 'done (if marked (- marked-count) -1) cat))
4955 (all
4956 (remove-overlays (point-min) (point-max))
4957 (delete-region (point-min) (point-max))))
4958 ;; If that was the last category in the archive, delete the whole file.
4959 (if (= (length todos-categories) 1)
4960 (progn
4961 (delete-file todos-current-todos-file)
4962 ;; Don't bother confirming killing the archive buffer.
4963 (set-buffer-modified-p nil)
4964 (kill-buffer))
4965 ;; Otherwise, if the archive category is now empty, delete it.
4966 (when (eq (point-min) (point-max))
4967 (widen)
4968 (let ((beg (re-search-backward
4969 (concat "^" (regexp-quote todos-category-beg) cat)
4970 nil t))
4971 (end (if (re-search-forward
4972 (concat "^" (regexp-quote todos-category-beg))
4973 nil t 2)
4974 (match-beginning 0)
4975 (point-max))))
4976 (remove-overlays beg end)
4977 (delete-region beg end)
4978 (setq todos-categories (delete (assoc cat todos-categories)
4979 todos-categories))
4980 (todos-update-categories-sexp))))
4981 ;; Visit category in Todos file and show restored done items.
4982 (let ((tfile (buffer-file-name tbuf))
4983 (todos-show-with-done t))
4984 (set-window-buffer (selected-window)
4985 (set-buffer (find-file-noselect tfile)))
4986 (todos-category-number cat)
4987 (todos-show)
4988 (message "Items unarchived."))))))
4989
4990 (defun todos-unarchive-category ()
4991 "Unarchive all items in this category. See `todos-unarchive-items'."
4992 (interactive)
4993 (todos-unarchive-items t))
4994
4995 (provide 'todos)
4996
4997 ;;; todos.el ends here
4998
4999 ;; ---------------------------------------------------------------------------
5000
5001 ;; FIXME: remove when part of Emacs
5002 (add-to-list 'auto-mode-alist '("\\.todo\\'" . todos-mode))
5003 (add-to-list 'auto-mode-alist '("\\.toda\\'" . todos-archive-mode))
5004
5005 ;;; Addition to calendar.el
5006 ;; FIXME: autoload when key-binding is defined in calendar.el
5007 (defun todos-insert-item-from-calendar ()
5008 ""
5009 (interactive)
5010 ;; FIXME: todos-current-todos-file is nil here, better to solicit Todos
5011 ;; file? todos-global-current-todos-file is nil if no Todos file has been
5012 ;; visited
5013 (pop-to-buffer (file-name-nondirectory todos-global-current-todos-file))
5014 (todos-show)
5015 ;; FIXME: this now calls todos-set-date-from-calendar
5016 (todos-insert-item t 'calendar))
5017
5018 ;; FIXME: calendar is loaded before todos
5019 ;; (add-hook 'calendar-load-hook
5020 ;; (lambda ()
5021 (define-key calendar-mode-map "it" 'todos-insert-item-from-calendar);))
5022
5023 ;; ---------------------------------------------------------------------------
5024 ;;; necessitated adaptations to diary-lib.el
5025
5026 ;; (defun diary-goto-entry (button)
5027 ;; "Jump to the diary entry for the BUTTON at point."
5028 ;; (let* ((locator (button-get button 'locator))
5029 ;; (marker (car locator))
5030 ;; markbuf file opoint)
5031 ;; ;; If marker pointing to diary location is valid, use that.
5032 ;; (if (and marker (setq markbuf (marker-buffer marker)))
5033 ;; (progn
5034 ;; (pop-to-buffer markbuf)
5035 ;; (goto-char (marker-position marker)))
5036 ;; ;; Marker is invalid (eg buffer has been killed, as is the case with
5037 ;; ;; included diary files).
5038 ;; (or (and (setq file (cadr locator))
5039 ;; (file-exists-p file)
5040 ;; (find-file-other-window file)
5041 ;; (progn
5042 ;; (when (eq major-mode (default-value 'major-mode)) (diary-mode))
5043 ;; (when (eq major-mode 'todos-mode) (widen))
5044 ;; (goto-char (point-min))
5045 ;; (when (re-search-forward (format "%s.*\\(%s\\)"
5046 ;; (regexp-quote (nth 2 locator))
5047 ;; (regexp-quote (nth 3 locator)))
5048 ;; nil t)
5049 ;; (goto-char (match-beginning 1))
5050 ;; (when (eq major-mode 'todos-mode)
5051 ;; (setq opoint (point))
5052 ;; (re-search-backward (concat "^"
5053 ;; (regexp-quote todos-category-beg)
5054 ;; "\\(.*\\)\n")
5055 ;; nil t)
5056 ;; (todos-category-number (match-string 1))
5057 ;; (todos-category-select)
5058 ;; (goto-char opoint)))))
5059 ;; (message "Unable to locate this diary entry")))))