]> git.notmuchmail.org Git - notmuch/blob - emacs/notmuch-lib.el
emacs: Add new option notmuch-search-hide-excluded
[notmuch] / emacs / notmuch-lib.el
1 ;;; notmuch-lib.el --- common variables, functions and function declarations  -*- 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
22 ;;; Code:
23
24 (require 'cl-lib)
25 (require 'pcase)
26 (require 'subr-x)
27
28 (require 'mm-util)
29 (require 'mm-view)
30 (require 'mm-decode)
31
32 (require 'notmuch-compat)
33
34 (unless (require 'notmuch-version nil t)
35   (defconst notmuch-emacs-version "unknown"
36     "Placeholder variable when notmuch-version.el[c] is not available."))
37
38 ;;; Groups
39
40 (defgroup notmuch nil
41   "Notmuch mail reader for Emacs."
42   :group 'mail)
43
44 (defgroup notmuch-hello nil
45   "Overview of saved searches, tags, etc."
46   :group 'notmuch)
47
48 (defgroup notmuch-search nil
49   "Searching and sorting mail."
50   :group 'notmuch)
51
52 (defgroup notmuch-show nil
53   "Showing messages and threads."
54   :group 'notmuch)
55
56 (defgroup notmuch-send nil
57   "Sending messages from Notmuch."
58   :group 'notmuch
59   :group 'message)
60
61 (defgroup notmuch-tag nil
62   "Tags and tagging in Notmuch."
63   :group 'notmuch)
64
65 (defgroup notmuch-crypto nil
66   "Processing and display of cryptographic MIME parts."
67   :group 'notmuch)
68
69 (defgroup notmuch-hooks nil
70   "Running custom code on well-defined occasions."
71   :group 'notmuch)
72
73 (defgroup notmuch-external nil
74   "Running external commands from within Notmuch."
75   :group 'notmuch)
76
77 (defgroup notmuch-address nil
78   "Address completion."
79   :group 'notmuch)
80
81 (defgroup notmuch-faces nil
82   "Graphical attributes for displaying text"
83   :group 'notmuch)
84
85 ;;; Options
86
87 (defcustom notmuch-command "notmuch"
88   "Name of the notmuch binary.
89
90 This can be a relative or absolute path to the notmuch binary.
91 If this is a relative path, it will be searched for in all of the
92 directories given in `exec-path' (which is, by default, based on
93 $PATH)."
94   :type 'string
95   :group 'notmuch-external)
96
97 (defcustom notmuch-search-oldest-first t
98   "Show the oldest mail first when searching.
99
100 This variable defines the default sort order for displaying
101 search results. Note that any filtered searches created by
102 `notmuch-search-filter' retain the search order of the parent
103 search."
104   :type 'boolean
105   :group 'notmuch-search)
106 (make-variable-buffer-local 'notmuch-search-oldest-first)
107
108 (defcustom notmuch-poll-script nil
109   "[Deprecated] Command to run to incorporate new mail into the notmuch database.
110
111 This option has been deprecated in favor of \"notmuch new\"
112 hooks (see man notmuch-hooks).  To change the path to the notmuch
113 binary, customize `notmuch-command'.
114
115 This variable controls the action invoked by
116 `notmuch-poll-and-refresh-this-buffer' (bound by default to 'G')
117 to incorporate new mail into the notmuch database.
118
119 If set to nil (the default), new mail is processed by invoking
120 \"notmuch new\". Otherwise, this should be set to a string that
121 gives the name of an external script that processes new mail. If
122 set to the empty string, no command will be run.
123
124 The external script could do any of the following depending on
125 the user's needs:
126
127 1. Invoke a program to transfer mail to the local mail store
128 2. Invoke \"notmuch new\" to incorporate the new mail
129 3. Invoke one or more \"notmuch tag\" commands to classify the mail"
130   :type '(choice (const :tag "notmuch new" nil)
131                  (const :tag "Disabled" "")
132                  (string :tag "Custom script"))
133   :group 'notmuch-external)
134
135 (defcustom notmuch-archive-tags '("-inbox")
136   "List of tag changes to apply to a message or a thread when it is archived.
137
138 Tags starting with \"+\" (or not starting with either \"+\" or
139 \"-\") in the list will be added, and tags starting with \"-\"
140 will be removed from the message or thread being archived.
141
142 For example, if you wanted to remove an \"inbox\" tag and add an
143 \"archived\" tag, you would set:
144     (\"-inbox\" \"+archived\")"
145   :type '(repeat string)
146   :group 'notmuch-search
147   :group 'notmuch-show)
148
149 ;;; Variables
150
151 (defvar notmuch-search-history nil
152   "Variable to store notmuch searches history.")
153
154 (defvar notmuch-common-keymap
155   (let ((map (make-sparse-keymap)))
156     (define-key map "?" 'notmuch-help)
157     (define-key map "v" 'notmuch-version)
158     (define-key map "q" 'notmuch-bury-or-kill-this-buffer)
159     (define-key map "s" 'notmuch-search)
160     (define-key map "t" 'notmuch-search-by-tag)
161     (define-key map "z" 'notmuch-tree)
162     (define-key map "u" 'notmuch-unthreaded)
163     (define-key map "m" 'notmuch-mua-new-mail)
164     (define-key map "g" 'notmuch-refresh-this-buffer)
165     (define-key map "=" 'notmuch-refresh-this-buffer)
166     (define-key map (kbd "M-=") 'notmuch-refresh-all-buffers)
167     (define-key map "G" 'notmuch-poll-and-refresh-this-buffer)
168     (define-key map "j" 'notmuch-jump-search)
169     (define-key map [remap undo] 'notmuch-tag-undo)
170     map)
171   "Keymap shared by all notmuch modes.")
172
173 ;; By default clicking on a button does not select the window
174 ;; containing the button (as opposed to clicking on a widget which
175 ;; does). This means that the button action is then executed in the
176 ;; current selected window which can cause problems if the button
177 ;; changes the buffer (e.g., id: links) or moves point.
178 ;;
179 ;; This provides a button type which overrides mouse-action so that
180 ;; the button's window is selected before the action is run. Other
181 ;; notmuch buttons can get the same behaviour by inheriting from this
182 ;; button type.
183 (define-button-type 'notmuch-button-type
184   'mouse-action (lambda (button)
185                   (select-window (posn-window (event-start last-input-event)))
186                   (button-activate button)))
187
188 ;;; CLI Utilities
189
190 (defun notmuch-command-to-string (&rest args)
191   "Synchronously invoke \"notmuch\" with the given list of arguments.
192
193 If notmuch exits with a non-zero status, output from the process
194 will appear in a buffer named \"*Notmuch errors*\" and an error
195 will be signaled.
196
197 Otherwise the output will be returned."
198   (with-temp-buffer
199     (let ((status (apply #'notmuch--call-process notmuch-command nil t nil args))
200           (output (buffer-string)))
201       (notmuch-check-exit-status status (cons notmuch-command args) output)
202       output)))
203
204 (defvar notmuch--cli-sane-p nil
205   "Cache whether the CLI seems to be configured sanely.")
206
207 (defun notmuch-cli-sane-p ()
208   "Return t if the cli seems to be configured sanely."
209   (unless notmuch--cli-sane-p
210     (let ((status (notmuch--call-process notmuch-command nil nil nil
211                                 "config" "get" "user.primary_email")))
212       (setq notmuch--cli-sane-p (= status 0))))
213   notmuch--cli-sane-p)
214
215 (defun notmuch-assert-cli-sane ()
216   (unless (notmuch-cli-sane-p)
217     (notmuch-logged-error
218      "notmuch cli seems misconfigured or unconfigured."
219      "Perhaps you haven't run \"notmuch setup\" yet? Try running this
220 on the command line, and then retry your notmuch command")))
221
222 (defun notmuch-cli-version ()
223   "Return a string with the notmuch cli command version number."
224   (let ((long-string
225          ;; Trim off the trailing newline.
226          (substring (notmuch-command-to-string "--version") 0 -1)))
227     (if (string-match "^notmuch\\( version\\)? \\(.*\\)$"
228                       long-string)
229         (match-string 2 long-string)
230       "unknown")))
231
232 (defvar notmuch-emacs-version)
233
234 (defun notmuch-version ()
235   "Display the notmuch version.
236 The versions of the Emacs package and the `notmuch' executable
237 should match, but if and only if they don't, then this command
238 displays both values separately."
239   (interactive)
240   (let ((cli-version (notmuch-cli-version)))
241     (message "notmuch version %s"
242              (if (string= notmuch-emacs-version cli-version)
243                  cli-version
244                (concat cli-version
245                        " (emacs mua version " notmuch-emacs-version ")")))))
246
247 ;;; Notmuch Configuration
248
249 (defun notmuch-config-get (item)
250   "Return a value from the notmuch configuration."
251   (let* ((val (notmuch-command-to-string "config" "get" item))
252          (len (length val)))
253     ;; Trim off the trailing newline (if the value is empty or not
254     ;; configured, there will be no newline).
255     (if (and (> len 0)
256              (= (aref val (- len 1)) ?\n))
257         (substring val 0 -1)
258       val)))
259
260 (defun notmuch-database-path ()
261   "Return the database.path value from the notmuch configuration."
262   (notmuch-config-get "database.path"))
263
264 (defun notmuch-user-name ()
265   "Return the user.name value from the notmuch configuration."
266   (notmuch-config-get "user.name"))
267
268 (defun notmuch-user-primary-email ()
269   "Return the user.primary_email value from the notmuch configuration."
270   (notmuch-config-get "user.primary_email"))
271
272 (defun notmuch-user-other-email ()
273   "Return the user.other_email value (as a list) from the notmuch configuration."
274   (split-string (notmuch-config-get "user.other_email") "\n" t))
275
276 (defun notmuch-user-emails ()
277   (cons (notmuch-user-primary-email) (notmuch-user-other-email)))
278
279 ;;; Commands
280
281 (defun notmuch-poll ()
282   "Run \"notmuch new\" or an external script to import mail.
283
284 Invokes `notmuch-poll-script', \"notmuch new\", or does nothing
285 depending on the value of `notmuch-poll-script'."
286   (interactive)
287   (message "Polling mail...")
288   (if (stringp notmuch-poll-script)
289       (unless (string-empty-p notmuch-poll-script)
290         (unless (equal (notmuch--call-process notmuch-poll-script nil nil) 0)
291           (error "Notmuch: poll script `%s' failed!" notmuch-poll-script)))
292     (notmuch-call-notmuch-process "new"))
293   (message "Polling mail...done"))
294
295 (defun notmuch-bury-or-kill-this-buffer ()
296   "Undisplay the current buffer.
297
298 Bury the current buffer, unless there is only one window showing
299 it, in which case it is killed."
300   (interactive)
301   (if (> (length (get-buffer-window-list nil nil t)) 1)
302       (bury-buffer)
303     (kill-buffer)))
304
305 ;;; Describe Key Bindings
306
307 (defun notmuch-prefix-key-description (key)
308   "Given a prefix key code, return a human-readable string representation.
309
310 This is basically just `format-kbd-macro' but we also convert ESC to M-."
311   (let* ((key-vector (if (vectorp key) key (vector key)))
312          (desc (format-kbd-macro key-vector)))
313     (if (string= desc "ESC")
314         "M-"
315       (concat desc " "))))
316
317 (defun notmuch-describe-key (actual-key binding prefix ua-keys tail)
318   "Prepend cons cells describing prefix-arg ACTUAL-KEY and ACTUAL-KEY to TAIL.
319
320 It does not prepend if ACTUAL-KEY is already listed in TAIL."
321   (let ((key-string (concat prefix (key-description actual-key))))
322     ;; We don't include documentation if the key-binding is
323     ;; over-ridden. Note, over-riding a binding automatically hides the
324     ;; prefixed version too.
325     (unless (assoc key-string tail)
326       (when (and ua-keys (symbolp binding)
327                  (get binding 'notmuch-prefix-doc))
328         ;; Documentation for prefixed command
329         (let ((ua-desc (key-description ua-keys)))
330           (push (cons (concat ua-desc " " prefix (format-kbd-macro actual-key))
331                       (get binding 'notmuch-prefix-doc))
332                 tail)))
333       ;; Documentation for command
334       (push (cons key-string
335                   (or (and (symbolp binding)
336                            (get binding 'notmuch-doc))
337                       (and (functionp binding)
338                            (let ((doc (documentation binding)))
339                              (and doc
340                                   (string-match "\\`.+" doc)
341                                   (match-string 0 doc))))))
342             tail)))
343   tail)
344
345 (defun notmuch-describe-remaps (remap-keymap ua-keys base-keymap prefix tail)
346   ;; Remappings are represented as a binding whose first "event" is
347   ;; 'remap.  Hence, if the keymap has any remappings, it will have a
348   ;; binding whose "key" is 'remap, and whose "binding" is itself a
349   ;; keymap that maps not from keys to commands, but from old (remapped)
350   ;; functions to the commands to use in their stead.
351   (map-keymap (lambda (command binding)
352                 (mapc (lambda (actual-key)
353                         (setq tail
354                               (notmuch-describe-key actual-key binding
355                                                     prefix ua-keys tail)))
356                       (where-is-internal command base-keymap)))
357               remap-keymap)
358   tail)
359
360 (defun notmuch-describe-keymap (keymap ua-keys base-keymap &optional prefix tail)
361   "Return a list of cons cells, each describing one binding in KEYMAP.
362
363 Each cons cell consists of a string giving a human-readable
364 description of the key, and a one-line description of the bound
365 function.  See `notmuch-help' for an overview of how this
366 documentation is extracted.
367
368 UA-KEYS should be a key sequence bound to `universal-argument'.
369 It will be used to describe bindings of commands that support a
370 prefix argument.  PREFIX and TAIL are used internally."
371   (map-keymap
372    (lambda (key binding)
373      (cond ((mouse-event-p key) nil)
374            ((keymapp binding)
375             (setq tail
376                   (if (eq key 'remap)
377                       (notmuch-describe-remaps
378                        binding ua-keys base-keymap prefix tail)
379                     (notmuch-describe-keymap
380                      binding ua-keys base-keymap
381                      (notmuch-prefix-key-description key)
382                      tail))))
383            (binding
384             (setq tail
385                   (notmuch-describe-key (vector key)
386                                         binding prefix ua-keys tail)))))
387    keymap)
388   tail)
389
390 (defun notmuch-substitute-command-keys (doc)
391   "Like `substitute-command-keys' but with documentation, not function names."
392   (let ((beg 0))
393     (while (string-match "\\\\{\\([^}[:space:]]*\\)}" doc beg)
394       (let ((desc
395              (save-match-data
396                (let* ((keymap-name (substring doc
397                                               (match-beginning 1)
398                                               (match-end 1)))
399                       (keymap (symbol-value (intern keymap-name)))
400                       (ua-keys (where-is-internal 'universal-argument keymap t))
401                       (desc-alist (notmuch-describe-keymap keymap ua-keys keymap))
402                       (desc-list (mapcar (lambda (arg)
403                                            (concat (car arg) "\t" (cdr arg)))
404                                          desc-alist)))
405                  (mapconcat #'identity desc-list "\n")))))
406         (setq doc (replace-match desc 1 1 doc)))
407       (setq beg (match-end 0)))
408     doc))
409
410 (defun notmuch-help ()
411   "Display help for the current notmuch mode.
412
413 This is similar to `describe-function' for the current major
414 mode, but bindings tables are shown with documentation strings
415 rather than command names.  By default, this uses the first line
416 of each command's documentation string.  A command can override
417 this by setting the 'notmuch-doc property of its command symbol.
418 A command that supports a prefix argument can explicitly document
419 its prefixed behavior by setting the 'notmuch-prefix-doc property
420 of its command symbol."
421   (interactive)
422   (let ((doc (substitute-command-keys
423               (notmuch-substitute-command-keys
424                (documentation major-mode t)))))
425     (with-current-buffer (generate-new-buffer "*notmuch-help*")
426       (insert doc)
427       (goto-char (point-min))
428       (set-buffer-modified-p nil)
429       (view-buffer (current-buffer) 'kill-buffer-if-not-modified))))
430
431 (defun notmuch-subkeymap-help ()
432   "Show help for a subkeymap."
433   (interactive)
434   (let* ((key (this-command-keys-vector))
435          (prefix (make-vector (1- (length key)) nil))
436          (i 0))
437     (while (< i (length prefix))
438       (aset prefix i (aref key i))
439       (cl-incf i))
440     (let* ((subkeymap (key-binding prefix))
441            (ua-keys (where-is-internal 'universal-argument nil t))
442            (prefix-string (notmuch-prefix-key-description prefix))
443            (desc-alist (notmuch-describe-keymap
444                         subkeymap ua-keys subkeymap prefix-string))
445            (desc-list (mapcar (lambda (arg) (concat (car arg) "\t" (cdr arg)))
446                               desc-alist))
447            (desc (mapconcat #'identity desc-list "\n")))
448       (with-help-window (help-buffer)
449         (with-current-buffer standard-output
450           (insert "\nPress 'q' to quit this window.\n\n")
451           (insert desc)))
452       (pop-to-buffer (help-buffer)))))
453
454 ;;; Refreshing Buffers
455
456 (defvar-local notmuch-buffer-refresh-function nil
457   "Function to call to refresh the current buffer.")
458
459 (defun notmuch-refresh-this-buffer ()
460   "Refresh the current buffer."
461   (interactive)
462   (when notmuch-buffer-refresh-function
463     ;; Pass prefix argument, etc.
464     (call-interactively notmuch-buffer-refresh-function)))
465
466 (defun notmuch-poll-and-refresh-this-buffer ()
467   "Invoke `notmuch-poll' to import mail, then refresh the current buffer."
468   (interactive)
469   (notmuch-poll)
470   (notmuch-refresh-this-buffer))
471
472 (defun notmuch-refresh-all-buffers ()
473   "Invoke `notmuch-refresh-this-buffer' on all notmuch major-mode buffers.
474
475 The buffers are silently refreshed, i.e. they are not forced to
476 be displayed."
477   (interactive)
478   (dolist (buffer (buffer-list))
479     (let ((buffer-mode (buffer-local-value 'major-mode buffer)))
480       (when (memq buffer-mode '(notmuch-show-mode
481                                 notmuch-tree-mode
482                                 notmuch-search-mode
483                                 notmuch-hello-mode))
484         (with-current-buffer buffer
485           (notmuch-refresh-this-buffer))))))
486
487 ;;; String Utilities
488
489 (defun notmuch-prettify-subject (subject)
490   ;; This function is used by `notmuch-search-process-filter',
491   ;; which requires that we not disrupt its matching state.
492   (save-match-data
493     (if (and subject
494              (string-match "^[ \t]*$" subject))
495         "[No Subject]"
496       subject)))
497
498 (defun notmuch-sanitize (str)
499   "Sanitize control character in STR.
500
501 This includes newlines, tabs, and other funny characters."
502   (replace-regexp-in-string "[[:cntrl:]\x7f\u2028\u2029]+" " " str))
503
504 (defun notmuch-escape-boolean-term (term)
505   "Escape a boolean term for use in a query.
506
507 The caller is responsible for prepending the term prefix and a
508 colon.  This performs minimal escaping in order to produce
509 user-friendly queries."
510   (save-match-data
511     (if (or (equal term "")
512             ;; To be pessimistic, only pass through terms composed
513             ;; entirely of ASCII printing characters other than ", (,
514             ;; and ).
515             (string-match "[^!#-'*-~]" term))
516         ;; Requires escaping
517         (concat "\"" (replace-regexp-in-string "\"" "\"\"" term t t) "\"")
518       term)))
519
520 (defun notmuch-id-to-query (id)
521   "Return a query that matches the message with id ID."
522   (concat "id:" (notmuch-escape-boolean-term id)))
523
524 (defun notmuch-hex-encode (str)
525   "Hex-encode STR (e.g., as used by batch tagging).
526
527 This replaces spaces, percents, and double quotes in STR with
528 %NN where NN is the hexadecimal value of the character."
529   (replace-regexp-in-string
530    "[ %\"]" (lambda (match) (format "%%%02x" (aref match 0))) str))
531
532 (defun notmuch-common-do-stash (text)
533   "Common function to stash text in kill ring, and display in minibuffer."
534   (if text
535       (progn
536         (kill-new text)
537         (message "Stashed: %s" text))
538     ;; There is nothing to stash so stash an empty string so the user
539     ;; doesn't accidentally paste something else somewhere.
540     (kill-new "")
541     (message "Nothing to stash!")))
542
543 ;;; Generic Utilities
544
545 (defun notmuch-plist-delete (plist property)
546   (let (p)
547     (while plist
548       (unless (eq property (car plist))
549         (setq p (plist-put p (car plist) (cadr plist))))
550       (setq plist (cddr plist)))
551     p))
552
553 ;;; MML Utilities
554
555 (defun notmuch-match-content-type (t1 t2)
556   "Return t if t1 and t2 are matching content types.
557 Take wildcards into account."
558   (and (stringp t1)
559        (stringp t2)
560        (let ((st1 (split-string t1 "/"))
561              (st2 (split-string t2 "/")))
562          (if (or (string= (cadr st1) "*")
563                  (string= (cadr st2) "*"))
564              ;; Comparison of content types should be case insensitive.
565              (string= (downcase (car st1))
566                       (downcase (car st2)))
567            (string= (downcase t1)
568                     (downcase t2))))))
569
570 (defcustom notmuch-multipart/alternative-discouraged
571   '(;; Avoid HTML parts.
572     "text/html"
573     ;; multipart/related usually contain a text/html part and some
574     ;; associated graphics.
575     "multipart/related")
576   "Which mime types to hide by default for multipart messages.
577
578 Can either be a list of mime types (as strings) or a function
579 mapping a plist representing the current message to such a list.
580 See Info node `(notmuch-emacs) notmuch-show' for a sample function."
581   :group 'notmuch-show
582   :type '(radio (repeat :tag "MIME Types" string)
583                 (function :tag "Function")))
584
585 (defun notmuch-multipart/alternative-determine-discouraged (msg)
586   "Return the discouraged alternatives for the specified message."
587   ;; If a function, return the result of calling it.
588   (if (functionp notmuch-multipart/alternative-discouraged)
589       (funcall notmuch-multipart/alternative-discouraged msg)
590     ;; Otherwise simply return the value of the variable, which is
591     ;; assumed to be a list of discouraged alternatives. This is the
592     ;; default behaviour.
593     notmuch-multipart/alternative-discouraged))
594
595 (defun notmuch-multipart/alternative-choose (msg types)
596   "Return a list of preferred types from the given list of types
597 for this message, if present."
598   ;; Based on `mm-preferred-alternative-precedence'.
599   (let ((discouraged (notmuch-multipart/alternative-determine-discouraged msg))
600         (seq types))
601     (dolist (pref (reverse discouraged))
602       (dolist (elem (copy-sequence seq))
603         (when (string-match pref elem)
604           (setq seq (nconc (delete elem seq) (list elem))))))
605     seq))
606
607 (defun notmuch-parts-filter-by-type (parts type)
608   "Given a list of message parts, return a list containing the ones matching
609 the given type."
610   (cl-remove-if-not
611    (lambda (part) (notmuch-match-content-type (plist-get part :content-type) type))
612    parts))
613
614 (defun notmuch--get-bodypart-raw (msg part process-crypto binaryp cache)
615   (let* ((plist-elem (if binaryp :content-binary :content))
616          (data (or (plist-get part plist-elem)
617                    (with-temp-buffer
618                      ;; Emacs internally uses a UTF-8-like multibyte string
619                      ;; representation by default (regardless of the coding
620                      ;; system, which only affects how it goes from outside data
621                      ;; to this internal representation).  This *almost* never
622                      ;; matters.  Annoyingly, it does matter if we use this data
623                      ;; in an image descriptor, since Emacs will use its internal
624                      ;; data buffer directly and this multibyte representation
625                      ;; corrupts binary image formats.  Since the caller is
626                      ;; asking for binary data, a unibyte string is a more
627                      ;; appropriate representation anyway.
628                      (when binaryp
629                        (set-buffer-multibyte nil))
630                      (let ((args `("show" "--format=raw"
631                                    ,(format "--part=%s" (plist-get part :id))
632                                    ,@(and process-crypto '("--decrypt=true"))
633                                    ,(notmuch-id-to-query (plist-get msg :id))))
634                            (coding-system-for-read
635                             (if binaryp
636                                 'no-conversion
637                               (let ((coding-system
638                                      (mm-charset-to-coding-system
639                                       (plist-get part :content-charset))))
640                                 ;; Sadly,
641                                 ;; `mm-charset-to-coding-system' seems
642                                 ;; to return things that are not
643                                 ;; considered acceptable values for
644                                 ;; `coding-system-for-read'.
645                                 (if (coding-system-p coding-system)
646                                     coding-system
647                                   ;; RFC 2047 says that the default
648                                   ;; charset is US-ASCII. RFC6657
649                                   ;; complicates this somewhat.
650                                   'us-ascii)))))
651                        (apply #'notmuch--call-process
652                               notmuch-command nil '(t nil) nil args)
653                        (buffer-string))))))
654     (when (and cache data)
655       (plist-put part plist-elem data))
656     data))
657
658 (defun notmuch-get-bodypart-binary (msg part process-crypto &optional cache)
659   "Return the unprocessed content of PART in MSG as a unibyte string.
660
661 This returns the \"raw\" content of the given part after content
662 transfer decoding, but with no further processing (see the
663 discussion of --format=raw in man notmuch-show).  In particular,
664 this does no charset conversion.
665
666 If CACHE is non-nil, the content of this part will be saved in
667 MSG (if it isn't already)."
668   (notmuch--get-bodypart-raw msg part process-crypto t cache))
669
670 (defun notmuch-get-bodypart-text (msg part process-crypto &optional cache)
671   "Return the text content of PART in MSG.
672
673 This returns the content of the given part as a multibyte Lisp
674 string after performing content transfer decoding and any
675 necessary charset decoding.
676
677 If CACHE is non-nil, the content of this part will be saved in
678 MSG (if it isn't already)."
679   (notmuch--get-bodypart-raw msg part process-crypto nil cache))
680
681 (defun notmuch-mm-display-part-inline (msg part content-type process-crypto)
682   "Use the mm-decode/mm-view functions to display a part in the
683 current buffer, if possible."
684   (let ((display-buffer (current-buffer)))
685     (with-temp-buffer
686       ;; In case we already have :content, use it and tell mm-* that
687       ;; it's already been charset-decoded by using the fake
688       ;; `gnus-decoded' charset.  Otherwise, we'll fetch the binary
689       ;; part content and let mm-* decode it.
690       (let* ((have-content (plist-member part :content))
691              (charset (if have-content
692                           'gnus-decoded
693                         (plist-get part :content-charset)))
694              (handle (mm-make-handle (current-buffer)
695                                      `(,content-type (charset . ,charset)))))
696         ;; If the user wants the part inlined, insert the content and
697         ;; test whether we are able to inline it (which includes both
698         ;; capability and suitability tests).
699         (when (mm-inlined-p handle)
700           (if have-content
701               (insert (notmuch-get-bodypart-text msg part process-crypto))
702             (insert (notmuch-get-bodypart-binary msg part process-crypto)))
703           (when (mm-inlinable-p handle)
704             (set-buffer display-buffer)
705             (mm-display-part handle)
706             t))))))
707
708 ;;; Generic Utilities
709
710 ;; Converts a plist of headers to an alist of headers. The input plist should
711 ;; have symbols of the form :Header as keys, and the resulting alist will have
712 ;; symbols of the form 'Header as keys.
713 (defun notmuch-headers-plist-to-alist (plist)
714   (cl-loop for (key value . rest) on plist by #'cddr
715            collect (cons (intern (substring (symbol-name key) 1)) value)))
716
717 (defun notmuch-face-ensure-list-form (face)
718   "Return FACE in face list form.
719
720 If FACE is already a face list, it will be returned as-is.  If
721 FACE is a face name or face plist, it will be returned as a
722 single element face list."
723   (if (and (listp face) (not (keywordp (car face))))
724       face
725     (list face)))
726
727 (defun notmuch-apply-face (object face &optional below start end)
728   "Combine FACE into the 'face text property of OBJECT between START and END.
729
730 This function combines FACE with any existing faces between START
731 and END in OBJECT.  Attributes specified by FACE take precedence
732 over existing attributes unless BELOW is non-nil.
733
734 OBJECT may be a string, a buffer, or nil (which means the current
735 buffer).  If object is a string, START and END are 0-based;
736 otherwise they are buffer positions (integers or markers).  FACE
737 must be a face name (a symbol or string), a property list of face
738 attributes, or a list of these.  If START and/or END are omitted,
739 they default to the beginning/end of OBJECT.  For convenience
740 when applied to strings, this returns OBJECT."
741   ;; A face property can have three forms: a face name (a string or
742   ;; symbol), a property list, or a list of these two forms.  In the
743   ;; list case, the faces will be combined, with the earlier faces
744   ;; taking precedent.  Here we canonicalize everything to list form
745   ;; to make it easy to combine.
746   (let ((pos (cond (start start)
747                    ((stringp object) 0)
748                    (t 1)))
749         (end (cond (end end)
750                    ((stringp object) (length object))
751                    (t (1+ (buffer-size object)))))
752         (face-list (notmuch-face-ensure-list-form face)))
753     (while (< pos end)
754       (let* ((cur (get-text-property pos 'face object))
755              (cur-list (notmuch-face-ensure-list-form cur))
756              (new (cond ((null cur-list) face)
757                         (below (append cur-list face-list))
758                         (t (append face-list cur-list))))
759              (next (next-single-property-change pos 'face object end)))
760         (put-text-property pos next 'face new object)
761         (setq pos next))))
762   object)
763
764 (defun notmuch-map-text-property (start end prop func &optional object)
765   "Transform text property PROP using FUNC.
766
767 Applies FUNC to each distinct value of the text property PROP
768 between START and END of OBJECT, setting PROP to the value
769 returned by FUNC."
770   (while (< start end)
771     (let ((value (get-text-property start prop object))
772           (next (next-single-property-change start prop object end)))
773       (put-text-property start next prop (funcall func value) object)
774       (setq start next))))
775
776 ;;; Running Notmuch
777
778 (defun notmuch-logged-error (msg &optional extra)
779   "Log MSG and EXTRA to *Notmuch errors* and signal MSG.
780
781 This logs MSG and EXTRA to the *Notmuch errors* buffer and
782 signals MSG as an error.  If EXTRA is non-nil, text referring the
783 user to the *Notmuch errors* buffer will be appended to the
784 signaled error.  This function does not return."
785   (with-current-buffer (get-buffer-create "*Notmuch errors*")
786     (goto-char (point-max))
787     (unless (bobp)
788       (newline))
789     (save-excursion
790       (insert "[" (current-time-string) "]\n" msg)
791       (unless (bolp)
792         (newline))
793       (when extra
794         (insert extra)
795         (unless (bolp)
796           (newline)))))
797   (error "%s%s" msg (if extra " (see *Notmuch errors* for more details)" "")))
798
799 (defun notmuch-check-async-exit-status (proc msg &optional command err)
800   "If PROC exited abnormally, pop up an error buffer and signal an error.
801
802 This is a wrapper around `notmuch-check-exit-status' for
803 asynchronous process sentinels.  PROC and MSG must be the
804 arguments passed to the sentinel.  COMMAND and ERR, if provided,
805 are passed to `notmuch-check-exit-status'.  If COMMAND is not
806 provided, it is taken from `process-command'."
807   (let ((exit-status
808          (cl-case (process-status proc)
809            ((exit) (process-exit-status proc))
810            ((signal) msg))))
811     (when exit-status
812       (notmuch-check-exit-status exit-status
813                                  (or command (process-command proc))
814                                  nil err))))
815
816 (defun notmuch-check-exit-status (exit-status command &optional output err)
817   "If EXIT-STATUS is non-zero, pop up an error buffer and signal an error.
818
819 If EXIT-STATUS is non-zero, pop up a notmuch error buffer
820 describing the error and signal an Elisp error.  EXIT-STATUS must
821 be a number indicating the exit status code of a process or a
822 string describing the signal that terminated the process (such as
823 returned by `call-process').  COMMAND must be a list giving the
824 command and its arguments.  OUTPUT, if provided, is a string
825 giving the output of command.  ERR, if provided, is the error
826 output of command.  OUTPUT and ERR will be included in the error
827 message."
828   (cond
829    ((eq exit-status 0) t)
830    ((eq exit-status 20)
831     (notmuch-logged-error "notmuch CLI version mismatch
832 Emacs requested an older output format than supported by the notmuch CLI.
833 You may need to restart Emacs or upgrade your notmuch Emacs package."))
834    ((eq exit-status 21)
835     (notmuch-logged-error "notmuch CLI version mismatch
836 Emacs requested a newer output format than supported by the notmuch CLI.
837 You may need to restart Emacs or upgrade your notmuch package."))
838    (t
839     (pcase-let*
840         ((`(,command . ,args) command)
841          (command (if (equal (file-name-nondirectory command)
842                              notmuch-command)
843                       notmuch-command
844                     command))
845          (command-string
846           (mapconcat (lambda (arg)
847                        (shell-quote-argument
848                         (cond ((stringp arg) arg)
849                               ((symbolp arg) (symbol-name arg))
850                               (t "*UNKNOWN ARGUMENT*"))))
851                      (cons command args)
852                      " "))
853          (extra
854           (concat "command: " command-string "\n"
855                   (if (integerp exit-status)
856                       (format "exit status: %s\n" exit-status)
857                     (format "exit signal: %s\n" exit-status))
858                   (and err    (concat "stderr:\n" err))
859                   (and output (concat "stdout:\n" output)))))
860       (if err
861           ;; We have an error message straight from the CLI.
862           (notmuch-logged-error
863            (replace-regexp-in-string "[ \n\r\t\f]*\\'" "" err) extra)
864         ;; We only have combined output from the CLI; don't inundate
865         ;; the user with it.  Mimic `process-lines'.
866         (notmuch-logged-error (format "%s exited with status %s"
867                                       command exit-status)
868                               extra))
869       ;; `notmuch-logged-error' does not return.
870       ))))
871
872 (defmacro notmuch--apply-with-env (func &rest args)
873   `(let ((default-directory "~"))
874      (apply ,func ,@args)))
875
876 (defun notmuch--process-lines (program &rest args)
877   "Wrap process-lines, binding DEFAULT-DIRECTORY to a safe
878 default"
879   (notmuch--apply-with-env #'process-lines program args))
880
881 (defun notmuch--make-process (&rest args)
882   "Wrap make-process, binding DEFAULT-DIRECTORY to a safe
883 default"
884   (notmuch--apply-with-env #'make-process args))
885
886 (defun notmuch--call-process-region (start end program
887                                            &optional delete buffer display
888                                            &rest args)
889   "Wrap call-process-region, binding DEFAULT-DIRECTORY to a safe
890 default"
891   (notmuch--apply-with-env
892    #'call-process-region start end program delete buffer display args))
893
894 (defun notmuch--call-process (program &optional infile destination display &rest args)
895   "Wrap call-process, binding DEFAULT-DIRECTORY to a safe default"
896   (notmuch--apply-with-env #'call-process program infile destination display args))
897
898 (defun notmuch-call-notmuch--helper (destination args)
899   "Helper for synchronous notmuch invocation commands.
900
901 This wraps `call-process'.  DESTINATION has the same meaning as
902 for `call-process'.  ARGS is as described for
903 `notmuch-call-notmuch-process'."
904   (let (stdin-string)
905     (while (keywordp (car args))
906       (cl-case (car args)
907         (:stdin-string (setq stdin-string (cadr args))
908                        (setq args (cddr args)))
909         (otherwise
910          (error "Unknown keyword argument: %s" (car args)))))
911     (if (null stdin-string)
912         (apply #'notmuch--call-process notmuch-command nil destination nil args)
913       (insert stdin-string)
914       (apply #'notmuch--call-process-region (point-min) (point-max)
915              notmuch-command t destination nil args))))
916
917 (defun notmuch-call-notmuch-process (&rest args)
918   "Synchronously invoke `notmuch-command' with ARGS.
919
920 The caller may provide keyword arguments before ARGS.  Currently
921 supported keyword arguments are:
922
923   :stdin-string STRING - Write STRING to stdin
924
925 If notmuch exits with a non-zero status, output from the process
926 will appear in a buffer named \"*Notmuch errors*\" and an error
927 will be signaled."
928   (with-temp-buffer
929     (let ((status (notmuch-call-notmuch--helper t args)))
930       (notmuch-check-exit-status status (cons notmuch-command args)
931                                  (buffer-string)))))
932
933 (defun notmuch-call-notmuch-sexp (&rest args)
934   "Invoke `notmuch-command' with ARGS and return the parsed S-exp output.
935
936 This is equivalent to `notmuch-call-notmuch-process', but parses
937 notmuch's output as an S-expression and returns the parsed value.
938 Like `notmuch-call-notmuch-process', if notmuch exits with a
939 non-zero status, this will report its output and signal an
940 error."
941   (with-temp-buffer
942     (let ((err-file (make-temp-file "nmerr")))
943       (unwind-protect
944           (let ((status (notmuch-call-notmuch--helper (list t err-file) args))
945                 (err (with-temp-buffer
946                        (insert-file-contents err-file)
947                        (unless (eobp)
948                          (buffer-string)))))
949             (notmuch-check-exit-status status (cons notmuch-command args)
950                                        (buffer-string) err)
951             (goto-char (point-min))
952             (read (current-buffer)))
953         (delete-file err-file)))))
954
955 (defun notmuch-start-notmuch (name buffer sentinel &rest args)
956   "Start and return an asynchronous notmuch command.
957
958 This starts and returns an asynchronous process running
959 `notmuch-command' with ARGS.  The exit status is checked via
960 `notmuch-check-async-exit-status'.  Output written to stderr is
961 redirected and displayed when the process exits (even if the
962 process exits successfully).  NAME and BUFFER are the same as in
963 `start-process'.  SENTINEL is a process sentinel function to call
964 when the process exits, or nil for none.  The caller must *not*
965 invoke `set-process-sentinel' directly on the returned process,
966 as that will interfere with the handling of stderr and the exit
967 status."
968   (let* ((command (or (executable-find notmuch-command)
969                       (error "Command not found: %s" notmuch-command)))
970          (err-buffer (generate-new-buffer " *notmuch-stderr*"))
971          (proc (notmuch--make-process
972                 :name name
973                 :buffer buffer
974                 :command (cons command args)
975                 :connection-type 'pipe
976                 :stderr err-buffer))
977          (err-proc (get-buffer-process err-buffer)))
978     (process-put proc 'err-buffer err-buffer)
979     (process-put proc 'sub-sentinel sentinel)
980     (set-process-sentinel proc #'notmuch-start-notmuch-sentinel)
981     (set-process-sentinel err-proc #'notmuch-start-notmuch-error-sentinel)
982     proc))
983
984 (defun notmuch-start-notmuch-sentinel (proc event)
985   "Process sentinel function used by `notmuch-start-notmuch'."
986   (let* ((err-buffer (process-get proc 'err-buffer))
987          (err (and (buffer-live-p err-buffer)
988                    (not (zerop (buffer-size err-buffer)))
989                    (with-current-buffer err-buffer (buffer-string))))
990          (sub-sentinel (process-get proc 'sub-sentinel)))
991     (condition-case err
992         (progn
993           ;; Invoke the sub-sentinel, if any
994           (when sub-sentinel
995             (funcall sub-sentinel proc event))
996           ;; Check the exit status.  This will signal an error if the
997           ;; exit status is non-zero.  Don't do this if the process
998           ;; buffer is dead since that means Emacs killed the process
999           ;; and there's no point in telling the user that (but we
1000           ;; still check for and report stderr output below).
1001           (when (buffer-live-p (process-buffer proc))
1002             (notmuch-check-async-exit-status proc event nil err))
1003           ;; If that didn't signal an error, then any error output was
1004           ;; really warning output.  Show warnings, if any.
1005           (let ((warnings
1006                  (and err
1007                       (with-current-buffer err-buffer
1008                         (goto-char (point-min))
1009                         (end-of-line)
1010                         ;; Show first line; stuff remaining lines in the
1011                         ;; errors buffer.
1012                         (let ((l1 (buffer-substring (point-min) (point))))
1013                           (skip-chars-forward "\n")
1014                           (cons l1 (and (not (eobp))
1015                                         (buffer-substring (point)
1016                                                           (point-max)))))))))
1017             (when warnings
1018               (notmuch-logged-error (car warnings) (cdr warnings)))))
1019       (error
1020        ;; Emacs behaves strangely if an error escapes from a sentinel,
1021        ;; so turn errors into messages.
1022        (message "%s" (error-message-string err))))))
1023
1024 (defun notmuch-start-notmuch-error-sentinel (proc _event)
1025   (unless (process-live-p proc)
1026     (let ((buffer (process-buffer proc)))
1027       (when (buffer-live-p buffer)
1028         (kill-buffer buffer)))))
1029
1030 (defvar-local notmuch-show-process-crypto nil)
1031
1032 (defun notmuch--run-show (search-terms)
1033   "Return a list of threads of messages matching SEARCH-TERMS.
1034
1035 A thread is a forest or list of trees. A tree is a two element
1036 list where the first element is a message, and the second element
1037 is a possibly empty forest of replies."
1038   (let ((args '("show" "--format=sexp" "--format-version=5")))
1039     (when notmuch-show-process-crypto
1040       (setq args (append args '("--decrypt=true"))))
1041     (setq args (append args search-terms))
1042     (apply #'notmuch-call-notmuch-sexp args)))
1043
1044 ;;; Generic Utilities
1045
1046 (defun notmuch-interactive-region ()
1047   "Return the bounds of the current interactive region.
1048
1049 This returns (BEG END), where BEG and END are the bounds of the
1050 region if the region is active, or both `point' otherwise."
1051   (if (region-active-p)
1052       (list (region-beginning) (region-end))
1053     (list (point) (point))))
1054
1055 (define-obsolete-function-alias
1056   'notmuch-search-interactive-region
1057   'notmuch-interactive-region
1058   "notmuch 0.29")
1059
1060 (defun notmuch--inline-override-types ()
1061   "Override mm-inline-override-types to stop application/*
1062 parts from being displayed unless the user has customized
1063 it themselves."
1064   (if (equal mm-inline-override-types
1065              (eval (car (get 'mm-inline-override-types 'standard-value))))
1066       (cons "application/.*" mm-inline-override-types)
1067     mm-inline-override-types))
1068 ;;; _
1069
1070 (provide 'notmuch-lib)
1071
1072 ;;; notmuch-lib.el ends here