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