]> git.notmuchmail.org Git - notmuch/blob - emacs/notmuch-lib.el
emacs: Utilities to manage asynchronous notmuch processes
[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 '(("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)
85
86 (defcustom notmuch-archive-tags '("-inbox")
87   "List of tag changes to apply to a message or a thread when it is archived.
88
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.
92
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
98   :group 'notmuch-show)
99
100 ;; By default clicking on a button does not select the window
101 ;; containing the button (as opposed to clicking on a widget which
102 ;; does). This means that the button action is then executed in the
103 ;; current selected window which can cause problems if the button
104 ;; changes the buffer (e.g., id: links) or moves point.
105 ;;
106 ;; This provides a button type which overrides mouse-action so that
107 ;; the button's window is selected before the action is run. Other
108 ;; notmuch buttons can get the same behaviour by inheriting from this
109 ;; button type.
110 (define-button-type 'notmuch-button-type
111   'mouse-action (lambda (button)
112                   (select-window (posn-window (event-start last-input-event)))
113                   (button-activate button)))
114
115 (defun notmuch-command-to-string (&rest args)
116   "Synchronously invoke \"notmuch\" with the given list of arguments.
117
118 If notmuch exits with a non-zero status, output from the process
119 will appear in a buffer named \"*Notmuch errors*\" and an error
120 will be signaled.
121
122 Otherwise the output will be returned"
123   (with-temp-buffer
124     (let* ((status (apply #'call-process notmuch-command nil t nil args))
125            (output (buffer-string)))
126       (notmuch-check-exit-status status (cons notmuch-command args) output)
127       output)))
128
129 (defun notmuch-version ()
130   "Return a string with the notmuch version number."
131   (let ((long-string
132          ;; Trim off the trailing newline.
133          (substring (notmuch-command-to-string "--version") 0 -1)))
134     (if (string-match "^notmuch\\( version\\)? \\(.*\\)$"
135                       long-string)
136         (match-string 2 long-string)
137       "unknown")))
138
139 (defun notmuch-config-get (item)
140   "Return a value from the notmuch configuration."
141   ;; Trim off the trailing newline
142   (substring (notmuch-command-to-string "config" "get" item) 0 -1))
143
144 (defun notmuch-database-path ()
145   "Return the database.path value from the notmuch configuration."
146   (notmuch-config-get "database.path"))
147
148 (defun notmuch-user-name ()
149   "Return the user.name value from the notmuch configuration."
150   (notmuch-config-get "user.name"))
151
152 (defun notmuch-user-primary-email ()
153   "Return the user.primary_email value from the notmuch configuration."
154   (notmuch-config-get "user.primary_email"))
155
156 (defun notmuch-user-other-email ()
157   "Return the user.other_email value (as a list) from the notmuch configuration."
158   (split-string (notmuch-config-get "user.other_email") "\n"))
159
160 (defun notmuch-kill-this-buffer ()
161   "Kill the current buffer."
162   (interactive)
163   (kill-buffer (current-buffer)))
164
165 (defun notmuch-prettify-subject (subject)
166   ;; This function is used by `notmuch-search-process-filter' which
167   ;; requires that we not disrupt its' matching state.
168   (save-match-data
169     (if (and subject
170              (string-match "^[ \t]*$" subject))
171         "[No Subject]"
172       subject)))
173
174 (defun notmuch-escape-boolean-term (term)
175   "Escape a boolean term for use in a query.
176
177 The caller is responsible for prepending the term prefix and a
178 colon.  This performs minimal escaping in order to produce
179 user-friendly queries."
180
181   (save-match-data
182     (if (or (equal term "")
183             (string-match "[ ()]\\|^\"" term))
184         ;; Requires escaping
185         (concat "\"" (replace-regexp-in-string "\"" "\"\"" term t t) "\"")
186       term)))
187
188 (defun notmuch-id-to-query (id)
189   "Return a query that matches the message with id ID."
190   (concat "id:" (notmuch-escape-boolean-term id)))
191
192 ;;
193
194 (defun notmuch-common-do-stash (text)
195   "Common function to stash text in kill ring, and display in minibuffer."
196   (if text
197       (progn
198         (kill-new text)
199         (message "Stashed: %s" text))
200     ;; There is nothing to stash so stash an empty string so the user
201     ;; doesn't accidentally paste something else somewhere.
202     (kill-new "")
203     (message "Nothing to stash!")))
204
205 ;;
206
207 (defun notmuch-remove-if-not (predicate list)
208   "Return a copy of LIST with all items not satisfying PREDICATE removed."
209   (let (out)
210     (while list
211       (when (funcall predicate (car list))
212         (push (car list) out))
213       (setq list (cdr list)))
214     (nreverse out)))
215
216 (defun notmuch-split-content-type (content-type)
217   "Split content/type into 'content' and 'type'"
218   (split-string content-type "/"))
219
220 (defun notmuch-match-content-type (t1 t2)
221   "Return t if t1 and t2 are matching content types, taking wildcards into account"
222   (let ((st1 (notmuch-split-content-type t1))
223         (st2 (notmuch-split-content-type t2)))
224     (if (or (string= (cadr st1) "*")
225             (string= (cadr st2) "*"))
226         ;; Comparison of content types should be case insensitive.
227         (string= (downcase (car st1)) (downcase (car st2)))
228       (string= (downcase t1) (downcase t2)))))
229
230 (defvar notmuch-multipart/alternative-discouraged
231   '(
232     ;; Avoid HTML parts.
233     "text/html"
234     ;; multipart/related usually contain a text/html part and some associated graphics.
235     "multipart/related"
236     ))
237
238 (defun notmuch-multipart/alternative-choose (types)
239   "Return a list of preferred types from the given list of types"
240   ;; Based on `mm-preferred-alternative-precedence'.
241   (let ((seq types))
242     (dolist (pref (reverse notmuch-multipart/alternative-discouraged))
243       (dolist (elem (copy-sequence seq))
244         (when (string-match pref elem)
245           (setq seq (nconc (delete elem seq) (list elem))))))
246     seq))
247
248 (defun notmuch-parts-filter-by-type (parts type)
249   "Given a list of message parts, return a list containing the ones matching
250 the given type."
251   (remove-if-not
252    (lambda (part) (notmuch-match-content-type (plist-get part :content-type) type))
253    parts))
254
255 ;; Helper for parts which are generally not included in the default
256 ;; JSON output.
257 (defun notmuch-get-bodypart-internal (query part-number process-crypto)
258   (let ((args '("show" "--format=raw"))
259         (part-arg (format "--part=%s" part-number)))
260     (setq args (append args (list part-arg)))
261     (if process-crypto
262         (setq args (append args '("--decrypt"))))
263     (setq args (append args (list query)))
264     (with-temp-buffer
265       (let ((coding-system-for-read 'no-conversion))
266         (progn
267           (apply 'call-process (append (list notmuch-command nil (list t nil) nil) args))
268           (buffer-string))))))
269
270 (defun notmuch-get-bodypart-content (msg part nth process-crypto)
271   (or (plist-get part :content)
272       (notmuch-get-bodypart-internal (notmuch-id-to-query (plist-get msg :id)) nth process-crypto)))
273
274 ;; Workaround: The call to `mm-display-part' below triggers a bug in
275 ;; Emacs 24 if it attempts to use the shr renderer to display an HTML
276 ;; part with images in it (demonstrated in 24.1 and 24.2 on Debian and
277 ;; Fedora 17, though unreproducable in other configurations).
278 ;; `mm-shr' references the variable `gnus-inhibit-images' without
279 ;; first loading gnus-art, which defines it, resulting in a
280 ;; void-variable error.  Hence, we advise `mm-shr' to ensure gnus-art
281 ;; is loaded.
282 (if (>= emacs-major-version 24)
283     (defadvice mm-shr (before load-gnus-arts activate)
284       (require 'gnus-art nil t)
285       (ad-disable-advice 'mm-shr 'before 'load-gnus-arts)))
286
287 (defun notmuch-mm-display-part-inline (msg part nth content-type process-crypto)
288   "Use the mm-decode/mm-view functions to display a part in the
289 current buffer, if possible."
290   (let ((display-buffer (current-buffer)))
291     (with-temp-buffer
292       ;; In case there is :content, the content string is already converted
293       ;; into emacs internal format. `gnus-decoded' is a fake charset,
294       ;; which means no further decoding (to be done by mm- functions).
295       (let* ((charset (if (plist-member part :content)
296                           'gnus-decoded
297                         (plist-get part :content-charset)))
298              (handle (mm-make-handle (current-buffer) `(,content-type (charset . ,charset)))))
299         ;; If the user wants the part inlined, insert the content and
300         ;; test whether we are able to inline it (which includes both
301         ;; capability and suitability tests).
302         (when (mm-inlined-p handle)
303           (insert (notmuch-get-bodypart-content msg part nth process-crypto))
304           (when (mm-inlinable-p handle)
305             (set-buffer display-buffer)
306             (mm-display-part handle)
307             t))))))
308
309 ;; Converts a plist of headers to an alist of headers. The input plist should
310 ;; have symbols of the form :Header as keys, and the resulting alist will have
311 ;; symbols of the form 'Header as keys.
312 (defun notmuch-headers-plist-to-alist (plist)
313   (loop for (key value . rest) on plist by #'cddr
314         collect (cons (intern (substring (symbol-name key) 1)) value)))
315
316 (defun notmuch-face-ensure-list-form (face)
317   "Return FACE in face list form.
318
319 If FACE is already a face list, it will be returned as-is.  If
320 FACE is a face name or face plist, it will be returned as a
321 single element face list."
322   (if (and (listp face) (not (keywordp (car face))))
323       face
324     (list face)))
325
326 (defun notmuch-combine-face-text-property (start end face &optional below object)
327   "Combine FACE into the 'face text property between START and END.
328
329 This function combines FACE with any existing faces between START
330 and END in OBJECT (which defaults to the current buffer).
331 Attributes specified by FACE take precedence over existing
332 attributes unless BELOW is non-nil.  FACE must be a face name (a
333 symbol or string), a property list of face attributes, or a list
334 of these.  For convenience when applied to strings, this returns
335 OBJECT."
336
337   ;; A face property can have three forms: a face name (a string or
338   ;; symbol), a property list, or a list of these two forms.  In the
339   ;; list case, the faces will be combined, with the earlier faces
340   ;; taking precedent.  Here we canonicalize everything to list form
341   ;; to make it easy to combine.
342   (let ((pos start)
343         (face-list (notmuch-face-ensure-list-form face)))
344     (while (< pos end)
345       (let* ((cur (get-text-property pos 'face object))
346              (cur-list (notmuch-face-ensure-list-form cur))
347              (new (cond ((null cur-list) face)
348                         (below (append cur-list face-list))
349                         (t (append face-list cur-list))))
350              (next (next-single-property-change pos 'face object end)))
351         (put-text-property pos next 'face new object)
352         (setq pos next))))
353   object)
354
355 (defun notmuch-combine-face-text-property-string (string face &optional below)
356   (notmuch-combine-face-text-property
357    0
358    (length string)
359    face
360    below
361    string))
362
363 (defun notmuch-map-text-property (start end prop func &optional object)
364   "Transform text property PROP using FUNC.
365
366 Applies FUNC to each distinct value of the text property PROP
367 between START and END of OBJECT, setting PROP to the value
368 returned by FUNC."
369   (while (< start end)
370     (let ((value (get-text-property start prop object))
371           (next (next-single-property-change start prop object end)))
372       (put-text-property start next prop (funcall func value) object)
373       (setq start next))))
374
375 (defun notmuch-logged-error (msg &optional extra)
376   "Log MSG and EXTRA to *Notmuch errors* and signal MSG.
377
378 This logs MSG and EXTRA to the *Notmuch errors* buffer and
379 signals MSG as an error.  If EXTRA is non-nil, text referring the
380 user to the *Notmuch errors* buffer will be appended to the
381 signaled error.  This function does not return."
382
383   (with-current-buffer (get-buffer-create "*Notmuch errors*")
384     (goto-char (point-max))
385     (unless (bobp)
386       (newline))
387     (save-excursion
388       (insert "[" (current-time-string) "]\n" msg)
389       (unless (bolp)
390         (newline))
391       (when extra
392         (insert extra)
393         (unless (bolp)
394           (newline)))))
395   (error "%s" (concat msg (when extra
396                             " (see *Notmuch errors* for more details)"))))
397
398 (defun notmuch-check-async-exit-status (proc msg &optional command err-file)
399   "If PROC exited abnormally, pop up an error buffer and signal an error.
400
401 This is a wrapper around `notmuch-check-exit-status' for
402 asynchronous process sentinels.  PROC and MSG must be the
403 arguments passed to the sentinel.  COMMAND and ERR-FILE, if
404 provided, are passed to `notmuch-check-exit-status'.  If COMMAND
405 is not provided, it is taken from `process-command'."
406   (let ((exit-status
407          (case (process-status proc)
408            ((exit) (process-exit-status proc))
409            ((signal) msg))))
410     (when exit-status
411       (notmuch-check-exit-status exit-status (or command (process-command proc))
412                                  nil err-file))))
413
414 (defun notmuch-check-exit-status (exit-status command &optional output err-file)
415   "If EXIT-STATUS is non-zero, pop up an error buffer and signal an error.
416
417 If EXIT-STATUS is non-zero, pop up a notmuch error buffer
418 describing the error and signal an Elisp error.  EXIT-STATUS must
419 be a number indicating the exit status code of a process or a
420 string describing the signal that terminated the process (such as
421 returned by `call-process').  COMMAND must be a list giving the
422 command and its arguments.  OUTPUT, if provided, is a string
423 giving the output of command.  ERR-FILE, if provided, is the name
424 of a file containing the error output of command.  OUTPUT and the
425 contents of ERR-FILE will be included in the error message."
426
427   (cond
428    ((eq exit-status 0) t)
429    ((eq exit-status 20)
430     (notmuch-logged-error "notmuch CLI version mismatch
431 Emacs requested an older output format than supported by the notmuch CLI.
432 You may need to restart Emacs or upgrade your notmuch Emacs package."))
433    ((eq exit-status 21)
434     (notmuch-logged-error "notmuch CLI version mismatch
435 Emacs requested a newer output format than supported by the notmuch CLI.
436 You may need to restart Emacs or upgrade your notmuch package."))
437    (t
438     (let* ((err (when err-file
439                   (with-temp-buffer
440                     (insert-file-contents err-file)
441                     (unless (eobp)
442                       (buffer-string)))))
443            (extra
444             (concat
445              "command: " (mapconcat #'shell-quote-argument command " ") "\n"
446              (if (integerp exit-status)
447                  (format "exit status: %s\n" exit-status)
448                (format "exit signal: %s\n" exit-status))
449              (when err
450                (concat "stderr:\n" err))
451              (when output
452                (concat "stdout:\n" output)))))
453         (if err
454             ;; We have an error message straight from the CLI.
455             (notmuch-logged-error
456              (replace-regexp-in-string "[ \n\r\t\f]*\\'" "" err) extra)
457           ;; We only have combined output from the CLI; don't inundate
458           ;; the user with it.  Mimic `process-lines'.
459           (notmuch-logged-error (format "%s exited with status %s"
460                                         (car command) exit-status)
461                                 extra))
462         ;; `notmuch-logged-error' does not return.
463         ))))
464
465 (defun notmuch-call-notmuch-json (&rest args)
466   "Invoke `notmuch-command' with ARGS and return the parsed JSON output.
467
468 The returned output will represent objects using property lists
469 and arrays as lists.  If notmuch exits with a non-zero status,
470 this will pop up a buffer containing notmuch's output and signal
471 an error."
472
473   (with-temp-buffer
474     (let ((err-file (make-temp-file "nmerr")))
475       (unwind-protect
476           (let ((status (apply #'call-process
477                                notmuch-command nil (list t err-file) nil args)))
478             (notmuch-check-exit-status status (cons notmuch-command args)
479                                        (buffer-string) err-file)
480             (goto-char (point-min))
481             (let ((json-object-type 'plist)
482                   (json-array-type 'list)
483                   (json-false 'nil))
484               (json-read)))
485         (delete-file err-file)))))
486
487 (defun notmuch-start-notmuch (name buffer sentinel &rest args)
488   "Start and return an asynchronous notmuch command.
489
490 This starts and returns an asynchronous process running
491 `notmuch-command' with ARGS.  The exit status is checked via
492 `notmuch-check-async-exit-status'.  Output written to stderr is
493 redirected and displayed when the process exits (even if the
494 process exits successfully).  NAME and BUFFER are the same as in
495 `start-process'.  SENTINEL is a process sentinel function to call
496 when the process exits, or nil for none.  The caller must *not*
497 invoke `set-process-sentinel' directly on the returned process,
498 as that will interfere with the handling of stderr and the exit
499 status."
500
501   ;; There is no way (as of Emacs 24.3) to capture stdout and stderr
502   ;; separately for asynchronous processes, or even to redirect stderr
503   ;; to a file, so we use a trivial shell wrapper to send stderr to a
504   ;; temporary file and clean things up in the sentinel.
505   (let* ((err-file (make-temp-file "nmerr"))
506          ;; Use a pipe
507          (process-connection-type nil)
508          ;; Find notmuch using Emacs' `exec-path'
509          (command (or (executable-find notmuch-command)
510                       (error "command not found: %s" notmuch-command)))
511          (proc (apply #'start-process name buffer
512                       "/bin/sh" "-c"
513                       "exec 2>\"$1\"; shift; exec \"$0\" \"$@\""
514                       command err-file args)))
515     (process-put proc 'err-file err-file)
516     (process-put proc 'sub-sentinel sentinel)
517     (process-put proc 'real-command (cons notmuch-command args))
518     (set-process-sentinel proc #'notmuch-start-notmuch-sentinel)
519     proc))
520
521 (defun notmuch-start-notmuch-sentinel (proc event)
522   (let ((err-file (process-get proc 'err-file))
523         (sub-sentinel (process-get proc 'sub-sentinel))
524         (real-command (process-get proc 'real-command)))
525     (condition-case err
526         (progn
527           ;; Invoke the sub-sentinel, if any
528           (when sub-sentinel
529             (funcall sub-sentinel proc event))
530           ;; Check the exit status.  This will signal an error if the
531           ;; exit status is non-zero.
532           (notmuch-check-async-exit-status proc event real-command err-file)
533           ;; If that didn't signal an error, then any error output was
534           ;; really warning output.  Show warnings, if any.
535           (let ((warnings
536                  (with-temp-buffer
537                    (unless (= (second (insert-file-contents err-file)) 0)
538                      (end-of-line)
539                      ;; Show first line; stuff remaining lines in the
540                      ;; errors buffer.
541                      (let ((l1 (buffer-substring (point-min) (point))))
542                        (skip-chars-forward "\n")
543                        (cons l1 (unless (eobp)
544                                   (buffer-substring (point) (point-max)))))))))
545             (when warnings
546               (notmuch-logged-error (car warnings) (cdr warnings)))))
547       (error
548        ;; Emacs behaves strangely if an error escapes from a sentinel,
549        ;; so turn errors into messages.
550        (message "%s" (error-message-string err))))
551     (ignore-errors (delete-file err-file))))
552
553 ;; This variable is used only buffer local, but it needs to be
554 ;; declared globally first to avoid compiler warnings.
555 (defvar notmuch-show-process-crypto nil)
556 (make-variable-buffer-local 'notmuch-show-process-crypto)
557
558 ;; Incremental JSON parsing
559
560 ;; These two variables are internal variables to the parsing
561 ;; routines. They are always used buffer local but need to be declared
562 ;; globally to avoid compiler warnings.
563
564 (defvar notmuch-json-parser nil
565   "Internal incremental JSON parser object: local to the buffer being parsed.")
566
567 (defvar notmuch-json-state nil
568   "State of the internal JSON parser: local to the buffer being parsed.")
569
570 (defun notmuch-json-create-parser (buffer)
571   "Return a streaming JSON parser that consumes input from BUFFER.
572
573 This parser is designed to read streaming JSON whose structure is
574 known to the caller.  Like a typical JSON parsing interface, it
575 provides a function to read a complete JSON value from the input.
576 However, it extends this with an additional function that
577 requires the next value in the input to be a compound value and
578 descends into it, allowing its elements to be read one at a time
579 or further descended into.  Both functions can return 'retry to
580 indicate that not enough input is available.
581
582 The parser always consumes input from BUFFER's point.  Hence, the
583 caller is allowed to delete and data before point and may
584 resynchronize after an error by moving point."
585
586   (list buffer
587         ;; Terminator stack: a stack of characters that indicate the
588         ;; end of the compound values enclosing point
589         '()
590         ;; Next: One of
591         ;; * 'expect-value if the next token must be a value, but a
592         ;;   value has not yet been reached
593         ;; * 'value if point is at the beginning of a value
594         ;; * 'expect-comma if the next token must be a comma
595         'expect-value
596         ;; Allow terminator: non-nil if the next token may be a
597         ;; terminator
598         nil
599         ;; Partial parse position: If state is 'value, a marker for
600         ;; the position of the partial parser or nil if no partial
601         ;; parsing has happened yet
602         nil
603         ;; Partial parse state: If state is 'value, the current
604         ;; `parse-partial-sexp' state
605         nil))
606
607 (defmacro notmuch-json-buffer (jp) `(first ,jp))
608 (defmacro notmuch-json-term-stack (jp) `(second ,jp))
609 (defmacro notmuch-json-next (jp) `(third ,jp))
610 (defmacro notmuch-json-allow-term (jp) `(fourth ,jp))
611 (defmacro notmuch-json-partial-pos (jp) `(fifth ,jp))
612 (defmacro notmuch-json-partial-state (jp) `(sixth ,jp))
613
614 (defvar notmuch-json-syntax-table
615   (let ((table (make-syntax-table)))
616     ;; The standard syntax table is what we need except that "." needs
617     ;; to have word syntax instead of punctuation syntax.
618     (modify-syntax-entry ?. "w" table)
619     table)
620   "Syntax table used for incremental JSON parsing.")
621
622 (defun notmuch-json-scan-to-value (jp)
623   ;; Helper function that consumes separators, terminators, and
624   ;; whitespace from point.  Returns nil if it successfully reached
625   ;; the beginning of a value, 'end if it consumed a terminator, or
626   ;; 'retry if not enough input was available to reach a value.  Upon
627   ;; nil return, (notmuch-json-next jp) is always 'value.
628
629   (if (eq (notmuch-json-next jp) 'value)
630       ;; We're already at a value
631       nil
632     ;; Drive the state toward 'expect-value
633     (skip-chars-forward " \t\r\n")
634     (or (when (eobp) 'retry)
635         ;; Test for the terminator for the current compound
636         (when (and (notmuch-json-allow-term jp)
637                    (eq (char-after) (car (notmuch-json-term-stack jp))))
638           ;; Consume it and expect a comma or terminator next
639           (forward-char)
640           (setf (notmuch-json-term-stack jp) (cdr (notmuch-json-term-stack jp))
641                 (notmuch-json-next jp) 'expect-comma
642                 (notmuch-json-allow-term jp) t)
643           'end)
644         ;; Test for a separator
645         (when (eq (notmuch-json-next jp) 'expect-comma)
646           (when (/= (char-after) ?,)
647             (signal 'json-readtable-error (list "expected ','")))
648           ;; Consume it, switch to 'expect-value, and disallow a
649           ;; terminator
650           (forward-char)
651           (skip-chars-forward " \t\r\n")
652           (setf (notmuch-json-next jp) 'expect-value
653                 (notmuch-json-allow-term jp) nil)
654           ;; We moved point, so test for eobp again and fall through
655           ;; to the next test if there's more input
656           (when (eobp) 'retry))
657         ;; Next must be 'expect-value and we know this isn't
658         ;; whitespace, EOB, or a terminator, so point must be on a
659         ;; value
660         (progn
661           (assert (eq (notmuch-json-next jp) 'expect-value))
662           (setf (notmuch-json-next jp) 'value)
663           nil))))
664
665 (defun notmuch-json-begin-compound (jp)
666   "Parse the beginning of a compound value and traverse inside it.
667
668 Returns 'retry if there is insufficient input to parse the
669 beginning of the compound.  If this is able to parse the
670 beginning of a compound, it moves point past the token that opens
671 the compound and returns t.  Later calls to `notmuch-json-read'
672 will return the compound's elements.
673
674 Entering JSON objects is currently unimplemented."
675
676   (with-current-buffer (notmuch-json-buffer jp)
677     ;; Disallow terminators
678     (setf (notmuch-json-allow-term jp) nil)
679     ;; Save "next" so we can restore it if there's a syntax error
680     (let ((saved-next (notmuch-json-next jp)))
681       (or (notmuch-json-scan-to-value jp)
682           (if (/= (char-after) ?\[)
683               (progn
684                 (setf (notmuch-json-next jp) saved-next)
685                 (signal 'json-readtable-error (list "expected '['")))
686             (forward-char)
687             (push ?\] (notmuch-json-term-stack jp))
688             ;; Expect a value or terminator next
689             (setf (notmuch-json-next jp) 'expect-value
690                   (notmuch-json-allow-term jp) t)
691             t)))))
692
693 (defun notmuch-json-read (jp)
694   "Parse the value at point in JP's buffer.
695
696 Returns 'retry if there is insufficient input to parse a complete
697 JSON value (though it may still move point over separators or
698 whitespace).  If the parser is currently inside a compound value
699 and the next token ends the list or object, this moves point just
700 past the terminator and returns 'end.  Otherwise, this moves
701 point to just past the end of the value and returns the value."
702
703   (with-current-buffer (notmuch-json-buffer jp)
704     (or
705      ;; Get to a value state
706      (notmuch-json-scan-to-value jp)
707
708      ;; Can we parse a complete value?
709      (let ((complete
710             (if (looking-at "[-+0-9tfn]")
711                 ;; This is a number or a keyword, so the partial
712                 ;; parser isn't going to help us because a truncated
713                 ;; number or keyword looks like a complete symbol to
714                 ;; it.  Look for something that clearly ends it.
715                 (save-excursion
716                   (skip-chars-forward "^]},: \t\r\n")
717                   (not (eobp)))
718
719               ;; We're looking at a string, object, or array, which we
720               ;; can partial parse.  If we just reached the value, set
721               ;; up the partial parser.
722               (when (null (notmuch-json-partial-state jp))
723                 (setf (notmuch-json-partial-pos jp) (point-marker)))
724
725               ;; Extend the partial parse until we either reach EOB or
726               ;; get the whole value
727               (save-excursion
728                 (let ((pstate
729                        (with-syntax-table notmuch-json-syntax-table
730                          (parse-partial-sexp
731                           (notmuch-json-partial-pos jp) (point-max) 0 nil
732                           (notmuch-json-partial-state jp)))))
733                   ;; A complete value is available if we've reached
734                   ;; depth 0 or less and encountered a complete
735                   ;; subexpression.
736                   (if (and (<= (first pstate) 0) (third pstate))
737                       t
738                     ;; Not complete.  Update the partial parser state
739                     (setf (notmuch-json-partial-pos jp) (point-marker)
740                           (notmuch-json-partial-state jp) pstate)
741                     nil))))))
742
743        (if (not complete)
744            'retry
745          ;; We have a value.  Reset the partial parse state and expect
746          ;; a comma or terminator after the value.
747          (setf (notmuch-json-next jp) 'expect-comma
748                (notmuch-json-allow-term jp) t
749                (notmuch-json-partial-pos jp) nil
750                (notmuch-json-partial-state jp) nil)
751          ;; Parse the value
752          (let ((json-object-type 'plist)
753                (json-array-type 'list)
754                (json-false nil))
755            (json-read)))))))
756
757 (defun notmuch-json-eof (jp)
758   "Signal a json-error if there is more data in JP's buffer.
759
760 Moves point to the beginning of any trailing data or to the end
761 of the buffer if there is only trailing whitespace."
762
763   (with-current-buffer (notmuch-json-buffer jp)
764     (skip-chars-forward " \t\r\n")
765     (unless (eobp)
766       (signal 'json-error (list "Trailing garbage following JSON data")))))
767
768 (defun notmuch-json-parse-partial-list (result-function error-function results-buf)
769   "Parse a partial JSON list from current buffer.
770
771 This function consumes a JSON list from the current buffer,
772 applying RESULT-FUNCTION in buffer RESULT-BUFFER to each complete
773 value in the list.  It operates incrementally and should be
774 called whenever the buffer has been extended with additional
775 data.
776
777 If there is a syntax error, this will attempt to resynchronize
778 with the input and will apply ERROR-FUNCTION in buffer
779 RESULT-BUFFER to any input that was skipped.
780
781 It sets up all the needed internal variables: the caller just
782 needs to call it with point in the same place that the parser
783 left it."
784   (let (done)
785     (unless (local-variable-p 'notmuch-json-parser)
786       (set (make-local-variable 'notmuch-json-parser)
787            (notmuch-json-create-parser (current-buffer)))
788       (set (make-local-variable 'notmuch-json-state) 'begin))
789     (while (not done)
790       (condition-case nil
791           (case notmuch-json-state
792                 ((begin)
793                  ;; Enter the results list
794                  (if (eq (notmuch-json-begin-compound
795                           notmuch-json-parser) 'retry)
796                      (setq done t)
797                    (setq notmuch-json-state 'result)))
798                 ((result)
799                  ;; Parse a result
800                  (let ((result (notmuch-json-read notmuch-json-parser)))
801                    (case result
802                          ((retry) (setq done t))
803                          ((end) (setq notmuch-json-state 'end))
804                          (otherwise (with-current-buffer results-buf
805                                       (funcall result-function result))))))
806                 ((end)
807                  ;; Any trailing data is unexpected
808                  (notmuch-json-eof notmuch-json-parser)
809                  (setq done t)))
810         (json-error
811          ;; Do our best to resynchronize and ensure forward
812          ;; progress
813          (let ((bad (buffer-substring (line-beginning-position)
814                                       (line-end-position))))
815            (forward-line)
816            (with-current-buffer results-buf
817              (funcall error-function "%s" bad))))))
818     ;; Clear out what we've parsed
819     (delete-region (point-min) (point))))
820
821
822
823
824 (provide 'notmuch-lib)
825
826 ;; Local Variables:
827 ;; byte-compile-warnings: (not cl-functions)
828 ;; End: