Skip to content

Instantly share code, notes, and snippets.

@garlic0x1
Last active December 7, 2023 07:57
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save garlic0x1/15e4bba1e398d53fb8ca98a645877a94 to your computer and use it in GitHub Desktop.
Save garlic0x1/15e4bba1e398d53fb8ca98a645877a94 to your computer and use it in GitHub Desktop.
Auto format C in Emacs
;; help load config files (convenience function for my Doom setup, change for other distros)
(defun config-path (path)
(concat doom-user-dir path))
;; runs clang-format with a specified config file
(defun clang-format-with-spec (spec)
(shell-command
(concat "clang-format"
" --style=file:" spec
" -i " buffer-file-name)))
;; runs clang-format with .clang-format either
;; in projectile root dir, or in doom config dir
(defun clang-format ()
(interactive)
(let ((project-spec (concat (projectile-project-root) ".clang-format"))
(global-spec (config-path ".clang-format")))
(clang-format-with-spec
(if (file-exists-p project-spec)
project-spec global-spec))))
;; create hook to format after save
(add-hook 'after-save-hook
#'(lambda () (when c-buffer-is-cc-mode (clang-format))))
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment