config

Personal configuration.
git clone git://code.dwrz.net/config
Log | Files | Refs

notmuch.el (47533B)


      1 ;;; notmuch.el --- run notmuch within emacs  -*- lexical-binding: t -*-
      2 ;;
      3 ;; Copyright © Carl Worth
      4 ;;
      5 ;; This file is part of Notmuch.
      6 ;;
      7 ;; Notmuch is free software: you can redistribute it and/or modify it
      8 ;; under the terms of the GNU General Public License as published by
      9 ;; the Free Software Foundation, either version 3 of the License, or
     10 ;; (at your option) any later version.
     11 ;;
     12 ;; Notmuch is distributed in the hope that it will be useful, but
     13 ;; WITHOUT ANY WARRANTY; without even the implied warranty of
     14 ;; MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU
     15 ;; General Public License for more details.
     16 ;;
     17 ;; You should have received a copy of the GNU General Public License
     18 ;; along with Notmuch.  If not, see <https://www.gnu.org/licenses/>.
     19 ;;
     20 ;; Authors: Carl Worth <cworth@cworth.org>
     21 ;; Homepage: https://notmuchmail.org
     22 
     23 ;;; Commentary:
     24 
     25 ;; This is an emacs-based interface to the notmuch mail system.
     26 ;;
     27 ;; You will first need to have the notmuch program installed and have a
     28 ;; notmuch database built in order to use this. See
     29 ;; https://notmuchmail.org for details.
     30 ;;
     31 ;; To install this software, copy it to a directory that is on the
     32 ;; `load-path' variable within emacs (a good candidate is
     33 ;; /usr/local/share/emacs/site-lisp). If you are viewing this from the
     34 ;; notmuch source distribution then you can simply run:
     35 ;;
     36 ;;	sudo make install-emacs
     37 ;;
     38 ;; to install it.
     39 ;;
     40 ;; Then, to actually run it, add:
     41 ;;
     42 ;;	(autoload 'notmuch "notmuch" "Notmuch mail" t)
     43 ;;
     44 ;; to your ~/.emacs file, and then run "M-x notmuch" from within emacs,
     45 ;; or run:
     46 ;;
     47 ;;	emacs -f notmuch
     48 ;;
     49 ;; Have fun, and let us know if you have any comment, questions, or
     50 ;; kudos: Notmuch list <notmuch@notmuchmail.org> (subscription is not
     51 ;; required, but is available from https://notmuchmail.org).
     52 ;;
     53 ;; Note for MELPA users (and others tracking the development version
     54 ;; of notmuch-emacs):
     55 ;;
     56 ;; This emacs package needs a fairly closely matched version of the
     57 ;; notmuch program. If you use the MELPA version of notmuch.el (as
     58 ;; opposed to MELPA stable), you should be prepared to track the
     59 ;; master development branch (i.e. build from git) for the notmuch
     60 ;; program as well. Upgrading notmuch-emacs too far beyond the notmuch
     61 ;; program can CAUSE YOUR EMAIL TO STOP WORKING.
     62 ;;
     63 ;; TL;DR: notmuch-emacs from MELPA and notmuch from distro packages is
     64 ;; NOT SUPPORTED.
     65 
     66 ;;; Code:
     67 
     68 (require 'mm-view)
     69 (require 'message)
     70 
     71 (require 'hl-line)
     72 
     73 (require 'notmuch-lib)
     74 (require 'notmuch-tag)
     75 (require 'notmuch-show)
     76 (require 'notmuch-tree)
     77 (require 'notmuch-mua)
     78 (require 'notmuch-hello)
     79 (require 'notmuch-maildir-fcc)
     80 (require 'notmuch-message)
     81 (require 'notmuch-parser)
     82 
     83 ;;; Options
     84 
     85 (defcustom notmuch-search-result-format
     86   `(("date" . "%12s ")
     87     ("count" . "%-7s ")
     88     ("authors" . "%-20s ")
     89     ("subject" . "%s ")
     90     ("tags" . "(%s)"))
     91   "Search result formatting.
     92 
     93 List of pairs of (field . format-string).  Supported field
     94 strings are: \"date\", \"count\", \"authors\", \"subject\",
     95 \"tags\".  It is also supported to pass a function in place of a
     96 field name. In this case the function is passed the thread
     97 object (plist) and format string.
     98 
     99 Line breaks are permitted in format strings (though this is
    100 currently experimental).  Note that a line break at the end of an
    101 \"authors\" field will get elided if the authors list is long;
    102 place it instead at the beginning of the following field.  To
    103 enter a line break when setting this variable with setq, use \\n.
    104 To enter a line break in customize, press \\[quoted-insert] C-j."
    105   :type '(alist
    106 	  :key-type
    107 	  (choice
    108 	   (const :tag "Date" "date")
    109 	   (const :tag "Count" "count")
    110 	   (const :tag "Authors" "authors")
    111 	   (const :tag "Subject" "subject")
    112 	   (const :tag "Tags" "tags")
    113 	   function)
    114 	  :value-type (string :tag "Format"))
    115   :group 'notmuch-search)
    116 
    117 ;; The name of this variable `notmuch-init-file' is consistent with the
    118 ;; convention used in e.g. emacs and gnus. The value, `notmuch-config[.el[c]]'
    119 ;; is consistent with notmuch cli configuration file `~/.notmuch-config'.
    120 (defcustom notmuch-init-file (locate-user-emacs-file "notmuch-config")
    121   "Your Notmuch Emacs-Lisp configuration file name.
    122 If a file with one of the suffixes defined by `get-load-suffixes' exists,
    123 it will be read instead.
    124 This file is read once when notmuch is loaded; the notmuch hooks added
    125 there will be called at other points of notmuch execution."
    126   :type 'file
    127   :group 'notmuch)
    128 
    129 (defcustom notmuch-search-hook '(notmuch-hl-line-mode)
    130   "List of functions to call when notmuch displays the search results."
    131   :type 'hook
    132   :options '(notmuch-hl-line-mode)
    133   :group 'notmuch-search
    134   :group 'notmuch-hooks)
    135 
    136 ;;; Mime Utilities
    137 
    138 (defun notmuch-foreach-mime-part (function mm-handle)
    139   (cond ((stringp (car mm-handle))
    140 	 (dolist (part (cdr mm-handle))
    141 	   (notmuch-foreach-mime-part function part)))
    142 	((bufferp (car mm-handle))
    143 	 (funcall function mm-handle))
    144 	(t (dolist (part mm-handle)
    145 	     (notmuch-foreach-mime-part function part)))))
    146 
    147 (defun notmuch-count-attachments (mm-handle)
    148   (let ((count 0))
    149     (notmuch-foreach-mime-part
    150      (lambda (p)
    151        (let ((disposition (mm-handle-disposition p)))
    152 	 (and (listp disposition)
    153 	      (or (equal (car disposition) "attachment")
    154 		  (and (equal (car disposition) "inline")
    155 		       (assq 'filename disposition)))
    156 	      (cl-incf count))))
    157      mm-handle)
    158     count))
    159 
    160 (defun notmuch-save-attachments (mm-handle &optional queryp)
    161   (notmuch-foreach-mime-part
    162    (lambda (p)
    163      (let ((disposition (mm-handle-disposition p)))
    164        (and (listp disposition)
    165 	    (or (equal (car disposition) "attachment")
    166 		(and (equal (car disposition) "inline")
    167 		     (assq 'filename disposition)))
    168 	    (or (not queryp)
    169 		(y-or-n-p
    170 		 (concat "Save '" (cdr (assq 'filename disposition)) "' ")))
    171 	    (mm-save-part p))))
    172    mm-handle))
    173 
    174 ;;; Keymap
    175 
    176 (defvar notmuch-search-mode-map
    177   (let ((map (make-sparse-keymap)))
    178     (set-keymap-parent map notmuch-common-keymap)
    179     (define-key map "x" 'notmuch-bury-or-kill-this-buffer)
    180     (define-key map (kbd "DEL") 'notmuch-search-scroll-down)
    181     (define-key map "b" 'notmuch-search-scroll-down)
    182     (define-key map " " 'notmuch-search-scroll-up)
    183     (define-key map "<" 'notmuch-search-first-thread)
    184     (define-key map ">" 'notmuch-search-last-thread)
    185     (define-key map "p" 'notmuch-search-previous-thread)
    186     (define-key map "n" 'notmuch-search-next-thread)
    187     (define-key map "r" 'notmuch-search-reply-to-thread-sender)
    188     (define-key map "R" 'notmuch-search-reply-to-thread)
    189     (define-key map "o" 'notmuch-search-toggle-order)
    190     (define-key map "i" 'notmuch-search-toggle-hide-excluded)
    191     (define-key map "c" 'notmuch-search-stash-map)
    192     (define-key map "t" 'notmuch-search-filter-by-tag)
    193     (define-key map "l" 'notmuch-search-filter)
    194     (define-key map "E" 'notmuch-search-edit-search)
    195     (define-key map [mouse-1] 'notmuch-search-show-thread)
    196     (define-key map "k" 'notmuch-tag-jump)
    197     (define-key map "*" 'notmuch-search-tag-all)
    198     (define-key map "a" 'notmuch-search-archive-thread)
    199     (define-key map "-" 'notmuch-search-remove-tag)
    200     (define-key map "+" 'notmuch-search-add-tag)
    201     (define-key map (kbd "RET") 'notmuch-search-show-thread)
    202     (define-key map (kbd "M-RET") 'notmuch-tree-from-search-thread)
    203     (define-key map "Z" 'notmuch-tree-from-search-current-query)
    204     (define-key map "U" 'notmuch-unthreaded-from-search-current-query)
    205     map)
    206   "Keymap for \"notmuch search\" buffers.")
    207 
    208 ;;; Internal Variables
    209 
    210 (defvar notmuch-query-history nil
    211   "Variable to store minibuffer history for notmuch queries.")
    212 
    213 (defvar-local notmuch-search-query-string nil)
    214 (defvar-local notmuch-search-target-thread nil)
    215 (defvar-local notmuch-search-target-line nil)
    216 
    217 ;;; Stashing
    218 
    219 (defvar notmuch-search-stash-map
    220   (let ((map (make-sparse-keymap)))
    221     (define-key map "i" 'notmuch-search-stash-thread-id)
    222     (define-key map "q" 'notmuch-stash-query)
    223     (define-key map "?" 'notmuch-subkeymap-help)
    224     map)
    225   "Submap for stash commands.")
    226 (fset 'notmuch-search-stash-map notmuch-search-stash-map)
    227 
    228 (defun notmuch-search-stash-thread-id ()
    229   "Copy thread ID of current thread to kill-ring."
    230   (interactive)
    231   (notmuch-common-do-stash (notmuch-search-find-thread-id)))
    232 
    233 (defun notmuch-stash-query ()
    234   "Copy current query to kill-ring."
    235   (interactive)
    236   (notmuch-common-do-stash notmuch-search-query-string))
    237 
    238 ;;; Movement
    239 
    240 (defun notmuch-search-scroll-up ()
    241   "Move forward through search results by one window's worth."
    242   (interactive)
    243   (condition-case nil
    244       (scroll-up nil)
    245     ((end-of-buffer) (notmuch-search-last-thread))))
    246 
    247 (defun notmuch-search-scroll-down ()
    248   "Move backward through the search results by one window's worth."
    249   (interactive)
    250   ;; I don't know why scroll-down doesn't signal beginning-of-buffer
    251   ;; the way that scroll-up signals end-of-buffer, but c'est la vie.
    252   ;;
    253   ;; So instead of trapping a signal we instead check whether the
    254   ;; window begins on the first line of the buffer and if so, move
    255   ;; directly to that position. (We have to count lines since the
    256   ;; window-start position is not the same as point-min due to the
    257   ;; invisible thread-ID characters on the first line.
    258   (if (equal (count-lines (point-min) (window-start)) 0)
    259       (goto-char (point-min))
    260     (scroll-down nil)))
    261 
    262 (defun notmuch-search-next-thread ()
    263   "Select the next thread in the search results."
    264   (interactive)
    265   (when (notmuch-search-get-result)
    266     (goto-char (notmuch-search-result-end))))
    267 
    268 (defun notmuch-search-previous-thread ()
    269   "Select the previous thread in the search results."
    270   (interactive)
    271   (if (notmuch-search-get-result)
    272       (unless (bobp)
    273 	(goto-char (notmuch-search-result-beginning (- (point) 1))))
    274     ;; We must be past the end; jump to the last result
    275     (notmuch-search-last-thread)))
    276 
    277 (defun notmuch-search-last-thread ()
    278   "Select the last thread in the search results."
    279   (interactive)
    280   (goto-char (point-max))
    281   (forward-line -2)
    282   (let ((beg (notmuch-search-result-beginning)))
    283     (when beg
    284       (goto-char beg))))
    285 
    286 (defun notmuch-search-first-thread ()
    287   "Select the first thread in the search results."
    288   (interactive)
    289   (goto-char (point-min)))
    290 
    291 ;;; Faces
    292 
    293 (defface notmuch-message-summary-face
    294   `((((class color) (background light))
    295      ,@(and (>= emacs-major-version 27) '(:extend t))
    296      :background "#f0f0f0")
    297     (((class color) (background dark))
    298      ,@(and (>= emacs-major-version 27) '(:extend t))
    299      :background "#303030"))
    300   "Face for the single-line message summary in notmuch-show-mode."
    301   :group 'notmuch-show
    302   :group 'notmuch-faces)
    303 
    304 (defface notmuch-search-date
    305   '((t :inherit default))
    306   "Face used in search mode for dates."
    307   :group 'notmuch-search
    308   :group 'notmuch-faces)
    309 
    310 (defface notmuch-search-count
    311   '((t :inherit default))
    312   "Face used in search mode for the count matching the query."
    313   :group 'notmuch-search
    314   :group 'notmuch-faces)
    315 
    316 (defface notmuch-search-subject
    317   '((t :inherit default))
    318   "Face used in search mode for subjects."
    319   :group 'notmuch-search
    320   :group 'notmuch-faces)
    321 
    322 (defface notmuch-search-matching-authors
    323   '((t :inherit default))
    324   "Face used in search mode for authors matching the query."
    325   :group 'notmuch-search
    326   :group 'notmuch-faces)
    327 
    328 (defface notmuch-search-non-matching-authors
    329   '((((class color)
    330       (background dark))
    331      (:foreground "grey30"))
    332     (((class color)
    333       (background light))
    334      (:foreground "grey60"))
    335     (t
    336      (:italic t)))
    337   "Face used in search mode for authors not matching the query."
    338   :group 'notmuch-search
    339   :group 'notmuch-faces)
    340 
    341 (defface notmuch-tag-face
    342   '((((class color)
    343       (background dark))
    344      (:foreground "OliveDrab1"))
    345     (((class color)
    346       (background light))
    347      (:foreground "navy blue" :bold t))
    348     (t
    349      (:bold t)))
    350   "Face used in search mode face for tags."
    351   :group 'notmuch-search
    352   :group 'notmuch-faces)
    353 
    354 (defface notmuch-search-flagged-face
    355   '((((class color)
    356       (background dark))
    357      (:foreground "LightBlue1"))
    358     (((class color)
    359       (background light))
    360      (:foreground "blue")))
    361   "Face used in search mode face for flagged threads.
    362 
    363 This face is the default value for the \"flagged\" tag in
    364 `notmuch-search-line-faces'."
    365   :group 'notmuch-search
    366   :group 'notmuch-faces)
    367 
    368 (defface notmuch-search-unread-face
    369   '((t
    370      (:weight bold)))
    371   "Face used in search mode for unread threads.
    372 
    373 This face is the default value for the \"unread\" tag in
    374 `notmuch-search-line-faces'."
    375   :group 'notmuch-search
    376   :group 'notmuch-faces)
    377 
    378 ;;; Mode
    379 
    380 (define-derived-mode notmuch-search-mode fundamental-mode "notmuch-search"
    381   "Major mode displaying results of a notmuch search.
    382 
    383 This buffer contains the results of a \"notmuch search\" of your
    384 email archives. Each line in the buffer represents a single
    385 thread giving a summary of the thread (a relative date, the
    386 number of matched messages and total messages in the thread,
    387 participants in the thread, a representative subject line, and
    388 any tags).
    389 
    390 Pressing \\[notmuch-search-show-thread] on any line displays that
    391 thread. The '\\[notmuch-search-add-tag]' and
    392 '\\[notmuch-search-remove-tag]' keys can be used to add or remove
    393 tags from a thread. The '\\[notmuch-search-archive-thread]' key
    394 is a convenience for archiving a thread (applying changes in
    395 `notmuch-archive-tags'). The '\\[notmuch-search-tag-all]' key can
    396 be used to add and/or remove tags from all messages (as opposed
    397 to threads) that match the current query.  Use with caution, as
    398 this will also tag matching messages that arrived *after*
    399 constructing the buffer.
    400 
    401 Other useful commands are '\\[notmuch-search-filter]' for
    402 filtering the current search based on an additional query string,
    403 '\\[notmuch-search-filter-by-tag]' for filtering to include only
    404 messages with a given tag, and '\\[notmuch-search]' to execute a
    405 new, global search.
    406 
    407 Complete list of currently available key bindings:
    408 
    409 \\{notmuch-search-mode-map}"
    410   (setq notmuch-buffer-refresh-function #'notmuch-search-refresh-view)
    411   (setq-local scroll-preserve-screen-position t)
    412   (add-to-invisibility-spec (cons 'ellipsis t))
    413   (setq truncate-lines t)
    414   (setq buffer-read-only t)
    415   (setq imenu-prev-index-position-function
    416 	#'notmuch-search-imenu-prev-index-position-function)
    417   (setq imenu-extract-index-name-function
    418 	#'notmuch-search-imenu-extract-index-name-function))
    419 
    420 ;;; Search Results
    421 
    422 (defun notmuch-search-get-result (&optional pos)
    423   "Return the result object for the thread at POS (or point).
    424 
    425 If there is no thread at POS (or point), returns nil."
    426   (get-text-property (or pos (point)) 'notmuch-search-result))
    427 
    428 (defun notmuch-search-result-beginning (&optional pos)
    429   "Return the point at the beginning of the thread at POS (or point).
    430 
    431 If there is no thread at POS (or point), returns nil."
    432   (and (notmuch-search-get-result pos)
    433        ;; We pass 1+point because previous-single-property-change starts
    434        ;; searching one before the position we give it.
    435        (previous-single-property-change (1+ (or pos (point)))
    436 					'notmuch-search-result nil
    437 					(point-min))))
    438 
    439 (defun notmuch-search-result-end (&optional pos)
    440   "Return the point at the end of the thread at POS (or point).
    441 
    442 The returned point will be just after the newline character that
    443 ends the result line.  If there is no thread at POS (or point),
    444 returns nil."
    445   (and (notmuch-search-get-result pos)
    446        (next-single-property-change (or pos (point))
    447 				    'notmuch-search-result nil
    448 				    (point-max))))
    449 
    450 (defun notmuch-search-foreach-result (beg end fn)
    451   "Invoke FN for each result between BEG and END.
    452 
    453 FN should take one argument.  It will be applied to the character
    454 position of the beginning of each result that overlaps the region
    455 between points BEG and END.  As a special case, if (= BEG END),
    456 FN will be applied to the result containing point BEG."
    457   (let ((pos (notmuch-search-result-beginning beg))
    458 	;; End must be a marker in case fn changes the
    459 	;; text.
    460 	(end (copy-marker end))
    461 	;; Make sure we examine at least one result, even if
    462 	;; (= beg end).
    463 	(first t))
    464     ;; We have to be careful if the region extends beyond the results.
    465     ;; In this case, pos could be null or there could be no result at
    466     ;; pos.
    467     (while (and pos (or (< pos end) first))
    468       (when (notmuch-search-get-result pos)
    469 	(funcall fn pos))
    470       (setq pos (notmuch-search-result-end pos))
    471       (setq first nil))))
    472 ;; Unindent the function argument of notmuch-search-foreach-result so
    473 ;; the indentation of callers doesn't get out of hand.
    474 (put 'notmuch-search-foreach-result 'lisp-indent-function 2)
    475 
    476 (defun notmuch-search-properties-in-region (property beg end)
    477   (let (output)
    478     (notmuch-search-foreach-result beg end
    479       (lambda (pos)
    480 	(push (plist-get (notmuch-search-get-result pos) property) output)))
    481     output))
    482 
    483 (defun notmuch-search-find-thread-id (&optional bare)
    484   "Return the thread for the current thread.
    485 
    486 If BARE is set then do not prefix with \"thread:\"."
    487   (let ((thread (plist-get (notmuch-search-get-result) :thread)))
    488     (when thread
    489       (concat (and (not bare) "thread:") thread))))
    490 
    491 (defun notmuch-search-find-stable-query ()
    492   "Return the stable queries for the current thread.
    493 
    494 Return a list (MATCHED-QUERY UNMATCHED-QUERY) for the
    495 matched and unmatched messages in the current thread."
    496   (plist-get (notmuch-search-get-result) :query))
    497 
    498 (defun notmuch-search-find-stable-query-region (beg end &optional only-matched)
    499   "Return the stable query for the current region.
    500 
    501 If ONLY-MATCHED is non-nil, include only matched messages.  If it
    502 is nil, include both matched and unmatched messages. If there are
    503 no messages in the region then return nil."
    504   (let ((query-list nil) (all (not only-matched)))
    505     (dolist (queries (notmuch-search-properties-in-region :query beg end))
    506       (when (car queries)
    507 	(push (car queries) query-list))
    508       (when (and all (cadr queries))
    509 	(push (cadr queries) query-list)))
    510     (and query-list
    511 	 (concat "(" (mapconcat 'identity query-list ") or (") ")"))))
    512 
    513 (defun notmuch-search-find-authors ()
    514   "Return the authors for the current thread."
    515   (plist-get (notmuch-search-get-result) :authors))
    516 
    517 (defun notmuch-search-find-authors-region (beg end)
    518   "Return a list of authors for the current region."
    519   (notmuch-search-properties-in-region :authors beg end))
    520 
    521 (defun notmuch-search-find-subject ()
    522   "Return the subject for the current thread."
    523   (plist-get (notmuch-search-get-result) :subject))
    524 
    525 (defun notmuch-search-find-subject-region (beg end)
    526   "Return a list of authors for the current region."
    527   (notmuch-search-properties-in-region :subject beg end))
    528 
    529 (defun notmuch-search-show-thread (&optional elide-toggle)
    530   "Display the currently selected thread.
    531 
    532 With a prefix argument, invert the default value of
    533 `notmuch-show-only-matching-messages' when displaying the
    534 thread.
    535 
    536 Return non-nil on success."
    537   (interactive "P")
    538   (let ((thread-id (notmuch-search-find-thread-id)))
    539     (if thread-id
    540 	(notmuch-show thread-id
    541 		      elide-toggle
    542 		      (current-buffer)
    543 		      notmuch-search-query-string
    544 		      ;; Name the buffer based on the subject.
    545 		      (format "*%s*" (truncate-string-to-width
    546 				      (notmuch-search-find-subject)
    547 				      30 nil nil t)))
    548       (message "End of search results.")
    549       nil)))
    550 
    551 (defun notmuch-tree-from-search-current-query ()
    552   "Tree view of current query."
    553   (interactive)
    554   (notmuch-tree notmuch-search-query-string
    555 		nil nil nil nil nil nil
    556 		notmuch-search-oldest-first
    557 		notmuch-search-hide-excluded))
    558 
    559 (defun notmuch-unthreaded-from-search-current-query ()
    560   "Unthreaded view of current query."
    561   (interactive)
    562   (notmuch-unthreaded notmuch-search-query-string
    563 		      nil nil nil nil
    564 		      notmuch-search-oldest-first
    565 		      notmuch-search-hide-excluded))
    566 
    567 (defun notmuch-tree-from-search-thread ()
    568   "Show the selected thread with notmuch-tree."
    569   (interactive)
    570   (notmuch-tree (notmuch-search-find-thread-id)
    571 		notmuch-search-query-string
    572 		nil
    573 		(notmuch-prettify-subject (notmuch-search-find-subject))
    574 		t nil (current-buffer)
    575 		notmuch-search-oldest-first
    576 		notmuch-search-hide-excluded))
    577 
    578 (defun notmuch-search-reply-to-thread (&optional prompt-for-sender)
    579   "Begin composing a reply-all to the entire current thread in a new buffer."
    580   (interactive "P")
    581   (notmuch-mua-new-reply (notmuch-search-find-thread-id)
    582 			 prompt-for-sender t))
    583 
    584 (defun notmuch-search-reply-to-thread-sender (&optional prompt-for-sender)
    585   "Begin composing a reply to the entire current thread in a new buffer."
    586   (interactive "P")
    587   (notmuch-mua-new-reply (notmuch-search-find-thread-id)
    588 			 prompt-for-sender nil))
    589 
    590 ;;; Tags
    591 
    592 (defun notmuch-search-set-tags (tags &optional pos)
    593   (notmuch-search-update-result
    594    (plist-put (notmuch-search-get-result pos) :tags tags)
    595    pos))
    596 
    597 (defun notmuch-search-get-tags (&optional pos)
    598   (plist-get (notmuch-search-get-result pos) :tags))
    599 
    600 (defun notmuch-search-get-tags-region (beg end)
    601   (let (output)
    602     (notmuch-search-foreach-result beg end
    603       (lambda (pos)
    604 	(setq output (append output (notmuch-search-get-tags pos)))))
    605     (delete-dups output)))
    606 
    607 (defun notmuch-search-interactive-tag-changes (&optional initial-input)
    608   "Prompt for tag changes for the current thread or region.
    609 
    610 Return (TAG-CHANGES REGION-BEGIN REGION-END)."
    611   (pcase-let ((`(,beg ,end) (notmuch-interactive-region)))
    612     (list (notmuch-read-tag-changes (notmuch-search-get-tags-region beg end)
    613 				    (if (= beg end) "Tag thread" "Tag region")
    614 				    initial-input)
    615 	  beg end)))
    616 
    617 (defun notmuch-search-tag (tag-changes &optional beg end only-matched)
    618   "Change tags for the currently selected thread or region.
    619 
    620 See `notmuch-tag' for information on the format of TAG-CHANGES.
    621 When called interactively, this uses the region if the region is
    622 active.  When called directly, BEG and END provide the region.
    623 If these are nil or not provided, then, if the region is active
    624 this applied to all threads meeting the region, and if the region
    625 is inactive this applies to the thread at point.
    626 
    627 If ONLY-MATCHED is non-nil, only tag matched messages."
    628   (interactive (notmuch-search-interactive-tag-changes))
    629   (unless (and beg end)
    630     (setq beg (car (notmuch-interactive-region)))
    631     (setq end (cadr (notmuch-interactive-region))))
    632   (let ((search-string (notmuch-search-find-stable-query-region
    633 			beg end only-matched)))
    634     (notmuch-tag search-string tag-changes)
    635     (notmuch-search-foreach-result beg end
    636       (lambda (pos)
    637 	(notmuch-search-set-tags
    638 	 (notmuch-update-tags (notmuch-search-get-tags pos) tag-changes)
    639 	 pos)))))
    640 
    641 (defun notmuch-search-add-tag (tag-changes &optional beg end)
    642   "Change tags for the current thread or region (defaulting to add).
    643 
    644 Same as `notmuch-search-tag' but sets initial input to '+'."
    645   (interactive (notmuch-search-interactive-tag-changes "+"))
    646   (notmuch-search-tag tag-changes beg end))
    647 
    648 (defun notmuch-search-remove-tag (tag-changes &optional beg end)
    649   "Change tags for the current thread or region (defaulting to remove).
    650 
    651 Same as `notmuch-search-tag' but sets initial input to '-'."
    652   (interactive (notmuch-search-interactive-tag-changes "-"))
    653   (notmuch-search-tag tag-changes beg end))
    654 
    655 (put 'notmuch-search-archive-thread 'notmuch-prefix-doc
    656      "Un-archive the currently selected thread.")
    657 (defun notmuch-search-archive-thread (&optional unarchive beg end)
    658   "Archive the currently selected thread or region.
    659 
    660 Archive each message in the currently selected thread by applying
    661 the tag changes in `notmuch-archive-tags' to each (remove the
    662 \"inbox\" tag by default). If a prefix argument is given, the
    663 messages will be \"unarchived\" (i.e. the tag changes in
    664 `notmuch-archive-tags' will be reversed).
    665 
    666 This function advances the next thread when finished."
    667   (interactive (cons current-prefix-arg (notmuch-interactive-region)))
    668   (when notmuch-archive-tags
    669     (notmuch-search-tag
    670      (notmuch-tag-change-list notmuch-archive-tags unarchive) beg end))
    671   (when (eq beg end)
    672     (notmuch-search-next-thread)))
    673 
    674 ;;; Search Results
    675 
    676 (defun notmuch-search-update-result (result &optional pos)
    677   "Replace the result object of the thread at POS (or point) by
    678 RESULT and redraw it.
    679 
    680 This will keep point in a reasonable location.  However, if there
    681 are enclosing save-excursions and the saved point is in the
    682 result being updated, the point will be restored to the beginning
    683 of the result."
    684   (let ((start (notmuch-search-result-beginning pos))
    685 	(end (notmuch-search-result-end pos))
    686 	(init-point (point))
    687 	(inhibit-read-only t))
    688     ;; Delete the current thread
    689     (delete-region start end)
    690     ;; Insert the updated thread
    691     (notmuch-search-show-result result start)
    692     ;; If point was inside the old result, make an educated guess
    693     ;; about where to place it now.  Unfortunately, this won't work
    694     ;; with save-excursion (or any other markers that would be nice to
    695     ;; preserve, such as the window start), but there's nothing we can
    696     ;; do about that without a way to retrieve markers in a region.
    697     (when (and (>= init-point start) (<= init-point end))
    698       (let* ((new-end (notmuch-search-result-end start))
    699 	     (new-point (if (= init-point end)
    700 			    new-end
    701 			  (min init-point (- new-end 1)))))
    702 	(goto-char new-point)))))
    703 
    704 (defun notmuch-search-process-sentinel (proc _msg)
    705   "Add a message to let user know when \"notmuch search\" exits."
    706   (let ((buffer (process-buffer proc))
    707 	(status (process-status proc))
    708 	(exit-status (process-exit-status proc))
    709 	(never-found-target-thread nil))
    710     (when (memq status '(exit signal))
    711       (catch 'return
    712 	(kill-buffer (process-get proc 'parse-buf))
    713 	(when (buffer-live-p buffer)
    714 	  (with-current-buffer buffer
    715 	    (save-excursion
    716 	      (let ((inhibit-read-only t)
    717 		    (atbob (bobp)))
    718 		(goto-char (point-max))
    719 		(when (eq status 'signal)
    720 		  (insert "Incomplete search results (search process was killed).\n"))
    721 		(when (eq status 'exit)
    722 		  (insert "End of search results.\n")
    723 		  ;; For version mismatch, there's no point in
    724 		  ;; showing the search buffer
    725 		  (when (or (= exit-status 20) (= exit-status 21))
    726 		    (kill-buffer)
    727 		    (throw 'return nil))
    728 		  (when (and atbob
    729 			     (not (string= notmuch-search-target-thread "found")))
    730 		    (setq never-found-target-thread t)))))
    731 	    (when (and never-found-target-thread
    732 		       notmuch-search-target-line)
    733 	      (goto-char (point-min))
    734 	      (forward-line (1- notmuch-search-target-line)))))))))
    735 
    736 (define-widget 'notmuch--custom-face-edit 'lazy
    737   "Custom face edit with a tag Edit Face"
    738   ;; I could not persuage custom-face-edit to respect the :tag
    739   ;; property so create a widget specially
    740   :tag "Manually specify face"
    741   :type 'custom-face-edit)
    742 
    743 (defcustom notmuch-search-line-faces
    744   '(("unread" . notmuch-search-unread-face)
    745     ("flagged" . notmuch-search-flagged-face))
    746   "Alist of tags to faces for line highlighting in notmuch-search.
    747 Each element looks like (TAG . FACE).
    748 A thread with TAG will have FACE applied.
    749 
    750 Here is an example of how to color search results based on tags.
    751  (the following text would be placed in your ~/.emacs file):
    752 
    753  (setq notmuch-search-line-faces \\='((\"unread\" . (:foreground \"green\"))
    754 				   (\"deleted\" . (:foreground \"red\"
    755 						  :background \"blue\"))))
    756 
    757 The FACE must be a face name (a symbol or string), a property
    758 list of face attributes, or a list of these.  The faces for
    759 matching tags are merged, with earlier attributes overriding
    760 later. A message having both \"deleted\" and \"unread\" tags with
    761 the above settings would have a green foreground and blue
    762 background."
    763   :type '(alist :key-type (string)
    764 		:value-type (radio (face :tag "Face name")
    765 				   (notmuch--custom-face-edit)))
    766   :group 'notmuch-search
    767   :group 'notmuch-faces)
    768 
    769 (defun notmuch-search-color-line (start end line-tag-list)
    770   "Colorize lines in `notmuch-show' based on tags."
    771   ;; Reverse the list so earlier entries take precedence
    772   (dolist (elem (reverse notmuch-search-line-faces))
    773     (let ((tag (car elem))
    774 	  (face (cdr elem)))
    775       (when (member tag line-tag-list)
    776 	(notmuch-apply-face nil face nil start end)))))
    777 
    778 (defun notmuch-search-author-propertize (authors)
    779   "Split `authors' into matching and non-matching authors and
    780 propertize appropriately. If no boundary between authors and
    781 non-authors is found, assume that all of the authors match."
    782   (if (string-match "\\(.*\\)|\\(.*\\)" authors)
    783       (concat (propertize (concat (match-string 1 authors) ",")
    784 			  'face 'notmuch-search-matching-authors)
    785 	      (propertize (match-string 2 authors)
    786 			  'face 'notmuch-search-non-matching-authors))
    787     (propertize authors 'face 'notmuch-search-matching-authors)))
    788 
    789 (defun notmuch-search-insert-authors (format-string authors)
    790   ;; Save the match data to avoid interfering with
    791   ;; `notmuch-search-process-filter'.
    792   (save-match-data
    793     (let* ((formatted-authors (format format-string authors))
    794 	   (formatted-sample (format format-string ""))
    795 	   (visible-string formatted-authors)
    796 	   (invisible-string "")
    797 	   (padding ""))
    798       ;; Truncate the author string to fit the specification.
    799       (when (> (length formatted-authors)
    800 	       (length formatted-sample))
    801 	(let ((visible-length (- (length formatted-sample)
    802 				 (length "... "))))
    803 	  ;; Truncate the visible string according to the width of
    804 	  ;; the display string.
    805 	  (setq visible-string (substring formatted-authors 0 visible-length))
    806 	  (setq invisible-string (substring formatted-authors visible-length))
    807 	  ;; If possible, truncate the visible string at a natural
    808 	  ;; break (comma or pipe), as incremental search doesn't
    809 	  ;; match across the visible/invisible border.
    810 	  (when (string-match "\\(.*\\)\\([,|] \\)\\([^,|]*\\)" visible-string)
    811 	    ;; Second clause is destructive on `visible-string', so
    812 	    ;; order is important.
    813 	    (setq invisible-string (concat (match-string 3 visible-string)
    814 					   invisible-string))
    815 	    (setq visible-string (concat (match-string 1 visible-string)
    816 					 (match-string 2 visible-string))))
    817 	  ;; `visible-string' may be shorter than the space allowed
    818 	  ;; by `format-string'. If so we must insert some padding
    819 	  ;; after `invisible-string'.
    820 	  (setq padding (make-string (- (length formatted-sample)
    821 					(length visible-string)
    822 					(length "..."))
    823 				     ? ))))
    824       ;; Use different faces to show matching and non-matching authors.
    825       (if (string-match "\\(.*\\)|\\(.*\\)" visible-string)
    826 	  ;; The visible string contains both matching and
    827 	  ;; non-matching authors.
    828 	  (progn
    829 	    (setq visible-string (notmuch-search-author-propertize visible-string))
    830 	    ;; The invisible string must contain only non-matching
    831 	    ;; authors, as the visible-string contains both.
    832 	    (setq invisible-string (propertize invisible-string
    833 					       'face 'notmuch-search-non-matching-authors)))
    834 	;; The visible string contains only matching authors.
    835 	(setq visible-string (propertize visible-string
    836 					 'face 'notmuch-search-matching-authors))
    837 	;; The invisible string may contain both matching and
    838 	;; non-matching authors.
    839 	(setq invisible-string (notmuch-search-author-propertize invisible-string)))
    840       ;; If there is any invisible text, add it as a tooltip to the
    841       ;; visible text.
    842       (unless (string-empty-p invisible-string)
    843 	(setq visible-string
    844 	      (propertize visible-string
    845 			  'help-echo (concat "..." invisible-string))))
    846       ;; Insert the visible and, if present, invisible author strings.
    847       (insert visible-string)
    848       (unless (string-empty-p invisible-string)
    849 	(let ((start (point))
    850 	      overlay)
    851 	  (insert invisible-string)
    852 	  (setq overlay (make-overlay start (point)))
    853 	  (overlay-put overlay 'evaporate t)
    854 	  (overlay-put overlay 'invisible 'ellipsis)
    855 	  (overlay-put overlay 'isearch-open-invisible #'delete-overlay)))
    856       (insert padding))))
    857 
    858 (defun notmuch-search-insert-field (field format-string result)
    859   (pcase field
    860     ((pred functionp)
    861      (insert (funcall field format-string result)))
    862     ("date"
    863      (insert (propertize (format format-string (plist-get result :date_relative))
    864 			 'face 'notmuch-search-date)))
    865     ("count"
    866      (insert (propertize (format format-string
    867 				 (format "[%s/%s]" (plist-get result :matched)
    868 					 (plist-get result :total)))
    869 			 'face 'notmuch-search-count)))
    870     ("subject"
    871      (insert (propertize (format format-string
    872 				 (notmuch-sanitize (plist-get result :subject)))
    873 			 'face 'notmuch-search-subject)))
    874     ("authors"
    875      (notmuch-search-insert-authors format-string
    876 				    (notmuch-sanitize (plist-get result :authors))))
    877     ("tags"
    878      (let ((tags (plist-get result :tags))
    879 	   (orig-tags (plist-get result :orig-tags)))
    880        (insert (format format-string (notmuch-tag-format-tags tags orig-tags)))))))
    881 
    882 (defun notmuch-search-show-result (result pos)
    883   "Insert RESULT at POS."
    884   ;; Ignore excluded matches
    885   (unless (= (plist-get result :matched) 0)
    886     (save-excursion
    887       (goto-char pos)
    888       (dolist (spec notmuch-search-result-format)
    889 	(notmuch-search-insert-field (car spec) (cdr spec) result))
    890       (insert "\n")
    891       (notmuch-search-color-line pos (point) (plist-get result :tags))
    892       (put-text-property pos (point) 'notmuch-search-result result))))
    893 
    894 (defun notmuch-search-append-result (result)
    895   "Insert RESULT at the end of the buffer.
    896 
    897 This is only called when a result is first inserted so it also
    898 sets the :orig-tag property."
    899   (let ((new-result (plist-put result :orig-tags (plist-get result :tags)))
    900 	(pos (point-max)))
    901     (notmuch-search-show-result new-result pos)
    902     (when (string= (plist-get result :thread) notmuch-search-target-thread)
    903       (setq notmuch-search-target-thread "found")
    904       (goto-char pos))))
    905 
    906 (defvar-local notmuch--search-hook-run nil
    907   "Flag used to ensure the notmuch-search-hook is only run once per buffer")
    908 
    909 (defun notmuch--search-hook-wrapper ()
    910   (unless notmuch--search-hook-run
    911     (setq notmuch--search-hook-run t)
    912     (run-hooks 'notmuch-search-hook)))
    913 
    914 (defun notmuch-search-process-filter (proc string)
    915   "Process and filter the output of \"notmuch search\"."
    916   (let ((results-buf (process-buffer proc))
    917 	(parse-buf (process-get proc 'parse-buf))
    918 	(inhibit-read-only t))
    919     (when (buffer-live-p results-buf)
    920       (with-current-buffer parse-buf
    921 	;; Insert new data
    922 	(save-excursion
    923 	  (goto-char (point-max))
    924 	  (insert string))
    925 	(notmuch-sexp-parse-partial-list 'notmuch-search-append-result
    926 					 results-buf))
    927       (with-current-buffer results-buf
    928 	(notmuch--search-hook-wrapper)))))
    929 
    930 ;;; Commands (and some helper functions used by them)
    931 
    932 (defun notmuch-search-tag-all (tag-changes)
    933   "Add/remove tags from all messages in current search buffer.
    934 
    935 See `notmuch-tag' for information on the format of TAG-CHANGES."
    936   (interactive
    937    (list (notmuch-read-tag-changes
    938 	  (notmuch-search-get-tags-region (point-min) (point-max)) "Tag all")))
    939   (notmuch-search-tag tag-changes (point-min) (point-max) t))
    940 
    941 (defcustom notmuch-search-buffer-name-format "*notmuch-%t-%s*"
    942   "Format for the name of search results buffers.
    943 
    944 In this spec, %s will be replaced by a description of the search
    945 query and %t by its type (search, tree or unthreaded).  The
    946 buffer name is formatted using `format-spec': see its docstring
    947 for additional parameters for the s and t format specifiers.
    948 
    949 See also `notmuch-saved-search-buffer-name-format'"
    950   :type 'string
    951   :group 'notmuch-search)
    952 
    953 (defcustom notmuch-saved-search-buffer-name-format "*notmuch-saved-%t-%s*"
    954   "Format for the name of search results buffers for saved searches.
    955 
    956 In this spec, %s will be replaced by the saved search name and %t
    957 by its type (search, tree or unthreaded).  The buffer name is
    958 formatted using `format-spec': see its docstring for additional
    959 parameters for the s and t format specifiers.
    960 
    961 See also `notmuch-search-buffer-name-format'"
    962   :type 'string
    963   :group 'notmuch-search)
    964 
    965 (defun notmuch-search-format-buffer-name (query type saved)
    966   "Compose a buffer name for the given QUERY, TYPE (search, tree,
    967 unthreaded) and whether it's SAVED (t or nil)."
    968   (let ((fmt (if saved
    969 		 notmuch-saved-search-buffer-name-format
    970 	       notmuch-search-buffer-name-format)))
    971     (format-spec fmt `((?t . ,(or type "search")) (?s . ,query)))))
    972 
    973 (defun notmuch-search-buffer-title (query &optional type)
    974   "Returns the title for a buffer with notmuch search results."
    975   (let* ((saved-search
    976 	  (let (longest
    977 		(longest-length 0))
    978 	    (cl-loop for tuple in notmuch-saved-searches
    979 		     if (let ((quoted-query
    980 			       (regexp-quote
    981 				(notmuch-saved-search-get tuple :query))))
    982 			  (and (string-match (concat "^" quoted-query) query)
    983 			       (> (length (match-string 0 query))
    984 				  longest-length)))
    985 		     do (setq longest tuple))
    986 	    longest))
    987 	 (saved-search-name (notmuch-saved-search-get saved-search :name))
    988 	 (saved-search-type (notmuch-saved-search-get saved-search :search-type))
    989 	 (saved-search-query (notmuch-saved-search-get saved-search :query)))
    990     (cond ((and saved-search (equal saved-search-query query))
    991 	   ;; Query is the same as saved search (ignoring case)
    992 	   (notmuch-search-format-buffer-name saved-search-name
    993 					      saved-search-type
    994 					      t))
    995 	  (saved-search
    996 	   (let ((query (replace-regexp-in-string
    997 			 (concat "^" (regexp-quote saved-search-query))
    998 			 (concat "[ " saved-search-name " ]")
    999 			 query)))
   1000 	     (notmuch-search-format-buffer-name query saved-search-type t)))
   1001 	  (t (notmuch-search-format-buffer-name query type nil)))))
   1002 
   1003 (defun notmuch-read-query (prompt)
   1004   "Read a notmuch-query from the minibuffer with completion.
   1005 
   1006 PROMPT is the string to prompt with."
   1007   (let* ((all-tags
   1008 	  (mapcar (lambda (tag) (notmuch-escape-boolean-term tag))
   1009 		  (notmuch--process-lines notmuch-command "search" "--output=tags" "*")))
   1010 	 (completions
   1011 	  (append (list "folder:" "path:" "thread:" "id:" "date:" "from:" "to:"
   1012 			"subject:" "attachment:")
   1013 		  (mapcar (lambda (tag) (concat "tag:" tag)) all-tags)
   1014 		  (mapcar (lambda (tag) (concat "is:" tag)) all-tags)
   1015 		  (mapcar (lambda (mimetype) (concat "mimetype:" mimetype))
   1016 			  (mailcap-mime-types))))
   1017 	 (keymap (copy-keymap minibuffer-local-map))
   1018 	 (current-query (cl-case major-mode
   1019 			  (notmuch-search-mode (notmuch-search-get-query))
   1020 			  (notmuch-show-mode (notmuch-show-get-query))
   1021 			  (notmuch-tree-mode (notmuch-tree-get-query))))
   1022 	 (minibuffer-completion-table
   1023 	  (completion-table-dynamic
   1024 	   (lambda (string)
   1025 	     ;; Generate a list of possible completions for the current input.
   1026 	     (cond
   1027 	      ;; This ugly regexp is used to get the last word of the input
   1028 	      ;; possibly preceded by a '('.
   1029 	      ((string-match "\\(^\\|.* (?\\)\\([^ ]*\\)$" string)
   1030 	       (mapcar (lambda (compl)
   1031 			 (concat (match-string-no-properties 1 string) compl))
   1032 		       (all-completions (match-string-no-properties 2 string)
   1033 					completions)))
   1034 	      (t (list string)))))))
   1035     ;; This was simpler than convincing completing-read to accept spaces:
   1036     (define-key keymap (kbd "TAB") 'minibuffer-complete)
   1037     (let ((history-delete-duplicates t))
   1038       (read-from-minibuffer prompt nil keymap nil
   1039 			    'notmuch-search-history current-query nil))))
   1040 
   1041 (defun notmuch-search-get-query ()
   1042   "Return the current query in this search buffer."
   1043   notmuch-search-query-string)
   1044 
   1045 (put 'notmuch-search 'notmuch-doc "Search for messages.")
   1046 ;;;###autoload
   1047 (defun notmuch-search (&optional query oldest-first hide-excluded target-thread
   1048 				 target-line no-display)
   1049   "Display threads matching QUERY in a notmuch-search buffer.
   1050 
   1051 If QUERY is nil, it is read interactively from the minibuffer.
   1052 Other optional parameters are used as follows:
   1053 
   1054   OLDEST-FIRST: A Boolean controlling the sort order of returned threads
   1055   HIDE-EXCLUDED: A boolean controlling whether to omit threads with excluded
   1056                  tags.
   1057   TARGET-THREAD: A thread ID (without the thread: prefix) that will be made
   1058                  current if it appears in the search results.
   1059   TARGET-LINE: The line number to move to if the target thread does not
   1060                appear in the search results.
   1061   NO-DISPLAY: Do not try to foreground the search results buffer. If it is
   1062               already foregrounded i.e. displayed in a window, this has no
   1063               effect, meaning the buffer will remain visible.
   1064 
   1065 When called interactively, this will prompt for a query and use
   1066 the configured default sort order."
   1067   (interactive
   1068    (list
   1069     ;; Prompt for a query
   1070     nil
   1071     ;; Use the default search order and exclude value (if we're doing a
   1072     ;; search from a search buffer, ignore any buffer-local overrides)
   1073     (default-value 'notmuch-search-oldest-first)
   1074     (default-value 'notmuch-search-hide-excluded)))
   1075 
   1076   (let* ((query (or query (notmuch-read-query "Notmuch search: ")))
   1077 	 (buffer (get-buffer-create (notmuch-search-buffer-title query))))
   1078     (if no-display
   1079 	(set-buffer buffer)
   1080       (pop-to-buffer-same-window buffer))
   1081     (notmuch-search-mode)
   1082     ;; Don't track undo information for this buffer
   1083     (setq buffer-undo-list t)
   1084     (setq notmuch-search-query-string query)
   1085     (setq notmuch-search-oldest-first oldest-first)
   1086     (setq notmuch-search-target-thread target-thread)
   1087     (setq notmuch-search-target-line target-line)
   1088     (setq notmuch-search-hide-excluded hide-excluded)
   1089     (notmuch-tag-clear-cache)
   1090     (when (get-buffer-process buffer)
   1091       (error "notmuch search process already running for query `%s'" query))
   1092     (let ((inhibit-read-only t))
   1093       (erase-buffer)
   1094       (goto-char (point-min))
   1095       (save-excursion
   1096 	(let ((proc (notmuch-start-notmuch
   1097 		     "notmuch-search" buffer #'notmuch-search-process-sentinel
   1098 		     "search" "--format=sexp" "--format-version=5"
   1099 		     (if oldest-first
   1100 			 "--sort=oldest-first"
   1101 		       "--sort=newest-first")
   1102 		     (if hide-excluded
   1103 			 "--exclude=true"
   1104 		       "--exclude=false")
   1105 		     query)))
   1106 	  ;; Use a scratch buffer to accumulate partial output.
   1107 	  ;; This buffer will be killed by the sentinel, which
   1108 	  ;; should be called no matter how the process dies.
   1109 	  (process-put proc 'parse-buf
   1110 		       (generate-new-buffer " *notmuch search parse*"))
   1111 	  (set-process-filter proc 'notmuch-search-process-filter)
   1112 	  (set-process-query-on-exit-flag proc nil))))))
   1113 
   1114 (defun notmuch-search-refresh-view ()
   1115   "Refresh the current view.
   1116 
   1117 Erases the current buffer and runs a new search with the same
   1118 query string as the current search. If the current thread is in
   1119 the new search results, then point will be placed on the same
   1120 thread. Otherwise, point will be moved to attempt to be in the
   1121 same relative position within the new buffer."
   1122   (interactive)
   1123   (notmuch-search notmuch-search-query-string
   1124 		  notmuch-search-oldest-first
   1125 		  notmuch-search-hide-excluded
   1126 		  (notmuch-search-find-thread-id 'bare)
   1127 		  (line-number-at-pos)
   1128 		  t)
   1129   (goto-char (point-min)))
   1130 
   1131 (defun notmuch-search-toggle-hide-excluded ()
   1132   "Toggle whether to hide excluded messages.
   1133 
   1134 This command toggles whether to hide excluded messages for the current
   1135 search. The default value for this is defined by `notmuch-search-hide-excluded'."
   1136   (interactive)
   1137   (setq notmuch-search-hide-excluded (not notmuch-search-hide-excluded))
   1138   (notmuch-search-refresh-view))
   1139 
   1140 (defun notmuch-search-toggle-order ()
   1141   "Toggle the current search order.
   1142 
   1143 This command toggles the sort order for the current search. The
   1144 default sort order is defined by `notmuch-search-oldest-first'."
   1145   (interactive)
   1146   (setq notmuch-search-oldest-first (not notmuch-search-oldest-first))
   1147   (notmuch-search-refresh-view))
   1148 
   1149 (defun notmuch-group-disjunctive-query-string (query-string)
   1150   "Group query if it contains a complex expression.
   1151 Enclose QUERY-STRING in parentheses if contains \"OR\" operators."
   1152   (if (string-match-p "\\<[oO][rR]\\>" query-string)
   1153       (concat "( " query-string " )")
   1154     query-string))
   1155 
   1156 (defun notmuch-search-filter (query)
   1157   "Filter or LIMIT the current search results based on an additional query string.
   1158 
   1159 Runs a new search matching only messages that match both the
   1160 current search results AND the additional query string provided."
   1161   (interactive (list (notmuch-read-query "Filter search: ")))
   1162   (let ((grouped-query (notmuch-group-disjunctive-query-string query))
   1163 	(grouped-original-query (notmuch-group-disjunctive-query-string
   1164 				 notmuch-search-query-string)))
   1165     (notmuch-search (if (string= grouped-original-query "*")
   1166 			grouped-query
   1167 		      (concat grouped-original-query " and " grouped-query))
   1168 		    notmuch-search-oldest-first
   1169 		    notmuch-search-hide-excluded)))
   1170 
   1171 (defun notmuch-search-filter-by-tag (tag)
   1172   "Filter the current search results based on a single TAG.
   1173 
   1174 Run a new search matching only messages that match the current
   1175 search results and that are also tagged with the given TAG."
   1176   (interactive
   1177    (list (notmuch-select-tag-with-completion "Filter by tag: "
   1178 					     notmuch-search-query-string)))
   1179   (notmuch-search (concat notmuch-search-query-string " and tag:" tag)
   1180 		  notmuch-search-oldest-first
   1181 		  notmuch-search-hide-excluded))
   1182 
   1183 (defun notmuch-search-by-tag (tag)
   1184   "Display threads matching TAG in a notmuch-search buffer."
   1185   (interactive
   1186    (list (notmuch-select-tag-with-completion "Notmuch search tag: ")))
   1187   (notmuch-search (concat "tag:" tag)
   1188 		  (default-value 'notmuch-search-oldest-first)
   1189 		  (default-value 'notmuch-search-hide-excluded)))
   1190 
   1191 (defun notmuch-search-edit-search (query)
   1192   "Edit the current search"
   1193   (interactive (list (read-from-minibuffer "Edit search: "
   1194 					   notmuch-search-query-string)))
   1195   (notmuch-search query notmuch-search-oldest-first))
   1196 
   1197 ;;;###autoload
   1198 (defun notmuch ()
   1199   "Run notmuch and display saved searches, known tags, etc."
   1200   (interactive)
   1201   (notmuch-hello))
   1202 
   1203 (defun notmuch-interesting-buffer (b)
   1204   "Whether the current buffer's major-mode is a notmuch mode."
   1205   (with-current-buffer b
   1206     (memq major-mode '(notmuch-show-mode
   1207 		       notmuch-search-mode
   1208 		       notmuch-tree-mode
   1209 		       notmuch-hello-mode
   1210 		       notmuch-message-mode))))
   1211 
   1212 ;;;###autoload
   1213 (defun notmuch-cycle-notmuch-buffers ()
   1214   "Cycle through any existing notmuch buffers (search, show or hello).
   1215 
   1216 If the current buffer is the only notmuch buffer, bury it.
   1217 If no notmuch buffers exist, run `notmuch'."
   1218   (interactive)
   1219   (let (start first)
   1220     ;; If the current buffer is a notmuch buffer, remember it and then
   1221     ;; bury it.
   1222     (when (notmuch-interesting-buffer (current-buffer))
   1223       (setq start (current-buffer))
   1224       (bury-buffer))
   1225 
   1226     ;; Find the first notmuch buffer.
   1227     (setq first (cl-loop for buffer in (buffer-list)
   1228 			 if (notmuch-interesting-buffer buffer)
   1229 			 return buffer))
   1230 
   1231     (if first
   1232 	;; If the first one we found is any other than the starting
   1233 	;; buffer, switch to it.
   1234 	(unless (eq first start)
   1235 	  (pop-to-buffer-same-window first))
   1236       (notmuch))))
   1237 
   1238 ;;; Integrations
   1239 ;;;; Hl-line Support
   1240 
   1241 (defun notmuch-hl-line-mode ()
   1242   (prog1 (hl-line-mode)
   1243     (when hl-line-overlay
   1244       (overlay-put hl-line-overlay 'priority 1))))
   1245 
   1246 ;;;; Imenu Support
   1247 
   1248 (defun notmuch-search-imenu-prev-index-position-function ()
   1249   "Move point to previous message in notmuch-search buffer.
   1250 Used as`imenu-prev-index-position-function' in notmuch buffers."
   1251   (notmuch-search-previous-thread))
   1252 
   1253 (defun notmuch-search-imenu-extract-index-name-function ()
   1254   "Return imenu name for line at point.
   1255 Used as `imenu-extract-index-name-function' in notmuch buffers.
   1256 Point should be at the beginning of the line."
   1257   (format "%s (%s)"
   1258 	  (notmuch-search-find-subject)
   1259 	  (notmuch-search-find-authors)))
   1260 
   1261 ;;; _
   1262 
   1263 (provide 'notmuch)
   1264 
   1265 ;; After provide to avoid loops if notmuch was require'd via notmuch-init-file.
   1266 (when init-file-user ; don't load init file if the -q option was used.
   1267   (load notmuch-init-file t t nil t))
   1268 
   1269 ;;; notmuch.el ends here