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