1 ;;; company.el --- Modular in-buffer completion framework
3 ;; Copyright (C) 2009-2013 Free Software Foundation, Inc.
5 ;; Author: Nikolaj Schumacher
6 ;; Maintainer: Dmitry Gutov <dgutov@yandex.ru>
8 ;; Keywords: abbrev, convenience, matching
9 ;; URL: http://company-mode.github.com/
10 ;; Compatibility: GNU Emacs 22.x, GNU Emacs 23.x, GNU Emacs 24.x
12 ;; This file is part of GNU Emacs.
14 ;; GNU Emacs is free software: you can redistribute it and/or modify
15 ;; it under the terms of the GNU General Public License as published by
16 ;; the Free Software Foundation, either version 3 of the License, or
17 ;; (at your option) any later version.
19 ;; GNU Emacs is distributed in the hope that it will be useful,
20 ;; but WITHOUT ANY WARRANTY; without even the implied warranty of
21 ;; MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
22 ;; GNU General Public License for more details.
24 ;; You should have received a copy of the GNU General Public License
25 ;; along with GNU Emacs. If not, see <http://www.gnu.org/licenses/>.
29 ;; Company is a modular completion mechanism. Modules for retrieving completion
30 ;; candidates are called back-ends, modules for displaying them are front-ends.
32 ;; Company comes with many back-ends, e.g. `company-elisp'. These are
33 ;; distributed in separate files and can be used individually.
35 ;; Place company.el and the back-ends you want to use in a directory and add the
36 ;; following to your .emacs:
37 ;; (add-to-list 'load-path "/path/to/company")
38 ;; (autoload 'company-mode "company" nil t)
40 ;; Enable company-mode with M-x company-mode. For further information look at
41 ;; the documentation for `company-mode' (C-h f company-mode RET)
43 ;; If you want to start a specific back-end, call it interactively or use
44 ;; `company-begin-backend'. For example:
45 ;; M-x company-abbrev will prompt for and insert an abbrev.
47 ;; To write your own back-end, look at the documentation for `company-backends'.
48 ;; Here is a simple example completing "foo":
50 ;; (defun company-my-backend (command &optional arg &rest ignored)
52 ;; (prefix (when (looking-back "foo\\>")
54 ;; (candidates (list "foobar" "foobaz" "foobarbaz"))
55 ;; (meta (format "This value is named %s" arg))))
57 ;; Sometimes it is a good idea to mix several back-ends together, for example to
58 ;; enrich gtags with dabbrev-code results (to emulate local variables).
59 ;; To do this, add a list with both back-ends as an element in company-backends.
62 ;; When point is at the very end of the buffer, the pseudo-tooltip appears very
63 ;; wrong, unless company is allowed to temporarily insert a fake newline.
64 ;; This behavior is enabled by `company-end-of-buffer-workaround'.
68 ;; See NEWS.md in the repository.
72 (eval-when-compile (require 'cl))
74 (add-to-list 'debug-ignored-errors "^.* frontend cannot be used twice$")
75 (add-to-list 'debug-ignored-errors "^Echo area cannot be used twice$")
76 (add-to-list 'debug-ignored-errors "^No \\(document\\|loc\\)ation available$")
77 (add-to-list 'debug-ignored-errors "^Company not ")
78 (add-to-list 'debug-ignored-errors "^No candidate number ")
79 (add-to-list 'debug-ignored-errors "^Cannot complete at point$")
80 (add-to-list 'debug-ignored-errors "^No other back-end$")
83 "Extensible inline text completion mechanism"
88 (defface company-tooltip
89 '((default :foreground "black")
90 (((class color) (min-colors 88) (background light))
91 (:background "cornsilk"))
92 (((class color) (min-colors 88) (background dark))
93 (:background "yellow")))
94 "Face used for the tool tip."
97 (defface company-tooltip-selection
98 '((default :inherit company-tooltip)
99 (((class color) (min-colors 88) (background light))
100 (:background "light blue"))
101 (((class color) (min-colors 88) (background dark))
102 (:background "orange1"))
103 (t (:background "green")))
104 "Face used for the selection in the tool tip."
107 (defface company-tooltip-mouse
108 '((default :inherit highlight))
109 "Face used for the tool tip item under the mouse."
112 (defface company-tooltip-common
113 '((default :inherit company-tooltip)
114 (((background light))
115 :foreground "darkred")
118 "Face used for the common completion in the tool tip."
121 (defface company-tooltip-common-selection
122 '((default :inherit company-tooltip-selection)
123 (((background light))
124 :foreground "darkred")
127 "Face used for the selected common completion in the tool tip."
130 (defface company-preview
131 '((t :background "blue4"
132 :foreground "wheat"))
133 "Face used for the completion preview."
136 (defface company-preview-common
137 '((t :inherit company-preview
139 "Face used for the common part of the completion preview."
142 (defface company-preview-search
143 '((t :inherit company-preview
144 :background "blue1"))
145 "Face used for the search string in the completion preview."
148 (defface company-echo nil
149 "Face used for completions in the echo area."
152 (defface company-echo-common
153 '((((background dark)) (:foreground "firebrick1"))
154 (((background light)) (:background "firebrick4")))
155 "Face used for the common part of completions in the echo area."
158 (defun company-frontends-set (variable value)
160 (let ((remainder value))
161 (setcdr remainder (delq (car remainder) (cdr remainder))))
162 (and (memq 'company-pseudo-tooltip-unless-just-one-frontend value)
163 (memq 'company-pseudo-tooltip-frontend value)
164 (error "Pseudo tooltip frontend cannot be used twice"))
165 (and (memq 'company-preview-if-just-one-frontend value)
166 (memq 'company-preview-frontend value)
167 (error "Preview frontend cannot be used twice"))
168 (and (memq 'company-echo value)
169 (memq 'company-echo-metadata-frontend value)
170 (error "Echo area cannot be used twice"))
171 ;; preview must come last
172 (dolist (f '(company-preview-if-just-one-frontend company-preview-frontend))
174 (setq value (append (delq f value) (list f)))))
175 (set variable value))
177 (defcustom company-frontends '(company-pseudo-tooltip-unless-just-one-frontend
178 company-preview-if-just-one-frontend
179 company-echo-metadata-frontend)
180 "The list of active front-ends (visualizations).
181 Each front-end is a function that takes one argument. It is called with
182 one of the following arguments:
184 'show: When the visualization should start.
186 'hide: When the visualization should end.
188 'update: When the data has been updated.
190 'pre-command: Before every command that is executed while the
191 visualization is active.
193 'post-command: After every command that is executed while the
194 visualization is active.
196 The visualized data is stored in `company-prefix', `company-candidates',
197 `company-common', `company-selection', `company-point' and
198 `company-search-string'."
199 :set 'company-frontends-set
201 :type '(repeat (choice (const :tag "echo" company-echo-frontend)
202 (const :tag "echo, strip common"
203 company-echo-strip-common-frontend)
204 (const :tag "show echo meta-data in echo"
205 company-echo-metadata-frontend)
206 (const :tag "pseudo tooltip"
207 company-pseudo-tooltip-frontend)
208 (const :tag "pseudo tooltip, multiple only"
209 company-pseudo-tooltip-unless-just-one-frontend)
210 (const :tag "preview" company-preview-frontend)
211 (const :tag "preview, unique only"
212 company-preview-if-just-one-frontend)
213 (function :tag "custom function" nil))))
215 (defcustom company-tooltip-limit 10
216 "The maximum number of candidates in the tool tip"
220 (defcustom company-tooltip-minimum 6
221 "The minimum height of the tool tip.
222 If this many lines are not available, prefer to display the tooltip above."
226 (defvar company-safe-backends
227 '((company-abbrev . "Abbrev")
228 (company-clang . "clang")
229 (company-css . "CSS")
230 (company-dabbrev . "dabbrev for plain text")
231 (company-dabbrev-code . "dabbrev for code")
232 (company-eclim . "eclim (an Eclipse interace)")
233 (company-elisp . "Emacs Lisp")
234 (company-etags . "etags")
235 (company-files . "Files")
236 (company-gtags . "GNU Global")
237 (company-ispell . "ispell")
238 (company-keywords . "Programming language keywords")
239 (company-nxml . "nxml")
240 (company-oddmuse . "Oddmuse")
241 (company-pysmell . "PySmell")
242 (company-ropemacs . "ropemacs")
243 (company-semantic . "CEDET Semantic")
244 (company-tempo . "Tempo templates")
245 (company-xcode . "Xcode")))
246 (put 'company-safe-backends 'risky-local-variable t)
248 (defun company-safe-backends-p (backends)
249 (and (consp backends)
250 (not (dolist (backend backends)
251 (unless (if (consp backend)
252 (company-safe-backends-p backend)
253 (assq backend company-safe-backends))
256 (defun company-capf (command &optional arg &rest args)
257 "`company-mode' back-end using `completion-at-point-functions'.
258 Requires Emacs 24.1 or newer."
259 (interactive (list 'interactive))
261 (interactive (company-begin-backend 'company-capf))
263 (let ((res (run-hook-wrapped 'completion-at-point-functions
264 ;; Ignore misbehaving functions.
265 #'completion--capf-wrapper 'optimist)))
267 (if (> (nth 2 res) (point))
269 (buffer-substring-no-properties (nth 1 res) (point))))))
271 (let ((res (run-hook-wrapped 'completion-at-point-functions
272 ;; Ignore misbehaving functions.
273 #'completion--capf-wrapper 'optimist)))
275 (all-completions arg (nth 3 res)
276 (plist-get (nthcdr 4 res) :predicate)))))))
278 (defcustom company-backends '(company-elisp company-nxml company-css
279 company-clang company-semantic company-eclim
280 company-xcode company-ropemacs
281 (company-gtags company-etags company-dabbrev-code
283 company-oddmuse company-files company-dabbrev)
284 "The list of active back-ends (completion engines).
285 Each list elements can itself be a list of back-ends. In that case their
286 completions are merged. Otherwise only the first matching back-end returns
289 `company-begin-backend' can be used to start a specific back-end,
290 `company-other-backend' will skip to the next matching back-end in the list.
292 Each back-end is a function that takes a variable number of arguments.
293 The first argument is the command requested from the back-end. It is one
296 `prefix': The back-end should return the text to be completed. It must be
297 text immediately before `point'. Returning nil passes control to the next
298 back-end. The function should return 'stop if it should complete but cannot
299 \(e.g. if it is in the middle of a string\). If the returned value is only
300 part of the prefix (e.g. the part after \"->\" in C), the back-end may return a
301 cons of prefix and prefix length, which is then used in the
302 `company-minimum-prefix-length' test.
304 `candidates': The second argument is the prefix to be completed. The
305 return value should be a list of candidates that start with the prefix.
309 `sorted': The back-end may return t here to indicate that the candidates
310 are sorted and will not need to be sorted again.
312 `duplicates': If non-nil, company will take care of removing duplicates
315 `no-cache': Usually company doesn't ask for candidates again as completion
316 progresses, unless the back-end returns t for this command. The second
317 argument is the latest prefix.
319 `meta': The second argument is a completion candidate. The back-end should
320 return a (short) documentation string for it.
322 `doc-buffer': The second argument is a completion candidate.
323 The back-end should create a buffer (preferably with `company-doc-buffer'),
324 fill it with documentation and return it.
326 `location': The second argument is a completion candidate. The back-end can
327 return the cons of buffer and buffer location, or of file and line
328 number where the completion candidate was defined.
330 `require-match': If this value is t, the user is not allowed to enter anything
331 not offered as a candidate. Use with care! The default value nil gives the
332 user that choice with `company-require-match'. Return value 'never overrides
333 that option the other way around.
335 `init': Called once for each buffer, the back-end can check for external
336 programs and files and load any required libraries. Raising an error here will
337 show up in message log once, and the backend will not be used for completion.
339 `post-completion': Called after a completion candidate has been inserted into
340 the buffer. The second argument is the candidate. Can be used to modify it,
341 e.g. to expand a snippet.
343 The back-end should return nil for all commands it does not support or
344 does not know about. It should also be callable interactively and use
345 `company-begin-backend' to start itself in that case."
350 ,@(mapcar (lambda (b) `(const :tag ,(cdr b) ,(car b)))
351 company-safe-backends)
352 (symbol :tag "User defined")
353 (repeat :tag "Merged Back-ends"
354 (choice :tag "Back-end"
355 ,@(mapcar (lambda (b)
356 `(const :tag ,(cdr b) ,(car b)))
357 company-safe-backends)
358 (symbol :tag "User defined"))))))
360 (put 'company-backends 'safe-local-variable 'company-safe-backends-p)
362 (defcustom company-completion-started-hook nil
363 "Hook run when company starts completing.
364 The hook is called with one argument that is non-nil if the completion was
369 (defcustom company-completion-cancelled-hook nil
370 "Hook run when company cancels completing.
371 The hook is called with one argument that is non-nil if the completion was
376 (defcustom company-completion-finished-hook nil
377 "Hook run when company successfully completes.
378 The hook is called with the selected candidate as an argument.
380 If you indend to use it to post-process candidates from a specific back-end,
381 consider using the `post-completion' command instead."
385 (defcustom company-minimum-prefix-length 3
386 "The minimum prefix length for automatic completion."
388 :type '(integer :tag "prefix length"))
390 (defcustom company-require-match 'company-explicit-action-p
391 "If enabled, disallow non-matching input.
392 This can be a function do determine if a match is required.
394 This can be overridden by the back-end, if it returns t or 'never to
395 'require-match. `company-auto-complete' also takes precedence over this."
397 :type '(choice (const :tag "Off" nil)
398 (function :tag "Predicate function")
399 (const :tag "On, if user interaction took place"
400 'company-explicit-action-p)
401 (const :tag "On" t)))
403 (defcustom company-auto-complete 'company-explicit-action-p
404 "Determines when to auto-complete.
405 If this is enabled, all characters from `company-auto-complete-chars' complete
406 the selected completion. This can also be a function."
408 :type '(choice (const :tag "Off" nil)
409 (function :tag "Predicate function")
410 (const :tag "On, if user interaction took place"
411 'company-explicit-action-p)
412 (const :tag "On" t)))
414 (defcustom company-auto-complete-chars '(?\ ?\( ?\) ?. ?\" ?$ ?\' ?< ?| ?!)
415 "Determines which characters trigger an automatic completion.
416 See `company-auto-complete'. If this is a string, each string character causes
417 completion. If it is a list of syntax description characters (see
418 `modify-syntax-entry'), all characters with that syntax auto-complete.
420 This can also be a function, which is called with the new input and should
421 return non-nil if company should auto-complete.
423 A character that is part of a valid candidate never triggers auto-completion."
425 :type '(choice (string :tag "Characters")
427 (const :tag "Whitespace" ?\ )
428 (const :tag "Symbol" ?_)
429 (const :tag "Opening parentheses" ?\()
430 (const :tag "Closing parentheses" ?\))
431 (const :tag "Word constituent" ?w)
432 (const :tag "Punctuation." ?.)
433 (const :tag "String quote." ?\")
434 (const :tag "Paired delimiter." ?$)
435 (const :tag "Expression quote or prefix operator." ?\')
436 (const :tag "Comment starter." ?<)
437 (const :tag "Comment ender." ?>)
438 (const :tag "Character-quote." ?/)
439 (const :tag "Generic string fence." ?|)
440 (const :tag "Generic comment fence." ?!))
441 (function :tag "Predicate function")))
443 (defcustom company-idle-delay .7
444 "The idle delay in seconds until automatic completions starts.
445 A value of nil means never complete automatically, t means complete
446 immediately when a prefix of `company-minimum-prefix-length' is reached."
448 :type '(choice (const :tag "never (nil)" nil)
449 (const :tag "immediate (t)" t)
450 (number :tag "seconds")))
452 (defcustom company-begin-commands t
453 "A list of commands following which company will start completing.
454 If this is t, it will complete after any command. See `company-idle-delay'.
456 Alternatively any command with a non-nil 'company-begin property is treated as
457 if it was on this list."
459 :type '(choice (const :tag "Any command" t)
460 (const :tag "Self insert command" '(self-insert-command))
461 (repeat :tag "Commands" function)))
463 (defcustom company-show-numbers nil
464 "If enabled, show quick-access numbers for the first ten candidates."
466 :type '(choice (const :tag "off" nil)
467 (const :tag "on" t)))
469 (defvar company-end-of-buffer-workaround t
470 "Work around a visualization bug when completing at the end of the buffer.
471 The work-around consists of adding a newline.")
473 ;;; mode ;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;
475 (defvar company-mode-map (make-sparse-keymap)
476 "Keymap used by `company-mode'.")
478 (defvar company-active-map
479 (let ((keymap (make-sparse-keymap)))
480 (define-key keymap "\e\e\e" 'company-abort)
481 (define-key keymap "\C-g" 'company-abort)
482 (define-key keymap (kbd "M-n") 'company-select-next)
483 (define-key keymap (kbd "M-p") 'company-select-previous)
484 (define-key keymap (kbd "<down>") 'company-select-next-or-abort)
485 (define-key keymap (kbd "<up>") 'company-select-previous-or-abort)
486 (define-key keymap [down-mouse-1] 'ignore)
487 (define-key keymap [down-mouse-3] 'ignore)
488 (define-key keymap [mouse-1] 'company-complete-mouse)
489 (define-key keymap [mouse-3] 'company-select-mouse)
490 (define-key keymap [up-mouse-1] 'ignore)
491 (define-key keymap [up-mouse-3] 'ignore)
492 (define-key keymap [return] 'company-complete-selection)
493 (define-key keymap [tab] 'company-complete-common)
494 (define-key keymap (kbd "<f1>") 'company-show-doc-buffer)
495 (define-key keymap "\C-w" 'company-show-location)
496 (define-key keymap "\C-s" 'company-search-candidates)
497 (define-key keymap "\C-\M-s" 'company-filter-candidates)
499 (define-key keymap (vector (+ (aref (kbd "M-0") 0) i))
500 `(lambda () (interactive) (company-complete-number ,i))))
503 "Keymap that is enabled during an active completion.")
505 (defvar company--disabled-backends nil)
507 (defun company-init-backend (backend)
508 (and (symbolp backend)
509 (not (fboundp backend))
510 (ignore-errors (require backend nil t)))
512 (if (or (symbolp backend)
516 (funcall backend 'init)
517 (put backend 'company-init t))
519 (put backend 'company-init 'failed)
520 (unless (memq backend company--disabled-backends)
521 (message "Company back-end '%s' could not be initialized:\n%s"
522 backend (error-message-string err)))
523 (pushnew backend company--disabled-backends)
525 (mapc 'company-init-backend backend)))
527 (defvar company-default-lighter " company")
529 (defvar company-lighter company-default-lighter)
530 (make-variable-buffer-local 'company-lighter)
533 (define-minor-mode company-mode
534 "\"complete anything\"; is an in-buffer completion framework.
535 Completion starts automatically, depending on the values
536 `company-idle-delay' and `company-minimum-prefix-length'.
538 Completion can be controlled with the commands:
539 `company-complete-common', `company-complete-selection', `company-complete',
540 `company-select-next', `company-select-previous'. If these commands are
541 called before `company-idle-delay', completion will also start.
543 Completions can be searched with `company-search-candidates' or
544 `company-filter-candidates'. These can be used while completion is
547 The completion data is retrieved using `company-backends' and displayed using
548 `company-frontends'. If you want to start a specific back-end, call it
549 interactively or use `company-begin-backend'.
551 regular keymap (`company-mode-map'):
554 keymap during active completions (`company-active-map'):
556 \\{company-active-map}"
557 nil company-lighter company-mode-map
560 (add-hook 'pre-command-hook 'company-pre-command nil t)
561 (add-hook 'post-command-hook 'company-post-command nil t)
562 (mapc 'company-init-backend company-backends))
563 (remove-hook 'pre-command-hook 'company-pre-command t)
564 (remove-hook 'post-command-hook 'company-post-command t)
566 (kill-local-variable 'company-point)))
569 (define-globalized-minor-mode global-company-mode company-mode company-mode-on)
571 (defun company-mode-on ()
572 (unless (or noninteractive (eq (aref (buffer-name) 0) ?\s))
575 (defsubst company-assert-enabled ()
577 (company-uninstall-map)
578 (error "Company not enabled")))
580 ;;; keymaps ;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;
582 (defvar company-my-keymap nil)
583 (make-variable-buffer-local 'company-my-keymap)
585 (defvar company-emulation-alist '((t . nil)))
587 (defsubst company-enable-overriding-keymap (keymap)
588 (company-uninstall-map)
589 (setq company-my-keymap keymap))
591 (defun company-ensure-emulation-alist ()
592 (unless (eq 'company-emulation-alist (car emulation-mode-map-alists))
593 (setq emulation-mode-map-alists
594 (cons 'company-emulation-alist
595 (delq 'company-emulation-alist emulation-mode-map-alists)))))
597 (defun company-install-map ()
598 (unless (or (cdar company-emulation-alist)
599 (null company-my-keymap))
600 (setf (cdar company-emulation-alist) company-my-keymap)))
602 (defun company-uninstall-map ()
603 (setf (cdar company-emulation-alist) nil))
606 ;; Emacs calculates the active keymaps before reading the event. That means we
607 ;; cannot change the keymap from a timer. So we send a bogus command.
608 (defun company-ignore ()
610 (setq this-command last-command))
612 (global-set-key '[31415926] 'company-ignore)
614 (defun company-input-noop ()
615 (push 31415926 unread-command-events))
618 ;; posn-col-row is incorrect in older Emacsen when line-spacing is set
619 (defun company--col-row (&optional pos)
620 (let ((posn (posn-at-point pos)))
621 (cons (car (posn-col-row posn)) (cdr (posn-actual-col-row posn)))))
623 (defsubst company--column (&optional pos)
624 (car (posn-col-row (posn-at-point pos))))
626 (defsubst company--row (&optional pos)
627 (cdr (posn-actual-col-row (posn-at-point pos))))
629 ;;; backends ;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;
631 (defun company-grab (regexp &optional expression limit)
632 (when (looking-back regexp limit)
633 (or (match-string-no-properties (or expression 0)) "")))
635 (defun company-grab-line (regexp &optional expression)
636 (company-grab regexp expression (point-at-bol)))
638 (defun company-grab-symbol ()
639 (if (looking-at "\\_>")
640 (buffer-substring (point) (save-excursion (skip-syntax-backward "w_")
642 (unless (and (char-after) (memq (char-syntax (char-after)) '(?w ?_)))
645 (defun company-grab-word ()
646 (if (looking-at "\\>")
647 (buffer-substring (point) (save-excursion (skip-syntax-backward "w")
649 (unless (and (char-after) (eq (char-syntax (char-after)) ?w))
652 (defun company-in-string-or-comment ()
653 (let ((ppss (syntax-ppss)))
654 (or (car (setq ppss (nthcdr 3 ppss)))
655 (car (setq ppss (cdr ppss)))
658 (if (fboundp 'locate-dominating-file)
659 (defalias 'company-locate-dominating-file 'locate-dominating-file)
660 (defun company-locate-dominating-file (file name)
662 (let ((dir (file-name-directory file))
664 (while (not (equal dir prev-dir))
665 (when (file-exists-p (expand-file-name name dir))
668 dir (file-name-directory (directory-file-name dir))))))))
670 (defun company-call-backend (&rest args)
671 (if (functionp company-backend)
672 (apply company-backend args)
673 (apply 'company--multi-backend-adapter company-backend args)))
675 (defun company--multi-backend-adapter (backends command &rest args)
676 (let ((backends (loop for b in backends
677 when (not (and (symbolp b)
678 (eq 'failed (get b 'company-init))))
682 (loop for backend in backends
683 when (equal (funcall backend 'prefix)
685 append (apply backend 'candidates args)))
690 (dolist (backend backends)
691 (when (setq value (apply backend command args))
692 (return value))))))))
694 ;;; completion mechanism ;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;
696 (defvar company-backend nil)
697 (make-variable-buffer-local 'company-backend)
699 (defvar company-prefix nil)
700 (make-variable-buffer-local 'company-prefix)
702 (defvar company-candidates nil)
703 (make-variable-buffer-local 'company-candidates)
705 (defvar company-candidates-length nil)
706 (make-variable-buffer-local 'company-candidates-length)
708 (defvar company-candidates-cache nil)
709 (make-variable-buffer-local 'company-candidates-cache)
711 (defvar company-candidates-predicate nil)
712 (make-variable-buffer-local 'company-candidates-predicate)
714 (defvar company-common nil)
715 (make-variable-buffer-local 'company-common)
717 (defvar company-selection 0)
718 (make-variable-buffer-local 'company-selection)
720 (defvar company-selection-changed nil)
721 (make-variable-buffer-local 'company-selection-changed)
723 (defvar company--explicit-action nil
724 "Non-nil, if explicit completion took place.")
725 (make-variable-buffer-local 'company--explicit-action)
727 (defvar company--auto-completion nil
728 "Non-nil when current candidate is being completed automatically.
729 Controlled by `company-auto-complete'.")
731 (defvar company--point-max nil)
732 (make-variable-buffer-local 'company--point-max)
734 (defvar company-point nil)
735 (make-variable-buffer-local 'company-point)
737 (defvar company-timer nil)
739 (defvar company-added-newline nil)
740 (make-variable-buffer-local 'company-added-newline)
742 (defsubst company-strip-prefix (str)
743 (substring str (length company-prefix)))
745 (defmacro company-with-candidate-inserted (candidate &rest body)
746 "Evaluate BODY with CANDIDATE temporarily inserted.
747 This is a tool for back-ends that need candidates inserted before they
748 can retrieve meta-data for them."
750 `(let ((inhibit-modification-hooks t)
751 (inhibit-point-motion-hooks t)
752 (modified-p (buffer-modified-p)))
753 (insert (company-strip-prefix ,candidate))
756 (delete-region company-point (point)))))
758 (defun company-explicit-action-p ()
759 "Return whether explicit completion action was taken by the user."
760 (or company--explicit-action
761 company-selection-changed))
763 (defsubst company-reformat (candidate)
764 ;; company-ispell needs this, because the results are always lower-case
765 ;; It's mory efficient to fix it only when they are displayed.
766 (concat company-prefix (substring candidate (length company-prefix))))
768 (defun company--should-complete ()
769 (and (not (or buffer-read-only overriding-terminal-local-map
772 ;; Check if in the middle of entering a key combination.
773 (or (equal (this-command-keys-vector) [])
774 (not (keymapp (key-binding (this-command-keys-vector)))))
775 (eq company-idle-delay t)
776 (or (eq t company-begin-commands)
777 (memq this-command company-begin-commands)
778 (and (symbolp this-command) (get this-command 'company-begin)))
779 (not (and transient-mark-mode mark-active))))
781 (defsubst company-call-frontends (command)
782 (dolist (frontend company-frontends)
784 (funcall frontend command)
785 (error (error "Company: Front-end %s error \"%s\" on command %s"
786 frontend (error-message-string err) command)))))
788 (defsubst company-set-selection (selection &optional force-update)
789 (setq selection (max 0 (min (1- company-candidates-length) selection)))
790 (when (or force-update (not (equal selection company-selection)))
791 (setq company-selection selection
792 company-selection-changed t)
793 (company-call-frontends 'update)))
795 (defun company-apply-predicate (candidates predicate)
797 (dolist (c candidates)
798 (when (funcall predicate c)
802 (defun company-update-candidates (candidates)
803 (setq company-candidates-length (length candidates))
804 (if (> company-selection 0)
805 ;; Try to restore the selection
806 (let ((selected (nth company-selection company-candidates)))
807 (setq company-selection 0
808 company-candidates candidates)
810 (while (and candidates (string< (pop candidates) selected))
811 (incf company-selection))
813 ;; Make sure selection isn't out of bounds.
814 (setq company-selection (min (1- company-candidates-length)
815 company-selection)))))
816 (setq company-selection 0
817 company-candidates candidates))
819 (push (cons company-prefix company-candidates) company-candidates-cache)
821 (let ((completion-ignore-case (company-call-backend 'ignore-case)))
822 (setq company-common (company--safe-candidate
823 (try-completion company-prefix company-candidates))))
824 (when (eq company-common t)
825 (setq company-candidates nil)))
827 (defun company--safe-candidate (str)
828 (or (company-call-backend 'crop str)
831 (defun company-calculate-candidates (prefix)
832 (let ((candidates (cdr (assoc prefix company-candidates-cache)))
833 (ignore-case (company-call-backend 'ignore-case)))
835 (when company-candidates-cache
836 (let ((len (length prefix))
837 (completion-ignore-case ignore-case)
839 (dotimes (i (1+ len))
840 (when (setq prev (cdr (assoc (substring prefix 0 (- len i))
841 company-candidates-cache)))
842 (setq candidates (all-completions prefix prev))
844 ;; no cache match, call back-end
846 (setq candidates (company-call-backend 'candidates prefix))
847 (when company-candidates-predicate
849 (company-apply-predicate candidates
850 company-candidates-predicate)))
851 (unless (company-call-backend 'sorted)
852 (setq candidates (sort candidates 'string<)))
853 (when (company-call-backend 'duplicates)
855 (let ((c2 candidates))
857 (setcdr c2 (progn (while (equal (pop c2) (car c2)))
860 (if (or (cdr candidates)
861 (not (eq t (compare-strings (car candidates) nil nil
862 prefix nil nil ignore-case))))
864 ;; Already completed and unique; don't start.
867 (defun company-idle-begin (buf win tick pos)
869 (eq buf (current-buffer))
870 (eq win (selected-window))
871 (eq tick (buffer-chars-modified-tick))
873 (not company-candidates)
874 (not (equal (point) company-point))
875 (let ((company-idle-delay t)
876 (company-begin-commands t))
878 (when company-candidates
880 (company-post-command)))))
882 (defun company-auto-begin ()
883 (company-assert-enabled)
885 (not company-candidates)
886 (let ((company-idle-delay t)
887 (company-minimum-prefix-length 0)
888 (company-begin-commands t))
890 ;; Return non-nil if active.
893 (defun company-manual-begin ()
895 (setq company--explicit-action t)
896 (company-auto-begin))
898 (defun company-other-backend (&optional backward)
899 (interactive (list current-prefix-arg))
900 (company-assert-enabled)
902 (let* ((after (cdr (member company-backend company-backends)))
903 (before (cdr (member company-backend (reverse company-backends))))
905 (append before (reverse after))
906 (append after (reverse before)))))
908 (dolist (backend next)
909 (when (ignore-errors (company-begin-backend backend))
911 (company-manual-begin))
912 (unless company-candidates
913 (error "No other back-end")))
915 (defun company-require-match-p ()
916 (let ((backend-value (company-call-backend 'require-match)))
917 (or (eq backend-value t)
918 (and (if (functionp company-require-match)
919 (funcall company-require-match)
920 (eq company-require-match t))
921 (not (eq backend-value 'never))))))
923 (defun company-punctuation-p (input)
924 "Return non-nil, if input starts with punctuation or parentheses."
925 (memq (char-syntax (string-to-char input)) '(?. ?\( ?\))))
927 (defun company-auto-complete-p (input)
928 "Return non-nil, if input starts with punctuation or parentheses."
929 (and (if (functionp company-auto-complete)
930 (funcall company-auto-complete)
931 company-auto-complete)
932 (if (functionp company-auto-complete-chars)
933 (funcall company-auto-complete-chars input)
934 (if (consp company-auto-complete-chars)
935 (memq (char-syntax (string-to-char input))
936 company-auto-complete-chars)
937 (string-match (substring input 0 1) company-auto-complete-chars)))))
939 (defun company--incremental-p ()
940 (and (> (point) company-point)
941 (> (point-max) company--point-max)
942 (not (eq this-command 'backward-delete-char-untabify))
943 (equal (buffer-substring (- company-point (length company-prefix))
947 (defsubst company--string-incremental-p (old-prefix new-prefix)
948 (and (> (length new-prefix) (length old-prefix))
949 (equal old-prefix (substring new-prefix 0 (length old-prefix)))))
951 (defun company--continue-failed (new-prefix)
952 (when (company--incremental-p)
953 (let ((input (buffer-substring-no-properties (point) company-point)))
955 ((company-auto-complete-p input)
958 (goto-char company-point)
959 (let ((company--auto-completion t))
960 (company-complete-selection))
962 ((and (company--string-incremental-p company-prefix new-prefix)
963 (company-require-match-p))
964 ;; wrong incremental input, but required match
965 (backward-delete-char (length input))
967 (message "Matching input is required")
969 ((equal company-prefix (car company-candidates))
970 ;; last input was actually success
971 (company-cancel company-prefix)
974 (defun company--good-prefix-p (prefix)
975 (and (or (company-explicit-action-p)
976 (unless (eq prefix 'stop)
977 (>= (or (cdr-safe prefix) (length prefix))
978 company-minimum-prefix-length)))
979 (stringp (or (car-safe prefix) prefix))))
981 (defun company--continue ()
982 (when (company-call-backend 'no-cache company-prefix)
983 ;; Don't complete existing candidates, fetch new ones.
984 (setq company-candidates-cache nil))
985 (let* ((new-prefix (company-call-backend 'prefix))
986 (c (when (and (company--good-prefix-p new-prefix)
987 (setq new-prefix (or (car-safe new-prefix) new-prefix))
988 (= (- (point) (length new-prefix))
989 (- company-point (length company-prefix))))
990 (setq new-prefix (or (car-safe new-prefix) new-prefix))
991 (company-calculate-candidates new-prefix))))
994 ;; t means complete/unique.
995 (company-cancel new-prefix)
999 (setq company-prefix new-prefix)
1000 (company-update-candidates c)
1002 (t (company--continue-failed new-prefix)))
1005 (defun company--begin-new ()
1007 (dolist (backend (if company-backend
1008 ;; prefer manual override
1009 (list company-backend)
1012 (if (or (symbolp backend)
1013 (functionp backend))
1014 (when (or (not (symbolp backend))
1015 (eq t (get backend 'company-init))
1016 (unless (get backend 'company-init)
1017 (company-init-backend backend)))
1018 (funcall backend 'prefix))
1019 (company--multi-backend-adapter backend 'prefix)))
1021 (when (company--good-prefix-p prefix)
1022 (setq prefix (or (car-safe prefix) prefix)
1023 company-backend backend
1024 c (company-calculate-candidates prefix))
1025 ;; t means complete/unique. We don't start, so no hooks.
1027 (when company--explicit-action
1028 (message "No completion found"))
1029 (setq company-prefix prefix)
1030 (when (symbolp backend)
1031 (setq company-lighter (concat " " (symbol-name backend))))
1032 (company-update-candidates c)
1033 (run-hook-with-args 'company-completion-started-hook
1034 (company-explicit-action-p))
1035 (company-call-frontends 'show)))
1038 (defun company-begin ()
1039 (or (and company-candidates (company--continue))
1040 (and (company--should-complete) (company--begin-new)))
1041 (when company-candidates
1042 (when (and company-end-of-buffer-workaround (eobp))
1043 (save-excursion (insert "\n"))
1044 (setq company-added-newline (buffer-chars-modified-tick)))
1045 (setq company-point (point)
1046 company--point-max (point-max))
1047 (company-ensure-emulation-alist)
1048 (company-enable-overriding-keymap company-active-map)
1049 (company-call-frontends 'update)))
1051 (defun company-cancel (&optional result)
1052 (and company-added-newline
1053 (> (point-max) (point-min))
1054 (let ((tick (buffer-chars-modified-tick)))
1055 (delete-region (1- (point-max)) (point-max))
1056 (equal tick company-added-newline))
1057 ;; Only set unmodified when tick remained the same since insert.
1058 (set-buffer-modified-p nil))
1059 (when company-prefix
1060 (if (stringp result)
1062 (company-call-backend 'pre-completion result)
1063 (run-hook-with-args 'company-completion-finished-hook result)
1064 (company-call-backend 'post-completion result))
1065 (run-hook-with-args 'company-completion-cancelled-hook result)))
1066 (setq company-added-newline nil
1069 company-candidates nil
1070 company-candidates-length nil
1071 company-candidates-cache nil
1072 company-candidates-predicate nil
1075 company-selection-changed nil
1076 company--explicit-action nil
1077 company-lighter company-default-lighter
1078 company--point-max nil
1081 (cancel-timer company-timer))
1082 (company-search-mode 0)
1083 (company-call-frontends 'hide)
1084 (company-enable-overriding-keymap nil))
1086 (defun company-abort ()
1089 ;; Don't start again, unless started manually.
1090 (setq company-point (point)))
1092 (defun company-finish (result)
1093 (insert (company-strip-prefix result))
1094 (company-cancel result)
1095 ;; Don't start again, unless started manually.
1096 (setq company-point (point)))
1098 (defsubst company-keep (command)
1099 (and (symbolp command) (get command 'company-keep)))
1101 (defun company-pre-command ()
1102 (unless (company-keep this-command)
1104 (when company-candidates
1105 (company-call-frontends 'pre-command))
1106 (error (message "Company: An error occurred in pre-command")
1107 (message "%s" (error-message-string err))
1110 (cancel-timer company-timer)
1111 (setq company-timer nil))
1112 (company-uninstall-map))
1114 (defun company-post-command ()
1115 (unless (company-keep this-command)
1118 (unless (equal (point) company-point)
1120 (if company-candidates
1121 (company-call-frontends 'post-command)
1122 (and (numberp company-idle-delay)
1123 (or (eq t company-begin-commands)
1124 (memq this-command company-begin-commands))
1126 (run-with-timer company-idle-delay nil
1128 (current-buffer) (selected-window)
1129 (buffer-chars-modified-tick) (point))))))
1130 (error (message "Company: An error occurred in post-command")
1131 (message "%s" (error-message-string err))
1133 (company-install-map))
1135 ;;; search ;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;
1137 (defvar company-search-string nil)
1138 (make-variable-buffer-local 'company-search-string)
1140 (defvar company-search-lighter " Search: \"\"")
1141 (make-variable-buffer-local 'company-search-lighter)
1143 (defvar company-search-old-map nil)
1144 (make-variable-buffer-local 'company-search-old-map)
1146 (defvar company-search-old-selection 0)
1147 (make-variable-buffer-local 'company-search-old-selection)
1149 (defun company-search (text lines)
1150 (let ((quoted (regexp-quote text))
1152 (dolist (line lines)
1153 (when (string-match quoted line (length company-prefix))
1157 (defun company-search-printing-char ()
1159 (company-search-assert-enabled)
1160 (setq company-search-string
1161 (concat (or company-search-string "") (string last-command-event))
1162 company-search-lighter (concat " Search: \"" company-search-string
1164 (let ((pos (company-search company-search-string
1165 (nthcdr company-selection company-candidates))))
1168 (company-set-selection (+ company-selection pos) t))))
1170 (defun company-search-repeat-forward ()
1171 "Repeat the incremental search in completion candidates forward."
1173 (company-search-assert-enabled)
1174 (let ((pos (company-search company-search-string
1175 (cdr (nthcdr company-selection
1176 company-candidates)))))
1179 (company-set-selection (+ company-selection pos 1) t))))
1181 (defun company-search-repeat-backward ()
1182 "Repeat the incremental search in completion candidates backwards."
1184 (company-search-assert-enabled)
1185 (let ((pos (company-search company-search-string
1186 (nthcdr (- company-candidates-length
1188 (reverse company-candidates)))))
1191 (company-set-selection (- company-selection pos 1) t))))
1193 (defun company-create-match-predicate ()
1194 (setq company-candidates-predicate
1195 `(lambda (candidate)
1196 ,(if company-candidates-predicate
1197 `(and (string-match ,company-search-string candidate)
1198 (funcall ,company-candidates-predicate
1200 `(string-match ,company-search-string candidate))))
1201 (company-update-candidates
1202 (company-apply-predicate company-candidates company-candidates-predicate))
1203 ;; Invalidate cache.
1204 (setq company-candidates-cache (cons company-prefix company-candidates)))
1206 (defun company-filter-printing-char ()
1208 (company-search-assert-enabled)
1209 (company-search-printing-char)
1210 (company-create-match-predicate)
1211 (company-call-frontends 'update))
1213 (defun company-search-kill-others ()
1214 "Limit the completion candidates to the ones matching the search string."
1216 (company-search-assert-enabled)
1217 (company-create-match-predicate)
1218 (company-search-mode 0)
1219 (company-call-frontends 'update))
1221 (defun company-search-abort ()
1222 "Abort searching the completion candidates."
1224 (company-search-assert-enabled)
1225 (company-set-selection company-search-old-selection t)
1226 (company-search-mode 0))
1228 (defun company-search-other-char ()
1230 (company-search-assert-enabled)
1231 (company-search-mode 0)
1232 (company--unread-last-input))
1234 (defvar company-search-map
1236 (keymap (make-keymap)))
1237 (if (fboundp 'max-char)
1238 (set-char-table-range (nth 1 keymap) (cons #x100 (max-char))
1239 'company-search-printing-char)
1241 ;; obsolete in Emacs 23
1242 (let ((l (generic-character-list))
1243 (table (nth 1 keymap)))
1245 (set-char-table-default table (car l) 'company-search-printing-char)
1246 (setq l (cdr l))))))
1247 (define-key keymap [t] 'company-search-other-char)
1249 (define-key keymap (make-string 1 i) 'company-search-other-char)
1252 (define-key keymap (vector i) 'company-search-printing-char)
1254 (let ((meta-map (make-sparse-keymap)))
1255 (define-key keymap (char-to-string meta-prefix-char) meta-map)
1256 (define-key keymap [escape] meta-map))
1257 (define-key keymap (vector meta-prefix-char t) 'company-search-other-char)
1258 (define-key keymap "\e\e\e" 'company-search-other-char)
1259 (define-key keymap [escape escape escape] 'company-search-other-char)
1261 (define-key keymap "\C-g" 'company-search-abort)
1262 (define-key keymap "\C-s" 'company-search-repeat-forward)
1263 (define-key keymap "\C-r" 'company-search-repeat-backward)
1264 (define-key keymap "\C-o" 'company-search-kill-others)
1266 "Keymap used for incrementally searching the completion candidates.")
1268 (define-minor-mode company-search-mode
1269 "Search mode for completion candidates.
1270 Don't start this directly, use `company-search-candidates' or
1271 `company-filter-candidates'."
1272 nil company-search-lighter nil
1273 (if company-search-mode
1274 (if (company-manual-begin)
1276 (setq company-search-old-selection company-selection)
1277 (company-call-frontends 'update))
1278 (setq company-search-mode nil))
1279 (kill-local-variable 'company-search-string)
1280 (kill-local-variable 'company-search-lighter)
1281 (kill-local-variable 'company-search-old-selection)
1282 (company-enable-overriding-keymap company-active-map)))
1284 (defsubst company-search-assert-enabled ()
1285 (company-assert-enabled)
1286 (unless company-search-mode
1287 (company-uninstall-map)
1288 (error "Company not in search mode")))
1290 (defun company-search-candidates ()
1291 "Start searching the completion candidates incrementally.
1293 \\<company-search-map>Search can be controlled with the commands:
1294 - `company-search-repeat-forward' (\\[company-search-repeat-forward])
1295 - `company-search-repeat-backward' (\\[company-search-repeat-backward])
1296 - `company-search-abort' (\\[company-search-abort])
1298 Regular characters are appended to the search string.
1300 The command `company-search-kill-others' (\\[company-search-kill-others]) uses
1301 the search string to limit the completion candidates."
1303 (company-search-mode 1)
1304 (company-enable-overriding-keymap company-search-map))
1306 (defvar company-filter-map
1307 (let ((keymap (make-keymap)))
1308 (define-key keymap [remap company-search-printing-char]
1309 'company-filter-printing-char)
1310 (set-keymap-parent keymap company-search-map)
1312 "Keymap used for incrementally searching the completion candidates.")
1314 (defun company-filter-candidates ()
1315 "Start filtering the completion candidates incrementally.
1316 This works the same way as `company-search-candidates' immediately
1317 followed by `company-search-kill-others' after each input."
1319 (company-search-mode 1)
1320 (company-enable-overriding-keymap company-filter-map))
1322 ;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;
1324 (defun company-select-next ()
1325 "Select the next candidate in the list."
1327 (when (company-manual-begin)
1328 (company-set-selection (1+ company-selection))))
1330 (defun company-select-previous ()
1331 "Select the previous candidate in the list."
1333 (when (company-manual-begin)
1334 (company-set-selection (1- company-selection))))
1336 (defun company-select-next-or-abort ()
1337 "Select the next candidate if more than one, else abort
1338 and invoke the normal binding."
1340 (if (> company-candidates-length 1)
1341 (company-select-next)
1343 (company--unread-last-input)))
1345 (defun company-select-previous-or-abort ()
1346 "Select the previous candidate if more than one, else abort
1347 and invoke the normal binding."
1349 (if (> company-candidates-length 1)
1350 (company-select-previous)
1352 (company--unread-last-input)))
1354 (defun company-select-mouse (event)
1355 "Select the candidate picked by the mouse."
1357 (when (nth 4 (event-start event))
1358 (company-set-selection (- (cdr (posn-actual-col-row (event-start event)))
1363 (defun company-complete-mouse (event)
1364 "Complete the candidate picked by the mouse."
1366 (when (company-select-mouse event)
1367 (company-complete-selection)))
1369 (defun company-complete-selection ()
1370 "Complete the selected candidate."
1372 (when (company-manual-begin)
1373 (let ((result (nth company-selection company-candidates)))
1374 (when company--auto-completion
1375 (setq result (company--safe-candidate result)))
1376 (company-finish result))))
1378 (defun company-complete-common ()
1379 "Complete the common part of all candidates."
1381 (when (company-manual-begin)
1382 (if (and (not (cdr company-candidates))
1383 (equal company-common (car company-candidates)))
1384 (company-complete-selection)
1385 (insert (company-strip-prefix company-common)))))
1387 (defun company-complete ()
1388 "Complete the common part of all candidates or the current selection.
1389 The first time this is called, the common part is completed, the second time, or
1390 when the selection has been changed, the selected candidate is completed."
1392 (when (company-manual-begin)
1393 (if (or company-selection-changed
1394 (eq last-command 'company-complete-common))
1395 (call-interactively 'company-complete-selection)
1396 (call-interactively 'company-complete-common)
1397 (setq this-command 'company-complete-common))))
1399 (defun company-complete-number (n)
1400 "Complete the Nth candidate.
1401 To show the number next to the candidates in some back-ends, enable
1402 `company-show-numbers'."
1403 (when (company-manual-begin)
1404 (and (< n 1) (> n company-candidates-length)
1405 (error "No candidate number %d" n))
1407 (company-finish (nth n company-candidates))))
1409 ;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;
1411 (defconst company-space-strings-limit 100)
1413 (defconst company-space-strings
1415 (dotimes (i company-space-strings-limit)
1416 (push (make-string (- company-space-strings-limit 1 i) ?\ ) lst))
1417 (apply 'vector lst)))
1419 (defsubst company-space-string (len)
1420 (if (< len company-space-strings-limit)
1421 (aref company-space-strings len)
1422 (make-string len ?\ )))
1424 (defsubst company-safe-substring (str from &optional to)
1425 (if (> from (string-width str))
1429 (move-to-column from)
1430 (let ((beg (point)))
1434 (concat (buffer-substring beg (point))
1435 (let ((padding (- to (current-column))))
1437 (company-space-string padding)))))
1438 (buffer-substring beg (point-max)))))))
1440 ;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;
1442 (defvar company-last-metadata nil)
1443 (make-variable-buffer-local 'company-last-metadata)
1445 (defun company-fetch-metadata ()
1446 (let ((selected (nth company-selection company-candidates)))
1447 (unless (equal selected (car company-last-metadata))
1448 (setq company-last-metadata
1449 (cons selected (company-call-backend 'meta selected))))
1450 (cdr company-last-metadata)))
1452 (defun company-doc-buffer (&optional string)
1453 (with-current-buffer (get-buffer-create "*Company meta-data*")
1457 (defvar company--electric-commands
1458 '(scroll-other-window scroll-other-window-down)
1459 "List of Commands that won't break out of electric commands.")
1461 (defmacro company--electric-do (&rest body)
1462 (declare (indent 0) (debug t))
1463 `(when (company-manual-begin)
1464 (save-window-excursion
1465 (let ((height (window-height))
1466 (row (company--row))
1469 (and (< (window-height) height)
1470 (< (- (window-height) row 2) company-tooltip-limit)
1471 (recenter (- (window-height) row 2)))
1472 (while (memq (setq cmd (key-binding (vector (list (read-event)))))
1473 company--electric-commands)
1474 (call-interactively cmd))
1475 (company--unread-last-input)))))
1477 (defun company--unread-last-input ()
1478 (when last-input-event
1479 (clear-this-command-keys t)
1480 (setq unread-command-events (list last-input-event))))
1482 (defun company-show-doc-buffer ()
1483 "Temporarily show a buffer with the complete documentation for the selection."
1485 (company--electric-do
1486 (let* ((selected (nth company-selection company-candidates))
1487 (doc-buffer (or (company-call-backend 'doc-buffer selected)
1488 (error "No documentation available"))))
1489 (with-current-buffer doc-buffer
1490 (goto-char (point-min)))
1491 (display-buffer doc-buffer t))))
1492 (put 'company-show-doc-buffer 'company-keep t)
1494 (defun company-show-location ()
1495 "Temporarily display a buffer showing the selected candidate in context."
1497 (company--electric-do
1498 (let* ((selected (nth company-selection company-candidates))
1499 (location (company-call-backend 'location selected))
1500 (pos (or (cdr location) (error "No location available")))
1501 (buffer (or (and (bufferp (car location)) (car location))
1502 (find-file-noselect (car location) t))))
1503 (with-selected-window (display-buffer buffer t)
1506 (if (bufferp (car location))
1508 (goto-char (point-min))
1509 (forward-line (1- pos))))
1510 (set-window-start nil (point))))))
1511 (put 'company-show-location 'company-keep t)
1513 ;;; package functions ;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;
1515 (defvar company-callback nil)
1516 (make-variable-buffer-local 'company-callback)
1518 (defvar company-begin-with-marker nil)
1519 (make-variable-buffer-local 'company-begin-with-marker)
1521 (defun company-remove-callback (&optional ignored)
1522 (remove-hook 'company-completion-finished-hook company-callback t)
1523 (remove-hook 'company-completion-cancelled-hook 'company-remove-callback t)
1524 (remove-hook 'company-completion-finished-hook 'company-remove-callback t)
1525 (when company-begin-with-marker
1526 (set-marker company-begin-with-marker nil)))
1528 (defun company-begin-backend (backend &optional callback)
1529 "Start a completion at point using BACKEND."
1530 (interactive (let ((val (completing-read "Company back-end: "
1532 'functionp nil "company-")))
1534 (list (intern val)))))
1535 (when (setq company-callback callback)
1536 (add-hook 'company-completion-finished-hook company-callback nil t))
1537 (add-hook 'company-completion-cancelled-hook 'company-remove-callback nil t)
1538 (add-hook 'company-completion-finished-hook 'company-remove-callback nil t)
1539 (setq company-backend backend)
1540 ;; Return non-nil if active.
1541 (or (company-manual-begin)
1543 (setq company-backend nil)
1544 (error "Cannot complete at point"))))
1546 (defun company-begin-with (candidates
1547 &optional prefix-length require-match callback)
1548 "Start a completion at point.
1549 CANDIDATES is the list of candidates to use and PREFIX-LENGTH is the length of
1550 the prefix that already is in the buffer before point. It defaults to 0.
1552 CALLBACK is a function called with the selected result if the user successfully
1553 completes the input.
1556 \(company-begin-with '\(\"foo\" \"foobar\" \"foobarbaz\"\)\)"
1557 (setq company-begin-with-marker (copy-marker (point) t))
1558 (company-begin-backend
1559 `(lambda (command &optional arg &rest ignored)
1561 ((eq command 'prefix)
1562 (when (equal (point) (marker-position company-begin-with-marker))
1563 (buffer-substring ,(- (point) (or prefix-length 0)) (point))))
1564 ((eq command 'candidates)
1565 (all-completions arg ',candidates))
1566 ((eq command 'require-match)
1570 ;;; pseudo-tooltip ;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;
1572 (defvar company-pseudo-tooltip-overlay nil)
1573 (make-variable-buffer-local 'company-pseudo-tooltip-overlay)
1575 (defvar company-tooltip-offset 0)
1576 (make-variable-buffer-local 'company-tooltip-offset)
1578 (defun company-pseudo-tooltip-update-offset (selection num-lines limit)
1581 (setq company-tooltip-offset
1582 (max (min selection company-tooltip-offset)
1583 (- selection -1 limit)))
1585 (when (<= company-tooltip-offset 1)
1587 (setq company-tooltip-offset 0))
1589 (when (>= company-tooltip-offset (- num-lines limit 1))
1591 (when (= selection (1- num-lines))
1592 (decf company-tooltip-offset)
1593 (when (<= company-tooltip-offset 1)
1594 (setq company-tooltip-offset 0)
1601 (defsubst company-round-tab (arg)
1602 (* (/ (+ arg tab-width) tab-width) tab-width))
1604 (defun company-untabify (str)
1605 (let* ((pieces (split-string str "\t"))
1608 (setcar copy (company-safe-substring
1609 (car copy) 0 (company-round-tab (string-width (car copy)))))
1611 (apply 'concat pieces)))
1613 (defun company-fill-propertize (line width selected)
1614 (setq line (company-safe-substring line 0 width))
1615 (add-text-properties 0 width '(face company-tooltip
1616 mouse-face company-tooltip-mouse)
1618 (add-text-properties 0 (length company-common)
1619 '(face company-tooltip-common
1620 mouse-face company-tooltip-mouse)
1623 (if (and company-search-string
1624 (string-match (regexp-quote company-search-string) line
1625 (length company-prefix)))
1627 (add-text-properties (match-beginning 0) (match-end 0)
1628 '(face company-tooltip-selection)
1630 (when (< (match-beginning 0) (length company-common))
1631 (add-text-properties (match-beginning 0) (length company-common)
1632 '(face company-tooltip-common-selection)
1634 (add-text-properties 0 width '(face company-tooltip-selection
1635 mouse-face company-tooltip-selection)
1637 (add-text-properties 0 (length company-common)
1638 '(face company-tooltip-common-selection
1639 mouse-face company-tooltip-selection)
1645 (defun company-buffer-lines (beg end)
1648 (while (and (= 1 (vertical-motion 1))
1650 (push (buffer-substring beg (min end (1- (point)))) lines)
1652 (unless (eq beg end)
1653 (push (buffer-substring beg end) lines))
1656 (defsubst company-modify-line (old new offset)
1657 (concat (company-safe-substring old 0 offset)
1659 (company-safe-substring old (+ offset (length new)))))
1661 (defsubst company--length-limit (lst limit)
1662 (if (nthcdr limit lst)
1666 (defun company--replacement-string (lines old column nl &optional align-top)
1668 (let ((width (length (car lines))))
1669 (when (> width (- (window-width) column))
1670 (setq column (max 0 (- (window-width) width)))))
1674 ;; untouched lines first
1675 (dotimes (i (- (length old) (length lines)))
1676 (push (pop old) new)))
1677 ;; length into old lines.
1679 (push (company-modify-line (pop old) (pop lines) column) new))
1680 ;; Append whole new lines.
1682 (push (concat (company-space-string column) (pop lines)) new))
1684 (let ((str (concat (when nl "\n")
1685 (mapconcat 'identity (nreverse new) "\n")
1687 (font-lock-append-text-property 0 (length str) 'face 'default str)
1690 (defun company--create-lines (selection limit)
1692 (let ((len company-candidates-length)
1701 ;; Scroll to offset.
1702 (setq limit (company-pseudo-tooltip-update-offset selection len limit))
1704 (when (> company-tooltip-offset 0)
1705 (setq previous (format "...(%d)" company-tooltip-offset)))
1707 (setq remainder (- len limit company-tooltip-offset)
1708 remainder (when (> remainder 0)
1709 (setq remainder (format "...(%d)" remainder))))
1711 (decf selection company-tooltip-offset)
1712 (setq width (max (length previous) (length remainder))
1713 lines (nthcdr company-tooltip-offset company-candidates)
1718 (setq width (max (length (pop lines-copy)) width)))
1719 (setq width (min width (window-width)))
1721 (setq lines-copy lines)
1723 ;; number can make tooltip too long
1724 (when company-show-numbers
1725 (setq numbered company-tooltip-offset))
1728 (push (propertize (company-safe-substring previous 0 width)
1729 'face 'company-tooltip)
1733 (push (company-fill-propertize
1734 (if (>= numbered 10)
1735 (company-reformat (pop lines))
1738 (company-safe-substring (company-reformat (pop lines))
1741 width (equal i selection))
1745 (push (propertize (company-safe-substring remainder 0 width)
1746 'face 'company-tooltip)
1749 (setq lines (nreverse new))))
1753 (defsubst company--window-inner-height ()
1754 (let ((edges (window-inside-edges (selected-window))))
1755 (- (nth 3 edges) (nth 1 edges))))
1757 (defsubst company--pseudo-tooltip-height ()
1758 "Calculate the appropriate tooltip height.
1759 Returns a negative number if the tooltip should be displayed above point."
1760 (let* ((lines (company--row))
1761 (below (- (company--window-inner-height) 1 lines)))
1762 (if (and (< below (min company-tooltip-minimum company-candidates-length))
1764 (- (max 3 (min company-tooltip-limit lines)))
1765 (max 3 (min company-tooltip-limit below)))))
1767 (defun company-pseudo-tooltip-show (row column selection)
1768 (company-pseudo-tooltip-hide)
1773 (let* ((height (company--pseudo-tooltip-height))
1777 (setq row (+ row height -1)
1780 (let* ((nl (< (move-to-window-line row) row))
1782 (end (save-excursion
1783 (move-to-window-line (+ row (abs height)))
1785 (ov (make-overlay beg end))
1786 (args (list (mapcar 'company-untabify
1787 (company-buffer-lines beg end))
1790 (setq company-pseudo-tooltip-overlay ov)
1791 (overlay-put ov 'company-replacement-args args)
1792 (overlay-put ov 'company-before
1793 (apply 'company--replacement-string
1794 (company--create-lines selection (abs height))
1797 (overlay-put ov 'company-column column)
1798 (overlay-put ov 'company-height (abs height))))))
1800 (defun company-pseudo-tooltip-show-at-point (pos)
1801 (let ((col-row (company--col-row pos)))
1803 (company-pseudo-tooltip-show (1+ (cdr col-row)) (car col-row)
1804 company-selection))))
1806 (defun company-pseudo-tooltip-edit (lines selection)
1807 (let ((column (overlay-get company-pseudo-tooltip-overlay 'company-column))
1808 (height (overlay-get company-pseudo-tooltip-overlay 'company-height)))
1809 (overlay-put company-pseudo-tooltip-overlay 'company-before
1810 (apply 'company--replacement-string
1811 (company--create-lines selection height)
1812 (overlay-get company-pseudo-tooltip-overlay
1813 'company-replacement-args)))))
1815 (defun company-pseudo-tooltip-hide ()
1816 (when company-pseudo-tooltip-overlay
1817 (delete-overlay company-pseudo-tooltip-overlay)
1818 (setq company-pseudo-tooltip-overlay nil)))
1820 (defun company-pseudo-tooltip-hide-temporarily ()
1821 (when (overlayp company-pseudo-tooltip-overlay)
1822 (overlay-put company-pseudo-tooltip-overlay 'invisible nil)
1823 (overlay-put company-pseudo-tooltip-overlay 'before-string nil)))
1825 (defun company-pseudo-tooltip-unhide ()
1826 (when company-pseudo-tooltip-overlay
1827 (overlay-put company-pseudo-tooltip-overlay 'invisible t)
1828 (overlay-put company-pseudo-tooltip-overlay 'before-string
1829 (overlay-get company-pseudo-tooltip-overlay 'company-before))
1830 (overlay-put company-pseudo-tooltip-overlay 'window (selected-window))))
1832 (defun company-pseudo-tooltip-guard ()
1833 (buffer-substring-no-properties
1834 (point) (overlay-start company-pseudo-tooltip-overlay)))
1836 (defun company-pseudo-tooltip-frontend (command)
1837 "A `company-mode' front-end similar to a tool-tip but based on overlays."
1839 (pre-command (company-pseudo-tooltip-hide-temporarily))
1841 (let ((old-height (if (overlayp company-pseudo-tooltip-overlay)
1842 (overlay-get company-pseudo-tooltip-overlay
1845 (new-height (company--pseudo-tooltip-height)))
1846 (unless (and (>= (* old-height new-height) 0)
1847 (>= (abs old-height) (abs new-height))
1848 (equal (company-pseudo-tooltip-guard)
1849 (overlay-get company-pseudo-tooltip-overlay
1852 (company-pseudo-tooltip-show-at-point (- (point)
1853 (length company-prefix)))
1854 (overlay-put company-pseudo-tooltip-overlay
1855 'company-guard (company-pseudo-tooltip-guard))))
1856 (company-pseudo-tooltip-unhide))
1857 (hide (company-pseudo-tooltip-hide)
1858 (setq company-tooltip-offset 0))
1859 (update (when (overlayp company-pseudo-tooltip-overlay)
1860 (company-pseudo-tooltip-edit company-candidates
1861 company-selection)))))
1863 (defun company-pseudo-tooltip-unless-just-one-frontend (command)
1864 "`company-pseudo-tooltip-frontend', but not shown for single candidates."
1865 (unless (and (eq command 'post-command)
1866 (not (cdr company-candidates)))
1867 (company-pseudo-tooltip-frontend command)))
1869 ;;; overlay ;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;
1871 (defvar company-preview-overlay nil)
1872 (make-variable-buffer-local 'company-preview-overlay)
1874 (defun company-preview-show-at-point (pos)
1875 (company-preview-hide)
1877 (setq company-preview-overlay (make-overlay pos pos))
1879 (let ((completion(nth company-selection company-candidates)))
1880 (setq completion (propertize completion 'face 'company-preview))
1881 (add-text-properties 0 (length company-common)
1882 '(face company-preview-common) completion)
1884 ;; Add search string
1885 (and company-search-string
1886 (string-match (regexp-quote company-search-string) completion)
1887 (add-text-properties (match-beginning 0)
1889 '(face company-preview-search)
1892 (setq completion (company-strip-prefix completion))
1894 (and (equal pos (point))
1895 (not (equal completion ""))
1896 (add-text-properties 0 1 '(cursor t) completion))
1898 (overlay-put company-preview-overlay 'after-string completion)
1899 (overlay-put company-preview-overlay 'window (selected-window))))
1901 (defun company-preview-hide ()
1902 (when company-preview-overlay
1903 (delete-overlay company-preview-overlay)
1904 (setq company-preview-overlay nil)))
1906 (defun company-preview-frontend (command)
1907 "A `company-mode' front-end showing the selection as if it had been inserted."
1909 (pre-command (company-preview-hide))
1910 (post-command (company-preview-show-at-point (point)))
1911 (hide (company-preview-hide))))
1913 (defun company-preview-if-just-one-frontend (command)
1914 "`company-preview-frontend', but only shown for single candidates."
1915 (unless (and (eq command 'post-command)
1916 (cdr company-candidates))
1917 (company-preview-frontend command)))
1919 ;;; echo ;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;
1921 (defvar company-echo-last-msg nil)
1922 (make-variable-buffer-local 'company-echo-last-msg)
1924 (defvar company-echo-timer nil)
1926 (defvar company-echo-delay .01)
1928 (defun company-echo-show (&optional getter)
1930 (setq company-echo-last-msg (funcall getter)))
1931 (let ((message-log-max nil))
1932 (if company-echo-last-msg
1933 (message "%s" company-echo-last-msg)
1936 (defsubst company-echo-show-soon (&optional getter)
1937 (when company-echo-timer
1938 (cancel-timer company-echo-timer))
1939 (setq company-echo-timer (run-with-timer 0 nil 'company-echo-show getter)))
1941 (defsubst company-echo-show-when-idle (&optional getter)
1943 (company-echo-show getter)))
1945 (defsubst company-echo-show-when-not-busy (&optional getter)
1946 "Run `company-echo-show' with arg GETTER once Emacs isn't busy."
1947 (when (sit-for company-echo-delay)
1948 (company-echo-show getter)))
1950 (defun company-echo-format ()
1952 (let ((limit (window-width (minibuffer-window)))
1954 ;; Roll to selection.
1955 (candidates (nthcdr company-selection company-candidates))
1956 (i (if company-show-numbers company-selection 99999))
1960 (setq comp (company-reformat (pop candidates))
1961 len (+ len 1 (length comp)))
1965 (setq comp (propertize (format "%d: %s" i comp)
1966 'face 'company-echo))
1969 (add-text-properties 3 (+ 3 (length company-common))
1970 '(face company-echo-common) comp))
1971 (setq comp (propertize comp 'face 'company-echo))
1972 (add-text-properties 0 (length company-common)
1973 '(face company-echo-common) comp))
1975 (setq candidates nil)
1978 (mapconcat 'identity (nreverse msg) " ")))
1980 (defun company-echo-strip-common-format ()
1982 (let ((limit (window-width (minibuffer-window)))
1983 (len (+ (length company-prefix) 2))
1984 ;; Roll to selection.
1985 (candidates (nthcdr company-selection company-candidates))
1986 (i (if company-show-numbers company-selection 99999))
1990 (setq comp (company-strip-prefix (pop candidates))
1991 len (+ len 2 (length comp)))
1994 (setq comp (format "%s (%d)" comp i))
1998 (setq candidates nil)
1999 (push (propertize comp 'face 'company-echo) msg)))
2001 (concat (propertize company-prefix 'face 'company-echo-common) "{"
2002 (mapconcat 'identity (nreverse msg) ", ")
2005 (defun company-echo-hide ()
2006 (unless (equal company-echo-last-msg "")
2007 (setq company-echo-last-msg "")
2008 (company-echo-show)))
2010 (defun company-echo-frontend (command)
2011 "A `company-mode' front-end showing the candidates in the echo area."
2013 (post-command (company-echo-show-soon 'company-echo-format))
2014 (hide (company-echo-hide))))
2016 (defun company-echo-strip-common-frontend (command)
2017 "A `company-mode' front-end showing the candidates in the echo area."
2019 (post-command (company-echo-show-soon 'company-echo-strip-common-format))
2020 (hide (company-echo-hide))))
2022 (defun company-echo-metadata-frontend (command)
2023 "A `company-mode' front-end showing the documentation in the echo area."
2025 (post-command (company-echo-show-when-idle 'company-fetch-metadata))
2026 (hide (company-echo-hide))))
2029 ;;; company.el ends here