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