* todos.el: Fixes and improvements related to item relocation.
[bpt/emacs.git] / lisp / calendar / todos.el
index 5c07f62..30c64ef 100644 (file)
@@ -71,14 +71,14 @@ makes it return the value of the variable `todos-archives'."
 This lacks the extension and directory components."
   (file-name-sans-extension (file-name-nondirectory file)))
 
-(defcustom todos-default-todos-file (car (funcall todos-files-function))
+(defcustom todos-default-todos-file (todos-short-file-name
+                                    (car (funcall todos-files-function)))
   "Todos file visited by first session invocation of `todos-show'."
   :type `(radio ,@(mapcar (lambda (f) (list 'const f))
                          (mapcar 'todos-short-file-name
                                  (funcall todos-files-function))))
   :group 'todos)
 
-;; FIXME: is there a better alternative to this?
 (defun todos-reevaluate-default-file-defcustom ()
   "Reevaluate defcustom of `todos-default-todos-file'.
 Called after adding or deleting a Todos file."
@@ -104,6 +104,23 @@ Otherwise, `todos-show' always visits `todos-default-todos-file'."
       (add-hook 'pre-command-hook 'todos-show-current-file nil t)
     (remove-hook 'pre-command-hook 'todos-show-current-file t)))
 
+(defcustom todos-category-completions-files nil
+  "List of files for building `todos-read-category' completions."
+  :type `(set ,@(mapcar (lambda (f) (list 'const f))
+                       (mapcar 'todos-short-file-name
+                               (funcall todos-files-function))))
+  :group 'todos)
+
+(defun todos-reevaluate-category-completions-files-defcustom ()
+  "Reevaluate defcustom of `todos-category-completions-files'.
+Called after adding or deleting a Todos file."
+  (eval (defcustom todos-category-completions-files nil
+  "List of files for building `todos-read-category' completions."
+         :type `(set ,@(mapcar (lambda (f) (list 'const f))
+                               (mapcar 'todos-short-file-name
+                                       (funcall todos-files-function))))
+         :group 'todos)))
+
 (defcustom todos-visit-files-commands (list 'find-file 'dired-find-file)
   "List of file finding commands for `todos-display-as-todos-file'.
 Invoking these commands to visit a Todos or Todos Archive file
@@ -122,9 +139,13 @@ displayed correctly."
   :type 'string
   :group 'todos)
 
-(defcustom todos-display-categories-first nil
-  "Non-nil to display category list on first visit to a Todos file."
-  :type 'boolean
+(defcustom todos-show-first 'first
+  "What action to take on first use of `todos-show' on a file."
+  :type '(choice (const :tag "Show first category" first)
+                (const :tag "Show table of categories" table)
+                (const :tag "Show top priorities" top)
+                (const :tag "Show diary items" diary)
+                (const :tag "Show regexp items" regexp))
   :group 'todos)
 
 (defcustom todos-completion-ignore-case nil
@@ -171,7 +192,13 @@ todo-mode.el."
 
 (defcustom todos-prefix ""
   "String prefixed to todo items for visual distinction."
-  :type 'string
+  :type '(string :validate
+                (lambda (widget)
+                  (when (string= (widget-value widget) todos-item-mark)
+                    (widget-put
+                     widget :error
+                     "Invalid value: must be distinct from `todos-item-mark'")
+                    widget)))
   :initialize 'custom-initialize-default
   :set 'todos-reset-prefix
   :group 'todos-mode-display)
@@ -187,23 +214,30 @@ These reflect the priorities of the items in each category."
 (defun todos-reset-prefix (symbol value)
   "The :set function for `todos-prefix' and `todos-number-priorities'."
   (let ((oldvalue (symbol-value symbol))
-       (files (append todos-files todos-archives)))
+       (files todos-file-buffers))
     (custom-set-default symbol value)
     (when (not (equal value oldvalue))
       (dolist (f files)
        (with-current-buffer (find-file-noselect f)
-         (save-window-excursion
-           (todos-show)
-           (save-excursion
-             (widen)
-             (goto-char (point-min))
-             (while (not (eobp))
-               (remove-overlays (point) (point)); 'before-string prefix)
-               (forward-line)))
-           ;; Activate the new setting (save-restriction does not help).
-           (save-excursion (todos-category-select))))))))
+         ;; Activate the new setting in the current category.
+         (save-excursion (todos-category-select)))))))
+
+(defcustom todos-item-mark "*"
+  "String used to mark items.
+To ensure item marking works, change the value of this option
+only when no items are marked."
+  :type '(string :validate
+                (lambda (widget)
+                  (when (string= (widget-value widget) todos-prefix)
+                    (widget-put
+                     widget :error
+                     "Invalid value: must be distinct from `todos-prefix'")
+                    widget)))
+  :set (lambda (symbol value)
+        (custom-set-default symbol (propertize value 'face 'todos-mark)))
+  :group 'todos-mode-display)
 
