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