]> git.notmuchmail.org Git - notmuch/blob - emacs/notmuch-lib.el
notmuch (0.38.2-1.1) unstable; urgency=medium
[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             (plist-put part :undisplayer (mm-handle-undisplayer handle))
707             t))))))
708
709 ;;; Generic Utilities
710
711 ;; Converts a plist of headers to an alist of headers. The input plist should
712 ;; have symbols of the form :Header as keys, and the resulting alist will have
713 ;; symbols of the form 'Header as keys.
714 (defun notmuch-headers-plist-to-alist (plist)
715   (cl-loop for (key value . rest) on plist by #'cddr
716            collect (cons (intern (substring (symbol-name key) 1)) value)))
717
718 (defun notmuch-face-ensure-list-form (face)
719   "Return FACE in face list form.
720
721 If FACE is already a face list, it will be returned as-is.  If
722 FACE is a face name or face plist, it will be returned as a
723 single element face list."
724   (if (and (listp face) (not (keywordp (car face))))
725       face
726     (list face)))
727
728 (defun notmuch-apply-face (object face &optional below start end)
729   "Combine FACE into the 'face text property of OBJECT between START and END.
730
731 This function combines FACE with any existing faces between START
732 and END in OBJECT.  Attributes specified by FACE take precedence
733 over existing attributes unless BELOW is non-nil.
734
735 OBJECT may be a string, a buffer, or nil (which means the current
736 buffer).  If object is a string, START and END are 0-based;
737 otherwise they are buffer positions (integers or markers).  FACE
738 must be a face name (a symbol or string), a property list of face
739 attributes, or a list of these.  If START and/or END are omitted,
740 they default to the beginning/end of OBJECT.  For convenience
741 when applied to strings, this returns OBJECT."
742   ;; A face property can have three forms: a face name (a string or
743   ;; symbol), a property list, or a list of these two forms.  In the
744   ;; list case, the faces will be combined, with the earlier faces
745   ;; taking precedent.  Here we canonicalize everything to list form
746   ;; to make it easy to combine.
747   (let ((pos (cond (start start)
748                    ((stringp object) 0)
749                    (t 1)))
750         (end (cond (end end)
751                    ((stringp object) (length object))
752                    (t (1+ (buffer-size object)))))
753         (face-list (notmuch-face-ensure-list-form face)))
754     (while (< pos end)
755       (let* ((cur (get-text-property pos 'face object))
756              (cur-list (notmuch-face-ensure-list-form cur))
757              (new (cond ((null cur-list) face)
758                         (below (append cur-list face-list))
759                         (t (append face-list cur-list))))
760              (next (next-single-property-change pos 'face object end)))
761         (put-text-property pos next 'face new object)
762         (setq pos next))))
763   object)
764
765 (defun notmuch-map-text-property (start end prop func &optional object)
766   "Transform text property PROP using FUNC.
767
768 Applies FUNC to each distinct value of the text property PROP
769 between START and END of OBJECT, setting PROP to the value
770 returned by FUNC."
771   (while (< start end)
772     (let ((value (get-text-property start prop object))
773           (next (next-single-property-change start prop object end)))
774       (put-text-property start next prop (funcall func value) object)
775       (setq start next))))
776
777 ;;; Running Notmuch
778
779 (defun notmuch-logged-error (msg &optional extra)
780   "Log MSG and EXTRA to *Notmuch errors* and signal MSG.
781
782 This logs MSG and EXTRA to the *Notmuch errors* buffer and
783 signals MSG as an error.  If EXTRA is non-nil, text referring the
784 user to the *Notmuch errors* buffer will be appended to the
785 signaled error.  This function does not return."
786   (with-current-buffer (get-buffer-create "*Notmuch errors*")
787     (goto-char (point-max))
788     (unless (bobp)
789       (newline))
790     (save-excursion
791       (insert "[" (current-time-string) "]\n" msg)
792       (unless (bolp)
793         (newline))
794       (when extra
795         (insert extra)
796         (unless (bolp)
797           (newline)))))
798   (error "%s%s" msg (if extra " (see *Notmuch errors* for more details)" "")))
799
800 (defun notmuch-check-async-exit-status (proc msg &optional command err)
801   "If PROC exited abnormally, pop up an error buffer and signal an error.
802
803 This is a wrapper around `notmuch-check-exit-status' for
804 asynchronous process sentinels.  PROC and MSG must be the
805 arguments passed to the sentinel.  COMMAND and ERR, if provided,
806 are passed to `notmuch-check-exit-status'.  If COMMAND is not
807 provided, it is taken from `process-command'."
808   (let ((exit-status
809          (cl-case (process-status proc)
810            ((exit) (process-exit-status proc))
811            ((signal) msg))))
812     (when exit-status
813       (notmuch-check-exit-status exit-status
814                                  (or command (process-command proc))
815                                  nil err))))
816
817 (defun notmuch-check-exit-status (exit-status command &optional output err)
818   "If EXIT-STATUS is non-zero, pop up an error buffer and signal an error.
819
820 If EXIT-STATUS is non-zero, pop up a notmuch error buffer
821 describing the error and signal an Elisp error.  EXIT-STATUS must
822 be a number indicating the exit status code of a process or a
823 string describing the signal that terminated the process (such as
824 returned by `call-process').  COMMAND must be a list giving the
825 command and its arguments.  OUTPUT, if provided, is a string
826 giving the output of command.  ERR, if provided, is the error
827 output of command.  OUTPUT and ERR will be included in the error
828 message."
829   (cond
830    ((eq exit-status 0) t)
831    ((eq exit-status 20)
832     (notmuch-logged-error "notmuch CLI version mismatch
833 Emacs requested an older output format than supported by the notmuch CLI.
834 You may need to restart Emacs or upgrade your notmuch Emacs package."))
835    ((eq exit-status 21)
836     (notmuch-logged-error "notmuch CLI version mismatch
837 Emacs requested a newer output format than supported by the notmuch CLI.
838 You may need to restart Emacs or upgrade your notmuch package."))
839    (t
840     (pcase-let*
841         ((`(,command . ,args) command)
842          (command (if (equal (file-name-nondirectory command)
843                              notmuch-command)
844                       notmuch-command
845                     command))
846          (command-string
847           (mapconcat (lambda (arg)
848                        (shell-quote-argument
849                         (cond ((stringp arg) arg)
850                               ((symbolp arg) (symbol-name arg))
851                               (t "*UNKNOWN ARGUMENT*"))))
852                      (cons command args)
853                      " "))
854          (extra
855           (concat "command: " command-string "\n"
856                   (if (integerp exit-status)
857                       (format "exit status: %s\n" exit-status)
858                     (format "exit signal: %s\n" exit-status))
859                   (and err    (concat "stderr:\n" err))
860                   (and output (concat "stdout:\n" output)))))
861       (if err
862           ;; We have an error message straight from the CLI.
863           (notmuch-logged-error
864            (replace-regexp-in-string "[ \n\r\t\f]*\\'" "" err) extra)
865         ;; We only have combined output from the CLI; don't inundate
866         ;; the user with it.  Mimic `process-lines'.
867         (notmuch-logged-error (format "%s exited with status %s"
868                                       command exit-status)
869                               extra))
870       ;; `notmuch-logged-error' does not return.
871       ))))
872
873 (defmacro notmuch--apply-with-env (func &rest args)
874   `(let ((default-directory "~"))
875      (apply ,func ,@args)))
876
877 (defun notmuch--process-lines (program &rest args)
878   "Wrap process-lines, binding DEFAULT-DIRECTORY to a safe
879 default"
880   (notmuch--apply-with-env #'process-lines program args))
881
882 (defun notmuch--make-process (&rest args)
883   "Wrap make-process, binding DEFAULT-DIRECTORY to a safe
884 default"
885   (notmuch--apply-with-env #'make-process args))
886
887 (defun notmuch--call-process-region (start end program
888                                            &optional delete buffer display
889                                            &rest args)
890   "Wrap call-process-region, binding DEFAULT-DIRECTORY to a safe
891 default"
892   (notmuch--apply-with-env
893    #'call-process-region start end program delete buffer display args))
894
895 (defun notmuch--call-process (program &optional infile destination display &rest args)
896   "Wrap call-process, binding DEFAULT-DIRECTORY to a safe default"
897   (notmuch--apply-with-env #'call-process program infile destination display args))
898
899 (defun notmuch-call-notmuch--helper (destination args)
900   "Helper for synchronous notmuch invocation commands.
901
902 This wraps `call-process'.  DESTINATION has the same meaning as
903 for `call-process'.  ARGS is as described for
904 `notmuch-call-notmuch-process'."
905   (let (stdin-string)
906     (while (keywordp (car args))
907       (cl-case (car args)
908         (:stdin-string (setq stdin-string (cadr args))
909                        (setq args (cddr args)))
910         (otherwise
911          (error "Unknown keyword argument: %s" (car args)))))
912     (if (null stdin-string)
913         (apply #'notmuch--call-process notmuch-command nil destination nil args)
914       (insert stdin-string)
915       (apply #'notmuch--call-process-region (point-min) (point-max)
916              notmuch-command t destination nil args))))
917
918 (defun notmuch-call-notmuch-process (&rest args)
919   "Synchronously invoke `notmuch-command' with ARGS.
920
921 The caller may provide keyword arguments before ARGS.  Currently
922 supported keyword arguments are:
923
924   :stdin-string STRING - Write STRING to stdin
925
926 If notmuch exits with a non-zero status, output from the process
927 will appear in a buffer named \"*Notmuch errors*\" and an error
928 will be signaled."
929   (with-temp-buffer
930     (let ((status (notmuch-call-notmuch--helper t args)))
931       (notmuch-check-exit-status status (cons notmuch-command args)
932                                  (buffer-string)))))
933
934 (defun notmuch-call-notmuch-sexp (&rest args)
935   "Invoke `notmuch-command' with ARGS and return the parsed S-exp output.
936
937 This is equivalent to `notmuch-call-notmuch-process', but parses
938 notmuch's output as an S-expression and returns the parsed value.
939 Like `notmuch-call-notmuch-process', if notmuch exits with a
940 non-zero status, this will report its output and signal an
941 error."
942   (with-temp-buffer
943     (let ((err-file (make-temp-file "nmerr")))
944       (unwind-protect
945           (let ((status (notmuch-call-notmuch--helper (list t err-file) args))
946                 (err (with-temp-buffer
947                        (insert-file-contents err-file)
948                        (unless (eobp)
949                          (buffer-string)))))
950             (notmuch-check-exit-status status (cons notmuch-command args)
951                                        (buffer-string) err)
952             (goto-char (point-min))
953             (read (current-buffer)))
954         (delete-file err-file)))))
955
956 (defun notmuch-start-notmuch (name buffer sentinel &rest args)
957   "Start and return an asynchronous notmuch command.
958
959 This starts and returns an asynchronous process running
960 `notmuch-command' with ARGS.  The exit status is checked via
961 `notmuch-check-async-exit-status'.  Output written to stderr is
962 redirected and displayed when the process exits (even if the
963 process exits successfully).  NAME and BUFFER are the same as in
964 `start-process'.  SENTINEL is a process sentinel function to call
965 when the process exits, or nil for none.  The caller must *not*
966 invoke `set-process-sentinel' directly on the returned process,
967 as that will interfere with the handling of stderr and the exit
968 status."
969   (let* ((command (or (executable-find notmuch-command)
970                       (error "Command not found: %s" notmuch-command)))
971          (err-buffer (generate-new-buffer " *notmuch-stderr*"))
972          (proc (notmuch--make-process
973                 :name name
974                 :buffer buffer
975                 :command (cons command args)
976                 :connection-type 'pipe
977                 :stderr err-buffer))
978          (err-proc (get-buffer-process err-buffer)))
979     (process-put proc 'err-buffer err-buffer)
980     (process-put proc 'sub-sentinel sentinel)
981     (set-process-sentinel proc #'notmuch-start-notmuch-sentinel)
982     (set-process-sentinel err-proc #'notmuch-start-notmuch-error-sentinel)
983     proc))
984
985 (defun notmuch-start-notmuch-sentinel (proc event)
986   "Process sentinel function used by `notmuch-start-notmuch'."
987   (let* ((err-buffer (process-get proc 'err-buffer))
988          (err (and (buffer-live-p err-buffer)
989                    (not (zerop (buffer-size err-buffer)))
990                    (with-current-buffer err-buffer (buffer-string))))
991          (sub-sentinel (process-get proc 'sub-sentinel)))
992     (condition-case err
993         (progn
994           ;; Invoke the sub-sentinel, if any
995           (when sub-sentinel
996             (funcall sub-sentinel proc event))
997           ;; Check the exit status.  This will signal an error if the
998           ;; exit status is non-zero.  Don't do this if the process
999           ;; buffer is dead since that means Emacs killed the process
1000           ;; and there's no point in telling the user that (but we
1001           ;; still check for and report stderr output below).
1002           (when (buffer-live-p (process-buffer proc))
1003             (notmuch-check-async-exit-status proc event nil err))
1004           ;; If that didn't signal an error, then any error output was
1005           ;; really warning output.  Show warnings, if any.
1006           (let ((warnings
1007                  (and err
1008                       (with-current-buffer err-buffer
1009                         (goto-char (point-min))
1010                         (end-of-line)
1011                         ;; Show first line; stuff remaining lines in the
1012                         ;; errors buffer.
1013                         (let ((l1 (buffer-substring (point-min) (point))))
1014                           (skip-chars-forward "\n")
1015                           (cons l1 (and (not (eobp))
1016                                         (buffer-substring (point)
1017                                                           (point-max)))))))))
1018             (when warnings
1019               (notmuch-logged-error (car warnings) (cdr warnings)))))
1020       (error
1021        ;; Emacs behaves strangely if an error escapes from a sentinel,
1022        ;; so turn errors into messages.
1023        (message "%s" (error-message-string err))))))
1024
1025 (defun notmuch-start-notmuch-error-sentinel (proc _event)
1026   (unless (process-live-p proc)
1027     (let ((buffer (process-buffer proc)))
1028       (when (buffer-live-p buffer)
1029         (kill-buffer buffer)))))
1030
1031 (defvar-local notmuch-show-process-crypto nil)
1032
1033 (defun notmuch--run-show (search-terms &optional duplicate)
1034   "Return a list of threads of messages matching SEARCH-TERMS.
1035
1036 A thread is a forest or list of trees. A tree is a two element
1037 list where the first element is a message, and the second element
1038 is a possibly empty forest of replies."
1039   (let ((args '("show" "--format=sexp" "--format-version=5")))
1040     (when notmuch-show-process-crypto
1041       (setq args (append args '("--decrypt=true"))))
1042     (when duplicate
1043       (setq args (append args (list (format "--duplicate=%d" duplicate)))))
1044     (setq args (append args search-terms))
1045     (apply #'notmuch-call-notmuch-sexp args)))
1046
1047 ;;; Generic Utilities
1048
1049 (defun notmuch-interactive-region ()
1050   "Return the bounds of the current interactive region.
1051
1052 This returns (BEG END), where BEG and END are the bounds of the
1053 region if the region is active, or both `point' otherwise."
1054   (if (region-active-p)
1055       (list (region-beginning) (region-end))
1056     (list (point) (point))))
1057
1058 (define-obsolete-function-alias
1059   'notmuch-search-interactive-region
1060   'notmuch-interactive-region
1061   "notmuch 0.29")
1062
1063 (defun notmuch--inline-override-types ()
1064   "Override mm-inline-override-types to stop application/*
1065 parts from being displayed unless the user has customized
1066 it themselves."
1067   (if (equal mm-inline-override-types
1068              (eval (car (get 'mm-inline-override-types 'standard-value))))
1069       (cons "application/.*" mm-inline-override-types)
1070     mm-inline-override-types))
1071 ;;; _
1072
1073 (provide 'notmuch-lib)
1074
1075 ;;; notmuch-lib.el ends here