* calendar/todos.el (todos-priorities-rules): Fix customization
[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."
86ea3fbd 496 :type 'sexp
6be04162
SB
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
d16da867
SB
1339(defconst todos-month-name-array
1340 (vconcat calendar-month-name-array (vector "*"))
1341 "Array of month names, in order.
1342The final element is \"*\", indicating an unspecified month.")
1343
1344(defconst todos-month-abbrev-array
1345 (vconcat calendar-month-abbrev-array (vector "*"))
1346 "Array of abbreviated month names, in order.
1347The final element is \"*\", indicating an unspecified month.")
1348
36341a66
SB
1349(defconst todos-date-pattern
1350 (let ((dayname (diary-name-pattern calendar-day-name-array nil t)))
d16da867 1351 (concat "\\(?5:" dayname "\\|"
36341a66
SB
1352 (let ((dayname)
1353 ;; FIXME: how to choose between abbreviated and unabbreviated
1354 ;; month name?
d16da867
SB
1355 ;; (monthname (format "\\(?6:%s\\|\\*\\)"
1356 ;; (diary-name-pattern
1357 ;; calendar-month-name-array
1358 ;; calendar-month-abbrev-array)))
1359 (monthname (format "\\(?6:%s\\)" (diary-name-pattern
1360 todos-month-name-array
1361 todos-month-abbrev-array)))
1362 (month "\\(?7:[0-9]+\\|\\*\\)")
1363 (day "\\(?8:[0-9]+\\|\\*\\)")
1364 (year "-?\\(?9:[0-9]+\\|\\*\\)"))
36341a66
SB
1365 (mapconcat 'eval calendar-date-display-form ""))
1366 "\\)"))
1367 "Regular expression matching a Todos date header.")
1368
1369(defconst todos-nondiary-start (nth 0 todos-nondiary-marker)
1370 "String inserted before item date to block diary inclusion.")
1371
1372(defconst todos-nondiary-end (nth 1 todos-nondiary-marker)
1373 "String inserted after item date matching `todos-nondiary-start'.")
1374
1375;; By itself this matches anything, because of the `?'; however, it's only
1376;; used in the context of `todos-date-pattern' (but Emacs Lisp lacks
1377;; lookahead).
1378(defconst todos-date-string-start
1379 (concat "^\\(" (regexp-quote todos-nondiary-start) "\\|"
1380 (regexp-quote diary-nonmarking-symbol) "\\)?")
1381 "Regular expression matching part of item header before the date.")
1382
1383(defconst todos-done-string-start
1384 (concat "^\\[" (regexp-quote todos-done-string))
1385 "Regular expression matching start of done item.")
abe748f5 1386
36341a66 1387(defconst todos-item-start (concat "\\(" todos-date-string-start "\\|"
0e89c3fc
SB
1388 todos-done-string-start "\\)"
1389 todos-date-pattern)
1390 "String identifying start of a Todos item.")
58c7641d 1391
0e89c3fc
SB
1392(defun todos-item-start ()
1393 "Move to start of current Todos item and return its position."
abe748f5 1394 (unless (or
a820dfe8
SB
1395 ;; Buffer is empty (invocation possible e.g. via todos-forward-item
1396 ;; from todos-filter-items when processing category with no todo
1397 ;; items).
1398 (eq (point-min) (point-max))
616ffa8b 1399 ;; Point is on the empty line below category's last todo item...
abe748f5 1400 (and (looking-at "^$")
616ffa8b
SB
1401 (or (eobp) ; ...and done items are hidden...
1402 (save-excursion ; ...or done items are visible.
1403 (forward-line)
1404 (looking-at (concat "^"
1405 (regexp-quote todos-category-done))))))
abe748f5 1406 ;; Buffer is widened.
0e89c3fc
SB
1407 (looking-at (regexp-quote todos-category-beg)))
1408 (goto-char (line-beginning-position))
1409 (while (not (looking-at todos-item-start))
1410 (forward-line -1))
1411 (point)))
d04d6b95 1412
0e89c3fc
SB
1413(defun todos-item-end ()
1414 "Move to end of current Todos item and return its position."
1415 ;; Items cannot end with a blank line.
1416 (unless (looking-at "^$")
0833689a
SB
1417 (let* ((done (todos-done-item-p))
1418 (to-lim nil)
1419 ;; For todo items, end is before the done items section, for done
1420 ;; items, end is before the next category. If these limits are
1421 ;; missing or inaccessible, end it before the end of the buffer.
1422 (lim (if (save-excursion
1423 (re-search-forward
1424 (concat "^" (regexp-quote (if done
1425 todos-category-beg
1426 todos-category-done)))
1427 nil t))
1428 (progn (setq to-lim t) (match-beginning 0))
1429 (point-max))))
1430 (when (bolp) (forward-char)) ; Find start of next item.
1431 (goto-char (if (re-search-forward todos-item-start lim t)
1432 (match-beginning 0)
1433 (if to-lim lim (point-max))))
1434 ;; For last todo item, skip back over the empty line before the done
1435 ;; items section, else just back to the end of the previous line.
1436 (backward-char (when (and to-lim (not done) (eq (point) lim)) 2))
1437 (point))))
ee7412e4 1438
0e89c3fc
SB
1439(defun todos-item-string ()
1440 "Return bare text of current item as a string."
1441 (let ((opoint (point))
1442 (start (todos-item-start))
1443 (end (todos-item-end)))
1444 (goto-char opoint)
1445 (and start end (buffer-substring-no-properties start end))))
3f031767 1446
0e89c3fc
SB
1447(defun todos-remove-item ()
1448 "Internal function called in editing, deleting or moving items."
1449 (let* ((beg (todos-item-start))
1450 (end (progn (todos-item-end) (1+ (point))))
1451 (ovs (overlays-in beg beg)))
1452 ;; There can be both prefix/number and mark overlays.
1453 (while ovs (delete-overlay (car ovs)) (pop ovs))
1454 (delete-region beg end)))
ee7412e4 1455
0e89c3fc 1456(defun todos-diary-item-p ()
3af3cd0b 1457 "Return non-nil if item at point has diary entry format."
0e89c3fc 1458 (save-excursion
57da062d
SB
1459 (when (todos-item-string) ; Exclude empty lines.
1460 (todos-item-start)
1461 (not (looking-at (regexp-quote todos-nondiary-start))))))
58c7641d 1462
0e89c3fc
SB
1463(defun todos-done-item-p ()
1464 "Return non-nil if item at point is a done item."
1465 (save-excursion
1466 (todos-item-start)
1467 (looking-at todos-done-string-start)))
d04d6b95 1468
0e89c3fc
SB
1469(defvar todos-item-mark (propertize (if (equal todos-prefix "*") "@" "*")
1470 'face 'todos-mark)
1471 "String used to mark items.")
2c173503 1472
0e89c3fc 1473(defun todos-marked-item-p ()
3af3cd0b 1474 "If this item begins with `todos-item-mark', return mark overlay."
0e89c3fc
SB
1475 (let ((ovs (overlays-in (line-beginning-position) (line-beginning-position)))
1476 (mark todos-item-mark)
1477 ov marked)
1478 (catch 'stop
1479 (while ovs
1480 (setq ov (pop ovs))
1481 (and (equal (overlay-get ov 'before-string) mark)
1482 (throw 'stop (setq marked t)))))
1483 (when marked ov)))
3f031767 1484
0e89c3fc
SB
1485(defun todos-insert-with-overlays (item)
1486 "Insert ITEM at point and update prefix/priority number overlays."
1487 (todos-item-start)
1488 (insert item "\n")
1489 (todos-backward-item)
1490 (todos-prefix-overlays))
2c173503 1491
0e89c3fc
SB
1492(defun todos-prefix-overlays ()
1493 "Put before-string overlay in front of this category's items.
1494The overlay's value is the string `todos-prefix' or with non-nil
3af3cd0b
SB
1495`todos-number-priorities' an integer in the sequence from 1 to
1496the number of todo or done items in the category indicating the
0e89c3fc
SB
1497item's priority. Todo and done items are numbered independently
1498of each other."
3af3cd0b 1499 (when (or todos-number-priorities
0e89c3fc
SB
1500 (not (string-match "^[[:space:]]*$" todos-prefix)))
1501 (let ((prefix (propertize (concat todos-prefix " ")
1502 'face 'todos-prefix-string))
1503 (num 0))
1504 (save-excursion
1505 (goto-char (point-min))
1506 (while (not (eobp))
1507 (when (or (todos-date-string-matcher (line-end-position))
1508 (todos-done-string-matcher (line-end-position)))
1509 (goto-char (match-beginning 0))
3af3cd0b 1510 (when todos-number-priorities
0e89c3fc
SB
1511 (setq num (1+ num))
1512 ;; Reset number to 1 for first done item.
1513 (when (and (looking-at todos-done-string-start)
1514 (looking-back (concat "^"
1515 (regexp-quote todos-category-done)
1516 "\n")))
1517 (setq num 1))
1518 (setq prefix (propertize (concat (number-to-string num) " ")
1519 'face 'todos-prefix-string)))
1520 (let ((ovs (overlays-in (point) (point)))
1521 marked ov-pref)
1522 (if ovs
1523 (dolist (ov ovs)
1524 (let ((val (overlay-get ov 'before-string)))
1525 (if (equal val "*")
1526 (setq marked t)
1527 (setq ov-pref val)))))
1528 (unless (equal ov-pref prefix)
1529 ;; Why doesn't this work?
1530 ;; (remove-overlays (point) (point) 'before-string)
1531 (remove-overlays (point) (point))
1532 (overlay-put (make-overlay (point) (point))
1533 'before-string prefix)
1534 (and marked (overlay-put (make-overlay (point) (point))
1535 'before-string todos-item-mark)))))
1536 (forward-line))))))
2c173503 1537
abe748f5 1538;; ---------------------------------------------------------------------------
36341a66 1539;;; Helper functions for user input with prompting and completion
abe748f5 1540
0e89c3fc
SB
1541(defun todos-read-file-name (prompt &optional archive mustmatch)
1542 "Choose and return the name of a Todos file, prompting with PROMPT.
ee7412e4 1543
0e89c3fc
SB
1544Show completions with TAB or SPC; the names are shown in short
1545form but the absolute truename is returned. With non-nil ARCHIVE
1546return the absolute truename of a Todos archive file. With non-nil
1547MUSTMATCH the name of an existing file must be chosen;
1548otherwise, a new file name is allowed."
459c6e93
SB
1549 (let* ((completion-ignore-case todos-completion-ignore-case)
1550 (files (mapcar 'todos-short-file-name
1551 (if archive todos-archives todos-files)))
1552 (file (completing-read prompt files nil mustmatch nil nil
1553 (unless files
1554 ;; Trigger prompt for initial file.
1555 ""))))
1556 (unless (file-exists-p todos-files-directory)
1557 (make-directory todos-files-directory))
0e89c3fc 1558 (unless mustmatch
459c6e93
SB
1559 (setq file (todos-validate-name file 'file)))
1560 (setq file (file-truename (concat todos-files-directory file
1561 (if archive ".toda" ".todo"))))))
d04d6b95 1562
2a9e69d6 1563(defun todos-read-category (prompt &optional mustmatch added)
0e89c3fc
SB
1564 "Choose and return a category name, prompting with PROMPT.
1565Show completions with TAB or SPC. With non-nil MUSTMATCH the
1566name must be that of an existing category; otherwise, a new
2a9e69d6
SB
1567category name is allowed, after checking its validity. Non-nil
1568argument ADDED means the caller is todos-add-category, so don't
1569ask whether to add the category."
0e89c3fc
SB
1570 ;; Allow SPC to insert spaces, for adding new category names.
1571 (let ((map minibuffer-local-completion-map))
1572 (define-key map " " nil)
1573 ;; Make a copy of todos-categories in case history-delete-duplicates is
1574 ;; non-nil, which makes completing-read alter todos-categories.
7464f422 1575 (let* ((categories (copy-sequence todos-categories))
0e89c3fc
SB
1576 (history (cons 'todos-categories (1+ todos-category-number)))
1577 (completion-ignore-case todos-completion-ignore-case)
1578 (cat (completing-read prompt todos-categories nil
1579 mustmatch nil history
1580 ;; Default for existing categories is the
1581 ;; current category.
1582 (if todos-categories
1583 (todos-current-category)
459c6e93 1584 ;; Trigger prompt for initial category.
7464f422
SB
1585 ""))))
1586 (unless (or mustmatch (assoc cat todos-categories))
2a9e69d6
SB
1587 (todos-validate-name cat 'category)
1588 (unless added
0e89c3fc
SB
1589 (if (y-or-n-p (format (concat "There is no category \"%s\" in "
1590 "this file; add it? ") cat))
57da062d
SB
1591 ;; Restore point and narrowing after adding new
1592 ;; category, to avoid moving to beginning of file when
1593 ;; moving marked items to a new category (todos-move-item).
1594 (save-excursion
1595 (save-restriction
1596 (todos-add-category cat)
1597 ;; We've changed todos-categories, so we must not
1598 ;; reset it below.
1599 (setq added t)))
7464f422 1600 (keyboard-quit))))
2a9e69d6
SB
1601 ;; Restore the original value of todos-categories unless a new category
1602 ;; was added (since todos-add-category changes todos-categories).
7464f422 1603 (unless added (setq todos-categories categories))
0e89c3fc 1604 cat)))
3f031767 1605
0e89c3fc
SB
1606(defun todos-validate-name (name type)
1607 "Prompt for new NAME for TYPE until it is valid, then return it.
1608TYPE can be either a file or a category"
7464f422
SB
1609 (let ((categories todos-categories)
1610 (files (mapcar 'todos-short-file-name todos-files))
1611 prompt)
0e89c3fc
SB
1612 (while
1613 (and (cond ((string= "" name)
1614 (setq prompt
1615 (cond ((eq type 'file)
459c6e93 1616 (if todos-files
0e89c3fc
SB
1617 "Enter a non-empty file name: "
1618 ;; Empty string passed by todos-show to
1619 ;; prompt for initial Todos file.
1620 (concat "Initial file name ["
1621 todos-initial-file "]: ")))
1622 ((eq type 'category)
1623 (if todos-categories
1624 "Enter a non-empty category name: "
1625 ;; Empty string passed by todos-show to
1626 ;; prompt for initial category of a new
1627 ;; Todos file.
1628 (concat "Initial category name ["
1629 todos-initial-category "]: "))))))
1630 ((string-match "\\`\\s-+\\'" name)
1631 (setq prompt
1632 "Enter a name that does not contain only white space: "))
1633 ((and (eq type 'file) (member name todos-files))
1634 (setq prompt "Enter a non-existing file name: "))
1635 ((and (eq type 'category) (assoc name todos-categories))
1636 (setq prompt "Enter a non-existing category name: ")))
1637 (setq name (if (or (and (eq type 'file) todos-files)
2a9e69d6 1638 (and (eq type 'category) todos-categories))
7464f422
SB
1639 (completing-read prompt (cond ((eq type 'file)
1640 todos-files)
1641 ((eq type 'category)
1642 todos-categories)))
0e89c3fc 1643 ;; Offer default initial name.
7464f422
SB
1644 (completing-read prompt (if (eq type 'file)
1645 todos-files
1646 todos-categories)
1647 nil nil (if (eq type 'file)
1648 todos-initial-file
1649 todos-initial-category))))))
1650 name))
0e89c3fc
SB
1651
1652;; Adapted from calendar-read-date and calendar-date-string.
d16da867 1653(defun todos-read-date (&optional arg mo yr)
0e89c3fc 1654 "Prompt for Gregorian date and return it in the current format.
d16da867
SB
1655
1656With non-nil ARG, prompt for and return only the date component
1657specified by ARG, which can be one of these symbols:
1658`month' (prompt for name, return name or number according to
1659value of `calendar-date-display-form'), `day' of month, or
1660`year'. The value of each of these components can be `*',
1661indicating an unspecified month, day, or year.
1662
1663When ARG is `day', non-nil arguments MO and YR determine the
1664number of the last the day of the month."
1665 (let (year monthname month day
1666 dayname) ; Needed by calendar-date-display-form.
1667 ;; FIXME: year can be omitted from Diary
1668 (when (or (not arg) (eq arg 'year))
1669 (while (if (natnump year) (< year 1) (not (eq year '*)))
1670 (setq year (read-from-minibuffer
1671 "Year (>0 or RET for this year or * for any year): "
1672 nil nil t nil (number-to-string
1673 (calendar-extract-year
1674 (calendar-current-date)))))))
1675 (when (or (not arg) (eq arg 'month))
1676 (let* ((marray todos-month-name-array)
1677 (mlist (append marray nil))
1678 (mabarray todos-month-abbrev-array)
1679 (mablist (append mabarray nil))
1680 (completion-ignore-case todos-completion-ignore-case))
1681 (setq monthname (completing-read
1682 "Month name (RET for current month, * for any month): "
1683 ;; (mapcar 'list (append marray nil))
1684 mlist nil t nil nil
1685 (calendar-month-name (calendar-extract-month
1686 (calendar-current-date)) t))
1687 ;; month (cdr (assoc-string
1688 ;; monthname (calendar-make-alist marray nil nil
1689 ;; abbrevs))))))
1690 month (1+ (- (length mlist)
1691 (length (or (member monthname mlist)
1692 (member monthname mablist))))))
1693 ;; FIXME: We follow diary-insert-entry in using abbreviated
1694 ;; month name (and no day name) in date string. Should this
1695 ;; be customizable?
1696 (setq monthname (aref mabarray (1- month)))))
1697 (when (or (not arg) (eq arg 'day))
1698 (let ((last (let ((mm (or month mo))
1699 (yy (or year yr)))
1700 ;; If month is unspecified, use a month with 31
1701 ;; days for checking day of month input. Does
1702 ;; Calendar do anything special when * is
1703 ;; currently a shorter month?
1704 (if (= mm 13) (setq mm 1))
1705 ;; If year is unspecified, use a leap year to
1706 ;; allow Feb. 29.
1707 (if (eq year '*) (setq yy 2012))
1708 (calendar-last-day-of-month mm yy))))
1709 (while (if (natnump day) (or (< day 1) (> day last)) (not (eq day '*)))
1710 (setq day (read-from-minibuffer
1711 (format "Day (1-%d or RET for today or * for any day): "
1712 last)
1713 nil nil t nil (number-to-string
1714 (calendar-extract-day
1715 (calendar-current-date))))))))
1716 ;; Stringify read values (monthname is already a string).
1717 (and year (setq year (if (eq year '*)
1718 (symbol-name '*)
1719 (number-to-string year))))
1720 (and day (setq day (if (eq day '*)
1721 (symbol-name '*)
1722 (number-to-string day))))
1723 (and month (setq month (if (eq month '*)
1724 (symbol-name '*)
1725 (number-to-string month))))
1726 (if arg
1727 (cond ((eq arg 'year) year)
1728 ((eq arg 'day) day)
1729 ((eq arg 'month)
1730 (if (memq 'month calendar-date-display-form)
1731 month
1732 monthname)))
1733 (mapconcat 'eval calendar-date-display-form ""))))
2c173503 1734
0e89c3fc
SB
1735(defun todos-read-dayname ()
1736 "Choose name of a day of the week with completion and return it."
1737 (let ((completion-ignore-case todos-completion-ignore-case))
1738 (completing-read "Enter a day name: "
1739 (append calendar-day-name-array nil)
1740 nil t)))
1741
1742(defun todos-read-time ()
1743 "Prompt for and return a valid clock time as a string.
58c7641d 1744
0e89c3fc
SB
1745Valid time strings are those matching `diary-time-regexp'.
1746Typing `<return>' at the prompt returns the current time, if the
1747user option `todos-always-add-time-string' is non-nil, otherwise
1748the empty string (i.e., no time string)."
1749 (let (valid answer)
1750 (while (not valid)
1751 (setq answer (read-string "Enter a clock time: " nil nil
1752 (when todos-always-add-time-string
1753 (substring (current-time-string) 11 16))))
1754 (when (or (string= "" answer)
1755 (string-match diary-time-regexp answer))
1756 (setq valid t)))
1757 answer))
58c7641d 1758
0e89c3fc 1759;; ---------------------------------------------------------------------------
36341a66 1760;;; Item filtering infrastructure
2c173503 1761
a820dfe8
SB
1762(defvar todos-multiple-filter-files nil
1763 "List of files selected from `todos-multiple-filter-files' widget.")
58c7641d 1764
a820dfe8
SB
1765(defvar todos-multiple-filter-files-widget nil
1766 "Variable holding widget created by `todos-multiple-filter-files'.")
58c7641d 1767
a820dfe8 1768(defun todos-multiple-filter-files ()
0e89c3fc
SB
1769 "Pop to a buffer with a widget for choosing multiple filter files."
1770 (require 'widget)
1771 (eval-when-compile
1772 (require 'wid-edit))
520d912e
SB
1773 (with-current-buffer (get-buffer-create "*Todos Filter Files*")
1774 (pop-to-buffer (current-buffer))
1775 (erase-buffer)
1776 (kill-all-local-variables)
1777 (widget-insert "Select files for generating the top priorities list.\n\n")
a820dfe8 1778 (setq todos-multiple-filter-files-widget
520d912e
SB
1779 (widget-create
1780 `(set ,@(mapcar (lambda (x) (list 'const x))
1781 (mapcar 'todos-short-file-name
1782 (funcall todos-files-function))))))
1783 (widget-insert "\n")
1784 (widget-create 'push-button
1785 :notify (lambda (widget &rest ignore)
a820dfe8 1786 (setq todos-multiple-filter-files 'quit)
520d912e
SB
1787 (quit-window t)
1788 (exit-recursive-edit))
1789 "Cancel")
1790 (widget-insert " ")
1791 (widget-create 'push-button
1792 :notify (lambda (&rest ignore)
a820dfe8 1793 (setq todos-multiple-filter-files
520d912e
SB
1794 (mapcar (lambda (f)
1795 (concat todos-files-directory
1796 f ".todo"))
1797 (widget-value
a820dfe8 1798 todos-multiple-filter-files-widget)))
520d912e
SB
1799 (quit-window t)
1800 (exit-recursive-edit))
1801 "Apply")
1802 (use-local-map widget-keymap)
1803 (widget-setup))
0e89c3fc
SB
1804 (message "Click \"Apply\" after selecting files.")
1805 (recursive-edit))
1806
0e89c3fc
SB
1807(defun todos-filter-items (filter &optional multifile)
1808 "Build and display a list of items from different categories.
1809
1810The items are selected according to the value of FILTER, which
1811can be `top' for top priority items, `diary' for diary items,
1812`regexp' for items matching a regular expresion entered by the
520d912e
SB
1813user, or a cons cell of one of these symbols and a number set by
1814the calling command, which overrides `todos-show-priorities'.
0e89c3fc
SB
1815
1816With non-nil argument MULTIFILE list top priorities of multiple
1817Todos files, by default those in `todos-filter-files'."
58c7641d 1818 (let ((num (if (consp filter) (cdr filter) todos-show-priorities))
b28872ce 1819 (buf (get-buffer-create todos-filtered-items-buffer))
d04d6b95 1820 (files (list todos-current-todos-file))
58c7641d 1821 regexp fname bufstr cat beg end done)
0e89c3fc 1822 (when multifile
a820dfe8 1823 (setq files (or todos-multiple-filter-files ; Passed from todos-*-multifile.
520d912e
SB
1824 (if (or (consp filter)
1825 (null todos-filter-files))
a820dfe8
SB
1826 (progn (todos-multiple-filter-files)
1827 todos-multiple-filter-files)
520d912e 1828 todos-filter-files))
a820dfe8 1829 todos-multiple-filter-files nil))
0e89c3fc
SB
1830 (if (eq files 'quit) (keyboard-quit))
1831 (if (null files)
1832 (error "No files have been chosen for filtering")
1833 (with-current-buffer buf
1834 (erase-buffer)
1835 (kill-all-local-variables)
b28872ce 1836 (todos-filtered-items-mode))
0e89c3fc
SB
1837 (when (eq filter 'regexp)
1838 (setq regexp (read-string "Enter a regular expression: ")))
1839 (save-current-buffer
1840 (dolist (f files)
1841 ;; Before inserting file contents into temp buffer, save a modified
1842 ;; buffer visiting it.
1843 (let ((bf (find-buffer-visiting f)))
1844 (when (buffer-modified-p bf)
1845 (with-current-buffer bf (save-buffer))))
1846 (setq fname (todos-short-file-name f))
1847 (with-temp-buffer
520d912e
SB
1848 (when (and todos-filter-done-items (eq filter 'regexp))
1849 ;; If there is a corresponding archive file for the Todos file,
1850 ;; insert it first and add identifiers for todos-jump-to-item.
1851 (let ((arch (concat (file-name-sans-extension f) ".toda")))
1852 (when (file-exists-p arch)
1853 (insert-file-contents arch)
1854 ;; Delete Todos archive file categories sexp.
1855 (delete-region (line-beginning-position)
1856 (1+ (line-end-position)))
1857 (save-excursion
1858 (while (not (eobp))
1859 (when (re-search-forward
1860 (concat (if todos-filter-done-items
1861 (concat "\\(?:" todos-done-string-start
1862 "\\|" todos-date-string-start
1863 "\\)")
1864 todos-date-string-start)
1865 todos-date-pattern "\\(?: "
1866 diary-time-regexp "\\)?"
1867 (if todos-filter-done-items
1868 "\\]"
1869 (regexp-quote todos-nondiary-end)) "?")
1870 nil t)
1871 (insert "(archive) "))
1872 (forward-line))))))
0e89c3fc 1873 (insert-file-contents f)
520d912e
SB
1874 ;; Delete Todos file categories sexp.
1875 (delete-region (line-beginning-position) (1+ (line-end-position)))
0e89c3fc
SB
1876 (let (fnum)
1877 ;; Unless the number of items to show was supplied by prefix
a820dfe8
SB
1878 ;; argument of caller, the file-wide value from
1879 ;; `todos-priorities-rules', if non-nil, overrides
1880 ;; `todos-show-priorities'.
0e89c3fc
SB
1881 (unless (consp filter)
1882 (setq fnum (nth 1 (assoc f todos-priorities-rules))))
0e89c3fc
SB
1883 (while (re-search-forward
1884 (concat "^" (regexp-quote todos-category-beg) "\\(.+\\)\n")
1885 nil t)
1886 (setq cat (match-string 1))
1887 (let (cnum)
1888 ;; Unless the number of items to show was supplied by prefix
a820dfe8
SB
1889 ;; argument of caller, the category-wide value from
1890 ;; `todos-priorities-rules', if non-nil, overrides a non-nil
1891 ;; file-wide value from `todos-priorities-rules' as well as
1892 ;; `todos-show-priorities'.
0e89c3fc
SB
1893 (unless (consp filter)
1894 (let ((cats (nth 2 (assoc f todos-priorities-rules))))
a820dfe8 1895 (setq cnum (or (cdr (assoc cat cats)) fnum))))
0e89c3fc 1896 (delete-region (match-beginning 0) (match-end 0))
520d912e 1897 (setq beg (point)) ; First item in the current category.
0e89c3fc
SB
1898 (setq end (if (re-search-forward
1899 (concat "^" (regexp-quote todos-category-beg))
1900 nil t)
1901 (match-beginning 0)
1902 (point-max)))
1903 (goto-char beg)
1904 (setq done
1905 (if (re-search-forward
1906 (concat "\n" (regexp-quote todos-category-done))
1907 end t)
1908 (match-beginning 0)
1909 end))
520d912e
SB
1910 (unless (and todos-filter-done-items (eq filter 'regexp))
1911 ;; Leave done items.
0e89c3fc
SB
1912 (delete-region done end)
1913 (setq end done))
520d912e 1914 (narrow-to-region beg end) ; Process only current category.
0e89c3fc
SB
1915 (goto-char (point-min))
1916 ;; Apply the filter.
1917 (cond ((eq filter 'diary)
1918 (while (not (eobp))
1919 (if (looking-at (regexp-quote todos-nondiary-start))
1920 (todos-remove-item)
1921 (todos-forward-item))))
1922 ((eq filter 'regexp)
1923 (while (not (eobp))
1924 (if (looking-at todos-item-start)
1925 (if (string-match regexp (todos-item-string))
1926 (todos-forward-item)
1927 (todos-remove-item))
1928 ;; Kill lines that aren't part of a todo or done
1929 ;; item (empty or todos-category-done).
1930 (delete-region (line-beginning-position)
1931 (1+ (line-end-position))))
1932 ;; If last todo item in file matches regexp and
1933 ;; there are no following done items,
1934 ;; todos-category-done string is left dangling,
1935 ;; because todos-forward-item jumps over it.
520d912e
SB
1936 (if (and (eobp)
1937 (looking-back
1938 (concat (regexp-quote todos-done-string)
1939 "\n")))
0e89c3fc
SB
1940 (delete-region (point) (progn
1941 (forward-line -2)
1942 (point))))))
0e89c3fc
SB
1943 (t ; Filter top priority items.
1944 (setq num (or cnum fnum num))
1945 (unless (zerop num)
1946 (todos-forward-item num))))
1947 (setq beg (point))
520d912e
SB
1948 ;; Delete non-top-priority items.
1949 (unless (member filter '(diary regexp))
0e89c3fc
SB
1950 (delete-region beg end))
1951 (goto-char (point-min))
1952 ;; Add file (if using multiple files) and category tags to
1953 ;; item.
1954 (while (not (eobp))
1955 (when (re-search-forward
520d912e
SB
1956 (concat (if todos-filter-done-items
1957 (concat "\\(?:" todos-done-string-start
1958 "\\|" todos-date-string-start
1959 "\\)")
1960 todos-date-string-start)
1961 todos-date-pattern "\\(?: " diary-time-regexp
1962 "\\)?" (if todos-filter-done-items
1963 "\\]"
1964 (regexp-quote todos-nondiary-end))
1965 "?")
0e89c3fc 1966 nil t)
520d912e
SB
1967 (insert " [")
1968 (when (looking-at "(archive) ") (goto-char (match-end 0)))
1969 (insert (if multifile (concat fname ":") "") cat "]"))
0e89c3fc
SB
1970 (forward-line))
1971 (widen)))
1972 (setq bufstr (buffer-string))
1973 (with-current-buffer buf
1974 (let (buffer-read-only)
1975 (insert bufstr)))))))
0e89c3fc
SB
1976 (set-window-buffer (selected-window) (set-buffer buf))
1977 (todos-prefix-overlays)
520d912e 1978 (goto-char (point-min)))))
0e89c3fc
SB
1979
1980(defun todos-set-top-priorities (&optional arg)
1981 "Set number of top priorities shown by `todos-top-priorities'.
1982With non-nil ARG, set the number only for the current Todos
1983category; otherwise, set the number for all categories in the
1984current Todos file.
1985
1986Calling this function via either of the commands
1987`todos-set-top-priorities-in-file' or
1988`todos-set-top-priorities-in-category' is the recommended way to
1989set the user customizable option `todos-priorities-rules'."
1990 (let* ((cat (todos-current-category))
1991 (file todos-current-todos-file)
1992 (rules todos-priorities-rules)
1993 (frule (assoc-string file rules))
1994 (crule (assoc-string cat (nth 2 frule)))
86ea3fbd 1995 (crules (nth 2 frule))
0e89c3fc
SB
1996 (cur (or (if arg (cdr crule) (nth 1 frule))
1997 todos-show-priorities))
86ea3fbd
SB
1998 (prompt (if arg (concat "Number of top priorities in this category"
1999 " (currently %d): ")
2000 (concat "Default number of top priorities per category"
2001 " in this file (currently %d): ")))
2002 (new -1)
0e89c3fc 2003 nrule)
86ea3fbd 2004 (while (< new 0)
0e89c3fc 2005 (let ((cur0 cur))
86ea3fbd 2006 (setq new (read-number (format prompt cur0))
0e89c3fc
SB
2007 prompt "Enter a non-negative number: "
2008 cur0 nil)))
0e89c3fc 2009 (setq nrule (if arg
86ea3fbd
SB
2010 (append (delete crule crules) (list (cons cat new)))
2011 (append (list file new) (list crules))))
0e89c3fc
SB
2012 (setq rules (cons (if arg
2013 (list file cur nrule)
2014 nrule)
2015 (delete frule rules)))
2016 (customize-save-variable 'todos-priorities-rules rules)))
2c173503 2017
b28872ce
SB
2018(defun todos-filtered-buffer-name (buffer-type file-list)
2019 "Rename Todos filtered buffer using BUFFER-TYPE and FILE-LIST.
6be04162
SB
2020
2021The new name is constructed from the string BUFFER-TYPE, which
2022refers to one of the top priorities, diary or regexp item
2023filters, and the names of the filtered files in FILE-LIST. Used
2024in Todos Filter Items mode."
2025 (let* ((flist (if (listp file-list) file-list (list file-list)))
2026 (multi (> (length flist) 1))
2027 (fnames (mapconcat (lambda (f) (todos-short-file-name f))
2028 flist ", ")))
2029 (rename-buffer (format (concat "%s for file" (if multi "s" "")
2030 " \"%s\"") buffer-type fnames))))
d04d6b95 2031
0e89c3fc
SB
2032;; ---------------------------------------------------------------------------
2033;;; Sorting and display routines for Todos Categories mode.
58c7641d 2034
0e89c3fc
SB
2035(defun todos-longest-category-name-length (categories)
2036 "Return the length of the longest name in list CATEGORIES."
2037 (let ((longest 0))
2038 (dolist (c categories longest)
2039 (setq longest (max longest (length c))))))
58c7641d 2040
0e89c3fc
SB
2041(defun todos-padded-string (str)
2042 "Return string STR padded with spaces.
2043The placement of the padding is determined by the value of user
2044option `todos-categories-align'."
2045 (let* ((categories (mapcar 'car todos-categories))
2046 (len (max (todos-longest-category-name-length categories)
2047 (length todos-categories-category-label)))
2048 (strlen (length str))
2049 (strlen-odd (eq (logand strlen 1) 1)) ; oddp from cl.el
2050 (padding (max 0 (/ (- len strlen) 2)))
2051 (padding-left (cond ((eq todos-categories-align 'left) 0)
2052 ((eq todos-categories-align 'center) padding)
2053 ((eq todos-categories-align 'right)
2054 (if strlen-odd (1+ (* padding 2)) (* padding 2)))))
2055 (padding-right (cond ((eq todos-categories-align 'left)
2056 (if strlen-odd (1+ (* padding 2)) (* padding 2)))
2057 ((eq todos-categories-align 'center)
2058 (if strlen-odd (1+ padding) padding))
2059 ((eq todos-categories-align 'right) 0))))
2060 (concat (make-string padding-left 32) str (make-string padding-right 32))))
58c7641d 2061
0e89c3fc
SB
2062(defvar todos-descending-counts nil
2063 "List of keys for category counts sorted in descending order.")
58c7641d 2064
0e89c3fc
SB
2065(defun todos-sort (list &optional key)
2066 "Return a copy of LIST, possibly sorted according to KEY."
2067 (let* ((l (copy-sequence list))
2068 (fn (if (eq key 'alpha)
2069 (lambda (x) (upcase x)) ; Alphabetize case insensitively.
2070 (lambda (x) (todos-get-count key x))))
a820dfe8
SB
2071 ;; Keep track of whether the last sort by key was descending or
2072 ;; ascending.
0e89c3fc
SB
2073 (descending (member key todos-descending-counts))
2074 (cmp (if (eq key 'alpha)
2075 'string<
2076 (if descending '< '>)))
2077 (pred (lambda (s1 s2) (let ((t1 (funcall fn (car s1)))
2078 (t2 (funcall fn (car s2))))
2079 (funcall cmp t1 t2)))))
2080 (when key
2081 (setq l (sort l pred))
a820dfe8 2082 ;; Switch between descending and ascending sort order.
0e89c3fc
SB
2083 (if descending
2084 (setq todos-descending-counts
2085 (delete key todos-descending-counts))
2086 (push key todos-descending-counts)))
2087 l))
58c7641d 2088
0e89c3fc
SB
2089(defun todos-display-sorted (type)
2090 "Keep point on the TYPE count sorting button just clicked."
2091 (let ((opoint (point)))
2092 (todos-update-categories-display type)
2093 (goto-char opoint)))
d04d6b95 2094
0e89c3fc
SB
2095(defun todos-label-to-key (label)
2096 "Return symbol for sort key associated with LABEL."
2097 (let (key)
2098 (cond ((string= label todos-categories-category-label)
2099 (setq key 'alpha))
2100 ((string= label todos-categories-todo-label)
2101 (setq key 'todo))
2102 ((string= label todos-categories-diary-label)
2103 (setq key 'diary))
2104 ((string= label todos-categories-done-label)
2105 (setq key 'done))
2106 ((string= label todos-categories-archived-label)
2107 (setq key 'archived)))
2108 key))
ee7412e4 2109
0e89c3fc
SB
2110(defun todos-insert-sort-button (label)
2111 "Insert button for displaying categories sorted by item counts.
2112LABEL determines which type of count is sorted."
2113 (setq str (if (string= label todos-categories-category-label)
2114 (todos-padded-string label)
2115 label))
2116 (setq beg (point))
2117 (setq end (+ beg (length str)))
2118 (insert-button str 'face nil
2119 'action
2120 `(lambda (button)
2121 (let ((key (todos-label-to-key ,label)))
2122 (if (and (member key todos-descending-counts)
2123 (eq key 'alpha))
2124 (progn
2125 ;; If display is alphabetical, switch back to
a820dfe8 2126 ;; category priority order.
0e89c3fc
SB
2127 (todos-display-sorted nil)
2128 (setq todos-descending-counts
2129 (delete key todos-descending-counts)))
2130 (todos-display-sorted key)))))
2131 (setq ovl (make-overlay beg end))
2132 (overlay-put ovl 'face 'todos-button))
ee7412e4 2133
0e89c3fc
SB
2134(defun todos-total-item-counts ()
2135 "Return a list of total item counts for the current file."
2136 (mapcar (lambda (i) (apply '+ (mapcar (lambda (l) (aref l i))
2137 (mapcar 'cdr todos-categories))))
2138 (list 0 1 2 3)))
ee7412e4 2139
7464f422
SB
2140(defvar todos-categories-category-number 0
2141 "Variable for numbering categories in Todos Categories mode.")
459c6e93 2142
0e89c3fc 2143(defun todos-insert-category-line (cat &optional nonum)
459c6e93 2144 "Insert button with category CAT's name and item counts.
0e89c3fc
SB
2145With non-nil argument NONUM show only these; otherwise, insert a
2146number in front of the button indicating the category's priority.
2147The number and the category name are separated by the string
2148which is the value of the user option
2149`todos-categories-number-separator'."
459c6e93 2150 (let ((archive (member todos-current-todos-file todos-archives))
7464f422 2151 (num todos-categories-category-number)
0e89c3fc
SB
2152 (str (todos-padded-string cat))
2153 (opoint (point)))
7464f422 2154 (setq num (1+ num) todos-categories-category-number num)
0e89c3fc
SB
2155 (insert-button
2156 (concat (if nonum
2157 (make-string (+ 4 (length todos-categories-number-separator))
2158 32)
2159 (format " %3d%s" num todos-categories-number-separator))
2160 str
2161 (mapconcat (lambda (elt)
2162 (concat
2163 (make-string (1+ (/ (length (car elt)) 2)) 32) ; label
2164 (format "%3d" (todos-get-count (cdr elt) cat)) ; count
2165 ;; Add an extra space if label length is odd
2166 ;; (using def of oddp from cl.el).
2167 (if (eq (logand (length (car elt)) 1) 1) " ")))
2168 (if archive
2169 (list (cons todos-categories-done-label 'done))
2170 (list (cons todos-categories-todo-label 'todo)
2171 (cons todos-categories-diary-label 'diary)
2172 (cons todos-categories-done-label 'done)
2173 (cons todos-categories-archived-label
2174 'archived)))
a820dfe8
SB
2175 "")
2176 " ") ; So highlighting of last column is consistent with the others.
6be04162 2177 'face (if (and todos-skip-archived-categories
0e89c3fc
SB
2178 (zerop (todos-get-count 'todo cat))
2179 (zerop (todos-get-count 'done cat))
2180 (not (zerop (todos-get-count 'archived cat))))
2181 'todos-archived-only
2182 nil)
2183 'action `(lambda (button) (let ((buf (current-buffer)))
2184 (todos-jump-to-category ,cat)
2185 (kill-buffer buf))))
2186 ;; Highlight the sorted count column.
a820dfe8 2187 (let* ((beg (+ opoint 7 (length str)))
0e89c3fc
SB
2188 end ovl)
2189 (cond ((eq nonum 'todo)
2190 (setq beg (+ beg 1 (/ (length todos-categories-todo-label) 2))))
2191 ((eq nonum 'diary)
2192 (setq beg (+ beg 1 (length todos-categories-todo-label)
2193 2 (/ (length todos-categories-diary-label) 2))))
2194 ((eq nonum 'done)
2195 (setq beg (+ beg 1 (length todos-categories-todo-label)
2196 2 (length todos-categories-diary-label)
2197 2 (/ (length todos-categories-done-label) 2))))
2198 ((eq nonum 'archived)
2199 (setq beg (+ beg 1 (length todos-categories-todo-label)
2200 2 (length todos-categories-diary-label)
2201 2 (length todos-categories-done-label)
2202 2 (/ (length todos-categories-archived-label) 2)))))
a820dfe8 2203 (unless (= beg (+ opoint 7 (length str))) ; Don't highlight categories.
0e89c3fc
SB
2204 (setq end (+ beg 4))
2205 (setq ovl (make-overlay beg end))
2206 (overlay-put ovl 'face 'todos-sorted-column)))
2207 (newline)))
d04d6b95 2208
0e89c3fc
SB
2209(defun todos-display-categories-1 ()
2210 "Prepare buffer for displaying table of categories and item counts."
2211 (unless (eq major-mode 'todos-categories-mode)
2212 (setq todos-global-current-todos-file (or todos-current-todos-file
2213 todos-default-todos-file))
2214 (set-window-buffer (selected-window)
2215 (set-buffer (get-buffer-create todos-categories-buffer)))
2216 (kill-all-local-variables)
2217 (todos-categories-mode)
6be04162
SB
2218 (let ((archive (member todos-current-todos-file todos-archives))
2219 buffer-read-only)
0e89c3fc
SB
2220 (erase-buffer)
2221 ;; FIXME: add usage tips?
6be04162
SB
2222 (insert (format (concat "Category counts for Todos "
2223 (if archive "archive" "file")
2224 " \"%s\".")
0e89c3fc
SB
2225 (todos-short-file-name todos-current-todos-file)))
2226 (newline 2)
2227 ;; Make space for the column of category numbers.
2228 (insert (make-string (+ 4 (length todos-categories-number-separator)) 32))
2229 ;; Add the category and item count buttons (if this is the list of
2230 ;; categories in an archive, show only done item counts).
2231 (todos-insert-sort-button todos-categories-category-label)
6be04162
SB
2232 (if archive
2233 (progn
2234 (insert (make-string 3 32))
2235 (todos-insert-sort-button todos-categories-done-label))
0e89c3fc
SB
2236 (insert (make-string 3 32))
2237 (todos-insert-sort-button todos-categories-todo-label)
2238 (insert (make-string 2 32))
2239 (todos-insert-sort-button todos-categories-diary-label)
2240 (insert (make-string 2 32))
2241 (todos-insert-sort-button todos-categories-done-label)
2242 (insert (make-string 2 32))
2243 (todos-insert-sort-button todos-categories-archived-label))
2244 (newline 2))))
2245
2246(defun todos-update-categories-display (sortkey)
2247 ""
7464f422 2248 (let* ((cats0 todos-categories)
459c6e93
SB
2249 (cats (todos-sort cats0 sortkey))
2250 (archive (member todos-current-todos-file todos-archives))
7464f422 2251 (todos-categories-category-number 0)
459c6e93
SB
2252 ;; Find start of Category button if we just entered Todos Categories
2253 ;; mode.
2254 (pt (if (eq (point) (point-max))
2255 (save-excursion
2256 (forward-line -2)
2257 (goto-char (next-single-char-property-change
2258 (point) 'face nil (line-end-position))))))
2259 (buffer-read-only))
2260 (forward-line 2)
2261 (delete-region (point) (point-max))
2262 ;; Fill in the table with buttonized lines, each showing a category and
2263 ;; its item counts.
2264 (mapc (lambda (cat) (todos-insert-category-line cat sortkey))
2265 (mapcar 'car cats))
2266 (newline)
2267 ;; Add a line showing item count totals.
2268 (insert (make-string (+ 4 (length todos-categories-number-separator)) 32)
2269 (todos-padded-string todos-categories-totals-label)
2270 (mapconcat
2271 (lambda (elt)
2272 (concat
2273 (make-string (1+ (/ (length (car elt)) 2)) 32)
2274 (format "%3d" (nth (cdr elt) (todos-total-item-counts)))
2275 ;; Add an extra space if label length is odd (using
2276 ;; definition of oddp from cl.el).
2277 (if (eq (logand (length (car elt)) 1) 1) " ")))
2278 (if archive
2279 (list (cons todos-categories-done-label 2))
2280 (list (cons todos-categories-todo-label 0)
2281 (cons todos-categories-diary-label 1)
2282 (cons todos-categories-done-label 2)
2283 (cons todos-categories-archived-label 3)))
2284 ""))
2285 ;; Put cursor on Category button initially.
2286 (if pt (goto-char pt))
2287 (setq buffer-read-only t)))
ee7412e4 2288
0e89c3fc 2289;; ---------------------------------------------------------------------------
6be04162 2290;;; Routines for generating Todos insertion commands and key bindings
ee7412e4 2291
0e89c3fc 2292;; Can either of these be included in Emacs? The originals are GFDL'd.
7464f422 2293
0e89c3fc
SB
2294;; Slightly reformulated from
2295;; http://rosettacode.org/wiki/Power_set#Common_Lisp.
2296(defun powerset-recursive (l)
2297 (cond ((null l)
2298 (list nil))
2299 (t
520d912e
SB
2300 (let ((prev (powerset-recursive (cdr l))))
2301 (append (mapcar (lambda (elt) (cons (car l) elt))
2302 prev)
0e89c3fc 2303 prev)))))
7464f422 2304
0e89c3fc
SB
2305;; Elisp implementation of http://rosettacode.org/wiki/Power_set#C
2306(defun powerset-bitwise (l)
2307 (let ((binnum (lsh 1 (length l)))
2308 pset elt)
2309 (dotimes (i binnum)
2310 (let ((bits i)
2311 (ll l))
2312 (while (not (zerop bits))
2313 (let ((arg (pop ll)))
2314 (unless (zerop (logand bits 1))
2315 (setq elt (append elt (list arg))))
2316 (setq bits (lsh bits -1))))
2317 (setq pset (append pset (list elt)))
2318 (setq elt nil)))
2319 pset))
2320
2321;; (defalias 'todos-powerset 'powerset-recursive)
2322(defalias 'todos-powerset 'powerset-bitwise)
ee7412e4 2323
0e89c3fc
SB
2324;; Return list of lists of non-nil atoms produced from ARGLIST. The elements
2325;; of ARGLIST may be atoms or lists.
2326(defun todos-gen-arglists (arglist)
2327 (let (arglists)
2328 (while arglist
2329 (let ((arg (pop arglist)))
2330 (cond ((symbolp arg)
2331 (setq arglists (if arglists
2332 (mapcar (lambda (l) (push arg l)) arglists)
2333 (list (push arg arglists)))))
2334 ((listp arg)
2335 (setq arglists
2336 (mapcar (lambda (a)
2337 (if (= 1 (length arglists))
2338 (apply (lambda (l) (push a l)) arglists)
2339 (mapcar (lambda (l) (push a l)) arglists)))
2340 arg))))))
2341 (setq arglists (mapcar 'reverse (apply 'append (mapc 'car arglists))))))
d04d6b95 2342
0e89c3fc
SB
2343(defvar todos-insertion-commands-args-genlist
2344 '(diary nonmarking (calendar date dayname) time (here region))
2345 "Generator list for argument lists of Todos insertion commands.")
ee7412e4 2346
0e89c3fc
SB
2347(defvar todos-insertion-commands-args
2348 (let ((argslist (todos-gen-arglists todos-insertion-commands-args-genlist))
2349 res new)
2350 (setq res (remove-duplicates
2351 (apply 'append (mapcar 'todos-powerset argslist)) :test 'equal))
2352 (dolist (l res)
2353 (unless (= 5 (length l))
2354 (let ((v (make-vector 5 nil)) elt)
2355 (while l
2356 (setq elt (pop l))
2357 (cond ((eq elt 'diary)
2358 (aset v 0 elt))
2359 ((eq elt 'nonmarking)
2360 (aset v 1 elt))
2361 ((or (eq elt 'calendar)
2362 (eq elt 'date)
2363 (eq elt 'dayname))
2364 (aset v 2 elt))
2365 ((eq elt 'time)
2366 (aset v 3 elt))
2367 ((or (eq elt 'here)
2368 (eq elt 'region))
2369 (aset v 4 elt))))
2370 (setq l (append v nil))))
2371 (setq new (append new (list l))))
2372 new)
2373 "List of all argument lists for Todos insertion commands.")
3f031767 2374
0e89c3fc
SB
2375(defun todos-insertion-command-name (arglist)
2376 "Generate Todos insertion command name from ARGLIST."
2377 (replace-regexp-in-string
2378 "-\\_>" ""
2379 (replace-regexp-in-string
2380 "-+" "-"
59ad682f 2381 ;; FIXME: "todos-insert-item-"
0e89c3fc
SB
2382 (concat "todos-item-insert-"
2383 (mapconcat (lambda (e) (if e (symbol-name e))) arglist "-")))))
d04d6b95 2384
0e89c3fc
SB
2385(defvar todos-insertion-commands-names
2386 (mapcar (lambda (l)
2387 (todos-insertion-command-name l))
2388 todos-insertion-commands-args)
2389 "List of names of Todos insertion commands.")
d04d6b95 2390
59ad682f 2391;; FIXME: prefix argument ARG is nil
0e89c3fc
SB
2392(defmacro todos-define-insertion-command (&rest args)
2393 (let ((name (intern (todos-insertion-command-name args)))
2394 (arg0 (nth 0 args))
2395 (arg1 (nth 1 args))
2396 (arg2 (nth 2 args))
2397 (arg3 (nth 3 args))
2398 (arg4 (nth 4 args)))
59ad682f 2399 `(defun ,name (&optional arg &rest args)
3af3cd0b 2400 "Todos item insertion command generated from ARGS."
59ad682f 2401 (interactive (list current-prefix-arg))
0e89c3fc 2402 (todos-insert-item arg ',arg0 ',arg1 ',arg2 ',arg3 ',arg4))))
3f031767 2403
59ad682f
SB
2404;; FIXME: exclude todos-insert-item (or rather from
2405;; todos-insertion-key-bindings?), otherwise its doc string won't be
2406;; found with C-h k (but it will with M-x todos-insert-item)
0e89c3fc
SB
2407(defvar todos-insertion-commands
2408 (mapcar (lambda (c)
2409 (eval `(todos-define-insertion-command ,@c)))
2410 todos-insertion-commands-args)
2411 "List of Todos insertion commands.")
db2c5d34 2412
0e89c3fc
SB
2413(defvar todos-insertion-commands-arg-key-list
2414 '(("diary" "y" "yy")
2415 ("nonmarking" "k" "kk")
2416 ("calendar" "c" "cc")
2417 ("date" "d" "dd")
2418 ("dayname" "n" "nn")
2419 ("time" "t" "tt")
2420 ("here" "h" "h")
2421 ("region" "r" "r"))
2422 "")
db2c5d34 2423
0e89c3fc
SB
2424(defun todos-insertion-key-bindings (map)
2425 ""
2426 (dolist (c todos-insertion-commands)
2427 (let* ((key "")
2428 (cname (symbol-name c)))
2429 (mapc (lambda (l)
2430 (let ((arg (nth 0 l))
2431 (key1 (nth 1 l))
2432 (key2 (nth 2 l)))
2433 (if (string-match (concat (regexp-quote arg) "\\_>") cname)
2434 (setq key (concat key key2)))
2435 (if (string-match (concat (regexp-quote arg) ".+") cname)
2436 (setq key (concat key key1)))))
2437 todos-insertion-commands-arg-key-list)
2438 (if (string-match (concat (regexp-quote "todos-item-insert") "\\_>") cname)
2439 (setq key (concat key "i")))
2440 (define-key map key c))))
ee7412e4 2441
0e89c3fc
SB
2442(defvar todos-insertion-map
2443 (let ((map (make-keymap)))
2444 (todos-insertion-key-bindings map)
fd6c6328 2445 (define-key map "p" 'todos-copy-item)
0e89c3fc
SB
2446 map)
2447 "Keymap for Todos mode insertion commands.")
ee7412e4 2448
abe748f5 2449;; ---------------------------------------------------------------------------
6be04162
SB
2450;;; Key maps and menus
2451
0e89c3fc
SB
2452(defvar todos-key-bindings
2453 `(
2454 ;; display
d16da867 2455 ("Cd" . todos-display-categories) ;FIXME: Fc todos-file-categories?
0e89c3fc 2456 ("H" . todos-highlight-item)
3af3cd0b 2457 ("N" . todos-hide-show-item-numbering)
78fe7289
SB
2458 ("D" . todos-hide-show-date-time)
2459 ("*" . todos-mark-unmark-item)
0e89c3fc
SB
2460 ("C*" . todos-mark-category)
2461 ("Cu" . todos-unmark-category)
2462 ("PP" . todos-print)
2463 ("PF" . todos-print-to-file)
3af3cd0b
SB
2464 ("v" . todos-hide-show-done-items)
2465 ("V" . todos-show-done-only)
0e89c3fc
SB
2466 ("As" . todos-show-archive)
2467 ("Ac" . todos-choose-archive)
d16da867 2468 ;; ("Y" . todos-diary-items)
0e89c3fc
SB
2469 ("Fe" . todos-edit-multiline)
2470 ("Fh" . todos-highlight-item)
3af3cd0b 2471 ("Fn" . todos-hide-show-item-numbering)
78fe7289 2472 ("Fd" . todos-hide-show-date-time)
0e89c3fc
SB
2473 ("Ftt" . todos-top-priorities)
2474 ("Ftm" . todos-top-priorities-multifile)
2475 ("Fts" . todos-set-top-priorities-in-file)
2476 ("Cts" . todos-set-top-priorities-in-category)
2477 ("Fyy" . todos-diary-items)
2478 ("Fym" . todos-diary-items-multifile)
2479 ("Fxx" . todos-regexp-items)
2480 ("Fxm" . todos-regexp-items-multifile)
0e89c3fc
SB
2481 ;; navigation
2482 ("f" . todos-forward-category)
2483 ("b" . todos-backward-category)
2484 ("j" . todos-jump-to-category)
2485 ("J" . todos-jump-to-category-other-file)
2486 ("n" . todos-forward-item)
2487 ("p" . todos-backward-item)
2488 ("S" . todos-search)
2489 ("X" . todos-clear-matches)
2490 ;; editing
2491 ("Fa" . todos-add-file)
2492 ("Ca" . todos-add-category)
2493 ("Cr" . todos-rename-category)
2494 ("Cg" . todos-merge-category)
0e89c3fc
SB
2495 ("Cm" . todos-move-category)
2496 ("Ck" . todos-delete-category)
2497 ("d" . todos-item-done)
2498 ("ee" . todos-edit-item)
2499 ("em" . todos-edit-multiline-item)
2500 ("eh" . todos-edit-item-header)
0e89c3fc 2501 ("edc" . todos-edit-item-date-from-calendar)
d16da867
SB
2502 ("edt" . todos-edit-item-date-to-today)
2503 ("edn" . todos-edit-item-date-day-name)
2504 ("edy" . todos-edit-item-date-year)
2505 ("edm" . todos-edit-item-date-month)
2506 ("edd" . todos-edit-item-date-day)
0e89c3fc
SB
2507 ("et" . todos-edit-item-time)
2508 ("eyy" . todos-edit-item-diary-inclusion)
2509 ;; ("" . todos-edit-category-diary-inclusion)
2510 ("eyn" . todos-edit-item-diary-nonmarking)
2511 ;;("" . todos-edit-category-diary-nonmarking)
b28872ce 2512 ("ec" . todos-done-item-add-edit-or-delete-comment)
0e89c3fc 2513 ("i" . ,todos-insertion-map)
7464f422 2514 ("k" . todos-delete-item) ;FIXME: not single letter?
0e89c3fc
SB
2515 ("m" . todos-move-item)
2516 ("M" . todos-move-item-to-file)
0e89c3fc 2517 ("r" . todos-raise-item-priority)
0e89c3fc
SB
2518 ("l" . todos-lower-item-priority)
2519 ("#" . todos-set-item-priority)
2520 ("u" . todos-item-undo)
b28872ce
SB
2521 ("Ad" . todos-archive-done-item) ;FIXME: ad
2522 ("AD" . todos-archive-category-done-items) ;FIXME: aD or C-u ad ?
0e89c3fc
SB
2523 ("s" . todos-save)
2524 ("q" . todos-quit)
2525 ([remap newline] . newline-and-indent)
2526 )
2527 "Alist pairing keys defined in Todos modes and their bindings.")
2528
2529(defvar todos-mode-map
2530 (let ((map (make-keymap)))
2531 ;; Don't suppress digit keys, so they can supply prefix arguments.
2532 (suppress-keymap map)
2533 (dolist (ck todos-key-bindings)
2534 (define-key map (car ck) (cdr ck)))
2535 map)
2536 "Todos mode keymap.")
d04d6b95 2537
58c7641d 2538;; FIXME
0e89c3fc
SB
2539(easy-menu-define
2540 todos-menu todos-mode-map "Todos Menu"
2541 '("Todos"
2542 ("Navigation"
2543 ["Next Item" todos-forward-item t]
2544 ["Previous Item" todos-backward-item t]
2545 "---"
2546 ["Next Category" todos-forward-category t]
2547 ["Previous Category" todos-backward-category t]
2548 ["Jump to Category" todos-jump-to-category t]
2549 ["Jump to Category in Other File" todos-jump-to-category-other-file t]
2550 "---"
2551 ["Search Todos File" todos-search t]
2552 ["Clear Highlighting on Search Matches" todos-category-done t])
2553 ("Display"
2554 ["List Current Categories" todos-display-categories t]
2555 ;; ["List Categories Alphabetically" todos-display-categories-alphabetically t]
2556 ["Turn Item Highlighting on/off" todos-highlight-item t]
3af3cd0b 2557 ["Turn Item Numbering on/off" todos-hide-show-item-numbering t]
78fe7289 2558 ["Turn Item Time Stamp on/off" todos-hide-show-date-time t]
3af3cd0b 2559 ["View/Hide Done Items" todos-hide-show-done-items t]
0e89c3fc
SB
2560 "---"
2561 ["View Diary Items" todos-diary-items t]
2562 ["View Top Priority Items" todos-top-priorities t]
2563 ["View Multifile Top Priority Items" todos-top-priorities-multifile t]
2564 "---"
0e89c3fc
SB
2565 ["Print Category" todos-print t])
2566 ("Editing"
2567 ["Insert New Item" todos-insert-item t]
2568 ["Insert Item Here" todos-insert-item-here t]
2569 ("More Insertion Commands")
2570 ["Edit Item" todos-edit-item t]
2571 ["Edit Multiline Item" todos-edit-multiline t]
2572 ["Edit Item Header" todos-edit-item-header t]
2573 ["Edit Item Date" todos-edit-item-date t]
2574 ["Edit Item Time" todos-edit-item-time t]
2575 "---"
2576 ["Lower Item Priority" todos-lower-item-priority t]
2577 ["Raise Item Priority" todos-raise-item-priority t]
2578 ["Set Item Priority" todos-set-item-priority t]
2579 ["Move (Recategorize) Item" todos-move-item t]
2580 ["Delete Item" todos-delete-item t]
2581 ["Undo Done Item" todos-item-undo t]
2582 ["Mark/Unmark Item for Diary" todos-toggle-item-diary-inclusion t]
2583 ["Mark/Unmark Items for Diary" todos-edit-item-diary-inclusion t]
2584 ["Mark & Hide Done Item" todos-item-done t]
2585 ["Archive Done Items" todos-archive-category-done-items t]
2586 "---"
2587 ["Add New Todos File" todos-add-file t]
2588 ["Add New Category" todos-add-category t]
2589 ["Delete Current Category" todos-delete-category t]
2590 ["Rename Current Category" todos-rename-category t]
2591 "---"
2592 ["Save Todos File" todos-save t]
a820dfe8 2593 )
0e89c3fc
SB
2594 "---"
2595 ["Quit" todos-quit t]
2596 ))
2597
2598(defvar todos-archive-mode-map
2599 (let ((map (make-sparse-keymap)))
2600 (suppress-keymap map t)
2601 ;; navigation commands
2602 (define-key map "f" 'todos-forward-category)
2603 (define-key map "b" 'todos-backward-category)
2604 (define-key map "j" 'todos-jump-to-category)
2605 (define-key map "n" 'todos-forward-item)
2606 (define-key map "p" 'todos-backward-item)
2607 ;; display commands
2608 (define-key map "C" 'todos-display-categories)
2609 (define-key map "H" 'todos-highlight-item)
3af3cd0b 2610 (define-key map "N" 'todos-hide-show-item-numbering)
78fe7289 2611 ;; (define-key map "" 'todos-hide-show-date-time)
0e89c3fc
SB
2612 (define-key map "P" 'todos-print)
2613 (define-key map "q" 'todos-quit)
2614 (define-key map "s" 'todos-save)
2615 (define-key map "S" 'todos-search)
2a9e69d6 2616 (define-key map "t" 'todos-show)
abe748f5 2617 (define-key map "u" 'todos-unarchive-items)
0e89c3fc
SB
2618 (define-key map "U" 'todos-unarchive-category)
2619 map)
2620 "Todos Archive mode keymap.")
2621
2622(defvar todos-edit-mode-map
2623 (let ((map (make-sparse-keymap)))
2624 (define-key map "\C-x\C-q" 'todos-edit-quit)
2625 (define-key map [remap newline] 'newline-and-indent)
2626 map)
2627 "Todos Edit mode keymap.")
2628
2629(defvar todos-categories-mode-map
2630 (let ((map (make-sparse-keymap)))
2631 (suppress-keymap map t)
a820dfe8
SB
2632 (define-key map "c" 'todos-display-categories-alphabetically-or-by-priority)
2633 (define-key map "t" 'todos-display-categories-sorted-by-todo)
2634 (define-key map "y" 'todos-display-categories-sorted-by-diary)
2635 (define-key map "d" 'todos-display-categories-sorted-by-done)
2636 (define-key map "a" 'todos-display-categories-sorted-by-archived)
2a9e69d6
SB
2637 (define-key map "l" 'todos-lower-category-priority)
2638 (define-key map "+" 'todos-lower-category-priority)
2639 (define-key map "r" 'todos-raise-category-priority)
2640 (define-key map "-" 'todos-raise-category-priority)
18aef8a3
SB
2641 (define-key map "n" 'todos-forward-button)
2642 (define-key map "p" 'todos-backward-button)
2643 (define-key map [tab] 'todos-forward-button)
2644 (define-key map [backtab] 'todos-backward-button)
0e89c3fc
SB
2645 (define-key map "q" 'todos-quit)
2646 ;; (define-key map "A" 'todos-add-category)
2647 ;; (define-key map "D" 'todos-delete-category)
2648 ;; (define-key map "R" 'todos-rename-category)
2649 map)
2650 "Todos Categories mode keymap.")
2651
b28872ce 2652(defvar todos-filtered-items-mode-map
0e89c3fc
SB
2653 (let ((map (make-keymap)))
2654 (suppress-keymap map t)
2655 ;; navigation commands
2656 (define-key map "j" 'todos-jump-to-item)
2657 (define-key map [remap newline] 'todos-jump-to-item)
2658 (define-key map "n" 'todos-forward-item)
2659 (define-key map "p" 'todos-backward-item)
2660 (define-key map "H" 'todos-highlight-item)
3af3cd0b 2661 (define-key map "N" 'todos-hide-show-item-numbering)
78fe7289 2662 (define-key map "D" 'todos-hide-show-date-time)
0e89c3fc
SB
2663 (define-key map "P" 'todos-print)
2664 (define-key map "q" 'todos-quit)
2665 (define-key map "s" 'todos-save)
0e89c3fc
SB
2666 ;; editing commands
2667 (define-key map "l" 'todos-lower-item-priority)
2668 (define-key map "r" 'todos-raise-item-priority)
616ffa8b 2669 (define-key map "#" 'todos-set-item-priority)
0e89c3fc
SB
2670 map)
2671 "Todos Top Priorities mode keymap.")
2672
abe748f5
SB
2673;; ---------------------------------------------------------------------------
2674;;; Mode definitions
6be04162 2675
0e89c3fc
SB
2676(defun todos-modes-set-1 ()
2677 ""
2678 (set (make-local-variable 'font-lock-defaults) '(todos-font-lock-keywords t))
2679 (set (make-local-variable 'indent-line-function) 'todos-indent)
2680 (when todos-wrap-lines (funcall todos-line-wrapping-function)))
2681
2682(defun todos-modes-set-2 ()
2683 ""
2684 (add-to-invisibility-spec 'todos)
2685 (setq buffer-read-only t)
2686 (set (make-local-variable 'hl-line-range-function)
2687 (lambda() (when (todos-item-end)
2688 (cons (todos-item-start) (todos-item-end))))))
2689
2690(defun todos-modes-set-3 ()
616ffa8b 2691 ""
0e89c3fc
SB
2692 (set (make-local-variable 'todos-categories) (todos-set-categories))
2693 (set (make-local-variable 'todos-category-number) 1)
2694 (set (make-local-variable 'todos-first-visit) t)
6be04162 2695 (add-hook 'find-file-hook 'todos-display-as-todos-file nil t))
0e89c3fc
SB
2696
2697(put 'todos-mode 'mode-class 'special)
2698
616ffa8b 2699(define-derived-mode todos-mode special-mode "Todos"
0e89c3fc
SB
2700 "Major mode for displaying, navigating and editing Todo lists.
2701
2702\\{todos-mode-map}"
2703 (easy-menu-add todos-menu)
2704 (todos-modes-set-1)
2705 (todos-modes-set-2)
2706 (todos-modes-set-3)
2707 ;; Initialize todos-current-todos-file.
2708 (when (member (file-truename (buffer-file-name))
2709 (funcall todos-files-function))
2710 (set (make-local-variable 'todos-current-todos-file)
2711 (file-truename (buffer-file-name))))
2712 (set (make-local-variable 'todos-first-visit) t)
2713 (set (make-local-variable 'todos-show-done-only) nil)
2a9e69d6 2714 (set (make-local-variable 'todos-categories-with-marks) nil)
6be04162
SB
2715 (add-hook 'find-file-hook 'todos-add-to-buffer-list nil t)
2716 (add-hook 'post-command-hook 'todos-update-buffer-list nil t)
0e89c3fc
SB
2717 (when todos-show-current-file
2718 (add-hook 'pre-command-hook 'todos-show-current-file nil t))
0e89c3fc 2719 (add-hook 'window-configuration-change-hook
18aef8a3 2720 'todos-reset-and-enable-done-separator nil t)
0e89c3fc
SB
2721 (add-hook 'kill-buffer-hook 'todos-reset-global-current-todos-file nil t))
2722
0e89c3fc
SB
2723(defun todos-unload-hook ()
2724 ""
2725 (remove-hook 'pre-command-hook 'todos-show-current-file t)
6be04162
SB
2726 (remove-hook 'post-command-hook 'todos-update-buffer-list t)
2727 (remove-hook 'find-file-hook 'todos-display-as-todos-file t)
2728 (remove-hook 'find-file-hook 'todos-add-to-buffer-list t)
0e89c3fc 2729 (remove-hook 'window-configuration-change-hook
d9be0d35 2730 'todos-reset-and-enable-done-separator t)
0e89c3fc
SB
2731 (remove-hook 'kill-buffer-hook 'todos-reset-global-current-todos-file t))
2732
2733(put 'todos-archive-mode 'mode-class 'special)
2734
abe748f5
SB
2735;; If todos-mode is parent, all todos-mode key bindings appear to be
2736;; available in todos-archive-mode (e.g. shown by C-h m).
616ffa8b 2737(define-derived-mode todos-archive-mode special-mode "Todos-Arch"
0e89c3fc
SB
2738 "Major mode for archived Todos categories.
2739
2740\\{todos-archive-mode-map}"
2741 (todos-modes-set-1)
2742 (todos-modes-set-2)
2743 (todos-modes-set-3)
2744 (set (make-local-variable 'todos-current-todos-file)
2745 (file-truename (buffer-file-name)))
2746 (set (make-local-variable 'todos-show-done-only) t))
2747
2748(defun todos-mode-external-set ()
d04d6b95 2749 ""
0e89c3fc
SB
2750 (set (make-local-variable 'todos-current-todos-file)
2751 todos-global-current-todos-file)
a820dfe8
SB
2752 (let ((cats (with-current-buffer
2753 (find-buffer-visiting todos-current-todos-file)
b28872ce 2754 todos-categories)))
0e89c3fc 2755 (set (make-local-variable 'todos-categories) cats)))
d04d6b95 2756
616ffa8b 2757(define-derived-mode todos-edit-mode text-mode "Todos-Ed"
0e89c3fc 2758 "Major mode for editing multiline Todo items.
58c7641d 2759
7464f422 2760\\{todos-edit-mode-map}"
0e89c3fc
SB
2761 (todos-modes-set-1)
2762 (todos-mode-external-set))
58c7641d 2763
0e89c3fc 2764(put 'todos-categories-mode 'mode-class 'special)
58c7641d 2765
616ffa8b 2766(define-derived-mode todos-categories-mode special-mode "Todos-Cats"
0e89c3fc 2767 "Major mode for displaying and editing Todos categories.
58c7641d 2768
0e89c3fc
SB
2769\\{todos-categories-mode-map}"
2770 (todos-mode-external-set))
58c7641d 2771
0e89c3fc 2772(put 'todos-filter-mode 'mode-class 'special)
58c7641d 2773
616ffa8b 2774(define-derived-mode todos-filtered-items-mode special-mode "Todos-Fltr"
0e89c3fc 2775 "Mode for displaying and reprioritizing top priority Todos.
58c7641d 2776
b28872ce 2777\\{todos-filtered-items-mode-map}"
0e89c3fc
SB
2778 (todos-modes-set-1)
2779 (todos-modes-set-2))
2780
b28872ce
SB
2781;; ---------------------------------------------------------------------------
2782;;; Todos Commands
0e89c3fc
SB
2783
2784;; ---------------------------------------------------------------------------
b28872ce 2785;;; Entering and Exiting
0e89c3fc
SB
2786
2787;;;###autoload
2788(defun todos-show (&optional solicit-file)
2789 "Visit the current Todos file and display one of its categories.
a820dfe8
SB
2790With non-nil prefix argument SOLICIT-FILE prompt for which todo
2791file to visit.
0e89c3fc 2792
a820dfe8
SB
2793Without a prefix argument, the first invocation of this command
2794in a session visits `todos-default-todos-file' (creating it if it
2795does not yet exist); subsequent invocations from outside of Todos
2796mode revisit this file or, if the user option
2797`todos-show-current-file' is non-nil, whichever Todos file
2798\(either a todo or an archive file) was visited last.
0e89c3fc
SB
2799
2800The category displayed on initial invocation is the first member
2801of `todos-categories' for the current Todos file, on subsequent
2802invocations whichever category was displayed last. If
2803`todos-display-categories-first' is non-nil, then the first
2804invocation of `todos-show' displays a clickable listing of the
2805categories in the current Todos file.
2806
2807In Todos mode just the category's unfinished todo items are shown
2808by default. The done items are hidden, but typing
3af3cd0b 2809`\\[todos-hide-show-done-items]' displays them below the todo
0e89c3fc 2810items. With non-nil user option `todos-show-with-done' both todo
2a9e69d6
SB
2811and done items are always shown on visiting a category.
2812
2813If this command is invoked in Todos Archive mode, it visits the
2814corresponding Todos file, displaying the corresponding category."
3f031767 2815 (interactive "P")
2a9e69d6
SB
2816 (let* ((cat)
2817 (file (cond (solicit-file
459c6e93
SB
2818 (if (funcall todos-files-function)
2819 (todos-read-file-name "Choose a Todos file to visit: "
2820 nil t)
2821 (error "There are no Todos files")))
6be04162
SB
2822 ((and (eq major-mode 'todos-archive-mode)
2823 ;; Called noninteractively via todos-quit from
2824 ;; Todos Categories mode to return to archive file.
2825 (called-interactively-p 'any))
459c6e93
SB
2826 (setq cat (todos-current-category))
2827 (concat (file-name-sans-extension todos-current-todos-file)
2828 ".todo"))
2829 (t
459c6e93
SB
2830 (or todos-current-todos-file
2831 (and todos-show-current-file
2832 todos-global-current-todos-file)
2833 todos-default-todos-file
2834 (todos-add-file))))))
0e89c3fc
SB
2835 (if (and todos-first-visit todos-display-categories-first)
2836 (todos-display-categories)
2837 (set-window-buffer (selected-window)
2838 (set-buffer (find-file-noselect file)))
2a9e69d6
SB
2839 ;; If called from archive file, show corresponding category in Todos
2840 ;; file, if it exists.
2841 (when (assoc cat todos-categories)
2842 (setq todos-category-number (todos-category-number cat)))
bbf95285 2843 ;; If this is a new Todos file, add its first category.
2a9e69d6 2844 (when (zerop (buffer-size))
2a9e69d6 2845 (setq todos-category-number (todos-add-category "")))
0e89c3fc
SB
2846 (save-excursion (todos-category-select)))
2847 (setq todos-first-visit nil)))
d04d6b95 2848
0e89c3fc
SB
2849(defun todos-display-categories ()
2850 "Display a table of the current file's categories and item counts.
2851
2852In the initial display the categories are numbered, indicating
2853their current order for navigating by \\[todos-forward-category]
2854and \\[todos-backward-category]. You can persistantly change the
2a9e69d6
SB
2855order of the category at point by typing
2856\\[todos-raise-category-priority] or
2857\\[todos-lower-category-priority].
0e89c3fc
SB
2858
2859The labels above the category names and item counts are buttons,
2860and clicking these changes the display: sorted by category name
2861or by the respective item counts (alternately descending or
2862ascending). In these displays the categories are not numbered
2a9e69d6
SB
2863and \\[todos-raise-category-priority] and
2864\\[todos-lower-category-priority] are
0e89c3fc
SB
2865disabled. (Programmatically, the sorting is triggered by passing
2866a non-nil SORTKEY argument.)
2867
2868In addition, the lines with the category names and item counts
2869are buttonized, and pressing one of these button jumps to the
2870category in Todos mode (or Todos Archive mode, for categories
2871containing only archived items, provided user option
6be04162 2872`todos-skip-archived-categories' is non-nil. These categories
0e89c3fc 2873are shown in `todos-archived-only' face."
2c173503 2874 (interactive)
0e89c3fc
SB
2875 (todos-display-categories-1)
2876 (let (sortkey)
2877 (todos-update-categories-display sortkey)))
2c173503 2878
a820dfe8
SB
2879(defun todos-display-categories-alphabetically-or-by-priority ()
2880 ""
2881 (interactive)
2882 (save-excursion
2883 (goto-char (point-min))
2884 (forward-line 2)
2885 (if (member 'alpha todos-descending-counts)
2886 (progn
2887 (todos-update-categories-display nil)
2888 (setq todos-descending-counts
2889 (delete 'alpha todos-descending-counts)))
2890 (todos-update-categories-display 'alpha))))
3f031767 2891
a820dfe8
SB
2892(defun todos-display-categories-sorted-by-todo ()
2893 ""
2894 (interactive)
2895 (save-excursion
2896 (goto-char (point-min))
2897 (forward-line 2)
2898 (todos-update-categories-display 'todo)))
58c7641d 2899
a820dfe8
SB
2900(defun todos-display-categories-sorted-by-diary ()
2901 ""
2902 (interactive)
2903 (save-excursion
2904 (goto-char (point-min))
2905 (forward-line 2)
2906 (todos-update-categories-display 'diary)))
58c7641d 2907
a820dfe8
SB
2908(defun todos-display-categories-sorted-by-done ()
2909 ""
2910 (interactive)
2911 (save-excursion
2912 (goto-char (point-min))
2913 (forward-line 2)
2914 (todos-update-categories-display 'done)))
0e89c3fc 2915
a820dfe8
SB
2916(defun todos-display-categories-sorted-by-archived ()
2917 ""
2918 (interactive)
2919 (save-excursion
2920 (goto-char (point-min))
2921 (forward-line 2)
2922 (todos-update-categories-display 'archived)))
0e89c3fc 2923
0e89c3fc 2924(defun todos-show-archive (&optional ask)
3af3cd0b
SB
2925 "Visit the archive of the current Todos category, if it exists.
2926If the category has no archived items, prompt to visit the
2927archive anyway. If there is no archive for this file or with
2928non-nil argument ASK, prompt to visit another archive.
2929
abe748f5
SB
2930The buffer showing the archive is in Todos Archive mode. The
2931first visit in a session displays the first category in the
2932archive, subsequent visits return to the last category
2933displayed."
0e89c3fc 2934 (interactive)
3af3cd0b
SB
2935 (let* ((cat (todos-current-category))
2936 (count (todos-get-count 'archived cat))
2937 (archive (concat (file-name-sans-extension todos-current-todos-file)
2938 ".toda"))
47011bed
SB
2939 place)
2940 (setq place (cond (ask 'other-archive)
2941 ((file-exists-p archive) 'this-archive)
2942 (t (when (y-or-n-p (concat "This file has no archive; "
2943 "visit another archive? "))
2944 'other-archive))))
2945 (when (eq place 'other-archive)
2946 (setq archive (todos-read-file-name "Choose a Todos archive: " t t)))
2947 (when (and (eq place 'this-archive) (zerop count))
2948 (setq place (when (y-or-n-p
2949 (concat "This category has no archived items;"
2950 " visit archive anyway? "))
2951 'other-cat)))
2952 (when place
3af3cd0b
SB
2953 (set-window-buffer (selected-window)
2954 (set-buffer (find-file-noselect archive)))
47011bed
SB
2955 (if (member place '(other-archive other-cat))
2956 (setq todos-category-number 1)
2957 (todos-category-number cat))
2958 (todos-category-select))))
58c7641d 2959
0e89c3fc
SB
2960(defun todos-choose-archive ()
2961 "Choose an archive and visit it."
2962 (interactive)
2963 (todos-show-archive t))
58c7641d 2964
b28872ce
SB
2965;; FIXME: need this?
2966(defun todos-save ()
2967 "Save the current Todos file."
3f031767 2968 (interactive)
a820dfe8 2969 (save-buffer))
d04d6b95 2970
b28872ce
SB
2971(defun todos-quit ()
2972 "Exit the current Todos-related buffer.
2973Depending on the specific mode, this either kills the buffer or
2974buries it and restores state as needed."
0e89c3fc 2975 (interactive)
b28872ce
SB
2976 (cond ((eq major-mode 'todos-categories-mode)
2977 (kill-buffer)
2978 (setq todos-descending-counts nil)
2979 (todos-show))
2980 ((eq major-mode 'todos-filtered-items-mode)
2981 (kill-buffer)
2982 (todos-show))
2983 ((member major-mode (list 'todos-mode 'todos-archive-mode))
616ffa8b
SB
2984 ;; Have to write previously nonexistant archives to file, and might
2985 ;; as well save Todos file also.
b28872ce
SB
2986 (todos-save)
2987 (bury-buffer))))
d04d6b95 2988
0e89c3fc
SB
2989(defun todos-print (&optional to-file)
2990 "Produce a printable version of the current Todos buffer.
2991This converts overlays and soft line wrapping and, depending on
2992the value of `todos-print-function', includes faces. With
2993non-nil argument TO-FILE write the printable version to a file;
2994otherwise, send it to the default printer."
db2c5d34 2995 (interactive)
0e89c3fc
SB
2996 (let ((buf todos-print-buffer)
2997 (header (cond
2998 ((eq major-mode 'todos-mode)
2999 (concat "Todos File: "
3000 (todos-short-file-name todos-current-todos-file)
3001 "\nCategory: " (todos-current-category)))
b28872ce 3002 ((eq major-mode 'todos-filtered-items-mode)
0e89c3fc
SB
3003 "Todos Top Priorities")))
3004 (prefix (propertize (concat todos-prefix " ")
3005 'face 'todos-prefix-string))
3006 (num 0)
3007 (fill-prefix (make-string todos-indent-to-here 32))
3008 (content (buffer-string))
3009 file)
3010 (with-current-buffer (get-buffer-create buf)
3011 (insert content)
3012 (goto-char (point-min))
3013 (while (not (eobp))
3014 (let ((beg (point))
3015 (end (save-excursion (todos-item-end))))
3af3cd0b 3016 (when todos-number-priorities
0e89c3fc
SB
3017 (setq num (1+ num))
3018 (setq prefix (propertize (concat (number-to-string num) " ")
3019 'face 'todos-prefix-string)))
3020 (insert prefix)
3021 (fill-region beg end))
3022 ;; Calling todos-forward-item infloops at todos-item-start due to
3023 ;; non-overlay prefix, so search for item start instead.
3024 (if (re-search-forward todos-item-start nil t)
3025 (beginning-of-line)
3026 (goto-char (point-max))))
3027 (if (re-search-backward (concat "^" (regexp-quote todos-category-done))
3028 nil t)
3029 (replace-match todos-done-separator))
3030 (goto-char (point-min))
3031 (insert header)
3032 (newline 2)
3033 (if to-file
3034 (let ((file (read-file-name "Print to file: ")))
3035 (funcall todos-print-function file))
3036 (funcall todos-print-function)))
3037 (kill-buffer buf)))
2c173503 3038
0e89c3fc
SB
3039(defun todos-print-to-file ()
3040 "Save printable version of this Todos buffer to a file."
d04d6b95 3041 (interactive)
0e89c3fc 3042 (todos-print t))
d04d6b95 3043
0e89c3fc
SB
3044(defun todos-convert-legacy-files ()
3045 "Convert legacy Todo files to the current Todos format.
3046The files `todo-file-do' and `todo-file-done' are converted and
3047saved (the latter as a Todos Archive file) with a new name in
3048`todos-files-directory'. See also the documentation string of
3049`todos-todo-mode-date-time-regexp' for further details."
3050 (interactive)
3051 (if (fboundp 'todo-mode)
3052 (require 'todo-mode)
3053 (error "Void function `todo-mode'"))
3054 ;; Convert `todo-file-do'.
3055 (if (file-exists-p todo-file-do)
3056 (let ((default "todo-do-conv")
3057 file archive-sexp)
3058 (with-temp-buffer
3059 (insert-file-contents todo-file-do)
3060 (let ((end (search-forward ")" (line-end-position) t))
3061 (beg (search-backward "(" (line-beginning-position) t)))
3062 (setq todo-categories
3063 (read (buffer-substring-no-properties beg end))))
3064 (todo-mode)
3065 (delete-region (line-beginning-position) (1+ (line-end-position)))
3066 (while (not (eobp))
3067 (cond
3068 ((looking-at (regexp-quote (concat todo-prefix todo-category-beg)))
3069 (replace-match todos-category-beg))
3070 ((looking-at (regexp-quote todo-category-end))
3071 (replace-match ""))
3072 ((looking-at (regexp-quote (concat todo-prefix " "
3073 todo-category-sep)))
3074 (replace-match todos-category-done))
3075 ((looking-at (concat (regexp-quote todo-prefix) " "
3076 todos-todo-mode-date-time-regexp " "
3077 (regexp-quote todo-initials) ":"))
3078 (todos-convert-legacy-date-time)))
3079 (forward-line))
3080 (setq file (concat todos-files-directory
3081 (read-string
3082 (format "Save file as (default \"%s\"): " default)
3083 nil nil default)
3084 ".todo"))
3085 (write-region (point-min) (point-max) file nil 'nomessage nil t))
3086 (with-temp-buffer
3087 (insert-file-contents file)
3088 (let ((todos-categories (todos-make-categories-list t)))
3089 (todos-update-categories-sexp))
3090 (write-region (point-min) (point-max) file nil 'nomessage))
3091 ;; Convert `todo-file-done'.
3092 (when (file-exists-p todo-file-done)
3093 (with-temp-buffer
3094 (insert-file-contents todo-file-done)
3095 (let ((beg (make-marker))
3096 (end (make-marker))
3097 cat cats comment item)
3098 (while (not (eobp))
3099 (when (looking-at todos-todo-mode-date-time-regexp)
3100 (set-marker beg (point))
3101 (todos-convert-legacy-date-time)
3102 (set-marker end (point))
3103 (goto-char beg)
3104 (insert "[" todos-done-string)
3105 (goto-char end)
3106 (insert "]")
3107 (forward-char)
3108 (when (looking-at todos-todo-mode-date-time-regexp)
3109 (todos-convert-legacy-date-time))
3110 (when (looking-at (concat " " (regexp-quote todo-initials) ":"))
3111 (replace-match "")))
3112 (if (re-search-forward
3113 (concat "^" todos-todo-mode-date-time-regexp) nil t)
3114 (goto-char (match-beginning 0))
3115 (goto-char (point-max)))
3116 (backward-char)
3117 (when (looking-back "\\[\\([^][]+\\)\\]")
3118 (setq cat (match-string 1))
3119 (goto-char (match-beginning 0))
3120 (replace-match ""))
3121 ;; If the item ends with a non-comment parenthesis not
3122 ;; followed by a period, we lose (but we inherit that problem
3123 ;; from todo-mode.el).
3124 (when (looking-back "(\\(.*\\)) ")
3125 (setq comment (match-string 1))
3126 (replace-match "")
3127 (insert "[" todos-comment-string ": " comment "]"))
3128 (set-marker end (point))
3129 (if (member cat cats)
3130 ;; If item is already in its category, leave it there.
3131 (unless (save-excursion
3132 (re-search-backward
3133 (concat "^" (regexp-quote todos-category-beg)
3134 "\\(.*\\)$") nil t)
3135 (string= (match-string 1) cat))
3136 ;; Else move it to its category.
3137 (setq item (buffer-substring-no-properties beg end))
3138 (delete-region beg (1+ end))
3139 (set-marker beg (point))
3140 (re-search-backward
11aa0eef
SB
3141 (concat "^" (regexp-quote (concat todos-category-beg cat))
3142 "$")
0e89c3fc
SB
3143 nil t)
3144 (forward-line)
3145 (if (re-search-forward
3146 (concat "^" (regexp-quote todos-category-beg)
3147 "\\(.*\\)$") nil t)
3148 (progn (goto-char (match-beginning 0))
3149 (newline)
3150 (forward-line -1))
3151 (goto-char (point-max)))
3152 (insert item "\n")
3153 (goto-char beg))
3154 (push cat cats)
3155 (goto-char beg)
3156 (insert todos-category-beg cat "\n\n" todos-category-done "\n"))
3157 (forward-line))
3158 (set-marker beg nil)
3159 (set-marker end nil))
3160 (setq file (concat (file-name-sans-extension file) ".toda"))
3161 (write-region (point-min) (point-max) file nil 'nomessage nil t))
3162 (with-temp-buffer
3163 (insert-file-contents file)
3164 (let ((todos-categories (todos-make-categories-list t)))
3165 (todos-update-categories-sexp))
3166 (write-region (point-min) (point-max) file nil 'nomessage)
3167 (setq archive-sexp (read (buffer-substring-no-properties
3168 (line-beginning-position)
3169 (line-end-position)))))
3170 (setq file (concat (file-name-sans-extension file) ".todo"))
3171 ;; Update categories sexp of converted Todos file again, adding
3172 ;; counts of archived items.
3173 (with-temp-buffer
3174 (insert-file-contents file)
3175 (let ((sexp (read (buffer-substring-no-properties
3176 (line-beginning-position)
3177 (line-end-position)))))
3178 (dolist (cat sexp)
3179 (let ((archive-cat (assoc (car cat) archive-sexp)))
3180 (if archive-cat
3181 (aset (cdr cat) 3 (aref (cdr archive-cat) 2)))))
3182 (delete-region (line-beginning-position) (line-end-position))
3183 (prin1 sexp (current-buffer)))
3184 (write-region (point-min) (point-max) file nil 'nomessage)))
36341a66 3185 (todos-reevaluate-filelist-defcustoms)
0e89c3fc
SB
3186 (message "Format conversion done."))
3187 (error "No legacy Todo file exists")))
2c173503 3188
0e89c3fc
SB
3189;; ---------------------------------------------------------------------------
3190;;; Navigation Commands
3191
3192(defun todos-forward-category (&optional back)
3193 "Visit the numerically next category in this Todos file.
3194If the current category is the highest numbered, visit the first
3195category. With non-nil argument BACK, visit the numerically
3196previous category (the highest numbered one, if the current
3197category is the first)."
58c7641d 3198 (interactive)
0e89c3fc
SB
3199 (setq todos-category-number
3200 (1+ (mod (- todos-category-number (if back 2 0))
3201 (length todos-categories))))
6be04162 3202 (when todos-skip-archived-categories
7464f422
SB
3203 (while (and (zerop (todos-get-count 'todo))
3204 (zerop (todos-get-count 'done))
45e4a397 3205 (not (zerop (todos-get-count 'archived))))
7464f422
SB
3206 (setq todos-category-number
3207 (apply (if back '1- '1+) (list todos-category-number)))))
0e89c3fc
SB
3208 (todos-category-select)
3209 (goto-char (point-min)))
58c7641d 3210
0e89c3fc
SB
3211(defun todos-backward-category ()
3212 "Visit the numerically previous category in this Todos file.
3213If the current category is the highest numbered, visit the first
3214category."
3215 (interactive)
3216 (todos-forward-category t))
58c7641d 3217
0e89c3fc
SB
3218(defun todos-jump-to-category (&optional cat other-file)
3219 "Jump to a category in this or another Todos file.
3220
3221Programmatically, optional argument CAT provides the category
3222name. When nil (as in interactive calls), prompt for the
3223category, with TAB completion on existing categories. If a
3224non-existing category name is entered, ask whether to add a new
3225category with this name; if affirmed, add it, then jump to that
3226category. With non-nil argument OTHER-FILE, prompt for a Todos
3227file, otherwise jump within the current Todos file."
2c173503 3228 (interactive)
0e89c3fc
SB
3229 (let ((file (or (and other-file
3230 (todos-read-file-name "Choose a Todos file: " nil t))
520d912e
SB
3231 ;; Jump to archived-only Categories from Todos Categories
3232 ;; mode.
0e89c3fc 3233 (and cat
6be04162 3234 todos-skip-archived-categories
0e89c3fc
SB
3235 (zerop (todos-get-count 'todo cat))
3236 (zerop (todos-get-count 'done cat))
3237 (not (zerop (todos-get-count 'archived cat)))
3238 (concat (file-name-sans-extension
3239 todos-current-todos-file) ".toda"))
3240 todos-current-todos-file
520d912e
SB
3241 ;; If invoked from outside of Todos mode before
3242 ;; todos-show...
0e89c3fc 3243 todos-default-todos-file)))
520d912e
SB
3244 (with-current-buffer (find-file-noselect file)
3245 (and other-file (setq todos-current-todos-file file))
3246 (let ((category (or (and (assoc cat todos-categories) cat)
3247 (todos-read-category "Jump to category: "))))
3248 ;; Clean up after selecting category in Todos Categories mode.
3249 (if (string= (buffer-name) todos-categories-buffer)
3250 (kill-buffer))
3251 (if (or cat other-file)
3252 (set-window-buffer (selected-window)
6be04162 3253 (set-buffer (find-buffer-visiting file))))
520d912e
SB
3254 (unless todos-global-current-todos-file
3255 (setq todos-global-current-todos-file todos-current-todos-file))
2a9e69d6
SB
3256 (todos-category-number category) ; (1+ (length t-c)) if new category.
3257 ;; (if (> todos-category-number (length todos-categories))
3258 ;; (setq todos-category-number (todos-add-category category)))
520d912e
SB
3259 (todos-category-select)
3260 (goto-char (point-min))))))
58c7641d 3261
0e89c3fc
SB
3262(defun todos-jump-to-category-other-file ()
3263 "Jump to a category in another Todos file.
3264The category is chosen by prompt, with TAB completion."
3265 (interactive)
3266 (todos-jump-to-category nil t))
58c7641d 3267
1a9cb339
SB
3268(defun todos-jump-to-any-category ()
3269 ""
3270 (interactive)
3271 (let* ((cats-alist todos-all-categories-alist)
3272 (cats (mapcar 'car cats-alist))
3273 (completion-ignore-case todos-completion-ignore-case)
3274 (cat (completing-read "Jump to category: " cats nil t))
3275 (files (if (zerop (length cat))
3276 (keyboard-quit)
3277 (cdr (assoc cat cats-alist))))
3278 (file (if (nlistp files)
3279 files
3280 (completing-read (format "Jump to \"%s\" in which file? " cat)
3281 files nil t))))
3282 (if (zerop (length file))
3283 (keyboard-quit)
3284 (setq file (concat todos-files-directory file ".todo"))
3285 (set-window-buffer (selected-window)
3286 (set-buffer (find-file-noselect file)))
3287 (unless todos-global-current-todos-file
3288 (setq todos-global-current-todos-file todos-current-todos-file))
3289 (todos-category-number cat)
3290 (todos-category-select)
3291 (goto-char (point-min)))))
3292
0e89c3fc
SB
3293(defun todos-jump-to-item ()
3294 "Jump to the file and category of the filtered item at point."
d04d6b95 3295 (interactive)
0e89c3fc
SB
3296 (let ((str (todos-item-string))
3297 (buf (current-buffer))
520d912e
SB
3298 cat file archive beg)
3299 (string-match (concat (if todos-filter-done-items
3300 (concat "\\(?:" todos-done-string-start "\\|"
3301 todos-date-string-start "\\)")
3302 todos-date-string-start)
3303 todos-date-pattern "\\(?: " diary-time-regexp "\\)?"
3304 (if todos-filter-done-items
3305 "\\]"
3306 (regexp-quote todos-nondiary-end)) "?"
3307 "\\(?4: \\[\\(?3:(archive) \\)?\\(?2:.*:\\)?"
3308 "\\(?1:.*\\)\\]\\).*$") str)
0e89c3fc
SB
3309 (setq cat (match-string 1 str))
3310 (setq file (match-string 2 str))
520d912e
SB
3311 (setq archive (string= (match-string 3 str) "(archive) "))
3312 (setq str (replace-match "" nil nil str 4))
0e89c3fc 3313 (setq file (if file
520d912e
SB
3314 (concat todos-files-directory (substring file 0 -1)
3315 (if archive ".toda" ".todo"))
3316 (if archive
3317 (concat (file-name-sans-extension
3318 todos-global-current-todos-file) ".toda")
3319 todos-global-current-todos-file)))
0e89c3fc 3320 (find-file-noselect file)
6be04162 3321 (with-current-buffer (find-buffer-visiting file)
0e89c3fc
SB
3322 (widen)
3323 (goto-char (point-min))
3324 (re-search-forward
11aa0eef 3325 (concat "^" (regexp-quote (concat todos-category-beg cat)) "$") nil t)
0e89c3fc
SB
3326 (search-forward str)
3327 (setq beg (match-beginning 0)))
3328 (kill-buffer buf)
6be04162 3329 (set-window-buffer (selected-window) (set-buffer (find-buffer-visiting file)))
0e89c3fc
SB
3330 (setq todos-current-todos-file file)
3331 (setq todos-category-number (todos-category-number cat))
520d912e
SB
3332 (let ((todos-show-with-done (if todos-filter-done-items t
3333 todos-show-with-done)))
3334 (todos-category-select))
0e89c3fc
SB
3335 (goto-char beg)))
3336
0e89c3fc
SB
3337(defun todos-forward-item (&optional count)
3338 "Move point down to start of item with next lower priority.
616ffa8b
SB
3339With positive numerical prefix COUNT, move point COUNT items
3340downward."
0e89c3fc 3341 (interactive "P")
616ffa8b
SB
3342 ;; It's not worth the trouble to allow prefix arg value < 1, since we have
3343 ;; the corresponding command.
3344 (if (and count (> 1 count))
3345 (error "This command only accepts a positive numerical prefix argument")
3346 (let* ((not-done (not (or (todos-done-item-p) (looking-at "^$"))))
3347 (start (line-end-position)))
3348 (goto-char start)
3349 (if (re-search-forward todos-item-start nil t (or count 1))
3350 (goto-char (match-beginning 0))
3351 (goto-char (point-max)))
3352 ;; If points advances by one from a todo to a done item, go back to the
3353 ;; space above todos-done-separator, since that is a legitimate place to
3354 ;; insert an item. But skip this space if count > 1, since that should
3355 ;; only stop on an item.
3356 (when (and not-done (todos-done-item-p))
3357 (if (or (not count) (= count 1))
3358 (re-search-backward "^$" start t))))))
0833689a
SB
3359 ;; FIXME: The preceding sexp is insufficient when buffer is not narrowed,
3360 ;; since there could be no done items in this category, so the search puts
3361 ;; us on first todo item of next category. Does this ever happen? If so:
3362 ;; (let ((opoint) (point))
3363 ;; (forward-line -1)
3364 ;; (when (or (not count) (= count 1))
3365 ;; (cond ((looking-at (concat "^" (regexp-quote todos-category-beg)))
3366 ;; (forward-line -2))
3367 ;; ((looking-at (concat "^" (regexp-quote todos-category-done)))
3368 ;; (forward-line -1))
3369 ;; (t
3370 ;; (goto-char opoint)))))))
58c7641d 3371
0e89c3fc
SB
3372(defun todos-backward-item (&optional count)
3373 "Move point up to start of item with next higher priority.
616ffa8b
SB
3374With positive numerical prefix COUNT, move point COUNT items
3375upward."
0e89c3fc 3376 (interactive "P")
616ffa8b
SB
3377 ;; Avoid moving to bob if on the first item but not at bob.
3378 (when (> (line-number-at-pos) 1)
3379 ;; It's not worth the trouble to allow prefix arg value < 1, since we have
3380 ;; the corresponding command.
3381 (if (and count (> 1 count))
3382 (error "This command only accepts a positive numerical prefix argument")
3383 (let* ((done (todos-done-item-p)))
3384 (todos-item-start)
3385 (unless (bobp)
3386 (re-search-backward todos-item-start nil t (or count 1)))
3387 ;; Unless this is a regexp filtered items buffer (which can contain
3388 ;; intermixed todo and done items), if points advances by one from a
3389 ;; done to a todo item, go back to the space above
3390 ;; todos-done-separator, since that is a legitimate place to insert an
3391 ;; item. But skip this space if count > 1, since that should only
3392 ;; stop on an item.
3393 (when (and done (not (todos-done-item-p)) (or (not count) (= count 1))
3394 (not (equal (buffer-name) todos-regexp-items-buffer)))
3395 (re-search-forward (concat "^" (regexp-quote todos-category-done))
3396 nil t)
3397 (forward-line -1))))))
b28872ce 3398
18aef8a3
SB
3399(defun todos-forward-button (n &optional wrap display-message)
3400 ""
3401 (interactive "p\nd\nd")
3402 (forward-button n wrap display-message)
3403 (and (bolp) (button-at (point))
3404 ;; Align with beginning of category label.
3405 (forward-char (+ 4 (length todos-categories-number-separator)))))
3406
3407(defun todos-backward-button (n &optional wrap display-message)
3408 ""
3409 (interactive "p\nd\nd")
3410 (backward-button n wrap display-message)
3411 (and (bolp) (button-at (point))
3412 ;; Align with beginning of category label.
3413 (forward-char (+ 4 (length todos-categories-number-separator)))))
3414
b28872ce 3415;; FIXME: (i) Extend search to other Todos files. (ii) Allow navigating among
616ffa8b
SB
3416;; hits. (But these features are effectively available with
3417;; todos-regexp-items-multifile, so maybe it's not worth the trouble here.)
b28872ce
SB
3418(defun todos-search ()
3419 "Search for a regular expression in this Todos file.
3420The search runs through the whole file and encompasses all and
3421only todo and done items; it excludes category names. Multiple
3422matches are shown sequentially, highlighted in `todos-search'
3423face."
3424 (interactive)
3425 (let ((regex (read-from-minibuffer "Enter a search string (regexp): "))
3426 (opoint (point))
3427 matches match cat in-done ov mlen msg)
3428 (widen)
3429 (goto-char (point-min))
3430 (while (not (eobp))
3431 (setq match (re-search-forward regex nil t))
3432 (goto-char (line-beginning-position))
3433 (unless (or (equal (point) 1)
3434 (looking-at (concat "^" (regexp-quote todos-category-beg))))
3435 (if match (push match matches)))
3436 (forward-line))
3437 (setq matches (reverse matches))
3438 (if matches
3439 (catch 'stop
3440 (while matches
3441 (setq match (pop matches))
3442 (goto-char match)
3443 (todos-item-start)
3444 (when (looking-at todos-done-string-start)
3445 (setq in-done t))
3446 (re-search-backward (concat "^" (regexp-quote todos-category-beg)
3447 "\\(.*\\)\n") nil t)
3448 (setq cat (match-string-no-properties 1))
3449 (todos-category-number cat)
3450 (todos-category-select)
3451 (if in-done
3452 (unless todos-show-with-done (todos-hide-show-done-items)))
3453 (goto-char match)
3454 (setq ov (make-overlay (- (point) (length regex)) (point)))
3455 (overlay-put ov 'face 'todos-search)
3456 (when matches
3457 (setq mlen (length matches))
3458 (if (y-or-n-p
3459 (if (> mlen 1)
3460 (format "There are %d more matches; go to next match? "
3461 mlen)
3462 "There is one more match; go to it? "))
3463 (widen)
3464 (throw 'stop (setq msg (if (> mlen 1)
3465 (format "There are %d more matches."
3466 mlen)
3467 "There is one more match."))))))
3468 (setq msg "There are no more matches."))
3469 (todos-category-select)
3470 (goto-char opoint)
3471 (message "No match for \"%s\"" regex))
3472 (when msg
3473 (if (y-or-n-p (concat msg "\nUnhighlight matches? "))
3474 (todos-clear-matches)
3475 (message "You can unhighlight the matches later by typing %s"
3476 (key-description (car (where-is-internal
3477 'todos-clear-matches))))))))
3478
3479(defun todos-clear-matches ()
3480 "Remove highlighting on matches found by todos-search."
3481 (interactive)
3482 (remove-overlays 1 (1+ (buffer-size)) 'face 'todos-search))
3483
3484;; ---------------------------------------------------------------------------
3485;;; Display Commands
3486
3487(defun todos-hide-show-item-numbering ()
3488 ""
3489 (interactive)
3490 (todos-reset-prefix 'todos-number-priorities (not todos-number-priorities)))
3491
3492(defun todos-hide-show-done-items ()
3493 "Show hidden or hide visible done items in current category."
3494 (interactive)
3495 (if (zerop (todos-get-count 'done (todos-current-category)))
3496 (message "There are no done items in this category.")
3497 (save-excursion
3498 (goto-char (point-min))
3499 (let ((todos-show-with-done (not (re-search-forward
3500 todos-done-string-start nil t))))
3501 (todos-category-select)))))
3502
3503(defun todos-show-done-only ()
3504 "Switch between displaying only done or only todo items."
3505 (interactive)
3506 (setq todos-show-done-only (not todos-show-done-only))
3507 (todos-category-select))
3508
3509(defun todos-highlight-item ()
616ffa8b 3510 "Highlight or unhighlight the todo item the cursor is on."
b28872ce
SB
3511 (interactive)
3512 (require 'hl-line)
3513 (if hl-line-mode
3514 (hl-line-mode -1)
3515 (hl-line-mode 1)))
3516
616ffa8b
SB
3517(defun todos-hide-show-date-time ()
3518 "Hide or show date-time header of todo items in the current file."
3519 (interactive)
b28872ce
SB
3520 (save-excursion
3521 (save-restriction
3522 (goto-char (point-min))
3523 (let ((ovs (overlays-in (point) (1+ (point))))
3524 ov hidden)
3525 (while ovs
3526 (setq ov (pop ovs))
3527 (if (equal (overlay-get ov 'display) "")
3528 (setq ovs nil hidden t)))
b28872ce 3529 (widen)
616ffa8b 3530 (goto-char (point-min))
b28872ce
SB
3531 (if hidden
3532 (remove-overlays (point-min) (point-max) 'display "")
3533 (while (not (eobp))
3534 (when (re-search-forward
3535 (concat todos-date-string-start todos-date-pattern
3536 "\\( " diary-time-regexp "\\)?"
3537 (regexp-quote todos-nondiary-end) "? ")
3538 nil t)
3539 (unless (save-match-data (todos-done-item-p))
3540 (setq ov (make-overlay (match-beginning 0) (match-end 0) nil t))
3541 (overlay-put ov 'display "")))
3542 (todos-forward-item)))))))
3543
3544(defun todos-mark-unmark-item (&optional n all)
3545 "Mark item at point if unmarked, or unmark it if marked.
3546
3547With a positive numerical prefix argument N, change the
3548markedness of the next N items. With non-nil argument ALL, mark
3549all visible items in the category (depending on visibility, all
3550todo and done items, or just todo or just done items).
3551
3552The mark is the character \"*\" inserted in front of the item's
3553priority number or the `todos-prefix' string; if `todos-prefix'
3554is \"*\", then the mark is \"@\"."
3555 (interactive "p")
3556 (if all (goto-char (point-min)))
3557 (unless (> n 0) (setq n 1))
3558 (let ((i 0))
3559 (while (or (and all (not (eobp)))
3560 (< i n))
3561 (let* ((cat (todos-current-category))
3562 (ov (todos-marked-item-p))
3563 (marked (assoc cat todos-categories-with-marks)))
3564 (if (and ov (not all))
3565 (progn
3566 (delete-overlay ov)
3567 (if (= (cdr marked) 1) ; Deleted last mark in this category.
3568 (setq todos-categories-with-marks
3569 (assq-delete-all cat todos-categories-with-marks))
3570 (setcdr marked (1- (cdr marked)))))
3571 (when (todos-item-start)
3572 (unless (and all (todos-marked-item-p))
3573 (setq ov (make-overlay (point) (point)))
3574 (overlay-put ov 'before-string todos-item-mark)
3575 (if marked
3576 (setcdr marked (1+ (cdr marked)))
3577 (push (cons cat 1) todos-categories-with-marks))))))
3578 (todos-forward-item)
3579 (setq i (1+ i)))))
3580
3581(defun todos-mark-category ()
3582 "Put the \"*\" mark on all items in this category.
3583\(If `todos-prefix' is \"*\", then the mark is \"@\".)"
3584 (interactive)
3585 (todos-mark-unmark-item 0 t))
3586
3587(defun todos-unmark-category ()
3588 "Remove the \"*\" mark from all items in this category.
3589\(If `todos-prefix' is \"*\", then the mark is \"@\".)"
3590 (interactive)
3591 (remove-overlays (point-min) (point-max) 'before-string todos-item-mark)
3592 (setq todos-categories-with-marks
3593 (delq (assoc (todos-current-category) todos-categories-with-marks)
3594 todos-categories-with-marks)))
3595
3596;; ---------------------------------------------------------------------------
3597;;; Item filtering commands
3598
3599(defun todos-set-top-priorities-in-file ()
3600 "Set number of top priorities for this file.
3601See `todos-set-top-priorities' for more details."
3602 (interactive)
3603 (todos-set-top-priorities))
3604
3605(defun todos-set-top-priorities-in-category ()
3606 "Set number of top priorities for this category.
3607See `todos-set-top-priorities' for more details."
3608 (interactive)
3609 (todos-set-top-priorities t))
3610
3611(defun todos-top-priorities (&optional num)
3612 "List top priorities of each category in `todos-filter-files'.
3613Number of entries for each category is given by NUM, which
3614defaults to `todos-show-priorities'."
3615 (interactive "P")
3616 (let ((arg (if num (cons 'top num) 'top))
3617 (buf todos-top-priorities-buffer)
3618 (file todos-current-todos-file))
3619 (todos-filter-items arg)
3620 (todos-filtered-buffer-name buf file)))
3621
3622(defun todos-top-priorities-multifile (&optional arg)
3623 "List top priorities of each category in `todos-filter-files'.
3624
3625If the prefix argument ARG is a number, this is the maximum
3626number of top priorities to list in each category. If the prefix
3627argument is `C-u', prompt for which files to filter and use
3628`todos-show-priorities' as the number of top priorities to list
3629in each category. If the prefix argument is `C-uC-u', prompt
3630both for which files to filter and for how many top priorities to
3631list in each category."
3632 (interactive "P")
3633 (let* ((buf todos-top-priorities-buffer)
3634 files
3635 (pref (if (numberp arg)
3636 (cons 'top arg)
3637 (setq files (if (or (consp arg)
3638 (null todos-filter-files))
a820dfe8
SB
3639 (progn (todos-multiple-filter-files)
3640 todos-multiple-filter-files)
b28872ce
SB
3641 todos-filter-files))
3642 (if (equal arg '(16))
3643 (cons 'top (read-number
3644 "Enter number of top priorities to show: "
3645 todos-show-priorities))
3646 'top))))
3647 (todos-filter-items pref t)
3648 (todos-filtered-buffer-name buf files)))
0e89c3fc 3649
b28872ce
SB
3650(defun todos-diary-items ()
3651 "Display todo items for diary inclusion in this Todos file."
58c7641d 3652 (interactive)
b28872ce
SB
3653 (let ((buf todos-diary-items-buffer)
3654 (file todos-current-todos-file))
3655 (todos-filter-items 'diary)
3656 (todos-filtered-buffer-name buf file)))
d04d6b95 3657
b28872ce
SB
3658(defun todos-diary-items-multifile (&optional arg)
3659 "Display todo items for diary inclusion in one or more Todos file.
3660The files are those listed in `todos-filter-files'."
3661 (interactive "P")
3662 (let ((buf todos-diary-items-buffer)
3663 (files (if (or arg (null todos-filter-files))
a820dfe8
SB
3664 (progn (todos-multiple-filter-files)
3665 todos-multiple-filter-files)
b28872ce
SB
3666 todos-filter-files)))
3667 (todos-filter-items 'diary t)
3668 (todos-filtered-buffer-name buf files)))
3669
3670(defun todos-regexp-items ()
3671 "Display todo items matching a user-entered regular expression.
3672The items are those in the current Todos file."
0e89c3fc 3673 (interactive)
b28872ce
SB
3674 (let ((buf todos-regexp-items-buffer)
3675 (file todos-current-todos-file))
3676 (todos-filter-items 'regexp)
3677 (todos-filtered-buffer-name buf file)))
3678
3679(defun todos-regexp-items-multifile (&optional arg)
3680 "Display todo items matching a user-entered regular expression.
3681The items are those in the files listed in `todos-filter-files'."
3682 (interactive "P")
3683 (let ((buf todos-regexp-items-buffer)
3684 (files (if (or arg (null todos-filter-files))
a820dfe8
SB
3685 (progn (todos-multiple-filter-files)
3686 todos-multiple-filter-files)
b28872ce
SB
3687 todos-filter-files)))
3688 (todos-filter-items 'regexp t)
3689 (todos-filtered-buffer-name buf files)))
58c7641d 3690
bbf95285 3691;; ---------------------------------------------------------------------------
0e89c3fc 3692;;; Editing Commands
58c7641d 3693
0e89c3fc
SB
3694(defun todos-add-file ()
3695 "Name and add a new Todos file.
3696Interactively, prompt for a category and display it.
3697Noninteractively, return the name of the new file."
d04d6b95 3698 (interactive)
2a9e69d6 3699 (let ((prompt (concat "Enter name of new Todos file "
0e89c3fc 3700 "(TAB or SPC to see current names): "))
459c6e93
SB
3701 file)
3702 (setq file (todos-read-file-name prompt))
0e89c3fc
SB
3703 (with-current-buffer (get-buffer-create file)
3704 (erase-buffer)
3705 (write-region (point-min) (point-max) file nil 'nomessage nil t)
3706 (kill-buffer file))
36341a66 3707 (todos-reevaluate-filelist-defcustoms)
0e89c3fc
SB
3708 (if (called-interactively-p)
3709 (progn
2a9e69d6
SB
3710 (set-window-buffer (selected-window)
3711 (set-buffer (find-file-noselect file)))
0e89c3fc
SB
3712 (setq todos-current-todos-file file)
3713 (todos-show))
3714 file)))
3715
b28872ce
SB
3716;;; Category editing commands
3717
0e89c3fc
SB
3718(defun todos-add-category (&optional cat)
3719 "Add a new category to the current Todos file.
2a9e69d6 3720Called interactively, prompts for category name, then visits the
0e89c3fc 3721category in Todos mode. Non-interactively, argument CAT provides
2a9e69d6 3722the category name and the return value is the category number."
0e89c3fc
SB
3723 (interactive)
3724 (let* ((buffer-read-only)
0e89c3fc
SB
3725 (num (1+ (length todos-categories)))
3726 (counts (make-vector 4 0))) ; [todo diary done archived]
bbf95285
SB
3727 ;; If cat is passed from caller, don't prompt, unless it is "",
3728 ;; which means the file was just added and has no category yet.
3729 (unless (and cat (> (length cat) 0))
2a9e69d6
SB
3730 (setq cat (todos-read-category "Enter new category name: " nil t)))
3731 (setq todos-categories (append todos-categories (list (cons cat counts))))
2a9e69d6
SB
3732 (widen)
3733 (goto-char (point-max))
3734 (save-excursion ; Save point for todos-category-select.
3735 (insert todos-category-beg cat "\n\n" todos-category-done "\n"))
3736 (todos-update-categories-sexp)
b28872ce
SB
3737 ;; If invoked by user, display the newly added category, if called
3738 ;; programmatically return the category number to the caller.
3739 (if (called-interactively-p 'any)
2a9e69d6
SB
3740 (progn
3741 (setq todos-category-number num)
3742 (todos-category-select))
3743 num)))
0e89c3fc
SB
3744
3745(defun todos-rename-category ()
3746 "Rename current Todos category.
3747If this file has an archive containing this category, rename the
3748category there as well."
3749 (interactive)
3750 (let* ((cat (todos-current-category))
3751 (new (read-from-minibuffer (format "Rename category \"%s\" to: " cat))))
3752 (setq new (todos-validate-name new 'category))
3753 (let* ((ofile todos-current-todos-file)
3754 (archive (concat (file-name-sans-extension ofile) ".toda"))
3755 (buffers (append (list ofile)
3756 (unless (zerop (todos-get-count 'archived cat))
3757 (list archive)))))
3758 (dolist (buf buffers)
3759 (with-current-buffer (find-file-noselect buf)
58c7641d 3760 (let (buffer-read-only)
0e89c3fc
SB
3761 (setq todos-categories (todos-set-categories))
3762 (save-excursion
3763 (save-restriction
3764 (setcar (assoc cat todos-categories) new)
3765 (widen)
3766 (goto-char (point-min))
3767 (todos-update-categories-sexp)
3768 (re-search-forward (concat (regexp-quote todos-category-beg)
3769 "\\(" (regexp-quote cat) "\\)\n")
58c7641d 3770 nil t)
0e89c3fc 3771 (replace-match new t t nil 1)))))))
2a9e69d6 3772 (force-mode-line-update))
0e89c3fc
SB
3773 (save-excursion (todos-category-select)))
3774
3775(defun todos-delete-category (&optional arg)
3776 "Delete current Todos category provided it is empty.
3777With ARG non-nil delete the category unconditionally,
3778i.e. including all existing todo and done items."
3779 (interactive "P")
2a9e69d6
SB
3780 (let* ((file todos-current-todos-file)
3781 (cat (todos-current-category))
0e89c3fc
SB
3782 (todo (todos-get-count 'todo cat))
3783 (done (todos-get-count 'done cat))
3784 (archived (todos-get-count 'archived cat)))
2a9e69d6
SB
3785 (if (and (not arg)
3786 (or (> todo 0) (> done 0)))
3787 (message "%s" (substitute-command-keys
3788 (concat "To delete a non-empty category, "
3789 "type C-u \\[todos-delete-category].")))
3790 (when (cond ((= (length todos-categories) 1)
3791 (y-or-n-p (concat "This is the only category in this file; "
3792 "deleting it will also delete the file.\n"
3793 "Do you want to proceed? ")))
3794 ((> archived 0)
3795 (y-or-n-p (concat "This category has archived items; "
3796 "the archived category will remain\n"
3797 "after deleting the todo category. "
3798 "Do you still want to delete it\n"
6be04162 3799 "(see 'todos-skip-archived-categories' "
2a9e69d6
SB
3800 "for another option)? ")))
3801 (t
3802 (y-or-n-p (concat "Permanently remove category \"" cat
3803 "\"" (and arg " and all its entries")
3804 "? "))))
3805 (widen)
3806 (let ((buffer-read-only)
3807 (beg (re-search-backward
3808 (concat "^" (regexp-quote (concat todos-category-beg cat))
3809 "\n") nil t))
3810 (end (if (re-search-forward
3811 (concat "\n\\(" (regexp-quote todos-category-beg)
3812 ".*\n\\)") nil t)
3813 (match-beginning 1)
3814 (point-max))))
3815 (remove-overlays beg end)
3816 (delete-region beg end)
3817 (if (= (length todos-categories) 1)
3818 ;; If deleted category was the only one, delete the file.
3819 (progn
36341a66 3820 (todos-reevaluate-filelist-defcustoms)
2a9e69d6
SB
3821 ;; Skip confirming killing the archive buffer if it has been
3822 ;; modified and not saved.
3823 (set-buffer-modified-p nil)
3824 (delete-file file)
3825 (kill-buffer)
3826 (message "Deleted Todos file %s." file))
7464f422
SB
3827 (setq todos-categories (delete (assoc cat todos-categories)
3828 todos-categories))
2a9e69d6
SB
3829 (todos-update-categories-sexp)
3830 (setq todos-category-number
3831 (1+ (mod todos-category-number (length todos-categories))))
3832 (todos-category-select)
3833 (goto-char (point-min))
3834 (message "Deleted category %s." cat)))))))
3f031767 3835
0e89c3fc
SB
3836(defun todos-move-category ()
3837 "Move current category to a different Todos file.
3838If current category has archived items, also move those to the
3839archive of the file moved to, creating it if it does not exist."
58c7641d 3840 (interactive)
0e89c3fc
SB
3841 (when (or (> (length todos-categories) 1)
3842 (y-or-n-p (concat "This is the only category in this file; "
3843 "moving it will also delete the file.\n"
3844 "Do you want to proceed? ")))
3845 (let* ((ofile todos-current-todos-file)
3846 (cat (todos-current-category))
616ffa8b
SB
3847 (nfile (todos-read-file-name
3848 "Choose a Todos file to move this category to: " nil t))
0e89c3fc
SB
3849 (archive (concat (file-name-sans-extension ofile) ".toda"))
3850 (buffers (append (list ofile)
3851 (unless (zerop (todos-get-count 'archived cat))
3852 (list archive))))
3853 new)
616ffa8b
SB
3854 (while (equal (file-truename nfile) (file-truename ofile))
3855 (setq nfile (todos-read-file-name
3856 "Choose a file distinct from this file: " nil t)))
0e89c3fc
SB
3857 (dolist (buf buffers)
3858 (with-current-buffer (find-file-noselect buf)
3859 (widen)
3860 (goto-char (point-max))
3861 (let* ((beg (re-search-backward
11aa0eef
SB
3862 (concat "^" (regexp-quote (concat todos-category-beg cat))
3863 "$")
0e89c3fc
SB
3864 nil t))
3865 (end (if (re-search-forward
3866 (concat "^" (regexp-quote todos-category-beg))
3867 nil t 2)
3868 (match-beginning 0)
3869 (point-max)))
3870 (content (buffer-substring-no-properties beg end))
3871 (counts (cdr (assoc cat todos-categories)))
3872 buffer-read-only)
3873 ;; Move the category to the new file. Also update or create
3874 ;; archive file if necessary.
3875 (with-current-buffer
3876 (find-file-noselect
3877 ;; Regenerate todos-archives in case there
3878 ;; is a newly created archive.
3879 (if (member buf (funcall todos-files-function t))
3880 (concat (file-name-sans-extension nfile) ".toda")
3881 nfile))
3882 (let* ((nfile-short (todos-short-file-name nfile))
3883 (prompt (concat
3884 (format "Todos file \"%s\" already has "
3885 nfile-short)
3886 (format "the category \"%s\";\n" cat)
3887 "enter a new category name: "))
3888 buffer-read-only)
3889 (widen)
3890 (goto-char (point-max))
3891 (insert content)
3892 ;; If the file moved to has a category with the same
3893 ;; name, rename the moved category.
3894 (when (assoc cat todos-categories)
3895 (unless (member (file-truename (buffer-file-name))
3896 (funcall todos-files-function t))
3897 (setq new (read-from-minibuffer prompt))
3898 (setq new (todos-validate-name new 'category))))
3899 ;; Replace old with new name in Todos and archive files.
3900 (when new
3901 (goto-char (point-max))
3902 (re-search-backward
3903 (concat "^" (regexp-quote todos-category-beg)
11aa0eef 3904 "\\(" (regexp-quote cat) "\\)$") nil t)
0e89c3fc
SB
3905 (replace-match new nil nil nil 1)))
3906 (setq todos-categories
3907 (append todos-categories (list (cons new counts))))
3908 (todos-update-categories-sexp)
3909 ;; If archive was just created, save it to avoid "File <xyz> no
3910 ;; longer exists!" message on invoking
3911 ;; `todos-view-archived-items'. FIXME: maybe better to save
3912 ;; unconditionally?
3913 (unless (file-exists-p (buffer-file-name))
3914 (save-buffer))
3915 (todos-category-number (or new cat))
3916 (todos-category-select))
3917 ;; Delete the category from the old file, and if that was the
3918 ;; last category, delete the file. Also handle archive file
3919 ;; if necessary.
3920 (remove-overlays beg end)
3921 (delete-region beg end)
3922 (goto-char (point-min))
3923 ;; Put point after todos-categories sexp.
3924 (forward-line)
3925 (if (eobp) ; Aside from sexp, file is empty.
3926 (progn
3927 ;; Skip confirming killing the archive buffer.
3928 (set-buffer-modified-p nil)
3929 (delete-file todos-current-todos-file)
3930 (kill-buffer)
3931 (when (member todos-current-todos-file todos-files)
36341a66 3932 (todos-reevaluate-filelist-defcustoms)))
7464f422
SB
3933 (setq todos-categories (delete (assoc cat todos-categories)
3934 todos-categories))
0e89c3fc
SB
3935 (todos-update-categories-sexp)
3936 (todos-category-select)))))
3937 (set-window-buffer (selected-window)
3938 (set-buffer (find-file-noselect nfile)))
3939 (todos-category-number (or new cat))
3940 (todos-category-select))))
2c173503 3941
0e89c3fc
SB
3942(defun todos-merge-category ()
3943 "Merge current category into another category in this file.
18aef8a3 3944
0e89c3fc 3945The current category's todo and done items are appended to the
18aef8a3
SB
3946chosen goal category's todo and done items, respectively. The
3947goal category becomes the current category, and the previous
3948current category is deleted.
3949
3950If both the first and goal categories also have archived items,
3951the former are merged to the latter. If only the first category
3952has archived items, the archived category is renamed to the goal
3953category."
0e89c3fc 3954 (interactive)
18aef8a3
SB
3955 (let* ((tfile todos-current-todos-file)
3956 (archive (concat (file-name-sans-extension tfile) ".toda"))
3957 (cat (todos-current-category))
3958 (goal (todos-read-category "Category to merge to: " t))
3959 archived-count here)
3960 ;; Merge in todo file.
3961 (with-current-buffer (get-buffer (find-file-noselect tfile))
3962 (widen)
3963 (let* ((buffer-read-only nil)
3964 (cbeg (progn
3965 (re-search-backward
0e89c3fc 3966 (concat "^" (regexp-quote todos-category-beg)) nil t)
18aef8a3
SB
3967 (point-marker)))
3968 (tbeg (progn (forward-line) (point-marker)))
3969 (dbeg (progn
3970 (re-search-forward
3971 (concat "^" (regexp-quote todos-category-done)) nil t)
3972 (forward-line) (point-marker)))
3973 ;; Omit empty line between todo and done items.
3974 (tend (progn (forward-line -2) (point-marker)))
3975 (cend (progn
3976 (if (re-search-forward
3977 (concat "^" (regexp-quote todos-category-beg)) nil t)
3978 (progn
3979 (goto-char (match-beginning 0))
3980 (point-marker))
3981 (point-max-marker))))
3982 (todo (buffer-substring-no-properties tbeg tend))
3983 (done (buffer-substring-no-properties dbeg cend)))
3984 (goto-char (point-min))
3985 ;; Merge any todo items.
3986 (unless (zerop (length todo))
3987 (re-search-forward
11aa0eef
SB
3988 (concat "^" (regexp-quote (concat todos-category-beg goal)) "$")
3989 nil t)
18aef8a3
SB
3990 (re-search-forward
3991 (concat "^" (regexp-quote todos-category-done)) nil t)
3992 (forward-line -1)
3993 (setq here (point-marker))
3994 (insert todo)
3995 (todos-update-count 'todo (todos-get-count 'todo cat) goal))
3996 ;; Merge any done items.
3997 (unless (zerop (length done))
3998 (goto-char (if (re-search-forward
3999 (concat "^" (regexp-quote todos-category-beg)) nil t)
4000 (match-beginning 0)
4001 (point-max)))
4002 (when (zerop (length todo)) (setq here (point-marker)))
4003 (insert done)
4004 (todos-update-count 'done (todos-get-count 'done cat) goal))
4005 (remove-overlays cbeg cend)
4006 (delete-region cbeg cend)
4007 (setq todos-categories (delete (assoc cat todos-categories)
4008 todos-categories))
4009 (todos-update-categories-sexp)
4010 (mapc (lambda (m) (set-marker m nil)) (list cbeg tbeg dbeg tend cend))))
4011 (when (file-exists-p archive)
4012 ;; Merge in archive file.
4013 (with-current-buffer (get-buffer (find-file-noselect archive))
4014 (widen)
4015 (goto-char (point-min))
4016 (let ((buffer-read-only nil)
4017 (cbeg (save-excursion
4018 (when (re-search-forward
4019 (concat "^" (regexp-quote
11aa0eef 4020 (concat todos-category-beg cat)) "$")
18aef8a3
SB
4021 nil t)
4022 (goto-char (match-beginning 0))
4023 (point-marker))))
4024 (gbeg (save-excursion
4025 (when (re-search-forward
4026 (concat "^" (regexp-quote
11aa0eef 4027 (concat todos-category-beg goal)) "$")
18aef8a3
SB
4028 nil t)
4029 (goto-char (match-beginning 0))
4030 (point-marker))))
4031 cend carch)
4032 (when cbeg
4033 (setq archived-count (todos-get-count 'done cat))
4034 (setq cend (save-excursion
4035 (if (re-search-forward
4036 (concat "^" (regexp-quote todos-category-beg))
4037 nil t)
4038 (match-beginning 0)
4039 (point-max))))
4040 (setq carch (save-excursion (goto-char cbeg) (forward-line)
4041 (buffer-substring-no-properties (point) cend)))
4042 ;; If both categories of the merge have archived items, merge the
4043 ;; source items to the goal items, else "merge" by renaming the
4044 ;; source category to goal.
4045 (if gbeg
4046 (progn
4047 (goto-char (if (re-search-forward
4048 (concat "^" (regexp-quote todos-category-beg))
4049 nil t)
4050 (match-beginning 0)
4051 (point-max)))
4052 (insert carch)
4053 (remove-overlays cbeg cend)
4054 (delete-region cbeg cend))
4055 (goto-char cbeg)
4056 (search-forward cat)
4057 (replace-match goal))
4058 (setq todos-categories (todos-make-categories-list t))
4059 (todos-update-categories-sexp)))))
4060 (with-current-buffer (get-file-buffer tfile)
4061 (when archived-count
4062 (unless (zerop archived-count)
4063 (todos-update-count 'archived archived-count goal)
4064 (todos-update-categories-sexp)))
0e89c3fc 4065 (todos-category-number goal)
18aef8a3
SB
4066 ;; If there are only merged done items, show them.
4067 (let ((todos-show-with-done (zerop (todos-get-count 'todo goal))))
4068 (todos-category-select)
4069 ;; Put point on the first merged item.
4070 (goto-char here)))
4071 (set-marker here nil)))
2c173503 4072
616ffa8b
SB
4073(defun todos-set-category-priority (&optional arg)
4074 "Change priority of category at point in Todos Categories buffer.
4075
4076With ARG nil, prompt for the new priority number. Alternatively,
4077the new priority can be provided by a numerical prefix ARG.
4078Otherwise, if ARG is either of the symbols `raise' or `lower',
4079raise or lower the category's priority by one."
4080 (interactive "P")
4081 (let ((curnum (save-excursion
4082 ;; Get the number representing the priority of the category
4083 ;; on the current line.
4084 (forward-line 0) (skip-chars-forward " ") (number-at-point))))
4085 (when curnum ; Do nothing if we're not on a category line.
4086 (let* ((maxnum (length todos-categories))
4087 (prompt (format "Set category priority (1-%d): " maxnum))
4088 (col (current-column))
4089 (buffer-read-only nil)
4090 (priority (cond ((and (eq arg 'raise) (> curnum 1))
4091 (1- curnum))
4092 ((and (eq arg 'lower) (< curnum maxnum))
4093 (1+ curnum))))
4094 candidate)
4095 (while (not priority)
4096 (setq candidate (or arg (read-number prompt)))
4097 (setq arg nil)
4098 (setq prompt
4099 (cond ((or (< candidate 1) (> candidate maxnum))
4100 (format "Priority must be an integer between 1 and %d: "
4101 maxnum))
4102 ((= candidate curnum)
4103 "Choose a different priority than the current one: ")))
4104 (unless prompt (setq priority candidate)))
4105 (let* ((lower (< curnum priority)) ; Priority is being lowered.
4106 (head (butlast todos-categories
4107 (apply (if lower 'identity '1+)
4108 (list (- maxnum priority)))))
4109 (tail (nthcdr (apply (if lower 'identity '1-) (list priority))
4110 todos-categories))
4111 ;; Category's name and items counts list.
4112 (catcons (nth (1- curnum) todos-categories))
4113 (todos-categories (nconc head (list catcons) tail))
4114 newcats)
4115 (when lower (setq todos-categories (nreverse todos-categories)))
4116 (setq todos-categories (delete-dups todos-categories))
4117 (when lower (setq todos-categories (nreverse todos-categories)))
4118 (setq newcats todos-categories)
4119 (kill-buffer)
4120 (with-current-buffer (find-buffer-visiting todos-current-todos-file)
4121 (setq todos-categories newcats)
4122 (todos-update-categories-sexp))
4123 (todos-display-categories)
4124 (forward-line (1+ priority))
4125 (forward-char col))))))
b28872ce 4126
616ffa8b
SB
4127(defun todos-raise-category-priority ()
4128 "Raise priority of category at point in Todos Categories buffer."
b28872ce 4129 (interactive)
616ffa8b 4130 (todos-set-category-priority 'raise))
b28872ce 4131
616ffa8b
SB
4132(defun todos-lower-category-priority ()
4133 "Lower priority of category at point in Todos Categories buffer."
b28872ce 4134 (interactive)
616ffa8b 4135 (todos-set-category-priority 'lower))
b28872ce
SB
4136
4137;; ---------------------------------------------------------------------------
4138;;; Item editing commands
4139
0e89c3fc
SB
4140;; FIXME: make insertion options customizable per category?
4141;;;###autoload
4142(defun todos-insert-item (&optional arg diary nonmarking date-type time
4143 region-or-here)
4144 "Add a new Todo item to a category.
4145\(See the note at the end of this document string about key
4146bindings and convenience commands derived from this command.)
f730d273 4147
0e89c3fc
SB
4148With no (or nil) prefix argument ARG, add the item to the current
4149category; with one prefix argument (C-u), prompt for a category
4150from the current Todos file; with two prefix arguments (C-u C-u),
4151first prompt for a Todos file, then a category in that file. If
4152a non-existing category is entered, ask whether to add it to the
4153Todos file; if answered affirmatively, add the category and
4154insert the item there.
d04d6b95 4155
0e89c3fc
SB
4156When argument DIARY is non-nil, this overrides the intent of the
4157user option `todos-include-in-diary' for this item: if
4158`todos-include-in-diary' is nil, include the item in the Fancy
4159Diary display, and if it is non-nil, exclude the item from the
4160Fancy Diary display. When DIARY is nil, `todos-include-in-diary'
4161has its intended effect.
58c7641d 4162
0e89c3fc
SB
4163When the item is included in the Fancy Diary display and the
4164argument NONMARKING is non-nil, this overrides the intent of the
4165user option `todos-diary-nonmarking' for this item: if
4166`todos-diary-nonmarking' is nil, append `diary-nonmarking-symbol'
4167to the item, and if it is non-nil, omit `diary-nonmarking-symbol'.
d04d6b95 4168
0e89c3fc
SB
4169The argument DATE-TYPE determines the content of the item's
4170mandatory date header string and how it is added:
4171- If DATE-TYPE is the symbol `calendar', the Calendar pops up and
4172 when the user puts the cursor on a date and hits RET, that
4173 date, in the format set by `calendar-date-display-form',
4174 becomes the date in the header.
18aef8a3
SB
4175- If DATE-TYPE is a string matching the regexp
4176 `todos-date-pattern', that string becomes the date in the
4177 header. This case is for the command
4178 `todos-insert-item-from-calendar' which is called from the
4179 Calendar.
0e89c3fc
SB
4180- If DATE-TYPE is the symbol `date', the header contains the date
4181 in the format set by `calendar-date-display-form', with year,
4182 month and day individually prompted for (month with tab
4183 completion).
4184- If DATE-TYPE is the symbol `dayname' the header contains a
4185 weekday name instead of a date, prompted for with tab
4186 completion.
4187- If DATE-TYPE has any other value (including nil or none) the
4188 header contains the current date (in the format set by
4189 `calendar-date-display-form').
58c7641d 4190
0e89c3fc
SB
4191With non-nil argument TIME prompt for a time string, which must
4192match `diary-time-regexp'. Typing `<return>' at the prompt
4193returns the current time, if the user option
4194`todos-always-add-time-string' is non-nil, otherwise the empty
4195string (i.e., no time string). If TIME is absent or nil, add or
4196omit the current time string according as
4197`todos-always-add-time-string' is non-nil or nil, respectively.
58c7641d 4198
0e89c3fc
SB
4199The argument REGION-OR-HERE determines the source and location of
4200the new item:
4201- If the REGION-OR-HERE is the symbol `here', prompt for the text
4202 of the new item and insert it directly above the todo item at
4203 point (hence lowering the priority of the remaining items), or
4204 if point is on the empty line below the last todo item, insert
4205 the new item there. An error is signalled if
4206 `todos-insert-item' is invoked with `here' outside of the
4207 current category.
4208- If REGION-OR-HERE is the symbol `region', use the region of the
4209 current buffer as the text of the new item, depending on the
4210 value of user option `todos-use-only-highlighted-region': if
4211 this is non-nil, then use the region only when it is
4212 highlighted; otherwise, use the region regardless of
4213 highlighting. An error is signalled if there is no region in
4214 the current buffer. Prompt for the item's priority in the
4215 category (an integer between 1 and one more than the number of
4216 items in the category), and insert the item accordingly.
4217- If REGION-OR-HERE has any other value (in particular, nil or
4218 none), prompt for the text and the item's priority, and insert
4219 the item accordingly.
58c7641d 4220
0e89c3fc
SB
4221To facilitate using these arguments when inserting a new todo
4222item, convenience commands have been defined for all admissible
78fe7289
SB
4223combinations together with mnenomic key bindings based on on the
4224name of the arguments and their order in the command's argument
4225list: diar_y_ - nonmar_k_ing - _c_alendar or _d_ate or day_n_ame
4226- _t_ime - _r_egion or _h_ere. These key combinations are
4227appended to the basic insertion key (i) and keys that allow a
4228following key must be doubled when used finally. For example,
4229`iyh' will insert a new item with today's date, marked according
4230to the DIARY argument described above, and with priority
4231according to the HERE argument; while `iyy' does the same except
4232the priority is not given by HERE but by prompting."
0e89c3fc
SB
4233;; An alternative interface for customizing key
4234;; binding is also provided with the function
4235;; `todos-insertion-bindings'." ;FIXME
4236 (interactive "P")
4237 (let ((region (eq region-or-here 'region))
4238 (here (eq region-or-here 'here)))
4239 (when region
2a9e69d6
SB
4240 (let (use-empty-active-region)
4241 (unless (and todos-use-only-highlighted-region (use-region-p))
4242 (error "There is no active region"))))
0e89c3fc
SB
4243 (let* ((buf (current-buffer))
4244 (new-item (if region
0e89c3fc
SB
4245 (buffer-substring-no-properties
4246 (region-beginning) (region-end))
4247 (read-from-minibuffer "Todo item: ")))
4248 (date-string (cond
4249 ((eq date-type 'date)
4250 (todos-read-date))
4251 ((eq date-type 'dayname)
4252 (todos-read-dayname))
4253 ((eq date-type 'calendar)
4254 (setq todos-date-from-calendar t)
d9f80d44
SB
4255 (or (todos-set-date-from-calendar)
4256 ;; If user exits Calendar before choosing
4257 ;; a date, cancel item insertion.
4258 (keyboard-quit)))
36341a66
SB
4259 ((and (stringp date-type)
4260 (string-match todos-date-pattern date-type))
18aef8a3
SB
4261 (setq todos-date-from-calendar date-type)
4262 (todos-set-date-from-calendar))
d16da867
SB
4263 (t
4264 ;; FIXME: We follow diary-insert-entry in
4265 ;; hardcoding abbreviated month name and no
4266 ;; day name in date string. Should this be
4267 ;; customizable?
4268 (calendar-date-string (calendar-current-date) t t))))
0e89c3fc
SB
4269 (time-string (or (and time (todos-read-time))
4270 (and todos-always-add-time-string
4271 (substring (current-time-string) 11 16)))))
4272 (setq todos-date-from-calendar nil)
36341a66 4273 (cond ((equal arg '(16))
0e89c3fc
SB
4274 (todos-jump-to-category nil t)
4275 (set-window-buffer
4276 (selected-window)
6be04162 4277 (set-buffer (find-buffer-visiting todos-global-current-todos-file))))
36341a66 4278 ((equal arg '(4))
0e89c3fc
SB
4279 (todos-jump-to-category)
4280 (set-window-buffer
4281 (selected-window)
6be04162 4282 (set-buffer (find-buffer-visiting todos-global-current-todos-file))))
0e89c3fc
SB
4283 (t
4284 (when (not (derived-mode-p 'todos-mode)) (todos-show))))
4285 (let (buffer-read-only)
4286 (setq new-item
4287 ;; Add date, time and diary marking as required.
4288 (concat (if (not (and diary (not todos-include-in-diary)))
4289 todos-nondiary-start
4290 (when (and nonmarking (not todos-diary-nonmarking))
4291 diary-nonmarking-symbol))
0833689a
SB
4292 date-string (when (and time-string ; Can be empty string.
4293 (not (zerop (length time-string))))
0e89c3fc
SB
4294 (concat " " time-string))
4295 (when (not (and diary (not todos-include-in-diary)))
4296 todos-nondiary-end)
4297 " " new-item))
4298 ;; Indent newlines inserted by C-q C-j if nonspace char follows.
4299 (setq new-item (replace-regexp-in-string
4300 "\\(\n\\)[^[:blank:]]"
4301 (concat "\n" (make-string todos-indent-to-here 32))
4302 new-item nil nil 1))
59ad682f
SB
4303 ;; FIXME: after jumping to another category due to `C-u i h',
4304 ;; item is inserted as first item -- ok?
0e89c3fc
SB
4305 (if here
4306 (cond ((not (eq major-mode 'todos-mode))
4307 (error "Cannot insert a todo item here outside of Todos mode"))
4308 ((not (eq buf (current-buffer)))
4309 (error "Cannot insert an item here after changing buffer"))
4310 ((or (todos-done-item-p)
4311 ;; Point on last blank line.
4312 (save-excursion (forward-line -1) (todos-done-item-p)))
4313 (error "Cannot insert a new item in the done item section"))
4314 (t
4315 (todos-insert-with-overlays new-item)))
4316 (todos-set-item-priority new-item (todos-current-category) t))
3af3cd0b
SB
4317 (todos-update-count 'todo 1)
4318 (if (or diary todos-include-in-diary) (todos-update-count 'diary 1))
0e89c3fc 4319 (todos-update-categories-sexp)))))
d04d6b95 4320
fd6c6328
SB
4321(defun todos-copy-item ()
4322 "Copy item at point and insert the copy as a new item."
4323 (interactive)
4324 (unless (or (todos-done-item-p) (looking-at "^$"))
4325 (let ((copy (todos-item-string))
4326 (diary-item (todos-diary-item-p)))
4327 (todos-set-item-priority copy (todos-current-category) t)
4328 (todos-update-count 'todo 1)
4329 (when diary-item (todos-update-count 'diary 1))
4330 (todos-update-categories-sexp))))
4331
0e89c3fc
SB
4332(defvar todos-date-from-calendar nil
4333 "Helper variable for setting item date from the Emacs Calendar.")
2c173503 4334
0e89c3fc
SB
4335(defun todos-set-date-from-calendar ()
4336 "Return string of date chosen from Calendar."
36341a66
SB
4337 (cond ((and (stringp todos-date-from-calendar)
4338 (string-match todos-date-pattern todos-date-from-calendar))
18aef8a3 4339 todos-date-from-calendar)
36341a66 4340 (todos-date-from-calendar
18aef8a3 4341 (let (calendar-view-diary-initially-flag)
d9f80d44
SB
4342 (calendar)) ; *Calendar* is now current buffer.
4343 (define-key calendar-mode-map [remap newline] 'exit-recursive-edit)
4344 ;; If user exits Calendar before choosing a date, clean up properly.
4345 (define-key calendar-mode-map
4346 [remap calendar-exit] (lambda ()
4347 (interactive)
4348 (progn
4349 (calendar-exit)
4350 (exit-recursive-edit))))
18aef8a3 4351 (message "Put cursor on a date and type <return> to set it.")
36341a66 4352 ;; FIXME: is there a better way than recursive-edit?
18aef8a3 4353 (recursive-edit)
d9f80d44
SB
4354 (unwind-protect
4355 (when (equal (buffer-name) calendar-buffer)
4356 (setq todos-date-from-calendar
4357 (calendar-date-string (calendar-cursor-to-date t) t t))
4358 (calendar-exit)
4359 todos-date-from-calendar)
4360 (define-key calendar-mode-map [remap newline] nil)
4361 (define-key calendar-mode-map [remap calendar-exit] nil)
4362 (unless (zerop (recursion-depth)) (exit-recursive-edit))
4363 (when (stringp todos-date-from-calendar)
4364 todos-date-from-calendar)))))
d04d6b95 4365
0e89c3fc
SB
4366(defun todos-delete-item ()
4367 "Delete at least one item in this category.
ee7412e4 4368
0e89c3fc
SB
4369If there are marked items, delete all of these; otherwise, delete
4370the item at point."
4371 (interactive)
18aef8a3
SB
4372 (let (ov)
4373 (unwind-protect
4374 (let* ((cat (todos-current-category))
4375 (marked (assoc cat todos-categories-with-marks))
4376 (item (unless marked (todos-item-string)))
4377 ;; FIXME: make confirmation an option?
4378 (answer (if marked
4379 (y-or-n-p "Permanently delete all marked items? ")
4380 (when item
4381 (setq ov (make-overlay
4382 (save-excursion (todos-item-start))
4383 (save-excursion (todos-item-end))))
4384 (overlay-put ov 'face 'todos-search)
4385 (y-or-n-p (concat "Permanently delete this item? ")))))
4386 (opoint (point))
4387 buffer-read-only)
4388 (when answer
4389 (and marked (goto-char (point-min)))
4390 (catch 'done
4391 (while (not (eobp))
4392 (if (or (and marked (todos-marked-item-p)) item)
4393 (progn
4394 (if (todos-done-item-p)
4395 (todos-update-count 'done -1)
4396 (todos-update-count 'todo -1 cat)
4397 (and (todos-diary-item-p) (todos-update-count 'diary -1)))
4398 (if ov (delete-overlay ov))
4399 (todos-remove-item)
4400 ;; Don't leave point below last item.
4401 (and item (bolp) (eolp) (< (point-min) (point-max))
4402 (todos-backward-item))
4403 (when item
4404 (throw 'done (setq item nil))))
4405 (todos-forward-item))))
4406 (when marked
4407 (remove-overlays (point-min) (point-max)
4408 'before-string todos-item-mark)
4409 (setq todos-categories-with-marks
4410 (assq-delete-all cat todos-categories-with-marks))
4411 (goto-char opoint))
4412 (todos-update-categories-sexp)
4413 (todos-prefix-overlays)))
4414 (if ov (delete-overlay ov)))))
0e89c3fc 4415
d16da867 4416(defun todos-edit-item (&optional arg)
0e89c3fc 4417 "Edit the Todo item at point.
d16da867
SB
4418
4419With non-nil prefix argument ARG, include the item's date/time
4420header, making it also editable; otherwise, include only the item
4421content.
4422
0e89c3fc
SB
4423If the item consists of only one logical line, edit it in the
4424minibuffer; otherwise, edit it in Todos Edit mode."
d16da867 4425 (interactive "P")
0e89c3fc 4426 (when (todos-item-string)
d16da867 4427 (let* ((opoint (point))
0e89c3fc
SB
4428 (start (todos-item-start))
4429 (item-beg (progn
4430 (re-search-forward
4431 (concat todos-date-string-start todos-date-pattern
4432 "\\( " diary-time-regexp "\\)?"
4433 (regexp-quote todos-nondiary-end) "?")
4434 (line-end-position) t)
4435 (1+ (- (point) start))))
d16da867
SB
4436 (header (substring (todos-item-string) 0 item-beg))
4437 (item (if arg (todos-item-string)
4438 (substring (todos-item-string) item-beg)))
0e89c3fc 4439 (multiline (> (length (split-string item "\n")) 1))
d16da867 4440 (buffer-read-only nil))
0e89c3fc 4441 (if multiline
d16da867
SB
4442 (todos-edit-multiline-item)
4443 (let ((new (concat (if arg "" header)
4444 (read-string "Edit: " (if arg
4445 (cons item item-beg)
4446 (cons item 0))))))
4447 (when arg
4448 (while (not (string-match (concat todos-date-string-start
4449 todos-date-pattern) new))
4450 (setq new (read-from-minibuffer
4451 "Item must start with a date: " new))))
0e89c3fc
SB
4452 ;; Indent newlines inserted by C-q C-j if nonspace char follows.
4453 (setq new (replace-regexp-in-string
4454 "\\(\n\\)[^[:blank:]]"
4455 (concat "\n" (make-string todos-indent-to-here 32)) new
4456 nil nil 1))
4457 ;; If user moved point during editing, make sure it moves back.
4458 (goto-char opoint)
4459 (todos-remove-item)
4460 (todos-insert-with-overlays new)
4461 (move-to-column item-beg))))))
3f031767 4462
0e89c3fc
SB
4463(defun todos-edit-multiline-item ()
4464 "Edit current Todo item in Todos Edit mode.
4465Use of newlines invokes `todos-indent' to insure compliance with
4466the format of Diary entries."
4467 (interactive)
4468 (todos-edit-multiline t))
3f031767 4469
0e89c3fc
SB
4470(defun todos-edit-multiline (&optional item)
4471 ""
4472 (interactive)
4473 ;; FIXME: should there be only one live Todos Edit buffer?
4474 ;; (let ((buffer-name todos-edit-buffer))
4475 (let ((buffer-name (generate-new-buffer-name todos-edit-buffer)))
4476 (set-window-buffer
4477 (selected-window)
4478 (set-buffer (make-indirect-buffer
4479 (file-name-nondirectory todos-current-todos-file)
4480 buffer-name)))
4481 (if item
4482 (narrow-to-region (todos-item-start) (todos-item-end))
4483 (widen))
4484 (todos-edit-mode)
0e89c3fc
SB
4485 (message "%s" (substitute-command-keys
4486 (concat "Type \\[todos-edit-quit] to check file format "
4487 "validity and return to Todos mode.\n")))))
3f031767 4488
0e89c3fc
SB
4489(defun todos-edit-quit ()
4490 "Return from Todos Edit mode to Todos mode.
d04d6b95 4491
0e89c3fc
SB
4492If the whole file was in Todos Edit mode, check before returning
4493whether the file is still a valid Todos file and if so, also
4494recalculate the Todos categories sexp, in case changes were made
4495in the number or names of categories."
4496 (interactive)
36341a66
SB
4497 ;; FIXME: Should do todos-check-format only if file was actually changed --
4498 ;; but how to tell?
0e89c3fc 4499 (when (eq (buffer-size) (- (point-max) (point-min)))
b28872ce 4500 (when (todos-check-format) (todos-repair-categories-sexp)))
0e89c3fc
SB
4501 (kill-buffer)
4502 ;; In case next buffer is not the one holding todos-current-todos-file.
4503 (todos-show))
3f031767 4504
d16da867
SB
4505(defun todos-edit-item-header-1 (what &optional inc)
4506 "Underlying function to edit items' date/time headers.
4507
4508The argument WHAT (passed by invoking commands) specifies what
4509part of the header to edit; possible values are these symbols:
4510`date', to edit the year, month, and day of the date string;
4511`time', to edit just the time string; `calendar', to select the
4512date from the Calendar; `today', to set the date to today's date;
4513`dayname', to set the date string to the name of a day or to
4514change the day name; and `year', `month' or `day', to edit only
4515these respective parts of the date string (`day' is the number of
4516the given day of the month, and `month' is either the name of the
4517given month or its number, depending on the value of
4518`calendar-date-display-form').
4519
4520The optional argument INC is a positive or negative integer
4521\(passed by invoking commands as a numerical prefix argument)
4522that in conjunction with the WHAT values `year', `month' or
4523`day', increments or decrements the specified date string
4524component by the specified number of suitable units, i.e., years,
4525months, or days, with automatic adjustment of the other date
4526string components as necessary.
4527
4528If there are marked items, apply the same edit to all of these;
4529otherwise, edit just the item at point."
0e89c3fc
SB
4530 (let* ((cat (todos-current-category))
4531 (marked (assoc cat todos-categories-with-marks))
d16da867 4532 (first t)
0e89c3fc 4533 (todos-date-from-calendar t)
d16da867
SB
4534 (buffer-read-only nil)
4535 ndate ntime year monthname month day
4536 dayname) ; Needed by calendar-date-display-form.
0e89c3fc
SB
4537 (save-excursion
4538 (or (and marked (goto-char (point-min))) (todos-item-start))
d16da867 4539 (catch 'end
0e89c3fc
SB
4540 (while (not (eobp))
4541 (and marked
4542 (while (not (todos-marked-item-p))
4543 (todos-forward-item)
d16da867 4544 (and (eobp) (throw 'end nil))))
0e89c3fc
SB
4545 (re-search-forward (concat todos-date-string-start "\\(?1:"
4546 todos-date-pattern
d16da867
SB
4547 "\\)\\(?2: " diary-time-regexp "\\)?"
4548 (regexp-quote todos-nondiary-end) "?")
0e89c3fc
SB
4549 (line-end-position) t)
4550 (let* ((odate (match-string-no-properties 1))
4551 (otime (match-string-no-properties 2))
d16da867
SB
4552 (omonthname (match-string-no-properties 6))
4553 (omonth (match-string-no-properties 7))
4554 (oday (match-string-no-properties 8))
4555 (oyear (match-string-no-properties 9))
4556 (tmn-array todos-month-name-array)
4557 (mlist (append tmn-array nil))
4558 (tma-array todos-month-abbrev-array)
4559 (mablist (append tma-array nil))
4560 (yy (and oyear (unless (string= oyear "*")
4561 (string-to-number oyear))))
4562 (mm (or (and omonth (unless (string= omonth "*")
4563 (string-to-number omonth)))
4564 (1+ (- (length mlist)
4565 (length (or (member omonthname mlist)
4566 (member omonthname mablist)))))))
4567 (dd (and oday (unless (string= oday "*")
4568 (string-to-number oday)))))
4569 ;; If there are marked items, use only the first to set
4570 ;; header changes, and apply these to all marked items.
4571 (when first
4572 (cond
4573 ((eq what 'date)
4574 (setq ndate (todos-read-date)))
4575 ((eq what 'calendar)
4576 (setq ndate (save-match-data (todos-set-date-from-calendar))))
4577 ((eq what 'today)
4578 (setq ndate (calendar-date-string (calendar-current-date) t t)))
4579 ((eq what 'dayname)
4580 (setq ndate (todos-read-dayname)))
4581 ((eq what 'time)
4582 (setq ntime (save-match-data (todos-read-time)))
4583 (when (> (length ntime) 0)
4584 (setq ntime (concat " " ntime))))
4585 ;; When date string consists only of a day name,
4586 ;; passing other date components is a NOP.
4587 ((and (memq what '(year month day))
4588 (not (or oyear omonth oday))))
4589 ((eq what 'year)
4590 (setq day oday
4591 monthname omonthname
4592 month omonth
4593 year (cond ((not current-prefix-arg)
4594 (todos-read-date 'year))
4595 ((string= oyear "*")
4596 (error "Cannot increment *"))
4597 (t ; FIXME: handle negative years
4598 (number-to-string (+ yy inc))))))
4599 ((eq what 'month)
4600 (setf day oday
4601 year oyear
4602 (if (memq 'month calendar-date-display-form)
4603 month
4604 monthname)
4605 (cond ((not current-prefix-arg)
4606 (todos-read-date 'month))
4607 ((or (string= omonth "*") (= mm 13))
4608 (error "Cannot increment *"))
4609 (t
4610 (let ((mminc (+ mm inc)))
4611 ;; Increment or decrement month by INC
4612 ;; modulo 12.
4613 (setq mm (% mminc 12))
4614 ;; If result is 0, make month December.
4615 (setq mm (if (= mm 0) 12 (abs mm)))
4616 ;; Adjust year if necessary.
4617 (setq year (or (and (cond ((> mminc 12)
4618 (+ yy (/ mminc 12)))
4619 ((< mminc 1)
4620 (- yy (/ mminc 12) 1))
4621 (t yy))
4622 (number-to-string yy))
4623 oyear)))
4624 ;; Return the changed numerical month as
4625 ;; a string or the corresponding month name.
4626 (if omonth
4627 (number-to-string mm)
4628 (aref tma-array (1- mm))))))
4629 (let ((yy (string-to-number year)) ; 0 if year is "*".
4630 ;; When mm is 13 (corresponding to "*" as value
4631 ;; of month), this raises an args-out-of-range
4632 ;; error in calendar-last-day-of-month, so use 1
4633 ;; (corresponding to January) to get 31 days.
4634 (mm (if (= mm 13) 1 mm)))
4635 (if (> (string-to-number day)
4636 (calendar-last-day-of-month mm yy))
4637 (error "%s %s does not have %s days"
4638 (aref tmn-array (1- mm))
4639 (if (= mm 2) yy "") day))))
4640 ((eq what 'day)
4641 (setq year oyear
4642 month omonth
4643 monthname omonthname
4644 day (cond
4645 ((not current-prefix-arg)
4646 (todos-read-date 'day mm oyear))
4647 ((string= oday "*")
4648 (error "Cannot increment *"))
4649 ((or (string= omonth "*") (string= omonthname "*"))
4650 (setq dd (+ dd inc))
4651 (if (> dd 31)
4652 (error "A month cannot have more than 31 days")
4653 (number-to-string dd)))
4654 ;; Increment or decrement day by INC,
4655 ;; adjusting month and year if necessary
4656 ;; (if year is "*" assume current year to
4657 ;; calculate adjustment).
4658 (t
4659 (let* ((yy (or yy (calendar-extract-year
4660 (calendar-current-date))))
4661 (date (calendar-gregorian-from-absolute
4662 (+ (calendar-absolute-from-gregorian
4663 (list mm dd yy)) inc)))
4664 (adjmm (nth 0 date)))
4665 ;; Set year and month(name) to adjusted values.
4666 (unless (string= year "*")
4667 (setq year (number-to-string (nth 2 date))))
4668 (if month
4669 (setq month (number-to-string adjmm))
4670 (setq monthname (aref tma-array (1- adjmm))))
4671 ;; Return changed numerical day as a string.
4672 (number-to-string (nth 1 date)))))))))
4673 ;; If new year, month or day date string components were
4674 ;; calculated, rebuild the whole date string from them.
4675 (when (memq what '(year month day))
4676 (if (or oyear omonth omonthname oday)
4677 (setq ndate (mapconcat 'eval calendar-date-display-form ""))
4678 (message "Cannot edit date component of empty date string")))
4679 (when ndate (replace-match ndate nil nil nil 1))
4680 ;; Add new time string to the header, if it was supplied.
4681 (when ntime
4682 (if otime
4683 (replace-match ntime nil nil nil 2)
4684 (goto-char (match-end 1))
4685 (insert ntime)))
0e89c3fc
SB
4686 (setq todos-date-from-calendar nil)
4687 (setq first nil))
d16da867
SB
4688 ;; Apply the changes to the first marked item header to the
4689 ;; remaining marked items. If there are no marked items,
4690 ;; we're finished.
0e89c3fc
SB
4691 (if marked
4692 (todos-forward-item)
4693 (goto-char (point-max))))))))
58c7641d 4694
d16da867
SB
4695(defun todos-edit-item-header ()
4696 "Interactively edit at least the date of item's date/time header.
4697If user option `todos-always-add-time-string' is non-nil, also
4698edit item's time string."
0e89c3fc 4699 (interactive)
d16da867
SB
4700 (todos-edit-item-header-1 'date)
4701 (when todos-always-add-time-string
4702 (todos-edit-item-time)))
4703
4704(defun todos-edit-item-time ()
4705 "Interactively edit the time string of item's date/time header."
4706 (interactive)
4707 (todos-edit-item-header-1 'time))
58c7641d 4708
0e89c3fc 4709(defun todos-edit-item-date-from-calendar ()
d16da867 4710 "Interactively edit item's date using the Calendar."
0e89c3fc 4711 (interactive)
d16da867 4712 (todos-edit-item-header-1 'calendar))
58c7641d 4713
d16da867
SB
4714(defun todos-edit-item-date-to-today ()
4715 "Set item's date to today's date."
0e89c3fc 4716 (interactive)
d16da867
SB
4717 (todos-edit-item-header-1 'today))
4718
4719(defun todos-edit-item-date-day-name ()
4720 "Replace item's date with the name of a day of the week."
0e89c3fc 4721 (interactive)
d16da867
SB
4722 (todos-edit-item-header-1 'dayname))
4723
4724(defun todos-edit-item-date-year (&optional inc)
4725 "Interactively edit the year of item's date string.
4726With prefix argument INC a positive or negative integer,
4727increment or decrement the year by INC."
4728 (interactive "p")
4729 (todos-edit-item-header-1 'year inc))
4730
4731(defun todos-edit-item-date-month (&optional inc)
4732 "Interactively edit the month of item's date string.
4733With prefix argument INC a positive or negative integer,
4734increment or decrement the month by INC."
4735 (interactive "p")
4736 (todos-edit-item-header-1 'month inc))
4737
4738(defun todos-edit-item-date-day (&optional inc)
4739 "Interactively edit the day of the month of item's date string.
4740With prefix argument INC a positive or negative integer,
4741increment or decrement the day by INC."
4742 (interactive "p")
4743 (todos-edit-item-header-1 'day inc))
58c7641d 4744
0e89c3fc
SB
4745(defun todos-edit-item-diary-inclusion ()
4746 "Change diary status of one or more todo items in this category.
4747That is, insert `todos-nondiary-marker' if the candidate items
4748lack this marking; otherwise, remove it.
d04d6b95 4749
0e89c3fc
SB
4750If there are marked todo items, change the diary status of all
4751and only these, otherwise change the diary status of the item at
4752point."
4753 (interactive)
4754 (let ((buffer-read-only)
4755 (marked (assoc (todos-current-category)
4756 todos-categories-with-marks)))
4757 (catch 'stop
4758 (save-excursion
4759 (when marked (goto-char (point-min)))
4760 (while (not (eobp))
4761 (if (todos-done-item-p)
4762 (throw 'stop (message "Done items cannot be edited"))
4763 (unless (and marked (not (todos-marked-item-p)))
4764 (let* ((beg (todos-item-start))
4765 (lim (save-excursion (todos-item-end)))
4766 (end (save-excursion
4767 (or (todos-time-string-matcher lim)
4768 (todos-date-string-matcher lim)))))
4769 (if (looking-at (regexp-quote todos-nondiary-start))
4770 (progn
4771 (replace-match "")
4772 (search-forward todos-nondiary-end (1+ end) t)
4773 (replace-match "")
3af3cd0b 4774 (todos-update-count 'diary 1))
0e89c3fc
SB
4775 (when end
4776 (insert todos-nondiary-start)
4777 (goto-char (1+ end))
4778 (insert todos-nondiary-end)
3af3cd0b 4779 (todos-update-count 'diary -1)))))
0e89c3fc
SB
4780 (unless marked (throw 'stop nil))
4781 (todos-forward-item)))))
4782 (todos-update-categories-sexp)))
58c7641d 4783
0e89c3fc
SB
4784(defun todos-edit-category-diary-inclusion (arg)
4785 "Make all items in this category diary items.
4786With prefix ARG, make all items in this category non-diary
4787items."
4788 (interactive "P")
d04d6b95 4789 (save-excursion
0e89c3fc
SB
4790 (goto-char (point-min))
4791 (let ((todo-count (todos-get-count 'todo))
4792 (diary-count (todos-get-count 'diary))
4793 (buffer-read-only))
4794 (catch 'stop
d04d6b95 4795 (while (not (eobp))
0e89c3fc
SB
4796 (if (todos-done-item-p) ; We've gone too far.
4797 (throw 'stop nil)
4798 (let* ((beg (todos-item-start))
4799 (lim (save-excursion (todos-item-end)))
4800 (end (save-excursion
4801 (or (todos-time-string-matcher lim)
4802 (todos-date-string-matcher lim)))))
4803 (if arg
4804 (unless (looking-at (regexp-quote todos-nondiary-start))
4805 (insert todos-nondiary-start)
4806 (goto-char (1+ end))
4807 (insert todos-nondiary-end))
4808 (when (looking-at (regexp-quote todos-nondiary-start))
4809 (replace-match "")
4810 (search-forward todos-nondiary-end (1+ end) t)
4811 (replace-match "")))))
4812 (todos-forward-item))
4813 (unless (if arg (zerop diary-count) (= diary-count todo-count))
3af3cd0b 4814 (todos-update-count 'diary (if arg
0e89c3fc
SB
4815 (- diary-count)
4816 (- todo-count diary-count))))
4817 (todos-update-categories-sexp)))))
d04d6b95 4818
0e89c3fc
SB
4819(defun todos-edit-item-diary-nonmarking ()
4820 "Change non-marking of one or more diary items in this category.
4821That is, insert `diary-nonmarking-symbol' if the candidate items
4822lack this marking; otherwise, remove it.
d04d6b95 4823
0e89c3fc
SB
4824If there are marked todo items, change the non-marking status of
4825all and only these, otherwise change the non-marking status of
4826the item at point."
4827 (interactive)
4828 (let ((buffer-read-only)
4829 (marked (assoc (todos-current-category)
4830 todos-categories-with-marks)))
4831 (catch 'stop
4832 (save-excursion
4833 (when marked (goto-char (point-min)))
4834 (while (not (eobp))
4835 (if (todos-done-item-p)
4836 (throw 'stop (message "Done items cannot be edited"))
4837 (unless (and marked (not (todos-marked-item-p)))
4838 (todos-item-start)
4839 (unless (looking-at (regexp-quote todos-nondiary-start))
4840 (if (looking-at (regexp-quote diary-nonmarking-symbol))
4841 (replace-match "")
4842 (insert diary-nonmarking-symbol))))
4843 (unless marked (throw 'stop nil))
4844 (todos-forward-item)))))))
58c7641d 4845
0e89c3fc
SB
4846(defun todos-edit-category-diary-nonmarking (arg)
4847 "Add `diary-nonmarking-symbol' to all diary items in this category.
4848With prefix ARG, remove `diary-nonmarking-symbol' from all diary
4849items in this category."
4850 (interactive "P")
4851 (save-excursion
4852 (goto-char (point-min))
4853 (let (buffer-read-only)
4854 (catch 'stop
4855 (while (not (eobp))
4856 (if (todos-done-item-p) ; We've gone too far.
4857 (throw 'stop nil)
4858 (unless (looking-at (regexp-quote todos-nondiary-start))
4859 (if arg
4860 (when (looking-at (regexp-quote diary-nonmarking-symbol))
4861 (replace-match ""))
4862 (unless (looking-at (regexp-quote diary-nonmarking-symbol))
4863 (insert diary-nonmarking-symbol))))
4864 (todos-forward-item)))))))
58c7641d 4865
59ad682f
SB
4866;; FIXME: Make NOP if point isn't on a todo item (cf. todos-copy-item,
4867;; todos-move-item
616ffa8b
SB
4868(defun todos-set-item-priority (&optional item cat new arg)
4869 "Set todo ITEM's priority in CATegory and move item accordingly.
4870
4871Interactively, ITEM defaults to the item at point, CAT to the
4872current category in Todos mode, and the priority is a number
4873between 1 and the number of items in the category.
4874Non-interactively, non-nil NEW means ITEM is a new item and the
4875lowest priority is one more than the number of items in CAT.
4876
4877The new priority is set either interactively by prompt or by a
4878numerical prefix argument, or noninteractively by argument ARG,
4879whose value can be either of the symbols `raise' or `lower',
4880meaning to raise or lower the item's priority by one."
0e89c3fc 4881 (interactive)
616ffa8b
SB
4882 (let* ((item (or item (todos-item-string)))
4883 (marked (todos-marked-item-p))
4884 (cat (or cat (cond ((eq major-mode 'todos-mode)
4885 (todos-current-category))
4886 ((eq major-mode 'todos-filtered-items-mode)
4887 (let* ((regexp1
4888 (concat todos-date-string-start
4889 todos-date-pattern
4890 "\\( " diary-time-regexp "\\)?"
4891 (regexp-quote todos-nondiary-end)
4892 "?\\(?1: \\[\\(.+:\\)?.+\\]\\)")))
4893 (save-excursion
4894 (re-search-forward regexp1 nil t)
4895 (match-string-no-properties 1)))))))
4896 curnum
4897 (todo (cond ((or (eq arg 'raise) (eq arg 'lower)
4898 (eq major-mode 'todos-filtered-items-mode))
4899 (save-excursion
4900 (let ((curstart (todos-item-start))
4901 (count 0))
4902 (goto-char (point-min))
4903 (while (looking-at todos-item-start)
4904 (setq count (1+ count))
4905 (when (= (point) curstart) (setq curnum count))
4906 (todos-forward-item))
4907 count)))
4908 ((eq major-mode 'todos-mode)
4909 (todos-get-count 'todo cat))))
4910 (maxnum (if new (1+ todo) todo))
4911 (prompt (format "Set item priority (1-%d): " maxnum))
4912 (priority (cond ((numberp current-prefix-arg)
4913 current-prefix-arg)
4914 ((and (eq arg 'raise) (>= curnum 1))
4915 (1- curnum))
4916 ((and (eq arg 'lower) (<= curnum maxnum))
4917 (1+ curnum))))
4918 candidate
4919 buffer-read-only)
4920 (unless (and priority
4921 (or (and (eq arg 'raise) (zerop priority))
4922 (and (eq arg 'lower) (> priority maxnum))))
4923 ;; When moving item to another category, show the category before
4924 ;; prompting for its priority.
4925 (unless (or arg (called-interactively-p t))
4926 (todos-category-number cat)
4927 (todos-category-select))
57da062d
SB
4928 ;; Prompt for priority only when the category has at least one todo item.
4929 (when (> maxnum 1)
4930 (while (not priority)
4931 (setq candidate (read-number prompt))
4932 (setq prompt (when (or (< candidate 1) (> candidate maxnum))
4933 (format "Priority must be an integer between 1 and %d.\n"
4934 maxnum)))
4935 (unless prompt (setq priority candidate))))
2a9e69d6
SB
4936 ;; In Top Priorities buffer, an item's priority can be changed
4937 ;; wrt items in another category, but not wrt items in the same
4938 ;; category.
b28872ce 4939 (when (eq major-mode 'todos-filtered-items-mode)
616ffa8b
SB
4940 (let* ((regexp2 (concat todos-date-string-start todos-date-pattern
4941 "\\( " diary-time-regexp "\\)?"
4942 (regexp-quote todos-nondiary-end)
4943 "?\\(?1:" (regexp-quote cat) "\\)"))
4944 (end (cond ((< curnum priority)
4945 (save-excursion (todos-item-end)))
4946 ((> curnum priority)
4947 (save-excursion (todos-item-start)))))
4948 (match (save-excursion
4949 (cond ((< curnum priority)
4950 (todos-forward-item (1+ (- priority curnum)))
4951 (when (re-search-backward regexp2 end t)
4952 (match-string-no-properties 1)))
4953 ((> curnum priority)
4954 (todos-backward-item (- curnum priority))
4955 (when (re-search-forward regexp2 end t)
4956 (match-string-no-properties 1)))))))
4957 (when match
4958 (error (concat "Cannot reprioritize items from the same "
4959 "category in this mode, only in Todos mode")))))
4960 ;; Interactively or with non-nil ARG, relocate the item within its
4961 ;; category.
4962 (when (or arg (called-interactively-p))
4963 (todos-remove-item))
4964 (goto-char (point-min))
57da062d
SB
4965 (when priority
4966 (unless (= priority 1)
4967 (todos-forward-item (1- priority))))
2a9e69d6 4968 (todos-insert-with-overlays item)
616ffa8b 4969 ;; If item was marked, restore the mark.
2a9e69d6
SB
4970 (and marked (overlay-put (make-overlay (point) (point))
4971 'before-string todos-item-mark)))))
3f031767 4972
616ffa8b
SB
4973(defun todos-raise-item-priority ()
4974 "Raise priority of current item by moving it up by one item."
0e89c3fc 4975 (interactive)
616ffa8b 4976 (todos-set-item-priority nil nil nil 'raise))
ee7412e4 4977
616ffa8b
SB
4978(defun todos-lower-item-priority ()
4979 "Lower priority of current item by moving it down by one item."
2a9e69d6 4980 (interactive)
616ffa8b 4981 (todos-set-item-priority nil nil nil 'lower))
2a9e69d6 4982
0e89c3fc
SB
4983(defun todos-move-item (&optional file)
4984 "Move at least one todo item to another category.
58c7641d 4985
0e89c3fc
SB
4986If there are marked items, move all of these; otherwise, move
4987the item at point.
58c7641d 4988
0e89c3fc
SB
4989With non-nil argument FILE, first prompt for another Todos file and
4990then a category in that file to move the item or items to.
58c7641d 4991
0e89c3fc
SB
4992If the chosen category is not one of the existing categories,
4993then it is created and the item(s) become(s) the first
4994entry/entries in that category."
4995 (interactive)
57da062d
SB
4996 (let* ((cat1 (todos-current-category))
4997 (marked (assoc cat1 todos-categories-with-marks)))
4998 (unless (or (todos-done-item-p)
4999 ;; Point is between todo and done items.
5000 (and (looking-at "^$") (not marked)))
5001 (let* ((buffer-read-only)
5002 (file1 todos-current-todos-file)
5003 (num todos-category-number)
5004 (item (todos-item-string))
5005 (diary-item (todos-diary-item-p))
5006 (omark (save-excursion (todos-item-start) (point-marker)))
5007 (file2 (if file
5008 (todos-read-file-name "Choose a Todos file: " nil t)
5009 file1))
5010 (count 0)
5011 (count-diary 0)
fec0fdae 5012 ov cat2 moved nmark)
57da062d
SB
5013 (set-buffer (find-file-noselect file2))
5014 (unwind-protect
5015 (progn
5016 (unless marked
5017 (setq ov (make-overlay (save-excursion (todos-item-start))
5018 (save-excursion (todos-item-end))))
5019 (overlay-put ov 'face 'todos-search))
5020 (setq cat2 (let* ((pl (if (and marked (> (cdr marked) 1)) "s" ""))
5021 (name (todos-read-category
5022 (concat "Move item" pl " to category: ")))
5023 (prompt (concat "Choose a different category than "
5024 "the current one\n(type `"
5025 (key-description
5026 (car (where-is-internal
5027 'todos-set-item-priority)))
5028 "' to reprioritize item "
5029 "within the same category): ")))
5030 (while (equal name cat1)
5031 (setq name (todos-read-category prompt)))
5032 name)))
5033 (if ov (delete-overlay ov)))
5034 (set-buffer (find-buffer-visiting file1))
5035 (if marked
5036 (progn
5037 (setq item nil)
5038 (goto-char (point-min))
5039 (while (not (eobp))
5040 (when (todos-marked-item-p)
5041 (setq item (concat item (todos-item-string) "\n"))
5042 (setq count (1+ count))
5043 (when (todos-diary-item-p)
5044 (setq count-diary (1+ count-diary))))
5045 (todos-forward-item))
5046 ;; Chop off last newline.
5047 (setq item (substring item 0 -1)))
5048 (setq count 1)
5049 (when (todos-diary-item-p) (setq count-diary 1)))
5050 (set-window-buffer (selected-window)
5051 (set-buffer (find-file-noselect file2)))
fec0fdae
SB
5052 (unwind-protect
5053 (progn
5054 (todos-set-item-priority item cat2 t)
5055 (setq moved t))
5056 (cond
5057 ;; Move succeeded, so remove item from starting category,
5058 ;; update item counts and display the category containing
5059 ;; the moved item.
5060 (moved
5061 (setq nmark (point-marker))
5062 (todos-update-count 'todo count)
5063 (todos-update-count 'diary count-diary)
5064 (todos-update-categories-sexp)
5065 (with-current-buffer (find-buffer-visiting file1)
5066 (save-excursion
5067 (save-restriction
5068 (widen)
5069 (goto-char omark)
5070 (if marked
5071 (let (beg end)
5072 (setq item nil)
5073 (re-search-backward
5074 (concat "^" (regexp-quote todos-category-beg)) nil t)
5075 (forward-line)
5076 (setq beg (point))
5077 (re-search-forward
5078 (concat "^" (regexp-quote todos-category-done)) nil t)
5079 (setq end (match-beginning 0))
5080 (goto-char beg)
5081 (while (< (point) end)
5082 (if (todos-marked-item-p)
5083 (todos-remove-item)
5084 (todos-forward-item)))
5085 ;; FIXME: does this work?
5086 (remove-overlays (point-min) (point-max)
5087 'before-string todos-item-mark)
5088 (setq todos-categories-with-marks
5089 (assq-delete-all cat1 todos-categories-with-marks)))
5090 (if ov (delete-overlay ov))
5091 (todos-remove-item))))
5092 (todos-update-count 'todo (- count) cat1)
5093 (todos-update-count 'diary (- count-diary) cat1)
5094 (todos-update-categories-sexp))
5095 (set-window-buffer (selected-window)
5096 (set-buffer (find-file-noselect file2)))
5097 (setq todos-category-number (todos-category-number cat2))
5098 (todos-category-select)
5099 (goto-char nmark)
5100 ;; If item is moved to end of category, make sure the
5101 ;; items above it are displayed in the window.
5102 (recenter))
5103 ;; User quit before moving, so return to starting category.
5104 (t
5105 (todos-category-number cat1)
5106 (todos-category-select)
5107 (goto-char omark))))))))
58c7641d 5108
0e89c3fc
SB
5109(defun todos-move-item-to-file ()
5110 "Move the current todo item to a category in another Todos file."
58c7641d 5111 (interactive)
0e89c3fc 5112 (todos-move-item t))
58c7641d 5113
616ffa8b
SB
5114;; (defun todos-move-item-to-diary ()
5115;; "Move one or more items in current category to the diary file.
5116;;
5117;; If there are marked items, move all of these; otherwise, move
5118;; the item at point."
5119;; (interactive)
5120;; ;; FIXME
5121;; )
58c7641d 5122
0e89c3fc
SB
5123;; FIXME: make adding date customizable, and make this and time customization
5124;; overridable via double prefix arg ??
5125(defun todos-item-done (&optional arg)
5126 "Tag at least one item in this category as done and hide it.
5127
5128With prefix argument ARG prompt for a comment and append it to
5129the done item; this is only possible if there are no marked
5130items. If there are marked items, tag all of these with
5131`todos-done-string' plus the current date and, if
5132`todos-always-add-time-string' is non-nil, the current time;
5133otherwise, just tag the item at point. Items tagged as done are
5134relocated to the category's (by default hidden) done section."
5135 (interactive "P")
5136 (let* ((cat (todos-current-category))
5137 (marked (assoc cat todos-categories-with-marks)))
5138 (unless (or (todos-done-item-p)
57da062d 5139 ;; Point is between todo and done items.
0e89c3fc
SB
5140 (and (looking-at "^$") (not marked)))
5141 (let* ((date-string (calendar-date-string (calendar-current-date) t t))
5142 (time-string (if todos-always-add-time-string
5143 (concat " " (substring (current-time-string) 11 16))
5144 ""))
5145 (done-prefix (concat "[" todos-done-string date-string time-string
5146 "] "))
5147 (comment (and arg (not marked) (read-string "Enter a comment: ")))
5148 (item-count 0)
5149 (diary-count 0)
5150 item done-item
5151 (buffer-read-only))
5152 (and marked (goto-char (point-min)))
5153 (catch 'done
5154 (while (not (eobp))
5155 (if (or (not marked) (and marked (todos-marked-item-p)))
5156 (progn
5157 (setq item (todos-item-string))
5158 (setq done-item (cond (marked
5159 (concat done-item done-prefix item "\n"))
5160 (comment
5161 (concat done-prefix item " ["
5162 todos-comment-string
5163 ": " comment "]"))
5164 (t
5165 (concat done-prefix item))))
5166 (setq item-count (1+ item-count))
5167 (when (todos-diary-item-p)
5168 (setq diary-count (1+ diary-count)))
5169 (todos-remove-item)
5170 (unless marked (throw 'done nil)))
5171 (todos-forward-item))))
5172 (when marked
5173 ;; Chop off last newline of done item string.
5174 (setq done-item (substring done-item 0 -1))
5175 (remove-overlays (point-min) (point-max) 'before-string todos-item-mark)
5176 (setq todos-categories-with-marks
5177 (assq-delete-all cat todos-categories-with-marks)))
5178 (save-excursion
5179 (widen)
5180 (re-search-forward
5181 (concat "^" (regexp-quote todos-category-done)) nil t)
5182 (forward-char)
5183 (insert done-item "\n"))
3af3cd0b
SB
5184 (todos-update-count 'todo (- item-count))
5185 (todos-update-count 'done item-count)
5186 (todos-update-count 'diary (- diary-count))
0e89c3fc
SB
5187 (todos-update-categories-sexp)
5188 (save-excursion (todos-category-select))))))
5189
b28872ce
SB
5190(defun todos-done-item-add-edit-or-delete-comment (&optional arg)
5191 "Add a comment to this done item or edit an existing comment.
5192With prefix ARG delete an existing comment."
5193 (interactive "P")
0e89c3fc 5194 (when (todos-done-item-p)
47011bed
SB
5195 (let ((item (todos-item-string))
5196 (end (save-excursion (todos-item-end)))
5197 comment buffer-read-only)
5198 (save-excursion
5199 (todos-item-start)
5200 (if (re-search-forward (concat " \\["
5201 (regexp-quote todos-comment-string)
5202 ": \\([^]]+\\)\\]") end t)
b28872ce
SB
5203 (if arg
5204 (when (y-or-n-p "Delete comment? ")
5205 (delete-region (match-beginning 0) (match-end 0)))
47011bed
SB
5206 (setq comment (read-string "Edit comment: "
5207 (cons (match-string 1) 1)))
5208 (replace-match comment nil nil nil 1))
5209 (setq comment (read-string "Enter a comment: "))
5210 (todos-item-end)
5211 (insert " [" todos-comment-string ": " comment "]"))))))
58c7641d 5212
0e89c3fc 5213(defun todos-item-undo ()
b28872ce
SB
5214 "Restore this done item to the todo section of this category.
5215If done item has a comment, ask whether to omit the comment from
5216the restored item."
0e89c3fc 5217 (interactive)
18aef8a3
SB
5218 (let* ((cat (todos-current-category))
5219 (marked (assoc cat todos-categories-with-marks)))
5220 (when (or marked (todos-done-item-p))
5221 (let ((buffer-read-only)
3160f2eb 5222 (bufmod (buffer-modified-p))
18aef8a3
SB
5223 (opoint (point))
5224 (orig-mrk (progn (todos-item-start) (point-marker)))
3160f2eb 5225 (orig-item (todos-item-string))
18aef8a3
SB
5226 (first 'first)
5227 (item-count 0)
5228 (diary-count 0)
5229 start end item undone)
5230 (and marked (goto-char (point-min)))
5231 (catch 'done
5232 (while (not (eobp))
5233 (if (or (not marked) (and marked (todos-marked-item-p)))
5234 (if (not (todos-done-item-p))
5235 (error "Only done items can be undone")
5236 (todos-item-start)
5237 ;; Find the end of the date string added upon tagging item as
5238 ;; done.
5239 (setq start (search-forward "] "))
5240 (setq item-count (1+ item-count))
5241 (unless (looking-at (regexp-quote todos-nondiary-start))
5242 (setq diary-count (1+ diary-count)))
5243 (setq end (save-excursion (todos-item-end)))
5244 ;; Ask (once) whether to omit done item's comment. If
5245 ;; affirmed, omit subsequent comments without asking.
5246 (when (re-search-forward
5247 (concat " \\[" (regexp-quote todos-comment-string)
5248 ": [^]]+\\]") end t)
5249 (if (eq first 'first)
5250 (setq first
1a9cb339
SB
5251 (if (eq todos-undo-item-omit-comment 'ask)
5252 (when (y-or-n-p
5253 "Omit comment from restored item? ")
5254 'omit)
5255 (when todos-undo-item-omit-comment 'omit)))
18aef8a3
SB
5256 t)
5257 (when (eq first 'omit)
5258 (delete-region (match-beginning 0) (match-end 0))
5259 (setq end (point))))
3160f2eb
SB
5260 (setq item (concat item
5261 (buffer-substring-no-properties start end)
18aef8a3
SB
5262 (when marked "\n")))
5263 (todos-remove-item)
5264 (unless marked (throw 'done nil)))
5265 (todos-forward-item))))
5266 (if marked
5267 (progn
3160f2eb
SB
5268 ;; (remove-overlays (point-min) (point-max)
5269 ;; 'before-string todos-item-mark)
18aef8a3
SB
5270 (setq todos-categories-with-marks
5271 (assq-delete-all cat todos-categories-with-marks))
5272 ;; Insert undone items that were marked at end of todo item list.
3160f2eb 5273 (goto-char (point-min))
18aef8a3
SB
5274 (re-search-forward (concat "^" (regexp-quote todos-category-done))
5275 nil t)
5276 (forward-line -1)
5277 (insert item)
5278 (todos-update-count 'todo item-count)
5279 (todos-update-count 'done (- item-count))
5280 (when diary-count (todos-update-count 'diary diary-count))
3160f2eb
SB
5281 (todos-update-categories-sexp)
5282 (let ((todos-show-with-done (> (todos-get-count 'done) 0)))
5283 (todos-category-select)))
18aef8a3
SB
5284 ;; With an unmarked undone item, prompt for its priority. If user
5285 ;; cancels before setting new priority, then leave the done item
5286 ;; unchanged.
5287 (unwind-protect
5288 (progn
5289 (todos-set-item-priority item (todos-current-category) t)
5290 (setq undone t)
5291 (todos-update-count 'todo 1)
5292 (todos-update-count 'done -1)
5293 (and (todos-diary-item-p) (todos-update-count 'diary 1))
3160f2eb
SB
5294 (todos-update-categories-sexp)
5295 (let ((todos-show-with-done (> (todos-get-count 'done) 0)))
5296 (todos-category-select)))
18aef8a3 5297 (unless undone
18aef8a3 5298 (let ((todos-show-with-done t))
3160f2eb
SB
5299 (widen)
5300 (goto-char orig-mrk)
5301 (todos-insert-with-overlays orig-item)
5302 (set-buffer-modified-p bufmod)
5303 (todos-category-select))
5304 (goto-char opoint))))
5305 (set-marker orig-mrk nil)))))
58c7641d 5306
2a9e69d6 5307(defun todos-archive-done-item (&optional all)
0e89c3fc 5308 "Archive at least one done item in this category.
d04d6b95 5309
0e89c3fc
SB
5310If there are marked done items (and no marked todo items),
5311archive all of these; otherwise, with non-nil argument ALL,
5312archive all done items in this category; otherwise, archive the
5313done item at point.
d04d6b95 5314
0e89c3fc
SB
5315If the archive of this file does not exist, it is created. If
5316this category does not exist in the archive, it is created."
5317 (interactive)
2a9e69d6 5318 (when (eq major-mode 'todos-mode)
0e89c3fc
SB
5319 (if (and all (zerop (todos-get-count 'done)))
5320 (message "No done items in this category")
5321 (catch 'end
5322 (let* ((cat (todos-current-category))
5323 (tbuf (current-buffer))
5324 (marked (assoc cat todos-categories-with-marks))
5325 (afile (concat (file-name-sans-extension
5326 todos-current-todos-file) ".toda"))
5327 (archive (if (file-exists-p afile)
5328 (find-file-noselect afile t)
6be04162 5329 (get-buffer-create afile)))
0e89c3fc
SB
5330 (item (and (todos-done-item-p) (concat (todos-item-string) "\n")))
5331 (count 0)
5332 marked-items beg end all-done
5333 buffer-read-only)
5334 (cond
5335 (marked
5336 (save-excursion
5337 (goto-char (point-min))
5338 (while (not (eobp))
6be04162
SB
5339 (when (todos-marked-item-p)
5340 (if (not (todos-done-item-p))
5341 (throw 'end (message "Only done items can be archived"))
5342 (setq marked-items
5343 (concat marked-items (todos-item-string) "\n"))
5344 (setq count (1+ count))))
5345 (todos-forward-item))))
0e89c3fc
SB
5346 (all
5347 (if (y-or-n-p "Archive all done items in this category? ")
5348 (save-excursion
5349 (save-restriction
5350 (goto-char (point-min))
5351 (widen)
5352 (setq beg (progn
5353 (re-search-forward todos-done-string-start nil t)
5354 (match-beginning 0))
5355 end (if (re-search-forward
5356 (concat "^" (regexp-quote todos-category-beg))
5357 nil t)
5358 (match-beginning 0)
5359 (point-max))
36341a66 5360 all-done (buffer-substring-no-properties beg end)
0e89c3fc
SB
5361 count (todos-get-count 'done))))
5362 (throw 'end nil))))
5363 (when (or marked all item)
5364 (with-current-buffer archive
6be04162 5365 (unless buffer-file-name (erase-buffer))
abe748f5 5366 (let (buffer-read-only)
0e89c3fc
SB
5367 (widen)
5368 (goto-char (point-min))
11aa0eef
SB
5369 (if (and (re-search-forward
5370 (concat "^" (regexp-quote
5371 (concat todos-category-beg cat)) "$")
5372 nil t)
6be04162
SB
5373 (re-search-forward (regexp-quote todos-category-done)
5374 nil t))
b28872ce
SB
5375 ;; Start of done items section in existing category.
5376 (forward-char)
0e89c3fc 5377 (todos-add-category cat)
b28872ce
SB
5378 ;; Start of done items section in new category.
5379 (goto-char (point-max)))
0e89c3fc
SB
5380 (insert (cond (marked marked-items)
5381 (all all-done)
5382 (item)))
abe748f5 5383 (todos-update-count 'done (if (or marked all) count 1) cat)
0e89c3fc 5384 (todos-update-categories-sexp)
abe748f5
SB
5385 ;; If archive is new, save to file now (using write-region in
5386 ;; order not to get prompted for file to save to), to let
5387 ;; auto-mode-alist take effect below.
6be04162
SB
5388 (unless buffer-file-name
5389 (write-region nil nil afile)
abe748f5 5390 (kill-buffer))))
0e89c3fc
SB
5391 (with-current-buffer tbuf
5392 (cond ((or marked item)
5393 (and marked (goto-char (point-min)))
5394 (catch 'done
5395 (while (not (eobp))
5396 (if (or (and marked (todos-marked-item-p)) item)
5397 (progn
5398 (todos-remove-item)
3af3cd0b
SB
5399 (todos-update-count 'done -1)
5400 (todos-update-count 'archived 1)
0e89c3fc
SB
5401 ;; Don't leave point below last item.
5402 (and item (bolp) (eolp) (< (point-min) (point-max))
5403 (todos-backward-item))
5404 (when item
5405 (throw 'done (setq item nil))))
5406 (todos-forward-item)))))
5407 (all
5408 (remove-overlays beg end)
5409 (delete-region beg end)
3af3cd0b
SB
5410 (todos-update-count 'done (- count))
5411 (todos-update-count 'archived count)))
0e89c3fc
SB
5412 (when marked
5413 (remove-overlays (point-min) (point-max)
5414 'before-string todos-item-mark)
5415 (setq todos-categories-with-marks
abe748f5 5416 (assq-delete-all cat todos-categories-with-marks)))
0e89c3fc 5417 (todos-update-categories-sexp)
abe748f5 5418 (todos-prefix-overlays)))
6be04162
SB
5419 (find-file afile)
5420 (todos-category-number cat)
5421 (todos-category-select)
6be04162
SB
5422 (split-window-below)
5423 (set-window-buffer (selected-window) tbuf))))))
d04d6b95 5424
0e89c3fc
SB
5425(defun todos-archive-category-done-items ()
5426 "Move all done items in this category to its archive."
5427 (interactive)
2a9e69d6 5428 (todos-archive-done-item t))
d04d6b95 5429
0e89c3fc
SB
5430(defun todos-unarchive-items (&optional all)
5431 "Unarchive at least one item in this archive category.
d04d6b95 5432
0e89c3fc
SB
5433If there are marked items, unarchive all of these; otherwise,
5434with non-nil argument ALL, unarchive all items in this category;
5435otherwise, unarchive the item at point.
d04d6b95 5436
0e89c3fc
SB
5437Unarchived items are restored as done items to the corresponding
5438category in the Todos file, inserted at the end of done section.
5439If all items in the archive category were restored, the category
5440is deleted from the archive. If this was the only category in the
5441archive, the archive file is deleted."
5442 (interactive)
abe748f5 5443 (when (eq major-mode 'todos-archive-mode)
0e89c3fc 5444 (catch 'end
abe748f5 5445 (let* ((cat (todos-current-category))
0e89c3fc
SB
5446 (tbuf (find-file-noselect
5447 (concat (file-name-sans-extension todos-current-todos-file)
5448 ".todo") t))
0e89c3fc
SB
5449 (marked (assoc cat todos-categories-with-marks))
5450 (item (concat (todos-item-string) "\n"))
36341a66
SB
5451 (all-items (when all (buffer-substring-no-properties
5452 (point-min) (point-max))))
abe748f5
SB
5453 (all-count (when all (todos-get-count 'done)))
5454 marked-items marked-count
5455 buffer-read-only)
5456 (when marked
5457 (save-excursion
5458 (goto-char (point-min))
5459 (while (not (eobp))
5460 (when (todos-marked-item-p)
5461 (concat marked-items (todos-item-string) "\n")
5462 (setq marked-count (1+ marked-count)))
5463 (todos-forward-item))))
0e89c3fc
SB
5464 ;; Restore items to end of category's done section and update counts.
5465 (with-current-buffer tbuf
5466 (let (buffer-read-only)
5467 (widen)
5468 (goto-char (point-min))
5469 (re-search-forward (concat "^" (regexp-quote
11aa0eef 5470 (concat todos-category-beg cat)) "$")
0e89c3fc 5471 nil t)
abe748f5 5472 ;; Go to end of category's done section.
0e89c3fc
SB
5473 (if (re-search-forward (concat "^" (regexp-quote todos-category-beg))
5474 nil t)
5475 (goto-char (match-beginning 0))
5476 (goto-char (point-max)))
5477 (cond (marked
5478 (insert marked-items)
abe748f5
SB
5479 (todos-update-count 'done marked-count cat)
5480 (todos-update-count 'archived (- marked-count) cat))
0e89c3fc 5481 (all
abe748f5
SB
5482 (insert all-items)
5483 (todos-update-count 'done all-count cat)
5484 (todos-update-count 'archived (- all-count) cat))
0e89c3fc
SB
5485 (t
5486 (insert item)
abe748f5
SB
5487 (todos-update-count 'done 1 cat)
5488 (todos-update-count 'archived -1 cat)))
0e89c3fc
SB
5489 (todos-update-categories-sexp)))
5490 ;; Delete restored items from archive.
5491 (cond ((or marked item)
5492 (and marked (goto-char (point-min)))
5493 (catch 'done
5494 (while (not (eobp))
5495 (if (or (and marked (todos-marked-item-p)) item)
5496 (progn
5497 (todos-remove-item)
0e89c3fc
SB
5498 ;; Don't leave point below last item.
5499 (and item (bolp) (eolp) (< (point-min) (point-max))
5500 (todos-backward-item))
5501 (when item
5502 (throw 'done (setq item nil))))
abe748f5
SB
5503 (todos-forward-item))))
5504 (todos-update-count 'done (if marked (- marked-count) -1) cat))
0e89c3fc
SB
5505 (all
5506 (remove-overlays (point-min) (point-max))
abe748f5 5507 (delete-region (point-min) (point-max))))
0e89c3fc
SB
5508 ;; If that was the last category in the archive, delete the whole file.
5509 (if (= (length todos-categories) 1)
5510 (progn
5511 (delete-file todos-current-todos-file)
5512 ;; Don't bother confirming killing the archive buffer.
5513 (set-buffer-modified-p nil)
5514 (kill-buffer))
5515 ;; Otherwise, if the archive category is now empty, delete it.
5516 (when (eq (point-min) (point-max))
5517 (widen)
5518 (let ((beg (re-search-backward
11aa0eef 5519 (concat "^" (regexp-quote todos-category-beg) cat "$")
0e89c3fc
SB
5520 nil t))
5521 (end (if (re-search-forward
5522 (concat "^" (regexp-quote todos-category-beg))
5523 nil t 2)
5524 (match-beginning 0)
5525 (point-max))))
5526 (remove-overlays beg end)
5527 (delete-region beg end)
5528 (setq todos-categories (delete (assoc cat todos-categories)
5529 todos-categories))
5530 (todos-update-categories-sexp))))
5531 ;; Visit category in Todos file and show restored done items.
5532 (let ((tfile (buffer-file-name tbuf))
5533 (todos-show-with-done t))
5534 (set-window-buffer (selected-window)
5535 (set-buffer (find-file-noselect tfile)))
5536 (todos-category-number cat)
5537 (todos-show)
5538 (message "Items unarchived."))))))
58c7641d 5539
0e89c3fc
SB
5540(defun todos-unarchive-category ()
5541 "Unarchive all items in this category. See `todos-unarchive-items'."
5542 (interactive)
5543 (todos-unarchive-items t))
3f031767
SB
5544
5545(provide 'todos)
5546
3f031767 5547;;; todos.el ends here
58c7641d 5548
7464f422 5549;; FIXME: remove when part of Emacs
18aef8a3 5550;; ---------------------------------------------------------------------------
7464f422
SB
5551(add-to-list 'auto-mode-alist '("\\.todo\\'" . todos-mode))
5552(add-to-list 'auto-mode-alist '("\\.toda\\'" . todos-archive-mode))
5553
5554;;; Addition to calendar.el
520d912e 5555;; FIXME: autoload when key-binding is defined in calendar.el
18aef8a3 5556(defun todos-insert-item-from-calendar (&optional arg)
520d912e 5557 ""
18aef8a3
SB
5558 (interactive "P")
5559 (setq todos-date-from-calendar
5560 (calendar-date-string (calendar-cursor-to-date t) t t))
5561 (calendar-exit)
520d912e 5562 (todos-show)
18aef8a3 5563 (todos-insert-item arg nil nil todos-date-from-calendar))
520d912e 5564
18aef8a3 5565(define-key calendar-mode-map "it" 'todos-insert-item-from-calendar)
520d912e 5566
58c7641d
SB
5567;;; necessitated adaptations to diary-lib.el
5568
5569;; (defun diary-goto-entry (button)
5570;; "Jump to the diary entry for the BUTTON at point."
5571;; (let* ((locator (button-get button 'locator))
5572;; (marker (car locator))
5573;; markbuf file opoint)
5574;; ;; If marker pointing to diary location is valid, use that.
5575;; (if (and marker (setq markbuf (marker-buffer marker)))
5576;; (progn
5577;; (pop-to-buffer markbuf)
5578;; (goto-char (marker-position marker)))
5579;; ;; Marker is invalid (eg buffer has been killed, as is the case with
5580;; ;; included diary files).
5581;; (or (and (setq file (cadr locator))
5582;; (file-exists-p file)
5583;; (find-file-other-window file)
5584;; (progn
5585;; (when (eq major-mode (default-value 'major-mode)) (diary-mode))
5586;; (when (eq major-mode 'todos-mode) (widen))
5587;; (goto-char (point-min))
5588;; (when (re-search-forward (format "%s.*\\(%s\\)"
5589;; (regexp-quote (nth 2 locator))
5590;; (regexp-quote (nth 3 locator)))
5591;; nil t)
5592;; (goto-char (match-beginning 1))
5593;; (when (eq major-mode 'todos-mode)
5594;; (setq opoint (point))
5595;; (re-search-backward (concat "^"
5596;; (regexp-quote todos-category-beg)
5597;; "\\(.*\\)\n")
5598;; nil t)
5599;; (todos-category-number (match-string 1))
5600;; (todos-category-select)
5601;; (goto-char opoint)))))
5602;; (message "Unable to locate this diary entry")))))