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