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