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 '(("inbox" . "tag:inbox")
81 ("unread" . "tag:unread"))
82 "A list of saved searches to display."
83 :type '(alist :key-type string :value-type string)
84 :group 'notmuch-hello)
86 (defcustom notmuch-archive-tags '("-inbox")
87 "List of tag changes to apply to a message or a thread when it is archived.
89 Tags starting with \"+\" (or not starting with either \"+\" or
90 \"-\") in the list will be added, and tags starting with \"-\"
91 will be removed from the message or thread being archived.
93 For example, if you wanted to remove an \"inbox\" tag and add an
94 \"archived\" tag, you would set:
95 (\"-inbox\" \"+archived\")"
96 :type '(repeat string)
97 :group 'notmuch-search
100 (defun notmuch-version ()
101 "Return a string with the notmuch version number."
103 ;; Trim off the trailing newline.
104 (substring (shell-command-to-string
105 (concat notmuch-command " --version"))
107 (if (string-match "^notmuch\\( version\\)? \\(.*\\)$"
109 (match-string 2 long-string)
112 (defun notmuch-config-get (item)
113 "Return a value from the notmuch configuration."
114 ;; Trim off the trailing newline
115 (substring (shell-command-to-string
116 (concat notmuch-command " config get " item))
119 (defun notmuch-database-path ()
120 "Return the database.path value from the notmuch configuration."
121 (notmuch-config-get "database.path"))
123 (defun notmuch-user-name ()
124 "Return the user.name value from the notmuch configuration."
125 (notmuch-config-get "user.name"))
127 (defun notmuch-user-primary-email ()
128 "Return the user.primary_email value from the notmuch configuration."
129 (notmuch-config-get "user.primary_email"))
131 (defun notmuch-user-other-email ()
132 "Return the user.other_email value (as a list) from the notmuch configuration."
133 (split-string (notmuch-config-get "user.other_email") "\n"))
135 (defun notmuch-kill-this-buffer ()
136 "Kill the current buffer."
138 (kill-buffer (current-buffer)))
140 (defun notmuch-prettify-subject (subject)
141 ;; This function is used by `notmuch-search-process-filter' which
142 ;; requires that we not disrupt its' matching state.
145 (string-match "^[ \t]*$" subject))
149 (defun notmuch-escape-boolean-term (term)
150 "Escape a boolean term for use in a query.
152 The caller is responsible for prepending the term prefix and a
153 colon. This performs minimal escaping in order to produce
154 user-friendly queries."
157 (if (or (equal term "")
158 (string-match "[ ()]\\|^\"" term))
160 (concat "\"" (replace-regexp-in-string "\"" "\"\"" term t t) "\"")
163 (defun notmuch-id-to-query (id)
164 "Return a query that matches the message with id ID."
165 (concat "id:" (notmuch-escape-boolean-term id)))
169 (defun notmuch-common-do-stash (text)
170 "Common function to stash text in kill ring, and display in minibuffer."
172 (message "Stashed: %s" text))
176 (defun notmuch-remove-if-not (predicate list)
177 "Return a copy of LIST with all items not satisfying PREDICATE removed."
180 (when (funcall predicate (car list))
181 (push (car list) out))
182 (setq list (cdr list)))
185 ;; This lets us avoid compiling these replacement functions when emacs
186 ;; is sufficiently new enough to supply them alone. We do the macro
187 ;; treatment rather than just wrapping our defun calls in a when form
188 ;; specifically so that the compiler never sees the code on new emacs,
189 ;; (since the code is triggering warnings that we don't know how to get
192 ;; A more clever macro here would accept a condition and a list of forms.
193 (defmacro compile-on-emacs-prior-to-23 (form)
194 "Conditionally evaluate form only on emacs < emacs-23."
195 (list 'when (< emacs-major-version 23)
198 (defun notmuch-split-content-type (content-type)
199 "Split content/type into 'content' and 'type'"
200 (split-string content-type "/"))
202 (defun notmuch-match-content-type (t1 t2)
203 "Return t if t1 and t2 are matching content types, taking wildcards into account"
204 (let ((st1 (notmuch-split-content-type t1))
205 (st2 (notmuch-split-content-type t2)))
206 (if (or (string= (cadr st1) "*")
207 (string= (cadr st2) "*"))
208 ;; Comparison of content types should be case insensitive.
209 (string= (downcase (car st1)) (downcase (car st2)))
210 (string= (downcase t1) (downcase t2)))))
212 (defvar notmuch-multipart/alternative-discouraged
216 ;; multipart/related usually contain a text/html part and some associated graphics.
220 (defun notmuch-multipart/alternative-choose (types)
221 "Return a list of preferred types from the given list of types"
222 ;; Based on `mm-preferred-alternative-precedence'.
224 (dolist (pref (reverse notmuch-multipart/alternative-discouraged))
225 (dolist (elem (copy-sequence seq))
226 (when (string-match pref elem)
227 (setq seq (nconc (delete elem seq) (list elem))))))
230 (defun notmuch-parts-filter-by-type (parts type)
231 "Given a list of message parts, return a list containing the ones matching
234 (lambda (part) (notmuch-match-content-type (plist-get part :content-type) type))
237 ;; Helper for parts which are generally not included in the default
239 (defun notmuch-get-bodypart-internal (query part-number process-crypto)
240 (let ((args '("show" "--format=raw"))
241 (part-arg (format "--part=%s" part-number)))
242 (setq args (append args (list part-arg)))
244 (setq args (append args '("--decrypt"))))
245 (setq args (append args (list query)))
247 (let ((coding-system-for-read 'no-conversion))
249 (apply 'call-process (append (list notmuch-command nil (list t nil) nil) args))
252 (defun notmuch-get-bodypart-content (msg part nth process-crypto)
253 (or (plist-get part :content)
254 (notmuch-get-bodypart-internal (notmuch-id-to-query (plist-get msg :id)) nth process-crypto)))
256 ;; Workaround: The call to `mm-display-part' below triggers a bug in
257 ;; Emacs 24 if it attempts to use the shr renderer to display an HTML
258 ;; part with images in it (demonstrated in 24.1 and 24.2 on Debian and
259 ;; Fedora 17, though unreproducable in other configurations).
260 ;; `mm-shr' references the variable `gnus-inhibit-images' without
261 ;; first loading gnus-art, which defines it, resulting in a
262 ;; void-variable error. Hence, we advise `mm-shr' to ensure gnus-art
264 (if (>= emacs-major-version 24)
265 (defadvice mm-shr (before load-gnus-arts activate)
266 (require 'gnus-art nil t)
267 (ad-disable-advice 'mm-shr 'before 'load-gnus-arts)))
269 (defun notmuch-mm-display-part-inline (msg part nth content-type process-crypto)
270 "Use the mm-decode/mm-view functions to display a part in the
271 current buffer, if possible."
272 (let ((display-buffer (current-buffer)))
274 ;; In case there is :content, the content string is already converted
275 ;; into emacs internal format. `gnus-decoded' is a fake charset,
276 ;; which means no further decoding (to be done by mm- functions).
277 (let* ((charset (if (plist-member part :content)
279 (plist-get part :content-charset)))
280 (handle (mm-make-handle (current-buffer) `(,content-type (charset . ,charset)))))
281 ;; If the user wants the part inlined, insert the content and
282 ;; test whether we are able to inline it (which includes both
283 ;; capability and suitability tests).
284 (when (mm-inlined-p handle)
285 (insert (notmuch-get-bodypart-content msg part nth process-crypto))
286 (when (mm-inlinable-p handle)
287 (set-buffer display-buffer)
288 (mm-display-part handle)
291 ;; Converts a plist of headers to an alist of headers. The input plist should
292 ;; have symbols of the form :Header as keys, and the resulting alist will have
293 ;; symbols of the form 'Header as keys.
294 (defun notmuch-headers-plist-to-alist (plist)
295 (loop for (key value . rest) on plist by #'cddr
296 collect (cons (intern (substring (symbol-name key) 1)) value)))
298 (defun notmuch-combine-face-text-property (start end face)
299 "Combine FACE into the 'face text property between START and END.
301 This function combines FACE with any existing faces between START
302 and END. Attributes specified by FACE take precedence over
303 existing attributes. FACE must be a face name (a symbol or
304 string), a property list of face attributes, or a list of these."
308 (let ((cur (get-text-property pos 'face))
309 (next (next-single-property-change pos 'face nil end)))
310 (put-text-property pos next 'face (cons face cur))
313 ;; Compatibility functions for versions of emacs before emacs 23.
315 ;; Both functions here were copied from emacs 23 with the following copyright:
317 ;; Copyright (C) 1985, 1986, 1992, 1994, 1995, 1999, 2000, 2001, 2002, 2003,
318 ;; 2004, 2005, 2006, 2007, 2008, 2009, 2010 Free Software Foundation, Inc.
320 ;; and under the GPL version 3 (or later) exactly as notmuch itself.
321 (compile-on-emacs-prior-to-23
322 (defun apply-partially (fun &rest args)
323 "Return a function that is a partial application of FUN to ARGS.
324 ARGS is a list of the first N arguments to pass to FUN.
325 The result is a new function which does the same as FUN, except that
326 the first N arguments are fixed at the values with which this function
328 (lexical-let ((fun fun) (args1 args))
329 (lambda (&rest args2) (apply fun (append args1 args2))))))
331 (compile-on-emacs-prior-to-23
332 (defun mouse-event-p (object)
333 "Return non-nil if OBJECT is a mouse click event."
334 (memq (event-basic-type object) '(mouse-1 mouse-2 mouse-3 mouse-movement))))
336 ;; This variable is used only buffer local, but it needs to be
337 ;; declared globally first to avoid compiler warnings.
338 (defvar notmuch-show-process-crypto nil)
339 (make-variable-buffer-local 'notmuch-show-process-crypto)
341 ;; Incremental JSON parsing
343 ;; These two variables are internal variables to the parsing
344 ;; routines. They are always used buffer local but need to be declared
345 ;; globally to avoid compiler warnings.
347 (defvar notmuch-json-parser nil
348 "Internal incremental JSON parser object: local to the buffer being parsed.")
350 (defvar notmuch-json-state nil
351 "State of the internal JSON parser: local to the buffer being parsed.")
353 (defun notmuch-json-create-parser (buffer)
354 "Return a streaming JSON parser that consumes input from BUFFER.
356 This parser is designed to read streaming JSON whose structure is
357 known to the caller. Like a typical JSON parsing interface, it
358 provides a function to read a complete JSON value from the input.
359 However, it extends this with an additional function that
360 requires the next value in the input to be a compound value and
361 descends into it, allowing its elements to be read one at a time
362 or further descended into. Both functions can return 'retry to
363 indicate that not enough input is available.
365 The parser always consumes input from BUFFER's point. Hence, the
366 caller is allowed to delete and data before point and may
367 resynchronize after an error by moving point."
370 ;; Terminator stack: a stack of characters that indicate the
371 ;; end of the compound values enclosing point
374 ;; * 'expect-value if the next token must be a value, but a
375 ;; value has not yet been reached
376 ;; * 'value if point is at the beginning of a value
377 ;; * 'expect-comma if the next token must be a comma
379 ;; Allow terminator: non-nil if the next token may be a
382 ;; Partial parse position: If state is 'value, a marker for
383 ;; the position of the partial parser or nil if no partial
384 ;; parsing has happened yet
386 ;; Partial parse state: If state is 'value, the current
387 ;; `parse-partial-sexp' state
390 (defmacro notmuch-json-buffer (jp) `(first ,jp))
391 (defmacro notmuch-json-term-stack (jp) `(second ,jp))
392 (defmacro notmuch-json-next (jp) `(third ,jp))
393 (defmacro notmuch-json-allow-term (jp) `(fourth ,jp))
394 (defmacro notmuch-json-partial-pos (jp) `(fifth ,jp))
395 (defmacro notmuch-json-partial-state (jp) `(sixth ,jp))
397 (defvar notmuch-json-syntax-table
398 (let ((table (make-syntax-table)))
399 ;; The standard syntax table is what we need except that "." needs
400 ;; to have word syntax instead of punctuation syntax.
401 (modify-syntax-entry ?. "w" table)
403 "Syntax table used for incremental JSON parsing.")
405 (defun notmuch-json-scan-to-value (jp)
406 ;; Helper function that consumes separators, terminators, and
407 ;; whitespace from point. Returns nil if it successfully reached
408 ;; the beginning of a value, 'end if it consumed a terminator, or
409 ;; 'retry if not enough input was available to reach a value. Upon
410 ;; nil return, (notmuch-json-next jp) is always 'value.
412 (if (eq (notmuch-json-next jp) 'value)
413 ;; We're already at a value
415 ;; Drive the state toward 'expect-value
416 (skip-chars-forward " \t\r\n")
417 (or (when (eobp) 'retry)
418 ;; Test for the terminator for the current compound
419 (when (and (notmuch-json-allow-term jp)
420 (eq (char-after) (car (notmuch-json-term-stack jp))))
421 ;; Consume it and expect a comma or terminator next
423 (setf (notmuch-json-term-stack jp) (cdr (notmuch-json-term-stack jp))
424 (notmuch-json-next jp) 'expect-comma
425 (notmuch-json-allow-term jp) t)
427 ;; Test for a separator
428 (when (eq (notmuch-json-next jp) 'expect-comma)
429 (when (/= (char-after) ?,)
430 (signal 'json-readtable-error (list "expected ','")))
431 ;; Consume it, switch to 'expect-value, and disallow a
434 (skip-chars-forward " \t\r\n")
435 (setf (notmuch-json-next jp) 'expect-value
436 (notmuch-json-allow-term jp) nil)
437 ;; We moved point, so test for eobp again and fall through
438 ;; to the next test if there's more input
439 (when (eobp) 'retry))
440 ;; Next must be 'expect-value and we know this isn't
441 ;; whitespace, EOB, or a terminator, so point must be on a
444 (assert (eq (notmuch-json-next jp) 'expect-value))
445 (setf (notmuch-json-next jp) 'value)
448 (defun notmuch-json-begin-compound (jp)
449 "Parse the beginning of a compound value and traverse inside it.
451 Returns 'retry if there is insufficient input to parse the
452 beginning of the compound. If this is able to parse the
453 beginning of a compound, it moves point past the token that opens
454 the compound and returns t. Later calls to `notmuch-json-read'
455 will return the compound's elements.
457 Entering JSON objects is currently unimplemented."
459 (with-current-buffer (notmuch-json-buffer jp)
460 ;; Disallow terminators
461 (setf (notmuch-json-allow-term jp) nil)
462 (or (notmuch-json-scan-to-value jp)
463 (if (/= (char-after) ?\[)
464 (signal 'json-readtable-error (list "expected '['"))
466 (push ?\] (notmuch-json-term-stack jp))
467 ;; Expect a value or terminator next
468 (setf (notmuch-json-next jp) 'expect-value
469 (notmuch-json-allow-term jp) t)
472 (defun notmuch-json-read (jp)
473 "Parse the value at point in JP's buffer.
475 Returns 'retry if there is insufficient input to parse a complete
476 JSON value (though it may still move point over separators or
477 whitespace). If the parser is currently inside a compound value
478 and the next token ends the list or object, this moves point just
479 past the terminator and returns 'end. Otherwise, this moves
480 point to just past the end of the value and returns the value."
482 (with-current-buffer (notmuch-json-buffer jp)
484 ;; Get to a value state
485 (notmuch-json-scan-to-value jp)
487 ;; Can we parse a complete value?
489 (if (looking-at "[-+0-9tfn]")
490 ;; This is a number or a keyword, so the partial
491 ;; parser isn't going to help us because a truncated
492 ;; number or keyword looks like a complete symbol to
493 ;; it. Look for something that clearly ends it.
495 (skip-chars-forward "^]},: \t\r\n")
498 ;; We're looking at a string, object, or array, which we
499 ;; can partial parse. If we just reached the value, set
500 ;; up the partial parser.
501 (when (null (notmuch-json-partial-state jp))
502 (setf (notmuch-json-partial-pos jp) (point-marker)))
504 ;; Extend the partial parse until we either reach EOB or
505 ;; get the whole value
508 (with-syntax-table notmuch-json-syntax-table
510 (notmuch-json-partial-pos jp) (point-max) 0 nil
511 (notmuch-json-partial-state jp)))))
512 ;; A complete value is available if we've reached
513 ;; depth 0 or less and encountered a complete
515 (if (and (<= (first pstate) 0) (third pstate))
517 ;; Not complete. Update the partial parser state
518 (setf (notmuch-json-partial-pos jp) (point-marker)
519 (notmuch-json-partial-state jp) pstate)
524 ;; We have a value. Reset the partial parse state and expect
525 ;; a comma or terminator after the value.
526 (setf (notmuch-json-next jp) 'expect-comma
527 (notmuch-json-allow-term jp) t
528 (notmuch-json-partial-pos jp) nil
529 (notmuch-json-partial-state jp) nil)
531 (let ((json-object-type 'plist)
532 (json-array-type 'list)
536 (defun notmuch-json-eof (jp)
537 "Signal a json-error if there is more data in JP's buffer.
539 Moves point to the beginning of any trailing data or to the end
540 of the buffer if there is only trailing whitespace."
542 (with-current-buffer (notmuch-json-buffer jp)
543 (skip-chars-forward " \t\r\n")
545 (signal 'json-error (list "Trailing garbage following JSON data")))))
547 (defun notmuch-json-parse-partial-list (result-function error-function results-buf)
548 "Parse a partial JSON list from current buffer.
550 This function consumes a JSON list from the current buffer,
551 applying RESULT-FUNCTION in buffer RESULT-BUFFER to each complete
552 value in the list. It operates incrementally and should be
553 called whenever the buffer has been extended with additional
556 If there is a syntax error, this will attempt to resynchronize
557 with the input and will apply ERROR-FUNCTION in buffer
558 RESULT-BUFFER to any input that was skipped.
560 It sets up all the needed internal variables: the caller just
561 needs to call it with point in the same place that the parser
564 (unless (local-variable-p 'notmuch-json-parser)
565 (set (make-local-variable 'notmuch-json-parser)
566 (notmuch-json-create-parser (current-buffer)))
567 (set (make-local-variable 'notmuch-json-state) 'begin))
570 (case notmuch-json-state
572 ;; Enter the results list
573 (if (eq (notmuch-json-begin-compound
574 notmuch-json-parser) 'retry)
576 (setq notmuch-json-state 'result)))
579 (let ((result (notmuch-json-read notmuch-json-parser)))
581 ((retry) (setq done t))
582 ((end) (setq notmuch-json-state 'end))
583 (otherwise (with-current-buffer results-buf
584 (funcall result-function result))))))
586 ;; Any trailing data is unexpected
587 (notmuch-json-eof notmuch-json-parser)
590 ;; Do our best to resynchronize and ensure forward
592 (let ((bad (buffer-substring (line-beginning-position)
593 (line-end-position))))
595 (with-current-buffer results-buf
596 (funcall error-function "%s" bad))))))
597 ;; Clear out what we've parsed
598 (delete-region (point-min) (point))))
603 (provide 'notmuch-lib)
606 ;; byte-compile-warnings: (not cl-functions)