File: clang-format.el

package info (click to toggle)
llvm-toolchain-3.5 1%3A3.5-10
  • links: PTS, VCS
  • area: main
  • in suites: jessie, jessie-kfreebsd
  • size: 282,028 kB
  • ctags: 310,872
  • sloc: cpp: 1,883,926; ansic: 310,731; objc: 86,612; python: 79,565; asm: 65,844; sh: 9,829; makefile: 6,057; perl: 5,589; ml: 5,254; pascal: 3,285; lisp: 1,640; xml: 686; cs: 239; csh: 117
file content (56 lines) | stat: -rw-r--r-- 2,339 bytes parent folder | download | duplicates (2)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
;;; Clang-format emacs integration for use with C/Objective-C/C++.

;; This defines a function clang-format-region that you can bind to a key.
;; A minimal .emacs would contain:
;;
;;   (load "<path-to-clang>/tools/clang-format/clang-format.el")
;;   (global-set-key [C-M-tab] 'clang-format-region)
;;
;; Depending on your configuration and coding style, you might need to modify
;; 'style' in clang-format, below.

(require 'json)

;; *Location of the clang-format binary. If it is on your PATH, a full path name
;; need not be specified.
(defvar clang-format-binary "clang-format-3.5")

(defun clang-format-region ()
  "Use clang-format to format the currently active region."
  (interactive)
  (let ((beg (if mark-active
                 (region-beginning)
               (min (line-beginning-position) (1- (point-max)))))
        (end (if mark-active
                 (region-end)
               (line-end-position))))
    (clang-format beg end)))

(defun clang-format-buffer ()
  "Use clang-format to format the current buffer."
  (interactive)
  (clang-format (point-min) (point-max)))

(defun clang-format (begin end)
  "Use clang-format to format the code between BEGIN and END."
  (let* ((orig-windows (get-buffer-window-list (current-buffer)))
         (orig-window-starts (mapcar #'window-start orig-windows))
         (orig-point (point))
         (style "file"))
    (unwind-protect
        (call-process-region (point-min) (point-max) clang-format-binary
                             t (list t nil) nil
                             "-offset" (number-to-string (1- begin))
                             "-length" (number-to-string (- end begin))
                             "-cursor" (number-to-string (1- (point)))
                             "-assume-filename" (buffer-file-name)
                             "-style" style)
      (goto-char (point-min))
      (let ((json-output (json-read-from-string
                           (buffer-substring-no-properties
                             (point-min) (line-beginning-position 2)))))
        (delete-region (point-min) (line-beginning-position 2))
        (goto-char (1+ (cdr (assoc 'Cursor json-output))))
        (dotimes (index (length orig-windows))
          (set-window-start (nth index orig-windows)
                            (nth index orig-window-starts)))))))