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