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