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