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