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-cmake . "CMake")
219 (company-css . "CSS")
220 (company-dabbrev . "dabbrev for plain text")
221 (company-dabbrev-code . "dabbrev for code")
222 (company-eclim . "Eclim (an Eclipse interface)")
223 (company-elisp . "Emacs Lisp")
224 (company-etags . "etags")
225 (company-files . "Files")
226 (company-gtags . "GNU Global")
227 (company-ispell . "Ispell")
228 (company-keywords . "Programming language keywords")
229 (company-nxml . "nxml")
230 (company-oddmuse . "Oddmuse")
231 (company-pysmell . "PySmell")
232 (company-ropemacs . "ropemacs")
233 (company-semantic . "Semantic")
234 (company-tempo . "Tempo templates")
235 (company-xcode . "Xcode")))
236 (put 'company-safe-backends 'risky-local-variable t)
238 (defun company-safe-backends-p (backends)
239 (and (consp backends)
240 (not (dolist (backend backends)
241 (unless (if (consp backend)
242 (company-safe-backends-p backend)
243 (assq backend company-safe-backends))
246 (defvar company--include-capf (version< "24.3.50" emacs-version))
248 (defcustom company-backends `(,@(unless company--include-capf
249 (list 'company-elisp))
250 company-nxml company-css
251 company-eclim company-semantic company-clang
252 company-xcode company-ropemacs company-cmake
253 ,@(when company--include-capf
254 (list 'company-capf))
255 (company-gtags company-etags company-dabbrev-code
257 company-oddmuse company-files company-dabbrev)
258 "The list of active back-ends (completion engines).
259 Each list elements can itself be a list of back-ends. In that case their
260 completions are merged. Otherwise only the first matching back-end returns
263 `company-begin-backend' can be used to start a specific back-end,
264 `company-other-backend' will skip to the next matching back-end in the list.
266 Each back-end is a function that takes a variable number of arguments.
267 The first argument is the command requested from the back-end. It is one
270 `prefix': The back-end should return the text to be completed. It must be
271 text immediately before point. Returning nil passes control to the next
272 back-end. The function should return `stop' if it should complete but
273 cannot \(e.g. if it is in the middle of a string\). Instead of a string,
274 the back-end may return a cons where car is the prefix and cdr is used in
275 `company-minimum-prefix-length' test. It's either number or t, in which
276 case the test automatically succeeds.
278 `candidates': The second argument is the prefix to be completed. The
279 return value should be a list of candidates that start with the prefix.
283 `sorted': Return t here to indicate that the candidates are sorted and will
284 not need to be sorted again.
286 `duplicates': If non-nil, company will take care of removing duplicates
289 `no-cache': Usually company doesn't ask for candidates again as completion
290 progresses, unless the back-end returns t for this command. The second
291 argument is the latest prefix.
293 `meta': The second argument is a completion candidate. Return a (short)
294 documentation string for it.
296 `doc-buffer': The second argument is a completion candidate. Return a
297 buffer with documentation for it. Preferably use `company-doc-buffer',
299 `location': The second argument is a completion candidate. Return the cons
300 of buffer and buffer location, or of file and line number where the
301 completion candidate was defined.
303 `require-match': If this returns t, the user is not allowed to enter
304 anything not offered as a candidate. Use with care! The default value nil
305 gives the user that choice with `company-require-match'. Return value
306 `never' overrides that option the other way around.
308 `init': Called once for each buffer. The back-end can check for external
309 programs and files and load any required libraries. Raising an error here
310 will show up in message log once, and the back-end will not be used for
313 `post-completion': Called after a completion candidate has been inserted
314 into the buffer. The second argument is the candidate. Can be used to
315 modify it, e.g. to expand a snippet.
317 The back-end should return nil for all commands it does not support or
318 does not know about. It should also be callable interactively and use
319 `company-begin-backend' to start itself in that case."
323 ,@(mapcar (lambda (b) `(const :tag ,(cdr b) ,(car b)))
324 company-safe-backends)
325 (symbol :tag "User defined")
326 (repeat :tag "Merged Back-ends"
327 (choice :tag "Back-end"
328 ,@(mapcar (lambda (b)
329 `(const :tag ,(cdr b) ,(car b)))
330 company-safe-backends)
331 (symbol :tag "User defined"))))))
333 (put 'company-backends 'safe-local-variable 'company-safe-backends-p)
335 (defcustom company-completion-started-hook nil
336 "Hook run when company starts completing.
337 The hook is called with one argument that is non-nil if the completion was
341 (defcustom company-completion-cancelled-hook nil
342 "Hook run when company cancels completing.
343 The hook is called with one argument that is non-nil if the completion was
347 (defcustom company-completion-finished-hook nil
348 "Hook run when company successfully completes.
349 The hook is called with the selected candidate as an argument.
351 If you indend to use it to post-process candidates from a specific
352 back-end, consider using the `post-completion' command instead."
355 (defcustom company-minimum-prefix-length 3
356 "The minimum prefix length for automatic completion."
357 :type '(integer :tag "prefix length"))
359 (defcustom company-require-match 'company-explicit-action-p
360 "If enabled, disallow non-matching input.
361 This can be a function do determine if a match is required.
363 This can be overridden by the back-end, if it returns t or `never' to
364 `require-match'. `company-auto-complete' also takes precedence over this."
365 :type '(choice (const :tag "Off" nil)
366 (function :tag "Predicate function")
367 (const :tag "On, if user interaction took place"
368 'company-explicit-action-p)
369 (const :tag "On" t)))
371 (defcustom company-auto-complete nil
372 "Determines when to auto-complete.
373 If this is enabled, all characters from `company-auto-complete-chars'
374 complete the selected completion. This can also be a function."
375 :type '(choice (const :tag "Off" nil)
376 (function :tag "Predicate function")
377 (const :tag "On, if user interaction took place"
378 'company-explicit-action-p)
379 (const :tag "On" t)))
381 (defcustom company-auto-complete-chars '(?\ ?\) ?.)
382 "Determines which characters trigger an automatic completion.
383 See `company-auto-complete'. If this is a string, each string character
384 causes completion. If it is a list of syntax description characters (see
385 `modify-syntax-entry'), all characters with that syntax auto-complete.
387 This can also be a function, which is called with the new input and should
388 return non-nil if company should auto-complete.
390 A character that is part of a valid candidate never triggers auto-completion."
391 :type '(choice (string :tag "Characters")
393 (const :tag "Whitespace" ?\ )
394 (const :tag "Symbol" ?_)
395 (const :tag "Opening parentheses" ?\()
396 (const :tag "Closing parentheses" ?\))
397 (const :tag "Word constituent" ?w)
398 (const :tag "Punctuation." ?.)
399 (const :tag "String quote." ?\")
400 (const :tag "Paired delimiter." ?$)
401 (const :tag "Expression quote or prefix operator." ?\')
402 (const :tag "Comment starter." ?<)
403 (const :tag "Comment ender." ?>)
404 (const :tag "Character-quote." ?/)
405 (const :tag "Generic string fence." ?|)
406 (const :tag "Generic comment fence." ?!))
407 (function :tag "Predicate function")))
409 (defcustom company-idle-delay .7
410 "The idle delay in seconds until automatic completions starts.
411 A value of nil means never complete automatically, t means complete
412 immediately when a prefix of `company-minimum-prefix-length' is reached."
413 :type '(choice (const :tag "never (nil)" nil)
414 (const :tag "immediate (t)" t)
415 (number :tag "seconds")))
417 (defcustom company-begin-commands '(self-insert-command)
418 "A list of commands following which company will start completing.
419 If this is t, it will complete after any command. See `company-idle-delay'.
421 Alternatively any command with a non-nil `company-begin' property is treated
422 as if it was on this list."
423 :type '(choice (const :tag "Any command" t)
424 (const :tag "Self insert command" '(self-insert-command))
425 (repeat :tag "Commands" function)))
427 (defcustom company-show-numbers nil
428 "If enabled, show quick-access numbers for the first ten candidates."
429 :type '(choice (const :tag "off" nil)
430 (const :tag "on" t)))
432 (defcustom company-selection-wrap-around nil
433 "If enabled, selecting item before first or after last wraps around."
434 :type '(choice (const :tag "off" nil)
435 (const :tag "on" t)))
437 (defvar company-end-of-buffer-workaround t
438 "Work around a visualization bug when completing at the end of the buffer.
439 The work-around consists of adding a newline.")
441 ;;; mode ;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;
443 (defvar company-mode-map (make-sparse-keymap)
444 "Keymap used by `company-mode'.")
446 (defvar company-active-map
447 (let ((keymap (make-sparse-keymap)))
448 (define-key keymap "\e\e\e" 'company-abort)
449 (define-key keymap "\C-g" 'company-abort)
450 (define-key keymap (kbd "M-n") 'company-select-next)
451 (define-key keymap (kbd "M-p") 'company-select-previous)
452 (define-key keymap (kbd "<down>") 'company-select-next-or-abort)
453 (define-key keymap (kbd "<up>") 'company-select-previous-or-abort)
454 (define-key keymap [down-mouse-1] 'ignore)
455 (define-key keymap [down-mouse-3] 'ignore)
456 (define-key keymap [mouse-1] 'company-complete-mouse)
457 (define-key keymap [mouse-3] 'company-select-mouse)
458 (define-key keymap [up-mouse-1] 'ignore)
459 (define-key keymap [up-mouse-3] 'ignore)
460 (define-key keymap [return] 'company-complete-selection)
461 (define-key keymap (kbd "RET") 'company-complete-selection)
462 (define-key keymap [tab] 'company-complete-common)
463 (define-key keymap (kbd "TAB") 'company-complete-common)
464 (define-key keymap (kbd "<f1>") 'company-show-doc-buffer)
465 (define-key keymap "\C-w" 'company-show-location)
466 (define-key keymap "\C-s" 'company-search-candidates)
467 (define-key keymap "\C-\M-s" 'company-filter-candidates)
469 (define-key keymap (vector (+ (aref (kbd "M-0") 0) i))
470 `(lambda () (interactive) (company-complete-number ,i))))
473 "Keymap that is enabled during an active completion.")
475 (defvar company--disabled-backends nil)
477 (defun company-init-backend (backend)
478 (and (symbolp backend)
479 (not (fboundp backend))
480 (ignore-errors (require backend nil t)))
482 (if (or (symbolp backend)
486 (funcall backend 'init)
487 (put backend 'company-init t))
489 (put backend 'company-init 'failed)
490 (unless (memq backend company--disabled-backends)
491 (message "Company back-end '%s' could not be initialized:\n%s"
492 backend (error-message-string err)))
493 (pushnew backend company--disabled-backends)
495 (mapc 'company-init-backend backend)))
497 (defvar company-default-lighter " company")
499 (defvar company-lighter company-default-lighter)
500 (make-variable-buffer-local 'company-lighter)
503 (define-minor-mode company-mode
504 "\"complete anything\"; is an in-buffer completion framework.
505 Completion starts automatically, depending on the values
506 `company-idle-delay' and `company-minimum-prefix-length'.
508 Completion can be controlled with the commands:
509 `company-complete-common', `company-complete-selection', `company-complete',
510 `company-select-next', `company-select-previous'. If these commands are
511 called before `company-idle-delay', completion will also start.
513 Completions can be searched with `company-search-candidates' or
514 `company-filter-candidates'. These can be used while completion is
517 The completion data is retrieved using `company-backends' and displayed
518 using `company-frontends'. If you want to start a specific back-end, call
519 it interactively or use `company-begin-backend'.
521 regular keymap (`company-mode-map'):
524 keymap during active completions (`company-active-map'):
526 \\{company-active-map}"
527 nil company-lighter company-mode-map
530 (add-hook 'pre-command-hook 'company-pre-command nil t)
531 (add-hook 'post-command-hook 'company-post-command nil t)
532 (mapc 'company-init-backend company-backends))
533 (remove-hook 'pre-command-hook 'company-pre-command t)
534 (remove-hook 'post-command-hook 'company-post-command t)
536 (kill-local-variable 'company-point)))
538 (defcustom company-global-modes t
539 "Modes for which `company-mode' mode is turned on by `global-company-mode'.
540 If nil, means no modes. If t, then all major modes have it turned on.
541 If a list, it should be a list of `major-mode' symbol names for which
542 `company-mode' should be automatically turned on. The sense of the list is
543 negated if it begins with `not'. For example:
545 means that `company-mode' is turned on for buffers in C and C++ modes only.
547 means that `company-mode' is always turned on except in `message-mode' buffers."
548 :type '(choice (const :tag "none" nil)
550 (set :menu-tag "mode specific" :tag "modes"
552 (const :tag "Except" not)
553 (repeat :inline t (symbol :tag "mode")))))
556 (define-globalized-minor-mode global-company-mode company-mode company-mode-on)
558 (defun company-mode-on ()
559 (when (and (not (or noninteractive (eq (aref (buffer-name) 0) ?\s)))
560 (cond ((eq company-global-modes t)
562 ((eq (car-safe company-global-modes) 'not)
563 (not (memq major-mode (cdr company-global-modes))))
564 (t (memq major-mode company-global-modes))))
567 (defsubst company-assert-enabled ()
569 (company-uninstall-map)
570 (error "Company not enabled")))
572 ;;; keymaps ;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;
574 (defvar company-my-keymap nil)
575 (make-variable-buffer-local 'company-my-keymap)
577 (defvar company-emulation-alist '((t . nil)))
579 (defsubst company-enable-overriding-keymap (keymap)
580 (company-uninstall-map)
581 (setq company-my-keymap keymap))
583 (defun company-ensure-emulation-alist ()
584 (unless (eq 'company-emulation-alist (car emulation-mode-map-alists))
585 (setq emulation-mode-map-alists
586 (cons 'company-emulation-alist
587 (delq 'company-emulation-alist emulation-mode-map-alists)))))
589 (defun company-install-map ()
590 (unless (or (cdar company-emulation-alist)
591 (null company-my-keymap))
592 (setf (cdar company-emulation-alist) company-my-keymap)))
594 (defun company-uninstall-map ()
595 (setf (cdar company-emulation-alist) nil))
598 ;; Emacs calculates the active keymaps before reading the event. That means we
599 ;; cannot change the keymap from a timer. So we send a bogus command.
600 (defun company-ignore ()
602 (setq this-command last-command))
604 (global-set-key '[31415926] 'company-ignore)
606 (defun company-input-noop ()
607 (push 31415926 unread-command-events))
609 (defun company--column (&optional pos)
611 (when pos (goto-char pos))
615 (narrow-to-region (point) (point-max))
616 (let ((prefix (get-text-property (point) 'line-prefix)))
617 (if prefix (length prefix) 0)))
620 (defun company--row (&optional pos)
622 (when pos (goto-char pos))
623 (count-screen-lines (window-start)
624 (progn (vertical-motion 0) (point)))))
626 ;;; backends ;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;
628 (defvar company-backend nil)
629 (make-variable-buffer-local 'company-backend)
631 (defun company-grab (regexp &optional expression limit)
632 (when (looking-back regexp limit)
633 (or (match-string-no-properties (or expression 0)) "")))
635 (defun company-grab-line (regexp &optional expression)
636 (company-grab regexp expression (point-at-bol)))
638 (defun company-grab-symbol ()
639 (if (looking-at "\\_>")
640 (buffer-substring (point) (save-excursion (skip-syntax-backward "w_")
642 (unless (and (char-after) (memq (char-syntax (char-after)) '(?w ?_)))
645 (defun company-grab-word ()
646 (if (looking-at "\\>")
647 (buffer-substring (point) (save-excursion (skip-syntax-backward "w")
649 (unless (and (char-after) (eq (char-syntax (char-after)) ?w))
652 (defun company-in-string-or-comment ()
653 (let ((ppss (syntax-ppss)))
654 (or (car (setq ppss (nthcdr 3 ppss)))
655 (car (setq ppss (cdr ppss)))
658 (if (fboundp 'locate-dominating-file)
659 (defalias 'company-locate-dominating-file 'locate-dominating-file)
660 (defun company-locate-dominating-file (file name)
662 (let ((dir (file-name-directory file))
664 (while (not (equal dir prev-dir))
665 (when (file-exists-p (expand-file-name name dir))
668 dir (file-name-directory (directory-file-name dir))))))))
670 (defun company-call-backend (&rest args)
671 (if (functionp company-backend)
672 (apply company-backend args)
673 (apply 'company--multi-backend-adapter company-backend args)))
675 (defun company--multi-backend-adapter (backends command &rest args)
676 (let ((backends (loop for b in backends
677 when (not (and (symbolp b)
678 (eq 'failed (get b 'company-init))))
682 (loop for backend in backends
683 when (equal (funcall backend 'prefix)
685 append (apply backend 'candidates args)))
690 (dolist (backend backends)
691 (when (setq value (apply backend command args))
692 (return value))))))))
694 ;;; completion mechanism ;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;
696 (defvar company-prefix nil)
697 (make-variable-buffer-local 'company-prefix)
699 (defvar company-candidates nil)
700 (make-variable-buffer-local 'company-candidates)
702 (defvar company-candidates-length nil)
703 (make-variable-buffer-local 'company-candidates-length)
705 (defvar company-candidates-cache nil)
706 (make-variable-buffer-local 'company-candidates-cache)
708 (defvar company-candidates-predicate nil)
709 (make-variable-buffer-local 'company-candidates-predicate)
711 (defvar company-common nil)
712 (make-variable-buffer-local 'company-common)
714 (defvar company-selection 0)
715 (make-variable-buffer-local 'company-selection)
717 (defvar company-selection-changed nil)
718 (make-variable-buffer-local 'company-selection-changed)
720 (defvar company--explicit-action nil
721 "Non-nil, if explicit completion took place.")
722 (make-variable-buffer-local 'company--explicit-action)
724 (defvar company--auto-completion nil
725 "Non-nil when current candidate is being completed automatically.
726 Controlled by `company-auto-complete'.")
728 (defvar company--point-max nil)
729 (make-variable-buffer-local 'company--point-max)
731 (defvar company-point nil)
732 (make-variable-buffer-local 'company-point)
734 (defvar company-timer nil)
736 (defvar company-added-newline nil)
737 (make-variable-buffer-local 'company-added-newline)
739 (defsubst company-strip-prefix (str)
740 (substring str (length company-prefix)))
742 (defmacro company-with-candidate-inserted (candidate &rest body)
743 "Evaluate BODY with CANDIDATE temporarily inserted.
744 This is a tool for back-ends that need candidates inserted before they
745 can retrieve meta-data for them."
747 `(let ((inhibit-modification-hooks t)
748 (inhibit-point-motion-hooks t)
749 (modified-p (buffer-modified-p)))
750 (insert (company-strip-prefix ,candidate))
753 (delete-region company-point (point)))))
755 (defun company-explicit-action-p ()
756 "Return whether explicit completion action was taken by the user."
757 (or company--explicit-action
758 company-selection-changed))
760 (defun company-reformat (candidate)
761 ;; company-ispell needs this, because the results are always lower-case
762 ;; It's mory efficient to fix it only when they are displayed.
763 (concat company-prefix (substring candidate (length company-prefix))))
765 (defun company--should-complete ()
766 (and (not (or buffer-read-only overriding-terminal-local-map
767 overriding-local-map))
768 ;; Check if in the middle of entering a key combination.
769 (or (equal (this-command-keys-vector) [])
770 (not (keymapp (key-binding (this-command-keys-vector)))))
771 (eq company-idle-delay t)
772 (or (eq t company-begin-commands)
773 (memq this-command company-begin-commands)
774 (and (symbolp this-command) (get this-command 'company-begin)))
775 (not (and transient-mark-mode mark-active))))
777 (defun company-call-frontends (command)
778 (dolist (frontend company-frontends)
780 (funcall frontend command)
781 (error (error "Company: Front-end %s error \"%s\" on command %s"
782 frontend (error-message-string err) command)))))
784 (defun company-set-selection (selection &optional force-update)
786 (if company-selection-wrap-around
787 (mod selection company-candidates-length)
788 (max 0 (min (1- company-candidates-length) selection))))
789 (when (or force-update (not (equal selection company-selection)))
790 (setq company-selection selection
791 company-selection-changed t)
792 (company-call-frontends 'update)))
794 (defun company-apply-predicate (candidates predicate)
796 (dolist (c candidates)
797 (when (funcall predicate c)
801 (defun company-update-candidates (candidates)
802 (setq company-candidates-length (length candidates))
803 (if (> company-selection 0)
804 ;; Try to restore the selection
805 (let ((selected (nth company-selection company-candidates)))
806 (setq company-selection 0
807 company-candidates candidates)
809 (while (and candidates (string< (pop candidates) selected))
810 (incf company-selection))
812 ;; Make sure selection isn't out of bounds.
813 (setq company-selection (min (1- company-candidates-length)
814 company-selection)))))
815 (setq company-selection 0
816 company-candidates candidates))
818 (push (cons company-prefix company-candidates) company-candidates-cache)
820 (let ((completion-ignore-case (company-call-backend 'ignore-case)))
821 (setq company-common (company--safe-candidate
822 (try-completion company-prefix company-candidates))))
823 (when (eq company-common t)
824 (setq company-candidates nil)))
826 (defun company--safe-candidate (str)
827 (or (company-call-backend 'crop str)
830 (defun company-calculate-candidates (prefix)
831 (let ((candidates (cdr (assoc prefix company-candidates-cache)))
832 (ignore-case (company-call-backend 'ignore-case)))
834 (when company-candidates-cache
835 (let ((len (length prefix))
836 (completion-ignore-case ignore-case)
838 (dotimes (i (1+ len))
839 (when (setq prev (cdr (assoc (substring prefix 0 (- len i))
840 company-candidates-cache)))
841 (setq candidates (all-completions prefix prev))
843 ;; no cache match, call back-end
845 (setq candidates (company-call-backend 'candidates prefix))
846 (when company-candidates-predicate
848 (company-apply-predicate candidates
849 company-candidates-predicate)))
850 (unless (company-call-backend 'sorted)
851 (setq candidates (sort candidates 'string<)))
852 (when (company-call-backend 'duplicates)
854 (let ((c2 candidates))
856 (setcdr c2 (progn (while (equal (pop c2) (car c2)))
859 (if (or (cdr candidates)
860 (not (eq t (compare-strings (car candidates) nil nil
861 prefix nil nil ignore-case))))
863 ;; Already completed and unique; don't start.
866 (defun company-idle-begin (buf win tick pos)
868 (eq buf (current-buffer))
869 (eq win (selected-window))
870 (eq tick (buffer-chars-modified-tick))
872 (not company-candidates)
873 (not (equal (point) company-point))
874 (let ((company-idle-delay t)
875 (company-begin-commands t))
877 (when company-candidates
879 (company-post-command)))))
881 (defun company-auto-begin ()
882 (company-assert-enabled)
884 (not company-candidates)
885 (let ((company-idle-delay t)
886 (company-minimum-prefix-length 0)
887 (company-begin-commands t))
889 ;; Return non-nil if active.
892 (defun company-manual-begin ()
894 (setq company--explicit-action t)
897 (unless company-candidates
898 (setq company--explicit-action nil))))
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 (not (eq backend-value 'never))
921 (if (functionp company-require-match)
922 (funcall company-require-match)
923 (eq company-require-match t))))))
925 (defun company-auto-complete-p (input)
926 "Return non-nil, if input starts with punctuation or parentheses."
927 (and (if (functionp company-auto-complete)
928 (funcall company-auto-complete)
929 company-auto-complete)
930 (if (functionp company-auto-complete-chars)
931 (funcall company-auto-complete-chars input)
932 (if (consp company-auto-complete-chars)
933 (memq (char-syntax (string-to-char input))
934 company-auto-complete-chars)
935 (string-match (substring input 0 1) company-auto-complete-chars)))))
937 (defun company--incremental-p ()
938 (and (> (point) company-point)
939 (> (point-max) company--point-max)
940 (not (eq this-command 'backward-delete-char-untabify))
941 (equal (buffer-substring (- company-point (length company-prefix))
945 (defsubst company--string-incremental-p (old-prefix new-prefix)
946 (and (> (length new-prefix) (length old-prefix))
947 (equal old-prefix (substring new-prefix 0 (length old-prefix)))))
949 (defun company--continue-failed (new-prefix)
950 (when (company--incremental-p)
951 (let ((input (buffer-substring-no-properties (point) company-point)))
953 ((company-auto-complete-p input)
956 (goto-char company-point)
957 (let ((company--auto-completion t))
958 (company-complete-selection))
960 ((and (company--string-incremental-p company-prefix new-prefix)
961 (company-require-match-p))
962 ;; wrong incremental input, but required match
963 (delete-char (- (length input)))
965 (message "Matching input is required")
967 ((equal company-prefix (car company-candidates))
968 ;; last input was actually success
969 (company-cancel company-prefix)
972 (defun company--good-prefix-p (prefix)
973 (and (or (company-explicit-action-p)
974 (unless (eq prefix 'stop)
975 (or (eq (cdr-safe prefix) t)
976 (>= (or (cdr-safe prefix) (length prefix))
977 company-minimum-prefix-length))))
978 (stringp (or (car-safe prefix) prefix))))
980 (defun company--continue ()
981 (when (company-call-backend 'no-cache company-prefix)
982 ;; Don't complete existing candidates, fetch new ones.
983 (setq company-candidates-cache nil))
984 (let* ((new-prefix (company-call-backend 'prefix))
985 (c (when (and (company--good-prefix-p new-prefix)
986 (setq new-prefix (or (car-safe new-prefix) new-prefix))
987 (= (- (point) (length new-prefix))
988 (- company-point (length company-prefix))))
989 (setq new-prefix (or (car-safe new-prefix) new-prefix))
990 (company-calculate-candidates new-prefix))))
993 ;; t means complete/unique.
994 (company-cancel new-prefix)
998 (setq company-prefix new-prefix)
999 (company-update-candidates c)
1001 (t (company--continue-failed new-prefix)))
1004 (defun company--begin-new ()
1006 (dolist (backend (if company-backend
1007 ;; prefer manual override
1008 (list company-backend)
1011 (if (or (symbolp backend)
1012 (functionp backend))
1013 (when (or (not (symbolp backend))
1014 (eq t (get backend 'company-init))
1015 (unless (get backend 'company-init)
1016 (company-init-backend backend)))
1017 (funcall backend 'prefix))
1018 (company--multi-backend-adapter backend 'prefix)))
1020 (when (company--good-prefix-p prefix)
1021 (setq prefix (or (car-safe prefix) prefix)
1022 company-backend backend
1023 c (company-calculate-candidates prefix))
1024 ;; t means complete/unique. We don't start, so no hooks.
1026 (when company--explicit-action
1027 (message "No completion found"))
1028 (setq company-prefix prefix)
1029 (when (symbolp backend)
1030 (setq company-lighter (concat " " (symbol-name backend))))
1031 (company-update-candidates c)
1032 (run-hook-with-args 'company-completion-started-hook
1033 (company-explicit-action-p))
1034 (company-call-frontends 'show)))
1037 (defun company-begin ()
1038 (or (and company-candidates (company--continue))
1039 (and (company--should-complete) (company--begin-new)))
1040 (when company-candidates
1041 (when (and company-end-of-buffer-workaround (eobp))
1042 (save-excursion (insert "\n"))
1043 (setq company-added-newline (buffer-chars-modified-tick)))
1044 (setq company-point (point)
1045 company--point-max (point-max))
1046 (company-ensure-emulation-alist)
1047 (company-enable-overriding-keymap company-active-map)
1048 (company-call-frontends 'update)))
1050 (defun company-cancel (&optional result)
1051 (and company-added-newline
1052 (> (point-max) (point-min))
1053 (let ((tick (buffer-chars-modified-tick)))
1054 (delete-region (1- (point-max)) (point-max))
1055 (equal tick company-added-newline))
1056 ;; Only set unmodified when tick remained the same since insert.
1057 (set-buffer-modified-p nil))
1058 (when company-prefix
1059 (if (stringp result)
1061 (company-call-backend 'pre-completion result)
1062 (run-hook-with-args 'company-completion-finished-hook result)
1063 (company-call-backend 'post-completion result))
1064 (run-hook-with-args 'company-completion-cancelled-hook result)))
1065 (setq company-added-newline nil
1068 company-candidates nil
1069 company-candidates-length nil
1070 company-candidates-cache nil
1071 company-candidates-predicate nil
1074 company-selection-changed nil
1075 company--explicit-action nil
1076 company-lighter company-default-lighter
1077 company--point-max nil
1080 (cancel-timer company-timer))
1081 (company-search-mode 0)
1082 (company-call-frontends 'hide)
1083 (company-enable-overriding-keymap nil))
1085 (defun company-abort ()
1088 ;; Don't start again, unless started manually.
1089 (setq company-point (point)))
1091 (defun company-finish (result)
1092 (insert (company-strip-prefix result))
1093 (company-cancel result)
1094 ;; Don't start again, unless started manually.
1095 (setq company-point (point)))
1097 (defsubst company-keep (command)
1098 (and (symbolp command) (get command 'company-keep)))
1100 (defun company-pre-command ()
1101 (unless (company-keep this-command)
1103 (when company-candidates
1104 (company-call-frontends 'pre-command))
1105 (error (message "Company: An error occurred in pre-command")
1106 (message "%s" (error-message-string err))
1109 (cancel-timer company-timer)
1110 (setq company-timer nil))
1111 (company-uninstall-map))
1113 (defun company-post-command ()
1114 (unless (company-keep this-command)
1117 (unless (equal (point) company-point)
1119 (if company-candidates
1120 (company-call-frontends 'post-command)
1121 (and (numberp company-idle-delay)
1122 (or (eq t company-begin-commands)
1123 (memq this-command company-begin-commands))
1125 (run-with-timer company-idle-delay nil
1127 (current-buffer) (selected-window)
1128 (buffer-chars-modified-tick) (point))))))
1129 (error (message "Company: An error occurred in post-command")
1130 (message "%s" (error-message-string err))
1132 (company-install-map))
1134 ;;; search ;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;
1136 (defvar company-search-string nil)
1137 (make-variable-buffer-local 'company-search-string)
1139 (defvar company-search-lighter " Search: \"\"")
1140 (make-variable-buffer-local 'company-search-lighter)
1142 (defvar company-search-old-map nil)
1143 (make-variable-buffer-local 'company-search-old-map)
1145 (defvar company-search-old-selection 0)
1146 (make-variable-buffer-local 'company-search-old-selection)
1148 (defun company-search (text lines)
1149 (let ((quoted (regexp-quote text))
1151 (dolist (line lines)
1152 (when (string-match quoted line (length company-prefix))
1156 (defun company-search-printing-char ()
1158 (company-search-assert-enabled)
1159 (setq company-search-string
1160 (concat (or company-search-string "") (string last-command-event))
1161 company-search-lighter (concat " Search: \"" company-search-string
1163 (let ((pos (company-search company-search-string
1164 (nthcdr company-selection company-candidates))))
1167 (company-set-selection (+ company-selection pos) t))))
1169 (defun company-search-repeat-forward ()
1170 "Repeat the incremental search in completion candidates forward."
1172 (company-search-assert-enabled)
1173 (let ((pos (company-search company-search-string
1174 (cdr (nthcdr company-selection
1175 company-candidates)))))
1178 (company-set-selection (+ company-selection pos 1) t))))
1180 (defun company-search-repeat-backward ()
1181 "Repeat the incremental search in completion candidates backwards."
1183 (company-search-assert-enabled)
1184 (let ((pos (company-search company-search-string
1185 (nthcdr (- company-candidates-length
1187 (reverse company-candidates)))))
1190 (company-set-selection (- company-selection pos 1) t))))
1192 (defun company-create-match-predicate ()
1193 (setq company-candidates-predicate
1194 `(lambda (candidate)
1195 ,(if company-candidates-predicate
1196 `(and (string-match ,company-search-string candidate)
1197 (funcall ,company-candidates-predicate
1199 `(string-match ,company-search-string candidate))))
1200 (company-update-candidates
1201 (company-apply-predicate company-candidates company-candidates-predicate))
1202 ;; Invalidate cache.
1203 (setq company-candidates-cache (cons company-prefix company-candidates)))
1205 (defun company-filter-printing-char ()
1207 (company-search-assert-enabled)
1208 (company-search-printing-char)
1209 (company-create-match-predicate)
1210 (company-call-frontends 'update))
1212 (defun company-search-kill-others ()
1213 "Limit the completion candidates to the ones matching the search string."
1215 (company-search-assert-enabled)
1216 (company-create-match-predicate)
1217 (company-search-mode 0)
1218 (company-call-frontends 'update))
1220 (defun company-search-abort ()
1221 "Abort searching the completion candidates."
1223 (company-search-assert-enabled)
1224 (company-set-selection company-search-old-selection t)
1225 (company-search-mode 0))
1227 (defun company-search-other-char ()
1229 (company-search-assert-enabled)
1230 (company-search-mode 0)
1231 (company--unread-last-input))
1233 (defvar company-search-map
1235 (keymap (make-keymap)))
1236 (if (fboundp 'max-char)
1237 (set-char-table-range (nth 1 keymap) (cons #x100 (max-char))
1238 'company-search-printing-char)
1240 ;; obsolete in Emacs 23
1241 (let ((l (generic-character-list))
1242 (table (nth 1 keymap)))
1244 (set-char-table-default table (car l) 'company-search-printing-char)
1245 (setq l (cdr l))))))
1246 (define-key keymap [t] 'company-search-other-char)
1248 (define-key keymap (make-string 1 i) 'company-search-other-char)
1251 (define-key keymap (vector i) 'company-search-printing-char)
1253 (let ((meta-map (make-sparse-keymap)))
1254 (define-key keymap (char-to-string meta-prefix-char) meta-map)
1255 (define-key keymap [escape] meta-map))
1256 (define-key keymap (vector meta-prefix-char t) 'company-search-other-char)
1257 (define-key keymap "\e\e\e" 'company-search-other-char)
1258 (define-key keymap [escape escape escape] 'company-search-other-char)
1260 (define-key keymap "\C-g" 'company-search-abort)
1261 (define-key keymap "\C-s" 'company-search-repeat-forward)
1262 (define-key keymap "\C-r" 'company-search-repeat-backward)
1263 (define-key keymap "\C-o" 'company-search-kill-others)
1265 "Keymap used for incrementally searching the completion candidates.")
1267 (define-minor-mode company-search-mode
1268 "Search mode for completion candidates.
1269 Don't start this directly, use `company-search-candidates' or
1270 `company-filter-candidates'."
1271 nil company-search-lighter nil
1272 (if company-search-mode
1273 (if (company-manual-begin)
1275 (setq company-search-old-selection company-selection)
1276 (company-call-frontends 'update))
1277 (setq company-search-mode nil))
1278 (kill-local-variable 'company-search-string)
1279 (kill-local-variable 'company-search-lighter)
1280 (kill-local-variable 'company-search-old-selection)
1281 (company-enable-overriding-keymap company-active-map)))
1283 (defun company-search-assert-enabled ()
1284 (company-assert-enabled)
1285 (unless company-search-mode
1286 (company-uninstall-map)
1287 (error "Company not in search mode")))
1289 (defun company-search-candidates ()
1290 "Start searching the completion candidates incrementally.
1292 \\<company-search-map>Search can be controlled with the commands:
1293 - `company-search-repeat-forward' (\\[company-search-repeat-forward])
1294 - `company-search-repeat-backward' (\\[company-search-repeat-backward])
1295 - `company-search-abort' (\\[company-search-abort])
1297 Regular characters are appended to the search string.
1299 The command `company-search-kill-others' (\\[company-search-kill-others])
1300 uses the search string to limit the completion candidates."
1302 (company-search-mode 1)
1303 (company-enable-overriding-keymap company-search-map))
1305 (defvar company-filter-map
1306 (let ((keymap (make-keymap)))
1307 (define-key keymap [remap company-search-printing-char]
1308 'company-filter-printing-char)
1309 (set-keymap-parent keymap company-search-map)
1311 "Keymap used for incrementally searching the completion candidates.")
1313 (defun company-filter-candidates ()
1314 "Start filtering the completion candidates incrementally.
1315 This works the same way as `company-search-candidates' immediately
1316 followed by `company-search-kill-others' after each input."
1318 (company-search-mode 1)
1319 (company-enable-overriding-keymap company-filter-map))
1321 ;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;
1323 (defun company-select-next ()
1324 "Select the next candidate in the list."
1326 (when (company-manual-begin)
1327 (company-set-selection (1+ company-selection))))
1329 (defun company-select-previous ()
1330 "Select the previous candidate in the list."
1332 (when (company-manual-begin)
1333 (company-set-selection (1- company-selection))))
1335 (defun company-select-next-or-abort ()
1336 "Select the next candidate if more than one, else abort
1337 and invoke the normal binding."
1339 (if (> company-candidates-length 1)
1340 (company-select-next)
1342 (company--unread-last-input)))
1344 (defun company-select-previous-or-abort ()
1345 "Select the previous candidate if more than one, else abort
1346 and invoke the normal binding."
1348 (if (> company-candidates-length 1)
1349 (company-select-previous)
1351 (company--unread-last-input)))
1353 (defvar company-pseudo-tooltip-overlay)
1355 (defvar company-tooltip-offset)
1357 (defun company--inside-tooltip-p (event-col-row row height)
1358 (let* ((ovl company-pseudo-tooltip-overlay)
1359 (column (overlay-get ovl 'company-column))
1360 (width (overlay-get ovl 'company-width))
1361 (evt-col (car event-col-row))
1362 (evt-row (cdr event-col-row)))
1363 (and (>= evt-col column)
1364 (< evt-col (+ column width))
1366 (and (> evt-row row)
1367 (<= evt-row (+ row height) ))
1368 (and (< evt-row row)
1369 (>= evt-row (+ row height)))))))
1371 (defun company--event-col-row (event)
1372 (let* ((col-row (posn-actual-col-row (event-start event)))
1374 (row (cdr col-row)))
1375 (incf col (window-hscroll))
1376 (and header-line-format
1377 (version< "24" emacs-version)
1381 (defun company-select-mouse (event)
1382 "Select the candidate picked by the mouse."
1384 (let ((event-col-row (company--event-col-row event))
1385 (ovl-row (company--row))
1386 (ovl-height (and company-pseudo-tooltip-overlay
1387 (min (overlay-get company-pseudo-tooltip-overlay
1389 company-candidates-length))))
1391 (company--inside-tooltip-p event-col-row ovl-row ovl-height))
1393 (company-set-selection (+ (cdr event-col-row)
1394 (if (zerop company-tooltip-offset)
1396 (- company-tooltip-offset 2))
1398 (if (< ovl-height 0)
1403 (company--unread-last-input)
1406 (defun company-complete-mouse (event)
1407 "Complete the candidate picked by the mouse."
1409 (when (company-select-mouse event)
1410 (company-complete-selection)))
1412 (defun company-complete-selection ()
1413 "Complete the selected candidate."
1415 (when (company-manual-begin)
1416 (let ((result (nth company-selection company-candidates)))
1417 (when company--auto-completion
1418 (setq result (company--safe-candidate result)))
1419 (company-finish result))))
1421 (defun company-complete-common ()
1422 "Complete the common part of all candidates."
1424 (when (company-manual-begin)
1425 (if (and (not (cdr company-candidates))
1426 (equal company-common (car company-candidates)))
1427 (company-complete-selection)
1428 (insert (company-strip-prefix company-common)))))
1430 (defun company-complete ()
1431 "Complete the common part of all candidates or the current selection.
1432 The first time this is called, the common part is completed, the second
1433 time, or when the selection has been changed, the selected candidate is
1436 (when (company-manual-begin)
1437 (if (or company-selection-changed
1438 (eq last-command 'company-complete-common))
1439 (call-interactively 'company-complete-selection)
1440 (call-interactively 'company-complete-common)
1441 (setq this-command 'company-complete-common))))
1443 (defun company-complete-number (n)
1444 "Complete the Nth candidate.
1445 To show the number next to the candidates in some back-ends, enable
1446 `company-show-numbers'."
1447 (when (company-manual-begin)
1448 (and (< n 1) (> n company-candidates-length)
1449 (error "No candidate number %d" n))
1451 (company-finish (nth n company-candidates))))
1453 ;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;
1455 (defconst company-space-strings-limit 100)
1457 (defconst company-space-strings
1459 (dotimes (i company-space-strings-limit)
1460 (push (make-string (- company-space-strings-limit 1 i) ?\ ) lst))
1461 (apply 'vector lst)))
1463 (defun company-space-string (len)
1464 (if (< len company-space-strings-limit)
1465 (aref company-space-strings len)
1466 (make-string len ?\ )))
1468 (defun company-safe-substring (str from &optional to)
1469 (if (> from (string-width str))
1473 (move-to-column from)
1474 (let ((beg (point)))
1478 (concat (buffer-substring beg (point))
1479 (let ((padding (- to (current-column))))
1481 (company-space-string padding)))))
1482 (buffer-substring beg (point-max)))))))
1484 ;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;
1486 (defvar company-last-metadata nil)
1487 (make-variable-buffer-local 'company-last-metadata)
1489 (defun company-fetch-metadata ()
1490 (let ((selected (nth company-selection company-candidates)))
1491 (unless (equal selected (car company-last-metadata))
1492 (setq company-last-metadata
1493 (cons selected (company-call-backend 'meta selected))))
1494 (cdr company-last-metadata)))
1496 (defun company-doc-buffer (&optional string)
1497 (with-current-buffer (get-buffer-create "*company-documentation*")
1504 (defvar company--electric-commands
1505 '(scroll-other-window scroll-other-window-down)
1506 "List of Commands that won't break out of electric commands.")
1508 (defmacro company--electric-do (&rest body)
1509 (declare (indent 0) (debug t))
1510 `(when (company-manual-begin)
1511 (save-window-excursion
1512 (let ((height (window-height))
1513 (row (company--row))
1516 (and (< (window-height) height)
1517 (< (- (window-height) row 2) company-tooltip-limit)
1518 (recenter (- (window-height) row 2)))
1519 (while (memq (setq cmd (key-binding (vector (list (read-event)))))
1520 company--electric-commands)
1521 (call-interactively cmd))
1522 (company--unread-last-input)))))
1524 (defun company--unread-last-input ()
1525 (when last-input-event
1526 (clear-this-command-keys t)
1527 (setq unread-command-events (list last-input-event))))
1529 (defun company-show-doc-buffer ()
1530 "Temporarily show the documentation buffer for the selection."
1532 (company--electric-do
1533 (let* ((selected (nth company-selection company-candidates))
1534 (doc-buffer (or (company-call-backend 'doc-buffer selected)
1535 (error "No documentation available"))))
1536 (with-current-buffer doc-buffer
1537 (goto-char (point-min)))
1538 (display-buffer doc-buffer t))))
1539 (put 'company-show-doc-buffer 'company-keep t)
1541 (defun company-show-location ()
1542 "Temporarily display a buffer showing the selected candidate in context."
1544 (company--electric-do
1545 (let* ((selected (nth company-selection company-candidates))
1546 (location (company-call-backend 'location selected))
1547 (pos (or (cdr location) (error "No location available")))
1548 (buffer (or (and (bufferp (car location)) (car location))
1549 (find-file-noselect (car location) t))))
1550 (with-selected-window (display-buffer buffer t)
1553 (if (bufferp (car location))
1555 (goto-char (point-min))
1556 (forward-line (1- pos))))
1557 (set-window-start nil (point))))))
1558 (put 'company-show-location 'company-keep t)
1560 ;;; package functions ;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;
1562 (defvar company-callback nil)
1563 (make-variable-buffer-local 'company-callback)
1565 (defvar company-begin-with-marker nil)
1566 (make-variable-buffer-local 'company-begin-with-marker)
1568 (defun company-remove-callback (&optional ignored)
1569 (remove-hook 'company-completion-finished-hook company-callback t)
1570 (remove-hook 'company-completion-cancelled-hook 'company-remove-callback t)
1571 (remove-hook 'company-completion-finished-hook 'company-remove-callback t)
1572 (when company-begin-with-marker
1573 (set-marker company-begin-with-marker nil)))
1575 (defun company-begin-backend (backend &optional callback)
1576 "Start a completion at point using BACKEND."
1577 (interactive (let ((val (completing-read "Company back-end: "
1579 'functionp nil "company-")))
1581 (list (intern val)))))
1582 (when (setq company-callback callback)
1583 (add-hook 'company-completion-finished-hook company-callback nil t))
1584 (add-hook 'company-completion-cancelled-hook 'company-remove-callback nil t)
1585 (add-hook 'company-completion-finished-hook 'company-remove-callback nil t)
1586 (setq company-backend backend)
1587 ;; Return non-nil if active.
1588 (or (company-manual-begin)
1590 (setq company-backend nil)
1591 (error "Cannot complete at point"))))
1593 (defun company-begin-with (candidates
1594 &optional prefix-length require-match callback)
1595 "Start a completion at point.
1596 CANDIDATES is the list of candidates to use and PREFIX-LENGTH is the length
1597 of the prefix that already is in the buffer before point.
1600 CALLBACK is a function called with the selected result if the user
1601 successfully completes the input.
1603 Example: \(company-begin-with '\(\"foo\" \"foobar\" \"foobarbaz\"\)\)"
1604 ;; FIXME: When Emacs 23 is no longer a concern, replace
1605 ;; `company-begin-with-marker' with a lexical variable; use a lexical closure.
1606 (setq company-begin-with-marker (copy-marker (point) t))
1607 (company-begin-backend
1608 `(lambda (command &optional arg &rest ignored)
1610 ((eq command 'prefix)
1611 (when (equal (point) (marker-position company-begin-with-marker))
1612 (buffer-substring ,(- (point) (or prefix-length 0)) (point))))
1613 ((eq command 'candidates)
1614 (all-completions arg ',candidates))
1615 ((eq command 'require-match)
1619 ;;; pseudo-tooltip ;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;
1621 (defvar company-pseudo-tooltip-overlay nil)
1622 (make-variable-buffer-local 'company-pseudo-tooltip-overlay)
1624 (defvar company-tooltip-offset 0)
1625 (make-variable-buffer-local 'company-tooltip-offset)
1627 (defun company-pseudo-tooltip-update-offset (selection num-lines limit)
1630 (setq company-tooltip-offset
1631 (max (min selection company-tooltip-offset)
1632 (- selection -1 limit)))
1634 (when (<= company-tooltip-offset 1)
1636 (setq company-tooltip-offset 0))
1638 (when (>= company-tooltip-offset (- num-lines limit 1))
1640 (when (= selection (1- num-lines))
1641 (decf company-tooltip-offset)
1642 (when (<= company-tooltip-offset 1)
1643 (setq company-tooltip-offset 0)
1650 (defsubst company-round-tab (arg)
1651 (* (/ (+ arg tab-width) tab-width) tab-width))
1653 (defun company-plainify (str)
1654 (let ((prefix (get-text-property 0 'line-prefix str)))
1655 (when prefix ; Keep the original value unmodified, for no special reason.
1656 (setq str (concat prefix str))
1657 (remove-text-properties 0 (length str) '(line-prefix) str)))
1658 (let* ((pieces (split-string str "\t"))
1661 (setcar copy (company-safe-substring
1662 (car copy) 0 (company-round-tab (string-width (car copy)))))
1664 (apply 'concat pieces)))
1666 (defun company-fill-propertize (line width selected)
1667 (setq line (company-safe-substring line 0 width))
1668 (add-text-properties 0 width '(face company-tooltip
1669 mouse-face company-tooltip-mouse)
1671 (add-text-properties 0 (length company-common)
1672 '(face company-tooltip-common
1673 mouse-face company-tooltip-mouse)
1676 (if (and company-search-string
1677 (string-match (regexp-quote company-search-string) line
1678 (length company-prefix)))
1680 (add-text-properties (match-beginning 0) (match-end 0)
1681 '(face company-tooltip-selection)
1683 (when (< (match-beginning 0) (length company-common))
1684 (add-text-properties (match-beginning 0) (length company-common)
1685 '(face company-tooltip-common-selection)
1687 (add-text-properties 0 width '(face company-tooltip-selection
1688 mouse-face company-tooltip-selection)
1690 (add-text-properties 0 (length company-common)
1691 '(face company-tooltip-common-selection
1692 mouse-face company-tooltip-selection)
1698 (defun company-buffer-lines (beg end)
1701 (while (and (= 1 (vertical-motion 1))
1703 (let ((bound (min end (1- (point)))))
1704 ;; A visual line can contain several physical lines (e.g. with outline's
1705 ;; folding overlay). Take only the first one.
1706 (push (buffer-substring beg
1709 (re-search-forward "$" bound 'move)
1713 (unless (eq beg end)
1714 (push (buffer-substring beg end) lines))
1717 (defun company-modify-line (old new offset)
1718 (concat (company-safe-substring old 0 offset)
1720 (company-safe-substring old (+ offset (length new)))))
1722 (defsubst company--length-limit (lst limit)
1723 (if (nthcdr limit lst)
1727 (defun company--replacement-string (lines old column nl &optional align-top)
1729 (let ((width (length (car lines)))
1730 (remaining-cols (- (+ (window-width) (window-hscroll))
1732 (when (> width remaining-cols)
1733 (decf column (- width remaining-cols))))
1737 ;; untouched lines first
1738 (dotimes (_ (- (length old) (length lines)))
1739 (push (pop old) new)))
1740 ;; length into old lines.
1742 (push (company-modify-line (pop old) (pop lines) column) new))
1743 ;; Append whole new lines.
1745 (push (concat (company-space-string column) (pop lines)) new))
1747 (let ((str (concat (when nl "\n")
1748 (mapconcat 'identity (nreverse new) "\n")
1750 (font-lock-append-text-property 0 (length str) 'face 'default str)
1753 (defun company--create-lines (selection limit)
1755 (let ((len company-candidates-length)
1764 ;; Scroll to offset.
1765 (setq limit (company-pseudo-tooltip-update-offset selection len limit))
1767 (when (> company-tooltip-offset 0)
1768 (setq previous (format "...(%d)" company-tooltip-offset)))
1770 (setq remainder (- len limit company-tooltip-offset)
1771 remainder (when (> remainder 0)
1772 (setq remainder (format "...(%d)" remainder))))
1774 (decf selection company-tooltip-offset)
1775 (setq width (max (length previous) (length remainder))
1776 lines (nthcdr company-tooltip-offset company-candidates)
1781 (setq width (max (length (pop lines-copy)) width)))
1782 (setq width (min (window-width)
1783 (if company-show-numbers
1786 (setq lines-copy lines)
1788 ;; number can make tooltip too long
1789 (when company-show-numbers
1790 (setq numbered company-tooltip-offset))
1793 (push (propertize (company-safe-substring previous 0 width)
1794 'face 'company-tooltip)
1798 (push (company-fill-propertize
1799 (if (>= numbered 10)
1800 (company-reformat (pop lines))
1803 (company-safe-substring (company-reformat (pop lines))
1806 width (equal i selection))
1810 (push (propertize (company-safe-substring remainder 0 width)
1811 'face 'company-tooltip)
1814 (setq lines (nreverse new))))
1818 (defsubst company--window-inner-height ()
1819 (let ((edges (window-inside-edges)))
1820 (- (nth 3 edges) (nth 1 edges))))
1822 (defun company--pseudo-tooltip-height ()
1823 "Calculate the appropriate tooltip height.
1824 Returns a negative number if the tooltip should be displayed above point."
1825 (let* ((lines (company--row))
1826 (below (- (company--window-inner-height) 1 lines)))
1827 (if (and (< below (min company-tooltip-minimum company-candidates-length))
1829 (- (max 3 (min company-tooltip-limit lines)))
1830 (max 3 (min company-tooltip-limit below)))))
1832 (defun company-pseudo-tooltip-show (row column selection)
1833 (company-pseudo-tooltip-hide)
1836 (let* ((height (company--pseudo-tooltip-height))
1840 (setq row (+ row height -1)
1843 (let* ((nl (< (move-to-window-line row) row))
1845 (end (save-excursion
1846 (move-to-window-line (+ row (abs height)))
1848 (ov (make-overlay beg end))
1849 (args (list (mapcar 'company-plainify
1850 (company-buffer-lines beg end))
1853 (setq company-pseudo-tooltip-overlay ov)
1854 (overlay-put ov 'company-replacement-args args)
1856 (let ((lines (company--create-lines selection (abs height))))
1857 (overlay-put ov 'company-after
1858 (apply 'company--replacement-string lines args))
1859 (overlay-put ov 'company-width (string-width (car lines))))
1861 (overlay-put ov 'company-column column)
1862 (overlay-put ov 'company-height height)))))
1864 (defun company-pseudo-tooltip-show-at-point (pos)
1865 (let ((row (company--row pos))
1866 (col (company--column pos)))
1867 (company-pseudo-tooltip-show (1+ row) col company-selection)))
1869 (defun company-pseudo-tooltip-edit (selection)
1870 (let ((height (overlay-get company-pseudo-tooltip-overlay 'company-height)))
1871 (overlay-put company-pseudo-tooltip-overlay 'company-after
1872 (apply 'company--replacement-string
1873 (company--create-lines selection (abs height))
1874 (overlay-get company-pseudo-tooltip-overlay
1875 'company-replacement-args)))))
1877 (defun company-pseudo-tooltip-hide ()
1878 (when company-pseudo-tooltip-overlay
1879 (delete-overlay company-pseudo-tooltip-overlay)
1880 (setq company-pseudo-tooltip-overlay nil)))
1882 (defun company-pseudo-tooltip-hide-temporarily ()
1883 (when (overlayp company-pseudo-tooltip-overlay)
1884 (overlay-put company-pseudo-tooltip-overlay 'invisible nil)
1885 (overlay-put company-pseudo-tooltip-overlay 'line-prefix nil)
1886 (overlay-put company-pseudo-tooltip-overlay 'after-string nil)))
1888 (defun company-pseudo-tooltip-unhide ()
1889 (when company-pseudo-tooltip-overlay
1890 (overlay-put company-pseudo-tooltip-overlay 'invisible t)
1891 ;; Beat outline's folding overlays, at least.
1892 (overlay-put company-pseudo-tooltip-overlay 'priority 1)
1893 ;; No (extra) prefix for the first line.
1894 (overlay-put company-pseudo-tooltip-overlay 'line-prefix "")
1895 (overlay-put company-pseudo-tooltip-overlay 'after-string
1896 (overlay-get company-pseudo-tooltip-overlay 'company-after))
1897 (overlay-put company-pseudo-tooltip-overlay 'window (selected-window))))
1899 (defun company-pseudo-tooltip-guard ()
1900 (buffer-substring-no-properties
1901 (point) (overlay-start company-pseudo-tooltip-overlay)))
1903 (defun company-pseudo-tooltip-frontend (command)
1904 "`company-mode' front-end similar to a tooltip but based on overlays."
1906 (pre-command (company-pseudo-tooltip-hide-temporarily))
1908 (let ((old-height (if (overlayp company-pseudo-tooltip-overlay)
1909 (overlay-get company-pseudo-tooltip-overlay
1912 (new-height (company--pseudo-tooltip-height)))
1913 (unless (and (>= (* old-height new-height) 0)
1914 (>= (abs old-height) (abs new-height))
1915 (equal (company-pseudo-tooltip-guard)
1916 (overlay-get company-pseudo-tooltip-overlay
1919 (company-pseudo-tooltip-show-at-point (- (point)
1920 (length company-prefix)))
1921 (overlay-put company-pseudo-tooltip-overlay
1922 'company-guard (company-pseudo-tooltip-guard))))
1923 (company-pseudo-tooltip-unhide))
1924 (hide (company-pseudo-tooltip-hide)
1925 (setq company-tooltip-offset 0))
1926 (update (when (overlayp company-pseudo-tooltip-overlay)
1927 (company-pseudo-tooltip-edit company-selection)))))
1929 (defun company-pseudo-tooltip-unless-just-one-frontend (command)
1930 "`company-pseudo-tooltip-frontend', but not shown for single candidates."
1931 (unless (and (eq command 'post-command)
1932 (not (cdr company-candidates)))
1933 (company-pseudo-tooltip-frontend command)))
1935 ;;; overlay ;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;
1937 (defvar company-preview-overlay nil)
1938 (make-variable-buffer-local 'company-preview-overlay)
1940 (defun company-preview-show-at-point (pos)
1941 (company-preview-hide)
1943 (setq company-preview-overlay (make-overlay pos pos))
1945 (let ((completion(nth company-selection company-candidates)))
1946 (setq completion (propertize completion 'face 'company-preview))
1947 (add-text-properties 0 (length company-common)
1948 '(face company-preview-common) completion)
1950 ;; Add search string
1951 (and company-search-string
1952 (string-match (regexp-quote company-search-string) completion)
1953 (add-text-properties (match-beginning 0)
1955 '(face company-preview-search)
1958 (setq completion (company-strip-prefix completion))
1960 (and (equal pos (point))
1961 (not (equal completion ""))
1962 (add-text-properties 0 1 '(cursor t) completion))
1964 (overlay-put company-preview-overlay 'after-string completion)
1965 (overlay-put company-preview-overlay 'window (selected-window))))
1967 (defun company-preview-hide ()
1968 (when company-preview-overlay
1969 (delete-overlay company-preview-overlay)
1970 (setq company-preview-overlay nil)))
1972 (defun company-preview-frontend (command)
1973 "`company-mode' front-end showing the selection as if it had been inserted."
1975 (pre-command (company-preview-hide))
1976 (post-command (company-preview-show-at-point (point)))
1977 (hide (company-preview-hide))))
1979 (defun company-preview-if-just-one-frontend (command)
1980 "`company-preview-frontend', but only shown for single candidates."
1981 (unless (and (eq command 'post-command)
1982 (cdr company-candidates))
1983 (company-preview-frontend command)))
1985 ;;; echo ;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;
1987 (defvar company-echo-last-msg nil)
1988 (make-variable-buffer-local 'company-echo-last-msg)
1990 (defvar company-echo-timer nil)
1992 (defvar company-echo-delay .01)
1994 (defun company-echo-show (&optional getter)
1996 (setq company-echo-last-msg (funcall getter)))
1997 (let ((message-log-max nil))
1998 (if company-echo-last-msg
1999 (message "%s" company-echo-last-msg)
2002 (defun company-echo-show-soon (&optional getter)
2003 (when company-echo-timer
2004 (cancel-timer company-echo-timer))
2005 (setq company-echo-timer (run-with-timer 0 nil 'company-echo-show getter)))
2007 (defsubst company-echo-show-when-idle (&optional getter)
2008 (when (sit-for company-echo-delay)
2009 (company-echo-show getter)))
2011 (defun company-echo-format ()
2013 (let ((limit (window-width (minibuffer-window)))
2015 ;; Roll to selection.
2016 (candidates (nthcdr company-selection company-candidates))
2017 (i (if company-show-numbers company-selection 99999))
2021 (setq comp (company-reformat (pop candidates))
2022 len (+ len 1 (length comp)))
2026 (setq comp (propertize (format "%d: %s" i comp)
2027 'face 'company-echo))
2030 (add-text-properties 3 (+ 3 (length company-common))
2031 '(face company-echo-common) comp))
2032 (setq comp (propertize comp 'face 'company-echo))
2033 (add-text-properties 0 (length company-common)
2034 '(face company-echo-common) comp))
2036 (setq candidates nil)
2039 (mapconcat 'identity (nreverse msg) " ")))
2041 (defun company-echo-strip-common-format ()
2043 (let ((limit (window-width (minibuffer-window)))
2044 (len (+ (length company-prefix) 2))
2045 ;; Roll to selection.
2046 (candidates (nthcdr company-selection company-candidates))
2047 (i (if company-show-numbers company-selection 99999))
2051 (setq comp (company-strip-prefix (pop candidates))
2052 len (+ len 2 (length comp)))
2055 (setq comp (format "%s (%d)" comp i))
2059 (setq candidates nil)
2060 (push (propertize comp 'face 'company-echo) msg)))
2062 (concat (propertize company-prefix 'face 'company-echo-common) "{"
2063 (mapconcat 'identity (nreverse msg) ", ")
2066 (defun company-echo-hide ()
2067 (unless (equal company-echo-last-msg "")
2068 (setq company-echo-last-msg "")
2069 (company-echo-show)))
2071 (defun company-echo-frontend (command)
2072 "`company-mode' front-end showing the candidates in the echo area."
2074 (post-command (company-echo-show-soon 'company-echo-format))
2075 (hide (company-echo-hide))))
2077 (defun company-echo-strip-common-frontend (command)
2078 "`company-mode' front-end showing the candidates in the echo area."
2080 (post-command (company-echo-show-soon 'company-echo-strip-common-format))
2081 (hide (company-echo-hide))))
2083 (defun company-echo-metadata-frontend (command)
2084 "`company-mode' front-end showing the documentation in the echo area."
2086 (post-command (company-echo-show-when-idle 'company-fetch-metadata))
2087 (hide (company-echo-hide))))
2090 ;;; company.el ends here