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