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