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