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