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