1 ;;; todo-mode.el --- facilities for making and maintaining todo lists
3 ;; Copyright (C) 1997, 1999, 2001-2014 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 ;; -----------------------------------------------------------------------------
333 (defface todo-key-prompt
334 '((t (:weight bold)))
335 "Face for making keys in item insertion prompt stand out."
339 ;; '((t :inherit font-lock-warning-face))
343 (:weight bold :foreground "Red1"))
347 (:weight bold :foreground "Pink"))
351 (:weight bold :foreground "Red1"))
355 (:weight bold :foreground "Pink"))
360 (:weight bold :inverse-video t)))
361 "Face for marks on marked items."
364 (defface todo-prefix-string
365 ;; '((t :inherit font-lock-constant-face))
366 '((((class grayscale) (background light))
367 (:foreground "LightGray" :weight bold :underline t))
368 (((class grayscale) (background dark))
369 (:foreground "Gray50" :weight bold :underline t))
370 (((class color) (min-colors 88) (background light)) (:foreground "dark cyan"))
371 (((class color) (min-colors 88) (background dark)) (:foreground "Aquamarine"))
372 (((class color) (min-colors 16) (background light)) (:foreground "CadetBlue"))
373 (((class color) (min-colors 16) (background dark)) (:foreground "Aquamarine"))
374 (((class color) (min-colors 8)) (:foreground "magenta"))
375 (t (:weight bold :underline t)))
376 "Face for todo item prefix or numerical priority string."
379 (defface todo-top-priority
380 ;; bold font-lock-comment-face
381 '((default :weight bold)
382 (((class grayscale) (background light)) :foreground "DimGray" :slant italic)
383 (((class grayscale) (background dark)) :foreground "LightGray" :slant italic)
384 (((class color) (min-colors 88) (background light)) :foreground "Firebrick")
385 (((class color) (min-colors 88) (background dark)) :foreground "chocolate1")
386 (((class color) (min-colors 16) (background light)) :foreground "red")
387 (((class color) (min-colors 16) (background dark)) :foreground "red1")
388 (((class color) (min-colors 8) (background light)) :foreground "red")
389 (((class color) (min-colors 8) (background dark)) :foreground "yellow")
391 "Face for top priority todo item numerical priority string.
392 The item's priority number string has this face if the number is
393 less than or equal the category's top priority setting."
396 (defface todo-nondiary
397 ;; '((t :inherit font-lock-type-face))
398 '((((class grayscale) (background light)) :foreground "Gray90" :weight bold)
399 (((class grayscale) (background dark)) :foreground "DimGray" :weight bold)
400 (((class color) (min-colors 88) (background light)) :foreground "ForestGreen")
401 (((class color) (min-colors 88) (background dark)) :foreground "PaleGreen")
402 (((class color) (min-colors 16) (background light)) :foreground "ForestGreen")
403 (((class color) (min-colors 16) (background dark)) :foreground "PaleGreen")
404 (((class color) (min-colors 8)) :foreground "green")
405 (t :weight bold :underline t))
406 "Face for non-diary markers around todo item date/time header."
410 '((t :inherit diary))
411 "Face for the date string of a todo item."
415 '((t :inherit diary-time))
416 "Face for the time string of a todo item."
419 (defface todo-diary-expired
420 ;; Doesn't contrast enough with todo-date (= diary) face.
421 ;; ;; '((t :inherit warning))
422 ;; '((default :weight bold)
423 ;; (((class color) (min-colors 16)) :foreground "DarkOrange")
424 ;; (((class color)) :foreground "yellow"))
425 ;; bold font-lock-function-name-face
426 '((default :weight bold)
427 (((class color) (min-colors 88) (background light)) :foreground "Blue1")
428 (((class color) (min-colors 88) (background dark)) :foreground "LightSkyBlue")
429 (((class color) (min-colors 16) (background light)) :foreground "Blue")
430 (((class color) (min-colors 16) (background dark)) :foreground "LightSkyBlue")
431 (((class color) (min-colors 8)) :foreground "blue")
432 (t :inverse-video t))
433 "Face for expired dates of diary items."
436 (defface todo-done-sep
437 ;; '((t :inherit font-lock-builtin-face))
438 '((((class grayscale) (background light)) :foreground "LightGray" :weight bold)
439 (((class grayscale) (background dark)) :foreground "DimGray" :weight bold)
440 (((class color) (min-colors 88) (background light)) :foreground "dark slate blue")
441 (((class color) (min-colors 88) (background dark)) :foreground "LightSteelBlue")
442 (((class color) (min-colors 16) (background light)) :foreground "Orchid")
443 (((class color) (min-colors 16) (background dark)) :foreground "LightSteelBlue")
444 (((class color) (min-colors 8)) :foreground "blue" :weight bold)
446 "Face for separator string between done and not done todo items."
450 ;; '((t :inherit font-lock-keyword-face))
451 '((((class grayscale) (background light)) :foreground "LightGray" :weight bold)
452 (((class grayscale) (background dark)) :foreground "DimGray" :weight bold)
453 (((class color) (min-colors 88) (background light)) :foreground "Purple")
454 (((class color) (min-colors 88) (background dark)) :foreground "Cyan1")
455 (((class color) (min-colors 16) (background light)) :foreground "Purple")
456 (((class color) (min-colors 16) (background dark)) :foreground "Cyan")
457 (((class color) (min-colors 8)) :foreground "cyan" :weight bold)
459 "Face for done todo item header string."
462 (defface todo-comment
463 ;; '((t :inherit font-lock-comment-face))
464 '((((class grayscale) (background light))
465 :foreground "DimGray" :weight bold :slant italic)
466 (((class grayscale) (background dark))
467 :foreground "LightGray" :weight bold :slant italic)
468 (((class color) (min-colors 88) (background light))
469 :foreground "Firebrick")
470 (((class color) (min-colors 88) (background dark))
471 :foreground "chocolate1")
472 (((class color) (min-colors 16) (background light))
474 (((class color) (min-colors 16) (background dark))
476 (((class color) (min-colors 8) (background light))
478 (((class color) (min-colors 8) (background dark))
479 :foreground "yellow")
480 (t :weight bold :slant italic))
481 "Face for comments appended to done todo items."
485 ;; '((t :inherit match))
489 (:background "yellow1"))
493 (:background "RoyalBlue3"))
497 (:foreground "black" :background "yellow"))
501 (:foreground "white" :background "blue"))
506 (:background "gray")))
507 "Face for matches found by `todo-search'."
511 ;; '((t :inherit widget-field))
513 (:foreground "black" :background "yellow3"))
514 (((class grayscale color)
516 (:background "gray85"))
517 (((class grayscale color)
519 (:background "dim gray"))
522 "Face for buttons in table of categories."
525 (defface todo-sorted-column
530 (:background "grey85"))
533 (:background "grey85" :foreground "grey10"))
535 (:background "gray")))
536 "Face for sorted column in table of categories."
539 (defface todo-archived-only
540 ;; '((t (:inherit (shadow))))
543 (:foreground "grey50"))
546 (:foreground "grey70"))
548 (:foreground "gray")))
549 "Face for archived-only category names in table of categories."
552 (defface todo-category-string
553 ;; '((t :inherit font-lock-type-face))
554 '((((class grayscale) (background light)) :foreground "Gray90" :weight bold)
555 (((class grayscale) (background dark)) :foreground "DimGray" :weight bold)
556 (((class color) (min-colors 88) (background light)) :foreground "ForestGreen")
557 (((class color) (min-colors 88) (background dark)) :foreground "PaleGreen")
558 (((class color) (min-colors 16) (background light)) :foreground "ForestGreen")
559 (((class color) (min-colors 16) (background dark)) :foreground "PaleGreen")
560 (((class color) (min-colors 8)) :foreground "green")
561 (t :weight bold :underline t))
562 "Face for category-file header in Todo Filtered Items mode."
565 ;; -----------------------------------------------------------------------------
566 ;;; Entering and exiting
567 ;; -----------------------------------------------------------------------------
569 ;; (defcustom todo-visit-files-commands (list 'find-file 'dired-find-file)
570 ;; "List of file finding commands for `todo-display-as-todo-file'.
571 ;; Invoking these commands to visit a todo file or todo archive file
572 ;; calls `todo-show' or `todo-find-archive', so that the file is
573 ;; displayed correctly."
574 ;; :type '(repeat function)
577 (defun todo-short-file-name (file)
578 "Return the short form of todo file FILE's name.
579 This lacks the extension and directory components."
581 (file-name-sans-extension (file-name-nondirectory file))))
583 (defcustom todo-default-todo-file (todo-short-file-name
584 (car (funcall todo-files-function)))
585 "Todo file visited by first session invocation of `todo-show'."
586 :type (when todo-files
587 `(radio ,@(mapcar (lambda (f) (list 'const f))
588 (mapcar 'todo-short-file-name
589 (funcall todo-files-function)))))
592 (defcustom todo-show-current-file t
593 "Non-nil to make `todo-show' visit the current todo file.
594 Otherwise, `todo-show' always visits `todo-default-todo-file'."
596 :initialize 'custom-initialize-default
597 :set 'todo-set-show-current-file
600 (defcustom todo-show-first 'first
601 "What action to take on first use of `todo-show' on a file."
602 :type '(choice (const :tag "Show first category" first)
603 (const :tag "Show table of categories" table)
604 (const :tag "Show top priorities" top)
605 (const :tag "Show diary items" diary)
606 (const :tag "Show regexp items" regexp))
609 (defcustom todo-add-item-if-new-category t
610 "Non-nil to prompt for an item after adding a new category."
614 (defcustom todo-initial-file "Todo"
615 "Default file name offered on adding first todo file."
619 (defcustom todo-initial-category "Todo"
620 "Default category name offered on initializing a new todo file."
624 (defcustom todo-category-completions-files nil
625 "List of files for building `todo-read-category' completions."
626 :type `(set ,@(mapcar (lambda (f) (list 'const f))
627 (mapcar 'todo-short-file-name
628 (funcall todo-files-function))))
631 (defcustom todo-completion-ignore-case nil
632 "Non-nil means case is ignored by `todo-read-*' functions."
637 (defun todo-show (&optional solicit-file interactive)
638 "Visit a todo file and display one of its categories.
640 When invoked in Todo mode, prompt for which todo file to visit.
641 When invoked outside of Todo mode with non-nil prefix argument
642 SOLICIT-FILE prompt for which todo file to visit; otherwise visit
643 `todo-default-todo-file'. Subsequent invocations from outside
644 of Todo mode revisit this file or, with option
645 `todo-show-current-file' non-nil (the default), whichever todo
646 file was last visited.
648 If you call this command before you have created any todo file in
649 the current format, and you have an todo file in old format, it
650 will ask you whether to convert that file and show it.
651 Otherwise, calling this command before any todo file exists
652 prompts for a file name and an initial category (defaulting to
653 `todo-initial-file' and `todo-initial-category'), creates both of
654 these, visits the file and displays the category, and if option
655 `todo-add-item-if-new-category' is non-nil (the default), prompts
658 The first invocation of this command on an existing todo file
659 interacts with the option `todo-show-first': if its value is
660 `first' (the default), show the first category in the file; if
661 its value is `table', show the table of categories in the file;
662 if its value is one of `top', `diary' or `regexp', show the
663 corresponding saved top priorities, diary items, or regexp items
664 file, if any. Subsequent invocations always show the file's
665 current (i.e., last displayed) category.
667 In Todo mode just the category's unfinished todo items are shown
668 by default. The done items are hidden, but typing
669 `\\[todo-toggle-view-done-items]' displays them below the todo
670 items. With non-nil user option `todo-show-with-done' both todo
671 and done items are always shown on visiting a category.
673 Invoking this command in Todo Archive mode visits the
674 corresponding todo file, displaying the corresponding category."
676 (when todo-default-todo-file
677 (todo-check-file (todo-absolute-file-name todo-default-todo-file)))
679 ;; Before initializing the first todo first, check if there is a
680 ;; legacy todo file and if so, offer to convert to the current
681 ;; format and make it the first new todo file.
682 (unless todo-default-todo-file
683 (let ((legacy-todo-file (if (boundp 'todo-file-do)
685 (locate-user-emacs-file "todo-do" ".todo-do"))))
686 (when (and (file-exists-p legacy-todo-file)
687 (y-or-n-p (concat "Do you want to convert a copy of your "
688 "old todo file to the new format? ")))
689 (when (todo-convert-legacy-files)
690 (throw 'shown nil)))))
693 (show-first todo-show-first)
694 (file (cond ((or solicit-file
696 (memq major-mode '(todo-mode
698 todo-filtered-items-mode))))
699 (if (funcall todo-files-function)
700 (todo-read-file-name "Choose a todo file to visit: "
702 (user-error "There are no todo files")))
703 ((and (eq major-mode 'todo-archive-mode)
704 ;; Called noninteractively via todo-quit
705 ;; to jump to corresponding category in
708 (setq cat (todo-current-category))
709 (concat (file-name-sans-extension
710 todo-current-todo-file) ".todo"))
712 (or todo-current-todo-file
713 (and todo-show-current-file
714 todo-global-current-todo-file)
715 (todo-absolute-file-name todo-default-todo-file)
718 (unless todo-default-todo-file
719 ;; We just initialized the first todo file, so make it the default.
720 (setq todo-default-todo-file (todo-short-file-name file)
722 (todo-reevaluate-default-file-defcustom))
723 (unless (member file todo-visited)
724 ;; Can't setq t-c-t-f here, otherwise wrong file shown when
725 ;; todo-show is called from todo-show-categories-table.
726 (let ((todo-current-todo-file file))
727 (cond ((eq todo-show-first 'table)
728 (todo-show-categories-table))
729 ((memq todo-show-first '(top diary regexp))
730 (let* ((shortf (todo-short-file-name file))
731 (fi-file (todo-absolute-file-name
732 shortf todo-show-first)))
733 (when (eq todo-show-first 'regexp)
734 (let ((rxfiles (directory-files todo-directory t
736 (when (and rxfiles (> (length rxfiles) 1))
737 (let ((rxf (mapcar 'todo-short-file-name rxfiles)))
738 (setq fi-file (todo-absolute-file-name
740 "Choose a regexp items file: "
742 (if (file-exists-p fi-file)
746 (set-buffer (find-file-noselect fi-file 'nowarn)))
747 (unless (derived-mode-p 'todo-filtered-items-mode)
748 (todo-filtered-items-mode)))
749 (message "There is no %s file for %s"
750 (cond ((eq todo-show-first 'top)
752 ((eq todo-show-first 'diary)
754 ((eq todo-show-first 'regexp)
757 (setq todo-show-first 'first)))))))
758 (when (or (member file todo-visited)
759 (eq todo-show-first 'first))
760 (unless (todo-check-file file) (throw 'end nil))
761 (set-window-buffer (selected-window)
762 (set-buffer (find-file-noselect file 'nowarn)))
763 (if (equal (file-name-extension (buffer-file-name)) "toda")
764 (unless (derived-mode-p 'todo-archive-mode) (todo-archive-mode))
765 (unless (derived-mode-p 'todo-mode) (todo-mode)))
766 ;; When quitting an archive file, show the corresponding
767 ;; category in the corresponding todo file, if it exists.
768 (when (assoc cat todo-categories)
769 (setq todo-category-number (todo-category-number cat)))
770 ;; If this is a new todo file, add its first category.
771 (when (zerop (buffer-size))
774 (setq todo-category-number
775 (todo-add-category todo-current-todo-file "")
776 add-item todo-add-item-if-new-category
779 ;; If the category was added, save the file now, so we
780 ;; don't risk having an empty todo file, which would
781 ;; signal an error if we tried to visit it later,
782 ;; since doing that looks for category boundaries.
784 ;; If user cancels before adding the category, clean up
785 ;; and exit, so we have a fresh slate the next time.
787 ;; (setq todo-files (funcall todo-files-function))
788 (setq todo-files (delete file todo-files))
790 (setq todo-default-todo-file nil
791 todo-current-todo-file nil)
792 (todo-reevaluate-default-file-defcustom))
795 (save-excursion (todo-category-select))
796 (when add-item (todo-insert-item--basic)))
797 (setq todo-show-first show-first)
798 (add-to-list 'todo-visited file)))))
801 "Save the current todo file."
803 (cond ((eq major-mode 'todo-filtered-items-mode)
804 (todo-check-filtered-items-file)
805 (todo-save-filtered-items-buffer))
809 (defvar todo-descending-counts)
812 "Exit the current Todo-related buffer.
813 Depending on the specific mode, this either kills the buffer or
814 buries it and restores state as needed."
816 (let ((buf (current-buffer)))
817 (cond ((eq major-mode 'todo-categories-mode)
818 ;; Postpone killing buffer till after calling todo-show, to
819 ;; prevent killing todo-mode buffer.
820 (setq todo-descending-counts nil)
821 ;; Ensure todo-show calls todo-show-categories-table only on
822 ;; first invocation per file.
823 (when (eq todo-show-first 'table)
824 (add-to-list 'todo-visited todo-current-todo-file))
827 ((eq major-mode 'todo-filtered-items-mode)
829 (unless (eq major-mode 'todo-mode) (todo-show)))
830 ((eq major-mode 'todo-archive-mode)
831 ;; Have to write a newly created archive to file to avoid
832 ;; subsequent errors.
834 (let ((todo-file (concat todo-directory
835 (todo-short-file-name todo-current-todo-file)
837 (if (todo-check-file todo-file)
839 (message "There is no todo file for this archive")))
840 ;; When todo-check-file runs in todo-show, it kills the
841 ;; buffer if the archive file was deleted externally.
842 (when (buffer-live-p buf) (bury-buffer buf)))
843 ((eq major-mode 'todo-mode)
845 ;; If we just quit archive mode, just burying the buffer
846 ;; in todo-mode would return to archive.
847 (set-window-buffer (selected-window)
848 (set-buffer (other-buffer)))
849 (bury-buffer buf)))))
851 ;; -----------------------------------------------------------------------------
852 ;;; Navigation between and within categories
853 ;; -----------------------------------------------------------------------------
855 (defcustom todo-skip-archived-categories nil
856 "Non-nil to handle categories with only archived items specially.
858 Sequential category navigation using \\[todo-forward-category]
859 or \\[todo-backward-category] skips categories that contain only
860 archived items. Other commands still recognize these categories.
861 In Todo Categories mode (\\[todo-show-categories-table]) these
862 categories shown in `todo-archived-only' face and pressing the
863 category button visits the category in the archive instead of the
866 :group 'todo-display)
868 (defun todo-forward-category (&optional back)
869 "Visit the numerically next category in this todo file.
870 If the current category is the highest numbered, visit the first
871 category. With non-nil argument BACK, visit the numerically
872 previous category (the highest numbered one, if the current
873 category is the first)."
875 (setq todo-category-number
876 (1+ (mod (- todo-category-number (if back 2 0))
877 (length todo-categories))))
878 (when todo-skip-archived-categories
879 (while (and (zerop (todo-get-count 'todo))
880 (zerop (todo-get-count 'done))
881 (not (zerop (todo-get-count 'archived))))
882 (setq todo-category-number
883 (apply (if back '1- '1+) (list todo-category-number)))))
884 (todo-category-select)
885 (goto-char (point-min)))
887 (defun todo-backward-category ()
888 "Visit the numerically previous category in this todo file.
889 If the current category is the highest numbered, visit the first
892 (todo-forward-category t))
894 (defvar todo-categories-buffer)
896 (defun todo-jump-to-category (&optional file where)
897 "Prompt for a category in a todo file and jump to it.
899 With non-nil FILE (interactively a prefix argument), prompt for a
900 specific todo file and choose (with TAB completion) a category
901 in it to jump to; otherwise, choose and jump to any category in
902 either the current todo file or a file in
903 `todo-category-completions-files'.
905 Also accept a non-existing category name and ask whether to add a
906 new category by that name; on confirmation, add it and jump to
907 that category, and if option `todo-add-item-if-new-category' is
908 non-nil (the default), then prompt for the first item.
910 In noninteractive calls non-nil WHERE specifies either the goal
911 category or its file. If its value is `archive', the choice of
912 categories is restricted to the current archive file or the
913 archive you were prompted to choose; this is used by
914 `todo-jump-to-archive-category'. If its value is the name of a
915 category, jump directly to that category; this is used in Todo
918 ;; If invoked outside of Todo mode and there is not yet any Todo
919 ;; file, initialize one.
920 (if (null (funcall todo-files-function))
922 (let* ((archive (eq where 'archive))
923 (cat (unless archive where))
924 (file0 (when cat ; We're in Todo Categories mode.
925 ;; With non-nil `todo-skip-archived-categories'
926 ;; jump to archive file of a category with only
928 (if (and todo-skip-archived-categories
929 (zerop (todo-get-count 'todo cat))
930 (zerop (todo-get-count 'done cat))
931 (not (zerop (todo-get-count 'archived cat))))
932 (concat (file-name-sans-extension
933 todo-current-todo-file) ".toda")
934 ;; Otherwise, jump to current todo file.
935 todo-current-todo-file)))
936 (len (length todo-categories))
937 (cat+file (unless cat
938 (todo-read-category "Jump to category: "
939 (if archive 'archive) file)))
940 (add-item (and todo-add-item-if-new-category
941 (> (length todo-categories) len)))
942 (category (or cat (car cat+file))))
943 (unless cat (setq file0 (cdr cat+file)))
944 (with-current-buffer (find-file-noselect file0 'nowarn)
945 (setq todo-current-todo-file file0)
946 ;; If called from Todo Categories mode, clean up before jumping.
947 (if (string= (buffer-name) todo-categories-buffer)
949 (set-window-buffer (selected-window)
950 (set-buffer (find-buffer-visiting file0)))
951 (unless todo-global-current-todo-file
952 (setq todo-global-current-todo-file todo-current-todo-file))
953 (todo-category-number category)
954 (todo-category-select)
955 (goto-char (point-min))
956 (when add-item (todo-insert-item--basic))))))
958 (defun todo-next-item (&optional count)
959 "Move point down to the beginning of the next item.
960 With positive numerical prefix COUNT, move point COUNT items
963 If the category's done items are hidden, this command also moves
964 point to the empty line below the last todo item from any higher
965 item in the category, i.e., when invoked with or without a prefix
966 argument. If the category's done items are visible, this command
967 called with a prefix argument only moves point to a lower item,
968 e.g., with point on the last todo item and called with prefix 1,
969 it moves point to the first done item; but if called with point
970 on the last todo item without a prefix argument, it moves point
971 the the empty line above the done items separator."
973 ;; It's not worth the trouble to allow prefix arg value < 1, since
974 ;; we have the corresponding command.
975 (cond ((and current-prefix-arg (< count 1))
976 (user-error "The prefix argument must be a positive number"))
978 (todo-forward-item count))
980 (todo-forward-item))))
982 (defun todo-previous-item (&optional count)
983 "Move point up to start of item with next higher priority.
984 With positive numerical prefix COUNT, move point COUNT items
987 If the category's done items are visible, this command called
988 with a prefix argument only moves point to a higher item, e.g.,
989 with point on the first done item and called with prefix 1, it
990 moves to the last todo item; but if called with point on the
991 first done item without a prefix argument, it moves point the the
992 empty line above the done items separator."
994 ;; Avoid moving to bob if on the first item but not at bob.
995 (when (> (line-number-at-pos) 1)
996 ;; It's not worth the trouble to allow prefix arg value < 1, since
997 ;; we have the corresponding command.
998 (cond ((and current-prefix-arg (< count 1))
999 (user-error "The prefix argument must be a positive number"))
1001 (todo-backward-item count))
1003 (todo-backward-item)))))
1005 ;; -----------------------------------------------------------------------------
1006 ;;; Display toggle commands
1007 ;; -----------------------------------------------------------------------------
1009 (defun todo-toggle-prefix-numbers ()
1010 "Hide item numbering if shown, show if hidden."
1014 (goto-char (point-min))
1015 (let* ((ov (todo-get-overlay 'prefix))
1016 (show-done (re-search-forward todo-done-string-start nil t))
1017 (todo-show-with-done show-done)
1018 (todo-number-prefix (not (equal (overlay-get ov 'before-string)
1020 (if (eq major-mode 'todo-filtered-items-mode)
1021 (todo-prefix-overlays)
1022 (todo-category-select))))))
1024 (defun todo-toggle-view-done-items ()
1025 "Show hidden or hide visible done items in current category."
1027 (if (zerop (todo-get-count 'done (todo-current-category)))
1028 (message "There are no done items in this category.")
1029 (let ((opoint (point)))
1030 (goto-char (point-min))
1031 (let* ((shown (re-search-forward todo-done-string-start nil t))
1032 (todo-show-with-done (not shown)))
1033 (todo-category-select)
1035 ;; If start of done items sections is below the bottom of the
1036 ;; window, make it visible.
1039 (goto-char (point-min))
1040 (re-search-forward todo-done-string-start nil t)))
1041 (if (not (pos-visible-in-window-p shown))
1043 (goto-char opoint)))))))
1045 (defun todo-toggle-view-done-only ()
1046 "Switch between displaying only done or only todo items."
1048 (setq todo-show-done-only (not todo-show-done-only))
1049 (todo-category-select))
1051 (defun todo-toggle-item-highlighting ()
1052 "Highlight or unhighlight the todo item the cursor is on."
1054 (eval-and-compile (require 'hl-line))
1055 (when (memq major-mode
1056 '(todo-mode todo-archive-mode todo-filtered-items-mode))
1061 (defun todo-toggle-item-header ()
1062 "Hide or show item date-time headers in the current file.
1063 With done items, this hides only the done date-time string, not
1064 the the original date-time string."
1068 (goto-char (point-min))
1069 (let ((ov (todo-get-overlay 'header)))
1071 (remove-overlays 1 (1+ (buffer-size)) 'todo 'header)
1073 (goto-char (point-min))
1075 (when (re-search-forward
1076 (concat todo-item-start
1077 "\\( " diary-time-regexp "\\)?"
1078 (regexp-quote todo-nondiary-end) "? ")
1080 (setq ov (make-overlay (match-beginning 0) (match-end 0) nil t))
1081 (overlay-put ov 'todo 'header)
1082 (overlay-put ov 'display ""))
1083 (todo-forward-item)))))))
1085 ;; -----------------------------------------------------------------------------
1086 ;;; File and category editing
1087 ;; -----------------------------------------------------------------------------
1089 (defun todo-add-file ()
1090 "Name and initialize a new todo file.
1091 Interactively, prompt for a category and display it, and if
1092 option `todo-add-item-if-new-category' is non-nil (the default),
1093 prompt for the first item.
1094 Noninteractively, return the name of the new file."
1096 (let* ((prompt (concat "Enter name of new todo file "
1097 "(TAB or SPC to see current names): "))
1098 (file (todo-read-file-name prompt)))
1099 ;; Don't accept the name of an existing todo file.
1100 (setq file (todo-absolute-file-name
1101 (todo-validate-name (todo-short-file-name file) 'file)))
1102 (with-current-buffer (get-buffer-create file)
1104 (write-region (point-min) (point-max) file nil 'nomessage nil t)
1106 (setq todo-files (funcall todo-files-function))
1107 (todo-reevaluate-filelist-defcustoms)
1108 (if (called-interactively-p 'any)
1110 (set-window-buffer (selected-window)
1111 (set-buffer (find-file-noselect file)))
1112 (setq todo-current-todo-file file)
1116 (defun todo-rename-file (&optional arg)
1117 "Rename the current todo file.
1118 With prefix ARG, prompt for a todo file and rename it.
1119 If there are corresponding archive or filtered items files,
1120 rename these accordingly. If there are live buffers visiting
1121 these files, also rename them accordingly."
1123 (let* ((oname (or (and arg
1124 (todo-read-file-name "Choose a file to rename: "
1126 (buffer-file-name)))
1127 (soname (todo-short-file-name oname))
1128 (nname (todo-read-file-name "New name for this file: "))
1129 (snname (todo-short-file-name nname))
1130 (files (directory-files todo-directory t
1131 (concat ".*" (regexp-quote soname)
1132 ".*\.tod[aorty]$") t)))
1134 (let* ((sfname (todo-short-file-name f))
1135 (fext (file-name-extension f t))
1136 (fbuf (find-buffer-visiting f))
1137 (fbname (buffer-name fbuf)))
1138 (when (string-match (regexp-quote soname) sfname)
1139 (let* ((snfname (replace-match snname t t sfname))
1140 (nfname (concat todo-directory snfname fext)))
1141 (rename-file f nfname)
1143 (with-current-buffer fbuf
1144 (set-visited-file-name nfname t t)
1145 (cond ((member fext '(".todo" ".toda"))
1146 (setq todo-current-todo-file (buffer-file-name))
1147 (setq mode-line-buffer-identification
1148 (funcall todo-mode-line-function
1149 (todo-current-category))))
1152 (replace-regexp-in-string
1153 (regexp-quote soname) snname fbname))))))))))
1154 (setq todo-files (funcall todo-files-function)
1155 todo-archives (funcall todo-files-function t))
1156 (when (string= todo-default-todo-file soname)
1157 (setq todo-default-todo-file snname))
1158 (when (string= todo-global-current-todo-file oname)
1159 (setq todo-global-current-todo-file nname))
1160 (todo-reevaluate-filelist-defcustoms)))
1162 (defun todo-delete-file ()
1163 "Delete the current todo, archive or filtered items file.
1164 If the todo file has a corresponding archive file, or vice versa,
1165 prompt whether to delete that as well. Also kill the buffers
1166 visiting the deleted files."
1168 (let* ((file1 (buffer-file-name))
1169 (todo (eq major-mode 'todo-mode))
1170 (archive (eq major-mode 'todo-archive-mode))
1171 (filtered (eq major-mode 'todo-filtered-items-mode))
1172 (file1-sn (todo-short-file-name file1))
1173 (file2 (concat todo-directory file1-sn (cond (todo ".toda")
1174 (archive ".todo"))))
1175 (buf1 (current-buffer))
1176 (buf2 (when file2 (find-buffer-visiting file2)))
1177 (prompt1 (concat "Delete " (cond (todo "todo")
1179 (filtered "filtered items"))
1181 (prompt2 (concat "Also delete the corresponding "
1182 (cond (todo "archive") (archive "todo")) " file "
1183 (when buf2 "and kill the buffer visiting it? ")))
1184 (delete1 (yes-or-no-p (format prompt1 file1-sn)))
1185 (delete2 (when (and delete1 (or (file-exists-p file2) buf2))
1186 (yes-or-no-p prompt2))))
1188 (when (file-exists-p file1) (delete-file file1))
1189 (setq todo-visited (delete file1 todo-visited))
1193 (when (file-exists-p file2) (delete-file file2))
1194 (setq todo-visited (delete file2 todo-visited))
1195 (and buf2 (kill-buffer buf2)))
1196 ;; If we deleted an archive but not its todo file, update the
1197 ;; latter's category sexp.
1198 (when (equal (file-name-extension file2) "todo")
1199 (with-current-buffer (or buf2 (find-file-noselect file2))
1203 (goto-char (point-min))
1204 (let ((sexp (read (buffer-substring-no-properties
1205 (line-beginning-position)
1206 (line-end-position))))
1207 (buffer-read-only nil))
1208 (mapc (lambda (x) (aset (cdr x) 3 0)) sexp)
1209 (delete-region (line-beginning-position) (line-end-position))
1210 (prin1 sexp (current-buffer)))))
1211 (todo-set-categories)
1212 (unless buf2 (kill-buffer)))))
1213 (setq todo-files (funcall todo-files-function)
1214 todo-archives (funcall todo-files-function t))
1215 (when (or (string= file1-sn todo-default-todo-file)
1216 (and delete2 (string= file1-sn todo-default-todo-file)))
1217 (setq todo-default-todo-file (todo-short-file-name (car todo-files))))
1218 (when (or (string= file1 todo-global-current-todo-file)
1219 (and delete2 (string= file2 todo-global-current-todo-file)))
1220 (setq todo-global-current-todo-file nil))
1221 (todo-reevaluate-filelist-defcustoms)
1222 (message (concat (cond (todo "Todo") (archive "Archive")) " file \"%s\" "
1225 (cond (todo "archive") (archive "todo"))
1230 (defvar todo-edit-buffer "*Todo Edit*"
1231 "Name of current buffer in Todo Edit mode.")
1233 (defun todo-edit-file ()
1234 "Put current buffer in `todo-edit-mode'.
1235 This makes the entire file visible and the buffer writable and
1236 you can use the self-insertion keys and standard Emacs editing
1237 commands to make changes. To return to Todo mode, type
1238 \\[todo-edit-quit]. This runs a file format check, signaling
1239 an error if the format has become invalid. However, this check
1240 cannot tell if the number of items changed, which could result in
1241 the file containing inconsistent information. For this reason
1242 this command should be used with caution."
1247 (display-warning 'todo (format "\
1249 Type %s to return to Todo mode.
1251 This also runs a file format check and signals an error if
1252 the format has become invalid. However, this check cannot
1253 tell if the number of items or categories changed, which
1254 could result in the file containing inconsistent information.
1255 You can repair this inconsistency by invoking the command
1256 `todo-repair-categories-sexp', but this will revert any
1257 renumbering of the categories you have made, so you will
1258 have to renumber them again (see `(todo-mode) Reordering
1259 Categories')." (substitute-command-keys "\\[todo-edit-quit]"))))
1261 (defun todo-add-category (&optional file cat)
1262 "Add a new category to a todo file.
1264 Called interactively with prefix argument FILE, prompt for a file
1265 and then for a new category to add to that file, otherwise prompt
1266 just for a category to add to the current todo file. After
1267 adding the category, visit it in Todo mode and if option
1268 `todo-add-item-if-new-category' is non-nil (the default), prompt
1271 Non-interactively, add category CAT to file FILE; if FILE is nil,
1272 add CAT to the current todo file. After adding the category,
1273 return the new category number."
1276 ;; If cat is passed from caller, don't prompt, unless it is "",
1277 ;; which means the file was just added and has no category yet.
1278 (if (and cat (> (length cat) 0))
1279 (setq file0 (or (and (stringp file) file)
1280 todo-current-todo-file))
1281 (setq catfil (todo-read-category "Enter a new category name: "
1282 'add (when (called-interactively-p 'any)
1285 file0 (if (called-interactively-p 'any)
1289 (let ((counts (make-vector 4 0)) ; [todo diary done archived]
1290 (num (1+ (length todo-categories)))
1291 (buffer-read-only nil))
1292 (setq todo-current-todo-file file0)
1293 (setq todo-categories (append todo-categories
1294 (list (cons cat counts))))
1296 (goto-char (point-max))
1297 (save-excursion ; Save point for todo-category-select.
1298 (insert todo-category-beg cat "\n\n" todo-category-done "\n"))
1299 (todo-update-categories-sexp)
1300 ;; If invoked by user, display the newly added category, if
1301 ;; called programmatically return the category number to the
1303 (if (called-interactively-p 'any)
1305 (setq todo-category-number num)
1306 (todo-category-select)
1307 (when todo-add-item-if-new-category
1308 (todo-insert-item--basic)))
1311 (defun todo-rename-category ()
1312 "Rename current todo category.
1313 If this file has an archive containing this category, rename the
1314 category there as well."
1316 (let* ((cat (todo-current-category))
1317 (new (read-from-minibuffer
1318 (format "Rename category \"%s\" to: " cat))))
1319 (setq new (todo-validate-name new 'category))
1320 (let* ((ofile todo-current-todo-file)
1321 (archive (concat (file-name-sans-extension ofile) ".toda"))
1322 (buffers (append (list ofile)
1323 (unless (zerop (todo-get-count 'archived cat))
1325 (dolist (buf buffers)
1326 (with-current-buffer (find-file-noselect buf)
1327 (let (buffer-read-only)
1328 (setq todo-categories (todo-set-categories))
1331 (setcar (assoc cat todo-categories) new)
1333 (goto-char (point-min))
1334 (todo-update-categories-sexp)
1335 (re-search-forward (concat (regexp-quote todo-category-beg)
1336 "\\(" (regexp-quote cat) "\\)\n")
1338 (replace-match new t t nil 1)))))))
1339 (force-mode-line-update))
1340 (save-excursion (todo-category-select)))
1342 (defun todo-delete-category (&optional arg)
1343 "Delete current todo category provided it contains no items.
1344 With prefix ARG delete the category even if it does contain
1345 todo or done items."
1347 (let* ((file todo-current-todo-file)
1348 (cat (todo-current-category))
1349 (todo (todo-get-count 'todo cat))
1350 (done (todo-get-count 'done cat))
1351 (archived (todo-get-count 'archived cat)))
1353 (or (> todo 0) (> done 0)))
1354 (message "%s" (substitute-command-keys
1355 (concat "To delete a non-empty category, "
1356 "type C-u \\[todo-delete-category].")))
1357 (when (cond ((= (length todo-categories) 1)
1359 (concat "This is the only category in this file; "
1360 "deleting it will also delete the file.\n"
1361 "Do you want to proceed? ")))
1363 (todo-y-or-n-p (concat "This category has archived items; "
1364 "the archived category will remain\n"
1365 "after deleting the todo category. "
1366 "Do you still want to delete it\n"
1367 "(see `todo-skip-archived-categories' "
1368 "for another option)? ")))
1370 (todo-y-or-n-p (concat "Permanently remove category \"" cat
1371 "\"" (and arg " and all its entries")
1374 (let ((buffer-read-only)
1375 (beg (re-search-backward
1376 (concat "^" (regexp-quote (concat todo-category-beg cat))
1378 (end (if (re-search-forward
1379 (concat "\n\\(" (regexp-quote todo-category-beg)
1383 (remove-overlays beg end)
1384 (delete-region beg end)
1385 (if (= (length todo-categories) 1)
1386 ;; If deleted category was the only one, delete the file.
1388 (todo-reevaluate-filelist-defcustoms)
1389 ;; Skip confirming killing the archive buffer if it has been
1390 ;; modified and not saved.
1391 (set-buffer-modified-p nil)
1394 (message "Deleted todo file %s." file))
1395 (setq todo-categories (delete (assoc cat todo-categories)
1397 (todo-update-categories-sexp)
1398 (setq todo-category-number
1399 (1+ (mod todo-category-number (length todo-categories))))
1400 (todo-category-select)
1401 (goto-char (point-min))
1402 (message "Deleted category %s." cat)))))))
1404 (defun todo-move-category ()
1405 "Move current category to a different todo file.
1406 If the todo file chosen does not exist, it is created.
1407 If the current category has archived items, also move those to
1408 the archive of the file moved to, creating it if it does not exist."
1410 (when (or (> (length todo-categories) 1)
1411 (todo-y-or-n-p (concat "This is the only category in this file; "
1412 "moving it will also delete the file.\n"
1413 "Do you want to proceed? ")))
1414 (let* ((ofile todo-current-todo-file)
1415 (cat (todo-current-category))
1416 (nfile (todo-read-file-name "Todo file to move this category to: "))
1417 (archive (concat (file-name-sans-extension ofile) ".toda"))
1418 (buffers (append (list ofile)
1419 (unless (zerop (todo-get-count 'archived cat))
1422 (while (equal nfile (file-truename ofile))
1423 (setq nfile (todo-read-file-name
1424 "Choose a file distinct from this file: ")))
1425 (unless (member nfile todo-files)
1426 (with-current-buffer (get-buffer-create nfile)
1428 (write-region (point-min) (point-max) nfile nil 'nomessage nil t)
1429 (kill-buffer nfile))
1430 (setq todo-files (funcall todo-files-function))
1431 (todo-reevaluate-filelist-defcustoms))
1432 (dolist (buf buffers)
1433 (with-current-buffer (find-file-noselect buf)
1435 (goto-char (point-max))
1436 (let* ((beg (re-search-backward
1438 (regexp-quote (concat todo-category-beg cat))
1441 (end (if (re-search-forward
1442 (concat "^" (regexp-quote todo-category-beg))
1446 (content (buffer-substring-no-properties beg end))
1447 (counts (cdr (assoc cat todo-categories)))
1449 ;; Move the category to the new file. Also update or create
1450 ;; archive file if necessary.
1451 (with-current-buffer
1453 ;; Regenerate todo-archives in case there
1454 ;; is a newly created archive.
1455 (if (member buf (funcall todo-files-function t))
1456 (concat (file-name-sans-extension nfile) ".toda")
1458 (if (equal (file-name-extension (buffer-file-name)) "toda")
1459 (unless (derived-mode-p 'todo-archive-mode)
1460 (todo-archive-mode))
1461 (unless (derived-mode-p 'todo-mode) (todo-mode)))
1462 (let* ((nfile-short (todo-short-file-name nfile))
1464 (format "Todo file \"%s\" already has "
1466 (format "the category \"%s\";\n" cat)
1467 "enter a new category name: "))
1470 (goto-char (point-max))
1472 ;; If the file moved to has a category with the same
1473 ;; name, rename the moved category.
1474 (when (assoc cat todo-categories)
1475 (unless (member (file-truename (buffer-file-name))
1476 (funcall todo-files-function t))
1477 (setq new (read-from-minibuffer prompt))
1478 (setq new (todo-validate-name new 'category))))
1479 ;; Replace old with new name in todo and archive files.
1481 (goto-char (point-max))
1483 (concat "^" (regexp-quote todo-category-beg)
1484 "\\(" (regexp-quote cat) "\\)$") nil t)
1485 (replace-match new nil nil nil 1)))
1486 (setq todo-categories
1487 (append todo-categories (list (cons (or new cat) counts))))
1488 (todo-update-categories-sexp)
1489 ;; If archive was just created, save it to avoid "File
1490 ;; <xyz> no longer exists!" message on invoking
1491 ;; `todo-view-archived-items'.
1492 (unless (file-exists-p (buffer-file-name))
1494 (todo-category-number (or new cat))
1495 (todo-category-select))
1496 ;; Delete the category from the old file, and if that was the
1497 ;; last category, delete the file. Also handle archive file
1499 (remove-overlays beg end)
1500 (delete-region beg end)
1501 (goto-char (point-min))
1502 ;; Put point after todo-categories sexp.
1504 (if (eobp) ; Aside from sexp, file is empty.
1506 ;; Skip confirming killing the archive buffer.
1507 (set-buffer-modified-p nil)
1508 (delete-file todo-current-todo-file)
1510 (when (member todo-current-todo-file todo-files)
1511 (todo-reevaluate-filelist-defcustoms)))
1512 (setq todo-categories (delete (assoc cat todo-categories)
1514 (todo-update-categories-sexp)
1515 (when (> todo-category-number (length todo-categories))
1516 (setq todo-category-number 1))
1517 (todo-category-select)))))
1518 (set-window-buffer (selected-window)
1519 (set-buffer (find-file-noselect nfile)))
1520 (todo-category-number (or new cat))
1521 (todo-category-select))))
1523 (defun todo-merge-category (&optional file)
1524 "Merge current category into another existing category.
1526 With prefix argument FILE, prompt for a specific todo file and
1527 choose (with TAB completion) a category in it to merge into;
1528 otherwise, choose and merge into a category in either the
1529 current todo file or a file in `todo-category-completions-files'.
1531 After merging, the source category's todo and done items are
1532 appended to the chosen goal category's todo and done items,
1533 respectively. The goal category becomes the current category,
1534 and the source category is deleted.
1536 If both the source and goal categories also have archived items,
1537 they are also merged. If only the source category has archived
1538 items, the goal category is added as a new category to the
1539 archive file and the source category is deleted."
1541 (let* ((tfile todo-current-todo-file)
1542 (cat (todo-current-category))
1543 (cat+file (todo-read-category "Merge into category: " 'todo file))
1544 (goal (car cat+file))
1545 (gfile (cdr cat+file))
1546 (tarchive (concat (file-name-sans-extension tfile) ".toda"))
1547 (garchive (concat (file-name-sans-extension gfile) ".toda"))
1548 (archived-count (todo-get-count 'archived))
1550 (with-current-buffer (get-buffer (find-file-noselect tfile))
1552 (let* ((buffer-read-only nil)
1555 (concat "^" (regexp-quote todo-category-beg)) nil t)
1557 (tbeg (progn (forward-line) (point-marker)))
1560 (concat "^" (regexp-quote todo-category-done)) nil t)
1561 (forward-line) (point-marker)))
1562 ;; Omit empty line between todo and done items.
1563 (tend (progn (forward-line -2) (point-marker)))
1565 (if (re-search-forward
1566 (concat "^" (regexp-quote todo-category-beg)) nil t)
1568 (goto-char (match-beginning 0))
1570 (point-max-marker))))
1571 (todo (buffer-substring-no-properties tbeg tend))
1572 (done (buffer-substring-no-properties dbeg cend))
1573 (todo-count (todo-get-count 'todo cat))
1574 (done-count (todo-get-count 'done cat)))
1575 ;; Merge into goal todo category.
1576 (with-current-buffer (get-buffer (find-file-noselect gfile))
1577 (unless (derived-mode-p 'todo-mode) (todo-mode))
1579 (goto-char (point-min))
1580 (let ((buffer-read-only nil))
1581 ;; Merge any todo items.
1582 (unless (zerop (length todo))
1584 (concat "^" (regexp-quote (concat todo-category-beg goal)) "$")
1587 (concat "^" (regexp-quote todo-category-done)) nil t)
1589 (setq here (point-marker))
1591 (todo-update-count 'todo todo-count goal))
1592 ;; Merge any done items.
1593 (unless (zerop (length done))
1594 (goto-char (if (re-search-forward
1595 (concat "^" (regexp-quote todo-category-beg))
1599 (when (zerop (length todo)) (setq here (point-marker)))
1601 (todo-update-count 'done done-count goal)))
1602 (todo-update-categories-sexp))
1603 ;; Update and clean up source todo file.
1604 (remove-overlays cbeg cend)
1605 (delete-region cbeg cend)
1606 (setq todo-categories (delete (assoc cat todo-categories)
1608 (todo-update-categories-sexp)
1609 (when (> todo-category-number (length todo-categories))
1610 (setq todo-category-number 1))
1611 (todo-category-select)
1612 (mapc (lambda (m) (set-marker m nil))
1613 (list cbeg tbeg dbeg tend cend))))
1614 (when (> archived-count 0)
1615 (with-current-buffer (get-buffer (find-file-noselect tarchive))
1617 (goto-char (point-min))
1618 (let* ((buffer-read-only nil)
1620 (when (re-search-forward
1621 (concat "^" (regexp-quote
1622 (concat todo-category-beg cat)) "$")
1624 (goto-char (match-beginning 0))
1626 (cend (if (re-search-forward
1627 (concat "^" (regexp-quote todo-category-beg)) nil t)
1633 (buffer-substring-no-properties (point) cend))))
1634 ;; Merge into goal archive category, if it exists, else create it.
1635 (with-current-buffer (get-buffer (find-file-noselect garchive))
1636 (let ((gbeg (when (re-search-forward
1637 (concat "^" (regexp-quote
1638 (concat todo-category-beg goal))
1641 (goto-char (match-beginning 0))
1643 (goto-char (if (and gbeg
1645 (concat "^" (regexp-quote todo-category-beg))
1649 (unless gbeg (todo-add-category nil goal))
1651 (todo-update-categories-sexp)))
1652 ;; Update and clean up source archive file.
1653 (remove-overlays cbeg cend)
1654 (delete-region cbeg cend)
1655 (setq todo-categories (todo-make-categories-list t))
1656 (todo-update-categories-sexp))))
1657 ;; Update goal todo file for merged archived items and display it.
1658 (set-window-buffer (selected-window) (set-buffer (get-file-buffer gfile)))
1659 (unless (zerop archived-count)
1660 (todo-update-count 'archived archived-count goal)
1661 (todo-update-categories-sexp))
1662 (todo-category-number goal)
1663 ;; If there are only merged done items, show them.
1664 (let ((todo-show-with-done (zerop (todo-get-count 'todo goal))))
1665 (todo-category-select)
1666 ;; Put point on the first merged item.
1668 (set-marker here nil)))
1670 ;; -----------------------------------------------------------------------------
1672 ;; -----------------------------------------------------------------------------
1674 (defcustom todo-include-in-diary nil
1675 "Non-nil to allow new todo items to be included in the diary."
1679 (defcustom todo-diary-nonmarking nil
1680 "Non-nil to insert new todo diary items as nonmarking by default.
1681 This appends `diary-nonmarking-symbol' to the front of an item on
1682 insertion provided it doesn't begin with `todo-nondiary-marker'."
1686 (defcustom todo-always-add-time-string nil
1687 "Non-nil adds current time to a new item's date header by default.
1688 When the todo insertion commands have a non-nil \"maybe-notime\"
1689 argument, this reverses the effect of
1690 `todo-always-add-time-string': if t, these commands omit the
1691 current time, if nil, they include it."
1695 (defcustom todo-use-only-highlighted-region t
1696 "Non-nil to enable inserting only highlighted region as new item."
1700 (defcustom todo-default-priority 'first
1701 "Default priority of new and moved items."
1702 :type '(choice (const :tag "Highest priority" first)
1703 (const :tag "Lowest priority" last))
1706 (defcustom todo-item-mark "*"
1707 "String used to mark items.
1708 To ensure item marking works, change the value of this option
1709 only when no items are marked."
1710 :type '(string :validate
1712 (when (string= (widget-value widget) todo-prefix)
1715 "Invalid value: must be distinct from `todo-prefix'")
1717 :set (lambda (symbol value)
1718 (custom-set-default symbol (propertize value 'face 'todo-mark)))
1721 (defcustom todo-comment-string "COMMENT"
1722 "String inserted before optional comment appended to done item."
1724 :initialize 'custom-initialize-default
1725 :set 'todo-reset-comment-string
1728 (defcustom todo-undo-item-omit-comment 'ask
1729 "Whether to omit done item comment on undoing the item.
1730 Nil means never omit the comment, t means always omit it, `ask'
1731 means prompt user and omit comment only on confirmation."
1732 :type '(choice (const :tag "Never" nil)
1733 (const :tag "Always" t)
1734 (const :tag "Ask" ask))
1737 (defun todo-toggle-mark-item (&optional n)
1738 "Mark item with `todo-item-mark' if unmarked, otherwise unmark it.
1739 With a positive numerical prefix argument N, change the
1740 marking of the next N items."
1742 (when (todo-item-string)
1743 (unless (> n 1) (setq n 1))
1745 (let* ((cat (todo-current-category))
1746 (marks (assoc cat todo-categories-with-marks))
1748 (unless (looking-at todo-item-start)
1750 (todo-get-overlay 'prefix)))
1751 (pref (overlay-get ov 'before-string)))
1752 (if (todo-marked-item-p)
1754 (overlay-put ov 'before-string (substring pref 1))
1755 (if (= (cdr marks) 1) ; Deleted last mark in this category.
1756 (setq todo-categories-with-marks
1757 (assq-delete-all cat todo-categories-with-marks))
1758 (setcdr marks (1- (cdr marks)))))
1759 (overlay-put ov 'before-string (concat todo-item-mark pref))
1761 (setcdr marks (1+ (cdr marks)))
1762 (push (cons cat 1) todo-categories-with-marks))))
1763 (todo-forward-item))))
1765 (defun todo-mark-category ()
1766 "Mark all visible items in this category with `todo-item-mark'."
1768 (let* ((cat (todo-current-category))
1769 (marks (assoc cat todo-categories-with-marks)))
1771 (goto-char (point-min))
1773 (let* ((ov (todo-get-overlay 'prefix))
1774 (pref (overlay-get ov 'before-string)))
1775 (unless (todo-marked-item-p)
1776 (overlay-put ov 'before-string (concat todo-item-mark pref))
1778 (setcdr marks (1+ (cdr marks)))
1779 (push (cons cat 1) todo-categories-with-marks))))
1780 (todo-forward-item)))))
1782 (defun todo-unmark-category ()
1783 "Remove `todo-item-mark' from all visible items in this category."
1785 (let* ((cat (todo-current-category))
1786 (marks (assoc cat todo-categories-with-marks)))
1788 (goto-char (point-min))
1790 (let* ((ov (todo-get-overlay 'prefix))
1791 ;; No overlay on empty line between todo and done items.
1792 (pref (when ov (overlay-get ov 'before-string))))
1793 (when (todo-marked-item-p)
1794 (overlay-put ov 'before-string (substring pref 1)))
1795 (todo-forward-item))))
1796 (setq todo-categories-with-marks
1797 (delq marks todo-categories-with-marks))))
1799 (defvar todo-date-from-calendar nil
1800 "Helper variable for setting item date from the Emacs Calendar.")
1802 (defvar todo-insert-item--keys-so-far)
1803 (defvar todo-insert-item--parameters)
1805 (defun todo-insert-item (&optional arg)
1806 "Choose an item insertion operation and carry it out.
1807 This inserts a new todo item into a category.
1809 With no prefix argument ARG, add the item to the current
1810 category; with one prefix argument (`C-u'), prompt for a category
1811 from the current todo file; with two prefix arguments (`C-u
1812 C-u'), first prompt for a todo file, then a category in that
1813 file. If a non-existing category is entered, ask whether to add
1814 it to the todo file; if answered affirmatively, add the category
1815 and insert the item there.
1817 There are a number of item insertion parameters which can be
1818 combined by entering specific keys to produce different insertion
1819 commands. After entering each key, a message shows which have
1820 already been entered and which remain available. See
1821 `(todo-mode) Inserting New Items' for details of the parameters,
1822 their associated keys and their effects."
1824 (setq todo-insert-item--keys-so-far "i")
1825 (todo-insert-item--next-param nil (list arg) todo-insert-item--parameters))
1827 (defun todo-insert-item--basic (&optional arg diary-type date-type time where)
1828 "Function implementing the core of `todo-insert-item'."
1829 ;; If invoked outside of Todo mode and there is not yet any Todo
1830 ;; file, initialize one.
1831 (if (null (funcall todo-files-function))
1833 (let ((copy (eq where 'copy))
1834 (region (eq where 'region))
1835 (here (eq where 'here))
1839 ((not (eq major-mode 'todo-mode))
1840 (user-error "You must be in Todo mode to copy a todo item"))
1842 (user-error "You cannot copy a done item as a new todo item"))
1844 (user-error "Point must be on a todo item to copy it")))
1845 (setq diary-item (todo-diary-item-p)))
1847 (let (use-empty-active-region)
1848 (unless (and todo-use-only-highlighted-region (use-region-p))
1849 (user-error "There is no active region"))))
1850 (let* ((obuf (current-buffer))
1851 (ocat (todo-current-category))
1853 (todo-mm (eq major-mode 'todo-mode))
1854 (cat+file (cond ((equal arg '(4))
1855 (todo-read-category "Insert in category: "))
1857 (todo-read-category "Insert in category: "
1860 (cons (todo-current-category)
1861 (or todo-current-todo-file
1862 (and todo-show-current-file
1863 todo-global-current-todo-file)
1864 (todo-absolute-file-name
1865 todo-default-todo-file))))))
1866 (cat (car cat+file))
1867 (file (cdr cat+file))
1868 (new-item (cond (copy (todo-item-string))
1869 (region (buffer-substring-no-properties
1870 (region-beginning) (region-end)))
1871 (t (read-from-minibuffer "Todo item: "))))
1873 ((eq date-type 'date)
1875 ((eq date-type 'dayname)
1876 (todo-read-dayname))
1877 ((eq date-type 'calendar)
1878 (setq todo-date-from-calendar t)
1879 (or (todo-set-date-from-calendar)
1880 ;; If user exits Calendar before choosing
1881 ;; a date, cancel item insertion.
1883 ((and (stringp date-type)
1884 (string-match todo-date-pattern date-type))
1885 (setq todo-date-from-calendar date-type)
1886 (todo-set-date-from-calendar))
1888 (calendar-date-string
1889 (calendar-current-date) t t))))
1890 (time-string (or (and time (todo-read-time))
1891 (and todo-always-add-time-string
1892 (substring (current-time-string) 11 16)))))
1893 (setq todo-date-from-calendar nil)
1894 (find-file-noselect file 'nowarn)
1895 (set-window-buffer (selected-window)
1896 (set-buffer (find-buffer-visiting file)))
1897 ;; If this command was invoked outside of a Todo mode buffer,
1898 ;; the call to todo-current-category above returned nil. If
1899 ;; we just entered Todo mode now, then cat was set to the
1900 ;; file's first category, but if todo-mode was already
1901 ;; enabled, cat did not get set, so we have to do that.
1903 (setq cat (todo-current-category)))
1904 (setq todo-current-todo-file file)
1905 (unless todo-global-current-todo-file
1906 (setq todo-global-current-todo-file todo-current-todo-file))
1907 (let ((buffer-read-only nil)
1908 (called-from-outside (not (and todo-mm (equal cat ocat))))
1909 done-only item-added)
1912 ;; Add date, time and diary marking as required.
1913 (concat (if (not (and diary-type
1914 (not todo-include-in-diary)))
1916 (when (and (eq diary-type 'nonmarking)
1917 (not todo-diary-nonmarking))
1918 diary-nonmarking-symbol))
1919 date-string (when (and time-string ; Can be empty.
1922 (concat " " time-string))
1923 (when (not (and diary-type
1924 (not todo-include-in-diary)))
1927 ;; Indent newlines inserted by C-q C-j if nonspace char follows.
1928 (setq new-item (replace-regexp-in-string "\\(\n\\)[^[:blank:]]"
1929 "\n\t" new-item nil nil 1)))
1932 ;; Make sure the correct category is selected. There
1933 ;; are two cases: (i) we just visited the file, so no
1934 ;; category is selected yet, or (ii) we invoked
1935 ;; insertion "here" from outside the category we want
1936 ;; to insert in (with priority insertion, category
1937 ;; selection is done by todo-set-item-priority).
1938 (when (or (= (- (point-max) (point-min)) (buffer-size))
1939 (and here called-from-outside))
1940 (todo-category-number cat)
1941 (todo-category-select))
1942 ;; If only done items are displayed in category,
1943 ;; toggle to todo items before inserting new item.
1944 (when (save-excursion
1945 (goto-char (point-min))
1946 (looking-at todo-done-string-start))
1948 (todo-toggle-view-done-only))
1951 ;; If command was invoked with point in done
1952 ;; items section or outside of the current
1953 ;; category, can't insert "here", so to be
1954 ;; useful give new item top priority.
1955 (when (or (todo-done-item-section-p)
1958 (goto-char (point-min)))
1959 (todo-insert-with-overlays new-item))
1960 (todo-set-item-priority new-item cat t))
1961 (setq item-added t))
1962 ;; If user cancels before setting priority, restore
1965 (set-window-buffer (selected-window) (set-buffer obuf))
1967 (unless (equal cat ocat)
1968 (todo-category-number ocat)
1969 (todo-category-select))
1970 (and done-only (todo-toggle-view-done-only)))
1972 ;; If the todo items section is not visible when the
1973 ;; insertion command is called (either because only done
1974 ;; items were shown or because the category was not in the
1975 ;; current buffer), then if the item is inserted at the
1976 ;; end of the category, point is at eob and eob at
1977 ;; window-start, so that higher priority todo items are
1978 ;; out of view. So we recenter to make sure the todo
1979 ;; items are displayed in the window.
1980 (when item-added (recenter)))
1981 (todo-update-count 'todo 1)
1982 (when (or diary-item diary-type todo-include-in-diary)
1983 (todo-update-count 'diary 1))
1984 (todo-update-categories-sexp))))))
1986 (defun todo-set-date-from-calendar ()
1987 "Return string of date chosen from Calendar."
1988 (cond ((and (stringp todo-date-from-calendar)
1989 (string-match todo-date-pattern todo-date-from-calendar))
1990 todo-date-from-calendar)
1991 (todo-date-from-calendar
1992 (let (calendar-view-diary-initially-flag)
1993 (calendar)) ; *Calendar* is now current buffer.
1994 (define-key calendar-mode-map [remap newline] 'exit-recursive-edit)
1995 ;; If user exits Calendar before choosing a date, clean up properly.
1996 (define-key calendar-mode-map
1997 [remap calendar-exit] (lambda ()
2001 (exit-recursive-edit))))
2002 (message "Put cursor on a date and type <return> to set it.")
2005 (when (equal (buffer-name) calendar-buffer)
2006 (setq todo-date-from-calendar
2007 (calendar-date-string (calendar-cursor-to-date t) t t))
2009 todo-date-from-calendar)
2010 (define-key calendar-mode-map [remap newline] nil)
2011 (define-key calendar-mode-map [remap calendar-exit] nil)
2012 (unless (zerop (recursion-depth)) (exit-recursive-edit))
2013 (when (stringp todo-date-from-calendar)
2014 todo-date-from-calendar)))))
2016 (defun todo-insert-item-from-calendar (&optional arg)
2017 "Prompt for and insert a new item with date selected from calendar.
2018 Invoked without prefix argument ARG, insert the item into the
2019 current category, without one prefix argument, prompt for the
2020 category from the current todo file or from one listed in
2021 `todo-category-completions-files'; with two prefix arguments,
2022 prompt for a todo file and then for a category in it."
2024 (setq todo-date-from-calendar
2025 (calendar-date-string (calendar-cursor-to-date t) t t))
2027 (todo-insert-item--basic arg nil todo-date-from-calendar))
2029 (define-key calendar-mode-map "it" 'todo-insert-item-from-calendar)
2031 (defun todo-delete-item ()
2032 "Delete at least one item in this category.
2033 If there are marked items, delete all of these; otherwise, delete
2038 (let* ((cat (todo-current-category))
2039 (marked (assoc cat todo-categories-with-marks))
2040 (item (unless marked (todo-item-string)))
2043 "Permanently delete all marked items? ")
2045 (setq ov (make-overlay
2046 (save-excursion (todo-item-start))
2047 (save-excursion (todo-item-end))))
2048 (overlay-put ov 'face 'todo-search)
2049 (todo-y-or-n-p "Permanently delete this item? "))))
2052 (and marked (goto-char (point-min)))
2055 (if (or (and marked (todo-marked-item-p)) item)
2057 (if (todo-done-item-p)
2058 (todo-update-count 'done -1)
2059 (todo-update-count 'todo -1 cat)
2060 (and (todo-diary-item-p)
2061 (todo-update-count 'diary -1)))
2062 (if ov (delete-overlay ov))
2064 ;; Don't leave point below last item.
2065 (and item (bolp) (eolp) (< (point-min) (point-max))
2066 (todo-backward-item))
2068 (throw 'done (setq item nil))))
2069 (todo-forward-item))))
2071 (setq todo-categories-with-marks
2072 (assq-delete-all cat todo-categories-with-marks)))
2073 (todo-update-categories-sexp)
2074 (todo-prefix-overlays)))
2075 (if ov (delete-overlay ov)))))
2077 (defvar todo-edit-item--param-key-alist)
2078 (defvar todo-edit-done-item--param-key-alist)
2080 (defun todo-edit-item (&optional arg)
2081 "Choose an editing operation for the current item and carry it out."
2083 (cond ((todo-done-item-p)
2084 (todo-edit-item--next-key todo-edit-done-item--param-key-alist))
2086 (todo-edit-item--next-key todo-edit-item--param-key-alist arg))))
2088 (defun todo-edit-item--text (&optional arg)
2089 "Function providing the text editing facilities of `todo-edit-item'."
2090 (let* ((opoint (point))
2091 (start (todo-item-start))
2092 (end (save-excursion (todo-item-end)))
2095 (concat todo-date-string-start todo-date-pattern
2096 "\\( " diary-time-regexp "\\)?"
2097 (regexp-quote todo-nondiary-end) "?")
2098 (line-end-position) t)
2099 (1+ (- (point) start))))
2100 (include-header (eq arg 'include-header))
2101 (comment-edit (eq arg 'comment-edit))
2102 (comment-delete (eq arg 'comment-delete))
2103 (header-string (substring (todo-item-string) 0 item-beg))
2104 (item (if (or include-header comment-edit comment-delete)
2106 (substring (todo-item-string) item-beg)))
2107 (multiline (> (length (split-string item "\n")) 1))
2108 (comment (save-excursion
2111 (concat " \\[" (regexp-quote todo-comment-string)
2112 ": \\([^]]+\\)\\]") end t)))
2113 (prompt (if comment "Edit comment: " "Enter a comment: "))
2114 (buffer-read-only nil))
2116 ((or comment-edit comment-delete)
2119 (if (re-search-forward (concat " \\[" (regexp-quote todo-comment-string)
2120 ": \\([^]]+\\)\\]") end t)
2122 (when (todo-y-or-n-p "Delete comment? ")
2123 (delete-region (match-beginning 0) (match-end 0)))
2124 (replace-match (read-string prompt (cons (match-string 1) 1))
2127 (user-error "There is no comment to delete")
2128 (insert " [" todo-comment-string ": "
2129 (prog1 (read-string prompt)
2130 ;; If user moved point during editing,
2131 ;; make sure it moves back.
2135 ((or multiline (eq arg 'multiline))
2136 (let ((buf todo-edit-buffer))
2137 (set-window-buffer (selected-window)
2138 (set-buffer (make-indirect-buffer (buffer-name) buf)))
2139 (narrow-to-region (todo-item-start) (todo-item-end))
2141 (message "%s" (substitute-command-keys
2142 (concat "Type \\[todo-edit-quit] "
2143 "to return to Todo mode.\n")))))
2145 (let ((new (concat (if include-header "" header-string)
2146 (read-string "Edit: " (if include-header
2147 (cons item item-beg)
2149 (when include-header
2150 (while (not (string-match (concat todo-date-string-start
2151 todo-date-pattern) new))
2152 (setq new (read-from-minibuffer
2153 "Item must start with a date: " new))))
2154 ;; Ensure lines following hard newlines are indented.
2155 (setq new (replace-regexp-in-string "\\(\n\\)[^[:blank:]]"
2156 "\n\t" new nil nil 1))
2157 ;; If user moved point during editing, make sure it moves back.
2160 (todo-insert-with-overlays new)
2161 (move-to-column item-beg))))))
2163 (defun todo-edit-quit ()
2164 "Return from Todo Edit mode to Todo mode.
2165 If the item contains hard line breaks, make sure the following
2166 lines are indented by `todo-indent-to-here' to conform to diary
2169 If the whole file was in Todo Edit mode, check before returning
2170 whether the file is still a valid todo file and if so, also
2171 recalculate the todo file's categories sexp, in case changes were
2172 made in the number or names of categories."
2174 (if (> (buffer-size) (- (point-max) (point-min)))
2175 ;; We got here via `e m'.
2176 (let ((item (buffer-string))
2177 (regex "\\(\n\\)[^[:blank:]]")
2178 (buf (buffer-base-buffer)))
2179 (while (not (string-match (concat todo-date-string-start
2180 todo-date-pattern) item))
2181 (setq item (read-from-minibuffer
2182 "Item must start with a date: " item)))
2183 ;; Ensure lines following hard newlines are indented.
2184 (when (string-match regex (buffer-string))
2185 (setq item (replace-regexp-in-string regex "\n\t" item nil nil 1))
2186 (delete-region (point-min) (point-max))
2189 (unless (eq (current-buffer) buf)
2190 (set-window-buffer (selected-window) (set-buffer buf))))
2191 ;; We got here via `F e'.
2192 (when (todo-check-format)
2193 ;; FIXME: separate out sexp check?
2194 ;; If manual editing makes e.g. item counts change, have to
2195 ;; call this to update todo-categories, but it restores
2196 ;; category order to list order.
2197 ;; (todo-repair-categories-sexp)
2198 ;; Compare (todo-make-categories-list t) with sexp and if
2199 ;; different ask (todo-update-categories-sexp) ?
2201 (let* ((cat-beg (concat "^" (regexp-quote todo-category-beg)
2203 (curline (buffer-substring-no-properties
2204 (line-beginning-position) (line-end-position)))
2205 (cat (cond ((string-match cat-beg curline)
2206 (match-string-no-properties 1 curline))
2207 ((or (re-search-backward cat-beg nil t)
2208 (re-search-forward cat-beg nil t))
2209 (match-string-no-properties 1)))))
2210 (todo-category-number cat)
2211 (todo-category-select)
2212 (goto-char (point-min))))))
2214 (defun todo-edit-item--header (what &optional inc)
2215 "Function providing header editing facilities of `todo-edit-item'."
2216 (let* ((cat (todo-current-category))
2217 (marked (assoc cat todo-categories-with-marks))
2219 (todo-date-from-calendar t)
2220 ;; INC must be an integer, but users could pass it via
2221 ;; `todo-edit-item' as e.g. `-' or `C-u'.
2222 (inc (prefix-numeric-value inc))
2223 (buffer-read-only nil)
2224 ndate ntime year monthname month day
2225 dayname) ; Needed by calendar-date-display-form.
2227 (or (and marked (goto-char (point-min))) (todo-item-start))
2231 (while (not (todo-marked-item-p))
2233 (and (eobp) (throw 'end nil))))
2234 (re-search-forward (concat todo-date-string-start "\\(?1:"
2236 "\\)\\(?2: " diary-time-regexp "\\)?"
2237 (regexp-quote todo-nondiary-end) "?")
2238 (line-end-position) t)
2239 (let* ((odate (match-string-no-properties 1))
2240 (otime (match-string-no-properties 2))
2241 (odayname (match-string-no-properties 5))
2242 (omonthname (match-string-no-properties 6))
2243 (omonth (match-string-no-properties 7))
2244 (oday (match-string-no-properties 8))
2245 (oyear (match-string-no-properties 9))
2246 (tmn-array todo-month-name-array)
2247 (mlist (append tmn-array nil))
2248 (tma-array todo-month-abbrev-array)
2249 (mablist (append tma-array nil))
2250 (yy (and oyear (unless (string= oyear "*")
2251 (string-to-number oyear))))
2252 (mm (or (and omonth (unless (string= omonth "*")
2253 (string-to-number omonth)))
2254 (1+ (- (length mlist)
2255 (length (or (member omonthname mlist)
2256 (member omonthname mablist)))))))
2257 (dd (and oday (unless (string= oday "*")
2258 (string-to-number oday)))))
2259 ;; If there are marked items, use only the first to set
2260 ;; header changes, and apply these to all marked items.
2264 (setq ndate (todo-read-date)))
2265 ((eq what 'calendar)
2266 (setq ndate (save-match-data (todo-set-date-from-calendar))))
2268 (setq ndate (calendar-date-string (calendar-current-date) t t)))
2270 (setq ndate (todo-read-dayname)))
2272 (setq ntime (save-match-data (todo-read-time)))
2273 (when (> (length ntime) 0)
2274 (setq ntime (concat " " ntime))))
2275 ;; When date string consists only of a day name,
2276 ;; passing other date components is a noop.
2277 ((and odayname (memq what '(year month day))))
2280 monthname omonthname
2282 year (cond ((not current-prefix-arg)
2283 (todo-read-date 'year))
2284 ((string= oyear "*")
2285 (user-error "Cannot increment *"))
2287 (number-to-string (+ yy inc))))))
2291 (if (memq 'month calendar-date-display-form)
2294 (cond ((not current-prefix-arg)
2295 (todo-read-date 'month))
2296 ((or (string= omonth "*") (= mm 13))
2297 (user-error "Cannot increment *"))
2299 (let ((mminc (+ mm inc)))
2300 ;; Increment or decrement month by INC
2302 (setq mm (% mminc 12))
2303 ;; If result is 0, make month December.
2304 (setq mm (if (= mm 0) 12 (abs mm)))
2305 ;; Adjust year if necessary.
2306 (setq year (or (and (cond ((> mminc 12)
2307 (+ yy (/ mminc 12)))
2309 (- yy (/ mminc 12) 1))
2311 (number-to-string yy))
2313 ;; Return the changed numerical month as
2314 ;; a string or the corresponding month name.
2316 (number-to-string mm)
2317 (aref tma-array (1- mm))))))
2318 (let ((yy (string-to-number year)) ; 0 if year is "*".
2319 ;; When mm is 13 (corresponding to "*" as value
2320 ;; of month), this raises an args-out-of-range
2321 ;; error in calendar-last-day-of-month, so use 1
2322 ;; (corresponding to January) to get 31 days.
2323 (mm (if (= mm 13) 1 mm)))
2324 (if (> (string-to-number day)
2325 (calendar-last-day-of-month mm yy))
2326 (user-error "%s %s does not have %s days"
2327 (aref tmn-array (1- mm))
2328 (if (= mm 2) yy "") day))))
2332 monthname omonthname
2334 ((not current-prefix-arg)
2335 (todo-read-date 'day mm oyear))
2337 (user-error "Cannot increment *"))
2338 ((or (string= omonth "*") (string= omonthname "*"))
2339 (setq dd (+ dd inc))
2342 "A month cannot have more than 31 days")
2343 (number-to-string dd)))
2344 ;; Increment or decrement day by INC,
2345 ;; adjusting month and year if necessary
2346 ;; (if year is "*" assume current year to
2347 ;; calculate adjustment).
2349 (let* ((yy (or yy (calendar-extract-year
2350 (calendar-current-date))))
2351 (date (calendar-gregorian-from-absolute
2352 (+ (calendar-absolute-from-gregorian
2353 (list mm dd yy)) inc)))
2354 (adjmm (nth 0 date)))
2355 ;; Set year and month(name) to adjusted values.
2356 (unless (string= year "*")
2357 (setq year (number-to-string (nth 2 date))))
2359 (setq month (number-to-string adjmm))
2360 (setq monthname (aref tma-array (1- adjmm))))
2361 ;; Return changed numerical day as a string.
2362 (number-to-string (nth 1 date)))))))))
2364 ;; If year, month or day date string components were
2365 ;; changed, rebuild the date string.
2366 (when (memq what '(year month day))
2367 (setq ndate (mapconcat 'eval calendar-date-display-form ""))))
2368 (when ndate (replace-match ndate nil nil nil 1))
2369 ;; Add new time string to the header, if it was supplied.
2372 (replace-match ntime nil nil nil 2)
2373 (goto-char (match-end 1))
2375 (setq todo-date-from-calendar nil)
2377 ;; Apply the changes to the first marked item header to the
2378 ;; remaining marked items. If there are no marked items,
2382 (goto-char (point-max))))))))
2384 (defun todo-edit-item--diary-inclusion (&optional nonmarking)
2385 "Function providing diary marking facilities of `todo-edit-item'."
2386 (let ((buffer-read-only)
2387 (marked (assoc (todo-current-category)
2388 todo-categories-with-marks)))
2391 (when marked (goto-char (point-min)))
2393 (if (todo-done-item-p)
2394 (throw 'stop (message "Done items cannot be edited"))
2395 (unless (and marked (not (todo-marked-item-p)))
2396 (let* ((beg (todo-item-start))
2397 (lim (save-excursion (todo-item-end)))
2398 (end (save-excursion
2399 (or (todo-time-string-matcher lim)
2400 (todo-date-string-matcher lim)))))
2402 (if (looking-at (regexp-quote diary-nonmarking-symbol))
2404 (when (looking-at (regexp-quote todo-nondiary-start))
2407 (search-forward todo-nondiary-end (1+ end) t)
2409 (todo-update-count 'diary 1)))
2410 (insert diary-nonmarking-symbol))
2411 (if (looking-at (regexp-quote todo-nondiary-start))
2414 (search-forward todo-nondiary-end (1+ end) t)
2416 (todo-update-count 'diary 1))
2418 (when (looking-at (regexp-quote diary-nonmarking-symbol))
2420 (setq end (1- end))) ; Since we deleted nonmarking symbol.
2421 (insert todo-nondiary-start)
2422 (goto-char (1+ end))
2423 (insert todo-nondiary-end)
2424 (todo-update-count 'diary -1))))))
2425 (unless marked (throw 'stop nil))
2426 (todo-forward-item)))))
2427 (todo-update-categories-sexp)))
2429 (defun todo-edit-category-diary-inclusion (arg)
2430 "Make all items in this category diary items.
2431 With prefix ARG, make all items in this category non-diary
2435 (goto-char (point-min))
2436 (let ((todo-count (todo-get-count 'todo))
2437 (diary-count (todo-get-count 'diary))
2441 (if (todo-done-item-p) ; We've gone too far.
2443 (let* ((beg (todo-item-start))
2444 (lim (save-excursion (todo-item-end)))
2445 (end (save-excursion
2446 (or (todo-time-string-matcher lim)
2447 (todo-date-string-matcher lim)))))
2449 (unless (looking-at (regexp-quote todo-nondiary-start))
2450 (when (looking-at (regexp-quote diary-nonmarking-symbol))
2452 (setq end (1- end))) ; Since we deleted nonmarking symbol.
2453 (insert todo-nondiary-start)
2454 (goto-char (1+ end))
2455 (insert todo-nondiary-end))
2456 (when (looking-at (regexp-quote todo-nondiary-start))
2458 (search-forward todo-nondiary-end (1+ end) t)
2459 (replace-match "")))))
2460 (todo-forward-item))
2461 (unless (if arg (zerop diary-count) (= diary-count todo-count))
2462 (todo-update-count 'diary (if arg
2464 (- todo-count diary-count))))
2465 (todo-update-categories-sexp)))))
2467 (defun todo-edit-category-diary-nonmarking (arg)
2468 "Add `diary-nonmarking-symbol' to all diary items in this category.
2469 With prefix ARG, remove `diary-nonmarking-symbol' from all diary
2470 items in this category."
2473 (goto-char (point-min))
2474 (let (buffer-read-only)
2477 (if (todo-done-item-p) ; We've gone too far.
2479 (unless (looking-at (regexp-quote todo-nondiary-start))
2481 (when (looking-at (regexp-quote diary-nonmarking-symbol))
2483 (unless (looking-at (regexp-quote diary-nonmarking-symbol))
2484 (insert diary-nonmarking-symbol))))
2485 (todo-forward-item)))))))
2487 (defun todo-set-item-priority (&optional item cat new arg)
2488 "Prompt for and set ITEM's priority in CATegory.
2490 Interactively, ITEM is the todo item at point, CAT is the current
2491 category, and the priority is a number between 1 and the number
2492 of items in the category. Non-interactively, non-nil NEW means
2493 ITEM is a new item and the lowest priority is one more than the
2494 number of items in CAT.
2496 The new priority is set either interactively by prompt or by a
2497 numerical prefix argument, or noninteractively by argument ARG,
2498 whose value can be either of the symbols `raise' or `lower',
2499 meaning to raise or lower the item's priority by one."
2501 (unless (and (called-interactively-p 'any)
2502 (or (todo-done-item-p) (looking-at "^$")))
2503 (let* ((item (or item (todo-item-string)))
2504 (marked (todo-marked-item-p))
2505 (cat (or cat (cond ((eq major-mode 'todo-mode)
2506 (todo-current-category))
2507 ((eq major-mode 'todo-filtered-items-mode)
2509 (concat todo-date-string-start
2511 "\\( " diary-time-regexp "\\)?"
2512 (regexp-quote todo-nondiary-end)
2513 "?\\(?1: \\[\\(.+:\\)?.+\\]\\)")))
2515 (re-search-forward regexp1 nil t)
2516 (match-string-no-properties 1)))))))
2518 (todo (cond ((or (eq arg 'raise) (eq arg 'lower)
2519 (eq major-mode 'todo-filtered-items-mode))
2521 (let ((curstart (todo-item-start))
2523 (goto-char (point-min))
2524 (while (looking-at todo-item-start)
2525 (setq count (1+ count))
2526 (when (= (point) curstart) (setq curnum count))
2527 (todo-forward-item))
2529 ((eq major-mode 'todo-mode)
2530 (todo-get-count 'todo cat))))
2531 (maxnum (if new (1+ todo) todo))
2532 (prompt (format "Set item priority (1-%d): " maxnum))
2533 (priority (cond ((and (not arg) (numberp current-prefix-arg))
2535 ((and (eq arg 'raise) (>= curnum 1))
2537 ((and (eq arg 'lower) (<= curnum maxnum))
2541 (unless (and priority
2542 (or (and (eq arg 'raise) (zerop priority))
2543 (and (eq arg 'lower) (> priority maxnum))))
2544 ;; When moving item to another category, show the category before
2545 ;; prompting for its priority.
2546 (unless (or arg (called-interactively-p 'any))
2547 (todo-category-number cat)
2548 ;; If done items in category are visible, keep them visible.
2549 (let ((done todo-show-with-done))
2550 (when (> (buffer-size) (- (point-max) (point-min)))
2552 (goto-char (point-min))
2553 (setq done (re-search-forward todo-done-string-start nil t))))
2554 (let ((todo-show-with-done done))
2555 ;; Keep current item or top of moved to category in view
2556 ;; while setting priority.
2557 (save-excursion (todo-category-select)))))
2558 ;; Prompt for priority only when the category has at least one
2561 (while (not priority)
2562 (setq candidate (read-number prompt
2563 (if (eq todo-default-priority 'first)
2565 (setq prompt (when (or (< candidate 1) (> candidate maxnum))
2566 (format "Priority must be an integer between 1 and %d.\n"
2568 (unless prompt (setq priority candidate))))
2569 ;; In Top Priorities buffer, an item's priority can be changed
2570 ;; wrt items in another category, but not wrt items in the same
2572 (when (eq major-mode 'todo-filtered-items-mode)
2573 (let* ((regexp2 (concat todo-date-string-start todo-date-pattern
2574 "\\( " diary-time-regexp "\\)?"
2575 (regexp-quote todo-nondiary-end)
2576 "?\\(?1:" (regexp-quote cat) "\\)"))
2577 (end (cond ((< curnum priority)
2578 (save-excursion (todo-item-end)))
2579 ((> curnum priority)
2580 (save-excursion (todo-item-start)))))
2581 (match (save-excursion
2582 (cond ((< curnum priority)
2583 (todo-forward-item (1+ (- priority curnum)))
2584 (when (re-search-backward regexp2 end t)
2585 (match-string-no-properties 1)))
2586 ((> curnum priority)
2587 (todo-backward-item (- curnum priority))
2588 (when (re-search-forward regexp2 end t)
2589 (match-string-no-properties 1)))))))
2591 (user-error (concat "Cannot reprioritize items from the same "
2592 "category in this mode, only in Todo mode")))))
2593 ;; Interactively or with non-nil ARG, relocate the item within its
2595 (when (or arg (called-interactively-p 'any))
2597 (goto-char (point-min))
2599 (unless (= priority 1)
2600 (todo-forward-item (1- priority))
2601 ;; When called from todo-item-undone and the highest priority
2602 ;; is chosen, this advances point to the first done item, so
2603 ;; move it up to the empty line above the done items
2605 (when (looking-back (concat "^"
2606 (regexp-quote todo-category-done)
2608 (todo-backward-item))))
2609 (todo-insert-with-overlays item)
2610 ;; If item was marked, restore the mark.
2612 (let* ((ov (todo-get-overlay 'prefix))
2613 (pref (overlay-get ov 'before-string)))
2614 (overlay-put ov 'before-string
2615 (concat todo-item-mark pref))))))))
2617 (defun todo-raise-item-priority ()
2618 "Raise priority of current item by moving it up by one item."
2620 (todo-set-item-priority nil nil nil 'raise))
2622 (defun todo-lower-item-priority ()
2623 "Lower priority of current item by moving it down by one item."
2625 (todo-set-item-priority nil nil nil 'lower))
2627 (defun todo-move-item (&optional file)
2628 "Move at least one todo or done item to another category.
2629 If there are marked items, move all of these; otherwise, move
2632 With prefix argument FILE, prompt for a specific todo file and
2633 choose (with TAB completion) a category in it to move the item or
2634 items to; otherwise, choose and move to any category in either
2635 the current todo file or one of the files in
2636 `todo-category-completions-files'. If the chosen category is
2637 not an existing categories, then it is created and the item(s)
2638 become(s) the first entry/entries in that category.
2640 With moved todo items, prompt to set the priority in the category
2641 moved to (with multiple todo items, the one that had the highest
2642 priority in the category moved from gets the new priority and the
2643 rest of the moved todo items are inserted in sequence below it).
2644 Moved done items are appended to the top of the done items
2645 section in the category moved to."
2647 (let* ((cat1 (todo-current-category))
2648 (marked (assoc cat1 todo-categories-with-marks)))
2649 ;; Noop if point is not on an item and there are no marked items.
2650 (unless (and (looking-at "^$")
2652 (let* ((buffer-read-only)
2653 (file1 todo-current-todo-file)
2654 (num todo-category-number)
2655 (item (todo-item-string))
2656 (diary-item (todo-diary-item-p))
2657 (done-item (and (todo-done-item-p) (concat item "\n")))
2658 (omark (save-excursion (todo-item-start) (point-marker)))
2662 ov cat2 file2 moved nmark todo-items done-items)
2666 (setq ov (make-overlay (save-excursion (todo-item-start))
2667 (save-excursion (todo-item-end))))
2668 (overlay-put ov 'face 'todo-search))
2669 (let* ((pl (if (and marked (> (cdr marked) 1)) "s" ""))
2670 (cat+file (todo-read-category (concat "Move item" pl
2673 (while (and (equal (car cat+file) cat1)
2674 (equal (cdr cat+file) file1))
2675 (setq cat+file (todo-read-category
2676 "Choose a different category: ")))
2677 (setq cat2 (car cat+file)
2678 file2 (cdr cat+file))))
2679 (if ov (delete-overlay ov)))
2680 (set-buffer (find-buffer-visiting file1))
2683 (goto-char (point-min))
2685 (when (todo-marked-item-p)
2686 (if (todo-done-item-p)
2687 (setq done-items (concat done-items
2688 (todo-item-string) "\n")
2690 (setq todo-items (concat todo-items
2691 (todo-item-string) "\n")
2693 (when (todo-diary-item-p)
2694 (setq diary (1+ diary)))))
2695 (todo-forward-item))
2696 ;; Chop off last newline of multiple todo item string,
2697 ;; since it will be reinserted when setting priority
2698 ;; (but with done items priority is not set, so keep
2701 (setq todo-items (substring todo-items 0 -1))))
2702 (if (todo-done-item-p)
2705 (when (todo-diary-item-p) (setq diary 1))))
2706 (set-window-buffer (selected-window)
2707 (set-buffer (find-file-noselect file2 'nowarn)))
2710 (when (or todo-items (and item (not done-item)))
2711 (todo-set-item-priority (or todo-items item) cat2 t))
2712 ;; Move done items en bloc to top of done items section.
2713 (when (or done-items done-item)
2714 (todo-category-number cat2)
2716 (goto-char (point-min))
2718 (concat "^" (regexp-quote (concat todo-category-beg cat2))
2721 (concat "^" (regexp-quote todo-category-done)) nil t)
2723 (insert (or done-items done-item)))
2726 ;; Move succeeded, so remove item from starting category,
2727 ;; update item counts and display the category containing
2730 (setq nmark (point-marker))
2731 (when todo (todo-update-count 'todo todo))
2732 (when diary (todo-update-count 'diary diary))
2733 (when done (todo-update-count 'done done))
2734 (todo-update-categories-sexp)
2735 (with-current-buffer (find-buffer-visiting file1)
2744 (concat "^" (regexp-quote todo-category-beg)) nil t)
2747 (setq end (if (re-search-forward
2748 (concat "^" (regexp-quote
2749 todo-category-beg)) nil t)
2753 (while (< (point) end)
2754 (if (todo-marked-item-p)
2756 (todo-forward-item)))
2757 (setq todo-categories-with-marks
2758 (assq-delete-all cat1 todo-categories-with-marks)))
2759 (if ov (delete-overlay ov))
2760 (todo-remove-item))))
2761 (when todo (todo-update-count 'todo (- todo) cat1))
2762 (when diary (todo-update-count 'diary (- diary) cat1))
2763 (when done (todo-update-count 'done (- done) cat1))
2764 (todo-update-categories-sexp))
2765 (set-window-buffer (selected-window)
2766 (set-buffer (find-file-noselect file2 'nowarn)))
2767 (setq todo-category-number (todo-category-number cat2))
2768 (let ((todo-show-with-done (or done-items done-item)))
2769 (todo-category-select))
2771 ;; If item is moved to end of (just first?) category, make
2772 ;; sure the items above it are displayed in the window.
2774 ;; User quit before setting priority of todo item(s), so
2775 ;; return to starting category.
2777 (set-window-buffer (selected-window)
2778 (set-buffer (find-file-noselect file1 'nowarn)))
2779 (todo-category-number cat1)
2780 (todo-category-select)
2781 (goto-char omark))))))))
2783 (defun todo-item-done (&optional arg)
2784 "Tag a todo item in this category as done and relocate it.
2786 With prefix argument ARG prompt for a comment and append it to
2787 the done item; this is only possible if there are no marked
2788 items. If there are marked items, tag all of these with
2789 `todo-done-string' plus the current date and, if
2790 `todo-always-add-time-string' is non-nil, the current time;
2791 otherwise, just tag the item at point. Items tagged as done are
2792 relocated to the category's (by default hidden) done section. If
2793 done items are visible on invoking this command, they remain
2796 (let* ((cat (todo-current-category))
2797 (marked (assoc cat todo-categories-with-marks)))
2801 (goto-char (point-max))
2802 (todo-backward-item)
2803 (unless (todo-done-item-p)
2805 (unless (re-search-forward
2806 (concat "^" (regexp-quote todo-category-beg)) nil t)
2807 (goto-char (point-max)))
2809 (while (todo-done-item-p)
2810 (when (todo-marked-item-p)
2811 (user-error "This command does not apply to done items"))
2812 (todo-backward-item)))))
2813 (unless (and (not marked)
2814 (or (todo-done-item-p)
2815 ;; Point is between todo and done items.
2817 (let* ((date-string (calendar-date-string (calendar-current-date) t t))
2818 (time-string (if todo-always-add-time-string
2819 (concat " " (substring (current-time-string)
2822 (done-prefix (concat "[" todo-done-string date-string time-string
2824 (comment (and arg (read-string "Enter a comment: ")))
2827 (show-done (save-excursion
2828 (goto-char (point-min))
2829 (re-search-forward todo-done-string-start nil t)))
2830 (buffer-read-only nil)
2831 item done-item opoint)
2832 ;; Don't add empty comment to done item.
2833 (setq comment (unless (zerop (length comment))
2834 (concat " [" todo-comment-string ": " comment "]")))
2835 (and marked (goto-char (point-min)))
2837 ;; Stop looping when we hit the empty line below the last
2838 ;; todo item (this is eobp if only done items are hidden).
2839 (while (not (looking-at "^$"))
2840 (if (or (not marked) (and marked (todo-marked-item-p)))
2842 (setq item (todo-item-string))
2843 (setq done-item (concat done-item done-prefix item
2844 comment (and marked "\n")))
2845 (setq item-count (1+ item-count))
2846 (when (todo-diary-item-p)
2847 (setq diary-count (1+ diary-count)))
2849 (unless marked (throw 'done nil)))
2850 (todo-forward-item))))
2852 ;; Chop off last newline of done item string.
2853 (setq done-item (substring done-item 0 -1))
2854 (setq todo-categories-with-marks
2855 (assq-delete-all cat todo-categories-with-marks)))
2859 (concat "^" (regexp-quote todo-category-done)) nil t)
2861 (when show-done (setq opoint (point)))
2862 (insert done-item "\n"))
2863 (todo-update-count 'todo (- item-count))
2864 (todo-update-count 'done item-count)
2865 (todo-update-count 'diary (- diary-count))
2866 (todo-update-categories-sexp)
2867 (let ((todo-show-with-done show-done))
2868 (todo-category-select)
2869 ;; When done items are shown, put cursor on first just done item.
2870 (when opoint (goto-char opoint)))))))
2872 (defun todo-item-undone ()
2873 "Restore at least one done item to this category's todo section.
2874 Prompt for the new priority. If there are marked items, undo all
2875 of these, giving the first undone item the new priority and the
2876 rest following directly in sequence; otherwise, undo just the
2879 If the done item has a comment, ask whether to omit the comment
2880 from the restored item. With multiple marked done items with
2881 comments, only ask once, and if affirmed, omit subsequent
2882 comments without asking."
2884 (let* ((cat (todo-current-category))
2885 (marked (assoc cat todo-categories-with-marks))
2886 (pl (if (and marked (> (cdr marked) 1)) "s" "")))
2887 (when (or marked (todo-done-item-p))
2888 (let ((buffer-read-only)
2890 (omark (point-marker))
2894 start end item ov npoint undone)
2895 (and marked (goto-char (point-min)))
2898 (when (or (not marked) (and marked (todo-marked-item-p)))
2899 (if (not (todo-done-item-p))
2900 (user-error "Only done items can be undone")
2903 (setq ov (make-overlay (save-excursion (todo-item-start))
2904 (save-excursion (todo-item-end))))
2905 (overlay-put ov 'face 'todo-search))
2906 ;; Find the end of the date string added upon tagging item as
2908 (setq start (search-forward "] "))
2909 (setq item-count (1+ item-count))
2910 (unless (looking-at (regexp-quote todo-nondiary-start))
2911 (setq diary-count (1+ diary-count)))
2912 (setq end (save-excursion (todo-item-end)))
2913 ;; Ask (once) whether to omit done item's comment. If
2914 ;; affirmed, omit subsequent comments without asking.
2915 (when (re-search-forward
2916 (concat " \\[" (regexp-quote todo-comment-string)
2917 ": [^]]+\\]") end t)
2919 (if (eq first 'first)
2921 (if (eq todo-undo-item-omit-comment 'ask)
2922 (when (todo-y-or-n-p
2923 (concat "Omit comment" pl
2924 " from restored item"
2927 (when todo-undo-item-omit-comment 'omit)))
2929 (when (and (eq first 'first) ov) (delete-overlay ov)))
2930 (when (eq first 'omit)
2931 (setq end (match-beginning 0))))
2932 (setq item (concat item
2933 (buffer-substring-no-properties start end)
2934 (when marked "\n")))
2935 (unless marked (throw 'done nil))))
2936 (todo-forward-item)))
2939 ;; Chop off last newline of multiple items string, since
2940 ;; it will be reinserted on setting priority.
2941 (and marked (setq item (substring item 0 -1)))
2942 (todo-set-item-priority item cat t)
2943 (setq npoint (point))
2945 (when ov (delete-overlay ov))
2952 (concat "^" (regexp-quote todo-category-done)) nil t)
2954 (if (todo-marked-item-p)
2956 (todo-forward-item)))
2957 (setq todo-categories-with-marks
2958 (assq-delete-all cat todo-categories-with-marks)))
2961 (todo-update-count 'todo item-count)
2962 (todo-update-count 'done (- item-count))
2963 (when diary-count (todo-update-count 'diary diary-count))
2964 (todo-update-categories-sexp)
2965 (let ((todo-show-with-done (> (todo-get-count 'done) 0)))
2966 (todo-category-select))
2967 ;; Put cursor on undone item.
2968 (goto-char npoint)))
2969 (set-marker omark nil)))))
2971 ;; -----------------------------------------------------------------------------
2972 ;;; Done item archives
2973 ;; -----------------------------------------------------------------------------
2975 (defun todo-find-archive (&optional ask)
2976 "Visit the archive of the current todo category, if it exists.
2977 If the category has no archived items, prompt to visit the
2978 archive anyway. If there is no archive for this file or with
2979 non-nil argument ASK, prompt to visit another archive.
2981 The buffer showing the archive is in Todo Archive mode. The
2982 first visit in a session displays the first category in the
2983 archive, subsequent visits return to the last category
2986 (if (null (funcall todo-files-function t))
2987 (message "There are no archive files")
2988 (let* ((cat (todo-current-category))
2989 (count (todo-get-count 'archived cat))
2990 (archive (concat (file-name-sans-extension todo-current-todo-file)
2992 (place (cond (ask 'other-archive)
2993 ((file-exists-p archive) 'this-archive)
2994 (t (when (todo-y-or-n-p
2995 (concat "This file has no archive; "
2996 "visit another archive? "))
2998 (when (eq place 'other-archive)
2999 (setq archive (todo-read-file-name "Choose a todo archive: " t t)))
3000 (when (and (eq place 'this-archive) (zerop count))
3001 (setq place (when (todo-y-or-n-p
3002 (concat "This category has no archived items;"
3003 " visit archive anyway? "))
3006 (set-window-buffer (selected-window)
3007 (set-buffer (find-file-noselect archive)))
3008 (unless (derived-mode-p 'todo-archive-mode) (todo-archive-mode))
3009 (if (member place '(other-archive other-cat))
3010 (setq todo-category-number 1)
3011 (todo-category-number cat))
3012 (todo-category-select)))))
3014 (defun todo-choose-archive ()
3015 "Choose an archive and visit it."
3017 (todo-find-archive t))
3019 (defun todo-archive-done-item (&optional all)
3020 "Archive at least one done item in this category.
3022 With prefix argument ALL, prompt whether to archive all done
3023 items in this category and on confirmation archive them.
3024 Otherwise, if there are marked done items (and no marked todo
3025 items), archive all of these; otherwise, archive the done item at
3028 If the archive of this file does not exist, it is created. If
3029 this category does not exist in the archive, it is created."
3031 (when (eq major-mode 'todo-mode)
3032 (if (and all (zerop (todo-get-count 'done)))
3033 (message "No done items in this category")
3035 (let* ((cat (todo-current-category))
3036 (tbuf (current-buffer))
3037 (marked (assoc cat todo-categories-with-marks))
3038 (afile (concat (file-name-sans-extension
3039 todo-current-todo-file) ".toda"))
3040 (archive (find-file-noselect afile t))
3041 (item (and (not marked) (todo-done-item-p)
3042 (concat (todo-item-string) "\n")))
3044 (opoint (unless (todo-done-item-p) (point)))
3045 marked-items beg end all-done
3049 (if (todo-y-or-n-p "Archive all done items in this category? ")
3052 (goto-char (point-min))
3055 (re-search-forward todo-done-string-start
3057 (match-beginning 0))
3058 end (if (re-search-forward
3060 (regexp-quote todo-category-beg))
3064 all-done (buffer-substring-no-properties beg end)
3065 count (todo-get-count 'done))
3066 ;; Restore starting point, unless it was on a done
3067 ;; item, since they will all be deleted.
3068 (when opoint (goto-char opoint))))
3072 (goto-char (point-min))
3074 (when (todo-marked-item-p)
3075 (if (not (todo-done-item-p))
3076 (throw 'end (message "Only done items can be archived"))
3078 (concat marked-items (todo-item-string) "\n"))
3079 (setq count (1+ count))))
3080 (todo-forward-item)))))
3081 (if (not (or marked all item))
3082 (throw 'end (message "Only done items can be archived"))
3083 (with-current-buffer archive
3084 (unless (derived-mode-p 'todo-archive-mode) (todo-archive-mode))
3085 (let (buffer-read-only)
3087 (goto-char (point-min))
3088 (if (and (re-search-forward
3089 (concat "^" (regexp-quote
3090 (concat todo-category-beg cat)) "$")
3092 (re-search-forward (regexp-quote todo-category-done)
3094 ;; Start of done items section in existing category.
3096 (todo-add-category nil cat)
3097 ;; Start of done items section in new category.
3098 (goto-char (point-max)))
3099 (insert (cond (marked marked-items)
3102 (todo-update-count 'done (if (or marked all) count 1) cat)
3103 (todo-update-categories-sexp)
3104 ;; If archive is new, save to file now (with
3105 ;; write-region to avoid prompt for file to save to)
3106 ;; to update todo-archives, and set the mode for
3107 ;; visiting the archive below.
3108 (unless (nth 7 (file-attributes afile))
3109 (write-region nil nil afile t t)
3110 (setq todo-archives (funcall todo-files-function t))
3111 (todo-archive-mode))))
3112 (with-current-buffer tbuf
3117 ;; Make sure done items are accessible.
3119 (remove-overlays beg end)
3120 (delete-region beg end)
3121 (todo-update-count 'done (- count))
3122 (todo-update-count 'archived count))))
3124 ;; If we're archiving all done items, can't
3125 ;; first archive item point was on, since
3126 ;; that will short-circuit the rest.
3127 (and item (not all)))
3128 (and marked (goto-char (point-min)))
3131 (if (or (and marked (todo-marked-item-p)) item)
3134 (todo-update-count 'done -1)
3135 (todo-update-count 'archived 1)
3136 ;; Don't leave point below last item.
3137 (and (or marked item) (bolp) (eolp)
3138 (< (point-min) (point-max))
3139 (todo-backward-item))
3141 (throw 'done (setq item nil))))
3142 (todo-forward-item))))))
3144 (setq todo-categories-with-marks
3145 (assq-delete-all cat todo-categories-with-marks)))
3146 (todo-update-categories-sexp)
3147 (todo-prefix-overlays)))
3149 (todo-category-number cat)
3150 (todo-category-select)
3151 (split-window-below)
3152 (set-window-buffer (selected-window) tbuf)
3153 ;; Make todo file current to select category.
3154 (find-file (buffer-file-name tbuf))
3155 ;; Make sure done item separator is hidden (if done items
3156 ;; were initially visible).
3157 (let (todo-show-with-done) (todo-category-select)))))))
3159 (defun todo-unarchive-items ()
3160 "Unarchive at least one item in this archive category.
3161 If there are marked items, unarchive all of these; otherwise,
3162 unarchive the item at point.
3164 Unarchived items are restored as done items to the corresponding
3165 category in the todo file, inserted at the top of done items
3166 section. If all items in the archive category have been
3167 restored, the category is deleted from the archive. If this was
3168 the only category in the archive, the archive file is deleted."
3170 (when (eq major-mode 'todo-archive-mode)
3171 (let* ((cat (todo-current-category))
3172 (tbuf (find-file-noselect
3173 (concat (file-name-sans-extension todo-current-todo-file)
3175 (marked (assoc cat todo-categories-with-marks))
3176 (item (concat (todo-item-string) "\n"))
3182 (goto-char (point-min))
3184 (when (todo-marked-item-p)
3185 (setq marked-items (concat marked-items (todo-item-string) "\n"))
3186 (setq marked-count (1+ marked-count)))
3187 (todo-forward-item))))
3188 ;; Restore items to top of category's done section and update counts.
3189 (with-current-buffer tbuf
3190 (let (buffer-read-only newcat)
3192 (goto-char (point-min))
3193 ;; Find the corresponding todo category, or if there isn't
3195 (unless (re-search-forward
3196 (concat "^" (regexp-quote (concat todo-category-beg cat))
3198 (todo-add-category nil cat)
3200 ;; Go to top of category's done section.
3202 (concat "^" (regexp-quote todo-category-done)) nil t)
3205 (insert marked-items)
3206 (todo-update-count 'done marked-count cat)
3207 (unless newcat ; Newly added category has no archive.
3208 (todo-update-count 'archived (- marked-count) cat)))
3211 (todo-update-count 'done 1 cat)
3212 (unless newcat ; Newly added category has no archive.
3213 (todo-update-count 'archived -1 cat))))
3214 (todo-update-categories-sexp)))
3215 ;; Delete restored items from archive.
3218 (goto-char (point-min)))
3221 (if (or (todo-marked-item-p) item)
3225 (throw 'done (setq item nil))))
3226 (todo-forward-item))))
3227 (todo-update-count 'done (if marked (- marked-count) -1) cat)
3228 ;; If we unarchived the last item in category, then if that was
3229 ;; the only category, delete the whole file, otherwise, just
3230 ;; delete the category.
3231 (when (= 0 (todo-get-count 'done))
3232 (if (= 1 (length todo-categories))
3234 (delete-file todo-current-todo-file)
3235 ;; Kill the archive buffer silently.
3236 (set-buffer-modified-p nil)
3239 (let ((beg (re-search-backward
3240 (concat "^" (regexp-quote todo-category-beg) cat "$")
3242 (end (if (re-search-forward
3243 (concat "^" (regexp-quote todo-category-beg))
3247 (remove-overlays beg end)
3248 (delete-region beg end)
3249 (setq todo-categories (delete (assoc cat todo-categories)
3250 todo-categories)))))
3251 (todo-update-categories-sexp)
3252 ;; Visit category in todo file and show restored done items.
3253 (let ((tfile (buffer-file-name tbuf))
3254 (todo-show-with-done t))
3255 (set-window-buffer (selected-window)
3256 (set-buffer (find-file-noselect tfile)))
3257 (todo-category-number cat)
3258 (todo-category-select)
3259 (message "Items unarchived.")))))
3261 (defun todo-jump-to-archive-category (&optional file)
3262 "Prompt for a category in a todo archive and jump to it.
3263 With prefix argument FILE, prompt for an archive and choose (with
3264 TAB completion) a category in it to jump to; otherwise, choose
3265 and jump to any category in the current archive."
3267 (todo-jump-to-category file 'archive))
3269 ;; -----------------------------------------------------------------------------
3270 ;;; Displaying and sorting tables of categories
3271 ;; -----------------------------------------------------------------------------
3273 (defcustom todo-categories-category-label "Category"
3274 "Category button label in Todo Categories mode."
3276 :group 'todo-categories)
3278 (defcustom todo-categories-todo-label "Todo"
3279 "Todo button label in Todo Categories mode."
3281 :group 'todo-categories)
3283 (defcustom todo-categories-diary-label "Diary"
3284 "Diary button label in Todo Categories mode."
3286 :group 'todo-categories)
3288 (defcustom todo-categories-done-label "Done"
3289 "Done button label in Todo Categories mode."
3291 :group 'todo-categories)
3293 (defcustom todo-categories-archived-label "Archived"
3294 "Archived button label in Todo Categories mode."
3296 :group 'todo-categories)
3298 (defcustom todo-categories-totals-label "Totals"
3299 "String to label total item counts in Todo Categories mode."
3301 :group 'todo-categories)
3303 (defcustom todo-categories-number-separator " | "
3304 "String between number and category in Todo Categories mode.
3305 This separates the number from the category name in the default
3306 categories display according to priority."
3308 :group 'todo-categories)
3310 (defcustom todo-categories-align 'center
3311 "Alignment of category names in Todo Categories mode."
3312 :type '(radio (const left) (const center) (const right))
3313 :group 'todo-categories)
3315 (defun todo-show-categories-table ()
3316 "Display a table of the current file's categories and item counts.
3318 In the initial display the lines of the table are numbered,
3319 indicating the current order of the categories when sequentially
3320 navigating through the todo file with `\\[todo-forward-category]'
3321 and `\\[todo-backward-category]'. You can reorder the lines, and
3322 hence the category sequence, by typing `\\[todo-raise-category]'
3323 or `\\[todo-lower-category]' to raise or lower the category at
3324 point, or by typing `\\[todo-set-category-number]' and entering a
3325 number at the prompt or by typing `\\[todo-set-category-number]'
3326 with a numeric prefix. If you save the todo file after
3327 reordering the categories, the new order persists in subsequent
3330 The labels above the category names and item counts are buttons,
3331 and clicking these changes the display: sorted by category name
3332 or by the respective item counts (alternately descending or
3333 ascending). In these displays the categories are not numbered
3334 and `\\[todo-set-category-number]', `\\[todo-raise-category]' and
3335 `\\[todo-lower-category]' are disabled. (Programmatically, the
3336 sorting is triggered by passing a non-nil SORTKEY argument.)
3338 In addition, the lines with the category names and item counts
3339 are buttonized, and pressing one of these button jumps to the
3340 category in Todo mode (or Todo Archive mode, for categories
3341 containing only archived items, provided user option
3342 `todo-skip-archived-categories' is non-nil. These categories
3343 are shown in `todo-archived-only' face."
3345 (todo-display-categories)
3347 (todo-update-categories-display sortkey)))
3349 (defun todo-next-button (n)
3350 "Move point to the Nth next button in the table of categories."
3352 (forward-button n 'wrap 'display-message)
3353 (and (bolp) (button-at (point))
3354 ;; Align with beginning of category label.
3355 (forward-char (+ 4 (length todo-categories-number-separator)))))
3357 (defun todo-previous-button (n)
3358 "Move point to the Nth previous button in the table of categories."
3360 (backward-button n 'wrap 'display-message)
3361 (and (bolp) (button-at (point))
3362 ;; Align with beginning of category label.
3363 (forward-char (+ 4 (length todo-categories-number-separator)))))
3365 (defun todo-set-category-number (&optional arg)
3366 "Change number of category at point in the table of categories.
3368 With ARG nil, prompt for the new number. Alternatively, the
3369 enter the new number with numerical prefix ARG. Otherwise, if
3370 ARG is either of the symbols `raise' or `lower', raise or lower
3371 the category line in the table by one, respectively, thereby
3372 decreasing or increasing its number."
3374 (let ((curnum (save-excursion
3375 ;; Get the number representing the priority of the category
3376 ;; on the current line.
3377 (forward-line 0) (skip-chars-forward " ") (number-at-point))))
3378 (when curnum ; Do nothing if we're not on a category line.
3379 (let* ((maxnum (length todo-categories))
3380 (prompt (format "Set category priority (1-%d): " maxnum))
3381 (col (current-column))
3382 (buffer-read-only nil)
3383 (priority (cond ((and (eq arg 'raise) (> curnum 1))
3385 ((and (eq arg 'lower) (< curnum maxnum))
3388 (while (not priority)
3389 (setq candidate (or arg (read-number prompt)))
3392 (cond ((or (< candidate 1) (> candidate maxnum))
3393 (format "Priority must be an integer between 1 and %d: "
3395 ((= candidate curnum)
3396 "Choose a different priority than the current one: ")))
3397 (unless prompt (setq priority candidate)))
3398 (let* ((lower (< curnum priority)) ; Priority is being lowered.
3399 (head (butlast todo-categories
3400 (apply (if lower 'identity '1+)
3401 (list (- maxnum priority)))))
3402 (tail (nthcdr (apply (if lower 'identity '1-) (list priority))
3404 ;; Category's name and items counts list.
3405 (catcons (nth (1- curnum) todo-categories))
3406 (todo-categories (nconc head (list catcons) tail))
3408 (when lower (setq todo-categories (nreverse todo-categories)))
3409 (setq todo-categories (delete-dups todo-categories))
3410 (when lower (setq todo-categories (nreverse todo-categories)))
3411 (setq newcats todo-categories)
3413 (with-current-buffer (find-buffer-visiting todo-current-todo-file)
3414 (setq todo-categories newcats)
3415 (todo-update-categories-sexp))
3416 (todo-show-categories-table)
3417 (forward-line (1+ priority))
3418 (forward-char col))))))
3420 (defun todo-raise-category ()
3421 "Raise priority of category at point in the table of categories."
3423 (todo-set-category-number 'raise))
3425 (defun todo-lower-category ()
3426 "Lower priority of category at point in the table of categories."
3428 (todo-set-category-number 'lower))
3430 (defun todo-sort-categories-alphabetically-or-numerically ()
3431 "Sort table of categories alphabetically or numerically."
3434 (goto-char (point-min))
3436 (if (member 'alpha todo-descending-counts)
3438 (todo-update-categories-display nil)
3439 (setq todo-descending-counts
3440 (delete 'alpha todo-descending-counts)))
3441 (todo-update-categories-display 'alpha))))
3443 (defun todo-sort-categories-by-todo ()
3444 "Sort table of categories by number of todo items."
3447 (goto-char (point-min))
3449 (todo-update-categories-display 'todo)))
3451 (defun todo-sort-categories-by-diary ()
3452 "Sort table of categories by number of diary items."
3455 (goto-char (point-min))
3457 (todo-update-categories-display 'diary)))
3459 (defun todo-sort-categories-by-done ()
3460 "Sort table of categories by number of non-archived done items."
3463 (goto-char (point-min))
3465 (todo-update-categories-display 'done)))
3467 (defun todo-sort-categories-by-archived ()
3468 "Sort table of categories by number of archived items."
3471 (goto-char (point-min))
3473 (todo-update-categories-display 'archived)))
3475 (defvar todo-categories-buffer "*Todo Categories*"
3476 "Name of buffer in Todo Categories mode.")
3478 (defun todo-longest-category-name-length (categories)
3479 "Return the length of the longest name in list CATEGORIES."
3481 (dolist (c categories longest)
3482 (setq longest (max longest (length c))))))
3484 (defun todo-adjusted-category-label-length ()
3485 "Return adjusted length of category label button.
3486 The adjustment ensures proper tabular alignment in Todo
3488 (let* ((categories (mapcar 'car todo-categories))
3489 (longest (todo-longest-category-name-length categories))
3490 (catlablen (length todo-categories-category-label))
3491 (lc-diff (- longest catlablen)))
3492 (if (and (natnump lc-diff) (cl-oddp lc-diff))
3494 (max longest catlablen))))
3496 (defun todo-padded-string (str)
3497 "Return category name or label string STR padded with spaces.
3498 The placement of the padding is determined by the value of user
3499 option `todo-categories-align'."
3500 (let* ((len (todo-adjusted-category-label-length))
3501 (strlen (length str))
3502 (strlen-odd (eq (logand strlen 1) 1))
3503 (padding (max 0 (/ (- len strlen) 2)))
3504 (padding-left (cond ((eq todo-categories-align 'left) 0)
3505 ((eq todo-categories-align 'center) padding)
3506 ((eq todo-categories-align 'right)
3507 (if strlen-odd (1+ (* padding 2)) (* padding 2)))))
3508 (padding-right (cond ((eq todo-categories-align 'left)
3509 (if strlen-odd (1+ (* padding 2)) (* padding 2)))
3510 ((eq todo-categories-align 'center)
3511 (if strlen-odd (1+ padding) padding))
3512 ((eq todo-categories-align 'right) 0))))
3513 (concat (make-string padding-left 32) str (make-string padding-right 32))))
3515 (defvar todo-descending-counts nil
3516 "List of keys for category counts sorted in descending order.")
3518 (defun todo-sort (list &optional key)
3519 "Return a copy of LIST, possibly sorted according to KEY."
3520 (let* ((l (copy-sequence list))
3521 (fn (if (eq key 'alpha)
3522 (lambda (x) (upcase x)) ; Alphabetize case insensitively.
3523 (lambda (x) (todo-get-count key x))))
3524 ;; Keep track of whether the last sort by key was descending or
3526 (descending (member key todo-descending-counts))
3527 (cmp (if (eq key 'alpha)
3529 (if descending '< '>)))
3530 (pred (lambda (s1 s2) (let ((t1 (funcall fn (car s1)))
3531 (t2 (funcall fn (car s2))))
3532 (funcall cmp t1 t2)))))
3534 (setq l (sort l pred))
3535 ;; Switch between descending and ascending sort order.
3537 (setq todo-descending-counts
3538 (delete key todo-descending-counts))
3539 (push key todo-descending-counts)))
3542 (defun todo-display-sorted (type)
3543 "Keep point on the TYPE count sorting button just clicked."
3544 (let ((opoint (point)))
3545 (todo-update-categories-display type)
3546 (goto-char opoint)))
3548 (defun todo-label-to-key (label)
3549 "Return symbol for sort key associated with LABEL."
3551 (cond ((string= label todo-categories-category-label)
3553 ((string= label todo-categories-todo-label)
3555 ((string= label todo-categories-diary-label)
3557 ((string= label todo-categories-done-label)
3559 ((string= label todo-categories-archived-label)
3560 (setq key 'archived)))
3563 (defun todo-insert-sort-button (label)
3564 "Insert button for displaying categories sorted by item counts.
3565 LABEL determines which type of count is sorted."
3566 (let* ((str (if (string= label todo-categories-category-label)
3567 (todo-padded-string label)
3570 (end (+ beg (length str)))
3572 (insert-button str 'face nil
3575 (let ((key (todo-label-to-key ,label)))
3576 (if (and (member key todo-descending-counts)
3579 ;; If display is alphabetical, switch back to
3580 ;; category priority order.
3581 (todo-display-sorted nil)
3582 (setq todo-descending-counts
3583 (delete key todo-descending-counts)))
3584 (todo-display-sorted key)))))
3585 (setq ov (make-overlay beg end))
3586 (overlay-put ov 'face 'todo-button)))
3588 (defun todo-total-item-counts ()
3589 "Return a list of total item counts for the current file."
3590 (mapcar (lambda (i) (apply '+ (mapcar (lambda (l) (aref l i))
3591 (mapcar 'cdr todo-categories))))
3594 (defvar todo-categories-category-number 0
3595 "Variable for numbering categories in Todo Categories mode.")
3597 (defun todo-insert-category-line (cat &optional nonum)
3598 "Insert button with category CAT's name and item counts.
3599 With non-nil argument NONUM show only these; otherwise, insert a
3600 number in front of the button indicating the category's priority.
3601 The number and the category name are separated by the string
3602 which is the value of the user option
3603 `todo-categories-number-separator'."
3604 (let ((archive (member todo-current-todo-file todo-archives))
3605 (num todo-categories-category-number)
3606 (str (todo-padded-string cat))
3608 (setq num (1+ num) todo-categories-category-number num)
3611 (make-string (+ 4 (length todo-categories-number-separator))
3613 (format " %3d%s" num todo-categories-number-separator))
3615 (mapconcat (lambda (elt)
3617 (make-string (1+ (/ (length (car elt)) 2)) 32) ; label
3618 (format "%3d" (todo-get-count (cdr elt) cat)) ; count
3619 ;; Add an extra space if label length is odd.
3620 (when (cl-oddp (length (car elt))) " ")))
3622 (list (cons todo-categories-done-label 'done))
3623 (list (cons todo-categories-todo-label 'todo)
3624 (cons todo-categories-diary-label 'diary)
3625 (cons todo-categories-done-label 'done)
3626 (cons todo-categories-archived-label
3629 " ") ; Make highlighting on last column look better.
3630 'face (if (and todo-skip-archived-categories
3631 (zerop (todo-get-count 'todo cat))
3632 (zerop (todo-get-count 'done cat))
3633 (not (zerop (todo-get-count 'archived cat))))
3636 'action `(lambda (button) (let ((buf (current-buffer)))
3637 (todo-jump-to-category nil ,cat)
3638 (kill-buffer buf))))
3639 ;; Highlight the sorted count column.
3640 (let* ((beg (+ opoint 7 (length str)))
3642 (cond ((eq nonum 'todo)
3643 (setq beg (+ beg 1 (/ (length todo-categories-todo-label) 2))))
3645 (setq beg (+ beg 1 (length todo-categories-todo-label)
3646 2 (/ (length todo-categories-diary-label) 2))))
3648 (setq beg (+ beg 1 (length todo-categories-todo-label)
3649 2 (length todo-categories-diary-label)
3650 2 (/ (length todo-categories-done-label) 2))))
3651 ((eq nonum 'archived)
3652 (setq beg (+ beg 1 (length todo-categories-todo-label)
3653 2 (length todo-categories-diary-label)
3654 2 (length todo-categories-done-label)
3655 2 (/ (length todo-categories-archived-label) 2)))))
3656 (unless (= beg (+ opoint 7 (length str))) ; Don't highlight categories.
3657 (setq end (+ beg 4))
3658 (setq ovl (make-overlay beg end))
3659 (overlay-put ovl 'face 'todo-sorted-column)))
3662 (defun todo-display-categories ()
3663 "Prepare buffer for displaying table of categories and item counts."
3664 (unless (eq major-mode 'todo-categories-mode)
3665 (setq todo-global-current-todo-file
3666 (or todo-current-todo-file
3667 (todo-absolute-file-name todo-default-todo-file)))
3668 (set-window-buffer (selected-window)
3669 (set-buffer (get-buffer-create todo-categories-buffer)))
3670 (kill-all-local-variables)
3671 (todo-categories-mode)
3672 (let ((archive (member todo-current-todo-file todo-archives))
3675 (insert (format (concat "Category counts for todo "
3676 (if archive "archive" "file")
3678 (todo-short-file-name todo-current-todo-file)))
3680 ;; Make space for the column of category numbers.
3681 (insert (make-string (+ 4 (length todo-categories-number-separator)) 32))
3682 ;; Add the category and item count buttons (if this is the list of
3683 ;; categories in an archive, show only done item counts).
3684 (todo-insert-sort-button todo-categories-category-label)
3687 (insert (make-string 3 32))
3688 (todo-insert-sort-button todo-categories-done-label))
3689 (insert (make-string 3 32))
3690 (todo-insert-sort-button todo-categories-todo-label)
3691 (insert (make-string 2 32))
3692 (todo-insert-sort-button todo-categories-diary-label)
3693 (insert (make-string 2 32))
3694 (todo-insert-sort-button todo-categories-done-label)
3695 (insert (make-string 2 32))
3696 (todo-insert-sort-button todo-categories-archived-label))
3699 (defun todo-update-categories-display (sortkey)
3700 "Populate table of categories and sort by SORTKEY."
3701 (let* ((cats0 todo-categories)
3702 (cats (todo-sort cats0 sortkey))
3703 (archive (member todo-current-todo-file todo-archives))
3704 (todo-categories-category-number 0)
3705 ;; Find start of Category button if we just entered Todo Categories
3707 (pt (if (eq (point) (point-max))
3710 (goto-char (next-single-char-property-change
3711 (point) 'face nil (line-end-position))))))
3714 (delete-region (point) (point-max))
3715 ;; Fill in the table with buttonized lines, each showing a category and
3717 (mapc (lambda (cat) (todo-insert-category-line cat sortkey))
3720 ;; Add a line showing item count totals.
3721 (insert (make-string (+ 4 (length todo-categories-number-separator)) 32)
3722 (todo-padded-string todo-categories-totals-label)
3726 (make-string (1+ (/ (length (car elt)) 2)) 32)
3727 (format "%3d" (nth (cdr elt) (todo-total-item-counts)))
3728 ;; Add an extra space if label length is odd.
3729 (when (cl-oddp (length (car elt))) " ")))
3731 (list (cons todo-categories-done-label 2))
3732 (list (cons todo-categories-todo-label 0)
3733 (cons todo-categories-diary-label 1)
3734 (cons todo-categories-done-label 2)
3735 (cons todo-categories-archived-label 3)))
3737 ;; Put cursor on Category button initially.
3738 (if pt (goto-char pt))
3739 (setq buffer-read-only t)))
3741 ;; -----------------------------------------------------------------------------
3742 ;;; Searching and item filtering
3743 ;; -----------------------------------------------------------------------------
3745 (defun todo-search ()
3746 "Search for a regular expression in this todo file.
3747 The search runs through the whole file and encompasses all and
3748 only todo and done items; it excludes category names. Multiple
3749 matches are shown sequentially, highlighted in `todo-search'
3752 (let ((regex (read-from-minibuffer "Enter a search string (regexp): "))
3754 matches match cat in-done ov mlen msg)
3756 (goto-char (point-min))
3758 (setq match (re-search-forward regex nil t))
3759 (goto-char (line-beginning-position))
3760 (unless (or (equal (point) 1)
3761 (looking-at (concat "^" (regexp-quote todo-category-beg))))
3762 (if match (push match matches)))
3764 (setq matches (reverse matches))
3768 (setq match (pop matches))
3771 (when (looking-at todo-done-string-start)
3773 (re-search-backward (concat "^" (regexp-quote todo-category-beg)
3774 "\\(.*\\)\n") nil t)
3775 (setq cat (match-string-no-properties 1))
3776 (todo-category-number cat)
3777 (todo-category-select)
3779 (unless todo-show-with-done (todo-toggle-view-done-items)))
3781 (setq ov (make-overlay (- (point) (length regex)) (point)))
3782 (overlay-put ov 'face 'todo-search)
3784 (setq mlen (length matches))
3787 (format "There are %d more matches; go to next match? "
3789 "There is one more match; go to it? "))
3791 (throw 'stop (setq msg (if (> mlen 1)
3792 (format "There are %d more matches."
3794 "There is one more match."))))))
3795 (setq msg "There are no more matches."))
3796 (todo-category-select)
3798 (message "No match for \"%s\"" regex))
3800 (if (todo-y-or-n-p (concat msg "\nUnhighlight matches? "))
3801 (todo-clear-matches)
3802 (message "You can unhighlight the matches later by typing %s"
3803 (key-description (car (where-is-internal
3804 'todo-clear-matches))))))))
3806 (defun todo-clear-matches ()
3807 "Remove highlighting on matches found by todo-search."
3809 (remove-overlays 1 (1+ (buffer-size)) 'face 'todo-search))
3811 (defcustom todo-top-priorities-overrides nil
3812 "List of rules specifying number of top priority items to show.
3813 These rules override `todo-top-priorities' on invocations of
3814 `\\[todo-filter-top-priorities]' and
3815 `\\[todo-filter-top-priorities-multifile]'. Each rule is a list
3816 of the form (FILE NUM ALIST), where FILE is a member of
3817 `todo-files', NUM is a number specifying the default number of
3818 top priority items for each category in that file, and ALIST,
3819 when non-nil, consists of conses of a category name in FILE and a
3820 number specifying the default number of top priority items in
3821 that category, which overrides NUM.
3823 This variable should be set interactively by
3824 `\\[todo-set-top-priorities-in-file]' or
3825 `\\[todo-set-top-priorities-in-category]'."
3827 :group 'todo-filtered)
3829 (defcustom todo-top-priorities 1
3830 "Default number of top priorities shown by `todo-filter-top-priorities'."
3832 :group 'todo-filtered)
3834 (defcustom todo-filter-files nil
3835 "List of default files for multifile item filtering."
3836 :type `(set ,@(mapcar (lambda (f) (list 'const f))
3837 (mapcar 'todo-short-file-name
3838 (funcall todo-files-function))))
3839 :group 'todo-filtered)
3841 (defcustom todo-filter-done-items nil
3842 "Non-nil to include done items when processing regexp filters.
3843 Done items from corresponding archive files are also included."
3845 :group 'todo-filtered)
3847 (defun todo-set-top-priorities-in-file ()
3848 "Set number of top priorities for this file.
3849 See `todo-set-top-priorities' for more details."
3851 (todo-set-top-priorities))
3853 (defun todo-set-top-priorities-in-category ()
3854 "Set number of top priorities for this category.
3855 See `todo-set-top-priorities' for more details."
3857 (todo-set-top-priorities t))
3859 (defun todo-filter-top-priorities (&optional arg)
3860 "Display a list of top priority items from different categories.
3861 The categories can be any of those in the current todo file.
3863 With numerical prefix ARG show at most ARG top priority items
3864 from each category. With `C-u' as prefix argument show the
3865 numbers of top priority items specified by category in
3866 `todo-top-priorities-overrides', if this has an entry for the file(s);
3867 otherwise show `todo-top-priorities' items per category in the
3868 file(s). With no prefix argument, if a top priorities file for
3869 the current todo file has previously been saved (see
3870 `todo-save-filtered-items-buffer'), visit this file; if there is
3871 no such file, build the list as with prefix argument `C-u'.
3873 The prefix ARG regulates how many top priorities from
3874 each category to show, as described above."
3876 (todo-filter-items 'top arg))
3878 (defun todo-filter-top-priorities-multifile (&optional arg)
3879 "Display a list of top priority items from different categories.
3880 The categories are a subset of the categories in the files listed
3881 in `todo-filter-files', or if this nil, in the files chosen from
3882 a file selection dialog that pops up in this case.
3884 With numerical prefix ARG show at most ARG top priority items
3885 from each category in each file. With `C-u' as prefix argument
3886 show the numbers of top priority items specified in
3887 `todo-top-priorities-overrides', if this is non-nil; otherwise show
3888 `todo-top-priorities' items per category. With no prefix
3889 argument, if a top priorities file for the chosen todo files
3890 exists (see `todo-save-filtered-items-buffer'), visit this file;
3891 if there is no such file, do the same as with prefix argument
3894 (todo-filter-items 'top arg t))
3896 (defun todo-filter-diary-items (&optional arg)
3897 "Display a list of todo diary items from different categories.
3898 The categories can be any of those in the current todo file.
3900 Called with no prefix ARG, if a diary items file for the current
3901 todo file has previously been saved (see
3902 `todo-save-filtered-items-buffer'), visit this file; if there is
3903 no such file, build the list of diary items. Called with a
3904 prefix argument, build the list even if there is a saved file of
3907 (todo-filter-items 'diary arg))
3909 (defun todo-filter-diary-items-multifile (&optional arg)
3910 "Display a list of todo diary items from different categories.
3911 The categories are a subset of the categories in the files listed
3912 in `todo-filter-files', or if this nil, in the files chosen from
3913 a file selection dialog that pops up in this case.
3915 Called with no prefix ARG, if a diary items file for the chosen
3916 todo files has previously been saved (see
3917 `todo-save-filtered-items-buffer'), visit this file; if there is
3918 no such file, build the list of diary items. Called with a
3919 prefix argument, build the list even if there is a saved file of
3922 (todo-filter-items 'diary arg t))
3924 (defun todo-filter-regexp-items (&optional arg)
3925 "Prompt for a regular expression and display items that match it.
3926 The matches can be from any categories in the current todo file
3927 and with non-nil option `todo-filter-done-items', can include
3928 not only todo items but also done items, including those in
3931 Called with no prefix ARG, if a regexp items file for the current
3932 todo file has previously been saved (see
3933 `todo-save-filtered-items-buffer'), visit this file; if there is
3934 no such file, build the list of regexp items. Called with a
3935 prefix argument, build the list even if there is a saved file of
3938 (todo-filter-items 'regexp arg))
3940 (defun todo-filter-regexp-items-multifile (&optional arg)
3941 "Prompt for a regular expression and display items that match it.
3942 The matches can be from any categories in the files listed in
3943 `todo-filter-files', or if this nil, in the files chosen from a
3944 file selection dialog that pops up in this case. With non-nil
3945 option `todo-filter-done-items', the matches can include not
3946 only todo items but also done items, including those in Archive
3949 Called with no prefix ARG, if a regexp items file for the current
3950 todo file has previously been saved (see
3951 `todo-save-filtered-items-buffer'), visit this file; if there is
3952 no such file, build the list of regexp items. Called with a
3953 prefix argument, build the list even if there is a saved file of
3956 (todo-filter-items 'regexp arg t))
3958 (defun todo-find-filtered-items-file ()
3959 "Choose a filtered items file and visit it."
3961 (let ((files (directory-files todo-directory t "\.tod[rty]$" t))
3964 (let ((type (cond ((equal (file-name-extension f) "todr") "regexp")
3965 ((equal (file-name-extension f) "todt") "top")
3966 ((equal (file-name-extension f) "tody") "diary"))))
3967 (push (cons (concat (todo-short-file-name f) " (" type ")") f)
3969 (setq file (completing-read "Choose a filtered items file: "
3970 falist nil t nil nil (car falist)))
3971 (setq file (cdr (assoc-string file falist)))
3973 (unless (derived-mode-p 'todo-filtered-items-mode)
3974 (todo-filtered-items-mode))))
3976 (defun todo-go-to-source-item ()
3977 "Display the file and category of the filtered item at point."
3979 (let* ((str (todo-item-string))
3980 (buf (current-buffer))
3981 (res (todo-find-item str))
3986 (message "Category %s does not contain this item." cat)
3988 (set-window-buffer (selected-window)
3989 (set-buffer (find-buffer-visiting file)))
3990 (setq todo-current-todo-file file)
3991 (setq todo-category-number (todo-category-number cat))
3992 (let ((todo-show-with-done (if (or todo-filter-done-items
3993 (eq (cdr found) 'done))
3995 todo-show-with-done)))
3996 (todo-category-select))
3997 (goto-char (car found)))))
3999 (defvar todo-multiple-filter-files nil
4000 "List of files selected from `todo-multiple-filter-files' widget.")
4002 (defvar todo-multiple-filter-files-widget nil
4003 "Variable holding widget created by `todo-multiple-filter-files'.")
4005 (defun todo-multiple-filter-files ()
4006 "Pop to a buffer with a widget for choosing multiple filter files."
4009 (require 'wid-edit))
4010 (with-current-buffer (get-buffer-create "*Todo Filter Files*")
4011 (pop-to-buffer (current-buffer))
4013 (kill-all-local-variables)
4014 (widget-insert "Select files for generating the top priorities list.\n\n")
4015 (setq todo-multiple-filter-files-widget
4017 `(set ,@(mapcar (lambda (x) (list 'const x))
4018 (mapcar 'todo-short-file-name
4019 (funcall todo-files-function))))))
4020 (widget-insert "\n")
4021 (widget-create 'push-button
4022 :notify (lambda (widget &rest ignore)
4023 (setq todo-multiple-filter-files 'quit)
4025 (exit-recursive-edit))
4028 (widget-create 'push-button
4029 :notify (lambda (&rest ignore)
4030 (setq todo-multiple-filter-files
4033 (concat todo-directory
4036 todo-multiple-filter-files-widget)))
4038 (exit-recursive-edit))
4040 (use-local-map widget-keymap)
4042 (message "Click \"Apply\" after selecting files.")
4045 (defconst todo-filtered-items-buffer "Todo filtered items"
4046 "Initial name of buffer in Todo Filter Items mode.")
4048 (defconst todo-top-priorities-buffer "Todo top priorities"
4049 "Buffer type string for `todo-filter-items'.")
4051 (defconst todo-diary-items-buffer "Todo diary items"
4052 "Buffer type string for `todo-filter-items'.")
4054 (defconst todo-regexp-items-buffer "Todo regexp items"
4055 "Buffer type string for `todo-filter-items'.")
4057 (defun todo-filter-items (filter &optional new multifile)
4058 "Display a list of items filtered by FILTER.
4059 The values of FILTER can be `top' for top priority items, a cons
4060 of `top' and a number passed by the caller, `diary' for diary
4061 items, or `regexp' for items matching a regular expression
4062 entered by the user. The items can come from any categories in
4063 the current todo file or, with non-nil MULTIFILE, from several
4064 files. If NEW is nil, visit an appropriate file containing the
4065 list of filtered items; if there is no such file, or with non-nil
4066 NEW, build the list and display it.
4068 See the documentation strings of the commands
4069 `todo-filter-top-priorities', `todo-filter-diary-items',
4070 `todo-filter-regexp-items', and those of the corresponding
4071 multifile commands for further details."
4072 (let* ((top (eq filter 'top))
4073 (diary (eq filter 'diary))
4074 (regexp (eq filter 'regexp))
4075 (buf (cond (top todo-top-priorities-buffer)
4076 (diary todo-diary-items-buffer)
4077 (regexp todo-regexp-items-buffer)))
4078 (flist (if multifile
4079 (or todo-filter-files
4080 (progn (todo-multiple-filter-files)
4081 todo-multiple-filter-files))
4082 (list todo-current-todo-file)))
4083 (multi (> (length flist) 1))
4084 (fname (if (equal flist 'quit)
4085 ;; Pressed `cancel' in t-m-f-f file selection dialog.
4087 (concat todo-directory
4088 (mapconcat 'todo-short-file-name flist "-")
4091 (regexp ".todr")))))
4092 (rxfiles (when regexp
4093 (directory-files todo-directory t ".*\\.todr$" t)))
4094 (file-exists (or (file-exists-p fname) rxfiles))
4096 (cond ((and top new (natnump new))
4097 (todo-filter-items-1 (cons 'top new) flist))
4098 ((and (not new) file-exists)
4099 (when (and rxfiles (> (length rxfiles) 1))
4100 (let ((rxf (mapcar 'todo-short-file-name rxfiles)))
4101 (setq fname (todo-absolute-file-name
4102 (completing-read "Choose a regexp items file: "
4105 (unless (derived-mode-p 'todo-filtered-items-mode)
4106 (todo-filtered-items-mode))
4107 (todo-prefix-overlays)
4108 (todo-check-filtered-items-file))
4110 (todo-filter-items-1 filter flist)))
4111 (dolist (s (split-string (todo-short-file-name fname) "-"))
4112 (setq bufname (if bufname
4113 (concat bufname (if (member s (mapcar
4114 'todo-short-file-name
4118 (rename-buffer (format (concat "%s for file" (if multi "s" "")
4119 " \"%s\"") buf bufname))))
4121 (defun todo-filter-items-1 (filter file-list)
4122 "Build a list of items by applying FILTER to FILE-LIST.
4123 Internal subroutine called by `todo-filter-items', which passes
4124 the values of FILTER and FILE-LIST."
4125 (let ((num (if (consp filter) (cdr filter) todo-top-priorities))
4126 (buf (get-buffer-create todo-filtered-items-buffer))
4127 (multifile (> (length file-list) 1))
4128 regexp fname bufstr cat beg end done)
4129 (if (null file-list)
4130 (user-error "No files have been chosen for filtering")
4131 (with-current-buffer buf
4133 (kill-all-local-variables)
4134 (todo-filtered-items-mode))
4135 (when (eq filter 'regexp)
4136 (setq regexp (read-string "Enter a regular expression: ")))
4137 (save-current-buffer
4138 (dolist (f file-list)
4139 ;; Before inserting file contents into temp buffer, save a modified
4140 ;; buffer visiting it.
4141 (let ((bf (find-buffer-visiting f)))
4142 (when (buffer-modified-p bf)
4143 (with-current-buffer bf (save-buffer))))
4144 (setq fname (todo-short-file-name f))
4146 (when (and todo-filter-done-items (eq filter 'regexp))
4147 ;; If there is a corresponding archive file for the
4148 ;; todo file, insert it first and add identifiers for
4149 ;; todo-go-to-source-item.
4150 (let ((arch (concat (file-name-sans-extension f) ".toda")))
4151 (when (file-exists-p arch)
4152 (insert-file-contents arch)
4153 ;; Delete todo archive file's categories sexp.
4154 (delete-region (line-beginning-position)
4155 (1+ (line-end-position)))
4158 (when (re-search-forward
4159 (concat (if todo-filter-done-items
4160 (concat "\\(?:" todo-done-string-start
4161 "\\|" todo-date-string-start
4163 todo-date-string-start)
4164 todo-date-pattern "\\(?: "
4165 diary-time-regexp "\\)?"
4166 (if todo-filter-done-items
4168 (regexp-quote todo-nondiary-end)) "?")
4170 (insert "(archive) "))
4172 (insert-file-contents f)
4173 ;; Delete todo file's categories sexp.
4174 (delete-region (line-beginning-position) (1+ (line-end-position)))
4176 ;; Unless the number of top priorities to show was
4177 ;; passed by the caller, the file-wide value from
4178 ;; `todo-top-priorities-overrides', if non-nil, overrides
4179 ;; `todo-top-priorities'.
4180 (unless (consp filter)
4181 (setq fnum (or (nth 1 (assoc f todo-top-priorities-overrides))
4182 todo-top-priorities)))
4183 (while (re-search-forward
4184 (concat "^" (regexp-quote todo-category-beg)
4185 "\\(.+\\)\n") nil t)
4186 (setq cat (match-string 1))
4188 ;; Unless the number of top priorities to show was
4189 ;; passed by the caller, the category-wide value
4190 ;; from `todo-top-priorities-overrides', if non-nil,
4191 ;; overrides a non-nil file-wide value from
4192 ;; `todo-top-priorities-overrides' as well as
4193 ;; `todo-top-priorities'.
4194 (unless (consp filter)
4195 (let ((cats (nth 2 (assoc f todo-top-priorities-overrides))))
4196 (setq cnum (or (cdr (assoc cat cats)) fnum))))
4197 (delete-region (match-beginning 0) (match-end 0))
4198 (setq beg (point)) ; First item in the current category.
4199 (setq end (if (re-search-forward
4200 (concat "^" (regexp-quote todo-category-beg))
4206 (if (re-search-forward
4207 (concat "\n" (regexp-quote todo-category-done))
4211 (unless (and todo-filter-done-items (eq filter 'regexp))
4212 ;; Leave done items.
4213 (delete-region done end)
4215 (narrow-to-region beg end) ; Process only current category.
4216 (goto-char (point-min))
4217 ;; Apply the filter.
4218 (cond ((eq filter 'diary)
4220 (if (looking-at (regexp-quote todo-nondiary-start))
4222 (todo-forward-item))))
4223 ((eq filter 'regexp)
4225 (if (looking-at todo-item-start)
4226 (if (string-match regexp (todo-item-string))
4229 ;; Kill lines that aren't part of a todo or done
4230 ;; item (empty or todo-category-done).
4231 (delete-region (line-beginning-position)
4232 (1+ (line-end-position))))
4233 ;; If last todo item in file matches regexp and
4234 ;; there are no following done items,
4235 ;; todo-category-done string is left dangling,
4236 ;; because todo-forward-item jumps over it.
4239 (concat (regexp-quote todo-done-string)
4241 (delete-region (point) (progn
4244 (t ; Filter top priority items.
4245 (setq num (or cnum fnum num))
4247 (todo-forward-item num))))
4249 ;; Delete non-top-priority items.
4250 (unless (member filter '(diary regexp))
4251 (delete-region beg end))
4252 (goto-char (point-min))
4253 ;; Add file (if using multiple files) and category tags to
4256 (when (re-search-forward
4257 (concat (if todo-filter-done-items
4258 (concat "\\(?:" todo-done-string-start
4259 "\\|" todo-date-string-start
4261 todo-date-string-start)
4262 todo-date-pattern "\\(?: " diary-time-regexp
4263 "\\)?" (if todo-filter-done-items
4265 (regexp-quote todo-nondiary-end))
4269 (when (looking-at "(archive) ") (goto-char (match-end 0)))
4270 (insert (if multifile (concat fname ":") "") cat "]"))
4273 (setq bufstr (buffer-string))
4274 (with-current-buffer buf
4275 (let (buffer-read-only)
4276 (insert bufstr)))))))
4277 (set-window-buffer (selected-window) (set-buffer buf))
4278 (todo-prefix-overlays)
4279 (goto-char (point-min)))))
4281 (defun todo-set-top-priorities (&optional arg)
4282 "Set number of top priorities shown by `todo-filter-top-priorities'.
4283 With non-nil ARG, set the number only for the current Todo
4284 category; otherwise, set the number for all categories in the
4287 Calling this function via either of the commands
4288 `todo-set-top-priorities-in-file' or
4289 `todo-set-top-priorities-in-category' is the recommended way to
4290 set the user customizable option `todo-top-priorities-overrides'."
4291 (let* ((cat (todo-current-category))
4292 (file todo-current-todo-file)
4293 (rules todo-top-priorities-overrides)
4294 (frule (assoc-string file rules))
4295 (crule (assoc-string cat (nth 2 frule)))
4296 (crules (nth 2 frule))
4297 (cur (or (if arg (cdr crule) (nth 1 frule))
4298 todo-top-priorities))
4299 (prompt (if arg (concat "Number of top priorities in this category"
4300 " (currently %d): ")
4301 (concat "Default number of top priorities per category"
4302 " in this file (currently %d): ")))
4307 (setq new (read-number (format prompt cur0))
4308 prompt "Enter a non-negative number: "
4311 (append (delete crule crules) (list (cons cat new)))
4312 (append (list file new) (list crules))))
4313 (setq rules (cons (if arg
4314 (list file cur nrule)
4316 (delete frule rules)))
4317 (customize-save-variable 'todo-top-priorities-overrides rules)
4318 (todo-prefix-overlays)))
4320 (defun todo-find-item (str)
4321 "Search for filtered item STR in its saved todo file.
4322 Return the list (FOUND FILE CAT), where CAT and FILE are the
4323 item's category and file, and FOUND is a cons cell if the search
4324 succeeds, whose car is the start of the item in FILE and whose
4325 cdr is `done', if the item is now a done item, `changed', if its
4326 text was truncated or augmented or, for a top priority item, if
4327 its priority has changed, and `same' otherwise."
4328 (string-match (concat (if todo-filter-done-items
4329 (concat "\\(?:" todo-done-string-start "\\|"
4330 todo-date-string-start "\\)")
4331 todo-date-string-start)
4332 todo-date-pattern "\\(?: " diary-time-regexp "\\)?"
4333 (if todo-filter-done-items
4335 (regexp-quote todo-nondiary-end)) "?"
4336 "\\(?4: \\[\\(?3:(archive) \\)?\\(?2:.*:\\)?"
4337 "\\(?1:.*\\)\\]\\).*$") str)
4338 (let ((cat (match-string 1 str))
4339 (file (match-string 2 str))
4340 (archive (string= (match-string 3 str) "(archive) "))
4341 (filcat (match-string 4 str))
4343 (tpbuf (save-match-data (string-match "top" (buffer-name))))
4345 (setq str (replace-match "" nil nil str 4))
4347 ;; Calculate priority of STR wrt its category.
4349 (while (search-backward filcat nil t)
4350 (setq tpriority (1+ tpriority)))))
4352 (concat todo-directory (substring file 0 -1)
4353 (if archive ".toda" ".todo"))
4355 (concat (file-name-sans-extension
4356 todo-global-current-todo-file) ".toda")
4357 todo-global-current-todo-file)))
4358 (find-file-noselect file)
4359 (with-current-buffer (find-buffer-visiting file)
4361 (unless (derived-mode-p 'todo-archive-mode) (todo-archive-mode))
4362 (unless (derived-mode-p 'todo-mode) (todo-mode)))
4365 (goto-char (point-min))
4366 (let ((beg (re-search-forward
4367 (concat "^" (regexp-quote (concat todo-category-beg cat))
4370 (done (save-excursion
4372 (concat "^" (regexp-quote todo-category-done)) nil t)))
4373 (end (save-excursion
4374 (or (re-search-forward
4375 (concat "^" (regexp-quote todo-category-beg))
4378 (setq found (when (search-forward str end t)
4379 (goto-char (match-beginning 0))))
4382 (cons found (if (> (point) done)
4384 (let ((cpriority 1))
4387 ;; Not top item in category.
4388 (while (> (point) (1+ beg))
4389 (let ((opoint (point)))
4390 (todo-backward-item)
4391 ;; Can't move backward beyond
4392 ;; first item in file.
4393 (unless (= (point) opoint)
4394 (setq cpriority (1+ cpriority)))))))
4395 (if (and (= tpriority cpriority)
4396 ;; Proper substring is not the same.
4397 (string= (todo-item-string)
4401 (list found file cat)))
4403 (defun todo-check-filtered-items-file ()
4404 "Check if filtered items file is up to date and a show suitable message."
4408 (let* ((item (todo-item-string))
4409 (found (car (todo-find-item item))))
4410 (unless (eq (cdr found) 'same)
4412 (overlay-put (make-overlay (todo-item-start) (todo-item-end))
4413 'face 'todo-search))
4414 (setq count (1+ count))))
4415 ;; (throw 'old (message "The marked item is not up to date.")))
4416 (todo-forward-item))
4418 (message "Filtered items file is up to date.")
4419 (message (concat "The highlighted item" (if (= count 1) " is " "s are ")
4421 ;; "\nType <return> on item for details."
4424 (defun todo-filter-items-filename ()
4425 "Return absolute file name for saving this Filtered Items buffer."
4426 (let ((bufname (buffer-name)))
4427 (string-match "\"\\([^\"]+\\)\"" bufname)
4428 (let* ((filename-str (substring bufname (match-beginning 1) (match-end 1)))
4429 (filename-base (replace-regexp-in-string ", " "-" filename-str))
4430 (top-priorities (string-match "top priorities" bufname))
4431 (diary-items (string-match "diary items" bufname))
4432 (regexp-items (string-match "regexp items" bufname)))
4434 (let ((prompt (concat "Enter a short identifying string"
4435 " to make this file name unique: ")))
4436 (setq filename-base (concat filename-base "-" (read-string prompt)))))
4437 (concat todo-directory filename-base
4438 (cond (top-priorities ".todt")
4439 (diary-items ".tody")
4440 (regexp-items ".todr"))))))
4442 (defun todo-save-filtered-items-buffer ()
4443 "Save current Filtered Items buffer to a file.
4444 If the file already exists, overwrite it only on confirmation."
4445 (let ((filename (or (buffer-file-name) (todo-filter-items-filename))))
4446 (write-file filename t)))
4448 ;; -----------------------------------------------------------------------------
4449 ;;; Printing Todo mode buffers
4450 ;; -----------------------------------------------------------------------------
4452 (defcustom todo-print-buffer-function 'ps-print-buffer-with-faces
4453 "Function called by the command `todo-print-buffer'."
4457 (defvar todo-print-buffer "*Todo Print*"
4458 "Name of buffer with printable version of Todo mode buffer.")
4460 (defun todo-print-buffer (&optional to-file)
4461 "Produce a printable version of the current Todo mode buffer.
4462 This converts overlays and soft line wrapping and, depending on
4463 the value of `todo-print-buffer-function', includes faces. With
4464 non-nil argument TO-FILE write the printable version to a file;
4465 otherwise, send it to the default printer."
4467 (let ((buf todo-print-buffer)
4469 ((eq major-mode 'todo-mode)
4470 (concat "Todo File: "
4471 (todo-short-file-name todo-current-todo-file)
4472 "\nCategory: " (todo-current-category)))
4473 ((eq major-mode 'todo-filtered-items-mode)
4475 (prefix (propertize (concat todo-prefix " ")
4476 'face 'todo-prefix-string))
4478 (fill-prefix (make-string todo-indent-to-here 32))
4479 (content (buffer-string))
4481 (with-current-buffer (get-buffer-create buf)
4483 (goto-char (point-min))
4486 (end (save-excursion (todo-item-end))))
4487 (when todo-number-prefix
4489 (setq prefix (propertize (concat (number-to-string num) " ")
4490 'face 'todo-prefix-string)))
4492 (fill-region beg end))
4493 ;; Calling todo-forward-item infloops at todo-item-start due to
4494 ;; non-overlay prefix, so search for item start instead.
4495 (if (re-search-forward todo-item-start nil t)
4497 (goto-char (point-max))))
4498 (if (re-search-backward (concat "^" (regexp-quote todo-category-done))
4500 (replace-match todo-done-separator))
4501 (goto-char (point-min))
4505 (let ((file (read-file-name "Print to file: ")))
4506 (funcall todo-print-buffer-function file))
4507 (funcall todo-print-buffer-function)))
4510 (defun todo-print-buffer-to-file ()
4511 "Save printable version of this Todo mode buffer to a file."
4513 (todo-print-buffer t))
4515 ;; -----------------------------------------------------------------------------
4516 ;;; Legacy Todo mode files
4517 ;; -----------------------------------------------------------------------------
4519 (defcustom todo-legacy-date-time-regexp
4520 (concat "\\(?1:[0-9]\\{4\\}\\)-\\(?2:[0-9]\\{2\\}\\)-"
4521 "\\(?3:[0-9]\\{2\\}\\) \\(?4:[0-9]\\{2\\}:[0-9]\\{2\\}\\)")
4522 "Regexp matching legacy todo-mode.el item date-time strings.
4523 In order for `todo-convert-legacy-files' to correctly convert
4524 this string to the current Todo mode format, the regexp must
4525 contain four explicitly numbered groups (see `(elisp) Regexp
4526 Backslash'), where group 1 matches a string for the year, group 2
4527 a string for the month, group 3 a string for the day and group 4
4528 a string for the time. The default value converts date-time
4529 strings built using the default value of
4530 `todo-time-string-format' from todo-mode.el."
4534 (defun todo-convert-legacy-date-time ()
4535 "Return converted date-time string.
4536 Helper function for `todo-convert-legacy-files'."
4537 (let* ((year (match-string 1))
4538 (month (match-string 2))
4539 (monthname (calendar-month-name (string-to-number month) t))
4540 (day (match-string 3))
4541 (time (match-string 4))
4544 (insert (mapconcat 'eval calendar-date-display-form "")
4545 (when time (concat " " time)))))
4547 (defun todo-convert-legacy-files ()
4548 "Convert legacy todo files to the current Todo mode format.
4549 The old-style files named by the variables `todo-file-do' and
4550 `todo-file-done' from the old package are converted to the new
4551 format and saved (the latter as a todo archive file) with a new
4552 name in `todo-directory'. See also the documentation string of
4553 `todo-legacy-date-time-regexp' for further details."
4555 ;; If there are user customizations of legacy options, use them,
4556 ;; otherwise use the legacy default values.
4557 (let ((todo-file-do-tem (if (boundp 'todo-file-do)
4559 (locate-user-emacs-file "todo-do" ".todo-do")))
4560 (todo-file-done-tem (if (boundp 'todo-file-done)
4562 (locate-user-emacs-file "todo-done" ".todo-done")))
4563 (todo-initials-tem (and (boundp 'todo-initials) todo-initials))
4564 (todo-entry-prefix-function-tem (and (boundp 'todo-entry-prefix-function)
4565 todo-entry-prefix-function))
4567 ;; Convert `todo-file-do'.
4568 (if (not (file-exists-p todo-file-do-tem))
4569 (message "No legacy todo file exists")
4570 (let ((default "todo-do-conv")
4573 (insert-file-contents todo-file-do-tem)
4574 ;; Eliminate old-style local variables list in first line.
4575 (delete-region (line-beginning-position) (1+ (line-end-position)))
4576 (search-forward " --- " nil t) ; Legacy todo-category-beg.
4577 (setq todo-prefix-tem (buffer-substring-no-properties
4578 (line-beginning-position) (match-beginning 0)))
4579 (goto-char (point-min))
4582 ;; Old-style category start delimiter.
4583 ((looking-at (regexp-quote (concat todo-prefix-tem " --- ")))
4584 (replace-match todo-category-beg))
4585 ;; Old-style category end delimiter.
4586 ((looking-at (regexp-quote "--- End"))
4588 ;; Old-style category separator.
4589 ((looking-at (regexp-quote
4590 (concat todo-prefix-tem " "
4591 (make-string 75 ?-))))
4592 (replace-match todo-category-done))
4593 ;; Old-style item header (date/time/initials).
4594 ((looking-at (concat (regexp-quote todo-prefix-tem) " "
4595 (if todo-entry-prefix-function-tem
4596 (funcall todo-entry-prefix-function-tem)
4597 (concat todo-legacy-date-time-regexp " "
4598 (if todo-initials-tem
4599 (regexp-quote todo-initials-tem)
4602 (todo-convert-legacy-date-time)))
4604 (setq file (concat todo-directory
4606 (format "Save file as (default \"%s\"): " default)
4609 (unless (file-exists-p todo-directory)
4610 (make-directory todo-directory))
4611 (write-region (point-min) (point-max) file nil 'nomessage nil t))
4613 (insert-file-contents file)
4614 (let ((todo-categories (todo-make-categories-list t)))
4615 (todo-update-categories-sexp)
4616 (todo-check-format))
4617 (write-region (point-min) (point-max) file nil 'nomessage))
4618 (setq todo-files (funcall todo-files-function))
4619 ;; Convert `todo-file-done'.
4620 (when (file-exists-p todo-file-done-tem)
4622 (insert-file-contents todo-file-done-tem)
4623 (let ((beg (make-marker))
4625 cat cats comment item)
4627 (when (looking-at todo-legacy-date-time-regexp)
4628 (set-marker beg (point))
4629 (todo-convert-legacy-date-time)
4630 (set-marker end (point))
4632 (insert "[" todo-done-string)
4636 (when (looking-at todo-legacy-date-time-regexp)
4637 (todo-convert-legacy-date-time))
4638 (when (looking-at (concat " " (if todo-initials-tem
4643 (replace-match "")))
4644 (if (re-search-forward
4645 (concat "^" todo-legacy-date-time-regexp) nil t)
4646 (goto-char (match-beginning 0))
4647 (goto-char (point-max)))
4649 (when (looking-back "\\[\\([^][]+\\)\\]")
4650 (setq cat (match-string 1))
4651 (goto-char (match-beginning 0))
4653 ;; If the item ends with a non-comment parenthesis not
4654 ;; followed by a period, we lose (but we inherit that
4655 ;; problem from the legacy code).
4656 (when (looking-back "(\\(.*\\)) ")
4657 (setq comment (match-string 1))
4659 (insert "[" todo-comment-string ": " comment "]"))
4660 (set-marker end (point))
4661 (if (member cat cats)
4662 ;; If item is already in its category, leave it there.
4663 (unless (save-excursion
4665 (concat "^" (regexp-quote todo-category-beg)
4667 (string= (match-string 1) cat))
4668 ;; Else move it to its category.
4669 (setq item (buffer-substring-no-properties beg end))
4670 (delete-region beg (1+ end))
4671 (set-marker beg (point))
4674 (regexp-quote (concat todo-category-beg cat))
4678 (if (re-search-forward
4679 (concat "^" (regexp-quote todo-category-beg)
4681 (progn (goto-char (match-beginning 0))
4684 (goto-char (point-max)))
4689 (insert todo-category-beg cat "\n\n"
4690 todo-category-done "\n"))
4692 (set-marker beg nil)
4693 (set-marker end nil))
4694 (setq file (concat (file-name-sans-extension file) ".toda"))
4695 (write-region (point-min) (point-max) file nil 'nomessage nil t))
4697 (insert-file-contents file)
4698 (let* ((todo-categories (todo-make-categories-list t)))
4699 (todo-update-categories-sexp)
4700 (todo-check-format))
4701 (write-region (point-min) (point-max) file nil 'nomessage)
4702 (setq archive-sexp (read (buffer-substring-no-properties
4703 (line-beginning-position)
4704 (line-end-position)))))
4705 (setq file (concat (file-name-sans-extension file) ".todo"))
4706 ;; Update categories sexp of converted todo file again, adding
4707 ;; counts of archived items.
4709 (insert-file-contents file)
4710 (let ((sexp (read (buffer-substring-no-properties
4711 (line-beginning-position)
4712 (line-end-position)))))
4714 (let ((archive-cat (assoc (car cat) archive-sexp)))
4716 (aset (cdr cat) 3 (aref (cdr archive-cat) 2)))))
4717 (delete-region (line-beginning-position) (line-end-position))
4718 (prin1 sexp (current-buffer)))
4719 (write-region (point-min) (point-max) file nil 'nomessage))
4720 (setq todo-archives (funcall todo-files-function t)))
4721 (todo-reevaluate-filelist-defcustoms)
4722 (when (y-or-n-p (concat "Format conversion done; do you want to "
4723 "visit the converted file now? "))
4724 (setq todo-current-todo-file file)
4725 (unless todo-default-todo-file
4726 ;; We just initialized the first todo file, so make it the
4727 ;; default now to avoid an infinite recursion with todo-show.
4728 (setq todo-default-todo-file (todo-short-file-name file)))
4731 ;; -----------------------------------------------------------------------------
4732 ;;; Utility functions for todo files, categories and items
4733 ;; -----------------------------------------------------------------------------
4735 (defun todo-absolute-file-name (name &optional type)
4736 "Return the absolute file name of short todo file NAME.
4737 With TYPE `archive' or `top' return the absolute file name of the
4738 short todo archive or top priorities file name, respectively."
4739 ;; No-op if there is no todo file yet (i.e. don't concatenate nil).
4742 (concat todo-directory name
4743 (cond ((eq type 'archive) ".toda")
4744 ((eq type 'top) ".todt")
4745 ((eq type 'diary) ".tody")
4746 ((eq type 'regexp) ".todr")
4749 (defun todo-check-file (file)
4750 "Check the state associated with FILE and update it if necessary.
4751 If FILE exists, return t. If it does not exist and there is no
4752 live buffer with its content, return nil; if there is such a
4753 buffer and the user tries to show it, ask whether to restore
4754 FILE, and if confirmed, do so and return t; else delete the
4755 buffer, clean up the state and return nil."
4756 (setq todo-files (funcall todo-files-function))
4757 (setq todo-archives (funcall todo-files-function t))
4758 (if (file-exists-p file)
4760 (setq todo-visited (delete file todo-visited))
4761 (let ((buf (find-buffer-visiting file)))
4765 (format (concat "Todo file \"%s\" has been deleted but "
4766 "its content is still in a buffer!\n")
4767 (todo-short-file-name file))
4768 "Save that buffer and restore the todo file? ")))
4770 (with-current-buffer buf (save-buffer))
4771 (setq todo-files (funcall todo-files-function))
4772 (setq todo-archives (funcall todo-files-function t))
4774 (let* ((files (append todo-files todo-archives))
4775 (tctf todo-current-todo-file)
4776 (tgctf todo-global-current-todo-file)
4777 (tdtf (todo-absolute-file-name todo-default-todo-file)))
4778 (unless (or (not todo-current-todo-file)
4779 (member todo-current-todo-file files))
4780 (setq todo-current-todo-file nil))
4781 (unless (or (not todo-global-current-todo-file)
4782 (member todo-global-current-todo-file files))
4783 (setq todo-global-current-todo-file nil))
4784 (unless (or (not todo-default-todo-file)
4785 (member todo-default-todo-file files))
4786 (setq todo-default-todo-file (todo-short-file-name
4788 (todo-reevaluate-filelist-defcustoms)
4789 (when buf (kill-buffer buf))
4792 (defun todo-category-number (cat)
4793 "Return the number of category CAT in this todo file.
4794 The buffer-local variable `todo-category-number' holds this
4795 number as its value."
4796 (let ((categories (mapcar 'car todo-categories)))
4797 (setq todo-category-number
4798 ;; Increment by one, so that the number of the first
4799 ;; category is one rather than zero.
4800 (1+ (- (length categories)
4801 (length (member cat categories)))))))
4803 (defun todo-current-category ()
4804 "Return the name of the current category."
4805 (car (nth (1- todo-category-number) todo-categories)))
4807 (defun todo-category-select ()
4808 "Display the current category correctly."
4809 (let ((name (todo-current-category))
4810 cat-begin cat-end done-start done-sep-start done-end)
4812 (goto-char (point-min))
4814 (concat "^" (regexp-quote (concat todo-category-beg name)) "$") nil t)
4815 (setq cat-begin (1+ (line-end-position)))
4816 (setq cat-end (if (re-search-forward
4817 (concat "^" (regexp-quote todo-category-beg)) nil t)
4820 (setq mode-line-buffer-identification
4821 (funcall todo-mode-line-function name))
4822 (narrow-to-region cat-begin cat-end)
4823 (todo-prefix-overlays)
4824 (goto-char (point-min))
4825 (if (re-search-forward (concat "\n\\(" (regexp-quote todo-category-done)
4828 (setq done-start (match-beginning 0))
4829 (setq done-sep-start (match-beginning 1))
4830 (setq done-end (match-end 0)))
4831 (error "Category %s is missing todo-category-done string" name))
4832 (if todo-show-done-only
4833 (narrow-to-region (1+ done-end) (point-max))
4834 (when (and todo-show-with-done
4835 (re-search-forward todo-done-string-start nil t))
4836 ;; Now we want to see the done items, so reset displayed end to end of
4838 (setq done-start cat-end)
4839 ;; Make display overlay for done items separator string, unless there
4841 (let* ((done-sep todo-done-separator)
4842 (ov (progn (goto-char done-sep-start)
4843 (todo-get-overlay 'separator))))
4845 (setq ov (make-overlay done-sep-start done-end))
4846 (overlay-put ov 'todo 'separator)
4847 (overlay-put ov 'display done-sep))))
4848 (narrow-to-region (point-min) done-start)
4849 ;; Loading this from todo-mode, or adding it to the mode hook, causes
4850 ;; Emacs to hang in todo-item-start, at (looking-at todo-item-start).
4851 (when todo-highlight-item
4853 (hl-line-mode 1)))))
4855 (defun todo-get-count (type &optional category)
4856 "Return count of TYPE items in CATEGORY.
4857 If CATEGORY is nil, default to the current category."
4858 (let* ((cat (or category (todo-current-category)))
4859 (counts (cdr (assoc cat todo-categories)))
4860 (idx (cond ((eq type 'todo) 0)
4861 ((eq type 'diary) 1)
4863 ((eq type 'archived) 3))))
4866 (defun todo-update-count (type increment &optional category)
4867 "Change count of TYPE items in CATEGORY by integer INCREMENT.
4868 With nil or omitted CATEGORY, default to the current category."
4869 (let* ((cat (or category (todo-current-category)))
4870 (counts (cdr (assoc cat todo-categories)))
4871 (idx (cond ((eq type 'todo) 0)
4872 ((eq type 'diary) 1)
4874 ((eq type 'archived) 3))))
4875 (aset counts idx (+ increment (aref counts idx)))))
4877 (defun todo-set-categories ()
4878 "Set `todo-categories' from the sexp at the top of the file."
4879 ;; New archive files created by `todo-move-category' are empty, which would
4880 ;; make the sexp test fail and raise an error, so in this case we skip it.
4881 (unless (zerop (buffer-size))
4885 (goto-char (point-min))
4886 (setq todo-categories
4887 (if (looking-at "\(\(\"")
4888 (read (buffer-substring-no-properties
4889 (line-beginning-position)
4890 (line-end-position)))
4891 (error "Invalid or missing todo-categories sexp")))))))
4893 (defun todo-update-categories-sexp ()
4894 "Update the `todo-categories' sexp at the top of the file."
4895 (let (buffer-read-only)
4899 (goto-char (point-min))
4900 (if (looking-at (concat "^" (regexp-quote todo-category-beg)))
4901 (progn (newline) (goto-char (point-min)) ; Make space for sexp.
4902 (setq todo-categories (todo-make-categories-list t)))
4903 (delete-region (line-beginning-position) (line-end-position)))
4904 (prin1 todo-categories (current-buffer))))))
4906 (defun todo-make-categories-list (&optional force)
4907 "Return an alist of todo categories and their item counts.
4908 With non-nil argument FORCE parse the entire file to build the
4909 list; otherwise, get the value by reading the sexp at the top of
4911 (setq todo-categories nil)
4915 (goto-char (point-min))
4916 (let (counts cat archive)
4917 ;; If the file is a todo file and has archived items, identify the
4918 ;; archive, in order to count its items. But skip this with
4919 ;; `todo-convert-legacy-files', since that converts filed items to
4921 (when buffer-file-name ; During conversion there is no file yet.
4922 ;; If the file is an archive, it doesn't have an archive.
4923 (unless (member (file-truename buffer-file-name)
4924 (funcall todo-files-function t))
4925 (setq archive (concat (file-name-sans-extension
4926 todo-current-todo-file) ".toda"))))
4928 (cond ((looking-at (concat (regexp-quote todo-category-beg)
4930 (setq cat (match-string-no-properties 1))
4931 ;; Counts for each category: [todo diary done archive]
4932 (setq counts (make-vector 4 0))
4933 (setq todo-categories
4934 (append todo-categories (list (cons cat counts))))
4935 ;; Add archived item count to the todo file item counts.
4936 ;; Make sure to include newly created archives, e.g. due to
4937 ;; todo-move-category.
4938 (when (member archive (funcall todo-files-function t))
4939 (let ((archive-count 0)
4940 (visiting (find-buffer-visiting archive)))
4941 (with-current-buffer (or visiting
4942 (find-file-noselect archive))
4946 (goto-char (point-min))
4947 (when (re-search-forward
4948 (concat "^" (regexp-quote todo-category-beg)
4952 (while (not (or (looking-at
4954 (regexp-quote todo-category-beg)
4957 (when (looking-at todo-done-string-start)
4958 (setq archive-count (1+ archive-count)))
4960 (unless visiting (kill-buffer)))
4961 (todo-update-count 'archived archive-count cat))))
4962 ((looking-at todo-done-string-start)
4963 (todo-update-count 'done 1 cat))
4964 ((looking-at (concat "^\\("
4965 (regexp-quote diary-nonmarking-symbol)
4966 "\\)?" todo-date-pattern))
4967 (todo-update-count 'diary 1 cat)
4968 (todo-update-count 'todo 1 cat))
4969 ((looking-at (concat todo-date-string-start todo-date-pattern))
4970 (todo-update-count 'todo 1 cat))
4971 ;; If first line is todo-categories list, use it and end loop
4972 ;; -- unless FORCEd to scan whole file.
4975 (setq todo-categories (read (buffer-substring-no-properties
4976 (line-beginning-position)
4977 (line-end-position))))
4978 (goto-char (1- (point-max))))))
4982 (defun todo-repair-categories-sexp ()
4983 "Repair corrupt todo file categories sexp.
4984 This should only be needed as a consequence of careless manual
4985 editing or a bug in todo.el.
4987 *Warning*: Calling this command restores the category order to
4988 the list element order in the todo file categories sexp, so any
4989 order changes made in Todo Categories mode will have to be made
4992 (let ((todo-categories (todo-make-categories-list t)))
4993 (todo-update-categories-sexp)))
4995 (defun todo-check-format ()
4996 "Signal an error if the current todo file is ill-formatted.
4997 Otherwise return t. Display a message if the file is well-formed
4998 but the categories sexp differs from the current value of
5003 (goto-char (point-min))
5004 (let* ((cats (prin1-to-string todo-categories))
5005 (ssexp (buffer-substring-no-properties (line-beginning-position)
5006 (line-end-position)))
5007 (sexp (read ssexp)))
5008 ;; Check the first line for `todo-categories' sexp.
5011 (unless (and (stringp (car c))
5014 (user-error "Invalid or missing todo-categories sexp"))))
5016 ;; Check well-formedness of categories.
5017 (let ((legit (concat
5018 "\\(^" (regexp-quote todo-category-beg) "\\)"
5019 "\\|\\(" todo-date-string-start todo-date-pattern "\\)"
5020 "\\|\\(^[ \t]+[^ \t]*\\)"
5022 "\\|\\(^" (regexp-quote todo-category-done) "\\)"
5023 "\\|\\(" todo-done-string-start "\\)")))
5025 (unless (looking-at legit)
5026 (user-error "Illegitimate todo file format at line %d"
5027 (line-number-at-pos (point))))
5029 ;; Warn user if categories sexp has changed.
5030 (unless (string= ssexp cats)
5031 (message (concat "The sexp at the beginning of the file differs "
5032 "from the value of `todo-categories.\n"
5033 "If the sexp is wrong, you can fix it with "
5034 "M-x todo-repair-categories-sexp,\n"
5035 "but note this reverts any changes you have "
5036 "made in the order of the categories."))))))
5039 (defun todo-item-start ()
5040 "Move to start of current todo item and return its position."
5042 ;; Buffer is empty (invocation possible e.g. via todo-forward-item
5043 ;; from todo-filter-items when processing category with no todo
5045 (eq (point-min) (point-max))
5046 ;; Point is on the empty line below category's last todo item...
5047 (and (looking-at "^$")
5048 (or (eobp) ; ...and done items are hidden...
5049 (save-excursion ; ...or done items are visible.
5051 (looking-at (concat "^"
5052 (regexp-quote todo-category-done))))))
5053 ;; Buffer is widened.
5054 (looking-at (regexp-quote todo-category-beg)))
5055 (goto-char (line-beginning-position))
5056 (while (not (looking-at todo-item-start))
5060 (defun todo-item-end ()
5061 "Move to end of current todo item and return its position."
5062 ;; Items cannot end with a blank line.
5063 (unless (looking-at "^$")
5064 (let* ((done (todo-done-item-p))
5066 ;; For todo items, end is before the done items section, for done
5067 ;; items, end is before the next category. If these limits are
5068 ;; missing or inaccessible, end it before the end of the buffer.
5069 (lim (if (save-excursion
5071 (concat "^" (regexp-quote (if done
5073 todo-category-done)))
5075 (progn (setq to-lim t) (match-beginning 0))
5077 (when (bolp) (forward-char)) ; Find start of next item.
5078 (goto-char (if (re-search-forward todo-item-start lim t)
5080 (if to-lim lim (point-max))))
5081 ;; For last todo item, skip back over the empty line before the done
5082 ;; items section, else just back to the end of the previous line.
5083 (backward-char (when (and to-lim (not done) (eq (point) lim)) 2))
5086 (defun todo-item-string ()
5087 "Return bare text of current item as a string."
5088 (let ((opoint (point))
5089 (start (todo-item-start))
5090 (end (todo-item-end)))
5092 (and start end (buffer-substring-no-properties start end))))
5094 (defun todo-forward-item (&optional count)
5095 "Move point COUNT items down (by default, move down by one item)."
5096 (let* ((not-done (not (or (todo-done-item-p) (looking-at "^$"))))
5097 (start (line-end-position)))
5099 (if (re-search-forward todo-item-start nil t (or count 1))
5100 (goto-char (match-beginning 0))
5101 (goto-char (point-max)))
5102 ;; If points advances by one from a todo to a done item, go back
5103 ;; to the space above todo-done-separator, since that is a
5104 ;; legitimate place to insert an item. But skip this space if
5105 ;; count > 1, since that should only stop on an item.
5106 (when (and not-done (todo-done-item-p) (not count))
5107 ;; (if (or (not count) (= count 1))
5108 (re-search-backward "^$" start t))));)
5109 ;; The preceding sexp is insufficient when buffer is not narrowed,
5110 ;; since there could be no done items in this category, so the
5111 ;; search puts us on first todo item of next category. Does this
5112 ;; ever happen? If so:
5113 ;; (let ((opoint) (point))
5114 ;; (forward-line -1)
5115 ;; (when (or (not count) (= count 1))
5116 ;; (cond ((looking-at (concat "^" (regexp-quote todo-category-beg)))
5117 ;; (forward-line -2))
5118 ;; ((looking-at (concat "^" (regexp-quote todo-category-done)))
5119 ;; (forward-line -1))
5121 ;; (goto-char opoint)))))))
5123 (defun todo-backward-item (&optional count)
5124 "Move point up to start of item with next higher priority.
5125 With positive numerical prefix COUNT, move point COUNT items
5128 If the category's done items are visible, this command called
5129 with a prefix argument only moves point to a higher item, e.g.,
5130 with point on the first done item and called with prefix 1, it
5131 moves to the last todo item; but if called with point on the
5132 first done item without a prefix argument, it moves point the the
5133 empty line above the done items separator."
5134 (let* ((done (todo-done-item-p)))
5137 (re-search-backward todo-item-start nil t (or count 1)))
5138 ;; Unless this is a regexp filtered items buffer (which can contain
5139 ;; intermixed todo and done items), if points advances by one from a
5140 ;; done to a todo item, go back to the space above
5141 ;; todo-done-separator, since that is a legitimate place to insert an
5142 ;; item. But skip this space if count > 1, since that should only
5144 (when (and done (not (todo-done-item-p)) (not count)
5145 ;(or (not count) (= count 1))
5146 (not (equal (buffer-name) todo-regexp-items-buffer)))
5147 (re-search-forward (concat "^" (regexp-quote todo-category-done))
5149 (forward-line -1))))
5151 (defun todo-remove-item ()
5152 "Internal function called in editing, deleting or moving items."
5153 (let* ((end (progn (todo-item-end) (1+ (point))))
5154 (beg (todo-item-start))
5155 (ov (todo-get-overlay 'prefix)))
5156 (when ov (delete-overlay ov))
5157 (delete-region beg end)))
5159 (defun todo-diary-item-p ()
5160 "Return non-nil if item at point has diary entry format."
5162 (when (todo-item-string) ; Exclude empty lines.
5164 (not (looking-at (regexp-quote todo-nondiary-start))))))
5166 ;; This duplicates the item locating code from diary-goto-entry, but
5167 ;; without the marker code, to test whether the latter is dispensable.
5168 ;; If it is, diary-goto-entry can be simplified. The code duplication
5169 ;; here can also be eliminated, leaving only the widening and category
5170 ;; selection, and instead of :override advice :around can be used.
5172 (defun todo-diary-goto-entry (button)
5173 "Jump to the diary entry for the BUTTON at point.
5174 If the entry is a todo item, display its category properly.
5175 Overrides `diary-goto-entry'."
5176 ;; Locate the diary item in its source file.
5177 (let* ((locator (button-get button 'locator))
5178 (file (cadr locator))
5179 (date (regexp-quote (nth 2 locator)))
5180 (content (regexp-quote (nth 3 locator))))
5181 (if (not (and (file-exists-p file)
5182 (find-file-other-window file)))
5183 (message "Unable to locate this diary entry")
5184 ;; If it's a Todo file, make sure it's in Todo mode.
5185 (when (and (equal (file-name-directory (file-truename file))
5186 (file-truename todo-directory))
5187 (not (derived-mode-p 'todo-mode)))
5189 (when (eq major-mode 'todo-mode) (widen))
5190 (goto-char (point-min))
5191 (when (re-search-forward (format "%s.*\\(%s\\)" date content) nil t)
5192 (goto-char (match-beginning 1)))
5193 ;; If it's a todo item, determine its category and display the
5194 ;; category properly.
5195 (when (eq major-mode 'todo-mode)
5196 (let ((opoint (point)))
5197 (re-search-backward (concat "^" (regexp-quote todo-category-beg)
5198 "\\(.*\\)\n") nil t)
5199 (todo-category-number (match-string 1))
5200 (todo-category-select)
5201 (goto-char opoint))))))
5203 (add-function :override diary-goto-entry-function #'todo-diary-goto-entry)
5205 (defun todo-desktop-save-buffer (_dir)
5206 `((catnum . ,(todo-category-number (todo-current-category)))))
5208 (declare-function desktop-restore-file-buffer "desktop"
5209 (buffer-filename buffer-name buffer-misc))
5211 (defun todo-restore-desktop-buffer (file buffer misc)
5212 (desktop-restore-file-buffer file buffer misc)
5213 (with-current-buffer buffer
5215 (let ((todo-category-number (cdr (assq 'catnum misc))))
5216 (todo-category-select))))
5218 (add-to-list 'desktop-buffer-mode-handlers
5219 '(todo-mode . todo-restore-desktop-buffer))
5221 (defun todo-done-item-p ()
5222 "Return non-nil if item at point is a done item."
5225 (looking-at todo-done-string-start)))
5227 (defun todo-done-item-section-p ()
5228 "Return non-nil if point is in category's done items section."
5230 (or (re-search-backward (concat "^" (regexp-quote todo-category-done))
5232 (progn (goto-char (point-min))
5233 (looking-at todo-done-string-start)))))
5235 (defun todo-reset-done-separator (sep)
5236 "Replace existing overlays of done items separator string SEP."
5240 (goto-char (point-min))
5241 (while (re-search-forward
5242 (concat "\n\\(" (regexp-quote todo-category-done) "\\)") nil t)
5243 (let* ((beg (match-beginning 1))
5245 (ov (progn (goto-char beg)
5246 (todo-get-overlay 'separator)))
5247 (old-sep (when ov (overlay-get ov 'display)))
5250 (unless (string= old-sep sep)
5251 (setq new-ov (make-overlay beg end))
5252 (overlay-put new-ov 'todo 'separator)
5253 (overlay-put new-ov 'display todo-done-separator)
5254 (delete-overlay ov))))))))
5256 (defun todo-get-overlay (val)
5257 "Return the overlay at point whose `todo' property has value VAL."
5258 ;; Use overlays-in to find prefix overlays and check over two
5259 ;; positions to find done separator overlay.
5260 (let ((ovs (overlays-in (point) (1+ (point))))
5265 (when (eq (overlay-get ov 'todo) val)
5266 (throw 'done ov))))))
5268 (defun todo-marked-item-p ()
5269 "Non-nil if this item begins with `todo-item-mark'.
5270 In that case, return the item's prefix overlay."
5271 (let* ((ov (todo-get-overlay 'prefix))
5272 ;; If an item insertion command is called on a todo file
5273 ;; before it is visited, it has no prefix overlays yet, so
5275 (pref (when ov (overlay-get ov 'before-string)))
5277 (string-match (concat "^" (regexp-quote todo-item-mark))
5281 (defun todo-insert-with-overlays (item)
5282 "Insert ITEM at point and update prefix/priority number overlays."
5284 ;; Insertion pushes item down but not its prefix overlay. When the
5285 ;; overlay includes a mark, this would now mark the inserted ITEM,
5286 ;; so move it to the pushed down item.
5287 (let ((ov (todo-get-overlay 'prefix))
5288 (marked (todo-marked-item-p)))
5290 (when marked (move-overlay ov (point) (point))))
5291 (todo-backward-item)
5292 (todo-prefix-overlays))
5294 (defun todo-prefix-overlays ()
5295 "Update the prefix overlays of the current category's items.
5296 The overlay's value is the string `todo-prefix' or with non-nil
5297 `todo-number-prefix' an integer in the sequence from 1 to
5298 the number of todo or done items in the category indicating the
5299 item's priority. Todo and done items are numbered independently
5302 (cat-tp (or (cdr (assoc-string
5303 (todo-current-category)
5304 (nth 2 (assoc-string todo-current-todo-file
5305 todo-top-priorities-overrides))))
5306 todo-top-priorities))
5309 (goto-char (point-min))
5311 (when (or (todo-date-string-matcher (line-end-position))
5312 (todo-done-string-matcher (line-end-position)))
5313 (goto-char (match-beginning 0))
5315 ;; Reset number to 1 for first done item.
5316 (when (and (eq major-mode 'todo-mode)
5317 (looking-at todo-done-string-start)
5318 (looking-back (concat "^"
5319 (regexp-quote todo-category-done)
5323 (setq prefix (concat (propertize
5324 (if todo-number-prefix
5325 (number-to-string num)
5328 ;; Prefix of top priority items has a
5329 ;; distinct face in Todo mode.
5330 (if (and (eq major-mode 'todo-mode)
5334 'todo-prefix-string))
5336 (let ((ov (todo-get-overlay 'prefix))
5337 (marked (todo-marked-item-p)))
5338 ;; Prefix overlay must be at a single position so its
5339 ;; bounds aren't changed when (re)moving an item.
5340 (unless ov (setq ov (make-overlay (point) (point))))
5341 (overlay-put ov 'todo 'prefix)
5342 (overlay-put ov 'before-string (if marked
5343 (concat todo-item-mark prefix)
5347 ;; -----------------------------------------------------------------------------
5348 ;;; Generating and applying item insertion and editing key sequences
5349 ;; -----------------------------------------------------------------------------
5351 ;; Thanks to Stefan Monnier for suggesting dynamically generating item
5352 ;; insertion commands and their key bindings, and offering an elegant
5353 ;; implementation, which, however, relies on lexical scoping and so
5354 ;; cannot be used here until the Calendar code used by todo-mode.el is
5355 ;; converted to lexical binding. Hence, the following implementation
5356 ;; uses dynamic binding.
5358 (defconst todo-insert-item--parameters
5359 '((default copy) (diary nonmarking) (calendar date dayname) time (here region))
5360 "List of all item insertion parameters.
5361 Passed by `todo-insert-item' to `todo-insert-item--next-param' to
5362 dynamically create item insertion commands.")
5364 (defconst todo-insert-item--param-key-alist
5375 "List pairing item insertion parameters with their completion keys.")
5377 (defsubst todo-insert-item--keyof (param)
5378 "Return key paired with item insertion PARAM."
5379 (cdr (assoc param todo-insert-item--param-key-alist)))
5381 (defun todo-insert-item--argsleft (key list)
5382 "Return sublist of LIST whose first member corresponds to KEY."
5388 (when (equal key (todo-insert-item--keyof s))
5389 (throw 'found1 (setq sym s))))))
5396 (setq list (reverse l)))
5397 (memq (catch 'found2
5398 (dolist (e todo-insert-item--param-key-alist)
5399 (when (equal key (cdr e))
5400 (throw 'found2 (car e)))))
5403 (defsubst todo-insert-item--this-key () (char-to-string last-command-event))
5405 (defvar todo-insert-item--keys-so-far ""
5406 "String of item insertion keys so far entered for this command.")
5408 (defvar todo-insert-item--args nil)
5409 (defvar todo-insert-item--argleft nil)
5410 (defvar todo-insert-item--argsleft nil)
5411 (defvar todo-insert-item--newargsleft nil)
5413 (defun todo-insert-item--apply-args ()
5414 "Build list of arguments for item insertion and apply them.
5415 The list consists of item insertion parameters that can be passed
5416 as insertion command arguments in fixed positions. If a position
5417 in the list is not occupied by the corresponding parameter, it is
5419 (let* ((arg (list (car todo-insert-item--args)))
5420 (args (nconc (cdr todo-insert-item--args)
5421 (list (car (todo-insert-item--argsleft
5422 (todo-insert-item--this-key)
5423 todo-insert-item--argsleft)))))
5424 (arglist (if (= 4 (length args))
5426 (let ((v (make-vector 4 nil)) elt)
5428 (setq elt (pop args))
5429 (cond ((memq elt '(diary nonmarking))
5431 ((memq elt '(calendar date dayname))
5435 ((memq elt '(copy here region))
5438 (apply #'todo-insert-item--basic (nconc arg arglist))))
5440 (defun todo-insert-item--next-param (last args argsleft)
5441 "Build item insertion command from LAST, ARGS and ARGSLEFT and call it.
5442 Dynamically generate key bindings, prompting with the keys
5443 already entered and those still available."
5444 (cl-assert argsleft)
5445 (let* ((map (make-sparse-keymap))
5453 (if (memq name '(default diary calendar here))
5456 (when (memq name '(copy nonmarking dayname region))
5458 (propertize k 'face 'todo-key-prompt)
5460 (setq todo-insert-item--args args)
5461 (setq todo-insert-item--argsleft argsleft)
5463 (if (memq last '(default copy))
5465 (setq todo-insert-item--argsleft nil)
5466 (todo-insert-item--apply-args))
5467 (let ((k (todo-insert-item--keyof last)))
5468 (funcall addprompt k (make-symbol (concat (symbol-name last) ":GO!")))
5469 (define-key map (todo-insert-item--keyof last)
5470 (lambda () (interactive)
5471 (todo-insert-item--apply-args))))))
5472 (while todo-insert-item--argsleft
5473 (let ((x (car todo-insert-item--argsleft)))
5474 (setq todo-insert-item--newargsleft (cdr todo-insert-item--argsleft))
5475 (dolist (argleft (if (consp x) x (list x)))
5476 (let ((k (todo-insert-item--keyof argleft)))
5477 (funcall addprompt k argleft)
5479 (if (null todo-insert-item--newargsleft)
5480 (lambda () (interactive)
5481 (todo-insert-item--apply-args))
5482 (lambda () (interactive)
5483 (setq todo-insert-item--keys-so-far
5484 (concat todo-insert-item--keys-so-far " "
5485 (todo-insert-item--this-key)))
5486 (todo-insert-item--next-param
5487 (car (todo-insert-item--argsleft
5488 (todo-insert-item--this-key)
5489 todo-insert-item--argsleft))
5490 (nconc todo-insert-item--args
5491 (list (car (todo-insert-item--argsleft
5492 (todo-insert-item--this-key)
5493 todo-insert-item--argsleft))))
5494 (cdr (todo-insert-item--argsleft
5495 (todo-insert-item--this-key)
5496 todo-insert-item--argsleft)))))))))
5497 (setq todo-insert-item--argsleft todo-insert-item--newargsleft))
5498 (when prompt (message "Press a key (so far `%s'): %s"
5499 todo-insert-item--keys-so-far prompt))
5500 (set-transient-map map)
5501 (setq todo-insert-item--argsleft argsleft)))
5503 (defconst todo-edit-item--param-key-alist
5511 "Alist of item editing parameters and their keys.")
5513 (defconst todo-edit-item--date-param-key-alist
5521 "Alist of item date editing parameters and their keys.")
5523 (defconst todo-edit-done-item--param-key-alist
5526 "Alist of done item comment editing parameters and their keys.")
5528 (defvar todo-edit-item--prompt "Press a key (so far `e'): ")
5530 (defun todo-edit-item--next-key (params &optional arg)
5531 (let* ((map (make-sparse-keymap))
5532 (p->k (mapconcat (lambda (elt)
5534 (propertize (cdr elt) 'face
5536 (concat (symbol-name (car elt))
5537 (when (memq (car elt)
5541 (this-key (char-to-string
5542 (read-key (concat todo-edit-item--prompt p->k))))
5543 (this-param (car (rassoc this-key params))))
5545 (`edit (todo-edit-item--text))
5546 (`header (todo-edit-item--text 'include-header))
5547 (`multiline (todo-edit-item--text 'multiline))
5548 (`add/edit (todo-edit-item--text 'comment-edit))
5549 (`delete (todo-edit-item--text 'comment-delete))
5550 (`diary (todo-edit-item--diary-inclusion))
5551 (`nonmarking (todo-edit-item--diary-inclusion 'nonmarking))
5552 (`date (let ((todo-edit-item--prompt "Press a key (so far `e d'): "))
5553 (todo-edit-item--next-key
5554 todo-edit-item--date-param-key-alist arg)))
5555 (`full (progn (todo-edit-item--header 'date)
5556 (when todo-always-add-time-string
5557 (todo-edit-item--header 'time))))
5558 (`calendar (todo-edit-item--header 'calendar))
5559 (`today (todo-edit-item--header 'today))
5560 (`dayname (todo-edit-item--header 'dayname))
5561 (`year (todo-edit-item--header 'year arg))
5562 (`month (todo-edit-item--header 'month arg))
5563 (`daynum (todo-edit-item--header 'day arg))
5564 (`time (todo-edit-item--header 'time)))))
5566 ;; -----------------------------------------------------------------------------
5567 ;;; Todo minibuffer utilities
5568 ;; -----------------------------------------------------------------------------
5570 (defcustom todo-y-with-space nil
5571 "Non-nil means allow SPC to affirm a \"y or n\" question."
5575 (defun todo-y-or-n-p (prompt)
5576 "Ask \"y or n\" question PROMPT and return t if answer is \"y\".
5577 Also return t if answer is \"Y\", but unlike `y-or-n-p', allow
5578 SPC to affirm the question only if option `todo-y-with-space' is
5580 (unless todo-y-with-space
5581 (define-key query-replace-map " " 'ignore))
5584 (define-key query-replace-map " " 'act)))
5586 (defun todo-category-completions (&optional archive)
5587 "Return a list of completions for `todo-read-category'.
5588 Each element of the list is a cons of a category name and the
5589 file or list of files (as short file names) it is in. The files
5590 are either the current (or if there is none, the default) todo
5591 file plus the files listed in `todo-category-completions-files',
5592 or, with non-nil ARCHIVE, the current archive file.
5594 Before calculating the completions, update the value of
5595 `todo-category-completions-files' in case any files named in it
5598 (dolist (f todo-category-completions-files)
5599 (unless (file-exists-p (todo-absolute-file-name f))
5600 (setq todo-category-completions-files
5601 (delete f todo-category-completions-files))
5604 (let ((pl (> (length deleted) 1))
5605 (names (mapconcat (lambda (f) (concat "\"" f "\"")) deleted ", ")))
5606 (message (concat "File" (if pl "s" "") " " names " ha" (if pl "ve" "s")
5607 " been deleted and removed from\n"
5608 "the list of category completion files")))
5609 (todo-reevaluate-category-completions-files-defcustom)
5610 (custom-set-default 'todo-category-completions-files
5611 (symbol-value 'todo-category-completions-files))
5613 (let* ((curfile (or todo-current-todo-file
5614 (and todo-show-current-file
5615 todo-global-current-todo-file)
5616 (todo-absolute-file-name todo-default-todo-file)))
5617 (files (or (unless archive
5618 (mapcar 'todo-absolute-file-name
5619 todo-category-completions-files))
5622 ;; If file was just added, it has no category completions.
5623 (unless (zerop (buffer-size (find-buffer-visiting curfile)))
5624 (unless (member curfile todo-archives)
5625 (add-to-list 'files curfile))
5626 (dolist (f files listall)
5627 (with-current-buffer (find-file-noselect f 'nowarn)
5629 (unless (derived-mode-p 'todo-archive-mode) (todo-archive-mode))
5630 (unless (derived-mode-p 'todo-mode) (todo-mode)))
5631 ;; Ensure category is properly displayed in case user
5632 ;; switches to file via a non-Todo mode command. And if
5633 ;; done items in category are visible, keep them visible.
5634 (let ((done todo-show-with-done))
5635 (when (> (buffer-size) (- (point-max) (point-min)))
5637 (goto-char (point-min))
5638 (setq done (re-search-forward todo-done-string-start nil t))))
5639 (let ((todo-show-with-done done))
5640 (save-excursion (todo-category-select))))
5644 (goto-char (point-min))
5645 (setq listf (read (buffer-substring-no-properties
5646 (line-beginning-position)
5647 (line-end-position)))))))
5648 (mapc (lambda (elt) (let* ((cat (car elt))
5649 (la-elt (assoc cat listall)))
5651 (setcdr la-elt (append (list (cdr la-elt))
5653 (push (cons cat f) listall))))
5656 (defun todo-read-file-name (prompt &optional archive mustmatch)
5657 "Choose and return the name of a todo file, prompting with PROMPT.
5659 Show completions with TAB or SPC; the names are shown in short
5660 form but the absolute truename is returned. With non-nil ARCHIVE
5661 return the absolute truename of a todo archive file. With non-nil
5662 MUSTMATCH the name of an existing file must be chosen;
5663 otherwise, a new file name is allowed."
5664 (let* ((completion-ignore-case todo-completion-ignore-case)
5665 (files (mapcar 'todo-short-file-name
5666 ;; (funcall todo-files-function archive)))
5667 (if archive todo-archives todo-files)))
5668 (file (completing-read prompt files nil mustmatch nil nil
5670 ;; If user hit RET without
5671 ;; choosing a file, default to
5672 ;; current or default file.
5673 (todo-short-file-name
5674 (or todo-current-todo-file
5675 (and todo-show-current-file
5676 todo-global-current-todo-file)
5677 (todo-absolute-file-name
5678 todo-default-todo-file)))
5679 ;; Trigger prompt for initial file.
5681 (unless (file-exists-p todo-directory)
5682 (make-directory todo-directory))
5683 (unless (or mustmatch (member file files))
5684 (setq file (todo-validate-name file 'file)))
5685 (setq file (file-truename (concat todo-directory file
5686 (if archive ".toda" ".todo"))))))
5688 (defun todo-read-category (prompt &optional match-type file)
5689 "Choose and return a category name, prompting with PROMPT.
5690 Show completions for existing categories with TAB or SPC.
5692 The argument MATCH-TYPE specifies the matching requirements on
5693 the category name: with the value `todo' or `archive' the name
5694 must complete to that of an existing todo or archive category,
5695 respectively; with the value `add' the name must not be that of
5696 an existing category; with all other values both existing and new
5697 valid category names are accepted.
5699 With non-nil argument FILE prompt for a file and complete only
5700 against categories in that file; otherwise complete against all
5701 categories from `todo-category-completions-files'."
5702 ;; Allow SPC to insert spaces, for adding new category names.
5703 (let ((map minibuffer-local-completion-map))
5704 (define-key map " " nil)
5705 (let* ((add (eq match-type 'add))
5706 (archive (eq match-type 'archive))
5707 (file0 (when (and file (> (length todo-files) 1))
5708 (todo-read-file-name (concat "Choose a" (if archive
5711 " file: ") archive t)))
5712 (completions (unless file0 (todo-category-completions archive)))
5713 (categories (cond (file0
5714 (with-current-buffer
5715 (find-file-noselect file0 'nowarn)
5716 (unless (derived-mode-p 'todo-mode) (todo-mode))
5717 (let ((todo-current-todo-file file0))
5719 ((and add (not file))
5720 (with-current-buffer
5721 (find-file-noselect todo-current-todo-file)
5725 (completion-ignore-case todo-completion-ignore-case)
5726 (cat (completing-read prompt categories nil
5727 (eq match-type 'todo) nil nil
5728 ;; Unless we're adding a category via
5729 ;; todo-add-category, set default
5730 ;; for existing categories to the
5731 ;; current category of the chosen
5732 ;; file or else of the current file.
5733 (if (and categories (not add))
5734 (with-current-buffer
5737 todo-current-todo-file
5738 (todo-absolute-file-name
5739 todo-default-todo-file)))
5740 (todo-current-category))
5741 ;; Trigger prompt for initial category.
5743 (catfil (cdr (assoc cat completions)))
5744 (str "Category \"%s\" from which file (TAB for choices)? "))
5745 ;; If we do category completion and the chosen category name
5746 ;; occurs in more than one file, prompt to choose one file.
5747 (unless (or file0 add (not catfil))
5748 (setq file0 (file-truename
5751 (todo-absolute-file-name
5752 (let ((files (mapcar 'todo-short-file-name catfil)))
5753 (completing-read (format str cat) files)))))))
5754 ;; Default to the current file.
5755 (unless file0 (setq file0 todo-current-todo-file))
5756 ;; First validate only a name passed interactively from
5757 ;; todo-add-category, which must be of a nonexistent category.
5758 (unless (and (assoc cat categories) (not add))
5759 ;; Validate only against completion categories.
5760 (let ((todo-categories categories))
5761 (setq cat (todo-validate-name cat 'category)))
5762 ;; When user enters a nonexistent category name by jumping or
5763 ;; moving, confirm that it should be added, then validate.
5765 (if (todo-y-or-n-p (format "Add new category \"%s\" to file \"%s\"? "
5766 cat (todo-short-file-name file0)))
5768 (when (assoc cat categories)
5769 (let ((todo-categories categories))
5770 (setq cat (todo-validate-name cat 'category))))
5771 ;; Restore point and narrowing after adding new
5772 ;; category, to avoid moving to beginning of file when
5773 ;; moving marked items to a new category
5774 ;; (todo-move-item).
5777 (todo-add-category file0 cat))))
5778 ;; If we decide not to add a category, exit without returning.
5782 (defun todo-validate-name (name type)
5783 "Prompt for new NAME for TYPE until it is valid, then return it.
5784 TYPE can be either of the symbols `file' or `category'."
5785 (let ((categories todo-categories)
5786 (files (mapcar 'todo-short-file-name todo-files))
5790 (cond ((string= "" name)
5792 (cond ((eq type 'file)
5794 "Enter a non-empty file name: "
5795 ;; Empty string passed by todo-show to
5796 ;; prompt for initial todo file.
5797 (concat "Initial file name ["
5798 todo-initial-file "]: ")))
5799 ((eq type 'category)
5801 "Enter a non-empty category name: "
5802 ;; Empty string passed by todo-show to
5803 ;; prompt for initial category of a new
5805 (concat "Initial category name ["
5806 todo-initial-category "]: "))))))
5807 ((string-match "\\`\\s-+\\'" name)
5809 "Enter a name that does not contain only white space: "))
5810 ((and (eq type 'file) (member name files))
5811 (setq prompt "Enter a non-existing file name: "))
5812 ((and (eq type 'category) (assoc name categories))
5813 (setq prompt "Enter a non-existing category name: ")))
5814 (setq name (if (or (and (eq type 'file) files)
5815 (and (eq type 'category) categories))
5816 (completing-read prompt (cond ((eq type 'file)
5818 ((eq type 'category)
5820 ;; Offer default initial name.
5821 (completing-read prompt (if (eq type 'file)
5824 nil nil (if (eq type 'file)
5826 todo-initial-category))))))
5829 ;; Adapted from calendar-read-date and calendar-date-string.
5830 (defun todo-read-date (&optional arg mo yr)
5831 "Prompt for Gregorian date and return it in the current format.
5833 With non-nil ARG, prompt for and return only the date component
5834 specified by ARG, which can be one of these symbols:
5835 `month' (prompt for name, return name or number according to
5836 value of `calendar-date-display-form'), `day' of month, or
5837 `year'. The value of each of these components can be `*',
5838 indicating an unspecified month, day, or year.
5840 When ARG is `day', non-nil arguments MO and YR determine the
5841 number of the last the day of the month."
5842 (let (year monthname month day
5843 dayname) ; Needed by calendar-date-display-form.
5844 (when (or (not arg) (eq arg 'year))
5845 (while (if (natnump year) (< year 1) (not (eq year '*)))
5846 (setq year (read-from-minibuffer
5847 "Year (>0 or RET for this year or * for any year): "
5848 nil nil t nil (number-to-string
5849 (calendar-extract-year
5850 (calendar-current-date)))))))
5851 (when (or (not arg) (eq arg 'month))
5852 (let* ((marray todo-month-name-array)
5853 (mlist (append marray nil))
5854 (mabarray todo-month-abbrev-array)
5855 (mablist (append mabarray nil))
5856 (completion-ignore-case todo-completion-ignore-case))
5857 (setq monthname (completing-read
5858 "Month name (RET for current month, * for any month): "
5860 (calendar-month-name (calendar-extract-month
5861 (calendar-current-date)) t))
5862 month (1+ (- (length mlist)
5863 (length (or (member monthname mlist)
5864 (member monthname mablist))))))
5865 (setq monthname (aref mabarray (1- month)))))
5866 (when (or (not arg) (eq arg 'day))
5867 (let ((last (let ((mm (or month mo))
5869 ;; If month is unspecified, use a month with 31
5870 ;; days for checking day of month input. Does
5871 ;; Calendar do anything special when * is
5872 ;; currently a shorter month?
5873 (if (= mm 13) (setq mm 1))
5874 ;; If year is unspecified, use a leap year to
5876 (if (eq year '*) (setq yy 2012))
5877 (calendar-last-day-of-month mm yy))))
5878 (while (if (natnump day) (or (< day 1) (> day last)) (not (eq day '*)))
5879 (setq day (read-from-minibuffer
5880 (format "Day (1-%d or RET for today or * for any day): "
5882 nil nil t nil (number-to-string
5883 (calendar-extract-day
5884 (calendar-current-date))))))))
5885 ;; Stringify read values (monthname is already a string).
5886 (and year (setq year (if (eq year '*)
5888 (number-to-string year))))
5889 (and day (setq day (if (eq day '*)
5891 (number-to-string day))))
5892 (and month (setq month (if (eq month '*)
5894 (number-to-string month))))
5896 (cond ((eq arg 'year) year)
5899 (if (memq 'month calendar-date-display-form)
5902 (mapconcat 'eval calendar-date-display-form ""))))
5904 (defun todo-read-dayname ()
5905 "Choose name of a day of the week with completion and return it."
5906 (let ((completion-ignore-case todo-completion-ignore-case))
5907 (completing-read "Enter a day name: "
5908 (append calendar-day-name-array nil)
5911 (defun todo-read-time ()
5912 "Prompt for and return a valid clock time as a string.
5914 Valid time strings are those matching `diary-time-regexp'.
5915 Typing `<return>' at the prompt returns the current time, if the
5916 user option `todo-always-add-time-string' is non-nil, otherwise
5917 the empty string (i.e., no time string)."
5920 (setq answer (read-string "Enter a clock time: " nil nil
5921 (when todo-always-add-time-string
5922 (substring (current-time-string) 11 16))))
5923 (when (or (string= "" answer)
5924 (string-match diary-time-regexp answer))
5928 ;; -----------------------------------------------------------------------------
5929 ;;; Customization groups and utilities
5930 ;; -----------------------------------------------------------------------------
5933 "Create and maintain categorized lists of todo items."
5934 :link '(emacs-commentary-link "todo")
5938 (defgroup todo-edit nil
5939 "User options for adding and editing todo items."
5943 (defgroup todo-categories nil
5944 "User options for Todo Categories mode."
5948 (defgroup todo-filtered nil
5949 "User options for Todo Filter Items mode."
5953 (defgroup todo-display nil
5954 "User display options for Todo mode."
5958 (defgroup todo-faces nil
5959 "Faces for the Todo modes."
5963 (defun todo-set-show-current-file (symbol value)
5964 "The :set function for user option `todo-show-current-file'."
5965 (custom-set-default symbol value)
5967 (add-hook 'pre-command-hook 'todo-show-current-file nil t)
5968 (remove-hook 'pre-command-hook 'todo-show-current-file t)))
5970 (defun todo-reset-prefix (symbol value)
5971 "The :set function for `todo-prefix' and `todo-number-prefix'."
5972 (let ((oldvalue (symbol-value symbol))
5973 (files todo-file-buffers))
5974 (custom-set-default symbol value)
5975 (when (not (equal value oldvalue))
5977 (with-current-buffer (find-file-noselect f)
5978 ;; Activate the new setting in the current category.
5979 (save-excursion (todo-category-select)))))))
5981 (defun todo-reset-nondiary-marker (symbol value)
5982 "The :set function for user option `todo-nondiary-marker'."
5983 (let* ((oldvalue (symbol-value symbol))
5984 (files (append todo-files todo-archives
5985 (directory-files todo-directory t "\.tod[rty]$" t))))
5986 (custom-set-default symbol value)
5987 ;; Need to reset these to get font-locking right.
5988 (setq todo-nondiary-start (nth 0 todo-nondiary-marker)
5989 todo-nondiary-end (nth 1 todo-nondiary-marker)
5990 todo-date-string-start
5991 ;; See comment in defvar of `todo-date-string-start'.
5992 (concat "^\\(" (regexp-quote todo-nondiary-start) "\\|"
5993 (regexp-quote diary-nonmarking-symbol) "\\)?"))
5994 (when (not (equal value oldvalue))
5996 (let ((buf (find-buffer-visiting f)))
5997 (with-current-buffer (find-file-noselect f)
5998 (let (buffer-read-only)
6000 (goto-char (point-min))
6002 (if (re-search-forward
6003 (concat "^\\(" todo-done-string-start "[^][]+] \\)?"
6004 "\\(?1:" (regexp-quote (car oldvalue))
6005 "\\)" todo-date-pattern "\\( "
6006 diary-time-regexp "\\)?\\(?2:"
6007 (regexp-quote (cadr oldvalue)) "\\)")
6010 (replace-match (nth 0 value) t t nil 1)
6011 (replace-match (nth 1 value) t t nil 2))
6014 (when (derived-mode-p 'todo-mode 'todo-archive-mode)
6015 (todo-category-select))
6017 (kill-buffer)))))))))
6019 (defun todo-reset-done-separator-string (symbol value)
6020 "The :set function for `todo-done-separator-string'."
6021 (let ((oldvalue (symbol-value symbol))
6022 (files todo-file-buffers)
6023 (sep todo-done-separator))
6024 (custom-set-default symbol value)
6025 (when (not (equal value oldvalue))
6027 (with-current-buffer (find-file-noselect f)
6028 (let (buffer-read-only)
6029 (setq todo-done-separator (todo-done-separator))
6030 (when (= 1 (length value))
6031 (todo-reset-done-separator sep)))
6032 (todo-category-select))))))
6034 (defun todo-reset-done-string (symbol value)
6035 "The :set function for user option `todo-done-string'."
6036 (let ((oldvalue (symbol-value symbol))
6037 (files (append todo-files todo-archives
6038 (directory-files todo-directory t "\.todr$" t))))
6039 (custom-set-default symbol value)
6040 ;; Need to reset this to get font-locking right.
6041 (setq todo-done-string-start
6042 (concat "^\\[" (regexp-quote todo-done-string)))
6043 (when (not (equal value oldvalue))
6045 (let ((buf (find-buffer-visiting f)))
6046 (with-current-buffer (find-file-noselect f)
6047 (let (buffer-read-only)
6049 (goto-char (point-min))
6051 (if (re-search-forward
6052 (concat "^" (regexp-quote todo-nondiary-start)
6053 "\\(" (regexp-quote oldvalue) "\\)")
6055 (replace-match value t t nil 1)
6058 (when (derived-mode-p 'todo-mode 'todo-archive-mode)
6059 (todo-category-select))
6061 (kill-buffer)))))))))
6063 (defun todo-reset-comment-string (symbol value)
6064 "The :set function for user option `todo-comment-string'."
6065 (let ((oldvalue (symbol-value symbol))
6066 (files (append todo-files todo-archives
6067 (directory-files todo-directory t "\.todr$" t))))
6068 (custom-set-default symbol value)
6069 (when (not (equal value oldvalue))
6071 (let ((buf (find-buffer-visiting f)))
6072 (with-current-buffer (find-file-noselect f)
6073 (let (buffer-read-only)
6075 (goto-char (point-min))
6077 (if (re-search-forward
6078 (concat "\\[\\(" (regexp-quote oldvalue)
6081 (replace-match value t t nil 1)
6084 (when (derived-mode-p 'todo-mode 'todo-archive-mode)
6085 (todo-category-select))
6087 (kill-buffer)))))))))
6089 (defun todo-reset-highlight-item (symbol value)
6090 "The :set function for user option `todo-highlight-item'."
6091 (let ((oldvalue (symbol-value symbol))
6092 (files (append todo-files todo-archives
6093 (directory-files todo-directory t "\.tod[rty]$" t))))
6094 (custom-set-default symbol value)
6095 (when (not (equal value oldvalue))
6097 (let ((buf (find-buffer-visiting f)))
6099 (with-current-buffer buf
6103 (hl-line-mode -1)))))))))
6105 (defun todo-reevaluate-filelist-defcustoms ()
6106 "Reevaluate defcustoms that provide choice list of todo files."
6107 (custom-set-default 'todo-default-todo-file
6108 (symbol-value 'todo-default-todo-file))
6109 (todo-reevaluate-default-file-defcustom)
6110 (custom-set-default 'todo-filter-files (symbol-value 'todo-filter-files))
6111 (todo-reevaluate-filter-files-defcustom)
6112 (custom-set-default 'todo-category-completions-files
6113 (symbol-value 'todo-category-completions-files))
6114 (todo-reevaluate-category-completions-files-defcustom))
6116 (defun todo-reevaluate-default-file-defcustom ()
6117 "Reevaluate defcustom of `todo-default-todo-file'.
6118 Called after adding or deleting a todo file. If the value of
6119 `todo-default-todo-file' before calling this function was
6120 associated with an existing file, keep that value."
6121 ;; (let ((curval todo-default-todo-file))
6123 (defcustom todo-default-todo-file (todo-short-file-name
6124 (car (funcall todo-files-function)))
6125 "Todo file visited by first session invocation of `todo-show'."
6126 :type (when todo-files
6127 `(radio ,@(mapcar (lambda (f) (list 'const f))
6128 (mapcar 'todo-short-file-name
6129 (funcall todo-files-function)))))
6131 ;; (when (and curval (file-exists-p (todo-absolute-file-name curval)))
6132 ;; (custom-set-default 'todo-default-todo-file curval)
6133 ;; ;; (custom-reevaluate-setting 'todo-default-todo-file)
6137 (defun todo-reevaluate-category-completions-files-defcustom ()
6138 "Reevaluate defcustom of `todo-category-completions-files'.
6139 Called after adding or deleting a todo file."
6140 (eval (defcustom todo-category-completions-files nil
6141 "List of files for building `todo-read-category' completions."
6142 :type `(set ,@(mapcar (lambda (f) (list 'const f))
6143 (mapcar 'todo-short-file-name
6144 (funcall todo-files-function))))
6147 (defun todo-reevaluate-filter-files-defcustom ()
6148 "Reevaluate defcustom of `todo-filter-files'.
6149 Called after adding or deleting a todo file."
6150 (eval (defcustom todo-filter-files nil
6151 "List of files for multifile item filtering."
6152 :type `(set ,@(mapcar (lambda (f) (list 'const f))
6153 (mapcar 'todo-short-file-name
6154 (funcall todo-files-function))))
6157 ;; -----------------------------------------------------------------------------
6159 ;; -----------------------------------------------------------------------------
6161 (defun todo-nondiary-marker-matcher (lim)
6162 "Search for todo item nondiary markers within LIM for font-locking."
6163 (re-search-forward (concat "^\\(?1:" (regexp-quote todo-nondiary-start) "\\)"
6164 todo-date-pattern "\\(?: " diary-time-regexp
6165 "\\)?\\(?2:" (regexp-quote todo-nondiary-end) "\\)")
6168 (defun todo-diary-nonmarking-matcher (lim)
6169 "Search for diary nonmarking symbol within LIM for font-locking."
6170 (re-search-forward (concat "^\\(?1:" (regexp-quote diary-nonmarking-symbol)
6171 "\\)" todo-date-pattern) lim t))
6173 (defun todo-date-string-matcher (lim)
6174 "Search for todo item date string within LIM for font-locking."
6176 (concat todo-date-string-start "\\(?1:" todo-date-pattern "\\)") lim t))
6178 (defun todo-time-string-matcher (lim)
6179 "Search for todo item time string within LIM for font-locking."
6180 (re-search-forward (concat todo-date-string-start todo-date-pattern
6181 " \\(?1:" diary-time-regexp "\\)") lim t))
6183 (defun todo-diary-expired-matcher (lim)
6184 "Search for expired diary item date within LIM for font-locking."
6185 (when (re-search-forward (concat "^\\(?:"
6186 (regexp-quote diary-nonmarking-symbol)
6187 "\\)?\\(?1:" todo-date-pattern "\\) \\(?2:"
6188 diary-time-regexp "\\)?") lim t)
6189 (let* ((date (match-string-no-properties 1))
6190 (time (match-string-no-properties 2))
6191 ;; Function days-between requires a non-empty time string.
6192 (date-time (concat date " " (or time "00:00"))))
6193 (or (and (not (string-match ".+day\\|\\*" date))
6194 (< (days-between date-time (current-time-string)) 0))
6195 (todo-diary-expired-matcher lim)))))
6197 (defun todo-done-string-matcher (lim)
6198 "Search for done todo item header within LIM for font-locking."
6199 (re-search-forward (concat todo-done-string-start
6203 (defun todo-comment-string-matcher (lim)
6204 "Search for done todo item comment within LIM for font-locking."
6205 (re-search-forward (concat "\\[\\(?1:" todo-comment-string "\\):")
6208 (defun todo-category-string-matcher-1 (lim)
6209 "Search for todo category name within LIM for font-locking.
6210 This is for fontifying category and file names appearing in Todo
6211 Filtered Items mode following done items."
6212 (if (eq major-mode 'todo-filtered-items-mode)
6213 (re-search-forward (concat todo-done-string-start todo-date-pattern
6214 "\\(?: " diary-time-regexp
6215 ;; Use non-greedy operator to prevent
6216 ;; capturing possible following non-diary
6218 "\\)?] \\(?1:\\[.+?\\]\\)")
6221 (defun todo-category-string-matcher-2 (lim)
6222 "Search for todo category name within LIM for font-locking.
6223 This is for fontifying category and file names appearing in Todo
6224 Filtered Items mode following todo (not done) items."
6225 (if (eq major-mode 'todo-filtered-items-mode)
6226 (re-search-forward (concat todo-date-string-start todo-date-pattern
6227 "\\(?: " diary-time-regexp "\\)?\\(?:"
6228 (regexp-quote todo-nondiary-end)
6229 "\\)? \\(?1:\\[.+\\]\\)")
6232 (defvar todo-nondiary-face 'todo-nondiary)
6233 (defvar todo-date-face 'todo-date)
6234 (defvar todo-time-face 'todo-time)
6235 (defvar todo-diary-expired-face 'todo-diary-expired)
6236 (defvar todo-done-sep-face 'todo-done-sep)
6237 (defvar todo-done-face 'todo-done)
6238 (defvar todo-comment-face 'todo-comment)
6239 (defvar todo-category-string-face 'todo-category-string)
6240 (defvar todo-font-lock-keywords
6242 '(todo-nondiary-marker-matcher 1 todo-nondiary-face t)
6243 '(todo-nondiary-marker-matcher 2 todo-nondiary-face t)
6244 ;; diary-lib.el uses font-lock-constant-face for diary-nonmarking-symbol.
6245 '(todo-diary-nonmarking-matcher 1 font-lock-constant-face t)
6246 '(todo-date-string-matcher 1 todo-date-face t)
6247 '(todo-time-string-matcher 1 todo-time-face t)
6248 '(todo-done-string-matcher 0 todo-done-face t)
6249 '(todo-comment-string-matcher 1 todo-comment-face t)
6250 '(todo-category-string-matcher-1 1 todo-category-string-face t t)
6251 '(todo-category-string-matcher-2 1 todo-category-string-face t t)
6252 '(todo-diary-expired-matcher 1 todo-diary-expired-face t)
6253 '(todo-diary-expired-matcher 2 todo-diary-expired-face t t)
6255 "Font-locking for Todo modes.")
6257 ;; -----------------------------------------------------------------------------
6259 ;; -----------------------------------------------------------------------------
6261 (defvar todo-key-bindings-t
6263 ("Af" todo-find-archive)
6264 ("Ac" todo-choose-archive)
6265 ("Ad" todo-archive-done-item)
6266 ("Cv" todo-toggle-view-done-items)
6267 ("v" todo-toggle-view-done-items)
6268 ("Ca" todo-add-category)
6269 ("Cr" todo-rename-category)
6270 ("Cg" todo-merge-category)
6271 ("Cm" todo-move-category)
6272 ("Ck" todo-delete-category)
6273 ("Cts" todo-set-top-priorities-in-category)
6274 ("Cey" todo-edit-category-diary-inclusion)
6275 ("Cek" todo-edit-category-diary-nonmarking)
6276 ("Fa" todo-add-file)
6277 ("Fr" todo-rename-file)
6278 ("Ff" todo-find-filtered-items-file)
6279 ("FV" todo-toggle-view-done-only)
6280 ("V" todo-toggle-view-done-only)
6281 ("Ftt" todo-filter-top-priorities)
6282 ("Ftm" todo-filter-top-priorities-multifile)
6283 ("Fts" todo-set-top-priorities-in-file)
6284 ("Fyy" todo-filter-diary-items)
6285 ("Fym" todo-filter-diary-items-multifile)
6286 ("Fxx" todo-filter-regexp-items)
6287 ("Fxm" todo-filter-regexp-items-multifile)
6288 ("e" todo-edit-item)
6289 ("d" todo-item-done)
6290 ("i" todo-insert-item)
6291 ("k" todo-delete-item)
6292 ("m" todo-move-item)
6293 ("u" todo-item-undone)
6294 ([remap newline] newline-and-indent)
6296 "List of key bindings for Todo mode only.")
6298 (defvar todo-key-bindings-t+a+f
6300 ("C*" todo-mark-category)
6301 ("Cu" todo-unmark-category)
6302 ("Fh" todo-toggle-item-header)
6303 ("h" todo-toggle-item-header)
6304 ("Fk" todo-delete-file)
6305 ("Fe" todo-edit-file)
6306 ("FH" todo-toggle-item-highlighting)
6307 ("H" todo-toggle-item-highlighting)
6308 ("FN" todo-toggle-prefix-numbers)
6309 ("N" todo-toggle-prefix-numbers)
6310 ("PB" todo-print-buffer)
6311 ("PF" todo-print-buffer-to-file)
6312 ("b" todo-backward-category)
6313 ("d" todo-item-done)
6314 ("f" todo-forward-category)
6315 ("j" todo-jump-to-category)
6316 ("n" todo-next-item)
6317 ("p" todo-previous-item)
6322 "List of key bindings for Todo, Archive, and Filtered Items modes.")
6324 (defvar todo-key-bindings-t+a
6326 ("Fc" todo-show-categories-table)
6328 ("X" todo-clear-matches)
6329 ("*" todo-toggle-mark-item)
6331 "List of key bindings for Todo and Todo Archive modes.")
6333 (defvar todo-key-bindings-t+f
6335 ("l" todo-lower-item-priority)
6336 ("r" todo-raise-item-priority)
6337 ("#" todo-set-item-priority)
6339 "List of key bindings for Todo and Todo Filtered Items modes.")
6341 (defvar todo-mode-map
6342 (let ((map (make-keymap)))
6343 ;; Don't suppress digit keys, so they can supply prefix arguments.
6344 (suppress-keymap map)
6345 (dolist (kb todo-key-bindings-t)
6346 (define-key map (nth 0 kb) (nth 1 kb)))
6347 (dolist (kb todo-key-bindings-t+a+f)
6348 (define-key map (nth 0 kb) (nth 1 kb)))
6349 (dolist (kb todo-key-bindings-t+a)
6350 (define-key map (nth 0 kb) (nth 1 kb)))
6351 (dolist (kb todo-key-bindings-t+f)
6352 (define-key map (nth 0 kb) (nth 1 kb)))
6354 "Todo mode keymap.")
6356 (defvar todo-archive-mode-map
6357 (let ((map (make-sparse-keymap)))
6358 (suppress-keymap map)
6359 (dolist (kb todo-key-bindings-t+a+f)
6360 (define-key map (nth 0 kb) (nth 1 kb)))
6361 (dolist (kb todo-key-bindings-t+a)
6362 (define-key map (nth 0 kb) (nth 1 kb)))
6363 (define-key map "a" 'todo-jump-to-archive-category)
6364 (define-key map "u" 'todo-unarchive-items)
6366 "Todo Archive mode keymap.")
6368 (defvar todo-edit-mode-map
6369 (let ((map (make-sparse-keymap)))
6370 (define-key map "\C-x\C-q" 'todo-edit-quit)
6371 (define-key map [remap newline] 'newline-and-indent)
6373 "Todo Edit mode keymap.")
6375 (defvar todo-categories-mode-map
6376 (let ((map (make-sparse-keymap)))
6377 (suppress-keymap map)
6378 (define-key map "c" 'todo-sort-categories-alphabetically-or-numerically)
6379 (define-key map "t" 'todo-sort-categories-by-todo)
6380 (define-key map "y" 'todo-sort-categories-by-diary)
6381 (define-key map "d" 'todo-sort-categories-by-done)
6382 (define-key map "a" 'todo-sort-categories-by-archived)
6383 (define-key map "#" 'todo-set-category-number)
6384 (define-key map "l" 'todo-lower-category)
6385 (define-key map "r" 'todo-raise-category)
6386 (define-key map "n" 'todo-next-button)
6387 (define-key map "p" 'todo-previous-button)
6388 (define-key map [tab] 'todo-next-button)
6389 (define-key map [backtab] 'todo-previous-button)
6390 (define-key map "q" 'todo-quit)
6392 "Todo Categories mode keymap.")
6394 (defvar todo-filtered-items-mode-map
6395 (let ((map (make-sparse-keymap)))
6396 (suppress-keymap map)
6397 (dolist (kb todo-key-bindings-t+a+f)
6398 (define-key map (nth 0 kb) (nth 1 kb)))
6399 (dolist (kb todo-key-bindings-t+f)
6400 (define-key map (nth 0 kb) (nth 1 kb)))
6401 (define-key map "g" 'todo-go-to-source-item)
6402 (define-key map [remap newline] 'todo-go-to-source-item)
6404 "Todo Filtered Items mode keymap.")
6407 todo-menu todo-mode-map "Todo Menu"
6410 ["Next Item" todo-next-item t]
6411 ["Previous Item" todo-previous-item t]
6413 ["Next Category" todo-forward-category t]
6414 ["Previous Category" todo-backward-category t]
6415 ["Jump to Another Category" todo-jump-to-category t]
6417 ["Visit Another Todo File" todo-show t]
6418 ["Visit Archive" todo-find-archive t]
6419 ["Visit Filtered Items File" todo-find-filtered-items-file t]
6422 ["Insert New Item" todo-insert-item t]
6423 ["Edit Item" todo-edit-item t]
6424 ["Lower Item Priority" todo-lower-item-priority t]
6425 ["Raise Item Priority" todo-raise-item-priority t]
6426 ["Set Item Priority" todo-set-item-priority t]
6427 ["Mark/Unmark Item" todo-toggle-mark-item t]
6428 ["Move (Recategorize) Item" todo-move-item t]
6429 ["Delete Item" todo-delete-item t]
6430 ["Mark and Bury Done Item" todo-item-done t]
6431 ["Undo Done Item" todo-item-undone t]
6432 ["Archive Done Item" todo-archive-done-item t]
6434 ["Add New Category" todo-add-category t]
6435 ["Rename Current Category" todo-rename-category t]
6436 ["Delete Current Category" todo-delete-category t]
6437 ["Move Current Category" todo-move-category t]
6438 ["Merge Current Category" todo-merge-category t]
6440 ["Add New Todo File" todo-add-file t]
6441 ["Rename Todo File" todo-rename-file t]
6442 ["Delete Todo File" todo-delete-file t]
6443 ["Edit Todo File" todo-edit-file t]
6445 ("Searching and Item Filtering"
6446 ["Search Todo File" todo-search t]
6447 ["Clear Match Highlighting" todo-clear-matches t]
6449 ["Set Top Priorities in File" todo-set-top-priorities-in-file t]
6450 ["Set Top Priorities in Category" todo-set-top-priorities-in-category t]
6451 ["Filter Top Priorities" todo-filter-top-priorities t]
6452 ["Filter Multifile Top Priorities" todo-filter-top-priorities-multifile t]
6453 ["Filter Diary Items" todo-filter-diary-items t]
6454 ["Filter Multifile Diary Items" todo-filter-diary-items-multifile t]
6455 ["Filter Regexp" todo-filter-regexp-items t]
6456 ["Filter Multifile Regexp" todo-filter-regexp-items-multifile t]
6458 ("Display and Printing"
6459 ["Show/Hide Done Items" todo-toggle-view-done-items t]
6460 ["Show/Hide Done Items Only" todo-toggle-view-done-only t]
6461 ["Show/Hide Item Highlighting" todo-toggle-item-highlighting t]
6462 ["Show/Hide Item Numbering" todo-toggle-prefix-numbers t]
6463 ["Show/Hide Item Header" todo-toggle-item-header t]
6465 ["Display Table of Categories" todo-show-categories-table t]
6467 ["Print Category" todo-print-buffer t]
6468 ["Print Category to File" todo-print-buffer-to-file t]
6471 ["Save Todo File" todo-save t]
6472 ["Quit Todo Mode" todo-quit t]
6475 ;; -----------------------------------------------------------------------------
6476 ;;; Hook functions and mode definitions
6477 ;; -----------------------------------------------------------------------------
6479 (defun todo-show-current-file ()
6480 "Visit current instead of default todo file with `todo-show'.
6481 Added to `pre-command-hook' in Todo mode when user option
6482 `todo-show-current-file' is set to non-nil."
6483 (setq todo-global-current-todo-file todo-current-todo-file))
6485 ;; (defun todo-display-as-todo-file ()
6486 ;; "Show todo files correctly when visited from outside of Todo mode.
6487 ;; Added to `find-file-hook' in Todo mode and Todo Archive mode."
6488 ;; (and (member this-command todo-visit-files-commands)
6489 ;; (= (- (point-max) (point-min)) (buffer-size))
6490 ;; (member major-mode '(todo-mode todo-archive-mode))
6491 ;; (todo-category-select)))
6493 ;; (defun todo-add-to-buffer-list ()
6494 ;; "Add name of just visited todo file to `todo-file-buffers'.
6495 ;; This function is added to `find-file-hook' in Todo mode."
6496 ;; (let ((filename (file-truename (buffer-file-name))))
6497 ;; (when (member filename todo-files)
6498 ;; (add-to-list 'todo-file-buffers filename))))
6500 (defun todo-update-buffer-list ()
6501 "Make current Todo mode buffer file car of `todo-file-buffers'.
6502 This function is added to `post-command-hook' in Todo mode."
6503 (let ((filename (file-truename (buffer-file-name))))
6504 (unless (eq (car todo-file-buffers) filename)
6505 (setq todo-file-buffers
6506 (cons filename (delete filename todo-file-buffers))))))
6508 (defun todo-reset-global-current-todo-file ()
6509 "Update the value of `todo-global-current-todo-file'.
6510 This becomes the latest existing todo file or, if there is none,
6511 the value of `todo-default-todo-file'.
6512 This function is added to `kill-buffer-hook' in Todo mode."
6513 (let ((filename (file-truename (buffer-file-name))))
6514 (setq todo-file-buffers (delete filename todo-file-buffers))
6515 (setq todo-global-current-todo-file
6516 (or (car todo-file-buffers)
6517 (todo-absolute-file-name todo-default-todo-file)))))
6519 (defun todo-reset-and-enable-done-separator ()
6520 "Show resized done items separator overlay after window change.
6521 Added to `window-configuration-change-hook' in Todo mode."
6522 (when (= 1 (length todo-done-separator-string))
6523 (let ((sep todo-done-separator))
6524 (setq todo-done-separator (todo-done-separator))
6525 (save-match-data (todo-reset-done-separator sep)))))
6527 (defun todo-modes-set-1 ()
6528 "Make some settings that apply to multiple Todo modes."
6529 (setq-local font-lock-defaults '(todo-font-lock-keywords t))
6530 (setq-local tab-width todo-indent-to-here)
6531 (setq-local indent-line-function 'todo-indent)
6532 (when todo-wrap-lines
6534 (setq wrap-prefix (make-string todo-indent-to-here 32))))
6536 (defun todo-modes-set-2 ()
6537 "Make some settings that apply to multiple Todo modes."
6538 (add-to-invisibility-spec 'todo)
6539 (setq buffer-read-only t)
6540 (when (and (boundp 'desktop-save-mode) desktop-save-mode)
6541 (setq-local desktop-save-buffer 'todo-desktop-save-buffer))
6542 (when (boundp 'hl-line-range-function)
6543 (setq-local hl-line-range-function
6544 (lambda() (save-excursion
6545 (when (todo-item-end)
6546 (cons (todo-item-start)
6547 (todo-item-end))))))))
6549 (defun todo-modes-set-3 ()
6550 "Make some settings that apply to multiple Todo modes."
6551 (setq-local todo-categories (todo-set-categories))
6552 (setq-local todo-category-number 1)
6553 ;; (add-hook 'find-file-hook 'todo-display-as-todo-file nil t)
6556 (put 'todo-mode 'mode-class 'special)
6559 (define-derived-mode todo-mode special-mode "Todo"
6560 "Major mode for displaying, navigating and editing todo lists.
6563 ;; (easy-menu-add todo-menu)
6567 ;; Initialize todo-current-todo-file.
6568 (when (member (file-truename (buffer-file-name))
6569 (funcall todo-files-function))
6570 (setq-local todo-current-todo-file (file-truename (buffer-file-name))))
6571 (setq-local todo-show-done-only nil)
6572 (setq-local todo-categories-with-marks nil)
6573 ;; (add-hook 'find-file-hook 'todo-add-to-buffer-list nil t)
6574 (add-hook 'post-command-hook 'todo-update-buffer-list nil t)
6575 (when todo-show-current-file
6576 (add-hook 'pre-command-hook 'todo-show-current-file nil t))
6577 (add-hook 'window-configuration-change-hook
6578 'todo-reset-and-enable-done-separator nil t)
6579 (add-hook 'kill-buffer-hook 'todo-reset-global-current-todo-file nil t))
6581 (put 'todo-archive-mode 'mode-class 'special)
6583 ;; If todo-mode is parent, all todo-mode key bindings appear to be
6584 ;; available in todo-archive-mode (e.g. shown by C-h m).
6586 (define-derived-mode todo-archive-mode special-mode "Todo-Arch"
6587 "Major mode for archived todo categories.
6589 \\{todo-archive-mode-map}"
6593 (setq-local todo-current-todo-file (file-truename (buffer-file-name)))
6594 (setq-local todo-show-done-only t))
6596 (defun todo-mode-external-set ()
6597 "Set `todo-categories' externally to `todo-current-todo-file'."
6598 (setq-local todo-current-todo-file todo-global-current-todo-file)
6599 (let ((cats (with-current-buffer
6600 ;; Can't use find-buffer-visiting when
6601 ;; `todo-show-categories-table' is called on first
6602 ;; invocation of `todo-show', since there is then
6603 ;; no buffer visiting the current file.
6604 (find-file-noselect todo-current-todo-file 'nowarn)
6606 ;; In Todo Edit mode todo-categories is now nil
6607 ;; since it uses same buffer as Todo mode but
6608 ;; doesn't have the latter's local variables.
6610 (goto-char (point-min))
6611 (read (buffer-substring-no-properties
6612 (line-beginning-position)
6613 (line-end-position))))))))
6614 (setq-local todo-categories cats)))
6616 (define-derived-mode todo-edit-mode text-mode "Todo-Ed"
6617 "Major mode for editing multiline todo items.
6619 \\{todo-edit-mode-map}"
6621 (todo-mode-external-set)
6622 (setq buffer-read-only nil))
6624 (put 'todo-categories-mode 'mode-class 'special)
6626 (define-derived-mode todo-categories-mode special-mode "Todo-Cats"
6627 "Major mode for displaying and editing todo categories.
6629 \\{todo-categories-mode-map}"
6630 (todo-mode-external-set))
6632 (put 'todo-filtered-items-mode 'mode-class 'special)
6635 (define-derived-mode todo-filtered-items-mode special-mode "Todo-Fltr"
6636 "Mode for displaying and reprioritizing top priority Todo.
6638 \\{todo-filtered-items-mode-map}"
6642 ;; -----------------------------------------------------------------------------
6643 (provide 'todo-mode)
6645 ;;; todo-mode.el ends here