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