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