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