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