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