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