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