1 ;;; todos.el --- facilities for making and maintaining todo lists
3 ;; Copyright (C) 2013 Free Software Foundation, Inc.
5 ;; Author: Stephen Berman <stephen.berman@gmx.net>
6 ;; Keywords: calendar, todo
8 ;; This file is [not yet] part of GNU Emacs.
10 ;; GNU Emacs is free software: you can redistribute it and/or modify
11 ;; it under the terms of the GNU General Public License as published by
12 ;; the Free Software Foundation, either version 3 of the License, or
13 ;; (at your option) any later version.
15 ;; GNU Emacs is distributed in the hope that it will be useful,
16 ;; but WITHOUT ANY WARRANTY; without even the implied warranty of
17 ;; MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
18 ;; GNU General Public License for more details.
20 ;; You should have received a copy of the GNU General Public License
21 ;; along with GNU Emacs. If not, see <http://www.gnu.org/licenses/>.
25 ;; This package provides facilities for making, displaying, navigating
26 ;; and editing todo lists, which are prioritized lists of todo items.
27 ;; Todo lists are identified with named categories, so you can group
28 ;; together and separately prioritize thematically related todo items.
29 ;; Each category is stored in a file, which thus provides a further
30 ;; level of organization. You can create as many todo files, and in
31 ;; each as many categories, as you want.
33 ;; With Todos you can navigate among the items of a category, and
34 ;; between categories in the same and in different todo files. You
35 ;; can edit todo items, reprioritize them within their category, move
36 ;; them to another category, delete them, or mark items as done and
37 ;; store them separately from the not yet done items in a category.
38 ;; You can add new todo files and categories, rename categories, move
39 ;; them to another file or delete them. You can also display summary
40 ;; tables of the categories in a file and the types of items they
41 ;; contain. And you can build cross-categorial lists of items that
42 ;; satisfy various criteria.
44 ;; To get started, load this package and type `M-x todos-show'. This
45 ;; will prompt you for the name of the first todo file, its first
46 ;; category and the category's first item, create these and display
47 ;; them in Todos mode. Now you can insert further items into the list
48 ;; (i.e., the category) and assign them priorities by typing `i i'.
50 ;; You will probably find it convenient to give `todos-show' a global
51 ;; key binding in your init file, since it is one of the entry points
52 ;; to Todos mode; a good choice is `C-c t', since `todos-show' is
53 ;; bound to `t' in Todos mode.
55 ;; To see a list of all Todos mode commands and their key bindings,
56 ;; including other entry points, type `C-h m' in Todos mode. Consult
57 ;; the document strings of the commands for details of their use. The
58 ;; `todos' customization group and its subgroups list the options you
59 ;; can set to alter the behavior of many commands and various aspects
62 ;; This package is a new version of Oliver Seidel's todo-mode.el.
63 ;; While it retains the same basic organization and handling of todo
64 ;; lists and the basic UI, it significantly extends these, adds many
65 ;; features, changes much of the internals and reimplements almost all
71 ;; For cl-remove-duplicates (in todos-insertion-commands-args) and
75 ;; -----------------------------------------------------------------------------
76 ;;; Setting up Todos files, categories, and items
77 ;; -----------------------------------------------------------------------------
79 (defcustom todos-directory (locate-user-emacs-file "todos/")
80 "Directory where user's Todos files are saved."
84 (defun todos-files (&optional archives)
85 "Default value of `todos-files-function'.
86 This returns the case-insensitive alphabetically sorted list of
87 file truenames in `todos-directory' with the extension
88 \".todo\". With non-nil ARCHIVES return the list of archive file
89 truenames (those with the extension \".toda\")."
90 (let ((files (if (file-exists-p todos-directory)
91 (mapcar 'file-truename
92 (directory-files todos-directory t
93 (if archives "\.toda$" "\.todo$") t)))))
94 (sort files (lambda (s1 s2) (let ((cis1 (upcase s1))
96 (string< cis1 cis2))))))
98 (defcustom todos-files-function 'todos-files
99 "Function returning the value of the variable `todos-files'.
100 This function should take an optional argument that, if non-nil,
101 makes it return the value of the variable `todos-archives'."
105 (defvar todos-files (funcall todos-files-function)
106 "List of truenames of user's Todos files.")
108 (defvar todos-archives (funcall todos-files-function t)
109 "List of truenames of user's Todos archives.")
111 (defvar todos-visited nil
112 "List of Todos files visited in this session by `todos-show'.
113 Used to determine initial display according to the value of
114 `todos-show-first'.")
116 (defvar todos-file-buffers nil
117 "List of file names of live Todos mode buffers.")
119 (defvar todos-global-current-todos-file nil
120 "Variable holding name of current Todos file.
121 Used by functions called from outside of Todos mode to visit the
122 current Todos file rather than the default Todos file (i.e. when
123 users option `todos-show-current-file' is non-nil).")
125 (defvar todos-current-todos-file nil
126 "Variable holding the name of the currently active Todos file.")
128 (defvar todos-categories nil
129 "Alist of categories in the current Todos file.
130 The elements are cons cells whose car is a category name and
131 whose cdr is a vector of the category's item counts. These are,
132 in order, the numbers of todo items, of todo items included in
133 the Diary, of done items and of archived items.")
135 (defvar todos-category-number 1
136 "Variable holding the number of the current Todos category.
137 Todos categories are numbered starting from 1.")
139 (defvar todos-categories-with-marks nil
140 "Alist of categories and number of marked items they contain.")
142 (defconst todos-category-beg "--==-- "
143 "String marking beginning of category (inserted with its name).")
145 (defconst todos-category-done "==--== DONE "
146 "String marking beginning of category's done items.")
148 (defcustom todos-done-separator-string "="
149 "String determining the value of variable `todos-done-separator'.
150 If the string consists of a single character,
151 `todos-done-separator' will be the string made by repeating this
152 character for the width of the window, and the length is
153 automatically recalculated when the window width changes. If the
154 string consists of more (or less) than one character, it will be
155 the value of `todos-done-separator'."
157 :initialize 'custom-initialize-default
158 :set 'todos-reset-done-separator-string
159 :group 'todos-display)
161 (defun todos-done-separator ()
162 "Return string used as value of variable `todos-done-separator'."
163 (let ((sep todos-done-separator-string))
164 (propertize (if (= 1 (length sep))
165 ;; Until bug#2749 is fixed, if separator's length
166 ;; is window-width and todos-wrap-lines is
167 ;; non-nil, an indented empty line appears between
168 ;; the separator and the first done item.
169 ;; (make-string (window-width) (string-to-char sep))
170 (make-string (1- (window-width)) (string-to-char sep))
171 todos-done-separator-string)
172 'face 'todos-done-sep)))
174 (defvar todos-done-separator (todos-done-separator)
175 "String used to visually separate done from not done items.
176 Displayed as an overlay instead of `todos-category-done' when
177 done items are shown. Its value is determined by user option
178 `todos-done-separator-string'.")
180 (defvar todos-show-done-only nil
181 "If non-nil display only done items in current category.
182 Set by the command `todos-toggle-view-done-only' and used by
183 `todos-category-select'.")
185 (defcustom todos-nondiary-marker '("[" "]")
186 "List of strings surrounding item date to block diary inclusion.
187 The first string is inserted before the item date and must be a
188 non-empty string that does not match a diary date in order to
189 have its intended effect. The second string is inserted after
191 :type '(list string string)
193 :initialize 'custom-initialize-default
194 :set 'todos-reset-nondiary-marker)
196 (defconst todos-nondiary-start (nth 0 todos-nondiary-marker)
197 "String inserted before item date to block diary inclusion.")
199 (defconst todos-nondiary-end (nth 1 todos-nondiary-marker)
200 "String inserted after item date matching `todos-nondiary-start'.")
202 (defconst todos-month-name-array
203 (vconcat calendar-month-name-array (vector "*"))
204 "Array of month names, in order.
205 The final element is \"*\", indicating an unspecified month.")
207 (defconst todos-month-abbrev-array
208 (vconcat calendar-month-abbrev-array (vector "*"))
209 "Array of abbreviated month names, in order.
210 The final element is \"*\", indicating an unspecified month.")
212 (defconst todos-date-pattern
213 (let ((dayname (diary-name-pattern calendar-day-name-array nil t)))
214 (concat "\\(?4:\\(?5:" dayname "\\)\\|"
216 (monthname (format "\\(?6:%s\\)" (diary-name-pattern
217 todos-month-name-array
218 todos-month-abbrev-array)))
219 (month "\\(?7:[0-9]+\\|\\*\\)")
220 (day "\\(?8:[0-9]+\\|\\*\\)")
221 (year "-?\\(?9:[0-9]+\\|\\*\\)"))
222 (mapconcat 'eval calendar-date-display-form ""))
224 "Regular expression matching a Todos date header.")
226 ;; By itself this matches anything, because of the `?'; however, it's only
227 ;; used in the context of `todos-date-pattern' (but Emacs Lisp lacks
229 (defconst todos-date-string-start
230 (concat "^\\(" (regexp-quote todos-nondiary-start) "\\|"
231 (regexp-quote diary-nonmarking-symbol) "\\)?")
232 "Regular expression matching part of item header before the date.")
234 (defcustom todos-done-string "DONE "
235 "Identifying string appended to the front of done todos items."
237 :initialize 'custom-initialize-default
238 :set 'todos-reset-done-string
241 (defconst todos-done-string-start
242 (concat "^\\[" (regexp-quote todos-done-string))
243 "Regular expression matching start of done item.")
245 (defconst todos-item-start (concat "\\(" todos-date-string-start "\\|"
246 todos-done-string-start "\\)"
248 "String identifying start of a Todos item.")
250 ;; -----------------------------------------------------------------------------
251 ;;; Todos mode display options
252 ;; -----------------------------------------------------------------------------
254 (defcustom todos-prefix ""
255 "String prefixed to todo items for visual distinction."
256 :type '(string :validate
258 (when (string= (widget-value widget) todos-item-mark)
261 "Invalid value: must be distinct from `todos-item-mark'")
263 :initialize 'custom-initialize-default
264 :set 'todos-reset-prefix
265 :group 'todos-display)
267 (defcustom todos-number-prefix t
268 "Non-nil to prefix items with consecutively increasing integers.
269 These reflect the priorities of the items in each category."
271 :initialize 'custom-initialize-default
272 :set 'todos-reset-prefix
273 :group 'todos-display)
275 (defun todos-mode-line-control (cat)
276 "Return a mode line control for todo or archive file buffers.
277 Argument CAT is the name of the current Todos category.
278 This function is the value of the user variable
279 `todos-mode-line-function'."
280 (let ((file (todos-short-file-name todos-current-todos-file)))
281 (format "%s category %d: %s" file todos-category-number cat)))
283 (defcustom todos-mode-line-function 'todos-mode-line-control
284 "Function that returns a mode line control for Todos buffers.
285 The function expects one argument holding the name of the current
286 Todos category. The resulting control becomes the local value of
287 `mode-line-buffer-identification' in each Todos buffer."
289 :group 'todos-display)
291 (defcustom todos-highlight-item nil
292 "Non-nil means highlight items at point."
294 :initialize 'custom-initialize-default
295 :set 'todos-reset-highlight-item
296 :group 'todos-display)
298 (defcustom todos-wrap-lines t
299 "Non-nil to activate Visual Line mode and use wrap prefix."
301 :group 'todos-display)
303 (defcustom todos-indent-to-here 3
304 "Number of spaces to indent continuation lines of items.
305 This must be a positive number to ensure such items are fully
306 shown in the Fancy Diary display."
307 :type '(integer :validate
309 (unless (> (widget-value widget) 0)
310 (widget-put widget :error
311 "Invalid value: must be a positive integer")
313 :group 'todos-display)
315 (defun todos-indent ()
316 "Indent from point to `todos-indent-to-here'."
317 (indent-to todos-indent-to-here todos-indent-to-here))
319 (defcustom todos-show-with-done nil
320 "Non-nil to display done items in all categories."
322 :group 'todos-display)
324 ;; -----------------------------------------------------------------------------
326 ;; -----------------------------------------------------------------------------
329 ;; '((t :inherit font-lock-warning-face))
333 (:weight bold :foreground "Red1"))
337 (:weight bold :foreground "Pink"))
341 (:weight bold :foreground "Red1"))
345 (:weight bold :foreground "Pink"))
350 (:weight bold :inverse-video t)))
351 "Face for marks on marked items."
354 (defface todos-prefix-string
355 ;; '((t :inherit font-lock-constant-face))
356 '((((class grayscale) (background light))
357 (:foreground "LightGray" :weight bold :underline t))
358 (((class grayscale) (background dark))
359 (:foreground "Gray50" :weight bold :underline t))
360 (((class color) (min-colors 88) (background light)) (:foreground "dark cyan"))
361 (((class color) (min-colors 88) (background dark)) (:foreground "Aquamarine"))
362 (((class color) (min-colors 16) (background light)) (:foreground "CadetBlue"))
363 (((class color) (min-colors 16) (background dark)) (:foreground "Aquamarine"))
364 (((class color) (min-colors 8)) (:foreground "magenta"))
365 (t (:weight bold :underline t)))
366 "Face for Todos prefix or numerical priority string."
369 (defface todos-top-priority
370 ;; bold font-lock-comment-face
371 '((default :weight bold)
372 (((class grayscale) (background light)) :foreground "DimGray" :slant italic)
373 (((class grayscale) (background dark)) :foreground "LightGray" :slant italic)
374 (((class color) (min-colors 88) (background light)) :foreground "Firebrick")
375 (((class color) (min-colors 88) (background dark)) :foreground "chocolate1")
376 (((class color) (min-colors 16) (background light)) :foreground "red")
377 (((class color) (min-colors 16) (background dark)) :foreground "red1")
378 (((class color) (min-colors 8) (background light)) :foreground "red")
379 (((class color) (min-colors 8) (background dark)) :foreground "yellow")
381 "Face for top priority Todos item numerical priority string.
382 The item's priority number string has this face if the number is
383 less than or equal the category's top priority setting."
386 (defface todos-nondiary
387 ;; '((t :inherit font-lock-type-face))
388 '((((class grayscale) (background light)) :foreground "Gray90" :weight bold)
389 (((class grayscale) (background dark)) :foreground "DimGray" :weight bold)
390 (((class color) (min-colors 88) (background light)) :foreground "ForestGreen")
391 (((class color) (min-colors 88) (background dark)) :foreground "PaleGreen")
392 (((class color) (min-colors 16) (background light)) :foreground "ForestGreen")
393 (((class color) (min-colors 16) (background dark)) :foreground "PaleGreen")
394 (((class color) (min-colors 8)) :foreground "green")
395 (t :weight bold :underline t))
396 "Face for non-diary markers around todo item date/time header."
400 '((t :inherit diary))
401 "Face for the date string of a Todos item."
405 '((t :inherit diary-time))
406 "Face for the time string of a Todos item."
409 (defface todos-diary-expired
410 ;; Doesn't contrast enough with todos-date (= diary) face.
411 ;; ;; '((t :inherit warning))
412 ;; '((default :weight bold)
413 ;; (((class color) (min-colors 16)) :foreground "DarkOrange")
414 ;; (((class color)) :foreground "yellow"))
415 ;; bold font-lock-function-name-face
416 '((default :weight bold)
417 (((class color) (min-colors 88) (background light)) :foreground "Blue1")
418 (((class color) (min-colors 88) (background dark)) :foreground "LightSkyBlue")
419 (((class color) (min-colors 16) (background light)) :foreground "Blue")
420 (((class color) (min-colors 16) (background dark)) :foreground "LightSkyBlue")
421 (((class color) (min-colors 8)) :foreground "blue")
422 (t :inverse-video t))
423 "Face for expired dates of diary items."
426 (defface todos-done-sep
427 ;; '((t :inherit font-lock-builtin-face))
428 '((((class grayscale) (background light)) :foreground "LightGray" :weight bold)
429 (((class grayscale) (background dark)) :foreground "DimGray" :weight bold)
430 (((class color) (min-colors 88) (background light)) :foreground "dark slate blue")
431 (((class color) (min-colors 88) (background dark)) :foreground "LightSteelBlue")
432 (((class color) (min-colors 16) (background light)) :foreground "Orchid")
433 (((class color) (min-colors 16) (background dark)) :foreground "LightSteelBlue")
434 (((class color) (min-colors 8)) :foreground "blue" :weight bold)
436 "Face for separator string bewteen done and not done Todos items."
440 ;; '((t :inherit font-lock-keyword-face))
441 '((((class grayscale) (background light)) :foreground "LightGray" :weight bold)
442 (((class grayscale) (background dark)) :foreground "DimGray" :weight bold)
443 (((class color) (min-colors 88) (background light)) :foreground "Purple")
444 (((class color) (min-colors 88) (background dark)) :foreground "Cyan1")
445 (((class color) (min-colors 16) (background light)) :foreground "Purple")
446 (((class color) (min-colors 16) (background dark)) :foreground "Cyan")
447 (((class color) (min-colors 8)) :foreground "cyan" :weight bold)
449 "Face for done Todos item header string."
452 (defface todos-comment
453 ;; '((t :inherit font-lock-comment-face))
454 '((((class grayscale) (background light))
455 :foreground "DimGray" :weight bold :slant italic)
456 (((class grayscale) (background dark))
457 :foreground "LightGray" :weight bold :slant italic)
458 (((class color) (min-colors 88) (background light))
459 :foreground "Firebrick")
460 (((class color) (min-colors 88) (background dark))
461 :foreground "chocolate1")
462 (((class color) (min-colors 16) (background light))
464 (((class color) (min-colors 16) (background dark))
466 (((class color) (min-colors 8) (background light))
468 (((class color) (min-colors 8) (background dark))
469 :foreground "yellow")
470 (t :weight bold :slant italic))
471 "Face for comments appended to done Todos items."
474 (defface todos-search
475 ;; '((t :inherit match))
479 (:background "yellow1"))
483 (:background "RoyalBlue3"))
487 (:foreground "black" :background "yellow"))
491 (:foreground "white" :background "blue"))
496 (:background "gray")))
497 "Face for matches found by `todos-search'."
500 (defface todos-button
501 ;; '((t :inherit widget-field))
503 (:foreground "black" :background "yellow3"))
504 (((class grayscale color)
506 (:background "gray85"))
507 (((class grayscale color)
509 (:background "dim gray"))
512 "Face for buttons in table of categories."
515 (defface todos-sorted-column
520 (:background "grey85"))
523 (:background "grey85" :foreground "grey10"))
525 (:background "gray")))
526 "Face for sorted column in table of categories."
529 (defface todos-archived-only
530 ;; '((t (:inherit (shadow))))
533 (:foreground "grey50"))
536 (:foreground "grey70"))
538 (:foreground "gray")))
539 "Face for archived-only category names in table of categories."
542 (defface todos-category-string
543 ;; '((t :inherit font-lock-type-face))
544 '((((class grayscale) (background light)) :foreground "Gray90" :weight bold)
545 (((class grayscale) (background dark)) :foreground "DimGray" :weight bold)
546 (((class color) (min-colors 88) (background light)) :foreground "ForestGreen")
547 (((class color) (min-colors 88) (background dark)) :foreground "PaleGreen")
548 (((class color) (min-colors 16) (background light)) :foreground "ForestGreen")
549 (((class color) (min-colors 16) (background dark)) :foreground "PaleGreen")
550 (((class color) (min-colors 8)) :foreground "green")
551 (t :weight bold :underline t))
552 "Face for category-file header in Todos Filtered Items mode."
555 ;; -----------------------------------------------------------------------------
556 ;;; Entering and exiting Todos
557 ;; -----------------------------------------------------------------------------
559 (defcustom todos-visit-files-commands (list 'find-file 'dired-find-file)
560 "List of file finding commands for `todos-display-as-todos-file'.
561 Invoking these commands to visit a Todos or Todos Archive file
562 calls `todos-show' or `todos-find-archive', so that the file is
563 displayed correctly."
564 :type '(repeat function)
567 (defun todos-short-file-name (file)
568 "Return short form of Todos FILE.
569 This lacks the extension and directory components."
571 (file-name-sans-extension (file-name-nondirectory file))))
573 (defcustom todos-default-todos-file (todos-short-file-name
574 (car (funcall todos-files-function)))
575 "Todos file visited by first session invocation of `todos-show'."
576 :type `(radio ,@(mapcar (lambda (f) (list 'const f))
577 (mapcar 'todos-short-file-name
578 (funcall todos-files-function))))
581 (defcustom todos-show-current-file t
582 "Non-nil to make `todos-show' visit the current Todos file.
583 Otherwise, `todos-show' always visits `todos-default-todos-file'."
585 :initialize 'custom-initialize-default
586 :set 'todos-set-show-current-file
589 (defcustom todos-show-first 'first
590 "What action to take on first use of `todos-show' on a file."
591 :type '(choice (const :tag "Show first category" first)
592 (const :tag "Show table of categories" table)
593 (const :tag "Show top priorities" top)
594 (const :tag "Show diary items" diary)
595 (const :tag "Show regexp items" regexp))
598 (defcustom todos-add-item-if-new-category t
599 "Non-nil to prompt for an item after adding a new category."
603 (defcustom todos-initial-file "Todo"
604 "Default file name offered on adding first Todos file."
608 (defcustom todos-initial-category "Todo"
609 "Default category name offered on initializing a new Todos file."
613 (defcustom todos-category-completions-files nil
614 "List of files for building `todos-read-category' completions."
615 :type `(set ,@(mapcar (lambda (f) (list 'const f))
616 (mapcar 'todos-short-file-name
617 (funcall todos-files-function))))
620 (defcustom todos-completion-ignore-case nil
621 "Non-nil means case is ignored by `todos-read-*' functions."
625 (defun todos-show (&optional solicit-file)
626 "Visit a Todos file and display one of its categories.
628 When invoked in Todos mode, prompt for which todo file to visit.
629 When invoked outside of Todos mode with non-nil prefix argument
630 SOLICIT-FILE prompt for which todo file to visit; otherwise visit
631 `todos-default-todos-file'. Subsequent invocations from outside
632 of Todos mode revisit this file or, with option
633 `todos-show-current-file' non-nil (the default), whichever Todos
634 file was last visited.
636 Calling this command before any Todos file exists prompts for a
637 file name and an initial category (defaulting to
638 `todos-initial-file' and `todos-initial-category'), creates both
639 of these, visits the file and displays the category, and if
640 option `todos-add-item-if-new-category' is non-nil (the default),
641 prompts for the first item.
643 The first invocation of this command on an existing Todos file
644 interacts with the option `todos-show-first': if its value is
645 `first' (the default), show the first category in the file; if
646 its value is `table', show the table of categories in the file;
647 if its value is one of `top', `diary' or `regexp', show the
648 corresponding saved top priorities, diary items, or regexp items
649 file, if any. Subsequent invocations always show the file's
650 current (i.e., last displayed) category.
652 In Todos mode just the category's unfinished todo items are shown
653 by default. The done items are hidden, but typing
654 `\\[todos-toggle-view-done-items]' displays them below the todo
655 items. With non-nil user option `todos-show-with-done' both todo
656 and done items are always shown on visiting a category.
658 Invoking this command in Todos Archive mode visits the
659 corresponding Todos file, displaying the corresponding category."
662 (show-first todos-show-first)
663 (file (cond ((or solicit-file
664 (and (called-interactively-p 'any)
665 (memq major-mode '(todos-mode
667 todos-filtered-items-mode))))
668 (if (funcall todos-files-function)
669 (todos-read-file-name "Choose a Todos file to visit: "
671 (user-error "There are no Todos files")))
672 ((and (eq major-mode 'todos-archive-mode)
673 ;; Called noninteractively via todos-quit
674 ;; to jump to corresponding category in
676 (not (called-interactively-p 'any)))
677 (setq cat (todos-current-category))
678 (concat (file-name-sans-extension
679 todos-current-todos-file) ".todo"))
681 (or todos-current-todos-file
682 (and todos-show-current-file
683 todos-global-current-todos-file)
684 (todos-absolute-file-name todos-default-todos-file)
687 (unless todos-default-todos-file
688 ;; We just initialized the first todo file, so make it the default.
689 (setq todos-default-todos-file (todos-short-file-name file)
691 (todos-reevaluate-default-file-defcustom))
692 (unless (member file todos-visited)
693 ;; Can't setq t-c-t-f here, otherwise wrong file shown when
694 ;; todos-show is called from todos-show-categories-table.
695 (let ((todos-current-todos-file file))
696 (cond ((eq todos-show-first 'table)
697 (todos-show-categories-table))
698 ((memq todos-show-first '(top diary regexp))
699 (let* ((shortf (todos-short-file-name file))
700 (fi-file (todos-absolute-file-name
701 shortf todos-show-first)))
702 (when (eq todos-show-first 'regexp)
703 (let ((rxfiles (directory-files todos-directory t
705 (when (and rxfiles (> (length rxfiles) 1))
706 (let ((rxf (mapcar 'todos-short-file-name rxfiles)))
707 (setq fi-file (todos-absolute-file-name
709 "Choose a regexp items file: "
711 (if (file-exists-p fi-file)
714 (set-buffer (find-file-noselect fi-file 'nowarn)))
715 (message "There is no %s file for %s"
716 (cond ((eq todos-show-first 'top)
718 ((eq todos-show-first 'diary)
720 ((eq todos-show-first 'regexp)
723 (setq todos-show-first 'first)))))))
724 (when (or (member file todos-visited)
725 (eq todos-show-first 'first))
726 (set-window-buffer (selected-window)
727 (set-buffer (find-file-noselect file 'nowarn)))
728 ;; When quitting archive file, show corresponding category in
729 ;; Todos file, if it exists.
730 (when (assoc cat todos-categories)
731 (setq todos-category-number (todos-category-number cat)))
732 ;; If this is a new Todos file, add its first category.
733 (when (zerop (buffer-size))
736 (setq todos-category-number
737 (todos-add-category todos-current-todos-file "")
738 add-item todos-add-item-if-new-category
741 ;; If the category was added, save the file now, so we
742 ;; don't risk having an empty todo file, which would
743 ;; signal an error if we tried to visit it later,
744 ;; since doing that looks for category boundaries.
746 ;; If user cancels before adding the category, clean up
747 ;; and exit, so we have a fresh slate the next time.
749 (setq todos-files (delete file todos-files))
751 (setq todos-default-todos-file nil
752 todos-current-todos-file nil))
755 (save-excursion (todos-category-select))
756 (when add-item (todos-basic-insert-item)))
757 (setq todos-show-first show-first)
758 (add-to-list 'todos-visited file)))
761 "Save the current Todos file."
763 (cond ((eq major-mode 'todos-filtered-items-mode)
764 (todos-check-filtered-items-file)
765 (todos-save-filtered-items-buffer))
769 (defvar todos-descending-counts)
772 "Exit the current Todos-related buffer.
773 Depending on the specific mode, this either kills the buffer or
774 buries it and restores state as needed."
776 (let ((buf (current-buffer)))
777 (cond ((eq major-mode 'todos-categories-mode)
778 ;; Postpone killing buffer till after calling todos-show, to
779 ;; prevent killing todos-mode buffer.
780 (setq todos-descending-counts nil)
781 ;; Ensure todos-show calls todos-show-categories-table only on
782 ;; first invocation per file.
783 (when (eq todos-show-first 'table)
784 (add-to-list 'todos-visited todos-current-todos-file))
787 ((eq major-mode 'todos-filtered-items-mode)
789 (unless (eq major-mode 'todos-mode) (todos-show)))
790 ((eq major-mode 'todos-archive-mode)
791 ;; Have to write a newly created archive to file to avoid
792 ;; subsequent errors.
796 ((eq major-mode 'todos-mode)
798 ;; If we just quit archive mode, just burying the buffer
799 ;; in todos-mode would return to archive.
800 (set-window-buffer (selected-window)
801 (set-buffer (other-buffer)))
802 (bury-buffer buf)))))
804 ;; -----------------------------------------------------------------------------
805 ;;; Navigation between and within categories
806 ;; -----------------------------------------------------------------------------
808 (defcustom todos-skip-archived-categories nil
809 "Non-nil to handle categories with only archived items specially.
811 Sequential category navigation using \\[todos-forward-category]
812 or \\[todos-backward-category] skips categories that contain only
813 archived items. Other commands still recognize these categories.
814 In Todos Categories mode (\\[todos-show-categories-table]) these
815 categories shown in `todos-archived-only' face and pressing the
816 category button visits the category in the archive instead of the
819 :group 'todos-display)
821 (defun todos-forward-category (&optional back)
822 "Visit the numerically next category in this Todos file.
823 If the current category is the highest numbered, visit the first
824 category. With non-nil argument BACK, visit the numerically
825 previous category (the highest numbered one, if the current
826 category is the first)."
828 (setq todos-category-number
829 (1+ (mod (- todos-category-number (if back 2 0))
830 (length todos-categories))))
831 (when todos-skip-archived-categories
832 (while (and (zerop (todos-get-count 'todo))
833 (zerop (todos-get-count 'done))
834 (not (zerop (todos-get-count 'archived))))
835 (setq todos-category-number
836 (apply (if back '1- '1+) (list todos-category-number)))))
837 (todos-category-select)
838 (goto-char (point-min)))
840 (defun todos-backward-category ()
841 "Visit the numerically previous category in this Todos file.
842 If the current category is the highest numbered, visit the first
845 (todos-forward-category t))
847 (defvar todos-categories-buffer)
849 (defun todos-jump-to-category (&optional file where)
850 "Prompt for a category in a Todos file and jump to it.
852 With non-nil FILE (interactively a prefix argument), prompt for a
853 specific Todos file and choose (with TAB completion) a category
854 in it to jump to; otherwise, choose and jump to any category in
855 either the current Todos file or a file in
856 `todos-category-completions-files'.
858 Also accept a non-existing category name and ask whether to add a
859 new category by that name; on confirmation, add it and jump to
860 that category, and if option `todos-add-item-if-new-category' is
861 non-nil (the default), then prompt for the first item.
863 In noninteractive calls non-nil WHERE specifies either the goal
864 category or its file. If its value is `archive', the choice of
865 categories is restricted to the current archive file or the
866 archive you were prompted to choose; this is used by
867 `todos-jump-to-archive-category'. If its value is the name of a
868 category, jump directly to that category; this is used in Todos
871 ;; If invoked outside of Todos mode and there is not yet any Todos
872 ;; file, initialize one.
873 (if (null todos-files)
875 (let* ((archive (eq where 'archive))
876 (cat (unless archive where))
877 (file0 (when cat ; We're in Todos Categories mode.
878 ;; With non-nil `todos-skip-archived-categories'
879 ;; jump to archive file of a category with only
881 (if (and todos-skip-archived-categories
882 (zerop (todos-get-count 'todo cat))
883 (zerop (todos-get-count 'done cat))
884 (not (zerop (todos-get-count 'archived cat))))
885 (concat (file-name-sans-extension
886 todos-current-todos-file) ".toda")
887 ;; Otherwise, jump to current todos file.
888 todos-current-todos-file)))
889 (len (length todos-categories))
890 (cat+file (unless cat
891 (todos-read-category "Jump to category: "
892 (if archive 'archive) file)))
893 (add-item (and todos-add-item-if-new-category
894 (> (length todos-categories) len)))
895 (category (or cat (car cat+file))))
896 (unless cat (setq file0 (cdr cat+file)))
897 (with-current-buffer (find-file-noselect file0 'nowarn)
898 (setq todos-current-todos-file file0)
899 ;; If called from Todos Categories mode, clean up before jumping.
900 (if (string= (buffer-name) todos-categories-buffer)
902 (set-window-buffer (selected-window)
903 (set-buffer (find-buffer-visiting file0)))
904 (unless todos-global-current-todos-file
905 (setq todos-global-current-todos-file todos-current-todos-file))
906 (todos-category-number category)
907 (todos-category-select)
908 (goto-char (point-min))
909 (when add-item (todos-basic-insert-item))))))
911 (defun todos-next-item (&optional count)
912 "Move point down to the beginning of the next item.
913 With positive numerical prefix COUNT, move point COUNT items
916 If the category's done items are hidden, this command also moves
917 point to the empty line below the last todo item from any higher
918 item in the category, i.e., when invoked with or without a prefix
919 argument. If the category's done items are visible, this command
920 called with a prefix argument only moves point to a lower item,
921 e.g., with point on the last todo item and called with prefix 1,
922 it moves point to the first done item; but if called with point
923 on the last todo item without a prefix argument, it moves point
924 the the empty line above the done items separator."
926 ;; It's not worth the trouble to allow prefix arg value < 1, since we have
927 ;; the corresponding command.
928 (cond ((and current-prefix-arg (< count 1))
929 (user-error "The prefix argument must be a positive number"))
931 (todos-forward-item count))
933 (todos-forward-item))))
935 (defun todos-previous-item (&optional count)
936 "Move point up to start of item with next higher priority.
937 With positive numerical prefix COUNT, move point COUNT items
940 If the category's done items are visible, this command called
941 with a prefix argument only moves point to a higher item, e.g.,
942 with point on the first done item and called with prefix 1, it
943 moves to the last todo item; but if called with point on the
944 first done item without a prefix argument, it moves point the the
945 empty line above the done items separator."
947 ;; Avoid moving to bob if on the first item but not at bob.
948 (when (> (line-number-at-pos) 1)
949 ;; It's not worth the trouble to allow prefix arg value < 1, since we have
950 ;; the corresponding command.
951 (cond ((and current-prefix-arg (< count 1))
952 (user-error "The prefix argument must be a positive number"))
954 (todos-backward-item count))
956 (todos-backward-item)))))
958 ;; -----------------------------------------------------------------------------
959 ;;; Display toggle commands
960 ;; -----------------------------------------------------------------------------
962 (defun todos-toggle-prefix-numbers ()
963 "Hide item numbering if shown, show if hidden."
967 (goto-char (point-min))
968 (let* ((ov (todos-get-overlay 'prefix))
969 (show-done (re-search-forward todos-done-string-start nil t))
970 (todos-show-with-done show-done)
971 (todos-number-prefix (not (equal (overlay-get ov 'before-string)
973 (if (eq major-mode 'todos-filtered-items-mode)
974 (todos-prefix-overlays)
975 (todos-category-select))))))
977 (defun todos-toggle-view-done-items ()
978 "Show hidden or hide visible done items in current category."
980 (if (zerop (todos-get-count 'done (todos-current-category)))
981 (message "There are no done items in this category.")
982 (let ((opoint (point)))
983 (goto-char (point-min))
984 (let* ((shown (re-search-forward todos-done-string-start nil t))
985 (todos-show-with-done (not shown)))
986 (todos-category-select)
988 ;; If start of done items sections is below the bottom of the
989 ;; window, make it visible.
992 (goto-char (point-min))
993 (re-search-forward todos-done-string-start nil t)))
994 (if (not (pos-visible-in-window-p shown))
996 (goto-char opoint)))))))
998 (defun todos-toggle-view-done-only ()
999 "Switch between displaying only done or only todo items."
1001 (setq todos-show-done-only (not todos-show-done-only))
1002 (todos-category-select))
1004 (defun todos-toggle-item-highlighting ()
1005 "Highlight or unhighlight the todo item the cursor is on."
1007 (eval-when-compile (require 'hl-line))
1008 (when (memq major-mode
1009 '(todos-mode todos-archive-mode todos-filtered-items-mode))
1014 (defun todos-toggle-item-header ()
1015 "Hide or show item date-time headers in the current file.
1016 With done items, this hides only the done date-time string, not
1017 the the original date-time string."
1021 (goto-char (point-min))
1022 (let ((ov (todos-get-overlay 'header)))
1024 (remove-overlays 1 (1+ (buffer-size)) 'todos 'header)
1026 (goto-char (point-min))
1028 (when (re-search-forward
1029 (concat todos-item-start
1030 "\\( " diary-time-regexp "\\)?"
1031 (regexp-quote todos-nondiary-end) "? ")
1033 (setq ov (make-overlay (match-beginning 0) (match-end 0) nil t))
1034 (overlay-put ov 'todos 'header)
1035 (overlay-put ov 'display ""))
1036 (todos-forward-item)))))))
1038 ;; -----------------------------------------------------------------------------
1039 ;;; File and category editing
1040 ;; -----------------------------------------------------------------------------
1042 (defun todos-add-file ()
1043 "Name and initialize a new Todos file.
1044 Interactively, prompt for a category and display it, and if
1045 option `todos-add-item-if-new-category' is non-nil (the default),
1046 prompt for the first item.
1047 Noninteractively, return the name of the new file."
1049 (let ((prompt (concat "Enter name of new Todos file "
1050 "(TAB or SPC to see current names): "))
1052 (setq file (todos-read-file-name prompt))
1053 (with-current-buffer (get-buffer-create file)
1055 (write-region (point-min) (point-max) file nil 'nomessage nil t)
1057 (setq todos-files (funcall todos-files-function))
1058 (todos-reevaluate-filelist-defcustoms)
1059 (if (called-interactively-p 'any)
1061 (set-window-buffer (selected-window)
1062 (set-buffer (find-file-noselect file)))
1063 (setq todos-current-todos-file file)
1067 (defvar todos-edit-buffer "*Todos Edit*"
1068 "Name of current buffer in Todos Edit mode.")
1070 (defun todos-edit-file ()
1071 "Put current buffer in `todos-edit-mode'.
1072 This makes the entire file visible and the buffer writeable and
1073 you can use the self-insertion keys and standard Emacs editing
1074 commands to make changes. To return to Todos mode, type
1075 \\[todos-edit-quit]. This runs a file format check, signalling
1076 an error if the format has become invalid. However, this check
1077 cannot tell if the number of items changed, which could result in
1078 the file containing inconsistent information. For this reason
1079 this command should be used with caution."
1084 (message "%s" (substitute-command-keys
1085 (concat "Type \\[todos-edit-quit] to check file format "
1086 "validity and return to Todos mode.\n"))))
1088 (defun todos-add-category (&optional file cat)
1089 "Add a new category to a Todos file.
1091 Called interactively with prefix argument FILE, prompt for a file
1092 and then for a new category to add to that file, otherwise prompt
1093 just for a category to add to the current Todos file. After
1094 adding the category, visit it in Todos mode and if option
1095 `todos-add-item-if-new-category' is non-nil (the default), prompt
1098 Non-interactively, add category CAT to file FILE; if FILE is nil,
1099 add CAT to the current Todos file. After adding the category,
1100 return the new category number."
1103 ;; If cat is passed from caller, don't prompt, unless it is "",
1104 ;; which means the file was just added and has no category yet.
1105 (if (and cat (> (length cat) 0))
1106 (setq file0 (or (and (stringp file) file)
1107 todos-current-todos-file))
1108 (setq catfil (todos-read-category "Enter a new category name: "
1109 'add (when (called-interactively-p 'any)
1112 file0 (if (called-interactively-p 'any)
1116 (let ((counts (make-vector 4 0)) ; [todo diary done archived]
1117 (num (1+ (length todos-categories)))
1118 (buffer-read-only nil))
1119 (setq todos-current-todos-file file0)
1120 (setq todos-categories (append todos-categories
1121 (list (cons cat counts))))
1123 (goto-char (point-max))
1124 (save-excursion ; Save point for todos-category-select.
1125 (insert todos-category-beg cat "\n\n" todos-category-done "\n"))
1126 (todos-update-categories-sexp)
1127 ;; If invoked by user, display the newly added category, if
1128 ;; called programmatically return the category number to the
1130 (if (called-interactively-p 'any)
1132 (setq todos-category-number num)
1133 (todos-category-select)
1134 (when todos-add-item-if-new-category
1135 (todos-basic-insert-item)))
1138 (defun todos-rename-category ()
1139 "Rename current Todos category.
1140 If this file has an archive containing this category, rename the
1141 category there as well."
1143 (let* ((cat (todos-current-category))
1144 (new (read-from-minibuffer
1145 (format "Rename category \"%s\" to: " cat))))
1146 (setq new (todos-validate-name new 'category))
1147 (let* ((ofile todos-current-todos-file)
1148 (archive (concat (file-name-sans-extension ofile) ".toda"))
1149 (buffers (append (list ofile)
1150 (unless (zerop (todos-get-count 'archived cat))
1152 (dolist (buf buffers)
1153 (with-current-buffer (find-file-noselect buf)
1154 (let (buffer-read-only)
1155 (setq todos-categories (todos-set-categories))
1158 (setcar (assoc cat todos-categories) new)
1160 (goto-char (point-min))
1161 (todos-update-categories-sexp)
1162 (re-search-forward (concat (regexp-quote todos-category-beg)
1163 "\\(" (regexp-quote cat) "\\)\n")
1165 (replace-match new t t nil 1)))))))
1166 (force-mode-line-update))
1167 (save-excursion (todos-category-select)))
1169 (defun todos-delete-category (&optional arg)
1170 "Delete current Todos category provided it is empty.
1171 With ARG non-nil delete the category unconditionally,
1172 i.e. including all existing todo and done items."
1174 (let* ((file todos-current-todos-file)
1175 (cat (todos-current-category))
1176 (todo (todos-get-count 'todo cat))
1177 (done (todos-get-count 'done cat))
1178 (archived (todos-get-count 'archived cat)))
1180 (or (> todo 0) (> done 0)))
1181 (message "%s" (substitute-command-keys
1182 (concat "To delete a non-empty category, "
1183 "type C-u \\[todos-delete-category].")))
1184 (when (cond ((= (length todos-categories) 1)
1186 (concat "This is the only category in this file; "
1187 "deleting it will also delete the file.\n"
1188 "Do you want to proceed? ")))
1190 (todos-y-or-n-p (concat "This category has archived items; "
1191 "the archived category will remain\n"
1192 "after deleting the todo category. "
1193 "Do you still want to delete it\n"
1194 "(see `todos-skip-archived-categories' "
1195 "for another option)? ")))
1197 (todos-y-or-n-p (concat "Permanently remove category \"" cat
1198 "\"" (and arg " and all its entries")
1201 (let ((buffer-read-only)
1202 (beg (re-search-backward
1203 (concat "^" (regexp-quote (concat todos-category-beg cat))
1205 (end (if (re-search-forward
1206 (concat "\n\\(" (regexp-quote todos-category-beg)
1210 (remove-overlays beg end)
1211 (delete-region beg end)
1212 (if (= (length todos-categories) 1)
1213 ;; If deleted category was the only one, delete the file.
1215 (todos-reevaluate-filelist-defcustoms)
1216 ;; Skip confirming killing the archive buffer if it has been
1217 ;; modified and not saved.
1218 (set-buffer-modified-p nil)
1221 (message "Deleted Todos file %s." file))
1222 (setq todos-categories (delete (assoc cat todos-categories)
1224 (todos-update-categories-sexp)
1225 (setq todos-category-number
1226 (1+ (mod todos-category-number (length todos-categories))))
1227 (todos-category-select)
1228 (goto-char (point-min))
1229 (message "Deleted category %s." cat)))))))
1231 (defun todos-move-category ()
1232 "Move current category to a different Todos file.
1233 If current category has archived items, also move those to the
1234 archive of the file moved to, creating it if it does not exist."
1236 (when (or (> (length todos-categories) 1)
1237 (todos-y-or-n-p (concat "This is the only category in this file; "
1238 "moving it will also delete the file.\n"
1239 "Do you want to proceed? ")))
1240 (let* ((ofile todos-current-todos-file)
1241 (cat (todos-current-category))
1242 (nfile (todos-read-file-name
1243 "Choose a Todos file to move this category to: " nil t))
1244 (archive (concat (file-name-sans-extension ofile) ".toda"))
1245 (buffers (append (list ofile)
1246 (unless (zerop (todos-get-count 'archived cat))
1249 (while (equal (file-truename nfile) (file-truename ofile))
1250 (setq nfile (todos-read-file-name
1251 "Choose a file distinct from this file: " nil t)))
1252 (dolist (buf buffers)
1253 (with-current-buffer (find-file-noselect buf)
1255 (goto-char (point-max))
1256 (let* ((beg (re-search-backward
1258 (regexp-quote (concat todos-category-beg cat))
1261 (end (if (re-search-forward
1262 (concat "^" (regexp-quote todos-category-beg))
1266 (content (buffer-substring-no-properties beg end))
1267 (counts (cdr (assoc cat todos-categories)))
1269 ;; Move the category to the new file. Also update or create
1270 ;; archive file if necessary.
1271 (with-current-buffer
1273 ;; Regenerate todos-archives in case there
1274 ;; is a newly created archive.
1275 (if (member buf (funcall todos-files-function t))
1276 (concat (file-name-sans-extension nfile) ".toda")
1278 (let* ((nfile-short (todos-short-file-name nfile))
1280 (format "Todos file \"%s\" already has "
1282 (format "the category \"%s\";\n" cat)
1283 "enter a new category name: "))
1286 (goto-char (point-max))
1288 ;; If the file moved to has a category with the same
1289 ;; name, rename the moved category.
1290 (when (assoc cat todos-categories)
1291 (unless (member (file-truename (buffer-file-name))
1292 (funcall todos-files-function t))
1293 (setq new (read-from-minibuffer prompt))
1294 (setq new (todos-validate-name new 'category))))
1295 ;; Replace old with new name in Todos and archive files.
1297 (goto-char (point-max))
1299 (concat "^" (regexp-quote todos-category-beg)
1300 "\\(" (regexp-quote cat) "\\)$") nil t)
1301 (replace-match new nil nil nil 1)))
1302 (setq todos-categories
1303 (append todos-categories (list (cons new counts))))
1304 (todos-update-categories-sexp)
1305 ;; If archive was just created, save it to avoid "File
1306 ;; <xyz> no longer exists!" message on invoking
1307 ;; `todos-view-archived-items'.
1308 (unless (file-exists-p (buffer-file-name))
1310 (todos-category-number (or new cat))
1311 (todos-category-select))
1312 ;; Delete the category from the old file, and if that was the
1313 ;; last category, delete the file. Also handle archive file
1315 (remove-overlays beg end)
1316 (delete-region beg end)
1317 (goto-char (point-min))
1318 ;; Put point after todos-categories sexp.
1320 (if (eobp) ; Aside from sexp, file is empty.
1322 ;; Skip confirming killing the archive buffer.
1323 (set-buffer-modified-p nil)
1324 (delete-file todos-current-todos-file)
1326 (when (member todos-current-todos-file todos-files)
1327 (todos-reevaluate-filelist-defcustoms)))
1328 (setq todos-categories (delete (assoc cat todos-categories)
1330 (todos-update-categories-sexp)
1331 (todos-category-select)))))
1332 (set-window-buffer (selected-window)
1333 (set-buffer (find-file-noselect nfile)))
1334 (todos-category-number (or new cat))
1335 (todos-category-select))))
1337 (defun todos-merge-category (&optional file)
1338 "Merge current category into another existing category.
1340 With prefix argument FILE, prompt for a specific Todos file and
1341 choose (with TAB completion) a category in it to merge into;
1342 otherwise, choose and merge into a category in either the
1343 current Todos file or a file in `todos-category-completions-files'.
1345 After merging, the current category's todo and done items are
1346 appended to the chosen goal category's todo and done items,
1347 respectively. The goal category becomes the current category,
1348 and the previous current category is deleted.
1350 If both the first and goal categories also have archived items,
1351 the former are merged to the latter. If only the first category
1352 has archived items, the archived category is renamed to the goal
1355 (let* ((tfile todos-current-todos-file)
1356 (cat (todos-current-category))
1357 (cat+file (todos-read-category "Merge into category: " 'todo file))
1358 (goal (car cat+file))
1359 (gfile (cdr cat+file))
1360 (archive (concat (file-name-sans-extension (if file gfile tfile))
1362 archived-count here)
1363 ;; Merge in todo file.
1364 (with-current-buffer (get-buffer (find-file-noselect tfile))
1366 (let* ((buffer-read-only nil)
1369 (concat "^" (regexp-quote todos-category-beg)) nil t)
1371 (tbeg (progn (forward-line) (point-marker)))
1374 (concat "^" (regexp-quote todos-category-done)) nil t)
1375 (forward-line) (point-marker)))
1376 ;; Omit empty line between todo and done items.
1377 (tend (progn (forward-line -2) (point-marker)))
1379 (if (re-search-forward
1380 (concat "^" (regexp-quote todos-category-beg)) nil t)
1382 (goto-char (match-beginning 0))
1384 (point-max-marker))))
1385 (todo (buffer-substring-no-properties tbeg tend))
1386 (done (buffer-substring-no-properties dbeg cend)))
1387 (goto-char (point-min))
1388 ;; Merge any todo items.
1389 (unless (zerop (length todo))
1391 (concat "^" (regexp-quote (concat todos-category-beg goal)) "$")
1394 (concat "^" (regexp-quote todos-category-done)) nil t)
1396 (setq here (point-marker))
1398 (todos-update-count 'todo (todos-get-count 'todo cat) goal))
1399 ;; Merge any done items.
1400 (unless (zerop (length done))
1401 (goto-char (if (re-search-forward
1402 (concat "^" (regexp-quote todos-category-beg)) nil t)
1405 (when (zerop (length todo)) (setq here (point-marker)))
1407 (todos-update-count 'done (todos-get-count 'done cat) goal))
1408 (remove-overlays cbeg cend)
1409 (delete-region cbeg cend)
1410 (setq todos-categories (delete (assoc cat todos-categories)
1412 (todos-update-categories-sexp)
1413 (mapc (lambda (m) (set-marker m nil)) (list cbeg tbeg dbeg tend cend))))
1414 (when (file-exists-p archive)
1415 ;; Merge in archive file.
1416 (with-current-buffer (get-buffer (find-file-noselect archive))
1418 (goto-char (point-min))
1419 (let ((buffer-read-only nil)
1420 (cbeg (save-excursion
1421 (when (re-search-forward
1422 (concat "^" (regexp-quote
1423 (concat todos-category-beg cat)) "$")
1425 (goto-char (match-beginning 0))
1427 (gbeg (save-excursion
1428 (when (re-search-forward
1429 (concat "^" (regexp-quote
1430 (concat todos-category-beg goal)) "$")
1432 (goto-char (match-beginning 0))
1436 (setq archived-count (todos-get-count 'done cat))
1437 (setq cend (save-excursion
1438 (if (re-search-forward
1439 (concat "^" (regexp-quote todos-category-beg))
1443 (setq carch (save-excursion (goto-char cbeg) (forward-line)
1444 (buffer-substring-no-properties (point) cend)))
1445 ;; If both categories of the merge have archived items, merge the
1446 ;; source items to the goal items, else "merge" by renaming the
1447 ;; source category to goal.
1450 (goto-char (if (re-search-forward
1451 (concat "^" (regexp-quote todos-category-beg))
1456 (remove-overlays cbeg cend)
1457 (delete-region cbeg cend))
1459 (search-forward cat)
1460 (replace-match goal))
1461 (setq todos-categories (todos-make-categories-list t))
1462 (todos-update-categories-sexp)))))
1463 (with-current-buffer (get-file-buffer tfile)
1464 (when archived-count
1465 (unless (zerop archived-count)
1466 (todos-update-count 'archived archived-count goal)
1467 (todos-update-categories-sexp)))
1468 (todos-category-number goal)
1469 ;; If there are only merged done items, show them.
1470 (let ((todos-show-with-done (zerop (todos-get-count 'todo goal))))
1471 (todos-category-select)
1472 ;; Put point on the first merged item.
1474 (set-marker here nil)))
1476 ;; -----------------------------------------------------------------------------
1478 ;; -----------------------------------------------------------------------------
1480 (defcustom todos-include-in-diary nil
1481 "Non-nil to allow new Todo items to be included in the diary."
1485 (defcustom todos-diary-nonmarking nil
1486 "Non-nil to insert new Todo diary items as nonmarking by default.
1487 This appends `diary-nonmarking-symbol' to the front of an item on
1488 insertion provided it doesn't begin with `todos-nondiary-marker'."
1492 (defcustom todos-always-add-time-string nil
1493 "Non-nil adds current time to a new item's date header by default.
1494 When the Todos insertion commands have a non-nil \"maybe-notime\"
1495 argument, this reverses the effect of
1496 `todos-always-add-time-string': if t, these commands omit the
1497 current time, if nil, they include it."
1501 (defcustom todos-use-only-highlighted-region t
1502 "Non-nil to enable inserting only highlighted region as new item."
1506 (defcustom todos-item-mark "*"
1507 "String used to mark items.
1508 To ensure item marking works, change the value of this option
1509 only when no items are marked."
1510 :type '(string :validate
1512 (when (string= (widget-value widget) todos-prefix)
1515 "Invalid value: must be distinct from `todos-prefix'")
1517 :set (lambda (symbol value)
1518 (custom-set-default symbol (propertize value 'face 'todos-mark)))
1521 (defcustom todos-comment-string "COMMENT"
1522 "String inserted before optional comment appended to done item."
1524 :initialize 'custom-initialize-default
1525 :set 'todos-reset-comment-string
1528 (defcustom todos-undo-item-omit-comment 'ask
1529 "Whether to omit done item comment on undoing the item.
1530 Nil means never omit the comment, t means always omit it, `ask'
1531 means prompt user and omit comment only on confirmation."
1532 :type '(choice (const :tag "Never" nil)
1533 (const :tag "Always" t)
1534 (const :tag "Ask" ask))
1537 (defun todos-toggle-mark-item (&optional n)
1538 "Mark item with `todos-item-mark' if unmarked, otherwise unmark it.
1539 With a positive numerical prefix argument N, change the
1540 marking of the next N items."
1542 (when (todos-item-string)
1543 (unless (> n 1) (setq n 1))
1545 (let* ((cat (todos-current-category))
1546 (marks (assoc cat todos-categories-with-marks))
1548 (unless (looking-at todos-item-start)
1550 (todos-get-overlay 'prefix)))
1551 (pref (overlay-get ov 'before-string)))
1552 (if (todos-marked-item-p)
1554 (overlay-put ov 'before-string (substring pref 1))
1555 (if (= (cdr marks) 1) ; Deleted last mark in this category.
1556 (setq todos-categories-with-marks
1557 (assq-delete-all cat todos-categories-with-marks))
1558 (setcdr marks (1- (cdr marks)))))
1559 (overlay-put ov 'before-string (concat todos-item-mark pref))
1561 (setcdr marks (1+ (cdr marks)))
1562 (push (cons cat 1) todos-categories-with-marks))))
1563 (todos-forward-item))))
1565 (defun todos-mark-category ()
1566 "Mark all visiblw items in this category with `todos-item-mark'."
1568 (let* ((cat (todos-current-category))
1569 (marks (assoc cat todos-categories-with-marks)))
1571 (goto-char (point-min))
1573 (let* ((ov (todos-get-overlay 'prefix))
1574 (pref (overlay-get ov 'before-string)))
1575 (unless (todos-marked-item-p)
1576 (overlay-put ov 'before-string (concat todos-item-mark pref))
1578 (setcdr marks (1+ (cdr marks)))
1579 (push (cons cat 1) todos-categories-with-marks))))
1580 (todos-forward-item)))))
1582 (defun todos-unmark-category ()
1583 "Remove `todos-item-mark' from all visible items in this category."
1585 (let* ((cat (todos-current-category))
1586 (marks (assoc cat todos-categories-with-marks)))
1588 (goto-char (point-min))
1590 (let* ((ov (todos-get-overlay 'prefix))
1591 ;; No overlay on empty line between todo and done items.
1592 (pref (when ov (overlay-get ov 'before-string))))
1593 (when (todos-marked-item-p)
1594 (overlay-put ov 'before-string (substring pref 1)))
1595 (todos-forward-item))))
1596 (setq todos-categories-with-marks
1597 (delq marks todos-categories-with-marks))))
1599 (defvar todos-date-from-calendar nil
1600 "Helper variable for setting item date from the Emacs Calendar.")
1602 (defun todos-basic-insert-item (&optional arg diary nonmarking date-type time
1604 "Insert a new Todo item into a category.
1605 This is the function from which the generated Todos item
1606 insertion commands derive.
1608 The generated commands have mnenomic key bindings based on the
1609 arguments' values and their order in the command's argument list,
1610 as follows: (1) for DIARY `d', (2) for NONMARKING `k', (3) for
1611 DATE-TYPE either `c' for calendar or `d' for date or `n' for
1612 weekday name, (4) for TIME `t', (5) for REGION-OR-HERE either `r'
1613 for region or `h' for here. Sequences of these keys are appended
1614 to the insertion prefix key `i'. Keys that allow a following
1615 key (i.e., any but `r' or `h') must be doubled when used finally.
1616 For example, the command bound to the key sequence `i y h' will
1617 insert a new item with today's date, marked according to the
1618 DIARY argument described below, and with priority according to
1619 the HERE argument; `i y y' does the same except that the priority
1620 is not given by HERE but by prompting.
1622 In command invocations, ARG is passed as a prefix argument as
1623 follows. With no prefix argument, add the item to the current
1624 category; with one prefix argument (`C-u'), prompt for a category
1625 from the current Todos file; with two prefix arguments (`C-u C-u'),
1626 first prompt for a Todos file, then a category in that file. If
1627 a non-existing category is entered, ask whether to add it to the
1628 Todos file; if answered affirmatively, add the category and
1629 insert the item there.
1631 The remaining arguments are set or left nil by the generated item
1632 insertion commands; their meanings are described in the follows
1635 When argument DIARY is non-nil, this overrides the intent of the
1636 user option `todos-include-in-diary' for this item: if
1637 `todos-include-in-diary' is nil, include the item in the Fancy
1638 Diary display, and if it is non-nil, exclude the item from the
1639 Fancy Diary display. When DIARY is nil, `todos-include-in-diary'
1640 has its intended effect.
1642 When the item is included in the Fancy Diary display and the
1643 argument NONMARKING is non-nil, this overrides the intent of the
1644 user option `todos-diary-nonmarking' for this item: if
1645 `todos-diary-nonmarking' is nil, append `diary-nonmarking-symbol'
1646 to the item, and if it is non-nil, omit `diary-nonmarking-symbol'.
1648 The argument DATE-TYPE determines the content of the item's
1649 mandatory date header string and how it is added:
1650 - If DATE-TYPE is the symbol `calendar', the Calendar pops up and
1651 when the user puts the cursor on a date and hits RET, that
1652 date, in the format set by `calendar-date-display-form',
1653 becomes the date in the header.
1654 - If DATE-TYPE is a string matching the regexp
1655 `todos-date-pattern', that string becomes the date in the
1656 header. This case is for the command
1657 `todos-insert-item-from-calendar' which is called from the
1659 - If DATE-TYPE is the symbol `date', the header contains the date
1660 in the format set by `calendar-date-display-form', with year,
1661 month and day individually prompted for (month with tab
1663 - If DATE-TYPE is the symbol `dayname' the header contains a
1664 weekday name instead of a date, prompted for with tab
1666 - If DATE-TYPE has any other value (including nil or none) the
1667 header contains the current date (in the format set by
1668 `calendar-date-display-form').
1670 With non-nil argument TIME prompt for a time string, which must
1671 match `diary-time-regexp'. Typing `<return>' at the prompt
1672 returns the current time, if the user option
1673 `todos-always-add-time-string' is non-nil, otherwise the empty
1674 string (i.e., no time string). If TIME is absent or nil, add or
1675 omit the current time string according as
1676 `todos-always-add-time-string' is non-nil or nil, respectively.
1678 The argument REGION-OR-HERE determines the source and location of
1680 - If the REGION-OR-HERE is the symbol `here', prompt for the text of
1681 the new item and, if the command was invoked with point in the todo
1682 items section of the current category, give the new item the
1683 priority of the item at point, lowering the latter's priority and
1684 the priority of the remaining items. If point is in the done items
1685 section of the category, insert the new item as the first todo item
1686 in the category. Likewise, if the command with `here' is invoked
1687 outside of the current category, jump to the chosen category and
1688 insert the new item as the first item in the category.
1689 - If REGION-OR-HERE is the symbol `region', use the region of the
1690 current buffer as the text of the new item, depending on the
1691 value of user option `todos-use-only-highlighted-region': if
1692 this is non-nil, then use the region only when it is
1693 highlighted; otherwise, use the region regardless of
1694 highlighting. An error is signalled if there is no region in
1695 the current buffer. Prompt for the item's priority in the
1696 category (an integer between 1 and one more than the number of
1697 items in the category), and insert the item accordingly.
1698 - If REGION-OR-HERE has any other value (in particular, nil or
1699 none), prompt for the text and the item's priority, and insert
1700 the item accordingly."
1701 ;; If invoked outside of Todos mode and there is not yet any Todos
1702 ;; file, initialize one.
1703 (if (null todos-files)
1705 (let ((region (eq region-or-here 'region))
1706 (here (eq region-or-here 'here)))
1708 (let (use-empty-active-region)
1709 (unless (and todos-use-only-highlighted-region (use-region-p))
1710 (user-error "There is no active region"))))
1711 (let* ((obuf (current-buffer))
1712 (ocat (todos-current-category))
1714 (todos-mm (eq major-mode 'todos-mode))
1715 (cat+file (cond ((equal arg '(4))
1716 (todos-read-category "Insert in category: "))
1718 (todos-read-category "Insert in category: "
1721 (cons (todos-current-category)
1722 (or todos-current-todos-file
1723 (and todos-show-current-file
1724 todos-global-current-todos-file)
1725 (todos-absolute-file-name
1726 todos-default-todos-file))))))
1727 (cat (car cat+file))
1728 (file (cdr cat+file))
1729 (new-item (if region
1730 (buffer-substring-no-properties
1731 (region-beginning) (region-end))
1732 (read-from-minibuffer "Todo item: ")))
1734 ((eq date-type 'date)
1736 ((eq date-type 'dayname)
1737 (todos-read-dayname))
1738 ((eq date-type 'calendar)
1739 (setq todos-date-from-calendar t)
1740 (or (todos-set-date-from-calendar)
1741 ;; If user exits Calendar before choosing
1742 ;; a date, cancel item insertion.
1744 ((and (stringp date-type)
1745 (string-match todos-date-pattern date-type))
1746 (setq todos-date-from-calendar date-type)
1747 (todos-set-date-from-calendar))
1749 (calendar-date-string
1750 (calendar-current-date) t t))))
1751 (time-string (or (and time (todos-read-time))
1752 (and todos-always-add-time-string
1753 (substring (current-time-string) 11 16)))))
1754 (setq todos-date-from-calendar nil)
1755 (find-file-noselect file 'nowarn)
1756 (set-window-buffer (selected-window)
1757 (set-buffer (find-buffer-visiting file)))
1758 ;; If this command was invoked outside of a Todos buffer, the
1759 ;; call to todos-current-category above returned nil. If we
1760 ;; just entered Todos mode now, then cat was set to the file's
1761 ;; first category, but if todos-mode was already enabled, cat
1762 ;; did not get set, so we have to set it explicitly.
1764 (setq cat (todos-current-category)))
1765 (setq todos-current-todos-file file)
1766 (unless todos-global-current-todos-file
1767 (setq todos-global-current-todos-file todos-current-todos-file))
1768 (let ((buffer-read-only nil)
1769 (called-from-outside (not (and todos-mm (equal cat ocat))))
1770 done-only item-added)
1772 ;; Add date, time and diary marking as required.
1773 (concat (if (not (and diary (not todos-include-in-diary)))
1774 todos-nondiary-start
1775 (when (and nonmarking (not todos-diary-nonmarking))
1776 diary-nonmarking-symbol))
1777 date-string (when (and time-string ; Can be empty.
1780 (concat " " time-string))
1781 (when (not (and diary (not todos-include-in-diary)))
1784 ;; Indent newlines inserted by C-q C-j if nonspace char follows.
1785 (setq new-item (replace-regexp-in-string "\\(\n\\)[^[:blank:]]"
1786 "\n\t" new-item nil nil 1))
1789 ;; Make sure the correct category is selected. There
1790 ;; are two cases: (i) we just visited the file, so no
1791 ;; category is selected yet, or (ii) we invoked
1792 ;; insertion "here" from outside the category we want
1793 ;; to insert in (with priority insertion, category
1794 ;; selection is done by todos-set-item-priority).
1795 (when (or (= (- (point-max) (point-min)) (buffer-size))
1796 (and here called-from-outside))
1797 (todos-category-number cat)
1798 (todos-category-select))
1799 ;; If only done items are displayed in category,
1800 ;; toggle to todo items before inserting new item.
1801 (when (save-excursion
1802 (goto-char (point-min))
1803 (looking-at todos-done-string-start))
1805 (todos-toggle-view-done-only))
1808 ;; If command was invoked with point in done
1809 ;; items section or outside of the current
1810 ;; category, can't insert "here", so to be
1811 ;; useful give new item top priority.
1812 (when (or (todos-done-item-section-p)
1815 (goto-char (point-min)))
1816 (todos-insert-with-overlays new-item))
1817 (todos-set-item-priority new-item cat t))
1818 (setq item-added t))
1819 ;; If user cancels before setting priority, restore
1824 (unless (equal cat ocat)
1825 (todos-category-number ocat)
1826 (todos-category-select))
1827 (and done-only (todos-toggle-view-done-only)))
1828 (set-window-buffer (selected-window) (set-buffer obuf)))
1830 ;; If the todo items section is not visible when the
1831 ;; insertion command is called (either because only done
1832 ;; items were shown or because the category was not in the
1833 ;; current buffer), then if the item is inserted at the
1834 ;; end of the category, point is at eob and eob at
1835 ;; window-start, so that higher priority todo items are
1836 ;; out of view. So we recenter to make sure the todo
1837 ;; items are displayed in the window.
1838 (when item-added (recenter)))
1839 (todos-update-count 'todo 1)
1840 (if (or diary todos-include-in-diary) (todos-update-count 'diary 1))
1841 (todos-update-categories-sexp))))))
1843 (defun todos-set-date-from-calendar ()
1844 "Return string of date chosen from Calendar."
1845 (cond ((and (stringp todos-date-from-calendar)
1846 (string-match todos-date-pattern todos-date-from-calendar))
1847 todos-date-from-calendar)
1848 (todos-date-from-calendar
1849 (let (calendar-view-diary-initially-flag)
1850 (calendar)) ; *Calendar* is now current buffer.
1851 (define-key calendar-mode-map [remap newline] 'exit-recursive-edit)
1852 ;; If user exits Calendar before choosing a date, clean up properly.
1853 (define-key calendar-mode-map
1854 [remap calendar-exit] (lambda ()
1858 (exit-recursive-edit))))
1859 (message "Put cursor on a date and type <return> to set it.")
1862 (when (equal (buffer-name) calendar-buffer)
1863 (setq todos-date-from-calendar
1864 (calendar-date-string (calendar-cursor-to-date t) t t))
1866 todos-date-from-calendar)
1867 (define-key calendar-mode-map [remap newline] nil)
1868 (define-key calendar-mode-map [remap calendar-exit] nil)
1869 (unless (zerop (recursion-depth)) (exit-recursive-edit))
1870 (when (stringp todos-date-from-calendar)
1871 todos-date-from-calendar)))))
1873 (defun todos-insert-item-from-calendar (&optional arg)
1874 "Prompt for and insert a new item with date selected from calendar.
1875 Invoked without prefix argument ARG, insert the item into the
1876 current category, without one prefix argument, prompt for the
1877 category from the current todo file or from one listed in
1878 `todos-category-completions-files'; with two prefix arguments,
1879 prompt for a todo file and then for a category in it."
1881 (setq todos-date-from-calendar
1882 (calendar-date-string (calendar-cursor-to-date t) t t))
1884 (todos-basic-insert-item arg nil nil todos-date-from-calendar))
1886 (define-key calendar-mode-map "it" 'todos-insert-item-from-calendar)
1888 (defun todos-copy-item ()
1889 "Copy item at point and insert the copy as a new item."
1891 (unless (or (todos-done-item-p) (looking-at "^$"))
1892 (let ((copy (todos-item-string))
1893 (diary-item (todos-diary-item-p)))
1894 (todos-set-item-priority copy (todos-current-category) t)
1895 (todos-update-count 'todo 1)
1896 (when diary-item (todos-update-count 'diary 1))
1897 (todos-update-categories-sexp))))
1899 (defun todos-delete-item ()
1900 "Delete at least one item in this category.
1901 If there are marked items, delete all of these; otherwise, delete
1906 (let* ((cat (todos-current-category))
1907 (marked (assoc cat todos-categories-with-marks))
1908 (item (unless marked (todos-item-string)))
1911 "Permanently delete all marked items? ")
1913 (setq ov (make-overlay
1914 (save-excursion (todos-item-start))
1915 (save-excursion (todos-item-end))))
1916 (overlay-put ov 'face 'todos-search)
1917 (todos-y-or-n-p "Permanently delete this item? "))))
1920 (and marked (goto-char (point-min)))
1923 (if (or (and marked (todos-marked-item-p)) item)
1925 (if (todos-done-item-p)
1926 (todos-update-count 'done -1)
1927 (todos-update-count 'todo -1 cat)
1928 (and (todos-diary-item-p)
1929 (todos-update-count 'diary -1)))
1930 (if ov (delete-overlay ov))
1932 ;; Don't leave point below last item.
1933 (and item (bolp) (eolp) (< (point-min) (point-max))
1934 (todos-backward-item))
1936 (throw 'done (setq item nil))))
1937 (todos-forward-item))))
1939 (setq todos-categories-with-marks
1940 (assq-delete-all cat todos-categories-with-marks)))
1941 (todos-update-categories-sexp)
1942 (todos-prefix-overlays)))
1943 (if ov (delete-overlay ov)))))
1945 (defun todos-edit-item (&optional arg)
1946 "Edit the Todo item at point.
1947 With non-nil prefix argument ARG, include the item's date/time
1948 header, making it also editable; otherwise, include only the item
1951 If the item consists of only one logical line, edit it in the
1952 minibuffer; otherwise, edit it in Todos Edit mode."
1954 (when (todos-item-string)
1955 (let* ((opoint (point))
1956 (start (todos-item-start))
1959 (concat todos-date-string-start todos-date-pattern
1960 "\\( " diary-time-regexp "\\)?"
1961 (regexp-quote todos-nondiary-end) "?")
1962 (line-end-position) t)
1963 (1+ (- (point) start))))
1964 (header (substring (todos-item-string) 0 item-beg))
1965 (item (if arg (todos-item-string)
1966 (substring (todos-item-string) item-beg)))
1967 (multiline (> (length (split-string item "\n")) 1))
1968 (buffer-read-only nil))
1970 (todos-edit-multiline-item)
1971 (let ((new (concat (if arg "" header)
1972 (read-string "Edit: " (if arg
1973 (cons item item-beg)
1976 (while (not (string-match (concat todos-date-string-start
1977 todos-date-pattern) new))
1978 (setq new (read-from-minibuffer
1979 "Item must start with a date: " new))))
1980 ;; Ensure lines following hard newlines are indented.
1981 (setq new (replace-regexp-in-string "\\(\n\\)[^[:blank:]]"
1982 "\n\t" new nil nil 1))
1983 ;; If user moved point during editing, make sure it moves back.
1986 (todos-insert-with-overlays new)
1987 (move-to-column item-beg))))))
1989 (defun todos-edit-multiline-item ()
1990 "Edit current Todo item in Todos Edit mode.
1991 Use of newlines invokes `todos-indent' to insure compliance with
1992 the format of Diary entries."
1994 (when (todos-item-string)
1995 (let ((buf todos-edit-buffer))
1996 (set-window-buffer (selected-window)
1997 (set-buffer (make-indirect-buffer (buffer-name) buf)))
1998 (narrow-to-region (todos-item-start) (todos-item-end))
2000 (message "%s" (substitute-command-keys
2001 (concat "Type \\[todos-edit-quit] "
2002 "to return to Todos mode.\n"))))))
2004 (defun todos-edit-quit ()
2005 "Return from Todos Edit mode to Todos mode.
2006 If the item contains hard line breaks, make sure the following
2007 lines are indented by `todos-indent-to-here' to conform to diary
2010 If the whole file was in Todos Edit mode, check before returning
2011 whether the file is still a valid Todos file and if so, also
2012 recalculate the Todos categories sexp, in case changes were made
2013 in the number or names of categories."
2015 (if (> (buffer-size) (- (point-max) (point-min)))
2016 ;; We got here via `e m'.
2017 (let ((item (buffer-string))
2018 (regex "\\(\n\\)[^[:blank:]]")
2019 (buf (buffer-base-buffer)))
2020 (while (not (string-match (concat todos-date-string-start
2021 todos-date-pattern) item))
2022 (setq item (read-from-minibuffer
2023 "Item must start with a date: " item)))
2024 ;; Ensure lines following hard newlines are indented.
2025 (when (string-match regex (buffer-string))
2026 (setq item (replace-regexp-in-string regex "\n\t" item nil nil 1))
2027 (delete-region (point-min) (point-max))
2030 (unless (eq (current-buffer) buf)
2031 (set-window-buffer (selected-window) (set-buffer buf))))
2032 ;; We got here via `F e'.
2033 (when (todos-check-format)
2034 ;; FIXME: separate out sexp check?
2035 ;; If manual editing makes e.g. item counts change, have to
2036 ;; call this to update todos-categories, but it restores
2037 ;; category order to list order.
2038 ;; (todos-repair-categories-sexp)
2039 ;; Compare (todos-make-categories-list t) with sexp and if
2040 ;; different ask (todos-update-categories-sexp) ?
2042 (let* ((cat-beg (concat "^" (regexp-quote todos-category-beg)
2044 (curline (buffer-substring-no-properties
2045 (line-beginning-position) (line-end-position)))
2046 (cat (cond ((string-match cat-beg curline)
2047 (match-string-no-properties 1 curline))
2048 ((or (re-search-backward cat-beg nil t)
2049 (re-search-forward cat-beg nil t))
2050 (match-string-no-properties 1)))))
2051 (todos-category-number cat)
2052 (todos-category-select)
2053 (goto-char (point-min))))))
2055 (defun todos-basic-edit-item-header (what &optional inc)
2056 "Function underlying commands to edit item date/time header.
2058 The argument WHAT (passed by invoking commands) specifies what
2059 part of the header to edit; possible values are these symbols:
2060 `date', to edit the year, month, and day of the date string;
2061 `time', to edit just the time string; `calendar', to select the
2062 date from the Calendar; `today', to set the date to today's date;
2063 `dayname', to set the date string to the name of a day or to
2064 change the day name; and `year', `month' or `day', to edit only
2065 these respective parts of the date string (`day' is the number of
2066 the given day of the month, and `month' is either the name of the
2067 given month or its number, depending on the value of
2068 `calendar-date-display-form').
2070 The optional argument INC is a positive or negative integer
2071 \(passed by invoking commands as a numerical prefix argument)
2072 that in conjunction with the WHAT values `year', `month' or
2073 `day', increments or decrements the specified date string
2074 component by the specified number of suitable units, i.e., years,
2075 months, or days, with automatic adjustment of the other date
2076 string components as necessary.
2078 If there are marked items, apply the same edit to all of these;
2079 otherwise, edit just the item at point."
2080 (let* ((cat (todos-current-category))
2081 (marked (assoc cat todos-categories-with-marks))
2083 (todos-date-from-calendar t)
2084 (buffer-read-only nil)
2085 ndate ntime year monthname month day
2086 dayname) ; Needed by calendar-date-display-form.
2088 (or (and marked (goto-char (point-min))) (todos-item-start))
2092 (while (not (todos-marked-item-p))
2093 (todos-forward-item)
2094 (and (eobp) (throw 'end nil))))
2095 (re-search-forward (concat todos-date-string-start "\\(?1:"
2097 "\\)\\(?2: " diary-time-regexp "\\)?"
2098 (regexp-quote todos-nondiary-end) "?")
2099 (line-end-position) t)
2100 (let* ((odate (match-string-no-properties 1))
2101 (otime (match-string-no-properties 2))
2102 (odayname (match-string-no-properties 5))
2103 (omonthname (match-string-no-properties 6))
2104 (omonth (match-string-no-properties 7))
2105 (oday (match-string-no-properties 8))
2106 (oyear (match-string-no-properties 9))
2107 (tmn-array todos-month-name-array)
2108 (mlist (append tmn-array nil))
2109 (tma-array todos-month-abbrev-array)
2110 (mablist (append tma-array nil))
2111 (yy (and oyear (unless (string= oyear "*")
2112 (string-to-number oyear))))
2113 (mm (or (and omonth (unless (string= omonth "*")
2114 (string-to-number omonth)))
2115 (1+ (- (length mlist)
2116 (length (or (member omonthname mlist)
2117 (member omonthname mablist)))))))
2118 (dd (and oday (unless (string= oday "*")
2119 (string-to-number oday)))))
2120 ;; If there are marked items, use only the first to set
2121 ;; header changes, and apply these to all marked items.
2125 (setq ndate (todos-read-date)))
2126 ((eq what 'calendar)
2127 (setq ndate (save-match-data (todos-set-date-from-calendar))))
2129 (setq ndate (calendar-date-string (calendar-current-date) t t)))
2131 (setq ndate (todos-read-dayname)))
2133 (setq ntime (save-match-data (todos-read-time)))
2134 (when (> (length ntime) 0)
2135 (setq ntime (concat " " ntime))))
2136 ;; When date string consists only of a day name,
2137 ;; passing other date components is a noop.
2138 ((and odayname (memq what '(year month day))))
2141 monthname omonthname
2143 year (cond ((not current-prefix-arg)
2144 (todos-read-date 'year))
2145 ((string= oyear "*")
2146 (user-error "Cannot increment *"))
2148 (number-to-string (+ yy inc))))))
2152 (if (memq 'month calendar-date-display-form)
2155 (cond ((not current-prefix-arg)
2156 (todos-read-date 'month))
2157 ((or (string= omonth "*") (= mm 13))
2158 (user-error "Cannot increment *"))
2160 (let ((mminc (+ mm inc)))
2161 ;; Increment or decrement month by INC
2163 (setq mm (% mminc 12))
2164 ;; If result is 0, make month December.
2165 (setq mm (if (= mm 0) 12 (abs mm)))
2166 ;; Adjust year if necessary.
2167 (setq year (or (and (cond ((> mminc 12)
2168 (+ yy (/ mminc 12)))
2170 (- yy (/ mminc 12) 1))
2172 (number-to-string yy))
2174 ;; Return the changed numerical month as
2175 ;; a string or the corresponding month name.
2177 (number-to-string mm)
2178 (aref tma-array (1- mm))))))
2179 (let ((yy (string-to-number year)) ; 0 if year is "*".
2180 ;; When mm is 13 (corresponding to "*" as value
2181 ;; of month), this raises an args-out-of-range
2182 ;; error in calendar-last-day-of-month, so use 1
2183 ;; (corresponding to January) to get 31 days.
2184 (mm (if (= mm 13) 1 mm)))
2185 (if (> (string-to-number day)
2186 (calendar-last-day-of-month mm yy))
2187 (user-error "%s %s does not have %s days"
2188 (aref tmn-array (1- mm))
2189 (if (= mm 2) yy "") day))))
2193 monthname omonthname
2195 ((not current-prefix-arg)
2196 (todos-read-date 'day mm oyear))
2198 (user-error "Cannot increment *"))
2199 ((or (string= omonth "*") (string= omonthname "*"))
2200 (setq dd (+ dd inc))
2202 (user-error "A month cannot have more than 31 days")
2203 (number-to-string dd)))
2204 ;; Increment or decrement day by INC,
2205 ;; adjusting month and year if necessary
2206 ;; (if year is "*" assume current year to
2207 ;; calculate adjustment).
2209 (let* ((yy (or yy (calendar-extract-year
2210 (calendar-current-date))))
2211 (date (calendar-gregorian-from-absolute
2212 (+ (calendar-absolute-from-gregorian
2213 (list mm dd yy)) inc)))
2214 (adjmm (nth 0 date)))
2215 ;; Set year and month(name) to adjusted values.
2216 (unless (string= year "*")
2217 (setq year (number-to-string (nth 2 date))))
2219 (setq month (number-to-string adjmm))
2220 (setq monthname (aref tma-array (1- adjmm))))
2221 ;; Return changed numerical day as a string.
2222 (number-to-string (nth 1 date)))))))))
2224 ;; If year, month or day date string components were
2225 ;; changed, rebuild the date string.
2226 (when (memq what '(year month day))
2227 (setq ndate (mapconcat 'eval calendar-date-display-form ""))))
2228 (when ndate (replace-match ndate nil nil nil 1))
2229 ;; Add new time string to the header, if it was supplied.
2232 (replace-match ntime nil nil nil 2)
2233 (goto-char (match-end 1))
2235 (setq todos-date-from-calendar nil)
2237 ;; Apply the changes to the first marked item header to the
2238 ;; remaining marked items. If there are no marked items,
2241 (todos-forward-item)
2242 (goto-char (point-max))))))))
2244 (defun todos-edit-item-header ()
2245 "Interactively edit at least the date of item's date/time header.
2246 If user option `todos-always-add-time-string' is non-nil, also
2247 edit item's time string."
2249 (todos-basic-edit-item-header 'date)
2250 (when todos-always-add-time-string
2251 (todos-edit-item-time)))
2253 (defun todos-edit-item-time ()
2254 "Interactively edit the time string of item's date/time header."
2256 (todos-basic-edit-item-header 'time))
2258 (defun todos-edit-item-date-from-calendar ()
2259 "Interactively edit item's date using the Calendar."
2261 (todos-basic-edit-item-header 'calendar))
2263 (defun todos-edit-item-date-to-today ()
2264 "Set item's date to today's date."
2266 (todos-basic-edit-item-header 'today))
2268 (defun todos-edit-item-date-day-name ()
2269 "Replace item's date with the name of a day of the week."
2271 (todos-basic-edit-item-header 'dayname))
2273 (defun todos-edit-item-date-year (&optional inc)
2274 "Interactively edit the year of item's date string.
2275 With prefix argument INC a positive or negative integer,
2276 increment or decrement the year by INC."
2278 (todos-basic-edit-item-header 'year inc))
2280 (defun todos-edit-item-date-month (&optional inc)
2281 "Interactively edit the month of item's date string.
2282 With prefix argument INC a positive or negative integer,
2283 increment or decrement the month by INC."
2285 (todos-basic-edit-item-header 'month inc))
2287 (defun todos-edit-item-date-day (&optional inc)
2288 "Interactively edit the day of the month of item's date string.
2289 With prefix argument INC a positive or negative integer,
2290 increment or decrement the day by INC."
2292 (todos-basic-edit-item-header 'day inc))
2294 (defun todos-edit-item-diary-inclusion ()
2295 "Change diary status of one or more todo items in this category.
2296 That is, insert `todos-nondiary-marker' if the candidate items
2297 lack this marking; otherwise, remove it.
2299 If there are marked todo items, change the diary status of all
2300 and only these, otherwise change the diary status of the item at
2303 (let ((buffer-read-only)
2304 (marked (assoc (todos-current-category)
2305 todos-categories-with-marks)))
2308 (when marked (goto-char (point-min)))
2310 (if (todos-done-item-p)
2311 (throw 'stop (message "Done items cannot be edited"))
2312 (unless (and marked (not (todos-marked-item-p)))
2313 (let* ((beg (todos-item-start))
2314 (lim (save-excursion (todos-item-end)))
2315 (end (save-excursion
2316 (or (todos-time-string-matcher lim)
2317 (todos-date-string-matcher lim)))))
2318 (if (looking-at (regexp-quote todos-nondiary-start))
2321 (search-forward todos-nondiary-end (1+ end) t)
2323 (todos-update-count 'diary 1))
2325 (insert todos-nondiary-start)
2326 (goto-char (1+ end))
2327 (insert todos-nondiary-end)
2328 (todos-update-count 'diary -1)))))
2329 (unless marked (throw 'stop nil))
2330 (todos-forward-item)))))
2331 (todos-update-categories-sexp)))
2333 (defun todos-edit-category-diary-inclusion (arg)
2334 "Make all items in this category diary items.
2335 With prefix ARG, make all items in this category non-diary
2339 (goto-char (point-min))
2340 (let ((todo-count (todos-get-count 'todo))
2341 (diary-count (todos-get-count 'diary))
2345 (if (todos-done-item-p) ; We've gone too far.
2347 (let* ((beg (todos-item-start))
2348 (lim (save-excursion (todos-item-end)))
2349 (end (save-excursion
2350 (or (todos-time-string-matcher lim)
2351 (todos-date-string-matcher lim)))))
2353 (unless (looking-at (regexp-quote todos-nondiary-start))
2354 (insert todos-nondiary-start)
2355 (goto-char (1+ end))
2356 (insert todos-nondiary-end))
2357 (when (looking-at (regexp-quote todos-nondiary-start))
2359 (search-forward todos-nondiary-end (1+ end) t)
2360 (replace-match "")))))
2361 (todos-forward-item))
2362 (unless (if arg (zerop diary-count) (= diary-count todo-count))
2363 (todos-update-count 'diary (if arg
2365 (- todo-count diary-count))))
2366 (todos-update-categories-sexp)))))
2368 (defun todos-edit-item-diary-nonmarking ()
2369 "Change non-marking of one or more diary items in this category.
2370 That is, insert `diary-nonmarking-symbol' if the candidate items
2371 lack this marking; otherwise, remove it.
2373 If there are marked todo items, change the non-marking status of
2374 all and only these, otherwise change the non-marking status of
2377 (let ((buffer-read-only)
2378 (marked (assoc (todos-current-category)
2379 todos-categories-with-marks)))
2382 (when marked (goto-char (point-min)))
2384 (if (todos-done-item-p)
2385 (throw 'stop (message "Done items cannot be edited"))
2386 (unless (and marked (not (todos-marked-item-p)))
2388 (unless (looking-at (regexp-quote todos-nondiary-start))
2389 (if (looking-at (regexp-quote diary-nonmarking-symbol))
2391 (insert diary-nonmarking-symbol))))
2392 (unless marked (throw 'stop nil))
2393 (todos-forward-item)))))))
2395 (defun todos-edit-category-diary-nonmarking (arg)
2396 "Add `diary-nonmarking-symbol' to all diary items in this category.
2397 With prefix ARG, remove `diary-nonmarking-symbol' from all diary
2398 items in this category."
2401 (goto-char (point-min))
2402 (let (buffer-read-only)
2405 (if (todos-done-item-p) ; We've gone too far.
2407 (unless (looking-at (regexp-quote todos-nondiary-start))
2409 (when (looking-at (regexp-quote diary-nonmarking-symbol))
2411 (unless (looking-at (regexp-quote diary-nonmarking-symbol))
2412 (insert diary-nonmarking-symbol))))
2413 (todos-forward-item)))))))
2415 (defun todos-set-item-priority (&optional item cat new arg)
2416 "Prompt for and set ITEM's priority in CATegory.
2418 Interactively, ITEM is the todo item at point, CAT is the current
2419 category, and the priority is a number between 1 and the number
2420 of items in the category. Non-interactively, non-nil NEW means
2421 ITEM is a new item and the lowest priority is one more than the
2422 number of items in CAT.
2424 The new priority is set either interactively by prompt or by a
2425 numerical prefix argument, or noninteractively by argument ARG,
2426 whose value can be either of the symbols `raise' or `lower',
2427 meaning to raise or lower the item's priority by one."
2429 (unless (and (called-interactively-p 'any)
2430 (or (todos-done-item-p) (looking-at "^$")))
2431 (let* ((item (or item (todos-item-string)))
2432 (marked (todos-marked-item-p))
2433 (cat (or cat (cond ((eq major-mode 'todos-mode)
2434 (todos-current-category))
2435 ((eq major-mode 'todos-filtered-items-mode)
2437 (concat todos-date-string-start
2439 "\\( " diary-time-regexp "\\)?"
2440 (regexp-quote todos-nondiary-end)
2441 "?\\(?1: \\[\\(.+:\\)?.+\\]\\)")))
2443 (re-search-forward regexp1 nil t)
2444 (match-string-no-properties 1)))))))
2446 (todo (cond ((or (eq arg 'raise) (eq arg 'lower)
2447 (eq major-mode 'todos-filtered-items-mode))
2449 (let ((curstart (todos-item-start))
2451 (goto-char (point-min))
2452 (while (looking-at todos-item-start)
2453 (setq count (1+ count))
2454 (when (= (point) curstart) (setq curnum count))
2455 (todos-forward-item))
2457 ((eq major-mode 'todos-mode)
2458 (todos-get-count 'todo cat))))
2459 (maxnum (if new (1+ todo) todo))
2460 (prompt (format "Set item priority (1-%d): " maxnum))
2461 (priority (cond ((and (not arg) (numberp current-prefix-arg))
2463 ((and (eq arg 'raise) (>= curnum 1))
2465 ((and (eq arg 'lower) (<= curnum maxnum))
2469 (unless (and priority
2470 (or (and (eq arg 'raise) (zerop priority))
2471 (and (eq arg 'lower) (> priority maxnum))))
2472 ;; When moving item to another category, show the category before
2473 ;; prompting for its priority.
2474 (unless (or arg (called-interactively-p 'any))
2475 (todos-category-number cat)
2476 ;; If done items in category are visible, keep them visible.
2477 (let ((done todos-show-with-done))
2478 (when (> (buffer-size) (- (point-max) (point-min)))
2480 (goto-char (point-min))
2481 (setq done (re-search-forward todos-done-string-start nil t))))
2482 (let ((todos-show-with-done done))
2483 (todos-category-select)
2484 ;; Keep top of category in view while setting priority.
2485 (goto-char (point-min)))))
2486 ;; Prompt for priority only when the category has at least one
2489 (while (not priority)
2490 (setq candidate (read-number prompt))
2491 (setq prompt (when (or (< candidate 1) (> candidate maxnum))
2492 (format "Priority must be an integer between 1 and %d.\n"
2494 (unless prompt (setq priority candidate))))
2495 ;; In Top Priorities buffer, an item's priority can be changed
2496 ;; wrt items in another category, but not wrt items in the same
2498 (when (eq major-mode 'todos-filtered-items-mode)
2499 (let* ((regexp2 (concat todos-date-string-start todos-date-pattern
2500 "\\( " diary-time-regexp "\\)?"
2501 (regexp-quote todos-nondiary-end)
2502 "?\\(?1:" (regexp-quote cat) "\\)"))
2503 (end (cond ((< curnum priority)
2504 (save-excursion (todos-item-end)))
2505 ((> curnum priority)
2506 (save-excursion (todos-item-start)))))
2507 (match (save-excursion
2508 (cond ((< curnum priority)
2509 (todos-forward-item (1+ (- priority curnum)))
2510 (when (re-search-backward regexp2 end t)
2511 (match-string-no-properties 1)))
2512 ((> curnum priority)
2513 (todos-backward-item (- curnum priority))
2514 (when (re-search-forward regexp2 end t)
2515 (match-string-no-properties 1)))))))
2517 (user-error (concat "Cannot reprioritize items from the same "
2518 "category in this mode, only in Todos mode")))))
2519 ;; Interactively or with non-nil ARG, relocate the item within its
2521 (when (or arg (called-interactively-p 'any))
2522 (todos-remove-item))
2523 (goto-char (point-min))
2525 (unless (= priority 1)
2526 (todos-forward-item (1- priority))
2527 ;; When called from todos-item-undone and the highest priority
2528 ;; is chosen, this advances point to the first done item, so
2529 ;; move it up to the empty line above the done items
2531 (when (looking-back (concat "^"
2532 (regexp-quote todos-category-done)
2534 (todos-backward-item))))
2535 (todos-insert-with-overlays item)
2536 ;; If item was marked, restore the mark.
2538 (let* ((ov (todos-get-overlay 'prefix))
2539 (pref (overlay-get ov 'before-string)))
2540 (overlay-put ov 'before-string
2541 (concat todos-item-mark pref))))))))
2543 (defun todos-raise-item-priority ()
2544 "Raise priority of current item by moving it up by one item."
2546 (todos-set-item-priority nil nil nil 'raise))
2548 (defun todos-lower-item-priority ()
2549 "Lower priority of current item by moving it down by one item."
2551 (todos-set-item-priority nil nil nil 'lower))
2553 (defun todos-move-item (&optional file)
2554 "Move at least one todo or done item to another category.
2555 If there are marked items, move all of these; otherwise, move
2558 With prefix argument FILE, prompt for a specific Todos file and
2559 choose (with TAB completion) a category in it to move the item or
2560 items to; otherwise, choose and move to any category in either
2561 the current Todos file or one of the files in
2562 `todos-category-completions-files'. If the chosen category is
2563 not an existing categories, then it is created and the item(s)
2564 become(s) the first entry/entries in that category.
2566 With moved Todo items, prompt to set the priority in the category
2567 moved to (with multiple todos items, the one that had the highest
2568 priority in the category moved from gets the new priority and the
2569 rest of the moved todo items are inserted in sequence below it).
2570 Moved done items are appended to the top of the done items
2571 section in the category moved to."
2573 (let* ((cat1 (todos-current-category))
2574 (marked (assoc cat1 todos-categories-with-marks)))
2575 ;; Noop if point is not on an item and there are no marked items.
2576 (unless (and (looking-at "^$")
2578 (let* ((buffer-read-only)
2579 (file1 todos-current-todos-file)
2580 (num todos-category-number)
2581 (item (todos-item-string))
2582 (diary-item (todos-diary-item-p))
2583 (done-item (and (todos-done-item-p) (concat item "\n")))
2584 (omark (save-excursion (todos-item-start) (point-marker)))
2588 ov cat2 file2 moved nmark todo-items done-items)
2592 (setq ov (make-overlay (save-excursion (todos-item-start))
2593 (save-excursion (todos-item-end))))
2594 (overlay-put ov 'face 'todos-search))
2595 (let* ((pl (if (and marked (> (cdr marked) 1)) "s" ""))
2596 (cat+file (todos-read-category (concat "Move item" pl
2599 (while (and (equal (car cat+file) cat1)
2600 (equal (cdr cat+file) file1))
2601 (setq cat+file (todos-read-category
2602 "Choose a different category: ")))
2603 (setq cat2 (car cat+file)
2604 file2 (cdr cat+file))))
2605 (if ov (delete-overlay ov)))
2606 (set-buffer (find-buffer-visiting file1))
2609 (goto-char (point-min))
2611 (when (todos-marked-item-p)
2612 (if (todos-done-item-p)
2613 (setq done-items (concat done-items
2614 (todos-item-string) "\n")
2616 (setq todo-items (concat todo-items
2617 (todos-item-string) "\n")
2619 (when (todos-diary-item-p)
2620 (setq diary (1+ diary)))))
2621 (todos-forward-item))
2622 ;; Chop off last newline of multiple todo item string,
2623 ;; since it will be reinserted when setting priority
2624 ;; (but with done items priority is not set, so keep
2627 (setq todo-items (substring todo-items 0 -1))))
2628 (if (todos-done-item-p)
2631 (when (todos-diary-item-p) (setq diary 1))))
2632 (set-window-buffer (selected-window)
2633 (set-buffer (find-file-noselect file2 'nowarn)))
2636 (when (or todo-items (and item (not done-item)))
2637 (todos-set-item-priority (or todo-items item) cat2 t))
2638 ;; Move done items en bloc to top of done items section.
2639 (when (or done-items done-item)
2640 (todos-category-number cat2)
2642 (goto-char (point-min))
2644 (concat "^" (regexp-quote (concat todos-category-beg cat2))
2647 (concat "^" (regexp-quote todos-category-done)) nil t)
2649 (insert (or done-items done-item)))
2652 ;; Move succeeded, so remove item from starting category,
2653 ;; update item counts and display the category containing
2656 (setq nmark (point-marker))
2657 (when todo (todos-update-count 'todo todo))
2658 (when diary (todos-update-count 'diary diary))
2659 (when done (todos-update-count 'done done))
2660 (todos-update-categories-sexp)
2661 (with-current-buffer (find-buffer-visiting file1)
2670 (concat "^" (regexp-quote todos-category-beg)) nil t)
2673 (setq end (if (re-search-forward
2674 (concat "^" (regexp-quote
2675 todos-category-beg)) nil t)
2679 (while (< (point) end)
2680 (if (todos-marked-item-p)
2682 (todos-forward-item)))
2683 (setq todos-categories-with-marks
2684 (assq-delete-all cat1 todos-categories-with-marks)))
2685 (if ov (delete-overlay ov))
2686 (todos-remove-item))))
2687 (when todo (todos-update-count 'todo (- todo) cat1))
2688 (when diary (todos-update-count 'diary (- diary) cat1))
2689 (when done (todos-update-count 'done (- done) cat1))
2690 (todos-update-categories-sexp))
2691 (set-window-buffer (selected-window)
2692 (set-buffer (find-file-noselect file2 'nowarn)))
2693 (setq todos-category-number (todos-category-number cat2))
2694 (let ((todos-show-with-done (or done-items done-item)))
2695 (todos-category-select))
2697 ;; If item is moved to end of (just first?) category, make
2698 ;; sure the items above it are displayed in the window.
2700 ;; User quit before setting priority of todo item(s), so
2701 ;; return to starting category.
2703 (set-window-buffer (selected-window)
2704 (set-buffer (find-file-noselect file1 'nowarn)))
2705 (todos-category-number cat1)
2706 (todos-category-select)
2707 (goto-char omark))))))))
2709 (defun todos-item-done (&optional arg)
2710 "Tag a todo item in this category as done and relocate it.
2712 With prefix argument ARG prompt for a comment and append it to
2713 the done item; this is only possible if there are no marked
2714 items. If there are marked items, tag all of these with
2715 `todos-done-string' plus the current date and, if
2716 `todos-always-add-time-string' is non-nil, the current time;
2717 otherwise, just tag the item at point. Items tagged as done are
2718 relocated to the category's (by default hidden) done section. If
2719 done items are visible on invoking this command, they remain
2722 (let* ((cat (todos-current-category))
2723 (marked (assoc cat todos-categories-with-marks)))
2727 (goto-char (point-max))
2728 (todos-backward-item)
2729 (unless (todos-done-item-p)
2731 (unless (re-search-forward
2732 (concat "^" (regexp-quote todos-category-beg)) nil t)
2733 (goto-char (point-max)))
2735 (while (todos-done-item-p)
2736 (when (todos-marked-item-p)
2737 (user-error "This command does not apply to done items"))
2738 (todos-backward-item)))))
2739 (unless (and (not marked)
2740 (or (todos-done-item-p)
2741 ;; Point is between todo and done items.
2743 (let* ((date-string (calendar-date-string (calendar-current-date) t t))
2744 (time-string (if todos-always-add-time-string
2745 (concat " " (substring (current-time-string)
2748 (done-prefix (concat "[" todos-done-string date-string time-string
2750 (comment (and arg (read-string "Enter a comment: ")))
2753 (show-done (save-excursion
2754 (goto-char (point-min))
2755 (re-search-forward todos-done-string-start nil t)))
2756 (buffer-read-only nil)
2757 item done-item opoint)
2758 ;; Don't add empty comment to done item.
2759 (setq comment (unless (zerop (length comment))
2760 (concat " [" todos-comment-string ": " comment "]")))
2761 (and marked (goto-char (point-min)))
2763 ;; Stop looping when we hit the empty line below the last
2764 ;; todo item (this is eobp if only done items are hidden).
2765 (while (not (looking-at "^$"))
2766 (if (or (not marked) (and marked (todos-marked-item-p)))
2768 (setq item (todos-item-string))
2769 (setq done-item (concat done-item done-prefix item
2770 comment (and marked "\n")))
2771 (setq item-count (1+ item-count))
2772 (when (todos-diary-item-p)
2773 (setq diary-count (1+ diary-count)))
2775 (unless marked (throw 'done nil)))
2776 (todos-forward-item))))
2778 ;; Chop off last newline of done item string.
2779 (setq done-item (substring done-item 0 -1))
2780 (setq todos-categories-with-marks
2781 (assq-delete-all cat todos-categories-with-marks)))
2785 (concat "^" (regexp-quote todos-category-done)) nil t)
2787 (when show-done (setq opoint (point)))
2788 (insert done-item "\n"))
2789 (todos-update-count 'todo (- item-count))
2790 (todos-update-count 'done item-count)
2791 (todos-update-count 'diary (- diary-count))
2792 (todos-update-categories-sexp)
2793 (let ((todos-show-with-done show-done))
2794 (todos-category-select)
2795 ;; When done items are shown, put cursor on first just done item.
2796 (when opoint (goto-char opoint)))))))
2798 (defun todos-edit-done-item-comment (&optional arg)
2799 "Add a comment to this done item or edit an existing comment.
2800 With prefix ARG delete an existing comment."
2802 (when (todos-done-item-p)
2803 (let ((item (todos-item-string))
2805 (end (save-excursion (todos-item-end)))
2806 comment buffer-read-only)
2809 (if (re-search-forward (concat " \\["
2810 (regexp-quote todos-comment-string)
2811 ": \\([^]]+\\)\\]") end t)
2813 (when (todos-y-or-n-p "Delete comment? ")
2814 (delete-region (match-beginning 0) (match-end 0)))
2815 (setq comment (read-string "Edit comment: "
2816 (cons (match-string 1) 1)))
2817 (replace-match comment nil nil nil 1))
2818 (setq comment (read-string "Enter a comment: "))
2819 ;; If user moved point during editing, make sure it moves back.
2822 (insert " [" todos-comment-string ": " comment "]"))))))
2824 (defun todos-item-undone ()
2825 "Restore at least one done item to this category's todo section.
2826 Prompt for the new priority. If there are marked items, undo all
2827 of these, giving the first undone item the new priority and the
2828 rest following directly in sequence; otherwise, undo just the
2831 If the done item has a comment, ask whether to omit the comment
2832 from the restored item. With multiple marked done items with
2833 comments, only ask once, and if affirmed, omit subsequent
2834 comments without asking."
2836 (let* ((cat (todos-current-category))
2837 (marked (assoc cat todos-categories-with-marks))
2838 (pl (if (and marked (> (cdr marked) 1)) "s" "")))
2839 (when (or marked (todos-done-item-p))
2840 (let ((buffer-read-only)
2842 (omark (point-marker))
2846 start end item ov npoint undone)
2847 (and marked (goto-char (point-min)))
2850 (when (or (not marked) (and marked (todos-marked-item-p)))
2851 (if (not (todos-done-item-p))
2852 (user-error "Only done items can be undone")
2855 (setq ov (make-overlay (save-excursion (todos-item-start))
2856 (save-excursion (todos-item-end))))
2857 (overlay-put ov 'face 'todos-search))
2858 ;; Find the end of the date string added upon tagging item as
2860 (setq start (search-forward "] "))
2861 (setq item-count (1+ item-count))
2862 (unless (looking-at (regexp-quote todos-nondiary-start))
2863 (setq diary-count (1+ diary-count)))
2864 (setq end (save-excursion (todos-item-end)))
2865 ;; Ask (once) whether to omit done item's comment. If
2866 ;; affirmed, omit subsequent comments without asking.
2867 (when (re-search-forward
2868 (concat " \\[" (regexp-quote todos-comment-string)
2869 ": [^]]+\\]") end t)
2871 (if (eq first 'first)
2873 (if (eq todos-undo-item-omit-comment 'ask)
2874 (when (todos-y-or-n-p
2875 (concat "Omit comment" pl
2876 " from restored item"
2879 (when todos-undo-item-omit-comment 'omit)))
2881 (when (and (eq first 'first) ov) (delete-overlay ov)))
2882 (when (eq first 'omit)
2883 (setq end (match-beginning 0))))
2884 (setq item (concat item
2885 (buffer-substring-no-properties start end)
2886 (when marked "\n")))
2887 (unless marked (throw 'done nil))))
2888 (todos-forward-item)))
2891 ;; Chop off last newline of multiple items string, since
2892 ;; it will be reinserted on setting priority.
2893 (and marked (setq item (substring item 0 -1)))
2894 (todos-set-item-priority item cat t)
2895 (setq npoint (point))
2897 (when ov (delete-overlay ov))
2904 (concat "^" (regexp-quote todos-category-done)) nil t)
2906 (if (todos-marked-item-p)
2908 (todos-forward-item)))
2909 (setq todos-categories-with-marks
2910 (assq-delete-all cat todos-categories-with-marks)))
2912 (todos-remove-item))
2913 (todos-update-count 'todo item-count)
2914 (todos-update-count 'done (- item-count))
2915 (when diary-count (todos-update-count 'diary diary-count))
2916 (todos-update-categories-sexp)
2917 (let ((todos-show-with-done (> (todos-get-count 'done) 0)))
2918 (todos-category-select))
2919 ;; Put cursor on undone item.
2920 (goto-char npoint)))
2921 (set-marker omark nil)))))
2923 ;; -----------------------------------------------------------------------------
2924 ;;; Done item archives
2925 ;; -----------------------------------------------------------------------------
2927 (defun todos-find-archive (&optional ask)
2928 "Visit the archive of the current Todos category, if it exists.
2929 If the category has no archived items, prompt to visit the
2930 archive anyway. If there is no archive for this file or with
2931 non-nil argument ASK, prompt to visit another archive.
2933 The buffer showing the archive is in Todos Archive mode. The
2934 first visit in a session displays the first category in the
2935 archive, subsequent visits return to the last category
2938 (let* ((cat (todos-current-category))
2939 (count (todos-get-count 'archived cat))
2940 (archive (concat (file-name-sans-extension todos-current-todos-file)
2943 (setq place (cond (ask 'other-archive)
2944 ((file-exists-p archive) 'this-archive)
2945 (t (when (todos-y-or-n-p
2946 (concat "This file has no archive; "
2947 "visit another archive? "))
2949 (when (eq place 'other-archive)
2950 (setq archive (todos-read-file-name "Choose a Todos archive: " t t)))
2951 (when (and (eq place 'this-archive) (zerop count))
2952 (setq place (when (todos-y-or-n-p
2953 (concat "This category has no archived items;"
2954 " visit archive anyway? "))
2957 (set-window-buffer (selected-window)
2958 (set-buffer (find-file-noselect archive)))
2959 (if (member place '(other-archive other-cat))
2960 (setq todos-category-number 1)
2961 (todos-category-number cat))
2962 (todos-category-select))))
2964 (defun todos-choose-archive ()
2965 "Choose an archive and visit it."
2967 (todos-find-archive t))
2969 (defun todos-archive-done-item (&optional all)
2970 "Archive at least one done item in this category.
2972 With prefix argument ALL, prompt whether to archive all done
2973 items in this category and on confirmation archive them.
2974 Otherwise, if there are marked done items (and no marked todo
2975 items), archive all of these; otherwise, archive the done item at
2978 If the archive of this file does not exist, it is created. If
2979 this category does not exist in the archive, it is created."
2981 (when (eq major-mode 'todos-mode)
2982 (if (and all (zerop (todos-get-count 'done)))
2983 (message "No done items in this category")
2985 (let* ((cat (todos-current-category))
2986 (tbuf (current-buffer))
2987 (marked (assoc cat todos-categories-with-marks))
2988 (afile (concat (file-name-sans-extension
2989 todos-current-todos-file) ".toda"))
2990 (archive (if (file-exists-p afile)
2991 (find-file-noselect afile t)
2992 (get-buffer-create afile)))
2993 (item (and (todos-done-item-p)
2994 (concat (todos-item-string) "\n")))
2996 (opoint (unless (todos-done-item-p) (point)))
2997 marked-items beg end all-done
3001 (if (todos-y-or-n-p "Archive all done items in this category? ")
3004 (goto-char (point-min))
3007 (re-search-forward todos-done-string-start
3009 (match-beginning 0))
3010 end (if (re-search-forward
3012 (regexp-quote todos-category-beg))
3016 all-done (buffer-substring-no-properties beg end)
3017 count (todos-get-count 'done))
3018 ;; Restore starting point, unless it was on a done
3019 ;; item, since they will all be deleted.
3020 (when opoint (goto-char opoint))))
3024 (goto-char (point-min))
3026 (when (todos-marked-item-p)
3027 (if (not (todos-done-item-p))
3028 (throw 'end (message "Only done items can be archived"))
3030 (concat marked-items (todos-item-string) "\n"))
3031 (setq count (1+ count))))
3032 (todos-forward-item)))))
3033 (if (not (or marked all item))
3034 (throw 'end (message "Only done items can be archived"))
3035 (with-current-buffer archive
3036 (unless buffer-file-name (erase-buffer))
3037 (let (buffer-read-only)
3039 (goto-char (point-min))
3040 (if (and (re-search-forward
3041 (concat "^" (regexp-quote
3042 (concat todos-category-beg cat)) "$")
3044 (re-search-forward (regexp-quote todos-category-done)
3046 ;; Start of done items section in existing category.
3048 (todos-add-category nil cat)
3049 ;; Start of done items section in new category.
3050 (goto-char (point-max)))
3051 (insert (cond (marked marked-items)
3054 (todos-update-count 'done (if (or marked all) count 1) cat)
3055 (todos-update-categories-sexp)
3056 ;; If archive is new, save to file now (using write-region in
3057 ;; order not to get prompted for file to save to), to let
3058 ;; auto-mode-alist take effect below.
3059 (unless buffer-file-name
3060 (write-region nil nil afile)
3062 (with-current-buffer tbuf
3067 ;; Make sure done items are accessible.
3069 (remove-overlays beg end)
3070 (delete-region beg end)
3071 (todos-update-count 'done (- count))
3072 (todos-update-count 'archived count))))
3074 ;; If we're archiving all done items, can't
3075 ;; first archive item point was on, since
3076 ;; that will short-circuit the rest.
3077 (and item (not all)))
3078 (and marked (goto-char (point-min)))
3081 (if (or (and marked (todos-marked-item-p)) item)
3084 (todos-update-count 'done -1)
3085 (todos-update-count 'archived 1)
3086 ;; Don't leave point below last item.
3087 (and item (bolp) (eolp) (< (point-min) (point-max))
3088 (todos-backward-item))
3090 (throw 'done (setq item nil))))
3091 (todos-forward-item))))))
3093 (setq todos-categories-with-marks
3094 (assq-delete-all cat todos-categories-with-marks)))
3095 (todos-update-categories-sexp)
3096 (todos-prefix-overlays)))
3098 (todos-category-number cat)
3099 (todos-category-select)
3100 (split-window-below)
3101 (set-window-buffer (selected-window) tbuf)
3102 ;; Make todo file current to select category.
3103 (find-file (buffer-file-name tbuf))
3104 ;; Make sure done item separator is hidden (if done items
3105 ;; were initially visible).
3106 (let (todos-show-with-done) (todos-category-select)))))))
3108 (defun todos-unarchive-items ()
3109 "Unarchive at least one item in this archive category.
3110 If there are marked items, unarchive all of these; otherwise,
3111 unarchive the item at point.
3113 Unarchived items are restored as done items to the corresponding
3114 category in the Todos file, inserted at the top of done items
3115 section. If all items in the archive category have been
3116 restored, the category is deleted from the archive. If this was
3117 the only category in the archive, the archive file is deleted."
3119 (when (eq major-mode 'todos-archive-mode)
3120 (let* ((cat (todos-current-category))
3121 (tbuf (find-file-noselect
3122 (concat (file-name-sans-extension todos-current-todos-file)
3124 (marked (assoc cat todos-categories-with-marks))
3125 (item (concat (todos-item-string) "\n"))
3131 (goto-char (point-min))
3133 (when (todos-marked-item-p)
3134 (setq marked-items (concat marked-items (todos-item-string) "\n"))
3135 (setq marked-count (1+ marked-count)))
3136 (todos-forward-item))))
3137 ;; Restore items to top of category's done section and update counts.
3138 (with-current-buffer tbuf
3139 (let (buffer-read-only newcat)
3141 (goto-char (point-min))
3142 ;; Find the corresponding todo category, or if there isn't
3144 (unless (re-search-forward
3145 (concat "^" (regexp-quote (concat todos-category-beg cat))
3147 (todos-add-category nil cat)
3149 ;; Go to top of category's done section.
3151 (concat "^" (regexp-quote todos-category-done)) nil t)
3154 (insert marked-items)
3155 (todos-update-count 'done marked-count cat)
3156 (unless newcat ; Newly added category has no archive.
3157 (todos-update-count 'archived (- marked-count) cat)))
3160 (todos-update-count 'done 1 cat)
3161 (unless newcat ; Newly added category has no archive.
3162 (todos-update-count 'archived -1 cat))))
3163 (todos-update-categories-sexp)))
3164 ;; Delete restored items from archive.
3167 (goto-char (point-min)))
3170 (if (or (todos-marked-item-p) item)
3174 (throw 'done (setq item nil))))
3175 (todos-forward-item))))
3176 (todos-update-count 'done (if marked (- marked-count) -1) cat)
3177 ;; If that was the last category in the archive, delete the whole file.
3178 (if (= (length todos-categories) 1)
3180 (delete-file todos-current-todos-file)
3181 ;; Kill the archive buffer silently.
3182 (set-buffer-modified-p nil)
3184 ;; Otherwise, if the archive category is now empty, delete it.
3185 (when (eq (point-min) (point-max))
3187 (let ((beg (re-search-backward
3188 (concat "^" (regexp-quote todos-category-beg) cat "$")
3190 (end (if (re-search-forward
3191 (concat "^" (regexp-quote todos-category-beg))
3195 (remove-overlays beg end)
3196 (delete-region beg end)
3197 (setq todos-categories (delete (assoc cat todos-categories)
3199 (todos-update-categories-sexp))))
3200 ;; Visit category in Todos file and show restored done items.
3201 (let ((tfile (buffer-file-name tbuf))
3202 (todos-show-with-done t))
3203 (set-window-buffer (selected-window)
3204 (set-buffer (find-file-noselect tfile)))
3205 (todos-category-number cat)
3206 (todos-category-select)
3207 (message "Items unarchived.")))))
3209 (defun todos-jump-to-archive-category (&optional file)
3210 "Prompt for a category in a Todos archive and jump to it.
3211 With prefix argument FILE, prompt for an archive and choose (with
3212 TAB completion) a category in it to jump to; otherwise, choose
3213 and jump to any category in the current archive."
3215 (todos-jump-to-category file 'archive))
3217 ;; -----------------------------------------------------------------------------
3218 ;;; Displaying and sorting tables of categories
3219 ;; -----------------------------------------------------------------------------
3221 (defcustom todos-categories-category-label "Category"
3222 "Category button label in Todos Categories mode."
3224 :group 'todos-categories)
3226 (defcustom todos-categories-todo-label "Todo"
3227 "Todo button label in Todos Categories mode."
3229 :group 'todos-categories)
3231 (defcustom todos-categories-diary-label "Diary"
3232 "Diary button label in Todos Categories mode."
3234 :group 'todos-categories)
3236 (defcustom todos-categories-done-label "Done"
3237 "Done button label in Todos Categories mode."
3239 :group 'todos-categories)
3241 (defcustom todos-categories-archived-label "Archived"
3242 "Archived button label in Todos Categories mode."
3244 :group 'todos-categories)
3246 (defcustom todos-categories-totals-label "Totals"
3247 "String to label total item counts in Todos Categories mode."
3249 :group 'todos-categories)
3251 (defcustom todos-categories-number-separator " | "
3252 "String between number and category in Todos Categories mode.
3253 This separates the number from the category name in the default
3254 categories display according to priority."
3256 :group 'todos-categories)
3258 (defcustom todos-categories-align 'center
3259 "Alignment of category names in Todos Categories mode."
3260 :type '(radio (const left) (const center) (const right))
3261 :group 'todos-categories)
3263 (defun todos-show-categories-table ()
3264 "Display a table of the current file's categories and item counts.
3266 In the initial display the categories are numbered, indicating
3267 their current order for navigating by \\[todos-forward-category]
3268 and \\[todos-backward-category]. You can persistantly change the
3269 order of the category at point by typing
3270 \\[todos-set-category-number], \\[todos-raise-category] or
3271 \\[todos-lower-category].
3273 The labels above the category names and item counts are buttons,
3274 and clicking these changes the display: sorted by category name
3275 or by the respective item counts (alternately descending or
3276 ascending). In these displays the categories are not numbered
3277 and \\[todos-set-category-number], \\[todos-raise-category] and
3278 \\[todos-lower-category] are disabled. (Programmatically, the
3279 sorting is triggered by passing a non-nil SORTKEY argument.)
3281 In addition, the lines with the category names and item counts
3282 are buttonized, and pressing one of these button jumps to the
3283 category in Todos mode (or Todos Archive mode, for categories
3284 containing only archived items, provided user option
3285 `todos-skip-archived-categories' is non-nil. These categories
3286 are shown in `todos-archived-only' face."
3288 (todos-display-categories)
3290 (todos-update-categories-display sortkey)))
3292 (defun todos-next-button (n)
3293 "Move point to the Nth next button in the table of categories."
3295 (forward-button n 'wrap 'display-message)
3296 (and (bolp) (button-at (point))
3297 ;; Align with beginning of category label.
3298 (forward-char (+ 4 (length todos-categories-number-separator)))))
3300 (defun todos-previous-button (n)
3301 "Move point to the Nth previous button in the table of categories."
3303 (backward-button n 'wrap 'display-message)
3304 (and (bolp) (button-at (point))
3305 ;; Align with beginning of category label.
3306 (forward-char (+ 4 (length todos-categories-number-separator)))))
3308 (defun todos-set-category-number (&optional arg)
3309 "Change number of category at point in the table of categories.
3311 With ARG nil, prompt for the new number. Alternatively, the
3312 enter the new number with numerical prefix ARG. Otherwise, if
3313 ARG is either of the symbols `raise' or `lower', raise or lower
3314 the category line in the table by one, respectively, thereby
3315 decreasing or increasing its number."
3317 (let ((curnum (save-excursion
3318 ;; Get the number representing the priority of the category
3319 ;; on the current line.
3320 (forward-line 0) (skip-chars-forward " ") (number-at-point))))
3321 (when curnum ; Do nothing if we're not on a category line.
3322 (let* ((maxnum (length todos-categories))
3323 (prompt (format "Set category priority (1-%d): " maxnum))
3324 (col (current-column))
3325 (buffer-read-only nil)
3326 (priority (cond ((and (eq arg 'raise) (> curnum 1))
3328 ((and (eq arg 'lower) (< curnum maxnum))
3331 (while (not priority)
3332 (setq candidate (or arg (read-number prompt)))
3335 (cond ((or (< candidate 1) (> candidate maxnum))
3336 (format "Priority must be an integer between 1 and %d: "
3338 ((= candidate curnum)
3339 "Choose a different priority than the current one: ")))
3340 (unless prompt (setq priority candidate)))
3341 (let* ((lower (< curnum priority)) ; Priority is being lowered.
3342 (head (butlast todos-categories
3343 (apply (if lower 'identity '1+)
3344 (list (- maxnum priority)))))
3345 (tail (nthcdr (apply (if lower 'identity '1-) (list priority))
3347 ;; Category's name and items counts list.
3348 (catcons (nth (1- curnum) todos-categories))
3349 (todos-categories (nconc head (list catcons) tail))
3351 (when lower (setq todos-categories (nreverse todos-categories)))
3352 (setq todos-categories (delete-dups todos-categories))
3353 (when lower (setq todos-categories (nreverse todos-categories)))
3354 (setq newcats todos-categories)
3356 (with-current-buffer (find-buffer-visiting todos-current-todos-file)
3357 (setq todos-categories newcats)
3358 (todos-update-categories-sexp))
3359 (todos-show-categories-table)
3360 (forward-line (1+ priority))
3361 (forward-char col))))))
3363 (defun todos-raise-category ()
3364 "Raise priority of category at point in Todos Categories buffer."
3366 (todos-set-category-number 'raise))
3368 (defun todos-lower-category ()
3369 "Lower priority of category at point in Todos Categories buffer."
3371 (todos-set-category-number 'lower))
3373 (defun todos-sort-categories-alphabetically-or-numerically ()
3374 "Sort table of categories alphabetically or numerically."
3377 (goto-char (point-min))
3379 (if (member 'alpha todos-descending-counts)
3381 (todos-update-categories-display nil)
3382 (setq todos-descending-counts
3383 (delete 'alpha todos-descending-counts)))
3384 (todos-update-categories-display 'alpha))))
3386 (defun todos-sort-categories-by-todo ()
3387 "Sort table of categories by number of todo items."
3390 (goto-char (point-min))
3392 (todos-update-categories-display 'todo)))
3394 (defun todos-sort-categories-by-diary ()
3395 "Sort table of categories by number of diary items."
3398 (goto-char (point-min))
3400 (todos-update-categories-display 'diary)))
3402 (defun todos-sort-categories-by-done ()
3403 "Sort table of categories by number of non-archived done items."
3406 (goto-char (point-min))
3408 (todos-update-categories-display 'done)))
3410 (defun todos-sort-categories-by-archived ()
3411 "Sort table of categories by number of archived items."
3414 (goto-char (point-min))
3416 (todos-update-categories-display 'archived)))
3418 (defvar todos-categories-buffer "*Todos Categories*"
3419 "Name of buffer in Todos Categories mode.")
3421 (defun todos-longest-category-name-length (categories)
3422 "Return the length of the longest name in list CATEGORIES."
3424 (dolist (c categories longest)
3425 (setq longest (max longest (length c))))))
3427 (defun todos-adjusted-category-label-length ()
3428 "Return adjusted length of category label button.
3429 The adjustment ensures proper tabular alignment in Todos
3431 (let* ((categories (mapcar 'car todos-categories))
3432 (longest (todos-longest-category-name-length categories))
3433 (catlablen (length todos-categories-category-label))
3434 (lc-diff (- longest catlablen)))
3435 (if (and (natnump lc-diff) (cl-oddp lc-diff))
3437 (max longest catlablen))))
3439 (defun todos-padded-string (str)
3440 "Return category name or label string STR padded with spaces.
3441 The placement of the padding is determined by the value of user
3442 option `todos-categories-align'."
3443 (let* ((len (todos-adjusted-category-label-length))
3444 (strlen (length str))
3445 (strlen-odd (eq (logand strlen 1) 1))
3446 (padding (max 0 (/ (- len strlen) 2)))
3447 (padding-left (cond ((eq todos-categories-align 'left) 0)
3448 ((eq todos-categories-align 'center) padding)
3449 ((eq todos-categories-align 'right)
3450 (if strlen-odd (1+ (* padding 2)) (* padding 2)))))
3451 (padding-right (cond ((eq todos-categories-align 'left)
3452 (if strlen-odd (1+ (* padding 2)) (* padding 2)))
3453 ((eq todos-categories-align 'center)
3454 (if strlen-odd (1+ padding) padding))
3455 ((eq todos-categories-align 'right) 0))))
3456 (concat (make-string padding-left 32) str (make-string padding-right 32))))
3458 (defvar todos-descending-counts nil
3459 "List of keys for category counts sorted in descending order.")
3461 (defun todos-sort (list &optional key)
3462 "Return a copy of LIST, possibly sorted according to KEY."
3463 (let* ((l (copy-sequence list))
3464 (fn (if (eq key 'alpha)
3465 (lambda (x) (upcase x)) ; Alphabetize case insensitively.
3466 (lambda (x) (todos-get-count key x))))
3467 ;; Keep track of whether the last sort by key was descending or
3469 (descending (member key todos-descending-counts))
3470 (cmp (if (eq key 'alpha)
3472 (if descending '< '>)))
3473 (pred (lambda (s1 s2) (let ((t1 (funcall fn (car s1)))
3474 (t2 (funcall fn (car s2))))
3475 (funcall cmp t1 t2)))))
3477 (setq l (sort l pred))
3478 ;; Switch between descending and ascending sort order.
3480 (setq todos-descending-counts
3481 (delete key todos-descending-counts))
3482 (push key todos-descending-counts)))
3485 (defun todos-display-sorted (type)
3486 "Keep point on the TYPE count sorting button just clicked."
3487 (let ((opoint (point)))
3488 (todos-update-categories-display type)
3489 (goto-char opoint)))
3491 (defun todos-label-to-key (label)
3492 "Return symbol for sort key associated with LABEL."
3494 (cond ((string= label todos-categories-category-label)
3496 ((string= label todos-categories-todo-label)
3498 ((string= label todos-categories-diary-label)
3500 ((string= label todos-categories-done-label)
3502 ((string= label todos-categories-archived-label)
3503 (setq key 'archived)))
3506 (defun todos-insert-sort-button (label)
3507 "Insert button for displaying categories sorted by item counts.
3508 LABEL determines which type of count is sorted."
3509 (let* ((str (if (string= label todos-categories-category-label)
3510 (todos-padded-string label)
3513 (end (+ beg (length str)))
3515 (insert-button str 'face nil
3518 (let ((key (todos-label-to-key ,label)))
3519 (if (and (member key todos-descending-counts)
3522 ;; If display is alphabetical, switch back to
3523 ;; category priority order.
3524 (todos-display-sorted nil)
3525 (setq todos-descending-counts
3526 (delete key todos-descending-counts)))
3527 (todos-display-sorted key)))))
3528 (setq ov (make-overlay beg end))
3529 (overlay-put ov 'face 'todos-button)))
3531 (defun todos-total-item-counts ()
3532 "Return a list of total item counts for the current file."
3533 (mapcar (lambda (i) (apply '+ (mapcar (lambda (l) (aref l i))
3534 (mapcar 'cdr todos-categories))))
3537 (defvar todos-categories-category-number 0
3538 "Variable for numbering categories in Todos Categories mode.")
3540 (defun todos-insert-category-line (cat &optional nonum)
3541 "Insert button with category CAT's name and item counts.
3542 With non-nil argument NONUM show only these; otherwise, insert a
3543 number in front of the button indicating the category's priority.
3544 The number and the category name are separated by the string
3545 which is the value of the user option
3546 `todos-categories-number-separator'."
3547 (let ((archive (member todos-current-todos-file todos-archives))
3548 (num todos-categories-category-number)
3549 (str (todos-padded-string cat))
3551 (setq num (1+ num) todos-categories-category-number num)
3554 (make-string (+ 4 (length todos-categories-number-separator))
3556 (format " %3d%s" num todos-categories-number-separator))
3558 (mapconcat (lambda (elt)
3560 (make-string (1+ (/ (length (car elt)) 2)) 32) ; label
3561 (format "%3d" (todos-get-count (cdr elt) cat)) ; count
3562 ;; Add an extra space if label length is odd.
3563 (when (cl-oddp (length (car elt))) " ")))
3565 (list (cons todos-categories-done-label 'done))
3566 (list (cons todos-categories-todo-label 'todo)
3567 (cons todos-categories-diary-label 'diary)
3568 (cons todos-categories-done-label 'done)
3569 (cons todos-categories-archived-label
3572 " ") ; Make highlighting on last column look better.
3573 'face (if (and todos-skip-archived-categories
3574 (zerop (todos-get-count 'todo cat))
3575 (zerop (todos-get-count 'done cat))
3576 (not (zerop (todos-get-count 'archived cat))))
3577 'todos-archived-only
3579 'action `(lambda (button) (let ((buf (current-buffer)))
3580 (todos-jump-to-category nil ,cat)
3581 (kill-buffer buf))))
3582 ;; Highlight the sorted count column.
3583 (let* ((beg (+ opoint 7 (length str)))
3585 (cond ((eq nonum 'todo)
3586 (setq beg (+ beg 1 (/ (length todos-categories-todo-label) 2))))
3588 (setq beg (+ beg 1 (length todos-categories-todo-label)
3589 2 (/ (length todos-categories-diary-label) 2))))
3591 (setq beg (+ beg 1 (length todos-categories-todo-label)
3592 2 (length todos-categories-diary-label)
3593 2 (/ (length todos-categories-done-label) 2))))
3594 ((eq nonum 'archived)
3595 (setq beg (+ beg 1 (length todos-categories-todo-label)
3596 2 (length todos-categories-diary-label)
3597 2 (length todos-categories-done-label)
3598 2 (/ (length todos-categories-archived-label) 2)))))
3599 (unless (= beg (+ opoint 7 (length str))) ; Don't highlight categories.
3600 (setq end (+ beg 4))
3601 (setq ovl (make-overlay beg end))
3602 (overlay-put ovl 'face 'todos-sorted-column)))
3605 (defun todos-display-categories ()
3606 "Prepare buffer for displaying table of categories and item counts."
3607 (unless (eq major-mode 'todos-categories-mode)
3608 (setq todos-global-current-todos-file
3609 (or todos-current-todos-file
3610 (todos-absolute-file-name todos-default-todos-file)))
3611 (set-window-buffer (selected-window)
3612 (set-buffer (get-buffer-create todos-categories-buffer)))
3613 (kill-all-local-variables)
3614 (todos-categories-mode)
3615 (let ((archive (member todos-current-todos-file todos-archives))
3618 (insert (format (concat "Category counts for Todos "
3619 (if archive "archive" "file")
3621 (todos-short-file-name todos-current-todos-file)))
3623 ;; Make space for the column of category numbers.
3624 (insert (make-string (+ 4 (length todos-categories-number-separator)) 32))
3625 ;; Add the category and item count buttons (if this is the list of
3626 ;; categories in an archive, show only done item counts).
3627 (todos-insert-sort-button todos-categories-category-label)
3630 (insert (make-string 3 32))
3631 (todos-insert-sort-button todos-categories-done-label))
3632 (insert (make-string 3 32))
3633 (todos-insert-sort-button todos-categories-todo-label)
3634 (insert (make-string 2 32))
3635 (todos-insert-sort-button todos-categories-diary-label)
3636 (insert (make-string 2 32))
3637 (todos-insert-sort-button todos-categories-done-label)
3638 (insert (make-string 2 32))
3639 (todos-insert-sort-button todos-categories-archived-label))
3642 (defun todos-update-categories-display (sortkey)
3643 "Populate table of categories and sort by SORTKEY."
3644 (let* ((cats0 todos-categories)
3645 (cats (todos-sort cats0 sortkey))
3646 (archive (member todos-current-todos-file todos-archives))
3647 (todos-categories-category-number 0)
3648 ;; Find start of Category button if we just entered Todos Categories
3650 (pt (if (eq (point) (point-max))
3653 (goto-char (next-single-char-property-change
3654 (point) 'face nil (line-end-position))))))
3657 (delete-region (point) (point-max))
3658 ;; Fill in the table with buttonized lines, each showing a category and
3660 (mapc (lambda (cat) (todos-insert-category-line cat sortkey))
3663 ;; Add a line showing item count totals.
3664 (insert (make-string (+ 4 (length todos-categories-number-separator)) 32)
3665 (todos-padded-string todos-categories-totals-label)
3669 (make-string (1+ (/ (length (car elt)) 2)) 32)
3670 (format "%3d" (nth (cdr elt) (todos-total-item-counts)))
3671 ;; Add an extra space if label length is odd.
3672 (when (cl-oddp (length (car elt))) " ")))
3674 (list (cons todos-categories-done-label 2))
3675 (list (cons todos-categories-todo-label 0)
3676 (cons todos-categories-diary-label 1)
3677 (cons todos-categories-done-label 2)
3678 (cons todos-categories-archived-label 3)))
3680 ;; Put cursor on Category button initially.
3681 (if pt (goto-char pt))
3682 (setq buffer-read-only t)))
3684 ;; -----------------------------------------------------------------------------
3685 ;;; Searching and item filtering
3686 ;; -----------------------------------------------------------------------------
3688 (defun todos-search ()
3689 "Search for a regular expression in this Todos file.
3690 The search runs through the whole file and encompasses all and
3691 only todo and done items; it excludes category names. Multiple
3692 matches are shown sequentially, highlighted in `todos-search'
3695 (let ((regex (read-from-minibuffer "Enter a search string (regexp): "))
3697 matches match cat in-done ov mlen msg)
3699 (goto-char (point-min))
3701 (setq match (re-search-forward regex nil t))
3702 (goto-char (line-beginning-position))
3703 (unless (or (equal (point) 1)
3704 (looking-at (concat "^" (regexp-quote todos-category-beg))))
3705 (if match (push match matches)))
3707 (setq matches (reverse matches))
3711 (setq match (pop matches))
3714 (when (looking-at todos-done-string-start)
3716 (re-search-backward (concat "^" (regexp-quote todos-category-beg)
3717 "\\(.*\\)\n") nil t)
3718 (setq cat (match-string-no-properties 1))
3719 (todos-category-number cat)
3720 (todos-category-select)
3722 (unless todos-show-with-done (todos-toggle-view-done-items)))
3724 (setq ov (make-overlay (- (point) (length regex)) (point)))
3725 (overlay-put ov 'face 'todos-search)
3727 (setq mlen (length matches))
3730 (format "There are %d more matches; go to next match? "
3732 "There is one more match; go to it? "))
3734 (throw 'stop (setq msg (if (> mlen 1)
3735 (format "There are %d more matches."
3737 "There is one more match."))))))
3738 (setq msg "There are no more matches."))
3739 (todos-category-select)
3741 (message "No match for \"%s\"" regex))
3743 (if (todos-y-or-n-p (concat msg "\nUnhighlight matches? "))
3744 (todos-clear-matches)
3745 (message "You can unhighlight the matches later by typing %s"
3746 (key-description (car (where-is-internal
3747 'todos-clear-matches))))))))
3749 (defun todos-clear-matches ()
3750 "Remove highlighting on matches found by todos-search."
3752 (remove-overlays 1 (1+ (buffer-size)) 'face 'todos-search))
3754 (defcustom todos-top-priorities-overrides nil
3755 "List of rules specifying number of top priority items to show.
3756 These rules override `todos-top-priorities' on invocations of
3757 `\\[todos-filter-top-priorities]' and
3758 `\\[todos-filter-top-priorities-multifile]'. Each rule is a list
3759 of the form (FILE NUM ALIST), where FILE is a member of
3760 `todos-files', NUM is a number specifying the default number of
3761 top priority items for each category in that file, and ALIST,
3762 when non-nil, consists of conses of a category name in FILE and a
3763 number specifying the default number of top priority items in
3764 that category, which overrides NUM.
3766 This variable should be set interactively by
3767 `\\[todos-set-top-priorities-in-file]' or
3768 `\\[todos-set-top-priorities-in-category]'."
3770 :group 'todos-filtered)
3772 (defcustom todos-top-priorities 1
3773 "Default number of top priorities shown by `todos-filter-top-priorities'."
3775 :group 'todos-filtered)
3777 (defcustom todos-filter-files nil
3778 "List of default files for multifile item filtering."
3779 :type `(set ,@(mapcar (lambda (f) (list 'const f))
3780 (mapcar 'todos-short-file-name
3781 (funcall todos-files-function))))
3782 :group 'todos-filtered)
3784 (defcustom todos-filter-done-items nil
3785 "Non-nil to include done items when processing regexp filters.
3786 Done items from corresponding archive files are also included."
3788 :group 'todos-filtered)
3790 (defun todos-set-top-priorities-in-file ()
3791 "Set number of top priorities for this file.
3792 See `todos-set-top-priorities' for more details."
3794 (todos-set-top-priorities))
3796 (defun todos-set-top-priorities-in-category ()
3797 "Set number of top priorities for this category.
3798 See `todos-set-top-priorities' for more details."
3800 (todos-set-top-priorities t))
3802 (defun todos-filter-top-priorities (&optional arg)
3803 "Display a list of top priority items from different categories.
3804 The categories can be any of those in the current Todos file.
3806 With numerical prefix ARG show at most ARG top priority items
3807 from each category. With `C-u' as prefix argument show the
3808 numbers of top priority items specified by category in
3809 `todos-top-priorities-overrides', if this has an entry for the file(s);
3810 otherwise show `todos-top-priorities' items per category in the
3811 file(s). With no prefix argument, if a top priorities file for
3812 the current Todos file has previously been saved (see
3813 `todos-save-filtered-items-buffer'), visit this file; if there is
3814 no such file, build the list as with prefix argument `C-u'.
3816 The prefix ARG regulates how many top priorities from
3817 each category to show, as described above."
3819 (todos-filter-items 'top arg))
3821 (defun todos-filter-top-priorities-multifile (&optional arg)
3822 "Display a list of top priority items from different categories.
3823 The categories are a subset of the categories in the files listed
3824 in `todos-filter-files', or if this nil, in the files chosen from
3825 a file selection dialog that pops up in this case.
3827 With numerical prefix ARG show at most ARG top priority items
3828 from each category in each file. With `C-u' as prefix argument
3829 show the numbers of top priority items specified in
3830 `todos-top-priorities-overrides', if this is non-nil; otherwise show
3831 `todos-top-priorities' items per category. With no prefix
3832 argument, if a top priorities file for the chosen Todos files
3833 exists (see `todos-save-filtered-items-buffer'), visit this file;
3834 if there is no such file, do the same as with prefix argument
3837 (todos-filter-items 'top arg t))
3839 (defun todos-filter-diary-items (&optional arg)
3840 "Display a list of todo diary items from different categories.
3841 The categories can be any of those in the current Todos file.
3843 Called with no prefix ARG, if a diary items file for the current
3844 Todos file has previously been saved (see
3845 `todos-save-filtered-items-buffer'), visit this file; if there is
3846 no such file, build the list of diary items. Called with a
3847 prefix argument, build the list even if there is a saved file of
3850 (todos-filter-items 'diary arg))
3852 (defun todos-filter-diary-items-multifile (&optional arg)
3853 "Display a list of todo diary items from different categories.
3854 The categories are a subset of the categories in the files listed
3855 in `todos-filter-files', or if this nil, in the files chosen from
3856 a file selection dialog that pops up in this case.
3858 Called with no prefix ARG, if a diary items file for the chosen
3859 Todos files has previously been saved (see
3860 `todos-save-filtered-items-buffer'), visit this file; if there is
3861 no such file, build the list of diary items. Called with a
3862 prefix argument, build the list even if there is a saved file of
3865 (todos-filter-items 'diary arg t))
3867 (defun todos-filter-regexp-items (&optional arg)
3868 "Prompt for a regular expression and display items that match it.
3869 The matches can be from any categories in the current Todos file
3870 and with non-nil option `todos-filter-done-items', can include
3871 not only todo items but also done items, including those in
3874 Called with no prefix ARG, if a regexp items file for the current
3875 Todos file has previously been saved (see
3876 `todos-save-filtered-items-buffer'), visit this file; if there is
3877 no such file, build the list of regexp items. Called with a
3878 prefix argument, build the list even if there is a saved file of
3881 (todos-filter-items 'regexp arg))
3883 (defun todos-filter-regexp-items-multifile (&optional arg)
3884 "Prompt for a regular expression and display items that match it.
3885 The matches can be from any categories in the files listed in
3886 `todos-filter-files', or if this nil, in the files chosen from a
3887 file selection dialog that pops up in this case. With non-nil
3888 option `todos-filter-done-items', the matches can include not
3889 only todo items but also done items, including those in Archive
3892 Called with no prefix ARG, if a regexp items file for the current
3893 Todos file has previously been saved (see
3894 `todos-save-filtered-items-buffer'), visit this file; if there is
3895 no such file, build the list of regexp items. Called with a
3896 prefix argument, build the list even if there is a saved file of
3899 (todos-filter-items 'regexp arg t))
3901 (defun todos-find-filtered-items-file ()
3902 "Choose a filtered items file and visit it."
3904 (let ((files (directory-files todos-directory t "\.tod[rty]$" t))
3907 (let ((type (cond ((equal (file-name-extension f) "todr") "regexp")
3908 ((equal (file-name-extension f) "todt") "top")
3909 ((equal (file-name-extension f) "tody") "diary"))))
3910 (push (cons (concat (todos-short-file-name f) " (" type ")") f)
3912 (setq file (completing-read "Choose a filtered items file: "
3913 falist nil t nil nil (car falist)))
3914 (setq file (cdr (assoc-string file falist)))
3917 (defun todos-go-to-source-item ()
3918 "Display the file and category of the filtered item at point."
3920 (let* ((str (todos-item-string))
3921 (buf (current-buffer))
3922 (res (todos-find-item str))
3927 (message "Category %s does not contain this item." cat)
3929 (set-window-buffer (selected-window)
3930 (set-buffer (find-buffer-visiting file)))
3931 (setq todos-current-todos-file file)
3932 (setq todos-category-number (todos-category-number cat))
3933 (let ((todos-show-with-done (if (or todos-filter-done-items
3934 (eq (cdr found) 'done))
3936 todos-show-with-done)))
3937 (todos-category-select))
3938 (goto-char (car found)))))
3940 (defvar todos-multiple-filter-files nil
3941 "List of files selected from `todos-multiple-filter-files' widget.")
3943 (defvar todos-multiple-filter-files-widget nil
3944 "Variable holding widget created by `todos-multiple-filter-files'.")
3946 (defun todos-multiple-filter-files ()
3947 "Pop to a buffer with a widget for choosing multiple filter files."
3950 (require 'wid-edit))
3951 (with-current-buffer (get-buffer-create "*Todos Filter Files*")
3952 (pop-to-buffer (current-buffer))
3954 (kill-all-local-variables)
3955 (widget-insert "Select files for generating the top priorities list.\n\n")
3956 (setq todos-multiple-filter-files-widget
3958 `(set ,@(mapcar (lambda (x) (list 'const x))
3959 (mapcar 'todos-short-file-name
3960 (funcall todos-files-function))))))
3961 (widget-insert "\n")
3962 (widget-create 'push-button
3963 :notify (lambda (widget &rest ignore)
3964 (setq todos-multiple-filter-files 'quit)
3966 (exit-recursive-edit))
3969 (widget-create 'push-button
3970 :notify (lambda (&rest ignore)
3971 (setq todos-multiple-filter-files
3974 (concat todos-directory
3977 todos-multiple-filter-files-widget)))
3979 (exit-recursive-edit))
3981 (use-local-map widget-keymap)
3983 (message "Click \"Apply\" after selecting files.")
3986 (defconst todos-filtered-items-buffer "Todos filtered items"
3987 "Initial name of buffer in Todos Filter Items mode.")
3989 (defconst todos-top-priorities-buffer "Todos top priorities"
3990 "Buffer type string for `todos-filter-items'.")
3992 (defconst todos-diary-items-buffer "Todos diary items"
3993 "Buffer type string for `todos-filter-items'.")
3995 (defconst todos-regexp-items-buffer "Todos regexp items"
3996 "Buffer type string for `todos-filter-items'.")
3998 (defun todos-filter-items (filter &optional new multifile)
3999 "Display a cross-categorial list of items filtered by FILTER.
4000 The values of FILTER can be `top' for top priority items, a cons
4001 of `top' and a number passed by the caller, `diary' for diary
4002 items, or `regexp' for items matching a regular expresion entered
4003 by the user. The items can be from any categories in the current
4004 todo file or, with non-nil MULTIFILE, from several files. If NEW
4005 is nil, visit an appropriate file containing the list of filtered
4006 items; if there is no such file, or with non-nil NEW, build the
4007 list and display it.
4009 See the document strings of the commands
4010 `todos-filter-top-priorities', `todos-filter-diary-items',
4011 `todos-filter-regexp-items', and those of the corresponding
4012 multifile commands for further details."
4013 (let* ((top (eq filter 'top))
4014 (diary (eq filter 'diary))
4015 (regexp (eq filter 'regexp))
4016 (buf (cond (top todos-top-priorities-buffer)
4017 (diary todos-diary-items-buffer)
4018 (regexp todos-regexp-items-buffer)))
4019 (flist (if multifile
4020 (or todos-filter-files
4021 (progn (todos-multiple-filter-files)
4022 todos-multiple-filter-files))
4023 (list todos-current-todos-file)))
4024 (multi (> (length flist) 1))
4025 (fname (if (equal flist 'quit)
4026 ;; Pressed `cancel' in t-m-f-f file selection dialog.
4028 (concat todos-directory
4029 (mapconcat 'todos-short-file-name flist "-")
4032 (regexp ".todr")))))
4033 (rxfiles (when regexp
4034 (directory-files todos-directory t ".*\\.todr$" t)))
4035 (file-exists (or (file-exists-p fname) rxfiles)))
4036 (cond ((and top new (natnump new))
4037 (todos-filter-items-1 (cons 'top new) flist))
4038 ((and (not new) file-exists)
4039 (when (and rxfiles (> (length rxfiles) 1))
4040 (let ((rxf (mapcar 'todos-short-file-name rxfiles)))
4041 (setq fname (todos-absolute-file-name
4042 (completing-read "Choose a regexp items file: "
4045 (todos-prefix-overlays)
4046 (todos-check-filtered-items-file))
4048 (todos-filter-items-1 filter flist)))
4049 (setq fname (replace-regexp-in-string "-" ", "
4050 (todos-short-file-name fname)))
4051 (rename-buffer (format (concat "%s for file" (if multi "s" "")
4052 " \"%s\"") buf fname))))
4054 (defun todos-filter-items-1 (filter file-list)
4055 "Build a list of items by applying FILTER to FILE-LIST.
4056 Internal subroutine called by `todos-filter-items', which passes
4057 the values of FILTER and FILE-LIST."
4058 (let ((num (if (consp filter) (cdr filter) todos-top-priorities))
4059 (buf (get-buffer-create todos-filtered-items-buffer))
4060 (multifile (> (length file-list) 1))
4061 regexp fname bufstr cat beg end done)
4062 (if (null file-list)
4063 (user-error "No files have been chosen for filtering")
4064 (with-current-buffer buf
4066 (kill-all-local-variables)
4067 (todos-filtered-items-mode))
4068 (when (eq filter 'regexp)
4069 (setq regexp (read-string "Enter a regular expression: ")))
4070 (save-current-buffer
4071 (dolist (f file-list)
4072 ;; Before inserting file contents into temp buffer, save a modified
4073 ;; buffer visiting it.
4074 (let ((bf (find-buffer-visiting f)))
4075 (when (buffer-modified-p bf)
4076 (with-current-buffer bf (save-buffer))))
4077 (setq fname (todos-short-file-name f))
4079 (when (and todos-filter-done-items (eq filter 'regexp))
4080 ;; If there is a corresponding archive file for the
4081 ;; Todos file, insert it first and add identifiers for
4082 ;; todos-go-to-source-item.
4083 (let ((arch (concat (file-name-sans-extension f) ".toda")))
4084 (when (file-exists-p arch)
4085 (insert-file-contents arch)
4086 ;; Delete Todos archive file categories sexp.
4087 (delete-region (line-beginning-position)
4088 (1+ (line-end-position)))
4091 (when (re-search-forward
4092 (concat (if todos-filter-done-items
4093 (concat "\\(?:" todos-done-string-start
4094 "\\|" todos-date-string-start
4096 todos-date-string-start)
4097 todos-date-pattern "\\(?: "
4098 diary-time-regexp "\\)?"
4099 (if todos-filter-done-items
4101 (regexp-quote todos-nondiary-end)) "?")
4103 (insert "(archive) "))
4105 (insert-file-contents f)
4106 ;; Delete Todos file categories sexp.
4107 (delete-region (line-beginning-position) (1+ (line-end-position)))
4109 ;; Unless the number of top priorities to show was
4110 ;; passed by the caller, the file-wide value from
4111 ;; `todos-top-priorities-overrides', if non-nil, overrides
4112 ;; `todos-top-priorities'.
4113 (unless (consp filter)
4114 (setq fnum (or (nth 1 (assoc f todos-top-priorities-overrides))
4115 todos-top-priorities)))
4116 (while (re-search-forward
4117 (concat "^" (regexp-quote todos-category-beg)
4118 "\\(.+\\)\n") nil t)
4119 (setq cat (match-string 1))
4121 ;; Unless the number of top priorities to show was
4122 ;; passed by the caller, the category-wide value
4123 ;; from `todos-top-priorities-overrides', if non-nil,
4124 ;; overrides a non-nil file-wide value from
4125 ;; `todos-top-priorities-overrides' as well as
4126 ;; `todos-top-priorities'.
4127 (unless (consp filter)
4128 (let ((cats (nth 2 (assoc f todos-top-priorities-overrides))))
4129 (setq cnum (or (cdr (assoc cat cats)) fnum))))
4130 (delete-region (match-beginning 0) (match-end 0))
4131 (setq beg (point)) ; First item in the current category.
4132 (setq end (if (re-search-forward
4133 (concat "^" (regexp-quote todos-category-beg))
4139 (if (re-search-forward
4140 (concat "\n" (regexp-quote todos-category-done))
4144 (unless (and todos-filter-done-items (eq filter 'regexp))
4145 ;; Leave done items.
4146 (delete-region done end)
4148 (narrow-to-region beg end) ; Process only current category.
4149 (goto-char (point-min))
4150 ;; Apply the filter.
4151 (cond ((eq filter 'diary)
4153 (if (looking-at (regexp-quote todos-nondiary-start))
4155 (todos-forward-item))))
4156 ((eq filter 'regexp)
4158 (if (looking-at todos-item-start)
4159 (if (string-match regexp (todos-item-string))
4160 (todos-forward-item)
4161 (todos-remove-item))
4162 ;; Kill lines that aren't part of a todo or done
4163 ;; item (empty or todos-category-done).
4164 (delete-region (line-beginning-position)
4165 (1+ (line-end-position))))
4166 ;; If last todo item in file matches regexp and
4167 ;; there are no following done items,
4168 ;; todos-category-done string is left dangling,
4169 ;; because todos-forward-item jumps over it.
4172 (concat (regexp-quote todos-done-string)
4174 (delete-region (point) (progn
4177 (t ; Filter top priority items.
4178 (setq num (or cnum fnum num))
4180 (todos-forward-item num))))
4182 ;; Delete non-top-priority items.
4183 (unless (member filter '(diary regexp))
4184 (delete-region beg end))
4185 (goto-char (point-min))
4186 ;; Add file (if using multiple files) and category tags to
4189 (when (re-search-forward
4190 (concat (if todos-filter-done-items
4191 (concat "\\(?:" todos-done-string-start
4192 "\\|" todos-date-string-start
4194 todos-date-string-start)
4195 todos-date-pattern "\\(?: " diary-time-regexp
4196 "\\)?" (if todos-filter-done-items
4198 (regexp-quote todos-nondiary-end))
4202 (when (looking-at "(archive) ") (goto-char (match-end 0)))
4203 (insert (if multifile (concat fname ":") "") cat "]"))
4206 (setq bufstr (buffer-string))
4207 (with-current-buffer buf
4208 (let (buffer-read-only)
4209 (insert bufstr)))))))
4210 (set-window-buffer (selected-window) (set-buffer buf))
4211 (todos-prefix-overlays)
4212 (goto-char (point-min)))))
4214 (defun todos-set-top-priorities (&optional arg)
4215 "Set number of top priorities shown by `todos-filter-top-priorities'.
4216 With non-nil ARG, set the number only for the current Todos
4217 category; otherwise, set the number for all categories in the
4220 Calling this function via either of the commands
4221 `todos-set-top-priorities-in-file' or
4222 `todos-set-top-priorities-in-category' is the recommended way to
4223 set the user customizable option `todos-top-priorities-overrides'."
4224 (let* ((cat (todos-current-category))
4225 (file todos-current-todos-file)
4226 (rules todos-top-priorities-overrides)
4227 (frule (assoc-string file rules))
4228 (crule (assoc-string cat (nth 2 frule)))
4229 (crules (nth 2 frule))
4230 (cur (or (if arg (cdr crule) (nth 1 frule))
4231 todos-top-priorities))
4232 (prompt (if arg (concat "Number of top priorities in this category"
4233 " (currently %d): ")
4234 (concat "Default number of top priorities per category"
4235 " in this file (currently %d): ")))
4240 (setq new (read-number (format prompt cur0))
4241 prompt "Enter a non-negative number: "
4244 (append (delete crule crules) (list (cons cat new)))
4245 (append (list file new) (list crules))))
4246 (setq rules (cons (if arg
4247 (list file cur nrule)
4249 (delete frule rules)))
4250 (customize-save-variable 'todos-top-priorities-overrides rules)
4251 (todos-prefix-overlays)))
4253 (defun todos-find-item (str)
4254 "Search for filtered item STR in its saved Todos file.
4255 Return the list (FOUND FILE CAT), where CAT and FILE are the
4256 item's category and file, and FOUND is a cons cell if the search
4257 succeeds, whose car is the start of the item in FILE and whose
4258 cdr is `done', if the item is now a done item, `changed', if its
4259 text was truncated or augmented or, for a top priority item, if
4260 its priority has changed, and `same' otherwise."
4261 (string-match (concat (if todos-filter-done-items
4262 (concat "\\(?:" todos-done-string-start "\\|"
4263 todos-date-string-start "\\)")
4264 todos-date-string-start)
4265 todos-date-pattern "\\(?: " diary-time-regexp "\\)?"
4266 (if todos-filter-done-items
4268 (regexp-quote todos-nondiary-end)) "?"
4269 "\\(?4: \\[\\(?3:(archive) \\)?\\(?2:.*:\\)?"
4270 "\\(?1:.*\\)\\]\\).*$") str)
4271 (let ((cat (match-string 1 str))
4272 (file (match-string 2 str))
4273 (archive (string= (match-string 3 str) "(archive) "))
4274 (filcat (match-string 4 str))
4276 (tpbuf (save-match-data (string-match "top" (buffer-name))))
4278 (setq str (replace-match "" nil nil str 4))
4280 ;; Calculate priority of STR wrt its category.
4282 (while (search-backward filcat nil t)
4283 (setq tpriority (1+ tpriority)))))
4285 (concat todos-directory (substring file 0 -1)
4286 (if archive ".toda" ".todo"))
4288 (concat (file-name-sans-extension
4289 todos-global-current-todos-file) ".toda")
4290 todos-global-current-todos-file)))
4291 (find-file-noselect file)
4292 (with-current-buffer (find-buffer-visiting file)
4295 (goto-char (point-min))
4296 (let ((beg (re-search-forward
4297 (concat "^" (regexp-quote (concat todos-category-beg cat))
4300 (done (save-excursion
4302 (concat "^" (regexp-quote todos-category-done)) nil t)))
4303 (end (save-excursion
4304 (or (re-search-forward
4305 (concat "^" (regexp-quote todos-category-beg))
4308 (setq found (when (search-forward str end t)
4309 (goto-char (match-beginning 0))))
4312 (cons found (if (> (point) done)
4314 (let ((cpriority 1))
4317 ;; Not top item in category.
4318 (while (> (point) (1+ beg))
4319 (let ((opoint (point)))
4320 (todos-backward-item)
4321 ;; Can't move backward beyond
4322 ;; first item in file.
4323 (unless (= (point) opoint)
4324 (setq cpriority (1+ cpriority)))))))
4325 (if (and (= tpriority cpriority)
4326 ;; Proper substring is not the same.
4327 (string= (todos-item-string)
4331 (list found file cat)))
4333 (defun todos-check-filtered-items-file ()
4334 "Check if filtered items file is up to date and a show suitable message."
4338 (let* ((item (todos-item-string))
4339 (found (car (todos-find-item item))))
4340 (unless (eq (cdr found) 'same)
4342 (overlay-put (make-overlay (todos-item-start) (todos-item-end))
4343 'face 'todos-search))
4344 (setq count (1+ count))))
4345 ;; (throw 'old (message "The marked item is not up to date.")))
4346 (todos-forward-item))
4348 (message "Filtered items file is up to date.")
4349 (message (concat "The highlighted item" (if (= count 1) " is " "s are ")
4351 ;; "\nType <return> on item for details."
4354 (defun todos-filter-items-filename ()
4355 "Return absolute file name for saving this Filtered Items buffer."
4356 (let ((bufname (buffer-name)))
4357 (string-match "\"\\([^\"]+\\)\"" bufname)
4358 (let* ((filename-str (substring bufname (match-beginning 1) (match-end 1)))
4359 (filename-base (replace-regexp-in-string ", " "-" filename-str))
4360 (top-priorities (string-match "top priorities" bufname))
4361 (diary-items (string-match "diary items" bufname))
4362 (regexp-items (string-match "regexp items" bufname)))
4364 (let ((prompt (concat "Enter a short identifying string"
4365 " to make this file name unique: ")))
4366 (setq filename-base (concat filename-base "-" (read-string prompt)))))
4367 (concat todos-directory filename-base
4368 (cond (top-priorities ".todt")
4369 (diary-items ".tody")
4370 (regexp-items ".todr"))))))
4372 (defun todos-save-filtered-items-buffer ()
4373 "Save current Filtered Items buffer to a file.
4374 If the file already exists, overwrite it only on confirmation."
4375 (let ((filename (or (buffer-file-name) (todos-filter-items-filename))))
4376 (write-file filename t)))
4378 ;; -----------------------------------------------------------------------------
4379 ;;; Printing Todos buffers
4380 ;; -----------------------------------------------------------------------------
4382 (defcustom todos-print-buffer-function 'ps-print-buffer-with-faces
4383 "Function called by the command `todos-print-buffer'."
4387 (defvar todos-print-buffer "*Todos Print*"
4388 "Name of buffer containing printable Todos text.")
4390 (defun todos-print-buffer (&optional to-file)
4391 "Produce a printable version of the current Todos buffer.
4392 This converts overlays and soft line wrapping and, depending on
4393 the value of `todos-print-buffer-function', includes faces. With
4394 non-nil argument TO-FILE write the printable version to a file;
4395 otherwise, send it to the default printer."
4397 (let ((buf todos-print-buffer)
4399 ((eq major-mode 'todos-mode)
4400 (concat "Todos File: "
4401 (todos-short-file-name todos-current-todos-file)
4402 "\nCategory: " (todos-current-category)))
4403 ((eq major-mode 'todos-filtered-items-mode)
4405 (prefix (propertize (concat todos-prefix " ")
4406 'face 'todos-prefix-string))
4408 (fill-prefix (make-string todos-indent-to-here 32))
4409 (content (buffer-string))
4411 (with-current-buffer (get-buffer-create buf)
4413 (goto-char (point-min))
4416 (end (save-excursion (todos-item-end))))
4417 (when todos-number-prefix
4419 (setq prefix (propertize (concat (number-to-string num) " ")
4420 'face 'todos-prefix-string)))
4422 (fill-region beg end))
4423 ;; Calling todos-forward-item infloops at todos-item-start due to
4424 ;; non-overlay prefix, so search for item start instead.
4425 (if (re-search-forward todos-item-start nil t)
4427 (goto-char (point-max))))
4428 (if (re-search-backward (concat "^" (regexp-quote todos-category-done))
4430 (replace-match todos-done-separator))
4431 (goto-char (point-min))
4435 (let ((file (read-file-name "Print to file: ")))
4436 (funcall todos-print-buffer-function file))
4437 (funcall todos-print-buffer-function)))
4440 (defun todos-print-buffer-to-file ()
4441 "Save printable version of this Todos buffer to a file."
4443 (todos-print-buffer t))
4445 ;; -----------------------------------------------------------------------------
4446 ;;; Legacy Todo mode files
4447 ;; -----------------------------------------------------------------------------
4449 (defcustom todos-todo-mode-date-time-regexp
4450 (concat "\\(?1:[0-9]\\{4\\}\\)-\\(?2:[0-9]\\{2\\}\\)-"
4451 "\\(?3:[0-9]\\{2\\}\\) \\(?4:[0-9]\\{2\\}:[0-9]\\{2\\}\\)")
4452 "Regexp matching legacy todo-mode.el item date-time strings.
4453 In order for `todos-convert-legacy-files' to correctly convert this
4454 string to the current Todos format, the regexp must contain four
4455 explicitly numbered groups (see `(elisp) Regexp Backslash'),
4456 where group 1 matches a string for the year, group 2 a string for
4457 the month, group 3 a string for the day and group 4 a string for
4458 the time. The default value converts date-time strings built
4459 using the default value of `todo-time-string-format' from
4464 (defun todos-convert-legacy-date-time ()
4465 "Return converted date-time string.
4466 Helper function for `todos-convert-legacy-files'."
4467 (let* ((year (match-string 1))
4468 (month (match-string 2))
4469 (monthname (calendar-month-name (string-to-number month) t))
4470 (day (match-string 3))
4471 (time (match-string 4))
4474 (insert (mapconcat 'eval calendar-date-display-form "")
4475 (when time (concat " " time)))))
4477 (defun todos-convert-legacy-files ()
4478 "Convert legacy Todo files to the current Todos format.
4479 The files `todo-file-do' and `todo-file-done' are converted and
4480 saved (the latter as a Todos Archive file) with a new name in
4481 `todos-directory'. See also the documentation string of
4482 `todos-todo-mode-date-time-regexp' for further details."
4484 (eval-when-compile (require 'todo-mode))
4485 ;; Convert `todo-file-do'.
4486 (if (file-exists-p todo-file-do)
4487 (let ((default "todo-do-conv")
4490 (insert-file-contents todo-file-do)
4491 (let ((end (search-forward ")" (line-end-position) t))
4492 (beg (search-backward "(" (line-beginning-position) t)))
4493 (setq todo-categories
4494 (read (buffer-substring-no-properties beg end))))
4496 (delete-region (line-beginning-position) (1+ (line-end-position)))
4499 ((looking-at (regexp-quote (concat todo-prefix todo-category-beg)))
4500 (replace-match todos-category-beg))
4501 ((looking-at (regexp-quote todo-category-end))
4503 ((looking-at (regexp-quote (concat todo-prefix " "
4504 todo-category-sep)))
4505 (replace-match todos-category-done))
4506 ((looking-at (concat (regexp-quote todo-prefix) " "
4507 todos-todo-mode-date-time-regexp " "
4508 (regexp-quote todo-initials) ":"))
4509 (todos-convert-legacy-date-time)))
4511 (setq file (concat todos-directory
4513 (format "Save file as (default \"%s\"): " default)
4516 (write-region (point-min) (point-max) file nil 'nomessage nil t))
4518 (insert-file-contents file)
4519 (let ((todos-categories (todos-make-categories-list t)))
4520 (todos-update-categories-sexp))
4521 (write-region (point-min) (point-max) file nil 'nomessage))
4522 ;; Convert `todo-file-done'.
4523 (when (file-exists-p todo-file-done)
4525 (insert-file-contents todo-file-done)
4526 (let ((beg (make-marker))
4528 cat cats comment item)
4530 (when (looking-at todos-todo-mode-date-time-regexp)
4531 (set-marker beg (point))
4532 (todos-convert-legacy-date-time)
4533 (set-marker end (point))
4535 (insert "[" todos-done-string)
4539 (when (looking-at todos-todo-mode-date-time-regexp)
4540 (todos-convert-legacy-date-time))
4541 (when (looking-at (concat " "
4542 (regexp-quote todo-initials) ":"))
4543 (replace-match "")))
4544 (if (re-search-forward
4545 (concat "^" todos-todo-mode-date-time-regexp) nil t)
4546 (goto-char (match-beginning 0))
4547 (goto-char (point-max)))
4549 (when (looking-back "\\[\\([^][]+\\)\\]")
4550 (setq cat (match-string 1))
4551 (goto-char (match-beginning 0))
4553 ;; If the item ends with a non-comment parenthesis not
4554 ;; followed by a period, we lose (but we inherit that problem
4555 ;; from todo-mode.el).
4556 (when (looking-back "(\\(.*\\)) ")
4557 (setq comment (match-string 1))
4559 (insert "[" todos-comment-string ": " comment "]"))
4560 (set-marker end (point))
4561 (if (member cat cats)
4562 ;; If item is already in its category, leave it there.
4563 (unless (save-excursion
4565 (concat "^" (regexp-quote todos-category-beg)
4567 (string= (match-string 1) cat))
4568 ;; Else move it to its category.
4569 (setq item (buffer-substring-no-properties beg end))
4570 (delete-region beg (1+ end))
4571 (set-marker beg (point))
4574 (regexp-quote (concat todos-category-beg cat))
4578 (if (re-search-forward
4579 (concat "^" (regexp-quote todos-category-beg)
4581 (progn (goto-char (match-beginning 0))
4584 (goto-char (point-max)))
4589 (insert todos-category-beg cat "\n\n" todos-category-done "\n"))
4591 (set-marker beg nil)
4592 (set-marker end nil))
4593 (setq file (concat (file-name-sans-extension file) ".toda"))
4594 (write-region (point-min) (point-max) file nil 'nomessage nil t))
4596 (insert-file-contents file)
4597 (let ((todos-categories (todos-make-categories-list t)))
4598 (todos-update-categories-sexp))
4599 (write-region (point-min) (point-max) file nil 'nomessage)
4600 (setq archive-sexp (read (buffer-substring-no-properties
4601 (line-beginning-position)
4602 (line-end-position)))))
4603 (setq file (concat (file-name-sans-extension file) ".todo"))
4604 ;; Update categories sexp of converted Todos file again, adding
4605 ;; counts of archived items.
4607 (insert-file-contents file)
4608 (let ((sexp (read (buffer-substring-no-properties
4609 (line-beginning-position)
4610 (line-end-position)))))
4612 (let ((archive-cat (assoc (car cat) archive-sexp)))
4614 (aset (cdr cat) 3 (aref (cdr archive-cat) 2)))))
4615 (delete-region (line-beginning-position) (line-end-position))
4616 (prin1 sexp (current-buffer)))
4617 (write-region (point-min) (point-max) file nil 'nomessage)))
4618 (todos-reevaluate-filelist-defcustoms)
4619 (message "Format conversion done."))
4620 (user-error "No legacy Todo file exists")))
4622 ;; -----------------------------------------------------------------------------
4623 ;;; Utility functions for Todos files, categories and items
4624 ;; -----------------------------------------------------------------------------
4626 (defun todos-absolute-file-name (name &optional type)
4627 "Return the absolute file name of short Todos file NAME.
4628 With TYPE `archive' or `top' return the absolute file name of the
4629 short Todos Archive or Top Priorities file name, respectively."
4630 ;; NOP if there is no Todos file yet (i.e. don't concatenate nil).
4633 (concat todos-directory name
4634 (cond ((eq type 'archive) ".toda")
4635 ((eq type 'top) ".todt")
4636 ((eq type 'diary) ".tody")
4637 ((eq type 'regexp) ".todr")
4640 (defun todos-category-number (cat)
4641 "Return the number of category CAT in this Todos file.
4642 The buffer-local variable `todos-category-number' holds this
4643 number as its value."
4644 (let ((categories (mapcar 'car todos-categories)))
4645 (setq todos-category-number
4646 ;; Increment by one, so that the highest priority category in Todos
4647 ;; Categories mode is numbered one rather than zero.
4648 (1+ (- (length categories)
4649 (length (member cat categories)))))))
4651 (defun todos-current-category ()
4652 "Return the name of the current category."
4653 (car (nth (1- todos-category-number) todos-categories)))
4655 (defun todos-category-select ()
4656 "Display the current category correctly."
4657 (let ((name (todos-current-category))
4658 cat-begin cat-end done-start done-sep-start done-end)
4660 (goto-char (point-min))
4662 (concat "^" (regexp-quote (concat todos-category-beg name)) "$") nil t)
4663 (setq cat-begin (1+ (line-end-position)))
4664 (setq cat-end (if (re-search-forward
4665 (concat "^" (regexp-quote todos-category-beg)) nil t)
4668 (setq mode-line-buffer-identification
4669 (funcall todos-mode-line-function name))
4670 (narrow-to-region cat-begin cat-end)
4671 (todos-prefix-overlays)
4672 (goto-char (point-min))
4673 (if (re-search-forward (concat "\n\\(" (regexp-quote todos-category-done)
4676 (setq done-start (match-beginning 0))
4677 (setq done-sep-start (match-beginning 1))
4678 (setq done-end (match-end 0)))
4679 (error "Category %s is missing todos-category-done string" name))
4680 (if todos-show-done-only
4681 (narrow-to-region (1+ done-end) (point-max))
4682 (when (and todos-show-with-done
4683 (re-search-forward todos-done-string-start nil t))
4684 ;; Now we want to see the done items, so reset displayed end to end of
4686 (setq done-start cat-end)
4687 ;; Make display overlay for done items separator string, unless there
4689 (let* ((done-sep todos-done-separator)
4690 (ov (progn (goto-char done-sep-start)
4691 (todos-get-overlay 'separator))))
4693 (setq ov (make-overlay done-sep-start done-end))
4694 (overlay-put ov 'todos 'separator)
4695 (overlay-put ov 'display done-sep))))
4696 (narrow-to-region (point-min) done-start)
4697 ;; Loading this from todos-mode, or adding it to the mode hook, causes
4698 ;; Emacs to hang in todos-item-start, at (looking-at todos-item-start).
4699 (when todos-highlight-item
4701 (hl-line-mode 1)))))
4703 (defun todos-get-count (type &optional category)
4704 "Return count of TYPE items in CATEGORY.
4705 If CATEGORY is nil, default to the current category."
4706 (let* ((cat (or category (todos-current-category)))
4707 (counts (cdr (assoc cat todos-categories)))
4708 (idx (cond ((eq type 'todo) 0)
4709 ((eq type 'diary) 1)
4711 ((eq type 'archived) 3))))
4714 (defun todos-update-count (type increment &optional category)
4715 "Change count of TYPE items in CATEGORY by integer INCREMENT.
4716 With nil or omitted CATEGORY, default to the current category."
4717 (let* ((cat (or category (todos-current-category)))
4718 (counts (cdr (assoc cat todos-categories)))
4719 (idx (cond ((eq type 'todo) 0)
4720 ((eq type 'diary) 1)
4722 ((eq type 'archived) 3))))
4723 (aset counts idx (+ increment (aref counts idx)))))
4725 (defun todos-set-categories ()
4726 "Set `todos-categories' from the sexp at the top of the file."
4727 ;; New archive files created by `todos-move-category' are empty, which would
4728 ;; make the sexp test fail and raise an error, so in this case we skip it.
4729 (unless (zerop (buffer-size))
4733 (goto-char (point-min))
4734 (setq todos-categories
4735 (if (looking-at "\(\(\"")
4736 (read (buffer-substring-no-properties
4737 (line-beginning-position)
4738 (line-end-position)))
4739 (error "Invalid or missing todos-categories sexp")))))))
4741 (defun todos-update-categories-sexp ()
4742 "Update the `todos-categories' sexp at the top of the file."
4743 (let (buffer-read-only)
4747 (goto-char (point-min))
4748 (if (looking-at (concat "^" (regexp-quote todos-category-beg)))
4749 (progn (newline) (goto-char (point-min)) ; Make space for sexp.
4750 (setq todos-categories (todos-make-categories-list t)))
4751 (delete-region (line-beginning-position) (line-end-position)))
4752 (prin1 todos-categories (current-buffer))))))
4754 (defun todos-make-categories-list (&optional force)
4755 "Return an alist of Todos categories and their item counts.
4756 With non-nil argument FORCE parse the entire file to build the
4757 list; otherwise, get the value by reading the sexp at the top of
4759 (setq todos-categories nil)
4763 (goto-char (point-min))
4764 (let (counts cat archive)
4765 ;; If the file is a todo file and has archived items, identify the
4766 ;; archive, in order to count its items. But skip this with
4767 ;; `todos-convert-legacy-files', since that converts filed items to
4769 (when buffer-file-name ; During conversion there is no file yet.
4770 ;; If the file is an archive, it doesn't have an archive.
4771 (unless (member (file-truename buffer-file-name)
4772 (funcall todos-files-function t))
4773 (setq archive (concat (file-name-sans-extension
4774 todos-current-todos-file) ".toda"))))
4776 (cond ((looking-at (concat (regexp-quote todos-category-beg)
4778 (setq cat (match-string-no-properties 1))
4779 ;; Counts for each category: [todo diary done archive]
4780 (setq counts (make-vector 4 0))
4781 (setq todos-categories
4782 (append todos-categories (list (cons cat counts))))
4783 ;; Add archived item count to the todo file item counts.
4784 ;; Make sure to include newly created archives, e.g. due to
4785 ;; todos-move-category.
4786 (when (member archive (funcall todos-files-function t))
4787 (let ((archive-count 0))
4788 (with-current-buffer (find-file-noselect archive)
4790 (goto-char (point-min))
4791 (when (re-search-forward
4792 (concat "^" (regexp-quote todos-category-beg)
4796 (while (not (or (looking-at
4798 (regexp-quote todos-category-beg)
4801 (when (looking-at todos-done-string-start)
4802 (setq archive-count (1+ archive-count)))
4804 (todos-update-count 'archived archive-count cat))))
4805 ((looking-at todos-done-string-start)
4806 (todos-update-count 'done 1 cat))
4807 ((looking-at (concat "^\\("
4808 (regexp-quote diary-nonmarking-symbol)
4809 "\\)?" todos-date-pattern))
4810 (todos-update-count 'diary 1 cat)
4811 (todos-update-count 'todo 1 cat))
4812 ((looking-at (concat todos-date-string-start todos-date-pattern))
4813 (todos-update-count 'todo 1 cat))
4814 ;; If first line is todos-categories list, use it and end loop
4815 ;; -- unless FORCEd to scan whole file.
4818 (setq todos-categories (read (buffer-substring-no-properties
4819 (line-beginning-position)
4820 (line-end-position))))
4821 (goto-char (1- (point-max))))))
4825 (defun todos-repair-categories-sexp ()
4826 "Repair corrupt Todos categories sexp.
4827 This should only be needed as a consequence of careless manual
4828 editing or a bug in todos.el.
4830 *Warning*: Calling this command restores the category order to
4831 the list element order in the Todos categories sexp, so any order
4832 changes made in Todos Categories mode will have to be made again."
4834 (let ((todos-categories (todos-make-categories-list t)))
4835 (todos-update-categories-sexp)))
4837 (defun todos-check-format ()
4838 "Signal an error if the current Todos file is ill-formatted.
4839 Otherwise return t. Display a message if the file is well-formed
4840 but the categories sexp differs from the current value of
4841 `todos-categories'."
4845 (goto-char (point-min))
4846 (let* ((cats (prin1-to-string todos-categories))
4847 (ssexp (buffer-substring-no-properties (line-beginning-position)
4848 (line-end-position)))
4849 (sexp (read ssexp)))
4850 ;; Check the first line for `todos-categories' sexp.
4853 (unless (and (stringp (car c))
4856 (user-error "Invalid or missing todos-categories sexp"))))
4858 ;; Check well-formedness of categories.
4859 (let ((legit (concat
4860 "\\(^" (regexp-quote todos-category-beg) "\\)"
4861 "\\|\\(" todos-date-string-start todos-date-pattern "\\)"
4862 "\\|\\(^[ \t]+[^ \t]*\\)"
4864 "\\|\\(^" (regexp-quote todos-category-done) "\\)"
4865 "\\|\\(" todos-done-string-start "\\)")))
4867 (unless (looking-at legit)
4868 (user-error "Illegitimate Todos file format at line %d"
4869 (line-number-at-pos (point))))
4871 ;; Warn user if categories sexp has changed.
4872 (unless (string= ssexp cats)
4873 (message (concat "The sexp at the beginning of the file differs "
4874 "from the value of `todos-categories.\n"
4875 "If the sexp is wrong, you can fix it with "
4876 "M-x todos-repair-categories-sexp,\n"
4877 "but note this reverts any changes you have "
4878 "made in the order of the categories."))))))
4881 (defun todos-item-start ()
4882 "Move to start of current Todos item and return its position."
4884 ;; Buffer is empty (invocation possible e.g. via todos-forward-item
4885 ;; from todos-filter-items when processing category with no todo
4887 (eq (point-min) (point-max))
4888 ;; Point is on the empty line below category's last todo item...
4889 (and (looking-at "^$")
4890 (or (eobp) ; ...and done items are hidden...
4891 (save-excursion ; ...or done items are visible.
4893 (looking-at (concat "^"
4894 (regexp-quote todos-category-done))))))
4895 ;; Buffer is widened.
4896 (looking-at (regexp-quote todos-category-beg)))
4897 (goto-char (line-beginning-position))
4898 (while (not (looking-at todos-item-start))
4902 (defun todos-item-end ()
4903 "Move to end of current Todos item and return its position."
4904 ;; Items cannot end with a blank line.
4905 (unless (looking-at "^$")
4906 (let* ((done (todos-done-item-p))
4908 ;; For todo items, end is before the done items section, for done
4909 ;; items, end is before the next category. If these limits are
4910 ;; missing or inaccessible, end it before the end of the buffer.
4911 (lim (if (save-excursion
4913 (concat "^" (regexp-quote (if done
4915 todos-category-done)))
4917 (progn (setq to-lim t) (match-beginning 0))
4919 (when (bolp) (forward-char)) ; Find start of next item.
4920 (goto-char (if (re-search-forward todos-item-start lim t)
4922 (if to-lim lim (point-max))))
4923 ;; For last todo item, skip back over the empty line before the done
4924 ;; items section, else just back to the end of the previous line.
4925 (backward-char (when (and to-lim (not done) (eq (point) lim)) 2))
4928 (defun todos-item-string ()
4929 "Return bare text of current item as a string."
4930 (let ((opoint (point))
4931 (start (todos-item-start))
4932 (end (todos-item-end)))
4934 (and start end (buffer-substring-no-properties start end))))
4936 (defun todos-forward-item (&optional count)
4937 "Move point COUNT items down (by default, move down by one item)."
4938 (let* ((not-done (not (or (todos-done-item-p) (looking-at "^$"))))
4939 (start (line-end-position)))
4941 (if (re-search-forward todos-item-start nil t (or count 1))
4942 (goto-char (match-beginning 0))
4943 (goto-char (point-max)))
4944 ;; If points advances by one from a todo to a done item, go back
4945 ;; to the space above todos-done-separator, since that is a
4946 ;; legitimate place to insert an item. But skip this space if
4947 ;; count > 1, since that should only stop on an item.
4948 (when (and not-done (todos-done-item-p) (not count))
4949 ;; (if (or (not count) (= count 1))
4950 (re-search-backward "^$" start t))));)
4951 ;; The preceding sexp is insufficient when buffer is not narrowed,
4952 ;; since there could be no done items in this category, so the
4953 ;; search puts us on first todo item of next category. Does this
4954 ;; ever happen? If so:
4955 ;; (let ((opoint) (point))
4956 ;; (forward-line -1)
4957 ;; (when (or (not count) (= count 1))
4958 ;; (cond ((looking-at (concat "^" (regexp-quote todos-category-beg)))
4959 ;; (forward-line -2))
4960 ;; ((looking-at (concat "^" (regexp-quote todos-category-done)))
4961 ;; (forward-line -1))
4963 ;; (goto-char opoint)))))))
4965 (defun todos-backward-item (&optional count)
4966 "Move point up to start of item with next higher priority.
4967 With positive numerical prefix COUNT, move point COUNT items
4970 If the category's done items are visible, this command called
4971 with a prefix argument only moves point to a higher item, e.g.,
4972 with point on the first done item and called with prefix 1, it
4973 moves to the last todo item; but if called with point on the
4974 first done item without a prefix argument, it moves point the the
4975 empty line above the done items separator."
4976 (let* ((done (todos-done-item-p)))
4979 (re-search-backward todos-item-start nil t (or count 1)))
4980 ;; Unless this is a regexp filtered items buffer (which can contain
4981 ;; intermixed todo and done items), if points advances by one from a
4982 ;; done to a todo item, go back to the space above
4983 ;; todos-done-separator, since that is a legitimate place to insert an
4984 ;; item. But skip this space if count > 1, since that should only
4986 (when (and done (not (todos-done-item-p)) (not count)
4987 ;(or (not count) (= count 1))
4988 (not (equal (buffer-name) todos-regexp-items-buffer)))
4989 (re-search-forward (concat "^" (regexp-quote todos-category-done))
4991 (forward-line -1))))
4993 (defun todos-remove-item ()
4994 "Internal function called in editing, deleting or moving items."
4995 (let* ((end (progn (todos-item-end) (1+ (point))))
4996 (beg (todos-item-start))
4997 (ov (todos-get-overlay 'prefix)))
4998 (when ov (delete-overlay ov))
4999 (delete-region beg end)))
5001 (defun todos-diary-item-p ()
5002 "Return non-nil if item at point has diary entry format."
5004 (when (todos-item-string) ; Exclude empty lines.
5006 (not (looking-at (regexp-quote todos-nondiary-start))))))
5008 (defun todos-diary-goto-entry ()
5009 "Jump to todo item included in Fancy Diary display.
5010 Helper function for `diary-goto-entry'."
5011 (when (eq major-mode 'todos-mode)
5012 (let ((opoint (point)))
5013 (re-search-backward (concat "^" (regexp-quote todos-category-beg)
5014 "\\(.*\\)\n") nil t)
5015 (todos-category-number (match-string 1))
5016 (todos-category-select)
5017 (goto-char opoint))))
5019 (defun todos-done-item-p ()
5020 "Return non-nil if item at point is a done item."
5023 (looking-at todos-done-string-start)))
5025 (defun todos-done-item-section-p ()
5026 "Return non-nil if point is in category's done items section."
5028 (or (re-search-backward (concat "^" (regexp-quote todos-category-done))
5030 (progn (goto-char (point-min))
5031 (looking-at todos-done-string-start)))))
5033 (defun todos-reset-done-separator (sep)
5034 "Replace existing overlays of done items separator string SEP."
5038 (goto-char (point-min))
5039 (while (re-search-forward
5040 (concat "\n\\(" (regexp-quote todos-category-done) "\\)") nil t)
5041 (let* ((beg (match-beginning 1))
5043 (ov (progn (goto-char beg)
5044 (todos-get-overlay 'separator)))
5045 (old-sep (when ov (overlay-get ov 'display)))
5048 (unless (string= old-sep sep)
5049 (setq new-ov (make-overlay beg end))
5050 (overlay-put new-ov 'todos 'separator)
5051 (overlay-put new-ov 'display todos-done-separator)
5052 (delete-overlay ov))))))))
5054 (defun todos-get-overlay (val)
5055 "Return the overlay at point whose `todos' property has value VAL."
5056 ;; Use overlays-in to find prefix overlays and check over two
5057 ;; positions to find done separator overlay.
5058 (let ((ovs (overlays-in (point) (1+ (point))))
5063 (when (eq (overlay-get ov 'todos) val)
5064 (throw 'done ov))))))
5066 (defun todos-marked-item-p ()
5067 "Non-nil if this item begins with `todos-item-mark'.
5068 In that case, return the item's prefix overlay."
5069 (let* ((ov (todos-get-overlay 'prefix))
5070 ;; If an item insertion command is called on a Todos file
5071 ;; before it is visited, it has no prefix overlays yet, so
5073 (pref (when ov (overlay-get ov 'before-string)))
5075 (string-match (concat "^" (regexp-quote todos-item-mark))
5079 (defun todos-insert-with-overlays (item)
5080 "Insert ITEM at point and update prefix/priority number overlays."
5082 ;; Insertion pushes item down but not its prefix overlay. When the
5083 ;; overlay includes a mark, this would now mark the inserted ITEM,
5084 ;; so move it to the pushed down item.
5085 (let ((ov (todos-get-overlay 'prefix))
5086 (marked (todos-marked-item-p)))
5088 (when marked (move-overlay ov (point) (point))))
5089 (todos-backward-item)
5090 (todos-prefix-overlays))
5092 (defun todos-prefix-overlays ()
5093 "Update the prefix overlays of the current category's items.
5094 The overlay's value is the string `todos-prefix' or with non-nil
5095 `todos-number-prefix' an integer in the sequence from 1 to
5096 the number of todo or done items in the category indicating the
5097 item's priority. Todo and done items are numbered independently
5100 (cat-tp (or (cdr (assoc-string
5101 (todos-current-category)
5102 (nth 2 (assoc-string todos-current-todos-file
5103 todos-top-priorities-overrides))))
5104 todos-top-priorities))
5107 (goto-char (point-min))
5109 (when (or (todos-date-string-matcher (line-end-position))
5110 (todos-done-string-matcher (line-end-position)))
5111 (goto-char (match-beginning 0))
5113 ;; Reset number to 1 for first done item.
5114 (when (and (eq major-mode 'todos-mode)
5115 (looking-at todos-done-string-start)
5116 (looking-back (concat "^"
5117 (regexp-quote todos-category-done)
5121 (setq prefix (concat (propertize
5122 (if todos-number-prefix
5123 (number-to-string num)
5126 ;; Prefix of top priority items has a
5127 ;; distinct face in Todos mode.
5128 (if (and (eq major-mode 'todos-mode)
5132 'todos-prefix-string))
5134 (let ((ov (todos-get-overlay 'prefix))
5135 (marked (todos-marked-item-p)))
5136 ;; Prefix overlay must be at a single position so its
5137 ;; bounds aren't changed when (re)moving an item.
5138 (unless ov (setq ov (make-overlay (point) (point))))
5139 (overlay-put ov 'todos 'prefix)
5140 (overlay-put ov 'before-string (if marked
5141 (concat todos-item-mark prefix)
5145 ;; -----------------------------------------------------------------------------
5146 ;;; Utilities for generating item insertion commands and key bindings
5147 ;; -----------------------------------------------------------------------------
5149 ;; These two powerset definitions are adaptations of code published at
5150 ;; http://rosettacode.org, whose content is licensed under GFDL 1.2.
5151 ;; The recursive definition is a slight reformulation of
5152 ;; http://rosettacode.org/wiki/Power_set#Common_Lisp. The iterative
5153 ;; definition is my Elisp implementation of
5154 ;; http://rosettacode.org/wiki/Power_set#C. Can either of these be
5155 ;; included in Emacs, or is there no need to concerned about copyright
5158 ;; (defun todos-powerset (list)
5159 ;; "Return the powerset of LIST."
5160 ;; (cond ((null list)
5163 ;; (let ((recur (todos-powerset-recursive (cdr list)))
5165 ;; (dolist (elt recur pset)
5166 ;; (push (cons (car list) elt) pset))
5167 ;; (append pset recur)))))
5169 (defun todos-powerset (list)
5170 "Return the powerset of LIST."
5171 (let ((card (expt 2 (length list)))
5176 (while (not (zerop i))
5177 (let ((arg (pop l)))
5179 (setq elt (append elt (list arg))))
5181 (setq pset (append pset (list elt)))
5185 (defun todos-gen-arglists (arglist)
5186 "Return list of lists of non-nil atoms produced from ARGLIST.
5187 The elements of ARGLIST may be atoms or lists."
5190 (let ((arg (pop arglist)))
5191 (cond ((symbolp arg)
5192 (setq arglists (if arglists
5193 (mapcar (lambda (l) (push arg l)) arglists)
5194 (list (push arg arglists)))))
5198 (if (= 1 (length arglists))
5199 (apply (lambda (l) (push a l)) arglists)
5200 (mapcar (lambda (l) (push a l)) arglists)))
5202 (setq arglists (mapcar 'reverse (apply 'append (mapc 'car arglists))))))
5204 (defvar todos-insertion-commands-args-genlist
5205 '(diary nonmarking (calendar date dayname) time (here region))
5206 "Generator list for argument lists of item insertion commands.")
5208 (defvar todos-insertion-commands-args
5209 (let ((argslist (todos-gen-arglists todos-insertion-commands-args-genlist))
5211 (setq res (cl-remove-duplicates
5212 (apply 'append (mapcar 'todos-powerset argslist)) :test 'equal))
5214 (unless (= 5 (length l))
5215 (let ((v (make-vector 5 nil)) elt)
5218 (cond ((eq elt 'diary)
5220 ((eq elt 'nonmarking)
5222 ((or (eq elt 'calendar)
5231 (setq l (append v nil))))
5232 (setq new (append new (list l))))
5234 "List of all argument lists for Todos item insertion commands.")
5236 (defun todos-insertion-command-name (arglist)
5237 "Generate Todos item insertion command name from ARGLIST."
5238 (replace-regexp-in-string
5240 (replace-regexp-in-string
5242 ;; (concat "todos-item-insert-"
5243 (concat "todos-insert-item-"
5244 (mapconcat (lambda (e) (if e (symbol-name e))) arglist "-")))))
5246 (defvar todos-insertion-commands-names
5248 (todos-insertion-command-name l))
5249 todos-insertion-commands-args)
5250 "List of names of Todos item insertion commands.")
5252 (defmacro todos-define-insertion-command (&rest args)
5253 "Generate item insertion command definitions from ARGS."
5254 (let ((name (intern (todos-insertion-command-name args)))
5259 (arg4 (nth 4 args)))
5260 `(defun ,name (&optional arg &rest args)
5261 "Todos item insertion command generated from ARGS.
5262 For descriptions of the individual arguments, their values, and
5263 their relation to key bindings, see `todos-basic-insert-item'."
5264 (interactive (list current-prefix-arg))
5265 (todos-basic-insert-item arg ',arg0 ',arg1 ',arg2 ',arg3 ',arg4))))
5267 (defvar todos-insertion-commands
5269 (eval `(todos-define-insertion-command ,@c)))
5270 todos-insertion-commands-args)
5271 "List of Todos item insertion commands.")
5273 (defvar todos-insertion-commands-arg-key-list
5274 '(("diary" "y" "yy")
5275 ("nonmarking" "k" "kk")
5276 ("calendar" "c" "cc")
5278 ("dayname" "n" "nn")
5282 "List of mappings of insertion command arguments to key sequences.")
5284 (defun todos-insertion-key-bindings (map)
5285 "Generate key binding definitions for item insertion keymap MAP."
5286 (dolist (c todos-insertion-commands)
5288 (cname (symbol-name c)))
5290 (let ((arg (nth 0 l))
5293 (if (string-match (concat (regexp-quote arg) "\\_>") cname)
5294 (setq key (concat key key2)))
5295 (if (string-match (concat (regexp-quote arg) ".+") cname)
5296 (setq key (concat key key1)))))
5297 todos-insertion-commands-arg-key-list)
5298 (if (string-match (concat (regexp-quote "todos-insert-item") "\\_>") cname)
5299 (setq key (concat key "i")))
5300 (define-key map key c))))
5302 ;; -----------------------------------------------------------------------------
5303 ;;; Todos minibuffer utilities
5304 ;; -----------------------------------------------------------------------------
5306 (defcustom todos-y-with-space nil
5307 "Non-nil means allow SPC to affirm a \"y or n\" question."
5311 (defun todos-y-or-n-p (prompt)
5312 "Ask \"y or n\" question PROMPT and return t if answer is \"y\".
5313 Also return t if answer is \"Y\", but unlike `y-or-n-p', allow
5314 SPC to affirm the question only if option `todos-y-with-space' is
5316 (unless todos-y-with-space
5317 (define-key query-replace-map " " 'ignore))
5320 (define-key query-replace-map " " 'act)))
5322 (defun todos-category-completions (&optional archive)
5323 "Return a list of completions for `todos-read-category'.
5324 Each element of the list is a cons of a category name and the
5325 file or list of files (as short file names) it is in. The files
5326 are either the current (or if there is none, the default) todo
5327 file plus the files listed in `todos-category-completions-files',
5328 or, with non-nil ARCHIVE, the current archive file."
5329 (let* ((curfile (or todos-current-todos-file
5330 (and todos-show-current-file
5331 todos-global-current-todos-file)
5332 (todos-absolute-file-name todos-default-todos-file)))
5333 (files (or (unless archive
5334 (mapcar 'todos-absolute-file-name
5335 todos-category-completions-files))
5338 ;; If file was just added, it has no category completions.
5339 (unless (zerop (buffer-size (find-buffer-visiting curfile)))
5340 (unless (member curfile todos-archives)
5341 (add-to-list 'files curfile))
5342 (dolist (f files listall)
5343 (with-current-buffer (find-file-noselect f 'nowarn)
5344 ;; Ensure category is properly displayed in case user
5345 ;; switches to file via a non-Todos command. And if done
5346 ;; items in category are visible, keep them visible.
5347 (let ((done todos-show-with-done))
5348 (when (> (buffer-size) (- (point-max) (point-min)))
5350 (goto-char (point-min))
5351 (setq done (re-search-forward todos-done-string-start nil t))))
5352 (let ((todos-show-with-done done))
5353 (save-excursion (todos-category-select))))
5357 (goto-char (point-min))
5358 (setq listf (read (buffer-substring-no-properties
5359 (line-beginning-position)
5360 (line-end-position)))))))
5361 (mapc (lambda (elt) (let* ((cat (car elt))
5362 (la-elt (assoc cat listall)))
5364 (setcdr la-elt (append (list (cdr la-elt))
5366 (push (cons cat f) listall))))
5369 (defun todos-read-file-name (prompt &optional archive mustmatch)
5370 "Choose and return the name of a Todos file, prompting with PROMPT.
5372 Show completions with TAB or SPC; the names are shown in short
5373 form but the absolute truename is returned. With non-nil ARCHIVE
5374 return the absolute truename of a Todos archive file. With non-nil
5375 MUSTMATCH the name of an existing file must be chosen;
5376 otherwise, a new file name is allowed."
5377 (let* ((completion-ignore-case todos-completion-ignore-case)
5378 (files (mapcar 'todos-short-file-name
5379 (if archive todos-archives todos-files)))
5380 (file (completing-read prompt files nil mustmatch nil nil
5382 ;; If user hit RET without
5383 ;; choosing a file, default to
5384 ;; current or default file.
5385 (todos-short-file-name
5386 (or todos-current-todos-file
5387 (and todos-show-current-file
5388 todos-global-current-todos-file)
5389 (todos-absolute-file-name
5390 todos-default-todos-file)))
5391 ;; Trigger prompt for initial file.
5393 (unless (file-exists-p todos-directory)
5394 (make-directory todos-directory))
5396 (setq file (todos-validate-name file 'file)))
5397 (setq file (file-truename (concat todos-directory file
5398 (if archive ".toda" ".todo"))))))
5400 (defun todos-read-category (prompt &optional match-type file)
5401 "Choose and return a category name, prompting with PROMPT.
5402 Show completions for existing categories with TAB or SPC.
5404 The argument MATCH-TYPE specifies the matching requirements on
5405 the category name: with the value `todo' or `archive' the name
5406 must complete to that of an existing todo or archive category,
5407 respectively; with the value `add' the name must not be that of
5408 an existing category; with all other values both existing and new
5409 valid category names are accepted.
5411 With non-nil argument FILE prompt for a file and complete only
5412 against categories in that file; otherwise complete against all
5413 categories from `todos-category-completions-files'."
5414 ;; Allow SPC to insert spaces, for adding new category names.
5415 (let ((map minibuffer-local-completion-map))
5416 (define-key map " " nil)
5417 (let* ((add (eq match-type 'add))
5418 (archive (eq match-type 'archive))
5419 (file0 (when (and file (> (length todos-files) 1))
5420 (todos-read-file-name (concat "Choose a" (if archive
5423 " file: ") archive t)))
5424 (completions (unless file0 (todos-category-completions archive)))
5425 (categories (cond (file0
5426 (with-current-buffer
5427 (find-file-noselect file0 'nowarn)
5428 (let ((todos-current-todos-file file0))
5430 ((and add (not file))
5431 (with-current-buffer
5432 (find-file-noselect todos-current-todos-file)
5436 (completion-ignore-case todos-completion-ignore-case)
5437 (cat (completing-read prompt categories nil
5438 (eq match-type 'todo) nil nil
5439 ;; Unless we're adding a category via
5440 ;; todos-add-category, set default
5441 ;; for existing categories to the
5442 ;; current category of the chosen
5443 ;; file or else of the current file.
5444 (if (and categories (not add))
5445 (with-current-buffer
5448 todos-current-todos-file
5449 (todos-absolute-file-name
5450 todos-default-todos-file)))
5451 (todos-current-category))
5452 ;; Trigger prompt for initial category.
5454 (catfil (cdr (assoc cat completions)))
5455 (str "Category \"%s\" from which file (TAB for choices)? "))
5456 ;; If we do category completion and the chosen category name
5457 ;; occurs in more than one file, prompt to choose one file.
5458 (unless (or file0 add (not catfil))
5459 (setq file0 (file-truename
5462 (todos-absolute-file-name
5463 (let ((files (mapcar 'todos-short-file-name catfil)))
5464 (completing-read (format str cat) files)))))))
5465 ;; Default to the current file.
5466 (unless file0 (setq file0 todos-current-todos-file))
5467 ;; First validate only a name passed interactively from
5468 ;; todos-add-category, which must be of a nonexisting category.
5469 (unless (and (assoc cat categories) (not add))
5470 ;; Validate only against completion categories.
5471 (let ((todos-categories categories))
5472 (setq cat (todos-validate-name cat 'category)))
5473 ;; When user enters a nonexisting category name by jumping or
5474 ;; moving, confirm that it should be added, then validate.
5476 (if (todos-y-or-n-p (format "Add new category \"%s\" to file \"%s\"? "
5477 cat (todos-short-file-name file0)))
5479 (when (assoc cat categories)
5480 (let ((todos-categories categories))
5481 (setq cat (todos-validate-name cat 'category))))
5482 ;; Restore point and narrowing after adding new
5483 ;; category, to avoid moving to beginning of file when
5484 ;; moving marked items to a new category
5485 ;; (todos-move-item).
5488 (todos-add-category file0 cat))))
5489 ;; If we decide not to add a category, exit without returning.
5493 (defun todos-validate-name (name type)
5494 "Prompt for new NAME for TYPE until it is valid, then return it.
5495 TYPE can be either of the symbols `file' or `category'."
5496 (let ((categories todos-categories)
5497 (files (mapcar 'todos-short-file-name todos-files))
5501 (cond ((string= "" name)
5503 (cond ((eq type 'file)
5505 "Enter a non-empty file name: "
5506 ;; Empty string passed by todos-show to
5507 ;; prompt for initial Todos file.
5508 (concat "Initial file name ["
5509 todos-initial-file "]: ")))
5510 ((eq type 'category)
5512 "Enter a non-empty category name: "
5513 ;; Empty string passed by todos-show to
5514 ;; prompt for initial category of a new
5516 (concat "Initial category name ["
5517 todos-initial-category "]: "))))))
5518 ((string-match "\\`\\s-+\\'" name)
5520 "Enter a name that does not contain only white space: "))
5521 ((and (eq type 'file) (member name files))
5522 (setq prompt "Enter a non-existing file name: "))
5523 ((and (eq type 'category) (assoc name categories))
5524 (setq prompt "Enter a non-existing category name: ")))
5525 (setq name (if (or (and (eq type 'file) files)
5526 (and (eq type 'category) categories))
5527 (completing-read prompt (cond ((eq type 'file)
5529 ((eq type 'category)
5531 ;; Offer default initial name.
5532 (completing-read prompt (if (eq type 'file)
5535 nil nil (if (eq type 'file)
5537 todos-initial-category))))))
5540 ;; Adapted from calendar-read-date and calendar-date-string.
5541 (defun todos-read-date (&optional arg mo yr)
5542 "Prompt for Gregorian date and return it in the current format.
5544 With non-nil ARG, prompt for and return only the date component
5545 specified by ARG, which can be one of these symbols:
5546 `month' (prompt for name, return name or number according to
5547 value of `calendar-date-display-form'), `day' of month, or
5548 `year'. The value of each of these components can be `*',
5549 indicating an unspecified month, day, or year.
5551 When ARG is `day', non-nil arguments MO and YR determine the
5552 number of the last the day of the month."
5553 (let (year monthname month day
5554 dayname) ; Needed by calendar-date-display-form.
5555 (when (or (not arg) (eq arg 'year))
5556 (while (if (natnump year) (< year 1) (not (eq year '*)))
5557 (setq year (read-from-minibuffer
5558 "Year (>0 or RET for this year or * for any year): "
5559 nil nil t nil (number-to-string
5560 (calendar-extract-year
5561 (calendar-current-date)))))))
5562 (when (or (not arg) (eq arg 'month))
5563 (let* ((marray todos-month-name-array)
5564 (mlist (append marray nil))
5565 (mabarray todos-month-abbrev-array)
5566 (mablist (append mabarray nil))
5567 (completion-ignore-case todos-completion-ignore-case))
5568 (setq monthname (completing-read
5569 "Month name (RET for current month, * for any month): "
5570 ;; (mapcar 'list (append marray nil))
5572 (calendar-month-name (calendar-extract-month
5573 (calendar-current-date)) t))
5574 ;; month (cdr (assoc-string
5575 ;; monthname (calendar-make-alist marray nil nil
5577 month (1+ (- (length mlist)
5578 (length (or (member monthname mlist)
5579 (member monthname mablist))))))
5580 (setq monthname (aref mabarray (1- month)))))
5581 (when (or (not arg) (eq arg 'day))
5582 (let ((last (let ((mm (or month mo))
5584 ;; If month is unspecified, use a month with 31
5585 ;; days for checking day of month input. Does
5586 ;; Calendar do anything special when * is
5587 ;; currently a shorter month?
5588 (if (= mm 13) (setq mm 1))
5589 ;; If year is unspecified, use a leap year to
5591 (if (eq year '*) (setq yy 2012))
5592 (calendar-last-day-of-month mm yy))))
5593 (while (if (natnump day) (or (< day 1) (> day last)) (not (eq day '*)))
5594 (setq day (read-from-minibuffer
5595 (format "Day (1-%d or RET for today or * for any day): "
5597 nil nil t nil (number-to-string
5598 (calendar-extract-day
5599 (calendar-current-date))))))))
5600 ;; Stringify read values (monthname is already a string).
5601 (and year (setq year (if (eq year '*)
5603 (number-to-string year))))
5604 (and day (setq day (if (eq day '*)
5606 (number-to-string day))))
5607 (and month (setq month (if (eq month '*)
5609 (number-to-string month))))
5611 (cond ((eq arg 'year) year)
5614 (if (memq 'month calendar-date-display-form)
5617 (mapconcat 'eval calendar-date-display-form ""))))
5619 (defun todos-read-dayname ()
5620 "Choose name of a day of the week with completion and return it."
5621 (let ((completion-ignore-case todos-completion-ignore-case))
5622 (completing-read "Enter a day name: "
5623 (append calendar-day-name-array nil)
5626 (defun todos-read-time ()
5627 "Prompt for and return a valid clock time as a string.
5629 Valid time strings are those matching `diary-time-regexp'.
5630 Typing `<return>' at the prompt returns the current time, if the
5631 user option `todos-always-add-time-string' is non-nil, otherwise
5632 the empty string (i.e., no time string)."
5635 (setq answer (read-string "Enter a clock time: " nil nil
5636 (when todos-always-add-time-string
5637 (substring (current-time-string) 11 16))))
5638 (when (or (string= "" answer)
5639 (string-match diary-time-regexp answer))
5643 ;; -----------------------------------------------------------------------------
5644 ;;; Customization groups and utilities
5645 ;; -----------------------------------------------------------------------------
5648 "Create and maintain categorized lists of todo items."
5649 :link '(emacs-commentary-link "todos")
5653 (defgroup todos-edit nil
5654 "User options for adding and editing todo items."
5658 (defgroup todos-categories nil
5659 "User options for Todos Categories mode."
5663 (defgroup todos-filtered nil
5664 "User options for Todos Filter Items mode."
5668 (defgroup todos-display nil
5669 "User display options for Todos mode."
5673 (defgroup todos-faces nil
5674 "Faces for the Todos modes."
5678 (defun todos-set-show-current-file (symbol value)
5679 "The :set function for user option `todos-show-current-file'."
5680 (custom-set-default symbol value)
5682 (add-hook 'pre-command-hook 'todos-show-current-file nil t)
5683 (remove-hook 'pre-command-hook 'todos-show-current-file t)))
5685 (defun todos-reset-prefix (symbol value)
5686 "The :set function for `todos-prefix' and `todos-number-prefix'."
5687 (let ((oldvalue (symbol-value symbol))
5688 (files todos-file-buffers))
5689 (custom-set-default symbol value)
5690 (when (not (equal value oldvalue))
5692 (with-current-buffer (find-file-noselect f)
5693 ;; Activate the new setting in the current category.
5694 (save-excursion (todos-category-select)))))))
5696 (defun todos-reset-nondiary-marker (symbol value)
5697 "The :set function for user option `todos-nondiary-marker'."
5698 (let ((oldvalue (symbol-value symbol))
5699 (files (append todos-files todos-archives)))
5700 (custom-set-default symbol value)
5701 ;; Need to reset these to get font-locking right.
5702 (setq todos-nondiary-start (nth 0 todos-nondiary-marker)
5703 todos-nondiary-end (nth 1 todos-nondiary-marker)
5704 todos-date-string-start
5705 ;; See comment in defvar of `todos-date-string-start'.
5706 (concat "^\\(" (regexp-quote todos-nondiary-start) "\\|"
5707 (regexp-quote diary-nonmarking-symbol) "\\)?"))
5708 (when (not (equal value oldvalue))
5710 (with-current-buffer (find-file-noselect f)
5711 (let (buffer-read-only)
5713 (goto-char (point-min))
5715 (if (re-search-forward
5716 (concat "^\\(" todos-done-string-start "[^][]+] \\)?"
5717 "\\(?1:" (regexp-quote (car oldvalue))
5718 "\\)" todos-date-pattern "\\( "
5719 diary-time-regexp "\\)?\\(?2:"
5720 (regexp-quote (cadr oldvalue)) "\\)")
5723 (replace-match (nth 0 value) t t nil 1)
5724 (replace-match (nth 1 value) t t nil 2))
5726 (todos-category-select)))))))
5728 (defun todos-reset-done-separator-string (symbol value)
5729 "The :set function for `todos-done-separator-string'."
5730 (let ((oldvalue (symbol-value symbol))
5731 (files todos-file-buffers)
5732 (sep todos-done-separator))
5733 (custom-set-default symbol value)
5734 (when (not (equal value oldvalue))
5736 (with-current-buffer (find-file-noselect f)
5737 (let (buffer-read-only)
5738 (setq todos-done-separator (todos-done-separator))
5739 (when (= 1 (length value))
5740 (todos-reset-done-separator sep)))
5741 (todos-category-select))))))
5743 (defun todos-reset-done-string (symbol value)
5744 "The :set function for user option `todos-done-string'."
5745 (let ((oldvalue (symbol-value symbol))
5746 (files (append todos-files todos-archives)))
5747 (custom-set-default symbol value)
5748 ;; Need to reset this to get font-locking right.
5749 (setq todos-done-string-start
5750 (concat "^\\[" (regexp-quote todos-done-string)))
5751 (when (not (equal value oldvalue))
5753 (with-current-buffer (find-file-noselect f)
5754 (let (buffer-read-only)
5756 (goto-char (point-min))
5758 (if (re-search-forward
5759 (concat "^" (regexp-quote todos-nondiary-start)
5760 "\\(" (regexp-quote oldvalue) "\\)")
5762 (replace-match value t t nil 1)
5764 (todos-category-select)))))))
5766 (defun todos-reset-comment-string (symbol value)
5767 "The :set function for user option `todos-comment-string'."
5768 (let ((oldvalue (symbol-value symbol))
5769 (files (append todos-files todos-archives)))
5770 (custom-set-default symbol value)
5771 (when (not (equal value oldvalue))
5773 (with-current-buffer (find-file-noselect f)
5774 (let (buffer-read-only)
5777 (goto-char (point-min))
5779 (if (re-search-forward
5781 "\\[\\(" (regexp-quote oldvalue) "\\): [^]]*\\]")
5783 (replace-match value t t nil 1)
5785 (todos-category-select))))))))
5787 (defun todos-reset-highlight-item (symbol value)
5788 "The :set function for `todos-toggle-item-highlighting'."
5789 (let ((oldvalue (symbol-value symbol))
5790 (files (append todos-files todos-archives)))
5791 (custom-set-default symbol value)
5792 (when (not (equal value oldvalue))
5794 (let ((buf (find-buffer-visiting f)))
5796 (with-current-buffer buf
5800 (hl-line-mode -1)))))))))
5802 (defun todos-reevaluate-filelist-defcustoms ()
5803 "Reevaluate defcustoms that provide choice list of Todos files."
5804 (custom-set-default 'todos-default-todos-file
5805 (symbol-value 'todos-default-todos-file))
5806 (todos-reevaluate-default-file-defcustom)
5807 (custom-set-default 'todos-filter-files (symbol-value 'todos-filter-files))
5808 (todos-reevaluate-filter-files-defcustom)
5809 (custom-set-default 'todos-category-completions-files
5810 (symbol-value 'todos-category-completions-files))
5811 (todos-reevaluate-category-completions-files-defcustom))
5813 (defun todos-reevaluate-default-file-defcustom ()
5814 "Reevaluate defcustom of `todos-default-todos-file'.
5815 Called after adding or deleting a Todos file."
5816 (eval (defcustom todos-default-todos-file (car (funcall todos-files-function))
5817 "Todos file visited by first session invocation of `todos-show'."
5818 :type `(radio ,@(mapcar (lambda (f) (list 'const f))
5819 (mapcar 'todos-short-file-name
5820 (funcall todos-files-function))))
5823 (defun todos-reevaluate-category-completions-files-defcustom ()
5824 "Reevaluate defcustom of `todos-category-completions-files'.
5825 Called after adding or deleting a Todos file."
5826 (eval (defcustom todos-category-completions-files nil
5827 "List of files for building `todos-read-category' completions."
5828 :type `(set ,@(mapcar (lambda (f) (list 'const f))
5829 (mapcar 'todos-short-file-name
5830 (funcall todos-files-function))))
5833 (defun todos-reevaluate-filter-files-defcustom ()
5834 "Reevaluate defcustom of `todos-filter-files'.
5835 Called after adding or deleting a Todos file."
5836 (eval (defcustom todos-filter-files nil
5837 "List of files for multifile item filtering."
5838 :type `(set ,@(mapcar (lambda (f) (list 'const f))
5839 (mapcar 'todos-short-file-name
5840 (funcall todos-files-function))))
5843 ;; -----------------------------------------------------------------------------
5845 ;; -----------------------------------------------------------------------------
5847 (defun todos-nondiary-marker-matcher (lim)
5848 "Search for Todos nondiary markers within LIM for font-locking."
5849 (re-search-forward (concat "^\\(?1:" (regexp-quote todos-nondiary-start) "\\)"
5850 todos-date-pattern "\\(?: " diary-time-regexp
5851 "\\)?\\(?2:" (regexp-quote todos-nondiary-end) "\\)")
5854 (defun todos-diary-nonmarking-matcher (lim)
5855 "Search for diary nonmarking symbol within LIM for font-locking."
5856 (re-search-forward (concat "^\\(?1:" (regexp-quote diary-nonmarking-symbol)
5857 "\\)" todos-date-pattern) lim t))
5859 (defun todos-date-string-matcher (lim)
5860 "Search for Todos date string within LIM for font-locking."
5862 (concat todos-date-string-start "\\(?1:" todos-date-pattern "\\)") lim t))
5864 (defun todos-time-string-matcher (lim)
5865 "Search for Todos time string within LIM for font-locking."
5866 (re-search-forward (concat todos-date-string-start todos-date-pattern
5867 " \\(?1:" diary-time-regexp "\\)") lim t))
5869 (defun todos-diary-expired-matcher (lim)
5870 "Search for expired diary item date within LIM for font-locking."
5871 (when (re-search-forward (concat "^\\(?:"
5872 (regexp-quote diary-nonmarking-symbol)
5873 "\\)?\\(?1:" todos-date-pattern "\\) \\(?2:"
5874 diary-time-regexp "\\)?") lim t)
5875 (let* ((date (match-string-no-properties 1))
5876 (time (match-string-no-properties 2))
5877 ;; Function days-between requires a non-empty time string.
5878 (date-time (concat date " " (or time "00:00"))))
5879 (or (and (not (string-match ".+day\\|\\*" date))
5880 (< (days-between date-time (current-time-string)) 0))
5881 (todos-diary-expired-matcher lim)))))
5883 (defun todos-done-string-matcher (lim)
5884 "Search for Todos done header within LIM for font-locking."
5885 (re-search-forward (concat todos-done-string-start
5889 (defun todos-comment-string-matcher (lim)
5890 "Search for Todos done comment within LIM for font-locking."
5891 (re-search-forward (concat "\\[\\(?1:" todos-comment-string "\\):")
5894 (defun todos-category-string-matcher-1 (lim)
5895 "Search for Todos category name within LIM for font-locking.
5896 This is for fontifying category and file names appearing in Todos
5897 Filtered Items mode following done items."
5898 (if (eq major-mode 'todos-filtered-items-mode)
5899 (re-search-forward (concat todos-done-string-start todos-date-pattern
5900 "\\(?: " diary-time-regexp
5901 ;; Use non-greedy operator to prevent
5902 ;; capturing possible following non-diary
5904 "\\)?] \\(?1:\\[.+?\\]\\)")
5907 (defun todos-category-string-matcher-2 (lim)
5908 "Search for Todos category name within LIM for font-locking.
5909 This is for fontifying category and file names appearing in Todos
5910 Filtered Items mode following todo (not done) items."
5911 (if (eq major-mode 'todos-filtered-items-mode)
5912 (re-search-forward (concat todos-date-string-start todos-date-pattern
5913 "\\(?: " diary-time-regexp "\\)?\\(?:"
5914 (regexp-quote todos-nondiary-end)
5915 "\\)? \\(?1:\\[.+\\]\\)")
5918 (defvar todos-nondiary-face 'todos-nondiary)
5919 (defvar todos-date-face 'todos-date)
5920 (defvar todos-time-face 'todos-time)
5921 (defvar todos-diary-expired-face 'todos-diary-expired)
5922 (defvar todos-done-sep-face 'todos-done-sep)
5923 (defvar todos-done-face 'todos-done)
5924 (defvar todos-comment-face 'todos-comment)
5925 (defvar todos-category-string-face 'todos-category-string)
5926 (defvar todos-font-lock-keywords
5928 '(todos-nondiary-marker-matcher 1 todos-nondiary-face t)
5929 '(todos-nondiary-marker-matcher 2 todos-nondiary-face t)
5930 ;; diary-lib.el uses font-lock-constant-face for diary-nonmarking-symbol.
5931 '(todos-diary-nonmarking-matcher 1 font-lock-constant-face t)
5932 '(todos-date-string-matcher 1 todos-date-face t)
5933 '(todos-time-string-matcher 1 todos-time-face t)
5934 '(todos-done-string-matcher 0 todos-done-face t)
5935 '(todos-comment-string-matcher 1 todos-comment-face t)
5936 '(todos-category-string-matcher-1 1 todos-category-string-face t t)
5937 '(todos-category-string-matcher-2 1 todos-category-string-face t t)
5938 '(todos-diary-expired-matcher 1 todos-diary-expired-face t)
5939 '(todos-diary-expired-matcher 2 todos-diary-expired-face t t)
5941 "Font-locking for Todos modes.")
5943 ;; -----------------------------------------------------------------------------
5945 ;; -----------------------------------------------------------------------------
5947 (defvar todos-insertion-map
5948 (let ((map (make-keymap)))
5949 (todos-insertion-key-bindings map)
5950 (define-key map "p" 'todos-copy-item)
5952 "Keymap for Todos mode item insertion commands.")
5954 (defvar todos-key-bindings-t
5956 ("Af" todos-find-archive)
5957 ("Ac" todos-choose-archive)
5958 ("Ad" todos-archive-done-item)
5959 ("Cv" todos-toggle-view-done-items)
5960 ("v" todos-toggle-view-done-items)
5961 ("Ca" todos-add-category)
5962 ("Cr" todos-rename-category)
5963 ("Cg" todos-merge-category)
5964 ("Cm" todos-move-category)
5965 ("Ck" todos-delete-category)
5966 ("Cts" todos-set-top-priorities-in-category)
5967 ("Cey" todos-edit-category-diary-inclusion)
5968 ("Cek" todos-edit-category-diary-nonmarking)
5969 ("Fa" todos-add-file)
5970 ("Ff" todos-find-filtered-items-file)
5971 ("FV" todos-toggle-view-done-only)
5972 ("V" todos-toggle-view-done-only)
5973 ("Ftt" todos-filter-top-priorities)
5974 ("Ftm" todos-filter-top-priorities-multifile)
5975 ("Fts" todos-set-top-priorities-in-file)
5976 ("Fyy" todos-filter-diary-items)
5977 ("Fym" todos-filter-diary-items-multifile)
5978 ("Frr" todos-filter-regexp-items)
5979 ("Frm" todos-filter-regexp-items-multifile)
5980 ("ee" todos-edit-item)
5981 ("em" todos-edit-multiline-item)
5982 ("edt" todos-edit-item-header)
5983 ("edc" todos-edit-item-date-from-calendar)
5984 ("eda" todos-edit-item-date-to-today)
5985 ("edn" todos-edit-item-date-day-name)
5986 ("edy" todos-edit-item-date-year)
5987 ("edm" todos-edit-item-date-month)
5988 ("edd" todos-edit-item-date-day)
5989 ("et" todos-edit-item-time)
5990 ("eyy" todos-edit-item-diary-inclusion)
5991 ("eyk" todos-edit-item-diary-nonmarking)
5992 ("ec" todos-edit-done-item-comment)
5993 ("d" todos-item-done)
5994 ("i" ,todos-insertion-map)
5995 ("k" todos-delete-item)
5996 ("m" todos-move-item)
5997 ("u" todos-item-undone)
5998 ([remap newline] newline-and-indent)
6000 "List of key bindings for Todos mode only.")
6002 (defvar todos-key-bindings-t+a+f
6004 ("C*" todos-mark-category)
6005 ("Cu" todos-unmark-category)
6006 ("Fh" todos-toggle-item-header)
6007 ("h" todos-toggle-item-header)
6008 ("Fe" todos-edit-file)
6009 ("FH" todos-toggle-item-highlighting)
6010 ("H" todos-toggle-item-highlighting)
6011 ("FN" todos-toggle-prefix-numbers)
6012 ("N" todos-toggle-prefix-numbers)
6013 ("PB" todos-print-buffer)
6014 ("PF" todos-print-buffer-to-file)
6015 ("b" todos-backward-category)
6016 ("d" todos-item-done)
6017 ("f" todos-forward-category)
6018 ("j" todos-jump-to-category)
6019 ("n" todos-next-item)
6020 ("p" todos-previous-item)
6025 "List of key bindings for Todos, Archive, and Filtered Items modes.")
6027 (defvar todos-key-bindings-t+a
6029 ("Fc" todos-show-categories-table)
6031 ("X" todos-clear-matches)
6032 ("*" todos-toggle-mark-item)
6034 "List of key bindings for Todos and Todos Archive modes.")
6036 (defvar todos-key-bindings-t+f
6038 ("l" todos-lower-item-priority)
6039 ("r" todos-raise-item-priority)
6040 ("#" todos-set-item-priority)
6042 "List of key bindings for Todos and Todos Filtered Items modes.")
6044 (defvar todos-mode-map
6045 (let ((map (make-keymap)))
6046 ;; Don't suppress digit keys, so they can supply prefix arguments.
6047 (suppress-keymap map)
6048 (dolist (kb todos-key-bindings-t)
6049 (define-key map (nth 0 kb) (nth 1 kb)))
6050 (dolist (kb todos-key-bindings-t+a+f)
6051 (define-key map (nth 0 kb) (nth 1 kb)))
6052 (dolist (kb todos-key-bindings-t+a)
6053 (define-key map (nth 0 kb) (nth 1 kb)))
6054 (dolist (kb todos-key-bindings-t+f)
6055 (define-key map (nth 0 kb) (nth 1 kb)))
6057 "Todos mode keymap.")
6059 (defvar todos-archive-mode-map
6060 (let ((map (make-sparse-keymap)))
6061 (suppress-keymap map)
6062 (dolist (kb todos-key-bindings-t+a+f)
6063 (define-key map (nth 0 kb) (nth 1 kb)))
6064 (dolist (kb todos-key-bindings-t+a)
6065 (define-key map (nth 0 kb) (nth 1 kb)))
6066 (define-key map "a" 'todos-jump-to-archive-category)
6067 (define-key map "u" 'todos-unarchive-items)
6069 "Todos Archive mode keymap.")
6071 (defvar todos-edit-mode-map
6072 (let ((map (make-sparse-keymap)))
6073 (define-key map "\C-x\C-q" 'todos-edit-quit)
6074 (define-key map [remap newline] 'newline-and-indent)
6076 "Todos Edit mode keymap.")
6078 (defvar todos-categories-mode-map
6079 (let ((map (make-sparse-keymap)))
6080 (suppress-keymap map)
6081 (define-key map "c" 'todos-sort-categories-alphabetically-or-numerically)
6082 (define-key map "t" 'todos-sort-categories-by-todo)
6083 (define-key map "y" 'todos-sort-categories-by-diary)
6084 (define-key map "d" 'todos-sort-categories-by-done)
6085 (define-key map "a" 'todos-sort-categories-by-archived)
6086 (define-key map "#" 'todos-set-category-number)
6087 (define-key map "l" 'todos-lower-category)
6088 (define-key map "r" 'todos-raise-category)
6089 (define-key map "n" 'todos-next-button)
6090 (define-key map "p" 'todos-previous-button)
6091 (define-key map [tab] 'todos-next-button)
6092 (define-key map [backtab] 'todos-previous-button)
6093 (define-key map "q" 'todos-quit)
6095 "Todos Categories mode keymap.")
6097 (defvar todos-filtered-items-mode-map
6098 (let ((map (make-sparse-keymap)))
6099 (suppress-keymap map)
6100 (dolist (kb todos-key-bindings-t+a+f)
6101 (define-key map (nth 0 kb) (nth 1 kb)))
6102 (dolist (kb todos-key-bindings-t+f)
6103 (define-key map (nth 0 kb) (nth 1 kb)))
6104 (define-key map "g" 'todos-go-to-source-item)
6105 (define-key map [remap newline] 'todos-go-to-source-item)
6107 "Todos Filtered Items mode keymap.")
6109 ;; FIXME: Is it worth having a menu and if so, which commands?
6110 ;; (easy-menu-define
6111 ;; todos-menu todos-mode-map "Todos Menu"
6114 ;; ["Next Item" todos-forward-item t]
6115 ;; ["Previous Item" todos-backward-item t]
6117 ;; ["Next Category" todos-forward-category t]
6118 ;; ["Previous Category" todos-backward-category t]
6119 ;; ["Jump to Category" todos-jump-to-category t]
6121 ;; ["Search Todos File" todos-search t]
6122 ;; ["Clear Highlighting on Search Matches" todos-category-done t])
6124 ;; ["List Current Categories" todos-show-categories-table t]
6125 ;; ;; ["List Categories Alphabetically" todos-display-categories-alphabetically t]
6126 ;; ["Turn Item Highlighting on/off" todos-toggle-item-highlighting t]
6127 ;; ["Turn Item Numbering on/off" todos-toggle-prefix-numbers t]
6128 ;; ["Turn Item Time Stamp on/off" todos-toggle-item-header t]
6129 ;; ["View/Hide Done Items" todos-toggle-view-done-items t]
6131 ;; ["View Diary Items" todos-filter-diary-items t]
6132 ;; ["View Top Priority Items" todos-filter-top-priorities t]
6133 ;; ["View Multifile Top Priority Items" todos-filter-top-priorities-multifile t]
6135 ;; ["Print Category" todos-print-buffer t])
6137 ;; ["Insert New Item" todos-insert-item t]
6138 ;; ["Insert Item Here" todos-insert-item-here t]
6139 ;; ("More Insertion Commands")
6140 ;; ["Edit Item" todos-edit-item t]
6141 ;; ["Edit Multiline Item" todos-edit-multiline-item t]
6142 ;; ["Edit Item Header" todos-edit-item-header t]
6143 ;; ["Edit Item Date" todos-edit-item-date t]
6144 ;; ["Edit Item Time" todos-edit-item-time t]
6146 ;; ["Lower Item Priority" todos-lower-item-priority t]
6147 ;; ["Raise Item Priority" todos-raise-item-priority t]
6148 ;; ["Set Item Priority" todos-set-item-priority t]
6149 ;; ["Move (Recategorize) Item" todos-move-item t]
6150 ;; ["Delete Item" todos-delete-item t]
6151 ;; ["Undo Done Item" todos-item-undone t]
6152 ;; ["Mark/Unmark Item for Diary" todos-toggle-item-diary-inclusion t]
6153 ;; ["Mark/Unmark Items for Diary" todos-edit-item-diary-inclusion t]
6154 ;; ["Mark & Hide Done Item" todos-item-done t]
6155 ;; ["Archive Done Items" todos-archive-category-done-items t]
6157 ;; ["Add New Todos File" todos-add-file t]
6158 ;; ["Add New Category" todos-add-category t]
6159 ;; ["Delete Current Category" todos-delete-category t]
6160 ;; ["Rename Current Category" todos-rename-category t]
6162 ;; ["Save Todos File" todos-save t]
6165 ;; ["Quit" todos-quit t]
6168 ;; -----------------------------------------------------------------------------
6169 ;;; Hook functions and mode definitions
6170 ;; -----------------------------------------------------------------------------
6172 (defun todos-show-current-file ()
6173 "Visit current instead of default Todos file with `todos-show'.
6174 This function is added to `pre-command-hook' when user option
6175 `todos-show-current-file' is set to non-nil."
6176 (setq todos-global-current-todos-file todos-current-todos-file))
6178 (defun todos-display-as-todos-file ()
6179 "Show Todos files correctly when visited from outside of Todos mode."
6180 (and (member this-command todos-visit-files-commands)
6181 (= (- (point-max) (point-min)) (buffer-size))
6182 (member major-mode '(todos-mode todos-archive-mode))
6183 (todos-category-select)))
6185 (defun todos-add-to-buffer-list ()
6186 "Add name of just visited Todos file to `todos-file-buffers'.
6187 This function is added to `find-file-hook' in Todos mode."
6188 (let ((filename (file-truename (buffer-file-name))))
6189 (when (member filename todos-files)
6190 (add-to-list 'todos-file-buffers filename))))
6192 (defun todos-update-buffer-list ()
6193 "Make current Todos mode buffer file car of `todos-file-buffers'.
6194 This function is added to `post-command-hook' in Todos mode."
6195 (let ((filename (file-truename (buffer-file-name))))
6196 (unless (eq (car todos-file-buffers) filename)
6197 (setq todos-file-buffers
6198 (cons filename (delete filename todos-file-buffers))))))
6200 (defun todos-reset-global-current-todos-file ()
6201 "Update the value of `todos-global-current-todos-file'.
6202 This becomes the latest existing Todos file or, if there is none,
6203 the value of `todos-default-todos-file'.
6204 This function is added to `kill-buffer-hook' in Todos mode."
6205 (let ((filename (file-truename (buffer-file-name))))
6206 (setq todos-file-buffers (delete filename todos-file-buffers))
6207 (setq todos-global-current-todos-file
6208 (or (car todos-file-buffers)
6209 (todos-absolute-file-name todos-default-todos-file)))))
6211 (defun todos-reset-and-enable-done-separator ()
6212 "Show resized done items separator overlay after window change.
6213 Added to `window-configuration-change-hook' in `todos-mode'."
6214 (when (= 1 (length todos-done-separator-string))
6215 (let ((sep todos-done-separator))
6216 (setq todos-done-separator (todos-done-separator))
6217 (save-match-data (todos-reset-done-separator sep)))))
6219 (defun todos-modes-set-1 ()
6220 "Make some settings that apply to multiple Todos modes."
6221 (setq-local font-lock-defaults '(todos-font-lock-keywords t))
6222 (setq-local tab-width todos-indent-to-here)
6223 (setq-local indent-line-function 'todos-indent)
6224 (when todos-wrap-lines
6226 (setq wrap-prefix (make-string todos-indent-to-here 32))))
6228 (defun todos-modes-set-2 ()
6229 "Make some settings that apply to multiple Todos modes."
6230 (add-to-invisibility-spec 'todos)
6231 (setq buffer-read-only t)
6232 (when (boundp 'hl-line-range-function)
6233 (setq-local hl-line-range-function
6234 (lambda() (save-excursion
6235 (when (todos-item-end)
6236 (cons (todos-item-start)
6237 (todos-item-end))))))))
6239 (defun todos-modes-set-3 ()
6240 "Make some settings that apply to multiple Todos modes."
6241 (setq-local todos-categories (todos-set-categories))
6242 (setq-local todos-category-number 1)
6243 (add-hook 'find-file-hook 'todos-display-as-todos-file nil t))
6245 (put 'todos-mode 'mode-class 'special)
6247 (define-derived-mode todos-mode special-mode "Todos"
6248 "Major mode for displaying, navigating and editing Todo lists.
6251 ;; (easy-menu-add todos-menu)
6255 ;; Initialize todos-current-todos-file.
6256 (when (member (file-truename (buffer-file-name))
6257 (funcall todos-files-function))
6258 (setq-local todos-current-todos-file (file-truename (buffer-file-name))))
6259 (setq-local todos-show-done-only nil)
6260 (setq-local todos-categories-with-marks nil)
6261 (add-hook 'find-file-hook 'todos-add-to-buffer-list nil t)
6262 (add-hook 'post-command-hook 'todos-update-buffer-list nil t)
6263 (when todos-show-current-file
6264 (add-hook 'pre-command-hook 'todos-show-current-file nil t))
6265 (add-hook 'window-configuration-change-hook
6266 'todos-reset-and-enable-done-separator nil t)
6267 (add-hook 'kill-buffer-hook 'todos-reset-global-current-todos-file nil t))
6269 (put 'todos-archive-mode 'mode-class 'special)
6271 ;; If todos-mode is parent, all todos-mode key bindings appear to be
6272 ;; available in todos-archive-mode (e.g. shown by C-h m).
6273 (define-derived-mode todos-archive-mode special-mode "Todos-Arch"
6274 "Major mode for archived Todos categories.
6276 \\{todos-archive-mode-map}"
6280 (setq-local todos-current-todos-file (file-truename (buffer-file-name)))
6281 (setq-local todos-show-done-only t))
6283 (defun todos-mode-external-set ()
6284 "Set `todos-categories' externally to `todos-current-todos-file'."
6285 (setq-local todos-current-todos-file todos-global-current-todos-file)
6286 (let ((cats (with-current-buffer
6287 ;; Can't use find-buffer-visiting when
6288 ;; `todos-show-categories-table' is called on first
6289 ;; invocation of `todos-show', since there is then
6290 ;; no buffer visiting the current file.
6291 (find-file-noselect todos-current-todos-file 'nowarn)
6292 (or todos-categories
6293 ;; In Todos Edit mode todos-categories is now nil
6294 ;; since it uses same buffer as Todos mode but
6295 ;; doesn't have the latter's local variables.
6297 (goto-char (point-min))
6298 (read (buffer-substring-no-properties
6299 (line-beginning-position)
6300 (line-end-position))))))))
6301 (setq-local todos-categories cats)))
6303 (define-derived-mode todos-edit-mode text-mode "Todos-Ed"
6304 "Major mode for editing multiline Todo items.
6306 \\{todos-edit-mode-map}"
6308 (todos-mode-external-set)
6309 (setq buffer-read-only nil))
6311 (put 'todos-categories-mode 'mode-class 'special)
6313 (define-derived-mode todos-categories-mode special-mode "Todos-Cats"
6314 "Major mode for displaying and editing Todos categories.
6316 \\{todos-categories-mode-map}"
6317 (todos-mode-external-set))
6319 (put 'todos-filtered-items-mode 'mode-class 'special)
6321 (define-derived-mode todos-filtered-items-mode special-mode "Todos-Fltr"
6322 "Mode for displaying and reprioritizing top priority Todos.
6324 \\{todos-filtered-items-mode-map}"
6326 (todos-modes-set-2))
6328 (add-to-list 'auto-mode-alist '("\\.todo\\'" . todos-mode))
6329 (add-to-list 'auto-mode-alist '("\\.toda\\'" . todos-archive-mode))
6330 (add-to-list 'auto-mode-alist '("\\.tod[tyr]\\'" . todos-filtered-items-mode))
6332 ;; -----------------------------------------------------------------------------
6335 ;;; todos.el ends here