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