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