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