* calendar/todos.el: Improve item marking and handling of marked items.
[bpt/emacs.git] / lisp / calendar / todos.el
CommitLineData
58c7641d 1;;; Todos.el --- facilities for making and maintaining Todo lists
3f031767 2
0e89c3fc 3;; Copyright (C) 1997, 1999, 2001-2012 Free Software Foundation, Inc.
3f031767
SB
4
5;; Author: Oliver Seidel <privat@os10000.net>
58c7641d 6;; Stephen Berman <stephen.berman@gmx.net>
3f031767
SB
7;; Maintainer: Stephen Berman <stephen.berman@gmx.net>
8;; Created: 2 Aug 1997
9;; Keywords: calendar, todo
10
0e89c3fc 11;; This file is [not yet] part of GNU Emacs.
3f031767
SB
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
3f031767
SB
26;;; Commentary:
27
3f031767
SB
28;;; Code:
29
b28025ed 30(require 'diary-lib)
6be04162 31;; For remove-duplicates in todos-insertion-commands-args.
0e89c3fc 32(eval-when-compile (require 'cl))
3f031767 33
2c173503 34;; ---------------------------------------------------------------------------
58c7641d 35;;; User options
ee7412e4 36
3f031767 37(defgroup todos nil
58c7641d 38 "Create and maintain categorized lists of todo items."
3f031767 39 :link '(emacs-commentary-link "todos")
0e89c3fc 40 :version "24.2"
3f031767
SB
41 :group 'calendar)
42
20166aea 43;; FIXME: use file-truename (but in a defcustom) ?
0e89c3fc
SB
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'.
51This returns the case-insensitive alphabetically sorted list of
52file truenames in `todos-files-directory' with the extension
53\".todo\". With non-nil ARCHIVES return the list of archive file
54truenames (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'.
65This function should take an optional argument that, if non-nil,
66makes 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.
72This lacks the extension and directory components."
73 (file-name-sans-extension (file-name-nondirectory file)))
74
a2730169
SB
75(defcustom todos-default-todos-file (todos-short-file-name
76 (car (funcall todos-files-function)))
0e89c3fc
SB
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'.
86Called 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.
96Otherwise, `todos-show' always visits `todos-default-todos-file'."
97 :type 'boolean
98 :initialize 'custom-initialize-default
3af3cd0b 99 :set 'todos-set-show-current-file
0e89c3fc
SB
100 :group 'todos)
101
3af3cd0b 102(defun todos-set-show-current-file (symbol value)
0e89c3fc
SB
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
a2730169
SB
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'.
119Called 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
0e89c3fc 127(defcustom todos-visit-files-commands (list 'find-file 'dired-find-file)
6be04162 128 "List of file finding commands for `todos-display-as-todos-file'.
0e89c3fc
SB
129Invoking these commands to visit a Todos or Todos Archive file
130calls `todos-show' or `todos-show-archive', so that the file is
131displayed 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
d04d6b95
SB
140(defcustom todos-initial-category "Todo"
141 "Default category name offered on initializing a new Todos file."
142 :type 'string
143 :group 'todos)
144
c523b0aa
SB
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))
d04d6b95
SB
150 :group 'todos)
151
18aef8a3
SB
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
1a9cb339
SB
157(defcustom todos-undo-item-omit-comment 'ask
158 "Whether to omit done item comment on undoing the item.
159Nil means never omit the comment, t means always omit it, `ask'
160means 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
18aef8a3
SB
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.
175In order for `todos-convert-legacy-files' to correctly convert this
176string to the current Todos format, the regexp must contain four
177explicitly numbered groups (see `(elisp) Regexp Backslash'),
178where group 1 matches a string for the year, group 2 a string for
179the month, group 3 a string for the day and group 4 a string for
180the time. The default value converts date-time strings built
181using the default value of `todo-time-string-format' from
182todo-mode.el."
183 :type 'regexp
184 :group 'todos)
185
36341a66
SB
186;; ---------------------------------------------------------------------------
187;;; Todos mode display options
188
18aef8a3
SB
189(defgroup todos-mode-display nil
190 "User display options for Todos mode."
191 :version "24.2"
192 :group 'todos)
193
d04d6b95 194(defcustom todos-prefix ""
b28025ed 195 "String prefixed to todo items for visual distinction."
1fcf038b
SB
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)))
b28025ed
SB
203 :initialize 'custom-initialize-default
204 :set 'todos-reset-prefix
18aef8a3 205 :group 'todos-mode-display)
2c173503 206
3af3cd0b 207(defcustom todos-number-priorities t
58c7641d 208 "Non-nil to prefix items with consecutively increasing integers.
d04d6b95 209These reflect the priorities of the items in each category."
2c173503
SB
210 :type 'boolean
211 :initialize 'custom-initialize-default
212 :set 'todos-reset-prefix
18aef8a3 213 :group 'todos-mode-display)
2c173503 214
0e89c3fc 215(defun todos-reset-prefix (symbol value)
3af3cd0b 216 "The :set function for `todos-prefix' and `todos-number-priorities'."
0e89c3fc
SB
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
1fcf038b
SB
234(defcustom todos-item-mark "*"
235 "String used to mark items.
236To ensure item marking works, change the value of this option
237only 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
144faf47
SB
249(defcustom todos-done-separator-string "_"
250 "String for generating `todos-done-separator'.
251
252If the string consists of a single character,
253`todos-done-separator' will be the string made by repeating this
254character for the width of the window, and the length is
255automatically recalculated when the window width changes. If the
256string consists of more (or less) than one character, it will be
257the value of `todos-done-separator'."
2c173503
SB
258 :type 'string
259 :initialize 'custom-initialize-default
144faf47 260 :set 'todos-reset-done-separator-string
18aef8a3 261 :group 'todos-mode-display)
2c173503 262
144faf47
SB
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))
d9be0d35
SB
270 (when (= 1 (length value))
271 (todos-reset-done-separator sep))))
0e89c3fc 272
2c173503
SB
273(defcustom todos-done-string "DONE "
274 "Identifying string appended to the front of done todos items."
275 :type 'string
58c7641d
SB
276 :initialize 'custom-initialize-default
277 :set 'todos-reset-done-string
18aef8a3 278 :group 'todos-mode-display)
58c7641d 279
0e89c3fc
SB
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
58c7641d
SB
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
18aef8a3 308 :group 'todos-mode-display)
2c173503 309
0e89c3fc
SB
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
2c173503
SB
331(defcustom todos-show-with-done nil
332 "Non-nil to display done items in all categories."
333 :type 'boolean
18aef8a3 334 :group 'todos-mode-display)
2c173503 335
58c7641d
SB
336(defun todos-mode-line-control (cat)
337 "Return a mode line control for Todos buffers.
338Argument CAT is the name of the current Todos category.
339This function is the value of the user variable
340`todos-mode-line-function'."
0e89c3fc
SB
341 (let ((file (todos-short-file-name todos-current-todos-file)))
342 (format "%s category %d: %s" file todos-category-number cat)))
58c7641d
SB
343
344(defcustom todos-mode-line-function 'todos-mode-line-control
345 "Function that returns a mode line control for Todos buffers.
0e89c3fc
SB
346The function expects one argument holding the name of the current
347Todos category. The resulting control becomes the local value of
348`mode-line-buffer-identification' in each Todos buffer."
d04d6b95 349 :type 'function
18aef8a3 350 :group 'todos-mode-display)
2c173503 351
6be04162 352(defcustom todos-skip-archived-categories nil
7464f422
SB
353 "Non-nil to skip categories with only archived items when browsing.
354
6be04162
SB
355Moving by category todos or archive file (with
356\\[todos-forward-category] and \\[todos-backward-category]) skips
357categories that contain only archived items. Other commands
358still recognize these categories. In Todos Categories
359mode (reached with \\[todos-display-categories]) these categories
360shown in `todos-archived-only' face and clicking them in Todos
361Categories mode visits the archived categories."
2c173503 362 :type 'boolean
18aef8a3 363 :group 'todos-mode-display)
2c173503 364
18aef8a3
SB
365(defcustom todos-highlight-item nil
366 "Non-nil means highlight items at point."
58c7641d 367 :type 'boolean
18aef8a3
SB
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.
399The 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
36341a66
SB
422;; ---------------------------------------------------------------------------
423;;; Item insertion options
424
18aef8a3
SB
425(defgroup todos-item-insertion nil
426 "User options for adding new todo items."
427 :version "24.2"
d04d6b95
SB
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
18aef8a3 433 :group 'todos-item-insertion)
d04d6b95 434
58c7641d
SB
435(defcustom todos-diary-nonmarking nil
436 "Non-nil to insert new Todo diary items as nonmarking by default.
437This appends `diary-nonmarking-symbol' to the front of an item on
438insertion provided it doesn't begin with `todos-nondiary-marker'."
439 :type 'boolean
18aef8a3 440 :group 'todos-item-insertion)
58c7641d 441
d04d6b95
SB
442(defcustom todos-nondiary-marker '("[" "]")
443 "List of strings surrounding item date to block diary inclusion.
444The first string is inserted before the item date and must be a
445non-empty string that does not match a diary date in order to
446have its intended effect. The second string is inserted after
447the diary date."
448 :type '(list string string)
18aef8a3 449 :group 'todos-item-insertion
d04d6b95
SB
450 :initialize 'custom-initialize-default
451 :set 'todos-reset-nondiary-marker)
2c173503 452
0e89c3fc
SB
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
6be04162
SB
485(defcustom todos-always-add-time-string nil
486 "Non-nil adds current time to a new item's date header by default.
487When the Todos insertion commands have a non-nil \"maybe-notime\"
488argument, this reverses the effect of
489`todos-always-add-time-string': if t, these commands omit the
490current time, if nil, they include it."
491 :type 'boolean
18aef8a3 492 :group 'todos-item-insertion)
2c173503 493
18aef8a3
SB
494(defcustom todos-use-only-highlighted-region t
495 "Non-nil to enable inserting only highlighted region as new item."
db2c5d34 496 :type 'boolean
18aef8a3 497 :group 'todos-item-insertion)
6be04162 498
36341a66
SB
499;; ---------------------------------------------------------------------------
500;;; Todos Filter Items mode options
501
6be04162
SB
502(defgroup todos-filtered nil
503 "User options for Todos Filter Items mode."
504 :version "24.2"
505 :group 'todos)
506
b28872ce 507(defcustom todos-filtered-items-buffer "Todos filtered items"
6be04162
SB
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"
b28872ce 513 "Buffer type string for `todos-filtered-buffer-name'."
6be04162
SB
514 :type 'string
515 :group 'todos-filtered)
516
517(defcustom todos-diary-items-buffer "Todos diary items"
b28872ce 518 "Buffer type string for `todos-filtered-buffer-name'."
6be04162
SB
519 :type 'string
520 :group 'todos-filtered)
521
522(defcustom todos-regexp-items-buffer "Todos regexp items"
b28872ce 523 "Buffer type string for `todos-filtered-buffer-name'."
6be04162
SB
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.
529This variable should be set interactively by
530`\\[todos-set-top-priorities-in-file]' or
531`\\[todos-set-top-priorities-in-category]'.
532
533Each rule is a list of the form (FILE NUM ALIST), where FILE is a
534member of `todos-files', NUM is a number specifying the default
535number of top priority items for each category in that file, and
536ALIST, when non-nil, consists of conses of a category name in
537FILE and a number specifying the default number of top priority
538items in that category, which overrides NUM."
86ea3fbd 539 :type 'sexp
6be04162
SB
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
20166aea
SB
547;; (defcustom todos-save-top-priorities nil ;FIXME: use or delete this
548;; "Non-nil to"
549;; :type 'boolean
550;; :group 'todos-filtered)
551
6be04162
SB
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'.
562Called 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.
572Done items from corresponding archive files are also included."
573 :type 'boolean
574 :group 'todos-filtered)
575
36341a66
SB
576;; ---------------------------------------------------------------------------
577;;; Todos Categories mode options
578
0e89c3fc 579(defgroup todos-categories nil
6be04162 580 "User options for Todos Categories mode."
0e89c3fc
SB
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.
616This separates the number from the category name in the default
617categories 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
ee7412e4 626;; ---------------------------------------------------------------------------
36341a66 627;;; Faces and font-lock matcher functions
ee7412e4 628
d04d6b95
SB
629(defgroup todos-faces nil
630 "Faces for the Todos modes."
0e89c3fc 631 :version "24.2"
d04d6b95
SB
632 :group 'todos)
633
db2c5d34 634(defface todos-prefix-string
0e89c3fc
SB
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)))
3a898abe
SB
646 "Face for Todos prefix or numerical priority string."
647 :group 'todos-faces)
648
649(defface todos-top-priority
e0f6342f
SB
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))
3a898abe
SB
661 "Face for top priority Todos item numerical priority string.
662The item's priority number string has this face if the number is
663less than or equal the category's top priority setting."
d04d6b95 664 :group 'todos-faces)
db2c5d34 665
58c7641d 666(defface todos-mark
0e89c3fc
SB
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)))
58c7641d
SB
689 "Face for marks on Todos items."
690 :group 'todos-faces)
691
ee7412e4 692(defface todos-button
0e89c3fc
SB
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)))
ee7412e4 704 "Face for buttons in todos-display-categories."
d04d6b95
SB
705 :group 'todos-faces)
706
707(defface todos-sorted-column
616ffa8b
SB
708 '((((type tty))
709 (:inverse-video t))
710 (((class color)
0e89c3fc 711 (background light))
a820dfe8 712 (:background "grey85"))
0e89c3fc
SB
713 (((class color)
714 (background dark))
616ffa8b 715 (:background "grey85" :foreground "grey10"))
0e89c3fc 716 (t
a820dfe8 717 (:background "gray")))
d04d6b95
SB
718 "Face for buttons in todos-display-categories."
719 :group 'todos-faces)
720
721(defface todos-archived-only
0e89c3fc
SB
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")))
d04d6b95
SB
731 "Face for archived-only categories in todos-display-categories."
732 :group 'todos-faces)
733
734(defface todos-search
0e89c3fc
SB
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")))
d04d6b95
SB
757 "Face for matches found by todos-search."
758 :group 'todos-faces)
ee7412e4 759
0e89c3fc 760(defface todos-diary-expired
e0f6342f
SB
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))
0e89c3fc
SB
774 "Face for expired dates of diary items."
775 :group 'todos-faces)
776(defvar todos-diary-expired-face 'todos-diary-expired)
777
b28025ed 778(defface todos-date
58c7641d 779 '((t :inherit diary))
0e89c3fc 780 "Face for the date string of a Todos item."
d04d6b95 781 :group 'todos-faces)
b28025ed
SB
782(defvar todos-date-face 'todos-date)
783
784(defface todos-time
58c7641d 785 '((t :inherit diary-time))
0e89c3fc 786 "Face for the time string of a Todos item."
d04d6b95 787 :group 'todos-faces)
b28025ed
SB
788(defvar todos-time-face 'todos-time)
789
e0f6342f
SB
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
2c173503 818(defface todos-done
e0f6342f
SB
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
0e89c3fc 833 ;; '((t :inherit font-lock-comment-face))
3a898abe
SB
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))
58c7641d
SB
851 "Face for comments appended to done Todos items."
852 :group 'todos-faces)
853(defvar todos-comment-face 'todos-comment)
854
2c173503 855(defface todos-done-sep
e0f6342f
SB
856 ;; '((t :inherit font-lock-builtin-face))
857 '((((class grayscale) (background light)) :foreground "LightGray" :weight bold)
3a898abe 858 (((class grayscale) (background dark)) :foreground "DimGray" :weight bold)
e0f6342f
SB
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))
2c173503 865 "Face for separator string bewteen done and not done Todos items."
d04d6b95 866 :group 'todos-faces)
2c173503 867(defvar todos-done-sep-face 'todos-done-sep)
db2c5d34 868
78fe7289
SB
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))
6be04162 899 ;; Function days-between requires a non-empty time string.
78fe7289
SB
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."
b28872ce 920;; (if (eq major-mode 'todos-filtered-items-mode)
78fe7289
SB
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.
e0f6342f
SB
929This is for fontifying category and file names appearing in Todos
930Filtered Items mode following done items."
b28872ce 931 (if (eq major-mode 'todos-filtered-items-mode)
78fe7289
SB
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.
e0f6342f
SB
942This is for fontifying category and file names appearing in Todos
943Filtered Items mode following todo (not done) items."
b28872ce 944 (if (eq major-mode 'todos-filtered-items-mode)
78fe7289
SB
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
db2c5d34
SB
951(defvar todos-font-lock-keywords
952 (list
e0f6342f
SB
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.
0e89c3fc 956 '(todos-diary-nonmarking-matcher 1 font-lock-constant-face t)
58c7641d
SB
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)
3a898abe 960 '(todos-comment-string-matcher 1 todos-comment-face t)
e0f6342f
SB
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)
0e89c3fc
SB
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.")
db2c5d34 967
3f031767 968;; ---------------------------------------------------------------------------
0e89c3fc 969;;; Todos mode local variables and hook functions
3f031767 970
58c7641d
SB
971(defvar todos-current-todos-file nil
972 "Variable holding the name of the currently active Todos file.")
58c7641d 973
0e89c3fc
SB
974(defun todos-show-current-file ()
975 "Visit current instead of default Todos file with `todos-show'.
976This 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))
0e89c3fc 979
6be04162 980(defun todos-display-as-todos-file ()
0e89c3fc
SB
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)))
58c7641d 986
6be04162
SB
987(defun todos-add-to-buffer-list ()
988 "Add name of just visited Todos file to `todos-file-buffers'.
989This 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'.
996This 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
58c7641d 1002(defun todos-reset-global-current-todos-file ()
0e89c3fc
SB
1003 "Update the value of `todos-global-current-todos-file'.
1004This becomes the latest existing Todos file or, if there is none,
1005the value of `todos-default-todos-file'.
1006This function is added to `kill-buffer-hook' in Todos mode."
6be04162
SB
1007 (let ((filename (file-truename (buffer-file-name))))
1008 (setq todos-file-buffers (delete filename todos-file-buffers))
a1a7d89e
SB
1009 (setq todos-global-current-todos-file
1010 (or (car todos-file-buffers)
1011 (todos-absolute-file-name todos-default-todos-file)))))
58c7641d 1012
0e89c3fc
SB
1013(defvar todos-categories nil
1014 "Alist of categories in the current Todos file.
1015The elements are cons cells whose car is a category name and
1016whose cdr is a vector of the category's item counts. These are,
3af3cd0b
SB
1017in order, the numbers of todo items, of todo items included in
1018the Diary, of done items and of archived items.")
0e89c3fc 1019
0e89c3fc
SB
1020(defvar todos-categories-with-marks nil
1021 "Alist of categories and number of marked items they contain.")
1022
58c7641d
SB
1023(defvar todos-category-number 1
1024 "Variable holding the number of the current Todos category.
0e89c3fc 1025Todos categories are numbered starting from 1.")
58c7641d 1026
0e89c3fc
SB
1027(defvar todos-show-done-only nil
1028 "If non-nil display only done items in current category.
3af3cd0b 1029Set by the command `todos-show-done-only' and used by
0e89c3fc 1030`todos-category-select'.")
58c7641d 1031
18aef8a3
SB
1032(defun todos-reset-and-enable-done-separator ()
1033 "Show resized catagory separator overlay after window size change.
1034Added 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
36341a66 1042 ;; also prevents widening category when edebugging todos.el.
18aef8a3
SB
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
0e89c3fc 1052;; ---------------------------------------------------------------------------
36341a66 1053;;; Global variables and helper functions for files and buffers
58c7641d 1054
6be04162
SB
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
c523b0aa
SB
1061(defvar todos-visited nil
1062 "List of Todos files visited in this session by `todos-show'.
1063Used to determine initial display according to the value of
1064`todos-show-first'.")
1065
6be04162
SB
1066(defvar todos-file-buffers nil
1067 "List of file names of live Todos mode buffers.")
1068
0e89c3fc
SB
1069(defvar todos-global-current-todos-file nil
1070 "Variable holding name of current Todos file.
1071Used by functions called from outside of Todos mode to visit the
1072current Todos file rather than the default Todos file (i.e. when
1073users option `todos-show-current-file' is non-nil).")
1074
36341a66 1075(defun todos-reevaluate-filelist-defcustoms ()
3af3cd0b 1076 "Reevaluate defcustoms that provide choice list of Todos files."
0e89c3fc
SB
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))
a2730169
SB
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))
0e89c3fc
SB
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
c523b0aa 1095(defun todos-absolute-file-name (name &optional type)
a2730169 1096 "Return the absolute file name of short Todos file NAME.
c523b0aa
SB
1097With TYPE `archive' or `top' return the absolute file name of the
1098short Todos Archive or Top Priorities file name, respectively."
a2730169
SB
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
c523b0aa
SB
1103 (cond ((eq type 'archive) ".toda")
1104 ((eq type 'top) ".todt")
1105 (t ".todo"))))))
a2730169 1106
36341a66
SB
1107(defun todos-check-format ()
1108 "Signal an error if the current Todos file is ill-formatted.
1109Otherwise return t. The error message gives the line number
1110where 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)
58c7641d 1133
36341a66
SB
1134;; ---------------------------------------------------------------------------
1135(defun todos-convert-legacy-date-time ()
1136 "Return converted date-time string.
1137Helper 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)))))
58c7641d 1147
36341a66
SB
1148;; ---------------------------------------------------------------------------
1149;;; Global variables and helper functions for categories
58c7641d 1150
0e89c3fc
SB
1151(defun todos-category-number (cat)
1152 "Return the number of category CAT in this Todos file.
1153The buffer-local variable `todos-category-number' holds this
1154number 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)))))))
58c7641d 1161
a2730169 1162(defun todos-current-category () ;FIXME: arg FILE ?
0e89c3fc
SB
1163 "Return the name of the current category."
1164 (car (nth (1- todos-category-number) todos-categories)))
58c7641d 1165
0e89c3fc
SB
1166(defconst todos-category-beg "--==-- "
1167 "String marking beginning of category (inserted with its name).")
58c7641d 1168
0e89c3fc
SB
1169(defconst todos-category-done "==--== DONE "
1170 "String marking beginning of category's done items.")
2c173503 1171
144faf47
SB
1172(defun todos-done-separator ()
1173 "Return string used as value of variable `todos-done-separator'."
1174 (let ((sep todos-done-separator-string))
e0f6342f
SB
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)))
144faf47
SB
1179
1180(defvar todos-done-separator (todos-done-separator)
1181 "String used to visually separate done from not done items.
1182Displayed as an overlay instead of `todos-category-done' when
1183done items are shown. Its value is determined by user option
1184`todos-done-separator-string'.")
1185
d9be0d35 1186(defun todos-reset-done-separator (sep)
36341a66 1187 "Replace existing overlays of done items separator string SEP."
d9be0d35
SB
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)
616ffa8b
SB
1194 (let* ((beg (match-beginning 1))
1195 (end (match-end 0))
1196 (ovs (overlays-at beg))
d9be0d35
SB
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
a2730169
SB
1206(defun todos-category-completions ()
1207 "Return a list of completions for `todos-read-category'.
1208Each element of the list is a cons of a category name and the
1209file or list of files (as short file names) it is in. The files
1210are the current (or else the default) Todos file plus all other
1211Todos 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
0e89c3fc
SB
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))
a2730169
SB
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)
0e89c3fc
SB
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)
144faf47 1282 ;; There should never be more than one overlay here, so car suffices.
0e89c3fc
SB
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))))
a2730169
SB
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).
0e89c3fc
SB
1294 (narrow-to-region (point-min) done-start)
1295 ;; Loading this from todos-mode, or adding it to the mode hook, causes
520d912e 1296 ;; Emacs to hang in todos-item-start, at (looking-at todos-item-start).
0e89c3fc
SB
1297 (when todos-highlight-item
1298 (require 'hl-line)
1299 (hl-line-mode 1)))))
3f031767 1300
0e89c3fc
SB
1301(defun todos-get-count (type &optional category)
1302 "Return count of TYPE items in CATEGORY.
1303If 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)))
ee7412e4 1311
3af3cd0b
SB
1312(defun todos-update-count (type increment &optional category)
1313 "Change count of TYPE items in CATEGORY by integer INCREMENT.
1314With nil or omitted CATEGORY, default to the current category."
0e89c3fc
SB
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)))))
d04d6b95 1322
b28872ce 1323(defun todos-set-categories ()
0e89c3fc
SB
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))
7464f422 1332 (setq todos-categories
0e89c3fc
SB
1333 (if (looking-at "\(\(\"")
1334 (read (buffer-substring-no-properties
1335 (line-beginning-position)
1336 (line-end-position)))
7464f422 1337 (error "Invalid or missing todos-categories sexp")))))))
d04d6b95 1338
0e89c3fc
SB
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)))
459c6e93
SB
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.
a1a7d89e 1352 ;; FIXME: is this right?
459c6e93 1353 (setq todos-default-todos-file (buffer-file-name))
7464f422 1354 (setq todos-categories (todos-make-categories-list t)))
0e89c3fc
SB
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)))
7464f422 1358 (prin1 todos-categories (current-buffer))))))
d04d6b95 1359
0e89c3fc
SB
1360(defun todos-make-categories-list (&optional force)
1361 "Return an alist of Todos categories and their item counts.
1362With non-nil argument FORCE parse the entire file to build the
1363list; otherwise, get the value by reading the sexp at the top of
1364the file."
1365 (setq todos-categories nil)
1366 (save-excursion
1367 (save-restriction
1368 (widen)
1369 (goto-char (point-min))
1370 (let (counts cat archive)
6be04162
SB
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.
6be04162
SB
1377 (unless (member (file-truename buffer-file-name)
1378 (funcall todos-files-function t))
0e89c3fc
SB
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))))
6be04162
SB
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.
0e89c3fc
SB
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
11aa0eef
SB
1398 (concat "^" (regexp-quote todos-category-beg)
1399 cat "$")
0e89c3fc
SB
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))))
3af3cd0b 1410 (todos-update-count 'archived archive-count cat))))
0e89c3fc 1411 ((looking-at todos-done-string-start)
3af3cd0b 1412 (todos-update-count 'done 1 cat))
0e89c3fc
SB
1413 ((looking-at (concat "^\\("
1414 (regexp-quote diary-nonmarking-symbol)
1415 "\\)?" todos-date-pattern))
3af3cd0b
SB
1416 (todos-update-count 'diary 1 cat)
1417 (todos-update-count 'todo 1 cat))
0e89c3fc 1418 ((looking-at (concat todos-date-string-start todos-date-pattern))
3af3cd0b 1419 (todos-update-count 'todo 1 cat))
0e89c3fc
SB
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)
3f031767 1430
0e89c3fc 1431(defun todos-repair-categories-sexp ()
520d912e
SB
1432 "Repair corrupt Todos categories sexp.
1433This should only be needed as a consequence of careless manual
1434editing or a bug in todos.el."
0e89c3fc 1435 (interactive)
7464f422 1436 (let ((todos-categories (todos-make-categories-list t)))
0e89c3fc 1437 (todos-update-categories-sexp)))
ee7412e4 1438
36341a66
SB
1439;;; Global variables and helper functions for items
1440
d16da867
SB
1441(defconst todos-month-name-array
1442 (vconcat calendar-month-name-array (vector "*"))
1443 "Array of month names, in order.
1444The 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.
1449The final element is \"*\", indicating an unspecified month.")
1450
36341a66
SB
1451(defconst todos-date-pattern
1452 (let ((dayname (diary-name-pattern calendar-day-name-array nil t)))
d16da867 1453 (concat "\\(?5:" dayname "\\|"
36341a66
SB
1454 (let ((dayname)
1455 ;; FIXME: how to choose between abbreviated and unabbreviated
1456 ;; month name?
d16da867
SB
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]+\\|\\*\\)"))
36341a66
SB
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.")
abe748f5 1488
36341a66 1489(defconst todos-item-start (concat "\\(" todos-date-string-start "\\|"
0e89c3fc
SB
1490 todos-done-string-start "\\)"
1491 todos-date-pattern)
1492 "String identifying start of a Todos item.")
58c7641d 1493
0e89c3fc
SB
1494(defun todos-item-start ()
1495 "Move to start of current Todos item and return its position."
abe748f5 1496 (unless (or
a820dfe8
SB
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))
616ffa8b 1501 ;; Point is on the empty line below category's last todo item...
abe748f5 1502 (and (looking-at "^$")
616ffa8b
SB
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))))))
abe748f5 1508 ;; Buffer is widened.
0e89c3fc
SB
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)))
d04d6b95 1514
0e89c3fc
SB
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 "^$")
0833689a
SB
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))))
ee7412e4 1540
0e89c3fc
SB
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))))
3f031767 1548
0e89c3fc
SB
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)))
ee7412e4 1557
0e89c3fc 1558(defun todos-diary-item-p ()
3af3cd0b 1559 "Return non-nil if item at point has diary entry format."
0e89c3fc 1560 (save-excursion
57da062d
SB
1561 (when (todos-item-string) ; Exclude empty lines.
1562 (todos-item-start)
1563 (not (looking-at (regexp-quote todos-nondiary-start))))))
58c7641d 1564
0e89c3fc
SB
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)))
d04d6b95 1570
1fcf038b
SB
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)))
2c173503 1576
0e89c3fc 1577(defun todos-marked-item-p ()
1fcf038b
SB
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))))
0e89c3fc 1587 (when marked ov)))
3f031767 1588
0e89c3fc
SB
1589(defun todos-insert-with-overlays (item)
1590 "Insert ITEM at point and update prefix/priority number overlays."
1591 (todos-item-start)
1fcf038b
SB
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))))
0e89c3fc
SB
1599 (todos-backward-item)
1600 (todos-prefix-overlays))
2c173503 1601
3a898abe 1602(defun todos-prefix-overlays () ;FIXME: this is a category function
0e89c3fc
SB
1603 "Put before-string overlay in front of this category's items.
1604The overlay's value is the string `todos-prefix' or with non-nil
3af3cd0b
SB
1605`todos-number-priorities' an integer in the sequence from 1 to
1606the number of todo or done items in the category indicating the
0e89c3fc
SB
1607item's priority. Todo and done items are numbered independently
1608of each other."
1fcf038b
SB
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)))))
2c173503 1648
abe748f5 1649;; ---------------------------------------------------------------------------
36341a66 1650;;; Helper functions for user input with prompting and completion
abe748f5 1651
0e89c3fc
SB
1652(defun todos-read-file-name (prompt &optional archive mustmatch)
1653 "Choose and return the name of a Todos file, prompting with PROMPT.
ee7412e4 1654
0e89c3fc
SB
1655Show completions with TAB or SPC; the names are shown in short
1656form but the absolute truename is returned. With non-nil ARCHIVE
1657return the absolute truename of a Todos archive file. With non-nil
1658MUSTMATCH the name of an existing file must be chosen;
1659otherwise, a new file name is allowed."
459c6e93
SB
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))
0e89c3fc 1669 (unless mustmatch
459c6e93
SB
1670 (setq file (todos-validate-name file 'file)))
1671 (setq file (file-truename (concat todos-files-directory file
1672 (if archive ".toda" ".todo"))))))
d04d6b95 1673
a2730169 1674(defun todos-read-category (prompt &optional match-type file)
0e89c3fc 1675 "Choose and return a category name, prompting with PROMPT.
a2730169
SB
1676Show completions for existing categories with TAB or SPC.
1677
1678The argument MATCH-TYPE specifies the matching requirements on
1679the category name: with the value `merge' the name must complete
1680to that of an existing category; with the value `add' the name
1681must not be that of an existing category; with all other values
1682both existing and new valid category names are accepted.
1683
1684With non-nil argument FILE prompt for a file and complete only
1685against categories in that file; otherwise complete against all
1686categories from `todos-category-completions-files'."
0e89c3fc
SB
1687 ;; Allow SPC to insert spaces, for adding new category names.
1688 (let ((map minibuffer-local-completion-map))
1689 (define-key map " " nil)
a2730169
SB
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)))
0e89c3fc 1705 (completion-ignore-case todos-completion-ignore-case)
a2730169
SB
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))
459c6e93 1721 ;; Trigger prompt for initial category.
a2730169
SB
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.
7464f422 1759 (keyboard-quit))))
a2730169 1760 (cons cat file0))))
3f031767 1761
0e89c3fc
SB
1762(defun todos-validate-name (name type)
1763 "Prompt for new NAME for TYPE until it is valid, then return it.
a2730169 1764TYPE can be either of the symbols `file' or `category'."
7464f422
SB
1765 (let ((categories todos-categories)
1766 (files (mapcar 'todos-short-file-name todos-files))
1767 prompt)
0e89c3fc
SB
1768 (while
1769 (and (cond ((string= "" name)
1770 (setq prompt
1771 (cond ((eq type 'file)
a2730169 1772 (if files
0e89c3fc
SB
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)
a2730169 1779 (if categories
0e89c3fc
SB
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: "))
a2730169 1789 ((and (eq type 'file) (member name files))
0e89c3fc 1790 (setq prompt "Enter a non-existing file name: "))
a2730169 1791 ((and (eq type 'category) (assoc name categories))
0e89c3fc 1792 (setq prompt "Enter a non-existing category name: ")))
a2730169
SB
1793 (setq name (if (or (and (eq type 'file) files)
1794 (and (eq type 'category) categories))
7464f422 1795 (completing-read prompt (cond ((eq type 'file)
a2730169 1796 files)
7464f422 1797 ((eq type 'category)
a2730169 1798 categories)))
0e89c3fc 1799 ;; Offer default initial name.
7464f422 1800 (completing-read prompt (if (eq type 'file)
a2730169
SB
1801 files
1802 categories)
7464f422
SB
1803 nil nil (if (eq type 'file)
1804 todos-initial-file
1805 todos-initial-category))))))
1806 name))
0e89c3fc
SB
1807
1808;; Adapted from calendar-read-date and calendar-date-string.
d16da867 1809(defun todos-read-date (&optional arg mo yr)
0e89c3fc 1810 "Prompt for Gregorian date and return it in the current format.
d16da867
SB
1811
1812With non-nil ARG, prompt for and return only the date component
1813specified by ARG, which can be one of these symbols:
1814`month' (prompt for name, return name or number according to
1815value of `calendar-date-display-form'), `day' of month, or
1816`year'. The value of each of these components can be `*',
1817indicating an unspecified month, day, or year.
1818
1819When ARG is `day', non-nil arguments MO and YR determine the
1820number 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 ""))))
2c173503 1890
0e89c3fc
SB
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.
58c7641d 1900
0e89c3fc
SB
1901Valid time strings are those matching `diary-time-regexp'.
1902Typing `<return>' at the prompt returns the current time, if the
1903user option `todos-always-add-time-string' is non-nil, otherwise
1904the 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))
58c7641d 1914
0e89c3fc 1915;; ---------------------------------------------------------------------------
36341a66 1916;;; Item filtering infrastructure
2c173503 1917
a820dfe8
SB
1918(defvar todos-multiple-filter-files nil
1919 "List of files selected from `todos-multiple-filter-files' widget.")
58c7641d 1920
a820dfe8
SB
1921(defvar todos-multiple-filter-files-widget nil
1922 "Variable holding widget created by `todos-multiple-filter-files'.")
58c7641d 1923
a820dfe8 1924(defun todos-multiple-filter-files ()
0e89c3fc
SB
1925 "Pop to a buffer with a widget for choosing multiple filter files."
1926 (require 'widget)
1927 (eval-when-compile
1928 (require 'wid-edit))
520d912e
SB
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")
a820dfe8 1934 (setq todos-multiple-filter-files-widget
520d912e
SB
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)
a820dfe8 1942 (setq todos-multiple-filter-files 'quit)
520d912e
SB
1943 (quit-window t)
1944 (exit-recursive-edit))
1945 "Cancel")
1946 (widget-insert " ")
1947 (widget-create 'push-button
1948 :notify (lambda (&rest ignore)
a820dfe8 1949 (setq todos-multiple-filter-files
520d912e 1950 (mapcar (lambda (f)
20166aea
SB
1951 (file-truename
1952 (concat todos-files-directory
1953 f ".todo")))
520d912e 1954 (widget-value
a820dfe8 1955 todos-multiple-filter-files-widget)))
520d912e
SB
1956 (quit-window t)
1957 (exit-recursive-edit))
1958 "Apply")
1959 (use-local-map widget-keymap)
1960 (widget-setup))
0e89c3fc
SB
1961 (message "Click \"Apply\" after selecting files.")
1962 (recursive-edit))
1963
20166aea
SB
1964(defun todos-filter-items (filter file-list)
1965 "Display a list of items from FILE-LIST that satisfy FILTER.
1966The values of FILE-LIST and FILTER are passed from the calling
1967commands. The files in FILE-LIST are either the current Todos
1968file or those listed in `todos-filter-files' or chosen
1969interactively. The values of FILTER can be `top' for top
1970priority items, a cons of `top' and a number passed by the
1971caller, `diary' for diary items, or `regexp' for items matching a
1972regular expresion entered by the user."
58c7641d 1973 (let ((num (if (consp filter) (cdr filter) todos-show-priorities))
b28872ce 1974 (buf (get-buffer-create todos-filtered-items-buffer))
20166aea 1975 (multifile (> (length file-list) 1))
58c7641d 1976 regexp fname bufstr cat beg end done)
20166aea 1977 (if (null file-list)
0e89c3fc
SB
1978 (error "No files have been chosen for filtering")
1979 (with-current-buffer buf
1980 (erase-buffer)
1981 (kill-all-local-variables)
b28872ce 1982 (todos-filtered-items-mode))
0e89c3fc
SB
1983 (when (eq filter 'regexp)
1984 (setq regexp (read-string "Enter a regular expression: ")))
1985 (save-current-buffer
20166aea 1986 (dolist (f file-list)
0e89c3fc
SB
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
520d912e
SB
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))))))
0e89c3fc 2019 (insert-file-contents f)
520d912e
SB
2020 ;; Delete Todos file categories sexp.
2021 (delete-region (line-beginning-position) (1+ (line-end-position)))
0e89c3fc 2022 (let (fnum)
20166aea
SB
2023 ;; Unless the number of top priorities to show was
2024 ;; passed by the caller, the file-wide value from
a820dfe8
SB
2025 ;; `todos-priorities-rules', if non-nil, overrides
2026 ;; `todos-show-priorities'.
0e89c3fc 2027 (unless (consp filter)
20166aea
SB
2028 (setq fnum (or (nth 1 (assoc f todos-priorities-rules))
2029 todos-show-priorities)))
0e89c3fc
SB
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)
20166aea
SB
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
a820dfe8 2040 ;; `todos-show-priorities'.
0e89c3fc
SB
2041 (unless (consp filter)
2042 (let ((cats (nth 2 (assoc f todos-priorities-rules))))
a820dfe8 2043 (setq cnum (or (cdr (assoc cat cats)) fnum))))
0e89c3fc 2044 (delete-region (match-beginning 0) (match-end 0))
520d912e 2045 (setq beg (point)) ; First item in the current category.
0e89c3fc
SB
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))
520d912e
SB
2058 (unless (and todos-filter-done-items (eq filter 'regexp))
2059 ;; Leave done items.
0e89c3fc
SB
2060 (delete-region done end)
2061 (setq end done))
520d912e 2062 (narrow-to-region beg end) ; Process only current category.
0e89c3fc
SB
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.
520d912e
SB
2084 (if (and (eobp)
2085 (looking-back
2086 (concat (regexp-quote todos-done-string)
2087 "\n")))
0e89c3fc
SB
2088 (delete-region (point) (progn
2089 (forward-line -2)
2090 (point))))))
0e89c3fc
SB
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))
520d912e
SB
2096 ;; Delete non-top-priority items.
2097 (unless (member filter '(diary regexp))
0e89c3fc
SB
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
520d912e
SB
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 "?")
0e89c3fc 2114 nil t)
520d912e
SB
2115 (insert " [")
2116 (when (looking-at "(archive) ") (goto-char (match-end 0)))
2117 (insert (if multifile (concat fname ":") "") cat "]"))
0e89c3fc
SB
2118 (forward-line))
2119 (widen)))
2120 (setq bufstr (buffer-string))
2121 (with-current-buffer buf
2122 (let (buffer-read-only)
2123 (insert bufstr)))))))
0e89c3fc
SB
2124 (set-window-buffer (selected-window) (set-buffer buf))
2125 (todos-prefix-overlays)
520d912e 2126 (goto-char (point-min)))))
0e89c3fc
SB
2127
2128(defun todos-set-top-priorities (&optional arg)
2129 "Set number of top priorities shown by `todos-top-priorities'.
2130With non-nil ARG, set the number only for the current Todos
2131category; otherwise, set the number for all categories in the
2132current Todos file.
2133
2134Calling 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
2137set 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)))
86ea3fbd 2143 (crules (nth 2 frule))
0e89c3fc
SB
2144 (cur (or (if arg (cdr crule) (nth 1 frule))
2145 todos-show-priorities))
86ea3fbd
SB
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)
0e89c3fc 2151 nrule)
86ea3fbd 2152 (while (< new 0)
0e89c3fc 2153 (let ((cur0 cur))
86ea3fbd 2154 (setq new (read-number (format prompt cur0))
0e89c3fc
SB
2155 prompt "Enter a non-negative number: "
2156 cur0 nil)))
0e89c3fc 2157 (setq nrule (if arg
86ea3fbd
SB
2158 (append (delete crule crules) (list (cons cat new)))
2159 (append (list file new) (list crules))))
0e89c3fc
SB
2160 (setq rules (cons (if arg
2161 (list file cur nrule)
2162 nrule)
2163 (delete frule rules)))
3a898abe
SB
2164 (customize-save-variable 'todos-priorities-rules rules)
2165 (todos-prefix-overlays)))
2c173503 2166
b28872ce
SB
2167(defun todos-filtered-buffer-name (buffer-type file-list)
2168 "Rename Todos filtered buffer using BUFFER-TYPE and FILE-LIST.
6be04162
SB
2169
2170The new name is constructed from the string BUFFER-TYPE, which
2171refers to one of the top priorities, diary or regexp item
2172filters, and the names of the filtered files in FILE-LIST. Used
2173in Todos Filter Items mode."
20166aea 2174 (let* ((multi (> (length file-list) 1))
6be04162 2175 (fnames (mapconcat (lambda (f) (todos-short-file-name f))
20166aea 2176 file-list ", ")))
6be04162
SB
2177 (rename-buffer (format (concat "%s for file" (if multi "s" "")
2178 " \"%s\"") buffer-type fnames))))
d04d6b95 2179
20166aea 2180(defun todos-find-item (str)
dda6bf79
SB
2181 "Search for saved top priority item STR in its Todos file.
2182Return the list (FOUND FILE CAT), where CAT and FILE are the
2183item's category and file, and FOUND is a cons cell if the search
2184succeeds, whose car is the start of the item in FILE and whose
2185cdr is `done' if the item is now a done item, `changed' if its
2186priority has changed or its text was truncated or augmented, and
2187`same' otherwise."
20166aea
SB
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) "))
dda6bf79
SB
2201 (filcat (match-string 4 str))
2202 (tpriority 1)
20166aea
SB
2203 found)
2204 (setq str (replace-match "" nil nil str 4))
dda6bf79
SB
2205 (save-excursion
2206 (while (search-backward filcat nil t)
2207 (setq tpriority (1+ tpriority))))
20166aea
SB
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))
dda6bf79
SB
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)))
20166aea
SB
2253
2254(defun todos-check-top-priorities ()
dda6bf79
SB
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 )))))
20166aea
SB
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
0e89c3fc
SB
2290;; ---------------------------------------------------------------------------
2291;;; Sorting and display routines for Todos Categories mode.
58c7641d 2292
0e89c3fc
SB
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))))))
58c7641d 2298
b58fa72f
SB
2299(defun todos-adjusted-category-label-length ()
2300 "Return adjusted length of category label button.
2301The adjustment ensures proper tabular alignment in Todos
2302Categories 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
0e89c3fc 2312(defun todos-padded-string (str)
b58fa72f 2313 "Return category name or label string STR padded with spaces.
0e89c3fc
SB
2314The placement of the padding is determined by the value of user
2315option `todos-categories-align'."
b58fa72f 2316 (let* ((len (todos-adjusted-category-label-length))
0e89c3fc 2317 (strlen (length str))
b58fa72f 2318 (strlen-odd (eq (logand strlen 1) 1))
0e89c3fc
SB
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))))
58c7641d 2330
0e89c3fc
SB
2331(defvar todos-descending-counts nil
2332 "List of keys for category counts sorted in descending order.")
58c7641d 2333
0e89c3fc
SB
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))))
a820dfe8
SB
2340 ;; Keep track of whether the last sort by key was descending or
2341 ;; ascending.
0e89c3fc
SB
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))
a820dfe8 2351 ;; Switch between descending and ascending sort order.
0e89c3fc
SB
2352 (if descending
2353 (setq todos-descending-counts
2354 (delete key todos-descending-counts))
2355 (push key todos-descending-counts)))
2356 l))
58c7641d 2357
0e89c3fc
SB
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)))
d04d6b95 2363
0e89c3fc
SB
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))
ee7412e4 2378
0e89c3fc
SB
2379(defun todos-insert-sort-button (label)
2380 "Insert button for displaying categories sorted by item counts.
2381LABEL 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
a820dfe8 2395 ;; category priority order.
0e89c3fc
SB
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))
ee7412e4 2402
0e89c3fc
SB
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)))
ee7412e4 2408
7464f422
SB
2409(defvar todos-categories-category-number 0
2410 "Variable for numbering categories in Todos Categories mode.")
459c6e93 2411
0e89c3fc 2412(defun todos-insert-category-line (cat &optional nonum)
459c6e93 2413 "Insert button with category CAT's name and item counts.
0e89c3fc
SB
2414With non-nil argument NONUM show only these; otherwise, insert a
2415number in front of the button indicating the category's priority.
2416The number and the category name are separated by the string
2417which is the value of the user option
2418`todos-categories-number-separator'."
459c6e93 2419 (let ((archive (member todos-current-todos-file todos-archives))
7464f422 2420 (num todos-categories-category-number)
0e89c3fc
SB
2421 (str (todos-padded-string cat))
2422 (opoint (point)))
7464f422 2423 (setq num (1+ num) todos-categories-category-number num)
0e89c3fc
SB
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)))
a820dfe8
SB
2444 "")
2445 " ") ; So highlighting of last column is consistent with the others.
6be04162 2446 'face (if (and todos-skip-archived-categories
0e89c3fc
SB
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)))
a2730169 2453 (todos-jump-to-category nil ,cat)
0e89c3fc
SB
2454 (kill-buffer buf))))
2455 ;; Highlight the sorted count column.
a820dfe8 2456 (let* ((beg (+ opoint 7 (length str)))
0e89c3fc
SB
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)))))
a820dfe8 2472 (unless (= beg (+ opoint 7 (length str))) ; Don't highlight categories.
0e89c3fc
SB
2473 (setq end (+ beg 4))
2474 (setq ovl (make-overlay beg end))
2475 (overlay-put ovl 'face 'todos-sorted-column)))
2476 (newline)))
d04d6b95 2477
0e89c3fc
SB
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)
a1a7d89e
SB
2481 (setq todos-global-current-todos-file
2482 (or todos-current-todos-file
2483 (todos-absolute-file-name todos-default-todos-file)))
0e89c3fc
SB
2484 (set-window-buffer (selected-window)
2485 (set-buffer (get-buffer-create todos-categories-buffer)))
2486 (kill-all-local-variables)
2487 (todos-categories-mode)
6be04162
SB
2488 (let ((archive (member todos-current-todos-file todos-archives))
2489 buffer-read-only)
0e89c3fc
SB
2490 (erase-buffer)
2491 ;; FIXME: add usage tips?
6be04162
SB
2492 (insert (format (concat "Category counts for Todos "
2493 (if archive "archive" "file")
2494 " \"%s\".")
0e89c3fc
SB
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)
6be04162
SB
2502 (if archive
2503 (progn
2504 (insert (make-string 3 32))
2505 (todos-insert-sort-button todos-categories-done-label))
0e89c3fc
SB
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 ""
7464f422 2518 (let* ((cats0 todos-categories)
459c6e93
SB
2519 (cats (todos-sort cats0 sortkey))
2520 (archive (member todos-current-todos-file todos-archives))
7464f422 2521 (todos-categories-category-number 0)
459c6e93
SB
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)))
ee7412e4 2558
0e89c3fc 2559;; ---------------------------------------------------------------------------
6be04162 2560;;; Routines for generating Todos insertion commands and key bindings
ee7412e4 2561
0e89c3fc 2562;; Can either of these be included in Emacs? The originals are GFDL'd.
7464f422 2563
0e89c3fc
SB
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
520d912e
SB
2570 (let ((prev (powerset-recursive (cdr l))))
2571 (append (mapcar (lambda (elt) (cons (car l) elt))
2572 prev)
0e89c3fc 2573 prev)))))
7464f422 2574
0e89c3fc
SB
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)
ee7412e4 2593
0e89c3fc
SB
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))))))
d04d6b95 2612
0e89c3fc
SB
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.")
ee7412e4 2616
0e89c3fc
SB
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.")
3f031767 2644
0e89c3fc
SB
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 "-+" "-"
59ad682f 2651 ;; FIXME: "todos-insert-item-"
0e89c3fc
SB
2652 (concat "todos-item-insert-"
2653 (mapconcat (lambda (e) (if e (symbol-name e))) arglist "-")))))
d04d6b95 2654
0e89c3fc
SB
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.")
d04d6b95 2660
59ad682f 2661;; FIXME: prefix argument ARG is nil
0e89c3fc
SB
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)))
59ad682f 2669 `(defun ,name (&optional arg &rest args)
3af3cd0b 2670 "Todos item insertion command generated from ARGS."
59ad682f 2671 (interactive (list current-prefix-arg))
0e89c3fc 2672 (todos-insert-item arg ',arg0 ',arg1 ',arg2 ',arg3 ',arg4))))
3f031767 2673
59ad682f
SB
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)
0e89c3fc
SB
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.")
db2c5d34 2682
0e89c3fc
SB
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 "")
db2c5d34 2693
0e89c3fc
SB
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))))
ee7412e4 2711
0e89c3fc
SB
2712(defvar todos-insertion-map
2713 (let ((map (make-keymap)))
2714 (todos-insertion-key-bindings map)
fd6c6328 2715 (define-key map "p" 'todos-copy-item)
0e89c3fc
SB
2716 map)
2717 "Keymap for Todos mode insertion commands.")
ee7412e4 2718
abe748f5 2719;; ---------------------------------------------------------------------------
6be04162
SB
2720;;; Key maps and menus
2721
0e89c3fc
SB
2722(defvar todos-key-bindings
2723 `(
2724 ;; display
d16da867 2725 ("Cd" . todos-display-categories) ;FIXME: Fc todos-file-categories?
0e89c3fc 2726 ("H" . todos-highlight-item)
3af3cd0b 2727 ("N" . todos-hide-show-item-numbering)
78fe7289
SB
2728 ("D" . todos-hide-show-date-time)
2729 ("*" . todos-mark-unmark-item)
0e89c3fc
SB
2730 ("C*" . todos-mark-category)
2731 ("Cu" . todos-unmark-category)
2732 ("PP" . todos-print)
2733 ("PF" . todos-print-to-file)
3af3cd0b
SB
2734 ("v" . todos-hide-show-done-items)
2735 ("V" . todos-show-done-only)
0e89c3fc
SB
2736 ("As" . todos-show-archive)
2737 ("Ac" . todos-choose-archive)
d16da867 2738 ;; ("Y" . todos-diary-items)
0e89c3fc
SB
2739 ("Fe" . todos-edit-multiline)
2740 ("Fh" . todos-highlight-item)
3af3cd0b 2741 ("Fn" . todos-hide-show-item-numbering)
78fe7289 2742 ("Fd" . todos-hide-show-date-time)
0e89c3fc
SB
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)
0e89c3fc
SB
2751 ;; navigation
2752 ("f" . todos-forward-category)
2753 ("b" . todos-backward-category)
2754 ("j" . todos-jump-to-category)
0e89c3fc
SB
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)
0e89c3fc
SB
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)
0e89c3fc 2770 ("edc" . todos-edit-item-date-from-calendar)
d16da867
SB
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)
0e89c3fc
SB
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)
b28872ce 2781 ("ec" . todos-done-item-add-edit-or-delete-comment)
0e89c3fc 2782 ("i" . ,todos-insertion-map)
7464f422 2783 ("k" . todos-delete-item) ;FIXME: not single letter?
0e89c3fc 2784 ("m" . todos-move-item)
0e89c3fc 2785 ("r" . todos-raise-item-priority)
0e89c3fc
SB
2786 ("l" . todos-lower-item-priority)
2787 ("#" . todos-set-item-priority)
2788 ("u" . todos-item-undo)
b28872ce
SB
2789 ("Ad" . todos-archive-done-item) ;FIXME: ad
2790 ("AD" . todos-archive-category-done-items) ;FIXME: aD or C-u ad ?
0e89c3fc
SB
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.")
d04d6b95 2805
58c7641d 2806;; FIXME
0e89c3fc
SB
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]
0e89c3fc
SB
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]
3af3cd0b 2824 ["Turn Item Numbering on/off" todos-hide-show-item-numbering t]
78fe7289 2825 ["Turn Item Time Stamp on/off" todos-hide-show-date-time t]
3af3cd0b 2826 ["View/Hide Done Items" todos-hide-show-done-items t]
0e89c3fc
SB
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 "---"
0e89c3fc
SB
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]
a820dfe8 2860 )
0e89c3fc
SB
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)
3af3cd0b 2877 (define-key map "N" 'todos-hide-show-item-numbering)
78fe7289 2878 ;; (define-key map "" 'todos-hide-show-date-time)
0e89c3fc
SB
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)
2a9e69d6 2883 (define-key map "t" 'todos-show)
abe748f5 2884 (define-key map "u" 'todos-unarchive-items)
0e89c3fc
SB
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)
a820dfe8
SB
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)
2a9e69d6
SB
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)
18aef8a3
SB
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)
0e89c3fc
SB
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
b28872ce 2919(defvar todos-filtered-items-mode-map
0e89c3fc
SB
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)
3af3cd0b 2928 (define-key map "N" 'todos-hide-show-item-numbering)
78fe7289 2929 (define-key map "D" 'todos-hide-show-date-time)
0e89c3fc
SB
2930 (define-key map "P" 'todos-print)
2931 (define-key map "q" 'todos-quit)
2932 (define-key map "s" 'todos-save)
0e89c3fc
SB
2933 ;; editing commands
2934 (define-key map "l" 'todos-lower-item-priority)
2935 (define-key map "r" 'todos-raise-item-priority)
616ffa8b 2936 (define-key map "#" 'todos-set-item-priority)
0e89c3fc
SB
2937 map)
2938 "Todos Top Priorities mode keymap.")
2939
abe748f5
SB
2940;; ---------------------------------------------------------------------------
2941;;; Mode definitions
6be04162 2942
0e89c3fc
SB
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 ()
616ffa8b 2958 ""
0e89c3fc
SB
2959 (set (make-local-variable 'todos-categories) (todos-set-categories))
2960 (set (make-local-variable 'todos-category-number) 1)
6be04162 2961 (add-hook 'find-file-hook 'todos-display-as-todos-file nil t))
0e89c3fc
SB
2962
2963(put 'todos-mode 'mode-class 'special)
2964
616ffa8b 2965(define-derived-mode todos-mode special-mode "Todos"
0e89c3fc
SB
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))))
0e89c3fc 2978 (set (make-local-variable 'todos-show-done-only) nil)
2a9e69d6 2979 (set (make-local-variable 'todos-categories-with-marks) nil)
6be04162
SB
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)
0e89c3fc
SB
2982 (when todos-show-current-file
2983 (add-hook 'pre-command-hook 'todos-show-current-file nil t))
0e89c3fc 2984 (add-hook 'window-configuration-change-hook
18aef8a3 2985 'todos-reset-and-enable-done-separator nil t)
0e89c3fc
SB
2986 (add-hook 'kill-buffer-hook 'todos-reset-global-current-todos-file nil t))
2987
0e89c3fc
SB
2988(defun todos-unload-hook ()
2989 ""
2990 (remove-hook 'pre-command-hook 'todos-show-current-file t)
6be04162
SB
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)
0e89c3fc 2994 (remove-hook 'window-configuration-change-hook
d9be0d35 2995 'todos-reset-and-enable-done-separator t)
0e89c3fc
SB
2996 (remove-hook 'kill-buffer-hook 'todos-reset-global-current-todos-file t))
2997
2998(put 'todos-archive-mode 'mode-class 'special)
2999
abe748f5
SB
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).
616ffa8b 3002(define-derived-mode todos-archive-mode special-mode "Todos-Arch"
0e89c3fc
SB
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 ()
d04d6b95 3014 ""
0e89c3fc
SB
3015 (set (make-local-variable 'todos-current-todos-file)
3016 todos-global-current-todos-file)
a820dfe8 3017 (let ((cats (with-current-buffer
c523b0aa
SB
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)
b28872ce 3023 todos-categories)))
0e89c3fc 3024 (set (make-local-variable 'todos-categories) cats)))
d04d6b95 3025
616ffa8b 3026(define-derived-mode todos-edit-mode text-mode "Todos-Ed"
0e89c3fc 3027 "Major mode for editing multiline Todo items.
58c7641d 3028
7464f422 3029\\{todos-edit-mode-map}"
0e89c3fc
SB
3030 (todos-modes-set-1)
3031 (todos-mode-external-set))
58c7641d 3032
0e89c3fc 3033(put 'todos-categories-mode 'mode-class 'special)
58c7641d 3034
616ffa8b 3035(define-derived-mode todos-categories-mode special-mode "Todos-Cats"
0e89c3fc 3036 "Major mode for displaying and editing Todos categories.
58c7641d 3037
0e89c3fc
SB
3038\\{todos-categories-mode-map}"
3039 (todos-mode-external-set))
58c7641d 3040
e0f6342f 3041(put 'todos-filtered-items-mode 'mode-class 'special)
58c7641d 3042
616ffa8b 3043(define-derived-mode todos-filtered-items-mode special-mode "Todos-Fltr"
0e89c3fc 3044 "Mode for displaying and reprioritizing top priority Todos.
58c7641d 3045
b28872ce 3046\\{todos-filtered-items-mode-map}"
0e89c3fc
SB
3047 (todos-modes-set-1)
3048 (todos-modes-set-2))
3049
b28872ce
SB
3050;; ---------------------------------------------------------------------------
3051;;; Todos Commands
0e89c3fc
SB
3052
3053;; ---------------------------------------------------------------------------
b28872ce 3054;;; Entering and Exiting
0e89c3fc
SB
3055
3056;;;###autoload
3057(defun todos-show (&optional solicit-file)
c523b0aa 3058 "Visit a Todos file and display one of its categories.
a820dfe8 3059With non-nil prefix argument SOLICIT-FILE prompt for which todo
c523b0aa
SB
3060file to visit; otherwise visit `todos-default-todos-file'.
3061Subsequent invocations from outside of Todos mode revisit this
3062file or, with option `todos-show-current-file' non-nil (the
3063default), whichever Todos file was last visited.
3064
3065Calling this command before any Todos file exists prompts for a
3066file name and an initial category (defaulting to
3067`todos-initial-file' and `todos-initial-category'), creates both
3068of these, visits the file and displays the category.
3069
3070The first invocation of this command on an existing Todos file
3071interacts with the option `todos-show-first': if `table', show
3072the table of categories in the file; if `top', show the
3073corresponding top priorities file, if any; if `first' (the
3074default value), show the first category in the file. Subsequent
3075invocations always show the file's current (i.e., last displayed)
3076category.
0e89c3fc
SB
3077
3078In Todos mode just the category's unfinished todo items are shown
3079by default. The done items are hidden, but typing
3af3cd0b 3080`\\[todos-hide-show-done-items]' displays them below the todo
0e89c3fc 3081items. With non-nil user option `todos-show-with-done' both todo
2a9e69d6
SB
3082and done items are always shown on visiting a category.
3083
c523b0aa 3084Invoking this command in Todos Archive mode visits the
2a9e69d6 3085corresponding Todos file, displaying the corresponding category."
3f031767 3086 (interactive "P")
2a9e69d6 3087 (let* ((cat)
c523b0aa 3088 (show-first todos-show-first)
2a9e69d6 3089 (file (cond (solicit-file
459c6e93
SB
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")))
6be04162
SB
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))
459c6e93
SB
3098 (setq cat (todos-current-category))
3099 (concat (file-name-sans-extension todos-current-todos-file)
3100 ".todo"))
3101 (t
459c6e93
SB
3102 (or todos-current-todos-file
3103 (and todos-show-current-file
3104 todos-global-current-todos-file)
a2730169 3105 (todos-absolute-file-name todos-default-todos-file)
459c6e93 3106 (todos-add-file))))))
c523b0aa
SB
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))
0e89c3fc 3125 (set-window-buffer (selected-window)
a2730169 3126 (set-buffer (find-file-noselect file 'nowarn)))
c523b0aa
SB
3127 ;; If called from archive file, show corresponding
3128 ;; category in Todos file, if it exists.
2a9e69d6
SB
3129 (when (assoc cat todos-categories)
3130 (setq todos-category-number (todos-category-number cat)))
bbf95285 3131 ;; If this is a new Todos file, add its first category.
2a9e69d6 3132 (when (zerop (buffer-size))
a2730169
SB
3133 (setq todos-category-number
3134 (todos-add-category todos-current-todos-file "")))
0e89c3fc 3135 (save-excursion (todos-category-select)))
c523b0aa
SB
3136 (setq todos-show-first show-first)
3137 (add-to-list 'todos-visited file)))
d04d6b95 3138
0e89c3fc
SB
3139(defun todos-display-categories ()
3140 "Display a table of the current file's categories and item counts.
3141
3142In the initial display the categories are numbered, indicating
3143their current order for navigating by \\[todos-forward-category]
3144and \\[todos-backward-category]. You can persistantly change the
2a9e69d6
SB
3145order of the category at point by typing
3146\\[todos-raise-category-priority] or
3147\\[todos-lower-category-priority].
0e89c3fc
SB
3148
3149The labels above the category names and item counts are buttons,
3150and clicking these changes the display: sorted by category name
3151or by the respective item counts (alternately descending or
3152ascending). In these displays the categories are not numbered
2a9e69d6
SB
3153and \\[todos-raise-category-priority] and
3154\\[todos-lower-category-priority] are
0e89c3fc
SB
3155disabled. (Programmatically, the sorting is triggered by passing
3156a non-nil SORTKEY argument.)
3157
3158In addition, the lines with the category names and item counts
3159are buttonized, and pressing one of these button jumps to the
3160category in Todos mode (or Todos Archive mode, for categories
3161containing only archived items, provided user option
6be04162 3162`todos-skip-archived-categories' is non-nil. These categories
0e89c3fc 3163are shown in `todos-archived-only' face."
2c173503 3164 (interactive)
0e89c3fc
SB
3165 (todos-display-categories-1)
3166 (let (sortkey)
3167 (todos-update-categories-display sortkey)))
2c173503 3168
a820dfe8
SB
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))))
3f031767 3181
a820dfe8
SB
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)))
58c7641d 3189
a820dfe8
SB
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)))
58c7641d 3197
a820dfe8
SB
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)))
0e89c3fc 3205
a820dfe8
SB
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)))
0e89c3fc 3213
0e89c3fc 3214(defun todos-show-archive (&optional ask)
3af3cd0b
SB
3215 "Visit the archive of the current Todos category, if it exists.
3216If the category has no archived items, prompt to visit the
3217archive anyway. If there is no archive for this file or with
3218non-nil argument ASK, prompt to visit another archive.
3219
abe748f5
SB
3220The buffer showing the archive is in Todos Archive mode. The
3221first visit in a session displays the first category in the
3222archive, subsequent visits return to the last category
3223displayed."
0e89c3fc 3224 (interactive)
3af3cd0b
SB
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"))
47011bed
SB
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
3af3cd0b
SB
3243 (set-window-buffer (selected-window)
3244 (set-buffer (find-file-noselect archive)))
47011bed
SB
3245 (if (member place '(other-archive other-cat))
3246 (setq todos-category-number 1)
3247 (todos-category-number cat))
3248 (todos-category-select))))
58c7641d 3249
0e89c3fc
SB
3250(defun todos-choose-archive ()
3251 "Choose an archive and visit it."
3252 (interactive)
3253 (todos-show-archive t))
58c7641d 3254
b28872ce
SB
3255(defun todos-save ()
3256 "Save the current Todos file."
3f031767 3257 (interactive)
20166aea
SB
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))))
d04d6b95 3263
b28872ce
SB
3264(defun todos-quit ()
3265 "Exit the current Todos-related buffer.
3266Depending on the specific mode, this either kills the buffer or
3267buries it and restores state as needed."
0e89c3fc 3268 (interactive)
b28872ce 3269 (cond ((eq major-mode 'todos-categories-mode)
c523b0aa
SB
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)))
b28872ce
SB
3280 ((eq major-mode 'todos-filtered-items-mode)
3281 (kill-buffer)
3282 (todos-show))
3283 ((member major-mode (list 'todos-mode 'todos-archive-mode))
616ffa8b
SB
3284 ;; Have to write previously nonexistant archives to file, and might
3285 ;; as well save Todos file also.
b28872ce
SB
3286 (todos-save)
3287 (bury-buffer))))
d04d6b95 3288
0e89c3fc
SB
3289(defun todos-print (&optional to-file)
3290 "Produce a printable version of the current Todos buffer.
3291This converts overlays and soft line wrapping and, depending on
3292the value of `todos-print-function', includes faces. With
3293non-nil argument TO-FILE write the printable version to a file;
3294otherwise, send it to the default printer."
db2c5d34 3295 (interactive)
0e89c3fc
SB
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)))
b28872ce 3302 ((eq major-mode 'todos-filtered-items-mode)
0e89c3fc
SB
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))))
3af3cd0b 3316 (when todos-number-priorities
0e89c3fc
SB
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)))
2c173503 3338
0e89c3fc
SB
3339(defun todos-print-to-file ()
3340 "Save printable version of this Todos buffer to a file."
d04d6b95 3341 (interactive)
0e89c3fc 3342 (todos-print t))
d04d6b95 3343
0e89c3fc
SB
3344(defun todos-convert-legacy-files ()
3345 "Convert legacy Todo files to the current Todos format.
3346The files `todo-file-do' and `todo-file-done' are converted and
3347saved (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
11aa0eef
SB
3441 (concat "^" (regexp-quote (concat todos-category-beg cat))
3442 "$")
0e89c3fc
SB
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)))
36341a66 3485 (todos-reevaluate-filelist-defcustoms)
0e89c3fc
SB
3486 (message "Format conversion done."))
3487 (error "No legacy Todo file exists")))
2c173503 3488
0e89c3fc
SB
3489;; ---------------------------------------------------------------------------
3490;;; Navigation Commands
3491
3492(defun todos-forward-category (&optional back)
3493 "Visit the numerically next category in this Todos file.
3494If the current category is the highest numbered, visit the first
3495category. With non-nil argument BACK, visit the numerically
3496previous category (the highest numbered one, if the current
3497category is the first)."
58c7641d 3498 (interactive)
0e89c3fc
SB
3499 (setq todos-category-number
3500 (1+ (mod (- todos-category-number (if back 2 0))
3501 (length todos-categories))))
6be04162 3502 (when todos-skip-archived-categories
7464f422
SB
3503 (while (and (zerop (todos-get-count 'todo))
3504 (zerop (todos-get-count 'done))
45e4a397 3505 (not (zerop (todos-get-count 'archived))))
7464f422
SB
3506 (setq todos-category-number
3507 (apply (if back '1- '1+) (list todos-category-number)))))
0e89c3fc
SB
3508 (todos-category-select)
3509 (goto-char (point-min)))
58c7641d 3510
0e89c3fc
SB
3511(defun todos-backward-category ()
3512 "Visit the numerically previous category in this Todos file.
3513If the current category is the highest numbered, visit the first
3514category."
3515 (interactive)
3516 (todos-forward-category t))
58c7641d 3517
a2730169
SB
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
3522With prefix argument FILE, prompt for a specific Todos file and
3523choose (with TAB completion) a category in it to jump to;
3524otherwise, choose and jump to any category in either the current
3525Todos file or a file in `todos-category-completions-files'.
0e89c3fc 3526
a2730169
SB
3527You can also enter a non-existing category name, triggering a
3528prompt whether to add a new category by that name; on
3529confirmation it is added and jumped to.
3530
3531Noninteractively, jump directly to the category named by argument
3532CAT; 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))))
0e89c3fc 3546 (concat (file-name-sans-extension
a2730169
SB
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.
520d912e
SB
3557 (if (string= (buffer-name) todos-categories-buffer)
3558 (kill-buffer))
a2730169
SB
3559 (set-window-buffer (selected-window)
3560 (set-buffer (find-buffer-visiting file0)))
520d912e
SB
3561 (unless todos-global-current-todos-file
3562 (setq todos-global-current-todos-file todos-current-todos-file))
a2730169 3563 (todos-category-number category)
520d912e
SB
3564 (todos-category-select)
3565 (goto-char (point-min))))))
58c7641d 3566
0e89c3fc
SB
3567(defun todos-jump-to-item ()
3568 "Jump to the file and category of the filtered item at point."
d04d6b95 3569 (interactive)
20166aea
SB
3570 (let* ((str (todos-item-string))
3571 (buf (current-buffer))
3572 (res (todos-find-item str))
dda6bf79 3573 (found (nth 0 res))
20166aea 3574 (file (nth 1 res))
dda6bf79
SB
3575 (cat (nth 2 res)))
3576 (if (not found)
3577 (message "Category %s does not contain this item." cat)
20166aea
SB
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))
dda6bf79
SB
3583 (let ((todos-show-with-done (if (or todos-filter-done-items
3584 (eq (cdr found) 'done))
20166aea
SB
3585 t
3586 todos-show-with-done)))
3587 (todos-category-select))
dda6bf79 3588 (goto-char (car found)))))
0e89c3fc 3589
0e89c3fc
SB
3590(defun todos-forward-item (&optional count)
3591 "Move point down to start of item with next lower priority.
616ffa8b
SB
3592With positive numerical prefix COUNT, move point COUNT items
3593downward."
0e89c3fc 3594 (interactive "P")
616ffa8b
SB
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))))))
0833689a
SB
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)))))))
58c7641d 3624
0e89c3fc
SB
3625(defun todos-backward-item (&optional count)
3626 "Move point up to start of item with next higher priority.
616ffa8b
SB
3627With positive numerical prefix COUNT, move point COUNT items
3628upward."
0e89c3fc 3629 (interactive "P")
616ffa8b
SB
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))))))
b28872ce 3651
18aef8a3
SB
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
b28872ce 3668;; FIXME: (i) Extend search to other Todos files. (ii) Allow navigating among
616ffa8b
SB
3669;; hits. (But these features are effectively available with
3670;; todos-regexp-items-multifile, so maybe it's not worth the trouble here.)
b28872ce
SB
3671(defun todos-search ()
3672 "Search for a regular expression in this Todos file.
3673The search runs through the whole file and encompasses all and
3674only todo and done items; it excludes category names. Multiple
3675matches are shown sequentially, highlighted in `todos-search'
3676face."
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 ()
616ffa8b 3763 "Highlight or unhighlight the todo item the cursor is on."
b28872ce
SB
3764 (interactive)
3765 (require 'hl-line)
3766 (if hl-line-mode
3767 (hl-line-mode -1)
3768 (hl-line-mode 1)))
3769
616ffa8b
SB
3770(defun todos-hide-show-date-time ()
3771 "Hide or show date-time header of todo items in the current file."
3772 (interactive)
b28872ce
SB
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)))
b28872ce 3782 (widen)
616ffa8b 3783 (goto-char (point-min))
b28872ce
SB
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
1fcf038b
SB
3797(defun todos-mark-unmark-item (&optional n)
3798 "Mark item with `todos-item-mark' if unmarked, otherwise unmark it.
b28872ce 3799With a positive numerical prefix argument N, change the
1fcf038b 3800marking of the next N items."
b28872ce 3801 (interactive "p")
1fcf038b
SB
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)))
b28872ce
SB
3820
3821(defun todos-mark-category ()
1fcf038b 3822 "Mark all visiblw items in this category with `todos-item-mark'."
b28872ce 3823 (interactive)
1fcf038b
SB
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))))
b28872ce
SB
3837
3838(defun todos-unmark-category ()
1fcf038b 3839 "Remove `todos-item-mark' from all visible items in this category."
b28872ce 3840 (interactive)
1fcf038b
SB
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))))
b28872ce
SB
3855
3856;; ---------------------------------------------------------------------------
3857;;; Item filtering commands
3858
3859(defun todos-set-top-priorities-in-file ()
3860 "Set number of top priorities for this file.
3861See `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.
3867See `todos-set-top-priorities' for more details."
3868 (interactive)
3869 (todos-set-top-priorities t))
3870
20166aea
SB
3871(defun todos-top-priorities (&optional arg multifile)
3872 "Display a list of top priority items from different categories.
3873The categories are either a subset of those in the current Todos
3874file, or else, with non-nil argument MULTIFILE, a subset of the
3875categories in the files listed in `todos-filter-files', or if
3876this nil, in the files chosen from a file selection dialog that
3877pops up in this case.
3878
3879With numerical prefix ARG show at most ARG top priority items
3880from each category. With `C-u' as prefix argument show the
3881numbers of top priority items specified by category in
3882`todos-priorities-rules', if this has an entry for the file(s);
3883otherwise show `todos-show-priorities' items per category in the
3884file(s). With no prefix argument, if a top priorities file for
3885the current Todos file has previously been saved (see
3886`todos-save-top-priorities-buffer'), visit this file; if there is
3887no such file, build the list as with prefix argument `C-u'.
3888
3889 The prefix ARG regulates how many top priorities from
3890each category to show, as described above."
b28872ce 3891 (interactive "P")
20166aea
SB
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))))
b28872ce
SB
3917
3918(defun todos-top-priorities-multifile (&optional arg)
20166aea
SB
3919 "Display a list of top priority items from different categories.
3920The categories are a subset of the categories in the files listed
3921in `todos-filter-files', or if this nil, in the files chosen from
3922a file selection dialog that pops up in this case.
3923
3924With numerical prefix ARG show at most ARG top priority items
3925from each category in each file. With `C-u' as prefix argument
3926show 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
3929argument, if a top priorities file for the chosen Todos files
3930exists (see `todos-save-top-priorities-buffer'), visit this file;
3931if there is no such file, do the same as with prefix argument
3932`C-u'."
b28872ce 3933 (interactive "P")
20166aea
SB
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.
3938The categories are either a subset of those in the current Todos
3939file, or else, with non-nil argument MULTIFILE, a subset of the
3940categories in the files listed in `todos-filter-files', or if
3941this nil, in the files chosen from a file selection dialog that
3942pops up in this case."
58c7641d 3943 (interactive)
20166aea
SB
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.
3958The categories are a subset of the categories in the files listed
3959in `todos-filter-files', or if this nil, in the files chosen from
3960a file selection dialog that pops up in this case."
0e89c3fc 3961 (interactive)
20166aea
SB
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.
3966The matches may be from different categories and with non-nil
3967option `todos-filter-done-items', can include not only todo items
3968but also done items, including those in Archive files.
3969
3970The categories are either a subset of those in the current Todos
3971file (and possibly in the corresponding Archive file), or else,
3972with non-nil argument MULTIFILE, a subset of the categories in
3973the files listed in `todos-filter-files', or if this nil, in the
3974files chosen from a file selection dialog that pops up in this
3975case (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.
3991The matches may be from different categories and with non-nil
3992option `todos-filter-done-items', can include not only todo items
3993but also done items, including those in Archive files.
3994
3995The categories are a subset of the categories in the files listed
3996in `todos-filter-files', or if this nil, in the files chosen from
3997a file selection dialog that pops up in this case (and possibly
3998in the corresponding Archive files)."
3999 (interactive)
4000 (todos-regexp-items t))
58c7641d 4001
bbf95285 4002;; ---------------------------------------------------------------------------
0e89c3fc 4003;;; Editing Commands
58c7641d 4004
0e89c3fc
SB
4005(defun todos-add-file ()
4006 "Name and add a new Todos file.
4007Interactively, prompt for a category and display it.
4008Noninteractively, return the name of the new file."
d04d6b95 4009 (interactive)
2a9e69d6 4010 (let ((prompt (concat "Enter name of new Todos file "
0e89c3fc 4011 "(TAB or SPC to see current names): "))
459c6e93
SB
4012 file)
4013 (setq file (todos-read-file-name prompt))
0e89c3fc
SB
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))
36341a66 4018 (todos-reevaluate-filelist-defcustoms)
0e89c3fc
SB
4019 (if (called-interactively-p)
4020 (progn
2a9e69d6
SB
4021 (set-window-buffer (selected-window)
4022 (set-buffer (find-file-noselect file)))
0e89c3fc
SB
4023 (setq todos-current-todos-file file)
4024 (todos-show))
4025 file)))
4026
b28872ce
SB
4027;;; Category editing commands
4028
a2730169
SB
4029(defun todos-add-category (&optional file cat)
4030 "Add a new category to a Todos file.
4031
4032Called interactively with prefix argument FILE, prompt for a file
4033and then for a new category to add to that file, otherwise prompt
4034just for a category to add to the current Todos file. After adding
4035the category, visit it in Todos mode.
4036
4037Non-interactively, add category CAT to file FILE; if FILE is nil,
4038add CAT to the current Todos file. After adding the category,
4039return the new category number."
4040 (interactive "P")
4041 (let (catfil file0)
bbf95285
SB
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.
a2730169
SB
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))))
0e89c3fc
SB
4074
4075(defun todos-rename-category ()
4076 "Rename current Todos category.
4077If this file has an archive containing this category, rename the
4078category 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)
58c7641d 4090 (let (buffer-read-only)
0e89c3fc
SB
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")
58c7641d 4100 nil t)
0e89c3fc 4101 (replace-match new t t nil 1)))))))
2a9e69d6 4102 (force-mode-line-update))
0e89c3fc
SB
4103 (save-excursion (todos-category-select)))
4104
4105(defun todos-delete-category (&optional arg)
4106 "Delete current Todos category provided it is empty.
4107With ARG non-nil delete the category unconditionally,
4108i.e. including all existing todo and done items."
4109 (interactive "P")
2a9e69d6
SB
4110 (let* ((file todos-current-todos-file)
4111 (cat (todos-current-category))
0e89c3fc
SB
4112 (todo (todos-get-count 'todo cat))
4113 (done (todos-get-count 'done cat))
4114 (archived (todos-get-count 'archived cat)))
2a9e69d6
SB
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"
6be04162 4129 "(see 'todos-skip-archived-categories' "
2a9e69d6
SB
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
36341a66 4150 (todos-reevaluate-filelist-defcustoms)
2a9e69d6
SB
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))
7464f422
SB
4157 (setq todos-categories (delete (assoc cat todos-categories)
4158 todos-categories))
2a9e69d6
SB
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)))))))
3f031767 4165
0e89c3fc
SB
4166(defun todos-move-category ()
4167 "Move current category to a different Todos file.
4168If current category has archived items, also move those to the
4169archive of the file moved to, creating it if it does not exist."
58c7641d 4170 (interactive)
0e89c3fc
SB
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))
616ffa8b
SB
4177 (nfile (todos-read-file-name
4178 "Choose a Todos file to move this category to: " nil t))
0e89c3fc
SB
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)
616ffa8b
SB
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)))
0e89c3fc
SB
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
11aa0eef
SB
4192 (concat "^" (regexp-quote (concat todos-category-beg cat))
4193 "$")
0e89c3fc
SB
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)
11aa0eef 4234 "\\(" (regexp-quote cat) "\\)$") nil t)
0e89c3fc
SB
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)
36341a66 4262 (todos-reevaluate-filelist-defcustoms)))
7464f422
SB
4263 (setq todos-categories (delete (assoc cat todos-categories)
4264 todos-categories))
0e89c3fc
SB
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))))
2c173503 4271
a2730169
SB
4272(defun todos-merge-category (&optional file)
4273 "Merge current category into another existing category.
18aef8a3 4274
a2730169
SB
4275With prefix argument FILE, prompt for a specific Todos file and
4276choose (with TAB completion) a category in it to merge into;
4277otherwise, choose and merge into a category in either the
4278current Todos file or a file in `todos-category-completions-files'.
4279
4280After merging, the current category's todo and done items are
4281appended to the chosen goal category's todo and done items,
4282respectively. The goal category becomes the current category,
4283and the previous current category is deleted.
18aef8a3
SB
4284
4285If both the first and goal categories also have archived items,
4286the former are merged to the latter. If only the first category
4287has archived items, the archived category is renamed to the goal
4288category."
a2730169 4289 (interactive "P")
18aef8a3 4290 (let* ((tfile todos-current-todos-file)
a2730169
SB
4291 (archive (concat (file-name-sans-extension (if file gfile tfile))
4292 ".toda"))
18aef8a3 4293 (cat (todos-current-category))
a2730169
SB
4294 (cat+file (todos-read-category "Merge into category: " 'merge file))
4295 (goal (car cat+file))
4296 (gfile (cdr cat+file))
18aef8a3
SB
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
0e89c3fc 4304 (concat "^" (regexp-quote todos-category-beg)) nil t)
18aef8a3
SB
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
11aa0eef
SB
4326 (concat "^" (regexp-quote (concat todos-category-beg goal)) "$")
4327 nil t)
18aef8a3
SB
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
11aa0eef 4358 (concat todos-category-beg cat)) "$")
18aef8a3
SB
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
11aa0eef 4365 (concat todos-category-beg goal)) "$")
18aef8a3
SB
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)))
0e89c3fc 4403 (todos-category-number goal)
18aef8a3
SB
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)))
2c173503 4410
616ffa8b
SB
4411(defun todos-set-category-priority (&optional arg)
4412 "Change priority of category at point in Todos Categories buffer.
4413
4414With ARG nil, prompt for the new priority number. Alternatively,
4415the new priority can be provided by a numerical prefix ARG.
4416Otherwise, if ARG is either of the symbols `raise' or `lower',
4417raise 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))))))
b28872ce 4464
616ffa8b
SB
4465(defun todos-raise-category-priority ()
4466 "Raise priority of category at point in Todos Categories buffer."
b28872ce 4467 (interactive)
616ffa8b 4468 (todos-set-category-priority 'raise))
b28872ce 4469
616ffa8b
SB
4470(defun todos-lower-category-priority ()
4471 "Lower priority of category at point in Todos Categories buffer."
b28872ce 4472 (interactive)
616ffa8b 4473 (todos-set-category-priority 'lower))
b28872ce
SB
4474
4475;; ---------------------------------------------------------------------------
4476;;; Item editing commands
4477
0e89c3fc
SB
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
4484bindings and convenience commands derived from this command.)
f730d273 4485
0e89c3fc
SB
4486With no (or nil) prefix argument ARG, add the item to the current
4487category; with one prefix argument (C-u), prompt for a category
4488from the current Todos file; with two prefix arguments (C-u C-u),
4489first prompt for a Todos file, then a category in that file. If
4490a non-existing category is entered, ask whether to add it to the
4491Todos file; if answered affirmatively, add the category and
4492insert the item there.
d04d6b95 4493
0e89c3fc
SB
4494When argument DIARY is non-nil, this overrides the intent of the
4495user option `todos-include-in-diary' for this item: if
4496`todos-include-in-diary' is nil, include the item in the Fancy
4497Diary display, and if it is non-nil, exclude the item from the
4498Fancy Diary display. When DIARY is nil, `todos-include-in-diary'
4499has its intended effect.
58c7641d 4500
0e89c3fc
SB
4501When the item is included in the Fancy Diary display and the
4502argument NONMARKING is non-nil, this overrides the intent of the
4503user option `todos-diary-nonmarking' for this item: if
4504`todos-diary-nonmarking' is nil, append `diary-nonmarking-symbol'
4505to the item, and if it is non-nil, omit `diary-nonmarking-symbol'.
d04d6b95 4506
0e89c3fc
SB
4507The argument DATE-TYPE determines the content of the item's
4508mandatory 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.
18aef8a3
SB
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.
0e89c3fc
SB
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').
58c7641d 4528
0e89c3fc
SB
4529With non-nil argument TIME prompt for a time string, which must
4530match `diary-time-regexp'. Typing `<return>' at the prompt
4531returns the current time, if the user option
4532`todos-always-add-time-string' is non-nil, otherwise the empty
4533string (i.e., no time string). If TIME is absent or nil, add or
4534omit the current time string according as
4535`todos-always-add-time-string' is non-nil or nil, respectively.
58c7641d 4536
0e89c3fc
SB
4537The argument REGION-OR-HERE determines the source and location of
4538the 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.
58c7641d 4558
0e89c3fc
SB
4559To facilitate using these arguments when inserting a new todo
4560item, convenience commands have been defined for all admissible
78fe7289
SB
4561combinations together with mnenomic key bindings based on on the
4562name of the arguments and their order in the command's argument
4563list: 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
4565appended to the basic insertion key (i) and keys that allow a
4566following key must be doubled when used finally. For example,
4567`iyh' will insert a new item with today's date, marked according
4568to the DIARY argument described above, and with priority
4569according to the HERE argument; while `iyy' does the same except
4570the priority is not given by HERE but by prompting."
0e89c3fc
SB
4571;; An alternative interface for customizing key
4572;; binding is also provided with the function
4573;; `todos-insertion-bindings'." ;FIXME
4574 (interactive "P")
a2730169
SB
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)
a2730169
SB
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))))))
d04d6b95 4679
fd6c6328
SB
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
0e89c3fc
SB
4691(defvar todos-date-from-calendar nil
4692 "Helper variable for setting item date from the Emacs Calendar.")
2c173503 4693
0e89c3fc
SB
4694(defun todos-set-date-from-calendar ()
4695 "Return string of date chosen from Calendar."
36341a66
SB
4696 (cond ((and (stringp todos-date-from-calendar)
4697 (string-match todos-date-pattern todos-date-from-calendar))
18aef8a3 4698 todos-date-from-calendar)
36341a66 4699 (todos-date-from-calendar
18aef8a3 4700 (let (calendar-view-diary-initially-flag)
d9f80d44
SB
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))))
18aef8a3 4710 (message "Put cursor on a date and type <return> to set it.")
36341a66 4711 ;; FIXME: is there a better way than recursive-edit?
18aef8a3 4712 (recursive-edit)
d9f80d44
SB
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)))))
d04d6b95 4724
0e89c3fc
SB
4725(defun todos-delete-item ()
4726 "Delete at least one item in this category.
ee7412e4 4727
0e89c3fc
SB
4728If there are marked items, delete all of these; otherwise, delete
4729the item at point."
4730 (interactive)
18aef8a3
SB
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? ")))))
18aef8a3
SB
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
18aef8a3 4765 (setq todos-categories-with-marks
1fcf038b 4766 (assq-delete-all cat todos-categories-with-marks)))
18aef8a3
SB
4767 (todos-update-categories-sexp)
4768 (todos-prefix-overlays)))
4769 (if ov (delete-overlay ov)))))
0e89c3fc 4770
d16da867 4771(defun todos-edit-item (&optional arg)
0e89c3fc 4772 "Edit the Todo item at point.
d16da867
SB
4773
4774With non-nil prefix argument ARG, include the item's date/time
4775header, making it also editable; otherwise, include only the item
4776content.
4777
0e89c3fc
SB
4778If the item consists of only one logical line, edit it in the
4779minibuffer; otherwise, edit it in Todos Edit mode."
d16da867 4780 (interactive "P")
0e89c3fc 4781 (when (todos-item-string)
d16da867 4782 (let* ((opoint (point))
0e89c3fc
SB
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))))
d16da867
SB
4791 (header (substring (todos-item-string) 0 item-beg))
4792 (item (if arg (todos-item-string)
4793 (substring (todos-item-string) item-beg)))
0e89c3fc 4794 (multiline (> (length (split-string item "\n")) 1))
d16da867 4795 (buffer-read-only nil))
0e89c3fc 4796 (if multiline
d16da867
SB
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))))
0e89c3fc
SB
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))))))
3f031767 4817
0e89c3fc
SB
4818(defun todos-edit-multiline-item ()
4819 "Edit current Todo item in Todos Edit mode.
4820Use of newlines invokes `todos-indent' to insure compliance with
4821the format of Diary entries."
4822 (interactive)
4823 (todos-edit-multiline t))
3f031767 4824
0e89c3fc
SB
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)
0e89c3fc
SB
4840 (message "%s" (substitute-command-keys
4841 (concat "Type \\[todos-edit-quit] to check file format "
4842 "validity and return to Todos mode.\n")))))
3f031767 4843
0e89c3fc
SB
4844(defun todos-edit-quit ()
4845 "Return from Todos Edit mode to Todos mode.
d04d6b95 4846
0e89c3fc
SB
4847If the whole file was in Todos Edit mode, check before returning
4848whether the file is still a valid Todos file and if so, also
4849recalculate the Todos categories sexp, in case changes were made
4850in the number or names of categories."
4851 (interactive)
36341a66
SB
4852 ;; FIXME: Should do todos-check-format only if file was actually changed --
4853 ;; but how to tell?
0e89c3fc 4854 (when (eq (buffer-size) (- (point-max) (point-min)))
b28872ce 4855 (when (todos-check-format) (todos-repair-categories-sexp)))
0e89c3fc
SB
4856 (kill-buffer)
4857 ;; In case next buffer is not the one holding todos-current-todos-file.
4858 (todos-show))
3f031767 4859
d16da867
SB
4860(defun todos-edit-item-header-1 (what &optional inc)
4861 "Underlying function to edit items' date/time headers.
4862
4863The argument WHAT (passed by invoking commands) specifies what
4864part 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
4867date 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
4869change the day name; and `year', `month' or `day', to edit only
4870these respective parts of the date string (`day' is the number of
4871the given day of the month, and `month' is either the name of the
4872given month or its number, depending on the value of
4873`calendar-date-display-form').
4874
4875The optional argument INC is a positive or negative integer
4876\(passed by invoking commands as a numerical prefix argument)
4877that in conjunction with the WHAT values `year', `month' or
4878`day', increments or decrements the specified date string
4879component by the specified number of suitable units, i.e., years,
4880months, or days, with automatic adjustment of the other date
4881string components as necessary.
4882
4883If there are marked items, apply the same edit to all of these;
4884otherwise, edit just the item at point."
0e89c3fc
SB
4885 (let* ((cat (todos-current-category))
4886 (marked (assoc cat todos-categories-with-marks))
d16da867 4887 (first t)
0e89c3fc 4888 (todos-date-from-calendar t)
d16da867
SB
4889 (buffer-read-only nil)
4890 ndate ntime year monthname month day
4891 dayname) ; Needed by calendar-date-display-form.
0e89c3fc
SB
4892 (save-excursion
4893 (or (and marked (goto-char (point-min))) (todos-item-start))
d16da867 4894 (catch 'end
0e89c3fc
SB
4895 (while (not (eobp))
4896 (and marked
4897 (while (not (todos-marked-item-p))
4898 (todos-forward-item)
d16da867 4899 (and (eobp) (throw 'end nil))))
0e89c3fc
SB
4900 (re-search-forward (concat todos-date-string-start "\\(?1:"
4901 todos-date-pattern
d16da867
SB
4902 "\\)\\(?2: " diary-time-regexp "\\)?"
4903 (regexp-quote todos-nondiary-end) "?")
0e89c3fc
SB
4904 (line-end-position) t)
4905 (let* ((odate (match-string-no-properties 1))
4906 (otime (match-string-no-properties 2))
d16da867
SB
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)))
0e89c3fc
SB
5041 (setq todos-date-from-calendar nil)
5042 (setq first nil))
d16da867
SB
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.
0e89c3fc
SB
5046 (if marked
5047 (todos-forward-item)
5048 (goto-char (point-max))))))))
58c7641d 5049
d16da867
SB
5050(defun todos-edit-item-header ()
5051 "Interactively edit at least the date of item's date/time header.
5052If user option `todos-always-add-time-string' is non-nil, also
5053edit item's time string."
0e89c3fc 5054 (interactive)
d16da867
SB
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))
58c7641d 5063
0e89c3fc 5064(defun todos-edit-item-date-from-calendar ()
d16da867 5065 "Interactively edit item's date using the Calendar."
0e89c3fc 5066 (interactive)
d16da867 5067 (todos-edit-item-header-1 'calendar))
58c7641d 5068
d16da867
SB
5069(defun todos-edit-item-date-to-today ()
5070 "Set item's date to today's date."
0e89c3fc 5071 (interactive)
d16da867
SB
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."
0e89c3fc 5076 (interactive)
d16da867
SB
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.
5081With prefix argument INC a positive or negative integer,
5082increment 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.
5088With prefix argument INC a positive or negative integer,
5089increment 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.
5095With prefix argument INC a positive or negative integer,
5096increment or decrement the day by INC."
5097 (interactive "p")
5098 (todos-edit-item-header-1 'day inc))
58c7641d 5099
0e89c3fc
SB
5100(defun todos-edit-item-diary-inclusion ()
5101 "Change diary status of one or more todo items in this category.
5102That is, insert `todos-nondiary-marker' if the candidate items
5103lack this marking; otherwise, remove it.
d04d6b95 5104
0e89c3fc
SB
5105If there are marked todo items, change the diary status of all
5106and only these, otherwise change the diary status of the item at
5107point."
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 "")
3af3cd0b 5129 (todos-update-count 'diary 1))
0e89c3fc
SB
5130 (when end
5131 (insert todos-nondiary-start)
5132 (goto-char (1+ end))
5133 (insert todos-nondiary-end)
3af3cd0b 5134 (todos-update-count 'diary -1)))))
0e89c3fc
SB
5135 (unless marked (throw 'stop nil))
5136 (todos-forward-item)))))
5137 (todos-update-categories-sexp)))
58c7641d 5138
0e89c3fc
SB
5139(defun todos-edit-category-diary-inclusion (arg)
5140 "Make all items in this category diary items.
5141With prefix ARG, make all items in this category non-diary
5142items."
5143 (interactive "P")
d04d6b95 5144 (save-excursion
0e89c3fc
SB
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
d04d6b95 5150 (while (not (eobp))
0e89c3fc
SB
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))
3af3cd0b 5169 (todos-update-count 'diary (if arg
0e89c3fc
SB
5170 (- diary-count)
5171 (- todo-count diary-count))))
5172 (todos-update-categories-sexp)))))
d04d6b95 5173
0e89c3fc
SB
5174(defun todos-edit-item-diary-nonmarking ()
5175 "Change non-marking of one or more diary items in this category.
5176That is, insert `diary-nonmarking-symbol' if the candidate items
5177lack this marking; otherwise, remove it.
d04d6b95 5178
0e89c3fc
SB
5179If there are marked todo items, change the non-marking status of
5180all and only these, otherwise change the non-marking status of
5181the 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)))))))
58c7641d 5200
0e89c3fc
SB
5201(defun todos-edit-category-diary-nonmarking (arg)
5202 "Add `diary-nonmarking-symbol' to all diary items in this category.
5203With prefix ARG, remove `diary-nonmarking-symbol' from all diary
5204items 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)))))))
58c7641d 5220
59ad682f
SB
5221;; FIXME: Make NOP if point isn't on a todo item (cf. todos-copy-item,
5222;; todos-move-item
616ffa8b
SB
5223(defun todos-set-item-priority (&optional item cat new arg)
5224 "Set todo ITEM's priority in CATegory and move item accordingly.
5225
5226Interactively, ITEM defaults to the item at point, CAT to the
5227current category in Todos mode, and the priority is a number
5228between 1 and the number of items in the category.
5229Non-interactively, non-nil NEW means ITEM is a new item and the
5230lowest priority is one more than the number of items in CAT.
5231
5232The new priority is set either interactively by prompt or by a
5233numerical prefix argument, or noninteractively by argument ARG,
5234whose value can be either of the symbols `raise' or `lower',
5235meaning to raise or lower the item's priority by one."
c4bf3e3d 5236 (interactive) ; Prefix arg?
616ffa8b
SB
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))
57da062d
SB
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))))
2a9e69d6
SB
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.
b28872ce 5294 (when (eq major-mode 'todos-filtered-items-mode)
616ffa8b
SB
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))
57da062d
SB
5320 (when priority
5321 (unless (= priority 1)
5322 (todos-forward-item (1- priority))))
2a9e69d6 5323 (todos-insert-with-overlays item)
616ffa8b 5324 ;; If item was marked, restore the mark.
1fcf038b
SB
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)))))))
3f031767 5329
616ffa8b
SB
5330(defun todos-raise-item-priority ()
5331 "Raise priority of current item by moving it up by one item."
0e89c3fc 5332 (interactive)
616ffa8b 5333 (todos-set-item-priority nil nil nil 'raise))
ee7412e4 5334
616ffa8b
SB
5335(defun todos-lower-item-priority ()
5336 "Lower priority of current item by moving it down by one item."
2a9e69d6 5337 (interactive)
616ffa8b 5338 (todos-set-item-priority nil nil nil 'lower))
2a9e69d6 5339
0e89c3fc 5340(defun todos-move-item (&optional file)
c4bf3e3d 5341 "Move at least one todo or done item to another category.
0e89c3fc
SB
5342If there are marked items, move all of these; otherwise, move
5343the item at point.
58c7641d 5344
a2730169
SB
5345With prefix argument FILE, prompt for a specific Todos file and
5346choose (with TAB completion) a category in it to move the item or
5347items to; otherwise, choose and move to any category in either
c4bf3e3d
SB
5348the current Todos file or one of the files in
5349`todos-category-completions-files'. If the chosen category is
5350not an existing categories, then it is created and the item(s)
5351become(s) the first entry/entries in that category.
5352
5353With moved Todo items, prompt to set the priority in the category
5354moved to (with multiple todos items, the one that had the highest
5355priority in the category moved from gets the new priority and the
5356rest of the moved todo items are inserted in sequence below it).
5357Moved done items are appended to the end of the done items
5358section in the category moved to."
a2730169 5359 (interactive "P")
57da062d
SB
5360 (let* ((cat1 (todos-current-category))
5361 (marked (assoc cat1 todos-categories-with-marks)))
c4bf3e3d
SB
5362 ;; NOP if point is not on an item and there are no marked items.
5363 (unless (and (looking-at "^$")
5364 (not marked))
57da062d
SB
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))
c4bf3e3d 5370 (done-item (and (todos-done-item-p) (concat item "\n")))
57da062d 5371 (omark (save-excursion (todos-item-start) (point-marker)))
c4bf3e3d
SB
5372 (todo 0)
5373 (diary 0)
5374 (done 0)
5375 ov cat+file cat2 file2 moved nmark todo-items done-items)
57da062d
SB
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))
a2730169
SB
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)))
57da062d
SB
5389 (if ov (delete-overlay ov)))
5390 (set-buffer (find-buffer-visiting file1))
5391 (if marked
5392 (progn
57da062d
SB
5393 (goto-char (point-min))
5394 (while (not (eobp))
5395 (when (todos-marked-item-p)
c4bf3e3d
SB
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)))))
57da062d 5405 (todos-forward-item))
c4bf3e3d
SB
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))))
57da062d 5416 (set-window-buffer (selected-window)
a2730169 5417 (set-buffer (find-file-noselect file2 'nowarn)))
fec0fdae
SB
5418 (unwind-protect
5419 (progn
c4bf3e3d
SB
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)))
fec0fdae
SB
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))
c4bf3e3d
SB
5444 (when todo (todos-update-count 'todo todo))
5445 (when diary (todos-update-count 'diary diary))
5446 (when done (todos-update-count 'done done))
fec0fdae
SB
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))
c4bf3e3d
SB
5460 (setq end (if (re-search-forward
5461 (concat "^" (regexp-quote
5462 todos-category-beg)) nil t)
5463 (match-beginning 0)
5464 (point-max)))
fec0fdae
SB
5465 (goto-char beg)
5466 (while (< (point) end)
5467 (if (todos-marked-item-p)
5468 (todos-remove-item)
5469 (todos-forward-item)))
fec0fdae
SB
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))))
c4bf3e3d
SB
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))
fec0fdae
SB
5477 (todos-update-categories-sexp))
5478 (set-window-buffer (selected-window)
a2730169 5479 (set-buffer (find-file-noselect file2 'nowarn)))
fec0fdae 5480 (setq todos-category-number (todos-category-number cat2))
c4bf3e3d
SB
5481 (let ((todos-show-with-done (or done-items done-item)))
5482 (todos-category-select))
fec0fdae
SB
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))
c4bf3e3d
SB
5487 ;; User quit before setting priority of todo item(s), so
5488 ;; return to starting category.
fec0fdae
SB
5489 (t
5490 (todos-category-number cat1)
5491 (todos-category-select)
5492 (goto-char omark))))))))
58c7641d 5493
616ffa8b
SB
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;; )
58c7641d 5502
0e89c3fc
SB
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
5508With prefix argument ARG prompt for a comment and append it to
5509the done item; this is only possible if there are no marked
5510items. 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;
5513otherwise, just tag the item at point. Items tagged as done are
5514relocated 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)
57da062d 5519 ;; Point is between todo and done items.
0e89c3fc
SB
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))
0e89c3fc
SB
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"))
3af3cd0b
SB
5563 (todos-update-count 'todo (- item-count))
5564 (todos-update-count 'done item-count)
5565 (todos-update-count 'diary (- diary-count))
0e89c3fc
SB
5566 (todos-update-categories-sexp)
5567 (save-excursion (todos-category-select))))))
5568
b28872ce
SB
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.
5571With prefix ARG delete an existing comment."
5572 (interactive "P")
0e89c3fc 5573 (when (todos-done-item-p)
47011bed
SB
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)
b28872ce
SB
5582 (if arg
5583 (when (y-or-n-p "Delete comment? ")
5584 (delete-region (match-beginning 0) (match-end 0)))
47011bed
SB
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 "]"))))))
58c7641d 5591
0e89c3fc 5592(defun todos-item-undo ()
b28872ce
SB
5593 "Restore this done item to the todo section of this category.
5594If done item has a comment, ask whether to omit the comment from
5595the restored item."
0e89c3fc 5596 (interactive)
18aef8a3
SB
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)
3160f2eb 5601 (bufmod (buffer-modified-p))
18aef8a3
SB
5602 (opoint (point))
5603 (orig-mrk (progn (todos-item-start) (point-marker)))
3160f2eb 5604 (orig-item (todos-item-string))
18aef8a3
SB
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
1a9cb339
SB
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)))
18aef8a3
SB
5635 t)
5636 (when (eq first 'omit)
5637 (delete-region (match-beginning 0) (match-end 0))
5638 (setq end (point))))
3160f2eb
SB
5639 (setq item (concat item
5640 (buffer-substring-no-properties start end)
18aef8a3
SB
5641 (when marked "\n")))
5642 (todos-remove-item)
5643 (unless marked (throw 'done nil)))
5644 (todos-forward-item))))
5645 (if marked
5646 (progn
18aef8a3
SB
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.
3160f2eb 5650 (goto-char (point-min))
18aef8a3
SB
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))
3160f2eb
SB
5658 (todos-update-categories-sexp)
5659 (let ((todos-show-with-done (> (todos-get-count 'done) 0)))
5660 (todos-category-select)))
18aef8a3
SB
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))
3160f2eb
SB
5671 (todos-update-categories-sexp)
5672 (let ((todos-show-with-done (> (todos-get-count 'done) 0)))
5673 (todos-category-select)))
18aef8a3 5674 (unless undone
18aef8a3 5675 (let ((todos-show-with-done t))
3160f2eb
SB
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)))))
58c7641d 5683
2a9e69d6 5684(defun todos-archive-done-item (&optional all)
0e89c3fc 5685 "Archive at least one done item in this category.
d04d6b95 5686
0e89c3fc
SB
5687If there are marked done items (and no marked todo items),
5688archive all of these; otherwise, with non-nil argument ALL,
5689archive all done items in this category; otherwise, archive the
5690done item at point.
d04d6b95 5691
0e89c3fc
SB
5692If the archive of this file does not exist, it is created. If
5693this category does not exist in the archive, it is created."
5694 (interactive)
2a9e69d6 5695 (when (eq major-mode 'todos-mode)
0e89c3fc
SB
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)
6be04162 5706 (get-buffer-create afile)))
0e89c3fc
SB
5707 (item (and (todos-done-item-p) (concat (todos-item-string) "\n")))
5708 (count 0)
1754db29 5709 (opoint (unless (todos-done-item-p) (point)))
0e89c3fc
SB
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))
6be04162
SB
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))))
0e89c3fc
SB
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))
36341a66 5738 all-done (buffer-substring-no-properties beg end)
1754db29
SB
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))))
0e89c3fc 5743 (throw 'end nil))))
a2730169
SB
5744 (if (not (or marked all item))
5745 (throw 'end (message "Only done items can be archived"))
0e89c3fc 5746 (with-current-buffer archive
6be04162 5747 (unless buffer-file-name (erase-buffer))
abe748f5 5748 (let (buffer-read-only)
0e89c3fc
SB
5749 (widen)
5750 (goto-char (point-min))
11aa0eef
SB
5751 (if (and (re-search-forward
5752 (concat "^" (regexp-quote
5753 (concat todos-category-beg cat)) "$")
5754 nil t)
6be04162
SB
5755 (re-search-forward (regexp-quote todos-category-done)
5756 nil t))
b28872ce
SB
5757 ;; Start of done items section in existing category.
5758 (forward-char)
a2730169 5759 (todos-add-category nil cat)
b28872ce
SB
5760 ;; Start of done items section in new category.
5761 (goto-char (point-max)))
0e89c3fc
SB
5762 (insert (cond (marked marked-items)
5763 (all all-done)
5764 (item)))
abe748f5 5765 (todos-update-count 'done (if (or marked all) count 1) cat)
0e89c3fc 5766 (todos-update-categories-sexp)
abe748f5
SB
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.
6be04162
SB
5770 (unless buffer-file-name
5771 (write-region nil nil afile)
abe748f5 5772 (kill-buffer))))
0e89c3fc 5773 (with-current-buffer tbuf
1754db29
SB
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)))
0e89c3fc
SB
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)
3af3cd0b
SB
5785 (todos-update-count 'done -1)
5786 (todos-update-count 'archived 1)
0e89c3fc
SB
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
1754db29
SB
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)))))
0e89c3fc 5802 (when marked
0e89c3fc 5803 (setq todos-categories-with-marks
abe748f5 5804 (assq-delete-all cat todos-categories-with-marks)))
0e89c3fc 5805 (todos-update-categories-sexp)
abe748f5 5806 (todos-prefix-overlays)))
6be04162
SB
5807 (find-file afile)
5808 (todos-category-number cat)
5809 (todos-category-select)
6be04162 5810 (split-window-below)
1754db29
SB
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)))))))
d04d6b95 5817
0e89c3fc
SB
5818(defun todos-archive-category-done-items ()
5819 "Move all done items in this category to its archive."
5820 (interactive)
2a9e69d6 5821 (todos-archive-done-item t))
d04d6b95 5822
0e89c3fc
SB
5823(defun todos-unarchive-items (&optional all)
5824 "Unarchive at least one item in this archive category.
d04d6b95 5825
0e89c3fc
SB
5826If there are marked items, unarchive all of these; otherwise,
5827with non-nil argument ALL, unarchive all items in this category;
5828otherwise, unarchive the item at point.
d04d6b95 5829
0e89c3fc
SB
5830Unarchived items are restored as done items to the corresponding
5831category in the Todos file, inserted at the end of done section.
5832If all items in the archive category were restored, the category
5833is deleted from the archive. If this was the only category in the
5834archive, the archive file is deleted."
5835 (interactive)
abe748f5 5836 (when (eq major-mode 'todos-archive-mode)
0e89c3fc 5837 (catch 'end
abe748f5 5838 (let* ((cat (todos-current-category))
0e89c3fc
SB
5839 (tbuf (find-file-noselect
5840 (concat (file-name-sans-extension todos-current-todos-file)
5841 ".todo") t))
0e89c3fc
SB
5842 (marked (assoc cat todos-categories-with-marks))
5843 (item (concat (todos-item-string) "\n"))
36341a66
SB
5844 (all-items (when all (buffer-substring-no-properties
5845 (point-min) (point-max))))
abe748f5
SB
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))))
0e89c3fc
SB
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
11aa0eef 5863 (concat todos-category-beg cat)) "$")
0e89c3fc 5864 nil t)
abe748f5 5865 ;; Go to end of category's done section.
0e89c3fc
SB
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)
abe748f5
SB
5872 (todos-update-count 'done marked-count cat)
5873 (todos-update-count 'archived (- marked-count) cat))
0e89c3fc 5874 (all
abe748f5
SB
5875 (insert all-items)
5876 (todos-update-count 'done all-count cat)
5877 (todos-update-count 'archived (- all-count) cat))
0e89c3fc
SB
5878 (t
5879 (insert item)
abe748f5
SB
5880 (todos-update-count 'done 1 cat)
5881 (todos-update-count 'archived -1 cat)))
0e89c3fc
SB
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)
0e89c3fc
SB
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))))
abe748f5
SB
5896 (todos-forward-item))))
5897 (todos-update-count 'done (if marked (- marked-count) -1) cat))
0e89c3fc
SB
5898 (all
5899 (remove-overlays (point-min) (point-max))
abe748f5 5900 (delete-region (point-min) (point-max))))
0e89c3fc
SB
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
11aa0eef 5912 (concat "^" (regexp-quote todos-category-beg) cat "$")
0e89c3fc
SB
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."))))))
58c7641d 5932
0e89c3fc
SB
5933(defun todos-unarchive-category ()
5934 "Unarchive all items in this category. See `todos-unarchive-items'."
5935 (interactive)
5936 (todos-unarchive-items t))
3f031767
SB
5937
5938(provide 'todos)
5939
3f031767 5940;;; todos.el ends here
58c7641d 5941
7464f422 5942;; FIXME: remove when part of Emacs
18aef8a3 5943;; ---------------------------------------------------------------------------
7464f422
SB
5944(add-to-list 'auto-mode-alist '("\\.todo\\'" . todos-mode))
5945(add-to-list 'auto-mode-alist '("\\.toda\\'" . todos-archive-mode))
20166aea 5946(add-to-list 'auto-mode-alist '("\\.todt\\'" . todos-filtered-items-mode))
7464f422
SB
5947
5948;;; Addition to calendar.el
520d912e 5949;; FIXME: autoload when key-binding is defined in calendar.el
18aef8a3 5950(defun todos-insert-item-from-calendar (&optional arg)
520d912e 5951 ""
18aef8a3
SB
5952 (interactive "P")
5953 (setq todos-date-from-calendar
5954 (calendar-date-string (calendar-cursor-to-date t) t t))
5955 (calendar-exit)
520d912e 5956 (todos-show)
18aef8a3 5957 (todos-insert-item arg nil nil todos-date-from-calendar))
520d912e 5958
18aef8a3 5959(define-key calendar-mode-map "it" 'todos-insert-item-from-calendar)
520d912e 5960
58c7641d
SB
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")))))