Rename comment-depth (etc.) to literal-cache (etc.). Enable it by default
[emacs.git] / lisp / calendar / todo-mode.el
blob94cd08eaa4e898f8e35de3bac942212cb3583167
1 ;;; todo-mode.el --- facilities for making and maintaining todo lists
3 ;; Copyright (C) 1997, 1999, 2001-2016 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/>.
25 ;;; Commentary:
27 ;; This package provides facilities for making and maintaining
28 ;; prioritized lists of things to do. These todo lists are identified
29 ;; with named categories, so you can group together thematically
30 ;; related todo items. Each category is stored in a file, providing a
31 ;; further level of organization. You can create as many todo files,
32 ;; and in each as many categories, as you want.
34 ;; With Todo mode you can navigate among the items of a category, and
35 ;; between categories in the same and in different todo files. You
36 ;; can add and edit todo items, reprioritize them, move them to
37 ;; another category, or delete them. You can also mark items as done
38 ;; and store them within their category or in separate archive files.
39 ;; You can include todo items in the Emacs Fancy Diary display and
40 ;; treat them as appointments. You can add new todo files, and rename
41 ;; or delete them. You can add new categories to a file, rename or
42 ;; delete them, move a category to another file and merge the items of
43 ;; two categories. You can also reorder the sequence of categories in
44 ;; a todo file for the purpose of navigation. You can display
45 ;; sortable summary tables of the categories in a file and the types
46 ;; of items they contain. And you can filter items by various
47 ;; criteria from multiple categories in one or more todo files to
48 ;; create prioritizable cross-category overviews of your todo items.
50 ;; To get started, type `M-x todo-show'. For full details of the user
51 ;; interface, commands and options, consult the Todo mode user manual,
52 ;; which is included in the Info documentation.
54 ;;; Code:
56 (require 'diary-lib)
57 (require 'cl-lib) ; For cl-oddp and cl-assert.
59 ;; -----------------------------------------------------------------------------
60 ;;; Setting up todo files, categories, and items
61 ;; -----------------------------------------------------------------------------
63 (defcustom todo-directory (locate-user-emacs-file "todo/")
64 "Directory where user's todo files are saved."
65 :type 'directory
66 :group 'todo)
68 (defun todo-files (&optional archives)
69 "Default value of `todo-files-function'.
70 This returns the case-insensitive alphabetically sorted list of
71 file truenames in `todo-directory' with the extension
72 \".todo\". With non-nil ARCHIVES return the list of archive file
73 truenames (those with the extension \".toda\")."
74 (let ((files (if (file-exists-p todo-directory)
75 (mapcar 'file-truename
76 (directory-files todo-directory t
77 (if archives "\\.toda$" "\\.todo$") t)))))
78 (sort files (lambda (s1 s2) (let ((cis1 (upcase s1))
79 (cis2 (upcase s2)))
80 (string< cis1 cis2))))))
82 (defcustom todo-files-function 'todo-files
83 "Function returning the value of the variable `todo-files'.
84 This function should take an optional argument that, if non-nil,
85 makes it return the value of the variable `todo-archives'."
86 :type 'function
87 :group 'todo)
89 (defvar todo-files (funcall todo-files-function)
90 "List of truenames of user's todo files.")
92 (defvar todo-archives (funcall todo-files-function t)
93 "List of truenames of user's todo archives.")
95 (defvar todo-visited nil
96 "List of todo files visited in this session by `todo-show'.
97 Used to determine initial display according to the value of
98 `todo-show-first'.")
100 (defvar todo-file-buffers nil
101 "List of file names of live Todo mode buffers.")
103 (defvar todo-global-current-todo-file nil
104 "Variable holding name of current todo file.
105 Used by functions called from outside of Todo mode to visit the
106 current todo file rather than the default todo file (i.e. when
107 users option `todo-show-current-file' is non-nil).")
109 (defvar todo-current-todo-file nil
110 "Variable holding the name of the currently active todo file.")
112 (defvar todo-categories nil
113 "Alist of categories in the current todo file.
114 The elements are cons cells whose car is a category name and
115 whose cdr is a vector of the category's item counts. These are,
116 in order, the numbers of todo items, of todo items included in
117 the Diary, of done items and of archived items.")
119 (defvar todo-category-number 1
120 "Variable holding the number of the current todo category.
121 Todo categories are numbered starting from 1.")
123 (defvar todo-categories-with-marks nil
124 "Alist of categories and number of marked items they contain.")
126 (defconst todo-category-beg "--==-- "
127 "String marking beginning of category (inserted with its name).")
129 (defconst todo-category-done "==--== DONE "
130 "String marking beginning of category's done items.")
132 (defcustom todo-done-separator-string "="
133 "String determining the value of variable `todo-done-separator'.
134 If the string consists of a single character,
135 `todo-done-separator' will be the string made by repeating this
136 character for the width of the window, and the length is
137 automatically recalculated when the window width changes. If the
138 string consists of more (or less) than one character, it will be
139 the value of `todo-done-separator'."
140 :type 'string
141 :initialize 'custom-initialize-default
142 :set 'todo-reset-done-separator-string
143 :group 'todo-display)
145 (defun todo-done-separator ()
146 "Return string used as value of variable `todo-done-separator'."
147 (let ((sep todo-done-separator-string))
148 (propertize (if (= 1 (length sep))
149 (make-string (window-width) (string-to-char sep))
150 todo-done-separator-string)
151 'face 'todo-done-sep)))
153 (defvar todo-done-separator (todo-done-separator)
154 "String used to visually separate done from not done items.
155 Displayed as an overlay instead of `todo-category-done' when
156 done items are shown. Its value is determined by user option
157 `todo-done-separator-string'.")
159 (defvar todo-show-done-only nil
160 "If non-nil display only done items in current category.
161 Set by the command `todo-toggle-view-done-only' and used by
162 `todo-category-select'.")
164 (defcustom todo-nondiary-marker '("[" "]")
165 "List of strings surrounding item date to block diary inclusion.
166 The first string is inserted before the item date and must be a
167 non-empty string that does not match a diary date in order to
168 have its intended effect. The second string is inserted after
169 the diary date."
170 :type '(list string string)
171 :group 'todo-edit
172 :initialize 'custom-initialize-default
173 :set 'todo-reset-nondiary-marker)
175 (defconst todo-nondiary-start (nth 0 todo-nondiary-marker)
176 "String inserted before item date to block diary inclusion.")
178 (defconst todo-nondiary-end (nth 1 todo-nondiary-marker)
179 "String inserted after item date matching `todo-nondiary-start'.")
181 (defconst todo-month-name-array
182 (vconcat calendar-month-name-array (vector "*"))
183 "Array of month names, in order.
184 The final element is \"*\", indicating an unspecified month.")
186 (defconst todo-month-abbrev-array
187 (vconcat calendar-month-abbrev-array (vector "*"))
188 "Array of abbreviated month names, in order.
189 The final element is \"*\", indicating an unspecified month.")
191 (defconst todo-date-pattern
192 (let ((dayname (diary-name-pattern calendar-day-name-array nil t)))
193 (concat "\\(?4:\\(?5:" dayname "\\)\\|"
194 (let ((dayname)
195 (monthname (format "\\(?6:%s\\)" (diary-name-pattern
196 todo-month-name-array
197 todo-month-abbrev-array)))
198 (month "\\(?7:[0-9]+\\|\\*\\)")
199 (day "\\(?8:[0-9]+\\|\\*\\)")
200 (year "-?\\(?9:[0-9]+\\|\\*\\)"))
201 (mapconcat 'eval calendar-date-display-form ""))
202 "\\)"))
203 "Regular expression matching a todo item date header.")
205 ;; By itself this matches anything, because of the `?'; however, it's only
206 ;; used in the context of `todo-date-pattern' (but Emacs Lisp lacks
207 ;; lookahead).
208 (defconst todo-date-string-start
209 (concat "^\\(" (regexp-quote todo-nondiary-start) "\\|"
210 (regexp-quote diary-nonmarking-symbol) "\\)?")
211 "Regular expression matching part of item header before the date.")
213 (defcustom todo-done-string "DONE "
214 "Identifying string appended to the front of done todo items."
215 :type 'string
216 :initialize 'custom-initialize-default
217 :set 'todo-reset-done-string
218 :group 'todo-edit)
220 (defconst todo-done-string-start
221 (concat "^\\[" (regexp-quote todo-done-string))
222 "Regular expression matching start of done item.")
224 (defconst todo-item-start (concat "\\(" todo-date-string-start "\\|"
225 todo-done-string-start "\\)"
226 todo-date-pattern)
227 "String identifying start of a todo item.")
229 ;; -----------------------------------------------------------------------------
230 ;;; Todo mode display options
231 ;; -----------------------------------------------------------------------------
233 (defcustom todo-prefix ""
234 "String prefixed to todo items for visual distinction."
235 :type '(string :validate
236 (lambda (widget)
237 (when (string= (widget-value widget) todo-item-mark)
238 (widget-put
239 widget :error
240 (format-message
241 "Invalid value: must be distinct from `todo-item-mark'"))
242 widget)))
243 :initialize 'custom-initialize-default
244 :set 'todo-reset-prefix
245 :group 'todo-display)
247 (defcustom todo-number-prefix t
248 "Non-nil to prefix items with consecutively increasing integers.
249 These reflect the priorities of the items in each category."
250 :type 'boolean
251 :initialize 'custom-initialize-default
252 :set 'todo-reset-prefix
253 :group 'todo-display)
255 (defun todo-mode-line-control (cat)
256 "Return a mode line control for todo or archive file buffers.
257 Argument CAT is the name of the current todo category.
258 This function is the value of the user variable
259 `todo-mode-line-function'."
260 (let ((file (todo-short-file-name todo-current-todo-file)))
261 (format "%s category %d: %s" file todo-category-number cat)))
263 (defcustom todo-mode-line-function 'todo-mode-line-control
264 "Function that returns a mode line control for Todo mode buffers.
265 The function expects one argument holding the name of the current
266 todo category. The resulting control becomes the local value of
267 `mode-line-buffer-identification' in each Todo mode buffer."
268 :type 'function
269 :group 'todo-display)
271 (defcustom todo-highlight-item nil
272 "Non-nil means highlight items at point."
273 :type 'boolean
274 :initialize 'custom-initialize-default
275 :set 'todo-reset-highlight-item
276 :group 'todo-display)
278 (defcustom todo-wrap-lines t
279 "Non-nil to activate Visual Line mode and use wrap prefix."
280 :type 'boolean
281 :group 'todo-display)
283 (defcustom todo-indent-to-here 3
284 "Number of spaces to indent continuation lines of items.
285 This must be a positive number to ensure such items are fully
286 shown in the Fancy Diary display."
287 :type '(integer :validate
288 (lambda (widget)
289 (unless (> (widget-value widget) 0)
290 (widget-put widget :error
291 "Invalid value: must be a positive integer")
292 widget)))
293 :group 'todo-display)
295 (defun todo-indent ()
296 "Indent from point to `todo-indent-to-here'."
297 (indent-to todo-indent-to-here todo-indent-to-here))
299 (defcustom todo-show-with-done nil
300 "Non-nil to display done items in all categories."
301 :type 'boolean
302 :group 'todo-display)
304 ;; -----------------------------------------------------------------------------
305 ;;; Faces
306 ;; -----------------------------------------------------------------------------
308 (defface todo-key-prompt
309 '((t (:weight bold)))
310 "Face for making keys in item insertion prompt stand out."
311 :group 'todo-faces)
313 (defface todo-mark
314 ;; '((t :inherit font-lock-warning-face))
315 '((((class color)
316 (min-colors 88)
317 (background light))
318 (:weight bold :foreground "Red1"))
319 (((class color)
320 (min-colors 88)
321 (background dark))
322 (:weight bold :foreground "Pink"))
323 (((class color)
324 (min-colors 16)
325 (background light))
326 (:weight bold :foreground "Red1"))
327 (((class color)
328 (min-colors 16)
329 (background dark))
330 (:weight bold :foreground "Pink"))
331 (((class color)
332 (min-colors 8))
333 (:foreground "red"))
335 (:weight bold :inverse-video t)))
336 "Face for marks on marked items."
337 :group 'todo-faces)
339 (defface todo-prefix-string
340 ;; '((t :inherit font-lock-constant-face))
341 '((((class grayscale) (background light))
342 (:foreground "LightGray" :weight bold :underline t))
343 (((class grayscale) (background dark))
344 (:foreground "Gray50" :weight bold :underline t))
345 (((class color) (min-colors 88) (background light)) (:foreground "dark cyan"))
346 (((class color) (min-colors 88) (background dark)) (:foreground "Aquamarine"))
347 (((class color) (min-colors 16) (background light)) (:foreground "CadetBlue"))
348 (((class color) (min-colors 16) (background dark)) (:foreground "Aquamarine"))
349 (((class color) (min-colors 8)) (:foreground "magenta"))
350 (t (:weight bold :underline t)))
351 "Face for todo item prefix or numerical priority string."
352 :group 'todo-faces)
354 (defface todo-top-priority
355 ;; bold font-lock-comment-face
356 '((default :weight bold)
357 (((class grayscale) (background light)) :foreground "DimGray" :slant italic)
358 (((class grayscale) (background dark)) :foreground "LightGray" :slant italic)
359 (((class color) (min-colors 88) (background light)) :foreground "Firebrick")
360 (((class color) (min-colors 88) (background dark)) :foreground "chocolate1")
361 (((class color) (min-colors 16) (background light)) :foreground "red")
362 (((class color) (min-colors 16) (background dark)) :foreground "red1")
363 (((class color) (min-colors 8) (background light)) :foreground "red")
364 (((class color) (min-colors 8) (background dark)) :foreground "yellow")
365 (t :slant italic))
366 "Face for top priority todo item numerical priority string.
367 The item's priority number string has this face if the number is
368 less than or equal the category's top priority setting."
369 :group 'todo-faces)
371 (defface todo-nondiary
372 ;; '((t :inherit font-lock-type-face))
373 '((((class grayscale) (background light)) :foreground "Gray90" :weight bold)
374 (((class grayscale) (background dark)) :foreground "DimGray" :weight bold)
375 (((class color) (min-colors 88) (background light)) :foreground "ForestGreen")
376 (((class color) (min-colors 88) (background dark)) :foreground "PaleGreen")
377 (((class color) (min-colors 16) (background light)) :foreground "ForestGreen")
378 (((class color) (min-colors 16) (background dark)) :foreground "PaleGreen")
379 (((class color) (min-colors 8)) :foreground "green")
380 (t :weight bold :underline t))
381 "Face for non-diary markers around todo item date/time header."
382 :group 'todo-faces)
384 (defface todo-date
385 '((t :inherit diary))
386 "Face for the date string of a todo item."
387 :group 'todo-faces)
389 (defface todo-time
390 '((t :inherit diary-time))
391 "Face for the time string of a todo item."
392 :group 'todo-faces)
394 (defface todo-diary-expired
395 ;; Doesn't contrast enough with todo-date (= diary) face.
396 ;; ;; '((t :inherit warning))
397 ;; '((default :weight bold)
398 ;; (((class color) (min-colors 16)) :foreground "DarkOrange")
399 ;; (((class color)) :foreground "yellow"))
400 ;; bold font-lock-function-name-face
401 '((default :weight bold)
402 (((class color) (min-colors 88) (background light)) :foreground "Blue1")
403 (((class color) (min-colors 88) (background dark)) :foreground "LightSkyBlue")
404 (((class color) (min-colors 16) (background light)) :foreground "Blue")
405 (((class color) (min-colors 16) (background dark)) :foreground "LightSkyBlue")
406 (((class color) (min-colors 8)) :foreground "blue")
407 (t :inverse-video t))
408 "Face for expired dates of diary items."
409 :group 'todo-faces)
411 (defface todo-done-sep
412 ;; '((t :inherit font-lock-builtin-face))
413 '((((class grayscale) (background light)) :foreground "LightGray" :weight bold)
414 (((class grayscale) (background dark)) :foreground "DimGray" :weight bold)
415 (((class color) (min-colors 88) (background light)) :foreground "dark slate blue")
416 (((class color) (min-colors 88) (background dark)) :foreground "LightSteelBlue")
417 (((class color) (min-colors 16) (background light)) :foreground "Orchid")
418 (((class color) (min-colors 16) (background dark)) :foreground "LightSteelBlue")
419 (((class color) (min-colors 8)) :foreground "blue" :weight bold)
420 (t :weight bold))
421 "Face for separator string between done and not done todo items."
422 :group 'todo-faces)
424 (defface todo-done
425 ;; '((t :inherit font-lock-keyword-face))
426 '((((class grayscale) (background light)) :foreground "LightGray" :weight bold)
427 (((class grayscale) (background dark)) :foreground "DimGray" :weight bold)
428 (((class color) (min-colors 88) (background light)) :foreground "Purple")
429 (((class color) (min-colors 88) (background dark)) :foreground "Cyan1")
430 (((class color) (min-colors 16) (background light)) :foreground "Purple")
431 (((class color) (min-colors 16) (background dark)) :foreground "Cyan")
432 (((class color) (min-colors 8)) :foreground "cyan" :weight bold)
433 (t :weight bold))
434 "Face for done todo item header string."
435 :group 'todo-faces)
437 (defface todo-comment
438 ;; '((t :inherit font-lock-comment-face))
439 '((((class grayscale) (background light))
440 :foreground "DimGray" :weight bold :slant italic)
441 (((class grayscale) (background dark))
442 :foreground "LightGray" :weight bold :slant italic)
443 (((class color) (min-colors 88) (background light))
444 :foreground "Firebrick")
445 (((class color) (min-colors 88) (background dark))
446 :foreground "chocolate1")
447 (((class color) (min-colors 16) (background light))
448 :foreground "red")
449 (((class color) (min-colors 16) (background dark))
450 :foreground "red1")
451 (((class color) (min-colors 8) (background light))
452 :foreground "red")
453 (((class color) (min-colors 8) (background dark))
454 :foreground "yellow")
455 (t :weight bold :slant italic))
456 "Face for comments appended to done todo items."
457 :group 'todo-faces)
459 (defface todo-search
460 ;; '((t :inherit match))
461 '((((class color)
462 (min-colors 88)
463 (background light))
464 (:background "yellow1"))
465 (((class color)
466 (min-colors 88)
467 (background dark))
468 (:background "RoyalBlue3"))
469 (((class color)
470 (min-colors 8)
471 (background light))
472 (:foreground "black" :background "yellow"))
473 (((class color)
474 (min-colors 8)
475 (background dark))
476 (:foreground "white" :background "blue"))
477 (((type tty)
478 (class mono))
479 (:inverse-video t))
481 (:background "gray")))
482 "Face for matches found by `todo-search'."
483 :group 'todo-faces)
485 (defface todo-button
486 ;; '((t :inherit widget-field))
487 '((((type tty))
488 (:foreground "black" :background "yellow3"))
489 (((class grayscale color)
490 (background light))
491 (:background "gray85"))
492 (((class grayscale color)
493 (background dark))
494 (:background "dim gray"))
496 (:slant italic)))
497 "Face for buttons in table of categories."
498 :group 'todo-faces)
500 (defface todo-sorted-column
501 '((((type tty))
502 (:inverse-video t))
503 (((class color)
504 (background light))
505 (:background "grey85"))
506 (((class color)
507 (background dark))
508 (:background "grey85" :foreground "grey10"))
510 (:background "gray")))
511 "Face for sorted column in table of categories."
512 :group 'todo-faces)
514 (defface todo-archived-only
515 ;; '((t (:inherit (shadow))))
516 '((((class color)
517 (background light))
518 (:foreground "grey50"))
519 (((class color)
520 (background dark))
521 (:foreground "grey70"))
523 (:foreground "gray")))
524 "Face for archived-only category names in table of categories."
525 :group 'todo-faces)
527 (defface todo-category-string
528 ;; '((t :inherit font-lock-type-face))
529 '((((class grayscale) (background light)) :foreground "Gray90" :weight bold)
530 (((class grayscale) (background dark)) :foreground "DimGray" :weight bold)
531 (((class color) (min-colors 88) (background light)) :foreground "ForestGreen")
532 (((class color) (min-colors 88) (background dark)) :foreground "PaleGreen")
533 (((class color) (min-colors 16) (background light)) :foreground "ForestGreen")
534 (((class color) (min-colors 16) (background dark)) :foreground "PaleGreen")
535 (((class color) (min-colors 8)) :foreground "green")
536 (t :weight bold :underline t))
537 "Face for category-file header in Todo Filtered Items mode."
538 :group 'todo-faces)
540 ;; -----------------------------------------------------------------------------
541 ;;; Entering and exiting
542 ;; -----------------------------------------------------------------------------
544 ;; (defcustom todo-visit-files-commands (list 'find-file 'dired-find-file)
545 ;; "List of file finding commands for `todo-display-as-todo-file'.
546 ;; Invoking these commands to visit a todo file or todo archive file
547 ;; calls `todo-show' or `todo-find-archive', so that the file is
548 ;; displayed correctly."
549 ;; :type '(repeat function)
550 ;; :group 'todo)
552 (defun todo-short-file-name (file)
553 "Return the short form of todo file FILE's name.
554 This lacks the extension and directory components."
555 (when (stringp file)
556 (file-name-sans-extension (file-name-nondirectory file))))
558 (defcustom todo-default-todo-file (todo-short-file-name
559 (car (funcall todo-files-function)))
560 "Todo file visited by first session invocation of `todo-show'."
561 :type (when todo-files
562 `(radio ,@(mapcar (lambda (f) (list 'const f))
563 (mapcar 'todo-short-file-name
564 (funcall todo-files-function)))))
565 :group 'todo)
567 (defcustom todo-show-current-file t
568 "Non-nil to make `todo-show' visit the current todo file.
569 Otherwise, `todo-show' always visits `todo-default-todo-file'."
570 :type 'boolean
571 :initialize 'custom-initialize-default
572 :set 'todo-set-show-current-file
573 :group 'todo)
575 (defcustom todo-show-first 'first
576 "What action to take on first use of `todo-show' on a file."
577 :type '(choice (const :tag "Show first category" first)
578 (const :tag "Show table of categories" table)
579 (const :tag "Show top priorities" top)
580 (const :tag "Show diary items" diary)
581 (const :tag "Show regexp items" regexp))
582 :group 'todo)
584 (defcustom todo-add-item-if-new-category t
585 "Non-nil to prompt for an item after adding a new category."
586 :type 'boolean
587 :group 'todo-edit)
589 (defcustom todo-initial-file "Todo"
590 "Default file name offered on adding first todo file."
591 :type 'string
592 :group 'todo)
594 (defcustom todo-initial-category "Todo"
595 "Default category name offered on initializing a new todo file."
596 :type 'string
597 :group 'todo)
599 (defcustom todo-category-completions-files nil
600 "List of files for building `todo-read-category' completions."
601 :type `(set ,@(mapcar (lambda (f) (list 'const f))
602 (mapcar 'todo-short-file-name
603 (funcall todo-files-function))))
604 :group 'todo)
606 (defcustom todo-completion-ignore-case nil
607 "Non-nil means case is ignored by `todo-read-*' functions."
608 :type 'boolean
609 :group 'todo)
611 ;;;###autoload
612 (defun todo-show (&optional solicit-file interactive)
613 "Visit a todo file and display one of its categories.
615 When invoked in Todo mode, prompt for which todo file to visit.
616 When invoked outside of Todo mode with non-nil prefix argument
617 SOLICIT-FILE prompt for which todo file to visit; otherwise visit
618 `todo-default-todo-file'. Subsequent invocations from outside
619 of Todo mode revisit this file or, with option
620 `todo-show-current-file' non-nil (the default), whichever todo
621 file was last visited.
623 If you call this command before you have created any todo file in
624 the current format, and you have an todo file in old format, it
625 will ask you whether to convert that file and show it.
626 Otherwise, calling this command before any todo file exists
627 prompts for a file name and an initial category (defaulting to
628 `todo-initial-file' and `todo-initial-category'), creates both of
629 these, visits the file and displays the category, and if option
630 `todo-add-item-if-new-category' is non-nil (the default), prompts
631 for the first item.
633 The first invocation of this command on an existing todo file
634 interacts with the option `todo-show-first': if its value is
635 `first' (the default), show the first category in the file; if
636 its value is `table', show the table of categories in the file;
637 if its value is one of `top', `diary' or `regexp', show the
638 corresponding saved top priorities, diary items, or regexp items
639 file, if any. Subsequent invocations always show the file's
640 current (i.e., last displayed) category.
642 In Todo mode just the category's unfinished todo items are shown
643 by default. The done items are hidden, but typing
644 `\\[todo-toggle-view-done-items]' displays them below the todo
645 items. With non-nil user option `todo-show-with-done' both todo
646 and done items are always shown on visiting a category.
648 Invoking this command in Todo Archive mode visits the
649 corresponding todo file, displaying the corresponding category."
650 (interactive "P\np")
651 (when todo-default-todo-file
652 (todo-check-file (todo-absolute-file-name todo-default-todo-file)))
653 (catch 'shown
654 ;; Before initializing the first todo first, check if there is a
655 ;; legacy todo file and if so, offer to convert to the current
656 ;; format and make it the first new todo file.
657 (unless todo-default-todo-file
658 (let ((legacy-todo-file (if (boundp 'todo-file-do)
659 todo-file-do
660 (locate-user-emacs-file "todo-do" ".todo-do"))))
661 (when (and (file-exists-p legacy-todo-file)
662 (y-or-n-p (concat "Do you want to convert a copy of your "
663 "old todo file to the new format? ")))
664 (when (todo-convert-legacy-files)
665 (throw 'shown nil)))))
666 (catch 'end
667 (let* ((cat)
668 (show-first todo-show-first)
669 (file (cond ((or solicit-file
670 (and interactive
671 (memq major-mode '(todo-mode
672 todo-archive-mode
673 todo-filtered-items-mode))))
674 (if (funcall todo-files-function)
675 (todo-read-file-name "Choose a todo file to visit: "
676 nil t)
677 (user-error "There are no todo files")))
678 ((and (eq major-mode 'todo-archive-mode)
679 ;; Called noninteractively via todo-quit
680 ;; to jump to corresponding category in
681 ;; todo file.
682 (not interactive))
683 (setq cat (todo-current-category))
684 (concat (file-name-sans-extension
685 todo-current-todo-file) ".todo"))
687 (or todo-current-todo-file
688 (and todo-show-current-file
689 todo-global-current-todo-file)
690 (todo-absolute-file-name todo-default-todo-file)
691 (todo-add-file)))))
692 add-item first-file)
693 (unless todo-default-todo-file
694 ;; We just initialized the first todo file, so make it the default.
695 (setq todo-default-todo-file (todo-short-file-name file)
696 first-file t)
697 (todo-reevaluate-default-file-defcustom))
698 (unless (member file todo-visited)
699 ;; Can't setq t-c-t-f here, otherwise wrong file shown when
700 ;; todo-show is called from todo-show-categories-table.
701 (let ((todo-current-todo-file file))
702 (cond ((eq todo-show-first 'table)
703 (todo-show-categories-table))
704 ((memq todo-show-first '(top diary regexp))
705 (let* ((shortf (todo-short-file-name file))
706 (fi-file (todo-absolute-file-name
707 shortf todo-show-first)))
708 (when (eq todo-show-first 'regexp)
709 (let ((rxfiles (directory-files todo-directory t
710 ".*\\.todr$" t)))
711 (when (and rxfiles (> (length rxfiles) 1))
712 (let ((rxf (mapcar 'todo-short-file-name rxfiles)))
713 (setq fi-file (todo-absolute-file-name
714 (completing-read
715 "Choose a regexp items file: "
716 rxf) 'regexp))))))
717 (if (file-exists-p fi-file)
718 (progn
719 (set-window-buffer
720 (selected-window)
721 (set-buffer (find-file-noselect fi-file 'nowarn)))
722 (unless (derived-mode-p 'todo-filtered-items-mode)
723 (todo-filtered-items-mode)))
724 (message "There is no %s file for %s"
725 (cond ((eq todo-show-first 'top)
726 "top priorities")
727 ((eq todo-show-first 'diary)
728 "diary items")
729 ((eq todo-show-first 'regexp)
730 "regexp items"))
731 shortf)
732 (setq todo-show-first 'first)))))))
733 (when (or (member file todo-visited)
734 (eq todo-show-first 'first))
735 (unless (todo-check-file file) (throw 'end nil))
736 ;; If todo-show is called from the minibuffer, don't visit
737 ;; the todo file there.
738 (set-window-buffer (if (minibufferp) (minibuffer-selected-window)
739 (selected-window))
740 (set-buffer (find-file-noselect file 'nowarn)))
741 (if (equal (file-name-extension (buffer-file-name)) "toda")
742 (unless (derived-mode-p 'todo-archive-mode) (todo-archive-mode))
743 (unless (derived-mode-p 'todo-mode) (todo-mode)))
744 ;; When quitting an archive file, show the corresponding
745 ;; category in the corresponding todo file, if it exists.
746 (when (assoc cat todo-categories)
747 (setq todo-category-number (todo-category-number cat)))
748 ;; If this is a new todo file, add its first category.
749 (when (zerop (buffer-size))
750 ;; Don't confuse an erased buffer with a fresh buffer for
751 ;; adding a new todo file -- it might have been erased by
752 ;; mistake or due to a bug (e.g. Bug#20832).
753 (when (buffer-modified-p)
754 (error "Buffer is empty but modified, please report a bug"))
755 (let (cat-added)
756 (unwind-protect
757 (setq todo-category-number
758 (todo-add-category todo-current-todo-file "")
759 add-item todo-add-item-if-new-category
760 cat-added t)
761 (if cat-added
762 ;; If the category was added, save the file now, so we
763 ;; don't risk having an empty todo file, which would
764 ;; signal an error if we tried to visit it later,
765 ;; since doing that looks for category boundaries.
766 (save-buffer 0)
767 ;; If user cancels before adding the category, clean up
768 ;; and exit, so we have a fresh slate the next time.
769 (delete-file file)
770 ;; (setq todo-files (funcall todo-files-function))
771 (setq todo-files (delete file todo-files))
772 (when first-file
773 (setq todo-default-todo-file nil
774 todo-current-todo-file nil)
775 (todo-reevaluate-default-file-defcustom))
776 (kill-buffer)
777 (keyboard-quit)))))
778 (save-excursion (todo-category-select))
779 (when add-item (todo-insert-item--basic)))
780 (setq todo-show-first show-first)
781 (add-to-list 'todo-visited file)))))
783 (defun todo-save ()
784 "Save the current todo file."
785 (interactive)
786 (cond ((eq major-mode 'todo-filtered-items-mode)
787 (todo-check-filtered-items-file)
788 (todo-save-filtered-items-buffer))
790 (save-buffer))))
792 (defvar todo-descending-counts)
794 (defun todo-quit ()
795 "Exit the current Todo-related buffer.
796 Depending on the specific mode, this either kills the buffer or
797 buries it and restores state as needed."
798 (interactive)
799 (let ((buf (current-buffer)))
800 (cond ((eq major-mode 'todo-categories-mode)
801 ;; Postpone killing buffer till after calling todo-show, to
802 ;; prevent killing todo-mode buffer.
803 (setq todo-descending-counts nil)
804 ;; Ensure todo-show calls todo-show-categories-table only on
805 ;; first invocation per file.
806 (when (eq todo-show-first 'table)
807 (add-to-list 'todo-visited todo-current-todo-file))
808 (todo-show)
809 (kill-buffer buf))
810 ((eq major-mode 'todo-filtered-items-mode)
811 (kill-buffer)
812 (unless (eq major-mode 'todo-mode) (todo-show)))
813 ((eq major-mode 'todo-archive-mode)
814 ;; Have to write a newly created archive to file to avoid
815 ;; subsequent errors.
816 (todo-save)
817 (let ((todo-file (concat todo-directory
818 (todo-short-file-name todo-current-todo-file)
819 ".todo")))
820 (if (todo-check-file todo-file)
821 (todo-show)
822 (message "There is no todo file for this archive")))
823 ;; When todo-check-file runs in todo-show, it kills the
824 ;; buffer if the archive file was deleted externally.
825 (when (buffer-live-p buf) (bury-buffer buf)))
826 ((eq major-mode 'todo-mode)
827 (todo-save)
828 ;; If we just quit archive mode, just burying the buffer
829 ;; in todo-mode would return to archive.
830 (set-window-buffer (selected-window)
831 (set-buffer (other-buffer)))
832 (bury-buffer buf)))))
834 ;; -----------------------------------------------------------------------------
835 ;;; Navigation between and within categories
836 ;; -----------------------------------------------------------------------------
838 (defcustom todo-skip-archived-categories nil
839 "Non-nil to handle categories with only archived items specially.
841 Sequential category navigation using \\[todo-forward-category]
842 or \\[todo-backward-category] skips categories that contain only
843 archived items. Other commands still recognize these categories.
844 In Todo Categories mode (\\[todo-show-categories-table]) these
845 categories shown in `todo-archived-only' face and pressing the
846 category button visits the category in the archive instead of the
847 todo file."
848 :type 'boolean
849 :group 'todo-display)
851 (defun todo-forward-category (&optional back)
852 "Visit the numerically next category in this todo file.
853 If the current category is the highest numbered, visit the first
854 category. With non-nil argument BACK, visit the numerically
855 previous category (the highest numbered one, if the current
856 category is the first)."
857 (interactive)
858 (setq todo-category-number
859 (1+ (mod (- todo-category-number (if back 2 0))
860 (length todo-categories))))
861 (when todo-skip-archived-categories
862 (while (and (zerop (todo-get-count 'todo))
863 (zerop (todo-get-count 'done))
864 (not (zerop (todo-get-count 'archived))))
865 (setq todo-category-number
866 (apply (if back '1- '1+) (list todo-category-number)))))
867 (todo-category-select)
868 (goto-char (point-min)))
870 (defun todo-backward-category ()
871 "Visit the numerically previous category in this todo file.
872 If the current category is the highest numbered, visit the first
873 category."
874 (interactive)
875 (todo-forward-category t))
877 (defvar todo-categories-buffer)
879 (defun todo-jump-to-category (&optional file where)
880 "Prompt for a category in a todo file and jump to it.
882 With non-nil FILE (interactively a prefix argument), prompt for a
883 specific todo file and choose (with TAB completion) a category
884 in it to jump to; otherwise, choose and jump to any category in
885 either the current todo file or a file in
886 `todo-category-completions-files'.
888 Also accept a non-existing category name and ask whether to add a
889 new category by that name; on confirmation, add it and jump to
890 that category, and if option `todo-add-item-if-new-category' is
891 non-nil (the default), then prompt for the first item.
893 In noninteractive calls non-nil WHERE specifies either the goal
894 category or its file. If its value is `archive', the choice of
895 categories is restricted to the current archive file or the
896 archive you were prompted to choose; this is used by
897 `todo-jump-to-archive-category'. If its value is the name of a
898 category, jump directly to that category; this is used in Todo
899 Categories mode."
900 (interactive "P")
901 ;; If invoked outside of Todo mode and there is not yet any Todo
902 ;; file, initialize one.
903 (if (null (funcall todo-files-function))
904 (todo-show)
905 (let* ((archive (eq where 'archive))
906 (cat (unless archive where))
907 (file0 (when cat ; We're in Todo Categories mode.
908 ;; With non-nil `todo-skip-archived-categories'
909 ;; jump to archive file of a category with only
910 ;; archived items.
911 (if (and todo-skip-archived-categories
912 (zerop (todo-get-count 'todo cat))
913 (zerop (todo-get-count 'done cat))
914 (not (zerop (todo-get-count 'archived cat))))
915 (concat (file-name-sans-extension
916 todo-current-todo-file) ".toda")
917 ;; Otherwise, jump to current todo file.
918 todo-current-todo-file)))
919 (len (length todo-categories))
920 (cat+file (unless cat
921 (todo-read-category "Jump to category: "
922 (if archive 'archive) file)))
923 (add-item (and todo-add-item-if-new-category
924 (> (length todo-categories) len)))
925 (category (or cat (car cat+file))))
926 (unless cat (setq file0 (cdr cat+file)))
927 (with-current-buffer (find-file-noselect file0 'nowarn)
928 (setq todo-current-todo-file file0)
929 ;; If called from Todo Categories mode, clean up before jumping.
930 (if (string= (buffer-name) todo-categories-buffer)
931 (kill-buffer))
932 (set-window-buffer (selected-window)
933 (set-buffer (find-buffer-visiting file0)))
934 (unless todo-global-current-todo-file
935 (setq todo-global-current-todo-file todo-current-todo-file))
936 (todo-category-number category)
937 (todo-category-select)
938 (goto-char (point-min))
939 (when add-item (todo-insert-item--basic))))))
941 (defun todo-next-item (&optional count)
942 "Move point down to the beginning of the next item.
943 With positive numerical prefix COUNT, move point COUNT items
944 downward.
946 If the category's done items are hidden, this command also moves
947 point to the empty line below the last todo item from any higher
948 item in the category, i.e., when invoked with or without a prefix
949 argument. If the category's done items are visible, this command
950 called with a prefix argument only moves point to a lower item,
951 e.g., with point on the last todo item and called with prefix 1,
952 it moves point to the first done item; but if called with point
953 on the last todo item without a prefix argument, it moves point
954 the the empty line above the done items separator."
955 (interactive "p")
956 ;; It's not worth the trouble to allow prefix arg value < 1, since
957 ;; we have the corresponding command.
958 (cond ((and current-prefix-arg (< count 1))
959 (user-error "The prefix argument must be a positive number"))
960 (current-prefix-arg
961 (todo-forward-item count))
963 (todo-forward-item))))
965 (defun todo-previous-item (&optional count)
966 "Move point up to start of item with next higher priority.
967 With positive numerical prefix COUNT, move point COUNT items
968 upward.
970 If the category's done items are visible, this command called
971 with a prefix argument only moves point to a higher item, e.g.,
972 with point on the first done item and called with prefix 1, it
973 moves to the last todo item; but if called with point on the
974 first done item without a prefix argument, it moves point the the
975 empty line above the done items separator."
976 (interactive "p")
977 ;; Avoid moving to bob if on the first item but not at bob.
978 (when (> (line-number-at-pos) 1)
979 ;; It's not worth the trouble to allow prefix arg value < 1, since
980 ;; we have the corresponding command.
981 (cond ((and current-prefix-arg (< count 1))
982 (user-error "The prefix argument must be a positive number"))
983 (current-prefix-arg
984 (todo-backward-item count))
986 (todo-backward-item)))))
988 ;; -----------------------------------------------------------------------------
989 ;;; Display toggle commands
990 ;; -----------------------------------------------------------------------------
992 (defun todo-toggle-prefix-numbers ()
993 "Hide item numbering if shown, show if hidden."
994 (interactive)
995 (save-excursion
996 (save-restriction
997 (goto-char (point-min))
998 (let* ((ov (todo-get-overlay 'prefix))
999 (show-done (re-search-forward todo-done-string-start nil t))
1000 (todo-show-with-done show-done)
1001 (todo-number-prefix (not (equal (overlay-get ov 'before-string)
1002 "1 "))))
1003 (if (eq major-mode 'todo-filtered-items-mode)
1004 (todo-prefix-overlays)
1005 (todo-category-select))))))
1007 (defun todo-toggle-view-done-items ()
1008 "Show hidden or hide visible done items in current category."
1009 (interactive)
1010 (if (zerop (todo-get-count 'done (todo-current-category)))
1011 (message "There are no done items in this category.")
1012 (let ((opoint (point)))
1013 (goto-char (point-min))
1014 (let* ((shown (re-search-forward todo-done-string-start nil t))
1015 (todo-show-with-done (not shown)))
1016 (todo-category-select)
1017 (goto-char opoint)
1018 ;; If start of done items sections is below the bottom of the
1019 ;; window, make it visible.
1020 (unless shown
1021 (setq shown (progn
1022 (goto-char (point-min))
1023 (re-search-forward todo-done-string-start nil t)))
1024 (if (not (pos-visible-in-window-p shown))
1025 (recenter)
1026 (goto-char opoint)))))))
1028 (defun todo-toggle-view-done-only ()
1029 "Switch between displaying only done or only todo items."
1030 (interactive)
1031 (setq todo-show-done-only (not todo-show-done-only))
1032 (todo-category-select))
1034 (defun todo-toggle-item-highlighting ()
1035 "Highlight or unhighlight the todo item the cursor is on."
1036 (interactive)
1037 (eval-and-compile (require 'hl-line))
1038 (when (memq major-mode
1039 '(todo-mode todo-archive-mode todo-filtered-items-mode))
1040 (if hl-line-mode
1041 (hl-line-mode -1)
1042 (hl-line-mode 1))))
1044 (defun todo-toggle-item-header ()
1045 "Hide or show item date-time headers in the current file.
1046 With done items, this hides only the done date-time string, not
1047 the the original date-time string."
1048 (interactive)
1049 (save-excursion
1050 (save-restriction
1051 (goto-char (point-min))
1052 (let ((ov (todo-get-overlay 'header)))
1053 (if ov
1054 (remove-overlays 1 (1+ (buffer-size)) 'todo 'header)
1055 (widen)
1056 (goto-char (point-min))
1057 (while (not (eobp))
1058 (when (re-search-forward
1059 (concat todo-item-start
1060 "\\( " diary-time-regexp "\\)?"
1061 (regexp-quote todo-nondiary-end) "? ")
1062 nil t)
1063 (setq ov (make-overlay (match-beginning 0) (match-end 0) nil t))
1064 (overlay-put ov 'todo 'header)
1065 (overlay-put ov 'display ""))
1066 (todo-forward-item)))))))
1068 ;; -----------------------------------------------------------------------------
1069 ;;; File and category editing
1070 ;; -----------------------------------------------------------------------------
1072 (defun todo-add-file ()
1073 "Name and initialize a new todo file.
1074 Interactively, prompt for a category and display it, and if
1075 option `todo-add-item-if-new-category' is non-nil (the default),
1076 prompt for the first item.
1077 Noninteractively, return the name of the new file."
1078 (interactive)
1079 (let* ((prompt (concat "Enter name of new todo file "
1080 "(TAB or SPC to see current names): "))
1081 (file (todo-read-file-name prompt)))
1082 ;; Don't accept the name of an existing todo file.
1083 (setq file (todo-absolute-file-name
1084 (todo-validate-name (todo-short-file-name file) 'file)))
1085 (with-current-buffer (get-buffer-create file)
1086 (erase-buffer)
1087 (write-region (point-min) (point-max) file nil 'nomessage nil t)
1088 (kill-buffer file))
1089 (setq todo-files (funcall todo-files-function))
1090 (todo-reevaluate-filelist-defcustoms)
1091 (if (called-interactively-p 'any)
1092 (progn
1093 (set-window-buffer (selected-window)
1094 (set-buffer (find-file-noselect file)))
1095 (setq todo-current-todo-file file)
1096 (todo-show))
1097 file)))
1099 (defun todo-rename-file (&optional arg)
1100 "Rename the current todo file.
1101 With prefix ARG, prompt for a todo file and rename it.
1102 If there are corresponding archive or filtered items files,
1103 rename these accordingly. If there are live buffers visiting
1104 these files, also rename them accordingly."
1105 (interactive "P")
1106 (let* ((oname (or (and arg
1107 (todo-read-file-name "Choose a file to rename: "
1108 nil t))
1109 (buffer-file-name)))
1110 (soname (todo-short-file-name oname))
1111 (nname (todo-read-file-name "New name for this file: "))
1112 (snname (todo-short-file-name nname))
1113 (files (directory-files todo-directory t
1114 (concat ".*" (regexp-quote soname)
1115 ".*\\.tod[aorty]$") t)))
1116 (dolist (f files)
1117 (let* ((sfname (todo-short-file-name f))
1118 (fext (file-name-extension f t))
1119 (fbuf (find-buffer-visiting f))
1120 (fbname (buffer-name fbuf)))
1121 (when (string-match (regexp-quote soname) sfname)
1122 (let* ((snfname (replace-match snname t t sfname))
1123 (nfname (concat todo-directory snfname fext)))
1124 (rename-file f nfname)
1125 (when fbuf
1126 (with-current-buffer fbuf
1127 (set-visited-file-name nfname t t)
1128 (cond ((member fext '(".todo" ".toda"))
1129 (setq todo-current-todo-file (buffer-file-name))
1130 (setq mode-line-buffer-identification
1131 (funcall todo-mode-line-function
1132 (todo-current-category))))
1134 (rename-buffer
1135 (replace-regexp-in-string
1136 (regexp-quote soname) snname fbname))))))))))
1137 (setq todo-files (funcall todo-files-function)
1138 todo-archives (funcall todo-files-function t))
1139 (when (string= todo-default-todo-file soname)
1140 (setq todo-default-todo-file snname))
1141 (when (string= todo-global-current-todo-file oname)
1142 (setq todo-global-current-todo-file nname))
1143 (todo-reevaluate-filelist-defcustoms)))
1145 (defun todo-delete-file ()
1146 "Delete the current todo, archive or filtered items file.
1147 If the todo file has a corresponding archive file, or vice versa,
1148 prompt whether to delete that as well. Also kill the buffers
1149 visiting the deleted files."
1150 (interactive)
1151 (let* ((file1 (buffer-file-name))
1152 (todo (eq major-mode 'todo-mode))
1153 (archive (eq major-mode 'todo-archive-mode))
1154 (filtered (eq major-mode 'todo-filtered-items-mode))
1155 (file1-sn (todo-short-file-name file1))
1156 (file2 (concat todo-directory file1-sn (cond (todo ".toda")
1157 (archive ".todo"))))
1158 (buf1 (current-buffer))
1159 (buf2 (when file2 (find-buffer-visiting file2)))
1160 (prompt1 (concat "Delete " (cond (todo "todo")
1161 (archive "archive")
1162 (filtered "filtered items"))
1163 " file \"%s\"? "))
1164 (prompt2 (concat "Also delete the corresponding "
1165 (cond (todo "archive") (archive "todo")) " file "
1166 (when buf2 "and kill the buffer visiting it? ")))
1167 (delete1 (yes-or-no-p (format prompt1 file1-sn)))
1168 (delete2 (when (and delete1 (or (file-exists-p file2) buf2))
1169 (yes-or-no-p prompt2))))
1170 (when delete1
1171 (when (file-exists-p file1) (delete-file file1))
1172 (setq todo-visited (delete file1 todo-visited))
1173 (kill-buffer buf1)
1174 (if delete2
1175 (progn
1176 (when (file-exists-p file2) (delete-file file2))
1177 (setq todo-visited (delete file2 todo-visited))
1178 (and buf2 (kill-buffer buf2)))
1179 ;; If we deleted an archive but not its todo file, update the
1180 ;; latter's category sexp.
1181 (when (equal (file-name-extension file2) "todo")
1182 (with-current-buffer (or buf2 (find-file-noselect file2))
1183 (save-excursion
1184 (save-restriction
1185 (widen)
1186 (goto-char (point-min))
1187 (let ((sexp (read (buffer-substring-no-properties
1188 (line-beginning-position)
1189 (line-end-position))))
1190 (buffer-read-only nil))
1191 (mapc (lambda (x) (aset (cdr x) 3 0)) sexp)
1192 (delete-region (line-beginning-position) (line-end-position))
1193 (prin1 sexp (current-buffer)))))
1194 (todo-set-categories)
1195 (unless buf2 (kill-buffer)))))
1196 (setq todo-files (funcall todo-files-function)
1197 todo-archives (funcall todo-files-function t))
1198 (when (or (string= file1-sn todo-default-todo-file)
1199 (and delete2 (string= file1-sn todo-default-todo-file)))
1200 (setq todo-default-todo-file (todo-short-file-name (car todo-files))))
1201 (when (or (string= file1 todo-global-current-todo-file)
1202 (and delete2 (string= file2 todo-global-current-todo-file)))
1203 (setq todo-global-current-todo-file nil))
1204 (todo-reevaluate-filelist-defcustoms)
1205 (message (concat (cond (todo "Todo") (archive "Archive")) " file \"%s\" "
1206 (when delete2
1207 (concat "and its "
1208 (cond (todo "archive") (archive "todo"))
1209 " file "))
1210 "deleted")
1211 file1-sn))))
1213 (defvar todo-edit-buffer "*Todo Edit*"
1214 "Name of current buffer in Todo Edit mode.")
1216 (defun todo-edit-file ()
1217 "Put current buffer in `todo-edit-mode'.
1218 This makes the entire file visible and the buffer writable and
1219 you can use the self-insertion keys and standard Emacs editing
1220 commands to make changes. To return to Todo mode, type
1221 \\[todo-edit-quit]. This runs a file format check, signaling
1222 an error if the format has become invalid. However, this check
1223 cannot tell if the number of items changed, which could result in
1224 the file containing inconsistent information. For this reason
1225 this command should be used with caution."
1226 (interactive)
1227 (widen)
1228 (todo-edit-mode)
1229 (remove-overlays)
1230 (display-warning 'todo (format "\
1232 Type %s to return to Todo mode.
1234 This also runs a file format check and signals an error if
1235 the format has become invalid. However, this check cannot
1236 tell if the number of items or categories changed, which
1237 could result in the file containing inconsistent information.
1238 You can repair this inconsistency by invoking the command
1239 `todo-repair-categories-sexp', but this will revert any
1240 renumbering of the categories you have made, so you will
1241 have to renumber them again (see `(todo-mode) Reordering
1242 Categories')." (substitute-command-keys "\\[todo-edit-quit]"))))
1244 (defun todo-add-category (&optional file cat)
1245 "Add a new category to a todo file.
1247 Called interactively with prefix argument FILE, prompt for a file
1248 and then for a new category to add to that file, otherwise prompt
1249 just for a category to add to the current todo file. After
1250 adding the category, visit it in Todo mode and if option
1251 `todo-add-item-if-new-category' is non-nil (the default), prompt
1252 for the first item.
1254 Non-interactively, add category CAT to file FILE; if FILE is nil,
1255 add CAT to the current todo file. After adding the category,
1256 return the new category number."
1257 (interactive "P")
1258 (let (catfil file0)
1259 ;; If cat is passed from caller, don't prompt, unless it is "",
1260 ;; which means the file was just added and has no category yet.
1261 (if (and cat (> (length cat) 0))
1262 (setq file0 (or (and (stringp file) file)
1263 todo-current-todo-file))
1264 (setq catfil (todo-read-category "Enter a new category name: "
1265 'add (when (called-interactively-p 'any)
1266 file))
1267 cat (car catfil)
1268 file0 (if (called-interactively-p 'any)
1269 (cdr catfil)
1270 file)))
1271 (find-file file0)
1272 (let ((counts (make-vector 4 0)) ; [todo diary done archived]
1273 (num (1+ (length todo-categories)))
1274 (buffer-read-only nil))
1275 (setq todo-current-todo-file file0)
1276 (setq todo-categories (append todo-categories
1277 (list (cons cat counts))))
1278 (widen)
1279 (goto-char (point-max))
1280 (save-excursion ; Save point for todo-category-select.
1281 (insert todo-category-beg cat "\n\n" todo-category-done "\n"))
1282 (todo-update-categories-sexp)
1283 ;; If invoked by user, display the newly added category, if
1284 ;; called programmatically return the category number to the
1285 ;; caller.
1286 (if (called-interactively-p 'any)
1287 (progn
1288 (setq todo-category-number num)
1289 (todo-category-select)
1290 (when todo-add-item-if-new-category
1291 (todo-insert-item--basic)))
1292 num))))
1294 (defun todo-rename-category ()
1295 "Rename current todo category.
1296 If this file has an archive containing this category, rename the
1297 category there as well."
1298 (interactive)
1299 (let* ((cat (todo-current-category))
1300 (new (read-from-minibuffer
1301 (format "Rename category \"%s\" to: " cat))))
1302 (setq new (todo-validate-name new 'category))
1303 (let* ((ofile todo-current-todo-file)
1304 (archive (concat (file-name-sans-extension ofile) ".toda"))
1305 (buffers (append (list ofile)
1306 (unless (zerop (todo-get-count 'archived cat))
1307 (list archive)))))
1308 (dolist (buf buffers)
1309 (with-current-buffer (find-file-noselect buf)
1310 (let (buffer-read-only)
1311 (setq todo-categories (todo-set-categories))
1312 (save-excursion
1313 (save-restriction
1314 (setcar (assoc cat todo-categories) new)
1315 (widen)
1316 (goto-char (point-min))
1317 (todo-update-categories-sexp)
1318 (re-search-forward (concat (regexp-quote todo-category-beg)
1319 "\\(" (regexp-quote cat) "\\)\n")
1320 nil t)
1321 (replace-match new t t nil 1)))))))
1322 (force-mode-line-update))
1323 (save-excursion (todo-category-select)))
1325 (defun todo-delete-category (&optional arg)
1326 "Delete current todo category provided it contains no items.
1327 With prefix ARG delete the category even if it does contain
1328 todo or done items."
1329 (interactive "P")
1330 (let* ((file todo-current-todo-file)
1331 (cat (todo-current-category))
1332 (todo (todo-get-count 'todo cat))
1333 (done (todo-get-count 'done cat))
1334 (archived (todo-get-count 'archived cat)))
1335 (if (and (not arg)
1336 (or (> todo 0) (> done 0)))
1337 (message "%s" (substitute-command-keys
1338 (concat "To delete a non-empty category, "
1339 "type C-u \\[todo-delete-category].")))
1340 (when (cond ((= (length todo-categories) 1)
1341 (todo-y-or-n-p
1342 (concat "This is the only category in this file; "
1343 "deleting it will also delete the file.\n"
1344 "Do you want to proceed? ")))
1345 ((> archived 0)
1346 (todo-y-or-n-p (format-message
1347 (concat "This category has archived items; "
1348 "the archived category will remain\n"
1349 "after deleting the todo category. "
1350 "Do you still want to delete it\n"
1351 "(see `todo-skip-archived-categories' "
1352 "for another option)? "))))
1354 (todo-y-or-n-p (concat "Permanently remove category \"" cat
1355 "\"" (and arg " and all its entries")
1356 "? "))))
1357 (widen)
1358 (let ((buffer-read-only)
1359 (beg (re-search-backward
1360 (concat "^" (regexp-quote (concat todo-category-beg cat))
1361 "\n") nil t))
1362 (end (if (re-search-forward
1363 (concat "\n\\(" (regexp-quote todo-category-beg)
1364 ".*\n\\)") nil t)
1365 (match-beginning 1)
1366 (point-max))))
1367 (remove-overlays beg end)
1368 (delete-region beg end)
1369 (if (= (length todo-categories) 1)
1370 ;; If deleted category was the only one, delete the file.
1371 (progn
1372 (todo-reevaluate-filelist-defcustoms)
1373 ;; Skip confirming killing the archive buffer if it has been
1374 ;; modified and not saved.
1375 (set-buffer-modified-p nil)
1376 (delete-file file)
1377 (kill-buffer)
1378 (message "Deleted todo file %s." file))
1379 (setq todo-categories (delete (assoc cat todo-categories)
1380 todo-categories))
1381 (todo-update-categories-sexp)
1382 (setq todo-category-number
1383 (1+ (mod todo-category-number (length todo-categories))))
1384 (todo-category-select)
1385 (goto-char (point-min))
1386 (message "Deleted category %s." cat)))))))
1388 (defun todo-move-category ()
1389 "Move current category to a different todo file.
1390 If the todo file chosen does not exist, it is created.
1391 If the current category has archived items, also move those to
1392 the archive of the file moved to, creating it if it does not exist."
1393 (interactive)
1394 (when (or (> (length todo-categories) 1)
1395 (todo-y-or-n-p (concat "This is the only category in this file; "
1396 "moving it will also delete the file.\n"
1397 "Do you want to proceed? ")))
1398 (let* ((ofile todo-current-todo-file)
1399 (cat (todo-current-category))
1400 (nfile (todo-read-file-name "Todo file to move this category to: "))
1401 (archive (concat (file-name-sans-extension ofile) ".toda"))
1402 (buffers (append (list ofile)
1403 (unless (zerop (todo-get-count 'archived cat))
1404 (list archive))))
1405 new)
1406 (while (equal nfile (file-truename ofile))
1407 (setq nfile (todo-read-file-name
1408 "Choose a file distinct from this file: ")))
1409 (unless (member nfile todo-files)
1410 (with-current-buffer (get-buffer-create nfile)
1411 (erase-buffer)
1412 (write-region (point-min) (point-max) nfile nil 'nomessage nil t)
1413 (kill-buffer nfile))
1414 (setq todo-files (funcall todo-files-function))
1415 (todo-reevaluate-filelist-defcustoms))
1416 (dolist (buf buffers)
1417 (with-current-buffer (find-file-noselect buf)
1418 (widen)
1419 (goto-char (point-max))
1420 (let* ((beg (re-search-backward
1421 (concat "^"
1422 (regexp-quote (concat todo-category-beg cat))
1423 "$")
1424 nil t))
1425 (end (if (re-search-forward
1426 (concat "^" (regexp-quote todo-category-beg))
1427 nil t 2)
1428 (match-beginning 0)
1429 (point-max)))
1430 (content (buffer-substring-no-properties beg end))
1431 (counts (cdr (assoc cat todo-categories)))
1432 buffer-read-only)
1433 ;; Move the category to the new file. Also update or create
1434 ;; archive file if necessary.
1435 (with-current-buffer
1436 (find-file-noselect
1437 ;; Regenerate todo-archives in case there
1438 ;; is a newly created archive.
1439 (if (member buf (funcall todo-files-function t))
1440 (concat (file-name-sans-extension nfile) ".toda")
1441 nfile))
1442 (if (equal (file-name-extension (buffer-file-name)) "toda")
1443 (unless (derived-mode-p 'todo-archive-mode)
1444 (todo-archive-mode))
1445 (unless (derived-mode-p 'todo-mode) (todo-mode)))
1446 (let* ((nfile-short (todo-short-file-name nfile))
1447 (prompt (concat
1448 (format "Todo file \"%s\" already has "
1449 nfile-short)
1450 (format "the category \"%s\";\n" cat)
1451 "enter a new category name: "))
1452 buffer-read-only)
1453 (widen)
1454 (goto-char (point-max))
1455 (insert content)
1456 ;; If the file moved to has a category with the same
1457 ;; name, rename the moved category.
1458 (when (assoc cat todo-categories)
1459 (unless (member (file-truename (buffer-file-name))
1460 (funcall todo-files-function t))
1461 (setq new (read-from-minibuffer prompt))
1462 (setq new (todo-validate-name new 'category))))
1463 ;; Replace old with new name in todo and archive files.
1464 (when new
1465 (goto-char (point-max))
1466 (re-search-backward
1467 (concat "^" (regexp-quote todo-category-beg)
1468 "\\(" (regexp-quote cat) "\\)$") nil t)
1469 (replace-match new nil nil nil 1)))
1470 (setq todo-categories
1471 (append todo-categories (list (cons (or new cat) counts))))
1472 (todo-update-categories-sexp)
1473 ;; If archive was just created, save it to avoid "File
1474 ;; <xyz> no longer exists!" message on invoking
1475 ;; `todo-view-archived-items'.
1476 (unless (file-exists-p (buffer-file-name))
1477 (save-buffer))
1478 (todo-category-number (or new cat))
1479 (todo-category-select))
1480 ;; Delete the category from the old file, and if that was the
1481 ;; last category, delete the file. Also handle archive file
1482 ;; if necessary.
1483 (remove-overlays beg end)
1484 (delete-region beg end)
1485 (goto-char (point-min))
1486 ;; Put point after todo-categories sexp.
1487 (forward-line)
1488 (if (eobp) ; Aside from sexp, file is empty.
1489 (progn
1490 ;; Skip confirming killing the archive buffer.
1491 (set-buffer-modified-p nil)
1492 (delete-file todo-current-todo-file)
1493 (kill-buffer)
1494 (when (member todo-current-todo-file todo-files)
1495 (todo-reevaluate-filelist-defcustoms)))
1496 (setq todo-categories (delete (assoc cat todo-categories)
1497 todo-categories))
1498 (todo-update-categories-sexp)
1499 (when (> todo-category-number (length todo-categories))
1500 (setq todo-category-number 1))
1501 (todo-category-select)))))
1502 (set-window-buffer (selected-window)
1503 (set-buffer (find-file-noselect nfile)))
1504 (todo-category-number (or new cat))
1505 (todo-category-select))))
1507 (defun todo-merge-category (&optional file)
1508 "Merge current category into another existing category.
1510 With prefix argument FILE, prompt for a specific todo file and
1511 choose (with TAB completion) a category in it to merge into;
1512 otherwise, choose and merge into a category in either the
1513 current todo file or a file in `todo-category-completions-files'.
1515 After merging, the source category's todo and done items are
1516 appended to the chosen goal category's todo and done items,
1517 respectively. The goal category becomes the current category,
1518 and the source category is deleted.
1520 If both the source and goal categories also have archived items,
1521 they are also merged. If only the source category has archived
1522 items, the goal category is added as a new category to the
1523 archive file and the source category is deleted."
1524 (interactive "P")
1525 (let* ((tfile todo-current-todo-file)
1526 (cat (todo-current-category))
1527 (cat+file (todo-read-category "Merge into category: " 'todo file))
1528 (goal (car cat+file))
1529 (gfile (cdr cat+file))
1530 (tarchive (concat (file-name-sans-extension tfile) ".toda"))
1531 (garchive (concat (file-name-sans-extension gfile) ".toda"))
1532 (archived-count (todo-get-count 'archived))
1533 here)
1534 (with-current-buffer (get-buffer (find-file-noselect tfile))
1535 (widen)
1536 (let* ((buffer-read-only nil)
1537 (cbeg (progn
1538 (re-search-backward
1539 (concat "^" (regexp-quote todo-category-beg)) nil t)
1540 (point-marker)))
1541 (tbeg (progn (forward-line) (point-marker)))
1542 (dbeg (progn
1543 (re-search-forward
1544 (concat "^" (regexp-quote todo-category-done)) nil t)
1545 (forward-line) (point-marker)))
1546 ;; Omit empty line between todo and done items.
1547 (tend (progn (forward-line -2) (point-marker)))
1548 (cend (progn
1549 (if (re-search-forward
1550 (concat "^" (regexp-quote todo-category-beg)) nil t)
1551 (progn
1552 (goto-char (match-beginning 0))
1553 (point-marker))
1554 (point-max-marker))))
1555 (todo (buffer-substring-no-properties tbeg tend))
1556 (done (buffer-substring-no-properties dbeg cend))
1557 (todo-count (todo-get-count 'todo cat))
1558 (done-count (todo-get-count 'done cat)))
1559 ;; Merge into goal todo category.
1560 (with-current-buffer (get-buffer (find-file-noselect gfile))
1561 (unless (derived-mode-p 'todo-mode) (todo-mode))
1562 (widen)
1563 (goto-char (point-min))
1564 (let ((buffer-read-only nil))
1565 ;; Merge any todo items.
1566 (unless (zerop (length todo))
1567 (re-search-forward
1568 (concat "^" (regexp-quote (concat todo-category-beg goal)) "$")
1569 nil t)
1570 (re-search-forward
1571 (concat "^" (regexp-quote todo-category-done)) nil t)
1572 (forward-line -1)
1573 (setq here (point-marker))
1574 (insert todo)
1575 (todo-update-count 'todo todo-count goal))
1576 ;; Merge any done items.
1577 (unless (zerop (length done))
1578 (goto-char (if (re-search-forward
1579 (concat "^" (regexp-quote todo-category-beg))
1580 nil t)
1581 (match-beginning 0)
1582 (point-max)))
1583 (when (zerop (length todo)) (setq here (point-marker)))
1584 (insert done)
1585 (todo-update-count 'done done-count goal)))
1586 (todo-update-categories-sexp))
1587 ;; Update and clean up source todo file.
1588 (remove-overlays cbeg cend)
1589 (delete-region cbeg cend)
1590 (setq todo-categories (delete (assoc cat todo-categories)
1591 todo-categories))
1592 (todo-update-categories-sexp)
1593 (when (> todo-category-number (length todo-categories))
1594 (setq todo-category-number 1))
1595 (todo-category-select)
1596 (mapc (lambda (m) (set-marker m nil))
1597 (list cbeg tbeg dbeg tend cend))))
1598 (when (> archived-count 0)
1599 (with-current-buffer (get-buffer (find-file-noselect tarchive))
1600 (widen)
1601 (goto-char (point-min))
1602 (let* ((buffer-read-only nil)
1603 (cbeg (progn
1604 (when (re-search-forward
1605 (concat "^" (regexp-quote
1606 (concat todo-category-beg cat)) "$")
1607 nil t)
1608 (goto-char (match-beginning 0))
1609 (point-marker))))
1610 (cend (if (re-search-forward
1611 (concat "^" (regexp-quote todo-category-beg)) nil t)
1612 (match-beginning 0)
1613 (point-max)))
1614 (carch (progn
1615 (goto-char cbeg)
1616 (forward-line)
1617 (buffer-substring-no-properties (point) cend))))
1618 ;; Merge into goal archive category, if it exists, else create it.
1619 (with-current-buffer (get-buffer (find-file-noselect garchive))
1620 (let ((gbeg (when (re-search-forward
1621 (concat "^" (regexp-quote
1622 (concat todo-category-beg goal))
1623 "$")
1624 nil t)
1625 (goto-char (match-beginning 0))
1626 (point-marker))))
1627 (goto-char (if (and gbeg
1628 (re-search-forward
1629 (concat "^" (regexp-quote todo-category-beg))
1630 nil t))
1631 (match-beginning 0)
1632 (point-max)))
1633 (unless gbeg (todo-add-category nil goal))
1634 (insert carch)
1635 (todo-update-categories-sexp)))
1636 ;; Update and clean up source archive file.
1637 (remove-overlays cbeg cend)
1638 (delete-region cbeg cend)
1639 (setq todo-categories (todo-make-categories-list t))
1640 (todo-update-categories-sexp))))
1641 ;; Update goal todo file for merged archived items and display it.
1642 (set-window-buffer (selected-window) (set-buffer (get-file-buffer gfile)))
1643 (unless (zerop archived-count)
1644 (todo-update-count 'archived archived-count goal)
1645 (todo-update-categories-sexp))
1646 (todo-category-number goal)
1647 ;; If there are only merged done items, show them.
1648 (let ((todo-show-with-done (zerop (todo-get-count 'todo goal))))
1649 (todo-category-select)
1650 ;; Put point on the first merged item.
1651 (goto-char here))
1652 (set-marker here nil)))
1654 ;; -----------------------------------------------------------------------------
1655 ;;; Item editing
1656 ;; -----------------------------------------------------------------------------
1658 (defcustom todo-include-in-diary nil
1659 "Non-nil to allow new todo items to be included in the diary."
1660 :type 'boolean
1661 :group 'todo-edit)
1663 (defcustom todo-diary-nonmarking nil
1664 "Non-nil to insert new todo diary items as nonmarking by default.
1665 This appends `diary-nonmarking-symbol' to the front of an item on
1666 insertion provided it doesn't begin with `todo-nondiary-marker'."
1667 :type 'boolean
1668 :group 'todo-edit)
1670 (defcustom todo-always-add-time-string nil
1671 "Non-nil adds current time to a new item's date header by default.
1672 When the todo insertion commands have a non-nil \"maybe-notime\"
1673 argument, this reverses the effect of
1674 `todo-always-add-time-string': if t, these commands omit the
1675 current time, if nil, they include it."
1676 :type 'boolean
1677 :group 'todo-edit)
1679 (defcustom todo-use-only-highlighted-region t
1680 "Non-nil to enable inserting only highlighted region as new item."
1681 :type 'boolean
1682 :group 'todo-edit)
1684 (defcustom todo-default-priority 'first
1685 "Default priority of new and moved items."
1686 :type '(choice (const :tag "Highest priority" first)
1687 (const :tag "Lowest priority" last))
1688 :group 'todo-edit)
1690 (defcustom todo-item-mark "*"
1691 "String used to mark items.
1692 To ensure item marking works, change the value of this option
1693 only when no items are marked."
1694 :type '(string :validate
1695 (lambda (widget)
1696 (when (string= (widget-value widget) todo-prefix)
1697 (widget-put
1698 widget :error
1699 (format-message
1700 "Invalid value: must be distinct from `todo-prefix'"))
1701 widget)))
1702 :set (lambda (symbol value)
1703 (custom-set-default symbol (propertize value 'face 'todo-mark)))
1704 :group 'todo-edit)
1706 (defcustom todo-comment-string "COMMENT"
1707 "String inserted before optional comment appended to done item."
1708 :type 'string
1709 :initialize 'custom-initialize-default
1710 :set 'todo-reset-comment-string
1711 :group 'todo-edit)
1713 (defcustom todo-undo-item-omit-comment 'ask
1714 "Whether to omit done item comment on undoing the item.
1715 Nil means never omit the comment, t means always omit it, `ask'
1716 means prompt user and omit comment only on confirmation."
1717 :type '(choice (const :tag "Never" nil)
1718 (const :tag "Always" t)
1719 (const :tag "Ask" ask))
1720 :group 'todo-edit)
1722 (defun todo-toggle-mark-item (&optional n)
1723 "Mark item with `todo-item-mark' if unmarked, otherwise unmark it.
1724 With positive numerical prefix argument N, change the marking of
1725 the next N items in the current category. If both the todo and
1726 done items sections are visible, the sequence of N items can
1727 consist of the the last todo items and the first done items."
1728 (interactive "p")
1729 (when (todo-item-string)
1730 (unless (> n 1) (setq n 1))
1731 (catch 'end
1732 (dotimes (i n)
1733 (let* ((cat (todo-current-category))
1734 (marks (assoc cat todo-categories-with-marks))
1735 (ov (progn
1736 (unless (looking-at todo-item-start)
1737 (todo-item-start))
1738 (todo-get-overlay 'prefix)))
1739 (pref (overlay-get ov 'before-string)))
1740 (if (todo-marked-item-p)
1741 (progn
1742 (overlay-put ov 'before-string (substring pref 1))
1743 (if (= (cdr marks) 1) ; Deleted last mark in this category.
1744 (setq todo-categories-with-marks
1745 (assq-delete-all cat todo-categories-with-marks))
1746 (setcdr marks (1- (cdr marks)))))
1747 (overlay-put ov 'before-string (concat todo-item-mark pref))
1748 (if marks
1749 (setcdr marks (1+ (cdr marks)))
1750 (push (cons cat 1) todo-categories-with-marks))))
1751 (todo-forward-item)
1752 ;; Don't try to mark the empty lines at the end of the todo
1753 ;; and done items sections.
1754 (when (looking-at "^$")
1755 (if (eobp)
1756 (throw 'end nil)
1757 (todo-forward-item)))))))
1759 (defun todo-mark-category ()
1760 "Mark all visible items in this category with `todo-item-mark'."
1761 (interactive)
1762 (let* ((cat (todo-current-category))
1763 (marks (assoc cat todo-categories-with-marks)))
1764 (save-excursion
1765 (goto-char (point-min))
1766 (while (not (eobp))
1767 (let* ((ov (todo-get-overlay 'prefix))
1768 (pref (overlay-get ov 'before-string)))
1769 (unless (todo-marked-item-p)
1770 (overlay-put ov 'before-string (concat todo-item-mark pref))
1771 (if marks
1772 (setcdr marks (1+ (cdr marks)))
1773 (push (cons cat 1) todo-categories-with-marks))))
1774 (todo-forward-item)
1775 ;; Don't try to mark the empty line between the todo and done
1776 ;; items sections.
1777 (when (looking-at "^$")
1778 (unless (eobp)
1779 (todo-forward-item)))))))
1781 (defun todo-unmark-category ()
1782 "Remove `todo-item-mark' from all visible items in this category."
1783 (interactive)
1784 (let* ((cat (todo-current-category))
1785 (marks (assoc cat todo-categories-with-marks)))
1786 (save-excursion
1787 (goto-char (point-min))
1788 (while (not (eobp))
1789 (let* ((ov (todo-get-overlay 'prefix))
1790 ;; No overlay on empty line between todo and done items.
1791 (pref (when ov (overlay-get ov 'before-string))))
1792 (when (todo-marked-item-p)
1793 (overlay-put ov 'before-string (substring pref 1)))
1794 (todo-forward-item))))
1795 (setq todo-categories-with-marks
1796 (delq marks todo-categories-with-marks))))
1798 (defvar todo-date-from-calendar nil
1799 "Helper variable for setting item date from the Emacs Calendar.")
1801 (defvar todo-insert-item--keys-so-far)
1802 (defvar todo-insert-item--parameters)
1804 (defun todo-insert-item (&optional arg)
1805 "Choose an item insertion operation and carry it out.
1806 This inserts a new todo item into a category.
1808 With no prefix argument ARG, add the item to the current
1809 category; with one prefix argument (`C-u'), prompt for a category
1810 from the current todo file; with two prefix arguments (`C-u
1811 C-u'), first prompt for a todo file, then a category in that
1812 file. If a non-existing category is entered, ask whether to add
1813 it to the todo file; if answered affirmatively, add the category
1814 and insert the item there.
1816 There are a number of item insertion parameters which can be
1817 combined by entering specific keys to produce different insertion
1818 commands. After entering each key, a message shows which have
1819 already been entered and which remain available. See
1820 `(todo-mode) Inserting New Items' for details of the parameters,
1821 their associated keys and their effects."
1822 (interactive "P")
1823 (setq todo-insert-item--keys-so-far "i")
1824 (todo-insert-item--next-param nil (list arg) todo-insert-item--parameters))
1826 (defun todo-insert-item--basic (&optional arg diary-type date-type time where)
1827 "Function implementing the core of `todo-insert-item'."
1828 ;; If invoked outside of Todo mode and there is not yet any Todo
1829 ;; file, initialize one.
1830 (if (null (funcall todo-files-function))
1831 (todo-show)
1832 (let ((copy (eq where 'copy))
1833 (region (eq where 'region))
1834 (here (eq where 'here))
1835 diary-item)
1836 (when copy
1837 (cond
1838 ((not (eq major-mode 'todo-mode))
1839 (user-error "You must be in Todo mode to copy a todo item"))
1840 ((todo-done-item-p)
1841 (user-error "You cannot copy a done item as a new todo item"))
1842 ((looking-at "^$")
1843 (user-error "Point must be on a todo item to copy it")))
1844 (setq diary-item (todo-diary-item-p)))
1845 (when region
1846 (let (use-empty-active-region)
1847 (unless (and todo-use-only-highlighted-region (use-region-p))
1848 (user-error "There is no active region"))))
1849 (let* ((obuf (current-buffer))
1850 (ocat (todo-current-category))
1851 (opoint (point))
1852 (todo-mm (eq major-mode 'todo-mode))
1853 (cat+file (cond ((equal arg '(4))
1854 (todo-read-category "Insert in category: "))
1855 ((equal arg '(16))
1856 (todo-read-category "Insert in category: "
1857 nil 'file))
1859 (cons (todo-current-category)
1860 (or todo-current-todo-file
1861 (and todo-show-current-file
1862 todo-global-current-todo-file)
1863 (todo-absolute-file-name
1864 todo-default-todo-file))))))
1865 (cat (car cat+file))
1866 (file (cdr cat+file))
1867 (new-item (cond (copy (todo-item-string))
1868 (region (buffer-substring-no-properties
1869 (region-beginning) (region-end)))
1870 (t (read-from-minibuffer "Todo item: "))))
1871 (date-string (cond
1872 ((eq date-type 'date)
1873 (todo-read-date))
1874 ((eq date-type 'dayname)
1875 (todo-read-dayname))
1876 ((eq date-type 'calendar)
1877 (setq todo-date-from-calendar t)
1878 (or (todo-set-date-from-calendar)
1879 ;; If user exits Calendar before choosing
1880 ;; a date, cancel item insertion.
1881 (keyboard-quit)))
1882 ((and (stringp date-type)
1883 (string-match todo-date-pattern date-type))
1884 (setq todo-date-from-calendar date-type)
1885 (todo-set-date-from-calendar))
1887 (calendar-date-string
1888 (calendar-current-date) t t))))
1889 (time-string (or (and time (todo-read-time))
1890 (and todo-always-add-time-string
1891 (substring (current-time-string) 11 16)))))
1892 (setq todo-date-from-calendar nil)
1893 (find-file-noselect file 'nowarn)
1894 (set-window-buffer (selected-window)
1895 (set-buffer (find-buffer-visiting file)))
1896 ;; If this command was invoked outside of a Todo mode buffer,
1897 ;; the call to todo-current-category above returned nil. If
1898 ;; we just entered Todo mode now, then cat was set to the
1899 ;; file's first category, but if todo-mode was already
1900 ;; enabled, cat did not get set, so we have to do that.
1901 (unless cat
1902 (setq cat (todo-current-category)))
1903 (setq todo-current-todo-file file)
1904 (unless todo-global-current-todo-file
1905 (setq todo-global-current-todo-file todo-current-todo-file))
1906 (let ((buffer-read-only nil)
1907 (called-from-outside (not (and todo-mm (equal cat ocat))))
1908 done-only item-added)
1909 (unless copy
1910 (setq new-item
1911 ;; Add date, time and diary marking as required.
1912 (concat (if (not (and diary-type
1913 (not todo-include-in-diary)))
1914 todo-nondiary-start
1915 (when (and (eq diary-type 'nonmarking)
1916 (not todo-diary-nonmarking))
1917 diary-nonmarking-symbol))
1918 date-string (when (and time-string ; Can be empty.
1919 (not (zerop (length
1920 time-string))))
1921 (concat " " time-string))
1922 (when (not (and diary-type
1923 (not todo-include-in-diary)))
1924 todo-nondiary-end)
1925 " " new-item))
1926 ;; Indent newlines inserted by C-q C-j if nonspace char follows.
1927 (setq new-item (replace-regexp-in-string "\\(\n\\)[^[:blank:]]"
1928 "\n\t" new-item nil nil 1)))
1929 (unwind-protect
1930 (progn
1931 ;; Make sure the correct category is selected. There
1932 ;; are two cases: (i) we just visited the file, so no
1933 ;; category is selected yet, or (ii) we invoked
1934 ;; insertion "here" from outside the category we want
1935 ;; to insert in (with priority insertion, category
1936 ;; selection is done by todo-set-item-priority).
1937 (when (or (= (- (point-max) (point-min)) (buffer-size))
1938 (and here called-from-outside))
1939 (todo-category-number cat)
1940 (todo-category-select))
1941 ;; If only done items are displayed in category,
1942 ;; toggle to todo items before inserting new item.
1943 (when (save-excursion
1944 (goto-char (point-min))
1945 (looking-at todo-done-string-start))
1946 (setq done-only t)
1947 (todo-toggle-view-done-only))
1948 (if here
1949 (progn
1950 ;; If command was invoked with point in done
1951 ;; items section or outside of the current
1952 ;; category, can't insert "here", so to be
1953 ;; useful give new item top priority.
1954 (when (or (todo-done-item-section-p)
1955 called-from-outside
1956 done-only)
1957 (goto-char (point-min)))
1958 (todo-insert-with-overlays new-item))
1959 (todo-set-item-priority new-item cat t))
1960 (setq item-added t))
1961 ;; If user cancels before setting priority, restore
1962 ;; display.
1963 (unless item-added
1964 (set-window-buffer (selected-window) (set-buffer obuf))
1965 (when ocat
1966 (unless (equal cat ocat)
1967 (todo-category-number ocat)
1968 (todo-category-select))
1969 (and done-only (todo-toggle-view-done-only)))
1970 (goto-char opoint))
1971 ;; If the todo items section is not visible when the
1972 ;; insertion command is called (either because only done
1973 ;; items were shown or because the category was not in the
1974 ;; current buffer), then if the item is inserted at the
1975 ;; end of the category, point is at eob and eob at
1976 ;; window-start, so that higher priority todo items are
1977 ;; out of view. So we recenter to make sure the todo
1978 ;; items are displayed in the window.
1979 (when item-added (recenter)))
1980 (todo-update-count 'todo 1)
1981 (when (or diary-item diary-type todo-include-in-diary)
1982 (todo-update-count 'diary 1))
1983 (todo-update-categories-sexp))))))
1985 (defun todo-set-date-from-calendar ()
1986 "Return string of date chosen from Calendar."
1987 (cond ((and (stringp todo-date-from-calendar)
1988 (string-match todo-date-pattern todo-date-from-calendar))
1989 todo-date-from-calendar)
1990 (todo-date-from-calendar
1991 (let (calendar-view-diary-initially-flag)
1992 (calendar)) ; *Calendar* is now current buffer.
1993 (define-key calendar-mode-map [remap newline] 'exit-recursive-edit)
1994 ;; If user exits Calendar before choosing a date, clean up properly.
1995 (define-key calendar-mode-map
1996 [remap calendar-exit] (lambda ()
1997 (interactive)
1998 (progn
1999 (calendar-exit)
2000 (exit-recursive-edit))))
2001 (message "Put cursor on a date and type <return> to set it.")
2002 (recursive-edit)
2003 (unwind-protect
2004 (when (equal (buffer-name) calendar-buffer)
2005 (setq todo-date-from-calendar
2006 (calendar-date-string (calendar-cursor-to-date t) t t))
2007 (calendar-exit)
2008 todo-date-from-calendar)
2009 (define-key calendar-mode-map [remap newline] nil)
2010 (define-key calendar-mode-map [remap calendar-exit] nil)
2011 (unless (zerop (recursion-depth)) (exit-recursive-edit))
2012 (when (stringp todo-date-from-calendar)
2013 todo-date-from-calendar)))))
2015 (defun todo-insert-item-from-calendar (&optional arg)
2016 "Prompt for and insert a new item with date selected from calendar.
2017 Invoked without prefix argument ARG, insert the item into the
2018 current category, without one prefix argument, prompt for the
2019 category from the current todo file or from one listed in
2020 `todo-category-completions-files'; with two prefix arguments,
2021 prompt for a todo file and then for a category in it."
2022 (interactive "P")
2023 (setq todo-date-from-calendar
2024 (calendar-date-string (calendar-cursor-to-date t) t t))
2025 (calendar-exit)
2026 (todo-insert-item--basic arg nil todo-date-from-calendar))
2028 (define-key calendar-mode-map "it" 'todo-insert-item-from-calendar)
2030 (defun todo-delete-item ()
2031 "Delete at least one item in this category.
2032 If there are marked items, delete all of these; otherwise, delete
2033 the item at point."
2034 (interactive)
2035 (let (ov)
2036 (unwind-protect
2037 (let* ((cat (todo-current-category))
2038 (marked (assoc cat todo-categories-with-marks))
2039 (item (unless marked (todo-item-string)))
2040 (answer (if marked
2041 (todo-y-or-n-p
2042 "Permanently delete all marked items? ")
2043 (when item
2044 (setq ov (make-overlay
2045 (save-excursion (todo-item-start))
2046 (save-excursion (todo-item-end))))
2047 (overlay-put ov 'face 'todo-search)
2048 (todo-y-or-n-p "Permanently delete this item? "))))
2049 buffer-read-only)
2050 (when answer
2051 (and marked (goto-char (point-min)))
2052 (catch 'done
2053 (while (not (eobp))
2054 (if (or (and marked (todo-marked-item-p)) item)
2055 (progn
2056 (if (todo-done-item-p)
2057 (todo-update-count 'done -1)
2058 (todo-update-count 'todo -1 cat)
2059 (and (todo-diary-item-p)
2060 (todo-update-count 'diary -1)))
2061 (if ov (delete-overlay ov))
2062 (todo-remove-item)
2063 ;; Don't leave point below last item.
2064 (and item (bolp) (eolp) (< (point-min) (point-max))
2065 (todo-backward-item))
2066 (when item
2067 (throw 'done (setq item nil))))
2068 (todo-forward-item))))
2069 (when marked
2070 (setq todo-categories-with-marks
2071 (assq-delete-all cat todo-categories-with-marks)))
2072 (todo-update-categories-sexp)
2073 (todo-prefix-overlays)))
2074 (if ov (delete-overlay ov)))))
2076 (defvar todo-edit-item--param-key-alist)
2077 (defvar todo-edit-done-item--param-key-alist)
2079 (defun todo-edit-item (&optional arg)
2080 "Choose an editing operation for the current item and carry it out."
2081 (interactive "P")
2082 (let ((marked (assoc (todo-current-category) todo-categories-with-marks)))
2083 (cond ((and (todo-done-item-p) (not marked))
2084 (todo-edit-item--next-key todo-edit-done-item--param-key-alist))
2085 ((or marked (todo-item-string))
2086 (todo-edit-item--next-key todo-edit-item--param-key-alist arg)))))
2088 (defun todo-edit-item--text (&optional arg)
2089 "Function providing the text editing facilities of `todo-edit-item'."
2090 (let ((full-item (todo-item-string)))
2091 ;; If there are marked items and user invokes a text-editing
2092 ;; commands with point not on an item, todo-item-start is nil and
2093 ;; 1+ signals an error, so just make this a noop.
2094 (when full-item
2095 (let* ((opoint (point))
2096 (start (todo-item-start))
2097 (end (save-excursion (todo-item-end)))
2098 (item-beg (progn
2099 (re-search-forward
2100 (concat todo-date-string-start todo-date-pattern
2101 "\\( " diary-time-regexp "\\)?"
2102 (regexp-quote todo-nondiary-end) "?")
2103 (line-end-position) t)
2104 (1+ (- (point) start))))
2105 (include-header (eq arg 'include-header))
2106 (comment-edit (eq arg 'comment-edit))
2107 (comment-delete (eq arg 'comment-delete))
2108 (header-string (substring full-item 0 item-beg))
2109 (item (if (or include-header comment-edit comment-delete)
2110 full-item
2111 (substring full-item item-beg)))
2112 (multiline (or (eq arg 'multiline)
2113 (> (length (split-string item "\n")) 1)))
2114 (comment (save-excursion
2115 (todo-item-start)
2116 (re-search-forward
2117 (concat " \\[" (regexp-quote todo-comment-string)
2118 ": \\([^]]+\\)\\]") end t)))
2119 (prompt (if comment "Edit comment: " "Enter a comment: "))
2120 (buffer-read-only nil))
2121 ;; When there are marked items, user can invoke todo-edit-item
2122 ;; even if point is not on an item, but text editing only
2123 ;; applies to the item at point.
2124 (when (or (and (todo-done-item-p)
2125 (or comment-edit comment-delete))
2126 (and (not (todo-done-item-p))
2127 (or (not arg) include-header multiline)))
2128 (cond
2129 ((or comment-edit comment-delete)
2130 (save-excursion
2131 (todo-item-start)
2132 (if (re-search-forward (concat " \\["
2133 (regexp-quote todo-comment-string)
2134 ": \\([^]]+\\)\\]") end t)
2135 (if comment-delete
2136 (when (todo-y-or-n-p "Delete comment? ")
2137 (delete-region (match-beginning 0) (match-end 0)))
2138 (replace-match (read-string prompt (cons (match-string 1) 1))
2139 nil nil nil 1))
2140 (if comment-delete
2141 (user-error "There is no comment to delete")
2142 (insert " [" todo-comment-string ": "
2143 (prog1 (read-string prompt)
2144 ;; If user moved point during editing,
2145 ;; make sure it moves back.
2146 (goto-char opoint)
2147 (todo-item-end))
2148 "]")))))
2149 (multiline
2150 (let ((buf todo-edit-buffer))
2151 (set-window-buffer (selected-window)
2152 (set-buffer (make-indirect-buffer
2153 (buffer-name) buf)))
2154 (narrow-to-region (todo-item-start) (todo-item-end))
2155 (todo-edit-mode)
2156 (message "%s" (substitute-command-keys
2157 (concat "Type \\[todo-edit-quit] "
2158 "to return to Todo mode.\n")))))
2160 (let ((new (concat (if include-header "" header-string)
2161 (read-string "Edit: " (if include-header
2162 (cons item item-beg)
2163 (cons item 0))))))
2164 (when include-header
2165 (while (not (string-match (concat todo-date-string-start
2166 todo-date-pattern) new))
2167 (setq new (read-from-minibuffer
2168 "Item must start with a date: " new))))
2169 ;; Ensure lines following hard newlines are indented.
2170 (setq new (replace-regexp-in-string "\\(\n\\)[^[:blank:]]"
2171 "\n\t" new nil nil 1))
2172 ;; If user moved point during editing, make sure it moves back.
2173 (goto-char opoint)
2174 (todo-remove-item)
2175 (todo-insert-with-overlays new)
2176 (move-to-column item-beg)))))))))
2178 (defun todo-edit-quit ()
2179 "Return from Todo Edit mode to Todo mode.
2180 If the item contains hard line breaks, make sure the following
2181 lines are indented by `todo-indent-to-here' to conform to diary
2182 format.
2184 If the whole file was in Todo Edit mode, check before returning
2185 whether the file is still a valid todo file and if so, also
2186 recalculate the todo file's categories sexp, in case changes were
2187 made in the number or names of categories."
2188 (interactive)
2189 (if (> (buffer-size) (- (point-max) (point-min)))
2190 ;; We got here via `e m'.
2191 (let ((item (buffer-string))
2192 (regex "\\(\n\\)[^[:blank:]]")
2193 (buf (buffer-base-buffer)))
2194 (while (not (string-match (concat todo-date-string-start
2195 todo-date-pattern) item))
2196 (setq item (read-from-minibuffer
2197 "Item must start with a date: " item)))
2198 ;; Ensure lines following hard newlines are indented.
2199 (when (string-match regex (buffer-string))
2200 (setq item (replace-regexp-in-string regex "\n\t" item nil nil 1))
2201 (delete-region (point-min) (point-max))
2202 (insert item))
2203 (kill-buffer)
2204 (unless (eq (current-buffer) buf)
2205 (set-window-buffer (selected-window) (set-buffer buf))))
2206 ;; We got here via `F e'.
2207 (when (todo-check-format)
2208 ;; FIXME: separate out sexp check?
2209 ;; If manual editing makes e.g. item counts change, have to
2210 ;; call this to update todo-categories, but it restores
2211 ;; category order to list order.
2212 ;; (todo-repair-categories-sexp)
2213 ;; Compare (todo-make-categories-list t) with sexp and if
2214 ;; different ask (todo-update-categories-sexp) ?
2215 (todo-mode)
2216 (let* ((cat-beg (concat "^" (regexp-quote todo-category-beg)
2217 "\\(.*\\)$"))
2218 (curline (buffer-substring-no-properties
2219 (line-beginning-position) (line-end-position)))
2220 (cat (cond ((string-match cat-beg curline)
2221 (match-string-no-properties 1 curline))
2222 ((or (re-search-backward cat-beg nil t)
2223 (re-search-forward cat-beg nil t))
2224 (match-string-no-properties 1)))))
2225 (todo-category-number cat)
2226 (todo-category-select)
2227 (goto-char (point-min))))))
2229 (defun todo-edit-item--header (what &optional inc)
2230 "Function providing header editing facilities of `todo-edit-item'."
2231 (let ((marked (assoc (todo-current-category) todo-categories-with-marks))
2232 (first t)
2233 (todo-date-from-calendar t)
2234 ;; INC must be an integer, but users could pass it via
2235 ;; `todo-edit-item' as e.g. `-' or `C-u'.
2236 (inc (prefix-numeric-value inc))
2237 (buffer-read-only nil)
2238 ndate ntime year monthname month day
2239 dayname) ; Needed by calendar-date-display-form.
2240 (when marked (todo--user-error-if-marked-done-item))
2241 (save-excursion
2242 (or (and marked (goto-char (point-min))) (todo-item-start))
2243 (catch 'end
2244 (while (not (eobp))
2245 (and marked
2246 (while (not (todo-marked-item-p))
2247 (todo-forward-item)
2248 (and (eobp) (throw 'end nil))))
2249 (re-search-forward (concat todo-date-string-start "\\(?1:"
2250 todo-date-pattern
2251 "\\)\\(?2: " diary-time-regexp "\\)?"
2252 (regexp-quote todo-nondiary-end) "?")
2253 (line-end-position) t)
2254 (let* ((odate (match-string-no-properties 1))
2255 (otime (match-string-no-properties 2))
2256 (odayname (match-string-no-properties 5))
2257 (omonthname (match-string-no-properties 6))
2258 (omonth (match-string-no-properties 7))
2259 (oday (match-string-no-properties 8))
2260 (oyear (match-string-no-properties 9))
2261 (tmn-array todo-month-name-array)
2262 (mlist (append tmn-array nil))
2263 (tma-array todo-month-abbrev-array)
2264 (mablist (append tma-array nil))
2265 (yy (and oyear (string-to-number oyear))) ; 0 if year is "*".
2266 (mm (or (and omonth (if (string= omonth "*") 13
2267 (string-to-number omonth)))
2268 (1+ (- (length mlist)
2269 (length (or (member omonthname mlist)
2270 (member omonthname mablist)))))))
2271 (dd (and oday (unless (string= oday "*")
2272 (string-to-number oday)))))
2273 ;; If there are marked items, use only the first to set
2274 ;; header changes, and apply these to all marked items.
2275 (when first
2276 (cond
2277 ((eq what 'date)
2278 (setq ndate (todo-read-date)))
2279 ((eq what 'calendar)
2280 (setq ndate (save-match-data (todo-set-date-from-calendar))))
2281 ((eq what 'today)
2282 (setq ndate (calendar-date-string (calendar-current-date) t t)))
2283 ((eq what 'dayname)
2284 (setq ndate (todo-read-dayname)))
2285 ((eq what 'time)
2286 (setq ntime (save-match-data (todo-read-time)))
2287 (when (> (length ntime) 0)
2288 (setq ntime (concat " " ntime))))
2289 ;; When date string consists only of a day name,
2290 ;; passing other date components is a noop.
2291 ((and odayname (memq what '(year month day))))
2292 ((eq what 'year)
2293 (setq day oday
2294 monthname omonthname
2295 month omonth
2296 year (cond ((not current-prefix-arg)
2297 (todo-read-date 'year))
2298 ((string= oyear "*")
2299 (user-error "Cannot increment *"))
2301 (number-to-string (+ yy inc))))))
2302 ((eq what 'month)
2303 (setf day oday
2304 year oyear
2305 (if (memq 'month calendar-date-display-form)
2306 month
2307 monthname)
2308 (cond ((not current-prefix-arg)
2309 (todo-read-date 'month))
2310 ((or (string= omonth "*") (= mm 13))
2311 (user-error "Cannot increment *"))
2313 (let ((mminc (+ mm inc)))
2314 ;; Increment or decrement month by INC
2315 ;; modulo 12.
2316 (setq mm (% mminc 12))
2317 ;; If result is 0, make month December.
2318 (setq mm (if (= mm 0) 12 (abs mm)))
2319 ;; Adjust year if necessary.
2320 (setq year (or (and (cond ((> mminc 12)
2321 (+ yy (/ mminc 12)))
2322 ((< mminc 1)
2323 (- yy (/ mminc 12) 1))
2324 (t yy))
2325 (number-to-string yy))
2326 oyear)))
2327 ;; Return the changed numerical month as
2328 ;; a string or the corresponding month name.
2329 (if omonth
2330 (number-to-string mm)
2331 (aref tma-array (1- mm))))))
2332 ;; Since the number corresponding to the arbitrary
2333 ;; month name "*" is out of the range of
2334 ;; calendar-last-day-of-month, set it to 1
2335 ;; (corresponding to January) to allow 31 days.
2336 (let ((mm (if (= mm 13) 1 mm)))
2337 (if (> (string-to-number day)
2338 (calendar-last-day-of-month mm yy))
2339 (user-error "%s %s does not have %s days"
2340 (aref tmn-array (1- mm))
2341 (if (= mm 2) yy "") day))))
2342 ((eq what 'day)
2343 (setq year oyear
2344 month omonth
2345 monthname omonthname
2346 day (cond
2347 ((not current-prefix-arg)
2348 (todo-read-date 'day mm yy))
2349 ((string= oday "*")
2350 (user-error "Cannot increment *"))
2351 ((or (string= omonth "*") (string= omonthname "*"))
2352 (setq dd (+ dd inc))
2353 (if (> dd 31)
2354 (user-error
2355 "A month cannot have more than 31 days")
2356 (number-to-string dd)))
2357 ;; Increment or decrement day by INC,
2358 ;; adjusting month and year if necessary
2359 ;; (if year is "*" assume current year to
2360 ;; calculate adjustment).
2362 (let* ((yy (or yy (calendar-extract-year
2363 (calendar-current-date))))
2364 (date (calendar-gregorian-from-absolute
2365 (+ (calendar-absolute-from-gregorian
2366 (list mm dd yy)) inc)))
2367 (adjmm (nth 0 date)))
2368 ;; Set year and month(name) to adjusted values.
2369 (unless (string= year "*")
2370 (setq year (number-to-string (nth 2 date))))
2371 (if month
2372 (setq month (number-to-string adjmm))
2373 (setq monthname (aref tma-array (1- adjmm))))
2374 ;; Return changed numerical day as a string.
2375 (number-to-string (nth 1 date)))))))))
2376 (unless odayname
2377 ;; If year, month or day date string components were
2378 ;; changed, rebuild the date string.
2379 (when (memq what '(year month day))
2380 (setq ndate (mapconcat 'eval calendar-date-display-form ""))))
2381 (when ndate (replace-match ndate nil nil nil 1))
2382 ;; Add new time string to the header, if it was supplied.
2383 (when ntime
2384 (if otime
2385 (replace-match ntime nil nil nil 2)
2386 (goto-char (match-end 1))
2387 (insert ntime)))
2388 (setq todo-date-from-calendar nil)
2389 (setq first nil))
2390 ;; Apply the changes to the first marked item header to the
2391 ;; remaining marked items. If there are no marked items,
2392 ;; we're finished.
2393 (if marked
2394 (todo-forward-item)
2395 (goto-char (point-max))))))))
2397 (defun todo-edit-item--diary-inclusion (&optional nonmarking)
2398 "Function providing diary marking facilities of `todo-edit-item'."
2399 (let ((buffer-read-only)
2400 (marked (assoc (todo-current-category) todo-categories-with-marks)))
2401 (when marked (todo--user-error-if-marked-done-item))
2402 (catch 'stop
2403 (save-excursion
2404 (when marked (goto-char (point-min)))
2405 (while (not (eobp))
2406 (unless (and marked (not (todo-marked-item-p)))
2407 (let* ((beg (todo-item-start))
2408 (lim (save-excursion (todo-item-end)))
2409 (end (save-excursion
2410 (or (todo-time-string-matcher lim)
2411 (todo-date-string-matcher lim)))))
2412 (if nonmarking
2413 (if (looking-at (regexp-quote diary-nonmarking-symbol))
2414 (replace-match "")
2415 (when (looking-at (regexp-quote todo-nondiary-start))
2416 (save-excursion
2417 (replace-match "")
2418 (search-forward todo-nondiary-end (1+ end) t)
2419 (replace-match "")
2420 (todo-update-count 'diary 1)))
2421 (insert diary-nonmarking-symbol))
2422 (if (looking-at (regexp-quote todo-nondiary-start))
2423 (progn
2424 (replace-match "")
2425 (search-forward todo-nondiary-end (1+ end) t)
2426 (replace-match "")
2427 (todo-update-count 'diary 1))
2428 (when end
2429 (when (looking-at (regexp-quote diary-nonmarking-symbol))
2430 (replace-match "")
2431 (setq end (1- end))) ; Since we deleted nonmarking symbol.
2432 (insert todo-nondiary-start)
2433 (goto-char (1+ end))
2434 (insert todo-nondiary-end)
2435 (todo-update-count 'diary -1))))))
2436 (unless marked (throw 'stop nil))
2437 (todo-forward-item)))))
2438 (todo-update-categories-sexp))
2440 (defun todo-edit-category-diary-inclusion (arg)
2441 "Make all items in this category diary items.
2442 With prefix ARG, make all items in this category non-diary
2443 items."
2444 (interactive "P")
2445 (save-excursion
2446 (goto-char (point-min))
2447 (let ((todo-count (todo-get-count 'todo))
2448 (diary-count (todo-get-count 'diary))
2449 (buffer-read-only))
2450 (catch 'stop
2451 (while (not (eobp))
2452 (if (todo-done-item-p) ; We've gone too far.
2453 (throw 'stop nil)
2454 (let* ((beg (todo-item-start))
2455 (lim (save-excursion (todo-item-end)))
2456 (end (save-excursion
2457 (or (todo-time-string-matcher lim)
2458 (todo-date-string-matcher lim)))))
2459 (if arg
2460 (unless (looking-at (regexp-quote todo-nondiary-start))
2461 (when (looking-at (regexp-quote diary-nonmarking-symbol))
2462 (replace-match "")
2463 (setq end (1- end))) ; Since we deleted nonmarking symbol.
2464 (insert todo-nondiary-start)
2465 (goto-char (1+ end))
2466 (insert todo-nondiary-end))
2467 (when (looking-at (regexp-quote todo-nondiary-start))
2468 (replace-match "")
2469 (search-forward todo-nondiary-end (1+ end) t)
2470 (replace-match "")))))
2471 (todo-forward-item))
2472 (unless (if arg (zerop diary-count) (= diary-count todo-count))
2473 (todo-update-count 'diary (if arg
2474 (- diary-count)
2475 (- todo-count diary-count))))
2476 (todo-update-categories-sexp)))))
2478 (defun todo-edit-category-diary-nonmarking (arg)
2479 "Add `diary-nonmarking-symbol' to all diary items in this category.
2480 With prefix ARG, remove `diary-nonmarking-symbol' from all diary
2481 items in this category."
2482 (interactive "P")
2483 (save-excursion
2484 (goto-char (point-min))
2485 (let (buffer-read-only)
2486 (catch 'stop
2487 (while (not (eobp))
2488 (if (todo-done-item-p) ; We've gone too far.
2489 (throw 'stop nil)
2490 (unless (looking-at (regexp-quote todo-nondiary-start))
2491 (if arg
2492 (when (looking-at (regexp-quote diary-nonmarking-symbol))
2493 (replace-match ""))
2494 (unless (looking-at (regexp-quote diary-nonmarking-symbol))
2495 (insert diary-nonmarking-symbol))))
2496 (todo-forward-item)))))))
2498 (defun todo-set-item-priority (&optional item cat new arg)
2499 "Prompt for and set ITEM's priority in CATegory.
2501 Interactively, ITEM is the todo item at point, CAT is the current
2502 category, and the priority is a number between 1 and the number
2503 of items in the category. Non-interactively, non-nil NEW means
2504 ITEM is a new item and the lowest priority is one more than the
2505 number of items in CAT.
2507 The new priority is set either interactively by prompt or by a
2508 numerical prefix argument, or noninteractively by argument ARG,
2509 whose value can be either of the symbols `raise' or `lower',
2510 meaning to raise or lower the item's priority by one."
2511 (interactive)
2512 (unless (and (called-interactively-p 'any)
2513 (or (todo-done-item-p) (looking-at "^$")))
2514 (let* ((item (or item (todo-item-string)))
2515 (marked (todo-marked-item-p))
2516 (cat (or cat (cond ((eq major-mode 'todo-mode)
2517 (todo-current-category))
2518 ((eq major-mode 'todo-filtered-items-mode)
2519 (let* ((regexp1
2520 (concat todo-date-string-start
2521 todo-date-pattern
2522 "\\( " diary-time-regexp "\\)?"
2523 (regexp-quote todo-nondiary-end)
2524 "?\\(?1: \\[\\(.+:\\)?.+\\]\\)")))
2525 (save-excursion
2526 (re-search-forward regexp1 nil t)
2527 (match-string-no-properties 1)))))))
2528 curnum
2529 (todo (cond ((or (eq arg 'raise) (eq arg 'lower)
2530 (eq major-mode 'todo-filtered-items-mode))
2531 (save-excursion
2532 (let ((curstart (todo-item-start))
2533 (count 0))
2534 (goto-char (point-min))
2535 (while (looking-at todo-item-start)
2536 (setq count (1+ count))
2537 (when (= (point) curstart) (setq curnum count))
2538 (todo-forward-item))
2539 count)))
2540 ((eq major-mode 'todo-mode)
2541 (todo-get-count 'todo cat))))
2542 (maxnum (if new (1+ todo) todo))
2543 (prompt (format "Set item priority (1-%d): " maxnum))
2544 (priority (cond ((and (not arg) (numberp current-prefix-arg))
2545 current-prefix-arg)
2546 ((and (eq arg 'raise) (>= curnum 1))
2547 (1- curnum))
2548 ((and (eq arg 'lower) (<= curnum maxnum))
2549 (1+ curnum))))
2550 candidate
2551 buffer-read-only)
2552 (unless (and priority
2553 (or (and (eq arg 'raise) (zerop priority))
2554 (and (eq arg 'lower) (> priority maxnum))))
2555 ;; When moving item to another category, show the category before
2556 ;; prompting for its priority.
2557 (unless (or arg (called-interactively-p 'any))
2558 (todo-category-number cat)
2559 ;; If done items in category are visible, keep them visible.
2560 (let ((done todo-show-with-done))
2561 (when (> (buffer-size) (- (point-max) (point-min)))
2562 (save-excursion
2563 (goto-char (point-min))
2564 (setq done (re-search-forward todo-done-string-start nil t))))
2565 (let ((todo-show-with-done done))
2566 ;; Keep current item or top of moved to category in view
2567 ;; while setting priority.
2568 (save-excursion (todo-category-select)))))
2569 ;; Prompt for priority only when the category has at least one
2570 ;; todo item.
2571 (when (> maxnum 1)
2572 (while (not priority)
2573 (setq candidate (read-number prompt
2574 (if (eq todo-default-priority 'first)
2575 1 maxnum)))
2576 (setq prompt (when (or (< candidate 1) (> candidate maxnum))
2577 (format "Priority must be an integer between 1 and %d.\n"
2578 maxnum)))
2579 (unless prompt (setq priority candidate))))
2580 ;; In Top Priorities buffer, an item's priority can be changed
2581 ;; wrt items in another category, but not wrt items in the same
2582 ;; category.
2583 (when (eq major-mode 'todo-filtered-items-mode)
2584 (let* ((regexp2 (concat todo-date-string-start todo-date-pattern
2585 "\\( " diary-time-regexp "\\)?"
2586 (regexp-quote todo-nondiary-end)
2587 "?\\(?1:" (regexp-quote cat) "\\)"))
2588 (end (cond ((< curnum priority)
2589 (save-excursion (todo-item-end)))
2590 ((> curnum priority)
2591 (save-excursion (todo-item-start)))))
2592 (match (save-excursion
2593 (cond ((< curnum priority)
2594 (todo-forward-item (1+ (- priority curnum)))
2595 (when (re-search-backward regexp2 end t)
2596 (match-string-no-properties 1)))
2597 ((> curnum priority)
2598 (todo-backward-item (- curnum priority))
2599 (when (re-search-forward regexp2 end t)
2600 (match-string-no-properties 1)))))))
2601 (when match
2602 (user-error (concat "Cannot reprioritize items from the same "
2603 "category in this mode, only in Todo mode")))))
2604 ;; Interactively or with non-nil ARG, relocate the item within its
2605 ;; category.
2606 (when (or arg (called-interactively-p 'any))
2607 (todo-remove-item))
2608 (goto-char (point-min))
2609 (when priority
2610 (unless (= priority 1)
2611 (todo-forward-item (1- priority))
2612 ;; When called from todo-item-undone and the highest priority
2613 ;; is chosen, this advances point to the first done item, so
2614 ;; move it up to the empty line above the done items
2615 ;; separator.
2616 (when (looking-back (concat "^"
2617 (regexp-quote todo-category-done)
2618 "\n")
2619 (line-beginning-position 0))
2620 (todo-backward-item))))
2621 (todo-insert-with-overlays item)
2622 ;; If item was marked, restore the mark.
2623 (and marked
2624 (let* ((ov (todo-get-overlay 'prefix))
2625 (pref (overlay-get ov 'before-string)))
2626 (overlay-put ov 'before-string
2627 (concat todo-item-mark pref))))))))
2629 (defun todo-raise-item-priority ()
2630 "Raise priority of current item by moving it up by one item."
2631 (interactive)
2632 (todo-set-item-priority nil nil nil 'raise))
2634 (defun todo-lower-item-priority ()
2635 "Lower priority of current item by moving it down by one item."
2636 (interactive)
2637 (todo-set-item-priority nil nil nil 'lower))
2639 (defun todo-move-item (&optional file)
2640 "Move at least one todo or done item to another category.
2641 If there are marked items, move all of these; otherwise, move
2642 the item at point.
2644 With prefix argument FILE, prompt for a specific todo file and
2645 choose (with TAB completion) a category in it to move the item or
2646 items to; otherwise, choose and move to any category in either
2647 the current todo file or one of the files in
2648 `todo-category-completions-files'. If the chosen category is
2649 not an existing categories, then it is created and the item(s)
2650 become(s) the first entry/entries in that category.
2652 With moved todo items, prompt to set the priority in the category
2653 moved to (with multiple todo items, the one that had the highest
2654 priority in the category moved from gets the new priority and the
2655 rest of the moved todo items are inserted in sequence below it).
2656 Moved done items are appended to the top of the done items
2657 section in the category moved to."
2658 (interactive "P")
2659 (let* ((cat1 (todo-current-category))
2660 (marked (assoc cat1 todo-categories-with-marks)))
2661 ;; Noop if point is not on an item and there are no marked items.
2662 (unless (and (looking-at "^$")
2663 (not marked))
2664 (let* ((buffer-read-only)
2665 (file1 todo-current-todo-file)
2666 (num todo-category-number)
2667 (item (todo-item-string))
2668 (diary-item (todo-diary-item-p))
2669 (done-item (and (todo-done-item-p) (concat item "\n")))
2670 (omark (save-excursion (todo-item-start) (point-marker)))
2671 (todo 0)
2672 (diary 0)
2673 (done 0)
2674 ov cat2 file2 moved nmark todo-items done-items)
2675 (unwind-protect
2676 (progn
2677 (unless marked
2678 (setq ov (make-overlay (save-excursion (todo-item-start))
2679 (save-excursion (todo-item-end))))
2680 (overlay-put ov 'face 'todo-search))
2681 (let* ((pl (if (and marked (> (cdr marked) 1)) "s" ""))
2682 (cat+file (todo-read-category (concat "Move item" pl
2683 " to category: ")
2684 nil file)))
2685 (while (and (equal (car cat+file) cat1)
2686 (equal (cdr cat+file) file1))
2687 (setq cat+file (todo-read-category
2688 "Choose a different category: ")))
2689 (setq cat2 (car cat+file)
2690 file2 (cdr cat+file))))
2691 (if ov (delete-overlay ov)))
2692 (set-buffer (find-buffer-visiting file1))
2693 (if marked
2694 (progn
2695 (goto-char (point-min))
2696 (while (not (eobp))
2697 (when (todo-marked-item-p)
2698 (if (todo-done-item-p)
2699 (setq done-items (concat done-items
2700 (todo-item-string) "\n")
2701 done (1+ done))
2702 (setq todo-items (concat todo-items
2703 (todo-item-string) "\n")
2704 todo (1+ todo))
2705 (when (todo-diary-item-p)
2706 (setq diary (1+ diary)))))
2707 (todo-forward-item))
2708 ;; Chop off last newline of multiple todo item string,
2709 ;; since it will be reinserted when setting priority
2710 ;; (but with done items priority is not set, so keep
2711 ;; last newline).
2712 (and todo-items
2713 (setq todo-items (substring todo-items 0 -1))))
2714 (if (todo-done-item-p)
2715 (setq done 1)
2716 (setq todo 1)
2717 (when (todo-diary-item-p) (setq diary 1))))
2718 (set-window-buffer (selected-window)
2719 (set-buffer (find-file-noselect file2 'nowarn)))
2720 (unwind-protect
2721 (progn
2722 (when (or todo-items (and item (not done-item)))
2723 (todo-set-item-priority (or todo-items item) cat2 t))
2724 ;; Move done items en bloc to top of done items section.
2725 (when (or done-items done-item)
2726 (todo-category-number cat2)
2727 (widen)
2728 (goto-char (point-min))
2729 (re-search-forward
2730 (concat "^" (regexp-quote (concat todo-category-beg cat2))
2731 "$") nil t)
2732 (re-search-forward
2733 (concat "^" (regexp-quote todo-category-done)) nil t)
2734 (forward-line)
2735 (insert (or done-items done-item)))
2736 (setq moved t))
2737 (cond
2738 ;; Move succeeded, so remove item from starting category,
2739 ;; update item counts and display the category containing
2740 ;; the moved item.
2741 (moved
2742 (setq nmark (point-marker))
2743 (when todo (todo-update-count 'todo todo))
2744 (when diary (todo-update-count 'diary diary))
2745 (when done (todo-update-count 'done done))
2746 (todo-update-categories-sexp)
2747 (with-current-buffer (find-buffer-visiting file1)
2748 (save-excursion
2749 (save-restriction
2750 (widen)
2751 (goto-char omark)
2752 (if marked
2753 (let (beg end)
2754 (setq item nil)
2755 (re-search-backward
2756 (concat "^" (regexp-quote todo-category-beg)) nil t)
2757 (forward-line)
2758 (setq beg (point))
2759 (setq end (if (re-search-forward
2760 (concat "^" (regexp-quote
2761 todo-category-beg)) nil t)
2762 (match-beginning 0)
2763 (point-max)))
2764 (goto-char beg)
2765 (while (< (point) end)
2766 (if (todo-marked-item-p)
2767 (todo-remove-item)
2768 (todo-forward-item)))
2769 (setq todo-categories-with-marks
2770 (assq-delete-all cat1 todo-categories-with-marks)))
2771 (if ov (delete-overlay ov))
2772 (todo-remove-item))))
2773 (when todo (todo-update-count 'todo (- todo) cat1))
2774 (when diary (todo-update-count 'diary (- diary) cat1))
2775 (when done (todo-update-count 'done (- done) cat1))
2776 (todo-update-categories-sexp))
2777 (set-window-buffer (selected-window)
2778 (set-buffer (find-file-noselect file2 'nowarn)))
2779 (setq todo-category-number (todo-category-number cat2))
2780 (let ((todo-show-with-done (or done-items done-item)))
2781 (todo-category-select))
2782 (goto-char nmark)
2783 ;; If item is moved to end of (just first?) category, make
2784 ;; sure the items above it are displayed in the window.
2785 (recenter))
2786 ;; User quit before setting priority of todo item(s), so
2787 ;; return to starting category.
2789 (set-window-buffer (selected-window)
2790 (set-buffer (find-file-noselect file1 'nowarn)))
2791 (todo-category-number cat1)
2792 (todo-category-select)
2793 (goto-char omark))))))))
2795 (defun todo-item-done (&optional arg)
2796 "Tag a todo item in this category as done and relocate it.
2798 With prefix argument ARG prompt for a comment and append it to
2799 the done item; this is only possible if there are no marked
2800 items. If there are marked items, tag all of these with
2801 `todo-done-string' plus the current date and, if
2802 `todo-always-add-time-string' is non-nil, the current time;
2803 otherwise, just tag the item at point. Items tagged as done are
2804 relocated to the category's (by default hidden) done section. If
2805 done items are visible on invoking this command, they remain
2806 visible."
2807 (interactive "P")
2808 (let* ((cat (todo-current-category))
2809 (marked (assoc cat todo-categories-with-marks)))
2810 (when marked (todo--user-error-if-marked-done-item))
2811 (unless (and (not marked)
2812 (or (todo-done-item-p)
2813 ;; Point is between todo and done items.
2814 (looking-at "^$")))
2815 (let* ((date-string (calendar-date-string (calendar-current-date) t t))
2816 (time-string (if todo-always-add-time-string
2817 (concat " " (substring (current-time-string)
2818 11 16))
2819 ""))
2820 (done-prefix (concat "[" todo-done-string date-string time-string
2821 "] "))
2822 (comment (and arg (read-string "Enter a comment: ")))
2823 (item-count 0)
2824 (diary-count 0)
2825 (show-done (save-excursion
2826 (goto-char (point-min))
2827 (re-search-forward todo-done-string-start nil t)))
2828 (buffer-read-only nil)
2829 item done-item
2830 (opoint (point)))
2831 ;; Don't add empty comment to done item.
2832 (setq comment (unless (zerop (length comment))
2833 (concat " [" todo-comment-string ": " comment "]")))
2834 (and marked (goto-char (point-min)))
2835 (catch 'done
2836 ;; Stop looping when we hit the empty line below the last
2837 ;; todo item (this is eobp if only done items are hidden).
2838 (while (not (looking-at "^$"))
2839 (if (or (not marked) (and marked (todo-marked-item-p)))
2840 (progn
2841 (setq item (todo-item-string))
2842 (setq done-item (concat done-item done-prefix item
2843 comment (and marked "\n")))
2844 (setq item-count (1+ item-count))
2845 (when (todo-diary-item-p)
2846 (setq diary-count (1+ diary-count)))
2847 (todo-remove-item)
2848 (unless marked (throw 'done nil)))
2849 (todo-forward-item))))
2850 (when marked
2851 ;; Chop off last newline of done item string.
2852 (setq done-item (substring done-item 0 -1))
2853 (setq todo-categories-with-marks
2854 (assq-delete-all cat todo-categories-with-marks)))
2855 (save-excursion
2856 (widen)
2857 (re-search-forward
2858 (concat "^" (regexp-quote todo-category-done)) nil t)
2859 (forward-char)
2860 (when show-done (setq opoint (point)))
2861 (insert done-item "\n"))
2862 (todo-update-count 'todo (- item-count))
2863 (todo-update-count 'done item-count)
2864 (todo-update-count 'diary (- diary-count))
2865 (todo-update-categories-sexp)
2866 (let ((todo-show-with-done show-done))
2867 (todo-category-select)
2868 ;; When done items are visible, put point at the top of the
2869 ;; done items section. When done items are hidden, restore
2870 ;; point to its location prior to invoking this command.
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
2878 item at point.
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."
2884 (interactive)
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)
2890 (opoint (point))
2891 (omark (point-marker))
2892 (first 'first)
2893 (item-count 0)
2894 (diary-count 0)
2895 start end item ov npoint undone)
2896 (and marked (goto-char (point-min)))
2897 (catch 'done
2898 (while (not (eobp))
2899 (when (or (not marked) (and marked (todo-marked-item-p)))
2900 (if (not (todo-done-item-p))
2901 (progn
2902 (goto-char opoint)
2903 (user-error "Only done items can be undone"))
2904 (todo-item-start)
2905 (unless marked
2906 (setq ov (make-overlay (save-excursion (todo-item-start))
2907 (save-excursion (todo-item-end))))
2908 (overlay-put ov 'face 'todo-search))
2909 ;; Find the end of the date string added upon tagging item as
2910 ;; done.
2911 (setq start (search-forward "] "))
2912 (setq item-count (1+ item-count))
2913 (unless (looking-at (regexp-quote todo-nondiary-start))
2914 (setq diary-count (1+ diary-count)))
2915 (setq end (save-excursion (todo-item-end)))
2916 ;; Ask (once) whether to omit done item's comment. If
2917 ;; affirmed, omit subsequent comments without asking.
2918 (when (re-search-forward
2919 (concat " \\[" (regexp-quote todo-comment-string)
2920 ": [^]]+\\]") end t)
2921 (unwind-protect
2922 (if (eq first 'first)
2923 (setq first
2924 (if (eq todo-undo-item-omit-comment 'ask)
2925 (when (todo-y-or-n-p
2926 (concat "Omit comment" pl
2927 " from restored item"
2928 pl "? "))
2929 'omit)
2930 (when todo-undo-item-omit-comment 'omit)))
2932 (when (and (eq first 'first) ov) (delete-overlay ov)))
2933 (when (eq first 'omit)
2934 (setq end (match-beginning 0))))
2935 (setq item (concat item
2936 (buffer-substring-no-properties start end)
2937 (when marked "\n")))
2938 (unless marked (throw 'done nil))))
2939 (todo-forward-item)))
2940 (unwind-protect
2941 (progn
2942 ;; Chop off last newline of multiple items string, since
2943 ;; it will be reinserted on setting priority.
2944 (and marked (setq item (substring item 0 -1)))
2945 (todo-set-item-priority item cat t)
2946 (setq npoint (point))
2947 (setq undone t))
2948 (when ov (delete-overlay ov))
2949 (if (not undone)
2950 (goto-char opoint)
2951 (if marked
2952 (progn
2953 (setq item nil)
2954 (re-search-forward
2955 (concat "^" (regexp-quote todo-category-done)) nil t)
2956 (while (not (eobp))
2957 (if (todo-marked-item-p)
2958 (todo-remove-item)
2959 (todo-forward-item)))
2960 (setq todo-categories-with-marks
2961 (assq-delete-all cat todo-categories-with-marks)))
2962 (goto-char omark)
2963 (todo-remove-item))
2964 (todo-update-count 'todo item-count)
2965 (todo-update-count 'done (- item-count))
2966 (when diary-count (todo-update-count 'diary diary-count))
2967 (todo-update-categories-sexp)
2968 (let ((todo-show-with-done (> (todo-get-count 'done) 0)))
2969 (todo-category-select))
2970 ;; Put cursor on undone item.
2971 (goto-char npoint)))
2972 (set-marker omark nil)))))
2974 ;; -----------------------------------------------------------------------------
2975 ;;; Done item archives
2976 ;; -----------------------------------------------------------------------------
2978 (defun todo-find-archive (&optional ask)
2979 "Visit the archive of the current todo category, if it exists.
2980 If the category has no archived items, prompt to visit the
2981 archive anyway. If there is no archive for this file or with
2982 non-nil argument ASK, prompt to visit another archive.
2984 The buffer showing the archive is in Todo Archive mode. The
2985 first visit in a session displays the first category in the
2986 archive, subsequent visits return to the last category
2987 displayed."
2988 (interactive)
2989 (if (null (funcall todo-files-function t))
2990 (message "There are no archive files")
2991 (let* ((cat (todo-current-category))
2992 (count (todo-get-count 'archived cat))
2993 (archive (concat (file-name-sans-extension todo-current-todo-file)
2994 ".toda"))
2995 (place (cond (ask 'other-archive)
2996 ((file-exists-p archive) 'this-archive)
2997 (t (when (todo-y-or-n-p
2998 (concat "This file has no archive; "
2999 "visit another archive? "))
3000 'other-archive)))))
3001 (when (eq place 'other-archive)
3002 (setq archive (todo-read-file-name "Choose a todo archive: " t t)))
3003 (when (and (eq place 'this-archive) (zerop count))
3004 (setq place (when (todo-y-or-n-p
3005 (concat "This category has no archived items;"
3006 " visit archive anyway? "))
3007 'other-cat)))
3008 (when place
3009 (set-window-buffer (selected-window)
3010 (set-buffer (find-file-noselect archive)))
3011 (unless (derived-mode-p 'todo-archive-mode) (todo-archive-mode))
3012 (if (member place '(other-archive other-cat))
3013 (setq todo-category-number 1)
3014 (todo-category-number cat))
3015 (todo-category-select)))))
3017 (defun todo-choose-archive ()
3018 "Choose an archive and visit it."
3019 (interactive)
3020 (todo-find-archive t))
3022 (defun todo-archive-done-item (&optional all)
3023 "Archive at least one done item in this category.
3025 With prefix argument ALL, prompt whether to archive all done
3026 items in this category and on confirmation archive them.
3027 Otherwise, if there are marked done items (and no marked todo
3028 items), archive all of these; otherwise, archive the done item at
3029 point.
3031 If the archive of this file does not exist, it is created. If
3032 this category does not exist in the archive, it is created."
3033 (interactive "P")
3034 (when (eq major-mode 'todo-mode)
3035 (if (and all (zerop (todo-get-count 'done)))
3036 (message "No done items in this category")
3037 (catch 'end
3038 (let* ((cat (todo-current-category))
3039 (tbuf (current-buffer))
3040 (marked (assoc cat todo-categories-with-marks))
3041 (afile (concat (file-name-sans-extension
3042 todo-current-todo-file) ".toda"))
3043 (archive (find-file-noselect afile t))
3044 (item (and (not marked) (todo-done-item-p)
3045 (concat (todo-item-string) "\n")))
3046 (count 0)
3047 (opoint (unless (todo-done-item-p) (point)))
3048 marked-items beg end all-done
3049 buffer-read-only)
3050 (cond
3051 (all
3052 (if (todo-y-or-n-p "Archive all done items in this category? ")
3053 (save-excursion
3054 (save-restriction
3055 (goto-char (point-min))
3056 (widen)
3057 (setq beg (progn
3058 (re-search-forward todo-done-string-start
3059 nil t)
3060 (match-beginning 0))
3061 end (if (re-search-forward
3062 (concat "^"
3063 (regexp-quote todo-category-beg))
3064 nil t)
3065 (match-beginning 0)
3066 (point-max))
3067 all-done (buffer-substring-no-properties beg end)
3068 count (todo-get-count 'done))
3069 ;; Restore starting point, unless it was on a done
3070 ;; item, since they will all be deleted.
3071 (when opoint (goto-char opoint))))
3072 (throw 'end nil)))
3073 (marked
3074 (save-excursion
3075 (goto-char (point-min))
3076 (while (not (eobp))
3077 (when (todo-marked-item-p)
3078 (if (not (todo-done-item-p))
3079 (throw 'end (message "Only done items can be archived"))
3080 (setq marked-items
3081 (concat marked-items (todo-item-string) "\n"))
3082 (setq count (1+ count))))
3083 (todo-forward-item)))))
3084 (if (not (or marked all item))
3085 (throw 'end (message "Only done items can be archived"))
3086 (with-current-buffer archive
3087 (unless (derived-mode-p 'todo-archive-mode) (todo-archive-mode))
3088 (let (buffer-read-only)
3089 (widen)
3090 (goto-char (point-min))
3091 (if (and (re-search-forward
3092 (concat "^" (regexp-quote
3093 (concat todo-category-beg cat)) "$")
3094 nil t)
3095 (re-search-forward (regexp-quote todo-category-done)
3096 nil t))
3097 ;; Start of done items section in existing category.
3098 (forward-char)
3099 (todo-add-category nil cat)
3100 ;; Start of done items section in new category.
3101 (goto-char (point-max)))
3102 (insert (cond (marked marked-items)
3103 (all all-done)
3104 (item)))
3105 (todo-update-count 'done (if (or marked all) count 1) cat)
3106 (todo-update-categories-sexp)
3107 ;; If archive is new, save to file now (with
3108 ;; write-region to avoid prompt for file to save to)
3109 ;; to update todo-archives, and set the mode for
3110 ;; visiting the archive below.
3111 (unless (nth 7 (file-attributes afile))
3112 (write-region nil nil afile t t)
3113 (setq todo-archives (funcall todo-files-function t))
3114 (todo-archive-mode))))
3115 (with-current-buffer tbuf
3116 (cond
3117 (all
3118 (save-excursion
3119 (save-restriction
3120 ;; Make sure done items are accessible.
3121 (widen)
3122 (remove-overlays beg end)
3123 (delete-region beg end)
3124 (todo-update-count 'done (- count))
3125 (todo-update-count 'archived count))))
3126 ((or marked
3127 ;; If we're archiving all done items, can't
3128 ;; first archive item point was on, since
3129 ;; that will short-circuit the rest.
3130 (and item (not all)))
3131 (and marked (goto-char (point-min)))
3132 (catch 'done
3133 (while (not (eobp))
3134 (if (or (and marked (todo-marked-item-p)) item)
3135 (progn
3136 (todo-remove-item)
3137 (todo-update-count 'done -1)
3138 (todo-update-count 'archived 1)
3139 ;; Don't leave point below last item.
3140 (and (or marked item) (bolp) (eolp)
3141 (< (point-min) (point-max))
3142 (todo-backward-item))
3143 (when item
3144 (throw 'done (setq item nil))))
3145 (todo-forward-item))))))
3146 (when marked
3147 (setq todo-categories-with-marks
3148 (assq-delete-all cat todo-categories-with-marks)))
3149 (todo-update-categories-sexp)
3150 (todo-prefix-overlays)))
3151 (find-file afile)
3152 (todo-category-number cat)
3153 (todo-category-select)
3154 (split-window-below)
3155 (set-window-buffer (selected-window) tbuf)
3156 ;; Make todo file current to select category.
3157 (find-file (buffer-file-name tbuf))
3158 ;; Make sure done item separator is hidden (if done items
3159 ;; were initially visible).
3160 (let (todo-show-with-done) (todo-category-select)))))))
3162 (defun todo-unarchive-items ()
3163 "Unarchive at least one item in this archive category.
3164 If there are marked items, unarchive all of these; otherwise,
3165 unarchive the item at point.
3167 Unarchived items are restored as done items to the corresponding
3168 category in the todo file, inserted at the top of done items
3169 section. If all items in the archive category have been
3170 restored, the category is deleted from the archive. If this was
3171 the only category in the archive, the archive file is deleted."
3172 (interactive)
3173 (when (eq major-mode 'todo-archive-mode)
3174 (let* ((cat (todo-current-category))
3175 (tbuf (find-file-noselect
3176 (concat (file-name-sans-extension todo-current-todo-file)
3177 ".todo") t))
3178 (marked (assoc cat todo-categories-with-marks))
3179 (item (concat (todo-item-string) "\n"))
3180 (marked-count 0)
3181 marked-items
3182 buffer-read-only)
3183 (when marked
3184 (save-excursion
3185 (goto-char (point-min))
3186 (while (not (eobp))
3187 (when (todo-marked-item-p)
3188 (setq marked-items (concat marked-items (todo-item-string) "\n"))
3189 (setq marked-count (1+ marked-count)))
3190 (todo-forward-item))))
3191 ;; Restore items to top of category's done section and update counts.
3192 (with-current-buffer tbuf
3193 (let (buffer-read-only newcat)
3194 (widen)
3195 (goto-char (point-min))
3196 ;; Find the corresponding todo category, or if there isn't
3197 ;; one, add it.
3198 (unless (re-search-forward
3199 (concat "^" (regexp-quote (concat todo-category-beg cat))
3200 "$") nil t)
3201 (todo-add-category nil cat)
3202 (setq newcat t))
3203 ;; Go to top of category's done section.
3204 (re-search-forward
3205 (concat "^" (regexp-quote todo-category-done)) nil t)
3206 (forward-line)
3207 (cond (marked
3208 (insert marked-items)
3209 (todo-update-count 'done marked-count cat)
3210 (unless newcat ; Newly added category has no archive.
3211 (todo-update-count 'archived (- marked-count) cat)))
3213 (insert item)
3214 (todo-update-count 'done 1 cat)
3215 (unless newcat ; Newly added category has no archive.
3216 (todo-update-count 'archived -1 cat))))
3217 (todo-update-categories-sexp)))
3218 ;; Delete restored items from archive.
3219 (when marked
3220 (setq item nil)
3221 (goto-char (point-min)))
3222 (catch 'done
3223 (while (not (eobp))
3224 (if (or (todo-marked-item-p) item)
3225 (progn
3226 (todo-remove-item)
3227 (when item
3228 (throw 'done (setq item nil))))
3229 (todo-forward-item))))
3230 (todo-update-count 'done (if marked (- marked-count) -1) cat)
3231 ;; If we unarchived the last item in category, then if that was
3232 ;; the only category, delete the whole file, otherwise, just
3233 ;; delete the category.
3234 (when (= 0 (todo-get-count 'done))
3235 (if (= 1 (length todo-categories))
3236 (progn
3237 (delete-file todo-current-todo-file)
3238 ;; Kill the archive buffer silently.
3239 (set-buffer-modified-p nil)
3240 (kill-buffer))
3241 (widen)
3242 (let ((beg (re-search-backward
3243 (concat "^" (regexp-quote todo-category-beg) cat "$")
3244 nil t))
3245 (end (if (re-search-forward
3246 (concat "^" (regexp-quote todo-category-beg))
3247 nil t 2)
3248 (match-beginning 0)
3249 (point-max))))
3250 (remove-overlays beg end)
3251 (delete-region beg end)
3252 (setq todo-categories (delete (assoc cat todo-categories)
3253 todo-categories)))))
3254 (todo-update-categories-sexp)
3255 ;; Visit category in todo file and show restored done items.
3256 (let ((tfile (buffer-file-name tbuf))
3257 (todo-show-with-done t))
3258 (set-window-buffer (selected-window)
3259 (set-buffer (find-file-noselect tfile)))
3260 (todo-category-number cat)
3261 (todo-category-select)
3262 (message "Items unarchived.")))))
3264 (defun todo-jump-to-archive-category (&optional file)
3265 "Prompt for a category in a todo archive and jump to it.
3266 With prefix argument FILE, prompt for an archive and choose (with
3267 TAB completion) a category in it to jump to; otherwise, choose
3268 and jump to any category in the current archive."
3269 (interactive "P")
3270 (todo-jump-to-category file 'archive))
3272 ;; -----------------------------------------------------------------------------
3273 ;;; Displaying and sorting tables of categories
3274 ;; -----------------------------------------------------------------------------
3276 (defcustom todo-categories-category-label "Category"
3277 "Category button label in Todo Categories mode."
3278 :type 'string
3279 :group 'todo-categories)
3281 (defcustom todo-categories-todo-label "Todo"
3282 "Todo button label in Todo Categories mode."
3283 :type 'string
3284 :group 'todo-categories)
3286 (defcustom todo-categories-diary-label "Diary"
3287 "Diary button label in Todo Categories mode."
3288 :type 'string
3289 :group 'todo-categories)
3291 (defcustom todo-categories-done-label "Done"
3292 "Done button label in Todo Categories mode."
3293 :type 'string
3294 :group 'todo-categories)
3296 (defcustom todo-categories-archived-label "Archived"
3297 "Archived button label in Todo Categories mode."
3298 :type 'string
3299 :group 'todo-categories)
3301 (defcustom todo-categories-totals-label "Totals"
3302 "String to label total item counts in Todo Categories mode."
3303 :type 'string
3304 :group 'todo-categories)
3306 (defcustom todo-categories-number-separator " | "
3307 "String between number and category in Todo Categories mode.
3308 This separates the number from the category name in the default
3309 categories display according to priority."
3310 :type 'string
3311 :group 'todo-categories)
3313 (defcustom todo-categories-align 'center
3314 "Alignment of category names in Todo Categories mode."
3315 :type '(radio (const left) (const center) (const right))
3316 :group 'todo-categories)
3318 (defun todo-show-categories-table ()
3319 "Display a table of the current file's categories and item counts.
3321 In the initial display the lines of the table are numbered,
3322 indicating the current order of the categories when sequentially
3323 navigating through the todo file with `\\[todo-forward-category]'
3324 and `\\[todo-backward-category]'. You can reorder the lines, and
3325 hence the category sequence, by typing `\\[todo-raise-category]'
3326 or `\\[todo-lower-category]' to raise or lower the category at
3327 point, or by typing `\\[todo-set-category-number]' and entering a
3328 number at the prompt or by typing `\\[todo-set-category-number]'
3329 with a numeric prefix. If you save the todo file after
3330 reordering the categories, the new order persists in subsequent
3331 Emacs sessions.
3333 The labels above the category names and item counts are buttons,
3334 and clicking these changes the display: sorted by category name
3335 or by the respective item counts (alternately descending or
3336 ascending). In these displays the categories are not numbered
3337 and `\\[todo-set-category-number]', `\\[todo-raise-category]' and
3338 `\\[todo-lower-category]' are disabled. (Programmatically, the
3339 sorting is triggered by passing a non-nil SORTKEY argument.)
3341 In addition, the lines with the category names and item counts
3342 are buttonized, and pressing one of these button jumps to the
3343 category in Todo mode (or Todo Archive mode, for categories
3344 containing only archived items, provided user option
3345 `todo-skip-archived-categories' is non-nil. These categories
3346 are shown in `todo-archived-only' face."
3347 (interactive)
3348 (todo-display-categories)
3349 (let (sortkey)
3350 (todo-update-categories-display sortkey)))
3352 (defun todo-next-button (n)
3353 "Move point to the Nth next button in the table of categories."
3354 (interactive "p")
3355 (forward-button n 'wrap 'display-message)
3356 (and (bolp) (button-at (point))
3357 ;; Align with beginning of category label.
3358 (forward-char (+ 4 (length todo-categories-number-separator)))))
3360 (defun todo-previous-button (n)
3361 "Move point to the Nth previous button in the table of categories."
3362 (interactive "p")
3363 (backward-button n 'wrap 'display-message)
3364 (and (bolp) (button-at (point))
3365 ;; Align with beginning of category label.
3366 (forward-char (+ 4 (length todo-categories-number-separator)))))
3368 (defun todo-set-category-number (&optional arg)
3369 "Change number of category at point in the table of categories.
3371 With ARG nil, prompt for the new number. Alternatively, the
3372 enter the new number with numerical prefix ARG. Otherwise, if
3373 ARG is either of the symbols `raise' or `lower', raise or lower
3374 the category line in the table by one, respectively, thereby
3375 decreasing or increasing its number."
3376 (interactive "P")
3377 (let ((curnum (save-excursion
3378 ;; Get the number representing the priority of the category
3379 ;; on the current line.
3380 (forward-line 0) (skip-chars-forward " ") (number-at-point))))
3381 (when curnum ; Do nothing if we're not on a category line.
3382 (let* ((maxnum (length todo-categories))
3383 (prompt (format "Set category priority (1-%d): " maxnum))
3384 (col (current-column))
3385 (buffer-read-only nil)
3386 (priority (cond ((and (eq arg 'raise) (> curnum 1))
3387 (1- curnum))
3388 ((and (eq arg 'lower) (< curnum maxnum))
3389 (1+ curnum))))
3390 candidate)
3391 (while (not priority)
3392 (setq candidate (or arg (read-number prompt)))
3393 (setq arg nil)
3394 (setq prompt
3395 (cond ((or (< candidate 1) (> candidate maxnum))
3396 (format "Priority must be an integer between 1 and %d: "
3397 maxnum))
3398 ((= candidate curnum)
3399 "Choose a different priority than the current one: ")))
3400 (unless prompt (setq priority candidate)))
3401 (let* ((lower (< curnum priority)) ; Priority is being lowered.
3402 (head (butlast todo-categories
3403 (apply (if lower 'identity '1+)
3404 (list (- maxnum priority)))))
3405 (tail (nthcdr (apply (if lower 'identity '1-) (list priority))
3406 todo-categories))
3407 ;; Category's name and items counts list.
3408 (catcons (nth (1- curnum) todo-categories))
3409 (todo-categories (nconc head (list catcons) tail))
3410 newcats)
3411 (when lower (setq todo-categories (nreverse todo-categories)))
3412 (setq todo-categories (delete-dups todo-categories))
3413 (when lower (setq todo-categories (nreverse todo-categories)))
3414 (setq newcats todo-categories)
3415 (kill-buffer)
3416 (with-current-buffer (find-buffer-visiting todo-current-todo-file)
3417 (setq todo-categories newcats)
3418 (todo-update-categories-sexp))
3419 (todo-show-categories-table)
3420 (forward-line (1+ priority))
3421 (forward-char col))))))
3423 (defun todo-raise-category ()
3424 "Raise priority of category at point in the table of categories."
3425 (interactive)
3426 (todo-set-category-number 'raise))
3428 (defun todo-lower-category ()
3429 "Lower priority of category at point in the table of categories."
3430 (interactive)
3431 (todo-set-category-number 'lower))
3433 (defun todo-sort-categories-alphabetically-or-numerically ()
3434 "Sort table of categories alphabetically or numerically."
3435 (interactive)
3436 (save-excursion
3437 (goto-char (point-min))
3438 (forward-line 2)
3439 (if (member 'alpha todo-descending-counts)
3440 (progn
3441 (todo-update-categories-display nil)
3442 (setq todo-descending-counts
3443 (delete 'alpha todo-descending-counts)))
3444 (todo-update-categories-display 'alpha))))
3446 (defun todo-sort-categories-by-todo ()
3447 "Sort table of categories by number of todo items."
3448 (interactive)
3449 (save-excursion
3450 (goto-char (point-min))
3451 (forward-line 2)
3452 (todo-update-categories-display 'todo)))
3454 (defun todo-sort-categories-by-diary ()
3455 "Sort table of categories by number of diary items."
3456 (interactive)
3457 (save-excursion
3458 (goto-char (point-min))
3459 (forward-line 2)
3460 (todo-update-categories-display 'diary)))
3462 (defun todo-sort-categories-by-done ()
3463 "Sort table of categories by number of non-archived done items."
3464 (interactive)
3465 (save-excursion
3466 (goto-char (point-min))
3467 (forward-line 2)
3468 (todo-update-categories-display 'done)))
3470 (defun todo-sort-categories-by-archived ()
3471 "Sort table of categories by number of archived items."
3472 (interactive)
3473 (save-excursion
3474 (goto-char (point-min))
3475 (forward-line 2)
3476 (todo-update-categories-display 'archived)))
3478 (defvar todo-categories-buffer "*Todo Categories*"
3479 "Name of buffer in Todo Categories mode.")
3481 (defun todo-longest-category-name-length (categories)
3482 "Return the length of the longest name in list CATEGORIES."
3483 (let ((longest 0))
3484 (dolist (c categories longest)
3485 (setq longest (max longest (length c))))))
3487 (defun todo-adjusted-category-label-length ()
3488 "Return adjusted length of category label button.
3489 The adjustment ensures proper tabular alignment in Todo
3490 Categories mode."
3491 (let* ((categories (mapcar 'car todo-categories))
3492 (longest (todo-longest-category-name-length categories))
3493 (catlablen (length todo-categories-category-label))
3494 (lc-diff (- longest catlablen)))
3495 (if (and (natnump lc-diff) (cl-oddp lc-diff))
3496 (1+ longest)
3497 (max longest catlablen))))
3499 (defun todo-padded-string (str)
3500 "Return category name or label string STR padded with spaces.
3501 The placement of the padding is determined by the value of user
3502 option `todo-categories-align'."
3503 (let* ((len (todo-adjusted-category-label-length))
3504 (strlen (length str))
3505 (strlen-odd (eq (logand strlen 1) 1))
3506 (padding (max 0 (/ (- len strlen) 2)))
3507 (padding-left (cond ((eq todo-categories-align 'left) 0)
3508 ((eq todo-categories-align 'center) padding)
3509 ((eq todo-categories-align 'right)
3510 (if strlen-odd (1+ (* padding 2)) (* padding 2)))))
3511 (padding-right (cond ((eq todo-categories-align 'left)
3512 (if strlen-odd (1+ (* padding 2)) (* padding 2)))
3513 ((eq todo-categories-align 'center)
3514 (if strlen-odd (1+ padding) padding))
3515 ((eq todo-categories-align 'right) 0))))
3516 (concat (make-string padding-left 32) str (make-string padding-right 32))))
3518 (defvar todo-descending-counts nil
3519 "List of keys for category counts sorted in descending order.")
3521 (defun todo-sort (list &optional key)
3522 "Return a copy of LIST, possibly sorted according to KEY."
3523 (let* ((l (copy-sequence list))
3524 (fn (if (eq key 'alpha)
3525 (lambda (x) (upcase x)) ; Alphabetize case insensitively.
3526 (lambda (x) (todo-get-count key x))))
3527 ;; Keep track of whether the last sort by key was descending or
3528 ;; ascending.
3529 (descending (member key todo-descending-counts))
3530 (cmp (if (eq key 'alpha)
3531 'string<
3532 (if descending '< '>)))
3533 (pred (lambda (s1 s2) (let ((t1 (funcall fn (car s1)))
3534 (t2 (funcall fn (car s2))))
3535 (funcall cmp t1 t2)))))
3536 (when key
3537 (setq l (sort l pred))
3538 ;; Switch between descending and ascending sort order.
3539 (if descending
3540 (setq todo-descending-counts
3541 (delete key todo-descending-counts))
3542 (push key todo-descending-counts)))
3545 (defun todo-display-sorted (type)
3546 "Keep point on the TYPE count sorting button just clicked."
3547 (let ((opoint (point)))
3548 (todo-update-categories-display type)
3549 (goto-char opoint)))
3551 (defun todo-label-to-key (label)
3552 "Return symbol for sort key associated with LABEL."
3553 (let (key)
3554 (cond ((string= label todo-categories-category-label)
3555 (setq key 'alpha))
3556 ((string= label todo-categories-todo-label)
3557 (setq key 'todo))
3558 ((string= label todo-categories-diary-label)
3559 (setq key 'diary))
3560 ((string= label todo-categories-done-label)
3561 (setq key 'done))
3562 ((string= label todo-categories-archived-label)
3563 (setq key 'archived)))
3564 key))
3566 (defun todo-insert-sort-button (label)
3567 "Insert button for displaying categories sorted by item counts.
3568 LABEL determines which type of count is sorted."
3569 (let* ((str (if (string= label todo-categories-category-label)
3570 (todo-padded-string label)
3571 label))
3572 (beg (point))
3573 (end (+ beg (length str)))
3575 (insert-button str 'face nil
3576 'action
3577 `(lambda (button)
3578 (let ((key (todo-label-to-key ,label)))
3579 (if (and (member key todo-descending-counts)
3580 (eq key 'alpha))
3581 (progn
3582 ;; If display is alphabetical, switch back to
3583 ;; category priority order.
3584 (todo-display-sorted nil)
3585 (setq todo-descending-counts
3586 (delete key todo-descending-counts)))
3587 (todo-display-sorted key)))))
3588 (setq ov (make-overlay beg end))
3589 (overlay-put ov 'face 'todo-button)))
3591 (defun todo-total-item-counts ()
3592 "Return a list of total item counts for the current file."
3593 (mapcar (lambda (i) (apply '+ (mapcar (lambda (l) (aref l i))
3594 (mapcar 'cdr todo-categories))))
3595 (list 0 1 2 3)))
3597 (defvar todo-categories-category-number 0
3598 "Variable for numbering categories in Todo Categories mode.")
3600 (defun todo-insert-category-line (cat &optional nonum)
3601 "Insert button with category CAT's name and item counts.
3602 With non-nil argument NONUM show only these; otherwise, insert a
3603 number in front of the button indicating the category's priority.
3604 The number and the category name are separated by the string
3605 which is the value of the user option
3606 `todo-categories-number-separator'."
3607 (let ((archive (member todo-current-todo-file todo-archives))
3608 (num todo-categories-category-number)
3609 (str (todo-padded-string cat))
3610 (opoint (point)))
3611 (setq num (1+ num) todo-categories-category-number num)
3612 (insert-button
3613 (concat (if nonum
3614 (make-string (+ 4 (length todo-categories-number-separator))
3616 (format " %3d%s" num todo-categories-number-separator))
3618 (mapconcat (lambda (elt)
3619 (concat
3620 (make-string (1+ (/ (length (car elt)) 2)) 32) ; label
3621 (format "%3d" (todo-get-count (cdr elt) cat)) ; count
3622 ;; Add an extra space if label length is odd.
3623 (when (cl-oddp (length (car elt))) " ")))
3624 (if archive
3625 (list (cons todo-categories-done-label 'done))
3626 (list (cons todo-categories-todo-label 'todo)
3627 (cons todo-categories-diary-label 'diary)
3628 (cons todo-categories-done-label 'done)
3629 (cons todo-categories-archived-label
3630 'archived)))
3632 " ") ; Make highlighting on last column look better.
3633 'face (if (and todo-skip-archived-categories
3634 (zerop (todo-get-count 'todo cat))
3635 (zerop (todo-get-count 'done cat))
3636 (not (zerop (todo-get-count 'archived cat))))
3637 'todo-archived-only
3638 nil)
3639 'action `(lambda (button) (let ((buf (current-buffer)))
3640 (todo-jump-to-category nil ,cat)
3641 (kill-buffer buf))))
3642 ;; Highlight the sorted count column.
3643 (let* ((beg (+ opoint 7 (length str)))
3644 end ovl)
3645 (cond ((eq nonum 'todo)
3646 (setq beg (+ beg 1 (/ (length todo-categories-todo-label) 2))))
3647 ((eq nonum 'diary)
3648 (setq beg (+ beg 1 (length todo-categories-todo-label)
3649 2 (/ (length todo-categories-diary-label) 2))))
3650 ((eq nonum 'done)
3651 (setq beg (+ beg 1 (length todo-categories-todo-label)
3652 2 (length todo-categories-diary-label)
3653 2 (/ (length todo-categories-done-label) 2))))
3654 ((eq nonum 'archived)
3655 (setq beg (+ beg 1 (length todo-categories-todo-label)
3656 2 (length todo-categories-diary-label)
3657 2 (length todo-categories-done-label)
3658 2 (/ (length todo-categories-archived-label) 2)))))
3659 (unless (= beg (+ opoint 7 (length str))) ; Don't highlight categories.
3660 (setq end (+ beg 4))
3661 (setq ovl (make-overlay beg end))
3662 (overlay-put ovl 'face 'todo-sorted-column)))
3663 (newline)))
3665 (defun todo-display-categories ()
3666 "Prepare buffer for displaying table of categories and item counts."
3667 (unless (eq major-mode 'todo-categories-mode)
3668 (setq todo-global-current-todo-file
3669 (or todo-current-todo-file
3670 (todo-absolute-file-name todo-default-todo-file)))
3671 (set-window-buffer (selected-window)
3672 (set-buffer (get-buffer-create todo-categories-buffer)))
3673 (kill-all-local-variables)
3674 (todo-categories-mode)
3675 (let ((archive (member todo-current-todo-file todo-archives))
3676 buffer-read-only)
3677 (erase-buffer)
3678 (insert (format (concat "Category counts for todo "
3679 (if archive "archive" "file")
3680 " \"%s\".")
3681 (todo-short-file-name todo-current-todo-file)))
3682 (newline 2)
3683 ;; Make space for the column of category numbers.
3684 (insert (make-string (+ 4 (length todo-categories-number-separator)) 32))
3685 ;; Add the category and item count buttons (if this is the list of
3686 ;; categories in an archive, show only done item counts).
3687 (todo-insert-sort-button todo-categories-category-label)
3688 (if archive
3689 (progn
3690 (insert (make-string 3 32))
3691 (todo-insert-sort-button todo-categories-done-label))
3692 (insert (make-string 3 32))
3693 (todo-insert-sort-button todo-categories-todo-label)
3694 (insert (make-string 2 32))
3695 (todo-insert-sort-button todo-categories-diary-label)
3696 (insert (make-string 2 32))
3697 (todo-insert-sort-button todo-categories-done-label)
3698 (insert (make-string 2 32))
3699 (todo-insert-sort-button todo-categories-archived-label))
3700 (newline 2))))
3702 (defun todo-update-categories-display (sortkey)
3703 "Populate table of categories and sort by SORTKEY."
3704 (let* ((cats0 todo-categories)
3705 (cats (todo-sort cats0 sortkey))
3706 (archive (member todo-current-todo-file todo-archives))
3707 (todo-categories-category-number 0)
3708 ;; Find start of Category button if we just entered Todo Categories
3709 ;; mode.
3710 (pt (if (eq (point) (point-max))
3711 (save-excursion
3712 (forward-line -2)
3713 (goto-char (next-single-char-property-change
3714 (point) 'face nil (line-end-position))))))
3715 (buffer-read-only))
3716 (forward-line 2)
3717 (delete-region (point) (point-max))
3718 ;; Fill in the table with buttonized lines, each showing a category and
3719 ;; its item counts.
3720 (mapc (lambda (cat) (todo-insert-category-line cat sortkey))
3721 (mapcar 'car cats))
3722 (newline)
3723 ;; Add a line showing item count totals.
3724 (insert (make-string (+ 4 (length todo-categories-number-separator)) 32)
3725 (todo-padded-string todo-categories-totals-label)
3726 (mapconcat
3727 (lambda (elt)
3728 (concat
3729 (make-string (1+ (/ (length (car elt)) 2)) 32)
3730 (format "%3d" (nth (cdr elt) (todo-total-item-counts)))
3731 ;; Add an extra space if label length is odd.
3732 (when (cl-oddp (length (car elt))) " ")))
3733 (if archive
3734 (list (cons todo-categories-done-label 2))
3735 (list (cons todo-categories-todo-label 0)
3736 (cons todo-categories-diary-label 1)
3737 (cons todo-categories-done-label 2)
3738 (cons todo-categories-archived-label 3)))
3739 ""))
3740 ;; Put cursor on Category button initially.
3741 (if pt (goto-char pt))
3742 (setq buffer-read-only t)))
3744 ;; -----------------------------------------------------------------------------
3745 ;;; Searching and item filtering
3746 ;; -----------------------------------------------------------------------------
3748 (defun todo-search ()
3749 "Search for a regular expression in this todo file.
3750 The search runs through the whole file and encompasses all and
3751 only todo and done items; it excludes category names. Multiple
3752 matches are shown sequentially, highlighted in `todo-search'
3753 face."
3754 (interactive)
3755 (let ((regex (read-from-minibuffer "Enter a search string (regexp): "))
3756 (opoint (point))
3757 matches match cat in-done ov mlen msg)
3758 (widen)
3759 (goto-char (point-min))
3760 (while (not (eobp))
3761 (setq match (re-search-forward regex nil t))
3762 (goto-char (line-beginning-position))
3763 (unless (or (equal (point) 1)
3764 (looking-at (concat "^" (regexp-quote todo-category-beg))))
3765 (if match (push match matches)))
3766 (forward-line))
3767 (setq matches (reverse matches))
3768 (if matches
3769 (catch 'stop
3770 (while matches
3771 (setq match (pop matches))
3772 (goto-char match)
3773 (todo-item-start)
3774 (when (looking-at todo-done-string-start)
3775 (setq in-done t))
3776 (re-search-backward (concat "^" (regexp-quote todo-category-beg)
3777 "\\(.*\\)\n") nil t)
3778 (setq cat (match-string-no-properties 1))
3779 (todo-category-number cat)
3780 (todo-category-select)
3781 (if in-done
3782 (unless todo-show-with-done (todo-toggle-view-done-items)))
3783 (goto-char match)
3784 (setq ov (make-overlay (- (point) (length regex)) (point)))
3785 (overlay-put ov 'face 'todo-search)
3786 (when matches
3787 (setq mlen (length matches))
3788 (if (todo-y-or-n-p
3789 (if (> mlen 1)
3790 (format "There are %d more matches; go to next match? "
3791 mlen)
3792 "There is one more match; go to it? "))
3793 (widen)
3794 (throw 'stop (setq msg (if (> mlen 1)
3795 (format "There are %d more matches."
3796 mlen)
3797 "There is one more match."))))))
3798 (setq msg "There are no more matches."))
3799 (todo-category-select)
3800 (goto-char opoint)
3801 (message "No match for \"%s\"" regex))
3802 (when msg
3803 (if (todo-y-or-n-p (concat msg "\nUnhighlight matches? "))
3804 (todo-clear-matches)
3805 (message "You can unhighlight the matches later by typing %s"
3806 (key-description (car (where-is-internal
3807 'todo-clear-matches))))))))
3809 (defun todo-clear-matches ()
3810 "Remove highlighting on matches found by todo-search."
3811 (interactive)
3812 (remove-overlays 1 (1+ (buffer-size)) 'face 'todo-search))
3814 (defcustom todo-top-priorities-overrides nil
3815 "List of rules specifying number of top priority items to show.
3816 These rules override `todo-top-priorities' on invocations of
3817 `\\[todo-filter-top-priorities]' and
3818 `\\[todo-filter-top-priorities-multifile]'. Each rule is a list
3819 of the form (FILE NUM ALIST), where FILE is a member of
3820 `todo-files', NUM is a number specifying the default number of
3821 top priority items for each category in that file, and ALIST,
3822 when non-nil, consists of conses of a category name in FILE and a
3823 number specifying the default number of top priority items in
3824 that category, which overrides NUM.
3826 This variable should be set interactively by
3827 `\\[todo-set-top-priorities-in-file]' or
3828 `\\[todo-set-top-priorities-in-category]'."
3829 :type 'sexp
3830 :group 'todo-filtered)
3832 (defcustom todo-top-priorities 1
3833 "Default number of top priorities shown by `todo-filter-top-priorities'."
3834 :type 'integer
3835 :group 'todo-filtered)
3837 (defcustom todo-filter-files nil
3838 "List of default files for multifile item filtering."
3839 :type `(set ,@(mapcar (lambda (f) (list 'const f))
3840 (mapcar 'todo-short-file-name
3841 (funcall todo-files-function))))
3842 :group 'todo-filtered)
3844 (defcustom todo-filter-done-items nil
3845 "Non-nil to include done items when processing regexp filters.
3846 Done items from corresponding archive files are also included."
3847 :type 'boolean
3848 :group 'todo-filtered)
3850 (defun todo-set-top-priorities-in-file ()
3851 "Set number of top priorities for this file.
3852 See `todo-set-top-priorities' for more details."
3853 (interactive)
3854 (todo-set-top-priorities))
3856 (defun todo-set-top-priorities-in-category ()
3857 "Set number of top priorities for this category.
3858 See `todo-set-top-priorities' for more details."
3859 (interactive)
3860 (todo-set-top-priorities t))
3862 (defun todo-filter-top-priorities (&optional arg)
3863 "Display a list of top priority items from different categories.
3864 The categories can be any of those in the current todo file.
3866 With numerical prefix ARG show at most ARG top priority items
3867 from each category. With `C-u' as prefix argument show the
3868 numbers of top priority items specified by category in
3869 `todo-top-priorities-overrides', if this has an entry for the file(s);
3870 otherwise show `todo-top-priorities' items per category in the
3871 file(s). With no prefix argument, if a top priorities file for
3872 the current todo file has previously been saved (see
3873 `todo-save-filtered-items-buffer'), visit this file; if there is
3874 no such file, build the list as with prefix argument `C-u'.
3876 The prefix ARG regulates how many top priorities from
3877 each category to show, as described above."
3878 (interactive "P")
3879 (todo-filter-items 'top arg))
3881 (defun todo-filter-top-priorities-multifile (&optional arg)
3882 "Display a list of top priority items from different categories.
3883 The categories are a subset of the categories in the files listed
3884 in `todo-filter-files', or if this nil, in the files chosen from
3885 a file selection dialog that pops up in this case.
3887 With numerical prefix ARG show at most ARG top priority items
3888 from each category in each file. With `C-u' as prefix argument
3889 show the numbers of top priority items specified in
3890 `todo-top-priorities-overrides', if this is non-nil; otherwise show
3891 `todo-top-priorities' items per category. With no prefix
3892 argument, if a top priorities file for the chosen todo files
3893 exists (see `todo-save-filtered-items-buffer'), visit this file;
3894 if there is no such file, do the same as with prefix argument
3895 `C-u'."
3896 (interactive "P")
3897 (todo-filter-items 'top arg t))
3899 (defun todo-filter-diary-items (&optional arg)
3900 "Display a list of todo diary items from different categories.
3901 The categories can be any of those in the current todo file.
3903 Called with no prefix ARG, if a diary items file for the current
3904 todo file has previously been saved (see
3905 `todo-save-filtered-items-buffer'), visit this file; if there is
3906 no such file, build the list of diary items. Called with a
3907 prefix argument, build the list even if there is a saved file of
3908 diary items."
3909 (interactive "P")
3910 (todo-filter-items 'diary arg))
3912 (defun todo-filter-diary-items-multifile (&optional arg)
3913 "Display a list of todo diary items from different categories.
3914 The categories are a subset of the categories in the files listed
3915 in `todo-filter-files', or if this nil, in the files chosen from
3916 a file selection dialog that pops up in this case.
3918 Called with no prefix ARG, if a diary items file for the chosen
3919 todo files has previously been saved (see
3920 `todo-save-filtered-items-buffer'), visit this file; if there is
3921 no such file, build the list of diary items. Called with a
3922 prefix argument, build the list even if there is a saved file of
3923 diary items."
3924 (interactive "P")
3925 (todo-filter-items 'diary arg t))
3927 (defun todo-filter-regexp-items (&optional arg)
3928 "Prompt for a regular expression and display items that match it.
3929 The matches can be from any categories in the current todo file
3930 and with non-nil option `todo-filter-done-items', can include
3931 not only todo items but also done items, including those in
3932 Archive files.
3934 Called with no prefix ARG, if a regexp items file for the current
3935 todo file has previously been saved (see
3936 `todo-save-filtered-items-buffer'), visit this file; if there is
3937 no such file, build the list of regexp items. Called with a
3938 prefix argument, build the list even if there is a saved file of
3939 regexp items."
3940 (interactive "P")
3941 (todo-filter-items 'regexp arg))
3943 (defun todo-filter-regexp-items-multifile (&optional arg)
3944 "Prompt for a regular expression and display items that match it.
3945 The matches can be from any categories in the files listed in
3946 `todo-filter-files', or if this nil, in the files chosen from a
3947 file selection dialog that pops up in this case. With non-nil
3948 option `todo-filter-done-items', the matches can include not
3949 only todo items but also done items, including those in Archive
3950 files.
3952 Called with no prefix ARG, if a regexp items file for the current
3953 todo file has previously been saved (see
3954 `todo-save-filtered-items-buffer'), visit this file; if there is
3955 no such file, build the list of regexp items. Called with a
3956 prefix argument, build the list even if there is a saved file of
3957 regexp items."
3958 (interactive "P")
3959 (todo-filter-items 'regexp arg t))
3961 (defun todo-find-filtered-items-file ()
3962 "Choose a filtered items file and visit it."
3963 (interactive)
3964 (let ((files (directory-files todo-directory t "\\.tod[rty]$" t))
3965 falist file)
3966 (dolist (f files)
3967 (let ((type (cond ((equal (file-name-extension f) "todr") "regexp")
3968 ((equal (file-name-extension f) "todt") "top")
3969 ((equal (file-name-extension f) "tody") "diary"))))
3970 (push (cons (concat (todo-short-file-name f) " (" type ")") f)
3971 falist)))
3972 (setq file (completing-read "Choose a filtered items file: "
3973 falist nil t nil nil (car falist)))
3974 (setq file (cdr (assoc-string file falist)))
3975 (find-file file)
3976 (unless (derived-mode-p 'todo-filtered-items-mode)
3977 (todo-filtered-items-mode))
3978 (todo-prefix-overlays)))
3980 (defun todo-go-to-source-item ()
3981 "Display the file and category of the filtered item at point."
3982 (interactive)
3983 (let* ((str (todo-item-string))
3984 (buf (current-buffer))
3985 (res (todo-find-item str))
3986 (found (nth 0 res))
3987 (file (nth 1 res))
3988 (cat (nth 2 res)))
3989 (if (not found)
3990 (message "Category %s does not contain this item." cat)
3991 (kill-buffer buf)
3992 (set-window-buffer (selected-window)
3993 (set-buffer (find-buffer-visiting file)))
3994 (setq todo-current-todo-file file)
3995 (setq todo-category-number (todo-category-number cat))
3996 (let ((todo-show-with-done (if (or todo-filter-done-items
3997 (eq (cdr found) 'done))
3999 todo-show-with-done)))
4000 (todo-category-select))
4001 (goto-char (car found)))))
4003 (defvar todo-multiple-filter-files nil
4004 "List of files selected from `todo-multiple-filter-files' widget.")
4006 (defvar todo-multiple-filter-files-widget nil
4007 "Variable holding widget created by `todo-multiple-filter-files'.")
4009 (defun todo-multiple-filter-files ()
4010 "Pop to a buffer with a widget for choosing multiple filter files."
4011 (require 'widget)
4012 (eval-when-compile
4013 (require 'wid-edit))
4014 (with-current-buffer (get-buffer-create "*Todo Filter Files*")
4015 (pop-to-buffer (current-buffer))
4016 (erase-buffer)
4017 (kill-all-local-variables)
4018 (widget-insert "Select files for generating the top priorities list.\n\n")
4019 (setq todo-multiple-filter-files-widget
4020 (widget-create
4021 `(set ,@(mapcar (lambda (x) (list 'const x))
4022 (mapcar 'todo-short-file-name
4023 (funcall todo-files-function))))))
4024 (widget-insert "\n")
4025 (widget-create 'push-button
4026 :notify (lambda (widget &rest ignore)
4027 (setq todo-multiple-filter-files 'quit)
4028 (quit-window t)
4029 (exit-recursive-edit))
4030 "Cancel")
4031 (widget-insert " ")
4032 (widget-create 'push-button
4033 :notify (lambda (&rest ignore)
4034 (setq todo-multiple-filter-files
4035 (mapcar (lambda (f)
4036 (file-truename
4037 (concat todo-directory
4038 f ".todo")))
4039 (widget-value
4040 todo-multiple-filter-files-widget)))
4041 (quit-window t)
4042 (exit-recursive-edit))
4043 "Apply")
4044 (use-local-map widget-keymap)
4045 (widget-setup))
4046 (message "Click \"Apply\" after selecting files.")
4047 (recursive-edit))
4049 (defconst todo-filtered-items-buffer "Todo filtered items"
4050 "Initial name of buffer in Todo Filter Items mode.")
4052 (defconst todo-top-priorities-buffer "Todo top priorities"
4053 "Buffer type string for `todo-filter-items'.")
4055 (defconst todo-diary-items-buffer "Todo diary items"
4056 "Buffer type string for `todo-filter-items'.")
4058 (defconst todo-regexp-items-buffer "Todo regexp items"
4059 "Buffer type string for `todo-filter-items'.")
4061 (defun todo-filter-items (filter &optional new multifile)
4062 "Display a list of items filtered by FILTER.
4063 The values of FILTER can be `top' for top priority items, a cons
4064 of `top' and a number passed by the caller, `diary' for diary
4065 items, or `regexp' for items matching a regular expression
4066 entered by the user. The items can come from any categories in
4067 the current todo file or, with non-nil MULTIFILE, from several
4068 files. If NEW is nil, visit an appropriate file containing the
4069 list of filtered items; if there is no such file, or with non-nil
4070 NEW, build the list and display it.
4072 See the documentation strings of the commands
4073 `todo-filter-top-priorities', `todo-filter-diary-items',
4074 `todo-filter-regexp-items', and those of the corresponding
4075 multifile commands for further details."
4076 (let* ((top (eq filter 'top))
4077 (diary (eq filter 'diary))
4078 (regexp (eq filter 'regexp))
4079 (buf (cond (top todo-top-priorities-buffer)
4080 (diary todo-diary-items-buffer)
4081 (regexp todo-regexp-items-buffer)))
4082 (flist (if multifile
4083 (or todo-filter-files
4084 (progn (todo-multiple-filter-files)
4085 todo-multiple-filter-files))
4086 (list todo-current-todo-file)))
4087 (fname (if (equal flist 'quit)
4088 ;; Pressed `cancel' in t-m-f-f file selection dialog.
4089 (keyboard-quit)
4090 (concat todo-directory
4091 (mapconcat 'todo-short-file-name flist "-")
4092 (cond (top ".todt")
4093 (diary ".tody")
4094 (regexp ".todr")))))
4095 (multi (> (length flist) 1))
4096 (rxfiles (when regexp
4097 (directory-files todo-directory t ".*\\.todr$" t)))
4098 (file-exists (or (file-exists-p fname) rxfiles))
4099 bufname)
4100 (cond ((and top new (natnump new))
4101 (todo-filter-items-1 (cons 'top new) flist))
4102 ((and (not new) file-exists)
4103 (when (and rxfiles (> (length rxfiles) 1))
4104 (let ((rxf (mapcar 'todo-short-file-name rxfiles)))
4105 (setq fname (todo-absolute-file-name
4106 (completing-read "Choose a regexp items file: "
4107 rxf) 'regexp))))
4108 (find-file fname)
4109 (unless (derived-mode-p 'todo-filtered-items-mode)
4110 (todo-filtered-items-mode))
4111 (todo-prefix-overlays)
4112 (todo-check-filtered-items-file))
4114 (todo-filter-items-1 filter flist)))
4115 (dolist (s (split-string (todo-short-file-name fname) "-"))
4116 (setq bufname (if bufname
4117 (concat bufname (if (member s (mapcar
4118 'todo-short-file-name
4119 todo-files))
4120 ", " "-") s)
4121 s)))
4122 (rename-buffer (format (concat "%s for file" (if multi "s" "")
4123 " \"%s\"") buf bufname))))
4125 (defun todo-filter-items-1 (filter file-list)
4126 "Build a list of items by applying FILTER to FILE-LIST.
4127 Internal subroutine called by `todo-filter-items', which passes
4128 the values of FILTER and FILE-LIST."
4129 (let ((num (if (consp filter) (cdr filter) todo-top-priorities))
4130 (buf (get-buffer-create todo-filtered-items-buffer))
4131 (multifile (> (length file-list) 1))
4132 regexp fname bufstr cat beg end done)
4133 (if (null file-list)
4134 (user-error "No files have been chosen for filtering")
4135 (with-current-buffer buf
4136 (erase-buffer)
4137 (kill-all-local-variables)
4138 (todo-filtered-items-mode))
4139 (when (eq filter 'regexp)
4140 (setq regexp (read-string "Enter a regular expression: ")))
4141 (save-current-buffer
4142 (dolist (f file-list)
4143 ;; Before inserting file contents into temp buffer, save a modified
4144 ;; buffer visiting it.
4145 (let ((bf (find-buffer-visiting f)))
4146 (when (buffer-modified-p bf)
4147 (with-current-buffer bf (save-buffer))))
4148 (setq fname (todo-short-file-name f))
4149 (with-temp-buffer
4150 (when (and todo-filter-done-items (eq filter 'regexp))
4151 ;; If there is a corresponding archive file for the
4152 ;; todo file, insert it first and add identifiers for
4153 ;; todo-go-to-source-item.
4154 (let ((arch (concat (file-name-sans-extension f) ".toda")))
4155 (when (file-exists-p arch)
4156 (insert-file-contents arch)
4157 ;; Delete todo archive file's categories sexp.
4158 (delete-region (line-beginning-position)
4159 (1+ (line-end-position)))
4160 (save-excursion
4161 (while (not (eobp))
4162 (when (re-search-forward
4163 (concat (if todo-filter-done-items
4164 (concat "\\(?:" todo-done-string-start
4165 "\\|" todo-date-string-start
4166 "\\)")
4167 todo-date-string-start)
4168 todo-date-pattern "\\(?: "
4169 diary-time-regexp "\\)?"
4170 (if todo-filter-done-items
4171 "\\]"
4172 (regexp-quote todo-nondiary-end)) "?")
4173 nil t)
4174 (insert "(archive) "))
4175 (forward-line))))))
4176 (insert-file-contents f)
4177 ;; Delete todo file's categories sexp.
4178 (delete-region (line-beginning-position) (1+ (line-end-position)))
4179 (let (fnum)
4180 ;; Unless the number of top priorities to show was
4181 ;; passed by the caller, the file-wide value from
4182 ;; `todo-top-priorities-overrides', if non-nil, overrides
4183 ;; `todo-top-priorities'.
4184 (unless (consp filter)
4185 (setq fnum (or (nth 1 (assoc f todo-top-priorities-overrides))
4186 todo-top-priorities)))
4187 (while (re-search-forward
4188 (concat "^" (regexp-quote todo-category-beg)
4189 "\\(.+\\)\n") nil t)
4190 (setq cat (match-string 1))
4191 (let (cnum)
4192 ;; Unless the number of top priorities to show was
4193 ;; passed by the caller, the category-wide value
4194 ;; from `todo-top-priorities-overrides', if non-nil,
4195 ;; overrides a non-nil file-wide value from
4196 ;; `todo-top-priorities-overrides' as well as
4197 ;; `todo-top-priorities'.
4198 (unless (consp filter)
4199 (let ((cats (nth 2 (assoc f todo-top-priorities-overrides))))
4200 (setq cnum (or (cdr (assoc cat cats)) fnum))))
4201 (delete-region (match-beginning 0) (match-end 0))
4202 (setq beg (point)) ; First item in the current category.
4203 (setq end (if (re-search-forward
4204 (concat "^" (regexp-quote todo-category-beg))
4205 nil t)
4206 (match-beginning 0)
4207 (point-max)))
4208 (goto-char beg)
4209 (setq done
4210 (if (re-search-forward
4211 (concat "\n" (regexp-quote todo-category-done))
4212 end t)
4213 (match-beginning 0)
4214 end))
4215 (unless (and todo-filter-done-items (eq filter 'regexp))
4216 ;; Leave done items.
4217 (delete-region done end)
4218 (setq end done))
4219 (narrow-to-region beg end) ; Process only current category.
4220 (goto-char (point-min))
4221 ;; Apply the filter.
4222 (cond ((eq filter 'diary)
4223 (while (not (eobp))
4224 (if (looking-at (regexp-quote todo-nondiary-start))
4225 (todo-remove-item)
4226 (todo-forward-item))))
4227 ((eq filter 'regexp)
4228 (while (not (eobp))
4229 (if (looking-at todo-item-start)
4230 (if (string-match regexp (todo-item-string))
4231 (todo-forward-item)
4232 (todo-remove-item))
4233 ;; Kill lines that aren't part of a todo or done
4234 ;; item (empty or todo-category-done).
4235 (delete-region (line-beginning-position)
4236 (1+ (line-end-position))))
4237 ;; If last todo item in file matches regexp and
4238 ;; there are no following done items,
4239 ;; todo-category-done string is left dangling,
4240 ;; because todo-forward-item jumps over it.
4241 (if (and (eobp)
4242 (looking-back
4243 (concat (regexp-quote todo-done-string)
4244 "\n")
4245 (line-beginning-position 0)))
4246 (delete-region (point) (progn
4247 (forward-line -2)
4248 (point))))))
4249 (t ; Filter top priority items.
4250 (setq num (or cnum fnum num))
4251 (unless (zerop num)
4252 (todo-forward-item num))))
4253 (setq beg (point))
4254 ;; Delete non-top-priority items.
4255 (unless (member filter '(diary regexp))
4256 (delete-region beg end))
4257 (goto-char (point-min))
4258 ;; Add file (if using multiple files) and category tags to
4259 ;; item.
4260 (while (not (eobp))
4261 (when (re-search-forward
4262 (concat (if todo-filter-done-items
4263 (concat "\\(?:" todo-done-string-start
4264 "\\|" todo-date-string-start
4265 "\\)")
4266 todo-date-string-start)
4267 todo-date-pattern "\\(?: " diary-time-regexp
4268 "\\)?" (if todo-filter-done-items
4269 "\\]"
4270 (regexp-quote todo-nondiary-end))
4271 "?")
4272 nil t)
4273 (insert " [")
4274 (when (looking-at "(archive) ") (goto-char (match-end 0)))
4275 (insert (if multifile (concat fname ":") "") cat "]"))
4276 (forward-line))
4277 (widen)))
4278 (setq bufstr (buffer-string))
4279 (with-current-buffer buf
4280 (let (buffer-read-only)
4281 (insert bufstr)))))))
4282 (set-window-buffer (selected-window) (set-buffer buf))
4283 (todo-prefix-overlays)
4284 (goto-char (point-min)))))
4286 (defun todo-set-top-priorities (&optional arg)
4287 "Set number of top priorities shown by `todo-filter-top-priorities'.
4288 With non-nil ARG, set the number only for the current Todo
4289 category; otherwise, set the number for all categories in the
4290 current todo file.
4292 Calling this function via either of the commands
4293 `todo-set-top-priorities-in-file' or
4294 `todo-set-top-priorities-in-category' is the recommended way to
4295 set the user customizable option `todo-top-priorities-overrides'."
4296 (let* ((cat (todo-current-category))
4297 (file todo-current-todo-file)
4298 (rules todo-top-priorities-overrides)
4299 (frule (assoc-string file rules))
4300 (crules (nth 2 frule))
4301 (crule (assoc-string cat crules))
4302 (fcur (or (nth 1 frule)
4303 todo-top-priorities))
4304 (ccur (or (and arg (cdr crule))
4305 fcur))
4306 (prompt (if arg (concat "Number of top priorities in this category"
4307 " (currently %d): ")
4308 (concat "Default number of top priorities per category"
4309 " in this file (currently %d): ")))
4310 (new -1))
4311 (while (< new 0)
4312 (let ((cur (if arg ccur fcur)))
4313 (setq new (read-number (format prompt cur))
4314 prompt "Enter a non-negative number: "
4315 cur nil)))
4316 (let ((nrule (if arg
4317 (append (delete crule crules) (list (cons cat new)))
4318 (append (list file new) (list crules)))))
4319 (setq rules (cons (if arg
4320 (list file fcur nrule)
4321 nrule)
4322 (delete frule rules)))
4323 (customize-save-variable 'todo-top-priorities-overrides rules)
4324 (todo-prefix-overlays))))
4326 (defun todo-find-item (str)
4327 "Search for filtered item STR in its saved todo file.
4328 Return the list (FOUND FILE CAT), where CAT and FILE are the
4329 item's category and file, and FOUND is a cons cell if the search
4330 succeeds, whose car is the start of the item in FILE and whose
4331 cdr is `done', if the item is now a done item, `changed', if its
4332 text was truncated or augmented or, for a top priority item, if
4333 its priority has changed, and `same' otherwise."
4334 (string-match (concat (if todo-filter-done-items
4335 (concat "\\(?:" todo-done-string-start "\\|"
4336 todo-date-string-start "\\)")
4337 todo-date-string-start)
4338 todo-date-pattern "\\(?: " diary-time-regexp "\\)?"
4339 (if todo-filter-done-items
4340 "\\]"
4341 (regexp-quote todo-nondiary-end)) "?"
4342 "\\(?4: \\[\\(?3:(archive) \\)?\\(?2:.*:\\)?"
4343 "\\(?1:.*\\)\\]\\).*$") str)
4344 (let ((cat (match-string 1 str))
4345 (file (match-string 2 str))
4346 (archive (string= (match-string 3 str) "(archive) "))
4347 (filcat (match-string 4 str))
4348 (tpriority 1)
4349 (tpbuf (save-match-data (string-match "top" (buffer-name))))
4350 found)
4351 (setq str (replace-match "" nil nil str 4))
4352 (when tpbuf
4353 ;; Calculate priority of STR wrt its category.
4354 (save-excursion
4355 (while (search-backward filcat nil t)
4356 (setq tpriority (1+ tpriority)))))
4357 (setq file (if file
4358 (concat todo-directory (substring file 0 -1)
4359 (if archive ".toda" ".todo"))
4360 (if archive
4361 (concat (file-name-sans-extension
4362 todo-global-current-todo-file) ".toda")
4363 todo-global-current-todo-file)))
4364 (find-file-noselect file)
4365 (with-current-buffer (find-buffer-visiting file)
4366 (if archive
4367 (unless (derived-mode-p 'todo-archive-mode) (todo-archive-mode))
4368 (unless (derived-mode-p 'todo-mode) (todo-mode)))
4369 (save-restriction
4370 (widen)
4371 (goto-char (point-min))
4372 (let ((beg (re-search-forward
4373 (concat "^" (regexp-quote (concat todo-category-beg cat))
4374 "$")
4375 nil t))
4376 (done (save-excursion
4377 (re-search-forward
4378 (concat "^" (regexp-quote todo-category-done)) nil t)))
4379 (end (save-excursion
4380 (or (re-search-forward
4381 (concat "^" (regexp-quote todo-category-beg))
4382 nil t)
4383 (point-max)))))
4384 (setq found (when (search-forward str end t)
4385 (goto-char (match-beginning 0))))
4386 (when found
4387 (setq found
4388 (cons found (if (> (point) done)
4389 'done
4390 (let ((cpriority 1))
4391 (when tpbuf
4392 (save-excursion
4393 ;; Not top item in category.
4394 (while (> (point) (1+ beg))
4395 (let ((opoint (point)))
4396 (todo-backward-item)
4397 ;; Can't move backward beyond
4398 ;; first item in file.
4399 (unless (= (point) opoint)
4400 (setq cpriority (1+ cpriority)))))))
4401 (if (and (= tpriority cpriority)
4402 ;; Proper substring is not the same.
4403 (string= (todo-item-string)
4404 str))
4405 'same
4406 'changed)))))))))
4407 (list found file cat)))
4409 (defun todo-check-filtered-items-file ()
4410 "Check if filtered items file is up to date and a show suitable message."
4411 ;; (catch 'old
4412 (let ((count 0))
4413 (while (not (eobp))
4414 (let* ((item (todo-item-string))
4415 (found (car (todo-find-item item))))
4416 (unless (eq (cdr found) 'same)
4417 (save-excursion
4418 (overlay-put (make-overlay (todo-item-start) (todo-item-end))
4419 'face 'todo-search))
4420 (setq count (1+ count))))
4421 ;; (throw 'old (message "The marked item is not up to date.")))
4422 (todo-forward-item))
4423 (if (zerop count)
4424 (message "Filtered items file is up to date.")
4425 (message (concat "The highlighted item" (if (= count 1) " is " "s are ")
4426 "not up to date."
4427 ;; "\nType <return> on item for details."
4428 )))))
4430 (defun todo-filter-items-filename ()
4431 "Return absolute file name for saving this Filtered Items buffer."
4432 (let ((bufname (buffer-name)))
4433 (string-match "\"\\([^\"]+\\)\"" bufname)
4434 (let* ((filename-str (substring bufname (match-beginning 1) (match-end 1)))
4435 (filename-base (replace-regexp-in-string ", " "-" filename-str))
4436 (top-priorities (string-match "top priorities" bufname))
4437 (diary-items (string-match "diary items" bufname))
4438 (regexp-items (string-match "regexp items" bufname)))
4439 (when regexp-items
4440 (let ((prompt (concat "Enter a short identifying string"
4441 " to make this file name unique: ")))
4442 (setq filename-base (concat filename-base "-" (read-string prompt)))))
4443 (concat todo-directory filename-base
4444 (cond (top-priorities ".todt")
4445 (diary-items ".tody")
4446 (regexp-items ".todr"))))))
4448 (defun todo-save-filtered-items-buffer ()
4449 "Save current Filtered Items buffer to a file.
4450 If the file already exists, overwrite it only on confirmation."
4451 (let ((filename (or (buffer-file-name) (todo-filter-items-filename))))
4452 (write-file filename t)))
4454 ;; -----------------------------------------------------------------------------
4455 ;;; Printing Todo mode buffers
4456 ;; -----------------------------------------------------------------------------
4458 (defcustom todo-print-buffer-function 'ps-print-buffer-with-faces
4459 "Function called by the command `todo-print-buffer'."
4460 :type 'symbol
4461 :group 'todo)
4463 (defvar todo-print-buffer "*Todo Print*"
4464 "Name of buffer with printable version of Todo mode buffer.")
4466 (defun todo-print-buffer (&optional to-file)
4467 "Produce a printable version of the current Todo mode buffer.
4468 This converts overlays and soft line wrapping and, depending on
4469 the value of `todo-print-buffer-function', includes faces. With
4470 non-nil argument TO-FILE write the printable version to a file;
4471 otherwise, send it to the default printer."
4472 (interactive)
4473 (let ((buf todo-print-buffer)
4474 (header (cond
4475 ((eq major-mode 'todo-mode)
4476 (concat "Todo File: "
4477 (todo-short-file-name todo-current-todo-file)
4478 "\nCategory: " (todo-current-category)))
4479 ((eq major-mode 'todo-filtered-items-mode)
4480 (buffer-name))))
4481 (prefix (propertize (concat todo-prefix " ")
4482 'face 'todo-prefix-string))
4483 (num 0)
4484 (fill-prefix (make-string todo-indent-to-here 32))
4485 (content (buffer-string))
4486 file)
4487 (with-current-buffer (get-buffer-create buf)
4488 (insert content)
4489 (goto-char (point-min))
4490 (while (not (eobp))
4491 (let ((beg (point))
4492 (end (save-excursion (todo-item-end))))
4493 (when todo-number-prefix
4494 (setq num (1+ num))
4495 (setq prefix (propertize (concat (number-to-string num) " ")
4496 'face 'todo-prefix-string)))
4497 (insert prefix)
4498 (fill-region beg end))
4499 ;; Calling todo-forward-item infloops at todo-item-start due to
4500 ;; non-overlay prefix, so search for item start instead.
4501 (if (re-search-forward todo-item-start nil t)
4502 (beginning-of-line)
4503 (goto-char (point-max))))
4504 (if (re-search-backward (concat "^" (regexp-quote todo-category-done))
4505 nil t)
4506 (replace-match todo-done-separator))
4507 (goto-char (point-min))
4508 (insert header)
4509 (newline 2)
4510 (if to-file
4511 (let ((file (read-file-name "Print to file: ")))
4512 (funcall todo-print-buffer-function file))
4513 (funcall todo-print-buffer-function)))
4514 (kill-buffer buf)))
4516 (defun todo-print-buffer-to-file ()
4517 "Save printable version of this Todo mode buffer to a file."
4518 (interactive)
4519 (todo-print-buffer t))
4521 ;; -----------------------------------------------------------------------------
4522 ;;; Legacy Todo mode files
4523 ;; -----------------------------------------------------------------------------
4525 (defcustom todo-legacy-date-time-regexp
4526 (concat "\\(?1:[0-9]\\{4\\}\\)-\\(?2:[0-9]\\{2\\}\\)-"
4527 "\\(?3:[0-9]\\{2\\}\\) \\(?4:[0-9]\\{2\\}:[0-9]\\{2\\}\\)")
4528 "Regexp matching legacy todo-mode.el item date-time strings.
4529 In order for `todo-convert-legacy-files' to correctly convert
4530 this string to the current Todo mode format, the regexp must
4531 contain four explicitly numbered groups (see `(elisp) Regexp
4532 Backslash'), where group 1 matches a string for the year, group 2
4533 a string for the month, group 3 a string for the day and group 4
4534 a string for the time. The default value converts date-time
4535 strings built using the default value of
4536 `todo-time-string-format' from todo-mode.el."
4537 :type 'regexp
4538 :group 'todo)
4540 (defun todo-convert-legacy-date-time ()
4541 "Return converted date-time string.
4542 Helper function for `todo-convert-legacy-files'."
4543 (let* ((year (match-string 1))
4544 (month (match-string 2))
4545 (monthname (calendar-month-name (string-to-number month) t))
4546 (day (match-string 3))
4547 (time (match-string 4))
4548 dayname)
4549 (replace-match "")
4550 (insert (mapconcat 'eval calendar-date-display-form "")
4551 (when time (concat " " time)))))
4553 (defun todo-convert-legacy-files ()
4554 "Convert legacy todo files to the current Todo mode format.
4555 The old-style files named by the variables `todo-file-do' and
4556 `todo-file-done' from the old package are converted to the new
4557 format and saved (the latter as a todo archive file) with a new
4558 name in `todo-directory'. See also the documentation string of
4559 `todo-legacy-date-time-regexp' for further details."
4560 (interactive)
4561 ;; If there are user customizations of legacy options, use them,
4562 ;; otherwise use the legacy default values.
4563 (let ((todo-file-do-tem (if (boundp 'todo-file-do)
4564 todo-file-do
4565 (locate-user-emacs-file "todo-do" ".todo-do")))
4566 (todo-file-done-tem (if (boundp 'todo-file-done)
4567 todo-file-done
4568 (locate-user-emacs-file "todo-done" ".todo-done")))
4569 (todo-initials-tem (and (boundp 'todo-initials) todo-initials))
4570 (todo-entry-prefix-function-tem (and (boundp 'todo-entry-prefix-function)
4571 todo-entry-prefix-function))
4572 todo-prefix-tem)
4573 ;; Convert `todo-file-do'.
4574 (if (not (file-exists-p todo-file-do-tem))
4575 (message "No legacy todo file exists")
4576 (let ((default "todo-do-conv")
4577 file archive-sexp)
4578 (with-temp-buffer
4579 (insert-file-contents todo-file-do-tem)
4580 ;; Eliminate old-style local variables list in first line.
4581 (delete-region (line-beginning-position) (1+ (line-end-position)))
4582 (search-forward " --- " nil t) ; Legacy todo-category-beg.
4583 (setq todo-prefix-tem (buffer-substring-no-properties
4584 (line-beginning-position) (match-beginning 0)))
4585 (goto-char (point-min))
4586 (while (not (eobp))
4587 (cond
4588 ;; Old-style category start delimiter.
4589 ((looking-at (regexp-quote (concat todo-prefix-tem " --- ")))
4590 (replace-match todo-category-beg))
4591 ;; Old-style category end delimiter.
4592 ((looking-at (regexp-quote "--- End"))
4593 (replace-match ""))
4594 ;; Old-style category separator.
4595 ((looking-at (regexp-quote
4596 (concat todo-prefix-tem " "
4597 (make-string 75 ?-))))
4598 (replace-match todo-category-done))
4599 ;; Old-style item header (date/time/initials).
4600 ((looking-at (concat (regexp-quote todo-prefix-tem) " "
4601 (if todo-entry-prefix-function-tem
4602 (funcall todo-entry-prefix-function-tem)
4603 (concat todo-legacy-date-time-regexp " "
4604 (if todo-initials-tem
4605 (regexp-quote todo-initials-tem)
4606 "[^:]*")
4607 ":"))))
4608 (todo-convert-legacy-date-time)))
4609 (forward-line))
4610 (setq file (concat todo-directory
4611 (read-string
4612 (format "Save file as (default \"%s\"): " default)
4613 nil nil default)
4614 ".todo"))
4615 (unless (file-exists-p todo-directory)
4616 (make-directory todo-directory))
4617 (write-region (point-min) (point-max) file nil 'nomessage nil t))
4618 (with-temp-buffer
4619 (insert-file-contents file)
4620 (let ((todo-categories (todo-make-categories-list t)))
4621 (todo-update-categories-sexp)
4622 (todo-check-format))
4623 (write-region (point-min) (point-max) file nil 'nomessage))
4624 (setq todo-files (funcall todo-files-function))
4625 ;; Convert `todo-file-done'.
4626 (when (file-exists-p todo-file-done-tem)
4627 (with-temp-buffer
4628 (insert-file-contents todo-file-done-tem)
4629 (let ((beg (make-marker))
4630 (end (make-marker))
4631 cat cats comment item)
4632 (while (not (eobp))
4633 (when (looking-at todo-legacy-date-time-regexp)
4634 (set-marker beg (point))
4635 (todo-convert-legacy-date-time)
4636 (set-marker end (point))
4637 (goto-char beg)
4638 (insert "[" todo-done-string)
4639 (goto-char end)
4640 (insert "]")
4641 (forward-char)
4642 (when (looking-at todo-legacy-date-time-regexp)
4643 (todo-convert-legacy-date-time))
4644 (when (looking-at (concat " " (if todo-initials-tem
4645 (regexp-quote
4646 todo-initials-tem)
4647 "[^:]*")
4648 ":"))
4649 (replace-match "")))
4650 (if (re-search-forward
4651 (concat "^" todo-legacy-date-time-regexp) nil t)
4652 (goto-char (match-beginning 0))
4653 (goto-char (point-max)))
4654 (backward-char)
4655 (when (looking-back "\\[\\([^][]+\\)\\]"
4656 (line-beginning-position))
4657 (setq cat (match-string 1))
4658 (goto-char (match-beginning 0))
4659 (replace-match ""))
4660 ;; If the item ends with a non-comment parenthesis not
4661 ;; followed by a period, we lose (but we inherit that
4662 ;; problem from the legacy code).
4663 ;; FIXME: fails on multiline comment
4664 (when (looking-back "(\\(.*\\)) " (line-beginning-position))
4665 (setq comment (match-string 1))
4666 (replace-match "")
4667 (insert "[" todo-comment-string ": " comment "]"))
4668 (set-marker end (point))
4669 (if (member cat cats)
4670 ;; If item is already in its category, leave it there.
4671 (unless (save-excursion
4672 (re-search-backward
4673 (concat "^" (regexp-quote todo-category-beg)
4674 "\\(.*\\)$") nil t)
4675 (string= (match-string 1) cat))
4676 ;; Else move it to its category.
4677 (setq item (buffer-substring-no-properties beg end))
4678 (delete-region beg (1+ end))
4679 (set-marker beg (point))
4680 (re-search-backward
4681 (concat "^"
4682 (regexp-quote (concat todo-category-beg cat))
4683 "$")
4684 nil t)
4685 (forward-line)
4686 (if (re-search-forward
4687 (concat "^" (regexp-quote todo-category-beg)
4688 "\\(.*\\)$") nil t)
4689 (progn (goto-char (match-beginning 0))
4690 (newline)
4691 (forward-line -1))
4692 (goto-char (point-max)))
4693 (insert item "\n")
4694 (goto-char beg))
4695 (push cat cats)
4696 (goto-char beg)
4697 (insert todo-category-beg cat "\n\n"
4698 todo-category-done "\n"))
4699 (forward-line))
4700 (set-marker beg nil)
4701 (set-marker end nil))
4702 (setq file (concat (file-name-sans-extension file) ".toda"))
4703 (write-region (point-min) (point-max) file nil 'nomessage nil t))
4704 (with-temp-buffer
4705 (insert-file-contents file)
4706 (let* ((todo-categories (todo-make-categories-list t)))
4707 (todo-update-categories-sexp)
4708 (todo-check-format))
4709 (write-region (point-min) (point-max) file nil 'nomessage)
4710 (setq archive-sexp (read (buffer-substring-no-properties
4711 (line-beginning-position)
4712 (line-end-position)))))
4713 (setq file (concat (file-name-sans-extension file) ".todo"))
4714 ;; Update categories sexp of converted todo file again, adding
4715 ;; counts of archived items.
4716 (with-temp-buffer
4717 (insert-file-contents file)
4718 (let ((sexp (read (buffer-substring-no-properties
4719 (line-beginning-position)
4720 (line-end-position)))))
4721 (dolist (cat sexp)
4722 (let ((archive-cat (assoc (car cat) archive-sexp)))
4723 (if archive-cat
4724 (aset (cdr cat) 3 (aref (cdr archive-cat) 2)))))
4725 (delete-region (line-beginning-position) (line-end-position))
4726 (prin1 sexp (current-buffer)))
4727 (write-region (point-min) (point-max) file nil 'nomessage))
4728 (setq todo-archives (funcall todo-files-function t)))
4729 (todo-reevaluate-filelist-defcustoms)
4730 (when (y-or-n-p (concat "Format conversion done; do you want to "
4731 "visit the converted file now? "))
4732 (setq todo-current-todo-file file)
4733 (unless todo-default-todo-file
4734 ;; We just initialized the first todo file, so make it the
4735 ;; default now to avoid an infinite recursion with todo-show.
4736 (setq todo-default-todo-file (todo-short-file-name file)))
4737 (todo-show))))))
4739 ;; -----------------------------------------------------------------------------
4740 ;;; Utility functions for todo files, categories and items
4741 ;; -----------------------------------------------------------------------------
4743 (defun todo-absolute-file-name (name &optional type)
4744 "Return the absolute file name of short todo file NAME.
4745 With TYPE `archive' or `top' return the absolute file name of the
4746 short todo archive or top priorities file name, respectively."
4747 ;; No-op if there is no todo file yet (i.e. don't concatenate nil).
4748 (when name
4749 (file-truename
4750 (concat todo-directory name
4751 (cond ((eq type 'archive) ".toda")
4752 ((eq type 'top) ".todt")
4753 ((eq type 'diary) ".tody")
4754 ((eq type 'regexp) ".todr")
4755 (t ".todo"))))))
4757 (defun todo-check-file (file)
4758 "Check the state associated with FILE and update it if necessary.
4759 If FILE exists, return t. If it does not exist and there is no
4760 live buffer with its content, return nil; if there is such a
4761 buffer and the user tries to show it, ask whether to restore
4762 FILE, and if confirmed, do so and return t; else delete the
4763 buffer, clean up the state and return nil."
4764 (setq todo-files (funcall todo-files-function))
4765 (setq todo-archives (funcall todo-files-function t))
4766 (if (file-exists-p file)
4768 (setq todo-visited (delete file todo-visited))
4769 (let ((buf (find-buffer-visiting file)))
4770 (if (and buf
4771 (y-or-n-p
4772 (concat
4773 (format (concat "Todo file \"%s\" has been deleted but "
4774 "its content is still in a buffer!\n")
4775 (todo-short-file-name file))
4776 "Save that buffer and restore the todo file? ")))
4777 (progn
4778 (with-current-buffer buf (save-buffer))
4779 (setq todo-files (funcall todo-files-function))
4780 (setq todo-archives (funcall todo-files-function t))
4782 (let* ((files (append todo-files todo-archives))
4783 (tctf todo-current-todo-file)
4784 (tgctf todo-global-current-todo-file)
4785 (tdtf (todo-absolute-file-name todo-default-todo-file)))
4786 (unless (or (not todo-current-todo-file)
4787 (member todo-current-todo-file files))
4788 (setq todo-current-todo-file nil))
4789 (unless (or (not todo-global-current-todo-file)
4790 (member todo-global-current-todo-file files))
4791 (setq todo-global-current-todo-file nil))
4792 (unless (or (not todo-default-todo-file)
4793 (member todo-default-todo-file files))
4794 (setq todo-default-todo-file (todo-short-file-name
4795 (car todo-files))))
4796 (todo-reevaluate-filelist-defcustoms)
4797 (when buf (kill-buffer buf))
4798 nil)))))
4800 (defun todo-category-number (cat)
4801 "Return the number of category CAT in this todo file.
4802 The buffer-local variable `todo-category-number' holds this
4803 number as its value."
4804 (let ((categories (mapcar 'car todo-categories)))
4805 (setq todo-category-number
4806 ;; Increment by one, so that the number of the first
4807 ;; category is one rather than zero.
4808 (1+ (- (length categories)
4809 (length (member cat categories)))))))
4811 (defun todo-current-category ()
4812 "Return the name of the current category."
4813 (car (nth (1- todo-category-number) todo-categories)))
4815 (defun todo-category-select ()
4816 "Display the current category correctly."
4817 (let ((name (todo-current-category))
4818 cat-begin cat-end done-start done-sep-start done-end)
4819 (widen)
4820 (goto-char (point-min))
4821 (re-search-forward
4822 (concat "^" (regexp-quote (concat todo-category-beg name)) "$") nil t)
4823 (setq cat-begin (1+ (line-end-position)))
4824 (setq cat-end (if (re-search-forward
4825 (concat "^" (regexp-quote todo-category-beg)) nil t)
4826 (match-beginning 0)
4827 (point-max)))
4828 (setq mode-line-buffer-identification
4829 (funcall todo-mode-line-function name))
4830 (narrow-to-region cat-begin cat-end)
4831 (todo-prefix-overlays)
4832 (goto-char (point-min))
4833 (if (re-search-forward (concat "\n\\(" (regexp-quote todo-category-done)
4834 "\\)") nil t)
4835 (progn
4836 (setq done-start (match-beginning 0))
4837 (setq done-sep-start (match-beginning 1))
4838 (setq done-end (match-end 0)))
4839 (error "Category %s is missing todo-category-done string" name))
4840 (if todo-show-done-only
4841 (narrow-to-region (1+ done-end) (point-max))
4842 (when (and todo-show-with-done
4843 (re-search-forward todo-done-string-start nil t))
4844 ;; Now we want to see the done items, so reset displayed end to end of
4845 ;; done items.
4846 (setq done-start cat-end)
4847 ;; Make display overlay for done items separator string, unless there
4848 ;; already is one.
4849 (let* ((done-sep todo-done-separator)
4850 (ov (progn (goto-char done-sep-start)
4851 (todo-get-overlay 'separator))))
4852 (unless ov
4853 (setq ov (make-overlay done-sep-start done-end))
4854 (overlay-put ov 'todo 'separator)
4855 (overlay-put ov 'display done-sep))))
4856 (narrow-to-region (point-min) done-start)
4857 ;; Loading this from todo-mode, or adding it to the mode hook, causes
4858 ;; Emacs to hang in todo-item-start, at (looking-at todo-item-start).
4859 (when todo-highlight-item
4860 (require 'hl-line)
4861 (hl-line-mode 1)))))
4863 (defun todo-get-count (type &optional category)
4864 "Return count of TYPE items in CATEGORY.
4865 If CATEGORY is nil, default to the current category."
4866 (let* ((cat (or category (todo-current-category)))
4867 (counts (cdr (assoc cat todo-categories)))
4868 (idx (cond ((eq type 'todo) 0)
4869 ((eq type 'diary) 1)
4870 ((eq type 'done) 2)
4871 ((eq type 'archived) 3))))
4872 (aref counts idx)))
4874 (defun todo-update-count (type increment &optional category)
4875 "Change count of TYPE items in CATEGORY by integer INCREMENT.
4876 With nil or omitted CATEGORY, default to the current category."
4877 (let* ((cat (or category (todo-current-category)))
4878 (counts (cdr (assoc cat todo-categories)))
4879 (idx (cond ((eq type 'todo) 0)
4880 ((eq type 'diary) 1)
4881 ((eq type 'done) 2)
4882 ((eq type 'archived) 3))))
4883 (aset counts idx (+ increment (aref counts idx)))))
4885 (defun todo-set-categories ()
4886 "Set `todo-categories' from the sexp at the top of the file."
4887 ;; New archive files created by `todo-move-category' are empty, which would
4888 ;; make the sexp test fail and raise an error, so in this case we skip it.
4889 (unless (zerop (buffer-size))
4890 (save-excursion
4891 (save-restriction
4892 (widen)
4893 (goto-char (point-min))
4894 (setq todo-categories
4895 (if (looking-at "((\"")
4896 (read (buffer-substring-no-properties
4897 (line-beginning-position)
4898 (line-end-position)))
4899 (error "Invalid or missing todo-categories sexp")))))))
4901 (defun todo-update-categories-sexp ()
4902 "Update the `todo-categories' sexp at the top of the file."
4903 (let (buffer-read-only)
4904 (save-excursion
4905 (save-restriction
4906 (widen)
4907 (goto-char (point-min))
4908 (if (looking-at (concat "^" (regexp-quote todo-category-beg)))
4909 (progn (newline) (goto-char (point-min)) ; Make space for sexp.
4910 (setq todo-categories (todo-make-categories-list t)))
4911 (delete-region (line-beginning-position) (line-end-position)))
4912 (prin1 todo-categories (current-buffer))))))
4914 (defun todo-make-categories-list (&optional force)
4915 "Return an alist of todo categories and their item counts.
4916 With non-nil argument FORCE parse the entire file to build the
4917 list; otherwise, get the value by reading the sexp at the top of
4918 the file."
4919 (setq todo-categories nil)
4920 (save-excursion
4921 (save-restriction
4922 (widen)
4923 (goto-char (point-min))
4924 (let (counts cat archive)
4925 ;; If the file is a todo file and has archived items, identify the
4926 ;; archive, in order to count its items. But skip this with
4927 ;; `todo-convert-legacy-files', since that converts filed items to
4928 ;; archived items.
4929 (when buffer-file-name ; During conversion there is no file yet.
4930 ;; If the file is an archive, it doesn't have an archive.
4931 (unless (member (file-truename buffer-file-name)
4932 (funcall todo-files-function t))
4933 (setq archive (concat (file-name-sans-extension
4934 todo-current-todo-file) ".toda"))))
4935 (while (not (eobp))
4936 (cond ((looking-at (concat (regexp-quote todo-category-beg)
4937 "\\(.*\\)\n"))
4938 (setq cat (match-string-no-properties 1))
4939 ;; Counts for each category: [todo diary done archive]
4940 (setq counts (make-vector 4 0))
4941 (setq todo-categories
4942 (append todo-categories (list (cons cat counts))))
4943 ;; Add archived item count to the todo file item counts.
4944 ;; Make sure to include newly created archives, e.g. due to
4945 ;; todo-move-category.
4946 (when (member archive (funcall todo-files-function t))
4947 (let ((archive-count 0)
4948 (visiting (find-buffer-visiting archive)))
4949 (with-current-buffer (or visiting
4950 (find-file-noselect archive))
4951 (save-excursion
4952 (save-restriction
4953 (widen)
4954 (goto-char (point-min))
4955 (when (re-search-forward
4956 (concat "^" (regexp-quote todo-category-beg)
4957 cat "$")
4958 (point-max) t)
4959 (forward-line)
4960 (while (not (or (looking-at
4961 (concat
4962 (regexp-quote todo-category-beg)
4963 "\\(.*\\)\n"))
4964 (eobp)))
4965 (when (looking-at todo-done-string-start)
4966 (setq archive-count (1+ archive-count)))
4967 (forward-line)))))
4968 (unless visiting (kill-buffer)))
4969 (todo-update-count 'archived archive-count cat))))
4970 ((looking-at todo-done-string-start)
4971 (todo-update-count 'done 1 cat))
4972 ((looking-at (concat "^\\("
4973 (regexp-quote diary-nonmarking-symbol)
4974 "\\)?" todo-date-pattern))
4975 (todo-update-count 'diary 1 cat)
4976 (todo-update-count 'todo 1 cat))
4977 ((looking-at (concat todo-date-string-start todo-date-pattern))
4978 (todo-update-count 'todo 1 cat))
4979 ;; If first line is todo-categories list, use it and end loop
4980 ;; -- unless FORCEd to scan whole file.
4981 ((bobp)
4982 (unless force
4983 (setq todo-categories (read (buffer-substring-no-properties
4984 (line-beginning-position)
4985 (line-end-position))))
4986 (goto-char (1- (point-max))))))
4987 (forward-line)))))
4988 todo-categories)
4990 (defun todo-repair-categories-sexp ()
4991 "Repair corrupt todo file categories sexp.
4992 This should only be needed as a consequence of careless manual
4993 editing or a bug in todo.el.
4995 *Warning*: Calling this command restores the category order to
4996 the list element order in the todo file categories sexp, so any
4997 order changes made in Todo Categories mode will have to be made
4998 again."
4999 (interactive)
5000 (let ((todo-categories (todo-make-categories-list t)))
5001 (todo-update-categories-sexp)))
5003 (defun todo-check-format ()
5004 "Signal an error if the current todo file is ill-formatted.
5005 Otherwise return t. Display a message if the file is well-formed
5006 but the categories sexp differs from the current value of
5007 `todo-categories'."
5008 (save-excursion
5009 (save-restriction
5010 (widen)
5011 (goto-char (point-min))
5012 (let* ((cats (prin1-to-string todo-categories))
5013 (ssexp (buffer-substring-no-properties (line-beginning-position)
5014 (line-end-position)))
5015 (sexp (read ssexp)))
5016 ;; Check the first line for `todo-categories' sexp.
5017 (dolist (c sexp)
5018 (let ((v (cdr c)))
5019 (unless (and (stringp (car c))
5020 (vectorp v)
5021 (= 4 (length v)))
5022 (user-error "Invalid or missing todo-categories sexp"))))
5023 (forward-line)
5024 ;; Check well-formedness of categories.
5025 (let ((legit (concat
5026 "\\(^" (regexp-quote todo-category-beg) "\\)"
5027 "\\|\\(" todo-date-string-start todo-date-pattern "\\)"
5028 "\\|\\(^[ \t]+[^ \t]*\\)"
5029 "\\|^$"
5030 "\\|\\(^" (regexp-quote todo-category-done) "\\)"
5031 "\\|\\(" todo-done-string-start "\\)")))
5032 (while (not (eobp))
5033 (unless (looking-at legit)
5034 (user-error "Illegitimate todo file format at line %d"
5035 (line-number-at-pos (point))))
5036 (forward-line)))
5037 ;; Warn user if categories sexp has changed.
5038 (unless (string= ssexp cats)
5039 (message (concat "The sexp at the beginning of the file differs "
5040 "from the value of `todo-categories'.\n"
5041 "If the sexp is wrong, you can fix it with "
5042 "M-x todo-repair-categories-sexp,\n"
5043 "but note this reverts any changes you have "
5044 "made in the order of the categories."))))))
5047 (defun todo-item-start ()
5048 "Move to start of current todo item and return its position."
5049 (unless (or
5050 ;; Buffer is empty (invocation possible e.g. via todo-forward-item
5051 ;; from todo-filter-items when processing category with no todo
5052 ;; items).
5053 (eq (point-min) (point-max))
5054 ;; Point is on the empty line below category's last todo item...
5055 (and (looking-at "^$")
5056 (or (eobp) ; ...and done items are hidden...
5057 (save-excursion ; ...or done items are visible.
5058 (forward-line)
5059 (looking-at (concat "^"
5060 (regexp-quote todo-category-done))))))
5061 ;; Buffer is widened.
5062 (looking-at (regexp-quote todo-category-beg)))
5063 (goto-char (line-beginning-position))
5064 (while (not (looking-at todo-item-start))
5065 (forward-line -1))
5066 (point)))
5068 (defun todo-item-end ()
5069 "Move to end of current todo item and return its position."
5070 ;; Items cannot end with a blank line.
5071 (unless (looking-at "^$")
5072 (let* ((done (todo-done-item-p))
5073 (to-lim nil)
5074 ;; For todo items, end is before the done items section, for done
5075 ;; items, end is before the next category. If these limits are
5076 ;; missing or inaccessible, end it before the end of the buffer.
5077 (lim (if (save-excursion
5078 (re-search-forward
5079 (concat "^" (regexp-quote (if done
5080 todo-category-beg
5081 todo-category-done)))
5082 nil t))
5083 (progn (setq to-lim t) (match-beginning 0))
5084 (point-max))))
5085 (when (bolp) (forward-char)) ; Find start of next item.
5086 (goto-char (if (re-search-forward todo-item-start lim t)
5087 (match-beginning 0)
5088 (if to-lim lim (point-max))))
5089 ;; For last todo item, skip back over the empty line before the done
5090 ;; items section, else just back to the end of the previous line.
5091 (backward-char (when (and to-lim (not done) (eq (point) lim)) 2))
5092 (point))))
5094 (defun todo-item-string ()
5095 "Return bare text of current item as a string."
5096 (let ((opoint (point))
5097 (start (todo-item-start))
5098 (end (todo-item-end)))
5099 (goto-char opoint)
5100 (and start end (buffer-substring-no-properties start end))))
5102 (defun todo-forward-item (&optional count)
5103 "Move point COUNT items down (by default, move down by one item)."
5104 (let* ((not-done (not (or (todo-done-item-p) (looking-at "^$"))))
5105 (start (line-end-position)))
5106 (goto-char start)
5107 (if (re-search-forward todo-item-start nil t (or count 1))
5108 (goto-char (match-beginning 0))
5109 (goto-char (point-max)))
5110 ;; If points advances by one from a todo to a done item, go back
5111 ;; to the space above todo-done-separator, since that is a
5112 ;; legitimate place to insert an item. But skip this space if
5113 ;; count > 1, since that should only stop on an item.
5114 (when (and not-done (todo-done-item-p) (not count))
5115 ;; (if (or (not count) (= count 1))
5116 (re-search-backward "^$" start t))));)
5117 ;; The preceding sexp is insufficient when buffer is not narrowed,
5118 ;; since there could be no done items in this category, so the
5119 ;; search puts us on first todo item of next category. Does this
5120 ;; ever happen? If so:
5121 ;; (let ((opoint) (point))
5122 ;; (forward-line -1)
5123 ;; (when (or (not count) (= count 1))
5124 ;; (cond ((looking-at (concat "^" (regexp-quote todo-category-beg)))
5125 ;; (forward-line -2))
5126 ;; ((looking-at (concat "^" (regexp-quote todo-category-done)))
5127 ;; (forward-line -1))
5128 ;; (t
5129 ;; (goto-char opoint)))))))
5131 (defun todo-backward-item (&optional count)
5132 "Move point up to start of item with next higher priority.
5133 With positive numerical prefix COUNT, move point COUNT items
5134 upward.
5136 If the category's done items are visible, this command called
5137 with a prefix argument only moves point to a higher item, e.g.,
5138 with point on the first done item and called with prefix 1, it
5139 moves to the last todo item; but if called with point on the
5140 first done item without a prefix argument, it moves point the the
5141 empty line above the done items separator."
5142 (let* ((done (todo-done-item-p)))
5143 (todo-item-start)
5144 (unless (bobp)
5145 (re-search-backward todo-item-start nil t (or count 1)))
5146 ;; Unless this is a regexp filtered items buffer (which can contain
5147 ;; intermixed todo and done items), if points advances by one from a
5148 ;; done to a todo item, go back to the space above
5149 ;; todo-done-separator, since that is a legitimate place to insert an
5150 ;; item. But skip this space if count > 1, since that should only
5151 ;; stop on an item.
5152 (when (and done (not (todo-done-item-p)) (not count)
5153 ;(or (not count) (= count 1))
5154 (not (equal (buffer-name) todo-regexp-items-buffer)))
5155 (re-search-forward (concat "^" (regexp-quote todo-category-done))
5156 nil t)
5157 (forward-line -1))))
5159 (defun todo-remove-item ()
5160 "Internal function called in editing, deleting or moving items."
5161 (let* ((end (progn (todo-item-end) (1+ (point))))
5162 (beg (todo-item-start))
5163 (ov (todo-get-overlay 'prefix)))
5164 (when ov (delete-overlay ov))
5165 (delete-region beg end)))
5167 (defun todo-diary-item-p ()
5168 "Return non-nil if item at point has diary entry format."
5169 (save-excursion
5170 (when (todo-item-string) ; Exclude empty lines.
5171 (todo-item-start)
5172 (not (looking-at (regexp-quote todo-nondiary-start))))))
5174 ;; This duplicates the item locating code from diary-goto-entry, but
5175 ;; without the marker code, to test whether the latter is dispensable.
5176 ;; If it is, diary-goto-entry can be simplified. The code duplication
5177 ;; here can also be eliminated, leaving only the widening and category
5178 ;; selection, and instead of :override advice :around can be used.
5180 (defun todo-diary-goto-entry (button)
5181 "Jump to the diary entry for the BUTTON at point.
5182 If the entry is a todo item, display its category properly.
5183 Overrides `diary-goto-entry'."
5184 ;; Locate the diary item in its source file.
5185 (let* ((locator (button-get button 'locator))
5186 (file (cadr locator))
5187 (date (regexp-quote (nth 2 locator)))
5188 (content (regexp-quote (nth 3 locator))))
5189 (if (not (and (file-exists-p file)
5190 (find-file-other-window file)))
5191 (message "Unable to locate this diary entry")
5192 ;; If it's a Todo file, make sure it's in Todo mode.
5193 (when (and (equal (file-name-directory (file-truename file))
5194 (file-truename todo-directory))
5195 (not (derived-mode-p 'todo-mode)))
5196 (todo-mode))
5197 (when (eq major-mode 'todo-mode) (widen))
5198 (goto-char (point-min))
5199 (when (re-search-forward (format "%s.*\\(%s\\)" date content) nil t)
5200 (goto-char (match-beginning 1)))
5201 ;; If it's a todo item, determine its category and display the
5202 ;; category properly.
5203 (when (eq major-mode 'todo-mode)
5204 (let ((opoint (point)))
5205 (re-search-backward (concat "^" (regexp-quote todo-category-beg)
5206 "\\(.*\\)\n") nil t)
5207 (todo-category-number (match-string 1))
5208 (todo-category-select)
5209 (goto-char opoint))))))
5211 (add-function :override diary-goto-entry-function #'todo-diary-goto-entry)
5213 (defun todo-revert-buffer (&optional ignore-auto noconfirm)
5214 "Call `revert-buffer', preserving buffer's current modes.
5215 Also preserve category display, if applicable."
5216 (interactive (list (not current-prefix-arg)))
5217 (let ((revert-buffer-function nil))
5218 (revert-buffer ignore-auto noconfirm 'preserve-modes)
5219 (when (memq major-mode '(todo-mode todo-archive-mode))
5220 (todo-category-select))))
5222 (defun todo-desktop-save-buffer (_dir)
5223 `((catnum . ,(todo-category-number (todo-current-category)))))
5225 (declare-function desktop-restore-file-buffer "desktop"
5226 (buffer-filename buffer-name buffer-misc))
5228 (defun todo-restore-desktop-buffer (file buffer misc)
5229 (desktop-restore-file-buffer file buffer misc)
5230 (with-current-buffer buffer
5231 (widen)
5232 (let ((todo-category-number (cdr (assq 'catnum misc))))
5233 (todo-category-select)
5234 (current-buffer))))
5236 (add-to-list 'desktop-buffer-mode-handlers
5237 '(todo-mode . todo-restore-desktop-buffer))
5239 (defun todo-done-item-p ()
5240 "Return non-nil if item at point is a done item."
5241 (save-excursion
5242 (todo-item-start)
5243 (looking-at todo-done-string-start)))
5245 (defun todo-done-item-section-p ()
5246 "Return non-nil if point is in category's done items section."
5247 (save-excursion
5248 (or (re-search-backward (concat "^" (regexp-quote todo-category-done))
5249 nil t)
5250 (progn (goto-char (point-min))
5251 (looking-at todo-done-string-start)))))
5253 (defun todo--user-error-if-marked-done-item ()
5254 "Signal user error on marked done items.
5255 Helper function for editing commands that apply only to (possibly
5256 marked) not done todo items."
5257 (save-excursion
5258 (save-restriction
5259 (goto-char (point-max))
5260 (todo-backward-item)
5261 (unless (todo-done-item-p)
5262 (widen)
5263 (unless (re-search-forward
5264 (concat "^" (regexp-quote todo-category-beg)) nil t)
5265 (goto-char (point-max)))
5266 (forward-line -1))
5267 (while (todo-done-item-p)
5268 (when (todo-marked-item-p)
5269 (user-error "This command does not apply to done items"))
5270 (todo-backward-item)))))
5272 (defun todo-reset-done-separator (sep)
5273 "Replace existing overlays of done items separator string SEP."
5274 (save-excursion
5275 (save-restriction
5276 (widen)
5277 (goto-char (point-min))
5278 (while (re-search-forward
5279 (concat "\n\\(" (regexp-quote todo-category-done) "\\)") nil t)
5280 (let* ((beg (match-beginning 1))
5281 (end (match-end 0))
5282 (ov (progn (goto-char beg)
5283 (todo-get-overlay 'separator)))
5284 (old-sep (when ov (overlay-get ov 'display)))
5285 new-ov)
5286 (when old-sep
5287 (unless (string= old-sep sep)
5288 (setq new-ov (make-overlay beg end))
5289 (overlay-put new-ov 'todo 'separator)
5290 (overlay-put new-ov 'display todo-done-separator)
5291 (delete-overlay ov))))))))
5293 (defun todo-get-overlay (val)
5294 "Return the overlay at point whose `todo' property has value VAL."
5295 ;; Use overlays-in to find prefix overlays and check over two
5296 ;; positions to find done separator overlay.
5297 (let ((ovs (overlays-in (point) (1+ (point))))
5299 (catch 'done
5300 (while ovs
5301 (setq ov (pop ovs))
5302 (when (eq (overlay-get ov 'todo) val)
5303 (throw 'done ov))))))
5305 (defun todo-marked-item-p ()
5306 "Non-nil if this item begins with `todo-item-mark'.
5307 In that case, return the item's prefix overlay."
5308 (let* ((ov (todo-get-overlay 'prefix))
5309 ;; If an item insertion command is called on a todo file
5310 ;; before it is visited, it has no prefix overlays yet, so
5311 ;; check for this.
5312 (pref (when ov (overlay-get ov 'before-string)))
5313 (marked (when pref
5314 (string-match (concat "^" (regexp-quote todo-item-mark))
5315 pref))))
5316 (when marked ov)))
5318 (defun todo-insert-with-overlays (item)
5319 "Insert ITEM at point and update prefix/priority number overlays."
5320 (todo-item-start)
5321 ;; Insertion pushes item down but not its prefix overlay. When the
5322 ;; overlay includes a mark, this would now mark the inserted ITEM,
5323 ;; so move it to the pushed down item.
5324 (let ((ov (todo-get-overlay 'prefix))
5325 (marked (todo-marked-item-p)))
5326 (insert item "\n")
5327 (when marked (move-overlay ov (point) (point))))
5328 (todo-backward-item)
5329 (todo-prefix-overlays))
5331 (defun todo-prefix-overlays ()
5332 "Update the prefix overlays of the current category's items.
5333 The overlay's value is the string `todo-prefix' or with non-nil
5334 `todo-number-prefix' an integer in the sequence from 1 to
5335 the number of todo or done items in the category indicating the
5336 item's priority. Todo and done items are numbered independently
5337 of each other."
5338 (let ((num 0)
5339 (cat-tp (or (cdr (assoc-string
5340 (todo-current-category)
5341 (nth 2 (assoc-string todo-current-todo-file
5342 todo-top-priorities-overrides))))
5343 (nth 1 (assoc-string todo-current-todo-file
5344 todo-top-priorities-overrides))
5345 todo-top-priorities))
5346 done prefix)
5347 (save-excursion
5348 (goto-char (point-min))
5349 (while (not (eobp))
5350 (when (or (todo-date-string-matcher (line-end-position))
5351 (todo-done-string-matcher (line-end-position)))
5352 (goto-char (match-beginning 0))
5353 (setq num (1+ num))
5354 ;; Reset number to 1 for first done item.
5355 (when (and (eq major-mode 'todo-mode)
5356 (looking-at todo-done-string-start)
5357 (looking-back (concat "^"
5358 (regexp-quote todo-category-done)
5359 "\n")
5360 (line-beginning-position 0)))
5361 (setq num 1
5362 done t))
5363 (setq prefix (concat (propertize
5364 (if todo-number-prefix
5365 (number-to-string num)
5366 todo-prefix)
5367 'face
5368 ;; Prefix of top priority items has a
5369 ;; distinct face in Todo mode.
5370 (if (and (eq major-mode 'todo-mode)
5371 (not done)
5372 (<= num cat-tp))
5373 'todo-top-priority
5374 'todo-prefix-string))
5375 " "))
5376 (let ((ov (todo-get-overlay 'prefix))
5377 (marked (todo-marked-item-p)))
5378 ;; Prefix overlay must be at a single position so its
5379 ;; bounds aren't changed when (re)moving an item.
5380 (unless ov (setq ov (make-overlay (point) (point))))
5381 (overlay-put ov 'todo 'prefix)
5382 (overlay-put ov 'before-string (if marked
5383 (concat todo-item-mark prefix)
5384 prefix))))
5385 (forward-line)))))
5387 ;; -----------------------------------------------------------------------------
5388 ;;; Generating and applying item insertion and editing key sequences
5389 ;; -----------------------------------------------------------------------------
5391 ;; Thanks to Stefan Monnier for suggesting dynamically generating item
5392 ;; insertion commands and their key bindings, and offering an elegant
5393 ;; implementation, which, however, relies on lexical scoping and so
5394 ;; cannot be used here until the Calendar code used by todo-mode.el is
5395 ;; converted to lexical binding. Hence, the following implementation
5396 ;; uses dynamic binding.
5398 (defconst todo-insert-item--parameters
5399 '((default copy) (diary nonmarking) (calendar date dayname) time (here region))
5400 "List of all item insertion parameters.
5401 Passed by `todo-insert-item' to `todo-insert-item--next-param' to
5402 dynamically create item insertion commands.")
5404 (defconst todo-insert-item--param-key-alist
5405 '((default . "i")
5406 (copy . "p")
5407 (diary . "y")
5408 (nonmarking . "k")
5409 (calendar . "c")
5410 (date . "d")
5411 (dayname . "n")
5412 (time . "t")
5413 (here . "h")
5414 (region . "r"))
5415 "List pairing item insertion parameters with their completion keys.")
5417 (defsubst todo-insert-item--keyof (param)
5418 "Return key paired with item insertion PARAM."
5419 (cdr (assoc param todo-insert-item--param-key-alist)))
5421 (defun todo-insert-item--argsleft (key list)
5422 "Return sublist of LIST whose first member corresponds to KEY."
5423 (let (l sym)
5424 (mapc (lambda (m)
5425 (when (consp m)
5426 (catch 'found1
5427 (dolist (s m)
5428 (when (equal key (todo-insert-item--keyof s))
5429 (throw 'found1 (setq sym s))))))
5430 (if sym
5431 (progn
5432 (push sym l)
5433 (setq sym nil))
5434 (push m l)))
5435 list)
5436 (setq list (reverse l)))
5437 (memq (catch 'found2
5438 (dolist (e todo-insert-item--param-key-alist)
5439 (when (equal key (cdr e))
5440 (throw 'found2 (car e)))))
5441 list))
5443 (defsubst todo-insert-item--this-key () (char-to-string last-command-event))
5445 (defvar todo-insert-item--keys-so-far ""
5446 "String of item insertion keys so far entered for this command.")
5448 (defvar todo-insert-item--args nil)
5449 (defvar todo-insert-item--argleft nil)
5450 (defvar todo-insert-item--argsleft nil)
5451 (defvar todo-insert-item--newargsleft nil)
5453 (defun todo-insert-item--apply-args ()
5454 "Build list of arguments for item insertion and apply them.
5455 The list consists of item insertion parameters that can be passed
5456 as insertion command arguments in fixed positions. If a position
5457 in the list is not occupied by the corresponding parameter, it is
5458 occupied by nil."
5459 (let* ((arg (list (car todo-insert-item--args)))
5460 (args (nconc (cdr todo-insert-item--args)
5461 (list (car (todo-insert-item--argsleft
5462 (todo-insert-item--this-key)
5463 todo-insert-item--argsleft)))))
5464 (arglist (if (= 4 (length args))
5465 args
5466 (let ((v (make-vector 4 nil)) elt)
5467 (while args
5468 (setq elt (pop args))
5469 (cond ((memq elt '(diary nonmarking))
5470 (aset v 0 elt))
5471 ((memq elt '(calendar date dayname))
5472 (aset v 1 elt))
5473 ((eq elt 'time)
5474 (aset v 2 elt))
5475 ((memq elt '(copy here region))
5476 (aset v 3 elt))))
5477 (append v nil)))))
5478 (apply #'todo-insert-item--basic (nconc arg arglist))))
5480 (defun todo-insert-item--next-param (last args argsleft)
5481 "Build item insertion command from LAST, ARGS and ARGSLEFT and call it.
5482 Dynamically generate key bindings, prompting with the keys
5483 already entered and those still available."
5484 (cl-assert argsleft)
5485 (let* ((map (make-sparse-keymap))
5486 (prompt nil)
5487 (addprompt
5488 (lambda (k name)
5489 (setq prompt
5490 (concat prompt
5491 (format
5492 (concat
5493 (if (memq name '(default diary calendar here))
5494 " { " " ")
5495 "%s=>%s"
5496 (when (memq name '(copy nonmarking dayname region))
5497 " }"))
5498 (propertize k 'face 'todo-key-prompt)
5499 name))))))
5500 (setq todo-insert-item--args args)
5501 (setq todo-insert-item--argsleft argsleft)
5502 (when last
5503 (if (memq last '(default copy))
5504 (progn
5505 (setq todo-insert-item--argsleft nil)
5506 (todo-insert-item--apply-args))
5507 (let ((k (todo-insert-item--keyof last)))
5508 (funcall addprompt k (make-symbol (concat (symbol-name last) ":GO!")))
5509 (define-key map (todo-insert-item--keyof last)
5510 (lambda () (interactive)
5511 (todo-insert-item--apply-args))))))
5512 (while todo-insert-item--argsleft
5513 (let ((x (car todo-insert-item--argsleft)))
5514 (setq todo-insert-item--newargsleft (cdr todo-insert-item--argsleft))
5515 (dolist (argleft (if (consp x) x (list x)))
5516 (let ((k (todo-insert-item--keyof argleft)))
5517 (funcall addprompt k argleft)
5518 (define-key map k
5519 (if (null todo-insert-item--newargsleft)
5520 (lambda () (interactive)
5521 (todo-insert-item--apply-args))
5522 (lambda () (interactive)
5523 (setq todo-insert-item--keys-so-far
5524 (concat todo-insert-item--keys-so-far " "
5525 (todo-insert-item--this-key)))
5526 (todo-insert-item--next-param
5527 (car (todo-insert-item--argsleft
5528 (todo-insert-item--this-key)
5529 todo-insert-item--argsleft))
5530 (nconc todo-insert-item--args
5531 (list (car (todo-insert-item--argsleft
5532 (todo-insert-item--this-key)
5533 todo-insert-item--argsleft))))
5534 (cdr (todo-insert-item--argsleft
5535 (todo-insert-item--this-key)
5536 todo-insert-item--argsleft)))))))))
5537 (setq todo-insert-item--argsleft todo-insert-item--newargsleft))
5538 (when prompt (message "Press a key (so far `%s'): %s"
5539 todo-insert-item--keys-so-far prompt))
5540 (set-transient-map map)
5541 (setq todo-insert-item--argsleft argsleft)))
5543 (defconst todo-edit-item--param-key-alist
5544 '((edit . "e")
5545 (header . "h")
5546 (multiline . "m")
5547 (diary . "y")
5548 (nonmarking . "k")
5549 (date . "d")
5550 (time . "t"))
5551 "Alist of item editing parameters and their keys.")
5553 (defconst todo-edit-item--date-param-key-alist
5554 '((full . "f")
5555 (calendar . "c")
5556 (today . "a")
5557 (dayname . "n")
5558 (year . "y")
5559 (month . "m")
5560 (daynum . "d"))
5561 "Alist of item date editing parameters and their keys.")
5563 (defconst todo-edit-done-item--param-key-alist
5564 '((add/edit . "c")
5565 (delete . "d"))
5566 "Alist of done item comment editing parameters and their keys.")
5568 (defvar todo-edit-item--prompt "Press a key (so far `e'): ")
5570 (defun todo-edit-item--next-key (params &optional arg)
5571 (let* ((map (make-sparse-keymap))
5572 (p->k (mapconcat (lambda (elt)
5573 (format "%s=>%s"
5574 (propertize (cdr elt) 'face
5575 'todo-key-prompt)
5576 (concat (symbol-name (car elt))
5577 (when (memq (car elt)
5578 '(add/edit delete))
5579 " comment"))))
5580 params " "))
5581 (key-prompt (substitute-command-keys todo-edit-item--prompt))
5582 (this-key (let ((key (read-key (concat key-prompt p->k))))
5583 (and (characterp key) (char-to-string key))))
5584 (this-param (car (rassoc this-key params))))
5585 (pcase this-param
5586 (`edit (todo-edit-item--text))
5587 (`header (todo-edit-item--text 'include-header))
5588 (`multiline (todo-edit-item--text 'multiline))
5589 (`add/edit (todo-edit-item--text 'comment-edit))
5590 (`delete (todo-edit-item--text 'comment-delete))
5591 (`diary (todo-edit-item--diary-inclusion))
5592 (`nonmarking (todo-edit-item--diary-inclusion 'nonmarking))
5593 (`date (let ((todo-edit-item--prompt "Press a key (so far `e d'): "))
5594 (todo-edit-item--next-key
5595 todo-edit-item--date-param-key-alist arg)))
5596 (`full (progn (todo-edit-item--header 'date)
5597 (when todo-always-add-time-string
5598 (todo-edit-item--header 'time))))
5599 (`calendar (todo-edit-item--header 'calendar))
5600 (`today (todo-edit-item--header 'today))
5601 (`dayname (todo-edit-item--header 'dayname))
5602 (`year (todo-edit-item--header 'year arg))
5603 (`month (todo-edit-item--header 'month arg))
5604 (`daynum (todo-edit-item--header 'day arg))
5605 (`time (todo-edit-item--header 'time)))))
5607 ;; -----------------------------------------------------------------------------
5608 ;;; Todo minibuffer utilities
5609 ;; -----------------------------------------------------------------------------
5611 (defcustom todo-y-with-space nil
5612 "Non-nil means allow SPC to affirm a \"y or n\" question."
5613 :type 'boolean
5614 :group 'todo)
5616 (defun todo-y-or-n-p (prompt)
5617 "Ask \"y or n\" question PROMPT and return t if answer is \"y\".
5618 Also return t if answer is \"Y\", but unlike `y-or-n-p', allow
5619 SPC to affirm the question only if option `todo-y-with-space' is
5620 non-nil."
5621 (unless todo-y-with-space
5622 (define-key query-replace-map " " 'ignore))
5623 (prog1
5624 (y-or-n-p prompt)
5625 (define-key query-replace-map " " 'act)))
5627 (defun todo-category-completions (&optional archive)
5628 "Return a list of completions for `todo-read-category'.
5629 Each element of the list is a cons of a category name and the
5630 file or list of files (as short file names) it is in. The files
5631 are either the current (or if there is none, the default) todo
5632 file plus the files listed in `todo-category-completions-files',
5633 or, with non-nil ARCHIVE, the current archive file.
5635 Before calculating the completions, update the value of
5636 `todo-category-completions-files' in case any files named in it
5637 have been removed."
5638 (let (deleted)
5639 (dolist (f todo-category-completions-files)
5640 (unless (file-exists-p (todo-absolute-file-name f))
5641 (setq todo-category-completions-files
5642 (delete f todo-category-completions-files))
5643 (push f deleted)))
5644 (when deleted
5645 (let ((pl (> (length deleted) 1))
5646 (names (mapconcat (lambda (f) (concat "\"" f "\"")) deleted ", ")))
5647 (message (concat "File" (if pl "s" "") " %s ha" (if pl "ve" "s")
5648 " been deleted and removed from\n"
5649 "the list of category completion files")
5650 names))
5651 (todo-reevaluate-category-completions-files-defcustom)
5652 (custom-set-default 'todo-category-completions-files
5653 (symbol-value 'todo-category-completions-files))
5654 (sleep-for 1.5)))
5655 (let* ((curfile (or todo-current-todo-file
5656 (and todo-show-current-file
5657 todo-global-current-todo-file)
5658 (todo-absolute-file-name todo-default-todo-file)))
5659 (files (or (unless archive
5660 (mapcar 'todo-absolute-file-name
5661 todo-category-completions-files))
5662 (list curfile)))
5663 listall listf)
5664 ;; If file was just added, it has no category completions.
5665 (unless (zerop (buffer-size (find-buffer-visiting curfile)))
5666 (unless (member curfile todo-archives)
5667 (add-to-list 'files curfile))
5668 (dolist (f files listall)
5669 (with-current-buffer (find-file-noselect f 'nowarn)
5670 (if archive
5671 (unless (derived-mode-p 'todo-archive-mode) (todo-archive-mode))
5672 (unless (derived-mode-p 'todo-mode) (todo-mode)))
5673 ;; Ensure category is properly displayed in case user
5674 ;; switches to file via a non-Todo mode command. And if
5675 ;; done items in category are visible, keep them visible.
5676 (let ((done todo-show-with-done))
5677 (when (> (buffer-size) (- (point-max) (point-min)))
5678 (save-excursion
5679 (goto-char (point-min))
5680 (setq done (re-search-forward todo-done-string-start nil t))))
5681 (let ((todo-show-with-done done))
5682 (save-excursion (todo-category-select))))
5683 (save-excursion
5684 (save-restriction
5685 (widen)
5686 (goto-char (point-min))
5687 (setq listf (read (buffer-substring-no-properties
5688 (line-beginning-position)
5689 (line-end-position)))))))
5690 (mapc (lambda (elt) (let* ((cat (car elt))
5691 (la-elt (assoc cat listall)))
5692 (if la-elt
5693 (setcdr la-elt (append (list (cdr la-elt))
5694 (list f)))
5695 (push (cons cat f) listall))))
5696 listf)))))
5698 (defun todo-read-file-name (prompt &optional archive mustmatch)
5699 "Choose and return the name of a todo file, prompting with PROMPT.
5701 Show completions with TAB or SPC; the names are shown in short
5702 form but the absolute truename is returned. With non-nil ARCHIVE
5703 return the absolute truename of a todo archive file. With non-nil
5704 MUSTMATCH the name of an existing file must be chosen;
5705 otherwise, a new file name is allowed."
5706 (let* ((completion-ignore-case todo-completion-ignore-case)
5707 (files (mapcar 'todo-short-file-name
5708 ;; (funcall todo-files-function archive)))
5709 (if archive todo-archives todo-files)))
5710 (file (completing-read prompt files nil mustmatch nil nil
5711 (if files
5712 ;; If user hit RET without
5713 ;; choosing a file, default to
5714 ;; current or default file.
5715 (todo-short-file-name
5716 (or todo-current-todo-file
5717 (and todo-show-current-file
5718 todo-global-current-todo-file)
5719 (todo-absolute-file-name
5720 todo-default-todo-file)))
5721 ;; Trigger prompt for initial file.
5722 ""))))
5723 (unless (file-exists-p todo-directory)
5724 (make-directory todo-directory))
5725 (unless (or mustmatch (member file files))
5726 (setq file (todo-validate-name file 'file)))
5727 (setq file (file-truename (concat todo-directory file
5728 (if archive ".toda" ".todo"))))))
5730 (defun todo-read-category (prompt &optional match-type file)
5731 "Choose and return a category name, prompting with PROMPT.
5732 Show completions for existing categories with TAB or SPC.
5734 The argument MATCH-TYPE specifies the matching requirements on
5735 the category name: with the value `todo' or `archive' the name
5736 must complete to that of an existing todo or archive category,
5737 respectively; with the value `add' the name must not be that of
5738 an existing category; with all other values both existing and new
5739 valid category names are accepted.
5741 With non-nil argument FILE prompt for a file and complete only
5742 against categories in that file; otherwise complete against all
5743 categories from `todo-category-completions-files'."
5744 ;; Allow SPC to insert spaces, for adding new category names.
5745 (let ((map minibuffer-local-completion-map))
5746 (define-key map " " nil)
5747 (let* ((add (eq match-type 'add))
5748 (archive (eq match-type 'archive))
5749 (file0 (when (and file (> (length todo-files) 1))
5750 (todo-read-file-name (concat "Choose a" (if archive
5751 "n archive"
5752 " todo")
5753 " file: ") archive t)))
5754 (completions (unless file0 (todo-category-completions archive)))
5755 (categories (cond (file0
5756 (with-current-buffer
5757 (find-file-noselect file0 'nowarn)
5758 (unless (derived-mode-p 'todo-mode) (todo-mode))
5759 (let ((todo-current-todo-file file0))
5760 todo-categories)))
5761 ((and add (not file))
5762 (with-current-buffer
5763 (find-file-noselect todo-current-todo-file)
5764 todo-categories))
5766 completions)))
5767 (completion-ignore-case todo-completion-ignore-case)
5768 (cat (completing-read prompt categories nil
5769 (eq match-type 'todo) nil nil
5770 ;; Unless we're adding a category via
5771 ;; todo-add-category, set default
5772 ;; for existing categories to the
5773 ;; current category of the chosen
5774 ;; file or else of the current file.
5775 (if (and categories (not add))
5776 (with-current-buffer
5777 (find-file-noselect
5778 (or file0
5779 todo-current-todo-file
5780 (todo-absolute-file-name
5781 todo-default-todo-file)))
5782 (todo-current-category))
5783 ;; Trigger prompt for initial category.
5784 "")))
5785 (catfil (cdr (assoc cat completions)))
5786 (str "Category \"%s\" from which file (TAB for choices)? "))
5787 ;; If we do category completion and the chosen category name
5788 ;; occurs in more than one file, prompt to choose one file.
5789 (unless (or file0 add (not catfil))
5790 (setq file0 (file-truename
5791 (if (atom catfil)
5792 catfil
5793 (todo-absolute-file-name
5794 (let ((files (mapcar 'todo-short-file-name catfil)))
5795 (completing-read (format str cat) files)))))))
5796 ;; Default to the current file.
5797 (unless file0 (setq file0 todo-current-todo-file))
5798 ;; First validate only a name passed interactively from
5799 ;; todo-add-category, which must be of a nonexistent category.
5800 (unless (and (assoc cat categories) (not add))
5801 ;; Validate only against completion categories.
5802 (let ((todo-categories categories))
5803 (setq cat (todo-validate-name cat 'category)))
5804 ;; When user enters a nonexistent category name by jumping or
5805 ;; moving, confirm that it should be added, then validate.
5806 (unless add
5807 (if (todo-y-or-n-p (format "Add new category \"%s\" to file \"%s\"? "
5808 cat (todo-short-file-name file0)))
5809 (progn
5810 (when (assoc cat categories)
5811 (let ((todo-categories categories))
5812 (setq cat (todo-validate-name cat 'category))))
5813 ;; Restore point and narrowing after adding new
5814 ;; category, to avoid moving to beginning of file when
5815 ;; moving marked items to a new category
5816 ;; (todo-move-item).
5817 (save-excursion
5818 (save-restriction
5819 (todo-add-category file0 cat))))
5820 ;; If we decide not to add a category, exit without returning.
5821 (keyboard-quit))))
5822 (cons cat file0))))
5824 (defun todo-validate-name (name type)
5825 "Prompt for new NAME for TYPE until it is valid, then return it.
5826 TYPE can be either of the symbols `file' or `category'."
5827 (let ((categories todo-categories)
5828 (files (mapcar 'todo-short-file-name todo-files))
5829 prompt)
5830 (while
5831 (and
5832 (cond ((string= "" name)
5833 (setq prompt
5834 (cond ((eq type 'file)
5835 (if files
5836 "Enter a non-empty file name: "
5837 ;; Empty string passed by todo-show to
5838 ;; prompt for initial todo file.
5839 (concat "Initial file name ["
5840 todo-initial-file "]: ")))
5841 ((eq type 'category)
5842 (if categories
5843 "Enter a non-empty category name: "
5844 ;; Empty string passed by todo-show to
5845 ;; prompt for initial category of a new
5846 ;; todo file.
5847 (concat "Initial category name ["
5848 todo-initial-category "]: "))))))
5849 ((string-match "\\`\\s-+\\'" name)
5850 (setq prompt
5851 "Enter a name that does not contain only white space: "))
5852 ((and (eq type 'file) (member name files))
5853 (setq prompt "Enter a non-existing file name: "))
5854 ((and (eq type 'category) (assoc name categories))
5855 (setq prompt "Enter a non-existing category name: ")))
5856 (setq name (if (or (and (eq type 'file) files)
5857 (and (eq type 'category) categories))
5858 (completing-read prompt (cond ((eq type 'file)
5859 files)
5860 ((eq type 'category)
5861 categories)))
5862 ;; Offer default initial name.
5863 (completing-read prompt (if (eq type 'file)
5864 files
5865 categories)
5866 nil nil (if (eq type 'file)
5867 todo-initial-file
5868 todo-initial-category))))))
5869 name))
5871 ;; Adapted from calendar-read-date and calendar-date-string.
5872 (defun todo-read-date (&optional arg mo yr)
5873 "Prompt for Gregorian date and return it in the current format.
5875 With non-nil ARG, prompt for and return only the date component
5876 specified by ARG, which can be one of these symbols:
5877 `month' (prompt for name, return name or number according to
5878 value of `calendar-date-display-form'), `day' of month, or
5879 `year'. The value of each of these components can be `*',
5880 indicating an unspecified month, day, or year.
5882 When ARG is `day', non-nil arguments MO and YR determine the
5883 number of the last the day of the month."
5884 (let (year monthname month day
5885 dayname) ; Needed by calendar-date-display-form.
5886 (when (or (not arg) (eq arg 'year))
5887 (while (if (natnump year) (< year 1) (not (eq year '*)))
5888 (setq year (read-from-minibuffer
5889 "Year (>0 or RET for this year or * for any year): "
5890 nil nil t nil (number-to-string
5891 (calendar-extract-year
5892 (calendar-current-date)))))))
5893 (when (or (not arg) (eq arg 'month))
5894 (let* ((marray todo-month-name-array)
5895 (mlist (append marray nil))
5896 (mabarray todo-month-abbrev-array)
5897 (mablist (append mabarray nil))
5898 (completion-ignore-case todo-completion-ignore-case))
5899 (setq monthname (completing-read
5900 "Month name (RET for current month, * for any month): "
5901 mlist nil t nil nil
5902 (calendar-month-name (calendar-extract-month
5903 (calendar-current-date)) t))
5904 month (1+ (- (length mlist)
5905 (length (or (member monthname mlist)
5906 (member monthname mablist))))))
5907 (setq monthname (aref mabarray (1- month)))))
5908 (when (or (not arg) (eq arg 'day))
5909 (let ((last (let ((mm (or month mo))
5910 (yy (or year yr)))
5911 ;; If month is unspecified, use a month with 31
5912 ;; days for checking day of month input. Does
5913 ;; Calendar do anything special when * is
5914 ;; currently a shorter month?
5915 (if (= mm 13) (setq mm 1))
5916 ;; If year is unspecified, use a leap year to
5917 ;; allow Feb. 29.
5918 (if (eq year '*) (setq yy 2012))
5919 (calendar-last-day-of-month mm yy))))
5920 (while (if (natnump day) (or (< day 1) (> day last)) (not (eq day '*)))
5921 (setq day (read-from-minibuffer
5922 (format "Day (1-%d or RET for today or * for any day): "
5923 last)
5924 nil nil t nil (number-to-string
5925 (calendar-extract-day
5926 (calendar-current-date))))))))
5927 ;; Stringify read values (monthname is already a string).
5928 (and year (setq year (if (eq year '*)
5929 (symbol-name '*)
5930 (number-to-string year))))
5931 (and day (setq day (if (eq day '*)
5932 (symbol-name '*)
5933 (number-to-string day))))
5934 (and month (setq month (if (= month 13)
5935 (symbol-name '*)
5936 (number-to-string month))))
5937 (if arg
5938 (cond ((eq arg 'year) year)
5939 ((eq arg 'day) day)
5940 ((eq arg 'month)
5941 (if (memq 'month calendar-date-display-form)
5942 month
5943 monthname)))
5944 (mapconcat 'eval calendar-date-display-form ""))))
5946 (defun todo-read-dayname ()
5947 "Choose name of a day of the week with completion and return it."
5948 (let ((completion-ignore-case todo-completion-ignore-case))
5949 (completing-read "Enter a day name: "
5950 (append calendar-day-name-array nil)
5951 nil t)))
5953 (defun todo-read-time ()
5954 "Prompt for and return a valid clock time as a string.
5956 Valid time strings are those matching `diary-time-regexp'.
5957 Typing `<return>' at the prompt returns the current time, if the
5958 user option `todo-always-add-time-string' is non-nil, otherwise
5959 the empty string (i.e., no time string)."
5960 (let (valid answer)
5961 (while (not valid)
5962 (setq answer (read-string "Enter a clock time: " nil nil
5963 (when todo-always-add-time-string
5964 (substring (current-time-string) 11 16))))
5965 (when (or (string= "" answer)
5966 (string-match diary-time-regexp answer))
5967 (setq valid t)))
5968 answer))
5970 ;; -----------------------------------------------------------------------------
5971 ;;; Customization groups and utilities
5972 ;; -----------------------------------------------------------------------------
5974 (defgroup todo nil
5975 "Create and maintain categorized lists of todo items."
5976 :link '(emacs-commentary-link "todo")
5977 :version "24.4"
5978 :group 'calendar)
5980 (defgroup todo-edit nil
5981 "User options for adding and editing todo items."
5982 :version "24.4"
5983 :group 'todo)
5985 (defgroup todo-categories nil
5986 "User options for Todo Categories mode."
5987 :version "24.4"
5988 :group 'todo)
5990 (defgroup todo-filtered nil
5991 "User options for Todo Filter Items mode."
5992 :version "24.4"
5993 :group 'todo)
5995 (defgroup todo-display nil
5996 "User display options for Todo mode."
5997 :version "24.4"
5998 :group 'todo)
6000 (defgroup todo-faces nil
6001 "Faces for the Todo modes."
6002 :version "24.4"
6003 :group 'todo)
6005 (defun todo-set-show-current-file (symbol value)
6006 "The :set function for user option `todo-show-current-file'."
6007 (custom-set-default symbol value)
6008 (if value
6009 (add-hook 'pre-command-hook 'todo-show-current-file nil t)
6010 (remove-hook 'pre-command-hook 'todo-show-current-file t)))
6012 (defun todo-reset-prefix (symbol value)
6013 "The :set function for `todo-prefix' and `todo-number-prefix'."
6014 (let ((oldvalue (symbol-value symbol))
6015 (files todo-file-buffers))
6016 (custom-set-default symbol value)
6017 (when (not (equal value oldvalue))
6018 (dolist (f files)
6019 (with-current-buffer (find-file-noselect f)
6020 ;; Activate the new setting in the current category.
6021 (save-excursion (todo-category-select)))))))
6023 (defun todo-reset-nondiary-marker (symbol value)
6024 "The :set function for user option `todo-nondiary-marker'."
6025 (let* ((oldvalue (symbol-value symbol))
6026 (files (append todo-files todo-archives
6027 (directory-files todo-directory t "\\.tod[rty]$" t))))
6028 (custom-set-default symbol value)
6029 ;; Need to reset these to get font-locking right.
6030 (setq todo-nondiary-start (nth 0 todo-nondiary-marker)
6031 todo-nondiary-end (nth 1 todo-nondiary-marker)
6032 todo-date-string-start
6033 ;; See comment in defvar of `todo-date-string-start'.
6034 (concat "^\\(" (regexp-quote todo-nondiary-start) "\\|"
6035 (regexp-quote diary-nonmarking-symbol) "\\)?"))
6036 (when (not (equal value oldvalue))
6037 (dolist (f files)
6038 (let ((buf (find-buffer-visiting f)))
6039 (with-current-buffer (find-file-noselect f)
6040 (let (buffer-read-only)
6041 (widen)
6042 (goto-char (point-min))
6043 (while (not (eobp))
6044 (if (re-search-forward
6045 (concat "^\\(" todo-done-string-start "[^][]+] \\)?"
6046 "\\(?1:" (regexp-quote (car oldvalue))
6047 "\\)" todo-date-pattern "\\( "
6048 diary-time-regexp "\\)?\\(?2:"
6049 (regexp-quote (cadr oldvalue)) "\\)")
6050 nil t)
6051 (progn
6052 (replace-match (nth 0 value) t t nil 1)
6053 (replace-match (nth 1 value) t t nil 2))
6054 (forward-line)))
6055 (if buf
6056 (when (derived-mode-p 'todo-mode 'todo-archive-mode)
6057 (todo-category-select))
6058 (save-buffer)
6059 (kill-buffer)))))))))
6061 (defun todo-reset-done-separator-string (symbol value)
6062 "The :set function for `todo-done-separator-string'."
6063 (let ((oldvalue (symbol-value symbol))
6064 (files todo-file-buffers)
6065 (sep todo-done-separator))
6066 (custom-set-default symbol value)
6067 (when (not (equal value oldvalue))
6068 (dolist (f files)
6069 (with-current-buffer (find-file-noselect f)
6070 (let (buffer-read-only)
6071 (setq todo-done-separator (todo-done-separator))
6072 (when (= 1 (length value))
6073 (todo-reset-done-separator sep)))
6074 (todo-category-select))))))
6076 (defun todo-reset-done-string (symbol value)
6077 "The :set function for user option `todo-done-string'."
6078 (let ((oldvalue (symbol-value symbol))
6079 (files (append todo-files todo-archives
6080 (directory-files todo-directory t "\\.todr$" t))))
6081 (custom-set-default symbol value)
6082 ;; Need to reset this to get font-locking right.
6083 (setq todo-done-string-start
6084 (concat "^\\[" (regexp-quote todo-done-string)))
6085 (when (not (equal value oldvalue))
6086 (dolist (f files)
6087 (let ((buf (find-buffer-visiting f)))
6088 (with-current-buffer (find-file-noselect f)
6089 (let (buffer-read-only)
6090 (widen)
6091 (goto-char (point-min))
6092 (while (not (eobp))
6093 (if (re-search-forward
6094 (concat "^" (regexp-quote todo-nondiary-start)
6095 "\\(" (regexp-quote oldvalue) "\\)")
6096 nil t)
6097 (replace-match value t t nil 1)
6098 (forward-line)))
6099 (if buf
6100 (when (derived-mode-p 'todo-mode 'todo-archive-mode)
6101 (todo-category-select))
6102 (save-buffer)
6103 (kill-buffer)))))))))
6105 (defun todo-reset-comment-string (symbol value)
6106 "The :set function for user option `todo-comment-string'."
6107 (let ((oldvalue (symbol-value symbol))
6108 (files (append todo-files todo-archives
6109 (directory-files todo-directory t "\\.todr$" t))))
6110 (custom-set-default symbol value)
6111 (when (not (equal value oldvalue))
6112 (dolist (f files)
6113 (let ((buf (find-buffer-visiting f)))
6114 (with-current-buffer (find-file-noselect f)
6115 (let (buffer-read-only)
6116 (widen)
6117 (goto-char (point-min))
6118 (while (not (eobp))
6119 (if (re-search-forward
6120 (concat "\\[\\(" (regexp-quote oldvalue)
6121 "\\): [^]]*\\]")
6122 nil t)
6123 (replace-match value t t nil 1)
6124 (forward-line)))
6125 (if buf
6126 (when (derived-mode-p 'todo-mode 'todo-archive-mode)
6127 (todo-category-select))
6128 (save-buffer)
6129 (kill-buffer)))))))))
6131 (defun todo-reset-highlight-item (symbol value)
6132 "The :set function for user option `todo-highlight-item'."
6133 (let ((oldvalue (symbol-value symbol))
6134 (files (append todo-files todo-archives
6135 (directory-files todo-directory t "\\.tod[rty]$" t))))
6136 (custom-set-default symbol value)
6137 (when (not (equal value oldvalue))
6138 (dolist (f files)
6139 (let ((buf (find-buffer-visiting f)))
6140 (when buf
6141 (with-current-buffer buf
6142 (require 'hl-line)
6143 (if value
6144 (hl-line-mode 1)
6145 (hl-line-mode -1)))))))))
6147 (defun todo-reevaluate-filelist-defcustoms ()
6148 "Reevaluate defcustoms that provide choice list of todo files."
6149 (custom-set-default 'todo-default-todo-file
6150 (symbol-value 'todo-default-todo-file))
6151 (todo-reevaluate-default-file-defcustom)
6152 (custom-set-default 'todo-filter-files (symbol-value 'todo-filter-files))
6153 (todo-reevaluate-filter-files-defcustom)
6154 (custom-set-default 'todo-category-completions-files
6155 (symbol-value 'todo-category-completions-files))
6156 (todo-reevaluate-category-completions-files-defcustom))
6158 (defun todo-reevaluate-default-file-defcustom ()
6159 "Reevaluate defcustom of `todo-default-todo-file'.
6160 Called after adding or deleting a todo file. If the value of
6161 `todo-default-todo-file' before calling this function was
6162 associated with an existing file, keep that value."
6163 ;; (let ((curval todo-default-todo-file))
6164 (eval
6165 (defcustom todo-default-todo-file (todo-short-file-name
6166 (car (funcall todo-files-function)))
6167 "Todo file visited by first session invocation of `todo-show'."
6168 :type (when todo-files
6169 `(radio ,@(mapcar (lambda (f) (list 'const f))
6170 (mapcar 'todo-short-file-name
6171 (funcall todo-files-function)))))
6172 :group 'todo))
6173 ;; (when (and curval (file-exists-p (todo-absolute-file-name curval)))
6174 ;; (custom-set-default 'todo-default-todo-file curval)
6175 ;; ;; (custom-reevaluate-setting 'todo-default-todo-file)
6176 ;; )))
6179 (defun todo-reevaluate-category-completions-files-defcustom ()
6180 "Reevaluate defcustom of `todo-category-completions-files'.
6181 Called after adding or deleting a todo file."
6182 (eval (defcustom todo-category-completions-files nil
6183 "List of files for building `todo-read-category' completions."
6184 :type `(set ,@(mapcar (lambda (f) (list 'const f))
6185 (mapcar 'todo-short-file-name
6186 (funcall todo-files-function))))
6187 :group 'todo)))
6189 (defun todo-reevaluate-filter-files-defcustom ()
6190 "Reevaluate defcustom of `todo-filter-files'.
6191 Called after adding or deleting a todo file."
6192 (eval (defcustom todo-filter-files nil
6193 "List of files for multifile item filtering."
6194 :type `(set ,@(mapcar (lambda (f) (list 'const f))
6195 (mapcar 'todo-short-file-name
6196 (funcall todo-files-function))))
6197 :group 'todo)))
6199 ;; -----------------------------------------------------------------------------
6200 ;;; Font locking
6201 ;; -----------------------------------------------------------------------------
6203 (defun todo-nondiary-marker-matcher (lim)
6204 "Search for todo item nondiary markers within LIM for font-locking."
6205 (re-search-forward (concat "^\\(?1:" (regexp-quote todo-nondiary-start) "\\)"
6206 todo-date-pattern "\\(?: " diary-time-regexp
6207 "\\)?\\(?2:" (regexp-quote todo-nondiary-end) "\\)")
6208 lim t))
6210 (defun todo-diary-nonmarking-matcher (lim)
6211 "Search for diary nonmarking symbol within LIM for font-locking."
6212 (re-search-forward (concat "^\\(?1:" (regexp-quote diary-nonmarking-symbol)
6213 "\\)" todo-date-pattern) lim t))
6215 (defun todo-date-string-matcher (lim)
6216 "Search for todo item date string within LIM for font-locking."
6217 (re-search-forward
6218 (concat todo-date-string-start "\\(?1:" todo-date-pattern "\\)") lim t))
6220 (defun todo-time-string-matcher (lim)
6221 "Search for todo item time string within LIM for font-locking."
6222 (re-search-forward (concat todo-date-string-start todo-date-pattern
6223 " \\(?1:" diary-time-regexp "\\)") lim t))
6225 (defun todo-diary-expired-matcher (lim)
6226 "Search for expired diary item date within LIM for font-locking."
6227 (when (re-search-forward (concat "^\\(?:"
6228 (regexp-quote diary-nonmarking-symbol)
6229 "\\)?\\(?1:" todo-date-pattern "\\) \\(?2:"
6230 diary-time-regexp "\\)?") lim t)
6231 (let* ((date (match-string-no-properties 1))
6232 (time (match-string-no-properties 2))
6233 ;; Function days-between requires a non-empty time string.
6234 (date-time (concat date " " (or time "00:00"))))
6235 (or (and (not (string-match ".+day\\|\\*" date))
6236 (< (days-between date-time (current-time-string)) 0))
6237 (todo-diary-expired-matcher lim)))))
6239 (defun todo-done-string-matcher (lim)
6240 "Search for done todo item header within LIM for font-locking."
6241 (re-search-forward (concat todo-done-string-start
6242 "[^][]+]")
6243 lim t))
6245 (defun todo-comment-string-matcher (lim)
6246 "Search for done todo item comment within LIM for font-locking."
6247 (re-search-forward (concat "\\[\\(?1:" todo-comment-string "\\):")
6248 lim t))
6250 (defun todo-category-string-matcher-1 (lim)
6251 "Search for todo category name within LIM for font-locking.
6252 This is for fontifying category and file names appearing in Todo
6253 Filtered Items mode following done items."
6254 (if (eq major-mode 'todo-filtered-items-mode)
6255 (re-search-forward (concat todo-done-string-start todo-date-pattern
6256 "\\(?: " diary-time-regexp
6257 ;; Use non-greedy operator to prevent
6258 ;; capturing possible following non-diary
6259 ;; date string.
6260 "\\)?] \\(?1:\\[.+?\\]\\)")
6261 lim t)))
6263 (defun todo-category-string-matcher-2 (lim)
6264 "Search for todo category name within LIM for font-locking.
6265 This is for fontifying category and file names appearing in Todo
6266 Filtered Items mode following todo (not done) items."
6267 (if (eq major-mode 'todo-filtered-items-mode)
6268 (re-search-forward (concat todo-date-string-start todo-date-pattern
6269 "\\(?: " diary-time-regexp "\\)?\\(?:"
6270 (regexp-quote todo-nondiary-end)
6271 "\\)? \\(?1:\\[.+\\]\\)")
6272 lim t)))
6274 (defvar todo-nondiary-face 'todo-nondiary)
6275 (defvar todo-date-face 'todo-date)
6276 (defvar todo-time-face 'todo-time)
6277 (defvar todo-diary-expired-face 'todo-diary-expired)
6278 (defvar todo-done-sep-face 'todo-done-sep)
6279 (defvar todo-done-face 'todo-done)
6280 (defvar todo-comment-face 'todo-comment)
6281 (defvar todo-category-string-face 'todo-category-string)
6282 (defvar todo-font-lock-keywords
6283 (list
6284 '(todo-nondiary-marker-matcher 1 todo-nondiary-face t)
6285 '(todo-nondiary-marker-matcher 2 todo-nondiary-face t)
6286 ;; diary-lib.el uses font-lock-constant-face for diary-nonmarking-symbol.
6287 '(todo-diary-nonmarking-matcher 1 font-lock-constant-face t)
6288 '(todo-date-string-matcher 1 todo-date-face t)
6289 '(todo-time-string-matcher 1 todo-time-face t)
6290 '(todo-done-string-matcher 0 todo-done-face t)
6291 '(todo-comment-string-matcher 1 todo-comment-face t)
6292 '(todo-category-string-matcher-1 1 todo-category-string-face t t)
6293 '(todo-category-string-matcher-2 1 todo-category-string-face t t)
6294 '(todo-diary-expired-matcher 1 todo-diary-expired-face t)
6295 '(todo-diary-expired-matcher 2 todo-diary-expired-face t t)
6297 "Font-locking for Todo modes.")
6299 ;; -----------------------------------------------------------------------------
6300 ;;; Key binding
6301 ;; -----------------------------------------------------------------------------
6303 (defvar todo-key-bindings-t
6305 ("Af" todo-find-archive)
6306 ("Ac" todo-choose-archive)
6307 ("Ad" todo-archive-done-item)
6308 ("Cv" todo-toggle-view-done-items)
6309 ("v" todo-toggle-view-done-items)
6310 ("Ca" todo-add-category)
6311 ("Cr" todo-rename-category)
6312 ("Cg" todo-merge-category)
6313 ("Cm" todo-move-category)
6314 ("Ck" todo-delete-category)
6315 ("Cts" todo-set-top-priorities-in-category)
6316 ("Cey" todo-edit-category-diary-inclusion)
6317 ("Cek" todo-edit-category-diary-nonmarking)
6318 ("Fa" todo-add-file)
6319 ("Fr" todo-rename-file)
6320 ("Ff" todo-find-filtered-items-file)
6321 ("FV" todo-toggle-view-done-only)
6322 ("V" todo-toggle-view-done-only)
6323 ("Ftt" todo-filter-top-priorities)
6324 ("Ftm" todo-filter-top-priorities-multifile)
6325 ("Fts" todo-set-top-priorities-in-file)
6326 ("Fyy" todo-filter-diary-items)
6327 ("Fym" todo-filter-diary-items-multifile)
6328 ("Fxx" todo-filter-regexp-items)
6329 ("Fxm" todo-filter-regexp-items-multifile)
6330 ("e" todo-edit-item)
6331 ("d" todo-item-done)
6332 ("i" todo-insert-item)
6333 ("k" todo-delete-item)
6334 ("m" todo-move-item)
6335 ("u" todo-item-undone)
6336 ([remap newline] newline-and-indent)
6338 "List of key bindings for Todo mode only.")
6340 (defvar todo-key-bindings-t+a+f
6342 ("C*" todo-mark-category)
6343 ("Cu" todo-unmark-category)
6344 ("Fh" todo-toggle-item-header)
6345 ("h" todo-toggle-item-header)
6346 ("Fk" todo-delete-file)
6347 ("Fe" todo-edit-file)
6348 ("FH" todo-toggle-item-highlighting)
6349 ("H" todo-toggle-item-highlighting)
6350 ("FN" todo-toggle-prefix-numbers)
6351 ("N" todo-toggle-prefix-numbers)
6352 ("PB" todo-print-buffer)
6353 ("PF" todo-print-buffer-to-file)
6354 ("b" todo-backward-category)
6355 ("d" todo-item-done)
6356 ("f" todo-forward-category)
6357 ("j" todo-jump-to-category)
6358 ("n" todo-next-item)
6359 ("p" todo-previous-item)
6360 ("q" todo-quit)
6361 ("s" todo-save)
6362 ("t" todo-show)
6364 "List of key bindings for Todo, Archive, and Filtered Items modes.")
6366 (defvar todo-key-bindings-t+a
6368 ("Fc" todo-show-categories-table)
6369 ("S" todo-search)
6370 ("X" todo-clear-matches)
6371 ("*" todo-toggle-mark-item)
6373 "List of key bindings for Todo and Todo Archive modes.")
6375 (defvar todo-key-bindings-t+f
6377 ("l" todo-lower-item-priority)
6378 ("r" todo-raise-item-priority)
6379 ("#" todo-set-item-priority)
6381 "List of key bindings for Todo and Todo Filtered Items modes.")
6383 (defvar todo-mode-map
6384 (let ((map (make-keymap)))
6385 ;; Don't suppress digit keys, so they can supply prefix arguments.
6386 (suppress-keymap map)
6387 (dolist (kb todo-key-bindings-t)
6388 (define-key map (nth 0 kb) (nth 1 kb)))
6389 (dolist (kb todo-key-bindings-t+a+f)
6390 (define-key map (nth 0 kb) (nth 1 kb)))
6391 (dolist (kb todo-key-bindings-t+a)
6392 (define-key map (nth 0 kb) (nth 1 kb)))
6393 (dolist (kb todo-key-bindings-t+f)
6394 (define-key map (nth 0 kb) (nth 1 kb)))
6395 map)
6396 "Todo mode keymap.")
6398 (defvar todo-archive-mode-map
6399 (let ((map (make-sparse-keymap)))
6400 (suppress-keymap map)
6401 (dolist (kb todo-key-bindings-t+a+f)
6402 (define-key map (nth 0 kb) (nth 1 kb)))
6403 (dolist (kb todo-key-bindings-t+a)
6404 (define-key map (nth 0 kb) (nth 1 kb)))
6405 (define-key map "a" 'todo-jump-to-archive-category)
6406 (define-key map "u" 'todo-unarchive-items)
6407 map)
6408 "Todo Archive mode keymap.")
6410 (defvar todo-edit-mode-map
6411 (let ((map (make-sparse-keymap)))
6412 (define-key map "\C-x\C-q" 'todo-edit-quit)
6413 (define-key map [remap newline] 'newline-and-indent)
6414 map)
6415 "Todo Edit mode keymap.")
6417 (defvar todo-categories-mode-map
6418 (let ((map (make-sparse-keymap)))
6419 (suppress-keymap map)
6420 (define-key map "c" 'todo-sort-categories-alphabetically-or-numerically)
6421 (define-key map "t" 'todo-sort-categories-by-todo)
6422 (define-key map "y" 'todo-sort-categories-by-diary)
6423 (define-key map "d" 'todo-sort-categories-by-done)
6424 (define-key map "a" 'todo-sort-categories-by-archived)
6425 (define-key map "#" 'todo-set-category-number)
6426 (define-key map "l" 'todo-lower-category)
6427 (define-key map "r" 'todo-raise-category)
6428 (define-key map "n" 'todo-next-button)
6429 (define-key map "p" 'todo-previous-button)
6430 (define-key map [tab] 'todo-next-button)
6431 (define-key map [backtab] 'todo-previous-button)
6432 (define-key map "q" 'todo-quit)
6433 map)
6434 "Todo Categories mode keymap.")
6436 (defvar todo-filtered-items-mode-map
6437 (let ((map (make-sparse-keymap)))
6438 (suppress-keymap map)
6439 (dolist (kb todo-key-bindings-t+a+f)
6440 (define-key map (nth 0 kb) (nth 1 kb)))
6441 (dolist (kb todo-key-bindings-t+f)
6442 (define-key map (nth 0 kb) (nth 1 kb)))
6443 (define-key map "g" 'todo-go-to-source-item)
6444 (define-key map [remap newline] 'todo-go-to-source-item)
6445 map)
6446 "Todo Filtered Items mode keymap.")
6448 (easy-menu-define
6449 todo-menu todo-mode-map "Todo Menu"
6450 '("Todo"
6451 ("Navigation"
6452 ["Next Item" todo-next-item t]
6453 ["Previous Item" todo-previous-item t]
6454 "---"
6455 ["Next Category" todo-forward-category t]
6456 ["Previous Category" todo-backward-category t]
6457 ["Jump to Another Category" todo-jump-to-category t]
6458 "---"
6459 ["Visit Another Todo File" todo-show t]
6460 ["Visit Archive" todo-find-archive t]
6461 ["Visit Filtered Items File" todo-find-filtered-items-file t]
6463 ("Editing"
6464 ["Insert New Item" todo-insert-item t]
6465 ["Edit Item" todo-edit-item t]
6466 ["Lower Item Priority" todo-lower-item-priority t]
6467 ["Raise Item Priority" todo-raise-item-priority t]
6468 ["Set Item Priority" todo-set-item-priority t]
6469 ["Mark/Unmark Item" todo-toggle-mark-item t]
6470 ["Move (Recategorize) Item" todo-move-item t]
6471 ["Delete Item" todo-delete-item t]
6472 ["Mark and Bury Done Item" todo-item-done t]
6473 ["Undo Done Item" todo-item-undone t]
6474 ["Archive Done Item" todo-archive-done-item t]
6475 "---"
6476 ["Add New Category" todo-add-category t]
6477 ["Rename Current Category" todo-rename-category t]
6478 ["Delete Current Category" todo-delete-category t]
6479 ["Move Current Category" todo-move-category t]
6480 ["Merge Current Category" todo-merge-category t]
6481 "---"
6482 ["Add New Todo File" todo-add-file t]
6483 ["Rename Todo File" todo-rename-file t]
6484 ["Delete Todo File" todo-delete-file t]
6485 ["Edit Todo File" todo-edit-file t]
6487 ("Searching and Item Filtering"
6488 ["Search Todo File" todo-search t]
6489 ["Clear Match Highlighting" todo-clear-matches t]
6490 "---"
6491 ["Set Top Priorities in File" todo-set-top-priorities-in-file t]
6492 ["Set Top Priorities in Category" todo-set-top-priorities-in-category t]
6493 ["Filter Top Priorities" todo-filter-top-priorities t]
6494 ["Filter Multifile Top Priorities" todo-filter-top-priorities-multifile t]
6495 ["Filter Diary Items" todo-filter-diary-items t]
6496 ["Filter Multifile Diary Items" todo-filter-diary-items-multifile t]
6497 ["Filter Regexp" todo-filter-regexp-items t]
6498 ["Filter Multifile Regexp" todo-filter-regexp-items-multifile t]
6500 ("Display and Printing"
6501 ["Show/Hide Done Items" todo-toggle-view-done-items t]
6502 ["Show/Hide Done Items Only" todo-toggle-view-done-only t]
6503 ["Show/Hide Item Highlighting" todo-toggle-item-highlighting t]
6504 ["Show/Hide Item Numbering" todo-toggle-prefix-numbers t]
6505 ["Show/Hide Item Header" todo-toggle-item-header t]
6506 "---"
6507 ["Display Table of Categories" todo-show-categories-table t]
6508 "---"
6509 ["Print Category" todo-print-buffer t]
6510 ["Print Category to File" todo-print-buffer-to-file t]
6512 "---"
6513 ["Save Todo File" todo-save t]
6514 ["Quit Todo Mode" todo-quit t]
6517 ;; -----------------------------------------------------------------------------
6518 ;;; Hook functions and mode definitions
6519 ;; -----------------------------------------------------------------------------
6521 (defun todo-show-current-file ()
6522 "Visit current instead of default todo file with `todo-show'.
6523 Added to `pre-command-hook' in Todo mode when user option
6524 `todo-show-current-file' is set to non-nil."
6525 (setq todo-global-current-todo-file todo-current-todo-file))
6527 ;; (defun todo-display-as-todo-file ()
6528 ;; "Show todo files correctly when visited from outside of Todo mode.
6529 ;; Added to `find-file-hook' in Todo mode and Todo Archive mode."
6530 ;; (and (member this-command todo-visit-files-commands)
6531 ;; (= (- (point-max) (point-min)) (buffer-size))
6532 ;; (member major-mode '(todo-mode todo-archive-mode))
6533 ;; (todo-category-select)))
6535 ;; (defun todo-add-to-buffer-list ()
6536 ;; "Add name of just visited todo file to `todo-file-buffers'.
6537 ;; This function is added to `find-file-hook' in Todo mode."
6538 ;; (let ((filename (file-truename (buffer-file-name))))
6539 ;; (when (member filename todo-files)
6540 ;; (add-to-list 'todo-file-buffers filename))))
6542 (defun todo-update-buffer-list ()
6543 "Make current Todo mode buffer file car of `todo-file-buffers'.
6544 This function is added to `post-command-hook' in Todo mode."
6545 (let ((filename (file-truename (buffer-file-name))))
6546 (unless (eq (car todo-file-buffers) filename)
6547 (setq todo-file-buffers
6548 (cons filename (delete filename todo-file-buffers))))))
6550 (defun todo-reset-global-current-todo-file ()
6551 "Update the value of `todo-global-current-todo-file'.
6552 This becomes the latest existing todo file or, if there is none,
6553 the value of `todo-default-todo-file'.
6554 This function is added to `kill-buffer-hook' in Todo mode."
6555 (let ((filename (file-truename (buffer-file-name))))
6556 (setq todo-file-buffers (delete filename todo-file-buffers))
6557 (setq todo-global-current-todo-file
6558 (or (car todo-file-buffers)
6559 (todo-absolute-file-name todo-default-todo-file)))))
6561 (defun todo-reset-and-enable-done-separator ()
6562 "Show resized done items separator overlay after window change.
6563 Added to `window-configuration-change-hook' in Todo mode."
6564 (when (= 1 (length todo-done-separator-string))
6565 (let ((sep todo-done-separator))
6566 (setq todo-done-separator (todo-done-separator))
6567 (save-match-data (todo-reset-done-separator sep)))))
6569 (defun todo-modes-set-1 ()
6570 "Make some settings that apply to multiple Todo modes."
6571 (setq-local font-lock-defaults '(todo-font-lock-keywords t))
6572 (setq-local revert-buffer-function 'todo-revert-buffer)
6573 (setq-local tab-width todo-indent-to-here)
6574 (setq-local indent-line-function 'todo-indent)
6575 (when todo-wrap-lines
6576 (visual-line-mode)
6577 (setq wrap-prefix (make-string todo-indent-to-here 32))))
6579 (defun todo-modes-set-2 ()
6580 "Make some settings that apply to multiple Todo modes."
6581 (add-to-invisibility-spec 'todo)
6582 (setq buffer-read-only t)
6583 (setq-local desktop-save-buffer 'todo-desktop-save-buffer)
6584 (when (boundp 'hl-line-range-function)
6585 (setq-local hl-line-range-function
6586 (lambda() (save-excursion
6587 (when (todo-item-end)
6588 (cons (todo-item-start)
6589 (todo-item-end))))))))
6591 (defun todo-modes-set-3 ()
6592 "Make some settings that apply to multiple Todo modes."
6593 (setq-local todo-categories (todo-set-categories))
6594 (setq-local todo-category-number 1)
6595 ;; (add-hook 'find-file-hook 'todo-display-as-todo-file nil t)
6598 (put 'todo-mode 'mode-class 'special)
6600 ;;;###autoload
6601 (define-derived-mode todo-mode special-mode "Todo"
6602 "Major mode for displaying, navigating and editing todo lists.
6604 \\{todo-mode-map}"
6605 (if (called-interactively-p 'any)
6606 (message "%s"
6607 (substitute-command-keys
6608 "Type `\\[todo-show]' to enter Todo mode"))
6609 (todo-modes-set-1)
6610 (todo-modes-set-2)
6611 (todo-modes-set-3)
6612 ;; Initialize todo-current-todo-file.
6613 (when (member (file-truename (buffer-file-name))
6614 (funcall todo-files-function))
6615 (setq-local todo-current-todo-file (file-truename (buffer-file-name))))
6616 (setq-local todo-show-done-only nil)
6617 (setq-local todo-categories-with-marks nil)
6618 ;; (add-hook 'find-file-hook 'todo-add-to-buffer-list nil t)
6619 (add-hook 'post-command-hook 'todo-update-buffer-list nil t)
6620 (when todo-show-current-file
6621 (add-hook 'pre-command-hook 'todo-show-current-file nil t))
6622 (add-hook 'window-configuration-change-hook
6623 'todo-reset-and-enable-done-separator nil t)
6624 (add-hook 'kill-buffer-hook 'todo-reset-global-current-todo-file nil t)))
6626 (put 'todo-archive-mode 'mode-class 'special)
6628 ;; If todo-mode is parent, all todo-mode key bindings appear to be
6629 ;; available in todo-archive-mode (e.g. shown by C-h m).
6630 ;;;###autoload
6631 (define-derived-mode todo-archive-mode special-mode "Todo-Arch"
6632 "Major mode for archived todo categories.
6634 \\{todo-archive-mode-map}"
6635 (todo-modes-set-1)
6636 (todo-modes-set-2)
6637 (todo-modes-set-3)
6638 (setq-local todo-current-todo-file (file-truename (buffer-file-name)))
6639 (setq-local todo-show-done-only t))
6641 (defun todo-mode-external-set ()
6642 "Set `todo-categories' externally to `todo-current-todo-file'."
6643 (setq-local todo-current-todo-file todo-global-current-todo-file)
6644 (let ((cats (with-current-buffer
6645 ;; Can't use find-buffer-visiting when
6646 ;; `todo-show-categories-table' is called on first
6647 ;; invocation of `todo-show', since there is then
6648 ;; no buffer visiting the current file.
6649 (find-file-noselect todo-current-todo-file 'nowarn)
6650 (or todo-categories
6651 ;; In Todo Edit mode todo-categories is now nil
6652 ;; since it uses same buffer as Todo mode but
6653 ;; doesn't have the latter's local variables.
6654 (save-excursion
6655 (goto-char (point-min))
6656 (read (buffer-substring-no-properties
6657 (line-beginning-position)
6658 (line-end-position))))))))
6659 (setq-local todo-categories cats)))
6661 (define-derived-mode todo-edit-mode text-mode "Todo-Ed"
6662 "Major mode for editing multiline todo items.
6664 \\{todo-edit-mode-map}"
6665 (todo-modes-set-1)
6666 (todo-mode-external-set)
6667 (setq buffer-read-only nil))
6669 (put 'todo-categories-mode 'mode-class 'special)
6671 (define-derived-mode todo-categories-mode special-mode "Todo-Cats"
6672 "Major mode for displaying and editing todo categories.
6674 \\{todo-categories-mode-map}"
6675 (todo-mode-external-set))
6677 (put 'todo-filtered-items-mode 'mode-class 'special)
6679 ;;;###autoload
6680 (define-derived-mode todo-filtered-items-mode special-mode "Todo-Fltr"
6681 "Mode for displaying and reprioritizing top priority Todo.
6683 \\{todo-filtered-items-mode-map}"
6684 (todo-modes-set-1)
6685 (todo-modes-set-2))
6687 ;; -----------------------------------------------------------------------------
6688 (provide 'todo-mode)
6690 ;;; todo-mode.el ends here