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