* calendar/todos.el: Further code rearrangement and comment
[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-filter-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-special-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-special-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-special-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
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-filter-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-filter-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-filter-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 () ;FIXME: need this?
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-filter-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-filter-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-special-buffer-name (buffer-type file-list) ;FIXME: rename to `filtered'
1824 "Rename Todos special 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-or-edit-comment) ;FIXME: or just "c"?
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
2323 ("AD" . todos-archive-category-done-items) ;FIXME
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-filter-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 ;; FIXME: is this right?
2493 (set (make-local-variable 'todos-categories) (todos-set-categories))
2494 (set (make-local-variable 'todos-category-number) 1)
2495 (set (make-local-variable 'todos-first-visit) t)
2496 (add-hook 'find-file-hook 'todos-display-as-todos-file nil t))
2497
2498 (put 'todos-mode 'mode-class 'special)
2499
2500 ;; Autoloading isn't needed if files are identified by auto-mode-alist
2501 ;; ;; As calendar reads included Todos file before todos-mode is loaded.
2502 ;; ;;;###autoload
2503 (define-derived-mode todos-mode special-mode "Todos" ()
2504 "Major mode for displaying, navigating and editing Todo lists.
2505
2506 \\{todos-mode-map}"
2507 (easy-menu-add todos-menu)
2508 (todos-modes-set-1)
2509 (todos-modes-set-2)
2510 (todos-modes-set-3)
2511 ;; Initialize todos-current-todos-file.
2512 (when (member (file-truename (buffer-file-name))
2513 (funcall todos-files-function))
2514 (set (make-local-variable 'todos-current-todos-file)
2515 (file-truename (buffer-file-name))))
2516 (set (make-local-variable 'todos-first-visit) t)
2517 (set (make-local-variable 'todos-show-done-only) nil)
2518 (set (make-local-variable 'todos-categories-with-marks) nil)
2519 (add-hook 'find-file-hook 'todos-add-to-buffer-list nil t)
2520 (add-hook 'post-command-hook 'todos-update-buffer-list nil t)
2521 (when todos-show-current-file
2522 (add-hook 'pre-command-hook 'todos-show-current-file nil t))
2523 ;; FIXME: works more or less, but should be tied to the defcustom
2524 (add-hook 'window-configuration-change-hook
2525 (lambda ()
2526 (setq todos-done-separator (make-string (window-width) ?_)))
2527 nil t)
2528 (add-hook 'kill-buffer-hook 'todos-reset-global-current-todos-file nil t))
2529
2530 ;; FIXME: need this?
2531 (defun todos-unload-hook ()
2532 ""
2533 (remove-hook 'pre-command-hook 'todos-show-current-file t)
2534 (remove-hook 'post-command-hook 'todos-update-buffer-list t)
2535 (remove-hook 'find-file-hook 'todos-display-as-todos-file t)
2536 (remove-hook 'find-file-hook 'todos-add-to-buffer-list t)
2537 (remove-hook 'window-configuration-change-hook
2538 (lambda ()
2539 (setq todos-done-separator
2540 (make-string (window-width) ?_))) t)
2541 (remove-hook 'kill-buffer-hook 'todos-reset-global-current-todos-file t))
2542
2543 (put 'todos-archive-mode 'mode-class 'special)
2544
2545 ;; If todos-mode is parent, all todos-mode key bindings appear to be
2546 ;; available in todos-archive-mode (e.g. shown by C-h m).
2547 (define-derived-mode todos-archive-mode special-mode "Todos-Arch" ()
2548 "Major mode for archived Todos categories.
2549
2550 \\{todos-archive-mode-map}"
2551 (todos-modes-set-1)
2552 (todos-modes-set-2)
2553 (todos-modes-set-3)
2554 (set (make-local-variable 'todos-current-todos-file)
2555 (file-truename (buffer-file-name)))
2556 (set (make-local-variable 'todos-show-done-only) t))
2557
2558 (defun todos-mode-external-set ()
2559 ""
2560 (set (make-local-variable 'todos-current-todos-file)
2561 todos-global-current-todos-file)
2562 (let ((cats (with-current-buffer (find-buffer-visiting todos-current-todos-file)
2563 ;; FIXME: or just todos-categories?
2564 (todos-set-categories))))
2565 (set (make-local-variable 'todos-categories) cats)))
2566
2567 (define-derived-mode todos-edit-mode text-mode "Todos-Ed" ()
2568 "Major mode for editing multiline Todo items.
2569
2570 \\{todos-edit-mode-map}"
2571 (todos-modes-set-1)
2572 (todos-mode-external-set))
2573
2574 (put 'todos-categories-mode 'mode-class 'special)
2575
2576 (define-derived-mode todos-categories-mode special-mode "Todos-Cats" ()
2577 "Major mode for displaying and editing Todos categories.
2578
2579 \\{todos-categories-mode-map}"
2580 (todos-mode-external-set))
2581
2582 (put 'todos-filter-mode 'mode-class 'special)
2583
2584 (define-derived-mode todos-filter-items-mode special-mode "Todos-Fltr" ()
2585 "Mode for displaying and reprioritizing top priority Todos.
2586
2587 \\{todos-filter-items-mode-map}"
2588 (todos-modes-set-1)
2589 (todos-modes-set-2))
2590
2591 ;; FIXME: need this?
2592 (defun todos-save ()
2593 "Save the current Todos file."
2594 (interactive)
2595 (save-buffer)
2596 ;; (if todos-save-top-priorities-too (todos-save-top-priorities))
2597 )
2598
2599 (defun todos-quit ()
2600 "Exit the current Todos-related buffer.
2601 Depending on the specific mode, this either kills the buffer or
2602 buries it and restores state as needed."
2603 (interactive)
2604 (cond ((eq major-mode 'todos-categories-mode)
2605 (kill-buffer)
2606 (setq todos-descending-counts nil)
2607 ;; FIXME: this jumps to todo file even when todos-display-categories
2608 ;; was called from archive
2609 (todos-show))
2610 ((eq major-mode 'todos-filter-items-mode)
2611 (kill-buffer)
2612 (todos-show))
2613 ((member major-mode (list 'todos-mode 'todos-archive-mode))
2614 ;; Have to write previously nonexistant archives to file.
2615 (unless (file-exists-p (buffer-file-name)) (todos-save))
2616 ;; FIXME: make this customizable?
2617 (todos-save)
2618 (bury-buffer))))
2619
2620 ;; ---------------------------------------------------------------------------
2621 ;;; Display Commands
2622
2623 ;;;###autoload
2624 (defun todos-show (&optional solicit-file)
2625 "Visit the current Todos file and display one of its categories.
2626
2627 With non-nil prefix argument SOLICIT-FILE ask for file to visit.
2628 Otherwise, the first invocation of this command in a session
2629 visits `todos-default-todos-file' (creating it if it does not yet
2630 exist); subsequent invocations from outside of Todos mode revisit
2631 this file or, if user option `todos-show-current-file' is
2632 non-nil, whichever Todos file was visited last.
2633
2634 The category displayed on initial invocation is the first member
2635 of `todos-categories' for the current Todos file, on subsequent
2636 invocations whichever category was displayed last. If
2637 `todos-display-categories-first' is non-nil, then the first
2638 invocation of `todos-show' displays a clickable listing of the
2639 categories in the current Todos file.
2640
2641 In Todos mode just the category's unfinished todo items are shown
2642 by default. The done items are hidden, but typing
2643 `\\[todos-hide-show-done-items]' displays them below the todo
2644 items. With non-nil user option `todos-show-with-done' both todo
2645 and done items are always shown on visiting a category.
2646
2647 If this command is invoked in Todos Archive mode, it visits the
2648 corresponding Todos file, displaying the corresponding category."
2649 (interactive "P")
2650 (let* ((cat)
2651 (file (cond (solicit-file
2652 (if (funcall todos-files-function)
2653 (todos-read-file-name "Choose a Todos file to visit: "
2654 nil t)
2655 (error "There are no Todos files")))
2656 ((and (eq major-mode 'todos-archive-mode)
2657 ;; Called noninteractively via todos-quit from
2658 ;; Todos Categories mode to return to archive file.
2659 (called-interactively-p 'any))
2660 (setq cat (todos-current-category))
2661 (concat (file-name-sans-extension todos-current-todos-file)
2662 ".todo"))
2663 (t
2664 ;; FIXME: If an archive is value of
2665 ;; todos-current-todos-file, todos-show will revisit it
2666 ;; rather than the corresponding todo file -- ok or make
2667 ;; it customizable?
2668 (or todos-current-todos-file
2669 (and todos-show-current-file
2670 todos-global-current-todos-file)
2671 todos-default-todos-file
2672 (todos-add-file))))))
2673 (if (and todos-first-visit todos-display-categories-first)
2674 (todos-display-categories)
2675 (set-window-buffer (selected-window)
2676 (set-buffer (find-file-noselect file)))
2677 ;; If called from archive file, show corresponding category in Todos
2678 ;; file, if it exists.
2679 (when (assoc cat todos-categories)
2680 (setq todos-category-number (todos-category-number cat)))
2681 ;; If no Todos file exists, initialize one.
2682 (when (zerop (buffer-size))
2683 ;; Call with empty category name to get initial prompt.
2684 (setq todos-category-number (todos-add-category "")))
2685 (save-excursion (todos-category-select)))
2686 (setq todos-first-visit nil)))
2687
2688 (defun todos-display-categories ()
2689 "Display a table of the current file's categories and item counts.
2690
2691 In the initial display the categories are numbered, indicating
2692 their current order for navigating by \\[todos-forward-category]
2693 and \\[todos-backward-category]. You can persistantly change the
2694 order of the category at point by typing
2695 \\[todos-raise-category-priority] or
2696 \\[todos-lower-category-priority].
2697
2698 The labels above the category names and item counts are buttons,
2699 and clicking these changes the display: sorted by category name
2700 or by the respective item counts (alternately descending or
2701 ascending). In these displays the categories are not numbered
2702 and \\[todos-raise-category-priority] and
2703 \\[todos-lower-category-priority] are
2704 disabled. (Programmatically, the sorting is triggered by passing
2705 a non-nil SORTKEY argument.)
2706
2707 In addition, the lines with the category names and item counts
2708 are buttonized, and pressing one of these button jumps to the
2709 category in Todos mode (or Todos Archive mode, for categories
2710 containing only archived items, provided user option
2711 `todos-skip-archived-categories' is non-nil. These categories
2712 are shown in `todos-archived-only' face."
2713 (interactive)
2714 (todos-display-categories-1)
2715 (let (sortkey)
2716 (todos-update-categories-display sortkey)))
2717
2718 ;; ;; FIXME: make this toggle with todos-display-categories
2719 ;; (defun todos-display-categories-alphabetically ()
2720 ;; ""
2721 ;; (interactive)
2722 ;; (todos-display-sorted 'alpha))
2723
2724 ;; ;; FIXME: provide key bindings for these or delete them
2725 ;; (defun todos-display-categories-sorted-by-todo ()
2726 ;; ""
2727 ;; (interactive)
2728 ;; (todos-display-sorted 'todo))
2729
2730 ;; (defun todos-display-categories-sorted-by-diary ()
2731 ;; ""
2732 ;; (interactive)
2733 ;; (todos-display-sorted 'diary))
2734
2735 ;; (defun todos-display-categories-sorted-by-done ()
2736 ;; ""
2737 ;; (interactive)
2738 ;; (todos-display-sorted 'done))
2739
2740 ;; (defun todos-display-categories-sorted-by-archived ()
2741 ;; ""
2742 ;; (interactive)
2743 ;; (todos-display-sorted 'archived))
2744
2745 (defun todos-show-archive (&optional ask)
2746 "Visit the archive of the current Todos category, if it exists.
2747 If the category has no archived items, prompt to visit the
2748 archive anyway. If there is no archive for this file or with
2749 non-nil argument ASK, prompt to visit another archive.
2750
2751 The buffer showing the archive is in Todos Archive mode. The
2752 first visit in a session displays the first category in the
2753 archive, subsequent visits return to the last category
2754 displayed."
2755 (interactive)
2756 (let* ((cat (todos-current-category))
2757 (count (todos-get-count 'archived cat))
2758 (archive (concat (file-name-sans-extension todos-current-todos-file)
2759 ".toda"))
2760 place)
2761 (setq place (cond (ask 'other-archive)
2762 ((file-exists-p archive) 'this-archive)
2763 (t (when (y-or-n-p (concat "This file has no archive; "
2764 "visit another archive? "))
2765 'other-archive))))
2766 (when (eq place 'other-archive)
2767 (setq archive (todos-read-file-name "Choose a Todos archive: " t t)))
2768 (when (and (eq place 'this-archive) (zerop count))
2769 (setq place (when (y-or-n-p
2770 (concat "This category has no archived items;"
2771 " visit archive anyway? "))
2772 'other-cat)))
2773 (when place
2774 (set-window-buffer (selected-window)
2775 (set-buffer (find-file-noselect archive)))
2776 (if (member place '(other-archive other-cat))
2777 (setq todos-category-number 1)
2778 (todos-category-number cat))
2779 (todos-category-select))))
2780
2781 (defun todos-choose-archive ()
2782 "Choose an archive and visit it."
2783 (interactive)
2784 (todos-show-archive t))
2785
2786 (defun todos-hide-show-item-numbering ()
2787 ""
2788 (interactive)
2789 (todos-reset-prefix 'todos-number-priorities (not todos-number-priorities)))
2790
2791 (defun todos-hide-show-done-items ()
2792 "Show hidden or hide visible done items in current category."
2793 (interactive)
2794 (if (zerop (todos-get-count 'done (todos-current-category)))
2795 (message "There are no done items in this category.")
2796 (save-excursion
2797 (goto-char (point-min))
2798 (let ((todos-show-with-done (not (re-search-forward
2799 todos-done-string-start nil t))))
2800 (todos-category-select)))))
2801
2802 (defun todos-show-done-only ()
2803 "Switch between displaying only done or only todo items."
2804 (interactive)
2805 (setq todos-show-done-only (not todos-show-done-only))
2806 (todos-category-select))
2807
2808 (defun todos-highlight-item ()
2809 "Toggle highlighting the todo item the cursor is on."
2810 (interactive)
2811 (require 'hl-line)
2812 (if hl-line-mode
2813 (hl-line-mode -1)
2814 (hl-line-mode 1)))
2815
2816 (defun todos-hide-show-date-time () ;(&optional all)
2817 "Hide or show date-time header of todo items.";; in current category.
2818 ;; With non-nil prefix argument ALL do this in the whole file."
2819 (interactive "P")
2820 (save-excursion
2821 (save-restriction
2822 (goto-char (point-min))
2823 (let ((ovs (overlays-in (point) (1+ (point))))
2824 ov hidden)
2825 (while ovs
2826 (setq ov (pop ovs))
2827 (if (equal (overlay-get ov 'display) "")
2828 (setq ovs nil hidden t)))
2829 ;; (when all
2830 (widen)
2831 (goto-char (point-min));)
2832 (if hidden
2833 (remove-overlays (point-min) (point-max) 'display "")
2834 (while (not (eobp))
2835 (when (re-search-forward
2836 (concat todos-date-string-start todos-date-pattern
2837 "\\( " diary-time-regexp "\\)?"
2838 (regexp-quote todos-nondiary-end) "? ")
2839 nil t)
2840 (unless (save-match-data (todos-done-item-p))
2841 (setq ov (make-overlay (match-beginning 0) (match-end 0) nil t))
2842 (overlay-put ov 'display "")))
2843 (todos-forward-item)))))))
2844
2845 (defun todos-mark-unmark-item (&optional n all)
2846 "Mark item at point if unmarked, or unmark it if marked.
2847
2848 With a positive numerical prefix argument N, change the
2849 markedness of the next N items. With non-nil argument ALL, mark
2850 all visible items in the category (depending on visibility, all
2851 todo and done items, or just todo or just done items).
2852
2853 The mark is the character \"*\" inserted in front of the item's
2854 priority number or the `todos-prefix' string; if `todos-prefix'
2855 is \"*\", then the mark is \"@\"."
2856 (interactive "p")
2857 (if all (goto-char (point-min)))
2858 (unless (> n 0) (setq n 1))
2859 (let ((i 0))
2860 (while (or (and all (not (eobp)))
2861 (< i n))
2862 (let* ((cat (todos-current-category))
2863 (ov (todos-marked-item-p))
2864 (marked (assoc cat todos-categories-with-marks)))
2865 (if (and ov (not all))
2866 (progn
2867 (delete-overlay ov)
2868 (if (= (cdr marked) 1) ; Deleted last mark in this category.
2869 (setq todos-categories-with-marks
2870 (assq-delete-all cat todos-categories-with-marks))
2871 (setcdr marked (1- (cdr marked)))))
2872 (when (todos-item-start)
2873 (unless (and all (todos-marked-item-p))
2874 (setq ov (make-overlay (point) (point)))
2875 (overlay-put ov 'before-string todos-item-mark)
2876 (if marked
2877 (setcdr marked (1+ (cdr marked)))
2878 (push (cons cat 1) todos-categories-with-marks))))))
2879 (todos-forward-item)
2880 (setq i (1+ i)))))
2881
2882 (defun todos-mark-category ()
2883 "Put the \"*\" mark on all items in this category.
2884 \(If `todos-prefix' is \"*\", then the mark is \"@\".)"
2885 (interactive)
2886 (todos-mark-unmark-item 0 t))
2887
2888 (defun todos-unmark-category ()
2889 "Remove the \"*\" mark from all items in this category.
2890 \(If `todos-prefix' is \"*\", then the mark is \"@\".)"
2891 (interactive)
2892 (remove-overlays (point-min) (point-max) 'before-string todos-item-mark)
2893 (setq todos-categories-with-marks
2894 (delq (assoc (todos-current-category) todos-categories-with-marks)
2895 todos-categories-with-marks)))
2896
2897 (defun todos-set-top-priorities-in-file ()
2898 "Set number of top priorities for this file.
2899 See `todos-set-top-priorities' for more details."
2900 (interactive)
2901 (todos-set-top-priorities))
2902
2903 (defun todos-set-top-priorities-in-category ()
2904 "Set number of top priorities for this category.
2905 See `todos-set-top-priorities' for more details."
2906 (interactive)
2907 (todos-set-top-priorities t))
2908
2909 (defun todos-top-priorities (&optional num)
2910 "List top priorities of each category in `todos-filter-files'.
2911 Number of entries for each category is given by NUM, which
2912 defaults to `todos-show-priorities'."
2913 (interactive "P")
2914 (let ((arg (if num (cons 'top num) 'top))
2915 (buf todos-top-priorities-buffer)
2916 (file todos-current-todos-file))
2917 (todos-filter-items arg)
2918 (todos-special-buffer-name buf file)))
2919
2920 (defun todos-top-priorities-multifile (&optional arg)
2921 "List top priorities of each category in `todos-filter-files'.
2922
2923 If the prefix argument ARG is a number, this is the maximum
2924 number of top priorities to list in each category. If the prefix
2925 argument is `C-u', prompt for which files to filter and use
2926 `todos-show-priorities' as the number of top priorities to list
2927 in each category. If the prefix argument is `C-uC-u', prompt
2928 both for which files to filter and for how many top priorities to
2929 list in each category."
2930 (interactive "P")
2931 (let* ((buf todos-top-priorities-buffer)
2932 files
2933 (pref (if (numberp arg)
2934 (cons 'top arg)
2935 (setq files (if (or (consp arg)
2936 (null todos-filter-files))
2937 (progn (todos-multiple-files)
2938 todos-multiple-files)
2939 todos-filter-files))
2940 (if (equal arg '(16))
2941 (cons 'top (read-number
2942 "Enter number of top priorities to show: "
2943 todos-show-priorities))
2944 'top))))
2945 (todos-filter-items pref t)
2946 (todos-special-buffer-name buf files)))
2947
2948 (defun todos-diary-items ()
2949 "Display todo items for diary inclusion in this Todos file."
2950 (interactive)
2951 (let ((buf todos-diary-items-buffer)
2952 (file todos-current-todos-file))
2953 (todos-filter-items 'diary)
2954 (todos-special-buffer-name buf file)))
2955
2956 (defun todos-diary-items-multifile (&optional arg)
2957 "Display todo items for diary inclusion in one or more Todos file.
2958 The files are those listed in `todos-filter-files'."
2959 (interactive "P")
2960 (let ((buf todos-diary-items-buffer)
2961 (files (if (or arg (null todos-filter-files))
2962 (progn (todos-multiple-files)
2963 todos-multiple-files)
2964 todos-filter-files)))
2965 (todos-filter-items 'diary t)
2966 (todos-special-buffer-name buf files)))
2967
2968 (defun todos-regexp-items ()
2969 "Display todo items matching a user-entered regular expression.
2970 The items are those in the current Todos file."
2971 (interactive)
2972 (let ((buf todos-regexp-items-buffer)
2973 (file todos-current-todos-file))
2974 (todos-filter-items 'regexp)
2975 (todos-special-buffer-name buf file)))
2976
2977 (defun todos-regexp-items-multifile (&optional arg)
2978 "Display todo items matching a user-entered regular expression.
2979 The items are those in the files listed in `todos-filter-files'."
2980 (interactive "P")
2981 (let ((buf todos-regexp-items-buffer)
2982 (files (if (or arg (null todos-filter-files))
2983 (progn (todos-multiple-files)
2984 todos-multiple-files)
2985 todos-filter-files)))
2986 (todos-filter-items 'regexp t)
2987 (todos-special-buffer-name buf files)))
2988
2989 (defun todos-print (&optional to-file)
2990 "Produce a printable version of the current Todos buffer.
2991 This converts overlays and soft line wrapping and, depending on
2992 the value of `todos-print-function', includes faces. With
2993 non-nil argument TO-FILE write the printable version to a file;
2994 otherwise, send it to the default printer."
2995 (interactive)
2996 (let ((buf todos-print-buffer)
2997 (header (cond
2998 ((eq major-mode 'todos-mode)
2999 (concat "Todos File: "
3000 (todos-short-file-name todos-current-todos-file)
3001 "\nCategory: " (todos-current-category)))
3002 ((eq major-mode 'todos-filter-items-mode)
3003 "Todos Top Priorities")))
3004 (prefix (propertize (concat todos-prefix " ")
3005 'face 'todos-prefix-string))
3006 (num 0)
3007 (fill-prefix (make-string todos-indent-to-here 32))
3008 (content (buffer-string))
3009 file)
3010 (with-current-buffer (get-buffer-create buf)
3011 (insert content)
3012 (goto-char (point-min))
3013 (while (not (eobp))
3014 (let ((beg (point))
3015 (end (save-excursion (todos-item-end))))
3016 (when todos-number-priorities
3017 (setq num (1+ num))
3018 (setq prefix (propertize (concat (number-to-string num) " ")
3019 'face 'todos-prefix-string)))
3020 (insert prefix)
3021 (fill-region beg end))
3022 ;; Calling todos-forward-item infloops at todos-item-start due to
3023 ;; non-overlay prefix, so search for item start instead.
3024 (if (re-search-forward todos-item-start nil t)
3025 (beginning-of-line)
3026 (goto-char (point-max))))
3027 (if (re-search-backward (concat "^" (regexp-quote todos-category-done))
3028 nil t)
3029 (replace-match todos-done-separator))
3030 (goto-char (point-min))
3031 (insert header)
3032 (newline 2)
3033 (if to-file
3034 (let ((file (read-file-name "Print to file: ")))
3035 (funcall todos-print-function file))
3036 (funcall todos-print-function)))
3037 (kill-buffer buf)))
3038
3039 (defun todos-print-to-file ()
3040 "Save printable version of this Todos buffer to a file."
3041 (interactive)
3042 (todos-print t))
3043
3044 (defun todos-convert-legacy-files ()
3045 "Convert legacy Todo files to the current Todos format.
3046 The files `todo-file-do' and `todo-file-done' are converted and
3047 saved (the latter as a Todos Archive file) with a new name in
3048 `todos-files-directory'. See also the documentation string of
3049 `todos-todo-mode-date-time-regexp' for further details."
3050 (interactive)
3051 (if (fboundp 'todo-mode)
3052 (require 'todo-mode)
3053 (error "Void function `todo-mode'"))
3054 ;; Convert `todo-file-do'.
3055 (if (file-exists-p todo-file-do)
3056 (let ((default "todo-do-conv")
3057 file archive-sexp)
3058 (with-temp-buffer
3059 (insert-file-contents todo-file-do)
3060 (let ((end (search-forward ")" (line-end-position) t))
3061 (beg (search-backward "(" (line-beginning-position) t)))
3062 (setq todo-categories
3063 (read (buffer-substring-no-properties beg end))))
3064 (todo-mode)
3065 (delete-region (line-beginning-position) (1+ (line-end-position)))
3066 (while (not (eobp))
3067 (cond
3068 ((looking-at (regexp-quote (concat todo-prefix todo-category-beg)))
3069 (replace-match todos-category-beg))
3070 ((looking-at (regexp-quote todo-category-end))
3071 (replace-match ""))
3072 ((looking-at (regexp-quote (concat todo-prefix " "
3073 todo-category-sep)))
3074 (replace-match todos-category-done))
3075 ((looking-at (concat (regexp-quote todo-prefix) " "
3076 todos-todo-mode-date-time-regexp " "
3077 (regexp-quote todo-initials) ":"))
3078 (todos-convert-legacy-date-time)))
3079 (forward-line))
3080 (setq file (concat todos-files-directory
3081 (read-string
3082 (format "Save file as (default \"%s\"): " default)
3083 nil nil default)
3084 ".todo"))
3085 (write-region (point-min) (point-max) file nil 'nomessage nil t))
3086 (with-temp-buffer
3087 (insert-file-contents file)
3088 (let ((todos-categories (todos-make-categories-list t)))
3089 (todos-update-categories-sexp))
3090 (write-region (point-min) (point-max) file nil 'nomessage))
3091 ;; Convert `todo-file-done'.
3092 (when (file-exists-p todo-file-done)
3093 (with-temp-buffer
3094 (insert-file-contents todo-file-done)
3095 (let ((beg (make-marker))
3096 (end (make-marker))
3097 cat cats comment item)
3098 (while (not (eobp))
3099 (when (looking-at todos-todo-mode-date-time-regexp)
3100 (set-marker beg (point))
3101 (todos-convert-legacy-date-time)
3102 (set-marker end (point))
3103 (goto-char beg)
3104 (insert "[" todos-done-string)
3105 (goto-char end)
3106 (insert "]")
3107 (forward-char)
3108 (when (looking-at todos-todo-mode-date-time-regexp)
3109 (todos-convert-legacy-date-time))
3110 (when (looking-at (concat " " (regexp-quote todo-initials) ":"))
3111 (replace-match "")))
3112 (if (re-search-forward
3113 (concat "^" todos-todo-mode-date-time-regexp) nil t)
3114 (goto-char (match-beginning 0))
3115 (goto-char (point-max)))
3116 (backward-char)
3117 (when (looking-back "\\[\\([^][]+\\)\\]")
3118 (setq cat (match-string 1))
3119 (goto-char (match-beginning 0))
3120 (replace-match ""))
3121 ;; If the item ends with a non-comment parenthesis not
3122 ;; followed by a period, we lose (but we inherit that problem
3123 ;; from todo-mode.el).
3124 (when (looking-back "(\\(.*\\)) ")
3125 (setq comment (match-string 1))
3126 (replace-match "")
3127 (insert "[" todos-comment-string ": " comment "]"))
3128 (set-marker end (point))
3129 (if (member cat cats)
3130 ;; If item is already in its category, leave it there.
3131 (unless (save-excursion
3132 (re-search-backward
3133 (concat "^" (regexp-quote todos-category-beg)
3134 "\\(.*\\)$") nil t)
3135 (string= (match-string 1) cat))
3136 ;; Else move it to its category.
3137 (setq item (buffer-substring-no-properties beg end))
3138 (delete-region beg (1+ end))
3139 (set-marker beg (point))
3140 (re-search-backward
3141 (concat "^" (regexp-quote (concat todos-category-beg cat)))
3142 nil t)
3143 (forward-line)
3144 (if (re-search-forward
3145 (concat "^" (regexp-quote todos-category-beg)
3146 "\\(.*\\)$") nil t)
3147 (progn (goto-char (match-beginning 0))
3148 (newline)
3149 (forward-line -1))
3150 (goto-char (point-max)))
3151 (insert item "\n")
3152 (goto-char beg))
3153 (push cat cats)
3154 (goto-char beg)
3155 (insert todos-category-beg cat "\n\n" todos-category-done "\n"))
3156 (forward-line))
3157 (set-marker beg nil)
3158 (set-marker end nil))
3159 (setq file (concat (file-name-sans-extension file) ".toda"))
3160 (write-region (point-min) (point-max) file nil 'nomessage nil t))
3161 (with-temp-buffer
3162 (insert-file-contents file)
3163 (let ((todos-categories (todos-make-categories-list t)))
3164 (todos-update-categories-sexp))
3165 (write-region (point-min) (point-max) file nil 'nomessage)
3166 (setq archive-sexp (read (buffer-substring-no-properties
3167 (line-beginning-position)
3168 (line-end-position)))))
3169 (setq file (concat (file-name-sans-extension file) ".todo"))
3170 ;; Update categories sexp of converted Todos file again, adding
3171 ;; counts of archived items.
3172 (with-temp-buffer
3173 (insert-file-contents file)
3174 (let ((sexp (read (buffer-substring-no-properties
3175 (line-beginning-position)
3176 (line-end-position)))))
3177 (dolist (cat sexp)
3178 (let ((archive-cat (assoc (car cat) archive-sexp)))
3179 (if archive-cat
3180 (aset (cdr cat) 3 (aref (cdr archive-cat) 2)))))
3181 (delete-region (line-beginning-position) (line-end-position))
3182 (prin1 sexp (current-buffer)))
3183 (write-region (point-min) (point-max) file nil 'nomessage)))
3184 (todos-reevaluate-defcustoms)
3185 (message "Format conversion done."))
3186 (error "No legacy Todo file exists")))
3187
3188 ;; ---------------------------------------------------------------------------
3189 ;;; Navigation Commands
3190
3191 (defun todos-forward-category (&optional back)
3192 "Visit the numerically next category in this Todos file.
3193 If the current category is the highest numbered, visit the first
3194 category. With non-nil argument BACK, visit the numerically
3195 previous category (the highest numbered one, if the current
3196 category is the first)."
3197 (interactive)
3198 (setq todos-category-number
3199 (1+ (mod (- todos-category-number (if back 2 0))
3200 (length todos-categories))))
3201 (when todos-skip-archived-categories
3202 (while (and (zerop (todos-get-count 'todo))
3203 (zerop (todos-get-count 'done))
3204 (not (zerop (todos-get-count 'archive))))
3205 (setq todos-category-number
3206 (apply (if back '1- '1+) (list todos-category-number)))))
3207 (todos-category-select)
3208 (goto-char (point-min)))
3209
3210 (defun todos-backward-category ()
3211 "Visit the numerically previous category in this Todos file.
3212 If the current category is the highest numbered, visit the first
3213 category."
3214 (interactive)
3215 (todos-forward-category t))
3216
3217 (defun todos-jump-to-category (&optional cat other-file)
3218 "Jump to a category in this or another Todos file.
3219
3220 Programmatically, optional argument CAT provides the category
3221 name. When nil (as in interactive calls), prompt for the
3222 category, with TAB completion on existing categories. If a
3223 non-existing category name is entered, ask whether to add a new
3224 category with this name; if affirmed, add it, then jump to that
3225 category. With non-nil argument OTHER-FILE, prompt for a Todos
3226 file, otherwise jump within the current Todos file."
3227 (interactive)
3228 (let ((file (or (and other-file
3229 (todos-read-file-name "Choose a Todos file: " nil t))
3230 ;; Jump to archived-only Categories from Todos Categories
3231 ;; mode.
3232 (and cat
3233 todos-skip-archived-categories
3234 (zerop (todos-get-count 'todo cat))
3235 (zerop (todos-get-count 'done cat))
3236 (not (zerop (todos-get-count 'archived cat)))
3237 (concat (file-name-sans-extension
3238 todos-current-todos-file) ".toda"))
3239 todos-current-todos-file
3240 ;; If invoked from outside of Todos mode before
3241 ;; todos-show...
3242 todos-default-todos-file)))
3243 (with-current-buffer (find-file-noselect file)
3244 (and other-file (setq todos-current-todos-file file))
3245 (let ((category (or (and (assoc cat todos-categories) cat)
3246 (todos-read-category "Jump to category: "))))
3247 ;; Clean up after selecting category in Todos Categories mode.
3248 (if (string= (buffer-name) todos-categories-buffer)
3249 (kill-buffer))
3250 (if (or cat other-file)
3251 (set-window-buffer (selected-window)
3252 (set-buffer (find-buffer-visiting file))))
3253 (unless todos-global-current-todos-file
3254 (setq todos-global-current-todos-file todos-current-todos-file))
3255 (todos-category-number category) ; (1+ (length t-c)) if new category.
3256 ;; (if (> todos-category-number (length todos-categories))
3257 ;; (setq todos-category-number (todos-add-category category)))
3258 (todos-category-select)
3259 (goto-char (point-min))))))
3260
3261 (defun todos-jump-to-category-other-file ()
3262 "Jump to a category in another Todos file.
3263 The category is chosen by prompt, with TAB completion."
3264 (interactive)
3265 (todos-jump-to-category nil t))
3266
3267 (defun todos-jump-to-item ()
3268 "Jump to the file and category of the filtered item at point."
3269 (interactive)
3270 (let ((str (todos-item-string))
3271 (buf (current-buffer))
3272 cat file archive beg)
3273 (string-match (concat (if todos-filter-done-items
3274 (concat "\\(?:" todos-done-string-start "\\|"
3275 todos-date-string-start "\\)")
3276 todos-date-string-start)
3277 todos-date-pattern "\\(?: " diary-time-regexp "\\)?"
3278 (if todos-filter-done-items
3279 "\\]"
3280 (regexp-quote todos-nondiary-end)) "?"
3281 "\\(?4: \\[\\(?3:(archive) \\)?\\(?2:.*:\\)?"
3282 "\\(?1:.*\\)\\]\\).*$") str)
3283 (setq cat (match-string 1 str))
3284 (setq file (match-string 2 str))
3285 (setq archive (string= (match-string 3 str) "(archive) "))
3286 (setq str (replace-match "" nil nil str 4))
3287 (setq file (if file
3288 (concat todos-files-directory (substring file 0 -1)
3289 (if archive ".toda" ".todo"))
3290 (if archive
3291 (concat (file-name-sans-extension
3292 todos-global-current-todos-file) ".toda")
3293 todos-global-current-todos-file)))
3294 (find-file-noselect file)
3295 (with-current-buffer (find-buffer-visiting file)
3296 (widen)
3297 (goto-char (point-min))
3298 (re-search-forward
3299 (concat "^" (regexp-quote (concat todos-category-beg cat))) nil t)
3300 (search-forward str)
3301 (setq beg (match-beginning 0)))
3302 (kill-buffer buf)
3303 (set-window-buffer (selected-window) (set-buffer (find-buffer-visiting file)))
3304 (setq todos-current-todos-file file)
3305 (setq todos-category-number (todos-category-number cat))
3306 (let ((todos-show-with-done (if todos-filter-done-items t
3307 todos-show-with-done)))
3308 (todos-category-select))
3309 (goto-char beg)))
3310
3311 ;; FIXME ? disallow prefix arg value < 1 (re-search-* allows these)
3312 (defun todos-forward-item (&optional count)
3313 "Move point down to start of item with next lower priority.
3314 With numerical prefix COUNT, move point COUNT items downward,"
3315 (interactive "P")
3316 (let* ((not-done (not (or (todos-done-item-p) (looking-at "^$"))))
3317 (start (line-end-position)))
3318 (goto-char start)
3319 (if (re-search-forward todos-item-start nil t (or count 1))
3320 (goto-char (match-beginning 0))
3321 (goto-char (point-max)))
3322 ;; If points advances by one from a todo to a done item, go back to the
3323 ;; space above todos-done-separator, since that is a legitimate place to
3324 ;; insert an item. But skip this space if count > 1, since that should
3325 ;; only stop on an item (FIXME: or not?)
3326 (when (and not-done (todos-done-item-p))
3327 (if (or (not count) (= count 1))
3328 (re-search-backward "^$" start t)))))
3329 ;; FIXME: The preceding sexp is insufficient when buffer is not narrowed,
3330 ;; since there could be no done items in this category, so the search puts
3331 ;; us on first todo item of next category. Does this ever happen? If so:
3332 ;; (let ((opoint) (point))
3333 ;; (forward-line -1)
3334 ;; (when (or (not count) (= count 1))
3335 ;; (cond ((looking-at (concat "^" (regexp-quote todos-category-beg)))
3336 ;; (forward-line -2))
3337 ;; ((looking-at (concat "^" (regexp-quote todos-category-done)))
3338 ;; (forward-line -1))
3339 ;; (t
3340 ;; (goto-char opoint)))))))
3341
3342 (defun todos-backward-item (&optional count)
3343 "Move point up to start of item with next higher priority.
3344 With numerical prefix COUNT, move point COUNT items upward,"
3345 (interactive "P")
3346 (let* ((done (todos-done-item-p)))
3347 ;; FIXME ? this moves to bob if on the first item (but so does previous-line)
3348 (todos-item-start)
3349 (unless (bobp)
3350 (re-search-backward todos-item-start nil t (or count 1)))
3351 ;; Unless this is a regexp filtered items buffer (which can contain
3352 ;; intermixed todo and done items), if points advances by one from a done
3353 ;; to a todo item, go back to the space above todos-done-separator, since
3354 ;; that is a legitimate place to insert an item. But skip this space if
3355 ;; count > 1, since that should only stop on an item (FIXME: or not?)
3356 (when (and done (not (todos-done-item-p)) (or (not count) (= count 1))
3357 (not (equal (buffer-name) todos-regexp-items-buffer)))
3358 (re-search-forward (concat "^" (regexp-quote todos-category-done)) nil t)
3359 (forward-line -1))))
3360
3361 ;; FIXME: (i) Extend search to other Todos files. (ii) Allow navigating among
3362 ;; hits. (But these are available in another form with
3363 ;; todos-regexp-items-multifile.)
3364 (defun todos-search ()
3365 "Search for a regular expression in this Todos file.
3366 The search runs through the whole file and encompasses all and
3367 only todo and done items; it excludes category names. Multiple
3368 matches are shown sequentially, highlighted in `todos-search'
3369 face."
3370 (interactive)
3371 (let ((regex (read-from-minibuffer "Enter a search string (regexp): "))
3372 (opoint (point))
3373 matches match cat in-done ov mlen msg)
3374 (widen)
3375 (goto-char (point-min))
3376 (while (not (eobp))
3377 (setq match (re-search-forward regex nil t))
3378 (goto-char (line-beginning-position))
3379 (unless (or (equal (point) 1)
3380 (looking-at (concat "^" (regexp-quote todos-category-beg))))
3381 (if match (push match matches)))
3382 (forward-line))
3383 (setq matches (reverse matches))
3384 (if matches
3385 (catch 'stop
3386 (while matches
3387 (setq match (pop matches))
3388 (goto-char match)
3389 (todos-item-start)
3390 (when (looking-at todos-done-string-start)
3391 (setq in-done t))
3392 (re-search-backward (concat "^" (regexp-quote todos-category-beg)
3393 "\\(.*\\)\n") nil t)
3394 (setq cat (match-string-no-properties 1))
3395 (todos-category-number cat)
3396 (todos-category-select)
3397 (if in-done
3398 (unless todos-show-with-done (todos-hide-show-done-items)))
3399 (goto-char match)
3400 (setq ov (make-overlay (- (point) (length regex)) (point)))
3401 (overlay-put ov 'face 'todos-search)
3402 (when matches
3403 (setq mlen (length matches))
3404 (if (y-or-n-p
3405 (if (> mlen 1)
3406 (format "There are %d more matches; go to next match? "
3407 mlen)
3408 "There is one more match; go to it? "))
3409 (widen)
3410 (throw 'stop (setq msg (if (> mlen 1)
3411 (format "There are %d more matches."
3412 mlen)
3413 "There is one more match."))))))
3414 (setq msg "There are no more matches."))
3415 (todos-category-select)
3416 (goto-char opoint)
3417 (message "No match for \"%s\"" regex))
3418 (when msg
3419 (if (y-or-n-p (concat msg "\nUnhighlight matches? "))
3420 (todos-clear-matches)
3421 (message "You can unhighlight the matches later by typing %s"
3422 (key-description (car (where-is-internal
3423 'todos-clear-matches))))))))
3424
3425 (defun todos-clear-matches ()
3426 "Remove highlighting on matches found by todos-search."
3427 (interactive)
3428 (remove-overlays 1 (1+ (buffer-size)) 'face 'todos-search))
3429
3430 ;; ---------------------------------------------------------------------------
3431 ;;; Editing Commands
3432
3433 (defun todos-add-file ()
3434 "Name and add a new Todos file.
3435 Interactively, prompt for a category and display it.
3436 Noninteractively, return the name of the new file."
3437 (interactive)
3438 (let ((prompt (concat "Enter name of new Todos file "
3439 "(TAB or SPC to see current names): "))
3440 file)
3441 (setq file (todos-read-file-name prompt))
3442 (with-current-buffer (get-buffer-create file)
3443 (erase-buffer)
3444 (write-region (point-min) (point-max) file nil 'nomessage nil t)
3445 (kill-buffer file))
3446 (todos-reevaluate-defcustoms)
3447 (if (called-interactively-p)
3448 (progn
3449 (set-window-buffer (selected-window)
3450 (set-buffer (find-file-noselect file)))
3451 (setq todos-current-todos-file file)
3452 (todos-show))
3453 file)))
3454
3455 (defun todos-add-category (&optional cat)
3456 "Add a new category to the current Todos file.
3457 Called interactively, prompts for category name, then visits the
3458 category in Todos mode. Non-interactively, argument CAT provides
3459 the category name and the return value is the category number."
3460 (interactive)
3461 (let* ((buffer-read-only)
3462 (num (1+ (length todos-categories)))
3463 (counts (make-vector 4 0))) ; [todo diary done archived]
3464 (if cat
3465 (setq cat (todos-validate-name cat 'category)) ;FIXME: need this?
3466 (setq cat (todos-read-category "Enter new category name: " nil t)))
3467 (setq todos-categories (append todos-categories (list (cons cat counts))))
3468 (widen)
3469 (goto-char (point-max))
3470 (save-excursion ; Save point for todos-category-select.
3471 (insert todos-category-beg cat "\n\n" todos-category-done "\n"))
3472 (todos-update-categories-sexp)
3473 ;; If called by command, display the newly added category, else return
3474 ;; the category number to the caller.
3475 (if (called-interactively-p 'any) ; FIXME?
3476 (progn
3477 (setq todos-category-number num)
3478 (todos-category-select))
3479 num)))
3480
3481 (defun todos-rename-category ()
3482 "Rename current Todos category.
3483 If this file has an archive containing this category, rename the
3484 category there as well."
3485 (interactive)
3486 (let* ((cat (todos-current-category))
3487 (new (read-from-minibuffer (format "Rename category \"%s\" to: " cat))))
3488 (setq new (todos-validate-name new 'category))
3489 (let* ((ofile todos-current-todos-file)
3490 (archive (concat (file-name-sans-extension ofile) ".toda"))
3491 (buffers (append (list ofile)
3492 (unless (zerop (todos-get-count 'archived cat))
3493 (list archive)))))
3494 (dolist (buf buffers)
3495 (with-current-buffer (find-file-noselect buf)
3496 (let (buffer-read-only)
3497 (setq todos-categories (todos-set-categories))
3498 (save-excursion
3499 (save-restriction
3500 (setcar (assoc cat todos-categories) new)
3501 (widen)
3502 (goto-char (point-min))
3503 (todos-update-categories-sexp)
3504 (re-search-forward (concat (regexp-quote todos-category-beg)
3505 "\\(" (regexp-quote cat) "\\)\n")
3506 nil t)
3507 (replace-match new t t nil 1)))))))
3508 (force-mode-line-update))
3509 (save-excursion (todos-category-select)))
3510
3511 (defun todos-delete-category (&optional arg)
3512 "Delete current Todos category provided it is empty.
3513 With ARG non-nil delete the category unconditionally,
3514 i.e. including all existing todo and done items."
3515 (interactive "P")
3516 (let* ((file todos-current-todos-file)
3517 (cat (todos-current-category))
3518 (todo (todos-get-count 'todo cat))
3519 (done (todos-get-count 'done cat))
3520 (archived (todos-get-count 'archived cat)))
3521 (if (and (not arg)
3522 (or (> todo 0) (> done 0)))
3523 (message "%s" (substitute-command-keys
3524 (concat "To delete a non-empty category, "
3525 "type C-u \\[todos-delete-category].")))
3526 (when (cond ((= (length todos-categories) 1)
3527 (y-or-n-p (concat "This is the only category in this file; "
3528 "deleting it will also delete the file.\n"
3529 "Do you want to proceed? ")))
3530 ((> archived 0)
3531 (y-or-n-p (concat "This category has archived items; "
3532 "the archived category will remain\n"
3533 "after deleting the todo category. "
3534 "Do you still want to delete it\n"
3535 "(see 'todos-skip-archived-categories' "
3536 "for another option)? ")))
3537 (t
3538 (y-or-n-p (concat "Permanently remove category \"" cat
3539 "\"" (and arg " and all its entries")
3540 "? "))))
3541 (widen)
3542 (let ((buffer-read-only)
3543 (beg (re-search-backward
3544 (concat "^" (regexp-quote (concat todos-category-beg cat))
3545 "\n") nil t))
3546 (end (if (re-search-forward
3547 (concat "\n\\(" (regexp-quote todos-category-beg)
3548 ".*\n\\)") nil t)
3549 (match-beginning 1)
3550 (point-max))))
3551 (remove-overlays beg end)
3552 (delete-region beg end)
3553 (if (= (length todos-categories) 1)
3554 ;; If deleted category was the only one, delete the file.
3555 (progn
3556 (todos-reevaluate-defcustoms)
3557 ;; Skip confirming killing the archive buffer if it has been
3558 ;; modified and not saved.
3559 (set-buffer-modified-p nil)
3560 (delete-file file)
3561 (kill-buffer)
3562 (message "Deleted Todos file %s." file))
3563 (setq todos-categories (delete (assoc cat todos-categories)
3564 todos-categories))
3565 (todos-update-categories-sexp)
3566 (setq todos-category-number
3567 (1+ (mod todos-category-number (length todos-categories))))
3568 (todos-category-select)
3569 (goto-char (point-min))
3570 (message "Deleted category %s." cat)))))))
3571
3572 (defun todos-raise-category-priority (&optional lower)
3573 "Raise priority of category point is on in Todos Categories buffer.
3574 With non-nil argument LOWER, lower the category's priority."
3575 (interactive)
3576 (save-excursion
3577 (forward-line 0)
3578 (skip-chars-forward " ")
3579 (setq todos-categories-category-number (number-at-point)))
3580 (when (if lower
3581 (< todos-categories-category-number (length todos-categories))
3582 (> todos-categories-category-number 1))
3583 (let* ((col (current-column))
3584 ;; The line we're raising to, or lowering from...
3585 (beg (progn (forward-line (if lower 0 -1)) (point)))
3586 ;; ...and its number.
3587 (num1 (progn (skip-chars-forward " ") (1- (number-at-point))))
3588 ;; The number of the line we're exchanging with.
3589 (num2 (1+ num1))
3590 ;; The start of the line below the one we're exchanging with.
3591 (end (progn (forward-line 2) (point)))
3592 (catvec (vconcat todos-categories))
3593 ;; Category names and item counts of the two lines being exchanged.
3594 (cat1-list (aref catvec num1))
3595 (cat2-list (aref catvec num2))
3596 (cat1 (car cat1-list))
3597 (cat2 (car cat2-list))
3598 buffer-read-only newcats)
3599 (delete-region beg end)
3600 (setq num1 (1+ num1))
3601 (setq num2 (1- num2))
3602 ;; Exchange the lines and rebuttonize them.
3603 (setq todos-categories-category-number num2)
3604 (todos-insert-category-line cat2)
3605 (setq todos-categories-category-number num1)
3606 (todos-insert-category-line cat1)
3607 ;; Update todos-categories alist.
3608 (aset catvec num2 (cons cat2 (cdr cat2-list)))
3609 (aset catvec num1 (cons cat1 (cdr cat1-list)))
3610 (setq todos-categories (append catvec nil))
3611 (setq newcats todos-categories)
3612 (with-current-buffer (find-buffer-visiting todos-current-todos-file)
3613 (setq todos-categories newcats)
3614 (todos-update-categories-sexp))
3615 (forward-line (if lower -1 -2))
3616 (forward-char col))))
3617
3618 (defun todos-lower-category-priority ()
3619 "Lower priority of category point is on in Todos Categories buffer."
3620 (interactive)
3621 (todos-raise-category-priority t))
3622
3623 (defun todos-set-category-priority ()
3624 ""
3625 (interactive)
3626 ;; FIXME
3627 )
3628
3629 (defun todos-move-category ()
3630 "Move current category to a different Todos file.
3631 If current category has archived items, also move those to the
3632 archive of the file moved to, creating it if it does not exist."
3633 (interactive)
3634 (when (or (> (length todos-categories) 1)
3635 (y-or-n-p (concat "This is the only category in this file; "
3636 "moving it will also delete the file.\n"
3637 "Do you want to proceed? ")))
3638 (let* ((ofile todos-current-todos-file)
3639 (cat (todos-current-category))
3640 (nfile (todos-read-file-name "Choose a Todos file: " nil t))
3641 (archive (concat (file-name-sans-extension ofile) ".toda"))
3642 (buffers (append (list ofile)
3643 (unless (zerop (todos-get-count 'archived cat))
3644 (list archive))))
3645 new)
3646 (dolist (buf buffers)
3647 (with-current-buffer (find-file-noselect buf)
3648 (widen)
3649 (goto-char (point-max))
3650 (let* ((beg (re-search-backward
3651 (concat "^"
3652 (regexp-quote (concat todos-category-beg cat)))
3653 nil t))
3654 (end (if (re-search-forward
3655 (concat "^" (regexp-quote todos-category-beg))
3656 nil t 2)
3657 (match-beginning 0)
3658 (point-max)))
3659 (content (buffer-substring-no-properties beg end))
3660 (counts (cdr (assoc cat todos-categories)))
3661 buffer-read-only)
3662 ;; Move the category to the new file. Also update or create
3663 ;; archive file if necessary.
3664 (with-current-buffer
3665 (find-file-noselect
3666 ;; Regenerate todos-archives in case there
3667 ;; is a newly created archive.
3668 (if (member buf (funcall todos-files-function t))
3669 (concat (file-name-sans-extension nfile) ".toda")
3670 nfile))
3671 (let* ((nfile-short (todos-short-file-name nfile))
3672 (prompt (concat
3673 (format "Todos file \"%s\" already has "
3674 nfile-short)
3675 (format "the category \"%s\";\n" cat)
3676 "enter a new category name: "))
3677 buffer-read-only)
3678 (widen)
3679 (goto-char (point-max))
3680 (insert content)
3681 ;; If the file moved to has a category with the same
3682 ;; name, rename the moved category.
3683 (when (assoc cat todos-categories)
3684 (unless (member (file-truename (buffer-file-name))
3685 (funcall todos-files-function t))
3686 (setq new (read-from-minibuffer prompt))
3687 (setq new (todos-validate-name new 'category))))
3688 ;; Replace old with new name in Todos and archive files.
3689 (when new
3690 (goto-char (point-max))
3691 (re-search-backward
3692 (concat "^" (regexp-quote todos-category-beg)
3693 "\\(" (regexp-quote cat) "\\)") nil t)
3694 (replace-match new nil nil nil 1)))
3695 (setq todos-categories
3696 (append todos-categories (list (cons new counts))))
3697 (todos-update-categories-sexp)
3698 ;; If archive was just created, save it to avoid "File <xyz> no
3699 ;; longer exists!" message on invoking
3700 ;; `todos-view-archived-items'. FIXME: maybe better to save
3701 ;; unconditionally?
3702 (unless (file-exists-p (buffer-file-name))
3703 (save-buffer))
3704 (todos-category-number (or new cat))
3705 (todos-category-select))
3706 ;; Delete the category from the old file, and if that was the
3707 ;; last category, delete the file. Also handle archive file
3708 ;; if necessary.
3709 (remove-overlays beg end)
3710 (delete-region beg end)
3711 (goto-char (point-min))
3712 ;; Put point after todos-categories sexp.
3713 (forward-line)
3714 (if (eobp) ; Aside from sexp, file is empty.
3715 (progn
3716 ;; Skip confirming killing the archive buffer.
3717 (set-buffer-modified-p nil)
3718 (delete-file todos-current-todos-file)
3719 (kill-buffer)
3720 (when (member todos-current-todos-file todos-files)
3721 (todos-reevaluate-defcustoms)))
3722 (setq todos-categories (delete (assoc cat todos-categories)
3723 todos-categories))
3724 (todos-update-categories-sexp)
3725 (todos-category-select)))))
3726 (set-window-buffer (selected-window)
3727 (set-buffer (find-file-noselect nfile)))
3728 (todos-category-number (or new cat))
3729 (todos-category-select))))
3730
3731 (defun todos-merge-category ()
3732 "Merge current category into another category in this file.
3733 The current category's todo and done items are appended to the
3734 chosen category's todo and done items, respectively, which
3735 becomes the current category, and the category moved from is
3736 deleted."
3737 (interactive)
3738 (let ((buffer-read-only nil)
3739 (cat (todos-current-category))
3740 (goal (todos-read-category "Category to merge to: " t)))
3741 (widen)
3742 ;; FIXME: check if cat has archived items and merge those too
3743 (let* ((cbeg (progn
3744 (re-search-backward
3745 (concat "^" (regexp-quote todos-category-beg)) nil t)
3746 (point)))
3747 (tbeg (progn (forward-line) (point)))
3748 (dbeg (progn
3749 (re-search-forward
3750 (concat "^" (regexp-quote todos-category-done)) nil t)
3751 (forward-line) (point)))
3752 (tend (progn (forward-line -2) (point)))
3753 (cend (progn
3754 (if (re-search-forward
3755 (concat "^" (regexp-quote todos-category-beg)) nil t)
3756 (match-beginning 0)
3757 (point-max))))
3758 (todo (buffer-substring-no-properties tbeg tend))
3759 (done (buffer-substring-no-properties dbeg cend))
3760 here)
3761 (goto-char (point-min))
3762 (re-search-forward
3763 (concat "^" (regexp-quote (concat todos-category-beg goal))) nil t)
3764 (re-search-forward
3765 (concat "^" (regexp-quote todos-category-done)) nil t)
3766 (forward-line -1)
3767 (setq here (point))
3768 (insert todo)
3769 (goto-char (if (re-search-forward
3770 (concat "^" (regexp-quote todos-category-beg)) nil t)
3771 (match-beginning 0)
3772 (point-max)))
3773 (insert done)
3774 (remove-overlays cbeg cend)
3775 (delete-region cbeg cend)
3776 (todos-update-count 'todo (todos-get-count 'todo cat) goal)
3777 (todos-update-count 'done (todos-get-count 'done cat) goal)
3778 (setq todos-categories (delete (assoc cat todos-categories)
3779 todos-categories))
3780 (todos-update-categories-sexp)
3781 (todos-category-number goal)
3782 (todos-category-select)
3783 ;; Put point at the start of the merged todo items.
3784 ;; FIXME: what if there are no merged todo items but only done items?
3785 (goto-char here))))
3786
3787 ;; FIXME
3788 (defun todos-merge-categories ()
3789 ""
3790 (interactive)
3791 (let* ((cats (mapcar 'car todos-categories))
3792 (goal (todos-read-category "Category to merge to: " t))
3793 (prompt (format "Merge to %s (type C-g to finish)? " goal))
3794 (source (let ((inhibit-quit t) l)
3795 (while (not (eq last-input-event 7))
3796 (dolist (c cats)
3797 (when (y-or-n-p prompt)
3798 (push c l)
3799 (setq cats (delete c cats))))))))
3800 (widen)
3801 ))
3802
3803 ;; FIXME: make insertion options customizable per category?
3804 ;;;###autoload
3805 (defun todos-insert-item (&optional arg diary nonmarking date-type time
3806 region-or-here)
3807 "Add a new Todo item to a category.
3808 \(See the note at the end of this document string about key
3809 bindings and convenience commands derived from this command.)
3810
3811 With no (or nil) prefix argument ARG, add the item to the current
3812 category; with one prefix argument (C-u), prompt for a category
3813 from the current Todos file; with two prefix arguments (C-u C-u),
3814 first prompt for a Todos file, then a category in that file. If
3815 a non-existing category is entered, ask whether to add it to the
3816 Todos file; if answered affirmatively, add the category and
3817 insert the item there.
3818
3819 When argument DIARY is non-nil, this overrides the intent of the
3820 user option `todos-include-in-diary' for this item: if
3821 `todos-include-in-diary' is nil, include the item in the Fancy
3822 Diary display, and if it is non-nil, exclude the item from the
3823 Fancy Diary display. When DIARY is nil, `todos-include-in-diary'
3824 has its intended effect.
3825
3826 When the item is included in the Fancy Diary display and the
3827 argument NONMARKING is non-nil, this overrides the intent of the
3828 user option `todos-diary-nonmarking' for this item: if
3829 `todos-diary-nonmarking' is nil, append `diary-nonmarking-symbol'
3830 to the item, and if it is non-nil, omit `diary-nonmarking-symbol'.
3831
3832 The argument DATE-TYPE determines the content of the item's
3833 mandatory date header string and how it is added:
3834 - If DATE-TYPE is the symbol `calendar', the Calendar pops up and
3835 when the user puts the cursor on a date and hits RET, that
3836 date, in the format set by `calendar-date-display-form',
3837 becomes the date in the header.
3838 - If DATE-TYPE is the symbol `date', the header contains the date
3839 in the format set by `calendar-date-display-form', with year,
3840 month and day individually prompted for (month with tab
3841 completion).
3842 - If DATE-TYPE is the symbol `dayname' the header contains a
3843 weekday name instead of a date, prompted for with tab
3844 completion.
3845 - If DATE-TYPE has any other value (including nil or none) the
3846 header contains the current date (in the format set by
3847 `calendar-date-display-form').
3848
3849 With non-nil argument TIME prompt for a time string, which must
3850 match `diary-time-regexp'. Typing `<return>' at the prompt
3851 returns the current time, if the user option
3852 `todos-always-add-time-string' is non-nil, otherwise the empty
3853 string (i.e., no time string). If TIME is absent or nil, add or
3854 omit the current time string according as
3855 `todos-always-add-time-string' is non-nil or nil, respectively.
3856
3857 The argument REGION-OR-HERE determines the source and location of
3858 the new item:
3859 - If the REGION-OR-HERE is the symbol `here', prompt for the text
3860 of the new item and insert it directly above the todo item at
3861 point (hence lowering the priority of the remaining items), or
3862 if point is on the empty line below the last todo item, insert
3863 the new item there. An error is signalled if
3864 `todos-insert-item' is invoked with `here' outside of the
3865 current category.
3866 - If REGION-OR-HERE is the symbol `region', use the region of the
3867 current buffer as the text of the new item, depending on the
3868 value of user option `todos-use-only-highlighted-region': if
3869 this is non-nil, then use the region only when it is
3870 highlighted; otherwise, use the region regardless of
3871 highlighting. An error is signalled if there is no region in
3872 the current buffer. Prompt for the item's priority in the
3873 category (an integer between 1 and one more than the number of
3874 items in the category), and insert the item accordingly.
3875 - If REGION-OR-HERE has any other value (in particular, nil or
3876 none), prompt for the text and the item's priority, and insert
3877 the item accordingly.
3878
3879 To facilitate using these arguments when inserting a new todo
3880 item, convenience commands have been defined for all admissible
3881 combinations together with mnenomic key bindings based on on the
3882 name of the arguments and their order in the command's argument
3883 list: diar_y_ - nonmar_k_ing - _c_alendar or _d_ate or day_n_ame
3884 - _t_ime - _r_egion or _h_ere. These key combinations are
3885 appended to the basic insertion key (i) and keys that allow a
3886 following key must be doubled when used finally. For example,
3887 `iyh' will insert a new item with today's date, marked according
3888 to the DIARY argument described above, and with priority
3889 according to the HERE argument; while `iyy' does the same except
3890 the priority is not given by HERE but by prompting."
3891 ;; An alternative interface for customizing key
3892 ;; binding is also provided with the function
3893 ;; `todos-insertion-bindings'." ;FIXME
3894 (interactive "P")
3895 (let ((region (eq region-or-here 'region))
3896 (here (eq region-or-here 'here)))
3897 (when region
3898 (let (use-empty-active-region)
3899 (unless (and todos-use-only-highlighted-region (use-region-p))
3900 (error "There is no active region"))))
3901 (let* ((buf (current-buffer))
3902 (new-item (if region
3903 ;; FIXME: or keep properties?
3904 (buffer-substring-no-properties
3905 (region-beginning) (region-end))
3906 (read-from-minibuffer "Todo item: ")))
3907 (date-string (cond
3908 ((eq date-type 'date)
3909 (todos-read-date))
3910 ((eq date-type 'dayname)
3911 (todos-read-dayname))
3912 ((eq date-type 'calendar)
3913 (setq todos-date-from-calendar t)
3914 (todos-set-date-from-calendar))
3915 (t (calendar-date-string (calendar-current-date) t t))))
3916 (time-string (or (and time (todos-read-time))
3917 (and todos-always-add-time-string
3918 (substring (current-time-string) 11 16)))))
3919 (setq todos-date-from-calendar nil)
3920 (cond ((equal arg '(16)) ; FIXME: cf. set-mark-command
3921 (todos-jump-to-category nil t)
3922 (set-window-buffer
3923 (selected-window)
3924 (set-buffer (find-buffer-visiting todos-global-current-todos-file))))
3925 ((equal arg '(4)) ; FIXME: just arg?
3926 (todos-jump-to-category)
3927 (set-window-buffer
3928 (selected-window)
3929 (set-buffer (find-buffer-visiting todos-global-current-todos-file))))
3930 (t
3931 (when (not (derived-mode-p 'todos-mode)) (todos-show))))
3932 (let (buffer-read-only)
3933 (setq new-item
3934 ;; Add date, time and diary marking as required.
3935 (concat (if (not (and diary (not todos-include-in-diary)))
3936 todos-nondiary-start
3937 (when (and nonmarking (not todos-diary-nonmarking))
3938 diary-nonmarking-symbol))
3939 date-string (when (and time-string ; Can be empty string.
3940 (not (zerop (length time-string))))
3941 (concat " " time-string))
3942 (when (not (and diary (not todos-include-in-diary)))
3943 todos-nondiary-end)
3944 " " new-item))
3945 ;; Indent newlines inserted by C-q C-j if nonspace char follows.
3946 (setq new-item (replace-regexp-in-string
3947 "\\(\n\\)[^[:blank:]]"
3948 (concat "\n" (make-string todos-indent-to-here 32))
3949 new-item nil nil 1))
3950 (if here
3951 (cond ((not (eq major-mode 'todos-mode))
3952 (error "Cannot insert a todo item here outside of Todos mode"))
3953 ((not (eq buf (current-buffer)))
3954 (error "Cannot insert an item here after changing buffer"))
3955 ((or (todos-done-item-p)
3956 ;; Point on last blank line.
3957 (save-excursion (forward-line -1) (todos-done-item-p)))
3958 (error "Cannot insert a new item in the done item section"))
3959 (t
3960 (todos-insert-with-overlays new-item)))
3961 (todos-set-item-priority new-item (todos-current-category) t))
3962 (todos-update-count 'todo 1)
3963 (if (or diary todos-include-in-diary) (todos-update-count 'diary 1))
3964 (todos-update-categories-sexp)))))
3965
3966 (defvar todos-date-from-calendar nil
3967 "Helper variable for setting item date from the Emacs Calendar.")
3968
3969 (defun todos-set-date-from-calendar ()
3970 "Return string of date chosen from Calendar."
3971 (when todos-date-from-calendar
3972 (let (calendar-view-diary-initially-flag)
3973 (calendar))
3974 ;; *Calendar* is now current buffer.
3975 (local-set-key (kbd "RET") 'exit-recursive-edit)
3976 (message "Put cursor on a date and type <return> to set it.")
3977 ;; FIXME: is there a better way than recursive-edit? Use unwind-protect?
3978 ;; Check recursive-depth?
3979 (recursive-edit)
3980 (setq todos-date-from-calendar
3981 (calendar-date-string (calendar-cursor-to-date t) t t))
3982 (calendar-exit)
3983 todos-date-from-calendar))
3984
3985 (defun todos-delete-item ()
3986 "Delete at least one item in this category.
3987
3988 If there are marked items, delete all of these; otherwise, delete
3989 the item at point."
3990 (interactive)
3991 (let* ((cat (todos-current-category))
3992 (marked (assoc cat todos-categories-with-marks))
3993 (item (unless marked (todos-item-string)))
3994 (ov (make-overlay (save-excursion (todos-item-start))
3995 (save-excursion (todos-item-end))))
3996 ;; FIXME: make confirmation an option?
3997 (answer (if marked
3998 (y-or-n-p "Permanently delete all marked items? ")
3999 (when item
4000 (overlay-put ov 'face 'todos-search)
4001 (y-or-n-p (concat "Permanently delete this item? ")))))
4002 (opoint (point))
4003 buffer-read-only)
4004 (when answer
4005 (and marked (goto-char (point-min)))
4006 (catch 'done
4007 (while (not (eobp))
4008 (if (or (and marked (todos-marked-item-p)) item)
4009 (progn
4010 (if (todos-done-item-p)
4011 (todos-update-count 'done -1)
4012 (todos-update-count 'todo -1 cat)
4013 (and (todos-diary-item-p) (todos-update-count 'diary -1)))
4014 (delete-overlay ov)
4015 (todos-remove-item)
4016 ;; Don't leave point below last item.
4017 (and item (bolp) (eolp) (< (point-min) (point-max))
4018 (todos-backward-item))
4019 (when item
4020 (throw 'done (setq item nil))))
4021 (todos-forward-item))))
4022 (when marked
4023 (remove-overlays (point-min) (point-max) 'before-string todos-item-mark)
4024 (setq todos-categories-with-marks
4025 (assq-delete-all cat todos-categories-with-marks))
4026 (goto-char opoint))
4027 (todos-update-categories-sexp)
4028 (todos-prefix-overlays))
4029 (if ov (delete-overlay ov))))
4030
4031 (defun todos-edit-item ()
4032 "Edit the Todo item at point.
4033 If the item consists of only one logical line, edit it in the
4034 minibuffer; otherwise, edit it in Todos Edit mode."
4035 (interactive)
4036 (when (todos-item-string)
4037 (let* ((buffer-read-only)
4038 (start (todos-item-start))
4039 (item-beg (progn
4040 (re-search-forward
4041 (concat todos-date-string-start todos-date-pattern
4042 "\\( " diary-time-regexp "\\)?"
4043 (regexp-quote todos-nondiary-end) "?")
4044 (line-end-position) t)
4045 (1+ (- (point) start))))
4046 (item (todos-item-string))
4047 (multiline (> (length (split-string item "\n")) 1))
4048 (opoint (point)))
4049 (if multiline
4050 (todos-edit-multiline t)
4051 (let ((new (read-string "Edit: " (cons item item-beg))))
4052 (while (not (string-match
4053 (concat todos-date-string-start todos-date-pattern) new))
4054 (setq new (read-from-minibuffer
4055 "Item must start with a date: " new)))
4056 ;; Indent newlines inserted by C-q C-j if nonspace char follows.
4057 (setq new (replace-regexp-in-string
4058 "\\(\n\\)[^[:blank:]]"
4059 (concat "\n" (make-string todos-indent-to-here 32)) new
4060 nil nil 1))
4061 ;; If user moved point during editing, make sure it moves back.
4062 (goto-char opoint)
4063 (todos-remove-item)
4064 (todos-insert-with-overlays new)
4065 (move-to-column item-beg))))))
4066
4067 (defun todos-edit-multiline-item ()
4068 "Edit current Todo item in Todos Edit mode.
4069 Use of newlines invokes `todos-indent' to insure compliance with
4070 the format of Diary entries."
4071 (interactive)
4072 (todos-edit-multiline t))
4073
4074 (defun todos-edit-multiline (&optional item)
4075 ""
4076 (interactive)
4077 ;; FIXME: should there be only one live Todos Edit buffer?
4078 ;; (let ((buffer-name todos-edit-buffer))
4079 (let ((buffer-name (generate-new-buffer-name todos-edit-buffer)))
4080 (set-window-buffer
4081 (selected-window)
4082 (set-buffer (make-indirect-buffer
4083 (file-name-nondirectory todos-current-todos-file)
4084 buffer-name)))
4085 (if item
4086 (narrow-to-region (todos-item-start) (todos-item-end))
4087 (widen))
4088 (todos-edit-mode)
4089 (message "%s" (substitute-command-keys
4090 (concat "Type \\[todos-edit-quit] to check file format "
4091 "validity and return to Todos mode.\n")))))
4092
4093 (defun todos-edit-quit ()
4094 "Return from Todos Edit mode to Todos mode.
4095
4096 If the whole file was in Todos Edit mode, check before returning
4097 whether the file is still a valid Todos file and if so, also
4098 recalculate the Todos categories sexp, in case changes were made
4099 in the number or names of categories."
4100 (interactive)
4101 ;; FIXME: worth doing this only if file was actually changed?
4102 (when (eq (buffer-size) (- (point-max) (point-min)))
4103 (when (todos-check-format)
4104 (todos-make-categories-list t)))
4105 (kill-buffer)
4106 ;; In case next buffer is not the one holding todos-current-todos-file.
4107 (todos-show))
4108
4109 (defun todos-edit-item-header (&optional what)
4110 "Edit date/time header of at least one item.
4111
4112 Interactively, ask whether to edit year, month and day or day of
4113 the week, as well as time. If there are marked items, apply the
4114 changes to all of these; otherwise, edit just the item at point.
4115
4116 Non-interactively, argument WHAT specifies whether to set the
4117 date from the Calendar or to today, or whether to edit only the
4118 date or day, or only the time."
4119 (interactive)
4120 (let* ((cat (todos-current-category))
4121 (marked (assoc cat todos-categories-with-marks))
4122 (first t) ; Match only first of marked items.
4123 (todos-date-from-calendar t)
4124 ndate ntime nheader)
4125 (save-excursion
4126 (or (and marked (goto-char (point-min))) (todos-item-start))
4127 (catch 'stop
4128 (while (not (eobp))
4129 (and marked
4130 (while (not (todos-marked-item-p))
4131 (todos-forward-item)
4132 (and (eobp) (throw 'stop nil))))
4133 (re-search-forward (concat todos-date-string-start "\\(?1:"
4134 todos-date-pattern
4135 "\\)\\(?2: " diary-time-regexp "\\)?")
4136 (line-end-position) t)
4137 (let* ((odate (match-string-no-properties 1))
4138 (otime (match-string-no-properties 2))
4139 (buffer-read-only))
4140 (cond ((eq what 'today)
4141 (progn
4142 (setq ndate (calendar-date-string
4143 (calendar-current-date) t t))
4144 (replace-match ndate nil nil nil 1)))
4145 ((eq what 'calendar)
4146 (setq ndate (save-match-data (todos-set-date-from-calendar)))
4147 (replace-match ndate nil nil nil 1))
4148 (t
4149 (unless (eq what 'timeonly)
4150 (when first
4151 (setq ndate (if (save-match-data
4152 (string-match "[0-9]+" odate))
4153 (if (y-or-n-p "Change date? ")
4154 (todos-read-date)
4155 (todos-read-dayname))
4156 (if (y-or-n-p "Change day? ")
4157 (todos-read-dayname)
4158 (todos-read-date)))))
4159 (replace-match ndate nil nil nil 1))
4160 (unless (eq what 'dateonly)
4161 (when first
4162 (setq ntime (save-match-data (todos-read-time)))
4163 (when (< 0 (length ntime))
4164 (setq ntime (concat " " ntime))))
4165 (if otime
4166 (replace-match ntime nil nil nil 2)
4167 (goto-char (match-end 1))
4168 (insert ntime)))))
4169 (setq todos-date-from-calendar nil)
4170 (setq first nil))
4171 (if marked
4172 (todos-forward-item)
4173 (goto-char (point-max))))))))
4174
4175 (defun todos-edit-item-date ()
4176 "Prompt for and apply changes to current item's date."
4177 (interactive)
4178 (todos-edit-item-header 'dateonly))
4179
4180 (defun todos-edit-item-date-from-calendar ()
4181 "Prompt for changes to current item's date and apply from Calendar."
4182 (interactive)
4183 (todos-edit-item-header 'calendar))
4184
4185 (defun todos-edit-item-date-is-today ()
4186 "Set item date to today's date."
4187 (interactive)
4188 (todos-edit-item-header 'today))
4189
4190 (defun todos-edit-item-time ()
4191 "Prompt For and apply changes to current item's time."
4192 (interactive)
4193 (todos-edit-item-header 'timeonly))
4194
4195 (defun todos-edit-item-diary-inclusion ()
4196 "Change diary status of one or more todo items in this category.
4197 That is, insert `todos-nondiary-marker' if the candidate items
4198 lack this marking; otherwise, remove it.
4199
4200 If there are marked todo items, change the diary status of all
4201 and only these, otherwise change the diary status of the item at
4202 point."
4203 (interactive)
4204 (let ((buffer-read-only)
4205 (marked (assoc (todos-current-category)
4206 todos-categories-with-marks)))
4207 (catch 'stop
4208 (save-excursion
4209 (when marked (goto-char (point-min)))
4210 (while (not (eobp))
4211 (if (todos-done-item-p)
4212 (throw 'stop (message "Done items cannot be edited"))
4213 (unless (and marked (not (todos-marked-item-p)))
4214 (let* ((beg (todos-item-start))
4215 (lim (save-excursion (todos-item-end)))
4216 (end (save-excursion
4217 (or (todos-time-string-matcher lim)
4218 (todos-date-string-matcher lim)))))
4219 (if (looking-at (regexp-quote todos-nondiary-start))
4220 (progn
4221 (replace-match "")
4222 (search-forward todos-nondiary-end (1+ end) t)
4223 (replace-match "")
4224 (todos-update-count 'diary 1))
4225 (when end
4226 (insert todos-nondiary-start)
4227 (goto-char (1+ end))
4228 (insert todos-nondiary-end)
4229 (todos-update-count 'diary -1)))))
4230 (unless marked (throw 'stop nil))
4231 (todos-forward-item)))))
4232 (todos-update-categories-sexp)))
4233
4234 (defun todos-edit-category-diary-inclusion (arg)
4235 "Make all items in this category diary items.
4236 With prefix ARG, make all items in this category non-diary
4237 items."
4238 (interactive "P")
4239 (save-excursion
4240 (goto-char (point-min))
4241 (let ((todo-count (todos-get-count 'todo))
4242 (diary-count (todos-get-count 'diary))
4243 (buffer-read-only))
4244 (catch 'stop
4245 (while (not (eobp))
4246 (if (todos-done-item-p) ; We've gone too far.
4247 (throw 'stop nil)
4248 (let* ((beg (todos-item-start))
4249 (lim (save-excursion (todos-item-end)))
4250 (end (save-excursion
4251 (or (todos-time-string-matcher lim)
4252 (todos-date-string-matcher lim)))))
4253 (if arg
4254 (unless (looking-at (regexp-quote todos-nondiary-start))
4255 (insert todos-nondiary-start)
4256 (goto-char (1+ end))
4257 (insert todos-nondiary-end))
4258 (when (looking-at (regexp-quote todos-nondiary-start))
4259 (replace-match "")
4260 (search-forward todos-nondiary-end (1+ end) t)
4261 (replace-match "")))))
4262 (todos-forward-item))
4263 (unless (if arg (zerop diary-count) (= diary-count todo-count))
4264 (todos-update-count 'diary (if arg
4265 (- diary-count)
4266 (- todo-count diary-count))))
4267 (todos-update-categories-sexp)))))
4268
4269 (defun todos-edit-item-diary-nonmarking ()
4270 "Change non-marking of one or more diary items in this category.
4271 That is, insert `diary-nonmarking-symbol' if the candidate items
4272 lack this marking; otherwise, remove it.
4273
4274 If there are marked todo items, change the non-marking status of
4275 all and only these, otherwise change the non-marking status of
4276 the item at point."
4277 (interactive)
4278 (let ((buffer-read-only)
4279 (marked (assoc (todos-current-category)
4280 todos-categories-with-marks)))
4281 (catch 'stop
4282 (save-excursion
4283 (when marked (goto-char (point-min)))
4284 (while (not (eobp))
4285 (if (todos-done-item-p)
4286 (throw 'stop (message "Done items cannot be edited"))
4287 (unless (and marked (not (todos-marked-item-p)))
4288 (todos-item-start)
4289 (unless (looking-at (regexp-quote todos-nondiary-start))
4290 (if (looking-at (regexp-quote diary-nonmarking-symbol))
4291 (replace-match "")
4292 (insert diary-nonmarking-symbol))))
4293 (unless marked (throw 'stop nil))
4294 (todos-forward-item)))))))
4295
4296 (defun todos-edit-category-diary-nonmarking (arg)
4297 "Add `diary-nonmarking-symbol' to all diary items in this category.
4298 With prefix ARG, remove `diary-nonmarking-symbol' from all diary
4299 items in this category."
4300 (interactive "P")
4301 (save-excursion
4302 (goto-char (point-min))
4303 (let (buffer-read-only)
4304 (catch 'stop
4305 (while (not (eobp))
4306 (if (todos-done-item-p) ; We've gone too far.
4307 (throw 'stop nil)
4308 (unless (looking-at (regexp-quote todos-nondiary-start))
4309 (if arg
4310 (when (looking-at (regexp-quote diary-nonmarking-symbol))
4311 (replace-match ""))
4312 (unless (looking-at (regexp-quote diary-nonmarking-symbol))
4313 (insert diary-nonmarking-symbol))))
4314 (todos-forward-item)))))))
4315
4316 (defun todos-raise-item-priority (&optional lower)
4317 "Raise priority of current item by moving it up by one item.
4318 With non-nil argument LOWER lower item's priority."
4319 (interactive)
4320 (unless (or (todos-done-item-p) ; Can't reprioritize done items.
4321 ;; Can't raise or lower todo item when it's the only one.
4322 (< (todos-get-count 'todo) 2)
4323 ;; Point is between todo and done items.
4324 (looking-at "^$")
4325 ;; Can't lower final todo item.
4326 (and lower
4327 (save-excursion
4328 (todos-forward-item)
4329 (looking-at "^$")))
4330 ;; Can't reprioritize filtered items other than Top Priorities.
4331 (and (eq major-mode 'todos-filter-items-mode)
4332 (not (string-match (regexp-quote todos-top-priorities-buffer)
4333 (buffer-name)))))
4334 (let ((item (todos-item-string))
4335 (marked (todos-marked-item-p))
4336 buffer-read-only)
4337 ;; In Top Priorities buffer, an item's priority can be changed
4338 ;; wrt items in another category, but not wrt items in the same
4339 ;; category.
4340 (when (eq major-mode 'todos-filter-items-mode)
4341 (let* ((regexp (concat todos-date-string-start todos-date-pattern
4342 "\\( " diary-time-regexp "\\)?"
4343 (regexp-quote todos-nondiary-end)
4344 "?\\(?1: \\[\\(.+:\\)?.+\\]\\)"))
4345 (cat1 (save-excursion
4346 (re-search-forward regexp nil t)
4347 (match-string 1)))
4348 (cat2 (save-excursion
4349 (if lower
4350 (todos-forward-item)
4351 (todos-backward-item))
4352 (re-search-forward regexp nil t)
4353 (match-string 1))))
4354 (if (string= cat1 cat2)
4355 (error
4356 (concat "Cannot reprioritize items in the same "
4357 "category in this mode, only in Todos mode")))))
4358 (todos-remove-item)
4359 (if lower (todos-forward-item) (todos-backward-item))
4360 (todos-insert-with-overlays item)
4361 ;; If item was marked, retore the mark.
4362 (and marked (overlay-put (make-overlay (point) (point))
4363 'before-string todos-item-mark)))))
4364
4365 (defun todos-lower-item-priority ()
4366 "Lower priority of current item by moving it down by one item."
4367 (interactive)
4368 (todos-raise-item-priority t))
4369
4370 ;; FIXME: incorporate todos-(raise|lower)-item-priority ?
4371 (defun todos-set-item-priority (item cat &optional new)
4372 "Set todo ITEM's priority in category CAT, moving item as needed.
4373 Interactively, the item and the category are the current ones,
4374 and the priority is a number between 1 and the number of items in
4375 the category. Non-interactively with argument NEW, the lowest
4376 priority is one more than the number of items in CAT."
4377 (interactive (list (todos-item-string) (todos-current-category)))
4378 (unless (called-interactively-p t)
4379 (todos-category-number cat)
4380 (todos-category-select))
4381 (let* ((todo (todos-get-count 'todo cat))
4382 (maxnum (if new (1+ todo) todo))
4383 (buffer-read-only)
4384 priority candidate prompt)
4385 (unless (zerop todo)
4386 (while (not priority)
4387 (setq candidate
4388 (string-to-number (read-from-minibuffer
4389 (concat prompt
4390 (format "Set item priority (1-%d): "
4391 maxnum)))))
4392 (setq prompt
4393 (when (or (< candidate 1) (> candidate maxnum))
4394 (format "Priority must be an integer between 1 and %d.\n"
4395 maxnum)))
4396 (unless prompt (setq priority candidate)))
4397 ;; Interactively, just relocate the item within its category.
4398 (when (called-interactively-p) (todos-remove-item))
4399 (goto-char (point-min))
4400 (unless (= priority 1) (todos-forward-item (1- priority))))
4401 (todos-insert-with-overlays item)))
4402
4403 (defun todos-set-item-top-priority ()
4404 "Set this item's priority in the Top Priorities display.
4405 Reprioritizing items that belong to the same category is not
4406 allowed; this is reserved for Todos mode."
4407 (interactive)
4408 (when (string-match (regexp-quote todos-top-priorities-buffer) (buffer-name))
4409 (let* ((count 0)
4410 (item (todos-item-string))
4411 (end (todos-item-end))
4412 (beg (todos-item-start))
4413 (regexp (concat todos-date-string-start todos-date-pattern
4414 "\\(?: " diary-time-regexp "\\)?"
4415 (regexp-quote todos-nondiary-end)
4416 "?\\(?1: \\[\\(?:.+:\\)?.+\\]\\)"))
4417 (cat (when (looking-at regexp) (match-string 1)))
4418 buffer-read-only current priority candidate prompt new)
4419 (save-excursion
4420 (goto-char (point-min))
4421 (while (not (eobp))
4422 (setq count (1+ count))
4423 (when (string= item (todos-item-string))
4424 (setq current count))
4425 (todos-forward-item)))
4426 (unless (zerop count)
4427 (while (not priority)
4428 (setq candidate
4429 (string-to-number (read-from-minibuffer
4430 (concat prompt
4431 (format "Set item priority (1-%d): "
4432 count)))))
4433 (setq prompt
4434 (when (or (< candidate 1) (> candidate count))
4435 (format "Priority must be an integer between 1 and %d.\n"
4436 count)))
4437 (unless prompt (setq priority candidate)))
4438 (goto-char (point-min))
4439 (unless (= priority 1) (todos-forward-item (1- priority)))
4440 (setq new (point-marker))
4441 (if (or (and (< priority current)
4442 (todos-item-end)
4443 (save-excursion (search-forward cat beg t)))
4444 (and (> priority current)
4445 (save-excursion (search-backward cat end t))))
4446 (progn
4447 (set-marker new nil)
4448 (goto-char beg)
4449 (error (concat "Cannot reprioritize items in the same category "
4450 "in this mode, only in Todos mode")))
4451 (goto-char beg)
4452 (todos-remove-item)
4453 (goto-char new)
4454 (todos-insert-with-overlays item)
4455 (set-marker new nil))))))
4456
4457 (defun todos-move-item (&optional file)
4458 "Move at least one todo item to another category.
4459
4460 If there are marked items, move all of these; otherwise, move
4461 the item at point.
4462
4463 With non-nil argument FILE, first prompt for another Todos file and
4464 then a category in that file to move the item or items to.
4465
4466 If the chosen category is not one of the existing categories,
4467 then it is created and the item(s) become(s) the first
4468 entry/entries in that category."
4469 (interactive)
4470 (unless (or (todos-done-item-p)
4471 ;; Point is between todo and done items.
4472 (looking-at "^$"))
4473 (let* ((buffer-read-only)
4474 (file1 todos-current-todos-file)
4475 (cat1 (todos-current-category))
4476 (marked (assoc cat1 todos-categories-with-marks))
4477 (num todos-category-number)
4478 (item (todos-item-string))
4479 (diary-item (todos-diary-item-p))
4480 (omark (save-excursion (todos-item-start) (point-marker)))
4481 (file2 (if file
4482 (todos-read-file-name "Choose a Todos file: " nil t)
4483 file1))
4484 (count 0)
4485 (count-diary 0)
4486 cat2 nmark)
4487 (set-buffer (find-file-noselect file2))
4488 (setq cat2 (let* ((pl (if (and marked (> (cdr marked) 1)) "s" ""))
4489 (name (todos-read-category
4490 (concat "Move item" pl " to category: ")))
4491 (prompt (concat "Choose a different category than "
4492 "the current one\n(type `"
4493 (key-description
4494 (car (where-is-internal
4495 'todos-set-item-priority)))
4496 "' to reprioritize item "
4497 "within the same category): ")))
4498 (while (equal name cat1)
4499 (setq name (todos-read-category prompt)))
4500 name))
4501 (set-buffer (find-buffer-visiting file1))
4502 (if marked
4503 (progn
4504 (setq item nil)
4505 (goto-char (point-min))
4506 (while (not (eobp))
4507 (when (todos-marked-item-p)
4508 (setq item (concat item (todos-item-string) "\n"))
4509 (setq count (1+ count))
4510 (when (todos-diary-item-p)
4511 (setq count-diary (1+ count-diary))))
4512 (todos-forward-item))
4513 ;; Chop off last newline.
4514 (setq item (substring item 0 -1)))
4515 (setq count 1)
4516 (when (todos-diary-item-p) (setq count-diary 1)))
4517 (set-window-buffer (selected-window)
4518 (set-buffer (find-file-noselect file2)))
4519 (unless (assoc cat2 todos-categories) (todos-add-category cat2))
4520 (todos-set-item-priority item cat2 t)
4521 (setq nmark (point-marker))
4522 (todos-update-count 'todo count)
4523 (todos-update-count 'diary count-diary)
4524 (todos-update-categories-sexp)
4525 (with-current-buffer (find-buffer-visiting file1)
4526 (save-excursion
4527 (save-restriction
4528 (widen)
4529 (goto-char omark)
4530 (if marked
4531 (let (beg end)
4532 (setq item nil)
4533 (re-search-backward
4534 (concat "^" (regexp-quote todos-category-beg)) nil t)
4535 (forward-line)
4536 (setq beg (point))
4537 (re-search-forward
4538 (concat "^" (regexp-quote todos-category-done)) nil t)
4539 (setq end (match-beginning 0))
4540 (goto-char beg)
4541 (while (< (point) end)
4542 (if (todos-marked-item-p)
4543 (todos-remove-item)
4544 (todos-forward-item))))
4545 (todos-remove-item))))
4546 (todos-update-count 'todo (- count) cat1)
4547 (todos-update-count 'diary (- count-diary) cat1)
4548 (todos-update-categories-sexp))
4549 (set-window-buffer (selected-window)
4550 (set-buffer (find-file-noselect file2)))
4551 (setq todos-category-number (todos-category-number cat2))
4552 (todos-category-select)
4553 (goto-char nmark))))
4554
4555 (defun todos-move-item-to-file ()
4556 "Move the current todo item to a category in another Todos file."
4557 (interactive)
4558 (todos-move-item t))
4559
4560 (defun todos-move-item-to-diary ()
4561 "Move one or more items in current category to the diary file.
4562
4563 If there are marked items, move all of these; otherwise, move
4564 the item at point."
4565 (interactive)
4566 ;; FIXME
4567 )
4568
4569 ;; FIXME: make adding date customizable, and make this and time customization
4570 ;; overridable via double prefix arg ??
4571 (defun todos-item-done (&optional arg)
4572 "Tag at least one item in this category as done and hide it.
4573
4574 With prefix argument ARG prompt for a comment and append it to
4575 the done item; this is only possible if there are no marked
4576 items. If there are marked items, tag all of these with
4577 `todos-done-string' plus the current date and, if
4578 `todos-always-add-time-string' is non-nil, the current time;
4579 otherwise, just tag the item at point. Items tagged as done are
4580 relocated to the category's (by default hidden) done section."
4581 (interactive "P")
4582 (let* ((cat (todos-current-category))
4583 (marked (assoc cat todos-categories-with-marks)))
4584 (unless (or (todos-done-item-p)
4585 (and (looking-at "^$") (not marked)))
4586 (let* ((date-string (calendar-date-string (calendar-current-date) t t))
4587 (time-string (if todos-always-add-time-string
4588 (concat " " (substring (current-time-string) 11 16))
4589 ""))
4590 (done-prefix (concat "[" todos-done-string date-string time-string
4591 "] "))
4592 (comment (and arg (not marked) (read-string "Enter a comment: ")))
4593 (item-count 0)
4594 (diary-count 0)
4595 item done-item
4596 (buffer-read-only))
4597 (and marked (goto-char (point-min)))
4598 (catch 'done
4599 (while (not (eobp))
4600 (if (or (not marked) (and marked (todos-marked-item-p)))
4601 (progn
4602 (setq item (todos-item-string))
4603 (setq done-item (cond (marked
4604 (concat done-item done-prefix item "\n"))
4605 (comment
4606 (concat done-prefix item " ["
4607 todos-comment-string
4608 ": " comment "]"))
4609 (t
4610 (concat done-prefix item))))
4611 (setq item-count (1+ item-count))
4612 (when (todos-diary-item-p)
4613 (setq diary-count (1+ diary-count)))
4614 (todos-remove-item)
4615 (unless marked (throw 'done nil)))
4616 (todos-forward-item))))
4617 (when marked
4618 ;; Chop off last newline of done item string.
4619 (setq done-item (substring done-item 0 -1))
4620 (remove-overlays (point-min) (point-max) 'before-string todos-item-mark)
4621 (setq todos-categories-with-marks
4622 (assq-delete-all cat todos-categories-with-marks)))
4623 (save-excursion
4624 (widen)
4625 (re-search-forward
4626 (concat "^" (regexp-quote todos-category-done)) nil t)
4627 (forward-char)
4628 (insert done-item "\n"))
4629 (todos-update-count 'todo (- item-count))
4630 (todos-update-count 'done item-count)
4631 (todos-update-count 'diary (- diary-count))
4632 (todos-update-categories-sexp)
4633 (save-excursion (todos-category-select))))))
4634
4635 (defun todos-done-item-add-or-edit-comment ()
4636 "Add a comment to this done item or edit an existing comment."
4637 (interactive)
4638 (when (todos-done-item-p)
4639 (let ((item (todos-item-string))
4640 (end (save-excursion (todos-item-end)))
4641 comment buffer-read-only)
4642 (save-excursion
4643 (todos-item-start)
4644 (if (re-search-forward (concat " \\["
4645 (regexp-quote todos-comment-string)
4646 ": \\([^]]+\\)\\]") end t)
4647 (progn
4648 (setq comment (read-string "Edit comment: "
4649 (cons (match-string 1) 1)))
4650 (replace-match comment nil nil nil 1))
4651 (setq comment (read-string "Enter a comment: "))
4652 (todos-item-end)
4653 (insert " [" todos-comment-string ": " comment "]"))))))
4654
4655 ;; FIXME: implement this or done item editing?
4656 (defun todos-uncomment-done-item ()
4657 ""
4658 )
4659
4660 ;; FIXME: delete comment from restored item or just leave it up to user?
4661 (defun todos-item-undo ()
4662 "Restore this done item to the todo section of this category."
4663 (interactive)
4664 (when (todos-done-item-p)
4665 (let* ((buffer-read-only)
4666 (done-item (todos-item-string))
4667 (opoint (point))
4668 (orig-mrk (progn (todos-item-start) (point-marker)))
4669 ;; Find the end of the date string added upon making item done.
4670 (start (search-forward "] "))
4671 (item (buffer-substring start (todos-item-end)))
4672 undone)
4673 (todos-remove-item)
4674 ;; If user cancels before setting new priority, then restore everything.
4675 (unwind-protect
4676 (progn
4677 (todos-set-item-priority item (todos-current-category) t)
4678 (setq undone t)
4679 (todos-update-count 'todo 1)
4680 (todos-update-count 'done -1)
4681 (and (todos-diary-item-p) (todos-update-count 'diary 1))
4682 (todos-update-categories-sexp))
4683 (unless undone
4684 (widen)
4685 (goto-char orig-mrk)
4686 (todos-insert-with-overlays done-item)
4687 (let ((todos-show-with-done t))
4688 (todos-category-select)
4689 (goto-char opoint)))
4690 (set-marker orig-mrk nil)))))
4691
4692 (defun todos-archive-done-item (&optional all)
4693 "Archive at least one done item in this category.
4694
4695 If there are marked done items (and no marked todo items),
4696 archive all of these; otherwise, with non-nil argument ALL,
4697 archive all done items in this category; otherwise, archive the
4698 done item at point.
4699
4700 If the archive of this file does not exist, it is created. If
4701 this category does not exist in the archive, it is created."
4702 (interactive)
4703 (when (eq major-mode 'todos-mode)
4704 (if (and all (zerop (todos-get-count 'done)))
4705 (message "No done items in this category")
4706 (catch 'end
4707 (let* ((cat (todos-current-category))
4708 (tbuf (current-buffer))
4709 (marked (assoc cat todos-categories-with-marks))
4710 (afile (concat (file-name-sans-extension
4711 todos-current-todos-file) ".toda"))
4712 (archive (if (file-exists-p afile)
4713 (find-file-noselect afile t)
4714 (get-buffer-create afile)))
4715 (item (and (todos-done-item-p) (concat (todos-item-string) "\n")))
4716 (count 0)
4717 marked-items beg end all-done
4718 buffer-read-only)
4719 (cond
4720 (marked
4721 (save-excursion
4722 (goto-char (point-min))
4723 (while (not (eobp))
4724 (when (todos-marked-item-p)
4725 (if (not (todos-done-item-p))
4726 (throw 'end (message "Only done items can be archived"))
4727 (setq marked-items
4728 (concat marked-items (todos-item-string) "\n"))
4729 (setq count (1+ count))))
4730 (todos-forward-item))))
4731 (all
4732 (if (y-or-n-p "Archive all done items in this category? ")
4733 (save-excursion
4734 (save-restriction
4735 (goto-char (point-min))
4736 (widen)
4737 (setq beg (progn
4738 (re-search-forward todos-done-string-start nil t)
4739 (match-beginning 0))
4740 end (if (re-search-forward
4741 (concat "^" (regexp-quote todos-category-beg))
4742 nil t)
4743 (match-beginning 0)
4744 (point-max))
4745 all-done (buffer-substring beg end)
4746 count (todos-get-count 'done))))
4747 (throw 'end nil))))
4748 (when (or marked all item)
4749 (with-current-buffer archive
4750 (unless buffer-file-name (erase-buffer))
4751 (let (buffer-read-only)
4752 (widen)
4753 (goto-char (point-min))
4754 (if (and (re-search-forward (concat "^"
4755 (regexp-quote
4756 (concat todos-category-beg
4757 cat)))
4758 nil t)
4759 (re-search-forward (regexp-quote todos-category-done)
4760 nil t))
4761 (forward-char) ; Start of done items section.
4762 (todos-add-category cat)
4763 (goto-char (point-max))) ; Start of done items section.
4764 (insert (cond (marked marked-items)
4765 (all all-done)
4766 (item)))
4767 (todos-update-count 'done (if (or marked all) count 1) cat)
4768 (todos-update-categories-sexp)
4769 ;; If archive is new, save to file now (using write-region in
4770 ;; order not to get prompted for file to save to), to let
4771 ;; auto-mode-alist take effect below.
4772 (unless buffer-file-name
4773 (write-region nil nil afile)
4774 (kill-buffer))))
4775 (with-current-buffer tbuf
4776 (cond ((or marked item)
4777 (and marked (goto-char (point-min)))
4778 (catch 'done
4779 (while (not (eobp))
4780 (if (or (and marked (todos-marked-item-p)) item)
4781 (progn
4782 (todos-remove-item)
4783 (todos-update-count 'done -1)
4784 (todos-update-count 'archived 1)
4785 ;; Don't leave point below last item.
4786 (and item (bolp) (eolp) (< (point-min) (point-max))
4787 (todos-backward-item))
4788 (when item
4789 (throw 'done (setq item nil))))
4790 (todos-forward-item)))))
4791 (all
4792 (remove-overlays beg end)
4793 (delete-region beg end)
4794 (todos-update-count 'done (- count))
4795 (todos-update-count 'archived count)))
4796 (when marked
4797 (remove-overlays (point-min) (point-max)
4798 'before-string todos-item-mark)
4799 (setq todos-categories-with-marks
4800 (assq-delete-all cat todos-categories-with-marks)))
4801 (todos-update-categories-sexp)
4802 (todos-prefix-overlays)))
4803 (find-file afile)
4804 (todos-category-number cat)
4805 (todos-category-select)
4806 (split-window-below)
4807 (set-window-buffer (selected-window) tbuf))))))
4808
4809 (defun todos-archive-category-done-items ()
4810 "Move all done items in this category to its archive."
4811 (interactive)
4812 (todos-archive-done-item t))
4813
4814 (defun todos-unarchive-items (&optional all)
4815 "Unarchive at least one item in this archive category.
4816
4817 If there are marked items, unarchive all of these; otherwise,
4818 with non-nil argument ALL, unarchive all items in this category;
4819 otherwise, unarchive the item at point.
4820
4821 Unarchived items are restored as done items to the corresponding
4822 category in the Todos file, inserted at the end of done section.
4823 If all items in the archive category were restored, the category
4824 is deleted from the archive. If this was the only category in the
4825 archive, the archive file is deleted."
4826 (interactive)
4827 (when (eq major-mode 'todos-archive-mode)
4828 (catch 'end
4829 (let* ((cat (todos-current-category))
4830 (tbuf (find-file-noselect
4831 (concat (file-name-sans-extension todos-current-todos-file)
4832 ".todo") t))
4833 (marked (assoc cat todos-categories-with-marks))
4834 (item (concat (todos-item-string) "\n"))
4835 (all-items (when all (buffer-substring (point-min) (point-max))))
4836 (all-count (when all (todos-get-count 'done)))
4837 marked-items marked-count
4838 buffer-read-only)
4839 (when marked
4840 (save-excursion
4841 (goto-char (point-min))
4842 (while (not (eobp))
4843 (when (todos-marked-item-p)
4844 (concat marked-items (todos-item-string) "\n")
4845 (setq marked-count (1+ marked-count)))
4846 (todos-forward-item))))
4847 ;; Restore items to end of category's done section and update counts.
4848 (with-current-buffer tbuf
4849 (let (buffer-read-only)
4850 (widen)
4851 (goto-char (point-min))
4852 (re-search-forward (concat "^" (regexp-quote
4853 (concat todos-category-beg cat)))
4854 nil t)
4855 ;; Go to end of category's done section.
4856 (if (re-search-forward (concat "^" (regexp-quote todos-category-beg))
4857 nil t)
4858 (goto-char (match-beginning 0))
4859 (goto-char (point-max)))
4860 (cond (marked
4861 (insert marked-items)
4862 (todos-update-count 'done marked-count cat)
4863 (todos-update-count 'archived (- marked-count) cat))
4864 (all
4865 (insert all-items)
4866 (todos-update-count 'done all-count cat)
4867 (todos-update-count 'archived (- all-count) cat))
4868 (t
4869 (insert item)
4870 (todos-update-count 'done 1 cat)
4871 (todos-update-count 'archived -1 cat)))
4872 (todos-update-categories-sexp)))
4873 ;; Delete restored items from archive.
4874 (cond ((or marked item)
4875 (and marked (goto-char (point-min)))
4876 (catch 'done
4877 (while (not (eobp))
4878 (if (or (and marked (todos-marked-item-p)) item)
4879 (progn
4880 (todos-remove-item)
4881 ;; Don't leave point below last item.
4882 (and item (bolp) (eolp) (< (point-min) (point-max))
4883 (todos-backward-item))
4884 (when item
4885 (throw 'done (setq item nil))))
4886 (todos-forward-item))))
4887 (todos-update-count 'done (if marked (- marked-count) -1) cat))
4888 (all
4889 (remove-overlays (point-min) (point-max))
4890 (delete-region (point-min) (point-max))))
4891 ;; If that was the last category in the archive, delete the whole file.
4892 (if (= (length todos-categories) 1)
4893 (progn
4894 (delete-file todos-current-todos-file)
4895 ;; Don't bother confirming killing the archive buffer.
4896 (set-buffer-modified-p nil)
4897 (kill-buffer))
4898 ;; Otherwise, if the archive category is now empty, delete it.
4899 (when (eq (point-min) (point-max))
4900 (widen)
4901 (let ((beg (re-search-backward
4902 (concat "^" (regexp-quote todos-category-beg) cat)
4903 nil t))
4904 (end (if (re-search-forward
4905 (concat "^" (regexp-quote todos-category-beg))
4906 nil t 2)
4907 (match-beginning 0)
4908 (point-max))))
4909 (remove-overlays beg end)
4910 (delete-region beg end)
4911 (setq todos-categories (delete (assoc cat todos-categories)
4912 todos-categories))
4913 (todos-update-categories-sexp))))
4914 ;; Visit category in Todos file and show restored done items.
4915 (let ((tfile (buffer-file-name tbuf))
4916 (todos-show-with-done t))
4917 (set-window-buffer (selected-window)
4918 (set-buffer (find-file-noselect tfile)))
4919 (todos-category-number cat)
4920 (todos-show)
4921 (message "Items unarchived."))))))
4922
4923 (defun todos-unarchive-category ()
4924 "Unarchive all items in this category. See `todos-unarchive-items'."
4925 (interactive)
4926 (todos-unarchive-items t))
4927
4928 (provide 'todos)
4929
4930 ;;; todos.el ends here
4931
4932 ;; ---------------------------------------------------------------------------
4933
4934 ;; FIXME: remove when part of Emacs
4935 (add-to-list 'auto-mode-alist '("\\.todo\\'" . todos-mode))
4936 (add-to-list 'auto-mode-alist '("\\.toda\\'" . todos-archive-mode))
4937
4938 ;;; Addition to calendar.el
4939 ;; FIXME: autoload when key-binding is defined in calendar.el
4940 (defun todos-insert-item-from-calendar ()
4941 ""
4942 (interactive)
4943 ;; FIXME: todos-current-todos-file is nil here, better to solicit Todos
4944 ;; file? todos-global-current-todos-file is nil if no Todos file has been
4945 ;; visited
4946 (pop-to-buffer (file-name-nondirectory todos-global-current-todos-file))
4947 (todos-show)
4948 ;; FIXME: this now calls todos-set-date-from-calendar
4949 (todos-insert-item t 'calendar))
4950
4951 ;; FIXME: calendar is loaded before todos
4952 ;; (add-hook 'calendar-load-hook
4953 ;; (lambda ()
4954 (define-key calendar-mode-map "it" 'todos-insert-item-from-calendar);))
4955
4956 ;; ---------------------------------------------------------------------------
4957 ;;; necessitated adaptations to diary-lib.el
4958
4959 ;; (defun diary-goto-entry (button)
4960 ;; "Jump to the diary entry for the BUTTON at point."
4961 ;; (let* ((locator (button-get button 'locator))
4962 ;; (marker (car locator))
4963 ;; markbuf file opoint)
4964 ;; ;; If marker pointing to diary location is valid, use that.
4965 ;; (if (and marker (setq markbuf (marker-buffer marker)))
4966 ;; (progn
4967 ;; (pop-to-buffer markbuf)
4968 ;; (goto-char (marker-position marker)))
4969 ;; ;; Marker is invalid (eg buffer has been killed, as is the case with
4970 ;; ;; included diary files).
4971 ;; (or (and (setq file (cadr locator))
4972 ;; (file-exists-p file)
4973 ;; (find-file-other-window file)
4974 ;; (progn
4975 ;; (when (eq major-mode (default-value 'major-mode)) (diary-mode))
4976 ;; (when (eq major-mode 'todos-mode) (widen))
4977 ;; (goto-char (point-min))
4978 ;; (when (re-search-forward (format "%s.*\\(%s\\)"
4979 ;; (regexp-quote (nth 2 locator))
4980 ;; (regexp-quote (nth 3 locator)))
4981 ;; nil t)
4982 ;; (goto-char (match-beginning 1))
4983 ;; (when (eq major-mode 'todos-mode)
4984 ;; (setq opoint (point))
4985 ;; (re-search-backward (concat "^"
4986 ;; (regexp-quote todos-category-beg)
4987 ;; "\\(.*\\)\n")
4988 ;; nil t)
4989 ;; (todos-category-number (match-string 1))
4990 ;; (todos-category-select)
4991 ;; (goto-char opoint)))))
4992 ;; (message "Unable to locate this diary entry")))))