1 ;;; company-clang.el --- company-mode completion back-end for Clang
3 ;; Copyright (C) 2009, 2011, 2013 Free Software Foundation, Inc.
5 ;; Author: Nikolaj Schumacher
7 ;; This file is part of GNU Emacs.
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.
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.
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/>.
29 (require 'company-template)
30 (eval-when-compile (require 'cl))
32 (defgroup company-clang nil
33 "Completion back-end for Clang."
36 (defcustom company-clang-executable
37 (executable-find "clang")
38 "Location of clang executable."
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'.
45 If `company-begin-commands' is a list, it should include `c-electric-lt-gt'.")
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)))
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))
58 (defvar company-clang-modes '(c-mode c++-mode objc-mode)
59 "Major modes which clang may complete.")
61 ;; prefix ;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;
63 (defvar company-clang--prefix nil)
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))))
71 (defsubst company-clang--file-substring (file beg end)
73 (insert-file-contents-literally file nil beg end)
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"))
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)))
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))))))
94 (setq company-clang--prefix (and (stringp prefix)
95 (file-regular-p prefix)
99 (add-hook 'kill-emacs-hook 'company-clang-set-prefix)
101 ;; parsing ;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;
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_:]*\\)\\(?: : \\(.*\\)$\\)?$")
108 (defconst company-clang--error-buffer-name "*clang error*")
110 (defvar company-clang--meta-cache nil)
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)))
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)
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)))
137 (defun company-clang--strip-formatting (text)
138 (replace-regexp-in-string
140 (replace-regexp-in-string "[<{[]#\\|#[>}]" "" text t)
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)
155 (with-current-buffer buf
156 (let ((inhibit-read-only t))
158 (insert (current-time-string)
159 (format "\nclang failed with error %d:\n" res)
162 (setq buffer-read-only t)
163 (goto-char (point-min))))))
165 (defun company-clang--call-process (prefix &rest args)
166 (let ((objc (derived-mode-p 'objc-mode))
167 (buf (get-buffer-create "*clang-output*"))
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
176 (company-clang--handle-error res args))
177 ;; Still try to get any useful input.
178 (company-clang--parse-output prefix objc))))
180 (defsubst company-clang--build-location (pos)
184 (if (company-clang--auto-save-p) buffer-file-name "-")
186 (1+ (current-column)))))
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 "-"))))
199 (defun company-clang--candidates (prefix)
200 (and (company-clang--auto-save-p)
203 (when (null company-clang--prefix)
204 (company-clang-set-prefix (or (funcall company-clang-prefix-guesser)
206 (apply 'company-clang--call-process
208 (company-clang--build-complete-args (- (point) (length prefix)))))
210 (defun company-clang--prefix ()
211 (let ((symbol (company-grab-symbol)))
213 (if (and company-clang-begin-after-member-access
215 (forward-char (- (length symbol)))
216 (looking-back "\\.\\|->" (- (point) 3))))
221 ;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;
223 (defconst company-clang-required-version 1.1)
225 (defvar company-clang--version nil)
227 (defun company-clang--auto-save-p ()
228 (< company-clang--version 2.9))
230 (defsubst company-clang-version ()
231 "Return the version of `company-clang-executable'."
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))))
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))
250 (while (search-forward ":" end t)
251 (company-template-add-field templ (point) (format "arg%d" cnt))
256 (company-template-move-to-first templ)))
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.
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'.
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
270 (interactive (list 'interactive))
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)
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))))))
294 (provide 'company-clang)
295 ;;; company-clang.el ends here