From 6e7a19a2f42baba16870a06f6187da9ee290fa29 Mon Sep 17 00:00:00 2001 From: Henrik Lissner Date: Wed, 26 May 2021 21:45:00 -0400 Subject: [PATCH] Enable formatter if LSP formatter is available 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. --- modules/editor/format/config.el | 39 ++++++++++++++++++++++++--------- 1 file changed, 29 insertions(+), 10 deletions(-) diff --git a/modules/editor/format/config.el b/modules/editor/format/config.el index 870a431929b..15ee5430716 100644 --- a/modules/editor/format/config.el +++ b/modules/editor/format/config.el @@ -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))