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