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