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