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