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