Last active
January 3, 2023 01:40
-
-
Save ul/11373d7314f580d59e73f2e73a4e8a4e to your computer and use it in GitHub Desktop.
Emacs: consult.el + jq
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
(defvar consult--jq-history nil) | |
(defun consult--jq-query (buffer query) | |
"Return jq candidates for the BUFFER. | |
QUERY is the jq query." | |
(with-temp-buffer | |
(insert-buffer buffer) | |
(call-process-region nil nil "jq" t t nil "-rM" query) | |
(mapcar | |
(lambda (s) | |
(concat s (propertize query 'invisible t 'read-only t 'cursor-intangible t 'rear-nonsticky t))) | |
(split-string | |
(replace-regexp-in-string | |
"\n$" "" | |
(buffer-string)) "\n")))) | |
(defun consult-jq () | |
"Dynamically query JSON buffer with jq. | |
When you are happy with the query, press RET to open the result | |
in *consult-jq-buffer*." | |
(interactive) | |
(setq consult--jq-input ".") | |
(setq consult--jq-current-buffer (current-buffer)) | |
(setq consult--jq-candidates (consult--jq-query consult--jq-current-buffer ".")) | |
(if-let ((result (consult--read | |
(lambda (input) | |
(cond | |
((not input) | |
consult--jq-candidates) | |
((listp input) | |
(appendq! consult--jq-candidates input) | |
consult--jq-candidates) | |
((stringp input) | |
(setq consult--jq-input input) | |
(setq consult--jq-candidates (consult--jq-query consult--jq-current-buffer input))))) | |
:prompt "jq: " | |
:require-match t | |
:history '(:input consult--jq-history) | |
:category 'consult-jq | |
:initial "." | |
:sort nil))) | |
(with-current-buffer (get-buffer-create "*consult-jq-buffer*") | |
(erase-buffer) | |
(insert-buffer consult--jq-current-buffer) | |
(call-process-region nil nil "jq" t t nil "-rM" consult--jq-input) | |
(json-mode) | |
(goto-char (point-min)) | |
(display-buffer (current-buffer))))) |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment