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