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