]> git.notmuchmail.org Git - notmuch/blob - emacs/notmuch-lib.el
emacs: Move `notmuch-call-notmuch-process' to notmuch-lib
[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 (defvar notmuch-command "notmuch"
29   "Command to run the notmuch binary.")
30
31 (defgroup notmuch nil
32   "Notmuch mail reader for Emacs."
33   :group 'mail)
34
35 (defgroup notmuch-hello nil
36   "Overview of saved searches, tags, etc."
37   :group 'notmuch)
38
39 (defgroup notmuch-search nil
40   "Searching and sorting mail."
41   :group 'notmuch)
42
43 (defgroup notmuch-show nil
44   "Showing messages and threads."
45   :group 'notmuch)
46
47 (defgroup notmuch-send nil
48   "Sending messages from Notmuch."
49   :group 'notmuch)
50
51 (custom-add-to-group 'notmuch-send 'message 'custom-group)
52
53 (defgroup notmuch-crypto nil
54   "Processing and display of cryptographic MIME parts."
55   :group 'notmuch)
56
57 (defgroup notmuch-hooks nil
58   "Running custom code on well-defined occasions."
59   :group 'notmuch)
60
61 (defgroup notmuch-external nil
62   "Running external commands from within Notmuch."
63   :group 'notmuch)
64
65 (defgroup notmuch-faces nil
66   "Graphical attributes for displaying text"
67   :group 'notmuch)
68
69 (defcustom notmuch-search-oldest-first t
70   "Show the oldest mail first when searching.
71
72 This variable defines the default sort order for displaying
73 search results. Note that any filtered searches created by
74 `notmuch-search-filter' retain the search order of the parent
75 search."
76   :type 'boolean
77   :group 'notmuch-search)
78
79 (defcustom notmuch-poll-script nil
80   "An external script to incorporate new mail into the notmuch database.
81
82 This variable controls the action invoked by
83 `notmuch-search-poll-and-refresh-view' and
84 `notmuch-hello-poll-and-update' (each have a default keybinding
85 of 'G') to incorporate new mail into the notmuch database.
86
87 If set to nil (the default), new mail is processed by invoking
88 \"notmuch new\". Otherwise, this should be set to a string that
89 gives the name of an external script that processes new mail. If
90 set to the empty string, no command will be run.
91
92 The external script could do any of the following depending on
93 the user's needs:
94
95 1. Invoke a program to transfer mail to the local mail store
96 2. Invoke \"notmuch new\" to incorporate the new mail
97 3. Invoke one or more \"notmuch tag\" commands to classify the mail
98
99 Note that the recommended way of achieving the same is using
100 \"notmuch new\" hooks."
101   :type '(choice (const :tag "notmuch new" nil)
102                  (const :tag "Disabled" "")
103                  (string :tag "Custom script"))
104   :group 'notmuch-external)
105
106 ;;
107
108 (defvar notmuch-search-history nil
109   "Variable to store notmuch searches history.")
110
111 (defcustom notmuch-saved-searches '(("inbox" . "tag:inbox")
112                                     ("unread" . "tag:unread"))
113   "A list of saved searches to display."
114   :type '(alist :key-type string :value-type string)
115   :group 'notmuch-hello)
116
117 (defcustom notmuch-archive-tags '("-inbox")
118   "List of tag changes to apply to a message or a thread when it is archived.
119
120 Tags starting with \"+\" (or not starting with either \"+\" or
121 \"-\") in the list will be added, and tags starting with \"-\"
122 will be removed from the message or thread being archived.
123
124 For example, if you wanted to remove an \"inbox\" tag and add an
125 \"archived\" tag, you would set:
126     (\"-inbox\" \"+archived\")"
127   :type '(repeat string)
128   :group 'notmuch-search
129   :group 'notmuch-show)
130
131 (defvar notmuch-common-keymap
132   (let ((map (make-sparse-keymap)))
133     (define-key map "?" 'notmuch-help)
134     (define-key map "q" 'notmuch-kill-this-buffer)
135     (define-key map "s" 'notmuch-search)
136     (define-key map "z" 'notmuch-tree)
137     (define-key map "m" 'notmuch-mua-new-mail)
138     (define-key map "=" 'notmuch-refresh-this-buffer)
139     (define-key map "G" 'notmuch-poll-and-refresh-this-buffer)
140     map)
141   "Keymap shared by all notmuch modes.")
142
143 ;; By default clicking on a button does not select the window
144 ;; containing the button (as opposed to clicking on a widget which
145 ;; does). This means that the button action is then executed in the
146 ;; current selected window which can cause problems if the button
147 ;; changes the buffer (e.g., id: links) or moves point.
148 ;;
149 ;; This provides a button type which overrides mouse-action so that
150 ;; the button's window is selected before the action is run. Other
151 ;; notmuch buttons can get the same behaviour by inheriting from this
152 ;; button type.
153 (define-button-type 'notmuch-button-type
154   'mouse-action (lambda (button)
155                   (select-window (posn-window (event-start last-input-event)))
156                   (button-activate button)))
157
158 (defun notmuch-command-to-string (&rest args)
159   "Synchronously invoke \"notmuch\" with the given list of arguments.
160
161 If notmuch exits with a non-zero status, output from the process
162 will appear in a buffer named \"*Notmuch errors*\" and an error
163 will be signaled.
164
165 Otherwise the output will be returned"
166   (with-temp-buffer
167     (let* ((status (apply #'call-process notmuch-command nil t nil args))
168            (output (buffer-string)))
169       (notmuch-check-exit-status status (cons notmuch-command args) output)
170       output)))
171
172 (defun notmuch-version ()
173   "Return a string with the notmuch version number."
174   (let ((long-string
175          ;; Trim off the trailing newline.
176          (substring (notmuch-command-to-string "--version") 0 -1)))
177     (if (string-match "^notmuch\\( version\\)? \\(.*\\)$"
178                       long-string)
179         (match-string 2 long-string)
180       "unknown")))
181
182 (defun notmuch-config-get (item)
183   "Return a value from the notmuch configuration."
184   ;; Trim off the trailing newline
185   (substring (notmuch-command-to-string "config" "get" item) 0 -1))
186
187 (defun notmuch-database-path ()
188   "Return the database.path value from the notmuch configuration."
189   (notmuch-config-get "database.path"))
190
191 (defun notmuch-user-name ()
192   "Return the user.name value from the notmuch configuration."
193   (notmuch-config-get "user.name"))
194
195 (defun notmuch-user-primary-email ()
196   "Return the user.primary_email value from the notmuch configuration."
197   (notmuch-config-get "user.primary_email"))
198
199 (defun notmuch-user-other-email ()
200   "Return the user.other_email value (as a list) from the notmuch configuration."
201   (split-string (notmuch-config-get "user.other_email") "\n"))
202
203 (defun notmuch-poll ()
204   "Run \"notmuch new\" or an external script to import mail.
205
206 Invokes `notmuch-poll-script', \"notmuch new\", or does nothing
207 depending on the value of `notmuch-poll-script'."
208   (interactive)
209   (if (stringp notmuch-poll-script)
210       (unless (string= notmuch-poll-script "")
211         (call-process notmuch-poll-script nil nil))
212     (call-process notmuch-command nil nil nil "new")))
213
214 (defun notmuch-kill-this-buffer ()
215   "Kill the current buffer."
216   (interactive)
217   (kill-buffer (current-buffer)))
218
219 (defun notmuch-documentation-first-line (symbol)
220   "Return the first line of the documentation string for SYMBOL."
221   (let ((doc (documentation symbol)))
222     (if doc
223         (with-temp-buffer
224           (insert (documentation symbol t))
225           (goto-char (point-min))
226           (let ((beg (point)))
227             (end-of-line)
228             (buffer-substring beg (point))))
229       "")))
230
231 (defun notmuch-prefix-key-description (key)
232   "Given a prefix key code, return a human-readable string representation.
233
234 This is basically just `format-kbd-macro' but we also convert ESC to M-."
235   (let ((desc (format-kbd-macro (vector key))))
236     (if (string= desc "ESC")
237         "M-"
238       (concat desc " "))))
239
240 (defun notmuch-describe-keymap (keymap ua-keys &optional prefix tail)
241   "Return a list of strings, each describing one binding in KEYMAP.
242
243 Each string gives a human-readable description of the key and a
244 one-line description of the bound function.  See `notmuch-help'
245 for an overview of how this documentation is extracted.
246
247 UA-KEYS should be a key sequence bound to `universal-argument'.
248 It will be used to describe bindings of commands that support a
249 prefix argument.  PREFIX and TAIL are used internally."
250   (map-keymap
251    (lambda (key binding)
252      (cond ((mouse-event-p key) nil)
253            ((keymapp binding)
254             (setq tail
255                   (notmuch-describe-keymap
256                    binding ua-keys (notmuch-prefix-key-description key) tail)))
257            (t
258             (when (and ua-keys (symbolp binding)
259                        (get binding 'notmuch-prefix-doc))
260               ;; Documentation for prefixed command
261               (let ((ua-desc (key-description ua-keys)))
262                 (push (concat ua-desc " " prefix (format-kbd-macro (vector key))
263                               "\t" (get binding 'notmuch-prefix-doc))
264                       tail)))
265             ;; Documentation for command
266             (push (concat prefix (format-kbd-macro (vector key)) "\t"
267                           (or (and (symbolp binding) (get binding 'notmuch-doc))
268                               (notmuch-documentation-first-line binding)))
269                   tail))))
270    keymap)
271   tail)
272
273 (defun notmuch-substitute-command-keys (doc)
274   "Like `substitute-command-keys' but with documentation, not function names."
275   (let ((beg 0))
276     (while (string-match "\\\\{\\([^}[:space:]]*\\)}" doc beg)
277       (let* ((keymap-name (substring doc (match-beginning 1) (match-end 1)))
278              (keymap (symbol-value (intern keymap-name)))
279              (ua-keys (where-is-internal 'universal-argument keymap t))
280              (desc-list (notmuch-describe-keymap keymap ua-keys))
281              (desc (mapconcat #'identity desc-list "\n")))
282         (setq doc (replace-match desc 1 1 doc)))
283       (setq beg (match-end 0)))
284     doc))
285
286 (defun notmuch-help ()
287   "Display help for the current notmuch mode.
288
289 This is similar to `describe-function' for the current major
290 mode, but bindings tables are shown with documentation strings
291 rather than command names.  By default, this uses the first line
292 of each command's documentation string.  A command can override
293 this by setting the 'notmuch-doc property of its command symbol.
294 A command that supports a prefix argument can explicitly document
295 its prefixed behavior by setting the 'notmuch-prefix-doc property
296 of its command symbol."
297   (interactive)
298   (let* ((mode major-mode)
299          (doc (substitute-command-keys (notmuch-substitute-command-keys (documentation mode t)))))
300     (with-current-buffer (generate-new-buffer "*notmuch-help*")
301       (insert doc)
302       (goto-char (point-min))
303       (set-buffer-modified-p nil)
304       (view-buffer (current-buffer) 'kill-buffer-if-not-modified))))
305
306 (defvar notmuch-buffer-refresh-function nil
307   "Function to call to refresh the current buffer.")
308 (make-variable-buffer-local 'notmuch-buffer-refresh-function)
309
310 (defun notmuch-refresh-this-buffer ()
311   "Refresh the current buffer."
312   (interactive)
313   (when notmuch-buffer-refresh-function
314     (if (commandp notmuch-buffer-refresh-function)
315         ;; Pass prefix argument, etc.
316         (call-interactively notmuch-buffer-refresh-function)
317       (funcall notmuch-buffer-refresh-function))))
318
319 (defun notmuch-poll-and-refresh-this-buffer ()
320   "Invoke `notmuch-poll' to import mail, then refresh the current buffer."
321   (interactive)
322   (notmuch-poll)
323   (notmuch-refresh-this-buffer))
324
325 (defun notmuch-prettify-subject (subject)
326   ;; This function is used by `notmuch-search-process-filter' which
327   ;; requires that we not disrupt its' matching state.
328   (save-match-data
329     (if (and subject
330              (string-match "^[ \t]*$" subject))
331         "[No Subject]"
332       subject)))
333
334 (defun notmuch-sanitize (str)
335   "Sanitize control character in STR.
336
337 This includes newlines, tabs, and other funny characters."
338   (replace-regexp-in-string "[[:cntrl:]\x7f\u2028\u2029]+" " " str))
339
340 (defun notmuch-escape-boolean-term (term)
341   "Escape a boolean term for use in a query.
342
343 The caller is responsible for prepending the term prefix and a
344 colon.  This performs minimal escaping in order to produce
345 user-friendly queries."
346
347   (save-match-data
348     (if (or (equal term "")
349             (string-match "[ ()]\\|^\"" term))
350         ;; Requires escaping
351         (concat "\"" (replace-regexp-in-string "\"" "\"\"" term t t) "\"")
352       term)))
353
354 (defun notmuch-id-to-query (id)
355   "Return a query that matches the message with id ID."
356   (concat "id:" (notmuch-escape-boolean-term id)))
357
358 ;;
359
360 (defun notmuch-common-do-stash (text)
361   "Common function to stash text in kill ring, and display in minibuffer."
362   (if text
363       (progn
364         (kill-new text)
365         (message "Stashed: %s" text))
366     ;; There is nothing to stash so stash an empty string so the user
367     ;; doesn't accidentally paste something else somewhere.
368     (kill-new "")
369     (message "Nothing to stash!")))
370
371 ;;
372
373 (defun notmuch-remove-if-not (predicate list)
374   "Return a copy of LIST with all items not satisfying PREDICATE removed."
375   (let (out)
376     (while list
377       (when (funcall predicate (car list))
378         (push (car list) out))
379       (setq list (cdr list)))
380     (nreverse out)))
381
382 (defun notmuch-split-content-type (content-type)
383   "Split content/type into 'content' and 'type'"
384   (split-string content-type "/"))
385
386 (defun notmuch-match-content-type (t1 t2)
387   "Return t if t1 and t2 are matching content types, taking wildcards into account"
388   (let ((st1 (notmuch-split-content-type t1))
389         (st2 (notmuch-split-content-type t2)))
390     (if (or (string= (cadr st1) "*")
391             (string= (cadr st2) "*"))
392         ;; Comparison of content types should be case insensitive.
393         (string= (downcase (car st1)) (downcase (car st2)))
394       (string= (downcase t1) (downcase t2)))))
395
396 (defvar notmuch-multipart/alternative-discouraged
397   '(
398     ;; Avoid HTML parts.
399     "text/html"
400     ;; multipart/related usually contain a text/html part and some associated graphics.
401     "multipart/related"
402     ))
403
404 (defun notmuch-multipart/alternative-choose (types)
405   "Return a list of preferred types from the given list of types"
406   ;; Based on `mm-preferred-alternative-precedence'.
407   (let ((seq types))
408     (dolist (pref (reverse notmuch-multipart/alternative-discouraged))
409       (dolist (elem (copy-sequence seq))
410         (when (string-match pref elem)
411           (setq seq (nconc (delete elem seq) (list elem))))))
412     seq))
413
414 (defun notmuch-parts-filter-by-type (parts type)
415   "Given a list of message parts, return a list containing the ones matching
416 the given type."
417   (remove-if-not
418    (lambda (part) (notmuch-match-content-type (plist-get part :content-type) type))
419    parts))
420
421 ;; Helper for parts which are generally not included in the default
422 ;; SEXP output.
423 (defun notmuch-get-bodypart-internal (query part-number process-crypto)
424   (let ((args '("show" "--format=raw"))
425         (part-arg (format "--part=%s" part-number)))
426     (setq args (append args (list part-arg)))
427     (if process-crypto
428         (setq args (append args '("--decrypt"))))
429     (setq args (append args (list query)))
430     (with-temp-buffer
431       (let ((coding-system-for-read 'no-conversion))
432         (progn
433           (apply 'call-process (append (list notmuch-command nil (list t nil) nil) args))
434           (buffer-string))))))
435
436 (defun notmuch-get-bodypart-content (msg part nth process-crypto)
437   (or (plist-get part :content)
438       (notmuch-get-bodypart-internal (notmuch-id-to-query (plist-get msg :id)) nth process-crypto)))
439
440 ;; Workaround: The call to `mm-display-part' below triggers a bug in
441 ;; Emacs 24 if it attempts to use the shr renderer to display an HTML
442 ;; part with images in it (demonstrated in 24.1 and 24.2 on Debian and
443 ;; Fedora 17, though unreproducable in other configurations).
444 ;; `mm-shr' references the variable `gnus-inhibit-images' without
445 ;; first loading gnus-art, which defines it, resulting in a
446 ;; void-variable error.  Hence, we advise `mm-shr' to ensure gnus-art
447 ;; is loaded.
448 (if (>= emacs-major-version 24)
449     (defadvice mm-shr (before load-gnus-arts activate)
450       (require 'gnus-art nil t)
451       (ad-disable-advice 'mm-shr 'before 'load-gnus-arts)))
452
453 (defun notmuch-mm-display-part-inline (msg part nth content-type process-crypto)
454   "Use the mm-decode/mm-view functions to display a part in the
455 current buffer, if possible."
456   (let ((display-buffer (current-buffer)))
457     (with-temp-buffer
458       ;; In case there is :content, the content string is already converted
459       ;; into emacs internal format. `gnus-decoded' is a fake charset,
460       ;; which means no further decoding (to be done by mm- functions).
461       (let* ((charset (if (plist-member part :content)
462                           'gnus-decoded
463                         (plist-get part :content-charset)))
464              (handle (mm-make-handle (current-buffer) `(,content-type (charset . ,charset)))))
465         ;; If the user wants the part inlined, insert the content and
466         ;; test whether we are able to inline it (which includes both
467         ;; capability and suitability tests).
468         (when (mm-inlined-p handle)
469           (insert (notmuch-get-bodypart-content msg part nth process-crypto))
470           (when (mm-inlinable-p handle)
471             (set-buffer display-buffer)
472             (mm-display-part handle)
473             t))))))
474
475 ;; Converts a plist of headers to an alist of headers. The input plist should
476 ;; have symbols of the form :Header as keys, and the resulting alist will have
477 ;; symbols of the form 'Header as keys.
478 (defun notmuch-headers-plist-to-alist (plist)
479   (loop for (key value . rest) on plist by #'cddr
480         collect (cons (intern (substring (symbol-name key) 1)) value)))
481
482 (defun notmuch-face-ensure-list-form (face)
483   "Return FACE in face list form.
484
485 If FACE is already a face list, it will be returned as-is.  If
486 FACE is a face name or face plist, it will be returned as a
487 single element face list."
488   (if (and (listp face) (not (keywordp (car face))))
489       face
490     (list face)))
491
492 (defun notmuch-combine-face-text-property (start end face &optional below object)
493   "Combine FACE into the 'face text property between START and END.
494
495 This function combines FACE with any existing faces between START
496 and END in OBJECT (which defaults to the current buffer).
497 Attributes specified by FACE take precedence over existing
498 attributes unless BELOW is non-nil.  FACE must be a face name (a
499 symbol or string), a property list of face attributes, or a list
500 of these.  For convenience when applied to strings, this returns
501 OBJECT."
502
503   ;; A face property can have three forms: a face name (a string or
504   ;; symbol), a property list, or a list of these two forms.  In the
505   ;; list case, the faces will be combined, with the earlier faces
506   ;; taking precedent.  Here we canonicalize everything to list form
507   ;; to make it easy to combine.
508   (let ((pos start)
509         (face-list (notmuch-face-ensure-list-form face)))
510     (while (< pos end)
511       (let* ((cur (get-text-property pos 'face object))
512              (cur-list (notmuch-face-ensure-list-form cur))
513              (new (cond ((null cur-list) face)
514                         (below (append cur-list face-list))
515                         (t (append face-list cur-list))))
516              (next (next-single-property-change pos 'face object end)))
517         (put-text-property pos next 'face new object)
518         (setq pos next))))
519   object)
520
521 (defun notmuch-combine-face-text-property-string (string face &optional below)
522   (notmuch-combine-face-text-property
523    0
524    (length string)
525    face
526    below
527    string))
528
529 (defun notmuch-map-text-property (start end prop func &optional object)
530   "Transform text property PROP using FUNC.
531
532 Applies FUNC to each distinct value of the text property PROP
533 between START and END of OBJECT, setting PROP to the value
534 returned by FUNC."
535   (while (< start end)
536     (let ((value (get-text-property start prop object))
537           (next (next-single-property-change start prop object end)))
538       (put-text-property start next prop (funcall func value) object)
539       (setq start next))))
540
541 (defun notmuch-logged-error (msg &optional extra)
542   "Log MSG and EXTRA to *Notmuch errors* and signal MSG.
543
544 This logs MSG and EXTRA to the *Notmuch errors* buffer and
545 signals MSG as an error.  If EXTRA is non-nil, text referring the
546 user to the *Notmuch errors* buffer will be appended to the
547 signaled error.  This function does not return."
548
549   (with-current-buffer (get-buffer-create "*Notmuch errors*")
550     (goto-char (point-max))
551     (unless (bobp)
552       (newline))
553     (save-excursion
554       (insert "[" (current-time-string) "]\n" msg)
555       (unless (bolp)
556         (newline))
557       (when extra
558         (insert extra)
559         (unless (bolp)
560           (newline)))))
561   (error "%s" (concat msg (when extra
562                             " (see *Notmuch errors* for more details)"))))
563
564 (defun notmuch-check-async-exit-status (proc msg &optional command err-file)
565   "If PROC exited abnormally, pop up an error buffer and signal an error.
566
567 This is a wrapper around `notmuch-check-exit-status' for
568 asynchronous process sentinels.  PROC and MSG must be the
569 arguments passed to the sentinel.  COMMAND and ERR-FILE, if
570 provided, are passed to `notmuch-check-exit-status'.  If COMMAND
571 is not provided, it is taken from `process-command'."
572   (let ((exit-status
573          (case (process-status proc)
574            ((exit) (process-exit-status proc))
575            ((signal) msg))))
576     (when exit-status
577       (notmuch-check-exit-status exit-status (or command (process-command proc))
578                                  nil err-file))))
579
580 (defun notmuch-check-exit-status (exit-status command &optional output err-file)
581   "If EXIT-STATUS is non-zero, pop up an error buffer and signal an error.
582
583 If EXIT-STATUS is non-zero, pop up a notmuch error buffer
584 describing the error and signal an Elisp error.  EXIT-STATUS must
585 be a number indicating the exit status code of a process or a
586 string describing the signal that terminated the process (such as
587 returned by `call-process').  COMMAND must be a list giving the
588 command and its arguments.  OUTPUT, if provided, is a string
589 giving the output of command.  ERR-FILE, if provided, is the name
590 of a file containing the error output of command.  OUTPUT and the
591 contents of ERR-FILE will be included in the error message."
592
593   (cond
594    ((eq exit-status 0) t)
595    ((eq exit-status 20)
596     (notmuch-logged-error "notmuch CLI version mismatch
597 Emacs requested an older output format than supported by the notmuch CLI.
598 You may need to restart Emacs or upgrade your notmuch Emacs package."))
599    ((eq exit-status 21)
600     (notmuch-logged-error "notmuch CLI version mismatch
601 Emacs requested a newer output format than supported by the notmuch CLI.
602 You may need to restart Emacs or upgrade your notmuch package."))
603    (t
604     (let* ((err (when err-file
605                   (with-temp-buffer
606                     (insert-file-contents err-file)
607                     (unless (eobp)
608                       (buffer-string)))))
609            (extra
610             (concat
611              "command: " (mapconcat #'shell-quote-argument command " ") "\n"
612              (if (integerp exit-status)
613                  (format "exit status: %s\n" exit-status)
614                (format "exit signal: %s\n" exit-status))
615              (when err
616                (concat "stderr:\n" err))
617              (when output
618                (concat "stdout:\n" output)))))
619         (if err
620             ;; We have an error message straight from the CLI.
621             (notmuch-logged-error
622              (replace-regexp-in-string "[ \n\r\t\f]*\\'" "" err) extra)
623           ;; We only have combined output from the CLI; don't inundate
624           ;; the user with it.  Mimic `process-lines'.
625           (notmuch-logged-error (format "%s exited with status %s"
626                                         (car command) exit-status)
627                                 extra))
628         ;; `notmuch-logged-error' does not return.
629         ))))
630
631 (defun notmuch-call-notmuch-process (&rest args)
632   "Synchronously invoke \"notmuch\" with the given list of arguments.
633
634 If notmuch exits with a non-zero status, output from the process
635 will appear in a buffer named \"*Notmuch errors*\" and an error
636 will be signaled."
637   (with-temp-buffer
638     (let ((status (apply #'call-process notmuch-command nil t nil args)))
639       (notmuch-check-exit-status status (cons notmuch-command args)
640                                  (buffer-string)))))
641
642 (defun notmuch-call-notmuch-sexp (&rest args)
643   "Invoke `notmuch-command' with ARGS and return the parsed S-exp output.
644
645 If notmuch exits with a non-zero status, this will pop up a
646 buffer containing notmuch's output and signal an error."
647
648   (with-temp-buffer
649     (let ((err-file (make-temp-file "nmerr")))
650       (unwind-protect
651           (let ((status (apply #'call-process
652                                notmuch-command nil (list t err-file) nil args)))
653             (notmuch-check-exit-status status (cons notmuch-command args)
654                                        (buffer-string) err-file)
655             (goto-char (point-min))
656             (read (current-buffer)))
657         (delete-file err-file)))))
658
659 (defun notmuch-start-notmuch (name buffer sentinel &rest args)
660   "Start and return an asynchronous notmuch command.
661
662 This starts and returns an asynchronous process running
663 `notmuch-command' with ARGS.  The exit status is checked via
664 `notmuch-check-async-exit-status'.  Output written to stderr is
665 redirected and displayed when the process exits (even if the
666 process exits successfully).  NAME and BUFFER are the same as in
667 `start-process'.  SENTINEL is a process sentinel function to call
668 when the process exits, or nil for none.  The caller must *not*
669 invoke `set-process-sentinel' directly on the returned process,
670 as that will interfere with the handling of stderr and the exit
671 status."
672
673   ;; There is no way (as of Emacs 24.3) to capture stdout and stderr
674   ;; separately for asynchronous processes, or even to redirect stderr
675   ;; to a file, so we use a trivial shell wrapper to send stderr to a
676   ;; temporary file and clean things up in the sentinel.
677   (let* ((err-file (make-temp-file "nmerr"))
678          ;; Use a pipe
679          (process-connection-type nil)
680          ;; Find notmuch using Emacs' `exec-path'
681          (command (or (executable-find notmuch-command)
682                       (error "command not found: %s" notmuch-command)))
683          (proc (apply #'start-process name buffer
684                       "/bin/sh" "-c"
685                       "exec 2>\"$1\"; shift; exec \"$0\" \"$@\""
686                       command err-file args)))
687     (process-put proc 'err-file err-file)
688     (process-put proc 'sub-sentinel sentinel)
689     (process-put proc 'real-command (cons notmuch-command args))
690     (set-process-sentinel proc #'notmuch-start-notmuch-sentinel)
691     proc))
692
693 (defun notmuch-start-notmuch-sentinel (proc event)
694   (let ((err-file (process-get proc 'err-file))
695         (sub-sentinel (process-get proc 'sub-sentinel))
696         (real-command (process-get proc 'real-command)))
697     (condition-case err
698         (progn
699           ;; Invoke the sub-sentinel, if any
700           (when sub-sentinel
701             (funcall sub-sentinel proc event))
702           ;; Check the exit status.  This will signal an error if the
703           ;; exit status is non-zero.  Don't do this if the process
704           ;; buffer is dead since that means Emacs killed the process
705           ;; and there's no point in telling the user that (but we
706           ;; still check for and report stderr output below).
707           (when (buffer-live-p (process-buffer proc))
708             (notmuch-check-async-exit-status proc event real-command err-file))
709           ;; If that didn't signal an error, then any error output was
710           ;; really warning output.  Show warnings, if any.
711           (let ((warnings
712                  (with-temp-buffer
713                    (unless (= (second (insert-file-contents err-file)) 0)
714                      (end-of-line)
715                      ;; Show first line; stuff remaining lines in the
716                      ;; errors buffer.
717                      (let ((l1 (buffer-substring (point-min) (point))))
718                        (skip-chars-forward "\n")
719                        (cons l1 (unless (eobp)
720                                   (buffer-substring (point) (point-max)))))))))
721             (when warnings
722               (notmuch-logged-error (car warnings) (cdr warnings)))))
723       (error
724        ;; Emacs behaves strangely if an error escapes from a sentinel,
725        ;; so turn errors into messages.
726        (message "%s" (error-message-string err))))
727     (ignore-errors (delete-file err-file))))
728
729 ;; This variable is used only buffer local, but it needs to be
730 ;; declared globally first to avoid compiler warnings.
731 (defvar notmuch-show-process-crypto nil)
732 (make-variable-buffer-local 'notmuch-show-process-crypto)
733
734 (provide 'notmuch-lib)
735
736 ;; Local Variables:
737 ;; byte-compile-warnings: (not cl-functions)
738 ;; End: