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)
898 (company-auto-begin))
900 (defun company-other-backend (&optional backward)
901 (interactive (list current-prefix-arg))
902 (company-assert-enabled)
904 (let* ((after (cdr (member company-backend company-backends)))
905 (before (cdr (member company-backend (reverse company-backends))))
907 (append before (reverse after))
908 (append after (reverse before)))))
910 (dolist (backend next)
911 (when (ignore-errors (company-begin-backend backend))
913 (company-manual-begin))
914 (unless company-candidates
915 (error "No other back-end")))
917 (defun company-require-match-p ()
918 (let ((backend-value (company-call-backend 'require-match)))
919 (or (eq backend-value t)
920 (and (if (functionp company-require-match)
921 (funcall company-require-match)
922 (eq company-require-match t))
923 (not (eq backend-value 'never))))))
925 (defun company-punctuation-p (input)
926 "Return non-nil, if input starts with punctuation or parentheses."
927 (memq (char-syntax (string-to-char input)) '(?. ?\( ?\))))
929 (defun company-auto-complete-p (input)
930 "Return non-nil, if input starts with punctuation or parentheses."
931 (and (if (functionp company-auto-complete)
932 (funcall company-auto-complete)
933 company-auto-complete)
934 (if (functionp company-auto-complete-chars)
935 (funcall company-auto-complete-chars input)
936 (if (consp company-auto-complete-chars)
937 (memq (char-syntax (string-to-char input))
938 company-auto-complete-chars)
939 (string-match (substring input 0 1) company-auto-complete-chars)))))
941 (defun company--incremental-p ()
942 (and (> (point) company-point)
943 (> (point-max) company--point-max)
944 (not (eq this-command 'backward-delete-char-untabify))
945 (equal (buffer-substring (- company-point (length company-prefix))
949 (defsubst company--string-incremental-p (old-prefix new-prefix)
950 (and (> (length new-prefix) (length old-prefix))
951 (equal old-prefix (substring new-prefix 0 (length old-prefix)))))
953 (defun company--continue-failed (new-prefix)
954 (when (company--incremental-p)
955 (let ((input (buffer-substring-no-properties (point) company-point)))
957 ((company-auto-complete-p input)
960 (goto-char company-point)
961 (let ((company--auto-completion t))
962 (company-complete-selection))
964 ((and (company--string-incremental-p company-prefix new-prefix)
965 (company-require-match-p))
966 ;; wrong incremental input, but required match
967 (backward-delete-char (length input))
969 (message "Matching input is required")
971 ((equal company-prefix (car company-candidates))
972 ;; last input was actually success
973 (company-cancel company-prefix)
976 (defun company--good-prefix-p (prefix)
977 (and (or (company-explicit-action-p)
978 (unless (eq prefix 'stop)
979 (>= (or (cdr-safe prefix) (length prefix))
980 company-minimum-prefix-length)))
981 (stringp (or (car-safe prefix) prefix))))
983 (defun company--continue ()
984 (when (company-call-backend 'no-cache company-prefix)
985 ;; Don't complete existing candidates, fetch new ones.
986 (setq company-candidates-cache nil))
987 (let* ((new-prefix (company-call-backend 'prefix))
988 (c (when (and (company--good-prefix-p new-prefix)
989 (setq new-prefix (or (car-safe new-prefix) new-prefix))
990 (= (- (point) (length new-prefix))
991 (- company-point (length company-prefix))))
992 (setq new-prefix (or (car-safe new-prefix) new-prefix))
993 (company-calculate-candidates new-prefix))))
996 ;; t means complete/unique.
997 (company-cancel new-prefix)
1000 ;; incremental match
1001 (setq company-prefix new-prefix)
1002 (company-update-candidates c)
1004 (t (company--continue-failed new-prefix)))
1007 (defun company--begin-new ()
1009 (dolist (backend (if company-backend
1010 ;; prefer manual override
1011 (list company-backend)
1014 (if (or (symbolp backend)
1015 (functionp backend))
1016 (when (or (not (symbolp backend))
1017 (eq t (get backend 'company-init))
1018 (unless (get backend 'company-init)
1019 (company-init-backend backend)))
1020 (funcall backend 'prefix))
1021 (company--multi-backend-adapter backend 'prefix)))
1023 (when (company--good-prefix-p prefix)
1024 (setq prefix (or (car-safe prefix) prefix)
1025 company-backend backend
1026 c (company-calculate-candidates prefix))
1027 ;; t means complete/unique. We don't start, so no hooks.
1029 (when company--explicit-action
1030 (message "No completion found"))
1031 (setq company-prefix prefix)
1032 (when (symbolp backend)
1033 (setq company-lighter (concat " " (symbol-name backend))))
1034 (company-update-candidates c)
1035 (run-hook-with-args 'company-completion-started-hook
1036 (company-explicit-action-p))
1037 (company-call-frontends 'show)))
1040 (defun company-begin ()
1041 (or (and company-candidates (company--continue))
1042 (and (company--should-complete) (company--begin-new)))
1043 (when company-candidates
1044 (when (and company-end-of-buffer-workaround (eobp))
1045 (save-excursion (insert "\n"))
1046 (setq company-added-newline (buffer-chars-modified-tick)))
1047 (setq company-point (point)
1048 company--point-max (point-max))
1049 (company-ensure-emulation-alist)
1050 (company-enable-overriding-keymap company-active-map)
1051 (company-call-frontends 'update)))
1053 (defun company-cancel (&optional result)
1054 (and company-added-newline
1055 (> (point-max) (point-min))
1056 (let ((tick (buffer-chars-modified-tick)))
1057 (delete-region (1- (point-max)) (point-max))
1058 (equal tick company-added-newline))
1059 ;; Only set unmodified when tick remained the same since insert.
1060 (set-buffer-modified-p nil))
1061 (when company-prefix
1062 (if (stringp result)
1064 (company-call-backend 'pre-completion result)
1065 (run-hook-with-args 'company-completion-finished-hook result)
1066 (company-call-backend 'post-completion result))
1067 (run-hook-with-args 'company-completion-cancelled-hook result)))
1068 (setq company-added-newline nil
1071 company-candidates nil
1072 company-candidates-length nil
1073 company-candidates-cache nil
1074 company-candidates-predicate nil
1077 company-selection-changed nil
1078 company--explicit-action nil
1079 company-lighter company-default-lighter
1080 company--point-max nil
1083 (cancel-timer company-timer))
1084 (company-search-mode 0)
1085 (company-call-frontends 'hide)
1086 (company-enable-overriding-keymap nil))
1088 (defun company-abort ()
1091 ;; Don't start again, unless started manually.
1092 (setq company-point (point)))
1094 (defun company-finish (result)
1095 (insert (company-strip-prefix result))
1096 (company-cancel result)
1097 ;; Don't start again, unless started manually.
1098 (setq company-point (point)))
1100 (defsubst company-keep (command)
1101 (and (symbolp command) (get command 'company-keep)))
1103 (defun company-pre-command ()
1104 (unless (company-keep this-command)
1106 (when company-candidates
1107 (company-call-frontends 'pre-command))
1108 (error (message "Company: An error occurred in pre-command")
1109 (message "%s" (error-message-string err))
1112 (cancel-timer company-timer)
1113 (setq company-timer nil))
1114 (company-uninstall-map))
1116 (defun company-post-command ()
1117 (unless (company-keep this-command)
1120 (unless (equal (point) company-point)
1122 (if company-candidates
1123 (company-call-frontends 'post-command)
1124 (and (numberp company-idle-delay)
1125 (or (eq t company-begin-commands)
1126 (memq this-command company-begin-commands))
1128 (run-with-timer company-idle-delay nil
1130 (current-buffer) (selected-window)
1131 (buffer-chars-modified-tick) (point))))))
1132 (error (message "Company: An error occurred in post-command")
1133 (message "%s" (error-message-string err))
1135 (company-install-map))
1137 ;;; search ;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;
1139 (defvar company-search-string nil)
1140 (make-variable-buffer-local 'company-search-string)
1142 (defvar company-search-lighter " Search: \"\"")
1143 (make-variable-buffer-local 'company-search-lighter)
1145 (defvar company-search-old-map nil)
1146 (make-variable-buffer-local 'company-search-old-map)
1148 (defvar company-search-old-selection 0)
1149 (make-variable-buffer-local 'company-search-old-selection)
1151 (defun company-search (text lines)
1152 (let ((quoted (regexp-quote text))
1154 (dolist (line lines)
1155 (when (string-match quoted line (length company-prefix))
1159 (defun company-search-printing-char ()
1161 (company-search-assert-enabled)
1162 (setq company-search-string
1163 (concat (or company-search-string "") (string last-command-event))
1164 company-search-lighter (concat " Search: \"" company-search-string
1166 (let ((pos (company-search company-search-string
1167 (nthcdr company-selection company-candidates))))
1170 (company-set-selection (+ company-selection pos) t))))
1172 (defun company-search-repeat-forward ()
1173 "Repeat the incremental search in completion candidates forward."
1175 (company-search-assert-enabled)
1176 (let ((pos (company-search company-search-string
1177 (cdr (nthcdr company-selection
1178 company-candidates)))))
1181 (company-set-selection (+ company-selection pos 1) t))))
1183 (defun company-search-repeat-backward ()
1184 "Repeat the incremental search in completion candidates backwards."
1186 (company-search-assert-enabled)
1187 (let ((pos (company-search company-search-string
1188 (nthcdr (- company-candidates-length
1190 (reverse company-candidates)))))
1193 (company-set-selection (- company-selection pos 1) t))))
1195 (defun company-create-match-predicate ()
1196 (setq company-candidates-predicate
1197 `(lambda (candidate)
1198 ,(if company-candidates-predicate
1199 `(and (string-match ,company-search-string candidate)
1200 (funcall ,company-candidates-predicate
1202 `(string-match ,company-search-string candidate))))
1203 (company-update-candidates
1204 (company-apply-predicate company-candidates company-candidates-predicate))
1205 ;; Invalidate cache.
1206 (setq company-candidates-cache (cons company-prefix company-candidates)))
1208 (defun company-filter-printing-char ()
1210 (company-search-assert-enabled)
1211 (company-search-printing-char)
1212 (company-create-match-predicate)
1213 (company-call-frontends 'update))
1215 (defun company-search-kill-others ()
1216 "Limit the completion candidates to the ones matching the search string."
1218 (company-search-assert-enabled)
1219 (company-create-match-predicate)
1220 (company-search-mode 0)
1221 (company-call-frontends 'update))
1223 (defun company-search-abort ()
1224 "Abort searching the completion candidates."
1226 (company-search-assert-enabled)
1227 (company-set-selection company-search-old-selection t)
1228 (company-search-mode 0))
1230 (defun company-search-other-char ()
1232 (company-search-assert-enabled)
1233 (company-search-mode 0)
1234 (company--unread-last-input))
1236 (defvar company-search-map
1238 (keymap (make-keymap)))
1239 (if (fboundp 'max-char)
1240 (set-char-table-range (nth 1 keymap) (cons #x100 (max-char))
1241 'company-search-printing-char)
1243 ;; obsolete in Emacs 23
1244 (let ((l (generic-character-list))
1245 (table (nth 1 keymap)))
1247 (set-char-table-default table (car l) 'company-search-printing-char)
1248 (setq l (cdr l))))))
1249 (define-key keymap [t] 'company-search-other-char)
1251 (define-key keymap (make-string 1 i) 'company-search-other-char)
1254 (define-key keymap (vector i) 'company-search-printing-char)
1256 (let ((meta-map (make-sparse-keymap)))
1257 (define-key keymap (char-to-string meta-prefix-char) meta-map)
1258 (define-key keymap [escape] meta-map))
1259 (define-key keymap (vector meta-prefix-char t) 'company-search-other-char)
1260 (define-key keymap "\e\e\e" 'company-search-other-char)
1261 (define-key keymap [escape escape escape] 'company-search-other-char)
1263 (define-key keymap "\C-g" 'company-search-abort)
1264 (define-key keymap "\C-s" 'company-search-repeat-forward)
1265 (define-key keymap "\C-r" 'company-search-repeat-backward)
1266 (define-key keymap "\C-o" 'company-search-kill-others)
1268 "Keymap used for incrementally searching the completion candidates.")
1270 (define-minor-mode company-search-mode
1271 "Search mode for completion candidates.
1272 Don't start this directly, use `company-search-candidates' or
1273 `company-filter-candidates'."
1274 nil company-search-lighter nil
1275 (if company-search-mode
1276 (if (company-manual-begin)
1278 (setq company-search-old-selection company-selection)
1279 (company-call-frontends 'update))
1280 (setq company-search-mode nil))
1281 (kill-local-variable 'company-search-string)
1282 (kill-local-variable 'company-search-lighter)
1283 (kill-local-variable 'company-search-old-selection)
1284 (company-enable-overriding-keymap company-active-map)))
1286 (defsubst company-search-assert-enabled ()
1287 (company-assert-enabled)
1288 (unless company-search-mode
1289 (company-uninstall-map)
1290 (error "Company not in search mode")))
1292 (defun company-search-candidates ()
1293 "Start searching the completion candidates incrementally.
1295 \\<company-search-map>Search can be controlled with the commands:
1296 - `company-search-repeat-forward' (\\[company-search-repeat-forward])
1297 - `company-search-repeat-backward' (\\[company-search-repeat-backward])
1298 - `company-search-abort' (\\[company-search-abort])
1300 Regular characters are appended to the search string.
1302 The command `company-search-kill-others' (\\[company-search-kill-others]) uses
1303 the search string to limit the completion candidates."
1305 (company-search-mode 1)
1306 (company-enable-overriding-keymap company-search-map))
1308 (defvar company-filter-map
1309 (let ((keymap (make-keymap)))
1310 (define-key keymap [remap company-search-printing-char]
1311 'company-filter-printing-char)
1312 (set-keymap-parent keymap company-search-map)
1314 "Keymap used for incrementally searching the completion candidates.")
1316 (defun company-filter-candidates ()
1317 "Start filtering the completion candidates incrementally.
1318 This works the same way as `company-search-candidates' immediately
1319 followed by `company-search-kill-others' after each input."
1321 (company-search-mode 1)
1322 (company-enable-overriding-keymap company-filter-map))
1324 ;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;
1326 (defun company-select-next ()
1327 "Select the next candidate in the list."
1329 (when (company-manual-begin)
1330 (company-set-selection (1+ company-selection))))
1332 (defun company-select-previous ()
1333 "Select the previous candidate in the list."
1335 (when (company-manual-begin)
1336 (company-set-selection (1- company-selection))))
1338 (defun company-select-next-or-abort ()
1339 "Select the next candidate if more than one, else abort
1340 and invoke the normal binding."
1342 (if (> company-candidates-length 1)
1343 (company-select-next)
1345 (company--unread-last-input)))
1347 (defun company-select-previous-or-abort ()
1348 "Select the previous candidate if more than one, else abort
1349 and invoke the normal binding."
1351 (if (> company-candidates-length 1)
1352 (company-select-previous)
1354 (company--unread-last-input)))
1356 (defun company-select-mouse (event)
1357 "Select the candidate picked by the mouse."
1359 (when (nth 4 (event-start event))
1360 (company-set-selection (- (cdr (posn-actual-col-row (event-start event)))
1365 (defun company-complete-mouse (event)
1366 "Complete the candidate picked by the mouse."
1368 (when (company-select-mouse event)
1369 (company-complete-selection)))
1371 (defun company-complete-selection ()
1372 "Complete the selected candidate."
1374 (when (company-manual-begin)
1375 (let ((result (nth company-selection company-candidates)))
1376 (when company--auto-completion
1377 (setq result (company--safe-candidate result)))
1378 (company-finish result))))
1380 (defun company-complete-common ()
1381 "Complete the common part of all candidates."
1383 (when (company-manual-begin)
1384 (if (and (not (cdr company-candidates))
1385 (equal company-common (car company-candidates)))
1386 (company-complete-selection)
1387 (insert (company-strip-prefix company-common)))))
1389 (defun company-complete ()
1390 "Complete the common part of all candidates or the current selection.
1391 The first time this is called, the common part is completed, the second time, or
1392 when the selection has been changed, the selected candidate is completed."
1394 (when (company-manual-begin)
1395 (if (or company-selection-changed
1396 (eq last-command 'company-complete-common))
1397 (call-interactively 'company-complete-selection)
1398 (call-interactively 'company-complete-common)
1399 (setq this-command 'company-complete-common))))
1401 (defun company-complete-number (n)
1402 "Complete the Nth candidate.
1403 To show the number next to the candidates in some back-ends, enable
1404 `company-show-numbers'."
1405 (when (company-manual-begin)
1406 (and (< n 1) (> n company-candidates-length)
1407 (error "No candidate number %d" n))
1409 (company-finish (nth n company-candidates))))
1411 ;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;
1413 (defconst company-space-strings-limit 100)
1415 (defconst company-space-strings
1417 (dotimes (i company-space-strings-limit)
1418 (push (make-string (- company-space-strings-limit 1 i) ?\ ) lst))
1419 (apply 'vector lst)))
1421 (defsubst company-space-string (len)
1422 (if (< len company-space-strings-limit)
1423 (aref company-space-strings len)
1424 (make-string len ?\ )))
1426 (defsubst company-safe-substring (str from &optional to)
1427 (if (> from (string-width str))
1431 (move-to-column from)
1432 (let ((beg (point)))
1436 (concat (buffer-substring beg (point))
1437 (let ((padding (- to (current-column))))
1439 (company-space-string padding)))))
1440 (buffer-substring beg (point-max)))))))
1442 ;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;
1444 (defvar company-last-metadata nil)
1445 (make-variable-buffer-local 'company-last-metadata)
1447 (defun company-fetch-metadata ()
1448 (let ((selected (nth company-selection company-candidates)))
1449 (unless (equal selected (car company-last-metadata))
1450 (setq company-last-metadata
1451 (cons selected (company-call-backend 'meta selected))))
1452 (cdr company-last-metadata)))
1454 (defun company-doc-buffer (&optional string)
1455 (with-current-buffer (get-buffer-create "*Company meta-data*")
1459 (defvar company--electric-commands
1460 '(scroll-other-window scroll-other-window-down)
1461 "List of Commands that won't break out of electric commands.")
1463 (defmacro company--electric-do (&rest body)
1464 (declare (indent 0) (debug t))
1465 `(when (company-manual-begin)
1466 (save-window-excursion
1467 (let ((height (window-height))
1468 (row (company--row))
1471 (and (< (window-height) height)
1472 (< (- (window-height) row 2) company-tooltip-limit)
1473 (recenter (- (window-height) row 2)))
1474 (while (memq (setq cmd (key-binding (vector (list (read-event)))))
1475 company--electric-commands)
1476 (call-interactively cmd))
1477 (company--unread-last-input)))))
1479 (defun company--unread-last-input ()
1480 (when last-input-event
1481 (clear-this-command-keys t)
1482 (setq unread-command-events (list last-input-event))))
1484 (defun company-show-doc-buffer ()
1485 "Temporarily show a buffer with the complete documentation for the selection."
1487 (company--electric-do
1488 (let* ((selected (nth company-selection company-candidates))
1489 (doc-buffer (or (company-call-backend 'doc-buffer selected)
1490 (error "No documentation available"))))
1491 (with-current-buffer doc-buffer
1492 (goto-char (point-min)))
1493 (display-buffer doc-buffer t))))
1494 (put 'company-show-doc-buffer 'company-keep t)
1496 (defun company-show-location ()
1497 "Temporarily display a buffer showing the selected candidate in context."
1499 (company--electric-do
1500 (let* ((selected (nth company-selection company-candidates))
1501 (location (company-call-backend 'location selected))
1502 (pos (or (cdr location) (error "No location available")))
1503 (buffer (or (and (bufferp (car location)) (car location))
1504 (find-file-noselect (car location) t))))
1505 (with-selected-window (display-buffer buffer t)
1508 (if (bufferp (car location))
1510 (goto-char (point-min))
1511 (forward-line (1- pos))))
1512 (set-window-start nil (point))))))
1513 (put 'company-show-location 'company-keep t)
1515 ;;; package functions ;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;
1517 (defvar company-callback nil)
1518 (make-variable-buffer-local 'company-callback)
1520 (defvar company-begin-with-marker nil)
1521 (make-variable-buffer-local 'company-begin-with-marker)
1523 (defun company-remove-callback (&optional ignored)
1524 (remove-hook 'company-completion-finished-hook company-callback t)
1525 (remove-hook 'company-completion-cancelled-hook 'company-remove-callback t)
1526 (remove-hook 'company-completion-finished-hook 'company-remove-callback t)
1527 (when company-begin-with-marker
1528 (set-marker company-begin-with-marker nil)))
1530 (defun company-begin-backend (backend &optional callback)
1531 "Start a completion at point using BACKEND."
1532 (interactive (let ((val (completing-read "Company back-end: "
1534 'functionp nil "company-")))
1536 (list (intern val)))))
1537 (when (setq company-callback callback)
1538 (add-hook 'company-completion-finished-hook company-callback nil t))
1539 (add-hook 'company-completion-cancelled-hook 'company-remove-callback nil t)
1540 (add-hook 'company-completion-finished-hook 'company-remove-callback nil t)
1541 (setq company-backend backend)
1542 ;; Return non-nil if active.
1543 (or (company-manual-begin)
1545 (setq company-backend nil)
1546 (error "Cannot complete at point"))))
1548 (defun company-begin-with (candidates
1549 &optional prefix-length require-match callback)
1550 "Start a completion at point.
1551 CANDIDATES is the list of candidates to use and PREFIX-LENGTH is the length of
1552 the prefix that already is in the buffer before point. It defaults to 0.
1554 CALLBACK is a function called with the selected result if the user successfully
1555 completes the input.
1558 \(company-begin-with '\(\"foo\" \"foobar\" \"foobarbaz\"\)\)"
1559 (setq company-begin-with-marker (copy-marker (point) t))
1560 (company-begin-backend
1561 `(lambda (command &optional arg &rest ignored)
1563 ((eq command 'prefix)
1564 (when (equal (point) (marker-position company-begin-with-marker))
1565 (buffer-substring ,(- (point) (or prefix-length 0)) (point))))
1566 ((eq command 'candidates)
1567 (all-completions arg ',candidates))
1568 ((eq command 'require-match)
1572 ;;; pseudo-tooltip ;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;
1574 (defvar company-pseudo-tooltip-overlay nil)
1575 (make-variable-buffer-local 'company-pseudo-tooltip-overlay)
1577 (defvar company-tooltip-offset 0)
1578 (make-variable-buffer-local 'company-tooltip-offset)
1580 (defun company-pseudo-tooltip-update-offset (selection num-lines limit)
1583 (setq company-tooltip-offset
1584 (max (min selection company-tooltip-offset)
1585 (- selection -1 limit)))
1587 (when (<= company-tooltip-offset 1)
1589 (setq company-tooltip-offset 0))
1591 (when (>= company-tooltip-offset (- num-lines limit 1))
1593 (when (= selection (1- num-lines))
1594 (decf company-tooltip-offset)
1595 (when (<= company-tooltip-offset 1)
1596 (setq company-tooltip-offset 0)
1603 (defsubst company-round-tab (arg)
1604 (* (/ (+ arg tab-width) tab-width) tab-width))
1606 (defun company-untabify (str)
1607 (let* ((pieces (split-string str "\t"))
1610 (setcar copy (company-safe-substring
1611 (car copy) 0 (company-round-tab (string-width (car copy)))))
1613 (apply 'concat pieces)))
1615 (defun company-fill-propertize (line width selected)
1616 (setq line (company-safe-substring line 0 width))
1617 (add-text-properties 0 width '(face company-tooltip
1618 mouse-face company-tooltip-mouse)
1620 (add-text-properties 0 (length company-common)
1621 '(face company-tooltip-common
1622 mouse-face company-tooltip-mouse)
1625 (if (and company-search-string
1626 (string-match (regexp-quote company-search-string) line
1627 (length company-prefix)))
1629 (add-text-properties (match-beginning 0) (match-end 0)
1630 '(face company-tooltip-selection)
1632 (when (< (match-beginning 0) (length company-common))
1633 (add-text-properties (match-beginning 0) (length company-common)
1634 '(face company-tooltip-common-selection)
1636 (add-text-properties 0 width '(face company-tooltip-selection
1637 mouse-face company-tooltip-selection)
1639 (add-text-properties 0 (length company-common)
1640 '(face company-tooltip-common-selection
1641 mouse-face company-tooltip-selection)
1647 (defun company-buffer-lines (beg end)
1650 (while (and (= 1 (vertical-motion 1))
1652 (push (buffer-substring beg (min end (1- (point)))) lines)
1654 (unless (eq beg end)
1655 (push (buffer-substring beg end) lines))
1658 (defsubst company-modify-line (old new offset)
1659 (concat (company-safe-substring old 0 offset)
1661 (company-safe-substring old (+ offset (length new)))))
1663 (defsubst company--length-limit (lst limit)
1664 (if (nthcdr limit lst)
1668 (defun company--replacement-string (lines old column nl &optional align-top)
1670 (let ((width (length (car lines))))
1671 (when (> width (- (window-width) column))
1672 (setq column (max 0 (- (window-width) width)))))
1676 ;; untouched lines first
1677 (dotimes (i (- (length old) (length lines)))
1678 (push (pop old) new)))
1679 ;; length into old lines.
1681 (push (company-modify-line (pop old) (pop lines) column) new))
1682 ;; Append whole new lines.
1684 (push (concat (company-space-string column) (pop lines)) new))
1686 (let ((str (concat (when nl "\n")
1687 (mapconcat 'identity (nreverse new) "\n")
1689 (font-lock-append-text-property 0 (length str) 'face 'default str)
1692 (defun company--create-lines (selection limit)
1694 (let ((len company-candidates-length)
1703 ;; Scroll to offset.
1704 (setq limit (company-pseudo-tooltip-update-offset selection len limit))
1706 (when (> company-tooltip-offset 0)
1707 (setq previous (format "...(%d)" company-tooltip-offset)))
1709 (setq remainder (- len limit company-tooltip-offset)
1710 remainder (when (> remainder 0)
1711 (setq remainder (format "...(%d)" remainder))))
1713 (decf selection company-tooltip-offset)
1714 (setq width (max (length previous) (length remainder))
1715 lines (nthcdr company-tooltip-offset company-candidates)
1720 (setq width (max (length (pop lines-copy)) width)))
1721 (setq width (min width (window-width)))
1723 (setq lines-copy lines)
1725 ;; number can make tooltip too long
1726 (when company-show-numbers
1727 (setq numbered company-tooltip-offset))
1730 (push (propertize (company-safe-substring previous 0 width)
1731 'face 'company-tooltip)
1735 (push (company-fill-propertize
1736 (if (>= numbered 10)
1737 (company-reformat (pop lines))
1740 (company-safe-substring (company-reformat (pop lines))
1743 width (equal i selection))
1747 (push (propertize (company-safe-substring remainder 0 width)
1748 'face 'company-tooltip)
1751 (setq lines (nreverse new))))
1755 (defsubst company--window-inner-height ()
1756 (let ((edges (window-inside-edges (selected-window))))
1757 (- (nth 3 edges) (nth 1 edges))))
1759 (defsubst company--pseudo-tooltip-height ()
1760 "Calculate the appropriate tooltip height.
1761 Returns a negative number if the tooltip should be displayed above point."
1762 (let* ((lines (company--row))
1763 (below (- (company--window-inner-height) 1 lines)))
1764 (if (and (< below (min company-tooltip-minimum company-candidates-length))
1766 (- (max 3 (min company-tooltip-limit lines)))
1767 (max 3 (min company-tooltip-limit below)))))
1769 (defun company-pseudo-tooltip-show (row column selection)
1770 (company-pseudo-tooltip-hide)
1775 (let* ((height (company--pseudo-tooltip-height))
1779 (setq row (+ row height -1)
1782 (let* ((nl (< (move-to-window-line row) row))
1784 (end (save-excursion
1785 (move-to-window-line (+ row (abs height)))
1787 (ov (make-overlay beg end))
1788 (args (list (mapcar 'company-untabify
1789 (company-buffer-lines beg end))
1792 (setq company-pseudo-tooltip-overlay ov)
1793 (overlay-put ov 'company-replacement-args args)
1794 (overlay-put ov 'company-before
1795 (apply 'company--replacement-string
1796 (company--create-lines selection (abs height))
1799 (overlay-put ov 'company-column column)
1800 (overlay-put ov 'company-height height)))))
1802 (defun company-pseudo-tooltip-show-at-point (pos)
1803 (let ((col-row (company--col-row pos)))
1805 (company-pseudo-tooltip-show (1+ (cdr col-row)) (car col-row)
1806 company-selection))))
1808 (defun company-pseudo-tooltip-edit (lines selection)
1809 (let ((column (overlay-get company-pseudo-tooltip-overlay 'company-column))
1810 (height (overlay-get company-pseudo-tooltip-overlay 'company-height)))
1811 (overlay-put company-pseudo-tooltip-overlay 'company-before
1812 (apply 'company--replacement-string
1813 (company--create-lines selection (abs height))
1814 (overlay-get company-pseudo-tooltip-overlay
1815 'company-replacement-args)))))
1817 (defun company-pseudo-tooltip-hide ()
1818 (when company-pseudo-tooltip-overlay
1819 (delete-overlay company-pseudo-tooltip-overlay)
1820 (setq company-pseudo-tooltip-overlay nil)))
1822 (defun company-pseudo-tooltip-hide-temporarily ()
1823 (when (overlayp company-pseudo-tooltip-overlay)
1824 (overlay-put company-pseudo-tooltip-overlay 'invisible nil)
1825 (overlay-put company-pseudo-tooltip-overlay 'before-string nil)))
1827 (defun company-pseudo-tooltip-unhide ()
1828 (when company-pseudo-tooltip-overlay
1829 (overlay-put company-pseudo-tooltip-overlay 'invisible t)
1830 (overlay-put company-pseudo-tooltip-overlay 'before-string
1831 (overlay-get company-pseudo-tooltip-overlay 'company-before))
1832 (overlay-put company-pseudo-tooltip-overlay 'window (selected-window))))
1834 (defun company-pseudo-tooltip-guard ()
1835 (buffer-substring-no-properties
1836 (point) (overlay-start company-pseudo-tooltip-overlay)))
1838 (defun company-pseudo-tooltip-frontend (command)
1839 "A `company-mode' front-end similar to a tool-tip but based on overlays."
1841 (pre-command (company-pseudo-tooltip-hide-temporarily))
1843 (let ((old-height (if (overlayp company-pseudo-tooltip-overlay)
1844 (overlay-get company-pseudo-tooltip-overlay
1847 (new-height (company--pseudo-tooltip-height)))
1848 (unless (and (>= (* old-height new-height) 0)
1849 (>= (abs old-height) (abs new-height))
1850 (equal (company-pseudo-tooltip-guard)
1851 (overlay-get company-pseudo-tooltip-overlay
1854 (company-pseudo-tooltip-show-at-point (- (point)
1855 (length company-prefix)))
1856 (overlay-put company-pseudo-tooltip-overlay
1857 'company-guard (company-pseudo-tooltip-guard))))
1858 (company-pseudo-tooltip-unhide))
1859 (hide (company-pseudo-tooltip-hide)
1860 (setq company-tooltip-offset 0))
1861 (update (when (overlayp company-pseudo-tooltip-overlay)
1862 (company-pseudo-tooltip-edit company-candidates
1863 company-selection)))))
1865 (defun company-pseudo-tooltip-unless-just-one-frontend (command)
1866 "`company-pseudo-tooltip-frontend', but not shown for single candidates."
1867 (unless (and (eq command 'post-command)
1868 (not (cdr company-candidates)))
1869 (company-pseudo-tooltip-frontend command)))
1871 ;;; overlay ;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;
1873 (defvar company-preview-overlay nil)
1874 (make-variable-buffer-local 'company-preview-overlay)
1876 (defun company-preview-show-at-point (pos)
1877 (company-preview-hide)
1879 (setq company-preview-overlay (make-overlay pos pos))
1881 (let ((completion(nth company-selection company-candidates)))
1882 (setq completion (propertize completion 'face 'company-preview))
1883 (add-text-properties 0 (length company-common)
1884 '(face company-preview-common) completion)
1886 ;; Add search string
1887 (and company-search-string
1888 (string-match (regexp-quote company-search-string) completion)
1889 (add-text-properties (match-beginning 0)
1891 '(face company-preview-search)
1894 (setq completion (company-strip-prefix completion))
1896 (and (equal pos (point))
1897 (not (equal completion ""))
1898 (add-text-properties 0 1 '(cursor t) completion))
1900 (overlay-put company-preview-overlay 'after-string completion)
1901 (overlay-put company-preview-overlay 'window (selected-window))))
1903 (defun company-preview-hide ()
1904 (when company-preview-overlay
1905 (delete-overlay company-preview-overlay)
1906 (setq company-preview-overlay nil)))
1908 (defun company-preview-frontend (command)
1909 "A `company-mode' front-end showing the selection as if it had been inserted."
1911 (pre-command (company-preview-hide))
1912 (post-command (company-preview-show-at-point (point)))
1913 (hide (company-preview-hide))))
1915 (defun company-preview-if-just-one-frontend (command)
1916 "`company-preview-frontend', but only shown for single candidates."
1917 (unless (and (eq command 'post-command)
1918 (cdr company-candidates))
1919 (company-preview-frontend command)))
1921 ;;; echo ;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;
1923 (defvar company-echo-last-msg nil)
1924 (make-variable-buffer-local 'company-echo-last-msg)
1926 (defvar company-echo-timer nil)
1928 (defvar company-echo-delay .01)
1930 (defun company-echo-show (&optional getter)
1932 (setq company-echo-last-msg (funcall getter)))
1933 (let ((message-log-max nil))
1934 (if company-echo-last-msg
1935 (message "%s" company-echo-last-msg)
1938 (defsubst company-echo-show-soon (&optional getter)
1939 (when company-echo-timer
1940 (cancel-timer company-echo-timer))
1941 (setq company-echo-timer (run-with-timer 0 nil 'company-echo-show getter)))
1943 (defsubst company-echo-show-when-idle (&optional getter)
1945 (company-echo-show getter)))
1947 (defsubst company-echo-show-when-not-busy (&optional getter)
1948 "Run `company-echo-show' with arg GETTER once Emacs isn't busy."
1949 (when (sit-for company-echo-delay)
1950 (company-echo-show getter)))
1952 (defun company-echo-format ()
1954 (let ((limit (window-width (minibuffer-window)))
1956 ;; Roll to selection.
1957 (candidates (nthcdr company-selection company-candidates))
1958 (i (if company-show-numbers company-selection 99999))
1962 (setq comp (company-reformat (pop candidates))
1963 len (+ len 1 (length comp)))
1967 (setq comp (propertize (format "%d: %s" i comp)
1968 'face 'company-echo))
1971 (add-text-properties 3 (+ 3 (length company-common))
1972 '(face company-echo-common) comp))
1973 (setq comp (propertize comp 'face 'company-echo))
1974 (add-text-properties 0 (length company-common)
1975 '(face company-echo-common) comp))
1977 (setq candidates nil)
1980 (mapconcat 'identity (nreverse msg) " ")))
1982 (defun company-echo-strip-common-format ()
1984 (let ((limit (window-width (minibuffer-window)))
1985 (len (+ (length company-prefix) 2))
1986 ;; Roll to selection.
1987 (candidates (nthcdr company-selection company-candidates))
1988 (i (if company-show-numbers company-selection 99999))
1992 (setq comp (company-strip-prefix (pop candidates))
1993 len (+ len 2 (length comp)))
1996 (setq comp (format "%s (%d)" comp i))
2000 (setq candidates nil)
2001 (push (propertize comp 'face 'company-echo) msg)))
2003 (concat (propertize company-prefix 'face 'company-echo-common) "{"
2004 (mapconcat 'identity (nreverse msg) ", ")
2007 (defun company-echo-hide ()
2008 (unless (equal company-echo-last-msg "")
2009 (setq company-echo-last-msg "")
2010 (company-echo-show)))
2012 (defun company-echo-frontend (command)
2013 "A `company-mode' front-end showing the candidates in the echo area."
2015 (post-command (company-echo-show-soon 'company-echo-format))
2016 (hide (company-echo-hide))))
2018 (defun company-echo-strip-common-frontend (command)
2019 "A `company-mode' front-end showing the candidates in the echo area."
2021 (post-command (company-echo-show-soon 'company-echo-strip-common-format))
2022 (hide (company-echo-hide))))
2024 (defun company-echo-metadata-frontend (command)
2025 "A `company-mode' front-end showing the documentation in the echo area."
2027 (post-command (company-echo-show-when-idle 'company-fetch-metadata))
2028 (hide (company-echo-hide))))
2031 ;;; company.el ends here