1;;; Clang-format emacs integration for use with C/Objective-C/C++. 2 3;; This defines a function clang-format-region that you can bind to a key. 4;; A minimal .emacs would contain: 5;; 6;; (load "<path-to-clang>/tools/clang-format/clang-format.el") 7;; (global-set-key [C-M-tab] 'clang-format-region) 8;; 9;; Depending on your configuration and coding style, you might need to modify 10;; 'style' in clang-format, below. 11 12(require 'json) 13 14;; *Location of the clang-format binary. If it is on your PATH, a full path name 15;; need not be specified. 16(defvar clang-format-binary "clang-format") 17 18(defun clang-format-region () 19 "Use clang-format to format the currently active region." 20 (interactive) 21 (let ((beg (if mark-active 22 (region-beginning) 23 (min (line-beginning-position) (1- (point-max))))) 24 (end (if mark-active 25 (region-end) 26 (line-end-position)))) 27 (clang-format beg end))) 28 29(defun clang-format-buffer () 30 "Use clang-format to format the current buffer." 31 (interactive) 32 (clang-format (point-min) (point-max))) 33 34(defun clang-format (begin end) 35 "Use clang-format to format the code between BEGIN and END." 36 (let* ((orig-windows (get-buffer-window-list (current-buffer))) 37 (orig-window-starts (mapcar #'window-start orig-windows)) 38 (orig-point (point)) 39 (style "LLVM")) 40 (unwind-protect 41 (call-process-region (point-min) (point-max) clang-format-binary t t nil 42 "-offset" (number-to-string (1- begin)) 43 "-length" (number-to-string (- end begin)) 44 "-cursor" (number-to-string (1- (point))) 45 "-style" style) 46 (goto-char (point-min)) 47 (let ((json-output (json-read-from-string 48 (buffer-substring-no-properties 49 (point-min) (line-beginning-position 2))))) 50 (delete-region (point-min) (line-beginning-position 2)) 51 (goto-char (1+ (cdr (assoc 'Cursor json-output)))) 52 (dotimes (index (length orig-windows)) 53 (set-window-start (nth index orig-windows) 54 (nth index orig-window-starts))))))) 55