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