-(defcustom todos-done-separator-string "_"
+(defcustom todos-done-separator-string "="
   "String for generating `todos-done-separator'.
 
 If the string consists of a single character,
@@ -223,9 +257,14 @@ the value of `todos-done-separator'."
        (files todos-file-buffers)
        (sep todos-done-separator))
     (custom-set-default symbol value)
-    (setq todos-done-separator (todos-done-separator))
-    (when (= 1 (length value))
-      (todos-reset-done-separator sep))))
+    (when (not (equal value oldvalue))
+      (dolist (f files)
+       (with-current-buffer (find-file-noselect f)
+         (let (buffer-read-only)
+           (setq todos-done-separator (todos-done-separator))
+           (when (= 1 (length value))
+             (todos-reset-done-separator sep)))
+         (todos-category-select))))))
 
 (defcustom todos-done-string "DONE "
   "Identifying string appended to the front of done todos items."
@@ -360,8 +399,6 @@ The amount of indentation is given by user option
   (unless (member '(continuation) fringe-indicator-alist)
     (push '(continuation) fringe-indicator-alist)))
 
-;; FIXME: :set function to refill items with hard newlines and to immediately
-;; update wrapped prefix display
 (defcustom todos-indent-to-here 6
   "Number of spaces `todos-line-wrapping-function' indents to."
   :type '(integer :validate
@@ -461,26 +498,6 @@ current time, if nil, they include it."
   :version "24.2"
   :group 'todos)
 
-(defcustom todos-filtered-items-buffer "Todos filtered items"
-  "Initial name of buffer in Todos Filter Items mode."
-  :type 'string
-  :group 'todos-filtered)
-
-(defcustom todos-top-priorities-buffer "Todos top priorities"
-  "Buffer type string for `todos-filtered-buffer-name'."
-  :type 'string
-  :group 'todos-filtered)
-
-(defcustom todos-diary-items-buffer "Todos diary items"
-  "Buffer type string for `todos-filtered-buffer-name'."
-  :type 'string
-  :group 'todos-filtered)
-
-(defcustom todos-regexp-items-buffer "Todos regexp items"
-  "Buffer type string for `todos-filtered-buffer-name'."
-  :type 'string
-  :group 'todos-filtered)
-
 (defcustom todos-priorities-rules nil
   "List of rules giving how many items `todos-top-priorities' shows.
 This variable should be set interactively by
@@ -493,9 +510,11 @@ number of top priority items for each category in that file, and
 ALIST, when non-nil, consists of conses of a category name in
 FILE and a number specifying the default number of top priority
 items in that category, which overrides NUM."
-  :type 'list
+  :type 'sexp
   :group 'todos-filtered)
 
+;; FIXME: rename to todos-top-priorities AFTER renaming command
+;; todos-top-priorities to todos-filter-top-priorities
 (defcustom todos-show-priorities 1
   "Default number of top priorities shown by `todos-top-priorities'."
   :type 'integer
@@ -508,7 +527,6 @@ items in that category, which overrides NUM."
                                (funcall todos-files-function))))
   :group 'todos-filtered)
 
-;; FIXME: is there a better alternative to this?
 (defun todos-reevaluate-filter-files-defcustom ()
   "Reevaluate defcustom of `todos-filter-files'.
 Called after adding or deleting a Todos file."
@@ -576,7 +594,7 @@ categories display according to priority."
   :group 'todos-categories)
 
 ;; ---------------------------------------------------------------------------
-;;; Faces and font-lock matcher functions
+;;; Faces and font locking
 
 (defgroup todos-faces nil
   "Faces for the Todos modes."
@@ -595,7 +613,24 @@ categories display according to priority."
     (((class color) (min-colors 16) (background dark)) (:foreground "Aquamarine"))
     (((class color) (min-colors 8)) (:foreground "magenta"))
     (t (:weight bold :underline t)))
-  "Face for Todos prefix string."
+  "Face for Todos prefix or numerical priority string."
+  :group 'todos-faces)
+
+(defface todos-top-priority
+  ;; bold font-lock-comment-face
+  '((default :weight bold)
+    (((class grayscale) (background light)) :foreground "DimGray" :slant italic)
+    (((class grayscale) (background dark)) :foreground "LightGray" :slant italic)
+    (((class color) (min-colors 88) (background light)) :foreground "Firebrick")
+    (((class color) (min-colors 88) (background dark)) :foreground "chocolate1")
+    (((class color) (min-colors 16) (background light)) :foreground "red")
+    (((class color) (min-colors 16) (background dark)) :foreground "red1")
+    (((class color) (min-colors 8) (background light)) :foreground "red")
+    (((class color) (min-colors 8) (background dark)) :foreground "yellow")
+    (t :slant italic))
+  "Face for top priority Todos item numerical priority string.
+The item's priority number string has this face if the number is
+less than or equal the category's top priority setting."
   :group 'todos-faces)
 
 (defface todos-mark
@@ -693,14 +728,19 @@ categories display according to priority."
   :group 'todos-faces)
 
 (defface todos-diary-expired
-  ;; '((t :inherit font-lock-warning-face))
-  '((((class color)
-      (min-colors 16))
-     (:weight bold :foreground "DarkOrange"))
-    (((class color))
-     (:weight bold :foreground "yellow"))
-    (t
-     (:weight bold)))
+  ;; Doesn't contrast enough with todos-date (= diary) face.
+  ;; ;; '((t :inherit warning))
+  ;; '((default :weight bold)
+  ;;   (((class color) (min-colors 16)) :foreground "DarkOrange")
+  ;;   (((class color)) :foreground "yellow"))
+  ;; bold font-lock-function-name-face
+  '((default :weight bold)
+    (((class color) (min-colors 88) (background light)) :foreground "Blue1")
+    (((class color) (min-colors 88) (background dark))  :foreground "LightSkyBlue")
+    (((class color) (min-colors 16) (background light)) :foreground "Blue")
+    (((class color) (min-colors 16) (background dark))  :foreground "LightSkyBlue")
+    (((class color) (min-colors 8)) :foreground "blue")
+    (t :inverse-video t))
   "Face for expired dates of diary items."
   :group 'todos-faces)
 (defvar todos-diary-expired-face 'todos-diary-expired)
@@ -717,79 +757,81 @@ categories display according to priority."
   :group 'todos-faces)
 (defvar todos-time-face 'todos-time)
 
+(defface todos-nondiary
+  ;; '((t :inherit font-lock-type-face))
+  '((((class grayscale) (background light)) :foreground "Gray90" :weight bold)
+    (((class grayscale) (background dark))  :foreground "DimGray" :weight bold)
+    (((class color) (min-colors 88) (background light)) :foreground "ForestGreen")
+    (((class color) (min-colors 88) (background dark))  :foreground "PaleGreen")
+    (((class color) (min-colors 16) (background light)) :foreground "ForestGreen")
+    (((class color) (min-colors 16) (background dark))  :foreground "PaleGreen")
+    (((class color) (min-colors 8)) :foreground "green")
+    (t :weight bold :underline t))
+  "Face for non-diary markers around todo item date/time header."
+  :group 'todos-faces)
+(defvar todos-nondiary-face 'todos-nondiary)
+
+(defface todos-category-string
+    ;; '((t :inherit font-lock-type-face))
+  '((((class grayscale) (background light)) :foreground "Gray90" :weight bold)
+    (((class grayscale) (background dark))  :foreground "DimGray" :weight bold)
+    (((class color) (min-colors 88) (background light)) :foreground "ForestGreen")
+    (((class color) (min-colors 88) (background dark))  :foreground "PaleGreen")
+    (((class color) (min-colors 16) (background light)) :foreground "ForestGreen")
+    (((class color) (min-colors 16) (background dark))  :foreground "PaleGreen")
+    (((class color) (min-colors 8)) :foreground "green")
+    (t :weight bold :underline t))
+  "Face for category file names in Todos Filtered Item."
+  :group 'todos-faces)
+(defvar todos-category-string-face 'todos-category-string)
+
 (defface todos-done
-  ;; '((t :inherit font-lock-comment-face))
-  '((((class grayscale)
-      (background light))
-     (:slant italic :weight bold :foreground "DimGray"))
-    (((class grayscale)
-      (background dark))
-     (:slant italic :weight bold :foreground "LightGray"))
-    (((class color)
-      (min-colors 88)
-      (background light))
-     (:foreground "Firebrick"))
-    (((class color)
-      (min-colors 88)
-      (background dark))
-     (:foreground "chocolate1"))
-    (((class color)
-      (min-colors 16)
-      (background light))
-     (:foreground "red"))
-    (((class color)
-      (min-colors 16)
-      (background dark))
-     (:foreground "red1"))
-    (((class color)
-      (min-colors 8)
-      (background light))
-     (:foreground "red"))
-    (((class color)
-      (min-colors 8)
-      (background dark))
-     (:foreground "yellow"))
-    (t
-     (:slant italic :weight bold)))
+  ;; '((t :inherit font-lock-keyword-face))
+  '((((class grayscale) (background light)) :foreground "LightGray" :weight bold)
+    (((class grayscale) (background dark))  :foreground "DimGray" :weight bold)
+    (((class color) (min-colors 88) (background light)) :foreground "Purple")
+    (((class color) (min-colors 88) (background dark))  :foreground "Cyan1")
+    (((class color) (min-colors 16) (background light)) :foreground "Purple")
+    (((class color) (min-colors 16) (background dark))  :foreground "Cyan")
+    (((class color) (min-colors 8)) :foreground "cyan" :weight bold)
+    (t :weight bold))
   "Face for done Todos item header string."
   :group 'todos-faces)
 (defvar todos-done-face 'todos-done)
 
 (defface todos-comment
-  '((t :inherit todos-done))
+  ;; '((t :inherit font-lock-comment-face))
+  '((((class grayscale) (background light))
+     :foreground "DimGray" :weight bold :slant italic)
+    (((class grayscale) (background dark))
+     :foreground "LightGray" :weight bold :slant italic)
+    (((class color) (min-colors 88) (background light))
+     :foreground "Firebrick")
+    (((class color) (min-colors 88) (background dark))
+     :foreground "chocolate1")
+    (((class color) (min-colors 16) (background light))
+     :foreground "red")
+    (((class color) (min-colors 16) (background dark))
+     :foreground "red1")
+    (((class color) (min-colors 8) (background light))
+     :foreground "red")
+    (((class color) (min-colors 8) (background dark))
+     :foreground "yellow")
+    (t :weight bold :slant italic))
   "Face for comments appended to done Todos items."
   :group 'todos-faces)
 (defvar todos-comment-face 'todos-comment)
 
 (defface todos-done-sep
-  ;; '((t :inherit font-lock-type-face))
-  '((((class grayscale)
-      (background light))
-     (:weight bold :foreground "Gray90"))
-    (((class grayscale)
-      (background dark))
-     (:weight bold :foreground "DimGray"))
-    (((class color)
-      (min-colors 88)
-      (background light))
-     (:foreground "ForestGreen"))
-    (((class color)
-      (min-colors 88)
-      (background dark))
-     (:foreground "PaleGreen"))
-    (((class color)
-      (min-colors 16)
-      (background light))
-     (:foreground "ForestGreen"))
-    (((class color)
-      (min-colors 16)
-      (background dark))
-     (:foreground "PaleGreen"))
-    (((class color)
-      (min-colors 8))
-     (:foreground "green"))
-    (t
-     (:underline t :weight bold)))
+  ;; '((t :inherit font-lock-builtin-face))
+  '((((class grayscale) (background light)) :foreground "LightGray" :weight bold)
+    (((class grayscale) (background dark))  :foreground "DimGray" :weight bold)
+    (((class color) (min-colors 88) (background light)) :foreground "dark slate blue")
+    (((class color) (min-colors 88) (background dark))  :foreground "LightSteelBlue")
+    (((class color) (min-colors 16) (background light)) :foreground "Orchid")
+    (((class color) (min-colors 16) (background dark)) :foreground "LightSteelBlue")
+    (((class color) (min-colors 8)) :foreground "blue" :weight bold)
+    (t :weight bold))
   "Face for separator string bewteen done and not done Todos items."
   :group 'todos-faces)
 (defvar todos-done-sep-face 'todos-done-sep)
@@ -854,8 +896,8 @@ categories display according to priority."
 
 (defun todos-category-string-matcher-1 (lim)
   "Search for Todos category name within LIM for font-locking.
-This is for fontifying category names appearing in Todos filter
-mode following done items."
+This is for fontifying category and file names appearing in Todos
+Filtered Items mode following done items."
   (if (eq major-mode 'todos-filtered-items-mode)
       (re-search-forward (concat todos-done-string-start todos-date-pattern
                                 "\\(?: " diary-time-regexp
@@ -867,8 +909,8 @@ mode following done items."
 
 (defun todos-category-string-matcher-2 (lim)
   "Search for Todos category name within LIM for font-locking.
-This is for fontifying category names appearing in Todos filter
-mode following todo (not done) items."
+This is for fontifying category and file names appearing in Todos
+Filtered Items mode following todo (not done) items."
   (if (eq major-mode 'todos-filtered-items-mode)
       (re-search-forward (concat todos-date-string-start todos-date-pattern
                                 "\\(?: " diary-time-regexp "\\)?\\(?:"
@@ -878,17 +920,16 @@ mode following todo (not done) items."
 
 (defvar todos-font-lock-keywords
   (list
-   '(todos-nondiary-marker-matcher 1 todos-done-sep-face t)
-   '(todos-nondiary-marker-matcher 2 todos-done-sep-face t)
-   ;; This is the face used by diary-lib.el.
+   '(todos-nondiary-marker-matcher 1 todos-nondiary-face t)
+   '(todos-nondiary-marker-matcher 2 todos-nondiary-face t)
+   ;; diary-lib.el uses font-lock-constant-face for diary-nonmarking-symbol.
    '(todos-diary-nonmarking-matcher 1 font-lock-constant-face t)
    '(todos-date-string-matcher 1 todos-date-face t)
    '(todos-time-string-matcher 1 todos-time-face t)
    '(todos-done-string-matcher 0 todos-done-face t)
-   '(todos-comment-string-matcher 1 todos-done-face t)
-   ;; '(todos-category-string-matcher 1 todos-done-sep-face t)
-   '(todos-category-string-matcher-1 1 todos-done-sep-face t t)
-   '(todos-category-string-matcher-2 1 todos-done-sep-face t t)
+   '(todos-comment-string-matcher 1 todos-comment-face t)
+   '(todos-category-string-matcher-1 1 todos-category-string-face t t)
+   '(todos-category-string-matcher-2 1 todos-category-string-face t t)
    '(todos-diary-expired-matcher 1 todos-diary-expired-face t)
    '(todos-diary-expired-matcher 2 todos-diary-expired-face t t)
    )
@@ -935,8 +976,9 @@ the value of `todos-default-todos-file'.
 This function is added to `kill-buffer-hook' in Todos mode."
   (let ((filename (file-truename (buffer-file-name))))
     (setq todos-file-buffers (delete filename todos-file-buffers))
-    (setq todos-global-current-todos-file (or (car todos-file-buffers)
-                                             todos-default-todos-file))))
+    (setq todos-global-current-todos-file
+         (or (car todos-file-buffers)
+             (todos-absolute-file-name todos-default-todos-file)))))
 
 (defvar todos-categories nil
   "Alist of categories in the current Todos file.
@@ -952,34 +994,18 @@ the Diary, of done items and of archived items.")
   "Variable holding the number of the current Todos category.
 Todos categories are numbered starting from 1.")
 
-(defvar todos-first-visit t
-  "Non-nil if first display of this file in the current session.
-See `todos-display-categories-first'.")
-
 (defvar todos-show-done-only nil
   "If non-nil display only done items in current category.
 Set by the command `todos-show-done-only' and used by
 `todos-category-select'.")
 
 (defun todos-reset-and-enable-done-separator ()
-  "Show resized catagory separator overlay after window size change.
+  "Show resized done items separator overlay after window change.
 Added to `window-configuration-change-hook' in `todos-mode'."
   (when (= 1 (length todos-done-separator-string))
     (let ((sep todos-done-separator))
       (setq todos-done-separator (todos-done-separator))
-      (save-match-data (todos-reset-done-separator sep)))
-    ;; FIXME: If this is called while the separator overlay is shown, the
-    ;; separator with deleted overlay becomes visible when waiting for user
-    ;; input and remains so.  The following workaround prevents this, but it
-    ;; also prevents widening category when edebugging todos.el.
-    ;; (save-excursion
-    ;;   (goto-char (point-min))
-    ;;   (when (re-search-forward todos-done-string-start nil t)
-    ;;         (let ((todos-show-with-done nil))
-    ;;           (todos-category-select))
-    ;;         (let ((todos-show-with-done t))
-    ;;           (todos-category-select))))
-    ))
+      (save-match-data (todos-reset-done-separator sep)))))
 
 ;; ---------------------------------------------------------------------------
 ;;; Global variables and helper functions for files and buffers
@@ -990,6 +1016,11 @@ Added to `window-configuration-change-hook' in `todos-mode'."
 (defvar todos-archives (funcall todos-files-function t)
   "List of truenames of user's Todos archives.")
 
+(defvar todos-visited nil
+  "List of Todos files visited in this session by `todos-show'.
+Used to determine initial display according to the value of
+`todos-show-first'.")
+
 (defvar todos-file-buffers nil
   "List of file names of live Todos mode buffers.")
 
@@ -1005,7 +1036,10 @@ users option `todos-show-current-file' is non-nil).")
                      (symbol-value 'todos-default-todos-file))
   (todos-reevaluate-default-file-defcustom)
   (custom-set-default 'todos-filter-files (symbol-value 'todos-filter-files))
-  (todos-reevaluate-filter-files-defcustom))
+  (todos-reevaluate-filter-files-defcustom)
+  (custom-set-default 'todos-category-completions-files
+                     (symbol-value 'todos-category-completions-files))
+  (todos-reevaluate-category-completions-files-defcustom))
 
 (defvar todos-edit-buffer "*Todos Edit*"
   "Name of current buffer in Todos Edit mode.")
@@ -1016,6 +1050,20 @@ users option `todos-show-current-file' is non-nil).")
 (defvar todos-print-buffer "*Todos Print*"
   "Name of buffer containing printable Todos text.")
 
+(defun todos-absolute-file-name (name &optional type)
+  "Return the absolute file name of short Todos file NAME.
+With TYPE `archive' or `top' return the absolute file name of the
+short Todos Archive or Top Priorities file name, respectively."
+  ;; NOP if there is no Todos file yet (i.e. don't concatenate nil).
+  (when name
+    (file-truename
+     (concat todos-files-directory name
+            (cond ((eq type 'archive) ".toda")
+                  ((eq type 'top) ".todt")
+                  ((eq type 'diary) ".tody")
+                  ((eq type 'regexp) ".todr")
+                  (t ".todo"))))))
+
 (defun todos-check-format ()
   "Signal an error if the current Todos file is ill-formatted.
 Otherwise return t.  The error message gives the line number
@@ -1024,9 +1072,11 @@ where the invalid formatting was found."
     (save-restriction
       (widen)
       (goto-char (point-min))
-      ;; Check for `todos-categories' sexp as the first line
-      (let ((cats (prin1-to-string todos-categories)))
-       (unless (looking-at (regexp-quote cats))
+      (let ((cats (prin1-to-string todos-categories))
+           (sexp (buffer-substring-no-properties (line-beginning-position)
+                                                 (line-end-position))))
+       ;; Check for `todos-categories' sexp as the first line
+       (unless (string= sexp cats)
          (error "Invalid or missing todos-categories sexp")))
       (forward-line)
       (let ((legit (concat "\\(^" (regexp-quote todos-category-beg) "\\)"
@@ -1084,9 +1134,17 @@ number as its value."
 (defun todos-done-separator ()
   "Return string used as value of variable `todos-done-separator'."
   (let ((sep todos-done-separator-string))
-    (if (= 1 (length sep))
-       (make-string (window-width) (string-to-char sep))
-      todos-done-separator-string)))
+    (propertize (if (= 1 (length sep))
+                   ;; If separator's length is window-width, then
+                   ;; with non-nil todos-wrap-lines and
+                   ;; todos-wrap-and-indent as value of
+                   ;; todos-line-wrapping-function, an indented empty
+                   ;; line appears between the separator and the
+                   ;; first done item.
+                   (make-string (1- (window-width)) (string-to-char sep))
+                   ;; (make-string (window-width) (string-to-char sep))
+                 todos-done-separator-string)
+               'face 'todos-done-sep)))
 
 (defvar todos-done-separator (todos-done-separator)
   "String used to visually separate done from not done items.
@@ -1104,15 +1162,60 @@ done items are shown.  Its value is determined by user option
              (concat "\n\\(" (regexp-quote todos-category-done) "\\)") nil t)
        (let* ((beg (match-beginning 1))
               (end (match-end 0))
-              (ovs (overlays-at beg))
-              old-sep new-sep)
-         (and ovs
-              (setq old-sep (overlay-get (car ovs) 'display))
-              (string= old-sep sep)
-              (delete-overlay (car ovs))
-              (setq new-sep (make-overlay beg end))
-              (overlay-put new-sep 'display
-                           todos-done-separator)))))))
+              (ov (progn (goto-char beg)
+                         (todos-get-overlay 'separator)))
+              (old-sep (when ov (overlay-get ov 'display)))
+              new-ov)
+         (when old-sep
+           (unless (string= old-sep sep)
+             (setq new-ov (make-overlay beg end))
+             (overlay-put new-ov 'todos 'separator)
+             (overlay-put new-ov 'display todos-done-separator)
+             (delete-overlay ov))))))))
+
+(defun todos-category-completions ()
+  "Return a list of completions for `todos-read-category'.
+Each element of the list is a cons of a category name and the
+file or list of files (as short file names) it is in.  The files
+are the current (or else the default) Todos file plus all other
+Todos files named in `todos-category-completions-files'."
+  (let* ((curfile (or todos-current-todos-file
+                     (and todos-show-current-file
+                          todos-global-current-todos-file)
+                     (todos-absolute-file-name todos-default-todos-file)))
+        (files (or (mapcar 'todos-absolute-file-name
+                           todos-category-completions-files)
+                   (list curfile)))
+        listall listf)
+    ;; If file was just added, it has no category completions.
+    (unless (zerop (buffer-size (find-buffer-visiting curfile)))
+      (add-to-list 'files curfile)
+      (dolist (f files listall)
+       (with-current-buffer (find-file-noselect f 'nowarn)
+         ;; Ensure category is properly displayed in case user
+         ;; switches to file via a non-Todos command.  And if done
+         ;; items in category are visible, keep them visible.
+         (let ((done todos-show-with-done))
+           (when (> (buffer-size) (- (point-max) (point-min)))
+             (save-excursion
+               (goto-char (point-min))
+               (setq done (re-search-forward todos-done-string-start nil t))))
+           (let ((todos-show-with-done done))
+             (todos-category-select)))
+         (save-excursion
+           (save-restriction
+             (widen)
+             (goto-char (point-min))
+             (setq listf (read (buffer-substring-no-properties
+                                (line-beginning-position)
+                                (line-end-position)))))))
+       (mapc (lambda (elt) (let* ((cat (car elt))
+                                  (la-elt (assoc cat listall)))
+                             (if la-elt
+                                 (setcdr la-elt (append (list (cdr la-elt))
+                                                        (list f)))
+                               (push (cons cat f) listall))))
+             listf)))))
 
 (defun todos-category-select ()
   "Display the current category correctly."
@@ -1149,12 +1252,12 @@ done items are shown.  Its value is determined by user option
        ;; Make display overlay for done items separator string, unless there
        ;; already is one.
        (let* ((done-sep todos-done-separator)
-              (ovs (overlays-at done-sep-start))
-              ov-sep)
-         ;; There should never be more than one overlay here, so car suffices.
-         (unless (and ovs (string= (overlay-get (car ovs) 'display) done-sep))
-           (setq ov-sep (make-overlay done-sep-start done-end))
-           (overlay-put ov-sep 'display done-sep))))
+              (ov (progn (goto-char done-sep-start)
+                         (todos-get-overlay 'separator))))
+         (unless ov
+           (setq ov (make-overlay done-sep-start done-end))
+           (overlay-put ov 'todos 'separator)
+           (overlay-put ov 'display done-sep))))
       (narrow-to-region (point-min) done-start)
       ;; Loading this from todos-mode, or adding it to the mode hook, causes
       ;; Emacs to hang in todos-item-start, at (looking-at todos-item-start).
@@ -1209,15 +1312,8 @@ With nil or omitted CATEGORY, default to the current category."
        (goto-char (point-min))
        (if (looking-at (concat "^" (regexp-quote todos-category-beg)))
            (progn (newline) (goto-char (point-min)) ; Make space for sexp.
-                  ;; No categories sexp means the first item was just added
-                  ;; to this file, so have to initialize Todos file and
-                  ;; categories variables in order e.g. to enable categories
-                  ;; display.
-                  (setq todos-default-todos-file (buffer-file-name))
                   (setq todos-categories (todos-make-categories-list t)))
-         ;; With empty buffer (e.g. with new archive in
-         ;; `todos-move-category') `kill-line' signals end of buffer.
-         (kill-region (line-beginning-position) (line-end-position)))
+         (delete-region (line-beginning-position) (line-end-position)))
        (prin1 todos-categories (current-buffer))))))
 
 (defun todos-make-categories-list (&optional force)
@@ -1258,7 +1354,8 @@ the file."
                       (widen)
                       (goto-char (point-min))
                       (when (re-search-forward
-                             (concat (regexp-quote todos-category-beg) cat)
+                             (concat "^" (regexp-quote todos-category-beg)
+                                     cat "$")
                              (point-max) t)
                         (forward-line)
                         (while (not (or (looking-at
@@ -1293,61 +1390,37 @@ the file."
 (defun todos-repair-categories-sexp ()
   "Repair corrupt Todos categories sexp.
 This should only be needed as a consequence of careless manual
-editing or a bug in todos.el."
+editing or a bug in todos.el.
+
+*Warning*: Calling this command restores the category order to
+the list element order in the Todos categories sexp, so any order
+changes made in Todos Categories mode will have to be made again."
   (interactive)
   (let ((todos-categories (todos-make-categories-list t)))
     (todos-update-categories-sexp)))
 
-(defvar todos-allcats-file (concat todos-files-directory "todos-allcats.el")
-  "Name of file containing the value of `todos-all-categories-alist'.
-The contents of this file are automatically generated and
-executed when todos.el is loaded, hence users should not edit
-it.")
+;;; Global variables and helper functions for items
 
-(defun todos-all-categories-alist ()
-  ""
-  ;; FIXME: loop through archive files for categories not in todo files?
-  (let ((files todos-files)
-       allcats)
-    (dolist (f files)
-      ;; FIXME: If file buffer is modified, save first.
-      (with-temp-buffer
-       (insert-file-contents f)
-       (let ((cats (read (buffer-substring-no-properties
-                          (line-beginning-position)
-                          (line-end-position)))))
-         (dolist (c cats)
-           (let* ((cat (assoc (car c) allcats))
-                  (catcdr (cdr cat)))
-             (unless (listp catcdr) (setq catcdr (list catcdr)))
-             (if cat
-                 (setcdr cat (append catcdr (list (todos-short-file-name f))))
-               (setq allcats (append allcats
-                                     (list
-                                      (cons (car c)
-                                            (todos-short-file-name f)))))))))))
-    allcats))
-
-(defvar todos-all-categories-alist (if (file-exists-p todos-allcats-file)
-                                      (load-file todos-allcats-file)
-                                    (todos-all-categories-alist))
-  "Alist of names of all Todos categories and their files.")
+(defconst todos-month-name-array
+  (vconcat calendar-month-name-array (vector "*"))
+  "Array of month names, in order.
+The final element is \"*\", indicating an unspecified month.")
 
-;;; Global variables and helper functions for items
+(defconst todos-month-abbrev-array
+  (vconcat calendar-month-abbrev-array (vector "*"))
+  "Array of abbreviated month names, in order.
+The final element is \"*\", indicating an unspecified month.")
 
 (defconst todos-date-pattern
   (let ((dayname (diary-name-pattern calendar-day-name-array nil t)))
-    (concat "\\(?:" dayname "\\|"
+    (concat "\\(?5:" dayname "\\|"
            (let ((dayname)
-                 ;; FIXME: how to choose between abbreviated and unabbreviated
-                 ;; month name?
-                 (monthname (format "\\(?:%s\\|\\*\\)"
-                                    (diary-name-pattern
-                                     calendar-month-name-array
-                                     calendar-month-abbrev-array t)))
-                 (month "\\(?:[0-9]+\\|\\*\\)")
-                 (day "\\(?:[0-9]+\\|\\*\\)")
-                 (year "-?\\(?:[0-9]+\\|\\*\\)"))
+                 (monthname (format "\\(?6:%s\\)" (diary-name-pattern
+                                                   todos-month-name-array
+                                                   todos-month-abbrev-array)))
+                 (month "\\(?7:[0-9]+\\|\\*\\)")
+                 (day "\\(?8:[0-9]+\\|\\*\\)")
+                 (year "-?\\(?9:[0-9]+\\|\\*\\)"))
              (mapconcat 'eval calendar-date-display-form ""))
            "\\)"))
   "Regular expression matching a Todos date header.")
@@ -1432,18 +1505,18 @@ it.")
 
 (defun todos-remove-item ()
   "Internal function called in editing, deleting or moving items."
-  (let* ((beg (todos-item-start))
-        (end (progn (todos-item-end) (1+ (point))))
-        (ovs (overlays-in beg beg)))
-    ;; There can be both prefix/number and mark overlays.
-    (while ovs (delete-overlay (car ovs)) (pop ovs))
+  (let* ((end (progn (todos-item-end) (1+ (point))))
+        (beg (todos-item-start))
+        (ov (todos-get-overlay 'prefix)))
+    (when ov (delete-overlay ov))
     (delete-region beg end)))
 
 (defun todos-diary-item-p ()
   "Return non-nil if item at point has diary entry format."
   (save-excursion
-    (todos-item-start)
-    (not (looking-at (regexp-quote todos-nondiary-start)))))
+    (when (todos-item-string)          ; Exclude empty lines.
+      (todos-item-start)
+      (not (looking-at (regexp-quote todos-nondiary-start))))))
 
 (defun todos-done-item-p ()
   "Return non-nil if item at point is a done item."
@@ -1451,74 +1524,101 @@ it.")
     (todos-item-start)
     (looking-at todos-done-string-start)))
 
-(defvar todos-item-mark (propertize (if (equal todos-prefix "*") "@" "*")
-                                   'face 'todos-mark)
-  "String used to mark items.")
+(defun todos-done-item-section-p ()
+  "Return non-nil if point is in category's done items section."
+  (save-excursion
+    (or (re-search-backward (concat "^" (regexp-quote todos-category-done))
+                           nil t)
+       (progn (goto-char (point-min))
+              (looking-at todos-done-string-start)))))
+
+(defun todos-get-overlay (val)
+  "Return the overlay at point whose `todos' property has value VAL."
+  ;; Use overlays-in to find prefix overlays and check over two
+  ;; positions to find done separator overlay.
+  (let ((ovs (overlays-in (point) (1+ (point))))
+       ov)
+    (catch 'done
+      (while ovs
+       (setq ov (pop ovs))
+       (when (eq (overlay-get ov 'todos) val)
+         (throw 'done ov))))))
 
 (defun todos-marked-item-p ()
-  "If this item begins with `todos-item-mark', return mark overlay."
-  (let ((ovs (overlays-in (line-beginning-position) (line-beginning-position)))
-       (mark todos-item-mark)
-       ov marked)
-    (catch 'stop
-      (while ovs
-       (setq ov (pop ovs))
-       (and (equal (overlay-get ov 'before-string) mark)
-            (throw 'stop (setq marked t)))))
+  "Non-nil if this item begins with `todos-item-mark'.
+ In that case, return the item's prefix overlay."
+  ;; If a todos-item-insert command is called on a Todos file before
+  ;; it is visited, it has no prefix overlays, so conditionalize:
+  (let* ((ov (todos-get-overlay 'prefix))
+        (pref (when ov (overlay-get ov 'before-string)))
+        (marked (when pref
+                  (string-match (concat "^" (regexp-quote todos-item-mark))
+                                pref))))
     (when marked ov)))
 
 (defun todos-insert-with-overlays (item)
   "Insert ITEM at point and update prefix/priority number overlays."
   (todos-item-start)
-  (insert item "\n")
+  ;; Insertion pushes item down but not its prefix overlay.  When the
+  ;; overlay includes a mark, this would now mark the inserted ITEM,
+  ;; so move it to the pushed down item.
+  (let ((ov (todos-get-overlay 'prefix))
+       (marked (todos-marked-item-p)))
+    (insert item "\n")
+    (when marked (move-overlay ov (point) (point))))
   (todos-backward-item)
   (todos-prefix-overlays))
 
 (defun todos-prefix-overlays ()
-  "Put before-string overlay in front of this category's items.
+  "Update the prefix overlays of the current category's items.
 The overlay's value is the string `todos-prefix' or with non-nil
 `todos-number-priorities' an integer in the sequence from 1 to
 the number of todo or done items in the category indicating the
 item's priority.  Todo and done items are numbered independently
 of each other."
-  (when (or todos-number-priorities
-           (not (string-match "^[[:space:]]*$" todos-prefix)))
-    (let ((prefix (propertize (concat todos-prefix " ")
-                             'face 'todos-prefix-string))
-         (num 0))
-      (save-excursion
-       (goto-char (point-min))
-       (while (not (eobp))
-         (when (or (todos-date-string-matcher (line-end-position))
-                   (todos-done-string-matcher (line-end-position)))
-           (goto-char (match-beginning 0))
-           (when todos-number-priorities
-             (setq num (1+ num))
-             ;; Reset number to 1 for first done item.
-             (when (and (looking-at todos-done-string-start)
-                        (looking-back (concat "^"
-                                              (regexp-quote todos-category-done)
-                                              "\n")))
-               (setq num 1))
-             (setq prefix (propertize (concat (number-to-string num) " ")
-                                      'face 'todos-prefix-string)))
-           (let ((ovs (overlays-in (point) (point)))
-                 marked ov-pref)
-             (if ovs
-                 (dolist (ov ovs)
-                   (let ((val (overlay-get ov 'before-string)))
-                     (if (equal val "*")
-                         (setq marked t)
-                       (setq ov-pref val)))))
-             (unless (equal ov-pref prefix)
-               ;; Why doesn't this work?
-               ;; (remove-overlays (point) (point) 'before-string)
-               (remove-overlays (point) (point))
-               (overlay-put (make-overlay (point) (point))
-                            'before-string prefix)
-               (and marked (overlay-put (make-overlay (point) (point))
-                                        'before-string todos-item-mark)))))
-         (forward-line))))))
+  (let ((num 0)
+       (cat-tp (or (cdr (assoc-string
+                         (todos-current-category)
+                         (nth 2 (assoc-string todos-current-todos-file
+                                              todos-priorities-rules))))
+                   todos-show-priorities))
+       done prefix)
+    (save-excursion
+      (goto-char (point-min))
+      (while (not (eobp))
+       (when (or (todos-date-string-matcher (line-end-position))
+                 (todos-done-string-matcher (line-end-position)))
+         (goto-char (match-beginning 0))
+         (setq num (1+ num))
+         ;; Reset number to 1 for first done item.
+         (when (and (looking-at todos-done-string-start)
+                    (looking-back (concat "^"
+                                          (regexp-quote todos-category-done)
+                                          "\n")))
+           (setq num 1
+                 done t))
+         (setq prefix (concat (propertize
+                               (if todos-number-priorities
+                                   (number-to-string num)
+                                 todos-prefix)
+                               'face
+                               ;; Prefix of top priority items has a
+                               ;; distinct face in Todos mode.
+                               (if (and (not done) (<= num cat-tp)
+                                        (eq major-mode 'todos-mode))
+                                   'todos-top-priority
+                                 'todos-prefix-string))
+                              " "))
+         (let ((ov (todos-get-overlay 'prefix))
+               (marked (todos-marked-item-p)))
+           ;; Prefix overlay must be at a single position so its
+           ;; bounds aren't changed when (re)moving an item.
+           (unless ov (setq ov (make-overlay (point) (point))))
+           (overlay-put ov 'todos 'prefix)
+           (overlay-put ov 'before-string (if marked
+                                              (concat todos-item-mark prefix)
+                                            prefix))))
+       (forward-line)))))
 
 ;; ---------------------------------------------------------------------------
 ;;; Helper functions for user input with prompting and completion
@@ -1545,44 +1645,97 @@ otherwise, a new file name is allowed."
     (setq file (file-truename (concat todos-files-directory file
                                      (if archive ".toda" ".todo"))))))
 
-(defun todos-read-category (prompt &optional mustmatch added)
+(defun todos-read-category (prompt &optional match-type file)
   "Choose and return a category name, prompting with PROMPT.
-Show completions with TAB or SPC.  With non-nil MUSTMATCH the
-name must be that of an existing category; otherwise, a new
-category name is allowed, after checking its validity.  Non-nil
-argument ADDED means the caller is todos-add-category, so don't
-ask whether to add the category."
+Show completions for existing categories with TAB or SPC.
+
+The argument MATCH-TYPE specifies the matching requirements on
+the category name: with the value `merge' the name must complete
+to that of an existing category; with the value `add' the name
+must not be that of an existing category; with all other values
+both existing and new valid category names are accepted.
+
+With non-nil argument FILE prompt for a file and complete only
+against categories in that file; otherwise complete against all
+categories from `todos-category-completions-files'."
   ;; Allow SPC to insert spaces, for adding new category names.
   (let ((map minibuffer-local-completion-map))
     (define-key map " " nil)
-    ;; Make a copy of todos-categories in case history-delete-duplicates is
-    ;; non-nil, which makes completing-read alter todos-categories.
-    (let* ((categories (copy-sequence todos-categories))
-          (history (cons 'todos-categories (1+ todos-category-number)))
+    (let* ((add (eq match-type 'add))
+          (file0 (when (and file (> (length todos-files) 1))
+                   (todos-read-file-name "Choose a Todos file: " nil t)))
+          (completions (unless file0 (todos-category-completions)))
+          (categories (cond (file0
+                             (with-current-buffer
+                                 (find-file-noselect file0 'nowarn)
+                               (let ((todos-current-todos-file file0))
+                                 todos-categories)))
+                            ((and add (not file))
+                             (with-current-buffer
+                                 (find-file-noselect todos-current-todos-file)
+                               todos-categories))
+                            (t
+                             completions)))
           (completion-ignore-case todos-completion-ignore-case)
-          (cat (completing-read prompt todos-categories nil
-                                mustmatch nil history
-                                ;; Default for existing categories is the
-                                ;; current category.
-                                (if todos-categories
-                                    (todos-current-category)
+          (cat (completing-read prompt categories nil
+                                (eq match-type 'merge) nil nil
+                                ;; Unless we're adding a category via
+                                ;; todos-add-category, set default
+                                ;; for existing categories to the
+                                ;; current category of the chosen
+                                ;; file or else of the current file.
+                                (if (and categories (not add))
+                                    (with-current-buffer
+                                        (find-file-noselect
+                                         (or file0
+                                             todos-current-todos-file
+                                             (todos-absolute-file-name
+                                              todos-default-todos-file)))
+                                      (todos-current-category))
                                   ;; Trigger prompt for initial category.
-                                  ""))))
-      (unless (or mustmatch (assoc cat todos-categories))
-       (todos-validate-name cat 'category)
-       (unless added
-         (if (y-or-n-p (format (concat "There is no category \"%s\" in "
-                                       "this file; add it? ") cat))
-             (todos-add-category cat)
+                                  "")))
+          (catfil (cdr (assoc cat completions)))
+          (str "Category \"%s\" from which file (TAB for choices)? "))
+      ;; If we do category completion and the chosen category name
+      ;; occurs in more than one file, prompt to choose one file.
+      (unless (or file0 add (not catfil))
+       (setq file0 (file-truename
+                    (if (atom catfil)
+                        catfil
+                      (todos-absolute-file-name
+                       (completing-read (format str cat)
+                                        todos-category-completions-files))))))
+      ;; Default to the current file.
+      (unless file0 (setq file0 todos-current-todos-file))
+      ;; First validate only a name passed interactively from
+      ;; todos-add-category, which must be of a nonexisting category.
+      (unless (and (assoc cat categories) (not add))
+       ;; Validate only against completion categories.
+       (let ((todos-categories categories))
+         (setq cat (todos-validate-name cat 'category)))
+       ;; When user enters a nonexisting category name by jumping or
+       ;; moving, confirm that it should be added, then validate.
+       (unless add
+         (if (y-or-n-p (format "Add new category \"%s\" to file \"%s\"? "
+                               cat (todos-short-file-name file0)))
+             (progn
+               (when (assoc cat categories)
+                 (let ((todos-categories categories))
+                   (setq cat (todos-validate-name cat 'category))))
+               ;; Restore point and narrowing after adding new
+               ;; category, to avoid moving to beginning of file when
+               ;; moving marked items to a new category
+               ;; (todos-move-item).
+               (save-excursion
+                 (save-restriction
+                   (todos-add-category file0 cat))))
+           ;; If we decide not to add a category, exit without returning.
            (keyboard-quit))))
-      ;; Restore the original value of todos-categories unless a new category
-      ;; was added (since todos-add-category changes todos-categories).
-      (unless added (setq todos-categories categories))
-      cat)))
+      (cons cat file0))))
 
 (defun todos-validate-name (name type)
   "Prompt for new NAME for TYPE until it is valid, then return it.
-TYPE can be either a file or a category"
+TYPE can be either of the symbols `file' or `category'."
   (let ((categories todos-categories)
        (files (mapcar 'todos-short-file-name todos-files))
        prompt)
@@ -1590,14 +1743,14 @@ TYPE can be either a file or a category"
        (and (cond ((string= "" name)
                    (setq prompt
                          (cond ((eq type 'file)
-                                (if todos-files
+                                (if files
                                     "Enter a non-empty file name: "
                                   ;; Empty string passed by todos-show to
                                   ;; prompt for initial Todos file.
                                   (concat "Initial file name ["
                                           todos-initial-file "]: ")))
                                ((eq type 'category)
-                                (if todos-categories
+                                (if categories
                                     "Enter a non-empty category name: "
                                   ;; Empty string passed by todos-show to
                                   ;; prompt for initial category of a new
@@ -1607,77 +1760,103 @@ TYPE can be either a file or a category"
                   ((string-match "\\`\\s-+\\'" name)
                    (setq prompt
                          "Enter a name that does not contain only white space: "))
-                  ((and (eq type 'file) (member name todos-files))
+                  ((and (eq type 'file) (member name files))
                    (setq prompt "Enter a non-existing file name: "))
-                  ((and (eq type 'category) (assoc name todos-categories))
+                  ((and (eq type 'category) (assoc name categories))
                    (setq prompt "Enter a non-existing category name: ")))
-            (setq name (if (or (and (eq type 'file) todos-files)
-                               (and (eq type 'category) todos-categories))
+            (setq name (if (or (and (eq type 'file) files)
+                               (and (eq type 'category) categories))
                            (completing-read prompt (cond ((eq type 'file)
-                                                          todos-files)
+                                                          files)
                                                          ((eq type 'category)
-                                                          todos-categories)))
+                                                          categories)))
                          ;; Offer default initial name.
                          (completing-read prompt (if (eq type 'file)
-                                                     todos-files
-                                                   todos-categories)
+                                                     files
+                                                   categories)
                                           nil nil (if (eq type 'file)
                                                       todos-initial-file
                                                     todos-initial-category))))))
     name))
 
 ;; Adapted from calendar-read-date and calendar-date-string.
-(defun todos-read-date ()
+(defun todos-read-date (&optional arg mo yr)
   "Prompt for Gregorian date and return it in the current format.
-Also accepts `*' as an unspecified month, day, or year."
-  (let* ((year (let (x)
-                (while (if (numberp x) (< x 0) (not (eq x '*)))
-                  (setq x (read-from-minibuffer
-                           "Year (>0 or RET for this year or * for any year): "
-                           nil nil t nil (number-to-string
-                                          (calendar-extract-year
-                                           (calendar-current-date))))))
-                x))
-         (month-array (vconcat calendar-month-name-array (vector "*")))
-        (abbrevs (vconcat calendar-month-abbrev-array (vector "*")))
-         (completion-ignore-case todos-completion-ignore-case)
-        (monthname (completing-read
-                    "Month name (RET for current month, * for any month): "
-                    (mapcar 'list (append month-array nil))
-                    nil t nil nil
-                    (calendar-month-name (calendar-extract-month
-                                          (calendar-current-date)) t)))
-         (month (cdr (assoc-string
-                     monthname (calendar-make-alist month-array nil nil
-                                                    abbrevs))))
-         (last (if (= month 13)
-                  ;; Use longest possible month for checking day number
-                  ;; input.  Does Calendar do anything special when * is
-                  ;; currently a shorter month?
-                  31
-                (let ((yr (if (eq year '*)
-                              ;; Use a leap year to allow Feb. 29.
-                              2012
-                            year)))
-                  (calendar-last-day-of-month month yr))))
-        (day (let (x)
-               (while (if (numberp x) (or (< x 0) (< last x)) (not (eq x '*)))
-                 (setq x (read-from-minibuffer
-                          (format
-                           "Day (1-%d or RET for today or * for any day): "
-                           last) nil nil t nil (number-to-string
-                                                (calendar-extract-day
-                                                 (calendar-current-date))))))
-                x))
-        dayname)                       ; Needed by calendar-date-display-form.
-    (setq year (if (eq year '*) (symbol-name '*) (number-to-string year)))
-    (setq day (if (eq day '*) (symbol-name '*) (number-to-string day)))
-    ;; FIXME: make abbreviation customizable
-    (setq monthname
-         (or (and (= month 13) "*")
-             (calendar-month-name (calendar-extract-month (list month day year))
-                                  t)))
-    (mapconcat 'eval calendar-date-display-form "")))
+
+With non-nil ARG, prompt for and return only the date component
+specified by ARG, which can be one of these symbols:
+`month' (prompt for name, return name or number according to
+value of `calendar-date-display-form'), `day' of month, or
+`year'.  The value of each of these components can be `*',
+indicating an unspecified month, day, or year.
+
+When ARG is `day', non-nil arguments MO and YR determine the
+number of the last the day of the month."
+  (let (year monthname month day
+            dayname)                   ; Needed by calendar-date-display-form.
+    (when (or (not arg) (eq arg 'year))
+      (while (if (natnump year) (< year 1) (not (eq year '*)))
+       (setq year (read-from-minibuffer
+                   "Year (>0 or RET for this year or * for any year): "
+                   nil nil t nil (number-to-string
+                                  (calendar-extract-year
+                                   (calendar-current-date)))))))
+    (when (or (not arg) (eq arg 'month))
+      (let* ((marray todos-month-name-array)
+            (mlist (append marray nil))
+            (mabarray todos-month-abbrev-array)
+            (mablist (append mabarray nil))
+            (completion-ignore-case todos-completion-ignore-case))
+       (setq monthname (completing-read
+                        "Month name (RET for current month, * for any month): "
+                        ;; (mapcar 'list (append marray nil))
+                        mlist nil t nil nil
+                        (calendar-month-name (calendar-extract-month
+                                              (calendar-current-date)) t))
+             ;; month (cdr (assoc-string
+             ;;                  monthname (calendar-make-alist marray nil nil
+             ;;                                                 abbrevs))))))
+             month (1+ (- (length mlist)
+                          (length (or (member monthname mlist)
+                                      (member monthname mablist))))))
+       (setq monthname (aref mabarray (1- month)))))
+    (when (or (not arg) (eq arg 'day))
+      (let ((last (let ((mm (or month mo))
+                       (yy (or year yr)))
+                   ;; If month is unspecified, use a month with 31
+                   ;; days for checking day of month input.  Does
+                   ;; Calendar do anything special when * is
+                   ;; currently a shorter month?
+                   (if (= mm 13) (setq mm 1))
+                   ;; If year is unspecified, use a leap year to
+                   ;; allow Feb. 29.
+                   (if (eq year '*) (setq yy 2012))
+                   (calendar-last-day-of-month mm yy))))
+       (while (if (natnump day) (or (< day 1) (> day last)) (not (eq day '*)))
+         (setq day (read-from-minibuffer
+                    (format "Day (1-%d or RET for today or * for any day): "
+                            last)
+                    nil nil t nil (number-to-string
+                                   (calendar-extract-day
+                                    (calendar-current-date))))))))
+    ;; Stringify read values (monthname is already a string).
+    (and year (setq year (if (eq year '*)
+                            (symbol-name '*)
+                          (number-to-string year))))
+    (and day (setq day (if (eq day '*)
+                          (symbol-name '*)
+                        (number-to-string day))))
+    (and month (setq month (if (eq month '*)
+                              (symbol-name '*)
+                            (number-to-string month))))
+    (if arg
+       (cond ((eq arg 'year) year)
+             ((eq arg 'day) day)
+             ((eq arg 'month)
+              (if (memq 'month calendar-date-display-form)
+                  month
+                monthname)))
+      (mapconcat 'eval calendar-date-display-form ""))))
 
 (defun todos-read-dayname ()
   "Choose name of a day of the week with completion and return it."
@@ -1739,8 +1918,9 @@ the empty string (i.e., no time string)."
                   :notify (lambda (&rest ignore)
                             (setq todos-multiple-filter-files
                                   (mapcar (lambda (f)
-                                            (concat todos-files-directory
-                                                    f ".todo"))
+                                            (file-truename
+                                             (concat todos-files-directory
+                                                     f ".todo")))
                                           (widget-value
                                            todos-multiple-filter-files-widget)))
                             (quit-window t)
@@ -1751,31 +1931,69 @@ the empty string (i.e., no time string)."
   (message "Click \"Apply\" after selecting files.")
   (recursive-edit))
 
-(defun todos-filter-items (filter &optional multifile)
-  "Build and display a list of items from different categories.
-
-The items are selected according to the value of FILTER, which
-can be `top' for top priority items, `diary' for diary items,
-`regexp' for items matching a regular expresion entered by the
-user, or a cons cell of one of these symbols and a number set by
-the calling command, which overrides `todos-show-priorities'.
-
-With non-nil argument MULTIFILE list top priorities of multiple
-Todos files, by default those in `todos-filter-files'."
+(defun todos-filter-items (filter &optional new multifile)
+  "Internal routine for displaying items that satisfy FILTER.
+The values of FILTER can be `top' for top priority items, a cons
+of `top' and a number passed by the caller, `diary' for diary
+items, or `regexp' for items matching a regular expresion entered
+by the user.  The items can be from any categories in the current
+todo file or, with non-nil MULTIFILE, from several files.  If NEW
+is nil, visit an appropriate file containing the list of filtered
+items; if there is no such file, or with non-nil NEW, build the
+list and display it.
+
+See the document strings of the commands `todos-top-priorities',
+`todos-diary-items', `todos-regexp-items', and those of the
+corresponding multifile commands for further details. "
+  (let* ((top (eq filter 'top))
+        (diary (eq filter 'diary))
+        (regexp (eq filter 'regexp))
+        (buf (cond (top todos-top-priorities-buffer)
+                   (diary todos-diary-items-buffer)
+                   (regexp todos-regexp-items-buffer)))
+        (flist (if multifile
+                   (or todos-filter-files
+                       (progn (todos-multiple-filter-files)
+                              todos-multiple-filter-files))
+                 (list todos-current-todos-file)))
+        (multi (> (length flist) 1))
+        (fname (if (equal flist 'quit)
+                   ;; Pressed `cancel' in t-m-f-f file selection dialog.
+                   (keyboard-quit)
+                 (concat todos-files-directory
+                         (mapconcat 'todos-short-file-name flist "-")
+                         (cond (top ".todt")
+                               (diary ".tody")
+                               (regexp ".todr")))))
+        (rxfiles (when regexp
+                   (directory-files todos-files-directory t ".*\\.todr$" t)))
+        (file-exists (or (file-exists-p fname) rxfiles)))
+    (cond ((and top new (natnump new))
+          (todos-filter-items-1 (cons 'top new) flist))
+         ((and (not new) file-exists)
+          (when (and rxfiles (> (length rxfiles) 1))
+            (let ((rxf (mapcar 'todos-short-file-name rxfiles)))
+              (setq fname (todos-absolute-file-name
+                           (completing-read "Choose a regexp items file: "
+                                            rxf) 'regexp))))
+          (find-file fname)
+          (todos-prefix-overlays)
+          (todos-check-filtered-items-file))
+         (t
+          (todos-filter-items-1 filter flist)))
+    (when (or new (not file-exists))
+      (setq fname (replace-regexp-in-string "-" ", " fname))
+      (rename-buffer (format (concat "%s for file" (if multi "s" "")
+                                  " \"%s\"") buf fname)))))
+
+(defun todos-filter-items-1 (filter file-list)
+  "Internal subroutine called by `todos-filter-items'.
+The values of FILTER and FILE-LIST are passed from the caller."
   (let ((num (if (consp filter) (cdr filter) todos-show-priorities))
        (buf (get-buffer-create todos-filtered-items-buffer))
-       (files (list todos-current-todos-file))
+       (multifile (> (length file-list) 1))
        regexp fname bufstr cat beg end done)
-    (when multifile
-      (setq files (or todos-multiple-filter-files ; Passed from todos-*-multifile.
-                     (if (or (consp filter)
-                             (null todos-filter-files))
-                         (progn (todos-multiple-filter-files)
-                                todos-multiple-filter-files)
-                       todos-filter-files))
-           todos-multiple-filter-files nil))
-    (if (eq files 'quit) (keyboard-quit))
-    (if (null files)
+    (if (null file-list)
        (error "No files have been chosen for filtering")
       (with-current-buffer buf
        (erase-buffer)
@@ -1784,7 +2002,7 @@ Todos files, by default those in `todos-filter-files'."
       (when (eq filter 'regexp)
        (setq regexp (read-string "Enter a regular expression: ")))
       (save-current-buffer
-       (dolist (f files)
+       (dolist (f file-list)
          ;; Before inserting file contents into temp buffer, save a modified
          ;; buffer visiting it.
          (let ((bf (find-buffer-visiting f)))
@@ -1821,21 +2039,23 @@ Todos files, by default those in `todos-filter-files'."
            ;; Delete Todos file categories sexp.
            (delete-region (line-beginning-position) (1+ (line-end-position)))
            (let (fnum)
-             ;; Unless the number of items to show was supplied by prefix
-             ;; argument of caller, the file-wide value from
+             ;; Unless the number of top priorities to show was
+             ;; passed by the caller, the file-wide value from
              ;; `todos-priorities-rules', if non-nil, overrides
              ;; `todos-show-priorities'.
              (unless (consp filter)
-               (setq fnum (nth 1 (assoc f todos-priorities-rules))))
+               (setq fnum (or (nth 1 (assoc f todos-priorities-rules))
+                              todos-show-priorities)))
              (while (re-search-forward
                      (concat "^" (regexp-quote todos-category-beg) "\\(.+\\)\n")
                      nil t)
                (setq cat (match-string 1))
                (let (cnum)
-                 ;; Unless the number of items to show was supplied by prefix
-                 ;; argument of caller, the category-wide value from
-                 ;; `todos-priorities-rules', if non-nil, overrides a non-nil
-                 ;; file-wide value from `todos-priorities-rules' as well as
+                 ;; Unless the number of top priorities to show was
+                 ;; passed by the caller, the category-wide value
+                 ;; from `todos-priorities-rules', if non-nil,
+                 ;; overrides a non-nil file-wide value from
+                 ;; `todos-priorities-rules' as well as
                  ;; `todos-show-priorities'.
                  (unless (consp filter)
                    (let ((cats (nth 2 (assoc f todos-priorities-rules))))
@@ -1939,40 +2159,166 @@ set the user customizable option `todos-priorities-rules'."
         (rules todos-priorities-rules)
         (frule (assoc-string file rules))
         (crule (assoc-string cat (nth 2 frule)))
+        (crules (nth 2 frule))
         (cur (or (if arg (cdr crule) (nth 1 frule))
                  todos-show-priorities))
-        (prompt (concat "Current number of top priorities in this "
-                        (if arg "category" "file") ": %d; "
-                        "enter new number: "))
-        (new "-1")
+        (prompt (if arg (concat "Number of top priorities in this category"
+                                " (currently %d): ")
+                  (concat "Default number of top priorities per category"
+                                " in this file (currently %d): ")))
+        (new -1)
         nrule)
-    (while (< (string-to-number new) 0)
+    (while (< new 0)
       (let ((cur0 cur))
-       (setq new (read-number (format prompt cur0) cur0)
+       (setq new (read-number (format prompt cur0))
              prompt "Enter a non-negative number: "
              cur0 nil)))
     (setq nrule (if arg
-                   (append (nth 2 (delete crule frule)) (list (cons cat new)))
-                 (append (list file new) (list (nth 2 frule)))))
+                   (append (delete crule crules) (list (cons cat new)))
+                 (append (list file new) (list crules))))
     (setq rules (cons (if arg
                          (list file cur nrule)
                        nrule)
                      (delete frule rules)))
-    (customize-save-variable 'todos-priorities-rules rules)))
-
-(defun todos-filtered-buffer-name (buffer-type file-list)
-  "Rename Todos filtered buffer using BUFFER-TYPE and FILE-LIST.
-
-The new name is constructed from the string BUFFER-TYPE, which
-refers to one of the top priorities, diary or regexp item
-filters, and the names of the filtered files in FILE-LIST.  Used
-in Todos Filter Items mode."
-  (let* ((flist (if (listp file-list) file-list (list file-list)))
-        (multi (> (length flist) 1))
-        (fnames (mapconcat (lambda (f) (todos-short-file-name f))
-                          flist ", ")))
-    (rename-buffer (format (concat "%s for file" (if multi "s" "")
-                                  " \"%s\"") buffer-type fnames))))
+    (customize-save-variable 'todos-priorities-rules rules)
+    (todos-prefix-overlays)))
+
+(defconst todos-filtered-items-buffer "Todos filtered items"
+  "Initial name of buffer in Todos Filter Items mode.")
+
+(defconst todos-top-priorities-buffer "Todos top priorities"
+  "Buffer type string for `todos-filter-items'.")
+
+(defconst todos-diary-items-buffer "Todos diary items"
+  "Buffer type string for `todos-filter-items'.")
+
+(defconst todos-regexp-items-buffer "Todos regexp items"
+  "Buffer type string for `todos-filter-items'.")
+
+(defun todos-find-item (str)
+  "Search for filtered item STR in its saved Todos file.
+Return the list (FOUND FILE CAT), where CAT and FILE are the
+item's category and file, and FOUND is a cons cell if the search
+succeeds, whose car is the start of the item in FILE and whose
+cdr is `done', if the item is now a done item, `changed', if its
+text was truncated or augmented or, for a top priority item, if
+its priority has changed, and `same' otherwise."
+  (string-match (concat (if todos-filter-done-items
+                           (concat "\\(?:" todos-done-string-start "\\|"
+                                   todos-date-string-start "\\)")
+                         todos-date-string-start)
+                       todos-date-pattern "\\(?: " diary-time-regexp "\\)?"
+                       (if todos-filter-done-items
+                           "\\]"
+                         (regexp-quote todos-nondiary-end)) "?"
+                       "\\(?4: \\[\\(?3:(archive) \\)?\\(?2:.*:\\)?"
+                       "\\(?1:.*\\)\\]\\).*$") str)
+  (let ((cat (match-string 1 str))
+       (file (match-string 2 str))
+       (archive (string= (match-string 3 str) "(archive) "))
+       (filcat (match-string 4 str))
+       (tpriority 1)
+       (tpbuf (string-match "top" (buffer-name)))
+       found)
+    (setq str (replace-match "" nil nil str 4))
+    (when tpbuf
+      ;; Calculate priority of STR wrt its category.
+      (save-excursion
+       (while (search-backward filcat nil t)
+           (setq tpriority (1+ tpriority)))))
+    (setq file (if file
+                  (concat todos-files-directory (substring file 0 -1)
+                          (if archive ".toda" ".todo"))
+                (if archive
+                    (concat (file-name-sans-extension
+                             todos-global-current-todos-file) ".toda")
+                  todos-global-current-todos-file)))
+    (find-file-noselect file)
+    (with-current-buffer (find-buffer-visiting file)
+      (save-restriction
+       (widen)
+       (goto-char (point-min))
+       (let ((beg (re-search-forward
+                   (concat "^" (regexp-quote (concat todos-category-beg cat))
+                           "$")
+                   nil t))
+             (done (save-excursion
+                     (re-search-forward
+                      (concat "^" (regexp-quote todos-category-done)) nil t)))
+             (end (save-excursion
+                    (or (re-search-forward
+                         (concat "^" (regexp-quote todos-category-beg))
+                         nil t)
+                        (point-max)))))
+         (setq found (when (search-forward str end t)
+                       (goto-char (match-beginning 0))))
+         (when found
+           (setq found
+                 (cons found (if (> (point) done)
+                                 'done
+                               (let ((cpriority 1))
+                                 (when tpbuf
+                                   (save-excursion
+                                     ;; Not top item in category.
+                                     (while (> (point) (1+ beg))
+                                       (let ((opoint (point)))
+                                         (todos-backward-item)
+                                         ;; Can't move backward beyond
+                                         ;; first item in file.
+                                         (unless (= (point) opoint)
+                                           (setq cpriority (1+ cpriority)))))))
+                                 (if (and (= tpriority cpriority)
+                                          ;; Proper substring is not the same.
+                                          (string= (todos-item-string)
+                                                   str))
+                                     'same
+                                   'changed)))))))))
+      (list found file cat)))
+
+(defun todos-check-filtered-items-file ()
+  "Check if filtered items file is up to date and a show suitable message."
+  ;; (catch 'old
+  (let ((count 0))
+    (while (not (eobp))
+      (let* ((item (todos-item-string))
+            (found (car (todos-find-item item))))
+       (unless (eq (cdr found) 'same)
+         (save-excursion
+           (overlay-put (make-overlay (todos-item-start) (todos-item-end))
+                        'face 'todos-search))
+         (setq count (1+ count))))
+         ;; (throw 'old (message "The marked item is not up to date.")))
+      (todos-forward-item))
+    (if (zerop count)
+       (message "Filtered items file is up to date.")
+      (message (concat "The highlighted item" (if (= count 1) " is " "s are ")
+                      "not up to date."
+                      ;; "\nType <return> on item for details."
+                      )))))
+
+(defun todos-filter-items-filename ()
+  "Return absolute file name for saving this Filtered Items buffer."
+  (let ((bufname (buffer-name)))
+    (string-match "\"\\([^\"]+\\)\"" bufname)
+    (let* ((filename-str (substring bufname (match-beginning 1) (match-end 1)))
+          (filename-base (replace-regexp-in-string ", " "-" filename-str))
+          (top-priorities (string-match "top priorities" bufname))
+          (diary-items (string-match "diary items" bufname))
+          (regexp-items (string-match "regexp items" bufname)))
+      (when regexp-items
+       (let ((prompt (concat "Enter a short identifying string"
+                             " to make this file name unique: ")))
+         (setq filename-base (concat filename-base "-" (read-string prompt)))))
+      (concat todos-files-directory filename-base
+             (cond (top-priorities ".todt")
+                   (diary-items ".tody")
+                   (regexp-items ".todr"))))))
+
+(defun todos-save-filtered-items-buffer ()
+  "Save current Filtered Items buffer to a file.
+If the file already exists, overwrite it only on confirmation."
+  (let ((filename (or (buffer-file-name) (todos-filter-items-filename))))
+    (write-file filename t)))
 
 ;; ---------------------------------------------------------------------------
 ;;; Sorting and display routines for Todos Categories mode.
@@ -1983,15 +2329,26 @@ in Todos Filter Items mode."
     (dolist (c categories longest)
       (setq longest (max longest (length c))))))
 
+(defun todos-adjusted-category-label-length ()
+  "Return adjusted length of category label button.
+The adjustment ensures proper tabular alignment in Todos
+Categories mode."
+  (let* ((categories (mapcar 'car todos-categories))
+        (longest (todos-longest-category-name-length categories))
+        (catlablen (length todos-categories-category-label))
+        (lc-diff (- longest catlablen)))
+    (if (and (natnump lc-diff)
+            (eq (logand lc-diff 1) 1)) ; oddp from cl.el
+       (1+ longest)
+      (max longest catlablen))))
+
 (defun todos-padded-string (str)
-  "Return string STR padded with spaces.
+  "Return category name or label string STR padded with spaces.
 The placement of the padding is determined by the value of user
 option `todos-categories-align'."
-  (let* ((categories (mapcar 'car todos-categories))
-        (len (max (todos-longest-category-name-length categories)
-                  (length todos-categories-category-label)))
+  (let* ((len (todos-adjusted-category-label-length))
         (strlen (length str))
-        (strlen-odd (eq (logand strlen 1) 1)) ; oddp from cl.el
+        (strlen-odd (eq (logand strlen 1) 1))
         (padding (max 0 (/ (- len strlen) 2)))
         (padding-left (cond ((eq todos-categories-align 'left) 0)
                             ((eq todos-categories-align 'center) padding)
@@ -2126,7 +2483,7 @@ which is the value of the user option
               'todos-archived-only
             nil)
      'action `(lambda (button) (let ((buf (current-buffer)))
-                                (todos-jump-to-category ,cat)
+                                (todos-jump-to-category nil ,cat)
                                 (kill-buffer buf))))
     ;; Highlight the sorted count column.
     (let* ((beg (+ opoint 7 (length str)))
@@ -2154,8 +2511,9 @@ which is the value of the user option
 (defun todos-display-categories-1 ()
   "Prepare buffer for displaying table of categories and item counts."
   (unless (eq major-mode 'todos-categories-mode)
-    (setq todos-global-current-todos-file (or todos-current-todos-file
-                                             todos-default-todos-file))
+    (setq todos-global-current-todos-file
+         (or todos-current-todos-file
+             (todos-absolute-file-name todos-default-todos-file)))
     (set-window-buffer (selected-window)
                       (set-buffer (get-buffer-create todos-categories-buffer)))
     (kill-all-local-variables)
@@ -2163,7 +2521,6 @@ which is the value of the user option
     (let ((archive (member todos-current-todos-file todos-archives))
          buffer-read-only) 
       (erase-buffer)
-      ;; FIXME: add usage tips?
       (insert (format (concat "Category counts for Todos "
                              (if archive "archive" "file")
                              " \"%s\".")
@@ -2324,6 +2681,7 @@ which is the value of the user option
    (replace-regexp-in-string
     "-+" "-"
     (concat "todos-item-insert-"
+    ;; (concat "todos-insert-item-"
            (mapconcat (lambda (e) (if e (symbol-name e))) arglist "-")))))
 
 (defvar todos-insertion-commands-names
@@ -2339,9 +2697,9 @@ which is the value of the user option
        (arg2 (nth 2 args))
        (arg3 (nth 3 args))
        (arg4 (nth 4 args)))
-    `(defun ,name (&optional arg)
+    `(defun ,name (&optional arg &rest args)
        "Todos item insertion command generated from ARGS."
-       (interactive)
+       (interactive (list current-prefix-arg))
        (todos-insert-item arg ',arg0 ',arg1 ',arg2 ',arg3 ',arg4))))
 
 (defvar todos-insertion-commands
@@ -2376,6 +2734,7 @@ which is the value of the user option
                    (setq key (concat key key1)))))
            todos-insertion-commands-arg-key-list)
       (if (string-match (concat (regexp-quote "todos-item-insert") "\\_>") cname)
+      ;; (if (string-match (concat (regexp-quote "todos-insert-item") "\\_>") cname)
          (setq key (concat key "i")))
       (define-key map key c))))
 
@@ -2392,7 +2751,7 @@ which is the value of the user option
 (defvar todos-key-bindings
   `(
     ;;               display
-    ("Cd"           . todos-display-categories) ;FIXME: Cs todos-show-categories?
+    ("Cd"           . todos-display-categories) ;FIXME: Fc todos-file-categories?
     ("H"            . todos-highlight-item)
     ("N"            . todos-hide-show-item-numbering)
     ("D"            . todos-hide-show-date-time)
@@ -2405,7 +2764,7 @@ which is the value of the user option
     ("V"            . todos-show-done-only)
     ("As"           . todos-show-archive)
     ("Ac"           . todos-choose-archive)
-    ("Y"            . todos-diary-items)
+    ;; ("Y"         . todos-diary-items)
     ("Fe"           . todos-edit-multiline)
     ("Fh"           . todos-highlight-item)
     ("Fn"           . todos-hide-show-item-numbering)
@@ -2421,8 +2780,8 @@ which is the value of the user option
     ;;               navigation                        
     ("f"            . todos-forward-category)
     ("b"            . todos-backward-category)
+    ("t"             . todos-show)
     ("j"            . todos-jump-to-category)
-    ("J"            . todos-jump-to-category-other-file)
     ("n"            . todos-forward-item)
     ("p"            . todos-backward-item)
     ("S"            . todos-search)
@@ -2438,9 +2797,12 @@ which is the value of the user option
     ("ee"           . todos-edit-item)
     ("em"           . todos-edit-multiline-item)
     ("eh"           . todos-edit-item-header)
-    ("edd"          . todos-edit-item-date)
     ("edc"          . todos-edit-item-date-from-calendar)
-    ("edt"          . todos-edit-item-date-is-today)
+    ("edt"          . todos-edit-item-date-to-today)
+    ("edn"          . todos-edit-item-date-day-name)
+    ("edy"          . todos-edit-item-date-year)
+    ("edm"          . todos-edit-item-date-month)
+    ("edd"          . todos-edit-item-date-day)
     ("et"           . todos-edit-item-time)
     ("eyy"          . todos-edit-item-diary-inclusion)
     ;; (""          . todos-edit-category-diary-inclusion)
@@ -2450,7 +2812,6 @@ which is the value of the user option
     ("i"            . ,todos-insertion-map)
     ("k"            . todos-delete-item) ;FIXME: not single letter?
     ("m"            . todos-move-item)
-    ("M"            . todos-move-item-to-file)
     ("r"            . todos-raise-item-priority)
     ("l"            . todos-lower-item-priority)
     ("#"            . todos-set-item-priority)
@@ -2472,7 +2833,6 @@ which is the value of the user option
     map)
   "Todos mode keymap.")
 
-;; FIXME
 (easy-menu-define
   todos-menu todos-mode-map "Todos Menu"
   '("Todos"
@@ -2483,7 +2843,6 @@ which is the value of the user option
      ["Next Category"        todos-forward-category t]
      ["Previous Category"    todos-backward-category t]
      ["Jump to Category"     todos-jump-to-category t]
-     ["Jump to Category in Other File" todos-jump-to-category-other-file t]
      "---"
      ["Search Todos File"    todos-search t]
      ["Clear Highlighting on Search Matches" todos-category-done t])
@@ -2542,9 +2901,12 @@ which is the value of the user option
     (define-key map "n" 'todos-forward-item)
     (define-key map "p" 'todos-backward-item)
     ;; display commands
-    (define-key map "C" 'todos-display-categories)
+    (define-key map "Cd" 'todos-display-categories)
     (define-key map "H" 'todos-highlight-item)
     (define-key map "N" 'todos-hide-show-item-numbering)
+    (define-key map "*"        'todos-mark-unmark-item)
+    (define-key map "C*" 'todos-mark-category)
+    (define-key map "Cu" 'todos-unmark-category)
     ;; (define-key map "" 'todos-hide-show-date-time)
     (define-key map "P" 'todos-print)
     (define-key map "q" 'todos-quit)
@@ -2552,7 +2914,6 @@ which is the value of the user option
     (define-key map "S" 'todos-search)
     (define-key map "t" 'todos-show)
     (define-key map "u" 'todos-unarchive-items)
-    (define-key map "U" 'todos-unarchive-category)
     map)
   "Todos Archive mode keymap.")
 
@@ -2566,17 +2927,19 @@ which is the value of the user option
 (defvar todos-categories-mode-map
   (let ((map (make-sparse-keymap)))
     (suppress-keymap map t)
+    ;; (define-key map "c" 'todos-display-categories-numberically-or-alphabetically)
     (define-key map "c" 'todos-display-categories-alphabetically-or-by-priority)
     (define-key map "t" 'todos-display-categories-sorted-by-todo)
     (define-key map "y" 'todos-display-categories-sorted-by-diary)
     (define-key map "d" 'todos-display-categories-sorted-by-done)
     (define-key map "a" 'todos-display-categories-sorted-by-archived)
+    (define-key map "#" 'todos-set-category-priority)
     (define-key map "l" 'todos-lower-category-priority)
     (define-key map "+" 'todos-lower-category-priority)
     (define-key map "r" 'todos-raise-category-priority)
     (define-key map "-" 'todos-raise-category-priority)
-    (define-key map "n" 'todos-forward-button)
-    (define-key map "p" 'todos-backward-button)
+    (define-key map "n" 'todos-forward-button) ; todos-next-button
+    (define-key map "p" 'todos-backward-button) ; todos-previous-button
     (define-key map [tab] 'todos-forward-button)
     (define-key map [backtab] 'todos-backward-button)
     (define-key map "q" 'todos-quit)
@@ -2628,7 +2991,6 @@ which is the value of the user option
   ""
   (set (make-local-variable 'todos-categories) (todos-set-categories))
   (set (make-local-variable 'todos-category-number) 1)
-  (set (make-local-variable 'todos-first-visit) t)
   (add-hook 'find-file-hook 'todos-display-as-todos-file nil t))
 
 (put 'todos-mode 'mode-class 'special)
@@ -2646,7 +3008,6 @@ which is the value of the user option
                (funcall todos-files-function))
     (set (make-local-variable 'todos-current-todos-file)
         (file-truename (buffer-file-name))))
-  (set (make-local-variable 'todos-first-visit) t)
   (set (make-local-variable 'todos-show-done-only) nil)
   (set (make-local-variable 'todos-categories-with-marks) nil)
   (add-hook 'find-file-hook 'todos-add-to-buffer-list nil t)
@@ -2657,16 +3018,6 @@ which is the value of the user option
            'todos-reset-and-enable-done-separator nil t)
   (add-hook 'kill-buffer-hook 'todos-reset-global-current-todos-file nil t))
 
-(defun todos-unload-hook ()
-  ""
-  (remove-hook 'pre-command-hook 'todos-show-current-file t)
-  (remove-hook 'post-command-hook 'todos-update-buffer-list t)
-  (remove-hook 'find-file-hook 'todos-display-as-todos-file t)
-  (remove-hook 'find-file-hook 'todos-add-to-buffer-list t)
-  (remove-hook 'window-configuration-change-hook
-              'todos-reset-and-enable-done-separator t)
-  (remove-hook 'kill-buffer-hook 'todos-reset-global-current-todos-file t))
-
 (put 'todos-archive-mode 'mode-class 'special)
 
 ;; If todos-mode is parent, all todos-mode key bindings appear to be
@@ -2687,8 +3038,20 @@ which is the value of the user option
   (set (make-local-variable 'todos-current-todos-file)
        todos-global-current-todos-file)
   (let ((cats (with-current-buffer
-                 (find-buffer-visiting todos-current-todos-file)
-               todos-categories)))
+                 ;; Can't use find-buffer-visiting when
+                 ;; `todos-display-categories' is called on first
+                 ;; invocation of `todos-show', since there is then
+                 ;; no buffer visiting the current file.
+                 (find-file-noselect todos-current-todos-file 'nowarn)
+               (or todos-categories
+                   ;; In Todos Edit mode todos-categories is now nil
+                   ;; since it uses same buffer as Todos mode but
+                   ;; doesn't have the latter's local variables.
+                   (save-excursion
+                     (goto-char (point-min))
+                     (read (buffer-substring-no-properties
+                            (line-beginning-position)
+                            (line-end-position))))))))
     (set (make-local-variable 'todos-categories) cats)))
 
 (define-derived-mode todos-edit-mode text-mode "Todos-Ed"
@@ -2696,7 +3059,8 @@ which is the value of the user option
 
 \\{todos-edit-mode-map}"
   (todos-modes-set-1)
-  (todos-mode-external-set))
+  (todos-mode-external-set)
+  (setq buffer-read-only nil))
 
 (put 'todos-categories-mode 'mode-class 'special)
 
@@ -2706,7 +3070,7 @@ which is the value of the user option
 \\{todos-categories-mode-map}"
   (todos-mode-external-set))
 
-(put 'todos-filter-mode 'mode-class 'special)
+(put 'todos-filtered-items-mode 'mode-class 'special)
 
 (define-derived-mode todos-filtered-items-mode special-mode "Todos-Fltr"
   "Mode for displaying and reprioritizing top priority Todos.
@@ -2723,23 +3087,29 @@ which is the value of the user option
 
 ;;;###autoload
 (defun todos-show (&optional solicit-file)
-  "Visit the current Todos file and display one of its categories.
-With non-nil prefix argument SOLICIT-FILE prompt for which todo
-file to visit.
-
-Without a prefix argument, the first invocation of this command
-in a session visits `todos-default-todos-file' (creating it if it
-does not yet exist); subsequent invocations from outside of Todos
-mode revisit this file or, if the user option
-`todos-show-current-file' is non-nil, whichever Todos file
-\(either a todo or an archive file) was visited last.
-
-The category displayed on initial invocation is the first member
-of `todos-categories' for the current Todos file, on subsequent
-invocations whichever category was displayed last.  If
-`todos-display-categories-first' is non-nil, then the first
-invocation of `todos-show' displays a clickable listing of the
-categories in the current Todos file.
+  "Visit a Todos file and display one of its categories.
+
+When invoked in Todos mode, prompt for which todo file to visit.
+When invoked outside of Todos mode with non-nil prefix argument
+SOLICIT-FILE prompt for which todo file to visit; otherwise visit
+`todos-default-todos-file'.  Subsequent invocations from outside
+of Todos mode revisit this file or, with option
+`todos-show-current-file' non-nil (the default), whichever Todos
+file was last visited.
+
+Calling this command before any Todos file exists prompts for a
+file name and an initial category (defaulting to
+`todos-initial-file' and `todos-initial-category'), creates both
+of these, visits the file and displays the category.
+
+The first invocation of this command on an existing Todos file
+interacts with the option `todos-show-first': if its value is
+`first' (the default), show the first category in the file; if
+its value is `table', show the table of categories in the file;
+if its value is one of `top', `diary' or `regexp', show the
+corresponding saved top priorities, diary items, or regexp items
+file, if any.  Subsequent invocations always show the file's
+current (i.e., last displayed) category.
 
 In Todos mode just the category's unfinished todo items are shown
 by default.  The done items are hidden, but typing
@@ -2747,11 +3117,13 @@ by default.  The done items are hidden, but typing
 items.  With non-nil user option `todos-show-with-done' both todo
 and done items are always shown on visiting a category.
 
-If this command is invoked in Todos Archive mode, it visits the
+Invoking this command in Todos Archive mode visits the
 corresponding Todos file, displaying the corresponding category."
   (interactive "P")
   (let* ((cat)
-        (file (cond (solicit-file
+        (show-first todos-show-first)
+        (file (cond ((or (eq major-mode 'todos-mode)
+                         solicit-file)
                      (if (funcall todos-files-function)
                          (todos-read-file-name "Choose a Todos file to visit: "
                                                nil t)
@@ -2767,22 +3139,55 @@ corresponding Todos file, displaying the corresponding category."
                      (or todos-current-todos-file
                          (and todos-show-current-file
                               todos-global-current-todos-file)
-                         todos-default-todos-file
+                         (todos-absolute-file-name todos-default-todos-file)
                          (todos-add-file))))))
-    (if (and todos-first-visit todos-display-categories-first)
-       (todos-display-categories)
+    (unless (member file todos-visited)
+      ;; Can't setq t-c-t-f here, otherwise wrong file shown when
+      ;; todos-show is called from todos-display-categories.
+      (let ((todos-current-todos-file file))
+       (cond ((eq todos-show-first 'table)
+              (todos-display-categories))
+             ((memq todos-show-first '(top diary regexp))
+              (let* ((shortf (todos-short-file-name file))
+                     (fi-file (todos-absolute-file-name
+                               shortf todos-show-first)))
+                (when (eq todos-show-first 'regexp)
+                  (let ((rxfiles (directory-files todos-files-directory t
+                                                  ".*\\.todr$" t)))
+                    (when (and rxfiles (> (length rxfiles) 1))
+                      (let ((rxf (mapcar 'todos-short-file-name rxfiles)))
+                        (setq fi-file (todos-absolute-file-name
+                                       (completing-read
+                                        "Choose a regexp items file: "
+                                        rxf) 'regexp))))))
+                (if (file-exists-p fi-file)
+                    (set-window-buffer
+                     (selected-window)
+                     (set-buffer (find-file-noselect fi-file 'nowarn)))
+                  (message "There is no %s file for %s"
+                           (cond ((eq todos-show-first 'top)
+                                  "top priorities")
+                                 ((eq todos-show-first 'diary)
+                                  "diary items")
+                                 ((eq todos-show-first 'regexp)
+                                  "regexp items"))
+                           shortf)
+                  (setq todos-show-first 'first)))))))
+    (when (or (member file todos-visited)
+             (eq todos-show-first 'first))
       (set-window-buffer (selected-window)
-                        (set-buffer (find-file-noselect file)))
-      ;; If called from archive file, show corresponding category in Todos
-      ;; file, if it exists.
+                        (set-buffer (find-file-noselect file 'nowarn)))
+      ;; If called from archive file, show corresponding
+      ;; category in Todos file, if it exists.
       (when (assoc cat todos-categories)
        (setq todos-category-number (todos-category-number cat)))
-      ;; If no Todos file exists, initialize one.
+      ;; If this is a new Todos file, add its first category.
       (when (zerop (buffer-size))
-       ;; Call with empty category name to get initial prompt.
-       (setq todos-category-number (todos-add-category "")))
+       (setq todos-category-number
+             (todos-add-category todos-current-todos-file "")))
       (save-excursion (todos-category-select)))
-    (setq todos-first-visit nil)))
+    (setq todos-show-first show-first)
+    (add-to-list 'todos-visited file)))
 
 (defun todos-display-categories ()
   "Display a table of the current file's categories and item counts.
@@ -2900,11 +3305,14 @@ displayed."
   (interactive)
   (todos-show-archive t))
 
-;; FIXME: need this?
 (defun todos-save ()
   "Save the current Todos file."
   (interactive)
-  (save-buffer))
+  (cond ((eq major-mode 'todos-filtered-items-mode)
+        (todos-check-filtered-items-file)
+        (todos-save-filtered-items-buffer))
+       (t
+        (save-buffer))))
 
 (defun todos-quit ()
   "Exit the current Todos-related buffer.
@@ -2912,12 +3320,19 @@ Depending on the specific mode, this either kills the buffer or
 buries it and restores state as needed."
   (interactive)
   (cond ((eq major-mode 'todos-categories-mode)
-        (kill-buffer)
-        (setq todos-descending-counts nil)
-        (todos-show))
+        ;; Postpone killing buffer till after calling todos-show, to
+        ;; prevent killing todos-mode buffer.
+        (let ((buf (current-buffer)))
+          (setq todos-descending-counts nil)
+          ;; Ensure todos-show calls todos-display-categories only on
+          ;; first invocation per file.
+          (when (eq todos-show-first 'table)
+            (add-to-list 'todos-visited todos-current-todos-file))
+          (todos-show)
+          (kill-buffer buf)))
        ((eq major-mode 'todos-filtered-items-mode)
         (kill-buffer)
-        (todos-show))
+        (unless (eq major-mode 'todos-mode) (todos-show)))
        ((member major-mode (list 'todos-mode 'todos-archive-mode))
         ;; Have to write previously nonexistant archives to file, and might
         ;; as well save Todos file also.
@@ -3076,7 +3491,8 @@ saved (the latter as a Todos Archive file) with a new name in
                      (delete-region beg (1+ end))
                      (set-marker beg (point))
                      (re-search-backward
-                      (concat "^" (regexp-quote (concat todos-category-beg cat)))
+                      (concat "^" (regexp-quote (concat todos-category-beg cat))
+                              "$")
                       nil t)
                      (forward-line)
                      (if (re-search-forward
@@ -3139,7 +3555,7 @@ category is the first)."
   (when todos-skip-archived-categories
     (while (and (zerop (todos-get-count 'todo))
                (zerop (todos-get-count 'done))
-               (not (zerop (todos-get-count 'archive))))
+               (not (zerop (todos-get-count 'archived))))
       (setq todos-category-number
            (apply (if back '1- '1+) (list todos-category-number)))))
   (todos-category-select)
@@ -3152,129 +3568,92 @@ category."
   (interactive)
   (todos-forward-category t))
 
-(defun todos-jump-to-category (&optional cat other-file)
-  "Jump to a category in this or another Todos file.
+;;;###autoload
+(defun todos-jump-to-category (&optional file cat)
+  "Prompt for a category in a Todos file and jump to it.
+
+With prefix argument FILE, prompt for a specific Todos file and
+choose (with TAB completion) a category in it to jump to;
+otherwise, choose and jump to any category in either the current
+Todos file or a file in `todos-category-completions-files'.
 
-Programmatically, optional argument CAT provides the category
-name.  When nil (as in interactive calls), prompt for the
-category, with TAB completion on existing categories.  If a
-non-existing category name is entered, ask whether to add a new
-category with this name; if affirmed, add it, then jump to that
-category.  With non-nil argument OTHER-FILE, prompt for a Todos
-file, otherwise jump within the current Todos file."
-  (interactive)
-  (let ((file (or (and other-file
-                      (todos-read-file-name "Choose a Todos file: " nil t))
-                 ;; Jump to archived-only Categories from Todos Categories
-                 ;; mode.
-                 (and cat
-                      todos-skip-archived-categories
-                      (zerop (todos-get-count 'todo cat))
-                      (zerop (todos-get-count 'done cat))
-                      (not (zerop (todos-get-count 'archived cat)))
+You can also enter a non-existing category name, triggering a
+prompt whether to add a new category by that name; on
+confirmation it is added and jumped to.
+
+Noninteractively, jump directly to the category named by argument
+CAT; this is used in Todos Categories mode."
+  (interactive "P")
+  ;; If invoked outside of Todos mode and there is not yet any Todos
+  ;; file, initialize one.
+  (if (null todos-files)
+      (todos-show)
+    (let ((file0 (when cat             ; We're in Todos Categories mode.
+                  ;; With non-nil `todos-skip-archived-categories'
+                  ;; jump to archive file of a category with only
+                  ;; archived items.
+                  (if (and todos-skip-archived-categories
+                           (zerop (todos-get-count 'todo cat))
+                           (zerop (todos-get-count 'done cat))
+                           (not (zerop (todos-get-count 'archived cat))))
                       (concat (file-name-sans-extension
-                               todos-current-todos-file) ".toda"))
-                 todos-current-todos-file
-                 ;; If invoked from outside of Todos mode before
-                 ;; todos-show...
-                 todos-default-todos-file)))
-    (with-current-buffer (find-file-noselect file)
-      (and other-file (setq todos-current-todos-file file))
-      (let ((category (or (and (assoc cat todos-categories) cat)
-                         (todos-read-category "Jump to category: "))))
-       ;; Clean up after selecting category in Todos Categories mode.
+                               todos-current-todos-file) ".toda")
+                    ;; Otherwise, jump to current todos file.
+                    todos-current-todos-file)))
+         (cat+file (unless cat
+                     (todos-read-category "Jump to category: " nil file))))
+      (setq category (or cat (car cat+file)))
+      (unless cat (setq file0 (cdr cat+file)))
+      (with-current-buffer (find-file-noselect file0 'nowarn)
+       (setq todos-current-todos-file file0)
+       ;; If called from Todos Categories mode, clean up before jumping.
        (if (string= (buffer-name) todos-categories-buffer)
            (kill-buffer))
-       (if (or cat other-file)
-           (set-window-buffer (selected-window)
-                              (set-buffer (find-buffer-visiting file))))
+       (set-window-buffer (selected-window)
+                          (set-buffer (find-buffer-visiting file0)))
        (unless todos-global-current-todos-file
          (setq todos-global-current-todos-file todos-current-todos-file))
-       (todos-category-number category) ; (1+ (length t-c)) if new category.
-       ;; (if (> todos-category-number (length todos-categories))
-       ;;     (setq todos-category-number (todos-add-category category)))
+       (todos-category-number category)
        (todos-category-select)
        (goto-char (point-min))))))
 
-(defun todos-jump-to-category-other-file ()
-  "Jump to a category in another Todos file.
-The category is chosen by prompt, with TAB completion."
-  (interactive)
-  (todos-jump-to-category nil t))
-
-(defun todos-jump-to-any-category ()
-  ""
-  (interactive)
-  (let* ((cats-alist todos-all-categories-alist)
-        (cats (mapcar 'car cats-alist))
-        (completion-ignore-case todos-completion-ignore-case)
-        (cat (completing-read "Jump to category: " cats nil t))
-        (files (if (zerop (length cat))
-                   (keyboard-quit)
-                 (cdr (assoc cat cats-alist))))
-        (file (if (nlistp files)
-                  files
-                (completing-read (format "Jump to \"%s\" in which file? " cat)
-                                 files nil t))))
-    (if (zerop (length file))
-       (keyboard-quit)
-      (setq file (concat todos-files-directory file ".todo"))
-      (set-window-buffer (selected-window)
-                        (set-buffer (find-file-noselect file)))
-      (unless todos-global-current-todos-file
-       (setq todos-global-current-todos-file todos-current-todos-file))
-      (todos-category-number cat)
-      (todos-category-select)
-       (goto-char (point-min)))))
-
 (defun todos-jump-to-item ()
   "Jump to the file and category of the filtered item at point."
   (interactive)
-  (let ((str (todos-item-string))
-       (buf (current-buffer))
-       cat file archive beg)
-    (string-match (concat (if todos-filter-done-items
-                             (concat "\\(?:" todos-done-string-start "\\|"
-                                     todos-date-string-start "\\)")
-                           todos-date-string-start)
-                         todos-date-pattern "\\(?: " diary-time-regexp "\\)?"
-                         (if todos-filter-done-items
-                             "\\]"
-                           (regexp-quote todos-nondiary-end)) "?"
-                         "\\(?4: \\[\\(?3:(archive) \\)?\\(?2:.*:\\)?"
-                         "\\(?1:.*\\)\\]\\).*$") str)
-    (setq cat (match-string 1 str))
-    (setq file (match-string 2 str))
-    (setq archive (string= (match-string 3 str) "(archive) "))
-    (setq str (replace-match "" nil nil str 4))
-    (setq file (if file
-                  (concat todos-files-directory (substring file 0 -1)
-                          (if archive ".toda" ".todo"))
-                (if archive
-                    (concat (file-name-sans-extension
-                             todos-global-current-todos-file) ".toda")
-                  todos-global-current-todos-file)))
-    (find-file-noselect file)
-    (with-current-buffer (find-buffer-visiting file)
-      (widen)
-      (goto-char (point-min))
-      (re-search-forward
-       (concat "^" (regexp-quote (concat todos-category-beg cat))) nil t)
-      (search-forward str)
-      (setq beg (match-beginning 0)))
-    (kill-buffer buf)
-    (set-window-buffer (selected-window) (set-buffer (find-buffer-visiting file)))
-    (setq todos-current-todos-file file)
-    (setq todos-category-number (todos-category-number cat))
-    (let ((todos-show-with-done (if todos-filter-done-items t
-                                 todos-show-with-done)))
-      (todos-category-select))
-    (goto-char beg)))
+  (let* ((str (todos-item-string))
+        (buf (current-buffer))
+        (res (todos-find-item str))
+        (found (nth 0 res))
+        (file (nth 1 res))
+        (cat (nth 2 res)))
+    (if (not found)
+       (message "Category %s does not contain this item." cat)
+      (kill-buffer buf)
+      (set-window-buffer (selected-window)
+                        (set-buffer (find-buffer-visiting file)))
+      (setq todos-current-todos-file file)
+      (setq todos-category-number (todos-category-number cat))
+      (let ((todos-show-with-done (if (or todos-filter-done-items
+                                         (eq (cdr found) 'done))
+                                     t
+                                   todos-show-with-done)))
+       (todos-category-select))
+      (goto-char (car found)))))
 
 (defun todos-forward-item (&optional count)
   "Move point down to start of item with next lower priority.
 With positive numerical prefix COUNT, move point COUNT items
-downward."
+downward.
+
+If the category's done items are hidden, this command also moves
+point to the empty line below the last todo item from any higher
+item in the category, i.e., when invoked with or without a prefix
+argument.  If the category's done items are visible, this command
+called with a prefix argument only moves point to a lower item,
+e.g., with point on the last todo item and called with prefix 1,
+it moves point to the first done item; but if called with point
+on the last todo item without a prefix argument, it moves point
+the the empty line above the done items separator."
   (interactive "P")
   ;; It's not worth the trouble to allow prefix arg value < 1, since we have
   ;; the corresponding command.
@@ -3290,9 +3669,9 @@ downward."
       ;; space above todos-done-separator, since that is a legitimate place to
       ;; insert an item.  But skip this space if count > 1, since that should
       ;; only stop on an item.
-      (when (and not-done (todos-done-item-p))
-       (if (or (not count) (= count 1))
-           (re-search-backward "^$" start t))))))
+      (when (and not-done (todos-done-item-p) (not count))
+       ;; (if (or (not count) (= count 1))
+           (re-search-backward "^$" start t)))));)
     ;; FIXME: The preceding sexp is insufficient when buffer is not narrowed,
     ;; since there could be no done items in this category, so the search puts
     ;; us on first todo item of next category.  Does this ever happen?  If so:
@@ -3309,7 +3688,14 @@ downward."
 (defun todos-backward-item (&optional count)
   "Move point up to start of item with next higher priority.
 With positive numerical prefix COUNT, move point COUNT items
-upward."
+upward.
+
+If the category's done items are visible, this command called
+with a prefix argument only moves point to a higher item, e.g.,
+with point on the first done item and called with prefix 1, it
+moves to the last todo item; but if called with point on the
+first done item without a prefix argument, it moves point the the
+empty line above the done items separator."
   (interactive "P")
   ;; Avoid moving to bob if on the first item but not at bob.
   (when (> (line-number-at-pos) 1)
@@ -3327,7 +3713,8 @@ upward."
        ;; todos-done-separator, since that is a legitimate place to insert an
        ;; item.  But skip this space if count > 1, since that should only
        ;; stop on an item.
-       (when (and done (not (todos-done-item-p)) (or (not count) (= count 1))
+       (when (and done (not (todos-done-item-p)) (not count)
+                                       ;(or (not count) (= count 1))
                   (not (equal (buffer-name) todos-regexp-items-buffer)))
          (re-search-forward (concat "^" (regexp-quote todos-category-done))
                             nil t)
@@ -3349,9 +3736,6 @@ upward."
        ;; Align with beginning of category label.
        (forward-char (+ 4 (length todos-categories-number-separator)))))
 
-;; FIXME: (i) Extend search to other Todos files. (ii) Allow navigating among
-;; hits. (But these features are effectively available with
-;; todos-regexp-items-multifile, so maybe it's not worth the trouble here.)
 (defun todos-search ()
   "Search for a regular expression in this Todos file.
 The search runs through the whole file and encompasses all and
@@ -3431,11 +3815,21 @@ face."
   (interactive)
   (if (zerop (todos-get-count 'done (todos-current-category)))
       (message "There are no done items in this category.")
-    (save-excursion
+    (let ((opoint (point)))
       (goto-char (point-min))
-      (let ((todos-show-with-done (not (re-search-forward
-                                       todos-done-string-start nil t))))
-       (todos-category-select)))))
+      (let* ((shown (re-search-forward todos-done-string-start nil t))
+            (todos-show-with-done (not shown)))
+       (todos-category-select)
+       (goto-char opoint)
+       ;; If start of done items sections is below the bottom of the
+       ;; window, make it visible.
+       (unless shown
+         (setq shown (progn
+                       (goto-char (point-min))
+                       (re-search-forward todos-done-string-start nil t)))
+         (if (not (pos-visible-in-window-p shown))
+             (recenter)
+           (goto-char opoint)))))))
 
 (defun todos-show-done-only ()
   "Switch between displaying only done or only todo items."
@@ -3457,78 +3851,78 @@ face."
   (save-excursion
     (save-restriction
       (goto-char (point-min))
-      (let ((ovs (overlays-in (point) (1+ (point))))
-           ov hidden)
-       (while ovs
-         (setq ov (pop ovs))
-         (if (equal (overlay-get ov 'display) "")
-             (setq ovs nil hidden t)))
+      (if (todos-get-overlay 'header)
+         (remove-overlays 1 (1+ (buffer-size)) 'todos 'header)
        (widen)
        (goto-char (point-min))
-       (if hidden
-           (remove-overlays (point-min) (point-max) 'display "")
-         (while (not (eobp))
-           (when (re-search-forward
-                  (concat todos-date-string-start todos-date-pattern
-                          "\\( " diary-time-regexp "\\)?"
-                          (regexp-quote todos-nondiary-end) "? ")
-                  nil t)
-             (unless (save-match-data (todos-done-item-p))
-               (setq ov (make-overlay (match-beginning 0) (match-end 0) nil t))
-               (overlay-put ov 'display "")))
-           (todos-forward-item)))))))
-
-(defun todos-mark-unmark-item (&optional n all)
-  "Mark item at point if unmarked, or unmark it if marked.
-
+       (while (not (eobp))
+         (when (re-search-forward
+                (concat todos-date-string-start todos-date-pattern
+                        "\\( " diary-time-regexp "\\)?"
+                        (regexp-quote todos-nondiary-end) "? ")
+                nil t)
+           (unless (save-match-data (todos-done-item-p))
+             (setq ov (make-overlay (match-beginning 0) (match-end 0) nil t))
+             (overlay-put ov 'todos 'header)
+             (overlay-put ov 'display "")))
+         (todos-forward-item))))))
+
+(defun todos-mark-unmark-item (&optional n)
+  "Mark item with `todos-item-mark' if unmarked, otherwise unmark it.
 With a positive numerical prefix argument N, change the
-markedness of the next N items.  With non-nil argument ALL, mark
-all visible items in the category (depending on visibility, all
-todo and done items, or just todo or just done items).
-
-The mark is the character \"*\" inserted in front of the item's
-priority number or the `todos-prefix' string; if `todos-prefix'
-is \"*\", then the mark is \"@\"."
+marking of the next N items."
   (interactive "p")
-  (if all (goto-char (point-min)))
-  (unless (> n 0) (setq n 1))
-  (let ((i 0))
-    (while (or (and all (not (eobp)))
-              (< i n))
-      (let* ((cat (todos-current-category))
-            (ov (todos-marked-item-p))
-            (marked (assoc cat todos-categories-with-marks)))
-       (if (and ov (not all))
-           (progn
-             (delete-overlay ov)
-             (if (= (cdr marked) 1)    ; Deleted last mark in this category.
-                 (setq todos-categories-with-marks
-                       (assq-delete-all cat todos-categories-with-marks))
-               (setcdr marked (1- (cdr marked)))))
-         (when (todos-item-start)
-           (unless (and all (todos-marked-item-p))
-             (setq ov (make-overlay (point) (point)))
-             (overlay-put ov 'before-string todos-item-mark)
-             (if marked
-                 (setcdr marked (1+ (cdr marked)))
-               (push (cons cat 1) todos-categories-with-marks))))))
-      (todos-forward-item)
-      (setq i (1+ i)))))
+  (unless (> n 1) (setq n 1))
+  (dotimes (i n)
+    (let* ((cat (todos-current-category))
+          (marks (assoc cat todos-categories-with-marks))
+          (ov (todos-get-overlay 'prefix))
+          (pref (overlay-get ov 'before-string)))
+      (if (todos-marked-item-p)
+         (progn
+           (overlay-put ov 'before-string (substring pref 1))
+           (if (= (cdr marks) 1)       ; Deleted last mark in this category.
+               (setq todos-categories-with-marks
+                     (assq-delete-all cat todos-categories-with-marks))
+             (setcdr marks (1- (cdr marks)))))
+       (overlay-put ov 'before-string (concat todos-item-mark pref))
+       (if marks
+           (setcdr marks (1+ (cdr marks)))
+         (push (cons cat 1) todos-categories-with-marks))))
+    (todos-forward-item)))
 
 (defun todos-mark-category ()
-  "Put the \"*\" mark on all items in this category.
-\(If `todos-prefix' is \"*\", then the mark is \"@\".)"
+  "Mark all visiblw items in this category with `todos-item-mark'."
   (interactive)
-  (todos-mark-unmark-item 0 t))
+  (let* ((cat (todos-current-category))
+        (marks (assoc cat todos-categories-with-marks)))
+    (save-excursion
+      (goto-char (point-min))
+      (while (not (eobp))
+       (let* ((ov (todos-get-overlay 'prefix))
+              (pref (overlay-get ov 'before-string)))
+         (unless (todos-marked-item-p)
+           (overlay-put ov 'before-string (concat todos-item-mark pref))
+           (if marks
+               (setcdr marks (1+ (cdr marks)))
+             (push (cons cat 1) todos-categories-with-marks))))
+       (todos-forward-item)))))
 
 (defun todos-unmark-category ()
-  "Remove the \"*\" mark from all items in this category.
-\(If `todos-prefix' is \"*\", then the mark is \"@\".)"
+  "Remove `todos-item-mark' from all visible items in this category."
   (interactive)
-  (remove-overlays (point-min) (point-max) 'before-string todos-item-mark)
-  (setq todos-categories-with-marks
-       (delq (assoc (todos-current-category) todos-categories-with-marks)
-             todos-categories-with-marks)))
+  (let* ((cat (todos-current-category))
+        (marks (assoc cat todos-categories-with-marks)))
+    (save-excursion
+      (goto-char (point-min))
+      (while (not (eobp))
+       (let* ((ov (todos-get-overlay 'prefix))
+              ;; No overlay on empty line between todo and done items.
+              (pref (when ov (overlay-get ov 'before-string))))
+         (when (todos-marked-item-p)
+           (overlay-put ov 'before-string (substring pref 1)))
+         (todos-forward-item))))
+    (setq todos-categories-with-marks (delq marks todos-categories-with-marks))))
 
 ;; ---------------------------------------------------------------------------
 ;;; Item filtering commands
@@ -3545,86 +3939,106 @@ See `todos-set-top-priorities' for more details."
   (interactive)
   (todos-set-top-priorities t))
 
-(defun todos-top-priorities (&optional num)
-  "List top priorities of each category in `todos-filter-files'.
-Number of entries for each category is given by NUM, which
-defaults to `todos-show-priorities'."
+(defun todos-top-priorities (&optional arg)
+  "Display a list of top priority items from different categories.
+The categories can be any of those in the current Todos file.
+
+With numerical prefix ARG show at most ARG top priority items
+from each category.  With `C-u' as prefix argument show the
+numbers of top priority items specified by category in
+`todos-priorities-rules', if this has an entry for the file(s);
+otherwise show `todos-show-priorities' items per category in the
+file(s).  With no prefix argument, if a top priorities file for
+the current Todos file has previously been saved (see
+`todos-save-filtered-items-buffer'), visit this file; if there is
+no such file, build the list as with prefix argument `C-u'.
+
+  The prefix ARG regulates how many top priorities from
+each category to show, as described above."
   (interactive "P")
-  (let ((arg (if num (cons 'top num) 'top))
-       (buf todos-top-priorities-buffer)
-       (file todos-current-todos-file))
-    (todos-filter-items arg)
-    (todos-filtered-buffer-name buf file)))
+  (todos-filter-items 'top arg))
 
 (defun todos-top-priorities-multifile (&optional arg)
-  "List top priorities of each category in `todos-filter-files'.
-
-If the prefix argument ARG is a number, this is the maximum
-number of top priorities to list in each category.  If the prefix
-argument is `C-u', prompt for which files to filter and use
-`todos-show-priorities' as the number of top priorities to list
-in each category.  If the prefix argument is `C-uC-u', prompt
-both for which files to filter and for how many top priorities to
-list in each category."
+  "Display a list of top priority items from different categories.
+The categories are a subset of the categories in the files listed
+in `todos-filter-files', or if this nil, in the files chosen from
+a file selection dialog that pops up in this case.
+
+With numerical prefix ARG show at most ARG top priority items
+from each category in each file.  With `C-u' as prefix argument
+show the numbers of top priority items specified in
+`todos-priorities-rules', if this is non-nil; otherwise show
+`todos-show-priorities' items per category.  With no prefix
+argument, if a top priorities file for the chosen Todos files
+exists (see `todos-save-filtered-items-buffer'), visit this file;
+if there is no such file, do the same as with prefix argument
+`C-u'."
   (interactive "P")
-  (let* ((buf todos-top-priorities-buffer)
-        files
-        (pref (if (numberp arg)
-                  (cons 'top arg)
-                (setq files (if (or (consp arg)
-                                    (null todos-filter-files))
-                                (progn (todos-multiple-filter-files)
-                                       todos-multiple-filter-files)
-                              todos-filter-files))
-                (if (equal arg '(16))
-                    (cons 'top (read-number
-                                "Enter number of top priorities to show: "
-                                todos-show-priorities))
-                  'top))))
-    (todos-filter-items pref t)
-    (todos-filtered-buffer-name buf files)))
-
-(defun todos-diary-items ()
-  "Display todo items for diary inclusion in this Todos file."
-  (interactive)
-  (let ((buf todos-diary-items-buffer)
-       (file todos-current-todos-file))
-    (todos-filter-items 'diary)
-    (todos-filtered-buffer-name buf file)))
+  (todos-filter-items 'top arg t))
+
+(defun todos-diary-items (&optional arg)
+  "Display a list of todo diary items from different categories.
+The categories can be any of those in the current Todos file.
+
+Called with no prefix argument, if a diary items file for the
+current Todos file has previously been saved (see
+`todos-save-filtered-items-buffer'), visit this file; if there is
+no such file, build the list of diary items.  Called with a
+prefix argument, build the list even if there is a saved file of
+diary items."
+  (interactive "P")
+  (todos-filter-items 'diary arg))
 
 (defun todos-diary-items-multifile (&optional arg)
-  "Display todo items for diary inclusion in one or more Todos file.
-The files are those listed in `todos-filter-files'."
+  "Display a list of todo diary items from different categories.
+The categories are a subset of the categories in the files listed
+in `todos-filter-files', or if this nil, in the files chosen from
+a file selection dialog that pops up in this case.
+
+Called with no prefix argument, if a diary items file for the
+chosen Todos files has previously been saved (see
+`todos-save-filtered-items-buffer'), visit this file; if there is
+no such file, build the list of diary items.  Called with a
+prefix argument, build the list even if there is a saved file of
+diary items."
   (interactive "P")
-  (let ((buf todos-diary-items-buffer)
-       (files (if (or arg (null todos-filter-files))
-                  (progn (todos-multiple-filter-files)
-                         todos-multiple-filter-files)
-                todos-filter-files)))
-    (todos-filter-items 'diary t)
-    (todos-filtered-buffer-name buf files)))
-
-(defun todos-regexp-items ()
-  "Display todo items matching a user-entered regular expression.
-The items are those in the current Todos file."
-  (interactive)
-  (let ((buf todos-regexp-items-buffer)
-       (file todos-current-todos-file))
-    (todos-filter-items 'regexp)
-    (todos-filtered-buffer-name buf file)))
+  (todos-filter-items 'diary arg t))
+
+(defun todos-regexp-items (&optional arg)
+  "Prompt for a regular expression and display items that match it.
+The matches can be from any categories in the current Todos file
+and with non-nil option `todos-filter-done-items', can include
+not only todo items but also done items, including those in
+Archive files.
+
+Called with no prefix argument, if a regexp items file for the
+current Todos file has previously been saved (see
+`todos-save-filtered-items-buffer'), visit this file; if there is
+no such file, build the list of regexp items.  Called with a
+prefix argument, build the list even if there is a saved file of
+regexp items."
+  (interactive "P")
+  (todos-filter-items 'regexp arg))
 
 (defun todos-regexp-items-multifile (&optional arg)
-  "Display todo items matching a user-entered regular expression.
-The items are those in the files listed in `todos-filter-files'."
+  "Prompt for a regular expression and display items that match it.
+The matches can be from any categories in the files listed in
+`todos-filter-files', or if this nil, in the files chosen from a
+file selection dialog that pops up in this case.  With non-nil
+option `todos-filter-done-items', the matches can include not
+only todo items but also done items, including those in Archive
+files.
+
+Called with no prefix argument, if a regexp items file for the
+current Todos file has previously been saved (see
+`todos-save-filtered-items-buffer'), visit this file; if there is
+no such file, build the list of regexp items.  Called with a
+prefix argument, build the list even if there is a saved file of
+regexp items."
   (interactive "P")
-  (let ((buf todos-regexp-items-buffer)
-       (files (if (or arg (null todos-filter-files))
-                  (progn (todos-multiple-filter-files)
-                         todos-multiple-filter-files)
-                todos-filter-files)))
-    (todos-filter-items 'regexp t)
-    (todos-filtered-buffer-name buf files)))
+  (todos-filter-items 'regexp arg t))
 
+;; ---------------------------------------------------------------------------
 ;;; Editing Commands
 
 (defun todos-add-file ()
@@ -3649,33 +4063,53 @@ Noninteractively, return the name of the new file."
          (todos-show))
       file)))
 
-;; ---------------------------------------------------------------------------
 ;;; Category editing commands
 
-(defun todos-add-category (&optional cat)
-  "Add a new category to the current Todos file.
-Called interactively, prompts for category name, then visits the
-category in Todos mode.  Non-interactively, argument CAT provides
-the category name and the return value is the category number."
-  (interactive)
-  (let* ((buffer-read-only)
-        (num (1+ (length todos-categories)))
-        (counts (make-vector 4 0)))    ; [todo diary done archived]
-    (unless cat
-      (setq cat (todos-read-category "Enter new category name: " nil t)))
-    (setq todos-categories (append todos-categories (list (cons cat counts))))
-    (widen)
-    (goto-char (point-max))
-    (save-excursion                    ; Save point for todos-category-select.
-      (insert todos-category-beg cat "\n\n" todos-category-done "\n"))
-    (todos-update-categories-sexp)
-    ;; If invoked by user, display the newly added category, if called
-    ;; programmatically return the category number to the caller.
-    (if (called-interactively-p 'any)
-       (progn
-         (setq todos-category-number num)
-         (todos-category-select))
-      num)))
+(defun todos-add-category (&optional file cat)
+  "Add a new category to a Todos file.
+
+Called interactively with prefix argument FILE, prompt for a file
+and then for a new category to add to that file, otherwise prompt
+just for a category to add to the current Todos file.  After adding
+the category, visit it in Todos mode.
+
+Non-interactively, add category CAT to file FILE; if FILE is nil,
+add CAT to the current Todos file.  After adding the category,
+return the new category number."
+  (interactive "P")
+  (let (catfil file0)
+    ;; If cat is passed from caller, don't prompt, unless it is "",
+    ;; which means the file was just added and has no category yet.
+    (if (and cat (> (length cat) 0))
+       (setq file0 (or (and (stringp file) file)
+                       todos-current-todos-file))
+      (setq catfil (todos-read-category "Enter a new category name: "
+                                       'add (when (called-interactively-p 'any)
+                                              file))
+           cat (car catfil)
+           file0 (if (called-interactively-p 'any)
+                     (cdr catfil)
+                   file)))
+    (find-file file0)
+    (let ((counts (make-vector 4 0))   ; [todo diary done archived]
+         (num (1+ (length todos-categories)))
+         (buffer-read-only nil))
+      (setq todos-current-todos-file file0)
+      (setq todos-categories (append todos-categories
+                                    (list (cons cat counts))))
+      (widen)
+      (goto-char (point-max))
+      (save-excursion                  ; Save point for todos-category-select.
+       (insert todos-category-beg cat "\n\n" todos-category-done "\n"))
+      (todos-update-categories-sexp)
+      ;; If invoked by user, display the newly added category, if
+      ;; called programmatically return the category number to the
+      ;; caller.
+      (if (called-interactively-p 'any)
+         (progn
+           (setq todos-category-number num)
+           (todos-category-select))
+       num))))
 
 (defun todos-rename-category ()
   "Rename current Todos category.
@@ -3731,7 +4165,7 @@ i.e. including all existing todo and done items."
                                     "the archived category will remain\n"
                                     "after deleting the todo category.  "
                                     "Do you still want to delete it\n"
-                                    "(see 'todos-skip-archived-categories' "
+                                    "(see `todos-skip-archived-categories' "
                                     "for another option)? ")))
                  (t
                   (y-or-n-p (concat "Permanently remove category \"" cat
@@ -3794,8 +4228,8 @@ archive of the file moved to, creating it if it does not exist."
          (widen)
          (goto-char (point-max))
          (let* ((beg (re-search-backward
-                      (concat "^"
-                              (regexp-quote (concat todos-category-beg cat)))
+                      (concat "^" (regexp-quote (concat todos-category-beg cat))
+                              "$")
                       nil t))
                 (end (if (re-search-forward
                           (concat "^" (regexp-quote todos-category-beg))
@@ -3836,15 +4270,14 @@ archive of the file moved to, creating it if it does not exist."
                  (goto-char (point-max))
                  (re-search-backward
                   (concat "^" (regexp-quote todos-category-beg)
-                          "\\(" (regexp-quote cat) "\\)") nil t)
+                          "\\(" (regexp-quote cat) "\\)$") nil t)
                  (replace-match new nil nil nil 1)))
              (setq todos-categories
                    (append todos-categories (list (cons new counts))))
              (todos-update-categories-sexp)
-             ;; If archive was just created, save it to avoid "File <xyz> no
-             ;; longer exists!" message on invoking
-             ;; `todos-view-archived-items'.  FIXME: maybe better to save
-             ;; unconditionally?
+             ;; If archive was just created, save it to avoid "File
+             ;; <xyz> no longer exists!" message on invoking
+             ;; `todos-view-archived-items'.
              (unless (file-exists-p (buffer-file-name))
                (save-buffer))
              (todos-category-number (or new cat))
@@ -3874,23 +4307,31 @@ archive of the file moved to, creating it if it does not exist."
       (todos-category-number (or new cat))
       (todos-category-select))))
 
-(defun todos-merge-category ()
-  "Merge current category into another category in this file.
+(defun todos-merge-category (&optional file)
+  "Merge current category into another existing category.
 
-The current category's todo and done items are appended to the
-chosen goal category's todo and done items, respectively.  The
-goal category becomes the current category, and the previous
-current category is deleted.
+With prefix argument FILE, prompt for a specific Todos file and
+choose (with TAB completion) a category in it to merge into;
+otherwise, choose and merge into a category in either the
+current Todos file or a file in `todos-category-completions-files'.
+
+After merging, the current category's todo and done items are
+appended to the chosen goal category's todo and done items,
+respectively.  The goal category becomes the current category,
+and the previous current category is deleted.
 
 If both the first and goal categories also have archived items,
 the former are merged to the latter.  If only the first category
 has archived items, the archived category is renamed to the goal
 category."
-  (interactive)
+  (interactive "P")
   (let* ((tfile todos-current-todos-file)
-        (archive (concat (file-name-sans-extension tfile) ".toda"))
+        (archive (concat (file-name-sans-extension (if file gfile tfile))
+                         ".toda"))
         (cat (todos-current-category))
-        (goal (todos-read-category "Category to merge to: " t))
+        (cat+file (todos-read-category "Merge into category: " 'merge file))
+        (goal (car cat+file))
+        (gfile  (cdr cat+file))
         archived-count here)
     ;; Merge in todo file.
     (with-current-buffer (get-buffer (find-file-noselect tfile))
@@ -3920,7 +4361,8 @@ category."
        ;; Merge any todo items.
        (unless (zerop (length todo))
          (re-search-forward
-          (concat "^" (regexp-quote (concat todos-category-beg goal))) nil t)
+          (concat "^" (regexp-quote (concat todos-category-beg goal)) "$")
+          nil t)
          (re-search-forward
           (concat "^" (regexp-quote todos-category-done)) nil t)
          (forward-line -1)
@@ -3951,14 +4393,14 @@ category."
              (cbeg (save-excursion
                      (when (re-search-forward
                             (concat "^" (regexp-quote
-                                         (concat todos-category-beg cat)))
+                                         (concat todos-category-beg cat)) "$")
                             nil t)
                        (goto-char (match-beginning 0))
                        (point-marker))))
              (gbeg (save-excursion
                      (when (re-search-forward
                             (concat "^" (regexp-quote
-                                         (concat todos-category-beg goal)))
+                                         (concat todos-category-beg goal)) "$")
                             nil t)
                        (goto-char (match-beginning 0))
                        (point-marker))))
@@ -4071,7 +4513,6 @@ raise or lower the category's priority by one."
 ;; ---------------------------------------------------------------------------
 ;;; Item editing commands
 
-;; FIXME: make insertion options customizable per category?
 ;;;###autoload
 (defun todos-insert-item (&optional arg diary nonmarking date-type time
                                    region-or-here)
@@ -4133,12 +4574,15 @@ omit the current time string according as
 The argument REGION-OR-HERE determines the source and location of
 the new item:
 - If the REGION-OR-HERE is the symbol `here', prompt for the text
-  of the new item and insert it directly above the todo item at
+  of the new item and, if the command was invoked in the current
+  category, insert it directly above the todo item at
   point (hence lowering the priority of the remaining items), or
   if point is on the empty line below the last todo item, insert
-  the new item there.  An error is signalled if
-  `todos-insert-item' is invoked with `here' outside of the
-  current category.
+  the new item there.  If point is in the done items section of
+  the category, insert the new item as the first todo item in the
+  category.  Likewise, if the command with `here' is invoked
+  outside of the current category, jump to the chosen category
+  and insert the new item as the first item in the category.
 - If REGION-OR-HERE is the symbol `region', use the region of the
   current buffer as the text of the new item, depending on the
   value of user option `todos-use-only-highlighted-region': if
@@ -4168,79 +4612,147 @@ the priority is not given by HERE but by prompting."
 ;; binding is also provided with the function
 ;; `todos-insertion-bindings'."                ;FIXME
   (interactive "P")
-  (let ((region (eq region-or-here 'region))
-       (here (eq region-or-here 'here)))
-    (when region
-      (let (use-empty-active-region)
-       (unless (and todos-use-only-highlighted-region (use-region-p))
-         (error "There is no active region"))))
-    (let* ((buf (current-buffer))
-          (new-item (if region
-                        (buffer-substring-no-properties
-                         (region-beginning) (region-end))
-                      (read-from-minibuffer "Todo item: ")))
-          (date-string (cond
-                        ((eq date-type 'date)
-                         (todos-read-date))
-                        ((eq date-type 'dayname)
-                         (todos-read-dayname))
-                        ((eq date-type 'calendar)
-                         (setq todos-date-from-calendar t)
-                         (todos-set-date-from-calendar))
-                        ((and (stringp date-type)
-                              (string-match todos-date-pattern date-type))
-                         (setq todos-date-from-calendar date-type)
-                         (todos-set-date-from-calendar))
-                        (t (calendar-date-string (calendar-current-date) t t))))
-          (time-string (or (and time (todos-read-time))
-                           (and todos-always-add-time-string
-                                (substring (current-time-string) 11 16)))))
-      (setq todos-date-from-calendar nil)
-      (cond ((equal arg '(16))
-            (todos-jump-to-category nil t)
-            (set-window-buffer
-             (selected-window)
-             (set-buffer (find-buffer-visiting todos-global-current-todos-file))))
-           ((equal arg '(4))
-            (todos-jump-to-category)
-            (set-window-buffer
-             (selected-window)
-             (set-buffer (find-buffer-visiting todos-global-current-todos-file))))
-           (t
-            (when (not (derived-mode-p 'todos-mode)) (todos-show))))
-      (let (buffer-read-only)
-       (setq new-item
-             ;; Add date, time and diary marking as required.
-             (concat (if (not (and diary (not todos-include-in-diary)))
-                         todos-nondiary-start
-                       (when (and nonmarking (not todos-diary-nonmarking))
-                         diary-nonmarking-symbol))
-                     date-string (when (and time-string ; Can be empty string.
-                                            (not (zerop (length time-string))))
-                                   (concat " " time-string))
-                     (when (not (and diary (not todos-include-in-diary)))
-                       todos-nondiary-end)
-                     " " new-item))
-       ;; Indent newlines inserted by C-q C-j if nonspace char follows.
-       (setq new-item (replace-regexp-in-string
-                       "\\(\n\\)[^[:blank:]]"
-                       (concat "\n" (make-string todos-indent-to-here 32))
-                       new-item nil nil 1))
-       (if here
-           (cond ((not (eq major-mode 'todos-mode))
-                  (error "Cannot insert a todo item here outside of Todos mode"))
-                 ((not (eq buf (current-buffer)))
-                  (error "Cannot insert an item here after changing buffer"))
-                 ((or (todos-done-item-p)
-                      ;; Point on last blank line.
-                      (save-excursion (forward-line -1) (todos-done-item-p)))
-                  (error "Cannot insert a new item in the done item section"))
-                 (t
-                  (todos-insert-with-overlays new-item)))
-         (todos-set-item-priority new-item (todos-current-category) t))
-       (todos-update-count 'todo 1)
-       (if (or diary todos-include-in-diary) (todos-update-count 'diary 1))
-       (todos-update-categories-sexp)))))
+  ;; If invoked outside of Todos mode and there is not yet any Todos
+  ;; file, initialize one.
+  (if (null todos-files)
+      (todos-show)
+    (let ((region (eq region-or-here 'region))
+         (here (eq region-or-here 'here)))
+      (when region
+       (let (use-empty-active-region)
+         (unless (and todos-use-only-highlighted-region (use-region-p))
+           (error "There is no active region"))))
+      (let* ((obuf (current-buffer))
+            (ocat (todos-current-category))
+            (opoint (point))
+            (todos-mm (eq major-mode 'todos-mode))
+            (cat+file (cond ((equal arg '(4))
+                             (todos-read-category "Insert in category: "))
+                            ((equal arg '(16))
+                             (todos-read-category "Insert in category: "
+                                                  nil 'file))
+                            (t
+                             (cons (todos-current-category)
+                                   (or todos-current-todos-file
+                                       (and todos-show-current-file
+                                            todos-global-current-todos-file)
+                                       (todos-absolute-file-name
+                                        todos-default-todos-file))))))
+            (cat (car cat+file))
+            (file (cdr cat+file))
+            (new-item (if region
+                          (buffer-substring-no-properties
+                           (region-beginning) (region-end))
+                        (read-from-minibuffer "Todo item: ")))
+            (date-string (cond
+                          ((eq date-type 'date)
+                           (todos-read-date))
+                          ((eq date-type 'dayname)
+                           (todos-read-dayname))
+                          ((eq date-type 'calendar)
+                           (setq todos-date-from-calendar t)
+                           (or (todos-set-date-from-calendar)
+                               ;; If user exits Calendar before choosing
+                               ;; a date, cancel item insertion.
+                               (keyboard-quit)))
+                          ((and (stringp date-type)
+                                (string-match todos-date-pattern date-type))
+                           (setq todos-date-from-calendar date-type)
+                           (todos-set-date-from-calendar))
+                          (t
+                           (calendar-date-string (calendar-current-date) t t))))
+            (time-string (or (and time (todos-read-time))
+                             (and todos-always-add-time-string
+                                  (substring (current-time-string) 11 16)))))
+       (setq todos-date-from-calendar nil)
+       (find-file-noselect file 'nowarn)
+       (set-window-buffer (selected-window)
+                          (set-buffer (find-buffer-visiting file)))
+       ;; If this command was invoked outside of a Todos buffer, the
+       ;; call to todos-current-category above returned nil.  If we
+       ;; just entered Todos mode now, then cat was set to the file's
+       ;; first category, but if todos-mode was already enabled, cat
+       ;; did not get set, so we have to set it explicitly.
+       (unless cat
+         (setq cat (todos-current-category)))
+       (setq todos-current-todos-file file)
+       (unless todos-global-current-todos-file
+         (setq todos-global-current-todos-file todos-current-todos-file))
+       (let ((buffer-read-only nil)
+             (called-from-outside (not (and todos-mm (equal cat ocat))))
+             done-only item-added)
+         (setq new-item
+               ;; Add date, time and diary marking as required.
+               (concat (if (not (and diary (not todos-include-in-diary)))
+                           todos-nondiary-start
+                         (when (and nonmarking (not todos-diary-nonmarking))
+                           diary-nonmarking-symbol))
+                       date-string (when (and time-string ; Can be empty string.
+                                              (not (zerop (length time-string))))
+                                     (concat " " time-string))
+                       (when (not (and diary (not todos-include-in-diary)))
+                         todos-nondiary-end)
+                       " " new-item))
+         ;; Indent newlines inserted by C-q C-j if nonspace char follows.
+         (setq new-item (replace-regexp-in-string
+                         "\\(\n\\)[^[:blank:]]"
+                         (concat "\n" (make-string todos-indent-to-here 32))
+                         new-item nil nil 1))
+         (unwind-protect
+             (progn
+               ;; Make sure the correct category is selected.  There
+               ;; are two cases: (i) we just visited the file, so no
+               ;; category is selected yet, or (ii) we invoked
+               ;; insertion "here" from outside the category we want
+               ;; to insert in (with priority insertion, category
+               ;; selection is done by todos-set-item-priority).
+               (when (or (= (- (point-max) (point-min)) (buffer-size))
+                         (and here called-from-outside))
+                 (todos-category-number cat)
+                 (todos-category-select))
+               ;; If only done items are displayed in category,
+               ;; toggle to todo items before inserting new item.
+               (when (save-excursion
+                       (goto-char (point-min))
+                       (looking-at todos-done-string-start))
+                 (setq done-only t)
+                 (todos-show-done-only))
+               (if here
+                   (progn
+                     ;; If command was invoked with point in done
+                     ;; items section or outside of the current
+                     ;; category, can't insert "here", so to be
+                     ;; useful give new item top priority.
+                     (when (or (todos-done-item-section-p)
+                               called-from-outside
+                               done-only)
+                       (goto-char (point-min)))
+                     (todos-insert-with-overlays new-item))
+                 (todos-set-item-priority new-item cat t))
+               (setq item-added t))
+           ;; If user cancels before setting priority, restore
+           ;; display.
+           (unless item-added
+             (if ocat
+                 (progn
+                   (unless (equal cat ocat)
+                     (todos-category-number ocat)
+                     (todos-category-select))
+                   (and done-only (todos-show-done-only)))
+               (set-window-buffer (selected-window) (set-buffer obuf)))
+             (goto-char opoint))
+           ;; If the todo items section is not visible when the
+           ;; insertion command is called (either because only done
+           ;; items were shown or because the category was not in the
+           ;; current buffer), then if the item is inserted at the
+           ;; end of the category, point is at eob and eob at
+           ;; window-start, so that higher priority todo items are
+           ;; out of view.  So we recenter to make sure the todo
+           ;; items are displayed in the window.
+           (when item-added (recenter)))
+         (todos-update-count 'todo 1)
+         (if (or diary todos-include-in-diary) (todos-update-count 'diary 1))
+         (todos-update-categories-sexp))))))
 
 (defun todos-copy-item ()
   "Copy item at point and insert the copy as a new item."
@@ -4263,16 +4775,28 @@ the priority is not given by HERE but by prompting."
         todos-date-from-calendar)
        (todos-date-from-calendar
         (let (calendar-view-diary-initially-flag)
-          (calendar))
-        ;; *Calendar* is now current buffer.
-        (local-set-key (kbd "RET") 'exit-recursive-edit)
+          (calendar))                  ; *Calendar* is now current buffer.
+        (define-key calendar-mode-map [remap newline] 'exit-recursive-edit)
+        ;; If user exits Calendar before choosing a date, clean up properly.
+        (define-key calendar-mode-map
+          [remap calendar-exit] (lambda ()
+                                   (interactive)
+                                   (progn
+                                     (calendar-exit)
+                                     (exit-recursive-edit))))
         (message "Put cursor on a date and type <return> to set it.")
-        ;; FIXME: is there a better way than recursive-edit?
         (recursive-edit)
-        (setq todos-date-from-calendar
-              (calendar-date-string (calendar-cursor-to-date t) t t))
-        (calendar-exit)
-        todos-date-from-calendar)))
+        (unwind-protect
+            (when (equal (buffer-name) calendar-buffer)
+              (setq todos-date-from-calendar
+                    (calendar-date-string (calendar-cursor-to-date t) t t))
+              (calendar-exit)
+              todos-date-from-calendar)
+          (define-key calendar-mode-map [remap newline] nil)
+          (define-key calendar-mode-map [remap calendar-exit] nil)
+          (unless (zerop (recursion-depth)) (exit-recursive-edit))
+          (when (stringp todos-date-from-calendar)
+            todos-date-from-calendar)))))
 
 (defun todos-delete-item ()
   "Delete at least one item in this category.
@@ -4285,7 +4809,6 @@ the item at point."
        (let* ((cat (todos-current-category))
               (marked (assoc cat todos-categories-with-marks))
               (item (unless marked (todos-item-string)))
-              ;; FIXME: make confirmation an option?
               (answer (if marked
                           (y-or-n-p "Permanently delete all marked items? ")
                         (when item
@@ -4294,7 +4817,6 @@ the item at point."
                                     (save-excursion (todos-item-end))))
                           (overlay-put ov 'face 'todos-search)
                           (y-or-n-p (concat "Permanently delete this item? ")))))
-              (opoint (point))
               buffer-read-only)
          (when answer
            (and marked (goto-char (point-min)))
@@ -4315,22 +4837,24 @@ the item at point."
                        (throw 'done (setq item nil))))
                  (todos-forward-item))))
            (when marked
-             (remove-overlays (point-min) (point-max)
-                              'before-string todos-item-mark)
              (setq todos-categories-with-marks
-                   (assq-delete-all cat todos-categories-with-marks))
-             (goto-char opoint))
+                   (assq-delete-all cat todos-categories-with-marks)))
            (todos-update-categories-sexp)
            (todos-prefix-overlays)))
       (if ov (delete-overlay ov)))))
 
-(defun todos-edit-item ()
+(defun todos-edit-item (&optional arg)
   "Edit the Todo item at point.
+
+With non-nil prefix argument ARG, include the item's date/time
+header, making it also editable; otherwise, include only the item
+content.
+
 If the item consists of only one logical line, edit it in the
 minibuffer; otherwise, edit it in Todos Edit mode."
-  (interactive)
+  (interactive "P")
   (when (todos-item-string)
-    (let* ((buffer-read-only)
+    (let* ((opoint (point))
           (start (todos-item-start))
           (item-beg (progn
                       (re-search-forward
@@ -4339,17 +4863,23 @@ minibuffer; otherwise, edit it in Todos Edit mode."
                                (regexp-quote todos-nondiary-end) "?")
                        (line-end-position) t)
                       (1+ (- (point) start))))
-          (item (todos-item-string))
+          (header (substring (todos-item-string) 0 item-beg))
+          (item (if arg (todos-item-string)
+                  (substring (todos-item-string) item-beg)))
           (multiline (> (length (split-string item "\n")) 1))
-          (opoint (point)))
+          (buffer-read-only nil))
       (if multiline
-         (todos-edit-multiline t)
-       (let ((new (read-string "Edit: " (cons item item-beg))))
-         (while (not (string-match
-                      (concat todos-date-string-start todos-date-pattern) new))
-           (setq new (read-from-minibuffer
-                      "Item must start with a date: " new)))
-         ;; Indent newlines inserted by C-q C-j if nonspace char follows.
+         (todos-edit-multiline-item)
+       (let ((new (concat (if arg "" header)
+                          (read-string "Edit: " (if arg
+                                                    (cons item item-beg)
+                                                  (cons item 0))))))
+         (when arg
+           (while (not (string-match (concat todos-date-string-start
+                                             todos-date-pattern) new))
+             (setq new (read-from-minibuffer
+                        "Item must start with a date: " new))))
+         ;; Ensure lines following hard newlines are indented.
          (setq new (replace-regexp-in-string
                     "\\(\n\\)[^[:blank:]]"
                     (concat "\n" (make-string todos-indent-to-here 32)) new
@@ -4365,128 +4895,308 @@ minibuffer; otherwise, edit it in Todos Edit mode."
 Use of newlines invokes `todos-indent' to insure compliance with
 the format of Diary entries."
   (interactive)
-  (todos-edit-multiline t))
-
-(defun todos-edit-multiline (&optional item)
-  ""
-  (interactive)
-  ;; FIXME: should there be only one live Todos Edit buffer?
-  ;; (let ((buffer-name todos-edit-buffer))
-  (let ((buffer-name (generate-new-buffer-name todos-edit-buffer)))
-    (set-window-buffer
-     (selected-window)
-     (set-buffer (make-indirect-buffer
-                 (file-name-nondirectory todos-current-todos-file)
-                 buffer-name)))
-    (if item
-       (narrow-to-region (todos-item-start) (todos-item-end))
-      (widen))
+  (let ((buf todos-edit-buffer))
+    (set-window-buffer (selected-window)
+                      (set-buffer (make-indirect-buffer (buffer-name) buf)))
+    (narrow-to-region (todos-item-start) (todos-item-end))
     (todos-edit-mode)
     (message "%s" (substitute-command-keys
-                  (concat "Type \\[todos-edit-quit] to check file format "
-                          "validity and return to Todos mode.\n")))))
+                  (concat "Type \\[todos-edit-quit] "
+                          "to return to Todos mode.\n")))))
+
+(defun todos-edit-multiline (&optional item) ;FIXME: not item editing command
+  ""                                   ;FIXME
+  (interactive)
+  (widen)
+  (todos-edit-mode)
+  (remove-overlays)
+  (message "%s" (substitute-command-keys
+                (concat "Type \\[todos-edit-quit] to check file format "
+                        "validity and return to Todos mode.\n"))))
 
 (defun todos-edit-quit ()
   "Return from Todos Edit mode to Todos mode.
+If the item contains hard line breaks, make sure the following
+lines are indented by `todos-indent-to-here' to conform to diary
+format.
 
 If the whole file was in Todos Edit mode, check before returning
 whether the file is still a valid Todos file and if so, also
 recalculate the Todos categories sexp, in case changes were made
 in the number or names of categories."
   (interactive)
-  ;; FIXME: Should do todos-check-format only if file was actually changed --
-  ;; but how to tell?
-  (when (eq (buffer-size) (- (point-max) (point-min)))
-    (when (todos-check-format) (todos-repair-categories-sexp)))
-  (kill-buffer)
-  ;; In case next buffer is not the one holding todos-current-todos-file.
-  (todos-show))
-
-(defun todos-edit-item-header (&optional what)
-  "Edit date/time header of at least one item.
-
-Interactively, ask whether to edit year, month and day or day of
-the week, as well as time.  If there are marked items, apply the
-changes to all of these; otherwise, edit just the item at point.  
-
-Non-interactively, argument WHAT specifies whether to set the
-date from the Calendar or to today, or whether to edit only the
-date or day, or only the time."
-  (interactive)
+  (if (> (buffer-size) (- (point-max) (point-min)))
+      (let ((item (buffer-string))
+           (regex "\\(\n\\)[^[:blank:]]"))
+       ;; Ensure lines following hard newlines are indented.
+       (when (string-match regex (buffer-string))
+         (replace-regexp-in-string
+          regex (concat "\n" (make-string todos-indent-to-here 32))
+          nil nil 1)
+         (delete-region (point-min) (point-max))
+         (insert item))
+       (kill-buffer))
+      (when (todos-check-format)
+       ;; FIXME: separate out sexp check?
+       ;; If manual editing makes e.g. item counts change, have to
+       ;; call this to update todos-categories, but it restores
+       ;; category order to list order.
+       ;; (todos-repair-categories-sexp)
+       ;; Compare (todos-make-categories-list t) with sexp and if
+       ;; different ask (todos-update-categories-sexp) ?
+       (todos-mode)
+       (let* ((cat-beg (concat "^" (regexp-quote todos-category-beg)
+                               "\\(.*\\)$"))
+              (curline (buffer-substring-no-properties
+                        (line-beginning-position) (line-end-position)))
+              (cat (cond ((string-match cat-beg curline)
+                          (match-string-no-properties 1 curline))
+                         ((or (re-search-backward cat-beg nil t)
+                              (re-search-forward cat-beg nil t))
+                          (match-string-no-properties 1)))))
+         (todos-category-number cat)
+         (todos-category-select)
+         (goto-char (point-min))))))
+
+(defun todos-edit-item-header-1 (what &optional inc)
+  "Function underlying commands to edit item date/time header.
+
+The argument WHAT (passed by invoking commands) specifies what
+part of the header to edit; possible values are these symbols:
+`date', to edit the year, month, and day of the date string;
+`time', to edit just the time string; `calendar', to select the
+date from the Calendar; `today', to set the date to today's date;
+`dayname', to set the date string to the name of a day or to
+change the day name; and `year', `month' or `day', to edit only
+these respective parts of the date string (`day' is the number of
+the given day of the month, and `month' is either the name of the
+given month or its number, depending on the value of
+`calendar-date-display-form').
+
+The optional argument INC is a positive or negative integer
+\(passed by invoking commands as a numerical prefix argument)
+that in conjunction with the WHAT values `year', `month' or
+`day', increments or decrements the specified date string
+component by the specified number of suitable units, i.e., years,
+months, or days, with automatic adjustment of the other date
+string components as necessary.
+
+If there are marked items, apply the same edit to all of these;
+otherwise, edit just the item at point."
   (let* ((cat (todos-current-category))
         (marked (assoc cat todos-categories-with-marks))
-        (first t)                      ; Match only first of marked items.
+        (first t)
         (todos-date-from-calendar t)
-        ndate ntime nheader)
+        (buffer-read-only nil)
+        ndate ntime year monthname month day
+        dayname)       ; Needed by calendar-date-display-form.
     (save-excursion
       (or (and marked (goto-char (point-min))) (todos-item-start))
-      (catch 'stop
+      (catch 'end
        (while (not (eobp))
          (and marked
               (while (not (todos-marked-item-p))
                 (todos-forward-item)
-                (and (eobp) (throw 'stop nil))))
+                (and (eobp) (throw 'end nil))))
          (re-search-forward (concat todos-date-string-start "\\(?1:"
                                     todos-date-pattern
-                                    "\\)\\(?2: " diary-time-regexp "\\)?")
+                                    "\\)\\(?2: " diary-time-regexp "\\)?"
+                                    (regexp-quote todos-nondiary-end) "?")
                             (line-end-position) t)
          (let* ((odate (match-string-no-properties 1))
                 (otime (match-string-no-properties 2))
-                (buffer-read-only))
-           (cond ((eq what 'today)
-                  (progn
-                    (setq ndate (calendar-date-string
-                                 (calendar-current-date) t t))
-                    (replace-match ndate nil nil nil 1)))
-                 ((eq what 'calendar)
-                  (setq ndate (save-match-data (todos-set-date-from-calendar)))
-                  (replace-match ndate nil nil nil 1))
-                 (t
-                  (unless (eq what 'timeonly)
-                    (when first
-                      (setq ndate (if (save-match-data
-                                        (string-match "[0-9]+" odate))
-                                      (if (y-or-n-p "Change date? ")
-                                          (todos-read-date)
-                                        (todos-read-dayname))
-                                    (if (y-or-n-p "Change day? ")
-                                        (todos-read-dayname)
-                                      (todos-read-date)))))
-                    (replace-match ndate nil nil nil 1))
-                  (unless (eq what 'dateonly)
-                    (when first
-                      (setq ntime (save-match-data (todos-read-time)))
-                      (when (< 0 (length ntime))
-                        (setq ntime (concat " " ntime))))
-                    (if otime
-                        (replace-match ntime nil nil nil 2)
-                      (goto-char (match-end 1))
-                      (insert ntime)))))
+                (omonthname (match-string-no-properties 6))
+                (omonth (match-string-no-properties 7))
+                (oday (match-string-no-properties 8))
+                (oyear (match-string-no-properties 9))
+                (tmn-array todos-month-name-array)
+                (mlist (append tmn-array nil))
+                (tma-array todos-month-abbrev-array)
+                (mablist (append tma-array nil))
+                (yy (and oyear (unless (string= oyear "*")
+                                 (string-to-number oyear))))
+                (mm (or (and omonth (unless (string= omonth "*")
+                                      (string-to-number omonth)))
+                        (1+ (- (length mlist)
+                               (length (or (member omonthname mlist)
+                                           (member omonthname mablist)))))))
+                (dd (and oday (unless (string= oday "*")
+                                (string-to-number oday)))))
+           ;; If there are marked items, use only the first to set
+           ;; header changes, and apply these to all marked items.
+           (when first
+             (cond
+              ((eq what 'date)
+               (setq ndate (todos-read-date)))
+              ((eq what 'calendar)
+               (setq ndate (save-match-data (todos-set-date-from-calendar))))
+              ((eq what 'today)
+               (setq ndate (calendar-date-string (calendar-current-date) t t)))
+              ((eq what 'dayname)
+               (setq ndate (todos-read-dayname)))
+              ((eq what 'time)
+               (setq ntime (save-match-data (todos-read-time)))
+               (when (> (length ntime) 0)
+                 (setq ntime (concat " " ntime))))
+              ;; When date string consists only of a day name,
+              ;; passing other date components is a NOP.
+              ((and (memq what '(year month day))
+                    (not (or oyear omonth oday))))
+              ((eq what 'year)
+               (setq day oday
+                     monthname omonthname
+                     month omonth
+                     year (cond ((not current-prefix-arg)
+                                 (todos-read-date 'year))
+                                ((string= oyear "*")
+                                 (error "Cannot increment *"))
+                                (t
+                                 (number-to-string (+ yy inc))))))
+              ((eq what 'month)
+               (setf day oday
+                     year oyear
+                     (if (memq 'month calendar-date-display-form)
+                         month
+                       monthname)
+                     (cond ((not current-prefix-arg)
+                            (todos-read-date 'month))
+                           ((or (string= omonth "*") (= mm 13))
+                            (error "Cannot increment *"))
+                           (t
+                            (let ((mminc (+ mm inc))) 
+                              ;; Increment or decrement month by INC
+                              ;; modulo 12.
+                              (setq mm (% mminc 12))
+                              ;; If result is 0, make month December.
+                              (setq mm (if (= mm 0) 12 (abs mm)))
+                              ;; Adjust year if necessary.
+                              (setq year (or (and (cond ((> mminc 12)
+                                                         (+ yy (/ mminc 12)))
+                                                        ((< mminc 1)
+                                                         (- yy (/ mminc 12) 1))
+                                                        (t yy))
+                                                  (number-to-string yy))
+                                             oyear)))
+                            ;; Return the changed numerical month as
+                            ;; a string or the corresponding month name.
+                            (if omonth
+                                (number-to-string mm)
+                              (aref tma-array (1- mm))))))
+               (let ((yy (string-to-number year)) ; 0 if year is "*".
+                     ;; When mm is 13 (corresponding to "*" as value
+                     ;; of month), this raises an args-out-of-range
+                     ;; error in calendar-last-day-of-month, so use 1
+                     ;; (corresponding to January) to get 31 days.
+                     (mm (if (= mm 13) 1 mm)))
+                 (if (> (string-to-number day)
+                        (calendar-last-day-of-month mm yy))
+                     (error "%s %s does not have %s days"
+                            (aref tmn-array (1- mm))
+                            (if (= mm 2) yy "") day))))
+              ((eq what 'day)
+               (setq year oyear
+                     month omonth
+                     monthname omonthname
+                     day (cond
+                          ((not current-prefix-arg)
+                           (todos-read-date 'day mm oyear))
+                          ((string= oday "*")
+                           (error "Cannot increment *"))
+                          ((or (string= omonth "*") (string= omonthname "*"))
+                           (setq dd (+ dd inc))
+                           (if (> dd 31)
+                               (error "A month cannot have more than 31 days")
+                             (number-to-string dd)))
+                          ;; Increment or decrement day by INC,
+                          ;; adjusting month and year if necessary
+                          ;; (if year is "*" assume current year to
+                          ;; calculate adjustment).
+                          (t
+                           (let* ((yy (or yy (calendar-extract-year
+                                              (calendar-current-date))))
+                                  (date (calendar-gregorian-from-absolute
+                                         (+ (calendar-absolute-from-gregorian
+                                             (list mm dd yy)) inc)))
+                                  (adjmm (nth 0 date)))
+                             ;; Set year and month(name) to adjusted values.
+                             (unless (string= year "*")
+                               (setq year (number-to-string (nth 2 date))))
+                             (if month
+                                 (setq month (number-to-string adjmm))
+                               (setq monthname (aref tma-array (1- adjmm))))
+                             ;; Return changed numerical day as a string.
+                             (number-to-string (nth 1 date)))))))))
+           ;; If new year, month or day date string components were
+           ;; calculated, rebuild the whole date string from them.
+           (when (memq what '(year month day))
+             (if (or oyear omonth omonthname oday)
+                 (setq ndate (mapconcat 'eval calendar-date-display-form ""))
+               (message "Cannot edit date component of empty date string")))
+           (when ndate (replace-match ndate nil nil nil 1))
+           ;; Add new time string to the header, if it was supplied.
+           (when ntime
+             (if otime
+                 (replace-match ntime nil nil nil 2)
+               (goto-char (match-end 1))
+               (insert ntime)))
            (setq todos-date-from-calendar nil)
            (setq first nil))
+         ;; Apply the changes to the first marked item header to the
+         ;; remaining marked items.  If there are no marked items,
+         ;; we're finished.
          (if marked
              (todos-forward-item)
            (goto-char (point-max))))))))
 
-(defun todos-edit-item-date ()
-  "Prompt for and apply changes to current item's date."
+(defun todos-edit-item-header ()
+  "Interactively edit at least the date of item's date/time header.
+If user option `todos-always-add-time-string' is non-nil, also
+edit item's time string."
+  (interactive)
+  (todos-edit-item-header-1 'date)
+  (when todos-always-add-time-string
+    (todos-edit-item-time)))
+
+(defun todos-edit-item-time ()
+  "Interactively edit the time string of item's date/time header."
   (interactive)
-  (todos-edit-item-header 'dateonly))
+  (todos-edit-item-header-1 'time))
 
 (defun todos-edit-item-date-from-calendar ()
-  "Prompt for changes to current item's date and apply from Calendar."
+  "Interactively edit item's date using the Calendar."
   (interactive)
-  (todos-edit-item-header 'calendar))
+  (todos-edit-item-header-1 'calendar))
 
-(defun todos-edit-item-date-is-today ()
-  "Set item date to today's date."
+(defun todos-edit-item-date-to-today ()
+  "Set item's date to today's date."
   (interactive)
-  (todos-edit-item-header 'today))
-(defun todos-edit-item-time ()
-  "Prompt For and apply changes to current item's time."
+  (todos-edit-item-header-1 'today))
+
+(defun todos-edit-item-date-day-name ()
+  "Replace item's date with the name of a day of the week."
   (interactive)
-  (todos-edit-item-header 'timeonly))
+  (todos-edit-item-header-1 'dayname))
+
+(defun todos-edit-item-date-year (&optional inc)
+  "Interactively edit the year of item's date string.
+With prefix argument INC a positive or negative integer,
+increment or decrement the year by INC."
+  (interactive "p")
+  (todos-edit-item-header-1 'year inc))
+
+(defun todos-edit-item-date-month (&optional inc)
+  "Interactively edit the month of item's date string.
+With prefix argument INC a positive or negative integer,
+increment or decrement the month by INC."
+  (interactive "p")
+  (todos-edit-item-header-1 'month inc))
+
+(defun todos-edit-item-date-day (&optional inc)
+  "Interactively edit the day of the month of item's date string.
+With prefix argument INC a positive or negative integer,
+increment or decrement the day by INC."
+  (interactive "p")
+  (todos-edit-item-header-1 'day inc))
 
 (defun todos-edit-item-diary-inclusion ()
   "Change diary status of one or more todo items in this category.
@@ -4610,105 +5320,129 @@ items in this category."
        (todos-forward-item)))))))
 
 (defun todos-set-item-priority (&optional item cat new arg)
-  "Set todo ITEM's priority in CATegory and move item accordingly.
+  "Prompt for and set ITEM's priority in CATegory.
 
-Interactively, ITEM defaults to the item at point, CAT to the
-current category in Todos mode, and the priority is a number
-between 1 and the number of items in the category.
-Non-interactively, non-nil NEW means ITEM is a new item and the
-lowest priority is one more than the number of items in CAT.
+Interactively, ITEM is the todo item at point, CAT is the current
+category, and the priority is a number between 1 and the number
+of items in the category.  Non-interactively, non-nil NEW means
+ITEM is a new item and the lowest priority is one more than the
+number of items in CAT.
 
 The new priority is set either interactively by prompt or by a
 numerical prefix argument, or noninteractively by argument ARG,
 whose value can be either of the symbols `raise' or `lower',
 meaning to raise or lower the item's priority by one."
-  (interactive)
-  (let* ((item (or item (todos-item-string)))
-        (marked (todos-marked-item-p))
-        (cat (or cat (cond ((eq major-mode 'todos-mode)
-                            (todos-current-category))
-                           ((eq major-mode 'todos-filtered-items-mode)
-                            (let* ((regexp1
-                                    (concat todos-date-string-start
-                                            todos-date-pattern
-                                            "\\( " diary-time-regexp "\\)?"
-                                            (regexp-quote todos-nondiary-end)
-                                            "?\\(?1: \\[\\(.+:\\)?.+\\]\\)")))
-                              (save-excursion
-                                (re-search-forward regexp1 nil t)
-                                (match-string-no-properties 1)))))))
-        curnum
-        (todo (cond ((or (eq arg 'raise) (eq arg 'lower)
-                         (eq major-mode 'todos-filtered-items-mode))
-                     (save-excursion
-                       (let ((curstart (todos-item-start))
-                             (count 0))
-                         (goto-char (point-min))
-                         (while (looking-at todos-item-start)
-                           (setq count (1+ count))
-                           (when (= (point) curstart) (setq curnum count))
-                           (todos-forward-item))
-                         count)))
-                    ((eq major-mode 'todos-mode)
-                     (todos-get-count 'todo cat))))
-        (maxnum (if new (1+ todo) todo))
-        (prompt (format "Set item priority (1-%d): " maxnum))
-        (priority (cond ((numberp current-prefix-arg)
-                         current-prefix-arg)
-                        ((and (eq arg 'raise) (>= curnum 1))
-                         (1- curnum))
-                        ((and (eq arg 'lower) (<= curnum maxnum))
-                         (1+ curnum))))
-        candidate
-        buffer-read-only)
-    (unless (and priority
-                (or (and (eq arg 'raise) (zerop priority))
-                    (and (eq arg 'lower) (> priority maxnum))))
-      ;; When moving item to another category, show the category before
-      ;; prompting for its priority.
-      (unless (or arg (called-interactively-p t))
-       (todos-category-number cat)
-       (todos-category-select))
-      (while (not priority)
-       (setq candidate (read-number prompt))
-       (setq prompt (when (or (< candidate 1) (> candidate maxnum))
-                      (format "Priority must be an integer between 1 and %d.\n"
-                              maxnum)))
-       (unless prompt (setq priority candidate)))
-      ;; In Top Priorities buffer, an item's priority can be changed
-      ;; wrt items in another category, but not wrt items in the same
-      ;; category.
-      (when (eq major-mode 'todos-filtered-items-mode)
-       (let* ((regexp2 (concat todos-date-string-start todos-date-pattern
-                               "\\( " diary-time-regexp "\\)?"
-                               (regexp-quote todos-nondiary-end)
-                               "?\\(?1:" (regexp-quote cat) "\\)"))
-              (end (cond ((< curnum priority)
-                          (save-excursion (todos-item-end)))
-                         ((> curnum priority)
-                          (save-excursion (todos-item-start)))))
-              (match (save-excursion
-                       (cond ((< curnum priority)
-                              (todos-forward-item (1+ (- priority curnum)))
-                              (when (re-search-backward regexp2 end t)
-                                (match-string-no-properties 1)))
-                             ((> curnum priority)
-                              (todos-backward-item (- curnum priority))
-                              (when (re-search-forward regexp2 end t)
-                                (match-string-no-properties 1)))))))
-         (when match
-           (error (concat "Cannot reprioritize items from the same "
-                          "category in this mode, only in Todos mode")))))
-      ;; Interactively or with non-nil ARG, relocate the item within its
-      ;; category.
-      (when (or arg (called-interactively-p))
-       (todos-remove-item))
-      (goto-char (point-min))
-      (unless (= priority 1) (todos-forward-item (1- priority)))
-      (todos-insert-with-overlays item)
-      ;; If item was marked, restore the mark.
-      (and marked (overlay-put (make-overlay (point) (point))
-                              'before-string todos-item-mark)))))
+  (interactive)                                ;FIXME: Prefix arg?
+  (unless (and (called-interactively-p 'any)
+              (or (todos-done-item-p) (looking-at "^$")))
+    (let* ((item (or item (todos-item-string)))
+          (marked (todos-marked-item-p))
+          (cat (or cat (cond ((eq major-mode 'todos-mode)
+                              (todos-current-category))
+                             ((eq major-mode 'todos-filtered-items-mode)
+                              (let* ((regexp1
+                                      (concat todos-date-string-start
+                                              todos-date-pattern
+                                              "\\( " diary-time-regexp "\\)?"
+                                              (regexp-quote todos-nondiary-end)
+                                              "?\\(?1: \\[\\(.+:\\)?.+\\]\\)")))
+                                (save-excursion
+                                  (re-search-forward regexp1 nil t)
+                                  (match-string-no-properties 1)))))))
+          curnum
+          (todo (cond ((or (eq arg 'raise) (eq arg 'lower)
+                           (eq major-mode 'todos-filtered-items-mode))
+                       (save-excursion
+                         (let ((curstart (todos-item-start))
+                               (count 0))
+                           (goto-char (point-min))
+                           (while (looking-at todos-item-start)
+                             (setq count (1+ count))
+                             (when (= (point) curstart) (setq curnum count))
+                             (todos-forward-item))
+                           count)))
+                      ((eq major-mode 'todos-mode)
+                       (todos-get-count 'todo cat))))
+          (maxnum (if new (1+ todo) todo))
+          (prompt (format "Set item priority (1-%d): " maxnum))
+          (priority (cond ((and (not arg) (numberp current-prefix-arg))
+                           current-prefix-arg)
+                          ((and (eq arg 'raise) (>= curnum 1))
+                           (1- curnum))
+                          ((and (eq arg 'lower) (<= curnum maxnum))
+                           (1+ curnum))))
+          candidate
+          buffer-read-only)
+      (unless (and priority
+                  (or (and (eq arg 'raise) (zerop priority))
+                      (and (eq arg 'lower) (> priority maxnum))))
+       ;; When moving item to another category, show the category before
+       ;; prompting for its priority.
+       (unless (or arg (called-interactively-p 'any))
+         (todos-category-number cat)
+         ;; If done items in category are visible, keep them visible.
+         (let ((done todos-show-with-done))
+           (when (> (buffer-size) (- (point-max) (point-min)))
+             (save-excursion
+               (goto-char (point-min))
+               (setq done (re-search-forward todos-done-string-start nil t))))
+           (let ((todos-show-with-done done))
+             (todos-category-select)
+             ;; Keep top of category in view while setting priority.
+             (goto-char (point-min)))))
+       ;; Prompt for priority only when the category has at least one todo item.
+       (when (> maxnum 1)
+         (while (not priority)
+           (setq candidate (read-number prompt))
+           (setq prompt (when (or (< candidate 1) (> candidate maxnum))
+                          (format "Priority must be an integer between 1 and %d.\n"
+                                  maxnum)))
+           (unless prompt (setq priority candidate))))
+       ;; In Top Priorities buffer, an item's priority can be changed
+       ;; wrt items in another category, but not wrt items in the same
+       ;; category.
+       (when (eq major-mode 'todos-filtered-items-mode)
+         (let* ((regexp2 (concat todos-date-string-start todos-date-pattern
+                                 "\\( " diary-time-regexp "\\)?"
+                                 (regexp-quote todos-nondiary-end)
+                                 "?\\(?1:" (regexp-quote cat) "\\)"))
+                (end (cond ((< curnum priority)
+                            (save-excursion (todos-item-end)))
+                           ((> curnum priority)
+                            (save-excursion (todos-item-start)))))
+                (match (save-excursion
+                         (cond ((< curnum priority)
+                                (todos-forward-item (1+ (- priority curnum)))
+                                (when (re-search-backward regexp2 end t)
+                                  (match-string-no-properties 1)))
+                               ((> curnum priority)
+                                (todos-backward-item (- curnum priority))
+                                (when (re-search-forward regexp2 end t)
+                                  (match-string-no-properties 1)))))))
+           (when match
+             (error (concat "Cannot reprioritize items from the same "
+                            "category in this mode, only in Todos mode")))))
+       ;; Interactively or with non-nil ARG, relocate the item within its
+       ;; category.
+       (when (or arg (called-interactively-p 'any))
+         (todos-remove-item))
+       (goto-char (point-min))
+       (when priority
+         (unless (= priority 1)
+           (todos-forward-item (1- priority))
+           ;; When called from todos-item-undo and the highest priority
+           ;; is chosen, this advances point to the first done item, so
+           ;; move it up to the empty line above the done items
+           ;; separator.
+           (when (looking-back (concat "^"
+                                       (regexp-quote todos-category-done) "\n"))
+             (todos-backward-item))))
+       (todos-insert-with-overlays item)
+       ;; If item was marked, restore the mark.
+       (and marked
+            (let* ((ov (todos-get-overlay 'prefix))
+                   (pref (overlay-get ov 'before-string)))
+              (overlay-put ov 'before-string (concat todos-item-mark pref))))))))
 
 (defun todos-raise-item-priority ()
   "Raise priority of current item by moving it up by one item."
@@ -4721,134 +5455,164 @@ meaning to raise or lower the item's priority by one."
   (todos-set-item-priority nil nil nil 'lower))
 
 (defun todos-move-item (&optional file)
-  "Move at least one todo item to another category.
-
+  "Move at least one todo or done item to another category.
 If there are marked items, move all of these; otherwise, move
 the item at point.
 
-With non-nil argument FILE, first prompt for another Todos file and
-then a category in that file to move the item or items to.
-
-If the chosen category is not one of the existing categories,
-then it is created and the item(s) become(s) the first
-entry/entries in that category."
-  (interactive)
-  (unless (or (todos-done-item-p)
-             ;; Point is between todo and done items.
-             (looking-at "^$"))
-    (let* ((buffer-read-only)
-          (file1 todos-current-todos-file)
-          (cat1 (todos-current-category))
-          (marked (assoc cat1 todos-categories-with-marks))
-          (num todos-category-number)
-          (item (todos-item-string))
-          (diary-item (todos-diary-item-p))
-          (omark (save-excursion (todos-item-start) (point-marker)))
-          (file2 (if file
-                     (todos-read-file-name "Choose a Todos file: " nil t)
-                   file1))
-          (count 0)
-          (count-diary 0)
-          ov cat2 nmark)
-      (set-buffer (find-file-noselect file2))
-      (unwind-protect
-         (progn
-           (unless marked
-             (setq ov (make-overlay (save-excursion (todos-item-start))
-                                    (save-excursion (todos-item-end))))
-             (overlay-put ov 'face 'todos-search))
-           (setq cat2 (let* ((pl (if (and marked (> (cdr marked) 1)) "s" ""))
-                             (name (todos-read-category
-                                    (concat "Move item" pl " to category: ")))
-                             (prompt (concat "Choose a different category than "
-                                             "the current one\n(type `"
-                                             (key-description
-                                              (car (where-is-internal
-                                                    'todos-set-item-priority)))
-                                             "' to reprioritize item "
-                                             "within the same category): ")))
-                        (while (equal name cat1)
-                          (setq name (todos-read-category prompt)))
-                        name)))
-       (if ov (delete-overlay ov)))
-      (set-buffer (find-buffer-visiting file1))
-      (if marked
-         (progn
-           (setq item nil)
-           (goto-char (point-min))
-           (while (not (eobp))
-             (when (todos-marked-item-p)
-               (setq item (concat item (todos-item-string) "\n"))
-               (setq count (1+ count))
-               (when (todos-diary-item-p)
-                 (setq count-diary (1+ count-diary))))
-             (todos-forward-item))
-           ;; Chop off last newline.
-           (setq item (substring item 0 -1)))
-       (setq count 1)
-       (when (todos-diary-item-p) (setq count-diary 1)))
-      (set-window-buffer (selected-window)
-                        (set-buffer (find-file-noselect file2)))
-      (unless (assoc cat2 todos-categories) (todos-add-category cat2))
-      (todos-set-item-priority item cat2 t)
-      (setq nmark (point-marker))
-      (todos-update-count 'todo count)
-      (todos-update-count 'diary count-diary)
-      (todos-update-categories-sexp)
-      (with-current-buffer (find-buffer-visiting file1)
-       (save-excursion
-         (save-restriction
-           (widen)
-           (goto-char omark)
-           (if marked
-               (let (beg end)
-                 (setq item nil)
-                 (re-search-backward
-                  (concat "^" (regexp-quote todos-category-beg)) nil t)
-                 (forward-line)
-                 (setq beg (point))
-                 (re-search-forward
-                  (concat "^" (regexp-quote todos-category-done)) nil t)
-                 (setq end (match-beginning 0))
-                 (goto-char beg)
-                 (while (< (point) end)
-                   (if (todos-marked-item-p)
-                       (todos-remove-item)
-                     (todos-forward-item)))
-                 ;; FIXME: does this work?
-                 (remove-overlays (point-min) (point-max)
-                                  'before-string todos-item-mark)
-                 (setq todos-categories-with-marks
-                       (assq-delete-all cat todos-categories-with-marks)))
-             (if ov (delete-overlay ov))
-             (todos-remove-item))))
-       (todos-update-count 'todo (- count) cat1)
-       (todos-update-count 'diary (- count-diary) cat1)
-       (todos-update-categories-sexp))
-      (set-window-buffer (selected-window)
-                        (set-buffer (find-file-noselect file2)))
-      (setq todos-category-number (todos-category-number cat2))
-      (todos-category-select)
-      (goto-char nmark))))
+With prefix argument FILE, prompt for a specific Todos file and
+choose (with TAB completion) a category in it to move the item or
+items to; otherwise, choose and move to any category in either
+the current Todos file or one of the files in
+`todos-category-completions-files'.  If the chosen category is
+not an existing categories, then it is created and the item(s)
+become(s) the first entry/entries in that category.
+
+With moved Todo items, prompt to set the priority in the category
+moved to (with multiple todos items, the one that had the highest
+priority in the category moved from gets the new priority and the
+rest of the moved todo items are inserted in sequence below it).
+Moved done items are appended to the top of the done items
+section in the category moved to."
+  (interactive "P")
+  (let* ((cat1 (todos-current-category))
+        (marked (assoc cat1 todos-categories-with-marks)))
+    ;; Noop if point is not on an item and there are no marked items.
+    (unless (and (looking-at "^$")
+                (not marked))
+      (let* ((buffer-read-only)
+            (file1 todos-current-todos-file)
+            (num todos-category-number)
+            (item (todos-item-string))
+            (diary-item (todos-diary-item-p))
+            (done-item (and (todos-done-item-p) (concat item "\n")))
+            (omark (save-excursion (todos-item-start) (point-marker)))
+            (todo 0)
+            (diary 0)
+            (done 0)
+            ov cat2 file2 moved nmark todo-items done-items)
+       (unwind-protect
+           (progn
+             (unless marked
+               (setq ov (make-overlay (save-excursion (todos-item-start))
+                                      (save-excursion (todos-item-end))))
+               (overlay-put ov 'face 'todos-search))
+             (let* ((pl (if (and marked (> (cdr marked) 1)) "s" ""))
+                    (cat+file (todos-read-category (concat "Move item" pl
+                                                           " to category: ")
+                                                   nil file)))
+               (while (and (equal (car cat+file) cat1)
+                           (equal (cdr cat+file) file1))
+                 (setq cat+file (todos-read-category
+                                 "Choose a different category: ")))
+               (setq cat2 (car cat+file)
+                     file2 (cdr cat+file))))
+         (if ov (delete-overlay ov)))
+       (set-buffer (find-buffer-visiting file1))
+       (if marked
+           (progn
+             (goto-char (point-min))
+             (while (not (eobp))
+               (when (todos-marked-item-p)
+                 (if (todos-done-item-p)
+                     (setq done-items (concat done-items
+                                              (todos-item-string) "\n")
+                           done (1+ done))
+                   (setq todo-items (concat todo-items
+                                            (todos-item-string) "\n")
+                         todo (1+ todo))
+                   (when (todos-diary-item-p)
+                     (setq diary (1+ diary)))))
+               (todos-forward-item))
+             ;; Chop off last newline of multiple todo item string,
+             ;; since it will be reinserted when setting priority
+             ;; (but with done items priority is not set, so keep
+             ;; last newline).
+             (and todo-items
+                  (setq todo-items (substring todo-items 0 -1))))
+         (if (todos-done-item-p)
+             (setq done 1)
+           (setq todo 1)
+           (when (todos-diary-item-p) (setq diary 1))))
+       (set-window-buffer (selected-window)
+                          (set-buffer (find-file-noselect file2 'nowarn)))
+       (unwind-protect
+           (progn
+             (when (or todo-items (and item (not done-item)))
+               (todos-set-item-priority (or todo-items item) cat2 t))
+             ;; Move done items en bloc to top of done items section.
+             (when (or done-items done-item)
+               (todos-category-number cat2)
+               (widen)
+               (goto-char (point-min))
+               (re-search-forward (concat "^" (regexp-quote
+                                               (concat todos-category-beg cat2))
+                                          "$")
+                                  nil t)
+               (re-search-forward
+                (concat "^" (regexp-quote todos-category-done)) nil t)
+               (forward-line)
+               (insert (or done-items done-item)))
+             (setq moved t))
+         (cond
+          ;; Move succeeded, so remove item from starting category,
+          ;; update item counts and display the category containing
+          ;; the moved item.
+          (moved
+           (setq nmark (point-marker))
+           (when todo (todos-update-count 'todo todo))
+           (when diary (todos-update-count 'diary diary))
+           (when done (todos-update-count 'done done))
+           (todos-update-categories-sexp)
+           (with-current-buffer (find-buffer-visiting file1)
+             (save-excursion
+               (save-restriction
+                 (widen)
+                 (goto-char omark)
+                 (if marked
+                     (let (beg end)
+                       (setq item nil)
+                       (re-search-backward
+                        (concat "^" (regexp-quote todos-category-beg)) nil t)
+                       (forward-line)
+                       (setq beg (point))
+                       (setq end (if (re-search-forward
+                                      (concat "^" (regexp-quote
+                                                   todos-category-beg)) nil t)
+                                     (match-beginning 0)
+                                   (point-max)))
+                       (goto-char beg)
+                       (while (< (point) end)
+                         (if (todos-marked-item-p)
+                             (todos-remove-item)
+                           (todos-forward-item)))
+                       (setq todos-categories-with-marks
+                             (assq-delete-all cat1 todos-categories-with-marks)))
+                   (if ov (delete-overlay ov))
+                   (todos-remove-item))))
+             (when todo (todos-update-count 'todo (- todo) cat1))
+             (when diary (todos-update-count 'diary (- diary) cat1))
+             (when done (todos-update-count 'done (- done) cat1))
+             (todos-update-categories-sexp))
+           (set-window-buffer (selected-window)
+                              (set-buffer (find-file-noselect file2 'nowarn)))
+           (setq todos-category-number (todos-category-number cat2))
+           (let ((todos-show-with-done (or done-items done-item)))
+             (todos-category-select))
+           (goto-char nmark)
+           ;; If item is moved to end of (just first?) category, make
+           ;; sure the items above it are displayed in the window.
+           (recenter))
+          ;; User quit before setting priority of todo item(s), so
+          ;; return to starting category.
+          (t
+           (set-window-buffer (selected-window)
+                              (set-buffer (find-file-noselect file1 'nowarn)))
+           (todos-category-number cat1)
+           (todos-category-select)
+           (goto-char omark))))))))
 
-(defun todos-move-item-to-file ()
-  "Move the current todo item to a category in another Todos file."
-  (interactive)
-  (todos-move-item t))
-
-;; (defun todos-move-item-to-diary ()
-;;   "Move one or more items in current category to the diary file.
-;;
-;; If there are marked items, move all of these; otherwise, move
-;; the item at point."
-;;   (interactive)
-;;   ;; FIXME
-;;   )
-
-;; FIXME: make adding date customizable, and make this and time customization
-;; overridable via double prefix arg ??
 (defun todos-item-done (&optional arg)
-  "Tag at least one item in this category as done and hide it.
+  "Tag a todo item in this category as done and relocate it.
 
 With prefix argument ARG prompt for a comment and append it to
 the done item; this is only possible if there are no marked
@@ -4856,11 +5620,14 @@ items.  If there are marked items, tag all of these with
 `todos-done-string' plus the current date and, if
 `todos-always-add-time-string' is non-nil, the current time;
 otherwise, just tag the item at point.  Items tagged as done are
-relocated to the category's (by default hidden) done section."
+relocated to the category's (by default hidden) done section.  If
+done items are visible on invoking this command, they remain
+visible."
   (interactive "P")
   (let* ((cat (todos-current-category))
         (marked (assoc cat todos-categories-with-marks)))
     (unless (or (todos-done-item-p) 
+               ;; Point is between todo and done items.
                (and (looking-at "^$") (not marked)))
       (let* ((date-string (calendar-date-string (calendar-current-date) t t))
             (time-string (if todos-always-add-time-string
@@ -4868,25 +5635,27 @@ relocated to the category's (by default hidden) done section."
                            ""))
             (done-prefix (concat "[" todos-done-string date-string time-string
                                  "] "))
-            (comment (and arg (not marked) (read-string "Enter a comment: ")))
+            (comment (and arg (read-string "Enter a comment: ")))
             (item-count 0)
             (diary-count 0)
-            item done-item
-            (buffer-read-only))
+            (show-done (save-excursion
+                         (goto-char (point-min))
+                         (re-search-forward todos-done-string-start nil t)))
+            (buffer-read-only nil)
+            item done-item opoint)
+       ;; Don't add empty comment to done item.
+       (setq comment (unless (zerop (length comment))
+                       (concat " [" todos-comment-string ": " comment "]")))
        (and marked (goto-char (point-min)))
        (catch 'done
-         (while (not (eobp))
+         ;; Stop looping when we hit the empty line below the last
+         ;; todo item (this is eobp if only done items are hidden).
+         (while (not (looking-at "^$")) ;(not (eobp))
            (if (or (not marked) (and marked (todos-marked-item-p)))
                (progn
                  (setq item (todos-item-string))
-                 (setq done-item (cond (marked
-                                        (concat done-item done-prefix item "\n"))
-                                       (comment
-                                        (concat done-prefix item " ["
-                                                todos-comment-string
-                                                ": " comment "]"))
-                                       (t
-                                        (concat done-prefix item))))
+                 (setq done-item (concat done-item done-prefix item
+                                         comment (and marked "\n")))
                  (setq item-count (1+ item-count))
                  (when (todos-diary-item-p)
                    (setq diary-count (1+ diary-count)))
@@ -4896,7 +5665,6 @@ relocated to the category's (by default hidden) done section."
        (when marked
          ;; Chop off last newline of done item string.
          (setq done-item (substring done-item 0 -1))
-         (remove-overlays (point-min) (point-max) 'before-string todos-item-mark)
          (setq todos-categories-with-marks
                (assq-delete-all cat todos-categories-with-marks)))
        (save-excursion
@@ -4904,12 +5672,16 @@ relocated to the category's (by default hidden) done section."
          (re-search-forward
           (concat "^" (regexp-quote todos-category-done)) nil t)
          (forward-char)
+         (when show-done (setq opoint (point)))
          (insert done-item "\n"))
        (todos-update-count 'todo (- item-count))
        (todos-update-count 'done item-count)
        (todos-update-count 'diary (- diary-count))
        (todos-update-categories-sexp)
-       (save-excursion (todos-category-select))))))
+       (let ((todos-show-with-done show-done))
+         (todos-category-select)
+         ;; When done items are shown, put cursor on first just done item.
+         (when opoint (goto-char opoint)))))))
 
 (defun todos-done-item-add-edit-or-delete-comment (&optional arg)
   "Add a comment to this done item or edit an existing comment.
@@ -4917,6 +5689,7 @@ With prefix ARG delete an existing comment."
   (interactive "P")
   (when (todos-done-item-p)
     (let ((item (todos-item-string))
+         (opoint (point))
          (end (save-excursion (todos-item-end)))
          comment buffer-read-only)
       (save-excursion
@@ -4931,26 +5704,34 @@ With prefix ARG delete an existing comment."
                                         (cons (match-string 1) 1)))
              (replace-match comment nil nil nil 1))
          (setq comment (read-string "Enter a comment: "))
+         ;; If user moved point during editing, make sure it moves back.
+         (goto-char opoint)
          (todos-item-end)
          (insert " [" todos-comment-string ": " comment "]"))))))
 
 (defun todos-item-undo ()
-  "Restore this done item to the todo section of this category.
-If done item has a comment, ask whether to omit the comment from
-the restored item."
+  "Restore at least one done item to this category's todo section.
+Prompt for the new priority.  If there are marked items, undo all
+of these, giving the first undone item the new priority and the
+rest following directly in sequence; otherwise, undo just the
+item at point.
+
+If the done item has a comment, ask whether to omit the comment
+from the restored item.  With multiple marked done items with
+comments, only ask once, and if affirmed, omit subsequent
+comments without asking."
   (interactive)
   (let* ((cat (todos-current-category))
-        (marked (assoc cat todos-categories-with-marks)))
+        (marked (assoc cat todos-categories-with-marks))
+        (pl (if (and marked (> (cdr marked) 1)) "s" "")))
     (when (or marked (todos-done-item-p))
       (let ((buffer-read-only)
-           (bufmod (buffer-modified-p))
            (opoint (point))
-           (orig-mrk (progn (todos-item-start) (point-marker)))
-           (orig-item (todos-item-string))
+           (omark (point-marker))
            (first 'first)
            (item-count 0)
            (diary-count 0)
-           start end item undone)
+           start end item ov npoint undone)
        (and marked (goto-char (point-min)))
        (catch 'done
          (while (not (eobp))
@@ -4958,6 +5739,10 @@ the restored item."
                (if (not (todos-done-item-p))
                    (error "Only done items can be undone")
                  (todos-item-start)
+                 (unless marked
+                   (setq ov (make-overlay (save-excursion (todos-item-start))
+                                          (save-excursion (todos-item-end))))
+                   (overlay-put ov 'face 'todos-search))
                  ;; Find the end of the date string added upon tagging item as
                  ;; done.
                  (setq start (search-forward "] "))
@@ -4973,60 +5758,52 @@ the restored item."
                    (if (eq first 'first)
                        (setq first
                              (if (eq todos-undo-item-omit-comment 'ask)
-                                 (when (y-or-n-p
-                                        "Omit comment from restored item? ")
+                                 (when (y-or-n-p (concat "Omit comment" pl
+                                                         " from restored item"
+                                                         pl "? "))
                                    'omit)
                                (when todos-undo-item-omit-comment 'omit)))
                      t)
                    (when (eq first 'omit)
-                     (delete-region (match-beginning 0) (match-end 0))
-                     (setq end (point))))
+                     (setq end (match-beginning 0)))
                  (setq item (concat item
                                     (buffer-substring-no-properties start end)
                                     (when marked "\n")))
-                 (todos-remove-item)
-                 (unless marked (throw 'done nil)))
-             (todos-forward-item))))
-       (if marked
+                 (unless marked (throw 'done nil)))))
+           (todos-forward-item)))
+       (unwind-protect
            (progn
-             ;; (remove-overlays (point-min) (point-max)
-             ;;                       'before-string todos-item-mark)
-             (setq todos-categories-with-marks
-                   (assq-delete-all cat todos-categories-with-marks))
-             ;; Insert undone items that were marked at end of todo item list.
-             (goto-char (point-min))
-             (re-search-forward (concat "^" (regexp-quote todos-category-done))
-                                nil t)
-             (forward-line -1)
-             (insert item)
-             (todos-update-count 'todo item-count)
-             (todos-update-count 'done (- item-count))
-             (when diary-count (todos-update-count 'diary diary-count))
-             (todos-update-categories-sexp)
-             (let ((todos-show-with-done (> (todos-get-count 'done) 0)))
-               (todos-category-select)))
-         ;; With an unmarked undone item, prompt for its priority.  If user
-         ;; cancels before setting new priority, then leave the done item
-         ;; unchanged.
-         (unwind-protect
-             (progn
-               (todos-set-item-priority item (todos-current-category) t)
-               (setq undone t)
-               (todos-update-count 'todo 1)
-               (todos-update-count 'done -1)
-               (and (todos-diary-item-p) (todos-update-count 'diary 1))
-               (todos-update-categories-sexp)
-               (let ((todos-show-with-done (> (todos-get-count 'done) 0)))
-                 (todos-category-select)))
-           (unless undone
-             (let ((todos-show-with-done t))
-               (widen)
-               (goto-char orig-mrk)
-               (todos-insert-with-overlays orig-item)
-               (set-buffer-modified-p bufmod)
-               (todos-category-select))
-               (goto-char opoint))))
-       (set-marker orig-mrk nil)))))
+             ;; Chop off last newline of multiple items string, since
+             ;; it will be reinserted on setting priority.
+             (and marked (setq item (substring item 0 -1)))
+             (todos-set-item-priority item cat t)
+             (setq npoint (point))
+             (setq undone t))
+         (if ov (delete-overlay ov))
+         (if (not undone)
+             (goto-char opoint)
+           (if marked
+               (progn
+                 (setq item nil)
+                 (re-search-forward
+                  (concat "^" (regexp-quote todos-category-done)) nil t)
+                 (while (not (eobp))
+                   (if (todos-marked-item-p)
+                       (todos-remove-item)
+                     (todos-forward-item)))
+                 (setq todos-categories-with-marks
+                       (assq-delete-all cat todos-categories-with-marks)))
+             (goto-char omark)
+             (todos-remove-item))
+           (todos-update-count 'todo item-count)
+           (todos-update-count 'done (- item-count))
+           (when diary-count (todos-update-count 'diary diary-count))
+           (todos-update-categories-sexp)
+           (let ((todos-show-with-done (> (todos-get-count 'done) 0)))
+             (todos-category-select))
+           ;; Put cursor on undone item.
+           (goto-char npoint)))
+       (set-marker omark nil)))))
 
 (defun todos-archive-done-item (&optional all)
   "Archive at least one done item in this category.
@@ -5053,6 +5830,7 @@ this category does not exist in the archive, it is created."
                          (get-buffer-create afile)))
               (item (and (todos-done-item-p) (concat (todos-item-string) "\n")))
               (count 0)
+              (opoint (unless (todos-done-item-p) (point)))
               marked-items beg end all-done
               buffer-read-only)
          (cond
@@ -5082,24 +5860,27 @@ this category does not exist in the archive, it is created."
                                  (match-beginning 0)
                                (point-max))
                          all-done (buffer-substring-no-properties beg end)
-                         count (todos-get-count 'done))))
+                         count (todos-get-count 'done))
+                   ;; Restore starting point, unless it was on a done
+                   ;; item, since they will all be deleted.
+                   (when opoint (goto-char opoint))))
              (throw 'end nil))))
-         (when (or marked all item)
+         (if (not (or marked all item))
+             (throw 'end (message "Only done items can be archived"))
            (with-current-buffer archive
              (unless buffer-file-name (erase-buffer))
              (let (buffer-read-only)
                (widen)
                (goto-char (point-min))
-               (if (and (re-search-forward (concat "^"
-                                                   (regexp-quote
-                                                    (concat todos-category-beg
-                                                            cat)))
-                                           nil t)
+               (if (and (re-search-forward
+                         (concat "^" (regexp-quote
+                                      (concat todos-category-beg cat)) "$")
+                         nil t)
                         (re-search-forward (regexp-quote todos-category-done)
                                            nil t))
                    ;; Start of done items section in existing category.
                    (forward-char)
-                 (todos-add-category cat)
+                 (todos-add-category nil cat)
                  ;; Start of done items section in new category.
                  (goto-char (point-max)))
                (insert (cond (marked marked-items)
@@ -5114,7 +5895,11 @@ this category does not exist in the archive, it is created."
                  (write-region nil nil afile)
                  (kill-buffer))))
            (with-current-buffer tbuf
-             (cond ((or marked item)
+             (cond ((or marked
+                        ;; If we're archiving all done items, can't
+                        ;; first archive item point was on, since
+                        ;; that will short-circuit the rest.
+                        (and item (not all)))
                     (and marked (goto-char (point-min)))
                     (catch 'done
                       (while (not (eobp))
@@ -5130,13 +5915,15 @@ this category does not exist in the archive, it is created."
                                 (throw 'done (setq item nil))))
                           (todos-forward-item)))))
                    (all
-                    (remove-overlays beg end)
-                    (delete-region beg end)
-                    (todos-update-count 'done (- count))
-                    (todos-update-count 'archived count)))
+                    (save-excursion
+                      (save-restriction
+                        ;; Make sure done items are accessible.
+                        (widen)
+                        (remove-overlays beg end)
+                        (delete-region beg end)
+                        (todos-update-count 'done (- count))
+                        (todos-update-count 'archived count)))))
              (when marked
-               (remove-overlays (point-min) (point-max)
-                                'before-string todos-item-mark)
                (setq todos-categories-with-marks
                      (assq-delete-all cat todos-categories-with-marks)))
              (todos-update-categories-sexp)
@@ -5145,127 +5932,126 @@ this category does not exist in the archive, it is created."
          (todos-category-number cat)
          (todos-category-select)
          (split-window-below)
-         (set-window-buffer (selected-window) tbuf))))))
+         (set-window-buffer (selected-window) tbuf)
+         ;; Make todo file current to select category.
+         (find-file (buffer-file-name tbuf))
+         ;; Make sure done item separator is hidden (if done items
+         ;; were initially visible).
+         (let (todos-show-with-done) (todos-category-select)))))))
 
 (defun todos-archive-category-done-items ()
   "Move all done items in this category to its archive."
   (interactive)
   (todos-archive-done-item t))
 
-(defun todos-unarchive-items (&optional all)
+(defun todos-unarchive-items ()
   "Unarchive at least one item in this archive category.
-
 If there are marked items, unarchive all of these; otherwise,
-with non-nil argument ALL, unarchive all items in this category;
-otherwise, unarchive the item at point.
+unarchive the item at point.
 
 Unarchived items are restored as done items to the corresponding
-category in the Todos file, inserted at the end of done section.
-If all items in the archive category were restored, the category
-is deleted from the archive.  If this was the only category in the
-archive, the archive file is deleted."
+category in the Todos file, inserted at the top of done items
+section.  If all items in the archive category have been
+restored, the category is deleted from the archive.  If this was
+the only category in the archive, the archive file is deleted."
   (interactive)
   (when (eq major-mode 'todos-archive-mode)
-    (catch 'end
-      (let* ((cat (todos-current-category))
-            (tbuf (find-file-noselect
-                   (concat (file-name-sans-extension todos-current-todos-file)
-                           ".todo") t))
-            (marked (assoc cat todos-categories-with-marks))
-            (item (concat (todos-item-string) "\n"))
-            (all-items (when all (buffer-substring-no-properties
-                                  (point-min) (point-max))))
-            (all-count (when all (todos-get-count 'done)))
-            marked-items marked-count
-            buffer-read-only)
-       (when marked
-         (save-excursion
-           (goto-char (point-min))
-           (while (not (eobp))
-             (when (todos-marked-item-p)
-               (concat marked-items (todos-item-string) "\n")
-               (setq marked-count (1+ marked-count)))
-             (todos-forward-item))))
-       ;; Restore items to end of category's done section and update counts.
-       (with-current-buffer tbuf
-         (let (buffer-read-only)
-           (widen)
-           (goto-char (point-min))
-           (re-search-forward (concat "^" (regexp-quote
-                                           (concat todos-category-beg cat)))
-                              nil t)
-           ;; Go to end of category's done section.
-           (if (re-search-forward (concat "^" (regexp-quote todos-category-beg))
-                                  nil t)
-               (goto-char (match-beginning 0))
-             (goto-char (point-max)))
-           (cond (marked
-                  (insert marked-items)
-                  (todos-update-count 'done marked-count cat)
-                  (todos-update-count 'archived (- marked-count) cat))
-                 (all
-                  (insert all-items)
-                  (todos-update-count 'done all-count cat)
-                  (todos-update-count 'archived (- all-count) cat))
-                 (t
-                  (insert item)
-                  (todos-update-count 'done 1 cat)
-                  (todos-update-count 'archived -1 cat)))
-           (todos-update-categories-sexp)))
-       ;; Delete restored items from archive.
-       (cond ((or marked item)
-              (and marked (goto-char (point-min)))
-              (catch 'done
-                (while (not (eobp))
-                  (if (or (and marked (todos-marked-item-p)) item)
-                      (progn
-                        (todos-remove-item)
-                        ;; Don't leave point below last item.
-                        (and item (bolp) (eolp) (< (point-min) (point-max))
-                             (todos-backward-item))
-                        (when item 
-                          (throw 'done (setq item nil))))
-                    (todos-forward-item))))
-              (todos-update-count 'done (if marked (- marked-count) -1) cat))
-             (all
-              (remove-overlays (point-min) (point-max))
-              (delete-region (point-min) (point-max))))
-       ;; If that was the last category in the archive, delete the whole file.
-       (if (= (length todos-categories) 1)
-           (progn
-             (delete-file todos-current-todos-file)
-             ;; Don't bother confirming killing the archive buffer.
-             (set-buffer-modified-p nil)
-             (kill-buffer))
-         ;; Otherwise, if the archive category is now empty, delete it.
-         (when (eq (point-min) (point-max))
-           (widen)
-           (let ((beg (re-search-backward
-                       (concat "^" (regexp-quote todos-category-beg) cat)
-                       nil t))
-                 (end (if (re-search-forward
-                           (concat "^" (regexp-quote todos-category-beg))
-                           nil t 2)
-                          (match-beginning 0)
-                        (point-max))))
-             (remove-overlays beg end)
-             (delete-region beg end)
-             (setq todos-categories (delete (assoc cat todos-categories)
-                                            todos-categories))
-             (todos-update-categories-sexp))))
-       ;; Visit category in Todos file and show restored done items.
-       (let ((tfile (buffer-file-name tbuf))
-             (todos-show-with-done t))
-         (set-window-buffer (selected-window)
-                            (set-buffer (find-file-noselect tfile)))
-         (todos-category-number cat)
-         (todos-show)
-         (message "Items unarchived."))))))
-
-(defun todos-unarchive-category ()
-  "Unarchive all items in this category.  See `todos-unarchive-items'."
-  (interactive)
-  (todos-unarchive-items t))
+    (let* ((cat (todos-current-category))
+          (tbuf (find-file-noselect
+                 (concat (file-name-sans-extension todos-current-todos-file)
+                         ".todo") t))
+          (marked (assoc cat todos-categories-with-marks))
+          (item (concat (todos-item-string) "\n"))
+          (marked-count 0)
+          marked-items
+          buffer-read-only)
+      (when marked
+       (save-excursion
+         (goto-char (point-min))
+         (while (not (eobp))
+           (when (todos-marked-item-p)
+             (setq marked-items (concat marked-items (todos-item-string) "\n"))
+             (setq marked-count (1+ marked-count)))
+           (todos-forward-item))))
+      ;; Restore items to top of category's done section and update counts.
+      (with-current-buffer tbuf
+       (let (buffer-read-only newcat)
+         (widen)
+         (goto-char (point-min))
+         ;; Find the corresponding todo category, or if there isn't
+         ;; one, add it.
+         (unless (re-search-forward
+                  (concat "^" (regexp-quote (concat todos-category-beg cat))
+                          "$") nil t)
+           (todos-add-category nil cat)
+           (setq newcat t))
+         ;; Go to top of category's done section.
+         (re-search-forward
+          (concat "^" (regexp-quote todos-category-done)) nil t)
+         (forward-line)
+         ;; FIXME: delete after checking
+         ;; ;; Put point below newly added category beginning,
+         ;; ;; otherwise the following search wrongly succeeds.
+         ;; (forward-line))
+         ;; (if (re-search-forward (concat "^" (regexp-quote todos-category-beg))
+         ;;                     nil t)
+         ;;     (goto-char (match-beginning 0))
+         ;;   (goto-char (point-max)))
+         (cond (marked
+                (insert marked-items)
+                (todos-update-count 'done marked-count cat)
+                (unless newcat         ; Newly added category has no archive.
+                  (todos-update-count 'archived (- marked-count) cat)))
+               (t
+                (insert item)
+                (todos-update-count 'done 1 cat)
+                (unless newcat         ; Newly added category has no archive.
+                  (todos-update-count 'archived -1 cat))))
+         (todos-update-categories-sexp)))
+      ;; Delete restored items from archive.
+      (when marked
+       (setq item nil)
+       (goto-char (point-min)))
+      (catch 'done
+       (while (not (eobp))
+         (if (or (todos-marked-item-p) item)
+             (progn
+               (todos-remove-item)
+               (when item
+                 (throw 'done (setq item nil))))
+           (todos-forward-item))))
+      (todos-update-count 'done (if marked (- marked-count) -1) cat)
+      ;; If that was the last category in the archive, delete the whole file.
+      (if (= (length todos-categories) 1)
+         (progn
+           (delete-file todos-current-todos-file)
+           ;; Kill the archive buffer silently.
+           (set-buffer-modified-p nil)
+           (kill-buffer))
+       ;; Otherwise, if the archive category is now empty, delete it.
+       (when (eq (point-min) (point-max))
+         (widen)
+         (let ((beg (re-search-backward
+                     (concat "^" (regexp-quote todos-category-beg) cat "$")
+                     nil t))
+               (end (if (re-search-forward
+                         (concat "^" (regexp-quote todos-category-beg))
+                         nil t 2)
+                        (match-beginning 0)
+                      (point-max))))
+           (remove-overlays beg end)
+           (delete-region beg end)
+           (setq todos-categories (delete (assoc cat todos-categories)
+                                          todos-categories))
+           (todos-update-categories-sexp))))
+      ;; Visit category in Todos file and show restored done items.
+      (let ((tfile (buffer-file-name tbuf))
+           (todos-show-with-done t))
+       (set-window-buffer (selected-window)
+                          (set-buffer (find-file-noselect tfile)))
+       (todos-category-number cat)
+       (todos-category-select)
+       (message "Items unarchived.")))))
 
 (provide 'todos)
 
@@ -5275,6 +6061,7 @@ archive, the archive file is deleted."
 ;; ---------------------------------------------------------------------------
 (add-to-list 'auto-mode-alist '("\\.todo\\'" . todos-mode))
 (add-to-list 'auto-mode-alist '("\\.toda\\'" . todos-archive-mode))
+(add-to-list 'auto-mode-alist '("\\.tod[tyr]\\'" . todos-filtered-items-mode))
 
 ;;; Addition to calendar.el
 ;; FIXME: autoload when key-binding is defined in calendar.el