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