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