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