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