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