]> rtime.felk.cvut.cz Git - sojka/company-mode.git/blob - company-clang.el
Be less verbose when writing files.
[sojka/company-mode.git] / company-clang.el
1 ;;; company-clang.el --- a company-mode completion back-end for clang
2 ;;
3 ;; Copyright (C) 2010 Nikolaj Schumacher
4 ;;
5 ;; This file is part of company 0.4.3.
6 ;;
7 ;; This program is free software; you can redistribute it and/or
8 ;; modify it under the terms of the GNU General Public License
9 ;; as published by the Free Software Foundation; either version 2
10 ;; of the License, or (at your option) any later version.
11 ;;
12 ;; This program is distributed in the hope that it will be useful,
13 ;; but WITHOUT ANY WARRANTY; without even the implied warranty of
14 ;; MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
15 ;; GNU General Public License for more details.
16 ;;
17 ;; You should have received a copy of the GNU General Public License
18 ;; along with this program.  If not, see <http://www.gnu.org/licenses/>.
19
20 (require 'company)
21 (eval-when-compile (require 'cl))
22
23 (defcustom company-clang-executable
24   (executable-find "clang")
25   "*Location of clang executable"
26   :group 'company-clang
27   :type 'file)
28
29 (defcustom company-clang-auto-save t
30   "*Determines whether to save the buffer when retrieving completions.
31 clang can only complete correctly when the buffer has been saved."
32   :group 'company-clang
33   :type '(choice (const :tag "Off" nil)
34                  (const :tag "On" t)))
35
36 (defcustom company-clang-arguments nil
37   "*Additional arguments to pass to clang when completing.
38 Prefix files (-include ...) can be selected with
39 `company-clang-set-prefix' or automatically through a custom
40 `company-clang-prefix-guesser'."
41   :group 'company-clang
42   :type '(repeat (string :tag "Argument" nil)))
43
44 (defcustom company-clang-prefix-guesser 'company-clang-guess-prefix
45   "*A function to determine the prefix file for the current buffer."
46   :group 'company-clang
47   :type '(function :tag "Guesser function" nil))
48
49 (defvar company-clang-modes '(c-mode objc-mode)
50   "Major modes which clang may complete.")
51
52 ;; prefix ;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;
53
54 (defvar company-clang--prefix nil)
55
56 (defsubst company-clang--guess-pch-file (file)
57   (let ((dir (directory-file-name (file-name-directory file))))
58     (when (equal (file-name-nondirectory dir) "Classes")
59       (setq dir (file-name-directory dir)))
60     (car (directory-files dir t "\\([^.]h\\|[^h]\\).pch\\'" t))))
61
62 (defsubst company-clang--file-substring (file beg end)
63   (with-temp-buffer
64     (insert-file-contents-literally file nil beg end)
65     (buffer-string)))
66
67 (defun company-clang-guess-prefix ()
68   "Try to guess the prefix file for the current buffer."
69   ;; Prefixes seem to be called .pch.  Pre-compiled headers do, too.
70   ;; So we look at the magic number to rule them out.
71   (let* ((file (company-clang--guess-pch-file buffer-file-name))
72          (magic-number (company-clang--file-substring file 0 4)))
73     (unless (member magic-number '("CPCH" "gpch"))
74       file)))
75
76 (defun company-clang-set-prefix (&optional prefix)
77   "Use PREFIX as a prefix (-include ...) file for clang completion."
78   (interactive (let ((def (funcall company-clang-prefix-guesser)))
79      (unless (stringp def)
80        (setq def default-directory))
81      (list (read-file-name "Prefix file: "
82                            (when def (file-name-directory def))
83                            def t (when def (file-name-nondirectory def))))))
84   ;; TODO: pre-compile?
85   (setq company-clang--prefix (and (stringp prefix)
86                                    (file-regular-p prefix)
87                                    prefix)))
88
89 ;; Clean-up on exit.
90 (add-hook 'kill-emacs-hook 'company-clang-set-prefix)
91
92 ;; parsing ;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;
93
94 ;; TODO: How to handle OVERLOAD and Pattern?
95 (defconst company-clang--completion-pattern
96   "^COMPLETION: \\_<\\(%s[a-zA-Z0-9_:]*\\)")
97
98 (defconst company-clang--error-buffer-name "*clang error*")
99
100 (defun company-clang--parse-output (prefix)
101   (goto-char (point-min))
102   (let ((pattern (format company-clang--completion-pattern
103                          (regexp-quote prefix)))
104         lines match)
105     (while (re-search-forward pattern nil t)
106       (setq match (match-string-no-properties 1))
107       (unless (equal match "Pattern")
108         (push match lines)))
109     lines))
110
111 (defun company-clang--handle-error (res args)
112   (goto-char (point-min))
113   (let* ((buf (get-buffer-create company-clang--error-buffer-name))
114          (cmd (concat company-clang-executable (mapconcat 'identity args " ")))
115          (pattern (format company-clang--completion-pattern ""))
116          (err (if (re-search-forward pattern nil t)
117                   (buffer-substring-no-properties (point-min)
118                                                   (1- (match-beginning 0)))
119                 ;; Warn the user more agressively if no match was found.
120                 (message "clang failed with error %d:\n%s" res cmd)
121                 (buffer-string))))
122
123     (with-current-buffer buf
124       (let ((inhibit-read-only t))
125         (erase-buffer)
126         (insert (current-time-string)
127                 (format "\nclang failed with error %d:\n" res)
128                 cmd "\n\n")
129         (insert err)
130         (setq buffer-read-only t)
131         (goto-char (point-min))))))
132
133 (defun company-clang--call-process (prefix &rest args)
134   (with-temp-buffer
135     (let ((res (apply 'call-process company-clang-executable nil t nil args)))
136       (unless (eq 0 res)
137         (company-clang--handle-error res args))
138       ;; Still try to get any useful input.
139       (company-clang--parse-output prefix))))
140
141 (defsubst company-clang--build-location (pos)
142   (save-excursion
143     (goto-char pos)
144     (format "%s:%d:%d" buffer-file-name (line-number-at-pos)
145             (1+ (current-column)))))
146
147 (defsubst company-clang--build-complete-args (pos)
148   (append '("-cc1" "-fsyntax-only")
149           company-clang-arguments
150           (when (stringp company-clang--prefix)
151             (list "-include" (expand-file-name company-clang--prefix)))
152           '("-code-completion-at")
153           (list (company-clang--build-location pos))
154           (list buffer-file-name)))
155
156 (defun company-clang--candidates (prefix)
157   (and company-clang-auto-save
158        (buffer-modified-p)
159        (basic-save-buffer))
160   (when (null company-clang--prefix)
161     (company-clang-set-prefix (or (funcall company-clang-prefix-guesser)
162                                   'none)))
163   (apply 'company-clang--call-process
164          prefix
165          (company-clang--build-complete-args (- (point) (length prefix)))))
166
167 (defun company-clang (command &optional arg &rest ignored)
168   "A `company-mode' completion back-end for clang.
169 Clang is a parser for C and ObjC.  The unreleased development version of
170 clang (1.1) is required.
171
172 Additional command line arguments can be specified in
173 `company-clang-arguments'.  Prefix files (-include ...) can be selected
174 with `company-clang-set-prefix' or automatically through a custom
175 `company-clang-prefix-guesser'.
176
177 Completions only work correctly when the buffer has been saved.
178 `company-clang-auto-save' determines whether to do this automatically."
179   (interactive (list 'interactive))
180   (case command
181         ('interactive (company-begin-backend 'company-clang))
182         ('prefix (and (memq major-mode company-clang-modes)
183                       buffer-file-name
184                       company-clang-executable
185                       (not (company-in-string-or-comment))
186                       (or (company-grab-symbol) 'stop)))
187         ('candidates (company-clang--candidates arg))))
188
189 (provide 'company-clang)
190 ;;; company-clang.el ends here