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