]> code.delx.au - gnu-emacs/blob - lisp/calendar/todos.el
* todos.el: Fixes for item marking and marked items.
[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() (when (todos-item-end)
2999 (cons (todos-item-start) (todos-item-end))))))
3000
3001 (defun todos-modes-set-3 ()
3002 ""
3003 (set (make-local-variable 'todos-categories) (todos-set-categories))
3004 (set (make-local-variable 'todos-category-number) 1)
3005 (add-hook 'find-file-hook 'todos-display-as-todos-file nil t))
3006
3007 (put 'todos-mode 'mode-class 'special)
3008
3009 (define-derived-mode todos-mode special-mode "Todos"
3010 "Major mode for displaying, navigating and editing Todo lists.
3011
3012 \\{todos-mode-map}"
3013 (easy-menu-add todos-menu)
3014 (todos-modes-set-1)
3015 (todos-modes-set-2)
3016 (todos-modes-set-3)
3017 ;; Initialize todos-current-todos-file.
3018 (when (member (file-truename (buffer-file-name))
3019 (funcall todos-files-function))
3020 (set (make-local-variable 'todos-current-todos-file)
3021 (file-truename (buffer-file-name))))
3022 (set (make-local-variable 'todos-show-done-only) nil)
3023 (set (make-local-variable 'todos-categories-with-marks) nil)
3024 (add-hook 'find-file-hook 'todos-add-to-buffer-list nil t)
3025 (add-hook 'post-command-hook 'todos-update-buffer-list nil t)
3026 (when todos-show-current-file
3027 (add-hook 'pre-command-hook 'todos-show-current-file nil t))
3028 (add-hook 'window-configuration-change-hook
3029 'todos-reset-and-enable-done-separator nil t)
3030 (add-hook 'kill-buffer-hook 'todos-reset-global-current-todos-file nil t))
3031
3032 (put 'todos-archive-mode 'mode-class 'special)
3033
3034 ;; If todos-mode is parent, all todos-mode key bindings appear to be
3035 ;; available in todos-archive-mode (e.g. shown by C-h m).
3036 (define-derived-mode todos-archive-mode special-mode "Todos-Arch"
3037 "Major mode for archived Todos categories.
3038
3039 \\{todos-archive-mode-map}"
3040 (todos-modes-set-1)
3041 (todos-modes-set-2)
3042 (todos-modes-set-3)
3043 (set (make-local-variable 'todos-current-todos-file)
3044 (file-truename (buffer-file-name)))
3045 (set (make-local-variable 'todos-show-done-only) t))
3046
3047 (defun todos-mode-external-set ()
3048 ""
3049 (set (make-local-variable 'todos-current-todos-file)
3050 todos-global-current-todos-file)
3051 (let ((cats (with-current-buffer
3052 ;; Can't use find-buffer-visiting when
3053 ;; `todos-show-categories-table' is called on first
3054 ;; invocation of `todos-show', since there is then
3055 ;; no buffer visiting the current file.
3056 (find-file-noselect todos-current-todos-file 'nowarn)
3057 (or todos-categories
3058 ;; In Todos Edit mode todos-categories is now nil
3059 ;; since it uses same buffer as Todos mode but
3060 ;; doesn't have the latter's local variables.
3061 (save-excursion
3062 (goto-char (point-min))
3063 (read (buffer-substring-no-properties
3064 (line-beginning-position)
3065 (line-end-position))))))))
3066 (set (make-local-variable 'todos-categories) cats)))
3067
3068 (define-derived-mode todos-edit-mode text-mode "Todos-Ed"
3069 "Major mode for editing multiline Todo items.
3070
3071 \\{todos-edit-mode-map}"
3072 (todos-modes-set-1)
3073 (todos-mode-external-set)
3074 (setq buffer-read-only nil))
3075
3076 (put 'todos-categories-mode 'mode-class 'special)
3077
3078 (define-derived-mode todos-categories-mode special-mode "Todos-Cats"
3079 "Major mode for displaying and editing Todos categories.
3080
3081 \\{todos-categories-mode-map}"
3082 (todos-mode-external-set))
3083
3084 (put 'todos-filtered-items-mode 'mode-class 'special)
3085
3086 (define-derived-mode todos-filtered-items-mode special-mode "Todos-Fltr"
3087 "Mode for displaying and reprioritizing top priority Todos.
3088
3089 \\{todos-filtered-items-mode-map}"
3090 (todos-modes-set-1)
3091 (todos-modes-set-2))
3092
3093 ;; ---------------------------------------------------------------------------
3094 ;;; Todos Commands
3095
3096 ;; ---------------------------------------------------------------------------
3097 ;;; Entering and Exiting
3098
3099 ;;;###autoload
3100 (defun todos-show (&optional solicit-file)
3101 "Visit a Todos file and display one of its categories.
3102
3103 When invoked in Todos mode, prompt for which todo file to visit.
3104 When invoked outside of Todos mode with non-nil prefix argument
3105 SOLICIT-FILE prompt for which todo file to visit; otherwise visit
3106 `todos-default-todos-file'. Subsequent invocations from outside
3107 of Todos mode revisit this file or, with option
3108 `todos-show-current-file' non-nil (the default), whichever Todos
3109 file was last visited.
3110
3111 Calling this command before any Todos file exists prompts for a
3112 file name and an initial category (defaulting to
3113 `todos-initial-file' and `todos-initial-category'), creates both
3114 of these, visits the file and displays the category.
3115
3116 The first invocation of this command on an existing Todos file
3117 interacts with the option `todos-show-first': if its value is
3118 `first' (the default), show the first category in the file; if
3119 its value is `table', show the table of categories in the file;
3120 if its value is one of `top', `diary' or `regexp', show the
3121 corresponding saved top priorities, diary items, or regexp items
3122 file, if any. Subsequent invocations always show the file's
3123 current (i.e., last displayed) category.
3124
3125 In Todos mode just the category's unfinished todo items are shown
3126 by default. The done items are hidden, but typing
3127 `\\[todos-toggle-view-done-items]' displays them below the todo
3128 items. With non-nil user option `todos-show-with-done' both todo
3129 and done items are always shown on visiting a category.
3130
3131 Invoking this command in Todos Archive mode visits the
3132 corresponding Todos file, displaying the corresponding category."
3133 (interactive "P")
3134 (let* ((cat)
3135 (show-first todos-show-first)
3136 (file (cond ((or (eq major-mode 'todos-mode)
3137 solicit-file)
3138 (if (funcall todos-files-function)
3139 (todos-read-file-name "Choose a Todos file to visit: "
3140 nil t)
3141 (error "There are no Todos files")))
3142 ((and (eq major-mode 'todos-archive-mode)
3143 ;; Called noninteractively via todos-quit from
3144 ;; Todos Categories mode to return to archive file.
3145 (called-interactively-p 'any))
3146 (setq cat (todos-current-category))
3147 (concat (file-name-sans-extension todos-current-todos-file)
3148 ".todo"))
3149 (t
3150 (or todos-current-todos-file
3151 (and todos-show-current-file
3152 todos-global-current-todos-file)
3153 (todos-absolute-file-name todos-default-todos-file)
3154 (todos-add-file))))))
3155 (unless (member file todos-visited)
3156 ;; Can't setq t-c-t-f here, otherwise wrong file shown when
3157 ;; todos-show is called from todos-show-categories-table.
3158 (let ((todos-current-todos-file file))
3159 (cond ((eq todos-show-first 'table)
3160 (todos-show-categories-table))
3161 ((memq todos-show-first '(top diary regexp))
3162 (let* ((shortf (todos-short-file-name file))
3163 (fi-file (todos-absolute-file-name
3164 shortf todos-show-first)))
3165 (when (eq todos-show-first 'regexp)
3166 (let ((rxfiles (directory-files todos-directory t
3167 ".*\\.todr$" t)))
3168 (when (and rxfiles (> (length rxfiles) 1))
3169 (let ((rxf (mapcar 'todos-short-file-name rxfiles)))
3170 (setq fi-file (todos-absolute-file-name
3171 (completing-read
3172 "Choose a regexp items file: "
3173 rxf) 'regexp))))))
3174 (if (file-exists-p fi-file)
3175 (set-window-buffer
3176 (selected-window)
3177 (set-buffer (find-file-noselect fi-file 'nowarn)))
3178 (message "There is no %s file for %s"
3179 (cond ((eq todos-show-first 'top)
3180 "top priorities")
3181 ((eq todos-show-first 'diary)
3182 "diary items")
3183 ((eq todos-show-first 'regexp)
3184 "regexp items"))
3185 shortf)
3186 (setq todos-show-first 'first)))))))
3187 (when (or (member file todos-visited)
3188 (eq todos-show-first 'first))
3189 (set-window-buffer (selected-window)
3190 (set-buffer (find-file-noselect file 'nowarn)))
3191 ;; If called from archive file, show corresponding
3192 ;; category in Todos file, if it exists.
3193 (when (assoc cat todos-categories)
3194 (setq todos-category-number (todos-category-number cat)))
3195 ;; If this is a new Todos file, add its first category.
3196 (when (zerop (buffer-size))
3197 (setq todos-category-number
3198 (todos-add-category todos-current-todos-file "")))
3199 (save-excursion (todos-category-select)))
3200 (setq todos-show-first show-first)
3201 (add-to-list 'todos-visited file)))
3202
3203 (defun todos-show-categories-table ()
3204 "Display a table of the current file's categories and item counts.
3205
3206 In the initial display the categories are numbered, indicating
3207 their current order for navigating by \\[todos-forward-category]
3208 and \\[todos-backward-category]. You can persistantly change the
3209 order of the category at point by typing
3210 \\[todos-raise-category-priority] or
3211 \\[todos-lower-category-priority].
3212
3213 The labels above the category names and item counts are buttons,
3214 and clicking these changes the display: sorted by category name
3215 or by the respective item counts (alternately descending or
3216 ascending). In these displays the categories are not numbered
3217 and \\[todos-raise-category-priority] and
3218 \\[todos-lower-category-priority] are
3219 disabled. (Programmatically, the sorting is triggered by passing
3220 a non-nil SORTKEY argument.)
3221
3222 In addition, the lines with the category names and item counts
3223 are buttonized, and pressing one of these button jumps to the
3224 category in Todos mode (or Todos Archive mode, for categories
3225 containing only archived items, provided user option
3226 `todos-skip-archived-categories' is non-nil. These categories
3227 are shown in `todos-archived-only' face."
3228 (interactive)
3229 (todos-display-categories-1)
3230 (let (sortkey)
3231 (todos-update-categories-display sortkey)))
3232
3233 (defun todos-sort-categories-alphabetically-or-by-priority ()
3234 ""
3235 (interactive)
3236 (save-excursion
3237 (goto-char (point-min))
3238 (forward-line 2)
3239 (if (member 'alpha todos-descending-counts)
3240 (progn
3241 (todos-update-categories-display nil)
3242 (setq todos-descending-counts
3243 (delete 'alpha todos-descending-counts)))
3244 (todos-update-categories-display 'alpha))))
3245
3246 (defun todos-sort-categories-by-todo ()
3247 ""
3248 (interactive)
3249 (save-excursion
3250 (goto-char (point-min))
3251 (forward-line 2)
3252 (todos-update-categories-display 'todo)))
3253
3254 (defun todos-sort-categories-by-diary ()
3255 ""
3256 (interactive)
3257 (save-excursion
3258 (goto-char (point-min))
3259 (forward-line 2)
3260 (todos-update-categories-display 'diary)))
3261
3262 (defun todos-sort-categories-by-done ()
3263 ""
3264 (interactive)
3265 (save-excursion
3266 (goto-char (point-min))
3267 (forward-line 2)
3268 (todos-update-categories-display 'done)))
3269
3270 (defun todos-sort-categories-by-archived ()
3271 ""
3272 (interactive)
3273 (save-excursion
3274 (goto-char (point-min))
3275 (forward-line 2)
3276 (todos-update-categories-display 'archived)))
3277
3278 (defun todos-show-archive (&optional ask)
3279 "Visit the archive of the current Todos category, if it exists.
3280 If the category has no archived items, prompt to visit the
3281 archive anyway. If there is no archive for this file or with
3282 non-nil argument ASK, prompt to visit another archive.
3283
3284 The buffer showing the archive is in Todos Archive mode. The
3285 first visit in a session displays the first category in the
3286 archive, subsequent visits return to the last category
3287 displayed."
3288 (interactive)
3289 (let* ((cat (todos-current-category))
3290 (count (todos-get-count 'archived cat))
3291 (archive (concat (file-name-sans-extension todos-current-todos-file)
3292 ".toda"))
3293 place)
3294 (setq place (cond (ask 'other-archive)
3295 ((file-exists-p archive) 'this-archive)
3296 (t (when (y-or-n-p (concat "This file has no archive; "
3297 "visit another archive? "))
3298 'other-archive))))
3299 (when (eq place 'other-archive)
3300 (setq archive (todos-read-file-name "Choose a Todos archive: " t t)))
3301 (when (and (eq place 'this-archive) (zerop count))
3302 (setq place (when (y-or-n-p
3303 (concat "This category has no archived items;"
3304 " visit archive anyway? "))
3305 'other-cat)))
3306 (when place
3307 (set-window-buffer (selected-window)
3308 (set-buffer (find-file-noselect archive)))
3309 (if (member place '(other-archive other-cat))
3310 (setq todos-category-number 1)
3311 (todos-category-number cat))
3312 (todos-category-select))))
3313
3314 (defun todos-choose-archive ()
3315 "Choose an archive and visit it."
3316 (interactive)
3317 (todos-show-archive t))
3318
3319 (defun todos-save ()
3320 "Save the current Todos file."
3321 (interactive)
3322 (cond ((eq major-mode 'todos-filtered-items-mode)
3323 (todos-check-filtered-items-file)
3324 (todos-save-filtered-items-buffer))
3325 (t
3326 (save-buffer))))
3327
3328 (defun todos-quit ()
3329 "Exit the current Todos-related buffer.
3330 Depending on the specific mode, this either kills the buffer or
3331 buries it and restores state as needed."
3332 (interactive)
3333 (cond ((eq major-mode 'todos-categories-mode)
3334 ;; Postpone killing buffer till after calling todos-show, to
3335 ;; prevent killing todos-mode buffer.
3336 (let ((buf (current-buffer)))
3337 (setq todos-descending-counts nil)
3338 ;; Ensure todos-show calls todos-show-categories-table only on
3339 ;; first invocation per file.
3340 (when (eq todos-show-first 'table)
3341 (add-to-list 'todos-visited todos-current-todos-file))
3342 (todos-show)
3343 (kill-buffer buf)))
3344 ((eq major-mode 'todos-filtered-items-mode)
3345 (kill-buffer)
3346 (unless (eq major-mode 'todos-mode) (todos-show)))
3347 ((member major-mode (list 'todos-mode 'todos-archive-mode))
3348 ;; Have to write previously nonexistant archives to file, and might
3349 ;; as well save Todos file also.
3350 (todos-save)
3351 (bury-buffer))))
3352
3353 (defun todos-print-buffer (&optional to-file)
3354 "Produce a printable version of the current Todos buffer.
3355 This converts overlays and soft line wrapping and, depending on
3356 the value of `todos-print-buffer-function', includes faces. With
3357 non-nil argument TO-FILE write the printable version to a file;
3358 otherwise, send it to the default printer."
3359 (interactive)
3360 (let ((buf todos-print-buffer)
3361 (header (cond
3362 ((eq major-mode 'todos-mode)
3363 (concat "Todos File: "
3364 (todos-short-file-name todos-current-todos-file)
3365 "\nCategory: " (todos-current-category)))
3366 ((eq major-mode 'todos-filtered-items-mode)
3367 "Todos Top Priorities")))
3368 (prefix (propertize (concat todos-prefix " ")
3369 'face 'todos-prefix-string))
3370 (num 0)
3371 (fill-prefix (make-string todos-indent-to-here 32))
3372 (content (buffer-string))
3373 file)
3374 (with-current-buffer (get-buffer-create buf)
3375 (insert content)
3376 (goto-char (point-min))
3377 (while (not (eobp))
3378 (let ((beg (point))
3379 (end (save-excursion (todos-item-end))))
3380 (when todos-number-prefix
3381 (setq num (1+ num))
3382 (setq prefix (propertize (concat (number-to-string num) " ")
3383 'face 'todos-prefix-string)))
3384 (insert prefix)
3385 (fill-region beg end))
3386 ;; Calling todos-forward-item infloops at todos-item-start due to
3387 ;; non-overlay prefix, so search for item start instead.
3388 (if (re-search-forward todos-item-start nil t)
3389 (beginning-of-line)
3390 (goto-char (point-max))))
3391 (if (re-search-backward (concat "^" (regexp-quote todos-category-done))
3392 nil t)
3393 (replace-match todos-done-separator))
3394 (goto-char (point-min))
3395 (insert header)
3396 (newline 2)
3397 (if to-file
3398 (let ((file (read-file-name "Print to file: ")))
3399 (funcall todos-print-buffer-function file))
3400 (funcall todos-print-buffer-function)))
3401 (kill-buffer buf)))
3402
3403 (defun todos-print-buffer-to-file ()
3404 "Save printable version of this Todos buffer to a file."
3405 (interactive)
3406 (todos-print-buffer t))
3407
3408 (defun todos-convert-legacy-files ()
3409 "Convert legacy Todo files to the current Todos format.
3410 The files `todo-file-do' and `todo-file-done' are converted and
3411 saved (the latter as a Todos Archive file) with a new name in
3412 `todos-directory'. See also the documentation string of
3413 `todos-todo-mode-date-time-regexp' for further details."
3414 (interactive)
3415 (if (fboundp 'todo-mode)
3416 (require 'todo-mode)
3417 (error "Void function `todo-mode'"))
3418 ;; Convert `todo-file-do'.
3419 (if (file-exists-p todo-file-do)
3420 (let ((default "todo-do-conv")
3421 file archive-sexp)
3422 (with-temp-buffer
3423 (insert-file-contents todo-file-do)
3424 (let ((end (search-forward ")" (line-end-position) t))
3425 (beg (search-backward "(" (line-beginning-position) t)))
3426 (setq todo-categories
3427 (read (buffer-substring-no-properties beg end))))
3428 (todo-mode)
3429 (delete-region (line-beginning-position) (1+ (line-end-position)))
3430 (while (not (eobp))
3431 (cond
3432 ((looking-at (regexp-quote (concat todo-prefix todo-category-beg)))
3433 (replace-match todos-category-beg))
3434 ((looking-at (regexp-quote todo-category-end))
3435 (replace-match ""))
3436 ((looking-at (regexp-quote (concat todo-prefix " "
3437 todo-category-sep)))
3438 (replace-match todos-category-done))
3439 ((looking-at (concat (regexp-quote todo-prefix) " "
3440 todos-todo-mode-date-time-regexp " "
3441 (regexp-quote todo-initials) ":"))
3442 (todos-convert-legacy-date-time)))
3443 (forward-line))
3444 (setq file (concat todos-directory
3445 (read-string
3446 (format "Save file as (default \"%s\"): " default)
3447 nil nil default)
3448 ".todo"))
3449 (write-region (point-min) (point-max) file nil 'nomessage nil t))
3450 (with-temp-buffer
3451 (insert-file-contents file)
3452 (let ((todos-categories (todos-make-categories-list t)))
3453 (todos-update-categories-sexp))
3454 (write-region (point-min) (point-max) file nil 'nomessage))
3455 ;; Convert `todo-file-done'.
3456 (when (file-exists-p todo-file-done)
3457 (with-temp-buffer
3458 (insert-file-contents todo-file-done)
3459 (let ((beg (make-marker))
3460 (end (make-marker))
3461 cat cats comment item)
3462 (while (not (eobp))
3463 (when (looking-at todos-todo-mode-date-time-regexp)
3464 (set-marker beg (point))
3465 (todos-convert-legacy-date-time)
3466 (set-marker end (point))
3467 (goto-char beg)
3468 (insert "[" todos-done-string)
3469 (goto-char end)
3470 (insert "]")
3471 (forward-char)
3472 (when (looking-at todos-todo-mode-date-time-regexp)
3473 (todos-convert-legacy-date-time))
3474 (when (looking-at (concat " " (regexp-quote todo-initials) ":"))
3475 (replace-match "")))
3476 (if (re-search-forward
3477 (concat "^" todos-todo-mode-date-time-regexp) nil t)
3478 (goto-char (match-beginning 0))
3479 (goto-char (point-max)))
3480 (backward-char)
3481 (when (looking-back "\\[\\([^][]+\\)\\]")
3482 (setq cat (match-string 1))
3483 (goto-char (match-beginning 0))
3484 (replace-match ""))
3485 ;; If the item ends with a non-comment parenthesis not
3486 ;; followed by a period, we lose (but we inherit that problem
3487 ;; from todo-mode.el).
3488 (when (looking-back "(\\(.*\\)) ")
3489 (setq comment (match-string 1))
3490 (replace-match "")
3491 (insert "[" todos-comment-string ": " comment "]"))
3492 (set-marker end (point))
3493 (if (member cat cats)
3494 ;; If item is already in its category, leave it there.
3495 (unless (save-excursion
3496 (re-search-backward
3497 (concat "^" (regexp-quote todos-category-beg)
3498 "\\(.*\\)$") nil t)
3499 (string= (match-string 1) cat))
3500 ;; Else move it to its category.
3501 (setq item (buffer-substring-no-properties beg end))
3502 (delete-region beg (1+ end))
3503 (set-marker beg (point))
3504 (re-search-backward
3505 (concat "^" (regexp-quote (concat todos-category-beg cat))
3506 "$")
3507 nil t)
3508 (forward-line)
3509 (if (re-search-forward
3510 (concat "^" (regexp-quote todos-category-beg)
3511 "\\(.*\\)$") nil t)
3512 (progn (goto-char (match-beginning 0))
3513 (newline)
3514 (forward-line -1))
3515 (goto-char (point-max)))
3516 (insert item "\n")
3517 (goto-char beg))
3518 (push cat cats)
3519 (goto-char beg)
3520 (insert todos-category-beg cat "\n\n" todos-category-done "\n"))
3521 (forward-line))
3522 (set-marker beg nil)
3523 (set-marker end nil))
3524 (setq file (concat (file-name-sans-extension file) ".toda"))
3525 (write-region (point-min) (point-max) file nil 'nomessage nil t))
3526 (with-temp-buffer
3527 (insert-file-contents file)
3528 (let ((todos-categories (todos-make-categories-list t)))
3529 (todos-update-categories-sexp))
3530 (write-region (point-min) (point-max) file nil 'nomessage)
3531 (setq archive-sexp (read (buffer-substring-no-properties
3532 (line-beginning-position)
3533 (line-end-position)))))
3534 (setq file (concat (file-name-sans-extension file) ".todo"))
3535 ;; Update categories sexp of converted Todos file again, adding
3536 ;; counts of archived items.
3537 (with-temp-buffer
3538 (insert-file-contents file)
3539 (let ((sexp (read (buffer-substring-no-properties
3540 (line-beginning-position)
3541 (line-end-position)))))
3542 (dolist (cat sexp)
3543 (let ((archive-cat (assoc (car cat) archive-sexp)))
3544 (if archive-cat
3545 (aset (cdr cat) 3 (aref (cdr archive-cat) 2)))))
3546 (delete-region (line-beginning-position) (line-end-position))
3547 (prin1 sexp (current-buffer)))
3548 (write-region (point-min) (point-max) file nil 'nomessage)))
3549 (todos-reevaluate-filelist-defcustoms)
3550 (message "Format conversion done."))
3551 (error "No legacy Todo file exists")))
3552
3553 ;; ---------------------------------------------------------------------------
3554 ;;; Navigation Commands
3555
3556 (defun todos-forward-category (&optional back)
3557 "Visit the numerically next category in this Todos file.
3558 If the current category is the highest numbered, visit the first
3559 category. With non-nil argument BACK, visit the numerically
3560 previous category (the highest numbered one, if the current
3561 category is the first)."
3562 (interactive)
3563 (setq todos-category-number
3564 (1+ (mod (- todos-category-number (if back 2 0))
3565 (length todos-categories))))
3566 (when todos-skip-archived-categories
3567 (while (and (zerop (todos-get-count 'todo))
3568 (zerop (todos-get-count 'done))
3569 (not (zerop (todos-get-count 'archived))))
3570 (setq todos-category-number
3571 (apply (if back '1- '1+) (list todos-category-number)))))
3572 (todos-category-select)
3573 (goto-char (point-min)))
3574
3575 (defun todos-backward-category ()
3576 "Visit the numerically previous category in this Todos file.
3577 If the current category is the highest numbered, visit the first
3578 category."
3579 (interactive)
3580 (todos-forward-category t))
3581
3582 ;;;###autoload
3583 (defun todos-jump-to-category (&optional file cat)
3584 "Prompt for a category in a Todos file and jump to it.
3585
3586 With prefix argument FILE, prompt for a specific Todos file and
3587 choose (with TAB completion) a category in it to jump to;
3588 otherwise, choose and jump to any category in either the current
3589 Todos file or a file in `todos-category-completions-files'.
3590
3591 You can also enter a non-existing category name, triggering a
3592 prompt whether to add a new category by that name; on
3593 confirmation it is added and jumped to.
3594
3595 Noninteractively, jump directly to the category named by argument
3596 CAT; this is used in Todos Categories mode."
3597 (interactive "P")
3598 ;; If invoked outside of Todos mode and there is not yet any Todos
3599 ;; file, initialize one.
3600 (if (null todos-files)
3601 (todos-show)
3602 (let ((file0 (when cat ; We're in Todos Categories mode.
3603 ;; With non-nil `todos-skip-archived-categories'
3604 ;; jump to archive file of a category with only
3605 ;; archived items.
3606 (if (and todos-skip-archived-categories
3607 (zerop (todos-get-count 'todo cat))
3608 (zerop (todos-get-count 'done cat))
3609 (not (zerop (todos-get-count 'archived cat))))
3610 (concat (file-name-sans-extension
3611 todos-current-todos-file) ".toda")
3612 ;; Otherwise, jump to current todos file.
3613 todos-current-todos-file)))
3614 (cat+file (unless cat
3615 (todos-read-category "Jump to category: " nil file))))
3616 (setq category (or cat (car cat+file)))
3617 (unless cat (setq file0 (cdr cat+file)))
3618 (with-current-buffer (find-file-noselect file0 'nowarn)
3619 (setq todos-current-todos-file file0)
3620 ;; If called from Todos Categories mode, clean up before jumping.
3621 (if (string= (buffer-name) todos-categories-buffer)
3622 (kill-buffer))
3623 (set-window-buffer (selected-window)
3624 (set-buffer (find-buffer-visiting file0)))
3625 (unless todos-global-current-todos-file
3626 (setq todos-global-current-todos-file todos-current-todos-file))
3627 (todos-category-number category)
3628 (todos-category-select)
3629 (goto-char (point-min))))))
3630
3631 (defun todos-go-to-source-item ()
3632 "Display the file and category of the filtered item at point."
3633 (interactive)
3634 (let* ((str (todos-item-string))
3635 (buf (current-buffer))
3636 (res (todos-find-item str))
3637 (found (nth 0 res))
3638 (file (nth 1 res))
3639 (cat (nth 2 res)))
3640 (if (not found)
3641 (message "Category %s does not contain this item." cat)
3642 (kill-buffer buf)
3643 (set-window-buffer (selected-window)
3644 (set-buffer (find-buffer-visiting file)))
3645 (setq todos-current-todos-file file)
3646 (setq todos-category-number (todos-category-number cat))
3647 (let ((todos-show-with-done (if (or todos-filter-done-items
3648 (eq (cdr found) 'done))
3649 t
3650 todos-show-with-done)))
3651 (todos-category-select))
3652 (goto-char (car found)))))
3653
3654 (defun todos-forward-item (&optional count)
3655 "Move point COUNT items down (by default, move down by one item)."
3656 (let* ((not-done (not (or (todos-done-item-p) (looking-at "^$"))))
3657 (start (line-end-position)))
3658 (goto-char start)
3659 (if (re-search-forward todos-item-start nil t (or count 1))
3660 (goto-char (match-beginning 0))
3661 (goto-char (point-max)))
3662 ;; If points advances by one from a todo to a done item, go back to the
3663 ;; space above todos-done-separator, since that is a legitimate place to
3664 ;; insert an item. But skip this space if count > 1, since that should
3665 ;; only stop on an item.
3666 (when (and not-done (todos-done-item-p) (not count))
3667 ;; (if (or (not count) (= count 1))
3668 (re-search-backward "^$" start t))));)
3669 ;; FIXME: The preceding sexp is insufficient when buffer is not narrowed,
3670 ;; since there could be no done items in this category, so the search puts
3671 ;; us on first todo item of next category. Does this ever happen? If so:
3672 ;; (let ((opoint) (point))
3673 ;; (forward-line -1)
3674 ;; (when (or (not count) (= count 1))
3675 ;; (cond ((looking-at (concat "^" (regexp-quote todos-category-beg)))
3676 ;; (forward-line -2))
3677 ;; ((looking-at (concat "^" (regexp-quote todos-category-done)))
3678 ;; (forward-line -1))
3679 ;; (t
3680 ;; (goto-char opoint)))))))
3681
3682 (defun todos-next-item (&optional count)
3683 "Move point down to the beginning of the next item.
3684 With positive numerical prefix COUNT, move point COUNT items
3685 downward.
3686
3687 If the category's done items are hidden, this command also moves
3688 point to the empty line below the last todo item from any higher
3689 item in the category, i.e., when invoked with or without a prefix
3690 argument. If the category's done items are visible, this command
3691 called with a prefix argument only moves point to a lower item,
3692 e.g., with point on the last todo item and called with prefix 1,
3693 it moves point to the first done item; but if called with point
3694 on the last todo item without a prefix argument, it moves point
3695 the the empty line above the done items separator."
3696 (interactive "p")
3697 ;; It's not worth the trouble to allow prefix arg value < 1, since we have
3698 ;; the corresponding command.
3699 (cond ((and current-prefix-arg (< count 1))
3700 (user-error "The prefix argument must be a positive number"))
3701 (current-prefix-arg
3702 (todos-forward-item count))
3703 (t
3704 (todos-forward-item))))
3705
3706 (defun todos-backward-item (&optional count)
3707 "Move point up to start of item with next higher priority.
3708 With positive numerical prefix COUNT, move point COUNT items
3709 upward.
3710
3711 If the category's done items are visible, this command called
3712 with a prefix argument only moves point to a higher item, e.g.,
3713 with point on the first done item and called with prefix 1, it
3714 moves to the last todo item; but if called with point on the
3715 first done item without a prefix argument, it moves point the the
3716 empty line above the done items separator."
3717 (let* ((done (todos-done-item-p)))
3718 (todos-item-start)
3719 (unless (bobp)
3720 (re-search-backward todos-item-start nil t (or count 1)))
3721 ;; Unless this is a regexp filtered items buffer (which can contain
3722 ;; intermixed todo and done items), if points advances by one from a
3723 ;; done to a todo item, go back to the space above
3724 ;; todos-done-separator, since that is a legitimate place to insert an
3725 ;; item. But skip this space if count > 1, since that should only
3726 ;; stop on an item.
3727 (when (and done (not (todos-done-item-p)) (not count)
3728 ;(or (not count) (= count 1))
3729 (not (equal (buffer-name) todos-regexp-items-buffer)))
3730 (re-search-forward (concat "^" (regexp-quote todos-category-done))
3731 nil t)
3732 (forward-line -1))))
3733
3734 (defun todos-previous-item (&optional count)
3735 "Move point up to start of item with next higher priority.
3736 With positive numerical prefix COUNT, move point COUNT items
3737 upward.
3738
3739 If the category's done items are visible, this command called
3740 with a prefix argument only moves point to a higher item, e.g.,
3741 with point on the first done item and called with prefix 1, it
3742 moves to the last todo item; but if called with point on the
3743 first done item without a prefix argument, it moves point the the
3744 empty line above the done items separator."
3745 (interactive "p")
3746 ;; Avoid moving to bob if on the first item but not at bob.
3747 (when (> (line-number-at-pos) 1)
3748 ;; It's not worth the trouble to allow prefix arg value < 1, since we have
3749 ;; the corresponding command.
3750 (cond ((and current-prefix-arg (< count 1))
3751 (user-error "The prefix argument must be a positive number"))
3752 (current-prefix-arg
3753 (todos-backward-item count))
3754 (t
3755 (todos-backward-item)))))
3756
3757 (defun todos-next-button (n &optional wrap display-message)
3758 ""
3759 (interactive "p\nd\nd")
3760 (forward-button n wrap display-message)
3761 (and (bolp) (button-at (point))
3762 ;; Align with beginning of category label.
3763 (forward-char (+ 4 (length todos-categories-number-separator)))))
3764
3765 (defun todos-previous-button (n &optional wrap display-message)
3766 ""
3767 (interactive "p\nd\nd")
3768 (backward-button n wrap display-message)
3769 (and (bolp) (button-at (point))
3770 ;; Align with beginning of category label.
3771 (forward-char (+ 4 (length todos-categories-number-separator)))))
3772
3773 (defun todos-search ()
3774 "Search for a regular expression in this Todos file.
3775 The search runs through the whole file and encompasses all and
3776 only todo and done items; it excludes category names. Multiple
3777 matches are shown sequentially, highlighted in `todos-search'
3778 face."
3779 (interactive)
3780 (let ((regex (read-from-minibuffer "Enter a search string (regexp): "))
3781 (opoint (point))
3782 matches match cat in-done ov mlen msg)
3783 (widen)
3784 (goto-char (point-min))
3785 (while (not (eobp))
3786 (setq match (re-search-forward regex nil t))
3787 (goto-char (line-beginning-position))
3788 (unless (or (equal (point) 1)
3789 (looking-at (concat "^" (regexp-quote todos-category-beg))))
3790 (if match (push match matches)))
3791 (forward-line))
3792 (setq matches (reverse matches))
3793 (if matches
3794 (catch 'stop
3795 (while matches
3796 (setq match (pop matches))
3797 (goto-char match)
3798 (todos-item-start)
3799 (when (looking-at todos-done-string-start)
3800 (setq in-done t))
3801 (re-search-backward (concat "^" (regexp-quote todos-category-beg)
3802 "\\(.*\\)\n") nil t)
3803 (setq cat (match-string-no-properties 1))
3804 (todos-category-number cat)
3805 (todos-category-select)
3806 (if in-done
3807 (unless todos-show-with-done (todos-toggle-view-done-items)))
3808 (goto-char match)
3809 (setq ov (make-overlay (- (point) (length regex)) (point)))
3810 (overlay-put ov 'face 'todos-search)
3811 (when matches
3812 (setq mlen (length matches))
3813 (if (y-or-n-p
3814 (if (> mlen 1)
3815 (format "There are %d more matches; go to next match? "
3816 mlen)
3817 "There is one more match; go to it? "))
3818 (widen)
3819 (throw 'stop (setq msg (if (> mlen 1)
3820 (format "There are %d more matches."
3821 mlen)
3822 "There is one more match."))))))
3823 (setq msg "There are no more matches."))
3824 (todos-category-select)
3825 (goto-char opoint)
3826 (message "No match for \"%s\"" regex))
3827 (when msg
3828 (if (y-or-n-p (concat msg "\nUnhighlight matches? "))
3829 (todos-clear-matches)
3830 (message "You can unhighlight the matches later by typing %s"
3831 (key-description (car (where-is-internal
3832 'todos-clear-matches))))))))
3833
3834 (defun todos-clear-matches ()
3835 "Remove highlighting on matches found by todos-search."
3836 (interactive)
3837 (remove-overlays 1 (1+ (buffer-size)) 'face 'todos-search))
3838
3839 ;; ---------------------------------------------------------------------------
3840 ;;; Display Commands
3841
3842 (defun todos-toggle-prefix-numbers ()
3843 ""
3844 (interactive)
3845 (todos-reset-prefix 'todos-number-prefix (not todos-number-prefix)))
3846
3847 (defun todos-toggle-view-done-items ()
3848 "Show hidden or hide visible done items in current category."
3849 (interactive)
3850 (if (zerop (todos-get-count 'done (todos-current-category)))
3851 (message "There are no done items in this category.")
3852 (let ((opoint (point)))
3853 (goto-char (point-min))
3854 (let* ((shown (re-search-forward todos-done-string-start nil t))
3855 (todos-show-with-done (not shown)))
3856 (todos-category-select)
3857 (goto-char opoint)
3858 ;; If start of done items sections is below the bottom of the
3859 ;; window, make it visible.
3860 (unless shown
3861 (setq shown (progn
3862 (goto-char (point-min))
3863 (re-search-forward todos-done-string-start nil t)))
3864 (if (not (pos-visible-in-window-p shown))
3865 (recenter)
3866 (goto-char opoint)))))))
3867
3868 (defun todos-toggle-view-done-only ()
3869 "Switch between displaying only done or only todo items."
3870 (interactive)
3871 (setq todos-show-done-only (not todos-show-done-only))
3872 (todos-category-select))
3873
3874 (defun todos-toggle-item-highlighting ()
3875 "Highlight or unhighlight the todo item the cursor is on."
3876 (interactive)
3877 (require 'hl-line)
3878 (if hl-line-mode
3879 (hl-line-mode -1)
3880 (hl-line-mode 1)))
3881
3882 (defun todos-toggle-item-header ()
3883 "Hide or show date-time header of todo items in the current file."
3884 (interactive)
3885 (save-excursion
3886 (save-restriction
3887 (goto-char (point-min))
3888 (if (todos-get-overlay 'header)
3889 (remove-overlays 1 (1+ (buffer-size)) 'todos 'header)
3890 (widen)
3891 (goto-char (point-min))
3892 (while (not (eobp))
3893 (when (re-search-forward
3894 (concat todos-date-string-start todos-date-pattern
3895 "\\( " diary-time-regexp "\\)?"
3896 (regexp-quote todos-nondiary-end) "? ")
3897 nil t)
3898 (unless (save-match-data (todos-done-item-p))
3899 (setq ov (make-overlay (match-beginning 0) (match-end 0) nil t))
3900 (overlay-put ov 'todos 'header)
3901 (overlay-put ov 'display "")))
3902 (todos-forward-item))))))
3903
3904 (defun todos-toggle-mark-item (&optional n)
3905 "Mark item with `todos-item-mark' if unmarked, otherwise unmark it.
3906 With a positive numerical prefix argument N, change the
3907 marking of the next N items."
3908 (interactive "p")
3909 (when (todos-item-string)
3910 (unless (> n 1) (setq n 1))
3911 (dotimes (i n)
3912 (let* ((cat (todos-current-category))
3913 (marks (assoc cat todos-categories-with-marks))
3914 (ov (progn
3915 (unless (looking-at todos-item-start)
3916 (todos-item-start))
3917 (todos-get-overlay 'prefix)))
3918 (pref (overlay-get ov 'before-string)))
3919 (if (todos-marked-item-p)
3920 (progn
3921 (overlay-put ov 'before-string (substring pref 1))
3922 (if (= (cdr marks) 1) ; Deleted last mark in this category.
3923 (setq todos-categories-with-marks
3924 (assq-delete-all cat todos-categories-with-marks))
3925 (setcdr marks (1- (cdr marks)))))
3926 (overlay-put ov 'before-string (concat todos-item-mark pref))
3927 (if marks
3928 (setcdr marks (1+ (cdr marks)))
3929 (push (cons cat 1) todos-categories-with-marks))))
3930 (todos-forward-item))))
3931
3932 (defun todos-mark-category ()
3933 "Mark all visiblw items in this category with `todos-item-mark'."
3934 (interactive)
3935 (let* ((cat (todos-current-category))
3936 (marks (assoc cat todos-categories-with-marks)))
3937 (save-excursion
3938 (goto-char (point-min))
3939 (while (not (eobp))
3940 (let* ((ov (todos-get-overlay 'prefix))
3941 (pref (overlay-get ov 'before-string)))
3942 (unless (todos-marked-item-p)
3943 (overlay-put ov 'before-string (concat todos-item-mark pref))
3944 (if marks
3945 (setcdr marks (1+ (cdr marks)))
3946 (push (cons cat 1) todos-categories-with-marks))))
3947 (todos-forward-item)))))
3948
3949 (defun todos-unmark-category ()
3950 "Remove `todos-item-mark' from all visible items in this category."
3951 (interactive)
3952 (let* ((cat (todos-current-category))
3953 (marks (assoc cat todos-categories-with-marks)))
3954 (save-excursion
3955 (goto-char (point-min))
3956 (while (not (eobp))
3957 (let* ((ov (todos-get-overlay 'prefix))
3958 ;; No overlay on empty line between todo and done items.
3959 (pref (when ov (overlay-get ov 'before-string))))
3960 (when (todos-marked-item-p)
3961 (overlay-put ov 'before-string (substring pref 1)))
3962 (todos-forward-item))))
3963 (setq todos-categories-with-marks (delq marks todos-categories-with-marks))))
3964
3965 ;; ---------------------------------------------------------------------------
3966 ;;; Item filtering commands
3967
3968 (defun todos-set-top-priorities-in-file ()
3969 "Set number of top priorities for this file.
3970 See `todos-set-top-priorities' for more details."
3971 (interactive)
3972 (todos-set-top-priorities))
3973
3974 (defun todos-set-top-priorities-in-category ()
3975 "Set number of top priorities for this category.
3976 See `todos-set-top-priorities' for more details."
3977 (interactive)
3978 (todos-set-top-priorities t))
3979
3980 (defun todos-filter-top-priorities (&optional arg)
3981 "Display a list of top priority items from different categories.
3982 The categories can be any of those in the current Todos file.
3983
3984 With numerical prefix ARG show at most ARG top priority items
3985 from each category. With `C-u' as prefix argument show the
3986 numbers of top priority items specified by category in
3987 `todos-top-priorities-overrides', if this has an entry for the file(s);
3988 otherwise show `todos-top-priorities' items per category in the
3989 file(s). With no prefix argument, if a top priorities file for
3990 the current Todos file has previously been saved (see
3991 `todos-save-filtered-items-buffer'), visit this file; if there is
3992 no such file, build the list as with prefix argument `C-u'.
3993
3994 The prefix ARG regulates how many top priorities from
3995 each category to show, as described above."
3996 (interactive "P")
3997 (todos-filter-items 'top arg))
3998
3999 (defun todos-filter-top-priorities-multifile (&optional arg)
4000 "Display a list of top priority items from different categories.
4001 The categories are a subset of the categories in the files listed
4002 in `todos-filter-files', or if this nil, in the files chosen from
4003 a file selection dialog that pops up in this case.
4004
4005 With numerical prefix ARG show at most ARG top priority items
4006 from each category in each file. With `C-u' as prefix argument
4007 show the numbers of top priority items specified in
4008 `todos-top-priorities-overrides', if this is non-nil; otherwise show
4009 `todos-top-priorities' items per category. With no prefix
4010 argument, if a top priorities file for the chosen Todos files
4011 exists (see `todos-save-filtered-items-buffer'), visit this file;
4012 if there is no such file, do the same as with prefix argument
4013 `C-u'."
4014 (interactive "P")
4015 (todos-filter-items 'top arg t))
4016
4017 (defun todos-filter-diary-items (&optional arg)
4018 "Display a list of todo diary items from different categories.
4019 The categories can be any of those in the current Todos file.
4020
4021 Called with no prefix argument, if a diary items file for the
4022 current Todos file has previously been saved (see
4023 `todos-save-filtered-items-buffer'), visit this file; if there is
4024 no such file, build the list of diary items. Called with a
4025 prefix argument, build the list even if there is a saved file of
4026 diary items."
4027 (interactive "P")
4028 (todos-filter-items 'diary arg))
4029
4030 (defun todos-filter-diary-items-multifile (&optional arg)
4031 "Display a list of todo diary items from different categories.
4032 The categories are a subset of the categories in the files listed
4033 in `todos-filter-files', or if this nil, in the files chosen from
4034 a file selection dialog that pops up in this case.
4035
4036 Called with no prefix argument, if a diary items file for the
4037 chosen Todos files has previously been saved (see
4038 `todos-save-filtered-items-buffer'), visit this file; if there is
4039 no such file, build the list of diary items. Called with a
4040 prefix argument, build the list even if there is a saved file of
4041 diary items."
4042 (interactive "P")
4043 (todos-filter-items 'diary arg t))
4044
4045 (defun todos-filter-regexp-items (&optional arg)
4046 "Prompt for a regular expression and display items that match it.
4047 The matches can be from any categories in the current Todos file
4048 and with non-nil option `todos-filter-done-items', can include
4049 not only todo items but also done items, including those in
4050 Archive files.
4051
4052 Called with no prefix argument, if a regexp items file for the
4053 current Todos file has previously been saved (see
4054 `todos-save-filtered-items-buffer'), visit this file; if there is
4055 no such file, build the list of regexp items. Called with a
4056 prefix argument, build the list even if there is a saved file of
4057 regexp items."
4058 (interactive "P")
4059 (todos-filter-items 'regexp arg))
4060
4061 (defun todos-filter-regexp-items-multifile (&optional arg)
4062 "Prompt for a regular expression and display items that match it.
4063 The matches can be from any categories in the files listed in
4064 `todos-filter-files', or if this nil, in the files chosen from a
4065 file selection dialog that pops up in this case. With non-nil
4066 option `todos-filter-done-items', the matches can include not
4067 only todo items but also done items, including those in Archive
4068 files.
4069
4070 Called with no prefix argument, if a regexp items file for the
4071 current Todos file has previously been saved (see
4072 `todos-save-filtered-items-buffer'), visit this file; if there is
4073 no such file, build the list of regexp items. Called with a
4074 prefix argument, build the list even if there is a saved file of
4075 regexp items."
4076 (interactive "P")
4077 (todos-filter-items 'regexp arg t))
4078
4079 ;; ---------------------------------------------------------------------------
4080 ;;; Editing Commands
4081
4082 (defun todos-add-file ()
4083 "Name and add a new Todos file.
4084 Interactively, prompt for a category and display it.
4085 Noninteractively, return the name of the new file."
4086 (interactive)
4087 (let ((prompt (concat "Enter name of new Todos file "
4088 "(TAB or SPC to see current names): "))
4089 file)
4090 (setq file (todos-read-file-name prompt))
4091 (with-current-buffer (get-buffer-create file)
4092 (erase-buffer)
4093 (write-region (point-min) (point-max) file nil 'nomessage nil t)
4094 (kill-buffer file))
4095 (todos-reevaluate-filelist-defcustoms)
4096 (if (called-interactively-p)
4097 (progn
4098 (set-window-buffer (selected-window)
4099 (set-buffer (find-file-noselect file)))
4100 (setq todos-current-todos-file file)
4101 (todos-show))
4102 file)))
4103
4104 ;;; Category editing commands
4105
4106 (defun todos-add-category (&optional file cat)
4107 "Add a new category to a Todos file.
4108
4109 Called interactively with prefix argument FILE, prompt for a file
4110 and then for a new category to add to that file, otherwise prompt
4111 just for a category to add to the current Todos file. After adding
4112 the category, visit it in Todos mode.
4113
4114 Non-interactively, add category CAT to file FILE; if FILE is nil,
4115 add CAT to the current Todos file. After adding the category,
4116 return the new category number."
4117 (interactive "P")
4118 (let (catfil file0)
4119 ;; If cat is passed from caller, don't prompt, unless it is "",
4120 ;; which means the file was just added and has no category yet.
4121 (if (and cat (> (length cat) 0))
4122 (setq file0 (or (and (stringp file) file)
4123 todos-current-todos-file))
4124 (setq catfil (todos-read-category "Enter a new category name: "
4125 'add (when (called-interactively-p 'any)
4126 file))
4127 cat (car catfil)
4128 file0 (if (called-interactively-p 'any)
4129 (cdr catfil)
4130 file)))
4131 (find-file file0)
4132 (let ((counts (make-vector 4 0)) ; [todo diary done archived]
4133 (num (1+ (length todos-categories)))
4134 (buffer-read-only nil))
4135 (setq todos-current-todos-file file0)
4136 (setq todos-categories (append todos-categories
4137 (list (cons cat counts))))
4138 (widen)
4139 (goto-char (point-max))
4140 (save-excursion ; Save point for todos-category-select.
4141 (insert todos-category-beg cat "\n\n" todos-category-done "\n"))
4142 (todos-update-categories-sexp)
4143 ;; If invoked by user, display the newly added category, if
4144 ;; called programmatically return the category number to the
4145 ;; caller.
4146 (if (called-interactively-p 'any)
4147 (progn
4148 (setq todos-category-number num)
4149 (todos-category-select))
4150 num))))
4151
4152 (defun todos-rename-category ()
4153 "Rename current Todos category.
4154 If this file has an archive containing this category, rename the
4155 category there as well."
4156 (interactive)
4157 (let* ((cat (todos-current-category))
4158 (new (read-from-minibuffer (format "Rename category \"%s\" to: " cat))))
4159 (setq new (todos-validate-name new 'category))
4160 (let* ((ofile todos-current-todos-file)
4161 (archive (concat (file-name-sans-extension ofile) ".toda"))
4162 (buffers (append (list ofile)
4163 (unless (zerop (todos-get-count 'archived cat))
4164 (list archive)))))
4165 (dolist (buf buffers)
4166 (with-current-buffer (find-file-noselect buf)
4167 (let (buffer-read-only)
4168 (setq todos-categories (todos-set-categories))
4169 (save-excursion
4170 (save-restriction
4171 (setcar (assoc cat todos-categories) new)
4172 (widen)
4173 (goto-char (point-min))
4174 (todos-update-categories-sexp)
4175 (re-search-forward (concat (regexp-quote todos-category-beg)
4176 "\\(" (regexp-quote cat) "\\)\n")
4177 nil t)
4178 (replace-match new t t nil 1)))))))
4179 (force-mode-line-update))
4180 (save-excursion (todos-category-select)))
4181
4182 (defun todos-delete-category (&optional arg)
4183 "Delete current Todos category provided it is empty.
4184 With ARG non-nil delete the category unconditionally,
4185 i.e. including all existing todo and done items."
4186 (interactive "P")
4187 (let* ((file todos-current-todos-file)
4188 (cat (todos-current-category))
4189 (todo (todos-get-count 'todo cat))
4190 (done (todos-get-count 'done cat))
4191 (archived (todos-get-count 'archived cat)))
4192 (if (and (not arg)
4193 (or (> todo 0) (> done 0)))
4194 (message "%s" (substitute-command-keys
4195 (concat "To delete a non-empty category, "
4196 "type C-u \\[todos-delete-category].")))
4197 (when (cond ((= (length todos-categories) 1)
4198 (y-or-n-p (concat "This is the only category in this file; "
4199 "deleting it will also delete the file.\n"
4200 "Do you want to proceed? ")))
4201 ((> archived 0)
4202 (y-or-n-p (concat "This category has archived items; "
4203 "the archived category will remain\n"
4204 "after deleting the todo category. "
4205 "Do you still want to delete it\n"
4206 "(see `todos-skip-archived-categories' "
4207 "for another option)? ")))
4208 (t
4209 (y-or-n-p (concat "Permanently remove category \"" cat
4210 "\"" (and arg " and all its entries")
4211 "? "))))
4212 (widen)
4213 (let ((buffer-read-only)
4214 (beg (re-search-backward
4215 (concat "^" (regexp-quote (concat todos-category-beg cat))
4216 "\n") nil t))
4217 (end (if (re-search-forward
4218 (concat "\n\\(" (regexp-quote todos-category-beg)
4219 ".*\n\\)") nil t)
4220 (match-beginning 1)
4221 (point-max))))
4222 (remove-overlays beg end)
4223 (delete-region beg end)
4224 (if (= (length todos-categories) 1)
4225 ;; If deleted category was the only one, delete the file.
4226 (progn
4227 (todos-reevaluate-filelist-defcustoms)
4228 ;; Skip confirming killing the archive buffer if it has been
4229 ;; modified and not saved.
4230 (set-buffer-modified-p nil)
4231 (delete-file file)
4232 (kill-buffer)
4233 (message "Deleted Todos file %s." file))
4234 (setq todos-categories (delete (assoc cat todos-categories)
4235 todos-categories))
4236 (todos-update-categories-sexp)
4237 (setq todos-category-number
4238 (1+ (mod todos-category-number (length todos-categories))))
4239 (todos-category-select)
4240 (goto-char (point-min))
4241 (message "Deleted category %s." cat)))))))
4242
4243 (defun todos-move-category ()
4244 "Move current category to a different Todos file.
4245 If current category has archived items, also move those to the
4246 archive of the file moved to, creating it if it does not exist."
4247 (interactive)
4248 (when (or (> (length todos-categories) 1)
4249 (y-or-n-p (concat "This is the only category in this file; "
4250 "moving it will also delete the file.\n"
4251 "Do you want to proceed? ")))
4252 (let* ((ofile todos-current-todos-file)
4253 (cat (todos-current-category))
4254 (nfile (todos-read-file-name
4255 "Choose a Todos file to move this category to: " nil t))
4256 (archive (concat (file-name-sans-extension ofile) ".toda"))
4257 (buffers (append (list ofile)
4258 (unless (zerop (todos-get-count 'archived cat))
4259 (list archive))))
4260 new)
4261 (while (equal (file-truename nfile) (file-truename ofile))
4262 (setq nfile (todos-read-file-name
4263 "Choose a file distinct from this file: " nil t)))
4264 (dolist (buf buffers)
4265 (with-current-buffer (find-file-noselect buf)
4266 (widen)
4267 (goto-char (point-max))
4268 (let* ((beg (re-search-backward
4269 (concat "^" (regexp-quote (concat todos-category-beg cat))
4270 "$")
4271 nil t))
4272 (end (if (re-search-forward
4273 (concat "^" (regexp-quote todos-category-beg))
4274 nil t 2)
4275 (match-beginning 0)
4276 (point-max)))
4277 (content (buffer-substring-no-properties beg end))
4278 (counts (cdr (assoc cat todos-categories)))
4279 buffer-read-only)
4280 ;; Move the category to the new file. Also update or create
4281 ;; archive file if necessary.
4282 (with-current-buffer
4283 (find-file-noselect
4284 ;; Regenerate todos-archives in case there
4285 ;; is a newly created archive.
4286 (if (member buf (funcall todos-files-function t))
4287 (concat (file-name-sans-extension nfile) ".toda")
4288 nfile))
4289 (let* ((nfile-short (todos-short-file-name nfile))
4290 (prompt (concat
4291 (format "Todos file \"%s\" already has "
4292 nfile-short)
4293 (format "the category \"%s\";\n" cat)
4294 "enter a new category name: "))
4295 buffer-read-only)
4296 (widen)
4297 (goto-char (point-max))
4298 (insert content)
4299 ;; If the file moved to has a category with the same
4300 ;; name, rename the moved category.
4301 (when (assoc cat todos-categories)
4302 (unless (member (file-truename (buffer-file-name))
4303 (funcall todos-files-function t))
4304 (setq new (read-from-minibuffer prompt))
4305 (setq new (todos-validate-name new 'category))))
4306 ;; Replace old with new name in Todos and archive files.
4307 (when new
4308 (goto-char (point-max))
4309 (re-search-backward
4310 (concat "^" (regexp-quote todos-category-beg)
4311 "\\(" (regexp-quote cat) "\\)$") nil t)
4312 (replace-match new nil nil nil 1)))
4313 (setq todos-categories
4314 (append todos-categories (list (cons new counts))))
4315 (todos-update-categories-sexp)
4316 ;; If archive was just created, save it to avoid "File
4317 ;; <xyz> no longer exists!" message on invoking
4318 ;; `todos-view-archived-items'.
4319 (unless (file-exists-p (buffer-file-name))
4320 (save-buffer))
4321 (todos-category-number (or new cat))
4322 (todos-category-select))
4323 ;; Delete the category from the old file, and if that was the
4324 ;; last category, delete the file. Also handle archive file
4325 ;; if necessary.
4326 (remove-overlays beg end)
4327 (delete-region beg end)
4328 (goto-char (point-min))
4329 ;; Put point after todos-categories sexp.
4330 (forward-line)
4331 (if (eobp) ; Aside from sexp, file is empty.
4332 (progn
4333 ;; Skip confirming killing the archive buffer.
4334 (set-buffer-modified-p nil)
4335 (delete-file todos-current-todos-file)
4336 (kill-buffer)
4337 (when (member todos-current-todos-file todos-files)
4338 (todos-reevaluate-filelist-defcustoms)))
4339 (setq todos-categories (delete (assoc cat todos-categories)
4340 todos-categories))
4341 (todos-update-categories-sexp)
4342 (todos-category-select)))))
4343 (set-window-buffer (selected-window)
4344 (set-buffer (find-file-noselect nfile)))
4345 (todos-category-number (or new cat))
4346 (todos-category-select))))
4347
4348 (defun todos-merge-category (&optional file)
4349 "Merge current category into another existing category.
4350
4351 With prefix argument FILE, prompt for a specific Todos file and
4352 choose (with TAB completion) a category in it to merge into;
4353 otherwise, choose and merge into a category in either the
4354 current Todos file or a file in `todos-category-completions-files'.
4355
4356 After merging, the current category's todo and done items are
4357 appended to the chosen goal category's todo and done items,
4358 respectively. The goal category becomes the current category,
4359 and the previous current category is deleted.
4360
4361 If both the first and goal categories also have archived items,
4362 the former are merged to the latter. If only the first category
4363 has archived items, the archived category is renamed to the goal
4364 category."
4365 (interactive "P")
4366 (let* ((tfile todos-current-todos-file)
4367 (archive (concat (file-name-sans-extension (if file gfile tfile))
4368 ".toda"))
4369 (cat (todos-current-category))
4370 (cat+file (todos-read-category "Merge into category: " 'merge file))
4371 (goal (car cat+file))
4372 (gfile (cdr cat+file))
4373 archived-count here)
4374 ;; Merge in todo file.
4375 (with-current-buffer (get-buffer (find-file-noselect tfile))
4376 (widen)
4377 (let* ((buffer-read-only nil)
4378 (cbeg (progn
4379 (re-search-backward
4380 (concat "^" (regexp-quote todos-category-beg)) nil t)
4381 (point-marker)))
4382 (tbeg (progn (forward-line) (point-marker)))
4383 (dbeg (progn
4384 (re-search-forward
4385 (concat "^" (regexp-quote todos-category-done)) nil t)
4386 (forward-line) (point-marker)))
4387 ;; Omit empty line between todo and done items.
4388 (tend (progn (forward-line -2) (point-marker)))
4389 (cend (progn
4390 (if (re-search-forward
4391 (concat "^" (regexp-quote todos-category-beg)) nil t)
4392 (progn
4393 (goto-char (match-beginning 0))
4394 (point-marker))
4395 (point-max-marker))))
4396 (todo (buffer-substring-no-properties tbeg tend))
4397 (done (buffer-substring-no-properties dbeg cend)))
4398 (goto-char (point-min))
4399 ;; Merge any todo items.
4400 (unless (zerop (length todo))
4401 (re-search-forward
4402 (concat "^" (regexp-quote (concat todos-category-beg goal)) "$")
4403 nil t)
4404 (re-search-forward
4405 (concat "^" (regexp-quote todos-category-done)) nil t)
4406 (forward-line -1)
4407 (setq here (point-marker))
4408 (insert todo)
4409 (todos-update-count 'todo (todos-get-count 'todo cat) goal))
4410 ;; Merge any done items.
4411 (unless (zerop (length done))
4412 (goto-char (if (re-search-forward
4413 (concat "^" (regexp-quote todos-category-beg)) nil t)
4414 (match-beginning 0)
4415 (point-max)))
4416 (when (zerop (length todo)) (setq here (point-marker)))
4417 (insert done)
4418 (todos-update-count 'done (todos-get-count 'done cat) goal))
4419 (remove-overlays cbeg cend)
4420 (delete-region cbeg cend)
4421 (setq todos-categories (delete (assoc cat todos-categories)
4422 todos-categories))
4423 (todos-update-categories-sexp)
4424 (mapc (lambda (m) (set-marker m nil)) (list cbeg tbeg dbeg tend cend))))
4425 (when (file-exists-p archive)
4426 ;; Merge in archive file.
4427 (with-current-buffer (get-buffer (find-file-noselect archive))
4428 (widen)
4429 (goto-char (point-min))
4430 (let ((buffer-read-only nil)
4431 (cbeg (save-excursion
4432 (when (re-search-forward
4433 (concat "^" (regexp-quote
4434 (concat todos-category-beg cat)) "$")
4435 nil t)
4436 (goto-char (match-beginning 0))
4437 (point-marker))))
4438 (gbeg (save-excursion
4439 (when (re-search-forward
4440 (concat "^" (regexp-quote
4441 (concat todos-category-beg goal)) "$")
4442 nil t)
4443 (goto-char (match-beginning 0))
4444 (point-marker))))
4445 cend carch)
4446 (when cbeg
4447 (setq archived-count (todos-get-count 'done cat))
4448 (setq cend (save-excursion
4449 (if (re-search-forward
4450 (concat "^" (regexp-quote todos-category-beg))
4451 nil t)
4452 (match-beginning 0)
4453 (point-max))))
4454 (setq carch (save-excursion (goto-char cbeg) (forward-line)
4455 (buffer-substring-no-properties (point) cend)))
4456 ;; If both categories of the merge have archived items, merge the
4457 ;; source items to the goal items, else "merge" by renaming the
4458 ;; source category to goal.
4459 (if gbeg
4460 (progn
4461 (goto-char (if (re-search-forward
4462 (concat "^" (regexp-quote todos-category-beg))
4463 nil t)
4464 (match-beginning 0)
4465 (point-max)))
4466 (insert carch)
4467 (remove-overlays cbeg cend)
4468 (delete-region cbeg cend))
4469 (goto-char cbeg)
4470 (search-forward cat)
4471 (replace-match goal))
4472 (setq todos-categories (todos-make-categories-list t))
4473 (todos-update-categories-sexp)))))
4474 (with-current-buffer (get-file-buffer tfile)
4475 (when archived-count
4476 (unless (zerop archived-count)
4477 (todos-update-count 'archived archived-count goal)
4478 (todos-update-categories-sexp)))
4479 (todos-category-number goal)
4480 ;; If there are only merged done items, show them.
4481 (let ((todos-show-with-done (zerop (todos-get-count 'todo goal))))
4482 (todos-category-select)
4483 ;; Put point on the first merged item.
4484 (goto-char here)))
4485 (set-marker here nil)))
4486
4487 (defun todos-set-category-priority (&optional arg)
4488 "Change priority of category at point in Todos Categories buffer.
4489
4490 With ARG nil, prompt for the new priority number. Alternatively,
4491 the new priority can be provided by a numerical prefix ARG.
4492 Otherwise, if ARG is either of the symbols `raise' or `lower',
4493 raise or lower the category's priority by one."
4494 (interactive "P")
4495 (let ((curnum (save-excursion
4496 ;; Get the number representing the priority of the category
4497 ;; on the current line.
4498 (forward-line 0) (skip-chars-forward " ") (number-at-point))))
4499 (when curnum ; Do nothing if we're not on a category line.
4500 (let* ((maxnum (length todos-categories))
4501 (prompt (format "Set category priority (1-%d): " maxnum))
4502 (col (current-column))
4503 (buffer-read-only nil)
4504 (priority (cond ((and (eq arg 'raise) (> curnum 1))
4505 (1- curnum))
4506 ((and (eq arg 'lower) (< curnum maxnum))
4507 (1+ curnum))))
4508 candidate)
4509 (while (not priority)
4510 (setq candidate (or arg (read-number prompt)))
4511 (setq arg nil)
4512 (setq prompt
4513 (cond ((or (< candidate 1) (> candidate maxnum))
4514 (format "Priority must be an integer between 1 and %d: "
4515 maxnum))
4516 ((= candidate curnum)
4517 "Choose a different priority than the current one: ")))
4518 (unless prompt (setq priority candidate)))
4519 (let* ((lower (< curnum priority)) ; Priority is being lowered.
4520 (head (butlast todos-categories
4521 (apply (if lower 'identity '1+)
4522 (list (- maxnum priority)))))
4523 (tail (nthcdr (apply (if lower 'identity '1-) (list priority))
4524 todos-categories))
4525 ;; Category's name and items counts list.
4526 (catcons (nth (1- curnum) todos-categories))
4527 (todos-categories (nconc head (list catcons) tail))
4528 newcats)
4529 (when lower (setq todos-categories (nreverse todos-categories)))
4530 (setq todos-categories (delete-dups todos-categories))
4531 (when lower (setq todos-categories (nreverse todos-categories)))
4532 (setq newcats todos-categories)
4533 (kill-buffer)
4534 (with-current-buffer (find-buffer-visiting todos-current-todos-file)
4535 (setq todos-categories newcats)
4536 (todos-update-categories-sexp))
4537 (todos-show-categories-table)
4538 (forward-line (1+ priority))
4539 (forward-char col))))))
4540
4541 (defun todos-raise-category-priority ()
4542 "Raise priority of category at point in Todos Categories buffer."
4543 (interactive)
4544 (todos-set-category-priority 'raise))
4545
4546 (defun todos-lower-category-priority ()
4547 "Lower priority of category at point in Todos Categories buffer."
4548 (interactive)
4549 (todos-set-category-priority 'lower))
4550
4551 ;; ---------------------------------------------------------------------------
4552 ;;; Item editing commands
4553
4554 ;;;###autoload
4555 (defun todos-insert-item-1 (&optional arg diary nonmarking date-type time
4556 region-or-here)
4557 "Add a new Todo item to a category.
4558 \(See the note at the end of this document string about key
4559 bindings and convenience commands derived from this command.)
4560
4561 With no (or nil) prefix argument ARG, add the item to the current
4562 category; with one prefix argument (C-u), prompt for a category
4563 from the current Todos file; with two prefix arguments (C-u C-u),
4564 first prompt for a Todos file, then a category in that file. If
4565 a non-existing category is entered, ask whether to add it to the
4566 Todos file; if answered affirmatively, add the category and
4567 insert the item there.
4568
4569 When argument DIARY is non-nil, this overrides the intent of the
4570 user option `todos-include-in-diary' for this item: if
4571 `todos-include-in-diary' is nil, include the item in the Fancy
4572 Diary display, and if it is non-nil, exclude the item from the
4573 Fancy Diary display. When DIARY is nil, `todos-include-in-diary'
4574 has its intended effect.
4575
4576 When the item is included in the Fancy Diary display and the
4577 argument NONMARKING is non-nil, this overrides the intent of the
4578 user option `todos-diary-nonmarking' for this item: if
4579 `todos-diary-nonmarking' is nil, append `diary-nonmarking-symbol'
4580 to the item, and if it is non-nil, omit `diary-nonmarking-symbol'.
4581
4582 The argument DATE-TYPE determines the content of the item's
4583 mandatory date header string and how it is added:
4584 - If DATE-TYPE is the symbol `calendar', the Calendar pops up and
4585 when the user puts the cursor on a date and hits RET, that
4586 date, in the format set by `calendar-date-display-form',
4587 becomes the date in the header.
4588 - If DATE-TYPE is a string matching the regexp
4589 `todos-date-pattern', that string becomes the date in the
4590 header. This case is for the command
4591 `todos-insert-item-from-calendar' which is called from the
4592 Calendar.
4593 - If DATE-TYPE is the symbol `date', the header contains the date
4594 in the format set by `calendar-date-display-form', with year,
4595 month and day individually prompted for (month with tab
4596 completion).
4597 - If DATE-TYPE is the symbol `dayname' the header contains a
4598 weekday name instead of a date, prompted for with tab
4599 completion.
4600 - If DATE-TYPE has any other value (including nil or none) the
4601 header contains the current date (in the format set by
4602 `calendar-date-display-form').
4603
4604 With non-nil argument TIME prompt for a time string, which must
4605 match `diary-time-regexp'. Typing `<return>' at the prompt
4606 returns the current time, if the user option
4607 `todos-always-add-time-string' is non-nil, otherwise the empty
4608 string (i.e., no time string). If TIME is absent or nil, add or
4609 omit the current time string according as
4610 `todos-always-add-time-string' is non-nil or nil, respectively.
4611
4612 The argument REGION-OR-HERE determines the source and location of
4613 the new item:
4614 - If the REGION-OR-HERE is the symbol `here', prompt for the text
4615 of the new item and, if the command was invoked in the current
4616 category, insert it directly above the todo item at
4617 point (hence lowering the priority of the remaining items), or
4618 if point is on the empty line below the last todo item, insert
4619 the new item there. If point is in the done items section of
4620 the category, insert the new item as the first todo item in the
4621 category. Likewise, if the command with `here' is invoked
4622 outside of the current category, jump to the chosen category
4623 and insert the new item as the first item in the category.
4624 - If REGION-OR-HERE is the symbol `region', use the region of the
4625 current buffer as the text of the new item, depending on the
4626 value of user option `todos-use-only-highlighted-region': if
4627 this is non-nil, then use the region only when it is
4628 highlighted; otherwise, use the region regardless of
4629 highlighting. An error is signalled if there is no region in
4630 the current buffer. Prompt for the item's priority in the
4631 category (an integer between 1 and one more than the number of
4632 items in the category), and insert the item accordingly.
4633 - If REGION-OR-HERE has any other value (in particular, nil or
4634 none), prompt for the text and the item's priority, and insert
4635 the item accordingly.
4636
4637 To facilitate using these arguments when inserting a new todo
4638 item, convenience commands have been defined for all admissible
4639 combinations together with mnenomic key bindings based on on the
4640 name of the arguments and their order in the command's argument
4641 list: diar_y_ - nonmar_k_ing - _c_alendar or _d_ate or day_n_ame
4642 - _t_ime - _r_egion or _h_ere. These key combinations are
4643 appended to the basic insertion key (i) and keys that allow a
4644 following key must be doubled when used finally. For example,
4645 `iyh' will insert a new item with today's date, marked according
4646 to the DIARY argument described above, and with priority
4647 according to the HERE argument; while `iyy' does the same except
4648 the priority is not given by HERE but by prompting."
4649 ;; An alternative interface for customizing key
4650 ;; binding is also provided with the function
4651 ;; `todos-insertion-bindings'." ;FIXME
4652 ;; (interactive "P")
4653 ;; If invoked outside of Todos mode and there is not yet any Todos
4654 ;; file, initialize one.
4655 (if (null todos-files)
4656 (todos-show)
4657 (let ((region (eq region-or-here 'region))
4658 (here (eq region-or-here 'here)))
4659 (when region
4660 (let (use-empty-active-region)
4661 (unless (and todos-use-only-highlighted-region (use-region-p))
4662 (error "There is no active region"))))
4663 (let* ((obuf (current-buffer))
4664 (ocat (todos-current-category))
4665 (opoint (point))
4666 (todos-mm (eq major-mode 'todos-mode))
4667 (cat+file (cond ((equal arg '(4))
4668 (todos-read-category "Insert in category: "))
4669 ((equal arg '(16))
4670 (todos-read-category "Insert in category: "
4671 nil 'file))
4672 (t
4673 (cons (todos-current-category)
4674 (or todos-current-todos-file
4675 (and todos-show-current-file
4676 todos-global-current-todos-file)
4677 (todos-absolute-file-name
4678 todos-default-todos-file))))))
4679 (cat (car cat+file))
4680 (file (cdr cat+file))
4681 (new-item (if region
4682 (buffer-substring-no-properties
4683 (region-beginning) (region-end))
4684 (read-from-minibuffer "Todo item: ")))
4685 (date-string (cond
4686 ((eq date-type 'date)
4687 (todos-read-date))
4688 ((eq date-type 'dayname)
4689 (todos-read-dayname))
4690 ((eq date-type 'calendar)
4691 (setq todos-date-from-calendar t)
4692 (or (todos-set-date-from-calendar)
4693 ;; If user exits Calendar before choosing
4694 ;; a date, cancel item insertion.
4695 (keyboard-quit)))
4696 ((and (stringp date-type)
4697 (string-match todos-date-pattern date-type))
4698 (setq todos-date-from-calendar date-type)
4699 (todos-set-date-from-calendar))
4700 (t
4701 (calendar-date-string (calendar-current-date) t t))))
4702 (time-string (or (and time (todos-read-time))
4703 (and todos-always-add-time-string
4704 (substring (current-time-string) 11 16)))))
4705 (setq todos-date-from-calendar nil)
4706 (find-file-noselect file 'nowarn)
4707 (set-window-buffer (selected-window)
4708 (set-buffer (find-buffer-visiting file)))
4709 ;; If this command was invoked outside of a Todos buffer, the
4710 ;; call to todos-current-category above returned nil. If we
4711 ;; just entered Todos mode now, then cat was set to the file's
4712 ;; first category, but if todos-mode was already enabled, cat
4713 ;; did not get set, so we have to set it explicitly.
4714 (unless cat
4715 (setq cat (todos-current-category)))
4716 (setq todos-current-todos-file file)
4717 (unless todos-global-current-todos-file
4718 (setq todos-global-current-todos-file todos-current-todos-file))
4719 (let ((buffer-read-only nil)
4720 (called-from-outside (not (and todos-mm (equal cat ocat))))
4721 done-only item-added)
4722 (setq new-item
4723 ;; Add date, time and diary marking as required.
4724 (concat (if (not (and diary (not todos-include-in-diary)))
4725 todos-nondiary-start
4726 (when (and nonmarking (not todos-diary-nonmarking))
4727 diary-nonmarking-symbol))
4728 date-string (when (and time-string ; Can be empty string.
4729 (not (zerop (length time-string))))
4730 (concat " " time-string))
4731 (when (not (and diary (not todos-include-in-diary)))
4732 todos-nondiary-end)
4733 " " new-item))
4734 ;; Indent newlines inserted by C-q C-j if nonspace char follows.
4735 (setq new-item (replace-regexp-in-string
4736 "\\(\n\\)[^[:blank:]]"
4737 (concat "\n" (make-string todos-indent-to-here 32))
4738 new-item nil nil 1))
4739 (unwind-protect
4740 (progn
4741 ;; Make sure the correct category is selected. There
4742 ;; are two cases: (i) we just visited the file, so no
4743 ;; category is selected yet, or (ii) we invoked
4744 ;; insertion "here" from outside the category we want
4745 ;; to insert in (with priority insertion, category
4746 ;; selection is done by todos-set-item-priority).
4747 (when (or (= (- (point-max) (point-min)) (buffer-size))
4748 (and here called-from-outside))
4749 (todos-category-number cat)
4750 (todos-category-select))
4751 ;; If only done items are displayed in category,
4752 ;; toggle to todo items before inserting new item.
4753 (when (save-excursion
4754 (goto-char (point-min))
4755 (looking-at todos-done-string-start))
4756 (setq done-only t)
4757 (todos-toggle-view-done-only))
4758 (if here
4759 (progn
4760 ;; If command was invoked with point in done
4761 ;; items section or outside of the current
4762 ;; category, can't insert "here", so to be
4763 ;; useful give new item top priority.
4764 (when (or (todos-done-item-section-p)
4765 called-from-outside
4766 done-only)
4767 (goto-char (point-min)))
4768 (todos-insert-with-overlays new-item))
4769 (todos-set-item-priority new-item cat t))
4770 (setq item-added t))
4771 ;; If user cancels before setting priority, restore
4772 ;; display.
4773 (unless item-added
4774 (if ocat
4775 (progn
4776 (unless (equal cat ocat)
4777 (todos-category-number ocat)
4778 (todos-category-select))
4779 (and done-only (todos-toggle-view-done-only)))
4780 (set-window-buffer (selected-window) (set-buffer obuf)))
4781 (goto-char opoint))
4782 ;; If the todo items section is not visible when the
4783 ;; insertion command is called (either because only done
4784 ;; items were shown or because the category was not in the
4785 ;; current buffer), then if the item is inserted at the
4786 ;; end of the category, point is at eob and eob at
4787 ;; window-start, so that higher priority todo items are
4788 ;; out of view. So we recenter to make sure the todo
4789 ;; items are displayed in the window.
4790 (when item-added (recenter)))
4791 (todos-update-count 'todo 1)
4792 (if (or diary todos-include-in-diary) (todos-update-count 'diary 1))
4793 (todos-update-categories-sexp))))))
4794
4795 (defun todos-copy-item ()
4796 "Copy item at point and insert the copy as a new item."
4797 (interactive)
4798 (unless (or (todos-done-item-p) (looking-at "^$"))
4799 (let ((copy (todos-item-string))
4800 (diary-item (todos-diary-item-p)))
4801 (todos-set-item-priority copy (todos-current-category) t)
4802 (todos-update-count 'todo 1)
4803 (when diary-item (todos-update-count 'diary 1))
4804 (todos-update-categories-sexp))))
4805
4806 (defvar todos-date-from-calendar nil
4807 "Helper variable for setting item date from the Emacs Calendar.")
4808
4809 (defun todos-set-date-from-calendar ()
4810 "Return string of date chosen from Calendar."
4811 (cond ((and (stringp todos-date-from-calendar)
4812 (string-match todos-date-pattern todos-date-from-calendar))
4813 todos-date-from-calendar)
4814 (todos-date-from-calendar
4815 (let (calendar-view-diary-initially-flag)
4816 (calendar)) ; *Calendar* is now current buffer.
4817 (define-key calendar-mode-map [remap newline] 'exit-recursive-edit)
4818 ;; If user exits Calendar before choosing a date, clean up properly.
4819 (define-key calendar-mode-map
4820 [remap calendar-exit] (lambda ()
4821 (interactive)
4822 (progn
4823 (calendar-exit)
4824 (exit-recursive-edit))))
4825 (message "Put cursor on a date and type <return> to set it.")
4826 (recursive-edit)
4827 (unwind-protect
4828 (when (equal (buffer-name) calendar-buffer)
4829 (setq todos-date-from-calendar
4830 (calendar-date-string (calendar-cursor-to-date t) t t))
4831 (calendar-exit)
4832 todos-date-from-calendar)
4833 (define-key calendar-mode-map [remap newline] nil)
4834 (define-key calendar-mode-map [remap calendar-exit] nil)
4835 (unless (zerop (recursion-depth)) (exit-recursive-edit))
4836 (when (stringp todos-date-from-calendar)
4837 todos-date-from-calendar)))))
4838
4839 (defun todos-delete-item ()
4840 "Delete at least one item in this category.
4841
4842 If there are marked items, delete all of these; otherwise, delete
4843 the item at point."
4844 (interactive)
4845 (let (ov)
4846 (unwind-protect
4847 (let* ((cat (todos-current-category))
4848 (marked (assoc cat todos-categories-with-marks))
4849 (item (unless marked (todos-item-string)))
4850 (answer (if marked
4851 (y-or-n-p "Permanently delete all marked items? ")
4852 (when item
4853 (setq ov (make-overlay
4854 (save-excursion (todos-item-start))
4855 (save-excursion (todos-item-end))))
4856 (overlay-put ov 'face 'todos-search)
4857 (y-or-n-p (concat "Permanently delete this item? ")))))
4858 buffer-read-only)
4859 (when answer
4860 (and marked (goto-char (point-min)))
4861 (catch 'done
4862 (while (not (eobp))
4863 (if (or (and marked (todos-marked-item-p)) item)
4864 (progn
4865 (if (todos-done-item-p)
4866 (todos-update-count 'done -1)
4867 (todos-update-count 'todo -1 cat)
4868 (and (todos-diary-item-p) (todos-update-count 'diary -1)))
4869 (if ov (delete-overlay ov))
4870 (todos-remove-item)
4871 ;; Don't leave point below last item.
4872 (and item (bolp) (eolp) (< (point-min) (point-max))
4873 (todos-backward-item))
4874 (when item
4875 (throw 'done (setq item nil))))
4876 (todos-forward-item))))
4877 (when marked
4878 (setq todos-categories-with-marks
4879 (assq-delete-all cat todos-categories-with-marks)))
4880 (todos-update-categories-sexp)
4881 (todos-prefix-overlays)))
4882 (if ov (delete-overlay ov)))))
4883
4884 (defun todos-edit-item (&optional arg)
4885 "Edit the Todo item at point.
4886
4887 With non-nil prefix argument ARG, include the item's date/time
4888 header, making it also editable; otherwise, include only the item
4889 content.
4890
4891 If the item consists of only one logical line, edit it in the
4892 minibuffer; otherwise, edit it in Todos Edit mode."
4893 (interactive "P")
4894 (when (todos-item-string)
4895 (let* ((opoint (point))
4896 (start (todos-item-start))
4897 (item-beg (progn
4898 (re-search-forward
4899 (concat todos-date-string-start todos-date-pattern
4900 "\\( " diary-time-regexp "\\)?"
4901 (regexp-quote todos-nondiary-end) "?")
4902 (line-end-position) t)
4903 (1+ (- (point) start))))
4904 (header (substring (todos-item-string) 0 item-beg))
4905 (item (if arg (todos-item-string)
4906 (substring (todos-item-string) item-beg)))
4907 (multiline (> (length (split-string item "\n")) 1))
4908 (buffer-read-only nil))
4909 (if multiline
4910 (todos-edit-multiline-item)
4911 (let ((new (concat (if arg "" header)
4912 (read-string "Edit: " (if arg
4913 (cons item item-beg)
4914 (cons item 0))))))
4915 (when arg
4916 (while (not (string-match (concat todos-date-string-start
4917 todos-date-pattern) new))
4918 (setq new (read-from-minibuffer
4919 "Item must start with a date: " new))))
4920 ;; Ensure lines following hard newlines are indented.
4921 (setq new (replace-regexp-in-string
4922 "\\(\n\\)[^[:blank:]]"
4923 (concat "\n" (make-string todos-indent-to-here 32)) new
4924 nil nil 1))
4925 ;; If user moved point during editing, make sure it moves back.
4926 (goto-char opoint)
4927 (todos-remove-item)
4928 (todos-insert-with-overlays new)
4929 (move-to-column item-beg))))))
4930
4931 (defun todos-edit-multiline-item ()
4932 "Edit current Todo item in Todos Edit mode.
4933 Use of newlines invokes `todos-indent' to insure compliance with
4934 the format of Diary entries."
4935 (interactive)
4936 (when (todos-item-string)
4937 (let ((buf todos-edit-buffer))
4938 (set-window-buffer (selected-window)
4939 (set-buffer (make-indirect-buffer (buffer-name) buf)))
4940 (narrow-to-region (todos-item-start) (todos-item-end))
4941 (todos-edit-mode)
4942 (message "%s" (substitute-command-keys
4943 (concat "Type \\[todos-edit-quit] "
4944 "to return to Todos mode.\n"))))))
4945
4946 (defun todos-edit-file (&optional item) ;FIXME: not item editing command
4947 "" ;FIXME
4948 (interactive)
4949 (widen)
4950 (todos-edit-mode)
4951 (remove-overlays)
4952 (message "%s" (substitute-command-keys
4953 (concat "Type \\[todos-edit-quit] to check file format "
4954 "validity and return to Todos mode.\n"))))
4955
4956 (defun todos-edit-quit ()
4957 "Return from Todos Edit mode to Todos mode.
4958 If the item contains hard line breaks, make sure the following
4959 lines are indented by `todos-indent-to-here' to conform to diary
4960 format.
4961
4962 If the whole file was in Todos Edit mode, check before returning
4963 whether the file is still a valid Todos file and if so, also
4964 recalculate the Todos categories sexp, in case changes were made
4965 in the number or names of categories."
4966 (interactive)
4967 (if (> (buffer-size) (- (point-max) (point-min)))
4968 (let ((item (buffer-string))
4969 (regex "\\(\n\\)[^[:blank:]]"))
4970 ;; Ensure lines following hard newlines are indented.
4971 (when (string-match regex (buffer-string))
4972 (replace-regexp-in-string
4973 regex (concat "\n" (make-string todos-indent-to-here 32))
4974 nil nil 1)
4975 (delete-region (point-min) (point-max))
4976 (insert item))
4977 (kill-buffer))
4978 (when (todos-check-format)
4979 ;; FIXME: separate out sexp check?
4980 ;; If manual editing makes e.g. item counts change, have to
4981 ;; call this to update todos-categories, but it restores
4982 ;; category order to list order.
4983 ;; (todos-repair-categories-sexp)
4984 ;; Compare (todos-make-categories-list t) with sexp and if
4985 ;; different ask (todos-update-categories-sexp) ?
4986 (todos-mode)
4987 (let* ((cat-beg (concat "^" (regexp-quote todos-category-beg)
4988 "\\(.*\\)$"))
4989 (curline (buffer-substring-no-properties
4990 (line-beginning-position) (line-end-position)))
4991 (cat (cond ((string-match cat-beg curline)
4992 (match-string-no-properties 1 curline))
4993 ((or (re-search-backward cat-beg nil t)
4994 (re-search-forward cat-beg nil t))
4995 (match-string-no-properties 1)))))
4996 (todos-category-number cat)
4997 (todos-category-select)
4998 (goto-char (point-min))))))
4999
5000 (defun todos-edit-item-header-1 (what &optional inc)
5001 "Function underlying commands to edit item date/time header.
5002
5003 The argument WHAT (passed by invoking commands) specifies what
5004 part of the header to edit; possible values are these symbols:
5005 `date', to edit the year, month, and day of the date string;
5006 `time', to edit just the time string; `calendar', to select the
5007 date from the Calendar; `today', to set the date to today's date;
5008 `dayname', to set the date string to the name of a day or to
5009 change the day name; and `year', `month' or `day', to edit only
5010 these respective parts of the date string (`day' is the number of
5011 the given day of the month, and `month' is either the name of the
5012 given month or its number, depending on the value of
5013 `calendar-date-display-form').
5014
5015 The optional argument INC is a positive or negative integer
5016 \(passed by invoking commands as a numerical prefix argument)
5017 that in conjunction with the WHAT values `year', `month' or
5018 `day', increments or decrements the specified date string
5019 component by the specified number of suitable units, i.e., years,
5020 months, or days, with automatic adjustment of the other date
5021 string components as necessary.
5022
5023 If there are marked items, apply the same edit to all of these;
5024 otherwise, edit just the item at point."
5025 (let* ((cat (todos-current-category))
5026 (marked (assoc cat todos-categories-with-marks))
5027 (first t)
5028 (todos-date-from-calendar t)
5029 (buffer-read-only nil)
5030 ndate ntime year monthname month day
5031 dayname) ; Needed by calendar-date-display-form.
5032 (save-excursion
5033 (or (and marked (goto-char (point-min))) (todos-item-start))
5034 (catch 'end
5035 (while (not (eobp))
5036 (and marked
5037 (while (not (todos-marked-item-p))
5038 (todos-forward-item)
5039 (and (eobp) (throw 'end nil))))
5040 (re-search-forward (concat todos-date-string-start "\\(?1:"
5041 todos-date-pattern
5042 "\\)\\(?2: " diary-time-regexp "\\)?"
5043 (regexp-quote todos-nondiary-end) "?")
5044 (line-end-position) t)
5045 (let* ((odate (match-string-no-properties 1))
5046 (otime (match-string-no-properties 2))
5047 (omonthname (match-string-no-properties 6))
5048 (omonth (match-string-no-properties 7))
5049 (oday (match-string-no-properties 8))
5050 (oyear (match-string-no-properties 9))
5051 (tmn-array todos-month-name-array)
5052 (mlist (append tmn-array nil))
5053 (tma-array todos-month-abbrev-array)
5054 (mablist (append tma-array nil))
5055 (yy (and oyear (unless (string= oyear "*")
5056 (string-to-number oyear))))
5057 (mm (or (and omonth (unless (string= omonth "*")
5058 (string-to-number omonth)))
5059 (1+ (- (length mlist)
5060 (length (or (member omonthname mlist)
5061 (member omonthname mablist)))))))
5062 (dd (and oday (unless (string= oday "*")
5063 (string-to-number oday)))))
5064 ;; If there are marked items, use only the first to set
5065 ;; header changes, and apply these to all marked items.
5066 (when first
5067 (cond
5068 ((eq what 'date)
5069 (setq ndate (todos-read-date)))
5070 ((eq what 'calendar)
5071 (setq ndate (save-match-data (todos-set-date-from-calendar))))
5072 ((eq what 'today)
5073 (setq ndate (calendar-date-string (calendar-current-date) t t)))
5074 ((eq what 'dayname)
5075 (setq ndate (todos-read-dayname)))
5076 ((eq what 'time)
5077 (setq ntime (save-match-data (todos-read-time)))
5078 (when (> (length ntime) 0)
5079 (setq ntime (concat " " ntime))))
5080 ;; When date string consists only of a day name,
5081 ;; passing other date components is a NOP.
5082 ((and (memq what '(year month day))
5083 (not (or oyear omonth oday))))
5084 ((eq what 'year)
5085 (setq day oday
5086 monthname omonthname
5087 month omonth
5088 year (cond ((not current-prefix-arg)
5089 (todos-read-date 'year))
5090 ((string= oyear "*")
5091 (error "Cannot increment *"))
5092 (t
5093 (number-to-string (+ yy inc))))))
5094 ((eq what 'month)
5095 (setf day oday
5096 year oyear
5097 (if (memq 'month calendar-date-display-form)
5098 month
5099 monthname)
5100 (cond ((not current-prefix-arg)
5101 (todos-read-date 'month))
5102 ((or (string= omonth "*") (= mm 13))
5103 (error "Cannot increment *"))
5104 (t
5105 (let ((mminc (+ mm inc)))
5106 ;; Increment or decrement month by INC
5107 ;; modulo 12.
5108 (setq mm (% mminc 12))
5109 ;; If result is 0, make month December.
5110 (setq mm (if (= mm 0) 12 (abs mm)))
5111 ;; Adjust year if necessary.
5112 (setq year (or (and (cond ((> mminc 12)
5113 (+ yy (/ mminc 12)))
5114 ((< mminc 1)
5115 (- yy (/ mminc 12) 1))
5116 (t yy))
5117 (number-to-string yy))
5118 oyear)))
5119 ;; Return the changed numerical month as
5120 ;; a string or the corresponding month name.
5121 (if omonth
5122 (number-to-string mm)
5123 (aref tma-array (1- mm))))))
5124 (let ((yy (string-to-number year)) ; 0 if year is "*".
5125 ;; When mm is 13 (corresponding to "*" as value
5126 ;; of month), this raises an args-out-of-range
5127 ;; error in calendar-last-day-of-month, so use 1
5128 ;; (corresponding to January) to get 31 days.
5129 (mm (if (= mm 13) 1 mm)))
5130 (if (> (string-to-number day)
5131 (calendar-last-day-of-month mm yy))
5132 (error "%s %s does not have %s days"
5133 (aref tmn-array (1- mm))
5134 (if (= mm 2) yy "") day))))
5135 ((eq what 'day)
5136 (setq year oyear
5137 month omonth
5138 monthname omonthname
5139 day (cond
5140 ((not current-prefix-arg)
5141 (todos-read-date 'day mm oyear))
5142 ((string= oday "*")
5143 (error "Cannot increment *"))
5144 ((or (string= omonth "*") (string= omonthname "*"))
5145 (setq dd (+ dd inc))
5146 (if (> dd 31)
5147 (error "A month cannot have more than 31 days")
5148 (number-to-string dd)))
5149 ;; Increment or decrement day by INC,
5150 ;; adjusting month and year if necessary
5151 ;; (if year is "*" assume current year to
5152 ;; calculate adjustment).
5153 (t
5154 (let* ((yy (or yy (calendar-extract-year
5155 (calendar-current-date))))
5156 (date (calendar-gregorian-from-absolute
5157 (+ (calendar-absolute-from-gregorian
5158 (list mm dd yy)) inc)))
5159 (adjmm (nth 0 date)))
5160 ;; Set year and month(name) to adjusted values.
5161 (unless (string= year "*")
5162 (setq year (number-to-string (nth 2 date))))
5163 (if month
5164 (setq month (number-to-string adjmm))
5165 (setq monthname (aref tma-array (1- adjmm))))
5166 ;; Return changed numerical day as a string.
5167 (number-to-string (nth 1 date)))))))))
5168 ;; If new year, month or day date string components were
5169 ;; calculated, rebuild the whole date string from them.
5170 (when (memq what '(year month day))
5171 (if (or oyear omonth omonthname oday)
5172 (setq ndate (mapconcat 'eval calendar-date-display-form ""))
5173 (message "Cannot edit date component of empty date string")))
5174 (when ndate (replace-match ndate nil nil nil 1))
5175 ;; Add new time string to the header, if it was supplied.
5176 (when ntime
5177 (if otime
5178 (replace-match ntime nil nil nil 2)
5179 (goto-char (match-end 1))
5180 (insert ntime)))
5181 (setq todos-date-from-calendar nil)
5182 (setq first nil))
5183 ;; Apply the changes to the first marked item header to the
5184 ;; remaining marked items. If there are no marked items,
5185 ;; we're finished.
5186 (if marked
5187 (todos-forward-item)
5188 (goto-char (point-max))))))))
5189
5190 (defun todos-edit-item-header ()
5191 "Interactively edit at least the date of item's date/time header.
5192 If user option `todos-always-add-time-string' is non-nil, also
5193 edit item's time string."
5194 (interactive)
5195 (todos-edit-item-header-1 'date)
5196 (when todos-always-add-time-string
5197 (todos-edit-item-time)))
5198
5199 (defun todos-edit-item-time ()
5200 "Interactively edit the time string of item's date/time header."
5201 (interactive)
5202 (todos-edit-item-header-1 'time))
5203
5204 (defun todos-edit-item-date-from-calendar ()
5205 "Interactively edit item's date using the Calendar."
5206 (interactive)
5207 (todos-edit-item-header-1 'calendar))
5208
5209 (defun todos-edit-item-date-to-today ()
5210 "Set item's date to today's date."
5211 (interactive)
5212 (todos-edit-item-header-1 'today))
5213
5214 (defun todos-edit-item-date-day-name ()
5215 "Replace item's date with the name of a day of the week."
5216 (interactive)
5217 (todos-edit-item-header-1 'dayname))
5218
5219 (defun todos-edit-item-date-year (&optional inc)
5220 "Interactively edit the year of item's date string.
5221 With prefix argument INC a positive or negative integer,
5222 increment or decrement the year by INC."
5223 (interactive "p")
5224 (todos-edit-item-header-1 'year inc))
5225
5226 (defun todos-edit-item-date-month (&optional inc)
5227 "Interactively edit the month of item's date string.
5228 With prefix argument INC a positive or negative integer,
5229 increment or decrement the month by INC."
5230 (interactive "p")
5231 (todos-edit-item-header-1 'month inc))
5232
5233 (defun todos-edit-item-date-day (&optional inc)
5234 "Interactively edit the day of the month of item's date string.
5235 With prefix argument INC a positive or negative integer,
5236 increment or decrement the day by INC."
5237 (interactive "p")
5238 (todos-edit-item-header-1 'day inc))
5239
5240 (defun todos-edit-item-diary-inclusion ()
5241 "Change diary status of one or more todo items in this category.
5242 That is, insert `todos-nondiary-marker' if the candidate items
5243 lack this marking; otherwise, remove it.
5244
5245 If there are marked todo items, change the diary status of all
5246 and only these, otherwise change the diary status of the item at
5247 point."
5248 (interactive)
5249 (let ((buffer-read-only)
5250 (marked (assoc (todos-current-category)
5251 todos-categories-with-marks)))
5252 (catch 'stop
5253 (save-excursion
5254 (when marked (goto-char (point-min)))
5255 (while (not (eobp))
5256 (if (todos-done-item-p)
5257 (throw 'stop (message "Done items cannot be edited"))
5258 (unless (and marked (not (todos-marked-item-p)))
5259 (let* ((beg (todos-item-start))
5260 (lim (save-excursion (todos-item-end)))
5261 (end (save-excursion
5262 (or (todos-time-string-matcher lim)
5263 (todos-date-string-matcher lim)))))
5264 (if (looking-at (regexp-quote todos-nondiary-start))
5265 (progn
5266 (replace-match "")
5267 (search-forward todos-nondiary-end (1+ end) t)
5268 (replace-match "")
5269 (todos-update-count 'diary 1))
5270 (when end
5271 (insert todos-nondiary-start)
5272 (goto-char (1+ end))
5273 (insert todos-nondiary-end)
5274 (todos-update-count 'diary -1)))))
5275 (unless marked (throw 'stop nil))
5276 (todos-forward-item)))))
5277 (todos-update-categories-sexp)))
5278
5279 (defun todos-edit-category-diary-inclusion (arg)
5280 "Make all items in this category diary items.
5281 With prefix ARG, make all items in this category non-diary
5282 items."
5283 (interactive "P")
5284 (save-excursion
5285 (goto-char (point-min))
5286 (let ((todo-count (todos-get-count 'todo))
5287 (diary-count (todos-get-count 'diary))
5288 (buffer-read-only))
5289 (catch 'stop
5290 (while (not (eobp))
5291 (if (todos-done-item-p) ; We've gone too far.
5292 (throw 'stop nil)
5293 (let* ((beg (todos-item-start))
5294 (lim (save-excursion (todos-item-end)))
5295 (end (save-excursion
5296 (or (todos-time-string-matcher lim)
5297 (todos-date-string-matcher lim)))))
5298 (if arg
5299 (unless (looking-at (regexp-quote todos-nondiary-start))
5300 (insert todos-nondiary-start)
5301 (goto-char (1+ end))
5302 (insert todos-nondiary-end))
5303 (when (looking-at (regexp-quote todos-nondiary-start))
5304 (replace-match "")
5305 (search-forward todos-nondiary-end (1+ end) t)
5306 (replace-match "")))))
5307 (todos-forward-item))
5308 (unless (if arg (zerop diary-count) (= diary-count todo-count))
5309 (todos-update-count 'diary (if arg
5310 (- diary-count)
5311 (- todo-count diary-count))))
5312 (todos-update-categories-sexp)))))
5313
5314 (defun todos-edit-item-diary-nonmarking ()
5315 "Change non-marking of one or more diary items in this category.
5316 That is, insert `diary-nonmarking-symbol' if the candidate items
5317 lack this marking; otherwise, remove it.
5318
5319 If there are marked todo items, change the non-marking status of
5320 all and only these, otherwise change the non-marking status of
5321 the item at point."
5322 (interactive)
5323 (let ((buffer-read-only)
5324 (marked (assoc (todos-current-category)
5325 todos-categories-with-marks)))
5326 (catch 'stop
5327 (save-excursion
5328 (when marked (goto-char (point-min)))
5329 (while (not (eobp))
5330 (if (todos-done-item-p)
5331 (throw 'stop (message "Done items cannot be edited"))
5332 (unless (and marked (not (todos-marked-item-p)))
5333 (todos-item-start)
5334 (unless (looking-at (regexp-quote todos-nondiary-start))
5335 (if (looking-at (regexp-quote diary-nonmarking-symbol))
5336 (replace-match "")
5337 (insert diary-nonmarking-symbol))))
5338 (unless marked (throw 'stop nil))
5339 (todos-forward-item)))))))
5340
5341 (defun todos-edit-category-diary-nonmarking (arg)
5342 "Add `diary-nonmarking-symbol' to all diary items in this category.
5343 With prefix ARG, remove `diary-nonmarking-symbol' from all diary
5344 items in this category."
5345 (interactive "P")
5346 (save-excursion
5347 (goto-char (point-min))
5348 (let (buffer-read-only)
5349 (catch 'stop
5350 (while (not (eobp))
5351 (if (todos-done-item-p) ; We've gone too far.
5352 (throw 'stop nil)
5353 (unless (looking-at (regexp-quote todos-nondiary-start))
5354 (if arg
5355 (when (looking-at (regexp-quote diary-nonmarking-symbol))
5356 (replace-match ""))
5357 (unless (looking-at (regexp-quote diary-nonmarking-symbol))
5358 (insert diary-nonmarking-symbol))))
5359 (todos-forward-item)))))))
5360
5361 (defun todos-set-item-priority (&optional item cat new arg)
5362 "Prompt for and set ITEM's priority in CATegory.
5363
5364 Interactively, ITEM is the todo item at point, CAT is the current
5365 category, and the priority is a number between 1 and the number
5366 of items in the category. Non-interactively, non-nil NEW means
5367 ITEM is a new item and the lowest priority is one more than the
5368 number of items in CAT.
5369
5370 The new priority is set either interactively by prompt or by a
5371 numerical prefix argument, or noninteractively by argument ARG,
5372 whose value can be either of the symbols `raise' or `lower',
5373 meaning to raise or lower the item's priority by one."
5374 (interactive) ;FIXME: Prefix arg?
5375 (unless (and (called-interactively-p 'any)
5376 (or (todos-done-item-p) (looking-at "^$")))
5377 (let* ((item (or item (todos-item-string)))
5378 (marked (todos-marked-item-p))
5379 (cat (or cat (cond ((eq major-mode 'todos-mode)
5380 (todos-current-category))
5381 ((eq major-mode 'todos-filtered-items-mode)
5382 (let* ((regexp1
5383 (concat todos-date-string-start
5384 todos-date-pattern
5385 "\\( " diary-time-regexp "\\)?"
5386 (regexp-quote todos-nondiary-end)
5387 "?\\(?1: \\[\\(.+:\\)?.+\\]\\)")))
5388 (save-excursion
5389 (re-search-forward regexp1 nil t)
5390 (match-string-no-properties 1)))))))
5391 curnum
5392 (todo (cond ((or (eq arg 'raise) (eq arg 'lower)
5393 (eq major-mode 'todos-filtered-items-mode))
5394 (save-excursion
5395 (let ((curstart (todos-item-start))
5396 (count 0))
5397 (goto-char (point-min))
5398 (while (looking-at todos-item-start)
5399 (setq count (1+ count))
5400 (when (= (point) curstart) (setq curnum count))
5401 (todos-forward-item))
5402 count)))
5403 ((eq major-mode 'todos-mode)
5404 (todos-get-count 'todo cat))))
5405 (maxnum (if new (1+ todo) todo))
5406 (prompt (format "Set item priority (1-%d): " maxnum))
5407 (priority (cond ((and (not arg) (numberp current-prefix-arg))
5408 current-prefix-arg)
5409 ((and (eq arg 'raise) (>= curnum 1))
5410 (1- curnum))
5411 ((and (eq arg 'lower) (<= curnum maxnum))
5412 (1+ curnum))))
5413 candidate
5414 buffer-read-only)
5415 (unless (and priority
5416 (or (and (eq arg 'raise) (zerop priority))
5417 (and (eq arg 'lower) (> priority maxnum))))
5418 ;; When moving item to another category, show the category before
5419 ;; prompting for its priority.
5420 (unless (or arg (called-interactively-p 'any))
5421 (todos-category-number cat)
5422 ;; If done items in category are visible, keep them visible.
5423 (let ((done todos-show-with-done))
5424 (when (> (buffer-size) (- (point-max) (point-min)))
5425 (save-excursion
5426 (goto-char (point-min))
5427 (setq done (re-search-forward todos-done-string-start nil t))))
5428 (let ((todos-show-with-done done))
5429 (todos-category-select)
5430 ;; Keep top of category in view while setting priority.
5431 (goto-char (point-min)))))
5432 ;; Prompt for priority only when the category has at least one todo item.
5433 (when (> maxnum 1)
5434 (while (not priority)
5435 (setq candidate (read-number prompt))
5436 (setq prompt (when (or (< candidate 1) (> candidate maxnum))
5437 (format "Priority must be an integer between 1 and %d.\n"
5438 maxnum)))
5439 (unless prompt (setq priority candidate))))
5440 ;; In Top Priorities buffer, an item's priority can be changed
5441 ;; wrt items in another category, but not wrt items in the same
5442 ;; category.
5443 (when (eq major-mode 'todos-filtered-items-mode)
5444 (let* ((regexp2 (concat todos-date-string-start todos-date-pattern
5445 "\\( " diary-time-regexp "\\)?"
5446 (regexp-quote todos-nondiary-end)
5447 "?\\(?1:" (regexp-quote cat) "\\)"))
5448 (end (cond ((< curnum priority)
5449 (save-excursion (todos-item-end)))
5450 ((> curnum priority)
5451 (save-excursion (todos-item-start)))))
5452 (match (save-excursion
5453 (cond ((< curnum priority)
5454 (todos-forward-item (1+ (- priority curnum)))
5455 (when (re-search-backward regexp2 end t)
5456 (match-string-no-properties 1)))
5457 ((> curnum priority)
5458 (todos-backward-item (- curnum priority))
5459 (when (re-search-forward regexp2 end t)
5460 (match-string-no-properties 1)))))))
5461 (when match
5462 (error (concat "Cannot reprioritize items from the same "
5463 "category in this mode, only in Todos mode")))))
5464 ;; Interactively or with non-nil ARG, relocate the item within its
5465 ;; category.
5466 (when (or arg (called-interactively-p 'any))
5467 (todos-remove-item))
5468 (goto-char (point-min))
5469 (when priority
5470 (unless (= priority 1)
5471 (todos-forward-item (1- priority))
5472 ;; When called from todos-item-undone and the highest priority
5473 ;; is chosen, this advances point to the first done item, so
5474 ;; move it up to the empty line above the done items
5475 ;; separator.
5476 (when (looking-back (concat "^"
5477 (regexp-quote todos-category-done) "\n"))
5478 (todos-backward-item))))
5479 (todos-insert-with-overlays item)
5480 ;; If item was marked, restore the mark.
5481 (and marked
5482 (let* ((ov (todos-get-overlay 'prefix))
5483 (pref (overlay-get ov 'before-string)))
5484 (overlay-put ov 'before-string (concat todos-item-mark pref))))))))
5485
5486 (defun todos-raise-item-priority ()
5487 "Raise priority of current item by moving it up by one item."
5488 (interactive)
5489 (todos-set-item-priority nil nil nil 'raise))
5490
5491 (defun todos-lower-item-priority ()
5492 "Lower priority of current item by moving it down by one item."
5493 (interactive)
5494 (todos-set-item-priority nil nil nil 'lower))
5495
5496 (defun todos-move-item (&optional file)
5497 "Move at least one todo or done item to another category.
5498 If there are marked items, move all of these; otherwise, move
5499 the item at point.
5500
5501 With prefix argument FILE, prompt for a specific Todos file and
5502 choose (with TAB completion) a category in it to move the item or
5503 items to; otherwise, choose and move to any category in either
5504 the current Todos file or one of the files in
5505 `todos-category-completions-files'. If the chosen category is
5506 not an existing categories, then it is created and the item(s)
5507 become(s) the first entry/entries in that category.
5508
5509 With moved Todo items, prompt to set the priority in the category
5510 moved to (with multiple todos items, the one that had the highest
5511 priority in the category moved from gets the new priority and the
5512 rest of the moved todo items are inserted in sequence below it).
5513 Moved done items are appended to the top of the done items
5514 section in the category moved to."
5515 (interactive "P")
5516 (let* ((cat1 (todos-current-category))
5517 (marked (assoc cat1 todos-categories-with-marks)))
5518 ;; Noop if point is not on an item and there are no marked items.
5519 (unless (and (looking-at "^$")
5520 (not marked))
5521 (let* ((buffer-read-only)
5522 (file1 todos-current-todos-file)
5523 (num todos-category-number)
5524 (item (todos-item-string))
5525 (diary-item (todos-diary-item-p))
5526 (done-item (and (todos-done-item-p) (concat item "\n")))
5527 (omark (save-excursion (todos-item-start) (point-marker)))
5528 (todo 0)
5529 (diary 0)
5530 (done 0)
5531 ov cat2 file2 moved nmark todo-items done-items)
5532 (unwind-protect
5533 (progn
5534 (unless marked
5535 (setq ov (make-overlay (save-excursion (todos-item-start))
5536 (save-excursion (todos-item-end))))
5537 (overlay-put ov 'face 'todos-search))
5538 (let* ((pl (if (and marked (> (cdr marked) 1)) "s" ""))
5539 (cat+file (todos-read-category (concat "Move item" pl
5540 " to category: ")
5541 nil file)))
5542 (while (and (equal (car cat+file) cat1)
5543 (equal (cdr cat+file) file1))
5544 (setq cat+file (todos-read-category
5545 "Choose a different category: ")))
5546 (setq cat2 (car cat+file)
5547 file2 (cdr cat+file))))
5548 (if ov (delete-overlay ov)))
5549 (set-buffer (find-buffer-visiting file1))
5550 (if marked
5551 (progn
5552 (goto-char (point-min))
5553 (while (not (eobp))
5554 (when (todos-marked-item-p)
5555 (if (todos-done-item-p)
5556 (setq done-items (concat done-items
5557 (todos-item-string) "\n")
5558 done (1+ done))
5559 (setq todo-items (concat todo-items
5560 (todos-item-string) "\n")
5561 todo (1+ todo))
5562 (when (todos-diary-item-p)
5563 (setq diary (1+ diary)))))
5564 (todos-forward-item))
5565 ;; Chop off last newline of multiple todo item string,
5566 ;; since it will be reinserted when setting priority
5567 ;; (but with done items priority is not set, so keep
5568 ;; last newline).
5569 (and todo-items
5570 (setq todo-items (substring todo-items 0 -1))))
5571 (if (todos-done-item-p)
5572 (setq done 1)
5573 (setq todo 1)
5574 (when (todos-diary-item-p) (setq diary 1))))
5575 (set-window-buffer (selected-window)
5576 (set-buffer (find-file-noselect file2 'nowarn)))
5577 (unwind-protect
5578 (progn
5579 (when (or todo-items (and item (not done-item)))
5580 (todos-set-item-priority (or todo-items item) cat2 t))
5581 ;; Move done items en bloc to top of done items section.
5582 (when (or done-items done-item)
5583 (todos-category-number cat2)
5584 (widen)
5585 (goto-char (point-min))
5586 (re-search-forward (concat "^" (regexp-quote
5587 (concat todos-category-beg cat2))
5588 "$")
5589 nil t)
5590 (re-search-forward
5591 (concat "^" (regexp-quote todos-category-done)) nil t)
5592 (forward-line)
5593 (insert (or done-items done-item)))
5594 (setq moved t))
5595 (cond
5596 ;; Move succeeded, so remove item from starting category,
5597 ;; update item counts and display the category containing
5598 ;; the moved item.
5599 (moved
5600 (setq nmark (point-marker))
5601 (when todo (todos-update-count 'todo todo))
5602 (when diary (todos-update-count 'diary diary))
5603 (when done (todos-update-count 'done done))
5604 (todos-update-categories-sexp)
5605 (with-current-buffer (find-buffer-visiting file1)
5606 (save-excursion
5607 (save-restriction
5608 (widen)
5609 (goto-char omark)
5610 (if marked
5611 (let (beg end)
5612 (setq item nil)
5613 (re-search-backward
5614 (concat "^" (regexp-quote todos-category-beg)) nil t)
5615 (forward-line)
5616 (setq beg (point))
5617 (setq end (if (re-search-forward
5618 (concat "^" (regexp-quote
5619 todos-category-beg)) nil t)
5620 (match-beginning 0)
5621 (point-max)))
5622 (goto-char beg)
5623 (while (< (point) end)
5624 (if (todos-marked-item-p)
5625 (todos-remove-item)
5626 (todos-forward-item)))
5627 (setq todos-categories-with-marks
5628 (assq-delete-all cat1 todos-categories-with-marks)))
5629 (if ov (delete-overlay ov))
5630 (todos-remove-item))))
5631 (when todo (todos-update-count 'todo (- todo) cat1))
5632 (when diary (todos-update-count 'diary (- diary) cat1))
5633 (when done (todos-update-count 'done (- done) cat1))
5634 (todos-update-categories-sexp))
5635 (set-window-buffer (selected-window)
5636 (set-buffer (find-file-noselect file2 'nowarn)))
5637 (setq todos-category-number (todos-category-number cat2))
5638 (let ((todos-show-with-done (or done-items done-item)))
5639 (todos-category-select))
5640 (goto-char nmark)
5641 ;; If item is moved to end of (just first?) category, make
5642 ;; sure the items above it are displayed in the window.
5643 (recenter))
5644 ;; User quit before setting priority of todo item(s), so
5645 ;; return to starting category.
5646 (t
5647 (set-window-buffer (selected-window)
5648 (set-buffer (find-file-noselect file1 'nowarn)))
5649 (todos-category-number cat1)
5650 (todos-category-select)
5651 (goto-char omark))))))))
5652
5653 (defun todos-item-done (&optional arg)
5654 "Tag a todo item in this category as done and relocate it.
5655
5656 With prefix argument ARG prompt for a comment and append it to
5657 the done item; this is only possible if there are no marked
5658 items. If there are marked items, tag all of these with
5659 `todos-done-string' plus the current date and, if
5660 `todos-always-add-time-string' is non-nil, the current time;
5661 otherwise, just tag the item at point. Items tagged as done are
5662 relocated to the category's (by default hidden) done section. If
5663 done items are visible on invoking this command, they remain
5664 visible."
5665 (interactive "P")
5666 (let* ((cat (todos-current-category))
5667 (marked (assoc cat todos-categories-with-marks)))
5668 (when marked
5669 (save-excursion
5670 (save-restriction
5671 (goto-char (point-max))
5672 (todos-backward-item)
5673 (unless (todos-done-item-p)
5674 (widen)
5675 (unless (re-search-forward
5676 (concat "^" (regexp-quote todos-category-beg)) nil t)
5677 (goto-char (point-max)))
5678 (forward-line -1))
5679 (while (todos-done-item-p)
5680 (when (todos-marked-item-p)
5681 (user-error "This command does not apply to done items"))
5682 (todos-backward-item)))))
5683 (unless (and (not marked)
5684 (or (todos-done-item-p)
5685 ;; Point is between todo and done items.
5686 (looking-at "^$")))
5687 (let* ((date-string (calendar-date-string (calendar-current-date) t t))
5688 (time-string (if todos-always-add-time-string
5689 (concat " " (substring (current-time-string) 11 16))
5690 ""))
5691 (done-prefix (concat "[" todos-done-string date-string time-string
5692 "] "))
5693 (comment (and arg (read-string "Enter a comment: ")))
5694 (item-count 0)
5695 (diary-count 0)
5696 (show-done (save-excursion
5697 (goto-char (point-min))
5698 (re-search-forward todos-done-string-start nil t)))
5699 (buffer-read-only nil)
5700 item done-item opoint)
5701 ;; Don't add empty comment to done item.
5702 (setq comment (unless (zerop (length comment))
5703 (concat " [" todos-comment-string ": " comment "]")))
5704 (and marked (goto-char (point-min)))
5705 (catch 'done
5706 ;; Stop looping when we hit the empty line below the last
5707 ;; todo item (this is eobp if only done items are hidden).
5708 (while (not (looking-at "^$"))
5709 (if (or (not marked) (and marked (todos-marked-item-p)))
5710 (progn
5711 (setq item (todos-item-string))
5712 (setq done-item (concat done-item done-prefix item
5713 comment (and marked "\n")))
5714 (setq item-count (1+ item-count))
5715 (when (todos-diary-item-p)
5716 (setq diary-count (1+ diary-count)))
5717 (todos-remove-item)
5718 (unless marked (throw 'done nil)))
5719 (todos-forward-item))))
5720 (when marked
5721 ;; Chop off last newline of done item string.
5722 (setq done-item (substring done-item 0 -1))
5723 (setq todos-categories-with-marks
5724 (assq-delete-all cat todos-categories-with-marks)))
5725 (save-excursion
5726 (widen)
5727 (re-search-forward
5728 (concat "^" (regexp-quote todos-category-done)) nil t)
5729 (forward-char)
5730 (when show-done (setq opoint (point)))
5731 (insert done-item "\n"))
5732 (todos-update-count 'todo (- item-count))
5733 (todos-update-count 'done item-count)
5734 (todos-update-count 'diary (- diary-count))
5735 (todos-update-categories-sexp)
5736 (let ((todos-show-with-done show-done))
5737 (todos-category-select)
5738 ;; When done items are shown, put cursor on first just done item.
5739 (when opoint (goto-char opoint)))))))
5740
5741 (defun todos-done-item-add-edit-or-delete-comment (&optional arg)
5742 "Add a comment to this done item or edit an existing comment.
5743 With prefix ARG delete an existing comment."
5744 (interactive "P")
5745 (when (todos-done-item-p)
5746 (let ((item (todos-item-string))
5747 (opoint (point))
5748 (end (save-excursion (todos-item-end)))
5749 comment buffer-read-only)
5750 (save-excursion
5751 (todos-item-start)
5752 (if (re-search-forward (concat " \\["
5753 (regexp-quote todos-comment-string)
5754 ": \\([^]]+\\)\\]") end t)
5755 (if arg
5756 (when (y-or-n-p "Delete comment? ")
5757 (delete-region (match-beginning 0) (match-end 0)))
5758 (setq comment (read-string "Edit comment: "
5759 (cons (match-string 1) 1)))
5760 (replace-match comment nil nil nil 1))
5761 (setq comment (read-string "Enter a comment: "))
5762 ;; If user moved point during editing, make sure it moves back.
5763 (goto-char opoint)
5764 (todos-item-end)
5765 (insert " [" todos-comment-string ": " comment "]"))))))
5766
5767 (defun todos-item-undone ()
5768 "Restore at least one done item to this category's todo section.
5769 Prompt for the new priority. If there are marked items, undo all
5770 of these, giving the first undone item the new priority and the
5771 rest following directly in sequence; otherwise, undo just the
5772 item at point.
5773
5774 If the done item has a comment, ask whether to omit the comment
5775 from the restored item. With multiple marked done items with
5776 comments, only ask once, and if affirmed, omit subsequent
5777 comments without asking."
5778 (interactive)
5779 (let* ((cat (todos-current-category))
5780 (marked (assoc cat todos-categories-with-marks))
5781 (pl (if (and marked (> (cdr marked) 1)) "s" "")))
5782 (when (or marked (todos-done-item-p))
5783 (let ((buffer-read-only)
5784 (opoint (point))
5785 (omark (point-marker))
5786 (first 'first)
5787 (item-count 0)
5788 (diary-count 0)
5789 start end item ov npoint undone)
5790 (and marked (goto-char (point-min)))
5791 (catch 'done
5792 (while (not (eobp))
5793 (when (or (not marked) (and marked (todos-marked-item-p)))
5794 (if (not (todos-done-item-p))
5795 (error "Only done items can be undone")
5796 (todos-item-start)
5797 (unless marked
5798 (setq ov (make-overlay (save-excursion (todos-item-start))
5799 (save-excursion (todos-item-end))))
5800 (overlay-put ov 'face 'todos-search))
5801 ;; Find the end of the date string added upon tagging item as
5802 ;; done.
5803 (setq start (search-forward "] "))
5804 (setq item-count (1+ item-count))
5805 (unless (looking-at (regexp-quote todos-nondiary-start))
5806 (setq diary-count (1+ diary-count)))
5807 (setq end (save-excursion (todos-item-end)))
5808 ;; Ask (once) whether to omit done item's comment. If
5809 ;; affirmed, omit subsequent comments without asking.
5810 (when (re-search-forward
5811 (concat " \\[" (regexp-quote todos-comment-string)
5812 ": [^]]+\\]") end t)
5813 (unwind-protect
5814 (if (eq first 'first)
5815 (setq first
5816 (if (eq todos-undo-item-omit-comment 'ask)
5817 (when (y-or-n-p (concat "Omit comment" pl
5818 " from restored item"
5819 pl "? "))
5820 'omit)
5821 (when todos-undo-item-omit-comment 'omit)))
5822 t)
5823 (when (and (eq first 'first) ov) (delete-overlay ov)))
5824 (when (eq first 'omit)
5825 (setq end (match-beginning 0))))
5826 (setq item (concat item
5827 (buffer-substring-no-properties start end)
5828 (when marked "\n")))
5829 (unless marked (throw 'done nil))))
5830 (todos-forward-item)))
5831 (unwind-protect
5832 (progn
5833 ;; Chop off last newline of multiple items string, since
5834 ;; it will be reinserted on setting priority.
5835 (and marked (setq item (substring item 0 -1)))
5836 (todos-set-item-priority item cat t)
5837 (setq npoint (point))
5838 (setq undone t))
5839 (when ov (delete-overlay ov))
5840 (if (not undone)
5841 (goto-char opoint)
5842 (if marked
5843 (progn
5844 (setq item nil)
5845 (re-search-forward
5846 (concat "^" (regexp-quote todos-category-done)) nil t)
5847 (while (not (eobp))
5848 (if (todos-marked-item-p)
5849 (todos-remove-item)
5850 (todos-forward-item)))
5851 (setq todos-categories-with-marks
5852 (assq-delete-all cat todos-categories-with-marks)))
5853 (goto-char omark)
5854 (todos-remove-item))
5855 (todos-update-count 'todo item-count)
5856 (todos-update-count 'done (- item-count))
5857 (when diary-count (todos-update-count 'diary diary-count))
5858 (todos-update-categories-sexp)
5859 (let ((todos-show-with-done (> (todos-get-count 'done) 0)))
5860 (todos-category-select))
5861 ;; Put cursor on undone item.
5862 (goto-char npoint)))
5863 (set-marker omark nil)))))
5864
5865 (defun todos-archive-done-item (&optional all)
5866 "Archive at least one done item in this category.
5867
5868 With a prefix argument, prompt whether to archive all done items
5869 in this category and on confirmation archive them. Otherwise, if
5870 there are marked done items (and no marked todo items), archive
5871 all of these; otherwise, archive the done item at point.
5872
5873 If the archive of this file does not exist, it is created. If
5874 this category does not exist in the archive, it is created."
5875 (interactive "P")
5876 (when (eq major-mode 'todos-mode)
5877 (if (and all (zerop (todos-get-count 'done)))
5878 (message "No done items in this category")
5879 (catch 'end
5880 (let* ((cat (todos-current-category))
5881 (tbuf (current-buffer))
5882 (marked (assoc cat todos-categories-with-marks))
5883 (afile (concat (file-name-sans-extension
5884 todos-current-todos-file) ".toda"))
5885 (archive (if (file-exists-p afile)
5886 (find-file-noselect afile t)
5887 (get-buffer-create afile)))
5888 (item (and (todos-done-item-p) (concat (todos-item-string) "\n")))
5889 (count 0)
5890 (opoint (unless (todos-done-item-p) (point)))
5891 marked-items beg end all-done
5892 buffer-read-only)
5893 (cond
5894 (all
5895 (if (y-or-n-p "Archive all done items in this category? ")
5896 (save-excursion
5897 (save-restriction
5898 (goto-char (point-min))
5899 (widen)
5900 (setq beg (progn
5901 (re-search-forward todos-done-string-start nil t)
5902 (match-beginning 0))
5903 end (if (re-search-forward
5904 (concat "^" (regexp-quote todos-category-beg))
5905 nil t)
5906 (match-beginning 0)
5907 (point-max))
5908 all-done (buffer-substring-no-properties beg end)
5909 count (todos-get-count 'done))
5910 ;; Restore starting point, unless it was on a done
5911 ;; item, since they will all be deleted.
5912 (when opoint (goto-char opoint))))
5913 (throw 'end nil)))
5914 (marked
5915 (save-excursion
5916 (goto-char (point-min))
5917 (while (not (eobp))
5918 (when (todos-marked-item-p)
5919 (if (not (todos-done-item-p))
5920 (throw 'end (message "Only done items can be archived"))
5921 (setq marked-items
5922 (concat marked-items (todos-item-string) "\n"))
5923 (setq count (1+ count))))
5924 (todos-forward-item)))))
5925 (if (not (or marked all item))
5926 (throw 'end (message "Only done items can be archived"))
5927 (with-current-buffer archive
5928 (unless buffer-file-name (erase-buffer))
5929 (let (buffer-read-only)
5930 (widen)
5931 (goto-char (point-min))
5932 (if (and (re-search-forward
5933 (concat "^" (regexp-quote
5934 (concat todos-category-beg cat)) "$")
5935 nil t)
5936 (re-search-forward (regexp-quote todos-category-done)
5937 nil t))
5938 ;; Start of done items section in existing category.
5939 (forward-char)
5940 (todos-add-category nil cat)
5941 ;; Start of done items section in new category.
5942 (goto-char (point-max)))
5943 (insert (cond (marked marked-items)
5944 (all all-done)
5945 (item)))
5946 (todos-update-count 'done (if (or marked all) count 1) cat)
5947 (todos-update-categories-sexp)
5948 ;; If archive is new, save to file now (using write-region in
5949 ;; order not to get prompted for file to save to), to let
5950 ;; auto-mode-alist take effect below.
5951 (unless buffer-file-name
5952 (write-region nil nil afile)
5953 (kill-buffer))))
5954 (with-current-buffer tbuf
5955 (cond
5956 (all
5957 (save-excursion
5958 (save-restriction
5959 ;; Make sure done items are accessible.
5960 (widen)
5961 (remove-overlays beg end)
5962 (delete-region beg end)
5963 (todos-update-count 'done (- count))
5964 (todos-update-count 'archived count))))
5965 ((or marked
5966 ;; If we're archiving all done items, can't
5967 ;; first archive item point was on, since
5968 ;; that will short-circuit the rest.
5969 (and item (not all)))
5970 (and marked (goto-char (point-min)))
5971 (catch 'done
5972 (while (not (eobp))
5973 (if (or (and marked (todos-marked-item-p)) item)
5974 (progn
5975 (todos-remove-item)
5976 (todos-update-count 'done -1)
5977 (todos-update-count 'archived 1)
5978 ;; Don't leave point below last item.
5979 (and item (bolp) (eolp) (< (point-min) (point-max))
5980 (todos-backward-item))
5981 (when item
5982 (throw 'done (setq item nil))))
5983 (todos-forward-item))))))
5984 (when marked
5985 (setq todos-categories-with-marks
5986 (assq-delete-all cat todos-categories-with-marks)))
5987 (todos-update-categories-sexp)
5988 (todos-prefix-overlays)))
5989 (find-file afile)
5990 (todos-category-number cat)
5991 (todos-category-select)
5992 (split-window-below)
5993 (set-window-buffer (selected-window) tbuf)
5994 ;; Make todo file current to select category.
5995 (find-file (buffer-file-name tbuf))
5996 ;; Make sure done item separator is hidden (if done items
5997 ;; were initially visible).
5998 (let (todos-show-with-done) (todos-category-select)))))))
5999
6000 (defun todos-unarchive-items ()
6001 "Unarchive at least one item in this archive category.
6002 If there are marked items, unarchive all of these; otherwise,
6003 unarchive the item at point.
6004
6005 Unarchived items are restored as done items to the corresponding
6006 category in the Todos file, inserted at the top of done items
6007 section. If all items in the archive category have been
6008 restored, the category is deleted from the archive. If this was
6009 the only category in the archive, the archive file is deleted."
6010 (interactive)
6011 (when (eq major-mode 'todos-archive-mode)
6012 (let* ((cat (todos-current-category))
6013 (tbuf (find-file-noselect
6014 (concat (file-name-sans-extension todos-current-todos-file)
6015 ".todo") t))
6016 (marked (assoc cat todos-categories-with-marks))
6017 (item (concat (todos-item-string) "\n"))
6018 (marked-count 0)
6019 marked-items
6020 buffer-read-only)
6021 (when marked
6022 (save-excursion
6023 (goto-char (point-min))
6024 (while (not (eobp))
6025 (when (todos-marked-item-p)
6026 (setq marked-items (concat marked-items (todos-item-string) "\n"))
6027 (setq marked-count (1+ marked-count)))
6028 (todos-forward-item))))
6029 ;; Restore items to top of category's done section and update counts.
6030 (with-current-buffer tbuf
6031 (let (buffer-read-only newcat)
6032 (widen)
6033 (goto-char (point-min))
6034 ;; Find the corresponding todo category, or if there isn't
6035 ;; one, add it.
6036 (unless (re-search-forward
6037 (concat "^" (regexp-quote (concat todos-category-beg cat))
6038 "$") nil t)
6039 (todos-add-category nil cat)
6040 (setq newcat t))
6041 ;; Go to top of category's done section.
6042 (re-search-forward
6043 (concat "^" (regexp-quote todos-category-done)) nil t)
6044 (forward-line)
6045 ;; FIXME: delete after checking
6046 ;; ;; Put point below newly added category beginning,
6047 ;; ;; otherwise the following search wrongly succeeds.
6048 ;; (forward-line))
6049 ;; (if (re-search-forward (concat "^" (regexp-quote todos-category-beg))
6050 ;; nil t)
6051 ;; (goto-char (match-beginning 0))
6052 ;; (goto-char (point-max)))
6053 (cond (marked
6054 (insert marked-items)
6055 (todos-update-count 'done marked-count cat)
6056 (unless newcat ; Newly added category has no archive.
6057 (todos-update-count 'archived (- marked-count) cat)))
6058 (t
6059 (insert item)
6060 (todos-update-count 'done 1 cat)
6061 (unless newcat ; Newly added category has no archive.
6062 (todos-update-count 'archived -1 cat))))
6063 (todos-update-categories-sexp)))
6064 ;; Delete restored items from archive.
6065 (when marked
6066 (setq item nil)
6067 (goto-char (point-min)))
6068 (catch 'done
6069 (while (not (eobp))
6070 (if (or (todos-marked-item-p) item)
6071 (progn
6072 (todos-remove-item)
6073 (when item
6074 (throw 'done (setq item nil))))
6075 (todos-forward-item))))
6076 (todos-update-count 'done (if marked (- marked-count) -1) cat)
6077 ;; If that was the last category in the archive, delete the whole file.
6078 (if (= (length todos-categories) 1)
6079 (progn
6080 (delete-file todos-current-todos-file)
6081 ;; Kill the archive buffer silently.
6082 (set-buffer-modified-p nil)
6083 (kill-buffer))
6084 ;; Otherwise, if the archive category is now empty, delete it.
6085 (when (eq (point-min) (point-max))
6086 (widen)
6087 (let ((beg (re-search-backward
6088 (concat "^" (regexp-quote todos-category-beg) cat "$")
6089 nil t))
6090 (end (if (re-search-forward
6091 (concat "^" (regexp-quote todos-category-beg))
6092 nil t 2)
6093 (match-beginning 0)
6094 (point-max))))
6095 (remove-overlays beg end)
6096 (delete-region beg end)
6097 (setq todos-categories (delete (assoc cat todos-categories)
6098 todos-categories))
6099 (todos-update-categories-sexp))))
6100 ;; Visit category in Todos file and show restored done items.
6101 (let ((tfile (buffer-file-name tbuf))
6102 (todos-show-with-done t))
6103 (set-window-buffer (selected-window)
6104 (set-buffer (find-file-noselect tfile)))
6105 (todos-category-number cat)
6106 (todos-category-select)
6107 (message "Items unarchived.")))))
6108
6109 (provide 'todos)
6110
6111 ;;; todos.el ends here
6112
6113 ;; FIXME: remove when part of Emacs
6114 ;; ---------------------------------------------------------------------------
6115 (add-to-list 'auto-mode-alist '("\\.todo\\'" . todos-mode))
6116 (add-to-list 'auto-mode-alist '("\\.toda\\'" . todos-archive-mode))
6117 (add-to-list 'auto-mode-alist '("\\.tod[tyr]\\'" . todos-filtered-items-mode))
6118
6119 ;;; Addition to calendar.el
6120 ;; FIXME: autoload when key-binding is defined in calendar.el
6121 (defun todos-insert-item-from-calendar (&optional arg)
6122 ""
6123 (interactive "P")
6124 (setq todos-date-from-calendar
6125 (calendar-date-string (calendar-cursor-to-date t) t t))
6126 (calendar-exit)
6127 (todos-show)
6128 (todos-insert-item arg nil nil todos-date-from-calendar))
6129
6130 (define-key calendar-mode-map "it" 'todos-insert-item-from-calendar)
6131
6132 ;;; necessitated adaptations to diary-lib.el
6133
6134 ;; (defun diary-goto-entry (button)
6135 ;; "Jump to the diary entry for the BUTTON at point."
6136 ;; (let* ((locator (button-get button 'locator))
6137 ;; (marker (car locator))
6138 ;; markbuf file opoint)
6139 ;; ;; If marker pointing to diary location is valid, use that.
6140 ;; (if (and marker (setq markbuf (marker-buffer marker)))
6141 ;; (progn
6142 ;; (pop-to-buffer markbuf)
6143 ;; (goto-char (marker-position marker)))
6144 ;; ;; Marker is invalid (eg buffer has been killed, as is the case with
6145 ;; ;; included diary files).
6146 ;; (or (and (setq file (cadr locator))
6147 ;; (file-exists-p file)
6148 ;; (find-file-other-window file)
6149 ;; (progn
6150 ;; (when (eq major-mode (default-value 'major-mode)) (diary-mode))
6151 ;; (when (eq major-mode 'todos-mode) (widen))
6152 ;; (goto-char (point-min))
6153 ;; (when (re-search-forward (format "%s.*\\(%s\\)"
6154 ;; (regexp-quote (nth 2 locator))
6155 ;; (regexp-quote (nth 3 locator)))
6156 ;; nil t)
6157 ;; (goto-char (match-beginning 1))
6158 ;; (when (eq major-mode 'todos-mode)
6159 ;; (setq opoint (point))
6160 ;; (re-search-backward (concat "^"
6161 ;; (regexp-quote todos-category-beg)
6162 ;; "\\(.*\\)\n")
6163 ;; nil t)
6164 ;; (todos-category-number (match-string 1))
6165 ;; (todos-category-select)
6166 ;; (goto-char opoint)))))
6167 ;; (message "Unable to locate this diary entry")))))