Use PAT rather than UPAT in pcase macros
[emacs.git] / lisp / calendar / todo-mode.el
blob83f2fedf25b688c5925beafefd0873d71369f201
1 ;;; todo-mode.el --- facilities for making and maintaining todo lists
3 ;; Copyright (C) 1997, 1999, 2001-2015 Free Software Foundation, Inc.
5 ;; Author: Oliver Seidel <privat@os10000.net>
6 ;; Stephen Berman <stephen.berman@gmx.net>
7 ;; Maintainer: Stephen Berman <stephen.berman@gmx.net>
8 ;; Keywords: calendar, todo
10 ;; This file is part of GNU Emacs.
12 ;; GNU Emacs is free software: you can redistribute it and/or modify
13 ;; it under the terms of the GNU General Public License as published by
14 ;; the Free Software Foundation, either version 3 of the License, or
15 ;; (at your option) any later version.
17 ;; GNU Emacs is distributed in the hope that it will be useful,
18 ;; but WITHOUT ANY WARRANTY; without even the implied warranty of
19 ;; MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
20 ;; GNU General Public License for more details.
22 ;; You should have received a copy of the GNU General Public License
23 ;; along with GNU Emacs. If not, see <http://www.gnu.org/licenses/>.
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 (concat "This category has archived items; "
1347 "the archived category will remain\n"
1348 "after deleting the todo category. "
1349 "Do you still want to delete it\n"
1350 "(see ‘todo-skip-archived-categories’ "
1351 "for another option)? ")))
1353 (todo-y-or-n-p (concat "Permanently remove category \"" cat
1354 "\"" (and arg " and all its entries")
1355 "? "))))
1356 (widen)
1357 (let ((buffer-read-only)
1358 (beg (re-search-backward
1359 (concat "^" (regexp-quote (concat todo-category-beg cat))
1360 "\n") nil t))
1361 (end (if (re-search-forward
1362 (concat "\n\\(" (regexp-quote todo-category-beg)
1363 ".*\n\\)") nil t)
1364 (match-beginning 1)
1365 (point-max))))
1366 (remove-overlays beg end)
1367 (delete-region beg end)
1368 (if (= (length todo-categories) 1)
1369 ;; If deleted category was the only one, delete the file.
1370 (progn
1371 (todo-reevaluate-filelist-defcustoms)
1372 ;; Skip confirming killing the archive buffer if it has been
1373 ;; modified and not saved.
1374 (set-buffer-modified-p nil)
1375 (delete-file file)
1376 (kill-buffer)
1377 (message "Deleted todo file %s." file))
1378 (setq todo-categories (delete (assoc cat todo-categories)
1379 todo-categories))
1380 (todo-update-categories-sexp)
1381 (setq todo-category-number
1382 (1+ (mod todo-category-number (length todo-categories))))
1383 (todo-category-select)
1384 (goto-char (point-min))
1385 (message "Deleted category %s." cat)))))))
1387 (defun todo-move-category ()
1388 "Move current category to a different todo file.
1389 If the todo file chosen does not exist, it is created.
1390 If the current category has archived items, also move those to
1391 the archive of the file moved to, creating it if it does not exist."
1392 (interactive)
1393 (when (or (> (length todo-categories) 1)
1394 (todo-y-or-n-p (concat "This is the only category in this file; "
1395 "moving it will also delete the file.\n"
1396 "Do you want to proceed? ")))
1397 (let* ((ofile todo-current-todo-file)
1398 (cat (todo-current-category))
1399 (nfile (todo-read-file-name "Todo file to move this category to: "))
1400 (archive (concat (file-name-sans-extension ofile) ".toda"))
1401 (buffers (append (list ofile)
1402 (unless (zerop (todo-get-count 'archived cat))
1403 (list archive))))
1404 new)
1405 (while (equal nfile (file-truename ofile))
1406 (setq nfile (todo-read-file-name
1407 "Choose a file distinct from this file: ")))
1408 (unless (member nfile todo-files)
1409 (with-current-buffer (get-buffer-create nfile)
1410 (erase-buffer)
1411 (write-region (point-min) (point-max) nfile nil 'nomessage nil t)
1412 (kill-buffer nfile))
1413 (setq todo-files (funcall todo-files-function))
1414 (todo-reevaluate-filelist-defcustoms))
1415 (dolist (buf buffers)
1416 (with-current-buffer (find-file-noselect buf)
1417 (widen)
1418 (goto-char (point-max))
1419 (let* ((beg (re-search-backward
1420 (concat "^"
1421 (regexp-quote (concat todo-category-beg cat))
1422 "$")
1423 nil t))
1424 (end (if (re-search-forward
1425 (concat "^" (regexp-quote todo-category-beg))
1426 nil t 2)
1427 (match-beginning 0)
1428 (point-max)))
1429 (content (buffer-substring-no-properties beg end))
1430 (counts (cdr (assoc cat todo-categories)))
1431 buffer-read-only)
1432 ;; Move the category to the new file. Also update or create
1433 ;; archive file if necessary.
1434 (with-current-buffer
1435 (find-file-noselect
1436 ;; Regenerate todo-archives in case there
1437 ;; is a newly created archive.
1438 (if (member buf (funcall todo-files-function t))
1439 (concat (file-name-sans-extension nfile) ".toda")
1440 nfile))
1441 (if (equal (file-name-extension (buffer-file-name)) "toda")
1442 (unless (derived-mode-p 'todo-archive-mode)
1443 (todo-archive-mode))
1444 (unless (derived-mode-p 'todo-mode) (todo-mode)))
1445 (let* ((nfile-short (todo-short-file-name nfile))
1446 (prompt (concat
1447 (format "Todo file \"%s\" already has "
1448 nfile-short)
1449 (format "the category \"%s\";\n" cat)
1450 "enter a new category name: "))
1451 buffer-read-only)
1452 (widen)
1453 (goto-char (point-max))
1454 (insert content)
1455 ;; If the file moved to has a category with the same
1456 ;; name, rename the moved category.
1457 (when (assoc cat todo-categories)
1458 (unless (member (file-truename (buffer-file-name))
1459 (funcall todo-files-function t))
1460 (setq new (read-from-minibuffer prompt))
1461 (setq new (todo-validate-name new 'category))))
1462 ;; Replace old with new name in todo and archive files.
1463 (when new
1464 (goto-char (point-max))
1465 (re-search-backward
1466 (concat "^" (regexp-quote todo-category-beg)
1467 "\\(" (regexp-quote cat) "\\)$") nil t)
1468 (replace-match new nil nil nil 1)))
1469 (setq todo-categories
1470 (append todo-categories (list (cons (or new cat) counts))))
1471 (todo-update-categories-sexp)
1472 ;; If archive was just created, save it to avoid "File
1473 ;; <xyz> no longer exists!" message on invoking
1474 ;; `todo-view-archived-items'.
1475 (unless (file-exists-p (buffer-file-name))
1476 (save-buffer))
1477 (todo-category-number (or new cat))
1478 (todo-category-select))
1479 ;; Delete the category from the old file, and if that was the
1480 ;; last category, delete the file. Also handle archive file
1481 ;; if necessary.
1482 (remove-overlays beg end)
1483 (delete-region beg end)
1484 (goto-char (point-min))
1485 ;; Put point after todo-categories sexp.
1486 (forward-line)
1487 (if (eobp) ; Aside from sexp, file is empty.
1488 (progn
1489 ;; Skip confirming killing the archive buffer.
1490 (set-buffer-modified-p nil)
1491 (delete-file todo-current-todo-file)
1492 (kill-buffer)
1493 (when (member todo-current-todo-file todo-files)
1494 (todo-reevaluate-filelist-defcustoms)))
1495 (setq todo-categories (delete (assoc cat todo-categories)
1496 todo-categories))
1497 (todo-update-categories-sexp)
1498 (when (> todo-category-number (length todo-categories))
1499 (setq todo-category-number 1))
1500 (todo-category-select)))))
1501 (set-window-buffer (selected-window)
1502 (set-buffer (find-file-noselect nfile)))
1503 (todo-category-number (or new cat))
1504 (todo-category-select))))
1506 (defun todo-merge-category (&optional file)
1507 "Merge current category into another existing category.
1509 With prefix argument FILE, prompt for a specific todo file and
1510 choose (with TAB completion) a category in it to merge into;
1511 otherwise, choose and merge into a category in either the
1512 current todo file or a file in `todo-category-completions-files'.
1514 After merging, the source category's todo and done items are
1515 appended to the chosen goal category's todo and done items,
1516 respectively. The goal category becomes the current category,
1517 and the source category is deleted.
1519 If both the source and goal categories also have archived items,
1520 they are also merged. If only the source category has archived
1521 items, the goal category is added as a new category to the
1522 archive file and the source category is deleted."
1523 (interactive "P")
1524 (let* ((tfile todo-current-todo-file)
1525 (cat (todo-current-category))
1526 (cat+file (todo-read-category "Merge into category: " 'todo file))
1527 (goal (car cat+file))
1528 (gfile (cdr cat+file))
1529 (tarchive (concat (file-name-sans-extension tfile) ".toda"))
1530 (garchive (concat (file-name-sans-extension gfile) ".toda"))
1531 (archived-count (todo-get-count 'archived))
1532 here)
1533 (with-current-buffer (get-buffer (find-file-noselect tfile))
1534 (widen)
1535 (let* ((buffer-read-only nil)
1536 (cbeg (progn
1537 (re-search-backward
1538 (concat "^" (regexp-quote todo-category-beg)) nil t)
1539 (point-marker)))
1540 (tbeg (progn (forward-line) (point-marker)))
1541 (dbeg (progn
1542 (re-search-forward
1543 (concat "^" (regexp-quote todo-category-done)) nil t)
1544 (forward-line) (point-marker)))
1545 ;; Omit empty line between todo and done items.
1546 (tend (progn (forward-line -2) (point-marker)))
1547 (cend (progn
1548 (if (re-search-forward
1549 (concat "^" (regexp-quote todo-category-beg)) nil t)
1550 (progn
1551 (goto-char (match-beginning 0))
1552 (point-marker))
1553 (point-max-marker))))
1554 (todo (buffer-substring-no-properties tbeg tend))
1555 (done (buffer-substring-no-properties dbeg cend))
1556 (todo-count (todo-get-count 'todo cat))
1557 (done-count (todo-get-count 'done cat)))
1558 ;; Merge into goal todo category.
1559 (with-current-buffer (get-buffer (find-file-noselect gfile))
1560 (unless (derived-mode-p 'todo-mode) (todo-mode))
1561 (widen)
1562 (goto-char (point-min))
1563 (let ((buffer-read-only nil))
1564 ;; Merge any todo items.
1565 (unless (zerop (length todo))
1566 (re-search-forward
1567 (concat "^" (regexp-quote (concat todo-category-beg goal)) "$")
1568 nil t)
1569 (re-search-forward
1570 (concat "^" (regexp-quote todo-category-done)) nil t)
1571 (forward-line -1)
1572 (setq here (point-marker))
1573 (insert todo)
1574 (todo-update-count 'todo todo-count goal))
1575 ;; Merge any done items.
1576 (unless (zerop (length done))
1577 (goto-char (if (re-search-forward
1578 (concat "^" (regexp-quote todo-category-beg))
1579 nil t)
1580 (match-beginning 0)
1581 (point-max)))
1582 (when (zerop (length todo)) (setq here (point-marker)))
1583 (insert done)
1584 (todo-update-count 'done done-count goal)))
1585 (todo-update-categories-sexp))
1586 ;; Update and clean up source todo file.
1587 (remove-overlays cbeg cend)
1588 (delete-region cbeg cend)
1589 (setq todo-categories (delete (assoc cat todo-categories)
1590 todo-categories))
1591 (todo-update-categories-sexp)
1592 (when (> todo-category-number (length todo-categories))
1593 (setq todo-category-number 1))
1594 (todo-category-select)
1595 (mapc (lambda (m) (set-marker m nil))
1596 (list cbeg tbeg dbeg tend cend))))
1597 (when (> archived-count 0)
1598 (with-current-buffer (get-buffer (find-file-noselect tarchive))
1599 (widen)
1600 (goto-char (point-min))
1601 (let* ((buffer-read-only nil)
1602 (cbeg (progn
1603 (when (re-search-forward
1604 (concat "^" (regexp-quote
1605 (concat todo-category-beg cat)) "$")
1606 nil t)
1607 (goto-char (match-beginning 0))
1608 (point-marker))))
1609 (cend (if (re-search-forward
1610 (concat "^" (regexp-quote todo-category-beg)) nil t)
1611 (match-beginning 0)
1612 (point-max)))
1613 (carch (progn
1614 (goto-char cbeg)
1615 (forward-line)
1616 (buffer-substring-no-properties (point) cend))))
1617 ;; Merge into goal archive category, if it exists, else create it.
1618 (with-current-buffer (get-buffer (find-file-noselect garchive))
1619 (let ((gbeg (when (re-search-forward
1620 (concat "^" (regexp-quote
1621 (concat todo-category-beg goal))
1622 "$")
1623 nil t)
1624 (goto-char (match-beginning 0))
1625 (point-marker))))
1626 (goto-char (if (and gbeg
1627 (re-search-forward
1628 (concat "^" (regexp-quote todo-category-beg))
1629 nil t))
1630 (match-beginning 0)
1631 (point-max)))
1632 (unless gbeg (todo-add-category nil goal))
1633 (insert carch)
1634 (todo-update-categories-sexp)))
1635 ;; Update and clean up source archive file.
1636 (remove-overlays cbeg cend)
1637 (delete-region cbeg cend)
1638 (setq todo-categories (todo-make-categories-list t))
1639 (todo-update-categories-sexp))))
1640 ;; Update goal todo file for merged archived items and display it.
1641 (set-window-buffer (selected-window) (set-buffer (get-file-buffer gfile)))
1642 (unless (zerop archived-count)
1643 (todo-update-count 'archived archived-count goal)
1644 (todo-update-categories-sexp))
1645 (todo-category-number goal)
1646 ;; If there are only merged done items, show them.
1647 (let ((todo-show-with-done (zerop (todo-get-count 'todo goal))))
1648 (todo-category-select)
1649 ;; Put point on the first merged item.
1650 (goto-char here))
1651 (set-marker here nil)))
1653 ;; -----------------------------------------------------------------------------
1654 ;;; Item editing
1655 ;; -----------------------------------------------------------------------------
1657 (defcustom todo-include-in-diary nil
1658 "Non-nil to allow new todo items to be included in the diary."
1659 :type 'boolean
1660 :group 'todo-edit)
1662 (defcustom todo-diary-nonmarking nil
1663 "Non-nil to insert new todo diary items as nonmarking by default.
1664 This appends `diary-nonmarking-symbol' to the front of an item on
1665 insertion provided it doesn't begin with `todo-nondiary-marker'."
1666 :type 'boolean
1667 :group 'todo-edit)
1669 (defcustom todo-always-add-time-string nil
1670 "Non-nil adds current time to a new item's date header by default.
1671 When the todo insertion commands have a non-nil \"maybe-notime\"
1672 argument, this reverses the effect of
1673 `todo-always-add-time-string': if t, these commands omit the
1674 current time, if nil, they include it."
1675 :type 'boolean
1676 :group 'todo-edit)
1678 (defcustom todo-use-only-highlighted-region t
1679 "Non-nil to enable inserting only highlighted region as new item."
1680 :type 'boolean
1681 :group 'todo-edit)
1683 (defcustom todo-default-priority 'first
1684 "Default priority of new and moved items."
1685 :type '(choice (const :tag "Highest priority" first)
1686 (const :tag "Lowest priority" last))
1687 :group 'todo-edit)
1689 (defcustom todo-item-mark "*"
1690 "String used to mark items.
1691 To ensure item marking works, change the value of this option
1692 only when no items are marked."
1693 :type '(string :validate
1694 (lambda (widget)
1695 (when (string= (widget-value widget) todo-prefix)
1696 (widget-put
1697 widget :error
1698 (format-message
1699 "Invalid value: must be distinct from ‘todo-prefix’"))
1700 widget)))
1701 :set (lambda (symbol value)
1702 (custom-set-default symbol (propertize value 'face 'todo-mark)))
1703 :group 'todo-edit)
1705 (defcustom todo-comment-string "COMMENT"
1706 "String inserted before optional comment appended to done item."
1707 :type 'string
1708 :initialize 'custom-initialize-default
1709 :set 'todo-reset-comment-string
1710 :group 'todo-edit)
1712 (defcustom todo-undo-item-omit-comment 'ask
1713 "Whether to omit done item comment on undoing the item.
1714 Nil means never omit the comment, t means always omit it, `ask'
1715 means prompt user and omit comment only on confirmation."
1716 :type '(choice (const :tag "Never" nil)
1717 (const :tag "Always" t)
1718 (const :tag "Ask" ask))
1719 :group 'todo-edit)
1721 (defun todo-toggle-mark-item (&optional n)
1722 "Mark item with `todo-item-mark' if unmarked, otherwise unmark it.
1723 With positive numerical prefix argument N, change the marking of
1724 the next N items in the current category. If both the todo and
1725 done items sections are visible, the sequence of N items can
1726 consist of the the last todo items and the first done items."
1727 (interactive "p")
1728 (when (todo-item-string)
1729 (unless (> n 1) (setq n 1))
1730 (catch 'end
1731 (dotimes (i n)
1732 (let* ((cat (todo-current-category))
1733 (marks (assoc cat todo-categories-with-marks))
1734 (ov (progn
1735 (unless (looking-at todo-item-start)
1736 (todo-item-start))
1737 (todo-get-overlay 'prefix)))
1738 (pref (overlay-get ov 'before-string)))
1739 (if (todo-marked-item-p)
1740 (progn
1741 (overlay-put ov 'before-string (substring pref 1))
1742 (if (= (cdr marks) 1) ; Deleted last mark in this category.
1743 (setq todo-categories-with-marks
1744 (assq-delete-all cat todo-categories-with-marks))
1745 (setcdr marks (1- (cdr marks)))))
1746 (overlay-put ov 'before-string (concat todo-item-mark pref))
1747 (if marks
1748 (setcdr marks (1+ (cdr marks)))
1749 (push (cons cat 1) todo-categories-with-marks))))
1750 (todo-forward-item)
1751 ;; Don't try to mark the empty lines at the end of the todo
1752 ;; and done items sections.
1753 (when (looking-at "^$")
1754 (if (eobp)
1755 (throw 'end nil)
1756 (todo-forward-item)))))))
1758 (defun todo-mark-category ()
1759 "Mark all visible items in this category with `todo-item-mark'."
1760 (interactive)
1761 (let* ((cat (todo-current-category))
1762 (marks (assoc cat todo-categories-with-marks)))
1763 (save-excursion
1764 (goto-char (point-min))
1765 (while (not (eobp))
1766 (let* ((ov (todo-get-overlay 'prefix))
1767 (pref (overlay-get ov 'before-string)))
1768 (unless (todo-marked-item-p)
1769 (overlay-put ov 'before-string (concat todo-item-mark pref))
1770 (if marks
1771 (setcdr marks (1+ (cdr marks)))
1772 (push (cons cat 1) todo-categories-with-marks))))
1773 (todo-forward-item)
1774 ;; Don't try to mark the empty line between the todo and done
1775 ;; items sections.
1776 (when (looking-at "^$")
1777 (unless (eobp)
1778 (todo-forward-item)))))))
1780 (defun todo-unmark-category ()
1781 "Remove `todo-item-mark' from all visible items in this category."
1782 (interactive)
1783 (let* ((cat (todo-current-category))
1784 (marks (assoc cat todo-categories-with-marks)))
1785 (save-excursion
1786 (goto-char (point-min))
1787 (while (not (eobp))
1788 (let* ((ov (todo-get-overlay 'prefix))
1789 ;; No overlay on empty line between todo and done items.
1790 (pref (when ov (overlay-get ov 'before-string))))
1791 (when (todo-marked-item-p)
1792 (overlay-put ov 'before-string (substring pref 1)))
1793 (todo-forward-item))))
1794 (setq todo-categories-with-marks
1795 (delq marks todo-categories-with-marks))))
1797 (defvar todo-date-from-calendar nil
1798 "Helper variable for setting item date from the Emacs Calendar.")
1800 (defvar todo-insert-item--keys-so-far)
1801 (defvar todo-insert-item--parameters)
1803 (defun todo-insert-item (&optional arg)
1804 "Choose an item insertion operation and carry it out.
1805 This inserts a new todo item into a category.
1807 With no prefix argument ARG, add the item to the current
1808 category; with one prefix argument (`C-u'), prompt for a category
1809 from the current todo file; with two prefix arguments (`C-u
1810 C-u'), first prompt for a todo file, then a category in that
1811 file. If a non-existing category is entered, ask whether to add
1812 it to the todo file; if answered affirmatively, add the category
1813 and insert the item there.
1815 There are a number of item insertion parameters which can be
1816 combined by entering specific keys to produce different insertion
1817 commands. After entering each key, a message shows which have
1818 already been entered and which remain available. See
1819 `(todo-mode) Inserting New Items' for details of the parameters,
1820 their associated keys and their effects."
1821 (interactive "P")
1822 (setq todo-insert-item--keys-so-far "i")
1823 (todo-insert-item--next-param nil (list arg) todo-insert-item--parameters))
1825 (defun todo-insert-item--basic (&optional arg diary-type date-type time where)
1826 "Function implementing the core of `todo-insert-item'."
1827 ;; If invoked outside of Todo mode and there is not yet any Todo
1828 ;; file, initialize one.
1829 (if (null (funcall todo-files-function))
1830 (todo-show)
1831 (let ((copy (eq where 'copy))
1832 (region (eq where 'region))
1833 (here (eq where 'here))
1834 diary-item)
1835 (when copy
1836 (cond
1837 ((not (eq major-mode 'todo-mode))
1838 (user-error "You must be in Todo mode to copy a todo item"))
1839 ((todo-done-item-p)
1840 (user-error "You cannot copy a done item as a new todo item"))
1841 ((looking-at "^$")
1842 (user-error "Point must be on a todo item to copy it")))
1843 (setq diary-item (todo-diary-item-p)))
1844 (when region
1845 (let (use-empty-active-region)
1846 (unless (and todo-use-only-highlighted-region (use-region-p))
1847 (user-error "There is no active region"))))
1848 (let* ((obuf (current-buffer))
1849 (ocat (todo-current-category))
1850 (opoint (point))
1851 (todo-mm (eq major-mode 'todo-mode))
1852 (cat+file (cond ((equal arg '(4))
1853 (todo-read-category "Insert in category: "))
1854 ((equal arg '(16))
1855 (todo-read-category "Insert in category: "
1856 nil 'file))
1858 (cons (todo-current-category)
1859 (or todo-current-todo-file
1860 (and todo-show-current-file
1861 todo-global-current-todo-file)
1862 (todo-absolute-file-name
1863 todo-default-todo-file))))))
1864 (cat (car cat+file))
1865 (file (cdr cat+file))
1866 (new-item (cond (copy (todo-item-string))
1867 (region (buffer-substring-no-properties
1868 (region-beginning) (region-end)))
1869 (t (read-from-minibuffer "Todo item: "))))
1870 (date-string (cond
1871 ((eq date-type 'date)
1872 (todo-read-date))
1873 ((eq date-type 'dayname)
1874 (todo-read-dayname))
1875 ((eq date-type 'calendar)
1876 (setq todo-date-from-calendar t)
1877 (or (todo-set-date-from-calendar)
1878 ;; If user exits Calendar before choosing
1879 ;; a date, cancel item insertion.
1880 (keyboard-quit)))
1881 ((and (stringp date-type)
1882 (string-match todo-date-pattern date-type))
1883 (setq todo-date-from-calendar date-type)
1884 (todo-set-date-from-calendar))
1886 (calendar-date-string
1887 (calendar-current-date) t t))))
1888 (time-string (or (and time (todo-read-time))
1889 (and todo-always-add-time-string
1890 (substring (current-time-string) 11 16)))))
1891 (setq todo-date-from-calendar nil)
1892 (find-file-noselect file 'nowarn)
1893 (set-window-buffer (selected-window)
1894 (set-buffer (find-buffer-visiting file)))
1895 ;; If this command was invoked outside of a Todo mode buffer,
1896 ;; the call to todo-current-category above returned nil. If
1897 ;; we just entered Todo mode now, then cat was set to the
1898 ;; file's first category, but if todo-mode was already
1899 ;; enabled, cat did not get set, so we have to do that.
1900 (unless cat
1901 (setq cat (todo-current-category)))
1902 (setq todo-current-todo-file file)
1903 (unless todo-global-current-todo-file
1904 (setq todo-global-current-todo-file todo-current-todo-file))
1905 (let ((buffer-read-only nil)
1906 (called-from-outside (not (and todo-mm (equal cat ocat))))
1907 done-only item-added)
1908 (unless copy
1909 (setq new-item
1910 ;; Add date, time and diary marking as required.
1911 (concat (if (not (and diary-type
1912 (not todo-include-in-diary)))
1913 todo-nondiary-start
1914 (when (and (eq diary-type 'nonmarking)
1915 (not todo-diary-nonmarking))
1916 diary-nonmarking-symbol))
1917 date-string (when (and time-string ; Can be empty.
1918 (not (zerop (length
1919 time-string))))
1920 (concat " " time-string))
1921 (when (not (and diary-type
1922 (not todo-include-in-diary)))
1923 todo-nondiary-end)
1924 " " new-item))
1925 ;; Indent newlines inserted by C-q C-j if nonspace char follows.
1926 (setq new-item (replace-regexp-in-string "\\(\n\\)[^[:blank:]]"
1927 "\n\t" new-item nil nil 1)))
1928 (unwind-protect
1929 (progn
1930 ;; Make sure the correct category is selected. There
1931 ;; are two cases: (i) we just visited the file, so no
1932 ;; category is selected yet, or (ii) we invoked
1933 ;; insertion "here" from outside the category we want
1934 ;; to insert in (with priority insertion, category
1935 ;; selection is done by todo-set-item-priority).
1936 (when (or (= (- (point-max) (point-min)) (buffer-size))
1937 (and here called-from-outside))
1938 (todo-category-number cat)
1939 (todo-category-select))
1940 ;; If only done items are displayed in category,
1941 ;; toggle to todo items before inserting new item.
1942 (when (save-excursion
1943 (goto-char (point-min))
1944 (looking-at todo-done-string-start))
1945 (setq done-only t)
1946 (todo-toggle-view-done-only))
1947 (if here
1948 (progn
1949 ;; If command was invoked with point in done
1950 ;; items section or outside of the current
1951 ;; category, can't insert "here", so to be
1952 ;; useful give new item top priority.
1953 (when (or (todo-done-item-section-p)
1954 called-from-outside
1955 done-only)
1956 (goto-char (point-min)))
1957 (todo-insert-with-overlays new-item))
1958 (todo-set-item-priority new-item cat t))
1959 (setq item-added t))
1960 ;; If user cancels before setting priority, restore
1961 ;; display.
1962 (unless item-added
1963 (set-window-buffer (selected-window) (set-buffer obuf))
1964 (when ocat
1965 (unless (equal cat ocat)
1966 (todo-category-number ocat)
1967 (todo-category-select))
1968 (and done-only (todo-toggle-view-done-only)))
1969 (goto-char opoint))
1970 ;; If the todo items section is not visible when the
1971 ;; insertion command is called (either because only done
1972 ;; items were shown or because the category was not in the
1973 ;; current buffer), then if the item is inserted at the
1974 ;; end of the category, point is at eob and eob at
1975 ;; window-start, so that higher priority todo items are
1976 ;; out of view. So we recenter to make sure the todo
1977 ;; items are displayed in the window.
1978 (when item-added (recenter)))
1979 (todo-update-count 'todo 1)
1980 (when (or diary-item diary-type todo-include-in-diary)
1981 (todo-update-count 'diary 1))
1982 (todo-update-categories-sexp))))))
1984 (defun todo-set-date-from-calendar ()
1985 "Return string of date chosen from Calendar."
1986 (cond ((and (stringp todo-date-from-calendar)
1987 (string-match todo-date-pattern todo-date-from-calendar))
1988 todo-date-from-calendar)
1989 (todo-date-from-calendar
1990 (let (calendar-view-diary-initially-flag)
1991 (calendar)) ; *Calendar* is now current buffer.
1992 (define-key calendar-mode-map [remap newline] 'exit-recursive-edit)
1993 ;; If user exits Calendar before choosing a date, clean up properly.
1994 (define-key calendar-mode-map
1995 [remap calendar-exit] (lambda ()
1996 (interactive)
1997 (progn
1998 (calendar-exit)
1999 (exit-recursive-edit))))
2000 (message "Put cursor on a date and type <return> to set it.")
2001 (recursive-edit)
2002 (unwind-protect
2003 (when (equal (buffer-name) calendar-buffer)
2004 (setq todo-date-from-calendar
2005 (calendar-date-string (calendar-cursor-to-date t) t t))
2006 (calendar-exit)
2007 todo-date-from-calendar)
2008 (define-key calendar-mode-map [remap newline] nil)
2009 (define-key calendar-mode-map [remap calendar-exit] nil)
2010 (unless (zerop (recursion-depth)) (exit-recursive-edit))
2011 (when (stringp todo-date-from-calendar)
2012 todo-date-from-calendar)))))
2014 (defun todo-insert-item-from-calendar (&optional arg)
2015 "Prompt for and insert a new item with date selected from calendar.
2016 Invoked without prefix argument ARG, insert the item into the
2017 current category, without one prefix argument, prompt for the
2018 category from the current todo file or from one listed in
2019 `todo-category-completions-files'; with two prefix arguments,
2020 prompt for a todo file and then for a category in it."
2021 (interactive "P")
2022 (setq todo-date-from-calendar
2023 (calendar-date-string (calendar-cursor-to-date t) t t))
2024 (calendar-exit)
2025 (todo-insert-item--basic arg nil todo-date-from-calendar))
2027 (define-key calendar-mode-map "it" 'todo-insert-item-from-calendar)
2029 (defun todo-delete-item ()
2030 "Delete at least one item in this category.
2031 If there are marked items, delete all of these; otherwise, delete
2032 the item at point."
2033 (interactive)
2034 (let (ov)
2035 (unwind-protect
2036 (let* ((cat (todo-current-category))
2037 (marked (assoc cat todo-categories-with-marks))
2038 (item (unless marked (todo-item-string)))
2039 (answer (if marked
2040 (todo-y-or-n-p
2041 "Permanently delete all marked items? ")
2042 (when item
2043 (setq ov (make-overlay
2044 (save-excursion (todo-item-start))
2045 (save-excursion (todo-item-end))))
2046 (overlay-put ov 'face 'todo-search)
2047 (todo-y-or-n-p "Permanently delete this item? "))))
2048 buffer-read-only)
2049 (when answer
2050 (and marked (goto-char (point-min)))
2051 (catch 'done
2052 (while (not (eobp))
2053 (if (or (and marked (todo-marked-item-p)) item)
2054 (progn
2055 (if (todo-done-item-p)
2056 (todo-update-count 'done -1)
2057 (todo-update-count 'todo -1 cat)
2058 (and (todo-diary-item-p)
2059 (todo-update-count 'diary -1)))
2060 (if ov (delete-overlay ov))
2061 (todo-remove-item)
2062 ;; Don't leave point below last item.
2063 (and item (bolp) (eolp) (< (point-min) (point-max))
2064 (todo-backward-item))
2065 (when item
2066 (throw 'done (setq item nil))))
2067 (todo-forward-item))))
2068 (when marked
2069 (setq todo-categories-with-marks
2070 (assq-delete-all cat todo-categories-with-marks)))
2071 (todo-update-categories-sexp)
2072 (todo-prefix-overlays)))
2073 (if ov (delete-overlay ov)))))
2075 (defvar todo-edit-item--param-key-alist)
2076 (defvar todo-edit-done-item--param-key-alist)
2078 (defun todo-edit-item (&optional arg)
2079 "Choose an editing operation for the current item and carry it out."
2080 (interactive "P")
2081 (let ((marked (assoc (todo-current-category) todo-categories-with-marks)))
2082 (cond ((and (todo-done-item-p) (not marked))
2083 (todo-edit-item--next-key todo-edit-done-item--param-key-alist))
2084 ((or marked (todo-item-string))
2085 (todo-edit-item--next-key todo-edit-item--param-key-alist arg)))))
2087 (defun todo-edit-item--text (&optional arg)
2088 "Function providing the text editing facilities of `todo-edit-item'."
2089 (let ((full-item (todo-item-string)))
2090 ;; If there are marked items and user invokes a text-editing
2091 ;; commands with point not on an item, todo-item-start is nil and
2092 ;; 1+ signals an error, so just make this a noop.
2093 (when full-item
2094 (let* ((opoint (point))
2095 (start (todo-item-start))
2096 (end (save-excursion (todo-item-end)))
2097 (item-beg (progn
2098 (re-search-forward
2099 (concat todo-date-string-start todo-date-pattern
2100 "\\( " diary-time-regexp "\\)?"
2101 (regexp-quote todo-nondiary-end) "?")
2102 (line-end-position) t)
2103 (1+ (- (point) start))))
2104 (include-header (eq arg 'include-header))
2105 (comment-edit (eq arg 'comment-edit))
2106 (comment-delete (eq arg 'comment-delete))
2107 (header-string (substring full-item 0 item-beg))
2108 (item (if (or include-header comment-edit comment-delete)
2109 full-item
2110 (substring full-item item-beg)))
2111 (multiline (or (eq arg 'multiline)
2112 (> (length (split-string item "\n")) 1)))
2113 (comment (save-excursion
2114 (todo-item-start)
2115 (re-search-forward
2116 (concat " \\[" (regexp-quote todo-comment-string)
2117 ": \\([^]]+\\)\\]") end t)))
2118 (prompt (if comment "Edit comment: " "Enter a comment: "))
2119 (buffer-read-only nil))
2120 ;; When there are marked items, user can invoke todo-edit-item
2121 ;; even if point is not on an item, but text editing only
2122 ;; applies to the item at point.
2123 (when (or (and (todo-done-item-p)
2124 (or comment-edit comment-delete))
2125 (and (not (todo-done-item-p))
2126 (or (not arg) include-header multiline)))
2127 (cond
2128 ((or comment-edit comment-delete)
2129 (save-excursion
2130 (todo-item-start)
2131 (if (re-search-forward (concat " \\["
2132 (regexp-quote todo-comment-string)
2133 ": \\([^]]+\\)\\]") end t)
2134 (if comment-delete
2135 (when (todo-y-or-n-p "Delete comment? ")
2136 (delete-region (match-beginning 0) (match-end 0)))
2137 (replace-match (read-string prompt (cons (match-string 1) 1))
2138 nil nil nil 1))
2139 (if comment-delete
2140 (user-error "There is no comment to delete")
2141 (insert " [" todo-comment-string ": "
2142 (prog1 (read-string prompt)
2143 ;; If user moved point during editing,
2144 ;; make sure it moves back.
2145 (goto-char opoint)
2146 (todo-item-end))
2147 "]")))))
2148 (multiline
2149 (let ((buf todo-edit-buffer))
2150 (set-window-buffer (selected-window)
2151 (set-buffer (make-indirect-buffer
2152 (buffer-name) buf)))
2153 (narrow-to-region (todo-item-start) (todo-item-end))
2154 (todo-edit-mode)
2155 (message "%s" (substitute-command-keys
2156 (concat "Type \\[todo-edit-quit] "
2157 "to return to Todo mode.\n")))))
2159 (let ((new (concat (if include-header "" header-string)
2160 (read-string "Edit: " (if include-header
2161 (cons item item-beg)
2162 (cons item 0))))))
2163 (when include-header
2164 (while (not (string-match (concat todo-date-string-start
2165 todo-date-pattern) new))
2166 (setq new (read-from-minibuffer
2167 "Item must start with a date: " new))))
2168 ;; Ensure lines following hard newlines are indented.
2169 (setq new (replace-regexp-in-string "\\(\n\\)[^[:blank:]]"
2170 "\n\t" new nil nil 1))
2171 ;; If user moved point during editing, make sure it moves back.
2172 (goto-char opoint)
2173 (todo-remove-item)
2174 (todo-insert-with-overlays new)
2175 (move-to-column item-beg)))))))))
2177 (defun todo-edit-quit ()
2178 "Return from Todo Edit mode to Todo mode.
2179 If the item contains hard line breaks, make sure the following
2180 lines are indented by `todo-indent-to-here' to conform to diary
2181 format.
2183 If the whole file was in Todo Edit mode, check before returning
2184 whether the file is still a valid todo file and if so, also
2185 recalculate the todo file's categories sexp, in case changes were
2186 made in the number or names of categories."
2187 (interactive)
2188 (if (> (buffer-size) (- (point-max) (point-min)))
2189 ;; We got here via `e m'.
2190 (let ((item (buffer-string))
2191 (regex "\\(\n\\)[^[:blank:]]")
2192 (buf (buffer-base-buffer)))
2193 (while (not (string-match (concat todo-date-string-start
2194 todo-date-pattern) item))
2195 (setq item (read-from-minibuffer
2196 "Item must start with a date: " item)))
2197 ;; Ensure lines following hard newlines are indented.
2198 (when (string-match regex (buffer-string))
2199 (setq item (replace-regexp-in-string regex "\n\t" item nil nil 1))
2200 (delete-region (point-min) (point-max))
2201 (insert item))
2202 (kill-buffer)
2203 (unless (eq (current-buffer) buf)
2204 (set-window-buffer (selected-window) (set-buffer buf))))
2205 ;; We got here via `F e'.
2206 (when (todo-check-format)
2207 ;; FIXME: separate out sexp check?
2208 ;; If manual editing makes e.g. item counts change, have to
2209 ;; call this to update todo-categories, but it restores
2210 ;; category order to list order.
2211 ;; (todo-repair-categories-sexp)
2212 ;; Compare (todo-make-categories-list t) with sexp and if
2213 ;; different ask (todo-update-categories-sexp) ?
2214 (todo-mode)
2215 (let* ((cat-beg (concat "^" (regexp-quote todo-category-beg)
2216 "\\(.*\\)$"))
2217 (curline (buffer-substring-no-properties
2218 (line-beginning-position) (line-end-position)))
2219 (cat (cond ((string-match cat-beg curline)
2220 (match-string-no-properties 1 curline))
2221 ((or (re-search-backward cat-beg nil t)
2222 (re-search-forward cat-beg nil t))
2223 (match-string-no-properties 1)))))
2224 (todo-category-number cat)
2225 (todo-category-select)
2226 (goto-char (point-min))))))
2228 (defun todo-edit-item--header (what &optional inc)
2229 "Function providing header editing facilities of `todo-edit-item'."
2230 (let ((marked (assoc (todo-current-category) todo-categories-with-marks))
2231 (first t)
2232 (todo-date-from-calendar t)
2233 ;; INC must be an integer, but users could pass it via
2234 ;; `todo-edit-item' as e.g. `-' or `C-u'.
2235 (inc (prefix-numeric-value inc))
2236 (buffer-read-only nil)
2237 ndate ntime year monthname month day
2238 dayname) ; Needed by calendar-date-display-form.
2239 (when marked (todo--user-error-if-marked-done-item))
2240 (save-excursion
2241 (or (and marked (goto-char (point-min))) (todo-item-start))
2242 (catch 'end
2243 (while (not (eobp))
2244 (and marked
2245 (while (not (todo-marked-item-p))
2246 (todo-forward-item)
2247 (and (eobp) (throw 'end nil))))
2248 (re-search-forward (concat todo-date-string-start "\\(?1:"
2249 todo-date-pattern
2250 "\\)\\(?2: " diary-time-regexp "\\)?"
2251 (regexp-quote todo-nondiary-end) "?")
2252 (line-end-position) t)
2253 (let* ((odate (match-string-no-properties 1))
2254 (otime (match-string-no-properties 2))
2255 (odayname (match-string-no-properties 5))
2256 (omonthname (match-string-no-properties 6))
2257 (omonth (match-string-no-properties 7))
2258 (oday (match-string-no-properties 8))
2259 (oyear (match-string-no-properties 9))
2260 (tmn-array todo-month-name-array)
2261 (mlist (append tmn-array nil))
2262 (tma-array todo-month-abbrev-array)
2263 (mablist (append tma-array nil))
2264 (yy (and oyear (unless (string= oyear "*")
2265 (string-to-number oyear))))
2266 (mm (or (and omonth (unless (string= omonth "*")
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 (let ((yy (string-to-number year)) ; 0 if year is "*".
2333 ;; When mm is 13 (corresponding to "*" as value
2334 ;; of month), this raises an args-out-of-range
2335 ;; error in calendar-last-day-of-month, so use 1
2336 ;; (corresponding to January) to get 31 days.
2337 (mm (if (= mm 13) 1 mm)))
2338 (if (> (string-to-number day)
2339 (calendar-last-day-of-month mm yy))
2340 (user-error "%s %s does not have %s days"
2341 (aref tmn-array (1- mm))
2342 (if (= mm 2) yy "") day))))
2343 ((eq what 'day)
2344 (setq year oyear
2345 month omonth
2346 monthname omonthname
2347 day (cond
2348 ((not current-prefix-arg)
2349 (todo-read-date 'day mm oyear))
2350 ((string= oday "*")
2351 (user-error "Cannot increment *"))
2352 ((or (string= omonth "*") (string= omonthname "*"))
2353 (setq dd (+ dd inc))
2354 (if (> dd 31)
2355 (user-error
2356 "A month cannot have more than 31 days")
2357 (number-to-string dd)))
2358 ;; Increment or decrement day by INC,
2359 ;; adjusting month and year if necessary
2360 ;; (if year is "*" assume current year to
2361 ;; calculate adjustment).
2363 (let* ((yy (or yy (calendar-extract-year
2364 (calendar-current-date))))
2365 (date (calendar-gregorian-from-absolute
2366 (+ (calendar-absolute-from-gregorian
2367 (list mm dd yy)) inc)))
2368 (adjmm (nth 0 date)))
2369 ;; Set year and month(name) to adjusted values.
2370 (unless (string= year "*")
2371 (setq year (number-to-string (nth 2 date))))
2372 (if month
2373 (setq month (number-to-string adjmm))
2374 (setq monthname (aref tma-array (1- adjmm))))
2375 ;; Return changed numerical day as a string.
2376 (number-to-string (nth 1 date)))))))))
2377 (unless odayname
2378 ;; If year, month or day date string components were
2379 ;; changed, rebuild the date string.
2380 (when (memq what '(year month day))
2381 (setq ndate (mapconcat 'eval calendar-date-display-form ""))))
2382 (when ndate (replace-match ndate nil nil nil 1))
2383 ;; Add new time string to the header, if it was supplied.
2384 (when ntime
2385 (if otime
2386 (replace-match ntime nil nil nil 2)
2387 (goto-char (match-end 1))
2388 (insert ntime)))
2389 (setq todo-date-from-calendar nil)
2390 (setq first nil))
2391 ;; Apply the changes to the first marked item header to the
2392 ;; remaining marked items. If there are no marked items,
2393 ;; we're finished.
2394 (if marked
2395 (todo-forward-item)
2396 (goto-char (point-max))))))))
2398 (defun todo-edit-item--diary-inclusion (&optional nonmarking)
2399 "Function providing diary marking facilities of `todo-edit-item'."
2400 (let ((buffer-read-only)
2401 (marked (assoc (todo-current-category) todo-categories-with-marks)))
2402 (when marked (todo--user-error-if-marked-done-item))
2403 (catch 'stop
2404 (save-excursion
2405 (when marked (goto-char (point-min)))
2406 (while (not (eobp))
2407 (unless (and marked (not (todo-marked-item-p)))
2408 (let* ((beg (todo-item-start))
2409 (lim (save-excursion (todo-item-end)))
2410 (end (save-excursion
2411 (or (todo-time-string-matcher lim)
2412 (todo-date-string-matcher lim)))))
2413 (if nonmarking
2414 (if (looking-at (regexp-quote diary-nonmarking-symbol))
2415 (replace-match "")
2416 (when (looking-at (regexp-quote todo-nondiary-start))
2417 (save-excursion
2418 (replace-match "")
2419 (search-forward todo-nondiary-end (1+ end) t)
2420 (replace-match "")
2421 (todo-update-count 'diary 1)))
2422 (insert diary-nonmarking-symbol))
2423 (if (looking-at (regexp-quote todo-nondiary-start))
2424 (progn
2425 (replace-match "")
2426 (search-forward todo-nondiary-end (1+ end) t)
2427 (replace-match "")
2428 (todo-update-count 'diary 1))
2429 (when end
2430 (when (looking-at (regexp-quote diary-nonmarking-symbol))
2431 (replace-match "")
2432 (setq end (1- end))) ; Since we deleted nonmarking symbol.
2433 (insert todo-nondiary-start)
2434 (goto-char (1+ end))
2435 (insert todo-nondiary-end)
2436 (todo-update-count 'diary -1))))))
2437 (unless marked (throw 'stop nil))
2438 (todo-forward-item)))))
2439 (todo-update-categories-sexp))
2441 (defun todo-edit-category-diary-inclusion (arg)
2442 "Make all items in this category diary items.
2443 With prefix ARG, make all items in this category non-diary
2444 items."
2445 (interactive "P")
2446 (save-excursion
2447 (goto-char (point-min))
2448 (let ((todo-count (todo-get-count 'todo))
2449 (diary-count (todo-get-count 'diary))
2450 (buffer-read-only))
2451 (catch 'stop
2452 (while (not (eobp))
2453 (if (todo-done-item-p) ; We've gone too far.
2454 (throw 'stop nil)
2455 (let* ((beg (todo-item-start))
2456 (lim (save-excursion (todo-item-end)))
2457 (end (save-excursion
2458 (or (todo-time-string-matcher lim)
2459 (todo-date-string-matcher lim)))))
2460 (if arg
2461 (unless (looking-at (regexp-quote todo-nondiary-start))
2462 (when (looking-at (regexp-quote diary-nonmarking-symbol))
2463 (replace-match "")
2464 (setq end (1- end))) ; Since we deleted nonmarking symbol.
2465 (insert todo-nondiary-start)
2466 (goto-char (1+ end))
2467 (insert todo-nondiary-end))
2468 (when (looking-at (regexp-quote todo-nondiary-start))
2469 (replace-match "")
2470 (search-forward todo-nondiary-end (1+ end) t)
2471 (replace-match "")))))
2472 (todo-forward-item))
2473 (unless (if arg (zerop diary-count) (= diary-count todo-count))
2474 (todo-update-count 'diary (if arg
2475 (- diary-count)
2476 (- todo-count diary-count))))
2477 (todo-update-categories-sexp)))))
2479 (defun todo-edit-category-diary-nonmarking (arg)
2480 "Add `diary-nonmarking-symbol' to all diary items in this category.
2481 With prefix ARG, remove `diary-nonmarking-symbol' from all diary
2482 items in this category."
2483 (interactive "P")
2484 (save-excursion
2485 (goto-char (point-min))
2486 (let (buffer-read-only)
2487 (catch 'stop
2488 (while (not (eobp))
2489 (if (todo-done-item-p) ; We've gone too far.
2490 (throw 'stop nil)
2491 (unless (looking-at (regexp-quote todo-nondiary-start))
2492 (if arg
2493 (when (looking-at (regexp-quote diary-nonmarking-symbol))
2494 (replace-match ""))
2495 (unless (looking-at (regexp-quote diary-nonmarking-symbol))
2496 (insert diary-nonmarking-symbol))))
2497 (todo-forward-item)))))))
2499 (defun todo-set-item-priority (&optional item cat new arg)
2500 "Prompt for and set ITEM's priority in CATegory.
2502 Interactively, ITEM is the todo item at point, CAT is the current
2503 category, and the priority is a number between 1 and the number
2504 of items in the category. Non-interactively, non-nil NEW means
2505 ITEM is a new item and the lowest priority is one more than the
2506 number of items in CAT.
2508 The new priority is set either interactively by prompt or by a
2509 numerical prefix argument, or noninteractively by argument ARG,
2510 whose value can be either of the symbols `raise' or `lower',
2511 meaning to raise or lower the item's priority by one."
2512 (interactive)
2513 (unless (and (called-interactively-p 'any)
2514 (or (todo-done-item-p) (looking-at "^$")))
2515 (let* ((item (or item (todo-item-string)))
2516 (marked (todo-marked-item-p))
2517 (cat (or cat (cond ((eq major-mode 'todo-mode)
2518 (todo-current-category))
2519 ((eq major-mode 'todo-filtered-items-mode)
2520 (let* ((regexp1
2521 (concat todo-date-string-start
2522 todo-date-pattern
2523 "\\( " diary-time-regexp "\\)?"
2524 (regexp-quote todo-nondiary-end)
2525 "?\\(?1: \\[\\(.+:\\)?.+\\]\\)")))
2526 (save-excursion
2527 (re-search-forward regexp1 nil t)
2528 (match-string-no-properties 1)))))))
2529 curnum
2530 (todo (cond ((or (eq arg 'raise) (eq arg 'lower)
2531 (eq major-mode 'todo-filtered-items-mode))
2532 (save-excursion
2533 (let ((curstart (todo-item-start))
2534 (count 0))
2535 (goto-char (point-min))
2536 (while (looking-at todo-item-start)
2537 (setq count (1+ count))
2538 (when (= (point) curstart) (setq curnum count))
2539 (todo-forward-item))
2540 count)))
2541 ((eq major-mode 'todo-mode)
2542 (todo-get-count 'todo cat))))
2543 (maxnum (if new (1+ todo) todo))
2544 (prompt (format "Set item priority (1-%d): " maxnum))
2545 (priority (cond ((and (not arg) (numberp current-prefix-arg))
2546 current-prefix-arg)
2547 ((and (eq arg 'raise) (>= curnum 1))
2548 (1- curnum))
2549 ((and (eq arg 'lower) (<= curnum maxnum))
2550 (1+ curnum))))
2551 candidate
2552 buffer-read-only)
2553 (unless (and priority
2554 (or (and (eq arg 'raise) (zerop priority))
2555 (and (eq arg 'lower) (> priority maxnum))))
2556 ;; When moving item to another category, show the category before
2557 ;; prompting for its priority.
2558 (unless (or arg (called-interactively-p 'any))
2559 (todo-category-number cat)
2560 ;; If done items in category are visible, keep them visible.
2561 (let ((done todo-show-with-done))
2562 (when (> (buffer-size) (- (point-max) (point-min)))
2563 (save-excursion
2564 (goto-char (point-min))
2565 (setq done (re-search-forward todo-done-string-start nil t))))
2566 (let ((todo-show-with-done done))
2567 ;; Keep current item or top of moved to category in view
2568 ;; while setting priority.
2569 (save-excursion (todo-category-select)))))
2570 ;; Prompt for priority only when the category has at least one
2571 ;; todo item.
2572 (when (> maxnum 1)
2573 (while (not priority)
2574 (setq candidate (read-number prompt
2575 (if (eq todo-default-priority 'first)
2576 1 maxnum)))
2577 (setq prompt (when (or (< candidate 1) (> candidate maxnum))
2578 (format "Priority must be an integer between 1 and %d.\n"
2579 maxnum)))
2580 (unless prompt (setq priority candidate))))
2581 ;; In Top Priorities buffer, an item's priority can be changed
2582 ;; wrt items in another category, but not wrt items in the same
2583 ;; category.
2584 (when (eq major-mode 'todo-filtered-items-mode)
2585 (let* ((regexp2 (concat todo-date-string-start todo-date-pattern
2586 "\\( " diary-time-regexp "\\)?"
2587 (regexp-quote todo-nondiary-end)
2588 "?\\(?1:" (regexp-quote cat) "\\)"))
2589 (end (cond ((< curnum priority)
2590 (save-excursion (todo-item-end)))
2591 ((> curnum priority)
2592 (save-excursion (todo-item-start)))))
2593 (match (save-excursion
2594 (cond ((< curnum priority)
2595 (todo-forward-item (1+ (- priority curnum)))
2596 (when (re-search-backward regexp2 end t)
2597 (match-string-no-properties 1)))
2598 ((> curnum priority)
2599 (todo-backward-item (- curnum priority))
2600 (when (re-search-forward regexp2 end t)
2601 (match-string-no-properties 1)))))))
2602 (when match
2603 (user-error (concat "Cannot reprioritize items from the same "
2604 "category in this mode, only in Todo mode")))))
2605 ;; Interactively or with non-nil ARG, relocate the item within its
2606 ;; category.
2607 (when (or arg (called-interactively-p 'any))
2608 (todo-remove-item))
2609 (goto-char (point-min))
2610 (when priority
2611 (unless (= priority 1)
2612 (todo-forward-item (1- priority))
2613 ;; When called from todo-item-undone and the highest priority
2614 ;; is chosen, this advances point to the first done item, so
2615 ;; move it up to the empty line above the done items
2616 ;; separator.
2617 (when (looking-back (concat "^"
2618 (regexp-quote todo-category-done)
2619 "\n")
2620 (line-beginning-position 0))
2621 (todo-backward-item))))
2622 (todo-insert-with-overlays item)
2623 ;; If item was marked, restore the mark.
2624 (and marked
2625 (let* ((ov (todo-get-overlay 'prefix))
2626 (pref (overlay-get ov 'before-string)))
2627 (overlay-put ov 'before-string
2628 (concat todo-item-mark pref))))))))
2630 (defun todo-raise-item-priority ()
2631 "Raise priority of current item by moving it up by one item."
2632 (interactive)
2633 (todo-set-item-priority nil nil nil 'raise))
2635 (defun todo-lower-item-priority ()
2636 "Lower priority of current item by moving it down by one item."
2637 (interactive)
2638 (todo-set-item-priority nil nil nil 'lower))
2640 (defun todo-move-item (&optional file)
2641 "Move at least one todo or done item to another category.
2642 If there are marked items, move all of these; otherwise, move
2643 the item at point.
2645 With prefix argument FILE, prompt for a specific todo file and
2646 choose (with TAB completion) a category in it to move the item or
2647 items to; otherwise, choose and move to any category in either
2648 the current todo file or one of the files in
2649 `todo-category-completions-files'. If the chosen category is
2650 not an existing categories, then it is created and the item(s)
2651 become(s) the first entry/entries in that category.
2653 With moved todo items, prompt to set the priority in the category
2654 moved to (with multiple todo items, the one that had the highest
2655 priority in the category moved from gets the new priority and the
2656 rest of the moved todo items are inserted in sequence below it).
2657 Moved done items are appended to the top of the done items
2658 section in the category moved to."
2659 (interactive "P")
2660 (let* ((cat1 (todo-current-category))
2661 (marked (assoc cat1 todo-categories-with-marks)))
2662 ;; Noop if point is not on an item and there are no marked items.
2663 (unless (and (looking-at "^$")
2664 (not marked))
2665 (let* ((buffer-read-only)
2666 (file1 todo-current-todo-file)
2667 (num todo-category-number)
2668 (item (todo-item-string))
2669 (diary-item (todo-diary-item-p))
2670 (done-item (and (todo-done-item-p) (concat item "\n")))
2671 (omark (save-excursion (todo-item-start) (point-marker)))
2672 (todo 0)
2673 (diary 0)
2674 (done 0)
2675 ov cat2 file2 moved nmark todo-items done-items)
2676 (unwind-protect
2677 (progn
2678 (unless marked
2679 (setq ov (make-overlay (save-excursion (todo-item-start))
2680 (save-excursion (todo-item-end))))
2681 (overlay-put ov 'face 'todo-search))
2682 (let* ((pl (if (and marked (> (cdr marked) 1)) "s" ""))
2683 (cat+file (todo-read-category (concat "Move item" pl
2684 " to category: ")
2685 nil file)))
2686 (while (and (equal (car cat+file) cat1)
2687 (equal (cdr cat+file) file1))
2688 (setq cat+file (todo-read-category
2689 "Choose a different category: ")))
2690 (setq cat2 (car cat+file)
2691 file2 (cdr cat+file))))
2692 (if ov (delete-overlay ov)))
2693 (set-buffer (find-buffer-visiting file1))
2694 (if marked
2695 (progn
2696 (goto-char (point-min))
2697 (while (not (eobp))
2698 (when (todo-marked-item-p)
2699 (if (todo-done-item-p)
2700 (setq done-items (concat done-items
2701 (todo-item-string) "\n")
2702 done (1+ done))
2703 (setq todo-items (concat todo-items
2704 (todo-item-string) "\n")
2705 todo (1+ todo))
2706 (when (todo-diary-item-p)
2707 (setq diary (1+ diary)))))
2708 (todo-forward-item))
2709 ;; Chop off last newline of multiple todo item string,
2710 ;; since it will be reinserted when setting priority
2711 ;; (but with done items priority is not set, so keep
2712 ;; last newline).
2713 (and todo-items
2714 (setq todo-items (substring todo-items 0 -1))))
2715 (if (todo-done-item-p)
2716 (setq done 1)
2717 (setq todo 1)
2718 (when (todo-diary-item-p) (setq diary 1))))
2719 (set-window-buffer (selected-window)
2720 (set-buffer (find-file-noselect file2 'nowarn)))
2721 (unwind-protect
2722 (progn
2723 (when (or todo-items (and item (not done-item)))
2724 (todo-set-item-priority (or todo-items item) cat2 t))
2725 ;; Move done items en bloc to top of done items section.
2726 (when (or done-items done-item)
2727 (todo-category-number cat2)
2728 (widen)
2729 (goto-char (point-min))
2730 (re-search-forward
2731 (concat "^" (regexp-quote (concat todo-category-beg cat2))
2732 "$") nil t)
2733 (re-search-forward
2734 (concat "^" (regexp-quote todo-category-done)) nil t)
2735 (forward-line)
2736 (insert (or done-items done-item)))
2737 (setq moved t))
2738 (cond
2739 ;; Move succeeded, so remove item from starting category,
2740 ;; update item counts and display the category containing
2741 ;; the moved item.
2742 (moved
2743 (setq nmark (point-marker))
2744 (when todo (todo-update-count 'todo todo))
2745 (when diary (todo-update-count 'diary diary))
2746 (when done (todo-update-count 'done done))
2747 (todo-update-categories-sexp)
2748 (with-current-buffer (find-buffer-visiting file1)
2749 (save-excursion
2750 (save-restriction
2751 (widen)
2752 (goto-char omark)
2753 (if marked
2754 (let (beg end)
2755 (setq item nil)
2756 (re-search-backward
2757 (concat "^" (regexp-quote todo-category-beg)) nil t)
2758 (forward-line)
2759 (setq beg (point))
2760 (setq end (if (re-search-forward
2761 (concat "^" (regexp-quote
2762 todo-category-beg)) nil t)
2763 (match-beginning 0)
2764 (point-max)))
2765 (goto-char beg)
2766 (while (< (point) end)
2767 (if (todo-marked-item-p)
2768 (todo-remove-item)
2769 (todo-forward-item)))
2770 (setq todo-categories-with-marks
2771 (assq-delete-all cat1 todo-categories-with-marks)))
2772 (if ov (delete-overlay ov))
2773 (todo-remove-item))))
2774 (when todo (todo-update-count 'todo (- todo) cat1))
2775 (when diary (todo-update-count 'diary (- diary) cat1))
2776 (when done (todo-update-count 'done (- done) cat1))
2777 (todo-update-categories-sexp))
2778 (set-window-buffer (selected-window)
2779 (set-buffer (find-file-noselect file2 'nowarn)))
2780 (setq todo-category-number (todo-category-number cat2))
2781 (let ((todo-show-with-done (or done-items done-item)))
2782 (todo-category-select))
2783 (goto-char nmark)
2784 ;; If item is moved to end of (just first?) category, make
2785 ;; sure the items above it are displayed in the window.
2786 (recenter))
2787 ;; User quit before setting priority of todo item(s), so
2788 ;; return to starting category.
2790 (set-window-buffer (selected-window)
2791 (set-buffer (find-file-noselect file1 'nowarn)))
2792 (todo-category-number cat1)
2793 (todo-category-select)
2794 (goto-char omark))))))))
2796 (defun todo-item-done (&optional arg)
2797 "Tag a todo item in this category as done and relocate it.
2799 With prefix argument ARG prompt for a comment and append it to
2800 the done item; this is only possible if there are no marked
2801 items. If there are marked items, tag all of these with
2802 `todo-done-string' plus the current date and, if
2803 `todo-always-add-time-string' is non-nil, the current time;
2804 otherwise, just tag the item at point. Items tagged as done are
2805 relocated to the category's (by default hidden) done section. If
2806 done items are visible on invoking this command, they remain
2807 visible."
2808 (interactive "P")
2809 (let* ((cat (todo-current-category))
2810 (marked (assoc cat todo-categories-with-marks)))
2811 (when marked (todo--user-error-if-marked-done-item))
2812 (unless (and (not marked)
2813 (or (todo-done-item-p)
2814 ;; Point is between todo and done items.
2815 (looking-at "^$")))
2816 (let* ((date-string (calendar-date-string (calendar-current-date) t t))
2817 (time-string (if todo-always-add-time-string
2818 (concat " " (substring (current-time-string)
2819 11 16))
2820 ""))
2821 (done-prefix (concat "[" todo-done-string date-string time-string
2822 "] "))
2823 (comment (and arg (read-string "Enter a comment: ")))
2824 (item-count 0)
2825 (diary-count 0)
2826 (show-done (save-excursion
2827 (goto-char (point-min))
2828 (re-search-forward todo-done-string-start nil t)))
2829 (buffer-read-only nil)
2830 item done-item
2831 (opoint (point)))
2832 ;; Don't add empty comment to done item.
2833 (setq comment (unless (zerop (length comment))
2834 (concat " [" todo-comment-string ": " comment "]")))
2835 (and marked (goto-char (point-min)))
2836 (catch 'done
2837 ;; Stop looping when we hit the empty line below the last
2838 ;; todo item (this is eobp if only done items are hidden).
2839 (while (not (looking-at "^$"))
2840 (if (or (not marked) (and marked (todo-marked-item-p)))
2841 (progn
2842 (setq item (todo-item-string))
2843 (setq done-item (concat done-item done-prefix item
2844 comment (and marked "\n")))
2845 (setq item-count (1+ item-count))
2846 (when (todo-diary-item-p)
2847 (setq diary-count (1+ diary-count)))
2848 (todo-remove-item)
2849 (unless marked (throw 'done nil)))
2850 (todo-forward-item))))
2851 (when marked
2852 ;; Chop off last newline of done item string.
2853 (setq done-item (substring done-item 0 -1))
2854 (setq todo-categories-with-marks
2855 (assq-delete-all cat todo-categories-with-marks)))
2856 (save-excursion
2857 (widen)
2858 (re-search-forward
2859 (concat "^" (regexp-quote todo-category-done)) nil t)
2860 (forward-char)
2861 (when show-done (setq opoint (point)))
2862 (insert done-item "\n"))
2863 (todo-update-count 'todo (- item-count))
2864 (todo-update-count 'done item-count)
2865 (todo-update-count 'diary (- diary-count))
2866 (todo-update-categories-sexp)
2867 (let ((todo-show-with-done show-done))
2868 (todo-category-select)
2869 ;; When done items are visible, put point at the top of the
2870 ;; done items section. When done items are hidden, restore
2871 ;; point to its location prior to invoking this command.
2872 (when opoint (goto-char opoint)))))))
2874 (defun todo-item-undone ()
2875 "Restore at least one done item to this category's todo section.
2876 Prompt for the new priority. If there are marked items, undo all
2877 of these, giving the first undone item the new priority and the
2878 rest following directly in sequence; otherwise, undo just the
2879 item at point.
2881 If the done item has a comment, ask whether to omit the comment
2882 from the restored item. With multiple marked done items with
2883 comments, only ask once, and if affirmed, omit subsequent
2884 comments without asking."
2885 (interactive)
2886 (let* ((cat (todo-current-category))
2887 (marked (assoc cat todo-categories-with-marks))
2888 (pl (if (and marked (> (cdr marked) 1)) "s" "")))
2889 (when (or marked (todo-done-item-p))
2890 (let ((buffer-read-only)
2891 (opoint (point))
2892 (omark (point-marker))
2893 (first 'first)
2894 (item-count 0)
2895 (diary-count 0)
2896 start end item ov npoint undone)
2897 (and marked (goto-char (point-min)))
2898 (catch 'done
2899 (while (not (eobp))
2900 (when (or (not marked) (and marked (todo-marked-item-p)))
2901 (if (not (todo-done-item-p))
2902 (progn
2903 (goto-char opoint)
2904 (user-error "Only done items can be undone"))
2905 (todo-item-start)
2906 (unless marked
2907 (setq ov (make-overlay (save-excursion (todo-item-start))
2908 (save-excursion (todo-item-end))))
2909 (overlay-put ov 'face 'todo-search))
2910 ;; Find the end of the date string added upon tagging item as
2911 ;; done.
2912 (setq start (search-forward "] "))
2913 (setq item-count (1+ item-count))
2914 (unless (looking-at (regexp-quote todo-nondiary-start))
2915 (setq diary-count (1+ diary-count)))
2916 (setq end (save-excursion (todo-item-end)))
2917 ;; Ask (once) whether to omit done item's comment. If
2918 ;; affirmed, omit subsequent comments without asking.
2919 (when (re-search-forward
2920 (concat " \\[" (regexp-quote todo-comment-string)
2921 ": [^]]+\\]") end t)
2922 (unwind-protect
2923 (if (eq first 'first)
2924 (setq first
2925 (if (eq todo-undo-item-omit-comment 'ask)
2926 (when (todo-y-or-n-p
2927 (concat "Omit comment" pl
2928 " from restored item"
2929 pl "? "))
2930 'omit)
2931 (when todo-undo-item-omit-comment 'omit)))
2933 (when (and (eq first 'first) ov) (delete-overlay ov)))
2934 (when (eq first 'omit)
2935 (setq end (match-beginning 0))))
2936 (setq item (concat item
2937 (buffer-substring-no-properties start end)
2938 (when marked "\n")))
2939 (unless marked (throw 'done nil))))
2940 (todo-forward-item)))
2941 (unwind-protect
2942 (progn
2943 ;; Chop off last newline of multiple items string, since
2944 ;; it will be reinserted on setting priority.
2945 (and marked (setq item (substring item 0 -1)))
2946 (todo-set-item-priority item cat t)
2947 (setq npoint (point))
2948 (setq undone t))
2949 (when ov (delete-overlay ov))
2950 (if (not undone)
2951 (goto-char opoint)
2952 (if marked
2953 (progn
2954 (setq item nil)
2955 (re-search-forward
2956 (concat "^" (regexp-quote todo-category-done)) nil t)
2957 (while (not (eobp))
2958 (if (todo-marked-item-p)
2959 (todo-remove-item)
2960 (todo-forward-item)))
2961 (setq todo-categories-with-marks
2962 (assq-delete-all cat todo-categories-with-marks)))
2963 (goto-char omark)
2964 (todo-remove-item))
2965 (todo-update-count 'todo item-count)
2966 (todo-update-count 'done (- item-count))
2967 (when diary-count (todo-update-count 'diary diary-count))
2968 (todo-update-categories-sexp)
2969 (let ((todo-show-with-done (> (todo-get-count 'done) 0)))
2970 (todo-category-select))
2971 ;; Put cursor on undone item.
2972 (goto-char npoint)))
2973 (set-marker omark nil)))))
2975 ;; -----------------------------------------------------------------------------
2976 ;;; Done item archives
2977 ;; -----------------------------------------------------------------------------
2979 (defun todo-find-archive (&optional ask)
2980 "Visit the archive of the current todo category, if it exists.
2981 If the category has no archived items, prompt to visit the
2982 archive anyway. If there is no archive for this file or with
2983 non-nil argument ASK, prompt to visit another archive.
2985 The buffer showing the archive is in Todo Archive mode. The
2986 first visit in a session displays the first category in the
2987 archive, subsequent visits return to the last category
2988 displayed."
2989 (interactive)
2990 (if (null (funcall todo-files-function t))
2991 (message "There are no archive files")
2992 (let* ((cat (todo-current-category))
2993 (count (todo-get-count 'archived cat))
2994 (archive (concat (file-name-sans-extension todo-current-todo-file)
2995 ".toda"))
2996 (place (cond (ask 'other-archive)
2997 ((file-exists-p archive) 'this-archive)
2998 (t (when (todo-y-or-n-p
2999 (concat "This file has no archive; "
3000 "visit another archive? "))
3001 'other-archive)))))
3002 (when (eq place 'other-archive)
3003 (setq archive (todo-read-file-name "Choose a todo archive: " t t)))
3004 (when (and (eq place 'this-archive) (zerop count))
3005 (setq place (when (todo-y-or-n-p
3006 (concat "This category has no archived items;"
3007 " visit archive anyway? "))
3008 'other-cat)))
3009 (when place
3010 (set-window-buffer (selected-window)
3011 (set-buffer (find-file-noselect archive)))
3012 (unless (derived-mode-p 'todo-archive-mode) (todo-archive-mode))
3013 (if (member place '(other-archive other-cat))
3014 (setq todo-category-number 1)
3015 (todo-category-number cat))
3016 (todo-category-select)))))
3018 (defun todo-choose-archive ()
3019 "Choose an archive and visit it."
3020 (interactive)
3021 (todo-find-archive t))
3023 (defun todo-archive-done-item (&optional all)
3024 "Archive at least one done item in this category.
3026 With prefix argument ALL, prompt whether to archive all done
3027 items in this category and on confirmation archive them.
3028 Otherwise, if there are marked done items (and no marked todo
3029 items), archive all of these; otherwise, archive the done item at
3030 point.
3032 If the archive of this file does not exist, it is created. If
3033 this category does not exist in the archive, it is created."
3034 (interactive "P")
3035 (when (eq major-mode 'todo-mode)
3036 (if (and all (zerop (todo-get-count 'done)))
3037 (message "No done items in this category")
3038 (catch 'end
3039 (let* ((cat (todo-current-category))
3040 (tbuf (current-buffer))
3041 (marked (assoc cat todo-categories-with-marks))
3042 (afile (concat (file-name-sans-extension
3043 todo-current-todo-file) ".toda"))
3044 (archive (find-file-noselect afile t))
3045 (item (and (not marked) (todo-done-item-p)
3046 (concat (todo-item-string) "\n")))
3047 (count 0)
3048 (opoint (unless (todo-done-item-p) (point)))
3049 marked-items beg end all-done
3050 buffer-read-only)
3051 (cond
3052 (all
3053 (if (todo-y-or-n-p "Archive all done items in this category? ")
3054 (save-excursion
3055 (save-restriction
3056 (goto-char (point-min))
3057 (widen)
3058 (setq beg (progn
3059 (re-search-forward todo-done-string-start
3060 nil t)
3061 (match-beginning 0))
3062 end (if (re-search-forward
3063 (concat "^"
3064 (regexp-quote todo-category-beg))
3065 nil t)
3066 (match-beginning 0)
3067 (point-max))
3068 all-done (buffer-substring-no-properties beg end)
3069 count (todo-get-count 'done))
3070 ;; Restore starting point, unless it was on a done
3071 ;; item, since they will all be deleted.
3072 (when opoint (goto-char opoint))))
3073 (throw 'end nil)))
3074 (marked
3075 (save-excursion
3076 (goto-char (point-min))
3077 (while (not (eobp))
3078 (when (todo-marked-item-p)
3079 (if (not (todo-done-item-p))
3080 (throw 'end (message "Only done items can be archived"))
3081 (setq marked-items
3082 (concat marked-items (todo-item-string) "\n"))
3083 (setq count (1+ count))))
3084 (todo-forward-item)))))
3085 (if (not (or marked all item))
3086 (throw 'end (message "Only done items can be archived"))
3087 (with-current-buffer archive
3088 (unless (derived-mode-p 'todo-archive-mode) (todo-archive-mode))
3089 (let (buffer-read-only)
3090 (widen)
3091 (goto-char (point-min))
3092 (if (and (re-search-forward
3093 (concat "^" (regexp-quote
3094 (concat todo-category-beg cat)) "$")
3095 nil t)
3096 (re-search-forward (regexp-quote todo-category-done)
3097 nil t))
3098 ;; Start of done items section in existing category.
3099 (forward-char)
3100 (todo-add-category nil cat)
3101 ;; Start of done items section in new category.
3102 (goto-char (point-max)))
3103 (insert (cond (marked marked-items)
3104 (all all-done)
3105 (item)))
3106 (todo-update-count 'done (if (or marked all) count 1) cat)
3107 (todo-update-categories-sexp)
3108 ;; If archive is new, save to file now (with
3109 ;; write-region to avoid prompt for file to save to)
3110 ;; to update todo-archives, and set the mode for
3111 ;; visiting the archive below.
3112 (unless (nth 7 (file-attributes afile))
3113 (write-region nil nil afile t t)
3114 (setq todo-archives (funcall todo-files-function t))
3115 (todo-archive-mode))))
3116 (with-current-buffer tbuf
3117 (cond
3118 (all
3119 (save-excursion
3120 (save-restriction
3121 ;; Make sure done items are accessible.
3122 (widen)
3123 (remove-overlays beg end)
3124 (delete-region beg end)
3125 (todo-update-count 'done (- count))
3126 (todo-update-count 'archived count))))
3127 ((or marked
3128 ;; If we're archiving all done items, can't
3129 ;; first archive item point was on, since
3130 ;; that will short-circuit the rest.
3131 (and item (not all)))
3132 (and marked (goto-char (point-min)))
3133 (catch 'done
3134 (while (not (eobp))
3135 (if (or (and marked (todo-marked-item-p)) item)
3136 (progn
3137 (todo-remove-item)
3138 (todo-update-count 'done -1)
3139 (todo-update-count 'archived 1)
3140 ;; Don't leave point below last item.
3141 (and (or marked item) (bolp) (eolp)
3142 (< (point-min) (point-max))
3143 (todo-backward-item))
3144 (when item
3145 (throw 'done (setq item nil))))
3146 (todo-forward-item))))))
3147 (when marked
3148 (setq todo-categories-with-marks
3149 (assq-delete-all cat todo-categories-with-marks)))
3150 (todo-update-categories-sexp)
3151 (todo-prefix-overlays)))
3152 (find-file afile)
3153 (todo-category-number cat)
3154 (todo-category-select)
3155 (split-window-below)
3156 (set-window-buffer (selected-window) tbuf)
3157 ;; Make todo file current to select category.
3158 (find-file (buffer-file-name tbuf))
3159 ;; Make sure done item separator is hidden (if done items
3160 ;; were initially visible).
3161 (let (todo-show-with-done) (todo-category-select)))))))
3163 (defun todo-unarchive-items ()
3164 "Unarchive at least one item in this archive category.
3165 If there are marked items, unarchive all of these; otherwise,
3166 unarchive the item at point.
3168 Unarchived items are restored as done items to the corresponding
3169 category in the todo file, inserted at the top of done items
3170 section. If all items in the archive category have been
3171 restored, the category is deleted from the archive. If this was
3172 the only category in the archive, the archive file is deleted."
3173 (interactive)
3174 (when (eq major-mode 'todo-archive-mode)
3175 (let* ((cat (todo-current-category))
3176 (tbuf (find-file-noselect
3177 (concat (file-name-sans-extension todo-current-todo-file)
3178 ".todo") t))
3179 (marked (assoc cat todo-categories-with-marks))
3180 (item (concat (todo-item-string) "\n"))
3181 (marked-count 0)
3182 marked-items
3183 buffer-read-only)
3184 (when marked
3185 (save-excursion
3186 (goto-char (point-min))
3187 (while (not (eobp))
3188 (when (todo-marked-item-p)
3189 (setq marked-items (concat marked-items (todo-item-string) "\n"))
3190 (setq marked-count (1+ marked-count)))
3191 (todo-forward-item))))
3192 ;; Restore items to top of category's done section and update counts.
3193 (with-current-buffer tbuf
3194 (let (buffer-read-only newcat)
3195 (widen)
3196 (goto-char (point-min))
3197 ;; Find the corresponding todo category, or if there isn't
3198 ;; one, add it.
3199 (unless (re-search-forward
3200 (concat "^" (regexp-quote (concat todo-category-beg cat))
3201 "$") nil t)
3202 (todo-add-category nil cat)
3203 (setq newcat t))
3204 ;; Go to top of category's done section.
3205 (re-search-forward
3206 (concat "^" (regexp-quote todo-category-done)) nil t)
3207 (forward-line)
3208 (cond (marked
3209 (insert marked-items)
3210 (todo-update-count 'done marked-count cat)
3211 (unless newcat ; Newly added category has no archive.
3212 (todo-update-count 'archived (- marked-count) cat)))
3214 (insert item)
3215 (todo-update-count 'done 1 cat)
3216 (unless newcat ; Newly added category has no archive.
3217 (todo-update-count 'archived -1 cat))))
3218 (todo-update-categories-sexp)))
3219 ;; Delete restored items from archive.
3220 (when marked
3221 (setq item nil)
3222 (goto-char (point-min)))
3223 (catch 'done
3224 (while (not (eobp))
3225 (if (or (todo-marked-item-p) item)
3226 (progn
3227 (todo-remove-item)
3228 (when item
3229 (throw 'done (setq item nil))))
3230 (todo-forward-item))))
3231 (todo-update-count 'done (if marked (- marked-count) -1) cat)
3232 ;; If we unarchived the last item in category, then if that was
3233 ;; the only category, delete the whole file, otherwise, just
3234 ;; delete the category.
3235 (when (= 0 (todo-get-count 'done))
3236 (if (= 1 (length todo-categories))
3237 (progn
3238 (delete-file todo-current-todo-file)
3239 ;; Kill the archive buffer silently.
3240 (set-buffer-modified-p nil)
3241 (kill-buffer))
3242 (widen)
3243 (let ((beg (re-search-backward
3244 (concat "^" (regexp-quote todo-category-beg) cat "$")
3245 nil t))
3246 (end (if (re-search-forward
3247 (concat "^" (regexp-quote todo-category-beg))
3248 nil t 2)
3249 (match-beginning 0)
3250 (point-max))))
3251 (remove-overlays beg end)
3252 (delete-region beg end)
3253 (setq todo-categories (delete (assoc cat todo-categories)
3254 todo-categories)))))
3255 (todo-update-categories-sexp)
3256 ;; Visit category in todo file and show restored done items.
3257 (let ((tfile (buffer-file-name tbuf))
3258 (todo-show-with-done t))
3259 (set-window-buffer (selected-window)
3260 (set-buffer (find-file-noselect tfile)))
3261 (todo-category-number cat)
3262 (todo-category-select)
3263 (message "Items unarchived.")))))
3265 (defun todo-jump-to-archive-category (&optional file)
3266 "Prompt for a category in a todo archive and jump to it.
3267 With prefix argument FILE, prompt for an archive and choose (with
3268 TAB completion) a category in it to jump to; otherwise, choose
3269 and jump to any category in the current archive."
3270 (interactive "P")
3271 (todo-jump-to-category file 'archive))
3273 ;; -----------------------------------------------------------------------------
3274 ;;; Displaying and sorting tables of categories
3275 ;; -----------------------------------------------------------------------------
3277 (defcustom todo-categories-category-label "Category"
3278 "Category button label in Todo Categories mode."
3279 :type 'string
3280 :group 'todo-categories)
3282 (defcustom todo-categories-todo-label "Todo"
3283 "Todo button label in Todo Categories mode."
3284 :type 'string
3285 :group 'todo-categories)
3287 (defcustom todo-categories-diary-label "Diary"
3288 "Diary button label in Todo Categories mode."
3289 :type 'string
3290 :group 'todo-categories)
3292 (defcustom todo-categories-done-label "Done"
3293 "Done button label in Todo Categories mode."
3294 :type 'string
3295 :group 'todo-categories)
3297 (defcustom todo-categories-archived-label "Archived"
3298 "Archived button label in Todo Categories mode."
3299 :type 'string
3300 :group 'todo-categories)
3302 (defcustom todo-categories-totals-label "Totals"
3303 "String to label total item counts in Todo Categories mode."
3304 :type 'string
3305 :group 'todo-categories)
3307 (defcustom todo-categories-number-separator " | "
3308 "String between number and category in Todo Categories mode.
3309 This separates the number from the category name in the default
3310 categories display according to priority."
3311 :type 'string
3312 :group 'todo-categories)
3314 (defcustom todo-categories-align 'center
3315 "Alignment of category names in Todo Categories mode."
3316 :type '(radio (const left) (const center) (const right))
3317 :group 'todo-categories)
3319 (defun todo-show-categories-table ()
3320 "Display a table of the current file's categories and item counts.
3322 In the initial display the lines of the table are numbered,
3323 indicating the current order of the categories when sequentially
3324 navigating through the todo file with `\\[todo-forward-category]'
3325 and `\\[todo-backward-category]'. You can reorder the lines, and
3326 hence the category sequence, by typing `\\[todo-raise-category]'
3327 or `\\[todo-lower-category]' to raise or lower the category at
3328 point, or by typing `\\[todo-set-category-number]' and entering a
3329 number at the prompt or by typing `\\[todo-set-category-number]'
3330 with a numeric prefix. If you save the todo file after
3331 reordering the categories, the new order persists in subsequent
3332 Emacs sessions.
3334 The labels above the category names and item counts are buttons,
3335 and clicking these changes the display: sorted by category name
3336 or by the respective item counts (alternately descending or
3337 ascending). In these displays the categories are not numbered
3338 and `\\[todo-set-category-number]', `\\[todo-raise-category]' and
3339 `\\[todo-lower-category]' are disabled. (Programmatically, the
3340 sorting is triggered by passing a non-nil SORTKEY argument.)
3342 In addition, the lines with the category names and item counts
3343 are buttonized, and pressing one of these button jumps to the
3344 category in Todo mode (or Todo Archive mode, for categories
3345 containing only archived items, provided user option
3346 `todo-skip-archived-categories' is non-nil. These categories
3347 are shown in `todo-archived-only' face."
3348 (interactive)
3349 (todo-display-categories)
3350 (let (sortkey)
3351 (todo-update-categories-display sortkey)))
3353 (defun todo-next-button (n)
3354 "Move point to the Nth next button in the table of categories."
3355 (interactive "p")
3356 (forward-button n 'wrap 'display-message)
3357 (and (bolp) (button-at (point))
3358 ;; Align with beginning of category label.
3359 (forward-char (+ 4 (length todo-categories-number-separator)))))
3361 (defun todo-previous-button (n)
3362 "Move point to the Nth previous button in the table of categories."
3363 (interactive "p")
3364 (backward-button n 'wrap 'display-message)
3365 (and (bolp) (button-at (point))
3366 ;; Align with beginning of category label.
3367 (forward-char (+ 4 (length todo-categories-number-separator)))))
3369 (defun todo-set-category-number (&optional arg)
3370 "Change number of category at point in the table of categories.
3372 With ARG nil, prompt for the new number. Alternatively, the
3373 enter the new number with numerical prefix ARG. Otherwise, if
3374 ARG is either of the symbols `raise' or `lower', raise or lower
3375 the category line in the table by one, respectively, thereby
3376 decreasing or increasing its number."
3377 (interactive "P")
3378 (let ((curnum (save-excursion
3379 ;; Get the number representing the priority of the category
3380 ;; on the current line.
3381 (forward-line 0) (skip-chars-forward " ") (number-at-point))))
3382 (when curnum ; Do nothing if we're not on a category line.
3383 (let* ((maxnum (length todo-categories))
3384 (prompt (format "Set category priority (1-%d): " maxnum))
3385 (col (current-column))
3386 (buffer-read-only nil)
3387 (priority (cond ((and (eq arg 'raise) (> curnum 1))
3388 (1- curnum))
3389 ((and (eq arg 'lower) (< curnum maxnum))
3390 (1+ curnum))))
3391 candidate)
3392 (while (not priority)
3393 (setq candidate (or arg (read-number prompt)))
3394 (setq arg nil)
3395 (setq prompt
3396 (cond ((or (< candidate 1) (> candidate maxnum))
3397 (format "Priority must be an integer between 1 and %d: "
3398 maxnum))
3399 ((= candidate curnum)
3400 "Choose a different priority than the current one: ")))
3401 (unless prompt (setq priority candidate)))
3402 (let* ((lower (< curnum priority)) ; Priority is being lowered.
3403 (head (butlast todo-categories
3404 (apply (if lower 'identity '1+)
3405 (list (- maxnum priority)))))
3406 (tail (nthcdr (apply (if lower 'identity '1-) (list priority))
3407 todo-categories))
3408 ;; Category's name and items counts list.
3409 (catcons (nth (1- curnum) todo-categories))
3410 (todo-categories (nconc head (list catcons) tail))
3411 newcats)
3412 (when lower (setq todo-categories (nreverse todo-categories)))
3413 (setq todo-categories (delete-dups todo-categories))
3414 (when lower (setq todo-categories (nreverse todo-categories)))
3415 (setq newcats todo-categories)
3416 (kill-buffer)
3417 (with-current-buffer (find-buffer-visiting todo-current-todo-file)
3418 (setq todo-categories newcats)
3419 (todo-update-categories-sexp))
3420 (todo-show-categories-table)
3421 (forward-line (1+ priority))
3422 (forward-char col))))))
3424 (defun todo-raise-category ()
3425 "Raise priority of category at point in the table of categories."
3426 (interactive)
3427 (todo-set-category-number 'raise))
3429 (defun todo-lower-category ()
3430 "Lower priority of category at point in the table of categories."
3431 (interactive)
3432 (todo-set-category-number 'lower))
3434 (defun todo-sort-categories-alphabetically-or-numerically ()
3435 "Sort table of categories alphabetically or numerically."
3436 (interactive)
3437 (save-excursion
3438 (goto-char (point-min))
3439 (forward-line 2)
3440 (if (member 'alpha todo-descending-counts)
3441 (progn
3442 (todo-update-categories-display nil)
3443 (setq todo-descending-counts
3444 (delete 'alpha todo-descending-counts)))
3445 (todo-update-categories-display 'alpha))))
3447 (defun todo-sort-categories-by-todo ()
3448 "Sort table of categories by number of todo items."
3449 (interactive)
3450 (save-excursion
3451 (goto-char (point-min))
3452 (forward-line 2)
3453 (todo-update-categories-display 'todo)))
3455 (defun todo-sort-categories-by-diary ()
3456 "Sort table of categories by number of diary items."
3457 (interactive)
3458 (save-excursion
3459 (goto-char (point-min))
3460 (forward-line 2)
3461 (todo-update-categories-display 'diary)))
3463 (defun todo-sort-categories-by-done ()
3464 "Sort table of categories by number of non-archived done items."
3465 (interactive)
3466 (save-excursion
3467 (goto-char (point-min))
3468 (forward-line 2)
3469 (todo-update-categories-display 'done)))
3471 (defun todo-sort-categories-by-archived ()
3472 "Sort table of categories by number of archived items."
3473 (interactive)
3474 (save-excursion
3475 (goto-char (point-min))
3476 (forward-line 2)
3477 (todo-update-categories-display 'archived)))
3479 (defvar todo-categories-buffer "*Todo Categories*"
3480 "Name of buffer in Todo Categories mode.")
3482 (defun todo-longest-category-name-length (categories)
3483 "Return the length of the longest name in list CATEGORIES."
3484 (let ((longest 0))
3485 (dolist (c categories longest)
3486 (setq longest (max longest (length c))))))
3488 (defun todo-adjusted-category-label-length ()
3489 "Return adjusted length of category label button.
3490 The adjustment ensures proper tabular alignment in Todo
3491 Categories mode."
3492 (let* ((categories (mapcar 'car todo-categories))
3493 (longest (todo-longest-category-name-length categories))
3494 (catlablen (length todo-categories-category-label))
3495 (lc-diff (- longest catlablen)))
3496 (if (and (natnump lc-diff) (cl-oddp lc-diff))
3497 (1+ longest)
3498 (max longest catlablen))))
3500 (defun todo-padded-string (str)
3501 "Return category name or label string STR padded with spaces.
3502 The placement of the padding is determined by the value of user
3503 option `todo-categories-align'."
3504 (let* ((len (todo-adjusted-category-label-length))
3505 (strlen (length str))
3506 (strlen-odd (eq (logand strlen 1) 1))
3507 (padding (max 0 (/ (- len strlen) 2)))
3508 (padding-left (cond ((eq todo-categories-align 'left) 0)
3509 ((eq todo-categories-align 'center) padding)
3510 ((eq todo-categories-align 'right)
3511 (if strlen-odd (1+ (* padding 2)) (* padding 2)))))
3512 (padding-right (cond ((eq todo-categories-align 'left)
3513 (if strlen-odd (1+ (* padding 2)) (* padding 2)))
3514 ((eq todo-categories-align 'center)
3515 (if strlen-odd (1+ padding) padding))
3516 ((eq todo-categories-align 'right) 0))))
3517 (concat (make-string padding-left 32) str (make-string padding-right 32))))
3519 (defvar todo-descending-counts nil
3520 "List of keys for category counts sorted in descending order.")
3522 (defun todo-sort (list &optional key)
3523 "Return a copy of LIST, possibly sorted according to KEY."
3524 (let* ((l (copy-sequence list))
3525 (fn (if (eq key 'alpha)
3526 (lambda (x) (upcase x)) ; Alphabetize case insensitively.
3527 (lambda (x) (todo-get-count key x))))
3528 ;; Keep track of whether the last sort by key was descending or
3529 ;; ascending.
3530 (descending (member key todo-descending-counts))
3531 (cmp (if (eq key 'alpha)
3532 'string<
3533 (if descending '< '>)))
3534 (pred (lambda (s1 s2) (let ((t1 (funcall fn (car s1)))
3535 (t2 (funcall fn (car s2))))
3536 (funcall cmp t1 t2)))))
3537 (when key
3538 (setq l (sort l pred))
3539 ;; Switch between descending and ascending sort order.
3540 (if descending
3541 (setq todo-descending-counts
3542 (delete key todo-descending-counts))
3543 (push key todo-descending-counts)))
3546 (defun todo-display-sorted (type)
3547 "Keep point on the TYPE count sorting button just clicked."
3548 (let ((opoint (point)))
3549 (todo-update-categories-display type)
3550 (goto-char opoint)))
3552 (defun todo-label-to-key (label)
3553 "Return symbol for sort key associated with LABEL."
3554 (let (key)
3555 (cond ((string= label todo-categories-category-label)
3556 (setq key 'alpha))
3557 ((string= label todo-categories-todo-label)
3558 (setq key 'todo))
3559 ((string= label todo-categories-diary-label)
3560 (setq key 'diary))
3561 ((string= label todo-categories-done-label)
3562 (setq key 'done))
3563 ((string= label todo-categories-archived-label)
3564 (setq key 'archived)))
3565 key))
3567 (defun todo-insert-sort-button (label)
3568 "Insert button for displaying categories sorted by item counts.
3569 LABEL determines which type of count is sorted."
3570 (let* ((str (if (string= label todo-categories-category-label)
3571 (todo-padded-string label)
3572 label))
3573 (beg (point))
3574 (end (+ beg (length str)))
3576 (insert-button str 'face nil
3577 'action
3578 `(lambda (button)
3579 (let ((key (todo-label-to-key ,label)))
3580 (if (and (member key todo-descending-counts)
3581 (eq key 'alpha))
3582 (progn
3583 ;; If display is alphabetical, switch back to
3584 ;; category priority order.
3585 (todo-display-sorted nil)
3586 (setq todo-descending-counts
3587 (delete key todo-descending-counts)))
3588 (todo-display-sorted key)))))
3589 (setq ov (make-overlay beg end))
3590 (overlay-put ov 'face 'todo-button)))
3592 (defun todo-total-item-counts ()
3593 "Return a list of total item counts for the current file."
3594 (mapcar (lambda (i) (apply '+ (mapcar (lambda (l) (aref l i))
3595 (mapcar 'cdr todo-categories))))
3596 (list 0 1 2 3)))
3598 (defvar todo-categories-category-number 0
3599 "Variable for numbering categories in Todo Categories mode.")
3601 (defun todo-insert-category-line (cat &optional nonum)
3602 "Insert button with category CAT's name and item counts.
3603 With non-nil argument NONUM show only these; otherwise, insert a
3604 number in front of the button indicating the category's priority.
3605 The number and the category name are separated by the string
3606 which is the value of the user option
3607 `todo-categories-number-separator'."
3608 (let ((archive (member todo-current-todo-file todo-archives))
3609 (num todo-categories-category-number)
3610 (str (todo-padded-string cat))
3611 (opoint (point)))
3612 (setq num (1+ num) todo-categories-category-number num)
3613 (insert-button
3614 (concat (if nonum
3615 (make-string (+ 4 (length todo-categories-number-separator))
3617 (format " %3d%s" num todo-categories-number-separator))
3619 (mapconcat (lambda (elt)
3620 (concat
3621 (make-string (1+ (/ (length (car elt)) 2)) 32) ; label
3622 (format "%3d" (todo-get-count (cdr elt) cat)) ; count
3623 ;; Add an extra space if label length is odd.
3624 (when (cl-oddp (length (car elt))) " ")))
3625 (if archive
3626 (list (cons todo-categories-done-label 'done))
3627 (list (cons todo-categories-todo-label 'todo)
3628 (cons todo-categories-diary-label 'diary)
3629 (cons todo-categories-done-label 'done)
3630 (cons todo-categories-archived-label
3631 'archived)))
3633 " ") ; Make highlighting on last column look better.
3634 'face (if (and todo-skip-archived-categories
3635 (zerop (todo-get-count 'todo cat))
3636 (zerop (todo-get-count 'done cat))
3637 (not (zerop (todo-get-count 'archived cat))))
3638 'todo-archived-only
3639 nil)
3640 'action `(lambda (button) (let ((buf (current-buffer)))
3641 (todo-jump-to-category nil ,cat)
3642 (kill-buffer buf))))
3643 ;; Highlight the sorted count column.
3644 (let* ((beg (+ opoint 7 (length str)))
3645 end ovl)
3646 (cond ((eq nonum 'todo)
3647 (setq beg (+ beg 1 (/ (length todo-categories-todo-label) 2))))
3648 ((eq nonum 'diary)
3649 (setq beg (+ beg 1 (length todo-categories-todo-label)
3650 2 (/ (length todo-categories-diary-label) 2))))
3651 ((eq nonum 'done)
3652 (setq beg (+ beg 1 (length todo-categories-todo-label)
3653 2 (length todo-categories-diary-label)
3654 2 (/ (length todo-categories-done-label) 2))))
3655 ((eq nonum 'archived)
3656 (setq beg (+ beg 1 (length todo-categories-todo-label)
3657 2 (length todo-categories-diary-label)
3658 2 (length todo-categories-done-label)
3659 2 (/ (length todo-categories-archived-label) 2)))))
3660 (unless (= beg (+ opoint 7 (length str))) ; Don't highlight categories.
3661 (setq end (+ beg 4))
3662 (setq ovl (make-overlay beg end))
3663 (overlay-put ovl 'face 'todo-sorted-column)))
3664 (newline)))
3666 (defun todo-display-categories ()
3667 "Prepare buffer for displaying table of categories and item counts."
3668 (unless (eq major-mode 'todo-categories-mode)
3669 (setq todo-global-current-todo-file
3670 (or todo-current-todo-file
3671 (todo-absolute-file-name todo-default-todo-file)))
3672 (set-window-buffer (selected-window)
3673 (set-buffer (get-buffer-create todo-categories-buffer)))
3674 (kill-all-local-variables)
3675 (todo-categories-mode)
3676 (let ((archive (member todo-current-todo-file todo-archives))
3677 buffer-read-only)
3678 (erase-buffer)
3679 (insert (format (concat "Category counts for todo "
3680 (if archive "archive" "file")
3681 " \"%s\".")
3682 (todo-short-file-name todo-current-todo-file)))
3683 (newline 2)
3684 ;; Make space for the column of category numbers.
3685 (insert (make-string (+ 4 (length todo-categories-number-separator)) 32))
3686 ;; Add the category and item count buttons (if this is the list of
3687 ;; categories in an archive, show only done item counts).
3688 (todo-insert-sort-button todo-categories-category-label)
3689 (if archive
3690 (progn
3691 (insert (make-string 3 32))
3692 (todo-insert-sort-button todo-categories-done-label))
3693 (insert (make-string 3 32))
3694 (todo-insert-sort-button todo-categories-todo-label)
3695 (insert (make-string 2 32))
3696 (todo-insert-sort-button todo-categories-diary-label)
3697 (insert (make-string 2 32))
3698 (todo-insert-sort-button todo-categories-done-label)
3699 (insert (make-string 2 32))
3700 (todo-insert-sort-button todo-categories-archived-label))
3701 (newline 2))))
3703 (defun todo-update-categories-display (sortkey)
3704 "Populate table of categories and sort by SORTKEY."
3705 (let* ((cats0 todo-categories)
3706 (cats (todo-sort cats0 sortkey))
3707 (archive (member todo-current-todo-file todo-archives))
3708 (todo-categories-category-number 0)
3709 ;; Find start of Category button if we just entered Todo Categories
3710 ;; mode.
3711 (pt (if (eq (point) (point-max))
3712 (save-excursion
3713 (forward-line -2)
3714 (goto-char (next-single-char-property-change
3715 (point) 'face nil (line-end-position))))))
3716 (buffer-read-only))
3717 (forward-line 2)
3718 (delete-region (point) (point-max))
3719 ;; Fill in the table with buttonized lines, each showing a category and
3720 ;; its item counts.
3721 (mapc (lambda (cat) (todo-insert-category-line cat sortkey))
3722 (mapcar 'car cats))
3723 (newline)
3724 ;; Add a line showing item count totals.
3725 (insert (make-string (+ 4 (length todo-categories-number-separator)) 32)
3726 (todo-padded-string todo-categories-totals-label)
3727 (mapconcat
3728 (lambda (elt)
3729 (concat
3730 (make-string (1+ (/ (length (car elt)) 2)) 32)
3731 (format "%3d" (nth (cdr elt) (todo-total-item-counts)))
3732 ;; Add an extra space if label length is odd.
3733 (when (cl-oddp (length (car elt))) " ")))
3734 (if archive
3735 (list (cons todo-categories-done-label 2))
3736 (list (cons todo-categories-todo-label 0)
3737 (cons todo-categories-diary-label 1)
3738 (cons todo-categories-done-label 2)
3739 (cons todo-categories-archived-label 3)))
3740 ""))
3741 ;; Put cursor on Category button initially.
3742 (if pt (goto-char pt))
3743 (setq buffer-read-only t)))
3745 ;; -----------------------------------------------------------------------------
3746 ;;; Searching and item filtering
3747 ;; -----------------------------------------------------------------------------
3749 (defun todo-search ()
3750 "Search for a regular expression in this todo file.
3751 The search runs through the whole file and encompasses all and
3752 only todo and done items; it excludes category names. Multiple
3753 matches are shown sequentially, highlighted in `todo-search'
3754 face."
3755 (interactive)
3756 (let ((regex (read-from-minibuffer "Enter a search string (regexp): "))
3757 (opoint (point))
3758 matches match cat in-done ov mlen msg)
3759 (widen)
3760 (goto-char (point-min))
3761 (while (not (eobp))
3762 (setq match (re-search-forward regex nil t))
3763 (goto-char (line-beginning-position))
3764 (unless (or (equal (point) 1)
3765 (looking-at (concat "^" (regexp-quote todo-category-beg))))
3766 (if match (push match matches)))
3767 (forward-line))
3768 (setq matches (reverse matches))
3769 (if matches
3770 (catch 'stop
3771 (while matches
3772 (setq match (pop matches))
3773 (goto-char match)
3774 (todo-item-start)
3775 (when (looking-at todo-done-string-start)
3776 (setq in-done t))
3777 (re-search-backward (concat "^" (regexp-quote todo-category-beg)
3778 "\\(.*\\)\n") nil t)
3779 (setq cat (match-string-no-properties 1))
3780 (todo-category-number cat)
3781 (todo-category-select)
3782 (if in-done
3783 (unless todo-show-with-done (todo-toggle-view-done-items)))
3784 (goto-char match)
3785 (setq ov (make-overlay (- (point) (length regex)) (point)))
3786 (overlay-put ov 'face 'todo-search)
3787 (when matches
3788 (setq mlen (length matches))
3789 (if (todo-y-or-n-p
3790 (if (> mlen 1)
3791 (format "There are %d more matches; go to next match? "
3792 mlen)
3793 "There is one more match; go to it? "))
3794 (widen)
3795 (throw 'stop (setq msg (if (> mlen 1)
3796 (format "There are %d more matches."
3797 mlen)
3798 "There is one more match."))))))
3799 (setq msg "There are no more matches."))
3800 (todo-category-select)
3801 (goto-char opoint)
3802 (message "No match for \"%s\"" regex))
3803 (when msg
3804 (if (todo-y-or-n-p (concat msg "\nUnhighlight matches? "))
3805 (todo-clear-matches)
3806 (message "You can unhighlight the matches later by typing %s"
3807 (key-description (car (where-is-internal
3808 'todo-clear-matches))))))))
3810 (defun todo-clear-matches ()
3811 "Remove highlighting on matches found by todo-search."
3812 (interactive)
3813 (remove-overlays 1 (1+ (buffer-size)) 'face 'todo-search))
3815 (defcustom todo-top-priorities-overrides nil
3816 "List of rules specifying number of top priority items to show.
3817 These rules override `todo-top-priorities' on invocations of
3818 `\\[todo-filter-top-priorities]' and
3819 `\\[todo-filter-top-priorities-multifile]'. Each rule is a list
3820 of the form (FILE NUM ALIST), where FILE is a member of
3821 `todo-files', NUM is a number specifying the default number of
3822 top priority items for each category in that file, and ALIST,
3823 when non-nil, consists of conses of a category name in FILE and a
3824 number specifying the default number of top priority items in
3825 that category, which overrides NUM.
3827 This variable should be set interactively by
3828 `\\[todo-set-top-priorities-in-file]' or
3829 `\\[todo-set-top-priorities-in-category]'."
3830 :type 'sexp
3831 :group 'todo-filtered)
3833 (defcustom todo-top-priorities 1
3834 "Default number of top priorities shown by `todo-filter-top-priorities'."
3835 :type 'integer
3836 :group 'todo-filtered)
3838 (defcustom todo-filter-files nil
3839 "List of default files for multifile item filtering."
3840 :type `(set ,@(mapcar (lambda (f) (list 'const f))
3841 (mapcar 'todo-short-file-name
3842 (funcall todo-files-function))))
3843 :group 'todo-filtered)
3845 (defcustom todo-filter-done-items nil
3846 "Non-nil to include done items when processing regexp filters.
3847 Done items from corresponding archive files are also included."
3848 :type 'boolean
3849 :group 'todo-filtered)
3851 (defun todo-set-top-priorities-in-file ()
3852 "Set number of top priorities for this file.
3853 See `todo-set-top-priorities' for more details."
3854 (interactive)
3855 (todo-set-top-priorities))
3857 (defun todo-set-top-priorities-in-category ()
3858 "Set number of top priorities for this category.
3859 See `todo-set-top-priorities' for more details."
3860 (interactive)
3861 (todo-set-top-priorities t))
3863 (defun todo-filter-top-priorities (&optional arg)
3864 "Display a list of top priority items from different categories.
3865 The categories can be any of those in the current todo file.
3867 With numerical prefix ARG show at most ARG top priority items
3868 from each category. With `C-u' as prefix argument show the
3869 numbers of top priority items specified by category in
3870 `todo-top-priorities-overrides', if this has an entry for the file(s);
3871 otherwise show `todo-top-priorities' items per category in the
3872 file(s). With no prefix argument, if a top priorities file for
3873 the current todo file has previously been saved (see
3874 `todo-save-filtered-items-buffer'), visit this file; if there is
3875 no such file, build the list as with prefix argument `C-u'.
3877 The prefix ARG regulates how many top priorities from
3878 each category to show, as described above."
3879 (interactive "P")
3880 (todo-filter-items 'top arg))
3882 (defun todo-filter-top-priorities-multifile (&optional arg)
3883 "Display a list of top priority items from different categories.
3884 The categories are a subset of the categories in the files listed
3885 in `todo-filter-files', or if this nil, in the files chosen from
3886 a file selection dialog that pops up in this case.
3888 With numerical prefix ARG show at most ARG top priority items
3889 from each category in each file. With `C-u' as prefix argument
3890 show the numbers of top priority items specified in
3891 `todo-top-priorities-overrides', if this is non-nil; otherwise show
3892 `todo-top-priorities' items per category. With no prefix
3893 argument, if a top priorities file for the chosen todo files
3894 exists (see `todo-save-filtered-items-buffer'), visit this file;
3895 if there is no such file, do the same as with prefix argument
3896 `C-u'."
3897 (interactive "P")
3898 (todo-filter-items 'top arg t))
3900 (defun todo-filter-diary-items (&optional arg)
3901 "Display a list of todo diary items from different categories.
3902 The categories can be any of those in the current todo file.
3904 Called with no prefix ARG, if a diary items file for the current
3905 todo file has previously been saved (see
3906 `todo-save-filtered-items-buffer'), visit this file; if there is
3907 no such file, build the list of diary items. Called with a
3908 prefix argument, build the list even if there is a saved file of
3909 diary items."
3910 (interactive "P")
3911 (todo-filter-items 'diary arg))
3913 (defun todo-filter-diary-items-multifile (&optional arg)
3914 "Display a list of todo diary items from different categories.
3915 The categories are a subset of the categories in the files listed
3916 in `todo-filter-files', or if this nil, in the files chosen from
3917 a file selection dialog that pops up in this case.
3919 Called with no prefix ARG, if a diary items file for the chosen
3920 todo files has previously been saved (see
3921 `todo-save-filtered-items-buffer'), visit this file; if there is
3922 no such file, build the list of diary items. Called with a
3923 prefix argument, build the list even if there is a saved file of
3924 diary items."
3925 (interactive "P")
3926 (todo-filter-items 'diary arg t))
3928 (defun todo-filter-regexp-items (&optional arg)
3929 "Prompt for a regular expression and display items that match it.
3930 The matches can be from any categories in the current todo file
3931 and with non-nil option `todo-filter-done-items', can include
3932 not only todo items but also done items, including those in
3933 Archive files.
3935 Called with no prefix ARG, if a regexp items file for the current
3936 todo file has previously been saved (see
3937 `todo-save-filtered-items-buffer'), visit this file; if there is
3938 no such file, build the list of regexp items. Called with a
3939 prefix argument, build the list even if there is a saved file of
3940 regexp items."
3941 (interactive "P")
3942 (todo-filter-items 'regexp arg))
3944 (defun todo-filter-regexp-items-multifile (&optional arg)
3945 "Prompt for a regular expression and display items that match it.
3946 The matches can be from any categories in the files listed in
3947 `todo-filter-files', or if this nil, in the files chosen from a
3948 file selection dialog that pops up in this case. With non-nil
3949 option `todo-filter-done-items', the matches can include not
3950 only todo items but also done items, including those in Archive
3951 files.
3953 Called with no prefix ARG, if a regexp items file for the current
3954 todo file has previously been saved (see
3955 `todo-save-filtered-items-buffer'), visit this file; if there is
3956 no such file, build the list of regexp items. Called with a
3957 prefix argument, build the list even if there is a saved file of
3958 regexp items."
3959 (interactive "P")
3960 (todo-filter-items 'regexp arg t))
3962 (defun todo-find-filtered-items-file ()
3963 "Choose a filtered items file and visit it."
3964 (interactive)
3965 (let ((files (directory-files todo-directory t "\.tod[rty]$" t))
3966 falist file)
3967 (dolist (f files)
3968 (let ((type (cond ((equal (file-name-extension f) "todr") "regexp")
3969 ((equal (file-name-extension f) "todt") "top")
3970 ((equal (file-name-extension f) "tody") "diary"))))
3971 (push (cons (concat (todo-short-file-name f) " (" type ")") f)
3972 falist)))
3973 (setq file (completing-read "Choose a filtered items file: "
3974 falist nil t nil nil (car falist)))
3975 (setq file (cdr (assoc-string file falist)))
3976 (find-file file)
3977 (unless (derived-mode-p 'todo-filtered-items-mode)
3978 (todo-filtered-items-mode))
3979 (todo-prefix-overlays)))
3981 (defun todo-go-to-source-item ()
3982 "Display the file and category of the filtered item at point."
3983 (interactive)
3984 (let* ((str (todo-item-string))
3985 (buf (current-buffer))
3986 (res (todo-find-item str))
3987 (found (nth 0 res))
3988 (file (nth 1 res))
3989 (cat (nth 2 res)))
3990 (if (not found)
3991 (message "Category %s does not contain this item." cat)
3992 (kill-buffer buf)
3993 (set-window-buffer (selected-window)
3994 (set-buffer (find-buffer-visiting file)))
3995 (setq todo-current-todo-file file)
3996 (setq todo-category-number (todo-category-number cat))
3997 (let ((todo-show-with-done (if (or todo-filter-done-items
3998 (eq (cdr found) 'done))
4000 todo-show-with-done)))
4001 (todo-category-select))
4002 (goto-char (car found)))))
4004 (defvar todo-multiple-filter-files nil
4005 "List of files selected from `todo-multiple-filter-files' widget.")
4007 (defvar todo-multiple-filter-files-widget nil
4008 "Variable holding widget created by `todo-multiple-filter-files'.")
4010 (defun todo-multiple-filter-files ()
4011 "Pop to a buffer with a widget for choosing multiple filter files."
4012 (require 'widget)
4013 (eval-when-compile
4014 (require 'wid-edit))
4015 (with-current-buffer (get-buffer-create "*Todo Filter Files*")
4016 (pop-to-buffer (current-buffer))
4017 (erase-buffer)
4018 (kill-all-local-variables)
4019 (widget-insert "Select files for generating the top priorities list.\n\n")
4020 (setq todo-multiple-filter-files-widget
4021 (widget-create
4022 `(set ,@(mapcar (lambda (x) (list 'const x))
4023 (mapcar 'todo-short-file-name
4024 (funcall todo-files-function))))))
4025 (widget-insert "\n")
4026 (widget-create 'push-button
4027 :notify (lambda (widget &rest ignore)
4028 (setq todo-multiple-filter-files 'quit)
4029 (quit-window t)
4030 (exit-recursive-edit))
4031 "Cancel")
4032 (widget-insert " ")
4033 (widget-create 'push-button
4034 :notify (lambda (&rest ignore)
4035 (setq todo-multiple-filter-files
4036 (mapcar (lambda (f)
4037 (file-truename
4038 (concat todo-directory
4039 f ".todo")))
4040 (widget-value
4041 todo-multiple-filter-files-widget)))
4042 (quit-window t)
4043 (exit-recursive-edit))
4044 "Apply")
4045 (use-local-map widget-keymap)
4046 (widget-setup))
4047 (message "Click \"Apply\" after selecting files.")
4048 (recursive-edit))
4050 (defconst todo-filtered-items-buffer "Todo filtered items"
4051 "Initial name of buffer in Todo Filter Items mode.")
4053 (defconst todo-top-priorities-buffer "Todo top priorities"
4054 "Buffer type string for `todo-filter-items'.")
4056 (defconst todo-diary-items-buffer "Todo diary items"
4057 "Buffer type string for `todo-filter-items'.")
4059 (defconst todo-regexp-items-buffer "Todo regexp items"
4060 "Buffer type string for `todo-filter-items'.")
4062 (defun todo-filter-items (filter &optional new multifile)
4063 "Display a list of items filtered by FILTER.
4064 The values of FILTER can be `top' for top priority items, a cons
4065 of `top' and a number passed by the caller, `diary' for diary
4066 items, or `regexp' for items matching a regular expression
4067 entered by the user. The items can come from any categories in
4068 the current todo file or, with non-nil MULTIFILE, from several
4069 files. If NEW is nil, visit an appropriate file containing the
4070 list of filtered items; if there is no such file, or with non-nil
4071 NEW, build the list and display it.
4073 See the documentation strings of the commands
4074 `todo-filter-top-priorities', `todo-filter-diary-items',
4075 `todo-filter-regexp-items', and those of the corresponding
4076 multifile commands for further details."
4077 (let* ((top (eq filter 'top))
4078 (diary (eq filter 'diary))
4079 (regexp (eq filter 'regexp))
4080 (buf (cond (top todo-top-priorities-buffer)
4081 (diary todo-diary-items-buffer)
4082 (regexp todo-regexp-items-buffer)))
4083 (flist (if multifile
4084 (or todo-filter-files
4085 (progn (todo-multiple-filter-files)
4086 todo-multiple-filter-files))
4087 (list todo-current-todo-file)))
4088 (fname (if (equal flist 'quit)
4089 ;; Pressed `cancel' in t-m-f-f file selection dialog.
4090 (keyboard-quit)
4091 (concat todo-directory
4092 (mapconcat 'todo-short-file-name flist "-")
4093 (cond (top ".todt")
4094 (diary ".tody")
4095 (regexp ".todr")))))
4096 (multi (> (length flist) 1))
4097 (rxfiles (when regexp
4098 (directory-files todo-directory t ".*\\.todr$" t)))
4099 (file-exists (or (file-exists-p fname) rxfiles))
4100 bufname)
4101 (cond ((and top new (natnump new))
4102 (todo-filter-items-1 (cons 'top new) flist))
4103 ((and (not new) file-exists)
4104 (when (and rxfiles (> (length rxfiles) 1))
4105 (let ((rxf (mapcar 'todo-short-file-name rxfiles)))
4106 (setq fname (todo-absolute-file-name
4107 (completing-read "Choose a regexp items file: "
4108 rxf) 'regexp))))
4109 (find-file fname)
4110 (unless (derived-mode-p 'todo-filtered-items-mode)
4111 (todo-filtered-items-mode))
4112 (todo-prefix-overlays)
4113 (todo-check-filtered-items-file))
4115 (todo-filter-items-1 filter flist)))
4116 (dolist (s (split-string (todo-short-file-name fname) "-"))
4117 (setq bufname (if bufname
4118 (concat bufname (if (member s (mapcar
4119 'todo-short-file-name
4120 todo-files))
4121 ", " "-") s)
4122 s)))
4123 (rename-buffer (format (concat "%s for file" (if multi "s" "")
4124 " \"%s\"") buf bufname))))
4126 (defun todo-filter-items-1 (filter file-list)
4127 "Build a list of items by applying FILTER to FILE-LIST.
4128 Internal subroutine called by `todo-filter-items', which passes
4129 the values of FILTER and FILE-LIST."
4130 (let ((num (if (consp filter) (cdr filter) todo-top-priorities))
4131 (buf (get-buffer-create todo-filtered-items-buffer))
4132 (multifile (> (length file-list) 1))
4133 regexp fname bufstr cat beg end done)
4134 (if (null file-list)
4135 (user-error "No files have been chosen for filtering")
4136 (with-current-buffer buf
4137 (erase-buffer)
4138 (kill-all-local-variables)
4139 (todo-filtered-items-mode))
4140 (when (eq filter 'regexp)
4141 (setq regexp (read-string "Enter a regular expression: ")))
4142 (save-current-buffer
4143 (dolist (f file-list)
4144 ;; Before inserting file contents into temp buffer, save a modified
4145 ;; buffer visiting it.
4146 (let ((bf (find-buffer-visiting f)))
4147 (when (buffer-modified-p bf)
4148 (with-current-buffer bf (save-buffer))))
4149 (setq fname (todo-short-file-name f))
4150 (with-temp-buffer
4151 (when (and todo-filter-done-items (eq filter 'regexp))
4152 ;; If there is a corresponding archive file for the
4153 ;; todo file, insert it first and add identifiers for
4154 ;; todo-go-to-source-item.
4155 (let ((arch (concat (file-name-sans-extension f) ".toda")))
4156 (when (file-exists-p arch)
4157 (insert-file-contents arch)
4158 ;; Delete todo archive file's categories sexp.
4159 (delete-region (line-beginning-position)
4160 (1+ (line-end-position)))
4161 (save-excursion
4162 (while (not (eobp))
4163 (when (re-search-forward
4164 (concat (if todo-filter-done-items
4165 (concat "\\(?:" todo-done-string-start
4166 "\\|" todo-date-string-start
4167 "\\)")
4168 todo-date-string-start)
4169 todo-date-pattern "\\(?: "
4170 diary-time-regexp "\\)?"
4171 (if todo-filter-done-items
4172 "\\]"
4173 (regexp-quote todo-nondiary-end)) "?")
4174 nil t)
4175 (insert "(archive) "))
4176 (forward-line))))))
4177 (insert-file-contents f)
4178 ;; Delete todo file's categories sexp.
4179 (delete-region (line-beginning-position) (1+ (line-end-position)))
4180 (let (fnum)
4181 ;; Unless the number of top priorities to show was
4182 ;; passed by the caller, the file-wide value from
4183 ;; `todo-top-priorities-overrides', if non-nil, overrides
4184 ;; `todo-top-priorities'.
4185 (unless (consp filter)
4186 (setq fnum (or (nth 1 (assoc f todo-top-priorities-overrides))
4187 todo-top-priorities)))
4188 (while (re-search-forward
4189 (concat "^" (regexp-quote todo-category-beg)
4190 "\\(.+\\)\n") nil t)
4191 (setq cat (match-string 1))
4192 (let (cnum)
4193 ;; Unless the number of top priorities to show was
4194 ;; passed by the caller, the category-wide value
4195 ;; from `todo-top-priorities-overrides', if non-nil,
4196 ;; overrides a non-nil file-wide value from
4197 ;; `todo-top-priorities-overrides' as well as
4198 ;; `todo-top-priorities'.
4199 (unless (consp filter)
4200 (let ((cats (nth 2 (assoc f todo-top-priorities-overrides))))
4201 (setq cnum (or (cdr (assoc cat cats)) fnum))))
4202 (delete-region (match-beginning 0) (match-end 0))
4203 (setq beg (point)) ; First item in the current category.
4204 (setq end (if (re-search-forward
4205 (concat "^" (regexp-quote todo-category-beg))
4206 nil t)
4207 (match-beginning 0)
4208 (point-max)))
4209 (goto-char beg)
4210 (setq done
4211 (if (re-search-forward
4212 (concat "\n" (regexp-quote todo-category-done))
4213 end t)
4214 (match-beginning 0)
4215 end))
4216 (unless (and todo-filter-done-items (eq filter 'regexp))
4217 ;; Leave done items.
4218 (delete-region done end)
4219 (setq end done))
4220 (narrow-to-region beg end) ; Process only current category.
4221 (goto-char (point-min))
4222 ;; Apply the filter.
4223 (cond ((eq filter 'diary)
4224 (while (not (eobp))
4225 (if (looking-at (regexp-quote todo-nondiary-start))
4226 (todo-remove-item)
4227 (todo-forward-item))))
4228 ((eq filter 'regexp)
4229 (while (not (eobp))
4230 (if (looking-at todo-item-start)
4231 (if (string-match regexp (todo-item-string))
4232 (todo-forward-item)
4233 (todo-remove-item))
4234 ;; Kill lines that aren't part of a todo or done
4235 ;; item (empty or todo-category-done).
4236 (delete-region (line-beginning-position)
4237 (1+ (line-end-position))))
4238 ;; If last todo item in file matches regexp and
4239 ;; there are no following done items,
4240 ;; todo-category-done string is left dangling,
4241 ;; because todo-forward-item jumps over it.
4242 (if (and (eobp)
4243 (looking-back
4244 (concat (regexp-quote todo-done-string)
4245 "\n")
4246 (line-beginning-position 0)))
4247 (delete-region (point) (progn
4248 (forward-line -2)
4249 (point))))))
4250 (t ; Filter top priority items.
4251 (setq num (or cnum fnum num))
4252 (unless (zerop num)
4253 (todo-forward-item num))))
4254 (setq beg (point))
4255 ;; Delete non-top-priority items.
4256 (unless (member filter '(diary regexp))
4257 (delete-region beg end))
4258 (goto-char (point-min))
4259 ;; Add file (if using multiple files) and category tags to
4260 ;; item.
4261 (while (not (eobp))
4262 (when (re-search-forward
4263 (concat (if todo-filter-done-items
4264 (concat "\\(?:" todo-done-string-start
4265 "\\|" todo-date-string-start
4266 "\\)")
4267 todo-date-string-start)
4268 todo-date-pattern "\\(?: " diary-time-regexp
4269 "\\)?" (if todo-filter-done-items
4270 "\\]"
4271 (regexp-quote todo-nondiary-end))
4272 "?")
4273 nil t)
4274 (insert " [")
4275 (when (looking-at "(archive) ") (goto-char (match-end 0)))
4276 (insert (if multifile (concat fname ":") "") cat "]"))
4277 (forward-line))
4278 (widen)))
4279 (setq bufstr (buffer-string))
4280 (with-current-buffer buf
4281 (let (buffer-read-only)
4282 (insert bufstr)))))))
4283 (set-window-buffer (selected-window) (set-buffer buf))
4284 (todo-prefix-overlays)
4285 (goto-char (point-min)))))
4287 (defun todo-set-top-priorities (&optional arg)
4288 "Set number of top priorities shown by `todo-filter-top-priorities'.
4289 With non-nil ARG, set the number only for the current Todo
4290 category; otherwise, set the number for all categories in the
4291 current todo file.
4293 Calling this function via either of the commands
4294 `todo-set-top-priorities-in-file' or
4295 `todo-set-top-priorities-in-category' is the recommended way to
4296 set the user customizable option `todo-top-priorities-overrides'."
4297 (let* ((cat (todo-current-category))
4298 (file todo-current-todo-file)
4299 (rules todo-top-priorities-overrides)
4300 (frule (assoc-string file rules))
4301 (crules (nth 2 frule))
4302 (crule (assoc-string cat crules))
4303 (fcur (or (nth 1 frule)
4304 todo-top-priorities))
4305 (ccur (or (and arg (cdr crule))
4306 fcur))
4307 (prompt (if arg (concat "Number of top priorities in this category"
4308 " (currently %d): ")
4309 (concat "Default number of top priorities per category"
4310 " in this file (currently %d): ")))
4311 (new -1))
4312 (while (< new 0)
4313 (let ((cur (if arg ccur fcur)))
4314 (setq new (read-number (format prompt cur))
4315 prompt "Enter a non-negative number: "
4316 cur nil)))
4317 (let ((nrule (if arg
4318 (append (delete crule crules) (list (cons cat new)))
4319 (append (list file new) (list crules)))))
4320 (setq rules (cons (if arg
4321 (list file fcur nrule)
4322 nrule)
4323 (delete frule rules)))
4324 (customize-save-variable 'todo-top-priorities-overrides rules)
4325 (todo-prefix-overlays))))
4327 (defun todo-find-item (str)
4328 "Search for filtered item STR in its saved todo file.
4329 Return the list (FOUND FILE CAT), where CAT and FILE are the
4330 item's category and file, and FOUND is a cons cell if the search
4331 succeeds, whose car is the start of the item in FILE and whose
4332 cdr is `done', if the item is now a done item, `changed', if its
4333 text was truncated or augmented or, for a top priority item, if
4334 its priority has changed, and `same' otherwise."
4335 (string-match (concat (if todo-filter-done-items
4336 (concat "\\(?:" todo-done-string-start "\\|"
4337 todo-date-string-start "\\)")
4338 todo-date-string-start)
4339 todo-date-pattern "\\(?: " diary-time-regexp "\\)?"
4340 (if todo-filter-done-items
4341 "\\]"
4342 (regexp-quote todo-nondiary-end)) "?"
4343 "\\(?4: \\[\\(?3:(archive) \\)?\\(?2:.*:\\)?"
4344 "\\(?1:.*\\)\\]\\).*$") str)
4345 (let ((cat (match-string 1 str))
4346 (file (match-string 2 str))
4347 (archive (string= (match-string 3 str) "(archive) "))
4348 (filcat (match-string 4 str))
4349 (tpriority 1)
4350 (tpbuf (save-match-data (string-match "top" (buffer-name))))
4351 found)
4352 (setq str (replace-match "" nil nil str 4))
4353 (when tpbuf
4354 ;; Calculate priority of STR wrt its category.
4355 (save-excursion
4356 (while (search-backward filcat nil t)
4357 (setq tpriority (1+ tpriority)))))
4358 (setq file (if file
4359 (concat todo-directory (substring file 0 -1)
4360 (if archive ".toda" ".todo"))
4361 (if archive
4362 (concat (file-name-sans-extension
4363 todo-global-current-todo-file) ".toda")
4364 todo-global-current-todo-file)))
4365 (find-file-noselect file)
4366 (with-current-buffer (find-buffer-visiting file)
4367 (if archive
4368 (unless (derived-mode-p 'todo-archive-mode) (todo-archive-mode))
4369 (unless (derived-mode-p 'todo-mode) (todo-mode)))
4370 (save-restriction
4371 (widen)
4372 (goto-char (point-min))
4373 (let ((beg (re-search-forward
4374 (concat "^" (regexp-quote (concat todo-category-beg cat))
4375 "$")
4376 nil t))
4377 (done (save-excursion
4378 (re-search-forward
4379 (concat "^" (regexp-quote todo-category-done)) nil t)))
4380 (end (save-excursion
4381 (or (re-search-forward
4382 (concat "^" (regexp-quote todo-category-beg))
4383 nil t)
4384 (point-max)))))
4385 (setq found (when (search-forward str end t)
4386 (goto-char (match-beginning 0))))
4387 (when found
4388 (setq found
4389 (cons found (if (> (point) done)
4390 'done
4391 (let ((cpriority 1))
4392 (when tpbuf
4393 (save-excursion
4394 ;; Not top item in category.
4395 (while (> (point) (1+ beg))
4396 (let ((opoint (point)))
4397 (todo-backward-item)
4398 ;; Can't move backward beyond
4399 ;; first item in file.
4400 (unless (= (point) opoint)
4401 (setq cpriority (1+ cpriority)))))))
4402 (if (and (= tpriority cpriority)
4403 ;; Proper substring is not the same.
4404 (string= (todo-item-string)
4405 str))
4406 'same
4407 'changed)))))))))
4408 (list found file cat)))
4410 (defun todo-check-filtered-items-file ()
4411 "Check if filtered items file is up to date and a show suitable message."
4412 ;; (catch 'old
4413 (let ((count 0))
4414 (while (not (eobp))
4415 (let* ((item (todo-item-string))
4416 (found (car (todo-find-item item))))
4417 (unless (eq (cdr found) 'same)
4418 (save-excursion
4419 (overlay-put (make-overlay (todo-item-start) (todo-item-end))
4420 'face 'todo-search))
4421 (setq count (1+ count))))
4422 ;; (throw 'old (message "The marked item is not up to date.")))
4423 (todo-forward-item))
4424 (if (zerop count)
4425 (message "Filtered items file is up to date.")
4426 (message (concat "The highlighted item" (if (= count 1) " is " "s are ")
4427 "not up to date."
4428 ;; "\nType <return> on item for details."
4429 )))))
4431 (defun todo-filter-items-filename ()
4432 "Return absolute file name for saving this Filtered Items buffer."
4433 (let ((bufname (buffer-name)))
4434 (string-match "\"\\([^\"]+\\)\"" bufname)
4435 (let* ((filename-str (substring bufname (match-beginning 1) (match-end 1)))
4436 (filename-base (replace-regexp-in-string ", " "-" filename-str))
4437 (top-priorities (string-match "top priorities" bufname))
4438 (diary-items (string-match "diary items" bufname))
4439 (regexp-items (string-match "regexp items" bufname)))
4440 (when regexp-items
4441 (let ((prompt (concat "Enter a short identifying string"
4442 " to make this file name unique: ")))
4443 (setq filename-base (concat filename-base "-" (read-string prompt)))))
4444 (concat todo-directory filename-base
4445 (cond (top-priorities ".todt")
4446 (diary-items ".tody")
4447 (regexp-items ".todr"))))))
4449 (defun todo-save-filtered-items-buffer ()
4450 "Save current Filtered Items buffer to a file.
4451 If the file already exists, overwrite it only on confirmation."
4452 (let ((filename (or (buffer-file-name) (todo-filter-items-filename))))
4453 (write-file filename t)))
4455 ;; -----------------------------------------------------------------------------
4456 ;;; Printing Todo mode buffers
4457 ;; -----------------------------------------------------------------------------
4459 (defcustom todo-print-buffer-function 'ps-print-buffer-with-faces
4460 "Function called by the command `todo-print-buffer'."
4461 :type 'symbol
4462 :group 'todo)
4464 (defvar todo-print-buffer "*Todo Print*"
4465 "Name of buffer with printable version of Todo mode buffer.")
4467 (defun todo-print-buffer (&optional to-file)
4468 "Produce a printable version of the current Todo mode buffer.
4469 This converts overlays and soft line wrapping and, depending on
4470 the value of `todo-print-buffer-function', includes faces. With
4471 non-nil argument TO-FILE write the printable version to a file;
4472 otherwise, send it to the default printer."
4473 (interactive)
4474 (let ((buf todo-print-buffer)
4475 (header (cond
4476 ((eq major-mode 'todo-mode)
4477 (concat "Todo File: "
4478 (todo-short-file-name todo-current-todo-file)
4479 "\nCategory: " (todo-current-category)))
4480 ((eq major-mode 'todo-filtered-items-mode)
4481 (buffer-name))))
4482 (prefix (propertize (concat todo-prefix " ")
4483 'face 'todo-prefix-string))
4484 (num 0)
4485 (fill-prefix (make-string todo-indent-to-here 32))
4486 (content (buffer-string))
4487 file)
4488 (with-current-buffer (get-buffer-create buf)
4489 (insert content)
4490 (goto-char (point-min))
4491 (while (not (eobp))
4492 (let ((beg (point))
4493 (end (save-excursion (todo-item-end))))
4494 (when todo-number-prefix
4495 (setq num (1+ num))
4496 (setq prefix (propertize (concat (number-to-string num) " ")
4497 'face 'todo-prefix-string)))
4498 (insert prefix)
4499 (fill-region beg end))
4500 ;; Calling todo-forward-item infloops at todo-item-start due to
4501 ;; non-overlay prefix, so search for item start instead.
4502 (if (re-search-forward todo-item-start nil t)
4503 (beginning-of-line)
4504 (goto-char (point-max))))
4505 (if (re-search-backward (concat "^" (regexp-quote todo-category-done))
4506 nil t)
4507 (replace-match todo-done-separator))
4508 (goto-char (point-min))
4509 (insert header)
4510 (newline 2)
4511 (if to-file
4512 (let ((file (read-file-name "Print to file: ")))
4513 (funcall todo-print-buffer-function file))
4514 (funcall todo-print-buffer-function)))
4515 (kill-buffer buf)))
4517 (defun todo-print-buffer-to-file ()
4518 "Save printable version of this Todo mode buffer to a file."
4519 (interactive)
4520 (todo-print-buffer t))
4522 ;; -----------------------------------------------------------------------------
4523 ;;; Legacy Todo mode files
4524 ;; -----------------------------------------------------------------------------
4526 (defcustom todo-legacy-date-time-regexp
4527 (concat "\\(?1:[0-9]\\{4\\}\\)-\\(?2:[0-9]\\{2\\}\\)-"
4528 "\\(?3:[0-9]\\{2\\}\\) \\(?4:[0-9]\\{2\\}:[0-9]\\{2\\}\\)")
4529 "Regexp matching legacy todo-mode.el item date-time strings.
4530 In order for `todo-convert-legacy-files' to correctly convert
4531 this string to the current Todo mode format, the regexp must
4532 contain four explicitly numbered groups (see `(elisp) Regexp
4533 Backslash'), where group 1 matches a string for the year, group 2
4534 a string for the month, group 3 a string for the day and group 4
4535 a string for the time. The default value converts date-time
4536 strings built using the default value of
4537 `todo-time-string-format' from todo-mode.el."
4538 :type 'regexp
4539 :group 'todo)
4541 (defun todo-convert-legacy-date-time ()
4542 "Return converted date-time string.
4543 Helper function for `todo-convert-legacy-files'."
4544 (let* ((year (match-string 1))
4545 (month (match-string 2))
4546 (monthname (calendar-month-name (string-to-number month) t))
4547 (day (match-string 3))
4548 (time (match-string 4))
4549 dayname)
4550 (replace-match "")
4551 (insert (mapconcat 'eval calendar-date-display-form "")
4552 (when time (concat " " time)))))
4554 (defun todo-convert-legacy-files ()
4555 "Convert legacy todo files to the current Todo mode format.
4556 The old-style files named by the variables `todo-file-do' and
4557 `todo-file-done' from the old package are converted to the new
4558 format and saved (the latter as a todo archive file) with a new
4559 name in `todo-directory'. See also the documentation string of
4560 `todo-legacy-date-time-regexp' for further details."
4561 (interactive)
4562 ;; If there are user customizations of legacy options, use them,
4563 ;; otherwise use the legacy default values.
4564 (let ((todo-file-do-tem (if (boundp 'todo-file-do)
4565 todo-file-do
4566 (locate-user-emacs-file "todo-do" ".todo-do")))
4567 (todo-file-done-tem (if (boundp 'todo-file-done)
4568 todo-file-done
4569 (locate-user-emacs-file "todo-done" ".todo-done")))
4570 (todo-initials-tem (and (boundp 'todo-initials) todo-initials))
4571 (todo-entry-prefix-function-tem (and (boundp 'todo-entry-prefix-function)
4572 todo-entry-prefix-function))
4573 todo-prefix-tem)
4574 ;; Convert `todo-file-do'.
4575 (if (not (file-exists-p todo-file-do-tem))
4576 (message "No legacy todo file exists")
4577 (let ((default "todo-do-conv")
4578 file archive-sexp)
4579 (with-temp-buffer
4580 (insert-file-contents todo-file-do-tem)
4581 ;; Eliminate old-style local variables list in first line.
4582 (delete-region (line-beginning-position) (1+ (line-end-position)))
4583 (search-forward " --- " nil t) ; Legacy todo-category-beg.
4584 (setq todo-prefix-tem (buffer-substring-no-properties
4585 (line-beginning-position) (match-beginning 0)))
4586 (goto-char (point-min))
4587 (while (not (eobp))
4588 (cond
4589 ;; Old-style category start delimiter.
4590 ((looking-at (regexp-quote (concat todo-prefix-tem " --- ")))
4591 (replace-match todo-category-beg))
4592 ;; Old-style category end delimiter.
4593 ((looking-at (regexp-quote "--- End"))
4594 (replace-match ""))
4595 ;; Old-style category separator.
4596 ((looking-at (regexp-quote
4597 (concat todo-prefix-tem " "
4598 (make-string 75 ?-))))
4599 (replace-match todo-category-done))
4600 ;; Old-style item header (date/time/initials).
4601 ((looking-at (concat (regexp-quote todo-prefix-tem) " "
4602 (if todo-entry-prefix-function-tem
4603 (funcall todo-entry-prefix-function-tem)
4604 (concat todo-legacy-date-time-regexp " "
4605 (if todo-initials-tem
4606 (regexp-quote todo-initials-tem)
4607 "[^:]*")
4608 ":"))))
4609 (todo-convert-legacy-date-time)))
4610 (forward-line))
4611 (setq file (concat todo-directory
4612 (read-string
4613 (format "Save file as (default \"%s\"): " default)
4614 nil nil default)
4615 ".todo"))
4616 (unless (file-exists-p todo-directory)
4617 (make-directory todo-directory))
4618 (write-region (point-min) (point-max) file nil 'nomessage nil t))
4619 (with-temp-buffer
4620 (insert-file-contents file)
4621 (let ((todo-categories (todo-make-categories-list t)))
4622 (todo-update-categories-sexp)
4623 (todo-check-format))
4624 (write-region (point-min) (point-max) file nil 'nomessage))
4625 (setq todo-files (funcall todo-files-function))
4626 ;; Convert `todo-file-done'.
4627 (when (file-exists-p todo-file-done-tem)
4628 (with-temp-buffer
4629 (insert-file-contents todo-file-done-tem)
4630 (let ((beg (make-marker))
4631 (end (make-marker))
4632 cat cats comment item)
4633 (while (not (eobp))
4634 (when (looking-at todo-legacy-date-time-regexp)
4635 (set-marker beg (point))
4636 (todo-convert-legacy-date-time)
4637 (set-marker end (point))
4638 (goto-char beg)
4639 (insert "[" todo-done-string)
4640 (goto-char end)
4641 (insert "]")
4642 (forward-char)
4643 (when (looking-at todo-legacy-date-time-regexp)
4644 (todo-convert-legacy-date-time))
4645 (when (looking-at (concat " " (if todo-initials-tem
4646 (regexp-quote
4647 todo-initials-tem)
4648 "[^:]*")
4649 ":"))
4650 (replace-match "")))
4651 (if (re-search-forward
4652 (concat "^" todo-legacy-date-time-regexp) nil t)
4653 (goto-char (match-beginning 0))
4654 (goto-char (point-max)))
4655 (backward-char)
4656 (when (looking-back "\\[\\([^][]+\\)\\]")
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 (when (looking-back "(\\(.*\\)) " (line-beginning-position))
4664 (setq comment (match-string 1))
4665 (replace-match "")
4666 (insert "[" todo-comment-string ": " comment "]"))
4667 (set-marker end (point))
4668 (if (member cat cats)
4669 ;; If item is already in its category, leave it there.
4670 (unless (save-excursion
4671 (re-search-backward
4672 (concat "^" (regexp-quote todo-category-beg)
4673 "\\(.*\\)$") nil t)
4674 (string= (match-string 1) cat))
4675 ;; Else move it to its category.
4676 (setq item (buffer-substring-no-properties beg end))
4677 (delete-region beg (1+ end))
4678 (set-marker beg (point))
4679 (re-search-backward
4680 (concat "^"
4681 (regexp-quote (concat todo-category-beg cat))
4682 "$")
4683 nil t)
4684 (forward-line)
4685 (if (re-search-forward
4686 (concat "^" (regexp-quote todo-category-beg)
4687 "\\(.*\\)$") nil t)
4688 (progn (goto-char (match-beginning 0))
4689 (newline)
4690 (forward-line -1))
4691 (goto-char (point-max)))
4692 (insert item "\n")
4693 (goto-char beg))
4694 (push cat cats)
4695 (goto-char beg)
4696 (insert todo-category-beg cat "\n\n"
4697 todo-category-done "\n"))
4698 (forward-line))
4699 (set-marker beg nil)
4700 (set-marker end nil))
4701 (setq file (concat (file-name-sans-extension file) ".toda"))
4702 (write-region (point-min) (point-max) file nil 'nomessage nil t))
4703 (with-temp-buffer
4704 (insert-file-contents file)
4705 (let* ((todo-categories (todo-make-categories-list t)))
4706 (todo-update-categories-sexp)
4707 (todo-check-format))
4708 (write-region (point-min) (point-max) file nil 'nomessage)
4709 (setq archive-sexp (read (buffer-substring-no-properties
4710 (line-beginning-position)
4711 (line-end-position)))))
4712 (setq file (concat (file-name-sans-extension file) ".todo"))
4713 ;; Update categories sexp of converted todo file again, adding
4714 ;; counts of archived items.
4715 (with-temp-buffer
4716 (insert-file-contents file)
4717 (let ((sexp (read (buffer-substring-no-properties
4718 (line-beginning-position)
4719 (line-end-position)))))
4720 (dolist (cat sexp)
4721 (let ((archive-cat (assoc (car cat) archive-sexp)))
4722 (if archive-cat
4723 (aset (cdr cat) 3 (aref (cdr archive-cat) 2)))))
4724 (delete-region (line-beginning-position) (line-end-position))
4725 (prin1 sexp (current-buffer)))
4726 (write-region (point-min) (point-max) file nil 'nomessage))
4727 (setq todo-archives (funcall todo-files-function t)))
4728 (todo-reevaluate-filelist-defcustoms)
4729 (when (y-or-n-p (concat "Format conversion done; do you want to "
4730 "visit the converted file now? "))
4731 (setq todo-current-todo-file file)
4732 (unless todo-default-todo-file
4733 ;; We just initialized the first todo file, so make it the
4734 ;; default now to avoid an infinite recursion with todo-show.
4735 (setq todo-default-todo-file (todo-short-file-name file)))
4736 (todo-show))))))
4738 ;; -----------------------------------------------------------------------------
4739 ;;; Utility functions for todo files, categories and items
4740 ;; -----------------------------------------------------------------------------
4742 (defun todo-absolute-file-name (name &optional type)
4743 "Return the absolute file name of short todo file NAME.
4744 With TYPE `archive' or `top' return the absolute file name of the
4745 short todo archive or top priorities file name, respectively."
4746 ;; No-op if there is no todo file yet (i.e. don't concatenate nil).
4747 (when name
4748 (file-truename
4749 (concat todo-directory name
4750 (cond ((eq type 'archive) ".toda")
4751 ((eq type 'top) ".todt")
4752 ((eq type 'diary) ".tody")
4753 ((eq type 'regexp) ".todr")
4754 (t ".todo"))))))
4756 (defun todo-check-file (file)
4757 "Check the state associated with FILE and update it if necessary.
4758 If FILE exists, return t. If it does not exist and there is no
4759 live buffer with its content, return nil; if there is such a
4760 buffer and the user tries to show it, ask whether to restore
4761 FILE, and if confirmed, do so and return t; else delete the
4762 buffer, clean up the state and return nil."
4763 (setq todo-files (funcall todo-files-function))
4764 (setq todo-archives (funcall todo-files-function t))
4765 (if (file-exists-p file)
4767 (setq todo-visited (delete file todo-visited))
4768 (let ((buf (find-buffer-visiting file)))
4769 (if (and buf
4770 (y-or-n-p
4771 (concat
4772 (format (concat "Todo file \"%s\" has been deleted but "
4773 "its content is still in a buffer!\n")
4774 (todo-short-file-name file))
4775 "Save that buffer and restore the todo file? ")))
4776 (progn
4777 (with-current-buffer buf (save-buffer))
4778 (setq todo-files (funcall todo-files-function))
4779 (setq todo-archives (funcall todo-files-function t))
4781 (let* ((files (append todo-files todo-archives))
4782 (tctf todo-current-todo-file)
4783 (tgctf todo-global-current-todo-file)
4784 (tdtf (todo-absolute-file-name todo-default-todo-file)))
4785 (unless (or (not todo-current-todo-file)
4786 (member todo-current-todo-file files))
4787 (setq todo-current-todo-file nil))
4788 (unless (or (not todo-global-current-todo-file)
4789 (member todo-global-current-todo-file files))
4790 (setq todo-global-current-todo-file nil))
4791 (unless (or (not todo-default-todo-file)
4792 (member todo-default-todo-file files))
4793 (setq todo-default-todo-file (todo-short-file-name
4794 (car todo-files))))
4795 (todo-reevaluate-filelist-defcustoms)
4796 (when buf (kill-buffer buf))
4797 nil)))))
4799 (defun todo-category-number (cat)
4800 "Return the number of category CAT in this todo file.
4801 The buffer-local variable `todo-category-number' holds this
4802 number as its value."
4803 (let ((categories (mapcar 'car todo-categories)))
4804 (setq todo-category-number
4805 ;; Increment by one, so that the number of the first
4806 ;; category is one rather than zero.
4807 (1+ (- (length categories)
4808 (length (member cat categories)))))))
4810 (defun todo-current-category ()
4811 "Return the name of the current category."
4812 (car (nth (1- todo-category-number) todo-categories)))
4814 (defun todo-category-select ()
4815 "Display the current category correctly."
4816 (let ((name (todo-current-category))
4817 cat-begin cat-end done-start done-sep-start done-end)
4818 (widen)
4819 (goto-char (point-min))
4820 (re-search-forward
4821 (concat "^" (regexp-quote (concat todo-category-beg name)) "$") nil t)
4822 (setq cat-begin (1+ (line-end-position)))
4823 (setq cat-end (if (re-search-forward
4824 (concat "^" (regexp-quote todo-category-beg)) nil t)
4825 (match-beginning 0)
4826 (point-max)))
4827 (setq mode-line-buffer-identification
4828 (funcall todo-mode-line-function name))
4829 (narrow-to-region cat-begin cat-end)
4830 (todo-prefix-overlays)
4831 (goto-char (point-min))
4832 (if (re-search-forward (concat "\n\\(" (regexp-quote todo-category-done)
4833 "\\)") nil t)
4834 (progn
4835 (setq done-start (match-beginning 0))
4836 (setq done-sep-start (match-beginning 1))
4837 (setq done-end (match-end 0)))
4838 (error "Category %s is missing todo-category-done string" name))
4839 (if todo-show-done-only
4840 (narrow-to-region (1+ done-end) (point-max))
4841 (when (and todo-show-with-done
4842 (re-search-forward todo-done-string-start nil t))
4843 ;; Now we want to see the done items, so reset displayed end to end of
4844 ;; done items.
4845 (setq done-start cat-end)
4846 ;; Make display overlay for done items separator string, unless there
4847 ;; already is one.
4848 (let* ((done-sep todo-done-separator)
4849 (ov (progn (goto-char done-sep-start)
4850 (todo-get-overlay 'separator))))
4851 (unless ov
4852 (setq ov (make-overlay done-sep-start done-end))
4853 (overlay-put ov 'todo 'separator)
4854 (overlay-put ov 'display done-sep))))
4855 (narrow-to-region (point-min) done-start)
4856 ;; Loading this from todo-mode, or adding it to the mode hook, causes
4857 ;; Emacs to hang in todo-item-start, at (looking-at todo-item-start).
4858 (when todo-highlight-item
4859 (require 'hl-line)
4860 (hl-line-mode 1)))))
4862 (defun todo-get-count (type &optional category)
4863 "Return count of TYPE items in CATEGORY.
4864 If CATEGORY is nil, default to the current category."
4865 (let* ((cat (or category (todo-current-category)))
4866 (counts (cdr (assoc cat todo-categories)))
4867 (idx (cond ((eq type 'todo) 0)
4868 ((eq type 'diary) 1)
4869 ((eq type 'done) 2)
4870 ((eq type 'archived) 3))))
4871 (aref counts idx)))
4873 (defun todo-update-count (type increment &optional category)
4874 "Change count of TYPE items in CATEGORY by integer INCREMENT.
4875 With nil or omitted CATEGORY, default to the current category."
4876 (let* ((cat (or category (todo-current-category)))
4877 (counts (cdr (assoc cat todo-categories)))
4878 (idx (cond ((eq type 'todo) 0)
4879 ((eq type 'diary) 1)
4880 ((eq type 'done) 2)
4881 ((eq type 'archived) 3))))
4882 (aset counts idx (+ increment (aref counts idx)))))
4884 (defun todo-set-categories ()
4885 "Set `todo-categories' from the sexp at the top of the file."
4886 ;; New archive files created by `todo-move-category' are empty, which would
4887 ;; make the sexp test fail and raise an error, so in this case we skip it.
4888 (unless (zerop (buffer-size))
4889 (save-excursion
4890 (save-restriction
4891 (widen)
4892 (goto-char (point-min))
4893 (setq todo-categories
4894 (if (looking-at "\(\(\"")
4895 (read (buffer-substring-no-properties
4896 (line-beginning-position)
4897 (line-end-position)))
4898 (error "Invalid or missing todo-categories sexp")))))))
4900 (defun todo-update-categories-sexp ()
4901 "Update the `todo-categories' sexp at the top of the file."
4902 (let (buffer-read-only)
4903 (save-excursion
4904 (save-restriction
4905 (widen)
4906 (goto-char (point-min))
4907 (if (looking-at (concat "^" (regexp-quote todo-category-beg)))
4908 (progn (newline) (goto-char (point-min)) ; Make space for sexp.
4909 (setq todo-categories (todo-make-categories-list t)))
4910 (delete-region (line-beginning-position) (line-end-position)))
4911 (prin1 todo-categories (current-buffer))))))
4913 (defun todo-make-categories-list (&optional force)
4914 "Return an alist of todo categories and their item counts.
4915 With non-nil argument FORCE parse the entire file to build the
4916 list; otherwise, get the value by reading the sexp at the top of
4917 the file."
4918 (setq todo-categories nil)
4919 (save-excursion
4920 (save-restriction
4921 (widen)
4922 (goto-char (point-min))
4923 (let (counts cat archive)
4924 ;; If the file is a todo file and has archived items, identify the
4925 ;; archive, in order to count its items. But skip this with
4926 ;; `todo-convert-legacy-files', since that converts filed items to
4927 ;; archived items.
4928 (when buffer-file-name ; During conversion there is no file yet.
4929 ;; If the file is an archive, it doesn't have an archive.
4930 (unless (member (file-truename buffer-file-name)
4931 (funcall todo-files-function t))
4932 (setq archive (concat (file-name-sans-extension
4933 todo-current-todo-file) ".toda"))))
4934 (while (not (eobp))
4935 (cond ((looking-at (concat (regexp-quote todo-category-beg)
4936 "\\(.*\\)\n"))
4937 (setq cat (match-string-no-properties 1))
4938 ;; Counts for each category: [todo diary done archive]
4939 (setq counts (make-vector 4 0))
4940 (setq todo-categories
4941 (append todo-categories (list (cons cat counts))))
4942 ;; Add archived item count to the todo file item counts.
4943 ;; Make sure to include newly created archives, e.g. due to
4944 ;; todo-move-category.
4945 (when (member archive (funcall todo-files-function t))
4946 (let ((archive-count 0)
4947 (visiting (find-buffer-visiting archive)))
4948 (with-current-buffer (or visiting
4949 (find-file-noselect archive))
4950 (save-excursion
4951 (save-restriction
4952 (widen)
4953 (goto-char (point-min))
4954 (when (re-search-forward
4955 (concat "^" (regexp-quote todo-category-beg)
4956 cat "$")
4957 (point-max) t)
4958 (forward-line)
4959 (while (not (or (looking-at
4960 (concat
4961 (regexp-quote todo-category-beg)
4962 "\\(.*\\)\n"))
4963 (eobp)))
4964 (when (looking-at todo-done-string-start)
4965 (setq archive-count (1+ archive-count)))
4966 (forward-line)))))
4967 (unless visiting (kill-buffer)))
4968 (todo-update-count 'archived archive-count cat))))
4969 ((looking-at todo-done-string-start)
4970 (todo-update-count 'done 1 cat))
4971 ((looking-at (concat "^\\("
4972 (regexp-quote diary-nonmarking-symbol)
4973 "\\)?" todo-date-pattern))
4974 (todo-update-count 'diary 1 cat)
4975 (todo-update-count 'todo 1 cat))
4976 ((looking-at (concat todo-date-string-start todo-date-pattern))
4977 (todo-update-count 'todo 1 cat))
4978 ;; If first line is todo-categories list, use it and end loop
4979 ;; -- unless FORCEd to scan whole file.
4980 ((bobp)
4981 (unless force
4982 (setq todo-categories (read (buffer-substring-no-properties
4983 (line-beginning-position)
4984 (line-end-position))))
4985 (goto-char (1- (point-max))))))
4986 (forward-line)))))
4987 todo-categories)
4989 (defun todo-repair-categories-sexp ()
4990 "Repair corrupt todo file categories sexp.
4991 This should only be needed as a consequence of careless manual
4992 editing or a bug in todo.el.
4994 *Warning*: Calling this command restores the category order to
4995 the list element order in the todo file categories sexp, so any
4996 order changes made in Todo Categories mode will have to be made
4997 again."
4998 (interactive)
4999 (let ((todo-categories (todo-make-categories-list t)))
5000 (todo-update-categories-sexp)))
5002 (defun todo-check-format ()
5003 "Signal an error if the current todo file is ill-formatted.
5004 Otherwise return t. Display a message if the file is well-formed
5005 but the categories sexp differs from the current value of
5006 `todo-categories'."
5007 (save-excursion
5008 (save-restriction
5009 (widen)
5010 (goto-char (point-min))
5011 (let* ((cats (prin1-to-string todo-categories))
5012 (ssexp (buffer-substring-no-properties (line-beginning-position)
5013 (line-end-position)))
5014 (sexp (read ssexp)))
5015 ;; Check the first line for `todo-categories' sexp.
5016 (dolist (c sexp)
5017 (let ((v (cdr c)))
5018 (unless (and (stringp (car c))
5019 (vectorp v)
5020 (= 4 (length v)))
5021 (user-error "Invalid or missing todo-categories sexp"))))
5022 (forward-line)
5023 ;; Check well-formedness of categories.
5024 (let ((legit (concat
5025 "\\(^" (regexp-quote todo-category-beg) "\\)"
5026 "\\|\\(" todo-date-string-start todo-date-pattern "\\)"
5027 "\\|\\(^[ \t]+[^ \t]*\\)"
5028 "\\|^$"
5029 "\\|\\(^" (regexp-quote todo-category-done) "\\)"
5030 "\\|\\(" todo-done-string-start "\\)")))
5031 (while (not (eobp))
5032 (unless (looking-at legit)
5033 (user-error "Illegitimate todo file format at line %d"
5034 (line-number-at-pos (point))))
5035 (forward-line)))
5036 ;; Warn user if categories sexp has changed.
5037 (unless (string= ssexp cats)
5038 (message (concat "The sexp at the beginning of the file differs "
5039 "from the value of ‘todo-categories’.\n"
5040 "If the sexp is wrong, you can fix it with "
5041 "M-x todo-repair-categories-sexp,\n"
5042 "but note this reverts any changes you have "
5043 "made in the order of the categories."))))))
5046 (defun todo-item-start ()
5047 "Move to start of current todo item and return its position."
5048 (unless (or
5049 ;; Buffer is empty (invocation possible e.g. via todo-forward-item
5050 ;; from todo-filter-items when processing category with no todo
5051 ;; items).
5052 (eq (point-min) (point-max))
5053 ;; Point is on the empty line below category's last todo item...
5054 (and (looking-at "^$")
5055 (or (eobp) ; ...and done items are hidden...
5056 (save-excursion ; ...or done items are visible.
5057 (forward-line)
5058 (looking-at (concat "^"
5059 (regexp-quote todo-category-done))))))
5060 ;; Buffer is widened.
5061 (looking-at (regexp-quote todo-category-beg)))
5062 (goto-char (line-beginning-position))
5063 (while (not (looking-at todo-item-start))
5064 (forward-line -1))
5065 (point)))
5067 (defun todo-item-end ()
5068 "Move to end of current todo item and return its position."
5069 ;; Items cannot end with a blank line.
5070 (unless (looking-at "^$")
5071 (let* ((done (todo-done-item-p))
5072 (to-lim nil)
5073 ;; For todo items, end is before the done items section, for done
5074 ;; items, end is before the next category. If these limits are
5075 ;; missing or inaccessible, end it before the end of the buffer.
5076 (lim (if (save-excursion
5077 (re-search-forward
5078 (concat "^" (regexp-quote (if done
5079 todo-category-beg
5080 todo-category-done)))
5081 nil t))
5082 (progn (setq to-lim t) (match-beginning 0))
5083 (point-max))))
5084 (when (bolp) (forward-char)) ; Find start of next item.
5085 (goto-char (if (re-search-forward todo-item-start lim t)
5086 (match-beginning 0)
5087 (if to-lim lim (point-max))))
5088 ;; For last todo item, skip back over the empty line before the done
5089 ;; items section, else just back to the end of the previous line.
5090 (backward-char (when (and to-lim (not done) (eq (point) lim)) 2))
5091 (point))))
5093 (defun todo-item-string ()
5094 "Return bare text of current item as a string."
5095 (let ((opoint (point))
5096 (start (todo-item-start))
5097 (end (todo-item-end)))
5098 (goto-char opoint)
5099 (and start end (buffer-substring-no-properties start end))))
5101 (defun todo-forward-item (&optional count)
5102 "Move point COUNT items down (by default, move down by one item)."
5103 (let* ((not-done (not (or (todo-done-item-p) (looking-at "^$"))))
5104 (start (line-end-position)))
5105 (goto-char start)
5106 (if (re-search-forward todo-item-start nil t (or count 1))
5107 (goto-char (match-beginning 0))
5108 (goto-char (point-max)))
5109 ;; If points advances by one from a todo to a done item, go back
5110 ;; to the space above todo-done-separator, since that is a
5111 ;; legitimate place to insert an item. But skip this space if
5112 ;; count > 1, since that should only stop on an item.
5113 (when (and not-done (todo-done-item-p) (not count))
5114 ;; (if (or (not count) (= count 1))
5115 (re-search-backward "^$" start t))));)
5116 ;; The preceding sexp is insufficient when buffer is not narrowed,
5117 ;; since there could be no done items in this category, so the
5118 ;; search puts us on first todo item of next category. Does this
5119 ;; ever happen? If so:
5120 ;; (let ((opoint) (point))
5121 ;; (forward-line -1)
5122 ;; (when (or (not count) (= count 1))
5123 ;; (cond ((looking-at (concat "^" (regexp-quote todo-category-beg)))
5124 ;; (forward-line -2))
5125 ;; ((looking-at (concat "^" (regexp-quote todo-category-done)))
5126 ;; (forward-line -1))
5127 ;; (t
5128 ;; (goto-char opoint)))))))
5130 (defun todo-backward-item (&optional count)
5131 "Move point up to start of item with next higher priority.
5132 With positive numerical prefix COUNT, move point COUNT items
5133 upward.
5135 If the category's done items are visible, this command called
5136 with a prefix argument only moves point to a higher item, e.g.,
5137 with point on the first done item and called with prefix 1, it
5138 moves to the last todo item; but if called with point on the
5139 first done item without a prefix argument, it moves point the the
5140 empty line above the done items separator."
5141 (let* ((done (todo-done-item-p)))
5142 (todo-item-start)
5143 (unless (bobp)
5144 (re-search-backward todo-item-start nil t (or count 1)))
5145 ;; Unless this is a regexp filtered items buffer (which can contain
5146 ;; intermixed todo and done items), if points advances by one from a
5147 ;; done to a todo item, go back to the space above
5148 ;; todo-done-separator, since that is a legitimate place to insert an
5149 ;; item. But skip this space if count > 1, since that should only
5150 ;; stop on an item.
5151 (when (and done (not (todo-done-item-p)) (not count)
5152 ;(or (not count) (= count 1))
5153 (not (equal (buffer-name) todo-regexp-items-buffer)))
5154 (re-search-forward (concat "^" (regexp-quote todo-category-done))
5155 nil t)
5156 (forward-line -1))))
5158 (defun todo-remove-item ()
5159 "Internal function called in editing, deleting or moving items."
5160 (let* ((end (progn (todo-item-end) (1+ (point))))
5161 (beg (todo-item-start))
5162 (ov (todo-get-overlay 'prefix)))
5163 (when ov (delete-overlay ov))
5164 (delete-region beg end)))
5166 (defun todo-diary-item-p ()
5167 "Return non-nil if item at point has diary entry format."
5168 (save-excursion
5169 (when (todo-item-string) ; Exclude empty lines.
5170 (todo-item-start)
5171 (not (looking-at (regexp-quote todo-nondiary-start))))))
5173 ;; This duplicates the item locating code from diary-goto-entry, but
5174 ;; without the marker code, to test whether the latter is dispensable.
5175 ;; If it is, diary-goto-entry can be simplified. The code duplication
5176 ;; here can also be eliminated, leaving only the widening and category
5177 ;; selection, and instead of :override advice :around can be used.
5179 (defun todo-diary-goto-entry (button)
5180 "Jump to the diary entry for the BUTTON at point.
5181 If the entry is a todo item, display its category properly.
5182 Overrides `diary-goto-entry'."
5183 ;; Locate the diary item in its source file.
5184 (let* ((locator (button-get button 'locator))
5185 (file (cadr locator))
5186 (date (regexp-quote (nth 2 locator)))
5187 (content (regexp-quote (nth 3 locator))))
5188 (if (not (and (file-exists-p file)
5189 (find-file-other-window file)))
5190 (message "Unable to locate this diary entry")
5191 ;; If it's a Todo file, make sure it's in Todo mode.
5192 (when (and (equal (file-name-directory (file-truename file))
5193 (file-truename todo-directory))
5194 (not (derived-mode-p 'todo-mode)))
5195 (todo-mode))
5196 (when (eq major-mode 'todo-mode) (widen))
5197 (goto-char (point-min))
5198 (when (re-search-forward (format "%s.*\\(%s\\)" date content) nil t)
5199 (goto-char (match-beginning 1)))
5200 ;; If it's a todo item, determine its category and display the
5201 ;; category properly.
5202 (when (eq major-mode 'todo-mode)
5203 (let ((opoint (point)))
5204 (re-search-backward (concat "^" (regexp-quote todo-category-beg)
5205 "\\(.*\\)\n") nil t)
5206 (todo-category-number (match-string 1))
5207 (todo-category-select)
5208 (goto-char opoint))))))
5210 (add-function :override diary-goto-entry-function #'todo-diary-goto-entry)
5212 (defun todo-revert-buffer (&optional ignore-auto noconfirm)
5213 "Call `revert-buffer', preserving buffer's current modes.
5214 Also preserve category display, if applicable."
5215 (interactive (list (not current-prefix-arg)))
5216 (let ((revert-buffer-function nil))
5217 (revert-buffer ignore-auto noconfirm 'preserve-modes)
5218 (when (memq major-mode '(todo-mode todo-archive-mode))
5219 (todo-category-select))))
5221 (defun todo-desktop-save-buffer (_dir)
5222 `((catnum . ,(todo-category-number (todo-current-category)))))
5224 (declare-function desktop-restore-file-buffer "desktop"
5225 (buffer-filename buffer-name buffer-misc))
5227 (defun todo-restore-desktop-buffer (file buffer misc)
5228 (desktop-restore-file-buffer file buffer misc)
5229 (with-current-buffer buffer
5230 (widen)
5231 (let ((todo-category-number (cdr (assq 'catnum misc))))
5232 (todo-category-select))))
5234 (add-to-list 'desktop-buffer-mode-handlers
5235 '(todo-mode . todo-restore-desktop-buffer))
5237 (defun todo-done-item-p ()
5238 "Return non-nil if item at point is a done item."
5239 (save-excursion
5240 (todo-item-start)
5241 (looking-at todo-done-string-start)))
5243 (defun todo-done-item-section-p ()
5244 "Return non-nil if point is in category's done items section."
5245 (save-excursion
5246 (or (re-search-backward (concat "^" (regexp-quote todo-category-done))
5247 nil t)
5248 (progn (goto-char (point-min))
5249 (looking-at todo-done-string-start)))))
5251 (defun todo--user-error-if-marked-done-item ()
5252 "Signal user error on marked done items.
5253 Helper function for editing commands that apply only to (possibly
5254 marked) not done todo items."
5255 (save-excursion
5256 (save-restriction
5257 (goto-char (point-max))
5258 (todo-backward-item)
5259 (unless (todo-done-item-p)
5260 (widen)
5261 (unless (re-search-forward
5262 (concat "^" (regexp-quote todo-category-beg)) nil t)
5263 (goto-char (point-max)))
5264 (forward-line -1))
5265 (while (todo-done-item-p)
5266 (when (todo-marked-item-p)
5267 (user-error "This command does not apply to done items"))
5268 (todo-backward-item)))))
5270 (defun todo-reset-done-separator (sep)
5271 "Replace existing overlays of done items separator string SEP."
5272 (save-excursion
5273 (save-restriction
5274 (widen)
5275 (goto-char (point-min))
5276 (while (re-search-forward
5277 (concat "\n\\(" (regexp-quote todo-category-done) "\\)") nil t)
5278 (let* ((beg (match-beginning 1))
5279 (end (match-end 0))
5280 (ov (progn (goto-char beg)
5281 (todo-get-overlay 'separator)))
5282 (old-sep (when ov (overlay-get ov 'display)))
5283 new-ov)
5284 (when old-sep
5285 (unless (string= old-sep sep)
5286 (setq new-ov (make-overlay beg end))
5287 (overlay-put new-ov 'todo 'separator)
5288 (overlay-put new-ov 'display todo-done-separator)
5289 (delete-overlay ov))))))))
5291 (defun todo-get-overlay (val)
5292 "Return the overlay at point whose `todo' property has value VAL."
5293 ;; Use overlays-in to find prefix overlays and check over two
5294 ;; positions to find done separator overlay.
5295 (let ((ovs (overlays-in (point) (1+ (point))))
5297 (catch 'done
5298 (while ovs
5299 (setq ov (pop ovs))
5300 (when (eq (overlay-get ov 'todo) val)
5301 (throw 'done ov))))))
5303 (defun todo-marked-item-p ()
5304 "Non-nil if this item begins with `todo-item-mark'.
5305 In that case, return the item's prefix overlay."
5306 (let* ((ov (todo-get-overlay 'prefix))
5307 ;; If an item insertion command is called on a todo file
5308 ;; before it is visited, it has no prefix overlays yet, so
5309 ;; check for this.
5310 (pref (when ov (overlay-get ov 'before-string)))
5311 (marked (when pref
5312 (string-match (concat "^" (regexp-quote todo-item-mark))
5313 pref))))
5314 (when marked ov)))
5316 (defun todo-insert-with-overlays (item)
5317 "Insert ITEM at point and update prefix/priority number overlays."
5318 (todo-item-start)
5319 ;; Insertion pushes item down but not its prefix overlay. When the
5320 ;; overlay includes a mark, this would now mark the inserted ITEM,
5321 ;; so move it to the pushed down item.
5322 (let ((ov (todo-get-overlay 'prefix))
5323 (marked (todo-marked-item-p)))
5324 (insert item "\n")
5325 (when marked (move-overlay ov (point) (point))))
5326 (todo-backward-item)
5327 (todo-prefix-overlays))
5329 (defun todo-prefix-overlays ()
5330 "Update the prefix overlays of the current category's items.
5331 The overlay's value is the string `todo-prefix' or with non-nil
5332 `todo-number-prefix' an integer in the sequence from 1 to
5333 the number of todo or done items in the category indicating the
5334 item's priority. Todo and done items are numbered independently
5335 of each other."
5336 (let ((num 0)
5337 (cat-tp (or (cdr (assoc-string
5338 (todo-current-category)
5339 (nth 2 (assoc-string todo-current-todo-file
5340 todo-top-priorities-overrides))))
5341 (nth 1 (assoc-string todo-current-todo-file
5342 todo-top-priorities-overrides))
5343 todo-top-priorities))
5344 done prefix)
5345 (save-excursion
5346 (goto-char (point-min))
5347 (while (not (eobp))
5348 (when (or (todo-date-string-matcher (line-end-position))
5349 (todo-done-string-matcher (line-end-position)))
5350 (goto-char (match-beginning 0))
5351 (setq num (1+ num))
5352 ;; Reset number to 1 for first done item.
5353 (when (and (eq major-mode 'todo-mode)
5354 (looking-at todo-done-string-start)
5355 (looking-back (concat "^"
5356 (regexp-quote todo-category-done)
5357 "\n")
5358 (line-beginning-position 0)))
5359 (setq num 1
5360 done t))
5361 (setq prefix (concat (propertize
5362 (if todo-number-prefix
5363 (number-to-string num)
5364 todo-prefix)
5365 'face
5366 ;; Prefix of top priority items has a
5367 ;; distinct face in Todo mode.
5368 (if (and (eq major-mode 'todo-mode)
5369 (not done)
5370 (<= num cat-tp))
5371 'todo-top-priority
5372 'todo-prefix-string))
5373 " "))
5374 (let ((ov (todo-get-overlay 'prefix))
5375 (marked (todo-marked-item-p)))
5376 ;; Prefix overlay must be at a single position so its
5377 ;; bounds aren't changed when (re)moving an item.
5378 (unless ov (setq ov (make-overlay (point) (point))))
5379 (overlay-put ov 'todo 'prefix)
5380 (overlay-put ov 'before-string (if marked
5381 (concat todo-item-mark prefix)
5382 prefix))))
5383 (forward-line)))))
5385 ;; -----------------------------------------------------------------------------
5386 ;;; Generating and applying item insertion and editing key sequences
5387 ;; -----------------------------------------------------------------------------
5389 ;; Thanks to Stefan Monnier for suggesting dynamically generating item
5390 ;; insertion commands and their key bindings, and offering an elegant
5391 ;; implementation, which, however, relies on lexical scoping and so
5392 ;; cannot be used here until the Calendar code used by todo-mode.el is
5393 ;; converted to lexical binding. Hence, the following implementation
5394 ;; uses dynamic binding.
5396 (defconst todo-insert-item--parameters
5397 '((default copy) (diary nonmarking) (calendar date dayname) time (here region))
5398 "List of all item insertion parameters.
5399 Passed by `todo-insert-item' to `todo-insert-item--next-param' to
5400 dynamically create item insertion commands.")
5402 (defconst todo-insert-item--param-key-alist
5403 '((default . "i")
5404 (copy . "p")
5405 (diary . "y")
5406 (nonmarking . "k")
5407 (calendar . "c")
5408 (date . "d")
5409 (dayname . "n")
5410 (time . "t")
5411 (here . "h")
5412 (region . "r"))
5413 "List pairing item insertion parameters with their completion keys.")
5415 (defsubst todo-insert-item--keyof (param)
5416 "Return key paired with item insertion PARAM."
5417 (cdr (assoc param todo-insert-item--param-key-alist)))
5419 (defun todo-insert-item--argsleft (key list)
5420 "Return sublist of LIST whose first member corresponds to KEY."
5421 (let (l sym)
5422 (mapc (lambda (m)
5423 (when (consp m)
5424 (catch 'found1
5425 (dolist (s m)
5426 (when (equal key (todo-insert-item--keyof s))
5427 (throw 'found1 (setq sym s))))))
5428 (if sym
5429 (progn
5430 (push sym l)
5431 (setq sym nil))
5432 (push m l)))
5433 list)
5434 (setq list (reverse l)))
5435 (memq (catch 'found2
5436 (dolist (e todo-insert-item--param-key-alist)
5437 (when (equal key (cdr e))
5438 (throw 'found2 (car e)))))
5439 list))
5441 (defsubst todo-insert-item--this-key () (char-to-string last-command-event))
5443 (defvar todo-insert-item--keys-so-far ""
5444 "String of item insertion keys so far entered for this command.")
5446 (defvar todo-insert-item--args nil)
5447 (defvar todo-insert-item--argleft nil)
5448 (defvar todo-insert-item--argsleft nil)
5449 (defvar todo-insert-item--newargsleft nil)
5451 (defun todo-insert-item--apply-args ()
5452 "Build list of arguments for item insertion and apply them.
5453 The list consists of item insertion parameters that can be passed
5454 as insertion command arguments in fixed positions. If a position
5455 in the list is not occupied by the corresponding parameter, it is
5456 occupied by nil."
5457 (let* ((arg (list (car todo-insert-item--args)))
5458 (args (nconc (cdr todo-insert-item--args)
5459 (list (car (todo-insert-item--argsleft
5460 (todo-insert-item--this-key)
5461 todo-insert-item--argsleft)))))
5462 (arglist (if (= 4 (length args))
5463 args
5464 (let ((v (make-vector 4 nil)) elt)
5465 (while args
5466 (setq elt (pop args))
5467 (cond ((memq elt '(diary nonmarking))
5468 (aset v 0 elt))
5469 ((memq elt '(calendar date dayname))
5470 (aset v 1 elt))
5471 ((eq elt 'time)
5472 (aset v 2 elt))
5473 ((memq elt '(copy here region))
5474 (aset v 3 elt))))
5475 (append v nil)))))
5476 (apply #'todo-insert-item--basic (nconc arg arglist))))
5478 (defun todo-insert-item--next-param (last args argsleft)
5479 "Build item insertion command from LAST, ARGS and ARGSLEFT and call it.
5480 Dynamically generate key bindings, prompting with the keys
5481 already entered and those still available."
5482 (cl-assert argsleft)
5483 (let* ((map (make-sparse-keymap))
5484 (prompt nil)
5485 (addprompt
5486 (lambda (k name)
5487 (setq prompt
5488 (concat prompt
5489 (format
5490 (concat
5491 (if (memq name '(default diary calendar here))
5492 " { " " ")
5493 "%s=>%s"
5494 (when (memq name '(copy nonmarking dayname region))
5495 " }"))
5496 (propertize k 'face 'todo-key-prompt)
5497 name))))))
5498 (setq todo-insert-item--args args)
5499 (setq todo-insert-item--argsleft argsleft)
5500 (when last
5501 (if (memq last '(default copy))
5502 (progn
5503 (setq todo-insert-item--argsleft nil)
5504 (todo-insert-item--apply-args))
5505 (let ((k (todo-insert-item--keyof last)))
5506 (funcall addprompt k (make-symbol (concat (symbol-name last) ":GO!")))
5507 (define-key map (todo-insert-item--keyof last)
5508 (lambda () (interactive)
5509 (todo-insert-item--apply-args))))))
5510 (while todo-insert-item--argsleft
5511 (let ((x (car todo-insert-item--argsleft)))
5512 (setq todo-insert-item--newargsleft (cdr todo-insert-item--argsleft))
5513 (dolist (argleft (if (consp x) x (list x)))
5514 (let ((k (todo-insert-item--keyof argleft)))
5515 (funcall addprompt k argleft)
5516 (define-key map k
5517 (if (null todo-insert-item--newargsleft)
5518 (lambda () (interactive)
5519 (todo-insert-item--apply-args))
5520 (lambda () (interactive)
5521 (setq todo-insert-item--keys-so-far
5522 (concat todo-insert-item--keys-so-far " "
5523 (todo-insert-item--this-key)))
5524 (todo-insert-item--next-param
5525 (car (todo-insert-item--argsleft
5526 (todo-insert-item--this-key)
5527 todo-insert-item--argsleft))
5528 (nconc todo-insert-item--args
5529 (list (car (todo-insert-item--argsleft
5530 (todo-insert-item--this-key)
5531 todo-insert-item--argsleft))))
5532 (cdr (todo-insert-item--argsleft
5533 (todo-insert-item--this-key)
5534 todo-insert-item--argsleft)))))))))
5535 (setq todo-insert-item--argsleft todo-insert-item--newargsleft))
5536 (when prompt (message "Press a key (so far ‘%s’): %s"
5537 todo-insert-item--keys-so-far prompt))
5538 (set-transient-map map)
5539 (setq todo-insert-item--argsleft argsleft)))
5541 (defconst todo-edit-item--param-key-alist
5542 '((edit . "e")
5543 (header . "h")
5544 (multiline . "m")
5545 (diary . "y")
5546 (nonmarking . "k")
5547 (date . "d")
5548 (time . "t"))
5549 "Alist of item editing parameters and their keys.")
5551 (defconst todo-edit-item--date-param-key-alist
5552 '((full . "f")
5553 (calendar . "c")
5554 (today . "a")
5555 (dayname . "n")
5556 (year . "y")
5557 (month . "m")
5558 (daynum . "d"))
5559 "Alist of item date editing parameters and their keys.")
5561 (defconst todo-edit-done-item--param-key-alist
5562 '((add/edit . "c")
5563 (delete . "d"))
5564 "Alist of done item comment editing parameters and their keys.")
5566 (defvar todo-edit-item--prompt "Press a key (so far `e'): ")
5568 (defun todo-edit-item--next-key (params &optional arg)
5569 (let* ((map (make-sparse-keymap))
5570 (p->k (mapconcat (lambda (elt)
5571 (format "%s=>%s"
5572 (propertize (cdr elt) 'face
5573 'todo-key-prompt)
5574 (concat (symbol-name (car elt))
5575 (when (memq (car elt)
5576 '(add/edit delete))
5577 " comment"))))
5578 params " "))
5579 (this-key (let ((key (read-key (concat todo-edit-item--prompt p->k))))
5580 (and (characterp key) (char-to-string key))))
5581 (this-param (car (rassoc this-key params))))
5582 (pcase this-param
5583 (`edit (todo-edit-item--text))
5584 (`header (todo-edit-item--text 'include-header))
5585 (`multiline (todo-edit-item--text 'multiline))
5586 (`add/edit (todo-edit-item--text 'comment-edit))
5587 (`delete (todo-edit-item--text 'comment-delete))
5588 (`diary (todo-edit-item--diary-inclusion))
5589 (`nonmarking (todo-edit-item--diary-inclusion 'nonmarking))
5590 (`date (let ((todo-edit-item--prompt "Press a key (so far ‘e d’): "))
5591 (todo-edit-item--next-key
5592 todo-edit-item--date-param-key-alist arg)))
5593 (`full (progn (todo-edit-item--header 'date)
5594 (when todo-always-add-time-string
5595 (todo-edit-item--header 'time))))
5596 (`calendar (todo-edit-item--header 'calendar))
5597 (`today (todo-edit-item--header 'today))
5598 (`dayname (todo-edit-item--header 'dayname))
5599 (`year (todo-edit-item--header 'year arg))
5600 (`month (todo-edit-item--header 'month arg))
5601 (`daynum (todo-edit-item--header 'day arg))
5602 (`time (todo-edit-item--header 'time)))))
5604 ;; -----------------------------------------------------------------------------
5605 ;;; Todo minibuffer utilities
5606 ;; -----------------------------------------------------------------------------
5608 (defcustom todo-y-with-space nil
5609 "Non-nil means allow SPC to affirm a \"y or n\" question."
5610 :type 'boolean
5611 :group 'todo)
5613 (defun todo-y-or-n-p (prompt)
5614 "Ask \"y or n\" question PROMPT and return t if answer is \"y\".
5615 Also return t if answer is \"Y\", but unlike `y-or-n-p', allow
5616 SPC to affirm the question only if option `todo-y-with-space' is
5617 non-nil."
5618 (unless todo-y-with-space
5619 (define-key query-replace-map " " 'ignore))
5620 (prog1
5621 (y-or-n-p prompt)
5622 (define-key query-replace-map " " 'act)))
5624 (defun todo-category-completions (&optional archive)
5625 "Return a list of completions for `todo-read-category'.
5626 Each element of the list is a cons of a category name and the
5627 file or list of files (as short file names) it is in. The files
5628 are either the current (or if there is none, the default) todo
5629 file plus the files listed in `todo-category-completions-files',
5630 or, with non-nil ARCHIVE, the current archive file.
5632 Before calculating the completions, update the value of
5633 `todo-category-completions-files' in case any files named in it
5634 have been removed."
5635 (let (deleted)
5636 (dolist (f todo-category-completions-files)
5637 (unless (file-exists-p (todo-absolute-file-name f))
5638 (setq todo-category-completions-files
5639 (delete f todo-category-completions-files))
5640 (push f deleted)))
5641 (when deleted
5642 (let ((pl (> (length deleted) 1))
5643 (names (mapconcat (lambda (f) (concat "\"" f "\"")) deleted ", ")))
5644 (message (concat "File" (if pl "s" "") " " names " ha" (if pl "ve" "s")
5645 " been deleted and removed from\n"
5646 "the list of category completion files")))
5647 (todo-reevaluate-category-completions-files-defcustom)
5648 (custom-set-default 'todo-category-completions-files
5649 (symbol-value 'todo-category-completions-files))
5650 (sleep-for 1.5)))
5651 (let* ((curfile (or todo-current-todo-file
5652 (and todo-show-current-file
5653 todo-global-current-todo-file)
5654 (todo-absolute-file-name todo-default-todo-file)))
5655 (files (or (unless archive
5656 (mapcar 'todo-absolute-file-name
5657 todo-category-completions-files))
5658 (list curfile)))
5659 listall listf)
5660 ;; If file was just added, it has no category completions.
5661 (unless (zerop (buffer-size (find-buffer-visiting curfile)))
5662 (unless (member curfile todo-archives)
5663 (add-to-list 'files curfile))
5664 (dolist (f files listall)
5665 (with-current-buffer (find-file-noselect f 'nowarn)
5666 (if archive
5667 (unless (derived-mode-p 'todo-archive-mode) (todo-archive-mode))
5668 (unless (derived-mode-p 'todo-mode) (todo-mode)))
5669 ;; Ensure category is properly displayed in case user
5670 ;; switches to file via a non-Todo mode command. And if
5671 ;; done items in category are visible, keep them visible.
5672 (let ((done todo-show-with-done))
5673 (when (> (buffer-size) (- (point-max) (point-min)))
5674 (save-excursion
5675 (goto-char (point-min))
5676 (setq done (re-search-forward todo-done-string-start nil t))))
5677 (let ((todo-show-with-done done))
5678 (save-excursion (todo-category-select))))
5679 (save-excursion
5680 (save-restriction
5681 (widen)
5682 (goto-char (point-min))
5683 (setq listf (read (buffer-substring-no-properties
5684 (line-beginning-position)
5685 (line-end-position)))))))
5686 (mapc (lambda (elt) (let* ((cat (car elt))
5687 (la-elt (assoc cat listall)))
5688 (if la-elt
5689 (setcdr la-elt (append (list (cdr la-elt))
5690 (list f)))
5691 (push (cons cat f) listall))))
5692 listf)))))
5694 (defun todo-read-file-name (prompt &optional archive mustmatch)
5695 "Choose and return the name of a todo file, prompting with PROMPT.
5697 Show completions with TAB or SPC; the names are shown in short
5698 form but the absolute truename is returned. With non-nil ARCHIVE
5699 return the absolute truename of a todo archive file. With non-nil
5700 MUSTMATCH the name of an existing file must be chosen;
5701 otherwise, a new file name is allowed."
5702 (let* ((completion-ignore-case todo-completion-ignore-case)
5703 (files (mapcar 'todo-short-file-name
5704 ;; (funcall todo-files-function archive)))
5705 (if archive todo-archives todo-files)))
5706 (file (completing-read prompt files nil mustmatch nil nil
5707 (if files
5708 ;; If user hit RET without
5709 ;; choosing a file, default to
5710 ;; current or default file.
5711 (todo-short-file-name
5712 (or todo-current-todo-file
5713 (and todo-show-current-file
5714 todo-global-current-todo-file)
5715 (todo-absolute-file-name
5716 todo-default-todo-file)))
5717 ;; Trigger prompt for initial file.
5718 ""))))
5719 (unless (file-exists-p todo-directory)
5720 (make-directory todo-directory))
5721 (unless (or mustmatch (member file files))
5722 (setq file (todo-validate-name file 'file)))
5723 (setq file (file-truename (concat todo-directory file
5724 (if archive ".toda" ".todo"))))))
5726 (defun todo-read-category (prompt &optional match-type file)
5727 "Choose and return a category name, prompting with PROMPT.
5728 Show completions for existing categories with TAB or SPC.
5730 The argument MATCH-TYPE specifies the matching requirements on
5731 the category name: with the value `todo' or `archive' the name
5732 must complete to that of an existing todo or archive category,
5733 respectively; with the value `add' the name must not be that of
5734 an existing category; with all other values both existing and new
5735 valid category names are accepted.
5737 With non-nil argument FILE prompt for a file and complete only
5738 against categories in that file; otherwise complete against all
5739 categories from `todo-category-completions-files'."
5740 ;; Allow SPC to insert spaces, for adding new category names.
5741 (let ((map minibuffer-local-completion-map))
5742 (define-key map " " nil)
5743 (let* ((add (eq match-type 'add))
5744 (archive (eq match-type 'archive))
5745 (file0 (when (and file (> (length todo-files) 1))
5746 (todo-read-file-name (concat "Choose a" (if archive
5747 "n archive"
5748 " todo")
5749 " file: ") archive t)))
5750 (completions (unless file0 (todo-category-completions archive)))
5751 (categories (cond (file0
5752 (with-current-buffer
5753 (find-file-noselect file0 'nowarn)
5754 (unless (derived-mode-p 'todo-mode) (todo-mode))
5755 (let ((todo-current-todo-file file0))
5756 todo-categories)))
5757 ((and add (not file))
5758 (with-current-buffer
5759 (find-file-noselect todo-current-todo-file)
5760 todo-categories))
5762 completions)))
5763 (completion-ignore-case todo-completion-ignore-case)
5764 (cat (completing-read prompt categories nil
5765 (eq match-type 'todo) nil nil
5766 ;; Unless we're adding a category via
5767 ;; todo-add-category, set default
5768 ;; for existing categories to the
5769 ;; current category of the chosen
5770 ;; file or else of the current file.
5771 (if (and categories (not add))
5772 (with-current-buffer
5773 (find-file-noselect
5774 (or file0
5775 todo-current-todo-file
5776 (todo-absolute-file-name
5777 todo-default-todo-file)))
5778 (todo-current-category))
5779 ;; Trigger prompt for initial category.
5780 "")))
5781 (catfil (cdr (assoc cat completions)))
5782 (str "Category \"%s\" from which file (TAB for choices)? "))
5783 ;; If we do category completion and the chosen category name
5784 ;; occurs in more than one file, prompt to choose one file.
5785 (unless (or file0 add (not catfil))
5786 (setq file0 (file-truename
5787 (if (atom catfil)
5788 catfil
5789 (todo-absolute-file-name
5790 (let ((files (mapcar 'todo-short-file-name catfil)))
5791 (completing-read (format str cat) files)))))))
5792 ;; Default to the current file.
5793 (unless file0 (setq file0 todo-current-todo-file))
5794 ;; First validate only a name passed interactively from
5795 ;; todo-add-category, which must be of a nonexistent category.
5796 (unless (and (assoc cat categories) (not add))
5797 ;; Validate only against completion categories.
5798 (let ((todo-categories categories))
5799 (setq cat (todo-validate-name cat 'category)))
5800 ;; When user enters a nonexistent category name by jumping or
5801 ;; moving, confirm that it should be added, then validate.
5802 (unless add
5803 (if (todo-y-or-n-p (format "Add new category \"%s\" to file \"%s\"? "
5804 cat (todo-short-file-name file0)))
5805 (progn
5806 (when (assoc cat categories)
5807 (let ((todo-categories categories))
5808 (setq cat (todo-validate-name cat 'category))))
5809 ;; Restore point and narrowing after adding new
5810 ;; category, to avoid moving to beginning of file when
5811 ;; moving marked items to a new category
5812 ;; (todo-move-item).
5813 (save-excursion
5814 (save-restriction
5815 (todo-add-category file0 cat))))
5816 ;; If we decide not to add a category, exit without returning.
5817 (keyboard-quit))))
5818 (cons cat file0))))
5820 (defun todo-validate-name (name type)
5821 "Prompt for new NAME for TYPE until it is valid, then return it.
5822 TYPE can be either of the symbols `file' or `category'."
5823 (let ((categories todo-categories)
5824 (files (mapcar 'todo-short-file-name todo-files))
5825 prompt)
5826 (while
5827 (and
5828 (cond ((string= "" name)
5829 (setq prompt
5830 (cond ((eq type 'file)
5831 (if files
5832 "Enter a non-empty file name: "
5833 ;; Empty string passed by todo-show to
5834 ;; prompt for initial todo file.
5835 (concat "Initial file name ["
5836 todo-initial-file "]: ")))
5837 ((eq type 'category)
5838 (if categories
5839 "Enter a non-empty category name: "
5840 ;; Empty string passed by todo-show to
5841 ;; prompt for initial category of a new
5842 ;; todo file.
5843 (concat "Initial category name ["
5844 todo-initial-category "]: "))))))
5845 ((string-match "\\`\\s-+\\'" name)
5846 (setq prompt
5847 "Enter a name that does not contain only white space: "))
5848 ((and (eq type 'file) (member name files))
5849 (setq prompt "Enter a non-existing file name: "))
5850 ((and (eq type 'category) (assoc name categories))
5851 (setq prompt "Enter a non-existing category name: ")))
5852 (setq name (if (or (and (eq type 'file) files)
5853 (and (eq type 'category) categories))
5854 (completing-read prompt (cond ((eq type 'file)
5855 files)
5856 ((eq type 'category)
5857 categories)))
5858 ;; Offer default initial name.
5859 (completing-read prompt (if (eq type 'file)
5860 files
5861 categories)
5862 nil nil (if (eq type 'file)
5863 todo-initial-file
5864 todo-initial-category))))))
5865 name))
5867 ;; Adapted from calendar-read-date and calendar-date-string.
5868 (defun todo-read-date (&optional arg mo yr)
5869 "Prompt for Gregorian date and return it in the current format.
5871 With non-nil ARG, prompt for and return only the date component
5872 specified by ARG, which can be one of these symbols:
5873 `month' (prompt for name, return name or number according to
5874 value of `calendar-date-display-form'), `day' of month, or
5875 `year'. The value of each of these components can be `*',
5876 indicating an unspecified month, day, or year.
5878 When ARG is `day', non-nil arguments MO and YR determine the
5879 number of the last the day of the month."
5880 (let (year monthname month day
5881 dayname) ; Needed by calendar-date-display-form.
5882 (when (or (not arg) (eq arg 'year))
5883 (while (if (natnump year) (< year 1) (not (eq year '*)))
5884 (setq year (read-from-minibuffer
5885 "Year (>0 or RET for this year or * for any year): "
5886 nil nil t nil (number-to-string
5887 (calendar-extract-year
5888 (calendar-current-date)))))))
5889 (when (or (not arg) (eq arg 'month))
5890 (let* ((marray todo-month-name-array)
5891 (mlist (append marray nil))
5892 (mabarray todo-month-abbrev-array)
5893 (mablist (append mabarray nil))
5894 (completion-ignore-case todo-completion-ignore-case))
5895 (setq monthname (completing-read
5896 "Month name (RET for current month, * for any month): "
5897 mlist nil t nil nil
5898 (calendar-month-name (calendar-extract-month
5899 (calendar-current-date)) t))
5900 month (1+ (- (length mlist)
5901 (length (or (member monthname mlist)
5902 (member monthname mablist))))))
5903 (setq monthname (aref mabarray (1- month)))))
5904 (when (or (not arg) (eq arg 'day))
5905 (let ((last (let ((mm (or month mo))
5906 (yy (or year yr)))
5907 ;; If month is unspecified, use a month with 31
5908 ;; days for checking day of month input. Does
5909 ;; Calendar do anything special when * is
5910 ;; currently a shorter month?
5911 (if (= mm 13) (setq mm 1))
5912 ;; If year is unspecified, use a leap year to
5913 ;; allow Feb. 29.
5914 (if (eq year '*) (setq yy 2012))
5915 (calendar-last-day-of-month mm yy))))
5916 (while (if (natnump day) (or (< day 1) (> day last)) (not (eq day '*)))
5917 (setq day (read-from-minibuffer
5918 (format "Day (1-%d or RET for today or * for any day): "
5919 last)
5920 nil nil t nil (number-to-string
5921 (calendar-extract-day
5922 (calendar-current-date))))))))
5923 ;; Stringify read values (monthname is already a string).
5924 (and year (setq year (if (eq year '*)
5925 (symbol-name '*)
5926 (number-to-string year))))
5927 (and day (setq day (if (eq day '*)
5928 (symbol-name '*)
5929 (number-to-string day))))
5930 (and month (setq month (if (eq month '*)
5931 (symbol-name '*)
5932 (number-to-string month))))
5933 (if arg
5934 (cond ((eq arg 'year) year)
5935 ((eq arg 'day) day)
5936 ((eq arg 'month)
5937 (if (memq 'month calendar-date-display-form)
5938 month
5939 monthname)))
5940 (mapconcat 'eval calendar-date-display-form ""))))
5942 (defun todo-read-dayname ()
5943 "Choose name of a day of the week with completion and return it."
5944 (let ((completion-ignore-case todo-completion-ignore-case))
5945 (completing-read "Enter a day name: "
5946 (append calendar-day-name-array nil)
5947 nil t)))
5949 (defun todo-read-time ()
5950 "Prompt for and return a valid clock time as a string.
5952 Valid time strings are those matching `diary-time-regexp'.
5953 Typing `<return>' at the prompt returns the current time, if the
5954 user option `todo-always-add-time-string' is non-nil, otherwise
5955 the empty string (i.e., no time string)."
5956 (let (valid answer)
5957 (while (not valid)
5958 (setq answer (read-string "Enter a clock time: " nil nil
5959 (when todo-always-add-time-string
5960 (substring (current-time-string) 11 16))))
5961 (when (or (string= "" answer)
5962 (string-match diary-time-regexp answer))
5963 (setq valid t)))
5964 answer))
5966 ;; -----------------------------------------------------------------------------
5967 ;;; Customization groups and utilities
5968 ;; -----------------------------------------------------------------------------
5970 (defgroup todo nil
5971 "Create and maintain categorized lists of todo items."
5972 :link '(emacs-commentary-link "todo")
5973 :version "24.4"
5974 :group 'calendar)
5976 (defgroup todo-edit nil
5977 "User options for adding and editing todo items."
5978 :version "24.4"
5979 :group 'todo)
5981 (defgroup todo-categories nil
5982 "User options for Todo Categories mode."
5983 :version "24.4"
5984 :group 'todo)
5986 (defgroup todo-filtered nil
5987 "User options for Todo Filter Items mode."
5988 :version "24.4"
5989 :group 'todo)
5991 (defgroup todo-display nil
5992 "User display options for Todo mode."
5993 :version "24.4"
5994 :group 'todo)
5996 (defgroup todo-faces nil
5997 "Faces for the Todo modes."
5998 :version "24.4"
5999 :group 'todo)
6001 (defun todo-set-show-current-file (symbol value)
6002 "The :set function for user option `todo-show-current-file'."
6003 (custom-set-default symbol value)
6004 (if value
6005 (add-hook 'pre-command-hook 'todo-show-current-file nil t)
6006 (remove-hook 'pre-command-hook 'todo-show-current-file t)))
6008 (defun todo-reset-prefix (symbol value)
6009 "The :set function for `todo-prefix' and `todo-number-prefix'."
6010 (let ((oldvalue (symbol-value symbol))
6011 (files todo-file-buffers))
6012 (custom-set-default symbol value)
6013 (when (not (equal value oldvalue))
6014 (dolist (f files)
6015 (with-current-buffer (find-file-noselect f)
6016 ;; Activate the new setting in the current category.
6017 (save-excursion (todo-category-select)))))))
6019 (defun todo-reset-nondiary-marker (symbol value)
6020 "The :set function for user option `todo-nondiary-marker'."
6021 (let* ((oldvalue (symbol-value symbol))
6022 (files (append todo-files todo-archives
6023 (directory-files todo-directory t "\.tod[rty]$" t))))
6024 (custom-set-default symbol value)
6025 ;; Need to reset these to get font-locking right.
6026 (setq todo-nondiary-start (nth 0 todo-nondiary-marker)
6027 todo-nondiary-end (nth 1 todo-nondiary-marker)
6028 todo-date-string-start
6029 ;; See comment in defvar of `todo-date-string-start'.
6030 (concat "^\\(" (regexp-quote todo-nondiary-start) "\\|"
6031 (regexp-quote diary-nonmarking-symbol) "\\)?"))
6032 (when (not (equal value oldvalue))
6033 (dolist (f files)
6034 (let ((buf (find-buffer-visiting f)))
6035 (with-current-buffer (find-file-noselect f)
6036 (let (buffer-read-only)
6037 (widen)
6038 (goto-char (point-min))
6039 (while (not (eobp))
6040 (if (re-search-forward
6041 (concat "^\\(" todo-done-string-start "[^][]+] \\)?"
6042 "\\(?1:" (regexp-quote (car oldvalue))
6043 "\\)" todo-date-pattern "\\( "
6044 diary-time-regexp "\\)?\\(?2:"
6045 (regexp-quote (cadr oldvalue)) "\\)")
6046 nil t)
6047 (progn
6048 (replace-match (nth 0 value) t t nil 1)
6049 (replace-match (nth 1 value) t t nil 2))
6050 (forward-line)))
6051 (if buf
6052 (when (derived-mode-p 'todo-mode 'todo-archive-mode)
6053 (todo-category-select))
6054 (save-buffer)
6055 (kill-buffer)))))))))
6057 (defun todo-reset-done-separator-string (symbol value)
6058 "The :set function for `todo-done-separator-string'."
6059 (let ((oldvalue (symbol-value symbol))
6060 (files todo-file-buffers)
6061 (sep todo-done-separator))
6062 (custom-set-default symbol value)
6063 (when (not (equal value oldvalue))
6064 (dolist (f files)
6065 (with-current-buffer (find-file-noselect f)
6066 (let (buffer-read-only)
6067 (setq todo-done-separator (todo-done-separator))
6068 (when (= 1 (length value))
6069 (todo-reset-done-separator sep)))
6070 (todo-category-select))))))
6072 (defun todo-reset-done-string (symbol value)
6073 "The :set function for user option `todo-done-string'."
6074 (let ((oldvalue (symbol-value symbol))
6075 (files (append todo-files todo-archives
6076 (directory-files todo-directory t "\.todr$" t))))
6077 (custom-set-default symbol value)
6078 ;; Need to reset this to get font-locking right.
6079 (setq todo-done-string-start
6080 (concat "^\\[" (regexp-quote todo-done-string)))
6081 (when (not (equal value oldvalue))
6082 (dolist (f files)
6083 (let ((buf (find-buffer-visiting f)))
6084 (with-current-buffer (find-file-noselect f)
6085 (let (buffer-read-only)
6086 (widen)
6087 (goto-char (point-min))
6088 (while (not (eobp))
6089 (if (re-search-forward
6090 (concat "^" (regexp-quote todo-nondiary-start)
6091 "\\(" (regexp-quote oldvalue) "\\)")
6092 nil t)
6093 (replace-match value t t nil 1)
6094 (forward-line)))
6095 (if buf
6096 (when (derived-mode-p 'todo-mode 'todo-archive-mode)
6097 (todo-category-select))
6098 (save-buffer)
6099 (kill-buffer)))))))))
6101 (defun todo-reset-comment-string (symbol value)
6102 "The :set function for user option `todo-comment-string'."
6103 (let ((oldvalue (symbol-value symbol))
6104 (files (append todo-files todo-archives
6105 (directory-files todo-directory t "\.todr$" t))))
6106 (custom-set-default symbol value)
6107 (when (not (equal value oldvalue))
6108 (dolist (f files)
6109 (let ((buf (find-buffer-visiting f)))
6110 (with-current-buffer (find-file-noselect f)
6111 (let (buffer-read-only)
6112 (widen)
6113 (goto-char (point-min))
6114 (while (not (eobp))
6115 (if (re-search-forward
6116 (concat "\\[\\(" (regexp-quote oldvalue)
6117 "\\): [^]]*\\]")
6118 nil t)
6119 (replace-match value t t nil 1)
6120 (forward-line)))
6121 (if buf
6122 (when (derived-mode-p 'todo-mode 'todo-archive-mode)
6123 (todo-category-select))
6124 (save-buffer)
6125 (kill-buffer)))))))))
6127 (defun todo-reset-highlight-item (symbol value)
6128 "The :set function for user option `todo-highlight-item'."
6129 (let ((oldvalue (symbol-value symbol))
6130 (files (append todo-files todo-archives
6131 (directory-files todo-directory t "\.tod[rty]$" t))))
6132 (custom-set-default symbol value)
6133 (when (not (equal value oldvalue))
6134 (dolist (f files)
6135 (let ((buf (find-buffer-visiting f)))
6136 (when buf
6137 (with-current-buffer buf
6138 (require 'hl-line)
6139 (if value
6140 (hl-line-mode 1)
6141 (hl-line-mode -1)))))))))
6143 (defun todo-reevaluate-filelist-defcustoms ()
6144 "Reevaluate defcustoms that provide choice list of todo files."
6145 (custom-set-default 'todo-default-todo-file
6146 (symbol-value 'todo-default-todo-file))
6147 (todo-reevaluate-default-file-defcustom)
6148 (custom-set-default 'todo-filter-files (symbol-value 'todo-filter-files))
6149 (todo-reevaluate-filter-files-defcustom)
6150 (custom-set-default 'todo-category-completions-files
6151 (symbol-value 'todo-category-completions-files))
6152 (todo-reevaluate-category-completions-files-defcustom))
6154 (defun todo-reevaluate-default-file-defcustom ()
6155 "Reevaluate defcustom of `todo-default-todo-file'.
6156 Called after adding or deleting a todo file. If the value of
6157 `todo-default-todo-file' before calling this function was
6158 associated with an existing file, keep that value."
6159 ;; (let ((curval todo-default-todo-file))
6160 (eval
6161 (defcustom todo-default-todo-file (todo-short-file-name
6162 (car (funcall todo-files-function)))
6163 "Todo file visited by first session invocation of `todo-show'."
6164 :type (when todo-files
6165 `(radio ,@(mapcar (lambda (f) (list 'const f))
6166 (mapcar 'todo-short-file-name
6167 (funcall todo-files-function)))))
6168 :group 'todo))
6169 ;; (when (and curval (file-exists-p (todo-absolute-file-name curval)))
6170 ;; (custom-set-default 'todo-default-todo-file curval)
6171 ;; ;; (custom-reevaluate-setting 'todo-default-todo-file)
6172 ;; )))
6175 (defun todo-reevaluate-category-completions-files-defcustom ()
6176 "Reevaluate defcustom of `todo-category-completions-files'.
6177 Called after adding or deleting a todo file."
6178 (eval (defcustom todo-category-completions-files nil
6179 "List of files for building `todo-read-category' completions."
6180 :type `(set ,@(mapcar (lambda (f) (list 'const f))
6181 (mapcar 'todo-short-file-name
6182 (funcall todo-files-function))))
6183 :group 'todo)))
6185 (defun todo-reevaluate-filter-files-defcustom ()
6186 "Reevaluate defcustom of `todo-filter-files'.
6187 Called after adding or deleting a todo file."
6188 (eval (defcustom todo-filter-files nil
6189 "List of files for multifile item filtering."
6190 :type `(set ,@(mapcar (lambda (f) (list 'const f))
6191 (mapcar 'todo-short-file-name
6192 (funcall todo-files-function))))
6193 :group 'todo)))
6195 ;; -----------------------------------------------------------------------------
6196 ;;; Font locking
6197 ;; -----------------------------------------------------------------------------
6199 (defun todo-nondiary-marker-matcher (lim)
6200 "Search for todo item nondiary markers within LIM for font-locking."
6201 (re-search-forward (concat "^\\(?1:" (regexp-quote todo-nondiary-start) "\\)"
6202 todo-date-pattern "\\(?: " diary-time-regexp
6203 "\\)?\\(?2:" (regexp-quote todo-nondiary-end) "\\)")
6204 lim t))
6206 (defun todo-diary-nonmarking-matcher (lim)
6207 "Search for diary nonmarking symbol within LIM for font-locking."
6208 (re-search-forward (concat "^\\(?1:" (regexp-quote diary-nonmarking-symbol)
6209 "\\)" todo-date-pattern) lim t))
6211 (defun todo-date-string-matcher (lim)
6212 "Search for todo item date string within LIM for font-locking."
6213 (re-search-forward
6214 (concat todo-date-string-start "\\(?1:" todo-date-pattern "\\)") lim t))
6216 (defun todo-time-string-matcher (lim)
6217 "Search for todo item time string within LIM for font-locking."
6218 (re-search-forward (concat todo-date-string-start todo-date-pattern
6219 " \\(?1:" diary-time-regexp "\\)") lim t))
6221 (defun todo-diary-expired-matcher (lim)
6222 "Search for expired diary item date within LIM for font-locking."
6223 (when (re-search-forward (concat "^\\(?:"
6224 (regexp-quote diary-nonmarking-symbol)
6225 "\\)?\\(?1:" todo-date-pattern "\\) \\(?2:"
6226 diary-time-regexp "\\)?") lim t)
6227 (let* ((date (match-string-no-properties 1))
6228 (time (match-string-no-properties 2))
6229 ;; Function days-between requires a non-empty time string.
6230 (date-time (concat date " " (or time "00:00"))))
6231 (or (and (not (string-match ".+day\\|\\*" date))
6232 (< (days-between date-time (current-time-string)) 0))
6233 (todo-diary-expired-matcher lim)))))
6235 (defun todo-done-string-matcher (lim)
6236 "Search for done todo item header within LIM for font-locking."
6237 (re-search-forward (concat todo-done-string-start
6238 "[^][]+]")
6239 lim t))
6241 (defun todo-comment-string-matcher (lim)
6242 "Search for done todo item comment within LIM for font-locking."
6243 (re-search-forward (concat "\\[\\(?1:" todo-comment-string "\\):")
6244 lim t))
6246 (defun todo-category-string-matcher-1 (lim)
6247 "Search for todo category name within LIM for font-locking.
6248 This is for fontifying category and file names appearing in Todo
6249 Filtered Items mode following done items."
6250 (if (eq major-mode 'todo-filtered-items-mode)
6251 (re-search-forward (concat todo-done-string-start todo-date-pattern
6252 "\\(?: " diary-time-regexp
6253 ;; Use non-greedy operator to prevent
6254 ;; capturing possible following non-diary
6255 ;; date string.
6256 "\\)?] \\(?1:\\[.+?\\]\\)")
6257 lim t)))
6259 (defun todo-category-string-matcher-2 (lim)
6260 "Search for todo category name within LIM for font-locking.
6261 This is for fontifying category and file names appearing in Todo
6262 Filtered Items mode following todo (not done) items."
6263 (if (eq major-mode 'todo-filtered-items-mode)
6264 (re-search-forward (concat todo-date-string-start todo-date-pattern
6265 "\\(?: " diary-time-regexp "\\)?\\(?:"
6266 (regexp-quote todo-nondiary-end)
6267 "\\)? \\(?1:\\[.+\\]\\)")
6268 lim t)))
6270 (defvar todo-nondiary-face 'todo-nondiary)
6271 (defvar todo-date-face 'todo-date)
6272 (defvar todo-time-face 'todo-time)
6273 (defvar todo-diary-expired-face 'todo-diary-expired)
6274 (defvar todo-done-sep-face 'todo-done-sep)
6275 (defvar todo-done-face 'todo-done)
6276 (defvar todo-comment-face 'todo-comment)
6277 (defvar todo-category-string-face 'todo-category-string)
6278 (defvar todo-font-lock-keywords
6279 (list
6280 '(todo-nondiary-marker-matcher 1 todo-nondiary-face t)
6281 '(todo-nondiary-marker-matcher 2 todo-nondiary-face t)
6282 ;; diary-lib.el uses font-lock-constant-face for diary-nonmarking-symbol.
6283 '(todo-diary-nonmarking-matcher 1 font-lock-constant-face t)
6284 '(todo-date-string-matcher 1 todo-date-face t)
6285 '(todo-time-string-matcher 1 todo-time-face t)
6286 '(todo-done-string-matcher 0 todo-done-face t)
6287 '(todo-comment-string-matcher 1 todo-comment-face t)
6288 '(todo-category-string-matcher-1 1 todo-category-string-face t t)
6289 '(todo-category-string-matcher-2 1 todo-category-string-face t t)
6290 '(todo-diary-expired-matcher 1 todo-diary-expired-face t)
6291 '(todo-diary-expired-matcher 2 todo-diary-expired-face t t)
6293 "Font-locking for Todo modes.")
6295 ;; -----------------------------------------------------------------------------
6296 ;;; Key binding
6297 ;; -----------------------------------------------------------------------------
6299 (defvar todo-key-bindings-t
6301 ("Af" todo-find-archive)
6302 ("Ac" todo-choose-archive)
6303 ("Ad" todo-archive-done-item)
6304 ("Cv" todo-toggle-view-done-items)
6305 ("v" todo-toggle-view-done-items)
6306 ("Ca" todo-add-category)
6307 ("Cr" todo-rename-category)
6308 ("Cg" todo-merge-category)
6309 ("Cm" todo-move-category)
6310 ("Ck" todo-delete-category)
6311 ("Cts" todo-set-top-priorities-in-category)
6312 ("Cey" todo-edit-category-diary-inclusion)
6313 ("Cek" todo-edit-category-diary-nonmarking)
6314 ("Fa" todo-add-file)
6315 ("Fr" todo-rename-file)
6316 ("Ff" todo-find-filtered-items-file)
6317 ("FV" todo-toggle-view-done-only)
6318 ("V" todo-toggle-view-done-only)
6319 ("Ftt" todo-filter-top-priorities)
6320 ("Ftm" todo-filter-top-priorities-multifile)
6321 ("Fts" todo-set-top-priorities-in-file)
6322 ("Fyy" todo-filter-diary-items)
6323 ("Fym" todo-filter-diary-items-multifile)
6324 ("Fxx" todo-filter-regexp-items)
6325 ("Fxm" todo-filter-regexp-items-multifile)
6326 ("e" todo-edit-item)
6327 ("d" todo-item-done)
6328 ("i" todo-insert-item)
6329 ("k" todo-delete-item)
6330 ("m" todo-move-item)
6331 ("u" todo-item-undone)
6332 ([remap newline] newline-and-indent)
6334 "List of key bindings for Todo mode only.")
6336 (defvar todo-key-bindings-t+a+f
6338 ("C*" todo-mark-category)
6339 ("Cu" todo-unmark-category)
6340 ("Fh" todo-toggle-item-header)
6341 ("h" todo-toggle-item-header)
6342 ("Fk" todo-delete-file)
6343 ("Fe" todo-edit-file)
6344 ("FH" todo-toggle-item-highlighting)
6345 ("H" todo-toggle-item-highlighting)
6346 ("FN" todo-toggle-prefix-numbers)
6347 ("N" todo-toggle-prefix-numbers)
6348 ("PB" todo-print-buffer)
6349 ("PF" todo-print-buffer-to-file)
6350 ("b" todo-backward-category)
6351 ("d" todo-item-done)
6352 ("f" todo-forward-category)
6353 ("j" todo-jump-to-category)
6354 ("n" todo-next-item)
6355 ("p" todo-previous-item)
6356 ("q" todo-quit)
6357 ("s" todo-save)
6358 ("t" todo-show)
6360 "List of key bindings for Todo, Archive, and Filtered Items modes.")
6362 (defvar todo-key-bindings-t+a
6364 ("Fc" todo-show-categories-table)
6365 ("S" todo-search)
6366 ("X" todo-clear-matches)
6367 ("*" todo-toggle-mark-item)
6369 "List of key bindings for Todo and Todo Archive modes.")
6371 (defvar todo-key-bindings-t+f
6373 ("l" todo-lower-item-priority)
6374 ("r" todo-raise-item-priority)
6375 ("#" todo-set-item-priority)
6377 "List of key bindings for Todo and Todo Filtered Items modes.")
6379 (defvar todo-mode-map
6380 (let ((map (make-keymap)))
6381 ;; Don't suppress digit keys, so they can supply prefix arguments.
6382 (suppress-keymap map)
6383 (dolist (kb todo-key-bindings-t)
6384 (define-key map (nth 0 kb) (nth 1 kb)))
6385 (dolist (kb todo-key-bindings-t+a+f)
6386 (define-key map (nth 0 kb) (nth 1 kb)))
6387 (dolist (kb todo-key-bindings-t+a)
6388 (define-key map (nth 0 kb) (nth 1 kb)))
6389 (dolist (kb todo-key-bindings-t+f)
6390 (define-key map (nth 0 kb) (nth 1 kb)))
6391 map)
6392 "Todo mode keymap.")
6394 (defvar todo-archive-mode-map
6395 (let ((map (make-sparse-keymap)))
6396 (suppress-keymap map)
6397 (dolist (kb todo-key-bindings-t+a+f)
6398 (define-key map (nth 0 kb) (nth 1 kb)))
6399 (dolist (kb todo-key-bindings-t+a)
6400 (define-key map (nth 0 kb) (nth 1 kb)))
6401 (define-key map "a" 'todo-jump-to-archive-category)
6402 (define-key map "u" 'todo-unarchive-items)
6403 map)
6404 "Todo Archive mode keymap.")
6406 (defvar todo-edit-mode-map
6407 (let ((map (make-sparse-keymap)))
6408 (define-key map "\C-x\C-q" 'todo-edit-quit)
6409 (define-key map [remap newline] 'newline-and-indent)
6410 map)
6411 "Todo Edit mode keymap.")
6413 (defvar todo-categories-mode-map
6414 (let ((map (make-sparse-keymap)))
6415 (suppress-keymap map)
6416 (define-key map "c" 'todo-sort-categories-alphabetically-or-numerically)
6417 (define-key map "t" 'todo-sort-categories-by-todo)
6418 (define-key map "y" 'todo-sort-categories-by-diary)
6419 (define-key map "d" 'todo-sort-categories-by-done)
6420 (define-key map "a" 'todo-sort-categories-by-archived)
6421 (define-key map "#" 'todo-set-category-number)
6422 (define-key map "l" 'todo-lower-category)
6423 (define-key map "r" 'todo-raise-category)
6424 (define-key map "n" 'todo-next-button)
6425 (define-key map "p" 'todo-previous-button)
6426 (define-key map [tab] 'todo-next-button)
6427 (define-key map [backtab] 'todo-previous-button)
6428 (define-key map "q" 'todo-quit)
6429 map)
6430 "Todo Categories mode keymap.")
6432 (defvar todo-filtered-items-mode-map
6433 (let ((map (make-sparse-keymap)))
6434 (suppress-keymap map)
6435 (dolist (kb todo-key-bindings-t+a+f)
6436 (define-key map (nth 0 kb) (nth 1 kb)))
6437 (dolist (kb todo-key-bindings-t+f)
6438 (define-key map (nth 0 kb) (nth 1 kb)))
6439 (define-key map "g" 'todo-go-to-source-item)
6440 (define-key map [remap newline] 'todo-go-to-source-item)
6441 map)
6442 "Todo Filtered Items mode keymap.")
6444 (easy-menu-define
6445 todo-menu todo-mode-map "Todo Menu"
6446 '("Todo"
6447 ("Navigation"
6448 ["Next Item" todo-next-item t]
6449 ["Previous Item" todo-previous-item t]
6450 "---"
6451 ["Next Category" todo-forward-category t]
6452 ["Previous Category" todo-backward-category t]
6453 ["Jump to Another Category" todo-jump-to-category t]
6454 "---"
6455 ["Visit Another Todo File" todo-show t]
6456 ["Visit Archive" todo-find-archive t]
6457 ["Visit Filtered Items File" todo-find-filtered-items-file t]
6459 ("Editing"
6460 ["Insert New Item" todo-insert-item t]
6461 ["Edit Item" todo-edit-item t]
6462 ["Lower Item Priority" todo-lower-item-priority t]
6463 ["Raise Item Priority" todo-raise-item-priority t]
6464 ["Set Item Priority" todo-set-item-priority t]
6465 ["Mark/Unmark Item" todo-toggle-mark-item t]
6466 ["Move (Recategorize) Item" todo-move-item t]
6467 ["Delete Item" todo-delete-item t]
6468 ["Mark and Bury Done Item" todo-item-done t]
6469 ["Undo Done Item" todo-item-undone t]
6470 ["Archive Done Item" todo-archive-done-item t]
6471 "---"
6472 ["Add New Category" todo-add-category t]
6473 ["Rename Current Category" todo-rename-category t]
6474 ["Delete Current Category" todo-delete-category t]
6475 ["Move Current Category" todo-move-category t]
6476 ["Merge Current Category" todo-merge-category t]
6477 "---"
6478 ["Add New Todo File" todo-add-file t]
6479 ["Rename Todo File" todo-rename-file t]
6480 ["Delete Todo File" todo-delete-file t]
6481 ["Edit Todo File" todo-edit-file t]
6483 ("Searching and Item Filtering"
6484 ["Search Todo File" todo-search t]
6485 ["Clear Match Highlighting" todo-clear-matches t]
6486 "---"
6487 ["Set Top Priorities in File" todo-set-top-priorities-in-file t]
6488 ["Set Top Priorities in Category" todo-set-top-priorities-in-category t]
6489 ["Filter Top Priorities" todo-filter-top-priorities t]
6490 ["Filter Multifile Top Priorities" todo-filter-top-priorities-multifile t]
6491 ["Filter Diary Items" todo-filter-diary-items t]
6492 ["Filter Multifile Diary Items" todo-filter-diary-items-multifile t]
6493 ["Filter Regexp" todo-filter-regexp-items t]
6494 ["Filter Multifile Regexp" todo-filter-regexp-items-multifile t]
6496 ("Display and Printing"
6497 ["Show/Hide Done Items" todo-toggle-view-done-items t]
6498 ["Show/Hide Done Items Only" todo-toggle-view-done-only t]
6499 ["Show/Hide Item Highlighting" todo-toggle-item-highlighting t]
6500 ["Show/Hide Item Numbering" todo-toggle-prefix-numbers t]
6501 ["Show/Hide Item Header" todo-toggle-item-header t]
6502 "---"
6503 ["Display Table of Categories" todo-show-categories-table t]
6504 "---"
6505 ["Print Category" todo-print-buffer t]
6506 ["Print Category to File" todo-print-buffer-to-file t]
6508 "---"
6509 ["Save Todo File" todo-save t]
6510 ["Quit Todo Mode" todo-quit t]
6513 ;; -----------------------------------------------------------------------------
6514 ;;; Hook functions and mode definitions
6515 ;; -----------------------------------------------------------------------------
6517 (defun todo-show-current-file ()
6518 "Visit current instead of default todo file with `todo-show'.
6519 Added to `pre-command-hook' in Todo mode when user option
6520 `todo-show-current-file' is set to non-nil."
6521 (setq todo-global-current-todo-file todo-current-todo-file))
6523 ;; (defun todo-display-as-todo-file ()
6524 ;; "Show todo files correctly when visited from outside of Todo mode.
6525 ;; Added to `find-file-hook' in Todo mode and Todo Archive mode."
6526 ;; (and (member this-command todo-visit-files-commands)
6527 ;; (= (- (point-max) (point-min)) (buffer-size))
6528 ;; (member major-mode '(todo-mode todo-archive-mode))
6529 ;; (todo-category-select)))
6531 ;; (defun todo-add-to-buffer-list ()
6532 ;; "Add name of just visited todo file to `todo-file-buffers'.
6533 ;; This function is added to `find-file-hook' in Todo mode."
6534 ;; (let ((filename (file-truename (buffer-file-name))))
6535 ;; (when (member filename todo-files)
6536 ;; (add-to-list 'todo-file-buffers filename))))
6538 (defun todo-update-buffer-list ()
6539 "Make current Todo mode buffer file car of `todo-file-buffers'.
6540 This function is added to `post-command-hook' in Todo mode."
6541 (let ((filename (file-truename (buffer-file-name))))
6542 (unless (eq (car todo-file-buffers) filename)
6543 (setq todo-file-buffers
6544 (cons filename (delete filename todo-file-buffers))))))
6546 (defun todo-reset-global-current-todo-file ()
6547 "Update the value of `todo-global-current-todo-file'.
6548 This becomes the latest existing todo file or, if there is none,
6549 the value of `todo-default-todo-file'.
6550 This function is added to `kill-buffer-hook' in Todo mode."
6551 (let ((filename (file-truename (buffer-file-name))))
6552 (setq todo-file-buffers (delete filename todo-file-buffers))
6553 (setq todo-global-current-todo-file
6554 (or (car todo-file-buffers)
6555 (todo-absolute-file-name todo-default-todo-file)))))
6557 (defun todo-reset-and-enable-done-separator ()
6558 "Show resized done items separator overlay after window change.
6559 Added to `window-configuration-change-hook' in Todo mode."
6560 (when (= 1 (length todo-done-separator-string))
6561 (let ((sep todo-done-separator))
6562 (setq todo-done-separator (todo-done-separator))
6563 (save-match-data (todo-reset-done-separator sep)))))
6565 (defun todo-modes-set-1 ()
6566 "Make some settings that apply to multiple Todo modes."
6567 (setq-local font-lock-defaults '(todo-font-lock-keywords t))
6568 (setq-local revert-buffer-function 'todo-revert-buffer)
6569 (setq-local tab-width todo-indent-to-here)
6570 (setq-local indent-line-function 'todo-indent)
6571 (when todo-wrap-lines
6572 (visual-line-mode)
6573 (setq wrap-prefix (make-string todo-indent-to-here 32))))
6575 (defun todo-modes-set-2 ()
6576 "Make some settings that apply to multiple Todo modes."
6577 (add-to-invisibility-spec 'todo)
6578 (setq buffer-read-only t)
6579 (when (and (boundp 'desktop-save-mode) desktop-save-mode)
6580 (setq-local desktop-save-buffer 'todo-desktop-save-buffer))
6581 (when (boundp 'hl-line-range-function)
6582 (setq-local hl-line-range-function
6583 (lambda() (save-excursion
6584 (when (todo-item-end)
6585 (cons (todo-item-start)
6586 (todo-item-end))))))))
6588 (defun todo-modes-set-3 ()
6589 "Make some settings that apply to multiple Todo modes."
6590 (setq-local todo-categories (todo-set-categories))
6591 (setq-local todo-category-number 1)
6592 ;; (add-hook 'find-file-hook 'todo-display-as-todo-file nil t)
6595 (put 'todo-mode 'mode-class 'special)
6597 ;;;###autoload
6598 (define-derived-mode todo-mode special-mode "Todo"
6599 "Major mode for displaying, navigating and editing todo lists.
6601 \\{todo-mode-map}"
6602 (if (called-interactively-p 'any)
6603 (message "%s"
6604 (substitute-command-keys
6605 "Type ‘\\[todo-show]’ to enter Todo mode"))
6606 (todo-modes-set-1)
6607 (todo-modes-set-2)
6608 (todo-modes-set-3)
6609 ;; Initialize todo-current-todo-file.
6610 (when (member (file-truename (buffer-file-name))
6611 (funcall todo-files-function))
6612 (setq-local todo-current-todo-file (file-truename (buffer-file-name))))
6613 (setq-local todo-show-done-only nil)
6614 (setq-local todo-categories-with-marks nil)
6615 ;; (add-hook 'find-file-hook 'todo-add-to-buffer-list nil t)
6616 (add-hook 'post-command-hook 'todo-update-buffer-list nil t)
6617 (when todo-show-current-file
6618 (add-hook 'pre-command-hook 'todo-show-current-file nil t))
6619 (add-hook 'window-configuration-change-hook
6620 'todo-reset-and-enable-done-separator nil t)
6621 (add-hook 'kill-buffer-hook 'todo-reset-global-current-todo-file nil t)))
6623 (put 'todo-archive-mode 'mode-class 'special)
6625 ;; If todo-mode is parent, all todo-mode key bindings appear to be
6626 ;; available in todo-archive-mode (e.g. shown by C-h m).
6627 ;;;###autoload
6628 (define-derived-mode todo-archive-mode special-mode "Todo-Arch"
6629 "Major mode for archived todo categories.
6631 \\{todo-archive-mode-map}"
6632 (todo-modes-set-1)
6633 (todo-modes-set-2)
6634 (todo-modes-set-3)
6635 (setq-local todo-current-todo-file (file-truename (buffer-file-name)))
6636 (setq-local todo-show-done-only t))
6638 (defun todo-mode-external-set ()
6639 "Set `todo-categories' externally to `todo-current-todo-file'."
6640 (setq-local todo-current-todo-file todo-global-current-todo-file)
6641 (let ((cats (with-current-buffer
6642 ;; Can't use find-buffer-visiting when
6643 ;; `todo-show-categories-table' is called on first
6644 ;; invocation of `todo-show', since there is then
6645 ;; no buffer visiting the current file.
6646 (find-file-noselect todo-current-todo-file 'nowarn)
6647 (or todo-categories
6648 ;; In Todo Edit mode todo-categories is now nil
6649 ;; since it uses same buffer as Todo mode but
6650 ;; doesn't have the latter's local variables.
6651 (save-excursion
6652 (goto-char (point-min))
6653 (read (buffer-substring-no-properties
6654 (line-beginning-position)
6655 (line-end-position))))))))
6656 (setq-local todo-categories cats)))
6658 (define-derived-mode todo-edit-mode text-mode "Todo-Ed"
6659 "Major mode for editing multiline todo items.
6661 \\{todo-edit-mode-map}"
6662 (todo-modes-set-1)
6663 (todo-mode-external-set)
6664 (setq buffer-read-only nil))
6666 (put 'todo-categories-mode 'mode-class 'special)
6668 (define-derived-mode todo-categories-mode special-mode "Todo-Cats"
6669 "Major mode for displaying and editing todo categories.
6671 \\{todo-categories-mode-map}"
6672 (todo-mode-external-set))
6674 (put 'todo-filtered-items-mode 'mode-class 'special)
6676 ;;;###autoload
6677 (define-derived-mode todo-filtered-items-mode special-mode "Todo-Fltr"
6678 "Mode for displaying and reprioritizing top priority Todo.
6680 \\{todo-filtered-items-mode-map}"
6681 (todo-modes-set-1)
6682 (todo-modes-set-2))
6684 ;; -----------------------------------------------------------------------------
6685 (provide 'todo-mode)
6687 ;;; todo-mode.el ends here