1 ;;; todo-mode.el --- facilities for making and maintaining todo lists
3 ;; Copyright (C) 1997, 1999, 2001-2013 Free Software Foundation, Inc.
5 ;; Author: Oliver Seidel <privat@os10000.net>
6 ;; Stephen Berman <stephen.berman@gmx.net>
7 ;; Maintainer: Stephen Berman <stephen.berman@gmx.net>
8 ;; Keywords: calendar, todo
10 ;; This file is part of GNU Emacs.
12 ;; GNU Emacs is free software: you can redistribute it and/or modify
13 ;; it under the terms of the GNU General Public License as published by
14 ;; the Free Software Foundation, either version 3 of the License, or
15 ;; (at your option) any later version.
17 ;; GNU Emacs is distributed in the hope that it will be useful,
18 ;; but WITHOUT ANY WARRANTY; without even the implied warranty of
19 ;; MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
20 ;; GNU General Public License for more details.
22 ;; You should have received a copy of the GNU General Public License
23 ;; along with GNU Emacs. If not, see <http://www.gnu.org/licenses/>.
27 ;; This package provides facilities for making, displaying, navigating
28 ;; and editing todo lists, which are prioritized lists of todo items.
29 ;; Todo lists are identified with named categories, so you can group
30 ;; together and separately prioritize thematically related todo items.
31 ;; Each category is stored in a file, which thus provides a further
32 ;; level of organization. You can create as many todo files, and in
33 ;; each as many categories, as you want.
35 ;; With Todo mode you can navigate among the items of a category, and
36 ;; between categories in the same and in different todo files. You
37 ;; can edit todo items, reprioritize them within their category, move
38 ;; them to another category, delete them, or mark items as done and
39 ;; store them separately from the not yet done items in a category.
40 ;; You can add new todo files, edit and delete them. You can add new
41 ;; categories, rename and delete them, move categories to another file
42 ;; and merge the items of two categories. You can also reorder the
43 ;; sequence of categories in a todo file for the purpose of
44 ;; navigation. You can display summary tables of the categories in a
45 ;; file and the types of items they contain. And you can compile
46 ;; lists of existing items from multiple categories in one or more
47 ;; todo files, which are filtered by various criteria.
49 ;; To get started, load this package and type `M-x todo-show'. This
50 ;; will prompt you for the name of the first todo file, its first
51 ;; category and the category's first item, create these and display
52 ;; them in Todo mode. Now you can insert further items into the list
53 ;; (i.e., the category) and assign them priorities by typing `i i'.
55 ;; You will probably find it convenient to give `todo-show' a global
56 ;; key binding in your init file, since it is one of the entry points
57 ;; to Todo mode; a good choice is `C-c t', since `todo-show' is
58 ;; bound to `t' in Todo mode.
60 ;; To see a list of all Todo mode commands and their key bindings,
61 ;; including other entry points, type `C-h m' in Todo mode. Consult
62 ;; the documentation strings of the commands for details of their use.
63 ;; The `todo' customization group and its subgroups list the options
64 ;; you can set to alter the behavior of many commands and various
65 ;; aspects of the display.
67 ;; This package is a new version of Oliver Seidel's todo-mode.el.
68 ;; While it retains the same basic organization and handling of todo
69 ;; lists and the basic UI, it significantly extends these and adds
70 ;; many features. This required also making changes to the internals,
71 ;; including the file format. If you have a todo file in old format,
72 ;; then the first time you invoke `todo-show' (i.e., before you have
73 ;; created any todo file in the current format), it will ask you
74 ;; whether to convert that file and show it. If you choose not to
75 ;; convert the old-style file at this time, you can do so later by
76 ;; calling the command `todo-convert-legacy-files'.
81 ;; For cl-remove-duplicates (in todo-insertion-commands-args) and
85 ;; -----------------------------------------------------------------------------
86 ;;; Setting up todo files, categories, and items
87 ;; -----------------------------------------------------------------------------
89 (defcustom todo-directory (locate-user-emacs-file "todo/")
90 "Directory where user's todo files are saved."
94 (defun todo-files (&optional archives)
95 "Default value of `todo-files-function'.
96 This returns the case-insensitive alphabetically sorted list of
97 file truenames in `todo-directory' with the extension
98 \".todo\". With non-nil ARCHIVES return the list of archive file
99 truenames (those with the extension \".toda\")."
100 (let ((files (if (file-exists-p todo-directory)
101 (mapcar 'file-truename
102 (directory-files todo-directory t
103 (if archives "\.toda$" "\.todo$") t)))))
104 (sort files (lambda (s1 s2) (let ((cis1 (upcase s1))
106 (string< cis1 cis2))))))
108 (defcustom todo-files-function 'todo-files
109 "Function returning the value of the variable `todo-files'.
110 This function should take an optional argument that, if non-nil,
111 makes it return the value of the variable `todo-archives'."
115 (defvar todo-files (funcall todo-files-function)
116 "List of truenames of user's todo files.")
118 (defvar todo-archives (funcall todo-files-function t)
119 "List of truenames of user's todo archives.")
121 (defvar todo-visited nil
122 "List of todo files visited in this session by `todo-show'.
123 Used to determine initial display according to the value of
126 (defvar todo-file-buffers nil
127 "List of file names of live Todo mode buffers.")
129 (defvar todo-global-current-todo-file nil
130 "Variable holding name of current todo file.
131 Used by functions called from outside of Todo mode to visit the
132 current todo file rather than the default todo file (i.e. when
133 users option `todo-show-current-file' is non-nil).")
135 (defvar todo-current-todo-file nil
136 "Variable holding the name of the currently active todo file.")
138 (defvar todo-categories nil
139 "Alist of categories in the current todo file.
140 The elements are cons cells whose car is a category name and
141 whose cdr is a vector of the category's item counts. These are,
142 in order, the numbers of todo items, of todo items included in
143 the Diary, of done items and of archived items.")
145 (defvar todo-category-number 1
146 "Variable holding the number of the current todo category.
147 Todo categories are numbered starting from 1.")
149 (defvar todo-categories-with-marks nil
150 "Alist of categories and number of marked items they contain.")
152 (defconst todo-category-beg "--==-- "
153 "String marking beginning of category (inserted with its name).")
155 (defconst todo-category-done "==--== DONE "
156 "String marking beginning of category's done items.")
158 (defcustom todo-done-separator-string "="
159 "String determining the value of variable `todo-done-separator'.
160 If the string consists of a single character,
161 `todo-done-separator' will be the string made by repeating this
162 character for the width of the window, and the length is
163 automatically recalculated when the window width changes. If the
164 string consists of more (or less) than one character, it will be
165 the value of `todo-done-separator'."
167 :initialize 'custom-initialize-default
168 :set 'todo-reset-done-separator-string
169 :group 'todo-display)
171 (defun todo-done-separator ()
172 "Return string used as value of variable `todo-done-separator'."
173 (let ((sep todo-done-separator-string))
174 (propertize (if (= 1 (length sep))
175 (make-string (window-width) (string-to-char sep))
176 todo-done-separator-string)
177 'face 'todo-done-sep)))
179 (defvar todo-done-separator (todo-done-separator)
180 "String used to visually separate done from not done items.
181 Displayed as an overlay instead of `todo-category-done' when
182 done items are shown. Its value is determined by user option
183 `todo-done-separator-string'.")
185 (defvar todo-show-done-only nil
186 "If non-nil display only done items in current category.
187 Set by the command `todo-toggle-view-done-only' and used by
188 `todo-category-select'.")
190 (defcustom todo-nondiary-marker '("[" "]")
191 "List of strings surrounding item date to block diary inclusion.
192 The first string is inserted before the item date and must be a
193 non-empty string that does not match a diary date in order to
194 have its intended effect. The second string is inserted after
196 :type '(list string string)
198 :initialize 'custom-initialize-default
199 :set 'todo-reset-nondiary-marker)
201 (defconst todo-nondiary-start (nth 0 todo-nondiary-marker)
202 "String inserted before item date to block diary inclusion.")
204 (defconst todo-nondiary-end (nth 1 todo-nondiary-marker)
205 "String inserted after item date matching `todo-nondiary-start'.")
207 (defconst todo-month-name-array
208 (vconcat calendar-month-name-array (vector "*"))
209 "Array of month names, in order.
210 The final element is \"*\", indicating an unspecified month.")
212 (defconst todo-month-abbrev-array
213 (vconcat calendar-month-abbrev-array (vector "*"))
214 "Array of abbreviated month names, in order.
215 The final element is \"*\", indicating an unspecified month.")
217 (defconst todo-date-pattern
218 (let ((dayname (diary-name-pattern calendar-day-name-array nil t)))
219 (concat "\\(?4:\\(?5:" dayname "\\)\\|"
221 (monthname (format "\\(?6:%s\\)" (diary-name-pattern
222 todo-month-name-array
223 todo-month-abbrev-array)))
224 (month "\\(?7:[0-9]+\\|\\*\\)")
225 (day "\\(?8:[0-9]+\\|\\*\\)")
226 (year "-?\\(?9:[0-9]+\\|\\*\\)"))
227 (mapconcat 'eval calendar-date-display-form ""))
229 "Regular expression matching a todo item date header.")
231 ;; By itself this matches anything, because of the `?'; however, it's only
232 ;; used in the context of `todo-date-pattern' (but Emacs Lisp lacks
234 (defconst todo-date-string-start
235 (concat "^\\(" (regexp-quote todo-nondiary-start) "\\|"
236 (regexp-quote diary-nonmarking-symbol) "\\)?")
237 "Regular expression matching part of item header before the date.")
239 (defcustom todo-done-string "DONE "
240 "Identifying string appended to the front of done todo items."
242 :initialize 'custom-initialize-default
243 :set 'todo-reset-done-string
246 (defconst todo-done-string-start
247 (concat "^\\[" (regexp-quote todo-done-string))
248 "Regular expression matching start of done item.")
250 (defconst todo-item-start (concat "\\(" todo-date-string-start "\\|"
251 todo-done-string-start "\\)"
253 "String identifying start of a todo item.")
255 ;; -----------------------------------------------------------------------------
256 ;;; Todo mode display options
257 ;; -----------------------------------------------------------------------------
259 (defcustom todo-prefix ""
260 "String prefixed to todo items for visual distinction."
261 :type '(string :validate
263 (when (string= (widget-value widget) todo-item-mark)
266 "Invalid value: must be distinct from `todo-item-mark'")
268 :initialize 'custom-initialize-default
269 :set 'todo-reset-prefix
270 :group 'todo-display)
272 (defcustom todo-number-prefix t
273 "Non-nil to prefix items with consecutively increasing integers.
274 These reflect the priorities of the items in each category."
276 :initialize 'custom-initialize-default
277 :set 'todo-reset-prefix
278 :group 'todo-display)
280 (defun todo-mode-line-control (cat)
281 "Return a mode line control for todo or archive file buffers.
282 Argument CAT is the name of the current todo category.
283 This function is the value of the user variable
284 `todo-mode-line-function'."
285 (let ((file (todo-short-file-name todo-current-todo-file)))
286 (format "%s category %d: %s" file todo-category-number cat)))
288 (defcustom todo-mode-line-function 'todo-mode-line-control
289 "Function that returns a mode line control for Todo mode buffers.
290 The function expects one argument holding the name of the current
291 todo category. The resulting control becomes the local value of
292 `mode-line-buffer-identification' in each Todo mode buffer."
294 :group 'todo-display)
296 (defcustom todo-highlight-item nil
297 "Non-nil means highlight items at point."
299 :initialize 'custom-initialize-default
300 :set 'todo-reset-highlight-item
301 :group 'todo-display)
303 (defcustom todo-wrap-lines t
304 "Non-nil to activate Visual Line mode and use wrap prefix."
306 :group 'todo-display)
308 (defcustom todo-indent-to-here 3
309 "Number of spaces to indent continuation lines of items.
310 This must be a positive number to ensure such items are fully
311 shown in the Fancy Diary display."
312 :type '(integer :validate
314 (unless (> (widget-value widget) 0)
315 (widget-put widget :error
316 "Invalid value: must be a positive integer")
318 :group 'todo-display)
320 (defun todo-indent ()
321 "Indent from point to `todo-indent-to-here'."
322 (indent-to todo-indent-to-here todo-indent-to-here))
324 (defcustom todo-show-with-done nil
325 "Non-nil to display done items in all categories."
327 :group 'todo-display)
329 ;; -----------------------------------------------------------------------------
331 ;; -----------------------------------------------------------------------------
334 ;; '((t :inherit font-lock-warning-face))
338 (:weight bold :foreground "Red1"))
342 (:weight bold :foreground "Pink"))
346 (:weight bold :foreground "Red1"))
350 (:weight bold :foreground "Pink"))
355 (:weight bold :inverse-video t)))
356 "Face for marks on marked items."
359 (defface todo-prefix-string
360 ;; '((t :inherit font-lock-constant-face))
361 '((((class grayscale) (background light))
362 (:foreground "LightGray" :weight bold :underline t))
363 (((class grayscale) (background dark))
364 (:foreground "Gray50" :weight bold :underline t))
365 (((class color) (min-colors 88) (background light)) (:foreground "dark cyan"))
366 (((class color) (min-colors 88) (background dark)) (:foreground "Aquamarine"))
367 (((class color) (min-colors 16) (background light)) (:foreground "CadetBlue"))
368 (((class color) (min-colors 16) (background dark)) (:foreground "Aquamarine"))
369 (((class color) (min-colors 8)) (:foreground "magenta"))
370 (t (:weight bold :underline t)))
371 "Face for todo item prefix or numerical priority string."
374 (defface todo-top-priority
375 ;; bold font-lock-comment-face
376 '((default :weight bold)
377 (((class grayscale) (background light)) :foreground "DimGray" :slant italic)
378 (((class grayscale) (background dark)) :foreground "LightGray" :slant italic)
379 (((class color) (min-colors 88) (background light)) :foreground "Firebrick")
380 (((class color) (min-colors 88) (background dark)) :foreground "chocolate1")
381 (((class color) (min-colors 16) (background light)) :foreground "red")
382 (((class color) (min-colors 16) (background dark)) :foreground "red1")
383 (((class color) (min-colors 8) (background light)) :foreground "red")
384 (((class color) (min-colors 8) (background dark)) :foreground "yellow")
386 "Face for top priority todo item numerical priority string.
387 The item's priority number string has this face if the number is
388 less than or equal the category's top priority setting."
391 (defface todo-nondiary
392 ;; '((t :inherit font-lock-type-face))
393 '((((class grayscale) (background light)) :foreground "Gray90" :weight bold)
394 (((class grayscale) (background dark)) :foreground "DimGray" :weight bold)
395 (((class color) (min-colors 88) (background light)) :foreground "ForestGreen")
396 (((class color) (min-colors 88) (background dark)) :foreground "PaleGreen")
397 (((class color) (min-colors 16) (background light)) :foreground "ForestGreen")
398 (((class color) (min-colors 16) (background dark)) :foreground "PaleGreen")
399 (((class color) (min-colors 8)) :foreground "green")
400 (t :weight bold :underline t))
401 "Face for non-diary markers around todo item date/time header."
405 '((t :inherit diary))
406 "Face for the date string of a todo item."
410 '((t :inherit diary-time))
411 "Face for the time string of a todo item."
414 (defface todo-diary-expired
415 ;; Doesn't contrast enough with todo-date (= diary) face.
416 ;; ;; '((t :inherit warning))
417 ;; '((default :weight bold)
418 ;; (((class color) (min-colors 16)) :foreground "DarkOrange")
419 ;; (((class color)) :foreground "yellow"))
420 ;; bold font-lock-function-name-face
421 '((default :weight bold)
422 (((class color) (min-colors 88) (background light)) :foreground "Blue1")
423 (((class color) (min-colors 88) (background dark)) :foreground "LightSkyBlue")
424 (((class color) (min-colors 16) (background light)) :foreground "Blue")
425 (((class color) (min-colors 16) (background dark)) :foreground "LightSkyBlue")
426 (((class color) (min-colors 8)) :foreground "blue")
427 (t :inverse-video t))
428 "Face for expired dates of diary items."
431 (defface todo-done-sep
432 ;; '((t :inherit font-lock-builtin-face))
433 '((((class grayscale) (background light)) :foreground "LightGray" :weight bold)
434 (((class grayscale) (background dark)) :foreground "DimGray" :weight bold)
435 (((class color) (min-colors 88) (background light)) :foreground "dark slate blue")
436 (((class color) (min-colors 88) (background dark)) :foreground "LightSteelBlue")
437 (((class color) (min-colors 16) (background light)) :foreground "Orchid")
438 (((class color) (min-colors 16) (background dark)) :foreground "LightSteelBlue")
439 (((class color) (min-colors 8)) :foreground "blue" :weight bold)
441 "Face for separator string between done and not done todo items."
445 ;; '((t :inherit font-lock-keyword-face))
446 '((((class grayscale) (background light)) :foreground "LightGray" :weight bold)
447 (((class grayscale) (background dark)) :foreground "DimGray" :weight bold)
448 (((class color) (min-colors 88) (background light)) :foreground "Purple")
449 (((class color) (min-colors 88) (background dark)) :foreground "Cyan1")
450 (((class color) (min-colors 16) (background light)) :foreground "Purple")
451 (((class color) (min-colors 16) (background dark)) :foreground "Cyan")
452 (((class color) (min-colors 8)) :foreground "cyan" :weight bold)
454 "Face for done todo item header string."
457 (defface todo-comment
458 ;; '((t :inherit font-lock-comment-face))
459 '((((class grayscale) (background light))
460 :foreground "DimGray" :weight bold :slant italic)
461 (((class grayscale) (background dark))
462 :foreground "LightGray" :weight bold :slant italic)
463 (((class color) (min-colors 88) (background light))
464 :foreground "Firebrick")
465 (((class color) (min-colors 88) (background dark))
466 :foreground "chocolate1")
467 (((class color) (min-colors 16) (background light))
469 (((class color) (min-colors 16) (background dark))
471 (((class color) (min-colors 8) (background light))
473 (((class color) (min-colors 8) (background dark))
474 :foreground "yellow")
475 (t :weight bold :slant italic))
476 "Face for comments appended to done todo items."
480 ;; '((t :inherit match))
484 (:background "yellow1"))
488 (:background "RoyalBlue3"))
492 (:foreground "black" :background "yellow"))
496 (:foreground "white" :background "blue"))
501 (:background "gray")))
502 "Face for matches found by `todo-search'."
506 ;; '((t :inherit widget-field))
508 (:foreground "black" :background "yellow3"))
509 (((class grayscale color)
511 (:background "gray85"))
512 (((class grayscale color)
514 (:background "dim gray"))
517 "Face for buttons in table of categories."
520 (defface todo-sorted-column
525 (:background "grey85"))
528 (:background "grey85" :foreground "grey10"))
530 (:background "gray")))
531 "Face for sorted column in table of categories."
534 (defface todo-archived-only
535 ;; '((t (:inherit (shadow))))
538 (:foreground "grey50"))
541 (:foreground "grey70"))
543 (:foreground "gray")))
544 "Face for archived-only category names in table of categories."
547 (defface todo-category-string
548 ;; '((t :inherit font-lock-type-face))
549 '((((class grayscale) (background light)) :foreground "Gray90" :weight bold)
550 (((class grayscale) (background dark)) :foreground "DimGray" :weight bold)
551 (((class color) (min-colors 88) (background light)) :foreground "ForestGreen")
552 (((class color) (min-colors 88) (background dark)) :foreground "PaleGreen")
553 (((class color) (min-colors 16) (background light)) :foreground "ForestGreen")
554 (((class color) (min-colors 16) (background dark)) :foreground "PaleGreen")
555 (((class color) (min-colors 8)) :foreground "green")
556 (t :weight bold :underline t))
557 "Face for category-file header in Todo Filtered Items mode."
560 ;; -----------------------------------------------------------------------------
561 ;;; Entering and exiting
562 ;; -----------------------------------------------------------------------------
564 (defcustom todo-visit-files-commands (list 'find-file 'dired-find-file)
565 "List of file finding commands for `todo-display-as-todo-file'.
566 Invoking these commands to visit a todo file or todo archive file
567 calls `todo-show' or `todo-find-archive', so that the file is
568 displayed correctly."
569 :type '(repeat function)
572 (defun todo-short-file-name (file)
573 "Return the short form of todo file FILE's name.
574 This lacks the extension and directory components."
576 (file-name-sans-extension (file-name-nondirectory file))))
578 (defcustom todo-default-todo-file (todo-short-file-name
579 (car (funcall todo-files-function)))
580 "Todo file visited by first session invocation of `todo-show'."
581 :type (when todo-files
582 `(radio ,@(mapcar (lambda (f) (list 'const f))
583 (mapcar 'todo-short-file-name
584 (funcall todo-files-function)))))
587 (defcustom todo-show-current-file t
588 "Non-nil to make `todo-show' visit the current todo file.
589 Otherwise, `todo-show' always visits `todo-default-todo-file'."
591 :initialize 'custom-initialize-default
592 :set 'todo-set-show-current-file
595 (defcustom todo-show-first 'first
596 "What action to take on first use of `todo-show' on a file."
597 :type '(choice (const :tag "Show first category" first)
598 (const :tag "Show table of categories" table)
599 (const :tag "Show top priorities" top)
600 (const :tag "Show diary items" diary)
601 (const :tag "Show regexp items" regexp))
604 (defcustom todo-add-item-if-new-category t
605 "Non-nil to prompt for an item after adding a new category."
609 (defcustom todo-initial-file "Todo"
610 "Default file name offered on adding first todo file."
614 (defcustom todo-initial-category "Todo"
615 "Default category name offered on initializing a new todo file."
619 (defcustom todo-category-completions-files nil
620 "List of files for building `todo-read-category' completions."
621 :type `(set ,@(mapcar (lambda (f) (list 'const f))
622 (mapcar 'todo-short-file-name
623 (funcall todo-files-function))))
626 (defcustom todo-completion-ignore-case nil
627 "Non-nil means case is ignored by `todo-read-*' functions."
632 (defun todo-show (&optional solicit-file interactive)
633 "Visit a todo file and display one of its categories.
635 When invoked in Todo mode, prompt for which todo file to visit.
636 When invoked outside of Todo mode with non-nil prefix argument
637 SOLICIT-FILE prompt for which todo file to visit; otherwise visit
638 `todo-default-todo-file'. Subsequent invocations from outside
639 of Todo mode revisit this file or, with option
640 `todo-show-current-file' non-nil (the default), whichever todo
641 file was last visited.
643 If you call this command before you have created any todo file in
644 the current format, and you have an todo file in old format, it
645 will ask you whether to convert that file and show it.
646 Otherwise, calling this command before any todo file exists
647 prompts for a file name and an initial category (defaulting to
648 `todo-initial-file' and `todo-initial-category'), creates both of
649 these, visits the file and displays the category, and if option
650 `todo-add-item-if-new-category' is non-nil (the default), prompts
653 The first invocation of this command on an existing todo file
654 interacts with the option `todo-show-first': if its value is
655 `first' (the default), show the first category in the file; if
656 its value is `table', show the table of categories in the file;
657 if its value is one of `top', `diary' or `regexp', show the
658 corresponding saved top priorities, diary items, or regexp items
659 file, if any. Subsequent invocations always show the file's
660 current (i.e., last displayed) category.
662 In Todo mode just the category's unfinished todo items are shown
663 by default. The done items are hidden, but typing
664 `\\[todo-toggle-view-done-items]' displays them below the todo
665 items. With non-nil user option `todo-show-with-done' both todo
666 and done items are always shown on visiting a category.
668 Invoking this command in Todo Archive mode visits the
669 corresponding todo file, displaying the corresponding category."
671 (when todo-default-todo-file
672 (todo-check-file (todo-absolute-file-name todo-default-todo-file)))
674 ;; Before initializing the first todo first, check if there is a
675 ;; legacy todo file and if so, offer to convert to the current
676 ;; format and make it the first new todo file.
677 (unless todo-default-todo-file
678 (let ((legacy-todo-file (if (boundp 'todo-file-do)
680 (locate-user-emacs-file "todo-do" ".todo-do"))))
681 (when (and (file-exists-p legacy-todo-file)
682 (y-or-n-p (concat "Do you want to convert a copy of your "
683 "old todo file to the new format? ")))
684 (when (todo-convert-legacy-files)
685 (throw 'shown nil)))))
688 (show-first todo-show-first)
689 (file (cond ((or solicit-file
691 (memq major-mode '(todo-mode
693 todo-filtered-items-mode))))
694 (if (funcall todo-files-function)
695 (todo-read-file-name "Choose a todo file to visit: "
697 (user-error "There are no todo files")))
698 ((and (eq major-mode 'todo-archive-mode)
699 ;; Called noninteractively via todo-quit
700 ;; to jump to corresponding category in
703 (setq cat (todo-current-category))
704 (concat (file-name-sans-extension
705 todo-current-todo-file) ".todo"))
707 (or todo-current-todo-file
708 (and todo-show-current-file
709 todo-global-current-todo-file)
710 (todo-absolute-file-name todo-default-todo-file)
713 (unless todo-default-todo-file
714 ;; We just initialized the first todo file, so make it the default.
715 (setq todo-default-todo-file (todo-short-file-name file)
717 (todo-reevaluate-default-file-defcustom))
718 (unless (member file todo-visited)
719 ;; Can't setq t-c-t-f here, otherwise wrong file shown when
720 ;; todo-show is called from todo-show-categories-table.
721 (let ((todo-current-todo-file file))
722 (cond ((eq todo-show-first 'table)
723 (todo-show-categories-table))
724 ((memq todo-show-first '(top diary regexp))
725 (let* ((shortf (todo-short-file-name file))
726 (fi-file (todo-absolute-file-name
727 shortf todo-show-first)))
728 (when (eq todo-show-first 'regexp)
729 (let ((rxfiles (directory-files todo-directory t
731 (when (and rxfiles (> (length rxfiles) 1))
732 (let ((rxf (mapcar 'todo-short-file-name rxfiles)))
733 (setq fi-file (todo-absolute-file-name
735 "Choose a regexp items file: "
737 (if (file-exists-p fi-file)
740 (set-buffer (find-file-noselect fi-file 'nowarn)))
741 (message "There is no %s file for %s"
742 (cond ((eq todo-show-first 'top)
744 ((eq todo-show-first 'diary)
746 ((eq todo-show-first 'regexp)
749 (setq todo-show-first 'first)))))))
750 (when (or (member file todo-visited)
751 (eq todo-show-first 'first))
752 (unless (todo-check-file file) (throw 'end nil))
753 (set-window-buffer (selected-window)
754 (set-buffer (find-file-noselect file 'nowarn)))
755 ;; When quitting an archive file, show the corresponding
756 ;; category in the corresponding todo file, if it exists.
757 (when (assoc cat todo-categories)
758 (setq todo-category-number (todo-category-number cat)))
759 ;; If this is a new todo file, add its first category.
760 (when (zerop (buffer-size))
763 (setq todo-category-number
764 (todo-add-category todo-current-todo-file "")
765 add-item todo-add-item-if-new-category
768 ;; If the category was added, save the file now, so we
769 ;; don't risk having an empty todo file, which would
770 ;; signal an error if we tried to visit it later,
771 ;; since doing that looks for category boundaries.
773 ;; If user cancels before adding the category, clean up
774 ;; and exit, so we have a fresh slate the next time.
776 ;; (setq todo-files (funcall todo-files-function))
777 (setq todo-files (delete file todo-files))
779 (setq todo-default-todo-file nil
780 todo-current-todo-file nil)
781 (todo-reevaluate-default-file-defcustom))
784 (save-excursion (todo-category-select))
785 (when add-item (todo-basic-insert-item)))
786 (setq todo-show-first show-first)
787 (add-to-list 'todo-visited file)))))
790 "Save the current todo file."
792 (cond ((eq major-mode 'todo-filtered-items-mode)
793 (todo-check-filtered-items-file)
794 (todo-save-filtered-items-buffer))
798 (defvar todo-descending-counts)
801 "Exit the current Todo-related buffer.
802 Depending on the specific mode, this either kills the buffer or
803 buries it and restores state as needed."
805 (let ((buf (current-buffer)))
806 (cond ((eq major-mode 'todo-categories-mode)
807 ;; Postpone killing buffer till after calling todo-show, to
808 ;; prevent killing todo-mode buffer.
809 (setq todo-descending-counts nil)
810 ;; Ensure todo-show calls todo-show-categories-table only on
811 ;; first invocation per file.
812 (when (eq todo-show-first 'table)
813 (add-to-list 'todo-visited todo-current-todo-file))
816 ((eq major-mode 'todo-filtered-items-mode)
818 (unless (eq major-mode 'todo-mode) (todo-show)))
819 ((eq major-mode 'todo-archive-mode)
820 ;; Have to write a newly created archive to file to avoid
821 ;; subsequent errors.
823 (let ((todo-file (concat todo-directory
824 (todo-short-file-name todo-current-todo-file)
826 (if (todo-check-file todo-file)
828 (message "There is no todo file for this archive")))
829 ;; When todo-check-file runs in todo-show, it kills the
830 ;; buffer if the archive file was deleted externally.
831 (when (buffer-live-p buf) (bury-buffer buf)))
832 ((eq major-mode 'todo-mode)
834 ;; If we just quit archive mode, just burying the buffer
835 ;; in todo-mode would return to archive.
836 (set-window-buffer (selected-window)
837 (set-buffer (other-buffer)))
838 (bury-buffer buf)))))
840 ;; -----------------------------------------------------------------------------
841 ;;; Navigation between and within categories
842 ;; -----------------------------------------------------------------------------
844 (defcustom todo-skip-archived-categories nil
845 "Non-nil to handle categories with only archived items specially.
847 Sequential category navigation using \\[todo-forward-category]
848 or \\[todo-backward-category] skips categories that contain only
849 archived items. Other commands still recognize these categories.
850 In Todo Categories mode (\\[todo-show-categories-table]) these
851 categories shown in `todo-archived-only' face and pressing the
852 category button visits the category in the archive instead of the
855 :group 'todo-display)
857 (defun todo-forward-category (&optional back)
858 "Visit the numerically next category in this todo file.
859 If the current category is the highest numbered, visit the first
860 category. With non-nil argument BACK, visit the numerically
861 previous category (the highest numbered one, if the current
862 category is the first)."
864 (setq todo-category-number
865 (1+ (mod (- todo-category-number (if back 2 0))
866 (length todo-categories))))
867 (when todo-skip-archived-categories
868 (while (and (zerop (todo-get-count 'todo))
869 (zerop (todo-get-count 'done))
870 (not (zerop (todo-get-count 'archived))))
871 (setq todo-category-number
872 (apply (if back '1- '1+) (list todo-category-number)))))
873 (todo-category-select)
874 (goto-char (point-min)))
876 (defun todo-backward-category ()
877 "Visit the numerically previous category in this todo file.
878 If the current category is the highest numbered, visit the first
881 (todo-forward-category t))
883 (defvar todo-categories-buffer)
885 (defun todo-jump-to-category (&optional file where)
886 "Prompt for a category in a todo file and jump to it.
888 With non-nil FILE (interactively a prefix argument), prompt for a
889 specific todo file and choose (with TAB completion) a category
890 in it to jump to; otherwise, choose and jump to any category in
891 either the current todo file or a file in
892 `todo-category-completions-files'.
894 Also accept a non-existing category name and ask whether to add a
895 new category by that name; on confirmation, add it and jump to
896 that category, and if option `todo-add-item-if-new-category' is
897 non-nil (the default), then prompt for the first item.
899 In noninteractive calls non-nil WHERE specifies either the goal
900 category or its file. If its value is `archive', the choice of
901 categories is restricted to the current archive file or the
902 archive you were prompted to choose; this is used by
903 `todo-jump-to-archive-category'. If its value is the name of a
904 category, jump directly to that category; this is used in Todo
907 ;; If invoked outside of Todo mode and there is not yet any Todo
908 ;; file, initialize one.
909 (if (null (funcall todo-files-function))
911 (let* ((archive (eq where 'archive))
912 (cat (unless archive where))
913 (file0 (when cat ; We're in Todo Categories mode.
914 ;; With non-nil `todo-skip-archived-categories'
915 ;; jump to archive file of a category with only
917 (if (and todo-skip-archived-categories
918 (zerop (todo-get-count 'todo cat))
919 (zerop (todo-get-count 'done cat))
920 (not (zerop (todo-get-count 'archived cat))))
921 (concat (file-name-sans-extension
922 todo-current-todo-file) ".toda")
923 ;; Otherwise, jump to current todo file.
924 todo-current-todo-file)))
925 (len (length todo-categories))
926 (cat+file (unless cat
927 (todo-read-category "Jump to category: "
928 (if archive 'archive) file)))
929 (add-item (and todo-add-item-if-new-category
930 (> (length todo-categories) len)))
931 (category (or cat (car cat+file))))
932 (unless cat (setq file0 (cdr cat+file)))
933 (with-current-buffer (find-file-noselect file0 'nowarn)
934 (setq todo-current-todo-file file0)
935 ;; If called from Todo Categories mode, clean up before jumping.
936 (if (string= (buffer-name) todo-categories-buffer)
938 (set-window-buffer (selected-window)
939 (set-buffer (find-buffer-visiting file0)))
940 (unless todo-global-current-todo-file
941 (setq todo-global-current-todo-file todo-current-todo-file))
942 (todo-category-number category)
943 (todo-category-select)
944 (goto-char (point-min))
945 (when add-item (todo-basic-insert-item))))))
947 (defun todo-next-item (&optional count)
948 "Move point down to the beginning of the next item.
949 With positive numerical prefix COUNT, move point COUNT items
952 If the category's done items are hidden, this command also moves
953 point to the empty line below the last todo item from any higher
954 item in the category, i.e., when invoked with or without a prefix
955 argument. If the category's done items are visible, this command
956 called with a prefix argument only moves point to a lower item,
957 e.g., with point on the last todo item and called with prefix 1,
958 it moves point to the first done item; but if called with point
959 on the last todo item without a prefix argument, it moves point
960 the the empty line above the done items separator."
962 ;; It's not worth the trouble to allow prefix arg value < 1, since
963 ;; we have the corresponding command.
964 (cond ((and current-prefix-arg (< count 1))
965 (user-error "The prefix argument must be a positive number"))
967 (todo-forward-item count))
969 (todo-forward-item))))
971 (defun todo-previous-item (&optional count)
972 "Move point up to start of item with next higher priority.
973 With positive numerical prefix COUNT, move point COUNT items
976 If the category's done items are visible, this command called
977 with a prefix argument only moves point to a higher item, e.g.,
978 with point on the first done item and called with prefix 1, it
979 moves to the last todo item; but if called with point on the
980 first done item without a prefix argument, it moves point the the
981 empty line above the done items separator."
983 ;; Avoid moving to bob if on the first item but not at bob.
984 (when (> (line-number-at-pos) 1)
985 ;; It's not worth the trouble to allow prefix arg value < 1, since
986 ;; we have the corresponding command.
987 (cond ((and current-prefix-arg (< count 1))
988 (user-error "The prefix argument must be a positive number"))
990 (todo-backward-item count))
992 (todo-backward-item)))))
994 ;; -----------------------------------------------------------------------------
995 ;;; Display toggle commands
996 ;; -----------------------------------------------------------------------------
998 (defun todo-toggle-prefix-numbers ()
999 "Hide item numbering if shown, show if hidden."
1003 (goto-char (point-min))
1004 (let* ((ov (todo-get-overlay 'prefix))
1005 (show-done (re-search-forward todo-done-string-start nil t))
1006 (todo-show-with-done show-done)
1007 (todo-number-prefix (not (equal (overlay-get ov 'before-string)
1009 (if (eq major-mode 'todo-filtered-items-mode)
1010 (todo-prefix-overlays)
1011 (todo-category-select))))))
1013 (defun todo-toggle-view-done-items ()
1014 "Show hidden or hide visible done items in current category."
1016 (if (zerop (todo-get-count 'done (todo-current-category)))
1017 (message "There are no done items in this category.")
1018 (let ((opoint (point)))
1019 (goto-char (point-min))
1020 (let* ((shown (re-search-forward todo-done-string-start nil t))
1021 (todo-show-with-done (not shown)))
1022 (todo-category-select)
1024 ;; If start of done items sections is below the bottom of the
1025 ;; window, make it visible.
1028 (goto-char (point-min))
1029 (re-search-forward todo-done-string-start nil t)))
1030 (if (not (pos-visible-in-window-p shown))
1032 (goto-char opoint)))))))
1034 (defun todo-toggle-view-done-only ()
1035 "Switch between displaying only done or only todo items."
1037 (setq todo-show-done-only (not todo-show-done-only))
1038 (todo-category-select))
1040 (defun todo-toggle-item-highlighting ()
1041 "Highlight or unhighlight the todo item the cursor is on."
1043 (eval-when-compile (require 'hl-line))
1044 (when (memq major-mode
1045 '(todo-mode todo-archive-mode todo-filtered-items-mode))
1050 (defun todo-toggle-item-header ()
1051 "Hide or show item date-time headers in the current file.
1052 With done items, this hides only the done date-time string, not
1053 the the original date-time string."
1057 (goto-char (point-min))
1058 (let ((ov (todo-get-overlay 'header)))
1060 (remove-overlays 1 (1+ (buffer-size)) 'todo 'header)
1062 (goto-char (point-min))
1064 (when (re-search-forward
1065 (concat todo-item-start
1066 "\\( " diary-time-regexp "\\)?"
1067 (regexp-quote todo-nondiary-end) "? ")
1069 (setq ov (make-overlay (match-beginning 0) (match-end 0) nil t))
1070 (overlay-put ov 'todo 'header)
1071 (overlay-put ov 'display ""))
1072 (todo-forward-item)))))))
1074 ;; -----------------------------------------------------------------------------
1075 ;;; File and category editing
1076 ;; -----------------------------------------------------------------------------
1078 (defun todo-add-file ()
1079 "Name and initialize a new todo file.
1080 Interactively, prompt for a category and display it, and if
1081 option `todo-add-item-if-new-category' is non-nil (the default),
1082 prompt for the first item.
1083 Noninteractively, return the name of the new file."
1085 (let* ((prompt (concat "Enter name of new todo file "
1086 "(TAB or SPC to see current names): "))
1087 (file (todo-read-file-name prompt)))
1088 (with-current-buffer (get-buffer-create file)
1090 (write-region (point-min) (point-max) file nil 'nomessage nil t)
1092 (setq todo-files (funcall todo-files-function))
1093 (todo-reevaluate-filelist-defcustoms)
1094 (if (called-interactively-p 'any)
1096 (set-window-buffer (selected-window)
1097 (set-buffer (find-file-noselect file)))
1098 (setq todo-current-todo-file file)
1102 (defun todo-rename-file (&optional arg)
1103 "Rename the current todo file.
1104 With prefix ARG, prompt for a todo file and rename it.
1105 If there are corresponding archive or filtered items files,
1106 rename these accordingly. If there are live buffers visiting
1107 these files, also rename them accordingly."
1109 (let* ((oname (or (and arg
1110 (todo-read-file-name "Choose a file to rename: "
1112 (buffer-file-name)))
1113 (soname (todo-short-file-name oname))
1114 (nname (todo-read-file-name "New name for this file: "))
1115 (snname (todo-short-file-name nname))
1116 (files (directory-files todo-directory t
1117 (concat ".*" (regexp-quote soname)
1118 ".*\.tod[aorty]$") t)))
1120 (let ((sfname (todo-short-file-name f))
1121 (fext (file-name-extension f t))
1122 (fbuf (find-buffer-visiting f)))
1123 (when (string-match (regexp-quote soname) sfname)
1124 (let* ((snfname (replace-match snname t t sfname))
1125 (nfname (concat todo-directory snfname fext)))
1126 (rename-file f nfname)
1128 (with-current-buffer fbuf
1129 (set-visited-file-name nfname t t)
1130 (cond ((member fext '(".todo" ".toda"))
1131 (setq todo-current-todo-file (buffer-file-name))
1132 (setq mode-line-buffer-identification
1133 (funcall todo-mode-line-function
1134 (todo-current-category))))
1137 (replace-regexp-in-string
1138 (regexp-quote soname) snfname))))))))))))
1140 (defun todo-delete-file ()
1141 "Delete the current todo, archive or filtered items file.
1142 If the todo file has a corresponding archive file, or vice versa,
1143 prompt whether to delete that as well. Also kill the buffers
1144 visiting the deleted files."
1146 (let* ((file1 (buffer-file-name))
1147 (todo (eq major-mode 'todo-mode))
1148 (archive (eq major-mode 'todo-archive-mode))
1149 (filtered (eq major-mode 'todo-filtered-items-mode))
1150 (file1-sn (todo-short-file-name file1))
1151 (file2 (concat todo-directory file1-sn (cond (todo ".toda")
1152 (archive ".todo"))))
1153 (buf1 (current-buffer))
1154 (buf2 (when file2 (find-buffer-visiting file2)))
1155 (prompt1 (concat "Delete " (cond (todo "todo")
1157 (filtered "filtered items"))
1159 (prompt2 (concat "Also delete the corresponding "
1160 (cond (todo "archive") (archive "todo")) " file "
1161 (when buf2 "and kill the buffer visiting it? ")))
1162 (delete1 (yes-or-no-p (format prompt1 file1-sn)))
1163 (delete2 (when (and delete1 (or (file-exists-p file2) buf2))
1164 (yes-or-no-p prompt2))))
1166 (when (file-exists-p file1) (delete-file file1))
1167 (setq todo-visited (delete file1 todo-visited))
1170 (when (file-exists-p file2) (delete-file file2))
1171 (setq todo-visited (delete file2 todo-visited))
1172 (and buf2 (kill-buffer buf2)))
1173 (setq todo-files (funcall todo-files-function)
1174 todo-archives (funcall todo-files-function t))
1175 (when (or (string= file1-sn todo-default-todo-file)
1176 (and delete2 (string= file1-sn todo-default-todo-file)))
1177 (setq todo-default-todo-file (todo-short-file-name (car todo-files))))
1178 (when (or (string= file1 todo-global-current-todo-file)
1179 (and delete2 (string= file2 todo-global-current-todo-file)))
1180 (setq todo-global-current-todo-file nil))
1181 (todo-reevaluate-filelist-defcustoms)
1182 (message (concat (cond (todo "Todo") (archive "Archive")) " file \"%s\" "
1185 (cond (todo "archive") (archive "todo"))
1187 "deleted") file1-sn))))
1189 (defvar todo-edit-buffer "*Todo Edit*"
1190 "Name of current buffer in Todo Edit mode.")
1192 (defun todo-edit-file ()
1193 "Put current buffer in `todo-edit-mode'.
1194 This makes the entire file visible and the buffer writeable and
1195 you can use the self-insertion keys and standard Emacs editing
1196 commands to make changes. To return to Todo mode, type
1197 \\[todo-edit-quit]. This runs a file format check, signaling
1198 an error if the format has become invalid. However, this check
1199 cannot tell if the number of items changed, which could result in
1200 the file containing inconsistent information. For this reason
1201 this command should be used with caution."
1206 (message "%s" (substitute-command-keys
1207 (concat "Type \\[todo-edit-quit] to check file format "
1208 "validity and return to Todo mode.\n"))))
1210 (defun todo-add-category (&optional file cat)
1211 "Add a new category to a todo file.
1213 Called interactively with prefix argument FILE, prompt for a file
1214 and then for a new category to add to that file, otherwise prompt
1215 just for a category to add to the current todo file. After
1216 adding the category, visit it in Todo mode and if option
1217 `todo-add-item-if-new-category' is non-nil (the default), prompt
1220 Non-interactively, add category CAT to file FILE; if FILE is nil,
1221 add CAT to the current todo file. After adding the category,
1222 return the new category number."
1225 ;; If cat is passed from caller, don't prompt, unless it is "",
1226 ;; which means the file was just added and has no category yet.
1227 (if (and cat (> (length cat) 0))
1228 (setq file0 (or (and (stringp file) file)
1229 todo-current-todo-file))
1230 (setq catfil (todo-read-category "Enter a new category name: "
1231 'add (when (called-interactively-p 'any)
1234 file0 (if (called-interactively-p 'any)
1238 (let ((counts (make-vector 4 0)) ; [todo diary done archived]
1239 (num (1+ (length todo-categories)))
1240 (buffer-read-only nil))
1241 (setq todo-current-todo-file file0)
1242 (setq todo-categories (append todo-categories
1243 (list (cons cat counts))))
1245 (goto-char (point-max))
1246 (save-excursion ; Save point for todo-category-select.
1247 (insert todo-category-beg cat "\n\n" todo-category-done "\n"))
1248 (todo-update-categories-sexp)
1249 ;; If invoked by user, display the newly added category, if
1250 ;; called programmatically return the category number to the
1252 (if (called-interactively-p 'any)
1254 (setq todo-category-number num)
1255 (todo-category-select)
1256 (when todo-add-item-if-new-category
1257 (todo-basic-insert-item)))
1260 (defun todo-rename-category ()
1261 "Rename current todo category.
1262 If this file has an archive containing this category, rename the
1263 category there as well."
1265 (let* ((cat (todo-current-category))
1266 (new (read-from-minibuffer
1267 (format "Rename category \"%s\" to: " cat))))
1268 (setq new (todo-validate-name new 'category))
1269 (let* ((ofile todo-current-todo-file)
1270 (archive (concat (file-name-sans-extension ofile) ".toda"))
1271 (buffers (append (list ofile)
1272 (unless (zerop (todo-get-count 'archived cat))
1274 (dolist (buf buffers)
1275 (with-current-buffer (find-file-noselect buf)
1276 (let (buffer-read-only)
1277 (setq todo-categories (todo-set-categories))
1280 (setcar (assoc cat todo-categories) new)
1282 (goto-char (point-min))
1283 (todo-update-categories-sexp)
1284 (re-search-forward (concat (regexp-quote todo-category-beg)
1285 "\\(" (regexp-quote cat) "\\)\n")
1287 (replace-match new t t nil 1)))))))
1288 (force-mode-line-update))
1289 (save-excursion (todo-category-select)))
1291 (defun todo-delete-category (&optional arg)
1292 "Delete current todo category provided it contains no items.
1293 With prefix ARG delete the category even if it does contain
1294 todo or done items."
1296 (let* ((file todo-current-todo-file)
1297 (cat (todo-current-category))
1298 (todo (todo-get-count 'todo cat))
1299 (done (todo-get-count 'done cat))
1300 (archived (todo-get-count 'archived cat)))
1302 (or (> todo 0) (> done 0)))
1303 (message "%s" (substitute-command-keys
1304 (concat "To delete a non-empty category, "
1305 "type C-u \\[todo-delete-category].")))
1306 (when (cond ((= (length todo-categories) 1)
1308 (concat "This is the only category in this file; "
1309 "deleting it will also delete the file.\n"
1310 "Do you want to proceed? ")))
1312 (todo-y-or-n-p (concat "This category has archived items; "
1313 "the archived category will remain\n"
1314 "after deleting the todo category. "
1315 "Do you still want to delete it\n"
1316 "(see `todo-skip-archived-categories' "
1317 "for another option)? ")))
1319 (todo-y-or-n-p (concat "Permanently remove category \"" cat
1320 "\"" (and arg " and all its entries")
1323 (let ((buffer-read-only)
1324 (beg (re-search-backward
1325 (concat "^" (regexp-quote (concat todo-category-beg cat))
1327 (end (if (re-search-forward
1328 (concat "\n\\(" (regexp-quote todo-category-beg)
1332 (remove-overlays beg end)
1333 (delete-region beg end)
1334 (if (= (length todo-categories) 1)
1335 ;; If deleted category was the only one, delete the file.
1337 (todo-reevaluate-filelist-defcustoms)
1338 ;; Skip confirming killing the archive buffer if it has been
1339 ;; modified and not saved.
1340 (set-buffer-modified-p nil)
1343 (message "Deleted todo file %s." file))
1344 (setq todo-categories (delete (assoc cat todo-categories)
1346 (todo-update-categories-sexp)
1347 (setq todo-category-number
1348 (1+ (mod todo-category-number (length todo-categories))))
1349 (todo-category-select)
1350 (goto-char (point-min))
1351 (message "Deleted category %s." cat)))))))
1353 (defun todo-move-category ()
1354 "Move current category to a different todo file.
1355 If current category has archived items, also move those to the
1356 archive of the file moved to, creating it if it does not exist."
1358 (when (or (> (length todo-categories) 1)
1359 (todo-y-or-n-p (concat "This is the only category in this file; "
1360 "moving it will also delete the file.\n"
1361 "Do you want to proceed? ")))
1362 (let* ((ofile todo-current-todo-file)
1363 (cat (todo-current-category))
1364 (nfile (todo-read-file-name
1365 "Choose a todo file to move this category to: " nil t))
1366 (archive (concat (file-name-sans-extension ofile) ".toda"))
1367 (buffers (append (list ofile)
1368 (unless (zerop (todo-get-count 'archived cat))
1371 (while (equal (file-truename nfile) (file-truename ofile))
1372 (setq nfile (todo-read-file-name
1373 "Choose a file distinct from this file: " nil t)))
1374 (dolist (buf buffers)
1375 (with-current-buffer (find-file-noselect buf)
1377 (goto-char (point-max))
1378 (let* ((beg (re-search-backward
1380 (regexp-quote (concat todo-category-beg cat))
1383 (end (if (re-search-forward
1384 (concat "^" (regexp-quote todo-category-beg))
1388 (content (buffer-substring-no-properties beg end))
1389 (counts (cdr (assoc cat todo-categories)))
1391 ;; Move the category to the new file. Also update or create
1392 ;; archive file if necessary.
1393 (with-current-buffer
1395 ;; Regenerate todo-archives in case there
1396 ;; is a newly created archive.
1397 (if (member buf (funcall todo-files-function t))
1398 (concat (file-name-sans-extension nfile) ".toda")
1400 (let* ((nfile-short (todo-short-file-name nfile))
1402 (format "Todo file \"%s\" already has "
1404 (format "the category \"%s\";\n" cat)
1405 "enter a new category name: "))
1408 (goto-char (point-max))
1410 ;; If the file moved to has a category with the same
1411 ;; name, rename the moved category.
1412 (when (assoc cat todo-categories)
1413 (unless (member (file-truename (buffer-file-name))
1414 (funcall todo-files-function t))
1415 (setq new (read-from-minibuffer prompt))
1416 (setq new (todo-validate-name new 'category))))
1417 ;; Replace old with new name in todo and archive files.
1419 (goto-char (point-max))
1421 (concat "^" (regexp-quote todo-category-beg)
1422 "\\(" (regexp-quote cat) "\\)$") nil t)
1423 (replace-match new nil nil nil 1)))
1424 (setq todo-categories
1425 (append todo-categories (list (cons new counts))))
1426 (todo-update-categories-sexp)
1427 ;; If archive was just created, save it to avoid "File
1428 ;; <xyz> no longer exists!" message on invoking
1429 ;; `todo-view-archived-items'.
1430 (unless (file-exists-p (buffer-file-name))
1432 (todo-category-number (or new cat))
1433 (todo-category-select))
1434 ;; Delete the category from the old file, and if that was the
1435 ;; last category, delete the file. Also handle archive file
1437 (remove-overlays beg end)
1438 (delete-region beg end)
1439 (goto-char (point-min))
1440 ;; Put point after todo-categories sexp.
1442 (if (eobp) ; Aside from sexp, file is empty.
1444 ;; Skip confirming killing the archive buffer.
1445 (set-buffer-modified-p nil)
1446 (delete-file todo-current-todo-file)
1448 (when (member todo-current-todo-file todo-files)
1449 (todo-reevaluate-filelist-defcustoms)))
1450 (setq todo-categories (delete (assoc cat todo-categories)
1452 (todo-update-categories-sexp)
1453 (todo-category-select)))))
1454 (set-window-buffer (selected-window)
1455 (set-buffer (find-file-noselect nfile)))
1456 (todo-category-number (or new cat))
1457 (todo-category-select))))
1459 (defun todo-merge-category (&optional file)
1460 "Merge current category into another existing category.
1462 With prefix argument FILE, prompt for a specific todo file and
1463 choose (with TAB completion) a category in it to merge into;
1464 otherwise, choose and merge into a category in either the
1465 current todo file or a file in `todo-category-completions-files'.
1467 After merging, the current category's todo and done items are
1468 appended to the chosen goal category's todo and done items,
1469 respectively. The goal category becomes the current category,
1470 and the previous current category is deleted.
1472 If both the first and goal categories also have archived items,
1473 the former are merged to the latter. If only the first category
1474 has archived items, the archived category is renamed to the goal
1477 (let* ((tfile todo-current-todo-file)
1478 (cat (todo-current-category))
1479 (cat+file (todo-read-category "Merge into category: " 'todo file))
1480 (goal (car cat+file))
1481 (gfile (cdr cat+file))
1482 (archive (concat (file-name-sans-extension (if file gfile tfile))
1484 archived-count here)
1485 ;; Merge in todo file.
1486 (with-current-buffer (get-buffer (find-file-noselect tfile))
1488 (let* ((buffer-read-only nil)
1491 (concat "^" (regexp-quote todo-category-beg)) nil t)
1493 (tbeg (progn (forward-line) (point-marker)))
1496 (concat "^" (regexp-quote todo-category-done)) nil t)
1497 (forward-line) (point-marker)))
1498 ;; Omit empty line between todo and done items.
1499 (tend (progn (forward-line -2) (point-marker)))
1501 (if (re-search-forward
1502 (concat "^" (regexp-quote todo-category-beg)) nil t)
1504 (goto-char (match-beginning 0))
1506 (point-max-marker))))
1507 (todo (buffer-substring-no-properties tbeg tend))
1508 (done (buffer-substring-no-properties dbeg cend)))
1509 (goto-char (point-min))
1510 ;; Merge any todo items.
1511 (unless (zerop (length todo))
1513 (concat "^" (regexp-quote (concat todo-category-beg goal)) "$")
1516 (concat "^" (regexp-quote todo-category-done)) nil t)
1518 (setq here (point-marker))
1520 (todo-update-count 'todo (todo-get-count 'todo cat) goal))
1521 ;; Merge any done items.
1522 (unless (zerop (length done))
1523 (goto-char (if (re-search-forward
1524 (concat "^" (regexp-quote todo-category-beg)) nil t)
1527 (when (zerop (length todo)) (setq here (point-marker)))
1529 (todo-update-count 'done (todo-get-count 'done cat) goal))
1530 (remove-overlays cbeg cend)
1531 (delete-region cbeg cend)
1532 (setq todo-categories (delete (assoc cat todo-categories)
1534 (todo-update-categories-sexp)
1535 (mapc (lambda (m) (set-marker m nil)) (list cbeg tbeg dbeg tend cend))))
1536 (when (file-exists-p archive)
1537 ;; Merge in archive file.
1538 (with-current-buffer (get-buffer (find-file-noselect archive))
1540 (goto-char (point-min))
1541 (let ((buffer-read-only nil)
1542 (cbeg (save-excursion
1543 (when (re-search-forward
1544 (concat "^" (regexp-quote
1545 (concat todo-category-beg cat)) "$")
1547 (goto-char (match-beginning 0))
1549 (gbeg (save-excursion
1550 (when (re-search-forward
1551 (concat "^" (regexp-quote
1552 (concat todo-category-beg goal)) "$")
1554 (goto-char (match-beginning 0))
1558 (setq archived-count (todo-get-count 'done cat))
1559 (setq cend (save-excursion
1560 (if (re-search-forward
1561 (concat "^" (regexp-quote todo-category-beg))
1565 (setq carch (save-excursion (goto-char cbeg) (forward-line)
1566 (buffer-substring-no-properties (point) cend)))
1567 ;; If both categories of the merge have archived items, merge the
1568 ;; source items to the goal items, else "merge" by renaming the
1569 ;; source category to goal.
1572 (goto-char (if (re-search-forward
1573 (concat "^" (regexp-quote todo-category-beg))
1578 (remove-overlays cbeg cend)
1579 (delete-region cbeg cend))
1581 (search-forward cat)
1582 (replace-match goal))
1583 (setq todo-categories (todo-make-categories-list t))
1584 (todo-update-categories-sexp)))))
1585 (with-current-buffer (get-file-buffer tfile)
1586 (when archived-count
1587 (unless (zerop archived-count)
1588 (todo-update-count 'archived archived-count goal)
1589 (todo-update-categories-sexp)))
1590 (todo-category-number goal)
1591 ;; If there are only merged done items, show them.
1592 (let ((todo-show-with-done (zerop (todo-get-count 'todo goal))))
1593 (todo-category-select)
1594 ;; Put point on the first merged item.
1596 (set-marker here nil)))
1598 ;; -----------------------------------------------------------------------------
1600 ;; -----------------------------------------------------------------------------
1602 (defcustom todo-include-in-diary nil
1603 "Non-nil to allow new todo items to be included in the diary."
1607 (defcustom todo-diary-nonmarking nil
1608 "Non-nil to insert new todo diary items as nonmarking by default.
1609 This appends `diary-nonmarking-symbol' to the front of an item on
1610 insertion provided it doesn't begin with `todo-nondiary-marker'."
1614 (defcustom todo-always-add-time-string nil
1615 "Non-nil adds current time to a new item's date header by default.
1616 When the todo insertion commands have a non-nil \"maybe-notime\"
1617 argument, this reverses the effect of
1618 `todo-always-add-time-string': if t, these commands omit the
1619 current time, if nil, they include it."
1623 (defcustom todo-use-only-highlighted-region t
1624 "Non-nil to enable inserting only highlighted region as new item."
1628 (defcustom todo-item-mark "*"
1629 "String used to mark items.
1630 To ensure item marking works, change the value of this option
1631 only when no items are marked."
1632 :type '(string :validate
1634 (when (string= (widget-value widget) todo-prefix)
1637 "Invalid value: must be distinct from `todo-prefix'")
1639 :set (lambda (symbol value)
1640 (custom-set-default symbol (propertize value 'face 'todo-mark)))
1643 (defcustom todo-comment-string "COMMENT"
1644 "String inserted before optional comment appended to done item."
1646 :initialize 'custom-initialize-default
1647 :set 'todo-reset-comment-string
1650 (defcustom todo-undo-item-omit-comment 'ask
1651 "Whether to omit done item comment on undoing the item.
1652 Nil means never omit the comment, t means always omit it, `ask'
1653 means prompt user and omit comment only on confirmation."
1654 :type '(choice (const :tag "Never" nil)
1655 (const :tag "Always" t)
1656 (const :tag "Ask" ask))
1659 (defun todo-toggle-mark-item (&optional n)
1660 "Mark item with `todo-item-mark' if unmarked, otherwise unmark it.
1661 With a positive numerical prefix argument N, change the
1662 marking of the next N items."
1664 (when (todo-item-string)
1665 (unless (> n 1) (setq n 1))
1667 (let* ((cat (todo-current-category))
1668 (marks (assoc cat todo-categories-with-marks))
1670 (unless (looking-at todo-item-start)
1672 (todo-get-overlay 'prefix)))
1673 (pref (overlay-get ov 'before-string)))
1674 (if (todo-marked-item-p)
1676 (overlay-put ov 'before-string (substring pref 1))
1677 (if (= (cdr marks) 1) ; Deleted last mark in this category.
1678 (setq todo-categories-with-marks
1679 (assq-delete-all cat todo-categories-with-marks))
1680 (setcdr marks (1- (cdr marks)))))
1681 (overlay-put ov 'before-string (concat todo-item-mark pref))
1683 (setcdr marks (1+ (cdr marks)))
1684 (push (cons cat 1) todo-categories-with-marks))))
1685 (todo-forward-item))))
1687 (defun todo-mark-category ()
1688 "Mark all visible items in this category with `todo-item-mark'."
1690 (let* ((cat (todo-current-category))
1691 (marks (assoc cat todo-categories-with-marks)))
1693 (goto-char (point-min))
1695 (let* ((ov (todo-get-overlay 'prefix))
1696 (pref (overlay-get ov 'before-string)))
1697 (unless (todo-marked-item-p)
1698 (overlay-put ov 'before-string (concat todo-item-mark pref))
1700 (setcdr marks (1+ (cdr marks)))
1701 (push (cons cat 1) todo-categories-with-marks))))
1702 (todo-forward-item)))))
1704 (defun todo-unmark-category ()
1705 "Remove `todo-item-mark' from all visible items in this category."
1707 (let* ((cat (todo-current-category))
1708 (marks (assoc cat todo-categories-with-marks)))
1710 (goto-char (point-min))
1712 (let* ((ov (todo-get-overlay 'prefix))
1713 ;; No overlay on empty line between todo and done items.
1714 (pref (when ov (overlay-get ov 'before-string))))
1715 (when (todo-marked-item-p)
1716 (overlay-put ov 'before-string (substring pref 1)))
1717 (todo-forward-item))))
1718 (setq todo-categories-with-marks
1719 (delq marks todo-categories-with-marks))))
1721 (defvar todo-date-from-calendar nil
1722 "Helper variable for setting item date from the Emacs Calendar.")
1724 (defun todo-basic-insert-item (&optional arg diary nonmarking date-type time
1726 "Insert a new todo item into a category.
1727 This is the function from which the generated Todo mode item
1728 insertion commands derive.
1730 The generated commands have mnemonic key bindings based on the
1731 arguments' values and their order in the command's argument list,
1732 as follows: (1) for DIARY `d', (2) for NONMARKING `k', (3) for
1733 DATE-TYPE either `c' for calendar or `d' for date or `n' for
1734 weekday name, (4) for TIME `t', (5) for REGION-OR-HERE either `r'
1735 for region or `h' for here. Sequences of these keys are appended
1736 to the insertion prefix key `i'. Keys that allow a following
1737 key (i.e., any but `r' or `h') must be doubled when used finally.
1738 For example, the command bound to the key sequence `i y h' will
1739 insert a new item with today's date, marked according to the
1740 DIARY argument described below, and with priority according to
1741 the HERE argument; `i y y' does the same except that the priority
1742 is not given by HERE but by prompting.
1744 In command invocations, ARG is passed as a prefix argument as
1745 follows. With no prefix argument, add the item to the current
1746 category; with one prefix argument (`C-u'), prompt for a category
1747 from the current todo file; with two prefix arguments (`C-u C-u'),
1748 first prompt for a todo file, then a category in that file. If
1749 a non-existing category is entered, ask whether to add it to the
1750 todo file; if answered affirmatively, add the category and
1751 insert the item there.
1753 The remaining arguments are set or left nil by the generated item
1754 insertion commands; their meanings are described in the follows
1757 When argument DIARY is non-nil, this overrides the intent of the
1758 user option `todo-include-in-diary' for this item: if
1759 `todo-include-in-diary' is nil, include the item in the Fancy
1760 Diary display, and if it is non-nil, exclude the item from the
1761 Fancy Diary display. When DIARY is nil, `todo-include-in-diary'
1762 has its intended effect.
1764 When the item is included in the Fancy Diary display and the
1765 argument NONMARKING is non-nil, this overrides the intent of the
1766 user option `todo-diary-nonmarking' for this item: if
1767 `todo-diary-nonmarking' is nil, append `diary-nonmarking-symbol'
1768 to the item, and if it is non-nil, omit `diary-nonmarking-symbol'.
1770 The argument DATE-TYPE determines the content of the item's
1771 mandatory date header string and how it is added:
1772 - If DATE-TYPE is the symbol `calendar', the Calendar pops up and
1773 when the user puts the cursor on a date and hits RET, that
1774 date, in the format set by `calendar-date-display-form',
1775 becomes the date in the header.
1776 - If DATE-TYPE is a string matching the regexp
1777 `todo-date-pattern', that string becomes the date in the
1778 header. This case is for the command
1779 `todo-insert-item-from-calendar' which is called from the
1781 - If DATE-TYPE is the symbol `date', the header contains the date
1782 in the format set by `calendar-date-display-form', with year,
1783 month and day individually prompted for (month with tab
1785 - If DATE-TYPE is the symbol `dayname' the header contains a
1786 weekday name instead of a date, prompted for with tab
1788 - If DATE-TYPE has any other value (including nil or none) the
1789 header contains the current date (in the format set by
1790 `calendar-date-display-form').
1792 With non-nil argument TIME prompt for a time string, which must
1793 match `diary-time-regexp'. Typing `<return>' at the prompt
1794 returns the current time, if the user option
1795 `todo-always-add-time-string' is non-nil, otherwise the empty
1796 string (i.e., no time string). If TIME is absent or nil, add or
1797 omit the current time string according as
1798 `todo-always-add-time-string' is non-nil or nil, respectively.
1800 The argument REGION-OR-HERE determines the source and location of
1802 - If the REGION-OR-HERE is the symbol `here', prompt for the text of
1803 the new item and, if the command was invoked with point in the todo
1804 items section of the current category, give the new item the
1805 priority of the item at point, lowering the latter's priority and
1806 the priority of the remaining items. If point is in the done items
1807 section of the category, insert the new item as the first todo item
1808 in the category. Likewise, if the command with `here' is invoked
1809 outside of the current category, jump to the chosen category and
1810 insert the new item as the first item in the category.
1811 - If REGION-OR-HERE is the symbol `region', use the region of the
1812 current buffer as the text of the new item, depending on the
1813 value of user option `todo-use-only-highlighted-region': if
1814 this is non-nil, then use the region only when it is
1815 highlighted; otherwise, use the region regardless of
1816 highlighting. An error is signalled if there is no region in
1817 the current buffer. Prompt for the item's priority in the
1818 category (an integer between 1 and one more than the number of
1819 items in the category), and insert the item accordingly.
1820 - If REGION-OR-HERE has any other value (in particular, nil or
1821 none), prompt for the text and the item's priority, and insert
1822 the item accordingly."
1823 ;; If invoked outside of Todo mode and there is not yet any Todo
1824 ;; file, initialize one.
1825 (if (null (funcall todo-files-function))
1827 (let ((region (eq region-or-here 'region))
1828 (here (eq region-or-here 'here)))
1830 (let (use-empty-active-region)
1831 (unless (and todo-use-only-highlighted-region (use-region-p))
1832 (user-error "There is no active region"))))
1833 (let* ((obuf (current-buffer))
1834 (ocat (todo-current-category))
1836 (todo-mm (eq major-mode 'todo-mode))
1837 (cat+file (cond ((equal arg '(4))
1838 (todo-read-category "Insert in category: "))
1840 (todo-read-category "Insert in category: "
1843 (cons (todo-current-category)
1844 (or todo-current-todo-file
1845 (and todo-show-current-file
1846 todo-global-current-todo-file)
1847 (todo-absolute-file-name
1848 todo-default-todo-file))))))
1849 (cat (car cat+file))
1850 (file (cdr cat+file))
1851 (new-item (if region
1852 (buffer-substring-no-properties
1853 (region-beginning) (region-end))
1854 (read-from-minibuffer "Todo item: ")))
1856 ((eq date-type 'date)
1858 ((eq date-type 'dayname)
1859 (todo-read-dayname))
1860 ((eq date-type 'calendar)
1861 (setq todo-date-from-calendar t)
1862 (or (todo-set-date-from-calendar)
1863 ;; If user exits Calendar before choosing
1864 ;; a date, cancel item insertion.
1866 ((and (stringp date-type)
1867 (string-match todo-date-pattern date-type))
1868 (setq todo-date-from-calendar date-type)
1869 (todo-set-date-from-calendar))
1871 (calendar-date-string
1872 (calendar-current-date) t t))))
1873 (time-string (or (and time (todo-read-time))
1874 (and todo-always-add-time-string
1875 (substring (current-time-string) 11 16)))))
1876 (setq todo-date-from-calendar nil)
1877 (find-file-noselect file 'nowarn)
1878 (set-window-buffer (selected-window)
1879 (set-buffer (find-buffer-visiting file)))
1880 ;; If this command was invoked outside of a Todo mode buffer,
1881 ;; the call to todo-current-category above returned nil. If
1882 ;; we just entered Todo mode now, then cat was set to the
1883 ;; file's first category, but if todo-mode was already
1884 ;; enabled, cat did not get set, so we have to do that.
1886 (setq cat (todo-current-category)))
1887 (setq todo-current-todo-file file)
1888 (unless todo-global-current-todo-file
1889 (setq todo-global-current-todo-file todo-current-todo-file))
1890 (let ((buffer-read-only nil)
1891 (called-from-outside (not (and todo-mm (equal cat ocat))))
1892 done-only item-added)
1894 ;; Add date, time and diary marking as required.
1895 (concat (if (not (and diary (not todo-include-in-diary)))
1897 (when (and nonmarking (not todo-diary-nonmarking))
1898 diary-nonmarking-symbol))
1899 date-string (when (and time-string ; Can be empty.
1902 (concat " " time-string))
1903 (when (not (and diary (not todo-include-in-diary)))
1906 ;; Indent newlines inserted by C-q C-j if nonspace char follows.
1907 (setq new-item (replace-regexp-in-string "\\(\n\\)[^[:blank:]]"
1908 "\n\t" new-item nil nil 1))
1911 ;; Make sure the correct category is selected. There
1912 ;; are two cases: (i) we just visited the file, so no
1913 ;; category is selected yet, or (ii) we invoked
1914 ;; insertion "here" from outside the category we want
1915 ;; to insert in (with priority insertion, category
1916 ;; selection is done by todo-set-item-priority).
1917 (when (or (= (- (point-max) (point-min)) (buffer-size))
1918 (and here called-from-outside))
1919 (todo-category-number cat)
1920 (todo-category-select))
1921 ;; If only done items are displayed in category,
1922 ;; toggle to todo items before inserting new item.
1923 (when (save-excursion
1924 (goto-char (point-min))
1925 (looking-at todo-done-string-start))
1927 (todo-toggle-view-done-only))
1930 ;; If command was invoked with point in done
1931 ;; items section or outside of the current
1932 ;; category, can't insert "here", so to be
1933 ;; useful give new item top priority.
1934 (when (or (todo-done-item-section-p)
1937 (goto-char (point-min)))
1938 (todo-insert-with-overlays new-item))
1939 (todo-set-item-priority new-item cat t))
1940 (setq item-added t))
1941 ;; If user cancels before setting priority, restore
1946 (unless (equal cat ocat)
1947 (todo-category-number ocat)
1948 (todo-category-select))
1949 (and done-only (todo-toggle-view-done-only)))
1950 (set-window-buffer (selected-window) (set-buffer obuf)))
1952 ;; If the todo items section is not visible when the
1953 ;; insertion command is called (either because only done
1954 ;; items were shown or because the category was not in the
1955 ;; current buffer), then if the item is inserted at the
1956 ;; end of the category, point is at eob and eob at
1957 ;; window-start, so that higher priority todo items are
1958 ;; out of view. So we recenter to make sure the todo
1959 ;; items are displayed in the window.
1960 (when item-added (recenter)))
1961 (todo-update-count 'todo 1)
1962 (if (or diary todo-include-in-diary) (todo-update-count 'diary 1))
1963 (todo-update-categories-sexp))))))
1965 (defun todo-set-date-from-calendar ()
1966 "Return string of date chosen from Calendar."
1967 (cond ((and (stringp todo-date-from-calendar)
1968 (string-match todo-date-pattern todo-date-from-calendar))
1969 todo-date-from-calendar)
1970 (todo-date-from-calendar
1971 (let (calendar-view-diary-initially-flag)
1972 (calendar)) ; *Calendar* is now current buffer.
1973 (define-key calendar-mode-map [remap newline] 'exit-recursive-edit)
1974 ;; If user exits Calendar before choosing a date, clean up properly.
1975 (define-key calendar-mode-map
1976 [remap calendar-exit] (lambda ()
1980 (exit-recursive-edit))))
1981 (message "Put cursor on a date and type <return> to set it.")
1984 (when (equal (buffer-name) calendar-buffer)
1985 (setq todo-date-from-calendar
1986 (calendar-date-string (calendar-cursor-to-date t) t t))
1988 todo-date-from-calendar)
1989 (define-key calendar-mode-map [remap newline] nil)
1990 (define-key calendar-mode-map [remap calendar-exit] nil)
1991 (unless (zerop (recursion-depth)) (exit-recursive-edit))
1992 (when (stringp todo-date-from-calendar)
1993 todo-date-from-calendar)))))
1995 (defun todo-insert-item-from-calendar (&optional arg)
1996 "Prompt for and insert a new item with date selected from calendar.
1997 Invoked without prefix argument ARG, insert the item into the
1998 current category, without one prefix argument, prompt for the
1999 category from the current todo file or from one listed in
2000 `todo-category-completions-files'; with two prefix arguments,
2001 prompt for a todo file and then for a category in it."
2003 (setq todo-date-from-calendar
2004 (calendar-date-string (calendar-cursor-to-date t) t t))
2006 (todo-basic-insert-item arg nil nil todo-date-from-calendar))
2008 (define-key calendar-mode-map "it" 'todo-insert-item-from-calendar)
2010 (defun todo-copy-item ()
2011 "Copy item at point and insert the copy as a new item."
2013 (unless (or (todo-done-item-p) (looking-at "^$"))
2014 (let ((copy (todo-item-string))
2015 (diary-item (todo-diary-item-p)))
2016 (todo-set-item-priority copy (todo-current-category) t)
2017 (todo-update-count 'todo 1)
2018 (when diary-item (todo-update-count 'diary 1))
2019 (todo-update-categories-sexp))))
2021 (defun todo-delete-item ()
2022 "Delete at least one item in this category.
2023 If there are marked items, delete all of these; otherwise, delete
2028 (let* ((cat (todo-current-category))
2029 (marked (assoc cat todo-categories-with-marks))
2030 (item (unless marked (todo-item-string)))
2033 "Permanently delete all marked items? ")
2035 (setq ov (make-overlay
2036 (save-excursion (todo-item-start))
2037 (save-excursion (todo-item-end))))
2038 (overlay-put ov 'face 'todo-search)
2039 (todo-y-or-n-p "Permanently delete this item? "))))
2042 (and marked (goto-char (point-min)))
2045 (if (or (and marked (todo-marked-item-p)) item)
2047 (if (todo-done-item-p)
2048 (todo-update-count 'done -1)
2049 (todo-update-count 'todo -1 cat)
2050 (and (todo-diary-item-p)
2051 (todo-update-count 'diary -1)))
2052 (if ov (delete-overlay ov))
2054 ;; Don't leave point below last item.
2055 (and item (bolp) (eolp) (< (point-min) (point-max))
2056 (todo-backward-item))
2058 (throw 'done (setq item nil))))
2059 (todo-forward-item))))
2061 (setq todo-categories-with-marks
2062 (assq-delete-all cat todo-categories-with-marks)))
2063 (todo-update-categories-sexp)
2064 (todo-prefix-overlays)))
2065 (if ov (delete-overlay ov)))))
2067 (defun todo-edit-item (&optional arg)
2068 "Edit the todo item at point.
2069 With non-nil prefix argument ARG, include the item's date/time
2070 header, making it also editable; otherwise, include only the item
2073 If the item consists of only one logical line, edit it in the
2074 minibuffer; otherwise, edit it in Todo Edit mode."
2076 (when (todo-item-string)
2077 (let* ((opoint (point))
2078 (start (todo-item-start))
2081 (concat todo-date-string-start todo-date-pattern
2082 "\\( " diary-time-regexp "\\)?"
2083 (regexp-quote todo-nondiary-end) "?")
2084 (line-end-position) t)
2085 (1+ (- (point) start))))
2086 (header (substring (todo-item-string) 0 item-beg))
2087 (item (if arg (todo-item-string)
2088 (substring (todo-item-string) item-beg)))
2089 (multiline (> (length (split-string item "\n")) 1))
2090 (buffer-read-only nil))
2092 (todo-edit-multiline-item)
2093 (let ((new (concat (if arg "" header)
2094 (read-string "Edit: " (if arg
2095 (cons item item-beg)
2098 (while (not (string-match (concat todo-date-string-start
2099 todo-date-pattern) new))
2100 (setq new (read-from-minibuffer
2101 "Item must start with a date: " new))))
2102 ;; Ensure lines following hard newlines are indented.
2103 (setq new (replace-regexp-in-string "\\(\n\\)[^[:blank:]]"
2104 "\n\t" new nil nil 1))
2105 ;; If user moved point during editing, make sure it moves back.
2108 (todo-insert-with-overlays new)
2109 (move-to-column item-beg))))))
2111 (defun todo-edit-multiline-item ()
2112 "Edit current todo item in Todo Edit mode.
2113 Use of newlines invokes `todo-indent' to insure compliance with
2114 the format of Diary entries."
2116 (when (todo-item-string)
2117 (let ((buf todo-edit-buffer))
2118 (set-window-buffer (selected-window)
2119 (set-buffer (make-indirect-buffer (buffer-name) buf)))
2120 (narrow-to-region (todo-item-start) (todo-item-end))
2122 (message "%s" (substitute-command-keys
2123 (concat "Type \\[todo-edit-quit] "
2124 "to return to Todo mode.\n"))))))
2126 (defun todo-edit-quit ()
2127 "Return from Todo Edit mode to Todo mode.
2128 If the item contains hard line breaks, make sure the following
2129 lines are indented by `todo-indent-to-here' to conform to diary
2132 If the whole file was in Todo Edit mode, check before returning
2133 whether the file is still a valid todo file and if so, also
2134 recalculate the todo file's categories sexp, in case changes were
2135 made in the number or names of categories."
2137 (if (> (buffer-size) (- (point-max) (point-min)))
2138 ;; We got here via `e m'.
2139 (let ((item (buffer-string))
2140 (regex "\\(\n\\)[^[:blank:]]")
2141 (buf (buffer-base-buffer)))
2142 (while (not (string-match (concat todo-date-string-start
2143 todo-date-pattern) item))
2144 (setq item (read-from-minibuffer
2145 "Item must start with a date: " item)))
2146 ;; Ensure lines following hard newlines are indented.
2147 (when (string-match regex (buffer-string))
2148 (setq item (replace-regexp-in-string regex "\n\t" item nil nil 1))
2149 (delete-region (point-min) (point-max))
2152 (unless (eq (current-buffer) buf)
2153 (set-window-buffer (selected-window) (set-buffer buf))))
2154 ;; We got here via `F e'.
2155 (when (todo-check-format)
2156 ;; FIXME: separate out sexp check?
2157 ;; If manual editing makes e.g. item counts change, have to
2158 ;; call this to update todo-categories, but it restores
2159 ;; category order to list order.
2160 ;; (todo-repair-categories-sexp)
2161 ;; Compare (todo-make-categories-list t) with sexp and if
2162 ;; different ask (todo-update-categories-sexp) ?
2164 (let* ((cat-beg (concat "^" (regexp-quote todo-category-beg)
2166 (curline (buffer-substring-no-properties
2167 (line-beginning-position) (line-end-position)))
2168 (cat (cond ((string-match cat-beg curline)
2169 (match-string-no-properties 1 curline))
2170 ((or (re-search-backward cat-beg nil t)
2171 (re-search-forward cat-beg nil t))
2172 (match-string-no-properties 1)))))
2173 (todo-category-number cat)
2174 (todo-category-select)
2175 (goto-char (point-min))))))
2177 (defun todo-basic-edit-item-header (what &optional inc)
2178 "Function underlying commands to edit item date/time header.
2180 The argument WHAT (passed by invoking commands) specifies what
2181 part of the header to edit; possible values are these symbols:
2182 `date', to edit the year, month, and day of the date string;
2183 `time', to edit just the time string; `calendar', to select the
2184 date from the Calendar; `today', to set the date to today's date;
2185 `dayname', to set the date string to the name of a day or to
2186 change the day name; and `year', `month' or `day', to edit only
2187 these respective parts of the date string (`day' is the number of
2188 the given day of the month, and `month' is either the name of the
2189 given month or its number, depending on the value of
2190 `calendar-date-display-form').
2192 The optional argument INC is a positive or negative integer
2193 \(passed by invoking commands as a numerical prefix argument)
2194 that in conjunction with the WHAT values `year', `month' or
2195 `day', increments or decrements the specified date string
2196 component by the specified number of suitable units, i.e., years,
2197 months, or days, with automatic adjustment of the other date
2198 string components as necessary.
2200 If there are marked items, apply the same edit to all of these;
2201 otherwise, edit just the item at point."
2202 (let* ((cat (todo-current-category))
2203 (marked (assoc cat todo-categories-with-marks))
2205 (todo-date-from-calendar t)
2206 (buffer-read-only nil)
2207 ndate ntime year monthname month day
2208 dayname) ; Needed by calendar-date-display-form.
2210 (or (and marked (goto-char (point-min))) (todo-item-start))
2214 (while (not (todo-marked-item-p))
2216 (and (eobp) (throw 'end nil))))
2217 (re-search-forward (concat todo-date-string-start "\\(?1:"
2219 "\\)\\(?2: " diary-time-regexp "\\)?"
2220 (regexp-quote todo-nondiary-end) "?")
2221 (line-end-position) t)
2222 (let* ((odate (match-string-no-properties 1))
2223 (otime (match-string-no-properties 2))
2224 (odayname (match-string-no-properties 5))
2225 (omonthname (match-string-no-properties 6))
2226 (omonth (match-string-no-properties 7))
2227 (oday (match-string-no-properties 8))
2228 (oyear (match-string-no-properties 9))
2229 (tmn-array todo-month-name-array)
2230 (mlist (append tmn-array nil))
2231 (tma-array todo-month-abbrev-array)
2232 (mablist (append tma-array nil))
2233 (yy (and oyear (unless (string= oyear "*")
2234 (string-to-number oyear))))
2235 (mm (or (and omonth (unless (string= omonth "*")
2236 (string-to-number omonth)))
2237 (1+ (- (length mlist)
2238 (length (or (member omonthname mlist)
2239 (member omonthname mablist)))))))
2240 (dd (and oday (unless (string= oday "*")
2241 (string-to-number oday)))))
2242 ;; If there are marked items, use only the first to set
2243 ;; header changes, and apply these to all marked items.
2247 (setq ndate (todo-read-date)))
2248 ((eq what 'calendar)
2249 (setq ndate (save-match-data (todo-set-date-from-calendar))))
2251 (setq ndate (calendar-date-string (calendar-current-date) t t)))
2253 (setq ndate (todo-read-dayname)))
2255 (setq ntime (save-match-data (todo-read-time)))
2256 (when (> (length ntime) 0)
2257 (setq ntime (concat " " ntime))))
2258 ;; When date string consists only of a day name,
2259 ;; passing other date components is a noop.
2260 ((and odayname (memq what '(year month day))))
2263 monthname omonthname
2265 year (cond ((not current-prefix-arg)
2266 (todo-read-date 'year))
2267 ((string= oyear "*")
2268 (user-error "Cannot increment *"))
2270 (number-to-string (+ yy inc))))))
2274 (if (memq 'month calendar-date-display-form)
2277 (cond ((not current-prefix-arg)
2278 (todo-read-date 'month))
2279 ((or (string= omonth "*") (= mm 13))
2280 (user-error "Cannot increment *"))
2282 (let ((mminc (+ mm inc)))
2283 ;; Increment or decrement month by INC
2285 (setq mm (% mminc 12))
2286 ;; If result is 0, make month December.
2287 (setq mm (if (= mm 0) 12 (abs mm)))
2288 ;; Adjust year if necessary.
2289 (setq year (or (and (cond ((> mminc 12)
2290 (+ yy (/ mminc 12)))
2292 (- yy (/ mminc 12) 1))
2294 (number-to-string yy))
2296 ;; Return the changed numerical month as
2297 ;; a string or the corresponding month name.
2299 (number-to-string mm)
2300 (aref tma-array (1- mm))))))
2301 (let ((yy (string-to-number year)) ; 0 if year is "*".
2302 ;; When mm is 13 (corresponding to "*" as value
2303 ;; of month), this raises an args-out-of-range
2304 ;; error in calendar-last-day-of-month, so use 1
2305 ;; (corresponding to January) to get 31 days.
2306 (mm (if (= mm 13) 1 mm)))
2307 (if (> (string-to-number day)
2308 (calendar-last-day-of-month mm yy))
2309 (user-error "%s %s does not have %s days"
2310 (aref tmn-array (1- mm))
2311 (if (= mm 2) yy "") day))))
2315 monthname omonthname
2317 ((not current-prefix-arg)
2318 (todo-read-date 'day mm oyear))
2320 (user-error "Cannot increment *"))
2321 ((or (string= omonth "*") (string= omonthname "*"))
2322 (setq dd (+ dd inc))
2324 (user-error "A month cannot have more than 31 days")
2325 (number-to-string dd)))
2326 ;; Increment or decrement day by INC,
2327 ;; adjusting month and year if necessary
2328 ;; (if year is "*" assume current year to
2329 ;; calculate adjustment).
2331 (let* ((yy (or yy (calendar-extract-year
2332 (calendar-current-date))))
2333 (date (calendar-gregorian-from-absolute
2334 (+ (calendar-absolute-from-gregorian
2335 (list mm dd yy)) inc)))
2336 (adjmm (nth 0 date)))
2337 ;; Set year and month(name) to adjusted values.
2338 (unless (string= year "*")
2339 (setq year (number-to-string (nth 2 date))))
2341 (setq month (number-to-string adjmm))
2342 (setq monthname (aref tma-array (1- adjmm))))
2343 ;; Return changed numerical day as a string.
2344 (number-to-string (nth 1 date)))))))))
2346 ;; If year, month or day date string components were
2347 ;; changed, rebuild the date string.
2348 (when (memq what '(year month day))
2349 (setq ndate (mapconcat 'eval calendar-date-display-form ""))))
2350 (when ndate (replace-match ndate nil nil nil 1))
2351 ;; Add new time string to the header, if it was supplied.
2354 (replace-match ntime nil nil nil 2)
2355 (goto-char (match-end 1))
2357 (setq todo-date-from-calendar nil)
2359 ;; Apply the changes to the first marked item header to the
2360 ;; remaining marked items. If there are no marked items,
2364 (goto-char (point-max))))))))
2366 (defun todo-edit-item-header ()
2367 "Interactively edit at least the date of item's date/time header.
2368 If user option `todo-always-add-time-string' is non-nil, also
2369 edit item's time string."
2371 (todo-basic-edit-item-header 'date)
2372 (when todo-always-add-time-string
2373 (todo-edit-item-time)))
2375 (defun todo-edit-item-time ()
2376 "Interactively edit the time string of item's date/time header."
2378 (todo-basic-edit-item-header 'time))
2380 (defun todo-edit-item-date-from-calendar ()
2381 "Interactively edit item's date using the Calendar."
2383 (todo-basic-edit-item-header 'calendar))
2385 (defun todo-edit-item-date-to-today ()
2386 "Set item's date to today's date."
2388 (todo-basic-edit-item-header 'today))
2390 (defun todo-edit-item-date-day-name ()
2391 "Replace item's date with the name of a day of the week."
2393 (todo-basic-edit-item-header 'dayname))
2395 (defun todo-edit-item-date-year (&optional inc)
2396 "Interactively edit the year of item's date string.
2397 With prefix argument INC a positive or negative integer,
2398 increment or decrement the year by INC."
2400 (todo-basic-edit-item-header 'year inc))
2402 (defun todo-edit-item-date-month (&optional inc)
2403 "Interactively edit the month of item's date string.
2404 With prefix argument INC a positive or negative integer,
2405 increment or decrement the month by INC."
2407 (todo-basic-edit-item-header 'month inc))
2409 (defun todo-edit-item-date-day (&optional inc)
2410 "Interactively edit the day of the month of item's date string.
2411 With prefix argument INC a positive or negative integer,
2412 increment or decrement the day by INC."
2414 (todo-basic-edit-item-header 'day inc))
2416 (defun todo-edit-item-diary-inclusion ()
2417 "Change diary status of one or more todo items in this category.
2418 That is, insert `todo-nondiary-marker' if the candidate items
2419 lack this marking; otherwise, remove it.
2421 If there are marked todo items, change the diary status of all
2422 and only these, otherwise change the diary status of the item at
2425 (let ((buffer-read-only)
2426 (marked (assoc (todo-current-category)
2427 todo-categories-with-marks)))
2430 (when marked (goto-char (point-min)))
2432 (if (todo-done-item-p)
2433 (throw 'stop (message "Done items cannot be edited"))
2434 (unless (and marked (not (todo-marked-item-p)))
2435 (let* ((beg (todo-item-start))
2436 (lim (save-excursion (todo-item-end)))
2437 (end (save-excursion
2438 (or (todo-time-string-matcher lim)
2439 (todo-date-string-matcher lim)))))
2440 (if (looking-at (regexp-quote todo-nondiary-start))
2443 (search-forward todo-nondiary-end (1+ end) t)
2445 (todo-update-count 'diary 1))
2447 (insert todo-nondiary-start)
2448 (goto-char (1+ end))
2449 (insert todo-nondiary-end)
2450 (todo-update-count 'diary -1)))))
2451 (unless marked (throw 'stop nil))
2452 (todo-forward-item)))))
2453 (todo-update-categories-sexp)))
2455 (defun todo-edit-category-diary-inclusion (arg)
2456 "Make all items in this category diary items.
2457 With prefix ARG, make all items in this category non-diary
2461 (goto-char (point-min))
2462 (let ((todo-count (todo-get-count 'todo))
2463 (diary-count (todo-get-count 'diary))
2467 (if (todo-done-item-p) ; We've gone too far.
2469 (let* ((beg (todo-item-start))
2470 (lim (save-excursion (todo-item-end)))
2471 (end (save-excursion
2472 (or (todo-time-string-matcher lim)
2473 (todo-date-string-matcher lim)))))
2475 (unless (looking-at (regexp-quote todo-nondiary-start))
2476 (insert todo-nondiary-start)
2477 (goto-char (1+ end))
2478 (insert todo-nondiary-end))
2479 (when (looking-at (regexp-quote todo-nondiary-start))
2481 (search-forward todo-nondiary-end (1+ end) t)
2482 (replace-match "")))))
2483 (todo-forward-item))
2484 (unless (if arg (zerop diary-count) (= diary-count todo-count))
2485 (todo-update-count 'diary (if arg
2487 (- todo-count diary-count))))
2488 (todo-update-categories-sexp)))))
2490 (defun todo-edit-item-diary-nonmarking ()
2491 "Change non-marking of one or more diary items in this category.
2492 That is, insert `diary-nonmarking-symbol' if the candidate items
2493 lack this marking; otherwise, remove it.
2495 If there are marked todo items, change the non-marking status of
2496 all and only these, otherwise change the non-marking status of
2499 (let ((buffer-read-only)
2500 (marked (assoc (todo-current-category)
2501 todo-categories-with-marks)))
2504 (when marked (goto-char (point-min)))
2506 (if (todo-done-item-p)
2507 (throw 'stop (message "Done items cannot be edited"))
2508 (unless (and marked (not (todo-marked-item-p)))
2510 (unless (looking-at (regexp-quote todo-nondiary-start))
2511 (if (looking-at (regexp-quote diary-nonmarking-symbol))
2513 (insert diary-nonmarking-symbol))))
2514 (unless marked (throw 'stop nil))
2515 (todo-forward-item)))))))
2517 (defun todo-edit-category-diary-nonmarking (arg)
2518 "Add `diary-nonmarking-symbol' to all diary items in this category.
2519 With prefix ARG, remove `diary-nonmarking-symbol' from all diary
2520 items in this category."
2523 (goto-char (point-min))
2524 (let (buffer-read-only)
2527 (if (todo-done-item-p) ; We've gone too far.
2529 (unless (looking-at (regexp-quote todo-nondiary-start))
2531 (when (looking-at (regexp-quote diary-nonmarking-symbol))
2533 (unless (looking-at (regexp-quote diary-nonmarking-symbol))
2534 (insert diary-nonmarking-symbol))))
2535 (todo-forward-item)))))))
2537 (defun todo-set-item-priority (&optional item cat new arg)
2538 "Prompt for and set ITEM's priority in CATegory.
2540 Interactively, ITEM is the todo item at point, CAT is the current
2541 category, and the priority is a number between 1 and the number
2542 of items in the category. Non-interactively, non-nil NEW means
2543 ITEM is a new item and the lowest priority is one more than the
2544 number of items in CAT.
2546 The new priority is set either interactively by prompt or by a
2547 numerical prefix argument, or noninteractively by argument ARG,
2548 whose value can be either of the symbols `raise' or `lower',
2549 meaning to raise or lower the item's priority by one."
2551 (unless (and (called-interactively-p 'any)
2552 (or (todo-done-item-p) (looking-at "^$")))
2553 (let* ((item (or item (todo-item-string)))
2554 (marked (todo-marked-item-p))
2555 (cat (or cat (cond ((eq major-mode 'todo-mode)
2556 (todo-current-category))
2557 ((eq major-mode 'todo-filtered-items-mode)
2559 (concat todo-date-string-start
2561 "\\( " diary-time-regexp "\\)?"
2562 (regexp-quote todo-nondiary-end)
2563 "?\\(?1: \\[\\(.+:\\)?.+\\]\\)")))
2565 (re-search-forward regexp1 nil t)
2566 (match-string-no-properties 1)))))))
2568 (todo (cond ((or (eq arg 'raise) (eq arg 'lower)
2569 (eq major-mode 'todo-filtered-items-mode))
2571 (let ((curstart (todo-item-start))
2573 (goto-char (point-min))
2574 (while (looking-at todo-item-start)
2575 (setq count (1+ count))
2576 (when (= (point) curstart) (setq curnum count))
2577 (todo-forward-item))
2579 ((eq major-mode 'todo-mode)
2580 (todo-get-count 'todo cat))))
2581 (maxnum (if new (1+ todo) todo))
2582 (prompt (format "Set item priority (1-%d): " maxnum))
2583 (priority (cond ((and (not arg) (numberp current-prefix-arg))
2585 ((and (eq arg 'raise) (>= curnum 1))
2587 ((and (eq arg 'lower) (<= curnum maxnum))
2591 (unless (and priority
2592 (or (and (eq arg 'raise) (zerop priority))
2593 (and (eq arg 'lower) (> priority maxnum))))
2594 ;; When moving item to another category, show the category before
2595 ;; prompting for its priority.
2596 (unless (or arg (called-interactively-p 'any))
2597 (todo-category-number cat)
2598 ;; If done items in category are visible, keep them visible.
2599 (let ((done todo-show-with-done))
2600 (when (> (buffer-size) (- (point-max) (point-min)))
2602 (goto-char (point-min))
2603 (setq done (re-search-forward todo-done-string-start nil t))))
2604 (let ((todo-show-with-done done))
2605 (todo-category-select)
2606 ;; Keep top of category in view while setting priority.
2607 (goto-char (point-min)))))
2608 ;; Prompt for priority only when the category has at least one
2611 (while (not priority)
2612 (setq candidate (read-number prompt))
2613 (setq prompt (when (or (< candidate 1) (> candidate maxnum))
2614 (format "Priority must be an integer between 1 and %d.\n"
2616 (unless prompt (setq priority candidate))))
2617 ;; In Top Priorities buffer, an item's priority can be changed
2618 ;; wrt items in another category, but not wrt items in the same
2620 (when (eq major-mode 'todo-filtered-items-mode)
2621 (let* ((regexp2 (concat todo-date-string-start todo-date-pattern
2622 "\\( " diary-time-regexp "\\)?"
2623 (regexp-quote todo-nondiary-end)
2624 "?\\(?1:" (regexp-quote cat) "\\)"))
2625 (end (cond ((< curnum priority)
2626 (save-excursion (todo-item-end)))
2627 ((> curnum priority)
2628 (save-excursion (todo-item-start)))))
2629 (match (save-excursion
2630 (cond ((< curnum priority)
2631 (todo-forward-item (1+ (- priority curnum)))
2632 (when (re-search-backward regexp2 end t)
2633 (match-string-no-properties 1)))
2634 ((> curnum priority)
2635 (todo-backward-item (- curnum priority))
2636 (when (re-search-forward regexp2 end t)
2637 (match-string-no-properties 1)))))))
2639 (user-error (concat "Cannot reprioritize items from the same "
2640 "category in this mode, only in Todo mode")))))
2641 ;; Interactively or with non-nil ARG, relocate the item within its
2643 (when (or arg (called-interactively-p 'any))
2645 (goto-char (point-min))
2647 (unless (= priority 1)
2648 (todo-forward-item (1- priority))
2649 ;; When called from todo-item-undone and the highest priority
2650 ;; is chosen, this advances point to the first done item, so
2651 ;; move it up to the empty line above the done items
2653 (when (looking-back (concat "^"
2654 (regexp-quote todo-category-done)
2656 (todo-backward-item))))
2657 (todo-insert-with-overlays item)
2658 ;; If item was marked, restore the mark.
2660 (let* ((ov (todo-get-overlay 'prefix))
2661 (pref (overlay-get ov 'before-string)))
2662 (overlay-put ov 'before-string
2663 (concat todo-item-mark pref))))))))
2665 (defun todo-raise-item-priority ()
2666 "Raise priority of current item by moving it up by one item."
2668 (todo-set-item-priority nil nil nil 'raise))
2670 (defun todo-lower-item-priority ()
2671 "Lower priority of current item by moving it down by one item."
2673 (todo-set-item-priority nil nil nil 'lower))
2675 (defun todo-move-item (&optional file)
2676 "Move at least one todo or done item to another category.
2677 If there are marked items, move all of these; otherwise, move
2680 With prefix argument FILE, prompt for a specific todo file and
2681 choose (with TAB completion) a category in it to move the item or
2682 items to; otherwise, choose and move to any category in either
2683 the current todo file or one of the files in
2684 `todo-category-completions-files'. If the chosen category is
2685 not an existing categories, then it is created and the item(s)
2686 become(s) the first entry/entries in that category.
2688 With moved todo items, prompt to set the priority in the category
2689 moved to (with multiple todo items, the one that had the highest
2690 priority in the category moved from gets the new priority and the
2691 rest of the moved todo items are inserted in sequence below it).
2692 Moved done items are appended to the top of the done items
2693 section in the category moved to."
2695 (let* ((cat1 (todo-current-category))
2696 (marked (assoc cat1 todo-categories-with-marks)))
2697 ;; Noop if point is not on an item and there are no marked items.
2698 (unless (and (looking-at "^$")
2700 (let* ((buffer-read-only)
2701 (file1 todo-current-todo-file)
2702 (num todo-category-number)
2703 (item (todo-item-string))
2704 (diary-item (todo-diary-item-p))
2705 (done-item (and (todo-done-item-p) (concat item "\n")))
2706 (omark (save-excursion (todo-item-start) (point-marker)))
2710 ov cat2 file2 moved nmark todo-items done-items)
2714 (setq ov (make-overlay (save-excursion (todo-item-start))
2715 (save-excursion (todo-item-end))))
2716 (overlay-put ov 'face 'todo-search))
2717 (let* ((pl (if (and marked (> (cdr marked) 1)) "s" ""))
2718 (cat+file (todo-read-category (concat "Move item" pl
2721 (while (and (equal (car cat+file) cat1)
2722 (equal (cdr cat+file) file1))
2723 (setq cat+file (todo-read-category
2724 "Choose a different category: ")))
2725 (setq cat2 (car cat+file)
2726 file2 (cdr cat+file))))
2727 (if ov (delete-overlay ov)))
2728 (set-buffer (find-buffer-visiting file1))
2731 (goto-char (point-min))
2733 (when (todo-marked-item-p)
2734 (if (todo-done-item-p)
2735 (setq done-items (concat done-items
2736 (todo-item-string) "\n")
2738 (setq todo-items (concat todo-items
2739 (todo-item-string) "\n")
2741 (when (todo-diary-item-p)
2742 (setq diary (1+ diary)))))
2743 (todo-forward-item))
2744 ;; Chop off last newline of multiple todo item string,
2745 ;; since it will be reinserted when setting priority
2746 ;; (but with done items priority is not set, so keep
2749 (setq todo-items (substring todo-items 0 -1))))
2750 (if (todo-done-item-p)
2753 (when (todo-diary-item-p) (setq diary 1))))
2754 (set-window-buffer (selected-window)
2755 (set-buffer (find-file-noselect file2 'nowarn)))
2758 (when (or todo-items (and item (not done-item)))
2759 (todo-set-item-priority (or todo-items item) cat2 t))
2760 ;; Move done items en bloc to top of done items section.
2761 (when (or done-items done-item)
2762 (todo-category-number cat2)
2764 (goto-char (point-min))
2766 (concat "^" (regexp-quote (concat todo-category-beg cat2))
2769 (concat "^" (regexp-quote todo-category-done)) nil t)
2771 (insert (or done-items done-item)))
2774 ;; Move succeeded, so remove item from starting category,
2775 ;; update item counts and display the category containing
2778 (setq nmark (point-marker))
2779 (when todo (todo-update-count 'todo todo))
2780 (when diary (todo-update-count 'diary diary))
2781 (when done (todo-update-count 'done done))
2782 (todo-update-categories-sexp)
2783 (with-current-buffer (find-buffer-visiting file1)
2792 (concat "^" (regexp-quote todo-category-beg)) nil t)
2795 (setq end (if (re-search-forward
2796 (concat "^" (regexp-quote
2797 todo-category-beg)) nil t)
2801 (while (< (point) end)
2802 (if (todo-marked-item-p)
2804 (todo-forward-item)))
2805 (setq todo-categories-with-marks
2806 (assq-delete-all cat1 todo-categories-with-marks)))
2807 (if ov (delete-overlay ov))
2808 (todo-remove-item))))
2809 (when todo (todo-update-count 'todo (- todo) cat1))
2810 (when diary (todo-update-count 'diary (- diary) cat1))
2811 (when done (todo-update-count 'done (- done) cat1))
2812 (todo-update-categories-sexp))
2813 (set-window-buffer (selected-window)
2814 (set-buffer (find-file-noselect file2 'nowarn)))
2815 (setq todo-category-number (todo-category-number cat2))
2816 (let ((todo-show-with-done (or done-items done-item)))
2817 (todo-category-select))
2819 ;; If item is moved to end of (just first?) category, make
2820 ;; sure the items above it are displayed in the window.
2822 ;; User quit before setting priority of todo item(s), so
2823 ;; return to starting category.
2825 (set-window-buffer (selected-window)
2826 (set-buffer (find-file-noselect file1 'nowarn)))
2827 (todo-category-number cat1)
2828 (todo-category-select)
2829 (goto-char omark))))))))
2831 (defun todo-item-done (&optional arg)
2832 "Tag a todo item in this category as done and relocate it.
2834 With prefix argument ARG prompt for a comment and append it to
2835 the done item; this is only possible if there are no marked
2836 items. If there are marked items, tag all of these with
2837 `todo-done-string' plus the current date and, if
2838 `todo-always-add-time-string' is non-nil, the current time;
2839 otherwise, just tag the item at point. Items tagged as done are
2840 relocated to the category's (by default hidden) done section. If
2841 done items are visible on invoking this command, they remain
2844 (let* ((cat (todo-current-category))
2845 (marked (assoc cat todo-categories-with-marks)))
2849 (goto-char (point-max))
2850 (todo-backward-item)
2851 (unless (todo-done-item-p)
2853 (unless (re-search-forward
2854 (concat "^" (regexp-quote todo-category-beg)) nil t)
2855 (goto-char (point-max)))
2857 (while (todo-done-item-p)
2858 (when (todo-marked-item-p)
2859 (user-error "This command does not apply to done items"))
2860 (todo-backward-item)))))
2861 (unless (and (not marked)
2862 (or (todo-done-item-p)
2863 ;; Point is between todo and done items.
2865 (let* ((date-string (calendar-date-string (calendar-current-date) t t))
2866 (time-string (if todo-always-add-time-string
2867 (concat " " (substring (current-time-string)
2870 (done-prefix (concat "[" todo-done-string date-string time-string
2872 (comment (and arg (read-string "Enter a comment: ")))
2875 (show-done (save-excursion
2876 (goto-char (point-min))
2877 (re-search-forward todo-done-string-start nil t)))
2878 (buffer-read-only nil)
2879 item done-item opoint)
2880 ;; Don't add empty comment to done item.
2881 (setq comment (unless (zerop (length comment))
2882 (concat " [" todo-comment-string ": " comment "]")))
2883 (and marked (goto-char (point-min)))
2885 ;; Stop looping when we hit the empty line below the last
2886 ;; todo item (this is eobp if only done items are hidden).
2887 (while (not (looking-at "^$"))
2888 (if (or (not marked) (and marked (todo-marked-item-p)))
2890 (setq item (todo-item-string))
2891 (setq done-item (concat done-item done-prefix item
2892 comment (and marked "\n")))
2893 (setq item-count (1+ item-count))
2894 (when (todo-diary-item-p)
2895 (setq diary-count (1+ diary-count)))
2897 (unless marked (throw 'done nil)))
2898 (todo-forward-item))))
2900 ;; Chop off last newline of done item string.
2901 (setq done-item (substring done-item 0 -1))
2902 (setq todo-categories-with-marks
2903 (assq-delete-all cat todo-categories-with-marks)))
2907 (concat "^" (regexp-quote todo-category-done)) nil t)
2909 (when show-done (setq opoint (point)))
2910 (insert done-item "\n"))
2911 (todo-update-count 'todo (- item-count))
2912 (todo-update-count 'done item-count)
2913 (todo-update-count 'diary (- diary-count))
2914 (todo-update-categories-sexp)
2915 (let ((todo-show-with-done show-done))
2916 (todo-category-select)
2917 ;; When done items are shown, put cursor on first just done item.
2918 (when opoint (goto-char opoint)))))))
2920 (defun todo-edit-done-item-comment (&optional arg)
2921 "Add a comment to this done item or edit an existing comment.
2922 With prefix ARG delete an existing comment."
2924 (when (todo-done-item-p)
2925 (let ((item (todo-item-string))
2927 (end (save-excursion (todo-item-end)))
2928 comment buffer-read-only)
2931 (if (re-search-forward (concat " \\["
2932 (regexp-quote todo-comment-string)
2933 ": \\([^]]+\\)\\]") end t)
2935 (when (todo-y-or-n-p "Delete comment? ")
2936 (delete-region (match-beginning 0) (match-end 0)))
2937 (setq comment (read-string "Edit comment: "
2938 (cons (match-string 1) 1)))
2939 (replace-match comment nil nil nil 1))
2940 (setq comment (read-string "Enter a comment: "))
2941 ;; If user moved point during editing, make sure it moves back.
2944 (insert " [" todo-comment-string ": " comment "]"))))))
2946 (defun todo-item-undone ()
2947 "Restore at least one done item to this category's todo section.
2948 Prompt for the new priority. If there are marked items, undo all
2949 of these, giving the first undone item the new priority and the
2950 rest following directly in sequence; otherwise, undo just the
2953 If the done item has a comment, ask whether to omit the comment
2954 from the restored item. With multiple marked done items with
2955 comments, only ask once, and if affirmed, omit subsequent
2956 comments without asking."
2958 (let* ((cat (todo-current-category))
2959 (marked (assoc cat todo-categories-with-marks))
2960 (pl (if (and marked (> (cdr marked) 1)) "s" "")))
2961 (when (or marked (todo-done-item-p))
2962 (let ((buffer-read-only)
2964 (omark (point-marker))
2968 start end item ov npoint undone)
2969 (and marked (goto-char (point-min)))
2972 (when (or (not marked) (and marked (todo-marked-item-p)))
2973 (if (not (todo-done-item-p))
2974 (user-error "Only done items can be undone")
2977 (setq ov (make-overlay (save-excursion (todo-item-start))
2978 (save-excursion (todo-item-end))))
2979 (overlay-put ov 'face 'todo-search))
2980 ;; Find the end of the date string added upon tagging item as
2982 (setq start (search-forward "] "))
2983 (setq item-count (1+ item-count))
2984 (unless (looking-at (regexp-quote todo-nondiary-start))
2985 (setq diary-count (1+ diary-count)))
2986 (setq end (save-excursion (todo-item-end)))
2987 ;; Ask (once) whether to omit done item's comment. If
2988 ;; affirmed, omit subsequent comments without asking.
2989 (when (re-search-forward
2990 (concat " \\[" (regexp-quote todo-comment-string)
2991 ": [^]]+\\]") end t)
2993 (if (eq first 'first)
2995 (if (eq todo-undo-item-omit-comment 'ask)
2996 (when (todo-y-or-n-p
2997 (concat "Omit comment" pl
2998 " from restored item"
3001 (when todo-undo-item-omit-comment 'omit)))
3003 (when (and (eq first 'first) ov) (delete-overlay ov)))
3004 (when (eq first 'omit)
3005 (setq end (match-beginning 0))))
3006 (setq item (concat item
3007 (buffer-substring-no-properties start end)
3008 (when marked "\n")))
3009 (unless marked (throw 'done nil))))
3010 (todo-forward-item)))
3013 ;; Chop off last newline of multiple items string, since
3014 ;; it will be reinserted on setting priority.
3015 (and marked (setq item (substring item 0 -1)))
3016 (todo-set-item-priority item cat t)
3017 (setq npoint (point))
3019 (when ov (delete-overlay ov))
3026 (concat "^" (regexp-quote todo-category-done)) nil t)
3028 (if (todo-marked-item-p)
3030 (todo-forward-item)))
3031 (setq todo-categories-with-marks
3032 (assq-delete-all cat todo-categories-with-marks)))
3035 (todo-update-count 'todo item-count)
3036 (todo-update-count 'done (- item-count))
3037 (when diary-count (todo-update-count 'diary diary-count))
3038 (todo-update-categories-sexp)
3039 (let ((todo-show-with-done (> (todo-get-count 'done) 0)))
3040 (todo-category-select))
3041 ;; Put cursor on undone item.
3042 (goto-char npoint)))
3043 (set-marker omark nil)))))
3045 ;; -----------------------------------------------------------------------------
3046 ;;; Done item archives
3047 ;; -----------------------------------------------------------------------------
3049 (defun todo-find-archive (&optional ask)
3050 "Visit the archive of the current todo category, if it exists.
3051 If the category has no archived items, prompt to visit the
3052 archive anyway. If there is no archive for this file or with
3053 non-nil argument ASK, prompt to visit another archive.
3055 The buffer showing the archive is in Todo Archive mode. The
3056 first visit in a session displays the first category in the
3057 archive, subsequent visits return to the last category
3060 (if (null (funcall todo-files-function t))
3061 (message "There are no archive files")
3062 (let* ((cat (todo-current-category))
3063 (count (todo-get-count 'archived cat))
3064 (archive (concat (file-name-sans-extension todo-current-todo-file)
3066 (place (cond (ask 'other-archive)
3067 ((file-exists-p archive) 'this-archive)
3068 (t (when (todo-y-or-n-p
3069 (concat "This file has no archive; "
3070 "visit another archive? "))
3072 (when (eq place 'other-archive)
3073 (setq archive (todo-read-file-name "Choose a todo archive: " t t)))
3074 (when (and (eq place 'this-archive) (zerop count))
3075 (setq place (when (todo-y-or-n-p
3076 (concat "This category has no archived items;"
3077 " visit archive anyway? "))
3080 (set-window-buffer (selected-window)
3081 (set-buffer (find-file-noselect archive)))
3082 (if (member place '(other-archive other-cat))
3083 (setq todo-category-number 1)
3084 (todo-category-number cat))
3085 (todo-category-select)))))
3087 (defun todo-choose-archive ()
3088 "Choose an archive and visit it."
3090 (todo-find-archive t))
3092 (defun todo-archive-done-item (&optional all)
3093 "Archive at least one done item in this category.
3095 With prefix argument ALL, prompt whether to archive all done
3096 items in this category and on confirmation archive them.
3097 Otherwise, if there are marked done items (and no marked todo
3098 items), archive all of these; otherwise, archive the done item at
3101 If the archive of this file does not exist, it is created. If
3102 this category does not exist in the archive, it is created."
3104 (when (eq major-mode 'todo-mode)
3105 (if (and all (zerop (todo-get-count 'done)))
3106 (message "No done items in this category")
3108 (let* ((cat (todo-current-category))
3109 (tbuf (current-buffer))
3110 (marked (assoc cat todo-categories-with-marks))
3111 (afile (concat (file-name-sans-extension
3112 todo-current-todo-file) ".toda"))
3113 (archive (find-file-noselect afile t))
3114 (item (and (todo-done-item-p)
3115 (concat (todo-item-string) "\n")))
3117 (opoint (unless (todo-done-item-p) (point)))
3118 marked-items beg end all-done
3122 (if (todo-y-or-n-p "Archive all done items in this category? ")
3125 (goto-char (point-min))
3128 (re-search-forward todo-done-string-start
3130 (match-beginning 0))
3131 end (if (re-search-forward
3133 (regexp-quote todo-category-beg))
3137 all-done (buffer-substring-no-properties beg end)
3138 count (todo-get-count 'done))
3139 ;; Restore starting point, unless it was on a done
3140 ;; item, since they will all be deleted.
3141 (when opoint (goto-char opoint))))
3145 (goto-char (point-min))
3147 (when (todo-marked-item-p)
3148 (if (not (todo-done-item-p))
3149 (throw 'end (message "Only done items can be archived"))
3151 (concat marked-items (todo-item-string) "\n"))
3152 (setq count (1+ count))))
3153 (todo-forward-item)))))
3154 (if (not (or marked all item))
3155 (throw 'end (message "Only done items can be archived"))
3156 (with-current-buffer archive
3157 (let (buffer-read-only)
3159 (goto-char (point-min))
3160 (if (and (re-search-forward
3161 (concat "^" (regexp-quote
3162 (concat todo-category-beg cat)) "$")
3164 (re-search-forward (regexp-quote todo-category-done)
3166 ;; Start of done items section in existing category.
3168 (todo-add-category nil cat)
3169 ;; Start of done items section in new category.
3170 (goto-char (point-max)))
3171 (insert (cond (marked marked-items)
3174 (todo-update-count 'done (if (or marked all) count 1) cat)
3175 (todo-update-categories-sexp)
3176 ;; If archive is new, save to file now (with
3177 ;; write-region to avoid prompt for file to save to)
3178 ;; to update todo-archives, and to let auto-mode-alist
3179 ;; take effect below on visiting the archive.
3180 (unless (nth 7 (file-attributes afile))
3181 (write-region nil nil afile t t)
3182 (setq todo-archives (funcall todo-files-function t))
3184 (with-current-buffer tbuf
3189 ;; Make sure done items are accessible.
3191 (remove-overlays beg end)
3192 (delete-region beg end)
3193 (todo-update-count 'done (- count))
3194 (todo-update-count 'archived count))))
3196 ;; If we're archiving all done items, can't
3197 ;; first archive item point was on, since
3198 ;; that will short-circuit the rest.
3199 (and item (not all)))
3200 (and marked (goto-char (point-min)))
3203 (if (or (and marked (todo-marked-item-p)) item)
3206 (todo-update-count 'done -1)
3207 (todo-update-count 'archived 1)
3208 ;; Don't leave point below last item.
3209 (and item (bolp) (eolp) (< (point-min) (point-max))
3210 (todo-backward-item))
3212 (throw 'done (setq item nil))))
3213 (todo-forward-item))))))
3215 (setq todo-categories-with-marks
3216 (assq-delete-all cat todo-categories-with-marks)))
3217 (todo-update-categories-sexp)
3218 (todo-prefix-overlays)))
3220 (todo-category-number cat)
3221 (todo-category-select)
3222 (split-window-below)
3223 (set-window-buffer (selected-window) tbuf)
3224 ;; Make todo file current to select category.
3225 (find-file (buffer-file-name tbuf))
3226 ;; Make sure done item separator is hidden (if done items
3227 ;; were initially visible).
3228 (let (todo-show-with-done) (todo-category-select)))))))
3230 (defun todo-unarchive-items ()
3231 "Unarchive at least one item in this archive category.
3232 If there are marked items, unarchive all of these; otherwise,
3233 unarchive the item at point.
3235 Unarchived items are restored as done items to the corresponding
3236 category in the todo file, inserted at the top of done items
3237 section. If all items in the archive category have been
3238 restored, the category is deleted from the archive. If this was
3239 the only category in the archive, the archive file is deleted."
3241 (when (eq major-mode 'todo-archive-mode)
3242 (let* ((cat (todo-current-category))
3243 (tbuf (find-file-noselect
3244 (concat (file-name-sans-extension todo-current-todo-file)
3246 (marked (assoc cat todo-categories-with-marks))
3247 (item (concat (todo-item-string) "\n"))
3253 (goto-char (point-min))
3255 (when (todo-marked-item-p)
3256 (setq marked-items (concat marked-items (todo-item-string) "\n"))
3257 (setq marked-count (1+ marked-count)))
3258 (todo-forward-item))))
3259 ;; Restore items to top of category's done section and update counts.
3260 (with-current-buffer tbuf
3261 (let (buffer-read-only newcat)
3263 (goto-char (point-min))
3264 ;; Find the corresponding todo category, or if there isn't
3266 (unless (re-search-forward
3267 (concat "^" (regexp-quote (concat todo-category-beg cat))
3269 (todo-add-category nil cat)
3271 ;; Go to top of category's done section.
3273 (concat "^" (regexp-quote todo-category-done)) nil t)
3276 (insert marked-items)
3277 (todo-update-count 'done marked-count cat)
3278 (unless newcat ; Newly added category has no archive.
3279 (todo-update-count 'archived (- marked-count) cat)))
3282 (todo-update-count 'done 1 cat)
3283 (unless newcat ; Newly added category has no archive.
3284 (todo-update-count 'archived -1 cat))))
3285 (todo-update-categories-sexp)))
3286 ;; Delete restored items from archive.
3289 (goto-char (point-min)))
3292 (if (or (todo-marked-item-p) item)
3296 (throw 'done (setq item nil))))
3297 (todo-forward-item))))
3298 (todo-update-count 'done (if marked (- marked-count) -1) cat)
3299 ;; If that was the last category in the archive, delete the whole file.
3300 (if (= (length todo-categories) 1)
3302 (delete-file todo-current-todo-file)
3303 ;; Kill the archive buffer silently.
3304 (set-buffer-modified-p nil)
3306 ;; Otherwise, if the archive category is now empty, delete it.
3307 (when (eq (point-min) (point-max))
3309 (let ((beg (re-search-backward
3310 (concat "^" (regexp-quote todo-category-beg) cat "$")
3312 (end (if (re-search-forward
3313 (concat "^" (regexp-quote todo-category-beg))
3317 (remove-overlays beg end)
3318 (delete-region beg end)
3319 (setq todo-categories (delete (assoc cat todo-categories)
3321 (todo-update-categories-sexp))))
3322 ;; Visit category in todo file and show restored done items.
3323 (let ((tfile (buffer-file-name tbuf))
3324 (todo-show-with-done t))
3325 (set-window-buffer (selected-window)
3326 (set-buffer (find-file-noselect tfile)))
3327 (todo-category-number cat)
3328 (todo-category-select)
3329 (message "Items unarchived.")))))
3331 (defun todo-jump-to-archive-category (&optional file)
3332 "Prompt for a category in a todo archive and jump to it.
3333 With prefix argument FILE, prompt for an archive and choose (with
3334 TAB completion) a category in it to jump to; otherwise, choose
3335 and jump to any category in the current archive."
3337 (todo-jump-to-category file 'archive))
3339 ;; -----------------------------------------------------------------------------
3340 ;;; Displaying and sorting tables of categories
3341 ;; -----------------------------------------------------------------------------
3343 (defcustom todo-categories-category-label "Category"
3344 "Category button label in Todo Categories mode."
3346 :group 'todo-categories)
3348 (defcustom todo-categories-todo-label "Todo"
3349 "Todo button label in Todo Categories mode."
3351 :group 'todo-categories)
3353 (defcustom todo-categories-diary-label "Diary"
3354 "Diary button label in Todo Categories mode."
3356 :group 'todo-categories)
3358 (defcustom todo-categories-done-label "Done"
3359 "Done button label in Todo Categories mode."
3361 :group 'todo-categories)
3363 (defcustom todo-categories-archived-label "Archived"
3364 "Archived button label in Todo Categories mode."
3366 :group 'todo-categories)
3368 (defcustom todo-categories-totals-label "Totals"
3369 "String to label total item counts in Todo Categories mode."
3371 :group 'todo-categories)
3373 (defcustom todo-categories-number-separator " | "
3374 "String between number and category in Todo Categories mode.
3375 This separates the number from the category name in the default
3376 categories display according to priority."
3378 :group 'todo-categories)
3380 (defcustom todo-categories-align 'center
3381 "Alignment of category names in Todo Categories mode."
3382 :type '(radio (const left) (const center) (const right))
3383 :group 'todo-categories)
3385 (defun todo-show-categories-table ()
3386 "Display a table of the current file's categories and item counts.
3388 In the initial display the lines of the table are numbered,
3389 indicating the current order of the categories when sequentially
3390 navigating through the todo file with `\\[todo-forward-category]'
3391 and `\\[todo-backward-category]'. You can reorder the lines, and
3392 hence the category sequence, by typing `\\[todo-raise-category]'
3393 or `\\[todo-lower-category]' to raise or lower the category at
3394 point, or by typing `\\[todo-set-category-number]' and entering a
3395 number at the prompt or by typing `\\[todo-set-category-number]'
3396 with a numeric prefix. If you save the todo file after
3397 reordering the categories, the new order persists in subsequent
3400 The labels above the category names and item counts are buttons,
3401 and clicking these changes the display: sorted by category name
3402 or by the respective item counts (alternately descending or
3403 ascending). In these displays the categories are not numbered
3404 and `\\[todo-set-category-number]', `\\[todo-raise-category]' and
3405 `\\[todo-lower-category]' are disabled. (Programmatically, the
3406 sorting is triggered by passing a non-nil SORTKEY argument.)
3408 In addition, the lines with the category names and item counts
3409 are buttonized, and pressing one of these button jumps to the
3410 category in Todo mode (or Todo Archive mode, for categories
3411 containing only archived items, provided user option
3412 `todo-skip-archived-categories' is non-nil. These categories
3413 are shown in `todo-archived-only' face."
3415 (todo-display-categories)
3417 (todo-update-categories-display sortkey)))
3419 (defun todo-next-button (n)
3420 "Move point to the Nth next button in the table of categories."
3422 (forward-button n 'wrap 'display-message)
3423 (and (bolp) (button-at (point))
3424 ;; Align with beginning of category label.
3425 (forward-char (+ 4 (length todo-categories-number-separator)))))
3427 (defun todo-previous-button (n)
3428 "Move point to the Nth previous button in the table of categories."
3430 (backward-button n 'wrap 'display-message)
3431 (and (bolp) (button-at (point))
3432 ;; Align with beginning of category label.
3433 (forward-char (+ 4 (length todo-categories-number-separator)))))
3435 (defun todo-set-category-number (&optional arg)
3436 "Change number of category at point in the table of categories.
3438 With ARG nil, prompt for the new number. Alternatively, the
3439 enter the new number with numerical prefix ARG. Otherwise, if
3440 ARG is either of the symbols `raise' or `lower', raise or lower
3441 the category line in the table by one, respectively, thereby
3442 decreasing or increasing its number."
3444 (let ((curnum (save-excursion
3445 ;; Get the number representing the priority of the category
3446 ;; on the current line.
3447 (forward-line 0) (skip-chars-forward " ") (number-at-point))))
3448 (when curnum ; Do nothing if we're not on a category line.
3449 (let* ((maxnum (length todo-categories))
3450 (prompt (format "Set category priority (1-%d): " maxnum))
3451 (col (current-column))
3452 (buffer-read-only nil)
3453 (priority (cond ((and (eq arg 'raise) (> curnum 1))
3455 ((and (eq arg 'lower) (< curnum maxnum))
3458 (while (not priority)
3459 (setq candidate (or arg (read-number prompt)))
3462 (cond ((or (< candidate 1) (> candidate maxnum))
3463 (format "Priority must be an integer between 1 and %d: "
3465 ((= candidate curnum)
3466 "Choose a different priority than the current one: ")))
3467 (unless prompt (setq priority candidate)))
3468 (let* ((lower (< curnum priority)) ; Priority is being lowered.
3469 (head (butlast todo-categories
3470 (apply (if lower 'identity '1+)
3471 (list (- maxnum priority)))))
3472 (tail (nthcdr (apply (if lower 'identity '1-) (list priority))
3474 ;; Category's name and items counts list.
3475 (catcons (nth (1- curnum) todo-categories))
3476 (todo-categories (nconc head (list catcons) tail))
3478 (when lower (setq todo-categories (nreverse todo-categories)))
3479 (setq todo-categories (delete-dups todo-categories))
3480 (when lower (setq todo-categories (nreverse todo-categories)))
3481 (setq newcats todo-categories)
3483 (with-current-buffer (find-buffer-visiting todo-current-todo-file)
3484 (setq todo-categories newcats)
3485 (todo-update-categories-sexp))
3486 (todo-show-categories-table)
3487 (forward-line (1+ priority))
3488 (forward-char col))))))
3490 (defun todo-raise-category ()
3491 "Raise priority of category at point in the table of categories."
3493 (todo-set-category-number 'raise))
3495 (defun todo-lower-category ()
3496 "Lower priority of category at point in the table of categories."
3498 (todo-set-category-number 'lower))
3500 (defun todo-sort-categories-alphabetically-or-numerically ()
3501 "Sort table of categories alphabetically or numerically."
3504 (goto-char (point-min))
3506 (if (member 'alpha todo-descending-counts)
3508 (todo-update-categories-display nil)
3509 (setq todo-descending-counts
3510 (delete 'alpha todo-descending-counts)))
3511 (todo-update-categories-display 'alpha))))
3513 (defun todo-sort-categories-by-todo ()
3514 "Sort table of categories by number of todo items."
3517 (goto-char (point-min))
3519 (todo-update-categories-display 'todo)))
3521 (defun todo-sort-categories-by-diary ()
3522 "Sort table of categories by number of diary items."
3525 (goto-char (point-min))
3527 (todo-update-categories-display 'diary)))
3529 (defun todo-sort-categories-by-done ()
3530 "Sort table of categories by number of non-archived done items."
3533 (goto-char (point-min))
3535 (todo-update-categories-display 'done)))
3537 (defun todo-sort-categories-by-archived ()
3538 "Sort table of categories by number of archived items."
3541 (goto-char (point-min))
3543 (todo-update-categories-display 'archived)))
3545 (defvar todo-categories-buffer "*Todo Categories*"
3546 "Name of buffer in Todo Categories mode.")
3548 (defun todo-longest-category-name-length (categories)
3549 "Return the length of the longest name in list CATEGORIES."
3551 (dolist (c categories longest)
3552 (setq longest (max longest (length c))))))
3554 (defun todo-adjusted-category-label-length ()
3555 "Return adjusted length of category label button.
3556 The adjustment ensures proper tabular alignment in Todo
3558 (let* ((categories (mapcar 'car todo-categories))
3559 (longest (todo-longest-category-name-length categories))
3560 (catlablen (length todo-categories-category-label))
3561 (lc-diff (- longest catlablen)))
3562 (if (and (natnump lc-diff) (cl-oddp lc-diff))
3564 (max longest catlablen))))
3566 (defun todo-padded-string (str)
3567 "Return category name or label string STR padded with spaces.
3568 The placement of the padding is determined by the value of user
3569 option `todo-categories-align'."
3570 (let* ((len (todo-adjusted-category-label-length))
3571 (strlen (length str))
3572 (strlen-odd (eq (logand strlen 1) 1))
3573 (padding (max 0 (/ (- len strlen) 2)))
3574 (padding-left (cond ((eq todo-categories-align 'left) 0)
3575 ((eq todo-categories-align 'center) padding)
3576 ((eq todo-categories-align 'right)
3577 (if strlen-odd (1+ (* padding 2)) (* padding 2)))))
3578 (padding-right (cond ((eq todo-categories-align 'left)
3579 (if strlen-odd (1+ (* padding 2)) (* padding 2)))
3580 ((eq todo-categories-align 'center)
3581 (if strlen-odd (1+ padding) padding))
3582 ((eq todo-categories-align 'right) 0))))
3583 (concat (make-string padding-left 32) str (make-string padding-right 32))))
3585 (defvar todo-descending-counts nil
3586 "List of keys for category counts sorted in descending order.")
3588 (defun todo-sort (list &optional key)
3589 "Return a copy of LIST, possibly sorted according to KEY."
3590 (let* ((l (copy-sequence list))
3591 (fn (if (eq key 'alpha)
3592 (lambda (x) (upcase x)) ; Alphabetize case insensitively.
3593 (lambda (x) (todo-get-count key x))))
3594 ;; Keep track of whether the last sort by key was descending or
3596 (descending (member key todo-descending-counts))
3597 (cmp (if (eq key 'alpha)
3599 (if descending '< '>)))
3600 (pred (lambda (s1 s2) (let ((t1 (funcall fn (car s1)))
3601 (t2 (funcall fn (car s2))))
3602 (funcall cmp t1 t2)))))
3604 (setq l (sort l pred))
3605 ;; Switch between descending and ascending sort order.
3607 (setq todo-descending-counts
3608 (delete key todo-descending-counts))
3609 (push key todo-descending-counts)))
3612 (defun todo-display-sorted (type)
3613 "Keep point on the TYPE count sorting button just clicked."
3614 (let ((opoint (point)))
3615 (todo-update-categories-display type)
3616 (goto-char opoint)))
3618 (defun todo-label-to-key (label)
3619 "Return symbol for sort key associated with LABEL."
3621 (cond ((string= label todo-categories-category-label)
3623 ((string= label todo-categories-todo-label)
3625 ((string= label todo-categories-diary-label)
3627 ((string= label todo-categories-done-label)
3629 ((string= label todo-categories-archived-label)
3630 (setq key 'archived)))
3633 (defun todo-insert-sort-button (label)
3634 "Insert button for displaying categories sorted by item counts.
3635 LABEL determines which type of count is sorted."
3636 (let* ((str (if (string= label todo-categories-category-label)
3637 (todo-padded-string label)
3640 (end (+ beg (length str)))
3642 (insert-button str 'face nil
3645 (let ((key (todo-label-to-key ,label)))
3646 (if (and (member key todo-descending-counts)
3649 ;; If display is alphabetical, switch back to
3650 ;; category priority order.
3651 (todo-display-sorted nil)
3652 (setq todo-descending-counts
3653 (delete key todo-descending-counts)))
3654 (todo-display-sorted key)))))
3655 (setq ov (make-overlay beg end))
3656 (overlay-put ov 'face 'todo-button)))
3658 (defun todo-total-item-counts ()
3659 "Return a list of total item counts for the current file."
3660 (mapcar (lambda (i) (apply '+ (mapcar (lambda (l) (aref l i))
3661 (mapcar 'cdr todo-categories))))
3664 (defvar todo-categories-category-number 0
3665 "Variable for numbering categories in Todo Categories mode.")
3667 (defun todo-insert-category-line (cat &optional nonum)
3668 "Insert button with category CAT's name and item counts.
3669 With non-nil argument NONUM show only these; otherwise, insert a
3670 number in front of the button indicating the category's priority.
3671 The number and the category name are separated by the string
3672 which is the value of the user option
3673 `todo-categories-number-separator'."
3674 (let ((archive (member todo-current-todo-file todo-archives))
3675 (num todo-categories-category-number)
3676 (str (todo-padded-string cat))
3678 (setq num (1+ num) todo-categories-category-number num)
3681 (make-string (+ 4 (length todo-categories-number-separator))
3683 (format " %3d%s" num todo-categories-number-separator))
3685 (mapconcat (lambda (elt)
3687 (make-string (1+ (/ (length (car elt)) 2)) 32) ; label
3688 (format "%3d" (todo-get-count (cdr elt) cat)) ; count
3689 ;; Add an extra space if label length is odd.
3690 (when (cl-oddp (length (car elt))) " ")))
3692 (list (cons todo-categories-done-label 'done))
3693 (list (cons todo-categories-todo-label 'todo)
3694 (cons todo-categories-diary-label 'diary)
3695 (cons todo-categories-done-label 'done)
3696 (cons todo-categories-archived-label
3699 " ") ; Make highlighting on last column look better.
3700 'face (if (and todo-skip-archived-categories
3701 (zerop (todo-get-count 'todo cat))
3702 (zerop (todo-get-count 'done cat))
3703 (not (zerop (todo-get-count 'archived cat))))
3706 'action `(lambda (button) (let ((buf (current-buffer)))
3707 (todo-jump-to-category nil ,cat)
3708 (kill-buffer buf))))
3709 ;; Highlight the sorted count column.
3710 (let* ((beg (+ opoint 7 (length str)))
3712 (cond ((eq nonum 'todo)
3713 (setq beg (+ beg 1 (/ (length todo-categories-todo-label) 2))))
3715 (setq beg (+ beg 1 (length todo-categories-todo-label)
3716 2 (/ (length todo-categories-diary-label) 2))))
3718 (setq beg (+ beg 1 (length todo-categories-todo-label)
3719 2 (length todo-categories-diary-label)
3720 2 (/ (length todo-categories-done-label) 2))))
3721 ((eq nonum 'archived)
3722 (setq beg (+ beg 1 (length todo-categories-todo-label)
3723 2 (length todo-categories-diary-label)
3724 2 (length todo-categories-done-label)
3725 2 (/ (length todo-categories-archived-label) 2)))))
3726 (unless (= beg (+ opoint 7 (length str))) ; Don't highlight categories.
3727 (setq end (+ beg 4))
3728 (setq ovl (make-overlay beg end))
3729 (overlay-put ovl 'face 'todo-sorted-column)))
3732 (defun todo-display-categories ()
3733 "Prepare buffer for displaying table of categories and item counts."
3734 (unless (eq major-mode 'todo-categories-mode)
3735 (setq todo-global-current-todo-file
3736 (or todo-current-todo-file
3737 (todo-absolute-file-name todo-default-todo-file)))
3738 (set-window-buffer (selected-window)
3739 (set-buffer (get-buffer-create todo-categories-buffer)))
3740 (kill-all-local-variables)
3741 (todo-categories-mode)
3742 (let ((archive (member todo-current-todo-file todo-archives))
3745 (insert (format (concat "Category counts for todo "
3746 (if archive "archive" "file")
3748 (todo-short-file-name todo-current-todo-file)))
3750 ;; Make space for the column of category numbers.
3751 (insert (make-string (+ 4 (length todo-categories-number-separator)) 32))
3752 ;; Add the category and item count buttons (if this is the list of
3753 ;; categories in an archive, show only done item counts).
3754 (todo-insert-sort-button todo-categories-category-label)
3757 (insert (make-string 3 32))
3758 (todo-insert-sort-button todo-categories-done-label))
3759 (insert (make-string 3 32))
3760 (todo-insert-sort-button todo-categories-todo-label)
3761 (insert (make-string 2 32))
3762 (todo-insert-sort-button todo-categories-diary-label)
3763 (insert (make-string 2 32))
3764 (todo-insert-sort-button todo-categories-done-label)
3765 (insert (make-string 2 32))
3766 (todo-insert-sort-button todo-categories-archived-label))
3769 (defun todo-update-categories-display (sortkey)
3770 "Populate table of categories and sort by SORTKEY."
3771 (let* ((cats0 todo-categories)
3772 (cats (todo-sort cats0 sortkey))
3773 (archive (member todo-current-todo-file todo-archives))
3774 (todo-categories-category-number 0)
3775 ;; Find start of Category button if we just entered Todo Categories
3777 (pt (if (eq (point) (point-max))
3780 (goto-char (next-single-char-property-change
3781 (point) 'face nil (line-end-position))))))
3784 (delete-region (point) (point-max))
3785 ;; Fill in the table with buttonized lines, each showing a category and
3787 (mapc (lambda (cat) (todo-insert-category-line cat sortkey))
3790 ;; Add a line showing item count totals.
3791 (insert (make-string (+ 4 (length todo-categories-number-separator)) 32)
3792 (todo-padded-string todo-categories-totals-label)
3796 (make-string (1+ (/ (length (car elt)) 2)) 32)
3797 (format "%3d" (nth (cdr elt) (todo-total-item-counts)))
3798 ;; Add an extra space if label length is odd.
3799 (when (cl-oddp (length (car elt))) " ")))
3801 (list (cons todo-categories-done-label 2))
3802 (list (cons todo-categories-todo-label 0)
3803 (cons todo-categories-diary-label 1)
3804 (cons todo-categories-done-label 2)
3805 (cons todo-categories-archived-label 3)))
3807 ;; Put cursor on Category button initially.
3808 (if pt (goto-char pt))
3809 (setq buffer-read-only t)))
3811 ;; -----------------------------------------------------------------------------
3812 ;;; Searching and item filtering
3813 ;; -----------------------------------------------------------------------------
3815 (defun todo-search ()
3816 "Search for a regular expression in this todo file.
3817 The search runs through the whole file and encompasses all and
3818 only todo and done items; it excludes category names. Multiple
3819 matches are shown sequentially, highlighted in `todo-search'
3822 (let ((regex (read-from-minibuffer "Enter a search string (regexp): "))
3824 matches match cat in-done ov mlen msg)
3826 (goto-char (point-min))
3828 (setq match (re-search-forward regex nil t))
3829 (goto-char (line-beginning-position))
3830 (unless (or (equal (point) 1)
3831 (looking-at (concat "^" (regexp-quote todo-category-beg))))
3832 (if match (push match matches)))
3834 (setq matches (reverse matches))
3838 (setq match (pop matches))
3841 (when (looking-at todo-done-string-start)
3843 (re-search-backward (concat "^" (regexp-quote todo-category-beg)
3844 "\\(.*\\)\n") nil t)
3845 (setq cat (match-string-no-properties 1))
3846 (todo-category-number cat)
3847 (todo-category-select)
3849 (unless todo-show-with-done (todo-toggle-view-done-items)))
3851 (setq ov (make-overlay (- (point) (length regex)) (point)))
3852 (overlay-put ov 'face 'todo-search)
3854 (setq mlen (length matches))
3857 (format "There are %d more matches; go to next match? "
3859 "There is one more match; go to it? "))
3861 (throw 'stop (setq msg (if (> mlen 1)
3862 (format "There are %d more matches."
3864 "There is one more match."))))))
3865 (setq msg "There are no more matches."))
3866 (todo-category-select)
3868 (message "No match for \"%s\"" regex))
3870 (if (todo-y-or-n-p (concat msg "\nUnhighlight matches? "))
3871 (todo-clear-matches)
3872 (message "You can unhighlight the matches later by typing %s"
3873 (key-description (car (where-is-internal
3874 'todo-clear-matches))))))))
3876 (defun todo-clear-matches ()
3877 "Remove highlighting on matches found by todo-search."
3879 (remove-overlays 1 (1+ (buffer-size)) 'face 'todo-search))
3881 (defcustom todo-top-priorities-overrides nil
3882 "List of rules specifying number of top priority items to show.
3883 These rules override `todo-top-priorities' on invocations of
3884 `\\[todo-filter-top-priorities]' and
3885 `\\[todo-filter-top-priorities-multifile]'. Each rule is a list
3886 of the form (FILE NUM ALIST), where FILE is a member of
3887 `todo-files', NUM is a number specifying the default number of
3888 top priority items for each category in that file, and ALIST,
3889 when non-nil, consists of conses of a category name in FILE and a
3890 number specifying the default number of top priority items in
3891 that category, which overrides NUM.
3893 This variable should be set interactively by
3894 `\\[todo-set-top-priorities-in-file]' or
3895 `\\[todo-set-top-priorities-in-category]'."
3897 :group 'todo-filtered)
3899 (defcustom todo-top-priorities 1
3900 "Default number of top priorities shown by `todo-filter-top-priorities'."
3902 :group 'todo-filtered)
3904 (defcustom todo-filter-files nil
3905 "List of default files for multifile item filtering."
3906 :type `(set ,@(mapcar (lambda (f) (list 'const f))
3907 (mapcar 'todo-short-file-name
3908 (funcall todo-files-function))))
3909 :group 'todo-filtered)
3911 (defcustom todo-filter-done-items nil
3912 "Non-nil to include done items when processing regexp filters.
3913 Done items from corresponding archive files are also included."
3915 :group 'todo-filtered)
3917 (defun todo-set-top-priorities-in-file ()
3918 "Set number of top priorities for this file.
3919 See `todo-set-top-priorities' for more details."
3921 (todo-set-top-priorities))
3923 (defun todo-set-top-priorities-in-category ()
3924 "Set number of top priorities for this category.
3925 See `todo-set-top-priorities' for more details."
3927 (todo-set-top-priorities t))
3929 (defun todo-filter-top-priorities (&optional arg)
3930 "Display a list of top priority items from different categories.
3931 The categories can be any of those in the current todo file.
3933 With numerical prefix ARG show at most ARG top priority items
3934 from each category. With `C-u' as prefix argument show the
3935 numbers of top priority items specified by category in
3936 `todo-top-priorities-overrides', if this has an entry for the file(s);
3937 otherwise show `todo-top-priorities' items per category in the
3938 file(s). With no prefix argument, if a top priorities file for
3939 the current todo file has previously been saved (see
3940 `todo-save-filtered-items-buffer'), visit this file; if there is
3941 no such file, build the list as with prefix argument `C-u'.
3943 The prefix ARG regulates how many top priorities from
3944 each category to show, as described above."
3946 (todo-filter-items 'top arg))
3948 (defun todo-filter-top-priorities-multifile (&optional arg)
3949 "Display a list of top priority items from different categories.
3950 The categories are a subset of the categories in the files listed
3951 in `todo-filter-files', or if this nil, in the files chosen from
3952 a file selection dialog that pops up in this case.
3954 With numerical prefix ARG show at most ARG top priority items
3955 from each category in each file. With `C-u' as prefix argument
3956 show the numbers of top priority items specified in
3957 `todo-top-priorities-overrides', if this is non-nil; otherwise show
3958 `todo-top-priorities' items per category. With no prefix
3959 argument, if a top priorities file for the chosen todo files
3960 exists (see `todo-save-filtered-items-buffer'), visit this file;
3961 if there is no such file, do the same as with prefix argument
3964 (todo-filter-items 'top arg t))
3966 (defun todo-filter-diary-items (&optional arg)
3967 "Display a list of todo diary items from different categories.
3968 The categories can be any of those in the current todo file.
3970 Called with no prefix ARG, if a diary items file for the current
3971 todo file has previously been saved (see
3972 `todo-save-filtered-items-buffer'), visit this file; if there is
3973 no such file, build the list of diary items. Called with a
3974 prefix argument, build the list even if there is a saved file of
3977 (todo-filter-items 'diary arg))
3979 (defun todo-filter-diary-items-multifile (&optional arg)
3980 "Display a list of todo diary items from different categories.
3981 The categories are a subset of the categories in the files listed
3982 in `todo-filter-files', or if this nil, in the files chosen from
3983 a file selection dialog that pops up in this case.
3985 Called with no prefix ARG, if a diary items file for the chosen
3986 todo files has previously been saved (see
3987 `todo-save-filtered-items-buffer'), visit this file; if there is
3988 no such file, build the list of diary items. Called with a
3989 prefix argument, build the list even if there is a saved file of
3992 (todo-filter-items 'diary arg t))
3994 (defun todo-filter-regexp-items (&optional arg)
3995 "Prompt for a regular expression and display items that match it.
3996 The matches can be from any categories in the current todo file
3997 and with non-nil option `todo-filter-done-items', can include
3998 not only todo items but also done items, including those in
4001 Called with no prefix ARG, if a regexp items file for the current
4002 todo file has previously been saved (see
4003 `todo-save-filtered-items-buffer'), visit this file; if there is
4004 no such file, build the list of regexp items. Called with a
4005 prefix argument, build the list even if there is a saved file of
4008 (todo-filter-items 'regexp arg))
4010 (defun todo-filter-regexp-items-multifile (&optional arg)
4011 "Prompt for a regular expression and display items that match it.
4012 The matches can be from any categories in the files listed in
4013 `todo-filter-files', or if this nil, in the files chosen from a
4014 file selection dialog that pops up in this case. With non-nil
4015 option `todo-filter-done-items', the matches can include not
4016 only todo items but also done items, including those in Archive
4019 Called with no prefix ARG, if a regexp items file for the current
4020 todo file has previously been saved (see
4021 `todo-save-filtered-items-buffer'), visit this file; if there is
4022 no such file, build the list of regexp items. Called with a
4023 prefix argument, build the list even if there is a saved file of
4026 (todo-filter-items 'regexp arg t))
4028 (defun todo-find-filtered-items-file ()
4029 "Choose a filtered items file and visit it."
4031 (let ((files (directory-files todo-directory t "\.tod[rty]$" t))
4034 (let ((type (cond ((equal (file-name-extension f) "todr") "regexp")
4035 ((equal (file-name-extension f) "todt") "top")
4036 ((equal (file-name-extension f) "tody") "diary"))))
4037 (push (cons (concat (todo-short-file-name f) " (" type ")") f)
4039 (setq file (completing-read "Choose a filtered items file: "
4040 falist nil t nil nil (car falist)))
4041 (setq file (cdr (assoc-string file falist)))
4044 (defun todo-go-to-source-item ()
4045 "Display the file and category of the filtered item at point."
4047 (let* ((str (todo-item-string))
4048 (buf (current-buffer))
4049 (res (todo-find-item str))
4054 (message "Category %s does not contain this item." cat)
4056 (set-window-buffer (selected-window)
4057 (set-buffer (find-buffer-visiting file)))
4058 (setq todo-current-todo-file file)
4059 (setq todo-category-number (todo-category-number cat))
4060 (let ((todo-show-with-done (if (or todo-filter-done-items
4061 (eq (cdr found) 'done))
4063 todo-show-with-done)))
4064 (todo-category-select))
4065 (goto-char (car found)))))
4067 (defvar todo-multiple-filter-files nil
4068 "List of files selected from `todo-multiple-filter-files' widget.")
4070 (defvar todo-multiple-filter-files-widget nil
4071 "Variable holding widget created by `todo-multiple-filter-files'.")
4073 (defun todo-multiple-filter-files ()
4074 "Pop to a buffer with a widget for choosing multiple filter files."
4077 (require 'wid-edit))
4078 (with-current-buffer (get-buffer-create "*Todo Filter Files*")
4079 (pop-to-buffer (current-buffer))
4081 (kill-all-local-variables)
4082 (widget-insert "Select files for generating the top priorities list.\n\n")
4083 (setq todo-multiple-filter-files-widget
4085 `(set ,@(mapcar (lambda (x) (list 'const x))
4086 (mapcar 'todo-short-file-name
4087 (funcall todo-files-function))))))
4088 (widget-insert "\n")
4089 (widget-create 'push-button
4090 :notify (lambda (widget &rest ignore)
4091 (setq todo-multiple-filter-files 'quit)
4093 (exit-recursive-edit))
4096 (widget-create 'push-button
4097 :notify (lambda (&rest ignore)
4098 (setq todo-multiple-filter-files
4101 (concat todo-directory
4104 todo-multiple-filter-files-widget)))
4106 (exit-recursive-edit))
4108 (use-local-map widget-keymap)
4110 (message "Click \"Apply\" after selecting files.")
4113 (defconst todo-filtered-items-buffer "Todo filtered items"
4114 "Initial name of buffer in Todo Filter Items mode.")
4116 (defconst todo-top-priorities-buffer "Todo top priorities"
4117 "Buffer type string for `todo-filter-items'.")
4119 (defconst todo-diary-items-buffer "Todo diary items"
4120 "Buffer type string for `todo-filter-items'.")
4122 (defconst todo-regexp-items-buffer "Todo regexp items"
4123 "Buffer type string for `todo-filter-items'.")
4125 (defun todo-filter-items (filter &optional new multifile)
4126 "Display a list of items filtered by FILTER.
4127 The values of FILTER can be `top' for top priority items, a cons
4128 of `top' and a number passed by the caller, `diary' for diary
4129 items, or `regexp' for items matching a regular expression
4130 entered by the user. The items can come from any categories in
4131 the current todo file or, with non-nil MULTIFILE, from several
4132 files. If NEW is nil, visit an appropriate file containing the
4133 list of filtered items; if there is no such file, or with non-nil
4134 NEW, build the list and display it.
4136 See the documentation strings of the commands
4137 `todo-filter-top-priorities', `todo-filter-diary-items',
4138 `todo-filter-regexp-items', and those of the corresponding
4139 multifile commands for further details."
4140 (let* ((top (eq filter 'top))
4141 (diary (eq filter 'diary))
4142 (regexp (eq filter 'regexp))
4143 (buf (cond (top todo-top-priorities-buffer)
4144 (diary todo-diary-items-buffer)
4145 (regexp todo-regexp-items-buffer)))
4146 (flist (if multifile
4147 (or todo-filter-files
4148 (progn (todo-multiple-filter-files)
4149 todo-multiple-filter-files))
4150 (list todo-current-todo-file)))
4151 (multi (> (length flist) 1))
4152 (fname (if (equal flist 'quit)
4153 ;; Pressed `cancel' in t-m-f-f file selection dialog.
4155 (concat todo-directory
4156 (mapconcat 'todo-short-file-name flist "-")
4159 (regexp ".todr")))))
4160 (rxfiles (when regexp
4161 (directory-files todo-directory t ".*\\.todr$" t)))
4162 (file-exists (or (file-exists-p fname) rxfiles)))
4163 (cond ((and top new (natnump new))
4164 (todo-filter-items-1 (cons 'top new) flist))
4165 ((and (not new) file-exists)
4166 (when (and rxfiles (> (length rxfiles) 1))
4167 (let ((rxf (mapcar 'todo-short-file-name rxfiles)))
4168 (setq fname (todo-absolute-file-name
4169 (completing-read "Choose a regexp items file: "
4172 (todo-prefix-overlays)
4173 (todo-check-filtered-items-file))
4175 (todo-filter-items-1 filter flist)))
4176 (setq fname (replace-regexp-in-string "-" ", "
4177 (todo-short-file-name fname)))
4178 (rename-buffer (format (concat "%s for file" (if multi "s" "")
4179 " \"%s\"") buf fname))))
4181 (defun todo-filter-items-1 (filter file-list)
4182 "Build a list of items by applying FILTER to FILE-LIST.
4183 Internal subroutine called by `todo-filter-items', which passes
4184 the values of FILTER and FILE-LIST."
4185 (let ((num (if (consp filter) (cdr filter) todo-top-priorities))
4186 (buf (get-buffer-create todo-filtered-items-buffer))
4187 (multifile (> (length file-list) 1))
4188 regexp fname bufstr cat beg end done)
4189 (if (null file-list)
4190 (user-error "No files have been chosen for filtering")
4191 (with-current-buffer buf
4193 (kill-all-local-variables)
4194 (todo-filtered-items-mode))
4195 (when (eq filter 'regexp)
4196 (setq regexp (read-string "Enter a regular expression: ")))
4197 (save-current-buffer
4198 (dolist (f file-list)
4199 ;; Before inserting file contents into temp buffer, save a modified
4200 ;; buffer visiting it.
4201 (let ((bf (find-buffer-visiting f)))
4202 (when (buffer-modified-p bf)
4203 (with-current-buffer bf (save-buffer))))
4204 (setq fname (todo-short-file-name f))
4206 (when (and todo-filter-done-items (eq filter 'regexp))
4207 ;; If there is a corresponding archive file for the
4208 ;; todo file, insert it first and add identifiers for
4209 ;; todo-go-to-source-item.
4210 (let ((arch (concat (file-name-sans-extension f) ".toda")))
4211 (when (file-exists-p arch)
4212 (insert-file-contents arch)
4213 ;; Delete todo archive file's categories sexp.
4214 (delete-region (line-beginning-position)
4215 (1+ (line-end-position)))
4218 (when (re-search-forward
4219 (concat (if todo-filter-done-items
4220 (concat "\\(?:" todo-done-string-start
4221 "\\|" todo-date-string-start
4223 todo-date-string-start)
4224 todo-date-pattern "\\(?: "
4225 diary-time-regexp "\\)?"
4226 (if todo-filter-done-items
4228 (regexp-quote todo-nondiary-end)) "?")
4230 (insert "(archive) "))
4232 (insert-file-contents f)
4233 ;; Delete todo file's categories sexp.
4234 (delete-region (line-beginning-position) (1+ (line-end-position)))
4236 ;; Unless the number of top priorities to show was
4237 ;; passed by the caller, the file-wide value from
4238 ;; `todo-top-priorities-overrides', if non-nil, overrides
4239 ;; `todo-top-priorities'.
4240 (unless (consp filter)
4241 (setq fnum (or (nth 1 (assoc f todo-top-priorities-overrides))
4242 todo-top-priorities)))
4243 (while (re-search-forward
4244 (concat "^" (regexp-quote todo-category-beg)
4245 "\\(.+\\)\n") nil t)
4246 (setq cat (match-string 1))
4248 ;; Unless the number of top priorities to show was
4249 ;; passed by the caller, the category-wide value
4250 ;; from `todo-top-priorities-overrides', if non-nil,
4251 ;; overrides a non-nil file-wide value from
4252 ;; `todo-top-priorities-overrides' as well as
4253 ;; `todo-top-priorities'.
4254 (unless (consp filter)
4255 (let ((cats (nth 2 (assoc f todo-top-priorities-overrides))))
4256 (setq cnum (or (cdr (assoc cat cats)) fnum))))
4257 (delete-region (match-beginning 0) (match-end 0))
4258 (setq beg (point)) ; First item in the current category.
4259 (setq end (if (re-search-forward
4260 (concat "^" (regexp-quote todo-category-beg))
4266 (if (re-search-forward
4267 (concat "\n" (regexp-quote todo-category-done))
4271 (unless (and todo-filter-done-items (eq filter 'regexp))
4272 ;; Leave done items.
4273 (delete-region done end)
4275 (narrow-to-region beg end) ; Process only current category.
4276 (goto-char (point-min))
4277 ;; Apply the filter.
4278 (cond ((eq filter 'diary)
4280 (if (looking-at (regexp-quote todo-nondiary-start))
4282 (todo-forward-item))))
4283 ((eq filter 'regexp)
4285 (if (looking-at todo-item-start)
4286 (if (string-match regexp (todo-item-string))
4289 ;; Kill lines that aren't part of a todo or done
4290 ;; item (empty or todo-category-done).
4291 (delete-region (line-beginning-position)
4292 (1+ (line-end-position))))
4293 ;; If last todo item in file matches regexp and
4294 ;; there are no following done items,
4295 ;; todo-category-done string is left dangling,
4296 ;; because todo-forward-item jumps over it.
4299 (concat (regexp-quote todo-done-string)
4301 (delete-region (point) (progn
4304 (t ; Filter top priority items.
4305 (setq num (or cnum fnum num))
4307 (todo-forward-item num))))
4309 ;; Delete non-top-priority items.
4310 (unless (member filter '(diary regexp))
4311 (delete-region beg end))
4312 (goto-char (point-min))
4313 ;; Add file (if using multiple files) and category tags to
4316 (when (re-search-forward
4317 (concat (if todo-filter-done-items
4318 (concat "\\(?:" todo-done-string-start
4319 "\\|" todo-date-string-start
4321 todo-date-string-start)
4322 todo-date-pattern "\\(?: " diary-time-regexp
4323 "\\)?" (if todo-filter-done-items
4325 (regexp-quote todo-nondiary-end))
4329 (when (looking-at "(archive) ") (goto-char (match-end 0)))
4330 (insert (if multifile (concat fname ":") "") cat "]"))
4333 (setq bufstr (buffer-string))
4334 (with-current-buffer buf
4335 (let (buffer-read-only)
4336 (insert bufstr)))))))
4337 (set-window-buffer (selected-window) (set-buffer buf))
4338 (todo-prefix-overlays)
4339 (goto-char (point-min)))))
4341 (defun todo-set-top-priorities (&optional arg)
4342 "Set number of top priorities shown by `todo-filter-top-priorities'.
4343 With non-nil ARG, set the number only for the current Todo
4344 category; otherwise, set the number for all categories in the
4347 Calling this function via either of the commands
4348 `todo-set-top-priorities-in-file' or
4349 `todo-set-top-priorities-in-category' is the recommended way to
4350 set the user customizable option `todo-top-priorities-overrides'."
4351 (let* ((cat (todo-current-category))
4352 (file todo-current-todo-file)
4353 (rules todo-top-priorities-overrides)
4354 (frule (assoc-string file rules))
4355 (crule (assoc-string cat (nth 2 frule)))
4356 (crules (nth 2 frule))
4357 (cur (or (if arg (cdr crule) (nth 1 frule))
4358 todo-top-priorities))
4359 (prompt (if arg (concat "Number of top priorities in this category"
4360 " (currently %d): ")
4361 (concat "Default number of top priorities per category"
4362 " in this file (currently %d): ")))
4367 (setq new (read-number (format prompt cur0))
4368 prompt "Enter a non-negative number: "
4371 (append (delete crule crules) (list (cons cat new)))
4372 (append (list file new) (list crules))))
4373 (setq rules (cons (if arg
4374 (list file cur nrule)
4376 (delete frule rules)))
4377 (customize-save-variable 'todo-top-priorities-overrides rules)
4378 (todo-prefix-overlays)))
4380 (defun todo-find-item (str)
4381 "Search for filtered item STR in its saved todo file.
4382 Return the list (FOUND FILE CAT), where CAT and FILE are the
4383 item's category and file, and FOUND is a cons cell if the search
4384 succeeds, whose car is the start of the item in FILE and whose
4385 cdr is `done', if the item is now a done item, `changed', if its
4386 text was truncated or augmented or, for a top priority item, if
4387 its priority has changed, and `same' otherwise."
4388 (string-match (concat (if todo-filter-done-items
4389 (concat "\\(?:" todo-done-string-start "\\|"
4390 todo-date-string-start "\\)")
4391 todo-date-string-start)
4392 todo-date-pattern "\\(?: " diary-time-regexp "\\)?"
4393 (if todo-filter-done-items
4395 (regexp-quote todo-nondiary-end)) "?"
4396 "\\(?4: \\[\\(?3:(archive) \\)?\\(?2:.*:\\)?"
4397 "\\(?1:.*\\)\\]\\).*$") str)
4398 (let ((cat (match-string 1 str))
4399 (file (match-string 2 str))
4400 (archive (string= (match-string 3 str) "(archive) "))
4401 (filcat (match-string 4 str))
4403 (tpbuf (save-match-data (string-match "top" (buffer-name))))
4405 (setq str (replace-match "" nil nil str 4))
4407 ;; Calculate priority of STR wrt its category.
4409 (while (search-backward filcat nil t)
4410 (setq tpriority (1+ tpriority)))))
4412 (concat todo-directory (substring file 0 -1)
4413 (if archive ".toda" ".todo"))
4415 (concat (file-name-sans-extension
4416 todo-global-current-todo-file) ".toda")
4417 todo-global-current-todo-file)))
4418 (find-file-noselect file)
4419 (with-current-buffer (find-buffer-visiting file)
4422 (goto-char (point-min))
4423 (let ((beg (re-search-forward
4424 (concat "^" (regexp-quote (concat todo-category-beg cat))
4427 (done (save-excursion
4429 (concat "^" (regexp-quote todo-category-done)) nil t)))
4430 (end (save-excursion
4431 (or (re-search-forward
4432 (concat "^" (regexp-quote todo-category-beg))
4435 (setq found (when (search-forward str end t)
4436 (goto-char (match-beginning 0))))
4439 (cons found (if (> (point) done)
4441 (let ((cpriority 1))
4444 ;; Not top item in category.
4445 (while (> (point) (1+ beg))
4446 (let ((opoint (point)))
4447 (todo-backward-item)
4448 ;; Can't move backward beyond
4449 ;; first item in file.
4450 (unless (= (point) opoint)
4451 (setq cpriority (1+ cpriority)))))))
4452 (if (and (= tpriority cpriority)
4453 ;; Proper substring is not the same.
4454 (string= (todo-item-string)
4458 (list found file cat)))
4460 (defun todo-check-filtered-items-file ()
4461 "Check if filtered items file is up to date and a show suitable message."
4465 (let* ((item (todo-item-string))
4466 (found (car (todo-find-item item))))
4467 (unless (eq (cdr found) 'same)
4469 (overlay-put (make-overlay (todo-item-start) (todo-item-end))
4470 'face 'todo-search))
4471 (setq count (1+ count))))
4472 ;; (throw 'old (message "The marked item is not up to date.")))
4473 (todo-forward-item))
4475 (message "Filtered items file is up to date.")
4476 (message (concat "The highlighted item" (if (= count 1) " is " "s are ")
4478 ;; "\nType <return> on item for details."
4481 (defun todo-filter-items-filename ()
4482 "Return absolute file name for saving this Filtered Items buffer."
4483 (let ((bufname (buffer-name)))
4484 (string-match "\"\\([^\"]+\\)\"" bufname)
4485 (let* ((filename-str (substring bufname (match-beginning 1) (match-end 1)))
4486 (filename-base (replace-regexp-in-string ", " "-" filename-str))
4487 (top-priorities (string-match "top priorities" bufname))
4488 (diary-items (string-match "diary items" bufname))
4489 (regexp-items (string-match "regexp items" bufname)))
4491 (let ((prompt (concat "Enter a short identifying string"
4492 " to make this file name unique: ")))
4493 (setq filename-base (concat filename-base "-" (read-string prompt)))))
4494 (concat todo-directory filename-base
4495 (cond (top-priorities ".todt")
4496 (diary-items ".tody")
4497 (regexp-items ".todr"))))))
4499 (defun todo-save-filtered-items-buffer ()
4500 "Save current Filtered Items buffer to a file.
4501 If the file already exists, overwrite it only on confirmation."
4502 (let ((filename (or (buffer-file-name) (todo-filter-items-filename))))
4503 (write-file filename t)))
4505 ;; -----------------------------------------------------------------------------
4506 ;;; Printing Todo mode buffers
4507 ;; -----------------------------------------------------------------------------
4509 (defcustom todo-print-buffer-function 'ps-print-buffer-with-faces
4510 "Function called by the command `todo-print-buffer'."
4514 (defvar todo-print-buffer "*Todo Print*"
4515 "Name of buffer with printable version of Todo mode buffer.")
4517 (defun todo-print-buffer (&optional to-file)
4518 "Produce a printable version of the current Todo mode buffer.
4519 This converts overlays and soft line wrapping and, depending on
4520 the value of `todo-print-buffer-function', includes faces. With
4521 non-nil argument TO-FILE write the printable version to a file;
4522 otherwise, send it to the default printer."
4524 (let ((buf todo-print-buffer)
4526 ((eq major-mode 'todo-mode)
4527 (concat "Todo File: "
4528 (todo-short-file-name todo-current-todo-file)
4529 "\nCategory: " (todo-current-category)))
4530 ((eq major-mode 'todo-filtered-items-mode)
4532 (prefix (propertize (concat todo-prefix " ")
4533 'face 'todo-prefix-string))
4535 (fill-prefix (make-string todo-indent-to-here 32))
4536 (content (buffer-string))
4538 (with-current-buffer (get-buffer-create buf)
4540 (goto-char (point-min))
4543 (end (save-excursion (todo-item-end))))
4544 (when todo-number-prefix
4546 (setq prefix (propertize (concat (number-to-string num) " ")
4547 'face 'todo-prefix-string)))
4549 (fill-region beg end))
4550 ;; Calling todo-forward-item infloops at todo-item-start due to
4551 ;; non-overlay prefix, so search for item start instead.
4552 (if (re-search-forward todo-item-start nil t)
4554 (goto-char (point-max))))
4555 (if (re-search-backward (concat "^" (regexp-quote todo-category-done))
4557 (replace-match todo-done-separator))
4558 (goto-char (point-min))
4562 (let ((file (read-file-name "Print to file: ")))
4563 (funcall todo-print-buffer-function file))
4564 (funcall todo-print-buffer-function)))
4567 (defun todo-print-buffer-to-file ()
4568 "Save printable version of this Todo mode buffer to a file."
4570 (todo-print-buffer t))
4572 ;; -----------------------------------------------------------------------------
4573 ;;; Legacy Todo mode files
4574 ;; -----------------------------------------------------------------------------
4576 (defcustom todo-legacy-date-time-regexp
4577 (concat "\\(?1:[0-9]\\{4\\}\\)-\\(?2:[0-9]\\{2\\}\\)-"
4578 "\\(?3:[0-9]\\{2\\}\\) \\(?4:[0-9]\\{2\\}:[0-9]\\{2\\}\\)")
4579 "Regexp matching legacy todo-mode.el item date-time strings.
4580 In order for `todo-convert-legacy-files' to correctly convert
4581 this string to the current Todo mode format, the regexp must
4582 contain four explicitly numbered groups (see `(elisp) Regexp
4583 Backslash'), where group 1 matches a string for the year, group 2
4584 a string for the month, group 3 a string for the day and group 4
4585 a string for the time. The default value converts date-time
4586 strings built using the default value of
4587 `todo-time-string-format' from todo-mode.el."
4591 (defun todo-convert-legacy-date-time ()
4592 "Return converted date-time string.
4593 Helper function for `todo-convert-legacy-files'."
4594 (let* ((year (match-string 1))
4595 (month (match-string 2))
4596 (monthname (calendar-month-name (string-to-number month) t))
4597 (day (match-string 3))
4598 (time (match-string 4))
4601 (insert (mapconcat 'eval calendar-date-display-form "")
4602 (when time (concat " " time)))))
4604 (defun todo-convert-legacy-files ()
4605 "Convert legacy todo files to the current Todo mode format.
4606 The old-style files named by the variables `todo-file-do' and
4607 `todo-file-done' from the old package are converted to the new
4608 format and saved (the latter as a todo archive file) with a new
4609 name in `todo-directory'. See also the documentation string of
4610 `todo-legacy-date-time-regexp' for further details."
4612 ;; If there are user customizations of legacy options, use them,
4613 ;; otherwise use the legacy default values.
4614 (let ((todo-file-do-tem (if (boundp 'todo-file-do)
4616 (locate-user-emacs-file "todo-do" ".todo-do")))
4617 (todo-file-done-tem (if (boundp 'todo-file-done)
4619 (locate-user-emacs-file "todo-done" ".todo-done")))
4620 (todo-initials-tem (and (boundp 'todo-initials) todo-initials))
4621 (todo-entry-prefix-function-tem (and (boundp 'todo-entry-prefix-function)
4622 todo-entry-prefix-function))
4624 ;; Convert `todo-file-do'.
4625 (if (not (file-exists-p todo-file-do-tem))
4626 (message "No legacy todo file exists")
4627 (let ((default "todo-do-conv")
4630 (insert-file-contents todo-file-do-tem)
4631 ;; Eliminate old-style local variables list in first line.
4632 (delete-region (line-beginning-position) (1+ (line-end-position)))
4633 (search-forward " --- " nil t) ; Legacy todo-category-beg.
4634 (setq todo-prefix-tem (buffer-substring-no-properties
4635 (line-beginning-position) (match-beginning 0)))
4636 (goto-char (point-min))
4639 ;; Old-style category start delimiter.
4640 ((looking-at (regexp-quote (concat todo-prefix-tem " --- ")))
4641 (replace-match todo-category-beg))
4642 ;; Old-style category end delimiter.
4643 ((looking-at (regexp-quote "--- End"))
4645 ;; Old-style category separator.
4646 ((looking-at (regexp-quote
4647 (concat todo-prefix-tem " "
4648 (make-string 75 ?-))))
4649 (replace-match todo-category-done))
4650 ;; Old-style item header (date/time/initials).
4651 ((looking-at (concat (regexp-quote todo-prefix-tem) " "
4652 (if todo-entry-prefix-function-tem
4653 (funcall todo-entry-prefix-function-tem)
4654 (concat todo-legacy-date-time-regexp " "
4655 (if todo-initials-tem
4656 (regexp-quote todo-initials-tem)
4659 (todo-convert-legacy-date-time)))
4661 (setq file (concat todo-directory
4663 (format "Save file as (default \"%s\"): " default)
4666 (unless (file-exists-p todo-directory)
4667 (make-directory todo-directory))
4668 (write-region (point-min) (point-max) file nil 'nomessage nil t))
4670 (insert-file-contents file)
4671 (let ((todo-categories (todo-make-categories-list t)))
4672 (todo-update-categories-sexp)
4673 (todo-check-format))
4674 (write-region (point-min) (point-max) file nil 'nomessage))
4675 (setq todo-files (funcall todo-files-function))
4676 ;; Convert `todo-file-done'.
4677 (when (file-exists-p todo-file-done-tem)
4679 (insert-file-contents todo-file-done-tem)
4680 (let ((beg (make-marker))
4682 cat cats comment item)
4684 (when (looking-at todo-legacy-date-time-regexp)
4685 (set-marker beg (point))
4686 (todo-convert-legacy-date-time)
4687 (set-marker end (point))
4689 (insert "[" todo-done-string)
4693 (when (looking-at todo-legacy-date-time-regexp)
4694 (todo-convert-legacy-date-time))
4695 (when (looking-at (concat " " (if todo-initials-tem
4700 (replace-match "")))
4701 (if (re-search-forward
4702 (concat "^" todo-legacy-date-time-regexp) nil t)
4703 (goto-char (match-beginning 0))
4704 (goto-char (point-max)))
4706 (when (looking-back "\\[\\([^][]+\\)\\]")
4707 (setq cat (match-string 1))
4708 (goto-char (match-beginning 0))
4710 ;; If the item ends with a non-comment parenthesis not
4711 ;; followed by a period, we lose (but we inherit that
4712 ;; problem from the legacy code).
4713 (when (looking-back "(\\(.*\\)) ")
4714 (setq comment (match-string 1))
4716 (insert "[" todo-comment-string ": " comment "]"))
4717 (set-marker end (point))
4718 (if (member cat cats)
4719 ;; If item is already in its category, leave it there.
4720 (unless (save-excursion
4722 (concat "^" (regexp-quote todo-category-beg)
4724 (string= (match-string 1) cat))
4725 ;; Else move it to its category.
4726 (setq item (buffer-substring-no-properties beg end))
4727 (delete-region beg (1+ end))
4728 (set-marker beg (point))
4731 (regexp-quote (concat todo-category-beg cat))
4735 (if (re-search-forward
4736 (concat "^" (regexp-quote todo-category-beg)
4738 (progn (goto-char (match-beginning 0))
4741 (goto-char (point-max)))
4746 (insert todo-category-beg cat "\n\n"
4747 todo-category-done "\n"))
4749 (set-marker beg nil)
4750 (set-marker end nil))
4751 (setq file (concat (file-name-sans-extension file) ".toda"))
4752 (write-region (point-min) (point-max) file nil 'nomessage nil t))
4754 (insert-file-contents file)
4755 (let* ((todo-categories (todo-make-categories-list t)))
4756 (todo-update-categories-sexp)
4757 (todo-check-format))
4758 (write-region (point-min) (point-max) file nil 'nomessage)
4759 (setq archive-sexp (read (buffer-substring-no-properties
4760 (line-beginning-position)
4761 (line-end-position)))))
4762 (setq file (concat (file-name-sans-extension file) ".todo"))
4763 ;; Update categories sexp of converted todo file again, adding
4764 ;; counts of archived items.
4766 (insert-file-contents file)
4767 (let ((sexp (read (buffer-substring-no-properties
4768 (line-beginning-position)
4769 (line-end-position)))))
4771 (let ((archive-cat (assoc (car cat) archive-sexp)))
4773 (aset (cdr cat) 3 (aref (cdr archive-cat) 2)))))
4774 (delete-region (line-beginning-position) (line-end-position))
4775 (prin1 sexp (current-buffer)))
4776 (write-region (point-min) (point-max) file nil 'nomessage))
4777 (setq todo-archives (funcall todo-files-function t)))
4778 (todo-reevaluate-filelist-defcustoms)
4779 (when (y-or-n-p (concat "Format conversion done; do you want to "
4780 "visit the converted file now? "))
4781 (setq todo-current-todo-file file)
4782 (unless todo-default-todo-file
4783 ;; We just initialized the first todo file, so make it the
4784 ;; default now to avoid an infinite recursion with todo-show.
4785 (setq todo-default-todo-file (todo-short-file-name file)))
4788 ;; -----------------------------------------------------------------------------
4789 ;;; Utility functions for todo files, categories and items
4790 ;; -----------------------------------------------------------------------------
4792 (defun todo-absolute-file-name (name &optional type)
4793 "Return the absolute file name of short todo file NAME.
4794 With TYPE `archive' or `top' return the absolute file name of the
4795 short todo archive or top priorities file name, respectively."
4796 ;; No-op if there is no todo file yet (i.e. don't concatenate nil).
4799 (concat todo-directory name
4800 (cond ((eq type 'archive) ".toda")
4801 ((eq type 'top) ".todt")
4802 ((eq type 'diary) ".tody")
4803 ((eq type 'regexp) ".todr")
4806 (defun todo-check-file (file)
4807 "Check the state associated with FILE and update it if necessary.
4808 If FILE exists, return t. If it does not exist and there is no
4809 live buffer with its content, return nil; if there is such a
4810 buffer and the user tries to show it, ask whether to restore
4811 FILE, and if confirmed, do so and return t; else delete the
4812 buffer, clean up the state and return nil."
4813 (setq todo-files (funcall todo-files-function))
4814 (setq todo-archives (funcall todo-files-function t))
4815 (if (file-exists-p file)
4817 (setq todo-visited (delete file todo-visited))
4818 (let ((buf (find-buffer-visiting file)))
4822 (format (concat "Todo file \"%s\" has been deleted but "
4823 "its content is still in a buffer!\n")
4824 (todo-short-file-name file))
4825 "Save that buffer and restore the todo file? ")))
4827 (with-current-buffer buf (save-buffer))
4828 (setq todo-files (funcall todo-files-function))
4829 (setq todo-archives (funcall todo-files-function t))
4831 (let* ((files (append todo-files todo-archives))
4832 (tctf todo-current-todo-file)
4833 (tgctf todo-global-current-todo-file)
4834 (tdtf (todo-absolute-file-name todo-default-todo-file)))
4835 (unless (or (not todo-current-todo-file)
4836 (member todo-current-todo-file files))
4837 (setq todo-current-todo-file nil))
4838 (unless (or (not todo-global-current-todo-file)
4839 (member todo-global-current-todo-file files))
4840 (setq todo-global-current-todo-file nil))
4841 (unless (or (not todo-default-todo-file)
4842 (member todo-default-todo-file files))
4843 (setq todo-default-todo-file (todo-short-file-name
4845 (todo-reevaluate-filelist-defcustoms)
4846 (when buf (kill-buffer buf))
4849 (defun todo-category-number (cat)
4850 "Return the number of category CAT in this todo file.
4851 The buffer-local variable `todo-category-number' holds this
4852 number as its value."
4853 (let ((categories (mapcar 'car todo-categories)))
4854 (setq todo-category-number
4855 ;; Increment by one, so that the number of the first
4856 ;; category is one rather than zero.
4857 (1+ (- (length categories)
4858 (length (member cat categories)))))))
4860 (defun todo-current-category ()
4861 "Return the name of the current category."
4862 (car (nth (1- todo-category-number) todo-categories)))
4864 (defun todo-category-select ()
4865 "Display the current category correctly."
4866 (let ((name (todo-current-category))
4867 cat-begin cat-end done-start done-sep-start done-end)
4869 (goto-char (point-min))
4871 (concat "^" (regexp-quote (concat todo-category-beg name)) "$") nil t)
4872 (setq cat-begin (1+ (line-end-position)))
4873 (setq cat-end (if (re-search-forward
4874 (concat "^" (regexp-quote todo-category-beg)) nil t)
4877 (setq mode-line-buffer-identification
4878 (funcall todo-mode-line-function name))
4879 (narrow-to-region cat-begin cat-end)
4880 (todo-prefix-overlays)
4881 (goto-char (point-min))
4882 (if (re-search-forward (concat "\n\\(" (regexp-quote todo-category-done)
4885 (setq done-start (match-beginning 0))
4886 (setq done-sep-start (match-beginning 1))
4887 (setq done-end (match-end 0)))
4888 (error "Category %s is missing todo-category-done string" name))
4889 (if todo-show-done-only
4890 (narrow-to-region (1+ done-end) (point-max))
4891 (when (and todo-show-with-done
4892 (re-search-forward todo-done-string-start nil t))
4893 ;; Now we want to see the done items, so reset displayed end to end of
4895 (setq done-start cat-end)
4896 ;; Make display overlay for done items separator string, unless there
4898 (let* ((done-sep todo-done-separator)
4899 (ov (progn (goto-char done-sep-start)
4900 (todo-get-overlay 'separator))))
4902 (setq ov (make-overlay done-sep-start done-end))
4903 (overlay-put ov 'todo 'separator)
4904 (overlay-put ov 'display done-sep))))
4905 (narrow-to-region (point-min) done-start)
4906 ;; Loading this from todo-mode, or adding it to the mode hook, causes
4907 ;; Emacs to hang in todo-item-start, at (looking-at todo-item-start).
4908 (when todo-highlight-item
4910 (hl-line-mode 1)))))
4912 (defun todo-get-count (type &optional category)
4913 "Return count of TYPE items in CATEGORY.
4914 If CATEGORY is nil, default to the current category."
4915 (let* ((cat (or category (todo-current-category)))
4916 (counts (cdr (assoc cat todo-categories)))
4917 (idx (cond ((eq type 'todo) 0)
4918 ((eq type 'diary) 1)
4920 ((eq type 'archived) 3))))
4923 (defun todo-update-count (type increment &optional category)
4924 "Change count of TYPE items in CATEGORY by integer INCREMENT.
4925 With nil or omitted CATEGORY, default to the current category."
4926 (let* ((cat (or category (todo-current-category)))
4927 (counts (cdr (assoc cat todo-categories)))
4928 (idx (cond ((eq type 'todo) 0)
4929 ((eq type 'diary) 1)
4931 ((eq type 'archived) 3))))
4932 (aset counts idx (+ increment (aref counts idx)))))
4934 (defun todo-set-categories ()
4935 "Set `todo-categories' from the sexp at the top of the file."
4936 ;; New archive files created by `todo-move-category' are empty, which would
4937 ;; make the sexp test fail and raise an error, so in this case we skip it.
4938 (unless (zerop (buffer-size))
4942 (goto-char (point-min))
4943 (setq todo-categories
4944 (if (looking-at "\(\(\"")
4945 (read (buffer-substring-no-properties
4946 (line-beginning-position)
4947 (line-end-position)))
4948 (error "Invalid or missing todo-categories sexp")))))))
4950 (defun todo-update-categories-sexp ()
4951 "Update the `todo-categories' sexp at the top of the file."
4952 (let (buffer-read-only)
4956 (goto-char (point-min))
4957 (if (looking-at (concat "^" (regexp-quote todo-category-beg)))
4958 (progn (newline) (goto-char (point-min)) ; Make space for sexp.
4959 (setq todo-categories (todo-make-categories-list t)))
4960 (delete-region (line-beginning-position) (line-end-position)))
4961 (prin1 todo-categories (current-buffer))))))
4963 (defun todo-make-categories-list (&optional force)
4964 "Return an alist of todo categories and their item counts.
4965 With non-nil argument FORCE parse the entire file to build the
4966 list; otherwise, get the value by reading the sexp at the top of
4968 (setq todo-categories nil)
4972 (goto-char (point-min))
4973 (let (counts cat archive)
4974 ;; If the file is a todo file and has archived items, identify the
4975 ;; archive, in order to count its items. But skip this with
4976 ;; `todo-convert-legacy-files', since that converts filed items to
4978 (when buffer-file-name ; During conversion there is no file yet.
4979 ;; If the file is an archive, it doesn't have an archive.
4980 (unless (member (file-truename buffer-file-name)
4981 (funcall todo-files-function t))
4982 (setq archive (concat (file-name-sans-extension
4983 todo-current-todo-file) ".toda"))))
4985 (cond ((looking-at (concat (regexp-quote todo-category-beg)
4987 (setq cat (match-string-no-properties 1))
4988 ;; Counts for each category: [todo diary done archive]
4989 (setq counts (make-vector 4 0))
4990 (setq todo-categories
4991 (append todo-categories (list (cons cat counts))))
4992 ;; Add archived item count to the todo file item counts.
4993 ;; Make sure to include newly created archives, e.g. due to
4994 ;; todo-move-category.
4995 (when (member archive (funcall todo-files-function t))
4996 (let ((archive-count 0))
4997 (with-current-buffer (find-file-noselect archive)
4999 (goto-char (point-min))
5000 (when (re-search-forward
5001 (concat "^" (regexp-quote todo-category-beg)
5005 (while (not (or (looking-at
5007 (regexp-quote todo-category-beg)
5010 (when (looking-at todo-done-string-start)
5011 (setq archive-count (1+ archive-count)))
5013 (todo-update-count 'archived archive-count cat))))
5014 ((looking-at todo-done-string-start)
5015 (todo-update-count 'done 1 cat))
5016 ((looking-at (concat "^\\("
5017 (regexp-quote diary-nonmarking-symbol)
5018 "\\)?" todo-date-pattern))
5019 (todo-update-count 'diary 1 cat)
5020 (todo-update-count 'todo 1 cat))
5021 ((looking-at (concat todo-date-string-start todo-date-pattern))
5022 (todo-update-count 'todo 1 cat))
5023 ;; If first line is todo-categories list, use it and end loop
5024 ;; -- unless FORCEd to scan whole file.
5027 (setq todo-categories (read (buffer-substring-no-properties
5028 (line-beginning-position)
5029 (line-end-position))))
5030 (goto-char (1- (point-max))))))
5034 (defun todo-repair-categories-sexp ()
5035 "Repair corrupt todo file categories sexp.
5036 This should only be needed as a consequence of careless manual
5037 editing or a bug in todo.el.
5039 *Warning*: Calling this command restores the category order to
5040 the list element order in the todo file categories sexp, so any
5041 order changes made in Todo Categories mode will have to be made
5044 (let ((todo-categories (todo-make-categories-list t)))
5045 (todo-update-categories-sexp)))
5047 (defun todo-check-format ()
5048 "Signal an error if the current todo file is ill-formatted.
5049 Otherwise return t. Display a message if the file is well-formed
5050 but the categories sexp differs from the current value of
5055 (goto-char (point-min))
5056 (let* ((cats (prin1-to-string todo-categories))
5057 (ssexp (buffer-substring-no-properties (line-beginning-position)
5058 (line-end-position)))
5059 (sexp (read ssexp)))
5060 ;; Check the first line for `todo-categories' sexp.
5063 (unless (and (stringp (car c))
5066 (user-error "Invalid or missing todo-categories sexp"))))
5068 ;; Check well-formedness of categories.
5069 (let ((legit (concat
5070 "\\(^" (regexp-quote todo-category-beg) "\\)"
5071 "\\|\\(" todo-date-string-start todo-date-pattern "\\)"
5072 "\\|\\(^[ \t]+[^ \t]*\\)"
5074 "\\|\\(^" (regexp-quote todo-category-done) "\\)"
5075 "\\|\\(" todo-done-string-start "\\)")))
5077 (unless (looking-at legit)
5078 (user-error "Illegitimate todo file format at line %d"
5079 (line-number-at-pos (point))))
5081 ;; Warn user if categories sexp has changed.
5082 (unless (string= ssexp cats)
5083 (message (concat "The sexp at the beginning of the file differs "
5084 "from the value of `todo-categories.\n"
5085 "If the sexp is wrong, you can fix it with "
5086 "M-x todo-repair-categories-sexp,\n"
5087 "but note this reverts any changes you have "
5088 "made in the order of the categories."))))))
5091 (defun todo-item-start ()
5092 "Move to start of current todo item and return its position."
5094 ;; Buffer is empty (invocation possible e.g. via todo-forward-item
5095 ;; from todo-filter-items when processing category with no todo
5097 (eq (point-min) (point-max))
5098 ;; Point is on the empty line below category's last todo item...
5099 (and (looking-at "^$")
5100 (or (eobp) ; ...and done items are hidden...
5101 (save-excursion ; ...or done items are visible.
5103 (looking-at (concat "^"
5104 (regexp-quote todo-category-done))))))
5105 ;; Buffer is widened.
5106 (looking-at (regexp-quote todo-category-beg)))
5107 (goto-char (line-beginning-position))
5108 (while (not (looking-at todo-item-start))
5112 (defun todo-item-end ()
5113 "Move to end of current todo item and return its position."
5114 ;; Items cannot end with a blank line.
5115 (unless (looking-at "^$")
5116 (let* ((done (todo-done-item-p))
5118 ;; For todo items, end is before the done items section, for done
5119 ;; items, end is before the next category. If these limits are
5120 ;; missing or inaccessible, end it before the end of the buffer.
5121 (lim (if (save-excursion
5123 (concat "^" (regexp-quote (if done
5125 todo-category-done)))
5127 (progn (setq to-lim t) (match-beginning 0))
5129 (when (bolp) (forward-char)) ; Find start of next item.
5130 (goto-char (if (re-search-forward todo-item-start lim t)
5132 (if to-lim lim (point-max))))
5133 ;; For last todo item, skip back over the empty line before the done
5134 ;; items section, else just back to the end of the previous line.
5135 (backward-char (when (and to-lim (not done) (eq (point) lim)) 2))
5138 (defun todo-item-string ()
5139 "Return bare text of current item as a string."
5140 (let ((opoint (point))
5141 (start (todo-item-start))
5142 (end (todo-item-end)))
5144 (and start end (buffer-substring-no-properties start end))))
5146 (defun todo-forward-item (&optional count)
5147 "Move point COUNT items down (by default, move down by one item)."
5148 (let* ((not-done (not (or (todo-done-item-p) (looking-at "^$"))))
5149 (start (line-end-position)))
5151 (if (re-search-forward todo-item-start nil t (or count 1))
5152 (goto-char (match-beginning 0))
5153 (goto-char (point-max)))
5154 ;; If points advances by one from a todo to a done item, go back
5155 ;; to the space above todo-done-separator, since that is a
5156 ;; legitimate place to insert an item. But skip this space if
5157 ;; count > 1, since that should only stop on an item.
5158 (when (and not-done (todo-done-item-p) (not count))
5159 ;; (if (or (not count) (= count 1))
5160 (re-search-backward "^$" start t))));)
5161 ;; The preceding sexp is insufficient when buffer is not narrowed,
5162 ;; since there could be no done items in this category, so the
5163 ;; search puts us on first todo item of next category. Does this
5164 ;; ever happen? If so:
5165 ;; (let ((opoint) (point))
5166 ;; (forward-line -1)
5167 ;; (when (or (not count) (= count 1))
5168 ;; (cond ((looking-at (concat "^" (regexp-quote todo-category-beg)))
5169 ;; (forward-line -2))
5170 ;; ((looking-at (concat "^" (regexp-quote todo-category-done)))
5171 ;; (forward-line -1))
5173 ;; (goto-char opoint)))))))
5175 (defun todo-backward-item (&optional count)
5176 "Move point up to start of item with next higher priority.
5177 With positive numerical prefix COUNT, move point COUNT items
5180 If the category's done items are visible, this command called
5181 with a prefix argument only moves point to a higher item, e.g.,
5182 with point on the first done item and called with prefix 1, it
5183 moves to the last todo item; but if called with point on the
5184 first done item without a prefix argument, it moves point the the
5185 empty line above the done items separator."
5186 (let* ((done (todo-done-item-p)))
5189 (re-search-backward todo-item-start nil t (or count 1)))
5190 ;; Unless this is a regexp filtered items buffer (which can contain
5191 ;; intermixed todo and done items), if points advances by one from a
5192 ;; done to a todo item, go back to the space above
5193 ;; todo-done-separator, since that is a legitimate place to insert an
5194 ;; item. But skip this space if count > 1, since that should only
5196 (when (and done (not (todo-done-item-p)) (not count)
5197 ;(or (not count) (= count 1))
5198 (not (equal (buffer-name) todo-regexp-items-buffer)))
5199 (re-search-forward (concat "^" (regexp-quote todo-category-done))
5201 (forward-line -1))))
5203 (defun todo-remove-item ()
5204 "Internal function called in editing, deleting or moving items."
5205 (let* ((end (progn (todo-item-end) (1+ (point))))
5206 (beg (todo-item-start))
5207 (ov (todo-get-overlay 'prefix)))
5208 (when ov (delete-overlay ov))
5209 (delete-region beg end)))
5211 (defun todo-diary-item-p ()
5212 "Return non-nil if item at point has diary entry format."
5214 (when (todo-item-string) ; Exclude empty lines.
5216 (not (looking-at (regexp-quote todo-nondiary-start))))))
5218 ;; This duplicates the item locating code from diary-goto-entry, but
5219 ;; without the marker code, to test whether the latter is dispensable.
5220 ;; If it is, diary-goto-entry can be simplified. The code duplication
5221 ;; here can also be eliminated, leaving only the widening and category
5222 ;; selection, and instead of :override advice :around can be used.
5224 (defun todo-diary-goto-entry (button)
5225 "Jump to the diary entry for the BUTTON at point.
5226 If the entry is a todo item, display its category properly.
5227 Overrides `diary-goto-entry'."
5228 ;; Locate the diary item in its source file.
5229 (let* ((locator (button-get button 'locator))
5230 (file (cadr locator))
5231 (date (regexp-quote (nth 2 locator)))
5232 (content (regexp-quote (nth 3 locator))))
5233 (if (not (and (file-exists-p file)
5234 (find-file-other-window file)))
5235 (message "Unable to locate this diary entry")
5236 (when (eq major-mode 'todo-mode) (widen))
5237 (goto-char (point-min))
5238 (when (re-search-forward (format "%s.*\\(%s\\)" date content) nil t)
5239 (goto-char (match-beginning 1)))
5240 ;; If it's a todo item, determine its category and display the
5241 ;; category properly.
5242 (when (eq major-mode 'todo-mode)
5243 (let ((opoint (point)))
5244 (re-search-backward (concat "^" (regexp-quote todo-category-beg)
5245 "\\(.*\\)\n") nil t)
5246 (todo-category-number (match-string 1))
5247 (todo-category-select)
5248 (goto-char opoint))))))
5250 (add-function :override diary-goto-entry-function #'todo-diary-goto-entry)
5252 (defun todo-done-item-p ()
5253 "Return non-nil if item at point is a done item."
5256 (looking-at todo-done-string-start)))
5258 (defun todo-done-item-section-p ()
5259 "Return non-nil if point is in category's done items section."
5261 (or (re-search-backward (concat "^" (regexp-quote todo-category-done))
5263 (progn (goto-char (point-min))
5264 (looking-at todo-done-string-start)))))
5266 (defun todo-reset-done-separator (sep)
5267 "Replace existing overlays of done items separator string SEP."
5271 (goto-char (point-min))
5272 (while (re-search-forward
5273 (concat "\n\\(" (regexp-quote todo-category-done) "\\)") nil t)
5274 (let* ((beg (match-beginning 1))
5276 (ov (progn (goto-char beg)
5277 (todo-get-overlay 'separator)))
5278 (old-sep (when ov (overlay-get ov 'display)))
5281 (unless (string= old-sep sep)
5282 (setq new-ov (make-overlay beg end))
5283 (overlay-put new-ov 'todo 'separator)
5284 (overlay-put new-ov 'display todo-done-separator)
5285 (delete-overlay ov))))))))
5287 (defun todo-get-overlay (val)
5288 "Return the overlay at point whose `todo' property has value VAL."
5289 ;; Use overlays-in to find prefix overlays and check over two
5290 ;; positions to find done separator overlay.
5291 (let ((ovs (overlays-in (point) (1+ (point))))
5296 (when (eq (overlay-get ov 'todo) val)
5297 (throw 'done ov))))))
5299 (defun todo-marked-item-p ()
5300 "Non-nil if this item begins with `todo-item-mark'.
5301 In that case, return the item's prefix overlay."
5302 (let* ((ov (todo-get-overlay 'prefix))
5303 ;; If an item insertion command is called on a todo file
5304 ;; before it is visited, it has no prefix overlays yet, so
5306 (pref (when ov (overlay-get ov 'before-string)))
5308 (string-match (concat "^" (regexp-quote todo-item-mark))
5312 (defun todo-insert-with-overlays (item)
5313 "Insert ITEM at point and update prefix/priority number overlays."
5315 ;; Insertion pushes item down but not its prefix overlay. When the
5316 ;; overlay includes a mark, this would now mark the inserted ITEM,
5317 ;; so move it to the pushed down item.
5318 (let ((ov (todo-get-overlay 'prefix))
5319 (marked (todo-marked-item-p)))
5321 (when marked (move-overlay ov (point) (point))))
5322 (todo-backward-item)
5323 (todo-prefix-overlays))
5325 (defun todo-prefix-overlays ()
5326 "Update the prefix overlays of the current category's items.
5327 The overlay's value is the string `todo-prefix' or with non-nil
5328 `todo-number-prefix' an integer in the sequence from 1 to
5329 the number of todo or done items in the category indicating the
5330 item's priority. Todo and done items are numbered independently
5333 (cat-tp (or (cdr (assoc-string
5334 (todo-current-category)
5335 (nth 2 (assoc-string todo-current-todo-file
5336 todo-top-priorities-overrides))))
5337 todo-top-priorities))
5340 (goto-char (point-min))
5342 (when (or (todo-date-string-matcher (line-end-position))
5343 (todo-done-string-matcher (line-end-position)))
5344 (goto-char (match-beginning 0))
5346 ;; Reset number to 1 for first done item.
5347 (when (and (eq major-mode 'todo-mode)
5348 (looking-at todo-done-string-start)
5349 (looking-back (concat "^"
5350 (regexp-quote todo-category-done)
5354 (setq prefix (concat (propertize
5355 (if todo-number-prefix
5356 (number-to-string num)
5359 ;; Prefix of top priority items has a
5360 ;; distinct face in Todo mode.
5361 (if (and (eq major-mode 'todo-mode)
5365 'todo-prefix-string))
5367 (let ((ov (todo-get-overlay 'prefix))
5368 (marked (todo-marked-item-p)))
5369 ;; Prefix overlay must be at a single position so its
5370 ;; bounds aren't changed when (re)moving an item.
5371 (unless ov (setq ov (make-overlay (point) (point))))
5372 (overlay-put ov 'todo 'prefix)
5373 (overlay-put ov 'before-string (if marked
5374 (concat todo-item-mark prefix)
5378 ;; -----------------------------------------------------------------------------
5379 ;;; Utilities for generating item insertion commands and key bindings
5380 ;; -----------------------------------------------------------------------------
5382 ;; Wolfgang Jenkner posted this powerset definition to emacs-devel
5383 ;; (http://lists.gnu.org/archive/html/emacs-devel/2013-06/msg00423.html)
5384 ;; and kindly gave me permission to use it.
5386 (defun todo-powerset (list)
5387 "Return the powerset of LIST."
5388 (let ((powerset (list nil)))
5389 (dolist (elt list (mapcar 'reverse powerset))
5390 (nconc powerset (mapcar (apply-partially 'cons elt) powerset)))))
5392 (defun todo-gen-arglists (arglist)
5393 "Return list of lists of non-nil atoms produced from ARGLIST.
5394 The elements of ARGLIST may be atoms or lists."
5397 (let ((arg (pop arglist)))
5398 (cond ((symbolp arg)
5399 (setq arglists (if arglists
5400 (mapcar (lambda (l) (push arg l)) arglists)
5401 (list (push arg arglists)))))
5405 (if (= 1 (length arglists))
5406 (apply (lambda (l) (push a l)) arglists)
5407 (mapcar (lambda (l) (push a l)) arglists)))
5409 (setq arglists (mapcar 'reverse (apply 'append (mapc 'car arglists))))))
5411 (defvar todo-insertion-commands-args-genlist
5412 '(diary nonmarking (calendar date dayname) time (here region))
5413 "Generator list for argument lists of item insertion commands.")
5415 (defvar todo-insertion-commands-args
5416 (let ((arglist (todo-gen-arglists todo-insertion-commands-args-genlist))
5418 (setq res (cl-remove-duplicates
5419 (apply 'append (mapcar 'todo-powerset arglist)) :test 'equal))
5421 (unless (= 5 (length l))
5422 (let ((v (make-vector 5 nil)) elt)
5425 (cond ((eq elt 'diary)
5427 ((eq elt 'nonmarking)
5429 ((or (eq elt 'calendar)
5438 (setq l (append v nil))))
5439 (setq new (append new (list l))))
5441 "List of all argument lists for Todo mode item insertion commands.")
5443 (defun todo-insertion-command-name (arglist)
5444 "Generate Todo mode item insertion command name from ARGLIST."
5445 (replace-regexp-in-string
5447 (replace-regexp-in-string
5449 (concat "todo-insert-item-"
5450 (mapconcat (lambda (e) (if e (symbol-name e))) arglist "-")))))
5452 (defvar todo-insertion-commands-names
5454 (todo-insertion-command-name l))
5455 todo-insertion-commands-args)
5456 "List of names of Todo mode item insertion commands.")
5458 (defmacro todo-define-insertion-command (&rest args)
5459 "Generate Todo mode item insertion command definitions from ARGS."
5460 (let ((name (intern (todo-insertion-command-name args)))
5465 (arg4 (nth 4 args)))
5466 `(defun ,name (&optional arg &rest args)
5467 "Todo mode item insertion command generated from ARGS.
5468 For descriptions of the individual arguments, their values, and
5469 their relation to key bindings, see `todo-basic-insert-item'."
5470 (interactive (list current-prefix-arg))
5471 (todo-basic-insert-item arg ',arg0 ',arg1 ',arg2 ',arg3 ',arg4))))
5473 (defvar todo-insertion-commands
5475 (eval `(todo-define-insertion-command ,@c)))
5476 todo-insertion-commands-args)
5477 "List of Todo mode item insertion commands.")
5479 (defvar todo-insertion-commands-arg-key-list
5480 '(("diary" "y" "yy")
5481 ("nonmarking" "k" "kk")
5482 ("calendar" "c" "cc")
5484 ("dayname" "n" "nn")
5488 "List of mappings of item insertion command arguments to key sequences.")
5490 (defun todo-insertion-key-bindings (map)
5491 "Generate key binding definitions for item insertion keymap MAP."
5492 (dolist (c todo-insertion-commands)
5494 (cname (symbol-name c)))
5496 (let ((arg (nth 0 l))
5499 (if (string-match (concat (regexp-quote arg) "\\_>") cname)
5500 (setq key (concat key key2)))
5501 (if (string-match (concat (regexp-quote arg) ".+") cname)
5502 (setq key (concat key key1)))))
5503 todo-insertion-commands-arg-key-list)
5504 (if (string-match (concat (regexp-quote "todo-insert-item") "\\_>") cname)
5505 (setq key (concat key "i")))
5506 (define-key map key c))))
5508 ;; -----------------------------------------------------------------------------
5509 ;;; Todo minibuffer utilities
5510 ;; -----------------------------------------------------------------------------
5512 (defcustom todo-y-with-space nil
5513 "Non-nil means allow SPC to affirm a \"y or n\" question."
5517 (defun todo-y-or-n-p (prompt)
5518 "Ask \"y or n\" question PROMPT and return t if answer is \"y\".
5519 Also return t if answer is \"Y\", but unlike `y-or-n-p', allow
5520 SPC to affirm the question only if option `todo-y-with-space' is
5522 (unless todo-y-with-space
5523 (define-key query-replace-map " " 'ignore))
5526 (define-key query-replace-map " " 'act)))
5528 (defun todo-category-completions (&optional archive)
5529 "Return a list of completions for `todo-read-category'.
5530 Each element of the list is a cons of a category name and the
5531 file or list of files (as short file names) it is in. The files
5532 are either the current (or if there is none, the default) todo
5533 file plus the files listed in `todo-category-completions-files',
5534 or, with non-nil ARCHIVE, the current archive file.
5536 Before calculating the completions, update the value of
5537 `todo-category-completions-files' in case any files named in it
5540 (dolist (f todo-category-completions-files)
5541 (unless (file-exists-p (todo-absolute-file-name f))
5542 (setq todo-category-completions-files
5543 (delete f todo-category-completions-files))
5546 (let ((pl (> (length deleted) 1))
5547 (names (mapconcat (lambda (f) (concat "\"" f "\"")) deleted ", ")))
5548 (message (concat "File" (if pl "s" "") " " names " ha" (if pl "ve" "s")
5549 " been deleted and removed from\n"
5550 "the list of category completion files")))
5551 (todo-reevaluate-category-completions-files-defcustom)
5552 (custom-set-default 'todo-category-completions-files
5553 (symbol-value 'todo-category-completions-files))
5555 (let* ((curfile (or todo-current-todo-file
5556 (and todo-show-current-file
5557 todo-global-current-todo-file)
5558 (todo-absolute-file-name todo-default-todo-file)))
5559 (files (or (unless archive
5560 (mapcar 'todo-absolute-file-name
5561 todo-category-completions-files))
5564 ;; If file was just added, it has no category completions.
5565 (unless (zerop (buffer-size (find-buffer-visiting curfile)))
5566 (unless (member curfile todo-archives)
5567 (add-to-list 'files curfile))
5568 (dolist (f files listall)
5569 (with-current-buffer (find-file-noselect f 'nowarn)
5570 ;; Ensure category is properly displayed in case user
5571 ;; switches to file via a non-Todo mode command. And if
5572 ;; done items in category are visible, keep them visible.
5573 (let ((done todo-show-with-done))
5574 (when (> (buffer-size) (- (point-max) (point-min)))
5576 (goto-char (point-min))
5577 (setq done (re-search-forward todo-done-string-start nil t))))
5578 (let ((todo-show-with-done done))
5579 (save-excursion (todo-category-select))))
5583 (goto-char (point-min))
5584 (setq listf (read (buffer-substring-no-properties
5585 (line-beginning-position)
5586 (line-end-position)))))))
5587 (mapc (lambda (elt) (let* ((cat (car elt))
5588 (la-elt (assoc cat listall)))
5590 (setcdr la-elt (append (list (cdr la-elt))
5592 (push (cons cat f) listall))))
5595 (defun todo-read-file-name (prompt &optional archive mustmatch)
5596 "Choose and return the name of a todo file, prompting with PROMPT.
5598 Show completions with TAB or SPC; the names are shown in short
5599 form but the absolute truename is returned. With non-nil ARCHIVE
5600 return the absolute truename of a todo archive file. With non-nil
5601 MUSTMATCH the name of an existing file must be chosen;
5602 otherwise, a new file name is allowed."
5603 (let* ((completion-ignore-case todo-completion-ignore-case)
5604 (files (mapcar 'todo-short-file-name
5605 ;; (funcall todo-files-function archive)))
5606 (if archive todo-archives todo-files)))
5607 (file (completing-read prompt files nil mustmatch nil nil
5609 ;; If user hit RET without
5610 ;; choosing a file, default to
5611 ;; current or default file.
5612 (todo-short-file-name
5613 (or todo-current-todo-file
5614 (and todo-show-current-file
5615 todo-global-current-todo-file)
5616 (todo-absolute-file-name
5617 todo-default-todo-file)))
5618 ;; Trigger prompt for initial file.
5620 (unless (file-exists-p todo-directory)
5621 (make-directory todo-directory))
5623 (setq file (todo-validate-name file 'file)))
5624 (setq file (file-truename (concat todo-directory file
5625 (if archive ".toda" ".todo"))))))
5627 (defun todo-read-category (prompt &optional match-type file)
5628 "Choose and return a category name, prompting with PROMPT.
5629 Show completions for existing categories with TAB or SPC.
5631 The argument MATCH-TYPE specifies the matching requirements on
5632 the category name: with the value `todo' or `archive' the name
5633 must complete to that of an existing todo or archive category,
5634 respectively; with the value `add' the name must not be that of
5635 an existing category; with all other values both existing and new
5636 valid category names are accepted.
5638 With non-nil argument FILE prompt for a file and complete only
5639 against categories in that file; otherwise complete against all
5640 categories from `todo-category-completions-files'."
5641 ;; Allow SPC to insert spaces, for adding new category names.
5642 (let ((map minibuffer-local-completion-map))
5643 (define-key map " " nil)
5644 (let* ((add (eq match-type 'add))
5645 (archive (eq match-type 'archive))
5646 (file0 (when (and file (> (length todo-files) 1))
5647 (todo-read-file-name (concat "Choose a" (if archive
5650 " file: ") archive t)))
5651 (completions (unless file0 (todo-category-completions archive)))
5652 (categories (cond (file0
5653 (with-current-buffer
5654 (find-file-noselect file0 'nowarn)
5655 (let ((todo-current-todo-file file0))
5657 ((and add (not file))
5658 (with-current-buffer
5659 (find-file-noselect todo-current-todo-file)
5663 (completion-ignore-case todo-completion-ignore-case)
5664 (cat (completing-read prompt categories nil
5665 (eq match-type 'todo) nil nil
5666 ;; Unless we're adding a category via
5667 ;; todo-add-category, set default
5668 ;; for existing categories to the
5669 ;; current category of the chosen
5670 ;; file or else of the current file.
5671 (if (and categories (not add))
5672 (with-current-buffer
5675 todo-current-todo-file
5676 (todo-absolute-file-name
5677 todo-default-todo-file)))
5678 (todo-current-category))
5679 ;; Trigger prompt for initial category.
5681 (catfil (cdr (assoc cat completions)))
5682 (str "Category \"%s\" from which file (TAB for choices)? "))
5683 ;; If we do category completion and the chosen category name
5684 ;; occurs in more than one file, prompt to choose one file.
5685 (unless (or file0 add (not catfil))
5686 (setq file0 (file-truename
5689 (todo-absolute-file-name
5690 (let ((files (mapcar 'todo-short-file-name catfil)))
5691 (completing-read (format str cat) files)))))))
5692 ;; Default to the current file.
5693 (unless file0 (setq file0 todo-current-todo-file))
5694 ;; First validate only a name passed interactively from
5695 ;; todo-add-category, which must be of a nonexistent category.
5696 (unless (and (assoc cat categories) (not add))
5697 ;; Validate only against completion categories.
5698 (let ((todo-categories categories))
5699 (setq cat (todo-validate-name cat 'category)))
5700 ;; When user enters a nonexistent category name by jumping or
5701 ;; moving, confirm that it should be added, then validate.
5703 (if (todo-y-or-n-p (format "Add new category \"%s\" to file \"%s\"? "
5704 cat (todo-short-file-name file0)))
5706 (when (assoc cat categories)
5707 (let ((todo-categories categories))
5708 (setq cat (todo-validate-name cat 'category))))
5709 ;; Restore point and narrowing after adding new
5710 ;; category, to avoid moving to beginning of file when
5711 ;; moving marked items to a new category
5712 ;; (todo-move-item).
5715 (todo-add-category file0 cat))))
5716 ;; If we decide not to add a category, exit without returning.
5720 (defun todo-validate-name (name type)
5721 "Prompt for new NAME for TYPE until it is valid, then return it.
5722 TYPE can be either of the symbols `file' or `category'."
5723 (let ((categories todo-categories)
5724 (files (mapcar 'todo-short-file-name todo-files))
5728 (cond ((string= "" name)
5730 (cond ((eq type 'file)
5732 "Enter a non-empty file name: "
5733 ;; Empty string passed by todo-show to
5734 ;; prompt for initial todo file.
5735 (concat "Initial file name ["
5736 todo-initial-file "]: ")))
5737 ((eq type 'category)
5739 "Enter a non-empty category name: "
5740 ;; Empty string passed by todo-show to
5741 ;; prompt for initial category of a new
5743 (concat "Initial category name ["
5744 todo-initial-category "]: "))))))
5745 ((string-match "\\`\\s-+\\'" name)
5747 "Enter a name that does not contain only white space: "))
5748 ((and (eq type 'file) (member name files))
5749 (setq prompt "Enter a non-existing file name: "))
5750 ((and (eq type 'category) (assoc name categories))
5751 (setq prompt "Enter a non-existing category name: ")))
5752 (setq name (if (or (and (eq type 'file) files)
5753 (and (eq type 'category) categories))
5754 (completing-read prompt (cond ((eq type 'file)
5756 ((eq type 'category)
5758 ;; Offer default initial name.
5759 (completing-read prompt (if (eq type 'file)
5762 nil nil (if (eq type 'file)
5764 todo-initial-category))))))
5767 ;; Adapted from calendar-read-date and calendar-date-string.
5768 (defun todo-read-date (&optional arg mo yr)
5769 "Prompt for Gregorian date and return it in the current format.
5771 With non-nil ARG, prompt for and return only the date component
5772 specified by ARG, which can be one of these symbols:
5773 `month' (prompt for name, return name or number according to
5774 value of `calendar-date-display-form'), `day' of month, or
5775 `year'. The value of each of these components can be `*',
5776 indicating an unspecified month, day, or year.
5778 When ARG is `day', non-nil arguments MO and YR determine the
5779 number of the last the day of the month."
5780 (let (year monthname month day
5781 dayname) ; Needed by calendar-date-display-form.
5782 (when (or (not arg) (eq arg 'year))
5783 (while (if (natnump year) (< year 1) (not (eq year '*)))
5784 (setq year (read-from-minibuffer
5785 "Year (>0 or RET for this year or * for any year): "
5786 nil nil t nil (number-to-string
5787 (calendar-extract-year
5788 (calendar-current-date)))))))
5789 (when (or (not arg) (eq arg 'month))
5790 (let* ((marray todo-month-name-array)
5791 (mlist (append marray nil))
5792 (mabarray todo-month-abbrev-array)
5793 (mablist (append mabarray nil))
5794 (completion-ignore-case todo-completion-ignore-case))
5795 (setq monthname (completing-read
5796 "Month name (RET for current month, * for any month): "
5798 (calendar-month-name (calendar-extract-month
5799 (calendar-current-date)) t))
5800 month (1+ (- (length mlist)
5801 (length (or (member monthname mlist)
5802 (member monthname mablist))))))
5803 (setq monthname (aref mabarray (1- month)))))
5804 (when (or (not arg) (eq arg 'day))
5805 (let ((last (let ((mm (or month mo))
5807 ;; If month is unspecified, use a month with 31
5808 ;; days for checking day of month input. Does
5809 ;; Calendar do anything special when * is
5810 ;; currently a shorter month?
5811 (if (= mm 13) (setq mm 1))
5812 ;; If year is unspecified, use a leap year to
5814 (if (eq year '*) (setq yy 2012))
5815 (calendar-last-day-of-month mm yy))))
5816 (while (if (natnump day) (or (< day 1) (> day last)) (not (eq day '*)))
5817 (setq day (read-from-minibuffer
5818 (format "Day (1-%d or RET for today or * for any day): "
5820 nil nil t nil (number-to-string
5821 (calendar-extract-day
5822 (calendar-current-date))))))))
5823 ;; Stringify read values (monthname is already a string).
5824 (and year (setq year (if (eq year '*)
5826 (number-to-string year))))
5827 (and day (setq day (if (eq day '*)
5829 (number-to-string day))))
5830 (and month (setq month (if (eq month '*)
5832 (number-to-string month))))
5834 (cond ((eq arg 'year) year)
5837 (if (memq 'month calendar-date-display-form)
5840 (mapconcat 'eval calendar-date-display-form ""))))
5842 (defun todo-read-dayname ()
5843 "Choose name of a day of the week with completion and return it."
5844 (let ((completion-ignore-case todo-completion-ignore-case))
5845 (completing-read "Enter a day name: "
5846 (append calendar-day-name-array nil)
5849 (defun todo-read-time ()
5850 "Prompt for and return a valid clock time as a string.
5852 Valid time strings are those matching `diary-time-regexp'.
5853 Typing `<return>' at the prompt returns the current time, if the
5854 user option `todo-always-add-time-string' is non-nil, otherwise
5855 the empty string (i.e., no time string)."
5858 (setq answer (read-string "Enter a clock time: " nil nil
5859 (when todo-always-add-time-string
5860 (substring (current-time-string) 11 16))))
5861 (when (or (string= "" answer)
5862 (string-match diary-time-regexp answer))
5866 ;; -----------------------------------------------------------------------------
5867 ;;; Customization groups and utilities
5868 ;; -----------------------------------------------------------------------------
5871 "Create and maintain categorized lists of todo items."
5872 :link '(emacs-commentary-link "todo")
5876 (defgroup todo-edit nil
5877 "User options for adding and editing todo items."
5881 (defgroup todo-categories nil
5882 "User options for Todo Categories mode."
5886 (defgroup todo-filtered nil
5887 "User options for Todo Filter Items mode."
5891 (defgroup todo-display nil
5892 "User display options for Todo mode."
5896 (defgroup todo-faces nil
5897 "Faces for the Todo modes."
5901 (defun todo-set-show-current-file (symbol value)
5902 "The :set function for user option `todo-show-current-file'."
5903 (custom-set-default symbol value)
5905 (add-hook 'pre-command-hook 'todo-show-current-file nil t)
5906 (remove-hook 'pre-command-hook 'todo-show-current-file t)))
5908 (defun todo-reset-prefix (symbol value)
5909 "The :set function for `todo-prefix' and `todo-number-prefix'."
5910 (let ((oldvalue (symbol-value symbol))
5911 (files todo-file-buffers))
5912 (custom-set-default symbol value)
5913 (when (not (equal value oldvalue))
5915 (with-current-buffer (find-file-noselect f)
5916 ;; Activate the new setting in the current category.
5917 (save-excursion (todo-category-select)))))))
5919 (defun todo-reset-nondiary-marker (symbol value)
5920 "The :set function for user option `todo-nondiary-marker'."
5921 (let ((oldvalue (symbol-value symbol))
5922 (files (append todo-files todo-archives)))
5923 (custom-set-default symbol value)
5924 ;; Need to reset these to get font-locking right.
5925 (setq todo-nondiary-start (nth 0 todo-nondiary-marker)
5926 todo-nondiary-end (nth 1 todo-nondiary-marker)
5927 todo-date-string-start
5928 ;; See comment in defvar of `todo-date-string-start'.
5929 (concat "^\\(" (regexp-quote todo-nondiary-start) "\\|"
5930 (regexp-quote diary-nonmarking-symbol) "\\)?"))
5931 (when (not (equal value oldvalue))
5933 (with-current-buffer (find-file-noselect f)
5934 (let (buffer-read-only)
5936 (goto-char (point-min))
5938 (if (re-search-forward
5939 (concat "^\\(" todo-done-string-start "[^][]+] \\)?"
5940 "\\(?1:" (regexp-quote (car oldvalue))
5941 "\\)" todo-date-pattern "\\( "
5942 diary-time-regexp "\\)?\\(?2:"
5943 (regexp-quote (cadr oldvalue)) "\\)")
5946 (replace-match (nth 0 value) t t nil 1)
5947 (replace-match (nth 1 value) t t nil 2))
5949 (todo-category-select)))))))
5951 (defun todo-reset-done-separator-string (symbol value)
5952 "The :set function for `todo-done-separator-string'."
5953 (let ((oldvalue (symbol-value symbol))
5954 (files todo-file-buffers)
5955 (sep todo-done-separator))
5956 (custom-set-default symbol value)
5957 (when (not (equal value oldvalue))
5959 (with-current-buffer (find-file-noselect f)
5960 (let (buffer-read-only)
5961 (setq todo-done-separator (todo-done-separator))
5962 (when (= 1 (length value))
5963 (todo-reset-done-separator sep)))
5964 (todo-category-select))))))
5966 (defun todo-reset-done-string (symbol value)
5967 "The :set function for user option `todo-done-string'."
5968 (let ((oldvalue (symbol-value symbol))
5969 (files (append todo-files todo-archives)))
5970 (custom-set-default symbol value)
5971 ;; Need to reset this to get font-locking right.
5972 (setq todo-done-string-start
5973 (concat "^\\[" (regexp-quote todo-done-string)))
5974 (when (not (equal value oldvalue))
5976 (with-current-buffer (find-file-noselect f)
5977 (let (buffer-read-only)
5979 (goto-char (point-min))
5981 (if (re-search-forward
5982 (concat "^" (regexp-quote todo-nondiary-start)
5983 "\\(" (regexp-quote oldvalue) "\\)")
5985 (replace-match value t t nil 1)
5987 (todo-category-select)))))))
5989 (defun todo-reset-comment-string (symbol value)
5990 "The :set function for user option `todo-comment-string'."
5991 (let ((oldvalue (symbol-value symbol))
5992 (files (append todo-files todo-archives)))
5993 (custom-set-default symbol value)
5994 (when (not (equal value oldvalue))
5996 (with-current-buffer (find-file-noselect f)
5997 (let (buffer-read-only)
6000 (goto-char (point-min))
6002 (if (re-search-forward
6004 "\\[\\(" (regexp-quote oldvalue) "\\): [^]]*\\]")
6006 (replace-match value t t nil 1)
6008 (todo-category-select))))))))
6010 (defun todo-reset-highlight-item (symbol value)
6011 "The :set function for `todo-toggle-item-highlighting'."
6012 (let ((oldvalue (symbol-value symbol))
6013 (files (append todo-files todo-archives)))
6014 (custom-set-default symbol value)
6015 (when (not (equal value oldvalue))
6017 (let ((buf (find-buffer-visiting f)))
6019 (with-current-buffer buf
6023 (hl-line-mode -1)))))))))
6025 (defun todo-reevaluate-filelist-defcustoms ()
6026 "Reevaluate defcustoms that provide choice list of todo files."
6027 (custom-set-default 'todo-default-todo-file
6028 (symbol-value 'todo-default-todo-file))
6029 (todo-reevaluate-default-file-defcustom)
6030 (custom-set-default 'todo-filter-files (symbol-value 'todo-filter-files))
6031 (todo-reevaluate-filter-files-defcustom)
6032 (custom-set-default 'todo-category-completions-files
6033 (symbol-value 'todo-category-completions-files))
6034 (todo-reevaluate-category-completions-files-defcustom))
6036 (defun todo-reevaluate-default-file-defcustom ()
6037 "Reevaluate defcustom of `todo-default-todo-file'.
6038 Called after adding or deleting a todo file. If the value of
6039 `todo-default-todo-file' before calling this function was
6040 associated with an existing file, keep that value."
6041 ;; (let ((curval todo-default-todo-file))
6043 (defcustom todo-default-todo-file (todo-short-file-name
6044 (car (funcall todo-files-function)))
6045 "Todo file visited by first session invocation of `todo-show'."
6046 :type (when todo-files
6047 `(radio ,@(mapcar (lambda (f) (list 'const f))
6048 (mapcar 'todo-short-file-name
6049 (funcall todo-files-function)))))
6051 ;; (when (and curval (file-exists-p (todo-absolute-file-name curval)))
6052 ;; (custom-set-default 'todo-default-todo-file curval)
6053 ;; ;; (custom-reevaluate-setting 'todo-default-todo-file)
6057 (defun todo-reevaluate-category-completions-files-defcustom ()
6058 "Reevaluate defcustom of `todo-category-completions-files'.
6059 Called after adding or deleting a todo file."
6060 (eval (defcustom todo-category-completions-files nil
6061 "List of files for building `todo-read-category' completions."
6062 :type `(set ,@(mapcar (lambda (f) (list 'const f))
6063 (mapcar 'todo-short-file-name
6064 (funcall todo-files-function))))
6067 (defun todo-reevaluate-filter-files-defcustom ()
6068 "Reevaluate defcustom of `todo-filter-files'.
6069 Called after adding or deleting a todo file."
6070 (eval (defcustom todo-filter-files nil
6071 "List of files for multifile item filtering."
6072 :type `(set ,@(mapcar (lambda (f) (list 'const f))
6073 (mapcar 'todo-short-file-name
6074 (funcall todo-files-function))))
6077 ;; -----------------------------------------------------------------------------
6079 ;; -----------------------------------------------------------------------------
6081 (defun todo-nondiary-marker-matcher (lim)
6082 "Search for todo item nondiary markers within LIM for font-locking."
6083 (re-search-forward (concat "^\\(?1:" (regexp-quote todo-nondiary-start) "\\)"
6084 todo-date-pattern "\\(?: " diary-time-regexp
6085 "\\)?\\(?2:" (regexp-quote todo-nondiary-end) "\\)")
6088 (defun todo-diary-nonmarking-matcher (lim)
6089 "Search for diary nonmarking symbol within LIM for font-locking."
6090 (re-search-forward (concat "^\\(?1:" (regexp-quote diary-nonmarking-symbol)
6091 "\\)" todo-date-pattern) lim t))
6093 (defun todo-date-string-matcher (lim)
6094 "Search for todo item date string within LIM for font-locking."
6096 (concat todo-date-string-start "\\(?1:" todo-date-pattern "\\)") lim t))
6098 (defun todo-time-string-matcher (lim)
6099 "Search for todo item time string within LIM for font-locking."
6100 (re-search-forward (concat todo-date-string-start todo-date-pattern
6101 " \\(?1:" diary-time-regexp "\\)") lim t))
6103 (defun todo-diary-expired-matcher (lim)
6104 "Search for expired diary item date within LIM for font-locking."
6105 (when (re-search-forward (concat "^\\(?:"
6106 (regexp-quote diary-nonmarking-symbol)
6107 "\\)?\\(?1:" todo-date-pattern "\\) \\(?2:"
6108 diary-time-regexp "\\)?") lim t)
6109 (let* ((date (match-string-no-properties 1))
6110 (time (match-string-no-properties 2))
6111 ;; Function days-between requires a non-empty time string.
6112 (date-time (concat date " " (or time "00:00"))))
6113 (or (and (not (string-match ".+day\\|\\*" date))
6114 (< (days-between date-time (current-time-string)) 0))
6115 (todo-diary-expired-matcher lim)))))
6117 (defun todo-done-string-matcher (lim)
6118 "Search for done todo item header within LIM for font-locking."
6119 (re-search-forward (concat todo-done-string-start
6123 (defun todo-comment-string-matcher (lim)
6124 "Search for done todo item comment within LIM for font-locking."
6125 (re-search-forward (concat "\\[\\(?1:" todo-comment-string "\\):")
6128 (defun todo-category-string-matcher-1 (lim)
6129 "Search for todo category name within LIM for font-locking.
6130 This is for fontifying category and file names appearing in Todo
6131 Filtered Items mode following done items."
6132 (if (eq major-mode 'todo-filtered-items-mode)
6133 (re-search-forward (concat todo-done-string-start todo-date-pattern
6134 "\\(?: " diary-time-regexp
6135 ;; Use non-greedy operator to prevent
6136 ;; capturing possible following non-diary
6138 "\\)?] \\(?1:\\[.+?\\]\\)")
6141 (defun todo-category-string-matcher-2 (lim)
6142 "Search for todo category name within LIM for font-locking.
6143 This is for fontifying category and file names appearing in Todo
6144 Filtered Items mode following todo (not done) items."
6145 (if (eq major-mode 'todo-filtered-items-mode)
6146 (re-search-forward (concat todo-date-string-start todo-date-pattern
6147 "\\(?: " diary-time-regexp "\\)?\\(?:"
6148 (regexp-quote todo-nondiary-end)
6149 "\\)? \\(?1:\\[.+\\]\\)")
6152 (defvar todo-nondiary-face 'todo-nondiary)
6153 (defvar todo-date-face 'todo-date)
6154 (defvar todo-time-face 'todo-time)
6155 (defvar todo-diary-expired-face 'todo-diary-expired)
6156 (defvar todo-done-sep-face 'todo-done-sep)
6157 (defvar todo-done-face 'todo-done)
6158 (defvar todo-comment-face 'todo-comment)
6159 (defvar todo-category-string-face 'todo-category-string)
6160 (defvar todo-font-lock-keywords
6162 '(todo-nondiary-marker-matcher 1 todo-nondiary-face t)
6163 '(todo-nondiary-marker-matcher 2 todo-nondiary-face t)
6164 ;; diary-lib.el uses font-lock-constant-face for diary-nonmarking-symbol.
6165 '(todo-diary-nonmarking-matcher 1 font-lock-constant-face t)
6166 '(todo-date-string-matcher 1 todo-date-face t)
6167 '(todo-time-string-matcher 1 todo-time-face t)
6168 '(todo-done-string-matcher 0 todo-done-face t)
6169 '(todo-comment-string-matcher 1 todo-comment-face t)
6170 '(todo-category-string-matcher-1 1 todo-category-string-face t t)
6171 '(todo-category-string-matcher-2 1 todo-category-string-face t t)
6172 '(todo-diary-expired-matcher 1 todo-diary-expired-face t)
6173 '(todo-diary-expired-matcher 2 todo-diary-expired-face t t)
6175 "Font-locking for Todo modes.")
6177 ;; -----------------------------------------------------------------------------
6179 ;; -----------------------------------------------------------------------------
6181 (defvar todo-insertion-map
6182 (let ((map (make-keymap)))
6183 (todo-insertion-key-bindings map)
6184 (define-key map "p" 'todo-copy-item)
6186 "Keymap for Todo mode item insertion commands.")
6188 (defvar todo-key-bindings-t
6190 ("Af" todo-find-archive)
6191 ("Ac" todo-choose-archive)
6192 ("Ad" todo-archive-done-item)
6193 ("Cv" todo-toggle-view-done-items)
6194 ("v" todo-toggle-view-done-items)
6195 ("Ca" todo-add-category)
6196 ("Cr" todo-rename-category)
6197 ("Cg" todo-merge-category)
6198 ("Cm" todo-move-category)
6199 ("Ck" todo-delete-category)
6200 ("Cts" todo-set-top-priorities-in-category)
6201 ("Cey" todo-edit-category-diary-inclusion)
6202 ("Cek" todo-edit-category-diary-nonmarking)
6203 ("Fa" todo-add-file)
6204 ("Fr" todo-rename-file)
6205 ("Ff" todo-find-filtered-items-file)
6206 ("FV" todo-toggle-view-done-only)
6207 ("V" todo-toggle-view-done-only)
6208 ("Ftt" todo-filter-top-priorities)
6209 ("Ftm" todo-filter-top-priorities-multifile)
6210 ("Fts" todo-set-top-priorities-in-file)
6211 ("Fyy" todo-filter-diary-items)
6212 ("Fym" todo-filter-diary-items-multifile)
6213 ("Fxx" todo-filter-regexp-items)
6214 ("Fxm" todo-filter-regexp-items-multifile)
6215 ("ee" todo-edit-item)
6216 ("em" todo-edit-multiline-item)
6217 ("edt" todo-edit-item-header)
6218 ("edc" todo-edit-item-date-from-calendar)
6219 ("eda" todo-edit-item-date-to-today)
6220 ("edn" todo-edit-item-date-day-name)
6221 ("edy" todo-edit-item-date-year)
6222 ("edm" todo-edit-item-date-month)
6223 ("edd" todo-edit-item-date-day)
6224 ("et" todo-edit-item-time)
6225 ("eyy" todo-edit-item-diary-inclusion)
6226 ("eyk" todo-edit-item-diary-nonmarking)
6227 ("ec" todo-edit-done-item-comment)
6228 ("d" todo-item-done)
6229 ("i" ,todo-insertion-map)
6230 ("k" todo-delete-item)
6231 ("m" todo-move-item)
6232 ("u" todo-item-undone)
6233 ([remap newline] newline-and-indent)
6235 "List of key bindings for Todo mode only.")
6237 (defvar todo-key-bindings-t+a+f
6239 ("C*" todo-mark-category)
6240 ("Cu" todo-unmark-category)
6241 ("Fh" todo-toggle-item-header)
6242 ("h" todo-toggle-item-header)
6243 ("Fk" todo-delete-file)
6244 ("Fe" todo-edit-file)
6245 ("FH" todo-toggle-item-highlighting)
6246 ("H" todo-toggle-item-highlighting)
6247 ("FN" todo-toggle-prefix-numbers)
6248 ("N" todo-toggle-prefix-numbers)
6249 ("PB" todo-print-buffer)
6250 ("PF" todo-print-buffer-to-file)
6251 ("b" todo-backward-category)
6252 ("d" todo-item-done)
6253 ("f" todo-forward-category)
6254 ("j" todo-jump-to-category)
6255 ("n" todo-next-item)
6256 ("p" todo-previous-item)
6261 "List of key bindings for Todo, Archive, and Filtered Items modes.")
6263 (defvar todo-key-bindings-t+a
6265 ("Fc" todo-show-categories-table)
6267 ("X" todo-clear-matches)
6268 ("*" todo-toggle-mark-item)
6270 "List of key bindings for Todo and Todo Archive modes.")
6272 (defvar todo-key-bindings-t+f
6274 ("l" todo-lower-item-priority)
6275 ("r" todo-raise-item-priority)
6276 ("#" todo-set-item-priority)
6278 "List of key bindings for Todo and Todo Filtered Items modes.")
6280 (defvar todo-mode-map
6281 (let ((map (make-keymap)))
6282 ;; Don't suppress digit keys, so they can supply prefix arguments.
6283 (suppress-keymap map)
6284 (dolist (kb todo-key-bindings-t)
6285 (define-key map (nth 0 kb) (nth 1 kb)))
6286 (dolist (kb todo-key-bindings-t+a+f)
6287 (define-key map (nth 0 kb) (nth 1 kb)))
6288 (dolist (kb todo-key-bindings-t+a)
6289 (define-key map (nth 0 kb) (nth 1 kb)))
6290 (dolist (kb todo-key-bindings-t+f)
6291 (define-key map (nth 0 kb) (nth 1 kb)))
6293 "Todo mode keymap.")
6295 (defvar todo-archive-mode-map
6296 (let ((map (make-sparse-keymap)))
6297 (suppress-keymap map)
6298 (dolist (kb todo-key-bindings-t+a+f)
6299 (define-key map (nth 0 kb) (nth 1 kb)))
6300 (dolist (kb todo-key-bindings-t+a)
6301 (define-key map (nth 0 kb) (nth 1 kb)))
6302 (define-key map "a" 'todo-jump-to-archive-category)
6303 (define-key map "u" 'todo-unarchive-items)
6305 "Todo Archive mode keymap.")
6307 (defvar todo-edit-mode-map
6308 (let ((map (make-sparse-keymap)))
6309 (define-key map "\C-x\C-q" 'todo-edit-quit)
6310 (define-key map [remap newline] 'newline-and-indent)
6312 "Todo Edit mode keymap.")
6314 (defvar todo-categories-mode-map
6315 (let ((map (make-sparse-keymap)))
6316 (suppress-keymap map)
6317 (define-key map "c" 'todo-sort-categories-alphabetically-or-numerically)
6318 (define-key map "t" 'todo-sort-categories-by-todo)
6319 (define-key map "y" 'todo-sort-categories-by-diary)
6320 (define-key map "d" 'todo-sort-categories-by-done)
6321 (define-key map "a" 'todo-sort-categories-by-archived)
6322 (define-key map "#" 'todo-set-category-number)
6323 (define-key map "l" 'todo-lower-category)
6324 (define-key map "r" 'todo-raise-category)
6325 (define-key map "n" 'todo-next-button)
6326 (define-key map "p" 'todo-previous-button)
6327 (define-key map [tab] 'todo-next-button)
6328 (define-key map [backtab] 'todo-previous-button)
6329 (define-key map "q" 'todo-quit)
6331 "Todo Categories mode keymap.")
6333 (defvar todo-filtered-items-mode-map
6334 (let ((map (make-sparse-keymap)))
6335 (suppress-keymap map)
6336 (dolist (kb todo-key-bindings-t+a+f)
6337 (define-key map (nth 0 kb) (nth 1 kb)))
6338 (dolist (kb todo-key-bindings-t+f)
6339 (define-key map (nth 0 kb) (nth 1 kb)))
6340 (define-key map "g" 'todo-go-to-source-item)
6341 (define-key map [remap newline] 'todo-go-to-source-item)
6343 "Todo Filtered Items mode keymap.")
6345 ;; FIXME: Is it worth having a menu and if so, which commands?
6346 ;; (easy-menu-define
6347 ;; todo-menu todo-mode-map "Todo Menu"
6350 ;; ["Next Item" todo-forward-item t]
6351 ;; ["Previous Item" todo-backward-item t]
6353 ;; ["Next Category" todo-forward-category t]
6354 ;; ["Previous Category" todo-backward-category t]
6355 ;; ["Jump to Category" todo-jump-to-category t]
6357 ;; ["Search Todo File" todo-search t]
6358 ;; ["Clear Highlighting on Search Matches" todo-category-done t])
6360 ;; ["List Current Categories" todo-show-categories-table t]
6361 ;; ;; ["List Categories Alphabetically" todo-display-categories-alphabetically t]
6362 ;; ["Turn Item Highlighting on/off" todo-toggle-item-highlighting t]
6363 ;; ["Turn Item Numbering on/off" todo-toggle-prefix-numbers t]
6364 ;; ["Turn Item Time Stamp on/off" todo-toggle-item-header t]
6365 ;; ["View/Hide Done Items" todo-toggle-view-done-items t]
6367 ;; ["View Diary Items" todo-filter-diary-items t]
6368 ;; ["View Top Priority Items" todo-filter-top-priorities t]
6369 ;; ["View Multifile Top Priority Items" todo-filter-top-priorities-multifile t]
6371 ;; ["Print Category" todo-print-buffer t])
6373 ;; ["Insert New Item" todo-insert-item t]
6374 ;; ["Insert Item Here" todo-insert-item-here t]
6375 ;; ("More Insertion Commands")
6376 ;; ["Edit Item" todo-edit-item t]
6377 ;; ["Edit Multiline Item" todo-edit-multiline-item t]
6378 ;; ["Edit Item Header" todo-edit-item-header t]
6379 ;; ["Edit Item Date" todo-edit-item-date t]
6380 ;; ["Edit Item Time" todo-edit-item-time t]
6382 ;; ["Lower Item Priority" todo-lower-item-priority t]
6383 ;; ["Raise Item Priority" todo-raise-item-priority t]
6384 ;; ["Set Item Priority" todo-set-item-priority t]
6385 ;; ["Move (Recategorize) Item" todo-move-item t]
6386 ;; ["Delete Item" todo-delete-item t]
6387 ;; ["Undo Done Item" todo-item-undone t]
6388 ;; ["Mark/Unmark Item for Diary" todo-toggle-item-diary-inclusion t]
6389 ;; ["Mark/Unmark Items for Diary" todo-edit-item-diary-inclusion t]
6390 ;; ["Mark & Hide Done Item" todo-item-done t]
6391 ;; ["Archive Done Items" todo-archive-category-done-items t]
6393 ;; ["Add New Todo File" todo-add-file t]
6394 ;; ["Add New Category" todo-add-category t]
6395 ;; ["Delete Current Category" todo-delete-category t]
6396 ;; ["Rename Current Category" todo-rename-category t]
6398 ;; ["Save Todo File" todo-save t]
6401 ;; ["Quit" todo-quit t]
6404 ;; -----------------------------------------------------------------------------
6405 ;;; Hook functions and mode definitions
6406 ;; -----------------------------------------------------------------------------
6408 (defun todo-show-current-file ()
6409 "Visit current instead of default todo file with `todo-show'.
6410 Added to `pre-command-hook' in Todo mode when user option
6411 `todo-show-current-file' is set to non-nil."
6412 (setq todo-global-current-todo-file todo-current-todo-file))
6414 (defun todo-display-as-todo-file ()
6415 "Show todo files correctly when visited from outside of Todo mode.
6416 Added to `find-file-hook' in Todo mode and Todo Archive mode."
6417 (and (member this-command todo-visit-files-commands)
6418 (= (- (point-max) (point-min)) (buffer-size))
6419 (member major-mode '(todo-mode todo-archive-mode))
6420 (todo-category-select)))
6422 (defun todo-add-to-buffer-list ()
6423 "Add name of just visited todo file to `todo-file-buffers'.
6424 This function is added to `find-file-hook' in Todo mode."
6425 (let ((filename (file-truename (buffer-file-name))))
6426 (when (member filename todo-files)
6427 (add-to-list 'todo-file-buffers filename))))
6429 (defun todo-update-buffer-list ()
6430 "Make current Todo mode buffer file car of `todo-file-buffers'.
6431 This function is added to `post-command-hook' in Todo mode."
6432 (let ((filename (file-truename (buffer-file-name))))
6433 (unless (eq (car todo-file-buffers) filename)
6434 (setq todo-file-buffers
6435 (cons filename (delete filename todo-file-buffers))))))
6437 (defun todo-reset-global-current-todo-file ()
6438 "Update the value of `todo-global-current-todo-file'.
6439 This becomes the latest existing todo file or, if there is none,
6440 the value of `todo-default-todo-file'.
6441 This function is added to `kill-buffer-hook' in Todo mode."
6442 (let ((filename (file-truename (buffer-file-name))))
6443 (setq todo-file-buffers (delete filename todo-file-buffers))
6444 (setq todo-global-current-todo-file
6445 (or (car todo-file-buffers)
6446 (todo-absolute-file-name todo-default-todo-file)))))
6448 (defun todo-reset-and-enable-done-separator ()
6449 "Show resized done items separator overlay after window change.
6450 Added to `window-configuration-change-hook' in Todo mode."
6451 (when (= 1 (length todo-done-separator-string))
6452 (let ((sep todo-done-separator))
6453 (setq todo-done-separator (todo-done-separator))
6454 (save-match-data (todo-reset-done-separator sep)))))
6456 (defun todo-modes-set-1 ()
6457 "Make some settings that apply to multiple Todo modes."
6458 (setq-local font-lock-defaults '(todo-font-lock-keywords t))
6459 (setq-local tab-width todo-indent-to-here)
6460 (setq-local indent-line-function 'todo-indent)
6461 (when todo-wrap-lines
6463 (setq wrap-prefix (make-string todo-indent-to-here 32))))
6465 (defun todo-modes-set-2 ()
6466 "Make some settings that apply to multiple Todo modes."
6467 (add-to-invisibility-spec 'todo)
6468 (setq buffer-read-only t)
6469 (when (boundp 'hl-line-range-function)
6470 (setq-local hl-line-range-function
6471 (lambda() (save-excursion
6472 (when (todo-item-end)
6473 (cons (todo-item-start)
6474 (todo-item-end))))))))
6476 (defun todo-modes-set-3 ()
6477 "Make some settings that apply to multiple Todo modes."
6478 (setq-local todo-categories (todo-set-categories))
6479 (setq-local todo-category-number 1)
6480 (add-hook 'find-file-hook 'todo-display-as-todo-file nil t))
6482 (put 'todo-mode 'mode-class 'special)
6484 (define-derived-mode todo-mode special-mode "Todo"
6485 "Major mode for displaying, navigating and editing todo lists.
6488 ;; (easy-menu-add todo-menu)
6492 ;; Initialize todo-current-todo-file.
6493 (when (member (file-truename (buffer-file-name))
6494 (funcall todo-files-function))
6495 (setq-local todo-current-todo-file (file-truename (buffer-file-name))))
6496 (setq-local todo-show-done-only nil)
6497 (setq-local todo-categories-with-marks nil)
6498 (add-hook 'find-file-hook 'todo-add-to-buffer-list nil t)
6499 (add-hook 'post-command-hook 'todo-update-buffer-list nil t)
6500 (when todo-show-current-file
6501 (add-hook 'pre-command-hook 'todo-show-current-file nil t))
6502 (add-hook 'window-configuration-change-hook
6503 'todo-reset-and-enable-done-separator nil t)
6504 (add-hook 'kill-buffer-hook 'todo-reset-global-current-todo-file nil t))
6506 (put 'todo-archive-mode 'mode-class 'special)
6508 ;; If todo-mode is parent, all todo-mode key bindings appear to be
6509 ;; available in todo-archive-mode (e.g. shown by C-h m).
6510 (define-derived-mode todo-archive-mode special-mode "Todo-Arch"
6511 "Major mode for archived todo categories.
6513 \\{todo-archive-mode-map}"
6517 (setq-local todo-current-todo-file (file-truename (buffer-file-name)))
6518 (setq-local todo-show-done-only t))
6520 (defun todo-mode-external-set ()
6521 "Set `todo-categories' externally to `todo-current-todo-file'."
6522 (setq-local todo-current-todo-file todo-global-current-todo-file)
6523 (let ((cats (with-current-buffer
6524 ;; Can't use find-buffer-visiting when
6525 ;; `todo-show-categories-table' is called on first
6526 ;; invocation of `todo-show', since there is then
6527 ;; no buffer visiting the current file.
6528 (find-file-noselect todo-current-todo-file 'nowarn)
6530 ;; In Todo Edit mode todo-categories is now nil
6531 ;; since it uses same buffer as Todo mode but
6532 ;; doesn't have the latter's local variables.
6534 (goto-char (point-min))
6535 (read (buffer-substring-no-properties
6536 (line-beginning-position)
6537 (line-end-position))))))))
6538 (setq-local todo-categories cats)))
6540 (define-derived-mode todo-edit-mode text-mode "Todo-Ed"
6541 "Major mode for editing multiline todo items.
6543 \\{todo-edit-mode-map}"
6545 (todo-mode-external-set)
6546 (setq buffer-read-only nil))
6548 (put 'todo-categories-mode 'mode-class 'special)
6550 (define-derived-mode todo-categories-mode special-mode "Todo-Cats"
6551 "Major mode for displaying and editing todo categories.
6553 \\{todo-categories-mode-map}"
6554 (todo-mode-external-set))
6556 (put 'todo-filtered-items-mode 'mode-class 'special)
6558 (define-derived-mode todo-filtered-items-mode special-mode "Todo-Fltr"
6559 "Mode for displaying and reprioritizing top priority Todo.
6561 \\{todo-filtered-items-mode-map}"
6565 (add-to-list 'auto-mode-alist '("\\.todo\\'" . todo-mode))
6566 (add-to-list 'auto-mode-alist '("\\.toda\\'" . todo-archive-mode))
6567 (add-to-list 'auto-mode-alist '("\\.tod[tyr]\\'" . todo-filtered-items-mode))
6569 ;; -----------------------------------------------------------------------------
6570 (provide 'todo-mode)
6572 ;;; todo-mode.el ends here