1 ;;; Clang-format emacs integration for use with C/Objective-C/C++.
3 ;; This defines a function clang-format-region that you can bind to a key.
4 ;; A minimal .emacs would contain:
6 ;; (load "<path-to-clang>/tools/clang-format/clang-format.el")
7 ;; (global-set-key [C-M-tab] 'clang-format-region)
9 ;; Depending on your configuration and coding style, you might need to modify
10 ;; 'style' in clang-format, below.
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")
18 (defun clang-format-region ()
19 "Use clang-format to format the currently active region."
21 (let ((beg (if mark-active
23 (min (line-beginning-position) (1- (point-max)))))
26 (line-end-position))))
27 (clang-format beg end)))
29 (defun clang-format-buffer ()
30 "Use clang-format to format the current buffer."
32 (clang-format (point-min) (point-max)))
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))
41 (call-process-region (point-min) (point-max) clang-format-binary
43 "-offset" (number-to-string (1- begin))
44 "-length" (number-to-string (- end begin))
45 "-cursor" (number-to-string (1- (point)))
46 "-assume-filename" (buffer-file-name)
48 (goto-char (point-min))
49 (let ((json-output (json-read-from-string
50 (buffer-substring-no-properties
51 (point-min) (line-beginning-position 2)))))
52 (delete-region (point-min) (line-beginning-position 2))
53 (goto-char (1+ (cdr (assoc 'Cursor json-output))))
54 (dotimes (index (length orig-windows))
55 (set-window-start (nth index orig-windows)
56 (nth index orig-window-starts)))))))