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