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