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