2020-02-18 20:55:35 +00:00
|
|
|
(defgroup sqlfmt nil
|
|
|
|
"Easy sqlfmt invocation in Emacs"
|
|
|
|
:group 'sql)
|
|
|
|
|
2018-09-17 14:24:16 +00:00
|
|
|
(defcustom sqlfmt-executable
|
|
|
|
"sqlfmt"
|
|
|
|
"Location of sqlfmt executable."
|
|
|
|
:type 'string)
|
|
|
|
|
|
|
|
(defcustom sqlfmt-options
|
2020-02-20 20:32:23 +00:00
|
|
|
'("--use-spaces")
|
2018-09-17 14:24:16 +00:00
|
|
|
"Command line options to pass to sqlfmt."
|
|
|
|
:type '(repeat string))
|
|
|
|
|
2020-02-18 20:55:35 +00:00
|
|
|
(defcustom sqlfmt-reuse-error-buffer
|
2020-02-20 20:32:23 +00:00
|
|
|
t
|
2020-02-18 20:55:35 +00:00
|
|
|
"Reuse the same buffer for sqlfmt errors, replacing content on new invocations, or generate new buffers on each invocation"
|
|
|
|
:type 'boolean)
|
|
|
|
|
2018-09-17 14:24:16 +00:00
|
|
|
(defun sqlfmt-buffer ()
|
|
|
|
(interactive)
|
2020-02-18 20:55:35 +00:00
|
|
|
(sqlfmt-region (point-min) (point-max)))
|
|
|
|
|
|
|
|
(defun sqlfmt-region (start end)
|
|
|
|
"Calls sqlfmt on region"
|
|
|
|
(interactive (if (use-region-p)
|
|
|
|
(list (region-beginning) (region-end))
|
|
|
|
(list nil nil)))
|
|
|
|
(if (not (and start end))
|
|
|
|
(error "No region active, sqlfmt cancelled"))
|
|
|
|
(let* ((sqlfmt-buffer-base "*sqlfmt*")
|
|
|
|
(inhibit-read-only t)
|
|
|
|
(orig-buffer (current-buffer))
|
2018-09-17 14:24:16 +00:00
|
|
|
(orig-point (point))
|
2020-02-18 20:55:35 +00:00
|
|
|
(tmpbuf (if sqlfmt-reuse-error-buffer
|
|
|
|
(get-buffer-create sqlfmt-buffer-base)
|
|
|
|
(generate-new-buffer sqlfmt-buffer-base)))
|
|
|
|
(status-code (progn
|
|
|
|
(with-current-buffer tmpbuf
|
|
|
|
(erase-buffer)
|
|
|
|
(setq buffer-read-only t))
|
|
|
|
(apply #'call-process-region start end
|
2020-02-20 20:32:23 +00:00
|
|
|
sqlfmt-executable nil tmpbuf nil
|
|
|
|
sqlfmt-options))))
|
2018-09-17 14:24:16 +00:00
|
|
|
(deactivate-mark)
|
|
|
|
(if (eq status-code 0)
|
|
|
|
(progn
|
2020-02-18 20:55:35 +00:00
|
|
|
(with-current-buffer orig-buffer
|
2020-02-20 20:32:23 +00:00
|
|
|
(delete-region start end)
|
|
|
|
(insert-buffer tmpbuf)
|
|
|
|
(kill-buffer tmpbuf)
|
|
|
|
(goto-char orig-point))
|
2020-02-18 20:55:35 +00:00
|
|
|
(message "sqlfmt applied"))
|
2018-09-17 14:24:16 +00:00
|
|
|
(error "sqlfmt failed, see %s buffer for details." (buffer-name tmpbuf)))))
|