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