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