Skip to content

Commit

Permalink
Enable formatter if LSP formatter is available
Browse files Browse the repository at this point in the history
The :editor format module uses either the formatter available through an
LSP server or a formatter that the format-all package supports.  With
:editor (format +onsave), this formatter is triggered when a file is
saved. However, if no format-all formatter is available, this on-save
behavior is disabled, even if an LSP formatter is available. This fixes
that.
  • Loading branch information
hlissner committed May 27, 2021
1 parent 68bee50 commit 6e7a19a
Showing 1 changed file with 29 additions and 10 deletions.
39 changes: 29 additions & 10 deletions modules/editor/format/config.el
Original file line number Diff line number Diff line change
Expand Up @@ -34,20 +34,39 @@ select buffers.")
;;
;;; Bootstrap

(defun +format-enable-for-lsp-on-save-maybe-h ()
"Enable LSP formatter when LSP client is available."
(cond ((not +format-with-lsp) nil)
((bound-and-true-p lsp-mode)
(remove-hook 'lsp-mode-hook #'+format-lsp-enable-on-save-maybe-h 'local)
(when (lsp-feature? "textDocument/formatting")
(+format-enable-on-save-h))
t)
((bound-and-true-p eglot--managed-mode)
(remove-hook 'eglot-managed-mode-hook #'+format-lsp-enable-on-save-maybe-h 'local)
(when (eglot--server-capable :documentRangeFormattingProvider)
(+format-enable-on-save-h))
t)
((bound-and-true-p lsp--buffer-deferred)
(add-hook 'lsp-mode-hook #'+format-lsp-enable-on-save-maybe-h
nil 'local)
t)))

(defun +format-enable-on-save-maybe-h ()
"Enable formatting on save in certain major modes.
This is controlled by `+format-on-save-enabled-modes'."
(or (eq major-mode 'fundamental-mode)
(cond ((booleanp +format-on-save-enabled-modes)
(null +format-on-save-enabled-modes))
((eq (car +format-on-save-enabled-modes) 'not)
(memq major-mode (cdr +format-on-save-enabled-modes)))
((not (memq major-mode +format-on-save-enabled-modes))))
(not (require 'format-all nil t))
(let (current-prefix-arg) ; never prompt
(null (car (format-all--probe))))
(+format-enable-on-save-h)))
(and (not (eq major-mode 'fundamental-mode))
(cond ((booleanp +format-on-save-enabled-modes)
+format-on-save-enabled-modes)
((eq (car-safe +format-on-save-enabled-modes) 'not)
(not (memq major-mode (cdr +format-on-save-enabled-modes))))
((memq major-mode +format-on-save-enabled-modes))
((not (require 'format-all nil t))))
(not (+format-lsp-enable-on-save-maybe-h))
(let (current-prefix-arg) ; never prompt
(not (car (format-all--probe))))
(+format-enable-on-save-h)))

(when (featurep! +onsave)
(add-hook 'after-change-major-mode-hook #'+format-enable-on-save-maybe-h))
Expand Down

0 comments on commit 6e7a19a

Please sign in to comment.