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