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