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