]> git.notmuchmail.org Git - notmuch/blob - emacs/notmuch-lib.el
emacs: Fix "not defined at runtime" warning
[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 <http://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 (require 'mm-view)
25 (require 'mm-decode)
26 (require 'json)
27 (require 'cl)
28
29 (defvar notmuch-command "notmuch"
30   "Command to run the notmuch binary.")
31
32 (defgroup notmuch nil
33   "Notmuch mail reader for Emacs."
34   :group 'mail)
35
36 (defgroup notmuch-hello nil
37   "Overview of saved searches, tags, etc."
38   :group 'notmuch)
39
40 (defgroup notmuch-search nil
41   "Searching and sorting mail."
42   :group 'notmuch)
43
44 (defgroup notmuch-show nil
45   "Showing messages and threads."
46   :group 'notmuch)
47
48 (defgroup notmuch-send nil
49   "Sending messages from Notmuch."
50   :group 'notmuch)
51
52 (custom-add-to-group 'notmuch-send 'message 'custom-group)
53
54 (defgroup notmuch-crypto nil
55   "Processing and display of cryptographic MIME parts."
56   :group 'notmuch)
57
58 (defgroup notmuch-hooks nil
59   "Running custom code on well-defined occasions."
60   :group 'notmuch)
61
62 (defgroup notmuch-external nil
63   "Running external commands from within Notmuch."
64   :group 'notmuch)
65
66 (defgroup notmuch-faces nil
67   "Graphical attributes for displaying text"
68   :group 'notmuch)
69
70 (defcustom notmuch-search-oldest-first t
71   "Show the oldest mail first when searching."
72   :type 'boolean
73   :group 'notmuch-search)
74
75 ;;
76
77 (defvar notmuch-search-history nil
78   "Variable to store notmuch searches history.")
79
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)
84
85 (defvar notmuch-folders nil
86   "Deprecated name for what is now known as `notmuch-saved-searches'.")
87
88 (defun notmuch-saved-searches ()
89   "Common function for querying the notmuch-saved-searches variable.
90
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
96     (if notmuch-folders
97         notmuch-folders
98       '(("inbox" . "tag:inbox")
99         ("unread" . "tag:unread")))))
100
101 (defun notmuch-version ()
102   "Return a string with the notmuch version number."
103   (let ((long-string
104          ;; Trim off the trailing newline.
105          (substring (shell-command-to-string
106                      (concat notmuch-command " --version"))
107                     0 -1)))
108     (if (string-match "^notmuch\\( version\\)? \\(.*\\)$"
109                       long-string)
110         (match-string 2 long-string)
111       "unknown")))
112
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))
118               0 -1))
119
120 (defun notmuch-database-path ()
121   "Return the database.path value from the notmuch configuration."
122   (notmuch-config-get "database.path"))
123
124 (defun notmuch-user-name ()
125   "Return the user.name value from the notmuch configuration."
126   (notmuch-config-get "user.name"))
127
128 (defun notmuch-user-primary-email ()
129   "Return the user.primary_email value from the notmuch configuration."
130   (notmuch-config-get "user.primary_email"))
131
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"))
135
136 (defun notmuch-kill-this-buffer ()
137   "Kill the current buffer."
138   (interactive)
139   (kill-buffer (current-buffer)))
140
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.
144   (save-match-data
145     (if (and subject
146              (string-match "^[ \t]*$" subject))
147         "[No Subject]"
148       subject)))
149
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) "\""))
153
154 ;;
155
156 (defun notmuch-common-do-stash (text)
157   "Common function to stash text in kill ring, and display in minibuffer."
158   (kill-new text)
159   (message "Stashed: %s" text))
160
161 ;;
162
163 (defun notmuch-remove-if-not (predicate list)
164   "Return a copy of LIST with all items not satisfying PREDICATE removed."
165   (let (out)
166     (while list
167       (when (funcall predicate (car list))
168         (push (car list) out))
169       (setq list (cdr list)))
170     (nreverse out)))
171
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
177 ;; rid of.
178 ;;
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)
183         form))
184
185 (defun notmuch-split-content-type (content-type)
186   "Split content/type into 'content' and 'type'"
187   (split-string content-type "/"))
188
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)))))
198
199 (defvar notmuch-multipart/alternative-discouraged
200   '(
201     ;; Avoid HTML parts.
202     "text/html"
203     ;; multipart/related usually contain a text/html part and some associated graphics.
204     "multipart/related"
205     ))
206
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'.
210   (let ((seq types))
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))))))
215     seq))
216
217 (defun notmuch-parts-filter-by-type (parts type)
218   "Given a list of message parts, return a list containing the ones matching
219 the given type."
220   (remove-if-not
221    (lambda (part) (notmuch-match-content-type (plist-get part :content-type) type))
222    parts))
223
224 ;; Helper for parts which are generally not included in the default
225 ;; JSON output.
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)))
230     (if process-crypto
231         (setq args (append args '("--decrypt"))))
232     (setq args (append args (list query)))
233     (with-temp-buffer
234       (let ((coding-system-for-read 'no-conversion))
235         (progn
236           (apply 'call-process (append (list notmuch-command nil (list t nil) nil) args))
237           (buffer-string))))))
238
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)))
242
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)))
247     (with-temp-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)
252                           'gnus-decoded
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)
263             t))))))
264
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)))
271
272 (defun notmuch-combine-face-text-property (start end face)
273   "Combine FACE into the 'face text property between START and END.
274
275 This function combines FACE with any existing faces between START
276 and END.  Attributes specified by FACE take precedence over
277 existing attributes.  FACE must be a face name (a symbol or
278 string), a property list of face attributes, or a list of these."
279
280   (let ((pos start))
281     (while (< pos end)
282       (let ((cur (get-text-property pos 'face))
283             (next (next-single-property-change pos 'face nil end)))
284         (put-text-property pos next 'face (cons face cur))
285         (setq pos next)))))
286
287 ;; Compatibility functions for versions of emacs before emacs 23.
288 ;;
289 ;; Both functions here were copied from emacs 23 with the following copyright:
290 ;;
291 ;; Copyright (C) 1985, 1986, 1992, 1994, 1995, 1999, 2000, 2001, 2002, 2003,
292 ;;   2004, 2005, 2006, 2007, 2008, 2009, 2010 Free Software Foundation, Inc.
293 ;;
294 ;; and under the GPL version 3 (or later) exactly as notmuch itself.
295 (compile-on-emacs-prior-to-23
296  (defun apply-partially (fun &rest args)
297    "Return a function that is a partial application of FUN to ARGS.
298 ARGS is a list of the first N arguments to pass to FUN.
299 The result is a new function which does the same as FUN, except that
300 the first N arguments are fixed at the values with which this function
301 was called."
302    (lexical-let ((fun fun) (args1 args))
303      (lambda (&rest args2) (apply fun (append args1 args2))))))
304
305 (compile-on-emacs-prior-to-23
306  (defun mouse-event-p (object)
307    "Return non-nil if OBJECT is a mouse click event."
308    (memq (event-basic-type object) '(mouse-1 mouse-2 mouse-3 mouse-movement))))
309
310 ;; This variable is used only buffer local, but it needs to be
311 ;; declared globally first to avoid compiler warnings.
312 (defvar notmuch-show-process-crypto nil)
313 (make-variable-buffer-local 'notmuch-show-process-crypto)
314
315 ;; Incremental JSON parsing
316
317 (defun notmuch-json-create-parser (buffer)
318   "Return a streaming JSON parser that consumes input from BUFFER.
319
320 This parser is designed to read streaming JSON whose structure is
321 known to the caller.  Like a typical JSON parsing interface, it
322 provides a function to read a complete JSON value from the input.
323 However, it extends this with an additional function that
324 requires the next value in the input to be a compound value and
325 descends into it, allowing its elements to be read one at a time
326 or further descended into.  Both functions can return 'retry to
327 indicate that not enough input is available.
328
329 The parser always consumes input from BUFFER's point.  Hence, the
330 caller is allowed to delete and data before point and may
331 resynchronize after an error by moving point."
332
333   (list buffer
334         ;; Terminator stack: a stack of characters that indicate the
335         ;; end of the compound values enclosing point
336         '()
337         ;; Next: One of
338         ;; * 'expect-value if the next token must be a value, but a
339         ;;   value has not yet been reached
340         ;; * 'value if point is at the beginning of a value
341         ;; * 'expect-comma if the next token must be a comma
342         'expect-value
343         ;; Allow terminator: non-nil if the next token may be a
344         ;; terminator
345         nil
346         ;; Partial parse position: If state is 'value, a marker for
347         ;; the position of the partial parser or nil if no partial
348         ;; parsing has happened yet
349         nil
350         ;; Partial parse state: If state is 'value, the current
351         ;; `parse-partial-sexp' state
352         nil))
353
354 (defmacro notmuch-json-buffer (jp) `(first ,jp))
355 (defmacro notmuch-json-term-stack (jp) `(second ,jp))
356 (defmacro notmuch-json-next (jp) `(third ,jp))
357 (defmacro notmuch-json-allow-term (jp) `(fourth ,jp))
358 (defmacro notmuch-json-partial-pos (jp) `(fifth ,jp))
359 (defmacro notmuch-json-partial-state (jp) `(sixth ,jp))
360
361 (defvar notmuch-json-syntax-table
362   (let ((table (make-syntax-table)))
363     ;; The standard syntax table is what we need except that "." needs
364     ;; to have word syntax instead of punctuation syntax.
365     (modify-syntax-entry ?. "w" table)
366     table)
367   "Syntax table used for incremental JSON parsing.")
368
369 (defun notmuch-json-scan-to-value (jp)
370   ;; Helper function that consumes separators, terminators, and
371   ;; whitespace from point.  Returns nil if it successfully reached
372   ;; the beginning of a value, 'end if it consumed a terminator, or
373   ;; 'retry if not enough input was available to reach a value.  Upon
374   ;; nil return, (notmuch-json-next jp) is always 'value.
375
376   (if (eq (notmuch-json-next jp) 'value)
377       ;; We're already at a value
378       nil
379     ;; Drive the state toward 'expect-value
380     (skip-chars-forward " \t\r\n")
381     (or (when (eobp) 'retry)
382         ;; Test for the terminator for the current compound
383         (when (and (notmuch-json-allow-term jp)
384                    (eq (char-after) (car (notmuch-json-term-stack jp))))
385           ;; Consume it and expect a comma or terminator next
386           (forward-char)
387           (setf (notmuch-json-term-stack jp) (cdr (notmuch-json-term-stack jp))
388                 (notmuch-json-next jp) 'expect-comma
389                 (notmuch-json-allow-term jp) t)
390           'end)
391         ;; Test for a separator
392         (when (eq (notmuch-json-next jp) 'expect-comma)
393           (when (/= (char-after) ?,)
394             (signal 'json-readtable-error (list "expected ','")))
395           ;; Consume it, switch to 'expect-value, and disallow a
396           ;; terminator
397           (forward-char)
398           (skip-chars-forward " \t\r\n")
399           (setf (notmuch-json-next jp) 'expect-value
400                 (notmuch-json-allow-term jp) nil)
401           ;; We moved point, so test for eobp again and fall through
402           ;; to the next test if there's more input
403           (when (eobp) 'retry))
404         ;; Next must be 'expect-value and we know this isn't
405         ;; whitespace, EOB, or a terminator, so point must be on a
406         ;; value
407         (progn
408           (assert (eq (notmuch-json-next jp) 'expect-value))
409           (setf (notmuch-json-next jp) 'value)
410           nil))))
411
412 (defun notmuch-json-begin-compound (jp)
413   "Parse the beginning of a compound value and traverse inside it.
414
415 Returns 'retry if there is insufficient input to parse the
416 beginning of the compound.  If this is able to parse the
417 beginning of a compound, it moves point past the token that opens
418 the compound and returns t.  Later calls to `notmuch-json-read'
419 will return the compound's elements.
420
421 Entering JSON objects is currently unimplemented."
422
423   (with-current-buffer (notmuch-json-buffer jp)
424     ;; Disallow terminators
425     (setf (notmuch-json-allow-term jp) nil)
426     (or (notmuch-json-scan-to-value jp)
427         (if (/= (char-after) ?\[)
428             (signal 'json-readtable-error (list "expected '['"))
429           (forward-char)
430           (push ?\] (notmuch-json-term-stack jp))
431           ;; Expect a value or terminator next
432           (setf (notmuch-json-next jp) 'expect-value
433                 (notmuch-json-allow-term jp) t)
434           t))))
435
436 (defun notmuch-json-read (jp)
437   "Parse the value at point in JP's buffer.
438
439 Returns 'retry if there is insufficient input to parse a complete
440 JSON value (though it may still move point over separators or
441 whitespace).  If the parser is currently inside a compound value
442 and the next token ends the list or object, this moves point just
443 past the terminator and returns 'end.  Otherwise, this moves
444 point to just past the end of the value and returns the value."
445
446   (with-current-buffer (notmuch-json-buffer jp)
447     (or
448      ;; Get to a value state
449      (notmuch-json-scan-to-value jp)
450
451      ;; Can we parse a complete value?
452      (let ((complete
453             (if (looking-at "[-+0-9tfn]")
454                 ;; This is a number or a keyword, so the partial
455                 ;; parser isn't going to help us because a truncated
456                 ;; number or keyword looks like a complete symbol to
457                 ;; it.  Look for something that clearly ends it.
458                 (save-excursion
459                   (skip-chars-forward "^]},: \t\r\n")
460                   (not (eobp)))
461
462               ;; We're looking at a string, object, or array, which we
463               ;; can partial parse.  If we just reached the value, set
464               ;; up the partial parser.
465               (when (null (notmuch-json-partial-state jp))
466                 (setf (notmuch-json-partial-pos jp) (point-marker)))
467
468               ;; Extend the partial parse until we either reach EOB or
469               ;; get the whole value
470               (save-excursion
471                 (let ((pstate
472                        (with-syntax-table notmuch-json-syntax-table
473                          (parse-partial-sexp
474                           (notmuch-json-partial-pos jp) (point-max) 0 nil
475                           (notmuch-json-partial-state jp)))))
476                   ;; A complete value is available if we've reached
477                   ;; depth 0 or less and encountered a complete
478                   ;; subexpression.
479                   (if (and (<= (first pstate) 0) (third pstate))
480                       t
481                     ;; Not complete.  Update the partial parser state
482                     (setf (notmuch-json-partial-pos jp) (point-marker)
483                           (notmuch-json-partial-state jp) pstate)
484                     nil))))))
485
486        (if (not complete)
487            'retry
488          ;; We have a value.  Reset the partial parse state and expect
489          ;; a comma or terminator after the value.
490          (setf (notmuch-json-next jp) 'expect-comma
491                (notmuch-json-allow-term jp) t
492                (notmuch-json-partial-pos jp) nil
493                (notmuch-json-partial-state jp) nil)
494          ;; Parse the value
495          (let ((json-object-type 'plist)
496                (json-array-type 'list)
497                (json-false nil))
498            (json-read)))))))
499
500 (defun notmuch-json-eof (jp)
501   "Signal a json-error if there is more data in JP's buffer.
502
503 Moves point to the beginning of any trailing data or to the end
504 of the buffer if there is only trailing whitespace."
505
506   (with-current-buffer (notmuch-json-buffer jp)
507     (skip-chars-forward " \t\r\n")
508     (unless (eobp)
509       (signal 'json-error (list "Trailing garbage following JSON data")))))
510
511 (provide 'notmuch-lib)
512
513 ;; Local Variables:
514 ;; byte-compile-warnings: (not cl-functions)
515 ;; End: