From 91a2ca456fabc7e9083ef33151884fb6f680fbd6 Mon Sep 17 00:00:00 2001 From: Robbert van der Helm Date: Fri, 7 Apr 2017 11:21:05 +0200 Subject: [PATCH] Add automatic formatting on save for C++ using ClangFormat This can be enabled by setting both `c-c++-enable-clang-format-on-save` and `c-c++-enable-clang-support` to `t`. --- layers/+lang/c-c++/README.org | 8 ++++++++ layers/+lang/c-c++/config.el | 4 ++++ layers/+lang/c-c++/funcs.el | 4 ++++ layers/+lang/c-c++/packages.el | 6 +++++- 4 files changed, 21 insertions(+), 1 deletion(-) diff --git a/layers/+lang/c-c++/README.org b/layers/+lang/c-c++/README.org index 15106791a..020e10944 100644 --- a/layers/+lang/c-c++/README.org +++ b/layers/+lang/c-c++/README.org @@ -84,6 +84,14 @@ particular mode or all modes in your =dotspacemacs/user-config= (within your (define-key c++-mode-map [tab] 'clang-format-buffer)) #+END_SRC +To enable automatic buffer formatting on save, set the variable +=c-c++-enable-clang-format-on-save= to =t=: + +#+BEGIN_SRC emacs-lisp + (setq-default dotspacemacs-configuration-layers '( + (c-c++ :variables c-c++-enable-clang-format-on-save t))) +#+END_SRC + *** Company-clang and flycheck This layer adds some fancy improvements to =company-clang=. It includes a hook to load a projects =.clang_complete= file, which is diff --git a/layers/+lang/c-c++/config.el b/layers/+lang/c-c++/config.el index 357e87541..f14e7ac99 100644 --- a/layers/+lang/c-c++/config.el +++ b/layers/+lang/c-c++/config.el @@ -14,6 +14,10 @@ (defvar c-c++-enable-clang-support nil "If non nil Clang related packages and configuration are enabled.") +(defvar c-c++-enable-clang-format-on-save nil + "If non-nil, automatically format code with ClangFormat on + save. Clang support has to be enabled for this to work.") + (spacemacs|define-jump-handlers c++-mode) (spacemacs|define-jump-handlers c-mode) diff --git a/layers/+lang/c-c++/funcs.el b/layers/+lang/c-c++/funcs.el index fb7056d85..b9603d5c3 100644 --- a/layers/+lang/c-c++/funcs.el +++ b/layers/+lang/c-c++/funcs.el @@ -9,6 +9,10 @@ ;; ;;; License: GPLv3 +(defun clang-format/format-on-save () + "Format buffers with ClangFormat when they get saved." + (add-hook 'before-save-hook 'clang-format-buffer nil t)) + (defun company-mode/more-than-prefix-guesser () (c-c++/load-clang-args) (company-clang-guess-prefix)) diff --git a/layers/+lang/c-c++/packages.el b/layers/+lang/c-c++/packages.el index d959ea357..54706ae7e 100644 --- a/layers/+lang/c-c++/packages.el +++ b/layers/+lang/c-c++/packages.el @@ -61,7 +61,11 @@ (defun c-c++/init-clang-format () (use-package clang-format - :if c-c++-enable-clang-support)) + :if c-c++-enable-clang-support + :init + (when c-c++-enable-clang-format-on-save + (spacemacs/add-to-hooks 'clang-format/format-on-save + '(c-mode-hook c++-mode-hook))))) (defun c-c++/init-cmake-mode () (use-package cmake-mode