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