]> git.notmuchmail.org Git - notmuch/blob - emacs/notmuch-lib.el
emacs: introduce notmuch-command-to-string, replace use of shell-command-to-string
[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 ;; This lets us avoid compiling these replacement functions when emacs
217 ;; is sufficiently new enough to supply them alone. We do the macro
218 ;; treatment rather than just wrapping our defun calls in a when form
219 ;; specifically so that the compiler never sees the code on new emacs,
220 ;; (since the code is triggering warnings that we don't know how to get
221 ;; rid of.
222 ;;
223 ;; A more clever macro here would accept a condition and a list of forms.
224 (defmacro compile-on-emacs-prior-to-23 (form)
225   "Conditionally evaluate form only on emacs < emacs-23."
226   (list 'when (< emacs-major-version 23)
227         form))
228
229 (defun notmuch-split-content-type (content-type)
230   "Split content/type into 'content' and 'type'"
231   (split-string content-type "/"))
232
233 (defun notmuch-match-content-type (t1 t2)
234   "Return t if t1 and t2 are matching content types, taking wildcards into account"
235   (let ((st1 (notmuch-split-content-type t1))
236         (st2 (notmuch-split-content-type t2)))
237     (if (or (string= (cadr st1) "*")
238             (string= (cadr st2) "*"))
239         ;; Comparison of content types should be case insensitive.
240         (string= (downcase (car st1)) (downcase (car st2)))
241       (string= (downcase t1) (downcase t2)))))
242
243 (defvar notmuch-multipart/alternative-discouraged
244   '(
245     ;; Avoid HTML parts.
246     "text/html"
247     ;; multipart/related usually contain a text/html part and some associated graphics.
248     "multipart/related"
249     ))
250
251 (defun notmuch-multipart/alternative-choose (types)
252   "Return a list of preferred types from the given list of types"
253   ;; Based on `mm-preferred-alternative-precedence'.
254   (let ((seq types))
255     (dolist (pref (reverse notmuch-multipart/alternative-discouraged))
256       (dolist (elem (copy-sequence seq))
257         (when (string-match pref elem)
258           (setq seq (nconc (delete elem seq) (list elem))))))
259     seq))
260
261 (defun notmuch-parts-filter-by-type (parts type)
262   "Given a list of message parts, return a list containing the ones matching
263 the given type."
264   (remove-if-not
265    (lambda (part) (notmuch-match-content-type (plist-get part :content-type) type))
266    parts))
267
268 ;; Helper for parts which are generally not included in the default
269 ;; JSON output.
270 (defun notmuch-get-bodypart-internal (query part-number process-crypto)
271   (let ((args '("show" "--format=raw"))
272         (part-arg (format "--part=%s" part-number)))
273     (setq args (append args (list part-arg)))
274     (if process-crypto
275         (setq args (append args '("--decrypt"))))
276     (setq args (append args (list query)))
277     (with-temp-buffer
278       (let ((coding-system-for-read 'no-conversion))
279         (progn
280           (apply 'call-process (append (list notmuch-command nil (list t nil) nil) args))
281           (buffer-string))))))
282
283 (defun notmuch-get-bodypart-content (msg part nth process-crypto)
284   (or (plist-get part :content)
285       (notmuch-get-bodypart-internal (notmuch-id-to-query (plist-get msg :id)) nth process-crypto)))
286
287 ;; Workaround: The call to `mm-display-part' below triggers a bug in
288 ;; Emacs 24 if it attempts to use the shr renderer to display an HTML
289 ;; part with images in it (demonstrated in 24.1 and 24.2 on Debian and
290 ;; Fedora 17, though unreproducable in other configurations).
291 ;; `mm-shr' references the variable `gnus-inhibit-images' without
292 ;; first loading gnus-art, which defines it, resulting in a
293 ;; void-variable error.  Hence, we advise `mm-shr' to ensure gnus-art
294 ;; is loaded.
295 (if (>= emacs-major-version 24)
296     (defadvice mm-shr (before load-gnus-arts activate)
297       (require 'gnus-art nil t)
298       (ad-disable-advice 'mm-shr 'before 'load-gnus-arts)))
299
300 (defun notmuch-mm-display-part-inline (msg part nth content-type process-crypto)
301   "Use the mm-decode/mm-view functions to display a part in the
302 current buffer, if possible."
303   (let ((display-buffer (current-buffer)))
304     (with-temp-buffer
305       ;; In case there is :content, the content string is already converted
306       ;; into emacs internal format. `gnus-decoded' is a fake charset,
307       ;; which means no further decoding (to be done by mm- functions).
308       (let* ((charset (if (plist-member part :content)
309                           'gnus-decoded
310                         (plist-get part :content-charset)))
311              (handle (mm-make-handle (current-buffer) `(,content-type (charset . ,charset)))))
312         ;; If the user wants the part inlined, insert the content and
313         ;; test whether we are able to inline it (which includes both
314         ;; capability and suitability tests).
315         (when (mm-inlined-p handle)
316           (insert (notmuch-get-bodypart-content msg part nth process-crypto))
317           (when (mm-inlinable-p handle)
318             (set-buffer display-buffer)
319             (mm-display-part handle)
320             t))))))
321
322 ;; Converts a plist of headers to an alist of headers. The input plist should
323 ;; have symbols of the form :Header as keys, and the resulting alist will have
324 ;; symbols of the form 'Header as keys.
325 (defun notmuch-headers-plist-to-alist (plist)
326   (loop for (key value . rest) on plist by #'cddr
327         collect (cons (intern (substring (symbol-name key) 1)) value)))
328
329 (defun notmuch-face-ensure-list-form (face)
330   "Return FACE in face list form.
331
332 If FACE is already a face list, it will be returned as-is.  If
333 FACE is a face name or face plist, it will be returned as a
334 single element face list."
335   (if (and (listp face) (not (keywordp (car face))))
336       face
337     (list face)))
338
339 (defun notmuch-combine-face-text-property (start end face &optional below object)
340   "Combine FACE into the 'face text property between START and END.
341
342 This function combines FACE with any existing faces between START
343 and END in OBJECT (which defaults to the current buffer).
344 Attributes specified by FACE take precedence over existing
345 attributes unless BELOW is non-nil.  FACE must be a face name (a
346 symbol or string), a property list of face attributes, or a list
347 of these.  For convenience when applied to strings, this returns
348 OBJECT."
349
350   ;; A face property can have three forms: a face name (a string or
351   ;; symbol), a property list, or a list of these two forms.  In the
352   ;; list case, the faces will be combined, with the earlier faces
353   ;; taking precedent.  Here we canonicalize everything to list form
354   ;; to make it easy to combine.
355   (let ((pos start)
356         (face-list (notmuch-face-ensure-list-form face)))
357     (while (< pos end)
358       (let* ((cur (get-text-property pos 'face object))
359              (cur-list (notmuch-face-ensure-list-form cur))
360              (new (cond ((null cur-list) face)
361                         (below (append cur-list face-list))
362                         (t (append face-list cur-list))))
363              (next (next-single-property-change pos 'face object end)))
364         (put-text-property pos next 'face new object)
365         (setq pos next))))
366   object)
367
368 (defun notmuch-combine-face-text-property-string (string face &optional below)
369   (notmuch-combine-face-text-property
370    0
371    (length string)
372    face
373    below
374    string))
375
376 (defun notmuch-logged-error (msg &optional extra)
377   "Log MSG and EXTRA to *Notmuch errors* and signal MSG.
378
379 This logs MSG and EXTRA to the *Notmuch errors* buffer and
380 signals MSG as an error.  If EXTRA is non-nil, text referring the
381 user to the *Notmuch errors* buffer will be appended to the
382 signaled error.  This function does not return."
383
384   (with-current-buffer (get-buffer-create "*Notmuch errors*")
385     (goto-char (point-max))
386     (unless (bobp)
387       (newline))
388     (save-excursion
389       (insert "[" (current-time-string) "]\n" msg)
390       (unless (bolp)
391         (newline))
392       (when extra
393         (insert extra)
394         (unless (bolp)
395           (newline)))))
396   (error "%s" (concat msg (when extra
397                             " (see *Notmuch errors* for more details)"))))
398
399 (defun notmuch-check-async-exit-status (proc msg)
400   "If PROC exited abnormally, pop up an error buffer and signal an error.
401
402 This is a wrapper around `notmuch-check-exit-status' for
403 asynchronous process sentinels.  PROC and MSG must be the
404 arguments passed to the sentinel."
405   (let ((exit-status
406          (case (process-status proc)
407            ((exit) (process-exit-status proc))
408            ((signal) msg))))
409     (when exit-status
410       (notmuch-check-exit-status exit-status (process-command proc)))))
411
412 (defun notmuch-check-exit-status (exit-status command &optional output err-file)
413   "If EXIT-STATUS is non-zero, pop up an error buffer and signal an error.
414
415 If EXIT-STATUS is non-zero, pop up a notmuch error buffer
416 describing the error and signal an Elisp error.  EXIT-STATUS must
417 be a number indicating the exit status code of a process or a
418 string describing the signal that terminated the process (such as
419 returned by `call-process').  COMMAND must be a list giving the
420 command and its arguments.  OUTPUT, if provided, is a string
421 giving the output of command.  ERR-FILE, if provided, is the name
422 of a file containing the error output of command.  OUTPUT and the
423 contents of ERR-FILE will be included in the error message."
424
425   (cond
426    ((eq exit-status 0) t)
427    ((eq exit-status 20)
428     (notmuch-logged-error "notmuch CLI version mismatch
429 Emacs requested an older output format than supported by the notmuch CLI.
430 You may need to restart Emacs or upgrade your notmuch Emacs package."))
431    ((eq exit-status 21)
432     (notmuch-logged-error "notmuch CLI version mismatch
433 Emacs requested a newer output format than supported by the notmuch CLI.
434 You may need to restart Emacs or upgrade your notmuch package."))
435    (t
436     (let* ((err (when err-file
437                   (with-temp-buffer
438                     (insert-file-contents err-file)
439                     (unless (eobp)
440                       (buffer-string)))))
441            (extra
442             (concat
443              "command: " (mapconcat #'shell-quote-argument command " ") "\n"
444              (if (integerp exit-status)
445                  (format "exit status: %s\n" exit-status)
446                (format "exit signal: %s\n" exit-status))
447              (when err
448                (concat "stderr:\n" err))
449              (when output
450                (concat "stdout:\n" output)))))
451         (if err
452             ;; We have an error message straight from the CLI.
453             (notmuch-logged-error
454              (replace-regexp-in-string "\\s $" "" err) extra)
455           ;; We only have combined output from the CLI; don't inundate
456           ;; the user with it.  Mimic `process-lines'.
457           (notmuch-logged-error (format "%s exited with status %s"
458                                         (car command) exit-status)
459                                 extra))
460         ;; `notmuch-logged-error' does not return.
461         ))))
462
463 (defun notmuch-call-notmuch-json (&rest args)
464   "Invoke `notmuch-command' with `args' and return the parsed JSON output.
465
466 The returned output will represent objects using property lists
467 and arrays as lists.  If notmuch exits with a non-zero status,
468 this will pop up a buffer containing notmuch's output and signal
469 an error."
470
471   (with-temp-buffer
472     (let ((err-file (make-temp-file "nmerr")))
473       (unwind-protect
474           (let ((status (apply #'call-process
475                                notmuch-command nil (list t err-file) nil args)))
476             (notmuch-check-exit-status status (cons notmuch-command args)
477                                        (buffer-string) err-file)
478             (goto-char (point-min))
479             (let ((json-object-type 'plist)
480                   (json-array-type 'list)
481                   (json-false 'nil))
482               (json-read)))
483         (delete-file err-file)))))
484
485 ;; Compatibility functions for versions of emacs before emacs 23.
486 ;;
487 ;; Both functions here were copied from emacs 23 with the following copyright:
488 ;;
489 ;; Copyright (C) 1985, 1986, 1992, 1994, 1995, 1999, 2000, 2001, 2002, 2003,
490 ;;   2004, 2005, 2006, 2007, 2008, 2009, 2010 Free Software Foundation, Inc.
491 ;;
492 ;; and under the GPL version 3 (or later) exactly as notmuch itself.
493 (compile-on-emacs-prior-to-23
494  (defun apply-partially (fun &rest args)
495    "Return a function that is a partial application of FUN to ARGS.
496 ARGS is a list of the first N arguments to pass to FUN.
497 The result is a new function which does the same as FUN, except that
498 the first N arguments are fixed at the values with which this function
499 was called."
500    (lexical-let ((fun fun) (args1 args))
501      (lambda (&rest args2) (apply fun (append args1 args2))))))
502
503 (compile-on-emacs-prior-to-23
504  (defun mouse-event-p (object)
505    "Return non-nil if OBJECT is a mouse click event."
506    (memq (event-basic-type object) '(mouse-1 mouse-2 mouse-3 mouse-movement))))
507
508 ;; This variable is used only buffer local, but it needs to be
509 ;; declared globally first to avoid compiler warnings.
510 (defvar notmuch-show-process-crypto nil)
511 (make-variable-buffer-local 'notmuch-show-process-crypto)
512
513 ;; Incremental JSON parsing
514
515 ;; These two variables are internal variables to the parsing
516 ;; routines. They are always used buffer local but need to be declared
517 ;; globally to avoid compiler warnings.
518
519 (defvar notmuch-json-parser nil
520   "Internal incremental JSON parser object: local to the buffer being parsed.")
521
522 (defvar notmuch-json-state nil
523   "State of the internal JSON parser: local to the buffer being parsed.")
524
525 (defun notmuch-json-create-parser (buffer)
526   "Return a streaming JSON parser that consumes input from BUFFER.
527
528 This parser is designed to read streaming JSON whose structure is
529 known to the caller.  Like a typical JSON parsing interface, it
530 provides a function to read a complete JSON value from the input.
531 However, it extends this with an additional function that
532 requires the next value in the input to be a compound value and
533 descends into it, allowing its elements to be read one at a time
534 or further descended into.  Both functions can return 'retry to
535 indicate that not enough input is available.
536
537 The parser always consumes input from BUFFER's point.  Hence, the
538 caller is allowed to delete and data before point and may
539 resynchronize after an error by moving point."
540
541   (list buffer
542         ;; Terminator stack: a stack of characters that indicate the
543         ;; end of the compound values enclosing point
544         '()
545         ;; Next: One of
546         ;; * 'expect-value if the next token must be a value, but a
547         ;;   value has not yet been reached
548         ;; * 'value if point is at the beginning of a value
549         ;; * 'expect-comma if the next token must be a comma
550         'expect-value
551         ;; Allow terminator: non-nil if the next token may be a
552         ;; terminator
553         nil
554         ;; Partial parse position: If state is 'value, a marker for
555         ;; the position of the partial parser or nil if no partial
556         ;; parsing has happened yet
557         nil
558         ;; Partial parse state: If state is 'value, the current
559         ;; `parse-partial-sexp' state
560         nil))
561
562 (defmacro notmuch-json-buffer (jp) `(first ,jp))
563 (defmacro notmuch-json-term-stack (jp) `(second ,jp))
564 (defmacro notmuch-json-next (jp) `(third ,jp))
565 (defmacro notmuch-json-allow-term (jp) `(fourth ,jp))
566 (defmacro notmuch-json-partial-pos (jp) `(fifth ,jp))
567 (defmacro notmuch-json-partial-state (jp) `(sixth ,jp))
568
569 (defvar notmuch-json-syntax-table
570   (let ((table (make-syntax-table)))
571     ;; The standard syntax table is what we need except that "." needs
572     ;; to have word syntax instead of punctuation syntax.
573     (modify-syntax-entry ?. "w" table)
574     table)
575   "Syntax table used for incremental JSON parsing.")
576
577 (defun notmuch-json-scan-to-value (jp)
578   ;; Helper function that consumes separators, terminators, and
579   ;; whitespace from point.  Returns nil if it successfully reached
580   ;; the beginning of a value, 'end if it consumed a terminator, or
581   ;; 'retry if not enough input was available to reach a value.  Upon
582   ;; nil return, (notmuch-json-next jp) is always 'value.
583
584   (if (eq (notmuch-json-next jp) 'value)
585       ;; We're already at a value
586       nil
587     ;; Drive the state toward 'expect-value
588     (skip-chars-forward " \t\r\n")
589     (or (when (eobp) 'retry)
590         ;; Test for the terminator for the current compound
591         (when (and (notmuch-json-allow-term jp)
592                    (eq (char-after) (car (notmuch-json-term-stack jp))))
593           ;; Consume it and expect a comma or terminator next
594           (forward-char)
595           (setf (notmuch-json-term-stack jp) (cdr (notmuch-json-term-stack jp))
596                 (notmuch-json-next jp) 'expect-comma
597                 (notmuch-json-allow-term jp) t)
598           'end)
599         ;; Test for a separator
600         (when (eq (notmuch-json-next jp) 'expect-comma)
601           (when (/= (char-after) ?,)
602             (signal 'json-readtable-error (list "expected ','")))
603           ;; Consume it, switch to 'expect-value, and disallow a
604           ;; terminator
605           (forward-char)
606           (skip-chars-forward " \t\r\n")
607           (setf (notmuch-json-next jp) 'expect-value
608                 (notmuch-json-allow-term jp) nil)
609           ;; We moved point, so test for eobp again and fall through
610           ;; to the next test if there's more input
611           (when (eobp) 'retry))
612         ;; Next must be 'expect-value and we know this isn't
613         ;; whitespace, EOB, or a terminator, so point must be on a
614         ;; value
615         (progn
616           (assert (eq (notmuch-json-next jp) 'expect-value))
617           (setf (notmuch-json-next jp) 'value)
618           nil))))
619
620 (defun notmuch-json-begin-compound (jp)
621   "Parse the beginning of a compound value and traverse inside it.
622
623 Returns 'retry if there is insufficient input to parse the
624 beginning of the compound.  If this is able to parse the
625 beginning of a compound, it moves point past the token that opens
626 the compound and returns t.  Later calls to `notmuch-json-read'
627 will return the compound's elements.
628
629 Entering JSON objects is currently unimplemented."
630
631   (with-current-buffer (notmuch-json-buffer jp)
632     ;; Disallow terminators
633     (setf (notmuch-json-allow-term jp) nil)
634     ;; Save "next" so we can restore it if there's a syntax error
635     (let ((saved-next (notmuch-json-next jp)))
636       (or (notmuch-json-scan-to-value jp)
637           (if (/= (char-after) ?\[)
638               (progn
639                 (setf (notmuch-json-next jp) saved-next)
640                 (signal 'json-readtable-error (list "expected '['")))
641             (forward-char)
642             (push ?\] (notmuch-json-term-stack jp))
643             ;; Expect a value or terminator next
644             (setf (notmuch-json-next jp) 'expect-value
645                   (notmuch-json-allow-term jp) t)
646             t)))))
647
648 (defun notmuch-json-read (jp)
649   "Parse the value at point in JP's buffer.
650
651 Returns 'retry if there is insufficient input to parse a complete
652 JSON value (though it may still move point over separators or
653 whitespace).  If the parser is currently inside a compound value
654 and the next token ends the list or object, this moves point just
655 past the terminator and returns 'end.  Otherwise, this moves
656 point to just past the end of the value and returns the value."
657
658   (with-current-buffer (notmuch-json-buffer jp)
659     (or
660      ;; Get to a value state
661      (notmuch-json-scan-to-value jp)
662
663      ;; Can we parse a complete value?
664      (let ((complete
665             (if (looking-at "[-+0-9tfn]")
666                 ;; This is a number or a keyword, so the partial
667                 ;; parser isn't going to help us because a truncated
668                 ;; number or keyword looks like a complete symbol to
669                 ;; it.  Look for something that clearly ends it.
670                 (save-excursion
671                   (skip-chars-forward "^]},: \t\r\n")
672                   (not (eobp)))
673
674               ;; We're looking at a string, object, or array, which we
675               ;; can partial parse.  If we just reached the value, set
676               ;; up the partial parser.
677               (when (null (notmuch-json-partial-state jp))
678                 (setf (notmuch-json-partial-pos jp) (point-marker)))
679
680               ;; Extend the partial parse until we either reach EOB or
681               ;; get the whole value
682               (save-excursion
683                 (let ((pstate
684                        (with-syntax-table notmuch-json-syntax-table
685                          (parse-partial-sexp
686                           (notmuch-json-partial-pos jp) (point-max) 0 nil
687                           (notmuch-json-partial-state jp)))))
688                   ;; A complete value is available if we've reached
689                   ;; depth 0 or less and encountered a complete
690                   ;; subexpression.
691                   (if (and (<= (first pstate) 0) (third pstate))
692                       t
693                     ;; Not complete.  Update the partial parser state
694                     (setf (notmuch-json-partial-pos jp) (point-marker)
695                           (notmuch-json-partial-state jp) pstate)
696                     nil))))))
697
698        (if (not complete)
699            'retry
700          ;; We have a value.  Reset the partial parse state and expect
701          ;; a comma or terminator after the value.
702          (setf (notmuch-json-next jp) 'expect-comma
703                (notmuch-json-allow-term jp) t
704                (notmuch-json-partial-pos jp) nil
705                (notmuch-json-partial-state jp) nil)
706          ;; Parse the value
707          (let ((json-object-type 'plist)
708                (json-array-type 'list)
709                (json-false nil))
710            (json-read)))))))
711
712 (defun notmuch-json-eof (jp)
713   "Signal a json-error if there is more data in JP's buffer.
714
715 Moves point to the beginning of any trailing data or to the end
716 of the buffer if there is only trailing whitespace."
717
718   (with-current-buffer (notmuch-json-buffer jp)
719     (skip-chars-forward " \t\r\n")
720     (unless (eobp)
721       (signal 'json-error (list "Trailing garbage following JSON data")))))
722
723 (defun notmuch-json-parse-partial-list (result-function error-function results-buf)
724   "Parse a partial JSON list from current buffer.
725
726 This function consumes a JSON list from the current buffer,
727 applying RESULT-FUNCTION in buffer RESULT-BUFFER to each complete
728 value in the list.  It operates incrementally and should be
729 called whenever the buffer has been extended with additional
730 data.
731
732 If there is a syntax error, this will attempt to resynchronize
733 with the input and will apply ERROR-FUNCTION in buffer
734 RESULT-BUFFER to any input that was skipped.
735
736 It sets up all the needed internal variables: the caller just
737 needs to call it with point in the same place that the parser
738 left it."
739   (let (done)
740     (unless (local-variable-p 'notmuch-json-parser)
741       (set (make-local-variable 'notmuch-json-parser)
742            (notmuch-json-create-parser (current-buffer)))
743       (set (make-local-variable 'notmuch-json-state) 'begin))
744     (while (not done)
745       (condition-case nil
746           (case notmuch-json-state
747                 ((begin)
748                  ;; Enter the results list
749                  (if (eq (notmuch-json-begin-compound
750                           notmuch-json-parser) 'retry)
751                      (setq done t)
752                    (setq notmuch-json-state 'result)))
753                 ((result)
754                  ;; Parse a result
755                  (let ((result (notmuch-json-read notmuch-json-parser)))
756                    (case result
757                          ((retry) (setq done t))
758                          ((end) (setq notmuch-json-state 'end))
759                          (otherwise (with-current-buffer results-buf
760                                       (funcall result-function result))))))
761                 ((end)
762                  ;; Any trailing data is unexpected
763                  (notmuch-json-eof notmuch-json-parser)
764                  (setq done t)))
765         (json-error
766          ;; Do our best to resynchronize and ensure forward
767          ;; progress
768          (let ((bad (buffer-substring (line-beginning-position)
769                                       (line-end-position))))
770            (forward-line)
771            (with-current-buffer results-buf
772              (funcall error-function "%s" bad))))))
773     ;; Clear out what we've parsed
774     (delete-region (point-min) (point))))
775
776
777
778
779 (provide 'notmuch-lib)
780
781 ;; Local Variables:
782 ;; byte-compile-warnings: (not cl-functions)
783 ;; End: