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