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