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