* todos.el: Fixes and improvements related to item relocation.
[bpt/emacs.git] / lisp / calendar / todos.el
index 13249f9..30c64ef 100644 (file)
@@ -143,7 +143,9 @@ displayed correctly."
   "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 top priorities" top)
+                (const :tag "Show diary items" diary)
+                (const :tag "Show regexp items" regexp))
   :group 'todos)
 
 (defcustom todos-completion-ignore-case nil
@@ -217,7 +219,6 @@ These reflect the priorities of the items in each category."
     (when (not (equal value oldvalue))
       (dolist (f files)
        (with-current-buffer (find-file-noselect f)
-         (remove-overlays 1 (1+ (buffer-size)) 'todos 'prefix)
          ;; Activate the new setting in the current category.
          (save-excursion (todos-category-select)))))))
 
@@ -497,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
@@ -532,6 +513,8 @@ items in that category, which overrides NUM."
   :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
@@ -611,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."
@@ -1077,6 +1060,8 @@ short Todos Archive or Top Priorities file name, respectively."
      (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 ()
@@ -1150,11 +1135,14 @@ number as its value."
   "Return string used as value of variable `todos-done-separator'."
   (let ((sep todos-done-separator-string))
     (propertize (if (= 1 (length sep))
-                   ;; If separator's length is window-width, an
-                   ;; indented empty line appears between the
-                   ;; separator and the first done item.
-                   ;; FIXME: should this be customizable?
+                   ;; 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)))
 
@@ -1204,6 +1192,16 @@ Todos files named in `todos-category-completions-files'."
       (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)
@@ -1933,15 +1931,64 @@ the empty string (i.e., no time string)."
   (message "Click \"Apply\" after selecting files.")
   (recursive-edit))
 
-(defun todos-filter-items (filter file-list)
-  "Display a list of items from FILE-LIST that satisfy FILTER.
-The values of FILE-LIST and FILTER are passed from the calling
-commands.  The files in FILE-LIST are either the current Todos
-file or those listed in `todos-filter-files' or chosen
-interactively.  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."
+(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))
        (multifile (> (length file-list) 1))
@@ -2136,27 +2183,26 @@ set the user customizable option `todos-priorities-rules'."
     (customize-save-variable 'todos-priorities-rules rules)
     (todos-prefix-overlays)))
 
-(defun todos-filtered-buffer-name (buffer-type file-list)
-  "Rename Todos filtered buffer using BUFFER-TYPE and FILE-LIST.
+(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'.")
 
-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* ((multi (> (length file-list) 1))
-        (fnames (mapconcat (lambda (f) (todos-short-file-name f))
-                          file-list ", ")))
-    (rename-buffer (format (concat "%s for file" (if multi "s" "")
-                                  " \"%s\"") buffer-type fnames))))
+(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 saved top priority item STR in its Todos file.
+  "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
-priority has changed or its text was truncated or augmented, and
-`same' otherwise."
+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 "\\)")
@@ -2172,11 +2218,14 @@ priority has changed or its text was truncated or augmented, and
        (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))
-    (save-excursion
-      (while (search-backward filcat nil t)
-         (setq tpriority (1+ tpriority))))
+    (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"))
@@ -2186,45 +2235,48 @@ priority has changed or its text was truncated or augmented, and
                   todos-global-current-todos-file)))
     (find-file-noselect file)
     (with-current-buffer (find-buffer-visiting file)
-      (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))
-                                (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))))))))
+      (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-top-priorities ()
-  "Return a message saying whether top priorities file is up to date."
+(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))
@@ -2238,26 +2290,35 @@ priority has changed or its text was truncated or augmented, and
          ;; (throw 'old (message "The marked item is not up to date.")))
       (todos-forward-item))
     (if (zerop count)
-       (message "Top priorities file is up to date.")
+       (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-top-priorities-filename ()
-  ""
+(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)))
-      (concat todos-files-directory filename-base ".todt"))))
-
-(defun todos-save-top-priorities-buffer ()
-  ""
-  (let ((filename (todos-top-priorities-filename)))
-    (if (file-exists-p filename)
-       (save-buffer)
-      (write-region nil nil filename nil t nil t))))
+          (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.
@@ -2620,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
@@ -2672,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))))
 
@@ -2717,6 +2780,7 @@ 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)
     ("n"            . todos-forward-item)
     ("p"            . todos-backward-item)
@@ -2837,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)
@@ -2847,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.")
 
