1 ;;; company.el --- Modular in-buffer completion framework -*- lexical-binding: t -*-
3 ;; Copyright (C) 2009-2014 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.io/
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 ;; FIXME: Use `user-error'.
75 (add-to-list 'debug-ignored-errors "^.* frontend cannot be used twice$")
76 (add-to-list 'debug-ignored-errors "^Echo area cannot be used twice$")
77 (add-to-list 'debug-ignored-errors "^No \\(document\\|loc\\)ation available$")
78 (add-to-list 'debug-ignored-errors "^Company not ")
79 (add-to-list 'debug-ignored-errors "^No candidate number ")
80 (add-to-list 'debug-ignored-errors "^Cannot complete at point$")
81 (add-to-list 'debug-ignored-errors "^No other back-end$")
84 "Extensible inline text completion mechanism"
89 (defface company-tooltip
90 '((default :foreground "black")
91 (((class color) (min-colors 88) (background light))
92 (:background "cornsilk"))
93 (((class color) (min-colors 88) (background dark))
94 (:background "yellow")))
95 "Face used for the tooltip.")
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 tooltip.")
106 (defface company-tooltip-mouse
107 '((default :inherit highlight))
108 "Face used for the tooltip item under the mouse.")
110 (defface company-tooltip-common
111 '((default :inherit company-tooltip)
112 (((background light))
113 :foreground "darkred")
116 "Face used for the common completion in the tooltip.")
118 (defface company-tooltip-common-selection
119 '((default :inherit company-tooltip-selection)
120 (((background light))
121 :foreground "darkred")
124 "Face used for the selected common completion in the tooltip.")
126 (defface company-preview
127 '((t :background "blue4"
128 :foreground "wheat"))
129 "Face used for the completion preview.")
131 (defface company-preview-common
132 '((t :inherit company-preview
134 "Face used for the common part of the completion preview.")
136 (defface company-preview-search
137 '((t :inherit company-preview
138 :background "blue1"))
139 "Face used for the search string in the completion preview.")
141 (defface company-echo nil
142 "Face used for completions in the echo area.")
144 (defface company-echo-common
145 '((((background dark)) (:foreground "firebrick1"))
146 (((background light)) (:background "firebrick4")))
147 "Face used for the common part of completions in the echo area.")
149 (defun company-frontends-set (variable value)
151 (let ((remainder value))
152 (setcdr remainder (delq (car remainder) (cdr remainder))))
153 (and (memq 'company-pseudo-tooltip-unless-just-one-frontend value)
154 (memq 'company-pseudo-tooltip-frontend value)
155 (error "Pseudo tooltip frontend cannot be used twice"))
156 (and (memq 'company-preview-if-just-one-frontend value)
157 (memq 'company-preview-frontend value)
158 (error "Preview frontend cannot be used twice"))
159 (and (memq 'company-echo value)
160 (memq 'company-echo-metadata-frontend value)
161 (error "Echo area cannot be used twice"))
162 ;; preview must come last
163 (dolist (f '(company-preview-if-just-one-frontend company-preview-frontend))
165 (setq value (append (delq f value) (list f)))))
166 (set variable value))
168 (defcustom company-frontends '(company-pseudo-tooltip-unless-just-one-frontend
169 company-preview-if-just-one-frontend
170 company-echo-metadata-frontend)
171 "The list of active front-ends (visualizations).
172 Each front-end is a function that takes one argument. It is called with
173 one of the following arguments:
175 `show': When the visualization should start.
177 `hide': When the visualization should end.
179 `update': When the data has been updated.
181 `pre-command': Before every command that is executed while the
182 visualization is active.
184 `post-command': After every command that is executed while the
185 visualization is active.
187 The visualized data is stored in `company-prefix', `company-candidates',
188 `company-common', `company-selection', `company-point' and
189 `company-search-string'."
190 :set 'company-frontends-set
191 :type '(repeat (choice (const :tag "echo" company-echo-frontend)
192 (const :tag "echo, strip common"
193 company-echo-strip-common-frontend)
194 (const :tag "show echo meta-data in echo"
195 company-echo-metadata-frontend)
196 (const :tag "pseudo tooltip"
197 company-pseudo-tooltip-frontend)
198 (const :tag "pseudo tooltip, multiple only"
199 company-pseudo-tooltip-unless-just-one-frontend)
200 (const :tag "preview" company-preview-frontend)
201 (const :tag "preview, unique only"
202 company-preview-if-just-one-frontend)
203 (function :tag "custom function" nil))))
205 (defcustom company-tooltip-limit 10
206 "The maximum number of candidates in the tooltip"
209 (defcustom company-tooltip-minimum 6
210 "The minimum height of the tooltip.
211 If this many lines are not available, prefer to display the tooltip above."
214 (defcustom company-tooltip-margin 1
215 "Width of margin columns to show around the toolip."
218 (defvar company-safe-backends
219 '((company-abbrev . "Abbrev")
220 (company-capf . "completion-at-point-functions")
221 (company-clang . "Clang")
222 (company-cmake . "CMake")
223 (company-css . "CSS")
224 (company-dabbrev . "dabbrev for plain text")
225 (company-dabbrev-code . "dabbrev for code")
226 (company-eclim . "Eclim (an Eclipse interface)")
227 (company-elisp . "Emacs Lisp")
228 (company-etags . "etags")
229 (company-files . "Files")
230 (company-gtags . "GNU Global")
231 (company-ispell . "Ispell")
232 (company-keywords . "Programming language keywords")
233 (company-nxml . "nxml")
234 (company-oddmuse . "Oddmuse")
235 (company-pysmell . "PySmell")
236 (company-ropemacs . "ropemacs")
237 (company-semantic . "Semantic")
238 (company-tempo . "Tempo templates")
239 (company-xcode . "Xcode")))
240 (put 'company-safe-backends 'risky-local-variable t)
242 (defun company-safe-backends-p (backends)
243 (and (consp backends)
244 (not (dolist (backend backends)
245 (unless (if (consp backend)
246 (company-safe-backends-p backend)
247 (assq backend company-safe-backends))
250 (defvar company--include-capf (version< "24.3.50" emacs-version))
252 (defcustom company-backends `(,@(unless company--include-capf
253 (list 'company-elisp))
254 company-nxml company-css
255 company-eclim company-semantic company-clang
256 company-xcode company-ropemacs company-cmake
257 ,@(when company--include-capf
258 (list 'company-capf))
259 (company-gtags company-etags company-dabbrev-code
261 company-oddmuse company-files company-dabbrev)
262 "The list of active back-ends (completion engines).
263 Each list elements can itself be a list of back-ends. In that case their
264 completions are merged. Otherwise only the first matching back-end returns
267 `company-begin-backend' can be used to start a specific back-end,
268 `company-other-backend' will skip to the next matching back-end in the list.
270 Each back-end is a function that takes a variable number of arguments.
271 The first argument is the command requested from the back-end. It is one
274 `prefix': The back-end should return the text to be completed. It must be
275 text immediately before point. Returning nil passes control to the next
276 back-end. The function should return `stop' if it should complete but
277 cannot \(e.g. if it is in the middle of a string\). Instead of a string,
278 the back-end may return a cons where car is the prefix and cdr is used in
279 `company-minimum-prefix-length' test. It's either number or t, in which
280 case the test automatically succeeds.
282 `candidates': The second argument is the prefix to be completed. The
283 return value should be a list of candidates that start with the prefix.
287 `sorted': Return t here to indicate that the candidates are sorted and will
288 not need to be sorted again.
290 `duplicates': If non-nil, company will take care of removing duplicates
293 `no-cache': Usually company doesn't ask for candidates again as completion
294 progresses, unless the back-end returns t for this command. The second
295 argument is the latest prefix.
297 `meta': The second argument is a completion candidate. Return a (short)
298 documentation string for it.
300 `doc-buffer': The second argument is a completion candidate. Return a
301 buffer with documentation for it. Preferably use `company-doc-buffer',
303 `location': The second argument is a completion candidate. Return the cons
304 of buffer and buffer location, or of file and line number where the
305 completion candidate was defined.
307 `require-match': If this returns t, the user is not allowed to enter
308 anything not offered as a candidate. Use with care! The default value nil
309 gives the user that choice with `company-require-match'. Return value
310 `never' overrides that option the other way around.
312 `init': Called once for each buffer. The back-end can check for external
313 programs and files and load any required libraries. Raising an error here
314 will show up in message log once, and the back-end will not be used for
317 `post-completion': Called after a completion candidate has been inserted
318 into the buffer. The second argument is the candidate. Can be used to
319 modify it, e.g. to expand a snippet.
321 The back-end should return nil for all commands it does not support or
322 does not know about. It should also be callable interactively and use
323 `company-begin-backend' to start itself in that case."
327 ,@(mapcar (lambda (b) `(const :tag ,(cdr b) ,(car b)))
328 company-safe-backends)
329 (symbol :tag "User defined")
330 (repeat :tag "Merged Back-ends"
331 (choice :tag "Back-end"
332 ,@(mapcar (lambda (b)
333 `(const :tag ,(cdr b) ,(car b)))
334 company-safe-backends)
335 (symbol :tag "User defined"))))))
337 (put 'company-backends 'safe-local-variable 'company-safe-backends-p)
339 (defcustom company-completion-started-hook nil
340 "Hook run when company starts completing.
341 The hook is called with one argument that is non-nil if the completion was
345 (defcustom company-completion-cancelled-hook nil
346 "Hook run when company cancels completing.
347 The hook is called with one argument that is non-nil if the completion was
351 (defcustom company-completion-finished-hook nil
352 "Hook run when company successfully completes.
353 The hook is called with the selected candidate as an argument.
355 If you indend to use it to post-process candidates from a specific
356 back-end, consider using the `post-completion' command instead."
359 (defcustom company-minimum-prefix-length 3
360 "The minimum prefix length for idle completion."
361 :type '(integer :tag "prefix length"))
363 (defcustom company-require-match 'company-explicit-action-p
364 "If enabled, disallow non-matching input.
365 This can be a function do determine if a match is required.
367 This can be overridden by the back-end, if it returns t or `never' to
368 `require-match'. `company-auto-complete' also takes precedence over this."
369 :type '(choice (const :tag "Off" nil)
370 (function :tag "Predicate function")
371 (const :tag "On, if user interaction took place"
372 'company-explicit-action-p)
373 (const :tag "On" t)))
375 (defcustom company-auto-complete nil
376 "Determines when to auto-complete.
377 If this is enabled, all characters from `company-auto-complete-chars'
378 trigger insertion of the selected completion candidate.
379 This can also be a function."
380 :type '(choice (const :tag "Off" nil)
381 (function :tag "Predicate function")
382 (const :tag "On, if user interaction took place"
383 'company-explicit-action-p)
384 (const :tag "On" t)))
386 (defcustom company-auto-complete-chars '(?\ ?\) ?.)
387 "Determines which characters trigger auto-completion.
388 See `company-auto-complete'. If this is a string, each string character
389 tiggers auto-completion. If it is a list of syntax description characters (see
390 `modify-syntax-entry'), all characters with that syntax auto-complete.
392 This can also be a function, which is called with the new input and should
393 return non-nil if company should auto-complete.
395 A character that is part of a valid candidate never triggers auto-completion."
396 :type '(choice (string :tag "Characters")
398 (const :tag "Whitespace" ?\ )
399 (const :tag "Symbol" ?_)
400 (const :tag "Opening parentheses" ?\()
401 (const :tag "Closing parentheses" ?\))
402 (const :tag "Word constituent" ?w)
403 (const :tag "Punctuation." ?.)
404 (const :tag "String quote." ?\")
405 (const :tag "Paired delimiter." ?$)
406 (const :tag "Expression quote or prefix operator." ?\')
407 (const :tag "Comment starter." ?<)
408 (const :tag "Comment ender." ?>)
409 (const :tag "Character-quote." ?/)
410 (const :tag "Generic string fence." ?|)
411 (const :tag "Generic comment fence." ?!))
412 (function :tag "Predicate function")))
414 (defcustom company-idle-delay .7
415 "The idle delay in seconds until completion starts automatically.
416 A value of nil means no idle completion, t means show candidates
417 immediately when a prefix of `company-minimum-prefix-length' is reached."
418 :type '(choice (const :tag "never (nil)" nil)
419 (const :tag "immediate (t)" t)
420 (number :tag "seconds")))
422 (defcustom company-begin-commands '(self-insert-command)
423 "A list of commands after which idle completion is allowed.
424 If this is t, it can show completions after any command. See
425 `company-idle-delay'.
427 Alternatively, any command with a non-nil `company-begin' property is
428 treated as if it was on this list."
429 :type '(choice (const :tag "Any command" t)
430 (const :tag "Self insert command" '(self-insert-command))
431 (repeat :tag "Commands" function)))
433 (defcustom company-show-numbers nil
434 "If enabled, show quick-access numbers for the first ten candidates."
435 :type '(choice (const :tag "off" nil)
436 (const :tag "on" t)))
438 (defcustom company-selection-wrap-around nil
439 "If enabled, selecting item before first or after last wraps around."
440 :type '(choice (const :tag "off" nil)
441 (const :tag "on" t)))
443 (defvar company-end-of-buffer-workaround t
444 "Work around a visualization bug when completing at the end of the buffer.
445 The work-around consists of adding a newline.")
447 ;;; mode ;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;
449 (defvar company-mode-map (make-sparse-keymap)
450 "Keymap used by `company-mode'.")
452 (defvar company-active-map
453 (let ((keymap (make-sparse-keymap)))
454 (define-key keymap "\e\e\e" 'company-abort)
455 (define-key keymap "\C-g" 'company-abort)
456 (define-key keymap (kbd "M-n") 'company-select-next)
457 (define-key keymap (kbd "M-p") 'company-select-previous)
458 (define-key keymap (kbd "<down>") 'company-select-next-or-abort)
459 (define-key keymap (kbd "<up>") 'company-select-previous-or-abort)
460 (define-key keymap [down-mouse-1] 'ignore)
461 (define-key keymap [down-mouse-3] 'ignore)
462 (define-key keymap [mouse-1] 'company-complete-mouse)
463 (define-key keymap [mouse-3] 'company-select-mouse)
464 (define-key keymap [up-mouse-1] 'ignore)
465 (define-key keymap [up-mouse-3] 'ignore)
466 (define-key keymap [return] 'company-complete-selection)
467 (define-key keymap (kbd "RET") 'company-complete-selection)
468 (define-key keymap [tab] 'company-complete-common)
469 (define-key keymap (kbd "TAB") 'company-complete-common)
470 (define-key keymap (kbd "<f1>") 'company-show-doc-buffer)
471 (define-key keymap "\C-w" 'company-show-location)
472 (define-key keymap "\C-s" 'company-search-candidates)
473 (define-key keymap "\C-\M-s" 'company-filter-candidates)
475 (define-key keymap (vector (+ (aref (kbd "M-0") 0) i))
476 `(lambda () (interactive) (company-complete-number ,i))))
479 "Keymap that is enabled during an active completion.")
481 (defvar company--disabled-backends nil)
483 (defun company-init-backend (backend)
484 (and (symbolp backend)
485 (not (fboundp backend))
486 (ignore-errors (require backend nil t)))
488 (if (or (symbolp backend)
492 (funcall backend 'init)
493 (put backend 'company-init t))
495 (put backend 'company-init 'failed)
496 (unless (memq backend company--disabled-backends)
497 (message "Company back-end '%s' could not be initialized:\n%s"
498 backend (error-message-string err)))
499 (pushnew backend company--disabled-backends)
501 (mapc 'company-init-backend backend)))
503 (defvar company-default-lighter " company")
505 (defvar company-lighter company-default-lighter)
506 (make-variable-buffer-local 'company-lighter)
509 (define-minor-mode company-mode
510 "\"complete anything\"; is an in-buffer completion framework.
511 Completion starts automatically, depending on the values
512 `company-idle-delay' and `company-minimum-prefix-length'.
514 Completion can be controlled with the commands:
515 `company-complete-common', `company-complete-selection', `company-complete',
516 `company-select-next', `company-select-previous'. If these commands are
517 called before `company-idle-delay', completion will also start.
519 Completions can be searched with `company-search-candidates' or
520 `company-filter-candidates'. These can be used while completion is
523 The completion data is retrieved using `company-backends' and displayed
524 using `company-frontends'. If you want to start a specific back-end, call
525 it interactively or use `company-begin-backend'.
527 regular keymap (`company-mode-map'):
530 keymap during active completions (`company-active-map'):
532 \\{company-active-map}"
533 nil company-lighter company-mode-map
536 (add-hook 'pre-command-hook 'company-pre-command nil t)
537 (add-hook 'post-command-hook 'company-post-command nil t)
538 (mapc 'company-init-backend company-backends))
539 (remove-hook 'pre-command-hook 'company-pre-command t)
540 (remove-hook 'post-command-hook 'company-post-command t)
542 (kill-local-variable 'company-point)))
544 (defcustom company-global-modes t
545 "Modes for which `company-mode' mode is turned on by `global-company-mode'.
546 If nil, means no modes. If t, then all major modes have it turned on.
547 If a list, it should be a list of `major-mode' symbol names for which
548 `company-mode' should be automatically turned on. The sense of the list is
549 negated if it begins with `not'. For example:
551 means that `company-mode' is turned on for buffers in C and C++ modes only.
553 means that `company-mode' is always turned on except in `message-mode' buffers."
554 :type '(choice (const :tag "none" nil)
556 (set :menu-tag "mode specific" :tag "modes"
558 (const :tag "Except" not)
559 (repeat :inline t (symbol :tag "mode")))))
562 (define-globalized-minor-mode global-company-mode company-mode company-mode-on)
564 (defun company-mode-on ()
565 (when (and (not (or noninteractive (eq (aref (buffer-name) 0) ?\s)))
566 (cond ((eq company-global-modes t)
568 ((eq (car-safe company-global-modes) 'not)
569 (not (memq major-mode (cdr company-global-modes))))
570 (t (memq major-mode company-global-modes))))
573 (defsubst company-assert-enabled ()
575 (company-uninstall-map)
576 (error "Company not enabled")))
578 ;;; keymaps ;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;
580 (defvar company-my-keymap nil)
581 (make-variable-buffer-local 'company-my-keymap)
583 (defvar company-emulation-alist '((t . nil)))
585 (defsubst company-enable-overriding-keymap (keymap)
586 (company-uninstall-map)
587 (setq company-my-keymap keymap))
589 (defun company-ensure-emulation-alist ()
590 (unless (eq 'company-emulation-alist (car emulation-mode-map-alists))
591 (setq emulation-mode-map-alists
592 (cons 'company-emulation-alist
593 (delq 'company-emulation-alist emulation-mode-map-alists)))))
595 (defun company-install-map ()
596 (unless (or (cdar company-emulation-alist)
597 (null company-my-keymap))
598 (setf (cdar company-emulation-alist) company-my-keymap)))
600 (defun company-uninstall-map ()
601 (setf (cdar company-emulation-alist) nil))
604 ;; Emacs calculates the active keymaps before reading the event. That means we
605 ;; cannot change the keymap from a timer. So we send a bogus command.
606 (defun company-ignore ()
608 (setq this-command last-command))
610 (global-set-key '[31415926] 'company-ignore)
612 (defun company-input-noop ()
613 (push 31415926 unread-command-events))
615 (defun company--column (&optional pos)
617 (when pos (goto-char pos))
621 (narrow-to-region (point) (point-max))
622 (let ((prefix (get-text-property (point) 'line-prefix)))
623 (if prefix (length prefix) 0)))
626 (defun company--row (&optional pos)
628 (when pos (goto-char pos))
629 (count-screen-lines (window-start)
630 (progn (vertical-motion 0) (point)))))
632 ;;; backends ;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;
634 (defvar company-backend nil)
635 (make-variable-buffer-local 'company-backend)
637 (defun company-grab (regexp &optional expression limit)
638 (when (looking-back regexp limit)
639 (or (match-string-no-properties (or expression 0)) "")))
641 (defun company-grab-line (regexp &optional expression)
642 (company-grab regexp expression (point-at-bol)))
644 (defun company-grab-symbol ()
645 (if (looking-at "\\_>")
646 (buffer-substring (point) (save-excursion (skip-syntax-backward "w_")
648 (unless (and (char-after) (memq (char-syntax (char-after)) '(?w ?_)))
651 (defun company-grab-word ()
652 (if (looking-at "\\>")
653 (buffer-substring (point) (save-excursion (skip-syntax-backward "w")
655 (unless (and (char-after) (eq (char-syntax (char-after)) ?w))
658 (defun company-in-string-or-comment ()
659 (let ((ppss (syntax-ppss)))
660 (or (car (setq ppss (nthcdr 3 ppss)))
661 (car (setq ppss (cdr ppss)))
664 (if (fboundp 'locate-dominating-file)
665 (defalias 'company-locate-dominating-file 'locate-dominating-file)
666 (defun company-locate-dominating-file (file name)
668 (let ((dir (file-name-directory file))
670 (while (not (equal dir prev-dir))
671 (when (file-exists-p (expand-file-name name dir))
674 dir (file-name-directory (directory-file-name dir))))))))
676 (defun company-call-backend (&rest args)
677 (if (functionp company-backend)
678 (apply company-backend args)
679 (apply 'company--multi-backend-adapter company-backend args)))
681 (defun company--multi-backend-adapter (backends command &rest args)
682 (let ((backends (loop for b in backends
683 when (not (and (symbolp b)
684 (eq 'failed (get b 'company-init))))
688 (loop for backend in backends
689 when (equal (funcall backend 'prefix)
691 append (apply backend 'candidates args)))
696 (dolist (backend backends)
697 (when (setq value (apply backend command args))
698 (return value))))))))
700 ;;; completion mechanism ;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;
702 (defvar company-prefix nil)
703 (make-variable-buffer-local 'company-prefix)
705 (defvar company-candidates nil)
706 (make-variable-buffer-local 'company-candidates)
708 (defvar company-candidates-length nil)
709 (make-variable-buffer-local 'company-candidates-length)
711 (defvar company-candidates-cache nil)
712 (make-variable-buffer-local 'company-candidates-cache)
714 (defvar company-candidates-predicate nil)
715 (make-variable-buffer-local 'company-candidates-predicate)
717 (defvar company-common nil)
718 (make-variable-buffer-local 'company-common)
720 (defvar company-selection 0)
721 (make-variable-buffer-local 'company-selection)
723 (defvar company-selection-changed nil)
724 (make-variable-buffer-local 'company-selection-changed)
726 (defvar company--explicit-action nil
727 "Non-nil, if explicit completion took place.")
728 (make-variable-buffer-local 'company--explicit-action)
730 (defvar company--auto-completion nil
731 "Non-nil when current candidate is being inserted automatically.
732 Controlled by `company-auto-complete'.")
734 (defvar company--point-max nil)
735 (make-variable-buffer-local 'company--point-max)
737 (defvar company-point nil)
738 (make-variable-buffer-local 'company-point)
740 (defvar company-timer nil)
742 (defvar company-added-newline nil)
743 (make-variable-buffer-local 'company-added-newline)
745 (defsubst company-strip-prefix (str)
746 (substring str (length company-prefix)))
748 (defun company--insert-candidate (candidate)
749 ;; XXX: Return value we check here is subject to change.
750 (set-text-properties 0 (length candidate) nil candidate)
751 (if (eq (company-call-backend 'ignore-case) 'keep-prefix)
752 (insert (company-strip-prefix candidate))
753 (delete-region (- (point) (length company-prefix)) (point))
756 (defmacro company-with-candidate-inserted (candidate &rest body)
757 "Evaluate BODY with CANDIDATE temporarily inserted.
758 This is a tool for back-ends that need candidates inserted before they
759 can retrieve meta-data for them."
761 `(let ((inhibit-modification-hooks t)
762 (inhibit-point-motion-hooks t)
763 (modified-p (buffer-modified-p)))
764 (company--insert-candidate ,candidate)
767 (delete-region company-point (point)))))
769 (defun company-explicit-action-p ()
770 "Return whether explicit completion action was taken by the user."
771 (or company--explicit-action
772 company-selection-changed))
774 (defun company-reformat (candidate)
775 ;; company-ispell needs this, because the results are always lower-case
776 ;; It's mory efficient to fix it only when they are displayed.
777 ;; FIXME: Adopt the current text's capitalization instead?
778 (if (eq (company-call-backend 'ignore-case) 'keep-prefix)
779 (concat company-prefix (substring candidate (length company-prefix)))
782 (defun company--should-complete ()
783 (and (not (or buffer-read-only overriding-terminal-local-map
784 overriding-local-map))
785 ;; Check if in the middle of entering a key combination.
786 (or (equal (this-command-keys-vector) [])
787 (not (keymapp (key-binding (this-command-keys-vector)))))
788 (eq company-idle-delay t)
789 (or (eq t company-begin-commands)
790 (memq this-command company-begin-commands)
791 (and (symbolp this-command) (get this-command 'company-begin)))
792 (not (and transient-mark-mode mark-active))))
794 (defun company-call-frontends (command)
795 (dolist (frontend company-frontends)
797 (funcall frontend command)
798 (error (error "Company: Front-end %s error \"%s\" on command %s"
799 frontend (error-message-string err) command)))))
801 (defun company-set-selection (selection &optional force-update)
803 (if company-selection-wrap-around
804 (mod selection company-candidates-length)
805 (max 0 (min (1- company-candidates-length) selection))))
806 (when (or force-update (not (equal selection company-selection)))
807 (setq company-selection selection
808 company-selection-changed t)
809 (company-call-frontends 'update)))
811 (defun company-apply-predicate (candidates predicate)
813 (dolist (c candidates)
814 (when (funcall predicate c)
818 (defun company-update-candidates (candidates)
819 (setq company-candidates-length (length candidates))
820 (if (> company-selection 0)
821 ;; Try to restore the selection
822 (let ((selected (nth company-selection company-candidates)))
823 (setq company-selection 0
824 company-candidates candidates)
826 (while (and candidates (string< (pop candidates) selected))
827 (incf company-selection))
829 ;; Make sure selection isn't out of bounds.
830 (setq company-selection (min (1- company-candidates-length)
831 company-selection)))))
832 (setq company-selection 0
833 company-candidates candidates))
835 (push (cons company-prefix company-candidates) company-candidates-cache)
837 (let ((completion-ignore-case (company-call-backend 'ignore-case)))
838 ;; We want to support non-prefix completion, so filtering is the
839 ;; responsibility of each respective backend, not ours.
840 ;; On the other hand, we don't want to replace non-prefix input in
841 ;; `company-complete-common'.
843 (if (cdr company-candidates)
844 (company--safe-candidate
845 (try-completion company-prefix company-candidates))
846 (car company-candidates)))))
848 (defun company--safe-candidate (str)
849 (or (company-call-backend 'crop str)
852 (defun company-calculate-candidates (prefix)
853 (let ((candidates (cdr (assoc prefix company-candidates-cache)))
854 (ignore-case (company-call-backend 'ignore-case)))
856 (when company-candidates-cache
857 (let ((len (length prefix))
858 (completion-ignore-case ignore-case)
860 (dotimes (i (1+ len))
861 (when (setq prev (cdr (assoc (substring prefix 0 (- len i))
862 company-candidates-cache)))
863 (setq candidates (all-completions prefix prev))
865 ;; no cache match, call back-end
867 (setq candidates (company-call-backend 'candidates prefix))
868 (when company-candidates-predicate
870 (company-apply-predicate candidates
871 company-candidates-predicate)))
872 (unless (company-call-backend 'sorted)
873 (setq candidates (sort candidates 'string<)))
874 (when (company-call-backend 'duplicates)
876 (let ((c2 candidates))
878 (setcdr c2 (progn (while (equal (pop c2) (car c2)))
881 (if (or (cdr candidates)
882 (not (eq t (compare-strings (car candidates) nil nil
883 prefix nil nil ignore-case))))
885 ;; Already completed and unique; don't start.
888 (defun company-idle-begin (buf win tick pos)
890 (eq buf (current-buffer))
891 (eq win (selected-window))
892 (eq tick (buffer-chars-modified-tick))
894 (not company-candidates)
895 (not (equal (point) company-point))
896 (let ((company-idle-delay t)
897 (company-begin-commands t))
899 (when company-candidates
901 (company-post-command)))))
903 (defun company-auto-begin ()
904 (company-assert-enabled)
906 (not company-candidates)
907 (let ((company-idle-delay t)
908 (company-minimum-prefix-length 0)
909 (company-begin-commands t))
911 ;; Return non-nil if active.
914 (defun company-manual-begin ()
916 (setq company--explicit-action t)
919 (unless company-candidates
920 (setq company--explicit-action nil))))
922 (defun company-other-backend (&optional backward)
923 (interactive (list current-prefix-arg))
924 (company-assert-enabled)
926 (let* ((after (cdr (member company-backend company-backends)))
927 (before (cdr (member company-backend (reverse company-backends))))
929 (append before (reverse after))
930 (append after (reverse before)))))
932 (dolist (backend next)
933 (when (ignore-errors (company-begin-backend backend))
935 (company-manual-begin))
936 (unless company-candidates
937 (error "No other back-end")))
939 (defun company-require-match-p ()
940 (let ((backend-value (company-call-backend 'require-match)))
941 (or (eq backend-value t)
942 (and (not (eq backend-value 'never))
943 (if (functionp company-require-match)
944 (funcall company-require-match)
945 (eq company-require-match t))))))
947 (defun company-auto-complete-p (input)
948 "Return non-nil, if input starts with punctuation or parentheses."
949 (and (if (functionp company-auto-complete)
950 (funcall company-auto-complete)
951 company-auto-complete)
952 (if (functionp company-auto-complete-chars)
953 (funcall company-auto-complete-chars input)
954 (if (consp company-auto-complete-chars)
955 (memq (char-syntax (string-to-char input))
956 company-auto-complete-chars)
957 (string-match (substring input 0 1) company-auto-complete-chars)))))
959 (defun company--incremental-p ()
960 (and (> (point) company-point)
961 (> (point-max) company--point-max)
962 (not (eq this-command 'backward-delete-char-untabify))
963 (equal (buffer-substring (- company-point (length company-prefix))
967 (defsubst company--string-incremental-p (old-prefix new-prefix)
968 (and (> (length new-prefix) (length old-prefix))
969 (equal old-prefix (substring new-prefix 0 (length old-prefix)))))
971 (defun company--continue-failed (new-prefix)
972 (when (company--incremental-p)
973 (let ((input (buffer-substring-no-properties (point) company-point)))
975 ((company-auto-complete-p input)
978 (goto-char company-point)
979 (let ((company--auto-completion t))
980 (company-complete-selection))
982 ((and (company--string-incremental-p company-prefix new-prefix)
983 (company-require-match-p))
984 ;; wrong incremental input, but required match
985 (delete-char (- (length input)))
987 (message "Matching input is required")
989 ((equal company-prefix (car company-candidates))
990 ;; last input was actually success
991 (company-cancel company-prefix)
994 (defun company--good-prefix-p (prefix)
995 (and (or (company-explicit-action-p)
996 (unless (eq prefix 'stop)
997 (or (eq (cdr-safe prefix) t)
998 (>= (or (cdr-safe prefix) (length prefix))
999 company-minimum-prefix-length))))
1000 (stringp (or (car-safe prefix) prefix))))
1002 (defun company--continue ()
1003 (when (company-call-backend 'no-cache company-prefix)
1004 ;; Don't complete existing candidates, fetch new ones.
1005 (setq company-candidates-cache nil))
1006 (let* ((new-prefix (company-call-backend 'prefix))
1007 (c (when (and (company--good-prefix-p new-prefix)
1008 (setq new-prefix (or (car-safe new-prefix) new-prefix))
1009 (= (- (point) (length new-prefix))
1010 (- company-point (length company-prefix))))
1011 (setq new-prefix (or (car-safe new-prefix) new-prefix))
1012 (company-calculate-candidates new-prefix))))
1015 ;; t means complete/unique.
1016 (company-cancel new-prefix)
1019 ;; incremental match
1020 (setq company-prefix new-prefix)
1021 (company-update-candidates c)
1023 (t (company--continue-failed new-prefix)))
1026 (defun company--begin-new ()
1028 (dolist (backend (if company-backend
1029 ;; prefer manual override
1030 (list company-backend)
1033 (if (or (symbolp backend)
1034 (functionp backend))
1035 (when (or (not (symbolp backend))
1036 (eq t (get backend 'company-init))
1037 (unless (get backend 'company-init)
1038 (company-init-backend backend)))
1039 (funcall backend 'prefix))
1040 (company--multi-backend-adapter backend 'prefix)))
1042 (when (company--good-prefix-p prefix)
1043 (setq prefix (or (car-safe prefix) prefix)
1044 company-backend backend
1045 c (company-calculate-candidates prefix))
1046 ;; t means complete/unique. We don't start, so no hooks.
1048 (when company--explicit-action
1049 (message "No completion found"))
1050 (setq company-prefix prefix)
1051 (when (symbolp backend)
1052 (setq company-lighter (concat " " (symbol-name backend))))
1053 (company-update-candidates c)
1054 (run-hook-with-args 'company-completion-started-hook
1055 (company-explicit-action-p))
1056 (company-call-frontends 'show)))
1059 (defun company-begin ()
1060 (or (and company-candidates (company--continue))
1061 (and (company--should-complete) (company--begin-new)))
1062 (when company-candidates
1063 (when (and company-end-of-buffer-workaround (eobp))
1064 (save-excursion (insert "\n"))
1065 (setq company-added-newline (buffer-chars-modified-tick)))
1066 (setq company-point (point)
1067 company--point-max (point-max))
1068 (company-ensure-emulation-alist)
1069 (company-enable-overriding-keymap company-active-map)
1070 (company-call-frontends 'update)))
1072 (defun company-cancel (&optional result)
1073 (and company-added-newline
1074 (> (point-max) (point-min))
1075 (let ((tick (buffer-chars-modified-tick)))
1076 (delete-region (1- (point-max)) (point-max))
1077 (equal tick company-added-newline))
1078 ;; Only set unmodified when tick remained the same since insert.
1079 (set-buffer-modified-p nil))
1080 (when company-prefix
1081 (if (stringp result)
1083 (company-call-backend 'pre-completion result)
1084 (run-hook-with-args 'company-completion-finished-hook result)
1085 (company-call-backend 'post-completion result))
1086 (run-hook-with-args 'company-completion-cancelled-hook result)))
1087 (setq company-added-newline nil
1090 company-candidates nil
1091 company-candidates-length nil
1092 company-candidates-cache nil
1093 company-candidates-predicate nil
1096 company-selection-changed nil
1097 company--explicit-action nil
1098 company-lighter company-default-lighter
1099 company--point-max nil
1102 (cancel-timer company-timer))
1103 (company-search-mode 0)
1104 (company-call-frontends 'hide)
1105 (company-enable-overriding-keymap nil))
1107 (defun company-abort ()
1110 ;; Don't start again, unless started manually.
1111 (setq company-point (point)))
1113 (defun company-finish (result)
1114 (company--insert-candidate result)
1115 (company-cancel result)
1116 ;; Don't start again, unless started manually.
1117 (setq company-point (point)))
1119 (defsubst company-keep (command)
1120 (and (symbolp command) (get command 'company-keep)))
1122 (defun company-pre-command ()
1123 (unless (company-keep this-command)
1125 (when company-candidates
1126 (company-call-frontends 'pre-command))
1127 (error (message "Company: An error occurred in pre-command")
1128 (message "%s" (error-message-string err))
1131 (cancel-timer company-timer)
1132 (setq company-timer nil))
1133 (company-uninstall-map))
1135 (defun company-post-command ()
1136 (unless (company-keep this-command)
1139 (unless (equal (point) company-point)
1141 (if company-candidates
1142 (company-call-frontends 'post-command)
1143 (and (numberp company-idle-delay)
1144 (or (eq t company-begin-commands)
1145 (memq this-command company-begin-commands))
1147 (run-with-timer company-idle-delay nil
1149 (current-buffer) (selected-window)
1150 (buffer-chars-modified-tick) (point))))))
1151 (error (message "Company: An error occurred in post-command")
1152 (message "%s" (error-message-string err))
1154 (company-install-map))
1156 ;;; search ;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;
1158 (defvar company-search-string nil)
1159 (make-variable-buffer-local 'company-search-string)
1161 (defvar company-search-lighter " Search: \"\"")
1162 (make-variable-buffer-local 'company-search-lighter)
1164 (defvar company-search-old-map nil)
1165 (make-variable-buffer-local 'company-search-old-map)
1167 (defvar company-search-old-selection 0)
1168 (make-variable-buffer-local 'company-search-old-selection)
1170 (defun company-search (text lines)
1171 (let ((quoted (regexp-quote text))
1173 (dolist (line lines)
1174 (when (string-match quoted line (length company-prefix))
1178 (defun company-search-printing-char ()
1180 (company-search-assert-enabled)
1181 (setq company-search-string
1182 (concat (or company-search-string "") (string last-command-event))
1183 company-search-lighter (concat " Search: \"" company-search-string
1185 (let ((pos (company-search company-search-string
1186 (nthcdr company-selection company-candidates))))
1189 (company-set-selection (+ company-selection pos) t))))
1191 (defun company-search-repeat-forward ()
1192 "Repeat the incremental search in completion candidates forward."
1194 (company-search-assert-enabled)
1195 (let ((pos (company-search company-search-string
1196 (cdr (nthcdr company-selection
1197 company-candidates)))))
1200 (company-set-selection (+ company-selection pos 1) t))))
1202 (defun company-search-repeat-backward ()
1203 "Repeat the incremental search in completion candidates backwards."
1205 (company-search-assert-enabled)
1206 (let ((pos (company-search company-search-string
1207 (nthcdr (- company-candidates-length
1209 (reverse company-candidates)))))
1212 (company-set-selection (- company-selection pos 1) t))))
1214 (defun company-create-match-predicate ()
1215 (setq company-candidates-predicate
1216 `(lambda (candidate)
1217 ,(if company-candidates-predicate
1218 `(and (string-match ,company-search-string candidate)
1219 (funcall ,company-candidates-predicate
1221 `(string-match ,company-search-string candidate))))
1222 (company-update-candidates
1223 (company-apply-predicate company-candidates company-candidates-predicate))
1224 ;; Invalidate cache.
1225 (setq company-candidates-cache (cons company-prefix company-candidates)))
1227 (defun company-filter-printing-char ()
1229 (company-search-assert-enabled)
1230 (company-search-printing-char)
1231 (company-create-match-predicate)
1232 (company-call-frontends 'update))
1234 (defun company-search-kill-others ()
1235 "Limit the completion candidates to the ones matching the search string."
1237 (company-search-assert-enabled)
1238 (company-create-match-predicate)
1239 (company-search-mode 0)
1240 (company-call-frontends 'update))
1242 (defun company-search-abort ()
1243 "Abort searching the completion candidates."
1245 (company-search-assert-enabled)
1246 (company-set-selection company-search-old-selection t)
1247 (company-search-mode 0))
1249 (defun company-search-other-char ()
1251 (company-search-assert-enabled)
1252 (company-search-mode 0)
1253 (company--unread-last-input))
1255 (defvar company-search-map
1257 (keymap (make-keymap)))
1258 (if (fboundp 'max-char)
1259 (set-char-table-range (nth 1 keymap) (cons #x100 (max-char))
1260 'company-search-printing-char)
1262 ;; obsolete in Emacs 23
1263 (let ((l (generic-character-list))
1264 (table (nth 1 keymap)))
1266 (set-char-table-default table (car l) 'company-search-printing-char)
1267 (setq l (cdr l))))))
1268 (define-key keymap [t] 'company-search-other-char)
1270 (define-key keymap (make-string 1 i) 'company-search-other-char)
1273 (define-key keymap (vector i) 'company-search-printing-char)
1275 (let ((meta-map (make-sparse-keymap)))
1276 (define-key keymap (char-to-string meta-prefix-char) meta-map)
1277 (define-key keymap [escape] meta-map))
1278 (define-key keymap (vector meta-prefix-char t) 'company-search-other-char)
1279 (define-key keymap "\e\e\e" 'company-search-other-char)
1280 (define-key keymap [escape escape escape] 'company-search-other-char)
1282 (define-key keymap "\C-g" 'company-search-abort)
1283 (define-key keymap "\C-s" 'company-search-repeat-forward)
1284 (define-key keymap "\C-r" 'company-search-repeat-backward)
1285 (define-key keymap "\C-o" 'company-search-kill-others)
1287 "Keymap used for incrementally searching the completion candidates.")
1289 (define-minor-mode company-search-mode
1290 "Search mode for completion candidates.
1291 Don't start this directly, use `company-search-candidates' or
1292 `company-filter-candidates'."
1293 nil company-search-lighter nil
1294 (if company-search-mode
1295 (if (company-manual-begin)
1297 (setq company-search-old-selection company-selection)
1298 (company-call-frontends 'update))
1299 (setq company-search-mode nil))
1300 (kill-local-variable 'company-search-string)
1301 (kill-local-variable 'company-search-lighter)
1302 (kill-local-variable 'company-search-old-selection)
1303 (company-enable-overriding-keymap company-active-map)))
1305 (defun company-search-assert-enabled ()
1306 (company-assert-enabled)
1307 (unless company-search-mode
1308 (company-uninstall-map)
1309 (error "Company not in search mode")))
1311 (defun company-search-candidates ()
1312 "Start searching the completion candidates incrementally.
1314 \\<company-search-map>Search can be controlled with the commands:
1315 - `company-search-repeat-forward' (\\[company-search-repeat-forward])
1316 - `company-search-repeat-backward' (\\[company-search-repeat-backward])
1317 - `company-search-abort' (\\[company-search-abort])
1319 Regular characters are appended to the search string.
1321 The command `company-search-kill-others' (\\[company-search-kill-others])
1322 uses the search string to limit the completion candidates."
1324 (company-search-mode 1)
1325 (company-enable-overriding-keymap company-search-map))
1327 (defvar company-filter-map
1328 (let ((keymap (make-keymap)))
1329 (define-key keymap [remap company-search-printing-char]
1330 'company-filter-printing-char)
1331 (set-keymap-parent keymap company-search-map)
1333 "Keymap used for incrementally searching the completion candidates.")
1335 (defun company-filter-candidates ()
1336 "Start filtering the completion candidates incrementally.
1337 This works the same way as `company-search-candidates' immediately
1338 followed by `company-search-kill-others' after each input."
1340 (company-search-mode 1)
1341 (company-enable-overriding-keymap company-filter-map))
1343 ;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;
1345 (defun company-select-next ()
1346 "Select the next candidate in the list."
1348 (when (company-manual-begin)
1349 (company-set-selection (1+ company-selection))))
1351 (defun company-select-previous ()
1352 "Select the previous candidate in the list."
1354 (when (company-manual-begin)
1355 (company-set-selection (1- company-selection))))
1357 (defun company-select-next-or-abort ()
1358 "Select the next candidate if more than one, else abort
1359 and invoke the normal binding."
1361 (if (> company-candidates-length 1)
1362 (company-select-next)
1364 (company--unread-last-input)))
1366 (defun company-select-previous-or-abort ()
1367 "Select the previous candidate if more than one, else abort
1368 and invoke the normal binding."
1370 (if (> company-candidates-length 1)
1371 (company-select-previous)
1373 (company--unread-last-input)))
1375 (defvar company-pseudo-tooltip-overlay)
1377 (defvar company-tooltip-offset)
1379 (defun company--inside-tooltip-p (event-col-row row height)
1380 (let* ((ovl company-pseudo-tooltip-overlay)
1381 (column (overlay-get ovl 'company-column))
1382 (width (overlay-get ovl 'company-width))
1383 (evt-col (car event-col-row))
1384 (evt-row (cdr event-col-row)))
1385 (and (>= evt-col column)
1386 (< evt-col (+ column width))
1388 (and (> evt-row row)
1389 (<= evt-row (+ row height) ))
1390 (and (< evt-row row)
1391 (>= evt-row (+ row height)))))))
1393 (defun company--event-col-row (event)
1394 (let* ((col-row (posn-actual-col-row (event-start event)))
1396 (row (cdr col-row)))
1397 (incf col (window-hscroll))
1398 (and header-line-format
1399 (version< "24" emacs-version)
1403 (defun company-select-mouse (event)
1404 "Select the candidate picked by the mouse."
1406 (let ((event-col-row (company--event-col-row event))
1407 (ovl-row (company--row))
1408 (ovl-height (and company-pseudo-tooltip-overlay
1409 (min (overlay-get company-pseudo-tooltip-overlay
1411 company-candidates-length))))
1413 (company--inside-tooltip-p event-col-row ovl-row ovl-height))
1415 (company-set-selection (+ (cdr event-col-row)
1416 (if (zerop company-tooltip-offset)
1418 (- company-tooltip-offset 2))
1420 (if (< ovl-height 0)
1425 (company--unread-last-input)
1428 (defun company-complete-mouse (event)
1429 "Insert the candidate picked by the mouse."
1431 (when (company-select-mouse event)
1432 (company-complete-selection)))
1434 (defun company-complete-selection ()
1435 "Insert the selected candidate."
1437 (when (company-manual-begin)
1438 (let ((result (nth company-selection company-candidates)))
1439 (when company--auto-completion
1440 (setq result (company--safe-candidate result)))
1441 (company-finish result))))
1443 (defun company-complete-common ()
1444 "Insert the common part of all candidates."
1446 (when (company-manual-begin)
1447 (if (and (not (cdr company-candidates))
1448 (equal company-common (car company-candidates)))
1449 (company-complete-selection)
1450 (when company-common
1451 (company--insert-candidate company-common)))))
1453 (defun company-complete ()
1454 "Insert the common part of all candidates or the current selection.
1455 The first time this is called, the common part is inserted, the second
1456 time, or when the selection has been changed, the selected candidate is
1459 (when (company-manual-begin)
1460 (if (or company-selection-changed
1461 (eq last-command 'company-complete-common))
1462 (call-interactively 'company-complete-selection)
1463 (call-interactively 'company-complete-common)
1464 (setq this-command 'company-complete-common))))
1466 (defun company-complete-number (n)
1467 "Insert the Nth candidate.
1468 To show the number next to the candidates in some back-ends, enable
1469 `company-show-numbers'."
1470 (when (company-manual-begin)
1471 (and (< n 1) (> n company-candidates-length)
1472 (error "No candidate number %d" n))
1474 (company-finish (nth n company-candidates))))
1476 ;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;
1478 (defconst company-space-strings-limit 100)
1480 (defconst company-space-strings
1482 (dotimes (i company-space-strings-limit)
1483 (push (make-string (- company-space-strings-limit 1 i) ?\ ) lst))
1484 (apply 'vector lst)))
1486 (defun company-space-string (len)
1487 (if (< len company-space-strings-limit)
1488 (aref company-space-strings len)
1489 (make-string len ?\ )))
1491 (defun company-safe-substring (str from &optional to)
1492 (if (> from (string-width str))
1496 (move-to-column from)
1497 (let ((beg (point)))
1501 (concat (buffer-substring beg (point))
1502 (let ((padding (- to (current-column))))
1504 (company-space-string padding)))))
1505 (buffer-substring beg (point-max)))))))
1507 ;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;
1509 (defvar company-last-metadata nil)
1510 (make-variable-buffer-local 'company-last-metadata)
1512 (defun company-fetch-metadata ()
1513 (let ((selected (nth company-selection company-candidates)))
1514 (unless (equal selected (car company-last-metadata))
1515 (setq company-last-metadata
1516 (cons selected (company-call-backend 'meta selected))))
1517 (cdr company-last-metadata)))
1519 (defun company-doc-buffer (&optional string)
1520 (with-current-buffer (get-buffer-create "*company-documentation*")
1527 (defvar company--electric-commands
1528 '(scroll-other-window scroll-other-window-down)
1529 "List of Commands that won't break out of electric commands.")
1531 (defmacro company--electric-do (&rest body)
1532 (declare (indent 0) (debug t))
1533 `(when (company-manual-begin)
1534 (save-window-excursion
1535 (let ((height (window-height))
1536 (row (company--row))
1539 (and (< (window-height) height)
1540 (< (- (window-height) row 2) company-tooltip-limit)
1541 (recenter (- (window-height) row 2)))
1542 (while (memq (setq cmd (key-binding (vector (list (read-event)))))
1543 company--electric-commands)
1544 (call-interactively cmd))
1545 (company--unread-last-input)))))
1547 (defun company--unread-last-input ()
1548 (when last-input-event
1549 (clear-this-command-keys t)
1550 (setq unread-command-events (list last-input-event))))
1552 (defun company-show-doc-buffer ()
1553 "Temporarily show the documentation buffer for the selection."
1555 (company--electric-do
1556 (let* ((selected (nth company-selection company-candidates))
1557 (doc-buffer (or (company-call-backend 'doc-buffer selected)
1558 (error "No documentation available"))))
1559 (with-current-buffer doc-buffer
1560 (goto-char (point-min)))
1561 (display-buffer doc-buffer t))))
1562 (put 'company-show-doc-buffer 'company-keep t)
1564 (defun company-show-location ()
1565 "Temporarily display a buffer showing the selected candidate in context."
1567 (company--electric-do
1568 (let* ((selected (nth company-selection company-candidates))
1569 (location (company-call-backend 'location selected))
1570 (pos (or (cdr location) (error "No location available")))
1571 (buffer (or (and (bufferp (car location)) (car location))
1572 (find-file-noselect (car location) t))))
1573 (with-selected-window (display-buffer buffer t)
1576 (if (bufferp (car location))
1578 (goto-char (point-min))
1579 (forward-line (1- pos))))
1580 (set-window-start nil (point))))))
1581 (put 'company-show-location 'company-keep t)
1583 ;;; package functions ;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;
1585 (defvar company-callback nil)
1586 (make-variable-buffer-local 'company-callback)
1588 (defvar company-begin-with-marker nil)
1589 (make-variable-buffer-local 'company-begin-with-marker)
1591 (defun company-remove-callback (&optional ignored)
1592 (remove-hook 'company-completion-finished-hook company-callback t)
1593 (remove-hook 'company-completion-cancelled-hook 'company-remove-callback t)
1594 (remove-hook 'company-completion-finished-hook 'company-remove-callback t)
1595 (when company-begin-with-marker
1596 (set-marker company-begin-with-marker nil)))
1598 (defun company-begin-backend (backend &optional callback)
1599 "Start a completion at point using BACKEND."
1600 (interactive (let ((val (completing-read "Company back-end: "
1602 'functionp nil "company-")))
1604 (list (intern val)))))
1605 (when (setq company-callback callback)
1606 (add-hook 'company-completion-finished-hook company-callback nil t))
1607 (add-hook 'company-completion-cancelled-hook 'company-remove-callback nil t)
1608 (add-hook 'company-completion-finished-hook 'company-remove-callback nil t)
1609 (setq company-backend backend)
1610 ;; Return non-nil if active.
1611 (or (company-manual-begin)
1613 (setq company-backend nil)
1614 (error "Cannot complete at point"))))
1616 (defun company-begin-with (candidates
1617 &optional prefix-length require-match callback)
1618 "Start a completion at point.
1619 CANDIDATES is the list of candidates to use and PREFIX-LENGTH is the length
1620 of the prefix that already is in the buffer before point.
1623 CALLBACK is a function called with the selected result if the user
1624 successfully completes the input.
1626 Example: \(company-begin-with '\(\"foo\" \"foobar\" \"foobarbaz\"\)\)"
1627 ;; FIXME: When Emacs 23 is no longer a concern, replace
1628 ;; `company-begin-with-marker' with a lexical variable; use a lexical closure.
1629 (setq company-begin-with-marker (copy-marker (point) t))
1630 (company-begin-backend
1631 `(lambda (command &optional arg &rest ignored)
1633 ((eq command 'prefix)
1634 (when (equal (point) (marker-position company-begin-with-marker))
1635 (buffer-substring ,(- (point) (or prefix-length 0)) (point))))
1636 ((eq command 'candidates)
1637 (all-completions arg ',candidates))
1638 ((eq command 'require-match)
1642 ;;; pseudo-tooltip ;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;
1644 (defvar company-pseudo-tooltip-overlay nil)
1645 (make-variable-buffer-local 'company-pseudo-tooltip-overlay)
1647 (defvar company-tooltip-offset 0)
1648 (make-variable-buffer-local 'company-tooltip-offset)
1650 (defun company-pseudo-tooltip-update-offset (selection num-lines limit)
1653 (setq company-tooltip-offset
1654 (max (min selection company-tooltip-offset)
1655 (- selection -1 limit)))
1657 (when (<= company-tooltip-offset 1)
1659 (setq company-tooltip-offset 0))
1661 (when (>= company-tooltip-offset (- num-lines limit 1))
1663 (when (= selection (1- num-lines))
1664 (decf company-tooltip-offset)
1665 (when (<= company-tooltip-offset 1)
1666 (setq company-tooltip-offset 0)
1673 (defsubst company-round-tab (arg)
1674 (* (/ (+ arg tab-width) tab-width) tab-width))
1676 (defun company-plainify (str)
1677 (let ((prefix (get-text-property 0 'line-prefix str)))
1678 (when prefix ; Keep the original value unmodified, for no special reason.
1679 (setq str (concat prefix str))
1680 (remove-text-properties 0 (length str) '(line-prefix) str)))
1681 (let* ((pieces (split-string str "\t"))
1684 (setcar copy (company-safe-substring
1685 (car copy) 0 (company-round-tab (string-width (car copy)))))
1687 (apply 'concat pieces)))
1689 (defun company--highlight-common (line properties)
1690 ;; XXX: Subject to change.
1691 (let ((common (or (company-call-backend 'common-part line)
1692 (length company-common))))
1693 (add-text-properties 0 common properties line)))
1695 (defun company-fill-propertize (line width selected)
1696 (let* ((margin company-tooltip-margin)
1697 (common (+ (or (company-call-backend 'common-part line)
1698 (length company-common)) margin)))
1699 (setq line (concat (company-space-string company-tooltip-margin)
1700 (company-safe-substring
1701 line 0 (+ width company-tooltip-margin)))
1702 width (+ width (* 2 margin)))
1704 (add-text-properties 0 width '(face company-tooltip
1705 mouse-face company-tooltip-mouse)
1707 (add-text-properties margin common
1708 '(face company-tooltip-common
1709 mouse-face company-tooltip-mouse)
1712 (if (and company-search-string
1713 (string-match (regexp-quote company-search-string) line
1714 (length company-prefix)))
1716 (add-text-properties (match-beginning 0) (match-end 0)
1717 '(face company-tooltip-selection)
1719 (when (< (match-beginning 0) common)
1720 (add-text-properties (match-beginning 0) common
1721 '(face company-tooltip-common-selection)
1723 (add-text-properties 0 width '(face company-tooltip-selection
1724 mouse-face company-tooltip-selection)
1726 (add-text-properties margin common
1727 '(face company-tooltip-common-selection
1728 mouse-face company-tooltip-selection)
1734 (defun company-buffer-lines (beg end)
1737 (while (and (= 1 (vertical-motion 1))
1739 (let ((bound (min end (1- (point)))))
1740 ;; A visual line can contain several physical lines (e.g. with outline's
1741 ;; folding overlay). Take only the first one.
1742 (push (buffer-substring beg
1745 (re-search-forward "$" bound 'move)
1749 (unless (eq beg end)
1750 (push (buffer-substring beg end) lines))
1753 (defun company-modify-line (old new offset)
1754 (concat (company-safe-substring old 0 offset)
1756 (company-safe-substring old (+ offset (length new)))))
1758 (defsubst company--length-limit (lst limit)
1759 (if (nthcdr limit lst)
1763 (defun company--replacement-string (lines old column nl &optional align-top)
1764 (decf column company-tooltip-margin)
1766 (let ((width (length (car lines)))
1767 (remaining-cols (- (+ (company--window-width) (window-hscroll))
1769 (when (> width remaining-cols)
1770 (decf column (- width remaining-cols))))
1772 (let ((cutoff (and (< column 0) (- column)))
1777 ;; untouched lines first
1778 (dotimes (_ (- (length old) (length lines)))
1779 (push (pop old) new)))
1780 ;; length into old lines.
1782 (push (company-modify-line (pop old)
1783 (company--cutoff-line (pop lines) cutoff)
1785 ;; Append whole new lines.
1787 (push (concat (company-space-string column)
1788 (company--cutoff-line (pop lines) cutoff))
1791 (let ((str (concat (when nl "\n")
1792 (mapconcat 'identity (nreverse new) "\n")
1794 (font-lock-append-text-property 0 (length str) 'face 'default str)
1797 (defun company--cutoff-line (line cutoff)
1798 (if (and cutoff line)
1799 (substring line cutoff)
1802 (defun company--create-lines (selection limit)
1804 (let ((len company-candidates-length)
1806 (window-width (company--window-width))
1814 ;; Scroll to offset.
1815 (setq limit (company-pseudo-tooltip-update-offset selection len limit))
1817 (when (> company-tooltip-offset 0)
1818 (setq previous (format "...(%d)" company-tooltip-offset)))
1820 (setq remainder (- len limit company-tooltip-offset)
1821 remainder (when (> remainder 0)
1822 (setq remainder (format "...(%d)" remainder))))
1824 (decf selection company-tooltip-offset)
1825 (setq width (max (length previous) (length remainder))
1826 lines (nthcdr company-tooltip-offset company-candidates)
1830 (decf window-width (* 2 company-tooltip-margin))
1833 (setq width (max (length (pop lines-copy)) width)))
1834 (setq width (min window-width
1835 (if company-show-numbers
1838 (setq lines-copy lines)
1840 ;; number can make tooltip too long
1841 (when company-show-numbers
1842 (setq numbered company-tooltip-offset))
1845 (push (company--numbered-line previous width) new))
1848 (push (company-fill-propertize
1849 (if (>= numbered 10)
1850 (company-reformat (pop lines))
1853 (company-safe-substring (company-reformat (pop lines))
1856 width (equal i selection))
1860 (push (company--numbered-line remainder width) new))
1862 (setq lines (nreverse new))))
1864 (defun company--numbered-line (text width)
1865 (concat (company-space-string company-tooltip-margin)
1866 (propertize (company-safe-substring text 0 width)
1867 'face 'company-tooltip)
1868 (company-space-string company-tooltip-margin)))
1872 (defsubst company--window-inner-height ()
1873 (let ((edges (window-inside-edges)))
1874 (- (nth 3 edges) (nth 1 edges))))
1876 (defsubst company--window-width ()
1879 ((display-graphic-p) 0)
1880 ;; Account for the line continuation column.
1881 ((version< "24.3.1" emacs-version) 1)
1882 ;; Emacs 24.3 and earlier included margins
1883 ;; in window-width when in TTY.
1884 (t (1+ (let ((margins (window-margins)))
1885 (+ (or (car margins) 0)
1886 (or (cdr margins) 0))))))))
1888 (defun company--pseudo-tooltip-height ()
1889 "Calculate the appropriate tooltip height.
1890 Returns a negative number if the tooltip should be displayed above point."
1891 (let* ((lines (company--row))
1892 (below (- (company--window-inner-height) 1 lines)))
1893 (if (and (< below (min company-tooltip-minimum company-candidates-length))
1895 (- (max 3 (min company-tooltip-limit lines)))
1896 (max 3 (min company-tooltip-limit below)))))
1898 (defun company-pseudo-tooltip-show (row column selection)
1899 (company-pseudo-tooltip-hide)
1902 (let* ((height (company--pseudo-tooltip-height))
1906 (setq row (+ row height -1)
1909 (let* ((nl (< (move-to-window-line row) row))
1911 (end (save-excursion
1912 (move-to-window-line (+ row (abs height)))
1914 (ov (make-overlay beg end))
1915 (args (list (mapcar 'company-plainify
1916 (company-buffer-lines beg end))
1919 (setq company-pseudo-tooltip-overlay ov)
1920 (overlay-put ov 'company-replacement-args args)
1922 (let ((lines (company--create-lines selection (abs height))))
1923 (overlay-put ov 'company-after
1924 (apply 'company--replacement-string lines args))
1925 (overlay-put ov 'company-width (string-width (car lines))))
1927 (overlay-put ov 'company-column column)
1928 (overlay-put ov 'company-height height)))))
1930 (defun company-pseudo-tooltip-show-at-point (pos)
1931 (let ((row (company--row pos))
1932 (col (company--column pos)))
1933 (company-pseudo-tooltip-show (1+ row) col company-selection)))
1935 (defun company-pseudo-tooltip-edit (selection)
1936 (let ((height (overlay-get company-pseudo-tooltip-overlay 'company-height)))
1937 (overlay-put company-pseudo-tooltip-overlay 'company-after
1938 (apply 'company--replacement-string
1939 (company--create-lines selection (abs height))
1940 (overlay-get company-pseudo-tooltip-overlay
1941 'company-replacement-args)))))
1943 (defun company-pseudo-tooltip-hide ()
1944 (when company-pseudo-tooltip-overlay
1945 (delete-overlay company-pseudo-tooltip-overlay)
1946 (setq company-pseudo-tooltip-overlay nil)))
1948 (defun company-pseudo-tooltip-hide-temporarily ()
1949 (when (overlayp company-pseudo-tooltip-overlay)
1950 (overlay-put company-pseudo-tooltip-overlay 'invisible nil)
1951 (overlay-put company-pseudo-tooltip-overlay 'line-prefix nil)
1952 (overlay-put company-pseudo-tooltip-overlay 'after-string nil)))
1954 (defun company-pseudo-tooltip-unhide ()
1955 (when company-pseudo-tooltip-overlay
1956 (overlay-put company-pseudo-tooltip-overlay 'invisible t)
1957 ;; Beat outline's folding overlays, at least.
1958 (overlay-put company-pseudo-tooltip-overlay 'priority 1)
1959 ;; No (extra) prefix for the first line.
1960 (overlay-put company-pseudo-tooltip-overlay 'line-prefix "")
1961 (overlay-put company-pseudo-tooltip-overlay 'after-string
1962 (overlay-get company-pseudo-tooltip-overlay 'company-after))
1963 (overlay-put company-pseudo-tooltip-overlay 'window (selected-window))))
1965 (defun company-pseudo-tooltip-guard ()
1966 (buffer-substring-no-properties
1967 (point) (overlay-start company-pseudo-tooltip-overlay)))
1969 (defun company-pseudo-tooltip-frontend (command)
1970 "`company-mode' front-end similar to a tooltip but based on overlays."
1972 (pre-command (company-pseudo-tooltip-hide-temporarily))
1974 (let ((old-height (if (overlayp company-pseudo-tooltip-overlay)
1975 (overlay-get company-pseudo-tooltip-overlay
1978 (new-height (company--pseudo-tooltip-height)))
1979 (unless (and (>= (* old-height new-height) 0)
1980 (>= (abs old-height) (abs new-height))
1981 (equal (company-pseudo-tooltip-guard)
1982 (overlay-get company-pseudo-tooltip-overlay
1985 (company-pseudo-tooltip-show-at-point (- (point)
1986 (length company-prefix)))
1987 (overlay-put company-pseudo-tooltip-overlay
1988 'company-guard (company-pseudo-tooltip-guard))))
1989 (company-pseudo-tooltip-unhide))
1990 (hide (company-pseudo-tooltip-hide)
1991 (setq company-tooltip-offset 0))
1992 (update (when (overlayp company-pseudo-tooltip-overlay)
1993 (company-pseudo-tooltip-edit company-selection)))))
1995 (defun company-pseudo-tooltip-unless-just-one-frontend (command)
1996 "`company-pseudo-tooltip-frontend', but not shown for single candidates."
1997 (unless (and (eq command 'post-command)
1998 (company--show-inline-p))
1999 (company-pseudo-tooltip-frontend command)))
2001 ;;; overlay ;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;
2003 (defvar company-preview-overlay nil)
2004 (make-variable-buffer-local 'company-preview-overlay)
2006 (defun company-preview-show-at-point (pos)
2007 (company-preview-hide)
2009 (setq company-preview-overlay (make-overlay pos pos))
2011 (let ((completion(nth company-selection company-candidates)))
2012 (setq completion (propertize completion 'face 'company-preview))
2013 (add-text-properties 0 (length company-common)
2014 '(face company-preview-common) completion)
2016 ;; Add search string
2017 (and company-search-string
2018 (string-match (regexp-quote company-search-string) completion)
2019 (add-text-properties (match-beginning 0)
2021 '(face company-preview-search)
2024 (setq completion (company-strip-prefix completion))
2026 (and (equal pos (point))
2027 (not (equal completion ""))
2028 (add-text-properties 0 1 '(cursor t) completion))
2030 (overlay-put company-preview-overlay 'after-string completion)
2031 (overlay-put company-preview-overlay 'window (selected-window))))
2033 (defun company-preview-hide ()
2034 (when company-preview-overlay
2035 (delete-overlay company-preview-overlay)
2036 (setq company-preview-overlay nil)))
2038 (defun company-preview-frontend (command)
2039 "`company-mode' front-end showing the selection as if it had been inserted."
2041 (pre-command (company-preview-hide))
2042 (post-command (company-preview-show-at-point (point)))
2043 (hide (company-preview-hide))))
2045 (defun company-preview-if-just-one-frontend (command)
2046 "`company-preview-frontend', but only shown for single candidates."
2047 (when (or (not (eq command 'post-command))
2048 (company--show-inline-p))
2049 (company-preview-frontend command)))
2051 (defun company--show-inline-p ()
2052 (and (not (cdr company-candidates))
2054 (string-prefix-p company-prefix company-common
2055 (company-call-backend 'ignore-case))))
2057 ;;; echo ;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;
2059 (defvar company-echo-last-msg nil)
2060 (make-variable-buffer-local 'company-echo-last-msg)
2062 (defvar company-echo-timer nil)
2064 (defvar company-echo-delay .01)
2066 (defun company-echo-show (&optional getter)
2068 (setq company-echo-last-msg (funcall getter)))
2069 (let ((message-log-max nil))
2070 (if company-echo-last-msg
2071 (message "%s" company-echo-last-msg)
2074 (defun company-echo-show-soon (&optional getter)
2075 (when company-echo-timer
2076 (cancel-timer company-echo-timer))
2077 (setq company-echo-timer (run-with-timer 0 nil 'company-echo-show getter)))
2079 (defsubst company-echo-show-when-idle (&optional getter)
2080 (when (sit-for company-echo-delay)
2081 (company-echo-show getter)))
2083 (defun company-echo-format ()
2085 (let ((limit (window-width (minibuffer-window)))
2087 ;; Roll to selection.
2088 (candidates (nthcdr company-selection company-candidates))
2089 (i (if company-show-numbers company-selection 99999))
2093 (setq comp (company-reformat (pop candidates))
2094 len (+ len 1 (length comp)))
2098 (setq comp (propertize (format "%d: %s" i comp)
2099 'face 'company-echo))
2102 (add-text-properties 3 (+ 3 (length company-common))
2103 '(face company-echo-common) comp))
2104 (setq comp (propertize comp 'face 'company-echo))
2105 (add-text-properties 0 (length company-common)
2106 '(face company-echo-common) comp))
2108 (setq candidates nil)
2111 (mapconcat 'identity (nreverse msg) " ")))
2113 (defun company-echo-strip-common-format ()
2115 (let ((limit (window-width (minibuffer-window)))
2116 (len (+ (length company-prefix) 2))
2117 ;; Roll to selection.
2118 (candidates (nthcdr company-selection company-candidates))
2119 (i (if company-show-numbers company-selection 99999))
2123 (setq comp (company-strip-prefix (pop candidates))
2124 len (+ len 2 (length comp)))
2127 (setq comp (format "%s (%d)" comp i))
2131 (setq candidates nil)
2132 (push (propertize comp 'face 'company-echo) msg)))
2134 (concat (propertize company-prefix 'face 'company-echo-common) "{"
2135 (mapconcat 'identity (nreverse msg) ", ")
2138 (defun company-echo-hide ()
2139 (unless (equal company-echo-last-msg "")
2140 (setq company-echo-last-msg "")
2141 (company-echo-show)))
2143 (defun company-echo-frontend (command)
2144 "`company-mode' front-end showing the candidates in the echo area."
2146 (post-command (company-echo-show-soon 'company-echo-format))
2147 (hide (company-echo-hide))))
2149 (defun company-echo-strip-common-frontend (command)
2150 "`company-mode' front-end showing the candidates in the echo area."
2152 (post-command (company-echo-show-soon 'company-echo-strip-common-format))
2153 (hide (company-echo-hide))))
2155 (defun company-echo-metadata-frontend (command)
2156 "`company-mode' front-end showing the documentation in the echo area."
2158 (post-command (company-echo-show-when-idle 'company-fetch-metadata))
2159 (hide (company-echo-hide))))
2162 ;;; company.el ends here