]> code.delx.au - gnu-emacs-elpa/blob - company-clang.el
company-clang: with 2.9+, use stdin
[gnu-emacs-elpa] / company-clang.el
1 ;;; company-clang.el --- company-mode completion back-end for Clang
2
3 ;; Copyright (C) 2009, 2011, 2013 Free Software Foundation, Inc.
4
5 ;; Author: Nikolaj Schumacher
6
7 ;; This file is part of GNU Emacs.
8
9 ;; GNU Emacs is free software: you can redistribute it and/or modify
10 ;; it under the terms of the GNU General Public License as published by
11 ;; the Free Software Foundation, either version 3 of the License, or
12 ;; (at your option) any later version.
13
14 ;; GNU Emacs is distributed in the hope that it will be useful,
15 ;; but WITHOUT ANY WARRANTY; without even the implied warranty of
16 ;; MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
17 ;; GNU General Public License for more details.
18
19 ;; You should have received a copy of the GNU General Public License
20 ;; along with GNU Emacs. If not, see <http://www.gnu.org/licenses/>.
21
22
23 ;;; Commentary:
24 ;;
25
26 ;;; Code:
27
28 (require 'company)
29 (require 'company-template)
30 (eval-when-compile (require 'cl))
31
32 (defgroup company-clang nil
33 "Completion back-end for Clang."
34 :group 'company)
35
36 (defcustom company-clang-executable
37 (executable-find "clang")
38 "Location of clang executable."
39 :type 'file)
40
41 (defcustom company-clang-arguments nil
42 "Additional arguments to pass to clang when completing.
43 Prefix files (-include ...) can be selected with
44 `company-clang-set-prefix' or automatically through a custom
45 `company-clang-prefix-guesser'."
46 :type '(repeat (string :tag "Argument" nil)))
47
48 (defcustom company-clang-prefix-guesser 'company-clang-guess-prefix
49 "A function to determine the prefix file for the current buffer."
50 :type '(function :tag "Guesser function" nil))
51
52 (defvar company-clang-modes '(c-mode c++-mode objc-mode)
53 "Major modes which clang may complete.")
54
55 ;; prefix ;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;
56
57 (defvar company-clang--prefix nil)
58
59 (defsubst company-clang--guess-pch-file (file)
60 (let ((dir (directory-file-name (file-name-directory file))))
61 (when (equal (file-name-nondirectory dir) "Classes")
62 (setq dir (file-name-directory dir)))
63 (car (directory-files dir t "\\([^.]h\\|[^h]\\).pch\\'" t))))
64
65 (defsubst company-clang--file-substring (file beg end)
66 (with-temp-buffer
67 (insert-file-contents-literally file nil beg end)
68 (buffer-string)))
69
70 (defun company-clang-guess-prefix ()
71 "Try to guess the prefix file for the current buffer."
72 ;; Prefixes seem to be called .pch. Pre-compiled headers do, too.
73 ;; So we look at the magic number to rule them out.
74 (let* ((file (company-clang--guess-pch-file buffer-file-name))
75 (magic-number (and file (company-clang--file-substring file 0 4))))
76 (unless (member magic-number '("CPCH" "gpch"))
77 file)))
78
79 (defun company-clang-set-prefix (&optional prefix)
80 "Use PREFIX as a prefix (-include ...) file for clang completion."
81 (interactive (let ((def (funcall company-clang-prefix-guesser)))
82 (unless (stringp def)
83 (setq def default-directory))
84 (list (read-file-name "Prefix file: "
85 (when def (file-name-directory def))
86 def t (when def (file-name-nondirectory def))))))
87 ;; TODO: pre-compile?
88 (setq company-clang--prefix (and (stringp prefix)
89 (file-regular-p prefix)
90 prefix)))
91
92 ;; Clean-up on exit.
93 (add-hook 'kill-emacs-hook 'company-clang-set-prefix)
94
95 ;; parsing ;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;
96
97 ;; TODO: Handle Pattern (syntactic hints would be neat).
98 ;; Do we ever see OVERLOAD (or OVERRIDE)?
99 (defconst company-clang--completion-pattern
100 "^COMPLETION: \\_<\\(%s[a-zA-Z0-9_:]*\\)\\(?: : \\(.*\\)$\\)?$")
101
102 (defconst company-clang--error-buffer-name "*clang error*")
103
104 (defvar company-clang--meta-cache nil)
105
106 (defun company-clang--lang-option ()
107 (if (eq major-mode 'objc-mode)
108 (if (string= "m" (file-name-extension buffer-file-name))
109 "objective-c" "objective-c++")
110 (substring (symbol-name major-mode) 0 -5)))
111
112 (defun company-clang--parse-output (prefix objc)
113 (goto-char (point-min))
114 (let ((pattern (format company-clang--completion-pattern
115 (regexp-quote prefix)))
116 (case-fold-search nil)
117 lines match)
118 (setq company-clang--meta-cache (make-hash-table :test 'equal))
119 (while (re-search-forward pattern nil t)
120 (setq match (match-string-no-properties 1))
121 (unless (equal match "Pattern")
122 (let ((meta (match-string-no-properties 2)))
123 (when (and meta (not (string= match meta)))
124 (setq meta (company-clang--strip-formatting meta))
125 (when (and (not objc) (string-match "\\((.*)\\)" meta))
126 (setq match (concat match (match-string 1 meta))))
127 (puthash match meta company-clang--meta-cache)))
128 (push match lines)))
129 lines))
130
131 (defun company-clang--strip-formatting (text)
132 (replace-regexp-in-string
133 "#]" " "
134 (replace-regexp-in-string "[<{[]#\\|#[>}]" "" text t)
135 t))
136
137 (defun company-clang--handle-error (res args)
138 (goto-char (point-min))
139 (let* ((buf (get-buffer-create company-clang--error-buffer-name))
140 (cmd (concat company-clang-executable (mapconcat 'identity args " ")))
141 (pattern (format company-clang--completion-pattern ""))
142 (err (if (re-search-forward pattern nil t)
143 (buffer-substring-no-properties (point-min)
144 (1- (match-beginning 0)))
145 ;; Warn the user more aggressively if no match was found.
146 (message "clang failed with error %d:\n%s" res cmd)
147 (buffer-string))))
148
149 (with-current-buffer buf
150 (let ((inhibit-read-only t))
151 (erase-buffer)
152 (insert (current-time-string)
153 (format "\nclang failed with error %d:\n" res)
154 cmd "\n\n")
155 (insert err)
156 (setq buffer-read-only t)
157 (goto-char (point-min))))))
158
159 (defun company-clang--call-process (prefix &rest args)
160 (let ((objc (derived-mode-p 'objc-mode))
161 (buf (get-buffer-create "*clang-output*"))
162 res)
163 (with-current-buffer buf (erase-buffer))
164 (setq res (if (company-clang--auto-save-p)
165 (apply 'call-process company-clang-executable nil buf nil args)
166 (apply 'call-process-region (point-min) (point-max)
167 company-clang-executable nil buf nil args)))
168 (with-current-buffer buf
169 (unless (eq 0 res)
170 (company-clang--handle-error res args))
171 ;; Still try to get any useful input.
172 (company-clang--parse-output prefix objc))))
173
174 (defsubst company-clang--build-location (pos)
175 (save-excursion
176 (goto-char pos)
177 (format "%s:%d:%d"
178 (if (company-clang--auto-save-p) buffer-file-name "-")
179 (line-number-at-pos)
180 (1+ (current-column)))))
181
182 (defsubst company-clang--build-complete-args (pos)
183 (append '("-cc1" "-fsyntax-only" "-code-completion-macros")
184 (unless (company-clang--auto-save-p)
185 (list "-x" (company-clang--lang-option)))
186 company-clang-arguments
187 (when (stringp company-clang--prefix)
188 (list "-include" (expand-file-name company-clang--prefix)))
189 '("-code-completion-at")
190 (list (company-clang--build-location pos))
191 (list (if (company-clang--auto-save-p) buffer-file-name "-"))))
192
193 (defun company-clang--candidates (prefix)
194 (and (company-clang--auto-save-p)
195 (buffer-modified-p)
196 (basic-save-buffer))
197 (when (null company-clang--prefix)
198 (company-clang-set-prefix (or (funcall company-clang-prefix-guesser)
199 'none)))
200 (apply 'company-clang--call-process
201 prefix
202 (company-clang--build-complete-args (- (point) (length prefix)))))
203
204 ;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;
205
206 (defconst company-clang-required-version 1.1)
207
208 (defvar company-clang--version nil)
209
210 (defun company-clang--auto-save-p ()
211 (< company-clang--version 2.9))
212
213 (defsubst company-clang-version ()
214 "Return the version of `company-clang-executable'."
215 (with-temp-buffer
216 (call-process company-clang-executable nil t nil "--version")
217 (goto-char (point-min))
218 (if (re-search-forward "clang\\(?: version \\|-\\)\\([0-9.]+\\)" nil t)
219 (let ((ver (string-to-number (match-string-no-properties 1))))
220 (if (> ver 100)
221 (/ ver 100)
222 ver))
223 0)))
224
225 (defun company-clang-objc-templatify (selector)
226 (let* ((end (point-marker))
227 (beg (- (point) (length selector)))
228 (templ (company-template-declare-template beg end))
229 (cnt 0))
230 (save-excursion
231 (goto-char beg)
232 (catch 'stop
233 (while (search-forward ":" end t)
234 (company-template-add-field templ (point) (format "arg%d" cnt))
235 (if (< (point) end)
236 (insert " ")
237 (throw 'stop t))
238 (incf cnt))))
239 (company-template-move-to-first templ)))
240
241 (defun company-clang (command &optional arg &rest ignored)
242 "`company-mode' completion back-end for Clang.
243 Clang is a parser for C and ObjC. Clang version 1.1 or newer is required.
244
245 Additional command line arguments can be specified in
246 `company-clang-arguments'. Prefix files (-include ...) can be selected
247 with `company-clang-set-prefix' or automatically through a custom
248 `company-clang-prefix-guesser'.
249
250 With Clang versions before 2.9, we have to save the buffer before performing
251 completion. With Clang 2.9 and later, buffer contents are passed via stardard
252 input."
253 (interactive (list 'interactive))
254 (case command
255 (interactive (company-begin-backend 'company-clang))
256 (init (when (memq major-mode company-clang-modes)
257 (unless company-clang-executable
258 (error "Company found no clang executable"))
259 (setq company-clang--version (company-clang-version))
260 (when (< company-clang--version company-clang-required-version)
261 (error "Company requires clang version 1.1"))))
262 (prefix (and (memq major-mode company-clang-modes)
263 buffer-file-name
264 company-clang-executable
265 (not (company-in-string-or-comment))
266 (or (company-grab-symbol) 'stop)))
267 (candidates (company-clang--candidates arg))
268 (meta (gethash arg company-clang--meta-cache))
269 (crop (and (string-match ":\\|(" arg)
270 (substring arg 0 (match-beginning 0))))
271 (post-completion (cond
272 ((not (derived-mode-p 'objc-mode))
273 (company-template-c-like-templatify arg))
274 ((string-match ":" arg)
275 (company-clang-objc-templatify arg))))))
276
277 (provide 'company-clang)
278 ;;; company-clang.el ends here