1 ;;; todo-mode.el --- facilities for making and maintaining todo lists
3 ;; Copyright (C) 1997, 1999, 2001-2015 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 and maintaining
28 ;; prioritized lists of things to do. These todo lists are identified
29 ;; with named categories, so you can group together thematically
30 ;; related todo items. Each category is stored in a file, providing a
31 ;; further level of organization. You can create as many todo files,
32 ;; and in each as many categories, as you want.
34 ;; With Todo mode you can navigate among the items of a category, and
35 ;; between categories in the same and in different todo files. You
36 ;; can add and edit todo items, reprioritize them, move them to
37 ;; another category, or delete them. You can also mark items as done
38 ;; and store them within their category or in separate archive files.
39 ;; You can include todo items in the Emacs Fancy Diary display and
40 ;; treat them as appointments. You can add new todo files, and rename
41 ;; or delete them. You can add new categories to a file, rename or
42 ;; delete them, move a category to another file and merge the items of
43 ;; two categories. You can also reorder the sequence of categories in
44 ;; a todo file for the purpose of navigation. You can display
45 ;; sortable summary tables of the categories in a file and the types
46 ;; of items they contain. And you can filter items by various
47 ;; criteria from multiple categories in one or more todo files to
48 ;; create prioritizable cross-category overviews of your todo items.
50 ;; To get started, type `M-x todo-show'. For full details of the user
51 ;; interface, commands and options, consult the Todo mode user manual,
52 ;; which is included in the Info documentation.
57 (require 'cl-lib) ; For cl-oddp and cl-assert.
59 ;; -----------------------------------------------------------------------------
60 ;;; Setting up todo files, categories, and items
61 ;; -----------------------------------------------------------------------------
63 (defcustom todo-directory (locate-user-emacs-file "todo/")
64 "Directory where user's todo files are saved."
68 (defun todo-files (&optional archives)
69 "Default value of `todo-files-function'.
70 This returns the case-insensitive alphabetically sorted list of
71 file truenames in `todo-directory' with the extension
72 \".todo\". With non-nil ARCHIVES return the list of archive file
73 truenames (those with the extension \".toda\")."
74 (let ((files (if (file-exists-p todo-directory)
75 (mapcar 'file-truename
76 (directory-files todo-directory t
77 (if archives "\\.toda$" "\\.todo$") t)))))
78 (sort files (lambda (s1 s2) (let ((cis1 (upcase s1))
80 (string< cis1 cis2))))))
82 (defcustom todo-files-function 'todo-files
83 "Function returning the value of the variable `todo-files'.
84 This function should take an optional argument that, if non-nil,
85 makes it return the value of the variable `todo-archives'."
89 (defvar todo-files (funcall todo-files-function)
90 "List of truenames of user's todo files.")
92 (defvar todo-archives (funcall todo-files-function t)
93 "List of truenames of user's todo archives.")
95 (defvar todo-visited nil
96 "List of todo files visited in this session by `todo-show'.
97 Used to determine initial display according to the value of
100 (defvar todo-file-buffers nil
101 "List of file names of live Todo mode buffers.")
103 (defvar todo-global-current-todo-file nil
104 "Variable holding name of current todo file.
105 Used by functions called from outside of Todo mode to visit the
106 current todo file rather than the default todo file (i.e. when
107 users option `todo-show-current-file' is non-nil).")
109 (defvar todo-current-todo-file nil
110 "Variable holding the name of the currently active todo file.")
112 (defvar todo-categories nil
113 "Alist of categories in the current todo file.
114 The elements are cons cells whose car is a category name and
115 whose cdr is a vector of the category's item counts. These are,
116 in order, the numbers of todo items, of todo items included in
117 the Diary, of done items and of archived items.")
119 (defvar todo-category-number 1
120 "Variable holding the number of the current todo category.
121 Todo categories are numbered starting from 1.")
123 (defvar todo-categories-with-marks nil
124 "Alist of categories and number of marked items they contain.")
126 (defconst todo-category-beg "--==-- "
127 "String marking beginning of category (inserted with its name).")
129 (defconst todo-category-done "==--== DONE "
130 "String marking beginning of category's done items.")
132 (defcustom todo-done-separator-string "="
133 "String determining the value of variable `todo-done-separator'.
134 If the string consists of a single character,
135 `todo-done-separator' will be the string made by repeating this
136 character for the width of the window, and the length is
137 automatically recalculated when the window width changes. If the
138 string consists of more (or less) than one character, it will be
139 the value of `todo-done-separator'."
141 :initialize 'custom-initialize-default
142 :set 'todo-reset-done-separator-string
143 :group 'todo-display)
145 (defun todo-done-separator ()
146 "Return string used as value of variable `todo-done-separator'."
147 (let ((sep todo-done-separator-string))
148 (propertize (if (= 1 (length sep))
149 (make-string (window-width) (string-to-char sep))
150 todo-done-separator-string)
151 'face 'todo-done-sep)))
153 (defvar todo-done-separator (todo-done-separator)
154 "String used to visually separate done from not done items.
155 Displayed as an overlay instead of `todo-category-done' when
156 done items are shown. Its value is determined by user option
157 `todo-done-separator-string'.")
159 (defvar todo-show-done-only nil
160 "If non-nil display only done items in current category.
161 Set by the command `todo-toggle-view-done-only' and used by
162 `todo-category-select'.")
164 (defcustom todo-nondiary-marker '("[" "]")
165 "List of strings surrounding item date to block diary inclusion.
166 The first string is inserted before the item date and must be a
167 non-empty string that does not match a diary date in order to
168 have its intended effect. The second string is inserted after
170 :type '(list string string)
172 :initialize 'custom-initialize-default
173 :set 'todo-reset-nondiary-marker)
175 (defconst todo-nondiary-start (nth 0 todo-nondiary-marker)
176 "String inserted before item date to block diary inclusion.")
178 (defconst todo-nondiary-end (nth 1 todo-nondiary-marker)
179 "String inserted after item date matching `todo-nondiary-start'.")
181 (defconst todo-month-name-array
182 (vconcat calendar-month-name-array (vector "*"))
183 "Array of month names, in order.
184 The final element is \"*\", indicating an unspecified month.")
186 (defconst todo-month-abbrev-array
187 (vconcat calendar-month-abbrev-array (vector "*"))
188 "Array of abbreviated month names, in order.
189 The final element is \"*\", indicating an unspecified month.")
191 (defconst todo-date-pattern
192 (let ((dayname (diary-name-pattern calendar-day-name-array nil t)))
193 (concat "\\(?4:\\(?5:" dayname "\\)\\|"
195 (monthname (format "\\(?6:%s\\)" (diary-name-pattern
196 todo-month-name-array
197 todo-month-abbrev-array)))
198 (month "\\(?7:[0-9]+\\|\\*\\)")
199 (day "\\(?8:[0-9]+\\|\\*\\)")
200 (year "-?\\(?9:[0-9]+\\|\\*\\)"))
201 (mapconcat 'eval calendar-date-display-form ""))
203 "Regular expression matching a todo item date header.")
205 ;; By itself this matches anything, because of the `?'; however, it's only
206 ;; used in the context of `todo-date-pattern' (but Emacs Lisp lacks
208 (defconst todo-date-string-start
209 (concat "^\\(" (regexp-quote todo-nondiary-start) "\\|"
210 (regexp-quote diary-nonmarking-symbol) "\\)?")
211 "Regular expression matching part of item header before the date.")
213 (defcustom todo-done-string "DONE "
214 "Identifying string appended to the front of done todo items."
216 :initialize 'custom-initialize-default
217 :set 'todo-reset-done-string
220 (defconst todo-done-string-start
221 (concat "^\\[" (regexp-quote todo-done-string))
222 "Regular expression matching start of done item.")
224 (defconst todo-item-start (concat "\\(" todo-date-string-start "\\|"
225 todo-done-string-start "\\)"
227 "String identifying start of a todo item.")
229 ;; -----------------------------------------------------------------------------
230 ;;; Todo mode display options
231 ;; -----------------------------------------------------------------------------
233 (defcustom todo-prefix ""
234 "String prefixed to todo items for visual distinction."
235 :type '(string :validate
237 (when (string= (widget-value widget) todo-item-mark)
241 "Invalid value: must be distinct from `todo-item-mark'"))
243 :initialize 'custom-initialize-default
244 :set 'todo-reset-prefix
245 :group 'todo-display)
247 (defcustom todo-number-prefix t
248 "Non-nil to prefix items with consecutively increasing integers.
249 These reflect the priorities of the items in each category."
251 :initialize 'custom-initialize-default
252 :set 'todo-reset-prefix
253 :group 'todo-display)
255 (defun todo-mode-line-control (cat)
256 "Return a mode line control for todo or archive file buffers.
257 Argument CAT is the name of the current todo category.
258 This function is the value of the user variable
259 `todo-mode-line-function'."
260 (let ((file (todo-short-file-name todo-current-todo-file)))
261 (format "%s category %d: %s" file todo-category-number cat)))
263 (defcustom todo-mode-line-function 'todo-mode-line-control
264 "Function that returns a mode line control for Todo mode buffers.
265 The function expects one argument holding the name of the current
266 todo category. The resulting control becomes the local value of
267 `mode-line-buffer-identification' in each Todo mode buffer."
269 :group 'todo-display)
271 (defcustom todo-highlight-item nil
272 "Non-nil means highlight items at point."
274 :initialize 'custom-initialize-default
275 :set 'todo-reset-highlight-item
276 :group 'todo-display)
278 (defcustom todo-wrap-lines t
279 "Non-nil to activate Visual Line mode and use wrap prefix."
281 :group 'todo-display)
283 (defcustom todo-indent-to-here 3
284 "Number of spaces to indent continuation lines of items.
285 This must be a positive number to ensure such items are fully
286 shown in the Fancy Diary display."
287 :type '(integer :validate
289 (unless (> (widget-value widget) 0)
290 (widget-put widget :error
291 "Invalid value: must be a positive integer")
293 :group 'todo-display)
295 (defun todo-indent ()
296 "Indent from point to `todo-indent-to-here'."
297 (indent-to todo-indent-to-here todo-indent-to-here))
299 (defcustom todo-show-with-done nil
300 "Non-nil to display done items in all categories."
302 :group 'todo-display)
304 ;; -----------------------------------------------------------------------------
306 ;; -----------------------------------------------------------------------------
308 (defface todo-key-prompt
309 '((t (:weight bold)))
310 "Face for making keys in item insertion prompt stand out."
314 ;; '((t :inherit font-lock-warning-face))
318 (:weight bold :foreground "Red1"))
322 (:weight bold :foreground "Pink"))
326 (:weight bold :foreground "Red1"))
330 (:weight bold :foreground "Pink"))
335 (:weight bold :inverse-video t)))
336 "Face for marks on marked items."
339 (defface todo-prefix-string
340 ;; '((t :inherit font-lock-constant-face))
341 '((((class grayscale) (background light))
342 (:foreground "LightGray" :weight bold :underline t))
343 (((class grayscale) (background dark))
344 (:foreground "Gray50" :weight bold :underline t))
345 (((class color) (min-colors 88) (background light)) (:foreground "dark cyan"))
346 (((class color) (min-colors 88) (background dark)) (:foreground "Aquamarine"))
347 (((class color) (min-colors 16) (background light)) (:foreground "CadetBlue"))
348 (((class color) (min-colors 16) (background dark)) (:foreground "Aquamarine"))
349 (((class color) (min-colors 8)) (:foreground "magenta"))
350 (t (:weight bold :underline t)))
351 "Face for todo item prefix or numerical priority string."
354 (defface todo-top-priority
355 ;; bold font-lock-comment-face
356 '((default :weight bold)
357 (((class grayscale) (background light)) :foreground "DimGray" :slant italic)
358 (((class grayscale) (background dark)) :foreground "LightGray" :slant italic)
359 (((class color) (min-colors 88) (background light)) :foreground "Firebrick")
360 (((class color) (min-colors 88) (background dark)) :foreground "chocolate1")
361 (((class color) (min-colors 16) (background light)) :foreground "red")
362 (((class color) (min-colors 16) (background dark)) :foreground "red1")
363 (((class color) (min-colors 8) (background light)) :foreground "red")
364 (((class color) (min-colors 8) (background dark)) :foreground "yellow")
366 "Face for top priority todo item numerical priority string.
367 The item's priority number string has this face if the number is
368 less than or equal the category's top priority setting."
371 (defface todo-nondiary
372 ;; '((t :inherit font-lock-type-face))
373 '((((class grayscale) (background light)) :foreground "Gray90" :weight bold)
374 (((class grayscale) (background dark)) :foreground "DimGray" :weight bold)
375 (((class color) (min-colors 88) (background light)) :foreground "ForestGreen")
376 (((class color) (min-colors 88) (background dark)) :foreground "PaleGreen")
377 (((class color) (min-colors 16) (background light)) :foreground "ForestGreen")
378 (((class color) (min-colors 16) (background dark)) :foreground "PaleGreen")
379 (((class color) (min-colors 8)) :foreground "green")
380 (t :weight bold :underline t))
381 "Face for non-diary markers around todo item date/time header."
385 '((t :inherit diary))
386 "Face for the date string of a todo item."
390 '((t :inherit diary-time))
391 "Face for the time string of a todo item."
394 (defface todo-diary-expired
395 ;; Doesn't contrast enough with todo-date (= diary) face.
396 ;; ;; '((t :inherit warning))
397 ;; '((default :weight bold)
398 ;; (((class color) (min-colors 16)) :foreground "DarkOrange")
399 ;; (((class color)) :foreground "yellow"))
400 ;; bold font-lock-function-name-face
401 '((default :weight bold)
402 (((class color) (min-colors 88) (background light)) :foreground "Blue1")
403 (((class color) (min-colors 88) (background dark)) :foreground "LightSkyBlue")
404 (((class color) (min-colors 16) (background light)) :foreground "Blue")
405 (((class color) (min-colors 16) (background dark)) :foreground "LightSkyBlue")
406 (((class color) (min-colors 8)) :foreground "blue")
407 (t :inverse-video t))
408 "Face for expired dates of diary items."
411 (defface todo-done-sep
412 ;; '((t :inherit font-lock-builtin-face))
413 '((((class grayscale) (background light)) :foreground "LightGray" :weight bold)
414 (((class grayscale) (background dark)) :foreground "DimGray" :weight bold)
415 (((class color) (min-colors 88) (background light)) :foreground "dark slate blue")
416 (((class color) (min-colors 88) (background dark)) :foreground "LightSteelBlue")
417 (((class color) (min-colors 16) (background light)) :foreground "Orchid")
418 (((class color) (min-colors 16) (background dark)) :foreground "LightSteelBlue")
419 (((class color) (min-colors 8)) :foreground "blue" :weight bold)
421 "Face for separator string between done and not done todo items."
425 ;; '((t :inherit font-lock-keyword-face))
426 '((((class grayscale) (background light)) :foreground "LightGray" :weight bold)
427 (((class grayscale) (background dark)) :foreground "DimGray" :weight bold)
428 (((class color) (min-colors 88) (background light)) :foreground "Purple")
429 (((class color) (min-colors 88) (background dark)) :foreground "Cyan1")
430 (((class color) (min-colors 16) (background light)) :foreground "Purple")
431 (((class color) (min-colors 16) (background dark)) :foreground "Cyan")
432 (((class color) (min-colors 8)) :foreground "cyan" :weight bold)
434 "Face for done todo item header string."
437 (defface todo-comment
438 ;; '((t :inherit font-lock-comment-face))
439 '((((class grayscale) (background light))
440 :foreground "DimGray" :weight bold :slant italic)
441 (((class grayscale) (background dark))
442 :foreground "LightGray" :weight bold :slant italic)
443 (((class color) (min-colors 88) (background light))
444 :foreground "Firebrick")
445 (((class color) (min-colors 88) (background dark))
446 :foreground "chocolate1")
447 (((class color) (min-colors 16) (background light))
449 (((class color) (min-colors 16) (background dark))
451 (((class color) (min-colors 8) (background light))
453 (((class color) (min-colors 8) (background dark))
454 :foreground "yellow")
455 (t :weight bold :slant italic))
456 "Face for comments appended to done todo items."
460 ;; '((t :inherit match))
464 (:background "yellow1"))
468 (:background "RoyalBlue3"))
472 (:foreground "black" :background "yellow"))
476 (:foreground "white" :background "blue"))
481 (:background "gray")))
482 "Face for matches found by `todo-search'."
486 ;; '((t :inherit widget-field))
488 (:foreground "black" :background "yellow3"))
489 (((class grayscale color)
491 (:background "gray85"))
492 (((class grayscale color)
494 (:background "dim gray"))
497 "Face for buttons in table of categories."
500 (defface todo-sorted-column
505 (:background "grey85"))
508 (:background "grey85" :foreground "grey10"))
510 (:background "gray")))
511 "Face for sorted column in table of categories."
514 (defface todo-archived-only
515 ;; '((t (:inherit (shadow))))
518 (:foreground "grey50"))
521 (:foreground "grey70"))
523 (:foreground "gray")))
524 "Face for archived-only category names in table of categories."
527 (defface todo-category-string
528 ;; '((t :inherit font-lock-type-face))
529 '((((class grayscale) (background light)) :foreground "Gray90" :weight bold)
530 (((class grayscale) (background dark)) :foreground "DimGray" :weight bold)
531 (((class color) (min-colors 88) (background light)) :foreground "ForestGreen")
532 (((class color) (min-colors 88) (background dark)) :foreground "PaleGreen")
533 (((class color) (min-colors 16) (background light)) :foreground "ForestGreen")
534 (((class color) (min-colors 16) (background dark)) :foreground "PaleGreen")
535 (((class color) (min-colors 8)) :foreground "green")
536 (t :weight bold :underline t))
537 "Face for category-file header in Todo Filtered Items mode."
540 ;; -----------------------------------------------------------------------------
541 ;;; Entering and exiting
542 ;; -----------------------------------------------------------------------------
544 ;; (defcustom todo-visit-files-commands (list 'find-file 'dired-find-file)
545 ;; "List of file finding commands for `todo-display-as-todo-file'.
546 ;; Invoking these commands to visit a todo file or todo archive file
547 ;; calls `todo-show' or `todo-find-archive', so that the file is
548 ;; displayed correctly."
549 ;; :type '(repeat function)
552 (defun todo-short-file-name (file)
553 "Return the short form of todo file FILE's name.
554 This lacks the extension and directory components."
556 (file-name-sans-extension (file-name-nondirectory file))))
558 (defcustom todo-default-todo-file (todo-short-file-name
559 (car (funcall todo-files-function)))
560 "Todo file visited by first session invocation of `todo-show'."
561 :type (when todo-files
562 `(radio ,@(mapcar (lambda (f) (list 'const f))
563 (mapcar 'todo-short-file-name
564 (funcall todo-files-function)))))
567 (defcustom todo-show-current-file t
568 "Non-nil to make `todo-show' visit the current todo file.
569 Otherwise, `todo-show' always visits `todo-default-todo-file'."
571 :initialize 'custom-initialize-default
572 :set 'todo-set-show-current-file
575 (defcustom todo-show-first 'first
576 "What action to take on first use of `todo-show' on a file."
577 :type '(choice (const :tag "Show first category" first)
578 (const :tag "Show table of categories" table)
579 (const :tag "Show top priorities" top)
580 (const :tag "Show diary items" diary)
581 (const :tag "Show regexp items" regexp))
584 (defcustom todo-add-item-if-new-category t
585 "Non-nil to prompt for an item after adding a new category."
589 (defcustom todo-initial-file "Todo"
590 "Default file name offered on adding first todo file."
594 (defcustom todo-initial-category "Todo"
595 "Default category name offered on initializing a new todo file."
599 (defcustom todo-category-completions-files nil
600 "List of files for building `todo-read-category' completions."
601 :type `(set ,@(mapcar (lambda (f) (list 'const f))
602 (mapcar 'todo-short-file-name
603 (funcall todo-files-function))))
606 (defcustom todo-completion-ignore-case nil
607 "Non-nil means case is ignored by `todo-read-*' functions."
612 (defun todo-show (&optional solicit-file interactive)
613 "Visit a todo file and display one of its categories.
615 When invoked in Todo mode, prompt for which todo file to visit.
616 When invoked outside of Todo mode with non-nil prefix argument
617 SOLICIT-FILE prompt for which todo file to visit; otherwise visit
618 `todo-default-todo-file'. Subsequent invocations from outside
619 of Todo mode revisit this file or, with option
620 `todo-show-current-file' non-nil (the default), whichever todo
621 file was last visited.
623 If you call this command before you have created any todo file in
624 the current format, and you have an todo file in old format, it
625 will ask you whether to convert that file and show it.
626 Otherwise, calling this command before any todo file exists
627 prompts for a file name and an initial category (defaulting to
628 `todo-initial-file' and `todo-initial-category'), creates both of
629 these, visits the file and displays the category, and if option
630 `todo-add-item-if-new-category' is non-nil (the default), prompts
633 The first invocation of this command on an existing todo file
634 interacts with the option `todo-show-first': if its value is
635 `first' (the default), show the first category in the file; if
636 its value is `table', show the table of categories in the file;
637 if its value is one of `top', `diary' or `regexp', show the
638 corresponding saved top priorities, diary items, or regexp items
639 file, if any. Subsequent invocations always show the file's
640 current (i.e., last displayed) category.
642 In Todo mode just the category's unfinished todo items are shown
643 by default. The done items are hidden, but typing
644 `\\[todo-toggle-view-done-items]' displays them below the todo
645 items. With non-nil user option `todo-show-with-done' both todo
646 and done items are always shown on visiting a category.
648 Invoking this command in Todo Archive mode visits the
649 corresponding todo file, displaying the corresponding category."
651 (when todo-default-todo-file
652 (todo-check-file (todo-absolute-file-name todo-default-todo-file)))
654 ;; Before initializing the first todo first, check if there is a
655 ;; legacy todo file and if so, offer to convert to the current
656 ;; format and make it the first new todo file.
657 (unless todo-default-todo-file
658 (let ((legacy-todo-file (if (boundp 'todo-file-do)
660 (locate-user-emacs-file "todo-do" ".todo-do"))))
661 (when (and (file-exists-p legacy-todo-file)
662 (y-or-n-p (concat "Do you want to convert a copy of your "
663 "old todo file to the new format? ")))
664 (when (todo-convert-legacy-files)
665 (throw 'shown nil)))))
668 (show-first todo-show-first)
669 (file (cond ((or solicit-file
671 (memq major-mode '(todo-mode
673 todo-filtered-items-mode))))
674 (if (funcall todo-files-function)
675 (todo-read-file-name "Choose a todo file to visit: "
677 (user-error "There are no todo files")))
678 ((and (eq major-mode 'todo-archive-mode)
679 ;; Called noninteractively via todo-quit
680 ;; to jump to corresponding category in
683 (setq cat (todo-current-category))
684 (concat (file-name-sans-extension
685 todo-current-todo-file) ".todo"))
687 (or todo-current-todo-file
688 (and todo-show-current-file
689 todo-global-current-todo-file)
690 (todo-absolute-file-name todo-default-todo-file)
693 (unless todo-default-todo-file
694 ;; We just initialized the first todo file, so make it the default.
695 (setq todo-default-todo-file (todo-short-file-name file)
697 (todo-reevaluate-default-file-defcustom))
698 (unless (member file todo-visited)
699 ;; Can't setq t-c-t-f here, otherwise wrong file shown when
700 ;; todo-show is called from todo-show-categories-table.
701 (let ((todo-current-todo-file file))
702 (cond ((eq todo-show-first 'table)
703 (todo-show-categories-table))
704 ((memq todo-show-first '(top diary regexp))
705 (let* ((shortf (todo-short-file-name file))
706 (fi-file (todo-absolute-file-name
707 shortf todo-show-first)))
708 (when (eq todo-show-first 'regexp)
709 (let ((rxfiles (directory-files todo-directory t
711 (when (and rxfiles (> (length rxfiles) 1))
712 (let ((rxf (mapcar 'todo-short-file-name rxfiles)))
713 (setq fi-file (todo-absolute-file-name
715 "Choose a regexp items file: "
717 (if (file-exists-p fi-file)
721 (set-buffer (find-file-noselect fi-file 'nowarn)))
722 (unless (derived-mode-p 'todo-filtered-items-mode)
723 (todo-filtered-items-mode)))
724 (message "There is no %s file for %s"
725 (cond ((eq todo-show-first 'top)
727 ((eq todo-show-first 'diary)
729 ((eq todo-show-first 'regexp)
732 (setq todo-show-first 'first)))))))
733 (when (or (member file todo-visited)
734 (eq todo-show-first 'first))
735 (unless (todo-check-file file) (throw 'end nil))
736 ;; If todo-show is called from the minibuffer, don't visit
737 ;; the todo file there.
738 (set-window-buffer (if (minibufferp) (minibuffer-selected-window)
740 (set-buffer (find-file-noselect file 'nowarn)))
741 (if (equal (file-name-extension (buffer-file-name)) "toda")
742 (unless (derived-mode-p 'todo-archive-mode) (todo-archive-mode))
743 (unless (derived-mode-p 'todo-mode) (todo-mode)))
744 ;; When quitting an archive file, show the corresponding
745 ;; category in the corresponding todo file, if it exists.
746 (when (assoc cat todo-categories)
747 (setq todo-category-number (todo-category-number cat)))
748 ;; If this is a new todo file, add its first category.
749 (when (zerop (buffer-size))
750 ;; Don't confuse an erased buffer with a fresh buffer for
751 ;; adding a new todo file -- it might have been erased by
752 ;; mistake or due to a bug (e.g. Bug#20832).
753 (when (buffer-modified-p)
754 (error "Buffer is empty but modified, please report a bug"))
757 (setq todo-category-number
758 (todo-add-category todo-current-todo-file "")
759 add-item todo-add-item-if-new-category
762 ;; If the category was added, save the file now, so we
763 ;; don't risk having an empty todo file, which would
764 ;; signal an error if we tried to visit it later,
765 ;; since doing that looks for category boundaries.
767 ;; If user cancels before adding the category, clean up
768 ;; and exit, so we have a fresh slate the next time.
770 ;; (setq todo-files (funcall todo-files-function))
771 (setq todo-files (delete file todo-files))
773 (setq todo-default-todo-file nil
774 todo-current-todo-file nil)
775 (todo-reevaluate-default-file-defcustom))
778 (save-excursion (todo-category-select))
779 (when add-item (todo-insert-item--basic)))
780 (setq todo-show-first show-first)
781 (add-to-list 'todo-visited file)))))
784 "Save the current todo file."
786 (cond ((eq major-mode 'todo-filtered-items-mode)
787 (todo-check-filtered-items-file)
788 (todo-save-filtered-items-buffer))
792 (defvar todo-descending-counts)
795 "Exit the current Todo-related buffer.
796 Depending on the specific mode, this either kills the buffer or
797 buries it and restores state as needed."
799 (let ((buf (current-buffer)))
800 (cond ((eq major-mode 'todo-categories-mode)
801 ;; Postpone killing buffer till after calling todo-show, to
802 ;; prevent killing todo-mode buffer.
803 (setq todo-descending-counts nil)
804 ;; Ensure todo-show calls todo-show-categories-table only on
805 ;; first invocation per file.
806 (when (eq todo-show-first 'table)
807 (add-to-list 'todo-visited todo-current-todo-file))
810 ((eq major-mode 'todo-filtered-items-mode)
812 (unless (eq major-mode 'todo-mode) (todo-show)))
813 ((eq major-mode 'todo-archive-mode)
814 ;; Have to write a newly created archive to file to avoid
815 ;; subsequent errors.
817 (let ((todo-file (concat todo-directory
818 (todo-short-file-name todo-current-todo-file)
820 (if (todo-check-file todo-file)
822 (message "There is no todo file for this archive")))
823 ;; When todo-check-file runs in todo-show, it kills the
824 ;; buffer if the archive file was deleted externally.
825 (when (buffer-live-p buf) (bury-buffer buf)))
826 ((eq major-mode 'todo-mode)
828 ;; If we just quit archive mode, just burying the buffer
829 ;; in todo-mode would return to archive.
830 (set-window-buffer (selected-window)
831 (set-buffer (other-buffer)))
832 (bury-buffer buf)))))
834 ;; -----------------------------------------------------------------------------
835 ;;; Navigation between and within categories
836 ;; -----------------------------------------------------------------------------
838 (defcustom todo-skip-archived-categories nil
839 "Non-nil to handle categories with only archived items specially.
841 Sequential category navigation using \\[todo-forward-category]
842 or \\[todo-backward-category] skips categories that contain only
843 archived items. Other commands still recognize these categories.
844 In Todo Categories mode (\\[todo-show-categories-table]) these
845 categories shown in `todo-archived-only' face and pressing the
846 category button visits the category in the archive instead of the
849 :group 'todo-display)
851 (defun todo-forward-category (&optional back)
852 "Visit the numerically next category in this todo file.
853 If the current category is the highest numbered, visit the first
854 category. With non-nil argument BACK, visit the numerically
855 previous category (the highest numbered one, if the current
856 category is the first)."
858 (setq todo-category-number
859 (1+ (mod (- todo-category-number (if back 2 0))
860 (length todo-categories))))
861 (when todo-skip-archived-categories
862 (while (and (zerop (todo-get-count 'todo))
863 (zerop (todo-get-count 'done))
864 (not (zerop (todo-get-count 'archived))))
865 (setq todo-category-number
866 (apply (if back '1- '1+) (list todo-category-number)))))
867 (todo-category-select)
868 (goto-char (point-min)))
870 (defun todo-backward-category ()
871 "Visit the numerically previous category in this todo file.
872 If the current category is the highest numbered, visit the first
875 (todo-forward-category t))
877 (defvar todo-categories-buffer)
879 (defun todo-jump-to-category (&optional file where)
880 "Prompt for a category in a todo file and jump to it.
882 With non-nil FILE (interactively a prefix argument), prompt for a
883 specific todo file and choose (with TAB completion) a category
884 in it to jump to; otherwise, choose and jump to any category in
885 either the current todo file or a file in
886 `todo-category-completions-files'.
888 Also accept a non-existing category name and ask whether to add a
889 new category by that name; on confirmation, add it and jump to
890 that category, and if option `todo-add-item-if-new-category' is
891 non-nil (the default), then prompt for the first item.
893 In noninteractive calls non-nil WHERE specifies either the goal
894 category or its file. If its value is `archive', the choice of
895 categories is restricted to the current archive file or the
896 archive you were prompted to choose; this is used by
897 `todo-jump-to-archive-category'. If its value is the name of a
898 category, jump directly to that category; this is used in Todo
901 ;; If invoked outside of Todo mode and there is not yet any Todo
902 ;; file, initialize one.
903 (if (null (funcall todo-files-function))
905 (let* ((archive (eq where 'archive))
906 (cat (unless archive where))
907 (file0 (when cat ; We're in Todo Categories mode.
908 ;; With non-nil `todo-skip-archived-categories'
909 ;; jump to archive file of a category with only
911 (if (and todo-skip-archived-categories
912 (zerop (todo-get-count 'todo cat))
913 (zerop (todo-get-count 'done cat))
914 (not (zerop (todo-get-count 'archived cat))))
915 (concat (file-name-sans-extension
916 todo-current-todo-file) ".toda")
917 ;; Otherwise, jump to current todo file.
918 todo-current-todo-file)))
919 (len (length todo-categories))
920 (cat+file (unless cat
921 (todo-read-category "Jump to category: "
922 (if archive 'archive) file)))
923 (add-item (and todo-add-item-if-new-category
924 (> (length todo-categories) len)))
925 (category (or cat (car cat+file))))
926 (unless cat (setq file0 (cdr cat+file)))
927 (with-current-buffer (find-file-noselect file0 'nowarn)
928 (setq todo-current-todo-file file0)
929 ;; If called from Todo Categories mode, clean up before jumping.
930 (if (string= (buffer-name) todo-categories-buffer)
932 (set-window-buffer (selected-window)
933 (set-buffer (find-buffer-visiting file0)))
934 (unless todo-global-current-todo-file
935 (setq todo-global-current-todo-file todo-current-todo-file))
936 (todo-category-number category)
937 (todo-category-select)
938 (goto-char (point-min))
939 (when add-item (todo-insert-item--basic))))))
941 (defun todo-next-item (&optional count)
942 "Move point down to the beginning of the next item.
943 With positive numerical prefix COUNT, move point COUNT items
946 If the category's done items are hidden, this command also moves
947 point to the empty line below the last todo item from any higher
948 item in the category, i.e., when invoked with or without a prefix
949 argument. If the category's done items are visible, this command
950 called with a prefix argument only moves point to a lower item,
951 e.g., with point on the last todo item and called with prefix 1,
952 it moves point to the first done item; but if called with point
953 on the last todo item without a prefix argument, it moves point
954 the the empty line above the done items separator."
956 ;; It's not worth the trouble to allow prefix arg value < 1, since
957 ;; we have the corresponding command.
958 (cond ((and current-prefix-arg (< count 1))
959 (user-error "The prefix argument must be a positive number"))
961 (todo-forward-item count))
963 (todo-forward-item))))
965 (defun todo-previous-item (&optional count)
966 "Move point up to start of item with next higher priority.
967 With positive numerical prefix COUNT, move point COUNT items
970 If the category's done items are visible, this command called
971 with a prefix argument only moves point to a higher item, e.g.,
972 with point on the first done item and called with prefix 1, it
973 moves to the last todo item; but if called with point on the
974 first done item without a prefix argument, it moves point the the
975 empty line above the done items separator."
977 ;; Avoid moving to bob if on the first item but not at bob.
978 (when (> (line-number-at-pos) 1)
979 ;; It's not worth the trouble to allow prefix arg value < 1, since
980 ;; we have the corresponding command.
981 (cond ((and current-prefix-arg (< count 1))
982 (user-error "The prefix argument must be a positive number"))
984 (todo-backward-item count))
986 (todo-backward-item)))))
988 ;; -----------------------------------------------------------------------------
989 ;;; Display toggle commands
990 ;; -----------------------------------------------------------------------------
992 (defun todo-toggle-prefix-numbers ()
993 "Hide item numbering if shown, show if hidden."
997 (goto-char (point-min))
998 (let* ((ov (todo-get-overlay 'prefix))
999 (show-done (re-search-forward todo-done-string-start nil t))
1000 (todo-show-with-done show-done)
1001 (todo-number-prefix (not (equal (overlay-get ov 'before-string)
1003 (if (eq major-mode 'todo-filtered-items-mode)
1004 (todo-prefix-overlays)
1005 (todo-category-select))))))
1007 (defun todo-toggle-view-done-items ()
1008 "Show hidden or hide visible done items in current category."
1010 (if (zerop (todo-get-count 'done (todo-current-category)))
1011 (message "There are no done items in this category.")
1012 (let ((opoint (point)))
1013 (goto-char (point-min))
1014 (let* ((shown (re-search-forward todo-done-string-start nil t))
1015 (todo-show-with-done (not shown)))
1016 (todo-category-select)
1018 ;; If start of done items sections is below the bottom of the
1019 ;; window, make it visible.
1022 (goto-char (point-min))
1023 (re-search-forward todo-done-string-start nil t)))
1024 (if (not (pos-visible-in-window-p shown))
1026 (goto-char opoint)))))))
1028 (defun todo-toggle-view-done-only ()
1029 "Switch between displaying only done or only todo items."
1031 (setq todo-show-done-only (not todo-show-done-only))
1032 (todo-category-select))
1034 (defun todo-toggle-item-highlighting ()
1035 "Highlight or unhighlight the todo item the cursor is on."
1037 (eval-and-compile (require 'hl-line))
1038 (when (memq major-mode
1039 '(todo-mode todo-archive-mode todo-filtered-items-mode))
1044 (defun todo-toggle-item-header ()
1045 "Hide or show item date-time headers in the current file.
1046 With done items, this hides only the done date-time string, not
1047 the the original date-time string."
1051 (goto-char (point-min))
1052 (let ((ov (todo-get-overlay 'header)))
1054 (remove-overlays 1 (1+ (buffer-size)) 'todo 'header)
1056 (goto-char (point-min))
1058 (when (re-search-forward
1059 (concat todo-item-start
1060 "\\( " diary-time-regexp "\\)?"
1061 (regexp-quote todo-nondiary-end) "? ")
1063 (setq ov (make-overlay (match-beginning 0) (match-end 0) nil t))
1064 (overlay-put ov 'todo 'header)
1065 (overlay-put ov 'display ""))
1066 (todo-forward-item)))))))
1068 ;; -----------------------------------------------------------------------------
1069 ;;; File and category editing
1070 ;; -----------------------------------------------------------------------------
1072 (defun todo-add-file ()
1073 "Name and initialize a new todo file.
1074 Interactively, prompt for a category and display it, and if
1075 option `todo-add-item-if-new-category' is non-nil (the default),
1076 prompt for the first item.
1077 Noninteractively, return the name of the new file."
1079 (let* ((prompt (concat "Enter name of new todo file "
1080 "(TAB or SPC to see current names): "))
1081 (file (todo-read-file-name prompt)))
1082 ;; Don't accept the name of an existing todo file.
1083 (setq file (todo-absolute-file-name
1084 (todo-validate-name (todo-short-file-name file) 'file)))
1085 (with-current-buffer (get-buffer-create file)
1087 (write-region (point-min) (point-max) file nil 'nomessage nil t)
1089 (setq todo-files (funcall todo-files-function))
1090 (todo-reevaluate-filelist-defcustoms)
1091 (if (called-interactively-p 'any)
1093 (set-window-buffer (selected-window)
1094 (set-buffer (find-file-noselect file)))
1095 (setq todo-current-todo-file file)
1099 (defun todo-rename-file (&optional arg)
1100 "Rename the current todo file.
1101 With prefix ARG, prompt for a todo file and rename it.
1102 If there are corresponding archive or filtered items files,
1103 rename these accordingly. If there are live buffers visiting
1104 these files, also rename them accordingly."
1106 (let* ((oname (or (and arg
1107 (todo-read-file-name "Choose a file to rename: "
1109 (buffer-file-name)))
1110 (soname (todo-short-file-name oname))
1111 (nname (todo-read-file-name "New name for this file: "))
1112 (snname (todo-short-file-name nname))
1113 (files (directory-files todo-directory t
1114 (concat ".*" (regexp-quote soname)
1115 ".*\\.tod[aorty]$") t)))
1117 (let* ((sfname (todo-short-file-name f))
1118 (fext (file-name-extension f t))
1119 (fbuf (find-buffer-visiting f))
1120 (fbname (buffer-name fbuf)))
1121 (when (string-match (regexp-quote soname) sfname)
1122 (let* ((snfname (replace-match snname t t sfname))
1123 (nfname (concat todo-directory snfname fext)))
1124 (rename-file f nfname)
1126 (with-current-buffer fbuf
1127 (set-visited-file-name nfname t t)
1128 (cond ((member fext '(".todo" ".toda"))
1129 (setq todo-current-todo-file (buffer-file-name))
1130 (setq mode-line-buffer-identification
1131 (funcall todo-mode-line-function
1132 (todo-current-category))))
1135 (replace-regexp-in-string
1136 (regexp-quote soname) snname fbname))))))))))
1137 (setq todo-files (funcall todo-files-function)
1138 todo-archives (funcall todo-files-function t))
1139 (when (string= todo-default-todo-file soname)
1140 (setq todo-default-todo-file snname))
1141 (when (string= todo-global-current-todo-file oname)
1142 (setq todo-global-current-todo-file nname))
1143 (todo-reevaluate-filelist-defcustoms)))
1145 (defun todo-delete-file ()
1146 "Delete the current todo, archive or filtered items file.
1147 If the todo file has a corresponding archive file, or vice versa,
1148 prompt whether to delete that as well. Also kill the buffers
1149 visiting the deleted files."
1151 (let* ((file1 (buffer-file-name))
1152 (todo (eq major-mode 'todo-mode))
1153 (archive (eq major-mode 'todo-archive-mode))
1154 (filtered (eq major-mode 'todo-filtered-items-mode))
1155 (file1-sn (todo-short-file-name file1))
1156 (file2 (concat todo-directory file1-sn (cond (todo ".toda")
1157 (archive ".todo"))))
1158 (buf1 (current-buffer))
1159 (buf2 (when file2 (find-buffer-visiting file2)))
1160 (prompt1 (concat "Delete " (cond (todo "todo")
1162 (filtered "filtered items"))
1164 (prompt2 (concat "Also delete the corresponding "
1165 (cond (todo "archive") (archive "todo")) " file "
1166 (when buf2 "and kill the buffer visiting it? ")))
1167 (delete1 (yes-or-no-p (format prompt1 file1-sn)))
1168 (delete2 (when (and delete1 (or (file-exists-p file2) buf2))
1169 (yes-or-no-p prompt2))))
1171 (when (file-exists-p file1) (delete-file file1))
1172 (setq todo-visited (delete file1 todo-visited))
1176 (when (file-exists-p file2) (delete-file file2))
1177 (setq todo-visited (delete file2 todo-visited))
1178 (and buf2 (kill-buffer buf2)))
1179 ;; If we deleted an archive but not its todo file, update the
1180 ;; latter's category sexp.
1181 (when (equal (file-name-extension file2) "todo")
1182 (with-current-buffer (or buf2 (find-file-noselect file2))
1186 (goto-char (point-min))
1187 (let ((sexp (read (buffer-substring-no-properties
1188 (line-beginning-position)
1189 (line-end-position))))
1190 (buffer-read-only nil))
1191 (mapc (lambda (x) (aset (cdr x) 3 0)) sexp)
1192 (delete-region (line-beginning-position) (line-end-position))
1193 (prin1 sexp (current-buffer)))))
1194 (todo-set-categories)
1195 (unless buf2 (kill-buffer)))))
1196 (setq todo-files (funcall todo-files-function)
1197 todo-archives (funcall todo-files-function t))
1198 (when (or (string= file1-sn todo-default-todo-file)
1199 (and delete2 (string= file1-sn todo-default-todo-file)))
1200 (setq todo-default-todo-file (todo-short-file-name (car todo-files))))
1201 (when (or (string= file1 todo-global-current-todo-file)
1202 (and delete2 (string= file2 todo-global-current-todo-file)))
1203 (setq todo-global-current-todo-file nil))
1204 (todo-reevaluate-filelist-defcustoms)
1205 (message (concat (cond (todo "Todo") (archive "Archive")) " file \"%s\" "
1208 (cond (todo "archive") (archive "todo"))
1213 (defvar todo-edit-buffer "*Todo Edit*"
1214 "Name of current buffer in Todo Edit mode.")
1216 (defun todo-edit-file ()
1217 "Put current buffer in `todo-edit-mode'.
1218 This makes the entire file visible and the buffer writable and
1219 you can use the self-insertion keys and standard Emacs editing
1220 commands to make changes. To return to Todo mode, type
1221 \\[todo-edit-quit]. This runs a file format check, signaling
1222 an error if the format has become invalid. However, this check
1223 cannot tell if the number of items changed, which could result in
1224 the file containing inconsistent information. For this reason
1225 this command should be used with caution."
1230 (display-warning 'todo (format "\
1232 Type %s to return to Todo mode.
1234 This also runs a file format check and signals an error if
1235 the format has become invalid. However, this check cannot
1236 tell if the number of items or categories changed, which
1237 could result in the file containing inconsistent information.
1238 You can repair this inconsistency by invoking the command
1239 `todo-repair-categories-sexp', but this will revert any
1240 renumbering of the categories you have made, so you will
1241 have to renumber them again (see `(todo-mode) Reordering
1242 Categories')." (substitute-command-keys "\\[todo-edit-quit]"))))
1244 (defun todo-add-category (&optional file cat)
1245 "Add a new category to a todo file.
1247 Called interactively with prefix argument FILE, prompt for a file
1248 and then for a new category to add to that file, otherwise prompt
1249 just for a category to add to the current todo file. After
1250 adding the category, visit it in Todo mode and if option
1251 `todo-add-item-if-new-category' is non-nil (the default), prompt
1254 Non-interactively, add category CAT to file FILE; if FILE is nil,
1255 add CAT to the current todo file. After adding the category,
1256 return the new category number."
1259 ;; If cat is passed from caller, don't prompt, unless it is "",
1260 ;; which means the file was just added and has no category yet.
1261 (if (and cat (> (length cat) 0))
1262 (setq file0 (or (and (stringp file) file)
1263 todo-current-todo-file))
1264 (setq catfil (todo-read-category "Enter a new category name: "
1265 'add (when (called-interactively-p 'any)
1268 file0 (if (called-interactively-p 'any)
1272 (let ((counts (make-vector 4 0)) ; [todo diary done archived]
1273 (num (1+ (length todo-categories)))
1274 (buffer-read-only nil))
1275 (setq todo-current-todo-file file0)
1276 (setq todo-categories (append todo-categories
1277 (list (cons cat counts))))
1279 (goto-char (point-max))
1280 (save-excursion ; Save point for todo-category-select.
1281 (insert todo-category-beg cat "\n\n" todo-category-done "\n"))
1282 (todo-update-categories-sexp)
1283 ;; If invoked by user, display the newly added category, if
1284 ;; called programmatically return the category number to the
1286 (if (called-interactively-p 'any)
1288 (setq todo-category-number num)
1289 (todo-category-select)
1290 (when todo-add-item-if-new-category
1291 (todo-insert-item--basic)))
1294 (defun todo-rename-category ()
1295 "Rename current todo category.
1296 If this file has an archive containing this category, rename the
1297 category there as well."
1299 (let* ((cat (todo-current-category))
1300 (new (read-from-minibuffer
1301 (format "Rename category \"%s\" to: " cat))))
1302 (setq new (todo-validate-name new 'category))
1303 (let* ((ofile todo-current-todo-file)
1304 (archive (concat (file-name-sans-extension ofile) ".toda"))
1305 (buffers (append (list ofile)
1306 (unless (zerop (todo-get-count 'archived cat))
1308 (dolist (buf buffers)
1309 (with-current-buffer (find-file-noselect buf)
1310 (let (buffer-read-only)
1311 (setq todo-categories (todo-set-categories))
1314 (setcar (assoc cat todo-categories) new)
1316 (goto-char (point-min))
1317 (todo-update-categories-sexp)
1318 (re-search-forward (concat (regexp-quote todo-category-beg)
1319 "\\(" (regexp-quote cat) "\\)\n")
1321 (replace-match new t t nil 1)))))))
1322 (force-mode-line-update))
1323 (save-excursion (todo-category-select)))
1325 (defun todo-delete-category (&optional arg)
1326 "Delete current todo category provided it contains no items.
1327 With prefix ARG delete the category even if it does contain
1328 todo or done items."
1330 (let* ((file todo-current-todo-file)
1331 (cat (todo-current-category))
1332 (todo (todo-get-count 'todo cat))
1333 (done (todo-get-count 'done cat))
1334 (archived (todo-get-count 'archived cat)))
1336 (or (> todo 0) (> done 0)))
1337 (message "%s" (substitute-command-keys
1338 (concat "To delete a non-empty category, "
1339 "type C-u \\[todo-delete-category].")))
1340 (when (cond ((= (length todo-categories) 1)
1342 (concat "This is the only category in this file; "
1343 "deleting it will also delete the file.\n"
1344 "Do you want to proceed? ")))
1346 (todo-y-or-n-p (format-message
1347 (concat "This category has archived items; "
1348 "the archived category will remain\n"
1349 "after deleting the todo category. "
1350 "Do you still want to delete it\n"
1351 "(see `todo-skip-archived-categories' "
1352 "for another option)? "))))
1354 (todo-y-or-n-p (concat "Permanently remove category \"" cat
1355 "\"" (and arg " and all its entries")
1358 (let ((buffer-read-only)
1359 (beg (re-search-backward
1360 (concat "^" (regexp-quote (concat todo-category-beg cat))
1362 (end (if (re-search-forward
1363 (concat "\n\\(" (regexp-quote todo-category-beg)
1367 (remove-overlays beg end)
1368 (delete-region beg end)
1369 (if (= (length todo-categories) 1)
1370 ;; If deleted category was the only one, delete the file.
1372 (todo-reevaluate-filelist-defcustoms)
1373 ;; Skip confirming killing the archive buffer if it has been
1374 ;; modified and not saved.
1375 (set-buffer-modified-p nil)
1378 (message "Deleted todo file %s." file))
1379 (setq todo-categories (delete (assoc cat todo-categories)
1381 (todo-update-categories-sexp)
1382 (setq todo-category-number
1383 (1+ (mod todo-category-number (length todo-categories))))
1384 (todo-category-select)
1385 (goto-char (point-min))
1386 (message "Deleted category %s." cat)))))))
1388 (defun todo-move-category ()
1389 "Move current category to a different todo file.
1390 If the todo file chosen does not exist, it is created.
1391 If the current category has archived items, also move those to
1392 the archive of the file moved to, creating it if it does not exist."
1394 (when (or (> (length todo-categories) 1)
1395 (todo-y-or-n-p (concat "This is the only category in this file; "
1396 "moving it will also delete the file.\n"
1397 "Do you want to proceed? ")))
1398 (let* ((ofile todo-current-todo-file)
1399 (cat (todo-current-category))
1400 (nfile (todo-read-file-name "Todo file to move this category to: "))
1401 (archive (concat (file-name-sans-extension ofile) ".toda"))
1402 (buffers (append (list ofile)
1403 (unless (zerop (todo-get-count 'archived cat))
1406 (while (equal nfile (file-truename ofile))
1407 (setq nfile (todo-read-file-name
1408 "Choose a file distinct from this file: ")))
1409 (unless (member nfile todo-files)
1410 (with-current-buffer (get-buffer-create nfile)
1412 (write-region (point-min) (point-max) nfile nil 'nomessage nil t)
1413 (kill-buffer nfile))
1414 (setq todo-files (funcall todo-files-function))
1415 (todo-reevaluate-filelist-defcustoms))
1416 (dolist (buf buffers)
1417 (with-current-buffer (find-file-noselect buf)
1419 (goto-char (point-max))
1420 (let* ((beg (re-search-backward
1422 (regexp-quote (concat todo-category-beg cat))
1425 (end (if (re-search-forward
1426 (concat "^" (regexp-quote todo-category-beg))
1430 (content (buffer-substring-no-properties beg end))
1431 (counts (cdr (assoc cat todo-categories)))
1433 ;; Move the category to the new file. Also update or create
1434 ;; archive file if necessary.
1435 (with-current-buffer
1437 ;; Regenerate todo-archives in case there
1438 ;; is a newly created archive.
1439 (if (member buf (funcall todo-files-function t))
1440 (concat (file-name-sans-extension nfile) ".toda")
1442 (if (equal (file-name-extension (buffer-file-name)) "toda")
1443 (unless (derived-mode-p 'todo-archive-mode)
1444 (todo-archive-mode))
1445 (unless (derived-mode-p 'todo-mode) (todo-mode)))
1446 (let* ((nfile-short (todo-short-file-name nfile))
1448 (format "Todo file \"%s\" already has "
1450 (format "the category \"%s\";\n" cat)
1451 "enter a new category name: "))
1454 (goto-char (point-max))
1456 ;; If the file moved to has a category with the same
1457 ;; name, rename the moved category.
1458 (when (assoc cat todo-categories)
1459 (unless (member (file-truename (buffer-file-name))
1460 (funcall todo-files-function t))
1461 (setq new (read-from-minibuffer prompt))
1462 (setq new (todo-validate-name new 'category))))
1463 ;; Replace old with new name in todo and archive files.
1465 (goto-char (point-max))
1467 (concat "^" (regexp-quote todo-category-beg)
1468 "\\(" (regexp-quote cat) "\\)$") nil t)
1469 (replace-match new nil nil nil 1)))
1470 (setq todo-categories
1471 (append todo-categories (list (cons (or new cat) counts))))
1472 (todo-update-categories-sexp)
1473 ;; If archive was just created, save it to avoid "File
1474 ;; <xyz> no longer exists!" message on invoking
1475 ;; `todo-view-archived-items'.
1476 (unless (file-exists-p (buffer-file-name))
1478 (todo-category-number (or new cat))
1479 (todo-category-select))
1480 ;; Delete the category from the old file, and if that was the
1481 ;; last category, delete the file. Also handle archive file
1483 (remove-overlays beg end)
1484 (delete-region beg end)
1485 (goto-char (point-min))
1486 ;; Put point after todo-categories sexp.
1488 (if (eobp) ; Aside from sexp, file is empty.
1490 ;; Skip confirming killing the archive buffer.
1491 (set-buffer-modified-p nil)
1492 (delete-file todo-current-todo-file)
1494 (when (member todo-current-todo-file todo-files)
1495 (todo-reevaluate-filelist-defcustoms)))
1496 (setq todo-categories (delete (assoc cat todo-categories)
1498 (todo-update-categories-sexp)
1499 (when (> todo-category-number (length todo-categories))
1500 (setq todo-category-number 1))
1501 (todo-category-select)))))
1502 (set-window-buffer (selected-window)
1503 (set-buffer (find-file-noselect nfile)))
1504 (todo-category-number (or new cat))
1505 (todo-category-select))))
1507 (defun todo-merge-category (&optional file)
1508 "Merge current category into another existing category.
1510 With prefix argument FILE, prompt for a specific todo file and
1511 choose (with TAB completion) a category in it to merge into;
1512 otherwise, choose and merge into a category in either the
1513 current todo file or a file in `todo-category-completions-files'.
1515 After merging, the source category's todo and done items are
1516 appended to the chosen goal category's todo and done items,
1517 respectively. The goal category becomes the current category,
1518 and the source category is deleted.
1520 If both the source and goal categories also have archived items,
1521 they are also merged. If only the source category has archived
1522 items, the goal category is added as a new category to the
1523 archive file and the source category is deleted."
1525 (let* ((tfile todo-current-todo-file)
1526 (cat (todo-current-category))
1527 (cat+file (todo-read-category "Merge into category: " 'todo file))
1528 (goal (car cat+file))
1529 (gfile (cdr cat+file))
1530 (tarchive (concat (file-name-sans-extension tfile) ".toda"))
1531 (garchive (concat (file-name-sans-extension gfile) ".toda"))
1532 (archived-count (todo-get-count 'archived))
1534 (with-current-buffer (get-buffer (find-file-noselect tfile))
1536 (let* ((buffer-read-only nil)
1539 (concat "^" (regexp-quote todo-category-beg)) nil t)
1541 (tbeg (progn (forward-line) (point-marker)))
1544 (concat "^" (regexp-quote todo-category-done)) nil t)
1545 (forward-line) (point-marker)))
1546 ;; Omit empty line between todo and done items.
1547 (tend (progn (forward-line -2) (point-marker)))
1549 (if (re-search-forward
1550 (concat "^" (regexp-quote todo-category-beg)) nil t)
1552 (goto-char (match-beginning 0))
1554 (point-max-marker))))
1555 (todo (buffer-substring-no-properties tbeg tend))
1556 (done (buffer-substring-no-properties dbeg cend))
1557 (todo-count (todo-get-count 'todo cat))
1558 (done-count (todo-get-count 'done cat)))
1559 ;; Merge into goal todo category.
1560 (with-current-buffer (get-buffer (find-file-noselect gfile))
1561 (unless (derived-mode-p 'todo-mode) (todo-mode))
1563 (goto-char (point-min))
1564 (let ((buffer-read-only nil))
1565 ;; Merge any todo items.
1566 (unless (zerop (length todo))
1568 (concat "^" (regexp-quote (concat todo-category-beg goal)) "$")
1571 (concat "^" (regexp-quote todo-category-done)) nil t)
1573 (setq here (point-marker))
1575 (todo-update-count 'todo todo-count goal))
1576 ;; Merge any done items.
1577 (unless (zerop (length done))
1578 (goto-char (if (re-search-forward
1579 (concat "^" (regexp-quote todo-category-beg))
1583 (when (zerop (length todo)) (setq here (point-marker)))
1585 (todo-update-count 'done done-count goal)))
1586 (todo-update-categories-sexp))
1587 ;; Update and clean up source todo file.
1588 (remove-overlays cbeg cend)
1589 (delete-region cbeg cend)
1590 (setq todo-categories (delete (assoc cat todo-categories)
1592 (todo-update-categories-sexp)
1593 (when (> todo-category-number (length todo-categories))
1594 (setq todo-category-number 1))
1595 (todo-category-select)
1596 (mapc (lambda (m) (set-marker m nil))
1597 (list cbeg tbeg dbeg tend cend))))
1598 (when (> archived-count 0)
1599 (with-current-buffer (get-buffer (find-file-noselect tarchive))
1601 (goto-char (point-min))
1602 (let* ((buffer-read-only nil)
1604 (when (re-search-forward
1605 (concat "^" (regexp-quote
1606 (concat todo-category-beg cat)) "$")
1608 (goto-char (match-beginning 0))
1610 (cend (if (re-search-forward
1611 (concat "^" (regexp-quote todo-category-beg)) nil t)
1617 (buffer-substring-no-properties (point) cend))))
1618 ;; Merge into goal archive category, if it exists, else create it.
1619 (with-current-buffer (get-buffer (find-file-noselect garchive))
1620 (let ((gbeg (when (re-search-forward
1621 (concat "^" (regexp-quote
1622 (concat todo-category-beg goal))
1625 (goto-char (match-beginning 0))
1627 (goto-char (if (and gbeg
1629 (concat "^" (regexp-quote todo-category-beg))
1633 (unless gbeg (todo-add-category nil goal))
1635 (todo-update-categories-sexp)))
1636 ;; Update and clean up source archive file.
1637 (remove-overlays cbeg cend)
1638 (delete-region cbeg cend)
1639 (setq todo-categories (todo-make-categories-list t))
1640 (todo-update-categories-sexp))))
1641 ;; Update goal todo file for merged archived items and display it.
1642 (set-window-buffer (selected-window) (set-buffer (get-file-buffer gfile)))
1643 (unless (zerop archived-count)
1644 (todo-update-count 'archived archived-count goal)
1645 (todo-update-categories-sexp))
1646 (todo-category-number goal)
1647 ;; If there are only merged done items, show them.
1648 (let ((todo-show-with-done (zerop (todo-get-count 'todo goal))))
1649 (todo-category-select)
1650 ;; Put point on the first merged item.
1652 (set-marker here nil)))
1654 ;; -----------------------------------------------------------------------------
1656 ;; -----------------------------------------------------------------------------
1658 (defcustom todo-include-in-diary nil
1659 "Non-nil to allow new todo items to be included in the diary."
1663 (defcustom todo-diary-nonmarking nil
1664 "Non-nil to insert new todo diary items as nonmarking by default.
1665 This appends `diary-nonmarking-symbol' to the front of an item on
1666 insertion provided it doesn't begin with `todo-nondiary-marker'."
1670 (defcustom todo-always-add-time-string nil
1671 "Non-nil adds current time to a new item's date header by default.
1672 When the todo insertion commands have a non-nil \"maybe-notime\"
1673 argument, this reverses the effect of
1674 `todo-always-add-time-string': if t, these commands omit the
1675 current time, if nil, they include it."
1679 (defcustom todo-use-only-highlighted-region t
1680 "Non-nil to enable inserting only highlighted region as new item."
1684 (defcustom todo-default-priority 'first
1685 "Default priority of new and moved items."
1686 :type '(choice (const :tag "Highest priority" first)
1687 (const :tag "Lowest priority" last))
1690 (defcustom todo-item-mark "*"
1691 "String used to mark items.
1692 To ensure item marking works, change the value of this option
1693 only when no items are marked."
1694 :type '(string :validate
1696 (when (string= (widget-value widget) todo-prefix)
1700 "Invalid value: must be distinct from `todo-prefix'"))
1702 :set (lambda (symbol value)
1703 (custom-set-default symbol (propertize value 'face 'todo-mark)))
1706 (defcustom todo-comment-string "COMMENT"
1707 "String inserted before optional comment appended to done item."
1709 :initialize 'custom-initialize-default
1710 :set 'todo-reset-comment-string
1713 (defcustom todo-undo-item-omit-comment 'ask
1714 "Whether to omit done item comment on undoing the item.
1715 Nil means never omit the comment, t means always omit it, `ask'
1716 means prompt user and omit comment only on confirmation."
1717 :type '(choice (const :tag "Never" nil)
1718 (const :tag "Always" t)
1719 (const :tag "Ask" ask))
1722 (defun todo-toggle-mark-item (&optional n)
1723 "Mark item with `todo-item-mark' if unmarked, otherwise unmark it.
1724 With positive numerical prefix argument N, change the marking of
1725 the next N items in the current category. If both the todo and
1726 done items sections are visible, the sequence of N items can
1727 consist of the the last todo items and the first done items."
1729 (when (todo-item-string)
1730 (unless (> n 1) (setq n 1))
1733 (let* ((cat (todo-current-category))
1734 (marks (assoc cat todo-categories-with-marks))
1736 (unless (looking-at todo-item-start)
1738 (todo-get-overlay 'prefix)))
1739 (pref (overlay-get ov 'before-string)))
1740 (if (todo-marked-item-p)
1742 (overlay-put ov 'before-string (substring pref 1))
1743 (if (= (cdr marks) 1) ; Deleted last mark in this category.
1744 (setq todo-categories-with-marks
1745 (assq-delete-all cat todo-categories-with-marks))
1746 (setcdr marks (1- (cdr marks)))))
1747 (overlay-put ov 'before-string (concat todo-item-mark pref))
1749 (setcdr marks (1+ (cdr marks)))
1750 (push (cons cat 1) todo-categories-with-marks))))
1752 ;; Don't try to mark the empty lines at the end of the todo
1753 ;; and done items sections.
1754 (when (looking-at "^$")
1757 (todo-forward-item)))))))
1759 (defun todo-mark-category ()
1760 "Mark all visible items in this category with `todo-item-mark'."
1762 (let* ((cat (todo-current-category))
1763 (marks (assoc cat todo-categories-with-marks)))
1765 (goto-char (point-min))
1767 (let* ((ov (todo-get-overlay 'prefix))
1768 (pref (overlay-get ov 'before-string)))
1769 (unless (todo-marked-item-p)
1770 (overlay-put ov 'before-string (concat todo-item-mark pref))
1772 (setcdr marks (1+ (cdr marks)))
1773 (push (cons cat 1) todo-categories-with-marks))))
1775 ;; Don't try to mark the empty line between the todo and done
1777 (when (looking-at "^$")
1779 (todo-forward-item)))))))
1781 (defun todo-unmark-category ()
1782 "Remove `todo-item-mark' from all visible items in this category."
1784 (let* ((cat (todo-current-category))
1785 (marks (assoc cat todo-categories-with-marks)))
1787 (goto-char (point-min))
1789 (let* ((ov (todo-get-overlay 'prefix))
1790 ;; No overlay on empty line between todo and done items.
1791 (pref (when ov (overlay-get ov 'before-string))))
1792 (when (todo-marked-item-p)
1793 (overlay-put ov 'before-string (substring pref 1)))
1794 (todo-forward-item))))
1795 (setq todo-categories-with-marks
1796 (delq marks todo-categories-with-marks))))
1798 (defvar todo-date-from-calendar nil
1799 "Helper variable for setting item date from the Emacs Calendar.")
1801 (defvar todo-insert-item--keys-so-far)
1802 (defvar todo-insert-item--parameters)
1804 (defun todo-insert-item (&optional arg)
1805 "Choose an item insertion operation and carry it out.
1806 This inserts a new todo item into a category.
1808 With no prefix argument ARG, add the item to the current
1809 category; with one prefix argument (`C-u'), prompt for a category
1810 from the current todo file; with two prefix arguments (`C-u
1811 C-u'), first prompt for a todo file, then a category in that
1812 file. If a non-existing category is entered, ask whether to add
1813 it to the todo file; if answered affirmatively, add the category
1814 and insert the item there.
1816 There are a number of item insertion parameters which can be
1817 combined by entering specific keys to produce different insertion
1818 commands. After entering each key, a message shows which have
1819 already been entered and which remain available. See
1820 `(todo-mode) Inserting New Items' for details of the parameters,
1821 their associated keys and their effects."
1823 (setq todo-insert-item--keys-so-far "i")
1824 (todo-insert-item--next-param nil (list arg) todo-insert-item--parameters))
1826 (defun todo-insert-item--basic (&optional arg diary-type date-type time where)
1827 "Function implementing the core of `todo-insert-item'."
1828 ;; If invoked outside of Todo mode and there is not yet any Todo
1829 ;; file, initialize one.
1830 (if (null (funcall todo-files-function))
1832 (let ((copy (eq where 'copy))
1833 (region (eq where 'region))
1834 (here (eq where 'here))
1838 ((not (eq major-mode 'todo-mode))
1839 (user-error "You must be in Todo mode to copy a todo item"))
1841 (user-error "You cannot copy a done item as a new todo item"))
1843 (user-error "Point must be on a todo item to copy it")))
1844 (setq diary-item (todo-diary-item-p)))
1846 (let (use-empty-active-region)
1847 (unless (and todo-use-only-highlighted-region (use-region-p))
1848 (user-error "There is no active region"))))
1849 (let* ((obuf (current-buffer))
1850 (ocat (todo-current-category))
1852 (todo-mm (eq major-mode 'todo-mode))
1853 (cat+file (cond ((equal arg '(4))
1854 (todo-read-category "Insert in category: "))
1856 (todo-read-category "Insert in category: "
1859 (cons (todo-current-category)
1860 (or todo-current-todo-file
1861 (and todo-show-current-file
1862 todo-global-current-todo-file)
1863 (todo-absolute-file-name
1864 todo-default-todo-file))))))
1865 (cat (car cat+file))
1866 (file (cdr cat+file))
1867 (new-item (cond (copy (todo-item-string))
1868 (region (buffer-substring-no-properties
1869 (region-beginning) (region-end)))
1870 (t (read-from-minibuffer "Todo item: "))))
1872 ((eq date-type 'date)
1874 ((eq date-type 'dayname)
1875 (todo-read-dayname))
1876 ((eq date-type 'calendar)
1877 (setq todo-date-from-calendar t)
1878 (or (todo-set-date-from-calendar)
1879 ;; If user exits Calendar before choosing
1880 ;; a date, cancel item insertion.
1882 ((and (stringp date-type)
1883 (string-match todo-date-pattern date-type))
1884 (setq todo-date-from-calendar date-type)
1885 (todo-set-date-from-calendar))
1887 (calendar-date-string
1888 (calendar-current-date) t t))))
1889 (time-string (or (and time (todo-read-time))
1890 (and todo-always-add-time-string
1891 (substring (current-time-string) 11 16)))))
1892 (setq todo-date-from-calendar nil)
1893 (find-file-noselect file 'nowarn)
1894 (set-window-buffer (selected-window)
1895 (set-buffer (find-buffer-visiting file)))
1896 ;; If this command was invoked outside of a Todo mode buffer,
1897 ;; the call to todo-current-category above returned nil. If
1898 ;; we just entered Todo mode now, then cat was set to the
1899 ;; file's first category, but if todo-mode was already
1900 ;; enabled, cat did not get set, so we have to do that.
1902 (setq cat (todo-current-category)))
1903 (setq todo-current-todo-file file)
1904 (unless todo-global-current-todo-file
1905 (setq todo-global-current-todo-file todo-current-todo-file))
1906 (let ((buffer-read-only nil)
1907 (called-from-outside (not (and todo-mm (equal cat ocat))))
1908 done-only item-added)
1911 ;; Add date, time and diary marking as required.
1912 (concat (if (not (and diary-type
1913 (not todo-include-in-diary)))
1915 (when (and (eq diary-type 'nonmarking)
1916 (not todo-diary-nonmarking))
1917 diary-nonmarking-symbol))
1918 date-string (when (and time-string ; Can be empty.
1921 (concat " " time-string))
1922 (when (not (and diary-type
1923 (not todo-include-in-diary)))
1926 ;; Indent newlines inserted by C-q C-j if nonspace char follows.
1927 (setq new-item (replace-regexp-in-string "\\(\n\\)[^[:blank:]]"
1928 "\n\t" new-item nil nil 1)))
1931 ;; Make sure the correct category is selected. There
1932 ;; are two cases: (i) we just visited the file, so no
1933 ;; category is selected yet, or (ii) we invoked
1934 ;; insertion "here" from outside the category we want
1935 ;; to insert in (with priority insertion, category
1936 ;; selection is done by todo-set-item-priority).
1937 (when (or (= (- (point-max) (point-min)) (buffer-size))
1938 (and here called-from-outside))
1939 (todo-category-number cat)
1940 (todo-category-select))
1941 ;; If only done items are displayed in category,
1942 ;; toggle to todo items before inserting new item.
1943 (when (save-excursion
1944 (goto-char (point-min))
1945 (looking-at todo-done-string-start))
1947 (todo-toggle-view-done-only))
1950 ;; If command was invoked with point in done
1951 ;; items section or outside of the current
1952 ;; category, can't insert "here", so to be
1953 ;; useful give new item top priority.
1954 (when (or (todo-done-item-section-p)
1957 (goto-char (point-min)))
1958 (todo-insert-with-overlays new-item))
1959 (todo-set-item-priority new-item cat t))
1960 (setq item-added t))
1961 ;; If user cancels before setting priority, restore
1964 (set-window-buffer (selected-window) (set-buffer obuf))
1966 (unless (equal cat ocat)
1967 (todo-category-number ocat)
1968 (todo-category-select))
1969 (and done-only (todo-toggle-view-done-only)))
1971 ;; If the todo items section is not visible when the
1972 ;; insertion command is called (either because only done
1973 ;; items were shown or because the category was not in the
1974 ;; current buffer), then if the item is inserted at the
1975 ;; end of the category, point is at eob and eob at
1976 ;; window-start, so that higher priority todo items are
1977 ;; out of view. So we recenter to make sure the todo
1978 ;; items are displayed in the window.
1979 (when item-added (recenter)))
1980 (todo-update-count 'todo 1)
1981 (when (or diary-item diary-type todo-include-in-diary)
1982 (todo-update-count 'diary 1))
1983 (todo-update-categories-sexp))))))
1985 (defun todo-set-date-from-calendar ()
1986 "Return string of date chosen from Calendar."
1987 (cond ((and (stringp todo-date-from-calendar)
1988 (string-match todo-date-pattern todo-date-from-calendar))
1989 todo-date-from-calendar)
1990 (todo-date-from-calendar
1991 (let (calendar-view-diary-initially-flag)
1992 (calendar)) ; *Calendar* is now current buffer.
1993 (define-key calendar-mode-map [remap newline] 'exit-recursive-edit)
1994 ;; If user exits Calendar before choosing a date, clean up properly.
1995 (define-key calendar-mode-map
1996 [remap calendar-exit] (lambda ()
2000 (exit-recursive-edit))))
2001 (message "Put cursor on a date and type <return> to set it.")
2004 (when (equal (buffer-name) calendar-buffer)
2005 (setq todo-date-from-calendar
2006 (calendar-date-string (calendar-cursor-to-date t) t t))
2008 todo-date-from-calendar)
2009 (define-key calendar-mode-map [remap newline] nil)
2010 (define-key calendar-mode-map [remap calendar-exit] nil)
2011 (unless (zerop (recursion-depth)) (exit-recursive-edit))
2012 (when (stringp todo-date-from-calendar)
2013 todo-date-from-calendar)))))
2015 (defun todo-insert-item-from-calendar (&optional arg)
2016 "Prompt for and insert a new item with date selected from calendar.
2017 Invoked without prefix argument ARG, insert the item into the
2018 current category, without one prefix argument, prompt for the
2019 category from the current todo file or from one listed in
2020 `todo-category-completions-files'; with two prefix arguments,
2021 prompt for a todo file and then for a category in it."
2023 (setq todo-date-from-calendar
2024 (calendar-date-string (calendar-cursor-to-date t) t t))
2026 (todo-insert-item--basic arg nil todo-date-from-calendar))
2028 (define-key calendar-mode-map "it" 'todo-insert-item-from-calendar)
2030 (defun todo-delete-item ()
2031 "Delete at least one item in this category.
2032 If there are marked items, delete all of these; otherwise, delete
2037 (let* ((cat (todo-current-category))
2038 (marked (assoc cat todo-categories-with-marks))
2039 (item (unless marked (todo-item-string)))
2042 "Permanently delete all marked items? ")
2044 (setq ov (make-overlay
2045 (save-excursion (todo-item-start))
2046 (save-excursion (todo-item-end))))
2047 (overlay-put ov 'face 'todo-search)
2048 (todo-y-or-n-p "Permanently delete this item? "))))
2051 (and marked (goto-char (point-min)))
2054 (if (or (and marked (todo-marked-item-p)) item)
2056 (if (todo-done-item-p)
2057 (todo-update-count 'done -1)
2058 (todo-update-count 'todo -1 cat)
2059 (and (todo-diary-item-p)
2060 (todo-update-count 'diary -1)))
2061 (if ov (delete-overlay ov))
2063 ;; Don't leave point below last item.
2064 (and item (bolp) (eolp) (< (point-min) (point-max))
2065 (todo-backward-item))
2067 (throw 'done (setq item nil))))
2068 (todo-forward-item))))
2070 (setq todo-categories-with-marks
2071 (assq-delete-all cat todo-categories-with-marks)))
2072 (todo-update-categories-sexp)
2073 (todo-prefix-overlays)))
2074 (if ov (delete-overlay ov)))))
2076 (defvar todo-edit-item--param-key-alist)
2077 (defvar todo-edit-done-item--param-key-alist)
2079 (defun todo-edit-item (&optional arg)
2080 "Choose an editing operation for the current item and carry it out."
2082 (let ((marked (assoc (todo-current-category) todo-categories-with-marks)))
2083 (cond ((and (todo-done-item-p) (not marked))
2084 (todo-edit-item--next-key todo-edit-done-item--param-key-alist))
2085 ((or marked (todo-item-string))
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 ((full-item (todo-item-string)))
2091 ;; If there are marked items and user invokes a text-editing
2092 ;; commands with point not on an item, todo-item-start is nil and
2093 ;; 1+ signals an error, so just make this a noop.
2095 (let* ((opoint (point))
2096 (start (todo-item-start))
2097 (end (save-excursion (todo-item-end)))
2100 (concat todo-date-string-start todo-date-pattern
2101 "\\( " diary-time-regexp "\\)?"
2102 (regexp-quote todo-nondiary-end) "?")
2103 (line-end-position) t)
2104 (1+ (- (point) start))))
2105 (include-header (eq arg 'include-header))
2106 (comment-edit (eq arg 'comment-edit))
2107 (comment-delete (eq arg 'comment-delete))
2108 (header-string (substring full-item 0 item-beg))
2109 (item (if (or include-header comment-edit comment-delete)
2111 (substring full-item item-beg)))
2112 (multiline (or (eq arg 'multiline)
2113 (> (length (split-string item "\n")) 1)))
2114 (comment (save-excursion
2117 (concat " \\[" (regexp-quote todo-comment-string)
2118 ": \\([^]]+\\)\\]") end t)))
2119 (prompt (if comment "Edit comment: " "Enter a comment: "))
2120 (buffer-read-only nil))
2121 ;; When there are marked items, user can invoke todo-edit-item
2122 ;; even if point is not on an item, but text editing only
2123 ;; applies to the item at point.
2124 (when (or (and (todo-done-item-p)
2125 (or comment-edit comment-delete))
2126 (and (not (todo-done-item-p))
2127 (or (not arg) include-header multiline)))
2129 ((or comment-edit comment-delete)
2132 (if (re-search-forward (concat " \\["
2133 (regexp-quote todo-comment-string)
2134 ": \\([^]]+\\)\\]") end t)
2136 (when (todo-y-or-n-p "Delete comment? ")
2137 (delete-region (match-beginning 0) (match-end 0)))
2138 (replace-match (read-string prompt (cons (match-string 1) 1))
2141 (user-error "There is no comment to delete")
2142 (insert " [" todo-comment-string ": "
2143 (prog1 (read-string prompt)
2144 ;; If user moved point during editing,
2145 ;; make sure it moves back.
2150 (let ((buf todo-edit-buffer))
2151 (set-window-buffer (selected-window)
2152 (set-buffer (make-indirect-buffer
2153 (buffer-name) buf)))
2154 (narrow-to-region (todo-item-start) (todo-item-end))
2156 (message "%s" (substitute-command-keys
2157 (concat "Type \\[todo-edit-quit] "
2158 "to return to Todo mode.\n")))))
2160 (let ((new (concat (if include-header "" header-string)
2161 (read-string "Edit: " (if include-header
2162 (cons item item-beg)
2164 (when include-header
2165 (while (not (string-match (concat todo-date-string-start
2166 todo-date-pattern) new))
2167 (setq new (read-from-minibuffer
2168 "Item must start with a date: " new))))
2169 ;; Ensure lines following hard newlines are indented.
2170 (setq new (replace-regexp-in-string "\\(\n\\)[^[:blank:]]"
2171 "\n\t" new nil nil 1))
2172 ;; If user moved point during editing, make sure it moves back.
2175 (todo-insert-with-overlays new)
2176 (move-to-column item-beg)))))))))
2178 (defun todo-edit-quit ()
2179 "Return from Todo Edit mode to Todo mode.
2180 If the item contains hard line breaks, make sure the following
2181 lines are indented by `todo-indent-to-here' to conform to diary
2184 If the whole file was in Todo Edit mode, check before returning
2185 whether the file is still a valid todo file and if so, also
2186 recalculate the todo file's categories sexp, in case changes were
2187 made in the number or names of categories."
2189 (if (> (buffer-size) (- (point-max) (point-min)))
2190 ;; We got here via `e m'.
2191 (let ((item (buffer-string))
2192 (regex "\\(\n\\)[^[:blank:]]")
2193 (buf (buffer-base-buffer)))
2194 (while (not (string-match (concat todo-date-string-start
2195 todo-date-pattern) item))
2196 (setq item (read-from-minibuffer
2197 "Item must start with a date: " item)))
2198 ;; Ensure lines following hard newlines are indented.
2199 (when (string-match regex (buffer-string))
2200 (setq item (replace-regexp-in-string regex "\n\t" item nil nil 1))
2201 (delete-region (point-min) (point-max))
2204 (unless (eq (current-buffer) buf)
2205 (set-window-buffer (selected-window) (set-buffer buf))))
2206 ;; We got here via `F e'.
2207 (when (todo-check-format)
2208 ;; FIXME: separate out sexp check?
2209 ;; If manual editing makes e.g. item counts change, have to
2210 ;; call this to update todo-categories, but it restores
2211 ;; category order to list order.
2212 ;; (todo-repair-categories-sexp)
2213 ;; Compare (todo-make-categories-list t) with sexp and if
2214 ;; different ask (todo-update-categories-sexp) ?
2216 (let* ((cat-beg (concat "^" (regexp-quote todo-category-beg)
2218 (curline (buffer-substring-no-properties
2219 (line-beginning-position) (line-end-position)))
2220 (cat (cond ((string-match cat-beg curline)
2221 (match-string-no-properties 1 curline))
2222 ((or (re-search-backward cat-beg nil t)
2223 (re-search-forward cat-beg nil t))
2224 (match-string-no-properties 1)))))
2225 (todo-category-number cat)
2226 (todo-category-select)
2227 (goto-char (point-min))))))
2229 (defun todo-edit-item--header (what &optional inc)
2230 "Function providing header editing facilities of `todo-edit-item'."
2231 (let ((marked (assoc (todo-current-category) todo-categories-with-marks))
2233 (todo-date-from-calendar t)
2234 ;; INC must be an integer, but users could pass it via
2235 ;; `todo-edit-item' as e.g. `-' or `C-u'.
2236 (inc (prefix-numeric-value inc))
2237 (buffer-read-only nil)
2238 ndate ntime year monthname month day
2239 dayname) ; Needed by calendar-date-display-form.
2240 (when marked (todo--user-error-if-marked-done-item))
2242 (or (and marked (goto-char (point-min))) (todo-item-start))
2246 (while (not (todo-marked-item-p))
2248 (and (eobp) (throw 'end nil))))
2249 (re-search-forward (concat todo-date-string-start "\\(?1:"
2251 "\\)\\(?2: " diary-time-regexp "\\)?"
2252 (regexp-quote todo-nondiary-end) "?")
2253 (line-end-position) t)
2254 (let* ((odate (match-string-no-properties 1))
2255 (otime (match-string-no-properties 2))
2256 (odayname (match-string-no-properties 5))
2257 (omonthname (match-string-no-properties 6))
2258 (omonth (match-string-no-properties 7))
2259 (oday (match-string-no-properties 8))
2260 (oyear (match-string-no-properties 9))
2261 (tmn-array todo-month-name-array)
2262 (mlist (append tmn-array nil))
2263 (tma-array todo-month-abbrev-array)
2264 (mablist (append tma-array nil))
2265 (yy (and oyear (unless (string= oyear "*")
2266 (string-to-number oyear))))
2267 (mm (or (and omonth (unless (string= omonth "*")
2268 (string-to-number omonth)))
2269 (1+ (- (length mlist)
2270 (length (or (member omonthname mlist)
2271 (member omonthname mablist)))))))
2272 (dd (and oday (unless (string= oday "*")
2273 (string-to-number oday)))))
2274 ;; If there are marked items, use only the first to set
2275 ;; header changes, and apply these to all marked items.
2279 (setq ndate (todo-read-date)))
2280 ((eq what 'calendar)
2281 (setq ndate (save-match-data (todo-set-date-from-calendar))))
2283 (setq ndate (calendar-date-string (calendar-current-date) t t)))
2285 (setq ndate (todo-read-dayname)))
2287 (setq ntime (save-match-data (todo-read-time)))
2288 (when (> (length ntime) 0)
2289 (setq ntime (concat " " ntime))))
2290 ;; When date string consists only of a day name,
2291 ;; passing other date components is a noop.
2292 ((and odayname (memq what '(year month day))))
2295 monthname omonthname
2297 year (cond ((not current-prefix-arg)
2298 (todo-read-date 'year))
2299 ((string= oyear "*")
2300 (user-error "Cannot increment *"))
2302 (number-to-string (+ yy inc))))))
2306 (if (memq 'month calendar-date-display-form)
2309 (cond ((not current-prefix-arg)
2310 (todo-read-date 'month))
2311 ((or (string= omonth "*") (= mm 13))
2312 (user-error "Cannot increment *"))
2314 (let ((mminc (+ mm inc)))
2315 ;; Increment or decrement month by INC
2317 (setq mm (% mminc 12))
2318 ;; If result is 0, make month December.
2319 (setq mm (if (= mm 0) 12 (abs mm)))
2320 ;; Adjust year if necessary.
2321 (setq year (or (and (cond ((> mminc 12)
2322 (+ yy (/ mminc 12)))
2324 (- yy (/ mminc 12) 1))
2326 (number-to-string yy))
2328 ;; Return the changed numerical month as
2329 ;; a string or the corresponding month name.
2331 (number-to-string mm)
2332 (aref tma-array (1- mm))))))
2333 (let ((yy (string-to-number year)) ; 0 if year is "*".
2334 ;; When mm is 13 (corresponding to "*" as value
2335 ;; of month), this raises an args-out-of-range
2336 ;; error in calendar-last-day-of-month, so use 1
2337 ;; (corresponding to January) to get 31 days.
2338 (mm (if (= mm 13) 1 mm)))
2339 (if (> (string-to-number day)
2340 (calendar-last-day-of-month mm yy))
2341 (user-error "%s %s does not have %s days"
2342 (aref tmn-array (1- mm))
2343 (if (= mm 2) yy "") day))))
2347 monthname omonthname
2349 ((not current-prefix-arg)
2350 (todo-read-date 'day mm oyear))
2352 (user-error "Cannot increment *"))
2353 ((or (string= omonth "*") (string= omonthname "*"))
2354 (setq dd (+ dd inc))
2357 "A month cannot have more than 31 days")
2358 (number-to-string dd)))
2359 ;; Increment or decrement day by INC,
2360 ;; adjusting month and year if necessary
2361 ;; (if year is "*" assume current year to
2362 ;; calculate adjustment).
2364 (let* ((yy (or yy (calendar-extract-year
2365 (calendar-current-date))))
2366 (date (calendar-gregorian-from-absolute
2367 (+ (calendar-absolute-from-gregorian
2368 (list mm dd yy)) inc)))
2369 (adjmm (nth 0 date)))
2370 ;; Set year and month(name) to adjusted values.
2371 (unless (string= year "*")
2372 (setq year (number-to-string (nth 2 date))))
2374 (setq month (number-to-string adjmm))
2375 (setq monthname (aref tma-array (1- adjmm))))
2376 ;; Return changed numerical day as a string.
2377 (number-to-string (nth 1 date)))))))))
2379 ;; If year, month or day date string components were
2380 ;; changed, rebuild the date string.
2381 (when (memq what '(year month day))
2382 (setq ndate (mapconcat 'eval calendar-date-display-form ""))))
2383 (when ndate (replace-match ndate nil nil nil 1))
2384 ;; Add new time string to the header, if it was supplied.
2387 (replace-match ntime nil nil nil 2)
2388 (goto-char (match-end 1))
2390 (setq todo-date-from-calendar nil)
2392 ;; Apply the changes to the first marked item header to the
2393 ;; remaining marked items. If there are no marked items,
2397 (goto-char (point-max))))))))
2399 (defun todo-edit-item--diary-inclusion (&optional nonmarking)
2400 "Function providing diary marking facilities of `todo-edit-item'."
2401 (let ((buffer-read-only)
2402 (marked (assoc (todo-current-category) todo-categories-with-marks)))
2403 (when marked (todo--user-error-if-marked-done-item))
2406 (when marked (goto-char (point-min)))
2408 (unless (and marked (not (todo-marked-item-p)))
2409 (let* ((beg (todo-item-start))
2410 (lim (save-excursion (todo-item-end)))
2411 (end (save-excursion
2412 (or (todo-time-string-matcher lim)
2413 (todo-date-string-matcher lim)))))
2415 (if (looking-at (regexp-quote diary-nonmarking-symbol))
2417 (when (looking-at (regexp-quote todo-nondiary-start))
2420 (search-forward todo-nondiary-end (1+ end) t)
2422 (todo-update-count 'diary 1)))
2423 (insert diary-nonmarking-symbol))
2424 (if (looking-at (regexp-quote todo-nondiary-start))
2427 (search-forward todo-nondiary-end (1+ end) t)
2429 (todo-update-count 'diary 1))
2431 (when (looking-at (regexp-quote diary-nonmarking-symbol))
2433 (setq end (1- end))) ; Since we deleted nonmarking symbol.
2434 (insert todo-nondiary-start)
2435 (goto-char (1+ end))
2436 (insert todo-nondiary-end)
2437 (todo-update-count 'diary -1))))))
2438 (unless marked (throw 'stop nil))
2439 (todo-forward-item)))))
2440 (todo-update-categories-sexp))
2442 (defun todo-edit-category-diary-inclusion (arg)
2443 "Make all items in this category diary items.
2444 With prefix ARG, make all items in this category non-diary
2448 (goto-char (point-min))
2449 (let ((todo-count (todo-get-count 'todo))
2450 (diary-count (todo-get-count 'diary))
2454 (if (todo-done-item-p) ; We've gone too far.
2456 (let* ((beg (todo-item-start))
2457 (lim (save-excursion (todo-item-end)))
2458 (end (save-excursion
2459 (or (todo-time-string-matcher lim)
2460 (todo-date-string-matcher lim)))))
2462 (unless (looking-at (regexp-quote todo-nondiary-start))
2463 (when (looking-at (regexp-quote diary-nonmarking-symbol))
2465 (setq end (1- end))) ; Since we deleted nonmarking symbol.
2466 (insert todo-nondiary-start)
2467 (goto-char (1+ end))
2468 (insert todo-nondiary-end))
2469 (when (looking-at (regexp-quote todo-nondiary-start))
2471 (search-forward todo-nondiary-end (1+ end) t)
2472 (replace-match "")))))
2473 (todo-forward-item))
2474 (unless (if arg (zerop diary-count) (= diary-count todo-count))
2475 (todo-update-count 'diary (if arg
2477 (- todo-count diary-count))))
2478 (todo-update-categories-sexp)))))
2480 (defun todo-edit-category-diary-nonmarking (arg)
2481 "Add `diary-nonmarking-symbol' to all diary items in this category.
2482 With prefix ARG, remove `diary-nonmarking-symbol' from all diary
2483 items in this category."
2486 (goto-char (point-min))
2487 (let (buffer-read-only)
2490 (if (todo-done-item-p) ; We've gone too far.
2492 (unless (looking-at (regexp-quote todo-nondiary-start))
2494 (when (looking-at (regexp-quote diary-nonmarking-symbol))
2496 (unless (looking-at (regexp-quote diary-nonmarking-symbol))
2497 (insert diary-nonmarking-symbol))))
2498 (todo-forward-item)))))))
2500 (defun todo-set-item-priority (&optional item cat new arg)
2501 "Prompt for and set ITEM's priority in CATegory.
2503 Interactively, ITEM is the todo item at point, CAT is the current
2504 category, and the priority is a number between 1 and the number
2505 of items in the category. Non-interactively, non-nil NEW means
2506 ITEM is a new item and the lowest priority is one more than the
2507 number of items in CAT.
2509 The new priority is set either interactively by prompt or by a
2510 numerical prefix argument, or noninteractively by argument ARG,
2511 whose value can be either of the symbols `raise' or `lower',
2512 meaning to raise or lower the item's priority by one."
2514 (unless (and (called-interactively-p 'any)
2515 (or (todo-done-item-p) (looking-at "^$")))
2516 (let* ((item (or item (todo-item-string)))
2517 (marked (todo-marked-item-p))
2518 (cat (or cat (cond ((eq major-mode 'todo-mode)
2519 (todo-current-category))
2520 ((eq major-mode 'todo-filtered-items-mode)
2522 (concat todo-date-string-start
2524 "\\( " diary-time-regexp "\\)?"
2525 (regexp-quote todo-nondiary-end)
2526 "?\\(?1: \\[\\(.+:\\)?.+\\]\\)")))
2528 (re-search-forward regexp1 nil t)
2529 (match-string-no-properties 1)))))))
2531 (todo (cond ((or (eq arg 'raise) (eq arg 'lower)
2532 (eq major-mode 'todo-filtered-items-mode))
2534 (let ((curstart (todo-item-start))
2536 (goto-char (point-min))
2537 (while (looking-at todo-item-start)
2538 (setq count (1+ count))
2539 (when (= (point) curstart) (setq curnum count))
2540 (todo-forward-item))
2542 ((eq major-mode 'todo-mode)
2543 (todo-get-count 'todo cat))))
2544 (maxnum (if new (1+ todo) todo))
2545 (prompt (format "Set item priority (1-%d): " maxnum))
2546 (priority (cond ((and (not arg) (numberp current-prefix-arg))
2548 ((and (eq arg 'raise) (>= curnum 1))
2550 ((and (eq arg 'lower) (<= curnum maxnum))
2554 (unless (and priority
2555 (or (and (eq arg 'raise) (zerop priority))
2556 (and (eq arg 'lower) (> priority maxnum))))
2557 ;; When moving item to another category, show the category before
2558 ;; prompting for its priority.
2559 (unless (or arg (called-interactively-p 'any))
2560 (todo-category-number cat)
2561 ;; If done items in category are visible, keep them visible.
2562 (let ((done todo-show-with-done))
2563 (when (> (buffer-size) (- (point-max) (point-min)))
2565 (goto-char (point-min))
2566 (setq done (re-search-forward todo-done-string-start nil t))))
2567 (let ((todo-show-with-done done))
2568 ;; Keep current item or top of moved to category in view
2569 ;; while setting priority.
2570 (save-excursion (todo-category-select)))))
2571 ;; Prompt for priority only when the category has at least one
2574 (while (not priority)
2575 (setq candidate (read-number prompt
2576 (if (eq todo-default-priority 'first)
2578 (setq prompt (when (or (< candidate 1) (> candidate maxnum))
2579 (format "Priority must be an integer between 1 and %d.\n"
2581 (unless prompt (setq priority candidate))))
2582 ;; In Top Priorities buffer, an item's priority can be changed
2583 ;; wrt items in another category, but not wrt items in the same
2585 (when (eq major-mode 'todo-filtered-items-mode)
2586 (let* ((regexp2 (concat todo-date-string-start todo-date-pattern
2587 "\\( " diary-time-regexp "\\)?"
2588 (regexp-quote todo-nondiary-end)
2589 "?\\(?1:" (regexp-quote cat) "\\)"))
2590 (end (cond ((< curnum priority)
2591 (save-excursion (todo-item-end)))
2592 ((> curnum priority)
2593 (save-excursion (todo-item-start)))))
2594 (match (save-excursion
2595 (cond ((< curnum priority)
2596 (todo-forward-item (1+ (- priority curnum)))
2597 (when (re-search-backward regexp2 end t)
2598 (match-string-no-properties 1)))
2599 ((> curnum priority)
2600 (todo-backward-item (- curnum priority))
2601 (when (re-search-forward regexp2 end t)
2602 (match-string-no-properties 1)))))))
2604 (user-error (concat "Cannot reprioritize items from the same "
2605 "category in this mode, only in Todo mode")))))
2606 ;; Interactively or with non-nil ARG, relocate the item within its
2608 (when (or arg (called-interactively-p 'any))
2610 (goto-char (point-min))
2612 (unless (= priority 1)
2613 (todo-forward-item (1- priority))
2614 ;; When called from todo-item-undone and the highest priority
2615 ;; is chosen, this advances point to the first done item, so
2616 ;; move it up to the empty line above the done items
2618 (when (looking-back (concat "^"
2619 (regexp-quote todo-category-done)
2621 (line-beginning-position 0))
2622 (todo-backward-item))))
2623 (todo-insert-with-overlays item)
2624 ;; If item was marked, restore the mark.
2626 (let* ((ov (todo-get-overlay 'prefix))
2627 (pref (overlay-get ov 'before-string)))
2628 (overlay-put ov 'before-string
2629 (concat todo-item-mark pref))))))))
2631 (defun todo-raise-item-priority ()
2632 "Raise priority of current item by moving it up by one item."
2634 (todo-set-item-priority nil nil nil 'raise))
2636 (defun todo-lower-item-priority ()
2637 "Lower priority of current item by moving it down by one item."
2639 (todo-set-item-priority nil nil nil 'lower))
2641 (defun todo-move-item (&optional file)
2642 "Move at least one todo or done item to another category.
2643 If there are marked items, move all of these; otherwise, move
2646 With prefix argument FILE, prompt for a specific todo file and
2647 choose (with TAB completion) a category in it to move the item or
2648 items to; otherwise, choose and move to any category in either
2649 the current todo file or one of the files in
2650 `todo-category-completions-files'. If the chosen category is
2651 not an existing categories, then it is created and the item(s)
2652 become(s) the first entry/entries in that category.
2654 With moved todo items, prompt to set the priority in the category
2655 moved to (with multiple todo items, the one that had the highest
2656 priority in the category moved from gets the new priority and the
2657 rest of the moved todo items are inserted in sequence below it).
2658 Moved done items are appended to the top of the done items
2659 section in the category moved to."
2661 (let* ((cat1 (todo-current-category))
2662 (marked (assoc cat1 todo-categories-with-marks)))
2663 ;; Noop if point is not on an item and there are no marked items.
2664 (unless (and (looking-at "^$")
2666 (let* ((buffer-read-only)
2667 (file1 todo-current-todo-file)
2668 (num todo-category-number)
2669 (item (todo-item-string))
2670 (diary-item (todo-diary-item-p))
2671 (done-item (and (todo-done-item-p) (concat item "\n")))
2672 (omark (save-excursion (todo-item-start) (point-marker)))
2676 ov cat2 file2 moved nmark todo-items done-items)
2680 (setq ov (make-overlay (save-excursion (todo-item-start))
2681 (save-excursion (todo-item-end))))
2682 (overlay-put ov 'face 'todo-search))
2683 (let* ((pl (if (and marked (> (cdr marked) 1)) "s" ""))
2684 (cat+file (todo-read-category (concat "Move item" pl
2687 (while (and (equal (car cat+file) cat1)
2688 (equal (cdr cat+file) file1))
2689 (setq cat+file (todo-read-category
2690 "Choose a different category: ")))
2691 (setq cat2 (car cat+file)
2692 file2 (cdr cat+file))))
2693 (if ov (delete-overlay ov)))
2694 (set-buffer (find-buffer-visiting file1))
2697 (goto-char (point-min))
2699 (when (todo-marked-item-p)
2700 (if (todo-done-item-p)
2701 (setq done-items (concat done-items
2702 (todo-item-string) "\n")
2704 (setq todo-items (concat todo-items
2705 (todo-item-string) "\n")
2707 (when (todo-diary-item-p)
2708 (setq diary (1+ diary)))))
2709 (todo-forward-item))
2710 ;; Chop off last newline of multiple todo item string,
2711 ;; since it will be reinserted when setting priority
2712 ;; (but with done items priority is not set, so keep
2715 (setq todo-items (substring todo-items 0 -1))))
2716 (if (todo-done-item-p)
2719 (when (todo-diary-item-p) (setq diary 1))))
2720 (set-window-buffer (selected-window)
2721 (set-buffer (find-file-noselect file2 'nowarn)))
2724 (when (or todo-items (and item (not done-item)))
2725 (todo-set-item-priority (or todo-items item) cat2 t))
2726 ;; Move done items en bloc to top of done items section.
2727 (when (or done-items done-item)
2728 (todo-category-number cat2)
2730 (goto-char (point-min))
2732 (concat "^" (regexp-quote (concat todo-category-beg cat2))
2735 (concat "^" (regexp-quote todo-category-done)) nil t)
2737 (insert (or done-items done-item)))
2740 ;; Move succeeded, so remove item from starting category,
2741 ;; update item counts and display the category containing
2744 (setq nmark (point-marker))
2745 (when todo (todo-update-count 'todo todo))
2746 (when diary (todo-update-count 'diary diary))
2747 (when done (todo-update-count 'done done))
2748 (todo-update-categories-sexp)
2749 (with-current-buffer (find-buffer-visiting file1)
2758 (concat "^" (regexp-quote todo-category-beg)) nil t)
2761 (setq end (if (re-search-forward
2762 (concat "^" (regexp-quote
2763 todo-category-beg)) nil t)
2767 (while (< (point) end)
2768 (if (todo-marked-item-p)
2770 (todo-forward-item)))
2771 (setq todo-categories-with-marks
2772 (assq-delete-all cat1 todo-categories-with-marks)))
2773 (if ov (delete-overlay ov))
2774 (todo-remove-item))))
2775 (when todo (todo-update-count 'todo (- todo) cat1))
2776 (when diary (todo-update-count 'diary (- diary) cat1))
2777 (when done (todo-update-count 'done (- done) cat1))
2778 (todo-update-categories-sexp))
2779 (set-window-buffer (selected-window)
2780 (set-buffer (find-file-noselect file2 'nowarn)))
2781 (setq todo-category-number (todo-category-number cat2))
2782 (let ((todo-show-with-done (or done-items done-item)))
2783 (todo-category-select))
2785 ;; If item is moved to end of (just first?) category, make
2786 ;; sure the items above it are displayed in the window.
2788 ;; User quit before setting priority of todo item(s), so
2789 ;; return to starting category.
2791 (set-window-buffer (selected-window)
2792 (set-buffer (find-file-noselect file1 'nowarn)))
2793 (todo-category-number cat1)
2794 (todo-category-select)
2795 (goto-char omark))))))))
2797 (defun todo-item-done (&optional arg)
2798 "Tag a todo item in this category as done and relocate it.
2800 With prefix argument ARG prompt for a comment and append it to
2801 the done item; this is only possible if there are no marked
2802 items. If there are marked items, tag all of these with
2803 `todo-done-string' plus the current date and, if
2804 `todo-always-add-time-string' is non-nil, the current time;
2805 otherwise, just tag the item at point. Items tagged as done are
2806 relocated to the category's (by default hidden) done section. If
2807 done items are visible on invoking this command, they remain
2810 (let* ((cat (todo-current-category))
2811 (marked (assoc cat todo-categories-with-marks)))
2812 (when marked (todo--user-error-if-marked-done-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)
2833 ;; Don't add empty comment to done item.
2834 (setq comment (unless (zerop (length comment))
2835 (concat " [" todo-comment-string ": " comment "]")))
2836 (and marked (goto-char (point-min)))
2838 ;; Stop looping when we hit the empty line below the last
2839 ;; todo item (this is eobp if only done items are hidden).
2840 (while (not (looking-at "^$"))
2841 (if (or (not marked) (and marked (todo-marked-item-p)))
2843 (setq item (todo-item-string))
2844 (setq done-item (concat done-item done-prefix item
2845 comment (and marked "\n")))
2846 (setq item-count (1+ item-count))
2847 (when (todo-diary-item-p)
2848 (setq diary-count (1+ diary-count)))
2850 (unless marked (throw 'done nil)))
2851 (todo-forward-item))))
2853 ;; Chop off last newline of done item string.
2854 (setq done-item (substring done-item 0 -1))
2855 (setq todo-categories-with-marks
2856 (assq-delete-all cat todo-categories-with-marks)))
2860 (concat "^" (regexp-quote todo-category-done)) nil t)
2862 (when show-done (setq opoint (point)))
2863 (insert done-item "\n"))
2864 (todo-update-count 'todo (- item-count))
2865 (todo-update-count 'done item-count)
2866 (todo-update-count 'diary (- diary-count))
2867 (todo-update-categories-sexp)
2868 (let ((todo-show-with-done show-done))
2869 (todo-category-select)
2870 ;; When done items are visible, put point at the top of the
2871 ;; done items section. When done items are hidden, restore
2872 ;; point to its location prior to invoking this command.
2873 (when opoint (goto-char opoint)))))))
2875 (defun todo-item-undone ()
2876 "Restore at least one done item to this category's todo section.
2877 Prompt for the new priority. If there are marked items, undo all
2878 of these, giving the first undone item the new priority and the
2879 rest following directly in sequence; otherwise, undo just the
2882 If the done item has a comment, ask whether to omit the comment
2883 from the restored item. With multiple marked done items with
2884 comments, only ask once, and if affirmed, omit subsequent
2885 comments without asking."
2887 (let* ((cat (todo-current-category))
2888 (marked (assoc cat todo-categories-with-marks))
2889 (pl (if (and marked (> (cdr marked) 1)) "s" "")))
2890 (when (or marked (todo-done-item-p))
2891 (let ((buffer-read-only)
2893 (omark (point-marker))
2897 start end item ov npoint undone)
2898 (and marked (goto-char (point-min)))
2901 (when (or (not marked) (and marked (todo-marked-item-p)))
2902 (if (not (todo-done-item-p))
2905 (user-error "Only done items can be undone"))
2908 (setq ov (make-overlay (save-excursion (todo-item-start))
2909 (save-excursion (todo-item-end))))
2910 (overlay-put ov 'face 'todo-search))
2911 ;; Find the end of the date string added upon tagging item as
2913 (setq start (search-forward "] "))
2914 (setq item-count (1+ item-count))
2915 (unless (looking-at (regexp-quote todo-nondiary-start))
2916 (setq diary-count (1+ diary-count)))
2917 (setq end (save-excursion (todo-item-end)))
2918 ;; Ask (once) whether to omit done item's comment. If
2919 ;; affirmed, omit subsequent comments without asking.
2920 (when (re-search-forward
2921 (concat " \\[" (regexp-quote todo-comment-string)
2922 ": [^]]+\\]") end t)
2924 (if (eq first 'first)
2926 (if (eq todo-undo-item-omit-comment 'ask)
2927 (when (todo-y-or-n-p
2928 (concat "Omit comment" pl
2929 " from restored item"
2932 (when todo-undo-item-omit-comment 'omit)))
2934 (when (and (eq first 'first) ov) (delete-overlay ov)))
2935 (when (eq first 'omit)
2936 (setq end (match-beginning 0))))
2937 (setq item (concat item
2938 (buffer-substring-no-properties start end)
2939 (when marked "\n")))
2940 (unless marked (throw 'done nil))))
2941 (todo-forward-item)))
2944 ;; Chop off last newline of multiple items string, since
2945 ;; it will be reinserted on setting priority.
2946 (and marked (setq item (substring item 0 -1)))
2947 (todo-set-item-priority item cat t)
2948 (setq npoint (point))
2950 (when ov (delete-overlay ov))
2957 (concat "^" (regexp-quote todo-category-done)) nil t)
2959 (if (todo-marked-item-p)
2961 (todo-forward-item)))
2962 (setq todo-categories-with-marks
2963 (assq-delete-all cat todo-categories-with-marks)))
2966 (todo-update-count 'todo item-count)
2967 (todo-update-count 'done (- item-count))
2968 (when diary-count (todo-update-count 'diary diary-count))
2969 (todo-update-categories-sexp)
2970 (let ((todo-show-with-done (> (todo-get-count 'done) 0)))
2971 (todo-category-select))
2972 ;; Put cursor on undone item.
2973 (goto-char npoint)))
2974 (set-marker omark nil)))))
2976 ;; -----------------------------------------------------------------------------
2977 ;;; Done item archives
2978 ;; -----------------------------------------------------------------------------
2980 (defun todo-find-archive (&optional ask)
2981 "Visit the archive of the current todo category, if it exists.
2982 If the category has no archived items, prompt to visit the
2983 archive anyway. If there is no archive for this file or with
2984 non-nil argument ASK, prompt to visit another archive.
2986 The buffer showing the archive is in Todo Archive mode. The
2987 first visit in a session displays the first category in the
2988 archive, subsequent visits return to the last category
2991 (if (null (funcall todo-files-function t))
2992 (message "There are no archive files")
2993 (let* ((cat (todo-current-category))
2994 (count (todo-get-count 'archived cat))
2995 (archive (concat (file-name-sans-extension todo-current-todo-file)
2997 (place (cond (ask 'other-archive)
2998 ((file-exists-p archive) 'this-archive)
2999 (t (when (todo-y-or-n-p
3000 (concat "This file has no archive; "
3001 "visit another archive? "))
3003 (when (eq place 'other-archive)
3004 (setq archive (todo-read-file-name "Choose a todo archive: " t t)))
3005 (when (and (eq place 'this-archive) (zerop count))
3006 (setq place (when (todo-y-or-n-p
3007 (concat "This category has no archived items;"
3008 " visit archive anyway? "))
3011 (set-window-buffer (selected-window)
3012 (set-buffer (find-file-noselect archive)))
3013 (unless (derived-mode-p 'todo-archive-mode) (todo-archive-mode))
3014 (if (member place '(other-archive other-cat))
3015 (setq todo-category-number 1)
3016 (todo-category-number cat))
3017 (todo-category-select)))))
3019 (defun todo-choose-archive ()
3020 "Choose an archive and visit it."
3022 (todo-find-archive t))
3024 (defun todo-archive-done-item (&optional all)
3025 "Archive at least one done item in this category.
3027 With prefix argument ALL, prompt whether to archive all done
3028 items in this category and on confirmation archive them.
3029 Otherwise, if there are marked done items (and no marked todo
3030 items), archive all of these; otherwise, archive the done item at
3033 If the archive of this file does not exist, it is created. If
3034 this category does not exist in the archive, it is created."
3036 (when (eq major-mode 'todo-mode)
3037 (if (and all (zerop (todo-get-count 'done)))
3038 (message "No done items in this category")
3040 (let* ((cat (todo-current-category))
3041 (tbuf (current-buffer))
3042 (marked (assoc cat todo-categories-with-marks))
3043 (afile (concat (file-name-sans-extension
3044 todo-current-todo-file) ".toda"))
3045 (archive (find-file-noselect afile t))
3046 (item (and (not marked) (todo-done-item-p)
3047 (concat (todo-item-string) "\n")))
3049 (opoint (unless (todo-done-item-p) (point)))
3050 marked-items beg end all-done
3054 (if (todo-y-or-n-p "Archive all done items in this category? ")
3057 (goto-char (point-min))
3060 (re-search-forward todo-done-string-start
3062 (match-beginning 0))
3063 end (if (re-search-forward
3065 (regexp-quote todo-category-beg))
3069 all-done (buffer-substring-no-properties beg end)
3070 count (todo-get-count 'done))
3071 ;; Restore starting point, unless it was on a done
3072 ;; item, since they will all be deleted.
3073 (when opoint (goto-char opoint))))
3077 (goto-char (point-min))
3079 (when (todo-marked-item-p)
3080 (if (not (todo-done-item-p))
3081 (throw 'end (message "Only done items can be archived"))
3083 (concat marked-items (todo-item-string) "\n"))
3084 (setq count (1+ count))))
3085 (todo-forward-item)))))
3086 (if (not (or marked all item))
3087 (throw 'end (message "Only done items can be archived"))
3088 (with-current-buffer archive
3089 (unless (derived-mode-p 'todo-archive-mode) (todo-archive-mode))
3090 (let (buffer-read-only)
3092 (goto-char (point-min))
3093 (if (and (re-search-forward
3094 (concat "^" (regexp-quote
3095 (concat todo-category-beg cat)) "$")
3097 (re-search-forward (regexp-quote todo-category-done)
3099 ;; Start of done items section in existing category.
3101 (todo-add-category nil cat)
3102 ;; Start of done items section in new category.
3103 (goto-char (point-max)))
3104 (insert (cond (marked marked-items)
3107 (todo-update-count 'done (if (or marked all) count 1) cat)
3108 (todo-update-categories-sexp)
3109 ;; If archive is new, save to file now (with
3110 ;; write-region to avoid prompt for file to save to)
3111 ;; to update todo-archives, and set the mode for
3112 ;; visiting the archive below.
3113 (unless (nth 7 (file-attributes afile))
3114 (write-region nil nil afile t t)
3115 (setq todo-archives (funcall todo-files-function t))
3116 (todo-archive-mode))))
3117 (with-current-buffer tbuf
3122 ;; Make sure done items are accessible.
3124 (remove-overlays beg end)
3125 (delete-region beg end)
3126 (todo-update-count 'done (- count))
3127 (todo-update-count 'archived count))))
3129 ;; If we're archiving all done items, can't
3130 ;; first archive item point was on, since
3131 ;; that will short-circuit the rest.
3132 (and item (not all)))
3133 (and marked (goto-char (point-min)))
3136 (if (or (and marked (todo-marked-item-p)) item)
3139 (todo-update-count 'done -1)
3140 (todo-update-count 'archived 1)
3141 ;; Don't leave point below last item.
3142 (and (or marked item) (bolp) (eolp)
3143 (< (point-min) (point-max))
3144 (todo-backward-item))
3146 (throw 'done (setq item nil))))
3147 (todo-forward-item))))))
3149 (setq todo-categories-with-marks
3150 (assq-delete-all cat todo-categories-with-marks)))
3151 (todo-update-categories-sexp)
3152 (todo-prefix-overlays)))
3154 (todo-category-number cat)
3155 (todo-category-select)
3156 (split-window-below)
3157 (set-window-buffer (selected-window) tbuf)
3158 ;; Make todo file current to select category.
3159 (find-file (buffer-file-name tbuf))
3160 ;; Make sure done item separator is hidden (if done items
3161 ;; were initially visible).
3162 (let (todo-show-with-done) (todo-category-select)))))))
3164 (defun todo-unarchive-items ()
3165 "Unarchive at least one item in this archive category.
3166 If there are marked items, unarchive all of these; otherwise,
3167 unarchive the item at point.
3169 Unarchived items are restored as done items to the corresponding
3170 category in the todo file, inserted at the top of done items
3171 section. If all items in the archive category have been
3172 restored, the category is deleted from the archive. If this was
3173 the only category in the archive, the archive file is deleted."
3175 (when (eq major-mode 'todo-archive-mode)
3176 (let* ((cat (todo-current-category))
3177 (tbuf (find-file-noselect
3178 (concat (file-name-sans-extension todo-current-todo-file)
3180 (marked (assoc cat todo-categories-with-marks))
3181 (item (concat (todo-item-string) "\n"))
3187 (goto-char (point-min))
3189 (when (todo-marked-item-p)
3190 (setq marked-items (concat marked-items (todo-item-string) "\n"))
3191 (setq marked-count (1+ marked-count)))
3192 (todo-forward-item))))
3193 ;; Restore items to top of category's done section and update counts.
3194 (with-current-buffer tbuf
3195 (let (buffer-read-only newcat)
3197 (goto-char (point-min))
3198 ;; Find the corresponding todo category, or if there isn't
3200 (unless (re-search-forward
3201 (concat "^" (regexp-quote (concat todo-category-beg cat))
3203 (todo-add-category nil cat)
3205 ;; Go to top of category's done section.
3207 (concat "^" (regexp-quote todo-category-done)) nil t)
3210 (insert marked-items)
3211 (todo-update-count 'done marked-count cat)
3212 (unless newcat ; Newly added category has no archive.
3213 (todo-update-count 'archived (- marked-count) cat)))
3216 (todo-update-count 'done 1 cat)
3217 (unless newcat ; Newly added category has no archive.
3218 (todo-update-count 'archived -1 cat))))
3219 (todo-update-categories-sexp)))
3220 ;; Delete restored items from archive.
3223 (goto-char (point-min)))
3226 (if (or (todo-marked-item-p) item)
3230 (throw 'done (setq item nil))))
3231 (todo-forward-item))))
3232 (todo-update-count 'done (if marked (- marked-count) -1) cat)
3233 ;; If we unarchived the last item in category, then if that was
3234 ;; the only category, delete the whole file, otherwise, just
3235 ;; delete the category.
3236 (when (= 0 (todo-get-count 'done))
3237 (if (= 1 (length todo-categories))
3239 (delete-file todo-current-todo-file)
3240 ;; Kill the archive buffer silently.
3241 (set-buffer-modified-p nil)
3244 (let ((beg (re-search-backward
3245 (concat "^" (regexp-quote todo-category-beg) cat "$")
3247 (end (if (re-search-forward
3248 (concat "^" (regexp-quote todo-category-beg))
3252 (remove-overlays beg end)
3253 (delete-region beg end)
3254 (setq todo-categories (delete (assoc cat todo-categories)
3255 todo-categories)))))
3256 (todo-update-categories-sexp)
3257 ;; Visit category in todo file and show restored done items.
3258 (let ((tfile (buffer-file-name tbuf))
3259 (todo-show-with-done t))
3260 (set-window-buffer (selected-window)
3261 (set-buffer (find-file-noselect tfile)))
3262 (todo-category-number cat)
3263 (todo-category-select)
3264 (message "Items unarchived.")))))
3266 (defun todo-jump-to-archive-category (&optional file)
3267 "Prompt for a category in a todo archive and jump to it.
3268 With prefix argument FILE, prompt for an archive and choose (with
3269 TAB completion) a category in it to jump to; otherwise, choose
3270 and jump to any category in the current archive."
3272 (todo-jump-to-category file 'archive))
3274 ;; -----------------------------------------------------------------------------
3275 ;;; Displaying and sorting tables of categories
3276 ;; -----------------------------------------------------------------------------
3278 (defcustom todo-categories-category-label "Category"
3279 "Category button label in Todo Categories mode."
3281 :group 'todo-categories)
3283 (defcustom todo-categories-todo-label "Todo"
3284 "Todo button label in Todo Categories mode."
3286 :group 'todo-categories)
3288 (defcustom todo-categories-diary-label "Diary"
3289 "Diary button label in Todo Categories mode."
3291 :group 'todo-categories)
3293 (defcustom todo-categories-done-label "Done"
3294 "Done button label in Todo Categories mode."
3296 :group 'todo-categories)
3298 (defcustom todo-categories-archived-label "Archived"
3299 "Archived button label in Todo Categories mode."
3301 :group 'todo-categories)
3303 (defcustom todo-categories-totals-label "Totals"
3304 "String to label total item counts in Todo Categories mode."
3306 :group 'todo-categories)
3308 (defcustom todo-categories-number-separator " | "
3309 "String between number and category in Todo Categories mode.
3310 This separates the number from the category name in the default
3311 categories display according to priority."
3313 :group 'todo-categories)
3315 (defcustom todo-categories-align 'center
3316 "Alignment of category names in Todo Categories mode."
3317 :type '(radio (const left) (const center) (const right))
3318 :group 'todo-categories)
3320 (defun todo-show-categories-table ()
3321 "Display a table of the current file's categories and item counts.
3323 In the initial display the lines of the table are numbered,
3324 indicating the current order of the categories when sequentially
3325 navigating through the todo file with `\\[todo-forward-category]'
3326 and `\\[todo-backward-category]'. You can reorder the lines, and
3327 hence the category sequence, by typing `\\[todo-raise-category]'
3328 or `\\[todo-lower-category]' to raise or lower the category at
3329 point, or by typing `\\[todo-set-category-number]' and entering a
3330 number at the prompt or by typing `\\[todo-set-category-number]'
3331 with a numeric prefix. If you save the todo file after
3332 reordering the categories, the new order persists in subsequent
3335 The labels above the category names and item counts are buttons,
3336 and clicking these changes the display: sorted by category name
3337 or by the respective item counts (alternately descending or
3338 ascending). In these displays the categories are not numbered
3339 and `\\[todo-set-category-number]', `\\[todo-raise-category]' and
3340 `\\[todo-lower-category]' are disabled. (Programmatically, the
3341 sorting is triggered by passing a non-nil SORTKEY argument.)
3343 In addition, the lines with the category names and item counts
3344 are buttonized, and pressing one of these button jumps to the
3345 category in Todo mode (or Todo Archive mode, for categories
3346 containing only archived items, provided user option
3347 `todo-skip-archived-categories' is non-nil. These categories
3348 are shown in `todo-archived-only' face."
3350 (todo-display-categories)
3352 (todo-update-categories-display sortkey)))
3354 (defun todo-next-button (n)
3355 "Move point to the Nth next button in the table of categories."
3357 (forward-button n 'wrap 'display-message)
3358 (and (bolp) (button-at (point))
3359 ;; Align with beginning of category label.
3360 (forward-char (+ 4 (length todo-categories-number-separator)))))
3362 (defun todo-previous-button (n)
3363 "Move point to the Nth previous button in the table of categories."
3365 (backward-button n 'wrap 'display-message)
3366 (and (bolp) (button-at (point))
3367 ;; Align with beginning of category label.
3368 (forward-char (+ 4 (length todo-categories-number-separator)))))
3370 (defun todo-set-category-number (&optional arg)
3371 "Change number of category at point in the table of categories.
3373 With ARG nil, prompt for the new number. Alternatively, the
3374 enter the new number with numerical prefix ARG. Otherwise, if
3375 ARG is either of the symbols `raise' or `lower', raise or lower
3376 the category line in the table by one, respectively, thereby
3377 decreasing or increasing its number."
3379 (let ((curnum (save-excursion
3380 ;; Get the number representing the priority of the category
3381 ;; on the current line.
3382 (forward-line 0) (skip-chars-forward " ") (number-at-point))))
3383 (when curnum ; Do nothing if we're not on a category line.
3384 (let* ((maxnum (length todo-categories))
3385 (prompt (format "Set category priority (1-%d): " maxnum))
3386 (col (current-column))
3387 (buffer-read-only nil)
3388 (priority (cond ((and (eq arg 'raise) (> curnum 1))
3390 ((and (eq arg 'lower) (< curnum maxnum))
3393 (while (not priority)
3394 (setq candidate (or arg (read-number prompt)))
3397 (cond ((or (< candidate 1) (> candidate maxnum))
3398 (format "Priority must be an integer between 1 and %d: "
3400 ((= candidate curnum)
3401 "Choose a different priority than the current one: ")))
3402 (unless prompt (setq priority candidate)))
3403 (let* ((lower (< curnum priority)) ; Priority is being lowered.
3404 (head (butlast todo-categories
3405 (apply (if lower 'identity '1+)
3406 (list (- maxnum priority)))))
3407 (tail (nthcdr (apply (if lower 'identity '1-) (list priority))
3409 ;; Category's name and items counts list.
3410 (catcons (nth (1- curnum) todo-categories))
3411 (todo-categories (nconc head (list catcons) tail))
3413 (when lower (setq todo-categories (nreverse todo-categories)))
3414 (setq todo-categories (delete-dups todo-categories))
3415 (when lower (setq todo-categories (nreverse todo-categories)))
3416 (setq newcats todo-categories)
3418 (with-current-buffer (find-buffer-visiting todo-current-todo-file)
3419 (setq todo-categories newcats)
3420 (todo-update-categories-sexp))
3421 (todo-show-categories-table)
3422 (forward-line (1+ priority))
3423 (forward-char col))))))
3425 (defun todo-raise-category ()
3426 "Raise priority of category at point in the table of categories."
3428 (todo-set-category-number 'raise))
3430 (defun todo-lower-category ()
3431 "Lower priority of category at point in the table of categories."
3433 (todo-set-category-number 'lower))
3435 (defun todo-sort-categories-alphabetically-or-numerically ()
3436 "Sort table of categories alphabetically or numerically."
3439 (goto-char (point-min))
3441 (if (member 'alpha todo-descending-counts)
3443 (todo-update-categories-display nil)
3444 (setq todo-descending-counts
3445 (delete 'alpha todo-descending-counts)))
3446 (todo-update-categories-display 'alpha))))
3448 (defun todo-sort-categories-by-todo ()
3449 "Sort table of categories by number of todo items."
3452 (goto-char (point-min))
3454 (todo-update-categories-display 'todo)))
3456 (defun todo-sort-categories-by-diary ()
3457 "Sort table of categories by number of diary items."
3460 (goto-char (point-min))
3462 (todo-update-categories-display 'diary)))
3464 (defun todo-sort-categories-by-done ()
3465 "Sort table of categories by number of non-archived done items."
3468 (goto-char (point-min))
3470 (todo-update-categories-display 'done)))
3472 (defun todo-sort-categories-by-archived ()
3473 "Sort table of categories by number of archived items."
3476 (goto-char (point-min))
3478 (todo-update-categories-display 'archived)))
3480 (defvar todo-categories-buffer "*Todo Categories*"
3481 "Name of buffer in Todo Categories mode.")
3483 (defun todo-longest-category-name-length (categories)
3484 "Return the length of the longest name in list CATEGORIES."
3486 (dolist (c categories longest)
3487 (setq longest (max longest (length c))))))
3489 (defun todo-adjusted-category-label-length ()
3490 "Return adjusted length of category label button.
3491 The adjustment ensures proper tabular alignment in Todo
3493 (let* ((categories (mapcar 'car todo-categories))
3494 (longest (todo-longest-category-name-length categories))
3495 (catlablen (length todo-categories-category-label))
3496 (lc-diff (- longest catlablen)))
3497 (if (and (natnump lc-diff) (cl-oddp lc-diff))
3499 (max longest catlablen))))
3501 (defun todo-padded-string (str)
3502 "Return category name or label string STR padded with spaces.
3503 The placement of the padding is determined by the value of user
3504 option `todo-categories-align'."
3505 (let* ((len (todo-adjusted-category-label-length))
3506 (strlen (length str))
3507 (strlen-odd (eq (logand strlen 1) 1))
3508 (padding (max 0 (/ (- len strlen) 2)))
3509 (padding-left (cond ((eq todo-categories-align 'left) 0)
3510 ((eq todo-categories-align 'center) padding)
3511 ((eq todo-categories-align 'right)
3512 (if strlen-odd (1+ (* padding 2)) (* padding 2)))))
3513 (padding-right (cond ((eq todo-categories-align 'left)
3514 (if strlen-odd (1+ (* padding 2)) (* padding 2)))
3515 ((eq todo-categories-align 'center)
3516 (if strlen-odd (1+ padding) padding))
3517 ((eq todo-categories-align 'right) 0))))
3518 (concat (make-string padding-left 32) str (make-string padding-right 32))))
3520 (defvar todo-descending-counts nil
3521 "List of keys for category counts sorted in descending order.")
3523 (defun todo-sort (list &optional key)
3524 "Return a copy of LIST, possibly sorted according to KEY."
3525 (let* ((l (copy-sequence list))
3526 (fn (if (eq key 'alpha)
3527 (lambda (x) (upcase x)) ; Alphabetize case insensitively.
3528 (lambda (x) (todo-get-count key x))))
3529 ;; Keep track of whether the last sort by key was descending or
3531 (descending (member key todo-descending-counts))
3532 (cmp (if (eq key 'alpha)
3534 (if descending '< '>)))
3535 (pred (lambda (s1 s2) (let ((t1 (funcall fn (car s1)))
3536 (t2 (funcall fn (car s2))))
3537 (funcall cmp t1 t2)))))
3539 (setq l (sort l pred))
3540 ;; Switch between descending and ascending sort order.
3542 (setq todo-descending-counts
3543 (delete key todo-descending-counts))
3544 (push key todo-descending-counts)))
3547 (defun todo-display-sorted (type)
3548 "Keep point on the TYPE count sorting button just clicked."
3549 (let ((opoint (point)))
3550 (todo-update-categories-display type)
3551 (goto-char opoint)))
3553 (defun todo-label-to-key (label)
3554 "Return symbol for sort key associated with LABEL."
3556 (cond ((string= label todo-categories-category-label)
3558 ((string= label todo-categories-todo-label)
3560 ((string= label todo-categories-diary-label)
3562 ((string= label todo-categories-done-label)
3564 ((string= label todo-categories-archived-label)
3565 (setq key 'archived)))
3568 (defun todo-insert-sort-button (label)
3569 "Insert button for displaying categories sorted by item counts.
3570 LABEL determines which type of count is sorted."
3571 (let* ((str (if (string= label todo-categories-category-label)
3572 (todo-padded-string label)
3575 (end (+ beg (length str)))
3577 (insert-button str 'face nil
3580 (let ((key (todo-label-to-key ,label)))
3581 (if (and (member key todo-descending-counts)
3584 ;; If display is alphabetical, switch back to
3585 ;; category priority order.
3586 (todo-display-sorted nil)
3587 (setq todo-descending-counts
3588 (delete key todo-descending-counts)))
3589 (todo-display-sorted key)))))
3590 (setq ov (make-overlay beg end))
3591 (overlay-put ov 'face 'todo-button)))
3593 (defun todo-total-item-counts ()
3594 "Return a list of total item counts for the current file."
3595 (mapcar (lambda (i) (apply '+ (mapcar (lambda (l) (aref l i))
3596 (mapcar 'cdr todo-categories))))
3599 (defvar todo-categories-category-number 0
3600 "Variable for numbering categories in Todo Categories mode.")
3602 (defun todo-insert-category-line (cat &optional nonum)
3603 "Insert button with category CAT's name and item counts.
3604 With non-nil argument NONUM show only these; otherwise, insert a
3605 number in front of the button indicating the category's priority.
3606 The number and the category name are separated by the string
3607 which is the value of the user option
3608 `todo-categories-number-separator'."
3609 (let ((archive (member todo-current-todo-file todo-archives))
3610 (num todo-categories-category-number)
3611 (str (todo-padded-string cat))
3613 (setq num (1+ num) todo-categories-category-number num)
3616 (make-string (+ 4 (length todo-categories-number-separator))
3618 (format " %3d%s" num todo-categories-number-separator))
3620 (mapconcat (lambda (elt)
3622 (make-string (1+ (/ (length (car elt)) 2)) 32) ; label
3623 (format "%3d" (todo-get-count (cdr elt) cat)) ; count
3624 ;; Add an extra space if label length is odd.
3625 (when (cl-oddp (length (car elt))) " ")))
3627 (list (cons todo-categories-done-label 'done))
3628 (list (cons todo-categories-todo-label 'todo)
3629 (cons todo-categories-diary-label 'diary)
3630 (cons todo-categories-done-label 'done)
3631 (cons todo-categories-archived-label
3634 " ") ; Make highlighting on last column look better.
3635 'face (if (and todo-skip-archived-categories
3636 (zerop (todo-get-count 'todo cat))
3637 (zerop (todo-get-count 'done cat))
3638 (not (zerop (todo-get-count 'archived cat))))
3641 'action `(lambda (button) (let ((buf (current-buffer)))
3642 (todo-jump-to-category nil ,cat)
3643 (kill-buffer buf))))
3644 ;; Highlight the sorted count column.
3645 (let* ((beg (+ opoint 7 (length str)))
3647 (cond ((eq nonum 'todo)
3648 (setq beg (+ beg 1 (/ (length todo-categories-todo-label) 2))))
3650 (setq beg (+ beg 1 (length todo-categories-todo-label)
3651 2 (/ (length todo-categories-diary-label) 2))))
3653 (setq beg (+ beg 1 (length todo-categories-todo-label)
3654 2 (length todo-categories-diary-label)
3655 2 (/ (length todo-categories-done-label) 2))))
3656 ((eq nonum 'archived)
3657 (setq beg (+ beg 1 (length todo-categories-todo-label)
3658 2 (length todo-categories-diary-label)
3659 2 (length todo-categories-done-label)
3660 2 (/ (length todo-categories-archived-label) 2)))))
3661 (unless (= beg (+ opoint 7 (length str))) ; Don't highlight categories.
3662 (setq end (+ beg 4))
3663 (setq ovl (make-overlay beg end))
3664 (overlay-put ovl 'face 'todo-sorted-column)))
3667 (defun todo-display-categories ()
3668 "Prepare buffer for displaying table of categories and item counts."
3669 (unless (eq major-mode 'todo-categories-mode)
3670 (setq todo-global-current-todo-file
3671 (or todo-current-todo-file
3672 (todo-absolute-file-name todo-default-todo-file)))
3673 (set-window-buffer (selected-window)
3674 (set-buffer (get-buffer-create todo-categories-buffer)))
3675 (kill-all-local-variables)
3676 (todo-categories-mode)
3677 (let ((archive (member todo-current-todo-file todo-archives))
3680 (insert (format (concat "Category counts for todo "
3681 (if archive "archive" "file")
3683 (todo-short-file-name todo-current-todo-file)))
3685 ;; Make space for the column of category numbers.
3686 (insert (make-string (+ 4 (length todo-categories-number-separator)) 32))
3687 ;; Add the category and item count buttons (if this is the list of
3688 ;; categories in an archive, show only done item counts).
3689 (todo-insert-sort-button todo-categories-category-label)
3692 (insert (make-string 3 32))
3693 (todo-insert-sort-button todo-categories-done-label))
3694 (insert (make-string 3 32))
3695 (todo-insert-sort-button todo-categories-todo-label)
3696 (insert (make-string 2 32))
3697 (todo-insert-sort-button todo-categories-diary-label)
3698 (insert (make-string 2 32))
3699 (todo-insert-sort-button todo-categories-done-label)
3700 (insert (make-string 2 32))
3701 (todo-insert-sort-button todo-categories-archived-label))
3704 (defun todo-update-categories-display (sortkey)
3705 "Populate table of categories and sort by SORTKEY."
3706 (let* ((cats0 todo-categories)
3707 (cats (todo-sort cats0 sortkey))
3708 (archive (member todo-current-todo-file todo-archives))
3709 (todo-categories-category-number 0)
3710 ;; Find start of Category button if we just entered Todo Categories
3712 (pt (if (eq (point) (point-max))
3715 (goto-char (next-single-char-property-change
3716 (point) 'face nil (line-end-position))))))
3719 (delete-region (point) (point-max))
3720 ;; Fill in the table with buttonized lines, each showing a category and
3722 (mapc (lambda (cat) (todo-insert-category-line cat sortkey))
3725 ;; Add a line showing item count totals.
3726 (insert (make-string (+ 4 (length todo-categories-number-separator)) 32)
3727 (todo-padded-string todo-categories-totals-label)
3731 (make-string (1+ (/ (length (car elt)) 2)) 32)
3732 (format "%3d" (nth (cdr elt) (todo-total-item-counts)))
3733 ;; Add an extra space if label length is odd.
3734 (when (cl-oddp (length (car elt))) " ")))
3736 (list (cons todo-categories-done-label 2))
3737 (list (cons todo-categories-todo-label 0)
3738 (cons todo-categories-diary-label 1)
3739 (cons todo-categories-done-label 2)
3740 (cons todo-categories-archived-label 3)))
3742 ;; Put cursor on Category button initially.
3743 (if pt (goto-char pt))
3744 (setq buffer-read-only t)))
3746 ;; -----------------------------------------------------------------------------
3747 ;;; Searching and item filtering
3748 ;; -----------------------------------------------------------------------------
3750 (defun todo-search ()
3751 "Search for a regular expression in this todo file.
3752 The search runs through the whole file and encompasses all and
3753 only todo and done items; it excludes category names. Multiple
3754 matches are shown sequentially, highlighted in `todo-search'
3757 (let ((regex (read-from-minibuffer "Enter a search string (regexp): "))
3759 matches match cat in-done ov mlen msg)
3761 (goto-char (point-min))
3763 (setq match (re-search-forward regex nil t))
3764 (goto-char (line-beginning-position))
3765 (unless (or (equal (point) 1)
3766 (looking-at (concat "^" (regexp-quote todo-category-beg))))
3767 (if match (push match matches)))
3769 (setq matches (reverse matches))
3773 (setq match (pop matches))
3776 (when (looking-at todo-done-string-start)
3778 (re-search-backward (concat "^" (regexp-quote todo-category-beg)
3779 "\\(.*\\)\n") nil t)
3780 (setq cat (match-string-no-properties 1))
3781 (todo-category-number cat)
3782 (todo-category-select)
3784 (unless todo-show-with-done (todo-toggle-view-done-items)))
3786 (setq ov (make-overlay (- (point) (length regex)) (point)))
3787 (overlay-put ov 'face 'todo-search)
3789 (setq mlen (length matches))
3792 (format "There are %d more matches; go to next match? "
3794 "There is one more match; go to it? "))
3796 (throw 'stop (setq msg (if (> mlen 1)
3797 (format "There are %d more matches."
3799 "There is one more match."))))))
3800 (setq msg "There are no more matches."))
3801 (todo-category-select)
3803 (message "No match for \"%s\"" regex))
3805 (if (todo-y-or-n-p (concat msg "\nUnhighlight matches? "))
3806 (todo-clear-matches)
3807 (message "You can unhighlight the matches later by typing %s"
3808 (key-description (car (where-is-internal
3809 'todo-clear-matches))))))))
3811 (defun todo-clear-matches ()
3812 "Remove highlighting on matches found by todo-search."
3814 (remove-overlays 1 (1+ (buffer-size)) 'face 'todo-search))
3816 (defcustom todo-top-priorities-overrides nil
3817 "List of rules specifying number of top priority items to show.
3818 These rules override `todo-top-priorities' on invocations of
3819 `\\[todo-filter-top-priorities]' and
3820 `\\[todo-filter-top-priorities-multifile]'. Each rule is a list
3821 of the form (FILE NUM ALIST), where FILE is a member of
3822 `todo-files', NUM is a number specifying the default number of
3823 top priority items for each category in that file, and ALIST,
3824 when non-nil, consists of conses of a category name in FILE and a
3825 number specifying the default number of top priority items in
3826 that category, which overrides NUM.
3828 This variable should be set interactively by
3829 `\\[todo-set-top-priorities-in-file]' or
3830 `\\[todo-set-top-priorities-in-category]'."
3832 :group 'todo-filtered)
3834 (defcustom todo-top-priorities 1
3835 "Default number of top priorities shown by `todo-filter-top-priorities'."
3837 :group 'todo-filtered)
3839 (defcustom todo-filter-files nil
3840 "List of default files for multifile item filtering."
3841 :type `(set ,@(mapcar (lambda (f) (list 'const f))
3842 (mapcar 'todo-short-file-name
3843 (funcall todo-files-function))))
3844 :group 'todo-filtered)
3846 (defcustom todo-filter-done-items nil
3847 "Non-nil to include done items when processing regexp filters.
3848 Done items from corresponding archive files are also included."
3850 :group 'todo-filtered)
3852 (defun todo-set-top-priorities-in-file ()
3853 "Set number of top priorities for this file.
3854 See `todo-set-top-priorities' for more details."
3856 (todo-set-top-priorities))
3858 (defun todo-set-top-priorities-in-category ()
3859 "Set number of top priorities for this category.
3860 See `todo-set-top-priorities' for more details."
3862 (todo-set-top-priorities t))
3864 (defun todo-filter-top-priorities (&optional arg)
3865 "Display a list of top priority items from different categories.
3866 The categories can be any of those in the current todo file.
3868 With numerical prefix ARG show at most ARG top priority items
3869 from each category. With `C-u' as prefix argument show the
3870 numbers of top priority items specified by category in
3871 `todo-top-priorities-overrides', if this has an entry for the file(s);
3872 otherwise show `todo-top-priorities' items per category in the
3873 file(s). With no prefix argument, if a top priorities file for
3874 the current todo file has previously been saved (see
3875 `todo-save-filtered-items-buffer'), visit this file; if there is
3876 no such file, build the list as with prefix argument `C-u'.
3878 The prefix ARG regulates how many top priorities from
3879 each category to show, as described above."
3881 (todo-filter-items 'top arg))
3883 (defun todo-filter-top-priorities-multifile (&optional arg)
3884 "Display a list of top priority items from different categories.
3885 The categories are a subset of the categories in the files listed
3886 in `todo-filter-files', or if this nil, in the files chosen from
3887 a file selection dialog that pops up in this case.
3889 With numerical prefix ARG show at most ARG top priority items
3890 from each category in each file. With `C-u' as prefix argument
3891 show the numbers of top priority items specified in
3892 `todo-top-priorities-overrides', if this is non-nil; otherwise show
3893 `todo-top-priorities' items per category. With no prefix
3894 argument, if a top priorities file for the chosen todo files
3895 exists (see `todo-save-filtered-items-buffer'), visit this file;
3896 if there is no such file, do the same as with prefix argument
3899 (todo-filter-items 'top arg t))
3901 (defun todo-filter-diary-items (&optional arg)
3902 "Display a list of todo diary items from different categories.
3903 The categories can be any of those in the current todo file.
3905 Called with no prefix ARG, if a diary items file for the current
3906 todo file has previously been saved (see
3907 `todo-save-filtered-items-buffer'), visit this file; if there is
3908 no such file, build the list of diary items. Called with a
3909 prefix argument, build the list even if there is a saved file of
3912 (todo-filter-items 'diary arg))
3914 (defun todo-filter-diary-items-multifile (&optional arg)
3915 "Display a list of todo diary items from different categories.
3916 The categories are a subset of the categories in the files listed
3917 in `todo-filter-files', or if this nil, in the files chosen from
3918 a file selection dialog that pops up in this case.
3920 Called with no prefix ARG, if a diary items file for the chosen
3921 todo files has previously been saved (see
3922 `todo-save-filtered-items-buffer'), visit this file; if there is
3923 no such file, build the list of diary items. Called with a
3924 prefix argument, build the list even if there is a saved file of
3927 (todo-filter-items 'diary arg t))
3929 (defun todo-filter-regexp-items (&optional arg)
3930 "Prompt for a regular expression and display items that match it.
3931 The matches can be from any categories in the current todo file
3932 and with non-nil option `todo-filter-done-items', can include
3933 not only todo items but also done items, including those in
3936 Called with no prefix ARG, if a regexp items file for the current
3937 todo file has previously been saved (see
3938 `todo-save-filtered-items-buffer'), visit this file; if there is
3939 no such file, build the list of regexp items. Called with a
3940 prefix argument, build the list even if there is a saved file of
3943 (todo-filter-items 'regexp arg))
3945 (defun todo-filter-regexp-items-multifile (&optional arg)
3946 "Prompt for a regular expression and display items that match it.
3947 The matches can be from any categories in the files listed in
3948 `todo-filter-files', or if this nil, in the files chosen from a
3949 file selection dialog that pops up in this case. With non-nil
3950 option `todo-filter-done-items', the matches can include not
3951 only todo items but also done items, including those in Archive
3954 Called with no prefix ARG, if a regexp items file for the current
3955 todo file has previously been saved (see
3956 `todo-save-filtered-items-buffer'), visit this file; if there is
3957 no such file, build the list of regexp items. Called with a
3958 prefix argument, build the list even if there is a saved file of
3961 (todo-filter-items 'regexp arg t))
3963 (defun todo-find-filtered-items-file ()
3964 "Choose a filtered items file and visit it."
3966 (let ((files (directory-files todo-directory t "\\.tod[rty]$" t))
3969 (let ((type (cond ((equal (file-name-extension f) "todr") "regexp")
3970 ((equal (file-name-extension f) "todt") "top")
3971 ((equal (file-name-extension f) "tody") "diary"))))
3972 (push (cons (concat (todo-short-file-name f) " (" type ")") f)
3974 (setq file (completing-read "Choose a filtered items file: "
3975 falist nil t nil nil (car falist)))
3976 (setq file (cdr (assoc-string file falist)))
3978 (unless (derived-mode-p 'todo-filtered-items-mode)
3979 (todo-filtered-items-mode))
3980 (todo-prefix-overlays)))
3982 (defun todo-go-to-source-item ()
3983 "Display the file and category of the filtered item at point."
3985 (let* ((str (todo-item-string))
3986 (buf (current-buffer))
3987 (res (todo-find-item str))
3992 (message "Category %s does not contain this item." cat)
3994 (set-window-buffer (selected-window)
3995 (set-buffer (find-buffer-visiting file)))
3996 (setq todo-current-todo-file file)
3997 (setq todo-category-number (todo-category-number cat))
3998 (let ((todo-show-with-done (if (or todo-filter-done-items
3999 (eq (cdr found) 'done))
4001 todo-show-with-done)))
4002 (todo-category-select))
4003 (goto-char (car found)))))
4005 (defvar todo-multiple-filter-files nil
4006 "List of files selected from `todo-multiple-filter-files' widget.")
4008 (defvar todo-multiple-filter-files-widget nil
4009 "Variable holding widget created by `todo-multiple-filter-files'.")
4011 (defun todo-multiple-filter-files ()
4012 "Pop to a buffer with a widget for choosing multiple filter files."
4015 (require 'wid-edit))
4016 (with-current-buffer (get-buffer-create "*Todo Filter Files*")
4017 (pop-to-buffer (current-buffer))
4019 (kill-all-local-variables)
4020 (widget-insert "Select files for generating the top priorities list.\n\n")
4021 (setq todo-multiple-filter-files-widget
4023 `(set ,@(mapcar (lambda (x) (list 'const x))
4024 (mapcar 'todo-short-file-name
4025 (funcall todo-files-function))))))
4026 (widget-insert "\n")
4027 (widget-create 'push-button
4028 :notify (lambda (widget &rest ignore)
4029 (setq todo-multiple-filter-files 'quit)
4031 (exit-recursive-edit))
4034 (widget-create 'push-button
4035 :notify (lambda (&rest ignore)
4036 (setq todo-multiple-filter-files
4039 (concat todo-directory
4042 todo-multiple-filter-files-widget)))
4044 (exit-recursive-edit))
4046 (use-local-map widget-keymap)
4048 (message "Click \"Apply\" after selecting files.")
4051 (defconst todo-filtered-items-buffer "Todo filtered items"
4052 "Initial name of buffer in Todo Filter Items mode.")
4054 (defconst todo-top-priorities-buffer "Todo top priorities"
4055 "Buffer type string for `todo-filter-items'.")
4057 (defconst todo-diary-items-buffer "Todo diary items"
4058 "Buffer type string for `todo-filter-items'.")
4060 (defconst todo-regexp-items-buffer "Todo regexp items"
4061 "Buffer type string for `todo-filter-items'.")
4063 (defun todo-filter-items (filter &optional new multifile)
4064 "Display a list of items filtered by FILTER.
4065 The values of FILTER can be `top' for top priority items, a cons
4066 of `top' and a number passed by the caller, `diary' for diary
4067 items, or `regexp' for items matching a regular expression
4068 entered by the user. The items can come from any categories in
4069 the current todo file or, with non-nil MULTIFILE, from several
4070 files. If NEW is nil, visit an appropriate file containing the
4071 list of filtered items; if there is no such file, or with non-nil
4072 NEW, build the list and display it.
4074 See the documentation strings of the commands
4075 `todo-filter-top-priorities', `todo-filter-diary-items',
4076 `todo-filter-regexp-items', and those of the corresponding
4077 multifile commands for further details."
4078 (let* ((top (eq filter 'top))
4079 (diary (eq filter 'diary))
4080 (regexp (eq filter 'regexp))
4081 (buf (cond (top todo-top-priorities-buffer)
4082 (diary todo-diary-items-buffer)
4083 (regexp todo-regexp-items-buffer)))
4084 (flist (if multifile
4085 (or todo-filter-files
4086 (progn (todo-multiple-filter-files)
4087 todo-multiple-filter-files))
4088 (list todo-current-todo-file)))
4089 (fname (if (equal flist 'quit)
4090 ;; Pressed `cancel' in t-m-f-f file selection dialog.
4092 (concat todo-directory
4093 (mapconcat 'todo-short-file-name flist "-")
4096 (regexp ".todr")))))
4097 (multi (> (length flist) 1))
4098 (rxfiles (when regexp
4099 (directory-files todo-directory t ".*\\.todr$" t)))
4100 (file-exists (or (file-exists-p fname) rxfiles))
4102 (cond ((and top new (natnump new))
4103 (todo-filter-items-1 (cons 'top new) flist))
4104 ((and (not new) file-exists)
4105 (when (and rxfiles (> (length rxfiles) 1))
4106 (let ((rxf (mapcar 'todo-short-file-name rxfiles)))
4107 (setq fname (todo-absolute-file-name
4108 (completing-read "Choose a regexp items file: "
4111 (unless (derived-mode-p 'todo-filtered-items-mode)
4112 (todo-filtered-items-mode))
4113 (todo-prefix-overlays)
4114 (todo-check-filtered-items-file))
4116 (todo-filter-items-1 filter flist)))
4117 (dolist (s (split-string (todo-short-file-name fname) "-"))
4118 (setq bufname (if bufname
4119 (concat bufname (if (member s (mapcar
4120 'todo-short-file-name
4124 (rename-buffer (format (concat "%s for file" (if multi "s" "")
4125 " \"%s\"") buf bufname))))
4127 (defun todo-filter-items-1 (filter file-list)
4128 "Build a list of items by applying FILTER to FILE-LIST.
4129 Internal subroutine called by `todo-filter-items', which passes
4130 the values of FILTER and FILE-LIST."
4131 (let ((num (if (consp filter) (cdr filter) todo-top-priorities))
4132 (buf (get-buffer-create todo-filtered-items-buffer))
4133 (multifile (> (length file-list) 1))
4134 regexp fname bufstr cat beg end done)
4135 (if (null file-list)
4136 (user-error "No files have been chosen for filtering")
4137 (with-current-buffer buf
4139 (kill-all-local-variables)
4140 (todo-filtered-items-mode))
4141 (when (eq filter 'regexp)
4142 (setq regexp (read-string "Enter a regular expression: ")))
4143 (save-current-buffer
4144 (dolist (f file-list)
4145 ;; Before inserting file contents into temp buffer, save a modified
4146 ;; buffer visiting it.
4147 (let ((bf (find-buffer-visiting f)))
4148 (when (buffer-modified-p bf)
4149 (with-current-buffer bf (save-buffer))))
4150 (setq fname (todo-short-file-name f))
4152 (when (and todo-filter-done-items (eq filter 'regexp))
4153 ;; If there is a corresponding archive file for the
4154 ;; todo file, insert it first and add identifiers for
4155 ;; todo-go-to-source-item.
4156 (let ((arch (concat (file-name-sans-extension f) ".toda")))
4157 (when (file-exists-p arch)
4158 (insert-file-contents arch)
4159 ;; Delete todo archive file's categories sexp.
4160 (delete-region (line-beginning-position)
4161 (1+ (line-end-position)))
4164 (when (re-search-forward
4165 (concat (if todo-filter-done-items
4166 (concat "\\(?:" todo-done-string-start
4167 "\\|" todo-date-string-start
4169 todo-date-string-start)
4170 todo-date-pattern "\\(?: "
4171 diary-time-regexp "\\)?"
4172 (if todo-filter-done-items
4174 (regexp-quote todo-nondiary-end)) "?")
4176 (insert "(archive) "))
4178 (insert-file-contents f)
4179 ;; Delete todo file's categories sexp.
4180 (delete-region (line-beginning-position) (1+ (line-end-position)))
4182 ;; Unless the number of top priorities to show was
4183 ;; passed by the caller, the file-wide value from
4184 ;; `todo-top-priorities-overrides', if non-nil, overrides
4185 ;; `todo-top-priorities'.
4186 (unless (consp filter)
4187 (setq fnum (or (nth 1 (assoc f todo-top-priorities-overrides))
4188 todo-top-priorities)))
4189 (while (re-search-forward
4190 (concat "^" (regexp-quote todo-category-beg)
4191 "\\(.+\\)\n") nil t)
4192 (setq cat (match-string 1))
4194 ;; Unless the number of top priorities to show was
4195 ;; passed by the caller, the category-wide value
4196 ;; from `todo-top-priorities-overrides', if non-nil,
4197 ;; overrides a non-nil file-wide value from
4198 ;; `todo-top-priorities-overrides' as well as
4199 ;; `todo-top-priorities'.
4200 (unless (consp filter)
4201 (let ((cats (nth 2 (assoc f todo-top-priorities-overrides))))
4202 (setq cnum (or (cdr (assoc cat cats)) fnum))))
4203 (delete-region (match-beginning 0) (match-end 0))
4204 (setq beg (point)) ; First item in the current category.
4205 (setq end (if (re-search-forward
4206 (concat "^" (regexp-quote todo-category-beg))
4212 (if (re-search-forward
4213 (concat "\n" (regexp-quote todo-category-done))
4217 (unless (and todo-filter-done-items (eq filter 'regexp))
4218 ;; Leave done items.
4219 (delete-region done end)
4221 (narrow-to-region beg end) ; Process only current category.
4222 (goto-char (point-min))
4223 ;; Apply the filter.
4224 (cond ((eq filter 'diary)
4226 (if (looking-at (regexp-quote todo-nondiary-start))
4228 (todo-forward-item))))
4229 ((eq filter 'regexp)
4231 (if (looking-at todo-item-start)
4232 (if (string-match regexp (todo-item-string))
4235 ;; Kill lines that aren't part of a todo or done
4236 ;; item (empty or todo-category-done).
4237 (delete-region (line-beginning-position)
4238 (1+ (line-end-position))))
4239 ;; If last todo item in file matches regexp and
4240 ;; there are no following done items,
4241 ;; todo-category-done string is left dangling,
4242 ;; because todo-forward-item jumps over it.
4245 (concat (regexp-quote todo-done-string)
4247 (line-beginning-position 0)))
4248 (delete-region (point) (progn
4251 (t ; Filter top priority items.
4252 (setq num (or cnum fnum num))
4254 (todo-forward-item num))))
4256 ;; Delete non-top-priority items.
4257 (unless (member filter '(diary regexp))
4258 (delete-region beg end))
4259 (goto-char (point-min))
4260 ;; Add file (if using multiple files) and category tags to
4263 (when (re-search-forward
4264 (concat (if todo-filter-done-items
4265 (concat "\\(?:" todo-done-string-start
4266 "\\|" todo-date-string-start
4268 todo-date-string-start)
4269 todo-date-pattern "\\(?: " diary-time-regexp
4270 "\\)?" (if todo-filter-done-items
4272 (regexp-quote todo-nondiary-end))
4276 (when (looking-at "(archive) ") (goto-char (match-end 0)))
4277 (insert (if multifile (concat fname ":") "") cat "]"))
4280 (setq bufstr (buffer-string))
4281 (with-current-buffer buf
4282 (let (buffer-read-only)
4283 (insert bufstr)))))))
4284 (set-window-buffer (selected-window) (set-buffer buf))
4285 (todo-prefix-overlays)
4286 (goto-char (point-min)))))
4288 (defun todo-set-top-priorities (&optional arg)
4289 "Set number of top priorities shown by `todo-filter-top-priorities'.
4290 With non-nil ARG, set the number only for the current Todo
4291 category; otherwise, set the number for all categories in the
4294 Calling this function via either of the commands
4295 `todo-set-top-priorities-in-file' or
4296 `todo-set-top-priorities-in-category' is the recommended way to
4297 set the user customizable option `todo-top-priorities-overrides'."
4298 (let* ((cat (todo-current-category))
4299 (file todo-current-todo-file)
4300 (rules todo-top-priorities-overrides)
4301 (frule (assoc-string file rules))
4302 (crules (nth 2 frule))
4303 (crule (assoc-string cat crules))
4304 (fcur (or (nth 1 frule)
4305 todo-top-priorities))
4306 (ccur (or (and arg (cdr crule))
4308 (prompt (if arg (concat "Number of top priorities in this category"
4309 " (currently %d): ")
4310 (concat "Default number of top priorities per category"
4311 " in this file (currently %d): ")))
4314 (let ((cur (if arg ccur fcur)))
4315 (setq new (read-number (format prompt cur))
4316 prompt "Enter a non-negative number: "
4318 (let ((nrule (if arg
4319 (append (delete crule crules) (list (cons cat new)))
4320 (append (list file new) (list crules)))))
4321 (setq rules (cons (if arg
4322 (list file fcur nrule)
4324 (delete frule rules)))
4325 (customize-save-variable 'todo-top-priorities-overrides rules)
4326 (todo-prefix-overlays))))
4328 (defun todo-find-item (str)
4329 "Search for filtered item STR in its saved todo file.
4330 Return the list (FOUND FILE CAT), where CAT and FILE are the
4331 item's category and file, and FOUND is a cons cell if the search
4332 succeeds, whose car is the start of the item in FILE and whose
4333 cdr is `done', if the item is now a done item, `changed', if its
4334 text was truncated or augmented or, for a top priority item, if
4335 its priority has changed, and `same' otherwise."
4336 (string-match (concat (if todo-filter-done-items
4337 (concat "\\(?:" todo-done-string-start "\\|"
4338 todo-date-string-start "\\)")
4339 todo-date-string-start)
4340 todo-date-pattern "\\(?: " diary-time-regexp "\\)?"
4341 (if todo-filter-done-items
4343 (regexp-quote todo-nondiary-end)) "?"
4344 "\\(?4: \\[\\(?3:(archive) \\)?\\(?2:.*:\\)?"
4345 "\\(?1:.*\\)\\]\\).*$") str)
4346 (let ((cat (match-string 1 str))
4347 (file (match-string 2 str))
4348 (archive (string= (match-string 3 str) "(archive) "))
4349 (filcat (match-string 4 str))
4351 (tpbuf (save-match-data (string-match "top" (buffer-name))))
4353 (setq str (replace-match "" nil nil str 4))
4355 ;; Calculate priority of STR wrt its category.
4357 (while (search-backward filcat nil t)
4358 (setq tpriority (1+ tpriority)))))
4360 (concat todo-directory (substring file 0 -1)
4361 (if archive ".toda" ".todo"))
4363 (concat (file-name-sans-extension
4364 todo-global-current-todo-file) ".toda")
4365 todo-global-current-todo-file)))
4366 (find-file-noselect file)
4367 (with-current-buffer (find-buffer-visiting file)
4369 (unless (derived-mode-p 'todo-archive-mode) (todo-archive-mode))
4370 (unless (derived-mode-p 'todo-mode) (todo-mode)))
4373 (goto-char (point-min))
4374 (let ((beg (re-search-forward
4375 (concat "^" (regexp-quote (concat todo-category-beg cat))
4378 (done (save-excursion
4380 (concat "^" (regexp-quote todo-category-done)) nil t)))
4381 (end (save-excursion
4382 (or (re-search-forward
4383 (concat "^" (regexp-quote todo-category-beg))
4386 (setq found (when (search-forward str end t)
4387 (goto-char (match-beginning 0))))
4390 (cons found (if (> (point) done)
4392 (let ((cpriority 1))
4395 ;; Not top item in category.
4396 (while (> (point) (1+ beg))
4397 (let ((opoint (point)))
4398 (todo-backward-item)
4399 ;; Can't move backward beyond
4400 ;; first item in file.
4401 (unless (= (point) opoint)
4402 (setq cpriority (1+ cpriority)))))))
4403 (if (and (= tpriority cpriority)
4404 ;; Proper substring is not the same.
4405 (string= (todo-item-string)
4409 (list found file cat)))
4411 (defun todo-check-filtered-items-file ()
4412 "Check if filtered items file is up to date and a show suitable message."
4416 (let* ((item (todo-item-string))
4417 (found (car (todo-find-item item))))
4418 (unless (eq (cdr found) 'same)
4420 (overlay-put (make-overlay (todo-item-start) (todo-item-end))
4421 'face 'todo-search))
4422 (setq count (1+ count))))
4423 ;; (throw 'old (message "The marked item is not up to date.")))
4424 (todo-forward-item))
4426 (message "Filtered items file is up to date.")
4427 (message (concat "The highlighted item" (if (= count 1) " is " "s are ")
4429 ;; "\nType <return> on item for details."
4432 (defun todo-filter-items-filename ()
4433 "Return absolute file name for saving this Filtered Items buffer."
4434 (let ((bufname (buffer-name)))
4435 (string-match "\"\\([^\"]+\\)\"" bufname)
4436 (let* ((filename-str (substring bufname (match-beginning 1) (match-end 1)))
4437 (filename-base (replace-regexp-in-string ", " "-" filename-str))
4438 (top-priorities (string-match "top priorities" bufname))
4439 (diary-items (string-match "diary items" bufname))
4440 (regexp-items (string-match "regexp items" bufname)))
4442 (let ((prompt (concat "Enter a short identifying string"
4443 " to make this file name unique: ")))
4444 (setq filename-base (concat filename-base "-" (read-string prompt)))))
4445 (concat todo-directory filename-base
4446 (cond (top-priorities ".todt")
4447 (diary-items ".tody")
4448 (regexp-items ".todr"))))))
4450 (defun todo-save-filtered-items-buffer ()
4451 "Save current Filtered Items buffer to a file.
4452 If the file already exists, overwrite it only on confirmation."
4453 (let ((filename (or (buffer-file-name) (todo-filter-items-filename))))
4454 (write-file filename t)))
4456 ;; -----------------------------------------------------------------------------
4457 ;;; Printing Todo mode buffers
4458 ;; -----------------------------------------------------------------------------
4460 (defcustom todo-print-buffer-function 'ps-print-buffer-with-faces
4461 "Function called by the command `todo-print-buffer'."
4465 (defvar todo-print-buffer "*Todo Print*"
4466 "Name of buffer with printable version of Todo mode buffer.")
4468 (defun todo-print-buffer (&optional to-file)
4469 "Produce a printable version of the current Todo mode buffer.
4470 This converts overlays and soft line wrapping and, depending on
4471 the value of `todo-print-buffer-function', includes faces. With
4472 non-nil argument TO-FILE write the printable version to a file;
4473 otherwise, send it to the default printer."
4475 (let ((buf todo-print-buffer)
4477 ((eq major-mode 'todo-mode)
4478 (concat "Todo File: "
4479 (todo-short-file-name todo-current-todo-file)
4480 "\nCategory: " (todo-current-category)))
4481 ((eq major-mode 'todo-filtered-items-mode)
4483 (prefix (propertize (concat todo-prefix " ")
4484 'face 'todo-prefix-string))
4486 (fill-prefix (make-string todo-indent-to-here 32))
4487 (content (buffer-string))
4489 (with-current-buffer (get-buffer-create buf)
4491 (goto-char (point-min))
4494 (end (save-excursion (todo-item-end))))
4495 (when todo-number-prefix
4497 (setq prefix (propertize (concat (number-to-string num) " ")
4498 'face 'todo-prefix-string)))
4500 (fill-region beg end))
4501 ;; Calling todo-forward-item infloops at todo-item-start due to
4502 ;; non-overlay prefix, so search for item start instead.
4503 (if (re-search-forward todo-item-start nil t)
4505 (goto-char (point-max))))
4506 (if (re-search-backward (concat "^" (regexp-quote todo-category-done))
4508 (replace-match todo-done-separator))
4509 (goto-char (point-min))
4513 (let ((file (read-file-name "Print to file: ")))
4514 (funcall todo-print-buffer-function file))
4515 (funcall todo-print-buffer-function)))
4518 (defun todo-print-buffer-to-file ()
4519 "Save printable version of this Todo mode buffer to a file."
4521 (todo-print-buffer t))
4523 ;; -----------------------------------------------------------------------------
4524 ;;; Legacy Todo mode files
4525 ;; -----------------------------------------------------------------------------
4527 (defcustom todo-legacy-date-time-regexp
4528 (concat "\\(?1:[0-9]\\{4\\}\\)-\\(?2:[0-9]\\{2\\}\\)-"
4529 "\\(?3:[0-9]\\{2\\}\\) \\(?4:[0-9]\\{2\\}:[0-9]\\{2\\}\\)")
4530 "Regexp matching legacy todo-mode.el item date-time strings.
4531 In order for `todo-convert-legacy-files' to correctly convert
4532 this string to the current Todo mode format, the regexp must
4533 contain four explicitly numbered groups (see `(elisp) Regexp
4534 Backslash'), where group 1 matches a string for the year, group 2
4535 a string for the month, group 3 a string for the day and group 4
4536 a string for the time. The default value converts date-time
4537 strings built using the default value of
4538 `todo-time-string-format' from todo-mode.el."
4542 (defun todo-convert-legacy-date-time ()
4543 "Return converted date-time string.
4544 Helper function for `todo-convert-legacy-files'."
4545 (let* ((year (match-string 1))
4546 (month (match-string 2))
4547 (monthname (calendar-month-name (string-to-number month) t))
4548 (day (match-string 3))
4549 (time (match-string 4))
4552 (insert (mapconcat 'eval calendar-date-display-form "")
4553 (when time (concat " " time)))))
4555 (defun todo-convert-legacy-files ()
4556 "Convert legacy todo files to the current Todo mode format.
4557 The old-style files named by the variables `todo-file-do' and
4558 `todo-file-done' from the old package are converted to the new
4559 format and saved (the latter as a todo archive file) with a new
4560 name in `todo-directory'. See also the documentation string of
4561 `todo-legacy-date-time-regexp' for further details."
4563 ;; If there are user customizations of legacy options, use them,
4564 ;; otherwise use the legacy default values.
4565 (let ((todo-file-do-tem (if (boundp 'todo-file-do)
4567 (locate-user-emacs-file "todo-do" ".todo-do")))
4568 (todo-file-done-tem (if (boundp 'todo-file-done)
4570 (locate-user-emacs-file "todo-done" ".todo-done")))
4571 (todo-initials-tem (and (boundp 'todo-initials) todo-initials))
4572 (todo-entry-prefix-function-tem (and (boundp 'todo-entry-prefix-function)
4573 todo-entry-prefix-function))
4575 ;; Convert `todo-file-do'.
4576 (if (not (file-exists-p todo-file-do-tem))
4577 (message "No legacy todo file exists")
4578 (let ((default "todo-do-conv")
4581 (insert-file-contents todo-file-do-tem)
4582 ;; Eliminate old-style local variables list in first line.
4583 (delete-region (line-beginning-position) (1+ (line-end-position)))
4584 (search-forward " --- " nil t) ; Legacy todo-category-beg.
4585 (setq todo-prefix-tem (buffer-substring-no-properties
4586 (line-beginning-position) (match-beginning 0)))
4587 (goto-char (point-min))
4590 ;; Old-style category start delimiter.
4591 ((looking-at (regexp-quote (concat todo-prefix-tem " --- ")))
4592 (replace-match todo-category-beg))
4593 ;; Old-style category end delimiter.
4594 ((looking-at (regexp-quote "--- End"))
4596 ;; Old-style category separator.
4597 ((looking-at (regexp-quote
4598 (concat todo-prefix-tem " "
4599 (make-string 75 ?-))))
4600 (replace-match todo-category-done))
4601 ;; Old-style item header (date/time/initials).
4602 ((looking-at (concat (regexp-quote todo-prefix-tem) " "
4603 (if todo-entry-prefix-function-tem
4604 (funcall todo-entry-prefix-function-tem)
4605 (concat todo-legacy-date-time-regexp " "
4606 (if todo-initials-tem
4607 (regexp-quote todo-initials-tem)
4610 (todo-convert-legacy-date-time)))
4612 (setq file (concat todo-directory
4614 (format "Save file as (default \"%s\"): " default)
4617 (unless (file-exists-p todo-directory)
4618 (make-directory todo-directory))
4619 (write-region (point-min) (point-max) file nil 'nomessage nil t))
4621 (insert-file-contents file)
4622 (let ((todo-categories (todo-make-categories-list t)))
4623 (todo-update-categories-sexp)
4624 (todo-check-format))
4625 (write-region (point-min) (point-max) file nil 'nomessage))
4626 (setq todo-files (funcall todo-files-function))
4627 ;; Convert `todo-file-done'.
4628 (when (file-exists-p todo-file-done-tem)
4630 (insert-file-contents todo-file-done-tem)
4631 (let ((beg (make-marker))
4633 cat cats comment item)
4635 (when (looking-at todo-legacy-date-time-regexp)
4636 (set-marker beg (point))
4637 (todo-convert-legacy-date-time)
4638 (set-marker end (point))
4640 (insert "[" todo-done-string)
4644 (when (looking-at todo-legacy-date-time-regexp)
4645 (todo-convert-legacy-date-time))
4646 (when (looking-at (concat " " (if todo-initials-tem
4651 (replace-match "")))
4652 (if (re-search-forward
4653 (concat "^" todo-legacy-date-time-regexp) nil t)
4654 (goto-char (match-beginning 0))
4655 (goto-char (point-max)))
4657 (when (looking-back "\\[\\([^][]+\\)\\]")
4658 (setq cat (match-string 1))
4659 (goto-char (match-beginning 0))
4661 ;; If the item ends with a non-comment parenthesis not
4662 ;; followed by a period, we lose (but we inherit that
4663 ;; problem from the legacy code).
4664 (when (looking-back "(\\(.*\\)) " (line-beginning-position))
4665 (setq comment (match-string 1))
4667 (insert "[" todo-comment-string ": " comment "]"))
4668 (set-marker end (point))
4669 (if (member cat cats)
4670 ;; If item is already in its category, leave it there.
4671 (unless (save-excursion
4673 (concat "^" (regexp-quote todo-category-beg)
4675 (string= (match-string 1) cat))
4676 ;; Else move it to its category.
4677 (setq item (buffer-substring-no-properties beg end))
4678 (delete-region beg (1+ end))
4679 (set-marker beg (point))
4682 (regexp-quote (concat todo-category-beg cat))
4686 (if (re-search-forward
4687 (concat "^" (regexp-quote todo-category-beg)
4689 (progn (goto-char (match-beginning 0))
4692 (goto-char (point-max)))
4697 (insert todo-category-beg cat "\n\n"
4698 todo-category-done "\n"))
4700 (set-marker beg nil)
4701 (set-marker end nil))
4702 (setq file (concat (file-name-sans-extension file) ".toda"))
4703 (write-region (point-min) (point-max) file nil 'nomessage nil t))
4705 (insert-file-contents file)
4706 (let* ((todo-categories (todo-make-categories-list t)))
4707 (todo-update-categories-sexp)
4708 (todo-check-format))
4709 (write-region (point-min) (point-max) file nil 'nomessage)
4710 (setq archive-sexp (read (buffer-substring-no-properties
4711 (line-beginning-position)
4712 (line-end-position)))))
4713 (setq file (concat (file-name-sans-extension file) ".todo"))
4714 ;; Update categories sexp of converted todo file again, adding
4715 ;; counts of archived items.
4717 (insert-file-contents file)
4718 (let ((sexp (read (buffer-substring-no-properties
4719 (line-beginning-position)
4720 (line-end-position)))))
4722 (let ((archive-cat (assoc (car cat) archive-sexp)))
4724 (aset (cdr cat) 3 (aref (cdr archive-cat) 2)))))
4725 (delete-region (line-beginning-position) (line-end-position))
4726 (prin1 sexp (current-buffer)))
4727 (write-region (point-min) (point-max) file nil 'nomessage))
4728 (setq todo-archives (funcall todo-files-function t)))
4729 (todo-reevaluate-filelist-defcustoms)
4730 (when (y-or-n-p (concat "Format conversion done; do you want to "
4731 "visit the converted file now? "))
4732 (setq todo-current-todo-file file)
4733 (unless todo-default-todo-file
4734 ;; We just initialized the first todo file, so make it the
4735 ;; default now to avoid an infinite recursion with todo-show.
4736 (setq todo-default-todo-file (todo-short-file-name file)))
4739 ;; -----------------------------------------------------------------------------
4740 ;;; Utility functions for todo files, categories and items
4741 ;; -----------------------------------------------------------------------------
4743 (defun todo-absolute-file-name (name &optional type)
4744 "Return the absolute file name of short todo file NAME.
4745 With TYPE `archive' or `top' return the absolute file name of the
4746 short todo archive or top priorities file name, respectively."
4747 ;; No-op if there is no todo file yet (i.e. don't concatenate nil).
4750 (concat todo-directory name
4751 (cond ((eq type 'archive) ".toda")
4752 ((eq type 'top) ".todt")
4753 ((eq type 'diary) ".tody")
4754 ((eq type 'regexp) ".todr")
4757 (defun todo-check-file (file)
4758 "Check the state associated with FILE and update it if necessary.
4759 If FILE exists, return t. If it does not exist and there is no
4760 live buffer with its content, return nil; if there is such a
4761 buffer and the user tries to show it, ask whether to restore
4762 FILE, and if confirmed, do so and return t; else delete the
4763 buffer, clean up the state and return nil."
4764 (setq todo-files (funcall todo-files-function))
4765 (setq todo-archives (funcall todo-files-function t))
4766 (if (file-exists-p file)
4768 (setq todo-visited (delete file todo-visited))
4769 (let ((buf (find-buffer-visiting file)))
4773 (format (concat "Todo file \"%s\" has been deleted but "
4774 "its content is still in a buffer!\n")
4775 (todo-short-file-name file))
4776 "Save that buffer and restore the todo file? ")))
4778 (with-current-buffer buf (save-buffer))
4779 (setq todo-files (funcall todo-files-function))
4780 (setq todo-archives (funcall todo-files-function t))
4782 (let* ((files (append todo-files todo-archives))
4783 (tctf todo-current-todo-file)
4784 (tgctf todo-global-current-todo-file)
4785 (tdtf (todo-absolute-file-name todo-default-todo-file)))
4786 (unless (or (not todo-current-todo-file)
4787 (member todo-current-todo-file files))
4788 (setq todo-current-todo-file nil))
4789 (unless (or (not todo-global-current-todo-file)
4790 (member todo-global-current-todo-file files))
4791 (setq todo-global-current-todo-file nil))
4792 (unless (or (not todo-default-todo-file)
4793 (member todo-default-todo-file files))
4794 (setq todo-default-todo-file (todo-short-file-name
4796 (todo-reevaluate-filelist-defcustoms)
4797 (when buf (kill-buffer buf))
4800 (defun todo-category-number (cat)
4801 "Return the number of category CAT in this todo file.
4802 The buffer-local variable `todo-category-number' holds this
4803 number as its value."
4804 (let ((categories (mapcar 'car todo-categories)))
4805 (setq todo-category-number
4806 ;; Increment by one, so that the number of the first
4807 ;; category is one rather than zero.
4808 (1+ (- (length categories)
4809 (length (member cat categories)))))))
4811 (defun todo-current-category ()
4812 "Return the name of the current category."
4813 (car (nth (1- todo-category-number) todo-categories)))
4815 (defun todo-category-select ()
4816 "Display the current category correctly."
4817 (let ((name (todo-current-category))
4818 cat-begin cat-end done-start done-sep-start done-end)
4820 (goto-char (point-min))
4822 (concat "^" (regexp-quote (concat todo-category-beg name)) "$") nil t)
4823 (setq cat-begin (1+ (line-end-position)))
4824 (setq cat-end (if (re-search-forward
4825 (concat "^" (regexp-quote todo-category-beg)) nil t)
4828 (setq mode-line-buffer-identification
4829 (funcall todo-mode-line-function name))
4830 (narrow-to-region cat-begin cat-end)
4831 (todo-prefix-overlays)
4832 (goto-char (point-min))
4833 (if (re-search-forward (concat "\n\\(" (regexp-quote todo-category-done)
4836 (setq done-start (match-beginning 0))
4837 (setq done-sep-start (match-beginning 1))
4838 (setq done-end (match-end 0)))
4839 (error "Category %s is missing todo-category-done string" name))
4840 (if todo-show-done-only
4841 (narrow-to-region (1+ done-end) (point-max))
4842 (when (and todo-show-with-done
4843 (re-search-forward todo-done-string-start nil t))
4844 ;; Now we want to see the done items, so reset displayed end to end of
4846 (setq done-start cat-end)
4847 ;; Make display overlay for done items separator string, unless there
4849 (let* ((done-sep todo-done-separator)
4850 (ov (progn (goto-char done-sep-start)
4851 (todo-get-overlay 'separator))))
4853 (setq ov (make-overlay done-sep-start done-end))
4854 (overlay-put ov 'todo 'separator)
4855 (overlay-put ov 'display done-sep))))
4856 (narrow-to-region (point-min) done-start)
4857 ;; Loading this from todo-mode, or adding it to the mode hook, causes
4858 ;; Emacs to hang in todo-item-start, at (looking-at todo-item-start).
4859 (when todo-highlight-item
4861 (hl-line-mode 1)))))
4863 (defun todo-get-count (type &optional category)
4864 "Return count of TYPE items in CATEGORY.
4865 If CATEGORY is nil, default to the current category."
4866 (let* ((cat (or category (todo-current-category)))
4867 (counts (cdr (assoc cat todo-categories)))
4868 (idx (cond ((eq type 'todo) 0)
4869 ((eq type 'diary) 1)
4871 ((eq type 'archived) 3))))
4874 (defun todo-update-count (type increment &optional category)
4875 "Change count of TYPE items in CATEGORY by integer INCREMENT.
4876 With nil or omitted CATEGORY, default to the current category."
4877 (let* ((cat (or category (todo-current-category)))
4878 (counts (cdr (assoc cat todo-categories)))
4879 (idx (cond ((eq type 'todo) 0)
4880 ((eq type 'diary) 1)
4882 ((eq type 'archived) 3))))
4883 (aset counts idx (+ increment (aref counts idx)))))
4885 (defun todo-set-categories ()
4886 "Set `todo-categories' from the sexp at the top of the file."
4887 ;; New archive files created by `todo-move-category' are empty, which would
4888 ;; make the sexp test fail and raise an error, so in this case we skip it.
4889 (unless (zerop (buffer-size))
4893 (goto-char (point-min))
4894 (setq todo-categories
4895 (if (looking-at "\(\(\"")
4896 (read (buffer-substring-no-properties
4897 (line-beginning-position)
4898 (line-end-position)))
4899 (error "Invalid or missing todo-categories sexp")))))))
4901 (defun todo-update-categories-sexp ()
4902 "Update the `todo-categories' sexp at the top of the file."
4903 (let (buffer-read-only)
4907 (goto-char (point-min))
4908 (if (looking-at (concat "^" (regexp-quote todo-category-beg)))
4909 (progn (newline) (goto-char (point-min)) ; Make space for sexp.
4910 (setq todo-categories (todo-make-categories-list t)))
4911 (delete-region (line-beginning-position) (line-end-position)))
4912 (prin1 todo-categories (current-buffer))))))
4914 (defun todo-make-categories-list (&optional force)
4915 "Return an alist of todo categories and their item counts.
4916 With non-nil argument FORCE parse the entire file to build the
4917 list; otherwise, get the value by reading the sexp at the top of
4919 (setq todo-categories nil)
4923 (goto-char (point-min))
4924 (let (counts cat archive)
4925 ;; If the file is a todo file and has archived items, identify the
4926 ;; archive, in order to count its items. But skip this with
4927 ;; `todo-convert-legacy-files', since that converts filed items to
4929 (when buffer-file-name ; During conversion there is no file yet.
4930 ;; If the file is an archive, it doesn't have an archive.
4931 (unless (member (file-truename buffer-file-name)
4932 (funcall todo-files-function t))
4933 (setq archive (concat (file-name-sans-extension
4934 todo-current-todo-file) ".toda"))))
4936 (cond ((looking-at (concat (regexp-quote todo-category-beg)
4938 (setq cat (match-string-no-properties 1))
4939 ;; Counts for each category: [todo diary done archive]
4940 (setq counts (make-vector 4 0))
4941 (setq todo-categories
4942 (append todo-categories (list (cons cat counts))))
4943 ;; Add archived item count to the todo file item counts.
4944 ;; Make sure to include newly created archives, e.g. due to
4945 ;; todo-move-category.
4946 (when (member archive (funcall todo-files-function t))
4947 (let ((archive-count 0)
4948 (visiting (find-buffer-visiting archive)))
4949 (with-current-buffer (or visiting
4950 (find-file-noselect archive))
4954 (goto-char (point-min))
4955 (when (re-search-forward
4956 (concat "^" (regexp-quote todo-category-beg)
4960 (while (not (or (looking-at
4962 (regexp-quote todo-category-beg)
4965 (when (looking-at todo-done-string-start)
4966 (setq archive-count (1+ archive-count)))
4968 (unless visiting (kill-buffer)))
4969 (todo-update-count 'archived archive-count cat))))
4970 ((looking-at todo-done-string-start)
4971 (todo-update-count 'done 1 cat))
4972 ((looking-at (concat "^\\("
4973 (regexp-quote diary-nonmarking-symbol)
4974 "\\)?" todo-date-pattern))
4975 (todo-update-count 'diary 1 cat)
4976 (todo-update-count 'todo 1 cat))
4977 ((looking-at (concat todo-date-string-start todo-date-pattern))
4978 (todo-update-count 'todo 1 cat))
4979 ;; If first line is todo-categories list, use it and end loop
4980 ;; -- unless FORCEd to scan whole file.
4983 (setq todo-categories (read (buffer-substring-no-properties
4984 (line-beginning-position)
4985 (line-end-position))))
4986 (goto-char (1- (point-max))))))
4990 (defun todo-repair-categories-sexp ()
4991 "Repair corrupt todo file categories sexp.
4992 This should only be needed as a consequence of careless manual
4993 editing or a bug in todo.el.
4995 *Warning*: Calling this command restores the category order to
4996 the list element order in the todo file categories sexp, so any
4997 order changes made in Todo Categories mode will have to be made
5000 (let ((todo-categories (todo-make-categories-list t)))
5001 (todo-update-categories-sexp)))
5003 (defun todo-check-format ()
5004 "Signal an error if the current todo file is ill-formatted.
5005 Otherwise return t. Display a message if the file is well-formed
5006 but the categories sexp differs from the current value of
5011 (goto-char (point-min))
5012 (let* ((cats (prin1-to-string todo-categories))
5013 (ssexp (buffer-substring-no-properties (line-beginning-position)
5014 (line-end-position)))
5015 (sexp (read ssexp)))
5016 ;; Check the first line for `todo-categories' sexp.
5019 (unless (and (stringp (car c))
5022 (user-error "Invalid or missing todo-categories sexp"))))
5024 ;; Check well-formedness of categories.
5025 (let ((legit (concat
5026 "\\(^" (regexp-quote todo-category-beg) "\\)"
5027 "\\|\\(" todo-date-string-start todo-date-pattern "\\)"
5028 "\\|\\(^[ \t]+[^ \t]*\\)"
5030 "\\|\\(^" (regexp-quote todo-category-done) "\\)"
5031 "\\|\\(" todo-done-string-start "\\)")))
5033 (unless (looking-at legit)
5034 (user-error "Illegitimate todo file format at line %d"
5035 (line-number-at-pos (point))))
5037 ;; Warn user if categories sexp has changed.
5038 (unless (string= ssexp cats)
5039 (message (concat "The sexp at the beginning of the file differs "
5040 "from the value of `todo-categories'.\n"
5041 "If the sexp is wrong, you can fix it with "
5042 "M-x todo-repair-categories-sexp,\n"
5043 "but note this reverts any changes you have "
5044 "made in the order of the categories."))))))
5047 (defun todo-item-start ()
5048 "Move to start of current todo item and return its position."
5050 ;; Buffer is empty (invocation possible e.g. via todo-forward-item
5051 ;; from todo-filter-items when processing category with no todo
5053 (eq (point-min) (point-max))
5054 ;; Point is on the empty line below category's last todo item...
5055 (and (looking-at "^$")
5056 (or (eobp) ; ...and done items are hidden...
5057 (save-excursion ; ...or done items are visible.
5059 (looking-at (concat "^"
5060 (regexp-quote todo-category-done))))))
5061 ;; Buffer is widened.
5062 (looking-at (regexp-quote todo-category-beg)))
5063 (goto-char (line-beginning-position))
5064 (while (not (looking-at todo-item-start))
5068 (defun todo-item-end ()
5069 "Move to end of current todo item and return its position."
5070 ;; Items cannot end with a blank line.
5071 (unless (looking-at "^$")
5072 (let* ((done (todo-done-item-p))
5074 ;; For todo items, end is before the done items section, for done
5075 ;; items, end is before the next category. If these limits are
5076 ;; missing or inaccessible, end it before the end of the buffer.
5077 (lim (if (save-excursion
5079 (concat "^" (regexp-quote (if done
5081 todo-category-done)))
5083 (progn (setq to-lim t) (match-beginning 0))
5085 (when (bolp) (forward-char)) ; Find start of next item.
5086 (goto-char (if (re-search-forward todo-item-start lim t)
5088 (if to-lim lim (point-max))))
5089 ;; For last todo item, skip back over the empty line before the done
5090 ;; items section, else just back to the end of the previous line.
5091 (backward-char (when (and to-lim (not done) (eq (point) lim)) 2))
5094 (defun todo-item-string ()
5095 "Return bare text of current item as a string."
5096 (let ((opoint (point))
5097 (start (todo-item-start))
5098 (end (todo-item-end)))
5100 (and start end (buffer-substring-no-properties start end))))
5102 (defun todo-forward-item (&optional count)
5103 "Move point COUNT items down (by default, move down by one item)."
5104 (let* ((not-done (not (or (todo-done-item-p) (looking-at "^$"))))
5105 (start (line-end-position)))
5107 (if (re-search-forward todo-item-start nil t (or count 1))
5108 (goto-char (match-beginning 0))
5109 (goto-char (point-max)))
5110 ;; If points advances by one from a todo to a done item, go back
5111 ;; to the space above todo-done-separator, since that is a
5112 ;; legitimate place to insert an item. But skip this space if
5113 ;; count > 1, since that should only stop on an item.
5114 (when (and not-done (todo-done-item-p) (not count))
5115 ;; (if (or (not count) (= count 1))
5116 (re-search-backward "^$" start t))));)
5117 ;; The preceding sexp is insufficient when buffer is not narrowed,
5118 ;; since there could be no done items in this category, so the
5119 ;; search puts us on first todo item of next category. Does this
5120 ;; ever happen? If so:
5121 ;; (let ((opoint) (point))
5122 ;; (forward-line -1)
5123 ;; (when (or (not count) (= count 1))
5124 ;; (cond ((looking-at (concat "^" (regexp-quote todo-category-beg)))
5125 ;; (forward-line -2))
5126 ;; ((looking-at (concat "^" (regexp-quote todo-category-done)))
5127 ;; (forward-line -1))
5129 ;; (goto-char opoint)))))))
5131 (defun todo-backward-item (&optional count)
5132 "Move point up to start of item with next higher priority.
5133 With positive numerical prefix COUNT, move point COUNT items
5136 If the category's done items are visible, this command called
5137 with a prefix argument only moves point to a higher item, e.g.,
5138 with point on the first done item and called with prefix 1, it
5139 moves to the last todo item; but if called with point on the
5140 first done item without a prefix argument, it moves point the the
5141 empty line above the done items separator."
5142 (let* ((done (todo-done-item-p)))
5145 (re-search-backward todo-item-start nil t (or count 1)))
5146 ;; Unless this is a regexp filtered items buffer (which can contain
5147 ;; intermixed todo and done items), if points advances by one from a
5148 ;; done to a todo item, go back to the space above
5149 ;; todo-done-separator, since that is a legitimate place to insert an
5150 ;; item. But skip this space if count > 1, since that should only
5152 (when (and done (not (todo-done-item-p)) (not count)
5153 ;(or (not count) (= count 1))
5154 (not (equal (buffer-name) todo-regexp-items-buffer)))
5155 (re-search-forward (concat "^" (regexp-quote todo-category-done))
5157 (forward-line -1))))
5159 (defun todo-remove-item ()
5160 "Internal function called in editing, deleting or moving items."
5161 (let* ((end (progn (todo-item-end) (1+ (point))))
5162 (beg (todo-item-start))
5163 (ov (todo-get-overlay 'prefix)))
5164 (when ov (delete-overlay ov))
5165 (delete-region beg end)))
5167 (defun todo-diary-item-p ()
5168 "Return non-nil if item at point has diary entry format."
5170 (when (todo-item-string) ; Exclude empty lines.
5172 (not (looking-at (regexp-quote todo-nondiary-start))))))
5174 ;; This duplicates the item locating code from diary-goto-entry, but
5175 ;; without the marker code, to test whether the latter is dispensable.
5176 ;; If it is, diary-goto-entry can be simplified. The code duplication
5177 ;; here can also be eliminated, leaving only the widening and category
5178 ;; selection, and instead of :override advice :around can be used.
5180 (defun todo-diary-goto-entry (button)
5181 "Jump to the diary entry for the BUTTON at point.
5182 If the entry is a todo item, display its category properly.
5183 Overrides `diary-goto-entry'."
5184 ;; Locate the diary item in its source file.
5185 (let* ((locator (button-get button 'locator))
5186 (file (cadr locator))
5187 (date (regexp-quote (nth 2 locator)))
5188 (content (regexp-quote (nth 3 locator))))
5189 (if (not (and (file-exists-p file)
5190 (find-file-other-window file)))
5191 (message "Unable to locate this diary entry")
5192 ;; If it's a Todo file, make sure it's in Todo mode.
5193 (when (and (equal (file-name-directory (file-truename file))
5194 (file-truename todo-directory))
5195 (not (derived-mode-p 'todo-mode)))
5197 (when (eq major-mode 'todo-mode) (widen))
5198 (goto-char (point-min))
5199 (when (re-search-forward (format "%s.*\\(%s\\)" date content) nil t)
5200 (goto-char (match-beginning 1)))
5201 ;; If it's a todo item, determine its category and display the
5202 ;; category properly.
5203 (when (eq major-mode 'todo-mode)
5204 (let ((opoint (point)))
5205 (re-search-backward (concat "^" (regexp-quote todo-category-beg)
5206 "\\(.*\\)\n") nil t)
5207 (todo-category-number (match-string 1))
5208 (todo-category-select)
5209 (goto-char opoint))))))
5211 (add-function :override diary-goto-entry-function #'todo-diary-goto-entry)
5213 (defun todo-revert-buffer (&optional ignore-auto noconfirm)
5214 "Call `revert-buffer', preserving buffer's current modes.
5215 Also preserve category display, if applicable."
5216 (interactive (list (not current-prefix-arg)))
5217 (let ((revert-buffer-function nil))
5218 (revert-buffer ignore-auto noconfirm 'preserve-modes)
5219 (when (memq major-mode '(todo-mode todo-archive-mode))
5220 (todo-category-select))))
5222 (defun todo-desktop-save-buffer (_dir)
5223 `((catnum . ,(todo-category-number (todo-current-category)))))
5225 (declare-function desktop-restore-file-buffer "desktop"
5226 (buffer-filename buffer-name buffer-misc))
5228 (defun todo-restore-desktop-buffer (file buffer misc)
5229 (desktop-restore-file-buffer file buffer misc)
5230 (with-current-buffer buffer
5232 (let ((todo-category-number (cdr (assq 'catnum misc))))
5233 (todo-category-select))))
5235 (add-to-list 'desktop-buffer-mode-handlers
5236 '(todo-mode . todo-restore-desktop-buffer))
5238 (defun todo-done-item-p ()
5239 "Return non-nil if item at point is a done item."
5242 (looking-at todo-done-string-start)))
5244 (defun todo-done-item-section-p ()
5245 "Return non-nil if point is in category's done items section."
5247 (or (re-search-backward (concat "^" (regexp-quote todo-category-done))
5249 (progn (goto-char (point-min))
5250 (looking-at todo-done-string-start)))))
5252 (defun todo--user-error-if-marked-done-item ()
5253 "Signal user error on marked done items.
5254 Helper function for editing commands that apply only to (possibly
5255 marked) not done todo items."
5258 (goto-char (point-max))
5259 (todo-backward-item)
5260 (unless (todo-done-item-p)
5262 (unless (re-search-forward
5263 (concat "^" (regexp-quote todo-category-beg)) nil t)
5264 (goto-char (point-max)))
5266 (while (todo-done-item-p)
5267 (when (todo-marked-item-p)
5268 (user-error "This command does not apply to done items"))
5269 (todo-backward-item)))))
5271 (defun todo-reset-done-separator (sep)
5272 "Replace existing overlays of done items separator string SEP."
5276 (goto-char (point-min))
5277 (while (re-search-forward
5278 (concat "\n\\(" (regexp-quote todo-category-done) "\\)") nil t)
5279 (let* ((beg (match-beginning 1))
5281 (ov (progn (goto-char beg)
5282 (todo-get-overlay 'separator)))
5283 (old-sep (when ov (overlay-get ov 'display)))
5286 (unless (string= old-sep sep)
5287 (setq new-ov (make-overlay beg end))
5288 (overlay-put new-ov 'todo 'separator)
5289 (overlay-put new-ov 'display todo-done-separator)
5290 (delete-overlay ov))))))))
5292 (defun todo-get-overlay (val)
5293 "Return the overlay at point whose `todo' property has value VAL."
5294 ;; Use overlays-in to find prefix overlays and check over two
5295 ;; positions to find done separator overlay.
5296 (let ((ovs (overlays-in (point) (1+ (point))))
5301 (when (eq (overlay-get ov 'todo) val)
5302 (throw 'done ov))))))
5304 (defun todo-marked-item-p ()
5305 "Non-nil if this item begins with `todo-item-mark'.
5306 In that case, return the item's prefix overlay."
5307 (let* ((ov (todo-get-overlay 'prefix))
5308 ;; If an item insertion command is called on a todo file
5309 ;; before it is visited, it has no prefix overlays yet, so
5311 (pref (when ov (overlay-get ov 'before-string)))
5313 (string-match (concat "^" (regexp-quote todo-item-mark))
5317 (defun todo-insert-with-overlays (item)
5318 "Insert ITEM at point and update prefix/priority number overlays."
5320 ;; Insertion pushes item down but not its prefix overlay. When the
5321 ;; overlay includes a mark, this would now mark the inserted ITEM,
5322 ;; so move it to the pushed down item.
5323 (let ((ov (todo-get-overlay 'prefix))
5324 (marked (todo-marked-item-p)))
5326 (when marked (move-overlay ov (point) (point))))
5327 (todo-backward-item)
5328 (todo-prefix-overlays))
5330 (defun todo-prefix-overlays ()
5331 "Update the prefix overlays of the current category's items.
5332 The overlay's value is the string `todo-prefix' or with non-nil
5333 `todo-number-prefix' an integer in the sequence from 1 to
5334 the number of todo or done items in the category indicating the
5335 item's priority. Todo and done items are numbered independently
5338 (cat-tp (or (cdr (assoc-string
5339 (todo-current-category)
5340 (nth 2 (assoc-string todo-current-todo-file
5341 todo-top-priorities-overrides))))
5342 (nth 1 (assoc-string todo-current-todo-file
5343 todo-top-priorities-overrides))
5344 todo-top-priorities))
5347 (goto-char (point-min))
5349 (when (or (todo-date-string-matcher (line-end-position))
5350 (todo-done-string-matcher (line-end-position)))
5351 (goto-char (match-beginning 0))
5353 ;; Reset number to 1 for first done item.
5354 (when (and (eq major-mode 'todo-mode)
5355 (looking-at todo-done-string-start)
5356 (looking-back (concat "^"
5357 (regexp-quote todo-category-done)
5359 (line-beginning-position 0)))
5362 (setq prefix (concat (propertize
5363 (if todo-number-prefix
5364 (number-to-string num)
5367 ;; Prefix of top priority items has a
5368 ;; distinct face in Todo mode.
5369 (if (and (eq major-mode 'todo-mode)
5373 'todo-prefix-string))
5375 (let ((ov (todo-get-overlay 'prefix))
5376 (marked (todo-marked-item-p)))
5377 ;; Prefix overlay must be at a single position so its
5378 ;; bounds aren't changed when (re)moving an item.
5379 (unless ov (setq ov (make-overlay (point) (point))))
5380 (overlay-put ov 'todo 'prefix)
5381 (overlay-put ov 'before-string (if marked
5382 (concat todo-item-mark prefix)
5386 ;; -----------------------------------------------------------------------------
5387 ;;; Generating and applying item insertion and editing key sequences
5388 ;; -----------------------------------------------------------------------------
5390 ;; Thanks to Stefan Monnier for suggesting dynamically generating item
5391 ;; insertion commands and their key bindings, and offering an elegant
5392 ;; implementation, which, however, relies on lexical scoping and so
5393 ;; cannot be used here until the Calendar code used by todo-mode.el is
5394 ;; converted to lexical binding. Hence, the following implementation
5395 ;; uses dynamic binding.
5397 (defconst todo-insert-item--parameters
5398 '((default copy) (diary nonmarking) (calendar date dayname) time (here region))
5399 "List of all item insertion parameters.
5400 Passed by `todo-insert-item' to `todo-insert-item--next-param' to
5401 dynamically create item insertion commands.")
5403 (defconst todo-insert-item--param-key-alist
5414 "List pairing item insertion parameters with their completion keys.")
5416 (defsubst todo-insert-item--keyof (param)
5417 "Return key paired with item insertion PARAM."
5418 (cdr (assoc param todo-insert-item--param-key-alist)))
5420 (defun todo-insert-item--argsleft (key list)
5421 "Return sublist of LIST whose first member corresponds to KEY."
5427 (when (equal key (todo-insert-item--keyof s))
5428 (throw 'found1 (setq sym s))))))
5435 (setq list (reverse l)))
5436 (memq (catch 'found2
5437 (dolist (e todo-insert-item--param-key-alist)
5438 (when (equal key (cdr e))
5439 (throw 'found2 (car e)))))
5442 (defsubst todo-insert-item--this-key () (char-to-string last-command-event))
5444 (defvar todo-insert-item--keys-so-far ""
5445 "String of item insertion keys so far entered for this command.")
5447 (defvar todo-insert-item--args nil)
5448 (defvar todo-insert-item--argleft nil)
5449 (defvar todo-insert-item--argsleft nil)
5450 (defvar todo-insert-item--newargsleft nil)
5452 (defun todo-insert-item--apply-args ()
5453 "Build list of arguments for item insertion and apply them.
5454 The list consists of item insertion parameters that can be passed
5455 as insertion command arguments in fixed positions. If a position
5456 in the list is not occupied by the corresponding parameter, it is
5458 (let* ((arg (list (car todo-insert-item--args)))
5459 (args (nconc (cdr todo-insert-item--args)
5460 (list (car (todo-insert-item--argsleft
5461 (todo-insert-item--this-key)
5462 todo-insert-item--argsleft)))))
5463 (arglist (if (= 4 (length args))
5465 (let ((v (make-vector 4 nil)) elt)
5467 (setq elt (pop args))
5468 (cond ((memq elt '(diary nonmarking))
5470 ((memq elt '(calendar date dayname))
5474 ((memq elt '(copy here region))
5477 (apply #'todo-insert-item--basic (nconc arg arglist))))
5479 (defun todo-insert-item--next-param (last args argsleft)
5480 "Build item insertion command from LAST, ARGS and ARGSLEFT and call it.
5481 Dynamically generate key bindings, prompting with the keys
5482 already entered and those still available."
5483 (cl-assert argsleft)
5484 (let* ((map (make-sparse-keymap))
5492 (if (memq name '(default diary calendar here))
5495 (when (memq name '(copy nonmarking dayname region))
5497 (propertize k 'face 'todo-key-prompt)
5499 (setq todo-insert-item--args args)
5500 (setq todo-insert-item--argsleft argsleft)
5502 (if (memq last '(default copy))
5504 (setq todo-insert-item--argsleft nil)
5505 (todo-insert-item--apply-args))
5506 (let ((k (todo-insert-item--keyof last)))
5507 (funcall addprompt k (make-symbol (concat (symbol-name last) ":GO!")))
5508 (define-key map (todo-insert-item--keyof last)
5509 (lambda () (interactive)
5510 (todo-insert-item--apply-args))))))
5511 (while todo-insert-item--argsleft
5512 (let ((x (car todo-insert-item--argsleft)))
5513 (setq todo-insert-item--newargsleft (cdr todo-insert-item--argsleft))
5514 (dolist (argleft (if (consp x) x (list x)))
5515 (let ((k (todo-insert-item--keyof argleft)))
5516 (funcall addprompt k argleft)
5518 (if (null todo-insert-item--newargsleft)
5519 (lambda () (interactive)
5520 (todo-insert-item--apply-args))
5521 (lambda () (interactive)
5522 (setq todo-insert-item--keys-so-far
5523 (concat todo-insert-item--keys-so-far " "
5524 (todo-insert-item--this-key)))
5525 (todo-insert-item--next-param
5526 (car (todo-insert-item--argsleft
5527 (todo-insert-item--this-key)
5528 todo-insert-item--argsleft))
5529 (nconc todo-insert-item--args
5530 (list (car (todo-insert-item--argsleft
5531 (todo-insert-item--this-key)
5532 todo-insert-item--argsleft))))
5533 (cdr (todo-insert-item--argsleft
5534 (todo-insert-item--this-key)
5535 todo-insert-item--argsleft)))))))))
5536 (setq todo-insert-item--argsleft todo-insert-item--newargsleft))
5537 (when prompt (message "Press a key (so far `%s'): %s"
5538 todo-insert-item--keys-so-far prompt))
5539 (set-transient-map map)
5540 (setq todo-insert-item--argsleft argsleft)))
5542 (defconst todo-edit-item--param-key-alist
5550 "Alist of item editing parameters and their keys.")
5552 (defconst todo-edit-item--date-param-key-alist
5560 "Alist of item date editing parameters and their keys.")
5562 (defconst todo-edit-done-item--param-key-alist
5565 "Alist of done item comment editing parameters and their keys.")
5567 (defvar todo-edit-item--prompt "Press a key (so far `e'): ")
5569 (defun todo-edit-item--next-key (params &optional arg)
5570 (let* ((map (make-sparse-keymap))
5571 (p->k (mapconcat (lambda (elt)
5573 (propertize (cdr elt) 'face
5575 (concat (symbol-name (car elt))
5576 (when (memq (car elt)
5580 (key-prompt (substitute-command-keys todo-edit-item--prompt))
5581 (this-key (let ((key (read-key (concat key-prompt p->k))))
5582 (and (characterp key) (char-to-string key))))
5583 (this-param (car (rassoc this-key params))))
5585 (`edit (todo-edit-item--text))
5586 (`header (todo-edit-item--text 'include-header))
5587 (`multiline (todo-edit-item--text 'multiline))
5588 (`add/edit (todo-edit-item--text 'comment-edit))
5589 (`delete (todo-edit-item--text 'comment-delete))
5590 (`diary (todo-edit-item--diary-inclusion))
5591 (`nonmarking (todo-edit-item--diary-inclusion 'nonmarking))
5592 (`date (let ((todo-edit-item--prompt "Press a key (so far `e d'): "))
5593 (todo-edit-item--next-key
5594 todo-edit-item--date-param-key-alist arg)))
5595 (`full (progn (todo-edit-item--header 'date)
5596 (when todo-always-add-time-string
5597 (todo-edit-item--header 'time))))
5598 (`calendar (todo-edit-item--header 'calendar))
5599 (`today (todo-edit-item--header 'today))
5600 (`dayname (todo-edit-item--header 'dayname))
5601 (`year (todo-edit-item--header 'year arg))
5602 (`month (todo-edit-item--header 'month arg))
5603 (`daynum (todo-edit-item--header 'day arg))
5604 (`time (todo-edit-item--header 'time)))))
5606 ;; -----------------------------------------------------------------------------
5607 ;;; Todo minibuffer utilities
5608 ;; -----------------------------------------------------------------------------
5610 (defcustom todo-y-with-space nil
5611 "Non-nil means allow SPC to affirm a \"y or n\" question."
5615 (defun todo-y-or-n-p (prompt)
5616 "Ask \"y or n\" question PROMPT and return t if answer is \"y\".
5617 Also return t if answer is \"Y\", but unlike `y-or-n-p', allow
5618 SPC to affirm the question only if option `todo-y-with-space' is
5620 (unless todo-y-with-space
5621 (define-key query-replace-map " " 'ignore))
5624 (define-key query-replace-map " " 'act)))
5626 (defun todo-category-completions (&optional archive)
5627 "Return a list of completions for `todo-read-category'.
5628 Each element of the list is a cons of a category name and the
5629 file or list of files (as short file names) it is in. The files
5630 are either the current (or if there is none, the default) todo
5631 file plus the files listed in `todo-category-completions-files',
5632 or, with non-nil ARCHIVE, the current archive file.
5634 Before calculating the completions, update the value of
5635 `todo-category-completions-files' in case any files named in it
5638 (dolist (f todo-category-completions-files)
5639 (unless (file-exists-p (todo-absolute-file-name f))
5640 (setq todo-category-completions-files
5641 (delete f todo-category-completions-files))
5644 (let ((pl (> (length deleted) 1))
5645 (names (mapconcat (lambda (f) (concat "\"" f "\"")) deleted ", ")))
5646 (message (concat "File" (if pl "s" "") " " names " ha" (if pl "ve" "s")
5647 " been deleted and removed from\n"
5648 "the list of category completion files")))
5649 (todo-reevaluate-category-completions-files-defcustom)
5650 (custom-set-default 'todo-category-completions-files
5651 (symbol-value 'todo-category-completions-files))
5653 (let* ((curfile (or todo-current-todo-file
5654 (and todo-show-current-file
5655 todo-global-current-todo-file)
5656 (todo-absolute-file-name todo-default-todo-file)))
5657 (files (or (unless archive
5658 (mapcar 'todo-absolute-file-name
5659 todo-category-completions-files))
5662 ;; If file was just added, it has no category completions.
5663 (unless (zerop (buffer-size (find-buffer-visiting curfile)))
5664 (unless (member curfile todo-archives)
5665 (add-to-list 'files curfile))
5666 (dolist (f files listall)
5667 (with-current-buffer (find-file-noselect f 'nowarn)
5669 (unless (derived-mode-p 'todo-archive-mode) (todo-archive-mode))
5670 (unless (derived-mode-p 'todo-mode) (todo-mode)))
5671 ;; Ensure category is properly displayed in case user
5672 ;; switches to file via a non-Todo mode command. And if
5673 ;; done items in category are visible, keep them visible.
5674 (let ((done todo-show-with-done))
5675 (when (> (buffer-size) (- (point-max) (point-min)))
5677 (goto-char (point-min))
5678 (setq done (re-search-forward todo-done-string-start nil t))))
5679 (let ((todo-show-with-done done))
5680 (save-excursion (todo-category-select))))
5684 (goto-char (point-min))
5685 (setq listf (read (buffer-substring-no-properties
5686 (line-beginning-position)
5687 (line-end-position)))))))
5688 (mapc (lambda (elt) (let* ((cat (car elt))
5689 (la-elt (assoc cat listall)))
5691 (setcdr la-elt (append (list (cdr la-elt))
5693 (push (cons cat f) listall))))
5696 (defun todo-read-file-name (prompt &optional archive mustmatch)
5697 "Choose and return the name of a todo file, prompting with PROMPT.
5699 Show completions with TAB or SPC; the names are shown in short
5700 form but the absolute truename is returned. With non-nil ARCHIVE
5701 return the absolute truename of a todo archive file. With non-nil
5702 MUSTMATCH the name of an existing file must be chosen;
5703 otherwise, a new file name is allowed."
5704 (let* ((completion-ignore-case todo-completion-ignore-case)
5705 (files (mapcar 'todo-short-file-name
5706 ;; (funcall todo-files-function archive)))
5707 (if archive todo-archives todo-files)))
5708 (file (completing-read prompt files nil mustmatch nil nil
5710 ;; If user hit RET without
5711 ;; choosing a file, default to
5712 ;; current or default file.
5713 (todo-short-file-name
5714 (or todo-current-todo-file
5715 (and todo-show-current-file
5716 todo-global-current-todo-file)
5717 (todo-absolute-file-name
5718 todo-default-todo-file)))
5719 ;; Trigger prompt for initial file.
5721 (unless (file-exists-p todo-directory)
5722 (make-directory todo-directory))
5723 (unless (or mustmatch (member file files))
5724 (setq file (todo-validate-name file 'file)))
5725 (setq file (file-truename (concat todo-directory file
5726 (if archive ".toda" ".todo"))))))
5728 (defun todo-read-category (prompt &optional match-type file)
5729 "Choose and return a category name, prompting with PROMPT.
5730 Show completions for existing categories with TAB or SPC.
5732 The argument MATCH-TYPE specifies the matching requirements on
5733 the category name: with the value `todo' or `archive' the name
5734 must complete to that of an existing todo or archive category,
5735 respectively; with the value `add' the name must not be that of
5736 an existing category; with all other values both existing and new
5737 valid category names are accepted.
5739 With non-nil argument FILE prompt for a file and complete only
5740 against categories in that file; otherwise complete against all
5741 categories from `todo-category-completions-files'."
5742 ;; Allow SPC to insert spaces, for adding new category names.
5743 (let ((map minibuffer-local-completion-map))
5744 (define-key map " " nil)
5745 (let* ((add (eq match-type 'add))
5746 (archive (eq match-type 'archive))
5747 (file0 (when (and file (> (length todo-files) 1))
5748 (todo-read-file-name (concat "Choose a" (if archive
5751 " file: ") archive t)))
5752 (completions (unless file0 (todo-category-completions archive)))
5753 (categories (cond (file0
5754 (with-current-buffer
5755 (find-file-noselect file0 'nowarn)
5756 (unless (derived-mode-p 'todo-mode) (todo-mode))
5757 (let ((todo-current-todo-file file0))
5759 ((and add (not file))
5760 (with-current-buffer
5761 (find-file-noselect todo-current-todo-file)
5765 (completion-ignore-case todo-completion-ignore-case)
5766 (cat (completing-read prompt categories nil
5767 (eq match-type 'todo) nil nil
5768 ;; Unless we're adding a category via
5769 ;; todo-add-category, set default
5770 ;; for existing categories to the
5771 ;; current category of the chosen
5772 ;; file or else of the current file.
5773 (if (and categories (not add))
5774 (with-current-buffer
5777 todo-current-todo-file
5778 (todo-absolute-file-name
5779 todo-default-todo-file)))
5780 (todo-current-category))
5781 ;; Trigger prompt for initial category.
5783 (catfil (cdr (assoc cat completions)))
5784 (str "Category \"%s\" from which file (TAB for choices)? "))
5785 ;; If we do category completion and the chosen category name
5786 ;; occurs in more than one file, prompt to choose one file.
5787 (unless (or file0 add (not catfil))
5788 (setq file0 (file-truename
5791 (todo-absolute-file-name
5792 (let ((files (mapcar 'todo-short-file-name catfil)))
5793 (completing-read (format str cat) files)))))))
5794 ;; Default to the current file.
5795 (unless file0 (setq file0 todo-current-todo-file))
5796 ;; First validate only a name passed interactively from
5797 ;; todo-add-category, which must be of a nonexistent category.
5798 (unless (and (assoc cat categories) (not add))
5799 ;; Validate only against completion categories.
5800 (let ((todo-categories categories))
5801 (setq cat (todo-validate-name cat 'category)))
5802 ;; When user enters a nonexistent category name by jumping or
5803 ;; moving, confirm that it should be added, then validate.
5805 (if (todo-y-or-n-p (format "Add new category \"%s\" to file \"%s\"? "
5806 cat (todo-short-file-name file0)))
5808 (when (assoc cat categories)
5809 (let ((todo-categories categories))
5810 (setq cat (todo-validate-name cat 'category))))
5811 ;; Restore point and narrowing after adding new
5812 ;; category, to avoid moving to beginning of file when
5813 ;; moving marked items to a new category
5814 ;; (todo-move-item).
5817 (todo-add-category file0 cat))))
5818 ;; If we decide not to add a category, exit without returning.
5822 (defun todo-validate-name (name type)
5823 "Prompt for new NAME for TYPE until it is valid, then return it.
5824 TYPE can be either of the symbols `file' or `category'."
5825 (let ((categories todo-categories)
5826 (files (mapcar 'todo-short-file-name todo-files))
5830 (cond ((string= "" name)
5832 (cond ((eq type 'file)
5834 "Enter a non-empty file name: "
5835 ;; Empty string passed by todo-show to
5836 ;; prompt for initial todo file.
5837 (concat "Initial file name ["
5838 todo-initial-file "]: ")))
5839 ((eq type 'category)
5841 "Enter a non-empty category name: "
5842 ;; Empty string passed by todo-show to
5843 ;; prompt for initial category of a new
5845 (concat "Initial category name ["
5846 todo-initial-category "]: "))))))
5847 ((string-match "\\`\\s-+\\'" name)
5849 "Enter a name that does not contain only white space: "))
5850 ((and (eq type 'file) (member name files))
5851 (setq prompt "Enter a non-existing file name: "))
5852 ((and (eq type 'category) (assoc name categories))
5853 (setq prompt "Enter a non-existing category name: ")))
5854 (setq name (if (or (and (eq type 'file) files)
5855 (and (eq type 'category) categories))
5856 (completing-read prompt (cond ((eq type 'file)
5858 ((eq type 'category)
5860 ;; Offer default initial name.
5861 (completing-read prompt (if (eq type 'file)
5864 nil nil (if (eq type 'file)
5866 todo-initial-category))))))
5869 ;; Adapted from calendar-read-date and calendar-date-string.
5870 (defun todo-read-date (&optional arg mo yr)
5871 "Prompt for Gregorian date and return it in the current format.
5873 With non-nil ARG, prompt for and return only the date component
5874 specified by ARG, which can be one of these symbols:
5875 `month' (prompt for name, return name or number according to
5876 value of `calendar-date-display-form'), `day' of month, or
5877 `year'. The value of each of these components can be `*',
5878 indicating an unspecified month, day, or year.
5880 When ARG is `day', non-nil arguments MO and YR determine the
5881 number of the last the day of the month."
5882 (let (year monthname month day
5883 dayname) ; Needed by calendar-date-display-form.
5884 (when (or (not arg) (eq arg 'year))
5885 (while (if (natnump year) (< year 1) (not (eq year '*)))
5886 (setq year (read-from-minibuffer
5887 "Year (>0 or RET for this year or * for any year): "
5888 nil nil t nil (number-to-string
5889 (calendar-extract-year
5890 (calendar-current-date)))))))
5891 (when (or (not arg) (eq arg 'month))
5892 (let* ((marray todo-month-name-array)
5893 (mlist (append marray nil))
5894 (mabarray todo-month-abbrev-array)
5895 (mablist (append mabarray nil))
5896 (completion-ignore-case todo-completion-ignore-case))
5897 (setq monthname (completing-read
5898 "Month name (RET for current month, * for any month): "
5900 (calendar-month-name (calendar-extract-month
5901 (calendar-current-date)) t))
5902 month (1+ (- (length mlist)
5903 (length (or (member monthname mlist)
5904 (member monthname mablist))))))
5905 (setq monthname (aref mabarray (1- month)))))
5906 (when (or (not arg) (eq arg 'day))
5907 (let ((last (let ((mm (or month mo))
5909 ;; If month is unspecified, use a month with 31
5910 ;; days for checking day of month input. Does
5911 ;; Calendar do anything special when * is
5912 ;; currently a shorter month?
5913 (if (= mm 13) (setq mm 1))
5914 ;; If year is unspecified, use a leap year to
5916 (if (eq year '*) (setq yy 2012))
5917 (calendar-last-day-of-month mm yy))))
5918 (while (if (natnump day) (or (< day 1) (> day last)) (not (eq day '*)))
5919 (setq day (read-from-minibuffer
5920 (format "Day (1-%d or RET for today or * for any day): "
5922 nil nil t nil (number-to-string
5923 (calendar-extract-day
5924 (calendar-current-date))))))))
5925 ;; Stringify read values (monthname is already a string).
5926 (and year (setq year (if (eq year '*)
5928 (number-to-string year))))
5929 (and day (setq day (if (eq day '*)
5931 (number-to-string day))))
5932 (and month (setq month (if (eq month '*)
5934 (number-to-string month))))
5936 (cond ((eq arg 'year) year)
5939 (if (memq 'month calendar-date-display-form)
5942 (mapconcat 'eval calendar-date-display-form ""))))
5944 (defun todo-read-dayname ()
5945 "Choose name of a day of the week with completion and return it."
5946 (let ((completion-ignore-case todo-completion-ignore-case))
5947 (completing-read "Enter a day name: "
5948 (append calendar-day-name-array nil)
5951 (defun todo-read-time ()
5952 "Prompt for and return a valid clock time as a string.
5954 Valid time strings are those matching `diary-time-regexp'.
5955 Typing `<return>' at the prompt returns the current time, if the
5956 user option `todo-always-add-time-string' is non-nil, otherwise
5957 the empty string (i.e., no time string)."
5960 (setq answer (read-string "Enter a clock time: " nil nil
5961 (when todo-always-add-time-string
5962 (substring (current-time-string) 11 16))))
5963 (when (or (string= "" answer)
5964 (string-match diary-time-regexp answer))
5968 ;; -----------------------------------------------------------------------------
5969 ;;; Customization groups and utilities
5970 ;; -----------------------------------------------------------------------------
5973 "Create and maintain categorized lists of todo items."
5974 :link '(emacs-commentary-link "todo")
5978 (defgroup todo-edit nil
5979 "User options for adding and editing todo items."
5983 (defgroup todo-categories nil
5984 "User options for Todo Categories mode."
5988 (defgroup todo-filtered nil
5989 "User options for Todo Filter Items mode."
5993 (defgroup todo-display nil
5994 "User display options for Todo mode."
5998 (defgroup todo-faces nil
5999 "Faces for the Todo modes."
6003 (defun todo-set-show-current-file (symbol value)
6004 "The :set function for user option `todo-show-current-file'."
6005 (custom-set-default symbol value)
6007 (add-hook 'pre-command-hook 'todo-show-current-file nil t)
6008 (remove-hook 'pre-command-hook 'todo-show-current-file t)))
6010 (defun todo-reset-prefix (symbol value)
6011 "The :set function for `todo-prefix' and `todo-number-prefix'."
6012 (let ((oldvalue (symbol-value symbol))
6013 (files todo-file-buffers))
6014 (custom-set-default symbol value)
6015 (when (not (equal value oldvalue))
6017 (with-current-buffer (find-file-noselect f)
6018 ;; Activate the new setting in the current category.
6019 (save-excursion (todo-category-select)))))))
6021 (defun todo-reset-nondiary-marker (symbol value)
6022 "The :set function for user option `todo-nondiary-marker'."
6023 (let* ((oldvalue (symbol-value symbol))
6024 (files (append todo-files todo-archives
6025 (directory-files todo-directory t "\\.tod[rty]$" t))))
6026 (custom-set-default symbol value)
6027 ;; Need to reset these to get font-locking right.
6028 (setq todo-nondiary-start (nth 0 todo-nondiary-marker)
6029 todo-nondiary-end (nth 1 todo-nondiary-marker)
6030 todo-date-string-start
6031 ;; See comment in defvar of `todo-date-string-start'.
6032 (concat "^\\(" (regexp-quote todo-nondiary-start) "\\|"
6033 (regexp-quote diary-nonmarking-symbol) "\\)?"))
6034 (when (not (equal value oldvalue))
6036 (let ((buf (find-buffer-visiting f)))
6037 (with-current-buffer (find-file-noselect f)
6038 (let (buffer-read-only)
6040 (goto-char (point-min))
6042 (if (re-search-forward
6043 (concat "^\\(" todo-done-string-start "[^][]+] \\)?"
6044 "\\(?1:" (regexp-quote (car oldvalue))
6045 "\\)" todo-date-pattern "\\( "
6046 diary-time-regexp "\\)?\\(?2:"
6047 (regexp-quote (cadr oldvalue)) "\\)")
6050 (replace-match (nth 0 value) t t nil 1)
6051 (replace-match (nth 1 value) t t nil 2))
6054 (when (derived-mode-p 'todo-mode 'todo-archive-mode)
6055 (todo-category-select))
6057 (kill-buffer)))))))))
6059 (defun todo-reset-done-separator-string (symbol value)
6060 "The :set function for `todo-done-separator-string'."
6061 (let ((oldvalue (symbol-value symbol))
6062 (files todo-file-buffers)
6063 (sep todo-done-separator))
6064 (custom-set-default symbol value)
6065 (when (not (equal value oldvalue))
6067 (with-current-buffer (find-file-noselect f)
6068 (let (buffer-read-only)
6069 (setq todo-done-separator (todo-done-separator))
6070 (when (= 1 (length value))
6071 (todo-reset-done-separator sep)))
6072 (todo-category-select))))))
6074 (defun todo-reset-done-string (symbol value)
6075 "The :set function for user option `todo-done-string'."
6076 (let ((oldvalue (symbol-value symbol))
6077 (files (append todo-files todo-archives
6078 (directory-files todo-directory t "\\.todr$" t))))
6079 (custom-set-default symbol value)
6080 ;; Need to reset this to get font-locking right.
6081 (setq todo-done-string-start
6082 (concat "^\\[" (regexp-quote todo-done-string)))
6083 (when (not (equal value oldvalue))
6085 (let ((buf (find-buffer-visiting f)))
6086 (with-current-buffer (find-file-noselect f)
6087 (let (buffer-read-only)
6089 (goto-char (point-min))
6091 (if (re-search-forward
6092 (concat "^" (regexp-quote todo-nondiary-start)
6093 "\\(" (regexp-quote oldvalue) "\\)")
6095 (replace-match value t t nil 1)
6098 (when (derived-mode-p 'todo-mode 'todo-archive-mode)
6099 (todo-category-select))
6101 (kill-buffer)))))))))
6103 (defun todo-reset-comment-string (symbol value)
6104 "The :set function for user option `todo-comment-string'."
6105 (let ((oldvalue (symbol-value symbol))
6106 (files (append todo-files todo-archives
6107 (directory-files todo-directory t "\\.todr$" t))))
6108 (custom-set-default symbol value)
6109 (when (not (equal value oldvalue))
6111 (let ((buf (find-buffer-visiting f)))
6112 (with-current-buffer (find-file-noselect f)
6113 (let (buffer-read-only)
6115 (goto-char (point-min))
6117 (if (re-search-forward
6118 (concat "\\[\\(" (regexp-quote oldvalue)
6121 (replace-match value t t nil 1)
6124 (when (derived-mode-p 'todo-mode 'todo-archive-mode)
6125 (todo-category-select))
6127 (kill-buffer)))))))))
6129 (defun todo-reset-highlight-item (symbol value)
6130 "The :set function for user option `todo-highlight-item'."
6131 (let ((oldvalue (symbol-value symbol))
6132 (files (append todo-files todo-archives
6133 (directory-files todo-directory t "\\.tod[rty]$" t))))
6134 (custom-set-default symbol value)
6135 (when (not (equal value oldvalue))
6137 (let ((buf (find-buffer-visiting f)))
6139 (with-current-buffer buf
6143 (hl-line-mode -1)))))))))
6145 (defun todo-reevaluate-filelist-defcustoms ()
6146 "Reevaluate defcustoms that provide choice list of todo files."
6147 (custom-set-default 'todo-default-todo-file
6148 (symbol-value 'todo-default-todo-file))
6149 (todo-reevaluate-default-file-defcustom)
6150 (custom-set-default 'todo-filter-files (symbol-value 'todo-filter-files))
6151 (todo-reevaluate-filter-files-defcustom)
6152 (custom-set-default 'todo-category-completions-files
6153 (symbol-value 'todo-category-completions-files))
6154 (todo-reevaluate-category-completions-files-defcustom))
6156 (defun todo-reevaluate-default-file-defcustom ()
6157 "Reevaluate defcustom of `todo-default-todo-file'.
6158 Called after adding or deleting a todo file. If the value of
6159 `todo-default-todo-file' before calling this function was
6160 associated with an existing file, keep that value."
6161 ;; (let ((curval todo-default-todo-file))
6163 (defcustom todo-default-todo-file (todo-short-file-name
6164 (car (funcall todo-files-function)))
6165 "Todo file visited by first session invocation of `todo-show'."
6166 :type (when todo-files
6167 `(radio ,@(mapcar (lambda (f) (list 'const f))
6168 (mapcar 'todo-short-file-name
6169 (funcall todo-files-function)))))
6171 ;; (when (and curval (file-exists-p (todo-absolute-file-name curval)))
6172 ;; (custom-set-default 'todo-default-todo-file curval)
6173 ;; ;; (custom-reevaluate-setting 'todo-default-todo-file)
6177 (defun todo-reevaluate-category-completions-files-defcustom ()
6178 "Reevaluate defcustom of `todo-category-completions-files'.
6179 Called after adding or deleting a todo file."
6180 (eval (defcustom todo-category-completions-files nil
6181 "List of files for building `todo-read-category' completions."
6182 :type `(set ,@(mapcar (lambda (f) (list 'const f))
6183 (mapcar 'todo-short-file-name
6184 (funcall todo-files-function))))
6187 (defun todo-reevaluate-filter-files-defcustom ()
6188 "Reevaluate defcustom of `todo-filter-files'.
6189 Called after adding or deleting a todo file."
6190 (eval (defcustom todo-filter-files nil
6191 "List of files for multifile item filtering."
6192 :type `(set ,@(mapcar (lambda (f) (list 'const f))
6193 (mapcar 'todo-short-file-name
6194 (funcall todo-files-function))))
6197 ;; -----------------------------------------------------------------------------
6199 ;; -----------------------------------------------------------------------------
6201 (defun todo-nondiary-marker-matcher (lim)
6202 "Search for todo item nondiary markers within LIM for font-locking."
6203 (re-search-forward (concat "^\\(?1:" (regexp-quote todo-nondiary-start) "\\)"
6204 todo-date-pattern "\\(?: " diary-time-regexp
6205 "\\)?\\(?2:" (regexp-quote todo-nondiary-end) "\\)")
6208 (defun todo-diary-nonmarking-matcher (lim)
6209 "Search for diary nonmarking symbol within LIM for font-locking."
6210 (re-search-forward (concat "^\\(?1:" (regexp-quote diary-nonmarking-symbol)
6211 "\\)" todo-date-pattern) lim t))
6213 (defun todo-date-string-matcher (lim)
6214 "Search for todo item date string within LIM for font-locking."
6216 (concat todo-date-string-start "\\(?1:" todo-date-pattern "\\)") lim t))
6218 (defun todo-time-string-matcher (lim)
6219 "Search for todo item time string within LIM for font-locking."
6220 (re-search-forward (concat todo-date-string-start todo-date-pattern
6221 " \\(?1:" diary-time-regexp "\\)") lim t))
6223 (defun todo-diary-expired-matcher (lim)
6224 "Search for expired diary item date within LIM for font-locking."
6225 (when (re-search-forward (concat "^\\(?:"
6226 (regexp-quote diary-nonmarking-symbol)
6227 "\\)?\\(?1:" todo-date-pattern "\\) \\(?2:"
6228 diary-time-regexp "\\)?") lim t)
6229 (let* ((date (match-string-no-properties 1))
6230 (time (match-string-no-properties 2))
6231 ;; Function days-between requires a non-empty time string.
6232 (date-time (concat date " " (or time "00:00"))))
6233 (or (and (not (string-match ".+day\\|\\*" date))
6234 (< (days-between date-time (current-time-string)) 0))
6235 (todo-diary-expired-matcher lim)))))
6237 (defun todo-done-string-matcher (lim)
6238 "Search for done todo item header within LIM for font-locking."
6239 (re-search-forward (concat todo-done-string-start
6243 (defun todo-comment-string-matcher (lim)
6244 "Search for done todo item comment within LIM for font-locking."
6245 (re-search-forward (concat "\\[\\(?1:" todo-comment-string "\\):")
6248 (defun todo-category-string-matcher-1 (lim)
6249 "Search for todo category name within LIM for font-locking.
6250 This is for fontifying category and file names appearing in Todo
6251 Filtered Items mode following done items."
6252 (if (eq major-mode 'todo-filtered-items-mode)
6253 (re-search-forward (concat todo-done-string-start todo-date-pattern
6254 "\\(?: " diary-time-regexp
6255 ;; Use non-greedy operator to prevent
6256 ;; capturing possible following non-diary
6258 "\\)?] \\(?1:\\[.+?\\]\\)")
6261 (defun todo-category-string-matcher-2 (lim)
6262 "Search for todo category name within LIM for font-locking.
6263 This is for fontifying category and file names appearing in Todo
6264 Filtered Items mode following todo (not done) items."
6265 (if (eq major-mode 'todo-filtered-items-mode)
6266 (re-search-forward (concat todo-date-string-start todo-date-pattern
6267 "\\(?: " diary-time-regexp "\\)?\\(?:"
6268 (regexp-quote todo-nondiary-end)
6269 "\\)? \\(?1:\\[.+\\]\\)")
6272 (defvar todo-nondiary-face 'todo-nondiary)
6273 (defvar todo-date-face 'todo-date)
6274 (defvar todo-time-face 'todo-time)
6275 (defvar todo-diary-expired-face 'todo-diary-expired)
6276 (defvar todo-done-sep-face 'todo-done-sep)
6277 (defvar todo-done-face 'todo-done)
6278 (defvar todo-comment-face 'todo-comment)
6279 (defvar todo-category-string-face 'todo-category-string)
6280 (defvar todo-font-lock-keywords
6282 '(todo-nondiary-marker-matcher 1 todo-nondiary-face t)
6283 '(todo-nondiary-marker-matcher 2 todo-nondiary-face t)
6284 ;; diary-lib.el uses font-lock-constant-face for diary-nonmarking-symbol.
6285 '(todo-diary-nonmarking-matcher 1 font-lock-constant-face t)
6286 '(todo-date-string-matcher 1 todo-date-face t)
6287 '(todo-time-string-matcher 1 todo-time-face t)
6288 '(todo-done-string-matcher 0 todo-done-face t)
6289 '(todo-comment-string-matcher 1 todo-comment-face t)
6290 '(todo-category-string-matcher-1 1 todo-category-string-face t t)
6291 '(todo-category-string-matcher-2 1 todo-category-string-face t t)
6292 '(todo-diary-expired-matcher 1 todo-diary-expired-face t)
6293 '(todo-diary-expired-matcher 2 todo-diary-expired-face t t)
6295 "Font-locking for Todo modes.")
6297 ;; -----------------------------------------------------------------------------
6299 ;; -----------------------------------------------------------------------------
6301 (defvar todo-key-bindings-t
6303 ("Af" todo-find-archive)
6304 ("Ac" todo-choose-archive)
6305 ("Ad" todo-archive-done-item)
6306 ("Cv" todo-toggle-view-done-items)
6307 ("v" todo-toggle-view-done-items)
6308 ("Ca" todo-add-category)
6309 ("Cr" todo-rename-category)
6310 ("Cg" todo-merge-category)
6311 ("Cm" todo-move-category)
6312 ("Ck" todo-delete-category)
6313 ("Cts" todo-set-top-priorities-in-category)
6314 ("Cey" todo-edit-category-diary-inclusion)
6315 ("Cek" todo-edit-category-diary-nonmarking)
6316 ("Fa" todo-add-file)
6317 ("Fr" todo-rename-file)
6318 ("Ff" todo-find-filtered-items-file)
6319 ("FV" todo-toggle-view-done-only)
6320 ("V" todo-toggle-view-done-only)
6321 ("Ftt" todo-filter-top-priorities)
6322 ("Ftm" todo-filter-top-priorities-multifile)
6323 ("Fts" todo-set-top-priorities-in-file)
6324 ("Fyy" todo-filter-diary-items)
6325 ("Fym" todo-filter-diary-items-multifile)
6326 ("Fxx" todo-filter-regexp-items)
6327 ("Fxm" todo-filter-regexp-items-multifile)
6328 ("e" todo-edit-item)
6329 ("d" todo-item-done)
6330 ("i" todo-insert-item)
6331 ("k" todo-delete-item)
6332 ("m" todo-move-item)
6333 ("u" todo-item-undone)
6334 ([remap newline] newline-and-indent)
6336 "List of key bindings for Todo mode only.")
6338 (defvar todo-key-bindings-t+a+f
6340 ("C*" todo-mark-category)
6341 ("Cu" todo-unmark-category)
6342 ("Fh" todo-toggle-item-header)
6343 ("h" todo-toggle-item-header)
6344 ("Fk" todo-delete-file)
6345 ("Fe" todo-edit-file)
6346 ("FH" todo-toggle-item-highlighting)
6347 ("H" todo-toggle-item-highlighting)
6348 ("FN" todo-toggle-prefix-numbers)
6349 ("N" todo-toggle-prefix-numbers)
6350 ("PB" todo-print-buffer)
6351 ("PF" todo-print-buffer-to-file)
6352 ("b" todo-backward-category)
6353 ("d" todo-item-done)
6354 ("f" todo-forward-category)
6355 ("j" todo-jump-to-category)
6356 ("n" todo-next-item)
6357 ("p" todo-previous-item)
6362 "List of key bindings for Todo, Archive, and Filtered Items modes.")
6364 (defvar todo-key-bindings-t+a
6366 ("Fc" todo-show-categories-table)
6368 ("X" todo-clear-matches)
6369 ("*" todo-toggle-mark-item)
6371 "List of key bindings for Todo and Todo Archive modes.")
6373 (defvar todo-key-bindings-t+f
6375 ("l" todo-lower-item-priority)
6376 ("r" todo-raise-item-priority)
6377 ("#" todo-set-item-priority)
6379 "List of key bindings for Todo and Todo Filtered Items modes.")
6381 (defvar todo-mode-map
6382 (let ((map (make-keymap)))
6383 ;; Don't suppress digit keys, so they can supply prefix arguments.
6384 (suppress-keymap map)
6385 (dolist (kb todo-key-bindings-t)
6386 (define-key map (nth 0 kb) (nth 1 kb)))
6387 (dolist (kb todo-key-bindings-t+a+f)
6388 (define-key map (nth 0 kb) (nth 1 kb)))
6389 (dolist (kb todo-key-bindings-t+a)
6390 (define-key map (nth 0 kb) (nth 1 kb)))
6391 (dolist (kb todo-key-bindings-t+f)
6392 (define-key map (nth 0 kb) (nth 1 kb)))
6394 "Todo mode keymap.")
6396 (defvar todo-archive-mode-map
6397 (let ((map (make-sparse-keymap)))
6398 (suppress-keymap map)
6399 (dolist (kb todo-key-bindings-t+a+f)
6400 (define-key map (nth 0 kb) (nth 1 kb)))
6401 (dolist (kb todo-key-bindings-t+a)
6402 (define-key map (nth 0 kb) (nth 1 kb)))
6403 (define-key map "a" 'todo-jump-to-archive-category)
6404 (define-key map "u" 'todo-unarchive-items)
6406 "Todo Archive mode keymap.")
6408 (defvar todo-edit-mode-map
6409 (let ((map (make-sparse-keymap)))
6410 (define-key map "\C-x\C-q" 'todo-edit-quit)
6411 (define-key map [remap newline] 'newline-and-indent)
6413 "Todo Edit mode keymap.")
6415 (defvar todo-categories-mode-map
6416 (let ((map (make-sparse-keymap)))
6417 (suppress-keymap map)
6418 (define-key map "c" 'todo-sort-categories-alphabetically-or-numerically)
6419 (define-key map "t" 'todo-sort-categories-by-todo)
6420 (define-key map "y" 'todo-sort-categories-by-diary)
6421 (define-key map "d" 'todo-sort-categories-by-done)
6422 (define-key map "a" 'todo-sort-categories-by-archived)
6423 (define-key map "#" 'todo-set-category-number)
6424 (define-key map "l" 'todo-lower-category)
6425 (define-key map "r" 'todo-raise-category)
6426 (define-key map "n" 'todo-next-button)
6427 (define-key map "p" 'todo-previous-button)
6428 (define-key map [tab] 'todo-next-button)
6429 (define-key map [backtab] 'todo-previous-button)
6430 (define-key map "q" 'todo-quit)
6432 "Todo Categories mode keymap.")
6434 (defvar todo-filtered-items-mode-map
6435 (let ((map (make-sparse-keymap)))
6436 (suppress-keymap map)
6437 (dolist (kb todo-key-bindings-t+a+f)
6438 (define-key map (nth 0 kb) (nth 1 kb)))
6439 (dolist (kb todo-key-bindings-t+f)
6440 (define-key map (nth 0 kb) (nth 1 kb)))
6441 (define-key map "g" 'todo-go-to-source-item)
6442 (define-key map [remap newline] 'todo-go-to-source-item)
6444 "Todo Filtered Items mode keymap.")
6447 todo-menu todo-mode-map "Todo Menu"
6450 ["Next Item" todo-next-item t]
6451 ["Previous Item" todo-previous-item t]
6453 ["Next Category" todo-forward-category t]
6454 ["Previous Category" todo-backward-category t]
6455 ["Jump to Another Category" todo-jump-to-category t]
6457 ["Visit Another Todo File" todo-show t]
6458 ["Visit Archive" todo-find-archive t]
6459 ["Visit Filtered Items File" todo-find-filtered-items-file t]
6462 ["Insert New Item" todo-insert-item t]
6463 ["Edit Item" todo-edit-item t]
6464 ["Lower Item Priority" todo-lower-item-priority t]
6465 ["Raise Item Priority" todo-raise-item-priority t]
6466 ["Set Item Priority" todo-set-item-priority t]
6467 ["Mark/Unmark Item" todo-toggle-mark-item t]
6468 ["Move (Recategorize) Item" todo-move-item t]
6469 ["Delete Item" todo-delete-item t]
6470 ["Mark and Bury Done Item" todo-item-done t]
6471 ["Undo Done Item" todo-item-undone t]
6472 ["Archive Done Item" todo-archive-done-item t]
6474 ["Add New Category" todo-add-category t]
6475 ["Rename Current Category" todo-rename-category t]
6476 ["Delete Current Category" todo-delete-category t]
6477 ["Move Current Category" todo-move-category t]
6478 ["Merge Current Category" todo-merge-category t]
6480 ["Add New Todo File" todo-add-file t]
6481 ["Rename Todo File" todo-rename-file t]
6482 ["Delete Todo File" todo-delete-file t]
6483 ["Edit Todo File" todo-edit-file t]
6485 ("Searching and Item Filtering"
6486 ["Search Todo File" todo-search t]
6487 ["Clear Match Highlighting" todo-clear-matches t]
6489 ["Set Top Priorities in File" todo-set-top-priorities-in-file t]
6490 ["Set Top Priorities in Category" todo-set-top-priorities-in-category t]
6491 ["Filter Top Priorities" todo-filter-top-priorities t]
6492 ["Filter Multifile Top Priorities" todo-filter-top-priorities-multifile t]
6493 ["Filter Diary Items" todo-filter-diary-items t]
6494 ["Filter Multifile Diary Items" todo-filter-diary-items-multifile t]
6495 ["Filter Regexp" todo-filter-regexp-items t]
6496 ["Filter Multifile Regexp" todo-filter-regexp-items-multifile t]
6498 ("Display and Printing"
6499 ["Show/Hide Done Items" todo-toggle-view-done-items t]
6500 ["Show/Hide Done Items Only" todo-toggle-view-done-only t]
6501 ["Show/Hide Item Highlighting" todo-toggle-item-highlighting t]
6502 ["Show/Hide Item Numbering" todo-toggle-prefix-numbers t]
6503 ["Show/Hide Item Header" todo-toggle-item-header t]
6505 ["Display Table of Categories" todo-show-categories-table t]
6507 ["Print Category" todo-print-buffer t]
6508 ["Print Category to File" todo-print-buffer-to-file t]
6511 ["Save Todo File" todo-save t]
6512 ["Quit Todo Mode" todo-quit t]
6515 ;; -----------------------------------------------------------------------------
6516 ;;; Hook functions and mode definitions
6517 ;; -----------------------------------------------------------------------------
6519 (defun todo-show-current-file ()
6520 "Visit current instead of default todo file with `todo-show'.
6521 Added to `pre-command-hook' in Todo mode when user option
6522 `todo-show-current-file' is set to non-nil."
6523 (setq todo-global-current-todo-file todo-current-todo-file))
6525 ;; (defun todo-display-as-todo-file ()
6526 ;; "Show todo files correctly when visited from outside of Todo mode.
6527 ;; Added to `find-file-hook' in Todo mode and Todo Archive mode."
6528 ;; (and (member this-command todo-visit-files-commands)
6529 ;; (= (- (point-max) (point-min)) (buffer-size))
6530 ;; (member major-mode '(todo-mode todo-archive-mode))
6531 ;; (todo-category-select)))
6533 ;; (defun todo-add-to-buffer-list ()
6534 ;; "Add name of just visited todo file to `todo-file-buffers'.
6535 ;; This function is added to `find-file-hook' in Todo mode."
6536 ;; (let ((filename (file-truename (buffer-file-name))))
6537 ;; (when (member filename todo-files)
6538 ;; (add-to-list 'todo-file-buffers filename))))
6540 (defun todo-update-buffer-list ()
6541 "Make current Todo mode buffer file car of `todo-file-buffers'.
6542 This function is added to `post-command-hook' in Todo mode."
6543 (let ((filename (file-truename (buffer-file-name))))
6544 (unless (eq (car todo-file-buffers) filename)
6545 (setq todo-file-buffers
6546 (cons filename (delete filename todo-file-buffers))))))
6548 (defun todo-reset-global-current-todo-file ()
6549 "Update the value of `todo-global-current-todo-file'.
6550 This becomes the latest existing todo file or, if there is none,
6551 the value of `todo-default-todo-file'.
6552 This function is added to `kill-buffer-hook' in Todo mode."
6553 (let ((filename (file-truename (buffer-file-name))))
6554 (setq todo-file-buffers (delete filename todo-file-buffers))
6555 (setq todo-global-current-todo-file
6556 (or (car todo-file-buffers)
6557 (todo-absolute-file-name todo-default-todo-file)))))
6559 (defun todo-reset-and-enable-done-separator ()
6560 "Show resized done items separator overlay after window change.
6561 Added to `window-configuration-change-hook' in Todo mode."
6562 (when (= 1 (length todo-done-separator-string))
6563 (let ((sep todo-done-separator))
6564 (setq todo-done-separator (todo-done-separator))
6565 (save-match-data (todo-reset-done-separator sep)))))
6567 (defun todo-modes-set-1 ()
6568 "Make some settings that apply to multiple Todo modes."
6569 (setq-local font-lock-defaults '(todo-font-lock-keywords t))
6570 (setq-local revert-buffer-function 'todo-revert-buffer)
6571 (setq-local tab-width todo-indent-to-here)
6572 (setq-local indent-line-function 'todo-indent)
6573 (when todo-wrap-lines
6575 (setq wrap-prefix (make-string todo-indent-to-here 32))))
6577 (defun todo-modes-set-2 ()
6578 "Make some settings that apply to multiple Todo modes."
6579 (add-to-invisibility-spec 'todo)
6580 (setq buffer-read-only t)
6581 (when (and (boundp 'desktop-save-mode) desktop-save-mode)
6582 (setq-local desktop-save-buffer 'todo-desktop-save-buffer))
6583 (when (boundp 'hl-line-range-function)
6584 (setq-local hl-line-range-function
6585 (lambda() (save-excursion
6586 (when (todo-item-end)
6587 (cons (todo-item-start)
6588 (todo-item-end))))))))
6590 (defun todo-modes-set-3 ()
6591 "Make some settings that apply to multiple Todo modes."
6592 (setq-local todo-categories (todo-set-categories))
6593 (setq-local todo-category-number 1)
6594 ;; (add-hook 'find-file-hook 'todo-display-as-todo-file nil t)
6597 (put 'todo-mode 'mode-class 'special)
6600 (define-derived-mode todo-mode special-mode "Todo"
6601 "Major mode for displaying, navigating and editing todo lists.
6604 (if (called-interactively-p 'any)
6606 (substitute-command-keys
6607 "Type `\\[todo-show]' to enter Todo mode"))
6611 ;; Initialize todo-current-todo-file.
6612 (when (member (file-truename (buffer-file-name))
6613 (funcall todo-files-function))
6614 (setq-local todo-current-todo-file (file-truename (buffer-file-name))))
6615 (setq-local todo-show-done-only nil)
6616 (setq-local todo-categories-with-marks nil)
6617 ;; (add-hook 'find-file-hook 'todo-add-to-buffer-list nil t)
6618 (add-hook 'post-command-hook 'todo-update-buffer-list nil t)
6619 (when todo-show-current-file
6620 (add-hook 'pre-command-hook 'todo-show-current-file nil t))
6621 (add-hook 'window-configuration-change-hook
6622 'todo-reset-and-enable-done-separator nil t)
6623 (add-hook 'kill-buffer-hook 'todo-reset-global-current-todo-file nil t)))
6625 (put 'todo-archive-mode 'mode-class 'special)
6627 ;; If todo-mode is parent, all todo-mode key bindings appear to be
6628 ;; available in todo-archive-mode (e.g. shown by C-h m).
6630 (define-derived-mode todo-archive-mode special-mode "Todo-Arch"
6631 "Major mode for archived todo categories.
6633 \\{todo-archive-mode-map}"
6637 (setq-local todo-current-todo-file (file-truename (buffer-file-name)))
6638 (setq-local todo-show-done-only t))
6640 (defun todo-mode-external-set ()
6641 "Set `todo-categories' externally to `todo-current-todo-file'."
6642 (setq-local todo-current-todo-file todo-global-current-todo-file)
6643 (let ((cats (with-current-buffer
6644 ;; Can't use find-buffer-visiting when
6645 ;; `todo-show-categories-table' is called on first
6646 ;; invocation of `todo-show', since there is then
6647 ;; no buffer visiting the current file.
6648 (find-file-noselect todo-current-todo-file 'nowarn)
6650 ;; In Todo Edit mode todo-categories is now nil
6651 ;; since it uses same buffer as Todo mode but
6652 ;; doesn't have the latter's local variables.
6654 (goto-char (point-min))
6655 (read (buffer-substring-no-properties
6656 (line-beginning-position)
6657 (line-end-position))))))))
6658 (setq-local todo-categories cats)))
6660 (define-derived-mode todo-edit-mode text-mode "Todo-Ed"
6661 "Major mode for editing multiline todo items.
6663 \\{todo-edit-mode-map}"
6665 (todo-mode-external-set)
6666 (setq buffer-read-only nil))
6668 (put 'todo-categories-mode 'mode-class 'special)
6670 (define-derived-mode todo-categories-mode special-mode "Todo-Cats"
6671 "Major mode for displaying and editing todo categories.
6673 \\{todo-categories-mode-map}"
6674 (todo-mode-external-set))
6676 (put 'todo-filtered-items-mode 'mode-class 'special)
6679 (define-derived-mode todo-filtered-items-mode special-mode "Todo-Fltr"
6680 "Mode for displaying and reprioritizing top priority Todo.
6682 \\{todo-filtered-items-mode-map}"
6686 ;; -----------------------------------------------------------------------------
6687 (provide 'todo-mode)
6689 ;;; todo-mode.el ends here