]> git.notmuchmail.org Git - notmuch/blobdiff - emacs/notmuch.el
emacs: Use 'and' instead of 'when' when the return value matters
[notmuch] / emacs / notmuch.el
index 079a3d1fdd1e9b7053d053f40b04e6607c4f335c..4120764352ff57115d9d4cae63f96ef87e227f02 100644 (file)
 ;; Have fun, and let us know if you have any comment, questions, or
 ;; kudos: Notmuch list <notmuch@notmuchmail.org> (subscription is not
 ;; required, but is available from https://notmuchmail.org).
-
+;;
+;; Note for MELPA users (and others tracking the development version
+;; of notmuch-emacs):
+;;
+;; This emacs package needs a fairly closely matched version of the
+;; notmuch program. If you use the MELPA version of notmuch.el (as
+;; opposed to MELPA stable), you should be prepared to track the
+;; master development branch (i.e. build from git) for the notmuch
+;; program as well. Upgrading notmuch-emacs too far beyond the notmuch
+;; program can CAUSE YOUR EMAIL TO STOP WORKING.
+;;
+;; TL;DR: notmuch-emacs from MELPA and notmuch from distro packages is
+;; NOT SUPPORTED.
+;;
 ;;; Code:
 
-(eval-when-compile (require 'cl))
+(eval-when-compile (require 'cl-lib))
+
 (require 'mm-view)
 (require 'message)
 
@@ -99,27 +113,27 @@ there will be called at other points of notmuch execution."
   :group 'notmuch)
 
 (defvar notmuch-query-history nil
-  "Variable to store minibuffer history for notmuch queries")
+  "Variable to store minibuffer history for notmuch queries.")
 
 (defun notmuch-foreach-mime-part (function mm-handle)
   (cond ((stringp (car mm-handle))
-         (dolist (part (cdr mm-handle))
-           (notmuch-foreach-mime-part function part)))
-        ((bufferp (car mm-handle))
-         (funcall function mm-handle))
-        (t (dolist (part mm-handle)
-             (notmuch-foreach-mime-part function part)))))
+        (dolist (part (cdr mm-handle))
+          (notmuch-foreach-mime-part function part)))
+       ((bufferp (car mm-handle))
+        (funcall function mm-handle))
+       (t (dolist (part mm-handle)
+            (notmuch-foreach-mime-part function part)))))
 
 (defun notmuch-count-attachments (mm-handle)
   (let ((count 0))
     (notmuch-foreach-mime-part
      (lambda (p)
        (let ((disposition (mm-handle-disposition p)))
-         (and (listp disposition)
-              (or (equal (car disposition) "attachment")
-                  (and (equal (car disposition) "inline")
-                       (assq 'filename disposition)))
-              (incf count))))
+        (and (listp disposition)
+             (or (equal (car disposition) "attachment")
+                 (and (equal (car disposition) "inline")
+                      (assq 'filename disposition)))
+             (cl-incf count))))
      mm-handle)
     count))
 
@@ -128,13 +142,13 @@ there will be called at other points of notmuch execution."
    (lambda (p)
      (let ((disposition (mm-handle-disposition p)))
        (and (listp disposition)
-            (or (equal (car disposition) "attachment")
-                (and (equal (car disposition) "inline")
-                     (assq 'filename disposition)))
-            (or (not queryp)
-                (y-or-n-p
-                 (concat "Save '" (cdr (assq 'filename disposition)) "' ")))
-            (mm-save-part p))))
+           (or (equal (car disposition) "attachment")
+               (and (equal (car disposition) "inline")
+                    (assq 'filename disposition)))
+           (or (not queryp)
+               (y-or-n-p
+                (concat "Save '" (cdr (assq 'filename disposition)) "' ")))
+           (mm-save-part p))))
    mm-handle))
 
 (require 'hl-line)
@@ -175,7 +189,9 @@ there will be called at other points of notmuch execution."
     (define-key map "-" 'notmuch-search-remove-tag)
     (define-key map "+" 'notmuch-search-add-tag)
     (define-key map (kbd "RET") 'notmuch-search-show-thread)
+    (define-key map (kbd "M-RET") 'notmuch-tree-from-search-thread)
     (define-key map "Z" 'notmuch-tree-from-search-current-query)
+    (define-key map "U" 'notmuch-unthreaded-from-search-current-query)
     map)
   "Keymap for \"notmuch search\" buffers.")
 (fset 'notmuch-search-mode-map notmuch-search-mode-map)
@@ -186,7 +202,7 @@ there will be called at other points of notmuch execution."
     (define-key map "q" 'notmuch-stash-query)
     (define-key map "?" 'notmuch-subkeymap-help)
     map)
-  "Submap for stash commands")
+  "Submap for stash commands.")
 (fset 'notmuch-search-stash-map notmuch-search-stash-map)
 
 (defun notmuch-search-stash-thread-id ()
@@ -248,7 +264,8 @@ there will be called at other points of notmuch execution."
   (goto-char (point-max))
   (forward-line -2)
   (let ((beg (notmuch-search-result-beginning)))
-    (when beg (goto-char beg))))
+    (when beg
+      (goto-char beg))))
 
 (defun notmuch-search-first-thread ()
   "Select the first thread in the search results."
@@ -256,11 +273,11 @@ there will be called at other points of notmuch execution."
   (goto-char (point-min)))
 
 (defface notmuch-message-summary-face
- '((((class color) (background light)) (:background "#f0f0f0"))
-   (((class color) (background dark)) (:background "#303030")))
- "Face for the single-line message summary in notmuch-show-mode."
- :group 'notmuch-show
- :group 'notmuch-faces)
 '((((class color) (background light)) (:background "#f0f0f0"))
+    (((class color) (background dark)) (:background "#303030")))
 "Face for the single-line message summary in notmuch-show-mode."
 :group 'notmuch-show
 :group 'notmuch-faces)
 
 (defface notmuch-search-date
   '((t :inherit default))
@@ -313,8 +330,12 @@ there will be called at other points of notmuch execution."
   :group 'notmuch-faces)
 
 (defface notmuch-search-flagged-face
-  '((t
-     (:weight bold)))
+  '((((class color)
+      (background dark))
+     (:foreground "LightBlue1"))
+    (((class color)
+      (background light))
+     (:foreground "blue")))
   "Face used in search mode face for flagged threads.
 
 This face is the default value for the \"flagged\" tag in
@@ -324,7 +345,7 @@ This face is the default value for the \"flagged\" tag in
 
 (defface notmuch-search-unread-face
   '((t
-     (:foreground "blue")))
+     (:weight bold)))
   "Face used in search mode for unread threads.
 
 This face is the default value for the \"unread\" tag in
@@ -370,7 +391,11 @@ Complete list of currently available key bindings:
   (set (make-local-variable 'scroll-preserve-screen-position) t)
   (add-to-invisibility-spec (cons 'ellipsis t))
   (setq truncate-lines t)
-  (setq buffer-read-only t))
+  (setq buffer-read-only t)
+  (setq imenu-prev-index-position-function
+       #'notmuch-search-imenu-prev-index-position-function)
+  (setq imenu-extract-index-name-function
+       #'notmuch-search-imenu-extract-index-name-function))
 
 (defun notmuch-search-get-result (&optional pos)
   "Return the result object for the thread at POS (or point).
@@ -382,46 +407,47 @@ If there is no thread at POS (or point), returns nil."
   "Return the point at the beginning of the thread at POS (or point).
 
 If there is no thread at POS (or point), returns nil."
-  (when (notmuch-search-get-result pos)
-    ;; We pass 1+point because previous-single-property-change starts
-    ;; searching one before the position we give it.
-    (previous-single-property-change (1+ (or pos (point)))
-                                    'notmuch-search-result nil (point-min))))
+  (and (notmuch-search-get-result pos)
+       ;; We pass 1+point because previous-single-property-change starts
+       ;; searching one before the position we give it.
+       (previous-single-property-change (1+ (or pos (point)))
+                                       'notmuch-search-result nil
+                                       (point-min))))
 
 (defun notmuch-search-result-end (&optional pos)
   "Return the point at the end of the thread at POS (or point).
 
 The returned point will be just after the newline character that
 ends the result line.  If there is no thread at POS (or point),
-returns nil"
-  (when (notmuch-search-get-result pos)
-    (next-single-property-change (or pos (point)) 'notmuch-search-result
-                                nil (point-max))))
+returns nil."
+  (and (notmuch-search-get-result pos)
+       (next-single-property-change (or pos (point))
+                                   'notmuch-search-result nil
+                                   (point-max))))
 
-(defun notmuch-search-foreach-result (beg end function)
-  "Invoke FUNCTION for each result between BEG and END.
+(defun notmuch-search-foreach-result (beg end fn)
+  "Invoke FN for each result between BEG and END.
 
-FUNCTION should take one argument.  It will be applied to the
+FN should take one argument.  It will be applied to the
 character position of the beginning of each result that overlaps
 the region between points BEG and END.  As a special case, if (=
-BEG END), FUNCTION will be applied to the result containing point
+BEG END), FN will be applied to the result containing point
 BEG."
-
-  (lexical-let ((pos (notmuch-search-result-beginning beg))
-               ;; End must be a marker in case function changes the
-               ;; text.
-               (end (copy-marker end))
-               ;; Make sure we examine at least one result, even if
-               ;; (= beg end).
-               (first t))
+  (let ((pos (notmuch-search-result-beginning beg))
+       ;; End must be a marker in case fn changes the
+       ;; text.
+       (end (copy-marker end))
+       ;; Make sure we examine at least one result, even if
+       ;; (= beg end).
+       (first t))
     ;; We have to be careful if the region extends beyond the results.
     ;; In this case, pos could be null or there could be no result at
     ;; pos.
     (while (and pos (or (< pos end) first))
       (when (notmuch-search-get-result pos)
-       (funcall function pos))
-      (setq pos (notmuch-search-result-end pos)
-           first nil))))
+       (funcall fn pos))
+      (setq pos (notmuch-search-result-end pos))
+      (setq first nil))))
 ;; Unindent the function argument of notmuch-search-foreach-result so
 ;; the indentation of callers doesn't get out of hand.
 (put 'notmuch-search-foreach-result 'lisp-indent-function 2)
@@ -434,11 +460,12 @@ BEG."
     output))
 
 (defun notmuch-search-find-thread-id (&optional bare)
-  "Return the thread for the current thread
+  "Return the thread for the current thread.
 
-If BARE is set then do not prefix with \"thread:\""
+If BARE is set then do not prefix with \"thread:\"."
   (let ((thread (plist-get (notmuch-search-get-result) :thread)))
-    (when thread (concat (unless bare "thread:") thread))))
+    (when thread
+      (concat (and (not bare) "thread:") thread))))
 
 (defun notmuch-search-find-stable-query ()
   "Return the stable queries for the current thread.
@@ -455,27 +482,27 @@ is nil, include both matched and unmatched messages. If there are
 no messages in the region then return nil."
   (let ((query-list nil) (all (not only-matched)))
     (dolist (queries (notmuch-search-properties-in-region :query beg end))
-      (when (first queries)
-       (push (first queries) query-list))
-      (when (and all (second queries))
-       (push (second queries) query-list)))
-    (when query-list
-      (concat "(" (mapconcat 'identity query-list ") or (") ")"))))
+      (when (car queries)
+       (push (car queries) query-list))
+      (when (and all (cadr queries))
+       (push (cadr queries) query-list)))
+    (and query-list
+        (concat "(" (mapconcat 'identity query-list ") or (") ")"))))
 
 (defun notmuch-search-find-authors ()
-  "Return the authors for the current thread"
+  "Return the authors for the current thread."
   (plist-get (notmuch-search-get-result) :authors))
 
 (defun notmuch-search-find-authors-region (beg end)
-  "Return a list of authors for the current region"
+  "Return a list of authors for the current region."
   (notmuch-search-properties-in-region :authors beg end))
 
 (defun notmuch-search-find-subject ()
-  "Return the subject for the current thread"
+  "Return the subject for the current thread."
   (plist-get (notmuch-search-get-result) :subject))
 
 (defun notmuch-search-find-subject-region (beg end)
-  "Return a list of authors for the current region"
+  "Return a list of authors for the current region."
   (notmuch-search-properties-in-region :subject beg end))
 
 (defun notmuch-search-show-thread (&optional elide-toggle)
@@ -493,21 +520,28 @@ thread."
                      (current-buffer)
                      notmuch-search-query-string
                      ;; Name the buffer based on the subject.
-                     (concat "*" (truncate-string-to-width subject 30 nil nil t) "*"))
+                     (concat "*"
+                             (truncate-string-to-width subject 30 nil nil t)
+                             "*"))
       (message "End of search results."))))
 
 (defun notmuch-tree-from-search-current-query ()
-  "Call notmuch tree with the current query"
+  "Call notmuch tree with the current query."
   (interactive)
   (notmuch-tree notmuch-search-query-string))
 
+(defun notmuch-unthreaded-from-search-current-query ()
+  "Call notmuch tree with the current query."
+  (interactive)
+  (notmuch-unthreaded notmuch-search-query-string))
+
 (defun notmuch-tree-from-search-thread ()
-  "Show the selected thread with notmuch-tree"
+  "Show the selected thread with notmuch-tree."
   (interactive)
   (notmuch-tree (notmuch-search-find-thread-id)
-                notmuch-search-query-string
+               notmuch-search-query-string
                nil
-                (notmuch-prettify-subject (notmuch-search-find-subject))
+               (notmuch-prettify-subject (notmuch-search-find-subject))
                t))
 
 (defun notmuch-search-reply-to-thread (&optional prompt-for-sender)
@@ -536,25 +570,15 @@ thread."
        (setq output (append output (notmuch-search-get-tags pos)))))
     output))
 
-(defun notmuch-search-interactive-region ()
-  "Return the bounds of the current interactive region.
-
-This returns (BEG END), where BEG and END are the bounds of the
-region if the region is active, or both `point' otherwise."
-  (if (region-active-p)
-      (list (region-beginning) (region-end))
-    (list (point) (point))))
-
 (defun notmuch-search-interactive-tag-changes (&optional initial-input)
   "Prompt for tag changes for the current thread or region.
 
 Returns (TAG-CHANGES REGION-BEGIN REGION-END)."
-  (let* ((region (notmuch-search-interactive-region))
-        (beg (first region)) (end (second region))
-        (prompt (if (= beg end) "Tag thread" "Tag region")))
-    (cons (notmuch-read-tag-changes
-          (notmuch-search-get-tags-region beg end) prompt initial-input)
-         region)))
+  (pcase-let ((`(,beg ,end) (notmuch-interactive-region)))
+    (list (notmuch-read-tag-changes (notmuch-search-get-tags-region beg end)
+                                   (if (= beg end) "Tag thread" "Tag region")
+                                   initial-input)
+         beg end)))
 
 (defun notmuch-search-tag (tag-changes &optional beg end only-matched)
   "Change tags for the currently selected thread or region.
@@ -562,12 +586,15 @@ Returns (TAG-CHANGES REGION-BEGIN REGION-END)."
 See `notmuch-tag' for information on the format of TAG-CHANGES.
 When called interactively, this uses the region if the region is
 active.  When called directly, BEG and END provide the region.
-If these are nil or not provided, this applies to the thread at
-point.
+If these are nil or not provided, then, if the region is active
+this applied to all threads meeting the region, and if the region
+is inactive this applies to the thread at point.
 
 If ONLY-MATCHED is non-nil, only tag matched messages."
   (interactive (notmuch-search-interactive-tag-changes))
-  (unless (and beg end) (setq beg (point) end (point)))
+  (unless (and beg end)
+    (setq beg (car (notmuch-interactive-region)))
+    (setq end (cadr (notmuch-interactive-region))))
   (let ((search-string (notmuch-search-find-stable-query-region
                        beg end only-matched)))
     (notmuch-tag search-string tag-changes)
@@ -603,7 +630,7 @@ messages will be \"unarchived\" (i.e. the tag changes in
 `notmuch-archive-tags' will be reversed).
 
 This function advances the next thread when finished."
-  (interactive (cons current-prefix-arg (notmuch-search-interactive-region)))
+  (interactive (cons current-prefix-arg (notmuch-interactive-region)))
   (when notmuch-archive-tags
     (notmuch-search-tag
      (notmuch-tag-change-list notmuch-archive-tags unarchive) beg end))
@@ -639,7 +666,7 @@ of the result."
        (goto-char new-point)))))
 
 (defun notmuch-search-process-sentinel (proc msg)
-  "Add a message to let user know when \"notmuch search\" exits"
+  "Add a message to let user know when \"notmuch search\" exits."
   (let ((buffer (process-buffer proc))
        (status (process-status proc))
        (exit-status (process-exit-status proc))
@@ -666,13 +693,20 @@ of the result."
                             (not (string= notmuch-search-target-thread "found")))
                        (set 'never-found-target-thread t)))))
              (when (and never-found-target-thread
-                      notmuch-search-target-line)
-                 (goto-char (point-min))
-                 (forward-line (1- notmuch-search-target-line)))))))))
+                        notmuch-search-target-line)
+               (goto-char (point-min))
+               (forward-line (1- notmuch-search-target-line)))))))))
+
+(define-widget 'notmuch--custom-face-edit 'lazy
+  "Custom face edit with a tag Edit Face"
+  ;; I could not persuage custom-face-edit to respect the :tag
+  ;; property so create a widget specially
+  :tag "Manually specify face"
+  :type 'custom-face-edit)
 
 (defcustom notmuch-search-line-faces
-  '(("unread" 'notmuch-search-unread-face)
-    ("flagged" 'notmuch-search-flagged-face))
+  '(("unread" notmuch-search-unread-face)
+    ("flagged" notmuch-search-flagged-face))
   "Alist of tags to faces for line highlighting in notmuch-search.
 Each element looks like (TAG . FACE).
 A thread with TAG will have FACE applied.
@@ -680,8 +714,8 @@ A thread with TAG will have FACE applied.
 Here is an example of how to color search results based on tags.
  (the following text would be placed in your ~/.emacs file):
 
- (setq notmuch-search-line-faces '((\"unread\" . (:foreground \"green\"))
-                                   (\"deleted\" . (:foreground \"red\"
+ (setq notmuch-search-line-faces \\='((\"unread\" . (:foreground \"green\"))
+                                  (\"deleted\" . (:foreground \"red\"
                                                  :background \"blue\"))))
 
 The FACE must be a face name (a symbol or string), a property
@@ -690,7 +724,9 @@ matching tags are merged, with earlier attributes overriding
 later. A message having both \"deleted\" and \"unread\" tags with
 the above settings would have a green foreground and blue
 background."
-  :type '(alist :key-type (string) :value-type (custom-face-edit))
+  :type '(alist :key-type (string)
+               :value-type (radio (face :tag "Face name")
+                                  (notmuch--custom-face-edit)))
   :group 'notmuch-search
   :group 'notmuch-faces)
 
@@ -723,7 +759,6 @@ non-authors is found, assume that all of the authors match."
           (visible-string formatted-authors)
           (invisible-string "")
           (padding ""))
-
       ;; Truncate the author string to fit the specification.
       (if (> (length formatted-authors)
             (length formatted-sample))
@@ -731,8 +766,8 @@ non-authors is found, assume that all of the authors match."
                                   (length "... "))))
            ;; Truncate the visible string according to the width of
            ;; the display string.
-           (setq visible-string (substring formatted-authors 0 visible-length)
-                 invisible-string (substring formatted-authors visible-length))
+           (setq visible-string (substring formatted-authors 0 visible-length))
+           (setq invisible-string (substring formatted-authors visible-length))
            ;; If possible, truncate the visible string at a natural
            ;; break (comma or pipe), as incremental search doesn't
            ;; match across the visible/invisible border.
@@ -740,8 +775,8 @@ non-authors is found, assume that all of the authors match."
              ;; Second clause is destructive on `visible-string', so
              ;; order is important.
              (setq invisible-string (concat (match-string 3 visible-string)
-                                            invisible-string)
-                   visible-string (concat (match-string 1 visible-string)
+                                            invisible-string))
+             (setq visible-string (concat (match-string 1 visible-string)
                                           (match-string 2 visible-string))))
            ;; `visible-string' may be shorter than the space allowed
            ;; by `format-string'. If so we must insert some padding
@@ -750,28 +785,28 @@ non-authors is found, assume that all of the authors match."
                                          (length visible-string)
                                          (length "..."))
                                       ? ))))
-
       ;; Use different faces to show matching and non-matching authors.
       (if (string-match "\\(.*\\)|\\(.*\\)" visible-string)
          ;; The visible string contains both matching and
          ;; non-matching authors.
-         (setq visible-string (notmuch-search-author-propertize visible-string)
-               ;; The invisible string must contain only non-matching
-               ;; authors, as the visible-string contains both.
-               invisible-string (propertize invisible-string
-                                            'face 'notmuch-search-non-matching-authors))
+         (progn
+           (setq visible-string (notmuch-search-author-propertize visible-string))
+           ;; The invisible string must contain only non-matching
+           ;; authors, as the visible-string contains both.
+           (setq invisible-string (propertize invisible-string
+                                              'face 'notmuch-search-non-matching-authors)))
        ;; The visible string contains only matching authors.
        (setq visible-string (propertize visible-string
-                                        'face 'notmuch-search-matching-authors)
-             ;; The invisible string may contain both matching and
-             ;; non-matching authors.
-             invisible-string (notmuch-search-author-propertize invisible-string)))
-
+                                        'face 'notmuch-search-matching-authors))
+       ;; The invisible string may contain both matching and
+       ;; non-matching authors.
+       (setq invisible-string (notmuch-search-author-propertize invisible-string)))
       ;; If there is any invisible text, add it as a tooltip to the
       ;; visible text.
       (when (not (string= invisible-string ""))
-       (setq visible-string (propertize visible-string 'help-echo (concat "..." invisible-string))))
-
+       (setq visible-string
+             (propertize visible-string
+                         'help-echo (concat "..." invisible-string))))
       ;; Insert the visible and, if present, invisible author strings.
       (insert visible-string)
       (when (not (string= invisible-string ""))
@@ -797,11 +832,9 @@ non-authors is found, assume that all of the authors match."
     (insert (propertize (format format-string
                                (notmuch-sanitize (plist-get result :subject)))
                        'face 'notmuch-search-subject)))
-
    ((string-equal field "authors")
     (notmuch-search-insert-authors
      format-string (notmuch-sanitize (plist-get result :authors))))
-
    ((string-equal field "tags")
     (let ((tags (plist-get result :tags))
          (orig-tags (plist-get result :orig-tags)))
@@ -832,7 +865,7 @@ sets the :orig-tag property."
       (goto-char pos))))
 
 (defun notmuch-search-process-filter (proc string)
-  "Process and filter the output of \"notmuch search\""
+  "Process and filter the output of \"notmuch search\"."
   (let ((results-buf (process-buffer proc))
        (parse-buf (process-get proc 'parse-buf))
        (inhibit-read-only t)
@@ -860,12 +893,14 @@ See `notmuch-tag' for information on the format of TAG-CHANGES."
   (let* ((saved-search
          (let (longest
                (longest-length 0))
-           (loop for tuple in notmuch-saved-searches
-                 if (let ((quoted-query (regexp-quote (notmuch-saved-search-get tuple :query))))
-                      (and (string-match (concat "^" quoted-query) query)
-                           (> (length (match-string 0 query))
-                              longest-length)))
-                 do (setq longest tuple))
+           (cl-loop for tuple in notmuch-saved-searches
+                    if (let ((quoted-query
+                              (regexp-quote
+                               (notmuch-saved-search-get tuple :query))))
+                         (and (string-match (concat "^" quoted-query) query)
+                              (> (length (match-string 0 query))
+                                 longest-length)))
+                    do (setq longest tuple))
            longest))
         (saved-search-name (notmuch-saved-search-get saved-search :name))
         (saved-search-query (notmuch-saved-search-get saved-search :query)))
@@ -874,30 +909,31 @@ See `notmuch-tag' for information on the format of TAG-CHANGES."
           (concat "*notmuch-saved-search-" saved-search-name "*"))
          (saved-search
           (concat "*notmuch-search-"
-                  (replace-regexp-in-string (concat "^" (regexp-quote saved-search-query))
-                                            (concat "[ " saved-search-name " ]")
-                                            query)
+                  (replace-regexp-in-string
+                   (concat "^" (regexp-quote saved-search-query))
+                   (concat "[ " saved-search-name " ]")
+                   query)
                   "*"))
          (t
-          (concat "*notmuch-search-" query "*"))
-         )))
+          (concat "*notmuch-search-" query "*")))))
 
 (defun notmuch-read-query (prompt)
   "Read a notmuch-query from the minibuffer with completion.
 
 PROMPT is the string to prompt with."
-  (lexical-let*
+  (let*
       ((all-tags
-        (mapcar (lambda (tag) (notmuch-escape-boolean-term tag))
-                (process-lines notmuch-command "search" "--output=tags" "*")))
+       (mapcar (lambda (tag) (notmuch-escape-boolean-term tag))
+               (process-lines notmuch-command "search" "--output=tags" "*")))
        (completions
-        (append (list "folder:" "path:" "thread:" "id:" "date:" "from:" "to:"
-                      "subject:" "attachment:")
-                (mapcar (lambda (tag) (concat "tag:" tag)) all-tags)
-                (mapcar (lambda (tag) (concat "is:" tag)) all-tags)
-                (mapcar (lambda (mimetype) (concat "mimetype:" mimetype)) (mailcap-mime-types)))))
+       (append (list "folder:" "path:" "thread:" "id:" "date:" "from:" "to:"
+                     "subject:" "attachment:")
+               (mapcar (lambda (tag) (concat "tag:" tag)) all-tags)
+               (mapcar (lambda (tag) (concat "is:" tag)) all-tags)
+               (mapcar (lambda (mimetype) (concat "mimetype:" mimetype))
+                       (mailcap-mime-types)))))
     (let ((keymap (copy-keymap minibuffer-local-map))
-         (current-query (case major-mode
+         (current-query (cl-case major-mode
                           (notmuch-search-mode (notmuch-search-get-query))
                           (notmuch-show-mode (notmuch-show-get-query))
                           (notmuch-tree-mode (notmuch-tree-get-query))))
@@ -921,11 +957,11 @@ PROMPT is the string to prompt with."
                              'notmuch-search-history current-query nil)))))
 
 (defun notmuch-search-get-query ()
-  "Return the current query in this search buffer"
+  "Return the current query in this search buffer."
   notmuch-search-query-string)
 
-;;;###autoload
 (put 'notmuch-search 'notmuch-doc "Search for messages.")
+;;;###autoload
 (defun notmuch-search (&optional query oldest-first target-thread target-line no-display)
   "Display threads matching QUERY in a notmuch-search buffer.
 
@@ -956,7 +992,11 @@ the configured default sort order."
     (if no-display
        (set-buffer buffer)
       (switch-to-buffer buffer))
-    (notmuch-search-mode)
+    ;; avoid wiping out third party buffer-local variables in the case
+    ;; where we're just refreshing or changing the sort order of an
+    ;; existing search results buffer
+    (unless (eq major-mode 'notmuch-search-mode)
+      (notmuch-search-mode))
     ;; Don't track undo information for this buffer
     (set 'buffer-undo-list t)
     (set 'notmuch-search-query-string query)
@@ -967,14 +1007,13 @@ the configured default sort order."
     (let ((proc (get-buffer-process (current-buffer)))
          (inhibit-read-only t))
       (if proc
-         (error "notmuch search process already running for query `%s'" query)
-       )
+         (error "notmuch search process already running for query `%s'" query))
       (erase-buffer)
       (goto-char (point-min))
       (save-excursion
        (let ((proc (notmuch-start-notmuch
                     "notmuch-search" buffer #'notmuch-search-process-sentinel
-                    "search" "--format=sexp" "--format-version=2"
+                    "search" "--format=sexp" "--format-version=4"
                     (if oldest-first
                         "--sort=oldest-first"
                       "--sort=newest-first")
@@ -1043,8 +1082,16 @@ current search results AND the additional query string provided."
 Runs a new search matching only messages that match both the
 current search results AND that are tagged with the given tag."
   (interactive
-   (list (notmuch-select-tag-with-completion "Filter by tag: ")))
-  (notmuch-search (concat notmuch-search-query-string " and tag:" tag) notmuch-search-oldest-first))
+   (list (notmuch-select-tag-with-completion "Filter by tag: "
+                                            notmuch-search-query-string)))
+  (notmuch-search (concat notmuch-search-query-string " and tag:" tag)
+                 notmuch-search-oldest-first))
+
+(defun notmuch-search-by-tag (tag)
+  "Display threads matching TAG in a notmuch-search buffer."
+  (interactive
+   (list (notmuch-select-tag-with-completion "Notmuch search tag: ")))
+  (notmuch-search (concat "tag:" tag)))
 
 ;;;###autoload
 (defun notmuch ()
@@ -1057,8 +1104,9 @@ current search results AND that are tagged with the given tag."
   (with-current-buffer b
     (memq major-mode '(notmuch-show-mode
                       notmuch-search-mode
+                      notmuch-tree-mode
                       notmuch-hello-mode
-                      message-mode))))
+                      notmuch-message-mode))))
 
 ;;;###autoload
 (defun notmuch-cycle-notmuch-buffers ()
@@ -1067,7 +1115,6 @@ current search results AND that are tagged with the given tag."
 If the current buffer is the only notmuch buffer, bury it. If no
 notmuch buffers exist, run `notmuch'."
   (interactive)
-
   (let (start first)
     ;; If the current buffer is a notmuch buffer, remember it and then
     ;; bury it.
@@ -1076,9 +1123,9 @@ notmuch buffers exist, run `notmuch'."
       (bury-buffer))
 
     ;; Find the first notmuch buffer.
