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