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