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