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