xref: /netbsd-src/external/apache2/llvm/dist/clang/tools/clang-format/clang-format.el (revision 181254a7b1bdde6873432bffef2d2decc4b5c22f)
1;;; clang-format.el --- Format code using clang-format  -*- lexical-binding: t; -*-
2
3;; Keywords: tools, c
4;; Package-Requires: ((cl-lib "0.3"))
5;; SPDX-License-Identifier: Apache-2.0 WITH LLVM-exception
6
7;;; Commentary:
8
9;; This package allows to filter code through clang-format to fix its formatting.
10;; clang-format is a tool that formats C/C++/Obj-C code according to a set of
11;; style options, see <http://clang.llvm.org/docs/ClangFormatStyleOptions.html>.
12;; Note that clang-format 3.4 or newer is required.
13
14;; clang-format.el is available via MELPA and can be installed via
15;;
16;;   M-x package-install clang-format
17;;
18;; when ("melpa" . "http://melpa.org/packages/") is included in
19;; `package-archives'.  Alternatively, ensure the directory of this
20;; file is in your `load-path' and add
21;;
22;;   (require 'clang-format)
23;;
24;; to your .emacs configuration.
25
26;; You may also want to bind `clang-format-region' to a key:
27;;
28;;   (global-set-key [C-M-tab] 'clang-format-region)
29
30;;; Code:
31
32(require 'cl-lib)
33(require 'xml)
34
35(defgroup clang-format nil
36  "Format code using clang-format."
37  :group 'tools)
38
39(defcustom clang-format-executable
40  (or (executable-find "clang-format")
41      "clang-format")
42  "Location of the clang-format executable.
43
44A string containing the name or the full path of the executable."
45  :group 'clang-format
46  :type '(file :must-match t)
47  :risky t)
48
49(defcustom clang-format-style nil
50  "Style argument to pass to clang-format.
51
52By default clang-format will load the style configuration from
53a file named .clang-format located in one of the parent directories
54of the buffer."
55  :group 'clang-format
56  :type '(choice (string) (const nil))
57  :safe #'stringp)
58(make-variable-buffer-local 'clang-format-style)
59
60(defun clang-format--extract (xml-node)
61  "Extract replacements and cursor information from XML-NODE."
62  (unless (and (listp xml-node) (eq (xml-node-name xml-node) 'replacements))
63    (error "Expected <replacements> node"))
64  (let ((nodes (xml-node-children xml-node))
65        (incomplete-format (xml-get-attribute xml-node 'incomplete_format))
66        replacements
67        cursor)
68    (dolist (node nodes)
69      (when (listp node)
70        (let* ((children (xml-node-children node))
71               (text (car children)))
72          (cl-case (xml-node-name node)
73            ('replacement
74             (let* ((offset (xml-get-attribute-or-nil node 'offset))
75                    (length (xml-get-attribute-or-nil node 'length)))
76               (when (or (null offset) (null length))
77                 (error "<replacement> node does not have offset and length attributes"))
78               (when (cdr children)
79                 (error "More than one child node in <replacement> node"))
80
81               (setq offset (string-to-number offset))
82               (setq length (string-to-number length))
83               (push (list offset length text) replacements)))
84            ('cursor
85             (setq cursor (string-to-number text)))))))
86
87    ;; Sort by decreasing offset, length.
88    (setq replacements (sort (delq nil replacements)
89                             (lambda (a b)
90                               (or (> (car a) (car b))
91                                   (and (= (car a) (car b))
92                                        (> (cadr a) (cadr b)))))))
93
94    (list replacements cursor (string= incomplete-format "true"))))
95
96(defun clang-format--replace (offset length &optional text)
97  "Replace the region defined by OFFSET and LENGTH with TEXT.
98OFFSET and LENGTH are measured in bytes, not characters.  OFFSET
99is a zero-based file offset, assuming ‘utf-8-unix’ coding."
100  (let ((start (clang-format--filepos-to-bufferpos offset 'exact 'utf-8-unix))
101        (end (clang-format--filepos-to-bufferpos (+ offset length) 'exact
102                                                 'utf-8-unix)))
103    (goto-char start)
104    (delete-region start end)
105    (when text
106      (insert text))))
107
108;; ‘bufferpos-to-filepos’ and ‘filepos-to-bufferpos’ are new in Emacs 25.1.
109;; Provide fallbacks for older versions.
110(defalias 'clang-format--bufferpos-to-filepos
111  (if (fboundp 'bufferpos-to-filepos)
112      'bufferpos-to-filepos
113    (lambda (position &optional _quality _coding-system)
114      (1- (position-bytes position)))))
115
116(defalias 'clang-format--filepos-to-bufferpos
117  (if (fboundp 'filepos-to-bufferpos)
118      'filepos-to-bufferpos
119    (lambda (byte &optional _quality _coding-system)
120      (byte-to-position (1+ byte)))))
121
122;;;###autoload
123(defun clang-format-region (start end &optional style assume-file-name)
124  "Use clang-format to format the code between START and END according to STYLE.
125If called interactively uses the region or the current statement if there is no
126no active region. If no STYLE is given uses `clang-format-style'. Use
127ASSUME-FILE-NAME to locate a style config file, if no ASSUME-FILE-NAME is given
128uses the function `buffer-file-name'."
129  (interactive
130   (if (use-region-p)
131       (list (region-beginning) (region-end))
132     (list (point) (point))))
133
134  (unless style
135    (setq style clang-format-style))
136
137  (unless assume-file-name
138    (setq assume-file-name buffer-file-name))
139
140  (let ((file-start (clang-format--bufferpos-to-filepos start 'approximate
141                                                        'utf-8-unix))
142        (file-end (clang-format--bufferpos-to-filepos end 'approximate
143                                                      'utf-8-unix))
144        (cursor (clang-format--bufferpos-to-filepos (point) 'exact 'utf-8-unix))
145        (temp-buffer (generate-new-buffer " *clang-format-temp*"))
146        (temp-file (make-temp-file "clang-format"))
147        ;; Output is XML, which is always UTF-8.  Input encoding should match
148        ;; the encoding used to convert between buffer and file positions,
149        ;; otherwise the offsets calculated above are off.  For simplicity, we
150        ;; always use ‘utf-8-unix’ and ignore the buffer coding system.
151        (default-process-coding-system '(utf-8-unix . utf-8-unix)))
152    (unwind-protect
153        (let ((status (apply #'call-process-region
154                             nil nil clang-format-executable
155                             nil `(,temp-buffer ,temp-file) nil
156                             `("-output-replacements-xml"
157                               ;; Guard against a nil assume-file-name.
158                               ;; If the clang-format option -assume-filename
159                               ;; is given a blank string it will crash as per
160                               ;; the following bug report
161                               ;; https://bugs.llvm.org/show_bug.cgi?id=34667
162                               ,@(and assume-file-name
163                                      (list "-assume-filename" assume-file-name))
164                               ,@(and style (list "-style" style))
165                               "-offset" ,(number-to-string file-start)
166                               "-length" ,(number-to-string (- file-end file-start))
167                               "-cursor" ,(number-to-string cursor))))
168              (stderr (with-temp-buffer
169                        (unless (zerop (cadr (insert-file-contents temp-file)))
170                          (insert ": "))
171                        (buffer-substring-no-properties
172                         (point-min) (line-end-position)))))
173          (cond
174           ((stringp status)
175            (error "(clang-format killed by signal %s%s)" status stderr))
176           ((not (zerop status))
177            (error "(clang-format failed with code %d%s)" status stderr)))
178
179          (cl-destructuring-bind (replacements cursor incomplete-format)
180              (with-current-buffer temp-buffer
181                (clang-format--extract (car (xml-parse-region))))
182            (save-excursion
183              (dolist (rpl replacements)
184                (apply #'clang-format--replace rpl)))
185            (when cursor
186              (goto-char (clang-format--filepos-to-bufferpos cursor 'exact
187                                                             'utf-8-unix)))
188            (if incomplete-format
189                (message "(clang-format: incomplete (syntax errors)%s)" stderr)
190              (message "(clang-format: success%s)" stderr))))
191      (delete-file temp-file)
192      (when (buffer-name temp-buffer) (kill-buffer temp-buffer)))))
193
194;;;###autoload
195(defun clang-format-buffer (&optional style assume-file-name)
196  "Use clang-format to format the current buffer according to STYLE.
197If no STYLE is given uses `clang-format-style'. Use ASSUME-FILE-NAME
198to locate a style config file. If no ASSUME-FILE-NAME is given uses
199the function `buffer-file-name'."
200  (interactive)
201  (clang-format-region (point-min) (point-max) style assume-file-name))
202
203;;;###autoload
204(defalias 'clang-format 'clang-format-region)
205
206(provide 'clang-format)
207;;; clang-format.el ends here
208