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