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