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 "file"))
40    (unwind-protect
41        (call-process-region (point-min) (point-max) clang-format-binary
42                             t (list t nil) nil
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)
47                             "-style" style)
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)))))))
57