1 ;; notmuch-lib.el --- common variables, functions and function declarations
3 ;; Copyright © Carl Worth
5 ;; This file is part of Notmuch.
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.
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.
17 ;; You should have received a copy of the GNU General Public License
18 ;; along with Notmuch. If not, see <http://www.gnu.org/licenses/>.
20 ;; Authors: Carl Worth <cworth@cworth.org>
22 ;; This is an part of an emacs-based interface to the notmuch mail system.
29 (defvar notmuch-command "notmuch"
30 "Command to run the notmuch binary.")
33 "Notmuch mail reader for Emacs."
36 (defgroup notmuch-hello nil
37 "Overview of saved searches, tags, etc."
40 (defgroup notmuch-search nil
41 "Searching and sorting mail."
44 (defgroup notmuch-show nil
45 "Showing messages and threads."
48 (defgroup notmuch-send nil
49 "Sending messages from Notmuch."
52 (custom-add-to-group 'notmuch-send 'message 'custom-group)
54 (defgroup notmuch-crypto nil
55 "Processing and display of cryptographic MIME parts."
58 (defgroup notmuch-hooks nil
59 "Running custom code on well-defined occasions."
62 (defgroup notmuch-external nil
63 "Running external commands from within Notmuch."
66 (defgroup notmuch-faces nil
67 "Graphical attributes for displaying text"
70 (defcustom notmuch-search-oldest-first t
71 "Show the oldest mail first when searching."
73 :group 'notmuch-search)
77 (defvar notmuch-search-history nil
78 "Variable to store notmuch searches history.")
80 (defcustom notmuch-saved-searches nil
81 "A list of saved searches to display."
82 :type '(alist :key-type string :value-type string)
83 :group 'notmuch-hello)
85 (defcustom notmuch-archive-tags '("-inbox")
86 "List of tag changes to apply to a message or a thread when it is archived.
88 Tags starting with \"+\" (or not starting with either \"+\" or
89 \"-\") in the list will be added, and tags starting with \"-\"
90 will be removed from the message or thread being archived.
92 For example, if you wanted to remove an \"inbox\" tag and add an
93 \"archived\" tag, you would set:
94 (\"-inbox\" \"+archived\")"
95 :type '(repeat string)
96 :group 'notmuch-search
99 (defvar notmuch-folders nil
100 "Deprecated name for what is now known as `notmuch-saved-searches'.")
102 (defun notmuch-saved-searches ()
103 "Common function for querying the notmuch-saved-searches variable.
105 We do this as a function to support the old name of the
106 variable (`notmuch-folders') as well as for the default value if
107 the user hasn't set this variable with the old or new value."
108 (if notmuch-saved-searches
109 notmuch-saved-searches
112 '(("inbox" . "tag:inbox")
113 ("unread" . "tag:unread")))))
115 (defun notmuch-version ()
116 "Return a string with the notmuch version number."
118 ;; Trim off the trailing newline.
119 (substring (shell-command-to-string
120 (concat notmuch-command " --version"))
122 (if (string-match "^notmuch\\( version\\)? \\(.*\\)$"
124 (match-string 2 long-string)
127 (defun notmuch-config-get (item)
128 "Return a value from the notmuch configuration."
129 ;; Trim off the trailing newline
130 (substring (shell-command-to-string
131 (concat notmuch-command " config get " item))
134 (defun notmuch-database-path ()
135 "Return the database.path value from the notmuch configuration."
136 (notmuch-config-get "database.path"))
138 (defun notmuch-user-name ()
139 "Return the user.name value from the notmuch configuration."
140 (notmuch-config-get "user.name"))
142 (defun notmuch-user-primary-email ()
143 "Return the user.primary_email value from the notmuch configuration."
144 (notmuch-config-get "user.primary_email"))
146 (defun notmuch-user-other-email ()
147 "Return the user.other_email value (as a list) from the notmuch configuration."
148 (split-string (notmuch-config-get "user.other_email") "\n"))
150 (defun notmuch-kill-this-buffer ()
151 "Kill the current buffer."
153 (kill-buffer (current-buffer)))
155 (defun notmuch-prettify-subject (subject)
156 ;; This function is used by `notmuch-search-process-filter' which
157 ;; requires that we not disrupt its' matching state.
160 (string-match "^[ \t]*$" subject))
164 (defun notmuch-escape-boolean-term (term)
165 "Escape a boolean term for use in a query.
167 The caller is responsible for prepending the term prefix and a
168 colon. This performs minimal escaping in order to produce
169 user-friendly queries."
172 (if (or (equal term "")
173 (string-match "[ ()]\\|^\"" term))
175 (concat "\"" (replace-regexp-in-string "\"" "\"\"" term t t) "\"")
178 (defun notmuch-id-to-query (id)
179 "Return a query that matches the message with id ID."
180 (concat "id:" (notmuch-escape-boolean-term id)))
184 (defun notmuch-common-do-stash (text)
185 "Common function to stash text in kill ring, and display in minibuffer."
187 (message "Stashed: %s" text))
191 (defun notmuch-remove-if-not (predicate list)
192 "Return a copy of LIST with all items not satisfying PREDICATE removed."
195 (when (funcall predicate (car list))
196 (push (car list) out))
197 (setq list (cdr list)))
200 ;; This lets us avoid compiling these replacement functions when emacs
201 ;; is sufficiently new enough to supply them alone. We do the macro
202 ;; treatment rather than just wrapping our defun calls in a when form
203 ;; specifically so that the compiler never sees the code on new emacs,
204 ;; (since the code is triggering warnings that we don't know how to get
207 ;; A more clever macro here would accept a condition and a list of forms.
208 (defmacro compile-on-emacs-prior-to-23 (form)
209 "Conditionally evaluate form only on emacs < emacs-23."
210 (list 'when (< emacs-major-version 23)
213 (defun notmuch-split-content-type (content-type)
214 "Split content/type into 'content' and 'type'"
215 (split-string content-type "/"))
217 (defun notmuch-match-content-type (t1 t2)
218 "Return t if t1 and t2 are matching content types, taking wildcards into account"
219 (let ((st1 (notmuch-split-content-type t1))
220 (st2 (notmuch-split-content-type t2)))
221 (if (or (string= (cadr st1) "*")
222 (string= (cadr st2) "*"))
223 ;; Comparison of content types should be case insensitive.
224 (string= (downcase (car st1)) (downcase (car st2)))
225 (string= (downcase t1) (downcase t2)))))
227 (defvar notmuch-multipart/alternative-discouraged
231 ;; multipart/related usually contain a text/html part and some associated graphics.
235 (defun notmuch-multipart/alternative-choose (types)
236 "Return a list of preferred types from the given list of types"
237 ;; Based on `mm-preferred-alternative-precedence'.
239 (dolist (pref (reverse notmuch-multipart/alternative-discouraged))
240 (dolist (elem (copy-sequence seq))
241 (when (string-match pref elem)
242 (setq seq (nconc (delete elem seq) (list elem))))))
245 (defun notmuch-parts-filter-by-type (parts type)
246 "Given a list of message parts, return a list containing the ones matching
249 (lambda (part) (notmuch-match-content-type (plist-get part :content-type) type))
252 ;; Helper for parts which are generally not included in the default
254 (defun notmuch-get-bodypart-internal (query part-number process-crypto)
255 (let ((args '("show" "--format=raw"))
256 (part-arg (format "--part=%s" part-number)))
257 (setq args (append args (list part-arg)))
259 (setq args (append args '("--decrypt"))))
260 (setq args (append args (list query)))
262 (let ((coding-system-for-read 'no-conversion))
264 (apply 'call-process (append (list notmuch-command nil (list t nil) nil) args))
267 (defun notmuch-get-bodypart-content (msg part nth process-crypto)
268 (or (plist-get part :content)
269 (notmuch-get-bodypart-internal (notmuch-id-to-query (plist-get msg :id)) nth process-crypto)))
271 ;; Workaround: The call to `mm-display-part' below triggers a bug in
272 ;; Emacs 24 if it attempts to use the shr renderer to display an HTML
273 ;; part with images in it (demonstrated in 24.1 and 24.2 on Debian and
274 ;; Fedora 17, though unreproducable in other configurations).
275 ;; `mm-shr' references the variable `gnus-inhibit-images' without
276 ;; first loading gnus-art, which defines it, resulting in a
277 ;; void-variable error. Hence, we advise `mm-shr' to ensure gnus-art
279 (if (>= emacs-major-version 24)
280 (defadvice mm-shr (before load-gnus-arts activate)
281 (require 'gnus-art nil t)
282 (ad-disable-advice 'mm-shr 'before 'load-gnus-arts)))
284 (defun notmuch-mm-display-part-inline (msg part nth content-type process-crypto)
285 "Use the mm-decode/mm-view functions to display a part in the
286 current buffer, if possible."
287 (let ((display-buffer (current-buffer)))
289 ;; In case there is :content, the content string is already converted
290 ;; into emacs internal format. `gnus-decoded' is a fake charset,
291 ;; which means no further decoding (to be done by mm- functions).
292 (let* ((charset (if (plist-member part :content)
294 (plist-get part :content-charset)))
295 (handle (mm-make-handle (current-buffer) `(,content-type (charset . ,charset)))))
296 ;; If the user wants the part inlined, insert the content and
297 ;; test whether we are able to inline it (which includes both
298 ;; capability and suitability tests).
299 (when (mm-inlined-p handle)
300 (insert (notmuch-get-bodypart-content msg part nth process-crypto))
301 (when (mm-inlinable-p handle)
302 (set-buffer display-buffer)
303 (mm-display-part handle)
306 ;; Converts a plist of headers to an alist of headers. The input plist should
307 ;; have symbols of the form :Header as keys, and the resulting alist will have
308 ;; symbols of the form 'Header as keys.
309 (defun notmuch-headers-plist-to-alist (plist)
310 (loop for (key value . rest) on plist by #'cddr
311 collect (cons (intern (substring (symbol-name key) 1)) value)))
313 (defun notmuch-combine-face-text-property (start end face)
314 "Combine FACE into the 'face text property between START and END.
316 This function combines FACE with any existing faces between START
317 and END. Attributes specified by FACE take precedence over
318 existing attributes. FACE must be a face name (a symbol or
319 string), a property list of face attributes, or a list of these."
323 (let ((cur (get-text-property pos 'face))
324 (next (next-single-property-change pos 'face nil end)))
325 (put-text-property pos next 'face (cons face cur))
328 ;; Compatibility functions for versions of emacs before emacs 23.
330 ;; Both functions here were copied from emacs 23 with the following copyright:
332 ;; Copyright (C) 1985, 1986, 1992, 1994, 1995, 1999, 2000, 2001, 2002, 2003,
333 ;; 2004, 2005, 2006, 2007, 2008, 2009, 2010 Free Software Foundation, Inc.
335 ;; and under the GPL version 3 (or later) exactly as notmuch itself.
336 (compile-on-emacs-prior-to-23
337 (defun apply-partially (fun &rest args)
338 "Return a function that is a partial application of FUN to ARGS.
339 ARGS is a list of the first N arguments to pass to FUN.
340 The result is a new function which does the same as FUN, except that
341 the first N arguments are fixed at the values with which this function
343 (lexical-let ((fun fun) (args1 args))
344 (lambda (&rest args2) (apply fun (append args1 args2))))))
346 (compile-on-emacs-prior-to-23
347 (defun mouse-event-p (object)
348 "Return non-nil if OBJECT is a mouse click event."
349 (memq (event-basic-type object) '(mouse-1 mouse-2 mouse-3 mouse-movement))))
351 ;; This variable is used only buffer local, but it needs to be
352 ;; declared globally first to avoid compiler warnings.
353 (defvar notmuch-show-process-crypto nil)
354 (make-variable-buffer-local 'notmuch-show-process-crypto)
356 ;; Incremental JSON parsing
358 (defun notmuch-json-create-parser (buffer)
359 "Return a streaming JSON parser that consumes input from BUFFER.
361 This parser is designed to read streaming JSON whose structure is
362 known to the caller. Like a typical JSON parsing interface, it
363 provides a function to read a complete JSON value from the input.
364 However, it extends this with an additional function that
365 requires the next value in the input to be a compound value and
366 descends into it, allowing its elements to be read one at a time
367 or further descended into. Both functions can return 'retry to
368 indicate that not enough input is available.
370 The parser always consumes input from BUFFER's point. Hence, the
371 caller is allowed to delete and data before point and may
372 resynchronize after an error by moving point."
375 ;; Terminator stack: a stack of characters that indicate the
376 ;; end of the compound values enclosing point
379 ;; * 'expect-value if the next token must be a value, but a
380 ;; value has not yet been reached
381 ;; * 'value if point is at the beginning of a value
382 ;; * 'expect-comma if the next token must be a comma
384 ;; Allow terminator: non-nil if the next token may be a
387 ;; Partial parse position: If state is 'value, a marker for
388 ;; the position of the partial parser or nil if no partial
389 ;; parsing has happened yet
391 ;; Partial parse state: If state is 'value, the current
392 ;; `parse-partial-sexp' state
395 (defmacro notmuch-json-buffer (jp) `(first ,jp))
396 (defmacro notmuch-json-term-stack (jp) `(second ,jp))
397 (defmacro notmuch-json-next (jp) `(third ,jp))
398 (defmacro notmuch-json-allow-term (jp) `(fourth ,jp))
399 (defmacro notmuch-json-partial-pos (jp) `(fifth ,jp))
400 (defmacro notmuch-json-partial-state (jp) `(sixth ,jp))
402 (defvar notmuch-json-syntax-table
403 (let ((table (make-syntax-table)))
404 ;; The standard syntax table is what we need except that "." needs
405 ;; to have word syntax instead of punctuation syntax.
406 (modify-syntax-entry ?. "w" table)
408 "Syntax table used for incremental JSON parsing.")
410 (defun notmuch-json-scan-to-value (jp)
411 ;; Helper function that consumes separators, terminators, and
412 ;; whitespace from point. Returns nil if it successfully reached
413 ;; the beginning of a value, 'end if it consumed a terminator, or
414 ;; 'retry if not enough input was available to reach a value. Upon
415 ;; nil return, (notmuch-json-next jp) is always 'value.
417 (if (eq (notmuch-json-next jp) 'value)
418 ;; We're already at a value
420 ;; Drive the state toward 'expect-value
421 (skip-chars-forward " \t\r\n")
422 (or (when (eobp) 'retry)
423 ;; Test for the terminator for the current compound
424 (when (and (notmuch-json-allow-term jp)
425 (eq (char-after) (car (notmuch-json-term-stack jp))))
426 ;; Consume it and expect a comma or terminator next
428 (setf (notmuch-json-term-stack jp) (cdr (notmuch-json-term-stack jp))
429 (notmuch-json-next jp) 'expect-comma
430 (notmuch-json-allow-term jp) t)
432 ;; Test for a separator
433 (when (eq (notmuch-json-next jp) 'expect-comma)
434 (when (/= (char-after) ?,)
435 (signal 'json-readtable-error (list "expected ','")))
436 ;; Consume it, switch to 'expect-value, and disallow a
439 (skip-chars-forward " \t\r\n")
440 (setf (notmuch-json-next jp) 'expect-value
441 (notmuch-json-allow-term jp) nil)
442 ;; We moved point, so test for eobp again and fall through
443 ;; to the next test if there's more input
444 (when (eobp) 'retry))
445 ;; Next must be 'expect-value and we know this isn't
446 ;; whitespace, EOB, or a terminator, so point must be on a
449 (assert (eq (notmuch-json-next jp) 'expect-value))
450 (setf (notmuch-json-next jp) 'value)
453 (defun notmuch-json-begin-compound (jp)
454 "Parse the beginning of a compound value and traverse inside it.
456 Returns 'retry if there is insufficient input to parse the
457 beginning of the compound. If this is able to parse the
458 beginning of a compound, it moves point past the token that opens
459 the compound and returns t. Later calls to `notmuch-json-read'
460 will return the compound's elements.
462 Entering JSON objects is currently unimplemented."
464 (with-current-buffer (notmuch-json-buffer jp)
465 ;; Disallow terminators
466 (setf (notmuch-json-allow-term jp) nil)
467 (or (notmuch-json-scan-to-value jp)
468 (if (/= (char-after) ?\[)
469 (signal 'json-readtable-error (list "expected '['"))
471 (push ?\] (notmuch-json-term-stack jp))
472 ;; Expect a value or terminator next
473 (setf (notmuch-json-next jp) 'expect-value
474 (notmuch-json-allow-term jp) t)
477 (defun notmuch-json-read (jp)
478 "Parse the value at point in JP's buffer.
480 Returns 'retry if there is insufficient input to parse a complete
481 JSON value (though it may still move point over separators or
482 whitespace). If the parser is currently inside a compound value
483 and the next token ends the list or object, this moves point just
484 past the terminator and returns 'end. Otherwise, this moves
485 point to just past the end of the value and returns the value."
487 (with-current-buffer (notmuch-json-buffer jp)
489 ;; Get to a value state
490 (notmuch-json-scan-to-value jp)
492 ;; Can we parse a complete value?
494 (if (looking-at "[-+0-9tfn]")
495 ;; This is a number or a keyword, so the partial
496 ;; parser isn't going to help us because a truncated
497 ;; number or keyword looks like a complete symbol to
498 ;; it. Look for something that clearly ends it.
500 (skip-chars-forward "^]},: \t\r\n")
503 ;; We're looking at a string, object, or array, which we
504 ;; can partial parse. If we just reached the value, set
505 ;; up the partial parser.
506 (when (null (notmuch-json-partial-state jp))
507 (setf (notmuch-json-partial-pos jp) (point-marker)))
509 ;; Extend the partial parse until we either reach EOB or
510 ;; get the whole value
513 (with-syntax-table notmuch-json-syntax-table
515 (notmuch-json-partial-pos jp) (point-max) 0 nil
516 (notmuch-json-partial-state jp)))))
517 ;; A complete value is available if we've reached
518 ;; depth 0 or less and encountered a complete
520 (if (and (<= (first pstate) 0) (third pstate))
522 ;; Not complete. Update the partial parser state
523 (setf (notmuch-json-partial-pos jp) (point-marker)
524 (notmuch-json-partial-state jp) pstate)
529 ;; We have a value. Reset the partial parse state and expect
530 ;; a comma or terminator after the value.
531 (setf (notmuch-json-next jp) 'expect-comma
532 (notmuch-json-allow-term jp) t
533 (notmuch-json-partial-pos jp) nil
534 (notmuch-json-partial-state jp) nil)
536 (let ((json-object-type 'plist)
537 (json-array-type 'list)
541 (defun notmuch-json-eof (jp)
542 "Signal a json-error if there is more data in JP's buffer.
544 Moves point to the beginning of any trailing data or to the end
545 of the buffer if there is only trailing whitespace."
547 (with-current-buffer (notmuch-json-buffer jp)
548 (skip-chars-forward " \t\r\n")
550 (signal 'json-error (list "Trailing garbage following JSON data")))))
552 (provide 'notmuch-lib)
555 ;; byte-compile-warnings: (not cl-functions)