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