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)
240 "Invalid value: must be distinct from `todo-item-mark'")
242 :initialize 'custom-initialize-default
243 :set 'todo-reset-prefix
244 :group 'todo-display)
246 (defcustom todo-number-prefix t
247 "Non-nil to prefix items with consecutively increasing integers.
248 These reflect the priorities of the items in each category."
250 :initialize 'custom-initialize-default
251 :set 'todo-reset-prefix
252 :group 'todo-display)
254 (defun todo-mode-line-control (cat)
255 "Return a mode line control for todo or archive file buffers.
256 Argument CAT is the name of the current todo category.
257 This function is the value of the user variable
258 `todo-mode-line-function'."
259 (let ((file (todo-short-file-name todo-current-todo-file)))
260 (format "%s category %d: %s" file todo-category-number cat)))
262 (defcustom todo-mode-line-function 'todo-mode-line-control
263 "Function that returns a mode line control for Todo mode buffers.
264 The function expects one argument holding the name of the current
265 todo category. The resulting control becomes the local value of
266 `mode-line-buffer-identification' in each Todo mode buffer."
268 :group 'todo-display)
270 (defcustom todo-highlight-item nil
271 "Non-nil means highlight items at point."
273 :initialize 'custom-initialize-default
274 :set 'todo-reset-highlight-item
275 :group 'todo-display)
277 (defcustom todo-wrap-lines t
278 "Non-nil to activate Visual Line mode and use wrap prefix."
280 :group 'todo-display)
282 (defcustom todo-indent-to-here 3
283 "Number of spaces to indent continuation lines of items.
284 This must be a positive number to ensure such items are fully
285 shown in the Fancy Diary display."
286 :type '(integer :validate
288 (unless (> (widget-value widget) 0)
289 (widget-put widget :error
290 "Invalid value: must be a positive integer")
292 :group 'todo-display)
294 (defun todo-indent ()
295 "Indent from point to `todo-indent-to-here'."
296 (indent-to todo-indent-to-here todo-indent-to-here))
298 (defcustom todo-show-with-done nil
299 "Non-nil to display done items in all categories."
301 :group 'todo-display)
303 ;; -----------------------------------------------------------------------------
305 ;; -----------------------------------------------------------------------------
307 (defface todo-key-prompt
308 '((t (:weight bold)))
309 "Face for making keys in item insertion prompt stand out."
313 ;; '((t :inherit font-lock-warning-face))
317 (:weight bold :foreground "Red1"))
321 (:weight bold :foreground "Pink"))
325 (:weight bold :foreground "Red1"))
329 (:weight bold :foreground "Pink"))
334 (:weight bold :inverse-video t)))
335 "Face for marks on marked items."
338 (defface todo-prefix-string
339 ;; '((t :inherit font-lock-constant-face))
340 '((((class grayscale) (background light))
341 (:foreground "LightGray" :weight bold :underline t))
342 (((class grayscale) (background dark))
343 (:foreground "Gray50" :weight bold :underline t))
344 (((class color) (min-colors 88) (background light)) (:foreground "dark cyan"))
345 (((class color) (min-colors 88) (background dark)) (:foreground "Aquamarine"))
346 (((class color) (min-colors 16) (background light)) (:foreground "CadetBlue"))
347 (((class color) (min-colors 16) (background dark)) (:foreground "Aquamarine"))
348 (((class color) (min-colors 8)) (:foreground "magenta"))
349 (t (:weight bold :underline t)))
350 "Face for todo item prefix or numerical priority string."
353 (defface todo-top-priority
354 ;; bold font-lock-comment-face
355 '((default :weight bold)
356 (((class grayscale) (background light)) :foreground "DimGray" :slant italic)
357 (((class grayscale) (background dark)) :foreground "LightGray" :slant italic)
358 (((class color) (min-colors 88) (background light)) :foreground "Firebrick")
359 (((class color) (min-colors 88) (background dark)) :foreground "chocolate1")
360 (((class color) (min-colors 16) (background light)) :foreground "red")
361 (((class color) (min-colors 16) (background dark)) :foreground "red1")
362 (((class color) (min-colors 8) (background light)) :foreground "red")
363 (((class color) (min-colors 8) (background dark)) :foreground "yellow")
365 "Face for top priority todo item numerical priority string.
366 The item's priority number string has this face if the number is
367 less than or equal the category's top priority setting."
370 (defface todo-nondiary
371 ;; '((t :inherit font-lock-type-face))
372 '((((class grayscale) (background light)) :foreground "Gray90" :weight bold)
373 (((class grayscale) (background dark)) :foreground "DimGray" :weight bold)
374 (((class color) (min-colors 88) (background light)) :foreground "ForestGreen")
375 (((class color) (min-colors 88) (background dark)) :foreground "PaleGreen")
376 (((class color) (min-colors 16) (background light)) :foreground "ForestGreen")
377 (((class color) (min-colors 16) (background dark)) :foreground "PaleGreen")
378 (((class color) (min-colors 8)) :foreground "green")
379 (t :weight bold :underline t))
380 "Face for non-diary markers around todo item date/time header."
384 '((t :inherit diary))
385 "Face for the date string of a todo item."
389 '((t :inherit diary-time))
390 "Face for the time string of a todo item."
393 (defface todo-diary-expired
394 ;; Doesn't contrast enough with todo-date (= diary) face.
395 ;; ;; '((t :inherit warning))
396 ;; '((default :weight bold)
397 ;; (((class color) (min-colors 16)) :foreground "DarkOrange")
398 ;; (((class color)) :foreground "yellow"))
399 ;; bold font-lock-function-name-face
400 '((default :weight bold)
401 (((class color) (min-colors 88) (background light)) :foreground "Blue1")
402 (((class color) (min-colors 88) (background dark)) :foreground "LightSkyBlue")
403 (((class color) (min-colors 16) (background light)) :foreground "Blue")
404 (((class color) (min-colors 16) (background dark)) :foreground "LightSkyBlue")
405 (((class color) (min-colors 8)) :foreground "blue")
406 (t :inverse-video t))
407 "Face for expired dates of diary items."
410 (defface todo-done-sep
411 ;; '((t :inherit font-lock-builtin-face))
412 '((((class grayscale) (background light)) :foreground "LightGray" :weight bold)
413 (((class grayscale) (background dark)) :foreground "DimGray" :weight bold)
414 (((class color) (min-colors 88) (background light)) :foreground "dark slate blue")
415 (((class color) (min-colors 88) (background dark)) :foreground "LightSteelBlue")
416 (((class color) (min-colors 16) (background light)) :foreground "Orchid")
417 (((class color) (min-colors 16) (background dark)) :foreground "LightSteelBlue")
418 (((class color) (min-colors 8)) :foreground "blue" :weight bold)
420 "Face for separator string between done and not done todo items."
424 ;; '((t :inherit font-lock-keyword-face))
425 '((((class grayscale) (background light)) :foreground "LightGray" :weight bold)
426 (((class grayscale) (background dark)) :foreground "DimGray" :weight bold)
427 (((class color) (min-colors 88) (background light)) :foreground "Purple")
428 (((class color) (min-colors 88) (background dark)) :foreground "Cyan1")
429 (((class color) (min-colors 16) (background light)) :foreground "Purple")
430 (((class color) (min-colors 16) (background dark)) :foreground "Cyan")
431 (((class color) (min-colors 8)) :foreground "cyan" :weight bold)
433 "Face for done todo item header string."
436 (defface todo-comment
437 ;; '((t :inherit font-lock-comment-face))
438 '((((class grayscale) (background light))
439 :foreground "DimGray" :weight bold :slant italic)
440 (((class grayscale) (background dark))
441 :foreground "LightGray" :weight bold :slant italic)
442 (((class color) (min-colors 88) (background light))
443 :foreground "Firebrick")
444 (((class color) (min-colors 88) (background dark))
445 :foreground "chocolate1")
446 (((class color) (min-colors 16) (background light))
448 (((class color) (min-colors 16) (background dark))
450 (((class color) (min-colors 8) (background light))
452 (((class color) (min-colors 8) (background dark))
453 :foreground "yellow")
454 (t :weight bold :slant italic))
455 "Face for comments appended to done todo items."
459 ;; '((t :inherit match))
463 (:background "yellow1"))
467 (:background "RoyalBlue3"))
471 (:foreground "black" :background "yellow"))
475 (:foreground "white" :background "blue"))
480 (:background "gray")))
481 "Face for matches found by `todo-search'."
485 ;; '((t :inherit widget-field))
487 (:foreground "black" :background "yellow3"))
488 (((class grayscale color)
490 (:background "gray85"))
491 (((class grayscale color)
493 (:background "dim gray"))
496 "Face for buttons in table of categories."
499 (defface todo-sorted-column
504 (:background "grey85"))
507 (:background "grey85" :foreground "grey10"))
509 (:background "gray")))
510 "Face for sorted column in table of categories."
513 (defface todo-archived-only
514 ;; '((t (:inherit (shadow))))
517 (:foreground "grey50"))
520 (:foreground "grey70"))
522 (:foreground "gray")))
523 "Face for archived-only category names in table of categories."
526 (defface todo-category-string
527 ;; '((t :inherit font-lock-type-face))
528 '((((class grayscale) (background light)) :foreground "Gray90" :weight bold)
529 (((class grayscale) (background dark)) :foreground "DimGray" :weight bold)
530 (((class color) (min-colors 88) (background light)) :foreground "ForestGreen")
531 (((class color) (min-colors 88) (background dark)) :foreground "PaleGreen")
532 (((class color) (min-colors 16) (background light)) :foreground "ForestGreen")
533 (((class color) (min-colors 16) (background dark)) :foreground "PaleGreen")
534 (((class color) (min-colors 8)) :foreground "green")
535 (t :weight bold :underline t))
536 "Face for category-file header in Todo Filtered Items mode."
539 ;; -----------------------------------------------------------------------------
540 ;;; Entering and exiting
541 ;; -----------------------------------------------------------------------------
543 ;; (defcustom todo-visit-files-commands (list 'find-file 'dired-find-file)
544 ;; "List of file finding commands for `todo-display-as-todo-file'.
545 ;; Invoking these commands to visit a todo file or todo archive file
546 ;; calls `todo-show' or `todo-find-archive', so that the file is
547 ;; displayed correctly."
548 ;; :type '(repeat function)
551 (defun todo-short-file-name (file)
552 "Return the short form of todo file FILE's name.
553 This lacks the extension and directory components."
555 (file-name-sans-extension (file-name-nondirectory file))))
557 (defcustom todo-default-todo-file (todo-short-file-name
558 (car (funcall todo-files-function)))
559 "Todo file visited by first session invocation of `todo-show'."
560 :type (when todo-files
561 `(radio ,@(mapcar (lambda (f) (list 'const f))
562 (mapcar 'todo-short-file-name
563 (funcall todo-files-function)))))
566 (defcustom todo-show-current-file t
567 "Non-nil to make `todo-show' visit the current todo file.
568 Otherwise, `todo-show' always visits `todo-default-todo-file'."
570 :initialize 'custom-initialize-default
571 :set 'todo-set-show-current-file
574 (defcustom todo-show-first 'first
575 "What action to take on first use of `todo-show' on a file."
576 :type '(choice (const :tag "Show first category" first)
577 (const :tag "Show table of categories" table)
578 (const :tag "Show top priorities" top)
579 (const :tag "Show diary items" diary)
580 (const :tag "Show regexp items" regexp))
583 (defcustom todo-add-item-if-new-category t
584 "Non-nil to prompt for an item after adding a new category."
588 (defcustom todo-initial-file "Todo"
589 "Default file name offered on adding first todo file."
593 (defcustom todo-initial-category "Todo"
594 "Default category name offered on initializing a new todo file."
598 (defcustom todo-category-completions-files nil
599 "List of files for building `todo-read-category' completions."
600 :type `(set ,@(mapcar (lambda (f) (list 'const f))
601 (mapcar 'todo-short-file-name
602 (funcall todo-files-function))))
605 (defcustom todo-completion-ignore-case nil
606 "Non-nil means case is ignored by `todo-read-*' functions."
611 (defun todo-show (&optional solicit-file interactive)
612 "Visit a todo file and display one of its categories.
614 When invoked in Todo mode, prompt for which todo file to visit.
615 When invoked outside of Todo mode with non-nil prefix argument
616 SOLICIT-FILE prompt for which todo file to visit; otherwise visit
617 `todo-default-todo-file'. Subsequent invocations from outside
618 of Todo mode revisit this file or, with option
619 `todo-show-current-file' non-nil (the default), whichever todo
620 file was last visited.
622 If you call this command before you have created any todo file in
623 the current format, and you have an todo file in old format, it
624 will ask you whether to convert that file and show it.
625 Otherwise, calling this command before any todo file exists
626 prompts for a file name and an initial category (defaulting to
627 `todo-initial-file' and `todo-initial-category'), creates both of
628 these, visits the file and displays the category, and if option
629 `todo-add-item-if-new-category' is non-nil (the default), prompts
632 The first invocation of this command on an existing todo file
633 interacts with the option `todo-show-first': if its value is
634 `first' (the default), show the first category in the file; if
635 its value is `table', show the table of categories in the file;
636 if its value is one of `top', `diary' or `regexp', show the
637 corresponding saved top priorities, diary items, or regexp items
638 file, if any. Subsequent invocations always show the file's
639 current (i.e., last displayed) category.
641 In Todo mode just the category's unfinished todo items are shown
642 by default. The done items are hidden, but typing
643 `\\[todo-toggle-view-done-items]' displays them below the todo
644 items. With non-nil user option `todo-show-with-done' both todo
645 and done items are always shown on visiting a category.
647 Invoking this command in Todo Archive mode visits the
648 corresponding todo file, displaying the corresponding category."
650 (when todo-default-todo-file
651 (todo-check-file (todo-absolute-file-name todo-default-todo-file)))
653 ;; Before initializing the first todo first, check if there is a
654 ;; legacy todo file and if so, offer to convert to the current
655 ;; format and make it the first new todo file.
656 (unless todo-default-todo-file
657 (let ((legacy-todo-file (if (boundp 'todo-file-do)
659 (locate-user-emacs-file "todo-do" ".todo-do"))))
660 (when (and (file-exists-p legacy-todo-file)
661 (y-or-n-p (concat "Do you want to convert a copy of your "
662 "old todo file to the new format? ")))
663 (when (todo-convert-legacy-files)
664 (throw 'shown nil)))))
667 (show-first todo-show-first)
668 (file (cond ((or solicit-file
670 (memq major-mode '(todo-mode
672 todo-filtered-items-mode))))
673 (if (funcall todo-files-function)
674 (todo-read-file-name "Choose a todo file to visit: "
676 (user-error "There are no todo files")))
677 ((and (eq major-mode 'todo-archive-mode)
678 ;; Called noninteractively via todo-quit
679 ;; to jump to corresponding category in
682 (setq cat (todo-current-category))
683 (concat (file-name-sans-extension
684 todo-current-todo-file) ".todo"))
686 (or todo-current-todo-file
687 (and todo-show-current-file
688 todo-global-current-todo-file)
689 (todo-absolute-file-name todo-default-todo-file)
692 (unless todo-default-todo-file
693 ;; We just initialized the first todo file, so make it the default.
694 (setq todo-default-todo-file (todo-short-file-name file)
696 (todo-reevaluate-default-file-defcustom))
697 (unless (member file todo-visited)
698 ;; Can't setq t-c-t-f here, otherwise wrong file shown when
699 ;; todo-show is called from todo-show-categories-table.
700 (let ((todo-current-todo-file file))
701 (cond ((eq todo-show-first 'table)
702 (todo-show-categories-table))
703 ((memq todo-show-first '(top diary regexp))
704 (let* ((shortf (todo-short-file-name file))
705 (fi-file (todo-absolute-file-name
706 shortf todo-show-first)))
707 (when (eq todo-show-first 'regexp)
708 (let ((rxfiles (directory-files todo-directory t
710 (when (and rxfiles (> (length rxfiles) 1))
711 (let ((rxf (mapcar 'todo-short-file-name rxfiles)))
712 (setq fi-file (todo-absolute-file-name
714 "Choose a regexp items file: "
716 (if (file-exists-p fi-file)
720 (set-buffer (find-file-noselect fi-file 'nowarn)))
721 (unless (derived-mode-p 'todo-filtered-items-mode)
722 (todo-filtered-items-mode)))
723 (message "There is no %s file for %s"
724 (cond ((eq todo-show-first 'top)
726 ((eq todo-show-first 'diary)
728 ((eq todo-show-first 'regexp)
731 (setq todo-show-first 'first)))))))
732 (when (or (member file todo-visited)
733 (eq todo-show-first 'first))
734 (unless (todo-check-file file) (throw 'end nil))
735 ;; If todo-show is called from the minibuffer, don't visit
736 ;; the todo file there.
737 (set-window-buffer (if (minibufferp) (minibuffer-selected-window)
739 (set-buffer (find-file-noselect file 'nowarn)))
740 (if (equal (file-name-extension (buffer-file-name)) "toda")
741 (unless (derived-mode-p 'todo-archive-mode) (todo-archive-mode))
742 (unless (derived-mode-p 'todo-mode) (todo-mode)))
743 ;; When quitting an archive file, show the corresponding
744 ;; category in the corresponding todo file, if it exists.
745 (when (assoc cat todo-categories)
746 (setq todo-category-number (todo-category-number cat)))
747 ;; If this is a new todo file, add its first category.
748 (when (zerop (buffer-size))
749 ;; Don't confuse an erased buffer with a fresh buffer for
750 ;; adding a new todo file -- it might have been erased by
751 ;; mistake or due to a bug (e.g. Bug#20832).
752 (when (buffer-modified-p)
753 (error "Buffer is empty but modified, please report a bug"))
756 (setq todo-category-number
757 (todo-add-category todo-current-todo-file "")
758 add-item todo-add-item-if-new-category
761 ;; If the category was added, save the file now, so we
762 ;; don't risk having an empty todo file, which would
763 ;; signal an error if we tried to visit it later,
764 ;; since doing that looks for category boundaries.
766 ;; If user cancels before adding the category, clean up
767 ;; and exit, so we have a fresh slate the next time.
769 ;; (setq todo-files (funcall todo-files-function))
770 (setq todo-files (delete file todo-files))
772 (setq todo-default-todo-file nil
773 todo-current-todo-file nil)
774 (todo-reevaluate-default-file-defcustom))
777 (save-excursion (todo-category-select))
778 (when add-item (todo-insert-item--basic)))
779 (setq todo-show-first show-first)
780 (add-to-list 'todo-visited file)))))
783 "Save the current todo file."
785 (cond ((eq major-mode 'todo-filtered-items-mode)
786 (todo-check-filtered-items-file)
787 (todo-save-filtered-items-buffer))
791 (defvar todo-descending-counts)
794 "Exit the current Todo-related buffer.
795 Depending on the specific mode, this either kills the buffer or
796 buries it and restores state as needed."
798 (let ((buf (current-buffer)))
799 (cond ((eq major-mode 'todo-categories-mode)
800 ;; Postpone killing buffer till after calling todo-show, to
801 ;; prevent killing todo-mode buffer.
802 (setq todo-descending-counts nil)
803 ;; Ensure todo-show calls todo-show-categories-table only on
804 ;; first invocation per file.
805 (when (eq todo-show-first 'table)
806 (add-to-list 'todo-visited todo-current-todo-file))
809 ((eq major-mode 'todo-filtered-items-mode)
811 (unless (eq major-mode 'todo-mode) (todo-show)))
812 ((eq major-mode 'todo-archive-mode)
813 ;; Have to write a newly created archive to file to avoid
814 ;; subsequent errors.
816 (let ((todo-file (concat todo-directory
817 (todo-short-file-name todo-current-todo-file)
819 (if (todo-check-file todo-file)
821 (message "There is no todo file for this archive")))
822 ;; When todo-check-file runs in todo-show, it kills the
823 ;; buffer if the archive file was deleted externally.
824 (when (buffer-live-p buf) (bury-buffer buf)))
825 ((eq major-mode 'todo-mode)
827 ;; If we just quit archive mode, just burying the buffer
828 ;; in todo-mode would return to archive.
829 (set-window-buffer (selected-window)
830 (set-buffer (other-buffer)))
831 (bury-buffer buf)))))
833 ;; -----------------------------------------------------------------------------
834 ;;; Navigation between and within categories
835 ;; -----------------------------------------------------------------------------
837 (defcustom todo-skip-archived-categories nil
838 "Non-nil to handle categories with only archived items specially.
840 Sequential category navigation using \\[todo-forward-category]
841 or \\[todo-backward-category] skips categories that contain only
842 archived items. Other commands still recognize these categories.
843 In Todo Categories mode (\\[todo-show-categories-table]) these
844 categories shown in `todo-archived-only' face and pressing the
845 category button visits the category in the archive instead of the
848 :group 'todo-display)
850 (defun todo-forward-category (&optional back)
851 "Visit the numerically next category in this todo file.
852 If the current category is the highest numbered, visit the first
853 category. With non-nil argument BACK, visit the numerically
854 previous category (the highest numbered one, if the current
855 category is the first)."
857 (setq todo-category-number
858 (1+ (mod (- todo-category-number (if back 2 0))
859 (length todo-categories))))
860 (when todo-skip-archived-categories
861 (while (and (zerop (todo-get-count 'todo))
862 (zerop (todo-get-count 'done))
863 (not (zerop (todo-get-count 'archived))))
864 (setq todo-category-number
865 (apply (if back '1- '1+) (list todo-category-number)))))
866 (todo-category-select)
867 (goto-char (point-min)))
869 (defun todo-backward-category ()
870 "Visit the numerically previous category in this todo file.
871 If the current category is the highest numbered, visit the first
874 (todo-forward-category t))
876 (defvar todo-categories-buffer)
878 (defun todo-jump-to-category (&optional file where)
879 "Prompt for a category in a todo file and jump to it.
881 With non-nil FILE (interactively a prefix argument), prompt for a
882 specific todo file and choose (with TAB completion) a category
883 in it to jump to; otherwise, choose and jump to any category in
884 either the current todo file or a file in
885 `todo-category-completions-files'.
887 Also accept a non-existing category name and ask whether to add a
888 new category by that name; on confirmation, add it and jump to
889 that category, and if option `todo-add-item-if-new-category' is
890 non-nil (the default), then prompt for the first item.
892 In noninteractive calls non-nil WHERE specifies either the goal
893 category or its file. If its value is `archive', the choice of
894 categories is restricted to the current archive file or the
895 archive you were prompted to choose; this is used by
896 `todo-jump-to-archive-category'. If its value is the name of a
897 category, jump directly to that category; this is used in Todo
900 ;; If invoked outside of Todo mode and there is not yet any Todo
901 ;; file, initialize one.
902 (if (null (funcall todo-files-function))
904 (let* ((archive (eq where 'archive))
905 (cat (unless archive where))
906 (file0 (when cat ; We're in Todo Categories mode.
907 ;; With non-nil `todo-skip-archived-categories'
908 ;; jump to archive file of a category with only
910 (if (and todo-skip-archived-categories
911 (zerop (todo-get-count 'todo cat))
912 (zerop (todo-get-count 'done cat))
913 (not (zerop (todo-get-count 'archived cat))))
914 (concat (file-name-sans-extension
915 todo-current-todo-file) ".toda")
916 ;; Otherwise, jump to current todo file.
917 todo-current-todo-file)))
918 (len (length todo-categories))
919 (cat+file (unless cat
920 (todo-read-category "Jump to category: "
921 (if archive 'archive) file)))
922 (add-item (and todo-add-item-if-new-category
923 (> (length todo-categories) len)))
924 (category (or cat (car cat+file))))
925 (unless cat (setq file0 (cdr cat+file)))
926 (with-current-buffer (find-file-noselect file0 'nowarn)
927 (setq todo-current-todo-file file0)
928 ;; If called from Todo Categories mode, clean up before jumping.
929 (if (string= (buffer-name) todo-categories-buffer)
931 (set-window-buffer (selected-window)
932 (set-buffer (find-buffer-visiting file0)))
933 (unless todo-global-current-todo-file
934 (setq todo-global-current-todo-file todo-current-todo-file))
935 (todo-category-number category)
936 (todo-category-select)
937 (goto-char (point-min))
938 (when add-item (todo-insert-item--basic))))))
940 (defun todo-next-item (&optional count)
941 "Move point down to the beginning of the next item.
942 With positive numerical prefix COUNT, move point COUNT items
945 If the category's done items are hidden, this command also moves
946 point to the empty line below the last todo item from any higher
947 item in the category, i.e., when invoked with or without a prefix
948 argument. If the category's done items are visible, this command
949 called with a prefix argument only moves point to a lower item,
950 e.g., with point on the last todo item and called with prefix 1,
951 it moves point to the first done item; but if called with point
952 on the last todo item without a prefix argument, it moves point
953 the the empty line above the done items separator."
955 ;; It's not worth the trouble to allow prefix arg value < 1, since
956 ;; we have the corresponding command.
957 (cond ((and current-prefix-arg (< count 1))
958 (user-error "The prefix argument must be a positive number"))
960 (todo-forward-item count))
962 (todo-forward-item))))
964 (defun todo-previous-item (&optional count)
965 "Move point up to start of item with next higher priority.
966 With positive numerical prefix COUNT, move point COUNT items
969 If the category's done items are visible, this command called
970 with a prefix argument only moves point to a higher item, e.g.,
971 with point on the first done item and called with prefix 1, it
972 moves to the last todo item; but if called with point on the
973 first done item without a prefix argument, it moves point the the
974 empty line above the done items separator."
976 ;; Avoid moving to bob if on the first item but not at bob.
977 (when (> (line-number-at-pos) 1)
978 ;; It's not worth the trouble to allow prefix arg value < 1, since
979 ;; we have the corresponding command.
980 (cond ((and current-prefix-arg (< count 1))
981 (user-error "The prefix argument must be a positive number"))
983 (todo-backward-item count))
985 (todo-backward-item)))))
987 ;; -----------------------------------------------------------------------------
988 ;;; Display toggle commands
989 ;; -----------------------------------------------------------------------------
991 (defun todo-toggle-prefix-numbers ()
992 "Hide item numbering if shown, show if hidden."
996 (goto-char (point-min))
997 (let* ((ov (todo-get-overlay 'prefix))
998 (show-done (re-search-forward todo-done-string-start nil t))
999 (todo-show-with-done show-done)
1000 (todo-number-prefix (not (equal (overlay-get ov 'before-string)
1002 (if (eq major-mode 'todo-filtered-items-mode)
1003 (todo-prefix-overlays)
1004 (todo-category-select))))))
1006 (defun todo-toggle-view-done-items ()
1007 "Show hidden or hide visible done items in current category."
1009 (if (zerop (todo-get-count 'done (todo-current-category)))
1010 (message "There are no done items in this category.")
1011 (let ((opoint (point)))
1012 (goto-char (point-min))
1013 (let* ((shown (re-search-forward todo-done-string-start nil t))
1014 (todo-show-with-done (not shown)))
1015 (todo-category-select)
1017 ;; If start of done items sections is below the bottom of the
1018 ;; window, make it visible.
1021 (goto-char (point-min))
1022 (re-search-forward todo-done-string-start nil t)))
1023 (if (not (pos-visible-in-window-p shown))
1025 (goto-char opoint)))))))
1027 (defun todo-toggle-view-done-only ()
1028 "Switch between displaying only done or only todo items."
1030 (setq todo-show-done-only (not todo-show-done-only))
1031 (todo-category-select))
1033 (defun todo-toggle-item-highlighting ()
1034 "Highlight or unhighlight the todo item the cursor is on."
1036 (eval-and-compile (require 'hl-line))
1037 (when (memq major-mode
1038 '(todo-mode todo-archive-mode todo-filtered-items-mode))
1043 (defun todo-toggle-item-header ()
1044 "Hide or show item date-time headers in the current file.
1045 With done items, this hides only the done date-time string, not
1046 the the original date-time string."
1050 (goto-char (point-min))
1051 (let ((ov (todo-get-overlay 'header)))
1053 (remove-overlays 1 (1+ (buffer-size)) 'todo 'header)
1055 (goto-char (point-min))
1057 (when (re-search-forward
1058 (concat todo-item-start
1059 "\\( " diary-time-regexp "\\)?"
1060 (regexp-quote todo-nondiary-end) "? ")
1062 (setq ov (make-overlay (match-beginning 0) (match-end 0) nil t))
1063 (overlay-put ov 'todo 'header)
1064 (overlay-put ov 'display ""))
1065 (todo-forward-item)))))))
1067 ;; -----------------------------------------------------------------------------
1068 ;;; File and category editing
1069 ;; -----------------------------------------------------------------------------
1071 (defun todo-add-file ()
1072 "Name and initialize a new todo file.
1073 Interactively, prompt for a category and display it, and if
1074 option `todo-add-item-if-new-category' is non-nil (the default),
1075 prompt for the first item.
1076 Noninteractively, return the name of the new file."
1078 (let* ((prompt (concat "Enter name of new todo file "
1079 "(TAB or SPC to see current names): "))
1080 (file (todo-read-file-name prompt)))
1081 ;; Don't accept the name of an existing todo file.
1082 (setq file (todo-absolute-file-name
1083 (todo-validate-name (todo-short-file-name file) 'file)))
1084 (with-current-buffer (get-buffer-create file)
1086 (write-region (point-min) (point-max) file nil 'nomessage nil t)
1088 (setq todo-files (funcall todo-files-function))
1089 (todo-reevaluate-filelist-defcustoms)
1090 (if (called-interactively-p 'any)
1092 (set-window-buffer (selected-window)
1093 (set-buffer (find-file-noselect file)))
1094 (setq todo-current-todo-file file)
1098 (defun todo-rename-file (&optional arg)
1099 "Rename the current todo file.
1100 With prefix ARG, prompt for a todo file and rename it.
1101 If there are corresponding archive or filtered items files,
1102 rename these accordingly. If there are live buffers visiting
1103 these files, also rename them accordingly."
1105 (let* ((oname (or (and arg
1106 (todo-read-file-name "Choose a file to rename: "
1108 (buffer-file-name)))
1109 (soname (todo-short-file-name oname))
1110 (nname (todo-read-file-name "New name for this file: "))
1111 (snname (todo-short-file-name nname))
1112 (files (directory-files todo-directory t
1113 (concat ".*" (regexp-quote soname)
1114 ".*\.tod[aorty]$") t)))
1116 (let* ((sfname (todo-short-file-name f))
1117 (fext (file-name-extension f t))
1118 (fbuf (find-buffer-visiting f))
1119 (fbname (buffer-name fbuf)))
1120 (when (string-match (regexp-quote soname) sfname)
1121 (let* ((snfname (replace-match snname t t sfname))
1122 (nfname (concat todo-directory snfname fext)))
1123 (rename-file f nfname)
1125 (with-current-buffer fbuf
1126 (set-visited-file-name nfname t t)
1127 (cond ((member fext '(".todo" ".toda"))
1128 (setq todo-current-todo-file (buffer-file-name))
1129 (setq mode-line-buffer-identification
1130 (funcall todo-mode-line-function
1131 (todo-current-category))))
1134 (replace-regexp-in-string
1135 (regexp-quote soname) snname fbname))))))))))
1136 (setq todo-files (funcall todo-files-function)
1137 todo-archives (funcall todo-files-function t))
1138 (when (string= todo-default-todo-file soname)
1139 (setq todo-default-todo-file snname))
1140 (when (string= todo-global-current-todo-file oname)
1141 (setq todo-global-current-todo-file nname))
1142 (todo-reevaluate-filelist-defcustoms)))
1144 (defun todo-delete-file ()
1145 "Delete the current todo, archive or filtered items file.
1146 If the todo file has a corresponding archive file, or vice versa,
1147 prompt whether to delete that as well. Also kill the buffers
1148 visiting the deleted files."
1150 (let* ((file1 (buffer-file-name))
1151 (todo (eq major-mode 'todo-mode))
1152 (archive (eq major-mode 'todo-archive-mode))
1153 (filtered (eq major-mode 'todo-filtered-items-mode))
1154 (file1-sn (todo-short-file-name file1))
1155 (file2 (concat todo-directory file1-sn (cond (todo ".toda")
1156 (archive ".todo"))))
1157 (buf1 (current-buffer))
1158 (buf2 (when file2 (find-buffer-visiting file2)))
1159 (prompt1 (concat "Delete " (cond (todo "todo")
1161 (filtered "filtered items"))
1163 (prompt2 (concat "Also delete the corresponding "
1164 (cond (todo "archive") (archive "todo")) " file "
1165 (when buf2 "and kill the buffer visiting it? ")))
1166 (delete1 (yes-or-no-p (format prompt1 file1-sn)))
1167 (delete2 (when (and delete1 (or (file-exists-p file2) buf2))
1168 (yes-or-no-p prompt2))))
1170 (when (file-exists-p file1) (delete-file file1))
1171 (setq todo-visited (delete file1 todo-visited))
1175 (when (file-exists-p file2) (delete-file file2))
1176 (setq todo-visited (delete file2 todo-visited))
1177 (and buf2 (kill-buffer buf2)))
1178 ;; If we deleted an archive but not its todo file, update the
1179 ;; latter's category sexp.
1180 (when (equal (file-name-extension file2) "todo")
1181 (with-current-buffer (or buf2 (find-file-noselect file2))
1185 (goto-char (point-min))
1186 (let ((sexp (read (buffer-substring-no-properties
1187 (line-beginning-position)
1188 (line-end-position))))
1189 (buffer-read-only nil))
1190 (mapc (lambda (x) (aset (cdr x) 3 0)) sexp)
1191 (delete-region (line-beginning-position) (line-end-position))
1192 (prin1 sexp (current-buffer)))))
1193 (todo-set-categories)
1194 (unless buf2 (kill-buffer)))))
1195 (setq todo-files (funcall todo-files-function)
1196 todo-archives (funcall todo-files-function t))
1197 (when (or (string= file1-sn todo-default-todo-file)
1198 (and delete2 (string= file1-sn todo-default-todo-file)))
1199 (setq todo-default-todo-file (todo-short-file-name (car todo-files))))
1200 (when (or (string= file1 todo-global-current-todo-file)
1201 (and delete2 (string= file2 todo-global-current-todo-file)))
1202 (setq todo-global-current-todo-file nil))
1203 (todo-reevaluate-filelist-defcustoms)
1204 (message (concat (cond (todo "Todo") (archive "Archive")) " file \"%s\" "
1207 (cond (todo "archive") (archive "todo"))
1212 (defvar todo-edit-buffer "*Todo Edit*"
1213 "Name of current buffer in Todo Edit mode.")
1215 (defun todo-edit-file ()
1216 "Put current buffer in `todo-edit-mode'.
1217 This makes the entire file visible and the buffer writable and
1218 you can use the self-insertion keys and standard Emacs editing
1219 commands to make changes. To return to Todo mode, type
1220 \\[todo-edit-quit]. This runs a file format check, signaling
1221 an error if the format has become invalid. However, this check
1222 cannot tell if the number of items changed, which could result in
1223 the file containing inconsistent information. For this reason
1224 this command should be used with caution."
1229 (display-warning 'todo (format "\
1231 Type %s to return to Todo mode.
1233 This also runs a file format check and signals an error if
1234 the format has become invalid. However, this check cannot
1235 tell if the number of items or categories changed, which
1236 could result in the file containing inconsistent information.
1237 You can repair this inconsistency by invoking the command
1238 `todo-repair-categories-sexp', but this will revert any
1239 renumbering of the categories you have made, so you will
1240 have to renumber them again (see `(todo-mode) Reordering
1241 Categories')." (substitute-command-keys "\\[todo-edit-quit]"))))
1243 (defun todo-add-category (&optional file cat)
1244 "Add a new category to a todo file.
1246 Called interactively with prefix argument FILE, prompt for a file
1247 and then for a new category to add to that file, otherwise prompt
1248 just for a category to add to the current todo file. After
1249 adding the category, visit it in Todo mode and if option
1250 `todo-add-item-if-new-category' is non-nil (the default), prompt
1253 Non-interactively, add category CAT to file FILE; if FILE is nil,
1254 add CAT to the current todo file. After adding the category,
1255 return the new category number."
1258 ;; If cat is passed from caller, don't prompt, unless it is "",
1259 ;; which means the file was just added and has no category yet.
1260 (if (and cat (> (length cat) 0))
1261 (setq file0 (or (and (stringp file) file)
1262 todo-current-todo-file))
1263 (setq catfil (todo-read-category "Enter a new category name: "
1264 'add (when (called-interactively-p 'any)
1267 file0 (if (called-interactively-p 'any)
1271 (let ((counts (make-vector 4 0)) ; [todo diary done archived]
1272 (num (1+ (length todo-categories)))
1273 (buffer-read-only nil))
1274 (setq todo-current-todo-file file0)
1275 (setq todo-categories (append todo-categories
1276 (list (cons cat counts))))
1278 (goto-char (point-max))
1279 (save-excursion ; Save point for todo-category-select.
1280 (insert todo-category-beg cat "\n\n" todo-category-done "\n"))
1281 (todo-update-categories-sexp)
1282 ;; If invoked by user, display the newly added category, if
1283 ;; called programmatically return the category number to the
1285 (if (called-interactively-p 'any)
1287 (setq todo-category-number num)
1288 (todo-category-select)
1289 (when todo-add-item-if-new-category
1290 (todo-insert-item--basic)))
1293 (defun todo-rename-category ()
1294 "Rename current todo category.
1295 If this file has an archive containing this category, rename the
1296 category there as well."
1298 (let* ((cat (todo-current-category))
1299 (new (read-from-minibuffer
1300 (format "Rename category \"%s\" to: " cat))))
1301 (setq new (todo-validate-name new 'category))
1302 (let* ((ofile todo-current-todo-file)
1303 (archive (concat (file-name-sans-extension ofile) ".toda"))
1304 (buffers (append (list ofile)
1305 (unless (zerop (todo-get-count 'archived cat))
1307 (dolist (buf buffers)
1308 (with-current-buffer (find-file-noselect buf)
1309 (let (buffer-read-only)
1310 (setq todo-categories (todo-set-categories))
1313 (setcar (assoc cat todo-categories) new)
1315 (goto-char (point-min))
1316 (todo-update-categories-sexp)
1317 (re-search-forward (concat (regexp-quote todo-category-beg)
1318 "\\(" (regexp-quote cat) "\\)\n")
1320 (replace-match new t t nil 1)))))))
1321 (force-mode-line-update))
1322 (save-excursion (todo-category-select)))
1324 (defun todo-delete-category (&optional arg)
1325 "Delete current todo category provided it contains no items.
1326 With prefix ARG delete the category even if it does contain
1327 todo or done items."
1329 (let* ((file todo-current-todo-file)
1330 (cat (todo-current-category))
1331 (todo (todo-get-count 'todo cat))
1332 (done (todo-get-count 'done cat))
1333 (archived (todo-get-count 'archived cat)))
1335 (or (> todo 0) (> done 0)))
1336 (message "%s" (substitute-command-keys
1337 (concat "To delete a non-empty category, "
1338 "type C-u \\[todo-delete-category].")))
1339 (when (cond ((= (length todo-categories) 1)
1341 (concat "This is the only category in this file; "
1342 "deleting it will also delete the file.\n"
1343 "Do you want to proceed? ")))
1345 (todo-y-or-n-p (concat "This category has archived items; "
1346 "the archived category will remain\n"
1347 "after deleting the todo category. "
1348 "Do you still want to delete it\n"
1349 "(see `todo-skip-archived-categories' "
1350 "for another option)? ")))
1352 (todo-y-or-n-p (concat "Permanently remove category \"" cat
1353 "\"" (and arg " and all its entries")
1356 (let ((buffer-read-only)
1357 (beg (re-search-backward
1358 (concat "^" (regexp-quote (concat todo-category-beg cat))
1360 (end (if (re-search-forward
1361 (concat "\n\\(" (regexp-quote todo-category-beg)
1365 (remove-overlays beg end)
1366 (delete-region beg end)
1367 (if (= (length todo-categories) 1)
1368 ;; If deleted category was the only one, delete the file.
1370 (todo-reevaluate-filelist-defcustoms)
1371 ;; Skip confirming killing the archive buffer if it has been
1372 ;; modified and not saved.
1373 (set-buffer-modified-p nil)
1376 (message "Deleted todo file %s." file))
1377 (setq todo-categories (delete (assoc cat todo-categories)
1379 (todo-update-categories-sexp)
1380 (setq todo-category-number
1381 (1+ (mod todo-category-number (length todo-categories))))
1382 (todo-category-select)
1383 (goto-char (point-min))
1384 (message "Deleted category %s." cat)))))))
1386 (defun todo-move-category ()
1387 "Move current category to a different todo file.
1388 If the todo file chosen does not exist, it is created.
1389 If the current category has archived items, also move those to
1390 the archive of the file moved to, creating it if it does not exist."
1392 (when (or (> (length todo-categories) 1)
1393 (todo-y-or-n-p (concat "This is the only category in this file; "
1394 "moving it will also delete the file.\n"
1395 "Do you want to proceed? ")))
1396 (let* ((ofile todo-current-todo-file)
1397 (cat (todo-current-category))
1398 (nfile (todo-read-file-name "Todo file to move this category to: "))
1399 (archive (concat (file-name-sans-extension ofile) ".toda"))
1400 (buffers (append (list ofile)
1401 (unless (zerop (todo-get-count 'archived cat))
1404 (while (equal nfile (file-truename ofile))
1405 (setq nfile (todo-read-file-name
1406 "Choose a file distinct from this file: ")))
1407 (unless (member nfile todo-files)
1408 (with-current-buffer (get-buffer-create nfile)
1410 (write-region (point-min) (point-max) nfile nil 'nomessage nil t)
1411 (kill-buffer nfile))
1412 (setq todo-files (funcall todo-files-function))
1413 (todo-reevaluate-filelist-defcustoms))
1414 (dolist (buf buffers)
1415 (with-current-buffer (find-file-noselect buf)
1417 (goto-char (point-max))
1418 (let* ((beg (re-search-backward
1420 (regexp-quote (concat todo-category-beg cat))
1423 (end (if (re-search-forward
1424 (concat "^" (regexp-quote todo-category-beg))
1428 (content (buffer-substring-no-properties beg end))
1429 (counts (cdr (assoc cat todo-categories)))
1431 ;; Move the category to the new file. Also update or create
1432 ;; archive file if necessary.
1433 (with-current-buffer
1435 ;; Regenerate todo-archives in case there
1436 ;; is a newly created archive.
1437 (if (member buf (funcall todo-files-function t))
1438 (concat (file-name-sans-extension nfile) ".toda")
1440 (if (equal (file-name-extension (buffer-file-name)) "toda")
1441 (unless (derived-mode-p 'todo-archive-mode)
1442 (todo-archive-mode))
1443 (unless (derived-mode-p 'todo-mode) (todo-mode)))
1444 (let* ((nfile-short (todo-short-file-name nfile))
1446 (format "Todo file \"%s\" already has "
1448 (format "the category \"%s\";\n" cat)
1449 "enter a new category name: "))
1452 (goto-char (point-max))
1454 ;; If the file moved to has a category with the same
1455 ;; name, rename the moved category.
1456 (when (assoc cat todo-categories)
1457 (unless (member (file-truename (buffer-file-name))
1458 (funcall todo-files-function t))
1459 (setq new (read-from-minibuffer prompt))
1460 (setq new (todo-validate-name new 'category))))
1461 ;; Replace old with new name in todo and archive files.
1463 (goto-char (point-max))
1465 (concat "^" (regexp-quote todo-category-beg)
1466 "\\(" (regexp-quote cat) "\\)$") nil t)
1467 (replace-match new nil nil nil 1)))
1468 (setq todo-categories
1469 (append todo-categories (list (cons (or new cat) counts))))
1470 (todo-update-categories-sexp)
1471 ;; If archive was just created, save it to avoid "File
1472 ;; <xyz> no longer exists!" message on invoking
1473 ;; `todo-view-archived-items'.
1474 (unless (file-exists-p (buffer-file-name))
1476 (todo-category-number (or new cat))
1477 (todo-category-select))
1478 ;; Delete the category from the old file, and if that was the
1479 ;; last category, delete the file. Also handle archive file
1481 (remove-overlays beg end)
1482 (delete-region beg end)
1483 (goto-char (point-min))
1484 ;; Put point after todo-categories sexp.
1486 (if (eobp) ; Aside from sexp, file is empty.
1488 ;; Skip confirming killing the archive buffer.
1489 (set-buffer-modified-p nil)
1490 (delete-file todo-current-todo-file)
1492 (when (member todo-current-todo-file todo-files)
1493 (todo-reevaluate-filelist-defcustoms)))
1494 (setq todo-categories (delete (assoc cat todo-categories)
1496 (todo-update-categories-sexp)
1497 (when (> todo-category-number (length todo-categories))
1498 (setq todo-category-number 1))
1499 (todo-category-select)))))
1500 (set-window-buffer (selected-window)
1501 (set-buffer (find-file-noselect nfile)))
1502 (todo-category-number (or new cat))
1503 (todo-category-select))))
1505 (defun todo-merge-category (&optional file)
1506 "Merge current category into another existing category.
1508 With prefix argument FILE, prompt for a specific todo file and
1509 choose (with TAB completion) a category in it to merge into;
1510 otherwise, choose and merge into a category in either the
1511 current todo file or a file in `todo-category-completions-files'.
1513 After merging, the source category's todo and done items are
1514 appended to the chosen goal category's todo and done items,
1515 respectively. The goal category becomes the current category,
1516 and the source category is deleted.
1518 If both the source and goal categories also have archived items,
1519 they are also merged. If only the source category has archived
1520 items, the goal category is added as a new category to the
1521 archive file and the source category is deleted."
1523 (let* ((tfile todo-current-todo-file)
1524 (cat (todo-current-category))
1525 (cat+file (todo-read-category "Merge into category: " 'todo file))
1526 (goal (car cat+file))
1527 (gfile (cdr cat+file))
1528 (tarchive (concat (file-name-sans-extension tfile) ".toda"))
1529 (garchive (concat (file-name-sans-extension gfile) ".toda"))
1530 (archived-count (todo-get-count 'archived))
1532 (with-current-buffer (get-buffer (find-file-noselect tfile))
1534 (let* ((buffer-read-only nil)
1537 (concat "^" (regexp-quote todo-category-beg)) nil t)
1539 (tbeg (progn (forward-line) (point-marker)))
1542 (concat "^" (regexp-quote todo-category-done)) nil t)
1543 (forward-line) (point-marker)))
1544 ;; Omit empty line between todo and done items.
1545 (tend (progn (forward-line -2) (point-marker)))
1547 (if (re-search-forward
1548 (concat "^" (regexp-quote todo-category-beg)) nil t)
1550 (goto-char (match-beginning 0))
1552 (point-max-marker))))
1553 (todo (buffer-substring-no-properties tbeg tend))
1554 (done (buffer-substring-no-properties dbeg cend))
1555 (todo-count (todo-get-count 'todo cat))
1556 (done-count (todo-get-count 'done cat)))
1557 ;; Merge into goal todo category.
1558 (with-current-buffer (get-buffer (find-file-noselect gfile))
1559 (unless (derived-mode-p 'todo-mode) (todo-mode))
1561 (goto-char (point-min))
1562 (let ((buffer-read-only nil))
1563 ;; Merge any todo items.
1564 (unless (zerop (length todo))
1566 (concat "^" (regexp-quote (concat todo-category-beg goal)) "$")
1569 (concat "^" (regexp-quote todo-category-done)) nil t)
1571 (setq here (point-marker))
1573 (todo-update-count 'todo todo-count goal))
1574 ;; Merge any done items.
1575 (unless (zerop (length done))
1576 (goto-char (if (re-search-forward
1577 (concat "^" (regexp-quote todo-category-beg))
1581 (when (zerop (length todo)) (setq here (point-marker)))
1583 (todo-update-count 'done done-count goal)))
1584 (todo-update-categories-sexp))
1585 ;; Update and clean up source todo file.
1586 (remove-overlays cbeg cend)
1587 (delete-region cbeg cend)
1588 (setq todo-categories (delete (assoc cat todo-categories)
1590 (todo-update-categories-sexp)
1591 (when (> todo-category-number (length todo-categories))
1592 (setq todo-category-number 1))
1593 (todo-category-select)
1594 (mapc (lambda (m) (set-marker m nil))
1595 (list cbeg tbeg dbeg tend cend))))
1596 (when (> archived-count 0)
1597 (with-current-buffer (get-buffer (find-file-noselect tarchive))
1599 (goto-char (point-min))
1600 (let* ((buffer-read-only nil)
1602 (when (re-search-forward
1603 (concat "^" (regexp-quote
1604 (concat todo-category-beg cat)) "$")
1606 (goto-char (match-beginning 0))
1608 (cend (if (re-search-forward
1609 (concat "^" (regexp-quote todo-category-beg)) nil t)
1615 (buffer-substring-no-properties (point) cend))))
1616 ;; Merge into goal archive category, if it exists, else create it.
1617 (with-current-buffer (get-buffer (find-file-noselect garchive))
1618 (let ((gbeg (when (re-search-forward
1619 (concat "^" (regexp-quote
1620 (concat todo-category-beg goal))
1623 (goto-char (match-beginning 0))
1625 (goto-char (if (and gbeg
1627 (concat "^" (regexp-quote todo-category-beg))
1631 (unless gbeg (todo-add-category nil goal))
1633 (todo-update-categories-sexp)))
1634 ;; Update and clean up source archive file.
1635 (remove-overlays cbeg cend)
1636 (delete-region cbeg cend)
1637 (setq todo-categories (todo-make-categories-list t))
1638 (todo-update-categories-sexp))))
1639 ;; Update goal todo file for merged archived items and display it.
1640 (set-window-buffer (selected-window) (set-buffer (get-file-buffer gfile)))
1641 (unless (zerop archived-count)
1642 (todo-update-count 'archived archived-count goal)
1643 (todo-update-categories-sexp))
1644 (todo-category-number goal)
1645 ;; If there are only merged done items, show them.
1646 (let ((todo-show-with-done (zerop (todo-get-count 'todo goal))))
1647 (todo-category-select)
1648 ;; Put point on the first merged item.
1650 (set-marker here nil)))
1652 ;; -----------------------------------------------------------------------------
1654 ;; -----------------------------------------------------------------------------
1656 (defcustom todo-include-in-diary nil
1657 "Non-nil to allow new todo items to be included in the diary."
1661 (defcustom todo-diary-nonmarking nil
1662 "Non-nil to insert new todo diary items as nonmarking by default.
1663 This appends `diary-nonmarking-symbol' to the front of an item on
1664 insertion provided it doesn't begin with `todo-nondiary-marker'."
1668 (defcustom todo-always-add-time-string nil
1669 "Non-nil adds current time to a new item's date header by default.
1670 When the todo insertion commands have a non-nil \"maybe-notime\"
1671 argument, this reverses the effect of
1672 `todo-always-add-time-string': if t, these commands omit the
1673 current time, if nil, they include it."
1677 (defcustom todo-use-only-highlighted-region t
1678 "Non-nil to enable inserting only highlighted region as new item."
1682 (defcustom todo-default-priority 'first
1683 "Default priority of new and moved items."
1684 :type '(choice (const :tag "Highest priority" first)
1685 (const :tag "Lowest priority" last))
1688 (defcustom todo-item-mark "*"
1689 "String used to mark items.
1690 To ensure item marking works, change the value of this option
1691 only when no items are marked."
1692 :type '(string :validate
1694 (when (string= (widget-value widget) todo-prefix)
1697 "Invalid value: must be distinct from `todo-prefix'")
1699 :set (lambda (symbol value)
1700 (custom-set-default symbol (propertize value 'face 'todo-mark)))
1703 (defcustom todo-comment-string "COMMENT"
1704 "String inserted before optional comment appended to done item."
1706 :initialize 'custom-initialize-default
1707 :set 'todo-reset-comment-string
1710 (defcustom todo-undo-item-omit-comment 'ask
1711 "Whether to omit done item comment on undoing the item.
1712 Nil means never omit the comment, t means always omit it, `ask'
1713 means prompt user and omit comment only on confirmation."
1714 :type '(choice (const :tag "Never" nil)
1715 (const :tag "Always" t)
1716 (const :tag "Ask" ask))
1719 (defun todo-toggle-mark-item (&optional n)
1720 "Mark item with `todo-item-mark' if unmarked, otherwise unmark it.
1721 With positive numerical prefix argument N, change the marking of
1722 the next N items in the current category. If both the todo and
1723 done items sections are visible, the sequence of N items can
1724 consist of the the last todo items and the first done items."
1726 (when (todo-item-string)
1727 (unless (> n 1) (setq n 1))
1730 (let* ((cat (todo-current-category))
1731 (marks (assoc cat todo-categories-with-marks))
1733 (unless (looking-at todo-item-start)
1735 (todo-get-overlay 'prefix)))
1736 (pref (overlay-get ov 'before-string)))
1737 (if (todo-marked-item-p)
1739 (overlay-put ov 'before-string (substring pref 1))
1740 (if (= (cdr marks) 1) ; Deleted last mark in this category.
1741 (setq todo-categories-with-marks
1742 (assq-delete-all cat todo-categories-with-marks))
1743 (setcdr marks (1- (cdr marks)))))
1744 (overlay-put ov 'before-string (concat todo-item-mark pref))
1746 (setcdr marks (1+ (cdr marks)))
1747 (push (cons cat 1) todo-categories-with-marks))))
1749 ;; Don't try to mark the empty lines at the end of the todo
1750 ;; and done items sections.
1751 (when (looking-at "^$")
1754 (todo-forward-item)))))))
1756 (defun todo-mark-category ()
1757 "Mark all visible items in this category with `todo-item-mark'."
1759 (let* ((cat (todo-current-category))
1760 (marks (assoc cat todo-categories-with-marks)))
1762 (goto-char (point-min))
1764 (let* ((ov (todo-get-overlay 'prefix))
1765 (pref (overlay-get ov 'before-string)))
1766 (unless (todo-marked-item-p)
1767 (overlay-put ov 'before-string (concat todo-item-mark pref))
1769 (setcdr marks (1+ (cdr marks)))
1770 (push (cons cat 1) todo-categories-with-marks))))
1772 ;; Don't try to mark the empty line between the todo and done
1774 (when (looking-at "^$")
1776 (todo-forward-item)))))))
1778 (defun todo-unmark-category ()
1779 "Remove `todo-item-mark' from all visible items in this category."
1781 (let* ((cat (todo-current-category))
1782 (marks (assoc cat todo-categories-with-marks)))
1784 (goto-char (point-min))
1786 (let* ((ov (todo-get-overlay 'prefix))
1787 ;; No overlay on empty line between todo and done items.
1788 (pref (when ov (overlay-get ov 'before-string))))
1789 (when (todo-marked-item-p)
1790 (overlay-put ov 'before-string (substring pref 1)))
1791 (todo-forward-item))))
1792 (setq todo-categories-with-marks
1793 (delq marks todo-categories-with-marks))))
1795 (defvar todo-date-from-calendar nil
1796 "Helper variable for setting item date from the Emacs Calendar.")
1798 (defvar todo-insert-item--keys-so-far)
1799 (defvar todo-insert-item--parameters)
1801 (defun todo-insert-item (&optional arg)
1802 "Choose an item insertion operation and carry it out.
1803 This inserts a new todo item into a category.
1805 With no prefix argument ARG, add the item to the current
1806 category; with one prefix argument (`C-u'), prompt for a category
1807 from the current todo file; with two prefix arguments (`C-u
1808 C-u'), first prompt for a todo file, then a category in that
1809 file. If a non-existing category is entered, ask whether to add
1810 it to the todo file; if answered affirmatively, add the category
1811 and insert the item there.
1813 There are a number of item insertion parameters which can be
1814 combined by entering specific keys to produce different insertion
1815 commands. After entering each key, a message shows which have
1816 already been entered and which remain available. See
1817 `(todo-mode) Inserting New Items' for details of the parameters,
1818 their associated keys and their effects."
1820 (setq todo-insert-item--keys-so-far "i")
1821 (todo-insert-item--next-param nil (list arg) todo-insert-item--parameters))
1823 (defun todo-insert-item--basic (&optional arg diary-type date-type time where)
1824 "Function implementing the core of `todo-insert-item'."
1825 ;; If invoked outside of Todo mode and there is not yet any Todo
1826 ;; file, initialize one.
1827 (if (null (funcall todo-files-function))
1829 (let ((copy (eq where 'copy))
1830 (region (eq where 'region))
1831 (here (eq where 'here))
1835 ((not (eq major-mode 'todo-mode))
1836 (user-error "You must be in Todo mode to copy a todo item"))
1838 (user-error "You cannot copy a done item as a new todo item"))
1840 (user-error "Point must be on a todo item to copy it")))
1841 (setq diary-item (todo-diary-item-p)))
1843 (let (use-empty-active-region)
1844 (unless (and todo-use-only-highlighted-region (use-region-p))
1845 (user-error "There is no active region"))))
1846 (let* ((obuf (current-buffer))
1847 (ocat (todo-current-category))
1849 (todo-mm (eq major-mode 'todo-mode))
1850 (cat+file (cond ((equal arg '(4))
1851 (todo-read-category "Insert in category: "))
1853 (todo-read-category "Insert in category: "
1856 (cons (todo-current-category)
1857 (or todo-current-todo-file
1858 (and todo-show-current-file
1859 todo-global-current-todo-file)
1860 (todo-absolute-file-name
1861 todo-default-todo-file))))))
1862 (cat (car cat+file))
1863 (file (cdr cat+file))
1864 (new-item (cond (copy (todo-item-string))
1865 (region (buffer-substring-no-properties
1866 (region-beginning) (region-end)))
1867 (t (read-from-minibuffer "Todo item: "))))
1869 ((eq date-type 'date)
1871 ((eq date-type 'dayname)
1872 (todo-read-dayname))
1873 ((eq date-type 'calendar)
1874 (setq todo-date-from-calendar t)
1875 (or (todo-set-date-from-calendar)
1876 ;; If user exits Calendar before choosing
1877 ;; a date, cancel item insertion.
1879 ((and (stringp date-type)
1880 (string-match todo-date-pattern date-type))
1881 (setq todo-date-from-calendar date-type)
1882 (todo-set-date-from-calendar))
1884 (calendar-date-string
1885 (calendar-current-date) t t))))
1886 (time-string (or (and time (todo-read-time))
1887 (and todo-always-add-time-string
1888 (substring (current-time-string) 11 16)))))
1889 (setq todo-date-from-calendar nil)
1890 (find-file-noselect file 'nowarn)
1891 (set-window-buffer (selected-window)
1892 (set-buffer (find-buffer-visiting file)))
1893 ;; If this command was invoked outside of a Todo mode buffer,
1894 ;; the call to todo-current-category above returned nil. If
1895 ;; we just entered Todo mode now, then cat was set to the
1896 ;; file's first category, but if todo-mode was already
1897 ;; enabled, cat did not get set, so we have to do that.
1899 (setq cat (todo-current-category)))
1900 (setq todo-current-todo-file file)
1901 (unless todo-global-current-todo-file
1902 (setq todo-global-current-todo-file todo-current-todo-file))
1903 (let ((buffer-read-only nil)
1904 (called-from-outside (not (and todo-mm (equal cat ocat))))
1905 done-only item-added)
1908 ;; Add date, time and diary marking as required.
1909 (concat (if (not (and diary-type
1910 (not todo-include-in-diary)))
1912 (when (and (eq diary-type 'nonmarking)
1913 (not todo-diary-nonmarking))
1914 diary-nonmarking-symbol))
1915 date-string (when (and time-string ; Can be empty.
1918 (concat " " time-string))
1919 (when (not (and diary-type
1920 (not todo-include-in-diary)))
1923 ;; Indent newlines inserted by C-q C-j if nonspace char follows.
1924 (setq new-item (replace-regexp-in-string "\\(\n\\)[^[:blank:]]"
1925 "\n\t" new-item nil nil 1)))
1928 ;; Make sure the correct category is selected. There
1929 ;; are two cases: (i) we just visited the file, so no
1930 ;; category is selected yet, or (ii) we invoked
1931 ;; insertion "here" from outside the category we want
1932 ;; to insert in (with priority insertion, category
1933 ;; selection is done by todo-set-item-priority).
1934 (when (or (= (- (point-max) (point-min)) (buffer-size))
1935 (and here called-from-outside))
1936 (todo-category-number cat)
1937 (todo-category-select))
1938 ;; If only done items are displayed in category,
1939 ;; toggle to todo items before inserting new item.
1940 (when (save-excursion
1941 (goto-char (point-min))
1942 (looking-at todo-done-string-start))
1944 (todo-toggle-view-done-only))
1947 ;; If command was invoked with point in done
1948 ;; items section or outside of the current
1949 ;; category, can't insert "here", so to be
1950 ;; useful give new item top priority.
1951 (when (or (todo-done-item-section-p)
1954 (goto-char (point-min)))
1955 (todo-insert-with-overlays new-item))
1956 (todo-set-item-priority new-item cat t))
1957 (setq item-added t))
1958 ;; If user cancels before setting priority, restore
1961 (set-window-buffer (selected-window) (set-buffer obuf))
1963 (unless (equal cat ocat)
1964 (todo-category-number ocat)
1965 (todo-category-select))
1966 (and done-only (todo-toggle-view-done-only)))
1968 ;; If the todo items section is not visible when the
1969 ;; insertion command is called (either because only done
1970 ;; items were shown or because the category was not in the
1971 ;; current buffer), then if the item is inserted at the
1972 ;; end of the category, point is at eob and eob at
1973 ;; window-start, so that higher priority todo items are
1974 ;; out of view. So we recenter to make sure the todo
1975 ;; items are displayed in the window.
1976 (when item-added (recenter)))
1977 (todo-update-count 'todo 1)
1978 (when (or diary-item diary-type todo-include-in-diary)
1979 (todo-update-count 'diary 1))
1980 (todo-update-categories-sexp))))))
1982 (defun todo-set-date-from-calendar ()
1983 "Return string of date chosen from Calendar."
1984 (cond ((and (stringp todo-date-from-calendar)
1985 (string-match todo-date-pattern todo-date-from-calendar))
1986 todo-date-from-calendar)
1987 (todo-date-from-calendar
1988 (let (calendar-view-diary-initially-flag)
1989 (calendar)) ; *Calendar* is now current buffer.
1990 (define-key calendar-mode-map [remap newline] 'exit-recursive-edit)
1991 ;; If user exits Calendar before choosing a date, clean up properly.
1992 (define-key calendar-mode-map
1993 [remap calendar-exit] (lambda ()
1997 (exit-recursive-edit))))
1998 (message "Put cursor on a date and type <return> to set it.")
2001 (when (equal (buffer-name) calendar-buffer)
2002 (setq todo-date-from-calendar
2003 (calendar-date-string (calendar-cursor-to-date t) t t))
2005 todo-date-from-calendar)
2006 (define-key calendar-mode-map [remap newline] nil)
2007 (define-key calendar-mode-map [remap calendar-exit] nil)
2008 (unless (zerop (recursion-depth)) (exit-recursive-edit))
2009 (when (stringp todo-date-from-calendar)
2010 todo-date-from-calendar)))))
2012 (defun todo-insert-item-from-calendar (&optional arg)
2013 "Prompt for and insert a new item with date selected from calendar.
2014 Invoked without prefix argument ARG, insert the item into the
2015 current category, without one prefix argument, prompt for the
2016 category from the current todo file or from one listed in
2017 `todo-category-completions-files'; with two prefix arguments,
2018 prompt for a todo file and then for a category in it."
2020 (setq todo-date-from-calendar
2021 (calendar-date-string (calendar-cursor-to-date t) t t))
2023 (todo-insert-item--basic arg nil todo-date-from-calendar))
2025 (define-key calendar-mode-map "it" 'todo-insert-item-from-calendar)
2027 (defun todo-delete-item ()
2028 "Delete at least one item in this category.
2029 If there are marked items, delete all of these; otherwise, delete
2034 (let* ((cat (todo-current-category))
2035 (marked (assoc cat todo-categories-with-marks))
2036 (item (unless marked (todo-item-string)))
2039 "Permanently delete all marked items? ")
2041 (setq ov (make-overlay
2042 (save-excursion (todo-item-start))
2043 (save-excursion (todo-item-end))))
2044 (overlay-put ov 'face 'todo-search)
2045 (todo-y-or-n-p "Permanently delete this item? "))))
2048 (and marked (goto-char (point-min)))
2051 (if (or (and marked (todo-marked-item-p)) item)
2053 (if (todo-done-item-p)
2054 (todo-update-count 'done -1)
2055 (todo-update-count 'todo -1 cat)
2056 (and (todo-diary-item-p)
2057 (todo-update-count 'diary -1)))
2058 (if ov (delete-overlay ov))
2060 ;; Don't leave point below last item.
2061 (and item (bolp) (eolp) (< (point-min) (point-max))
2062 (todo-backward-item))
2064 (throw 'done (setq item nil))))
2065 (todo-forward-item))))
2067 (setq todo-categories-with-marks
2068 (assq-delete-all cat todo-categories-with-marks)))
2069 (todo-update-categories-sexp)
2070 (todo-prefix-overlays)))
2071 (if ov (delete-overlay ov)))))
2073 (defvar todo-edit-item--param-key-alist)
2074 (defvar todo-edit-done-item--param-key-alist)
2076 (defun todo-edit-item (&optional arg)
2077 "Choose an editing operation for the current item and carry it out."
2079 (let ((marked (assoc (todo-current-category) todo-categories-with-marks)))
2080 (cond ((and (todo-done-item-p) (not marked))
2081 (todo-edit-item--next-key todo-edit-done-item--param-key-alist))
2082 ((or marked (todo-item-string))
2083 (todo-edit-item--next-key todo-edit-item--param-key-alist arg)))))
2085 (defun todo-edit-item--text (&optional arg)
2086 "Function providing the text editing facilities of `todo-edit-item'."
2087 (let ((full-item (todo-item-string)))
2088 ;; If there are marked items and user invokes a text-editing
2089 ;; commands with point not on an item, todo-item-start is nil and
2090 ;; 1+ signals an error, so just make this a noop.
2092 (let* ((opoint (point))
2093 (start (todo-item-start))
2094 (end (save-excursion (todo-item-end)))
2097 (concat todo-date-string-start todo-date-pattern
2098 "\\( " diary-time-regexp "\\)?"
2099 (regexp-quote todo-nondiary-end) "?")
2100 (line-end-position) t)
2101 (1+ (- (point) start))))
2102 (include-header (eq arg 'include-header))
2103 (comment-edit (eq arg 'comment-edit))
2104 (comment-delete (eq arg 'comment-delete))
2105 (header-string (substring full-item 0 item-beg))
2106 (item (if (or include-header comment-edit comment-delete)
2108 (substring full-item item-beg)))
2109 (multiline (or (eq arg 'multiline)
2110 (> (length (split-string item "\n")) 1)))
2111 (comment (save-excursion
2114 (concat " \\[" (regexp-quote todo-comment-string)
2115 ": \\([^]]+\\)\\]") end t)))
2116 (prompt (if comment "Edit comment: " "Enter a comment: "))
2117 (buffer-read-only nil))
2118 ;; When there are marked items, user can invoke todo-edit-item
2119 ;; even if point is not on an item, but text editing only
2120 ;; applies to the item at point.
2121 (when (or (and (todo-done-item-p)
2122 (or comment-edit comment-delete))
2123 (and (not (todo-done-item-p))
2124 (or (not arg) include-header multiline)))
2126 ((or comment-edit comment-delete)
2129 (if (re-search-forward (concat " \\["
2130 (regexp-quote todo-comment-string)
2131 ": \\([^]]+\\)\\]") end t)
2133 (when (todo-y-or-n-p "Delete comment? ")
2134 (delete-region (match-beginning 0) (match-end 0)))
2135 (replace-match (read-string prompt (cons (match-string 1) 1))
2138 (user-error "There is no comment to delete")
2139 (insert " [" todo-comment-string ": "
2140 (prog1 (read-string prompt)
2141 ;; If user moved point during editing,
2142 ;; make sure it moves back.
2147 (let ((buf todo-edit-buffer))
2148 (set-window-buffer (selected-window)
2149 (set-buffer (make-indirect-buffer
2150 (buffer-name) buf)))
2151 (narrow-to-region (todo-item-start) (todo-item-end))
2153 (message "%s" (substitute-command-keys
2154 (concat "Type \\[todo-edit-quit] "
2155 "to return to Todo mode.\n")))))
2157 (let ((new (concat (if include-header "" header-string)
2158 (read-string "Edit: " (if include-header
2159 (cons item item-beg)
2161 (when include-header
2162 (while (not (string-match (concat todo-date-string-start
2163 todo-date-pattern) new))
2164 (setq new (read-from-minibuffer
2165 "Item must start with a date: " new))))
2166 ;; Ensure lines following hard newlines are indented.
2167 (setq new (replace-regexp-in-string "\\(\n\\)[^[:blank:]]"
2168 "\n\t" new nil nil 1))
2169 ;; If user moved point during editing, make sure it moves back.
2172 (todo-insert-with-overlays new)
2173 (move-to-column item-beg)))))))))
2175 (defun todo-edit-quit ()
2176 "Return from Todo Edit mode to Todo mode.
2177 If the item contains hard line breaks, make sure the following
2178 lines are indented by `todo-indent-to-here' to conform to diary
2181 If the whole file was in Todo Edit mode, check before returning
2182 whether the file is still a valid todo file and if so, also
2183 recalculate the todo file's categories sexp, in case changes were
2184 made in the number or names of categories."
2186 (if (> (buffer-size) (- (point-max) (point-min)))
2187 ;; We got here via `e m'.
2188 (let ((item (buffer-string))
2189 (regex "\\(\n\\)[^[:blank:]]")
2190 (buf (buffer-base-buffer)))
2191 (while (not (string-match (concat todo-date-string-start
2192 todo-date-pattern) item))
2193 (setq item (read-from-minibuffer
2194 "Item must start with a date: " item)))
2195 ;; Ensure lines following hard newlines are indented.
2196 (when (string-match regex (buffer-string))
2197 (setq item (replace-regexp-in-string regex "\n\t" item nil nil 1))
2198 (delete-region (point-min) (point-max))
2201 (unless (eq (current-buffer) buf)
2202 (set-window-buffer (selected-window) (set-buffer buf))))
2203 ;; We got here via `F e'.
2204 (when (todo-check-format)
2205 ;; FIXME: separate out sexp check?
2206 ;; If manual editing makes e.g. item counts change, have to
2207 ;; call this to update todo-categories, but it restores
2208 ;; category order to list order.
2209 ;; (todo-repair-categories-sexp)
2210 ;; Compare (todo-make-categories-list t) with sexp and if
2211 ;; different ask (todo-update-categories-sexp) ?
2213 (let* ((cat-beg (concat "^" (regexp-quote todo-category-beg)
2215 (curline (buffer-substring-no-properties
2216 (line-beginning-position) (line-end-position)))
2217 (cat (cond ((string-match cat-beg curline)
2218 (match-string-no-properties 1 curline))
2219 ((or (re-search-backward cat-beg nil t)
2220 (re-search-forward cat-beg nil t))
2221 (match-string-no-properties 1)))))
2222 (todo-category-number cat)
2223 (todo-category-select)
2224 (goto-char (point-min))))))
2226 (defun todo-edit-item--header (what &optional inc)
2227 "Function providing header editing facilities of `todo-edit-item'."
2228 (let ((marked (assoc (todo-current-category) todo-categories-with-marks))
2230 (todo-date-from-calendar t)
2231 ;; INC must be an integer, but users could pass it via
2232 ;; `todo-edit-item' as e.g. `-' or `C-u'.
2233 (inc (prefix-numeric-value inc))
2234 (buffer-read-only nil)
2235 ndate ntime year monthname month day
2236 dayname) ; Needed by calendar-date-display-form.
2237 (when marked (todo--user-error-if-marked-done-item))
2239 (or (and marked (goto-char (point-min))) (todo-item-start))
2243 (while (not (todo-marked-item-p))
2245 (and (eobp) (throw 'end nil))))
2246 (re-search-forward (concat todo-date-string-start "\\(?1:"
2248 "\\)\\(?2: " diary-time-regexp "\\)?"
2249 (regexp-quote todo-nondiary-end) "?")
2250 (line-end-position) t)
2251 (let* ((odate (match-string-no-properties 1))
2252 (otime (match-string-no-properties 2))
2253 (odayname (match-string-no-properties 5))
2254 (omonthname (match-string-no-properties 6))
2255 (omonth (match-string-no-properties 7))
2256 (oday (match-string-no-properties 8))
2257 (oyear (match-string-no-properties 9))
2258 (tmn-array todo-month-name-array)
2259 (mlist (append tmn-array nil))
2260 (tma-array todo-month-abbrev-array)
2261 (mablist (append tma-array nil))
2262 (yy (and oyear (unless (string= oyear "*")
2263 (string-to-number oyear))))
2264 (mm (or (and omonth (unless (string= omonth "*")
2265 (string-to-number omonth)))
2266 (1+ (- (length mlist)
2267 (length (or (member omonthname mlist)
2268 (member omonthname mablist)))))))
2269 (dd (and oday (unless (string= oday "*")
2270 (string-to-number oday)))))
2271 ;; If there are marked items, use only the first to set
2272 ;; header changes, and apply these to all marked items.
2276 (setq ndate (todo-read-date)))
2277 ((eq what 'calendar)
2278 (setq ndate (save-match-data (todo-set-date-from-calendar))))
2280 (setq ndate (calendar-date-string (calendar-current-date) t t)))
2282 (setq ndate (todo-read-dayname)))
2284 (setq ntime (save-match-data (todo-read-time)))
2285 (when (> (length ntime) 0)
2286 (setq ntime (concat " " ntime))))
2287 ;; When date string consists only of a day name,
2288 ;; passing other date components is a noop.
2289 ((and odayname (memq what '(year month day))))
2292 monthname omonthname
2294 year (cond ((not current-prefix-arg)
2295 (todo-read-date 'year))
2296 ((string= oyear "*")
2297 (user-error "Cannot increment *"))
2299 (number-to-string (+ yy inc))))))
2303 (if (memq 'month calendar-date-display-form)
2306 (cond ((not current-prefix-arg)
2307 (todo-read-date 'month))
2308 ((or (string= omonth "*") (= mm 13))
2309 (user-error "Cannot increment *"))
2311 (let ((mminc (+ mm inc)))
2312 ;; Increment or decrement month by INC
2314 (setq mm (% mminc 12))
2315 ;; If result is 0, make month December.
2316 (setq mm (if (= mm 0) 12 (abs mm)))
2317 ;; Adjust year if necessary.
2318 (setq year (or (and (cond ((> mminc 12)
2319 (+ yy (/ mminc 12)))
2321 (- yy (/ mminc 12) 1))
2323 (number-to-string yy))
2325 ;; Return the changed numerical month as
2326 ;; a string or the corresponding month name.
2328 (number-to-string mm)
2329 (aref tma-array (1- mm))))))
2330 (let ((yy (string-to-number year)) ; 0 if year is "*".
2331 ;; When mm is 13 (corresponding to "*" as value
2332 ;; of month), this raises an args-out-of-range
2333 ;; error in calendar-last-day-of-month, so use 1
2334 ;; (corresponding to January) to get 31 days.
2335 (mm (if (= mm 13) 1 mm)))
2336 (if (> (string-to-number day)
2337 (calendar-last-day-of-month mm yy))
2338 (user-error "%s %s does not have %s days"
2339 (aref tmn-array (1- mm))
2340 (if (= mm 2) yy "") day))))
2344 monthname omonthname
2346 ((not current-prefix-arg)
2347 (todo-read-date 'day mm oyear))
2349 (user-error "Cannot increment *"))
2350 ((or (string= omonth "*") (string= omonthname "*"))
2351 (setq dd (+ dd inc))
2354 "A month cannot have more than 31 days")
2355 (number-to-string dd)))
2356 ;; Increment or decrement day by INC,
2357 ;; adjusting month and year if necessary
2358 ;; (if year is "*" assume current year to
2359 ;; calculate adjustment).
2361 (let* ((yy (or yy (calendar-extract-year
2362 (calendar-current-date))))
2363 (date (calendar-gregorian-from-absolute
2364 (+ (calendar-absolute-from-gregorian
2365 (list mm dd yy)) inc)))
2366 (adjmm (nth 0 date)))
2367 ;; Set year and month(name) to adjusted values.
2368 (unless (string= year "*")
2369 (setq year (number-to-string (nth 2 date))))
2371 (setq month (number-to-string adjmm))
2372 (setq monthname (aref tma-array (1- adjmm))))
2373 ;; Return changed numerical day as a string.
2374 (number-to-string (nth 1 date)))))))))
2376 ;; If year, month or day date string components were
2377 ;; changed, rebuild the date string.
2378 (when (memq what '(year month day))
2379 (setq ndate (mapconcat 'eval calendar-date-display-form ""))))
2380 (when ndate (replace-match ndate nil nil nil 1))
2381 ;; Add new time string to the header, if it was supplied.
2384 (replace-match ntime nil nil nil 2)
2385 (goto-char (match-end 1))
2387 (setq todo-date-from-calendar nil)
2389 ;; Apply the changes to the first marked item header to the
2390 ;; remaining marked items. If there are no marked items,
2394 (goto-char (point-max))))))))
2396 (defun todo-edit-item--diary-inclusion (&optional nonmarking)
2397 "Function providing diary marking facilities of `todo-edit-item'."
2398 (let ((buffer-read-only)
2399 (marked (assoc (todo-current-category) todo-categories-with-marks)))
2400 (when marked (todo--user-error-if-marked-done-item))
2403 (when marked (goto-char (point-min)))
2405 (unless (and marked (not (todo-marked-item-p)))
2406 (let* ((beg (todo-item-start))
2407 (lim (save-excursion (todo-item-end)))
2408 (end (save-excursion
2409 (or (todo-time-string-matcher lim)
2410 (todo-date-string-matcher lim)))))
2412 (if (looking-at (regexp-quote diary-nonmarking-symbol))
2414 (when (looking-at (regexp-quote todo-nondiary-start))
2417 (search-forward todo-nondiary-end (1+ end) t)
2419 (todo-update-count 'diary 1)))
2420 (insert diary-nonmarking-symbol))
2421 (if (looking-at (regexp-quote todo-nondiary-start))
2424 (search-forward todo-nondiary-end (1+ end) t)
2426 (todo-update-count 'diary 1))
2428 (when (looking-at (regexp-quote diary-nonmarking-symbol))
2430 (setq end (1- end))) ; Since we deleted nonmarking symbol.
2431 (insert todo-nondiary-start)
2432 (goto-char (1+ end))
2433 (insert todo-nondiary-end)
2434 (todo-update-count 'diary -1))))))
2435 (unless marked (throw 'stop nil))
2436 (todo-forward-item)))))
2437 (todo-update-categories-sexp))
2439 (defun todo-edit-category-diary-inclusion (arg)
2440 "Make all items in this category diary items.
2441 With prefix ARG, make all items in this category non-diary
2445 (goto-char (point-min))
2446 (let ((todo-count (todo-get-count 'todo))
2447 (diary-count (todo-get-count 'diary))
2451 (if (todo-done-item-p) ; We've gone too far.
2453 (let* ((beg (todo-item-start))
2454 (lim (save-excursion (todo-item-end)))
2455 (end (save-excursion
2456 (or (todo-time-string-matcher lim)
2457 (todo-date-string-matcher lim)))))
2459 (unless (looking-at (regexp-quote todo-nondiary-start))
2460 (when (looking-at (regexp-quote diary-nonmarking-symbol))
2462 (setq end (1- end))) ; Since we deleted nonmarking symbol.
2463 (insert todo-nondiary-start)
2464 (goto-char (1+ end))
2465 (insert todo-nondiary-end))
2466 (when (looking-at (regexp-quote todo-nondiary-start))
2468 (search-forward todo-nondiary-end (1+ end) t)
2469 (replace-match "")))))
2470 (todo-forward-item))
2471 (unless (if arg (zerop diary-count) (= diary-count todo-count))
2472 (todo-update-count 'diary (if arg
2474 (- todo-count diary-count))))
2475 (todo-update-categories-sexp)))))
2477 (defun todo-edit-category-diary-nonmarking (arg)
2478 "Add `diary-nonmarking-symbol' to all diary items in this category.
2479 With prefix ARG, remove `diary-nonmarking-symbol' from all diary
2480 items in this category."
2483 (goto-char (point-min))
2484 (let (buffer-read-only)
2487 (if (todo-done-item-p) ; We've gone too far.
2489 (unless (looking-at (regexp-quote todo-nondiary-start))
2491 (when (looking-at (regexp-quote diary-nonmarking-symbol))
2493 (unless (looking-at (regexp-quote diary-nonmarking-symbol))
2494 (insert diary-nonmarking-symbol))))
2495 (todo-forward-item)))))))
2497 (defun todo-set-item-priority (&optional item cat new arg)
2498 "Prompt for and set ITEM's priority in CATegory.
2500 Interactively, ITEM is the todo item at point, CAT is the current
2501 category, and the priority is a number between 1 and the number
2502 of items in the category. Non-interactively, non-nil NEW means
2503 ITEM is a new item and the lowest priority is one more than the
2504 number of items in CAT.
2506 The new priority is set either interactively by prompt or by a
2507 numerical prefix argument, or noninteractively by argument ARG,
2508 whose value can be either of the symbols `raise' or `lower',
2509 meaning to raise or lower the item's priority by one."
2511 (unless (and (called-interactively-p 'any)
2512 (or (todo-done-item-p) (looking-at "^$")))
2513 (let* ((item (or item (todo-item-string)))
2514 (marked (todo-marked-item-p))
2515 (cat (or cat (cond ((eq major-mode 'todo-mode)
2516 (todo-current-category))
2517 ((eq major-mode 'todo-filtered-items-mode)
2519 (concat todo-date-string-start
2521 "\\( " diary-time-regexp "\\)?"
2522 (regexp-quote todo-nondiary-end)
2523 "?\\(?1: \\[\\(.+:\\)?.+\\]\\)")))
2525 (re-search-forward regexp1 nil t)
2526 (match-string-no-properties 1)))))))
2528 (todo (cond ((or (eq arg 'raise) (eq arg 'lower)
2529 (eq major-mode 'todo-filtered-items-mode))
2531 (let ((curstart (todo-item-start))
2533 (goto-char (point-min))
2534 (while (looking-at todo-item-start)
2535 (setq count (1+ count))
2536 (when (= (point) curstart) (setq curnum count))
2537 (todo-forward-item))
2539 ((eq major-mode 'todo-mode)
2540 (todo-get-count 'todo cat))))
2541 (maxnum (if new (1+ todo) todo))
2542 (prompt (format "Set item priority (1-%d): " maxnum))
2543 (priority (cond ((and (not arg) (numberp current-prefix-arg))
2545 ((and (eq arg 'raise) (>= curnum 1))
2547 ((and (eq arg 'lower) (<= curnum maxnum))
2551 (unless (and priority
2552 (or (and (eq arg 'raise) (zerop priority))
2553 (and (eq arg 'lower) (> priority maxnum))))
2554 ;; When moving item to another category, show the category before
2555 ;; prompting for its priority.
2556 (unless (or arg (called-interactively-p 'any))
2557 (todo-category-number cat)
2558 ;; If done items in category are visible, keep them visible.
2559 (let ((done todo-show-with-done))
2560 (when (> (buffer-size) (- (point-max) (point-min)))
2562 (goto-char (point-min))
2563 (setq done (re-search-forward todo-done-string-start nil t))))
2564 (let ((todo-show-with-done done))
2565 ;; Keep current item or top of moved to category in view
2566 ;; while setting priority.
2567 (save-excursion (todo-category-select)))))
2568 ;; Prompt for priority only when the category has at least one
2571 (while (not priority)
2572 (setq candidate (read-number prompt
2573 (if (eq todo-default-priority 'first)
2575 (setq prompt (when (or (< candidate 1) (> candidate maxnum))
2576 (format "Priority must be an integer between 1 and %d.\n"
2578 (unless prompt (setq priority candidate))))
2579 ;; In Top Priorities buffer, an item's priority can be changed
2580 ;; wrt items in another category, but not wrt items in the same
2582 (when (eq major-mode 'todo-filtered-items-mode)
2583 (let* ((regexp2 (concat todo-date-string-start todo-date-pattern
2584 "\\( " diary-time-regexp "\\)?"
2585 (regexp-quote todo-nondiary-end)
2586 "?\\(?1:" (regexp-quote cat) "\\)"))
2587 (end (cond ((< curnum priority)
2588 (save-excursion (todo-item-end)))
2589 ((> curnum priority)
2590 (save-excursion (todo-item-start)))))
2591 (match (save-excursion
2592 (cond ((< curnum priority)
2593 (todo-forward-item (1+ (- priority curnum)))
2594 (when (re-search-backward regexp2 end t)
2595 (match-string-no-properties 1)))
2596 ((> curnum priority)
2597 (todo-backward-item (- curnum priority))
2598 (when (re-search-forward regexp2 end t)
2599 (match-string-no-properties 1)))))))
2601 (user-error (concat "Cannot reprioritize items from the same "
2602 "category in this mode, only in Todo mode")))))
2603 ;; Interactively or with non-nil ARG, relocate the item within its
2605 (when (or arg (called-interactively-p 'any))
2607 (goto-char (point-min))
2609 (unless (= priority 1)
2610 (todo-forward-item (1- priority))
2611 ;; When called from todo-item-undone and the highest priority
2612 ;; is chosen, this advances point to the first done item, so
2613 ;; move it up to the empty line above the done items
2615 (when (looking-back (concat "^"
2616 (regexp-quote todo-category-done)
2618 (line-beginning-position 0))
2619 (todo-backward-item))))
2620 (todo-insert-with-overlays item)
2621 ;; If item was marked, restore the mark.
2623 (let* ((ov (todo-get-overlay 'prefix))
2624 (pref (overlay-get ov 'before-string)))
2625 (overlay-put ov 'before-string
2626 (concat todo-item-mark pref))))))))
2628 (defun todo-raise-item-priority ()
2629 "Raise priority of current item by moving it up by one item."
2631 (todo-set-item-priority nil nil nil 'raise))
2633 (defun todo-lower-item-priority ()
2634 "Lower priority of current item by moving it down by one item."
2636 (todo-set-item-priority nil nil nil 'lower))
2638 (defun todo-move-item (&optional file)
2639 "Move at least one todo or done item to another category.
2640 If there are marked items, move all of these; otherwise, move
2643 With prefix argument FILE, prompt for a specific todo file and
2644 choose (with TAB completion) a category in it to move the item or
2645 items to; otherwise, choose and move to any category in either
2646 the current todo file or one of the files in
2647 `todo-category-completions-files'. If the chosen category is
2648 not an existing categories, then it is created and the item(s)
2649 become(s) the first entry/entries in that category.
2651 With moved todo items, prompt to set the priority in the category
2652 moved to (with multiple todo items, the one that had the highest
2653 priority in the category moved from gets the new priority and the
2654 rest of the moved todo items are inserted in sequence below it).
2655 Moved done items are appended to the top of the done items
2656 section in the category moved to."
2658 (let* ((cat1 (todo-current-category))
2659 (marked (assoc cat1 todo-categories-with-marks)))
2660 ;; Noop if point is not on an item and there are no marked items.
2661 (unless (and (looking-at "^$")
2663 (let* ((buffer-read-only)
2664 (file1 todo-current-todo-file)
2665 (num todo-category-number)
2666 (item (todo-item-string))
2667 (diary-item (todo-diary-item-p))
2668 (done-item (and (todo-done-item-p) (concat item "\n")))
2669 (omark (save-excursion (todo-item-start) (point-marker)))
2673 ov cat2 file2 moved nmark todo-items done-items)
2677 (setq ov (make-overlay (save-excursion (todo-item-start))
2678 (save-excursion (todo-item-end))))
2679 (overlay-put ov 'face 'todo-search))
2680 (let* ((pl (if (and marked (> (cdr marked) 1)) "s" ""))
2681 (cat+file (todo-read-category (concat "Move item" pl
2684 (while (and (equal (car cat+file) cat1)
2685 (equal (cdr cat+file) file1))
2686 (setq cat+file (todo-read-category
2687 "Choose a different category: ")))
2688 (setq cat2 (car cat+file)
2689 file2 (cdr cat+file))))
2690 (if ov (delete-overlay ov)))
2691 (set-buffer (find-buffer-visiting file1))
2694 (goto-char (point-min))
2696 (when (todo-marked-item-p)
2697 (if (todo-done-item-p)
2698 (setq done-items (concat done-items
2699 (todo-item-string) "\n")
2701 (setq todo-items (concat todo-items
2702 (todo-item-string) "\n")
2704 (when (todo-diary-item-p)
2705 (setq diary (1+ diary)))))
2706 (todo-forward-item))
2707 ;; Chop off last newline of multiple todo item string,
2708 ;; since it will be reinserted when setting priority
2709 ;; (but with done items priority is not set, so keep
2712 (setq todo-items (substring todo-items 0 -1))))
2713 (if (todo-done-item-p)
2716 (when (todo-diary-item-p) (setq diary 1))))
2717 (set-window-buffer (selected-window)
2718 (set-buffer (find-file-noselect file2 'nowarn)))
2721 (when (or todo-items (and item (not done-item)))
2722 (todo-set-item-priority (or todo-items item) cat2 t))
2723 ;; Move done items en bloc to top of done items section.
2724 (when (or done-items done-item)
2725 (todo-category-number cat2)
2727 (goto-char (point-min))
2729 (concat "^" (regexp-quote (concat todo-category-beg cat2))
2732 (concat "^" (regexp-quote todo-category-done)) nil t)
2734 (insert (or done-items done-item)))
2737 ;; Move succeeded, so remove item from starting category,
2738 ;; update item counts and display the category containing
2741 (setq nmark (point-marker))
2742 (when todo (todo-update-count 'todo todo))
2743 (when diary (todo-update-count 'diary diary))
2744 (when done (todo-update-count 'done done))
2745 (todo-update-categories-sexp)
2746 (with-current-buffer (find-buffer-visiting file1)
2755 (concat "^" (regexp-quote todo-category-beg)) nil t)
2758 (setq end (if (re-search-forward
2759 (concat "^" (regexp-quote
2760 todo-category-beg)) nil t)
2764 (while (< (point) end)
2765 (if (todo-marked-item-p)
2767 (todo-forward-item)))
2768 (setq todo-categories-with-marks
2769 (assq-delete-all cat1 todo-categories-with-marks)))
2770 (if ov (delete-overlay ov))
2771 (todo-remove-item))))
2772 (when todo (todo-update-count 'todo (- todo) cat1))
2773 (when diary (todo-update-count 'diary (- diary) cat1))
2774 (when done (todo-update-count 'done (- done) cat1))
2775 (todo-update-categories-sexp))
2776 (set-window-buffer (selected-window)
2777 (set-buffer (find-file-noselect file2 'nowarn)))
2778 (setq todo-category-number (todo-category-number cat2))
2779 (let ((todo-show-with-done (or done-items done-item)))
2780 (todo-category-select))
2782 ;; If item is moved to end of (just first?) category, make
2783 ;; sure the items above it are displayed in the window.
2785 ;; User quit before setting priority of todo item(s), so
2786 ;; return to starting category.
2788 (set-window-buffer (selected-window)
2789 (set-buffer (find-file-noselect file1 'nowarn)))
2790 (todo-category-number cat1)
2791 (todo-category-select)
2792 (goto-char omark))))))))
2794 (defun todo-item-done (&optional arg)
2795 "Tag a todo item in this category as done and relocate it.
2797 With prefix argument ARG prompt for a comment and append it to
2798 the done item; this is only possible if there are no marked
2799 items. If there are marked items, tag all of these with
2800 `todo-done-string' plus the current date and, if
2801 `todo-always-add-time-string' is non-nil, the current time;
2802 otherwise, just tag the item at point. Items tagged as done are
2803 relocated to the category's (by default hidden) done section. If
2804 done items are visible on invoking this command, they remain
2807 (let* ((cat (todo-current-category))
2808 (marked (assoc cat todo-categories-with-marks)))
2809 (when marked (todo--user-error-if-marked-done-item))
2810 (unless (and (not marked)
2811 (or (todo-done-item-p)
2812 ;; Point is between todo and done items.
2814 (let* ((date-string (calendar-date-string (calendar-current-date) t t))
2815 (time-string (if todo-always-add-time-string
2816 (concat " " (substring (current-time-string)
2819 (done-prefix (concat "[" todo-done-string date-string time-string
2821 (comment (and arg (read-string "Enter a comment: ")))
2824 (show-done (save-excursion
2825 (goto-char (point-min))
2826 (re-search-forward todo-done-string-start nil t)))
2827 (buffer-read-only nil)
2830 ;; Don't add empty comment to done item.
2831 (setq comment (unless (zerop (length comment))
2832 (concat " [" todo-comment-string ": " comment "]")))
2833 (and marked (goto-char (point-min)))
2835 ;; Stop looping when we hit the empty line below the last
2836 ;; todo item (this is eobp if only done items are hidden).
2837 (while (not (looking-at "^$"))
2838 (if (or (not marked) (and marked (todo-marked-item-p)))
2840 (setq item (todo-item-string))
2841 (setq done-item (concat done-item done-prefix item
2842 comment (and marked "\n")))
2843 (setq item-count (1+ item-count))
2844 (when (todo-diary-item-p)
2845 (setq diary-count (1+ diary-count)))
2847 (unless marked (throw 'done nil)))
2848 (todo-forward-item))))
2850 ;; Chop off last newline of done item string.
2851 (setq done-item (substring done-item 0 -1))
2852 (setq todo-categories-with-marks
2853 (assq-delete-all cat todo-categories-with-marks)))
2857 (concat "^" (regexp-quote todo-category-done)) nil t)
2859 (when show-done (setq opoint (point)))
2860 (insert done-item "\n"))
2861 (todo-update-count 'todo (- item-count))
2862 (todo-update-count 'done item-count)
2863 (todo-update-count 'diary (- diary-count))
2864 (todo-update-categories-sexp)
2865 (let ((todo-show-with-done show-done))
2866 (todo-category-select)
2867 ;; When done items are visible, put point at the top of the
2868 ;; done items section. When done items are hidden, restore
2869 ;; point to its location prior to invoking this command.
2870 (when opoint (goto-char opoint)))))))
2872 (defun todo-item-undone ()
2873 "Restore at least one done item to this category's todo section.
2874 Prompt for the new priority. If there are marked items, undo all
2875 of these, giving the first undone item the new priority and the
2876 rest following directly in sequence; otherwise, undo just the
2879 If the done item has a comment, ask whether to omit the comment
2880 from the restored item. With multiple marked done items with
2881 comments, only ask once, and if affirmed, omit subsequent
2882 comments without asking."
2884 (let* ((cat (todo-current-category))
2885 (marked (assoc cat todo-categories-with-marks))
2886 (pl (if (and marked (> (cdr marked) 1)) "s" "")))
2887 (when (or marked (todo-done-item-p))
2888 (let ((buffer-read-only)
2890 (omark (point-marker))
2894 start end item ov npoint undone)
2895 (and marked (goto-char (point-min)))
2898 (when (or (not marked) (and marked (todo-marked-item-p)))
2899 (if (not (todo-done-item-p))
2902 (user-error "Only done items can be undone"))
2905 (setq ov (make-overlay (save-excursion (todo-item-start))
2906 (save-excursion (todo-item-end))))
2907 (overlay-put ov 'face 'todo-search))
2908 ;; Find the end of the date string added upon tagging item as
2910 (setq start (search-forward "] "))
2911 (setq item-count (1+ item-count))
2912 (unless (looking-at (regexp-quote todo-nondiary-start))
2913 (setq diary-count (1+ diary-count)))
2914 (setq end (save-excursion (todo-item-end)))
2915 ;; Ask (once) whether to omit done item's comment. If
2916 ;; affirmed, omit subsequent comments without asking.
2917 (when (re-search-forward
2918 (concat " \\[" (regexp-quote todo-comment-string)
2919 ": [^]]+\\]") end t)
2921 (if (eq first 'first)
2923 (if (eq todo-undo-item-omit-comment 'ask)
2924 (when (todo-y-or-n-p
2925 (concat "Omit comment" pl
2926 " from restored item"
2929 (when todo-undo-item-omit-comment 'omit)))
2931 (when (and (eq first 'first) ov) (delete-overlay ov)))
2932 (when (eq first 'omit)
2933 (setq end (match-beginning 0))))
2934 (setq item (concat item
2935 (buffer-substring-no-properties start end)
2936 (when marked "\n")))
2937 (unless marked (throw 'done nil))))
2938 (todo-forward-item)))
2941 ;; Chop off last newline of multiple items string, since
2942 ;; it will be reinserted on setting priority.
2943 (and marked (setq item (substring item 0 -1)))
2944 (todo-set-item-priority item cat t)
2945 (setq npoint (point))
2947 (when ov (delete-overlay ov))
2954 (concat "^" (regexp-quote todo-category-done)) nil t)
2956 (if (todo-marked-item-p)
2958 (todo-forward-item)))
2959 (setq todo-categories-with-marks
2960 (assq-delete-all cat todo-categories-with-marks)))
2963 (todo-update-count 'todo item-count)
2964 (todo-update-count 'done (- item-count))
2965 (when diary-count (todo-update-count 'diary diary-count))
2966 (todo-update-categories-sexp)
2967 (let ((todo-show-with-done (> (todo-get-count 'done) 0)))
2968 (todo-category-select))
2969 ;; Put cursor on undone item.
2970 (goto-char npoint)))
2971 (set-marker omark nil)))))
2973 ;; -----------------------------------------------------------------------------
2974 ;;; Done item archives
2975 ;; -----------------------------------------------------------------------------
2977 (defun todo-find-archive (&optional ask)
2978 "Visit the archive of the current todo category, if it exists.
2979 If the category has no archived items, prompt to visit the
2980 archive anyway. If there is no archive for this file or with
2981 non-nil argument ASK, prompt to visit another archive.
2983 The buffer showing the archive is in Todo Archive mode. The
2984 first visit in a session displays the first category in the
2985 archive, subsequent visits return to the last category
2988 (if (null (funcall todo-files-function t))
2989 (message "There are no archive files")
2990 (let* ((cat (todo-current-category))
2991 (count (todo-get-count 'archived cat))
2992 (archive (concat (file-name-sans-extension todo-current-todo-file)
2994 (place (cond (ask 'other-archive)
2995 ((file-exists-p archive) 'this-archive)
2996 (t (when (todo-y-or-n-p
2997 (concat "This file has no archive; "
2998 "visit another archive? "))
3000 (when (eq place 'other-archive)
3001 (setq archive (todo-read-file-name "Choose a todo archive: " t t)))
3002 (when (and (eq place 'this-archive) (zerop count))
3003 (setq place (when (todo-y-or-n-p
3004 (concat "This category has no archived items;"
3005 " visit archive anyway? "))
3008 (set-window-buffer (selected-window)
3009 (set-buffer (find-file-noselect archive)))
3010 (unless (derived-mode-p 'todo-archive-mode) (todo-archive-mode))
3011 (if (member place '(other-archive other-cat))
3012 (setq todo-category-number 1)
3013 (todo-category-number cat))
3014 (todo-category-select)))))
3016 (defun todo-choose-archive ()
3017 "Choose an archive and visit it."
3019 (todo-find-archive t))
3021 (defun todo-archive-done-item (&optional all)
3022 "Archive at least one done item in this category.
3024 With prefix argument ALL, prompt whether to archive all done
3025 items in this category and on confirmation archive them.
3026 Otherwise, if there are marked done items (and no marked todo
3027 items), archive all of these; otherwise, archive the done item at
3030 If the archive of this file does not exist, it is created. If
3031 this category does not exist in the archive, it is created."
3033 (when (eq major-mode 'todo-mode)
3034 (if (and all (zerop (todo-get-count 'done)))
3035 (message "No done items in this category")
3037 (let* ((cat (todo-current-category))
3038 (tbuf (current-buffer))
3039 (marked (assoc cat todo-categories-with-marks))
3040 (afile (concat (file-name-sans-extension
3041 todo-current-todo-file) ".toda"))
3042 (archive (find-file-noselect afile t))
3043 (item (and (not marked) (todo-done-item-p)
3044 (concat (todo-item-string) "\n")))
3046 (opoint (unless (todo-done-item-p) (point)))
3047 marked-items beg end all-done
3051 (if (todo-y-or-n-p "Archive all done items in this category? ")
3054 (goto-char (point-min))
3057 (re-search-forward todo-done-string-start
3059 (match-beginning 0))
3060 end (if (re-search-forward
3062 (regexp-quote todo-category-beg))
3066 all-done (buffer-substring-no-properties beg end)
3067 count (todo-get-count 'done))
3068 ;; Restore starting point, unless it was on a done
3069 ;; item, since they will all be deleted.
3070 (when opoint (goto-char opoint))))
3074 (goto-char (point-min))
3076 (when (todo-marked-item-p)
3077 (if (not (todo-done-item-p))
3078 (throw 'end (message "Only done items can be archived"))
3080 (concat marked-items (todo-item-string) "\n"))
3081 (setq count (1+ count))))
3082 (todo-forward-item)))))
3083 (if (not (or marked all item))
3084 (throw 'end (message "Only done items can be archived"))
3085 (with-current-buffer archive
3086 (unless (derived-mode-p 'todo-archive-mode) (todo-archive-mode))
3087 (let (buffer-read-only)
3089 (goto-char (point-min))
3090 (if (and (re-search-forward
3091 (concat "^" (regexp-quote
3092 (concat todo-category-beg cat)) "$")
3094 (re-search-forward (regexp-quote todo-category-done)
3096 ;; Start of done items section in existing category.
3098 (todo-add-category nil cat)
3099 ;; Start of done items section in new category.
3100 (goto-char (point-max)))
3101 (insert (cond (marked marked-items)
3104 (todo-update-count 'done (if (or marked all) count 1) cat)
3105 (todo-update-categories-sexp)
3106 ;; If archive is new, save to file now (with
3107 ;; write-region to avoid prompt for file to save to)
3108 ;; to update todo-archives, and set the mode for
3109 ;; visiting the archive below.
3110 (unless (nth 7 (file-attributes afile))
3111 (write-region nil nil afile t t)
3112 (setq todo-archives (funcall todo-files-function t))
3113 (todo-archive-mode))))
3114 (with-current-buffer tbuf
3119 ;; Make sure done items are accessible.
3121 (remove-overlays beg end)
3122 (delete-region beg end)
3123 (todo-update-count 'done (- count))
3124 (todo-update-count 'archived count))))
3126 ;; If we're archiving all done items, can't
3127 ;; first archive item point was on, since
3128 ;; that will short-circuit the rest.
3129 (and item (not all)))
3130 (and marked (goto-char (point-min)))
3133 (if (or (and marked (todo-marked-item-p)) item)
3136 (todo-update-count 'done -1)
3137 (todo-update-count 'archived 1)
3138 ;; Don't leave point below last item.
3139 (and (or marked item) (bolp) (eolp)
3140 (< (point-min) (point-max))
3141 (todo-backward-item))
3143 (throw 'done (setq item nil))))
3144 (todo-forward-item))))))
3146 (setq todo-categories-with-marks
3147 (assq-delete-all cat todo-categories-with-marks)))
3148 (todo-update-categories-sexp)
3149 (todo-prefix-overlays)))
3151 (todo-category-number cat)
3152 (todo-category-select)
3153 (split-window-below)
3154 (set-window-buffer (selected-window) tbuf)
3155 ;; Make todo file current to select category.
3156 (find-file (buffer-file-name tbuf))
3157 ;; Make sure done item separator is hidden (if done items
3158 ;; were initially visible).
3159 (let (todo-show-with-done) (todo-category-select)))))))
3161 (defun todo-unarchive-items ()
3162 "Unarchive at least one item in this archive category.
3163 If there are marked items, unarchive all of these; otherwise,
3164 unarchive the item at point.
3166 Unarchived items are restored as done items to the corresponding
3167 category in the todo file, inserted at the top of done items
3168 section. If all items in the archive category have been
3169 restored, the category is deleted from the archive. If this was
3170 the only category in the archive, the archive file is deleted."
3172 (when (eq major-mode 'todo-archive-mode)
3173 (let* ((cat (todo-current-category))
3174 (tbuf (find-file-noselect
3175 (concat (file-name-sans-extension todo-current-todo-file)
3177 (marked (assoc cat todo-categories-with-marks))
3178 (item (concat (todo-item-string) "\n"))
3184 (goto-char (point-min))
3186 (when (todo-marked-item-p)
3187 (setq marked-items (concat marked-items (todo-item-string) "\n"))
3188 (setq marked-count (1+ marked-count)))
3189 (todo-forward-item))))
3190 ;; Restore items to top of category's done section and update counts.
3191 (with-current-buffer tbuf
3192 (let (buffer-read-only newcat)
3194 (goto-char (point-min))
3195 ;; Find the corresponding todo category, or if there isn't
3197 (unless (re-search-forward
3198 (concat "^" (regexp-quote (concat todo-category-beg cat))
3200 (todo-add-category nil cat)
3202 ;; Go to top of category's done section.
3204 (concat "^" (regexp-quote todo-category-done)) nil t)
3207 (insert marked-items)
3208 (todo-update-count 'done marked-count cat)
3209 (unless newcat ; Newly added category has no archive.
3210 (todo-update-count 'archived (- marked-count) cat)))
3213 (todo-update-count 'done 1 cat)
3214 (unless newcat ; Newly added category has no archive.
3215 (todo-update-count 'archived -1 cat))))
3216 (todo-update-categories-sexp)))
3217 ;; Delete restored items from archive.
3220 (goto-char (point-min)))
3223 (if (or (todo-marked-item-p) item)
3227 (throw 'done (setq item nil))))
3228 (todo-forward-item))))
3229 (todo-update-count 'done (if marked (- marked-count) -1) cat)
3230 ;; If we unarchived the last item in category, then if that was
3231 ;; the only category, delete the whole file, otherwise, just
3232 ;; delete the category.
3233 (when (= 0 (todo-get-count 'done))
3234 (if (= 1 (length todo-categories))
3236 (delete-file todo-current-todo-file)
3237 ;; Kill the archive buffer silently.
3238 (set-buffer-modified-p nil)
3241 (let ((beg (re-search-backward
3242 (concat "^" (regexp-quote todo-category-beg) cat "$")
3244 (end (if (re-search-forward
3245 (concat "^" (regexp-quote todo-category-beg))
3249 (remove-overlays beg end)
3250 (delete-region beg end)
3251 (setq todo-categories (delete (assoc cat todo-categories)
3252 todo-categories)))))
3253 (todo-update-categories-sexp)
3254 ;; Visit category in todo file and show restored done items.
3255 (let ((tfile (buffer-file-name tbuf))
3256 (todo-show-with-done t))
3257 (set-window-buffer (selected-window)
3258 (set-buffer (find-file-noselect tfile)))
3259 (todo-category-number cat)
3260 (todo-category-select)
3261 (message "Items unarchived.")))))
3263 (defun todo-jump-to-archive-category (&optional file)
3264 "Prompt for a category in a todo archive and jump to it.
3265 With prefix argument FILE, prompt for an archive and choose (with
3266 TAB completion) a category in it to jump to; otherwise, choose
3267 and jump to any category in the current archive."
3269 (todo-jump-to-category file 'archive))
3271 ;; -----------------------------------------------------------------------------
3272 ;;; Displaying and sorting tables of categories
3273 ;; -----------------------------------------------------------------------------
3275 (defcustom todo-categories-category-label "Category"
3276 "Category button label in Todo Categories mode."
3278 :group 'todo-categories)
3280 (defcustom todo-categories-todo-label "Todo"
3281 "Todo button label in Todo Categories mode."
3283 :group 'todo-categories)
3285 (defcustom todo-categories-diary-label "Diary"
3286 "Diary button label in Todo Categories mode."
3288 :group 'todo-categories)
3290 (defcustom todo-categories-done-label "Done"
3291 "Done button label in Todo Categories mode."
3293 :group 'todo-categories)
3295 (defcustom todo-categories-archived-label "Archived"
3296 "Archived button label in Todo Categories mode."
3298 :group 'todo-categories)
3300 (defcustom todo-categories-totals-label "Totals"
3301 "String to label total item counts in Todo Categories mode."
3303 :group 'todo-categories)
3305 (defcustom todo-categories-number-separator " | "
3306 "String between number and category in Todo Categories mode.
3307 This separates the number from the category name in the default
3308 categories display according to priority."
3310 :group 'todo-categories)
3312 (defcustom todo-categories-align 'center
3313 "Alignment of category names in Todo Categories mode."
3314 :type '(radio (const left) (const center) (const right))
3315 :group 'todo-categories)
3317 (defun todo-show-categories-table ()
3318 "Display a table of the current file's categories and item counts.
3320 In the initial display the lines of the table are numbered,
3321 indicating the current order of the categories when sequentially
3322 navigating through the todo file with `\\[todo-forward-category]'
3323 and `\\[todo-backward-category]'. You can reorder the lines, and
3324 hence the category sequence, by typing `\\[todo-raise-category]'
3325 or `\\[todo-lower-category]' to raise or lower the category at
3326 point, or by typing `\\[todo-set-category-number]' and entering a
3327 number at the prompt or by typing `\\[todo-set-category-number]'
3328 with a numeric prefix. If you save the todo file after
3329 reordering the categories, the new order persists in subsequent
3332 The labels above the category names and item counts are buttons,
3333 and clicking these changes the display: sorted by category name
3334 or by the respective item counts (alternately descending or
3335 ascending). In these displays the categories are not numbered
3336 and `\\[todo-set-category-number]', `\\[todo-raise-category]' and
3337 `\\[todo-lower-category]' are disabled. (Programmatically, the
3338 sorting is triggered by passing a non-nil SORTKEY argument.)
3340 In addition, the lines with the category names and item counts
3341 are buttonized, and pressing one of these button jumps to the
3342 category in Todo mode (or Todo Archive mode, for categories
3343 containing only archived items, provided user option
3344 `todo-skip-archived-categories' is non-nil. These categories
3345 are shown in `todo-archived-only' face."
3347 (todo-display-categories)
3349 (todo-update-categories-display sortkey)))
3351 (defun todo-next-button (n)
3352 "Move point to the Nth next button in the table of categories."
3354 (forward-button n 'wrap 'display-message)
3355 (and (bolp) (button-at (point))
3356 ;; Align with beginning of category label.
3357 (forward-char (+ 4 (length todo-categories-number-separator)))))
3359 (defun todo-previous-button (n)
3360 "Move point to the Nth previous button in the table of categories."
3362 (backward-button n 'wrap 'display-message)
3363 (and (bolp) (button-at (point))
3364 ;; Align with beginning of category label.
3365 (forward-char (+ 4 (length todo-categories-number-separator)))))
3367 (defun todo-set-category-number (&optional arg)
3368 "Change number of category at point in the table of categories.
3370 With ARG nil, prompt for the new number. Alternatively, the
3371 enter the new number with numerical prefix ARG. Otherwise, if
3372 ARG is either of the symbols `raise' or `lower', raise or lower
3373 the category line in the table by one, respectively, thereby
3374 decreasing or increasing its number."
3376 (let ((curnum (save-excursion
3377 ;; Get the number representing the priority of the category
3378 ;; on the current line.
3379 (forward-line 0) (skip-chars-forward " ") (number-at-point))))
3380 (when curnum ; Do nothing if we're not on a category line.
3381 (let* ((maxnum (length todo-categories))
3382 (prompt (format "Set category priority (1-%d): " maxnum))
3383 (col (current-column))
3384 (buffer-read-only nil)
3385 (priority (cond ((and (eq arg 'raise) (> curnum 1))
3387 ((and (eq arg 'lower) (< curnum maxnum))
3390 (while (not priority)
3391 (setq candidate (or arg (read-number prompt)))
3394 (cond ((or (< candidate 1) (> candidate maxnum))
3395 (format "Priority must be an integer between 1 and %d: "
3397 ((= candidate curnum)
3398 "Choose a different priority than the current one: ")))
3399 (unless prompt (setq priority candidate)))
3400 (let* ((lower (< curnum priority)) ; Priority is being lowered.
3401 (head (butlast todo-categories
3402 (apply (if lower 'identity '1+)
3403 (list (- maxnum priority)))))
3404 (tail (nthcdr (apply (if lower 'identity '1-) (list priority))
3406 ;; Category's name and items counts list.
3407 (catcons (nth (1- curnum) todo-categories))
3408 (todo-categories (nconc head (list catcons) tail))
3410 (when lower (setq todo-categories (nreverse todo-categories)))
3411 (setq todo-categories (delete-dups todo-categories))
3412 (when lower (setq todo-categories (nreverse todo-categories)))
3413 (setq newcats todo-categories)
3415 (with-current-buffer (find-buffer-visiting todo-current-todo-file)
3416 (setq todo-categories newcats)
3417 (todo-update-categories-sexp))
3418 (todo-show-categories-table)
3419 (forward-line (1+ priority))
3420 (forward-char col))))))
3422 (defun todo-raise-category ()
3423 "Raise priority of category at point in the table of categories."
3425 (todo-set-category-number 'raise))
3427 (defun todo-lower-category ()
3428 "Lower priority of category at point in the table of categories."
3430 (todo-set-category-number 'lower))
3432 (defun todo-sort-categories-alphabetically-or-numerically ()
3433 "Sort table of categories alphabetically or numerically."
3436 (goto-char (point-min))
3438 (if (member 'alpha todo-descending-counts)
3440 (todo-update-categories-display nil)
3441 (setq todo-descending-counts
3442 (delete 'alpha todo-descending-counts)))
3443 (todo-update-categories-display 'alpha))))
3445 (defun todo-sort-categories-by-todo ()
3446 "Sort table of categories by number of todo items."
3449 (goto-char (point-min))
3451 (todo-update-categories-display 'todo)))
3453 (defun todo-sort-categories-by-diary ()
3454 "Sort table of categories by number of diary items."
3457 (goto-char (point-min))
3459 (todo-update-categories-display 'diary)))
3461 (defun todo-sort-categories-by-done ()
3462 "Sort table of categories by number of non-archived done items."
3465 (goto-char (point-min))
3467 (todo-update-categories-display 'done)))
3469 (defun todo-sort-categories-by-archived ()
3470 "Sort table of categories by number of archived items."
3473 (goto-char (point-min))
3475 (todo-update-categories-display 'archived)))
3477 (defvar todo-categories-buffer "*Todo Categories*"
3478 "Name of buffer in Todo Categories mode.")
3480 (defun todo-longest-category-name-length (categories)
3481 "Return the length of the longest name in list CATEGORIES."
3483 (dolist (c categories longest)
3484 (setq longest (max longest (length c))))))
3486 (defun todo-adjusted-category-label-length ()
3487 "Return adjusted length of category label button.
3488 The adjustment ensures proper tabular alignment in Todo
3490 (let* ((categories (mapcar 'car todo-categories))
3491 (longest (todo-longest-category-name-length categories))
3492 (catlablen (length todo-categories-category-label))
3493 (lc-diff (- longest catlablen)))
3494 (if (and (natnump lc-diff) (cl-oddp lc-diff))
3496 (max longest catlablen))))
3498 (defun todo-padded-string (str)
3499 "Return category name or label string STR padded with spaces.
3500 The placement of the padding is determined by the value of user
3501 option `todo-categories-align'."
3502 (let* ((len (todo-adjusted-category-label-length))
3503 (strlen (length str))
3504 (strlen-odd (eq (logand strlen 1) 1))
3505 (padding (max 0 (/ (- len strlen) 2)))
3506 (padding-left (cond ((eq todo-categories-align 'left) 0)
3507 ((eq todo-categories-align 'center) padding)
3508 ((eq todo-categories-align 'right)
3509 (if strlen-odd (1+ (* padding 2)) (* padding 2)))))
3510 (padding-right (cond ((eq todo-categories-align 'left)
3511 (if strlen-odd (1+ (* padding 2)) (* padding 2)))
3512 ((eq todo-categories-align 'center)
3513 (if strlen-odd (1+ padding) padding))
3514 ((eq todo-categories-align 'right) 0))))
3515 (concat (make-string padding-left 32) str (make-string padding-right 32))))
3517 (defvar todo-descending-counts nil
3518 "List of keys for category counts sorted in descending order.")
3520 (defun todo-sort (list &optional key)
3521 "Return a copy of LIST, possibly sorted according to KEY."
3522 (let* ((l (copy-sequence list))
3523 (fn (if (eq key 'alpha)
3524 (lambda (x) (upcase x)) ; Alphabetize case insensitively.
3525 (lambda (x) (todo-get-count key x))))
3526 ;; Keep track of whether the last sort by key was descending or
3528 (descending (member key todo-descending-counts))
3529 (cmp (if (eq key 'alpha)
3531 (if descending '< '>)))
3532 (pred (lambda (s1 s2) (let ((t1 (funcall fn (car s1)))
3533 (t2 (funcall fn (car s2))))
3534 (funcall cmp t1 t2)))))
3536 (setq l (sort l pred))
3537 ;; Switch between descending and ascending sort order.
3539 (setq todo-descending-counts
3540 (delete key todo-descending-counts))
3541 (push key todo-descending-counts)))
3544 (defun todo-display-sorted (type)
3545 "Keep point on the TYPE count sorting button just clicked."
3546 (let ((opoint (point)))
3547 (todo-update-categories-display type)
3548 (goto-char opoint)))
3550 (defun todo-label-to-key (label)
3551 "Return symbol for sort key associated with LABEL."
3553 (cond ((string= label todo-categories-category-label)
3555 ((string= label todo-categories-todo-label)
3557 ((string= label todo-categories-diary-label)
3559 ((string= label todo-categories-done-label)
3561 ((string= label todo-categories-archived-label)
3562 (setq key 'archived)))
3565 (defun todo-insert-sort-button (label)
3566 "Insert button for displaying categories sorted by item counts.
3567 LABEL determines which type of count is sorted."
3568 (let* ((str (if (string= label todo-categories-category-label)
3569 (todo-padded-string label)
3572 (end (+ beg (length str)))
3574 (insert-button str 'face nil
3577 (let ((key (todo-label-to-key ,label)))
3578 (if (and (member key todo-descending-counts)
3581 ;; If display is alphabetical, switch back to
3582 ;; category priority order.
3583 (todo-display-sorted nil)
3584 (setq todo-descending-counts
3585 (delete key todo-descending-counts)))
3586 (todo-display-sorted key)))))
3587 (setq ov (make-overlay beg end))
3588 (overlay-put ov 'face 'todo-button)))
3590 (defun todo-total-item-counts ()
3591 "Return a list of total item counts for the current file."
3592 (mapcar (lambda (i) (apply '+ (mapcar (lambda (l) (aref l i))
3593 (mapcar 'cdr todo-categories))))
3596 (defvar todo-categories-category-number 0
3597 "Variable for numbering categories in Todo Categories mode.")
3599 (defun todo-insert-category-line (cat &optional nonum)
3600 "Insert button with category CAT's name and item counts.
3601 With non-nil argument NONUM show only these; otherwise, insert a
3602 number in front of the button indicating the category's priority.
3603 The number and the category name are separated by the string
3604 which is the value of the user option
3605 `todo-categories-number-separator'."
3606 (let ((archive (member todo-current-todo-file todo-archives))
3607 (num todo-categories-category-number)
3608 (str (todo-padded-string cat))
3610 (setq num (1+ num) todo-categories-category-number num)
3613 (make-string (+ 4 (length todo-categories-number-separator))
3615 (format " %3d%s" num todo-categories-number-separator))
3617 (mapconcat (lambda (elt)
3619 (make-string (1+ (/ (length (car elt)) 2)) 32) ; label
3620 (format "%3d" (todo-get-count (cdr elt) cat)) ; count
3621 ;; Add an extra space if label length is odd.
3622 (when (cl-oddp (length (car elt))) " ")))
3624 (list (cons todo-categories-done-label 'done))
3625 (list (cons todo-categories-todo-label 'todo)
3626 (cons todo-categories-diary-label 'diary)
3627 (cons todo-categories-done-label 'done)
3628 (cons todo-categories-archived-label
3631 " ") ; Make highlighting on last column look better.
3632 'face (if (and todo-skip-archived-categories
3633 (zerop (todo-get-count 'todo cat))
3634 (zerop (todo-get-count 'done cat))
3635 (not (zerop (todo-get-count 'archived cat))))
3638 'action `(lambda (button) (let ((buf (current-buffer)))
3639 (todo-jump-to-category nil ,cat)
3640 (kill-buffer buf))))
3641 ;; Highlight the sorted count column.
3642 (let* ((beg (+ opoint 7 (length str)))
3644 (cond ((eq nonum 'todo)
3645 (setq beg (+ beg 1 (/ (length todo-categories-todo-label) 2))))
3647 (setq beg (+ beg 1 (length todo-categories-todo-label)
3648 2 (/ (length todo-categories-diary-label) 2))))
3650 (setq beg (+ beg 1 (length todo-categories-todo-label)
3651 2 (length todo-categories-diary-label)
3652 2 (/ (length todo-categories-done-label) 2))))
3653 ((eq nonum 'archived)
3654 (setq beg (+ beg 1 (length todo-categories-todo-label)
3655 2 (length todo-categories-diary-label)
3656 2 (length todo-categories-done-label)
3657 2 (/ (length todo-categories-archived-label) 2)))))
3658 (unless (= beg (+ opoint 7 (length str))) ; Don't highlight categories.
3659 (setq end (+ beg 4))
3660 (setq ovl (make-overlay beg end))
3661 (overlay-put ovl 'face 'todo-sorted-column)))
3664 (defun todo-display-categories ()
3665 "Prepare buffer for displaying table of categories and item counts."
3666 (unless (eq major-mode 'todo-categories-mode)
3667 (setq todo-global-current-todo-file
3668 (or todo-current-todo-file
3669 (todo-absolute-file-name todo-default-todo-file)))
3670 (set-window-buffer (selected-window)
3671 (set-buffer (get-buffer-create todo-categories-buffer)))
3672 (kill-all-local-variables)
3673 (todo-categories-mode)
3674 (let ((archive (member todo-current-todo-file todo-archives))
3677 (insert (format (concat "Category counts for todo "
3678 (if archive "archive" "file")
3680 (todo-short-file-name todo-current-todo-file)))
3682 ;; Make space for the column of category numbers.
3683 (insert (make-string (+ 4 (length todo-categories-number-separator)) 32))
3684 ;; Add the category and item count buttons (if this is the list of
3685 ;; categories in an archive, show only done item counts).
3686 (todo-insert-sort-button todo-categories-category-label)
3689 (insert (make-string 3 32))
3690 (todo-insert-sort-button todo-categories-done-label))
3691 (insert (make-string 3 32))
3692 (todo-insert-sort-button todo-categories-todo-label)
3693 (insert (make-string 2 32))
3694 (todo-insert-sort-button todo-categories-diary-label)
3695 (insert (make-string 2 32))
3696 (todo-insert-sort-button todo-categories-done-label)
3697 (insert (make-string 2 32))
3698 (todo-insert-sort-button todo-categories-archived-label))
3701 (defun todo-update-categories-display (sortkey)
3702 "Populate table of categories and sort by SORTKEY."
3703 (let* ((cats0 todo-categories)
3704 (cats (todo-sort cats0 sortkey))
3705 (archive (member todo-current-todo-file todo-archives))
3706 (todo-categories-category-number 0)
3707 ;; Find start of Category button if we just entered Todo Categories
3709 (pt (if (eq (point) (point-max))
3712 (goto-char (next-single-char-property-change
3713 (point) 'face nil (line-end-position))))))
3716 (delete-region (point) (point-max))
3717 ;; Fill in the table with buttonized lines, each showing a category and
3719 (mapc (lambda (cat) (todo-insert-category-line cat sortkey))
3722 ;; Add a line showing item count totals.
3723 (insert (make-string (+ 4 (length todo-categories-number-separator)) 32)
3724 (todo-padded-string todo-categories-totals-label)
3728 (make-string (1+ (/ (length (car elt)) 2)) 32)
3729 (format "%3d" (nth (cdr elt) (todo-total-item-counts)))
3730 ;; Add an extra space if label length is odd.
3731 (when (cl-oddp (length (car elt))) " ")))
3733 (list (cons todo-categories-done-label 2))
3734 (list (cons todo-categories-todo-label 0)
3735 (cons todo-categories-diary-label 1)
3736 (cons todo-categories-done-label 2)
3737 (cons todo-categories-archived-label 3)))
3739 ;; Put cursor on Category button initially.
3740 (if pt (goto-char pt))
3741 (setq buffer-read-only t)))
3743 ;; -----------------------------------------------------------------------------
3744 ;;; Searching and item filtering
3745 ;; -----------------------------------------------------------------------------
3747 (defun todo-search ()
3748 "Search for a regular expression in this todo file.
3749 The search runs through the whole file and encompasses all and
3750 only todo and done items; it excludes category names. Multiple
3751 matches are shown sequentially, highlighted in `todo-search'
3754 (let ((regex (read-from-minibuffer "Enter a search string (regexp): "))
3756 matches match cat in-done ov mlen msg)
3758 (goto-char (point-min))
3760 (setq match (re-search-forward regex nil t))
3761 (goto-char (line-beginning-position))
3762 (unless (or (equal (point) 1)
3763 (looking-at (concat "^" (regexp-quote todo-category-beg))))
3764 (if match (push match matches)))
3766 (setq matches (reverse matches))
3770 (setq match (pop matches))
3773 (when (looking-at todo-done-string-start)
3775 (re-search-backward (concat "^" (regexp-quote todo-category-beg)
3776 "\\(.*\\)\n") nil t)
3777 (setq cat (match-string-no-properties 1))
3778 (todo-category-number cat)
3779 (todo-category-select)
3781 (unless todo-show-with-done (todo-toggle-view-done-items)))
3783 (setq ov (make-overlay (- (point) (length regex)) (point)))
3784 (overlay-put ov 'face 'todo-search)
3786 (setq mlen (length matches))
3789 (format "There are %d more matches; go to next match? "
3791 "There is one more match; go to it? "))
3793 (throw 'stop (setq msg (if (> mlen 1)
3794 (format "There are %d more matches."
3796 "There is one more match."))))))
3797 (setq msg "There are no more matches."))
3798 (todo-category-select)
3800 (message "No match for \"%s\"" regex))
3802 (if (todo-y-or-n-p (concat msg "\nUnhighlight matches? "))
3803 (todo-clear-matches)
3804 (message "You can unhighlight the matches later by typing %s"
3805 (key-description (car (where-is-internal
3806 'todo-clear-matches))))))))
3808 (defun todo-clear-matches ()
3809 "Remove highlighting on matches found by todo-search."
3811 (remove-overlays 1 (1+ (buffer-size)) 'face 'todo-search))
3813 (defcustom todo-top-priorities-overrides nil
3814 "List of rules specifying number of top priority items to show.
3815 These rules override `todo-top-priorities' on invocations of
3816 `\\[todo-filter-top-priorities]' and
3817 `\\[todo-filter-top-priorities-multifile]'. Each rule is a list
3818 of the form (FILE NUM ALIST), where FILE is a member of
3819 `todo-files', NUM is a number specifying the default number of
3820 top priority items for each category in that file, and ALIST,
3821 when non-nil, consists of conses of a category name in FILE and a
3822 number specifying the default number of top priority items in
3823 that category, which overrides NUM.
3825 This variable should be set interactively by
3826 `\\[todo-set-top-priorities-in-file]' or
3827 `\\[todo-set-top-priorities-in-category]'."
3829 :group 'todo-filtered)
3831 (defcustom todo-top-priorities 1
3832 "Default number of top priorities shown by `todo-filter-top-priorities'."
3834 :group 'todo-filtered)
3836 (defcustom todo-filter-files nil
3837 "List of default files for multifile item filtering."
3838 :type `(set ,@(mapcar (lambda (f) (list 'const f))
3839 (mapcar 'todo-short-file-name
3840 (funcall todo-files-function))))
3841 :group 'todo-filtered)
3843 (defcustom todo-filter-done-items nil
3844 "Non-nil to include done items when processing regexp filters.
3845 Done items from corresponding archive files are also included."
3847 :group 'todo-filtered)
3849 (defun todo-set-top-priorities-in-file ()
3850 "Set number of top priorities for this file.
3851 See `todo-set-top-priorities' for more details."
3853 (todo-set-top-priorities))
3855 (defun todo-set-top-priorities-in-category ()
3856 "Set number of top priorities for this category.
3857 See `todo-set-top-priorities' for more details."
3859 (todo-set-top-priorities t))
3861 (defun todo-filter-top-priorities (&optional arg)
3862 "Display a list of top priority items from different categories.
3863 The categories can be any of those in the current todo file.
3865 With numerical prefix ARG show at most ARG top priority items
3866 from each category. With `C-u' as prefix argument show the
3867 numbers of top priority items specified by category in
3868 `todo-top-priorities-overrides', if this has an entry for the file(s);
3869 otherwise show `todo-top-priorities' items per category in the
3870 file(s). With no prefix argument, if a top priorities file for
3871 the current todo file has previously been saved (see
3872 `todo-save-filtered-items-buffer'), visit this file; if there is
3873 no such file, build the list as with prefix argument `C-u'.
3875 The prefix ARG regulates how many top priorities from
3876 each category to show, as described above."
3878 (todo-filter-items 'top arg))
3880 (defun todo-filter-top-priorities-multifile (&optional arg)
3881 "Display a list of top priority items from different categories.
3882 The categories are a subset of the categories in the files listed
3883 in `todo-filter-files', or if this nil, in the files chosen from
3884 a file selection dialog that pops up in this case.
3886 With numerical prefix ARG show at most ARG top priority items
3887 from each category in each file. With `C-u' as prefix argument
3888 show the numbers of top priority items specified in
3889 `todo-top-priorities-overrides', if this is non-nil; otherwise show
3890 `todo-top-priorities' items per category. With no prefix
3891 argument, if a top priorities file for the chosen todo files
3892 exists (see `todo-save-filtered-items-buffer'), visit this file;
3893 if there is no such file, do the same as with prefix argument
3896 (todo-filter-items 'top arg t))
3898 (defun todo-filter-diary-items (&optional arg)
3899 "Display a list of todo diary items from different categories.
3900 The categories can be any of those in the current todo file.
3902 Called with no prefix ARG, if a diary items file for the current
3903 todo file has previously been saved (see
3904 `todo-save-filtered-items-buffer'), visit this file; if there is
3905 no such file, build the list of diary items. Called with a
3906 prefix argument, build the list even if there is a saved file of
3909 (todo-filter-items 'diary arg))
3911 (defun todo-filter-diary-items-multifile (&optional arg)
3912 "Display a list of todo diary items from different categories.
3913 The categories are a subset of the categories in the files listed
3914 in `todo-filter-files', or if this nil, in the files chosen from
3915 a file selection dialog that pops up in this case.
3917 Called with no prefix ARG, if a diary items file for the chosen
3918 todo files has previously been saved (see
3919 `todo-save-filtered-items-buffer'), visit this file; if there is
3920 no such file, build the list of diary items. Called with a
3921 prefix argument, build the list even if there is a saved file of
3924 (todo-filter-items 'diary arg t))
3926 (defun todo-filter-regexp-items (&optional arg)
3927 "Prompt for a regular expression and display items that match it.
3928 The matches can be from any categories in the current todo file
3929 and with non-nil option `todo-filter-done-items', can include
3930 not only todo items but also done items, including those in
3933 Called with no prefix ARG, if a regexp items file for the current
3934 todo file has previously been saved (see
3935 `todo-save-filtered-items-buffer'), visit this file; if there is
3936 no such file, build the list of regexp items. Called with a
3937 prefix argument, build the list even if there is a saved file of
3940 (todo-filter-items 'regexp arg))
3942 (defun todo-filter-regexp-items-multifile (&optional arg)
3943 "Prompt for a regular expression and display items that match it.
3944 The matches can be from any categories in the files listed in
3945 `todo-filter-files', or if this nil, in the files chosen from a
3946 file selection dialog that pops up in this case. With non-nil
3947 option `todo-filter-done-items', the matches can include not
3948 only todo items but also done items, including those in Archive
3951 Called with no prefix ARG, if a regexp items file for the current
3952 todo file has previously been saved (see
3953 `todo-save-filtered-items-buffer'), visit this file; if there is
3954 no such file, build the list of regexp items. Called with a
3955 prefix argument, build the list even if there is a saved file of
3958 (todo-filter-items 'regexp arg t))
3960 (defun todo-find-filtered-items-file ()
3961 "Choose a filtered items file and visit it."
3963 (let ((files (directory-files todo-directory t "\.tod[rty]$" t))
3966 (let ((type (cond ((equal (file-name-extension f) "todr") "regexp")
3967 ((equal (file-name-extension f) "todt") "top")
3968 ((equal (file-name-extension f) "tody") "diary"))))
3969 (push (cons (concat (todo-short-file-name f) " (" type ")") f)
3971 (setq file (completing-read "Choose a filtered items file: "
3972 falist nil t nil nil (car falist)))
3973 (setq file (cdr (assoc-string file falist)))
3975 (unless (derived-mode-p 'todo-filtered-items-mode)
3976 (todo-filtered-items-mode))
3977 (todo-prefix-overlays)))
3979 (defun todo-go-to-source-item ()
3980 "Display the file and category of the filtered item at point."
3982 (let* ((str (todo-item-string))
3983 (buf (current-buffer))
3984 (res (todo-find-item str))
3989 (message "Category %s does not contain this item." cat)
3991 (set-window-buffer (selected-window)
3992 (set-buffer (find-buffer-visiting file)))
3993 (setq todo-current-todo-file file)
3994 (setq todo-category-number (todo-category-number cat))
3995 (let ((todo-show-with-done (if (or todo-filter-done-items
3996 (eq (cdr found) 'done))
3998 todo-show-with-done)))
3999 (todo-category-select))
4000 (goto-char (car found)))))
4002 (defvar todo-multiple-filter-files nil
4003 "List of files selected from `todo-multiple-filter-files' widget.")
4005 (defvar todo-multiple-filter-files-widget nil
4006 "Variable holding widget created by `todo-multiple-filter-files'.")
4008 (defun todo-multiple-filter-files ()
4009 "Pop to a buffer with a widget for choosing multiple filter files."
4012 (require 'wid-edit))
4013 (with-current-buffer (get-buffer-create "*Todo Filter Files*")
4014 (pop-to-buffer (current-buffer))
4016 (kill-all-local-variables)
4017 (widget-insert "Select files for generating the top priorities list.\n\n")
4018 (setq todo-multiple-filter-files-widget
4020 `(set ,@(mapcar (lambda (x) (list 'const x))
4021 (mapcar 'todo-short-file-name
4022 (funcall todo-files-function))))))
4023 (widget-insert "\n")
4024 (widget-create 'push-button
4025 :notify (lambda (widget &rest ignore)
4026 (setq todo-multiple-filter-files 'quit)
4028 (exit-recursive-edit))
4031 (widget-create 'push-button
4032 :notify (lambda (&rest ignore)
4033 (setq todo-multiple-filter-files
4036 (concat todo-directory
4039 todo-multiple-filter-files-widget)))
4041 (exit-recursive-edit))
4043 (use-local-map widget-keymap)
4045 (message "Click \"Apply\" after selecting files.")
4048 (defconst todo-filtered-items-buffer "Todo filtered items"
4049 "Initial name of buffer in Todo Filter Items mode.")
4051 (defconst todo-top-priorities-buffer "Todo top priorities"
4052 "Buffer type string for `todo-filter-items'.")
4054 (defconst todo-diary-items-buffer "Todo diary items"
4055 "Buffer type string for `todo-filter-items'.")
4057 (defconst todo-regexp-items-buffer "Todo regexp items"
4058 "Buffer type string for `todo-filter-items'.")
4060 (defun todo-filter-items (filter &optional new multifile)
4061 "Display a list of items filtered by FILTER.
4062 The values of FILTER can be `top' for top priority items, a cons
4063 of `top' and a number passed by the caller, `diary' for diary
4064 items, or `regexp' for items matching a regular expression
4065 entered by the user. The items can come from any categories in
4066 the current todo file or, with non-nil MULTIFILE, from several
4067 files. If NEW is nil, visit an appropriate file containing the
4068 list of filtered items; if there is no such file, or with non-nil
4069 NEW, build the list and display it.
4071 See the documentation strings of the commands
4072 `todo-filter-top-priorities', `todo-filter-diary-items',
4073 `todo-filter-regexp-items', and those of the corresponding
4074 multifile commands for further details."
4075 (let* ((top (eq filter 'top))
4076 (diary (eq filter 'diary))
4077 (regexp (eq filter 'regexp))
4078 (buf (cond (top todo-top-priorities-buffer)
4079 (diary todo-diary-items-buffer)
4080 (regexp todo-regexp-items-buffer)))
4081 (flist (if multifile
4082 (or todo-filter-files
4083 (progn (todo-multiple-filter-files)
4084 todo-multiple-filter-files))
4085 (list todo-current-todo-file)))
4086 (fname (if (equal flist 'quit)
4087 ;; Pressed `cancel' in t-m-f-f file selection dialog.
4089 (concat todo-directory
4090 (mapconcat 'todo-short-file-name flist "-")
4093 (regexp ".todr")))))
4094 (multi (> (length flist) 1))
4095 (rxfiles (when regexp
4096 (directory-files todo-directory t ".*\\.todr$" t)))
4097 (file-exists (or (file-exists-p fname) rxfiles))
4099 (cond ((and top new (natnump new))
4100 (todo-filter-items-1 (cons 'top new) flist))
4101 ((and (not new) file-exists)
4102 (when (and rxfiles (> (length rxfiles) 1))
4103 (let ((rxf (mapcar 'todo-short-file-name rxfiles)))
4104 (setq fname (todo-absolute-file-name
4105 (completing-read "Choose a regexp items file: "
4108 (unless (derived-mode-p 'todo-filtered-items-mode)
4109 (todo-filtered-items-mode))
4110 (todo-prefix-overlays)
4111 (todo-check-filtered-items-file))
4113 (todo-filter-items-1 filter flist)))
4114 (dolist (s (split-string (todo-short-file-name fname) "-"))
4115 (setq bufname (if bufname
4116 (concat bufname (if (member s (mapcar
4117 'todo-short-file-name
4121 (rename-buffer (format (concat "%s for file" (if multi "s" "")
4122 " \"%s\"") buf bufname))))
4124 (defun todo-filter-items-1 (filter file-list)
4125 "Build a list of items by applying FILTER to FILE-LIST.
4126 Internal subroutine called by `todo-filter-items', which passes
4127 the values of FILTER and FILE-LIST."
4128 (let ((num (if (consp filter) (cdr filter) todo-top-priorities))
4129 (buf (get-buffer-create todo-filtered-items-buffer))
4130 (multifile (> (length file-list) 1))
4131 regexp fname bufstr cat beg end done)
4132 (if (null file-list)
4133 (user-error "No files have been chosen for filtering")
4134 (with-current-buffer buf
4136 (kill-all-local-variables)
4137 (todo-filtered-items-mode))
4138 (when (eq filter 'regexp)
4139 (setq regexp (read-string "Enter a regular expression: ")))
4140 (save-current-buffer
4141 (dolist (f file-list)
4142 ;; Before inserting file contents into temp buffer, save a modified
4143 ;; buffer visiting it.
4144 (let ((bf (find-buffer-visiting f)))
4145 (when (buffer-modified-p bf)
4146 (with-current-buffer bf (save-buffer))))
4147 (setq fname (todo-short-file-name f))
4149 (when (and todo-filter-done-items (eq filter 'regexp))
4150 ;; If there is a corresponding archive file for the
4151 ;; todo file, insert it first and add identifiers for
4152 ;; todo-go-to-source-item.
4153 (let ((arch (concat (file-name-sans-extension f) ".toda")))
4154 (when (file-exists-p arch)
4155 (insert-file-contents arch)
4156 ;; Delete todo archive file's categories sexp.
4157 (delete-region (line-beginning-position)
4158 (1+ (line-end-position)))
4161 (when (re-search-forward
4162 (concat (if todo-filter-done-items
4163 (concat "\\(?:" todo-done-string-start
4164 "\\|" todo-date-string-start
4166 todo-date-string-start)
4167 todo-date-pattern "\\(?: "
4168 diary-time-regexp "\\)?"
4169 (if todo-filter-done-items
4171 (regexp-quote todo-nondiary-end)) "?")
4173 (insert "(archive) "))
4175 (insert-file-contents f)
4176 ;; Delete todo file's categories sexp.
4177 (delete-region (line-beginning-position) (1+ (line-end-position)))
4179 ;; Unless the number of top priorities to show was
4180 ;; passed by the caller, the file-wide value from
4181 ;; `todo-top-priorities-overrides', if non-nil, overrides
4182 ;; `todo-top-priorities'.
4183 (unless (consp filter)
4184 (setq fnum (or (nth 1 (assoc f todo-top-priorities-overrides))
4185 todo-top-priorities)))
4186 (while (re-search-forward
4187 (concat "^" (regexp-quote todo-category-beg)
4188 "\\(.+\\)\n") nil t)
4189 (setq cat (match-string 1))
4191 ;; Unless the number of top priorities to show was
4192 ;; passed by the caller, the category-wide value
4193 ;; from `todo-top-priorities-overrides', if non-nil,
4194 ;; overrides a non-nil file-wide value from
4195 ;; `todo-top-priorities-overrides' as well as
4196 ;; `todo-top-priorities'.
4197 (unless (consp filter)
4198 (let ((cats (nth 2 (assoc f todo-top-priorities-overrides))))
4199 (setq cnum (or (cdr (assoc cat cats)) fnum))))
4200 (delete-region (match-beginning 0) (match-end 0))
4201 (setq beg (point)) ; First item in the current category.
4202 (setq end (if (re-search-forward
4203 (concat "^" (regexp-quote todo-category-beg))
4209 (if (re-search-forward
4210 (concat "\n" (regexp-quote todo-category-done))
4214 (unless (and todo-filter-done-items (eq filter 'regexp))
4215 ;; Leave done items.
4216 (delete-region done end)
4218 (narrow-to-region beg end) ; Process only current category.
4219 (goto-char (point-min))
4220 ;; Apply the filter.
4221 (cond ((eq filter 'diary)
4223 (if (looking-at (regexp-quote todo-nondiary-start))
4225 (todo-forward-item))))
4226 ((eq filter 'regexp)
4228 (if (looking-at todo-item-start)
4229 (if (string-match regexp (todo-item-string))
4232 ;; Kill lines that aren't part of a todo or done
4233 ;; item (empty or todo-category-done).
4234 (delete-region (line-beginning-position)
4235 (1+ (line-end-position))))
4236 ;; If last todo item in file matches regexp and
4237 ;; there are no following done items,
4238 ;; todo-category-done string is left dangling,
4239 ;; because todo-forward-item jumps over it.
4242 (concat (regexp-quote todo-done-string)
4244 (line-beginning-position 0)))
4245 (delete-region (point) (progn
4248 (t ; Filter top priority items.
4249 (setq num (or cnum fnum num))
4251 (todo-forward-item num))))
4253 ;; Delete non-top-priority items.
4254 (unless (member filter '(diary regexp))
4255 (delete-region beg end))
4256 (goto-char (point-min))
4257 ;; Add file (if using multiple files) and category tags to
4260 (when (re-search-forward
4261 (concat (if todo-filter-done-items
4262 (concat "\\(?:" todo-done-string-start
4263 "\\|" todo-date-string-start
4265 todo-date-string-start)
4266 todo-date-pattern "\\(?: " diary-time-regexp
4267 "\\)?" (if todo-filter-done-items
4269 (regexp-quote todo-nondiary-end))
4273 (when (looking-at "(archive) ") (goto-char (match-end 0)))
4274 (insert (if multifile (concat fname ":") "") cat "]"))
4277 (setq bufstr (buffer-string))
4278 (with-current-buffer buf
4279 (let (buffer-read-only)
4280 (insert bufstr)))))))
4281 (set-window-buffer (selected-window) (set-buffer buf))
4282 (todo-prefix-overlays)
4283 (goto-char (point-min)))))
4285 (defun todo-set-top-priorities (&optional arg)
4286 "Set number of top priorities shown by `todo-filter-top-priorities'.
4287 With non-nil ARG, set the number only for the current Todo
4288 category; otherwise, set the number for all categories in the
4291 Calling this function via either of the commands
4292 `todo-set-top-priorities-in-file' or
4293 `todo-set-top-priorities-in-category' is the recommended way to
4294 set the user customizable option `todo-top-priorities-overrides'."
4295 (let* ((cat (todo-current-category))
4296 (file todo-current-todo-file)
4297 (rules todo-top-priorities-overrides)
4298 (frule (assoc-string file rules))
4299 (crules (nth 2 frule))
4300 (crule (assoc-string cat crules))
4301 (fcur (or (nth 1 frule)
4302 todo-top-priorities))
4303 (ccur (or (and arg (cdr crule))
4305 (prompt (if arg (concat "Number of top priorities in this category"
4306 " (currently %d): ")
4307 (concat "Default number of top priorities per category"
4308 " in this file (currently %d): ")))
4311 (let ((cur (if arg ccur fcur)))
4312 (setq new (read-number (format prompt cur))
4313 prompt "Enter a non-negative number: "
4315 (let ((nrule (if arg
4316 (append (delete crule crules) (list (cons cat new)))
4317 (append (list file new) (list crules)))))
4318 (setq rules (cons (if arg
4319 (list file fcur nrule)
4321 (delete frule rules)))
4322 (customize-save-variable 'todo-top-priorities-overrides rules)
4323 (todo-prefix-overlays))))
4325 (defun todo-find-item (str)
4326 "Search for filtered item STR in its saved todo file.
4327 Return the list (FOUND FILE CAT), where CAT and FILE are the
4328 item's category and file, and FOUND is a cons cell if the search
4329 succeeds, whose car is the start of the item in FILE and whose
4330 cdr is `done', if the item is now a done item, `changed', if its
4331 text was truncated or augmented or, for a top priority item, if
4332 its priority has changed, and `same' otherwise."
4333 (string-match (concat (if todo-filter-done-items
4334 (concat "\\(?:" todo-done-string-start "\\|"
4335 todo-date-string-start "\\)")
4336 todo-date-string-start)
4337 todo-date-pattern "\\(?: " diary-time-regexp "\\)?"
4338 (if todo-filter-done-items
4340 (regexp-quote todo-nondiary-end)) "?"
4341 "\\(?4: \\[\\(?3:(archive) \\)?\\(?2:.*:\\)?"
4342 "\\(?1:.*\\)\\]\\).*$") str)
4343 (let ((cat (match-string 1 str))
4344 (file (match-string 2 str))
4345 (archive (string= (match-string 3 str) "(archive) "))
4346 (filcat (match-string 4 str))
4348 (tpbuf (save-match-data (string-match "top" (buffer-name))))
4350 (setq str (replace-match "" nil nil str 4))
4352 ;; Calculate priority of STR wrt its category.
4354 (while (search-backward filcat nil t)
4355 (setq tpriority (1+ tpriority)))))
4357 (concat todo-directory (substring file 0 -1)
4358 (if archive ".toda" ".todo"))
4360 (concat (file-name-sans-extension
4361 todo-global-current-todo-file) ".toda")
4362 todo-global-current-todo-file)))
4363 (find-file-noselect file)
4364 (with-current-buffer (find-buffer-visiting file)
4366 (unless (derived-mode-p 'todo-archive-mode) (todo-archive-mode))
4367 (unless (derived-mode-p 'todo-mode) (todo-mode)))
4370 (goto-char (point-min))
4371 (let ((beg (re-search-forward
4372 (concat "^" (regexp-quote (concat todo-category-beg cat))
4375 (done (save-excursion
4377 (concat "^" (regexp-quote todo-category-done)) nil t)))
4378 (end (save-excursion
4379 (or (re-search-forward
4380 (concat "^" (regexp-quote todo-category-beg))
4383 (setq found (when (search-forward str end t)
4384 (goto-char (match-beginning 0))))
4387 (cons found (if (> (point) done)
4389 (let ((cpriority 1))
4392 ;; Not top item in category.
4393 (while (> (point) (1+ beg))
4394 (let ((opoint (point)))
4395 (todo-backward-item)
4396 ;; Can't move backward beyond
4397 ;; first item in file.
4398 (unless (= (point) opoint)
4399 (setq cpriority (1+ cpriority)))))))
4400 (if (and (= tpriority cpriority)
4401 ;; Proper substring is not the same.
4402 (string= (todo-item-string)
4406 (list found file cat)))
4408 (defun todo-check-filtered-items-file ()
4409 "Check if filtered items file is up to date and a show suitable message."
4413 (let* ((item (todo-item-string))
4414 (found (car (todo-find-item item))))
4415 (unless (eq (cdr found) 'same)
4417 (overlay-put (make-overlay (todo-item-start) (todo-item-end))
4418 'face 'todo-search))
4419 (setq count (1+ count))))
4420 ;; (throw 'old (message "The marked item is not up to date.")))
4421 (todo-forward-item))
4423 (message "Filtered items file is up to date.")
4424 (message (concat "The highlighted item" (if (= count 1) " is " "s are ")
4426 ;; "\nType <return> on item for details."
4429 (defun todo-filter-items-filename ()
4430 "Return absolute file name for saving this Filtered Items buffer."
4431 (let ((bufname (buffer-name)))
4432 (string-match "\"\\([^\"]+\\)\"" bufname)
4433 (let* ((filename-str (substring bufname (match-beginning 1) (match-end 1)))
4434 (filename-base (replace-regexp-in-string ", " "-" filename-str))
4435 (top-priorities (string-match "top priorities" bufname))
4436 (diary-items (string-match "diary items" bufname))
4437 (regexp-items (string-match "regexp items" bufname)))
4439 (let ((prompt (concat "Enter a short identifying string"
4440 " to make this file name unique: ")))
4441 (setq filename-base (concat filename-base "-" (read-string prompt)))))
4442 (concat todo-directory filename-base
4443 (cond (top-priorities ".todt")
4444 (diary-items ".tody")
4445 (regexp-items ".todr"))))))
4447 (defun todo-save-filtered-items-buffer ()
4448 "Save current Filtered Items buffer to a file.
4449 If the file already exists, overwrite it only on confirmation."
4450 (let ((filename (or (buffer-file-name) (todo-filter-items-filename))))
4451 (write-file filename t)))
4453 ;; -----------------------------------------------------------------------------
4454 ;;; Printing Todo mode buffers
4455 ;; -----------------------------------------------------------------------------
4457 (defcustom todo-print-buffer-function 'ps-print-buffer-with-faces
4458 "Function called by the command `todo-print-buffer'."
4462 (defvar todo-print-buffer "*Todo Print*"
4463 "Name of buffer with printable version of Todo mode buffer.")
4465 (defun todo-print-buffer (&optional to-file)
4466 "Produce a printable version of the current Todo mode buffer.
4467 This converts overlays and soft line wrapping and, depending on
4468 the value of `todo-print-buffer-function', includes faces. With
4469 non-nil argument TO-FILE write the printable version to a file;
4470 otherwise, send it to the default printer."
4472 (let ((buf todo-print-buffer)
4474 ((eq major-mode 'todo-mode)
4475 (concat "Todo File: "
4476 (todo-short-file-name todo-current-todo-file)
4477 "\nCategory: " (todo-current-category)))
4478 ((eq major-mode 'todo-filtered-items-mode)
4480 (prefix (propertize (concat todo-prefix " ")
4481 'face 'todo-prefix-string))
4483 (fill-prefix (make-string todo-indent-to-here 32))
4484 (content (buffer-string))
4486 (with-current-buffer (get-buffer-create buf)
4488 (goto-char (point-min))
4491 (end (save-excursion (todo-item-end))))
4492 (when todo-number-prefix
4494 (setq prefix (propertize (concat (number-to-string num) " ")
4495 'face 'todo-prefix-string)))
4497 (fill-region beg end))
4498 ;; Calling todo-forward-item infloops at todo-item-start due to
4499 ;; non-overlay prefix, so search for item start instead.
4500 (if (re-search-forward todo-item-start nil t)
4502 (goto-char (point-max))))
4503 (if (re-search-backward (concat "^" (regexp-quote todo-category-done))
4505 (replace-match todo-done-separator))
4506 (goto-char (point-min))
4510 (let ((file (read-file-name "Print to file: ")))
4511 (funcall todo-print-buffer-function file))
4512 (funcall todo-print-buffer-function)))
4515 (defun todo-print-buffer-to-file ()
4516 "Save printable version of this Todo mode buffer to a file."
4518 (todo-print-buffer t))
4520 ;; -----------------------------------------------------------------------------
4521 ;;; Legacy Todo mode files
4522 ;; -----------------------------------------------------------------------------
4524 (defcustom todo-legacy-date-time-regexp
4525 (concat "\\(?1:[0-9]\\{4\\}\\)-\\(?2:[0-9]\\{2\\}\\)-"
4526 "\\(?3:[0-9]\\{2\\}\\) \\(?4:[0-9]\\{2\\}:[0-9]\\{2\\}\\)")
4527 "Regexp matching legacy todo-mode.el item date-time strings.
4528 In order for `todo-convert-legacy-files' to correctly convert
4529 this string to the current Todo mode format, the regexp must
4530 contain four explicitly numbered groups (see `(elisp) Regexp
4531 Backslash'), where group 1 matches a string for the year, group 2
4532 a string for the month, group 3 a string for the day and group 4
4533 a string for the time. The default value converts date-time
4534 strings built using the default value of
4535 `todo-time-string-format' from todo-mode.el."
4539 (defun todo-convert-legacy-date-time ()
4540 "Return converted date-time string.
4541 Helper function for `todo-convert-legacy-files'."
4542 (let* ((year (match-string 1))
4543 (month (match-string 2))
4544 (monthname (calendar-month-name (string-to-number month) t))
4545 (day (match-string 3))
4546 (time (match-string 4))
4549 (insert (mapconcat 'eval calendar-date-display-form "")
4550 (when time (concat " " time)))))
4552 (defun todo-convert-legacy-files ()
4553 "Convert legacy todo files to the current Todo mode format.
4554 The old-style files named by the variables `todo-file-do' and
4555 `todo-file-done' from the old package are converted to the new
4556 format and saved (the latter as a todo archive file) with a new
4557 name in `todo-directory'. See also the documentation string of
4558 `todo-legacy-date-time-regexp' for further details."
4560 ;; If there are user customizations of legacy options, use them,
4561 ;; otherwise use the legacy default values.
4562 (let ((todo-file-do-tem (if (boundp 'todo-file-do)
4564 (locate-user-emacs-file "todo-do" ".todo-do")))
4565 (todo-file-done-tem (if (boundp 'todo-file-done)
4567 (locate-user-emacs-file "todo-done" ".todo-done")))
4568 (todo-initials-tem (and (boundp 'todo-initials) todo-initials))
4569 (todo-entry-prefix-function-tem (and (boundp 'todo-entry-prefix-function)
4570 todo-entry-prefix-function))
4572 ;; Convert `todo-file-do'.
4573 (if (not (file-exists-p todo-file-do-tem))
4574 (message "No legacy todo file exists")
4575 (let ((default "todo-do-conv")
4578 (insert-file-contents todo-file-do-tem)
4579 ;; Eliminate old-style local variables list in first line.
4580 (delete-region (line-beginning-position) (1+ (line-end-position)))
4581 (search-forward " --- " nil t) ; Legacy todo-category-beg.
4582 (setq todo-prefix-tem (buffer-substring-no-properties
4583 (line-beginning-position) (match-beginning 0)))
4584 (goto-char (point-min))
4587 ;; Old-style category start delimiter.
4588 ((looking-at (regexp-quote (concat todo-prefix-tem " --- ")))
4589 (replace-match todo-category-beg))
4590 ;; Old-style category end delimiter.
4591 ((looking-at (regexp-quote "--- End"))
4593 ;; Old-style category separator.
4594 ((looking-at (regexp-quote
4595 (concat todo-prefix-tem " "
4596 (make-string 75 ?-))))
4597 (replace-match todo-category-done))
4598 ;; Old-style item header (date/time/initials).
4599 ((looking-at (concat (regexp-quote todo-prefix-tem) " "
4600 (if todo-entry-prefix-function-tem
4601 (funcall todo-entry-prefix-function-tem)
4602 (concat todo-legacy-date-time-regexp " "
4603 (if todo-initials-tem
4604 (regexp-quote todo-initials-tem)
4607 (todo-convert-legacy-date-time)))
4609 (setq file (concat todo-directory
4611 (format "Save file as (default \"%s\"): " default)
4614 (unless (file-exists-p todo-directory)
4615 (make-directory todo-directory))
4616 (write-region (point-min) (point-max) file nil 'nomessage nil t))
4618 (insert-file-contents file)
4619 (let ((todo-categories (todo-make-categories-list t)))
4620 (todo-update-categories-sexp)
4621 (todo-check-format))
4622 (write-region (point-min) (point-max) file nil 'nomessage))
4623 (setq todo-files (funcall todo-files-function))
4624 ;; Convert `todo-file-done'.
4625 (when (file-exists-p todo-file-done-tem)
4627 (insert-file-contents todo-file-done-tem)
4628 (let ((beg (make-marker))
4630 cat cats comment item)
4632 (when (looking-at todo-legacy-date-time-regexp)
4633 (set-marker beg (point))
4634 (todo-convert-legacy-date-time)
4635 (set-marker end (point))
4637 (insert "[" todo-done-string)
4641 (when (looking-at todo-legacy-date-time-regexp)
4642 (todo-convert-legacy-date-time))
4643 (when (looking-at (concat " " (if todo-initials-tem
4648 (replace-match "")))
4649 (if (re-search-forward
4650 (concat "^" todo-legacy-date-time-regexp) nil t)
4651 (goto-char (match-beginning 0))
4652 (goto-char (point-max)))
4654 (when (looking-back "\\[\\([^][]+\\)\\]")
4655 (setq cat (match-string 1))
4656 (goto-char (match-beginning 0))
4658 ;; If the item ends with a non-comment parenthesis not
4659 ;; followed by a period, we lose (but we inherit that
4660 ;; problem from the legacy code).
4661 (when (looking-back "(\\(.*\\)) " (line-beginning-position))
4662 (setq comment (match-string 1))
4664 (insert "[" todo-comment-string ": " comment "]"))
4665 (set-marker end (point))
4666 (if (member cat cats)
4667 ;; If item is already in its category, leave it there.
4668 (unless (save-excursion
4670 (concat "^" (regexp-quote todo-category-beg)
4672 (string= (match-string 1) cat))
4673 ;; Else move it to its category.
4674 (setq item (buffer-substring-no-properties beg end))
4675 (delete-region beg (1+ end))
4676 (set-marker beg (point))
4679 (regexp-quote (concat todo-category-beg cat))
4683 (if (re-search-forward
4684 (concat "^" (regexp-quote todo-category-beg)
4686 (progn (goto-char (match-beginning 0))
4689 (goto-char (point-max)))
4694 (insert todo-category-beg cat "\n\n"
4695 todo-category-done "\n"))
4697 (set-marker beg nil)
4698 (set-marker end nil))
4699 (setq file (concat (file-name-sans-extension file) ".toda"))
4700 (write-region (point-min) (point-max) file nil 'nomessage nil t))
4702 (insert-file-contents file)
4703 (let* ((todo-categories (todo-make-categories-list t)))
4704 (todo-update-categories-sexp)
4705 (todo-check-format))
4706 (write-region (point-min) (point-max) file nil 'nomessage)
4707 (setq archive-sexp (read (buffer-substring-no-properties
4708 (line-beginning-position)
4709 (line-end-position)))))
4710 (setq file (concat (file-name-sans-extension file) ".todo"))
4711 ;; Update categories sexp of converted todo file again, adding
4712 ;; counts of archived items.
4714 (insert-file-contents file)
4715 (let ((sexp (read (buffer-substring-no-properties
4716 (line-beginning-position)
4717 (line-end-position)))))
4719 (let ((archive-cat (assoc (car cat) archive-sexp)))
4721 (aset (cdr cat) 3 (aref (cdr archive-cat) 2)))))
4722 (delete-region (line-beginning-position) (line-end-position))
4723 (prin1 sexp (current-buffer)))
4724 (write-region (point-min) (point-max) file nil 'nomessage))
4725 (setq todo-archives (funcall todo-files-function t)))
4726 (todo-reevaluate-filelist-defcustoms)
4727 (when (y-or-n-p (concat "Format conversion done; do you want to "
4728 "visit the converted file now? "))
4729 (setq todo-current-todo-file file)
4730 (unless todo-default-todo-file
4731 ;; We just initialized the first todo file, so make it the
4732 ;; default now to avoid an infinite recursion with todo-show.
4733 (setq todo-default-todo-file (todo-short-file-name file)))
4736 ;; -----------------------------------------------------------------------------
4737 ;;; Utility functions for todo files, categories and items
4738 ;; -----------------------------------------------------------------------------
4740 (defun todo-absolute-file-name (name &optional type)
4741 "Return the absolute file name of short todo file NAME.
4742 With TYPE `archive' or `top' return the absolute file name of the
4743 short todo archive or top priorities file name, respectively."
4744 ;; No-op if there is no todo file yet (i.e. don't concatenate nil).
4747 (concat todo-directory name
4748 (cond ((eq type 'archive) ".toda")
4749 ((eq type 'top) ".todt")
4750 ((eq type 'diary) ".tody")
4751 ((eq type 'regexp) ".todr")
4754 (defun todo-check-file (file)
4755 "Check the state associated with FILE and update it if necessary.
4756 If FILE exists, return t. If it does not exist and there is no
4757 live buffer with its content, return nil; if there is such a
4758 buffer and the user tries to show it, ask whether to restore
4759 FILE, and if confirmed, do so and return t; else delete the
4760 buffer, clean up the state and return nil."
4761 (setq todo-files (funcall todo-files-function))
4762 (setq todo-archives (funcall todo-files-function t))
4763 (if (file-exists-p file)
4765 (setq todo-visited (delete file todo-visited))
4766 (let ((buf (find-buffer-visiting file)))
4770 (format (concat "Todo file \"%s\" has been deleted but "
4771 "its content is still in a buffer!\n")
4772 (todo-short-file-name file))
4773 "Save that buffer and restore the todo file? ")))
4775 (with-current-buffer buf (save-buffer))
4776 (setq todo-files (funcall todo-files-function))
4777 (setq todo-archives (funcall todo-files-function t))
4779 (let* ((files (append todo-files todo-archives))
4780 (tctf todo-current-todo-file)
4781 (tgctf todo-global-current-todo-file)
4782 (tdtf (todo-absolute-file-name todo-default-todo-file)))
4783 (unless (or (not todo-current-todo-file)
4784 (member todo-current-todo-file files))
4785 (setq todo-current-todo-file nil))
4786 (unless (or (not todo-global-current-todo-file)
4787 (member todo-global-current-todo-file files))
4788 (setq todo-global-current-todo-file nil))
4789 (unless (or (not todo-default-todo-file)
4790 (member todo-default-todo-file files))
4791 (setq todo-default-todo-file (todo-short-file-name
4793 (todo-reevaluate-filelist-defcustoms)
4794 (when buf (kill-buffer buf))
4797 (defun todo-category-number (cat)
4798 "Return the number of category CAT in this todo file.
4799 The buffer-local variable `todo-category-number' holds this
4800 number as its value."
4801 (let ((categories (mapcar 'car todo-categories)))
4802 (setq todo-category-number
4803 ;; Increment by one, so that the number of the first
4804 ;; category is one rather than zero.
4805 (1+ (- (length categories)
4806 (length (member cat categories)))))))
4808 (defun todo-current-category ()
4809 "Return the name of the current category."
4810 (car (nth (1- todo-category-number) todo-categories)))
4812 (defun todo-category-select ()
4813 "Display the current category correctly."
4814 (let ((name (todo-current-category))
4815 cat-begin cat-end done-start done-sep-start done-end)
4817 (goto-char (point-min))
4819 (concat "^" (regexp-quote (concat todo-category-beg name)) "$") nil t)
4820 (setq cat-begin (1+ (line-end-position)))
4821 (setq cat-end (if (re-search-forward
4822 (concat "^" (regexp-quote todo-category-beg)) nil t)
4825 (setq mode-line-buffer-identification
4826 (funcall todo-mode-line-function name))
4827 (narrow-to-region cat-begin cat-end)
4828 (todo-prefix-overlays)
4829 (goto-char (point-min))
4830 (if (re-search-forward (concat "\n\\(" (regexp-quote todo-category-done)
4833 (setq done-start (match-beginning 0))
4834 (setq done-sep-start (match-beginning 1))
4835 (setq done-end (match-end 0)))
4836 (error "Category %s is missing todo-category-done string" name))
4837 (if todo-show-done-only
4838 (narrow-to-region (1+ done-end) (point-max))
4839 (when (and todo-show-with-done
4840 (re-search-forward todo-done-string-start nil t))
4841 ;; Now we want to see the done items, so reset displayed end to end of
4843 (setq done-start cat-end)
4844 ;; Make display overlay for done items separator string, unless there
4846 (let* ((done-sep todo-done-separator)
4847 (ov (progn (goto-char done-sep-start)
4848 (todo-get-overlay 'separator))))
4850 (setq ov (make-overlay done-sep-start done-end))
4851 (overlay-put ov 'todo 'separator)
4852 (overlay-put ov 'display done-sep))))
4853 (narrow-to-region (point-min) done-start)
4854 ;; Loading this from todo-mode, or adding it to the mode hook, causes
4855 ;; Emacs to hang in todo-item-start, at (looking-at todo-item-start).
4856 (when todo-highlight-item
4858 (hl-line-mode 1)))))
4860 (defun todo-get-count (type &optional category)
4861 "Return count of TYPE items in CATEGORY.
4862 If CATEGORY is nil, default to the current category."
4863 (let* ((cat (or category (todo-current-category)))
4864 (counts (cdr (assoc cat todo-categories)))
4865 (idx (cond ((eq type 'todo) 0)
4866 ((eq type 'diary) 1)
4868 ((eq type 'archived) 3))))
4871 (defun todo-update-count (type increment &optional category)
4872 "Change count of TYPE items in CATEGORY by integer INCREMENT.
4873 With nil or omitted CATEGORY, default to the current category."
4874 (let* ((cat (or category (todo-current-category)))
4875 (counts (cdr (assoc cat todo-categories)))
4876 (idx (cond ((eq type 'todo) 0)
4877 ((eq type 'diary) 1)
4879 ((eq type 'archived) 3))))
4880 (aset counts idx (+ increment (aref counts idx)))))
4882 (defun todo-set-categories ()
4883 "Set `todo-categories' from the sexp at the top of the file."
4884 ;; New archive files created by `todo-move-category' are empty, which would
4885 ;; make the sexp test fail and raise an error, so in this case we skip it.
4886 (unless (zerop (buffer-size))
4890 (goto-char (point-min))
4891 (setq todo-categories
4892 (if (looking-at "\(\(\"")
4893 (read (buffer-substring-no-properties
4894 (line-beginning-position)
4895 (line-end-position)))
4896 (error "Invalid or missing todo-categories sexp")))))))
4898 (defun todo-update-categories-sexp ()
4899 "Update the `todo-categories' sexp at the top of the file."
4900 (let (buffer-read-only)
4904 (goto-char (point-min))
4905 (if (looking-at (concat "^" (regexp-quote todo-category-beg)))
4906 (progn (newline) (goto-char (point-min)) ; Make space for sexp.
4907 (setq todo-categories (todo-make-categories-list t)))
4908 (delete-region (line-beginning-position) (line-end-position)))
4909 (prin1 todo-categories (current-buffer))))))
4911 (defun todo-make-categories-list (&optional force)
4912 "Return an alist of todo categories and their item counts.
4913 With non-nil argument FORCE parse the entire file to build the
4914 list; otherwise, get the value by reading the sexp at the top of
4916 (setq todo-categories nil)
4920 (goto-char (point-min))
4921 (let (counts cat archive)
4922 ;; If the file is a todo file and has archived items, identify the
4923 ;; archive, in order to count its items. But skip this with
4924 ;; `todo-convert-legacy-files', since that converts filed items to
4926 (when buffer-file-name ; During conversion there is no file yet.
4927 ;; If the file is an archive, it doesn't have an archive.
4928 (unless (member (file-truename buffer-file-name)
4929 (funcall todo-files-function t))
4930 (setq archive (concat (file-name-sans-extension
4931 todo-current-todo-file) ".toda"))))
4933 (cond ((looking-at (concat (regexp-quote todo-category-beg)
4935 (setq cat (match-string-no-properties 1))
4936 ;; Counts for each category: [todo diary done archive]
4937 (setq counts (make-vector 4 0))
4938 (setq todo-categories
4939 (append todo-categories (list (cons cat counts))))
4940 ;; Add archived item count to the todo file item counts.
4941 ;; Make sure to include newly created archives, e.g. due to
4942 ;; todo-move-category.
4943 (when (member archive (funcall todo-files-function t))
4944 (let ((archive-count 0)
4945 (visiting (find-buffer-visiting archive)))
4946 (with-current-buffer (or visiting
4947 (find-file-noselect archive))
4951 (goto-char (point-min))
4952 (when (re-search-forward
4953 (concat "^" (regexp-quote todo-category-beg)
4957 (while (not (or (looking-at
4959 (regexp-quote todo-category-beg)
4962 (when (looking-at todo-done-string-start)
4963 (setq archive-count (1+ archive-count)))
4965 (unless visiting (kill-buffer)))
4966 (todo-update-count 'archived archive-count cat))))
4967 ((looking-at todo-done-string-start)
4968 (todo-update-count 'done 1 cat))
4969 ((looking-at (concat "^\\("
4970 (regexp-quote diary-nonmarking-symbol)
4971 "\\)?" todo-date-pattern))
4972 (todo-update-count 'diary 1 cat)
4973 (todo-update-count 'todo 1 cat))
4974 ((looking-at (concat todo-date-string-start todo-date-pattern))
4975 (todo-update-count 'todo 1 cat))
4976 ;; If first line is todo-categories list, use it and end loop
4977 ;; -- unless FORCEd to scan whole file.
4980 (setq todo-categories (read (buffer-substring-no-properties
4981 (line-beginning-position)
4982 (line-end-position))))
4983 (goto-char (1- (point-max))))))
4987 (defun todo-repair-categories-sexp ()
4988 "Repair corrupt todo file categories sexp.
4989 This should only be needed as a consequence of careless manual
4990 editing or a bug in todo.el.
4992 *Warning*: Calling this command restores the category order to
4993 the list element order in the todo file categories sexp, so any
4994 order changes made in Todo Categories mode will have to be made
4997 (let ((todo-categories (todo-make-categories-list t)))
4998 (todo-update-categories-sexp)))
5000 (defun todo-check-format ()
5001 "Signal an error if the current todo file is ill-formatted.
5002 Otherwise return t. Display a message if the file is well-formed
5003 but the categories sexp differs from the current value of
5008 (goto-char (point-min))
5009 (let* ((cats (prin1-to-string todo-categories))
5010 (ssexp (buffer-substring-no-properties (line-beginning-position)
5011 (line-end-position)))
5012 (sexp (read ssexp)))
5013 ;; Check the first line for `todo-categories' sexp.
5016 (unless (and (stringp (car c))
5019 (user-error "Invalid or missing todo-categories sexp"))))
5021 ;; Check well-formedness of categories.
5022 (let ((legit (concat
5023 "\\(^" (regexp-quote todo-category-beg) "\\)"
5024 "\\|\\(" todo-date-string-start todo-date-pattern "\\)"
5025 "\\|\\(^[ \t]+[^ \t]*\\)"
5027 "\\|\\(^" (regexp-quote todo-category-done) "\\)"
5028 "\\|\\(" todo-done-string-start "\\)")))
5030 (unless (looking-at legit)
5031 (user-error "Illegitimate todo file format at line %d"
5032 (line-number-at-pos (point))))
5034 ;; Warn user if categories sexp has changed.
5035 (unless (string= ssexp cats)
5036 (message (concat "The sexp at the beginning of the file differs "
5037 "from the value of `todo-categories.\n"
5038 "If the sexp is wrong, you can fix it with "
5039 "M-x todo-repair-categories-sexp,\n"
5040 "but note this reverts any changes you have "
5041 "made in the order of the categories."))))))
5044 (defun todo-item-start ()
5045 "Move to start of current todo item and return its position."
5047 ;; Buffer is empty (invocation possible e.g. via todo-forward-item
5048 ;; from todo-filter-items when processing category with no todo
5050 (eq (point-min) (point-max))
5051 ;; Point is on the empty line below category's last todo item...
5052 (and (looking-at "^$")
5053 (or (eobp) ; ...and done items are hidden...
5054 (save-excursion ; ...or done items are visible.
5056 (looking-at (concat "^"
5057 (regexp-quote todo-category-done))))))
5058 ;; Buffer is widened.
5059 (looking-at (regexp-quote todo-category-beg)))
5060 (goto-char (line-beginning-position))
5061 (while (not (looking-at todo-item-start))
5065 (defun todo-item-end ()
5066 "Move to end of current todo item and return its position."
5067 ;; Items cannot end with a blank line.
5068 (unless (looking-at "^$")
5069 (let* ((done (todo-done-item-p))
5071 ;; For todo items, end is before the done items section, for done
5072 ;; items, end is before the next category. If these limits are
5073 ;; missing or inaccessible, end it before the end of the buffer.
5074 (lim (if (save-excursion
5076 (concat "^" (regexp-quote (if done
5078 todo-category-done)))
5080 (progn (setq to-lim t) (match-beginning 0))
5082 (when (bolp) (forward-char)) ; Find start of next item.
5083 (goto-char (if (re-search-forward todo-item-start lim t)
5085 (if to-lim lim (point-max))))
5086 ;; For last todo item, skip back over the empty line before the done
5087 ;; items section, else just back to the end of the previous line.
5088 (backward-char (when (and to-lim (not done) (eq (point) lim)) 2))
5091 (defun todo-item-string ()
5092 "Return bare text of current item as a string."
5093 (let ((opoint (point))
5094 (start (todo-item-start))
5095 (end (todo-item-end)))
5097 (and start end (buffer-substring-no-properties start end))))
5099 (defun todo-forward-item (&optional count)
5100 "Move point COUNT items down (by default, move down by one item)."
5101 (let* ((not-done (not (or (todo-done-item-p) (looking-at "^$"))))
5102 (start (line-end-position)))
5104 (if (re-search-forward todo-item-start nil t (or count 1))
5105 (goto-char (match-beginning 0))
5106 (goto-char (point-max)))
5107 ;; If points advances by one from a todo to a done item, go back
5108 ;; to the space above todo-done-separator, since that is a
5109 ;; legitimate place to insert an item. But skip this space if
5110 ;; count > 1, since that should only stop on an item.
5111 (when (and not-done (todo-done-item-p) (not count))
5112 ;; (if (or (not count) (= count 1))
5113 (re-search-backward "^$" start t))));)
5114 ;; The preceding sexp is insufficient when buffer is not narrowed,
5115 ;; since there could be no done items in this category, so the
5116 ;; search puts us on first todo item of next category. Does this
5117 ;; ever happen? If so:
5118 ;; (let ((opoint) (point))
5119 ;; (forward-line -1)
5120 ;; (when (or (not count) (= count 1))
5121 ;; (cond ((looking-at (concat "^" (regexp-quote todo-category-beg)))
5122 ;; (forward-line -2))
5123 ;; ((looking-at (concat "^" (regexp-quote todo-category-done)))
5124 ;; (forward-line -1))
5126 ;; (goto-char opoint)))))))
5128 (defun todo-backward-item (&optional count)
5129 "Move point up to start of item with next higher priority.
5130 With positive numerical prefix COUNT, move point COUNT items
5133 If the category's done items are visible, this command called
5134 with a prefix argument only moves point to a higher item, e.g.,
5135 with point on the first done item and called with prefix 1, it
5136 moves to the last todo item; but if called with point on the
5137 first done item without a prefix argument, it moves point the the
5138 empty line above the done items separator."
5139 (let* ((done (todo-done-item-p)))
5142 (re-search-backward todo-item-start nil t (or count 1)))
5143 ;; Unless this is a regexp filtered items buffer (which can contain
5144 ;; intermixed todo and done items), if points advances by one from a
5145 ;; done to a todo item, go back to the space above
5146 ;; todo-done-separator, since that is a legitimate place to insert an
5147 ;; item. But skip this space if count > 1, since that should only
5149 (when (and done (not (todo-done-item-p)) (not count)
5150 ;(or (not count) (= count 1))
5151 (not (equal (buffer-name) todo-regexp-items-buffer)))
5152 (re-search-forward (concat "^" (regexp-quote todo-category-done))
5154 (forward-line -1))))
5156 (defun todo-remove-item ()
5157 "Internal function called in editing, deleting or moving items."
5158 (let* ((end (progn (todo-item-end) (1+ (point))))
5159 (beg (todo-item-start))
5160 (ov (todo-get-overlay 'prefix)))
5161 (when ov (delete-overlay ov))
5162 (delete-region beg end)))
5164 (defun todo-diary-item-p ()
5165 "Return non-nil if item at point has diary entry format."
5167 (when (todo-item-string) ; Exclude empty lines.
5169 (not (looking-at (regexp-quote todo-nondiary-start))))))
5171 ;; This duplicates the item locating code from diary-goto-entry, but
5172 ;; without the marker code, to test whether the latter is dispensable.
5173 ;; If it is, diary-goto-entry can be simplified. The code duplication
5174 ;; here can also be eliminated, leaving only the widening and category
5175 ;; selection, and instead of :override advice :around can be used.
5177 (defun todo-diary-goto-entry (button)
5178 "Jump to the diary entry for the BUTTON at point.
5179 If the entry is a todo item, display its category properly.
5180 Overrides `diary-goto-entry'."
5181 ;; Locate the diary item in its source file.
5182 (let* ((locator (button-get button 'locator))
5183 (file (cadr locator))
5184 (date (regexp-quote (nth 2 locator)))
5185 (content (regexp-quote (nth 3 locator))))
5186 (if (not (and (file-exists-p file)
5187 (find-file-other-window file)))
5188 (message "Unable to locate this diary entry")
5189 ;; If it's a Todo file, make sure it's in Todo mode.
5190 (when (and (equal (file-name-directory (file-truename file))
5191 (file-truename todo-directory))
5192 (not (derived-mode-p 'todo-mode)))
5194 (when (eq major-mode 'todo-mode) (widen))
5195 (goto-char (point-min))
5196 (when (re-search-forward (format "%s.*\\(%s\\)" date content) nil t)
5197 (goto-char (match-beginning 1)))
5198 ;; If it's a todo item, determine its category and display the
5199 ;; category properly.
5200 (when (eq major-mode 'todo-mode)
5201 (let ((opoint (point)))
5202 (re-search-backward (concat "^" (regexp-quote todo-category-beg)
5203 "\\(.*\\)\n") nil t)
5204 (todo-category-number (match-string 1))
5205 (todo-category-select)
5206 (goto-char opoint))))))
5208 (add-function :override diary-goto-entry-function #'todo-diary-goto-entry)
5210 (defun todo-revert-buffer (&optional ignore-auto noconfirm)
5211 "Call `revert-buffer', preserving buffer's current modes.
5212 Also preserve category display, if applicable."
5213 (interactive (list (not current-prefix-arg)))
5214 (let ((revert-buffer-function nil))
5215 (revert-buffer ignore-auto noconfirm 'preserve-modes)
5216 (when (memq major-mode '(todo-mode todo-archive-mode))
5217 (todo-category-select))))
5219 (defun todo-desktop-save-buffer (_dir)
5220 `((catnum . ,(todo-category-number (todo-current-category)))))
5222 (declare-function desktop-restore-file-buffer "desktop"
5223 (buffer-filename buffer-name buffer-misc))
5225 (defun todo-restore-desktop-buffer (file buffer misc)
5226 (desktop-restore-file-buffer file buffer misc)
5227 (with-current-buffer buffer
5229 (let ((todo-category-number (cdr (assq 'catnum misc))))
5230 (todo-category-select))))
5232 (add-to-list 'desktop-buffer-mode-handlers
5233 '(todo-mode . todo-restore-desktop-buffer))
5235 (defun todo-done-item-p ()
5236 "Return non-nil if item at point is a done item."
5239 (looking-at todo-done-string-start)))
5241 (defun todo-done-item-section-p ()
5242 "Return non-nil if point is in category's done items section."
5244 (or (re-search-backward (concat "^" (regexp-quote todo-category-done))
5246 (progn (goto-char (point-min))
5247 (looking-at todo-done-string-start)))))
5249 (defun todo--user-error-if-marked-done-item ()
5250 "Signal user error on marked done items.
5251 Helper function for editing commands that apply only to (possibly
5252 marked) not done todo items."
5255 (goto-char (point-max))
5256 (todo-backward-item)
5257 (unless (todo-done-item-p)
5259 (unless (re-search-forward
5260 (concat "^" (regexp-quote todo-category-beg)) nil t)
5261 (goto-char (point-max)))
5263 (while (todo-done-item-p)
5264 (when (todo-marked-item-p)
5265 (user-error "This command does not apply to done items"))
5266 (todo-backward-item)))))
5268 (defun todo-reset-done-separator (sep)
5269 "Replace existing overlays of done items separator string SEP."
5273 (goto-char (point-min))
5274 (while (re-search-forward
5275 (concat "\n\\(" (regexp-quote todo-category-done) "\\)") nil t)
5276 (let* ((beg (match-beginning 1))
5278 (ov (progn (goto-char beg)
5279 (todo-get-overlay 'separator)))
5280 (old-sep (when ov (overlay-get ov 'display)))
5283 (unless (string= old-sep sep)
5284 (setq new-ov (make-overlay beg end))
5285 (overlay-put new-ov 'todo 'separator)
5286 (overlay-put new-ov 'display todo-done-separator)
5287 (delete-overlay ov))))))))
5289 (defun todo-get-overlay (val)
5290 "Return the overlay at point whose `todo' property has value VAL."
5291 ;; Use overlays-in to find prefix overlays and check over two
5292 ;; positions to find done separator overlay.
5293 (let ((ovs (overlays-in (point) (1+ (point))))
5298 (when (eq (overlay-get ov 'todo) val)
5299 (throw 'done ov))))))
5301 (defun todo-marked-item-p ()
5302 "Non-nil if this item begins with `todo-item-mark'.
5303 In that case, return the item's prefix overlay."
5304 (let* ((ov (todo-get-overlay 'prefix))
5305 ;; If an item insertion command is called on a todo file
5306 ;; before it is visited, it has no prefix overlays yet, so
5308 (pref (when ov (overlay-get ov 'before-string)))
5310 (string-match (concat "^" (regexp-quote todo-item-mark))
5314 (defun todo-insert-with-overlays (item)
5315 "Insert ITEM at point and update prefix/priority number overlays."
5317 ;; Insertion pushes item down but not its prefix overlay. When the
5318 ;; overlay includes a mark, this would now mark the inserted ITEM,
5319 ;; so move it to the pushed down item.
5320 (let ((ov (todo-get-overlay 'prefix))
5321 (marked (todo-marked-item-p)))
5323 (when marked (move-overlay ov (point) (point))))
5324 (todo-backward-item)
5325 (todo-prefix-overlays))
5327 (defun todo-prefix-overlays ()
5328 "Update the prefix overlays of the current category's items.
5329 The overlay's value is the string `todo-prefix' or with non-nil
5330 `todo-number-prefix' an integer in the sequence from 1 to
5331 the number of todo or done items in the category indicating the
5332 item's priority. Todo and done items are numbered independently
5335 (cat-tp (or (cdr (assoc-string
5336 (todo-current-category)
5337 (nth 2 (assoc-string todo-current-todo-file
5338 todo-top-priorities-overrides))))
5339 (nth 1 (assoc-string todo-current-todo-file
5340 todo-top-priorities-overrides))
5341 todo-top-priorities))
5344 (goto-char (point-min))
5346 (when (or (todo-date-string-matcher (line-end-position))
5347 (todo-done-string-matcher (line-end-position)))
5348 (goto-char (match-beginning 0))
5350 ;; Reset number to 1 for first done item.
5351 (when (and (eq major-mode 'todo-mode)
5352 (looking-at todo-done-string-start)
5353 (looking-back (concat "^"
5354 (regexp-quote todo-category-done)
5356 (line-beginning-position 0)))
5359 (setq prefix (concat (propertize
5360 (if todo-number-prefix
5361 (number-to-string num)
5364 ;; Prefix of top priority items has a
5365 ;; distinct face in Todo mode.
5366 (if (and (eq major-mode 'todo-mode)
5370 'todo-prefix-string))
5372 (let ((ov (todo-get-overlay 'prefix))
5373 (marked (todo-marked-item-p)))
5374 ;; Prefix overlay must be at a single position so its
5375 ;; bounds aren't changed when (re)moving an item.
5376 (unless ov (setq ov (make-overlay (point) (point))))
5377 (overlay-put ov 'todo 'prefix)
5378 (overlay-put ov 'before-string (if marked
5379 (concat todo-item-mark prefix)
5383 ;; -----------------------------------------------------------------------------
5384 ;;; Generating and applying item insertion and editing key sequences
5385 ;; -----------------------------------------------------------------------------
5387 ;; Thanks to Stefan Monnier for suggesting dynamically generating item
5388 ;; insertion commands and their key bindings, and offering an elegant
5389 ;; implementation, which, however, relies on lexical scoping and so
5390 ;; cannot be used here until the Calendar code used by todo-mode.el is
5391 ;; converted to lexical binding. Hence, the following implementation
5392 ;; uses dynamic binding.
5394 (defconst todo-insert-item--parameters
5395 '((default copy) (diary nonmarking) (calendar date dayname) time (here region))
5396 "List of all item insertion parameters.
5397 Passed by `todo-insert-item' to `todo-insert-item--next-param' to
5398 dynamically create item insertion commands.")
5400 (defconst todo-insert-item--param-key-alist
5411 "List pairing item insertion parameters with their completion keys.")
5413 (defsubst todo-insert-item--keyof (param)
5414 "Return key paired with item insertion PARAM."
5415 (cdr (assoc param todo-insert-item--param-key-alist)))
5417 (defun todo-insert-item--argsleft (key list)
5418 "Return sublist of LIST whose first member corresponds to KEY."
5424 (when (equal key (todo-insert-item--keyof s))
5425 (throw 'found1 (setq sym s))))))
5432 (setq list (reverse l)))
5433 (memq (catch 'found2
5434 (dolist (e todo-insert-item--param-key-alist)
5435 (when (equal key (cdr e))
5436 (throw 'found2 (car e)))))
5439 (defsubst todo-insert-item--this-key () (char-to-string last-command-event))
5441 (defvar todo-insert-item--keys-so-far ""
5442 "String of item insertion keys so far entered for this command.")
5444 (defvar todo-insert-item--args nil)
5445 (defvar todo-insert-item--argleft nil)
5446 (defvar todo-insert-item--argsleft nil)
5447 (defvar todo-insert-item--newargsleft nil)
5449 (defun todo-insert-item--apply-args ()
5450 "Build list of arguments for item insertion and apply them.
5451 The list consists of item insertion parameters that can be passed
5452 as insertion command arguments in fixed positions. If a position
5453 in the list is not occupied by the corresponding parameter, it is
5455 (let* ((arg (list (car todo-insert-item--args)))
5456 (args (nconc (cdr todo-insert-item--args)
5457 (list (car (todo-insert-item--argsleft
5458 (todo-insert-item--this-key)
5459 todo-insert-item--argsleft)))))
5460 (arglist (if (= 4 (length args))
5462 (let ((v (make-vector 4 nil)) elt)
5464 (setq elt (pop args))
5465 (cond ((memq elt '(diary nonmarking))
5467 ((memq elt '(calendar date dayname))
5471 ((memq elt '(copy here region))
5474 (apply #'todo-insert-item--basic (nconc arg arglist))))
5476 (defun todo-insert-item--next-param (last args argsleft)
5477 "Build item insertion command from LAST, ARGS and ARGSLEFT and call it.
5478 Dynamically generate key bindings, prompting with the keys
5479 already entered and those still available."
5480 (cl-assert argsleft)
5481 (let* ((map (make-sparse-keymap))
5489 (if (memq name '(default diary calendar here))
5492 (when (memq name '(copy nonmarking dayname region))
5494 (propertize k 'face 'todo-key-prompt)
5496 (setq todo-insert-item--args args)
5497 (setq todo-insert-item--argsleft argsleft)
5499 (if (memq last '(default copy))
5501 (setq todo-insert-item--argsleft nil)
5502 (todo-insert-item--apply-args))
5503 (let ((k (todo-insert-item--keyof last)))
5504 (funcall addprompt k (make-symbol (concat (symbol-name last) ":GO!")))
5505 (define-key map (todo-insert-item--keyof last)
5506 (lambda () (interactive)
5507 (todo-insert-item--apply-args))))))
5508 (while todo-insert-item--argsleft
5509 (let ((x (car todo-insert-item--argsleft)))
5510 (setq todo-insert-item--newargsleft (cdr todo-insert-item--argsleft))
5511 (dolist (argleft (if (consp x) x (list x)))
5512 (let ((k (todo-insert-item--keyof argleft)))
5513 (funcall addprompt k argleft)
5515 (if (null todo-insert-item--newargsleft)
5516 (lambda () (interactive)
5517 (todo-insert-item--apply-args))
5518 (lambda () (interactive)
5519 (setq todo-insert-item--keys-so-far
5520 (concat todo-insert-item--keys-so-far " "
5521 (todo-insert-item--this-key)))
5522 (todo-insert-item--next-param
5523 (car (todo-insert-item--argsleft
5524 (todo-insert-item--this-key)
5525 todo-insert-item--argsleft))
5526 (nconc todo-insert-item--args
5527 (list (car (todo-insert-item--argsleft
5528 (todo-insert-item--this-key)
5529 todo-insert-item--argsleft))))
5530 (cdr (todo-insert-item--argsleft
5531 (todo-insert-item--this-key)
5532 todo-insert-item--argsleft)))))))))
5533 (setq todo-insert-item--argsleft todo-insert-item--newargsleft))
5534 (when prompt (message "Press a key (so far `%s'): %s"
5535 todo-insert-item--keys-so-far prompt))
5536 (set-transient-map map)
5537 (setq todo-insert-item--argsleft argsleft)))
5539 (defconst todo-edit-item--param-key-alist
5547 "Alist of item editing parameters and their keys.")
5549 (defconst todo-edit-item--date-param-key-alist
5557 "Alist of item date editing parameters and their keys.")
5559 (defconst todo-edit-done-item--param-key-alist
5562 "Alist of done item comment editing parameters and their keys.")
5564 (defvar todo-edit-item--prompt "Press a key (so far `e'): ")
5566 (defun todo-edit-item--next-key (params &optional arg)
5567 (let* ((map (make-sparse-keymap))
5568 (p->k (mapconcat (lambda (elt)
5570 (propertize (cdr elt) 'face
5572 (concat (symbol-name (car elt))
5573 (when (memq (car elt)
5577 (this-key (let ((key (read-key (concat todo-edit-item--prompt p->k))))
5578 (and (characterp key) (char-to-string key))))
5579 (this-param (car (rassoc this-key params))))
5581 (`edit (todo-edit-item--text))
5582 (`header (todo-edit-item--text 'include-header))
5583 (`multiline (todo-edit-item--text 'multiline))
5584 (`add/edit (todo-edit-item--text 'comment-edit))
5585 (`delete (todo-edit-item--text 'comment-delete))
5586 (`diary (todo-edit-item--diary-inclusion))
5587 (`nonmarking (todo-edit-item--diary-inclusion 'nonmarking))
5588 (`date (let ((todo-edit-item--prompt "Press a key (so far `e d'): "))
5589 (todo-edit-item--next-key
5590 todo-edit-item--date-param-key-alist arg)))
5591 (`full (progn (todo-edit-item--header 'date)
5592 (when todo-always-add-time-string
5593 (todo-edit-item--header 'time))))
5594 (`calendar (todo-edit-item--header 'calendar))
5595 (`today (todo-edit-item--header 'today))
5596 (`dayname (todo-edit-item--header 'dayname))
5597 (`year (todo-edit-item--header 'year arg))
5598 (`month (todo-edit-item--header 'month arg))
5599 (`daynum (todo-edit-item--header 'day arg))
5600 (`time (todo-edit-item--header 'time)))))
5602 ;; -----------------------------------------------------------------------------
5603 ;;; Todo minibuffer utilities
5604 ;; -----------------------------------------------------------------------------
5606 (defcustom todo-y-with-space nil
5607 "Non-nil means allow SPC to affirm a \"y or n\" question."
5611 (defun todo-y-or-n-p (prompt)
5612 "Ask \"y or n\" question PROMPT and return t if answer is \"y\".
5613 Also return t if answer is \"Y\", but unlike `y-or-n-p', allow
5614 SPC to affirm the question only if option `todo-y-with-space' is
5616 (unless todo-y-with-space
5617 (define-key query-replace-map " " 'ignore))
5620 (define-key query-replace-map " " 'act)))
5622 (defun todo-category-completions (&optional archive)
5623 "Return a list of completions for `todo-read-category'.
5624 Each element of the list is a cons of a category name and the
5625 file or list of files (as short file names) it is in. The files
5626 are either the current (or if there is none, the default) todo
5627 file plus the files listed in `todo-category-completions-files',
5628 or, with non-nil ARCHIVE, the current archive file.
5630 Before calculating the completions, update the value of
5631 `todo-category-completions-files' in case any files named in it
5634 (dolist (f todo-category-completions-files)
5635 (unless (file-exists-p (todo-absolute-file-name f))
5636 (setq todo-category-completions-files
5637 (delete f todo-category-completions-files))
5640 (let ((pl (> (length deleted) 1))
5641 (names (mapconcat (lambda (f) (concat "\"" f "\"")) deleted ", ")))
5642 (message (concat "File" (if pl "s" "") " " names " ha" (if pl "ve" "s")
5643 " been deleted and removed from\n"
5644 "the list of category completion files")))
5645 (todo-reevaluate-category-completions-files-defcustom)
5646 (custom-set-default 'todo-category-completions-files
5647 (symbol-value 'todo-category-completions-files))
5649 (let* ((curfile (or todo-current-todo-file
5650 (and todo-show-current-file
5651 todo-global-current-todo-file)
5652 (todo-absolute-file-name todo-default-todo-file)))
5653 (files (or (unless archive
5654 (mapcar 'todo-absolute-file-name
5655 todo-category-completions-files))
5658 ;; If file was just added, it has no category completions.
5659 (unless (zerop (buffer-size (find-buffer-visiting curfile)))
5660 (unless (member curfile todo-archives)
5661 (add-to-list 'files curfile))
5662 (dolist (f files listall)
5663 (with-current-buffer (find-file-noselect f 'nowarn)
5665 (unless (derived-mode-p 'todo-archive-mode) (todo-archive-mode))
5666 (unless (derived-mode-p 'todo-mode) (todo-mode)))
5667 ;; Ensure category is properly displayed in case user
5668 ;; switches to file via a non-Todo mode command. And if
5669 ;; done items in category are visible, keep them visible.
5670 (let ((done todo-show-with-done))
5671 (when (> (buffer-size) (- (point-max) (point-min)))
5673 (goto-char (point-min))
5674 (setq done (re-search-forward todo-done-string-start nil t))))
5675 (let ((todo-show-with-done done))
5676 (save-excursion (todo-category-select))))
5680 (goto-char (point-min))
5681 (setq listf (read (buffer-substring-no-properties
5682 (line-beginning-position)
5683 (line-end-position)))))))
5684 (mapc (lambda (elt) (let* ((cat (car elt))
5685 (la-elt (assoc cat listall)))
5687 (setcdr la-elt (append (list (cdr la-elt))
5689 (push (cons cat f) listall))))
5692 (defun todo-read-file-name (prompt &optional archive mustmatch)
5693 "Choose and return the name of a todo file, prompting with PROMPT.
5695 Show completions with TAB or SPC; the names are shown in short
5696 form but the absolute truename is returned. With non-nil ARCHIVE
5697 return the absolute truename of a todo archive file. With non-nil
5698 MUSTMATCH the name of an existing file must be chosen;
5699 otherwise, a new file name is allowed."
5700 (let* ((completion-ignore-case todo-completion-ignore-case)
5701 (files (mapcar 'todo-short-file-name
5702 ;; (funcall todo-files-function archive)))
5703 (if archive todo-archives todo-files)))
5704 (file (completing-read prompt files nil mustmatch nil nil
5706 ;; If user hit RET without
5707 ;; choosing a file, default to
5708 ;; current or default file.
5709 (todo-short-file-name
5710 (or todo-current-todo-file
5711 (and todo-show-current-file
5712 todo-global-current-todo-file)
5713 (todo-absolute-file-name
5714 todo-default-todo-file)))
5715 ;; Trigger prompt for initial file.
5717 (unless (file-exists-p todo-directory)
5718 (make-directory todo-directory))
5719 (unless (or mustmatch (member file files))
5720 (setq file (todo-validate-name file 'file)))
5721 (setq file (file-truename (concat todo-directory file
5722 (if archive ".toda" ".todo"))))))
5724 (defun todo-read-category (prompt &optional match-type file)
5725 "Choose and return a category name, prompting with PROMPT.
5726 Show completions for existing categories with TAB or SPC.
5728 The argument MATCH-TYPE specifies the matching requirements on
5729 the category name: with the value `todo' or `archive' the name
5730 must complete to that of an existing todo or archive category,
5731 respectively; with the value `add' the name must not be that of
5732 an existing category; with all other values both existing and new
5733 valid category names are accepted.
5735 With non-nil argument FILE prompt for a file and complete only
5736 against categories in that file; otherwise complete against all
5737 categories from `todo-category-completions-files'."
5738 ;; Allow SPC to insert spaces, for adding new category names.
5739 (let ((map minibuffer-local-completion-map))
5740 (define-key map " " nil)
5741 (let* ((add (eq match-type 'add))
5742 (archive (eq match-type 'archive))
5743 (file0 (when (and file (> (length todo-files) 1))
5744 (todo-read-file-name (concat "Choose a" (if archive
5747 " file: ") archive t)))
5748 (completions (unless file0 (todo-category-completions archive)))
5749 (categories (cond (file0
5750 (with-current-buffer
5751 (find-file-noselect file0 'nowarn)
5752 (unless (derived-mode-p 'todo-mode) (todo-mode))
5753 (let ((todo-current-todo-file file0))
5755 ((and add (not file))
5756 (with-current-buffer
5757 (find-file-noselect todo-current-todo-file)
5761 (completion-ignore-case todo-completion-ignore-case)
5762 (cat (completing-read prompt categories nil
5763 (eq match-type 'todo) nil nil
5764 ;; Unless we're adding a category via
5765 ;; todo-add-category, set default
5766 ;; for existing categories to the
5767 ;; current category of the chosen
5768 ;; file or else of the current file.
5769 (if (and categories (not add))
5770 (with-current-buffer
5773 todo-current-todo-file
5774 (todo-absolute-file-name
5775 todo-default-todo-file)))
5776 (todo-current-category))
5777 ;; Trigger prompt for initial category.
5779 (catfil (cdr (assoc cat completions)))
5780 (str "Category \"%s\" from which file (TAB for choices)? "))
5781 ;; If we do category completion and the chosen category name
5782 ;; occurs in more than one file, prompt to choose one file.
5783 (unless (or file0 add (not catfil))
5784 (setq file0 (file-truename
5787 (todo-absolute-file-name
5788 (let ((files (mapcar 'todo-short-file-name catfil)))
5789 (completing-read (format str cat) files)))))))
5790 ;; Default to the current file.
5791 (unless file0 (setq file0 todo-current-todo-file))
5792 ;; First validate only a name passed interactively from
5793 ;; todo-add-category, which must be of a nonexistent category.
5794 (unless (and (assoc cat categories) (not add))
5795 ;; Validate only against completion categories.
5796 (let ((todo-categories categories))
5797 (setq cat (todo-validate-name cat 'category)))
5798 ;; When user enters a nonexistent category name by jumping or
5799 ;; moving, confirm that it should be added, then validate.
5801 (if (todo-y-or-n-p (format "Add new category \"%s\" to file \"%s\"? "
5802 cat (todo-short-file-name file0)))
5804 (when (assoc cat categories)
5805 (let ((todo-categories categories))
5806 (setq cat (todo-validate-name cat 'category))))
5807 ;; Restore point and narrowing after adding new
5808 ;; category, to avoid moving to beginning of file when
5809 ;; moving marked items to a new category
5810 ;; (todo-move-item).
5813 (todo-add-category file0 cat))))
5814 ;; If we decide not to add a category, exit without returning.
5818 (defun todo-validate-name (name type)
5819 "Prompt for new NAME for TYPE until it is valid, then return it.
5820 TYPE can be either of the symbols `file' or `category'."
5821 (let ((categories todo-categories)
5822 (files (mapcar 'todo-short-file-name todo-files))
5826 (cond ((string= "" name)
5828 (cond ((eq type 'file)
5830 "Enter a non-empty file name: "
5831 ;; Empty string passed by todo-show to
5832 ;; prompt for initial todo file.
5833 (concat "Initial file name ["
5834 todo-initial-file "]: ")))
5835 ((eq type 'category)
5837 "Enter a non-empty category name: "
5838 ;; Empty string passed by todo-show to
5839 ;; prompt for initial category of a new
5841 (concat "Initial category name ["
5842 todo-initial-category "]: "))))))
5843 ((string-match "\\`\\s-+\\'" name)
5845 "Enter a name that does not contain only white space: "))
5846 ((and (eq type 'file) (member name files))
5847 (setq prompt "Enter a non-existing file name: "))
5848 ((and (eq type 'category) (assoc name categories))
5849 (setq prompt "Enter a non-existing category name: ")))
5850 (setq name (if (or (and (eq type 'file) files)
5851 (and (eq type 'category) categories))
5852 (completing-read prompt (cond ((eq type 'file)
5854 ((eq type 'category)
5856 ;; Offer default initial name.
5857 (completing-read prompt (if (eq type 'file)
5860 nil nil (if (eq type 'file)
5862 todo-initial-category))))))
5865 ;; Adapted from calendar-read-date and calendar-date-string.
5866 (defun todo-read-date (&optional arg mo yr)
5867 "Prompt for Gregorian date and return it in the current format.
5869 With non-nil ARG, prompt for and return only the date component
5870 specified by ARG, which can be one of these symbols:
5871 `month' (prompt for name, return name or number according to
5872 value of `calendar-date-display-form'), `day' of month, or
5873 `year'. The value of each of these components can be `*',
5874 indicating an unspecified month, day, or year.
5876 When ARG is `day', non-nil arguments MO and YR determine the
5877 number of the last the day of the month."
5878 (let (year monthname month day
5879 dayname) ; Needed by calendar-date-display-form.
5880 (when (or (not arg) (eq arg 'year))
5881 (while (if (natnump year) (< year 1) (not (eq year '*)))
5882 (setq year (read-from-minibuffer
5883 "Year (>0 or RET for this year or * for any year): "
5884 nil nil t nil (number-to-string
5885 (calendar-extract-year
5886 (calendar-current-date)))))))
5887 (when (or (not arg) (eq arg 'month))
5888 (let* ((marray todo-month-name-array)
5889 (mlist (append marray nil))
5890 (mabarray todo-month-abbrev-array)
5891 (mablist (append mabarray nil))
5892 (completion-ignore-case todo-completion-ignore-case))
5893 (setq monthname (completing-read
5894 "Month name (RET for current month, * for any month): "
5896 (calendar-month-name (calendar-extract-month
5897 (calendar-current-date)) t))
5898 month (1+ (- (length mlist)
5899 (length (or (member monthname mlist)
5900 (member monthname mablist))))))
5901 (setq monthname (aref mabarray (1- month)))))
5902 (when (or (not arg) (eq arg 'day))
5903 (let ((last (let ((mm (or month mo))
5905 ;; If month is unspecified, use a month with 31
5906 ;; days for checking day of month input. Does
5907 ;; Calendar do anything special when * is
5908 ;; currently a shorter month?
5909 (if (= mm 13) (setq mm 1))
5910 ;; If year is unspecified, use a leap year to
5912 (if (eq year '*) (setq yy 2012))
5913 (calendar-last-day-of-month mm yy))))
5914 (while (if (natnump day) (or (< day 1) (> day last)) (not (eq day '*)))
5915 (setq day (read-from-minibuffer
5916 (format "Day (1-%d or RET for today or * for any day): "
5918 nil nil t nil (number-to-string
5919 (calendar-extract-day
5920 (calendar-current-date))))))))
5921 ;; Stringify read values (monthname is already a string).
5922 (and year (setq year (if (eq year '*)
5924 (number-to-string year))))
5925 (and day (setq day (if (eq day '*)
5927 (number-to-string day))))
5928 (and month (setq month (if (eq month '*)
5930 (number-to-string month))))
5932 (cond ((eq arg 'year) year)
5935 (if (memq 'month calendar-date-display-form)
5938 (mapconcat 'eval calendar-date-display-form ""))))
5940 (defun todo-read-dayname ()
5941 "Choose name of a day of the week with completion and return it."
5942 (let ((completion-ignore-case todo-completion-ignore-case))
5943 (completing-read "Enter a day name: "
5944 (append calendar-day-name-array nil)
5947 (defun todo-read-time ()
5948 "Prompt for and return a valid clock time as a string.
5950 Valid time strings are those matching `diary-time-regexp'.
5951 Typing `<return>' at the prompt returns the current time, if the
5952 user option `todo-always-add-time-string' is non-nil, otherwise
5953 the empty string (i.e., no time string)."
5956 (setq answer (read-string "Enter a clock time: " nil nil
5957 (when todo-always-add-time-string
5958 (substring (current-time-string) 11 16))))
5959 (when (or (string= "" answer)
5960 (string-match diary-time-regexp answer))
5964 ;; -----------------------------------------------------------------------------
5965 ;;; Customization groups and utilities
5966 ;; -----------------------------------------------------------------------------
5969 "Create and maintain categorized lists of todo items."
5970 :link '(emacs-commentary-link "todo")
5974 (defgroup todo-edit nil
5975 "User options for adding and editing todo items."
5979 (defgroup todo-categories nil
5980 "User options for Todo Categories mode."
5984 (defgroup todo-filtered nil
5985 "User options for Todo Filter Items mode."
5989 (defgroup todo-display nil
5990 "User display options for Todo mode."
5994 (defgroup todo-faces nil
5995 "Faces for the Todo modes."
5999 (defun todo-set-show-current-file (symbol value)
6000 "The :set function for user option `todo-show-current-file'."
6001 (custom-set-default symbol value)
6003 (add-hook 'pre-command-hook 'todo-show-current-file nil t)
6004 (remove-hook 'pre-command-hook 'todo-show-current-file t)))
6006 (defun todo-reset-prefix (symbol value)
6007 "The :set function for `todo-prefix' and `todo-number-prefix'."
6008 (let ((oldvalue (symbol-value symbol))
6009 (files todo-file-buffers))
6010 (custom-set-default symbol value)
6011 (when (not (equal value oldvalue))
6013 (with-current-buffer (find-file-noselect f)
6014 ;; Activate the new setting in the current category.
6015 (save-excursion (todo-category-select)))))))
6017 (defun todo-reset-nondiary-marker (symbol value)
6018 "The :set function for user option `todo-nondiary-marker'."
6019 (let* ((oldvalue (symbol-value symbol))
6020 (files (append todo-files todo-archives
6021 (directory-files todo-directory t "\.tod[rty]$" t))))
6022 (custom-set-default symbol value)
6023 ;; Need to reset these to get font-locking right.
6024 (setq todo-nondiary-start (nth 0 todo-nondiary-marker)
6025 todo-nondiary-end (nth 1 todo-nondiary-marker)
6026 todo-date-string-start
6027 ;; See comment in defvar of `todo-date-string-start'.
6028 (concat "^\\(" (regexp-quote todo-nondiary-start) "\\|"
6029 (regexp-quote diary-nonmarking-symbol) "\\)?"))
6030 (when (not (equal value oldvalue))
6032 (let ((buf (find-buffer-visiting f)))
6033 (with-current-buffer (find-file-noselect f)
6034 (let (buffer-read-only)
6036 (goto-char (point-min))
6038 (if (re-search-forward
6039 (concat "^\\(" todo-done-string-start "[^][]+] \\)?"
6040 "\\(?1:" (regexp-quote (car oldvalue))
6041 "\\)" todo-date-pattern "\\( "
6042 diary-time-regexp "\\)?\\(?2:"
6043 (regexp-quote (cadr oldvalue)) "\\)")
6046 (replace-match (nth 0 value) t t nil 1)
6047 (replace-match (nth 1 value) t t nil 2))
6050 (when (derived-mode-p 'todo-mode 'todo-archive-mode)
6051 (todo-category-select))
6053 (kill-buffer)))))))))
6055 (defun todo-reset-done-separator-string (symbol value)
6056 "The :set function for `todo-done-separator-string'."
6057 (let ((oldvalue (symbol-value symbol))
6058 (files todo-file-buffers)
6059 (sep todo-done-separator))
6060 (custom-set-default symbol value)
6061 (when (not (equal value oldvalue))
6063 (with-current-buffer (find-file-noselect f)
6064 (let (buffer-read-only)
6065 (setq todo-done-separator (todo-done-separator))
6066 (when (= 1 (length value))
6067 (todo-reset-done-separator sep)))
6068 (todo-category-select))))))
6070 (defun todo-reset-done-string (symbol value)
6071 "The :set function for user option `todo-done-string'."
6072 (let ((oldvalue (symbol-value symbol))
6073 (files (append todo-files todo-archives
6074 (directory-files todo-directory t "\.todr$" t))))
6075 (custom-set-default symbol value)
6076 ;; Need to reset this to get font-locking right.
6077 (setq todo-done-string-start
6078 (concat "^\\[" (regexp-quote todo-done-string)))
6079 (when (not (equal value oldvalue))
6081 (let ((buf (find-buffer-visiting f)))
6082 (with-current-buffer (find-file-noselect f)
6083 (let (buffer-read-only)
6085 (goto-char (point-min))
6087 (if (re-search-forward
6088 (concat "^" (regexp-quote todo-nondiary-start)
6089 "\\(" (regexp-quote oldvalue) "\\)")
6091 (replace-match value t t nil 1)
6094 (when (derived-mode-p 'todo-mode 'todo-archive-mode)
6095 (todo-category-select))
6097 (kill-buffer)))))))))
6099 (defun todo-reset-comment-string (symbol value)
6100 "The :set function for user option `todo-comment-string'."
6101 (let ((oldvalue (symbol-value symbol))
6102 (files (append todo-files todo-archives
6103 (directory-files todo-directory t "\.todr$" t))))
6104 (custom-set-default symbol value)
6105 (when (not (equal value oldvalue))
6107 (let ((buf (find-buffer-visiting f)))
6108 (with-current-buffer (find-file-noselect f)
6109 (let (buffer-read-only)
6111 (goto-char (point-min))
6113 (if (re-search-forward
6114 (concat "\\[\\(" (regexp-quote oldvalue)
6117 (replace-match value t t nil 1)
6120 (when (derived-mode-p 'todo-mode 'todo-archive-mode)
6121 (todo-category-select))
6123 (kill-buffer)))))))))
6125 (defun todo-reset-highlight-item (symbol value)
6126 "The :set function for user option `todo-highlight-item'."
6127 (let ((oldvalue (symbol-value symbol))
6128 (files (append todo-files todo-archives
6129 (directory-files todo-directory t "\.tod[rty]$" t))))
6130 (custom-set-default symbol value)
6131 (when (not (equal value oldvalue))
6133 (let ((buf (find-buffer-visiting f)))
6135 (with-current-buffer buf
6139 (hl-line-mode -1)))))))))
6141 (defun todo-reevaluate-filelist-defcustoms ()
6142 "Reevaluate defcustoms that provide choice list of todo files."
6143 (custom-set-default 'todo-default-todo-file
6144 (symbol-value 'todo-default-todo-file))
6145 (todo-reevaluate-default-file-defcustom)
6146 (custom-set-default 'todo-filter-files (symbol-value 'todo-filter-files))
6147 (todo-reevaluate-filter-files-defcustom)
6148 (custom-set-default 'todo-category-completions-files
6149 (symbol-value 'todo-category-completions-files))
6150 (todo-reevaluate-category-completions-files-defcustom))
6152 (defun todo-reevaluate-default-file-defcustom ()
6153 "Reevaluate defcustom of `todo-default-todo-file'.
6154 Called after adding or deleting a todo file. If the value of
6155 `todo-default-todo-file' before calling this function was
6156 associated with an existing file, keep that value."
6157 ;; (let ((curval todo-default-todo-file))
6159 (defcustom todo-default-todo-file (todo-short-file-name
6160 (car (funcall todo-files-function)))
6161 "Todo file visited by first session invocation of `todo-show'."
6162 :type (when todo-files
6163 `(radio ,@(mapcar (lambda (f) (list 'const f))
6164 (mapcar 'todo-short-file-name
6165 (funcall todo-files-function)))))
6167 ;; (when (and curval (file-exists-p (todo-absolute-file-name curval)))
6168 ;; (custom-set-default 'todo-default-todo-file curval)
6169 ;; ;; (custom-reevaluate-setting 'todo-default-todo-file)
6173 (defun todo-reevaluate-category-completions-files-defcustom ()
6174 "Reevaluate defcustom of `todo-category-completions-files'.
6175 Called after adding or deleting a todo file."
6176 (eval (defcustom todo-category-completions-files nil
6177 "List of files for building `todo-read-category' completions."
6178 :type `(set ,@(mapcar (lambda (f) (list 'const f))
6179 (mapcar 'todo-short-file-name
6180 (funcall todo-files-function))))
6183 (defun todo-reevaluate-filter-files-defcustom ()
6184 "Reevaluate defcustom of `todo-filter-files'.
6185 Called after adding or deleting a todo file."
6186 (eval (defcustom todo-filter-files nil
6187 "List of files for multifile item filtering."
6188 :type `(set ,@(mapcar (lambda (f) (list 'const f))
6189 (mapcar 'todo-short-file-name
6190 (funcall todo-files-function))))
6193 ;; -----------------------------------------------------------------------------
6195 ;; -----------------------------------------------------------------------------
6197 (defun todo-nondiary-marker-matcher (lim)
6198 "Search for todo item nondiary markers within LIM for font-locking."
6199 (re-search-forward (concat "^\\(?1:" (regexp-quote todo-nondiary-start) "\\)"
6200 todo-date-pattern "\\(?: " diary-time-regexp
6201 "\\)?\\(?2:" (regexp-quote todo-nondiary-end) "\\)")
6204 (defun todo-diary-nonmarking-matcher (lim)
6205 "Search for diary nonmarking symbol within LIM for font-locking."
6206 (re-search-forward (concat "^\\(?1:" (regexp-quote diary-nonmarking-symbol)
6207 "\\)" todo-date-pattern) lim t))
6209 (defun todo-date-string-matcher (lim)
6210 "Search for todo item date string within LIM for font-locking."
6212 (concat todo-date-string-start "\\(?1:" todo-date-pattern "\\)") lim t))
6214 (defun todo-time-string-matcher (lim)
6215 "Search for todo item time string within LIM for font-locking."
6216 (re-search-forward (concat todo-date-string-start todo-date-pattern
6217 " \\(?1:" diary-time-regexp "\\)") lim t))
6219 (defun todo-diary-expired-matcher (lim)
6220 "Search for expired diary item date within LIM for font-locking."
6221 (when (re-search-forward (concat "^\\(?:"
6222 (regexp-quote diary-nonmarking-symbol)
6223 "\\)?\\(?1:" todo-date-pattern "\\) \\(?2:"
6224 diary-time-regexp "\\)?") lim t)
6225 (let* ((date (match-string-no-properties 1))
6226 (time (match-string-no-properties 2))
6227 ;; Function days-between requires a non-empty time string.
6228 (date-time (concat date " " (or time "00:00"))))
6229 (or (and (not (string-match ".+day\\|\\*" date))
6230 (< (days-between date-time (current-time-string)) 0))
6231 (todo-diary-expired-matcher lim)))))
6233 (defun todo-done-string-matcher (lim)
6234 "Search for done todo item header within LIM for font-locking."
6235 (re-search-forward (concat todo-done-string-start
6239 (defun todo-comment-string-matcher (lim)
6240 "Search for done todo item comment within LIM for font-locking."
6241 (re-search-forward (concat "\\[\\(?1:" todo-comment-string "\\):")
6244 (defun todo-category-string-matcher-1 (lim)
6245 "Search for todo category name within LIM for font-locking.
6246 This is for fontifying category and file names appearing in Todo
6247 Filtered Items mode following done items."
6248 (if (eq major-mode 'todo-filtered-items-mode)
6249 (re-search-forward (concat todo-done-string-start todo-date-pattern
6250 "\\(?: " diary-time-regexp
6251 ;; Use non-greedy operator to prevent
6252 ;; capturing possible following non-diary
6254 "\\)?] \\(?1:\\[.+?\\]\\)")
6257 (defun todo-category-string-matcher-2 (lim)
6258 "Search for todo category name within LIM for font-locking.
6259 This is for fontifying category and file names appearing in Todo
6260 Filtered Items mode following todo (not done) items."
6261 (if (eq major-mode 'todo-filtered-items-mode)
6262 (re-search-forward (concat todo-date-string-start todo-date-pattern
6263 "\\(?: " diary-time-regexp "\\)?\\(?:"
6264 (regexp-quote todo-nondiary-end)
6265 "\\)? \\(?1:\\[.+\\]\\)")
6268 (defvar todo-nondiary-face 'todo-nondiary)
6269 (defvar todo-date-face 'todo-date)
6270 (defvar todo-time-face 'todo-time)
6271 (defvar todo-diary-expired-face 'todo-diary-expired)
6272 (defvar todo-done-sep-face 'todo-done-sep)
6273 (defvar todo-done-face 'todo-done)
6274 (defvar todo-comment-face 'todo-comment)
6275 (defvar todo-category-string-face 'todo-category-string)
6276 (defvar todo-font-lock-keywords
6278 '(todo-nondiary-marker-matcher 1 todo-nondiary-face t)
6279 '(todo-nondiary-marker-matcher 2 todo-nondiary-face t)
6280 ;; diary-lib.el uses font-lock-constant-face for diary-nonmarking-symbol.
6281 '(todo-diary-nonmarking-matcher 1 font-lock-constant-face t)
6282 '(todo-date-string-matcher 1 todo-date-face t)
6283 '(todo-time-string-matcher 1 todo-time-face t)
6284 '(todo-done-string-matcher 0 todo-done-face t)
6285 '(todo-comment-string-matcher 1 todo-comment-face t)
6286 '(todo-category-string-matcher-1 1 todo-category-string-face t t)
6287 '(todo-category-string-matcher-2 1 todo-category-string-face t t)
6288 '(todo-diary-expired-matcher 1 todo-diary-expired-face t)
6289 '(todo-diary-expired-matcher 2 todo-diary-expired-face t t)
6291 "Font-locking for Todo modes.")
6293 ;; -----------------------------------------------------------------------------
6295 ;; -----------------------------------------------------------------------------
6297 (defvar todo-key-bindings-t
6299 ("Af" todo-find-archive)
6300 ("Ac" todo-choose-archive)
6301 ("Ad" todo-archive-done-item)
6302 ("Cv" todo-toggle-view-done-items)
6303 ("v" todo-toggle-view-done-items)
6304 ("Ca" todo-add-category)
6305 ("Cr" todo-rename-category)
6306 ("Cg" todo-merge-category)
6307 ("Cm" todo-move-category)
6308 ("Ck" todo-delete-category)
6309 ("Cts" todo-set-top-priorities-in-category)
6310 ("Cey" todo-edit-category-diary-inclusion)
6311 ("Cek" todo-edit-category-diary-nonmarking)
6312 ("Fa" todo-add-file)
6313 ("Fr" todo-rename-file)
6314 ("Ff" todo-find-filtered-items-file)
6315 ("FV" todo-toggle-view-done-only)
6316 ("V" todo-toggle-view-done-only)
6317 ("Ftt" todo-filter-top-priorities)
6318 ("Ftm" todo-filter-top-priorities-multifile)
6319 ("Fts" todo-set-top-priorities-in-file)
6320 ("Fyy" todo-filter-diary-items)
6321 ("Fym" todo-filter-diary-items-multifile)
6322 ("Fxx" todo-filter-regexp-items)
6323 ("Fxm" todo-filter-regexp-items-multifile)
6324 ("e" todo-edit-item)
6325 ("d" todo-item-done)
6326 ("i" todo-insert-item)
6327 ("k" todo-delete-item)
6328 ("m" todo-move-item)
6329 ("u" todo-item-undone)
6330 ([remap newline] newline-and-indent)
6332 "List of key bindings for Todo mode only.")
6334 (defvar todo-key-bindings-t+a+f
6336 ("C*" todo-mark-category)
6337 ("Cu" todo-unmark-category)
6338 ("Fh" todo-toggle-item-header)
6339 ("h" todo-toggle-item-header)
6340 ("Fk" todo-delete-file)
6341 ("Fe" todo-edit-file)
6342 ("FH" todo-toggle-item-highlighting)
6343 ("H" todo-toggle-item-highlighting)
6344 ("FN" todo-toggle-prefix-numbers)
6345 ("N" todo-toggle-prefix-numbers)
6346 ("PB" todo-print-buffer)
6347 ("PF" todo-print-buffer-to-file)
6348 ("b" todo-backward-category)
6349 ("d" todo-item-done)
6350 ("f" todo-forward-category)
6351 ("j" todo-jump-to-category)
6352 ("n" todo-next-item)
6353 ("p" todo-previous-item)
6358 "List of key bindings for Todo, Archive, and Filtered Items modes.")
6360 (defvar todo-key-bindings-t+a
6362 ("Fc" todo-show-categories-table)
6364 ("X" todo-clear-matches)
6365 ("*" todo-toggle-mark-item)
6367 "List of key bindings for Todo and Todo Archive modes.")
6369 (defvar todo-key-bindings-t+f
6371 ("l" todo-lower-item-priority)
6372 ("r" todo-raise-item-priority)
6373 ("#" todo-set-item-priority)
6375 "List of key bindings for Todo and Todo Filtered Items modes.")
6377 (defvar todo-mode-map
6378 (let ((map (make-keymap)))
6379 ;; Don't suppress digit keys, so they can supply prefix arguments.
6380 (suppress-keymap map)
6381 (dolist (kb todo-key-bindings-t)
6382 (define-key map (nth 0 kb) (nth 1 kb)))
6383 (dolist (kb todo-key-bindings-t+a+f)
6384 (define-key map (nth 0 kb) (nth 1 kb)))
6385 (dolist (kb todo-key-bindings-t+a)
6386 (define-key map (nth 0 kb) (nth 1 kb)))
6387 (dolist (kb todo-key-bindings-t+f)
6388 (define-key map (nth 0 kb) (nth 1 kb)))
6390 "Todo mode keymap.")
6392 (defvar todo-archive-mode-map
6393 (let ((map (make-sparse-keymap)))
6394 (suppress-keymap map)
6395 (dolist (kb todo-key-bindings-t+a+f)
6396 (define-key map (nth 0 kb) (nth 1 kb)))
6397 (dolist (kb todo-key-bindings-t+a)
6398 (define-key map (nth 0 kb) (nth 1 kb)))
6399 (define-key map "a" 'todo-jump-to-archive-category)
6400 (define-key map "u" 'todo-unarchive-items)
6402 "Todo Archive mode keymap.")
6404 (defvar todo-edit-mode-map
6405 (let ((map (make-sparse-keymap)))
6406 (define-key map "\C-x\C-q" 'todo-edit-quit)
6407 (define-key map [remap newline] 'newline-and-indent)
6409 "Todo Edit mode keymap.")
6411 (defvar todo-categories-mode-map
6412 (let ((map (make-sparse-keymap)))
6413 (suppress-keymap map)
6414 (define-key map "c" 'todo-sort-categories-alphabetically-or-numerically)
6415 (define-key map "t" 'todo-sort-categories-by-todo)
6416 (define-key map "y" 'todo-sort-categories-by-diary)
6417 (define-key map "d" 'todo-sort-categories-by-done)
6418 (define-key map "a" 'todo-sort-categories-by-archived)
6419 (define-key map "#" 'todo-set-category-number)
6420 (define-key map "l" 'todo-lower-category)
6421 (define-key map "r" 'todo-raise-category)
6422 (define-key map "n" 'todo-next-button)
6423 (define-key map "p" 'todo-previous-button)
6424 (define-key map [tab] 'todo-next-button)
6425 (define-key map [backtab] 'todo-previous-button)
6426 (define-key map "q" 'todo-quit)
6428 "Todo Categories mode keymap.")
6430 (defvar todo-filtered-items-mode-map
6431 (let ((map (make-sparse-keymap)))
6432 (suppress-keymap map)
6433 (dolist (kb todo-key-bindings-t+a+f)
6434 (define-key map (nth 0 kb) (nth 1 kb)))
6435 (dolist (kb todo-key-bindings-t+f)
6436 (define-key map (nth 0 kb) (nth 1 kb)))
6437 (define-key map "g" 'todo-go-to-source-item)
6438 (define-key map [remap newline] 'todo-go-to-source-item)
6440 "Todo Filtered Items mode keymap.")
6443 todo-menu todo-mode-map "Todo Menu"
6446 ["Next Item" todo-next-item t]
6447 ["Previous Item" todo-previous-item t]
6449 ["Next Category" todo-forward-category t]
6450 ["Previous Category" todo-backward-category t]
6451 ["Jump to Another Category" todo-jump-to-category t]
6453 ["Visit Another Todo File" todo-show t]
6454 ["Visit Archive" todo-find-archive t]
6455 ["Visit Filtered Items File" todo-find-filtered-items-file t]
6458 ["Insert New Item" todo-insert-item t]
6459 ["Edit Item" todo-edit-item t]
6460 ["Lower Item Priority" todo-lower-item-priority t]
6461 ["Raise Item Priority" todo-raise-item-priority t]
6462 ["Set Item Priority" todo-set-item-priority t]
6463 ["Mark/Unmark Item" todo-toggle-mark-item t]
6464 ["Move (Recategorize) Item" todo-move-item t]
6465 ["Delete Item" todo-delete-item t]
6466 ["Mark and Bury Done Item" todo-item-done t]
6467 ["Undo Done Item" todo-item-undone t]
6468 ["Archive Done Item" todo-archive-done-item t]
6470 ["Add New Category" todo-add-category t]
6471 ["Rename Current Category" todo-rename-category t]
6472 ["Delete Current Category" todo-delete-category t]
6473 ["Move Current Category" todo-move-category t]
6474 ["Merge Current Category" todo-merge-category t]
6476 ["Add New Todo File" todo-add-file t]
6477 ["Rename Todo File" todo-rename-file t]
6478 ["Delete Todo File" todo-delete-file t]
6479 ["Edit Todo File" todo-edit-file t]
6481 ("Searching and Item Filtering"
6482 ["Search Todo File" todo-search t]
6483 ["Clear Match Highlighting" todo-clear-matches t]
6485 ["Set Top Priorities in File" todo-set-top-priorities-in-file t]
6486 ["Set Top Priorities in Category" todo-set-top-priorities-in-category t]
6487 ["Filter Top Priorities" todo-filter-top-priorities t]
6488 ["Filter Multifile Top Priorities" todo-filter-top-priorities-multifile t]
6489 ["Filter Diary Items" todo-filter-diary-items t]
6490 ["Filter Multifile Diary Items" todo-filter-diary-items-multifile t]
6491 ["Filter Regexp" todo-filter-regexp-items t]
6492 ["Filter Multifile Regexp" todo-filter-regexp-items-multifile t]
6494 ("Display and Printing"
6495 ["Show/Hide Done Items" todo-toggle-view-done-items t]
6496 ["Show/Hide Done Items Only" todo-toggle-view-done-only t]
6497 ["Show/Hide Item Highlighting" todo-toggle-item-highlighting t]
6498 ["Show/Hide Item Numbering" todo-toggle-prefix-numbers t]
6499 ["Show/Hide Item Header" todo-toggle-item-header t]
6501 ["Display Table of Categories" todo-show-categories-table t]
6503 ["Print Category" todo-print-buffer t]
6504 ["Print Category to File" todo-print-buffer-to-file t]
6507 ["Save Todo File" todo-save t]
6508 ["Quit Todo Mode" todo-quit t]
6511 ;; -----------------------------------------------------------------------------
6512 ;;; Hook functions and mode definitions
6513 ;; -----------------------------------------------------------------------------
6515 (defun todo-show-current-file ()
6516 "Visit current instead of default todo file with `todo-show'.
6517 Added to `pre-command-hook' in Todo mode when user option
6518 `todo-show-current-file' is set to non-nil."
6519 (setq todo-global-current-todo-file todo-current-todo-file))
6521 ;; (defun todo-display-as-todo-file ()
6522 ;; "Show todo files correctly when visited from outside of Todo mode.
6523 ;; Added to `find-file-hook' in Todo mode and Todo Archive mode."
6524 ;; (and (member this-command todo-visit-files-commands)
6525 ;; (= (- (point-max) (point-min)) (buffer-size))
6526 ;; (member major-mode '(todo-mode todo-archive-mode))
6527 ;; (todo-category-select)))
6529 ;; (defun todo-add-to-buffer-list ()
6530 ;; "Add name of just visited todo file to `todo-file-buffers'.
6531 ;; This function is added to `find-file-hook' in Todo mode."
6532 ;; (let ((filename (file-truename (buffer-file-name))))
6533 ;; (when (member filename todo-files)
6534 ;; (add-to-list 'todo-file-buffers filename))))
6536 (defun todo-update-buffer-list ()
6537 "Make current Todo mode buffer file car of `todo-file-buffers'.
6538 This function is added to `post-command-hook' in Todo mode."
6539 (let ((filename (file-truename (buffer-file-name))))
6540 (unless (eq (car todo-file-buffers) filename)
6541 (setq todo-file-buffers
6542 (cons filename (delete filename todo-file-buffers))))))
6544 (defun todo-reset-global-current-todo-file ()
6545 "Update the value of `todo-global-current-todo-file'.
6546 This becomes the latest existing todo file or, if there is none,
6547 the value of `todo-default-todo-file'.
6548 This function is added to `kill-buffer-hook' in Todo mode."
6549 (let ((filename (file-truename (buffer-file-name))))
6550 (setq todo-file-buffers (delete filename todo-file-buffers))
6551 (setq todo-global-current-todo-file
6552 (or (car todo-file-buffers)
6553 (todo-absolute-file-name todo-default-todo-file)))))
6555 (defun todo-reset-and-enable-done-separator ()
6556 "Show resized done items separator overlay after window change.
6557 Added to `window-configuration-change-hook' in Todo mode."
6558 (when (= 1 (length todo-done-separator-string))
6559 (let ((sep todo-done-separator))
6560 (setq todo-done-separator (todo-done-separator))
6561 (save-match-data (todo-reset-done-separator sep)))))
6563 (defun todo-modes-set-1 ()
6564 "Make some settings that apply to multiple Todo modes."
6565 (setq-local font-lock-defaults '(todo-font-lock-keywords t))
6566 (setq-local revert-buffer-function 'todo-revert-buffer)
6567 (setq-local tab-width todo-indent-to-here)
6568 (setq-local indent-line-function 'todo-indent)
6569 (when todo-wrap-lines
6571 (setq wrap-prefix (make-string todo-indent-to-here 32))))
6573 (defun todo-modes-set-2 ()
6574 "Make some settings that apply to multiple Todo modes."
6575 (add-to-invisibility-spec 'todo)
6576 (setq buffer-read-only t)
6577 (when (and (boundp 'desktop-save-mode) desktop-save-mode)
6578 (setq-local desktop-save-buffer 'todo-desktop-save-buffer))
6579 (when (boundp 'hl-line-range-function)
6580 (setq-local hl-line-range-function
6581 (lambda() (save-excursion
6582 (when (todo-item-end)
6583 (cons (todo-item-start)
6584 (todo-item-end))))))))
6586 (defun todo-modes-set-3 ()
6587 "Make some settings that apply to multiple Todo modes."
6588 (setq-local todo-categories (todo-set-categories))
6589 (setq-local todo-category-number 1)
6590 ;; (add-hook 'find-file-hook 'todo-display-as-todo-file nil t)
6593 (put 'todo-mode 'mode-class 'special)
6596 (define-derived-mode todo-mode special-mode "Todo"
6597 "Major mode for displaying, navigating and editing todo lists.
6600 (if (called-interactively-p 'any)
6601 (message "Type `M-x todo-show' to enter Todo mode")
6605 ;; Initialize todo-current-todo-file.
6606 (when (member (file-truename (buffer-file-name))
6607 (funcall todo-files-function))
6608 (setq-local todo-current-todo-file (file-truename (buffer-file-name))))
6609 (setq-local todo-show-done-only nil)
6610 (setq-local todo-categories-with-marks nil)
6611 ;; (add-hook 'find-file-hook 'todo-add-to-buffer-list nil t)
6612 (add-hook 'post-command-hook 'todo-update-buffer-list nil t)
6613 (when todo-show-current-file
6614 (add-hook 'pre-command-hook 'todo-show-current-file nil t))
6615 (add-hook 'window-configuration-change-hook
6616 'todo-reset-and-enable-done-separator nil t)
6617 (add-hook 'kill-buffer-hook 'todo-reset-global-current-todo-file nil t)))
6619 (put 'todo-archive-mode 'mode-class 'special)
6621 ;; If todo-mode is parent, all todo-mode key bindings appear to be
6622 ;; available in todo-archive-mode (e.g. shown by C-h m).
6624 (define-derived-mode todo-archive-mode special-mode "Todo-Arch"
6625 "Major mode for archived todo categories.
6627 \\{todo-archive-mode-map}"
6631 (setq-local todo-current-todo-file (file-truename (buffer-file-name)))
6632 (setq-local todo-show-done-only t))
6634 (defun todo-mode-external-set ()
6635 "Set `todo-categories' externally to `todo-current-todo-file'."
6636 (setq-local todo-current-todo-file todo-global-current-todo-file)
6637 (let ((cats (with-current-buffer
6638 ;; Can't use find-buffer-visiting when
6639 ;; `todo-show-categories-table' is called on first
6640 ;; invocation of `todo-show', since there is then
6641 ;; no buffer visiting the current file.
6642 (find-file-noselect todo-current-todo-file 'nowarn)
6644 ;; In Todo Edit mode todo-categories is now nil
6645 ;; since it uses same buffer as Todo mode but
6646 ;; doesn't have the latter's local variables.
6648 (goto-char (point-min))
6649 (read (buffer-substring-no-properties
6650 (line-beginning-position)
6651 (line-end-position))))))))
6652 (setq-local todo-categories cats)))
6654 (define-derived-mode todo-edit-mode text-mode "Todo-Ed"
6655 "Major mode for editing multiline todo items.
6657 \\{todo-edit-mode-map}"
6659 (todo-mode-external-set)
6660 (setq buffer-read-only nil))
6662 (put 'todo-categories-mode 'mode-class 'special)
6664 (define-derived-mode todo-categories-mode special-mode "Todo-Cats"
6665 "Major mode for displaying and editing todo categories.
6667 \\{todo-categories-mode-map}"
6668 (todo-mode-external-set))
6670 (put 'todo-filtered-items-mode 'mode-class 'special)
6673 (define-derived-mode todo-filtered-items-mode special-mode "Todo-Fltr"
6674 "Mode for displaying and reprioritizing top priority Todo.
6676 \\{todo-filtered-items-mode-map}"
6680 ;; -----------------------------------------------------------------------------
6681 (provide 'todo-mode)
6683 ;;; todo-mode.el ends here