1 ;;; todo-mode.el --- facilities for making and maintaining todo lists
3 ;; Copyright (C) 1997, 1999, 2001-2014 Free Software Foundation, Inc.
5 ;; Author: Oliver Seidel <privat@os10000.net>
6 ;; Stephen Berman <stephen.berman@gmx.net>
7 ;; Maintainer: Stephen Berman <stephen.berman@gmx.net>
8 ;; Keywords: calendar, todo
10 ;; This file is part of GNU Emacs.
12 ;; GNU Emacs is free software: you can redistribute it and/or modify
13 ;; it under the terms of the GNU General Public License as published by
14 ;; the Free Software Foundation, either version 3 of the License, or
15 ;; (at your option) any later version.
17 ;; GNU Emacs is distributed in the hope that it will be useful,
18 ;; but WITHOUT ANY WARRANTY; without even the implied warranty of
19 ;; MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
20 ;; GNU General Public License for more details.
22 ;; You should have received a copy of the GNU General Public License
23 ;; along with GNU Emacs. If not, see <http://www.gnu.org/licenses/>.
27 ;; This package provides facilities for making, displaying, navigating
28 ;; and editing todo lists, which are prioritized lists of todo items.
29 ;; Todo lists are identified with named categories, so you can group
30 ;; together and separately prioritize thematically related todo items.
31 ;; Each category is stored in a file, which thus provides a further
32 ;; level of organization. You can create as many todo files, and in
33 ;; each as many categories, as you want.
35 ;; With Todo mode you can navigate among the items of a category, and
36 ;; between categories in the same and in different todo files. You
37 ;; can edit todo items, reprioritize them within their category, move
38 ;; them to another category, delete them, or mark items as done and
39 ;; store them separately from the not yet done items in a category.
40 ;; You can add new todo files, edit and delete them. You can add new
41 ;; categories, rename and delete them, move categories to another file
42 ;; and merge the items of two categories. You can also reorder the
43 ;; sequence of categories in a todo file for the purpose of
44 ;; navigation. You can display summary tables of the categories in a
45 ;; file and the types of items they contain. And you can compile
46 ;; lists of existing items from multiple categories in one or more
47 ;; todo files, which are filtered by various criteria.
49 ;; To get started, load this package and type `M-x todo-show'. This
50 ;; will prompt you for the name of the first todo file, its first
51 ;; category and the category's first item, create these and display
52 ;; them in Todo mode. Now you can insert further items into the list
53 ;; (i.e., the category) and assign them priorities by typing `i i'.
55 ;; You will probably find it convenient to give `todo-show' a global
56 ;; key binding in your init file, since it is one of the entry points
57 ;; to Todo mode; a good choice is `C-c t', since `todo-show' is
58 ;; bound to `t' in Todo mode.
60 ;; To see a list of all Todo mode commands and their key bindings,
61 ;; including other entry points, type `C-h m' in Todo mode. Consult
62 ;; the documentation strings of the commands for details of their use.
63 ;; The `todo' customization group and its subgroups list the options
64 ;; you can set to alter the behavior of many commands and various
65 ;; aspects of the display.
67 ;; This package is a new version of Oliver Seidel's todo-mode.el.
68 ;; While it retains the same basic organization and handling of todo
69 ;; lists and the basic UI, it significantly extends these and adds
70 ;; many features. This required also making changes to the internals,
71 ;; including the file format. If you have a todo file in old format,
72 ;; then the first time you invoke `todo-show' (i.e., before you have
73 ;; created any todo file in the current format), it will ask you
74 ;; whether to convert that file and show it. If you choose not to
75 ;; convert the old-style file at this time, you can do so later by
76 ;; calling the command `todo-convert-legacy-files'.
81 ;; For cl-remove-duplicates (in todo-insertion-commands-args) and
85 ;; -----------------------------------------------------------------------------
86 ;;; Setting up todo files, categories, and items
87 ;; -----------------------------------------------------------------------------
89 (defcustom todo-directory (locate-user-emacs-file "todo/")
90 "Directory where user's todo files are saved."
94 (defun todo-files (&optional archives)
95 "Default value of `todo-files-function'.
96 This returns the case-insensitive alphabetically sorted list of
97 file truenames in `todo-directory' with the extension
98 \".todo\". With non-nil ARCHIVES return the list of archive file
99 truenames (those with the extension \".toda\")."
100 (let ((files (if (file-exists-p todo-directory)
101 (mapcar 'file-truename
102 (directory-files todo-directory t
103 (if archives "\.toda$" "\.todo$") t)))))
104 (sort files (lambda (s1 s2) (let ((cis1 (upcase s1))
106 (string< cis1 cis2))))))
108 (defcustom todo-files-function 'todo-files
109 "Function returning the value of the variable `todo-files'.
110 This function should take an optional argument that, if non-nil,
111 makes it return the value of the variable `todo-archives'."
115 (defvar todo-files (funcall todo-files-function)
116 "List of truenames of user's todo files.")
118 (defvar todo-archives (funcall todo-files-function t)
119 "List of truenames of user's todo archives.")
121 (defvar todo-visited nil
122 "List of todo files visited in this session by `todo-show'.
123 Used to determine initial display according to the value of
126 (defvar todo-file-buffers nil
127 "List of file names of live Todo mode buffers.")
129 (defvar todo-global-current-todo-file nil
130 "Variable holding name of current todo file.
131 Used by functions called from outside of Todo mode to visit the
132 current todo file rather than the default todo file (i.e. when
133 users option `todo-show-current-file' is non-nil).")
135 (defvar todo-current-todo-file nil
136 "Variable holding the name of the currently active todo file.")
138 (defvar todo-categories nil
139 "Alist of categories in the current todo file.
140 The elements are cons cells whose car is a category name and
141 whose cdr is a vector of the category's item counts. These are,
142 in order, the numbers of todo items, of todo items included in
143 the Diary, of done items and of archived items.")
145 (defvar todo-category-number 1
146 "Variable holding the number of the current todo category.
147 Todo categories are numbered starting from 1.")
149 (defvar todo-categories-with-marks nil
150 "Alist of categories and number of marked items they contain.")
152 (defconst todo-category-beg "--==-- "
153 "String marking beginning of category (inserted with its name).")
155 (defconst todo-category-done "==--== DONE "
156 "String marking beginning of category's done items.")
158 (defcustom todo-done-separator-string "="
159 "String determining the value of variable `todo-done-separator'.
160 If the string consists of a single character,
161 `todo-done-separator' will be the string made by repeating this
162 character for the width of the window, and the length is
163 automatically recalculated when the window width changes. If the
164 string consists of more (or less) than one character, it will be
165 the value of `todo-done-separator'."
167 :initialize 'custom-initialize-default
168 :set 'todo-reset-done-separator-string
169 :group 'todo-display)
171 (defun todo-done-separator ()
172 "Return string used as value of variable `todo-done-separator'."
173 (let ((sep todo-done-separator-string))
174 (propertize (if (= 1 (length sep))
175 (make-string (window-width) (string-to-char sep))
176 todo-done-separator-string)
177 'face 'todo-done-sep)))
179 (defvar todo-done-separator (todo-done-separator)
180 "String used to visually separate done from not done items.
181 Displayed as an overlay instead of `todo-category-done' when
182 done items are shown. Its value is determined by user option
183 `todo-done-separator-string'.")
185 (defvar todo-show-done-only nil
186 "If non-nil display only done items in current category.
187 Set by the command `todo-toggle-view-done-only' and used by
188 `todo-category-select'.")
190 (defcustom todo-nondiary-marker '("[" "]")
191 "List of strings surrounding item date to block diary inclusion.
192 The first string is inserted before the item date and must be a
193 non-empty string that does not match a diary date in order to
194 have its intended effect. The second string is inserted after
196 :type '(list string string)
198 :initialize 'custom-initialize-default
199 :set 'todo-reset-nondiary-marker)
201 (defconst todo-nondiary-start (nth 0 todo-nondiary-marker)
202 "String inserted before item date to block diary inclusion.")
204 (defconst todo-nondiary-end (nth 1 todo-nondiary-marker)
205 "String inserted after item date matching `todo-nondiary-start'.")
207 (defconst todo-month-name-array
208 (vconcat calendar-month-name-array (vector "*"))
209 "Array of month names, in order.
210 The final element is \"*\", indicating an unspecified month.")
212 (defconst todo-month-abbrev-array
213 (vconcat calendar-month-abbrev-array (vector "*"))
214 "Array of abbreviated month names, in order.
215 The final element is \"*\", indicating an unspecified month.")
217 (defconst todo-date-pattern
218 (let ((dayname (diary-name-pattern calendar-day-name-array nil t)))
219 (concat "\\(?4:\\(?5:" dayname "\\)\\|"
221 (monthname (format "\\(?6:%s\\)" (diary-name-pattern
222 todo-month-name-array
223 todo-month-abbrev-array)))
224 (month "\\(?7:[0-9]+\\|\\*\\)")
225 (day "\\(?8:[0-9]+\\|\\*\\)")
226 (year "-?\\(?9:[0-9]+\\|\\*\\)"))
227 (mapconcat 'eval calendar-date-display-form ""))
229 "Regular expression matching a todo item date header.")
231 ;; By itself this matches anything, because of the `?'; however, it's only
232 ;; used in the context of `todo-date-pattern' (but Emacs Lisp lacks
234 (defconst todo-date-string-start
235 (concat "^\\(" (regexp-quote todo-nondiary-start) "\\|"
236 (regexp-quote diary-nonmarking-symbol) "\\)?")
237 "Regular expression matching part of item header before the date.")
239 (defcustom todo-done-string "DONE "
240 "Identifying string appended to the front of done todo items."
242 :initialize 'custom-initialize-default
243 :set 'todo-reset-done-string
246 (defconst todo-done-string-start
247 (concat "^\\[" (regexp-quote todo-done-string))
248 "Regular expression matching start of done item.")
250 (defconst todo-item-start (concat "\\(" todo-date-string-start "\\|"
251 todo-done-string-start "\\)"
253 "String identifying start of a todo item.")
255 ;; -----------------------------------------------------------------------------
256 ;;; Todo mode display options
257 ;; -----------------------------------------------------------------------------
259 (defcustom todo-prefix ""
260 "String prefixed to todo items for visual distinction."
261 :type '(string :validate
263 (when (string= (widget-value widget) todo-item-mark)
266 "Invalid value: must be distinct from `todo-item-mark'")
268 :initialize 'custom-initialize-default
269 :set 'todo-reset-prefix
270 :group 'todo-display)
272 (defcustom todo-number-prefix t
273 "Non-nil to prefix items with consecutively increasing integers.
274 These reflect the priorities of the items in each category."
276 :initialize 'custom-initialize-default
277 :set 'todo-reset-prefix
278 :group 'todo-display)
280 (defun todo-mode-line-control (cat)
281 "Return a mode line control for todo or archive file buffers.
282 Argument CAT is the name of the current todo category.
283 This function is the value of the user variable
284 `todo-mode-line-function'."
285 (let ((file (todo-short-file-name todo-current-todo-file)))
286 (format "%s category %d: %s" file todo-category-number cat)))
288 (defcustom todo-mode-line-function 'todo-mode-line-control
289 "Function that returns a mode line control for Todo mode buffers.
290 The function expects one argument holding the name of the current
291 todo category. The resulting control becomes the local value of
292 `mode-line-buffer-identification' in each Todo mode buffer."
294 :group 'todo-display)
296 (defcustom todo-highlight-item nil
297 "Non-nil means highlight items at point."
299 :initialize 'custom-initialize-default
300 :set 'todo-reset-highlight-item
301 :group 'todo-display)
303 (defcustom todo-wrap-lines t
304 "Non-nil to activate Visual Line mode and use wrap prefix."
306 :group 'todo-display)
308 (defcustom todo-indent-to-here 3
309 "Number of spaces to indent continuation lines of items.
310 This must be a positive number to ensure such items are fully
311 shown in the Fancy Diary display."
312 :type '(integer :validate
314 (unless (> (widget-value widget) 0)
315 (widget-put widget :error
316 "Invalid value: must be a positive integer")
318 :group 'todo-display)
320 (defun todo-indent ()
321 "Indent from point to `todo-indent-to-here'."
322 (indent-to todo-indent-to-here todo-indent-to-here))
324 (defcustom todo-show-with-done nil
325 "Non-nil to display done items in all categories."
327 :group 'todo-display)
329 ;; -----------------------------------------------------------------------------
331 ;; -----------------------------------------------------------------------------
333 (defface todo-key-prompt
334 '((t (:weight bold)))
335 "Face for making keys in item insertion prompt stand out."
339 ;; '((t :inherit font-lock-warning-face))
343 (:weight bold :foreground "Red1"))
347 (:weight bold :foreground "Pink"))
351 (:weight bold :foreground "Red1"))
355 (:weight bold :foreground "Pink"))
360 (:weight bold :inverse-video t)))
361 "Face for marks on marked items."
364 (defface todo-prefix-string
365 ;; '((t :inherit font-lock-constant-face))
366 '((((class grayscale) (background light))
367 (:foreground "LightGray" :weight bold :underline t))
368 (((class grayscale) (background dark))
369 (:foreground "Gray50" :weight bold :underline t))
370 (((class color) (min-colors 88) (background light)) (:foreground "dark cyan"))
371 (((class color) (min-colors 88) (background dark)) (:foreground "Aquamarine"))
372 (((class color) (min-colors 16) (background light)) (:foreground "CadetBlue"))
373 (((class color) (min-colors 16) (background dark)) (:foreground "Aquamarine"))
374 (((class color) (min-colors 8)) (:foreground "magenta"))
375 (t (:weight bold :underline t)))
376 "Face for todo item prefix or numerical priority string."
379 (defface todo-top-priority
380 ;; bold font-lock-comment-face
381 '((default :weight bold)
382 (((class grayscale) (background light)) :foreground "DimGray" :slant italic)
383 (((class grayscale) (background dark)) :foreground "LightGray" :slant italic)
384 (((class color) (min-colors 88) (background light)) :foreground "Firebrick")
385 (((class color) (min-colors 88) (background dark)) :foreground "chocolate1")
386 (((class color) (min-colors 16) (background light)) :foreground "red")
387 (((class color) (min-colors 16) (background dark)) :foreground "red1")
388 (((class color) (min-colors 8) (background light)) :foreground "red")
389 (((class color) (min-colors 8) (background dark)) :foreground "yellow")
391 "Face for top priority todo item numerical priority string.
392 The item's priority number string has this face if the number is
393 less than or equal the category's top priority setting."
396 (defface todo-nondiary
397 ;; '((t :inherit font-lock-type-face))
398 '((((class grayscale) (background light)) :foreground "Gray90" :weight bold)
399 (((class grayscale) (background dark)) :foreground "DimGray" :weight bold)
400 (((class color) (min-colors 88) (background light)) :foreground "ForestGreen")
401 (((class color) (min-colors 88) (background dark)) :foreground "PaleGreen")
402 (((class color) (min-colors 16) (background light)) :foreground "ForestGreen")
403 (((class color) (min-colors 16) (background dark)) :foreground "PaleGreen")
404 (((class color) (min-colors 8)) :foreground "green")
405 (t :weight bold :underline t))
406 "Face for non-diary markers around todo item date/time header."
410 '((t :inherit diary))
411 "Face for the date string of a todo item."
415 '((t :inherit diary-time))
416 "Face for the time string of a todo item."
419 (defface todo-diary-expired
420 ;; Doesn't contrast enough with todo-date (= diary) face.
421 ;; ;; '((t :inherit warning))
422 ;; '((default :weight bold)
423 ;; (((class color) (min-colors 16)) :foreground "DarkOrange")
424 ;; (((class color)) :foreground "yellow"))
425 ;; bold font-lock-function-name-face
426 '((default :weight bold)
427 (((class color) (min-colors 88) (background light)) :foreground "Blue1")
428 (((class color) (min-colors 88) (background dark)) :foreground "LightSkyBlue")
429 (((class color) (min-colors 16) (background light)) :foreground "Blue")
430 (((class color) (min-colors 16) (background dark)) :foreground "LightSkyBlue")
431 (((class color) (min-colors 8)) :foreground "blue")
432 (t :inverse-video t))
433 "Face for expired dates of diary items."
436 (defface todo-done-sep
437 ;; '((t :inherit font-lock-builtin-face))
438 '((((class grayscale) (background light)) :foreground "LightGray" :weight bold)
439 (((class grayscale) (background dark)) :foreground "DimGray" :weight bold)
440 (((class color) (min-colors 88) (background light)) :foreground "dark slate blue")
441 (((class color) (min-colors 88) (background dark)) :foreground "LightSteelBlue")
442 (((class color) (min-colors 16) (background light)) :foreground "Orchid")
443 (((class color) (min-colors 16) (background dark)) :foreground "LightSteelBlue")
444 (((class color) (min-colors 8)) :foreground "blue" :weight bold)
446 "Face for separator string between done and not done todo items."
450 ;; '((t :inherit font-lock-keyword-face))
451 '((((class grayscale) (background light)) :foreground "LightGray" :weight bold)
452 (((class grayscale) (background dark)) :foreground "DimGray" :weight bold)
453 (((class color) (min-colors 88) (background light)) :foreground "Purple")
454 (((class color) (min-colors 88) (background dark)) :foreground "Cyan1")
455 (((class color) (min-colors 16) (background light)) :foreground "Purple")
456 (((class color) (min-colors 16) (background dark)) :foreground "Cyan")
457 (((class color) (min-colors 8)) :foreground "cyan" :weight bold)
459 "Face for done todo item header string."
462 (defface todo-comment
463 ;; '((t :inherit font-lock-comment-face))
464 '((((class grayscale) (background light))
465 :foreground "DimGray" :weight bold :slant italic)
466 (((class grayscale) (background dark))
467 :foreground "LightGray" :weight bold :slant italic)
468 (((class color) (min-colors 88) (background light))
469 :foreground "Firebrick")
470 (((class color) (min-colors 88) (background dark))
471 :foreground "chocolate1")
472 (((class color) (min-colors 16) (background light))
474 (((class color) (min-colors 16) (background dark))
476 (((class color) (min-colors 8) (background light))
478 (((class color) (min-colors 8) (background dark))
479 :foreground "yellow")
480 (t :weight bold :slant italic))
481 "Face for comments appended to done todo items."
485 ;; '((t :inherit match))
489 (:background "yellow1"))
493 (:background "RoyalBlue3"))
497 (:foreground "black" :background "yellow"))
501 (:foreground "white" :background "blue"))
506 (:background "gray")))
507 "Face for matches found by `todo-search'."
511 ;; '((t :inherit widget-field))
513 (:foreground "black" :background "yellow3"))
514 (((class grayscale color)
516 (:background "gray85"))
517 (((class grayscale color)
519 (:background "dim gray"))
522 "Face for buttons in table of categories."
525 (defface todo-sorted-column
530 (:background "grey85"))
533 (:background "grey85" :foreground "grey10"))
535 (:background "gray")))
536 "Face for sorted column in table of categories."
539 (defface todo-archived-only
540 ;; '((t (:inherit (shadow))))
543 (:foreground "grey50"))
546 (:foreground "grey70"))
548 (:foreground "gray")))
549 "Face for archived-only category names in table of categories."
552 (defface todo-category-string
553 ;; '((t :inherit font-lock-type-face))
554 '((((class grayscale) (background light)) :foreground "Gray90" :weight bold)
555 (((class grayscale) (background dark)) :foreground "DimGray" :weight bold)
556 (((class color) (min-colors 88) (background light)) :foreground "ForestGreen")
557 (((class color) (min-colors 88) (background dark)) :foreground "PaleGreen")
558 (((class color) (min-colors 16) (background light)) :foreground "ForestGreen")
559 (((class color) (min-colors 16) (background dark)) :foreground "PaleGreen")
560 (((class color) (min-colors 8)) :foreground "green")
561 (t :weight bold :underline t))
562 "Face for category-file header in Todo Filtered Items mode."
565 ;; -----------------------------------------------------------------------------
566 ;;; Entering and exiting
567 ;; -----------------------------------------------------------------------------
569 ;; (defcustom todo-visit-files-commands (list 'find-file 'dired-find-file)
570 ;; "List of file finding commands for `todo-display-as-todo-file'.
571 ;; Invoking these commands to visit a todo file or todo archive file
572 ;; calls `todo-show' or `todo-find-archive', so that the file is
573 ;; displayed correctly."
574 ;; :type '(repeat function)
577 (defun todo-short-file-name (file)
578 "Return the short form of todo file FILE's name.
579 This lacks the extension and directory components."
581 (file-name-sans-extension (file-name-nondirectory file))))
583 (defcustom todo-default-todo-file (todo-short-file-name
584 (car (funcall todo-files-function)))
585 "Todo file visited by first session invocation of `todo-show'."
586 :type (when todo-files
587 `(radio ,@(mapcar (lambda (f) (list 'const f))
588 (mapcar 'todo-short-file-name
589 (funcall todo-files-function)))))
592 (defcustom todo-show-current-file t
593 "Non-nil to make `todo-show' visit the current todo file.
594 Otherwise, `todo-show' always visits `todo-default-todo-file'."
596 :initialize 'custom-initialize-default
597 :set 'todo-set-show-current-file
600 (defcustom todo-show-first 'first
601 "What action to take on first use of `todo-show' on a file."
602 :type '(choice (const :tag "Show first category" first)
603 (const :tag "Show table of categories" table)
604 (const :tag "Show top priorities" top)
605 (const :tag "Show diary items" diary)
606 (const :tag "Show regexp items" regexp))
609 (defcustom todo-add-item-if-new-category t
610 "Non-nil to prompt for an item after adding a new category."
614 (defcustom todo-initial-file "Todo"
615 "Default file name offered on adding first todo file."
619 (defcustom todo-initial-category "Todo"
620 "Default category name offered on initializing a new todo file."
624 (defcustom todo-category-completions-files nil
625 "List of files for building `todo-read-category' completions."
626 :type `(set ,@(mapcar (lambda (f) (list 'const f))
627 (mapcar 'todo-short-file-name
628 (funcall todo-files-function))))
631 (defcustom todo-completion-ignore-case nil
632 "Non-nil means case is ignored by `todo-read-*' functions."
637 (defun todo-show (&optional solicit-file interactive)
638 "Visit a todo file and display one of its categories.
640 When invoked in Todo mode, prompt for which todo file to visit.
641 When invoked outside of Todo mode with non-nil prefix argument
642 SOLICIT-FILE prompt for which todo file to visit; otherwise visit
643 `todo-default-todo-file'. Subsequent invocations from outside
644 of Todo mode revisit this file or, with option
645 `todo-show-current-file' non-nil (the default), whichever todo
646 file was last visited.
648 If you call this command before you have created any todo file in
649 the current format, and you have an todo file in old format, it
650 will ask you whether to convert that file and show it.
651 Otherwise, calling this command before any todo file exists
652 prompts for a file name and an initial category (defaulting to
653 `todo-initial-file' and `todo-initial-category'), creates both of
654 these, visits the file and displays the category, and if option
655 `todo-add-item-if-new-category' is non-nil (the default), prompts
658 The first invocation of this command on an existing todo file
659 interacts with the option `todo-show-first': if its value is
660 `first' (the default), show the first category in the file; if
661 its value is `table', show the table of categories in the file;
662 if its value is one of `top', `diary' or `regexp', show the
663 corresponding saved top priorities, diary items, or regexp items
664 file, if any. Subsequent invocations always show the file's
665 current (i.e., last displayed) category.
667 In Todo mode just the category's unfinished todo items are shown
668 by default. The done items are hidden, but typing
669 `\\[todo-toggle-view-done-items]' displays them below the todo
670 items. With non-nil user option `todo-show-with-done' both todo
671 and done items are always shown on visiting a category.
673 Invoking this command in Todo Archive mode visits the
674 corresponding todo file, displaying the corresponding category."
676 (when todo-default-todo-file
677 (todo-check-file (todo-absolute-file-name todo-default-todo-file)))
679 ;; Before initializing the first todo first, check if there is a
680 ;; legacy todo file and if so, offer to convert to the current
681 ;; format and make it the first new todo file.
682 (unless todo-default-todo-file
683 (let ((legacy-todo-file (if (boundp 'todo-file-do)
685 (locate-user-emacs-file "todo-do" ".todo-do"))))
686 (when (and (file-exists-p legacy-todo-file)
687 (y-or-n-p (concat "Do you want to convert a copy of your "
688 "old todo file to the new format? ")))
689 (when (todo-convert-legacy-files)
690 (throw 'shown nil)))))
693 (show-first todo-show-first)
694 (file (cond ((or solicit-file
696 (memq major-mode '(todo-mode
698 todo-filtered-items-mode))))
699 (if (funcall todo-files-function)
700 (todo-read-file-name "Choose a todo file to visit: "
702 (user-error "There are no todo files")))
703 ((and (eq major-mode 'todo-archive-mode)
704 ;; Called noninteractively via todo-quit
705 ;; to jump to corresponding category in
708 (setq cat (todo-current-category))
709 (concat (file-name-sans-extension
710 todo-current-todo-file) ".todo"))
712 (or todo-current-todo-file
713 (and todo-show-current-file
714 todo-global-current-todo-file)
715 (todo-absolute-file-name todo-default-todo-file)
718 (unless todo-default-todo-file
719 ;; We just initialized the first todo file, so make it the default.
720 (setq todo-default-todo-file (todo-short-file-name file)
722 (todo-reevaluate-default-file-defcustom))
723 (unless (member file todo-visited)
724 ;; Can't setq t-c-t-f here, otherwise wrong file shown when
725 ;; todo-show is called from todo-show-categories-table.
726 (let ((todo-current-todo-file file))
727 (cond ((eq todo-show-first 'table)
728 (todo-show-categories-table))
729 ((memq todo-show-first '(top diary regexp))
730 (let* ((shortf (todo-short-file-name file))
731 (fi-file (todo-absolute-file-name
732 shortf todo-show-first)))
733 (when (eq todo-show-first 'regexp)
734 (let ((rxfiles (directory-files todo-directory t
736 (when (and rxfiles (> (length rxfiles) 1))
737 (let ((rxf (mapcar 'todo-short-file-name rxfiles)))
738 (setq fi-file (todo-absolute-file-name
740 "Choose a regexp items file: "
742 (if (file-exists-p fi-file)
746 (set-buffer (find-file-noselect fi-file 'nowarn)))
747 (unless (derived-mode-p 'todo-filtered-items-mode)
748 (todo-filtered-items-mode)))
749 (message "There is no %s file for %s"
750 (cond ((eq todo-show-first 'top)
752 ((eq todo-show-first 'diary)
754 ((eq todo-show-first 'regexp)
757 (setq todo-show-first 'first)))))))
758 (when (or (member file todo-visited)
759 (eq todo-show-first 'first))
760 (unless (todo-check-file file) (throw 'end nil))
761 (set-window-buffer (selected-window)
762 (set-buffer (find-file-noselect file 'nowarn)))
763 (if (equal (file-name-extension (buffer-file-name)) "toda")
764 (unless (derived-mode-p 'todo-archive-mode) (todo-archive-mode))
765 (unless (derived-mode-p 'todo-mode) (todo-mode)))
766 ;; When quitting an archive file, show the corresponding
767 ;; category in the corresponding todo file, if it exists.
768 (when (assoc cat todo-categories)
769 (setq todo-category-number (todo-category-number cat)))
770 ;; If this is a new todo file, add its first category.
771 (when (zerop (buffer-size))
774 (setq todo-category-number
775 (todo-add-category todo-current-todo-file "")
776 add-item todo-add-item-if-new-category
779 ;; If the category was added, save the file now, so we
780 ;; don't risk having an empty todo file, which would
781 ;; signal an error if we tried to visit it later,
782 ;; since doing that looks for category boundaries.
784 ;; If user cancels before adding the category, clean up
785 ;; and exit, so we have a fresh slate the next time.
787 ;; (setq todo-files (funcall todo-files-function))
788 (setq todo-files (delete file todo-files))
790 (setq todo-default-todo-file nil
791 todo-current-todo-file nil)
792 (todo-reevaluate-default-file-defcustom))
795 (save-excursion (todo-category-select))
796 (when add-item (todo-insert-item--basic)))
797 (setq todo-show-first show-first)
798 (add-to-list 'todo-visited file)))))
801 "Save the current todo file."
803 (cond ((eq major-mode 'todo-filtered-items-mode)
804 (todo-check-filtered-items-file)
805 (todo-save-filtered-items-buffer))
809 (defvar todo-descending-counts)
812 "Exit the current Todo-related buffer.
813 Depending on the specific mode, this either kills the buffer or
814 buries it and restores state as needed."
816 (let ((buf (current-buffer)))
817 (cond ((eq major-mode 'todo-categories-mode)
818 ;; Postpone killing buffer till after calling todo-show, to
819 ;; prevent killing todo-mode buffer.
820 (setq todo-descending-counts nil)
821 ;; Ensure todo-show calls todo-show-categories-table only on
822 ;; first invocation per file.
823 (when (eq todo-show-first 'table)
824 (add-to-list 'todo-visited todo-current-todo-file))
827 ((eq major-mode 'todo-filtered-items-mode)
829 (unless (eq major-mode 'todo-mode) (todo-show)))
830 ((eq major-mode 'todo-archive-mode)
831 ;; Have to write a newly created archive to file to avoid
832 ;; subsequent errors.
834 (let ((todo-file (concat todo-directory
835 (todo-short-file-name todo-current-todo-file)
837 (if (todo-check-file todo-file)
839 (message "There is no todo file for this archive")))
840 ;; When todo-check-file runs in todo-show, it kills the
841 ;; buffer if the archive file was deleted externally.
842 (when (buffer-live-p buf) (bury-buffer buf)))
843 ((eq major-mode 'todo-mode)
845 ;; If we just quit archive mode, just burying the buffer
846 ;; in todo-mode would return to archive.
847 (set-window-buffer (selected-window)
848 (set-buffer (other-buffer)))
849 (bury-buffer buf)))))
851 ;; -----------------------------------------------------------------------------
852 ;;; Navigation between and within categories
853 ;; -----------------------------------------------------------------------------
855 (defcustom todo-skip-archived-categories nil
856 "Non-nil to handle categories with only archived items specially.
858 Sequential category navigation using \\[todo-forward-category]
859 or \\[todo-backward-category] skips categories that contain only
860 archived items. Other commands still recognize these categories.
861 In Todo Categories mode (\\[todo-show-categories-table]) these
862 categories shown in `todo-archived-only' face and pressing the
863 category button visits the category in the archive instead of the
866 :group 'todo-display)
868 (defun todo-forward-category (&optional back)
869 "Visit the numerically next category in this todo file.
870 If the current category is the highest numbered, visit the first
871 category. With non-nil argument BACK, visit the numerically
872 previous category (the highest numbered one, if the current
873 category is the first)."
875 (setq todo-category-number
876 (1+ (mod (- todo-category-number (if back 2 0))
877 (length todo-categories))))
878 (when todo-skip-archived-categories
879 (while (and (zerop (todo-get-count 'todo))
880 (zerop (todo-get-count 'done))
881 (not (zerop (todo-get-count 'archived))))
882 (setq todo-category-number
883 (apply (if back '1- '1+) (list todo-category-number)))))
884 (todo-category-select)
885 (goto-char (point-min)))
887 (defun todo-backward-category ()
888 "Visit the numerically previous category in this todo file.
889 If the current category is the highest numbered, visit the first
892 (todo-forward-category t))
894 (defvar todo-categories-buffer)
896 (defun todo-jump-to-category (&optional file where)
897 "Prompt for a category in a todo file and jump to it.
899 With non-nil FILE (interactively a prefix argument), prompt for a
900 specific todo file and choose (with TAB completion) a category
901 in it to jump to; otherwise, choose and jump to any category in
902 either the current todo file or a file in
903 `todo-category-completions-files'.
905 Also accept a non-existing category name and ask whether to add a
906 new category by that name; on confirmation, add it and jump to
907 that category, and if option `todo-add-item-if-new-category' is
908 non-nil (the default), then prompt for the first item.
910 In noninteractive calls non-nil WHERE specifies either the goal
911 category or its file. If its value is `archive', the choice of
912 categories is restricted to the current archive file or the
913 archive you were prompted to choose; this is used by
914 `todo-jump-to-archive-category'. If its value is the name of a
915 category, jump directly to that category; this is used in Todo
918 ;; If invoked outside of Todo mode and there is not yet any Todo
919 ;; file, initialize one.
920 (if (null (funcall todo-files-function))
922 (let* ((archive (eq where 'archive))
923 (cat (unless archive where))
924 (file0 (when cat ; We're in Todo Categories mode.
925 ;; With non-nil `todo-skip-archived-categories'
926 ;; jump to archive file of a category with only
928 (if (and todo-skip-archived-categories
929 (zerop (todo-get-count 'todo cat))
930 (zerop (todo-get-count 'done cat))
931 (not (zerop (todo-get-count 'archived cat))))
932 (concat (file-name-sans-extension
933 todo-current-todo-file) ".toda")
934 ;; Otherwise, jump to current todo file.
935 todo-current-todo-file)))
936 (len (length todo-categories))
937 (cat+file (unless cat
938 (todo-read-category "Jump to category: "
939 (if archive 'archive) file)))
940 (add-item (and todo-add-item-if-new-category
941 (> (length todo-categories) len)))
942 (category (or cat (car cat+file))))
943 (unless cat (setq file0 (cdr cat+file)))
944 (with-current-buffer (find-file-noselect file0 'nowarn)
945 (setq todo-current-todo-file file0)
946 ;; If called from Todo Categories mode, clean up before jumping.
947 (if (string= (buffer-name) todo-categories-buffer)
949 (set-window-buffer (selected-window)
950 (set-buffer (find-buffer-visiting file0)))
951 (unless todo-global-current-todo-file
952 (setq todo-global-current-todo-file todo-current-todo-file))
953 (todo-category-number category)
954 (todo-category-select)
955 (goto-char (point-min))
956 (when add-item (todo-insert-item--basic))))))
958 (defun todo-next-item (&optional count)
959 "Move point down to the beginning of the next item.
960 With positive numerical prefix COUNT, move point COUNT items
963 If the category's done items are hidden, this command also moves
964 point to the empty line below the last todo item from any higher
965 item in the category, i.e., when invoked with or without a prefix
966 argument. If the category's done items are visible, this command
967 called with a prefix argument only moves point to a lower item,
968 e.g., with point on the last todo item and called with prefix 1,
969 it moves point to the first done item; but if called with point
970 on the last todo item without a prefix argument, it moves point
971 the the empty line above the done items separator."
973 ;; It's not worth the trouble to allow prefix arg value < 1, since
974 ;; we have the corresponding command.
975 (cond ((and current-prefix-arg (< count 1))
976 (user-error "The prefix argument must be a positive number"))
978 (todo-forward-item count))
980 (todo-forward-item))))
982 (defun todo-previous-item (&optional count)
983 "Move point up to start of item with next higher priority.
984 With positive numerical prefix COUNT, move point COUNT items
987 If the category's done items are visible, this command called
988 with a prefix argument only moves point to a higher item, e.g.,
989 with point on the first done item and called with prefix 1, it
990 moves to the last todo item; but if called with point on the
991 first done item without a prefix argument, it moves point the the
992 empty line above the done items separator."
994 ;; Avoid moving to bob if on the first item but not at bob.
995 (when (> (line-number-at-pos) 1)
996 ;; It's not worth the trouble to allow prefix arg value < 1, since
997 ;; we have the corresponding command.
998 (cond ((and current-prefix-arg (< count 1))
999 (user-error "The prefix argument must be a positive number"))
1001 (todo-backward-item count))
1003 (todo-backward-item)))))
1005 ;; -----------------------------------------------------------------------------
1006 ;;; Display toggle commands
1007 ;; -----------------------------------------------------------------------------
1009 (defun todo-toggle-prefix-numbers ()
1010 "Hide item numbering if shown, show if hidden."
1014 (goto-char (point-min))
1015 (let* ((ov (todo-get-overlay 'prefix))
1016 (show-done (re-search-forward todo-done-string-start nil t))
1017 (todo-show-with-done show-done)
1018 (todo-number-prefix (not (equal (overlay-get ov 'before-string)
1020 (if (eq major-mode 'todo-filtered-items-mode)
1021 (todo-prefix-overlays)
1022 (todo-category-select))))))
1024 (defun todo-toggle-view-done-items ()
1025 "Show hidden or hide visible done items in current category."
1027 (if (zerop (todo-get-count 'done (todo-current-category)))
1028 (message "There are no done items in this category.")
1029 (let ((opoint (point)))
1030 (goto-char (point-min))
1031 (let* ((shown (re-search-forward todo-done-string-start nil t))
1032 (todo-show-with-done (not shown)))
1033 (todo-category-select)
1035 ;; If start of done items sections is below the bottom of the
1036 ;; window, make it visible.
1039 (goto-char (point-min))
1040 (re-search-forward todo-done-string-start nil t)))
1041 (if (not (pos-visible-in-window-p shown))
1043 (goto-char opoint)))))))
1045 (defun todo-toggle-view-done-only ()
1046 "Switch between displaying only done or only todo items."
1048 (setq todo-show-done-only (not todo-show-done-only))
1049 (todo-category-select))
1051 (defun todo-toggle-item-highlighting ()
1052 "Highlight or unhighlight the todo item the cursor is on."
1054 (eval-and-compile (require 'hl-line))
1055 (when (memq major-mode
1056 '(todo-mode todo-archive-mode todo-filtered-items-mode))
1061 (defun todo-toggle-item-header ()
1062 "Hide or show item date-time headers in the current file.
1063 With done items, this hides only the done date-time string, not
1064 the the original date-time string."
1068 (goto-char (point-min))
1069 (let ((ov (todo-get-overlay 'header)))
1071 (remove-overlays 1 (1+ (buffer-size)) 'todo 'header)
1073 (goto-char (point-min))
1075 (when (re-search-forward
1076 (concat todo-item-start
1077 "\\( " diary-time-regexp "\\)?"
1078 (regexp-quote todo-nondiary-end) "? ")
1080 (setq ov (make-overlay (match-beginning 0) (match-end 0) nil t))
1081 (overlay-put ov 'todo 'header)
1082 (overlay-put ov 'display ""))
1083 (todo-forward-item)))))))
1085 ;; -----------------------------------------------------------------------------
1086 ;;; File and category editing
1087 ;; -----------------------------------------------------------------------------
1089 (defun todo-add-file ()
1090 "Name and initialize a new todo file.
1091 Interactively, prompt for a category and display it, and if
1092 option `todo-add-item-if-new-category' is non-nil (the default),
1093 prompt for the first item.
1094 Noninteractively, return the name of the new file."
1096 (let* ((prompt (concat "Enter name of new todo file "
1097 "(TAB or SPC to see current names): "))
1098 (file (todo-read-file-name prompt)))
1099 ;; Don't accept the name of an existing todo file.
1100 (setq file (todo-absolute-file-name
1101 (todo-validate-name (todo-short-file-name file) 'file)))
1102 (with-current-buffer (get-buffer-create file)
1104 (write-region (point-min) (point-max) file nil 'nomessage nil t)
1106 (setq todo-files (funcall todo-files-function))
1107 (todo-reevaluate-filelist-defcustoms)
1108 (if (called-interactively-p 'any)
1110 (set-window-buffer (selected-window)
1111 (set-buffer (find-file-noselect file)))
1112 (setq todo-current-todo-file file)
1116 (defun todo-rename-file (&optional arg)
1117 "Rename the current todo file.
1118 With prefix ARG, prompt for a todo file and rename it.
1119 If there are corresponding archive or filtered items files,
1120 rename these accordingly. If there are live buffers visiting
1121 these files, also rename them accordingly."
1123 (let* ((oname (or (and arg
1124 (todo-read-file-name "Choose a file to rename: "
1126 (buffer-file-name)))
1127 (soname (todo-short-file-name oname))
1128 (nname (todo-read-file-name "New name for this file: "))
1129 (snname (todo-short-file-name nname))
1130 (files (directory-files todo-directory t
1131 (concat ".*" (regexp-quote soname)
1132 ".*\.tod[aorty]$") t)))
1134 (let* ((sfname (todo-short-file-name f))
1135 (fext (file-name-extension f t))
1136 (fbuf (find-buffer-visiting f))
1137 (fbname (buffer-name fbuf)))
1138 (when (string-match (regexp-quote soname) sfname)
1139 (let* ((snfname (replace-match snname t t sfname))
1140 (nfname (concat todo-directory snfname fext)))
1141 (rename-file f nfname)
1143 (with-current-buffer fbuf
1144 (set-visited-file-name nfname t t)
1145 (cond ((member fext '(".todo" ".toda"))
1146 (setq todo-current-todo-file (buffer-file-name))
1147 (setq mode-line-buffer-identification
1148 (funcall todo-mode-line-function
1149 (todo-current-category))))
1152 (replace-regexp-in-string
1153 (regexp-quote soname) snname fbname))))))))))
1154 (setq todo-files (funcall todo-files-function)
1155 todo-archives (funcall todo-files-function t))
1156 (when (string= todo-default-todo-file soname)
1157 (setq todo-default-todo-file snname))
1158 (when (string= todo-global-current-todo-file oname)
1159 (setq todo-global-current-todo-file nname))
1160 (todo-reevaluate-filelist-defcustoms)))
1162 (defun todo-delete-file ()
1163 "Delete the current todo, archive or filtered items file.
1164 If the todo file has a corresponding archive file, or vice versa,
1165 prompt whether to delete that as well. Also kill the buffers
1166 visiting the deleted files."
1168 (let* ((file1 (buffer-file-name))
1169 (todo (eq major-mode 'todo-mode))
1170 (archive (eq major-mode 'todo-archive-mode))
1171 (filtered (eq major-mode 'todo-filtered-items-mode))
1172 (file1-sn (todo-short-file-name file1))
1173 (file2 (concat todo-directory file1-sn (cond (todo ".toda")
1174 (archive ".todo"))))
1175 (buf1 (current-buffer))
1176 (buf2 (when file2 (find-buffer-visiting file2)))
1177 (prompt1 (concat "Delete " (cond (todo "todo")
1179 (filtered "filtered items"))
1181 (prompt2 (concat "Also delete the corresponding "
1182 (cond (todo "archive") (archive "todo")) " file "
1183 (when buf2 "and kill the buffer visiting it? ")))
1184 (delete1 (yes-or-no-p (format prompt1 file1-sn)))
1185 (delete2 (when (and delete1 (or (file-exists-p file2) buf2))
1186 (yes-or-no-p prompt2))))
1188 (when (file-exists-p file1) (delete-file file1))
1189 (setq todo-visited (delete file1 todo-visited))
1193 (when (file-exists-p file2) (delete-file file2))
1194 (setq todo-visited (delete file2 todo-visited))
1195 (and buf2 (kill-buffer buf2)))
1196 ;; If we deleted an archive but not its todo file, update the
1197 ;; latter's category sexp.
1198 (when (equal (file-name-extension file2) "todo")
1199 (with-current-buffer (or buf2 (find-file-noselect file2))
1203 (goto-char (point-min))
1204 (let ((sexp (read (buffer-substring-no-properties
1205 (line-beginning-position)
1206 (line-end-position))))
1207 (buffer-read-only nil))
1208 (mapc (lambda (x) (aset (cdr x) 3 0)) sexp)
1209 (delete-region (line-beginning-position) (line-end-position))
1210 (prin1 sexp (current-buffer)))))
1211 (todo-set-categories)
1212 (unless buf2 (kill-buffer)))))
1213 (setq todo-files (funcall todo-files-function)
1214 todo-archives (funcall todo-files-function t))
1215 (when (or (string= file1-sn todo-default-todo-file)
1216 (and delete2 (string= file1-sn todo-default-todo-file)))
1217 (setq todo-default-todo-file (todo-short-file-name (car todo-files))))
1218 (when (or (string= file1 todo-global-current-todo-file)
1219 (and delete2 (string= file2 todo-global-current-todo-file)))
1220 (setq todo-global-current-todo-file nil))
1221 (todo-reevaluate-filelist-defcustoms)
1222 (message (concat (cond (todo "Todo") (archive "Archive")) " file \"%s\" "
1225 (cond (todo "archive") (archive "todo"))
1230 (defvar todo-edit-buffer "*Todo Edit*"
1231 "Name of current buffer in Todo Edit mode.")
1233 (defun todo-edit-file ()
1234 "Put current buffer in `todo-edit-mode'.
1235 This makes the entire file visible and the buffer writable and
1236 you can use the self-insertion keys and standard Emacs editing
1237 commands to make changes. To return to Todo mode, type
1238 \\[todo-edit-quit]. This runs a file format check, signaling
1239 an error if the format has become invalid. However, this check
1240 cannot tell if the number of items changed, which could result in
1241 the file containing inconsistent information. For this reason
1242 this command should be used with caution."
1247 (display-warning 'todo (format "\
1249 Type %s to return to Todo mode.
1251 This also runs a file format check and signals an error if
1252 the format has become invalid. However, this check cannot
1253 tell if the number of items or categories changed, which
1254 could result in the file containing inconsistent information.
1255 You can repair this inconsistency by invoking the command
1256 `todo-repair-categories-sexp', but this will revert any
1257 renumbering of the categories you have made, so you will
1258 have to renumber them again (see `(todo-mode) Reordering
1259 Categories')." (substitute-command-keys "\\[todo-edit-quit]"))))
1261 (defun todo-add-category (&optional file cat)
1262 "Add a new category to a todo file.
1264 Called interactively with prefix argument FILE, prompt for a file
1265 and then for a new category to add to that file, otherwise prompt
1266 just for a category to add to the current todo file. After
1267 adding the category, visit it in Todo mode and if option
1268 `todo-add-item-if-new-category' is non-nil (the default), prompt
1271 Non-interactively, add category CAT to file FILE; if FILE is nil,
1272 add CAT to the current todo file. After adding the category,
1273 return the new category number."
1276 ;; If cat is passed from caller, don't prompt, unless it is "",
1277 ;; which means the file was just added and has no category yet.
1278 (if (and cat (> (length cat) 0))
1279 (setq file0 (or (and (stringp file) file)
1280 todo-current-todo-file))
1281 (setq catfil (todo-read-category "Enter a new category name: "
1282 'add (when (called-interactively-p 'any)
1285 file0 (if (called-interactively-p 'any)
1289 (let ((counts (make-vector 4 0)) ; [todo diary done archived]
1290 (num (1+ (length todo-categories)))
1291 (buffer-read-only nil))
1292 (setq todo-current-todo-file file0)
1293 (setq todo-categories (append todo-categories
1294 (list (cons cat counts))))
1296 (goto-char (point-max))
1297 (save-excursion ; Save point for todo-category-select.
1298 (insert todo-category-beg cat "\n\n" todo-category-done "\n"))
1299 (todo-update-categories-sexp)
1300 ;; If invoked by user, display the newly added category, if
1301 ;; called programmatically return the category number to the
1303 (if (called-interactively-p 'any)
1305 (setq todo-category-number num)
1306 (todo-category-select)
1307 (when todo-add-item-if-new-category
1308 (todo-insert-item--basic)))
1311 (defun todo-rename-category ()
1312 "Rename current todo category.
1313 If this file has an archive containing this category, rename the
1314 category there as well."
1316 (let* ((cat (todo-current-category))
1317 (new (read-from-minibuffer
1318 (format "Rename category \"%s\" to: " cat))))
1319 (setq new (todo-validate-name new 'category))
1320 (let* ((ofile todo-current-todo-file)
1321 (archive (concat (file-name-sans-extension ofile) ".toda"))
1322 (buffers (append (list ofile)
1323 (unless (zerop (todo-get-count 'archived cat))
1325 (dolist (buf buffers)
1326 (with-current-buffer (find-file-noselect buf)
1327 (let (buffer-read-only)
1328 (setq todo-categories (todo-set-categories))
1331 (setcar (assoc cat todo-categories) new)
1333 (goto-char (point-min))
1334 (todo-update-categories-sexp)
1335 (re-search-forward (concat (regexp-quote todo-category-beg)
1336 "\\(" (regexp-quote cat) "\\)\n")
1338 (replace-match new t t nil 1)))))))
1339 (force-mode-line-update))
1340 (save-excursion (todo-category-select)))
1342 (defun todo-delete-category (&optional arg)
1343 "Delete current todo category provided it contains no items.
1344 With prefix ARG delete the category even if it does contain
1345 todo or done items."
1347 (let* ((file todo-current-todo-file)
1348 (cat (todo-current-category))
1349 (todo (todo-get-count 'todo cat))
1350 (done (todo-get-count 'done cat))
1351 (archived (todo-get-count 'archived cat)))
1353 (or (> todo 0) (> done 0)))
1354 (message "%s" (substitute-command-keys
1355 (concat "To delete a non-empty category, "
1356 "type C-u \\[todo-delete-category].")))
1357 (when (cond ((= (length todo-categories) 1)
1359 (concat "This is the only category in this file; "
1360 "deleting it will also delete the file.\n"
1361 "Do you want to proceed? ")))
1363 (todo-y-or-n-p (concat "This category has archived items; "
1364 "the archived category will remain\n"
1365 "after deleting the todo category. "
1366 "Do you still want to delete it\n"
1367 "(see `todo-skip-archived-categories' "
1368 "for another option)? ")))
1370 (todo-y-or-n-p (concat "Permanently remove category \"" cat
1371 "\"" (and arg " and all its entries")
1374 (let ((buffer-read-only)
1375 (beg (re-search-backward
1376 (concat "^" (regexp-quote (concat todo-category-beg cat))
1378 (end (if (re-search-forward
1379 (concat "\n\\(" (regexp-quote todo-category-beg)
1383 (remove-overlays beg end)
1384 (delete-region beg end)
1385 (if (= (length todo-categories) 1)
1386 ;; If deleted category was the only one, delete the file.
1388 (todo-reevaluate-filelist-defcustoms)
1389 ;; Skip confirming killing the archive buffer if it has been
1390 ;; modified and not saved.
1391 (set-buffer-modified-p nil)
1394 (message "Deleted todo file %s." file))
1395 (setq todo-categories (delete (assoc cat todo-categories)
1397 (todo-update-categories-sexp)
1398 (setq todo-category-number
1399 (1+ (mod todo-category-number (length todo-categories))))
1400 (todo-category-select)
1401 (goto-char (point-min))
1402 (message "Deleted category %s." cat)))))))
1404 (defun todo-move-category ()
1405 "Move current category to a different todo file.
1406 If the todo file chosen does not exist, it is created.
1407 If the current category has archived items, also move those to
1408 the archive of the file moved to, creating it if it does not exist."
1410 (when (or (> (length todo-categories) 1)
1411 (todo-y-or-n-p (concat "This is the only category in this file; "
1412 "moving it will also delete the file.\n"
1413 "Do you want to proceed? ")))
1414 (let* ((ofile todo-current-todo-file)
1415 (cat (todo-current-category))
1416 (nfile (todo-read-file-name "Todo file to move this category to: "))
1417 (archive (concat (file-name-sans-extension ofile) ".toda"))
1418 (buffers (append (list ofile)
1419 (unless (zerop (todo-get-count 'archived cat))
1422 (while (equal nfile (file-truename ofile))
1423 (setq nfile (todo-read-file-name
1424 "Choose a file distinct from this file: ")))
1425 (unless (member nfile todo-files)
1426 (with-current-buffer (get-buffer-create nfile)
1428 (write-region (point-min) (point-max) nfile nil 'nomessage nil t)
1429 (kill-buffer nfile))
1430 (setq todo-files (funcall todo-files-function))
1431 (todo-reevaluate-filelist-defcustoms))
1432 (dolist (buf buffers)
1433 (with-current-buffer (find-file-noselect buf)
1435 (goto-char (point-max))
1436 (let* ((beg (re-search-backward
1438 (regexp-quote (concat todo-category-beg cat))
1441 (end (if (re-search-forward
1442 (concat "^" (regexp-quote todo-category-beg))
1446 (content (buffer-substring-no-properties beg end))
1447 (counts (cdr (assoc cat todo-categories)))
1449 ;; Move the category to the new file. Also update or create
1450 ;; archive file if necessary.
1451 (with-current-buffer
1453 ;; Regenerate todo-archives in case there
1454 ;; is a newly created archive.
1455 (if (member buf (funcall todo-files-function t))
1456 (concat (file-name-sans-extension nfile) ".toda")
1458 (if (equal (file-name-extension (buffer-file-name)) "toda")
1459 (unless (derived-mode-p 'todo-archive-mode)
1460 (todo-archive-mode))
1461 (unless (derived-mode-p 'todo-mode) (todo-mode)))
1462 (let* ((nfile-short (todo-short-file-name nfile))
1464 (format "Todo file \"%s\" already has "
1466 (format "the category \"%s\";\n" cat)
1467 "enter a new category name: "))
1470 (goto-char (point-max))
1472 ;; If the file moved to has a category with the same
1473 ;; name, rename the moved category.
1474 (when (assoc cat todo-categories)
1475 (unless (member (file-truename (buffer-file-name))
1476 (funcall todo-files-function t))
1477 (setq new (read-from-minibuffer prompt))
1478 (setq new (todo-validate-name new 'category))))
1479 ;; Replace old with new name in todo and archive files.
1481 (goto-char (point-max))
1483 (concat "^" (regexp-quote todo-category-beg)
1484 "\\(" (regexp-quote cat) "\\)$") nil t)
1485 (replace-match new nil nil nil 1)))
1486 (setq todo-categories
1487 (append todo-categories (list (cons (or new cat) counts))))
1488 (todo-update-categories-sexp)
1489 ;; If archive was just created, save it to avoid "File
1490 ;; <xyz> no longer exists!" message on invoking
1491 ;; `todo-view-archived-items'.
1492 (unless (file-exists-p (buffer-file-name))
1494 (todo-category-number (or new cat))
1495 (todo-category-select))
1496 ;; Delete the category from the old file, and if that was the
1497 ;; last category, delete the file. Also handle archive file
1499 (remove-overlays beg end)
1500 (delete-region beg end)
1501 (goto-char (point-min))
1502 ;; Put point after todo-categories sexp.
1504 (if (eobp) ; Aside from sexp, file is empty.
1506 ;; Skip confirming killing the archive buffer.
1507 (set-buffer-modified-p nil)
1508 (delete-file todo-current-todo-file)
1510 (when (member todo-current-todo-file todo-files)
1511 (todo-reevaluate-filelist-defcustoms)))
1512 (setq todo-categories (delete (assoc cat todo-categories)
1514 (todo-update-categories-sexp)
1515 (when (> todo-category-number (length todo-categories))
1516 (setq todo-category-number 1))
1517 (todo-category-select)))))
1518 (set-window-buffer (selected-window)
1519 (set-buffer (find-file-noselect nfile)))
1520 (todo-category-number (or new cat))
1521 (todo-category-select))))
1523 (defun todo-merge-category (&optional file)
1524 "Merge current category into another existing category.
1526 With prefix argument FILE, prompt for a specific todo file and
1527 choose (with TAB completion) a category in it to merge into;
1528 otherwise, choose and merge into a category in either the
1529 current todo file or a file in `todo-category-completions-files'.
1531 After merging, the source category's todo and done items are
1532 appended to the chosen goal category's todo and done items,
1533 respectively. The goal category becomes the current category,
1534 and the source category is deleted.
1536 If both the source and goal categories also have archived items,
1537 they are also merged. If only the source category has archived
1538 items, the goal category is added as a new category to the
1539 archive file and the source category is deleted."
1541 (let* ((tfile todo-current-todo-file)
1542 (cat (todo-current-category))
1543 (cat+file (todo-read-category "Merge into category: " 'todo file))
1544 (goal (car cat+file))
1545 (gfile (cdr cat+file))
1546 (tarchive (concat (file-name-sans-extension tfile) ".toda"))
1547 (garchive (concat (file-name-sans-extension gfile) ".toda"))
1548 (archived-count (todo-get-count 'archived))
1550 (with-current-buffer (get-buffer (find-file-noselect tfile))
1552 (let* ((buffer-read-only nil)
1555 (concat "^" (regexp-quote todo-category-beg)) nil t)
1557 (tbeg (progn (forward-line) (point-marker)))
1560 (concat "^" (regexp-quote todo-category-done)) nil t)
1561 (forward-line) (point-marker)))
1562 ;; Omit empty line between todo and done items.
1563 (tend (progn (forward-line -2) (point-marker)))
1565 (if (re-search-forward
1566 (concat "^" (regexp-quote todo-category-beg)) nil t)
1568 (goto-char (match-beginning 0))
1570 (point-max-marker))))
1571 (todo (buffer-substring-no-properties tbeg tend))
1572 (done (buffer-substring-no-properties dbeg cend))
1573 (todo-count (todo-get-count 'todo cat))
1574 (done-count (todo-get-count 'done cat)))
1575 ;; Merge into goal todo category.
1576 (with-current-buffer (get-buffer (find-file-noselect gfile))
1577 (unless (derived-mode-p 'todo-mode) (todo-mode))
1579 (goto-char (point-min))
1580 (let ((buffer-read-only nil))
1581 ;; Merge any todo items.
1582 (unless (zerop (length todo))
1584 (concat "^" (regexp-quote (concat todo-category-beg goal)) "$")
1587 (concat "^" (regexp-quote todo-category-done)) nil t)
1589 (setq here (point-marker))
1591 (todo-update-count 'todo todo-count goal))
1592 ;; Merge any done items.
1593 (unless (zerop (length done))
1594 (goto-char (if (re-search-forward
1595 (concat "^" (regexp-quote todo-category-beg))
1599 (when (zerop (length todo)) (setq here (point-marker)))
1601 (todo-update-count 'done done-count goal)))
1602 (todo-update-categories-sexp))
1603 ;; Update and clean up source todo file.
1604 (remove-overlays cbeg cend)
1605 (delete-region cbeg cend)
1606 (setq todo-categories (delete (assoc cat todo-categories)
1608 (todo-update-categories-sexp)
1609 (when (> todo-category-number (length todo-categories))
1610 (setq todo-category-number 1))
1611 (todo-category-select)
1612 (mapc (lambda (m) (set-marker m nil))
1613 (list cbeg tbeg dbeg tend cend))))
1614 (when (> archived-count 0)
1615 (with-current-buffer (get-buffer (find-file-noselect tarchive))
1617 (goto-char (point-min))
1618 (let* ((buffer-read-only nil)
1620 (when (re-search-forward
1621 (concat "^" (regexp-quote
1622 (concat todo-category-beg cat)) "$")
1624 (goto-char (match-beginning 0))
1626 (cend (if (re-search-forward
1627 (concat "^" (regexp-quote todo-category-beg)) nil t)
1633 (buffer-substring-no-properties (point) cend))))
1634 ;; Merge into goal archive category, if it exists, else create it.
1635 (with-current-buffer (get-buffer (find-file-noselect garchive))
1636 (let ((gbeg (when (re-search-forward
1637 (concat "^" (regexp-quote
1638 (concat todo-category-beg goal))
1641 (goto-char (match-beginning 0))
1643 (goto-char (if (and gbeg
1645 (concat "^" (regexp-quote todo-category-beg))
1649 (unless gbeg (todo-add-category nil goal))
1651 (todo-update-categories-sexp)))
1652 ;; Update and clean up source archive file.
1653 (remove-overlays cbeg cend)
1654 (delete-region cbeg cend)
1655 (setq todo-categories (todo-make-categories-list t))
1656 (todo-update-categories-sexp))))
1657 ;; Update goal todo file for merged archived items and display it.
1658 (set-window-buffer (selected-window) (set-buffer (get-file-buffer gfile)))
1659 (unless (zerop archived-count)
1660 (todo-update-count 'archived archived-count goal)
1661 (todo-update-categories-sexp))
1662 (todo-category-number goal)
1663 ;; If there are only merged done items, show them.
1664 (let ((todo-show-with-done (zerop (todo-get-count 'todo goal))))
1665 (todo-category-select)
1666 ;; Put point on the first merged item.
1668 (set-marker here nil)))
1670 ;; -----------------------------------------------------------------------------
1672 ;; -----------------------------------------------------------------------------
1674 (defcustom todo-include-in-diary nil
1675 "Non-nil to allow new todo items to be included in the diary."
1679 (defcustom todo-diary-nonmarking nil
1680 "Non-nil to insert new todo diary items as nonmarking by default.
1681 This appends `diary-nonmarking-symbol' to the front of an item on
1682 insertion provided it doesn't begin with `todo-nondiary-marker'."
1686 (defcustom todo-always-add-time-string nil
1687 "Non-nil adds current time to a new item's date header by default.
1688 When the todo insertion commands have a non-nil \"maybe-notime\"
1689 argument, this reverses the effect of
1690 `todo-always-add-time-string': if t, these commands omit the
1691 current time, if nil, they include it."
1695 (defcustom todo-use-only-highlighted-region t
1696 "Non-nil to enable inserting only highlighted region as new item."
1700 (defcustom todo-default-priority 'first
1701 "Default priority of new and moved items."
1702 :type '(choice (const :tag "Highest priority" first)
1703 (const :tag "Lowest priority" last))
1706 (defcustom todo-item-mark "*"
1707 "String used to mark items.
1708 To ensure item marking works, change the value of this option
1709 only when no items are marked."
1710 :type '(string :validate
1712 (when (string= (widget-value widget) todo-prefix)
1715 "Invalid value: must be distinct from `todo-prefix'")
1717 :set (lambda (symbol value)
1718 (custom-set-default symbol (propertize value 'face 'todo-mark)))
1721 (defcustom todo-comment-string "COMMENT"
1722 "String inserted before optional comment appended to done item."
1724 :initialize 'custom-initialize-default
1725 :set 'todo-reset-comment-string
1728 (defcustom todo-undo-item-omit-comment 'ask
1729 "Whether to omit done item comment on undoing the item.
1730 Nil means never omit the comment, t means always omit it, `ask'
1731 means prompt user and omit comment only on confirmation."
1732 :type '(choice (const :tag "Never" nil)
1733 (const :tag "Always" t)
1734 (const :tag "Ask" ask))
1737 (defun todo-toggle-mark-item (&optional n)
1738 "Mark item with `todo-item-mark' if unmarked, otherwise unmark it.
1739 With a positive numerical prefix argument N, change the
1740 marking of the next N items."
1742 (when (todo-item-string)
1743 (unless (> n 1) (setq n 1))
1745 (let* ((cat (todo-current-category))
1746 (marks (assoc cat todo-categories-with-marks))
1748 (unless (looking-at todo-item-start)
1750 (todo-get-overlay 'prefix)))
1751 (pref (overlay-get ov 'before-string)))
1752 (if (todo-marked-item-p)
1754 (overlay-put ov 'before-string (substring pref 1))
1755 (if (= (cdr marks) 1) ; Deleted last mark in this category.
1756 (setq todo-categories-with-marks
1757 (assq-delete-all cat todo-categories-with-marks))
1758 (setcdr marks (1- (cdr marks)))))
1759 (overlay-put ov 'before-string (concat todo-item-mark pref))
1761 (setcdr marks (1+ (cdr marks)))
1762 (push (cons cat 1) todo-categories-with-marks))))
1763 (todo-forward-item))))
1765 (defun todo-mark-category ()
1766 "Mark all visible items in this category with `todo-item-mark'."
1768 (let* ((cat (todo-current-category))
1769 (marks (assoc cat todo-categories-with-marks)))
1771 (goto-char (point-min))
1773 (let* ((ov (todo-get-overlay 'prefix))
1774 (pref (overlay-get ov 'before-string)))
1775 (unless (todo-marked-item-p)
1776 (overlay-put ov 'before-string (concat todo-item-mark pref))
1778 (setcdr marks (1+ (cdr marks)))
1779 (push (cons cat 1) todo-categories-with-marks))))
1780 (todo-forward-item)))))
1782 (defun todo-unmark-category ()
1783 "Remove `todo-item-mark' from all visible items in this category."
1785 (let* ((cat (todo-current-category))
1786 (marks (assoc cat todo-categories-with-marks)))
1788 (goto-char (point-min))
1790 (let* ((ov (todo-get-overlay 'prefix))
1791 ;; No overlay on empty line between todo and done items.
1792 (pref (when ov (overlay-get ov 'before-string))))
1793 (when (todo-marked-item-p)
1794 (overlay-put ov 'before-string (substring pref 1)))
1795 (todo-forward-item))))
1796 (setq todo-categories-with-marks
1797 (delq marks todo-categories-with-marks))))
1799 (defvar todo-date-from-calendar nil
1800 "Helper variable for setting item date from the Emacs Calendar.")
1802 (defvar todo-insert-item--keys-so-far)
1803 (defvar todo-insert-item--parameters)
1805 (defun todo-insert-item (&optional arg)
1806 "Choose an item insertion operation and carry it out.
1807 This inserts a new todo item into a category.
1809 With no prefix argument ARG, add the item to the current
1810 category; with one prefix argument (`C-u'), prompt for a category
1811 from the current todo file; with two prefix arguments (`C-u
1812 C-u'), first prompt for a todo file, then a category in that
1813 file. If a non-existing category is entered, ask whether to add
1814 it to the todo file; if answered affirmatively, add the category
1815 and insert the item there.
1817 There are a number of item insertion parameters which can be
1818 combined by entering specific keys to produce different insertion
1819 commands. After entering each key, a message shows which have
1820 already been entered and which remain available. See
1821 `(todo-mode) Inserting New Items' for details of the parameters,
1822 their associated keys and their effects."
1824 (setq todo-insert-item--keys-so-far "i")
1825 (todo-insert-item--next-param nil (list arg) todo-insert-item--parameters))
1827 (defun todo-insert-item--basic (&optional arg diary-type date-type time where)
1828 "Function implementing the core of `todo-insert-item'."
1829 ;; If invoked outside of Todo mode and there is not yet any Todo
1830 ;; file, initialize one.
1831 (if (null (funcall todo-files-function))
1833 (let ((copy (eq where 'copy))
1834 (region (eq where 'region))
1835 (here (eq where 'here))
1839 ((not (eq major-mode 'todo-mode))
1840 (user-error "You must be in Todo mode to copy a todo item"))
1842 (user-error "You cannot copy a done item as a new todo item"))
1844 (user-error "Point must be on a todo item to copy it")))
1845 (setq diary-item (todo-diary-item-p)))
1847 (let (use-empty-active-region)
1848 (unless (and todo-use-only-highlighted-region (use-region-p))
1849 (user-error "There is no active region"))))
1850 (let* ((obuf (current-buffer))
1851 (ocat (todo-current-category))
1853 (todo-mm (eq major-mode 'todo-mode))
1854 (cat+file (cond ((equal arg '(4))
1855 (todo-read-category "Insert in category: "))
1857 (todo-read-category "Insert in category: "
1860 (cons (todo-current-category)
1861 (or todo-current-todo-file
1862 (and todo-show-current-file
1863 todo-global-current-todo-file)
1864 (todo-absolute-file-name
1865 todo-default-todo-file))))))
1866 (cat (car cat+file))
1867 (file (cdr cat+file))
1868 (new-item (cond (copy (todo-item-string))
1869 (region (buffer-substring-no-properties
1870 (region-beginning) (region-end)))
1871 (t (read-from-minibuffer "Todo item: "))))
1873 ((eq date-type 'date)
1875 ((eq date-type 'dayname)
1876 (todo-read-dayname))
1877 ((eq date-type 'calendar)
1878 (setq todo-date-from-calendar t)
1879 (or (todo-set-date-from-calendar)
1880 ;; If user exits Calendar before choosing
1881 ;; a date, cancel item insertion.
1883 ((and (stringp date-type)
1884 (string-match todo-date-pattern date-type))
1885 (setq todo-date-from-calendar date-type)
1886 (todo-set-date-from-calendar))
1888 (calendar-date-string
1889 (calendar-current-date) t t))))
1890 (time-string (or (and time (todo-read-time))
1891 (and todo-always-add-time-string
1892 (substring (current-time-string) 11 16)))))
1893 (setq todo-date-from-calendar nil)
1894 (find-file-noselect file 'nowarn)
1895 (set-window-buffer (selected-window)
1896 (set-buffer (find-buffer-visiting file)))
1897 ;; If this command was invoked outside of a Todo mode buffer,
1898 ;; the call to todo-current-category above returned nil. If
1899 ;; we just entered Todo mode now, then cat was set to the
1900 ;; file's first category, but if todo-mode was already
1901 ;; enabled, cat did not get set, so we have to do that.
1903 (setq cat (todo-current-category)))
1904 (setq todo-current-todo-file file)
1905 (unless todo-global-current-todo-file
1906 (setq todo-global-current-todo-file todo-current-todo-file))
1907 (let ((buffer-read-only nil)
1908 (called-from-outside (not (and todo-mm (equal cat ocat))))
1909 done-only item-added)
1912 ;; Add date, time and diary marking as required.
1913 (concat (if (not (and diary-type
1914 (not todo-include-in-diary)))
1916 (when (and (eq diary-type 'nonmarking)
1917 (not todo-diary-nonmarking))
1918 diary-nonmarking-symbol))
1919 date-string (when (and time-string ; Can be empty.
1922 (concat " " time-string))
1923 (when (not (and diary-type
1924 (not todo-include-in-diary)))
1927 ;; Indent newlines inserted by C-q C-j if nonspace char follows.
1928 (setq new-item (replace-regexp-in-string "\\(\n\\)[^[:blank:]]"
1929 "\n\t" new-item nil nil 1)))
1932 ;; Make sure the correct category is selected. There
1933 ;; are two cases: (i) we just visited the file, so no
1934 ;; category is selected yet, or (ii) we invoked
1935 ;; insertion "here" from outside the category we want
1936 ;; to insert in (with priority insertion, category
1937 ;; selection is done by todo-set-item-priority).
1938 (when (or (= (- (point-max) (point-min)) (buffer-size))
1939 (and here called-from-outside))
1940 (todo-category-number cat)
1941 (todo-category-select))
1942 ;; If only done items are displayed in category,
1943 ;; toggle to todo items before inserting new item.
1944 (when (save-excursion
1945 (goto-char (point-min))
1946 (looking-at todo-done-string-start))
1948 (todo-toggle-view-done-only))
1951 ;; If command was invoked with point in done
1952 ;; items section or outside of the current
1953 ;; category, can't insert "here", so to be
1954 ;; useful give new item top priority.
1955 (when (or (todo-done-item-section-p)
1958 (goto-char (point-min)))
1959 (todo-insert-with-overlays new-item))
1960 (todo-set-item-priority new-item cat t))
1961 (setq item-added t))
1962 ;; If user cancels before setting priority, restore
1967 (unless (equal cat ocat)
1968 (todo-category-number ocat)
1969 (todo-category-select))
1970 (and done-only (todo-toggle-view-done-only)))
1971 (set-window-buffer (selected-window) (set-buffer obuf)))
1973 ;; If the todo items section is not visible when the
1974 ;; insertion command is called (either because only done
1975 ;; items were shown or because the category was not in the
1976 ;; current buffer), then if the item is inserted at the
1977 ;; end of the category, point is at eob and eob at
1978 ;; window-start, so that higher priority todo items are
1979 ;; out of view. So we recenter to make sure the todo
1980 ;; items are displayed in the window.
1981 (when item-added (recenter)))
1982 (todo-update-count 'todo 1)
1983 (when (or diary-item diary-type todo-include-in-diary)
1984 (todo-update-count 'diary 1))
1985 (todo-update-categories-sexp))))))
1987 (defun todo-set-date-from-calendar ()
1988 "Return string of date chosen from Calendar."
1989 (cond ((and (stringp todo-date-from-calendar)
1990 (string-match todo-date-pattern todo-date-from-calendar))
1991 todo-date-from-calendar)
1992 (todo-date-from-calendar
1993 (let (calendar-view-diary-initially-flag)
1994 (calendar)) ; *Calendar* is now current buffer.
1995 (define-key calendar-mode-map [remap newline] 'exit-recursive-edit)
1996 ;; If user exits Calendar before choosing a date, clean up properly.
1997 (define-key calendar-mode-map
1998 [remap calendar-exit] (lambda ()
2002 (exit-recursive-edit))))
2003 (message "Put cursor on a date and type <return> to set it.")
2006 (when (equal (buffer-name) calendar-buffer)
2007 (setq todo-date-from-calendar
2008 (calendar-date-string (calendar-cursor-to-date t) t t))
2010 todo-date-from-calendar)
2011 (define-key calendar-mode-map [remap newline] nil)
2012 (define-key calendar-mode-map [remap calendar-exit] nil)
2013 (unless (zerop (recursion-depth)) (exit-recursive-edit))
2014 (when (stringp todo-date-from-calendar)
2015 todo-date-from-calendar)))))
2017 (defun todo-insert-item-from-calendar (&optional arg)
2018 "Prompt for and insert a new item with date selected from calendar.
2019 Invoked without prefix argument ARG, insert the item into the
2020 current category, without one prefix argument, prompt for the
2021 category from the current todo file or from one listed in
2022 `todo-category-completions-files'; with two prefix arguments,
2023 prompt for a todo file and then for a category in it."
2025 (setq todo-date-from-calendar
2026 (calendar-date-string (calendar-cursor-to-date t) t t))
2028 (todo-insert-item--basic arg nil todo-date-from-calendar))
2030 (define-key calendar-mode-map "it" 'todo-insert-item-from-calendar)
2032 (defun todo-delete-item ()
2033 "Delete at least one item in this category.
2034 If there are marked items, delete all of these; otherwise, delete
2039 (let* ((cat (todo-current-category))
2040 (marked (assoc cat todo-categories-with-marks))
2041 (item (unless marked (todo-item-string)))
2044 "Permanently delete all marked items? ")
2046 (setq ov (make-overlay
2047 (save-excursion (todo-item-start))
2048 (save-excursion (todo-item-end))))
2049 (overlay-put ov 'face 'todo-search)
2050 (todo-y-or-n-p "Permanently delete this item? "))))
2053 (and marked (goto-char (point-min)))
2056 (if (or (and marked (todo-marked-item-p)) item)
2058 (if (todo-done-item-p)
2059 (todo-update-count 'done -1)
2060 (todo-update-count 'todo -1 cat)
2061 (and (todo-diary-item-p)
2062 (todo-update-count 'diary -1)))
2063 (if ov (delete-overlay ov))
2065 ;; Don't leave point below last item.
2066 (and item (bolp) (eolp) (< (point-min) (point-max))
2067 (todo-backward-item))
2069 (throw 'done (setq item nil))))
2070 (todo-forward-item))))
2072 (setq todo-categories-with-marks
2073 (assq-delete-all cat todo-categories-with-marks)))
2074 (todo-update-categories-sexp)
2075 (todo-prefix-overlays)))
2076 (if ov (delete-overlay ov)))))
2078 (defvar todo-edit-item--param-key-alist)
2079 (defvar todo-edit-done-item--param-key-alist)
2081 (defun todo-edit-item (&optional arg)
2082 "Choose an editing operation for the current item and carry it out."
2084 (cond ((todo-done-item-p)
2085 (todo-edit-item--next-key todo-edit-done-item--param-key-alist))
2087 (todo-edit-item--next-key todo-edit-item--param-key-alist arg))))
2089 (defun todo-edit-item--text (&optional arg)
2090 "Function providing the text editing facilities of `todo-edit-item'."
2091 (let* ((opoint (point))
2092 (start (todo-item-start))
2093 (end (save-excursion (todo-item-end)))
2096 (concat todo-date-string-start todo-date-pattern
2097 "\\( " diary-time-regexp "\\)?"
2098 (regexp-quote todo-nondiary-end) "?")
2099 (line-end-position) t)
2100 (1+ (- (point) start))))
2101 (include-header (eq arg 'include-header))
2102 (comment-edit (eq arg 'comment-edit))
2103 (comment-delete (eq arg 'comment-delete))
2104 (header-string (substring (todo-item-string) 0 item-beg))
2105 (item (if (or include-header comment-edit comment-delete)
2107 (substring (todo-item-string) item-beg)))
2108 (multiline (> (length (split-string item "\n")) 1))
2109 (comment (save-excursion
2112 (concat " \\[" (regexp-quote todo-comment-string)
2113 ": \\([^]]+\\)\\]") end t)))
2114 (prompt (if comment "Edit comment: " "Enter a comment: "))
2115 (buffer-read-only nil))
2117 ((or comment-edit comment-delete)
2120 (if (re-search-forward (concat " \\[" (regexp-quote todo-comment-string)
2121 ": \\([^]]+\\)\\]") end t)
2123 (when (todo-y-or-n-p "Delete comment? ")
2124 (delete-region (match-beginning 0) (match-end 0)))
2125 (replace-match (read-string prompt (cons (match-string 1) 1))
2128 (user-error "There is no comment to delete")
2129 (insert " [" todo-comment-string ": "
2130 (prog1 (read-string prompt)
2131 ;; If user moved point during editing,
2132 ;; make sure it moves back.
2136 ((or multiline (eq arg 'multiline))
2137 (let ((buf todo-edit-buffer))
2138 (set-window-buffer (selected-window)
2139 (set-buffer (make-indirect-buffer (buffer-name) buf)))
2140 (narrow-to-region (todo-item-start) (todo-item-end))
2142 (message "%s" (substitute-command-keys
2143 (concat "Type \\[todo-edit-quit] "
2144 "to return to Todo mode.\n")))))
2146 (let ((new (concat (if include-header "" header-string)
2147 (read-string "Edit: " (if include-header
2148 (cons item item-beg)
2150 (when include-header
2151 (while (not (string-match (concat todo-date-string-start
2152 todo-date-pattern) new))
2153 (setq new (read-from-minibuffer
2154 "Item must start with a date: " new))))
2155 ;; Ensure lines following hard newlines are indented.
2156 (setq new (replace-regexp-in-string "\\(\n\\)[^[:blank:]]"
2157 "\n\t" new nil nil 1))
2158 ;; If user moved point during editing, make sure it moves back.
2161 (todo-insert-with-overlays new)
2162 (move-to-column item-beg))))))
2164 (defun todo-edit-quit ()
2165 "Return from Todo Edit mode to Todo mode.
2166 If the item contains hard line breaks, make sure the following
2167 lines are indented by `todo-indent-to-here' to conform to diary
2170 If the whole file was in Todo Edit mode, check before returning
2171 whether the file is still a valid todo file and if so, also
2172 recalculate the todo file's categories sexp, in case changes were
2173 made in the number or names of categories."
2175 (if (> (buffer-size) (- (point-max) (point-min)))
2176 ;; We got here via `e m'.
2177 (let ((item (buffer-string))
2178 (regex "\\(\n\\)[^[:blank:]]")
2179 (buf (buffer-base-buffer)))
2180 (while (not (string-match (concat todo-date-string-start
2181 todo-date-pattern) item))
2182 (setq item (read-from-minibuffer
2183 "Item must start with a date: " item)))
2184 ;; Ensure lines following hard newlines are indented.
2185 (when (string-match regex (buffer-string))
2186 (setq item (replace-regexp-in-string regex "\n\t" item nil nil 1))
2187 (delete-region (point-min) (point-max))
2190 (unless (eq (current-buffer) buf)
2191 (set-window-buffer (selected-window) (set-buffer buf))))
2192 ;; We got here via `F e'.
2193 (when (todo-check-format)
2194 ;; FIXME: separate out sexp check?
2195 ;; If manual editing makes e.g. item counts change, have to
2196 ;; call this to update todo-categories, but it restores
2197 ;; category order to list order.
2198 ;; (todo-repair-categories-sexp)
2199 ;; Compare (todo-make-categories-list t) with sexp and if
2200 ;; different ask (todo-update-categories-sexp) ?
2202 (let* ((cat-beg (concat "^" (regexp-quote todo-category-beg)
2204 (curline (buffer-substring-no-properties
2205 (line-beginning-position) (line-end-position)))
2206 (cat (cond ((string-match cat-beg curline)
2207 (match-string-no-properties 1 curline))
2208 ((or (re-search-backward cat-beg nil t)
2209 (re-search-forward cat-beg nil t))
2210 (match-string-no-properties 1)))))
2211 (todo-category-number cat)
2212 (todo-category-select)
2213 (goto-char (point-min))))))
2215 (defun todo-edit-item--header (what &optional inc)
2216 "Function providing header editing facilities of `todo-edit-item'."
2217 (let* ((cat (todo-current-category))
2218 (marked (assoc cat todo-categories-with-marks))
2220 (todo-date-from-calendar t)
2221 ;; INC must be an integer, but users could pass it via
2222 ;; `todo-edit-item' as e.g. `-' or `C-u'.
2223 (inc (prefix-numeric-value inc))
2224 (buffer-read-only nil)
2225 ndate ntime year monthname month day
2226 dayname) ; Needed by calendar-date-display-form.
2228 (or (and marked (goto-char (point-min))) (todo-item-start))
2232 (while (not (todo-marked-item-p))
2234 (and (eobp) (throw 'end nil))))
2235 (re-search-forward (concat todo-date-string-start "\\(?1:"
2237 "\\)\\(?2: " diary-time-regexp "\\)?"
2238 (regexp-quote todo-nondiary-end) "?")
2239 (line-end-position) t)
2240 (let* ((odate (match-string-no-properties 1))
2241 (otime (match-string-no-properties 2))
2242 (odayname (match-string-no-properties 5))
2243 (omonthname (match-string-no-properties 6))
2244 (omonth (match-string-no-properties 7))
2245 (oday (match-string-no-properties 8))
2246 (oyear (match-string-no-properties 9))
2247 (tmn-array todo-month-name-array)
2248 (mlist (append tmn-array nil))
2249 (tma-array todo-month-abbrev-array)
2250 (mablist (append tma-array nil))
2251 (yy (and oyear (unless (string= oyear "*")
2252 (string-to-number oyear))))
2253 (mm (or (and omonth (unless (string= omonth "*")
2254 (string-to-number omonth)))
2255 (1+ (- (length mlist)
2256 (length (or (member omonthname mlist)
2257 (member omonthname mablist)))))))
2258 (dd (and oday (unless (string= oday "*")
2259 (string-to-number oday)))))
2260 ;; If there are marked items, use only the first to set
2261 ;; header changes, and apply these to all marked items.
2265 (setq ndate (todo-read-date)))
2266 ((eq what 'calendar)
2267 (setq ndate (save-match-data (todo-set-date-from-calendar))))
2269 (setq ndate (calendar-date-string (calendar-current-date) t t)))
2271 (setq ndate (todo-read-dayname)))
2273 (setq ntime (save-match-data (todo-read-time)))
2274 (when (> (length ntime) 0)
2275 (setq ntime (concat " " ntime))))
2276 ;; When date string consists only of a day name,
2277 ;; passing other date components is a noop.
2278 ((and odayname (memq what '(year month day))))
2281 monthname omonthname
2283 year (cond ((not current-prefix-arg)
2284 (todo-read-date 'year))
2285 ((string= oyear "*")
2286 (user-error "Cannot increment *"))
2288 (number-to-string (+ yy inc))))))
2292 (if (memq 'month calendar-date-display-form)
2295 (cond ((not current-prefix-arg)
2296 (todo-read-date 'month))
2297 ((or (string= omonth "*") (= mm 13))
2298 (user-error "Cannot increment *"))
2300 (let ((mminc (+ mm inc)))
2301 ;; Increment or decrement month by INC
2303 (setq mm (% mminc 12))
2304 ;; If result is 0, make month December.
2305 (setq mm (if (= mm 0) 12 (abs mm)))
2306 ;; Adjust year if necessary.
2307 (setq year (or (and (cond ((> mminc 12)
2308 (+ yy (/ mminc 12)))
2310 (- yy (/ mminc 12) 1))
2312 (number-to-string yy))
2314 ;; Return the changed numerical month as
2315 ;; a string or the corresponding month name.
2317 (number-to-string mm)
2318 (aref tma-array (1- mm))))))
2319 (let ((yy (string-to-number year)) ; 0 if year is "*".
2320 ;; When mm is 13 (corresponding to "*" as value
2321 ;; of month), this raises an args-out-of-range
2322 ;; error in calendar-last-day-of-month, so use 1
2323 ;; (corresponding to January) to get 31 days.
2324 (mm (if (= mm 13) 1 mm)))
2325 (if (> (string-to-number day)
2326 (calendar-last-day-of-month mm yy))
2327 (user-error "%s %s does not have %s days"
2328 (aref tmn-array (1- mm))
2329 (if (= mm 2) yy "") day))))
2333 monthname omonthname
2335 ((not current-prefix-arg)
2336 (todo-read-date 'day mm oyear))
2338 (user-error "Cannot increment *"))
2339 ((or (string= omonth "*") (string= omonthname "*"))
2340 (setq dd (+ dd inc))
2343 "A month cannot have more than 31 days")
2344 (number-to-string dd)))
2345 ;; Increment or decrement day by INC,
2346 ;; adjusting month and year if necessary
2347 ;; (if year is "*" assume current year to
2348 ;; calculate adjustment).
2350 (let* ((yy (or yy (calendar-extract-year
2351 (calendar-current-date))))
2352 (date (calendar-gregorian-from-absolute
2353 (+ (calendar-absolute-from-gregorian
2354 (list mm dd yy)) inc)))
2355 (adjmm (nth 0 date)))
2356 ;; Set year and month(name) to adjusted values.
2357 (unless (string= year "*")
2358 (setq year (number-to-string (nth 2 date))))
2360 (setq month (number-to-string adjmm))
2361 (setq monthname (aref tma-array (1- adjmm))))
2362 ;; Return changed numerical day as a string.
2363 (number-to-string (nth 1 date)))))))))
2365 ;; If year, month or day date string components were
2366 ;; changed, rebuild the date string.
2367 (when (memq what '(year month day))
2368 (setq ndate (mapconcat 'eval calendar-date-display-form ""))))
2369 (when ndate (replace-match ndate nil nil nil 1))
2370 ;; Add new time string to the header, if it was supplied.
2373 (replace-match ntime nil nil nil 2)
2374 (goto-char (match-end 1))
2376 (setq todo-date-from-calendar nil)
2378 ;; Apply the changes to the first marked item header to the
2379 ;; remaining marked items. If there are no marked items,
2383 (goto-char (point-max))))))))
2385 (defun todo-edit-item--diary-inclusion (&optional nonmarking)
2386 "Function providing diary marking facilities of `todo-edit-item'."
2387 (let ((buffer-read-only)
2388 (marked (assoc (todo-current-category)
2389 todo-categories-with-marks)))
2392 (when marked (goto-char (point-min)))
2394 (if (todo-done-item-p)
2395 (throw 'stop (message "Done items cannot be edited"))
2396 (unless (and marked (not (todo-marked-item-p)))
2397 (let* ((beg (todo-item-start))
2398 (lim (save-excursion (todo-item-end)))
2399 (end (save-excursion
2400 (or (todo-time-string-matcher lim)
2401 (todo-date-string-matcher lim)))))
2403 (if (looking-at (regexp-quote diary-nonmarking-symbol))
2405 (when (looking-at (regexp-quote todo-nondiary-start))
2408 (search-forward todo-nondiary-end (1+ end) t)
2410 (todo-update-count 'diary 1)))
2411 (insert diary-nonmarking-symbol))
2412 (if (looking-at (regexp-quote todo-nondiary-start))
2415 (search-forward todo-nondiary-end (1+ end) t)
2417 (todo-update-count 'diary 1))
2419 (when (looking-at (regexp-quote diary-nonmarking-symbol))
2421 (setq end (1- end))) ; Since we deleted nonmarking symbol.
2422 (insert todo-nondiary-start)
2423 (goto-char (1+ end))
2424 (insert todo-nondiary-end)
2425 (todo-update-count 'diary -1))))))
2426 (unless marked (throw 'stop nil))
2427 (todo-forward-item)))))
2428 (todo-update-categories-sexp)))
2430 (defun todo-edit-category-diary-inclusion (arg)
2431 "Make all items in this category diary items.
2432 With prefix ARG, make all items in this category non-diary
2436 (goto-char (point-min))
2437 (let ((todo-count (todo-get-count 'todo))
2438 (diary-count (todo-get-count 'diary))
2442 (if (todo-done-item-p) ; We've gone too far.
2444 (let* ((beg (todo-item-start))
2445 (lim (save-excursion (todo-item-end)))
2446 (end (save-excursion
2447 (or (todo-time-string-matcher lim)
2448 (todo-date-string-matcher lim)))))
2450 (unless (looking-at (regexp-quote todo-nondiary-start))
2451 (when (looking-at (regexp-quote diary-nonmarking-symbol))
2453 (setq end (1- end))) ; Since we deleted nonmarking symbol.
2454 (insert todo-nondiary-start)
2455 (goto-char (1+ end))
2456 (insert todo-nondiary-end))
2457 (when (looking-at (regexp-quote todo-nondiary-start))
2459 (search-forward todo-nondiary-end (1+ end) t)
2460 (replace-match "")))))
2461 (todo-forward-item))
2462 (unless (if arg (zerop diary-count) (= diary-count todo-count))
2463 (todo-update-count 'diary (if arg
2465 (- todo-count diary-count))))
2466 (todo-update-categories-sexp)))))
2468 (defun todo-edit-category-diary-nonmarking (arg)
2469 "Add `diary-nonmarking-symbol' to all diary items in this category.
2470 With prefix ARG, remove `diary-nonmarking-symbol' from all diary
2471 items in this category."
2474 (goto-char (point-min))
2475 (let (buffer-read-only)
2478 (if (todo-done-item-p) ; We've gone too far.
2480 (unless (looking-at (regexp-quote todo-nondiary-start))
2482 (when (looking-at (regexp-quote diary-nonmarking-symbol))
2484 (unless (looking-at (regexp-quote diary-nonmarking-symbol))
2485 (insert diary-nonmarking-symbol))))
2486 (todo-forward-item)))))))
2488 (defun todo-set-item-priority (&optional item cat new arg)
2489 "Prompt for and set ITEM's priority in CATegory.
2491 Interactively, ITEM is the todo item at point, CAT is the current
2492 category, and the priority is a number between 1 and the number
2493 of items in the category. Non-interactively, non-nil NEW means
2494 ITEM is a new item and the lowest priority is one more than the
2495 number of items in CAT.
2497 The new priority is set either interactively by prompt or by a
2498 numerical prefix argument, or noninteractively by argument ARG,
2499 whose value can be either of the symbols `raise' or `lower',
2500 meaning to raise or lower the item's priority by one."
2502 (unless (and (called-interactively-p 'any)
2503 (or (todo-done-item-p) (looking-at "^$")))
2504 (let* ((item (or item (todo-item-string)))
2505 (marked (todo-marked-item-p))
2506 (cat (or cat (cond ((eq major-mode 'todo-mode)
2507 (todo-current-category))
2508 ((eq major-mode 'todo-filtered-items-mode)
2510 (concat todo-date-string-start
2512 "\\( " diary-time-regexp "\\)?"
2513 (regexp-quote todo-nondiary-end)
2514 "?\\(?1: \\[\\(.+:\\)?.+\\]\\)")))
2516 (re-search-forward regexp1 nil t)
2517 (match-string-no-properties 1)))))))
2519 (todo (cond ((or (eq arg 'raise) (eq arg 'lower)
2520 (eq major-mode 'todo-filtered-items-mode))
2522 (let ((curstart (todo-item-start))
2524 (goto-char (point-min))
2525 (while (looking-at todo-item-start)
2526 (setq count (1+ count))
2527 (when (= (point) curstart) (setq curnum count))
2528 (todo-forward-item))
2530 ((eq major-mode 'todo-mode)
2531 (todo-get-count 'todo cat))))
2532 (maxnum (if new (1+ todo) todo))
2533 (prompt (format "Set item priority (1-%d): " maxnum))
2534 (priority (cond ((and (not arg) (numberp current-prefix-arg))
2536 ((and (eq arg 'raise) (>= curnum 1))
2538 ((and (eq arg 'lower) (<= curnum maxnum))
2542 (unless (and priority
2543 (or (and (eq arg 'raise) (zerop priority))
2544 (and (eq arg 'lower) (> priority maxnum))))
2545 ;; When moving item to another category, show the category before
2546 ;; prompting for its priority.
2547 (unless (or arg (called-interactively-p 'any))
2548 (todo-category-number cat)
2549 ;; If done items in category are visible, keep them visible.
2550 (let ((done todo-show-with-done))
2551 (when (> (buffer-size) (- (point-max) (point-min)))
2553 (goto-char (point-min))
2554 (setq done (re-search-forward todo-done-string-start nil t))))
2555 (let ((todo-show-with-done done))
2556 (todo-category-select)
2557 ;; Keep top of category in view while setting priority.
2558 (goto-char (point-min)))))
2559 ;; Prompt for priority only when the category has at least one
2562 (while (not priority)
2563 (setq candidate (read-number prompt
2564 (if (eq todo-default-priority 'first)
2566 (setq prompt (when (or (< candidate 1) (> candidate maxnum))
2567 (format "Priority must be an integer between 1 and %d.\n"
2569 (unless prompt (setq priority candidate))))
2570 ;; In Top Priorities buffer, an item's priority can be changed
2571 ;; wrt items in another category, but not wrt items in the same
2573 (when (eq major-mode 'todo-filtered-items-mode)
2574 (let* ((regexp2 (concat todo-date-string-start todo-date-pattern
2575 "\\( " diary-time-regexp "\\)?"
2576 (regexp-quote todo-nondiary-end)
2577 "?\\(?1:" (regexp-quote cat) "\\)"))
2578 (end (cond ((< curnum priority)
2579 (save-excursion (todo-item-end)))
2580 ((> curnum priority)
2581 (save-excursion (todo-item-start)))))
2582 (match (save-excursion
2583 (cond ((< curnum priority)
2584 (todo-forward-item (1+ (- priority curnum)))
2585 (when (re-search-backward regexp2 end t)
2586 (match-string-no-properties 1)))
2587 ((> curnum priority)
2588 (todo-backward-item (- curnum priority))
2589 (when (re-search-forward regexp2 end t)
2590 (match-string-no-properties 1)))))))
2592 (user-error (concat "Cannot reprioritize items from the same "
2593 "category in this mode, only in Todo mode")))))
2594 ;; Interactively or with non-nil ARG, relocate the item within its
2596 (when (or arg (called-interactively-p 'any))
2598 (goto-char (point-min))
2600 (unless (= priority 1)
2601 (todo-forward-item (1- priority))
2602 ;; When called from todo-item-undone and the highest priority
2603 ;; is chosen, this advances point to the first done item, so
2604 ;; move it up to the empty line above the done items
2606 (when (looking-back (concat "^"
2607 (regexp-quote todo-category-done)
2609 (todo-backward-item))))
2610 (todo-insert-with-overlays item)
2611 ;; If item was marked, restore the mark.
2613 (let* ((ov (todo-get-overlay 'prefix))
2614 (pref (overlay-get ov 'before-string)))
2615 (overlay-put ov 'before-string
2616 (concat todo-item-mark pref))))))))
2618 (defun todo-raise-item-priority ()
2619 "Raise priority of current item by moving it up by one item."
2621 (todo-set-item-priority nil nil nil 'raise))
2623 (defun todo-lower-item-priority ()
2624 "Lower priority of current item by moving it down by one item."
2626 (todo-set-item-priority nil nil nil 'lower))
2628 (defun todo-move-item (&optional file)
2629 "Move at least one todo or done item to another category.
2630 If there are marked items, move all of these; otherwise, move
2633 With prefix argument FILE, prompt for a specific todo file and
2634 choose (with TAB completion) a category in it to move the item or
2635 items to; otherwise, choose and move to any category in either
2636 the current todo file or one of the files in
2637 `todo-category-completions-files'. If the chosen category is
2638 not an existing categories, then it is created and the item(s)
2639 become(s) the first entry/entries in that category.
2641 With moved todo items, prompt to set the priority in the category
2642 moved to (with multiple todo items, the one that had the highest
2643 priority in the category moved from gets the new priority and the
2644 rest of the moved todo items are inserted in sequence below it).
2645 Moved done items are appended to the top of the done items
2646 section in the category moved to."
2648 (let* ((cat1 (todo-current-category))
2649 (marked (assoc cat1 todo-categories-with-marks)))
2650 ;; Noop if point is not on an item and there are no marked items.
2651 (unless (and (looking-at "^$")
2653 (let* ((buffer-read-only)
2654 (file1 todo-current-todo-file)
2655 (num todo-category-number)
2656 (item (todo-item-string))
2657 (diary-item (todo-diary-item-p))
2658 (done-item (and (todo-done-item-p) (concat item "\n")))
2659 (omark (save-excursion (todo-item-start) (point-marker)))
2663 ov cat2 file2 moved nmark todo-items done-items)
2667 (setq ov (make-overlay (save-excursion (todo-item-start))
2668 (save-excursion (todo-item-end))))
2669 (overlay-put ov 'face 'todo-search))
2670 (let* ((pl (if (and marked (> (cdr marked) 1)) "s" ""))
2671 (cat+file (todo-read-category (concat "Move item" pl
2674 (while (and (equal (car cat+file) cat1)
2675 (equal (cdr cat+file) file1))
2676 (setq cat+file (todo-read-category
2677 "Choose a different category: ")))
2678 (setq cat2 (car cat+file)
2679 file2 (cdr cat+file))))
2680 (if ov (delete-overlay ov)))
2681 (set-buffer (find-buffer-visiting file1))
2684 (goto-char (point-min))
2686 (when (todo-marked-item-p)
2687 (if (todo-done-item-p)
2688 (setq done-items (concat done-items
2689 (todo-item-string) "\n")
2691 (setq todo-items (concat todo-items
2692 (todo-item-string) "\n")
2694 (when (todo-diary-item-p)
2695 (setq diary (1+ diary)))))
2696 (todo-forward-item))
2697 ;; Chop off last newline of multiple todo item string,
2698 ;; since it will be reinserted when setting priority
2699 ;; (but with done items priority is not set, so keep
2702 (setq todo-items (substring todo-items 0 -1))))
2703 (if (todo-done-item-p)
2706 (when (todo-diary-item-p) (setq diary 1))))
2707 (set-window-buffer (selected-window)
2708 (set-buffer (find-file-noselect file2 'nowarn)))
2711 (when (or todo-items (and item (not done-item)))
2712 (todo-set-item-priority (or todo-items item) cat2 t))
2713 ;; Move done items en bloc to top of done items section.
2714 (when (or done-items done-item)
2715 (todo-category-number cat2)
2717 (goto-char (point-min))
2719 (concat "^" (regexp-quote (concat todo-category-beg cat2))
2722 (concat "^" (regexp-quote todo-category-done)) nil t)
2724 (insert (or done-items done-item)))
2727 ;; Move succeeded, so remove item from starting category,
2728 ;; update item counts and display the category containing
2731 (setq nmark (point-marker))
2732 (when todo (todo-update-count 'todo todo))
2733 (when diary (todo-update-count 'diary diary))
2734 (when done (todo-update-count 'done done))
2735 (todo-update-categories-sexp)
2736 (with-current-buffer (find-buffer-visiting file1)
2745 (concat "^" (regexp-quote todo-category-beg)) nil t)
2748 (setq end (if (re-search-forward
2749 (concat "^" (regexp-quote
2750 todo-category-beg)) nil t)
2754 (while (< (point) end)
2755 (if (todo-marked-item-p)
2757 (todo-forward-item)))
2758 (setq todo-categories-with-marks
2759 (assq-delete-all cat1 todo-categories-with-marks)))
2760 (if ov (delete-overlay ov))
2761 (todo-remove-item))))
2762 (when todo (todo-update-count 'todo (- todo) cat1))
2763 (when diary (todo-update-count 'diary (- diary) cat1))
2764 (when done (todo-update-count 'done (- done) cat1))
2765 (todo-update-categories-sexp))
2766 (set-window-buffer (selected-window)
2767 (set-buffer (find-file-noselect file2 'nowarn)))
2768 (setq todo-category-number (todo-category-number cat2))
2769 (let ((todo-show-with-done (or done-items done-item)))
2770 (todo-category-select))
2772 ;; If item is moved to end of (just first?) category, make
2773 ;; sure the items above it are displayed in the window.
2775 ;; User quit before setting priority of todo item(s), so
2776 ;; return to starting category.
2778 (set-window-buffer (selected-window)
2779 (set-buffer (find-file-noselect file1 'nowarn)))
2780 (todo-category-number cat1)
2781 (todo-category-select)
2782 (goto-char omark))))))))
2784 (defun todo-item-done (&optional arg)
2785 "Tag a todo item in this category as done and relocate it.
2787 With prefix argument ARG prompt for a comment and append it to
2788 the done item; this is only possible if there are no marked
2789 items. If there are marked items, tag all of these with
2790 `todo-done-string' plus the current date and, if
2791 `todo-always-add-time-string' is non-nil, the current time;
2792 otherwise, just tag the item at point. Items tagged as done are
2793 relocated to the category's (by default hidden) done section. If
2794 done items are visible on invoking this command, they remain
2797 (let* ((cat (todo-current-category))
2798 (marked (assoc cat todo-categories-with-marks)))
2802 (goto-char (point-max))
2803 (todo-backward-item)
2804 (unless (todo-done-item-p)
2806 (unless (re-search-forward
2807 (concat "^" (regexp-quote todo-category-beg)) nil t)
2808 (goto-char (point-max)))
2810 (while (todo-done-item-p)
2811 (when (todo-marked-item-p)
2812 (user-error "This command does not apply to done items"))
2813 (todo-backward-item)))))
2814 (unless (and (not marked)
2815 (or (todo-done-item-p)
2816 ;; Point is between todo and done items.
2818 (let* ((date-string (calendar-date-string (calendar-current-date) t t))
2819 (time-string (if todo-always-add-time-string
2820 (concat " " (substring (current-time-string)
2823 (done-prefix (concat "[" todo-done-string date-string time-string
2825 (comment (and arg (read-string "Enter a comment: ")))
2828 (show-done (save-excursion
2829 (goto-char (point-min))
2830 (re-search-forward todo-done-string-start nil t)))
2831 (buffer-read-only nil)
2832 item done-item opoint)
2833 ;; Don't add empty comment to done item.
2834 (setq comment (unless (zerop (length comment))
2835 (concat " [" todo-comment-string ": " comment "]")))
2836 (and marked (goto-char (point-min)))
2838 ;; Stop looping when we hit the empty line below the last
2839 ;; todo item (this is eobp if only done items are hidden).
2840 (while (not (looking-at "^$"))
2841 (if (or (not marked) (and marked (todo-marked-item-p)))
2843 (setq item (todo-item-string))
2844 (setq done-item (concat done-item done-prefix item
2845 comment (and marked "\n")))
2846 (setq item-count (1+ item-count))
2847 (when (todo-diary-item-p)
2848 (setq diary-count (1+ diary-count)))
2850 (unless marked (throw 'done nil)))
2851 (todo-forward-item))))
2853 ;; Chop off last newline of done item string.
2854 (setq done-item (substring done-item 0 -1))
2855 (setq todo-categories-with-marks
2856 (assq-delete-all cat todo-categories-with-marks)))
2860 (concat "^" (regexp-quote todo-category-done)) nil t)
2862 (when show-done (setq opoint (point)))
2863 (insert done-item "\n"))
2864 (todo-update-count 'todo (- item-count))
2865 (todo-update-count 'done item-count)
2866 (todo-update-count 'diary (- diary-count))
2867 (todo-update-categories-sexp)
2868 (let ((todo-show-with-done show-done))
2869 (todo-category-select)
2870 ;; When done items are shown, put cursor on first just done item.
2871 (when opoint (goto-char opoint)))))))
2873 (defun todo-item-undone ()
2874 "Restore at least one done item to this category's todo section.
2875 Prompt for the new priority. If there are marked items, undo all
2876 of these, giving the first undone item the new priority and the
2877 rest following directly in sequence; otherwise, undo just the
2880 If the done item has a comment, ask whether to omit the comment
2881 from the restored item. With multiple marked done items with
2882 comments, only ask once, and if affirmed, omit subsequent
2883 comments without asking."
2885 (let* ((cat (todo-current-category))
2886 (marked (assoc cat todo-categories-with-marks))
2887 (pl (if (and marked (> (cdr marked) 1)) "s" "")))
2888 (when (or marked (todo-done-item-p))
2889 (let ((buffer-read-only)
2891 (omark (point-marker))
2895 start end item ov npoint undone)
2896 (and marked (goto-char (point-min)))
2899 (when (or (not marked) (and marked (todo-marked-item-p)))
2900 (if (not (todo-done-item-p))
2901 (user-error "Only done items can be undone")
2904 (setq ov (make-overlay (save-excursion (todo-item-start))
2905 (save-excursion (todo-item-end))))
2906 (overlay-put ov 'face 'todo-search))
2907 ;; Find the end of the date string added upon tagging item as
2909 (setq start (search-forward "] "))
2910 (setq item-count (1+ item-count))
2911 (unless (looking-at (regexp-quote todo-nondiary-start))
2912 (setq diary-count (1+ diary-count)))
2913 (setq end (save-excursion (todo-item-end)))
2914 ;; Ask (once) whether to omit done item's comment. If
2915 ;; affirmed, omit subsequent comments without asking.
2916 (when (re-search-forward
2917 (concat " \\[" (regexp-quote todo-comment-string)
2918 ": [^]]+\\]") end t)
2920 (if (eq first 'first)
2922 (if (eq todo-undo-item-omit-comment 'ask)
2923 (when (todo-y-or-n-p
2924 (concat "Omit comment" pl
2925 " from restored item"
2928 (when todo-undo-item-omit-comment 'omit)))
2930 (when (and (eq first 'first) ov) (delete-overlay ov)))
2931 (when (eq first 'omit)
2932 (setq end (match-beginning 0))))
2933 (setq item (concat item
2934 (buffer-substring-no-properties start end)
2935 (when marked "\n")))
2936 (unless marked (throw 'done nil))))
2937 (todo-forward-item)))
2940 ;; Chop off last newline of multiple items string, since
2941 ;; it will be reinserted on setting priority.
2942 (and marked (setq item (substring item 0 -1)))
2943 (todo-set-item-priority item cat t)
2944 (setq npoint (point))
2946 (when ov (delete-overlay ov))
2953 (concat "^" (regexp-quote todo-category-done)) nil t)
2955 (if (todo-marked-item-p)
2957 (todo-forward-item)))
2958 (setq todo-categories-with-marks
2959 (assq-delete-all cat todo-categories-with-marks)))
2962 (todo-update-count 'todo item-count)
2963 (todo-update-count 'done (- item-count))
2964 (when diary-count (todo-update-count 'diary diary-count))
2965 (todo-update-categories-sexp)
2966 (let ((todo-show-with-done (> (todo-get-count 'done) 0)))
2967 (todo-category-select))
2968 ;; Put cursor on undone item.
2969 (goto-char npoint)))
2970 (set-marker omark nil)))))
2972 ;; -----------------------------------------------------------------------------
2973 ;;; Done item archives
2974 ;; -----------------------------------------------------------------------------
2976 (defun todo-find-archive (&optional ask)
2977 "Visit the archive of the current todo category, if it exists.
2978 If the category has no archived items, prompt to visit the
2979 archive anyway. If there is no archive for this file or with
2980 non-nil argument ASK, prompt to visit another archive.
2982 The buffer showing the archive is in Todo Archive mode. The
2983 first visit in a session displays the first category in the
2984 archive, subsequent visits return to the last category
2987 (if (null (funcall todo-files-function t))
2988 (message "There are no archive files")
2989 (let* ((cat (todo-current-category))
2990 (count (todo-get-count 'archived cat))
2991 (archive (concat (file-name-sans-extension todo-current-todo-file)
2993 (place (cond (ask 'other-archive)
2994 ((file-exists-p archive) 'this-archive)
2995 (t (when (todo-y-or-n-p
2996 (concat "This file has no archive; "
2997 "visit another archive? "))
2999 (when (eq place 'other-archive)
3000 (setq archive (todo-read-file-name "Choose a todo archive: " t t)))
3001 (when (and (eq place 'this-archive) (zerop count))
3002 (setq place (when (todo-y-or-n-p
3003 (concat "This category has no archived items;"
3004 " visit archive anyway? "))
3007 (set-window-buffer (selected-window)
3008 (set-buffer (find-file-noselect archive)))
3009 (unless (derived-mode-p 'todo-archive-mode) (todo-archive-mode))
3010 (if (member place '(other-archive other-cat))
3011 (setq todo-category-number 1)
3012 (todo-category-number cat))
3013 (todo-category-select)))))
3015 (defun todo-choose-archive ()
3016 "Choose an archive and visit it."
3018 (todo-find-archive t))
3020 (defun todo-archive-done-item (&optional all)
3021 "Archive at least one done item in this category.
3023 With prefix argument ALL, prompt whether to archive all done
3024 items in this category and on confirmation archive them.
3025 Otherwise, if there are marked done items (and no marked todo
3026 items), archive all of these; otherwise, archive the done item at
3029 If the archive of this file does not exist, it is created. If
3030 this category does not exist in the archive, it is created."
3032 (when (eq major-mode 'todo-mode)
3033 (if (and all (zerop (todo-get-count 'done)))
3034 (message "No done items in this category")
3036 (let* ((cat (todo-current-category))
3037 (tbuf (current-buffer))
3038 (marked (assoc cat todo-categories-with-marks))
3039 (afile (concat (file-name-sans-extension
3040 todo-current-todo-file) ".toda"))
3041 (archive (find-file-noselect afile t))
3042 (item (and (not marked) (todo-done-item-p)
3043 (concat (todo-item-string) "\n")))
3045 (opoint (unless (todo-done-item-p) (point)))
3046 marked-items beg end all-done
3050 (if (todo-y-or-n-p "Archive all done items in this category? ")
3053 (goto-char (point-min))
3056 (re-search-forward todo-done-string-start
3058 (match-beginning 0))
3059 end (if (re-search-forward
3061 (regexp-quote todo-category-beg))
3065 all-done (buffer-substring-no-properties beg end)
3066 count (todo-get-count 'done))
3067 ;; Restore starting point, unless it was on a done
3068 ;; item, since they will all be deleted.
3069 (when opoint (goto-char opoint))))
3073 (goto-char (point-min))
3075 (when (todo-marked-item-p)
3076 (if (not (todo-done-item-p))
3077 (throw 'end (message "Only done items can be archived"))
3079 (concat marked-items (todo-item-string) "\n"))
3080 (setq count (1+ count))))
3081 (todo-forward-item)))))
3082 (if (not (or marked all item))
3083 (throw 'end (message "Only done items can be archived"))
3084 (with-current-buffer archive
3085 (unless (derived-mode-p 'todo-archive-mode) (todo-archive-mode))
3086 (let (buffer-read-only)
3088 (goto-char (point-min))
3089 (if (and (re-search-forward
3090 (concat "^" (regexp-quote
3091 (concat todo-category-beg cat)) "$")
3093 (re-search-forward (regexp-quote todo-category-done)
3095 ;; Start of done items section in existing category.
3097 (todo-add-category nil cat)
3098 ;; Start of done items section in new category.
3099 (goto-char (point-max)))
3100 (insert (cond (marked marked-items)
3103 (todo-update-count 'done (if (or marked all) count 1) cat)
3104 (todo-update-categories-sexp)
3105 ;; If archive is new, save to file now (with
3106 ;; write-region to avoid prompt for file to save to)
3107 ;; to update todo-archives, and set the mode for
3108 ;; visiting the archive below.
3109 (unless (nth 7 (file-attributes afile))
3110 (write-region nil nil afile t t)
3111 (setq todo-archives (funcall todo-files-function t))
3112 (todo-archive-mode))))
3113 (with-current-buffer tbuf
3118 ;; Make sure done items are accessible.
3120 (remove-overlays beg end)
3121 (delete-region beg end)
3122 (todo-update-count 'done (- count))
3123 (todo-update-count 'archived count))))
3125 ;; If we're archiving all done items, can't
3126 ;; first archive item point was on, since
3127 ;; that will short-circuit the rest.
3128 (and item (not all)))
3129 (and marked (goto-char (point-min)))
3132 (if (or (and marked (todo-marked-item-p)) item)
3135 (todo-update-count 'done -1)
3136 (todo-update-count 'archived 1)
3137 ;; Don't leave point below last item.
3138 (and (or marked item) (bolp) (eolp)
3139 (< (point-min) (point-max))
3140 (todo-backward-item))
3142 (throw 'done (setq item nil))))
3143 (todo-forward-item))))))
3145 (setq todo-categories-with-marks
3146 (assq-delete-all cat todo-categories-with-marks)))
3147 (todo-update-categories-sexp)
3148 (todo-prefix-overlays)))
3150 (todo-category-number cat)
3151 (todo-category-select)
3152 (split-window-below)
3153 (set-window-buffer (selected-window) tbuf)
3154 ;; Make todo file current to select category.
3155 (find-file (buffer-file-name tbuf))
3156 ;; Make sure done item separator is hidden (if done items
3157 ;; were initially visible).
3158 (let (todo-show-with-done) (todo-category-select)))))))
3160 (defun todo-unarchive-items ()
3161 "Unarchive at least one item in this archive category.
3162 If there are marked items, unarchive all of these; otherwise,
3163 unarchive the item at point.
3165 Unarchived items are restored as done items to the corresponding
3166 category in the todo file, inserted at the top of done items
3167 section. If all items in the archive category have been
3168 restored, the category is deleted from the archive. If this was
3169 the only category in the archive, the archive file is deleted."
3171 (when (eq major-mode 'todo-archive-mode)
3172 (let* ((cat (todo-current-category))
3173 (tbuf (find-file-noselect
3174 (concat (file-name-sans-extension todo-current-todo-file)
3176 (marked (assoc cat todo-categories-with-marks))
3177 (item (concat (todo-item-string) "\n"))
3183 (goto-char (point-min))
3185 (when (todo-marked-item-p)
3186 (setq marked-items (concat marked-items (todo-item-string) "\n"))
3187 (setq marked-count (1+ marked-count)))
3188 (todo-forward-item))))
3189 ;; Restore items to top of category's done section and update counts.
3190 (with-current-buffer tbuf
3191 (let (buffer-read-only newcat)
3193 (goto-char (point-min))
3194 ;; Find the corresponding todo category, or if there isn't
3196 (unless (re-search-forward
3197 (concat "^" (regexp-quote (concat todo-category-beg cat))
3199 (todo-add-category nil cat)
3201 ;; Go to top of category's done section.
3203 (concat "^" (regexp-quote todo-category-done)) nil t)
3206 (insert marked-items)
3207 (todo-update-count 'done marked-count cat)
3208 (unless newcat ; Newly added category has no archive.
3209 (todo-update-count 'archived (- marked-count) cat)))
3212 (todo-update-count 'done 1 cat)
3213 (unless newcat ; Newly added category has no archive.
3214 (todo-update-count 'archived -1 cat))))
3215 (todo-update-categories-sexp)))
3216 ;; Delete restored items from archive.
3219 (goto-char (point-min)))
3222 (if (or (todo-marked-item-p) item)
3226 (throw 'done (setq item nil))))
3227 (todo-forward-item))))
3228 (todo-update-count 'done (if marked (- marked-count) -1) cat)
3229 ;; If we unarchived the last item in category, then if that was
3230 ;; the only category, delete the whole file, otherwise, just
3231 ;; delete the category.
3232 (when (= 0 (todo-get-count 'done))
3233 (if (= 1 (length todo-categories))
3235 (delete-file todo-current-todo-file)
3236 ;; Kill the archive buffer silently.
3237 (set-buffer-modified-p nil)
3240 (let ((beg (re-search-backward
3241 (concat "^" (regexp-quote todo-category-beg) cat "$")
3243 (end (if (re-search-forward
3244 (concat "^" (regexp-quote todo-category-beg))
3248 (remove-overlays beg end)
3249 (delete-region beg end)
3250 (setq todo-categories (delete (assoc cat todo-categories)
3251 todo-categories)))))
3252 (todo-update-categories-sexp)
3253 ;; Visit category in todo file and show restored done items.
3254 (let ((tfile (buffer-file-name tbuf))
3255 (todo-show-with-done t))
3256 (set-window-buffer (selected-window)
3257 (set-buffer (find-file-noselect tfile)))
3258 (todo-category-number cat)
3259 (todo-category-select)
3260 (message "Items unarchived.")))))
3262 (defun todo-jump-to-archive-category (&optional file)
3263 "Prompt for a category in a todo archive and jump to it.
3264 With prefix argument FILE, prompt for an archive and choose (with
3265 TAB completion) a category in it to jump to; otherwise, choose
3266 and jump to any category in the current archive."
3268 (todo-jump-to-category file 'archive))
3270 ;; -----------------------------------------------------------------------------
3271 ;;; Displaying and sorting tables of categories
3272 ;; -----------------------------------------------------------------------------
3274 (defcustom todo-categories-category-label "Category"
3275 "Category button label in Todo Categories mode."
3277 :group 'todo-categories)
3279 (defcustom todo-categories-todo-label "Todo"
3280 "Todo button label in Todo Categories mode."
3282 :group 'todo-categories)
3284 (defcustom todo-categories-diary-label "Diary"
3285 "Diary button label in Todo Categories mode."
3287 :group 'todo-categories)
3289 (defcustom todo-categories-done-label "Done"
3290 "Done button label in Todo Categories mode."
3292 :group 'todo-categories)
3294 (defcustom todo-categories-archived-label "Archived"
3295 "Archived button label in Todo Categories mode."
3297 :group 'todo-categories)
3299 (defcustom todo-categories-totals-label "Totals"
3300 "String to label total item counts in Todo Categories mode."
3302 :group 'todo-categories)
3304 (defcustom todo-categories-number-separator " | "
3305 "String between number and category in Todo Categories mode.
3306 This separates the number from the category name in the default
3307 categories display according to priority."
3309 :group 'todo-categories)
3311 (defcustom todo-categories-align 'center
3312 "Alignment of category names in Todo Categories mode."
3313 :type '(radio (const left) (const center) (const right))
3314 :group 'todo-categories)
3316 (defun todo-show-categories-table ()
3317 "Display a table of the current file's categories and item counts.
3319 In the initial display the lines of the table are numbered,
3320 indicating the current order of the categories when sequentially
3321 navigating through the todo file with `\\[todo-forward-category]'
3322 and `\\[todo-backward-category]'. You can reorder the lines, and
3323 hence the category sequence, by typing `\\[todo-raise-category]'
3324 or `\\[todo-lower-category]' to raise or lower the category at
3325 point, or by typing `\\[todo-set-category-number]' and entering a
3326 number at the prompt or by typing `\\[todo-set-category-number]'
3327 with a numeric prefix. If you save the todo file after
3328 reordering the categories, the new order persists in subsequent
3331 The labels above the category names and item counts are buttons,
3332 and clicking these changes the display: sorted by category name
3333 or by the respective item counts (alternately descending or
3334 ascending). In these displays the categories are not numbered
3335 and `\\[todo-set-category-number]', `\\[todo-raise-category]' and
3336 `\\[todo-lower-category]' are disabled. (Programmatically, the
3337 sorting is triggered by passing a non-nil SORTKEY argument.)
3339 In addition, the lines with the category names and item counts
3340 are buttonized, and pressing one of these button jumps to the
3341 category in Todo mode (or Todo Archive mode, for categories
3342 containing only archived items, provided user option
3343 `todo-skip-archived-categories' is non-nil. These categories
3344 are shown in `todo-archived-only' face."
3346 (todo-display-categories)
3348 (todo-update-categories-display sortkey)))
3350 (defun todo-next-button (n)
3351 "Move point to the Nth next button in the table of categories."
3353 (forward-button n 'wrap 'display-message)
3354 (and (bolp) (button-at (point))
3355 ;; Align with beginning of category label.
3356 (forward-char (+ 4 (length todo-categories-number-separator)))))
3358 (defun todo-previous-button (n)
3359 "Move point to the Nth previous button in the table of categories."
3361 (backward-button n 'wrap 'display-message)
3362 (and (bolp) (button-at (point))
3363 ;; Align with beginning of category label.
3364 (forward-char (+ 4 (length todo-categories-number-separator)))))
3366 (defun todo-set-category-number (&optional arg)
3367 "Change number of category at point in the table of categories.
3369 With ARG nil, prompt for the new number. Alternatively, the
3370 enter the new number with numerical prefix ARG. Otherwise, if
3371 ARG is either of the symbols `raise' or `lower', raise or lower
3372 the category line in the table by one, respectively, thereby
3373 decreasing or increasing its number."
3375 (let ((curnum (save-excursion
3376 ;; Get the number representing the priority of the category
3377 ;; on the current line.
3378 (forward-line 0) (skip-chars-forward " ") (number-at-point))))
3379 (when curnum ; Do nothing if we're not on a category line.
3380 (let* ((maxnum (length todo-categories))
3381 (prompt (format "Set category priority (1-%d): " maxnum))
3382 (col (current-column))
3383 (buffer-read-only nil)
3384 (priority (cond ((and (eq arg 'raise) (> curnum 1))
3386 ((and (eq arg 'lower) (< curnum maxnum))
3389 (while (not priority)
3390 (setq candidate (or arg (read-number prompt)))
3393 (cond ((or (< candidate 1) (> candidate maxnum))
3394 (format "Priority must be an integer between 1 and %d: "
3396 ((= candidate curnum)
3397 "Choose a different priority than the current one: ")))
3398 (unless prompt (setq priority candidate)))
3399 (let* ((lower (< curnum priority)) ; Priority is being lowered.
3400 (head (butlast todo-categories
3401 (apply (if lower 'identity '1+)
3402 (list (- maxnum priority)))))
3403 (tail (nthcdr (apply (if lower 'identity '1-) (list priority))
3405 ;; Category's name and items counts list.
3406 (catcons (nth (1- curnum) todo-categories))
3407 (todo-categories (nconc head (list catcons) tail))
3409 (when lower (setq todo-categories (nreverse todo-categories)))
3410 (setq todo-categories (delete-dups todo-categories))
3411 (when lower (setq todo-categories (nreverse todo-categories)))
3412 (setq newcats todo-categories)
3414 (with-current-buffer (find-buffer-visiting todo-current-todo-file)
3415 (setq todo-categories newcats)
3416 (todo-update-categories-sexp))
3417 (todo-show-categories-table)
3418 (forward-line (1+ priority))
3419 (forward-char col))))))
3421 (defun todo-raise-category ()
3422 "Raise priority of category at point in the table of categories."
3424 (todo-set-category-number 'raise))
3426 (defun todo-lower-category ()
3427 "Lower priority of category at point in the table of categories."
3429 (todo-set-category-number 'lower))
3431 (defun todo-sort-categories-alphabetically-or-numerically ()
3432 "Sort table of categories alphabetically or numerically."
3435 (goto-char (point-min))
3437 (if (member 'alpha todo-descending-counts)
3439 (todo-update-categories-display nil)
3440 (setq todo-descending-counts
3441 (delete 'alpha todo-descending-counts)))
3442 (todo-update-categories-display 'alpha))))
3444 (defun todo-sort-categories-by-todo ()
3445 "Sort table of categories by number of todo items."
3448 (goto-char (point-min))
3450 (todo-update-categories-display 'todo)))
3452 (defun todo-sort-categories-by-diary ()
3453 "Sort table of categories by number of diary items."
3456 (goto-char (point-min))
3458 (todo-update-categories-display 'diary)))
3460 (defun todo-sort-categories-by-done ()
3461 "Sort table of categories by number of non-archived done items."
3464 (goto-char (point-min))
3466 (todo-update-categories-display 'done)))
3468 (defun todo-sort-categories-by-archived ()
3469 "Sort table of categories by number of archived items."
3472 (goto-char (point-min))
3474 (todo-update-categories-display 'archived)))
3476 (defvar todo-categories-buffer "*Todo Categories*"
3477 "Name of buffer in Todo Categories mode.")
3479 (defun todo-longest-category-name-length (categories)
3480 "Return the length of the longest name in list CATEGORIES."
3482 (dolist (c categories longest)
3483 (setq longest (max longest (length c))))))
3485 (defun todo-adjusted-category-label-length ()
3486 "Return adjusted length of category label button.
3487 The adjustment ensures proper tabular alignment in Todo
3489 (let* ((categories (mapcar 'car todo-categories))
3490 (longest (todo-longest-category-name-length categories))
3491 (catlablen (length todo-categories-category-label))
3492 (lc-diff (- longest catlablen)))
3493 (if (and (natnump lc-diff) (cl-oddp lc-diff))
3495 (max longest catlablen))))
3497 (defun todo-padded-string (str)
3498 "Return category name or label string STR padded with spaces.
3499 The placement of the padding is determined by the value of user
3500 option `todo-categories-align'."
3501 (let* ((len (todo-adjusted-category-label-length))
3502 (strlen (length str))
3503 (strlen-odd (eq (logand strlen 1) 1))
3504 (padding (max 0 (/ (- len strlen) 2)))
3505 (padding-left (cond ((eq todo-categories-align 'left) 0)
3506 ((eq todo-categories-align 'center) padding)
3507 ((eq todo-categories-align 'right)
3508 (if strlen-odd (1+ (* padding 2)) (* padding 2)))))
3509 (padding-right (cond ((eq todo-categories-align 'left)
3510 (if strlen-odd (1+ (* padding 2)) (* padding 2)))
3511 ((eq todo-categories-align 'center)
3512 (if strlen-odd (1+ padding) padding))
3513 ((eq todo-categories-align 'right) 0))))
3514 (concat (make-string padding-left 32) str (make-string padding-right 32))))
3516 (defvar todo-descending-counts nil
3517 "List of keys for category counts sorted in descending order.")
3519 (defun todo-sort (list &optional key)
3520 "Return a copy of LIST, possibly sorted according to KEY."
3521 (let* ((l (copy-sequence list))
3522 (fn (if (eq key 'alpha)
3523 (lambda (x) (upcase x)) ; Alphabetize case insensitively.
3524 (lambda (x) (todo-get-count key x))))
3525 ;; Keep track of whether the last sort by key was descending or
3527 (descending (member key todo-descending-counts))
3528 (cmp (if (eq key 'alpha)
3530 (if descending '< '>)))
3531 (pred (lambda (s1 s2) (let ((t1 (funcall fn (car s1)))
3532 (t2 (funcall fn (car s2))))
3533 (funcall cmp t1 t2)))))
3535 (setq l (sort l pred))
3536 ;; Switch between descending and ascending sort order.
3538 (setq todo-descending-counts
3539 (delete key todo-descending-counts))
3540 (push key todo-descending-counts)))
3543 (defun todo-display-sorted (type)
3544 "Keep point on the TYPE count sorting button just clicked."
3545 (let ((opoint (point)))
3546 (todo-update-categories-display type)
3547 (goto-char opoint)))
3549 (defun todo-label-to-key (label)
3550 "Return symbol for sort key associated with LABEL."
3552 (cond ((string= label todo-categories-category-label)
3554 ((string= label todo-categories-todo-label)
3556 ((string= label todo-categories-diary-label)
3558 ((string= label todo-categories-done-label)
3560 ((string= label todo-categories-archived-label)
3561 (setq key 'archived)))
3564 (defun todo-insert-sort-button (label)
3565 "Insert button for displaying categories sorted by item counts.
3566 LABEL determines which type of count is sorted."
3567 (let* ((str (if (string= label todo-categories-category-label)
3568 (todo-padded-string label)
3571 (end (+ beg (length str)))
3573 (insert-button str 'face nil
3576 (let ((key (todo-label-to-key ,label)))
3577 (if (and (member key todo-descending-counts)
3580 ;; If display is alphabetical, switch back to
3581 ;; category priority order.
3582 (todo-display-sorted nil)
3583 (setq todo-descending-counts
3584 (delete key todo-descending-counts)))
3585 (todo-display-sorted key)))))
3586 (setq ov (make-overlay beg end))
3587 (overlay-put ov 'face 'todo-button)))
3589 (defun todo-total-item-counts ()
3590 "Return a list of total item counts for the current file."
3591 (mapcar (lambda (i) (apply '+ (mapcar (lambda (l) (aref l i))
3592 (mapcar 'cdr todo-categories))))
3595 (defvar todo-categories-category-number 0
3596 "Variable for numbering categories in Todo Categories mode.")
3598 (defun todo-insert-category-line (cat &optional nonum)
3599 "Insert button with category CAT's name and item counts.
3600 With non-nil argument NONUM show only these; otherwise, insert a
3601 number in front of the button indicating the category's priority.
3602 The number and the category name are separated by the string
3603 which is the value of the user option
3604 `todo-categories-number-separator'."
3605 (let ((archive (member todo-current-todo-file todo-archives))
3606 (num todo-categories-category-number)
3607 (str (todo-padded-string cat))
3609 (setq num (1+ num) todo-categories-category-number num)
3612 (make-string (+ 4 (length todo-categories-number-separator))
3614 (format " %3d%s" num todo-categories-number-separator))
3616 (mapconcat (lambda (elt)
3618 (make-string (1+ (/ (length (car elt)) 2)) 32) ; label
3619 (format "%3d" (todo-get-count (cdr elt) cat)) ; count
3620 ;; Add an extra space if label length is odd.
3621 (when (cl-oddp (length (car elt))) " ")))
3623 (list (cons todo-categories-done-label 'done))
3624 (list (cons todo-categories-todo-label 'todo)
3625 (cons todo-categories-diary-label 'diary)
3626 (cons todo-categories-done-label 'done)
3627 (cons todo-categories-archived-label
3630 " ") ; Make highlighting on last column look better.
3631 'face (if (and todo-skip-archived-categories
3632 (zerop (todo-get-count 'todo cat))
3633 (zerop (todo-get-count 'done cat))
3634 (not (zerop (todo-get-count 'archived cat))))
3637 'action `(lambda (button) (let ((buf (current-buffer)))
3638 (todo-jump-to-category nil ,cat)
3639 (kill-buffer buf))))
3640 ;; Highlight the sorted count column.
3641 (let* ((beg (+ opoint 7 (length str)))
3643 (cond ((eq nonum 'todo)
3644 (setq beg (+ beg 1 (/ (length todo-categories-todo-label) 2))))
3646 (setq beg (+ beg 1 (length todo-categories-todo-label)
3647 2 (/ (length todo-categories-diary-label) 2))))
3649 (setq beg (+ beg 1 (length todo-categories-todo-label)
3650 2 (length todo-categories-diary-label)
3651 2 (/ (length todo-categories-done-label) 2))))
3652 ((eq nonum 'archived)
3653 (setq beg (+ beg 1 (length todo-categories-todo-label)
3654 2 (length todo-categories-diary-label)
3655 2 (length todo-categories-done-label)
3656 2 (/ (length todo-categories-archived-label) 2)))))
3657 (unless (= beg (+ opoint 7 (length str))) ; Don't highlight categories.
3658 (setq end (+ beg 4))
3659 (setq ovl (make-overlay beg end))
3660 (overlay-put ovl 'face 'todo-sorted-column)))
3663 (defun todo-display-categories ()
3664 "Prepare buffer for displaying table of categories and item counts."
3665 (unless (eq major-mode 'todo-categories-mode)
3666 (setq todo-global-current-todo-file
3667 (or todo-current-todo-file
3668 (todo-absolute-file-name todo-default-todo-file)))
3669 (set-window-buffer (selected-window)
3670 (set-buffer (get-buffer-create todo-categories-buffer)))
3671 (kill-all-local-variables)
3672 (todo-categories-mode)
3673 (let ((archive (member todo-current-todo-file todo-archives))
3676 (insert (format (concat "Category counts for todo "
3677 (if archive "archive" "file")
3679 (todo-short-file-name todo-current-todo-file)))
3681 ;; Make space for the column of category numbers.
3682 (insert (make-string (+ 4 (length todo-categories-number-separator)) 32))
3683 ;; Add the category and item count buttons (if this is the list of
3684 ;; categories in an archive, show only done item counts).
3685 (todo-insert-sort-button todo-categories-category-label)
3688 (insert (make-string 3 32))
3689 (todo-insert-sort-button todo-categories-done-label))
3690 (insert (make-string 3 32))
3691 (todo-insert-sort-button todo-categories-todo-label)
3692 (insert (make-string 2 32))
3693 (todo-insert-sort-button todo-categories-diary-label)
3694 (insert (make-string 2 32))
3695 (todo-insert-sort-button todo-categories-done-label)
3696 (insert (make-string 2 32))
3697 (todo-insert-sort-button todo-categories-archived-label))
3700 (defun todo-update-categories-display (sortkey)
3701 "Populate table of categories and sort by SORTKEY."
3702 (let* ((cats0 todo-categories)
3703 (cats (todo-sort cats0 sortkey))
3704 (archive (member todo-current-todo-file todo-archives))
3705 (todo-categories-category-number 0)
3706 ;; Find start of Category button if we just entered Todo Categories
3708 (pt (if (eq (point) (point-max))
3711 (goto-char (next-single-char-property-change
3712 (point) 'face nil (line-end-position))))))
3715 (delete-region (point) (point-max))
3716 ;; Fill in the table with buttonized lines, each showing a category and
3718 (mapc (lambda (cat) (todo-insert-category-line cat sortkey))
3721 ;; Add a line showing item count totals.
3722 (insert (make-string (+ 4 (length todo-categories-number-separator)) 32)
3723 (todo-padded-string todo-categories-totals-label)
3727 (make-string (1+ (/ (length (car elt)) 2)) 32)
3728 (format "%3d" (nth (cdr elt) (todo-total-item-counts)))
3729 ;; Add an extra space if label length is odd.
3730 (when (cl-oddp (length (car elt))) " ")))
3732 (list (cons todo-categories-done-label 2))
3733 (list (cons todo-categories-todo-label 0)
3734 (cons todo-categories-diary-label 1)
3735 (cons todo-categories-done-label 2)
3736 (cons todo-categories-archived-label 3)))
3738 ;; Put cursor on Category button initially.
3739 (if pt (goto-char pt))
3740 (setq buffer-read-only t)))
3742 ;; -----------------------------------------------------------------------------
3743 ;;; Searching and item filtering
3744 ;; -----------------------------------------------------------------------------
3746 (defun todo-search ()
3747 "Search for a regular expression in this todo file.
3748 The search runs through the whole file and encompasses all and
3749 only todo and done items; it excludes category names. Multiple
3750 matches are shown sequentially, highlighted in `todo-search'
3753 (let ((regex (read-from-minibuffer "Enter a search string (regexp): "))
3755 matches match cat in-done ov mlen msg)
3757 (goto-char (point-min))
3759 (setq match (re-search-forward regex nil t))
3760 (goto-char (line-beginning-position))
3761 (unless (or (equal (point) 1)
3762 (looking-at (concat "^" (regexp-quote todo-category-beg))))
3763 (if match (push match matches)))
3765 (setq matches (reverse matches))
3769 (setq match (pop matches))
3772 (when (looking-at todo-done-string-start)
3774 (re-search-backward (concat "^" (regexp-quote todo-category-beg)
3775 "\\(.*\\)\n") nil t)
3776 (setq cat (match-string-no-properties 1))
3777 (todo-category-number cat)
3778 (todo-category-select)
3780 (unless todo-show-with-done (todo-toggle-view-done-items)))
3782 (setq ov (make-overlay (- (point) (length regex)) (point)))
3783 (overlay-put ov 'face 'todo-search)
3785 (setq mlen (length matches))
3788 (format "There are %d more matches; go to next match? "
3790 "There is one more match; go to it? "))
3792 (throw 'stop (setq msg (if (> mlen 1)
3793 (format "There are %d more matches."
3795 "There is one more match."))))))
3796 (setq msg "There are no more matches."))
3797 (todo-category-select)
3799 (message "No match for \"%s\"" regex))
3801 (if (todo-y-or-n-p (concat msg "\nUnhighlight matches? "))
3802 (todo-clear-matches)
3803 (message "You can unhighlight the matches later by typing %s"
3804 (key-description (car (where-is-internal
3805 'todo-clear-matches))))))))
3807 (defun todo-clear-matches ()
3808 "Remove highlighting on matches found by todo-search."
3810 (remove-overlays 1 (1+ (buffer-size)) 'face 'todo-search))
3812 (defcustom todo-top-priorities-overrides nil
3813 "List of rules specifying number of top priority items to show.
3814 These rules override `todo-top-priorities' on invocations of
3815 `\\[todo-filter-top-priorities]' and
3816 `\\[todo-filter-top-priorities-multifile]'. Each rule is a list
3817 of the form (FILE NUM ALIST), where FILE is a member of
3818 `todo-files', NUM is a number specifying the default number of
3819 top priority items for each category in that file, and ALIST,
3820 when non-nil, consists of conses of a category name in FILE and a
3821 number specifying the default number of top priority items in
3822 that category, which overrides NUM.
3824 This variable should be set interactively by
3825 `\\[todo-set-top-priorities-in-file]' or
3826 `\\[todo-set-top-priorities-in-category]'."
3828 :group 'todo-filtered)
3830 (defcustom todo-top-priorities 1
3831 "Default number of top priorities shown by `todo-filter-top-priorities'."
3833 :group 'todo-filtered)
3835 (defcustom todo-filter-files nil
3836 "List of default files for multifile item filtering."
3837 :type `(set ,@(mapcar (lambda (f) (list 'const f))
3838 (mapcar 'todo-short-file-name
3839 (funcall todo-files-function))))
3840 :group 'todo-filtered)
3842 (defcustom todo-filter-done-items nil
3843 "Non-nil to include done items when processing regexp filters.
3844 Done items from corresponding archive files are also included."
3846 :group 'todo-filtered)
3848 (defun todo-set-top-priorities-in-file ()
3849 "Set number of top priorities for this file.
3850 See `todo-set-top-priorities' for more details."
3852 (todo-set-top-priorities))
3854 (defun todo-set-top-priorities-in-category ()
3855 "Set number of top priorities for this category.
3856 See `todo-set-top-priorities' for more details."
3858 (todo-set-top-priorities t))
3860 (defun todo-filter-top-priorities (&optional arg)
3861 "Display a list of top priority items from different categories.
3862 The categories can be any of those in the current todo file.
3864 With numerical prefix ARG show at most ARG top priority items
3865 from each category. With `C-u' as prefix argument show the
3866 numbers of top priority items specified by category in
3867 `todo-top-priorities-overrides', if this has an entry for the file(s);
3868 otherwise show `todo-top-priorities' items per category in the
3869 file(s). With no prefix argument, if a top priorities file for
3870 the current todo file has previously been saved (see
3871 `todo-save-filtered-items-buffer'), visit this file; if there is
3872 no such file, build the list as with prefix argument `C-u'.
3874 The prefix ARG regulates how many top priorities from
3875 each category to show, as described above."
3877 (todo-filter-items 'top arg))
3879 (defun todo-filter-top-priorities-multifile (&optional arg)
3880 "Display a list of top priority items from different categories.
3881 The categories are a subset of the categories in the files listed
3882 in `todo-filter-files', or if this nil, in the files chosen from
3883 a file selection dialog that pops up in this case.
3885 With numerical prefix ARG show at most ARG top priority items
3886 from each category in each file. With `C-u' as prefix argument
3887 show the numbers of top priority items specified in
3888 `todo-top-priorities-overrides', if this is non-nil; otherwise show
3889 `todo-top-priorities' items per category. With no prefix
3890 argument, if a top priorities file for the chosen todo files
3891 exists (see `todo-save-filtered-items-buffer'), visit this file;
3892 if there is no such file, do the same as with prefix argument
3895 (todo-filter-items 'top arg t))
3897 (defun todo-filter-diary-items (&optional arg)
3898 "Display a list of todo diary items from different categories.
3899 The categories can be any of those in the current todo file.
3901 Called with no prefix ARG, if a diary items file for the current
3902 todo file has previously been saved (see
3903 `todo-save-filtered-items-buffer'), visit this file; if there is
3904 no such file, build the list of diary items. Called with a
3905 prefix argument, build the list even if there is a saved file of
3908 (todo-filter-items 'diary arg))
3910 (defun todo-filter-diary-items-multifile (&optional arg)
3911 "Display a list of todo diary items from different categories.
3912 The categories are a subset of the categories in the files listed
3913 in `todo-filter-files', or if this nil, in the files chosen from
3914 a file selection dialog that pops up in this case.
3916 Called with no prefix ARG, if a diary items file for the chosen
3917 todo files has previously been saved (see
3918 `todo-save-filtered-items-buffer'), visit this file; if there is
3919 no such file, build the list of diary items. Called with a
3920 prefix argument, build the list even if there is a saved file of
3923 (todo-filter-items 'diary arg t))
3925 (defun todo-filter-regexp-items (&optional arg)
3926 "Prompt for a regular expression and display items that match it.
3927 The matches can be from any categories in the current todo file
3928 and with non-nil option `todo-filter-done-items', can include
3929 not only todo items but also done items, including those in
3932 Called with no prefix ARG, if a regexp items file for the current
3933 todo file has previously been saved (see
3934 `todo-save-filtered-items-buffer'), visit this file; if there is
3935 no such file, build the list of regexp items. Called with a
3936 prefix argument, build the list even if there is a saved file of
3939 (todo-filter-items 'regexp arg))
3941 (defun todo-filter-regexp-items-multifile (&optional arg)
3942 "Prompt for a regular expression and display items that match it.
3943 The matches can be from any categories in the files listed in
3944 `todo-filter-files', or if this nil, in the files chosen from a
3945 file selection dialog that pops up in this case. With non-nil
3946 option `todo-filter-done-items', the matches can include not
3947 only todo items but also done items, including those in Archive
3950 Called with no prefix ARG, if a regexp items file for the current
3951 todo file has previously been saved (see
3952 `todo-save-filtered-items-buffer'), visit this file; if there is
3953 no such file, build the list of regexp items. Called with a
3954 prefix argument, build the list even if there is a saved file of
3957 (todo-filter-items 'regexp arg t))
3959 (defun todo-find-filtered-items-file ()
3960 "Choose a filtered items file and visit it."
3962 (let ((files (directory-files todo-directory t "\.tod[rty]$" t))
3965 (let ((type (cond ((equal (file-name-extension f) "todr") "regexp")
3966 ((equal (file-name-extension f) "todt") "top")
3967 ((equal (file-name-extension f) "tody") "diary"))))
3968 (push (cons (concat (todo-short-file-name f) " (" type ")") f)
3970 (setq file (completing-read "Choose a filtered items file: "
3971 falist nil t nil nil (car falist)))
3972 (setq file (cdr (assoc-string file falist)))
3974 (unless (derived-mode-p 'todo-filtered-items-mode)
3975 (todo-filtered-items-mode))))
3977 (defun todo-go-to-source-item ()
3978 "Display the file and category of the filtered item at point."
3980 (let* ((str (todo-item-string))
3981 (buf (current-buffer))
3982 (res (todo-find-item str))
3987 (message "Category %s does not contain this item." cat)
3989 (set-window-buffer (selected-window)
3990 (set-buffer (find-buffer-visiting file)))
3991 (setq todo-current-todo-file file)
3992 (setq todo-category-number (todo-category-number cat))
3993 (let ((todo-show-with-done (if (or todo-filter-done-items
3994 (eq (cdr found) 'done))
3996 todo-show-with-done)))
3997 (todo-category-select))
3998 (goto-char (car found)))))
4000 (defvar todo-multiple-filter-files nil
4001 "List of files selected from `todo-multiple-filter-files' widget.")
4003 (defvar todo-multiple-filter-files-widget nil
4004 "Variable holding widget created by `todo-multiple-filter-files'.")
4006 (defun todo-multiple-filter-files ()
4007 "Pop to a buffer with a widget for choosing multiple filter files."
4010 (require 'wid-edit))
4011 (with-current-buffer (get-buffer-create "*Todo Filter Files*")
4012 (pop-to-buffer (current-buffer))
4014 (kill-all-local-variables)
4015 (widget-insert "Select files for generating the top priorities list.\n\n")
4016 (setq todo-multiple-filter-files-widget
4018 `(set ,@(mapcar (lambda (x) (list 'const x))
4019 (mapcar 'todo-short-file-name
4020 (funcall todo-files-function))))))
4021 (widget-insert "\n")
4022 (widget-create 'push-button
4023 :notify (lambda (widget &rest ignore)
4024 (setq todo-multiple-filter-files 'quit)
4026 (exit-recursive-edit))
4029 (widget-create 'push-button
4030 :notify (lambda (&rest ignore)
4031 (setq todo-multiple-filter-files
4034 (concat todo-directory
4037 todo-multiple-filter-files-widget)))
4039 (exit-recursive-edit))
4041 (use-local-map widget-keymap)
4043 (message "Click \"Apply\" after selecting files.")
4046 (defconst todo-filtered-items-buffer "Todo filtered items"
4047 "Initial name of buffer in Todo Filter Items mode.")
4049 (defconst todo-top-priorities-buffer "Todo top priorities"
4050 "Buffer type string for `todo-filter-items'.")
4052 (defconst todo-diary-items-buffer "Todo diary items"
4053 "Buffer type string for `todo-filter-items'.")
4055 (defconst todo-regexp-items-buffer "Todo regexp items"
4056 "Buffer type string for `todo-filter-items'.")
4058 (defun todo-filter-items (filter &optional new multifile)
4059 "Display a list of items filtered by FILTER.
4060 The values of FILTER can be `top' for top priority items, a cons
4061 of `top' and a number passed by the caller, `diary' for diary
4062 items, or `regexp' for items matching a regular expression
4063 entered by the user. The items can come from any categories in
4064 the current todo file or, with non-nil MULTIFILE, from several
4065 files. If NEW is nil, visit an appropriate file containing the
4066 list of filtered items; if there is no such file, or with non-nil
4067 NEW, build the list and display it.
4069 See the documentation strings of the commands
4070 `todo-filter-top-priorities', `todo-filter-diary-items',
4071 `todo-filter-regexp-items', and those of the corresponding
4072 multifile commands for further details."
4073 (let* ((top (eq filter 'top))
4074 (diary (eq filter 'diary))
4075 (regexp (eq filter 'regexp))
4076 (buf (cond (top todo-top-priorities-buffer)
4077 (diary todo-diary-items-buffer)
4078 (regexp todo-regexp-items-buffer)))
4079 (flist (if multifile
4080 (or todo-filter-files
4081 (progn (todo-multiple-filter-files)
4082 todo-multiple-filter-files))
4083 (list todo-current-todo-file)))
4084 (multi (> (length flist) 1))
4085 (fname (if (equal flist 'quit)
4086 ;; Pressed `cancel' in t-m-f-f file selection dialog.
4088 (concat todo-directory
4089 (mapconcat 'todo-short-file-name flist "-")
4092 (regexp ".todr")))))
4093 (rxfiles (when regexp
4094 (directory-files todo-directory t ".*\\.todr$" t)))
4095 (file-exists (or (file-exists-p fname) rxfiles))
4097 (cond ((and top new (natnump new))
4098 (todo-filter-items-1 (cons 'top new) flist))
4099 ((and (not new) file-exists)
4100 (when (and rxfiles (> (length rxfiles) 1))
4101 (let ((rxf (mapcar 'todo-short-file-name rxfiles)))
4102 (setq fname (todo-absolute-file-name
4103 (completing-read "Choose a regexp items file: "
4106 (unless (derived-mode-p 'todo-filtered-items-mode)
4107 (todo-filtered-items-mode))
4108 (todo-prefix-overlays)
4109 (todo-check-filtered-items-file))
4111 (todo-filter-items-1 filter flist)))
4112 (dolist (s (split-string (todo-short-file-name fname) "-"))
4113 (setq bufname (if bufname
4114 (concat bufname (if (member s (mapcar
4115 'todo-short-file-name
4119 (rename-buffer (format (concat "%s for file" (if multi "s" "")
4120 " \"%s\"") buf bufname))))
4122 (defun todo-filter-items-1 (filter file-list)
4123 "Build a list of items by applying FILTER to FILE-LIST.
4124 Internal subroutine called by `todo-filter-items', which passes
4125 the values of FILTER and FILE-LIST."
4126 (let ((num (if (consp filter) (cdr filter) todo-top-priorities))
4127 (buf (get-buffer-create todo-filtered-items-buffer))
4128 (multifile (> (length file-list) 1))
4129 regexp fname bufstr cat beg end done)
4130 (if (null file-list)
4131 (user-error "No files have been chosen for filtering")
4132 (with-current-buffer buf
4134 (kill-all-local-variables)
4135 (todo-filtered-items-mode))
4136 (when (eq filter 'regexp)
4137 (setq regexp (read-string "Enter a regular expression: ")))
4138 (save-current-buffer
4139 (dolist (f file-list)
4140 ;; Before inserting file contents into temp buffer, save a modified
4141 ;; buffer visiting it.
4142 (let ((bf (find-buffer-visiting f)))
4143 (when (buffer-modified-p bf)
4144 (with-current-buffer bf (save-buffer))))
4145 (setq fname (todo-short-file-name f))
4147 (when (and todo-filter-done-items (eq filter 'regexp))
4148 ;; If there is a corresponding archive file for the
4149 ;; todo file, insert it first and add identifiers for
4150 ;; todo-go-to-source-item.
4151 (let ((arch (concat (file-name-sans-extension f) ".toda")))
4152 (when (file-exists-p arch)
4153 (insert-file-contents arch)
4154 ;; Delete todo archive file's categories sexp.
4155 (delete-region (line-beginning-position)
4156 (1+ (line-end-position)))
4159 (when (re-search-forward
4160 (concat (if todo-filter-done-items
4161 (concat "\\(?:" todo-done-string-start
4162 "\\|" todo-date-string-start
4164 todo-date-string-start)
4165 todo-date-pattern "\\(?: "
4166 diary-time-regexp "\\)?"
4167 (if todo-filter-done-items
4169 (regexp-quote todo-nondiary-end)) "?")
4171 (insert "(archive) "))
4173 (insert-file-contents f)
4174 ;; Delete todo file's categories sexp.
4175 (delete-region (line-beginning-position) (1+ (line-end-position)))
4177 ;; Unless the number of top priorities to show was
4178 ;; passed by the caller, the file-wide value from
4179 ;; `todo-top-priorities-overrides', if non-nil, overrides
4180 ;; `todo-top-priorities'.
4181 (unless (consp filter)
4182 (setq fnum (or (nth 1 (assoc f todo-top-priorities-overrides))
4183 todo-top-priorities)))
4184 (while (re-search-forward
4185 (concat "^" (regexp-quote todo-category-beg)
4186 "\\(.+\\)\n") nil t)
4187 (setq cat (match-string 1))
4189 ;; Unless the number of top priorities to show was
4190 ;; passed by the caller, the category-wide value
4191 ;; from `todo-top-priorities-overrides', if non-nil,
4192 ;; overrides a non-nil file-wide value from
4193 ;; `todo-top-priorities-overrides' as well as
4194 ;; `todo-top-priorities'.
4195 (unless (consp filter)
4196 (let ((cats (nth 2 (assoc f todo-top-priorities-overrides))))
4197 (setq cnum (or (cdr (assoc cat cats)) fnum))))
4198 (delete-region (match-beginning 0) (match-end 0))
4199 (setq beg (point)) ; First item in the current category.
4200 (setq end (if (re-search-forward
4201 (concat "^" (regexp-quote todo-category-beg))
4207 (if (re-search-forward
4208 (concat "\n" (regexp-quote todo-category-done))
4212 (unless (and todo-filter-done-items (eq filter 'regexp))
4213 ;; Leave done items.
4214 (delete-region done end)
4216 (narrow-to-region beg end) ; Process only current category.
4217 (goto-char (point-min))
4218 ;; Apply the filter.
4219 (cond ((eq filter 'diary)
4221 (if (looking-at (regexp-quote todo-nondiary-start))
4223 (todo-forward-item))))
4224 ((eq filter 'regexp)
4226 (if (looking-at todo-item-start)
4227 (if (string-match regexp (todo-item-string))
4230 ;; Kill lines that aren't part of a todo or done
4231 ;; item (empty or todo-category-done).
4232 (delete-region (line-beginning-position)
4233 (1+ (line-end-position))))
4234 ;; If last todo item in file matches regexp and
4235 ;; there are no following done items,
4236 ;; todo-category-done string is left dangling,
4237 ;; because todo-forward-item jumps over it.
4240 (concat (regexp-quote todo-done-string)
4242 (delete-region (point) (progn
4245 (t ; Filter top priority items.
4246 (setq num (or cnum fnum num))
4248 (todo-forward-item num))))
4250 ;; Delete non-top-priority items.
4251 (unless (member filter '(diary regexp))
4252 (delete-region beg end))
4253 (goto-char (point-min))
4254 ;; Add file (if using multiple files) and category tags to
4257 (when (re-search-forward
4258 (concat (if todo-filter-done-items
4259 (concat "\\(?:" todo-done-string-start
4260 "\\|" todo-date-string-start
4262 todo-date-string-start)
4263 todo-date-pattern "\\(?: " diary-time-regexp
4264 "\\)?" (if todo-filter-done-items
4266 (regexp-quote todo-nondiary-end))
4270 (when (looking-at "(archive) ") (goto-char (match-end 0)))
4271 (insert (if multifile (concat fname ":") "") cat "]"))
4274 (setq bufstr (buffer-string))
4275 (with-current-buffer buf
4276 (let (buffer-read-only)
4277 (insert bufstr)))))))
4278 (set-window-buffer (selected-window) (set-buffer buf))
4279 (todo-prefix-overlays)
4280 (goto-char (point-min)))))
4282 (defun todo-set-top-priorities (&optional arg)
4283 "Set number of top priorities shown by `todo-filter-top-priorities'.
4284 With non-nil ARG, set the number only for the current Todo
4285 category; otherwise, set the number for all categories in the
4288 Calling this function via either of the commands
4289 `todo-set-top-priorities-in-file' or
4290 `todo-set-top-priorities-in-category' is the recommended way to
4291 set the user customizable option `todo-top-priorities-overrides'."
4292 (let* ((cat (todo-current-category))
4293 (file todo-current-todo-file)
4294 (rules todo-top-priorities-overrides)
4295 (frule (assoc-string file rules))
4296 (crule (assoc-string cat (nth 2 frule)))
4297 (crules (nth 2 frule))
4298 (cur (or (if arg (cdr crule) (nth 1 frule))
4299 todo-top-priorities))
4300 (prompt (if arg (concat "Number of top priorities in this category"
4301 " (currently %d): ")
4302 (concat "Default number of top priorities per category"
4303 " in this file (currently %d): ")))
4308 (setq new (read-number (format prompt cur0))
4309 prompt "Enter a non-negative number: "
4312 (append (delete crule crules) (list (cons cat new)))
4313 (append (list file new) (list crules))))
4314 (setq rules (cons (if arg
4315 (list file cur nrule)
4317 (delete frule rules)))
4318 (customize-save-variable 'todo-top-priorities-overrides rules)
4319 (todo-prefix-overlays)))
4321 (defun todo-find-item (str)
4322 "Search for filtered item STR in its saved todo file.
4323 Return the list (FOUND FILE CAT), where CAT and FILE are the
4324 item's category and file, and FOUND is a cons cell if the search
4325 succeeds, whose car is the start of the item in FILE and whose
4326 cdr is `done', if the item is now a done item, `changed', if its
4327 text was truncated or augmented or, for a top priority item, if
4328 its priority has changed, and `same' otherwise."
4329 (string-match (concat (if todo-filter-done-items
4330 (concat "\\(?:" todo-done-string-start "\\|"
4331 todo-date-string-start "\\)")
4332 todo-date-string-start)
4333 todo-date-pattern "\\(?: " diary-time-regexp "\\)?"
4334 (if todo-filter-done-items
4336 (regexp-quote todo-nondiary-end)) "?"
4337 "\\(?4: \\[\\(?3:(archive) \\)?\\(?2:.*:\\)?"
4338 "\\(?1:.*\\)\\]\\).*$") str)
4339 (let ((cat (match-string 1 str))
4340 (file (match-string 2 str))
4341 (archive (string= (match-string 3 str) "(archive) "))
4342 (filcat (match-string 4 str))
4344 (tpbuf (save-match-data (string-match "top" (buffer-name))))
4346 (setq str (replace-match "" nil nil str 4))
4348 ;; Calculate priority of STR wrt its category.
4350 (while (search-backward filcat nil t)
4351 (setq tpriority (1+ tpriority)))))
4353 (concat todo-directory (substring file 0 -1)
4354 (if archive ".toda" ".todo"))
4356 (concat (file-name-sans-extension
4357 todo-global-current-todo-file) ".toda")
4358 todo-global-current-todo-file)))
4359 (find-file-noselect file)
4360 (with-current-buffer (find-buffer-visiting file)
4362 (unless (derived-mode-p 'todo-archive-mode) (todo-archive-mode))
4363 (unless (derived-mode-p 'todo-mode) (todo-mode)))
4366 (goto-char (point-min))
4367 (let ((beg (re-search-forward
4368 (concat "^" (regexp-quote (concat todo-category-beg cat))
4371 (done (save-excursion
4373 (concat "^" (regexp-quote todo-category-done)) nil t)))
4374 (end (save-excursion
4375 (or (re-search-forward
4376 (concat "^" (regexp-quote todo-category-beg))
4379 (setq found (when (search-forward str end t)
4380 (goto-char (match-beginning 0))))
4383 (cons found (if (> (point) done)
4385 (let ((cpriority 1))
4388 ;; Not top item in category.
4389 (while (> (point) (1+ beg))
4390 (let ((opoint (point)))
4391 (todo-backward-item)
4392 ;; Can't move backward beyond
4393 ;; first item in file.
4394 (unless (= (point) opoint)
4395 (setq cpriority (1+ cpriority)))))))
4396 (if (and (= tpriority cpriority)
4397 ;; Proper substring is not the same.
4398 (string= (todo-item-string)
4402 (list found file cat)))
4404 (defun todo-check-filtered-items-file ()
4405 "Check if filtered items file is up to date and a show suitable message."
4409 (let* ((item (todo-item-string))
4410 (found (car (todo-find-item item))))
4411 (unless (eq (cdr found) 'same)
4413 (overlay-put (make-overlay (todo-item-start) (todo-item-end))
4414 'face 'todo-search))
4415 (setq count (1+ count))))
4416 ;; (throw 'old (message "The marked item is not up to date.")))
4417 (todo-forward-item))
4419 (message "Filtered items file is up to date.")
4420 (message (concat "The highlighted item" (if (= count 1) " is " "s are ")
4422 ;; "\nType <return> on item for details."
4425 (defun todo-filter-items-filename ()
4426 "Return absolute file name for saving this Filtered Items buffer."
4427 (let ((bufname (buffer-name)))
4428 (string-match "\"\\([^\"]+\\)\"" bufname)
4429 (let* ((filename-str (substring bufname (match-beginning 1) (match-end 1)))
4430 (filename-base (replace-regexp-in-string ", " "-" filename-str))
4431 (top-priorities (string-match "top priorities" bufname))
4432 (diary-items (string-match "diary items" bufname))
4433 (regexp-items (string-match "regexp items" bufname)))
4435 (let ((prompt (concat "Enter a short identifying string"
4436 " to make this file name unique: ")))
4437 (setq filename-base (concat filename-base "-" (read-string prompt)))))
4438 (concat todo-directory filename-base
4439 (cond (top-priorities ".todt")
4440 (diary-items ".tody")
4441 (regexp-items ".todr"))))))
4443 (defun todo-save-filtered-items-buffer ()
4444 "Save current Filtered Items buffer to a file.
4445 If the file already exists, overwrite it only on confirmation."
4446 (let ((filename (or (buffer-file-name) (todo-filter-items-filename))))
4447 (write-file filename t)))
4449 ;; -----------------------------------------------------------------------------
4450 ;;; Printing Todo mode buffers
4451 ;; -----------------------------------------------------------------------------
4453 (defcustom todo-print-buffer-function 'ps-print-buffer-with-faces
4454 "Function called by the command `todo-print-buffer'."
4458 (defvar todo-print-buffer "*Todo Print*"
4459 "Name of buffer with printable version of Todo mode buffer.")
4461 (defun todo-print-buffer (&optional to-file)
4462 "Produce a printable version of the current Todo mode buffer.
4463 This converts overlays and soft line wrapping and, depending on
4464 the value of `todo-print-buffer-function', includes faces. With
4465 non-nil argument TO-FILE write the printable version to a file;
4466 otherwise, send it to the default printer."
4468 (let ((buf todo-print-buffer)
4470 ((eq major-mode 'todo-mode)
4471 (concat "Todo File: "
4472 (todo-short-file-name todo-current-todo-file)
4473 "\nCategory: " (todo-current-category)))
4474 ((eq major-mode 'todo-filtered-items-mode)
4476 (prefix (propertize (concat todo-prefix " ")
4477 'face 'todo-prefix-string))
4479 (fill-prefix (make-string todo-indent-to-here 32))
4480 (content (buffer-string))
4482 (with-current-buffer (get-buffer-create buf)
4484 (goto-char (point-min))
4487 (end (save-excursion (todo-item-end))))
4488 (when todo-number-prefix
4490 (setq prefix (propertize (concat (number-to-string num) " ")
4491 'face 'todo-prefix-string)))
4493 (fill-region beg end))
4494 ;; Calling todo-forward-item infloops at todo-item-start due to
4495 ;; non-overlay prefix, so search for item start instead.
4496 (if (re-search-forward todo-item-start nil t)
4498 (goto-char (point-max))))
4499 (if (re-search-backward (concat "^" (regexp-quote todo-category-done))
4501 (replace-match todo-done-separator))
4502 (goto-char (point-min))
4506 (let ((file (read-file-name "Print to file: ")))
4507 (funcall todo-print-buffer-function file))
4508 (funcall todo-print-buffer-function)))
4511 (defun todo-print-buffer-to-file ()
4512 "Save printable version of this Todo mode buffer to a file."
4514 (todo-print-buffer t))
4516 ;; -----------------------------------------------------------------------------
4517 ;;; Legacy Todo mode files
4518 ;; -----------------------------------------------------------------------------
4520 (defcustom todo-legacy-date-time-regexp
4521 (concat "\\(?1:[0-9]\\{4\\}\\)-\\(?2:[0-9]\\{2\\}\\)-"
4522 "\\(?3:[0-9]\\{2\\}\\) \\(?4:[0-9]\\{2\\}:[0-9]\\{2\\}\\)")
4523 "Regexp matching legacy todo-mode.el item date-time strings.
4524 In order for `todo-convert-legacy-files' to correctly convert
4525 this string to the current Todo mode format, the regexp must
4526 contain four explicitly numbered groups (see `(elisp) Regexp
4527 Backslash'), where group 1 matches a string for the year, group 2
4528 a string for the month, group 3 a string for the day and group 4
4529 a string for the time. The default value converts date-time
4530 strings built using the default value of
4531 `todo-time-string-format' from todo-mode.el."
4535 (defun todo-convert-legacy-date-time ()
4536 "Return converted date-time string.
4537 Helper function for `todo-convert-legacy-files'."
4538 (let* ((year (match-string 1))
4539 (month (match-string 2))
4540 (monthname (calendar-month-name (string-to-number month) t))
4541 (day (match-string 3))
4542 (time (match-string 4))
4545 (insert (mapconcat 'eval calendar-date-display-form "")
4546 (when time (concat " " time)))))
4548 (defun todo-convert-legacy-files ()
4549 "Convert legacy todo files to the current Todo mode format.
4550 The old-style files named by the variables `todo-file-do' and
4551 `todo-file-done' from the old package are converted to the new
4552 format and saved (the latter as a todo archive file) with a new
4553 name in `todo-directory'. See also the documentation string of
4554 `todo-legacy-date-time-regexp' for further details."
4556 ;; If there are user customizations of legacy options, use them,
4557 ;; otherwise use the legacy default values.
4558 (let ((todo-file-do-tem (if (boundp 'todo-file-do)
4560 (locate-user-emacs-file "todo-do" ".todo-do")))
4561 (todo-file-done-tem (if (boundp 'todo-file-done)
4563 (locate-user-emacs-file "todo-done" ".todo-done")))
4564 (todo-initials-tem (and (boundp 'todo-initials) todo-initials))
4565 (todo-entry-prefix-function-tem (and (boundp 'todo-entry-prefix-function)
4566 todo-entry-prefix-function))
4568 ;; Convert `todo-file-do'.
4569 (if (not (file-exists-p todo-file-do-tem))
4570 (message "No legacy todo file exists")
4571 (let ((default "todo-do-conv")
4574 (insert-file-contents todo-file-do-tem)
4575 ;; Eliminate old-style local variables list in first line.
4576 (delete-region (line-beginning-position) (1+ (line-end-position)))
4577 (search-forward " --- " nil t) ; Legacy todo-category-beg.
4578 (setq todo-prefix-tem (buffer-substring-no-properties
4579 (line-beginning-position) (match-beginning 0)))
4580 (goto-char (point-min))
4583 ;; Old-style category start delimiter.
4584 ((looking-at (regexp-quote (concat todo-prefix-tem " --- ")))
4585 (replace-match todo-category-beg))
4586 ;; Old-style category end delimiter.
4587 ((looking-at (regexp-quote "--- End"))
4589 ;; Old-style category separator.
4590 ((looking-at (regexp-quote
4591 (concat todo-prefix-tem " "
4592 (make-string 75 ?-))))
4593 (replace-match todo-category-done))
4594 ;; Old-style item header (date/time/initials).
4595 ((looking-at (concat (regexp-quote todo-prefix-tem) " "
4596 (if todo-entry-prefix-function-tem
4597 (funcall todo-entry-prefix-function-tem)
4598 (concat todo-legacy-date-time-regexp " "
4599 (if todo-initials-tem
4600 (regexp-quote todo-initials-tem)
4603 (todo-convert-legacy-date-time)))
4605 (setq file (concat todo-directory
4607 (format "Save file as (default \"%s\"): " default)
4610 (unless (file-exists-p todo-directory)
4611 (make-directory todo-directory))
4612 (write-region (point-min) (point-max) file nil 'nomessage nil t))
4614 (insert-file-contents file)
4615 (let ((todo-categories (todo-make-categories-list t)))
4616 (todo-update-categories-sexp)
4617 (todo-check-format))
4618 (write-region (point-min) (point-max) file nil 'nomessage))
4619 (setq todo-files (funcall todo-files-function))
4620 ;; Convert `todo-file-done'.
4621 (when (file-exists-p todo-file-done-tem)
4623 (insert-file-contents todo-file-done-tem)
4624 (let ((beg (make-marker))
4626 cat cats comment item)
4628 (when (looking-at todo-legacy-date-time-regexp)
4629 (set-marker beg (point))
4630 (todo-convert-legacy-date-time)
4631 (set-marker end (point))
4633 (insert "[" todo-done-string)
4637 (when (looking-at todo-legacy-date-time-regexp)
4638 (todo-convert-legacy-date-time))
4639 (when (looking-at (concat " " (if todo-initials-tem
4644 (replace-match "")))
4645 (if (re-search-forward
4646 (concat "^" todo-legacy-date-time-regexp) nil t)
4647 (goto-char (match-beginning 0))
4648 (goto-char (point-max)))
4650 (when (looking-back "\\[\\([^][]+\\)\\]")
4651 (setq cat (match-string 1))
4652 (goto-char (match-beginning 0))
4654 ;; If the item ends with a non-comment parenthesis not
4655 ;; followed by a period, we lose (but we inherit that
4656 ;; problem from the legacy code).
4657 (when (looking-back "(\\(.*\\)) ")
4658 (setq comment (match-string 1))
4660 (insert "[" todo-comment-string ": " comment "]"))
4661 (set-marker end (point))
4662 (if (member cat cats)
4663 ;; If item is already in its category, leave it there.
4664 (unless (save-excursion
4666 (concat "^" (regexp-quote todo-category-beg)
4668 (string= (match-string 1) cat))
4669 ;; Else move it to its category.
4670 (setq item (buffer-substring-no-properties beg end))
4671 (delete-region beg (1+ end))
4672 (set-marker beg (point))
4675 (regexp-quote (concat todo-category-beg cat))
4679 (if (re-search-forward
4680 (concat "^" (regexp-quote todo-category-beg)
4682 (progn (goto-char (match-beginning 0))
4685 (goto-char (point-max)))
4690 (insert todo-category-beg cat "\n\n"
4691 todo-category-done "\n"))
4693 (set-marker beg nil)
4694 (set-marker end nil))
4695 (setq file (concat (file-name-sans-extension file) ".toda"))
4696 (write-region (point-min) (point-max) file nil 'nomessage nil t))
4698 (insert-file-contents file)
4699 (let* ((todo-categories (todo-make-categories-list t)))
4700 (todo-update-categories-sexp)
4701 (todo-check-format))
4702 (write-region (point-min) (point-max) file nil 'nomessage)
4703 (setq archive-sexp (read (buffer-substring-no-properties
4704 (line-beginning-position)
4705 (line-end-position)))))
4706 (setq file (concat (file-name-sans-extension file) ".todo"))
4707 ;; Update categories sexp of converted todo file again, adding
4708 ;; counts of archived items.
4710 (insert-file-contents file)
4711 (let ((sexp (read (buffer-substring-no-properties
4712 (line-beginning-position)
4713 (line-end-position)))))
4715 (let ((archive-cat (assoc (car cat) archive-sexp)))
4717 (aset (cdr cat) 3 (aref (cdr archive-cat) 2)))))
4718 (delete-region (line-beginning-position) (line-end-position))
4719 (prin1 sexp (current-buffer)))
4720 (write-region (point-min) (point-max) file nil 'nomessage))
4721 (setq todo-archives (funcall todo-files-function t)))
4722 (todo-reevaluate-filelist-defcustoms)
4723 (when (y-or-n-p (concat "Format conversion done; do you want to "
4724 "visit the converted file now? "))
4725 (setq todo-current-todo-file file)
4726 (unless todo-default-todo-file
4727 ;; We just initialized the first todo file, so make it the
4728 ;; default now to avoid an infinite recursion with todo-show.
4729 (setq todo-default-todo-file (todo-short-file-name file)))
4732 ;; -----------------------------------------------------------------------------
4733 ;;; Utility functions for todo files, categories and items
4734 ;; -----------------------------------------------------------------------------
4736 (defun todo-absolute-file-name (name &optional type)
4737 "Return the absolute file name of short todo file NAME.
4738 With TYPE `archive' or `top' return the absolute file name of the
4739 short todo archive or top priorities file name, respectively."
4740 ;; No-op if there is no todo file yet (i.e. don't concatenate nil).
4743 (concat todo-directory name
4744 (cond ((eq type 'archive) ".toda")
4745 ((eq type 'top) ".todt")
4746 ((eq type 'diary) ".tody")
4747 ((eq type 'regexp) ".todr")
4750 (defun todo-check-file (file)
4751 "Check the state associated with FILE and update it if necessary.
4752 If FILE exists, return t. If it does not exist and there is no
4753 live buffer with its content, return nil; if there is such a
4754 buffer and the user tries to show it, ask whether to restore
4755 FILE, and if confirmed, do so and return t; else delete the
4756 buffer, clean up the state and return nil."
4757 (setq todo-files (funcall todo-files-function))
4758 (setq todo-archives (funcall todo-files-function t))
4759 (if (file-exists-p file)
4761 (setq todo-visited (delete file todo-visited))
4762 (let ((buf (find-buffer-visiting file)))
4766 (format (concat "Todo file \"%s\" has been deleted but "
4767 "its content is still in a buffer!\n")
4768 (todo-short-file-name file))
4769 "Save that buffer and restore the todo file? ")))
4771 (with-current-buffer buf (save-buffer))
4772 (setq todo-files (funcall todo-files-function))
4773 (setq todo-archives (funcall todo-files-function t))
4775 (let* ((files (append todo-files todo-archives))
4776 (tctf todo-current-todo-file)
4777 (tgctf todo-global-current-todo-file)
4778 (tdtf (todo-absolute-file-name todo-default-todo-file)))
4779 (unless (or (not todo-current-todo-file)
4780 (member todo-current-todo-file files))
4781 (setq todo-current-todo-file nil))
4782 (unless (or (not todo-global-current-todo-file)
4783 (member todo-global-current-todo-file files))
4784 (setq todo-global-current-todo-file nil))
4785 (unless (or (not todo-default-todo-file)
4786 (member todo-default-todo-file files))
4787 (setq todo-default-todo-file (todo-short-file-name
4789 (todo-reevaluate-filelist-defcustoms)
4790 (when buf (kill-buffer buf))
4793 (defun todo-category-number (cat)
4794 "Return the number of category CAT in this todo file.
4795 The buffer-local variable `todo-category-number' holds this
4796 number as its value."
4797 (let ((categories (mapcar 'car todo-categories)))
4798 (setq todo-category-number
4799 ;; Increment by one, so that the number of the first
4800 ;; category is one rather than zero.
4801 (1+ (- (length categories)
4802 (length (member cat categories)))))))
4804 (defun todo-current-category ()
4805 "Return the name of the current category."
4806 (car (nth (1- todo-category-number) todo-categories)))
4808 (defun todo-category-select ()
4809 "Display the current category correctly."
4810 (let ((name (todo-current-category))
4811 cat-begin cat-end done-start done-sep-start done-end)
4813 (goto-char (point-min))
4815 (concat "^" (regexp-quote (concat todo-category-beg name)) "$") nil t)
4816 (setq cat-begin (1+ (line-end-position)))
4817 (setq cat-end (if (re-search-forward
4818 (concat "^" (regexp-quote todo-category-beg)) nil t)
4821 (setq mode-line-buffer-identification
4822 (funcall todo-mode-line-function name))
4823 (narrow-to-region cat-begin cat-end)
4824 (todo-prefix-overlays)
4825 (goto-char (point-min))
4826 (if (re-search-forward (concat "\n\\(" (regexp-quote todo-category-done)
4829 (setq done-start (match-beginning 0))
4830 (setq done-sep-start (match-beginning 1))
4831 (setq done-end (match-end 0)))
4832 (error "Category %s is missing todo-category-done string" name))
4833 (if todo-show-done-only
4834 (narrow-to-region (1+ done-end) (point-max))
4835 (when (and todo-show-with-done
4836 (re-search-forward todo-done-string-start nil t))
4837 ;; Now we want to see the done items, so reset displayed end to end of
4839 (setq done-start cat-end)
4840 ;; Make display overlay for done items separator string, unless there
4842 (let* ((done-sep todo-done-separator)
4843 (ov (progn (goto-char done-sep-start)
4844 (todo-get-overlay 'separator))))
4846 (setq ov (make-overlay done-sep-start done-end))
4847 (overlay-put ov 'todo 'separator)
4848 (overlay-put ov 'display done-sep))))
4849 (narrow-to-region (point-min) done-start)
4850 ;; Loading this from todo-mode, or adding it to the mode hook, causes
4851 ;; Emacs to hang in todo-item-start, at (looking-at todo-item-start).
4852 (when todo-highlight-item
4854 (hl-line-mode 1)))))
4856 (defun todo-get-count (type &optional category)
4857 "Return count of TYPE items in CATEGORY.
4858 If CATEGORY is nil, default to the current category."
4859 (let* ((cat (or category (todo-current-category)))
4860 (counts (cdr (assoc cat todo-categories)))
4861 (idx (cond ((eq type 'todo) 0)
4862 ((eq type 'diary) 1)
4864 ((eq type 'archived) 3))))
4867 (defun todo-update-count (type increment &optional category)
4868 "Change count of TYPE items in CATEGORY by integer INCREMENT.
4869 With nil or omitted CATEGORY, default to the current category."
4870 (let* ((cat (or category (todo-current-category)))
4871 (counts (cdr (assoc cat todo-categories)))
4872 (idx (cond ((eq type 'todo) 0)
4873 ((eq type 'diary) 1)
4875 ((eq type 'archived) 3))))
4876 (aset counts idx (+ increment (aref counts idx)))))
4878 (defun todo-set-categories ()
4879 "Set `todo-categories' from the sexp at the top of the file."
4880 ;; New archive files created by `todo-move-category' are empty, which would
4881 ;; make the sexp test fail and raise an error, so in this case we skip it.
4882 (unless (zerop (buffer-size))
4886 (goto-char (point-min))
4887 (setq todo-categories
4888 (if (looking-at "\(\(\"")
4889 (read (buffer-substring-no-properties
4890 (line-beginning-position)
4891 (line-end-position)))
4892 (error "Invalid or missing todo-categories sexp")))))))
4894 (defun todo-update-categories-sexp ()
4895 "Update the `todo-categories' sexp at the top of the file."
4896 (let (buffer-read-only)
4900 (goto-char (point-min))
4901 (if (looking-at (concat "^" (regexp-quote todo-category-beg)))
4902 (progn (newline) (goto-char (point-min)) ; Make space for sexp.
4903 (setq todo-categories (todo-make-categories-list t)))
4904 (delete-region (line-beginning-position) (line-end-position)))
4905 (prin1 todo-categories (current-buffer))))))
4907 (defun todo-make-categories-list (&optional force)
4908 "Return an alist of todo categories and their item counts.
4909 With non-nil argument FORCE parse the entire file to build the
4910 list; otherwise, get the value by reading the sexp at the top of
4912 (setq todo-categories nil)
4916 (goto-char (point-min))
4917 (let (counts cat archive)
4918 ;; If the file is a todo file and has archived items, identify the
4919 ;; archive, in order to count its items. But skip this with
4920 ;; `todo-convert-legacy-files', since that converts filed items to
4922 (when buffer-file-name ; During conversion there is no file yet.
4923 ;; If the file is an archive, it doesn't have an archive.
4924 (unless (member (file-truename buffer-file-name)
4925 (funcall todo-files-function t))
4926 (setq archive (concat (file-name-sans-extension
4927 todo-current-todo-file) ".toda"))))
4929 (cond ((looking-at (concat (regexp-quote todo-category-beg)
4931 (setq cat (match-string-no-properties 1))
4932 ;; Counts for each category: [todo diary done archive]
4933 (setq counts (make-vector 4 0))
4934 (setq todo-categories
4935 (append todo-categories (list (cons cat counts))))
4936 ;; Add archived item count to the todo file item counts.
4937 ;; Make sure to include newly created archives, e.g. due to
4938 ;; todo-move-category.
4939 (when (member archive (funcall todo-files-function t))
4940 (let ((archive-count 0)
4941 (visiting (find-buffer-visiting archive)))
4942 (with-current-buffer (or visiting
4943 (find-file-noselect archive))
4947 (goto-char (point-min))
4948 (when (re-search-forward
4949 (concat "^" (regexp-quote todo-category-beg)
4953 (while (not (or (looking-at
4955 (regexp-quote todo-category-beg)
4958 (when (looking-at todo-done-string-start)
4959 (setq archive-count (1+ archive-count)))
4961 (unless visiting (kill-buffer)))
4962 (todo-update-count 'archived archive-count cat))))
4963 ((looking-at todo-done-string-start)
4964 (todo-update-count 'done 1 cat))
4965 ((looking-at (concat "^\\("
4966 (regexp-quote diary-nonmarking-symbol)
4967 "\\)?" todo-date-pattern))
4968 (todo-update-count 'diary 1 cat)
4969 (todo-update-count 'todo 1 cat))
4970 ((looking-at (concat todo-date-string-start todo-date-pattern))
4971 (todo-update-count 'todo 1 cat))
4972 ;; If first line is todo-categories list, use it and end loop
4973 ;; -- unless FORCEd to scan whole file.
4976 (setq todo-categories (read (buffer-substring-no-properties
4977 (line-beginning-position)
4978 (line-end-position))))
4979 (goto-char (1- (point-max))))))
4983 (defun todo-repair-categories-sexp ()
4984 "Repair corrupt todo file categories sexp.
4985 This should only be needed as a consequence of careless manual
4986 editing or a bug in todo.el.
4988 *Warning*: Calling this command restores the category order to
4989 the list element order in the todo file categories sexp, so any
4990 order changes made in Todo Categories mode will have to be made
4993 (let ((todo-categories (todo-make-categories-list t)))
4994 (todo-update-categories-sexp)))
4996 (defun todo-check-format ()
4997 "Signal an error if the current todo file is ill-formatted.
4998 Otherwise return t. Display a message if the file is well-formed
4999 but the categories sexp differs from the current value of
5004 (goto-char (point-min))
5005 (let* ((cats (prin1-to-string todo-categories))
5006 (ssexp (buffer-substring-no-properties (line-beginning-position)
5007 (line-end-position)))
5008 (sexp (read ssexp)))
5009 ;; Check the first line for `todo-categories' sexp.
5012 (unless (and (stringp (car c))
5015 (user-error "Invalid or missing todo-categories sexp"))))
5017 ;; Check well-formedness of categories.
5018 (let ((legit (concat
5019 "\\(^" (regexp-quote todo-category-beg) "\\)"
5020 "\\|\\(" todo-date-string-start todo-date-pattern "\\)"
5021 "\\|\\(^[ \t]+[^ \t]*\\)"
5023 "\\|\\(^" (regexp-quote todo-category-done) "\\)"
5024 "\\|\\(" todo-done-string-start "\\)")))
5026 (unless (looking-at legit)
5027 (user-error "Illegitimate todo file format at line %d"
5028 (line-number-at-pos (point))))
5030 ;; Warn user if categories sexp has changed.
5031 (unless (string= ssexp cats)
5032 (message (concat "The sexp at the beginning of the file differs "
5033 "from the value of `todo-categories.\n"
5034 "If the sexp is wrong, you can fix it with "
5035 "M-x todo-repair-categories-sexp,\n"
5036 "but note this reverts any changes you have "
5037 "made in the order of the categories."))))))
5040 (defun todo-item-start ()
5041 "Move to start of current todo item and return its position."
5043 ;; Buffer is empty (invocation possible e.g. via todo-forward-item
5044 ;; from todo-filter-items when processing category with no todo
5046 (eq (point-min) (point-max))
5047 ;; Point is on the empty line below category's last todo item...
5048 (and (looking-at "^$")
5049 (or (eobp) ; ...and done items are hidden...
5050 (save-excursion ; ...or done items are visible.
5052 (looking-at (concat "^"
5053 (regexp-quote todo-category-done))))))
5054 ;; Buffer is widened.
5055 (looking-at (regexp-quote todo-category-beg)))
5056 (goto-char (line-beginning-position))
5057 (while (not (looking-at todo-item-start))
5061 (defun todo-item-end ()
5062 "Move to end of current todo item and return its position."
5063 ;; Items cannot end with a blank line.
5064 (unless (looking-at "^$")
5065 (let* ((done (todo-done-item-p))
5067 ;; For todo items, end is before the done items section, for done
5068 ;; items, end is before the next category. If these limits are
5069 ;; missing or inaccessible, end it before the end of the buffer.
5070 (lim (if (save-excursion
5072 (concat "^" (regexp-quote (if done
5074 todo-category-done)))
5076 (progn (setq to-lim t) (match-beginning 0))
5078 (when (bolp) (forward-char)) ; Find start of next item.
5079 (goto-char (if (re-search-forward todo-item-start lim t)
5081 (if to-lim lim (point-max))))
5082 ;; For last todo item, skip back over the empty line before the done
5083 ;; items section, else just back to the end of the previous line.
5084 (backward-char (when (and to-lim (not done) (eq (point) lim)) 2))
5087 (defun todo-item-string ()
5088 "Return bare text of current item as a string."
5089 (let ((opoint (point))
5090 (start (todo-item-start))
5091 (end (todo-item-end)))
5093 (and start end (buffer-substring-no-properties start end))))
5095 (defun todo-forward-item (&optional count)
5096 "Move point COUNT items down (by default, move down by one item)."
5097 (let* ((not-done (not (or (todo-done-item-p) (looking-at "^$"))))
5098 (start (line-end-position)))
5100 (if (re-search-forward todo-item-start nil t (or count 1))
5101 (goto-char (match-beginning 0))
5102 (goto-char (point-max)))
5103 ;; If points advances by one from a todo to a done item, go back
5104 ;; to the space above todo-done-separator, since that is a
5105 ;; legitimate place to insert an item. But skip this space if
5106 ;; count > 1, since that should only stop on an item.
5107 (when (and not-done (todo-done-item-p) (not count))
5108 ;; (if (or (not count) (= count 1))
5109 (re-search-backward "^$" start t))));)
5110 ;; The preceding sexp is insufficient when buffer is not narrowed,
5111 ;; since there could be no done items in this category, so the
5112 ;; search puts us on first todo item of next category. Does this
5113 ;; ever happen? If so:
5114 ;; (let ((opoint) (point))
5115 ;; (forward-line -1)
5116 ;; (when (or (not count) (= count 1))
5117 ;; (cond ((looking-at (concat "^" (regexp-quote todo-category-beg)))
5118 ;; (forward-line -2))
5119 ;; ((looking-at (concat "^" (regexp-quote todo-category-done)))
5120 ;; (forward-line -1))
5122 ;; (goto-char opoint)))))))
5124 (defun todo-backward-item (&optional count)
5125 "Move point up to start of item with next higher priority.
5126 With positive numerical prefix COUNT, move point COUNT items
5129 If the category's done items are visible, this command called
5130 with a prefix argument only moves point to a higher item, e.g.,
5131 with point on the first done item and called with prefix 1, it
5132 moves to the last todo item; but if called with point on the
5133 first done item without a prefix argument, it moves point the the
5134 empty line above the done items separator."
5135 (let* ((done (todo-done-item-p)))
5138 (re-search-backward todo-item-start nil t (or count 1)))
5139 ;; Unless this is a regexp filtered items buffer (which can contain
5140 ;; intermixed todo and done items), if points advances by one from a
5141 ;; done to a todo item, go back to the space above
5142 ;; todo-done-separator, since that is a legitimate place to insert an
5143 ;; item. But skip this space if count > 1, since that should only
5145 (when (and done (not (todo-done-item-p)) (not count)
5146 ;(or (not count) (= count 1))
5147 (not (equal (buffer-name) todo-regexp-items-buffer)))
5148 (re-search-forward (concat "^" (regexp-quote todo-category-done))
5150 (forward-line -1))))
5152 (defun todo-remove-item ()
5153 "Internal function called in editing, deleting or moving items."
5154 (let* ((end (progn (todo-item-end) (1+ (point))))
5155 (beg (todo-item-start))
5156 (ov (todo-get-overlay 'prefix)))
5157 (when ov (delete-overlay ov))
5158 (delete-region beg end)))
5160 (defun todo-diary-item-p ()
5161 "Return non-nil if item at point has diary entry format."
5163 (when (todo-item-string) ; Exclude empty lines.
5165 (not (looking-at (regexp-quote todo-nondiary-start))))))
5167 ;; This duplicates the item locating code from diary-goto-entry, but
5168 ;; without the marker code, to test whether the latter is dispensable.
5169 ;; If it is, diary-goto-entry can be simplified. The code duplication
5170 ;; here can also be eliminated, leaving only the widening and category
5171 ;; selection, and instead of :override advice :around can be used.
5173 (defun todo-diary-goto-entry (button)
5174 "Jump to the diary entry for the BUTTON at point.
5175 If the entry is a todo item, display its category properly.
5176 Overrides `diary-goto-entry'."
5177 ;; Locate the diary item in its source file.
5178 (let* ((locator (button-get button 'locator))
5179 (file (cadr locator))
5180 (date (regexp-quote (nth 2 locator)))
5181 (content (regexp-quote (nth 3 locator))))
5182 (if (not (and (file-exists-p file)
5183 (find-file-other-window file)))
5184 (message "Unable to locate this diary entry")
5185 ;; If it's a Todo file, make sure it's in Todo mode.
5186 (when (and (equal (file-name-directory (file-truename file))
5187 (file-truename todo-directory))
5188 (not (derived-mode-p 'todo-mode)))
5190 (when (eq major-mode 'todo-mode) (widen))
5191 (goto-char (point-min))
5192 (when (re-search-forward (format "%s.*\\(%s\\)" date content) nil t)
5193 (goto-char (match-beginning 1)))
5194 ;; If it's a todo item, determine its category and display the
5195 ;; category properly.
5196 (when (eq major-mode 'todo-mode)
5197 (let ((opoint (point)))
5198 (re-search-backward (concat "^" (regexp-quote todo-category-beg)
5199 "\\(.*\\)\n") nil t)
5200 (todo-category-number (match-string 1))
5201 (todo-category-select)
5202 (goto-char opoint))))))
5204 (add-function :override diary-goto-entry-function #'todo-diary-goto-entry)
5206 (defun todo-desktop-save-buffer (_dir)
5207 `((catnum . ,(todo-category-number (todo-current-category)))))
5209 (declare-function desktop-restore-file-buffer "desktop"
5210 (buffer-filename buffer-name buffer-misc))
5212 (defun todo-restore-desktop-buffer (file buffer misc)
5213 (desktop-restore-file-buffer file buffer misc)
5214 (with-current-buffer buffer
5216 (let ((todo-category-number (cdr (assq 'catnum misc))))
5217 (todo-category-select))))
5219 (add-to-list 'desktop-buffer-mode-handlers
5220 '(todo-mode . todo-restore-desktop-buffer))
5222 (defun todo-done-item-p ()
5223 "Return non-nil if item at point is a done item."
5226 (looking-at todo-done-string-start)))
5228 (defun todo-done-item-section-p ()
5229 "Return non-nil if point is in category's done items section."
5231 (or (re-search-backward (concat "^" (regexp-quote todo-category-done))
5233 (progn (goto-char (point-min))
5234 (looking-at todo-done-string-start)))))
5236 (defun todo-reset-done-separator (sep)
5237 "Replace existing overlays of done items separator string SEP."
5241 (goto-char (point-min))
5242 (while (re-search-forward
5243 (concat "\n\\(" (regexp-quote todo-category-done) "\\)") nil t)
5244 (let* ((beg (match-beginning 1))
5246 (ov (progn (goto-char beg)
5247 (todo-get-overlay 'separator)))
5248 (old-sep (when ov (overlay-get ov 'display)))
5251 (unless (string= old-sep sep)
5252 (setq new-ov (make-overlay beg end))
5253 (overlay-put new-ov 'todo 'separator)
5254 (overlay-put new-ov 'display todo-done-separator)
5255 (delete-overlay ov))))))))
5257 (defun todo-get-overlay (val)
5258 "Return the overlay at point whose `todo' property has value VAL."
5259 ;; Use overlays-in to find prefix overlays and check over two
5260 ;; positions to find done separator overlay.
5261 (let ((ovs (overlays-in (point) (1+ (point))))
5266 (when (eq (overlay-get ov 'todo) val)
5267 (throw 'done ov))))))
5269 (defun todo-marked-item-p ()
5270 "Non-nil if this item begins with `todo-item-mark'.
5271 In that case, return the item's prefix overlay."
5272 (let* ((ov (todo-get-overlay 'prefix))
5273 ;; If an item insertion command is called on a todo file
5274 ;; before it is visited, it has no prefix overlays yet, so
5276 (pref (when ov (overlay-get ov 'before-string)))
5278 (string-match (concat "^" (regexp-quote todo-item-mark))
5282 (defun todo-insert-with-overlays (item)
5283 "Insert ITEM at point and update prefix/priority number overlays."
5285 ;; Insertion pushes item down but not its prefix overlay. When the
5286 ;; overlay includes a mark, this would now mark the inserted ITEM,
5287 ;; so move it to the pushed down item.
5288 (let ((ov (todo-get-overlay 'prefix))
5289 (marked (todo-marked-item-p)))
5291 (when marked (move-overlay ov (point) (point))))
5292 (todo-backward-item)
5293 (todo-prefix-overlays))
5295 (defun todo-prefix-overlays ()
5296 "Update the prefix overlays of the current category's items.
5297 The overlay's value is the string `todo-prefix' or with non-nil
5298 `todo-number-prefix' an integer in the sequence from 1 to
5299 the number of todo or done items in the category indicating the
5300 item's priority. Todo and done items are numbered independently
5303 (cat-tp (or (cdr (assoc-string
5304 (todo-current-category)
5305 (nth 2 (assoc-string todo-current-todo-file
5306 todo-top-priorities-overrides))))
5307 todo-top-priorities))
5310 (goto-char (point-min))
5312 (when (or (todo-date-string-matcher (line-end-position))
5313 (todo-done-string-matcher (line-end-position)))
5314 (goto-char (match-beginning 0))
5316 ;; Reset number to 1 for first done item.
5317 (when (and (eq major-mode 'todo-mode)
5318 (looking-at todo-done-string-start)
5319 (looking-back (concat "^"
5320 (regexp-quote todo-category-done)
5324 (setq prefix (concat (propertize
5325 (if todo-number-prefix
5326 (number-to-string num)
5329 ;; Prefix of top priority items has a
5330 ;; distinct face in Todo mode.
5331 (if (and (eq major-mode 'todo-mode)
5335 'todo-prefix-string))
5337 (let ((ov (todo-get-overlay 'prefix))
5338 (marked (todo-marked-item-p)))
5339 ;; Prefix overlay must be at a single position so its
5340 ;; bounds aren't changed when (re)moving an item.
5341 (unless ov (setq ov (make-overlay (point) (point))))
5342 (overlay-put ov 'todo 'prefix)
5343 (overlay-put ov 'before-string (if marked
5344 (concat todo-item-mark prefix)
5348 ;; -----------------------------------------------------------------------------
5349 ;;; Generating and applying item insertion and editing key sequences
5350 ;; -----------------------------------------------------------------------------
5352 ;; Thanks to Stefan Monnier for suggesting dynamically generating item
5353 ;; insertion commands and their key bindings, and offering an elegant
5354 ;; implementation, which, however, relies on lexical scoping and so
5355 ;; cannot be used here until the Calendar code used by todo-mode.el is
5356 ;; converted to lexical binding. Hence, the following implementation
5357 ;; uses dynamic binding.
5359 (defconst todo-insert-item--parameters
5360 '((default copy) (diary nonmarking) (calendar date dayname) time (here region))
5361 "List of all item insertion parameters.
5362 Passed by `todo-insert-item' to `todo-insert-item--next-param' to
5363 dynamically create item insertion commands.")
5365 (defconst todo-insert-item--param-key-alist
5376 "List pairing item insertion parameters with their completion keys.")
5378 (defsubst todo-insert-item--keyof (param)
5379 "Return key paired with item insertion PARAM."
5380 (cdr (assoc param todo-insert-item--param-key-alist)))
5382 (defun todo-insert-item--argsleft (key list)
5383 "Return sublist of LIST whose first member corresponds to KEY."
5389 (when (equal key (todo-insert-item--keyof s))
5390 (throw 'found1 (setq sym s))))))
5397 (setq list (reverse l)))
5398 (memq (catch 'found2
5399 (dolist (e todo-insert-item--param-key-alist)
5400 (when (equal key (cdr e))
5401 (throw 'found2 (car e)))))
5404 (defsubst todo-insert-item--this-key () (char-to-string last-command-event))
5406 (defvar todo-insert-item--keys-so-far ""
5407 "String of item insertion keys so far entered for this command.")
5409 (defvar todo-insert-item--args nil)
5410 (defvar todo-insert-item--argleft nil)
5411 (defvar todo-insert-item--argsleft nil)
5412 (defvar todo-insert-item--newargsleft nil)
5414 (defun todo-insert-item--apply-args ()
5415 "Build list of arguments for item insertion and apply them.
5416 The list consists of item insertion parameters that can be passed
5417 as insertion command arguments in fixed positions. If a position
5418 in the list is not occupied by the corresponding parameter, it is
5420 (let* ((arg (list (car todo-insert-item--args)))
5421 (args (nconc (cdr todo-insert-item--args)
5422 (list (car (todo-insert-item--argsleft
5423 (todo-insert-item--this-key)
5424 todo-insert-item--argsleft)))))
5425 (arglist (if (= 4 (length args))
5427 (let ((v (make-vector 4 nil)) elt)
5429 (setq elt (pop args))
5430 (cond ((memq elt '(diary nonmarking))
5432 ((memq elt '(calendar date dayname))
5436 ((memq elt '(copy here region))
5439 (apply #'todo-insert-item--basic (nconc arg arglist))))
5441 (defun todo-insert-item--next-param (last args argsleft)
5442 "Build item insertion command from LAST, ARGS and ARGSLEFT and call it.
5443 Dynamically generate key bindings, prompting with the keys
5444 already entered and those still available."
5445 (cl-assert argsleft)
5446 (let* ((map (make-sparse-keymap))
5454 (if (memq name '(default diary calendar here))
5457 (when (memq name '(copy nonmarking dayname region))
5459 (propertize k 'face 'todo-key-prompt)
5461 (setq todo-insert-item--args args)
5462 (setq todo-insert-item--argsleft argsleft)
5464 (if (memq last '(default copy))
5466 (setq todo-insert-item--argsleft nil)
5467 (todo-insert-item--apply-args))
5468 (let ((k (todo-insert-item--keyof last)))
5469 (funcall addprompt k (make-symbol (concat (symbol-name last) ":GO!")))
5470 (define-key map (todo-insert-item--keyof last)
5471 (lambda () (interactive)
5472 (todo-insert-item--apply-args))))))
5473 (while todo-insert-item--argsleft
5474 (let ((x (car todo-insert-item--argsleft)))
5475 (setq todo-insert-item--newargsleft (cdr todo-insert-item--argsleft))
5476 (dolist (argleft (if (consp x) x (list x)))
5477 (let ((k (todo-insert-item--keyof argleft)))
5478 (funcall addprompt k argleft)
5480 (if (null todo-insert-item--newargsleft)
5481 (lambda () (interactive)
5482 (todo-insert-item--apply-args))
5483 (lambda () (interactive)
5484 (setq todo-insert-item--keys-so-far
5485 (concat todo-insert-item--keys-so-far " "
5486 (todo-insert-item--this-key)))
5487 (todo-insert-item--next-param
5488 (car (todo-insert-item--argsleft
5489 (todo-insert-item--this-key)
5490 todo-insert-item--argsleft))
5491 (nconc todo-insert-item--args
5492 (list (car (todo-insert-item--argsleft
5493 (todo-insert-item--this-key)
5494 todo-insert-item--argsleft))))
5495 (cdr (todo-insert-item--argsleft
5496 (todo-insert-item--this-key)
5497 todo-insert-item--argsleft)))))))))
5498 (setq todo-insert-item--argsleft todo-insert-item--newargsleft))
5499 (when prompt (message "Press a key (so far `%s'): %s"
5500 todo-insert-item--keys-so-far prompt))
5501 (set-transient-map map)
5502 (setq todo-insert-item--argsleft argsleft)))
5504 (defconst todo-edit-item--param-key-alist
5512 "Alist of item editing parameters and their keys.")
5514 (defconst todo-edit-item--date-param-key-alist
5522 "Alist of item date editing parameters and their keys.")
5524 (defconst todo-edit-done-item--param-key-alist
5527 "Alist of done item comment editing parameters and their keys.")
5529 (defvar todo-edit-item--prompt "Press a key (so far `e'): ")
5531 (defun todo-edit-item--next-key (params &optional arg)
5532 (let* ((map (make-sparse-keymap))
5533 (p->k (mapconcat (lambda (elt)
5535 (propertize (cdr elt) 'face
5537 (concat (symbol-name (car elt))
5538 (when (memq (car elt)
5542 (this-key (char-to-string
5543 (read-key (concat todo-edit-item--prompt p->k))))
5544 (this-param (car (rassoc this-key params))))
5546 (`edit (todo-edit-item--text))
5547 (`header (todo-edit-item--text 'include-header))
5548 (`multiline (todo-edit-item--text 'multiline))
5549 (`add/edit (todo-edit-item--text 'comment-edit))
5550 (`delete (todo-edit-item--text 'comment-delete))
5551 (`diary (todo-edit-item--diary-inclusion))
5552 (`nonmarking (todo-edit-item--diary-inclusion 'nonmarking))
5553 (`date (let ((todo-edit-item--prompt "Press a key (so far `e d'): "))
5554 (todo-edit-item--next-key
5555 todo-edit-item--date-param-key-alist arg)))
5556 (`full (progn (todo-edit-item--header 'date)
5557 (when todo-always-add-time-string
5558 (todo-edit-item--header 'time))))
5559 (`calendar (todo-edit-item--header 'calendar))
5560 (`today (todo-edit-item--header 'today))
5561 (`dayname (todo-edit-item--header 'dayname))
5562 (`year (todo-edit-item--header 'year arg))
5563 (`month (todo-edit-item--header 'month arg))
5564 (`daynum (todo-edit-item--header 'day arg))
5565 (`time (todo-edit-item--header 'time)))))
5567 ;; -----------------------------------------------------------------------------
5568 ;;; Todo minibuffer utilities
5569 ;; -----------------------------------------------------------------------------
5571 (defcustom todo-y-with-space nil
5572 "Non-nil means allow SPC to affirm a \"y or n\" question."
5576 (defun todo-y-or-n-p (prompt)
5577 "Ask \"y or n\" question PROMPT and return t if answer is \"y\".
5578 Also return t if answer is \"Y\", but unlike `y-or-n-p', allow
5579 SPC to affirm the question only if option `todo-y-with-space' is
5581 (unless todo-y-with-space
5582 (define-key query-replace-map " " 'ignore))
5585 (define-key query-replace-map " " 'act)))
5587 (defun todo-category-completions (&optional archive)
5588 "Return a list of completions for `todo-read-category'.
5589 Each element of the list is a cons of a category name and the
5590 file or list of files (as short file names) it is in. The files
5591 are either the current (or if there is none, the default) todo
5592 file plus the files listed in `todo-category-completions-files',
5593 or, with non-nil ARCHIVE, the current archive file.
5595 Before calculating the completions, update the value of
5596 `todo-category-completions-files' in case any files named in it
5599 (dolist (f todo-category-completions-files)
5600 (unless (file-exists-p (todo-absolute-file-name f))
5601 (setq todo-category-completions-files
5602 (delete f todo-category-completions-files))
5605 (let ((pl (> (length deleted) 1))
5606 (names (mapconcat (lambda (f) (concat "\"" f "\"")) deleted ", ")))
5607 (message (concat "File" (if pl "s" "") " " names " ha" (if pl "ve" "s")
5608 " been deleted and removed from\n"
5609 "the list of category completion files")))
5610 (todo-reevaluate-category-completions-files-defcustom)
5611 (custom-set-default 'todo-category-completions-files
5612 (symbol-value 'todo-category-completions-files))
5614 (let* ((curfile (or todo-current-todo-file
5615 (and todo-show-current-file
5616 todo-global-current-todo-file)
5617 (todo-absolute-file-name todo-default-todo-file)))
5618 (files (or (unless archive
5619 (mapcar 'todo-absolute-file-name
5620 todo-category-completions-files))
5623 ;; If file was just added, it has no category completions.
5624 (unless (zerop (buffer-size (find-buffer-visiting curfile)))
5625 (unless (member curfile todo-archives)
5626 (add-to-list 'files curfile))
5627 (dolist (f files listall)
5628 (with-current-buffer (find-file-noselect f 'nowarn)
5630 (unless (derived-mode-p 'todo-archive-mode) (todo-archive-mode))
5631 (unless (derived-mode-p 'todo-mode) (todo-mode)))
5632 ;; Ensure category is properly displayed in case user
5633 ;; switches to file via a non-Todo mode command. And if
5634 ;; done items in category are visible, keep them visible.
5635 (let ((done todo-show-with-done))
5636 (when (> (buffer-size) (- (point-max) (point-min)))
5638 (goto-char (point-min))
5639 (setq done (re-search-forward todo-done-string-start nil t))))
5640 (let ((todo-show-with-done done))
5641 (save-excursion (todo-category-select))))
5645 (goto-char (point-min))
5646 (setq listf (read (buffer-substring-no-properties
5647 (line-beginning-position)
5648 (line-end-position)))))))
5649 (mapc (lambda (elt) (let* ((cat (car elt))
5650 (la-elt (assoc cat listall)))
5652 (setcdr la-elt (append (list (cdr la-elt))
5654 (push (cons cat f) listall))))
5657 (defun todo-read-file-name (prompt &optional archive mustmatch)
5658 "Choose and return the name of a todo file, prompting with PROMPT.
5660 Show completions with TAB or SPC; the names are shown in short
5661 form but the absolute truename is returned. With non-nil ARCHIVE
5662 return the absolute truename of a todo archive file. With non-nil
5663 MUSTMATCH the name of an existing file must be chosen;
5664 otherwise, a new file name is allowed."
5665 (let* ((completion-ignore-case todo-completion-ignore-case)
5666 (files (mapcar 'todo-short-file-name
5667 ;; (funcall todo-files-function archive)))
5668 (if archive todo-archives todo-files)))
5669 (file (completing-read prompt files nil mustmatch nil nil
5671 ;; If user hit RET without
5672 ;; choosing a file, default to
5673 ;; current or default file.
5674 (todo-short-file-name
5675 (or todo-current-todo-file
5676 (and todo-show-current-file
5677 todo-global-current-todo-file)
5678 (todo-absolute-file-name
5679 todo-default-todo-file)))
5680 ;; Trigger prompt for initial file.
5682 (unless (file-exists-p todo-directory)
5683 (make-directory todo-directory))
5684 (unless (or mustmatch (member file files))
5685 (setq file (todo-validate-name file 'file)))
5686 (setq file (file-truename (concat todo-directory file
5687 (if archive ".toda" ".todo"))))))
5689 (defun todo-read-category (prompt &optional match-type file)
5690 "Choose and return a category name, prompting with PROMPT.
5691 Show completions for existing categories with TAB or SPC.
5693 The argument MATCH-TYPE specifies the matching requirements on
5694 the category name: with the value `todo' or `archive' the name
5695 must complete to that of an existing todo or archive category,
5696 respectively; with the value `add' the name must not be that of
5697 an existing category; with all other values both existing and new
5698 valid category names are accepted.
5700 With non-nil argument FILE prompt for a file and complete only
5701 against categories in that file; otherwise complete against all
5702 categories from `todo-category-completions-files'."
5703 ;; Allow SPC to insert spaces, for adding new category names.
5704 (let ((map minibuffer-local-completion-map))
5705 (define-key map " " nil)
5706 (let* ((add (eq match-type 'add))
5707 (archive (eq match-type 'archive))
5708 (file0 (when (and file (> (length todo-files) 1))
5709 (todo-read-file-name (concat "Choose a" (if archive
5712 " file: ") archive t)))
5713 (completions (unless file0 (todo-category-completions archive)))
5714 (categories (cond (file0
5715 (with-current-buffer
5716 (find-file-noselect file0 'nowarn)
5717 (unless (derived-mode-p 'todo-mode) (todo-mode))
5718 (let ((todo-current-todo-file file0))
5720 ((and add (not file))
5721 (with-current-buffer
5722 (find-file-noselect todo-current-todo-file)
5726 (completion-ignore-case todo-completion-ignore-case)
5727 (cat (completing-read prompt categories nil
5728 (eq match-type 'todo) nil nil
5729 ;; Unless we're adding a category via
5730 ;; todo-add-category, set default
5731 ;; for existing categories to the
5732 ;; current category of the chosen
5733 ;; file or else of the current file.
5734 (if (and categories (not add))
5735 (with-current-buffer
5738 todo-current-todo-file
5739 (todo-absolute-file-name
5740 todo-default-todo-file)))
5741 (todo-current-category))
5742 ;; Trigger prompt for initial category.
5744 (catfil (cdr (assoc cat completions)))
5745 (str "Category \"%s\" from which file (TAB for choices)? "))
5746 ;; If we do category completion and the chosen category name
5747 ;; occurs in more than one file, prompt to choose one file.
5748 (unless (or file0 add (not catfil))
5749 (setq file0 (file-truename
5752 (todo-absolute-file-name
5753 (let ((files (mapcar 'todo-short-file-name catfil)))
5754 (completing-read (format str cat) files)))))))
5755 ;; Default to the current file.
5756 (unless file0 (setq file0 todo-current-todo-file))
5757 ;; First validate only a name passed interactively from
5758 ;; todo-add-category, which must be of a nonexistent category.
5759 (unless (and (assoc cat categories) (not add))
5760 ;; Validate only against completion categories.
5761 (let ((todo-categories categories))
5762 (setq cat (todo-validate-name cat 'category)))
5763 ;; When user enters a nonexistent category name by jumping or
5764 ;; moving, confirm that it should be added, then validate.
5766 (if (todo-y-or-n-p (format "Add new category \"%s\" to file \"%s\"? "
5767 cat (todo-short-file-name file0)))
5769 (when (assoc cat categories)
5770 (let ((todo-categories categories))
5771 (setq cat (todo-validate-name cat 'category))))
5772 ;; Restore point and narrowing after adding new
5773 ;; category, to avoid moving to beginning of file when
5774 ;; moving marked items to a new category
5775 ;; (todo-move-item).
5778 (todo-add-category file0 cat))))
5779 ;; If we decide not to add a category, exit without returning.
5783 (defun todo-validate-name (name type)
5784 "Prompt for new NAME for TYPE until it is valid, then return it.
5785 TYPE can be either of the symbols `file' or `category'."
5786 (let ((categories todo-categories)
5787 (files (mapcar 'todo-short-file-name todo-files))
5791 (cond ((string= "" name)
5793 (cond ((eq type 'file)
5795 "Enter a non-empty file name: "
5796 ;; Empty string passed by todo-show to
5797 ;; prompt for initial todo file.
5798 (concat "Initial file name ["
5799 todo-initial-file "]: ")))
5800 ((eq type 'category)
5802 "Enter a non-empty category name: "
5803 ;; Empty string passed by todo-show to
5804 ;; prompt for initial category of a new
5806 (concat "Initial category name ["
5807 todo-initial-category "]: "))))))
5808 ((string-match "\\`\\s-+\\'" name)
5810 "Enter a name that does not contain only white space: "))
5811 ((and (eq type 'file) (member name files))
5812 (setq prompt "Enter a non-existing file name: "))
5813 ((and (eq type 'category) (assoc name categories))
5814 (setq prompt "Enter a non-existing category name: ")))
5815 (setq name (if (or (and (eq type 'file) files)
5816 (and (eq type 'category) categories))
5817 (completing-read prompt (cond ((eq type 'file)
5819 ((eq type 'category)
5821 ;; Offer default initial name.
5822 (completing-read prompt (if (eq type 'file)
5825 nil nil (if (eq type 'file)
5827 todo-initial-category))))))
5830 ;; Adapted from calendar-read-date and calendar-date-string.
5831 (defun todo-read-date (&optional arg mo yr)
5832 "Prompt for Gregorian date and return it in the current format.
5834 With non-nil ARG, prompt for and return only the date component
5835 specified by ARG, which can be one of these symbols:
5836 `month' (prompt for name, return name or number according to
5837 value of `calendar-date-display-form'), `day' of month, or
5838 `year'. The value of each of these components can be `*',
5839 indicating an unspecified month, day, or year.
5841 When ARG is `day', non-nil arguments MO and YR determine the
5842 number of the last the day of the month."
5843 (let (year monthname month day
5844 dayname) ; Needed by calendar-date-display-form.
5845 (when (or (not arg) (eq arg 'year))
5846 (while (if (natnump year) (< year 1) (not (eq year '*)))
5847 (setq year (read-from-minibuffer
5848 "Year (>0 or RET for this year or * for any year): "
5849 nil nil t nil (number-to-string
5850 (calendar-extract-year
5851 (calendar-current-date)))))))
5852 (when (or (not arg) (eq arg 'month))
5853 (let* ((marray todo-month-name-array)
5854 (mlist (append marray nil))
5855 (mabarray todo-month-abbrev-array)
5856 (mablist (append mabarray nil))
5857 (completion-ignore-case todo-completion-ignore-case))
5858 (setq monthname (completing-read
5859 "Month name (RET for current month, * for any month): "
5861 (calendar-month-name (calendar-extract-month
5862 (calendar-current-date)) t))
5863 month (1+ (- (length mlist)
5864 (length (or (member monthname mlist)
5865 (member monthname mablist))))))
5866 (setq monthname (aref mabarray (1- month)))))
5867 (when (or (not arg) (eq arg 'day))
5868 (let ((last (let ((mm (or month mo))
5870 ;; If month is unspecified, use a month with 31
5871 ;; days for checking day of month input. Does
5872 ;; Calendar do anything special when * is
5873 ;; currently a shorter month?
5874 (if (= mm 13) (setq mm 1))
5875 ;; If year is unspecified, use a leap year to
5877 (if (eq year '*) (setq yy 2012))
5878 (calendar-last-day-of-month mm yy))))
5879 (while (if (natnump day) (or (< day 1) (> day last)) (not (eq day '*)))
5880 (setq day (read-from-minibuffer
5881 (format "Day (1-%d or RET for today or * for any day): "
5883 nil nil t nil (number-to-string
5884 (calendar-extract-day
5885 (calendar-current-date))))))))
5886 ;; Stringify read values (monthname is already a string).
5887 (and year (setq year (if (eq year '*)
5889 (number-to-string year))))
5890 (and day (setq day (if (eq day '*)
5892 (number-to-string day))))
5893 (and month (setq month (if (eq month '*)
5895 (number-to-string month))))
5897 (cond ((eq arg 'year) year)
5900 (if (memq 'month calendar-date-display-form)
5903 (mapconcat 'eval calendar-date-display-form ""))))
5905 (defun todo-read-dayname ()
5906 "Choose name of a day of the week with completion and return it."
5907 (let ((completion-ignore-case todo-completion-ignore-case))
5908 (completing-read "Enter a day name: "
5909 (append calendar-day-name-array nil)
5912 (defun todo-read-time ()
5913 "Prompt for and return a valid clock time as a string.
5915 Valid time strings are those matching `diary-time-regexp'.
5916 Typing `<return>' at the prompt returns the current time, if the
5917 user option `todo-always-add-time-string' is non-nil, otherwise
5918 the empty string (i.e., no time string)."
5921 (setq answer (read-string "Enter a clock time: " nil nil
5922 (when todo-always-add-time-string
5923 (substring (current-time-string) 11 16))))
5924 (when (or (string= "" answer)
5925 (string-match diary-time-regexp answer))
5929 ;; -----------------------------------------------------------------------------
5930 ;;; Customization groups and utilities
5931 ;; -----------------------------------------------------------------------------
5934 "Create and maintain categorized lists of todo items."
5935 :link '(emacs-commentary-link "todo")
5939 (defgroup todo-edit nil
5940 "User options for adding and editing todo items."
5944 (defgroup todo-categories nil
5945 "User options for Todo Categories mode."
5949 (defgroup todo-filtered nil
5950 "User options for Todo Filter Items mode."
5954 (defgroup todo-display nil
5955 "User display options for Todo mode."
5959 (defgroup todo-faces nil
5960 "Faces for the Todo modes."
5964 (defun todo-set-show-current-file (symbol value)
5965 "The :set function for user option `todo-show-current-file'."
5966 (custom-set-default symbol value)
5968 (add-hook 'pre-command-hook 'todo-show-current-file nil t)
5969 (remove-hook 'pre-command-hook 'todo-show-current-file t)))
5971 (defun todo-reset-prefix (symbol value)
5972 "The :set function for `todo-prefix' and `todo-number-prefix'."
5973 (let ((oldvalue (symbol-value symbol))
5974 (files todo-file-buffers))
5975 (custom-set-default symbol value)
5976 (when (not (equal value oldvalue))
5978 (with-current-buffer (find-file-noselect f)
5979 ;; Activate the new setting in the current category.
5980 (save-excursion (todo-category-select)))))))
5982 (defun todo-reset-nondiary-marker (symbol value)
5983 "The :set function for user option `todo-nondiary-marker'."
5984 (let* ((oldvalue (symbol-value symbol))
5985 (files (append todo-files todo-archives
5986 (directory-files todo-directory t "\.tod[rty]$" t))))
5987 (custom-set-default symbol value)
5988 ;; Need to reset these to get font-locking right.
5989 (setq todo-nondiary-start (nth 0 todo-nondiary-marker)
5990 todo-nondiary-end (nth 1 todo-nondiary-marker)
5991 todo-date-string-start
5992 ;; See comment in defvar of `todo-date-string-start'.
5993 (concat "^\\(" (regexp-quote todo-nondiary-start) "\\|"
5994 (regexp-quote diary-nonmarking-symbol) "\\)?"))
5995 (when (not (equal value oldvalue))
5997 (let ((buf (find-buffer-visiting f)))
5998 (with-current-buffer (find-file-noselect f)
5999 (let (buffer-read-only)
6001 (goto-char (point-min))
6003 (if (re-search-forward
6004 (concat "^\\(" todo-done-string-start "[^][]+] \\)?"
6005 "\\(?1:" (regexp-quote (car oldvalue))
6006 "\\)" todo-date-pattern "\\( "
6007 diary-time-regexp "\\)?\\(?2:"
6008 (regexp-quote (cadr oldvalue)) "\\)")
6011 (replace-match (nth 0 value) t t nil 1)
6012 (replace-match (nth 1 value) t t nil 2))
6015 (when (derived-mode-p 'todo-mode 'todo-archive-mode)
6016 (todo-category-select))
6018 (kill-buffer)))))))))
6020 (defun todo-reset-done-separator-string (symbol value)
6021 "The :set function for `todo-done-separator-string'."
6022 (let ((oldvalue (symbol-value symbol))
6023 (files todo-file-buffers)
6024 (sep todo-done-separator))
6025 (custom-set-default symbol value)
6026 (when (not (equal value oldvalue))
6028 (with-current-buffer (find-file-noselect f)
6029 (let (buffer-read-only)
6030 (setq todo-done-separator (todo-done-separator))
6031 (when (= 1 (length value))
6032 (todo-reset-done-separator sep)))
6033 (todo-category-select))))))
6035 (defun todo-reset-done-string (symbol value)
6036 "The :set function for user option `todo-done-string'."
6037 (let ((oldvalue (symbol-value symbol))
6038 (files (append todo-files todo-archives
6039 (directory-files todo-directory t "\.todr$" t))))
6040 (custom-set-default symbol value)
6041 ;; Need to reset this to get font-locking right.
6042 (setq todo-done-string-start
6043 (concat "^\\[" (regexp-quote todo-done-string)))
6044 (when (not (equal value oldvalue))
6046 (let ((buf (find-buffer-visiting f)))
6047 (with-current-buffer (find-file-noselect f)
6048 (let (buffer-read-only)
6050 (goto-char (point-min))
6052 (if (re-search-forward
6053 (concat "^" (regexp-quote todo-nondiary-start)
6054 "\\(" (regexp-quote oldvalue) "\\)")
6056 (replace-match value t t nil 1)
6059 (when (derived-mode-p 'todo-mode 'todo-archive-mode)
6060 (todo-category-select))
6062 (kill-buffer)))))))))
6064 (defun todo-reset-comment-string (symbol value)
6065 "The :set function for user option `todo-comment-string'."
6066 (let ((oldvalue (symbol-value symbol))
6067 (files (append todo-files todo-archives
6068 (directory-files todo-directory t "\.todr$" t))))
6069 (custom-set-default symbol value)
6070 (when (not (equal value oldvalue))
6072 (let ((buf (find-buffer-visiting f)))
6073 (with-current-buffer (find-file-noselect f)
6074 (let (buffer-read-only)
6076 (goto-char (point-min))
6078 (if (re-search-forward
6079 (concat "\\[\\(" (regexp-quote oldvalue)
6082 (replace-match value t t nil 1)
6085 (when (derived-mode-p 'todo-mode 'todo-archive-mode)
6086 (todo-category-select))
6088 (kill-buffer)))))))))
6090 (defun todo-reset-highlight-item (symbol value)
6091 "The :set function for user option `todo-highlight-item'."
6092 (let ((oldvalue (symbol-value symbol))
6093 (files (append todo-files todo-archives
6094 (directory-files todo-directory t "\.tod[rty]$" t))))
6095 (custom-set-default symbol value)
6096 (when (not (equal value oldvalue))
6098 (let ((buf (find-buffer-visiting f)))
6100 (with-current-buffer buf
6104 (hl-line-mode -1)))))))))
6106 (defun todo-reevaluate-filelist-defcustoms ()
6107 "Reevaluate defcustoms that provide choice list of todo files."
6108 (custom-set-default 'todo-default-todo-file
6109 (symbol-value 'todo-default-todo-file))
6110 (todo-reevaluate-default-file-defcustom)
6111 (custom-set-default 'todo-filter-files (symbol-value 'todo-filter-files))
6112 (todo-reevaluate-filter-files-defcustom)
6113 (custom-set-default 'todo-category-completions-files
6114 (symbol-value 'todo-category-completions-files))
6115 (todo-reevaluate-category-completions-files-defcustom))
6117 (defun todo-reevaluate-default-file-defcustom ()
6118 "Reevaluate defcustom of `todo-default-todo-file'.
6119 Called after adding or deleting a todo file. If the value of
6120 `todo-default-todo-file' before calling this function was
6121 associated with an existing file, keep that value."
6122 ;; (let ((curval todo-default-todo-file))
6124 (defcustom todo-default-todo-file (todo-short-file-name
6125 (car (funcall todo-files-function)))
6126 "Todo file visited by first session invocation of `todo-show'."
6127 :type (when todo-files
6128 `(radio ,@(mapcar (lambda (f) (list 'const f))
6129 (mapcar 'todo-short-file-name
6130 (funcall todo-files-function)))))
6132 ;; (when (and curval (file-exists-p (todo-absolute-file-name curval)))
6133 ;; (custom-set-default 'todo-default-todo-file curval)
6134 ;; ;; (custom-reevaluate-setting 'todo-default-todo-file)
6138 (defun todo-reevaluate-category-completions-files-defcustom ()
6139 "Reevaluate defcustom of `todo-category-completions-files'.
6140 Called after adding or deleting a todo file."
6141 (eval (defcustom todo-category-completions-files nil
6142 "List of files for building `todo-read-category' completions."
6143 :type `(set ,@(mapcar (lambda (f) (list 'const f))
6144 (mapcar 'todo-short-file-name
6145 (funcall todo-files-function))))
6148 (defun todo-reevaluate-filter-files-defcustom ()
6149 "Reevaluate defcustom of `todo-filter-files'.
6150 Called after adding or deleting a todo file."
6151 (eval (defcustom todo-filter-files nil
6152 "List of files for multifile item filtering."
6153 :type `(set ,@(mapcar (lambda (f) (list 'const f))
6154 (mapcar 'todo-short-file-name
6155 (funcall todo-files-function))))
6158 ;; -----------------------------------------------------------------------------
6160 ;; -----------------------------------------------------------------------------
6162 (defun todo-nondiary-marker-matcher (lim)
6163 "Search for todo item nondiary markers within LIM for font-locking."
6164 (re-search-forward (concat "^\\(?1:" (regexp-quote todo-nondiary-start) "\\)"
6165 todo-date-pattern "\\(?: " diary-time-regexp
6166 "\\)?\\(?2:" (regexp-quote todo-nondiary-end) "\\)")
6169 (defun todo-diary-nonmarking-matcher (lim)
6170 "Search for diary nonmarking symbol within LIM for font-locking."
6171 (re-search-forward (concat "^\\(?1:" (regexp-quote diary-nonmarking-symbol)
6172 "\\)" todo-date-pattern) lim t))
6174 (defun todo-date-string-matcher (lim)
6175 "Search for todo item date string within LIM for font-locking."
6177 (concat todo-date-string-start "\\(?1:" todo-date-pattern "\\)") lim t))
6179 (defun todo-time-string-matcher (lim)
6180 "Search for todo item time string within LIM for font-locking."
6181 (re-search-forward (concat todo-date-string-start todo-date-pattern
6182 " \\(?1:" diary-time-regexp "\\)") lim t))
6184 (defun todo-diary-expired-matcher (lim)
6185 "Search for expired diary item date within LIM for font-locking."
6186 (when (re-search-forward (concat "^\\(?:"
6187 (regexp-quote diary-nonmarking-symbol)
6188 "\\)?\\(?1:" todo-date-pattern "\\) \\(?2:"
6189 diary-time-regexp "\\)?") lim t)
6190 (let* ((date (match-string-no-properties 1))
6191 (time (match-string-no-properties 2))
6192 ;; Function days-between requires a non-empty time string.
6193 (date-time (concat date " " (or time "00:00"))))
6194 (or (and (not (string-match ".+day\\|\\*" date))
6195 (< (days-between date-time (current-time-string)) 0))
6196 (todo-diary-expired-matcher lim)))))
6198 (defun todo-done-string-matcher (lim)
6199 "Search for done todo item header within LIM for font-locking."
6200 (re-search-forward (concat todo-done-string-start
6204 (defun todo-comment-string-matcher (lim)
6205 "Search for done todo item comment within LIM for font-locking."
6206 (re-search-forward (concat "\\[\\(?1:" todo-comment-string "\\):")
6209 (defun todo-category-string-matcher-1 (lim)
6210 "Search for todo category name within LIM for font-locking.
6211 This is for fontifying category and file names appearing in Todo
6212 Filtered Items mode following done items."
6213 (if (eq major-mode 'todo-filtered-items-mode)
6214 (re-search-forward (concat todo-done-string-start todo-date-pattern
6215 "\\(?: " diary-time-regexp
6216 ;; Use non-greedy operator to prevent
6217 ;; capturing possible following non-diary
6219 "\\)?] \\(?1:\\[.+?\\]\\)")
6222 (defun todo-category-string-matcher-2 (lim)
6223 "Search for todo category name within LIM for font-locking.
6224 This is for fontifying category and file names appearing in Todo
6225 Filtered Items mode following todo (not done) items."
6226 (if (eq major-mode 'todo-filtered-items-mode)
6227 (re-search-forward (concat todo-date-string-start todo-date-pattern
6228 "\\(?: " diary-time-regexp "\\)?\\(?:"
6229 (regexp-quote todo-nondiary-end)
6230 "\\)? \\(?1:\\[.+\\]\\)")
6233 (defvar todo-nondiary-face 'todo-nondiary)
6234 (defvar todo-date-face 'todo-date)
6235 (defvar todo-time-face 'todo-time)
6236 (defvar todo-diary-expired-face 'todo-diary-expired)
6237 (defvar todo-done-sep-face 'todo-done-sep)
6238 (defvar todo-done-face 'todo-done)
6239 (defvar todo-comment-face 'todo-comment)
6240 (defvar todo-category-string-face 'todo-category-string)
6241 (defvar todo-font-lock-keywords
6243 '(todo-nondiary-marker-matcher 1 todo-nondiary-face t)
6244 '(todo-nondiary-marker-matcher 2 todo-nondiary-face t)
6245 ;; diary-lib.el uses font-lock-constant-face for diary-nonmarking-symbol.
6246 '(todo-diary-nonmarking-matcher 1 font-lock-constant-face t)
6247 '(todo-date-string-matcher 1 todo-date-face t)
6248 '(todo-time-string-matcher 1 todo-time-face t)
6249 '(todo-done-string-matcher 0 todo-done-face t)
6250 '(todo-comment-string-matcher 1 todo-comment-face t)
6251 '(todo-category-string-matcher-1 1 todo-category-string-face t t)
6252 '(todo-category-string-matcher-2 1 todo-category-string-face t t)
6253 '(todo-diary-expired-matcher 1 todo-diary-expired-face t)
6254 '(todo-diary-expired-matcher 2 todo-diary-expired-face t t)
6256 "Font-locking for Todo modes.")
6258 ;; -----------------------------------------------------------------------------
6260 ;; -----------------------------------------------------------------------------
6262 (defvar todo-key-bindings-t
6264 ("Af" todo-find-archive)
6265 ("Ac" todo-choose-archive)
6266 ("Ad" todo-archive-done-item)
6267 ("Cv" todo-toggle-view-done-items)
6268 ("v" todo-toggle-view-done-items)
6269 ("Ca" todo-add-category)
6270 ("Cr" todo-rename-category)
6271 ("Cg" todo-merge-category)
6272 ("Cm" todo-move-category)
6273 ("Ck" todo-delete-category)
6274 ("Cts" todo-set-top-priorities-in-category)
6275 ("Cey" todo-edit-category-diary-inclusion)
6276 ("Cek" todo-edit-category-diary-nonmarking)
6277 ("Fa" todo-add-file)
6278 ("Fr" todo-rename-file)
6279 ("Ff" todo-find-filtered-items-file)
6280 ("FV" todo-toggle-view-done-only)
6281 ("V" todo-toggle-view-done-only)
6282 ("Ftt" todo-filter-top-priorities)
6283 ("Ftm" todo-filter-top-priorities-multifile)
6284 ("Fts" todo-set-top-priorities-in-file)
6285 ("Fyy" todo-filter-diary-items)
6286 ("Fym" todo-filter-diary-items-multifile)
6287 ("Fxx" todo-filter-regexp-items)
6288 ("Fxm" todo-filter-regexp-items-multifile)
6289 ("e" todo-edit-item)
6290 ("d" todo-item-done)
6291 ("i" todo-insert-item)
6292 ("k" todo-delete-item)
6293 ("m" todo-move-item)
6294 ("u" todo-item-undone)
6295 ([remap newline] newline-and-indent)
6297 "List of key bindings for Todo mode only.")
6299 (defvar todo-key-bindings-t+a+f
6301 ("C*" todo-mark-category)
6302 ("Cu" todo-unmark-category)
6303 ("Fh" todo-toggle-item-header)
6304 ("h" todo-toggle-item-header)
6305 ("Fk" todo-delete-file)
6306 ("Fe" todo-edit-file)
6307 ("FH" todo-toggle-item-highlighting)
6308 ("H" todo-toggle-item-highlighting)
6309 ("FN" todo-toggle-prefix-numbers)
6310 ("N" todo-toggle-prefix-numbers)
6311 ("PB" todo-print-buffer)
6312 ("PF" todo-print-buffer-to-file)
6313 ("b" todo-backward-category)
6314 ("d" todo-item-done)
6315 ("f" todo-forward-category)
6316 ("j" todo-jump-to-category)
6317 ("n" todo-next-item)
6318 ("p" todo-previous-item)
6323 "List of key bindings for Todo, Archive, and Filtered Items modes.")
6325 (defvar todo-key-bindings-t+a
6327 ("Fc" todo-show-categories-table)
6329 ("X" todo-clear-matches)
6330 ("*" todo-toggle-mark-item)
6332 "List of key bindings for Todo and Todo Archive modes.")
6334 (defvar todo-key-bindings-t+f
6336 ("l" todo-lower-item-priority)
6337 ("r" todo-raise-item-priority)
6338 ("#" todo-set-item-priority)
6340 "List of key bindings for Todo and Todo Filtered Items modes.")
6342 (defvar todo-mode-map
6343 (let ((map (make-keymap)))
6344 ;; Don't suppress digit keys, so they can supply prefix arguments.
6345 (suppress-keymap map)
6346 (dolist (kb todo-key-bindings-t)
6347 (define-key map (nth 0 kb) (nth 1 kb)))
6348 (dolist (kb todo-key-bindings-t+a+f)
6349 (define-key map (nth 0 kb) (nth 1 kb)))
6350 (dolist (kb todo-key-bindings-t+a)
6351 (define-key map (nth 0 kb) (nth 1 kb)))
6352 (dolist (kb todo-key-bindings-t+f)
6353 (define-key map (nth 0 kb) (nth 1 kb)))
6355 "Todo mode keymap.")
6357 (defvar todo-archive-mode-map
6358 (let ((map (make-sparse-keymap)))
6359 (suppress-keymap map)
6360 (dolist (kb todo-key-bindings-t+a+f)
6361 (define-key map (nth 0 kb) (nth 1 kb)))
6362 (dolist (kb todo-key-bindings-t+a)
6363 (define-key map (nth 0 kb) (nth 1 kb)))
6364 (define-key map "a" 'todo-jump-to-archive-category)
6365 (define-key map "u" 'todo-unarchive-items)
6367 "Todo Archive mode keymap.")
6369 (defvar todo-edit-mode-map
6370 (let ((map (make-sparse-keymap)))
6371 (define-key map "\C-x\C-q" 'todo-edit-quit)
6372 (define-key map [remap newline] 'newline-and-indent)
6374 "Todo Edit mode keymap.")
6376 (defvar todo-categories-mode-map
6377 (let ((map (make-sparse-keymap)))
6378 (suppress-keymap map)
6379 (define-key map "c" 'todo-sort-categories-alphabetically-or-numerically)
6380 (define-key map "t" 'todo-sort-categories-by-todo)
6381 (define-key map "y" 'todo-sort-categories-by-diary)
6382 (define-key map "d" 'todo-sort-categories-by-done)
6383 (define-key map "a" 'todo-sort-categories-by-archived)
6384 (define-key map "#" 'todo-set-category-number)
6385 (define-key map "l" 'todo-lower-category)
6386 (define-key map "r" 'todo-raise-category)
6387 (define-key map "n" 'todo-next-button)
6388 (define-key map "p" 'todo-previous-button)
6389 (define-key map [tab] 'todo-next-button)
6390 (define-key map [backtab] 'todo-previous-button)
6391 (define-key map "q" 'todo-quit)
6393 "Todo Categories mode keymap.")
6395 (defvar todo-filtered-items-mode-map
6396 (let ((map (make-sparse-keymap)))
6397 (suppress-keymap map)
6398 (dolist (kb todo-key-bindings-t+a+f)
6399 (define-key map (nth 0 kb) (nth 1 kb)))
6400 (dolist (kb todo-key-bindings-t+f)
6401 (define-key map (nth 0 kb) (nth 1 kb)))
6402 (define-key map "g" 'todo-go-to-source-item)
6403 (define-key map [remap newline] 'todo-go-to-source-item)
6405 "Todo Filtered Items mode keymap.")
6408 todo-menu todo-mode-map "Todo Menu"
6411 ["Next Item" todo-next-item t]
6412 ["Previous Item" todo-previous-item t]
6414 ["Next Category" todo-forward-category t]
6415 ["Previous Category" todo-backward-category t]
6416 ["Jump to Another Category" todo-jump-to-category t]
6418 ["Visit Another Todo File" todo-show t]
6419 ["Visit Archive" todo-find-archive t]
6420 ["Visit Filtered Items File" todo-find-filtered-items-file t]
6423 ["Insert New Item" todo-insert-item t]
6424 ["Edit Item" todo-edit-item t]
6425 ["Lower Item Priority" todo-lower-item-priority t]
6426 ["Raise Item Priority" todo-raise-item-priority t]
6427 ["Set Item Priority" todo-set-item-priority t]
6428 ["Mark/Unmark Item" todo-toggle-mark-item t]
6429 ["Move (Recategorize) Item" todo-move-item t]
6430 ["Delete Item" todo-delete-item t]
6431 ["Mark and Bury Done Item" todo-item-done t]
6432 ["Undo Done Item" todo-item-undone t]
6433 ["Archive Done Item" todo-archive-done-item t]
6435 ["Add New Category" todo-add-category t]
6436 ["Rename Current Category" todo-rename-category t]
6437 ["Delete Current Category" todo-delete-category t]
6438 ["Move Current Category" todo-move-category t]
6439 ["Merge Current Category" todo-merge-category t]
6441 ["Add New Todo File" todo-add-file t]
6442 ["Rename Todo File" todo-rename-file t]
6443 ["Delete Todo File" todo-delete-file t]
6444 ["Edit Todo File" todo-edit-file t]
6446 ("Searching and Item Filtering"
6447 ["Search Todo File" todo-search t]
6448 ["Clear Match Highlighting" todo-clear-matches t]
6450 ["Set Top Priorities in File" todo-set-top-priorities-in-file t]
6451 ["Set Top Priorities in Category" todo-set-top-priorities-in-category t]
6452 ["Filter Top Priorities" todo-filter-top-priorities t]
6453 ["Filter Multifile Top Priorities" todo-filter-top-priorities-multifile t]
6454 ["Filter Diary Items" todo-filter-diary-items t]
6455 ["Filter Multifile Diary Items" todo-filter-diary-items-multifile t]
6456 ["Filter Regexp" todo-filter-regexp-items t]
6457 ["Filter Multifile Regexp" todo-filter-regexp-items-multifile t]
6459 ("Display and Printing"
6460 ["Show/Hide Done Items" todo-toggle-view-done-items t]
6461 ["Show/Hide Done Items Only" todo-toggle-view-done-only t]
6462 ["Show/Hide Item Highlighting" todo-toggle-item-highlighting t]
6463 ["Show/Hide Item Numbering" todo-toggle-prefix-numbers t]
6464 ["Show/Hide Item Header" todo-toggle-item-header t]
6466 ["Display Table of Categories" todo-show-categories-table t]
6468 ["Print Category" todo-print-buffer t]
6469 ["Print Category to File" todo-print-buffer-to-file t]
6472 ["Save Todo File" todo-save t]
6473 ["Quit Todo Mode" todo-quit t]
6476 ;; -----------------------------------------------------------------------------
6477 ;;; Hook functions and mode definitions
6478 ;; -----------------------------------------------------------------------------
6480 (defun todo-show-current-file ()
6481 "Visit current instead of default todo file with `todo-show'.
6482 Added to `pre-command-hook' in Todo mode when user option
6483 `todo-show-current-file' is set to non-nil."
6484 (setq todo-global-current-todo-file todo-current-todo-file))
6486 ;; (defun todo-display-as-todo-file ()
6487 ;; "Show todo files correctly when visited from outside of Todo mode.
6488 ;; Added to `find-file-hook' in Todo mode and Todo Archive mode."
6489 ;; (and (member this-command todo-visit-files-commands)
6490 ;; (= (- (point-max) (point-min)) (buffer-size))
6491 ;; (member major-mode '(todo-mode todo-archive-mode))
6492 ;; (todo-category-select)))
6494 ;; (defun todo-add-to-buffer-list ()
6495 ;; "Add name of just visited todo file to `todo-file-buffers'.
6496 ;; This function is added to `find-file-hook' in Todo mode."
6497 ;; (let ((filename (file-truename (buffer-file-name))))
6498 ;; (when (member filename todo-files)
6499 ;; (add-to-list 'todo-file-buffers filename))))
6501 (defun todo-update-buffer-list ()
6502 "Make current Todo mode buffer file car of `todo-file-buffers'.
6503 This function is added to `post-command-hook' in Todo mode."
6504 (let ((filename (file-truename (buffer-file-name))))
6505 (unless (eq (car todo-file-buffers) filename)
6506 (setq todo-file-buffers
6507 (cons filename (delete filename todo-file-buffers))))))
6509 (defun todo-reset-global-current-todo-file ()
6510 "Update the value of `todo-global-current-todo-file'.
6511 This becomes the latest existing todo file or, if there is none,
6512 the value of `todo-default-todo-file'.
6513 This function is added to `kill-buffer-hook' in Todo mode."
6514 (let ((filename (file-truename (buffer-file-name))))
6515 (setq todo-file-buffers (delete filename todo-file-buffers))
6516 (setq todo-global-current-todo-file
6517 (or (car todo-file-buffers)
6518 (todo-absolute-file-name todo-default-todo-file)))))
6520 (defun todo-reset-and-enable-done-separator ()
6521 "Show resized done items separator overlay after window change.
6522 Added to `window-configuration-change-hook' in Todo mode."
6523 (when (= 1 (length todo-done-separator-string))
6524 (let ((sep todo-done-separator))
6525 (setq todo-done-separator (todo-done-separator))
6526 (save-match-data (todo-reset-done-separator sep)))))
6528 (defun todo-modes-set-1 ()
6529 "Make some settings that apply to multiple Todo modes."
6530 (setq-local font-lock-defaults '(todo-font-lock-keywords t))
6531 (setq-local tab-width todo-indent-to-here)
6532 (setq-local indent-line-function 'todo-indent)
6533 (when todo-wrap-lines
6535 (setq wrap-prefix (make-string todo-indent-to-here 32))))
6537 (defun todo-modes-set-2 ()
6538 "Make some settings that apply to multiple Todo modes."
6539 (add-to-invisibility-spec 'todo)
6540 (setq buffer-read-only t)
6541 (when (and (boundp 'desktop-save-mode) desktop-save-mode)
6542 (setq-local desktop-save-buffer 'todo-desktop-save-buffer))
6543 (when (boundp 'hl-line-range-function)
6544 (setq-local hl-line-range-function
6545 (lambda() (save-excursion
6546 (when (todo-item-end)
6547 (cons (todo-item-start)
6548 (todo-item-end))))))))
6550 (defun todo-modes-set-3 ()
6551 "Make some settings that apply to multiple Todo modes."
6552 (setq-local todo-categories (todo-set-categories))
6553 (setq-local todo-category-number 1)
6554 ;; (add-hook 'find-file-hook 'todo-display-as-todo-file nil t)
6557 (put 'todo-mode 'mode-class 'special)
6560 (define-derived-mode todo-mode special-mode "Todo"
6561 "Major mode for displaying, navigating and editing todo lists.
6564 ;; (easy-menu-add todo-menu)
6568 ;; Initialize todo-current-todo-file.
6569 (when (member (file-truename (buffer-file-name))
6570 (funcall todo-files-function))
6571 (setq-local todo-current-todo-file (file-truename (buffer-file-name))))
6572 (setq-local todo-show-done-only nil)
6573 (setq-local todo-categories-with-marks nil)
6574 ;; (add-hook 'find-file-hook 'todo-add-to-buffer-list nil t)
6575 (add-hook 'post-command-hook 'todo-update-buffer-list nil t)
6576 (when todo-show-current-file
6577 (add-hook 'pre-command-hook 'todo-show-current-file nil t))
6578 (add-hook 'window-configuration-change-hook
6579 'todo-reset-and-enable-done-separator nil t)
6580 (add-hook 'kill-buffer-hook 'todo-reset-global-current-todo-file nil t))
6582 (put 'todo-archive-mode 'mode-class 'special)
6584 ;; If todo-mode is parent, all todo-mode key bindings appear to be
6585 ;; available in todo-archive-mode (e.g. shown by C-h m).
6587 (define-derived-mode todo-archive-mode special-mode "Todo-Arch"
6588 "Major mode for archived todo categories.
6590 \\{todo-archive-mode-map}"
6594 (setq-local todo-current-todo-file (file-truename (buffer-file-name)))
6595 (setq-local todo-show-done-only t))
6597 (defun todo-mode-external-set ()
6598 "Set `todo-categories' externally to `todo-current-todo-file'."
6599 (setq-local todo-current-todo-file todo-global-current-todo-file)
6600 (let ((cats (with-current-buffer
6601 ;; Can't use find-buffer-visiting when
6602 ;; `todo-show-categories-table' is called on first
6603 ;; invocation of `todo-show', since there is then
6604 ;; no buffer visiting the current file.
6605 (find-file-noselect todo-current-todo-file 'nowarn)
6607 ;; In Todo Edit mode todo-categories is now nil
6608 ;; since it uses same buffer as Todo mode but
6609 ;; doesn't have the latter's local variables.
6611 (goto-char (point-min))
6612 (read (buffer-substring-no-properties
6613 (line-beginning-position)
6614 (line-end-position))))))))
6615 (setq-local todo-categories cats)))
6617 (define-derived-mode todo-edit-mode text-mode "Todo-Ed"
6618 "Major mode for editing multiline todo items.
6620 \\{todo-edit-mode-map}"
6622 (todo-mode-external-set)
6623 (setq buffer-read-only nil))
6625 (put 'todo-categories-mode 'mode-class 'special)
6627 (define-derived-mode todo-categories-mode special-mode "Todo-Cats"
6628 "Major mode for displaying and editing todo categories.
6630 \\{todo-categories-mode-map}"
6631 (todo-mode-external-set))
6633 (put 'todo-filtered-items-mode 'mode-class 'special)
6636 (define-derived-mode todo-filtered-items-mode special-mode "Todo-Fltr"
6637 "Mode for displaying and reprioritizing top priority Todo.
6639 \\{todo-filtered-items-mode-map}"
6643 ;; -----------------------------------------------------------------------------
6644 (provide 'todo-mode)
6646 ;;; todo-mode.el ends here