From 287595960984882e03e0b31aa882eb14cf76e034 Mon Sep 17 00:00:00 2001 From: David Robillard Date: Fri, 25 Dec 2020 15:28:53 +0100 Subject: Add automatic indentation based on clang-format configuration --- emacs/.emacs.d/init.el | 53 +++++++++++++++++++++++++++++++++++++++++++++++++- 1 file changed, 52 insertions(+), 1 deletion(-) (limited to 'emacs/.emacs.d') diff --git a/emacs/.emacs.d/init.el b/emacs/.emacs.d/init.el index c4da671..be3946b 100644 --- a/emacs/.emacs.d/init.el +++ b/emacs/.emacs.d/init.el @@ -25,6 +25,51 @@ (add-hook 'dired-mode-hook (lambda () (dired-hide-details-mode))) +;;; Code formatting + +(defun get-clang-format-option (config-str field is-num) + "Retrieve a config option from a clang-format config." + (cond (is-num + (let ((primary-match (s-match (concat "^" field ":[ \t]*[0-9]+") config-str))) + (if primary-match + (string-to-number (car (s-match "[0-9]+" (car primary-match)))) + 0))) + (t + (let ((primary-match (s-match (concat "^" field ":[ \t]*[A-Za-z]+") config-str))) + (if primary-match + (car (s-match "[A-Za-z]+$" (car primary-match))) + ""))))) + +(defun clang-format-c-mode-hook () + (let* ((clang-format-config + (shell-command-to-string "clang-format -dump-config")) + (c-offset (get-clang-format-option clang-format-config "IndentWidth" t)) + (tabs-str (get-clang-format-option clang-format-config "UseTab" nil)) + (base-style + (get-clang-format-option clang-format-config "BasedOnStyle" nil))) + (progn + (if (> c-offset 0) + (setq-local c-basic-offset c-offset) + (if (not (equal "" base-style)) + (cond ((or (equal "LLVM" base-style) + (equal "Google" base-style) + (equal "Chromium" base-style) + (equal "Mozilla" base-style)) + (setq-local c-basic-offset 2)) + ((equal "WebKit" base-style) + (setq-local c-basic-offset 4))))) + (if (not (equal "" tabs-str)) + (if (not (string-equal "Never" tabs-str)) + (setq-local indent-tabs-mode t) + (setq-local indent-tabs-mode nil)) + (if (not (equal "" base-style)) + (cond ((or (equal "LLVM" base-style) + (equal "Google" base-style) + (equal "Chromium" base-style) + (equal "Mozilla" base-style) + (equal "WebKit" base-style)) + (setq-local indent-tabs-mode nil)))))))) + ;;; Packages (require 'package) @@ -36,7 +81,12 @@ (package-install 'use-package))) (setq use-package-always-ensure t) -(use-package clang-format :commands (c-mode c++-mode)) + +(use-package clang-format + :commands (c-mode c++-mode objc-mode) + :after (s) + :hook (c-mode-common . clang-format-c-mode-hook)) + (use-package counsel :after (ivy) :config (counsel-mode)) (use-package counsel-gtags :commands ggtags-mode) (use-package counsel-projectile :after (counsel projectile)) @@ -494,6 +544,7 @@ (add-to-list 'auto-mode-alist '("\\.jsonld" . json-mode)) (add-to-list 'auto-mode-alist '("\\.tesc" . glsl-mode)) (add-to-list 'auto-mode-alist '("\\.tese" . glsl-mode)) +(add-to-list 'auto-mode-alist '("\\.clang-format" . yaml-mode)) ;;; Projectile -- cgit v1.2.1