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