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>
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/>.
31 ;; For remove-duplicates in todos-insertion-commands-args.
32 (eval-when-compile (require 'cl))
34 ;; ---------------------------------------------------------------------------
38 "Create and maintain categorized lists of todo items."
39 :link '(emacs-commentary-link "todos")
43 (defcustom todos-files-directory (locate-user-emacs-file "todos/")
44 "Directory where user's Todos files are saved."
48 (defun todos-files (&optional archives)
49 "Default value of `todos-files-function'.
50 This returns the case-insensitive alphabetically sorted list of
51 file truenames in `todos-files-directory' with the extension
52 \".todo\". With non-nil ARCHIVES return the list of archive file
53 truenames (those with the extension \".toda\")."
54 (let ((files (if (file-exists-p todos-files-directory)
55 (mapcar 'file-truename
56 (directory-files todos-files-directory t
57 (if archives "\.toda$" "\.todo$") t)))))
58 (sort files (lambda (s1 s2) (let ((cis1 (upcase s1))
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'."
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))))
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))))
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'."
96 :initialize 'custom-initialize-default
97 :set 'todos-set-show-current-file
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)
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))))
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))))
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)
132 (defcustom todos-initial-file "Todo"
133 "Default file name offered on adding first Todos file."
137 (defcustom todos-initial-category "Todo"
138 "Default category name offered on initializing a new Todos file."
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))
149 (defcustom todos-completion-ignore-case nil
150 "Non-nil means case is ignored by `todos-read-*' functions."
154 (defcustom todos-undo-item-omit-comment 'ask
155 "Whether to omit done item comment on undoing the item.
156 Nil means never omit the comment, t means always omit it, `ask'
157 means prompt user and omit comment only on confirmation."
158 :type '(choice (const :tag "Never" nil)
159 (const :tag "Always" t)
160 (const :tag "Ask" ask))
163 (defcustom todos-print-function 'ps-print-buffer-with-faces
164 "Function called to print buffer content; see `todos-print'."
168 (defcustom todos-todo-mode-date-time-regexp
169 (concat "\\(?1:[0-9]\\{4\\}\\)-\\(?2:[0-9]\\{2\\}\\)-"
170 "\\(?3:[0-9]\\{2\\}\\) \\(?4:[0-9]\\{2\\}:[0-9]\\{2\\}\\)")
171 "Regexp matching legacy todo-mode.el item date-time strings.
172 In order for `todos-convert-legacy-files' to correctly convert this
173 string to the current Todos format, the regexp must contain four
174 explicitly numbered groups (see `(elisp) Regexp Backslash'),
175 where group 1 matches a string for the year, group 2 a string for
176 the month, group 3 a string for the day and group 4 a string for
177 the time. The default value converts date-time strings built
178 using the default value of `todo-time-string-format' from
183 ;; ---------------------------------------------------------------------------
184 ;;; Todos mode display options
186 (defgroup todos-mode-display nil
187 "User display options for Todos mode."
191 (defcustom todos-prefix ""
192 "String prefixed to todo items for visual distinction."
193 :type '(string :validate
195 (when (string= (widget-value widget) todos-item-mark)
198 "Invalid value: must be distinct from `todos-item-mark'")
200 :initialize 'custom-initialize-default
201 :set 'todos-reset-prefix
202 :group 'todos-mode-display)
204 (defcustom todos-number-priorities t
205 "Non-nil to prefix items with consecutively increasing integers.
206 These reflect the priorities of the items in each category."
208 :initialize 'custom-initialize-default
209 :set 'todos-reset-prefix
210 :group 'todos-mode-display)
212 (defun todos-reset-prefix (symbol value)
213 "The :set function for `todos-prefix' and `todos-number-priorities'."
214 (let ((oldvalue (symbol-value symbol))
215 (files todos-file-buffers))
216 (custom-set-default symbol value)
217 (when (not (equal value oldvalue))
219 (with-current-buffer (find-file-noselect f)
220 (remove-overlays 1 (1+ (buffer-size)) 'todos 'prefix)
221 ;; Activate the new setting in the current category.
222 (save-excursion (todos-category-select)))))))
224 (defcustom todos-item-mark "*"
225 "String used to mark items.
226 To ensure item marking works, change the value of this option
227 only when no items are marked."
228 :type '(string :validate
230 (when (string= (widget-value widget) todos-prefix)
233 "Invalid value: must be distinct from `todos-prefix'")
235 :set (lambda (symbol value)
236 (custom-set-default symbol (propertize value 'face 'todos-mark)))
237 :group 'todos-mode-display)
239 (defcustom todos-done-separator-string "="
240 "String for generating `todos-done-separator'.
242 If the string consists of a single character,
243 `todos-done-separator' will be the string made by repeating this
244 character for the width of the window, and the length is
245 automatically recalculated when the window width changes. If the
246 string consists of more (or less) than one character, it will be
247 the value of `todos-done-separator'."
249 :initialize 'custom-initialize-default
250 :set 'todos-reset-done-separator-string
251 :group 'todos-mode-display)
253 (defun todos-reset-done-separator-string (symbol value)
254 "The :set function for `todos-done-separator-string'."
255 (let ((oldvalue (symbol-value symbol))
256 (files todos-file-buffers)
257 (sep todos-done-separator))
258 (custom-set-default symbol value)
259 (when (not (equal value oldvalue))
261 (with-current-buffer (find-file-noselect f)
262 (let (buffer-read-only)
263 (setq todos-done-separator (todos-done-separator))
264 (when (= 1 (length value))
265 (todos-reset-done-separator sep)))
266 (todos-category-select))))))
268 (defcustom todos-done-string "DONE "
269 "Identifying string appended to the front of done todos items."
271 :initialize 'custom-initialize-default
272 :set 'todos-reset-done-string
273 :group 'todos-mode-display)
275 (defun todos-reset-done-string (symbol value)
276 "The :set function for user option `todos-done-string'."
277 (let ((oldvalue (symbol-value symbol))
278 (files (append todos-files todos-archives)))
279 (custom-set-default symbol value)
280 ;; Need to reset this to get font-locking right.
281 (setq todos-done-string-start
282 (concat "^\\[" (regexp-quote todos-done-string)))
283 (when (not (equal value oldvalue))
285 (with-current-buffer (find-file-noselect f)
286 (let (buffer-read-only)
288 (goto-char (point-min))
290 (if (re-search-forward
291 (concat "^" (regexp-quote todos-nondiary-start)
292 "\\(" (regexp-quote oldvalue) "\\)")
294 (replace-match value t t nil 1)
296 (todos-category-select)))))))
298 (defcustom todos-comment-string "COMMENT"
299 "String inserted before optional comment appended to done item."
301 :initialize 'custom-initialize-default
302 :set 'todos-reset-comment-string
303 :group 'todos-mode-display)
305 (defun todos-reset-comment-string (symbol value)
306 "The :set function for user option `todos-comment-string'."
307 (let ((oldvalue (symbol-value symbol))
308 (files (append todos-files todos-archives)))
309 (custom-set-default symbol value)
310 (when (not (equal value oldvalue))
312 (with-current-buffer (find-file-noselect f)
313 (let (buffer-read-only)
316 (goto-char (point-min))
318 (if (re-search-forward
320 "\\[\\(" (regexp-quote oldvalue) "\\): [^]]*\\]")
322 (replace-match value t t nil 1)
324 (todos-category-select))))))))
326 (defcustom todos-show-with-done nil
327 "Non-nil to display done items in all categories."
329 :group 'todos-mode-display)
331 (defun todos-mode-line-control (cat)
332 "Return a mode line control for Todos buffers.
333 Argument CAT is the name of the current Todos category.
334 This function is the value of the user variable
335 `todos-mode-line-function'."
336 (let ((file (todos-short-file-name todos-current-todos-file)))
337 (format "%s category %d: %s" file todos-category-number cat)))
339 (defcustom todos-mode-line-function 'todos-mode-line-control
340 "Function that returns a mode line control for Todos buffers.
341 The function expects one argument holding the name of the current
342 Todos category. The resulting control becomes the local value of
343 `mode-line-buffer-identification' in each Todos buffer."
345 :group 'todos-mode-display)
347 (defcustom todos-skip-archived-categories nil
348 "Non-nil to skip categories with only archived items when browsing.
350 Moving by category todos or archive file (with
351 \\[todos-forward-category] and \\[todos-backward-category]) skips
352 categories that contain only archived items. Other commands
353 still recognize these categories. In Todos Categories
354 mode (reached with \\[todos-display-categories]) these categories
355 shown in `todos-archived-only' face and clicking them in Todos
356 Categories mode visits the archived categories."
358 :group 'todos-mode-display)
360 (defcustom todos-highlight-item nil
361 "Non-nil means highlight items at point."
363 :initialize 'custom-initialize-default
364 :set 'todos-reset-highlight-item
365 :group 'todos-mode-display)
367 (defun todos-reset-highlight-item (symbol value)
368 "The :set function for `todos-highlight-item'."
369 (let ((oldvalue (symbol-value symbol))
370 (files (append todos-files todos-archives)))
371 (custom-set-default symbol value)
372 (when (not (equal value oldvalue))
374 (let ((buf (find-buffer-visiting f)))
376 (with-current-buffer buf
380 (hl-line-mode -1)))))))))
382 (defcustom todos-wrap-lines t
383 "Non-nil to wrap long lines via `todos-line-wrapping-function'."
384 :group 'todos-mode-display
387 (defcustom todos-line-wrapping-function 'todos-wrap-and-indent
388 "Line wrapping function used with non-nil `todos-wrap-lines'."
389 :group 'todos-mode-display
392 (defun todos-wrap-and-indent ()
393 "Use word wrapping on long lines and indent with a wrap prefix.
394 The amount of indentation is given by user option
395 `todos-indent-to-here'."
396 (set (make-local-variable 'word-wrap) t)
397 (set (make-local-variable 'wrap-prefix) (make-string todos-indent-to-here 32))
398 (unless (member '(continuation) fringe-indicator-alist)
399 (push '(continuation) fringe-indicator-alist)))
401 (defcustom todos-indent-to-here 6
402 "Number of spaces `todos-line-wrapping-function' indents to."
403 :type '(integer :validate
405 (unless (> (widget-value widget) 0)
406 (widget-put widget :error
407 "Invalid value: must be a positive integer")
411 (defun todos-indent ()
412 "Indent from point to `todos-indent-to-here'."
413 (indent-to todos-indent-to-here todos-indent-to-here))
415 ;; ---------------------------------------------------------------------------
416 ;;; Item insertion options
418 (defgroup todos-item-insertion nil
419 "User options for adding new todo items."
423 (defcustom todos-include-in-diary nil
424 "Non-nil to allow new Todo items to be included in the diary."
426 :group 'todos-item-insertion)
428 (defcustom todos-diary-nonmarking nil
429 "Non-nil to insert new Todo diary items as nonmarking by default.
430 This appends `diary-nonmarking-symbol' to the front of an item on
431 insertion provided it doesn't begin with `todos-nondiary-marker'."
433 :group 'todos-item-insertion)
435 (defcustom todos-nondiary-marker '("[" "]")
436 "List of strings surrounding item date to block diary inclusion.
437 The first string is inserted before the item date and must be a
438 non-empty string that does not match a diary date in order to
439 have its intended effect. The second string is inserted after
441 :type '(list string string)
442 :group 'todos-item-insertion
443 :initialize 'custom-initialize-default
444 :set 'todos-reset-nondiary-marker)
446 (defun todos-reset-nondiary-marker (symbol value)
447 "The :set function for user option `todos-nondiary-marker'."
448 (let ((oldvalue (symbol-value symbol))
449 (files (append todos-files todos-archives)))
450 (custom-set-default symbol value)
451 ;; Need to reset these to get font-locking right.
452 (setq todos-nondiary-start (nth 0 todos-nondiary-marker)
453 todos-nondiary-end (nth 1 todos-nondiary-marker)
454 todos-date-string-start
455 ;; See comment in defvar of `todos-date-string-start'.
456 (concat "^\\(" (regexp-quote todos-nondiary-start) "\\|"
457 (regexp-quote diary-nonmarking-symbol) "\\)?"))
458 (when (not (equal value oldvalue))
460 (with-current-buffer (find-file-noselect f)
461 (let (buffer-read-only)
463 (goto-char (point-min))
465 (if (re-search-forward
466 (concat "^\\(" todos-done-string-start "[^][]+] \\)?"
467 "\\(?1:" (regexp-quote (car oldvalue))
468 "\\)" todos-date-pattern "\\( "
469 diary-time-regexp "\\)?\\(?2:"
470 (regexp-quote (cadr oldvalue)) "\\)")
473 (replace-match (nth 0 value) t t nil 1)
474 (replace-match (nth 1 value) t t nil 2))
476 (todos-category-select)))))))
478 (defcustom todos-always-add-time-string nil
479 "Non-nil adds current time to a new item's date header by default.
480 When the Todos insertion commands have a non-nil \"maybe-notime\"
481 argument, this reverses the effect of
482 `todos-always-add-time-string': if t, these commands omit the
483 current time, if nil, they include it."
485 :group 'todos-item-insertion)
487 (defcustom todos-use-only-highlighted-region t
488 "Non-nil to enable inserting only highlighted region as new item."
490 :group 'todos-item-insertion)
492 ;; ---------------------------------------------------------------------------
493 ;;; Todos Filter Items mode options
495 (defgroup todos-filtered nil
496 "User options for Todos Filter Items mode."
500 (defcustom todos-filtered-items-buffer "Todos filtered items"
501 "Initial name of buffer in Todos Filter Items mode."
503 :group 'todos-filtered)
505 (defcustom todos-top-priorities-buffer "Todos top priorities"
506 "Buffer type string for `todos-filtered-buffer-name'."
508 :group 'todos-filtered)
510 (defcustom todos-diary-items-buffer "Todos diary items"
511 "Buffer type string for `todos-filtered-buffer-name'."
513 :group 'todos-filtered)
515 (defcustom todos-regexp-items-buffer "Todos regexp items"
516 "Buffer type string for `todos-filtered-buffer-name'."
518 :group 'todos-filtered)
520 (defcustom todos-priorities-rules nil
521 "List of rules giving how many items `todos-top-priorities' shows.
522 This variable should be set interactively by
523 `\\[todos-set-top-priorities-in-file]' or
524 `\\[todos-set-top-priorities-in-category]'.
526 Each rule is a list of the form (FILE NUM ALIST), where FILE is a
527 member of `todos-files', NUM is a number specifying the default
528 number of top priority items for each category in that file, and
529 ALIST, when non-nil, consists of conses of a category name in
530 FILE and a number specifying the default number of top priority
531 items in that category, which overrides NUM."
533 :group 'todos-filtered)
535 (defcustom todos-show-priorities 1
536 "Default number of top priorities shown by `todos-top-priorities'."
538 :group 'todos-filtered)
540 (defcustom todos-filter-files nil
541 "List of default files for multifile item filtering."
542 :type `(set ,@(mapcar (lambda (f) (list 'const f))
543 (mapcar 'todos-short-file-name
544 (funcall todos-files-function))))
545 :group 'todos-filtered)
547 (defun todos-reevaluate-filter-files-defcustom ()
548 "Reevaluate defcustom of `todos-filter-files'.
549 Called after adding or deleting a Todos file."
550 (eval (defcustom todos-filter-files nil
551 "List of files for multifile item filtering."
552 :type `(set ,@(mapcar (lambda (f) (list 'const f))
553 (mapcar 'todos-short-file-name
554 (funcall todos-files-function))))
557 (defcustom todos-filter-done-items nil
558 "Non-nil to include done items when processing regexp filters.
559 Done items from corresponding archive files are also included."
561 :group 'todos-filtered)
563 ;; ---------------------------------------------------------------------------
564 ;;; Todos Categories mode options
566 (defgroup todos-categories nil
567 "User options for Todos Categories mode."
571 (defcustom todos-categories-category-label "Category"
572 "Category button label in Todos Categories mode."
574 :group 'todos-categories)
576 (defcustom todos-categories-todo-label "Todo"
577 "Todo button label in Todos Categories mode."
579 :group 'todos-categories)
581 (defcustom todos-categories-diary-label "Diary"
582 "Diary button label in Todos Categories mode."
584 :group 'todos-categories)
586 (defcustom todos-categories-done-label "Done"
587 "Done button label in Todos Categories mode."
589 :group 'todos-categories)
591 (defcustom todos-categories-archived-label "Archived"
592 "Archived button label in Todos Categories mode."
594 :group 'todos-categories)
596 (defcustom todos-categories-totals-label "Totals"
597 "String to label total item counts in Todos Categories mode."
599 :group 'todos-categories)
601 (defcustom todos-categories-number-separator " | "
602 "String between number and category in Todos Categories mode.
603 This separates the number from the category name in the default
604 categories display according to priority."
606 :group 'todos-categories)
608 (defcustom todos-categories-align 'center
609 "Alignment of category names in Todos Categories mode."
610 :type '(radio (const left) (const center) (const right))
611 :group 'todos-categories)
613 ;; ---------------------------------------------------------------------------
614 ;;; Faces and font-lock matcher functions
616 (defgroup todos-faces nil
617 "Faces for the Todos modes."
621 (defface todos-prefix-string
622 ;; '((t :inherit font-lock-constant-face))
623 '((((class grayscale) (background light))
624 (:foreground "LightGray" :weight bold :underline t))
625 (((class grayscale) (background dark))
626 (:foreground "Gray50" :weight bold :underline t))
627 (((class color) (min-colors 88) (background light)) (:foreground "dark cyan"))
628 (((class color) (min-colors 88) (background dark)) (:foreground "Aquamarine"))
629 (((class color) (min-colors 16) (background light)) (:foreground "CadetBlue"))
630 (((class color) (min-colors 16) (background dark)) (:foreground "Aquamarine"))
631 (((class color) (min-colors 8)) (:foreground "magenta"))
632 (t (:weight bold :underline t)))
633 "Face for Todos prefix or numerical priority string."
636 (defface todos-top-priority
637 ;; bold font-lock-comment-face
638 '((default :weight bold)
639 (((class grayscale) (background light)) :foreground "DimGray" :slant italic)
640 (((class grayscale) (background dark)) :foreground "LightGray" :slant italic)
641 (((class color) (min-colors 88) (background light)) :foreground "Firebrick")
642 (((class color) (min-colors 88) (background dark)) :foreground "chocolate1")
643 (((class color) (min-colors 16) (background light)) :foreground "red")
644 (((class color) (min-colors 16) (background dark)) :foreground "red1")
645 (((class color) (min-colors 8) (background light)) :foreground "red")
646 (((class color) (min-colors 8) (background dark)) :foreground "yellow")
648 "Face for top priority Todos item numerical priority string.
649 The item's priority number string has this face if the number is
650 less than or equal the category's top priority setting."
654 ;; '((t :inherit font-lock-warning-face))
658 (:weight bold :foreground "Red1"))
662 (:weight bold :foreground "Pink"))
666 (:weight bold :foreground "Red1"))
670 (:weight bold :foreground "Pink"))
675 (:weight bold :inverse-video t)))
676 "Face for marks on Todos items."
679 (defface todos-button
680 ;; '((t :inherit widget-field))
682 (:foreground "black" :background "yellow3"))
683 (((class grayscale color)
685 (:background "gray85"))
686 (((class grayscale color)
688 (:background "dim gray"))
691 "Face for buttons in todos-display-categories."
694 (defface todos-sorted-column
699 (:background "grey85"))
702 (:background "grey85" :foreground "grey10"))
704 (:background "gray")))
705 "Face for buttons in todos-display-categories."
708 (defface todos-archived-only
709 ;; '((t (:inherit (shadow))))
712 (:foreground "grey50"))
715 (:foreground "grey70"))
717 (:foreground "gray")))
718 "Face for archived-only categories in todos-display-categories."
721 (defface todos-search
722 ;; '((t :inherit match))
726 (:background "yellow1"))
730 (:background "RoyalBlue3"))
734 (:foreground "black" :background "yellow"))
738 (:foreground "white" :background "blue"))
743 (:background "gray")))
744 "Face for matches found by todos-search."
747 (defface todos-diary-expired
748 ;; Doesn't contrast enough with todos-date (= diary) face.
749 ;; ;; '((t :inherit warning))
750 ;; '((default :weight bold)
751 ;; (((class color) (min-colors 16)) :foreground "DarkOrange")
752 ;; (((class color)) :foreground "yellow"))
753 ;; bold font-lock-function-name-face
754 '((default :weight bold)
755 (((class color) (min-colors 88) (background light)) :foreground "Blue1")
756 (((class color) (min-colors 88) (background dark)) :foreground "LightSkyBlue")
757 (((class color) (min-colors 16) (background light)) :foreground "Blue")
758 (((class color) (min-colors 16) (background dark)) :foreground "LightSkyBlue")
759 (((class color) (min-colors 8)) :foreground "blue")
760 (t :inverse-video t))
761 "Face for expired dates of diary items."
763 (defvar todos-diary-expired-face 'todos-diary-expired)
766 '((t :inherit diary))
767 "Face for the date string of a Todos item."
769 (defvar todos-date-face 'todos-date)
772 '((t :inherit diary-time))
773 "Face for the time string of a Todos item."
775 (defvar todos-time-face 'todos-time)
777 (defface todos-nondiary
778 ;; '((t :inherit font-lock-type-face))
779 '((((class grayscale) (background light)) :foreground "Gray90" :weight bold)
780 (((class grayscale) (background dark)) :foreground "DimGray" :weight bold)
781 (((class color) (min-colors 88) (background light)) :foreground "ForestGreen")
782 (((class color) (min-colors 88) (background dark)) :foreground "PaleGreen")
783 (((class color) (min-colors 16) (background light)) :foreground "ForestGreen")
784 (((class color) (min-colors 16) (background dark)) :foreground "PaleGreen")
785 (((class color) (min-colors 8)) :foreground "green")
786 (t :weight bold :underline t))
787 "Face for non-diary markers around todo item date/time header."
789 (defvar todos-nondiary-face 'todos-nondiary)
791 (defface todos-category-string
792 ;; '((t :inherit font-lock-type-face))
793 '((((class grayscale) (background light)) :foreground "Gray90" :weight bold)
794 (((class grayscale) (background dark)) :foreground "DimGray" :weight bold)
795 (((class color) (min-colors 88) (background light)) :foreground "ForestGreen")
796 (((class color) (min-colors 88) (background dark)) :foreground "PaleGreen")
797 (((class color) (min-colors 16) (background light)) :foreground "ForestGreen")
798 (((class color) (min-colors 16) (background dark)) :foreground "PaleGreen")
799 (((class color) (min-colors 8)) :foreground "green")
800 (t :weight bold :underline t))
801 "Face for category file names in Todos Filtered Item."
803 (defvar todos-category-string-face 'todos-category-string)
806 ;; '((t :inherit font-lock-keyword-face))
807 '((((class grayscale) (background light)) :foreground "LightGray" :weight bold)
808 (((class grayscale) (background dark)) :foreground "DimGray" :weight bold)
809 (((class color) (min-colors 88) (background light)) :foreground "Purple")
810 (((class color) (min-colors 88) (background dark)) :foreground "Cyan1")
811 (((class color) (min-colors 16) (background light)) :foreground "Purple")
812 (((class color) (min-colors 16) (background dark)) :foreground "Cyan")
813 (((class color) (min-colors 8)) :foreground "cyan" :weight bold)
815 "Face for done Todos item header string."
817 (defvar todos-done-face 'todos-done)
819 (defface todos-comment
820 ;; '((t :inherit font-lock-comment-face))
821 '((((class grayscale) (background light))
822 :foreground "DimGray" :weight bold :slant italic)
823 (((class grayscale) (background dark))
824 :foreground "LightGray" :weight bold :slant italic)
825 (((class color) (min-colors 88) (background light))
826 :foreground "Firebrick")
827 (((class color) (min-colors 88) (background dark))
828 :foreground "chocolate1")
829 (((class color) (min-colors 16) (background light))
831 (((class color) (min-colors 16) (background dark))
833 (((class color) (min-colors 8) (background light))
835 (((class color) (min-colors 8) (background dark))
836 :foreground "yellow")
837 (t :weight bold :slant italic))
838 "Face for comments appended to done Todos items."
840 (defvar todos-comment-face 'todos-comment)
842 (defface todos-done-sep
843 ;; '((t :inherit font-lock-builtin-face))
844 '((((class grayscale) (background light)) :foreground "LightGray" :weight bold)
845 (((class grayscale) (background dark)) :foreground "DimGray" :weight bold)
846 (((class color) (min-colors 88) (background light)) :foreground "dark slate blue")
847 (((class color) (min-colors 88) (background dark)) :foreground "LightSteelBlue")
848 (((class color) (min-colors 16) (background light)) :foreground "Orchid")
849 (((class color) (min-colors 16) (background dark)) :foreground "LightSteelBlue")
850 (((class color) (min-colors 8)) :foreground "blue" :weight bold)
852 "Face for separator string bewteen done and not done Todos items."
854 (defvar todos-done-sep-face 'todos-done-sep)
856 (defun todos-date-string-matcher (lim)
857 "Search for Todos date string within LIM for font-locking."
859 (concat todos-date-string-start "\\(?1:" todos-date-pattern "\\)") lim t))
861 (defun todos-time-string-matcher (lim)
862 "Search for Todos time string within LIM for font-locking."
863 (re-search-forward (concat todos-date-string-start todos-date-pattern
864 " \\(?1:" diary-time-regexp "\\)") lim t))
866 (defun todos-nondiary-marker-matcher (lim)
867 "Search for Todos nondiary markers within LIM for font-locking."
868 (re-search-forward (concat "^\\(?1:" (regexp-quote todos-nondiary-start) "\\)"
869 todos-date-pattern "\\(?: " diary-time-regexp
870 "\\)?\\(?2:" (regexp-quote todos-nondiary-end) "\\)")
873 (defun todos-diary-nonmarking-matcher (lim)
874 "Search for diary nonmarking symbol within LIM for font-locking."
875 (re-search-forward (concat "^\\(?1:" (regexp-quote diary-nonmarking-symbol)
876 "\\)" todos-date-pattern) lim t))
878 (defun todos-diary-expired-matcher (lim)
879 "Search for expired diary item date within LIM for font-locking."
880 (when (re-search-forward (concat "^\\(?:"
881 (regexp-quote diary-nonmarking-symbol)
882 "\\)?\\(?1:" todos-date-pattern "\\) \\(?2:"
883 diary-time-regexp "\\)?") lim t)
884 (let* ((date (match-string-no-properties 1))
885 (time (match-string-no-properties 2))
886 ;; Function days-between requires a non-empty time string.
887 (date-time (concat date " " (or time "00:00"))))
888 (or (and (not (string-match ".+day\\|\\*" date))
889 (< (days-between date-time (current-time-string)) 0))
890 (todos-diary-expired-matcher lim)))))
892 (defun todos-done-string-matcher (lim)
893 "Search for Todos done header within LIM for font-locking."
894 (re-search-forward (concat todos-done-string-start
898 (defun todos-comment-string-matcher (lim)
899 "Search for Todos done comment within LIM for font-locking."
900 (re-search-forward (concat "\\[\\(?1:" todos-comment-string "\\):")
903 ;; (defun todos-category-string-matcher (lim)
904 ;; "Search for Todos category name within LIM for font-locking.
905 ;; This is for fontifying category names appearing in Todos filter
907 ;; (if (eq major-mode 'todos-filtered-items-mode)
908 ;; (re-search-forward
909 ;; (concat "^\\(?:" todos-date-string-start "\\)?" todos-date-pattern
910 ;; "\\(?: " diary-time-regexp "\\)?\\(?:"
911 ;; (regexp-quote todos-nondiary-end) "\\)? \\(?1:\\[.+\\]\\)")
914 (defun todos-category-string-matcher-1 (lim)
915 "Search for Todos category name within LIM for font-locking.
916 This is for fontifying category and file names appearing in Todos
917 Filtered Items mode following done items."
918 (if (eq major-mode 'todos-filtered-items-mode)
919 (re-search-forward (concat todos-done-string-start todos-date-pattern
920 "\\(?: " diary-time-regexp
921 ;; Use non-greedy operator to prevent
922 ;; capturing possible following non-diary
924 "\\)?] \\(?1:\\[.+?\\]\\)")
927 (defun todos-category-string-matcher-2 (lim)
928 "Search for Todos category name within LIM for font-locking.
929 This is for fontifying category and file names appearing in Todos
930 Filtered Items mode following todo (not done) items."
931 (if (eq major-mode 'todos-filtered-items-mode)
932 (re-search-forward (concat todos-date-string-start todos-date-pattern
933 "\\(?: " diary-time-regexp "\\)?\\(?:"
934 (regexp-quote todos-nondiary-end)
935 "\\)? \\(?1:\\[.+\\]\\)")
938 (defvar todos-font-lock-keywords
940 '(todos-nondiary-marker-matcher 1 todos-nondiary-face t)
941 '(todos-nondiary-marker-matcher 2 todos-nondiary-face t)
942 ;; diary-lib.el uses font-lock-constant-face for diary-nonmarking-symbol.
943 '(todos-diary-nonmarking-matcher 1 font-lock-constant-face t)
944 '(todos-date-string-matcher 1 todos-date-face t)
945 '(todos-time-string-matcher 1 todos-time-face t)
946 '(todos-done-string-matcher 0 todos-done-face t)
947 '(todos-comment-string-matcher 1 todos-comment-face t)
948 '(todos-category-string-matcher-1 1 todos-category-string-face t t)
949 '(todos-category-string-matcher-2 1 todos-category-string-face t t)
950 '(todos-diary-expired-matcher 1 todos-diary-expired-face t)
951 '(todos-diary-expired-matcher 2 todos-diary-expired-face t t)
953 "Font-locking for Todos modes.")
955 ;; ---------------------------------------------------------------------------
956 ;;; Todos mode local variables and hook functions
958 (defvar todos-current-todos-file nil
959 "Variable holding the name of the currently active Todos file.")
961 (defun todos-show-current-file ()
962 "Visit current instead of default Todos file with `todos-show'.
963 This function is added to `pre-command-hook' when user option
964 `todos-show-current-file' is set to non-nil."
965 (setq todos-global-current-todos-file todos-current-todos-file))
967 (defun todos-display-as-todos-file ()
968 "Show Todos files correctly when visited from outside of Todos mode."
969 (and (member this-command todos-visit-files-commands)
970 (= (- (point-max) (point-min)) (buffer-size))
971 (member major-mode '(todos-mode todos-archive-mode))
972 (todos-category-select)))
974 (defun todos-add-to-buffer-list ()
975 "Add name of just visited Todos file to `todos-file-buffers'.
976 This function is added to `find-file-hook' in Todos mode."
977 (let ((filename (file-truename (buffer-file-name))))
978 (when (member filename todos-files)
979 (add-to-list 'todos-file-buffers filename))))
981 (defun todos-update-buffer-list ()
982 "Make current Todos mode buffer file car of `todos-file-buffers'.
983 This function is added to `post-command-hook' in Todos mode."
984 (let ((filename (file-truename (buffer-file-name))))
985 (unless (eq (car todos-file-buffers) filename)
986 (setq todos-file-buffers
987 (cons filename (delete filename todos-file-buffers))))))
989 (defun todos-reset-global-current-todos-file ()
990 "Update the value of `todos-global-current-todos-file'.
991 This becomes the latest existing Todos file or, if there is none,
992 the value of `todos-default-todos-file'.
993 This function is added to `kill-buffer-hook' in Todos mode."
994 (let ((filename (file-truename (buffer-file-name))))
995 (setq todos-file-buffers (delete filename todos-file-buffers))
996 (setq todos-global-current-todos-file
997 (or (car todos-file-buffers)
998 (todos-absolute-file-name todos-default-todos-file)))))
1000 (defvar todos-categories nil
1001 "Alist of categories in the current Todos file.
1002 The elements are cons cells whose car is a category name and
1003 whose cdr is a vector of the category's item counts. These are,
1004 in order, the numbers of todo items, of todo items included in
1005 the Diary, of done items and of archived items.")
1007 (defvar todos-categories-with-marks nil
1008 "Alist of categories and number of marked items they contain.")
1010 (defvar todos-category-number 1
1011 "Variable holding the number of the current Todos category.
1012 Todos categories are numbered starting from 1.")
1014 (defvar todos-show-done-only nil
1015 "If non-nil display only done items in current category.
1016 Set by the command `todos-show-done-only' and used by
1017 `todos-category-select'.")
1019 (defun todos-reset-and-enable-done-separator ()
1020 "Show resized done items separator overlay after window change.
1021 Added to `window-configuration-change-hook' in `todos-mode'."
1022 (when (= 1 (length todos-done-separator-string))
1023 (let ((sep todos-done-separator))
1024 (setq todos-done-separator (todos-done-separator))
1025 (save-match-data (todos-reset-done-separator sep)))))
1027 ;; ---------------------------------------------------------------------------
1028 ;;; Global variables and helper functions for files and buffers
1030 (defvar todos-files (funcall todos-files-function)
1031 "List of truenames of user's Todos files.")
1033 (defvar todos-archives (funcall todos-files-function t)
1034 "List of truenames of user's Todos archives.")
1036 (defvar todos-visited nil
1037 "List of Todos files visited in this session by `todos-show'.
1038 Used to determine initial display according to the value of
1039 `todos-show-first'.")
1041 (defvar todos-file-buffers nil
1042 "List of file names of live Todos mode buffers.")
1044 (defvar todos-global-current-todos-file nil
1045 "Variable holding name of current Todos file.
1046 Used by functions called from outside of Todos mode to visit the
1047 current Todos file rather than the default Todos file (i.e. when
1048 users option `todos-show-current-file' is non-nil).")
1050 (defun todos-reevaluate-filelist-defcustoms ()
1051 "Reevaluate defcustoms that provide choice list of Todos files."
1052 (custom-set-default 'todos-default-todos-file
1053 (symbol-value 'todos-default-todos-file))
1054 (todos-reevaluate-default-file-defcustom)
1055 (custom-set-default 'todos-filter-files (symbol-value 'todos-filter-files))
1056 (todos-reevaluate-filter-files-defcustom)
1057 (custom-set-default 'todos-category-completions-files
1058 (symbol-value 'todos-category-completions-files))
1059 (todos-reevaluate-category-completions-files-defcustom))
1061 (defvar todos-edit-buffer "*Todos Edit*"
1062 "Name of current buffer in Todos Edit mode.")
1064 (defvar todos-categories-buffer "*Todos Categories*"
1065 "Name of buffer in Todos Categories mode.")
1067 (defvar todos-print-buffer "*Todos Print*"
1068 "Name of buffer containing printable Todos text.")
1070 (defun todos-absolute-file-name (name &optional type)
1071 "Return the absolute file name of short Todos file NAME.
1072 With TYPE `archive' or `top' return the absolute file name of the
1073 short Todos Archive or Top Priorities file name, respectively."
1074 ;; NOP if there is no Todos file yet (i.e. don't concatenate nil).
1077 (concat todos-files-directory name
1078 (cond ((eq type 'archive) ".toda")
1079 ((eq type 'top) ".todt")
1082 (defun todos-check-format ()
1083 "Signal an error if the current Todos file is ill-formatted.
1084 Otherwise return t. The error message gives the line number
1085 where the invalid formatting was found."
1089 (goto-char (point-min))
1090 (let ((cats (prin1-to-string todos-categories))
1091 (sexp (buffer-substring-no-properties (line-beginning-position)
1092 (line-end-position))))
1093 ;; Check for `todos-categories' sexp as the first line
1094 (unless (string= sexp cats)
1095 (error "Invalid or missing todos-categories sexp")))
1097 (let ((legit (concat "\\(^" (regexp-quote todos-category-beg) "\\)"
1098 "\\|\\(" todos-date-string-start todos-date-pattern "\\)"
1099 "\\|\\(^[ \t]+[^ \t]*\\)"
1101 "\\|\\(^" (regexp-quote todos-category-done) "\\)"
1102 "\\|\\(" todos-done-string-start "\\)")))
1104 (unless (looking-at legit)
1105 (error "Illegitimate Todos file format at line %d"
1106 (line-number-at-pos (point))))
1108 ;; (message "This Todos file is well-formatted.")
1111 ;; ---------------------------------------------------------------------------
1112 (defun todos-convert-legacy-date-time ()
1113 "Return converted date-time string.
1114 Helper function for `todos-convert-legacy-files'."
1115 (let* ((year (match-string 1))
1116 (month (match-string 2))
1117 (monthname (calendar-month-name (string-to-number month) t))
1118 (day (match-string 3))
1119 (time (match-string 4))
1122 (insert (mapconcat 'eval calendar-date-display-form "")
1123 (when time (concat " " time)))))
1125 ;; ---------------------------------------------------------------------------
1126 ;;; Global variables and helper functions for categories
1128 (defun todos-category-number (cat)
1129 "Return the number of category CAT in this Todos file.
1130 The buffer-local variable `todos-category-number' holds this
1131 number as its value."
1132 (let ((categories (mapcar 'car todos-categories)))
1133 (setq todos-category-number
1134 ;; Increment by one, so that the highest priority category in Todos
1135 ;; Categories mode is numbered one rather than zero.
1136 (1+ (- (length categories)
1137 (length (member cat categories)))))))
1139 (defun todos-current-category ()
1140 "Return the name of the current category."
1141 (car (nth (1- todos-category-number) todos-categories)))
1143 (defconst todos-category-beg "--==-- "
1144 "String marking beginning of category (inserted with its name).")
1146 (defconst todos-category-done "==--== DONE "
1147 "String marking beginning of category's done items.")
1149 (defun todos-done-separator ()
1150 "Return string used as value of variable `todos-done-separator'."
1151 (let ((sep todos-done-separator-string))
1152 (propertize (if (= 1 (length sep))
1153 ;; If separator's length is window-width, then
1154 ;; with non-nil todos-wrap-lines and
1155 ;; todos-wrap-and-indent as value of
1156 ;; todos-line-wrapping-function, an indented empty
1157 ;; line appears between the separator and the
1159 (make-string (1- (window-width)) (string-to-char sep))
1160 ;; (make-string (window-width) (string-to-char sep))
1161 todos-done-separator-string)
1162 'face 'todos-done-sep)))
1164 (defvar todos-done-separator (todos-done-separator)
1165 "String used to visually separate done from not done items.
1166 Displayed as an overlay instead of `todos-category-done' when
1167 done items are shown. Its value is determined by user option
1168 `todos-done-separator-string'.")
1170 (defun todos-reset-done-separator (sep)
1171 "Replace existing overlays of done items separator string SEP."
1175 (goto-char (point-min))
1176 (while (re-search-forward
1177 (concat "\n\\(" (regexp-quote todos-category-done) "\\)") nil t)
1178 (let* ((beg (match-beginning 1))
1180 (ov (progn (goto-char beg)
1181 (todos-get-overlay 'separator)))
1182 (old-sep (when ov (overlay-get ov 'display)))
1185 (unless (string= old-sep sep)
1186 (setq new-ov (make-overlay beg end))
1187 (overlay-put new-ov 'todos 'separator)
1188 (overlay-put new-ov 'display todos-done-separator)
1189 (delete-overlay ov))))))))
1191 (defun todos-category-completions ()
1192 "Return a list of completions for `todos-read-category'.
1193 Each element of the list is a cons of a category name and the
1194 file or list of files (as short file names) it is in. The files
1195 are the current (or else the default) Todos file plus all other
1196 Todos files named in `todos-category-completions-files'."
1197 (let* ((curfile (or todos-current-todos-file
1198 (and todos-show-current-file
1199 todos-global-current-todos-file)
1200 (todos-absolute-file-name todos-default-todos-file)))
1201 (files (or (mapcar 'todos-absolute-file-name
1202 todos-category-completions-files)
1205 ;; If file was just added, it has no category completions.
1206 (unless (zerop (buffer-size (find-buffer-visiting curfile)))
1207 (add-to-list 'files curfile)
1208 (dolist (f files listall)
1209 (with-current-buffer (find-file-noselect f 'nowarn)
1213 (goto-char (point-min))
1214 (setq listf (read (buffer-substring-no-properties
1215 (line-beginning-position)
1216 (line-end-position)))))))
1217 (mapc (lambda (elt) (let* ((cat (car elt))
1218 (la-elt (assoc cat listall)))
1220 (setcdr la-elt (append (list (cdr la-elt))
1222 (push (cons cat f) listall))))
1225 (defun todos-category-select ()
1226 "Display the current category correctly."
1227 (let ((name (todos-current-category))
1228 cat-begin cat-end done-start done-sep-start done-end)
1230 (goto-char (point-min))
1232 (concat "^" (regexp-quote (concat todos-category-beg name)) "$") nil t)
1233 (setq cat-begin (1+ (line-end-position)))
1234 (setq cat-end (if (re-search-forward
1235 (concat "^" (regexp-quote todos-category-beg)) nil t)
1238 (setq mode-line-buffer-identification
1239 (funcall todos-mode-line-function name))
1240 (narrow-to-region cat-begin cat-end)
1241 (todos-prefix-overlays)
1242 (goto-char (point-min))
1243 (if (re-search-forward (concat "\n\\(" (regexp-quote todos-category-done)
1246 (setq done-start (match-beginning 0))
1247 (setq done-sep-start (match-beginning 1))
1248 (setq done-end (match-end 0)))
1249 (error "Category %s is missing todos-category-done string" name))
1250 (if todos-show-done-only
1251 (narrow-to-region (1+ done-end) (point-max))
1252 (when (and todos-show-with-done
1253 (re-search-forward todos-done-string-start nil t))
1254 ;; Now we want to see the done items, so reset displayed end to end of
1256 (setq done-start cat-end)
1257 ;; Make display overlay for done items separator string, unless there
1259 (let* ((done-sep todos-done-separator)
1260 (ov (progn (goto-char done-sep-start)
1261 (todos-get-overlay 'separator))))
1263 (setq ov (make-overlay done-sep-start done-end))
1264 (overlay-put ov 'todos 'separator)
1265 (overlay-put ov 'display done-sep))))
1266 (narrow-to-region (point-min) done-start)
1267 ;; Loading this from todos-mode, or adding it to the mode hook, causes
1268 ;; Emacs to hang in todos-item-start, at (looking-at todos-item-start).
1269 (when todos-highlight-item
1271 (hl-line-mode 1)))))
1273 (defun todos-get-count (type &optional category)
1274 "Return count of TYPE items in CATEGORY.
1275 If CATEGORY is nil, default to the current category."
1276 (let* ((cat (or category (todos-current-category)))
1277 (counts (cdr (assoc cat todos-categories)))
1278 (idx (cond ((eq type 'todo) 0)
1279 ((eq type 'diary) 1)
1281 ((eq type 'archived) 3))))
1284 (defun todos-update-count (type increment &optional category)
1285 "Change count of TYPE items in CATEGORY by integer INCREMENT.
1286 With nil or omitted CATEGORY, default to the current category."
1287 (let* ((cat (or category (todos-current-category)))
1288 (counts (cdr (assoc cat todos-categories)))
1289 (idx (cond ((eq type 'todo) 0)
1290 ((eq type 'diary) 1)
1292 ((eq type 'archived) 3))))
1293 (aset counts idx (+ increment (aref counts idx)))))
1295 (defun todos-set-categories ()
1296 "Set `todos-categories' from the sexp at the top of the file."
1297 ;; New archive files created by `todos-move-category' are empty, which would
1298 ;; make the sexp test fail and raise an error, so in this case we skip it.
1299 (unless (zerop (buffer-size))
1303 (goto-char (point-min))
1304 (setq todos-categories
1305 (if (looking-at "\(\(\"")
1306 (read (buffer-substring-no-properties
1307 (line-beginning-position)
1308 (line-end-position)))
1309 (error "Invalid or missing todos-categories sexp")))))))
1311 (defun todos-update-categories-sexp ()
1312 "Update the `todos-categories' sexp at the top of the file."
1313 (let (buffer-read-only)
1317 (goto-char (point-min))
1318 (if (looking-at (concat "^" (regexp-quote todos-category-beg)))
1319 (progn (newline) (goto-char (point-min)) ; Make space for sexp.
1320 (setq todos-categories (todos-make-categories-list t)))
1321 (delete-region (line-beginning-position) (line-end-position)))
1322 (prin1 todos-categories (current-buffer))))))
1324 (defun todos-make-categories-list (&optional force)
1325 "Return an alist of Todos categories and their item counts.
1326 With non-nil argument FORCE parse the entire file to build the
1327 list; otherwise, get the value by reading the sexp at the top of
1329 (setq todos-categories nil)
1333 (goto-char (point-min))
1334 (let (counts cat archive)
1335 ;; If the file is a todo file and has archived items, identify the
1336 ;; archive, in order to count its items. But skip this with
1337 ;; `todos-convert-legacy-files', since that converts filed items to
1339 (when buffer-file-name ; During conversion there is no file yet.
1340 ;; If the file is an archive, it doesn't have an archive.
1341 (unless (member (file-truename buffer-file-name)
1342 (funcall todos-files-function t))
1343 (setq archive (concat (file-name-sans-extension
1344 todos-current-todos-file) ".toda"))))
1346 (cond ((looking-at (concat (regexp-quote todos-category-beg)
1348 (setq cat (match-string-no-properties 1))
1349 ;; Counts for each category: [todo diary done archive]
1350 (setq counts (make-vector 4 0))
1351 (setq todos-categories
1352 (append todos-categories (list (cons cat counts))))
1353 ;; Add archived item count to the todo file item counts.
1354 ;; Make sure to include newly created archives, e.g. due to
1355 ;; todos-move-category.
1356 (when (member archive (funcall todos-files-function t))
1357 (let ((archive-count 0))
1358 (with-current-buffer (find-file-noselect archive)
1360 (goto-char (point-min))
1361 (when (re-search-forward
1362 (concat "^" (regexp-quote todos-category-beg)
1366 (while (not (or (looking-at
1368 (regexp-quote todos-category-beg)
1371 (when (looking-at todos-done-string-start)
1372 (setq archive-count (1+ archive-count)))
1374 (todos-update-count 'archived archive-count cat))))
1375 ((looking-at todos-done-string-start)
1376 (todos-update-count 'done 1 cat))
1377 ((looking-at (concat "^\\("
1378 (regexp-quote diary-nonmarking-symbol)
1379 "\\)?" todos-date-pattern))
1380 (todos-update-count 'diary 1 cat)
1381 (todos-update-count 'todo 1 cat))
1382 ((looking-at (concat todos-date-string-start todos-date-pattern))
1383 (todos-update-count 'todo 1 cat))
1384 ;; If first line is todos-categories list, use it and end loop
1385 ;; -- unless FORCEd to scan whole file.
1388 (setq todos-categories (read (buffer-substring-no-properties
1389 (line-beginning-position)
1390 (line-end-position))))
1391 (goto-char (1- (point-max))))))
1395 (defun todos-repair-categories-sexp ()
1396 "Repair corrupt Todos categories sexp.
1397 This should only be needed as a consequence of careless manual
1398 editing or a bug in todos.el.
1400 *Warning*: Calling this command restores the category order to
1401 the list element order in the Todos categories sexp, so any order
1402 changes made in Todos Categories mode will have to be made again."
1404 (let ((todos-categories (todos-make-categories-list t)))
1405 (todos-update-categories-sexp)))
1407 ;;; Global variables and helper functions for items
1409 (defconst todos-month-name-array
1410 (vconcat calendar-month-name-array (vector "*"))
1411 "Array of month names, in order.
1412 The final element is \"*\", indicating an unspecified month.")
1414 (defconst todos-month-abbrev-array
1415 (vconcat calendar-month-abbrev-array (vector "*"))
1416 "Array of abbreviated month names, in order.
1417 The final element is \"*\", indicating an unspecified month.")
1419 (defconst todos-date-pattern
1420 (let ((dayname (diary-name-pattern calendar-day-name-array nil t)))
1421 (concat "\\(?5:" dayname "\\|"
1423 (monthname (format "\\(?6:%s\\)" (diary-name-pattern
1424 todos-month-name-array
1425 todos-month-abbrev-array)))
1426 (month "\\(?7:[0-9]+\\|\\*\\)")
1427 (day "\\(?8:[0-9]+\\|\\*\\)")
1428 (year "-?\\(?9:[0-9]+\\|\\*\\)"))
1429 (mapconcat 'eval calendar-date-display-form ""))
1431 "Regular expression matching a Todos date header.")
1433 (defconst todos-nondiary-start (nth 0 todos-nondiary-marker)
1434 "String inserted before item date to block diary inclusion.")
1436 (defconst todos-nondiary-end (nth 1 todos-nondiary-marker)
1437 "String inserted after item date matching `todos-nondiary-start'.")
1439 ;; By itself this matches anything, because of the `?'; however, it's only
1440 ;; used in the context of `todos-date-pattern' (but Emacs Lisp lacks
1442 (defconst todos-date-string-start
1443 (concat "^\\(" (regexp-quote todos-nondiary-start) "\\|"
1444 (regexp-quote diary-nonmarking-symbol) "\\)?")
1445 "Regular expression matching part of item header before the date.")
1447 (defconst todos-done-string-start
1448 (concat "^\\[" (regexp-quote todos-done-string))
1449 "Regular expression matching start of done item.")
1451 (defconst todos-item-start (concat "\\(" todos-date-string-start "\\|"
1452 todos-done-string-start "\\)"
1454 "String identifying start of a Todos item.")
1456 (defun todos-item-start ()
1457 "Move to start of current Todos item and return its position."
1459 ;; Buffer is empty (invocation possible e.g. via todos-forward-item
1460 ;; from todos-filter-items when processing category with no todo
1462 (eq (point-min) (point-max))
1463 ;; Point is on the empty line below category's last todo item...
1464 (and (looking-at "^$")
1465 (or (eobp) ; ...and done items are hidden...
1466 (save-excursion ; ...or done items are visible.
1468 (looking-at (concat "^"
1469 (regexp-quote todos-category-done))))))
1470 ;; Buffer is widened.
1471 (looking-at (regexp-quote todos-category-beg)))
1472 (goto-char (line-beginning-position))
1473 (while (not (looking-at todos-item-start))
1477 (defun todos-item-end ()
1478 "Move to end of current Todos item and return its position."
1479 ;; Items cannot end with a blank line.
1480 (unless (looking-at "^$")
1481 (let* ((done (todos-done-item-p))
1483 ;; For todo items, end is before the done items section, for done
1484 ;; items, end is before the next category. If these limits are
1485 ;; missing or inaccessible, end it before the end of the buffer.
1486 (lim (if (save-excursion
1488 (concat "^" (regexp-quote (if done
1490 todos-category-done)))
1492 (progn (setq to-lim t) (match-beginning 0))
1494 (when (bolp) (forward-char)) ; Find start of next item.
1495 (goto-char (if (re-search-forward todos-item-start lim t)
1497 (if to-lim lim (point-max))))
1498 ;; For last todo item, skip back over the empty line before the done
1499 ;; items section, else just back to the end of the previous line.
1500 (backward-char (when (and to-lim (not done) (eq (point) lim)) 2))
1503 (defun todos-item-string ()
1504 "Return bare text of current item as a string."
1505 (let ((opoint (point))
1506 (start (todos-item-start))
1507 (end (todos-item-end)))
1509 (and start end (buffer-substring-no-properties start end))))
1511 (defun todos-remove-item ()
1512 "Internal function called in editing, deleting or moving items."
1513 (let* ((end (progn (todos-item-end) (1+ (point))))
1514 (beg (todos-item-start))
1515 (ov (todos-get-overlay 'prefix)))
1516 (when ov (delete-overlay ov))
1517 (delete-region beg end)))
1519 (defun todos-diary-item-p ()
1520 "Return non-nil if item at point has diary entry format."
1522 (when (todos-item-string) ; Exclude empty lines.
1524 (not (looking-at (regexp-quote todos-nondiary-start))))))
1526 (defun todos-done-item-p ()
1527 "Return non-nil if item at point is a done item."
1530 (looking-at todos-done-string-start)))
1532 (defun todos-done-item-section-p ()
1533 "Return non-nil if point is in category's done items section."
1535 (or (re-search-backward (concat "^" (regexp-quote todos-category-done))
1537 (progn (goto-char (point-min))
1538 (looking-at todos-done-string-start)))))
1540 (defun todos-get-overlay (val)
1541 "Return the overlay at point whose `todos' property has value VAL."
1542 ;; Use overlays-in to find prefix overlays and check over two
1543 ;; positions to find done separator overlay.
1544 (let ((ovs (overlays-in (point) (1+ (point))))
1549 (when (eq (overlay-get ov 'todos) val)
1550 (throw 'done ov))))))
1552 (defun todos-marked-item-p ()
1553 "Non-nil if this item begins with `todos-item-mark'.
1554 In that case, return the item's prefix overlay."
1555 ;; If a todos-item-insert command is called on a Todos file before
1556 ;; it is visited, it has no prefix overlays, so conditionalize:
1557 (let* ((ov (todos-get-overlay 'prefix))
1558 (pref (when ov (overlay-get ov 'before-string)))
1560 (string-match (concat "^" (regexp-quote todos-item-mark))
1564 (defun todos-insert-with-overlays (item)
1565 "Insert ITEM at point and update prefix/priority number overlays."
1567 ;; Insertion pushes item down but not its prefix overlay. When the
1568 ;; overlay includes a mark, this would now mark the inserted ITEM,
1569 ;; so move it to the pushed down item.
1570 (let ((ov (todos-get-overlay 'prefix))
1571 (marked (todos-marked-item-p)))
1573 (when marked (move-overlay ov (point) (point))))
1574 (todos-backward-item)
1575 (todos-prefix-overlays))
1577 (defun todos-prefix-overlays ()
1578 "Update the prefix overlays of the current category's items.
1579 The overlay's value is the string `todos-prefix' or with non-nil
1580 `todos-number-priorities' an integer in the sequence from 1 to
1581 the number of todo or done items in the category indicating the
1582 item's priority. Todo and done items are numbered independently
1585 (cat-tp (or (cdr (assoc-string
1586 (todos-current-category)
1587 (nth 2 (assoc-string todos-current-todos-file
1588 todos-priorities-rules))))
1589 todos-show-priorities))
1592 (goto-char (point-min))
1594 (when (or (todos-date-string-matcher (line-end-position))
1595 (todos-done-string-matcher (line-end-position)))
1596 (goto-char (match-beginning 0))
1598 ;; Reset number to 1 for first done item.
1599 (when (and (looking-at todos-done-string-start)
1600 (looking-back (concat "^"
1601 (regexp-quote todos-category-done)
1605 (setq prefix (concat (propertize
1606 (if todos-number-priorities
1607 (number-to-string num)
1610 ;; Prefix of top priority items has a
1611 ;; distinct face in Todos mode.
1612 (if (and (not done) (<= num cat-tp)
1613 (eq major-mode 'todos-mode))
1615 'todos-prefix-string))
1617 (let ((ov (todos-get-overlay 'prefix))
1618 (marked (todos-marked-item-p)))
1619 ;; Prefix overlay must be at a single position so its
1620 ;; bounds aren't changed when (re)moving an item.
1621 (unless ov (setq ov (make-overlay (point) (point))))
1622 (overlay-put ov 'todos 'prefix)
1623 (overlay-put ov 'before-string (if marked
1624 (concat todos-item-mark prefix)
1628 ;; ---------------------------------------------------------------------------
1629 ;;; Helper functions for user input with prompting and completion
1631 (defun todos-read-file-name (prompt &optional archive mustmatch)
1632 "Choose and return the name of a Todos file, prompting with PROMPT.
1634 Show completions with TAB or SPC; the names are shown in short
1635 form but the absolute truename is returned. With non-nil ARCHIVE
1636 return the absolute truename of a Todos archive file. With non-nil
1637 MUSTMATCH the name of an existing file must be chosen;
1638 otherwise, a new file name is allowed."
1639 (let* ((completion-ignore-case todos-completion-ignore-case)
1640 (files (mapcar 'todos-short-file-name
1641 (if archive todos-archives todos-files)))
1642 (file (completing-read prompt files nil mustmatch nil nil
1644 ;; Trigger prompt for initial file.
1646 (unless (file-exists-p todos-files-directory)
1647 (make-directory todos-files-directory))
1649 (setq file (todos-validate-name file 'file)))
1650 (setq file (file-truename (concat todos-files-directory file
1651 (if archive ".toda" ".todo"))))))
1653 (defun todos-read-category (prompt &optional match-type file)
1654 "Choose and return a category name, prompting with PROMPT.
1655 Show completions for existing categories with TAB or SPC.
1657 The argument MATCH-TYPE specifies the matching requirements on
1658 the category name: with the value `merge' the name must complete
1659 to that of an existing category; with the value `add' the name
1660 must not be that of an existing category; with all other values
1661 both existing and new valid category names are accepted.
1663 With non-nil argument FILE prompt for a file and complete only
1664 against categories in that file; otherwise complete against all
1665 categories from `todos-category-completions-files'."
1666 ;; Allow SPC to insert spaces, for adding new category names.
1667 (let ((map minibuffer-local-completion-map))
1668 (define-key map " " nil)
1669 (let* ((add (eq match-type 'add))
1670 (file0 (when (and file (> (length todos-files) 1))
1671 (todos-read-file-name "Choose a Todos file: " nil t)))
1672 (completions (unless file0 (todos-category-completions)))
1673 (categories (cond (file0
1674 (with-current-buffer
1675 (find-file-noselect file0 'nowarn)
1676 (let ((todos-current-todos-file file0))
1678 ((and add (not file))
1679 (with-current-buffer
1680 (find-file-noselect todos-current-todos-file)
1684 (completion-ignore-case todos-completion-ignore-case)
1685 (cat (completing-read prompt categories nil
1686 (eq match-type 'merge) nil nil
1687 ;; Unless we're adding a category via
1688 ;; todos-add-category, set default
1689 ;; for existing categories to the
1690 ;; current category of the chosen
1691 ;; file or else of the current file.
1692 (if (and categories (not add))
1693 (with-current-buffer
1696 todos-current-todos-file
1697 (todos-absolute-file-name
1698 todos-default-todos-file)))
1699 (todos-current-category))
1700 ;; Trigger prompt for initial category.
1702 (catfil (cdr (assoc cat completions)))
1703 (str "Category \"%s\" from which file (TAB for choices)? "))
1704 ;; If we do category completion and the chosen category name
1705 ;; occurs in more than one file, prompt to choose one file.
1706 (unless (or file0 add (not catfil))
1707 (setq file0 (file-truename
1710 (todos-absolute-file-name
1711 (completing-read (format str cat)
1712 todos-category-completions-files))))))
1713 ;; Default to the current file.
1714 (unless file0 (setq file0 todos-current-todos-file))
1715 ;; First validate only a name passed interactively from
1716 ;; todos-add-category, which must be of a nonexisting category.
1717 (unless (and (assoc cat categories) (not add))
1718 ;; Validate only against completion categories.
1719 (let ((todos-categories categories))
1720 (setq cat (todos-validate-name cat 'category)))
1721 ;; When user enters a nonexisting category name by jumping or
1722 ;; moving, confirm that it should be added, then validate.
1724 (if (y-or-n-p (format "Add new category \"%s\" to file \"%s\"? "
1725 cat (todos-short-file-name file0)))
1727 (when (assoc cat categories)
1728 (let ((todos-categories categories))
1729 (setq cat (todos-validate-name cat 'category))))
1730 ;; Restore point and narrowing after adding new
1731 ;; category, to avoid moving to beginning of file when
1732 ;; moving marked items to a new category
1733 ;; (todos-move-item).
1736 (todos-add-category file0 cat))))
1737 ;; If we decide not to add a category, exit without returning.
1741 (defun todos-validate-name (name type)
1742 "Prompt for new NAME for TYPE until it is valid, then return it.
1743 TYPE can be either of the symbols `file' or `category'."
1744 (let ((categories todos-categories)
1745 (files (mapcar 'todos-short-file-name todos-files))
1748 (and (cond ((string= "" name)
1750 (cond ((eq type 'file)
1752 "Enter a non-empty file name: "
1753 ;; Empty string passed by todos-show to
1754 ;; prompt for initial Todos file.
1755 (concat "Initial file name ["
1756 todos-initial-file "]: ")))
1757 ((eq type 'category)
1759 "Enter a non-empty category name: "
1760 ;; Empty string passed by todos-show to
1761 ;; prompt for initial category of a new
1763 (concat "Initial category name ["
1764 todos-initial-category "]: "))))))
1765 ((string-match "\\`\\s-+\\'" name)
1767 "Enter a name that does not contain only white space: "))
1768 ((and (eq type 'file) (member name files))
1769 (setq prompt "Enter a non-existing file name: "))
1770 ((and (eq type 'category) (assoc name categories))
1771 (setq prompt "Enter a non-existing category name: ")))
1772 (setq name (if (or (and (eq type 'file) files)
1773 (and (eq type 'category) categories))
1774 (completing-read prompt (cond ((eq type 'file)
1776 ((eq type 'category)
1778 ;; Offer default initial name.
1779 (completing-read prompt (if (eq type 'file)
1782 nil nil (if (eq type 'file)
1784 todos-initial-category))))))
1787 ;; Adapted from calendar-read-date and calendar-date-string.
1788 (defun todos-read-date (&optional arg mo yr)
1789 "Prompt for Gregorian date and return it in the current format.
1791 With non-nil ARG, prompt for and return only the date component
1792 specified by ARG, which can be one of these symbols:
1793 `month' (prompt for name, return name or number according to
1794 value of `calendar-date-display-form'), `day' of month, or
1795 `year'. The value of each of these components can be `*',
1796 indicating an unspecified month, day, or year.
1798 When ARG is `day', non-nil arguments MO and YR determine the
1799 number of the last the day of the month."
1800 (let (year monthname month day
1801 dayname) ; Needed by calendar-date-display-form.
1802 (when (or (not arg) (eq arg 'year))
1803 (while (if (natnump year) (< year 1) (not (eq year '*)))
1804 (setq year (read-from-minibuffer
1805 "Year (>0 or RET for this year or * for any year): "
1806 nil nil t nil (number-to-string
1807 (calendar-extract-year
1808 (calendar-current-date)))))))
1809 (when (or (not arg) (eq arg 'month))
1810 (let* ((marray todos-month-name-array)
1811 (mlist (append marray nil))
1812 (mabarray todos-month-abbrev-array)
1813 (mablist (append mabarray nil))
1814 (completion-ignore-case todos-completion-ignore-case))
1815 (setq monthname (completing-read
1816 "Month name (RET for current month, * for any month): "
1817 ;; (mapcar 'list (append marray nil))
1819 (calendar-month-name (calendar-extract-month
1820 (calendar-current-date)) t))
1821 ;; month (cdr (assoc-string
1822 ;; monthname (calendar-make-alist marray nil nil
1824 month (1+ (- (length mlist)
1825 (length (or (member monthname mlist)
1826 (member monthname mablist))))))
1827 (setq monthname (aref mabarray (1- month)))))
1828 (when (or (not arg) (eq arg 'day))
1829 (let ((last (let ((mm (or month mo))
1831 ;; If month is unspecified, use a month with 31
1832 ;; days for checking day of month input. Does
1833 ;; Calendar do anything special when * is
1834 ;; currently a shorter month?
1835 (if (= mm 13) (setq mm 1))
1836 ;; If year is unspecified, use a leap year to
1838 (if (eq year '*) (setq yy 2012))
1839 (calendar-last-day-of-month mm yy))))
1840 (while (if (natnump day) (or (< day 1) (> day last)) (not (eq day '*)))
1841 (setq day (read-from-minibuffer
1842 (format "Day (1-%d or RET for today or * for any day): "
1844 nil nil t nil (number-to-string
1845 (calendar-extract-day
1846 (calendar-current-date))))))))
1847 ;; Stringify read values (monthname is already a string).
1848 (and year (setq year (if (eq year '*)
1850 (number-to-string year))))
1851 (and day (setq day (if (eq day '*)
1853 (number-to-string day))))
1854 (and month (setq month (if (eq month '*)
1856 (number-to-string month))))
1858 (cond ((eq arg 'year) year)
1861 (if (memq 'month calendar-date-display-form)
1864 (mapconcat 'eval calendar-date-display-form ""))))
1866 (defun todos-read-dayname ()
1867 "Choose name of a day of the week with completion and return it."
1868 (let ((completion-ignore-case todos-completion-ignore-case))
1869 (completing-read "Enter a day name: "
1870 (append calendar-day-name-array nil)
1873 (defun todos-read-time ()
1874 "Prompt for and return a valid clock time as a string.
1876 Valid time strings are those matching `diary-time-regexp'.
1877 Typing `<return>' at the prompt returns the current time, if the
1878 user option `todos-always-add-time-string' is non-nil, otherwise
1879 the empty string (i.e., no time string)."
1882 (setq answer (read-string "Enter a clock time: " nil nil
1883 (when todos-always-add-time-string
1884 (substring (current-time-string) 11 16))))
1885 (when (or (string= "" answer)
1886 (string-match diary-time-regexp answer))
1890 ;; ---------------------------------------------------------------------------
1891 ;;; Item filtering infrastructure
1893 (defvar todos-multiple-filter-files nil
1894 "List of files selected from `todos-multiple-filter-files' widget.")
1896 (defvar todos-multiple-filter-files-widget nil
1897 "Variable holding widget created by `todos-multiple-filter-files'.")
1899 (defun todos-multiple-filter-files ()
1900 "Pop to a buffer with a widget for choosing multiple filter files."
1903 (require 'wid-edit))
1904 (with-current-buffer (get-buffer-create "*Todos Filter Files*")
1905 (pop-to-buffer (current-buffer))
1907 (kill-all-local-variables)
1908 (widget-insert "Select files for generating the top priorities list.\n\n")
1909 (setq todos-multiple-filter-files-widget
1911 `(set ,@(mapcar (lambda (x) (list 'const x))
1912 (mapcar 'todos-short-file-name
1913 (funcall todos-files-function))))))
1914 (widget-insert "\n")
1915 (widget-create 'push-button
1916 :notify (lambda (widget &rest ignore)
1917 (setq todos-multiple-filter-files 'quit)
1919 (exit-recursive-edit))
1922 (widget-create 'push-button
1923 :notify (lambda (&rest ignore)
1924 (setq todos-multiple-filter-files
1927 (concat todos-files-directory
1930 todos-multiple-filter-files-widget)))
1932 (exit-recursive-edit))
1934 (use-local-map widget-keymap)
1936 (message "Click \"Apply\" after selecting files.")
1939 (defun todos-filter-items (filter file-list)
1940 "Display a list of items from FILE-LIST that satisfy FILTER.
1941 The values of FILE-LIST and FILTER are passed from the calling
1942 commands. The files in FILE-LIST are either the current Todos
1943 file or those listed in `todos-filter-files' or chosen
1944 interactively. The values of FILTER can be `top' for top
1945 priority items, a cons of `top' and a number passed by the
1946 caller, `diary' for diary items, or `regexp' for items matching a
1947 regular expresion entered by the user."
1948 (let ((num (if (consp filter) (cdr filter) todos-show-priorities))
1949 (buf (get-buffer-create todos-filtered-items-buffer))
1950 (multifile (> (length file-list) 1))
1951 regexp fname bufstr cat beg end done)
1952 (if (null file-list)
1953 (error "No files have been chosen for filtering")
1954 (with-current-buffer buf
1956 (kill-all-local-variables)
1957 (todos-filtered-items-mode))
1958 (when (eq filter 'regexp)
1959 (setq regexp (read-string "Enter a regular expression: ")))
1960 (save-current-buffer
1961 (dolist (f file-list)
1962 ;; Before inserting file contents into temp buffer, save a modified
1963 ;; buffer visiting it.
1964 (let ((bf (find-buffer-visiting f)))
1965 (when (buffer-modified-p bf)
1966 (with-current-buffer bf (save-buffer))))
1967 (setq fname (todos-short-file-name f))
1969 (when (and todos-filter-done-items (eq filter 'regexp))
1970 ;; If there is a corresponding archive file for the Todos file,
1971 ;; insert it first and add identifiers for todos-jump-to-item.
1972 (let ((arch (concat (file-name-sans-extension f) ".toda")))
1973 (when (file-exists-p arch)
1974 (insert-file-contents arch)
1975 ;; Delete Todos archive file categories sexp.
1976 (delete-region (line-beginning-position)
1977 (1+ (line-end-position)))
1980 (when (re-search-forward
1981 (concat (if todos-filter-done-items
1982 (concat "\\(?:" todos-done-string-start
1983 "\\|" todos-date-string-start
1985 todos-date-string-start)
1986 todos-date-pattern "\\(?: "
1987 diary-time-regexp "\\)?"
1988 (if todos-filter-done-items
1990 (regexp-quote todos-nondiary-end)) "?")
1992 (insert "(archive) "))
1994 (insert-file-contents f)
1995 ;; Delete Todos file categories sexp.
1996 (delete-region (line-beginning-position) (1+ (line-end-position)))
1998 ;; Unless the number of top priorities to show was
1999 ;; passed by the caller, the file-wide value from
2000 ;; `todos-priorities-rules', if non-nil, overrides
2001 ;; `todos-show-priorities'.
2002 (unless (consp filter)
2003 (setq fnum (or (nth 1 (assoc f todos-priorities-rules))
2004 todos-show-priorities)))
2005 (while (re-search-forward
2006 (concat "^" (regexp-quote todos-category-beg) "\\(.+\\)\n")
2008 (setq cat (match-string 1))
2010 ;; Unless the number of top priorities to show was
2011 ;; passed by the caller, the category-wide value
2012 ;; from `todos-priorities-rules', if non-nil,
2013 ;; overrides a non-nil file-wide value from
2014 ;; `todos-priorities-rules' as well as
2015 ;; `todos-show-priorities'.
2016 (unless (consp filter)
2017 (let ((cats (nth 2 (assoc f todos-priorities-rules))))
2018 (setq cnum (or (cdr (assoc cat cats)) fnum))))
2019 (delete-region (match-beginning 0) (match-end 0))
2020 (setq beg (point)) ; First item in the current category.
2021 (setq end (if (re-search-forward
2022 (concat "^" (regexp-quote todos-category-beg))
2028 (if (re-search-forward
2029 (concat "\n" (regexp-quote todos-category-done))
2033 (unless (and todos-filter-done-items (eq filter 'regexp))
2034 ;; Leave done items.
2035 (delete-region done end)
2037 (narrow-to-region beg end) ; Process only current category.
2038 (goto-char (point-min))
2039 ;; Apply the filter.
2040 (cond ((eq filter 'diary)
2042 (if (looking-at (regexp-quote todos-nondiary-start))
2044 (todos-forward-item))))
2045 ((eq filter 'regexp)
2047 (if (looking-at todos-item-start)
2048 (if (string-match regexp (todos-item-string))
2049 (todos-forward-item)
2050 (todos-remove-item))
2051 ;; Kill lines that aren't part of a todo or done
2052 ;; item (empty or todos-category-done).
2053 (delete-region (line-beginning-position)
2054 (1+ (line-end-position))))
2055 ;; If last todo item in file matches regexp and
2056 ;; there are no following done items,
2057 ;; todos-category-done string is left dangling,
2058 ;; because todos-forward-item jumps over it.
2061 (concat (regexp-quote todos-done-string)
2063 (delete-region (point) (progn
2066 (t ; Filter top priority items.
2067 (setq num (or cnum fnum num))
2069 (todos-forward-item num))))
2071 ;; Delete non-top-priority items.
2072 (unless (member filter '(diary regexp))
2073 (delete-region beg end))
2074 (goto-char (point-min))
2075 ;; Add file (if using multiple files) and category tags to
2078 (when (re-search-forward
2079 (concat (if todos-filter-done-items
2080 (concat "\\(?:" todos-done-string-start
2081 "\\|" todos-date-string-start
2083 todos-date-string-start)
2084 todos-date-pattern "\\(?: " diary-time-regexp
2085 "\\)?" (if todos-filter-done-items
2087 (regexp-quote todos-nondiary-end))
2091 (when (looking-at "(archive) ") (goto-char (match-end 0)))
2092 (insert (if multifile (concat fname ":") "") cat "]"))
2095 (setq bufstr (buffer-string))
2096 (with-current-buffer buf
2097 (let (buffer-read-only)
2098 (insert bufstr)))))))
2099 (set-window-buffer (selected-window) (set-buffer buf))
2100 (todos-prefix-overlays)
2101 (goto-char (point-min)))))
2103 (defun todos-set-top-priorities (&optional arg)
2104 "Set number of top priorities shown by `todos-top-priorities'.
2105 With non-nil ARG, set the number only for the current Todos
2106 category; otherwise, set the number for all categories in the
2109 Calling this function via either of the commands
2110 `todos-set-top-priorities-in-file' or
2111 `todos-set-top-priorities-in-category' is the recommended way to
2112 set the user customizable option `todos-priorities-rules'."
2113 (let* ((cat (todos-current-category))
2114 (file todos-current-todos-file)
2115 (rules todos-priorities-rules)
2116 (frule (assoc-string file rules))
2117 (crule (assoc-string cat (nth 2 frule)))
2118 (crules (nth 2 frule))
2119 (cur (or (if arg (cdr crule) (nth 1 frule))
2120 todos-show-priorities))
2121 (prompt (if arg (concat "Number of top priorities in this category"
2122 " (currently %d): ")
2123 (concat "Default number of top priorities per category"
2124 " in this file (currently %d): ")))
2129 (setq new (read-number (format prompt cur0))
2130 prompt "Enter a non-negative number: "
2133 (append (delete crule crules) (list (cons cat new)))
2134 (append (list file new) (list crules))))
2135 (setq rules (cons (if arg
2136 (list file cur nrule)
2138 (delete frule rules)))
2139 (customize-save-variable 'todos-priorities-rules rules)
2140 (todos-prefix-overlays)))
2142 (defun todos-filtered-buffer-name (buffer-type file-list)
2143 "Rename Todos filtered buffer using BUFFER-TYPE and FILE-LIST.
2145 The new name is constructed from the string BUFFER-TYPE, which
2146 refers to one of the top priorities, diary or regexp item
2147 filters, and the names of the filtered files in FILE-LIST. Used
2148 in Todos Filter Items mode."
2149 (let* ((multi (> (length file-list) 1))
2150 (fnames (mapconcat (lambda (f) (todos-short-file-name f))
2152 (rename-buffer (format (concat "%s for file" (if multi "s" "")
2153 " \"%s\"") buffer-type fnames))))
2155 (defun todos-find-item (str)
2156 "Search for saved top priority item STR in its Todos file.
2157 Return the list (FOUND FILE CAT), where CAT and FILE are the
2158 item's category and file, and FOUND is a cons cell if the search
2159 succeeds, whose car is the start of the item in FILE and whose
2160 cdr is `done' if the item is now a done item, `changed' if its
2161 priority has changed or its text was truncated or augmented, and
2163 (string-match (concat (if todos-filter-done-items
2164 (concat "\\(?:" todos-done-string-start "\\|"
2165 todos-date-string-start "\\)")
2166 todos-date-string-start)
2167 todos-date-pattern "\\(?: " diary-time-regexp "\\)?"
2168 (if todos-filter-done-items
2170 (regexp-quote todos-nondiary-end)) "?"
2171 "\\(?4: \\[\\(?3:(archive) \\)?\\(?2:.*:\\)?"
2172 "\\(?1:.*\\)\\]\\).*$") str)
2173 (let ((cat (match-string 1 str))
2174 (file (match-string 2 str))
2175 (archive (string= (match-string 3 str) "(archive) "))
2176 (filcat (match-string 4 str))
2179 (setq str (replace-match "" nil nil str 4))
2181 (while (search-backward filcat nil t)
2182 (setq tpriority (1+ tpriority))))
2184 (concat todos-files-directory (substring file 0 -1)
2185 (if archive ".toda" ".todo"))
2187 (concat (file-name-sans-extension
2188 todos-global-current-todos-file) ".toda")
2189 todos-global-current-todos-file)))
2190 (find-file-noselect file)
2191 (with-current-buffer (find-buffer-visiting file)
2193 (goto-char (point-min))
2194 (let ((beg (re-search-forward
2195 (concat "^" (regexp-quote (concat todos-category-beg cat)) "$")
2197 (done (save-excursion
2199 (concat "^" (regexp-quote todos-category-done)) nil t)))
2200 (end (save-excursion
2201 (or (re-search-forward
2202 (concat "^" (regexp-quote todos-category-beg))
2205 (setq found (when (search-forward str end t)
2206 (goto-char (match-beginning 0))))
2209 (cons found (if (> (point) done)
2211 (let ((cpriority 1))
2213 ;; Not top item in category.
2214 (while (> (point) (1+ beg))
2215 (let ((opoint (point)))
2216 (todos-backward-item)
2217 ;; Can't move backward beyond
2218 ;; first item in file.
2219 (unless (= (point) opoint)
2220 (setq cpriority (1+ cpriority))))))
2221 (if (and (= tpriority cpriority)
2222 ;; Proper substring is not the same.
2223 (string= (todos-item-string)
2227 (list found file cat)))
2229 (defun todos-check-top-priorities ()
2230 "Return a message saying whether top priorities file is up to date."
2234 (let* ((item (todos-item-string))
2235 (found (car (todos-find-item item))))
2236 (unless (eq (cdr found) 'same)
2238 (overlay-put (make-overlay (todos-item-start) (todos-item-end))
2239 'face 'todos-search))
2240 (setq count (1+ count))))
2241 ;; (throw 'old (message "The marked item is not up to date.")))
2242 (todos-forward-item))
2244 (message "Top priorities file is up to date.")
2245 (message (concat "The highlighted item" (if (= count 1) " is " "s are ")
2247 ;; "\nType <return> on item for details."
2250 (defun todos-top-priorities-filename ()
2252 (let ((bufname (buffer-name)))
2253 (string-match "\"\\([^\"]+\\)\"" bufname)
2254 (let* ((filename-str (substring bufname (match-beginning 1) (match-end 1)))
2255 (filename-base (replace-regexp-in-string ", " "-" filename-str)))
2256 (concat todos-files-directory filename-base ".todt"))))
2258 (defun todos-save-top-priorities-buffer ()
2260 (let ((filename (todos-top-priorities-filename)))
2261 (if (file-exists-p filename)
2263 (write-region nil nil filename nil t nil t))))
2265 ;; ---------------------------------------------------------------------------
2266 ;;; Sorting and display routines for Todos Categories mode.
2268 (defun todos-longest-category-name-length (categories)
2269 "Return the length of the longest name in list CATEGORIES."
2271 (dolist (c categories longest)
2272 (setq longest (max longest (length c))))))
2274 (defun todos-adjusted-category-label-length ()
2275 "Return adjusted length of category label button.
2276 The adjustment ensures proper tabular alignment in Todos
2278 (let* ((categories (mapcar 'car todos-categories))
2279 (longest (todos-longest-category-name-length categories))
2280 (catlablen (length todos-categories-category-label))
2281 (lc-diff (- longest catlablen)))
2282 (if (and (natnump lc-diff)
2283 (eq (logand lc-diff 1) 1)) ; oddp from cl.el
2285 (max longest catlablen))))
2287 (defun todos-padded-string (str)
2288 "Return category name or label string STR padded with spaces.
2289 The placement of the padding is determined by the value of user
2290 option `todos-categories-align'."
2291 (let* ((len (todos-adjusted-category-label-length))
2292 (strlen (length str))
2293 (strlen-odd (eq (logand strlen 1) 1))
2294 (padding (max 0 (/ (- len strlen) 2)))
2295 (padding-left (cond ((eq todos-categories-align 'left) 0)
2296 ((eq todos-categories-align 'center) padding)
2297 ((eq todos-categories-align 'right)
2298 (if strlen-odd (1+ (* padding 2)) (* padding 2)))))
2299 (padding-right (cond ((eq todos-categories-align 'left)
2300 (if strlen-odd (1+ (* padding 2)) (* padding 2)))
2301 ((eq todos-categories-align 'center)
2302 (if strlen-odd (1+ padding) padding))
2303 ((eq todos-categories-align 'right) 0))))
2304 (concat (make-string padding-left 32) str (make-string padding-right 32))))
2306 (defvar todos-descending-counts nil
2307 "List of keys for category counts sorted in descending order.")
2309 (defun todos-sort (list &optional key)
2310 "Return a copy of LIST, possibly sorted according to KEY."
2311 (let* ((l (copy-sequence list))
2312 (fn (if (eq key 'alpha)
2313 (lambda (x) (upcase x)) ; Alphabetize case insensitively.
2314 (lambda (x) (todos-get-count key x))))
2315 ;; Keep track of whether the last sort by key was descending or
2317 (descending (member key todos-descending-counts))
2318 (cmp (if (eq key 'alpha)
2320 (if descending '< '>)))
2321 (pred (lambda (s1 s2) (let ((t1 (funcall fn (car s1)))
2322 (t2 (funcall fn (car s2))))
2323 (funcall cmp t1 t2)))))
2325 (setq l (sort l pred))
2326 ;; Switch between descending and ascending sort order.
2328 (setq todos-descending-counts
2329 (delete key todos-descending-counts))
2330 (push key todos-descending-counts)))
2333 (defun todos-display-sorted (type)
2334 "Keep point on the TYPE count sorting button just clicked."
2335 (let ((opoint (point)))
2336 (todos-update-categories-display type)
2337 (goto-char opoint)))
2339 (defun todos-label-to-key (label)
2340 "Return symbol for sort key associated with LABEL."
2342 (cond ((string= label todos-categories-category-label)
2344 ((string= label todos-categories-todo-label)
2346 ((string= label todos-categories-diary-label)
2348 ((string= label todos-categories-done-label)
2350 ((string= label todos-categories-archived-label)
2351 (setq key 'archived)))
2354 (defun todos-insert-sort-button (label)
2355 "Insert button for displaying categories sorted by item counts.
2356 LABEL determines which type of count is sorted."
2357 (setq str (if (string= label todos-categories-category-label)
2358 (todos-padded-string label)
2361 (setq end (+ beg (length str)))
2362 (insert-button str 'face nil
2365 (let ((key (todos-label-to-key ,label)))
2366 (if (and (member key todos-descending-counts)
2369 ;; If display is alphabetical, switch back to
2370 ;; category priority order.
2371 (todos-display-sorted nil)
2372 (setq todos-descending-counts
2373 (delete key todos-descending-counts)))
2374 (todos-display-sorted key)))))
2375 (setq ovl (make-overlay beg end))
2376 (overlay-put ovl 'face 'todos-button))
2378 (defun todos-total-item-counts ()
2379 "Return a list of total item counts for the current file."
2380 (mapcar (lambda (i) (apply '+ (mapcar (lambda (l) (aref l i))
2381 (mapcar 'cdr todos-categories))))
2384 (defvar todos-categories-category-number 0
2385 "Variable for numbering categories in Todos Categories mode.")
2387 (defun todos-insert-category-line (cat &optional nonum)
2388 "Insert button with category CAT's name and item counts.
2389 With non-nil argument NONUM show only these; otherwise, insert a
2390 number in front of the button indicating the category's priority.
2391 The number and the category name are separated by the string
2392 which is the value of the user option
2393 `todos-categories-number-separator'."
2394 (let ((archive (member todos-current-todos-file todos-archives))
2395 (num todos-categories-category-number)
2396 (str (todos-padded-string cat))
2398 (setq num (1+ num) todos-categories-category-number num)
2401 (make-string (+ 4 (length todos-categories-number-separator))
2403 (format " %3d%s" num todos-categories-number-separator))
2405 (mapconcat (lambda (elt)
2407 (make-string (1+ (/ (length (car elt)) 2)) 32) ; label
2408 (format "%3d" (todos-get-count (cdr elt) cat)) ; count
2409 ;; Add an extra space if label length is odd
2410 ;; (using def of oddp from cl.el).
2411 (if (eq (logand (length (car elt)) 1) 1) " ")))
2413 (list (cons todos-categories-done-label 'done))
2414 (list (cons todos-categories-todo-label 'todo)
2415 (cons todos-categories-diary-label 'diary)
2416 (cons todos-categories-done-label 'done)
2417 (cons todos-categories-archived-label
2420 " ") ; So highlighting of last column is consistent with the others.
2421 'face (if (and todos-skip-archived-categories
2422 (zerop (todos-get-count 'todo cat))
2423 (zerop (todos-get-count 'done cat))
2424 (not (zerop (todos-get-count 'archived cat))))
2425 'todos-archived-only
2427 'action `(lambda (button) (let ((buf (current-buffer)))
2428 (todos-jump-to-category nil ,cat)
2429 (kill-buffer buf))))
2430 ;; Highlight the sorted count column.
2431 (let* ((beg (+ opoint 7 (length str)))
2433 (cond ((eq nonum 'todo)
2434 (setq beg (+ beg 1 (/ (length todos-categories-todo-label) 2))))
2436 (setq beg (+ beg 1 (length todos-categories-todo-label)
2437 2 (/ (length todos-categories-diary-label) 2))))
2439 (setq beg (+ beg 1 (length todos-categories-todo-label)
2440 2 (length todos-categories-diary-label)
2441 2 (/ (length todos-categories-done-label) 2))))
2442 ((eq nonum 'archived)
2443 (setq beg (+ beg 1 (length todos-categories-todo-label)
2444 2 (length todos-categories-diary-label)
2445 2 (length todos-categories-done-label)
2446 2 (/ (length todos-categories-archived-label) 2)))))
2447 (unless (= beg (+ opoint 7 (length str))) ; Don't highlight categories.
2448 (setq end (+ beg 4))
2449 (setq ovl (make-overlay beg end))
2450 (overlay-put ovl 'face 'todos-sorted-column)))
2453 (defun todos-display-categories-1 ()
2454 "Prepare buffer for displaying table of categories and item counts."
2455 (unless (eq major-mode 'todos-categories-mode)
2456 (setq todos-global-current-todos-file
2457 (or todos-current-todos-file
2458 (todos-absolute-file-name todos-default-todos-file)))
2459 (set-window-buffer (selected-window)
2460 (set-buffer (get-buffer-create todos-categories-buffer)))
2461 (kill-all-local-variables)
2462 (todos-categories-mode)
2463 (let ((archive (member todos-current-todos-file todos-archives))
2466 (insert (format (concat "Category counts for Todos "
2467 (if archive "archive" "file")
2469 (todos-short-file-name todos-current-todos-file)))
2471 ;; Make space for the column of category numbers.
2472 (insert (make-string (+ 4 (length todos-categories-number-separator)) 32))
2473 ;; Add the category and item count buttons (if this is the list of
2474 ;; categories in an archive, show only done item counts).
2475 (todos-insert-sort-button todos-categories-category-label)
2478 (insert (make-string 3 32))
2479 (todos-insert-sort-button todos-categories-done-label))
2480 (insert (make-string 3 32))
2481 (todos-insert-sort-button todos-categories-todo-label)
2482 (insert (make-string 2 32))
2483 (todos-insert-sort-button todos-categories-diary-label)
2484 (insert (make-string 2 32))
2485 (todos-insert-sort-button todos-categories-done-label)
2486 (insert (make-string 2 32))
2487 (todos-insert-sort-button todos-categories-archived-label))
2490 (defun todos-update-categories-display (sortkey)
2492 (let* ((cats0 todos-categories)
2493 (cats (todos-sort cats0 sortkey))
2494 (archive (member todos-current-todos-file todos-archives))
2495 (todos-categories-category-number 0)
2496 ;; Find start of Category button if we just entered Todos Categories
2498 (pt (if (eq (point) (point-max))
2501 (goto-char (next-single-char-property-change
2502 (point) 'face nil (line-end-position))))))
2505 (delete-region (point) (point-max))
2506 ;; Fill in the table with buttonized lines, each showing a category and
2508 (mapc (lambda (cat) (todos-insert-category-line cat sortkey))
2511 ;; Add a line showing item count totals.
2512 (insert (make-string (+ 4 (length todos-categories-number-separator)) 32)
2513 (todos-padded-string todos-categories-totals-label)
2517 (make-string (1+ (/ (length (car elt)) 2)) 32)
2518 (format "%3d" (nth (cdr elt) (todos-total-item-counts)))
2519 ;; Add an extra space if label length is odd (using
2520 ;; definition of oddp from cl.el).
2521 (if (eq (logand (length (car elt)) 1) 1) " ")))
2523 (list (cons todos-categories-done-label 2))
2524 (list (cons todos-categories-todo-label 0)
2525 (cons todos-categories-diary-label 1)
2526 (cons todos-categories-done-label 2)
2527 (cons todos-categories-archived-label 3)))
2529 ;; Put cursor on Category button initially.
2530 (if pt (goto-char pt))
2531 (setq buffer-read-only t)))
2533 ;; ---------------------------------------------------------------------------
2534 ;;; Routines for generating Todos insertion commands and key bindings
2536 ;; Can either of these be included in Emacs? The originals are GFDL'd.
2538 ;; Slightly reformulated from
2539 ;; http://rosettacode.org/wiki/Power_set#Common_Lisp.
2540 (defun powerset-recursive (l)
2544 (let ((prev (powerset-recursive (cdr l))))
2545 (append (mapcar (lambda (elt) (cons (car l) elt))
2549 ;; Elisp implementation of http://rosettacode.org/wiki/Power_set#C
2550 (defun powerset-bitwise (l)
2551 (let ((binnum (lsh 1 (length l)))
2556 (while (not (zerop bits))
2557 (let ((arg (pop ll)))
2558 (unless (zerop (logand bits 1))
2559 (setq elt (append elt (list arg))))
2560 (setq bits (lsh bits -1))))
2561 (setq pset (append pset (list elt)))
2565 ;; (defalias 'todos-powerset 'powerset-recursive)
2566 (defalias 'todos-powerset 'powerset-bitwise)
2568 ;; Return list of lists of non-nil atoms produced from ARGLIST. The elements
2569 ;; of ARGLIST may be atoms or lists.
2570 (defun todos-gen-arglists (arglist)
2573 (let ((arg (pop arglist)))
2574 (cond ((symbolp arg)
2575 (setq arglists (if arglists
2576 (mapcar (lambda (l) (push arg l)) arglists)
2577 (list (push arg arglists)))))
2581 (if (= 1 (length arglists))
2582 (apply (lambda (l) (push a l)) arglists)
2583 (mapcar (lambda (l) (push a l)) arglists)))
2585 (setq arglists (mapcar 'reverse (apply 'append (mapc 'car arglists))))))
2587 (defvar todos-insertion-commands-args-genlist
2588 '(diary nonmarking (calendar date dayname) time (here region))
2589 "Generator list for argument lists of Todos insertion commands.")
2591 (defvar todos-insertion-commands-args
2592 (let ((argslist (todos-gen-arglists todos-insertion-commands-args-genlist))
2594 (setq res (remove-duplicates
2595 (apply 'append (mapcar 'todos-powerset argslist)) :test 'equal))
2597 (unless (= 5 (length l))
2598 (let ((v (make-vector 5 nil)) elt)
2601 (cond ((eq elt 'diary)
2603 ((eq elt 'nonmarking)
2605 ((or (eq elt 'calendar)
2614 (setq l (append v nil))))
2615 (setq new (append new (list l))))
2617 "List of all argument lists for Todos insertion commands.")
2619 (defun todos-insertion-command-name (arglist)
2620 "Generate Todos insertion command name from ARGLIST."
2621 (replace-regexp-in-string
2623 (replace-regexp-in-string
2625 (concat "todos-item-insert-"
2626 (mapconcat (lambda (e) (if e (symbol-name e))) arglist "-")))))
2628 (defvar todos-insertion-commands-names
2630 (todos-insertion-command-name l))
2631 todos-insertion-commands-args)
2632 "List of names of Todos insertion commands.")
2634 (defmacro todos-define-insertion-command (&rest args)
2635 (let ((name (intern (todos-insertion-command-name args)))
2640 (arg4 (nth 4 args)))
2641 `(defun ,name (&optional arg &rest args)
2642 "Todos item insertion command generated from ARGS."
2643 (interactive (list current-prefix-arg))
2644 (todos-insert-item arg ',arg0 ',arg1 ',arg2 ',arg3 ',arg4))))
2646 (defvar todos-insertion-commands
2648 (eval `(todos-define-insertion-command ,@c)))
2649 todos-insertion-commands-args)
2650 "List of Todos insertion commands.")
2652 (defvar todos-insertion-commands-arg-key-list
2653 '(("diary" "y" "yy")
2654 ("nonmarking" "k" "kk")
2655 ("calendar" "c" "cc")
2657 ("dayname" "n" "nn")
2663 (defun todos-insertion-key-bindings (map)
2665 (dolist (c todos-insertion-commands)
2667 (cname (symbol-name c)))
2669 (let ((arg (nth 0 l))
2672 (if (string-match (concat (regexp-quote arg) "\\_>") cname)
2673 (setq key (concat key key2)))
2674 (if (string-match (concat (regexp-quote arg) ".+") cname)
2675 (setq key (concat key key1)))))
2676 todos-insertion-commands-arg-key-list)
2677 (if (string-match (concat (regexp-quote "todos-item-insert") "\\_>") cname)
2678 (setq key (concat key "i")))
2679 (define-key map key c))))
2681 (defvar todos-insertion-map
2682 (let ((map (make-keymap)))
2683 (todos-insertion-key-bindings map)
2684 (define-key map "p" 'todos-copy-item)
2686 "Keymap for Todos mode insertion commands.")
2688 ;; ---------------------------------------------------------------------------
2689 ;;; Key maps and menus
2691 (defvar todos-key-bindings
2694 ("Cd" . todos-display-categories) ;FIXME: Fc todos-file-categories?
2695 ("H" . todos-highlight-item)
2696 ("N" . todos-hide-show-item-numbering)
2697 ("D" . todos-hide-show-date-time)
2698 ("*" . todos-mark-unmark-item)
2699 ("C*" . todos-mark-category)
2700 ("Cu" . todos-unmark-category)
2701 ("PP" . todos-print)
2702 ("PF" . todos-print-to-file)
2703 ("v" . todos-hide-show-done-items)
2704 ("V" . todos-show-done-only)
2705 ("As" . todos-show-archive)
2706 ("Ac" . todos-choose-archive)
2707 ;; ("Y" . todos-diary-items)
2708 ("Fe" . todos-edit-multiline)
2709 ("Fh" . todos-highlight-item)
2710 ("Fn" . todos-hide-show-item-numbering)
2711 ("Fd" . todos-hide-show-date-time)
2712 ("Ftt" . todos-top-priorities)
2713 ("Ftm" . todos-top-priorities-multifile)
2714 ("Fts" . todos-set-top-priorities-in-file)
2715 ("Cts" . todos-set-top-priorities-in-category)
2716 ("Fyy" . todos-diary-items)
2717 ("Fym" . todos-diary-items-multifile)
2718 ("Fxx" . todos-regexp-items)
2719 ("Fxm" . todos-regexp-items-multifile)
2721 ("f" . todos-forward-category)
2722 ("b" . todos-backward-category)
2723 ("j" . todos-jump-to-category)
2724 ("n" . todos-forward-item)
2725 ("p" . todos-backward-item)
2726 ("S" . todos-search)
2727 ("X" . todos-clear-matches)
2729 ("Fa" . todos-add-file)
2730 ("Ca" . todos-add-category)
2731 ("Cr" . todos-rename-category)
2732 ("Cg" . todos-merge-category)
2733 ("Cm" . todos-move-category)
2734 ("Ck" . todos-delete-category)
2735 ("d" . todos-item-done)
2736 ("ee" . todos-edit-item)
2737 ("em" . todos-edit-multiline-item)
2738 ("eh" . todos-edit-item-header)
2739 ("edc" . todos-edit-item-date-from-calendar)
2740 ("edt" . todos-edit-item-date-to-today)
2741 ("edn" . todos-edit-item-date-day-name)
2742 ("edy" . todos-edit-item-date-year)
2743 ("edm" . todos-edit-item-date-month)
2744 ("edd" . todos-edit-item-date-day)
2745 ("et" . todos-edit-item-time)
2746 ("eyy" . todos-edit-item-diary-inclusion)
2747 ;; ("" . todos-edit-category-diary-inclusion)
2748 ("eyn" . todos-edit-item-diary-nonmarking)
2749 ;;("" . todos-edit-category-diary-nonmarking)
2750 ("ec" . todos-done-item-add-edit-or-delete-comment)
2751 ("i" . ,todos-insertion-map)
2752 ("k" . todos-delete-item) ;FIXME: not single letter?
2753 ("m" . todos-move-item)
2754 ("r" . todos-raise-item-priority)
2755 ("l" . todos-lower-item-priority)
2756 ("#" . todos-set-item-priority)
2757 ("u" . todos-item-undo)
2758 ("Ad" . todos-archive-done-item) ;FIXME: ad
2759 ("AD" . todos-archive-category-done-items) ;FIXME: aD or C-u ad ?
2762 ([remap newline] . newline-and-indent)
2764 "Alist pairing keys defined in Todos modes and their bindings.")
2766 (defvar todos-mode-map
2767 (let ((map (make-keymap)))
2768 ;; Don't suppress digit keys, so they can supply prefix arguments.
2769 (suppress-keymap map)
2770 (dolist (ck todos-key-bindings)
2771 (define-key map (car ck) (cdr ck)))
2773 "Todos mode keymap.")
2776 todos-menu todos-mode-map "Todos Menu"
2779 ["Next Item" todos-forward-item t]
2780 ["Previous Item" todos-backward-item t]
2782 ["Next Category" todos-forward-category t]
2783 ["Previous Category" todos-backward-category t]
2784 ["Jump to Category" todos-jump-to-category t]
2786 ["Search Todos File" todos-search t]
2787 ["Clear Highlighting on Search Matches" todos-category-done t])
2789 ["List Current Categories" todos-display-categories t]
2790 ;; ["List Categories Alphabetically" todos-display-categories-alphabetically t]
2791 ["Turn Item Highlighting on/off" todos-highlight-item t]
2792 ["Turn Item Numbering on/off" todos-hide-show-item-numbering t]
2793 ["Turn Item Time Stamp on/off" todos-hide-show-date-time t]
2794 ["View/Hide Done Items" todos-hide-show-done-items t]
2796 ["View Diary Items" todos-diary-items t]
2797 ["View Top Priority Items" todos-top-priorities t]
2798 ["View Multifile Top Priority Items" todos-top-priorities-multifile t]
2800 ["Print Category" todos-print t])
2802 ["Insert New Item" todos-insert-item t]
2803 ["Insert Item Here" todos-insert-item-here t]
2804 ("More Insertion Commands")
2805 ["Edit Item" todos-edit-item t]
2806 ["Edit Multiline Item" todos-edit-multiline t]
2807 ["Edit Item Header" todos-edit-item-header t]
2808 ["Edit Item Date" todos-edit-item-date t]
2809 ["Edit Item Time" todos-edit-item-time t]
2811 ["Lower Item Priority" todos-lower-item-priority t]
2812 ["Raise Item Priority" todos-raise-item-priority t]
2813 ["Set Item Priority" todos-set-item-priority t]
2814 ["Move (Recategorize) Item" todos-move-item t]
2815 ["Delete Item" todos-delete-item t]
2816 ["Undo Done Item" todos-item-undo t]
2817 ["Mark/Unmark Item for Diary" todos-toggle-item-diary-inclusion t]
2818 ["Mark/Unmark Items for Diary" todos-edit-item-diary-inclusion t]
2819 ["Mark & Hide Done Item" todos-item-done t]
2820 ["Archive Done Items" todos-archive-category-done-items t]
2822 ["Add New Todos File" todos-add-file t]
2823 ["Add New Category" todos-add-category t]
2824 ["Delete Current Category" todos-delete-category t]
2825 ["Rename Current Category" todos-rename-category t]
2827 ["Save Todos File" todos-save t]
2830 ["Quit" todos-quit t]
2833 (defvar todos-archive-mode-map
2834 (let ((map (make-sparse-keymap)))
2835 (suppress-keymap map t)
2836 ;; navigation commands
2837 (define-key map "f" 'todos-forward-category)
2838 (define-key map "b" 'todos-backward-category)
2839 (define-key map "j" 'todos-jump-to-category)
2840 (define-key map "n" 'todos-forward-item)
2841 (define-key map "p" 'todos-backward-item)
2843 (define-key map "C" 'todos-display-categories)
2844 (define-key map "H" 'todos-highlight-item)
2845 (define-key map "N" 'todos-hide-show-item-numbering)
2846 ;; (define-key map "" 'todos-hide-show-date-time)
2847 (define-key map "P" 'todos-print)
2848 (define-key map "q" 'todos-quit)
2849 (define-key map "s" 'todos-save)
2850 (define-key map "S" 'todos-search)
2851 (define-key map "t" 'todos-show)
2852 (define-key map "u" 'todos-unarchive-items)
2853 (define-key map "U" 'todos-unarchive-category)
2855 "Todos Archive mode keymap.")
2857 (defvar todos-edit-mode-map
2858 (let ((map (make-sparse-keymap)))
2859 (define-key map "\C-x\C-q" 'todos-edit-quit)
2860 (define-key map [remap newline] 'newline-and-indent)
2862 "Todos Edit mode keymap.")
2864 (defvar todos-categories-mode-map
2865 (let ((map (make-sparse-keymap)))
2866 (suppress-keymap map t)
2867 (define-key map "c" 'todos-display-categories-alphabetically-or-by-priority)
2868 (define-key map "t" 'todos-display-categories-sorted-by-todo)
2869 (define-key map "y" 'todos-display-categories-sorted-by-diary)
2870 (define-key map "d" 'todos-display-categories-sorted-by-done)
2871 (define-key map "a" 'todos-display-categories-sorted-by-archived)
2872 (define-key map "l" 'todos-lower-category-priority)
2873 (define-key map "+" 'todos-lower-category-priority)
2874 (define-key map "r" 'todos-raise-category-priority)
2875 (define-key map "-" 'todos-raise-category-priority)
2876 (define-key map "n" 'todos-forward-button)
2877 (define-key map "p" 'todos-backward-button)
2878 (define-key map [tab] 'todos-forward-button)
2879 (define-key map [backtab] 'todos-backward-button)
2880 (define-key map "q" 'todos-quit)
2881 ;; (define-key map "A" 'todos-add-category)
2882 ;; (define-key map "D" 'todos-delete-category)
2883 ;; (define-key map "R" 'todos-rename-category)
2885 "Todos Categories mode keymap.")
2887 (defvar todos-filtered-items-mode-map
2888 (let ((map (make-keymap)))
2889 (suppress-keymap map t)
2890 ;; navigation commands
2891 (define-key map "j" 'todos-jump-to-item)
2892 (define-key map [remap newline] 'todos-jump-to-item)
2893 (define-key map "n" 'todos-forward-item)
2894 (define-key map "p" 'todos-backward-item)
2895 (define-key map "H" 'todos-highlight-item)
2896 (define-key map "N" 'todos-hide-show-item-numbering)
2897 (define-key map "D" 'todos-hide-show-date-time)
2898 (define-key map "P" 'todos-print)
2899 (define-key map "q" 'todos-quit)
2900 (define-key map "s" 'todos-save)
2902 (define-key map "l" 'todos-lower-item-priority)
2903 (define-key map "r" 'todos-raise-item-priority)
2904 (define-key map "#" 'todos-set-item-priority)
2906 "Todos Top Priorities mode keymap.")
2908 ;; ---------------------------------------------------------------------------
2909 ;;; Mode definitions
2911 (defun todos-modes-set-1 ()
2913 (set (make-local-variable 'font-lock-defaults) '(todos-font-lock-keywords t))
2914 (set (make-local-variable 'indent-line-function) 'todos-indent)
2915 (when todos-wrap-lines (funcall todos-line-wrapping-function)))
2917 (defun todos-modes-set-2 ()
2919 (add-to-invisibility-spec 'todos)
2920 (setq buffer-read-only t)
2921 (set (make-local-variable 'hl-line-range-function)
2922 (lambda() (when (todos-item-end)
2923 (cons (todos-item-start) (todos-item-end))))))
2925 (defun todos-modes-set-3 ()
2927 (set (make-local-variable 'todos-categories) (todos-set-categories))
2928 (set (make-local-variable 'todos-category-number) 1)
2929 (add-hook 'find-file-hook 'todos-display-as-todos-file nil t))
2931 (put 'todos-mode 'mode-class 'special)
2933 (define-derived-mode todos-mode special-mode "Todos"
2934 "Major mode for displaying, navigating and editing Todo lists.
2937 (easy-menu-add todos-menu)
2941 ;; Initialize todos-current-todos-file.
2942 (when (member (file-truename (buffer-file-name))
2943 (funcall todos-files-function))
2944 (set (make-local-variable 'todos-current-todos-file)
2945 (file-truename (buffer-file-name))))
2946 (set (make-local-variable 'todos-show-done-only) nil)
2947 (set (make-local-variable 'todos-categories-with-marks) nil)
2948 (add-hook 'find-file-hook 'todos-add-to-buffer-list nil t)
2949 (add-hook 'post-command-hook 'todos-update-buffer-list nil t)
2950 (when todos-show-current-file
2951 (add-hook 'pre-command-hook 'todos-show-current-file nil t))
2952 (add-hook 'window-configuration-change-hook
2953 'todos-reset-and-enable-done-separator nil t)
2954 (add-hook 'kill-buffer-hook 'todos-reset-global-current-todos-file nil t))
2956 (put 'todos-archive-mode 'mode-class 'special)
2958 ;; If todos-mode is parent, all todos-mode key bindings appear to be
2959 ;; available in todos-archive-mode (e.g. shown by C-h m).
2960 (define-derived-mode todos-archive-mode special-mode "Todos-Arch"
2961 "Major mode for archived Todos categories.
2963 \\{todos-archive-mode-map}"
2967 (set (make-local-variable 'todos-current-todos-file)
2968 (file-truename (buffer-file-name)))
2969 (set (make-local-variable 'todos-show-done-only) t))
2971 (defun todos-mode-external-set ()
2973 (set (make-local-variable 'todos-current-todos-file)
2974 todos-global-current-todos-file)
2975 (let ((cats (with-current-buffer
2976 ;; Can't use find-buffer-visiting when
2977 ;; `todos-display-categories' is called on first
2978 ;; invocation of `todos-show', since there is then
2979 ;; no buffer visiting the current file.
2980 (find-file-noselect todos-current-todos-file 'nowarn)
2981 (or todos-categories
2982 ;; In Todos Edit mode todos-categories is now nil
2983 ;; since it uses same buffer as Todos mode but
2984 ;; doesn't have the latter's local variables.
2986 (goto-char (point-min))
2987 (read (buffer-substring-no-properties
2988 (line-beginning-position)
2989 (line-end-position))))))))
2990 (set (make-local-variable 'todos-categories) cats)))
2992 (define-derived-mode todos-edit-mode text-mode "Todos-Ed"
2993 "Major mode for editing multiline Todo items.
2995 \\{todos-edit-mode-map}"
2997 (todos-mode-external-set)
2998 (setq buffer-read-only nil))
3000 (put 'todos-categories-mode 'mode-class 'special)
3002 (define-derived-mode todos-categories-mode special-mode "Todos-Cats"
3003 "Major mode for displaying and editing Todos categories.
3005 \\{todos-categories-mode-map}"
3006 (todos-mode-external-set))
3008 (put 'todos-filtered-items-mode 'mode-class 'special)
3010 (define-derived-mode todos-filtered-items-mode special-mode "Todos-Fltr"
3011 "Mode for displaying and reprioritizing top priority Todos.
3013 \\{todos-filtered-items-mode-map}"
3015 (todos-modes-set-2))
3017 ;; ---------------------------------------------------------------------------
3020 ;; ---------------------------------------------------------------------------
3021 ;;; Entering and Exiting
3024 (defun todos-show (&optional solicit-file)
3025 "Visit a Todos file and display one of its categories.
3026 With non-nil prefix argument SOLICIT-FILE prompt for which todo
3027 file to visit; otherwise visit `todos-default-todos-file'.
3028 Subsequent invocations from outside of Todos mode revisit this
3029 file or, with option `todos-show-current-file' non-nil (the
3030 default), whichever Todos file was last visited.
3032 Calling this command before any Todos file exists prompts for a
3033 file name and an initial category (defaulting to
3034 `todos-initial-file' and `todos-initial-category'), creates both
3035 of these, visits the file and displays the category.
3037 The first invocation of this command on an existing Todos file
3038 interacts with the option `todos-show-first': if `table', show
3039 the table of categories in the file; if `top', show the
3040 corresponding top priorities file, if any; if `first' (the
3041 default value), show the first category in the file. Subsequent
3042 invocations always show the file's current (i.e., last displayed)
3045 In Todos mode just the category's unfinished todo items are shown
3046 by default. The done items are hidden, but typing
3047 `\\[todos-hide-show-done-items]' displays them below the todo
3048 items. With non-nil user option `todos-show-with-done' both todo
3049 and done items are always shown on visiting a category.
3051 Invoking this command in Todos Archive mode visits the
3052 corresponding Todos file, displaying the corresponding category."
3055 (show-first todos-show-first)
3056 (file (cond (solicit-file
3057 (if (funcall todos-files-function)
3058 (todos-read-file-name "Choose a Todos file to visit: "
3060 (error "There are no Todos files")))
3061 ((and (eq major-mode 'todos-archive-mode)
3062 ;; Called noninteractively via todos-quit from
3063 ;; Todos Categories mode to return to archive file.
3064 (called-interactively-p 'any))
3065 (setq cat (todos-current-category))
3066 (concat (file-name-sans-extension todos-current-todos-file)
3069 (or todos-current-todos-file
3070 (and todos-show-current-file
3071 todos-global-current-todos-file)
3072 (todos-absolute-file-name todos-default-todos-file)
3073 (todos-add-file))))))
3074 (unless (member file todos-visited)
3075 ;; Can't setq t-c-t-f here, otherwise wrong file shown when
3076 ;; called again from todos-display-categories.
3077 (let ((todos-current-todos-file file))
3078 (cond ((eq todos-show-first 'table)
3079 (todos-display-categories))
3080 ((eq todos-show-first 'top)
3081 (let* ((shortf (todos-short-file-name file))
3082 (tp-file (todos-absolute-file-name shortf 'top)))
3083 (if (file-exists-p tp-file)
3086 (set-buffer (find-file-noselect tp-file 'nowarn)))
3087 (message "There is no top priorities file for %s" shortf)
3088 (setq todos-show-first 'first)))))))
3089 (when (or (member file todos-visited)
3090 (eq todos-show-first 'first))
3091 (set-window-buffer (selected-window)
3092 (set-buffer (find-file-noselect file 'nowarn)))
3093 ;; If called from archive file, show corresponding
3094 ;; category in Todos file, if it exists.
3095 (when (assoc cat todos-categories)
3096 (setq todos-category-number (todos-category-number cat)))
3097 ;; If this is a new Todos file, add its first category.
3098 (when (zerop (buffer-size))
3099 (setq todos-category-number
3100 (todos-add-category todos-current-todos-file "")))
3101 (save-excursion (todos-category-select)))
3102 (setq todos-show-first show-first)
3103 (add-to-list 'todos-visited file)))
3105 (defun todos-display-categories ()
3106 "Display a table of the current file's categories and item counts.
3108 In the initial display the categories are numbered, indicating
3109 their current order for navigating by \\[todos-forward-category]
3110 and \\[todos-backward-category]. You can persistantly change the
3111 order of the category at point by typing
3112 \\[todos-raise-category-priority] or
3113 \\[todos-lower-category-priority].
3115 The labels above the category names and item counts are buttons,
3116 and clicking these changes the display: sorted by category name
3117 or by the respective item counts (alternately descending or
3118 ascending). In these displays the categories are not numbered
3119 and \\[todos-raise-category-priority] and
3120 \\[todos-lower-category-priority] are
3121 disabled. (Programmatically, the sorting is triggered by passing
3122 a non-nil SORTKEY argument.)
3124 In addition, the lines with the category names and item counts
3125 are buttonized, and pressing one of these button jumps to the
3126 category in Todos mode (or Todos Archive mode, for categories
3127 containing only archived items, provided user option
3128 `todos-skip-archived-categories' is non-nil. These categories
3129 are shown in `todos-archived-only' face."
3131 (todos-display-categories-1)
3133 (todos-update-categories-display sortkey)))
3135 (defun todos-display-categories-alphabetically-or-by-priority ()
3139 (goto-char (point-min))
3141 (if (member 'alpha todos-descending-counts)
3143 (todos-update-categories-display nil)
3144 (setq todos-descending-counts
3145 (delete 'alpha todos-descending-counts)))
3146 (todos-update-categories-display 'alpha))))
3148 (defun todos-display-categories-sorted-by-todo ()
3152 (goto-char (point-min))
3154 (todos-update-categories-display 'todo)))
3156 (defun todos-display-categories-sorted-by-diary ()
3160 (goto-char (point-min))
3162 (todos-update-categories-display 'diary)))
3164 (defun todos-display-categories-sorted-by-done ()
3168 (goto-char (point-min))
3170 (todos-update-categories-display 'done)))
3172 (defun todos-display-categories-sorted-by-archived ()
3176 (goto-char (point-min))
3178 (todos-update-categories-display 'archived)))
3180 (defun todos-show-archive (&optional ask)
3181 "Visit the archive of the current Todos category, if it exists.
3182 If the category has no archived items, prompt to visit the
3183 archive anyway. If there is no archive for this file or with
3184 non-nil argument ASK, prompt to visit another archive.
3186 The buffer showing the archive is in Todos Archive mode. The
3187 first visit in a session displays the first category in the
3188 archive, subsequent visits return to the last category
3191 (let* ((cat (todos-current-category))
3192 (count (todos-get-count 'archived cat))
3193 (archive (concat (file-name-sans-extension todos-current-todos-file)
3196 (setq place (cond (ask 'other-archive)
3197 ((file-exists-p archive) 'this-archive)
3198 (t (when (y-or-n-p (concat "This file has no archive; "
3199 "visit another archive? "))
3201 (when (eq place 'other-archive)
3202 (setq archive (todos-read-file-name "Choose a Todos archive: " t t)))
3203 (when (and (eq place 'this-archive) (zerop count))
3204 (setq place (when (y-or-n-p
3205 (concat "This category has no archived items;"
3206 " visit archive anyway? "))
3209 (set-window-buffer (selected-window)
3210 (set-buffer (find-file-noselect archive)))
3211 (if (member place '(other-archive other-cat))
3212 (setq todos-category-number 1)
3213 (todos-category-number cat))
3214 (todos-category-select))))
3216 (defun todos-choose-archive ()
3217 "Choose an archive and visit it."
3219 (todos-show-archive t))
3221 (defun todos-save ()
3222 "Save the current Todos file."
3224 (cond ((eq major-mode 'todos-filtered-items-mode)
3225 (todos-check-top-priorities)
3226 (todos-save-top-priorities-buffer))
3230 (defun todos-quit ()
3231 "Exit the current Todos-related buffer.
3232 Depending on the specific mode, this either kills the buffer or
3233 buries it and restores state as needed."
3235 (cond ((eq major-mode 'todos-categories-mode)
3236 ;; Postpone killing buffer till after calling todos-show, to
3237 ;; prevent killing todos-mode buffer.
3238 (let ((buf (current-buffer)))
3239 (setq todos-descending-counts nil)
3240 ;; Ensure todos-show calls todos-display-categories only on
3241 ;; first invocation per file.
3242 (when (eq todos-show-first 'table)
3243 (add-to-list 'todos-visited todos-current-todos-file))
3246 ((eq major-mode 'todos-filtered-items-mode)
3249 ((member major-mode (list 'todos-mode 'todos-archive-mode))
3250 ;; Have to write previously nonexistant archives to file, and might
3251 ;; as well save Todos file also.
3255 (defun todos-print (&optional to-file)
3256 "Produce a printable version of the current Todos buffer.
3257 This converts overlays and soft line wrapping and, depending on
3258 the value of `todos-print-function', includes faces. With
3259 non-nil argument TO-FILE write the printable version to a file;
3260 otherwise, send it to the default printer."
3262 (let ((buf todos-print-buffer)
3264 ((eq major-mode 'todos-mode)
3265 (concat "Todos File: "
3266 (todos-short-file-name todos-current-todos-file)
3267 "\nCategory: " (todos-current-category)))
3268 ((eq major-mode 'todos-filtered-items-mode)
3269 "Todos Top Priorities")))
3270 (prefix (propertize (concat todos-prefix " ")
3271 'face 'todos-prefix-string))
3273 (fill-prefix (make-string todos-indent-to-here 32))
3274 (content (buffer-string))
3276 (with-current-buffer (get-buffer-create buf)
3278 (goto-char (point-min))
3281 (end (save-excursion (todos-item-end))))
3282 (when todos-number-priorities
3284 (setq prefix (propertize (concat (number-to-string num) " ")
3285 'face 'todos-prefix-string)))
3287 (fill-region beg end))
3288 ;; Calling todos-forward-item infloops at todos-item-start due to
3289 ;; non-overlay prefix, so search for item start instead.
3290 (if (re-search-forward todos-item-start nil t)
3292 (goto-char (point-max))))
3293 (if (re-search-backward (concat "^" (regexp-quote todos-category-done))
3295 (replace-match todos-done-separator))
3296 (goto-char (point-min))
3300 (let ((file (read-file-name "Print to file: ")))
3301 (funcall todos-print-function file))
3302 (funcall todos-print-function)))
3305 (defun todos-print-to-file ()
3306 "Save printable version of this Todos buffer to a file."
3310 (defun todos-convert-legacy-files ()
3311 "Convert legacy Todo files to the current Todos format.
3312 The files `todo-file-do' and `todo-file-done' are converted and
3313 saved (the latter as a Todos Archive file) with a new name in
3314 `todos-files-directory'. See also the documentation string of
3315 `todos-todo-mode-date-time-regexp' for further details."
3317 (if (fboundp 'todo-mode)
3318 (require 'todo-mode)
3319 (error "Void function `todo-mode'"))
3320 ;; Convert `todo-file-do'.
3321 (if (file-exists-p todo-file-do)
3322 (let ((default "todo-do-conv")
3325 (insert-file-contents todo-file-do)
3326 (let ((end (search-forward ")" (line-end-position) t))
3327 (beg (search-backward "(" (line-beginning-position) t)))
3328 (setq todo-categories
3329 (read (buffer-substring-no-properties beg end))))
3331 (delete-region (line-beginning-position) (1+ (line-end-position)))
3334 ((looking-at (regexp-quote (concat todo-prefix todo-category-beg)))
3335 (replace-match todos-category-beg))
3336 ((looking-at (regexp-quote todo-category-end))
3338 ((looking-at (regexp-quote (concat todo-prefix " "
3339 todo-category-sep)))
3340 (replace-match todos-category-done))
3341 ((looking-at (concat (regexp-quote todo-prefix) " "
3342 todos-todo-mode-date-time-regexp " "
3343 (regexp-quote todo-initials) ":"))
3344 (todos-convert-legacy-date-time)))
3346 (setq file (concat todos-files-directory
3348 (format "Save file as (default \"%s\"): " default)
3351 (write-region (point-min) (point-max) file nil 'nomessage nil t))
3353 (insert-file-contents file)
3354 (let ((todos-categories (todos-make-categories-list t)))
3355 (todos-update-categories-sexp))
3356 (write-region (point-min) (point-max) file nil 'nomessage))
3357 ;; Convert `todo-file-done'.
3358 (when (file-exists-p todo-file-done)
3360 (insert-file-contents todo-file-done)
3361 (let ((beg (make-marker))
3363 cat cats comment item)
3365 (when (looking-at todos-todo-mode-date-time-regexp)
3366 (set-marker beg (point))
3367 (todos-convert-legacy-date-time)
3368 (set-marker end (point))
3370 (insert "[" todos-done-string)
3374 (when (looking-at todos-todo-mode-date-time-regexp)
3375 (todos-convert-legacy-date-time))
3376 (when (looking-at (concat " " (regexp-quote todo-initials) ":"))
3377 (replace-match "")))
3378 (if (re-search-forward
3379 (concat "^" todos-todo-mode-date-time-regexp) nil t)
3380 (goto-char (match-beginning 0))
3381 (goto-char (point-max)))
3383 (when (looking-back "\\[\\([^][]+\\)\\]")
3384 (setq cat (match-string 1))
3385 (goto-char (match-beginning 0))
3387 ;; If the item ends with a non-comment parenthesis not
3388 ;; followed by a period, we lose (but we inherit that problem
3389 ;; from todo-mode.el).
3390 (when (looking-back "(\\(.*\\)) ")
3391 (setq comment (match-string 1))
3393 (insert "[" todos-comment-string ": " comment "]"))
3394 (set-marker end (point))
3395 (if (member cat cats)
3396 ;; If item is already in its category, leave it there.
3397 (unless (save-excursion
3399 (concat "^" (regexp-quote todos-category-beg)
3401 (string= (match-string 1) cat))
3402 ;; Else move it to its category.
3403 (setq item (buffer-substring-no-properties beg end))
3404 (delete-region beg (1+ end))
3405 (set-marker beg (point))
3407 (concat "^" (regexp-quote (concat todos-category-beg cat))
3411 (if (re-search-forward
3412 (concat "^" (regexp-quote todos-category-beg)
3414 (progn (goto-char (match-beginning 0))
3417 (goto-char (point-max)))
3422 (insert todos-category-beg cat "\n\n" todos-category-done "\n"))
3424 (set-marker beg nil)
3425 (set-marker end nil))
3426 (setq file (concat (file-name-sans-extension file) ".toda"))
3427 (write-region (point-min) (point-max) file nil 'nomessage nil t))
3429 (insert-file-contents file)
3430 (let ((todos-categories (todos-make-categories-list t)))
3431 (todos-update-categories-sexp))
3432 (write-region (point-min) (point-max) file nil 'nomessage)
3433 (setq archive-sexp (read (buffer-substring-no-properties
3434 (line-beginning-position)
3435 (line-end-position)))))
3436 (setq file (concat (file-name-sans-extension file) ".todo"))
3437 ;; Update categories sexp of converted Todos file again, adding
3438 ;; counts of archived items.
3440 (insert-file-contents file)
3441 (let ((sexp (read (buffer-substring-no-properties
3442 (line-beginning-position)
3443 (line-end-position)))))
3445 (let ((archive-cat (assoc (car cat) archive-sexp)))
3447 (aset (cdr cat) 3 (aref (cdr archive-cat) 2)))))
3448 (delete-region (line-beginning-position) (line-end-position))
3449 (prin1 sexp (current-buffer)))
3450 (write-region (point-min) (point-max) file nil 'nomessage)))
3451 (todos-reevaluate-filelist-defcustoms)
3452 (message "Format conversion done."))
3453 (error "No legacy Todo file exists")))
3455 ;; ---------------------------------------------------------------------------
3456 ;;; Navigation Commands
3458 (defun todos-forward-category (&optional back)
3459 "Visit the numerically next category in this Todos file.
3460 If the current category is the highest numbered, visit the first
3461 category. With non-nil argument BACK, visit the numerically
3462 previous category (the highest numbered one, if the current
3463 category is the first)."
3465 (setq todos-category-number
3466 (1+ (mod (- todos-category-number (if back 2 0))
3467 (length todos-categories))))
3468 (when todos-skip-archived-categories
3469 (while (and (zerop (todos-get-count 'todo))
3470 (zerop (todos-get-count 'done))
3471 (not (zerop (todos-get-count 'archived))))
3472 (setq todos-category-number
3473 (apply (if back '1- '1+) (list todos-category-number)))))
3474 (todos-category-select)
3475 (goto-char (point-min)))
3477 (defun todos-backward-category ()
3478 "Visit the numerically previous category in this Todos file.
3479 If the current category is the highest numbered, visit the first
3482 (todos-forward-category t))
3485 (defun todos-jump-to-category (&optional file cat)
3486 "Prompt for a category in a Todos file and jump to it.
3488 With prefix argument FILE, prompt for a specific Todos file and
3489 choose (with TAB completion) a category in it to jump to;
3490 otherwise, choose and jump to any category in either the current
3491 Todos file or a file in `todos-category-completions-files'.
3493 You can also enter a non-existing category name, triggering a
3494 prompt whether to add a new category by that name; on
3495 confirmation it is added and jumped to.
3497 Noninteractively, jump directly to the category named by argument
3498 CAT; this is used in Todos Categories mode."
3500 ;; If invoked outside of Todos mode and there is not yet any Todos
3501 ;; file, initialize one.
3502 (if (null todos-files)
3504 (let ((file0 (when cat ; We're in Todos Categories mode.
3505 ;; With non-nil `todos-skip-archived-categories'
3506 ;; jump to archive file of a category with only
3508 (if (and todos-skip-archived-categories
3509 (zerop (todos-get-count 'todo cat))
3510 (zerop (todos-get-count 'done cat))
3511 (not (zerop (todos-get-count 'archived cat))))
3512 (concat (file-name-sans-extension
3513 todos-current-todos-file) ".toda")
3514 ;; Otherwise, jump to current todos file.
3515 todos-current-todos-file)))
3516 (cat+file (unless cat
3517 (todos-read-category "Jump to category: " nil file))))
3518 (setq category (or cat (car cat+file)))
3519 (unless cat (setq file0 (cdr cat+file)))
3520 (with-current-buffer (find-file-noselect file0 'nowarn)
3521 (setq todos-current-todos-file file0)
3522 ;; If called from Todos Categories mode, clean up before jumping.
3523 (if (string= (buffer-name) todos-categories-buffer)
3525 (set-window-buffer (selected-window)
3526 (set-buffer (find-buffer-visiting file0)))
3527 (unless todos-global-current-todos-file
3528 (setq todos-global-current-todos-file todos-current-todos-file))
3529 (todos-category-number category)
3530 (todos-category-select)
3531 (goto-char (point-min))))))
3533 (defun todos-jump-to-item ()
3534 "Jump to the file and category of the filtered item at point."
3536 (let* ((str (todos-item-string))
3537 (buf (current-buffer))
3538 (res (todos-find-item str))
3543 (message "Category %s does not contain this item." cat)
3545 (set-window-buffer (selected-window)
3546 (set-buffer (find-buffer-visiting file)))
3547 (setq todos-current-todos-file file)
3548 (setq todos-category-number (todos-category-number cat))
3549 (let ((todos-show-with-done (if (or todos-filter-done-items
3550 (eq (cdr found) 'done))
3552 todos-show-with-done)))
3553 (todos-category-select))
3554 (goto-char (car found)))))
3556 (defun todos-forward-item (&optional count)
3557 "Move point down to start of item with next lower priority.
3558 With positive numerical prefix COUNT, move point COUNT items
3561 If the category's done items are hidden, this command also moves
3562 point to the empty line below the last todo item from any higher
3563 item in the category, i.e., when invoked with or without a prefix
3564 argument. If the category's done items are visible, this command
3565 called with a prefix argument only moves point to a lower item,
3566 e.g., with point on the last todo item and called with prefix 1,
3567 it moves point to the first done item; but if called with point
3568 on the last todo item without a prefix argument, it moves point
3569 the the empty line above the done items separator."
3571 ;; It's not worth the trouble to allow prefix arg value < 1, since we have
3572 ;; the corresponding command.
3573 (if (and count (> 1 count))
3574 (error "This command only accepts a positive numerical prefix argument")
3575 (let* ((not-done (not (or (todos-done-item-p) (looking-at "^$"))))
3576 (start (line-end-position)))
3578 (if (re-search-forward todos-item-start nil t (or count 1))
3579 (goto-char (match-beginning 0))
3580 (goto-char (point-max)))
3581 ;; If points advances by one from a todo to a done item, go back to the
3582 ;; space above todos-done-separator, since that is a legitimate place to
3583 ;; insert an item. But skip this space if count > 1, since that should
3584 ;; only stop on an item.
3585 (when (and not-done (todos-done-item-p) (not count))
3586 ;; (if (or (not count) (= count 1))
3587 (re-search-backward "^$" start t)))));)
3588 ;; FIXME: The preceding sexp is insufficient when buffer is not narrowed,
3589 ;; since there could be no done items in this category, so the search puts
3590 ;; us on first todo item of next category. Does this ever happen? If so:
3591 ;; (let ((opoint) (point))
3592 ;; (forward-line -1)
3593 ;; (when (or (not count) (= count 1))
3594 ;; (cond ((looking-at (concat "^" (regexp-quote todos-category-beg)))
3595 ;; (forward-line -2))
3596 ;; ((looking-at (concat "^" (regexp-quote todos-category-done)))
3597 ;; (forward-line -1))
3599 ;; (goto-char opoint)))))))
3601 (defun todos-backward-item (&optional count)
3602 "Move point up to start of item with next higher priority.
3603 With positive numerical prefix COUNT, move point COUNT items
3606 If the category's done items are visible, this command called
3607 with a prefix argument only moves point to a higher item, e.g.,
3608 with point on the first done item and called with prefix 1, it
3609 moves to the last todo item; but if called with point on the
3610 first done item without a prefix argument, it moves point the the
3611 empty line above the done items separator."
3613 ;; Avoid moving to bob if on the first item but not at bob.
3614 (when (> (line-number-at-pos) 1)
3615 ;; It's not worth the trouble to allow prefix arg value < 1, since we have
3616 ;; the corresponding command.
3617 (if (and count (> 1 count))
3618 (error "This command only accepts a positive numerical prefix argument")
3619 (let* ((done (todos-done-item-p)))
3622 (re-search-backward todos-item-start nil t (or count 1)))
3623 ;; Unless this is a regexp filtered items buffer (which can contain
3624 ;; intermixed todo and done items), if points advances by one from a
3625 ;; done to a todo item, go back to the space above
3626 ;; todos-done-separator, since that is a legitimate place to insert an
3627 ;; item. But skip this space if count > 1, since that should only
3629 (when (and done (not (todos-done-item-p)) (not count)
3630 ;(or (not count) (= count 1))
3631 (not (equal (buffer-name) todos-regexp-items-buffer)))
3632 (re-search-forward (concat "^" (regexp-quote todos-category-done))
3634 (forward-line -1))))))
3636 (defun todos-forward-button (n &optional wrap display-message)
3638 (interactive "p\nd\nd")
3639 (forward-button n wrap display-message)
3640 (and (bolp) (button-at (point))
3641 ;; Align with beginning of category label.
3642 (forward-char (+ 4 (length todos-categories-number-separator)))))
3644 (defun todos-backward-button (n &optional wrap display-message)
3646 (interactive "p\nd\nd")
3647 (backward-button n wrap display-message)
3648 (and (bolp) (button-at (point))
3649 ;; Align with beginning of category label.
3650 (forward-char (+ 4 (length todos-categories-number-separator)))))
3652 (defun todos-search ()
3653 "Search for a regular expression in this Todos file.
3654 The search runs through the whole file and encompasses all and
3655 only todo and done items; it excludes category names. Multiple
3656 matches are shown sequentially, highlighted in `todos-search'
3659 (let ((regex (read-from-minibuffer "Enter a search string (regexp): "))
3661 matches match cat in-done ov mlen msg)
3663 (goto-char (point-min))
3665 (setq match (re-search-forward regex nil t))
3666 (goto-char (line-beginning-position))
3667 (unless (or (equal (point) 1)
3668 (looking-at (concat "^" (regexp-quote todos-category-beg))))
3669 (if match (push match matches)))
3671 (setq matches (reverse matches))
3675 (setq match (pop matches))
3678 (when (looking-at todos-done-string-start)
3680 (re-search-backward (concat "^" (regexp-quote todos-category-beg)
3681 "\\(.*\\)\n") nil t)
3682 (setq cat (match-string-no-properties 1))
3683 (todos-category-number cat)
3684 (todos-category-select)
3686 (unless todos-show-with-done (todos-hide-show-done-items)))
3688 (setq ov (make-overlay (- (point) (length regex)) (point)))
3689 (overlay-put ov 'face 'todos-search)
3691 (setq mlen (length matches))
3694 (format "There are %d more matches; go to next match? "
3696 "There is one more match; go to it? "))
3698 (throw 'stop (setq msg (if (> mlen 1)
3699 (format "There are %d more matches."
3701 "There is one more match."))))))
3702 (setq msg "There are no more matches."))
3703 (todos-category-select)
3705 (message "No match for \"%s\"" regex))
3707 (if (y-or-n-p (concat msg "\nUnhighlight matches? "))
3708 (todos-clear-matches)
3709 (message "You can unhighlight the matches later by typing %s"
3710 (key-description (car (where-is-internal
3711 'todos-clear-matches))))))))
3713 (defun todos-clear-matches ()
3714 "Remove highlighting on matches found by todos-search."
3716 (remove-overlays 1 (1+ (buffer-size)) 'face 'todos-search))
3718 ;; ---------------------------------------------------------------------------
3719 ;;; Display Commands
3721 (defun todos-hide-show-item-numbering ()
3724 (todos-reset-prefix 'todos-number-priorities (not todos-number-priorities)))
3726 (defun todos-hide-show-done-items ()
3727 "Show hidden or hide visible done items in current category."
3729 (if (zerop (todos-get-count 'done (todos-current-category)))
3730 (message "There are no done items in this category.")
3731 (let ((opoint (point)))
3732 (goto-char (point-min))
3733 (let* ((shown (re-search-forward todos-done-string-start nil t))
3734 (todos-show-with-done (not shown)))
3735 (todos-category-select)
3737 ;; If start of done items sections is below the bottom of the
3738 ;; window, make it visible.
3741 (goto-char (point-min))
3742 (re-search-forward todos-done-string-start nil t)))
3743 (if (not (pos-visible-in-window-p shown))
3745 (goto-char opoint)))))))
3747 (defun todos-show-done-only ()
3748 "Switch between displaying only done or only todo items."
3750 (setq todos-show-done-only (not todos-show-done-only))
3751 (todos-category-select))
3753 (defun todos-highlight-item ()
3754 "Highlight or unhighlight the todo item the cursor is on."
3761 (defun todos-hide-show-date-time ()
3762 "Hide or show date-time header of todo items in the current file."
3766 (goto-char (point-min))
3767 (if (todos-get-overlay 'header)
3768 (remove-overlays 1 (1+ (buffer-size)) 'todos 'header)
3770 (goto-char (point-min))
3772 (when (re-search-forward
3773 (concat todos-date-string-start todos-date-pattern
3774 "\\( " diary-time-regexp "\\)?"
3775 (regexp-quote todos-nondiary-end) "? ")
3777 (unless (save-match-data (todos-done-item-p))
3778 (setq ov (make-overlay (match-beginning 0) (match-end 0) nil t))
3779 (overlay-put ov 'todos 'header)
3780 (overlay-put ov 'display "")))
3781 (todos-forward-item))))))
3783 (defun todos-mark-unmark-item (&optional n)
3784 "Mark item with `todos-item-mark' if unmarked, otherwise unmark it.
3785 With a positive numerical prefix argument N, change the
3786 marking of the next N items."
3788 (unless (> n 1) (setq n 1))
3790 (let* ((cat (todos-current-category))
3791 (marks (assoc cat todos-categories-with-marks))
3792 (ov (todos-get-overlay 'prefix))
3793 (pref (overlay-get ov 'before-string)))
3794 (if (todos-marked-item-p)
3796 (overlay-put ov 'before-string (substring pref 1))
3797 (if (= (cdr marks) 1) ; Deleted last mark in this category.
3798 (setq todos-categories-with-marks
3799 (assq-delete-all cat todos-categories-with-marks))
3800 (setcdr marks (1- (cdr marks)))))
3801 (overlay-put ov 'before-string (concat todos-item-mark pref))
3803 (setcdr marks (1+ (cdr marks)))
3804 (push (cons cat 1) todos-categories-with-marks))))
3805 (todos-forward-item)))
3807 (defun todos-mark-category ()
3808 "Mark all visiblw items in this category with `todos-item-mark'."
3811 (goto-char (point-min))
3813 (let* ((cat (todos-current-category))
3814 (marks (assoc cat todos-categories-with-marks))
3815 (ov (todos-get-overlay 'prefix))
3816 (pref (overlay-get ov 'before-string)))
3817 (unless (todos-marked-item-p)
3818 (overlay-put ov 'before-string (concat todos-item-mark pref))
3820 (setcdr marks (1+ (cdr marks)))
3821 (push (cons cat 1) todos-categories-with-marks))))
3822 (todos-forward-item))))
3824 (defun todos-unmark-category ()
3825 "Remove `todos-item-mark' from all visible items in this category."
3828 (goto-char (point-min))
3830 (let* ((cat (todos-current-category))
3831 (marks (assoc cat todos-categories-with-marks))
3832 (ov (todos-get-overlay 'prefix))
3833 (pref (overlay-get ov 'before-string)))
3834 (when (todos-marked-item-p)
3835 (overlay-put ov 'before-string (substring pref 1))
3836 (setq todos-categories-with-marks
3837 (delq (assoc (todos-current-category)
3838 todos-categories-with-marks)
3839 todos-categories-with-marks))))
3840 (todos-forward-item))))
3842 ;; ---------------------------------------------------------------------------
3843 ;;; Item filtering commands
3845 (defun todos-set-top-priorities-in-file ()
3846 "Set number of top priorities for this file.
3847 See `todos-set-top-priorities' for more details."
3849 (todos-set-top-priorities))
3851 (defun todos-set-top-priorities-in-category ()
3852 "Set number of top priorities for this category.
3853 See `todos-set-top-priorities' for more details."
3855 (todos-set-top-priorities t))
3857 (defun todos-top-priorities (&optional arg multifile)
3858 "Display a list of top priority items from different categories.
3859 The categories are either a subset of those in the current Todos
3860 file, or else, with non-nil argument MULTIFILE, a subset of the
3861 categories in the files listed in `todos-filter-files', or if
3862 this nil, in the files chosen from a file selection dialog that
3863 pops up in this case.
3865 With numerical prefix ARG show at most ARG top priority items
3866 from each category. With `C-u' as prefix argument show the
3867 numbers of top priority items specified by category in
3868 `todos-priorities-rules', if this has an entry for the file(s);
3869 otherwise show `todos-show-priorities' items per category in the
3870 file(s). With no prefix argument, if a top priorities file for
3871 the current Todos file has previously been saved (see
3872 `todos-save-top-priorities-buffer'), visit this file; if there is
3873 no such file, build the list as with prefix argument `C-u'.
3875 The prefix ARG regulates how many top priorities from
3876 each category to show, as described above."
3878 (let* ((flist (if multifile
3879 (or todos-filter-files
3880 (progn (todos-multiple-filter-files)
3881 todos-multiple-filter-files))
3882 (list todos-current-todos-file)))
3883 (tp-file (if (equal flist 'quit)
3884 ;; Pressed `cancel' in file selection dialog.
3886 (concat todos-files-directory
3887 (mapconcat 'identity
3888 (mapcar 'todos-short-file-name flist)
3891 (tp-file-exists (file-exists-p tp-file))
3892 (buf todos-top-priorities-buffer))
3893 (cond ((and arg (natnump arg))
3894 (todos-filter-items (cons 'top arg) flist))
3895 ((and (not arg) tp-file-exists)
3897 (todos-prefix-overlays)
3898 (todos-check-top-priorities))
3900 (todos-filter-items 'top flist)))
3901 (unless tp-file-exists
3902 (todos-filtered-buffer-name buf flist))))
3904 (defun todos-top-priorities-multifile (&optional arg)
3905 "Display a list of top priority items from different categories.
3906 The categories are a subset of the categories in the files listed
3907 in `todos-filter-files', or if this nil, in the files chosen from
3908 a file selection dialog that pops up in this case.
3910 With numerical prefix ARG show at most ARG top priority items
3911 from each category in each file. With `C-u' as prefix argument
3912 show the numbers of top priority items specified in
3913 `todos-priorities-rules', if this is non-nil; otherwise show
3914 `todos-show-priorities' items per category. With no prefix
3915 argument, if a top priorities file for the chosen Todos files
3916 exists (see `todos-save-top-priorities-buffer'), visit this file;
3917 if there is no such file, do the same as with prefix argument
3920 (todos-top-priorities arg t))
3922 (defun todos-diary-items (&optional multifile)
3923 "Display a list of todo diary items from different categories.
3924 The categories are either a subset of those in the current Todos
3925 file, or else, with non-nil argument MULTIFILE, a subset of the
3926 categories in the files listed in `todos-filter-files', or if
3927 this nil, in the files chosen from a file selection dialog that
3928 pops up in this case."
3930 (let ((flist (if multifile
3931 (or todos-filter-files
3932 (progn (todos-multiple-filter-files)
3933 todos-multiple-filter-files))
3934 (list todos-current-todos-file)))
3935 (buf todos-diary-items-buffer))
3936 (if (equal flist 'quit)
3937 ;; Pressed `cancel' in file selection dialog.
3939 (todos-filter-items 'diary flist)
3940 (todos-filtered-buffer-name buf flist))))
3942 (defun todos-diary-items-multifile ()
3943 "Display a list of todo diary items from one or more Todos files.
3944 The categories are a subset of the categories in the files listed
3945 in `todos-filter-files', or if this nil, in the files chosen from
3946 a file selection dialog that pops up in this case."
3948 (todos-diary-items t))
3950 (defun todos-regexp-items (&optional multifile)
3951 "Prompt for a regular expression and display items that match it.
3952 The matches may be from different categories and with non-nil
3953 option `todos-filter-done-items', can include not only todo items
3954 but also done items, including those in Archive files.
3956 The categories are either a subset of those in the current Todos
3957 file (and possibly in the corresponding Archive file), or else,
3958 with non-nil argument MULTIFILE, a subset of the categories in
3959 the files listed in `todos-filter-files', or if this nil, in the
3960 files chosen from a file selection dialog that pops up in this
3961 case (and possibly in the corresponding Archive files)."
3963 (let ((flist (if multifile
3964 (or todos-filter-files
3965 (progn (todos-multiple-filter-files)
3966 todos-multiple-filter-files))
3967 (list todos-current-todos-file)))
3968 (buf todos-regexp-items-buffer))
3969 (if (equal flist 'quit)
3970 ;; Pressed `cancel' in file selection dialog.
3972 (todos-filter-items 'regexp flist)
3973 (todos-filtered-buffer-name buf flist))))
3975 (defun todos-regexp-items-multifile ()
3976 "Prompt for a regular expression and display items that match it.
3977 The matches may be from different categories and with non-nil
3978 option `todos-filter-done-items', can include not only todo items
3979 but also done items, including those in Archive files.
3981 The categories are a subset of the categories in the files listed
3982 in `todos-filter-files', or if this nil, in the files chosen from
3983 a file selection dialog that pops up in this case (and possibly
3984 in the corresponding Archive files)."
3986 (todos-regexp-items t))
3988 ;; ---------------------------------------------------------------------------
3989 ;;; Editing Commands
3991 (defun todos-add-file ()
3992 "Name and add a new Todos file.
3993 Interactively, prompt for a category and display it.
3994 Noninteractively, return the name of the new file."
3996 (let ((prompt (concat "Enter name of new Todos file "
3997 "(TAB or SPC to see current names): "))
3999 (setq file (todos-read-file-name prompt))
4000 (with-current-buffer (get-buffer-create file)
4002 (write-region (point-min) (point-max) file nil 'nomessage nil t)
4004 (todos-reevaluate-filelist-defcustoms)
4005 (if (called-interactively-p)
4007 (set-window-buffer (selected-window)
4008 (set-buffer (find-file-noselect file)))
4009 (setq todos-current-todos-file file)
4013 ;;; Category editing commands
4015 (defun todos-add-category (&optional file cat)
4016 "Add a new category to a Todos file.
4018 Called interactively with prefix argument FILE, prompt for a file
4019 and then for a new category to add to that file, otherwise prompt
4020 just for a category to add to the current Todos file. After adding
4021 the category, visit it in Todos mode.
4023 Non-interactively, add category CAT to file FILE; if FILE is nil,
4024 add CAT to the current Todos file. After adding the category,
4025 return the new category number."
4028 ;; If cat is passed from caller, don't prompt, unless it is "",
4029 ;; which means the file was just added and has no category yet.
4030 (if (and cat (> (length cat) 0))
4031 (setq file0 (or (and (stringp file) file)
4032 todos-current-todos-file))
4033 (setq catfil (todos-read-category "Enter a new category name: "
4034 'add (when (called-interactively-p 'any)
4037 file0 (if (called-interactively-p 'any)
4041 (let ((counts (make-vector 4 0)) ; [todo diary done archived]
4042 (num (1+ (length todos-categories)))
4043 (buffer-read-only nil))
4044 (setq todos-current-todos-file file0)
4045 (setq todos-categories (append todos-categories
4046 (list (cons cat counts))))
4048 (goto-char (point-max))
4049 (save-excursion ; Save point for todos-category-select.
4050 (insert todos-category-beg cat "\n\n" todos-category-done "\n"))
4051 (todos-update-categories-sexp)
4052 ;; If invoked by user, display the newly added category, if
4053 ;; called programmatically return the category number to the
4055 (if (called-interactively-p 'any)
4057 (setq todos-category-number num)
4058 (todos-category-select))
4061 (defun todos-rename-category ()
4062 "Rename current Todos category.
4063 If this file has an archive containing this category, rename the
4064 category there as well."
4066 (let* ((cat (todos-current-category))
4067 (new (read-from-minibuffer (format "Rename category \"%s\" to: " cat))))
4068 (setq new (todos-validate-name new 'category))
4069 (let* ((ofile todos-current-todos-file)
4070 (archive (concat (file-name-sans-extension ofile) ".toda"))
4071 (buffers (append (list ofile)
4072 (unless (zerop (todos-get-count 'archived cat))
4074 (dolist (buf buffers)
4075 (with-current-buffer (find-file-noselect buf)
4076 (let (buffer-read-only)
4077 (setq todos-categories (todos-set-categories))
4080 (setcar (assoc cat todos-categories) new)
4082 (goto-char (point-min))
4083 (todos-update-categories-sexp)
4084 (re-search-forward (concat (regexp-quote todos-category-beg)
4085 "\\(" (regexp-quote cat) "\\)\n")
4087 (replace-match new t t nil 1)))))))
4088 (force-mode-line-update))
4089 (save-excursion (todos-category-select)))
4091 (defun todos-delete-category (&optional arg)
4092 "Delete current Todos category provided it is empty.
4093 With ARG non-nil delete the category unconditionally,
4094 i.e. including all existing todo and done items."
4096 (let* ((file todos-current-todos-file)
4097 (cat (todos-current-category))
4098 (todo (todos-get-count 'todo cat))
4099 (done (todos-get-count 'done cat))
4100 (archived (todos-get-count 'archived cat)))
4102 (or (> todo 0) (> done 0)))
4103 (message "%s" (substitute-command-keys
4104 (concat "To delete a non-empty category, "
4105 "type C-u \\[todos-delete-category].")))
4106 (when (cond ((= (length todos-categories) 1)
4107 (y-or-n-p (concat "This is the only category in this file; "
4108 "deleting it will also delete the file.\n"
4109 "Do you want to proceed? ")))
4111 (y-or-n-p (concat "This category has archived items; "
4112 "the archived category will remain\n"
4113 "after deleting the todo category. "
4114 "Do you still want to delete it\n"
4115 "(see 'todos-skip-archived-categories' "
4116 "for another option)? ")))
4118 (y-or-n-p (concat "Permanently remove category \"" cat
4119 "\"" (and arg " and all its entries")
4122 (let ((buffer-read-only)
4123 (beg (re-search-backward
4124 (concat "^" (regexp-quote (concat todos-category-beg cat))
4126 (end (if (re-search-forward
4127 (concat "\n\\(" (regexp-quote todos-category-beg)
4131 (remove-overlays beg end)
4132 (delete-region beg end)
4133 (if (= (length todos-categories) 1)
4134 ;; If deleted category was the only one, delete the file.
4136 (todos-reevaluate-filelist-defcustoms)
4137 ;; Skip confirming killing the archive buffer if it has been
4138 ;; modified and not saved.
4139 (set-buffer-modified-p nil)
4142 (message "Deleted Todos file %s." file))
4143 (setq todos-categories (delete (assoc cat todos-categories)
4145 (todos-update-categories-sexp)
4146 (setq todos-category-number
4147 (1+ (mod todos-category-number (length todos-categories))))
4148 (todos-category-select)
4149 (goto-char (point-min))
4150 (message "Deleted category %s." cat)))))))
4152 (defun todos-move-category ()
4153 "Move current category to a different Todos file.
4154 If current category has archived items, also move those to the
4155 archive of the file moved to, creating it if it does not exist."
4157 (when (or (> (length todos-categories) 1)
4158 (y-or-n-p (concat "This is the only category in this file; "
4159 "moving it will also delete the file.\n"
4160 "Do you want to proceed? ")))
4161 (let* ((ofile todos-current-todos-file)
4162 (cat (todos-current-category))
4163 (nfile (todos-read-file-name
4164 "Choose a Todos file to move this category to: " nil t))
4165 (archive (concat (file-name-sans-extension ofile) ".toda"))
4166 (buffers (append (list ofile)
4167 (unless (zerop (todos-get-count 'archived cat))
4170 (while (equal (file-truename nfile) (file-truename ofile))
4171 (setq nfile (todos-read-file-name
4172 "Choose a file distinct from this file: " nil t)))
4173 (dolist (buf buffers)
4174 (with-current-buffer (find-file-noselect buf)
4176 (goto-char (point-max))
4177 (let* ((beg (re-search-backward
4178 (concat "^" (regexp-quote (concat todos-category-beg cat))
4181 (end (if (re-search-forward
4182 (concat "^" (regexp-quote todos-category-beg))
4186 (content (buffer-substring-no-properties beg end))
4187 (counts (cdr (assoc cat todos-categories)))
4189 ;; Move the category to the new file. Also update or create
4190 ;; archive file if necessary.
4191 (with-current-buffer
4193 ;; Regenerate todos-archives in case there
4194 ;; is a newly created archive.
4195 (if (member buf (funcall todos-files-function t))
4196 (concat (file-name-sans-extension nfile) ".toda")
4198 (let* ((nfile-short (todos-short-file-name nfile))
4200 (format "Todos file \"%s\" already has "
4202 (format "the category \"%s\";\n" cat)
4203 "enter a new category name: "))
4206 (goto-char (point-max))
4208 ;; If the file moved to has a category with the same
4209 ;; name, rename the moved category.
4210 (when (assoc cat todos-categories)
4211 (unless (member (file-truename (buffer-file-name))
4212 (funcall todos-files-function t))
4213 (setq new (read-from-minibuffer prompt))
4214 (setq new (todos-validate-name new 'category))))
4215 ;; Replace old with new name in Todos and archive files.
4217 (goto-char (point-max))
4219 (concat "^" (regexp-quote todos-category-beg)
4220 "\\(" (regexp-quote cat) "\\)$") nil t)
4221 (replace-match new nil nil nil 1)))
4222 (setq todos-categories
4223 (append todos-categories (list (cons new counts))))
4224 (todos-update-categories-sexp)
4225 ;; If archive was just created, save it to avoid "File
4226 ;; <xyz> no longer exists!" message on invoking
4227 ;; `todos-view-archived-items'.
4228 (unless (file-exists-p (buffer-file-name))
4230 (todos-category-number (or new cat))
4231 (todos-category-select))
4232 ;; Delete the category from the old file, and if that was the
4233 ;; last category, delete the file. Also handle archive file
4235 (remove-overlays beg end)
4236 (delete-region beg end)
4237 (goto-char (point-min))
4238 ;; Put point after todos-categories sexp.
4240 (if (eobp) ; Aside from sexp, file is empty.
4242 ;; Skip confirming killing the archive buffer.
4243 (set-buffer-modified-p nil)
4244 (delete-file todos-current-todos-file)
4246 (when (member todos-current-todos-file todos-files)
4247 (todos-reevaluate-filelist-defcustoms)))
4248 (setq todos-categories (delete (assoc cat todos-categories)
4250 (todos-update-categories-sexp)
4251 (todos-category-select)))))
4252 (set-window-buffer (selected-window)
4253 (set-buffer (find-file-noselect nfile)))
4254 (todos-category-number (or new cat))
4255 (todos-category-select))))
4257 (defun todos-merge-category (&optional file)
4258 "Merge current category into another existing category.
4260 With prefix argument FILE, prompt for a specific Todos file and
4261 choose (with TAB completion) a category in it to merge into;
4262 otherwise, choose and merge into a category in either the
4263 current Todos file or a file in `todos-category-completions-files'.
4265 After merging, the current category's todo and done items are
4266 appended to the chosen goal category's todo and done items,
4267 respectively. The goal category becomes the current category,
4268 and the previous current category is deleted.
4270 If both the first and goal categories also have archived items,
4271 the former are merged to the latter. If only the first category
4272 has archived items, the archived category is renamed to the goal
4275 (let* ((tfile todos-current-todos-file)
4276 (archive (concat (file-name-sans-extension (if file gfile tfile))
4278 (cat (todos-current-category))
4279 (cat+file (todos-read-category "Merge into category: " 'merge file))
4280 (goal (car cat+file))
4281 (gfile (cdr cat+file))
4282 archived-count here)
4283 ;; Merge in todo file.
4284 (with-current-buffer (get-buffer (find-file-noselect tfile))
4286 (let* ((buffer-read-only nil)
4289 (concat "^" (regexp-quote todos-category-beg)) nil t)
4291 (tbeg (progn (forward-line) (point-marker)))
4294 (concat "^" (regexp-quote todos-category-done)) nil t)
4295 (forward-line) (point-marker)))
4296 ;; Omit empty line between todo and done items.
4297 (tend (progn (forward-line -2) (point-marker)))
4299 (if (re-search-forward
4300 (concat "^" (regexp-quote todos-category-beg)) nil t)
4302 (goto-char (match-beginning 0))
4304 (point-max-marker))))
4305 (todo (buffer-substring-no-properties tbeg tend))
4306 (done (buffer-substring-no-properties dbeg cend)))
4307 (goto-char (point-min))
4308 ;; Merge any todo items.
4309 (unless (zerop (length todo))
4311 (concat "^" (regexp-quote (concat todos-category-beg goal)) "$")
4314 (concat "^" (regexp-quote todos-category-done)) nil t)
4316 (setq here (point-marker))
4318 (todos-update-count 'todo (todos-get-count 'todo cat) goal))
4319 ;; Merge any done items.
4320 (unless (zerop (length done))
4321 (goto-char (if (re-search-forward
4322 (concat "^" (regexp-quote todos-category-beg)) nil t)
4325 (when (zerop (length todo)) (setq here (point-marker)))
4327 (todos-update-count 'done (todos-get-count 'done cat) goal))
4328 (remove-overlays cbeg cend)
4329 (delete-region cbeg cend)
4330 (setq todos-categories (delete (assoc cat todos-categories)
4332 (todos-update-categories-sexp)
4333 (mapc (lambda (m) (set-marker m nil)) (list cbeg tbeg dbeg tend cend))))
4334 (when (file-exists-p archive)
4335 ;; Merge in archive file.
4336 (with-current-buffer (get-buffer (find-file-noselect archive))
4338 (goto-char (point-min))
4339 (let ((buffer-read-only nil)
4340 (cbeg (save-excursion
4341 (when (re-search-forward
4342 (concat "^" (regexp-quote
4343 (concat todos-category-beg cat)) "$")
4345 (goto-char (match-beginning 0))
4347 (gbeg (save-excursion
4348 (when (re-search-forward
4349 (concat "^" (regexp-quote
4350 (concat todos-category-beg goal)) "$")
4352 (goto-char (match-beginning 0))
4356 (setq archived-count (todos-get-count 'done cat))
4357 (setq cend (save-excursion
4358 (if (re-search-forward
4359 (concat "^" (regexp-quote todos-category-beg))
4363 (setq carch (save-excursion (goto-char cbeg) (forward-line)
4364 (buffer-substring-no-properties (point) cend)))
4365 ;; If both categories of the merge have archived items, merge the
4366 ;; source items to the goal items, else "merge" by renaming the
4367 ;; source category to goal.
4370 (goto-char (if (re-search-forward
4371 (concat "^" (regexp-quote todos-category-beg))
4376 (remove-overlays cbeg cend)
4377 (delete-region cbeg cend))
4379 (search-forward cat)
4380 (replace-match goal))
4381 (setq todos-categories (todos-make-categories-list t))
4382 (todos-update-categories-sexp)))))
4383 (with-current-buffer (get-file-buffer tfile)
4384 (when archived-count
4385 (unless (zerop archived-count)
4386 (todos-update-count 'archived archived-count goal)
4387 (todos-update-categories-sexp)))
4388 (todos-category-number goal)
4389 ;; If there are only merged done items, show them.
4390 (let ((todos-show-with-done (zerop (todos-get-count 'todo goal))))
4391 (todos-category-select)
4392 ;; Put point on the first merged item.
4394 (set-marker here nil)))
4396 (defun todos-set-category-priority (&optional arg)
4397 "Change priority of category at point in Todos Categories buffer.
4399 With ARG nil, prompt for the new priority number. Alternatively,
4400 the new priority can be provided by a numerical prefix ARG.
4401 Otherwise, if ARG is either of the symbols `raise' or `lower',
4402 raise or lower the category's priority by one."
4404 (let ((curnum (save-excursion
4405 ;; Get the number representing the priority of the category
4406 ;; on the current line.
4407 (forward-line 0) (skip-chars-forward " ") (number-at-point))))
4408 (when curnum ; Do nothing if we're not on a category line.
4409 (let* ((maxnum (length todos-categories))
4410 (prompt (format "Set category priority (1-%d): " maxnum))
4411 (col (current-column))
4412 (buffer-read-only nil)
4413 (priority (cond ((and (eq arg 'raise) (> curnum 1))
4415 ((and (eq arg 'lower) (< curnum maxnum))
4418 (while (not priority)
4419 (setq candidate (or arg (read-number prompt)))
4422 (cond ((or (< candidate 1) (> candidate maxnum))
4423 (format "Priority must be an integer between 1 and %d: "
4425 ((= candidate curnum)
4426 "Choose a different priority than the current one: ")))
4427 (unless prompt (setq priority candidate)))
4428 (let* ((lower (< curnum priority)) ; Priority is being lowered.
4429 (head (butlast todos-categories
4430 (apply (if lower 'identity '1+)
4431 (list (- maxnum priority)))))
4432 (tail (nthcdr (apply (if lower 'identity '1-) (list priority))
4434 ;; Category's name and items counts list.
4435 (catcons (nth (1- curnum) todos-categories))
4436 (todos-categories (nconc head (list catcons) tail))
4438 (when lower (setq todos-categories (nreverse todos-categories)))
4439 (setq todos-categories (delete-dups todos-categories))
4440 (when lower (setq todos-categories (nreverse todos-categories)))
4441 (setq newcats todos-categories)
4443 (with-current-buffer (find-buffer-visiting todos-current-todos-file)
4444 (setq todos-categories newcats)
4445 (todos-update-categories-sexp))
4446 (todos-display-categories)
4447 (forward-line (1+ priority))
4448 (forward-char col))))))
4450 (defun todos-raise-category-priority ()
4451 "Raise priority of category at point in Todos Categories buffer."
4453 (todos-set-category-priority 'raise))
4455 (defun todos-lower-category-priority ()
4456 "Lower priority of category at point in Todos Categories buffer."
4458 (todos-set-category-priority 'lower))
4460 ;; ---------------------------------------------------------------------------
4461 ;;; Item editing commands
4464 (defun todos-insert-item (&optional arg diary nonmarking date-type time
4466 "Add a new Todo item to a category.
4467 \(See the note at the end of this document string about key
4468 bindings and convenience commands derived from this command.)
4470 With no (or nil) prefix argument ARG, add the item to the current
4471 category; with one prefix argument (C-u), prompt for a category
4472 from the current Todos file; with two prefix arguments (C-u C-u),
4473 first prompt for a Todos file, then a category in that file. If
4474 a non-existing category is entered, ask whether to add it to the
4475 Todos file; if answered affirmatively, add the category and
4476 insert the item there.
4478 When argument DIARY is non-nil, this overrides the intent of the
4479 user option `todos-include-in-diary' for this item: if
4480 `todos-include-in-diary' is nil, include the item in the Fancy
4481 Diary display, and if it is non-nil, exclude the item from the
4482 Fancy Diary display. When DIARY is nil, `todos-include-in-diary'
4483 has its intended effect.
4485 When the item is included in the Fancy Diary display and the
4486 argument NONMARKING is non-nil, this overrides the intent of the
4487 user option `todos-diary-nonmarking' for this item: if
4488 `todos-diary-nonmarking' is nil, append `diary-nonmarking-symbol'
4489 to the item, and if it is non-nil, omit `diary-nonmarking-symbol'.
4491 The argument DATE-TYPE determines the content of the item's
4492 mandatory date header string and how it is added:
4493 - If DATE-TYPE is the symbol `calendar', the Calendar pops up and
4494 when the user puts the cursor on a date and hits RET, that
4495 date, in the format set by `calendar-date-display-form',
4496 becomes the date in the header.
4497 - If DATE-TYPE is a string matching the regexp
4498 `todos-date-pattern', that string becomes the date in the
4499 header. This case is for the command
4500 `todos-insert-item-from-calendar' which is called from the
4502 - If DATE-TYPE is the symbol `date', the header contains the date
4503 in the format set by `calendar-date-display-form', with year,
4504 month and day individually prompted for (month with tab
4506 - If DATE-TYPE is the symbol `dayname' the header contains a
4507 weekday name instead of a date, prompted for with tab
4509 - If DATE-TYPE has any other value (including nil or none) the
4510 header contains the current date (in the format set by
4511 `calendar-date-display-form').
4513 With non-nil argument TIME prompt for a time string, which must
4514 match `diary-time-regexp'. Typing `<return>' at the prompt
4515 returns the current time, if the user option
4516 `todos-always-add-time-string' is non-nil, otherwise the empty
4517 string (i.e., no time string). If TIME is absent or nil, add or
4518 omit the current time string according as
4519 `todos-always-add-time-string' is non-nil or nil, respectively.
4521 The argument REGION-OR-HERE determines the source and location of
4523 - If the REGION-OR-HERE is the symbol `here', prompt for the text
4524 of the new item and, if the command was invoked in the current
4525 category, insert it directly above the todo item at
4526 point (hence lowering the priority of the remaining items), or
4527 if point is on the empty line below the last todo item, insert
4528 the new item there. If point is in the done items section of
4529 the category, insert the new item as the first todo item in the
4530 category. Likewise, if the command with `here' is invoked
4531 outside of the current category, jump to the chosen category
4532 and insert the new item as the first item in the category.
4533 - If REGION-OR-HERE is the symbol `region', use the region of the
4534 current buffer as the text of the new item, depending on the
4535 value of user option `todos-use-only-highlighted-region': if
4536 this is non-nil, then use the region only when it is
4537 highlighted; otherwise, use the region regardless of
4538 highlighting. An error is signalled if there is no region in
4539 the current buffer. Prompt for the item's priority in the
4540 category (an integer between 1 and one more than the number of
4541 items in the category), and insert the item accordingly.
4542 - If REGION-OR-HERE has any other value (in particular, nil or
4543 none), prompt for the text and the item's priority, and insert
4544 the item accordingly.
4546 To facilitate using these arguments when inserting a new todo
4547 item, convenience commands have been defined for all admissible
4548 combinations together with mnenomic key bindings based on on the
4549 name of the arguments and their order in the command's argument
4550 list: diar_y_ - nonmar_k_ing - _c_alendar or _d_ate or day_n_ame
4551 - _t_ime - _r_egion or _h_ere. These key combinations are
4552 appended to the basic insertion key (i) and keys that allow a
4553 following key must be doubled when used finally. For example,
4554 `iyh' will insert a new item with today's date, marked according
4555 to the DIARY argument described above, and with priority
4556 according to the HERE argument; while `iyy' does the same except
4557 the priority is not given by HERE but by prompting."
4558 ;; An alternative interface for customizing key
4559 ;; binding is also provided with the function
4560 ;; `todos-insertion-bindings'." ;FIXME
4562 ;; If invoked outside of Todos mode and there is not yet any Todos
4563 ;; file, initialize one.
4564 (if (null todos-files)
4566 (let ((region (eq region-or-here 'region))
4567 (here (eq region-or-here 'here)))
4569 (let (use-empty-active-region)
4570 (unless (and todos-use-only-highlighted-region (use-region-p))
4571 (error "There is no active region"))))
4572 (let* ((buf (current-buffer))
4573 (ocat (todos-current-category))
4574 (todos-mm (eq major-mode 'todos-mode))
4575 (cat+file (cond ((equal arg '(4))
4576 (todos-read-category "Insert in category: "))
4578 (todos-read-category "Insert in category: "
4581 (cons (todos-current-category)
4582 (or todos-current-todos-file
4583 (and todos-show-current-file
4584 todos-global-current-todos-file)
4585 (todos-absolute-file-name
4586 todos-default-todos-file))))))
4587 (cat (car cat+file))
4588 (file (cdr cat+file))
4589 (new-item (if region
4590 (buffer-substring-no-properties
4591 (region-beginning) (region-end))
4592 (read-from-minibuffer "Todo item: ")))
4594 ((eq date-type 'date)
4596 ((eq date-type 'dayname)
4597 (todos-read-dayname))
4598 ((eq date-type 'calendar)
4599 (setq todos-date-from-calendar t)
4600 (or (todos-set-date-from-calendar)
4601 ;; If user exits Calendar before choosing
4602 ;; a date, cancel item insertion.
4604 ((and (stringp date-type)
4605 (string-match todos-date-pattern date-type))
4606 (setq todos-date-from-calendar date-type)
4607 (todos-set-date-from-calendar))
4609 (calendar-date-string (calendar-current-date) t t))))
4610 (time-string (or (and time (todos-read-time))
4611 (and todos-always-add-time-string
4612 (substring (current-time-string) 11 16)))))
4613 (setq todos-date-from-calendar nil)
4614 (find-file-noselect file 'nowarn)
4615 (set-window-buffer (selected-window)
4616 ;; If current category was nil till now, on
4617 ;; entering Todos mode here it will be set to
4618 ;; file's first category.
4619 (set-buffer (find-buffer-visiting file)))
4620 (setq todos-current-todos-file file)
4621 (unless todos-global-current-todos-file
4622 (setq todos-global-current-todos-file todos-current-todos-file))
4623 ;; When inserting into a file that was not being visited on
4624 ;; invoking this command, point is at bof.
4626 (todos-category-number cat)
4627 (todos-category-select))
4628 (let ((buffer-read-only nil)
4629 done-only item-added)
4631 ;; Add date, time and diary marking as required.
4632 (concat (if (not (and diary (not todos-include-in-diary)))
4633 todos-nondiary-start
4634 (when (and nonmarking (not todos-diary-nonmarking))
4635 diary-nonmarking-symbol))
4636 date-string (when (and time-string ; Can be empty string.
4637 (not (zerop (length time-string))))
4638 (concat " " time-string))
4639 (when (not (and diary (not todos-include-in-diary)))
4642 ;; Indent newlines inserted by C-q C-j if nonspace char follows.
4643 (setq new-item (replace-regexp-in-string
4644 "\\(\n\\)[^[:blank:]]"
4645 (concat "\n" (make-string todos-indent-to-here 32))
4646 new-item nil nil 1))
4649 ;; If only done items are displayed in category,
4650 ;; toggle to todo items.
4651 (when (save-excursion
4652 (goto-char (point-min))
4653 (looking-at todos-done-string-start))
4655 (todos-show-done-only))
4658 (unless (and todos-mm (equal cat ocat)
4659 (not (todos-done-item-section-p)))
4660 (goto-char (point-min)))
4661 (todos-insert-with-overlays new-item))
4662 (todos-set-item-priority new-item cat t))
4663 (setq item-added t))
4664 ;; If user cancels before setting priority, restore
4667 (and done-only (todos-show-done-only)))
4668 ;; If todos section is not visible when insertion
4669 ;; command is called (either because only done items
4670 ;; were shown or because category was not in current
4671 ;; buffer), then if item is inserted at end of category,
4672 ;; point is at eob and eob at window-start, so that that
4673 ;; higher priority todo items are out of view. So we
4674 ;; recenter to make sure the todo items are displayed in
4676 (when item-added (recenter)))
4677 (todos-update-count 'todo 1)
4678 (if (or diary todos-include-in-diary) (todos-update-count 'diary 1))
4679 (todos-update-categories-sexp))))))
4681 (defun todos-copy-item ()
4682 "Copy item at point and insert the copy as a new item."
4684 (unless (or (todos-done-item-p) (looking-at "^$"))
4685 (let ((copy (todos-item-string))
4686 (diary-item (todos-diary-item-p)))
4687 (todos-set-item-priority copy (todos-current-category) t)
4688 (todos-update-count 'todo 1)
4689 (when diary-item (todos-update-count 'diary 1))
4690 (todos-update-categories-sexp))))
4692 (defvar todos-date-from-calendar nil
4693 "Helper variable for setting item date from the Emacs Calendar.")
4695 (defun todos-set-date-from-calendar ()
4696 "Return string of date chosen from Calendar."
4697 (cond ((and (stringp todos-date-from-calendar)
4698 (string-match todos-date-pattern todos-date-from-calendar))
4699 todos-date-from-calendar)
4700 (todos-date-from-calendar
4701 (let (calendar-view-diary-initially-flag)
4702 (calendar)) ; *Calendar* is now current buffer.
4703 (define-key calendar-mode-map [remap newline] 'exit-recursive-edit)
4704 ;; If user exits Calendar before choosing a date, clean up properly.
4705 (define-key calendar-mode-map
4706 [remap calendar-exit] (lambda ()
4710 (exit-recursive-edit))))
4711 (message "Put cursor on a date and type <return> to set it.")
4714 (when (equal (buffer-name) calendar-buffer)
4715 (setq todos-date-from-calendar
4716 (calendar-date-string (calendar-cursor-to-date t) t t))
4718 todos-date-from-calendar)
4719 (define-key calendar-mode-map [remap newline] nil)
4720 (define-key calendar-mode-map [remap calendar-exit] nil)
4721 (unless (zerop (recursion-depth)) (exit-recursive-edit))
4722 (when (stringp todos-date-from-calendar)
4723 todos-date-from-calendar)))))
4725 (defun todos-delete-item ()
4726 "Delete at least one item in this category.
4728 If there are marked items, delete all of these; otherwise, delete
4733 (let* ((cat (todos-current-category))
4734 (marked (assoc cat todos-categories-with-marks))
4735 (item (unless marked (todos-item-string)))
4737 (y-or-n-p "Permanently delete all marked items? ")
4739 (setq ov (make-overlay
4740 (save-excursion (todos-item-start))
4741 (save-excursion (todos-item-end))))
4742 (overlay-put ov 'face 'todos-search)
4743 (y-or-n-p (concat "Permanently delete this item? ")))))
4746 (and marked (goto-char (point-min)))
4749 (if (or (and marked (todos-marked-item-p)) item)
4751 (if (todos-done-item-p)
4752 (todos-update-count 'done -1)
4753 (todos-update-count 'todo -1 cat)
4754 (and (todos-diary-item-p) (todos-update-count 'diary -1)))
4755 (if ov (delete-overlay ov))
4757 ;; Don't leave point below last item.
4758 (and item (bolp) (eolp) (< (point-min) (point-max))
4759 (todos-backward-item))
4761 (throw 'done (setq item nil))))
4762 (todos-forward-item))))
4764 (setq todos-categories-with-marks
4765 (assq-delete-all cat todos-categories-with-marks)))
4766 (todos-update-categories-sexp)
4767 (todos-prefix-overlays)))
4768 (if ov (delete-overlay ov)))))
4770 (defun todos-edit-item (&optional arg)
4771 "Edit the Todo item at point.
4773 With non-nil prefix argument ARG, include the item's date/time
4774 header, making it also editable; otherwise, include only the item
4777 If the item consists of only one logical line, edit it in the
4778 minibuffer; otherwise, edit it in Todos Edit mode."
4780 (when (todos-item-string)
4781 (let* ((opoint (point))
4782 (start (todos-item-start))
4785 (concat todos-date-string-start todos-date-pattern
4786 "\\( " diary-time-regexp "\\)?"
4787 (regexp-quote todos-nondiary-end) "?")
4788 (line-end-position) t)
4789 (1+ (- (point) start))))
4790 (header (substring (todos-item-string) 0 item-beg))
4791 (item (if arg (todos-item-string)
4792 (substring (todos-item-string) item-beg)))
4793 (multiline (> (length (split-string item "\n")) 1))
4794 (buffer-read-only nil))
4796 (todos-edit-multiline-item)
4797 (let ((new (concat (if arg "" header)
4798 (read-string "Edit: " (if arg
4799 (cons item item-beg)
4802 (while (not (string-match (concat todos-date-string-start
4803 todos-date-pattern) new))
4804 (setq new (read-from-minibuffer
4805 "Item must start with a date: " new))))
4806 ;; Ensure lines following hard newlines are indented.
4807 (setq new (replace-regexp-in-string
4808 "\\(\n\\)[^[:blank:]]"
4809 (concat "\n" (make-string todos-indent-to-here 32)) new
4811 ;; If user moved point during editing, make sure it moves back.
4814 (todos-insert-with-overlays new)
4815 (move-to-column item-beg))))))
4817 (defun todos-edit-multiline-item ()
4818 "Edit current Todo item in Todos Edit mode.
4819 Use of newlines invokes `todos-indent' to insure compliance with
4820 the format of Diary entries."
4822 (let ((buf todos-edit-buffer))
4823 (set-window-buffer (selected-window)
4824 (set-buffer (make-indirect-buffer (buffer-name) buf)))
4825 (narrow-to-region (todos-item-start) (todos-item-end))
4827 (message "%s" (substitute-command-keys
4828 (concat "Type \\[todos-edit-quit] "
4829 "to return to Todos mode.\n")))))
4831 (defun todos-edit-multiline (&optional item) ;FIXME: not item editing command
4837 (message "%s" (substitute-command-keys
4838 (concat "Type \\[todos-edit-quit] to check file format "
4839 "validity and return to Todos mode.\n"))))
4841 (defun todos-edit-quit ()
4842 "Return from Todos Edit mode to Todos mode.
4843 If the item contains hard line breaks, make sure the following
4844 lines are indented by `todos-indent-to-here' to conform to diary
4847 If the whole file was in Todos Edit mode, check before returning
4848 whether the file is still a valid Todos file and if so, also
4849 recalculate the Todos categories sexp, in case changes were made
4850 in the number or names of categories."
4852 (if (> (buffer-size) (- (point-max) (point-min)))
4853 (let ((item (buffer-string))
4854 (regex "\\(\n\\)[^[:blank:]]"))
4855 ;; Ensure lines following hard newlines are indented.
4856 (when (string-match regex (buffer-string))
4857 (replace-regexp-in-string
4858 regex (concat "\n" (make-string todos-indent-to-here 32))
4860 (delete-region (point-min) (point-max))
4863 (when (todos-check-format)
4864 ;; FIXME: separate out sexp check?
4865 ;; If manual editing makes e.g. item counts change, have to
4866 ;; call this to update todos-categories, but it restores
4867 ;; category order to list order.
4868 ;; (todos-repair-categories-sexp)
4869 ;; Compare (todos-make-categories-list t) with sexp and if
4870 ;; different ask (todos-update-categories-sexp) ?
4872 (let* ((cat-beg (concat "^" (regexp-quote todos-category-beg)
4874 (curline (buffer-substring-no-properties
4875 (line-beginning-position) (line-end-position)))
4876 (cat (cond ((string-match cat-beg curline)
4877 (match-string-no-properties 1 curline))
4878 ((or (re-search-backward cat-beg nil t)
4879 (re-search-forward cat-beg nil t))
4880 (match-string-no-properties 1)))))
4881 (todos-category-number cat)
4882 (todos-category-select)
4883 (goto-char (point-min))))))
4885 (defun todos-edit-item-header-1 (what &optional inc)
4886 "Function underlying commands to edit item date/time header.
4888 The argument WHAT (passed by invoking commands) specifies what
4889 part of the header to edit; possible values are these symbols:
4890 `date', to edit the year, month, and day of the date string;
4891 `time', to edit just the time string; `calendar', to select the
4892 date from the Calendar; `today', to set the date to today's date;
4893 `dayname', to set the date string to the name of a day or to
4894 change the day name; and `year', `month' or `day', to edit only
4895 these respective parts of the date string (`day' is the number of
4896 the given day of the month, and `month' is either the name of the
4897 given month or its number, depending on the value of
4898 `calendar-date-display-form').
4900 The optional argument INC is a positive or negative integer
4901 \(passed by invoking commands as a numerical prefix argument)
4902 that in conjunction with the WHAT values `year', `month' or
4903 `day', increments or decrements the specified date string
4904 component by the specified number of suitable units, i.e., years,
4905 months, or days, with automatic adjustment of the other date
4906 string components as necessary.
4908 If there are marked items, apply the same edit to all of these;
4909 otherwise, edit just the item at point."
4910 (let* ((cat (todos-current-category))
4911 (marked (assoc cat todos-categories-with-marks))
4913 (todos-date-from-calendar t)
4914 (buffer-read-only nil)
4915 ndate ntime year monthname month day
4916 dayname) ; Needed by calendar-date-display-form.
4918 (or (and marked (goto-char (point-min))) (todos-item-start))
4922 (while (not (todos-marked-item-p))
4923 (todos-forward-item)
4924 (and (eobp) (throw 'end nil))))
4925 (re-search-forward (concat todos-date-string-start "\\(?1:"
4927 "\\)\\(?2: " diary-time-regexp "\\)?"
4928 (regexp-quote todos-nondiary-end) "?")
4929 (line-end-position) t)
4930 (let* ((odate (match-string-no-properties 1))
4931 (otime (match-string-no-properties 2))
4932 (omonthname (match-string-no-properties 6))
4933 (omonth (match-string-no-properties 7))
4934 (oday (match-string-no-properties 8))
4935 (oyear (match-string-no-properties 9))
4936 (tmn-array todos-month-name-array)
4937 (mlist (append tmn-array nil))
4938 (tma-array todos-month-abbrev-array)
4939 (mablist (append tma-array nil))
4940 (yy (and oyear (unless (string= oyear "*")
4941 (string-to-number oyear))))
4942 (mm (or (and omonth (unless (string= omonth "*")
4943 (string-to-number omonth)))
4944 (1+ (- (length mlist)
4945 (length (or (member omonthname mlist)
4946 (member omonthname mablist)))))))
4947 (dd (and oday (unless (string= oday "*")
4948 (string-to-number oday)))))
4949 ;; If there are marked items, use only the first to set
4950 ;; header changes, and apply these to all marked items.
4954 (setq ndate (todos-read-date)))
4955 ((eq what 'calendar)
4956 (setq ndate (save-match-data (todos-set-date-from-calendar))))
4958 (setq ndate (calendar-date-string (calendar-current-date) t t)))
4960 (setq ndate (todos-read-dayname)))
4962 (setq ntime (save-match-data (todos-read-time)))
4963 (when (> (length ntime) 0)
4964 (setq ntime (concat " " ntime))))
4965 ;; When date string consists only of a day name,
4966 ;; passing other date components is a NOP.
4967 ((and (memq what '(year month day))
4968 (not (or oyear omonth oday))))
4971 monthname omonthname
4973 year (cond ((not current-prefix-arg)
4974 (todos-read-date 'year))
4975 ((string= oyear "*")
4976 (error "Cannot increment *"))
4978 (number-to-string (+ yy inc))))))
4982 (if (memq 'month calendar-date-display-form)
4985 (cond ((not current-prefix-arg)
4986 (todos-read-date 'month))
4987 ((or (string= omonth "*") (= mm 13))
4988 (error "Cannot increment *"))
4990 (let ((mminc (+ mm inc)))
4991 ;; Increment or decrement month by INC
4993 (setq mm (% mminc 12))
4994 ;; If result is 0, make month December.
4995 (setq mm (if (= mm 0) 12 (abs mm)))
4996 ;; Adjust year if necessary.
4997 (setq year (or (and (cond ((> mminc 12)
4998 (+ yy (/ mminc 12)))
5000 (- yy (/ mminc 12) 1))
5002 (number-to-string yy))
5004 ;; Return the changed numerical month as
5005 ;; a string or the corresponding month name.
5007 (number-to-string mm)
5008 (aref tma-array (1- mm))))))
5009 (let ((yy (string-to-number year)) ; 0 if year is "*".
5010 ;; When mm is 13 (corresponding to "*" as value
5011 ;; of month), this raises an args-out-of-range
5012 ;; error in calendar-last-day-of-month, so use 1
5013 ;; (corresponding to January) to get 31 days.
5014 (mm (if (= mm 13) 1 mm)))
5015 (if (> (string-to-number day)
5016 (calendar-last-day-of-month mm yy))
5017 (error "%s %s does not have %s days"
5018 (aref tmn-array (1- mm))
5019 (if (= mm 2) yy "") day))))
5023 monthname omonthname
5025 ((not current-prefix-arg)
5026 (todos-read-date 'day mm oyear))
5028 (error "Cannot increment *"))
5029 ((or (string= omonth "*") (string= omonthname "*"))
5030 (setq dd (+ dd inc))
5032 (error "A month cannot have more than 31 days")
5033 (number-to-string dd)))
5034 ;; Increment or decrement day by INC,
5035 ;; adjusting month and year if necessary
5036 ;; (if year is "*" assume current year to
5037 ;; calculate adjustment).
5039 (let* ((yy (or yy (calendar-extract-year
5040 (calendar-current-date))))
5041 (date (calendar-gregorian-from-absolute
5042 (+ (calendar-absolute-from-gregorian
5043 (list mm dd yy)) inc)))
5044 (adjmm (nth 0 date)))
5045 ;; Set year and month(name) to adjusted values.
5046 (unless (string= year "*")
5047 (setq year (number-to-string (nth 2 date))))
5049 (setq month (number-to-string adjmm))
5050 (setq monthname (aref tma-array (1- adjmm))))
5051 ;; Return changed numerical day as a string.
5052 (number-to-string (nth 1 date)))))))))
5053 ;; If new year, month or day date string components were
5054 ;; calculated, rebuild the whole date string from them.
5055 (when (memq what '(year month day))
5056 (if (or oyear omonth omonthname oday)
5057 (setq ndate (mapconcat 'eval calendar-date-display-form ""))
5058 (message "Cannot edit date component of empty date string")))
5059 (when ndate (replace-match ndate nil nil nil 1))
5060 ;; Add new time string to the header, if it was supplied.
5063 (replace-match ntime nil nil nil 2)
5064 (goto-char (match-end 1))
5066 (setq todos-date-from-calendar nil)
5068 ;; Apply the changes to the first marked item header to the
5069 ;; remaining marked items. If there are no marked items,
5072 (todos-forward-item)
5073 (goto-char (point-max))))))))
5075 (defun todos-edit-item-header ()
5076 "Interactively edit at least the date of item's date/time header.
5077 If user option `todos-always-add-time-string' is non-nil, also
5078 edit item's time string."
5080 (todos-edit-item-header-1 'date)
5081 (when todos-always-add-time-string
5082 (todos-edit-item-time)))
5084 (defun todos-edit-item-time ()
5085 "Interactively edit the time string of item's date/time header."
5087 (todos-edit-item-header-1 'time))
5089 (defun todos-edit-item-date-from-calendar ()
5090 "Interactively edit item's date using the Calendar."
5092 (todos-edit-item-header-1 'calendar))
5094 (defun todos-edit-item-date-to-today ()
5095 "Set item's date to today's date."
5097 (todos-edit-item-header-1 'today))
5099 (defun todos-edit-item-date-day-name ()
5100 "Replace item's date with the name of a day of the week."
5102 (todos-edit-item-header-1 'dayname))
5104 (defun todos-edit-item-date-year (&optional inc)
5105 "Interactively edit the year of item's date string.
5106 With prefix argument INC a positive or negative integer,
5107 increment or decrement the year by INC."
5109 (todos-edit-item-header-1 'year inc))
5111 (defun todos-edit-item-date-month (&optional inc)
5112 "Interactively edit the month of item's date string.
5113 With prefix argument INC a positive or negative integer,
5114 increment or decrement the month by INC."
5116 (todos-edit-item-header-1 'month inc))
5118 (defun todos-edit-item-date-day (&optional inc)
5119 "Interactively edit the day of the month of item's date string.
5120 With prefix argument INC a positive or negative integer,
5121 increment or decrement the day by INC."
5123 (todos-edit-item-header-1 'day inc))
5125 (defun todos-edit-item-diary-inclusion ()
5126 "Change diary status of one or more todo items in this category.
5127 That is, insert `todos-nondiary-marker' if the candidate items
5128 lack this marking; otherwise, remove it.
5130 If there are marked todo items, change the diary status of all
5131 and only these, otherwise change the diary status of the item at
5134 (let ((buffer-read-only)
5135 (marked (assoc (todos-current-category)
5136 todos-categories-with-marks)))
5139 (when marked (goto-char (point-min)))
5141 (if (todos-done-item-p)
5142 (throw 'stop (message "Done items cannot be edited"))
5143 (unless (and marked (not (todos-marked-item-p)))
5144 (let* ((beg (todos-item-start))
5145 (lim (save-excursion (todos-item-end)))
5146 (end (save-excursion
5147 (or (todos-time-string-matcher lim)
5148 (todos-date-string-matcher lim)))))
5149 (if (looking-at (regexp-quote todos-nondiary-start))
5152 (search-forward todos-nondiary-end (1+ end) t)
5154 (todos-update-count 'diary 1))
5156 (insert todos-nondiary-start)
5157 (goto-char (1+ end))
5158 (insert todos-nondiary-end)
5159 (todos-update-count 'diary -1)))))
5160 (unless marked (throw 'stop nil))
5161 (todos-forward-item)))))
5162 (todos-update-categories-sexp)))
5164 (defun todos-edit-category-diary-inclusion (arg)
5165 "Make all items in this category diary items.
5166 With prefix ARG, make all items in this category non-diary
5170 (goto-char (point-min))
5171 (let ((todo-count (todos-get-count 'todo))
5172 (diary-count (todos-get-count 'diary))
5176 (if (todos-done-item-p) ; We've gone too far.
5178 (let* ((beg (todos-item-start))
5179 (lim (save-excursion (todos-item-end)))
5180 (end (save-excursion
5181 (or (todos-time-string-matcher lim)
5182 (todos-date-string-matcher lim)))))
5184 (unless (looking-at (regexp-quote todos-nondiary-start))
5185 (insert todos-nondiary-start)
5186 (goto-char (1+ end))
5187 (insert todos-nondiary-end))
5188 (when (looking-at (regexp-quote todos-nondiary-start))
5190 (search-forward todos-nondiary-end (1+ end) t)
5191 (replace-match "")))))
5192 (todos-forward-item))
5193 (unless (if arg (zerop diary-count) (= diary-count todo-count))
5194 (todos-update-count 'diary (if arg
5196 (- todo-count diary-count))))
5197 (todos-update-categories-sexp)))))
5199 (defun todos-edit-item-diary-nonmarking ()
5200 "Change non-marking of one or more diary items in this category.
5201 That is, insert `diary-nonmarking-symbol' if the candidate items
5202 lack this marking; otherwise, remove it.
5204 If there are marked todo items, change the non-marking status of
5205 all and only these, otherwise change the non-marking status of
5208 (let ((buffer-read-only)
5209 (marked (assoc (todos-current-category)
5210 todos-categories-with-marks)))
5213 (when marked (goto-char (point-min)))
5215 (if (todos-done-item-p)
5216 (throw 'stop (message "Done items cannot be edited"))
5217 (unless (and marked (not (todos-marked-item-p)))
5219 (unless (looking-at (regexp-quote todos-nondiary-start))
5220 (if (looking-at (regexp-quote diary-nonmarking-symbol))
5222 (insert diary-nonmarking-symbol))))
5223 (unless marked (throw 'stop nil))
5224 (todos-forward-item)))))))
5226 (defun todos-edit-category-diary-nonmarking (arg)
5227 "Add `diary-nonmarking-symbol' to all diary items in this category.
5228 With prefix ARG, remove `diary-nonmarking-symbol' from all diary
5229 items in this category."
5232 (goto-char (point-min))
5233 (let (buffer-read-only)
5236 (if (todos-done-item-p) ; We've gone too far.
5238 (unless (looking-at (regexp-quote todos-nondiary-start))
5240 (when (looking-at (regexp-quote diary-nonmarking-symbol))
5242 (unless (looking-at (regexp-quote diary-nonmarking-symbol))
5243 (insert diary-nonmarking-symbol))))
5244 (todos-forward-item)))))))
5246 (defun todos-set-item-priority (&optional item cat new arg)
5247 "Prompt for and set ITEM's priority in CATegory.
5249 Interactively, ITEM is the todo item at point, CAT is the current
5250 category, and the priority is a number between 1 and the number
5251 of items in the category. Non-interactively, non-nil NEW means
5252 ITEM is a new item and the lowest priority is one more than the
5253 number of items in CAT.
5255 The new priority is set either interactively by prompt or by a
5256 numerical prefix argument, or noninteractively by argument ARG,
5257 whose value can be either of the symbols `raise' or `lower',
5258 meaning to raise or lower the item's priority by one."
5259 (interactive) ;FIXME: Prefix arg?
5260 (unless (and (called-interactively-p 'any)
5261 (or (todos-done-item-p) (looking-at "^$")))
5262 (let* ((item (or item (todos-item-string)))
5263 (marked (todos-marked-item-p))
5264 (cat (or cat (cond ((eq major-mode 'todos-mode)
5265 (todos-current-category))
5266 ((eq major-mode 'todos-filtered-items-mode)
5268 (concat todos-date-string-start
5270 "\\( " diary-time-regexp "\\)?"
5271 (regexp-quote todos-nondiary-end)
5272 "?\\(?1: \\[\\(.+:\\)?.+\\]\\)")))
5274 (re-search-forward regexp1 nil t)
5275 (match-string-no-properties 1)))))))
5277 (todo (cond ((or (eq arg 'raise) (eq arg 'lower)
5278 (eq major-mode 'todos-filtered-items-mode))
5280 (let ((curstart (todos-item-start))
5282 (goto-char (point-min))
5283 (while (looking-at todos-item-start)
5284 (setq count (1+ count))
5285 (when (= (point) curstart) (setq curnum count))
5286 (todos-forward-item))
5288 ((eq major-mode 'todos-mode)
5289 (todos-get-count 'todo cat))))
5290 (maxnum (if new (1+ todo) todo))
5291 (prompt (format "Set item priority (1-%d): " maxnum))
5292 (priority (cond ((numberp current-prefix-arg)
5294 ((and (eq arg 'raise) (>= curnum 1))
5296 ((and (eq arg 'lower) (<= curnum maxnum))
5300 (unless (and priority
5301 (or (and (eq arg 'raise) (zerop priority))
5302 (and (eq arg 'lower) (> priority maxnum))))
5303 ;; When moving item to another category, show the category before
5304 ;; prompting for its priority.
5305 (unless (or arg (called-interactively-p 'any))
5306 (todos-category-number cat)
5307 ;; If done items in category are visible, keep them visible.
5308 (let ((done todos-show-with-done))
5309 (when (> (buffer-size) (- (point-max) (point-min)))
5311 (goto-char (point-min))
5312 (setq done (re-search-forward todos-done-string-start nil t))))
5313 (let ((todos-show-with-done done))
5314 (todos-category-select)))))
5315 ;; Prompt for priority only when the category has at least one todo item.
5317 (while (not priority)
5318 (setq candidate (read-number prompt))
5319 (setq prompt (when (or (< candidate 1) (> candidate maxnum))
5320 (format "Priority must be an integer between 1 and %d.\n"
5322 (unless prompt (setq priority candidate))))
5323 ;; In Top Priorities buffer, an item's priority can be changed
5324 ;; wrt items in another category, but not wrt items in the same
5326 (when (eq major-mode 'todos-filtered-items-mode)
5327 (let* ((regexp2 (concat todos-date-string-start todos-date-pattern
5328 "\\( " diary-time-regexp "\\)?"
5329 (regexp-quote todos-nondiary-end)
5330 "?\\(?1:" (regexp-quote cat) "\\)"))
5331 (end (cond ((< curnum priority)
5332 (save-excursion (todos-item-end)))
5333 ((> curnum priority)
5334 (save-excursion (todos-item-start)))))
5335 (match (save-excursion
5336 (cond ((< curnum priority)
5337 (todos-forward-item (1+ (- priority curnum)))
5338 (when (re-search-backward regexp2 end t)
5339 (match-string-no-properties 1)))
5340 ((> curnum priority)
5341 (todos-backward-item (- curnum priority))
5342 (when (re-search-forward regexp2 end t)
5343 (match-string-no-properties 1)))))))
5345 (error (concat "Cannot reprioritize items from the same "
5346 "category in this mode, only in Todos mode")))))
5347 ;; Interactively or with non-nil ARG, relocate the item within its
5349 (when (or arg (called-interactively-p 'any))
5350 (todos-remove-item))
5351 (goto-char (point-min))
5353 (unless (= priority 1)
5354 (todos-forward-item (1- priority))
5355 ;; When called from todos-item-undo and the highest priority
5356 ;; is chosen, this advances point to the first done item, so
5357 ;; move it up to the empty line above the done items
5359 (when (looking-back (concat "^"
5360 (regexp-quote todos-category-done) "\n"))
5361 (todos-backward-item))))
5362 (todos-insert-with-overlays item)
5363 ;; If item was marked, restore the mark.
5365 (let* ((ov (todos-get-overlay 'prefix))
5366 (pref (overlay-get ov 'before-string)))
5367 (overlay-put ov 'before-string (concat todos-item-mark pref)))))))
5369 (defun todos-raise-item-priority ()
5370 "Raise priority of current item by moving it up by one item."
5372 (todos-set-item-priority nil nil nil 'raise))
5374 (defun todos-lower-item-priority ()
5375 "Lower priority of current item by moving it down by one item."
5377 (todos-set-item-priority nil nil nil 'lower))
5379 (defun todos-move-item (&optional file)
5380 "Move at least one todo or done item to another category.
5381 If there are marked items, move all of these; otherwise, move
5384 With prefix argument FILE, prompt for a specific Todos file and
5385 choose (with TAB completion) a category in it to move the item or
5386 items to; otherwise, choose and move to any category in either
5387 the current Todos file or one of the files in
5388 `todos-category-completions-files'. If the chosen category is
5389 not an existing categories, then it is created and the item(s)
5390 become(s) the first entry/entries in that category.
5392 With moved Todo items, prompt to set the priority in the category
5393 moved to (with multiple todos items, the one that had the highest
5394 priority in the category moved from gets the new priority and the
5395 rest of the moved todo items are inserted in sequence below it).
5396 Moved done items are appended to the end of the done items
5397 section in the category moved to."
5399 (let* ((cat1 (todos-current-category))
5400 (marked (assoc cat1 todos-categories-with-marks)))
5401 ;; NOP if point is not on an item and there are no marked items.
5402 (unless (and (looking-at "^$")
5404 (let* ((buffer-read-only)
5405 (file1 todos-current-todos-file)
5406 (num todos-category-number)
5407 (item (todos-item-string))
5408 (diary-item (todos-diary-item-p))
5409 (done-item (and (todos-done-item-p) (concat item "\n")))
5410 (omark (save-excursion (todos-item-start) (point-marker)))
5414 ov cat+file cat2 file2 moved nmark todo-items done-items)
5418 (setq ov (make-overlay (save-excursion (todos-item-start))
5419 (save-excursion (todos-item-end))))
5420 (overlay-put ov 'face 'todos-search))
5421 (setq cat+file (let ((pl (if (and marked (> (cdr marked) 1))
5423 (todos-read-category (concat "Move item" pl
5427 file2 (cdr cat+file)))
5428 (if ov (delete-overlay ov)))
5429 (set-buffer (find-buffer-visiting file1))
5432 (goto-char (point-min))
5434 (when (todos-marked-item-p)
5435 (if (todos-done-item-p)
5436 (setq done-items (concat done-items
5437 (todos-item-string) "\n")
5439 (setq todo-items (concat todo-items
5440 (todos-item-string) "\n")
5442 (when (todos-diary-item-p)
5443 (setq diary (1+ diary)))))
5444 (todos-forward-item))
5445 ;; Chop off last newline of multiple todo item string,
5446 ;; since it will be reinserted when setting priority
5447 ;; (but with done items priority is not set, so keep
5450 (setq todo-items (substring todo-items 0 -1))))
5451 (if (todos-done-item-p)
5454 (when (todos-diary-item-p) (setq diary 1))))
5455 (set-window-buffer (selected-window)
5456 (set-buffer (find-file-noselect file2 'nowarn)))
5459 (when (or todo-items (and item (not done-item)))
5460 (todos-set-item-priority (or todo-items item) cat2 t))
5461 ;; Move done items en bloc to end of done item section.
5462 (when (or done-items done-item)
5463 (todos-category-number cat2)
5465 (goto-char (point-min))
5466 (re-search-forward (concat "^" (regexp-quote
5467 (concat todos-category-beg cat2))
5470 (goto-char (if (re-search-forward
5471 (concat "^" (regexp-quote todos-category-beg))
5475 (insert (or done-items done-item)))
5478 ;; Move succeeded, so remove item from starting category,
5479 ;; update item counts and display the category containing
5482 (setq nmark (point-marker))
5483 (when todo (todos-update-count 'todo todo))
5484 (when diary (todos-update-count 'diary diary))
5485 (when done (todos-update-count 'done done))
5486 (todos-update-categories-sexp)
5487 (with-current-buffer (find-buffer-visiting file1)
5496 (concat "^" (regexp-quote todos-category-beg)) nil t)
5499 (setq end (if (re-search-forward
5500 (concat "^" (regexp-quote
5501 todos-category-beg)) nil t)
5505 (while (< (point) end)
5506 (if (todos-marked-item-p)
5508 (todos-forward-item)))
5509 (setq todos-categories-with-marks
5510 (assq-delete-all cat1 todos-categories-with-marks)))
5511 (if ov (delete-overlay ov))
5512 (todos-remove-item))))
5513 (when todo (todos-update-count 'todo (- todo) cat1))
5514 (when diary (todos-update-count 'diary (- diary) cat1))
5515 (when done (todos-update-count 'done (- done) cat1))
5516 (todos-update-categories-sexp))
5517 (set-window-buffer (selected-window)
5518 (set-buffer (find-file-noselect file2 'nowarn)))
5519 (setq todos-category-number (todos-category-number cat2))
5520 (let ((todos-show-with-done (or done-items done-item)))
5521 (todos-category-select))
5523 ;; If item is moved to end of (just first?) category, make
5524 ;; sure the items above it are displayed in the window.
5526 ;; User quit before setting priority of todo item(s), so
5527 ;; return to starting category.
5529 (todos-category-number cat1)
5530 (todos-category-select)
5531 (goto-char omark))))))))
5533 (defun todos-item-done (&optional arg)
5534 "Tag a todo item in this category as done and relocate it.
5536 With prefix argument ARG prompt for a comment and append it to
5537 the done item; this is only possible if there are no marked
5538 items. If there are marked items, tag all of these with
5539 `todos-done-string' plus the current date and, if
5540 `todos-always-add-time-string' is non-nil, the current time;
5541 otherwise, just tag the item at point. Items tagged as done are
5542 relocated to the category's (by default hidden) done section. If
5543 done items are visible on invoking this command, they remain
5546 (let* ((cat (todos-current-category))
5547 (marked (assoc cat todos-categories-with-marks)))
5548 (unless (or (todos-done-item-p)
5549 ;; Point is between todo and done items.
5550 (and (looking-at "^$") (not marked)))
5551 (let* ((date-string (calendar-date-string (calendar-current-date) t t))
5552 (time-string (if todos-always-add-time-string
5553 (concat " " (substring (current-time-string) 11 16))
5555 (done-prefix (concat "[" todos-done-string date-string time-string
5557 (comment (and arg (not marked) (read-string "Enter a comment: ")))
5560 (show-done (save-excursion
5561 (goto-char (point-min))
5562 (re-search-forward todos-done-string-start nil t)))
5563 (buffer-read-only nil)
5564 item done-item opoint)
5565 (and marked (goto-char (point-min)))
5567 ;; Stop looping when we hit the empty line below the last
5568 ;; todo item (this is eobp if only done items are hidden).
5569 (while (not (looking-at "^$")) ;(not (eobp))
5570 (if (or (not marked) (and marked (todos-marked-item-p)))
5572 (setq item (todos-item-string))
5573 (setq done-item (cond (marked
5574 (concat done-item done-prefix item "\n"))
5576 (concat done-prefix item " ["
5577 todos-comment-string
5580 (concat done-prefix item))))
5581 (setq item-count (1+ item-count))
5582 (when (todos-diary-item-p)
5583 (setq diary-count (1+ diary-count)))
5585 (unless marked (throw 'done nil)))
5586 (todos-forward-item))))
5588 ;; Chop off last newline of done item string.
5589 (setq done-item (substring done-item 0 -1))
5590 (setq todos-categories-with-marks
5591 (assq-delete-all cat todos-categories-with-marks)))
5595 (concat "^" (regexp-quote todos-category-done)) nil t)
5597 (when show-done (setq opoint (point)))
5598 (insert done-item "\n"))
5599 (todos-update-count 'todo (- item-count))
5600 (todos-update-count 'done item-count)
5601 (todos-update-count 'diary (- diary-count))
5602 (todos-update-categories-sexp)
5603 (let ((todos-show-with-done show-done))
5604 (todos-category-select)
5605 ;; When done items are shown, put cursor on first just done item.
5606 (when opoint (goto-char opoint)))))))
5608 (defun todos-done-item-add-edit-or-delete-comment (&optional arg)
5609 "Add a comment to this done item or edit an existing comment.
5610 With prefix ARG delete an existing comment."
5612 (when (todos-done-item-p)
5613 (let ((item (todos-item-string))
5615 (end (save-excursion (todos-item-end)))
5616 comment buffer-read-only)
5619 (if (re-search-forward (concat " \\["
5620 (regexp-quote todos-comment-string)
5621 ": \\([^]]+\\)\\]") end t)
5623 (when (y-or-n-p "Delete comment? ")
5624 (delete-region (match-beginning 0) (match-end 0)))
5625 (setq comment (read-string "Edit comment: "
5626 (cons (match-string 1) 1)))
5627 (replace-match comment nil nil nil 1))
5628 (setq comment (read-string "Enter a comment: "))
5629 ;; If user moved point during editing, make sure it moves back.
5632 (insert " [" todos-comment-string ": " comment "]"))))))
5634 (defun todos-item-undo ()
5635 "Restore this done item to the todo section of this category.
5636 If done item has a comment, ask whether to omit the comment from
5639 (let* ((cat (todos-current-category))
5640 (marked (assoc cat todos-categories-with-marks)))
5641 (when (or marked (todos-done-item-p))
5642 (let ((buffer-read-only)
5643 (bufmod (buffer-modified-p))
5645 (orig-mrk (progn (todos-item-start) (point-marker)))
5646 (orig-item (todos-item-string))
5650 start end item undone)
5651 (and marked (goto-char (point-min)))
5654 (if (or (not marked) (and marked (todos-marked-item-p)))
5655 (if (not (todos-done-item-p))
5656 (error "Only done items can be undone")
5658 ;; Find the end of the date string added upon tagging item as
5660 (setq start (search-forward "] "))
5661 (setq item-count (1+ item-count))
5662 (unless (looking-at (regexp-quote todos-nondiary-start))
5663 (setq diary-count (1+ diary-count)))
5664 (setq end (save-excursion (todos-item-end)))
5665 ;; Ask (once) whether to omit done item's comment. If
5666 ;; affirmed, omit subsequent comments without asking.
5667 (when (re-search-forward
5668 (concat " \\[" (regexp-quote todos-comment-string)
5669 ": [^]]+\\]") end t)
5670 (if (eq first 'first)
5672 (if (eq todos-undo-item-omit-comment 'ask)
5674 "Omit comment from restored item? ")
5676 (when todos-undo-item-omit-comment 'omit)))
5678 (when (eq first 'omit)
5679 (delete-region (match-beginning 0) (match-end 0))
5680 (setq end (point))))
5681 (setq item (concat item
5682 (buffer-substring-no-properties start end)
5683 (when marked "\n")))
5685 (unless marked (throw 'done nil)))
5686 (todos-forward-item))))
5689 (setq todos-categories-with-marks
5690 (assq-delete-all cat todos-categories-with-marks))
5691 ;; Insert undone items that were marked at end of todo item list.
5692 (goto-char (point-min))
5693 (re-search-forward (concat "^" (regexp-quote todos-category-done))
5697 (todos-update-count 'todo item-count)
5698 (todos-update-count 'done (- item-count))
5699 (when diary-count (todos-update-count 'diary diary-count))
5700 (todos-update-categories-sexp)
5701 (let ((todos-show-with-done (> (todos-get-count 'done) 0)))
5702 (todos-category-select)))
5703 ;; With an unmarked undone item, prompt for its priority. If user
5704 ;; cancels before setting new priority, then leave the done item
5708 (todos-set-item-priority item (todos-current-category) t)
5711 (todos-update-count 'todo 1)
5712 (todos-update-count 'done -1)
5713 (and (todos-diary-item-p) (todos-update-count 'diary 1))
5714 (todos-update-categories-sexp)
5715 (let ((todos-show-with-done (> (todos-get-count 'done) 0)))
5716 (todos-category-select)
5717 ;; Put the cursor on the undone item.
5718 (goto-char opoint)))
5720 (let ((todos-show-with-done t))
5722 (goto-char orig-mrk)
5723 (todos-insert-with-overlays orig-item)
5724 (set-buffer-modified-p bufmod)
5725 (todos-category-select))
5726 (goto-char opoint))))
5727 (set-marker orig-mrk nil)))))
5729 (defun todos-archive-done-item (&optional all)
5730 "Archive at least one done item in this category.
5732 If there are marked done items (and no marked todo items),
5733 archive all of these; otherwise, with non-nil argument ALL,
5734 archive all done items in this category; otherwise, archive the
5737 If the archive of this file does not exist, it is created. If
5738 this category does not exist in the archive, it is created."
5740 (when (eq major-mode 'todos-mode)
5741 (if (and all (zerop (todos-get-count 'done)))
5742 (message "No done items in this category")
5744 (let* ((cat (todos-current-category))
5745 (tbuf (current-buffer))
5746 (marked (assoc cat todos-categories-with-marks))
5747 (afile (concat (file-name-sans-extension
5748 todos-current-todos-file) ".toda"))
5749 (archive (if (file-exists-p afile)
5750 (find-file-noselect afile t)
5751 (get-buffer-create afile)))
5752 (item (and (todos-done-item-p) (concat (todos-item-string) "\n")))
5754 (opoint (unless (todos-done-item-p) (point)))
5755 marked-items beg end all-done
5760 (goto-char (point-min))
5762 (when (todos-marked-item-p)
5763 (if (not (todos-done-item-p))
5764 (throw 'end (message "Only done items can be archived"))
5766 (concat marked-items (todos-item-string) "\n"))
5767 (setq count (1+ count))))
5768 (todos-forward-item))))
5770 (if (y-or-n-p "Archive all done items in this category? ")
5773 (goto-char (point-min))
5776 (re-search-forward todos-done-string-start nil t)
5777 (match-beginning 0))
5778 end (if (re-search-forward
5779 (concat "^" (regexp-quote todos-category-beg))
5783 all-done (buffer-substring-no-properties beg end)
5784 count (todos-get-count 'done))
5785 ;; Restore starting point, unless it was on a done
5786 ;; item, since they will all be deleted.
5787 (when opoint (goto-char opoint))))
5789 (if (not (or marked all item))
5790 (throw 'end (message "Only done items can be archived"))
5791 (with-current-buffer archive
5792 (unless buffer-file-name (erase-buffer))
5793 (let (buffer-read-only)
5795 (goto-char (point-min))
5796 (if (and (re-search-forward
5797 (concat "^" (regexp-quote
5798 (concat todos-category-beg cat)) "$")
5800 (re-search-forward (regexp-quote todos-category-done)
5802 ;; Start of done items section in existing category.
5804 (todos-add-category nil cat)
5805 ;; Start of done items section in new category.
5806 (goto-char (point-max)))
5807 (insert (cond (marked marked-items)
5810 (todos-update-count 'done (if (or marked all) count 1) cat)
5811 (todos-update-categories-sexp)
5812 ;; If archive is new, save to file now (using write-region in
5813 ;; order not to get prompted for file to save to), to let
5814 ;; auto-mode-alist take effect below.
5815 (unless buffer-file-name
5816 (write-region nil nil afile)
5818 (with-current-buffer tbuf
5820 ;; If we're archiving all done items, can't
5821 ;; first archive item point was on, since
5822 ;; that will short-circuit the rest.
5823 (and item (not all)))
5824 (and marked (goto-char (point-min)))
5827 (if (or (and marked (todos-marked-item-p)) item)
5830 (todos-update-count 'done -1)
5831 (todos-update-count 'archived 1)
5832 ;; Don't leave point below last item.
5833 (and item (bolp) (eolp) (< (point-min) (point-max))
5834 (todos-backward-item))
5836 (throw 'done (setq item nil))))
5837 (todos-forward-item)))))
5841 ;; Make sure done items are accessible.
5843 (remove-overlays beg end)
5844 (delete-region beg end)
5845 (todos-update-count 'done (- count))
5846 (todos-update-count 'archived count)))))
5848 (setq todos-categories-with-marks
5849 (assq-delete-all cat todos-categories-with-marks)))
5850 (todos-update-categories-sexp)
5851 (todos-prefix-overlays)))
5853 (todos-category-number cat)
5854 (todos-category-select)
5855 (split-window-below)
5856 (set-window-buffer (selected-window) tbuf)
5857 ;; Make todo file current to select category.
5858 (find-file (buffer-file-name tbuf))
5859 ;; Make sure done item separator is hidden (if done items
5860 ;; were initially visible).
5861 (let (todos-show-with-done) (todos-category-select)))))))
5863 (defun todos-archive-category-done-items ()
5864 "Move all done items in this category to its archive."
5866 (todos-archive-done-item t))
5868 (defun todos-unarchive-items (&optional all)
5869 "Unarchive at least one item in this archive category.
5871 If there are marked items, unarchive all of these; otherwise,
5872 with non-nil argument ALL, unarchive all items in this category;
5873 otherwise, unarchive the item at point.
5875 Unarchived items are restored as done items to the corresponding
5876 category in the Todos file, inserted at the end of done section.
5877 If all items in the archive category were restored, the category
5878 is deleted from the archive. If this was the only category in the
5879 archive, the archive file is deleted."
5881 (when (eq major-mode 'todos-archive-mode)
5883 (let* ((cat (todos-current-category))
5884 (tbuf (find-file-noselect
5885 (concat (file-name-sans-extension todos-current-todos-file)
5887 (marked (assoc cat todos-categories-with-marks))
5888 (item (concat (todos-item-string) "\n"))
5889 (all-items (when all (buffer-substring-no-properties
5890 (point-min) (point-max))))
5891 (all-count (when all (todos-get-count 'done)))
5892 marked-items marked-count
5896 (goto-char (point-min))
5898 (when (todos-marked-item-p)
5899 (concat marked-items (todos-item-string) "\n")
5900 (setq marked-count (1+ marked-count)))
5901 (todos-forward-item))))
5902 ;; Restore items to end of category's done section and update counts.
5903 (with-current-buffer tbuf
5904 (let (buffer-read-only)
5906 (goto-char (point-min))
5907 (re-search-forward (concat "^" (regexp-quote
5908 (concat todos-category-beg cat)) "$")
5910 ;; Go to end of category's done section.
5911 (if (re-search-forward (concat "^" (regexp-quote todos-category-beg))
5913 (goto-char (match-beginning 0))
5914 (goto-char (point-max)))
5916 (insert marked-items)
5917 (todos-update-count 'done marked-count cat)
5918 (todos-update-count 'archived (- marked-count) cat))
5921 (todos-update-count 'done all-count cat)
5922 (todos-update-count 'archived (- all-count) cat))
5925 (todos-update-count 'done 1 cat)
5926 (todos-update-count 'archived -1 cat)))
5927 (todos-update-categories-sexp)))
5928 ;; Delete restored items from archive.
5929 (cond ((or marked item)
5930 (and marked (goto-char (point-min)))
5933 (if (or (and marked (todos-marked-item-p)) item)
5936 ;; Don't leave point below last item.
5937 (and item (bolp) (eolp) (< (point-min) (point-max))
5938 (todos-backward-item))
5940 (throw 'done (setq item nil))))
5941 (todos-forward-item))))
5942 (todos-update-count 'done (if marked (- marked-count) -1) cat))
5944 (remove-overlays (point-min) (point-max))
5945 (delete-region (point-min) (point-max))))
5946 ;; If that was the last category in the archive, delete the whole file.
5947 (if (= (length todos-categories) 1)
5949 (delete-file todos-current-todos-file)
5950 ;; Don't bother confirming killing the archive buffer.
5951 (set-buffer-modified-p nil)
5953 ;; Otherwise, if the archive category is now empty, delete it.
5954 (when (eq (point-min) (point-max))
5956 (let ((beg (re-search-backward
5957 (concat "^" (regexp-quote todos-category-beg) cat "$")
5959 (end (if (re-search-forward
5960 (concat "^" (regexp-quote todos-category-beg))
5964 (remove-overlays beg end)
5965 (delete-region beg end)
5966 (setq todos-categories (delete (assoc cat todos-categories)
5968 (todos-update-categories-sexp))))
5969 ;; Visit category in Todos file and show restored done items.
5970 (let ((tfile (buffer-file-name tbuf))
5971 (todos-show-with-done t))
5972 (set-window-buffer (selected-window)
5973 (set-buffer (find-file-noselect tfile)))
5974 (todos-category-number cat)
5976 (message "Items unarchived."))))))
5978 (defun todos-unarchive-category ()
5979 "Unarchive all items in this category. See `todos-unarchive-items'."
5981 (todos-unarchive-items t))
5985 ;;; todos.el ends here
5987 ;; FIXME: remove when part of Emacs
5988 ;; ---------------------------------------------------------------------------
5989 (add-to-list 'auto-mode-alist '("\\.todo\\'" . todos-mode))
5990 (add-to-list 'auto-mode-alist '("\\.toda\\'" . todos-archive-mode))
5991 (add-to-list 'auto-mode-alist '("\\.todt\\'" . todos-filtered-items-mode))
5993 ;;; Addition to calendar.el
5994 ;; FIXME: autoload when key-binding is defined in calendar.el
5995 (defun todos-insert-item-from-calendar (&optional arg)
5998 (setq todos-date-from-calendar
5999 (calendar-date-string (calendar-cursor-to-date t) t t))
6002 (todos-insert-item arg nil nil todos-date-from-calendar))
6004 (define-key calendar-mode-map "it" 'todos-insert-item-from-calendar)
6006 ;;; necessitated adaptations to diary-lib.el
6008 ;; (defun diary-goto-entry (button)
6009 ;; "Jump to the diary entry for the BUTTON at point."
6010 ;; (let* ((locator (button-get button 'locator))
6011 ;; (marker (car locator))
6012 ;; markbuf file opoint)
6013 ;; ;; If marker pointing to diary location is valid, use that.
6014 ;; (if (and marker (setq markbuf (marker-buffer marker)))
6016 ;; (pop-to-buffer markbuf)
6017 ;; (goto-char (marker-position marker)))
6018 ;; ;; Marker is invalid (eg buffer has been killed, as is the case with
6019 ;; ;; included diary files).
6020 ;; (or (and (setq file (cadr locator))
6021 ;; (file-exists-p file)
6022 ;; (find-file-other-window file)
6024 ;; (when (eq major-mode (default-value 'major-mode)) (diary-mode))
6025 ;; (when (eq major-mode 'todos-mode) (widen))
6026 ;; (goto-char (point-min))
6027 ;; (when (re-search-forward (format "%s.*\\(%s\\)"
6028 ;; (regexp-quote (nth 2 locator))
6029 ;; (regexp-quote (nth 3 locator)))
6031 ;; (goto-char (match-beginning 1))
6032 ;; (when (eq major-mode 'todos-mode)
6033 ;; (setq opoint (point))
6034 ;; (re-search-backward (concat "^"
6035 ;; (regexp-quote todos-category-beg)
6038 ;; (todos-category-number (match-string 1))
6039 ;; (todos-category-select)
6040 ;; (goto-char opoint)))))
6041 ;; (message "Unable to locate this diary entry")))))