1 ;;; company.el --- Modular in-buffer completion framework -*- lexical-binding: t -*-
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 (kbd "RET") 'company-complete-selection)
494 (define-key keymap [tab] 'company-complete-common)
495 (define-key keymap (kbd "TAB") 'company-complete-common)
496 (define-key keymap (kbd "<f1>") 'company-show-doc-buffer)
497 (define-key keymap "\C-w" 'company-show-location)
498 (define-key keymap "\C-s" 'company-search-candidates)
499 (define-key keymap "\C-\M-s" 'company-filter-candidates)
501 (define-key keymap (vector (+ (aref (kbd "M-0") 0) i))
502 `(lambda () (interactive) (company-complete-number ,i))))
505 "Keymap that is enabled during an active completion.")
507 (defvar company--disabled-backends nil)
509 (defun company-init-backend (backend)
510 (and (symbolp backend)
511 (not (fboundp backend))
512 (ignore-errors (require backend nil t)))
514 (if (or (symbolp backend)
518 (funcall backend 'init)
519 (put backend 'company-init t))
521 (put backend 'company-init 'failed)
522 (unless (memq backend company--disabled-backends)
523 (message "Company back-end '%s' could not be initialized:\n%s"
524 backend (error-message-string err)))
525 (pushnew backend company--disabled-backends)
527 (mapc 'company-init-backend backend)))
529 (defvar company-default-lighter " company")
531 (defvar company-lighter company-default-lighter)
532 (make-variable-buffer-local 'company-lighter)
535 (define-minor-mode company-mode
536 "\"complete anything\"; is an in-buffer completion framework.
537 Completion starts automatically, depending on the values
538 `company-idle-delay' and `company-minimum-prefix-length'.
540 Completion can be controlled with the commands:
541 `company-complete-common', `company-complete-selection', `company-complete',
542 `company-select-next', `company-select-previous'. If these commands are
543 called before `company-idle-delay', completion will also start.
545 Completions can be searched with `company-search-candidates' or
546 `company-filter-candidates'. These can be used while completion is
549 The completion data is retrieved using `company-backends' and displayed using
550 `company-frontends'. If you want to start a specific back-end, call it
551 interactively or use `company-begin-backend'.
553 regular keymap (`company-mode-map'):
556 keymap during active completions (`company-active-map'):
558 \\{company-active-map}"
559 nil company-lighter company-mode-map
562 (add-hook 'pre-command-hook 'company-pre-command nil t)
563 (add-hook 'post-command-hook 'company-post-command nil t)
564 (mapc 'company-init-backend company-backends))
565 (remove-hook 'pre-command-hook 'company-pre-command t)
566 (remove-hook 'post-command-hook 'company-post-command t)
568 (kill-local-variable 'company-point)))
571 (define-globalized-minor-mode global-company-mode company-mode company-mode-on)
573 (defun company-mode-on ()
574 (unless (or noninteractive (eq (aref (buffer-name) 0) ?\s))
577 (defsubst company-assert-enabled ()
579 (company-uninstall-map)
580 (error "Company not enabled")))
582 ;;; keymaps ;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;
584 (defvar company-my-keymap nil)
585 (make-variable-buffer-local 'company-my-keymap)
587 (defvar company-emulation-alist '((t . nil)))
589 (defsubst company-enable-overriding-keymap (keymap)
590 (company-uninstall-map)
591 (setq company-my-keymap keymap))
593 (defun company-ensure-emulation-alist ()
594 (unless (eq 'company-emulation-alist (car emulation-mode-map-alists))
595 (setq emulation-mode-map-alists
596 (cons 'company-emulation-alist
597 (delq 'company-emulation-alist emulation-mode-map-alists)))))
599 (defun company-install-map ()
600 (unless (or (cdar company-emulation-alist)
601 (null company-my-keymap))
602 (setf (cdar company-emulation-alist) company-my-keymap)))
604 (defun company-uninstall-map ()
605 (setf (cdar company-emulation-alist) nil))
608 ;; Emacs calculates the active keymaps before reading the event. That means we
609 ;; cannot change the keymap from a timer. So we send a bogus command.
610 (defun company-ignore ()
612 (setq this-command last-command))
614 (global-set-key '[31415926] 'company-ignore)
616 (defun company-input-noop ()
617 (push 31415926 unread-command-events))
620 ;; posn-col-row is incorrect in older Emacsen when line-spacing is set
621 (defun company--col-row (&optional pos)
622 (let ((posn (posn-at-point pos)))
623 (cons (car (posn-col-row posn)) (cdr (posn-actual-col-row posn)))))
625 (defsubst company--column (&optional pos)
626 (car (posn-col-row (posn-at-point pos))))
628 (defsubst company--row (&optional pos)
629 (cdr (posn-actual-col-row (posn-at-point pos))))
631 ;;; backends ;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;
633 (defun company-grab (regexp &optional expression limit)
634 (when (looking-back regexp limit)
635 (or (match-string-no-properties (or expression 0)) "")))
637 (defun company-grab-line (regexp &optional expression)
638 (company-grab regexp expression (point-at-bol)))
640 (defun company-grab-symbol ()
641 (if (looking-at "\\_>")
642 (buffer-substring (point) (save-excursion (skip-syntax-backward "w_")
644 (unless (and (char-after) (memq (char-syntax (char-after)) '(?w ?_)))
647 (defun company-grab-word ()
648 (if (looking-at "\\>")
649 (buffer-substring (point) (save-excursion (skip-syntax-backward "w")
651 (unless (and (char-after) (eq (char-syntax (char-after)) ?w))
654 (defun company-in-string-or-comment ()
655 (let ((ppss (syntax-ppss)))
656 (or (car (setq ppss (nthcdr 3 ppss)))
657 (car (setq ppss (cdr ppss)))
660 (if (fboundp 'locate-dominating-file)
661 (defalias 'company-locate-dominating-file 'locate-dominating-file)
662 (defun company-locate-dominating-file (file name)
664 (let ((dir (file-name-directory file))
666 (while (not (equal dir prev-dir))
667 (when (file-exists-p (expand-file-name name dir))
670 dir (file-name-directory (directory-file-name dir))))))))
672 (defun company-call-backend (&rest args)
673 (if (functionp company-backend)
674 (apply company-backend args)
675 (apply 'company--multi-backend-adapter company-backend args)))
677 (defun company--multi-backend-adapter (backends command &rest args)
678 (let ((backends (loop for b in backends
679 when (not (and (symbolp b)
680 (eq 'failed (get b 'company-init))))
684 (loop for backend in backends
685 when (equal (funcall backend 'prefix)
687 append (apply backend 'candidates args)))
692 (dolist (backend backends)
693 (when (setq value (apply backend command args))
694 (return value))))))))
696 ;;; completion mechanism ;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;
698 (defvar company-backend nil)
699 (make-variable-buffer-local 'company-backend)
701 (defvar company-prefix nil)
702 (make-variable-buffer-local 'company-prefix)
704 (defvar company-candidates nil)
705 (make-variable-buffer-local 'company-candidates)
707 (defvar company-candidates-length nil)
708 (make-variable-buffer-local 'company-candidates-length)
710 (defvar company-candidates-cache nil)
711 (make-variable-buffer-local 'company-candidates-cache)
713 (defvar company-candidates-predicate nil)
714 (make-variable-buffer-local 'company-candidates-predicate)
716 (defvar company-common nil)
717 (make-variable-buffer-local 'company-common)
719 (defvar company-selection 0)
720 (make-variable-buffer-local 'company-selection)
722 (defvar company-selection-changed nil)
723 (make-variable-buffer-local 'company-selection-changed)
725 (defvar company--explicit-action nil
726 "Non-nil, if explicit completion took place.")
727 (make-variable-buffer-local 'company--explicit-action)
729 (defvar company--auto-completion nil
730 "Non-nil when current candidate is being completed automatically.
731 Controlled by `company-auto-complete'.")
733 (defvar company--point-max nil)
734 (make-variable-buffer-local 'company--point-max)
736 (defvar company-point nil)
737 (make-variable-buffer-local 'company-point)
739 (defvar company-timer nil)
741 (defvar company-added-newline nil)
742 (make-variable-buffer-local 'company-added-newline)
744 (defsubst company-strip-prefix (str)
745 (substring str (length company-prefix)))
747 (defmacro company-with-candidate-inserted (candidate &rest body)
748 "Evaluate BODY with CANDIDATE temporarily inserted.
749 This is a tool for back-ends that need candidates inserted before they
750 can retrieve meta-data for them."
752 `(let ((inhibit-modification-hooks t)
753 (inhibit-point-motion-hooks t)
754 (modified-p (buffer-modified-p)))
755 (insert (company-strip-prefix ,candidate))
758 (delete-region company-point (point)))))
760 (defun company-explicit-action-p ()
761 "Return whether explicit completion action was taken by the user."
762 (or company--explicit-action
763 company-selection-changed))
765 (defsubst company-reformat (candidate)
766 ;; company-ispell needs this, because the results are always lower-case
767 ;; It's mory efficient to fix it only when they are displayed.
768 (concat company-prefix (substring candidate (length company-prefix))))
770 (defun company--should-complete ()
771 (and (not (or buffer-read-only overriding-terminal-local-map
774 ;; Check if in the middle of entering a key combination.
775 (or (equal (this-command-keys-vector) [])
776 (not (keymapp (key-binding (this-command-keys-vector)))))
777 (eq company-idle-delay t)
778 (or (eq t company-begin-commands)
779 (memq this-command company-begin-commands)
780 (and (symbolp this-command) (get this-command 'company-begin)))
781 (not (and transient-mark-mode mark-active))))
783 (defsubst company-call-frontends (command)
784 (dolist (frontend company-frontends)
786 (funcall frontend command)
787 (error (error "Company: Front-end %s error \"%s\" on command %s"
788 frontend (error-message-string err) command)))))
790 (defsubst company-set-selection (selection &optional force-update)
791 (setq selection (max 0 (min (1- company-candidates-length) selection)))
792 (when (or force-update (not (equal selection company-selection)))
793 (setq company-selection selection
794 company-selection-changed t)
795 (company-call-frontends 'update)))
797 (defun company-apply-predicate (candidates predicate)
799 (dolist (c candidates)
800 (when (funcall predicate c)
804 (defun company-update-candidates (candidates)
805 (setq company-candidates-length (length candidates))
806 (if (> company-selection 0)
807 ;; Try to restore the selection
808 (let ((selected (nth company-selection company-candidates)))
809 (setq company-selection 0
810 company-candidates candidates)
812 (while (and candidates (string< (pop candidates) selected))
813 (incf company-selection))
815 ;; Make sure selection isn't out of bounds.
816 (setq company-selection (min (1- company-candidates-length)
817 company-selection)))))
818 (setq company-selection 0
819 company-candidates candidates))
821 (push (cons company-prefix company-candidates) company-candidates-cache)
823 (let ((completion-ignore-case (company-call-backend 'ignore-case)))
824 (setq company-common (company--safe-candidate
825 (try-completion company-prefix company-candidates))))
826 (when (eq company-common t)
827 (setq company-candidates nil)))
829 (defun company--safe-candidate (str)
830 (or (company-call-backend 'crop str)
833 (defun company-calculate-candidates (prefix)
834 (let ((candidates (cdr (assoc prefix company-candidates-cache)))
835 (ignore-case (company-call-backend 'ignore-case)))
837 (when company-candidates-cache
838 (let ((len (length prefix))
839 (completion-ignore-case ignore-case)
841 (dotimes (i (1+ len))
842 (when (setq prev (cdr (assoc (substring prefix 0 (- len i))
843 company-candidates-cache)))
844 (setq candidates (all-completions prefix prev))
846 ;; no cache match, call back-end
848 (setq candidates (company-call-backend 'candidates prefix))
849 (when company-candidates-predicate
851 (company-apply-predicate candidates
852 company-candidates-predicate)))
853 (unless (company-call-backend 'sorted)
854 (setq candidates (sort candidates 'string<)))
855 (when (company-call-backend 'duplicates)
857 (let ((c2 candidates))
859 (setcdr c2 (progn (while (equal (pop c2) (car c2)))
862 (if (or (cdr candidates)
863 (not (eq t (compare-strings (car candidates) nil nil
864 prefix nil nil ignore-case))))
866 ;; Already completed and unique; don't start.
869 (defun company-idle-begin (buf win tick pos)
871 (eq buf (current-buffer))
872 (eq win (selected-window))
873 (eq tick (buffer-chars-modified-tick))
875 (not company-candidates)
876 (not (equal (point) company-point))
877 (let ((company-idle-delay t)
878 (company-begin-commands t))
880 (when company-candidates
882 (company-post-command)))))
884 (defun company-auto-begin ()
885 (company-assert-enabled)
887 (not company-candidates)
888 (let ((company-idle-delay t)
889 (company-minimum-prefix-length 0)
890 (company-begin-commands t))
892 ;; Return non-nil if active.
895 (defun company-manual-begin ()
897 (setq company--explicit-action t)
900 (unless company-candidates
901 (setq company--explicit-action nil))))
903 (defun company-other-backend (&optional backward)
904 (interactive (list current-prefix-arg))
905 (company-assert-enabled)
907 (let* ((after (cdr (member company-backend company-backends)))
908 (before (cdr (member company-backend (reverse company-backends))))
910 (append before (reverse after))
911 (append after (reverse before)))))
913 (dolist (backend next)
914 (when (ignore-errors (company-begin-backend backend))
916 (company-manual-begin))
917 (unless company-candidates
918 (error "No other back-end")))
920 (defun company-require-match-p ()
921 (let ((backend-value (company-call-backend 'require-match)))
922 (or (eq backend-value t)
923 (and (if (functionp company-require-match)
924 (funcall company-require-match)
925 (eq company-require-match t))
926 (not (eq backend-value 'never))))))
928 (defun company-punctuation-p (input)
929 "Return non-nil, if input starts with punctuation or parentheses."
930 (memq (char-syntax (string-to-char input)) '(?. ?\( ?\))))
932 (defun company-auto-complete-p (input)
933 "Return non-nil, if input starts with punctuation or parentheses."
934 (and (if (functionp company-auto-complete)
935 (funcall company-auto-complete)
936 company-auto-complete)
937 (if (functionp company-auto-complete-chars)
938 (funcall company-auto-complete-chars input)
939 (if (consp company-auto-complete-chars)
940 (memq (char-syntax (string-to-char input))
941 company-auto-complete-chars)
942 (string-match (substring input 0 1) company-auto-complete-chars)))))
944 (defun company--incremental-p ()
945 (and (> (point) company-point)
946 (> (point-max) company--point-max)
947 (not (eq this-command 'backward-delete-char-untabify))
948 (equal (buffer-substring (- company-point (length company-prefix))
952 (defsubst company--string-incremental-p (old-prefix new-prefix)
953 (and (> (length new-prefix) (length old-prefix))
954 (equal old-prefix (substring new-prefix 0 (length old-prefix)))))
956 (defun company--continue-failed (new-prefix)
957 (when (company--incremental-p)
958 (let ((input (buffer-substring-no-properties (point) company-point)))
960 ((company-auto-complete-p input)
963 (goto-char company-point)
964 (let ((company--auto-completion t))
965 (company-complete-selection))
967 ((and (company--string-incremental-p company-prefix new-prefix)
968 (company-require-match-p))
969 ;; wrong incremental input, but required match
970 (backward-delete-char (length input))
972 (message "Matching input is required")
974 ((equal company-prefix (car company-candidates))
975 ;; last input was actually success
976 (company-cancel company-prefix)
979 (defun company--good-prefix-p (prefix)
980 (and (or (company-explicit-action-p)
981 (unless (eq prefix 'stop)
982 (>= (or (cdr-safe prefix) (length prefix))
983 company-minimum-prefix-length)))
984 (stringp (or (car-safe prefix) prefix))))
986 (defun company--continue ()
987 (when (company-call-backend 'no-cache company-prefix)
988 ;; Don't complete existing candidates, fetch new ones.
989 (setq company-candidates-cache nil))
990 (let* ((new-prefix (company-call-backend 'prefix))
991 (c (when (and (company--good-prefix-p new-prefix)
992 (setq new-prefix (or (car-safe new-prefix) new-prefix))
993 (= (- (point) (length new-prefix))
994 (- company-point (length company-prefix))))
995 (setq new-prefix (or (car-safe new-prefix) new-prefix))
996 (company-calculate-candidates new-prefix))))
999 ;; t means complete/unique.
1000 (company-cancel new-prefix)
1003 ;; incremental match
1004 (setq company-prefix new-prefix)
1005 (company-update-candidates c)
1007 (t (company--continue-failed new-prefix)))
1010 (defun company--begin-new ()
1012 (dolist (backend (if company-backend
1013 ;; prefer manual override
1014 (list company-backend)
1017 (if (or (symbolp backend)
1018 (functionp backend))
1019 (when (or (not (symbolp backend))
1020 (eq t (get backend 'company-init))
1021 (unless (get backend 'company-init)
1022 (company-init-backend backend)))
1023 (funcall backend 'prefix))
1024 (company--multi-backend-adapter backend 'prefix)))
1026 (when (company--good-prefix-p prefix)
1027 (setq prefix (or (car-safe prefix) prefix)
1028 company-backend backend
1029 c (company-calculate-candidates prefix))
1030 ;; t means complete/unique. We don't start, so no hooks.
1032 (when company--explicit-action
1033 (message "No completion found"))
1034 (setq company-prefix prefix)
1035 (when (symbolp backend)
1036 (setq company-lighter (concat " " (symbol-name backend))))
1037 (company-update-candidates c)
1038 (run-hook-with-args 'company-completion-started-hook
1039 (company-explicit-action-p))
1040 (company-call-frontends 'show)))
1043 (defun company-begin ()
1044 (or (and company-candidates (company--continue))
1045 (and (company--should-complete) (company--begin-new)))
1046 (when company-candidates
1047 (when (and company-end-of-buffer-workaround (eobp))
1048 (save-excursion (insert "\n"))
1049 (setq company-added-newline (buffer-chars-modified-tick)))
1050 (setq company-point (point)
1051 company--point-max (point-max))
1052 (company-ensure-emulation-alist)
1053 (company-enable-overriding-keymap company-active-map)
1054 (company-call-frontends 'update)))
1056 (defun company-cancel (&optional result)
1057 (and company-added-newline
1058 (> (point-max) (point-min))
1059 (let ((tick (buffer-chars-modified-tick)))
1060 (delete-region (1- (point-max)) (point-max))
1061 (equal tick company-added-newline))
1062 ;; Only set unmodified when tick remained the same since insert.
1063 (set-buffer-modified-p nil))
1064 (when company-prefix
1065 (if (stringp result)
1067 (company-call-backend 'pre-completion result)
1068 (run-hook-with-args 'company-completion-finished-hook result)
1069 (company-call-backend 'post-completion result))
1070 (run-hook-with-args 'company-completion-cancelled-hook result)))
1071 (setq company-added-newline nil
1074 company-candidates nil
1075 company-candidates-length nil
1076 company-candidates-cache nil
1077 company-candidates-predicate nil
1080 company-selection-changed nil
1081 company--explicit-action nil
1082 company-lighter company-default-lighter
1083 company--point-max nil
1086 (cancel-timer company-timer))
1087 (company-search-mode 0)
1088 (company-call-frontends 'hide)
1089 (company-enable-overriding-keymap nil))
1091 (defun company-abort ()
1094 ;; Don't start again, unless started manually.
1095 (setq company-point (point)))
1097 (defun company-finish (result)
1098 (insert (company-strip-prefix result))
1099 (company-cancel result)
1100 ;; Don't start again, unless started manually.
1101 (setq company-point (point)))
1103 (defsubst company-keep (command)
1104 (and (symbolp command) (get command 'company-keep)))
1106 (defun company-pre-command ()
1107 (unless (company-keep this-command)
1109 (when company-candidates
1110 (company-call-frontends 'pre-command))
1111 (error (message "Company: An error occurred in pre-command")
1112 (message "%s" (error-message-string err))
1115 (cancel-timer company-timer)
1116 (setq company-timer nil))
1117 (company-uninstall-map))
1119 (defun company-post-command ()
1120 (unless (company-keep this-command)
1123 (unless (equal (point) company-point)
1125 (if company-candidates
1126 (company-call-frontends 'post-command)
1127 (and (numberp company-idle-delay)
1128 (or (eq t company-begin-commands)
1129 (memq this-command company-begin-commands))
1131 (run-with-timer company-idle-delay nil
1133 (current-buffer) (selected-window)
1134 (buffer-chars-modified-tick) (point))))))
1135 (error (message "Company: An error occurred in post-command")
1136 (message "%s" (error-message-string err))
1138 (company-install-map))
1140 ;;; search ;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;
1142 (defvar company-search-string nil)
1143 (make-variable-buffer-local 'company-search-string)
1145 (defvar company-search-lighter " Search: \"\"")
1146 (make-variable-buffer-local 'company-search-lighter)
1148 (defvar company-search-old-map nil)
1149 (make-variable-buffer-local 'company-search-old-map)
1151 (defvar company-search-old-selection 0)
1152 (make-variable-buffer-local 'company-search-old-selection)
1154 (defun company-search (text lines)
1155 (let ((quoted (regexp-quote text))
1157 (dolist (line lines)
1158 (when (string-match quoted line (length company-prefix))
1162 (defun company-search-printing-char ()
1164 (company-search-assert-enabled)
1165 (setq company-search-string
1166 (concat (or company-search-string "") (string last-command-event))
1167 company-search-lighter (concat " Search: \"" company-search-string
1169 (let ((pos (company-search company-search-string
1170 (nthcdr company-selection company-candidates))))
1173 (company-set-selection (+ company-selection pos) t))))
1175 (defun company-search-repeat-forward ()
1176 "Repeat the incremental search in completion candidates forward."
1178 (company-search-assert-enabled)
1179 (let ((pos (company-search company-search-string
1180 (cdr (nthcdr company-selection
1181 company-candidates)))))
1184 (company-set-selection (+ company-selection pos 1) t))))
1186 (defun company-search-repeat-backward ()
1187 "Repeat the incremental search in completion candidates backwards."
1189 (company-search-assert-enabled)
1190 (let ((pos (company-search company-search-string
1191 (nthcdr (- company-candidates-length
1193 (reverse company-candidates)))))
1196 (company-set-selection (- company-selection pos 1) t))))
1198 (defun company-create-match-predicate ()
1199 (setq company-candidates-predicate
1200 `(lambda (candidate)
1201 ,(if company-candidates-predicate
1202 `(and (string-match ,company-search-string candidate)
1203 (funcall ,company-candidates-predicate
1205 `(string-match ,company-search-string candidate))))
1206 (company-update-candidates
1207 (company-apply-predicate company-candidates company-candidates-predicate))
1208 ;; Invalidate cache.
1209 (setq company-candidates-cache (cons company-prefix company-candidates)))
1211 (defun company-filter-printing-char ()
1213 (company-search-assert-enabled)
1214 (company-search-printing-char)
1215 (company-create-match-predicate)
1216 (company-call-frontends 'update))
1218 (defun company-search-kill-others ()
1219 "Limit the completion candidates to the ones matching the search string."
1221 (company-search-assert-enabled)
1222 (company-create-match-predicate)
1223 (company-search-mode 0)
1224 (company-call-frontends 'update))
1226 (defun company-search-abort ()
1227 "Abort searching the completion candidates."
1229 (company-search-assert-enabled)
1230 (company-set-selection company-search-old-selection t)
1231 (company-search-mode 0))
1233 (defun company-search-other-char ()
1235 (company-search-assert-enabled)
1236 (company-search-mode 0)
1237 (company--unread-last-input))
1239 (defvar company-search-map
1241 (keymap (make-keymap)))
1242 (if (fboundp 'max-char)
1243 (set-char-table-range (nth 1 keymap) (cons #x100 (max-char))
1244 'company-search-printing-char)
1246 ;; obsolete in Emacs 23
1247 (let ((l (generic-character-list))
1248 (table (nth 1 keymap)))
1250 (set-char-table-default table (car l) 'company-search-printing-char)
1251 (setq l (cdr l))))))
1252 (define-key keymap [t] 'company-search-other-char)
1254 (define-key keymap (make-string 1 i) 'company-search-other-char)
1257 (define-key keymap (vector i) 'company-search-printing-char)
1259 (let ((meta-map (make-sparse-keymap)))
1260 (define-key keymap (char-to-string meta-prefix-char) meta-map)
1261 (define-key keymap [escape] meta-map))
1262 (define-key keymap (vector meta-prefix-char t) 'company-search-other-char)
1263 (define-key keymap "\e\e\e" 'company-search-other-char)
1264 (define-key keymap [escape escape escape] 'company-search-other-char)
1266 (define-key keymap "\C-g" 'company-search-abort)
1267 (define-key keymap "\C-s" 'company-search-repeat-forward)
1268 (define-key keymap "\C-r" 'company-search-repeat-backward)
1269 (define-key keymap "\C-o" 'company-search-kill-others)
1271 "Keymap used for incrementally searching the completion candidates.")
1273 (define-minor-mode company-search-mode
1274 "Search mode for completion candidates.
1275 Don't start this directly, use `company-search-candidates' or
1276 `company-filter-candidates'."
1277 nil company-search-lighter nil
1278 (if company-search-mode
1279 (if (company-manual-begin)
1281 (setq company-search-old-selection company-selection)
1282 (company-call-frontends 'update))
1283 (setq company-search-mode nil))
1284 (kill-local-variable 'company-search-string)
1285 (kill-local-variable 'company-search-lighter)
1286 (kill-local-variable 'company-search-old-selection)
1287 (company-enable-overriding-keymap company-active-map)))
1289 (defsubst company-search-assert-enabled ()
1290 (company-assert-enabled)
1291 (unless company-search-mode
1292 (company-uninstall-map)
1293 (error "Company not in search mode")))
1295 (defun company-search-candidates ()
1296 "Start searching the completion candidates incrementally.
1298 \\<company-search-map>Search can be controlled with the commands:
1299 - `company-search-repeat-forward' (\\[company-search-repeat-forward])
1300 - `company-search-repeat-backward' (\\[company-search-repeat-backward])
1301 - `company-search-abort' (\\[company-search-abort])
1303 Regular characters are appended to the search string.
1305 The command `company-search-kill-others' (\\[company-search-kill-others]) uses
1306 the search string to limit the completion candidates."
1308 (company-search-mode 1)
1309 (company-enable-overriding-keymap company-search-map))
1311 (defvar company-filter-map
1312 (let ((keymap (make-keymap)))
1313 (define-key keymap [remap company-search-printing-char]
1314 'company-filter-printing-char)
1315 (set-keymap-parent keymap company-search-map)
1317 "Keymap used for incrementally searching the completion candidates.")
1319 (defun company-filter-candidates ()
1320 "Start filtering the completion candidates incrementally.
1321 This works the same way as `company-search-candidates' immediately
1322 followed by `company-search-kill-others' after each input."
1324 (company-search-mode 1)
1325 (company-enable-overriding-keymap company-filter-map))
1327 ;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;
1329 (defun company-select-next ()
1330 "Select the next candidate in the list."
1332 (when (company-manual-begin)
1333 (company-set-selection (1+ company-selection))))
1335 (defun company-select-previous ()
1336 "Select the previous candidate in the list."
1338 (when (company-manual-begin)
1339 (company-set-selection (1- company-selection))))
1341 (defun company-select-next-or-abort ()
1342 "Select the next candidate if more than one, else abort
1343 and invoke the normal binding."
1345 (if (> company-candidates-length 1)
1346 (company-select-next)
1348 (company--unread-last-input)))
1350 (defun company-select-previous-or-abort ()
1351 "Select the previous candidate if more than one, else abort
1352 and invoke the normal binding."
1354 (if (> company-candidates-length 1)
1355 (company-select-previous)
1357 (company--unread-last-input)))
1359 (defun company-select-mouse (event)
1360 "Select the candidate picked by the mouse."
1362 (when (nth 4 (event-start event))
1363 (company-set-selection (- (cdr (posn-actual-col-row (event-start event)))
1368 (defun company-complete-mouse (event)
1369 "Complete the candidate picked by the mouse."
1371 (when (company-select-mouse event)
1372 (company-complete-selection)))
1374 (defun company-complete-selection ()
1375 "Complete the selected candidate."
1377 (when (company-manual-begin)
1378 (let ((result (nth company-selection company-candidates)))
1379 (when company--auto-completion
1380 (setq result (company--safe-candidate result)))
1381 (company-finish result))))
1383 (defun company-complete-common ()
1384 "Complete the common part of all candidates."
1386 (when (company-manual-begin)
1387 (if (and (not (cdr company-candidates))
1388 (equal company-common (car company-candidates)))
1389 (company-complete-selection)
1390 (insert (company-strip-prefix company-common)))))
1392 (defun company-complete ()
1393 "Complete the common part of all candidates or the current selection.
1394 The first time this is called, the common part is completed, the second time, or
1395 when the selection has been changed, the selected candidate is completed."
1397 (when (company-manual-begin)
1398 (if (or company-selection-changed
1399 (eq last-command 'company-complete-common))
1400 (call-interactively 'company-complete-selection)
1401 (call-interactively 'company-complete-common)
1402 (setq this-command 'company-complete-common))))
1404 (defun company-complete-number (n)
1405 "Complete the Nth candidate.
1406 To show the number next to the candidates in some back-ends, enable
1407 `company-show-numbers'."
1408 (when (company-manual-begin)
1409 (and (< n 1) (> n company-candidates-length)
1410 (error "No candidate number %d" n))
1412 (company-finish (nth n company-candidates))))
1414 ;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;
1416 (defconst company-space-strings-limit 100)
1418 (defconst company-space-strings
1420 (dotimes (i company-space-strings-limit)
1421 (push (make-string (- company-space-strings-limit 1 i) ?\ ) lst))
1422 (apply 'vector lst)))
1424 (defsubst company-space-string (len)
1425 (if (< len company-space-strings-limit)
1426 (aref company-space-strings len)
1427 (make-string len ?\ )))
1429 (defsubst company-safe-substring (str from &optional to)
1430 (if (> from (string-width str))
1434 (move-to-column from)
1435 (let ((beg (point)))
1439 (concat (buffer-substring beg (point))
1440 (let ((padding (- to (current-column))))
1442 (company-space-string padding)))))
1443 (buffer-substring beg (point-max)))))))
1445 ;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;
1447 (defvar company-last-metadata nil)
1448 (make-variable-buffer-local 'company-last-metadata)
1450 (defun company-fetch-metadata ()
1451 (let ((selected (nth company-selection company-candidates)))
1452 (unless (equal selected (car company-last-metadata))
1453 (setq company-last-metadata
1454 (cons selected (company-call-backend 'meta selected))))
1455 (cdr company-last-metadata)))
1457 (defun company-doc-buffer (&optional string)
1458 (with-current-buffer (get-buffer-create "*Company meta-data*")
1462 (defvar company--electric-commands
1463 '(scroll-other-window scroll-other-window-down)
1464 "List of Commands that won't break out of electric commands.")
1466 (defmacro company--electric-do (&rest body)
1467 (declare (indent 0) (debug t))
1468 `(when (company-manual-begin)
1469 (save-window-excursion
1470 (let ((height (window-height))
1471 (row (company--row))
1474 (and (< (window-height) height)
1475 (< (- (window-height) row 2) company-tooltip-limit)
1476 (recenter (- (window-height) row 2)))
1477 (while (memq (setq cmd (key-binding (vector (list (read-event)))))
1478 company--electric-commands)
1479 (call-interactively cmd))
1480 (company--unread-last-input)))))
1482 (defun company--unread-last-input ()
1483 (when last-input-event
1484 (clear-this-command-keys t)
1485 (setq unread-command-events (list last-input-event))))
1487 (defun company-show-doc-buffer ()
1488 "Temporarily show a buffer with the complete documentation for the selection."
1490 (company--electric-do
1491 (let* ((selected (nth company-selection company-candidates))
1492 (doc-buffer (or (company-call-backend 'doc-buffer selected)
1493 (error "No documentation available"))))
1494 (with-current-buffer doc-buffer
1495 (goto-char (point-min)))
1496 (display-buffer doc-buffer t))))
1497 (put 'company-show-doc-buffer 'company-keep t)
1499 (defun company-show-location ()
1500 "Temporarily display a buffer showing the selected candidate in context."
1502 (company--electric-do
1503 (let* ((selected (nth company-selection company-candidates))
1504 (location (company-call-backend 'location selected))
1505 (pos (or (cdr location) (error "No location available")))
1506 (buffer (or (and (bufferp (car location)) (car location))
1507 (find-file-noselect (car location) t))))
1508 (with-selected-window (display-buffer buffer t)
1511 (if (bufferp (car location))
1513 (goto-char (point-min))
1514 (forward-line (1- pos))))
1515 (set-window-start nil (point))))))
1516 (put 'company-show-location 'company-keep t)
1518 ;;; package functions ;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;
1520 (defvar company-callback nil)
1521 (make-variable-buffer-local 'company-callback)
1523 (defvar company-begin-with-marker nil)
1524 (make-variable-buffer-local 'company-begin-with-marker)
1526 (defun company-remove-callback (&optional ignored)
1527 (remove-hook 'company-completion-finished-hook company-callback t)
1528 (remove-hook 'company-completion-cancelled-hook 'company-remove-callback t)
1529 (remove-hook 'company-completion-finished-hook 'company-remove-callback t)
1530 (when company-begin-with-marker
1531 (set-marker company-begin-with-marker nil)))
1533 (defun company-begin-backend (backend &optional callback)
1534 "Start a completion at point using BACKEND."
1535 (interactive (let ((val (completing-read "Company back-end: "
1537 'functionp nil "company-")))
1539 (list (intern val)))))
1540 (when (setq company-callback callback)
1541 (add-hook 'company-completion-finished-hook company-callback nil t))
1542 (add-hook 'company-completion-cancelled-hook 'company-remove-callback nil t)
1543 (add-hook 'company-completion-finished-hook 'company-remove-callback nil t)
1544 (setq company-backend backend)
1545 ;; Return non-nil if active.
1546 (or (company-manual-begin)
1548 (setq company-backend nil)
1549 (error "Cannot complete at point"))))
1551 (defun company-begin-with (candidates
1552 &optional prefix-length require-match callback)
1553 "Start a completion at point.
1554 CANDIDATES is the list of candidates to use and PREFIX-LENGTH is the length of
1555 the prefix that already is in the buffer before point. It defaults to 0.
1557 CALLBACK is a function called with the selected result if the user successfully
1558 completes the input.
1561 \(company-begin-with '\(\"foo\" \"foobar\" \"foobarbaz\"\)\)"
1562 (setq company-begin-with-marker (copy-marker (point) t))
1563 (company-begin-backend
1564 `(lambda (command &optional arg &rest ignored)
1566 ((eq command 'prefix)
1567 (when (equal (point) (marker-position company-begin-with-marker))
1568 (buffer-substring ,(- (point) (or prefix-length 0)) (point))))
1569 ((eq command 'candidates)
1570 (all-completions arg ',candidates))
1571 ((eq command 'require-match)
1575 ;;; pseudo-tooltip ;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;
1577 (defvar company-pseudo-tooltip-overlay nil)
1578 (make-variable-buffer-local 'company-pseudo-tooltip-overlay)
1580 (defvar company-tooltip-offset 0)
1581 (make-variable-buffer-local 'company-tooltip-offset)
1583 (defun company-pseudo-tooltip-update-offset (selection num-lines limit)
1586 (setq company-tooltip-offset
1587 (max (min selection company-tooltip-offset)
1588 (- selection -1 limit)))
1590 (when (<= company-tooltip-offset 1)
1592 (setq company-tooltip-offset 0))
1594 (when (>= company-tooltip-offset (- num-lines limit 1))
1596 (when (= selection (1- num-lines))
1597 (decf company-tooltip-offset)
1598 (when (<= company-tooltip-offset 1)
1599 (setq company-tooltip-offset 0)
1606 (defsubst company-round-tab (arg)
1607 (* (/ (+ arg tab-width) tab-width) tab-width))
1609 (defun company-untabify (str)
1610 (let* ((pieces (split-string str "\t"))
1613 (setcar copy (company-safe-substring
1614 (car copy) 0 (company-round-tab (string-width (car copy)))))
1616 (apply 'concat pieces)))
1618 (defun company-fill-propertize (line width selected)
1619 (setq line (company-safe-substring line 0 width))
1620 (add-text-properties 0 width '(face company-tooltip
1621 mouse-face company-tooltip-mouse)
1623 (add-text-properties 0 (length company-common)
1624 '(face company-tooltip-common
1625 mouse-face company-tooltip-mouse)
1628 (if (and company-search-string
1629 (string-match (regexp-quote company-search-string) line
1630 (length company-prefix)))
1632 (add-text-properties (match-beginning 0) (match-end 0)
1633 '(face company-tooltip-selection)
1635 (when (< (match-beginning 0) (length company-common))
1636 (add-text-properties (match-beginning 0) (length company-common)
1637 '(face company-tooltip-common-selection)
1639 (add-text-properties 0 width '(face company-tooltip-selection
1640 mouse-face company-tooltip-selection)
1642 (add-text-properties 0 (length company-common)
1643 '(face company-tooltip-common-selection
1644 mouse-face company-tooltip-selection)
1650 (defun company-buffer-lines (beg end)
1653 (while (and (= 1 (vertical-motion 1))
1655 (push (buffer-substring beg (min end (1- (point)))) lines)
1657 (unless (eq beg end)
1658 (push (buffer-substring beg end) lines))
1661 (defsubst company-modify-line (old new offset)
1662 (concat (company-safe-substring old 0 offset)
1664 (company-safe-substring old (+ offset (length new)))))
1666 (defsubst company--length-limit (lst limit)
1667 (if (nthcdr limit lst)
1671 (defun company--replacement-string (lines old column nl &optional align-top)
1673 (let ((width (length (car lines))))
1674 (when (> width (- (window-width) column))
1675 (setq column (max 0 (- (window-width) width)))))
1679 ;; untouched lines first
1680 (dotimes (i (- (length old) (length lines)))
1681 (push (pop old) new)))
1682 ;; length into old lines.
1684 (push (company-modify-line (pop old) (pop lines) column) new))
1685 ;; Append whole new lines.
1687 (push (concat (company-space-string column) (pop lines)) new))
1689 (let ((str (concat (when nl "\n")
1690 (mapconcat 'identity (nreverse new) "\n")
1692 (font-lock-append-text-property 0 (length str) 'face 'default str)
1695 (defun company--create-lines (selection limit)
1697 (let ((len company-candidates-length)
1706 ;; Scroll to offset.
1707 (setq limit (company-pseudo-tooltip-update-offset selection len limit))
1709 (when (> company-tooltip-offset 0)
1710 (setq previous (format "...(%d)" company-tooltip-offset)))
1712 (setq remainder (- len limit company-tooltip-offset)
1713 remainder (when (> remainder 0)
1714 (setq remainder (format "...(%d)" remainder))))
1716 (decf selection company-tooltip-offset)
1717 (setq width (max (length previous) (length remainder))
1718 lines (nthcdr company-tooltip-offset company-candidates)
1723 (setq width (max (length (pop lines-copy)) width)))
1724 (setq width (min width (window-width)))
1726 (setq lines-copy lines)
1728 ;; number can make tooltip too long
1729 (when company-show-numbers
1730 (setq numbered company-tooltip-offset))
1733 (push (propertize (company-safe-substring previous 0 width)
1734 'face 'company-tooltip)
1738 (push (company-fill-propertize
1739 (if (>= numbered 10)
1740 (company-reformat (pop lines))
1743 (company-safe-substring (company-reformat (pop lines))
1746 width (equal i selection))
1750 (push (propertize (company-safe-substring remainder 0 width)
1751 'face 'company-tooltip)
1754 (setq lines (nreverse new))))
1758 (defsubst company--window-inner-height ()
1759 (let ((edges (window-inside-edges (selected-window))))
1760 (- (nth 3 edges) (nth 1 edges))))
1762 (defsubst company--pseudo-tooltip-height ()
1763 "Calculate the appropriate tooltip height.
1764 Returns a negative number if the tooltip should be displayed above point."
1765 (let* ((lines (company--row))
1766 (below (- (company--window-inner-height) 1 lines)))
1767 (if (and (< below (min company-tooltip-minimum company-candidates-length))
1769 (- (max 3 (min company-tooltip-limit lines)))
1770 (max 3 (min company-tooltip-limit below)))))
1772 (defun company-pseudo-tooltip-show (row column selection)
1773 (company-pseudo-tooltip-hide)
1778 (let* ((height (company--pseudo-tooltip-height))
1782 (setq row (+ row height -1)
1785 (let* ((nl (< (move-to-window-line row) row))
1787 (end (save-excursion
1788 (move-to-window-line (+ row (abs height)))
1790 (ov (make-overlay beg end))
1791 (args (list (mapcar 'company-untabify
1792 (company-buffer-lines beg end))
1795 (setq company-pseudo-tooltip-overlay ov)
1796 (overlay-put ov 'company-replacement-args args)
1797 (overlay-put ov 'company-before
1798 (apply 'company--replacement-string
1799 (company--create-lines selection (abs height))
1802 (overlay-put ov 'company-column column)
1803 (overlay-put ov 'company-height height)))))
1805 (defun company-pseudo-tooltip-show-at-point (pos)
1806 (let ((col-row (company--col-row pos)))
1808 (company-pseudo-tooltip-show (1+ (cdr col-row)) (car col-row)
1809 company-selection))))
1811 (defun company-pseudo-tooltip-edit (lines selection)
1812 (let ((column (overlay-get company-pseudo-tooltip-overlay 'company-column))
1813 (height (overlay-get company-pseudo-tooltip-overlay 'company-height)))
1814 (overlay-put company-pseudo-tooltip-overlay 'company-before
1815 (apply 'company--replacement-string
1816 (company--create-lines selection (abs height))
1817 (overlay-get company-pseudo-tooltip-overlay
1818 'company-replacement-args)))))
1820 (defun company-pseudo-tooltip-hide ()
1821 (when company-pseudo-tooltip-overlay
1822 (delete-overlay company-pseudo-tooltip-overlay)
1823 (setq company-pseudo-tooltip-overlay nil)))
1825 (defun company-pseudo-tooltip-hide-temporarily ()
1826 (when (overlayp company-pseudo-tooltip-overlay)
1827 (overlay-put company-pseudo-tooltip-overlay 'invisible nil)
1828 (overlay-put company-pseudo-tooltip-overlay 'before-string nil)))
1830 (defun company-pseudo-tooltip-unhide ()
1831 (when company-pseudo-tooltip-overlay
1832 (overlay-put company-pseudo-tooltip-overlay 'invisible t)
1833 (overlay-put company-pseudo-tooltip-overlay 'before-string
1834 (overlay-get company-pseudo-tooltip-overlay 'company-before))
1835 (overlay-put company-pseudo-tooltip-overlay 'window (selected-window))))
1837 (defun company-pseudo-tooltip-guard ()
1838 (buffer-substring-no-properties
1839 (point) (overlay-start company-pseudo-tooltip-overlay)))
1841 (defun company-pseudo-tooltip-frontend (command)
1842 "A `company-mode' front-end similar to a tool-tip but based on overlays."
1844 (pre-command (company-pseudo-tooltip-hide-temporarily))
1846 (let ((old-height (if (overlayp company-pseudo-tooltip-overlay)
1847 (overlay-get company-pseudo-tooltip-overlay
1850 (new-height (company--pseudo-tooltip-height)))
1851 (unless (and (>= (* old-height new-height) 0)
1852 (>= (abs old-height) (abs new-height))
1853 (equal (company-pseudo-tooltip-guard)
1854 (overlay-get company-pseudo-tooltip-overlay
1857 (company-pseudo-tooltip-show-at-point (- (point)
1858 (length company-prefix)))
1859 (overlay-put company-pseudo-tooltip-overlay
1860 'company-guard (company-pseudo-tooltip-guard))))
1861 (company-pseudo-tooltip-unhide))
1862 (hide (company-pseudo-tooltip-hide)
1863 (setq company-tooltip-offset 0))
1864 (update (when (overlayp company-pseudo-tooltip-overlay)
1865 (company-pseudo-tooltip-edit company-candidates
1866 company-selection)))))
1868 (defun company-pseudo-tooltip-unless-just-one-frontend (command)
1869 "`company-pseudo-tooltip-frontend', but not shown for single candidates."
1870 (unless (and (eq command 'post-command)
1871 (not (cdr company-candidates)))
1872 (company-pseudo-tooltip-frontend command)))
1874 ;;; overlay ;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;
1876 (defvar company-preview-overlay nil)
1877 (make-variable-buffer-local 'company-preview-overlay)
1879 (defun company-preview-show-at-point (pos)
1880 (company-preview-hide)
1882 (setq company-preview-overlay (make-overlay pos pos))
1884 (let ((completion(nth company-selection company-candidates)))
1885 (setq completion (propertize completion 'face 'company-preview))
1886 (add-text-properties 0 (length company-common)
1887 '(face company-preview-common) completion)
1889 ;; Add search string
1890 (and company-search-string
1891 (string-match (regexp-quote company-search-string) completion)
1892 (add-text-properties (match-beginning 0)
1894 '(face company-preview-search)
1897 (setq completion (company-strip-prefix completion))
1899 (and (equal pos (point))
1900 (not (equal completion ""))
1901 (add-text-properties 0 1 '(cursor t) completion))
1903 (overlay-put company-preview-overlay 'after-string completion)
1904 (overlay-put company-preview-overlay 'window (selected-window))))
1906 (defun company-preview-hide ()
1907 (when company-preview-overlay
1908 (delete-overlay company-preview-overlay)
1909 (setq company-preview-overlay nil)))
1911 (defun company-preview-frontend (command)
1912 "A `company-mode' front-end showing the selection as if it had been inserted."
1914 (pre-command (company-preview-hide))
1915 (post-command (company-preview-show-at-point (point)))
1916 (hide (company-preview-hide))))
1918 (defun company-preview-if-just-one-frontend (command)
1919 "`company-preview-frontend', but only shown for single candidates."
1920 (unless (and (eq command 'post-command)
1921 (cdr company-candidates))
1922 (company-preview-frontend command)))
1924 ;;; echo ;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;
1926 (defvar company-echo-last-msg nil)
1927 (make-variable-buffer-local 'company-echo-last-msg)
1929 (defvar company-echo-timer nil)
1931 (defvar company-echo-delay .01)
1933 (defun company-echo-show (&optional getter)
1935 (setq company-echo-last-msg (funcall getter)))
1936 (let ((message-log-max nil))
1937 (if company-echo-last-msg
1938 (message "%s" company-echo-last-msg)
1941 (defsubst company-echo-show-soon (&optional getter)
1942 (when company-echo-timer
1943 (cancel-timer company-echo-timer))
1944 (setq company-echo-timer (run-with-timer 0 nil 'company-echo-show getter)))
1946 (defsubst company-echo-show-when-idle (&optional getter)
1948 (company-echo-show getter)))
1950 (defsubst company-echo-show-when-not-busy (&optional getter)
1951 "Run `company-echo-show' with arg GETTER once Emacs isn't busy."
1952 (when (sit-for company-echo-delay)
1953 (company-echo-show getter)))
1955 (defun company-echo-format ()
1957 (let ((limit (window-width (minibuffer-window)))
1959 ;; Roll to selection.
1960 (candidates (nthcdr company-selection company-candidates))
1961 (i (if company-show-numbers company-selection 99999))
1965 (setq comp (company-reformat (pop candidates))
1966 len (+ len 1 (length comp)))
1970 (setq comp (propertize (format "%d: %s" i comp)
1971 'face 'company-echo))
1974 (add-text-properties 3 (+ 3 (length company-common))
1975 '(face company-echo-common) comp))
1976 (setq comp (propertize comp 'face 'company-echo))
1977 (add-text-properties 0 (length company-common)
1978 '(face company-echo-common) comp))
1980 (setq candidates nil)
1983 (mapconcat 'identity (nreverse msg) " ")))
1985 (defun company-echo-strip-common-format ()
1987 (let ((limit (window-width (minibuffer-window)))
1988 (len (+ (length company-prefix) 2))
1989 ;; Roll to selection.
1990 (candidates (nthcdr company-selection company-candidates))
1991 (i (if company-show-numbers company-selection 99999))
1995 (setq comp (company-strip-prefix (pop candidates))
1996 len (+ len 2 (length comp)))
1999 (setq comp (format "%s (%d)" comp i))
2003 (setq candidates nil)
2004 (push (propertize comp 'face 'company-echo) msg)))
2006 (concat (propertize company-prefix 'face 'company-echo-common) "{"
2007 (mapconcat 'identity (nreverse msg) ", ")
2010 (defun company-echo-hide ()
2011 (unless (equal company-echo-last-msg "")
2012 (setq company-echo-last-msg "")
2013 (company-echo-show)))
2015 (defun company-echo-frontend (command)
2016 "A `company-mode' front-end showing the candidates in the echo area."
2018 (post-command (company-echo-show-soon 'company-echo-format))
2019 (hide (company-echo-hide))))
2021 (defun company-echo-strip-common-frontend (command)
2022 "A `company-mode' front-end showing the candidates in the echo area."
2024 (post-command (company-echo-show-soon 'company-echo-strip-common-format))
2025 (hide (company-echo-hide))))
2027 (defun company-echo-metadata-frontend (command)
2028 "A `company-mode' front-end showing the documentation in the echo area."
2030 (post-command (company-echo-show-when-idle 'company-fetch-metadata))
2031 (hide (company-echo-hide))))
2034 ;;; company.el ends here