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