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.
27 (eval-when-compile (require 'cl))
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 (defvar notmuch-folders nil
86 "Deprecated name for what is now known as `notmuch-saved-searches'.")
88 (defun notmuch-saved-searches ()
89 "Common function for querying the notmuch-saved-searches variable.
91 We do this as a function to support the old name of the
92 variable (`notmuch-folders') as well as for the default value if
93 the user hasn't set this variable with the old or new value."
94 (if notmuch-saved-searches
95 notmuch-saved-searches
98 '(("inbox" . "tag:inbox")
99 ("unread" . "tag:unread")))))
101 (defun notmuch-version ()
102 "Return a string with the notmuch version number."
104 ;; Trim off the trailing newline.
105 (substring (shell-command-to-string
106 (concat notmuch-command " --version"))
108 (if (string-match "^notmuch\\( version\\)? \\(.*\\)$"
110 (match-string 2 long-string)
113 (defun notmuch-config-get (item)
114 "Return a value from the notmuch configuration."
115 ;; Trim off the trailing newline
116 (substring (shell-command-to-string
117 (concat notmuch-command " config get " item))
120 (defun notmuch-database-path ()
121 "Return the database.path value from the notmuch configuration."
122 (notmuch-config-get "database.path"))
124 (defun notmuch-user-name ()
125 "Return the user.name value from the notmuch configuration."
126 (notmuch-config-get "user.name"))
128 (defun notmuch-user-primary-email ()
129 "Return the user.primary_email value from the notmuch configuration."
130 (notmuch-config-get "user.primary_email"))
132 (defun notmuch-user-other-email ()
133 "Return the user.other_email value (as a list) from the notmuch configuration."
134 (split-string (notmuch-config-get "user.other_email") "\n"))
136 (defun notmuch-kill-this-buffer ()
137 "Kill the current buffer."
139 (kill-buffer (current-buffer)))
141 (defun notmuch-prettify-subject (subject)
142 ;; This function is used by `notmuch-search-process-filter' which
143 ;; requires that we not disrupt its' matching state.
146 (string-match "^[ \t]*$" subject))
150 (defun notmuch-id-to-query (id)
151 "Return a query that matches the message with id ID."
152 (concat "id:\"" (replace-regexp-in-string "\"" "\"\"" id t t) "\""))
156 (defun notmuch-common-do-stash (text)
157 "Common function to stash text in kill ring, and display in minibuffer."
159 (message "Stashed: %s" text))
163 (defun notmuch-remove-if-not (predicate list)
164 "Return a copy of LIST with all items not satisfying PREDICATE removed."
167 (when (funcall predicate (car list))
168 (push (car list) out))
169 (setq list (cdr list)))
172 ;; This lets us avoid compiling these replacement functions when emacs
173 ;; is sufficiently new enough to supply them alone. We do the macro
174 ;; treatment rather than just wrapping our defun calls in a when form
175 ;; specifically so that the compiler never sees the code on new emacs,
176 ;; (since the code is triggering warnings that we don't know how to get
179 ;; A more clever macro here would accept a condition and a list of forms.
180 (defmacro compile-on-emacs-prior-to-23 (form)
181 "Conditionally evaluate form only on emacs < emacs-23."
182 (list 'when (< emacs-major-version 23)
185 (defun notmuch-split-content-type (content-type)
186 "Split content/type into 'content' and 'type'"
187 (split-string content-type "/"))
189 (defun notmuch-match-content-type (t1 t2)
190 "Return t if t1 and t2 are matching content types, taking wildcards into account"
191 (let ((st1 (notmuch-split-content-type t1))
192 (st2 (notmuch-split-content-type t2)))
193 (if (or (string= (cadr st1) "*")
194 (string= (cadr st2) "*"))
195 ;; Comparison of content types should be case insensitive.
196 (string= (downcase (car st1)) (downcase (car st2)))
197 (string= (downcase t1) (downcase t2)))))
199 (defvar notmuch-multipart/alternative-discouraged
203 ;; multipart/related usually contain a text/html part and some associated graphics.
207 (defun notmuch-multipart/alternative-choose (types)
208 "Return a list of preferred types from the given list of types"
209 ;; Based on `mm-preferred-alternative-precedence'.
211 (dolist (pref (reverse notmuch-multipart/alternative-discouraged))
212 (dolist (elem (copy-sequence seq))
213 (when (string-match pref elem)
214 (setq seq (nconc (delete elem seq) (list elem))))))
217 (defun notmuch-parts-filter-by-type (parts type)
218 "Given a list of message parts, return a list containing the ones matching
221 (lambda (part) (notmuch-match-content-type (plist-get part :content-type) type))
224 ;; Helper for parts which are generally not included in the default
226 (defun notmuch-get-bodypart-internal (query part-number process-crypto)
227 (let ((args '("show" "--format=raw"))
228 (part-arg (format "--part=%s" part-number)))
229 (setq args (append args (list part-arg)))
231 (setq args (append args '("--decrypt"))))
232 (setq args (append args (list query)))
234 (let ((coding-system-for-read 'no-conversion))
236 (apply 'call-process (append (list notmuch-command nil (list t nil) nil) args))
239 (defun notmuch-get-bodypart-content (msg part nth process-crypto)
240 (or (plist-get part :content)
241 (notmuch-get-bodypart-internal (notmuch-id-to-query (plist-get msg :id)) nth process-crypto)))
243 (defun notmuch-mm-display-part-inline (msg part nth content-type process-crypto)
244 "Use the mm-decode/mm-view functions to display a part in the
245 current buffer, if possible."
246 (let ((display-buffer (current-buffer)))
248 ;; In case there is :content, the content string is already converted
249 ;; into emacs internal format. `gnus-decoded' is a fake charset,
250 ;; which means no further decoding (to be done by mm- functions).
251 (let* ((charset (if (plist-member part :content)
253 (plist-get part :content-charset)))
254 (handle (mm-make-handle (current-buffer) `(,content-type (charset . ,charset)))))
255 ;; If the user wants the part inlined, insert the content and
256 ;; test whether we are able to inline it (which includes both
257 ;; capability and suitability tests).
258 (when (mm-inlined-p handle)
259 (insert (notmuch-get-bodypart-content msg part nth process-crypto))
260 (when (mm-inlinable-p handle)
261 (set-buffer display-buffer)
262 (mm-display-part handle)
265 ;; Converts a plist of headers to an alist of headers. The input plist should
266 ;; have symbols of the form :Header as keys, and the resulting alist will have
267 ;; symbols of the form 'Header as keys.
268 (defun notmuch-headers-plist-to-alist (plist)
269 (loop for (key value . rest) on plist by #'cddr
270 collect (cons (intern (substring (symbol-name key) 1)) value)))
272 ;; Compatibility functions for versions of emacs before emacs 23.
274 ;; Both functions here were copied from emacs 23 with the following copyright:
276 ;; Copyright (C) 1985, 1986, 1992, 1994, 1995, 1999, 2000, 2001, 2002, 2003,
277 ;; 2004, 2005, 2006, 2007, 2008, 2009, 2010 Free Software Foundation, Inc.
279 ;; and under the GPL version 3 (or later) exactly as notmuch itself.
280 (compile-on-emacs-prior-to-23
281 (defun apply-partially (fun &rest args)
282 "Return a function that is a partial application of FUN to ARGS.
283 ARGS is a list of the first N arguments to pass to FUN.
284 The result is a new function which does the same as FUN, except that
285 the first N arguments are fixed at the values with which this function
287 (lexical-let ((fun fun) (args1 args))
288 (lambda (&rest args2) (apply fun (append args1 args2))))))
290 (compile-on-emacs-prior-to-23
291 (defun mouse-event-p (object)
292 "Return non-nil if OBJECT is a mouse click event."
293 (memq (event-basic-type object) '(mouse-1 mouse-2 mouse-3 mouse-movement))))
295 ;; This variable is used only buffer local, but it needs to be
296 ;; declared globally first to avoid compiler warnings.
297 (defvar notmuch-show-process-crypto nil)
298 (make-variable-buffer-local 'notmuch-show-process-crypto)
300 ;; Incremental JSON parsing
302 (defun notmuch-json-create-parser (buffer)
303 "Return a streaming JSON parser that consumes input from BUFFER.
305 This parser is designed to read streaming JSON whose structure is
306 known to the caller. Like a typical JSON parsing interface, it
307 provides a function to read a complete JSON value from the input.
308 However, it extends this with an additional function that
309 requires the next value in the input to be a compound value and
310 descends into it, allowing its elements to be read one at a time
311 or further descended into. Both functions can return 'retry to
312 indicate that not enough input is available.
314 The parser always consumes input from BUFFER's point. Hence, the
315 caller is allowed to delete and data before point and may
316 resynchronize after an error by moving point."
319 ;; Terminator stack: a stack of characters that indicate the
320 ;; end of the compound values enclosing point
323 ;; * 'expect-value if the next token must be a value, but a
324 ;; value has not yet been reached
325 ;; * 'value if point is at the beginning of a value
326 ;; * 'expect-comma if the next token must be a comma
328 ;; Allow terminator: non-nil if the next token may be a
331 ;; Partial parse position: If state is 'value, a marker for
332 ;; the position of the partial parser or nil if no partial
333 ;; parsing has happened yet
335 ;; Partial parse state: If state is 'value, the current
336 ;; `parse-partial-sexp' state
339 (defmacro notmuch-json-buffer (jp) `(first ,jp))
340 (defmacro notmuch-json-term-stack (jp) `(second ,jp))
341 (defmacro notmuch-json-next (jp) `(third ,jp))
342 (defmacro notmuch-json-allow-term (jp) `(fourth ,jp))
343 (defmacro notmuch-json-partial-pos (jp) `(fifth ,jp))
344 (defmacro notmuch-json-partial-state (jp) `(sixth ,jp))
346 (defvar notmuch-json-syntax-table
347 (let ((table (make-syntax-table)))
348 ;; The standard syntax table is what we need except that "." needs
349 ;; to have word syntax instead of punctuation syntax.
350 (modify-syntax-entry ?. "w" table)
352 "Syntax table used for incremental JSON parsing.")
354 (defun notmuch-json-scan-to-value (jp)
355 ;; Helper function that consumes separators, terminators, and
356 ;; whitespace from point. Returns nil if it successfully reached
357 ;; the beginning of a value, 'end if it consumed a terminator, or
358 ;; 'retry if not enough input was available to reach a value. Upon
359 ;; nil return, (notmuch-json-next jp) is always 'value.
361 (if (eq (notmuch-json-next jp) 'value)
362 ;; We're already at a value
364 ;; Drive the state toward 'expect-value
365 (skip-chars-forward " \t\r\n")
366 (or (when (eobp) 'retry)
367 ;; Test for the terminator for the current compound
368 (when (and (notmuch-json-allow-term jp)
369 (eq (char-after) (car (notmuch-json-term-stack jp))))
370 ;; Consume it and expect a comma or terminator next
372 (setf (notmuch-json-term-stack jp) (cdr (notmuch-json-term-stack jp))
373 (notmuch-json-next jp) 'expect-comma
374 (notmuch-json-allow-term jp) t)
376 ;; Test for a separator
377 (when (eq (notmuch-json-next jp) 'expect-comma)
378 (when (/= (char-after) ?,)
379 (signal 'json-readtable-error (list "expected ','")))
380 ;; Consume it, switch to 'expect-value, and disallow a
383 (skip-chars-forward " \t\r\n")
384 (setf (notmuch-json-next jp) 'expect-value
385 (notmuch-json-allow-term jp) nil)
386 ;; We moved point, so test for eobp again and fall through
387 ;; to the next test if there's more input
388 (when (eobp) 'retry))
389 ;; Next must be 'expect-value and we know this isn't
390 ;; whitespace, EOB, or a terminator, so point must be on a
393 (assert (eq (notmuch-json-next jp) 'expect-value))
394 (setf (notmuch-json-next jp) 'value)
397 (defun notmuch-json-begin-compound (jp)
398 "Parse the beginning of a compound value and traverse inside it.
400 Returns 'retry if there is insufficient input to parse the
401 beginning of the compound. If this is able to parse the
402 beginning of a compound, it moves point past the token that opens
403 the compound and returns t. Later calls to `notmuch-json-read'
404 will return the compound's elements.
406 Entering JSON objects is currently unimplemented."
408 (with-current-buffer (notmuch-json-buffer jp)
409 ;; Disallow terminators
410 (setf (notmuch-json-allow-term jp) nil)
411 (or (notmuch-json-scan-to-value jp)
412 (if (/= (char-after) ?\[)
413 (signal 'json-readtable-error (list "expected '['"))
415 (push ?\] (notmuch-json-term-stack jp))
416 ;; Expect a value or terminator next
417 (setf (notmuch-json-next jp) 'expect-value
418 (notmuch-json-allow-term jp) t)
421 (defun notmuch-json-read (jp)
422 "Parse the value at point in JP's buffer.
424 Returns 'retry if there is insufficient input to parse a complete
425 JSON value (though it may still move point over separators or
426 whitespace). If the parser is currently inside a compound value
427 and the next token ends the list or object, this moves point just
428 past the terminator and returns 'end. Otherwise, this moves
429 point to just past the end of the value and returns the value."
431 (with-current-buffer (notmuch-json-buffer jp)
433 ;; Get to a value state
434 (notmuch-json-scan-to-value jp)
436 ;; Can we parse a complete value?
438 (if (looking-at "[-+0-9tfn]")
439 ;; This is a number or a keyword, so the partial
440 ;; parser isn't going to help us because a truncated
441 ;; number or keyword looks like a complete symbol to
442 ;; it. Look for something that clearly ends it.
444 (skip-chars-forward "^]},: \t\r\n")
447 ;; We're looking at a string, object, or array, which we
448 ;; can partial parse. If we just reached the value, set
449 ;; up the partial parser.
450 (when (null (notmuch-json-partial-state jp))
451 (setf (notmuch-json-partial-pos jp) (point-marker)))
453 ;; Extend the partial parse until we either reach EOB or
454 ;; get the whole value
457 (with-syntax-table notmuch-json-syntax-table
459 (notmuch-json-partial-pos jp) (point-max) 0 nil
460 (notmuch-json-partial-state jp)))))
461 ;; A complete value is available if we've reached
462 ;; depth 0 or less and encountered a complete
464 (if (and (<= (first pstate) 0) (third pstate))
466 ;; Not complete. Update the partial parser state
467 (setf (notmuch-json-partial-pos jp) (point-marker)
468 (notmuch-json-partial-state jp) pstate)
473 ;; We have a value. Reset the partial parse state and expect
474 ;; a comma or terminator after the value.
475 (setf (notmuch-json-next jp) 'expect-comma
476 (notmuch-json-allow-term jp) t
477 (notmuch-json-partial-pos jp) nil
478 (notmuch-json-partial-state jp) nil)
480 (let ((json-object-type 'plist)
481 (json-array-type 'list)
485 (defun notmuch-json-eof (jp)
486 "Signal a json-error if there is more data in JP's buffer.
488 Moves point to the beginning of any trailing data or to the end
489 of the buffer if there is only trailing whitespace."
491 (with-current-buffer (notmuch-json-buffer jp)
492 (skip-chars-forward " \t\r\n")
494 (signal 'json-error (list "Trailing garbage following JSON data")))))
496 (provide 'notmuch-lib)
499 ;; byte-compile-warnings: (not cl-functions)