@@ -2861,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)
@@ -3020,11 +3088,14 @@ which is the value of the user option
 ;;;###autoload
 (defun todos-show (&optional solicit-file)
   "Visit a Todos file and display one of its categories.
-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.
+
+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
@@ -3032,12 +3103,13 @@ file name and an initial category (defaulting to
 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 `table', show
-the table of categories in the file; if `top', show the
-corresponding top priorities file, if any; if `first' (the
-default value), show the first category in the file.  Subsequent
-invocations always show the file's current (i.e., last displayed)
-category.
+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
@@ -3050,7 +3122,8 @@ corresponding Todos file, displaying the corresponding category."
   (interactive "P")
   (let* ((cat)
         (show-first todos-show-first)
-        (file (cond (solicit-file
+        (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)
@@ -3070,18 +3143,35 @@ corresponding Todos file, displaying the corresponding category."
                          (todos-add-file))))))
     (unless (member file todos-visited)
       ;; Can't setq t-c-t-f here, otherwise wrong file shown when
-      ;; called again from todos-display-categories.
+      ;; todos-show is called from todos-display-categories.
       (let ((todos-current-todos-file file))
        (cond ((eq todos-show-first 'table)
               (todos-display-categories))
-             ((eq todos-show-first 'top)
+             ((memq todos-show-first '(top diary regexp))
               (let* ((shortf (todos-short-file-name file))
-                     (tp-file (todos-absolute-file-name shortf 'top)))
-                (if (file-exists-p tp-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 tp-file 'nowarn)))
-                  (message "There is no top priorities file for %s" shortf)
+                     (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))
@@ -3219,8 +3309,8 @@ displayed."
   "Save the current Todos file."
   (interactive)
   (cond ((eq major-mode 'todos-filtered-items-mode)
-        (todos-check-top-priorities)
-        (todos-save-top-priorities-buffer))
+        (todos-check-filtered-items-file)
+        (todos-save-filtered-items-buffer))
        (t
         (save-buffer))))
 
@@ -3242,7 +3332,7 @@ buries it and restores state as needed."
           (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.
@@ -3804,37 +3894,35 @@ marking of the next N items."
 (defun todos-mark-category ()
   "Mark all visiblw items in this category with `todos-item-mark'."
   (interactive)
-  (save-excursion
-    (goto-char (point-min))
-    (while (not (eobp))
-      (let* ((cat (todos-current-category))
-            (marks (assoc cat todos-categories-with-marks))
-            (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))))
+  (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 `todos-item-mark' from all visible items in this category."
   (interactive)
-  (save-excursion
-    (goto-char (point-min))
-    (while (not (eobp))
-      (let* ((cat (todos-current-category))
-            (marks (assoc cat todos-categories-with-marks))
-            (ov (todos-get-overlay 'prefix))
-            (pref (overlay-get ov 'before-string)))
-       (when (todos-marked-item-p)
-         (overlay-put ov 'before-string (substring pref 1))
-         (setq todos-categories-with-marks
-               (delq (assoc (todos-current-category)
-                            todos-categories-with-marks)
-                     todos-categories-with-marks))))
-      (todos-forward-item))))
+  (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
@@ -3851,13 +3939,9 @@ See `todos-set-top-priorities' for more details."
   (interactive)
   (todos-set-top-priorities t))
 
-(defun todos-top-priorities (&optional arg multifile)
+(defun todos-top-priorities (&optional arg)
   "Display a list of top priority items from different categories.
-The categories are either a subset of those in the current Todos
-file, or else, with non-nil argument MULTIFILE, 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.
+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
@@ -3866,37 +3950,13 @@ numbers of top priority items specified by category in
 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-top-priorities-buffer'), visit this file; if there is
+`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* ((flist (if multifile
-                   (or todos-filter-files
-                       (progn (todos-multiple-filter-files)
-                              todos-multiple-filter-files))
-                 (list todos-current-todos-file)))
-        (tp-file (if (equal flist 'quit)
-                     ;; Pressed `cancel' in file selection dialog.
-                     (keyboard-quit)
-                   (concat todos-files-directory
-                           (mapconcat 'identity
-                                      (mapcar 'todos-short-file-name flist)
-                                      "-")
-                           ".todt")))
-        (tp-file-exists (file-exists-p tp-file))
-        (buf todos-top-priorities-buffer))
-    (cond ((and arg (natnump arg))
-          (todos-filter-items (cons 'top arg) flist))
-         ((and (not arg) tp-file-exists)
-          (find-file tp-file)
-          (todos-prefix-overlays)
-          (todos-check-top-priorities))
-         (t
-          (todos-filter-items 'top flist)))
-    (unless tp-file-exists
-      (todos-filtered-buffer-name buf flist))))
+  (todos-filter-items 'top arg))
 
 (defun todos-top-priorities-multifile (&optional arg)
   "Display a list of top priority items from different categories.
@@ -3910,77 +3970,73 @@ 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-top-priorities-buffer'), visit this file;
+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")
-    (todos-top-priorities arg t))
+  (todos-filter-items 'top arg t))
 
-(defun todos-diary-items (&optional multifile)
+(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 a list of todo diary items from different categories.
-The categories are either a subset of those in the current Todos
-file, or else, with non-nil argument MULTIFILE, 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."
-  (interactive)
-  (let ((flist (if multifile
-                   (or todos-filter-files
-                       (progn (todos-multiple-filter-files)
-                              todos-multiple-filter-files))
-                 (list todos-current-todos-file)))
-       (buf todos-diary-items-buffer))
-    (if (equal flist 'quit)
-       ;; Pressed `cancel' in file selection dialog.
-       (keyboard-quit)
-      (todos-filter-items 'diary flist)
-      (todos-filtered-buffer-name buf flist))))
-
-(defun todos-diary-items-multifile ()
-  "Display a list of todo diary items from one or more Todos files.
 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."
-  (interactive)
-  (todos-diary-items t))
+a file selection dialog that pops up in this case.
 
-(defun todos-regexp-items (&optional multifile)
-  "Prompt for a regular expression and display items that match it.
-The matches may be from different categories and with non-nil
-option `todos-filter-done-items', can include not only todo items
-but also done items, including those in Archive files.
-
-The categories are either a subset of those in the current Todos
-file (and possibly in the corresponding Archive file), or else,
-with non-nil argument MULTIFILE, 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 (and possibly in the corresponding Archive files)."
-  (interactive)
-  (let ((flist (if multifile
-                   (or todos-filter-files
-                       (progn (todos-multiple-filter-files)
-                              todos-multiple-filter-files))
-                 (list todos-current-todos-file)))
-       (buf todos-regexp-items-buffer))
-    (if (equal flist 'quit)
-       ;; Pressed `cancel' in file selection dialog.
-       (keyboard-quit)
-      (todos-filter-items 'regexp flist)
-      (todos-filtered-buffer-name buf flist))))
-
-(defun todos-regexp-items-multifile ()
+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")
+  (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 may be from different categories and with non-nil
-option `todos-filter-done-items', can include not only todo items
-but also done items, including those in Archive files.
+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))
 
-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 (and possibly
-in the corresponding Archive files)."
-  (interactive)
-  (todos-regexp-items t))
+(defun todos-regexp-items-multifile (&optional arg)
+  "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")
+  (todos-filter-items 'regexp arg t))
 
 ;; ---------------------------------------------------------------------------
 ;;; Editing Commands
@@ -4109,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
@@ -4522,7 +4578,9 @@ the new item:
   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.  If the command with `here' is invoked
+  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
@@ -4564,8 +4622,9 @@ the priority is not given by HERE but by prompting."
        (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))
+      (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: "))
@@ -4575,6 +4634,8 @@ the priority is not given by HERE but by prompting."
                             (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))
@@ -4606,18 +4667,19 @@ the priority is not given by HERE but by prompting."
        (setq todos-date-from-calendar nil)
        (find-file-noselect file 'nowarn)
        (set-window-buffer (selected-window)
-                          ;; If current category was nil till now, on
-                          ;; entering Todos mode here it will be set to
-                          ;; file's first category.
                           (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))
-       ;; These are not needed here, since they are called in
-       ;; todos-set-item-priority.
-       ;; (todos-category-number cat)
-       ;; (todos-category-select)
        (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.
@@ -4636,37 +4698,58 @@ the priority is not given by HERE but by prompting."
                          "\\(\n\\)[^[:blank:]]"
                          (concat "\n" (make-string todos-indent-to-here 32))
                          new-item nil nil 1))
-         (if here
-             (if (or (todos-done-item-p) (todos-done-item-section-p))
-                 (error "Cannot insert item in done items section")
-               (unless (and todos-mm (equal cat ocat))
+         (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)
-                 (goto-char (point-min)))
-               (todos-insert-with-overlays new-item))
-           (unwind-protect
-               (progn
-                 ;; If only done items are displayed in category,
-                 ;; toggle to todo items.
-                 (when (and (goto-char (point-min))
-                              (looking-at todos-done-string-start))
-                   (setq done-only t)
-                   (todos-show-done-only))
-                 (todos-set-item-priority new-item cat t)
-                 (setq item-added t))
-             ;; If user cancels before setting priority, restore
-             ;; display.
-             (unless item-added
-               (and done-only (todos-show-done-only)))
-             ;; If todos section is not visible when insertion
-             ;; command is called (either because only done items
-             ;; were shown or because category was not in current
-             ;; buffer), then if item is inserted at end of category,
-             ;; point is at eob and eob at window-start, so that 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-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))))))
@@ -4807,55 +4890,6 @@ minibuffer; otherwise, edit it in Todos Edit mode."
          (todos-insert-with-overlays new)
          (move-to-column item-beg))))))
 
-;; (defun todos-edit-multiline-item ()
-;;   "Edit current Todo item 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) ;FIXME: not item editing command
-;;   ""                                        ;FIXME
-;;   (interactive)
-;;   (let ((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))
-;;     (todos-edit-mode)
-;;     (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)
-;;   (if (eq (buffer-size) (- (point-max) (point-min)))
-;;       (when (todos-check-format)
-;;     (todos-repair-categories-sexp))
-;;     ;; Ensure lines following hard newlines are indented.
-;;     (let ((item (replace-regexp-in-string
-;;              "\\(\n\\)[^[:blank:]]"
-;;              (concat "\n" (make-string todos-indent-to-here 32))
-;;              (buffer-string) nil nil 1)))
-;;       (delete-region (point-min) (point-max))
-;;       (insert item)))
-;;   (kill-buffer)
-;;   ;; In case next buffer is not the one holding todos-current-todos-file.
-;;   (todos-show))
-
 (defun todos-edit-multiline-item ()
   "Edit current Todo item in Todos Edit mode.
 Use of newlines invokes `todos-indent' to insure compliance with
@@ -5331,7 +5365,7 @@ meaning to raise or lower the item's priority by one."
                        (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)
+          (priority (cond ((and (not arg) (numberp current-prefix-arg))
                            current-prefix-arg)
                           ((and (eq arg 'raise) (>= curnum 1))
                            (1- curnum))
@@ -5353,7 +5387,9 @@ meaning to raise or lower the item's priority by one."
                (goto-char (point-min))
                (setq done (re-search-forward todos-done-string-start nil t))))
            (let ((todos-show-with-done done))
-             (todos-category-select)))))
+             (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)
@@ -5406,7 +5442,7 @@ meaning to raise or lower the item's priority by one."
        (and marked
             (let* ((ov (todos-get-overlay 'prefix))
                    (pref (overlay-get ov 'before-string)))
-              (overlay-put ov 'before-string (concat todos-item-mark pref)))))))
+              (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."
@@ -5435,12 +5471,12 @@ 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 end of the done items
+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)))
-    ;; NOP if point is not on an item and there are no marked items.
+    ;; Noop if point is not on an item and there are no marked items.
     (unless (and (looking-at "^$")
                 (not marked))
       (let* ((buffer-read-only)
@@ -5453,20 +5489,23 @@ section in the category moved to."
             (todo 0)
             (diary 0)
             (done 0)
-            ov cat+file cat2 file2 moved nmark todo-items done-items)
+            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))
-             (setq cat+file (let ((pl (if (and marked (> (cdr marked) 1))
-                                          "s" "")))
-                              (todos-read-category (concat "Move item" pl
+             (let* ((pl (if (and marked (> (cdr marked) 1)) "s" ""))
+                    (cat+file (todos-read-category (concat "Move item" pl
                                                            " to category: ")
-                                                   nil file))
-                   cat2 (car cat+file)
-                   file2 (cdr cat+file)))
+                                                   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
@@ -5500,7 +5539,7 @@ section in the category moved to."
            (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 end of done item section.
+             ;; Move done items en bloc to top of done items section.
              (when (or done-items done-item)
                (todos-category-number cat2)
                (widen)
@@ -5509,11 +5548,9 @@ section in the category moved to."
                                                (concat todos-category-beg cat2))
                                           "$")
                                   nil t)
-               (goto-char (if (re-search-forward
-                               (concat "^" (regexp-quote todos-category-beg))
-                               nil t)
-                              (match-beginning 0)
-                            (point-max)))
+               (re-search-forward
+                (concat "^" (regexp-quote todos-category-done)) nil t)
+               (forward-line)
                (insert (or done-items done-item)))
              (setq moved t))
          (cond
@@ -5568,6 +5605,8 @@ section in the category moved to."
           ;; 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))))))))
@@ -5596,14 +5635,17 @@ visible."
                            ""))
             (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)
             (show-done (save-excursion
                          (goto-char (point-min))
                          (re-search-forward todos-done-string-start nil t)))
-            item done-item
-            (buffer-read-only))
+            (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
          ;; Stop looping when we hit the empty line below the last
@@ -5612,14 +5654,8 @@ visible."
            (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)))
@@ -5636,13 +5672,16 @@ visible."
          (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)
        (let ((todos-show-with-done show-done))
-         (todos-category-select))))))
+         (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.
@@ -5671,22 +5710,28 @@ With prefix ARG delete an existing comment."
          (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))
@@ -5694,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 "] "))
@@ -5709,58 +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
-             (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.
@@ -5901,120 +5944,114 @@ this category does not exist in the archive, it is created."
   (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)
 
@@ -6024,7 +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 '("\\.todt\\'" . todos-filtered-items-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