-    (setq first (loop for buffer in (buffer-list)
-                    if (notmuch-interesting-buffer buffer)
-                    return buffer))
+    (setq first (cl-loop for buffer in (buffer-list)
+                        if (notmuch-interesting-buffer buffer)
+                        return buffer))
 
     (if first
        ;; If the first one we found is any other than the starting
@@ -1087,14 +1134,29 @@ notmuch buffers exist, run `notmuch'."
          (switch-to-buffer first))
       (notmuch))))
 
+;;;; Imenu Support
+
+(defun notmuch-search-imenu-prev-index-position-function ()
+  "Move point to previous message in notmuch-search buffer.
+This function is used as a value for
+`imenu-prev-index-position-function'."
+  (notmuch-search-previous-thread))
+
+(defun notmuch-search-imenu-extract-index-name-function ()
+  "Return imenu name for line at point.
+This function is used as a value for
+`imenu-extract-index-name-function'.  Point should be at the
+beginning of the line."
+  (let ((subject (notmuch-search-find-subject))
+       (author (notmuch-search-find-authors)))
+    (format "%s (%s)" subject author)))
+
 (setq mail-user-agent 'notmuch-user-agent)
 
 (provide 'notmuch)
 
 ;; After provide to avoid loops if notmuch was require'd via notmuch-init-file.
 (if init-file-user ; don't load init file if the -q option was used.
-    (let ((init-file (locate-file notmuch-init-file '("/")
-                                 (get-load-suffixes))))
-      (if init-file (load init-file nil t t))))
+    (load notmuch-init-file t t nil t))
 
 ;;; notmuch.el ends here