]> code.delx.au - gnu-emacs-elpa/blob - company.el
Don't consider backward-delete-char-untabify incremental.
[gnu-emacs-elpa] / company.el
1 ;;; company.el --- extensible inline text completion mechanism
2 ;;
3 ;; Copyright (C) 2009 Nikolaj Schumacher
4 ;;
5 ;; Author: Nikolaj Schumacher <bugs * nschum de>
6 ;; Version: 0.4
7 ;; Keywords: abbrev, convenience, matchis
8 ;; URL: http://nschum.de/src/emacs/company/
9 ;; Compatibility: GNU Emacs 22.x, GNU Emacs 23.x
10 ;;
11 ;; This file is NOT part of GNU Emacs.
12 ;;
13 ;; This program is free software; you can redistribute it and/or
14 ;; modify it under the terms of the GNU General Public License
15 ;; as published by the Free Software Foundation; either version 2
16 ;; of the License, or (at your option) any later version.
17 ;;
18 ;; This program is distributed in the hope that it will be useful,
19 ;; but WITHOUT ANY WARRANTY; without even the implied warranty of
20 ;; MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
21 ;; GNU General Public License for more details.
22 ;;
23 ;; You should have received a copy of the GNU General Public License
24 ;; along with this program. If not, see <http://www.gnu.org/licenses/>.
25 ;;
26 ;;; Commentary:
27 ;;
28 ;; Company is a modular completion mechanism. Modules for retrieving completion
29 ;; candidates are called back-ends, modules for displaying them are front-ends.
30 ;;
31 ;; Company comes with many back-ends, e.g. `company-elisp'. These are
32 ;; distributed in individual files and can be used individually.
33 ;;
34 ;; Place company.el and the back-ends you want to use in a directory and add the
35 ;; following to your .emacs:
36 ;; (add-to-list 'load-path "/path/to/company")
37 ;; (autoload 'company-mode "company" nil t)
38 ;;
39 ;; Enable company-mode with M-x company-mode. For further information look at
40 ;; the documentation for `company-mode' (C-h f company-mode RET)
41 ;;
42 ;; If you want to start a specific back-end, call it interactively or use
43 ;; `company-begin-backend'. For example:
44 ;; M-x company-abbrev will prompt for and insert an abbrev.
45 ;;
46 ;; To write your own back-end, look at the documentation for `company-backends'.
47 ;; Here is a simple example completing "foo":
48 ;;
49 ;; (defun company-my-backend (command &optional arg &rest ignored)
50 ;; (case command
51 ;; ('prefix (when (looking-back "foo\\>")
52 ;; (match-string 0)))
53 ;; ('candidates (list "foobar" "foobaz" "foobarbaz"))
54 ;; ('meta (format "This value is named %s" arg))))
55 ;;
56 ;; Sometimes it is a good idea to mix two back-ends together, for example to
57 ;; enrich gtags with dabbrev text (to emulate local variables):
58 ;;
59 ;; (defun gtags-gtags-dabbrev-backend (command &optional arg &rest ignored)
60 ;; (case command
61 ;; (prefix (company-gtags 'prefix))
62 ;; (candidates (append (company-gtags 'candidates arg)
63 ;; (company-dabbrev 'candidates arg)))))
64 ;;
65 ;; Known Issues:
66 ;; When point is at the very end of the buffer, the pseudo-tooltip appears very
67 ;; wrong, unless company is allowed to temporarily insert a fake newline.
68 ;; This behavior is enabled by `company-end-of-buffer-workaround'.
69 ;;
70 ;;; Change Log:
71 ;;
72 ;; Added safer workaround for Emacs `posn-col-row' bug.
73 ;;
74 ;; 2009-04-18 (0.4)
75 ;; Automatic completion is now aborted if the prefix gets too short.
76 ;; Added option `company-dabbrev-time-limit'.
77 ;; `company-backends' now supports merging back-ends.
78 ;; Added back-end `company-dabbrev-code' for generic code.
79 ;; Fixed `company-begin-with'.
80 ;;
81 ;; 2009-04-15 (0.3.1)
82 ;; Added 'stop prefix to prevent dabbrev from completing inside of symbols.
83 ;; Fixed issues with tabbar-mode and line-spacing.
84 ;; Performance enhancements.
85 ;;
86 ;; 2009-04-12 (0.3)
87 ;; Added `company-begin-commands' option.
88 ;; Added abbrev, tempo and Xcode back-ends.
89 ;; Back-ends are now interactive. You can start them with M-x backend-name.
90 ;; Added `company-begin-with' for starting company from elisp-code.
91 ;; Added hooks.
92 ;; Added `company-require-match' and `company-auto-complete' options.
93 ;;
94 ;; 2009-04-05 (0.2.1)
95 ;; Improved Emacs Lisp back-end behavior for local variables.
96 ;; Added `company-elisp-detect-function-context' option.
97 ;; The mouse can now be used for selection.
98 ;;
99 ;; 2009-03-22 (0.2)
100 ;; Added `company-show-location'.
101 ;; Added etags back-end.
102 ;; Added work-around for end-of-buffer bug.
103 ;; Added `company-filter-candidates'.
104 ;; More local Lisp variables are now included in the candidates.
105 ;;
106 ;; 2009-03-21 (0.1.5)
107 ;; Fixed elisp documentation buffer always showing the same doc.
108 ;; Added `company-echo-strip-common-frontend'.
109 ;; Added `company-show-numbers' option and M-0 ... M-9 default bindings.
110 ;; Don't hide the echo message if it isn't shown.
111 ;;
112 ;; 2009-03-20 (0.1)
113 ;; Initial release.
114 ;;
115 ;;; Code:
116
117 (eval-when-compile (require 'cl))
118
119 (add-to-list 'debug-ignored-errors "^.* frontend cannot be used twice$")
120 (add-to-list 'debug-ignored-errors "^Echo area cannot be used twice$")
121 (add-to-list 'debug-ignored-errors "^No \\(document\\|loc\\)ation available$")
122 (add-to-list 'debug-ignored-errors "^Company not ")
123 (add-to-list 'debug-ignored-errors "^No candidate number ")
124 (add-to-list 'debug-ignored-errors "^Cannot complete at point$")
125
126 (defgroup company nil
127 "Extensible inline text completion mechanism"
128 :group 'abbrev
129 :group 'convenience
130 :group 'maching)
131
132 (defface company-tooltip
133 '((t :background "yellow"
134 :foreground "black"))
135 "*Face used for the tool tip."
136 :group 'company)
137
138 (defface company-tooltip-selection
139 '((default :inherit company-tooltip)
140 (((class color) (min-colors 88)) (:background "orange1"))
141 (t (:background "green")))
142 "*Face used for the selection in the tool tip."
143 :group 'company)
144
145 (defface company-tooltip-mouse
146 '((default :inherit highlight))
147 "*Face used for the tool tip item under the mouse."
148 :group 'company)
149
150 (defface company-tooltip-common
151 '((t :inherit company-tooltip
152 :foreground "red"))
153 "*Face used for the common completion in the tool tip."
154 :group 'company)
155
156 (defface company-tooltip-common-selection
157 '((t :inherit company-tooltip-selection
158 :foreground "red"))
159 "*Face used for the selected common completion in the tool tip."
160 :group 'company)
161
162 (defcustom company-tooltip-limit 10
163 "*The maximum number of candidates in the tool tip"
164 :group 'company
165 :type 'integer)
166
167 (defface company-preview
168 '((t :background "blue4"
169 :foreground "wheat"))
170 "*Face used for the completion preview."
171 :group 'company)
172
173 (defface company-preview-common
174 '((t :inherit company-preview
175 :foreground "red"))
176 "*Face used for the common part of the completion preview."
177 :group 'company)
178
179 (defface company-preview-search
180 '((t :inherit company-preview
181 :background "blue1"))
182 "*Face used for the search string in the completion preview."
183 :group 'company)
184
185 (defface company-echo nil
186 "*Face used for completions in the echo area."
187 :group 'company)
188
189 (defface company-echo-common
190 '((((background dark)) (:foreground "firebrick1"))
191 (((background light)) (:background "firebrick4")))
192 "*Face used for the common part of completions in the echo area."
193 :group 'company)
194
195 (defun company-frontends-set (variable value)
196 ;; uniquify
197 (let ((remainder value))
198 (setcdr remainder (delq (car remainder) (cdr remainder))))
199 (and (memq 'company-pseudo-tooltip-unless-just-one-frontend value)
200 (memq 'company-pseudo-tooltip-frontend value)
201 (error "Pseudo tooltip frontend cannot be used twice"))
202 (and (memq 'company-preview-if-just-one-frontend value)
203 (memq 'company-preview-frontend value)
204 (error "Preview frontend cannot be used twice"))
205 (and (memq 'company-echo value)
206 (memq 'company-echo-metadata-frontend value)
207 (error "Echo area cannot be used twice"))
208 ;; preview must come last
209 (dolist (f '(company-preview-if-just-one-frontend company-preview-frontend))
210 (when (memq f value)
211 (setq value (append (delq f value) (list f)))))
212 (set variable value))
213
214 (defcustom company-frontends '(company-pseudo-tooltip-unless-just-one-frontend
215 company-preview-frontend
216 company-echo-metadata-frontend)
217 "*The list of active front-ends (visualizations).
218 Each front-end is a function that takes one argument. It is called with
219 one of the following arguments:
220
221 'show: When the visualization should start.
222
223 'hide: When the visualization should end.
224
225 'update: When the data has been updated.
226
227 'pre-command: Before every command that is executed while the
228 visualization is active.
229
230 'post-command: After every command that is executed while the
231 visualization is active.
232
233 The visualized data is stored in `company-prefix', `company-candidates',
234 `company-common', `company-selection', `company-point' and
235 `company-search-string'."
236 :set 'company-frontends-set
237 :group 'company
238 :type '(repeat (choice (const :tag "echo" company-echo-frontend)
239 (const :tag "echo, strip common"
240 company-echo-strip-common-frontend)
241 (const :tag "show echo meta-data in echo"
242 company-echo-metadata-frontend)
243 (const :tag "pseudo tooltip"
244 company-pseudo-tooltip-frontend)
245 (const :tag "pseudo tooltip, multiple only"
246 company-pseudo-tooltip-unless-just-one-frontend)
247 (const :tag "preview" company-preview-frontend)
248 (const :tag "preview, unique only"
249 company-preview-if-just-one-frontend)
250 (function :tag "custom function" nil))))
251
252 (defvar company-safe-backends
253 '((company-abbrev . "Abbrev")
254 (company-css . "CSS")
255 (company-dabbrev . "dabbrev for plain text")
256 (company-dabbrev-code . "dabbrev for code")
257 (company-elisp . "Emacs Lisp")
258 (company-etags . "etags")
259 (company-files . "Files")
260 (company-gtags . "GNU Global")
261 (company-ispell . "ispell")
262 (company-keywords . "Programming language keywords")
263 (company-nxml . "nxml")
264 (company-oddmuse . "Oddmuse")
265 (company-semantic . "CEDET Semantic")
266 (company-tempo . "Tempo templates")
267 (company-xcode . "Xcode")))
268 (put 'company-safe-backends 'risky-local-variable t)
269
270 (defun company-safe-backends-p (backends)
271 (and (consp backends)
272 (not (dolist (backend backends)
273 (unless (if (consp backend)
274 (company-safe-backends-p backend)
275 (assq backend company-safe-backends))
276 (return t))))))
277
278 (defcustom company-backends '(company-elisp company-nxml company-css
279 company-semantic company-xcode
280 (company-gtags company-etags company-dabbrev-code
281 company-keywords)
282 company-oddmuse company-files company-dabbrev)
283 "*The list of active back-ends (completion engines).
284 Each list elements can itself be a list of back-ends. In that case their
285 completions are merged. Otherwise only the first matching back-end returns
286 results.
287
288 Each back-end is a function that takes a variable number of arguments.
289 The first argument is the command requested from the back-end. It is one
290 of the following:
291
292 'prefix: The back-end should return the text to be completed. It must be
293 text immediately before `point'. Returning nil passes control to the next
294 back-end. The function should return 'stop if it should complete but cannot
295 \(e.g. if it is in the middle of a string\).
296
297 'candidates: The second argument is the prefix to be completed. The
298 return value should be a list of candidates that start with the prefix.
299
300 Optional commands:
301
302 'sorted: The back-end may return t here to indicate that the candidates
303 are sorted and will not need to be sorted again.
304
305 'duplicates: If non-nil, company will take care of removing duplicates
306 from the list.
307
308 'no-cache: Usually company doesn't ask for candidates again as completion
309 progresses, unless the back-end returns t for this command. The second
310 argument is the latest prefix.
311
312 'meta: The second argument is a completion candidate. The back-end should
313 return a (short) documentation string for it.
314
315 'doc-buffer: The second argument is a completion candidate. The back-end should
316 create a buffer (preferably with `company-doc-buffer'), fill it with
317 documentation and return it.
318
319 'location: The second argument is a completion candidate. The back-end can
320 return the cons of buffer and buffer location, or of file and line
321 number where the completion candidate was defined.
322
323 'require-match: If this value is t, the user is not allowed to enter anything
324 not offering as a candidate. Use with care! The default value nil gives the
325 user that choice with `company-require-match'. Return value 'never overrides
326 that option the other way around.
327
328 The back-end should return nil for all commands it does not support or
329 does not know about. It should also be callable interactively and use
330 `company-begin-backend' to start itself in that case."
331 :group 'company
332 :type `(repeat
333 (choice
334 :tag "Back-end"
335 ,@(mapcar (lambda (b) `(const :tag ,(cdr b) ,(car b)))
336 company-safe-backends)
337 (symbol :tag "User defined")
338 (repeat :tag "Merged Back-ends"
339 (choice :tag "Back-end"
340 ,@(mapcar (lambda (b)
341 `(const :tag ,(cdr b) ,(car b)))
342 company-safe-backends)
343 (symbol :tag "User defined"))))))
344
345 (put 'company-backends 'safe-local-variable 'company-safe-backend-p)
346
347 (defcustom company-completion-started-hook nil
348 "*Hook run when company starts completing.
349 The hook is called with one argument that is non-nil if the completion was
350 started manually."
351 :group 'company
352 :type 'hook)
353
354 (defcustom company-completion-cancelled-hook nil
355 "*Hook run when company cancels completing.
356 The hook is called with one argument that is non-nil if the completion was
357 aborted manually."
358 :group 'company
359 :type 'hook)
360
361 (defcustom company-completion-finished-hook nil
362 "*Hook run when company successfully completes.
363 The hook is called with the selected candidate as an argument."
364 :group 'company
365 :type 'hook)
366
367 (defcustom company-minimum-prefix-length 3
368 "*The minimum prefix length for automatic completion."
369 :group 'company
370 :type '(integer :tag "prefix length"))
371
372 (defcustom company-require-match 'company-explicit-action-p
373 "*If enabled, disallow non-matching input.
374 This can be a function do determine if a match is required.
375
376 This can be overridden by the back-end, if it returns t or 'never to
377 'require-match. `company-auto-complete' also takes precedence over this."
378 :group 'company
379 :type '(choice (const :tag "Off" nil)
380 (function :tag "Predicate function")
381 (const :tag "On, if user interaction took place"
382 'company-explicit-action-p)
383 (const :tag "On" t)))
384
385 (defcustom company-auto-complete 'company-explicit-action-p
386 "Determines when to auto-complete.
387 If this is enabled, all characters from `company-auto-complete-chars' complete
388 the selected completion. This can also be a function."
389 :group 'company
390 :type '(choice (const :tag "Off" nil)
391 (function :tag "Predicate function")
392 (const :tag "On, if user interaction took place"
393 'company-explicit-action-p)
394 (const :tag "On" t)))
395
396 (defcustom company-auto-complete-chars '(?\ ?\( ?\) ?. ?\" ?$ ?\' ?< ?| ?!)
397 "Determines which characters trigger an automatic completion.
398 See `company-auto-complete'. If this is a string, each string character causes
399 completion. If it is a list of syntax description characters (see
400 `modify-syntax-entry'), all characters with that syntax auto-complete.
401
402 This can also be a function, which is called with the new input and should
403 return non-nil if company should auto-complete.
404
405 A character that is part of a valid candidate never starts auto-completion."
406 :group 'company
407 :type '(choice (string :tag "Characters")
408 (set :tag "Syntax"
409 (const :tag "Whitespace" ?\ )
410 (const :tag "Symbol" ?_)
411 (const :tag "Opening parentheses" ?\()
412 (const :tag "Closing parentheses" ?\))
413 (const :tag "Word constituent" ?w)
414 (const :tag "Punctuation." ?.)
415 (const :tag "String quote." ?\")
416 (const :tag "Paired delimiter." ?$)
417 (const :tag "Expression quote or prefix operator." ?\')
418 (const :tag "Comment starter." ?<)
419 (const :tag "Comment ender." ?>)
420 (const :tag "Character-quote." ?/)
421 (const :tag "Generic string fence." ?|)
422 (const :tag "Generic comment fence." ?!))
423 (function :tag "Predicate function")))
424
425 (defcustom company-idle-delay .7
426 "*The idle delay in seconds until automatic completions starts.
427 A value of nil means never complete automatically, t means complete
428 immediately when a prefix of `company-minimum-prefix-length' is reached."
429 :group 'company
430 :type '(choice (const :tag "never (nil)" nil)
431 (const :tag "immediate (t)" t)
432 (number :tag "seconds")))
433
434 (defcustom company-begin-commands t
435 "*A list of commands following which company will start completing.
436 If this is t, it will complete after any command. See `company-idle-delay'.
437
438 Alternatively any command with a non-nil 'company-begin property is treated as
439 if it was on this list."
440 :group 'company
441 :type '(choice (const :tag "Any command" t)
442 (const :tag "Self insert command" '(self-insert-command))
443 (repeat :tag "Commands" function)))
444
445 (defcustom company-show-numbers nil
446 "*If enabled, show quick-access numbers for the first ten candidates."
447 :group 'company
448 :type '(choice (const :tag "off" nil)
449 (const :tag "on" t)))
450
451 (defvar company-end-of-buffer-workaround t
452 "*Work around a visualization bug when completing at the end of the buffer.
453 The work-around consists of adding a newline.")
454
455 ;;; mode ;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;
456
457 (defvar company-mode-map (make-sparse-keymap)
458 "Keymap used by `company-mode'.")
459
460 (defvar company-active-map
461 (let ((keymap (make-sparse-keymap)))
462 (define-key keymap "\e\e\e" 'company-abort)
463 (define-key keymap "\C-g" 'company-abort)
464 (define-key keymap (kbd "M-n") 'company-select-next)
465 (define-key keymap (kbd "M-p") 'company-select-previous)
466 (define-key keymap (kbd "<down>") 'company-select-next)
467 (define-key keymap (kbd "<up>") 'company-select-previous)
468 (define-key keymap [down-mouse-1] 'ignore)
469 (define-key keymap [down-mouse-3] 'ignore)
470 (define-key keymap [mouse-1] 'company-complete-mouse)
471 (define-key keymap [mouse-3] 'company-select-mouse)
472 (define-key keymap [up-mouse-1] 'ignore)
473 (define-key keymap [up-mouse-3] 'ignore)
474 (define-key keymap "\C-m" 'company-complete-selection)
475 (define-key keymap "\t" 'company-complete-common)
476 (define-key keymap (kbd "<f1>") 'company-show-doc-buffer)
477 (define-key keymap "\C-w" 'company-show-location)
478 (define-key keymap "\C-s" 'company-search-candidates)
479 (define-key keymap "\C-\M-s" 'company-filter-candidates)
480 (dotimes (i 10)
481 (define-key keymap (vector (+ (aref (kbd "M-0") 0) i))
482 `(lambda () (interactive) (company-complete-number ,i))))
483
484 keymap)
485 "Keymap that is enabled during an active completion.")
486
487 (defun company-init-backend (backend)
488 (and (symbolp backend)
489 (not (fboundp backend))
490 (ignore-errors (require backend nil t)))
491
492 (if (or (symbolp backend)
493 (functionp backend))
494 (if (ignore-errors (funcall backend 'init) t)
495 (put backend 'company-init t)
496 (message "Company back-end '%s' could not be initialized"
497 backend))
498 (mapc 'company-init-backend backend)))
499
500 ;;;###autoload
501 (define-minor-mode company-mode
502 "\"complete anything\"; in in-buffer completion framework.
503 Completion starts automatically, depending on the values
504 `company-idle-delay' and `company-minimum-prefix-length'.
505
506 Completion can be controlled with the commands:
507 `company-complete-common', `company-complete-selection', `company-complete',
508 `company-select-next', `company-select-previous'. If these commands are
509 called before `company-idle-delay', completion will also start.
510
511 Completions can be searched with `company-search-candidates' or
512 `company-filter-candidates'. These can be used while completion is
513 inactive, as well.
514
515 The completion data is retrieved using `company-backends' and displayed using
516 `company-frontends'. If you want to start a specific back-end, call it
517 interactively or use `company-begin-backend'.
518
519 regular keymap (`company-mode-map'):
520
521 \\{company-mode-map}
522 keymap during active completions (`company-active-map'):
523
524 \\{company-active-map}"
525 nil " comp" company-mode-map
526 (if company-mode
527 (progn
528 (add-hook 'pre-command-hook 'company-pre-command nil t)
529 (add-hook 'post-command-hook 'company-post-command nil t)
530 (mapc 'company-init-backend company-backends))
531 (remove-hook 'pre-command-hook 'company-pre-command t)
532 (remove-hook 'post-command-hook 'company-post-command t)
533 (company-cancel)
534 (kill-local-variable 'company-point)))
535
536 (defsubst company-assert-enabled ()
537 (unless company-mode
538 (company-uninstall-map)
539 (error "Company not enabled")))
540
541 ;;; keymaps ;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;
542
543 (defvar company-overriding-keymap-bound nil)
544 (make-variable-buffer-local 'company-overriding-keymap-bound)
545
546 (defvar company-old-keymap nil)
547 (make-variable-buffer-local 'company-old-keymap)
548
549 (defvar company-my-keymap nil)
550 (make-variable-buffer-local 'company-my-keymap)
551
552 (defsubst company-enable-overriding-keymap (keymap)
553 (setq company-my-keymap keymap)
554 (when company-overriding-keymap-bound
555 (company-uninstall-map)))
556
557 (defun company-install-map ()
558 (unless (or company-overriding-keymap-bound
559 (null company-my-keymap))
560 (setq company-old-keymap overriding-terminal-local-map
561 overriding-terminal-local-map company-my-keymap
562 company-overriding-keymap-bound t)))
563
564 (defun company-uninstall-map ()
565 (when (eq overriding-terminal-local-map company-my-keymap)
566 (setq overriding-terminal-local-map company-old-keymap
567 company-overriding-keymap-bound nil)))
568
569 ;; Hack:
570 ;; Emacs calculates the active keymaps before reading the event. That means we
571 ;; cannot change the keymap from a timer. So we send a bogus command.
572 (defun company-ignore ()
573 (interactive)
574 (setq this-command last-command))
575
576 (global-set-key '[31415926] 'company-ignore)
577
578 (defun company-input-noop ()
579 (push 31415926 unread-command-events))
580
581 ;; Hack:
582 ;; posn-col-row is incorrect in older Emacsen when line-spacing is set
583 (defun company--col-row (&optional pos)
584 (let ((posn (posn-at-point pos)))
585 (cons (car (posn-col-row posn)) (cdr (posn-actual-col-row posn)))))
586
587 (defsubst company--column (&optional pos)
588 (car (posn-col-row (posn-at-point pos))))
589
590 (defsubst company--row (&optional pos)
591 (cdr (posn-actual-col-row (posn-at-point pos))))
592
593 ;;; backends ;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;
594
595 (defun company-grab (regexp &optional expression limit)
596 (when (looking-back regexp limit)
597 (or (match-string-no-properties (or expression 0)) "")))
598
599 (defun company-grab-line (regexp &optional expression)
600 (company-grab regexp expression (point-at-bol)))
601
602 (defun company-grab-symbol ()
603 (if (looking-at "\\_>")
604 (buffer-substring (point) (save-excursion (skip-syntax-backward "w_")
605 (point)))
606 (unless (and (char-after) (memq (char-syntax (char-after)) '(?w ?_)))
607 "")))
608
609 (defun company-grab-word ()
610 (if (looking-at "\\>")
611 (buffer-substring (point) (save-excursion (skip-syntax-backward "w")
612 (point)))
613 (unless (and (char-after) (eq (char-syntax (char-after)) ?w))
614 "")))
615
616 (defun company-in-string-or-comment ()
617 (let ((ppss (syntax-ppss)))
618 (or (car (setq ppss (nthcdr 3 ppss)))
619 (car (setq ppss (cdr ppss)))
620 (nth 3 ppss))))
621
622 (defun company-call-backend (&rest args)
623 (if (functionp company-backend)
624 (apply company-backend args)
625 (apply 'company--multi-backend-adapter company-backend args)))
626
627 (defun company--multi-backend-adapter (backends command &rest args)
628 (case command
629 ('candidates
630 (apply 'append (mapcar (lambda (backend) (apply backend command args))
631 backends)))
632 ('sorted nil)
633 ('duplicates t)
634 (otherwise
635 (let (value)
636 (dolist (backend backends)
637 (when (setq value (apply backend command args))
638 (return value)))))))
639
640 ;;; completion mechanism ;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;
641
642 (defvar company-backend nil)
643 (make-variable-buffer-local 'company-backend)
644
645 (defvar company-prefix nil)
646 (make-variable-buffer-local 'company-prefix)
647
648 (defvar company-candidates nil)
649 (make-variable-buffer-local 'company-candidates)
650
651 (defvar company-candidates-length nil)
652 (make-variable-buffer-local 'company-candidates-length)
653
654 (defvar company-candidates-cache nil)
655 (make-variable-buffer-local 'company-candidates-cache)
656
657 (defvar company-candidates-predicate nil)
658 (make-variable-buffer-local 'company-candidates-predicate)
659
660 (defvar company-common nil)
661 (make-variable-buffer-local 'company-common)
662
663 (defvar company-selection 0)
664 (make-variable-buffer-local 'company-selection)
665
666 (defvar company-selection-changed nil)
667 (make-variable-buffer-local 'company-selection-changed)
668
669 (defvar company--explicit-action nil
670 "Non-nil, if explicit completion took place.")
671 (make-variable-buffer-local 'company--explicit-action)
672
673 (defvar company--point-max nil)
674 (make-variable-buffer-local 'company--point-max)
675
676 (defvar company--this-command nil)
677
678 (defvar company-point nil)
679 (make-variable-buffer-local 'company-point)
680
681 (defvar company-timer nil)
682
683 (defvar company-added-newline nil)
684 (make-variable-buffer-local 'company-added-newline)
685
686 (defsubst company-strip-prefix (str)
687 (substring str (length company-prefix)))
688
689 (defun company-explicit-action-p ()
690 "Return whether explicit completion action was taken by the user."
691 (or company--explicit-action
692 company-selection-changed))
693
694 (defsubst company-reformat (candidate)
695 ;; company-ispell needs this, because the results are always lower-case
696 ;; It's mory efficient to fix it only when they are displayed.
697 (concat company-prefix (substring candidate (length company-prefix))))
698
699 (defun company--should-complete ()
700 (and (not (or buffer-read-only overriding-terminal-local-map
701 overriding-local-map))
702 (eq company-idle-delay t)
703 (or (eq t company-begin-commands)
704 (memq company--this-command company-begin-commands)
705 (and (symbolp this-command) (get this-command 'company-begin)))
706 (not (and transient-mark-mode mark-active))))
707
708 (defsubst company-call-frontends (command)
709 (dolist (frontend company-frontends)
710 (condition-case err
711 (funcall frontend command)
712 (error (error "Company: Front-end %s error \"%s\" on command %s"
713 frontend (error-message-string err) command)))))
714
715 (defsubst company-set-selection (selection &optional force-update)
716 (setq selection (max 0 (min (1- company-candidates-length) selection)))
717 (when (or force-update (not (equal selection company-selection)))
718 (setq company-selection selection
719 company-selection-changed t)
720 (company-call-frontends 'update)))
721
722 (defun company-apply-predicate (candidates predicate)
723 (let (new)
724 (dolist (c candidates)
725 (when (funcall predicate c)
726 (push c new)))
727 (nreverse new)))
728
729 (defun company-update-candidates (candidates)
730 (setq company-candidates-length (length candidates))
731 (if (> company-selection 0)
732 ;; Try to restore the selection
733 (let ((selected (nth company-selection company-candidates)))
734 (setq company-selection 0
735 company-candidates candidates)
736 (when selected
737 (while (and candidates (string< (pop candidates) selected))
738 (incf company-selection))
739 (unless candidates
740 ;; Make sure selection isn't out of bounds.
741 (setq company-selection (min (1- company-candidates-length)
742 company-selection)))))
743 (setq company-selection 0
744 company-candidates candidates))
745 ;; Save in cache:
746 (push (cons company-prefix company-candidates) company-candidates-cache)
747 ;; Calculate common.
748 (let ((completion-ignore-case (company-call-backend 'ignore-case)))
749 (setq company-common (try-completion company-prefix company-candidates)))
750 (when (eq company-common t)
751 (setq company-candidates nil)))
752
753 (defun company-calculate-candidates (prefix)
754 (let ((candidates
755 (or (cdr (assoc prefix company-candidates-cache))
756 (when company-candidates-cache
757 (let ((len (length prefix))
758 (completion-ignore-case (company-call-backend
759 'ignore-case))
760 prev)
761 (dotimes (i (1+ len))
762 (when (setq prev (cdr (assoc (substring prefix 0 (- len i))
763 company-candidates-cache)))
764 (return (all-completions prefix prev))))))
765 (let ((c (company-call-backend 'candidates prefix)))
766 (when company-candidates-predicate
767 (setq c (company-apply-predicate
768 c company-candidates-predicate)))
769 (unless (company-call-backend 'sorted)
770 (setq c (sort c 'string<)))
771 (when (company-call-backend 'duplicates)
772 ;; strip duplicates
773 (let ((c2 c))
774 (while c2
775 (setcdr c2 (progn (while (equal (pop c2) (car c2)))
776 c2)))))
777 c))))
778 (if (or (cdr candidates)
779 (not (equal (car candidates) prefix)))
780 ;; Don't start when already completed and unique.
781 candidates
782 ;; Not the right place? maybe when setting?
783 (and company-candidates t))))
784
785 (defun company-idle-begin (buf win tick pos)
786 (and company-mode
787 (eq buf (current-buffer))
788 (eq win (selected-window))
789 (eq tick (buffer-chars-modified-tick))
790 (eq pos (point))
791 (not company-candidates)
792 (not (equal (point) company-point))
793 (let ((company-idle-delay t))
794 (company-begin)
795 (when company-candidates
796 (company-input-noop)
797 (company-post-command)))))
798
799 (defun company-manual-begin ()
800 (interactive)
801 (company-assert-enabled)
802 (and company-mode
803 (not company-candidates)
804 (let ((company-idle-delay t)
805 (company-minimum-prefix-length 0)
806 (company-begin-commands t))
807 (setq company--explicit-action t)
808 (company-begin)))
809 ;; Return non-nil if active.
810 company-candidates)
811
812 (defun company-require-match-p ()
813 (let ((backend-value (company-call-backend 'require-match)))
814 (or (eq backend-value t)
815 (and (if (functionp company-require-match)
816 (funcall company-require-match)
817 (eq company-require-match t))
818 (not (eq backend-value 'never))))))
819
820 (defun company-punctuation-p (input)
821 "Return non-nil, if input starts with punctuation or parentheses."
822 (memq (char-syntax (string-to-char input)) '(?. ?\( ?\))))
823
824 (defun company-auto-complete-p (input)
825 "Return non-nil, if input starts with punctuation or parentheses."
826 (and (if (functionp company-auto-complete)
827 (funcall company-auto-complete)
828 company-auto-complete)
829 (if (functionp company-auto-complete-chars)
830 (funcall company-auto-complete-chars input)
831 (if (consp company-auto-complete-chars)
832 (memq (char-syntax (string-to-char input))
833 company-auto-complete-chars)
834 (string-match (substring input 0 1) company-auto-complete-chars)))))
835
836 (defun company--incremental-p ()
837 (and (> (point) company-point)
838 (> (point-max) company--point-max)
839 (not (eq this-command 'backward-delete-char-untabify))
840 (equal (buffer-substring (- company-point (length company-prefix))
841 company-point)
842 company-prefix)))
843
844 (defsubst company--string-incremental-p (old-prefix new-prefix)
845 (and (> (length new-prefix) (length old-prefix))
846 (equal old-prefix (substring new-prefix 0 (length old-prefix)))))
847
848 (defun company--continue-failed (new-prefix)
849 (when (company--incremental-p)
850 (let ((input (buffer-substring-no-properties (point) company-point)))
851 (cond
852 ((company-auto-complete-p input)
853 ;; auto-complete
854 (save-excursion
855 (goto-char company-point)
856 (company-complete-selection)
857 nil))
858 ((and (company--string-incremental-p company-prefix new-prefix)
859 (company-require-match-p))
860 ;; wrong incremental input, but required match
861 (backward-delete-char (length input))
862 (ding)
863 (message "Matching input is required")
864 company-candidates)
865 ((equal company-prefix (car company-candidates))
866 ;; last input was actually success
867 (company-cancel company-prefix)
868 nil)))))
869
870 (defun company--continue ()
871 (when (company-call-backend 'no-cache company-prefix)
872 ;; Don't complete existing candidates, fetch new ones.
873 (setq company-candidates-cache nil))
874 (let* ((new-prefix (company-call-backend 'prefix))
875 (c (when (and (stringp new-prefix)
876 (or (company-explicit-action-p)
877 (>= (length new-prefix)
878 company-minimum-prefix-length))
879 (= (- (point) (length new-prefix))
880 (- company-point (length company-prefix))))
881 (company-calculate-candidates new-prefix))))
882 (cond
883 ((eq c t)
884 ;; t means complete/unique.
885 (company-cancel new-prefix)
886 nil)
887 ((consp c)
888 ;; incremental match
889 (setq company-prefix new-prefix)
890 (company-update-candidates c)
891 c)
892 (t (company--continue-failed new-prefix)))))
893
894 (defun company--begin-new ()
895 (let (prefix c)
896 (dolist (backend (if company-backend
897 ;; prefer manual override
898 (list company-backend)
899 company-backends))
900 (setq prefix
901 (if (or (symbolp backend)
902 (functionp backend))
903 (when (or (not (symbolp backend))
904 (get backend 'company-init))
905 (funcall backend 'prefix))
906 (company--multi-backend-adapter backend 'prefix)))
907 (when prefix
908 (when (and (stringp prefix)
909 (>= (length prefix) company-minimum-prefix-length))
910 (setq company-backend backend
911 company-prefix prefix
912 c (company-calculate-candidates prefix))
913 ;; t means complete/unique. We don't start, so no hooks.
914 (when (consp c)
915 (company-update-candidates c)
916 (run-hook-with-args 'company-completion-started-hook
917 (company-explicit-action-p))
918 (company-call-frontends 'show)))
919 (return c)))))
920
921 (defun company-begin ()
922 (setq company-candidates
923 (or (and company-candidates (company--continue))
924 (and (company--should-complete) (company--begin-new))))
925 (if company-candidates
926 (progn
927 (when (and company-end-of-buffer-workaround (eobp))
928 (save-excursion (insert "\n"))
929 (setq company-added-newline (buffer-chars-modified-tick)))
930 (setq company-point (point)
931 company--point-max (point-max))
932 (company-enable-overriding-keymap company-active-map)
933 (company-call-frontends 'update))
934 (company-cancel)))
935
936 (defun company-cancel (&optional result)
937 (and company-added-newline
938 (> (point-max) (point-min))
939 (let ((tick (buffer-chars-modified-tick)))
940 (delete-region (1- (point-max)) (point-max))
941 (equal tick company-added-newline))
942 ;; Only set unmodified when tick remained the same since insert.
943 (set-buffer-modified-p nil))
944 (when company-prefix
945 (if (stringp result)
946 (run-hook-with-args 'company-completion-finished-hook result)
947 (run-hook-with-args 'company-completion-cancelled-hook result)))
948 (setq company-added-newline nil
949 company-backend nil
950 company-prefix nil
951 company-candidates nil
952 company-candidates-length nil
953 company-candidates-cache nil
954 company-candidates-predicate nil
955 company-common nil
956 company-selection 0
957 company-selection-changed nil
958 company--explicit-action nil
959 company--point-max nil
960 company-point nil)
961 (when company-timer
962 (cancel-timer company-timer))
963 (company-search-mode 0)
964 (company-call-frontends 'hide)
965 (company-enable-overriding-keymap nil))
966
967 (defun company-abort ()
968 (interactive)
969 (company-cancel t)
970 ;; Don't start again, unless started manually.
971 (setq company-point (point)))
972
973 (defun company-finish (result)
974 (insert (company-strip-prefix result))
975 (company-cancel result)
976 ;; Don't start again, unless started manually.
977 (setq company-point (point)))
978
979 (defsubst company-keep (command)
980 (and (symbolp command) (get command 'company-keep)))
981
982 (defun company-pre-command ()
983 (unless (company-keep this-command)
984 (condition-case err
985 (when company-candidates
986 (company-call-frontends 'pre-command))
987 (error (message "Company: An error occurred in pre-command")
988 (message "%s" (error-message-string err))
989 (company-cancel))))
990 (when company-timer
991 (cancel-timer company-timer))
992 (company-uninstall-map))
993
994 (defun company-post-command ()
995 (unless (company-keep this-command)
996 (condition-case err
997 (progn
998 (setq company--this-command this-command)
999 (unless (equal (point) company-point)
1000 (company-begin))
1001 (when company-candidates
1002 (company-call-frontends 'post-command))
1003 (when (numberp company-idle-delay)
1004 (setq company-timer
1005 (run-with-timer company-idle-delay nil 'company-idle-begin
1006 (current-buffer) (selected-window)
1007 (buffer-chars-modified-tick) (point)))))
1008 (error (message "Company: An error occurred in post-command")
1009 (message "%s" (error-message-string err))
1010 (company-cancel))))
1011 (company-install-map))
1012
1013 ;;; search ;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;
1014
1015 (defvar company-search-string nil)
1016 (make-variable-buffer-local 'company-search-string)
1017
1018 (defvar company-search-lighter " Search: \"\"")
1019 (make-variable-buffer-local 'company-search-lighter)
1020
1021 (defvar company-search-old-map nil)
1022 (make-variable-buffer-local 'company-search-old-map)
1023
1024 (defvar company-search-old-selection 0)
1025 (make-variable-buffer-local 'company-search-old-selection)
1026
1027 (defun company-search (text lines)
1028 (let ((quoted (regexp-quote text))
1029 (i 0))
1030 (dolist (line lines)
1031 (when (string-match quoted line (length company-prefix))
1032 (return i))
1033 (incf i))))
1034
1035 (defun company-search-printing-char ()
1036 (interactive)
1037 (company-search-assert-enabled)
1038 (setq company-search-string
1039 (concat (or company-search-string "") (string last-command-event))
1040 company-search-lighter (concat " Search: \"" company-search-string
1041 "\""))
1042 (let ((pos (company-search company-search-string
1043 (nthcdr company-selection company-candidates))))
1044 (if (null pos)
1045 (ding)
1046 (company-set-selection (+ company-selection pos) t))))
1047
1048 (defun company-search-repeat-forward ()
1049 "Repeat the incremental search in completion candidates forward."
1050 (interactive)
1051 (company-search-assert-enabled)
1052 (let ((pos (company-search company-search-string
1053 (cdr (nthcdr company-selection
1054 company-candidates)))))
1055 (if (null pos)
1056 (ding)
1057 (company-set-selection (+ company-selection pos 1) t))))
1058
1059 (defun company-search-repeat-backward ()
1060 "Repeat the incremental search in completion candidates backwards."
1061 (interactive)
1062 (company-search-assert-enabled)
1063 (let ((pos (company-search company-search-string
1064 (nthcdr (- company-candidates-length
1065 company-selection)
1066 (reverse company-candidates)))))
1067 (if (null pos)
1068 (ding)
1069 (company-set-selection (- company-selection pos 1) t))))
1070
1071 (defun company-create-match-predicate ()
1072 (setq company-candidates-predicate
1073 `(lambda (candidate)
1074 ,(if company-candidates-predicate
1075 `(and (string-match ,company-search-string candidate)
1076 (funcall ,company-candidates-predicate
1077 candidate))
1078 `(string-match ,company-search-string candidate))))
1079 (company-update-candidates
1080 (company-apply-predicate company-candidates company-candidates-predicate))
1081 ;; Invalidate cache.
1082 (setq company-candidates-cache (cons company-prefix company-candidates)))
1083
1084 (defun company-filter-printing-char ()
1085 (interactive)
1086 (company-search-assert-enabled)
1087 (company-search-printing-char)
1088 (company-create-match-predicate)
1089 (company-call-frontends 'update))
1090
1091 (defun company-search-kill-others ()
1092 "Limit the completion candidates to the ones matching the search string."
1093 (interactive)
1094 (company-search-assert-enabled)
1095 (company-create-match-predicate)
1096 (company-search-mode 0)
1097 (company-call-frontends 'update))
1098
1099 (defun company-search-abort ()
1100 "Abort searching the completion candidates."
1101 (interactive)
1102 (company-search-assert-enabled)
1103 (company-set-selection company-search-old-selection t)
1104 (company-search-mode 0))
1105
1106 (defun company-search-other-char ()
1107 (interactive)
1108 (company-search-assert-enabled)
1109 (company-search-mode 0)
1110 (when last-input-event
1111 (clear-this-command-keys t)
1112 (setq unread-command-events (list last-input-event))))
1113
1114 (defvar company-search-map
1115 (let ((i 0)
1116 (keymap (make-keymap)))
1117 (if (fboundp 'max-char)
1118 (set-char-table-range (nth 1 keymap) (cons #x100 (max-char))
1119 'company-search-printing-char)
1120 (with-no-warnings
1121 ;; obselete in Emacs 23
1122 (let ((l (generic-character-list))
1123 (table (nth 1 keymap)))
1124 (while l
1125 (set-char-table-default table (car l) 'company-search-printing-char)
1126 (setq l (cdr l))))))
1127 (define-key keymap [t] 'company-search-other-char)
1128 (while (< i ?\s)
1129 (define-key keymap (make-string 1 i) 'company-search-other-char)
1130 (incf i))
1131 (while (< i 256)
1132 (define-key keymap (vector i) 'company-search-printing-char)
1133 (incf i))
1134 (let ((meta-map (make-sparse-keymap)))
1135 (define-key keymap (char-to-string meta-prefix-char) meta-map)
1136 (define-key keymap [escape] meta-map))
1137 (define-key keymap (vector meta-prefix-char t) 'company-search-other-char)
1138 (define-key keymap "\e\e\e" 'company-search-other-char)
1139 (define-key keymap [escape escape escape] 'company-search-other-char)
1140
1141 (define-key keymap "\C-g" 'company-search-abort)
1142 (define-key keymap "\C-s" 'company-search-repeat-forward)
1143 (define-key keymap "\C-r" 'company-search-repeat-backward)
1144 (define-key keymap "\C-o" 'company-search-kill-others)
1145 keymap)
1146 "Keymap used for incrementally searching the completion candidates.")
1147
1148 (define-minor-mode company-search-mode
1149 "Search mode for completion candidates.
1150 Don't start this directly, use `company-search-candidates' or
1151 `company-filter-candidates'."
1152 nil company-search-lighter nil
1153 (if company-search-mode
1154 (if (company-manual-begin)
1155 (progn
1156 (setq company-search-old-selection company-selection)
1157 (company-call-frontends 'update))
1158 (setq company-search-mode nil))
1159 (kill-local-variable 'company-search-string)
1160 (kill-local-variable 'company-search-lighter)
1161 (kill-local-variable 'company-search-old-selection)
1162 (company-enable-overriding-keymap company-active-map)))
1163
1164 (defsubst company-search-assert-enabled ()
1165 (company-assert-enabled)
1166 (unless company-search-mode
1167 (company-uninstall-map)
1168 (error "Company not in search mode")))
1169
1170 (defun company-search-candidates ()
1171 "Start searching the completion candidates incrementally.
1172
1173 \\<company-search-map>Search can be controlled with the commands:
1174 - `company-search-repeat-forward' (\\[company-search-repeat-forward])
1175 - `company-search-repeat-backward' (\\[company-search-repeat-backward])
1176 - `company-search-abort' (\\[company-search-abort])
1177
1178 Regular characters are appended to the search string.
1179
1180 The command `company-search-kill-others' (\\[company-search-kill-others]) uses
1181 the search string to limit the completion candidates."
1182 (interactive)
1183 (company-search-mode 1)
1184 (company-enable-overriding-keymap company-search-map))
1185
1186 (defvar company-filter-map
1187 (let ((keymap (make-keymap)))
1188 (define-key keymap [remap company-search-printing-char]
1189 'company-filter-printing-char)
1190 (set-keymap-parent keymap company-search-map)
1191 keymap)
1192 "Keymap used for incrementally searching the completion candidates.")
1193
1194 (defun company-filter-candidates ()
1195 "Start filtering the completion candidates incrementally.
1196 This works the same way as `company-search-candidates' immediately
1197 followed by `company-search-kill-others' after each input."
1198 (interactive)
1199 (company-search-mode 1)
1200 (company-enable-overriding-keymap company-filter-map))
1201
1202 ;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;
1203
1204 (defun company-select-next ()
1205 "Select the next candidate in the list."
1206 (interactive)
1207 (when (company-manual-begin)
1208 (company-set-selection (1+ company-selection))))
1209
1210 (defun company-select-previous ()
1211 "Select the previous candidate in the list."
1212 (interactive)
1213 (when (company-manual-begin)
1214 (company-set-selection (1- company-selection))))
1215
1216 (defun company-select-mouse (event)
1217 "Select the candidate picked by the mouse."
1218 (interactive "e")
1219 (when (nth 4 (event-start event))
1220 (company-set-selection (- (cdr (posn-actual-col-row (event-start event)))
1221 (company--row)
1222 1))
1223 t))
1224
1225 (defun company-complete-mouse (event)
1226 "Complete the candidate picked by the mouse."
1227 (interactive "e")
1228 (when (company-select-mouse event)
1229 (company-complete-selection)))
1230
1231 (defun company-complete-selection ()
1232 "Complete the selected candidate."
1233 (interactive)
1234 (when (company-manual-begin)
1235 (company-finish (nth company-selection company-candidates))))
1236
1237 (defun company-complete-common ()
1238 "Complete the common part of all candidates."
1239 (interactive)
1240 (when (company-manual-begin)
1241 (if (and (not (cdr company-candidates))
1242 (equal company-common (car company-candidates)))
1243 (company-complete-selection)
1244 (insert (company-strip-prefix company-common)))))
1245
1246 (defun company-complete ()
1247 "Complete the common part of all candidates or the current selection.
1248 The first time this is called, the common part is completed, the second time, or
1249 when the selection has been changed, the selected candidate is completed."
1250 (interactive)
1251 (when (company-manual-begin)
1252 (if (or company-selection-changed
1253 (eq last-command 'company-complete-common))
1254 (call-interactively 'company-complete-selection)
1255 (call-interactively 'company-complete-common)
1256 (setq this-command 'company-complete-common))))
1257
1258 (defun company-complete-number (n)
1259 "Complete the Nth candidate.
1260 To show the number next to the candidates in some back-ends, enable
1261 `company-show-numbers'."
1262 (when (company-manual-begin)
1263 (and (< n 1) (> n company-candidates-length)
1264 (error "No candidate number %d" n))
1265 (decf n)
1266 (company-finish (nth n company-candidates))))
1267
1268 ;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;
1269
1270 (defconst company-space-strings-limit 100)
1271
1272 (defconst company-space-strings
1273 (let (lst)
1274 (dotimes (i company-space-strings-limit)
1275 (push (make-string (- company-space-strings-limit 1 i) ?\ ) lst))
1276 (apply 'vector lst)))
1277
1278 (defsubst company-space-string (len)
1279 (if (< len company-space-strings-limit)
1280 (aref company-space-strings len)
1281 (make-string len ?\ )))
1282
1283 (defsubst company-safe-substring (str from &optional to)
1284 (let ((len (length str)))
1285 (if (> from len)
1286 ""
1287 (if (and to (> to len))
1288 (concat (substring str from)
1289 (company-space-string (- to len)))
1290 (substring str from to)))))
1291
1292 ;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;
1293
1294 (defvar company-last-metadata nil)
1295 (make-variable-buffer-local 'company-last-metadata)
1296
1297 (defun company-fetch-metadata ()
1298 (let ((selected (nth company-selection company-candidates)))
1299 (unless (equal selected (car company-last-metadata))
1300 (setq company-last-metadata
1301 (cons selected (company-call-backend 'meta selected))))
1302 (cdr company-last-metadata)))
1303
1304 (defun company-doc-buffer (&optional string)
1305 (with-current-buffer (get-buffer-create "*Company meta-data*")
1306 (erase-buffer)
1307 (current-buffer)))
1308
1309 (defmacro company-electric (&rest body)
1310 (declare (indent 0) (debug t))
1311 `(when (company-manual-begin)
1312 (save-window-excursion
1313 (let ((height (window-height))
1314 (row (company--row)))
1315 ,@body
1316 (and (< (window-height) height)
1317 (< (- (window-height) row 2) company-tooltip-limit)
1318 (recenter (- (window-height) row 2)))
1319 (while (eq 'scroll-other-window
1320 (key-binding (vector (list (read-event)))))
1321 (call-interactively 'scroll-other-window))
1322 (when last-input-event
1323 (clear-this-command-keys t)
1324 (setq unread-command-events (list last-input-event)))))))
1325
1326 (defun company-show-doc-buffer ()
1327 "Temporarily show a buffer with the complete documentation for the selection."
1328 (interactive)
1329 (company-electric
1330 (let ((selected (nth company-selection company-candidates)))
1331 (display-buffer (or (company-call-backend 'doc-buffer selected)
1332 (error "No documentation available")) t))))
1333 (put 'company-show-doc-buffer 'company-keep t)
1334
1335 (defun company-show-location ()
1336 "Temporarily display a buffer showing the selected candidate in context."
1337 (interactive)
1338 (company-electric
1339 (let* ((selected (nth company-selection company-candidates))
1340 (location (company-call-backend 'location selected))
1341 (pos (or (cdr location) (error "No location available")))
1342 (buffer (or (and (bufferp (car location)) (car location))
1343 (find-file-noselect (car location) t))))
1344 (with-selected-window (display-buffer buffer t)
1345 (if (bufferp (car location))
1346 (goto-char pos)
1347 (goto-line pos))
1348 (set-window-start nil (point))))))
1349 (put 'company-show-location 'company-keep t)
1350
1351 ;;; package functions ;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;
1352
1353 (defvar company-callback nil)
1354 (make-variable-buffer-local 'company-callback)
1355
1356 (defvar company-begin-with-marker nil)
1357 (make-variable-buffer-local 'company-begin-with-marker)
1358
1359 (defun company-remove-callback (&optional ignored)
1360 (remove-hook 'company-completion-finished-hook company-callback t)
1361 (remove-hook 'company-completion-cancelled-hook 'company-remove-callback t)
1362 (remove-hook 'company-completion-finished-hook 'company-remove-callback t)
1363 (set-marker company-begin-with-marker nil))
1364
1365 (defun company-begin-backend (backend &optional callback)
1366 "Start a completion at point using BACKEND."
1367 (interactive (let ((val (completing-read "Company back-end: "
1368 obarray
1369 'functionp nil "company-")))
1370 (when val
1371 (list (intern val)))))
1372 (when (setq company-callback callback)
1373 (add-hook 'company-completion-finished-hook company-callback nil t))
1374 (add-hook 'company-completion-cancelled-hook 'company-remove-callback nil t)
1375 (add-hook 'company-completion-finished-hook 'company-remove-callback nil t)
1376 (setq company-backend backend)
1377 ;; Return non-nil if active.
1378 (or (company-manual-begin)
1379 (error "Cannot complete at point")))
1380
1381 (defun company-begin-with (candidates
1382 &optional prefix-length require-match callback)
1383 "Start a completion at point.
1384 CANDIDATES is the list of candidates to use and PREFIX-LENGTH is the length of
1385 the prefix that already is in the buffer before point. It defaults to 0.
1386
1387 CALLBACK is a function called with the selected result if the user successfully
1388 completes the input.
1389
1390 Example:
1391 \(company-begin-with '\(\"foo\" \"foobar\" \"foobarbaz\"\)\)"
1392 (setq company-begin-with-marker (copy-marker (point) t))
1393 (company-begin-backend
1394 `(lambda (command &optional arg &rest ignored)
1395 (cond
1396 ((eq command 'prefix)
1397 (when (equal (point) (marker-position company-begin-with-marker))
1398 (buffer-substring ,(- (point) (or prefix-length 0)) (point))))
1399 ((eq command 'candidates)
1400 (all-completions arg ',candidates))
1401 ((eq command 'require-match)
1402 ,require-match)))
1403 callback))
1404
1405 ;;; pseudo-tooltip ;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;
1406
1407 (defvar company-pseudo-tooltip-overlay nil)
1408 (make-variable-buffer-local 'company-pseudo-tooltip-overlay)
1409
1410 (defvar company-tooltip-offset 0)
1411 (make-variable-buffer-local 'company-tooltip-offset)
1412
1413 (defun company-pseudo-tooltip-update-offset (selection num-lines limit)
1414
1415 (decf limit 2)
1416 (setq company-tooltip-offset
1417 (max (min selection company-tooltip-offset)
1418 (- selection -1 limit)))
1419
1420 (when (<= company-tooltip-offset 1)
1421 (incf limit)
1422 (setq company-tooltip-offset 0))
1423
1424 (when (>= company-tooltip-offset (- num-lines limit 1))
1425 (incf limit)
1426 (when (= selection (1- num-lines))
1427 (decf company-tooltip-offset)
1428 (when (<= company-tooltip-offset 1)
1429 (setq company-tooltip-offset 0)
1430 (incf limit))))
1431
1432 limit)
1433
1434 ;;; propertize
1435
1436 (defsubst company-round-tab (arg)
1437 (* (/ (+ arg tab-width) tab-width) tab-width))
1438
1439 (defun company-untabify (str)
1440 (let* ((pieces (split-string str "\t"))
1441 (copy pieces))
1442 (while (cdr copy)
1443 (setcar copy (company-safe-substring
1444 (car copy) 0 (company-round-tab (string-width (car copy)))))
1445 (pop copy))
1446 (apply 'concat pieces)))
1447
1448 (defun company-fill-propertize (line width selected)
1449 (setq line (company-safe-substring line 0 width))
1450 (add-text-properties 0 width '(face company-tooltip
1451 mouse-face company-tooltip-mouse)
1452 line)
1453 (add-text-properties 0 (length company-common)
1454 '(face company-tooltip-common
1455 mouse-face company-tooltip-mouse)
1456 line)
1457 (when selected
1458 (if (and company-search-string
1459 (string-match (regexp-quote company-search-string) line
1460 (length company-prefix)))
1461 (progn
1462 (add-text-properties (match-beginning 0) (match-end 0)
1463 '(face company-tooltip-selection)
1464 line)
1465 (when (< (match-beginning 0) (length company-common))
1466 (add-text-properties (match-beginning 0) (length company-common)
1467 '(face company-tooltip-common-selection)
1468 line)))
1469 (add-text-properties 0 width '(face company-tooltip-selection
1470 mouse-face company-tooltip-selection)
1471 line)
1472 (add-text-properties 0 (length company-common)
1473 '(face company-tooltip-common-selection
1474 mouse-face company-tooltip-selection)
1475 line)))
1476 line)
1477
1478 ;;; replace
1479
1480 (defun company-buffer-lines (beg end)
1481 (goto-char beg)
1482 (let ((row (company--row))
1483 lines)
1484 (while (and (equal (move-to-window-line (incf row)) row)
1485 (<= (point) end))
1486 (push (buffer-substring beg (min end (1- (point)))) lines)
1487 (setq beg (point)))
1488 (unless (eq beg end)
1489 (push (buffer-substring beg end) lines))
1490 (nreverse lines)))
1491
1492 (defsubst company-modify-line (old new offset)
1493 (concat (company-safe-substring old 0 offset)
1494 new
1495 (company-safe-substring old (+ offset (length new)))))
1496
1497 (defun company-replacement-string (old lines column nl)
1498 (let (new)
1499 ;; Inject into old lines.
1500 (while old
1501 (push (company-modify-line (pop old) (pop lines) column) new))
1502 ;; Append whole new lines.
1503 (while lines
1504 (push (concat (company-space-string column) (pop lines)) new))
1505 (concat (when nl "\n")
1506 (mapconcat 'identity (nreverse new) "\n")
1507 "\n")))
1508
1509 (defun company-create-lines (column selection limit)
1510
1511 (let ((len company-candidates-length)
1512 (numbered 99999)
1513 lines
1514 width
1515 lines-copy
1516 previous
1517 remainder
1518 new)
1519
1520 ;; Scroll to offset.
1521 (setq limit (company-pseudo-tooltip-update-offset selection len limit))
1522
1523 (when (> company-tooltip-offset 0)
1524 (setq previous (format "...(%d)" company-tooltip-offset)))
1525
1526 (setq remainder (- len limit company-tooltip-offset)
1527 remainder (when (> remainder 0)
1528 (setq remainder (format "...(%d)" remainder))))
1529
1530 (decf selection company-tooltip-offset)
1531 (setq width (max (length previous) (length remainder))
1532 lines (nthcdr company-tooltip-offset company-candidates)
1533 len (min limit len)
1534 lines-copy lines)
1535
1536 (dotimes (i len)
1537 (setq width (max (length (pop lines-copy)) width)))
1538 (setq width (min width (- (window-width) column)))
1539
1540 (setq lines-copy lines)
1541
1542 ;; number can make tooltip too long
1543 (when company-show-numbers
1544 (setq numbered company-tooltip-offset))
1545
1546 (when previous
1547 (push (propertize (company-safe-substring previous 0 width)
1548 'face 'company-tooltip)
1549 new))
1550
1551 (dotimes (i len)
1552 (push (company-fill-propertize
1553 (if (>= numbered 10)
1554 (company-reformat (pop lines))
1555 (incf numbered)
1556 (format "%s %d"
1557 (company-safe-substring (company-reformat (pop lines))
1558 0 (- width 2))
1559 (mod numbered 10)))
1560 width (equal i selection))
1561 new))
1562
1563 (when remainder
1564 (push (propertize (company-safe-substring remainder 0 width)
1565 'face 'company-tooltip)
1566 new))
1567
1568 (setq lines (nreverse new))))
1569
1570 ;; show
1571
1572 (defsubst company-pseudo-tooltip-height ()
1573 "Calculate the appropriate tooltip height."
1574 (max 3 (min company-tooltip-limit
1575 (- (window-height) 2
1576 (count-lines (window-start) (point-at-bol))))))
1577
1578 (defun company-pseudo-tooltip-show (row column selection)
1579 (company-pseudo-tooltip-hide)
1580 (save-excursion
1581
1582 (move-to-column 0)
1583
1584 (let* ((height (company-pseudo-tooltip-height))
1585 (lines (company-create-lines column selection height))
1586 (nl (< (move-to-window-line row) row))
1587 (beg (point))
1588 (end (save-excursion
1589 (move-to-window-line (+ row height))
1590 (point)))
1591 (old-string
1592 (mapcar 'company-untabify (company-buffer-lines beg end)))
1593 str)
1594
1595 (setq company-pseudo-tooltip-overlay (make-overlay beg end))
1596
1597 (overlay-put company-pseudo-tooltip-overlay 'company-old old-string)
1598 (overlay-put company-pseudo-tooltip-overlay 'company-column column)
1599 (overlay-put company-pseudo-tooltip-overlay 'company-nl nl)
1600 (overlay-put company-pseudo-tooltip-overlay 'company-before
1601 (company-replacement-string old-string lines column nl))
1602 (overlay-put company-pseudo-tooltip-overlay 'company-height height)
1603
1604 (overlay-put company-pseudo-tooltip-overlay 'window (selected-window)))))
1605
1606 (defun company-pseudo-tooltip-show-at-point (pos)
1607 (let ((col-row (company--col-row pos)))
1608 (when col-row
1609 (company-pseudo-tooltip-show (1+ (cdr col-row)) (car col-row)
1610 company-selection))))
1611
1612 (defun company-pseudo-tooltip-edit (lines selection)
1613 (let* ((old-string (overlay-get company-pseudo-tooltip-overlay 'company-old))
1614 (column (overlay-get company-pseudo-tooltip-overlay 'company-column))
1615 (nl (overlay-get company-pseudo-tooltip-overlay 'company-nl))
1616 (height (overlay-get company-pseudo-tooltip-overlay 'company-height))
1617 (lines (company-create-lines column selection height)))
1618 (overlay-put company-pseudo-tooltip-overlay 'company-before
1619 (company-replacement-string old-string lines column nl))))
1620
1621 (defun company-pseudo-tooltip-hide ()
1622 (when company-pseudo-tooltip-overlay
1623 (delete-overlay company-pseudo-tooltip-overlay)
1624 (setq company-pseudo-tooltip-overlay nil)))
1625
1626 (defun company-pseudo-tooltip-hide-temporarily ()
1627 (when (overlayp company-pseudo-tooltip-overlay)
1628 (overlay-put company-pseudo-tooltip-overlay 'invisible nil)
1629 (overlay-put company-pseudo-tooltip-overlay 'before-string nil)))
1630
1631 (defun company-pseudo-tooltip-unhide ()
1632 (when company-pseudo-tooltip-overlay
1633 (overlay-put company-pseudo-tooltip-overlay 'invisible t)
1634 (overlay-put company-pseudo-tooltip-overlay 'before-string
1635 (overlay-get company-pseudo-tooltip-overlay 'company-before))
1636 (overlay-put company-pseudo-tooltip-overlay 'window (selected-window))))
1637
1638 (defun company-pseudo-tooltip-frontend (command)
1639 "A `company-mode' front-end similar to a tool-tip but based on overlays."
1640 (case command
1641 ('pre-command (company-pseudo-tooltip-hide-temporarily))
1642 ('post-command
1643 (unless (and (overlayp company-pseudo-tooltip-overlay)
1644 (equal (overlay-get company-pseudo-tooltip-overlay
1645 'company-height)
1646 (company-pseudo-tooltip-height)))
1647 ;; Redraw needed.
1648 (company-pseudo-tooltip-show-at-point (- (point)
1649 (length company-prefix))))
1650 (company-pseudo-tooltip-unhide))
1651 ('hide (company-pseudo-tooltip-hide)
1652 (setq company-tooltip-offset 0))
1653 ('update (when (overlayp company-pseudo-tooltip-overlay)
1654 (company-pseudo-tooltip-edit company-candidates
1655 company-selection)))))
1656
1657 (defun company-pseudo-tooltip-unless-just-one-frontend (command)
1658 "`company-pseudo-tooltip-frontend', but not shown for single candidates."
1659 (unless (and (eq command 'post-command)
1660 (not (cdr company-candidates)))
1661 (company-pseudo-tooltip-frontend command)))
1662
1663 ;;; overlay ;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;
1664
1665 (defvar company-preview-overlay nil)
1666 (make-variable-buffer-local 'company-preview-overlay)
1667
1668 (defun company-preview-show-at-point (pos)
1669 (company-preview-hide)
1670
1671 (setq company-preview-overlay (make-overlay pos pos))
1672
1673 (let ((completion(nth company-selection company-candidates)))
1674 (setq completion (propertize completion 'face 'company-preview))
1675 (add-text-properties 0 (length company-common)
1676 '(face company-preview-common) completion)
1677
1678 ;; Add search string
1679 (and company-search-string
1680 (string-match (regexp-quote company-search-string) completion)
1681 (add-text-properties (match-beginning 0)
1682 (match-end 0)
1683 '(face company-preview-search)
1684 completion))
1685
1686 (setq completion (company-strip-prefix completion))
1687
1688 (and (equal pos (point))
1689 (not (equal completion ""))
1690 (add-text-properties 0 1 '(cursor t) completion))
1691
1692 (overlay-put company-preview-overlay 'after-string completion)
1693 (overlay-put company-preview-overlay 'window (selected-window))))
1694
1695 (defun company-preview-hide ()
1696 (when company-preview-overlay
1697 (delete-overlay company-preview-overlay)
1698 (setq company-preview-overlay nil)))
1699
1700 (defun company-preview-frontend (command)
1701 "A `company-mode' front-end showing the selection as if it had been inserted."
1702 (case command
1703 ('pre-command (company-preview-hide))
1704 ('post-command (company-preview-show-at-point (point)))
1705 ('hide (company-preview-hide))))
1706
1707 (defun company-preview-if-just-one-frontend (command)
1708 "`company-preview-frontend', but only shown for single candidates."
1709 (unless (and (eq command 'post-command)
1710 (cdr company-candidates))
1711 (company-preview-frontend command)))
1712
1713 ;;; echo ;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;
1714
1715 (defvar company-echo-last-msg nil)
1716 (make-variable-buffer-local 'company-echo-last-msg)
1717
1718 (defvar company-echo-timer nil)
1719
1720 (defvar company-echo-delay .1)
1721
1722 (defun company-echo-show (&optional getter)
1723 (when getter
1724 (setq company-echo-last-msg (funcall getter)))
1725 (let ((message-log-max nil))
1726 (if company-echo-last-msg
1727 (message "%s" company-echo-last-msg)
1728 (message ""))))
1729
1730 (defsubst company-echo-show-soon (&optional getter)
1731 (when company-echo-timer
1732 (cancel-timer company-echo-timer))
1733 (setq company-echo-timer (run-with-timer company-echo-delay nil
1734 'company-echo-show getter)))
1735
1736 (defun company-echo-format ()
1737
1738 (let ((limit (window-width (minibuffer-window)))
1739 (len -1)
1740 ;; Roll to selection.
1741 (candidates (nthcdr company-selection company-candidates))
1742 (i (if company-show-numbers company-selection 99999))
1743 comp msg)
1744
1745 (while candidates
1746 (setq comp (company-reformat (pop candidates))
1747 len (+ len 1 (length comp)))
1748 (if (< i 10)
1749 ;; Add number.
1750 (progn
1751 (setq comp (propertize (format "%d: %s" i comp)
1752 'face 'company-echo))
1753 (incf len 3)
1754 (incf i)
1755 (add-text-properties 3 (+ 3 (length company-common))
1756 '(face company-echo-common) comp))
1757 (setq comp (propertize comp 'face 'company-echo))
1758 (add-text-properties 0 (length company-common)
1759 '(face company-echo-common) comp))
1760 (if (>= len limit)
1761 (setq candidates nil)
1762 (push comp msg)))
1763
1764 (mapconcat 'identity (nreverse msg) " ")))
1765
1766 (defun company-echo-strip-common-format ()
1767
1768 (let ((limit (window-width (minibuffer-window)))
1769 (len (+ (length company-prefix) 2))
1770 ;; Roll to selection.
1771 (candidates (nthcdr company-selection company-candidates))
1772 (i (if company-show-numbers company-selection 99999))
1773 msg comp)
1774
1775 (while candidates
1776 (setq comp (company-strip-prefix (pop candidates))
1777 len (+ len 2 (length comp)))
1778 (when (< i 10)
1779 ;; Add number.
1780 (setq comp (format "%s (%d)" comp i))
1781 (incf len 4)
1782 (incf i))
1783 (if (>= len limit)
1784 (setq candidates nil)
1785 (push (propertize comp 'face 'company-echo) msg)))
1786
1787 (concat (propertize company-prefix 'face 'company-echo-common) "{"
1788 (mapconcat 'identity (nreverse msg) ", ")
1789 "}")))
1790
1791 (defun company-echo-hide ()
1792 (when company-echo-timer
1793 (cancel-timer company-echo-timer))
1794 (unless (equal company-echo-last-msg "")
1795 (setq company-echo-last-msg "")
1796 (company-echo-show)))
1797
1798 (defun company-echo-frontend (command)
1799 "A `company-mode' front-end showing the candidates in the echo area."
1800 (case command
1801 ('pre-command (company-echo-show-soon))
1802 ('post-command (company-echo-show-soon 'company-echo-format))
1803 ('hide (company-echo-hide))))
1804
1805 (defun company-echo-strip-common-frontend (command)
1806 "A `company-mode' front-end showing the candidates in the echo area."
1807 (case command
1808 ('pre-command (company-echo-show-soon))
1809 ('post-command (company-echo-show-soon 'company-echo-strip-common-format))
1810 ('hide (company-echo-hide))))
1811
1812 (defun company-echo-metadata-frontend (command)
1813 "A `company-mode' front-end showing the documentation in the echo area."
1814 (case command
1815 ('pre-command (company-echo-show-soon))
1816 ('post-command (company-echo-show-soon 'company-fetch-metadata))
1817 ('hide (company-echo-hide))))
1818
1819 (provide 'company)
1820 ;;; company.el ends here