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