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