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