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 (car (funcall todos-files-function))
75 "Todos file visited by first session invocation of `todos-show'."
76 :type `(radio ,@(mapcar (lambda (f) (list 'const f))
77 (mapcar 'todos-short-file-name
78 (funcall todos-files-function))))
81 ;; FIXME: is there a better alternative to this?
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-visit-files-commands (list 'find-file 'dired-find-file)
108 "List of file finding commands for `todos-display-as-todos-file'.
109 Invoking these commands to visit a Todos or Todos Archive file
110 calls `todos-show' or `todos-show-archive', so that the file is
111 displayed correctly."
112 :type '(repeat function)
115 (defcustom todos-initial-file "Todo"
116 "Default file name offered on adding first Todos file."
120 (defcustom todos-initial-category "Todo"
121 "Default category name offered on initializing a new Todos file."
125 (defcustom todos-display-categories-first nil
126 "Non-nil to display category list on first visit to a Todos file."
130 (defcustom todos-prefix ""
131 "String prefixed to todo items for visual distinction."
133 :initialize 'custom-initialize-default
134 :set 'todos-reset-prefix
137 (defcustom todos-number-priorities t
138 "Non-nil to prefix items with consecutively increasing integers.
139 These reflect the priorities of the items in each category."
141 :initialize 'custom-initialize-default
142 :set 'todos-reset-prefix
145 (defun todos-reset-prefix (symbol value)
146 "The :set function for `todos-prefix' and `todos-number-priorities'."
147 (let ((oldvalue (symbol-value symbol))
148 (files (append todos-files todos-archives)))
149 (custom-set-default symbol value)
150 (when (not (equal value oldvalue))
152 (with-current-buffer (find-file-noselect f)
153 (save-window-excursion
157 (goto-char (point-min))
159 (remove-overlays (point) (point)); 'before-string prefix)
161 ;; Activate the new setting (save-restriction does not help).
162 (save-excursion (todos-category-select))))))))
164 (defcustom todos-done-separator-string "_"
165 "String for generating `todos-done-separator'.
167 If the string consists of a single character,
168 `todos-done-separator' will be the string made by repeating this
169 character for the width of the window, and the length is
170 automatically recalculated when the window width changes. If the
171 string consists of more (or less) than one character, it will be
172 the value of `todos-done-separator'."
174 :initialize 'custom-initialize-default
175 :set 'todos-reset-done-separator-string
178 (defun todos-reset-done-separator-string (symbol value)
179 "The :set function for `todos-done-separator-string'."
180 (let ((oldvalue (symbol-value symbol))
181 (files todos-file-buffers)
182 (sep todos-done-separator))
183 (custom-set-default symbol value)
184 (setq todos-done-separator (todos-done-separator))
185 (when (= 1 (length value))
186 (todos-reset-done-separator sep))))
188 (defcustom todos-done-string "DONE "
189 "Identifying string appended to the front of done todos items."
191 :initialize 'custom-initialize-default
192 :set 'todos-reset-done-string
195 (defun todos-reset-done-string (symbol value)
196 "The :set function for user option `todos-done-string'."
197 (let ((oldvalue (symbol-value symbol))
198 (files (append todos-files todos-archives)))
199 (custom-set-default symbol value)
200 ;; Need to reset this to get font-locking right.
201 (setq todos-done-string-start
202 (concat "^\\[" (regexp-quote todos-done-string)))
203 (when (not (equal value oldvalue))
205 (with-current-buffer (find-file-noselect f)
206 (let (buffer-read-only)
208 (goto-char (point-min))
210 (if (re-search-forward
211 (concat "^" (regexp-quote todos-nondiary-start)
212 "\\(" (regexp-quote oldvalue) "\\)")
214 (replace-match value t t nil 1)
216 (todos-category-select)))))))
218 (defcustom todos-comment-string "COMMENT"
219 "String inserted before optional comment appended to done item."
221 :initialize 'custom-initialize-default
222 :set 'todos-reset-comment-string
225 (defun todos-reset-comment-string (symbol value)
226 "The :set function for user option `todos-comment-string'."
227 (let ((oldvalue (symbol-value symbol))
228 (files (append todos-files todos-archives)))
229 (custom-set-default symbol value)
230 (when (not (equal value oldvalue))
232 (with-current-buffer (find-file-noselect f)
233 (let (buffer-read-only)
236 (goto-char (point-min))
238 (if (re-search-forward
240 "\\[\\(" (regexp-quote oldvalue) "\\): [^]]*\\]")
242 (replace-match value t t nil 1)
244 (todos-category-select))))))))
246 (defcustom todos-show-with-done nil
247 "Non-nil to display done items in all categories."
251 (defun todos-mode-line-control (cat)
252 "Return a mode line control for Todos buffers.
253 Argument CAT is the name of the current Todos category.
254 This function is the value of the user variable
255 `todos-mode-line-function'."
256 (let ((file (todos-short-file-name todos-current-todos-file)))
257 (format "%s category %d: %s" file todos-category-number cat)))
259 (defcustom todos-mode-line-function 'todos-mode-line-control
260 "Function that returns a mode line control for Todos buffers.
261 The function expects one argument holding the name of the current
262 Todos category. The resulting control becomes the local value of
263 `mode-line-buffer-identification' in each Todos buffer."
267 (defcustom todos-skip-archived-categories nil
268 "Non-nil to skip categories with only archived items when browsing.
270 Moving by category todos or archive file (with
271 \\[todos-forward-category] and \\[todos-backward-category]) skips
272 categories that contain only archived items. Other commands
273 still recognize these categories. In Todos Categories
274 mode (reached with \\[todos-display-categories]) these categories
275 shown in `todos-archived-only' face and clicking them in Todos
276 Categories mode visits the archived categories."
280 (defcustom todos-use-only-highlighted-region t
281 "Non-nil to enable inserting only highlighted region as new item."
285 (defcustom todos-include-in-diary nil
286 "Non-nil to allow new Todo items to be included in the diary."
290 (defcustom todos-diary-nonmarking nil
291 "Non-nil to insert new Todo diary items as nonmarking by default.
292 This appends `diary-nonmarking-symbol' to the front of an item on
293 insertion provided it doesn't begin with `todos-nondiary-marker'."
297 (defcustom todos-nondiary-marker '("[" "]")
298 "List of strings surrounding item date to block diary inclusion.
299 The first string is inserted before the item date and must be a
300 non-empty string that does not match a diary date in order to
301 have its intended effect. The second string is inserted after
303 :type '(list string string)
305 :initialize 'custom-initialize-default
306 :set 'todos-reset-nondiary-marker)
308 (defun todos-reset-nondiary-marker (symbol value)
309 "The :set function for user option `todos-nondiary-marker'."
310 (let ((oldvalue (symbol-value symbol))
311 (files (append todos-files todos-archives)))
312 (custom-set-default symbol value)
313 ;; Need to reset these to get font-locking right.
314 (setq todos-nondiary-start (nth 0 todos-nondiary-marker)
315 todos-nondiary-end (nth 1 todos-nondiary-marker)
316 todos-date-string-start
317 ;; See comment in defvar of `todos-date-string-start'.
318 (concat "^\\(" (regexp-quote todos-nondiary-start) "\\|"
319 (regexp-quote diary-nonmarking-symbol) "\\)?"))
320 (when (not (equal value oldvalue))
322 (with-current-buffer (find-file-noselect f)
323 (let (buffer-read-only)
325 (goto-char (point-min))
327 (if (re-search-forward
328 (concat "^\\(" todos-done-string-start "[^][]+] \\)?"
329 "\\(?1:" (regexp-quote (car oldvalue))
330 "\\)" todos-date-pattern "\\( "
331 diary-time-regexp "\\)?\\(?2:"
332 (regexp-quote (cadr oldvalue)) "\\)")
335 (replace-match (nth 0 value) t t nil 1)
336 (replace-match (nth 1 value) t t nil 2))
338 (todos-category-select)))))))
340 (defcustom todos-always-add-time-string nil
341 "Non-nil adds current time to a new item's date header by default.
342 When the Todos insertion commands have a non-nil \"maybe-notime\"
343 argument, this reverses the effect of
344 `todos-always-add-time-string': if t, these commands omit the
345 current time, if nil, they include it."
349 (defcustom todos-completion-ignore-case nil
350 "Non-nil means case of user input in `todos-read-*' is ignored."
354 (defcustom todos-highlight-item nil
355 "Non-nil means highlight items at point."
357 :initialize 'custom-initialize-default
358 :set 'todos-reset-highlight-item
361 (defun todos-reset-highlight-item (symbol value)
362 "The :set function for `todos-highlight-item'."
363 (let ((oldvalue (symbol-value symbol))
364 (files (append todos-files todos-archives)))
365 (custom-set-default symbol value)
366 (when (not (equal value oldvalue))
368 (let ((buf (find-buffer-visiting f)))
370 (with-current-buffer buf
374 (hl-line-mode -1)))))))))
376 (defcustom todos-wrap-lines t
377 "Non-nil to wrap long lines via `todos-line-wrapping-function'."
381 (defcustom todos-line-wrapping-function 'todos-wrap-and-indent
382 "Line wrapping function used with non-nil `todos-wrap-lines'."
386 (defun todos-wrap-and-indent ()
387 "Use word wrapping on long lines and indent with a wrap prefix.
388 The amount of indentation is given by user option
389 `todos-indent-to-here'."
390 (set (make-local-variable 'word-wrap) t)
391 (set (make-local-variable 'wrap-prefix) (make-string todos-indent-to-here 32))
392 (unless (member '(continuation) fringe-indicator-alist)
393 (push '(continuation) fringe-indicator-alist)))
395 ;; FIXME: :set function (otherwise change takes effect only after killing and
397 (defcustom todos-indent-to-here 6
398 "Number of spaces `todos-line-wrapping-function' indents to."
399 :type '(integer :validate
401 (unless (> (widget-value widget) 0)
402 (widget-put widget :error
403 "Invalid value: must be a positive integer")
407 (defun todos-indent ()
408 "Indent from point to `todos-indent-to-here'."
409 (indent-to todos-indent-to-here todos-indent-to-here))
411 (defcustom todos-todo-mode-date-time-regexp
412 (concat "\\(?1:[0-9]\\{4\\}\\)-\\(?2:[0-9]\\{2\\}\\)-"
413 "\\(?3:[0-9]\\{2\\}\\) \\(?4:[0-9]\\{2\\}:[0-9]\\{2\\}\\)")
414 "Regexp matching legacy todo-mode.el item date-time strings.
415 In order for `todos-convert-legacy-files' to correctly convert this
416 string to the current Todos format, the regexp must contain four
417 explicitly numbered groups (see `(elisp) Regexp Backslash'),
418 where group 1 matches a string for the year, group 2 a string for
419 the month, group 3 a string for the day and group 4 a string for
420 the time. The default value converts date-time strings built
421 using the default value of `todo-time-string-format' from
426 (defcustom todos-print-function 'ps-print-buffer-with-faces
427 "Function called to print buffer content; see `todos-print'."
431 (defgroup todos-filtered nil
432 "User options for Todos Filter Items mode."
436 (defcustom todos-filtered-items-buffer "Todos filtered items"
437 "Initial name of buffer in Todos Filter Items mode."
439 :group 'todos-filtered)
441 (defcustom todos-top-priorities-buffer "Todos top priorities"
442 "Buffer type string for `todos-filtered-buffer-name'."
444 :group 'todos-filtered)
446 (defcustom todos-diary-items-buffer "Todos diary items"
447 "Buffer type string for `todos-filtered-buffer-name'."
449 :group 'todos-filtered)
451 (defcustom todos-regexp-items-buffer "Todos regexp items"
452 "Buffer type string for `todos-filtered-buffer-name'."
454 :group 'todos-filtered)
456 (defcustom todos-priorities-rules nil
457 "List of rules giving how many items `todos-top-priorities' shows.
458 This variable should be set interactively by
459 `\\[todos-set-top-priorities-in-file]' or
460 `\\[todos-set-top-priorities-in-category]'.
462 Each rule is a list of the form (FILE NUM ALIST), where FILE is a
463 member of `todos-files', NUM is a number specifying the default
464 number of top priority items for each category in that file, and
465 ALIST, when non-nil, consists of conses of a category name in
466 FILE and a number specifying the default number of top priority
467 items in that category, which overrides NUM."
469 :group 'todos-filtered)
471 (defcustom todos-show-priorities 1
472 "Default number of top priorities shown by `todos-top-priorities'."
474 :group 'todos-filtered)
476 (defcustom todos-filter-files nil
477 "List of default files for multifile item filtering."
478 :type `(set ,@(mapcar (lambda (f) (list 'const f))
479 (mapcar 'todos-short-file-name
480 (funcall todos-files-function))))
481 :group 'todos-filtered)
483 ;; FIXME: is there a better alternative to this?
484 (defun todos-reevaluate-filter-files-defcustom ()
485 "Reevaluate defcustom of `todos-filter-files'.
486 Called after adding or deleting a Todos file."
487 (eval (defcustom todos-filter-files nil
488 "List of files for multifile item filtering."
489 :type `(set ,@(mapcar (lambda (f) (list 'const f))
490 (mapcar 'todos-short-file-name
491 (funcall todos-files-function))))
494 (defcustom todos-filter-done-items nil
495 "Non-nil to include done items when processing regexp filters.
496 Done items from corresponding archive files are also included."
498 :group 'todos-filtered)
500 (defgroup todos-categories nil
501 "User options for Todos Categories mode."
505 (defcustom todos-categories-category-label "Category"
506 "Category button label in Todos Categories mode."
508 :group 'todos-categories)
510 (defcustom todos-categories-todo-label "Todo"
511 "Todo button label in Todos Categories mode."
513 :group 'todos-categories)
515 (defcustom todos-categories-diary-label "Diary"
516 "Diary button label in Todos Categories mode."
518 :group 'todos-categories)
520 (defcustom todos-categories-done-label "Done"
521 "Done button label in Todos Categories mode."
523 :group 'todos-categories)
525 (defcustom todos-categories-archived-label "Archived"
526 "Archived button label in Todos Categories mode."
528 :group 'todos-categories)
530 (defcustom todos-categories-totals-label "Totals"
531 "String to label total item counts in Todos Categories mode."
533 :group 'todos-categories)
535 (defcustom todos-categories-number-separator " | "
536 "String between number and category in Todos Categories mode.
537 This separates the number from the category name in the default
538 categories display according to priority."
540 :group 'todos-categories)
542 (defcustom todos-categories-align 'center
543 "Alignment of category names in Todos Categories mode."
544 :type '(radio (const left) (const center) (const right))
545 :group 'todos-categories)
547 ;; ---------------------------------------------------------------------------
548 ;;; Faces and font-locking
550 (defgroup todos-faces nil
551 "Faces for the Todos modes."
555 (defface todos-prefix-string
556 ;; '((t :inherit font-lock-constant-face))
557 '((((class grayscale) (background light))
558 (:foreground "LightGray" :weight bold :underline t))
559 (((class grayscale) (background dark))
560 (:foreground "Gray50" :weight bold :underline t))
561 (((class color) (min-colors 88) (background light)) (:foreground "dark cyan"))
562 (((class color) (min-colors 88) (background dark)) (:foreground "Aquamarine"))
563 (((class color) (min-colors 16) (background light)) (:foreground "CadetBlue"))
564 (((class color) (min-colors 16) (background dark)) (:foreground "Aquamarine"))
565 (((class color) (min-colors 8)) (:foreground "magenta"))
566 (t (:weight bold :underline t)))
567 "Face for Todos prefix string."
571 ;; '((t :inherit font-lock-warning-face))
575 (:weight bold :foreground "Red1"))
579 (:weight bold :foreground "Pink"))
583 (:weight bold :foreground "Red1"))
587 (:weight bold :foreground "Pink"))
592 (:weight bold :inverse-video t)))
593 "Face for marks on Todos items."
596 (defface todos-button
597 ;; '((t :inherit widget-field))
599 (:foreground "black" :background "yellow3"))
600 (((class grayscale color)
602 (:background "gray85"))
603 (((class grayscale color)
605 (:background "dim gray"))
608 "Face for buttons in todos-display-categories."
611 (defface todos-sorted-column
614 (:background "grey85"))
617 ;; FIXME: make foreground dark, else illegible
618 (:background "grey10"))
620 (:background "gray")))
621 "Face for buttons in todos-display-categories."
624 (defface todos-archived-only
625 ;; '((t (:inherit (shadow))))
628 (:foreground "grey50"))
631 (:foreground "grey70"))
633 (:foreground "gray")))
634 "Face for archived-only categories in todos-display-categories."
637 (defface todos-search
638 ;; '((t :inherit match))
642 (:background "yellow1"))
646 (:background "RoyalBlue3"))
650 (:foreground "black" :background "yellow"))
654 (:foreground "white" :background "blue"))
659 (:background "gray")))
660 "Face for matches found by todos-search."
663 (defface todos-diary-expired
664 ;; '((t :inherit font-lock-warning-face))
667 (:weight bold :foreground "DarkOrange"))
669 (:weight bold :foreground "yellow"))
672 "Face for expired dates of diary items."
674 (defvar todos-diary-expired-face 'todos-diary-expired)
677 '((t :inherit diary))
678 "Face for the date string of a Todos item."
680 (defvar todos-date-face 'todos-date)
683 '((t :inherit diary-time))
684 "Face for the time string of a Todos item."
686 (defvar todos-time-face 'todos-time)
689 ;; '((t :inherit font-lock-comment-face))
690 '((((class grayscale)
692 (:slant italic :weight bold :foreground "DimGray"))
695 (:slant italic :weight bold :foreground "LightGray"))
699 (:foreground "Firebrick"))
703 (:foreground "chocolate1"))
711 (:foreground "red1"))
719 (:foreground "yellow"))
721 (:slant italic :weight bold)))
722 "Face for done Todos item header string."
724 (defvar todos-done-face 'todos-done)
726 (defface todos-comment
727 '((t :inherit todos-done))
728 "Face for comments appended to done Todos items."
730 (defvar todos-comment-face 'todos-comment)
732 (defface todos-done-sep
733 ;; '((t :inherit font-lock-type-face))
734 '((((class grayscale)
736 (:weight bold :foreground "Gray90"))
739 (:weight bold :foreground "DimGray"))
743 (:foreground "ForestGreen"))
747 (:foreground "PaleGreen"))
751 (:foreground "ForestGreen"))
755 (:foreground "PaleGreen"))
758 (:foreground "green"))
760 (:underline t :weight bold)))
761 "Face for separator string bewteen done and not done Todos items."
763 (defvar todos-done-sep-face 'todos-done-sep)
765 (defun todos-date-string-matcher (lim)
766 "Search for Todos date string within LIM for font-locking."
768 (concat todos-date-string-start "\\(?1:" todos-date-pattern "\\)") lim t))
770 (defun todos-time-string-matcher (lim)
771 "Search for Todos time string within LIM for font-locking."
772 (re-search-forward (concat todos-date-string-start todos-date-pattern
773 " \\(?1:" diary-time-regexp "\\)") lim t))
775 (defun todos-nondiary-marker-matcher (lim)
776 "Search for Todos nondiary markers within LIM for font-locking."
777 (re-search-forward (concat "^\\(?1:" (regexp-quote todos-nondiary-start) "\\)"
778 todos-date-pattern "\\(?: " diary-time-regexp
779 "\\)?\\(?2:" (regexp-quote todos-nondiary-end) "\\)")
782 (defun todos-diary-nonmarking-matcher (lim)
783 "Search for diary nonmarking symbol within LIM for font-locking."
784 (re-search-forward (concat "^\\(?1:" (regexp-quote diary-nonmarking-symbol)
785 "\\)" todos-date-pattern) lim t))
787 (defun todos-diary-expired-matcher (lim)
788 "Search for expired diary item date within LIM for font-locking."
789 (when (re-search-forward (concat "^\\(?:"
790 (regexp-quote diary-nonmarking-symbol)
791 "\\)?\\(?1:" todos-date-pattern "\\) \\(?2:"
792 diary-time-regexp "\\)?") lim t)
793 (let* ((date (match-string-no-properties 1))
794 (time (match-string-no-properties 2))
795 ;; Function days-between requires a non-empty time string.
796 (date-time (concat date " " (or time "00:00"))))
797 (or (and (not (string-match ".+day\\|\\*" date))
798 (< (days-between date-time (current-time-string)) 0))
799 (todos-diary-expired-matcher lim)))))
801 (defun todos-done-string-matcher (lim)
802 "Search for Todos done header within LIM for font-locking."
803 (re-search-forward (concat todos-done-string-start
807 (defun todos-comment-string-matcher (lim)
808 "Search for Todos done comment within LIM for font-locking."
809 (re-search-forward (concat "\\[\\(?1:" todos-comment-string "\\):")
812 ;; (defun todos-category-string-matcher (lim)
813 ;; "Search for Todos category name within LIM for font-locking.
814 ;; This is for fontifying category names appearing in Todos filter
816 ;; (if (eq major-mode 'todos-filtered-items-mode)
817 ;; (re-search-forward
818 ;; (concat "^\\(?:" todos-date-string-start "\\)?" todos-date-pattern
819 ;; "\\(?: " diary-time-regexp "\\)?\\(?:"
820 ;; (regexp-quote todos-nondiary-end) "\\)? \\(?1:\\[.+\\]\\)")
823 (defun todos-category-string-matcher-1 (lim)
824 "Search for Todos category name within LIM for font-locking.
825 This is for fontifying category names appearing in Todos filter
826 mode following done items."
827 (if (eq major-mode 'todos-filtered-items-mode)
828 (re-search-forward (concat todos-done-string-start todos-date-pattern
829 "\\(?: " diary-time-regexp
830 ;; Use non-greedy operator to prevent
831 ;; capturing possible following non-diary
833 "\\)?] \\(?1:\\[.+?\\]\\)")
836 (defun todos-category-string-matcher-2 (lim)
837 "Search for Todos category name within LIM for font-locking.
838 This is for fontifying category names appearing in Todos filter
839 mode following todo (not done) items."
840 (if (eq major-mode 'todos-filtered-items-mode)
841 (re-search-forward (concat todos-date-string-start todos-date-pattern
842 "\\(?: " diary-time-regexp "\\)?\\(?:"
843 (regexp-quote todos-nondiary-end)
844 "\\)? \\(?1:\\[.+\\]\\)")
847 (defvar todos-font-lock-keywords
849 '(todos-nondiary-marker-matcher 1 todos-done-sep-face t)
850 '(todos-nondiary-marker-matcher 2 todos-done-sep-face t)
851 ;; This is the face used by diary-lib.el.
852 '(todos-diary-nonmarking-matcher 1 font-lock-constant-face t)
853 '(todos-date-string-matcher 1 todos-date-face t)
854 '(todos-time-string-matcher 1 todos-time-face t)
855 '(todos-done-string-matcher 0 todos-done-face t)
856 '(todos-comment-string-matcher 1 todos-done-face t)
857 ;; '(todos-category-string-matcher 1 todos-done-sep-face t)
858 '(todos-category-string-matcher-1 1 todos-done-sep-face t t)
859 '(todos-category-string-matcher-2 1 todos-done-sep-face t t)
860 '(todos-diary-expired-matcher 1 todos-diary-expired-face t)
861 '(todos-diary-expired-matcher 2 todos-diary-expired-face t t)
863 "Font-locking for Todos modes.")
865 ;; ---------------------------------------------------------------------------
866 ;;; Todos mode local variables and hook functions
868 (defvar todos-current-todos-file nil
869 "Variable holding the name of the currently active Todos file.")
871 (defun todos-show-current-file ()
872 "Visit current instead of default Todos file with `todos-show'.
873 This function is added to `pre-command-hook' when user option
874 `todos-show-current-file' is set to non-nil."
875 (setq todos-global-current-todos-file todos-current-todos-file))
877 (defun todos-display-as-todos-file ()
878 "Show Todos files correctly when visited from outside of Todos mode."
879 (and (member this-command todos-visit-files-commands)
880 (= (- (point-max) (point-min)) (buffer-size))
881 (member major-mode '(todos-mode todos-archive-mode))
882 (todos-category-select)))
884 (defun todos-add-to-buffer-list ()
885 "Add name of just visited Todos file to `todos-file-buffers'.
886 This function is added to `find-file-hook' in Todos mode."
887 (let ((filename (file-truename (buffer-file-name))))
888 (when (member filename todos-files)
889 (add-to-list 'todos-file-buffers filename))))
891 (defun todos-update-buffer-list ()
892 "Make current Todos mode buffer file car of `todos-file-buffers'.
893 This function is added to `post-command-hook' in Todos mode."
894 (let ((filename (file-truename (buffer-file-name))))
895 (unless (eq (car todos-file-buffers) filename)
896 (setq todos-file-buffers
897 (cons filename (delete filename todos-file-buffers))))))
899 (defun todos-reset-global-current-todos-file ()
900 "Update the value of `todos-global-current-todos-file'.
901 This becomes the latest existing Todos file or, if there is none,
902 the value of `todos-default-todos-file'.
903 This function is added to `kill-buffer-hook' in Todos mode."
904 (let ((filename (file-truename (buffer-file-name))))
905 (setq todos-file-buffers (delete filename todos-file-buffers))
906 (setq todos-global-current-todos-file (or (car todos-file-buffers)
907 todos-default-todos-file))))
909 (defvar todos-categories nil
910 "Alist of categories in the current Todos file.
911 The elements are cons cells whose car is a category name and
912 whose cdr is a vector of the category's item counts. These are,
913 in order, the numbers of todo items, of todo items included in
914 the Diary, of done items and of archived items.")
916 (defvar todos-categories-with-marks nil
917 "Alist of categories and number of marked items they contain.")
919 (defvar todos-category-number 1
920 "Variable holding the number of the current Todos category.
921 Todos categories are numbered starting from 1.")
923 (defvar todos-first-visit t
924 "Non-nil if first display of this file in the current session.
925 See `todos-display-categories-first'.")
927 (defvar todos-show-done-only nil
928 "If non-nil display only done items in current category.
929 Set by the command `todos-show-done-only' and used by
930 `todos-category-select'.")
932 ;; ---------------------------------------------------------------------------
933 ;;; Global variables and helper functions
935 (defvar todos-files (funcall todos-files-function)
936 "List of truenames of user's Todos files.")
938 (defvar todos-archives (funcall todos-files-function t)
939 "List of truenames of user's Todos archives.")
941 (defvar todos-file-buffers nil
942 "List of file names of live Todos mode buffers.")
944 (defvar todos-global-current-todos-file nil
945 "Variable holding name of current Todos file.
946 Used by functions called from outside of Todos mode to visit the
947 current Todos file rather than the default Todos file (i.e. when
948 users option `todos-show-current-file' is non-nil).")
950 (defun todos-reevaluate-defcustoms ()
951 "Reevaluate defcustoms that provide choice list of Todos files."
952 (custom-set-default 'todos-default-todos-file
953 (symbol-value 'todos-default-todos-file))
954 (todos-reevaluate-default-file-defcustom)
955 (custom-set-default 'todos-filter-files (symbol-value 'todos-filter-files))
956 (todos-reevaluate-filter-files-defcustom))
958 (defvar todos-edit-buffer "*Todos Edit*"
959 "Name of current buffer in Todos Edit mode.")
961 (defvar todos-categories-buffer "*Todos Categories*"
962 "Name of buffer in Todos Categories mode.")
964 (defvar todos-print-buffer "*Todos Print*"
965 "Name of buffer containing printable Todos text.")
967 (defvar todos-date-pattern
968 (let ((dayname (diary-name-pattern calendar-day-name-array nil t)))
969 (concat "\\(?:" dayname "\\|"
971 ;; FIXME: how to choose between abbreviated and unabbreviated
973 (monthname (format "\\(?:%s\\|\\*\\)"
975 calendar-month-name-array
976 calendar-month-abbrev-array t)))
977 (month "\\(?:[0-9]+\\|\\*\\)")
978 (day "\\(?:[0-9]+\\|\\*\\)")
979 (year "-?\\(?:[0-9]+\\|\\*\\)"))
980 (mapconcat 'eval calendar-date-display-form ""))
982 "Regular expression matching a Todos date header.")
984 (defvar todos-nondiary-start (nth 0 todos-nondiary-marker)
985 "String inserted before item date to block diary inclusion.")
987 (defvar todos-nondiary-end (nth 1 todos-nondiary-marker)
988 "String inserted after item date matching `todos-nondiary-start'.")
990 ;; By itself this matches anything, because of the `?'; however, it's only
991 ;; used in the context of `todos-date-pattern' (but Emacs Lisp lacks
993 (defvar todos-date-string-start
994 (concat "^\\(" (regexp-quote todos-nondiary-start) "\\|"
995 (regexp-quote diary-nonmarking-symbol) "\\)?")
996 "Regular expression matching part of item header before the date.")
998 (defvar todos-done-string-start
999 (concat "^\\[" (regexp-quote todos-done-string))
1000 "Regular expression matching start of done item.")
1002 (defun todos-category-number (cat)
1003 "Return the number of category CAT in this Todos file.
1004 The buffer-local variable `todos-category-number' holds this
1005 number as its value."
1006 (let ((categories (mapcar 'car todos-categories)))
1007 (setq todos-category-number
1008 ;; Increment by one, so that the highest priority category in Todos
1009 ;; Categories mode is numbered one rather than zero.
1010 (1+ (- (length categories)
1011 (length (member cat categories)))))))
1013 (defun todos-current-category ()
1014 "Return the name of the current category."
1015 (car (nth (1- todos-category-number) todos-categories)))
1017 (defconst todos-category-beg "--==-- "
1018 "String marking beginning of category (inserted with its name).")
1020 (defconst todos-category-done "==--== DONE "
1021 "String marking beginning of category's done items.")
1023 (defun todos-done-separator ()
1024 "Return string used as value of variable `todos-done-separator'."
1025 (let ((sep todos-done-separator-string))
1026 (if (= 1 (length sep))
1027 (make-string (window-width) (string-to-char sep))
1028 todos-done-separator-string)))
1030 (defvar todos-done-separator (todos-done-separator)
1031 "String used to visually separate done from not done items.
1032 Displayed as an overlay instead of `todos-category-done' when
1033 done items are shown. Its value is determined by user option
1034 `todos-done-separator-string'.")
1036 (defun todos-reset-done-separator (sep)
1037 "Replace any existing overlays of separator string SEP."
1041 (goto-char (point-min))
1042 (while (re-search-forward
1043 (concat "\n\\(" (regexp-quote todos-category-done) "\\)") nil t)
1044 (setq beg (match-beginning 1))
1045 (setq end (match-end 0))
1046 (let* ((ovs (overlays-at beg))
1049 (setq old-sep (overlay-get (car ovs) 'display))
1050 (string= old-sep sep)
1051 (delete-overlay (car ovs))
1052 (setq new-sep (make-overlay beg end))
1053 (overlay-put new-sep 'display
1054 todos-done-separator)))))))
1056 (defun todos-reset-and-enable-done-separator ()
1057 "Hook function for activating new separator overlay.
1058 Added to `window-configuration-change-hook' in `todos-mode'."
1059 (when (= 1 (length todos-done-separator-string))
1060 (let ((sep todos-done-separator))
1061 (setq todos-done-separator (todos-done-separator))
1062 (todos-reset-done-separator sep))
1063 ;; If the separator overlay is now shown, we have to hide and then show it
1064 ;; again in order to let the change in length take effect.
1066 (goto-char (point-min))
1067 (when (re-search-forward todos-done-string-start nil t)
1068 (let ((todos-show-with-done nil))
1069 (todos-category-select))
1070 (let ((todos-show-with-done t))
1071 (todos-category-select))))))
1073 (defun todos-category-select ()
1074 "Display the current category correctly."
1075 (let ((name (todos-current-category))
1076 cat-begin cat-end done-start done-sep-start done-end)
1078 (goto-char (point-min))
1080 (concat "^" (regexp-quote (concat todos-category-beg name)) "$") nil t)
1081 (setq cat-begin (1+ (line-end-position)))
1082 (setq cat-end (if (re-search-forward
1083 (concat "^" (regexp-quote todos-category-beg)) nil t)
1086 (setq mode-line-buffer-identification
1087 (funcall todos-mode-line-function name))
1088 (narrow-to-region cat-begin cat-end)
1089 (todos-prefix-overlays)
1090 (goto-char (point-min))
1091 (if (re-search-forward (concat "\n\\(" (regexp-quote todos-category-done)
1094 (setq done-start (match-beginning 0))
1095 (setq done-sep-start (match-beginning 1))
1096 (setq done-end (match-end 0)))
1097 (error "Category %s is missing todos-category-done string" name))
1098 (if todos-show-done-only
1099 (narrow-to-region (1+ done-end) (point-max))
1100 (when (and todos-show-with-done
1101 (re-search-forward todos-done-string-start nil t))
1102 ;; Now we want to see the done items, so reset displayed end to end of
1104 (setq done-start cat-end)
1105 ;; Make display overlay for done items separator string, unless there
1107 (let* ((done-sep todos-done-separator)
1108 (ovs (overlays-at done-sep-start))
1110 ;; There should never be more than one overlay here, so car suffices.
1111 (unless (and ovs (string= (overlay-get (car ovs) 'display) done-sep))
1112 (setq ov-sep (make-overlay done-sep-start done-end))
1113 (overlay-put ov-sep 'display done-sep))))
1114 (narrow-to-region (point-min) done-start)
1115 ;; Loading this from todos-mode, or adding it to the mode hook, causes
1116 ;; Emacs to hang in todos-item-start, at (looking-at todos-item-start).
1117 (when todos-highlight-item
1119 (hl-line-mode 1)))))
1121 (defun todos-get-count (type &optional category)
1122 "Return count of TYPE items in CATEGORY.
1123 If CATEGORY is nil, default to the current category."
1124 (let* ((cat (or category (todos-current-category)))
1125 (counts (cdr (assoc cat todos-categories)))
1126 (idx (cond ((eq type 'todo) 0)
1127 ((eq type 'diary) 1)
1129 ((eq type 'archived) 3))))
1132 (defun todos-update-count (type increment &optional category)
1133 "Change count of TYPE items in CATEGORY by integer INCREMENT.
1134 With nil or omitted CATEGORY, default to the current category."
1135 (let* ((cat (or category (todos-current-category)))
1136 (counts (cdr (assoc cat todos-categories)))
1137 (idx (cond ((eq type 'todo) 0)
1138 ((eq type 'diary) 1)
1140 ((eq type 'archived) 3))))
1141 (aset counts idx (+ increment (aref counts idx)))))
1143 (defun todos-set-categories ()
1144 "Set `todos-categories' from the sexp at the top of the file."
1145 ;; New archive files created by `todos-move-category' are empty, which would
1146 ;; make the sexp test fail and raise an error, so in this case we skip it.
1147 (unless (zerop (buffer-size))
1151 (goto-char (point-min))
1152 (setq todos-categories
1153 (if (looking-at "\(\(\"")
1154 (read (buffer-substring-no-properties
1155 (line-beginning-position)
1156 (line-end-position)))
1157 (error "Invalid or missing todos-categories sexp")))))))
1159 (defun todos-update-categories-sexp ()
1160 "Update the `todos-categories' sexp at the top of the file."
1161 (let (buffer-read-only)
1165 (goto-char (point-min))
1166 (if (looking-at (concat "^" (regexp-quote todos-category-beg)))
1167 (progn (newline) (goto-char (point-min)) ; Make space for sexp.
1168 ;; No categories sexp means the first item was just added
1169 ;; to this file, so have to initialize Todos file and
1170 ;; categories variables in order e.g. to enable categories
1172 (setq todos-default-todos-file (buffer-file-name))
1173 (setq todos-categories (todos-make-categories-list t)))
1174 ;; With empty buffer (e.g. with new archive in
1175 ;; `todos-move-category') `kill-line' signals end of buffer.
1176 (kill-region (line-beginning-position) (line-end-position)))
1177 (prin1 todos-categories (current-buffer))))))
1179 (defun todos-make-categories-list (&optional force)
1180 "Return an alist of Todos categories and their item counts.
1181 With non-nil argument FORCE parse the entire file to build the
1182 list; otherwise, get the value by reading the sexp at the top of
1184 (setq todos-categories nil)
1188 (goto-char (point-min))
1189 (let (counts cat archive)
1190 ;; If the file is a todo file and has archived items, identify the
1191 ;; archive, in order to count its items. But skip this with
1192 ;; `todos-convert-legacy-files', since that converts filed items to
1194 (when buffer-file-name ; During conversion there is no file yet.
1195 ;; If the file is an archive, it doesn't have an archive.
1196 (unless (member (file-truename buffer-file-name)
1197 (funcall todos-files-function t))
1198 (setq archive (concat (file-name-sans-extension
1199 todos-current-todos-file) ".toda"))))
1201 (cond ((looking-at (concat (regexp-quote todos-category-beg)
1203 (setq cat (match-string-no-properties 1))
1204 ;; Counts for each category: [todo diary done archive]
1205 (setq counts (make-vector 4 0))
1206 (setq todos-categories
1207 (append todos-categories (list (cons cat counts))))
1208 ;; Add archived item count to the todo file item counts.
1209 ;; Make sure to include newly created archives, e.g. due to
1210 ;; todos-move-category.
1211 (when (member archive (funcall todos-files-function t))
1212 (let ((archive-count 0))
1213 (with-current-buffer (find-file-noselect archive)
1215 (goto-char (point-min))
1216 (when (re-search-forward
1217 (concat (regexp-quote todos-category-beg) cat)
1220 (while (not (or (looking-at
1222 (regexp-quote todos-category-beg)
1225 (when (looking-at todos-done-string-start)
1226 (setq archive-count (1+ archive-count)))
1228 (todos-update-count 'archived archive-count cat))))
1229 ((looking-at todos-done-string-start)
1230 (todos-update-count 'done 1 cat))
1231 ((looking-at (concat "^\\("
1232 (regexp-quote diary-nonmarking-symbol)
1233 "\\)?" todos-date-pattern))
1234 (todos-update-count 'diary 1 cat)
1235 (todos-update-count 'todo 1 cat))
1236 ((looking-at (concat todos-date-string-start todos-date-pattern))
1237 (todos-update-count 'todo 1 cat))
1238 ;; If first line is todos-categories list, use it and end loop
1239 ;; -- unless FORCEd to scan whole file.
1242 (setq todos-categories (read (buffer-substring-no-properties
1243 (line-beginning-position)
1244 (line-end-position))))
1245 (goto-char (1- (point-max))))))
1249 (defun todos-check-format ()
1250 "Signal an error if the current Todos file is ill-formatted.
1251 Otherwise return t. The error message gives the line number
1252 where the invalid formatting was found."
1256 (goto-char (point-min))
1257 ;; Check for `todos-categories' sexp as the first line
1258 (let ((cats (prin1-to-string todos-categories)))
1259 (unless (looking-at (regexp-quote cats))
1260 (error "Invalid or missing todos-categories sexp")))
1262 (let ((legit (concat "\\(^" (regexp-quote todos-category-beg) "\\)"
1263 "\\|\\(" todos-date-string-start todos-date-pattern "\\)"
1264 "\\|\\(^[ \t]+[^ \t]*\\)"
1266 "\\|\\(^" (regexp-quote todos-category-done) "\\)"
1267 "\\|\\(" todos-done-string-start "\\)")))
1269 (unless (looking-at legit)
1270 (error "Illegitimate Todos file format at line %d"
1271 (line-number-at-pos (point))))
1273 ;; (message "This Todos file is well-formatted.")
1276 (defun todos-repair-categories-sexp ()
1277 "Repair corrupt Todos categories sexp.
1278 This should only be needed as a consequence of careless manual
1279 editing or a bug in todos.el."
1281 (let ((todos-categories (todos-make-categories-list t)))
1282 (todos-update-categories-sexp)))
1284 (defun todos-convert-legacy-date-time ()
1285 "Return converted date-time string.
1286 Helper function for `todos-convert-legacy-files'."
1287 (let* ((year (match-string 1))
1288 (month (match-string 2))
1289 (monthname (calendar-month-name (string-to-number month) t))
1290 (day (match-string 3))
1291 (time (match-string 4))
1294 (insert (mapconcat 'eval calendar-date-display-form "")
1295 (when time (concat " " time)))))
1297 (defvar todos-item-start (concat "\\(" todos-date-string-start "\\|"
1298 todos-done-string-start "\\)"
1300 "String identifying start of a Todos item.")
1302 (defun todos-item-start ()
1303 "Move to start of current Todos item and return its position."
1305 ;; Buffer is empty (invocation possible e.g. via todos-forward-item
1306 ;; from todos-filter-items when processing category with no todo
1308 (eq (point-min) (point-max))
1309 ;; Point is on the empty line between todo and done items.
1310 (and (looking-at "^$")
1313 (looking-at (concat "^" (regexp-quote todos-category-done)))))
1314 ;; Buffer is widened.
1315 (looking-at (regexp-quote todos-category-beg)))
1316 (goto-char (line-beginning-position))
1317 (while (not (looking-at todos-item-start))
1321 (defun todos-item-end ()
1322 "Move to end of current Todos item and return its position."
1323 ;; Items cannot end with a blank line.
1324 (unless (looking-at "^$")
1325 (let* ((done (todos-done-item-p))
1327 ;; For todo items, end is before the done items section, for done
1328 ;; items, end is before the next category. If these limits are
1329 ;; missing or inaccessible, end it before the end of the buffer.
1330 (lim (if (save-excursion
1332 (concat "^" (regexp-quote (if done
1334 todos-category-done)))
1336 (progn (setq to-lim t) (match-beginning 0))
1338 (when (bolp) (forward-char)) ; Find start of next item.
1339 (goto-char (if (re-search-forward todos-item-start lim t)
1341 (if to-lim lim (point-max))))
1342 ;; For last todo item, skip back over the empty line before the done
1343 ;; items section, else just back to the end of the previous line.
1344 (backward-char (when (and to-lim (not done) (eq (point) lim)) 2))
1347 (defun todos-item-string ()
1348 "Return bare text of current item as a string."
1349 (let ((opoint (point))
1350 (start (todos-item-start))
1351 (end (todos-item-end)))
1353 (and start end (buffer-substring-no-properties start end))))
1355 (defun todos-remove-item ()
1356 "Internal function called in editing, deleting or moving items."
1357 (let* ((beg (todos-item-start))
1358 (end (progn (todos-item-end) (1+ (point))))
1359 (ovs (overlays-in beg beg)))
1360 ;; There can be both prefix/number and mark overlays.
1361 (while ovs (delete-overlay (car ovs)) (pop ovs))
1362 (delete-region beg end)))
1364 (defun todos-diary-item-p ()
1365 "Return non-nil if item at point has diary entry format."
1368 (not (looking-at (regexp-quote todos-nondiary-start)))))
1370 (defun todos-done-item-p ()
1371 "Return non-nil if item at point is a done item."
1374 (looking-at todos-done-string-start)))
1376 (defvar todos-item-mark (propertize (if (equal todos-prefix "*") "@" "*")
1378 "String used to mark items.")
1380 (defun todos-marked-item-p ()
1381 "If this item begins with `todos-item-mark', return mark overlay."
1382 (let ((ovs (overlays-in (line-beginning-position) (line-beginning-position)))
1383 (mark todos-item-mark)
1388 (and (equal (overlay-get ov 'before-string) mark)
1389 (throw 'stop (setq marked t)))))
1392 (defun todos-insert-with-overlays (item)
1393 "Insert ITEM at point and update prefix/priority number overlays."
1396 (todos-backward-item)
1397 (todos-prefix-overlays))
1399 (defun todos-prefix-overlays ()
1400 "Put before-string overlay in front of this category's items.
1401 The overlay's value is the string `todos-prefix' or with non-nil
1402 `todos-number-priorities' an integer in the sequence from 1 to
1403 the number of todo or done items in the category indicating the
1404 item's priority. Todo and done items are numbered independently
1406 (when (or todos-number-priorities
1407 (not (string-match "^[[:space:]]*$" todos-prefix)))
1408 (let ((prefix (propertize (concat todos-prefix " ")
1409 'face 'todos-prefix-string))
1412 (goto-char (point-min))
1414 (when (or (todos-date-string-matcher (line-end-position))
1415 (todos-done-string-matcher (line-end-position)))
1416 (goto-char (match-beginning 0))
1417 (when todos-number-priorities
1419 ;; Reset number to 1 for first done item.
1420 (when (and (looking-at todos-done-string-start)
1421 (looking-back (concat "^"
1422 (regexp-quote todos-category-done)
1425 (setq prefix (propertize (concat (number-to-string num) " ")
1426 'face 'todos-prefix-string)))
1427 (let ((ovs (overlays-in (point) (point)))
1431 (let ((val (overlay-get ov 'before-string)))
1434 (setq ov-pref val)))))
1435 (unless (equal ov-pref prefix)
1436 ;; Why doesn't this work?
1437 ;; (remove-overlays (point) (point) 'before-string)
1438 (remove-overlays (point) (point))
1439 (overlay-put (make-overlay (point) (point))
1440 'before-string prefix)
1441 (and marked (overlay-put (make-overlay (point) (point))
1442 'before-string todos-item-mark)))))
1445 ;; ---------------------------------------------------------------------------
1446 ;;; Functions for user input with prompting and completion
1448 (defun todos-read-file-name (prompt &optional archive mustmatch)
1449 "Choose and return the name of a Todos file, prompting with PROMPT.
1451 Show completions with TAB or SPC; the names are shown in short
1452 form but the absolute truename is returned. With non-nil ARCHIVE
1453 return the absolute truename of a Todos archive file. With non-nil
1454 MUSTMATCH the name of an existing file must be chosen;
1455 otherwise, a new file name is allowed."
1456 (let* ((completion-ignore-case todos-completion-ignore-case)
1457 (files (mapcar 'todos-short-file-name
1458 (if archive todos-archives todos-files)))
1459 (file (completing-read prompt files nil mustmatch nil nil
1461 ;; Trigger prompt for initial file.
1463 (unless (file-exists-p todos-files-directory)
1464 (make-directory todos-files-directory))
1466 (setq file (todos-validate-name file 'file)))
1467 (setq file (file-truename (concat todos-files-directory file
1468 (if archive ".toda" ".todo"))))))
1470 (defun todos-read-category (prompt &optional mustmatch added)
1471 "Choose and return a category name, prompting with PROMPT.
1472 Show completions with TAB or SPC. With non-nil MUSTMATCH the
1473 name must be that of an existing category; otherwise, a new
1474 category name is allowed, after checking its validity. Non-nil
1475 argument ADDED means the caller is todos-add-category, so don't
1476 ask whether to add the category."
1477 ;; Allow SPC to insert spaces, for adding new category names.
1478 (let ((map minibuffer-local-completion-map))
1479 (define-key map " " nil)
1480 ;; Make a copy of todos-categories in case history-delete-duplicates is
1481 ;; non-nil, which makes completing-read alter todos-categories.
1482 (let* ((categories (copy-sequence todos-categories))
1483 (history (cons 'todos-categories (1+ todos-category-number)))
1484 (completion-ignore-case todos-completion-ignore-case)
1485 (cat (completing-read prompt todos-categories nil
1486 mustmatch nil history
1487 ;; Default for existing categories is the
1488 ;; current category.
1489 (if todos-categories
1490 (todos-current-category)
1491 ;; Trigger prompt for initial category.
1493 (unless (or mustmatch (assoc cat todos-categories))
1494 (todos-validate-name cat 'category)
1496 (if (y-or-n-p (format (concat "There is no category \"%s\" in "
1497 "this file; add it? ") cat))
1498 (todos-add-category cat)
1500 ;; Restore the original value of todos-categories unless a new category
1501 ;; was added (since todos-add-category changes todos-categories).
1502 (unless added (setq todos-categories categories))
1505 (defun todos-validate-name (name type)
1506 "Prompt for new NAME for TYPE until it is valid, then return it.
1507 TYPE can be either a file or a category"
1508 (let ((categories todos-categories)
1509 (files (mapcar 'todos-short-file-name todos-files))
1512 (and (cond ((string= "" name)
1514 (cond ((eq type 'file)
1516 "Enter a non-empty file name: "
1517 ;; Empty string passed by todos-show to
1518 ;; prompt for initial Todos file.
1519 (concat "Initial file name ["
1520 todos-initial-file "]: ")))
1521 ((eq type 'category)
1522 (if todos-categories
1523 "Enter a non-empty category name: "
1524 ;; Empty string passed by todos-show to
1525 ;; prompt for initial category of a new
1527 (concat "Initial category name ["
1528 todos-initial-category "]: "))))))
1529 ((string-match "\\`\\s-+\\'" name)
1531 "Enter a name that does not contain only white space: "))
1532 ((and (eq type 'file) (member name todos-files))
1533 (setq prompt "Enter a non-existing file name: "))
1534 ((and (eq type 'category) (assoc name todos-categories))
1535 (setq prompt "Enter a non-existing category name: ")))
1536 (setq name (if (or (and (eq type 'file) todos-files)
1537 (and (eq type 'category) todos-categories))
1538 (completing-read prompt (cond ((eq type 'file)
1540 ((eq type 'category)
1542 ;; Offer default initial name.
1543 (completing-read prompt (if (eq type 'file)
1546 nil nil (if (eq type 'file)
1548 todos-initial-category))))))
1551 ;; Adapted from calendar-read-date and calendar-date-string.
1552 (defun todos-read-date ()
1553 "Prompt for Gregorian date and return it in the current format.
1554 Also accepts `*' as an unspecified month, day, or year."
1555 (let* ((year (let (x)
1556 (while (if (numberp x) (< x 0) (not (eq x '*)))
1557 (setq x (read-from-minibuffer
1558 "Year (>0 or RET for this year or * for any year): "
1559 nil nil t nil (number-to-string
1560 (calendar-extract-year
1561 (calendar-current-date))))))
1563 (month-array (vconcat calendar-month-name-array (vector "*")))
1564 (abbrevs (vconcat calendar-month-abbrev-array (vector "*")))
1565 (completion-ignore-case todos-completion-ignore-case)
1566 (monthname (completing-read
1567 "Month name (RET for current month, * for any month): "
1568 (mapcar 'list (append month-array nil))
1570 (calendar-month-name (calendar-extract-month
1571 (calendar-current-date)) t)))
1572 (month (cdr (assoc-string
1573 monthname (calendar-make-alist month-array nil nil
1575 (last (if (= month 13)
1576 31 ; FIXME: what about shorter months?
1577 (let ((yr (if (eq year '*)
1578 1999 ; FIXME: no Feb. 29
1580 (calendar-last-day-of-month month yr))))
1582 (while (if (numberp x) (or (< x 0) (< last x)) (not (eq x '*)))
1583 (setq x (read-from-minibuffer
1585 "Day (1-%d or RET for today or * for any day): "
1586 last) nil nil t nil (number-to-string
1587 (calendar-extract-day
1588 (calendar-current-date))))))
1590 dayname) ; Needed by calendar-date-display-form.
1591 (setq year (if (eq year '*) (symbol-name '*) (number-to-string year)))
1592 (setq day (if (eq day '*) (symbol-name '*) (number-to-string day)))
1593 ;; FIXME: make abbreviation customizable
1595 (or (and (= month 13) "*")
1596 (calendar-month-name (calendar-extract-month (list month day year))
1598 (mapconcat 'eval calendar-date-display-form "")))
1600 (defun todos-read-dayname ()
1601 "Choose name of a day of the week with completion and return it."
1602 (let ((completion-ignore-case todos-completion-ignore-case))
1603 (completing-read "Enter a day name: "
1604 (append calendar-day-name-array nil)
1607 (defun todos-read-time ()
1608 "Prompt for and return a valid clock time as a string.
1610 Valid time strings are those matching `diary-time-regexp'.
1611 Typing `<return>' at the prompt returns the current time, if the
1612 user option `todos-always-add-time-string' is non-nil, otherwise
1613 the empty string (i.e., no time string)."
1616 (setq answer (read-string "Enter a clock time: " nil nil
1617 (when todos-always-add-time-string
1618 (substring (current-time-string) 11 16))))
1619 (when (or (string= "" answer)
1620 (string-match diary-time-regexp answer))
1624 ;; ---------------------------------------------------------------------------
1627 (defvar todos-multiple-filter-files nil
1628 "List of files selected from `todos-multiple-filter-files' widget.")
1630 (defvar todos-multiple-filter-files-widget nil
1631 "Variable holding widget created by `todos-multiple-filter-files'.")
1633 (defun todos-multiple-filter-files ()
1634 "Pop to a buffer with a widget for choosing multiple filter files."
1637 (require 'wid-edit))
1638 (with-current-buffer (get-buffer-create "*Todos Filter Files*")
1639 (pop-to-buffer (current-buffer))
1641 (kill-all-local-variables)
1642 (widget-insert "Select files for generating the top priorities list.\n\n")
1643 (setq todos-multiple-filter-files-widget
1645 `(set ,@(mapcar (lambda (x) (list 'const x))
1646 (mapcar 'todos-short-file-name
1647 (funcall todos-files-function))))))
1648 (widget-insert "\n")
1649 (widget-create 'push-button
1650 :notify (lambda (widget &rest ignore)
1651 (setq todos-multiple-filter-files 'quit)
1653 (exit-recursive-edit))
1656 (widget-create 'push-button
1657 :notify (lambda (&rest ignore)
1658 (setq todos-multiple-filter-files
1660 (concat todos-files-directory
1663 todos-multiple-filter-files-widget)))
1665 (exit-recursive-edit))
1667 (use-local-map widget-keymap)
1669 (message "Click \"Apply\" after selecting files.")
1672 (defun todos-filter-items (filter &optional multifile)
1673 "Build and display a list of items from different categories.
1675 The items are selected according to the value of FILTER, which
1676 can be `top' for top priority items, `diary' for diary items,
1677 `regexp' for items matching a regular expresion entered by the
1678 user, or a cons cell of one of these symbols and a number set by
1679 the calling command, which overrides `todos-show-priorities'.
1681 With non-nil argument MULTIFILE list top priorities of multiple
1682 Todos files, by default those in `todos-filter-files'."
1683 (let ((num (if (consp filter) (cdr filter) todos-show-priorities))
1684 (buf (get-buffer-create todos-filtered-items-buffer))
1685 (files (list todos-current-todos-file))
1686 regexp fname bufstr cat beg end done)
1688 (setq files (or todos-multiple-filter-files ; Passed from todos-*-multifile.
1689 (if (or (consp filter)
1690 (null todos-filter-files))
1691 (progn (todos-multiple-filter-files)
1692 todos-multiple-filter-files)
1693 todos-filter-files))
1694 todos-multiple-filter-files nil))
1695 (if (eq files 'quit) (keyboard-quit))
1697 (error "No files have been chosen for filtering")
1698 (with-current-buffer buf
1700 (kill-all-local-variables)
1701 (todos-filtered-items-mode))
1702 (when (eq filter 'regexp)
1703 (setq regexp (read-string "Enter a regular expression: ")))
1704 (save-current-buffer
1706 ;; Before inserting file contents into temp buffer, save a modified
1707 ;; buffer visiting it.
1708 (let ((bf (find-buffer-visiting f)))
1709 (when (buffer-modified-p bf)
1710 (with-current-buffer bf (save-buffer))))
1711 (setq fname (todos-short-file-name f))
1713 (when (and todos-filter-done-items (eq filter 'regexp))
1714 ;; If there is a corresponding archive file for the Todos file,
1715 ;; insert it first and add identifiers for todos-jump-to-item.
1716 (let ((arch (concat (file-name-sans-extension f) ".toda")))
1717 (when (file-exists-p arch)
1718 (insert-file-contents arch)
1719 ;; Delete Todos archive file categories sexp.
1720 (delete-region (line-beginning-position)
1721 (1+ (line-end-position)))
1724 (when (re-search-forward
1725 (concat (if todos-filter-done-items
1726 (concat "\\(?:" todos-done-string-start
1727 "\\|" todos-date-string-start
1729 todos-date-string-start)
1730 todos-date-pattern "\\(?: "
1731 diary-time-regexp "\\)?"
1732 (if todos-filter-done-items
1734 (regexp-quote todos-nondiary-end)) "?")
1736 (insert "(archive) "))
1738 (insert-file-contents f)
1739 ;; Delete Todos file categories sexp.
1740 (delete-region (line-beginning-position) (1+ (line-end-position)))
1742 ;; Unless the number of items to show was supplied by prefix
1743 ;; argument of caller, the file-wide value from
1744 ;; `todos-priorities-rules', if non-nil, overrides
1745 ;; `todos-show-priorities'.
1746 (unless (consp filter)
1747 (setq fnum (nth 1 (assoc f todos-priorities-rules))))
1748 (while (re-search-forward
1749 (concat "^" (regexp-quote todos-category-beg) "\\(.+\\)\n")
1751 (setq cat (match-string 1))
1753 ;; Unless the number of items to show was supplied by prefix
1754 ;; argument of caller, the category-wide value from
1755 ;; `todos-priorities-rules', if non-nil, overrides a non-nil
1756 ;; file-wide value from `todos-priorities-rules' as well as
1757 ;; `todos-show-priorities'.
1758 (unless (consp filter)
1759 (let ((cats (nth 2 (assoc f todos-priorities-rules))))
1760 (setq cnum (or (cdr (assoc cat cats)) fnum))))
1761 (delete-region (match-beginning 0) (match-end 0))
1762 (setq beg (point)) ; First item in the current category.
1763 (setq end (if (re-search-forward
1764 (concat "^" (regexp-quote todos-category-beg))
1770 (if (re-search-forward
1771 (concat "\n" (regexp-quote todos-category-done))
1775 (unless (and todos-filter-done-items (eq filter 'regexp))
1776 ;; Leave done items.
1777 (delete-region done end)
1779 (narrow-to-region beg end) ; Process only current category.
1780 (goto-char (point-min))
1781 ;; Apply the filter.
1782 (cond ((eq filter 'diary)
1784 (if (looking-at (regexp-quote todos-nondiary-start))
1786 (todos-forward-item))))
1787 ((eq filter 'regexp)
1789 (if (looking-at todos-item-start)
1790 (if (string-match regexp (todos-item-string))
1791 (todos-forward-item)
1792 (todos-remove-item))
1793 ;; Kill lines that aren't part of a todo or done
1794 ;; item (empty or todos-category-done).
1795 (delete-region (line-beginning-position)
1796 (1+ (line-end-position))))
1797 ;; If last todo item in file matches regexp and
1798 ;; there are no following done items,
1799 ;; todos-category-done string is left dangling,
1800 ;; because todos-forward-item jumps over it.
1803 (concat (regexp-quote todos-done-string)
1805 (delete-region (point) (progn
1808 (t ; Filter top priority items.
1809 (setq num (or cnum fnum num))
1811 (todos-forward-item num))))
1813 ;; Delete non-top-priority items.
1814 (unless (member filter '(diary regexp))
1815 (delete-region beg end))
1816 (goto-char (point-min))
1817 ;; Add file (if using multiple files) and category tags to
1820 (when (re-search-forward
1821 (concat (if todos-filter-done-items
1822 (concat "\\(?:" todos-done-string-start
1823 "\\|" todos-date-string-start
1825 todos-date-string-start)
1826 todos-date-pattern "\\(?: " diary-time-regexp
1827 "\\)?" (if todos-filter-done-items
1829 (regexp-quote todos-nondiary-end))
1833 (when (looking-at "(archive) ") (goto-char (match-end 0)))
1834 (insert (if multifile (concat fname ":") "") cat "]"))
1837 (setq bufstr (buffer-string))
1838 (with-current-buffer buf
1839 (let (buffer-read-only)
1840 (insert bufstr)))))))
1841 (set-window-buffer (selected-window) (set-buffer buf))
1842 (todos-prefix-overlays)
1843 (goto-char (point-min)))))
1845 (defun todos-set-top-priorities (&optional arg)
1846 "Set number of top priorities shown by `todos-top-priorities'.
1847 With non-nil ARG, set the number only for the current Todos
1848 category; otherwise, set the number for all categories in the
1851 Calling this function via either of the commands
1852 `todos-set-top-priorities-in-file' or
1853 `todos-set-top-priorities-in-category' is the recommended way to
1854 set the user customizable option `todos-priorities-rules'."
1855 (let* ((cat (todos-current-category))
1856 (file todos-current-todos-file)
1857 (rules todos-priorities-rules)
1858 (frule (assoc-string file rules))
1859 (crule (assoc-string cat (nth 2 frule)))
1860 (cur (or (if arg (cdr crule) (nth 1 frule))
1861 todos-show-priorities))
1862 (prompt (concat "Current number of top priorities in this "
1863 (if arg "category" "file") ": %d; "
1864 "enter new number: "))
1867 (while (or (not (string-match "[0-9]+" new)) ; Don't accept "" or "bla".
1868 (< (string-to-number new) 0))
1870 (setq new (read-string (format prompt cur0) nil nil cur0)
1871 prompt "Enter a non-negative number: "
1873 (setq new (string-to-number new))
1875 (append (nth 2 (delete crule frule)) (list (cons cat new)))
1876 (append (list file new) (list (nth 2 frule)))))
1877 (setq rules (cons (if arg
1878 (list file cur nrule)
1880 (delete frule rules)))
1881 (customize-save-variable 'todos-priorities-rules rules)))
1883 (defun todos-filtered-buffer-name (buffer-type file-list)
1884 "Rename Todos filtered buffer using BUFFER-TYPE and FILE-LIST.
1886 The new name is constructed from the string BUFFER-TYPE, which
1887 refers to one of the top priorities, diary or regexp item
1888 filters, and the names of the filtered files in FILE-LIST. Used
1889 in Todos Filter Items mode."
1890 (let* ((flist (if (listp file-list) file-list (list file-list)))
1891 (multi (> (length flist) 1))
1892 (fnames (mapconcat (lambda (f) (todos-short-file-name f))
1894 (rename-buffer (format (concat "%s for file" (if multi "s" "")
1895 " \"%s\"") buffer-type fnames))))
1897 ;; ---------------------------------------------------------------------------
1898 ;;; Sorting and display routines for Todos Categories mode.
1900 (defun todos-longest-category-name-length (categories)
1901 "Return the length of the longest name in list CATEGORIES."
1903 (dolist (c categories longest)
1904 (setq longest (max longest (length c))))))
1906 (defun todos-padded-string (str)
1907 "Return string STR padded with spaces.
1908 The placement of the padding is determined by the value of user
1909 option `todos-categories-align'."
1910 (let* ((categories (mapcar 'car todos-categories))
1911 (len (max (todos-longest-category-name-length categories)
1912 (length todos-categories-category-label)))
1913 (strlen (length str))
1914 (strlen-odd (eq (logand strlen 1) 1)) ; oddp from cl.el
1915 (padding (max 0 (/ (- len strlen) 2)))
1916 (padding-left (cond ((eq todos-categories-align 'left) 0)
1917 ((eq todos-categories-align 'center) padding)
1918 ((eq todos-categories-align 'right)
1919 (if strlen-odd (1+ (* padding 2)) (* padding 2)))))
1920 (padding-right (cond ((eq todos-categories-align 'left)
1921 (if strlen-odd (1+ (* padding 2)) (* padding 2)))
1922 ((eq todos-categories-align 'center)
1923 (if strlen-odd (1+ padding) padding))
1924 ((eq todos-categories-align 'right) 0))))
1925 (concat (make-string padding-left 32) str (make-string padding-right 32))))
1927 (defvar todos-descending-counts nil
1928 "List of keys for category counts sorted in descending order.")
1930 (defun todos-sort (list &optional key)
1931 "Return a copy of LIST, possibly sorted according to KEY."
1932 (let* ((l (copy-sequence list))
1933 (fn (if (eq key 'alpha)
1934 (lambda (x) (upcase x)) ; Alphabetize case insensitively.
1935 (lambda (x) (todos-get-count key x))))
1936 ;; Keep track of whether the last sort by key was descending or
1938 (descending (member key todos-descending-counts))
1939 (cmp (if (eq key 'alpha)
1941 (if descending '< '>)))
1942 (pred (lambda (s1 s2) (let ((t1 (funcall fn (car s1)))
1943 (t2 (funcall fn (car s2))))
1944 (funcall cmp t1 t2)))))
1946 (setq l (sort l pred))
1947 ;; Switch between descending and ascending sort order.
1949 (setq todos-descending-counts
1950 (delete key todos-descending-counts))
1951 (push key todos-descending-counts)))
1954 (defun todos-display-sorted (type)
1955 "Keep point on the TYPE count sorting button just clicked."
1956 (let ((opoint (point)))
1957 (todos-update-categories-display type)
1958 (goto-char opoint)))
1960 (defun todos-label-to-key (label)
1961 "Return symbol for sort key associated with LABEL."
1963 (cond ((string= label todos-categories-category-label)
1965 ((string= label todos-categories-todo-label)
1967 ((string= label todos-categories-diary-label)
1969 ((string= label todos-categories-done-label)
1971 ((string= label todos-categories-archived-label)
1972 (setq key 'archived)))
1975 (defun todos-insert-sort-button (label)
1976 "Insert button for displaying categories sorted by item counts.
1977 LABEL determines which type of count is sorted."
1978 (setq str (if (string= label todos-categories-category-label)
1979 (todos-padded-string label)
1982 (setq end (+ beg (length str)))
1983 (insert-button str 'face nil
1986 (let ((key (todos-label-to-key ,label)))
1987 (if (and (member key todos-descending-counts)
1990 ;; If display is alphabetical, switch back to
1991 ;; category priority order.
1992 (todos-display-sorted nil)
1993 (setq todos-descending-counts
1994 (delete key todos-descending-counts)))
1995 (todos-display-sorted key)))))
1996 (setq ovl (make-overlay beg end))
1997 (overlay-put ovl 'face 'todos-button))
1999 (defun todos-total-item-counts ()
2000 "Return a list of total item counts for the current file."
2001 (mapcar (lambda (i) (apply '+ (mapcar (lambda (l) (aref l i))
2002 (mapcar 'cdr todos-categories))))
2005 (defvar todos-categories-category-number 0
2006 "Variable for numbering categories in Todos Categories mode.")
2008 (defun todos-insert-category-line (cat &optional nonum)
2009 "Insert button with category CAT's name and item counts.
2010 With non-nil argument NONUM show only these; otherwise, insert a
2011 number in front of the button indicating the category's priority.
2012 The number and the category name are separated by the string
2013 which is the value of the user option
2014 `todos-categories-number-separator'."
2015 (let ((archive (member todos-current-todos-file todos-archives))
2016 (num todos-categories-category-number)
2017 (str (todos-padded-string cat))
2019 (setq num (1+ num) todos-categories-category-number num)
2022 (make-string (+ 4 (length todos-categories-number-separator))
2024 (format " %3d%s" num todos-categories-number-separator))
2026 (mapconcat (lambda (elt)
2028 (make-string (1+ (/ (length (car elt)) 2)) 32) ; label
2029 (format "%3d" (todos-get-count (cdr elt) cat)) ; count
2030 ;; Add an extra space if label length is odd
2031 ;; (using def of oddp from cl.el).
2032 (if (eq (logand (length (car elt)) 1) 1) " ")))
2034 (list (cons todos-categories-done-label 'done))
2035 (list (cons todos-categories-todo-label 'todo)
2036 (cons todos-categories-diary-label 'diary)
2037 (cons todos-categories-done-label 'done)
2038 (cons todos-categories-archived-label
2041 " ") ; So highlighting of last column is consistent with the others.
2042 'face (if (and todos-skip-archived-categories
2043 (zerop (todos-get-count 'todo cat))
2044 (zerop (todos-get-count 'done cat))
2045 (not (zerop (todos-get-count 'archived cat))))
2046 'todos-archived-only
2048 'action `(lambda (button) (let ((buf (current-buffer)))
2049 (todos-jump-to-category ,cat)
2050 (kill-buffer buf))))
2051 ;; Highlight the sorted count column.
2052 (let* ((beg (+ opoint 7 (length str)))
2054 (cond ((eq nonum 'todo)
2055 (setq beg (+ beg 1 (/ (length todos-categories-todo-label) 2))))
2057 (setq beg (+ beg 1 (length todos-categories-todo-label)
2058 2 (/ (length todos-categories-diary-label) 2))))
2060 (setq beg (+ beg 1 (length todos-categories-todo-label)
2061 2 (length todos-categories-diary-label)
2062 2 (/ (length todos-categories-done-label) 2))))
2063 ((eq nonum 'archived)
2064 (setq beg (+ beg 1 (length todos-categories-todo-label)
2065 2 (length todos-categories-diary-label)
2066 2 (length todos-categories-done-label)
2067 2 (/ (length todos-categories-archived-label) 2)))))
2068 (unless (= beg (+ opoint 7 (length str))) ; Don't highlight categories.
2069 (setq end (+ beg 4))
2070 (setq ovl (make-overlay beg end))
2071 (overlay-put ovl 'face 'todos-sorted-column)))
2074 (defun todos-display-categories-1 ()
2075 "Prepare buffer for displaying table of categories and item counts."
2076 (unless (eq major-mode 'todos-categories-mode)
2077 (setq todos-global-current-todos-file (or todos-current-todos-file
2078 todos-default-todos-file))
2079 (set-window-buffer (selected-window)
2080 (set-buffer (get-buffer-create todos-categories-buffer)))
2081 (kill-all-local-variables)
2082 (todos-categories-mode)
2083 (let ((archive (member todos-current-todos-file todos-archives))
2086 ;; FIXME: add usage tips?
2087 (insert (format (concat "Category counts for Todos "
2088 (if archive "archive" "file")
2090 (todos-short-file-name todos-current-todos-file)))
2092 ;; Make space for the column of category numbers.
2093 (insert (make-string (+ 4 (length todos-categories-number-separator)) 32))
2094 ;; Add the category and item count buttons (if this is the list of
2095 ;; categories in an archive, show only done item counts).
2096 (todos-insert-sort-button todos-categories-category-label)
2099 (insert (make-string 3 32))
2100 (todos-insert-sort-button todos-categories-done-label))
2101 (insert (make-string 3 32))
2102 (todos-insert-sort-button todos-categories-todo-label)
2103 (insert (make-string 2 32))
2104 (todos-insert-sort-button todos-categories-diary-label)
2105 (insert (make-string 2 32))
2106 (todos-insert-sort-button todos-categories-done-label)
2107 (insert (make-string 2 32))
2108 (todos-insert-sort-button todos-categories-archived-label))
2111 (defun todos-update-categories-display (sortkey)
2113 (let* ((cats0 todos-categories)
2114 (cats (todos-sort cats0 sortkey))
2115 (archive (member todos-current-todos-file todos-archives))
2116 (todos-categories-category-number 0)
2117 ;; Find start of Category button if we just entered Todos Categories
2119 (pt (if (eq (point) (point-max))
2122 (goto-char (next-single-char-property-change
2123 (point) 'face nil (line-end-position))))))
2126 (delete-region (point) (point-max))
2127 ;; Fill in the table with buttonized lines, each showing a category and
2129 (mapc (lambda (cat) (todos-insert-category-line cat sortkey))
2132 ;; Add a line showing item count totals.
2133 (insert (make-string (+ 4 (length todos-categories-number-separator)) 32)
2134 (todos-padded-string todos-categories-totals-label)
2138 (make-string (1+ (/ (length (car elt)) 2)) 32)
2139 (format "%3d" (nth (cdr elt) (todos-total-item-counts)))
2140 ;; Add an extra space if label length is odd (using
2141 ;; definition of oddp from cl.el).
2142 (if (eq (logand (length (car elt)) 1) 1) " ")))
2144 (list (cons todos-categories-done-label 2))
2145 (list (cons todos-categories-todo-label 0)
2146 (cons todos-categories-diary-label 1)
2147 (cons todos-categories-done-label 2)
2148 (cons todos-categories-archived-label 3)))
2150 ;; Put cursor on Category button initially.
2151 (if pt (goto-char pt))
2152 (setq buffer-read-only t)))
2154 ;; ---------------------------------------------------------------------------
2155 ;;; Routines for generating Todos insertion commands and key bindings
2157 ;; Can either of these be included in Emacs? The originals are GFDL'd.
2159 ;; Slightly reformulated from
2160 ;; http://rosettacode.org/wiki/Power_set#Common_Lisp.
2161 (defun powerset-recursive (l)
2165 (let ((prev (powerset-recursive (cdr l))))
2166 (append (mapcar (lambda (elt) (cons (car l) elt))
2170 ;; Elisp implementation of http://rosettacode.org/wiki/Power_set#C
2171 (defun powerset-bitwise (l)
2172 (let ((binnum (lsh 1 (length l)))
2177 (while (not (zerop bits))
2178 (let ((arg (pop ll)))
2179 (unless (zerop (logand bits 1))
2180 (setq elt (append elt (list arg))))
2181 (setq bits (lsh bits -1))))
2182 (setq pset (append pset (list elt)))
2186 ;; (defalias 'todos-powerset 'powerset-recursive)
2187 (defalias 'todos-powerset 'powerset-bitwise)
2189 ;; Return list of lists of non-nil atoms produced from ARGLIST. The elements
2190 ;; of ARGLIST may be atoms or lists.
2191 (defun todos-gen-arglists (arglist)
2194 (let ((arg (pop arglist)))
2195 (cond ((symbolp arg)
2196 (setq arglists (if arglists
2197 (mapcar (lambda (l) (push arg l)) arglists)
2198 (list (push arg arglists)))))
2202 (if (= 1 (length arglists))
2203 (apply (lambda (l) (push a l)) arglists)
2204 (mapcar (lambda (l) (push a l)) arglists)))
2206 (setq arglists (mapcar 'reverse (apply 'append (mapc 'car arglists))))))
2208 (defvar todos-insertion-commands-args-genlist
2209 '(diary nonmarking (calendar date dayname) time (here region))
2210 "Generator list for argument lists of Todos insertion commands.")
2212 (defvar todos-insertion-commands-args
2213 (let ((argslist (todos-gen-arglists todos-insertion-commands-args-genlist))
2215 (setq res (remove-duplicates
2216 (apply 'append (mapcar 'todos-powerset argslist)) :test 'equal))
2218 (unless (= 5 (length l))
2219 (let ((v (make-vector 5 nil)) elt)
2222 (cond ((eq elt 'diary)
2224 ((eq elt 'nonmarking)
2226 ((or (eq elt 'calendar)
2235 (setq l (append v nil))))
2236 (setq new (append new (list l))))
2238 "List of all argument lists for Todos insertion commands.")
2240 (defun todos-insertion-command-name (arglist)
2241 "Generate Todos insertion command name from ARGLIST."
2242 (replace-regexp-in-string
2244 (replace-regexp-in-string
2246 (concat "todos-item-insert-"
2247 (mapconcat (lambda (e) (if e (symbol-name e))) arglist "-")))))
2249 (defvar todos-insertion-commands-names
2251 (todos-insertion-command-name l))
2252 todos-insertion-commands-args)
2253 "List of names of Todos insertion commands.")
2255 (defmacro todos-define-insertion-command (&rest args)
2256 (let ((name (intern (todos-insertion-command-name args)))
2261 (arg4 (nth 4 args)))
2262 `(defun ,name (&optional arg)
2263 "Todos item insertion command generated from ARGS."
2265 (todos-insert-item arg ',arg0 ',arg1 ',arg2 ',arg3 ',arg4))))
2267 (defvar todos-insertion-commands
2269 (eval `(todos-define-insertion-command ,@c)))
2270 todos-insertion-commands-args)
2271 "List of Todos insertion commands.")
2273 (defvar todos-insertion-commands-arg-key-list
2274 '(("diary" "y" "yy")
2275 ("nonmarking" "k" "kk")
2276 ("calendar" "c" "cc")
2278 ("dayname" "n" "nn")
2284 (defun todos-insertion-key-bindings (map)
2286 (dolist (c todos-insertion-commands)
2288 (cname (symbol-name c)))
2290 (let ((arg (nth 0 l))
2293 (if (string-match (concat (regexp-quote arg) "\\_>") cname)
2294 (setq key (concat key key2)))
2295 (if (string-match (concat (regexp-quote arg) ".+") cname)
2296 (setq key (concat key key1)))))
2297 todos-insertion-commands-arg-key-list)
2298 (if (string-match (concat (regexp-quote "todos-item-insert") "\\_>") cname)
2299 (setq key (concat key "i")))
2300 (define-key map key c))))
2302 (defvar todos-insertion-map
2303 (let ((map (make-keymap)))
2304 (todos-insertion-key-bindings map)
2306 "Keymap for Todos mode insertion commands.")
2308 ;; ---------------------------------------------------------------------------
2309 ;;; Key maps and menus
2311 (defvar todos-key-bindings
2314 ("Cd" . todos-display-categories) ;FIXME: Cs todos-show-categories?
2315 ;("" . todos-display-categories-alphabetically)
2316 ("H" . todos-highlight-item)
2317 ("N" . todos-hide-show-item-numbering)
2318 ("D" . todos-hide-show-date-time)
2319 ("*" . todos-mark-unmark-item)
2320 ("C*" . todos-mark-category)
2321 ("Cu" . todos-unmark-category)
2322 ("PP" . todos-print)
2323 ("PF" . todos-print-to-file)
2324 ("v" . todos-hide-show-done-items)
2325 ("V" . todos-show-done-only)
2326 ("As" . todos-show-archive)
2327 ("Ac" . todos-choose-archive)
2328 ("Y" . todos-diary-items)
2329 ("Fe" . todos-edit-multiline)
2330 ("Fh" . todos-highlight-item)
2331 ("Fn" . todos-hide-show-item-numbering)
2332 ("Fd" . todos-hide-show-date-time)
2333 ("Ftt" . todos-top-priorities)
2334 ("Ftm" . todos-top-priorities-multifile)
2335 ("Fts" . todos-set-top-priorities-in-file)
2336 ("Cts" . todos-set-top-priorities-in-category)
2337 ("Fyy" . todos-diary-items)
2338 ("Fym" . todos-diary-items-multifile)
2339 ("Fxx" . todos-regexp-items)
2340 ("Fxm" . todos-regexp-items-multifile)
2342 ("f" . todos-forward-category)
2343 ("b" . todos-backward-category)
2344 ("j" . todos-jump-to-category)
2345 ("J" . todos-jump-to-category-other-file)
2346 ("n" . todos-forward-item)
2347 ("p" . todos-backward-item)
2348 ("S" . todos-search)
2349 ("X" . todos-clear-matches)
2351 ("Fa" . todos-add-file)
2352 ("Ca" . todos-add-category)
2353 ("Cr" . todos-rename-category)
2354 ("Cg" . todos-merge-category)
2355 ;;("" . todos-merge-categories)
2356 ("Cm" . todos-move-category)
2357 ("Ck" . todos-delete-category)
2358 ("d" . todos-item-done)
2359 ("ee" . todos-edit-item)
2360 ("em" . todos-edit-multiline-item)
2361 ("eh" . todos-edit-item-header)
2362 ("edd" . todos-edit-item-date)
2363 ("edc" . todos-edit-item-date-from-calendar)
2364 ("edt" . todos-edit-item-date-is-today)
2365 ("et" . todos-edit-item-time)
2366 ("eyy" . todos-edit-item-diary-inclusion)
2367 ;; ("" . todos-edit-category-diary-inclusion)
2368 ("eyn" . todos-edit-item-diary-nonmarking)
2369 ;;("" . todos-edit-category-diary-nonmarking)
2370 ("ec" . todos-done-item-add-edit-or-delete-comment)
2371 ("i" . ,todos-insertion-map)
2372 ("k" . todos-delete-item) ;FIXME: not single letter?
2373 ("m" . todos-move-item)
2374 ("M" . todos-move-item-to-file)
2375 ("r" . todos-raise-item-priority)
2376 ("l" . todos-lower-item-priority)
2377 ("#" . todos-set-item-priority)
2378 ("u" . todos-item-undo)
2379 ("Ad" . todos-archive-done-item) ;FIXME: ad
2380 ("AD" . todos-archive-category-done-items) ;FIXME: aD or C-u ad ?
2383 ([remap newline] . newline-and-indent)
2385 "Alist pairing keys defined in Todos modes and their bindings.")
2387 (defvar todos-mode-map
2388 (let ((map (make-keymap)))
2389 ;; Don't suppress digit keys, so they can supply prefix arguments.
2390 (suppress-keymap map)
2391 (dolist (ck todos-key-bindings)
2392 (define-key map (car ck) (cdr ck)))
2394 "Todos mode keymap.")
2398 todos-menu todos-mode-map "Todos Menu"
2401 ["Next Item" todos-forward-item t]
2402 ["Previous Item" todos-backward-item t]
2404 ["Next Category" todos-forward-category t]
2405 ["Previous Category" todos-backward-category t]
2406 ["Jump to Category" todos-jump-to-category t]
2407 ["Jump to Category in Other File" todos-jump-to-category-other-file t]
2409 ["Search Todos File" todos-search t]
2410 ["Clear Highlighting on Search Matches" todos-category-done t])
2412 ["List Current Categories" todos-display-categories t]
2413 ;; ["List Categories Alphabetically" todos-display-categories-alphabetically t]
2414 ["Turn Item Highlighting on/off" todos-highlight-item t]
2415 ["Turn Item Numbering on/off" todos-hide-show-item-numbering t]
2416 ["Turn Item Time Stamp on/off" todos-hide-show-date-time t]
2417 ["View/Hide Done Items" todos-hide-show-done-items t]
2419 ["View Diary Items" todos-diary-items t]
2420 ["View Top Priority Items" todos-top-priorities t]
2421 ["View Multifile Top Priority Items" todos-top-priorities-multifile t]
2423 ["Print Category" todos-print t])
2425 ["Insert New Item" todos-insert-item t]
2426 ["Insert Item Here" todos-insert-item-here t]
2427 ("More Insertion Commands")
2428 ["Edit Item" todos-edit-item t]
2429 ["Edit Multiline Item" todos-edit-multiline t]
2430 ["Edit Item Header" todos-edit-item-header t]
2431 ["Edit Item Date" todos-edit-item-date t]
2432 ["Edit Item Time" todos-edit-item-time t]
2434 ["Lower Item Priority" todos-lower-item-priority t]
2435 ["Raise Item Priority" todos-raise-item-priority t]
2436 ["Set Item Priority" todos-set-item-priority t]
2437 ["Move (Recategorize) Item" todos-move-item t]
2438 ["Delete Item" todos-delete-item t]
2439 ["Undo Done Item" todos-item-undo t]
2440 ["Mark/Unmark Item for Diary" todos-toggle-item-diary-inclusion t]
2441 ["Mark/Unmark Items for Diary" todos-edit-item-diary-inclusion t]
2442 ["Mark & Hide Done Item" todos-item-done t]
2443 ["Archive Done Items" todos-archive-category-done-items t]
2445 ["Add New Todos File" todos-add-file t]
2446 ["Add New Category" todos-add-category t]
2447 ["Delete Current Category" todos-delete-category t]
2448 ["Rename Current Category" todos-rename-category t]
2450 ["Save Todos File" todos-save t]
2453 ["Quit" todos-quit t]
2456 (defvar todos-archive-mode-map
2457 (let ((map (make-sparse-keymap)))
2458 (suppress-keymap map t)
2459 ;; navigation commands
2460 (define-key map "f" 'todos-forward-category)
2461 (define-key map "b" 'todos-backward-category)
2462 (define-key map "j" 'todos-jump-to-category)
2463 (define-key map "n" 'todos-forward-item)
2464 (define-key map "p" 'todos-backward-item)
2466 (define-key map "C" 'todos-display-categories)
2467 (define-key map "H" 'todos-highlight-item)
2468 (define-key map "N" 'todos-hide-show-item-numbering)
2469 ;; (define-key map "" 'todos-hide-show-date-time)
2470 (define-key map "P" 'todos-print)
2471 (define-key map "q" 'todos-quit)
2472 (define-key map "s" 'todos-save)
2473 (define-key map "S" 'todos-search)
2474 (define-key map "t" 'todos-show)
2475 (define-key map "u" 'todos-unarchive-items)
2476 (define-key map "U" 'todos-unarchive-category)
2478 "Todos Archive mode keymap.")
2480 (defvar todos-edit-mode-map
2481 (let ((map (make-sparse-keymap)))
2482 (define-key map "\C-x\C-q" 'todos-edit-quit)
2483 (define-key map [remap newline] 'newline-and-indent)
2485 "Todos Edit mode keymap.")
2487 (defvar todos-categories-mode-map
2488 (let ((map (make-sparse-keymap)))
2489 (suppress-keymap map t)
2490 (define-key map "c" 'todos-display-categories-alphabetically-or-by-priority)
2491 (define-key map "t" 'todos-display-categories-sorted-by-todo)
2492 (define-key map "y" 'todos-display-categories-sorted-by-diary)
2493 (define-key map "d" 'todos-display-categories-sorted-by-done)
2494 (define-key map "a" 'todos-display-categories-sorted-by-archived)
2495 (define-key map "l" 'todos-lower-category-priority)
2496 (define-key map "+" 'todos-lower-category-priority)
2497 (define-key map "r" 'todos-raise-category-priority)
2498 (define-key map "-" 'todos-raise-category-priority)
2499 (define-key map "n" 'forward-button)
2500 (define-key map "p" 'backward-button)
2501 (define-key map [tab] 'forward-button)
2502 (define-key map [backtab] 'backward-button)
2503 (define-key map "q" 'todos-quit)
2504 ;; (define-key map "A" 'todos-add-category)
2505 ;; (define-key map "D" 'todos-delete-category)
2506 ;; (define-key map "R" 'todos-rename-category)
2508 "Todos Categories mode keymap.")
2510 (defvar todos-filtered-items-mode-map
2511 (let ((map (make-keymap)))
2512 (suppress-keymap map t)
2513 ;; navigation commands
2514 (define-key map "j" 'todos-jump-to-item)
2515 (define-key map [remap newline] 'todos-jump-to-item)
2516 (define-key map "n" 'todos-forward-item)
2517 (define-key map "p" 'todos-backward-item)
2518 (define-key map "H" 'todos-highlight-item)
2519 (define-key map "N" 'todos-hide-show-item-numbering)
2520 (define-key map "D" 'todos-hide-show-date-time)
2521 (define-key map "P" 'todos-print)
2522 (define-key map "q" 'todos-quit)
2523 (define-key map "s" 'todos-save)
2525 (define-key map "l" 'todos-lower-item-priority)
2526 (define-key map "r" 'todos-raise-item-priority)
2527 (define-key map "#" 'todos-set-item-top-priority)
2529 "Todos Top Priorities mode keymap.")
2531 ;; ---------------------------------------------------------------------------
2532 ;;; Mode definitions
2534 (defun todos-modes-set-1 ()
2536 (set (make-local-variable 'font-lock-defaults) '(todos-font-lock-keywords t))
2537 (set (make-local-variable 'indent-line-function) 'todos-indent)
2538 (when todos-wrap-lines (funcall todos-line-wrapping-function)))
2540 (defun todos-modes-set-2 ()
2542 (add-to-invisibility-spec 'todos)
2543 (setq buffer-read-only t)
2544 (set (make-local-variable 'hl-line-range-function)
2545 (lambda() (when (todos-item-end)
2546 (cons (todos-item-start) (todos-item-end))))))
2548 (defun todos-modes-set-3 ()
2549 (set (make-local-variable 'todos-categories) (todos-set-categories))
2550 (set (make-local-variable 'todos-category-number) 1)
2551 (set (make-local-variable 'todos-first-visit) t)
2552 (add-hook 'find-file-hook 'todos-display-as-todos-file nil t))
2554 (put 'todos-mode 'mode-class 'special)
2556 ;; FIXME: Autoloading isn't needed if files are identified by auto-mode-alist
2557 ;; ;; As calendar reads included Todos file before todos-mode is loaded.
2559 (define-derived-mode todos-mode special-mode "Todos" ()
2560 "Major mode for displaying, navigating and editing Todo lists.
2563 (easy-menu-add todos-menu)
2567 ;; Initialize todos-current-todos-file.
2568 (when (member (file-truename (buffer-file-name))
2569 (funcall todos-files-function))
2570 (set (make-local-variable 'todos-current-todos-file)
2571 (file-truename (buffer-file-name))))
2572 (set (make-local-variable 'todos-first-visit) t)
2573 (set (make-local-variable 'todos-show-done-only) nil)
2574 (set (make-local-variable 'todos-categories-with-marks) nil)
2575 (add-hook 'find-file-hook 'todos-add-to-buffer-list nil t)
2576 (add-hook 'post-command-hook 'todos-update-buffer-list nil t)
2577 (when todos-show-current-file
2578 (add-hook 'pre-command-hook 'todos-show-current-file nil t))
2579 (add-hook 'window-configuration-change-hook
2580 'todos-reset-and-enable-done-separator nil t)
2581 (add-hook 'kill-buffer-hook 'todos-reset-global-current-todos-file nil t))
2583 ;; FIXME: need this?
2584 (defun todos-unload-hook ()
2586 (remove-hook 'pre-command-hook 'todos-show-current-file t)
2587 (remove-hook 'post-command-hook 'todos-update-buffer-list t)
2588 (remove-hook 'find-file-hook 'todos-display-as-todos-file t)
2589 (remove-hook 'find-file-hook 'todos-add-to-buffer-list t)
2590 (remove-hook 'window-configuration-change-hook
2591 'todos-reset-and-enable-done-separator t)
2592 (remove-hook 'kill-buffer-hook 'todos-reset-global-current-todos-file t))
2594 (put 'todos-archive-mode 'mode-class 'special)
2596 ;; If todos-mode is parent, all todos-mode key bindings appear to be
2597 ;; available in todos-archive-mode (e.g. shown by C-h m).
2598 (define-derived-mode todos-archive-mode special-mode "Todos-Arch" ()
2599 "Major mode for archived Todos categories.
2601 \\{todos-archive-mode-map}"
2605 (set (make-local-variable 'todos-current-todos-file)
2606 (file-truename (buffer-file-name)))
2607 (set (make-local-variable 'todos-show-done-only) t))
2609 (defun todos-mode-external-set ()
2611 (set (make-local-variable 'todos-current-todos-file)
2612 todos-global-current-todos-file)
2613 (let ((cats (with-current-buffer
2614 (find-buffer-visiting todos-current-todos-file)
2616 (set (make-local-variable 'todos-categories) cats)))
2618 (define-derived-mode todos-edit-mode text-mode "Todos-Ed" ()
2619 "Major mode for editing multiline Todo items.
2621 \\{todos-edit-mode-map}"
2623 (todos-mode-external-set))
2625 (put 'todos-categories-mode 'mode-class 'special)
2627 (define-derived-mode todos-categories-mode special-mode "Todos-Cats" ()
2628 "Major mode for displaying and editing Todos categories.
2630 \\{todos-categories-mode-map}"
2631 (todos-mode-external-set))
2633 (put 'todos-filter-mode 'mode-class 'special)
2635 (define-derived-mode todos-filtered-items-mode special-mode "Todos-Fltr" ()
2636 "Mode for displaying and reprioritizing top priority Todos.
2638 \\{todos-filtered-items-mode-map}"
2640 (todos-modes-set-2))
2642 ;; ---------------------------------------------------------------------------
2645 ;; ---------------------------------------------------------------------------
2646 ;;; Entering and Exiting
2649 (defun todos-show (&optional solicit-file)
2650 "Visit the current Todos file and display one of its categories.
2651 With non-nil prefix argument SOLICIT-FILE prompt for which todo
2654 Without a prefix argument, the first invocation of this command
2655 in a session visits `todos-default-todos-file' (creating it if it
2656 does not yet exist); subsequent invocations from outside of Todos
2657 mode revisit this file or, if the user option
2658 `todos-show-current-file' is non-nil, whichever Todos file
2659 \(either a todo or an archive file) was visited last.
2661 The category displayed on initial invocation is the first member
2662 of `todos-categories' for the current Todos file, on subsequent
2663 invocations whichever category was displayed last. If
2664 `todos-display-categories-first' is non-nil, then the first
2665 invocation of `todos-show' displays a clickable listing of the
2666 categories in the current Todos file.
2668 In Todos mode just the category's unfinished todo items are shown
2669 by default. The done items are hidden, but typing
2670 `\\[todos-hide-show-done-items]' displays them below the todo
2671 items. With non-nil user option `todos-show-with-done' both todo
2672 and done items are always shown on visiting a category.
2674 If this command is invoked in Todos Archive mode, it visits the
2675 corresponding Todos file, displaying the corresponding category."
2678 (file (cond (solicit-file
2679 (if (funcall todos-files-function)
2680 (todos-read-file-name "Choose a Todos file to visit: "
2682 (error "There are no Todos files")))
2683 ((and (eq major-mode 'todos-archive-mode)
2684 ;; Called noninteractively via todos-quit from
2685 ;; Todos Categories mode to return to archive file.
2686 (called-interactively-p 'any))
2687 (setq cat (todos-current-category))
2688 (concat (file-name-sans-extension todos-current-todos-file)
2691 (or todos-current-todos-file
2692 (and todos-show-current-file
2693 todos-global-current-todos-file)
2694 todos-default-todos-file
2695 (todos-add-file))))))
2696 (if (and todos-first-visit todos-display-categories-first)
2697 (todos-display-categories)
2698 (set-window-buffer (selected-window)
2699 (set-buffer (find-file-noselect file)))
2700 ;; If called from archive file, show corresponding category in Todos
2701 ;; file, if it exists.
2702 (when (assoc cat todos-categories)
2703 (setq todos-category-number (todos-category-number cat)))
2704 ;; If no Todos file exists, initialize one.
2705 (when (zerop (buffer-size))
2706 ;; Call with empty category name to get initial prompt.
2707 (setq todos-category-number (todos-add-category "")))
2708 (save-excursion (todos-category-select)))
2709 (setq todos-first-visit nil)))
2711 (defun todos-display-categories ()
2712 "Display a table of the current file's categories and item counts.
2714 In the initial display the categories are numbered, indicating
2715 their current order for navigating by \\[todos-forward-category]
2716 and \\[todos-backward-category]. You can persistantly change the
2717 order of the category at point by typing
2718 \\[todos-raise-category-priority] or
2719 \\[todos-lower-category-priority].
2721 The labels above the category names and item counts are buttons,
2722 and clicking these changes the display: sorted by category name
2723 or by the respective item counts (alternately descending or
2724 ascending). In these displays the categories are not numbered
2725 and \\[todos-raise-category-priority] and
2726 \\[todos-lower-category-priority] are
2727 disabled. (Programmatically, the sorting is triggered by passing
2728 a non-nil SORTKEY argument.)
2730 In addition, the lines with the category names and item counts
2731 are buttonized, and pressing one of these button jumps to the
2732 category in Todos mode (or Todos Archive mode, for categories
2733 containing only archived items, provided user option
2734 `todos-skip-archived-categories' is non-nil. These categories
2735 are shown in `todos-archived-only' face."
2737 (todos-display-categories-1)
2739 (todos-update-categories-display sortkey)))
2741 (defun todos-display-categories-alphabetically-or-by-priority ()
2745 (goto-char (point-min))
2747 (if (member 'alpha todos-descending-counts)
2749 (todos-update-categories-display nil)
2750 (setq todos-descending-counts
2751 (delete 'alpha todos-descending-counts)))
2752 (todos-update-categories-display 'alpha))))
2754 (defun todos-display-categories-sorted-by-todo ()
2758 (goto-char (point-min))
2760 (todos-update-categories-display 'todo)))
2762 (defun todos-display-categories-sorted-by-diary ()
2766 (goto-char (point-min))
2768 (todos-update-categories-display 'diary)))
2770 (defun todos-display-categories-sorted-by-done ()
2774 (goto-char (point-min))
2776 (todos-update-categories-display 'done)))
2778 (defun todos-display-categories-sorted-by-archived ()
2782 (goto-char (point-min))
2784 (todos-update-categories-display 'archived)))
2786 (defun todos-show-archive (&optional ask)
2787 "Visit the archive of the current Todos category, if it exists.
2788 If the category has no archived items, prompt to visit the
2789 archive anyway. If there is no archive for this file or with
2790 non-nil argument ASK, prompt to visit another archive.
2792 The buffer showing the archive is in Todos Archive mode. The
2793 first visit in a session displays the first category in the
2794 archive, subsequent visits return to the last category
2797 (let* ((cat (todos-current-category))
2798 (count (todos-get-count 'archived cat))
2799 (archive (concat (file-name-sans-extension todos-current-todos-file)
2802 (setq place (cond (ask 'other-archive)
2803 ((file-exists-p archive) 'this-archive)
2804 (t (when (y-or-n-p (concat "This file has no archive; "
2805 "visit another archive? "))
2807 (when (eq place 'other-archive)
2808 (setq archive (todos-read-file-name "Choose a Todos archive: " t t)))
2809 (when (and (eq place 'this-archive) (zerop count))
2810 (setq place (when (y-or-n-p
2811 (concat "This category has no archived items;"
2812 " visit archive anyway? "))
2815 (set-window-buffer (selected-window)
2816 (set-buffer (find-file-noselect archive)))
2817 (if (member place '(other-archive other-cat))
2818 (setq todos-category-number 1)
2819 (todos-category-number cat))
2820 (todos-category-select))))
2822 (defun todos-choose-archive ()
2823 "Choose an archive and visit it."
2825 (todos-show-archive t))
2827 ;; FIXME: need this?
2828 (defun todos-save ()
2829 "Save the current Todos file."
2833 (defun todos-quit ()
2834 "Exit the current Todos-related buffer.
2835 Depending on the specific mode, this either kills the buffer or
2836 buries it and restores state as needed."
2838 (cond ((eq major-mode 'todos-categories-mode)
2840 (setq todos-descending-counts nil)
2842 ((eq major-mode 'todos-filtered-items-mode)
2845 ((member major-mode (list 'todos-mode 'todos-archive-mode))
2846 ;; Have to write previously nonexistant archives to file.
2847 (unless (file-exists-p (buffer-file-name)) (todos-save))
2848 ;; FIXME: make this customizable?
2852 (defun todos-print (&optional to-file)
2853 "Produce a printable version of the current Todos buffer.
2854 This converts overlays and soft line wrapping and, depending on
2855 the value of `todos-print-function', includes faces. With
2856 non-nil argument TO-FILE write the printable version to a file;
2857 otherwise, send it to the default printer."
2859 (let ((buf todos-print-buffer)
2861 ((eq major-mode 'todos-mode)
2862 (concat "Todos File: "
2863 (todos-short-file-name todos-current-todos-file)
2864 "\nCategory: " (todos-current-category)))
2865 ((eq major-mode 'todos-filtered-items-mode)
2866 "Todos Top Priorities")))
2867 (prefix (propertize (concat todos-prefix " ")
2868 'face 'todos-prefix-string))
2870 (fill-prefix (make-string todos-indent-to-here 32))
2871 (content (buffer-string))
2873 (with-current-buffer (get-buffer-create buf)
2875 (goto-char (point-min))
2878 (end (save-excursion (todos-item-end))))
2879 (when todos-number-priorities
2881 (setq prefix (propertize (concat (number-to-string num) " ")
2882 'face 'todos-prefix-string)))
2884 (fill-region beg end))
2885 ;; Calling todos-forward-item infloops at todos-item-start due to
2886 ;; non-overlay prefix, so search for item start instead.
2887 (if (re-search-forward todos-item-start nil t)
2889 (goto-char (point-max))))
2890 (if (re-search-backward (concat "^" (regexp-quote todos-category-done))
2892 (replace-match todos-done-separator))
2893 (goto-char (point-min))
2897 (let ((file (read-file-name "Print to file: ")))
2898 (funcall todos-print-function file))
2899 (funcall todos-print-function)))
2902 (defun todos-print-to-file ()
2903 "Save printable version of this Todos buffer to a file."
2907 (defun todos-convert-legacy-files ()
2908 "Convert legacy Todo files to the current Todos format.
2909 The files `todo-file-do' and `todo-file-done' are converted and
2910 saved (the latter as a Todos Archive file) with a new name in
2911 `todos-files-directory'. See also the documentation string of
2912 `todos-todo-mode-date-time-regexp' for further details."
2914 (if (fboundp 'todo-mode)
2915 (require 'todo-mode)
2916 (error "Void function `todo-mode'"))
2917 ;; Convert `todo-file-do'.
2918 (if (file-exists-p todo-file-do)
2919 (let ((default "todo-do-conv")
2922 (insert-file-contents todo-file-do)
2923 (let ((end (search-forward ")" (line-end-position) t))
2924 (beg (search-backward "(" (line-beginning-position) t)))
2925 (setq todo-categories
2926 (read (buffer-substring-no-properties beg end))))
2928 (delete-region (line-beginning-position) (1+ (line-end-position)))
2931 ((looking-at (regexp-quote (concat todo-prefix todo-category-beg)))
2932 (replace-match todos-category-beg))
2933 ((looking-at (regexp-quote todo-category-end))
2935 ((looking-at (regexp-quote (concat todo-prefix " "
2936 todo-category-sep)))
2937 (replace-match todos-category-done))
2938 ((looking-at (concat (regexp-quote todo-prefix) " "
2939 todos-todo-mode-date-time-regexp " "
2940 (regexp-quote todo-initials) ":"))
2941 (todos-convert-legacy-date-time)))
2943 (setq file (concat todos-files-directory
2945 (format "Save file as (default \"%s\"): " default)
2948 (write-region (point-min) (point-max) file nil 'nomessage nil t))
2950 (insert-file-contents file)
2951 (let ((todos-categories (todos-make-categories-list t)))
2952 (todos-update-categories-sexp))
2953 (write-region (point-min) (point-max) file nil 'nomessage))
2954 ;; Convert `todo-file-done'.
2955 (when (file-exists-p todo-file-done)
2957 (insert-file-contents todo-file-done)
2958 (let ((beg (make-marker))
2960 cat cats comment item)
2962 (when (looking-at todos-todo-mode-date-time-regexp)
2963 (set-marker beg (point))
2964 (todos-convert-legacy-date-time)
2965 (set-marker end (point))
2967 (insert "[" todos-done-string)
2971 (when (looking-at todos-todo-mode-date-time-regexp)
2972 (todos-convert-legacy-date-time))
2973 (when (looking-at (concat " " (regexp-quote todo-initials) ":"))
2974 (replace-match "")))
2975 (if (re-search-forward
2976 (concat "^" todos-todo-mode-date-time-regexp) nil t)
2977 (goto-char (match-beginning 0))
2978 (goto-char (point-max)))
2980 (when (looking-back "\\[\\([^][]+\\)\\]")
2981 (setq cat (match-string 1))
2982 (goto-char (match-beginning 0))
2984 ;; If the item ends with a non-comment parenthesis not
2985 ;; followed by a period, we lose (but we inherit that problem
2986 ;; from todo-mode.el).
2987 (when (looking-back "(\\(.*\\)) ")
2988 (setq comment (match-string 1))
2990 (insert "[" todos-comment-string ": " comment "]"))
2991 (set-marker end (point))
2992 (if (member cat cats)
2993 ;; If item is already in its category, leave it there.
2994 (unless (save-excursion
2996 (concat "^" (regexp-quote todos-category-beg)
2998 (string= (match-string 1) cat))
2999 ;; Else move it to its category.
3000 (setq item (buffer-substring-no-properties beg end))
3001 (delete-region beg (1+ end))
3002 (set-marker beg (point))
3004 (concat "^" (regexp-quote (concat todos-category-beg cat)))
3007 (if (re-search-forward
3008 (concat "^" (regexp-quote todos-category-beg)
3010 (progn (goto-char (match-beginning 0))
3013 (goto-char (point-max)))
3018 (insert todos-category-beg cat "\n\n" todos-category-done "\n"))
3020 (set-marker beg nil)
3021 (set-marker end nil))
3022 (setq file (concat (file-name-sans-extension file) ".toda"))
3023 (write-region (point-min) (point-max) file nil 'nomessage nil t))
3025 (insert-file-contents file)
3026 (let ((todos-categories (todos-make-categories-list t)))
3027 (todos-update-categories-sexp))
3028 (write-region (point-min) (point-max) file nil 'nomessage)
3029 (setq archive-sexp (read (buffer-substring-no-properties
3030 (line-beginning-position)
3031 (line-end-position)))))
3032 (setq file (concat (file-name-sans-extension file) ".todo"))
3033 ;; Update categories sexp of converted Todos file again, adding
3034 ;; counts of archived items.
3036 (insert-file-contents file)
3037 (let ((sexp (read (buffer-substring-no-properties
3038 (line-beginning-position)
3039 (line-end-position)))))
3041 (let ((archive-cat (assoc (car cat) archive-sexp)))
3043 (aset (cdr cat) 3 (aref (cdr archive-cat) 2)))))
3044 (delete-region (line-beginning-position) (line-end-position))
3045 (prin1 sexp (current-buffer)))
3046 (write-region (point-min) (point-max) file nil 'nomessage)))
3047 (todos-reevaluate-defcustoms)
3048 (message "Format conversion done."))
3049 (error "No legacy Todo file exists")))
3051 ;; ---------------------------------------------------------------------------
3052 ;;; Navigation Commands
3054 (defun todos-forward-category (&optional back)
3055 "Visit the numerically next category in this Todos file.
3056 If the current category is the highest numbered, visit the first
3057 category. With non-nil argument BACK, visit the numerically
3058 previous category (the highest numbered one, if the current
3059 category is the first)."
3061 (setq todos-category-number
3062 (1+ (mod (- todos-category-number (if back 2 0))
3063 (length todos-categories))))
3064 (when todos-skip-archived-categories
3065 (while (and (zerop (todos-get-count 'todo))
3066 (zerop (todos-get-count 'done))
3067 (not (zerop (todos-get-count 'archive))))
3068 (setq todos-category-number
3069 (apply (if back '1- '1+) (list todos-category-number)))))
3070 (todos-category-select)
3071 (goto-char (point-min)))
3073 (defun todos-backward-category ()
3074 "Visit the numerically previous category in this Todos file.
3075 If the current category is the highest numbered, visit the first
3078 (todos-forward-category t))
3080 (defun todos-jump-to-category (&optional cat other-file)
3081 "Jump to a category in this or another Todos file.
3083 Programmatically, optional argument CAT provides the category
3084 name. When nil (as in interactive calls), prompt for the
3085 category, with TAB completion on existing categories. If a
3086 non-existing category name is entered, ask whether to add a new
3087 category with this name; if affirmed, add it, then jump to that
3088 category. With non-nil argument OTHER-FILE, prompt for a Todos
3089 file, otherwise jump within the current Todos file."
3091 (let ((file (or (and other-file
3092 (todos-read-file-name "Choose a Todos file: " nil t))
3093 ;; Jump to archived-only Categories from Todos Categories
3096 todos-skip-archived-categories
3097 (zerop (todos-get-count 'todo cat))
3098 (zerop (todos-get-count 'done cat))
3099 (not (zerop (todos-get-count 'archived cat)))
3100 (concat (file-name-sans-extension
3101 todos-current-todos-file) ".toda"))
3102 todos-current-todos-file
3103 ;; If invoked from outside of Todos mode before
3105 todos-default-todos-file)))
3106 (with-current-buffer (find-file-noselect file)
3107 (and other-file (setq todos-current-todos-file file))
3108 (let ((category (or (and (assoc cat todos-categories) cat)
3109 (todos-read-category "Jump to category: "))))
3110 ;; Clean up after selecting category in Todos Categories mode.
3111 (if (string= (buffer-name) todos-categories-buffer)
3113 (if (or cat other-file)
3114 (set-window-buffer (selected-window)
3115 (set-buffer (find-buffer-visiting file))))
3116 (unless todos-global-current-todos-file
3117 (setq todos-global-current-todos-file todos-current-todos-file))
3118 (todos-category-number category) ; (1+ (length t-c)) if new category.
3119 ;; (if (> todos-category-number (length todos-categories))
3120 ;; (setq todos-category-number (todos-add-category category)))
3121 (todos-category-select)
3122 (goto-char (point-min))))))
3124 (defun todos-jump-to-category-other-file ()
3125 "Jump to a category in another Todos file.
3126 The category is chosen by prompt, with TAB completion."
3128 (todos-jump-to-category nil t))
3130 (defun todos-jump-to-item ()
3131 "Jump to the file and category of the filtered item at point."
3133 (let ((str (todos-item-string))
3134 (buf (current-buffer))
3135 cat file archive beg)
3136 (string-match (concat (if todos-filter-done-items
3137 (concat "\\(?:" todos-done-string-start "\\|"
3138 todos-date-string-start "\\)")
3139 todos-date-string-start)
3140 todos-date-pattern "\\(?: " diary-time-regexp "\\)?"
3141 (if todos-filter-done-items
3143 (regexp-quote todos-nondiary-end)) "?"
3144 "\\(?4: \\[\\(?3:(archive) \\)?\\(?2:.*:\\)?"
3145 "\\(?1:.*\\)\\]\\).*$") str)
3146 (setq cat (match-string 1 str))
3147 (setq file (match-string 2 str))
3148 (setq archive (string= (match-string 3 str) "(archive) "))
3149 (setq str (replace-match "" nil nil str 4))
3151 (concat todos-files-directory (substring file 0 -1)
3152 (if archive ".toda" ".todo"))
3154 (concat (file-name-sans-extension
3155 todos-global-current-todos-file) ".toda")
3156 todos-global-current-todos-file)))
3157 (find-file-noselect file)
3158 (with-current-buffer (find-buffer-visiting file)
3160 (goto-char (point-min))
3162 (concat "^" (regexp-quote (concat todos-category-beg cat))) nil t)
3163 (search-forward str)
3164 (setq beg (match-beginning 0)))
3166 (set-window-buffer (selected-window) (set-buffer (find-buffer-visiting file)))
3167 (setq todos-current-todos-file file)
3168 (setq todos-category-number (todos-category-number cat))
3169 (let ((todos-show-with-done (if todos-filter-done-items t
3170 todos-show-with-done)))
3171 (todos-category-select))
3174 ;; FIXME ? disallow prefix arg value < 1 (re-search-* allows these)
3175 (defun todos-forward-item (&optional count)
3176 "Move point down to start of item with next lower priority.
3177 With numerical prefix COUNT, move point COUNT items downward,"
3179 (let* ((not-done (not (or (todos-done-item-p) (looking-at "^$"))))
3180 (start (line-end-position)))
3182 (if (re-search-forward todos-item-start nil t (or count 1))
3183 (goto-char (match-beginning 0))
3184 (goto-char (point-max)))
3185 ;; If points advances by one from a todo to a done item, go back to the
3186 ;; space above todos-done-separator, since that is a legitimate place to
3187 ;; insert an item. But skip this space if count > 1, since that should
3188 ;; only stop on an item (FIXME: or not?)
3189 (when (and not-done (todos-done-item-p))
3190 (if (or (not count) (= count 1))
3191 (re-search-backward "^$" start t)))))
3192 ;; FIXME: The preceding sexp is insufficient when buffer is not narrowed,
3193 ;; since there could be no done items in this category, so the search puts
3194 ;; us on first todo item of next category. Does this ever happen? If so:
3195 ;; (let ((opoint) (point))
3196 ;; (forward-line -1)
3197 ;; (when (or (not count) (= count 1))
3198 ;; (cond ((looking-at (concat "^" (regexp-quote todos-category-beg)))
3199 ;; (forward-line -2))
3200 ;; ((looking-at (concat "^" (regexp-quote todos-category-done)))
3201 ;; (forward-line -1))
3203 ;; (goto-char opoint)))))))
3205 (defun todos-backward-item (&optional count)
3206 "Move point up to start of item with next higher priority.
3207 With numerical prefix COUNT, move point COUNT items upward,"
3209 (let* ((done (todos-done-item-p)))
3210 ;; FIXME ? this moves to bob if on the first item (but so does previous-line)
3213 (re-search-backward todos-item-start nil t (or count 1)))
3214 ;; Unless this is a regexp filtered items buffer (which can contain
3215 ;; intermixed todo and done items), if points advances by one from a done
3216 ;; to a todo item, go back to the space above todos-done-separator, since
3217 ;; that is a legitimate place to insert an item. But skip this space if
3218 ;; count > 1, since that should only stop on an item (FIXME: or not?)
3219 (when (and done (not (todos-done-item-p)) (or (not count) (= count 1))
3220 (not (equal (buffer-name) todos-regexp-items-buffer)))
3221 (re-search-forward (concat "^" (regexp-quote todos-category-done)) nil t)
3222 (forward-line -1))))
3224 ;; FIXME: (i) Extend search to other Todos files. (ii) Allow navigating among
3225 ;; hits. (But these are available in another form with
3226 ;; todos-regexp-items-multifile.)
3227 (defun todos-search ()
3228 "Search for a regular expression in this Todos file.
3229 The search runs through the whole file and encompasses all and
3230 only todo and done items; it excludes category names. Multiple
3231 matches are shown sequentially, highlighted in `todos-search'
3234 (let ((regex (read-from-minibuffer "Enter a search string (regexp): "))
3236 matches match cat in-done ov mlen msg)
3238 (goto-char (point-min))
3240 (setq match (re-search-forward regex nil t))
3241 (goto-char (line-beginning-position))
3242 (unless (or (equal (point) 1)
3243 (looking-at (concat "^" (regexp-quote todos-category-beg))))
3244 (if match (push match matches)))
3246 (setq matches (reverse matches))
3250 (setq match (pop matches))
3253 (when (looking-at todos-done-string-start)
3255 (re-search-backward (concat "^" (regexp-quote todos-category-beg)
3256 "\\(.*\\)\n") nil t)
3257 (setq cat (match-string-no-properties 1))
3258 (todos-category-number cat)
3259 (todos-category-select)
3261 (unless todos-show-with-done (todos-hide-show-done-items)))
3263 (setq ov (make-overlay (- (point) (length regex)) (point)))
3264 (overlay-put ov 'face 'todos-search)
3266 (setq mlen (length matches))
3269 (format "There are %d more matches; go to next match? "
3271 "There is one more match; go to it? "))
3273 (throw 'stop (setq msg (if (> mlen 1)
3274 (format "There are %d more matches."
3276 "There is one more match."))))))
3277 (setq msg "There are no more matches."))
3278 (todos-category-select)
3280 (message "No match for \"%s\"" regex))
3282 (if (y-or-n-p (concat msg "\nUnhighlight matches? "))
3283 (todos-clear-matches)
3284 (message "You can unhighlight the matches later by typing %s"
3285 (key-description (car (where-is-internal
3286 'todos-clear-matches))))))))
3288 (defun todos-clear-matches ()
3289 "Remove highlighting on matches found by todos-search."
3291 (remove-overlays 1 (1+ (buffer-size)) 'face 'todos-search))
3293 ;; ---------------------------------------------------------------------------
3294 ;;; Display Commands
3296 (defun todos-hide-show-item-numbering ()
3299 (todos-reset-prefix 'todos-number-priorities (not todos-number-priorities)))
3301 (defun todos-hide-show-done-items ()
3302 "Show hidden or hide visible done items in current category."
3304 (if (zerop (todos-get-count 'done (todos-current-category)))
3305 (message "There are no done items in this category.")
3307 (goto-char (point-min))
3308 (let ((todos-show-with-done (not (re-search-forward
3309 todos-done-string-start nil t))))
3310 (todos-category-select)))))
3312 (defun todos-show-done-only ()
3313 "Switch between displaying only done or only todo items."
3315 (setq todos-show-done-only (not todos-show-done-only))
3316 (todos-category-select))
3318 (defun todos-highlight-item ()
3319 "Toggle highlighting the todo item the cursor is on."
3326 (defun todos-hide-show-date-time () ;(&optional all)
3327 "Hide or show date-time header of todo items.";; in current category.
3328 ;; With non-nil prefix argument ALL do this in the whole file."
3332 (goto-char (point-min))
3333 (let ((ovs (overlays-in (point) (1+ (point))))
3337 (if (equal (overlay-get ov 'display) "")
3338 (setq ovs nil hidden t)))
3341 (goto-char (point-min));)
3343 (remove-overlays (point-min) (point-max) 'display "")
3345 (when (re-search-forward
3346 (concat todos-date-string-start todos-date-pattern
3347 "\\( " diary-time-regexp "\\)?"
3348 (regexp-quote todos-nondiary-end) "? ")
3350 (unless (save-match-data (todos-done-item-p))
3351 (setq ov (make-overlay (match-beginning 0) (match-end 0) nil t))
3352 (overlay-put ov 'display "")))
3353 (todos-forward-item)))))))
3355 (defun todos-mark-unmark-item (&optional n all)
3356 "Mark item at point if unmarked, or unmark it if marked.
3358 With a positive numerical prefix argument N, change the
3359 markedness of the next N items. With non-nil argument ALL, mark
3360 all visible items in the category (depending on visibility, all
3361 todo and done items, or just todo or just done items).
3363 The mark is the character \"*\" inserted in front of the item's
3364 priority number or the `todos-prefix' string; if `todos-prefix'
3365 is \"*\", then the mark is \"@\"."
3367 (if all (goto-char (point-min)))
3368 (unless (> n 0) (setq n 1))
3370 (while (or (and all (not (eobp)))
3372 (let* ((cat (todos-current-category))
3373 (ov (todos-marked-item-p))
3374 (marked (assoc cat todos-categories-with-marks)))
3375 (if (and ov (not all))
3378 (if (= (cdr marked) 1) ; Deleted last mark in this category.
3379 (setq todos-categories-with-marks
3380 (assq-delete-all cat todos-categories-with-marks))
3381 (setcdr marked (1- (cdr marked)))))
3382 (when (todos-item-start)
3383 (unless (and all (todos-marked-item-p))
3384 (setq ov (make-overlay (point) (point)))
3385 (overlay-put ov 'before-string todos-item-mark)
3387 (setcdr marked (1+ (cdr marked)))
3388 (push (cons cat 1) todos-categories-with-marks))))))
3389 (todos-forward-item)
3392 (defun todos-mark-category ()
3393 "Put the \"*\" mark on all items in this category.
3394 \(If `todos-prefix' is \"*\", then the mark is \"@\".)"
3396 (todos-mark-unmark-item 0 t))
3398 (defun todos-unmark-category ()
3399 "Remove the \"*\" mark from all items in this category.
3400 \(If `todos-prefix' is \"*\", then the mark is \"@\".)"
3402 (remove-overlays (point-min) (point-max) 'before-string todos-item-mark)
3403 (setq todos-categories-with-marks
3404 (delq (assoc (todos-current-category) todos-categories-with-marks)
3405 todos-categories-with-marks)))
3407 ;; ---------------------------------------------------------------------------
3408 ;;; Item filtering commands
3410 (defun todos-set-top-priorities-in-file ()
3411 "Set number of top priorities for this file.
3412 See `todos-set-top-priorities' for more details."
3414 (todos-set-top-priorities))
3416 (defun todos-set-top-priorities-in-category ()
3417 "Set number of top priorities for this category.
3418 See `todos-set-top-priorities' for more details."
3420 (todos-set-top-priorities t))
3422 (defun todos-top-priorities (&optional num)
3423 "List top priorities of each category in `todos-filter-files'.
3424 Number of entries for each category is given by NUM, which
3425 defaults to `todos-show-priorities'."
3427 (let ((arg (if num (cons 'top num) 'top))
3428 (buf todos-top-priorities-buffer)
3429 (file todos-current-todos-file))
3430 (todos-filter-items arg)
3431 (todos-filtered-buffer-name buf file)))
3433 (defun todos-top-priorities-multifile (&optional arg)
3434 "List top priorities of each category in `todos-filter-files'.
3436 If the prefix argument ARG is a number, this is the maximum
3437 number of top priorities to list in each category. If the prefix
3438 argument is `C-u', prompt for which files to filter and use
3439 `todos-show-priorities' as the number of top priorities to list
3440 in each category. If the prefix argument is `C-uC-u', prompt
3441 both for which files to filter and for how many top priorities to
3442 list in each category."
3444 (let* ((buf todos-top-priorities-buffer)
3446 (pref (if (numberp arg)
3448 (setq files (if (or (consp arg)
3449 (null todos-filter-files))
3450 (progn (todos-multiple-filter-files)
3451 todos-multiple-filter-files)
3452 todos-filter-files))
3453 (if (equal arg '(16))
3454 (cons 'top (read-number
3455 "Enter number of top priorities to show: "
3456 todos-show-priorities))
3458 (todos-filter-items pref t)
3459 (todos-filtered-buffer-name buf files)))
3461 (defun todos-diary-items ()
3462 "Display todo items for diary inclusion in this Todos file."
3464 (let ((buf todos-diary-items-buffer)
3465 (file todos-current-todos-file))
3466 (todos-filter-items 'diary)
3467 (todos-filtered-buffer-name buf file)))
3469 (defun todos-diary-items-multifile (&optional arg)
3470 "Display todo items for diary inclusion in one or more Todos file.
3471 The files are those listed in `todos-filter-files'."
3473 (let ((buf todos-diary-items-buffer)
3474 (files (if (or arg (null todos-filter-files))
3475 (progn (todos-multiple-filter-files)
3476 todos-multiple-filter-files)
3477 todos-filter-files)))
3478 (todos-filter-items 'diary t)
3479 (todos-filtered-buffer-name buf files)))
3481 (defun todos-regexp-items ()
3482 "Display todo items matching a user-entered regular expression.
3483 The items are those in the current Todos file."
3485 (let ((buf todos-regexp-items-buffer)
3486 (file todos-current-todos-file))
3487 (todos-filter-items 'regexp)
3488 (todos-filtered-buffer-name buf file)))
3490 (defun todos-regexp-items-multifile (&optional arg)
3491 "Display todo items matching a user-entered regular expression.
3492 The items are those in the files listed in `todos-filter-files'."
3494 (let ((buf todos-regexp-items-buffer)
3495 (files (if (or arg (null todos-filter-files))
3496 (progn (todos-multiple-filter-files)
3497 todos-multiple-filter-files)
3498 todos-filter-files)))
3499 (todos-filter-items 'regexp t)
3500 (todos-filtered-buffer-name buf files)))
3502 ;;; Editing Commands
3504 (defun todos-add-file ()
3505 "Name and add a new Todos file.
3506 Interactively, prompt for a category and display it.
3507 Noninteractively, return the name of the new file."
3509 (let ((prompt (concat "Enter name of new Todos file "
3510 "(TAB or SPC to see current names): "))
3512 (setq file (todos-read-file-name prompt))
3513 (with-current-buffer (get-buffer-create file)
3515 (write-region (point-min) (point-max) file nil 'nomessage nil t)
3517 (todos-reevaluate-defcustoms)
3518 (if (called-interactively-p)
3520 (set-window-buffer (selected-window)
3521 (set-buffer (find-file-noselect file)))
3522 (setq todos-current-todos-file file)
3526 ;; ---------------------------------------------------------------------------
3527 ;;; Category editing commands
3529 (defun todos-add-category (&optional cat)
3530 "Add a new category to the current Todos file.
3531 Called interactively, prompts for category name, then visits the
3532 category in Todos mode. Non-interactively, argument CAT provides
3533 the category name and the return value is the category number."
3535 (let* ((buffer-read-only)
3536 (num (1+ (length todos-categories)))
3537 (counts (make-vector 4 0))) ; [todo diary done archived]
3539 (setq cat (todos-read-category "Enter new category name: " nil t)))
3540 (setq todos-categories (append todos-categories (list (cons cat counts))))
3542 (goto-char (point-max))
3543 (save-excursion ; Save point for todos-category-select.
3544 (insert todos-category-beg cat "\n\n" todos-category-done "\n"))
3545 (todos-update-categories-sexp)
3546 ;; If invoked by user, display the newly added category, if called
3547 ;; programmatically return the category number to the caller.
3548 (if (called-interactively-p 'any)
3550 (setq todos-category-number num)
3551 (todos-category-select))
3554 (defun todos-rename-category ()
3555 "Rename current Todos category.
3556 If this file has an archive containing this category, rename the
3557 category there as well."
3559 (let* ((cat (todos-current-category))
3560 (new (read-from-minibuffer (format "Rename category \"%s\" to: " cat))))
3561 (setq new (todos-validate-name new 'category))
3562 (let* ((ofile todos-current-todos-file)
3563 (archive (concat (file-name-sans-extension ofile) ".toda"))
3564 (buffers (append (list ofile)
3565 (unless (zerop (todos-get-count 'archived cat))
3567 (dolist (buf buffers)
3568 (with-current-buffer (find-file-noselect buf)
3569 (let (buffer-read-only)
3570 (setq todos-categories (todos-set-categories))
3573 (setcar (assoc cat todos-categories) new)
3575 (goto-char (point-min))
3576 (todos-update-categories-sexp)
3577 (re-search-forward (concat (regexp-quote todos-category-beg)
3578 "\\(" (regexp-quote cat) "\\)\n")
3580 (replace-match new t t nil 1)))))))
3581 (force-mode-line-update))
3582 (save-excursion (todos-category-select)))
3584 (defun todos-delete-category (&optional arg)
3585 "Delete current Todos category provided it is empty.
3586 With ARG non-nil delete the category unconditionally,
3587 i.e. including all existing todo and done items."
3589 (let* ((file todos-current-todos-file)
3590 (cat (todos-current-category))
3591 (todo (todos-get-count 'todo cat))
3592 (done (todos-get-count 'done cat))
3593 (archived (todos-get-count 'archived cat)))
3595 (or (> todo 0) (> done 0)))
3596 (message "%s" (substitute-command-keys
3597 (concat "To delete a non-empty category, "
3598 "type C-u \\[todos-delete-category].")))
3599 (when (cond ((= (length todos-categories) 1)
3600 (y-or-n-p (concat "This is the only category in this file; "
3601 "deleting it will also delete the file.\n"
3602 "Do you want to proceed? ")))
3604 (y-or-n-p (concat "This category has archived items; "
3605 "the archived category will remain\n"
3606 "after deleting the todo category. "
3607 "Do you still want to delete it\n"
3608 "(see 'todos-skip-archived-categories' "
3609 "for another option)? ")))
3611 (y-or-n-p (concat "Permanently remove category \"" cat
3612 "\"" (and arg " and all its entries")
3615 (let ((buffer-read-only)
3616 (beg (re-search-backward
3617 (concat "^" (regexp-quote (concat todos-category-beg cat))
3619 (end (if (re-search-forward
3620 (concat "\n\\(" (regexp-quote todos-category-beg)
3624 (remove-overlays beg end)
3625 (delete-region beg end)
3626 (if (= (length todos-categories) 1)
3627 ;; If deleted category was the only one, delete the file.
3629 (todos-reevaluate-defcustoms)
3630 ;; Skip confirming killing the archive buffer if it has been
3631 ;; modified and not saved.
3632 (set-buffer-modified-p nil)
3635 (message "Deleted Todos file %s." file))
3636 (setq todos-categories (delete (assoc cat todos-categories)
3638 (todos-update-categories-sexp)
3639 (setq todos-category-number
3640 (1+ (mod todos-category-number (length todos-categories))))
3641 (todos-category-select)
3642 (goto-char (point-min))
3643 (message "Deleted category %s." cat)))))))
3645 (defun todos-move-category ()
3646 "Move current category to a different Todos file.
3647 If current category has archived items, also move those to the
3648 archive of the file moved to, creating it if it does not exist."
3650 (when (or (> (length todos-categories) 1)
3651 (y-or-n-p (concat "This is the only category in this file; "
3652 "moving it will also delete the file.\n"
3653 "Do you want to proceed? ")))
3654 (let* ((ofile todos-current-todos-file)
3655 (cat (todos-current-category))
3656 (nfile (todos-read-file-name "Choose a Todos file: " nil t))
3657 (archive (concat (file-name-sans-extension ofile) ".toda"))
3658 (buffers (append (list ofile)
3659 (unless (zerop (todos-get-count 'archived cat))
3662 (dolist (buf buffers)
3663 (with-current-buffer (find-file-noselect buf)
3665 (goto-char (point-max))
3666 (let* ((beg (re-search-backward
3668 (regexp-quote (concat todos-category-beg cat)))
3670 (end (if (re-search-forward
3671 (concat "^" (regexp-quote todos-category-beg))
3675 (content (buffer-substring-no-properties beg end))
3676 (counts (cdr (assoc cat todos-categories)))
3678 ;; Move the category to the new file. Also update or create
3679 ;; archive file if necessary.
3680 (with-current-buffer
3682 ;; Regenerate todos-archives in case there
3683 ;; is a newly created archive.
3684 (if (member buf (funcall todos-files-function t))
3685 (concat (file-name-sans-extension nfile) ".toda")
3687 (let* ((nfile-short (todos-short-file-name nfile))
3689 (format "Todos file \"%s\" already has "
3691 (format "the category \"%s\";\n" cat)
3692 "enter a new category name: "))
3695 (goto-char (point-max))
3697 ;; If the file moved to has a category with the same
3698 ;; name, rename the moved category.
3699 (when (assoc cat todos-categories)
3700 (unless (member (file-truename (buffer-file-name))
3701 (funcall todos-files-function t))
3702 (setq new (read-from-minibuffer prompt))
3703 (setq new (todos-validate-name new 'category))))
3704 ;; Replace old with new name in Todos and archive files.
3706 (goto-char (point-max))
3708 (concat "^" (regexp-quote todos-category-beg)
3709 "\\(" (regexp-quote cat) "\\)") nil t)
3710 (replace-match new nil nil nil 1)))
3711 (setq todos-categories
3712 (append todos-categories (list (cons new counts))))
3713 (todos-update-categories-sexp)
3714 ;; If archive was just created, save it to avoid "File <xyz> no
3715 ;; longer exists!" message on invoking
3716 ;; `todos-view-archived-items'. FIXME: maybe better to save
3718 (unless (file-exists-p (buffer-file-name))
3720 (todos-category-number (or new cat))
3721 (todos-category-select))
3722 ;; Delete the category from the old file, and if that was the
3723 ;; last category, delete the file. Also handle archive file
3725 (remove-overlays beg end)
3726 (delete-region beg end)
3727 (goto-char (point-min))
3728 ;; Put point after todos-categories sexp.
3730 (if (eobp) ; Aside from sexp, file is empty.
3732 ;; Skip confirming killing the archive buffer.
3733 (set-buffer-modified-p nil)
3734 (delete-file todos-current-todos-file)
3736 (when (member todos-current-todos-file todos-files)
3737 (todos-reevaluate-defcustoms)))
3738 (setq todos-categories (delete (assoc cat todos-categories)
3740 (todos-update-categories-sexp)
3741 (todos-category-select)))))
3742 (set-window-buffer (selected-window)
3743 (set-buffer (find-file-noselect nfile)))
3744 (todos-category-number (or new cat))
3745 (todos-category-select))))
3747 (defun todos-merge-category ()
3748 "Merge current category into another category in this file.
3749 The current category's todo and done items are appended to the
3750 chosen category's todo and done items, respectively, which
3751 becomes the current category, and the category moved from is
3754 (let ((buffer-read-only nil)
3755 (cat (todos-current-category))
3756 (goal (todos-read-category "Category to merge to: " t)))
3758 ;; FIXME: check if cat has archived items and merge those too
3761 (concat "^" (regexp-quote todos-category-beg)) nil t)
3763 (tbeg (progn (forward-line) (point)))
3766 (concat "^" (regexp-quote todos-category-done)) nil t)
3767 (forward-line) (point)))
3768 (tend (progn (forward-line -2) (point)))
3770 (if (re-search-forward
3771 (concat "^" (regexp-quote todos-category-beg)) nil t)
3774 (todo (buffer-substring-no-properties tbeg tend))
3775 (done (buffer-substring-no-properties dbeg cend))
3777 (goto-char (point-min))
3779 (concat "^" (regexp-quote (concat todos-category-beg goal))) nil t)
3781 (concat "^" (regexp-quote todos-category-done)) nil t)
3785 (goto-char (if (re-search-forward
3786 (concat "^" (regexp-quote todos-category-beg)) nil t)
3790 (remove-overlays cbeg cend)
3791 (delete-region cbeg cend)
3792 (todos-update-count 'todo (todos-get-count 'todo cat) goal)
3793 (todos-update-count 'done (todos-get-count 'done cat) goal)
3794 (setq todos-categories (delete (assoc cat todos-categories)
3796 (todos-update-categories-sexp)
3797 (todos-category-number goal)
3798 (todos-category-select)
3799 ;; Put point at the start of the merged todo items.
3800 ;; FIXME: what if there are no merged todo items but only done items?
3804 (defun todos-merge-categories ()
3807 (let* ((cats (mapcar 'car todos-categories))
3808 (goal (todos-read-category "Category to merge to: " t))
3809 (prompt (format "Merge to %s (type C-g to finish)? " goal))
3810 (source (let ((inhibit-quit t) l)
3811 (while (not (eq last-input-event 7))
3813 (when (y-or-n-p prompt)
3815 (setq cats (delete c cats))))))))
3819 (defun todos-raise-category-priority (&optional lower)
3820 "Raise priority of category point is on in Todos Categories buffer.
3821 With non-nil argument LOWER, lower the category's priority."
3825 (skip-chars-forward " ")
3826 (setq todos-categories-category-number (number-at-point)))
3828 (< todos-categories-category-number (length todos-categories))
3829 (> todos-categories-category-number 1))
3830 (let* ((col (current-column))
3831 ;; The line we're raising to, or lowering from...
3832 (beg (progn (forward-line (if lower 0 -1)) (point)))
3833 ;; ...and its number.
3834 (num1 (progn (skip-chars-forward " ") (1- (number-at-point))))
3835 ;; The number of the line we're exchanging with.
3837 ;; The start of the line below the one we're exchanging with.
3838 (end (progn (forward-line 2) (point)))
3839 (catvec (vconcat todos-categories))
3840 ;; Category names and item counts of the two lines being exchanged.
3841 (cat1-list (aref catvec num1))
3842 (cat2-list (aref catvec num2))
3843 (cat1 (car cat1-list))
3844 (cat2 (car cat2-list))
3845 buffer-read-only newcats)
3846 (delete-region beg end)
3847 (setq num1 (1+ num1))
3848 (setq num2 (1- num2))
3849 ;; Exchange the lines and rebuttonize them.
3850 (setq todos-categories-category-number num2)
3851 (todos-insert-category-line cat2)
3852 (setq todos-categories-category-number num1)
3853 (todos-insert-category-line cat1)
3854 ;; Update todos-categories alist.
3855 (aset catvec num2 (cons cat2 (cdr cat2-list)))
3856 (aset catvec num1 (cons cat1 (cdr cat1-list)))
3857 (setq todos-categories (append catvec nil))
3858 (setq newcats todos-categories)
3859 (with-current-buffer (find-buffer-visiting todos-current-todos-file)
3860 (setq todos-categories newcats)
3861 (todos-update-categories-sexp))
3862 (forward-line (if lower -1 -2))
3863 (forward-char col))))
3865 (defun todos-lower-category-priority ()
3866 "Lower priority of category point is on in Todos Categories buffer."
3868 (todos-raise-category-priority t))
3870 (defun todos-set-category-priority ()
3876 ;; ---------------------------------------------------------------------------
3877 ;;; Item editing commands
3879 ;; FIXME: make insertion options customizable per category?
3881 (defun todos-insert-item (&optional arg diary nonmarking date-type time
3883 "Add a new Todo item to a category.
3884 \(See the note at the end of this document string about key
3885 bindings and convenience commands derived from this command.)
3887 With no (or nil) prefix argument ARG, add the item to the current
3888 category; with one prefix argument (C-u), prompt for a category
3889 from the current Todos file; with two prefix arguments (C-u C-u),
3890 first prompt for a Todos file, then a category in that file. If
3891 a non-existing category is entered, ask whether to add it to the
3892 Todos file; if answered affirmatively, add the category and
3893 insert the item there.
3895 When argument DIARY is non-nil, this overrides the intent of the
3896 user option `todos-include-in-diary' for this item: if
3897 `todos-include-in-diary' is nil, include the item in the Fancy
3898 Diary display, and if it is non-nil, exclude the item from the
3899 Fancy Diary display. When DIARY is nil, `todos-include-in-diary'
3900 has its intended effect.
3902 When the item is included in the Fancy Diary display and the
3903 argument NONMARKING is non-nil, this overrides the intent of the
3904 user option `todos-diary-nonmarking' for this item: if
3905 `todos-diary-nonmarking' is nil, append `diary-nonmarking-symbol'
3906 to the item, and if it is non-nil, omit `diary-nonmarking-symbol'.
3908 The argument DATE-TYPE determines the content of the item's
3909 mandatory date header string and how it is added:
3910 - If DATE-TYPE is the symbol `calendar', the Calendar pops up and
3911 when the user puts the cursor on a date and hits RET, that
3912 date, in the format set by `calendar-date-display-form',
3913 becomes the date in the header.
3914 - If DATE-TYPE is the symbol `date', the header contains the date
3915 in the format set by `calendar-date-display-form', with year,
3916 month and day individually prompted for (month with tab
3918 - If DATE-TYPE is the symbol `dayname' the header contains a
3919 weekday name instead of a date, prompted for with tab
3921 - If DATE-TYPE has any other value (including nil or none) the
3922 header contains the current date (in the format set by
3923 `calendar-date-display-form').
3925 With non-nil argument TIME prompt for a time string, which must
3926 match `diary-time-regexp'. Typing `<return>' at the prompt
3927 returns the current time, if the user option
3928 `todos-always-add-time-string' is non-nil, otherwise the empty
3929 string (i.e., no time string). If TIME is absent or nil, add or
3930 omit the current time string according as
3931 `todos-always-add-time-string' is non-nil or nil, respectively.
3933 The argument REGION-OR-HERE determines the source and location of
3935 - If the REGION-OR-HERE is the symbol `here', prompt for the text
3936 of the new item and insert it directly above the todo item at
3937 point (hence lowering the priority of the remaining items), or
3938 if point is on the empty line below the last todo item, insert
3939 the new item there. An error is signalled if
3940 `todos-insert-item' is invoked with `here' outside of the
3942 - If REGION-OR-HERE is the symbol `region', use the region of the
3943 current buffer as the text of the new item, depending on the
3944 value of user option `todos-use-only-highlighted-region': if
3945 this is non-nil, then use the region only when it is
3946 highlighted; otherwise, use the region regardless of
3947 highlighting. An error is signalled if there is no region in
3948 the current buffer. Prompt for the item's priority in the
3949 category (an integer between 1 and one more than the number of
3950 items in the category), and insert the item accordingly.
3951 - If REGION-OR-HERE has any other value (in particular, nil or
3952 none), prompt for the text and the item's priority, and insert
3953 the item accordingly.
3955 To facilitate using these arguments when inserting a new todo
3956 item, convenience commands have been defined for all admissible
3957 combinations together with mnenomic key bindings based on on the
3958 name of the arguments and their order in the command's argument
3959 list: diar_y_ - nonmar_k_ing - _c_alendar or _d_ate or day_n_ame
3960 - _t_ime - _r_egion or _h_ere. These key combinations are
3961 appended to the basic insertion key (i) and keys that allow a
3962 following key must be doubled when used finally. For example,
3963 `iyh' will insert a new item with today's date, marked according
3964 to the DIARY argument described above, and with priority
3965 according to the HERE argument; while `iyy' does the same except
3966 the priority is not given by HERE but by prompting."
3967 ;; An alternative interface for customizing key
3968 ;; binding is also provided with the function
3969 ;; `todos-insertion-bindings'." ;FIXME
3971 (let ((region (eq region-or-here 'region))
3972 (here (eq region-or-here 'here)))
3974 (let (use-empty-active-region)
3975 (unless (and todos-use-only-highlighted-region (use-region-p))
3976 (error "There is no active region"))))
3977 (let* ((buf (current-buffer))
3978 (new-item (if region
3979 ;; FIXME: or keep properties?
3980 (buffer-substring-no-properties
3981 (region-beginning) (region-end))
3982 (read-from-minibuffer "Todo item: ")))
3984 ((eq date-type 'date)
3986 ((eq date-type 'dayname)
3987 (todos-read-dayname))
3988 ((eq date-type 'calendar)
3989 (setq todos-date-from-calendar t)
3990 (todos-set-date-from-calendar))
3991 (t (calendar-date-string (calendar-current-date) t t))))
3992 (time-string (or (and time (todos-read-time))
3993 (and todos-always-add-time-string
3994 (substring (current-time-string) 11 16)))))
3995 (setq todos-date-from-calendar nil)
3996 (cond ((equal arg '(16)) ; FIXME: cf. set-mark-command
3997 (todos-jump-to-category nil t)
4000 (set-buffer (find-buffer-visiting todos-global-current-todos-file))))
4001 ((equal arg '(4)) ; FIXME: just arg?
4002 (todos-jump-to-category)
4005 (set-buffer (find-buffer-visiting todos-global-current-todos-file))))
4007 (when (not (derived-mode-p 'todos-mode)) (todos-show))))
4008 (let (buffer-read-only)
4010 ;; Add date, time and diary marking as required.
4011 (concat (if (not (and diary (not todos-include-in-diary)))
4012 todos-nondiary-start
4013 (when (and nonmarking (not todos-diary-nonmarking))
4014 diary-nonmarking-symbol))
4015 date-string (when (and time-string ; Can be empty string.
4016 (not (zerop (length time-string))))
4017 (concat " " time-string))
4018 (when (not (and diary (not todos-include-in-diary)))
4021 ;; Indent newlines inserted by C-q C-j if nonspace char follows.
4022 (setq new-item (replace-regexp-in-string
4023 "\\(\n\\)[^[:blank:]]"
4024 (concat "\n" (make-string todos-indent-to-here 32))
4025 new-item nil nil 1))
4027 (cond ((not (eq major-mode 'todos-mode))
4028 (error "Cannot insert a todo item here outside of Todos mode"))
4029 ((not (eq buf (current-buffer)))
4030 (error "Cannot insert an item here after changing buffer"))
4031 ((or (todos-done-item-p)
4032 ;; Point on last blank line.
4033 (save-excursion (forward-line -1) (todos-done-item-p)))
4034 (error "Cannot insert a new item in the done item section"))
4036 (todos-insert-with-overlays new-item)))
4037 (todos-set-item-priority new-item (todos-current-category) t))
4038 (todos-update-count 'todo 1)
4039 (if (or diary todos-include-in-diary) (todos-update-count 'diary 1))
4040 (todos-update-categories-sexp)))))
4042 (defvar todos-date-from-calendar nil
4043 "Helper variable for setting item date from the Emacs Calendar.")
4045 (defun todos-set-date-from-calendar ()
4046 "Return string of date chosen from Calendar."
4047 (when todos-date-from-calendar
4048 (let (calendar-view-diary-initially-flag)
4050 ;; *Calendar* is now current buffer.
4051 (local-set-key (kbd "RET") 'exit-recursive-edit)
4052 (message "Put cursor on a date and type <return> to set it.")
4053 ;; FIXME: is there a better way than recursive-edit? Use unwind-protect?
4054 ;; Check recursive-depth?
4056 (setq todos-date-from-calendar
4057 (calendar-date-string (calendar-cursor-to-date t) t t))
4059 todos-date-from-calendar))
4061 (defun todos-delete-item ()
4062 "Delete at least one item in this category.
4064 If there are marked items, delete all of these; otherwise, delete
4067 (let* ((cat (todos-current-category))
4068 (marked (assoc cat todos-categories-with-marks))
4069 (item (unless marked (todos-item-string)))
4070 (ov (make-overlay (save-excursion (todos-item-start))
4071 (save-excursion (todos-item-end))))
4072 ;; FIXME: make confirmation an option?
4074 (y-or-n-p "Permanently delete all marked items? ")
4076 (overlay-put ov 'face 'todos-search)
4077 (y-or-n-p (concat "Permanently delete this item? ")))))
4081 (and marked (goto-char (point-min)))
4084 (if (or (and marked (todos-marked-item-p)) item)
4086 (if (todos-done-item-p)
4087 (todos-update-count 'done -1)
4088 (todos-update-count 'todo -1 cat)
4089 (and (todos-diary-item-p) (todos-update-count 'diary -1)))
4092 ;; Don't leave point below last item.
4093 (and item (bolp) (eolp) (< (point-min) (point-max))
4094 (todos-backward-item))
4096 (throw 'done (setq item nil))))
4097 (todos-forward-item))))
4099 (remove-overlays (point-min) (point-max) 'before-string todos-item-mark)
4100 (setq todos-categories-with-marks
4101 (assq-delete-all cat todos-categories-with-marks))
4103 (todos-update-categories-sexp)
4104 (todos-prefix-overlays))
4105 (if ov (delete-overlay ov))))
4107 (defun todos-edit-item ()
4108 "Edit the Todo item at point.
4109 If the item consists of only one logical line, edit it in the
4110 minibuffer; otherwise, edit it in Todos Edit mode."
4112 (when (todos-item-string)
4113 (let* ((buffer-read-only)
4114 (start (todos-item-start))
4117 (concat todos-date-string-start todos-date-pattern
4118 "\\( " diary-time-regexp "\\)?"
4119 (regexp-quote todos-nondiary-end) "?")
4120 (line-end-position) t)
4121 (1+ (- (point) start))))
4122 (item (todos-item-string))
4123 (multiline (> (length (split-string item "\n")) 1))
4126 (todos-edit-multiline t)
4127 (let ((new (read-string "Edit: " (cons item item-beg))))
4128 (while (not (string-match
4129 (concat todos-date-string-start todos-date-pattern) new))
4130 (setq new (read-from-minibuffer
4131 "Item must start with a date: " new)))
4132 ;; Indent newlines inserted by C-q C-j if nonspace char follows.
4133 (setq new (replace-regexp-in-string
4134 "\\(\n\\)[^[:blank:]]"
4135 (concat "\n" (make-string todos-indent-to-here 32)) new
4137 ;; If user moved point during editing, make sure it moves back.
4140 (todos-insert-with-overlays new)
4141 (move-to-column item-beg))))))
4143 (defun todos-edit-multiline-item ()
4144 "Edit current Todo item in Todos Edit mode.
4145 Use of newlines invokes `todos-indent' to insure compliance with
4146 the format of Diary entries."
4148 (todos-edit-multiline t))
4150 (defun todos-edit-multiline (&optional item)
4153 ;; FIXME: should there be only one live Todos Edit buffer?
4154 ;; (let ((buffer-name todos-edit-buffer))
4155 (let ((buffer-name (generate-new-buffer-name todos-edit-buffer)))
4158 (set-buffer (make-indirect-buffer
4159 (file-name-nondirectory todos-current-todos-file)
4162 (narrow-to-region (todos-item-start) (todos-item-end))
4165 (message "%s" (substitute-command-keys
4166 (concat "Type \\[todos-edit-quit] to check file format "
4167 "validity and return to Todos mode.\n")))))
4169 (defun todos-edit-quit ()
4170 "Return from Todos Edit mode to Todos mode.
4172 If the whole file was in Todos Edit mode, check before returning
4173 whether the file is still a valid Todos file and if so, also
4174 recalculate the Todos categories sexp, in case changes were made
4175 in the number or names of categories."
4177 ;; FIXME: should do only if file was actually changed -- but how to tell?
4178 (when (eq (buffer-size) (- (point-max) (point-min)))
4179 (when (todos-check-format) (todos-repair-categories-sexp)))
4181 ;; In case next buffer is not the one holding todos-current-todos-file.
4184 (defun todos-edit-item-header (&optional what)
4185 "Edit date/time header of at least one item.
4187 Interactively, ask whether to edit year, month and day or day of
4188 the week, as well as time. If there are marked items, apply the
4189 changes to all of these; otherwise, edit just the item at point.
4191 Non-interactively, argument WHAT specifies whether to set the
4192 date from the Calendar or to today, or whether to edit only the
4193 date or day, or only the time."
4195 (let* ((cat (todos-current-category))
4196 (marked (assoc cat todos-categories-with-marks))
4197 (first t) ; Match only first of marked items.
4198 (todos-date-from-calendar t)
4199 ndate ntime nheader)
4201 (or (and marked (goto-char (point-min))) (todos-item-start))
4205 (while (not (todos-marked-item-p))
4206 (todos-forward-item)
4207 (and (eobp) (throw 'stop nil))))
4208 (re-search-forward (concat todos-date-string-start "\\(?1:"
4210 "\\)\\(?2: " diary-time-regexp "\\)?")
4211 (line-end-position) t)
4212 (let* ((odate (match-string-no-properties 1))
4213 (otime (match-string-no-properties 2))
4215 (cond ((eq what 'today)
4217 (setq ndate (calendar-date-string
4218 (calendar-current-date) t t))
4219 (replace-match ndate nil nil nil 1)))
4220 ((eq what 'calendar)
4221 (setq ndate (save-match-data (todos-set-date-from-calendar)))
4222 (replace-match ndate nil nil nil 1))
4224 (unless (eq what 'timeonly)
4226 (setq ndate (if (save-match-data
4227 (string-match "[0-9]+" odate))
4228 (if (y-or-n-p "Change date? ")
4230 (todos-read-dayname))
4231 (if (y-or-n-p "Change day? ")
4232 (todos-read-dayname)
4233 (todos-read-date)))))
4234 (replace-match ndate nil nil nil 1))
4235 (unless (eq what 'dateonly)
4237 (setq ntime (save-match-data (todos-read-time)))
4238 (when (< 0 (length ntime))
4239 (setq ntime (concat " " ntime))))
4241 (replace-match ntime nil nil nil 2)
4242 (goto-char (match-end 1))
4244 (setq todos-date-from-calendar nil)
4247 (todos-forward-item)
4248 (goto-char (point-max))))))))
4250 (defun todos-edit-item-date ()
4251 "Prompt for and apply changes to current item's date."
4253 (todos-edit-item-header 'dateonly))
4255 (defun todos-edit-item-date-from-calendar ()
4256 "Prompt for changes to current item's date and apply from Calendar."
4258 (todos-edit-item-header 'calendar))
4260 (defun todos-edit-item-date-is-today ()
4261 "Set item date to today's date."
4263 (todos-edit-item-header 'today))
4265 (defun todos-edit-item-time ()
4266 "Prompt For and apply changes to current item's time."
4268 (todos-edit-item-header 'timeonly))
4270 (defun todos-edit-item-diary-inclusion ()
4271 "Change diary status of one or more todo items in this category.
4272 That is, insert `todos-nondiary-marker' if the candidate items
4273 lack this marking; otherwise, remove it.
4275 If there are marked todo items, change the diary status of all
4276 and only these, otherwise change the diary status of the item at
4279 (let ((buffer-read-only)
4280 (marked (assoc (todos-current-category)
4281 todos-categories-with-marks)))
4284 (when marked (goto-char (point-min)))
4286 (if (todos-done-item-p)
4287 (throw 'stop (message "Done items cannot be edited"))
4288 (unless (and marked (not (todos-marked-item-p)))
4289 (let* ((beg (todos-item-start))
4290 (lim (save-excursion (todos-item-end)))
4291 (end (save-excursion
4292 (or (todos-time-string-matcher lim)
4293 (todos-date-string-matcher lim)))))
4294 (if (looking-at (regexp-quote todos-nondiary-start))
4297 (search-forward todos-nondiary-end (1+ end) t)
4299 (todos-update-count 'diary 1))
4301 (insert todos-nondiary-start)
4302 (goto-char (1+ end))
4303 (insert todos-nondiary-end)
4304 (todos-update-count 'diary -1)))))
4305 (unless marked (throw 'stop nil))
4306 (todos-forward-item)))))
4307 (todos-update-categories-sexp)))
4309 (defun todos-edit-category-diary-inclusion (arg)
4310 "Make all items in this category diary items.
4311 With prefix ARG, make all items in this category non-diary
4315 (goto-char (point-min))
4316 (let ((todo-count (todos-get-count 'todo))
4317 (diary-count (todos-get-count 'diary))
4321 (if (todos-done-item-p) ; We've gone too far.
4323 (let* ((beg (todos-item-start))
4324 (lim (save-excursion (todos-item-end)))
4325 (end (save-excursion
4326 (or (todos-time-string-matcher lim)
4327 (todos-date-string-matcher lim)))))
4329 (unless (looking-at (regexp-quote todos-nondiary-start))
4330 (insert todos-nondiary-start)
4331 (goto-char (1+ end))
4332 (insert todos-nondiary-end))
4333 (when (looking-at (regexp-quote todos-nondiary-start))
4335 (search-forward todos-nondiary-end (1+ end) t)
4336 (replace-match "")))))
4337 (todos-forward-item))
4338 (unless (if arg (zerop diary-count) (= diary-count todo-count))
4339 (todos-update-count 'diary (if arg
4341 (- todo-count diary-count))))
4342 (todos-update-categories-sexp)))))
4344 (defun todos-edit-item-diary-nonmarking ()
4345 "Change non-marking of one or more diary items in this category.
4346 That is, insert `diary-nonmarking-symbol' if the candidate items
4347 lack this marking; otherwise, remove it.
4349 If there are marked todo items, change the non-marking status of
4350 all and only these, otherwise change the non-marking status of
4353 (let ((buffer-read-only)
4354 (marked (assoc (todos-current-category)
4355 todos-categories-with-marks)))
4358 (when marked (goto-char (point-min)))
4360 (if (todos-done-item-p)
4361 (throw 'stop (message "Done items cannot be edited"))
4362 (unless (and marked (not (todos-marked-item-p)))
4364 (unless (looking-at (regexp-quote todos-nondiary-start))
4365 (if (looking-at (regexp-quote diary-nonmarking-symbol))
4367 (insert diary-nonmarking-symbol))))
4368 (unless marked (throw 'stop nil))
4369 (todos-forward-item)))))))
4371 (defun todos-edit-category-diary-nonmarking (arg)
4372 "Add `diary-nonmarking-symbol' to all diary items in this category.
4373 With prefix ARG, remove `diary-nonmarking-symbol' from all diary
4374 items in this category."
4377 (goto-char (point-min))
4378 (let (buffer-read-only)
4381 (if (todos-done-item-p) ; We've gone too far.
4383 (unless (looking-at (regexp-quote todos-nondiary-start))
4385 (when (looking-at (regexp-quote diary-nonmarking-symbol))
4387 (unless (looking-at (regexp-quote diary-nonmarking-symbol))
4388 (insert diary-nonmarking-symbol))))
4389 (todos-forward-item)))))))
4391 (defun todos-raise-item-priority (&optional lower)
4392 "Raise priority of current item by moving it up by one item.
4393 With non-nil argument LOWER lower item's priority."
4395 (unless (or (todos-done-item-p) ; Can't reprioritize done items.
4396 ;; Can't raise or lower todo item when it's the only one.
4397 (< (todos-get-count 'todo) 2)
4398 ;; Point is between todo and done items.
4400 ;; Can't lower final todo item.
4403 (todos-forward-item)
4405 ;; Can't reprioritize filtered items other than Top Priorities.
4406 (and (eq major-mode 'todos-filtered-items-mode)
4407 (not (string-match (regexp-quote todos-top-priorities-buffer)
4409 (let ((item (todos-item-string))
4410 (marked (todos-marked-item-p))
4412 ;; In Top Priorities buffer, an item's priority can be changed
4413 ;; wrt items in another category, but not wrt items in the same
4415 (when (eq major-mode 'todos-filtered-items-mode)
4416 (let* ((regexp (concat todos-date-string-start todos-date-pattern
4417 "\\( " diary-time-regexp "\\)?"
4418 (regexp-quote todos-nondiary-end)
4419 "?\\(?1: \\[\\(.+:\\)?.+\\]\\)"))
4420 (cat1 (save-excursion
4421 (re-search-forward regexp nil t)
4423 (cat2 (save-excursion
4425 (todos-forward-item)
4426 (todos-backward-item))
4427 (re-search-forward regexp nil t)
4429 (if (string= cat1 cat2)
4431 (concat "Cannot reprioritize items in the same "
4432 "category in this mode, only in Todos mode")))))
4434 (if lower (todos-forward-item) (todos-backward-item))
4435 (todos-insert-with-overlays item)
4436 ;; If item was marked, retore the mark.
4437 (and marked (overlay-put (make-overlay (point) (point))
4438 'before-string todos-item-mark)))))
4440 (defun todos-lower-item-priority ()
4441 "Lower priority of current item by moving it down by one item."
4443 (todos-raise-item-priority t))
4445 ;; FIXME: incorporate todos-(raise|lower)-item-priority ?
4446 (defun todos-set-item-priority (item cat &optional new)
4447 "Set todo ITEM's priority in category CAT, moving item as needed.
4448 Interactively, the item and the category are the current ones,
4449 and the priority is a number between 1 and the number of items in
4450 the category. Non-interactively with argument NEW, the lowest
4451 priority is one more than the number of items in CAT."
4452 (interactive (list (todos-item-string) (todos-current-category)))
4453 (unless (called-interactively-p t)
4454 (todos-category-number cat)
4455 (todos-category-select))
4456 (let* ((todo (todos-get-count 'todo cat))
4457 (maxnum (if new (1+ todo) todo))
4459 priority candidate prompt)
4460 (unless (zerop todo)
4461 (while (not priority)
4463 (string-to-number (read-from-minibuffer
4465 (format "Set item priority (1-%d): "
4468 (when (or (< candidate 1) (> candidate maxnum))
4469 (format "Priority must be an integer between 1 and %d.\n"
4471 (unless prompt (setq priority candidate)))
4472 ;; Interactively, just relocate the item within its category.
4473 (when (called-interactively-p) (todos-remove-item))
4474 (goto-char (point-min))
4475 (unless (= priority 1) (todos-forward-item (1- priority))))
4476 (todos-insert-with-overlays item)))
4478 (defun todos-set-item-top-priority ()
4479 "Set this item's priority in the Top Priorities display.
4480 Reprioritizing items that belong to the same category is not
4481 allowed; this is reserved for Todos mode."
4483 (when (string-match (regexp-quote todos-top-priorities-buffer) (buffer-name))
4485 (item (todos-item-string))
4486 (end (todos-item-end))
4487 (beg (todos-item-start))
4488 (regexp (concat todos-date-string-start todos-date-pattern
4489 "\\(?: " diary-time-regexp "\\)?"
4490 (regexp-quote todos-nondiary-end)
4491 "?\\(?1: \\[\\(?:.+:\\)?.+\\]\\)"))
4492 (cat (when (looking-at regexp) (match-string 1)))
4493 buffer-read-only current priority candidate prompt new)
4495 (goto-char (point-min))
4497 (setq count (1+ count))
4498 (when (string= item (todos-item-string))
4499 (setq current count))
4500 (todos-forward-item)))
4501 (unless (zerop count)
4502 (while (not priority)
4504 (string-to-number (read-from-minibuffer
4506 (format "Set item priority (1-%d): "
4509 (when (or (< candidate 1) (> candidate count))
4510 (format "Priority must be an integer between 1 and %d.\n"
4512 (unless prompt (setq priority candidate)))
4513 (goto-char (point-min))
4514 (unless (= priority 1) (todos-forward-item (1- priority)))
4515 (setq new (point-marker))
4516 (if (or (and (< priority current)
4518 (save-excursion (search-forward cat beg t)))
4519 (and (> priority current)
4520 (save-excursion (search-backward cat end t))))
4522 (set-marker new nil)
4524 (error (concat "Cannot reprioritize items in the same category "
4525 "in this mode, only in Todos mode")))
4529 (todos-insert-with-overlays item)
4530 (set-marker new nil))))))
4532 (defun todos-move-item (&optional file)
4533 "Move at least one todo item to another category.
4535 If there are marked items, move all of these; otherwise, move
4538 With non-nil argument FILE, first prompt for another Todos file and
4539 then a category in that file to move the item or items to.
4541 If the chosen category is not one of the existing categories,
4542 then it is created and the item(s) become(s) the first
4543 entry/entries in that category."
4545 (unless (or (todos-done-item-p)
4546 ;; Point is between todo and done items.
4548 (let* ((buffer-read-only)
4549 (file1 todos-current-todos-file)
4550 (cat1 (todos-current-category))
4551 (marked (assoc cat1 todos-categories-with-marks))
4552 (num todos-category-number)
4553 (item (todos-item-string))
4554 (diary-item (todos-diary-item-p))
4555 (omark (save-excursion (todos-item-start) (point-marker)))
4557 (todos-read-file-name "Choose a Todos file: " nil t)
4562 (set-buffer (find-file-noselect file2))
4563 (setq cat2 (let* ((pl (if (and marked (> (cdr marked) 1)) "s" ""))
4564 (name (todos-read-category
4565 (concat "Move item" pl " to category: ")))
4566 (prompt (concat "Choose a different category than "
4567 "the current one\n(type `"
4569 (car (where-is-internal
4570 'todos-set-item-priority)))
4571 "' to reprioritize item "
4572 "within the same category): ")))
4573 (while (equal name cat1)
4574 (setq name (todos-read-category prompt)))
4576 (set-buffer (find-buffer-visiting file1))
4580 (goto-char (point-min))
4582 (when (todos-marked-item-p)
4583 (setq item (concat item (todos-item-string) "\n"))
4584 (setq count (1+ count))
4585 (when (todos-diary-item-p)
4586 (setq count-diary (1+ count-diary))))
4587 (todos-forward-item))
4588 ;; Chop off last newline.
4589 (setq item (substring item 0 -1)))
4591 (when (todos-diary-item-p) (setq count-diary 1)))
4592 (set-window-buffer (selected-window)
4593 (set-buffer (find-file-noselect file2)))
4594 (unless (assoc cat2 todos-categories) (todos-add-category cat2))
4595 (todos-set-item-priority item cat2 t)
4596 (setq nmark (point-marker))
4597 (todos-update-count 'todo count)
4598 (todos-update-count 'diary count-diary)
4599 (todos-update-categories-sexp)
4600 (with-current-buffer (find-buffer-visiting file1)
4609 (concat "^" (regexp-quote todos-category-beg)) nil t)
4613 (concat "^" (regexp-quote todos-category-done)) nil t)
4614 (setq end (match-beginning 0))
4616 (while (< (point) end)
4617 (if (todos-marked-item-p)
4619 (todos-forward-item))))
4620 (todos-remove-item))))
4621 (todos-update-count 'todo (- count) cat1)
4622 (todos-update-count 'diary (- count-diary) cat1)
4623 (todos-update-categories-sexp))
4624 (set-window-buffer (selected-window)
4625 (set-buffer (find-file-noselect file2)))
4626 (setq todos-category-number (todos-category-number cat2))
4627 (todos-category-select)
4628 (goto-char nmark))))
4630 (defun todos-move-item-to-file ()
4631 "Move the current todo item to a category in another Todos file."
4633 (todos-move-item t))
4635 (defun todos-move-item-to-diary ()
4636 "Move one or more items in current category to the diary file.
4638 If there are marked items, move all of these; otherwise, move
4644 ;; FIXME: make adding date customizable, and make this and time customization
4645 ;; overridable via double prefix arg ??
4646 (defun todos-item-done (&optional arg)
4647 "Tag at least one item in this category as done and hide it.
4649 With prefix argument ARG prompt for a comment and append it to
4650 the done item; this is only possible if there are no marked
4651 items. If there are marked items, tag all of these with
4652 `todos-done-string' plus the current date and, if
4653 `todos-always-add-time-string' is non-nil, the current time;
4654 otherwise, just tag the item at point. Items tagged as done are
4655 relocated to the category's (by default hidden) done section."
4657 (let* ((cat (todos-current-category))
4658 (marked (assoc cat todos-categories-with-marks)))
4659 (unless (or (todos-done-item-p)
4660 (and (looking-at "^$") (not marked)))
4661 (let* ((date-string (calendar-date-string (calendar-current-date) t t))
4662 (time-string (if todos-always-add-time-string
4663 (concat " " (substring (current-time-string) 11 16))
4665 (done-prefix (concat "[" todos-done-string date-string time-string
4667 (comment (and arg (not marked) (read-string "Enter a comment: ")))
4672 (and marked (goto-char (point-min)))
4675 (if (or (not marked) (and marked (todos-marked-item-p)))
4677 (setq item (todos-item-string))
4678 (setq done-item (cond (marked
4679 (concat done-item done-prefix item "\n"))
4681 (concat done-prefix item " ["
4682 todos-comment-string
4685 (concat done-prefix item))))
4686 (setq item-count (1+ item-count))
4687 (when (todos-diary-item-p)
4688 (setq diary-count (1+ diary-count)))
4690 (unless marked (throw 'done nil)))
4691 (todos-forward-item))))
4693 ;; Chop off last newline of done item string.
4694 (setq done-item (substring done-item 0 -1))
4695 (remove-overlays (point-min) (point-max) 'before-string todos-item-mark)
4696 (setq todos-categories-with-marks
4697 (assq-delete-all cat todos-categories-with-marks)))
4701 (concat "^" (regexp-quote todos-category-done)) nil t)
4703 (insert done-item "\n"))
4704 (todos-update-count 'todo (- item-count))
4705 (todos-update-count 'done item-count)
4706 (todos-update-count 'diary (- diary-count))
4707 (todos-update-categories-sexp)
4708 (save-excursion (todos-category-select))))))
4710 (defun todos-done-item-add-edit-or-delete-comment (&optional arg)
4711 "Add a comment to this done item or edit an existing comment.
4712 With prefix ARG delete an existing comment."
4714 (when (todos-done-item-p)
4715 (let ((item (todos-item-string))
4716 (end (save-excursion (todos-item-end)))
4717 comment buffer-read-only)
4720 (if (re-search-forward (concat " \\["
4721 (regexp-quote todos-comment-string)
4722 ": \\([^]]+\\)\\]") end t)
4724 (when (y-or-n-p "Delete comment? ")
4725 (delete-region (match-beginning 0) (match-end 0)))
4726 (setq comment (read-string "Edit comment: "
4727 (cons (match-string 1) 1)))
4728 (replace-match comment nil nil nil 1))
4729 (setq comment (read-string "Enter a comment: "))
4731 (insert " [" todos-comment-string ": " comment "]"))))))
4733 ;; FIXME: also with marked items
4734 ;; FIXME: delete comment from restored item or just leave it up to user?
4735 (defun todos-item-undo ()
4736 "Restore this done item to the todo section of this category.
4737 If done item has a comment, ask whether to omit the comment from
4740 (when (todos-done-item-p)
4741 (let* ((buffer-read-only)
4742 (done-item (todos-item-string))
4744 (orig-mrk (progn (todos-item-start) (point-marker)))
4745 ;; Find the end of the date string added upon tagging item as done.
4746 (start (search-forward "] "))
4747 (end (save-excursion (todos-item-end)))
4750 (when (and (re-search-forward (concat " \\["
4751 (regexp-quote todos-comment-string)
4752 ": \\([^]]+\\)\\]") end t)
4753 (y-or-n-p "Omit comment from restored item? "))
4754 (delete-region (match-beginning 0) (match-end 0)))
4755 (setq item (buffer-substring start end))
4757 ;; If user cancels before setting new priority, then leave the done item
4761 (todos-set-item-priority item (todos-current-category) t)
4763 (todos-update-count 'todo 1)
4764 (todos-update-count 'done -1)
4765 (and (todos-diary-item-p) (todos-update-count 'diary 1))
4766 (todos-update-categories-sexp))
4769 (goto-char orig-mrk)
4770 (todos-insert-with-overlays done-item)
4771 (let ((todos-show-with-done t))
4772 (todos-category-select)
4773 (goto-char opoint)))
4774 (set-marker orig-mrk nil)))))
4776 (defun todos-archive-done-item (&optional all)
4777 "Archive at least one done item in this category.
4779 If there are marked done items (and no marked todo items),
4780 archive all of these; otherwise, with non-nil argument ALL,
4781 archive all done items in this category; otherwise, archive the
4784 If the archive of this file does not exist, it is created. If
4785 this category does not exist in the archive, it is created."
4787 (when (eq major-mode 'todos-mode)
4788 (if (and all (zerop (todos-get-count 'done)))
4789 (message "No done items in this category")
4791 (let* ((cat (todos-current-category))
4792 (tbuf (current-buffer))
4793 (marked (assoc cat todos-categories-with-marks))
4794 (afile (concat (file-name-sans-extension
4795 todos-current-todos-file) ".toda"))
4796 (archive (if (file-exists-p afile)
4797 (find-file-noselect afile t)
4798 (get-buffer-create afile)))
4799 (item (and (todos-done-item-p) (concat (todos-item-string) "\n")))
4801 marked-items beg end all-done
4806 (goto-char (point-min))
4808 (when (todos-marked-item-p)
4809 (if (not (todos-done-item-p))
4810 (throw 'end (message "Only done items can be archived"))
4812 (concat marked-items (todos-item-string) "\n"))
4813 (setq count (1+ count))))
4814 (todos-forward-item))))
4816 (if (y-or-n-p "Archive all done items in this category? ")
4819 (goto-char (point-min))
4822 (re-search-forward todos-done-string-start nil t)
4823 (match-beginning 0))
4824 end (if (re-search-forward
4825 (concat "^" (regexp-quote todos-category-beg))
4829 all-done (buffer-substring beg end)
4830 count (todos-get-count 'done))))
4832 (when (or marked all item)
4833 (with-current-buffer archive
4834 (unless buffer-file-name (erase-buffer))
4835 (let (buffer-read-only)
4837 (goto-char (point-min))
4838 (if (and (re-search-forward (concat "^"
4840 (concat todos-category-beg
4843 (re-search-forward (regexp-quote todos-category-done)
4845 ;; Start of done items section in existing category.
4847 (todos-add-category cat)
4848 ;; Start of done items section in new category.
4849 (goto-char (point-max)))
4850 (insert (cond (marked marked-items)
4853 (todos-update-count 'done (if (or marked all) count 1) cat)
4854 (todos-update-categories-sexp)
4855 ;; If archive is new, save to file now (using write-region in
4856 ;; order not to get prompted for file to save to), to let
4857 ;; auto-mode-alist take effect below.
4858 (unless buffer-file-name
4859 (write-region nil nil afile)
4861 (with-current-buffer tbuf
4862 (cond ((or marked item)
4863 (and marked (goto-char (point-min)))
4866 (if (or (and marked (todos-marked-item-p)) item)
4869 (todos-update-count 'done -1)
4870 (todos-update-count 'archived 1)
4871 ;; Don't leave point below last item.
4872 (and item (bolp) (eolp) (< (point-min) (point-max))
4873 (todos-backward-item))
4875 (throw 'done (setq item nil))))
4876 (todos-forward-item)))))
4878 (remove-overlays beg end)
4879 (delete-region beg end)
4880 (todos-update-count 'done (- count))
4881 (todos-update-count 'archived count)))
4883 (remove-overlays (point-min) (point-max)
4884 'before-string todos-item-mark)
4885 (setq todos-categories-with-marks
4886 (assq-delete-all cat todos-categories-with-marks)))
4887 (todos-update-categories-sexp)
4888 (todos-prefix-overlays)))
4890 (todos-category-number cat)
4891 (todos-category-select)
4892 (split-window-below)
4893 (set-window-buffer (selected-window) tbuf))))))
4895 (defun todos-archive-category-done-items ()
4896 "Move all done items in this category to its archive."
4898 (todos-archive-done-item t))
4900 (defun todos-unarchive-items (&optional all)
4901 "Unarchive at least one item in this archive category.
4903 If there are marked items, unarchive all of these; otherwise,
4904 with non-nil argument ALL, unarchive all items in this category;
4905 otherwise, unarchive the item at point.
4907 Unarchived items are restored as done items to the corresponding
4908 category in the Todos file, inserted at the end of done section.
4909 If all items in the archive category were restored, the category
4910 is deleted from the archive. If this was the only category in the
4911 archive, the archive file is deleted."
4913 (when (eq major-mode 'todos-archive-mode)
4915 (let* ((cat (todos-current-category))
4916 (tbuf (find-file-noselect
4917 (concat (file-name-sans-extension todos-current-todos-file)
4919 (marked (assoc cat todos-categories-with-marks))
4920 (item (concat (todos-item-string) "\n"))
4921 (all-items (when all (buffer-substring (point-min) (point-max))))
4922 (all-count (when all (todos-get-count 'done)))
4923 marked-items marked-count
4927 (goto-char (point-min))
4929 (when (todos-marked-item-p)
4930 (concat marked-items (todos-item-string) "\n")
4931 (setq marked-count (1+ marked-count)))
4932 (todos-forward-item))))
4933 ;; Restore items to end of category's done section and update counts.
4934 (with-current-buffer tbuf
4935 (let (buffer-read-only)
4937 (goto-char (point-min))
4938 (re-search-forward (concat "^" (regexp-quote
4939 (concat todos-category-beg cat)))
4941 ;; Go to end of category's done section.
4942 (if (re-search-forward (concat "^" (regexp-quote todos-category-beg))
4944 (goto-char (match-beginning 0))
4945 (goto-char (point-max)))
4947 (insert marked-items)
4948 (todos-update-count 'done marked-count cat)
4949 (todos-update-count 'archived (- marked-count) cat))
4952 (todos-update-count 'done all-count cat)
4953 (todos-update-count 'archived (- all-count) cat))
4956 (todos-update-count 'done 1 cat)
4957 (todos-update-count 'archived -1 cat)))
4958 (todos-update-categories-sexp)))
4959 ;; Delete restored items from archive.
4960 (cond ((or marked item)
4961 (and marked (goto-char (point-min)))
4964 (if (or (and marked (todos-marked-item-p)) item)
4967 ;; Don't leave point below last item.
4968 (and item (bolp) (eolp) (< (point-min) (point-max))
4969 (todos-backward-item))
4971 (throw 'done (setq item nil))))
4972 (todos-forward-item))))
4973 (todos-update-count 'done (if marked (- marked-count) -1) cat))
4975 (remove-overlays (point-min) (point-max))
4976 (delete-region (point-min) (point-max))))
4977 ;; If that was the last category in the archive, delete the whole file.
4978 (if (= (length todos-categories) 1)
4980 (delete-file todos-current-todos-file)
4981 ;; Don't bother confirming killing the archive buffer.
4982 (set-buffer-modified-p nil)
4984 ;; Otherwise, if the archive category is now empty, delete it.
4985 (when (eq (point-min) (point-max))
4987 (let ((beg (re-search-backward
4988 (concat "^" (regexp-quote todos-category-beg) cat)
4990 (end (if (re-search-forward
4991 (concat "^" (regexp-quote todos-category-beg))
4995 (remove-overlays beg end)
4996 (delete-region beg end)
4997 (setq todos-categories (delete (assoc cat todos-categories)
4999 (todos-update-categories-sexp))))
5000 ;; Visit category in Todos file and show restored done items.
5001 (let ((tfile (buffer-file-name tbuf))
5002 (todos-show-with-done t))
5003 (set-window-buffer (selected-window)
5004 (set-buffer (find-file-noselect tfile)))
5005 (todos-category-number cat)
5007 (message "Items unarchived."))))))
5009 (defun todos-unarchive-category ()
5010 "Unarchive all items in this category. See `todos-unarchive-items'."
5012 (todos-unarchive-items t))
5016 ;;; todos.el ends here
5018 ;; ---------------------------------------------------------------------------
5020 ;; FIXME: remove when part of Emacs
5021 (add-to-list 'auto-mode-alist '("\\.todo\\'" . todos-mode))
5022 (add-to-list 'auto-mode-alist '("\\.toda\\'" . todos-archive-mode))
5024 ;;; Addition to calendar.el
5025 ;; FIXME: autoload when key-binding is defined in calendar.el
5026 (defun todos-insert-item-from-calendar ()
5029 ;; FIXME: todos-current-todos-file is nil here, better to solicit Todos
5030 ;; file? todos-global-current-todos-file is nil if no Todos file has been
5032 (pop-to-buffer (file-name-nondirectory todos-global-current-todos-file))
5034 ;; FIXME: this now calls todos-set-date-from-calendar
5035 (todos-insert-item t 'calendar))
5037 ;; FIXME: calendar is loaded before todos
5038 ;; (add-hook 'calendar-load-hook
5040 (define-key calendar-mode-map "it" 'todos-insert-item-from-calendar);))
5042 ;; ---------------------------------------------------------------------------
5043 ;;; necessitated adaptations to diary-lib.el
5045 ;; (defun diary-goto-entry (button)
5046 ;; "Jump to the diary entry for the BUTTON at point."
5047 ;; (let* ((locator (button-get button 'locator))
5048 ;; (marker (car locator))
5049 ;; markbuf file opoint)
5050 ;; ;; If marker pointing to diary location is valid, use that.
5051 ;; (if (and marker (setq markbuf (marker-buffer marker)))
5053 ;; (pop-to-buffer markbuf)
5054 ;; (goto-char (marker-position marker)))
5055 ;; ;; Marker is invalid (eg buffer has been killed, as is the case with
5056 ;; ;; included diary files).
5057 ;; (or (and (setq file (cadr locator))
5058 ;; (file-exists-p file)
5059 ;; (find-file-other-window file)
5061 ;; (when (eq major-mode (default-value 'major-mode)) (diary-mode))
5062 ;; (when (eq major-mode 'todos-mode) (widen))
5063 ;; (goto-char (point-min))
5064 ;; (when (re-search-forward (format "%s.*\\(%s\\)"
5065 ;; (regexp-quote (nth 2 locator))
5066 ;; (regexp-quote (nth 3 locator)))
5068 ;; (goto-char (match-beginning 1))
5069 ;; (when (eq major-mode 'todos-mode)
5070 ;; (setq opoint (point))
5071 ;; (re-search-backward (concat "^"
5072 ;; (regexp-quote todos-category-beg)
5075 ;; (todos-category-number (match-string 1))
5076 ;; (todos-category-select)
5077 ;; (goto-char opoint)))))
5078 ;; (message "Unable to locate this diary entry")))))