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