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.io/
10 ;; Compatibility: GNU Emacs 22.x, GNU Emacs 23.x, GNU Emacs 24.x
12 ;; This file is part of GNU Emacs.
14 ;; GNU Emacs is free software: you can redistribute it and/or modify
15 ;; it under the terms of the GNU General Public License as published by
16 ;; the Free Software Foundation, either version 3 of the License, or
17 ;; (at your option) any later version.
19 ;; GNU Emacs is distributed in the hope that it will be useful,
20 ;; but WITHOUT ANY WARRANTY; without even the implied warranty of
21 ;; MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
22 ;; GNU General Public License for more details.
24 ;; You should have received a copy of the GNU General Public License
25 ;; along with GNU Emacs. If not, see <http://www.gnu.org/licenses/>.
29 ;; Company is a modular completion mechanism. Modules for retrieving completion
30 ;; candidates are called back-ends, modules for displaying them are front-ends.
32 ;; Company comes with many back-ends, e.g. `company-elisp'. These are
33 ;; distributed in separate files and can be used individually.
35 ;; Place company.el and the back-ends you want to use in a directory and add the
36 ;; following to your .emacs:
37 ;; (add-to-list 'load-path "/path/to/company")
38 ;; (autoload 'company-mode "company" nil t)
40 ;; Enable company-mode with M-x company-mode. For further information look at
41 ;; the documentation for `company-mode' (C-h f company-mode RET)
43 ;; If you want to start a specific back-end, call it interactively or use
44 ;; `company-begin-backend'. For example:
45 ;; M-x company-abbrev will prompt for and insert an abbrev.
47 ;; To write your own back-end, look at the documentation for `company-backends'.
48 ;; Here is a simple example completing "foo":
50 ;; (defun company-my-backend (command &optional arg &rest ignored)
52 ;; (prefix (when (looking-back "foo\\>")
54 ;; (candidates (list "foobar" "foobaz" "foobarbaz"))
55 ;; (meta (format "This value is named %s" arg))))
57 ;; Sometimes it is a good idea to mix several back-ends together, for example to
58 ;; enrich gtags with dabbrev-code results (to emulate local variables).
59 ;; To do this, add a list with both back-ends as an element in company-backends.
62 ;; When point is at the very end of the buffer, the pseudo-tooltip appears very
63 ;; wrong, unless company is allowed to temporarily insert a fake newline.
64 ;; This behavior is enabled by `company-end-of-buffer-workaround'.
68 ;; See NEWS.md in the repository.
72 (eval-when-compile (require 'cl))
74 ;; FIXME: Use `user-error'.
75 (add-to-list 'debug-ignored-errors "^.* frontend cannot be used twice$")
76 (add-to-list 'debug-ignored-errors "^Echo area cannot be used twice$")
77 (add-to-list 'debug-ignored-errors "^No \\(document\\|loc\\)ation available$")
78 (add-to-list 'debug-ignored-errors "^Company not ")
79 (add-to-list 'debug-ignored-errors "^No candidate number ")
80 (add-to-list 'debug-ignored-errors "^Cannot complete at point$")
81 (add-to-list 'debug-ignored-errors "^No other back-end$")
84 "Extensible inline text completion mechanism"
89 (defface company-tooltip
90 '((default :foreground "black")
91 (((class color) (min-colors 88) (background light))
92 (:background "cornsilk"))
93 (((class color) (min-colors 88) (background dark))
94 (:background "yellow")))
95 "Face used for the tooltip.")
97 (defface company-tooltip-selection
98 '((default :inherit company-tooltip)
99 (((class color) (min-colors 88) (background light))
100 (:background "light blue"))
101 (((class color) (min-colors 88) (background dark))
102 (:background "orange1"))
103 (t (:background "green")))
104 "Face used for the selection in the tooltip.")
106 (defface company-tooltip-mouse
107 '((default :inherit highlight))
108 "Face used for the tooltip item under the mouse.")
110 (defface company-tooltip-common
111 '((default :inherit company-tooltip)
112 (((background light))
113 :foreground "darkred")
116 "Face used for the common completion in the tooltip.")
118 (defface company-tooltip-common-selection
119 '((default :inherit company-tooltip-selection)
120 (((background light))
121 :foreground "darkred")
124 "Face used for the selected common completion in the tooltip.")
126 (defface company-preview
127 '((t :background "blue4"
128 :foreground "wheat"))
129 "Face used for the completion preview.")
131 (defface company-preview-common
132 '((t :inherit company-preview
134 "Face used for the common part of the completion preview.")
136 (defface company-preview-search
137 '((t :inherit company-preview
138 :background "blue1"))
139 "Face used for the search string in the completion preview.")
141 (defface company-echo nil
142 "Face used for completions in the echo area.")
144 (defface company-echo-common
145 '((((background dark)) (:foreground "firebrick1"))
146 (((background light)) (:background "firebrick4")))
147 "Face used for the common part of completions in the echo area.")
149 (defun company-frontends-set (variable value)
151 (let ((remainder value))
152 (setcdr remainder (delq (car remainder) (cdr remainder))))
153 (and (memq 'company-pseudo-tooltip-unless-just-one-frontend value)
154 (memq 'company-pseudo-tooltip-frontend value)
155 (error "Pseudo tooltip frontend cannot be used twice"))
156 (and (memq 'company-preview-if-just-one-frontend value)
157 (memq 'company-preview-frontend value)
158 (error "Preview frontend cannot be used twice"))
159 (and (memq 'company-echo value)
160 (memq 'company-echo-metadata-frontend value)
161 (error "Echo area cannot be used twice"))
162 ;; preview must come last
163 (dolist (f '(company-preview-if-just-one-frontend company-preview-frontend))
165 (setq value (append (delq f value) (list f)))))
166 (set variable value))
168 (defcustom company-frontends '(company-pseudo-tooltip-unless-just-one-frontend
169 company-preview-if-just-one-frontend
170 company-echo-metadata-frontend)
171 "The list of active front-ends (visualizations).
172 Each front-end is a function that takes one argument. It is called with
173 one of the following arguments:
175 `show': When the visualization should start.
177 `hide': When the visualization should end.
179 `update': When the data has been updated.
181 `pre-command': Before every command that is executed while the
182 visualization is active.
184 `post-command': After every command that is executed while the
185 visualization is active.
187 The visualized data is stored in `company-prefix', `company-candidates',
188 `company-common', `company-selection', `company-point' and
189 `company-search-string'."
190 :set 'company-frontends-set
191 :type '(repeat (choice (const :tag "echo" company-echo-frontend)
192 (const :tag "echo, strip common"
193 company-echo-strip-common-frontend)
194 (const :tag "show echo meta-data in echo"
195 company-echo-metadata-frontend)
196 (const :tag "pseudo tooltip"
197 company-pseudo-tooltip-frontend)
198 (const :tag "pseudo tooltip, multiple only"
199 company-pseudo-tooltip-unless-just-one-frontend)
200 (const :tag "preview" company-preview-frontend)
201 (const :tag "preview, unique only"
202 company-preview-if-just-one-frontend)
203 (function :tag "custom function" nil))))
205 (defcustom company-tooltip-limit 10
206 "The maximum number of candidates in the tooltip"
209 (defcustom company-tooltip-minimum 6
210 "The minimum height of the tooltip.
211 If this many lines are not available, prefer to display the tooltip above."
214 (defvar company-safe-backends
215 '((company-abbrev . "Abbrev")
216 (company-capf . "completion-at-point-functions")
217 (company-clang . "Clang")
218 (company-css . "CSS")
219 (company-dabbrev . "dabbrev for plain text")
220 (company-dabbrev-code . "dabbrev for code")
221 (company-eclim . "Eclim (an Eclipse interface)")
222 (company-elisp . "Emacs Lisp")
223 (company-etags . "etags")
224 (company-files . "Files")
225 (company-gtags . "GNU Global")
226 (company-ispell . "Ispell")
227 (company-keywords . "Programming language keywords")
228 (company-nxml . "nxml")
229 (company-oddmuse . "Oddmuse")
230 (company-pysmell . "PySmell")
231 (company-ropemacs . "ropemacs")
232 (company-semantic . "Semantic")
233 (company-tempo . "Tempo templates")
234 (company-xcode . "Xcode")))
235 (put 'company-safe-backends 'risky-local-variable t)
237 (defun company-safe-backends-p (backends)
238 (and (consp backends)
239 (not (dolist (backend backends)
240 (unless (if (consp backend)
241 (company-safe-backends-p backend)
242 (assq backend company-safe-backends))
245 (defcustom company-backends '(company-elisp company-nxml company-css
246 company-semantic company-clang company-eclim
247 company-xcode company-ropemacs
248 (company-gtags company-etags company-dabbrev-code
250 company-oddmuse company-files company-dabbrev)
251 "The list of active back-ends (completion engines).
252 Each list elements can itself be a list of back-ends. In that case their
253 completions are merged. Otherwise only the first matching back-end returns
256 `company-begin-backend' can be used to start a specific back-end,
257 `company-other-backend' will skip to the next matching back-end in the list.
259 Each back-end is a function that takes a variable number of arguments.
260 The first argument is the command requested from the back-end. It is one
263 `prefix': The back-end should return the text to be completed. It must be text
264 immediately before point. Returning nil passes control to the next back-end.
265 The function should return `stop' if it should complete but cannot \(e.g. if it
266 is in the middle of a string\). Instead of a string, the back-end may return a
267 cons where car is the prefix and cdr is used in `company-minimum-prefix-length'
268 test. It's either number or t, in which case the test automatically succeeds.
270 `candidates': The second argument is the prefix to be completed. The
271 return value should be a list of candidates that start with the prefix.
275 `sorted': The back-end may return t here to indicate that the candidates
276 are sorted and will not need to be sorted again.
278 `duplicates': If non-nil, company will take care of removing duplicates
281 `no-cache': Usually company doesn't ask for candidates again as completion
282 progresses, unless the back-end returns t for this command. The second
283 argument is the latest prefix.
285 `meta': The second argument is a completion candidate. The back-end should
286 return a (short) documentation string for it.
288 `doc-buffer': The second argument is a completion candidate.
289 The back-end should create a buffer (preferably with `company-doc-buffer'),
290 fill it with documentation and return it.
292 `location': The second argument is a completion candidate. The back-end can
293 return the cons of buffer and buffer location, or of file and line
294 number where the completion candidate was defined.
296 `require-match': If this value is t, the user is not allowed to enter anything
297 not offered as a candidate. Use with care! The default value nil gives the
298 user that choice with `company-require-match'. Return value 'never overrides
299 that option the other way around.
301 `init': Called once for each buffer, the back-end can check for external
302 programs and files and load any required libraries. Raising an error here will
303 show up in message log once, and the backend will not be used for completion.
305 `post-completion': Called after a completion candidate has been inserted into
306 the buffer. The second argument is the candidate. Can be used to modify it,
307 e.g. to expand a snippet.
309 The back-end should return nil for all commands it does not support or
310 does not know about. It should also be callable interactively and use
311 `company-begin-backend' to start itself in that case."
315 ,@(mapcar (lambda (b) `(const :tag ,(cdr b) ,(car b)))
316 company-safe-backends)
317 (symbol :tag "User defined")
318 (repeat :tag "Merged Back-ends"
319 (choice :tag "Back-end"
320 ,@(mapcar (lambda (b)
321 `(const :tag ,(cdr b) ,(car b)))
322 company-safe-backends)
323 (symbol :tag "User defined"))))))
325 (put 'company-backends 'safe-local-variable 'company-safe-backends-p)
327 (defcustom company-completion-started-hook nil
328 "Hook run when company starts completing.
329 The hook is called with one argument that is non-nil if the completion was
333 (defcustom company-completion-cancelled-hook nil
334 "Hook run when company cancels completing.
335 The hook is called with one argument that is non-nil if the completion was
339 (defcustom company-completion-finished-hook nil
340 "Hook run when company successfully completes.
341 The hook is called with the selected candidate as an argument.
343 If you indend to use it to post-process candidates from a specific back-end,
344 consider using the `post-completion' command instead."
347 (defcustom company-minimum-prefix-length 3
348 "The minimum prefix length for automatic completion."
349 :type '(integer :tag "prefix length"))
351 (defcustom company-require-match 'company-explicit-action-p
352 "If enabled, disallow non-matching input.
353 This can be a function do determine if a match is required.
355 This can be overridden by the back-end, if it returns t or `never' to
356 `require-match'. `company-auto-complete' also takes precedence over this."
357 :type '(choice (const :tag "Off" nil)
358 (function :tag "Predicate function")
359 (const :tag "On, if user interaction took place"
360 'company-explicit-action-p)
361 (const :tag "On" t)))
363 (defcustom company-auto-complete nil
364 "Determines when to auto-complete.
365 If this is enabled, all characters from `company-auto-complete-chars' complete
366 the selected completion. This can also be a function."
367 :type '(choice (const :tag "Off" nil)
368 (function :tag "Predicate function")
369 (const :tag "On, if user interaction took place"
370 'company-explicit-action-p)
371 (const :tag "On" t)))
373 (defcustom company-auto-complete-chars '(?\ ?\) ?.)
374 "Determines which characters trigger an automatic completion.
375 See `company-auto-complete'. If this is a string, each string character causes
376 completion. If it is a list of syntax description characters (see
377 `modify-syntax-entry'), all characters with that syntax auto-complete.
379 This can also be a function, which is called with the new input and should
380 return non-nil if company should auto-complete.
382 A character that is part of a valid candidate never triggers auto-completion."
383 :type '(choice (string :tag "Characters")
385 (const :tag "Whitespace" ?\ )
386 (const :tag "Symbol" ?_)
387 (const :tag "Opening parentheses" ?\()
388 (const :tag "Closing parentheses" ?\))
389 (const :tag "Word constituent" ?w)
390 (const :tag "Punctuation." ?.)
391 (const :tag "String quote." ?\")
392 (const :tag "Paired delimiter." ?$)
393 (const :tag "Expression quote or prefix operator." ?\')
394 (const :tag "Comment starter." ?<)
395 (const :tag "Comment ender." ?>)
396 (const :tag "Character-quote." ?/)
397 (const :tag "Generic string fence." ?|)
398 (const :tag "Generic comment fence." ?!))
399 (function :tag "Predicate function")))
401 (defcustom company-idle-delay .7
402 "The idle delay in seconds until automatic completions starts.
403 A value of nil means never complete automatically, t means complete
404 immediately when a prefix of `company-minimum-prefix-length' is reached."
405 :type '(choice (const :tag "never (nil)" nil)
406 (const :tag "immediate (t)" t)
407 (number :tag "seconds")))
409 (defcustom company-begin-commands t
410 "A list of commands following which company will start completing.
411 If this is t, it will complete after any command. See `company-idle-delay'.
413 Alternatively any command with a non-nil 'company-begin property is treated as
414 if it was on this list."
415 :type '(choice (const :tag "Any command" t)
416 (const :tag "Self insert command" '(self-insert-command))
417 (repeat :tag "Commands" function)))
419 (defcustom company-show-numbers nil
420 "If enabled, show quick-access numbers for the first ten candidates."
421 :type '(choice (const :tag "off" nil)
422 (const :tag "on" t)))
424 (defvar company-end-of-buffer-workaround t
425 "Work around a visualization bug when completing at the end of the buffer.
426 The work-around consists of adding a newline.")
428 ;;; mode ;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;
430 (defvar company-mode-map (make-sparse-keymap)
431 "Keymap used by `company-mode'.")
433 (defvar company-active-map
434 (let ((keymap (make-sparse-keymap)))
435 (define-key keymap "\e\e\e" 'company-abort)
436 (define-key keymap "\C-g" 'company-abort)
437 (define-key keymap (kbd "M-n") 'company-select-next)
438 (define-key keymap (kbd "M-p") 'company-select-previous)
439 (define-key keymap (kbd "<down>") 'company-select-next-or-abort)
440 (define-key keymap (kbd "<up>") 'company-select-previous-or-abort)
441 (define-key keymap [down-mouse-1] 'ignore)
442 (define-key keymap [down-mouse-3] 'ignore)
443 (define-key keymap [mouse-1] 'company-complete-mouse)
444 (define-key keymap [mouse-3] 'company-select-mouse)
445 (define-key keymap [up-mouse-1] 'ignore)
446 (define-key keymap [up-mouse-3] 'ignore)
447 (define-key keymap [return] 'company-complete-selection)
448 (define-key keymap (kbd "RET") 'company-complete-selection)
449 (define-key keymap [tab] 'company-complete-common)
450 (define-key keymap (kbd "TAB") 'company-complete-common)
451 (define-key keymap (kbd "<f1>") 'company-show-doc-buffer)
452 (define-key keymap "\C-w" 'company-show-location)
453 (define-key keymap "\C-s" 'company-search-candidates)
454 (define-key keymap "\C-\M-s" 'company-filter-candidates)
456 (define-key keymap (vector (+ (aref (kbd "M-0") 0) i))
457 `(lambda () (interactive) (company-complete-number ,i))))
460 "Keymap that is enabled during an active completion.")
462 (defvar company--disabled-backends nil)
464 (defun company-init-backend (backend)
465 (and (symbolp backend)
466 (not (fboundp backend))
467 (ignore-errors (require backend nil t)))
469 (if (or (symbolp backend)
473 (funcall backend 'init)
474 (put backend 'company-init t))
476 (put backend 'company-init 'failed)
477 (unless (memq backend company--disabled-backends)
478 (message "Company back-end '%s' could not be initialized:\n%s"
479 backend (error-message-string err)))
480 (pushnew backend company--disabled-backends)
482 (mapc 'company-init-backend backend)))
484 (defvar company-default-lighter " company")
486 (defvar company-lighter company-default-lighter)
487 (make-variable-buffer-local 'company-lighter)
490 (define-minor-mode company-mode
491 "\"complete anything\"; is an in-buffer completion framework.
492 Completion starts automatically, depending on the values
493 `company-idle-delay' and `company-minimum-prefix-length'.
495 Completion can be controlled with the commands:
496 `company-complete-common', `company-complete-selection', `company-complete',
497 `company-select-next', `company-select-previous'. If these commands are
498 called before `company-idle-delay', completion will also start.
500 Completions can be searched with `company-search-candidates' or
501 `company-filter-candidates'. These can be used while completion is
504 The completion data is retrieved using `company-backends' and displayed using
505 `company-frontends'. If you want to start a specific back-end, call it
506 interactively or use `company-begin-backend'.
508 regular keymap (`company-mode-map'):
511 keymap during active completions (`company-active-map'):
513 \\{company-active-map}"
514 nil company-lighter company-mode-map
517 (add-hook 'pre-command-hook 'company-pre-command nil t)
518 (add-hook 'post-command-hook 'company-post-command nil t)
519 (mapc 'company-init-backend company-backends))
520 (remove-hook 'pre-command-hook 'company-pre-command t)
521 (remove-hook 'post-command-hook 'company-post-command t)
523 (kill-local-variable 'company-point)))
526 (define-globalized-minor-mode global-company-mode company-mode company-mode-on)
528 (defun company-mode-on ()
529 (unless (or noninteractive (eq (aref (buffer-name) 0) ?\s))
532 (defsubst company-assert-enabled ()
534 (company-uninstall-map)
535 (error "Company not enabled")))
537 ;;; keymaps ;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;
539 (defvar company-my-keymap nil)
540 (make-variable-buffer-local 'company-my-keymap)
542 (defvar company-emulation-alist '((t . nil)))
544 (defsubst company-enable-overriding-keymap (keymap)
545 (company-uninstall-map)
546 (setq company-my-keymap keymap))
548 (defun company-ensure-emulation-alist ()
549 (unless (eq 'company-emulation-alist (car emulation-mode-map-alists))
550 (setq emulation-mode-map-alists
551 (cons 'company-emulation-alist
552 (delq 'company-emulation-alist emulation-mode-map-alists)))))
554 (defun company-install-map ()
555 (unless (or (cdar company-emulation-alist)
556 (null company-my-keymap))
557 (setf (cdar company-emulation-alist) company-my-keymap)))
559 (defun company-uninstall-map ()
560 (setf (cdar company-emulation-alist) nil))
563 ;; Emacs calculates the active keymaps before reading the event. That means we
564 ;; cannot change the keymap from a timer. So we send a bogus command.
565 (defun company-ignore ()
567 (setq this-command last-command))
569 (global-set-key '[31415926] 'company-ignore)
571 (defun company-input-noop ()
572 (push 31415926 unread-command-events))
574 (defun company--column (&optional pos)
576 (when pos (goto-char pos))
578 (narrow-to-region (save-excursion
579 (vertical-motion 0) (point))
583 (defun company--row (&optional pos)
585 (when pos (goto-char pos))
586 (count-screen-lines (window-start)
587 (progn (vertical-motion 0) (point)))))
589 ;;; backends ;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;
591 (defvar company-backend nil)
592 (make-variable-buffer-local 'company-backend)
594 (defun company-grab (regexp &optional expression limit)
595 (when (looking-back regexp limit)
596 (or (match-string-no-properties (or expression 0)) "")))
598 (defun company-grab-line (regexp &optional expression)
599 (company-grab regexp expression (point-at-bol)))
601 (defun company-grab-symbol ()
602 (if (looking-at "\\_>")
603 (buffer-substring (point) (save-excursion (skip-syntax-backward "w_")
605 (unless (and (char-after) (memq (char-syntax (char-after)) '(?w ?_)))
608 (defun company-grab-word ()
609 (if (looking-at "\\>")
610 (buffer-substring (point) (save-excursion (skip-syntax-backward "w")
612 (unless (and (char-after) (eq (char-syntax (char-after)) ?w))
615 (defun company-in-string-or-comment ()
616 (let ((ppss (syntax-ppss)))
617 (or (car (setq ppss (nthcdr 3 ppss)))
618 (car (setq ppss (cdr ppss)))
621 (if (fboundp 'locate-dominating-file)
622 (defalias 'company-locate-dominating-file 'locate-dominating-file)
623 (defun company-locate-dominating-file (file name)
625 (let ((dir (file-name-directory file))
627 (while (not (equal dir prev-dir))
628 (when (file-exists-p (expand-file-name name dir))
631 dir (file-name-directory (directory-file-name dir))))))))
633 (defun company-call-backend (&rest args)
634 (if (functionp company-backend)
635 (apply company-backend args)
636 (apply 'company--multi-backend-adapter company-backend args)))
638 (defun company--multi-backend-adapter (backends command &rest args)
639 (let ((backends (loop for b in backends
640 when (not (and (symbolp b)
641 (eq 'failed (get b 'company-init))))
645 (loop for backend in backends
646 when (equal (funcall backend 'prefix)
648 append (apply backend 'candidates args)))
653 (dolist (backend backends)
654 (when (setq value (apply backend command args))
655 (return value))))))))
657 ;;; completion mechanism ;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;
659 (defvar company-prefix nil)
660 (make-variable-buffer-local 'company-prefix)
662 (defvar company-candidates nil)
663 (make-variable-buffer-local 'company-candidates)
665 (defvar company-candidates-length nil)
666 (make-variable-buffer-local 'company-candidates-length)
668 (defvar company-candidates-cache nil)
669 (make-variable-buffer-local 'company-candidates-cache)
671 (defvar company-candidates-predicate nil)
672 (make-variable-buffer-local 'company-candidates-predicate)
674 (defvar company-common nil)
675 (make-variable-buffer-local 'company-common)
677 (defvar company-selection 0)
678 (make-variable-buffer-local 'company-selection)
680 (defvar company-selection-changed nil)
681 (make-variable-buffer-local 'company-selection-changed)
683 (defvar company--explicit-action nil
684 "Non-nil, if explicit completion took place.")
685 (make-variable-buffer-local 'company--explicit-action)
687 (defvar company--auto-completion nil
688 "Non-nil when current candidate is being completed automatically.
689 Controlled by `company-auto-complete'.")
691 (defvar company--point-max nil)
692 (make-variable-buffer-local 'company--point-max)
694 (defvar company-point nil)
695 (make-variable-buffer-local 'company-point)
697 (defvar company-timer nil)
699 (defvar company-added-newline nil)
700 (make-variable-buffer-local 'company-added-newline)
702 (defsubst company-strip-prefix (str)
703 (substring str (length company-prefix)))
705 (defmacro company-with-candidate-inserted (candidate &rest body)
706 "Evaluate BODY with CANDIDATE temporarily inserted.
707 This is a tool for back-ends that need candidates inserted before they
708 can retrieve meta-data for them."
710 `(let ((inhibit-modification-hooks t)
711 (inhibit-point-motion-hooks t)
712 (modified-p (buffer-modified-p)))
713 (insert (company-strip-prefix ,candidate))
716 (delete-region company-point (point)))))
718 (defun company-explicit-action-p ()
719 "Return whether explicit completion action was taken by the user."
720 (or company--explicit-action
721 company-selection-changed))
723 (defsubst company-reformat (candidate)
724 ;; company-ispell needs this, because the results are always lower-case
725 ;; It's mory efficient to fix it only when they are displayed.
726 (concat company-prefix (substring candidate (length company-prefix))))
728 (defun company--should-complete ()
729 (and (not (or buffer-read-only overriding-terminal-local-map
732 ;; Check if in the middle of entering a key combination.
733 (or (equal (this-command-keys-vector) [])
734 (not (keymapp (key-binding (this-command-keys-vector)))))
735 (eq company-idle-delay t)
736 (or (eq t company-begin-commands)
737 (memq this-command company-begin-commands)
738 (and (symbolp this-command) (get this-command 'company-begin)))
739 (not (and transient-mark-mode mark-active))))
741 (defsubst company-call-frontends (command)
742 (dolist (frontend company-frontends)
744 (funcall frontend command)
745 (error (error "Company: Front-end %s error \"%s\" on command %s"
746 frontend (error-message-string err) command)))))
748 (defsubst company-set-selection (selection &optional force-update)
749 (setq selection (max 0 (min (1- company-candidates-length) selection)))
750 (when (or force-update (not (equal selection company-selection)))
751 (setq company-selection selection
752 company-selection-changed t)
753 (company-call-frontends 'update)))
755 (defun company-apply-predicate (candidates predicate)
757 (dolist (c candidates)
758 (when (funcall predicate c)
762 (defun company-update-candidates (candidates)
763 (setq company-candidates-length (length candidates))
764 (if (> company-selection 0)
765 ;; Try to restore the selection
766 (let ((selected (nth company-selection company-candidates)))
767 (setq company-selection 0
768 company-candidates candidates)
770 (while (and candidates (string< (pop candidates) selected))
771 (incf company-selection))
773 ;; Make sure selection isn't out of bounds.
774 (setq company-selection (min (1- company-candidates-length)
775 company-selection)))))
776 (setq company-selection 0
777 company-candidates candidates))
779 (push (cons company-prefix company-candidates) company-candidates-cache)
781 (let ((completion-ignore-case (company-call-backend 'ignore-case)))
782 (setq company-common (company--safe-candidate
783 (try-completion company-prefix company-candidates))))
784 (when (eq company-common t)
785 (setq company-candidates nil)))
787 (defun company--safe-candidate (str)
788 (or (company-call-backend 'crop str)
791 (defun company-calculate-candidates (prefix)
792 (let ((candidates (cdr (assoc prefix company-candidates-cache)))
793 (ignore-case (company-call-backend 'ignore-case)))
795 (when company-candidates-cache
796 (let ((len (length prefix))
797 (completion-ignore-case ignore-case)
799 (dotimes (i (1+ len))
800 (when (setq prev (cdr (assoc (substring prefix 0 (- len i))
801 company-candidates-cache)))
802 (setq candidates (all-completions prefix prev))
804 ;; no cache match, call back-end
806 (setq candidates (company-call-backend 'candidates prefix))
807 (when company-candidates-predicate
809 (company-apply-predicate candidates
810 company-candidates-predicate)))
811 (unless (company-call-backend 'sorted)
812 (setq candidates (sort candidates 'string<)))
813 (when (company-call-backend 'duplicates)
815 (let ((c2 candidates))
817 (setcdr c2 (progn (while (equal (pop c2) (car c2)))
820 (if (or (cdr candidates)
821 (not (eq t (compare-strings (car candidates) nil nil
822 prefix nil nil ignore-case))))
824 ;; Already completed and unique; don't start.
827 (defun company-idle-begin (buf win tick pos)
829 (eq buf (current-buffer))
830 (eq win (selected-window))
831 (eq tick (buffer-chars-modified-tick))
833 (not company-candidates)
834 (not (equal (point) company-point))
835 (let ((company-idle-delay t)
836 (company-begin-commands t))
838 (when company-candidates
840 (company-post-command)))))
842 (defun company-auto-begin ()
843 (company-assert-enabled)
845 (not company-candidates)
846 (let ((company-idle-delay t)
847 (company-minimum-prefix-length 0)
848 (company-begin-commands t))
850 ;; Return non-nil if active.
853 (defun company-manual-begin ()
855 (setq company--explicit-action t)
858 (unless company-candidates
859 (setq company--explicit-action nil))))
861 (defun company-other-backend (&optional backward)
862 (interactive (list current-prefix-arg))
863 (company-assert-enabled)
865 (let* ((after (cdr (member company-backend company-backends)))
866 (before (cdr (member company-backend (reverse company-backends))))
868 (append before (reverse after))
869 (append after (reverse before)))))
871 (dolist (backend next)
872 (when (ignore-errors (company-begin-backend backend))
874 (company-manual-begin))
875 (unless company-candidates
876 (error "No other back-end")))
878 (defun company-require-match-p ()
879 (let ((backend-value (company-call-backend 'require-match)))
880 (or (eq backend-value t)
881 (and (not (eq backend-value 'never))
882 (if (functionp company-require-match)
883 (funcall company-require-match)
884 (eq company-require-match t))))))
886 (defun company-auto-complete-p (input)
887 "Return non-nil, if input starts with punctuation or parentheses."
888 (and (if (functionp company-auto-complete)
889 (funcall company-auto-complete)
890 company-auto-complete)
891 (if (functionp company-auto-complete-chars)
892 (funcall company-auto-complete-chars input)
893 (if (consp company-auto-complete-chars)
894 (memq (char-syntax (string-to-char input))
895 company-auto-complete-chars)
896 (string-match (substring input 0 1) company-auto-complete-chars)))))
898 (defun company--incremental-p ()
899 (and (> (point) company-point)
900 (> (point-max) company--point-max)
901 (not (eq this-command 'backward-delete-char-untabify))
902 (equal (buffer-substring (- company-point (length company-prefix))
906 (defsubst company--string-incremental-p (old-prefix new-prefix)
907 (and (> (length new-prefix) (length old-prefix))
908 (equal old-prefix (substring new-prefix 0 (length old-prefix)))))
910 (defun company--continue-failed (new-prefix)
911 (when (company--incremental-p)
912 (let ((input (buffer-substring-no-properties (point) company-point)))
914 ((company-auto-complete-p input)
917 (goto-char company-point)
918 (let ((company--auto-completion t))
919 (company-complete-selection))
921 ((and (company--string-incremental-p company-prefix new-prefix)
922 (company-require-match-p))
923 ;; wrong incremental input, but required match
924 (delete-char (- (length input)))
926 (message "Matching input is required")
928 ((equal company-prefix (car company-candidates))
929 ;; last input was actually success
930 (company-cancel company-prefix)
933 (defun company--good-prefix-p (prefix)
934 (and (or (company-explicit-action-p)
935 (unless (eq prefix 'stop)
936 (or (eq (cdr-safe prefix) t)
937 (>= (or (cdr-safe prefix) (length prefix))
938 company-minimum-prefix-length))))
939 (stringp (or (car-safe prefix) prefix))))
941 (defun company--continue ()
942 (when (company-call-backend 'no-cache company-prefix)
943 ;; Don't complete existing candidates, fetch new ones.
944 (setq company-candidates-cache nil))
945 (let* ((new-prefix (company-call-backend 'prefix))
946 (c (when (and (company--good-prefix-p new-prefix)
947 (setq new-prefix (or (car-safe new-prefix) new-prefix))
948 (= (- (point) (length new-prefix))
949 (- company-point (length company-prefix))))
950 (setq new-prefix (or (car-safe new-prefix) new-prefix))
951 (company-calculate-candidates new-prefix))))
954 ;; t means complete/unique.
955 (company-cancel new-prefix)
959 (setq company-prefix new-prefix)
960 (company-update-candidates c)
962 (t (company--continue-failed new-prefix)))
965 (defun company--begin-new ()
967 (dolist (backend (if company-backend
968 ;; prefer manual override
969 (list company-backend)
972 (if (or (symbolp backend)
974 (when (or (not (symbolp backend))
975 (eq t (get backend 'company-init))
976 (unless (get backend 'company-init)
977 (company-init-backend backend)))
978 (funcall backend 'prefix))
979 (company--multi-backend-adapter backend 'prefix)))
981 (when (company--good-prefix-p prefix)
982 (setq prefix (or (car-safe prefix) prefix)
983 company-backend backend
984 c (company-calculate-candidates prefix))
985 ;; t means complete/unique. We don't start, so no hooks.
987 (when company--explicit-action
988 (message "No completion found"))
989 (setq company-prefix prefix)
990 (when (symbolp backend)
991 (setq company-lighter (concat " " (symbol-name backend))))
992 (company-update-candidates c)
993 (run-hook-with-args 'company-completion-started-hook
994 (company-explicit-action-p))
995 (company-call-frontends 'show)))
998 (defun company-begin ()
999 (or (and company-candidates (company--continue))
1000 (and (company--should-complete) (company--begin-new)))
1001 (when company-candidates
1002 (when (and company-end-of-buffer-workaround (eobp))
1003 (save-excursion (insert "\n"))
1004 (setq company-added-newline (buffer-chars-modified-tick)))
1005 (setq company-point (point)
1006 company--point-max (point-max))
1007 (company-ensure-emulation-alist)
1008 (company-enable-overriding-keymap company-active-map)
1009 (company-call-frontends 'update)))
1011 (defun company-cancel (&optional result)
1012 (and company-added-newline
1013 (> (point-max) (point-min))
1014 (let ((tick (buffer-chars-modified-tick)))
1015 (delete-region (1- (point-max)) (point-max))
1016 (equal tick company-added-newline))
1017 ;; Only set unmodified when tick remained the same since insert.
1018 (set-buffer-modified-p nil))
1019 (when company-prefix
1020 (if (stringp result)
1022 (company-call-backend 'pre-completion result)
1023 (run-hook-with-args 'company-completion-finished-hook result)
1024 (company-call-backend 'post-completion result))
1025 (run-hook-with-args 'company-completion-cancelled-hook result)))
1026 (setq company-added-newline nil
1029 company-candidates nil
1030 company-candidates-length nil
1031 company-candidates-cache nil
1032 company-candidates-predicate nil
1035 company-selection-changed nil
1036 company--explicit-action nil
1037 company-lighter company-default-lighter
1038 company--point-max nil
1041 (cancel-timer company-timer))
1042 (company-search-mode 0)
1043 (company-call-frontends 'hide)
1044 (company-enable-overriding-keymap nil))
1046 (defun company-abort ()
1049 ;; Don't start again, unless started manually.
1050 (setq company-point (point)))
1052 (defun company-finish (result)
1053 (insert (company-strip-prefix result))
1054 (company-cancel result)
1055 ;; Don't start again, unless started manually.
1056 (setq company-point (point)))
1058 (defsubst company-keep (command)
1059 (and (symbolp command) (get command 'company-keep)))
1061 (defun company-pre-command ()
1062 (unless (company-keep this-command)
1064 (when company-candidates
1065 (company-call-frontends 'pre-command))
1066 (error (message "Company: An error occurred in pre-command")
1067 (message "%s" (error-message-string err))
1070 (cancel-timer company-timer)
1071 (setq company-timer nil))
1072 (company-uninstall-map))
1074 (defun company-post-command ()
1075 (unless (company-keep this-command)
1078 (unless (equal (point) company-point)
1080 (if company-candidates
1081 (company-call-frontends 'post-command)
1082 (and (numberp company-idle-delay)
1083 (or (eq t company-begin-commands)
1084 (memq this-command company-begin-commands))
1086 (run-with-timer company-idle-delay nil
1088 (current-buffer) (selected-window)
1089 (buffer-chars-modified-tick) (point))))))
1090 (error (message "Company: An error occurred in post-command")
1091 (message "%s" (error-message-string err))
1093 (company-install-map))
1095 ;;; search ;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;
1097 (defvar company-search-string nil)
1098 (make-variable-buffer-local 'company-search-string)
1100 (defvar company-search-lighter " Search: \"\"")
1101 (make-variable-buffer-local 'company-search-lighter)
1103 (defvar company-search-old-map nil)
1104 (make-variable-buffer-local 'company-search-old-map)
1106 (defvar company-search-old-selection 0)
1107 (make-variable-buffer-local 'company-search-old-selection)
1109 (defun company-search (text lines)
1110 (let ((quoted (regexp-quote text))
1112 (dolist (line lines)
1113 (when (string-match quoted line (length company-prefix))
1117 (defun company-search-printing-char ()
1119 (company-search-assert-enabled)
1120 (setq company-search-string
1121 (concat (or company-search-string "") (string last-command-event))
1122 company-search-lighter (concat " Search: \"" company-search-string
1124 (let ((pos (company-search company-search-string
1125 (nthcdr company-selection company-candidates))))
1128 (company-set-selection (+ company-selection pos) t))))
1130 (defun company-search-repeat-forward ()
1131 "Repeat the incremental search in completion candidates forward."
1133 (company-search-assert-enabled)
1134 (let ((pos (company-search company-search-string
1135 (cdr (nthcdr company-selection
1136 company-candidates)))))
1139 (company-set-selection (+ company-selection pos 1) t))))
1141 (defun company-search-repeat-backward ()
1142 "Repeat the incremental search in completion candidates backwards."
1144 (company-search-assert-enabled)
1145 (let ((pos (company-search company-search-string
1146 (nthcdr (- company-candidates-length
1148 (reverse company-candidates)))))
1151 (company-set-selection (- company-selection pos 1) t))))
1153 (defun company-create-match-predicate ()
1154 (setq company-candidates-predicate
1155 `(lambda (candidate)
1156 ,(if company-candidates-predicate
1157 `(and (string-match ,company-search-string candidate)
1158 (funcall ,company-candidates-predicate
1160 `(string-match ,company-search-string candidate))))
1161 (company-update-candidates
1162 (company-apply-predicate company-candidates company-candidates-predicate))
1163 ;; Invalidate cache.
1164 (setq company-candidates-cache (cons company-prefix company-candidates)))
1166 (defun company-filter-printing-char ()
1168 (company-search-assert-enabled)
1169 (company-search-printing-char)
1170 (company-create-match-predicate)
1171 (company-call-frontends 'update))
1173 (defun company-search-kill-others ()
1174 "Limit the completion candidates to the ones matching the search string."
1176 (company-search-assert-enabled)
1177 (company-create-match-predicate)
1178 (company-search-mode 0)
1179 (company-call-frontends 'update))
1181 (defun company-search-abort ()
1182 "Abort searching the completion candidates."
1184 (company-search-assert-enabled)
1185 (company-set-selection company-search-old-selection t)
1186 (company-search-mode 0))
1188 (defun company-search-other-char ()
1190 (company-search-assert-enabled)
1191 (company-search-mode 0)
1192 (company--unread-last-input))
1194 (defvar company-search-map
1196 (keymap (make-keymap)))
1197 (if (fboundp 'max-char)
1198 (set-char-table-range (nth 1 keymap) (cons #x100 (max-char))
1199 'company-search-printing-char)
1201 ;; obsolete in Emacs 23
1202 (let ((l (generic-character-list))
1203 (table (nth 1 keymap)))
1205 (set-char-table-default table (car l) 'company-search-printing-char)
1206 (setq l (cdr l))))))
1207 (define-key keymap [t] 'company-search-other-char)
1209 (define-key keymap (make-string 1 i) 'company-search-other-char)
1212 (define-key keymap (vector i) 'company-search-printing-char)
1214 (let ((meta-map (make-sparse-keymap)))
1215 (define-key keymap (char-to-string meta-prefix-char) meta-map)
1216 (define-key keymap [escape] meta-map))
1217 (define-key keymap (vector meta-prefix-char t) 'company-search-other-char)
1218 (define-key keymap "\e\e\e" 'company-search-other-char)
1219 (define-key keymap [escape escape escape] 'company-search-other-char)
1221 (define-key keymap "\C-g" 'company-search-abort)
1222 (define-key keymap "\C-s" 'company-search-repeat-forward)
1223 (define-key keymap "\C-r" 'company-search-repeat-backward)
1224 (define-key keymap "\C-o" 'company-search-kill-others)
1226 "Keymap used for incrementally searching the completion candidates.")
1228 (define-minor-mode company-search-mode
1229 "Search mode for completion candidates.
1230 Don't start this directly, use `company-search-candidates' or
1231 `company-filter-candidates'."
1232 nil company-search-lighter nil
1233 (if company-search-mode
1234 (if (company-manual-begin)
1236 (setq company-search-old-selection company-selection)
1237 (company-call-frontends 'update))
1238 (setq company-search-mode nil))
1239 (kill-local-variable 'company-search-string)
1240 (kill-local-variable 'company-search-lighter)
1241 (kill-local-variable 'company-search-old-selection)
1242 (company-enable-overriding-keymap company-active-map)))
1244 (defun company-search-assert-enabled ()
1245 (company-assert-enabled)
1246 (unless company-search-mode
1247 (company-uninstall-map)
1248 (error "Company not in search mode")))
1250 (defun company-search-candidates ()
1251 "Start searching the completion candidates incrementally.
1253 \\<company-search-map>Search can be controlled with the commands:
1254 - `company-search-repeat-forward' (\\[company-search-repeat-forward])
1255 - `company-search-repeat-backward' (\\[company-search-repeat-backward])
1256 - `company-search-abort' (\\[company-search-abort])
1258 Regular characters are appended to the search string.
1260 The command `company-search-kill-others' (\\[company-search-kill-others]) uses
1261 the search string to limit the completion candidates."
1263 (company-search-mode 1)
1264 (company-enable-overriding-keymap company-search-map))
1266 (defvar company-filter-map
1267 (let ((keymap (make-keymap)))
1268 (define-key keymap [remap company-search-printing-char]
1269 'company-filter-printing-char)
1270 (set-keymap-parent keymap company-search-map)
1272 "Keymap used for incrementally searching the completion candidates.")
1274 (defun company-filter-candidates ()
1275 "Start filtering the completion candidates incrementally.
1276 This works the same way as `company-search-candidates' immediately
1277 followed by `company-search-kill-others' after each input."
1279 (company-search-mode 1)
1280 (company-enable-overriding-keymap company-filter-map))
1282 ;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;
1284 (defun company-select-next ()
1285 "Select the next candidate in the list."
1287 (when (company-manual-begin)
1288 (company-set-selection (1+ company-selection))))
1290 (defun company-select-previous ()
1291 "Select the previous candidate in the list."
1293 (when (company-manual-begin)
1294 (company-set-selection (1- company-selection))))
1296 (defun company-select-next-or-abort ()
1297 "Select the next candidate if more than one, else abort
1298 and invoke the normal binding."
1300 (if (> company-candidates-length 1)
1301 (company-select-next)
1303 (company--unread-last-input)))
1305 (defun company-select-previous-or-abort ()
1306 "Select the previous candidate if more than one, else abort
1307 and invoke the normal binding."
1309 (if (> company-candidates-length 1)
1310 (company-select-previous)
1312 (company--unread-last-input)))
1314 (defvar company-pseudo-tooltip-overlay)
1316 (defvar company-tooltip-offset)
1318 (defun company--inside-tooltip-p (event-col-row row height)
1319 (let* ((ovl company-pseudo-tooltip-overlay)
1320 (column (overlay-get ovl 'company-column))
1321 (width (overlay-get ovl 'company-width))
1322 (evt-col (car event-col-row))
1323 (evt-row (cdr event-col-row)))
1324 (and (>= evt-col column)
1325 (< evt-col (+ column width))
1327 (and (> evt-row row)
1328 (<= evt-row (+ row height) ))
1329 (and (< evt-row row)
1330 (>= evt-row (+ row height)))))))
1332 (defun company--event-col-row (event)
1333 (let* ((col-row (posn-actual-col-row (event-start event)))
1335 (row (cdr col-row)))
1336 (incf col (window-hscroll))
1337 (and header-line-format
1338 (version< "24" emacs-version)
1342 (defun company-select-mouse (event)
1343 "Select the candidate picked by the mouse."
1345 (let ((event-col-row (company--event-col-row event))
1346 (ovl-row (company--row))
1347 (ovl-height (and company-pseudo-tooltip-overlay
1348 (min (overlay-get company-pseudo-tooltip-overlay
1350 company-candidates-length))))
1352 (company--inside-tooltip-p event-col-row ovl-row ovl-height))
1354 (company-set-selection (+ (cdr event-col-row)
1355 (if (zerop company-tooltip-offset)
1357 (- company-tooltip-offset 2))
1359 (if (< ovl-height 0)
1364 (company--unread-last-input)
1367 (defun company-complete-mouse (event)
1368 "Complete the candidate picked by the mouse."
1370 (when (company-select-mouse event)
1371 (company-complete-selection)))
1373 (defun company-complete-selection ()
1374 "Complete the selected candidate."
1376 (when (company-manual-begin)
1377 (let ((result (nth company-selection company-candidates)))
1378 (when company--auto-completion
1379 (setq result (company--safe-candidate result)))
1380 (company-finish result))))
1382 (defun company-complete-common ()
1383 "Complete the common part of all candidates."
1385 (when (company-manual-begin)
1386 (if (and (not (cdr company-candidates))
1387 (equal company-common (car company-candidates)))
1388 (company-complete-selection)
1389 (insert (company-strip-prefix company-common)))))
1391 (defun company-complete ()
1392 "Complete the common part of all candidates or the current selection.
1393 The first time this is called, the common part is completed, the second time, or
1394 when the selection has been changed, the selected candidate is completed."
1396 (when (company-manual-begin)
1397 (if (or company-selection-changed
1398 (eq last-command 'company-complete-common))
1399 (call-interactively 'company-complete-selection)
1400 (call-interactively 'company-complete-common)
1401 (setq this-command 'company-complete-common))))
1403 (defun company-complete-number (n)
1404 "Complete the Nth candidate.
1405 To show the number next to the candidates in some back-ends, enable
1406 `company-show-numbers'."
1407 (when (company-manual-begin)
1408 (and (< n 1) (> n company-candidates-length)
1409 (error "No candidate number %d" n))
1411 (company-finish (nth n company-candidates))))
1413 ;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;
1415 (defconst company-space-strings-limit 100)
1417 (defconst company-space-strings
1419 (dotimes (i company-space-strings-limit)
1420 (push (make-string (- company-space-strings-limit 1 i) ?\ ) lst))
1421 (apply 'vector lst)))
1423 (defsubst company-space-string (len)
1424 (if (< len company-space-strings-limit)
1425 (aref company-space-strings len)
1426 (make-string len ?\ )))
1428 (defsubst company-safe-substring (str from &optional to)
1429 (if (> from (string-width str))
1433 (move-to-column from)
1434 (let ((beg (point)))
1438 (concat (buffer-substring beg (point))
1439 (let ((padding (- to (current-column))))
1441 (company-space-string padding)))))
1442 (buffer-substring beg (point-max)))))))
1444 ;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;
1446 (defvar company-last-metadata nil)
1447 (make-variable-buffer-local 'company-last-metadata)
1449 (defun company-fetch-metadata ()
1450 (let ((selected (nth company-selection company-candidates)))
1451 (unless (equal selected (car company-last-metadata))
1452 (setq company-last-metadata
1453 (cons selected (company-call-backend 'meta selected))))
1454 (cdr company-last-metadata)))
1456 (defun company-doc-buffer (&optional _string)
1457 (with-current-buffer (get-buffer-create "*Company meta-data*")
1461 (defvar company--electric-commands
1462 '(scroll-other-window scroll-other-window-down)
1463 "List of Commands that won't break out of electric commands.")
1465 (defmacro company--electric-do (&rest body)
1466 (declare (indent 0) (debug t))
1467 `(when (company-manual-begin)
1468 (save-window-excursion
1469 (let ((height (window-height))
1470 (row (company--row))
1473 (and (< (window-height) height)
1474 (< (- (window-height) row 2) company-tooltip-limit)
1475 (recenter (- (window-height) row 2)))
1476 (while (memq (setq cmd (key-binding (vector (list (read-event)))))
1477 company--electric-commands)
1478 (call-interactively cmd))
1479 (company--unread-last-input)))))
1481 (defun company--unread-last-input ()
1482 (when last-input-event
1483 (clear-this-command-keys t)
1484 (setq unread-command-events (list last-input-event))))
1486 (defun company-show-doc-buffer ()
1487 "Temporarily show a buffer with the complete documentation for the selection."
1489 (company--electric-do
1490 (let* ((selected (nth company-selection company-candidates))
1491 (doc-buffer (or (company-call-backend 'doc-buffer selected)
1492 (error "No documentation available"))))
1493 (with-current-buffer doc-buffer
1494 (goto-char (point-min)))
1495 (display-buffer doc-buffer t))))
1496 (put 'company-show-doc-buffer 'company-keep t)
1498 (defun company-show-location ()
1499 "Temporarily display a buffer showing the selected candidate in context."
1501 (company--electric-do
1502 (let* ((selected (nth company-selection company-candidates))
1503 (location (company-call-backend 'location selected))
1504 (pos (or (cdr location) (error "No location available")))
1505 (buffer (or (and (bufferp (car location)) (car location))
1506 (find-file-noselect (car location) t))))
1507 (with-selected-window (display-buffer buffer t)
1510 (if (bufferp (car location))
1512 (goto-char (point-min))
1513 (forward-line (1- pos))))
1514 (set-window-start nil (point))))))
1515 (put 'company-show-location 'company-keep t)
1517 ;;; package functions ;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;
1519 (defvar company-callback nil)
1520 (make-variable-buffer-local 'company-callback)
1522 (defvar company-begin-with-marker nil)
1523 (make-variable-buffer-local 'company-begin-with-marker)
1525 (defun company-remove-callback (&optional ignored)
1526 (remove-hook 'company-completion-finished-hook company-callback t)
1527 (remove-hook 'company-completion-cancelled-hook 'company-remove-callback t)
1528 (remove-hook 'company-completion-finished-hook 'company-remove-callback t)
1529 (when company-begin-with-marker
1530 (set-marker company-begin-with-marker nil)))
1532 (defun company-begin-backend (backend &optional callback)
1533 "Start a completion at point using BACKEND."
1534 (interactive (let ((val (completing-read "Company back-end: "
1536 'functionp nil "company-")))
1538 (list (intern val)))))
1539 (when (setq company-callback callback)
1540 (add-hook 'company-completion-finished-hook company-callback nil t))
1541 (add-hook 'company-completion-cancelled-hook 'company-remove-callback nil t)
1542 (add-hook 'company-completion-finished-hook 'company-remove-callback nil t)
1543 (setq company-backend backend)
1544 ;; Return non-nil if active.
1545 (or (company-manual-begin)
1547 (setq company-backend nil)
1548 (error "Cannot complete at point"))))
1550 (defun company-begin-with (candidates
1551 &optional prefix-length require-match callback)
1552 "Start a completion at point.
1553 CANDIDATES is the list of candidates to use and PREFIX-LENGTH is the length of
1554 the prefix that already is in the buffer before point. It defaults to 0.
1556 CALLBACK is a function called with the selected result if the user successfully
1557 completes the input.
1560 \(company-begin-with '\(\"foo\" \"foobar\" \"foobarbaz\"\)\)"
1561 ;; FIXME: When Emacs 23 is no longer a concern, replace
1562 ;; `company-begin-with-marker' with a lexical variable; use a lexical closure.
1563 (setq company-begin-with-marker (copy-marker (point) t))
1564 (company-begin-backend
1565 `(lambda (command &optional arg &rest ignored)
1567 ((eq command 'prefix)
1568 (when (equal (point) (marker-position company-begin-with-marker))
1569 (buffer-substring ,(- (point) (or prefix-length 0)) (point))))
1570 ((eq command 'candidates)
1571 (all-completions arg ',candidates))
1572 ((eq command 'require-match)
1576 ;;; pseudo-tooltip ;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;
1578 (defvar company-pseudo-tooltip-overlay nil)
1579 (make-variable-buffer-local 'company-pseudo-tooltip-overlay)
1581 (defvar company-tooltip-offset 0)
1582 (make-variable-buffer-local 'company-tooltip-offset)
1584 (defun company-pseudo-tooltip-update-offset (selection num-lines limit)
1587 (setq company-tooltip-offset
1588 (max (min selection company-tooltip-offset)
1589 (- selection -1 limit)))
1591 (when (<= company-tooltip-offset 1)
1593 (setq company-tooltip-offset 0))
1595 (when (>= company-tooltip-offset (- num-lines limit 1))
1597 (when (= selection (1- num-lines))
1598 (decf company-tooltip-offset)
1599 (when (<= company-tooltip-offset 1)
1600 (setq company-tooltip-offset 0)
1607 (defsubst company-round-tab (arg)
1608 (* (/ (+ arg tab-width) tab-width) tab-width))
1610 (defun company-untabify (str)
1611 (let* ((pieces (split-string str "\t"))
1614 (setcar copy (company-safe-substring
1615 (car copy) 0 (company-round-tab (string-width (car copy)))))
1617 (apply 'concat pieces)))
1619 (defun company-fill-propertize (line width selected)
1620 (setq line (company-safe-substring line 0 width))
1621 (add-text-properties 0 width '(face company-tooltip
1622 mouse-face company-tooltip-mouse)
1624 (add-text-properties 0 (length company-common)
1625 '(face company-tooltip-common
1626 mouse-face company-tooltip-mouse)
1629 (if (and company-search-string
1630 (string-match (regexp-quote company-search-string) line
1631 (length company-prefix)))
1633 (add-text-properties (match-beginning 0) (match-end 0)
1634 '(face company-tooltip-selection)
1636 (when (< (match-beginning 0) (length company-common))
1637 (add-text-properties (match-beginning 0) (length company-common)
1638 '(face company-tooltip-common-selection)
1640 (add-text-properties 0 width '(face company-tooltip-selection
1641 mouse-face company-tooltip-selection)
1643 (add-text-properties 0 (length company-common)
1644 '(face company-tooltip-common-selection
1645 mouse-face company-tooltip-selection)
1651 (defun company-buffer-lines (beg end)
1654 (while (< (point) end)
1655 (let ((bol (point)))
1656 ;; A visual line can contain several physical lines (e.g. with outline's
1657 ;; folding overlay). Take only the first one.
1658 (re-search-forward "$")
1659 (push (buffer-substring bol (min end (point))) lines))
1660 (vertical-motion 1))
1663 (defsubst company-modify-line (old new offset)
1664 (concat (company-safe-substring old 0 offset)
1666 (company-safe-substring old (+ offset (length new)))))
1668 (defsubst company--length-limit (lst limit)
1669 (if (nthcdr limit lst)
1673 (defun company--replacement-string (lines old column nl &optional align-top)
1675 (let ((width (length (car lines)))
1676 (remaining-cols (- (+ (window-width) (window-hscroll))
1678 (when (> width remaining-cols)
1679 (decf column (- width remaining-cols))))
1683 ;; untouched lines first
1684 (dotimes (_ (- (length old) (length lines)))
1685 (push (pop old) new)))
1686 ;; length into old lines.
1688 (push (company-modify-line (pop old) (pop lines) column) new))
1689 ;; Append whole new lines.
1691 (push (concat (company-space-string column) (pop lines)) new))
1693 (let ((str (concat (when nl "\n")
1694 (mapconcat 'identity (nreverse new) "\n")
1696 (font-lock-append-text-property 0 (length str) 'face 'default str)
1699 (defun company--create-lines (selection limit)
1701 (let ((len company-candidates-length)
1710 ;; Scroll to offset.
1711 (setq limit (company-pseudo-tooltip-update-offset selection len limit))
1713 (when (> company-tooltip-offset 0)
1714 (setq previous (format "...(%d)" company-tooltip-offset)))
1716 (setq remainder (- len limit company-tooltip-offset)
1717 remainder (when (> remainder 0)
1718 (setq remainder (format "...(%d)" remainder))))
1720 (decf selection company-tooltip-offset)
1721 (setq width (max (length previous) (length remainder))
1722 lines (nthcdr company-tooltip-offset company-candidates)
1727 (setq width (max (length (pop lines-copy)) width)))
1728 (setq width (min width (window-width)))
1730 (setq lines-copy lines)
1732 ;; number can make tooltip too long
1733 (when company-show-numbers
1734 (setq numbered company-tooltip-offset))
1737 (push (propertize (company-safe-substring previous 0 width)
1738 'face 'company-tooltip)
1742 (push (company-fill-propertize
1743 (if (>= numbered 10)
1744 (company-reformat (pop lines))
1747 (company-safe-substring (company-reformat (pop lines))
1750 width (equal i selection))
1754 (push (propertize (company-safe-substring remainder 0 width)
1755 'face 'company-tooltip)
1758 (setq lines (nreverse new))))
1762 (defsubst company--window-inner-height ()
1763 (let ((edges (window-inside-edges)))
1764 (- (nth 3 edges) (nth 1 edges))))
1766 (defsubst company--pseudo-tooltip-height ()
1767 "Calculate the appropriate tooltip height.
1768 Returns a negative number if the tooltip should be displayed above point."
1769 (let* ((lines (company--row))
1770 (below (- (company--window-inner-height) 1 lines)))
1771 (if (and (< below (min company-tooltip-minimum company-candidates-length))
1773 (- (max 3 (min company-tooltip-limit lines)))
1774 (max 3 (min company-tooltip-limit below)))))
1776 (defun company-pseudo-tooltip-show (row column selection)
1777 (company-pseudo-tooltip-hide)
1780 (let* ((height (company--pseudo-tooltip-height))
1784 (setq row (+ row height -1)
1787 (let* ((nl (< (move-to-window-line row) row))
1789 (end (save-excursion
1790 (move-to-window-line (+ row (abs height)))
1792 (ov (make-overlay beg end))
1793 (args (list (mapcar 'company-untabify
1794 (company-buffer-lines beg end))
1797 (setq company-pseudo-tooltip-overlay ov)
1798 (overlay-put ov 'company-replacement-args args)
1800 (let ((lines (company--create-lines selection (abs height))))
1801 (overlay-put ov 'company-before
1802 (apply 'company--replacement-string lines args))
1803 (overlay-put ov 'company-width (string-width (car lines))))
1805 (overlay-put ov 'company-column column)
1806 (overlay-put ov 'company-height height)))))
1808 (defun company-pseudo-tooltip-show-at-point (pos)
1809 (let ((row (company--row pos))
1810 (col (company--column pos)))
1811 (company-pseudo-tooltip-show (1+ row) col company-selection)))
1813 (defun company-pseudo-tooltip-edit (selection)
1814 (let ((height (overlay-get company-pseudo-tooltip-overlay 'company-height)))
1815 (overlay-put company-pseudo-tooltip-overlay 'company-before
1816 (apply 'company--replacement-string
1817 (company--create-lines selection (abs height))
1818 (overlay-get company-pseudo-tooltip-overlay
1819 'company-replacement-args)))))
1821 (defun company-pseudo-tooltip-hide ()
1822 (when company-pseudo-tooltip-overlay
1823 (delete-overlay company-pseudo-tooltip-overlay)
1824 (setq company-pseudo-tooltip-overlay nil)))
1826 (defun company-pseudo-tooltip-hide-temporarily ()
1827 (when (overlayp company-pseudo-tooltip-overlay)
1828 (overlay-put company-pseudo-tooltip-overlay 'invisible nil)
1829 (overlay-put company-pseudo-tooltip-overlay 'before-string nil)))
1831 (defun company-pseudo-tooltip-unhide ()
1832 (when company-pseudo-tooltip-overlay
1833 (overlay-put company-pseudo-tooltip-overlay 'invisible t)
1834 ;; Beat outline's folding overlays, at least.
1835 (overlay-put company-pseudo-tooltip-overlay 'priority 1)
1836 (overlay-put company-pseudo-tooltip-overlay 'before-string
1837 (overlay-get company-pseudo-tooltip-overlay 'company-before))
1838 (overlay-put company-pseudo-tooltip-overlay 'window (selected-window))))
1840 (defun company-pseudo-tooltip-guard ()
1841 (buffer-substring-no-properties
1842 (point) (overlay-start company-pseudo-tooltip-overlay)))
1844 (defun company-pseudo-tooltip-frontend (command)
1845 "`company-mode' front-end similar to a tooltip but based on overlays."
1847 (pre-command (company-pseudo-tooltip-hide-temporarily))
1849 (let ((old-height (if (overlayp company-pseudo-tooltip-overlay)
1850 (overlay-get company-pseudo-tooltip-overlay
1853 (new-height (company--pseudo-tooltip-height)))
1854 (unless (and (>= (* old-height new-height) 0)
1855 (>= (abs old-height) (abs new-height))
1856 (equal (company-pseudo-tooltip-guard)
1857 (overlay-get company-pseudo-tooltip-overlay
1860 (company-pseudo-tooltip-show-at-point (- (point)
1861 (length company-prefix)))
1862 (overlay-put company-pseudo-tooltip-overlay
1863 'company-guard (company-pseudo-tooltip-guard))))
1864 (company-pseudo-tooltip-unhide))
1865 (hide (company-pseudo-tooltip-hide)
1866 (setq company-tooltip-offset 0))
1867 (update (when (overlayp company-pseudo-tooltip-overlay)
1868 (company-pseudo-tooltip-edit company-selection)))))
1870 (defun company-pseudo-tooltip-unless-just-one-frontend (command)
1871 "`company-pseudo-tooltip-frontend', but not shown for single candidates."
1872 (unless (and (eq command 'post-command)
1873 (not (cdr company-candidates)))
1874 (company-pseudo-tooltip-frontend command)))
1876 ;;; overlay ;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;
1878 (defvar company-preview-overlay nil)
1879 (make-variable-buffer-local 'company-preview-overlay)
1881 (defun company-preview-show-at-point (pos)
1882 (company-preview-hide)
1884 (setq company-preview-overlay (make-overlay pos pos))
1886 (let ((completion(nth company-selection company-candidates)))
1887 (setq completion (propertize completion 'face 'company-preview))
1888 (add-text-properties 0 (length company-common)
1889 '(face company-preview-common) completion)
1891 ;; Add search string
1892 (and company-search-string
1893 (string-match (regexp-quote company-search-string) completion)
1894 (add-text-properties (match-beginning 0)
1896 '(face company-preview-search)
1899 (setq completion (company-strip-prefix completion))
1901 (and (equal pos (point))
1902 (not (equal completion ""))
1903 (add-text-properties 0 1 '(cursor t) completion))
1905 (overlay-put company-preview-overlay 'after-string completion)
1906 (overlay-put company-preview-overlay 'window (selected-window))))
1908 (defun company-preview-hide ()
1909 (when company-preview-overlay
1910 (delete-overlay company-preview-overlay)
1911 (setq company-preview-overlay nil)))
1913 (defun company-preview-frontend (command)
1914 "`company-mode' front-end showing the selection as if it had been inserted."
1916 (pre-command (company-preview-hide))
1917 (post-command (company-preview-show-at-point (point)))
1918 (hide (company-preview-hide))))
1920 (defun company-preview-if-just-one-frontend (command)
1921 "`company-preview-frontend', but only shown for single candidates."
1922 (unless (and (eq command 'post-command)
1923 (cdr company-candidates))
1924 (company-preview-frontend command)))
1926 ;;; echo ;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;
1928 (defvar company-echo-last-msg nil)
1929 (make-variable-buffer-local 'company-echo-last-msg)
1931 (defvar company-echo-timer nil)
1933 (defvar company-echo-delay .01)
1935 (defun company-echo-show (&optional getter)
1937 (setq company-echo-last-msg (funcall getter)))
1938 (let ((message-log-max nil))
1939 (if company-echo-last-msg
1940 (message "%s" company-echo-last-msg)
1943 (defsubst company-echo-show-soon (&optional getter)
1944 (when company-echo-timer
1945 (cancel-timer company-echo-timer))
1946 (setq company-echo-timer (run-with-timer 0 nil 'company-echo-show getter)))
1948 (defsubst company-echo-show-when-idle (&optional getter)
1950 (company-echo-show getter)))
1952 (defsubst company-echo-show-when-not-busy (&optional getter)
1953 "Run `company-echo-show' with arg GETTER once Emacs isn't busy."
1954 (when (sit-for company-echo-delay)
1955 (company-echo-show getter)))
1957 (defun company-echo-format ()
1959 (let ((limit (window-width (minibuffer-window)))
1961 ;; Roll to selection.
1962 (candidates (nthcdr company-selection company-candidates))
1963 (i (if company-show-numbers company-selection 99999))
1967 (setq comp (company-reformat (pop candidates))
1968 len (+ len 1 (length comp)))
1972 (setq comp (propertize (format "%d: %s" i comp)
1973 'face 'company-echo))
1976 (add-text-properties 3 (+ 3 (length company-common))
1977 '(face company-echo-common) comp))
1978 (setq comp (propertize comp 'face 'company-echo))
1979 (add-text-properties 0 (length company-common)
1980 '(face company-echo-common) comp))
1982 (setq candidates nil)
1985 (mapconcat 'identity (nreverse msg) " ")))
1987 (defun company-echo-strip-common-format ()
1989 (let ((limit (window-width (minibuffer-window)))
1990 (len (+ (length company-prefix) 2))
1991 ;; Roll to selection.
1992 (candidates (nthcdr company-selection company-candidates))
1993 (i (if company-show-numbers company-selection 99999))
1997 (setq comp (company-strip-prefix (pop candidates))
1998 len (+ len 2 (length comp)))
2001 (setq comp (format "%s (%d)" comp i))
2005 (setq candidates nil)
2006 (push (propertize comp 'face 'company-echo) msg)))
2008 (concat (propertize company-prefix 'face 'company-echo-common) "{"
2009 (mapconcat 'identity (nreverse msg) ", ")
2012 (defun company-echo-hide ()
2013 (unless (equal company-echo-last-msg "")
2014 (setq company-echo-last-msg "")
2015 (company-echo-show)))
2017 (defun company-echo-frontend (command)
2018 "`company-mode' front-end showing the candidates in the echo area."
2020 (post-command (company-echo-show-soon 'company-echo-format))
2021 (hide (company-echo-hide))))
2023 (defun company-echo-strip-common-frontend (command)
2024 "`company-mode' front-end showing the candidates in the echo area."
2026 (post-command (company-echo-show-soon 'company-echo-strip-common-format))
2027 (hide (company-echo-hide))))
2029 (defun company-echo-metadata-frontend (command)
2030 "`company-mode' front-end showing the documentation in the echo area."
2032 (post-command (company-echo-show-when-idle 'company-fetch-metadata))
2033 (hide (company-echo-hide))))
2036 ;;; company.el ends here