From 92fa2f52d8aaf805af8b613f73cc9ede16704e70 Mon Sep 17 00:00:00 2001 From: Riyyi Date: Fri, 5 Aug 2022 16:22:13 +0200 Subject: [PATCH] Emacs: Format C++ project buffers before saving --- .config/emacs/config.org | 2 +- .config/emacs/config/development.org | 20 ++++++++++++++++++-- 2 files changed, 19 insertions(+), 3 deletions(-) diff --git a/.config/emacs/config.org b/.config/emacs/config.org index 6deeeec..aa04b0f 100644 --- a/.config/emacs/config.org +++ b/.config/emacs/config.org @@ -1127,7 +1127,7 @@ Evaluated keybinds. (with-eval-after-load 'lsp-mode (space-leader lsp-mode-map "l" lsp-command-map - "l = f" '(lsp-format-buffer-or-region :which-key "format buffer or region") + "l = f" '(dot/lsp-format-buffer-or-region :which-key "format buffer or region") )) (with-eval-after-load 'dap-mode diff --git a/.config/emacs/config/development.org b/.config/emacs/config/development.org index c04769d..74fed82 100644 --- a/.config/emacs/config/development.org +++ b/.config/emacs/config/development.org @@ -210,7 +210,7 @@ Language Server Protocol. (let ((lsp-keymap-prefix (concat leader-key " l"))) (lsp-enable-which-key-integration))) - (defun lsp-format-buffer-or-region () + (defun dot/lsp-format-buffer-or-region () "Format the selection (or buffer) with LSP." (interactive) (unless (bound-and-true-p lsp-mode) @@ -218,7 +218,23 @@ Language Server Protocol. (call-interactively (if (use-region-p) #'lsp-format-region - #'lsp-format-buffer)))) + #'lsp-format-buffer))) + + ;; This is cached to prevent unneeded I/O + (setq lsp-in-cpp-project-cache nil) + (defun dot/lsp-format-cpp-buffer () + "Format buffer in C++ projects." + (unless lsp-in-cpp-project-cache + (set (make-local-variable 'lsp-in-cpp-project-cache) + (list + (if (and (eq major-mode 'c++-mode) + (bound-and-true-p lsp-mode) + (project-current)) + t + nil)))) + (when (car lsp-in-cpp-project-cache) + (lsp-format-buffer))) + (add-hook 'before-save-hook #'dot/lsp-format-cpp-buffer)) ;; TODO: add lsp-signature keybinds