1 ;;; company.el --- Modular text completion framework -*- lexical-binding: t -*-
3 ;; Copyright (C) 2009-2015 Free Software Foundation, Inc.
5 ;; Author: Nikolaj Schumacher
6 ;; Maintainer: Dmitry Gutov <dgutov@yandex.ru>
7 ;; URL: http://company-mode.github.io/
9 ;; Keywords: abbrev, convenience, matching
10 ;; Package-Requires: ((emacs "24.1") (cl-lib "0.5"))
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 backends, modules for displaying them are frontends.
32 ;; Company comes with many backends, e.g. `company-elisp'. These are
33 ;; distributed in separate files and can be used individually.
35 ;; Place company.el and the backends 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 backend, 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 backend, 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 backends together, for example to
58 ;; enrich gtags with dabbrev-code results (to emulate local variables).
59 ;; To do this, add a list with both backends as an element in company-backends.
63 ;; See NEWS.md in the repository.
70 ;; FIXME: Use `user-error'.
71 (add-to-list 'debug-ignored-errors "^.* frontend cannot be used twice$")
72 (add-to-list 'debug-ignored-errors "^Echo area cannot be used twice$")
73 (add-to-list 'debug-ignored-errors "^No \\(document\\|loc\\)ation available$")
74 (add-to-list 'debug-ignored-errors "^Company not ")
75 (add-to-list 'debug-ignored-errors "^No candidate number ")
76 (add-to-list 'debug-ignored-errors "^Cannot complete at point$")
77 (add-to-list 'debug-ignored-errors "^No other backend$")
81 ;; `defvar-local' for Emacs 24.2 and below
82 (unless (fboundp 'defvar-local)
83 (defmacro defvar-local (var val &optional docstring)
84 "Define VAR as a buffer-local variable with default value VAL.
85 Like `defvar' but additionally marks the variable as being automatically
86 buffer-local wherever it is set."
87 (declare (debug defvar) (doc-string 3))
89 (defvar ,var ,val ,docstring)
90 (make-variable-buffer-local ',var)))))
93 "Extensible inline text completion mechanism"
98 (defface company-tooltip
99 '((default :foreground "black")
100 (((class color) (min-colors 88) (background light))
101 (:background "cornsilk"))
102 (((class color) (min-colors 88) (background dark))
103 (:background "yellow")))
104 "Face used for the tooltip.")
106 (defface company-tooltip-selection
107 '((default :inherit company-tooltip)
108 (((class color) (min-colors 88) (background light))
109 (:background "light blue"))
110 (((class color) (min-colors 88) (background dark))
111 (:background "orange1"))
112 (t (:background "green")))
113 "Face used for the selection in the tooltip.")
115 (defface company-tooltip-search
116 '((default :inherit company-tooltip-selection))
117 "Face used for the search string in the tooltip.")
119 (defface company-tooltip-mouse
120 '((default :inherit highlight))
121 "Face used for the tooltip item under the mouse.")
123 (defface company-tooltip-common
124 '((default :inherit company-tooltip)
125 (((background light))
126 :foreground "darkred")
129 "Face used for the common completion in the tooltip.")
131 (defface company-tooltip-common-selection
132 '((default :inherit company-tooltip-selection)
133 (((background light))
134 :foreground "darkred")
137 "Face used for the selected common completion in the tooltip.")
139 (defface company-tooltip-annotation
140 '((default :inherit company-tooltip)
141 (((background light))
142 :foreground "firebrick4")
145 "Face used for the annotation in the tooltip.")
147 (defface company-scrollbar-fg
148 '((((background light))
149 :background "darkred")
152 "Face used for the tooltip scrollbar thumb.")
154 (defface company-scrollbar-bg
155 '((default :inherit company-tooltip)
156 (((background light))
160 "Face used for the tooltip scrollbar background.")
162 (defface company-preview
163 '((((background light))
164 :inherit company-tooltip-selection)
167 :foreground "wheat"))
168 "Face used for the completion preview.")
170 (defface company-preview-common
171 '((((background light))
172 :inherit company-tooltip-selection)
174 :inherit company-preview
176 "Face used for the common part of the completion preview.")
178 (defface company-preview-search
179 '((((background light))
180 :inherit company-tooltip-common-selection)
182 :inherit company-preview
183 :background "blue1"))
184 "Face used for the search string in the completion preview.")
186 (defface company-echo nil
187 "Face used for completions in the echo area.")
189 (defface company-echo-common
190 '((((background dark)) (:foreground "firebrick1"))
191 (((background light)) (:background "firebrick4")))
192 "Face used for the common part of completions in the echo area.")
194 (defun company-frontends-set (variable value)
196 (let ((value (delete-dups (copy-sequence value))))
197 (and (memq 'company-pseudo-tooltip-unless-just-one-frontend value)
198 (memq 'company-pseudo-tooltip-frontend value)
199 (error "Pseudo tooltip frontend cannot be used twice"))
200 (and (memq 'company-preview-if-just-one-frontend value)
201 (memq 'company-preview-frontend value)
202 (error "Preview frontend cannot be used twice"))
203 (and (memq 'company-echo value)
204 (memq 'company-echo-metadata-frontend value)
205 (error "Echo area cannot be used twice"))
206 ;; Preview must come last.
207 (dolist (f '(company-preview-if-just-one-frontend company-preview-frontend))
208 (when (cdr (memq f value))
209 (setq value (append (delq f value) (list f)))))
210 (set variable value)))
212 (defcustom company-frontends '(company-pseudo-tooltip-unless-just-one-frontend
213 company-preview-if-just-one-frontend
214 company-echo-metadata-frontend)
215 "The list of active frontends (visualizations).
216 Each frontend is a function that takes one argument. It is called with
217 one of the following arguments:
219 `show': When the visualization should start.
221 `hide': When the visualization should end.
223 `update': When the data has been updated.
225 `pre-command': Before every command that is executed while the
226 visualization is active.
228 `post-command': After every command that is executed while the
229 visualization is active.
231 The visualized data is stored in `company-prefix', `company-candidates',
232 `company-common', `company-selection', `company-point' and
233 `company-search-string'."
234 :set 'company-frontends-set
235 :type '(repeat (choice (const :tag "echo" company-echo-frontend)
236 (const :tag "echo, strip common"
237 company-echo-strip-common-frontend)
238 (const :tag "show echo meta-data in echo"
239 company-echo-metadata-frontend)
240 (const :tag "pseudo tooltip"
241 company-pseudo-tooltip-frontend)
242 (const :tag "pseudo tooltip, multiple only"
243 company-pseudo-tooltip-unless-just-one-frontend)
244 (const :tag "preview" company-preview-frontend)
245 (const :tag "preview, unique only"
246 company-preview-if-just-one-frontend)
247 (function :tag "custom function" nil))))
249 (defcustom company-tooltip-limit 10
250 "The maximum number of candidates in the tooltip."
253 (defcustom company-tooltip-minimum 6
254 "The minimum height of the tooltip.
255 If this many lines are not available, prefer to display the tooltip above."
258 (defcustom company-tooltip-minimum-width 0
259 "The minimum width of the tooltip's inner area.
260 This doesn't include the margins and the scroll bar."
262 :package-version '(company . "0.8.0"))
264 (defcustom company-tooltip-margin 1
265 "Width of margin columns to show around the toolip."
268 (defcustom company-tooltip-offset-display 'scrollbar
269 "Method using which the tooltip displays scrolling position.
270 `scrollbar' means draw a scrollbar to the right of the items.
271 `lines' means wrap items in lines with \"before\" and \"after\" counters."
272 :type '(choice (const :tag "Scrollbar" scrollbar)
273 (const :tag "Two lines" lines)))
275 (defcustom company-tooltip-align-annotations nil
276 "When non-nil, align annotations to the right tooltip border."
278 :package-version '(company . "0.7.1"))
280 (defcustom company-tooltip-flip-when-above nil
281 "Whether to flip the tooltip when it's above the current line."
283 :package-version '(company . "0.8.1"))
285 (defvar company-safe-backends
286 '((company-abbrev . "Abbrev")
287 (company-bbdb . "BBDB")
288 (company-capf . "completion-at-point-functions")
289 (company-clang . "Clang")
290 (company-cmake . "CMake")
291 (company-css . "CSS")
292 (company-dabbrev . "dabbrev for plain text")
293 (company-dabbrev-code . "dabbrev for code")
294 (company-eclim . "Eclim (an Eclipse interface)")
295 (company-elisp . "Emacs Lisp")
296 (company-etags . "etags")
297 (company-files . "Files")
298 (company-gtags . "GNU Global")
299 (company-ispell . "Ispell")
300 (company-keywords . "Programming language keywords")
301 (company-nxml . "nxml")
302 (company-oddmuse . "Oddmuse")
303 (company-semantic . "Semantic")
304 (company-tempo . "Tempo templates")
305 (company-xcode . "Xcode")))
306 (put 'company-safe-backends 'risky-local-variable t)
308 (defun company-safe-backends-p (backends)
309 (and (consp backends)
310 (not (cl-dolist (backend backends)
311 (unless (if (consp backend)
312 (company-safe-backends-p backend)
313 (assq backend company-safe-backends))
316 (defcustom company-backends `(,@(unless (version< "24.3.51" emacs-version)
317 (list 'company-elisp))
319 company-nxml company-css
320 company-eclim company-semantic company-clang
321 company-xcode company-cmake
323 (company-dabbrev-code company-gtags company-etags
325 company-oddmuse company-files company-dabbrev)
326 "The list of active backends (completion engines).
328 Only one backend is used at a time. The choice depends on the order of
329 the items in this list, and on the values they return in response to the
330 `prefix' command (see below). But a backend can also be a \"grouped\"
333 `company-begin-backend' can be used to start a specific backend,
334 `company-other-backend' will skip to the next matching backend in the list.
336 Each backend is a function that takes a variable number of arguments.
337 The first argument is the command requested from the backend. It is one
340 `prefix': The backend should return the text to be completed. It must be
341 text immediately before point. Returning nil from this command passes
342 control to the next backend. The function should return `stop' if it
343 should complete but cannot (e.g. if it is in the middle of a string).
344 Instead of a string, the backend may return a cons where car is the prefix
345 and cdr is used instead of the actual prefix length in the comparison
346 against `company-minimum-prefix-length'. It must be either number or t,
347 and in the latter case the test automatically succeeds.
349 `candidates': The second argument is the prefix to be completed. The
350 return value should be a list of candidates that match the prefix.
352 Non-prefix matches are also supported (candidates that don't start with the
353 prefix, but match it in some backend-defined way). Backends that use this
354 feature must disable cache (return t to `no-cache') and might also want to
359 `sorted': Return t here to indicate that the candidates are sorted and will
360 not need to be sorted again.
362 `duplicates': If non-nil, company will take care of removing duplicates
365 `no-cache': Usually company doesn't ask for candidates again as completion
366 progresses, unless the backend returns t for this command. The second
367 argument is the latest prefix.
369 `ignore-case': Return t here if the backend returns case-insensitive
370 matches. This value is used to determine the longest common prefix (as
371 used in `company-complete-common'), and to filter completions when fetching
374 `meta': The second argument is a completion candidate. Return a (short)
375 documentation string for it.
377 `doc-buffer': The second argument is a completion candidate. Return a
378 buffer with documentation for it. Preferably use `company-doc-buffer'. If
379 not all buffer contents pertain to this candidate, return a cons of buffer
380 and window start position.
382 `location': The second argument is a completion candidate. Return a cons
383 of buffer and buffer location, or of file and line number where the
384 completion candidate was defined.
386 `annotation': The second argument is a completion candidate. Return a
387 string to be displayed inline with the candidate in the popup. If
388 duplicates are removed by company, candidates with equal string values will
389 be kept if they have different annotations. For that to work properly,
390 backends should store the related information on candidates using text
393 `match': The second argument is a completion candidate. Return the index
394 after the end of text matching `prefix' within the candidate string. It
395 will be used when rendering the popup. This command only makes sense for
396 backends that provide non-prefix completion.
398 `require-match': If this returns t, the user is not allowed to enter
399 anything not offered as a candidate. Please don't use that value in normal
400 backends. The default value nil gives the user that choice with
401 `company-require-match'. Return value `never' overrides that option the
404 `init': Called once for each buffer. The backend can check for external
405 programs and files and load any required libraries. Raising an error here
406 will show up in message log once, and the backend will not be used for
409 `post-completion': Called after a completion candidate has been inserted
410 into the buffer. The second argument is the candidate. Can be used to
411 modify it, e.g. to expand a snippet.
413 The backend should return nil for all commands it does not support or
414 does not know about. It should also be callable interactively and use
415 `company-begin-backend' to start itself in that case.
419 An element of `company-backends' can also itself be a list of backends,
420 then it's considered to be a \"grouped\" backend.
422 When possible, commands taking a candidate as an argument are dispatched to
423 the backend it came from. In other cases, the first non-nil value among
424 all the backends is returned.
426 The latter is the case for the `prefix' command. But if the group contains
427 the keyword `:with', the backends after it are ignored for this command.
429 The completions from backends in a group are merged (but only from those
430 that return the same `prefix').
432 Asynchronous backends:
434 The return value of each command can also be a cons (:async . FETCHER)
435 where FETCHER is a function of one argument, CALLBACK. When the data
436 arrives, FETCHER must call CALLBACK and pass it the appropriate return
437 value, as described above.
439 True asynchronous operation is only supported for command `candidates', and
440 only during idle completion. Other commands will block the user interface,
441 even if the backend uses the asynchronous calling convention."
445 ,@(mapcar (lambda (b) `(const :tag ,(cdr b) ,(car b)))
446 company-safe-backends)
447 (symbol :tag "User defined")
448 (repeat :tag "Merged backends"
449 (choice :tag "backend"
450 ,@(mapcar (lambda (b)
451 `(const :tag ,(cdr b) ,(car b)))
452 company-safe-backends)
453 (const :tag "With" :with)
454 (symbol :tag "User defined"))))))
456 (put 'company-backends 'safe-local-variable 'company-safe-backends-p)
458 (defcustom company-transformers nil
459 "Functions to change the list of candidates received from backends.
461 Each function gets called with the return value of the previous one.
462 The first one gets passed the list of candidates, already sorted and
465 (const :tag "None" nil)
466 (const :tag "Sort by occurrence" (company-sort-by-occurrence))
467 (const :tag "Sort by backend importance"
468 (company-sort-by-backend-importance))
469 (repeat :tag "User defined" (function))))
471 (defcustom company-completion-started-hook nil
472 "Hook run when company starts completing.
473 The hook is called with one argument that is non-nil if the completion was
477 (defcustom company-completion-cancelled-hook nil
478 "Hook run when company cancels completing.
479 The hook is called with one argument that is non-nil if the completion was
483 (defcustom company-completion-finished-hook nil
484 "Hook run when company successfully completes.
485 The hook is called with the selected candidate as an argument.
487 If you indend to use it to post-process candidates from a specific
488 backend, consider using the `post-completion' command instead."
491 (defcustom company-minimum-prefix-length 3
492 "The minimum prefix length for idle completion."
493 :type '(integer :tag "prefix length"))
495 (defcustom company-abort-manual-when-too-short nil
496 "If enabled, cancel a manually started completion when the prefix gets
497 shorter than both `company-minimum-prefix-length' and the length of the
498 prefix it was started from."
500 :package-version '(company . "0.8.0"))
502 (defcustom company-require-match 'company-explicit-action-p
503 "If enabled, disallow non-matching input.
504 This can be a function do determine if a match is required.
506 This can be overridden by the backend, if it returns t or `never' to
507 `require-match'. `company-auto-complete' also takes precedence over this."
508 :type '(choice (const :tag "Off" nil)
509 (function :tag "Predicate function")
510 (const :tag "On, if user interaction took place"
511 'company-explicit-action-p)
512 (const :tag "On" t)))
514 (defcustom company-auto-complete nil
515 "Determines when to auto-complete.
516 If this is enabled, all characters from `company-auto-complete-chars'
517 trigger insertion of the selected completion candidate.
518 This can also be a function."
519 :type '(choice (const :tag "Off" nil)
520 (function :tag "Predicate function")
521 (const :tag "On, if user interaction took place"
522 'company-explicit-action-p)
523 (const :tag "On" t)))
525 (defcustom company-auto-complete-chars '(?\ ?\) ?.)
526 "Determines which characters trigger auto-completion.
527 See `company-auto-complete'. If this is a string, each string character
528 tiggers auto-completion. If it is a list of syntax description characters (see
529 `modify-syntax-entry'), all characters with that syntax auto-complete.
531 This can also be a function, which is called with the new input and should
532 return non-nil if company should auto-complete.
534 A character that is part of a valid candidate never triggers auto-completion."
535 :type '(choice (string :tag "Characters")
537 (const :tag "Whitespace" ?\ )
538 (const :tag "Symbol" ?_)
539 (const :tag "Opening parentheses" ?\()
540 (const :tag "Closing parentheses" ?\))
541 (const :tag "Word constituent" ?w)
542 (const :tag "Punctuation." ?.)
543 (const :tag "String quote." ?\")
544 (const :tag "Paired delimiter." ?$)
545 (const :tag "Expression quote or prefix operator." ?\')
546 (const :tag "Comment starter." ?<)
547 (const :tag "Comment ender." ?>)
548 (const :tag "Character-quote." ?/)
549 (const :tag "Generic string fence." ?|)
550 (const :tag "Generic comment fence." ?!))
551 (function :tag "Predicate function")))
553 (defcustom company-idle-delay .5
554 "The idle delay in seconds until completion starts automatically.
555 The prefix still has to satisfy `company-minimum-prefix-length' before that
556 happens. The value of nil means no idle completion."
557 :type '(choice (const :tag "never (nil)" nil)
558 (const :tag "immediate (0)" 0)
559 (number :tag "seconds")))
561 (defcustom company-begin-commands '(self-insert-command
562 org-self-insert-command
563 orgtbl-self-insert-command
568 "A list of commands after which idle completion is allowed.
569 If this is t, it can show completions after any command except a few from a
570 pre-defined list. See `company-idle-delay'.
572 Alternatively, any command with a non-nil `company-begin' property is
573 treated as if it was on this list."
574 :type '(choice (const :tag "Any command" t)
575 (const :tag "Self insert command" '(self-insert-command))
576 (repeat :tag "Commands" function))
577 :package-version '(company . "0.8.4"))
579 (defcustom company-continue-commands '(not save-buffer save-some-buffers
580 save-buffers-kill-terminal
581 save-buffers-kill-emacs)
582 "A list of commands that are allowed during completion.
583 If this is t, or if `company-begin-commands' is t, any command is allowed.
584 Otherwise, the value must be a list of symbols. If it starts with `not',
585 the cdr is the list of commands that abort completion. Otherwise, all
586 commands except those in that list, or in `company-begin-commands', or
587 commands in the `company-' namespace, abort completion."
588 :type '(choice (const :tag "Any command" t)
589 (cons :tag "Any except"
591 (repeat :tag "Commands" function))
592 (repeat :tag "Commands" function)))
594 (defcustom company-show-numbers nil
595 "If enabled, show quick-access numbers for the first ten candidates."
596 :type '(choice (const :tag "off" nil)
597 (const :tag "on" t)))
599 (defcustom company-selection-wrap-around nil
600 "If enabled, selecting item before first or after last wraps around."
601 :type '(choice (const :tag "off" nil)
602 (const :tag "on" t)))
604 (defvar company-async-wait 0.03
605 "Pause between checks to see if the value's been set when turning an
606 asynchronous call into synchronous.")
608 (defvar company-async-timeout 2
609 "Maximum wait time for a value to be set during asynchronous call.")
611 ;;; mode ;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;
613 (defvar company-mode-map (make-sparse-keymap)
614 "Keymap used by `company-mode'.")
616 (defvar company-active-map
617 (let ((keymap (make-sparse-keymap)))
618 (define-key keymap "\e\e\e" 'company-abort)
619 (define-key keymap "\C-g" 'company-abort)
620 (define-key keymap (kbd "M-n") 'company-select-next)
621 (define-key keymap (kbd "M-p") 'company-select-previous)
622 (define-key keymap (kbd "<down>") 'company-select-next-or-abort)
623 (define-key keymap (kbd "<up>") 'company-select-previous-or-abort)
624 (define-key keymap [remap scroll-up-command] 'company-next-page)
625 (define-key keymap [remap scroll-down-command] 'company-previous-page)
626 (define-key keymap [down-mouse-1] 'ignore)
627 (define-key keymap [down-mouse-3] 'ignore)
628 (define-key keymap [mouse-1] 'company-complete-mouse)
629 (define-key keymap [mouse-3] 'company-select-mouse)
630 (define-key keymap [up-mouse-1] 'ignore)
631 (define-key keymap [up-mouse-3] 'ignore)
632 (define-key keymap [return] 'company-complete-selection)
633 (define-key keymap (kbd "RET") 'company-complete-selection)
634 (define-key keymap [tab] 'company-complete-common)
635 (define-key keymap (kbd "TAB") 'company-complete-common)
636 (define-key keymap (kbd "<f1>") 'company-show-doc-buffer)
637 (define-key keymap (kbd "C-h") 'company-show-doc-buffer)
638 (define-key keymap "\C-w" 'company-show-location)
639 (define-key keymap "\C-s" 'company-search-candidates)
640 (define-key keymap "\C-\M-s" 'company-filter-candidates)
642 (define-key keymap (read-kbd-macro (format "M-%d" i)) 'company-complete-number))
644 "Keymap that is enabled during an active completion.")
646 (defvar company--disabled-backends nil)
648 (defun company-init-backend (backend)
649 (and (symbolp backend)
650 (not (fboundp backend))
651 (ignore-errors (require backend nil t)))
656 (funcall backend 'init)
657 (put backend 'company-init t))
659 (put backend 'company-init 'failed)
660 (unless (memq backend company--disabled-backends)
661 (message "Company backend '%s' could not be initialized:\n%s"
662 backend (error-message-string err)))
663 (cl-pushnew backend company--disabled-backends)
665 ;; No initialization for lambdas.
666 ((functionp backend) t)
667 (t ;; Must be a list.
668 (cl-dolist (b backend)
670 (company-init-backend b))))))
672 (defcustom company-lighter-base "company"
673 "Base string to use for the `company-mode' lighter."
675 :package-version '(company . "0.8.10"))
677 (defvar company-lighter '(" "
680 (if (consp company-backend)
681 (company--group-lighter (nth company-selection
683 company-lighter-base)
684 (symbol-name company-backend)))
685 company-lighter-base))
686 "Mode line lighter for Company.
688 The value of this variable is a mode line template as in
689 `mode-line-format'.")
691 (put 'company-lighter 'risky-local-variable t)
694 (define-minor-mode company-mode
695 "\"complete anything\"; is an in-buffer completion framework.
696 Completion starts automatically, depending on the values
697 `company-idle-delay' and `company-minimum-prefix-length'.
699 Completion can be controlled with the commands:
700 `company-complete-common', `company-complete-selection', `company-complete',
701 `company-select-next', `company-select-previous'. If these commands are
702 called before `company-idle-delay', completion will also start.
704 Completions can be searched with `company-search-candidates' or
705 `company-filter-candidates'. These can be used while completion is
708 The completion data is retrieved using `company-backends' and displayed
709 using `company-frontends'. If you want to start a specific backend, call
710 it interactively or use `company-begin-backend'.
712 By default, the completions list is sorted alphabetically, unless the
713 backend chooses otherwise, or `company-transformers' changes it later.
715 regular keymap (`company-mode-map'):
718 keymap during active completions (`company-active-map'):
720 \\{company-active-map}"
721 nil company-lighter company-mode-map
724 (when (eq company-idle-delay t)
725 (setq company-idle-delay 0)
726 (warn "Setting `company-idle-delay' to t is deprecated. Set it to 0 instead."))
727 (add-hook 'pre-command-hook 'company-pre-command nil t)
728 (add-hook 'post-command-hook 'company-post-command nil t)
729 (mapc 'company-init-backend company-backends))
730 (remove-hook 'pre-command-hook 'company-pre-command t)
731 (remove-hook 'post-command-hook 'company-post-command t)
733 (kill-local-variable 'company-point)))
735 (defcustom company-global-modes t
736 "Modes for which `company-mode' mode is turned on by `global-company-mode'.
737 If nil, means no modes. If t, then all major modes have it turned on.
738 If a list, it should be a list of `major-mode' symbol names for which
739 `company-mode' should be automatically turned on. The sense of the list is
740 negated if it begins with `not'. For example:
742 means that `company-mode' is turned on for buffers in C and C++ modes only.
744 means that `company-mode' is always turned on except in `message-mode' buffers."
745 :type '(choice (const :tag "none" nil)
747 (set :menu-tag "mode specific" :tag "modes"
749 (const :tag "Except" not)
750 (repeat :inline t (symbol :tag "mode")))))
753 (define-globalized-minor-mode global-company-mode company-mode company-mode-on)
755 (defun company-mode-on ()
756 (when (and (not (or noninteractive (eq (aref (buffer-name) 0) ?\s)))
757 (cond ((eq company-global-modes t)
759 ((eq (car-safe company-global-modes) 'not)
760 (not (memq major-mode (cdr company-global-modes))))
761 (t (memq major-mode company-global-modes))))
764 (defsubst company-assert-enabled ()
766 (company-uninstall-map)
767 (error "Company not enabled")))
769 ;;; keymaps ;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;
771 (defvar-local company-my-keymap nil)
773 (defvar company-emulation-alist '((t . nil)))
775 (defsubst company-enable-overriding-keymap (keymap)
776 (company-uninstall-map)
777 (setq company-my-keymap keymap))
779 (defun company-ensure-emulation-alist ()
780 (unless (eq 'company-emulation-alist (car emulation-mode-map-alists))
781 (setq emulation-mode-map-alists
782 (cons 'company-emulation-alist
783 (delq 'company-emulation-alist emulation-mode-map-alists)))))
785 (defun company-install-map ()
786 (unless (or (cdar company-emulation-alist)
787 (null company-my-keymap))
788 (setf (cdar company-emulation-alist) company-my-keymap)))
790 (defun company-uninstall-map ()
791 (setf (cdar company-emulation-alist) nil))
794 ;; Emacs calculates the active keymaps before reading the event. That means we
795 ;; cannot change the keymap from a timer. So we send a bogus command.
796 ;; XXX: Even in Emacs 24.4, seems to be needed in the terminal.
797 (defun company-ignore ()
799 (setq this-command last-command))
801 (global-set-key '[company-dummy-event] 'company-ignore)
803 (defun company-input-noop ()
804 (push 'company-dummy-event unread-command-events))
806 (defun company--posn-col-row (posn)
807 (let ((col (car (posn-col-row posn)))
808 ;; `posn-col-row' doesn't work well with lines of different height.
809 ;; `posn-actual-col-row' doesn't handle multiple-width characters.
810 (row (cdr (posn-actual-col-row posn))))
811 (when (and header-line-format (version< emacs-version "24.3.93.3"))
812 ;; http://debbugs.gnu.org/18384
814 (cons (+ col (window-hscroll)) row)))
816 (defun company--col-row (&optional pos)
817 (company--posn-col-row (posn-at-point pos)))
819 (defun company--row (&optional pos)
820 (cdr (company--col-row pos)))
822 ;;; backends ;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;
824 (defvar-local company-backend nil)
826 (defun company-grab (regexp &optional expression limit)
827 (when (looking-back regexp limit)
828 (or (match-string-no-properties (or expression 0)) "")))
830 (defun company-grab-line (regexp &optional expression)
831 (company-grab regexp expression (point-at-bol)))
833 (defun company-grab-symbol ()
834 (if (looking-at "\\_>")
835 (buffer-substring (point) (save-excursion (skip-syntax-backward "w_")
837 (unless (and (char-after) (memq (char-syntax (char-after)) '(?w ?_)))
840 (defun company-grab-word ()
841 (if (looking-at "\\>")
842 (buffer-substring (point) (save-excursion (skip-syntax-backward "w")
844 (unless (and (char-after) (eq (char-syntax (char-after)) ?w))
847 (defun company-grab-symbol-cons (idle-begin-after-re &optional max-len)
848 (let ((symbol (company-grab-symbol)))
851 (forward-char (- (length symbol)))
852 (if (looking-back idle-begin-after-re (if max-len
854 (line-beginning-position)))
858 (defun company-in-string-or-comment ()
859 (let ((ppss (syntax-ppss)))
860 (or (car (setq ppss (nthcdr 3 ppss)))
861 (car (setq ppss (cdr ppss)))
864 (defun company-call-backend (&rest args)
865 (company--force-sync #'company-call-backend-raw args company-backend))
867 (defun company--force-sync (fun args backend)
868 (let ((value (apply fun args)))
869 (if (not (eq (car-safe value) :async))
872 (start (time-to-seconds)))
874 (lambda (result) (setq res result)))
875 (while (eq res 'trash)
876 (if (> (- (time-to-seconds) start) company-async-timeout)
877 (error "Company: backend %s async timeout with args %s"
879 (sleep-for company-async-wait)))
882 (defun company-call-backend-raw (&rest args)
883 (condition-case-unless-debug err
884 (if (functionp company-backend)
885 (apply company-backend args)
886 (apply #'company--multi-backend-adapter company-backend args))
887 (error (error "Company: backend %s error \"%s\" with args %s"
888 company-backend (error-message-string err) args))))
890 (defun company--multi-backend-adapter (backends command &rest args)
891 (let ((backends (cl-loop for b in backends
892 when (not (and (symbolp b)
893 (eq 'failed (get b 'company-init))))
896 (if (eq command 'prefix)
897 (butlast backends (length (member :with backends)))
898 (delq :with backends)))
901 (company--multi-backend-adapter-candidates backends (car args)))
904 ((or `prefix `ignore-case `no-cache `require-match)
906 (cl-dolist (backend backends)
907 (when (setq value (company--force-sync
908 backend (cons command args) backend))
909 (cl-return value)))))
911 (let ((arg (car args)))
912 (when (> (length arg) 0)
913 (let ((backend (or (get-text-property 0 'company-backend arg)
915 (apply backend command args))))))))
917 (defun company--multi-backend-adapter-candidates (backends prefix)
918 (let ((pairs (cl-loop for backend in (cdr backends)
919 when (equal (company--prefix-str
920 (funcall backend 'prefix))
922 collect (cons (funcall backend 'candidates prefix)
927 (propertize str 'company-backend b))
929 (when (equal (company--prefix-str (funcall (car backends) 'prefix)) prefix)
930 ;; Small perf optimization: don't tag the candidates received
931 ;; from the first backend in the group.
932 (push (cons (funcall (car backends) 'candidates prefix)
935 (company--merge-async pairs (lambda (values) (apply #'append values)))))
937 (defun company--merge-async (pairs merger)
938 (let ((async (cl-loop for pair in pairs
940 (eq :async (car-safe (car pair))))))
942 (funcall merger (cl-loop for (val . mapper) in pairs
943 collect (funcall mapper val)))
948 (pending (mapcar #'car pairs))
959 (this-finisher (lambda (res)
960 (setq pending (delq val pending))
961 (setcar cell (funcall mapper res))
962 (funcall finisher))))
963 (if (not (eq :async (car-safe val)))
964 (funcall this-finisher val)
965 (let ((fetcher (cdr val)))
966 (funcall fetcher this-finisher)))))))))))
968 (defun company--prefix-str (prefix)
969 (or (car-safe prefix) prefix))
971 ;;; completion mechanism ;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;
973 (defvar-local company-prefix nil)
975 (defvar-local company-candidates nil)
977 (defvar-local company-candidates-length nil)
979 (defvar-local company-candidates-cache nil)
981 (defvar-local company-candidates-predicate nil)
983 (defvar-local company-common nil)
985 (defvar-local company-selection 0)
987 (defvar-local company-selection-changed nil)
989 (defvar-local company--manual-action nil
990 "Non-nil, if manual completion took place.")
992 (defvar-local company--manual-prefix nil)
994 (defvar company--auto-completion nil
995 "Non-nil when current candidate is being inserted automatically.
996 Controlled by `company-auto-complete'.")
998 (defvar-local company--point-max nil)
1000 (defvar-local company-point nil)
1002 (defvar company-timer nil)
1004 (defsubst company-strip-prefix (str)
1005 (substring str (length company-prefix)))
1007 (defun company--insert-candidate (candidate)
1008 (when (> (length candidate) 0)
1009 (setq candidate (substring-no-properties candidate))
1010 ;; XXX: Return value we check here is subject to change.
1011 (if (eq (company-call-backend 'ignore-case) 'keep-prefix)
1012 (insert (company-strip-prefix candidate))
1013 (unless (equal company-prefix candidate)
1014 (delete-region (- (point) (length company-prefix)) (point))
1015 (insert candidate)))))
1017 (defmacro company-with-candidate-inserted (candidate &rest body)
1018 "Evaluate BODY with CANDIDATE temporarily inserted.
1019 This is a tool for backends that need candidates inserted before they
1020 can retrieve meta-data for them."
1021 (declare (indent 1))
1022 `(let ((inhibit-modification-hooks t)
1023 (inhibit-point-motion-hooks t)
1024 (modified-p (buffer-modified-p)))
1025 (company--insert-candidate ,candidate)
1028 (delete-region company-point (point))
1029 (set-buffer-modified-p modified-p))))
1031 (defun company-explicit-action-p ()
1032 "Return whether explicit completion action was taken by the user."
1033 (or company--manual-action
1034 company-selection-changed))
1036 (defun company-reformat (candidate)
1037 ;; company-ispell needs this, because the results are always lower-case
1038 ;; It's mory efficient to fix it only when they are displayed.
1039 ;; FIXME: Adopt the current text's capitalization instead?
1040 (if (eq (company-call-backend 'ignore-case) 'keep-prefix)
1041 (concat company-prefix (substring candidate (length company-prefix)))
1044 (defun company--should-complete ()
1045 (and (eq company-idle-delay 'now)
1046 (not (or buffer-read-only overriding-terminal-local-map
1047 overriding-local-map))
1048 ;; Check if in the middle of entering a key combination.
1049 (or (equal (this-command-keys-vector) [])
1050 (not (keymapp (key-binding (this-command-keys-vector)))))
1051 (not (and transient-mark-mode mark-active))))
1053 (defun company--should-continue ()
1054 (or (eq t company-begin-commands)
1055 (eq t company-continue-commands)
1056 (if (eq 'not (car company-continue-commands))
1057 (not (memq this-command (cdr company-continue-commands)))
1058 (or (memq this-command company-begin-commands)
1059 (memq this-command company-continue-commands)
1060 (and (symbolp this-command)
1061 (string-match-p "\\`company-" (symbol-name this-command)))))))
1063 (defun company-call-frontends (command)
1064 (dolist (frontend company-frontends)
1065 (condition-case-unless-debug err
1066 (funcall frontend command)
1067 (error (error "Company: frontend %s error \"%s\" on command %s"
1068 frontend (error-message-string err) command)))))
1070 (defun company-set-selection (selection &optional force-update)
1072 (if company-selection-wrap-around
1073 (mod selection company-candidates-length)
1074 (max 0 (min (1- company-candidates-length) selection))))
1075 (when (or force-update (not (equal selection company-selection)))
1076 (setq company-selection selection
1077 company-selection-changed t)
1078 (company-call-frontends 'update)))
1080 (defun company--group-lighter (candidate base)
1081 (let ((backend (or (get-text-property 0 'company-backend candidate)
1082 (car company-backend))))
1083 (when (and backend (symbolp backend))
1084 (let ((name (replace-regexp-in-string "company-\\|-company" ""
1085 (symbol-name backend))))
1086 (format "%s-<%s>" base name)))))
1088 (defun company-update-candidates (candidates)
1089 (setq company-candidates-length (length candidates))
1090 (if company-selection-changed
1091 ;; Try to restore the selection
1092 (let ((selected (nth company-selection company-candidates)))
1093 (setq company-selection 0
1094 company-candidates candidates)
1098 (let ((candidate (pop candidates)))
1099 (when (and (string= candidate selected)
1100 (equal (company-call-backend 'annotation candidate)
1101 (company-call-backend 'annotation selected)))
1103 (cl-incf company-selection))
1104 (setq company-selection 0
1105 company-selection-changed nil))))
1106 (setq company-selection 0
1107 company-candidates candidates))
1108 ;; Calculate common.
1109 (let ((completion-ignore-case (company-call-backend 'ignore-case)))
1110 ;; We want to support non-prefix completion, so filtering is the
1111 ;; responsibility of each respective backend, not ours.
1112 ;; On the other hand, we don't want to replace non-prefix input in
1113 ;; `company-complete-common', unless there's only one candidate.
1114 (setq company-common
1115 (if (cdr company-candidates)
1116 (let ((common (try-completion "" company-candidates)))
1117 (when (string-prefix-p company-prefix common
1118 completion-ignore-case)
1120 (car company-candidates)))))
1122 (defun company-calculate-candidates (prefix)
1123 (let ((candidates (cdr (assoc prefix company-candidates-cache)))
1124 (ignore-case (company-call-backend 'ignore-case)))
1126 (when company-candidates-cache
1127 (let ((len (length prefix))
1128 (completion-ignore-case ignore-case)
1130 (cl-dotimes (i (1+ len))
1131 (when (setq prev (cdr (assoc (substring prefix 0 (- len i))
1132 company-candidates-cache)))
1133 (setq candidates (all-completions prefix prev))
1136 ;; No cache match, call the backend.
1137 (setq candidates (company--preprocess-candidates
1138 (company--fetch-candidates prefix)))
1140 (push (cons prefix candidates) company-candidates-cache)))
1141 ;; Only now apply the predicate and transformers.
1142 (setq candidates (company--postprocess-candidates candidates))
1144 (if (or (cdr candidates)
1145 (not (eq t (compare-strings (car candidates) nil nil
1146 prefix nil nil ignore-case))))
1148 ;; Already completed and unique; don't start.
1151 (defun company--fetch-candidates (prefix)
1152 (let ((c (if company--manual-action
1153 (company-call-backend 'candidates prefix)
1154 (company-call-backend-raw 'candidates prefix)))
1156 (if (not (eq (car c) :async))
1158 (let ((buf (current-buffer))
1159 (win (selected-window))
1160 (tick (buffer-chars-modified-tick))
1162 (backend company-backend))
1165 (lambda (candidates)
1166 (if (not (and candidates (eq res 'done)))
1167 ;; There's no completions to display,
1168 ;; or the fetcher called us back right away.
1169 (setq res candidates)
1170 (setq company-backend backend
1171 company-candidates-cache
1173 (company--preprocess-candidates candidates))))
1174 (company-idle-begin buf win tick pt)))))
1175 ;; FIXME: Relying on the fact that the callers
1176 ;; will interpret nil as "do nothing" is shaky.
1177 ;; A throw-catch would be one possible improvement.
1179 (progn (setq res 'done) nil)))))
1181 (defun company--preprocess-candidates (candidates)
1182 (unless (company-call-backend 'sorted)
1183 (setq candidates (sort candidates 'string<)))
1184 (when (company-call-backend 'duplicates)
1185 (company--strip-duplicates candidates))
1188 (defun company--postprocess-candidates (candidates)
1189 (when (or company-candidates-predicate company-transformers)
1190 (setq candidates (copy-sequence candidates)))
1191 (when company-candidates-predicate
1192 (setq candidates (cl-delete-if-not company-candidates-predicate candidates)))
1193 (company--transform-candidates candidates))
1195 (defun company--strip-duplicates (candidates)
1196 (let ((c2 candidates)
1200 (let ((str (pop c2)))
1201 (while (let ((str2 (car c2)))
1202 (if (not (equal str str2))
1206 (when (eq annos 'unk)
1207 (setq annos (list (company-call-backend
1209 (let ((anno2 (company-call-backend
1211 (if (member anno2 annos)
1218 (defun company--transform-candidates (candidates)
1219 (let ((c candidates))
1220 (dolist (tr company-transformers)
1221 (setq c (funcall tr c)))
1224 (defcustom company-occurrence-weight-function
1225 #'company-occurrence-prefer-closest-above
1226 "Function to weigh matches in `company-sort-by-occurrence'.
1227 It's called with three arguments: cursor position, the beginning and the
1230 (const :tag "First above point, then below point"
1231 company-occurrence-prefer-closest-above)
1232 (const :tag "Prefer closest in any direction"
1233 company-occurrence-prefer-any-closest)))
1235 (defun company-occurrence-prefer-closest-above (pos match-beg match-end)
1236 "Give priority to the matches above point, then those below point."
1237 (if (< match-beg pos)
1239 (- match-beg (window-start))))
1241 (defun company-occurrence-prefer-any-closest (pos _match-beg match-end)
1242 "Give priority to the matches closest to the point."
1243 (abs (- pos match-end)))
1245 (defun company-sort-by-occurrence (candidates)
1246 "Sort CANDIDATES according to their occurrences.
1247 Searches for each in the currently visible part of the current buffer and
1248 prioritizes the matches according to `company-occurrence-weight-function'.
1249 The rest of the list is appended unchanged.
1250 Keywords and function definition names are ignored."
1251 (let* ((w-start (window-start))
1252 (w-end (window-end))
1253 (start-point (point))
1261 (while (search-forward candidate w-end t)
1262 (when (and (not (eq (point) start-point))
1264 (company--occurrence-predicate)))
1268 (funcall company-occurrence-weight-function
1276 (mapcar #'car (sort occurs (lambda (e1 e2) (<= (cdr e1) (cdr e2)))))
1279 (defun company--occurrence-predicate ()
1280 (let ((beg (match-beginning 0))
1281 (end (match-end 0)))
1284 (and (not (memq (get-text-property (1- (point)) 'face)
1285 '(font-lock-function-name-face
1286 font-lock-keyword-face)))
1287 (let ((prefix (company--prefix-str
1288 (company-call-backend 'prefix))))
1289 (and (stringp prefix)
1290 (= (length prefix) (- end beg))))))))
1292 (defun company-sort-by-backend-importance (candidates)
1293 "Sort CANDIDATES as two priority groups.
1294 If `company-backend' is a function, do nothing. If it's a list, move
1295 candidates from backends before keyword `:with' to the front. Candidates
1296 from the rest of the backends in the group, if any, will be left at the end."
1297 (if (functionp company-backend)
1299 (let ((low-priority (cdr (memq :with company-backend))))
1300 (if (null low-priority)
1305 (let ((b2 (get-text-property 0 'company-backend c2)))
1306 (and b2 (memq b2 low-priority)))
1307 (let ((b1 (get-text-property 0 'company-backend c1)))
1308 (or (not b1) (not (memq b1 low-priority)))))))))))
1310 (defun company-idle-begin (buf win tick pos)
1311 (and (eq buf (current-buffer))
1312 (eq win (selected-window))
1313 (eq tick (buffer-chars-modified-tick))
1315 (when (company-auto-begin)
1316 (company-input-noop)
1317 (let ((this-command 'company-idle-begin))
1318 (company-post-command)))))
1320 (defun company-auto-begin ()
1322 (not company-candidates)
1323 (let ((company-idle-delay 'now))
1324 (condition-case-unless-debug err
1327 ;; Return non-nil if active.
1329 (error (message "Company: An error occurred in auto-begin")
1330 (message "%s" (error-message-string err))
1332 (quit (company-cancel))))))
1334 (defun company-manual-begin ()
1336 (company-assert-enabled)
1337 (setq company--manual-action t)
1339 (let ((company-minimum-prefix-length 0))
1340 (or company-candidates
1341 (company-auto-begin)))
1342 (unless company-candidates
1343 (setq company--manual-action nil))))
1345 (defun company-other-backend (&optional backward)
1346 (interactive (list current-prefix-arg))
1347 (company-assert-enabled)
1348 (let* ((after (if company-backend
1349 (cdr (member company-backend company-backends))
1351 (before (cdr (member company-backend (reverse company-backends))))
1353 (append before (reverse after))
1354 (append after (reverse before)))))
1356 (cl-dolist (backend next)
1357 (when (ignore-errors (company-begin-backend backend))
1359 (unless company-candidates
1360 (error "No other backend")))
1362 (defun company-require-match-p ()
1363 (let ((backend-value (company-call-backend 'require-match)))
1364 (or (eq backend-value t)
1365 (and (not (eq backend-value 'never))
1366 (if (functionp company-require-match)
1367 (funcall company-require-match)
1368 (eq company-require-match t))))))
1370 (defun company-auto-complete-p (input)
1371 "Return non-nil, if input starts with punctuation or parentheses."
1372 (and (if (functionp company-auto-complete)
1373 (funcall company-auto-complete)
1374 company-auto-complete)
1375 (if (functionp company-auto-complete-chars)
1376 (funcall company-auto-complete-chars input)
1377 (if (consp company-auto-complete-chars)
1378 (memq (char-syntax (string-to-char input))
1379 company-auto-complete-chars)
1380 (string-match (substring input 0 1) company-auto-complete-chars)))))
1382 (defun company--incremental-p ()
1383 (and (> (point) company-point)
1384 (> (point-max) company--point-max)
1385 (not (eq this-command 'backward-delete-char-untabify))
1386 (equal (buffer-substring (- company-point (length company-prefix))
1390 (defun company--continue-failed (new-prefix)
1391 (let ((input (buffer-substring-no-properties (point) company-point)))
1393 ((company-auto-complete-p input)
1396 (goto-char company-point)
1397 (let ((company--auto-completion t))
1398 (company-complete-selection))
1400 ((and (or (not (company-require-match-p))
1401 ;; Don't require match if the new prefix
1402 ;; doesn't continue the old one, and the latter was a match.
1403 (not (stringp new-prefix))
1404 (<= (length new-prefix) (length company-prefix)))
1405 (member company-prefix company-candidates))
1406 ;; Last input was a success,
1407 ;; but we're treating it as an abort + input anyway,
1408 ;; like the `unique' case below.
1409 (company-cancel 'non-unique))
1410 ((company-require-match-p)
1411 ;; Wrong incremental input, but required match.
1412 (delete-char (- (length input)))
1414 (message "Matching input is required")
1416 (t (company-cancel)))))
1418 (defun company--good-prefix-p (prefix)
1419 (and (stringp (company--prefix-str prefix)) ;excludes 'stop
1420 (or (eq (cdr-safe prefix) t)
1421 (let ((len (or (cdr-safe prefix) (length prefix))))
1422 (if company--manual-prefix
1423 (or (not company-abort-manual-when-too-short)
1424 ;; Must not be less than minimum or initial length.
1425 (>= len (min company-minimum-prefix-length
1426 (length company--manual-prefix))))
1427 (>= len company-minimum-prefix-length))))))
1429 (defun company--continue ()
1430 (when (company-call-backend 'no-cache company-prefix)
1431 ;; Don't complete existing candidates, fetch new ones.
1432 (setq company-candidates-cache nil))
1433 (let* ((new-prefix (company-call-backend 'prefix))
1434 (c (when (and (company--good-prefix-p new-prefix)
1435 (setq new-prefix (company--prefix-str new-prefix))
1436 (= (- (point) (length new-prefix))
1437 (- company-point (length company-prefix))))
1438 (company-calculate-candidates new-prefix))))
1441 ;; t means complete/unique.
1442 ;; Handle it like completion was aborted, to differentiate from user
1443 ;; calling one of Company's commands to insert the candidate,
1444 ;; not to trigger template expansion, etc.
1445 (company-cancel 'unique))
1447 ;; incremental match
1448 (setq company-prefix new-prefix)
1449 (company-update-candidates c)
1451 ((not (company--incremental-p))
1453 (t (company--continue-failed new-prefix)))))
1455 (defun company--begin-new ()
1457 (cl-dolist (backend (if company-backend
1458 ;; prefer manual override
1459 (list company-backend)
1462 (if (or (symbolp backend)
1463 (functionp backend))
1464 (when (or (not (symbolp backend))
1465 (eq t (get backend 'company-init))
1466 (unless (get backend 'company-init)
1467 (company-init-backend backend)))
1468 (funcall backend 'prefix))
1469 (company--multi-backend-adapter backend 'prefix)))
1471 (when (company--good-prefix-p prefix)
1472 (setq company-prefix (company--prefix-str prefix)
1473 company-backend backend
1474 c (company-calculate-candidates company-prefix))
1477 (when company--manual-action
1478 (message "No completion found"))
1480 ;; t means complete/unique.
1481 ;; Run the hooks anyway, to e.g. clear the cache.
1482 (company-cancel 'unique)))
1483 (when company--manual-action
1484 (setq company--manual-prefix prefix))
1485 (company-update-candidates c)
1486 (run-hook-with-args 'company-completion-started-hook
1487 (company-explicit-action-p))
1488 (company-call-frontends 'show)))
1491 (defun company--perform ()
1492 (or (and company-candidates (company--continue))
1493 (and (company--should-complete) (company--begin-new)))
1494 (if (not company-candidates)
1495 (setq company-backend nil)
1496 (setq company-point (point)
1497 company--point-max (point-max))
1498 (company-ensure-emulation-alist)
1499 (company-enable-overriding-keymap company-active-map)
1500 (company-call-frontends 'update)))
1502 (defun company-cancel (&optional result)
1504 (when company-prefix
1505 (if (stringp result)
1507 (company-call-backend 'pre-completion result)
1508 (run-hook-with-args 'company-completion-finished-hook result)
1509 (company-call-backend 'post-completion result))
1510 (run-hook-with-args 'company-completion-cancelled-hook result)))
1511 (setq company-backend nil
1513 company-candidates nil
1514 company-candidates-length nil
1515 company-candidates-cache nil
1516 company-candidates-predicate nil
1519 company-selection-changed nil
1520 company--manual-action nil
1521 company--manual-prefix nil
1522 company--point-max nil
1525 (cancel-timer company-timer))
1526 (company-echo-cancel t)
1527 (company-search-mode 0)
1528 (company-call-frontends 'hide)
1529 (company-enable-overriding-keymap nil))
1530 ;; Make return value explicit.
1533 (defun company-abort ()
1535 (company-cancel 'abort))
1537 (defun company-finish (result)
1538 (company--insert-candidate result)
1539 (company-cancel result))
1541 (defsubst company-keep (command)
1542 (and (symbolp command) (get command 'company-keep)))
1544 (defun company-pre-command ()
1545 (unless (company-keep this-command)
1546 (condition-case-unless-debug err
1547 (when company-candidates
1548 (company-call-frontends 'pre-command)
1549 (unless (company--should-continue)
1551 (error (message "Company: An error occurred in pre-command")
1552 (message "%s" (error-message-string err))
1555 (cancel-timer company-timer)
1556 (setq company-timer nil))
1557 (company-echo-cancel t)
1558 (company-uninstall-map))
1560 (defun company-post-command ()
1561 (when (null this-command)
1562 ;; Happens when the user presses `C-g' while inside
1563 ;; `flyspell-post-command-hook', for example.
1564 ;; Or any other `post-command-hook' function that can call `sit-for',
1565 ;; or any quittable timer function.
1567 (setq this-command 'company-abort))
1568 (unless (company-keep this-command)
1569 (condition-case-unless-debug err
1571 (unless (equal (point) company-point)
1572 (let (company-idle-delay) ; Against misbehavior while debugging.
1573 (company--perform)))
1574 (if company-candidates
1575 (company-call-frontends 'post-command)
1576 (and (numberp company-idle-delay)
1577 (not defining-kbd-macro)
1578 (company--should-begin)
1580 (run-with-timer company-idle-delay nil
1582 (current-buffer) (selected-window)
1583 (buffer-chars-modified-tick) (point))))))
1584 (error (message "Company: An error occurred in post-command")
1585 (message "%s" (error-message-string err))
1587 (company-install-map))
1589 (defvar company--begin-inhibit-commands '(company-abort
1590 company-complete-mouse
1592 company-complete-common
1593 company-complete-selection
1594 company-complete-number)
1595 "List of commands after which idle completion is (still) disabled when
1596 `company-begin-commands' is t.")
1598 (defun company--should-begin ()
1599 (if (eq t company-begin-commands)
1600 (not (memq this-command company--begin-inhibit-commands))
1602 (memq this-command company-begin-commands)
1603 (and (symbolp this-command) (get this-command 'company-begin)))))
1605 ;;; search ;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;
1607 (defvar-local company-search-string "")
1609 (defvar company-search-lighter '(" "
1610 (company-search-filtering "Filter" "Search")
1612 company-search-string
1615 (defvar-local company-search-filtering nil
1616 "Non-nil to filter the completion candidates by the search string")
1618 (defvar-local company--search-old-selection 0)
1620 (defvar-local company--search-old-changed nil)
1622 (defun company--search (text lines)
1623 (let ((quoted (regexp-quote text))
1625 (cl-dolist (line lines)
1626 (when (string-match quoted line (length company-prefix))
1630 (defun company-search-keypad ()
1632 (let* ((name (symbol-name last-command-event))
1633 (last-command-event (aref name (1- (length name)))))
1634 (company-search-printing-char)))
1636 (defun company-search-printing-char ()
1638 (company--search-assert-enabled)
1639 (let ((ss (concat company-search-string (string last-command-event))))
1640 (when company-search-filtering
1641 (company--search-update-predicate ss))
1642 (company--search-update-string ss)))
1644 (defun company--search-update-predicate (&optional ss)
1645 (let* ((company-candidates-predicate
1646 (and (not (string= ss ""))
1647 company-search-filtering
1648 (lambda (candidate) (string-match ss candidate))))
1649 (cc (company-calculate-candidates company-prefix)))
1650 (unless cc (error "No match"))
1651 (company-update-candidates cc)))
1653 (defun company--search-update-string (new)
1654 (let* ((pos (company--search new (nthcdr company-selection company-candidates))))
1657 (setq company-search-string new)
1658 (company-set-selection (+ company-selection pos) t))))
1660 (defun company--search-assert-input ()
1661 (company--search-assert-enabled)
1662 (when (string= company-search-string "")
1663 (error "Empty search string")))
1665 (defun company-search-repeat-forward ()
1666 "Repeat the incremental search in completion candidates forward."
1668 (company--search-assert-input)
1669 (let ((pos (company--search company-search-string
1670 (cdr (nthcdr company-selection
1671 company-candidates)))))
1674 (company-set-selection (+ company-selection pos 1) t))))
1676 (defun company-search-repeat-backward ()
1677 "Repeat the incremental search in completion candidates backwards."
1679 (company--search-assert-input)
1680 (let ((pos (company--search company-search-string
1681 (nthcdr (- company-candidates-length
1683 (reverse company-candidates)))))
1686 (company-set-selection (- company-selection pos 1) t))))
1688 (defun company-search-toggle-filtering ()
1689 "Toggle `company-search-filtering'."
1691 (company--search-assert-enabled)
1692 (setq company-search-filtering (not company-search-filtering))
1693 (let ((ss company-search-string))
1694 (company--search-update-predicate ss)
1695 (company--search-update-string ss)))
1697 (defun company-search-abort ()
1698 "Abort searching the completion candidates."
1700 (company--search-assert-enabled)
1701 (company-search-mode 0)
1702 (company-set-selection company--search-old-selection t)
1703 (setq company-selection-changed company--search-old-changed))
1705 (defun company-search-other-char ()
1707 (company--search-assert-enabled)
1708 (company-search-mode 0)
1709 (company--unread-last-input))
1711 (defun company-search-delete-char ()
1713 (company--search-assert-enabled)
1714 (if (string= company-search-string "")
1716 (let ((ss (substring company-search-string 0 -1)))
1717 (when company-search-filtering
1718 (company--search-update-predicate ss))
1719 (company--search-update-string ss))))
1721 (defvar company-search-map
1723 (keymap (make-keymap)))
1724 (if (fboundp 'max-char)
1725 (set-char-table-range (nth 1 keymap) (cons #x100 (max-char))
1726 'company-search-printing-char)
1728 ;; obsolete in Emacs 23
1729 (let ((l (generic-character-list))
1730 (table (nth 1 keymap)))
1732 (set-char-table-default table (car l) 'company-search-printing-char)
1733 (setq l (cdr l))))))
1734 (define-key keymap [t] 'company-search-other-char)
1736 (define-key keymap (make-string 1 i) 'company-search-other-char)
1739 (define-key keymap (vector i) 'company-search-printing-char)
1742 (define-key keymap (read (format "[kp-%s]" i)) 'company-search-keypad))
1743 (let ((meta-map (make-sparse-keymap)))
1744 (define-key keymap (char-to-string meta-prefix-char) meta-map)
1745 (define-key keymap [escape] meta-map))
1746 (define-key keymap (vector meta-prefix-char t) 'company-search-other-char)
1747 (define-key keymap (kbd "M-n") 'company-select-next)
1748 (define-key keymap (kbd "M-p") 'company-select-previous)
1749 (define-key keymap (kbd "<down>") 'company-select-next-or-abort)
1750 (define-key keymap (kbd "<up>") 'company-select-previous-or-abort)
1751 (define-key keymap "\e\e\e" 'company-search-other-char)
1752 (define-key keymap [escape escape escape] 'company-search-other-char)
1753 (define-key keymap (kbd "DEL") 'company-search-delete-char)
1754 (define-key keymap [backspace] 'company-search-delete-char)
1755 (define-key keymap "\C-g" 'company-search-abort)
1756 (define-key keymap "\C-s" 'company-search-repeat-forward)
1757 (define-key keymap "\C-r" 'company-search-repeat-backward)
1758 (define-key keymap "\C-o" 'company-search-toggle-filtering)
1760 (define-key keymap (read-kbd-macro (format "M-%d" i)) 'company-complete-number))
1762 "Keymap used for incrementally searching the completion candidates.")
1764 (define-minor-mode company-search-mode
1765 "Search mode for completion candidates.
1766 Don't start this directly, use `company-search-candidates' or
1767 `company-filter-candidates'."
1768 nil company-search-lighter nil
1769 (if company-search-mode
1770 (if (company-manual-begin)
1772 (setq company--search-old-selection company-selection
1773 company--search-old-changed company-selection-changed)
1774 (company-call-frontends 'update)
1775 (company-enable-overriding-keymap company-search-map))
1776 (setq company-search-mode nil))
1777 (kill-local-variable 'company-search-string)
1778 (kill-local-variable 'company-search-filtering)
1779 (kill-local-variable 'company--search-old-selection)
1780 (kill-local-variable 'company--search-old-changed)
1781 (when company-backend
1782 (company--search-update-predicate "")
1783 (company-call-frontends 'update))
1784 (company-enable-overriding-keymap company-active-map)))
1786 (defun company--search-assert-enabled ()
1787 (company-assert-enabled)
1788 (unless company-search-mode
1789 (company-uninstall-map)
1790 (error "Company not in search mode")))
1792 (defun company-search-candidates ()
1793 "Start searching the completion candidates incrementally.
1795 \\<company-search-map>Search can be controlled with the commands:
1796 - `company-search-repeat-forward' (\\[company-search-repeat-forward])
1797 - `company-search-repeat-backward' (\\[company-search-repeat-backward])
1798 - `company-search-abort' (\\[company-search-abort])
1799 - `company-search-delete-char' (\\[company-search-delete-char])
1801 Regular characters are appended to the search string.
1803 The command `company-search-toggle-filtering' (\\[company-search-toggle-filtering])
1804 uses the search string to filter the completion candidates."
1806 (company-search-mode 1))
1808 (defvar company-filter-map
1809 (let ((keymap (make-keymap)))
1810 (define-key keymap [remap company-search-printing-char]
1811 'company-filter-printing-char)
1812 (set-keymap-parent keymap company-search-map)
1814 "Keymap used for incrementally searching the completion candidates.")
1816 (defun company-filter-candidates ()
1817 "Start filtering the completion candidates incrementally.
1818 This works the same way as `company-search-candidates' immediately
1819 followed by `company-search-toggle-filtering'."
1821 (company-search-mode 1)
1822 (setq company-search-filtering t))
1824 ;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;
1826 (defun company-select-next (&optional arg)
1827 "Select the next candidate in the list.
1829 With ARG, move by that many elements."
1831 (when (company-manual-begin)
1832 (company-set-selection (+ (or arg 1) company-selection))))
1834 (defun company-select-previous (&optional arg)
1835 "Select the previous candidate in the list.
1837 With ARG, move by that many elements."
1839 (company-select-next (if arg (- arg) -1)))
1841 (defun company-select-next-or-abort (&optional arg)
1842 "Select the next candidate if more than one, else abort
1843 and invoke the normal binding.
1845 With ARG, move by that many elements."
1847 (if (> company-candidates-length 1)
1848 (company-select-next arg)
1850 (company--unread-last-input)))
1852 (defun company-select-previous-or-abort (&optional arg)
1853 "Select the previous candidate if more than one, else abort
1854 and invoke the normal binding.
1856 With ARG, move by that many elements."
1858 (if (> company-candidates-length 1)
1859 (company-select-previous arg)
1861 (company--unread-last-input)))
1863 (defun company-next-page ()
1864 "Select the candidate one page further."
1866 (when (company-manual-begin)
1867 (company-set-selection (+ company-selection
1868 company-tooltip-limit))))
1870 (defun company-previous-page ()
1871 "Select the candidate one page earlier."
1873 (when (company-manual-begin)
1874 (company-set-selection (- company-selection
1875 company-tooltip-limit))))
1877 (defvar company-pseudo-tooltip-overlay)
1879 (defvar company-tooltip-offset)
1881 (defun company--inside-tooltip-p (event-col-row row height)
1882 (let* ((ovl company-pseudo-tooltip-overlay)
1883 (column (overlay-get ovl 'company-column))
1884 (width (overlay-get ovl 'company-width))
1885 (evt-col (car event-col-row))
1886 (evt-row (cdr event-col-row)))
1887 (and (>= evt-col column)
1888 (< evt-col (+ column width))
1890 (and (> evt-row row)
1891 (<= evt-row (+ row height) ))
1892 (and (< evt-row row)
1893 (>= evt-row (+ row height)))))))
1895 (defun company--event-col-row (event)
1896 (company--posn-col-row (event-start event)))
1898 (defun company-select-mouse (event)
1899 "Select the candidate picked by the mouse."
1901 (let ((event-col-row (company--event-col-row event))
1902 (ovl-row (company--row))
1903 (ovl-height (and company-pseudo-tooltip-overlay
1904 (min (overlay-get company-pseudo-tooltip-overlay
1906 company-candidates-length))))
1908 (company--inside-tooltip-p event-col-row ovl-row ovl-height))
1910 (company-set-selection (+ (cdr event-col-row)
1911 (1- company-tooltip-offset)
1912 (if (and (eq company-tooltip-offset-display 'lines)
1913 (not (zerop company-tooltip-offset)))
1916 (if (< ovl-height 0)
1921 (company--unread-last-input)
1924 (defun company-complete-mouse (event)
1925 "Insert the candidate picked by the mouse."
1927 (when (company-select-mouse event)
1928 (company-complete-selection)))
1930 (defun company-complete-selection ()
1931 "Insert the selected candidate."
1933 (when (company-manual-begin)
1934 (let ((result (nth company-selection company-candidates)))
1935 (company-finish result))))
1937 (defun company-complete-common ()
1938 "Insert the common part of all candidates."
1940 (when (company-manual-begin)
1941 (if (and (not (cdr company-candidates))
1942 (equal company-common (car company-candidates)))
1943 (company-complete-selection)
1944 (company--insert-candidate company-common))))
1946 (defun company-complete-common-or-cycle (&optional arg)
1947 "Insert the common part of all candidates, or select the next one.
1949 With ARG, move by that many elements."
1951 (when (company-manual-begin)
1952 (let ((tick (buffer-chars-modified-tick)))
1953 (call-interactively 'company-complete-common)
1954 (when (eq tick (buffer-chars-modified-tick))
1955 (let ((company-selection-wrap-around t)
1956 (current-prefix-arg arg))
1957 (call-interactively 'company-select-next))))))
1959 (defun company-indent-or-complete-common ()
1960 "Indent the current line or region, or complete the common part."
1964 (indent-region (region-beginning) (region-end)))
1965 ((let ((old-point (point))
1966 (old-tick (buffer-chars-modified-tick))
1967 (tab-always-indent t))
1968 (call-interactively #'indent-for-tab-command)
1969 (when (and (eq old-point (point))
1970 (eq old-tick (buffer-chars-modified-tick)))
1971 (company-complete-common))))))
1973 (defun company-complete ()
1974 "Insert the common part of all candidates or the current selection.
1975 The first time this is called, the common part is inserted, the second
1976 time, or when the selection has been changed, the selected candidate is
1979 (when (company-manual-begin)
1980 (if (or company-selection-changed
1981 (eq last-command 'company-complete-common))
1982 (call-interactively 'company-complete-selection)
1983 (call-interactively 'company-complete-common)
1984 (setq this-command 'company-complete-common))))
1986 (defun company-complete-number (n)
1987 "Insert the Nth candidate visible in the tooltip.
1988 To show the number next to the candidates in some backends, enable
1989 `company-show-numbers'. When called interactively, uses the last typed
1990 character, stripping the modifiers. That character must be a digit."
1992 (list (let* ((type (event-basic-type last-command-event))
1993 (char (if (characterp type)
1994 ;; Number on the main row.
1996 ;; Keypad number, if bound directly.
1997 (car (last (string-to-list (symbol-name type))))))
1999 (if (zerop n) 10 n))))
2000 (when (company-manual-begin)
2001 (and (or (< n 1) (> n (- company-candidates-length
2002 company-tooltip-offset)))
2003 (error "No candidate number %d" n))
2005 (company-finish (nth (+ n company-tooltip-offset)
2006 company-candidates))))
2008 ;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;
2010 (defconst company-space-strings-limit 100)
2012 (defconst company-space-strings
2014 (dotimes (i company-space-strings-limit)
2015 (push (make-string (- company-space-strings-limit 1 i) ?\ ) lst))
2016 (apply 'vector lst)))
2018 (defun company-space-string (len)
2019 (if (< len company-space-strings-limit)
2020 (aref company-space-strings len)
2021 (make-string len ?\ )))
2023 (defun company-safe-substring (str from &optional to)
2024 (if (> from (string-width str))
2028 (move-to-column from)
2029 (let ((beg (point)))
2033 (concat (buffer-substring beg (point))
2034 (let ((padding (- to (current-column))))
2036 (company-space-string padding)))))
2037 (buffer-substring beg (point-max)))))))
2039 ;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;
2041 (defvar-local company-last-metadata nil)
2043 (defun company-fetch-metadata ()
2044 (let ((selected (nth company-selection company-candidates)))
2045 (unless (eq selected (car company-last-metadata))
2046 (setq company-last-metadata
2047 (cons selected (company-call-backend 'meta selected))))
2048 (cdr company-last-metadata)))
2050 (defun company-doc-buffer (&optional string)
2051 (with-current-buffer (get-buffer-create "*company-documentation*")
2058 (defvar company--electric-commands
2059 '(scroll-other-window scroll-other-window-down mwheel-scroll)
2060 "List of Commands that won't break out of electric commands.")
2062 (defmacro company--electric-do (&rest body)
2063 (declare (indent 0) (debug t))
2064 `(when (company-manual-begin)
2065 (save-window-excursion
2066 (let ((height (window-height))
2067 (row (company--row))
2070 (and (< (window-height) height)
2071 (< (- (window-height) row 2) company-tooltip-limit)
2072 (recenter (- (window-height) row 2)))
2073 (while (memq (setq cmd (key-binding (read-key-sequence-vector nil)))
2074 company--electric-commands)
2076 (call-interactively cmd)
2077 ((beginning-of-buffer end-of-buffer)
2078 (message (error-message-string err)))))
2079 (company--unread-last-input)))))
2081 (defun company--unread-last-input ()
2082 (when last-input-event
2083 (clear-this-command-keys t)
2084 (setq unread-command-events (list last-input-event))))
2086 (defun company-show-doc-buffer ()
2087 "Temporarily show the documentation buffer for the selection."
2089 (let (other-window-scroll-buffer)
2090 (company--electric-do
2091 (let* ((selected (nth company-selection company-candidates))
2092 (doc-buffer (or (company-call-backend 'doc-buffer selected)
2093 (error "No documentation available")))
2095 (when (consp doc-buffer)
2096 (setq start (cdr doc-buffer)
2097 doc-buffer (car doc-buffer)))
2098 (setq other-window-scroll-buffer (get-buffer doc-buffer))
2099 (let ((win (display-buffer doc-buffer t)))
2100 (set-window-start win (if start start (point-min))))))))
2101 (put 'company-show-doc-buffer 'company-keep t)
2103 (defun company-show-location ()
2104 "Temporarily display a buffer showing the selected candidate in context."
2106 (let (other-window-scroll-buffer)
2107 (company--electric-do
2108 (let* ((selected (nth company-selection company-candidates))
2109 (location (company-call-backend 'location selected))
2110 (pos (or (cdr location) (error "No location available")))
2111 (buffer (or (and (bufferp (car location)) (car location))
2112 (find-file-noselect (car location) t))))
2113 (setq other-window-scroll-buffer (get-buffer buffer))
2114 (with-selected-window (display-buffer buffer t)
2117 (if (bufferp (car location))
2119 (goto-char (point-min))
2120 (forward-line (1- pos))))
2121 (set-window-start nil (point)))))))
2122 (put 'company-show-location 'company-keep t)
2124 ;;; package functions ;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;
2126 (defvar-local company-callback nil)
2128 (defun company-remove-callback (&optional ignored)
2129 (remove-hook 'company-completion-finished-hook company-callback t)
2130 (remove-hook 'company-completion-cancelled-hook 'company-remove-callback t)
2131 (remove-hook 'company-completion-finished-hook 'company-remove-callback t))
2133 (defun company-begin-backend (backend &optional callback)
2134 "Start a completion at point using BACKEND."
2135 (interactive (let ((val (completing-read "Company backend: "
2137 'functionp nil "company-")))
2139 (list (intern val)))))
2140 (when (setq company-callback callback)
2141 (add-hook 'company-completion-finished-hook company-callback nil t))
2142 (add-hook 'company-completion-cancelled-hook 'company-remove-callback nil t)
2143 (add-hook 'company-completion-finished-hook 'company-remove-callback nil t)
2144 (setq company-backend backend)
2145 ;; Return non-nil if active.
2146 (or (company-manual-begin)
2147 (error "Cannot complete at point")))
2149 (defun company-begin-with (candidates
2150 &optional prefix-length require-match callback)
2151 "Start a completion at point.
2152 CANDIDATES is the list of candidates to use and PREFIX-LENGTH is the length
2153 of the prefix that already is in the buffer before point.
2156 CALLBACK is a function called with the selected result if the user
2157 successfully completes the input.
2159 Example: \(company-begin-with '\(\"foo\" \"foobar\" \"foobarbaz\"\)\)"
2160 (let ((begin-marker (copy-marker (point) t)))
2161 (company-begin-backend
2162 (lambda (command &optional arg &rest ignored)
2165 (when (equal (point) (marker-position begin-marker))
2166 (buffer-substring (- (point) (or prefix-length 0)) (point))))
2168 (all-completions arg candidates))
2173 (defun company-version (&optional show-version)
2174 "Get the Company version as string.
2176 If SHOW-VERSION is non-nil, show the version in the echo area."
2177 (interactive (list t))
2179 (require 'find-func)
2180 (insert-file-contents (find-library-name "company"))
2183 (message "Company version: %s" (lm-version))
2186 (defun company-diag ()
2187 "Pop a buffer with information about completions at point."
2189 (let* ((bb company-backends)
2191 (prefix (cl-loop for b in bb
2192 thereis (let ((company-backend b))
2194 (company-call-backend 'prefix))))
2196 (when (stringp prefix)
2197 (let ((company-backend backend))
2198 (setq cc (company-call-backend 'candidates prefix)
2201 (lambda (c) (cons c (company-call-backend 'annotation c)))
2203 (pop-to-buffer (get-buffer-create "*company-diag*"))
2204 (setq buffer-read-only nil)
2206 (insert (format "Emacs %s (%s) of %s on %s"
2207 emacs-version system-configuration
2208 (format-time-string "%Y-%m-%d" emacs-build-time)
2209 emacs-build-system))
2210 (insert "\nCompany " (company-version) "\n\n")
2211 (insert "company-backends: " (pp-to-string bb))
2213 (insert "Used backend: " (pp-to-string backend))
2215 (insert "Prefix: " (pp-to-string prefix))
2217 (insert (message "Completions:"))
2218 (unless cc (insert " none"))
2220 (dolist (c annotations)
2221 (insert "\n " (prin1-to-string (car c)))
2223 (insert " " (prin1-to-string (cdr c))))))
2226 ;;; pseudo-tooltip ;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;
2228 (defvar-local company-pseudo-tooltip-overlay nil)
2230 (defvar-local company-tooltip-offset 0)
2232 (defun company-tooltip--lines-update-offset (selection num-lines limit)
2234 (setq company-tooltip-offset
2235 (max (min selection company-tooltip-offset)
2236 (- selection -1 limit)))
2238 (when (<= company-tooltip-offset 1)
2240 (setq company-tooltip-offset 0))
2242 (when (>= company-tooltip-offset (- num-lines limit 1))
2244 (when (= selection (1- num-lines))
2245 (cl-decf company-tooltip-offset)
2246 (when (<= company-tooltip-offset 1)
2247 (setq company-tooltip-offset 0)
2252 (defun company-tooltip--simple-update-offset (selection _num-lines limit)
2253 (setq company-tooltip-offset
2254 (if (< selection company-tooltip-offset)
2256 (max company-tooltip-offset
2257 (- selection limit -1)))))
2261 (defsubst company-round-tab (arg)
2262 (* (/ (+ arg tab-width) tab-width) tab-width))
2264 (defun company-plainify (str)
2265 (let ((prefix (get-text-property 0 'line-prefix str)))
2266 (when prefix ; Keep the original value unmodified, for no special reason.
2267 (setq str (concat prefix str))
2268 (remove-text-properties 0 (length str) '(line-prefix) str)))
2269 (let* ((pieces (split-string str "\t"))
2272 (setcar copy (company-safe-substring
2273 (car copy) 0 (company-round-tab (string-width (car copy)))))
2275 (apply 'concat pieces)))
2277 (defun company-fill-propertize (value annotation width selected left right)
2278 (let* ((margin (length left))
2279 (common (or (company-call-backend 'match value)
2281 (string-width company-common)
2283 (ann-ralign company-tooltip-align-annotations)
2284 (ann-truncate (< width
2285 (+ (length value) (length annotation)
2286 (if ann-ralign 1 0))))
2287 (ann-start (+ margin
2291 (- width (length annotation)))
2293 (ann-end (min (+ ann-start (length annotation)) (+ margin width)))
2295 (if (or ann-truncate (not ann-ralign))
2296 (company-safe-substring
2298 (when (and annotation ann-ralign) " ")
2302 (company-safe-substring value 0
2303 (- width (length annotation)))
2306 (setq common (+ (min common width) margin))
2307 (setq width (+ width margin (length right)))
2309 (add-text-properties 0 width '(face company-tooltip
2310 mouse-face company-tooltip-mouse)
2312 (add-text-properties margin common
2313 '(face company-tooltip-common
2314 mouse-face company-tooltip-mouse)
2316 (when (< ann-start ann-end)
2317 (add-text-properties ann-start ann-end
2318 '(face company-tooltip-annotation
2319 mouse-face company-tooltip-mouse)
2322 (if (and (not (string= company-search-string ""))
2323 (string-match (regexp-quote company-search-string) value
2324 (length company-prefix)))
2325 (let ((beg (+ margin (match-beginning 0)))
2326 (end (+ margin (match-end 0)))
2327 (width (- width (length right))))
2329 (add-text-properties beg (min end width)
2330 '(face company-tooltip-search)
2332 (add-text-properties 0 width '(face company-tooltip-selection
2333 mouse-face company-tooltip-selection)
2335 (add-text-properties margin common
2336 '(face company-tooltip-common-selection
2337 mouse-face company-tooltip-selection)
2341 (defun company--clean-string (str)
2342 (replace-regexp-in-string
2343 "\\([^[:graph:] ]\\)\\|\\(\ufeff\\)\\|[[:multibyte:]]"
2346 ((match-beginning 1)
2347 ;; FIXME: Better char for 'non-printable'?
2348 ;; We shouldn't get any of these, but sometimes we might.
2350 ((match-beginning 2)
2351 ;; Zero-width non-breakable space.
2353 ((> (string-width match) 1)
2355 (make-string (1- (string-width match)) ?\ufeff)
2362 (defun company-buffer-lines (beg end)
2364 (let (lines lines-moved)
2365 (while (and (not (eobp)) ; http://debbugs.gnu.org/19553
2366 (> (setq lines-moved (vertical-motion 1)) 0)
2368 (let ((bound (min end (point))))
2369 ;; A visual line can contain several physical lines (e.g. with outline's
2370 ;; folding overlay). Take only the first one.
2371 (push (buffer-substring beg
2374 (re-search-forward "$" bound 'move)
2377 ;; One physical line can be displayed as several visual ones as well:
2378 ;; add empty strings to the list, to even the count.
2379 (dotimes (_ (1- lines-moved))
2382 (unless (eq beg end)
2383 (push (buffer-substring beg end) lines))
2386 (defun company-modify-line (old new offset)
2387 (concat (company-safe-substring old 0 offset)
2389 (company-safe-substring old (+ offset (length new)))))
2391 (defsubst company--length-limit (lst limit)
2392 (if (nthcdr limit lst)
2396 (defsubst company--window-height ()
2397 (if (fboundp 'window-screen-lines)
2398 (floor (window-screen-lines))
2399 (window-body-height)))
2401 (defun company--window-width ()
2402 (let ((ww (window-body-width)))
2403 ;; Account for the line continuation column.
2404 (when (zerop (cadr (window-fringes)))
2406 (unless (or (display-graphic-p)
2407 (version< "24.3.1" emacs-version))
2408 ;; Emacs 24.3 and earlier included margins
2409 ;; in window-width when in TTY.
2411 (let ((margins (window-margins)))
2412 (+ (or (car margins) 0)
2413 (or (cdr margins) 0)))))
2414 (when (and word-wrap
2415 (version< emacs-version "24.4.51.5"))
2416 ;; http://debbugs.gnu.org/19300
2418 ;; whitespace-mode with newline-mark
2419 (when (and buffer-display-table
2420 (aref buffer-display-table ?\n))
2421 (cl-decf ww (1- (length (aref buffer-display-table ?\n)))))
2424 (defun company--replacement-string (lines old column nl &optional align-top)
2425 (cl-decf column company-tooltip-margin)
2427 (when (and align-top company-tooltip-flip-when-above)
2428 (setq lines (reverse lines)))
2430 (let ((width (length (car lines)))
2431 (remaining-cols (- (+ (company--window-width) (window-hscroll))
2433 (when (> width remaining-cols)
2434 (cl-decf column (- width remaining-cols))))
2436 (let ((offset (and (< column 0) (- column)))
2441 ;; untouched lines first
2442 (dotimes (_ (- (length old) (length lines)))
2443 (push (pop old) new)))
2444 ;; length into old lines.
2446 (push (company-modify-line (pop old)
2447 (company--offset-line (pop lines) offset)
2450 ;; Append whole new lines.
2452 (push (concat (company-space-string column)
2453 (company--offset-line (pop lines) offset))
2456 (let ((str (concat (when nl " \n")
2457 (mapconcat 'identity (nreverse new) "\n")
2459 (font-lock-append-text-property 0 (length str) 'face 'default str)
2460 (when nl (put-text-property 0 1 'cursor t str))
2463 (defun company--offset-line (line offset)
2464 (if (and offset line)
2465 (substring line offset)
2468 (defun company--create-lines (selection limit)
2469 (let ((len company-candidates-length)
2470 (window-width (company--window-width))
2479 ;; Maybe clear old offset.
2480 (when (< len (+ company-tooltip-offset limit))
2481 (setq company-tooltip-offset 0))
2483 ;; Scroll to offset.
2484 (if (eq company-tooltip-offset-display 'lines)
2485 (setq limit (company-tooltip--lines-update-offset selection len limit))
2486 (company-tooltip--simple-update-offset selection len limit))
2489 ((eq company-tooltip-offset-display 'scrollbar)
2490 (setq scrollbar-bounds (company--scrollbar-bounds company-tooltip-offset
2492 ((eq company-tooltip-offset-display 'lines)
2493 (when (> company-tooltip-offset 0)
2494 (setq previous (format "...(%d)" company-tooltip-offset)))
2495 (setq remainder (- len limit company-tooltip-offset)
2496 remainder (when (> remainder 0)
2497 (setq remainder (format "...(%d)" remainder))))))
2499 (cl-decf selection company-tooltip-offset)
2500 (setq width (max (length previous) (length remainder))
2501 lines (nthcdr company-tooltip-offset company-candidates)
2505 (cl-decf window-width (* 2 company-tooltip-margin))
2506 (when scrollbar-bounds (cl-decf window-width))
2509 (let* ((value (pop lines-copy))
2510 (annotation (company-call-backend 'annotation value)))
2511 (setq value (company--clean-string (company-reformat value)))
2513 (when company-tooltip-align-annotations
2514 ;; `lisp-completion-at-point' adds a space.
2515 (setq annotation (comment-string-strip annotation t nil)))
2516 (setq annotation (company--clean-string annotation)))
2517 (push (cons value annotation) items)
2518 (setq width (max (+ (length value)
2519 (if (and annotation company-tooltip-align-annotations)
2520 (1+ (length annotation))
2521 (length annotation)))
2524 (setq width (min window-width
2525 (max company-tooltip-minimum-width
2526 (if company-show-numbers
2530 (let ((items (nreverse items))
2531 (numbered (if company-show-numbers 0 99999))
2534 (push (company--scrollpos-line previous width) new))
2537 (let* ((item (pop items))
2539 (annotation (cdr item))
2540 (right (company-space-string company-tooltip-margin))
2542 (when (< numbered 10)
2545 (setq right (concat (format " %d" (mod numbered 10)) right)))
2547 (company-fill-propertize str annotation
2548 width (equal i selection)
2549 (company-space-string
2550 company-tooltip-margin)
2552 (when scrollbar-bounds
2553 (company--scrollbar i scrollbar-bounds)))
2557 (push (company--scrollpos-line remainder width) new))
2561 (defun company--scrollbar-bounds (offset limit length)
2562 (when (> length limit)
2563 (let* ((size (ceiling (* limit (float limit)) length))
2564 (lower (floor (* limit (float offset)) length))
2565 (upper (+ lower size -1)))
2566 (cons lower upper))))
2568 (defun company--scrollbar (i bounds)
2569 (propertize " " 'face
2570 (if (and (>= i (car bounds)) (<= i (cdr bounds)))
2571 'company-scrollbar-fg
2572 'company-scrollbar-bg)))
2574 (defun company--scrollpos-line (text width)
2575 (propertize (concat (company-space-string company-tooltip-margin)
2576 (company-safe-substring text 0 width)
2577 (company-space-string company-tooltip-margin))
2578 'face 'company-tooltip))
2582 (defun company--pseudo-tooltip-height ()
2583 "Calculate the appropriate tooltip height.
2584 Returns a negative number if the tooltip should be displayed above point."
2585 (let* ((lines (company--row))
2586 (below (- (company--window-height) 1 lines)))
2587 (if (and (< below (min company-tooltip-minimum company-candidates-length))
2589 (- (max 3 (min company-tooltip-limit lines)))
2590 (max 3 (min company-tooltip-limit below)))))
2592 (defun company-pseudo-tooltip-show (row column selection)
2593 (company-pseudo-tooltip-hide)
2596 (let* ((height (company--pseudo-tooltip-height))
2600 (setq row (+ row height -1)
2603 (let* ((nl (< (move-to-window-line row) row))
2605 (end (save-excursion
2606 (move-to-window-line (+ row (abs height)))
2608 (ov (make-overlay beg end nil t))
2609 (args (list (mapcar 'company-plainify
2610 (company-buffer-lines beg end))
2613 (setq company-pseudo-tooltip-overlay ov)
2614 (overlay-put ov 'company-replacement-args args)
2616 (let ((lines (company--create-lines selection (abs height))))
2617 (overlay-put ov 'company-display
2618 (apply 'company--replacement-string lines args))
2619 (overlay-put ov 'company-width (string-width (car lines))))
2621 (overlay-put ov 'company-column column)
2622 (overlay-put ov 'company-height height)))))
2624 (defun company-pseudo-tooltip-show-at-point (pos column-offset)
2625 (let* ((col-row (company--col-row pos))
2626 (col (- (car col-row) column-offset)))
2627 (when (< col 0) (setq col 0))
2628 (company-pseudo-tooltip-show (1+ (cdr col-row)) col company-selection)))
2630 (defun company-pseudo-tooltip-edit (selection)
2631 (let* ((height (overlay-get company-pseudo-tooltip-overlay 'company-height))
2632 (lines (company--create-lines selection (abs height))))
2633 (overlay-put company-pseudo-tooltip-overlay 'company-width
2634 (string-width (car lines)))
2635 (overlay-put company-pseudo-tooltip-overlay 'company-display
2636 (apply 'company--replacement-string
2638 (overlay-get company-pseudo-tooltip-overlay
2639 'company-replacement-args)))))
2641 (defun company-pseudo-tooltip-hide ()
2642 (when company-pseudo-tooltip-overlay
2643 (delete-overlay company-pseudo-tooltip-overlay)
2644 (setq company-pseudo-tooltip-overlay nil)))
2646 (defun company-pseudo-tooltip-hide-temporarily ()
2647 (when (overlayp company-pseudo-tooltip-overlay)
2648 (overlay-put company-pseudo-tooltip-overlay 'invisible nil)
2649 (overlay-put company-pseudo-tooltip-overlay 'line-prefix nil)
2650 (overlay-put company-pseudo-tooltip-overlay 'after-string nil)
2651 (overlay-put company-pseudo-tooltip-overlay 'display nil)))
2653 (defun company-pseudo-tooltip-unhide ()
2654 (when company-pseudo-tooltip-overlay
2655 (let* ((ov company-pseudo-tooltip-overlay)
2656 (disp (overlay-get ov 'company-display)))
2657 ;; Beat outline's folding overlays, at least.
2658 (overlay-put ov 'priority 1)
2659 ;; No (extra) prefix for the first line.
2660 (overlay-put ov 'line-prefix "")
2661 ;; `display' is better
2662 ;; (http://debbugs.gnu.org/18285, http://debbugs.gnu.org/20847),
2663 ;; but it doesn't work on 0-length overlays.
2664 (if (< (overlay-start ov) (overlay-end ov))
2665 (overlay-put ov 'display disp)
2666 (overlay-put ov 'after-string disp)
2667 (overlay-put ov 'invisible t))
2668 (overlay-put ov 'window (selected-window)))))
2670 (defun company-pseudo-tooltip-guard ()
2672 (save-excursion (beginning-of-visual-line))
2673 (let ((ov company-pseudo-tooltip-overlay)
2674 (overhang (save-excursion (end-of-visual-line)
2675 (- (line-end-position) (point)))))
2676 (when (>= (overlay-get ov 'company-height) 0)
2678 (buffer-substring-no-properties (point) (overlay-start ov))
2679 (when (>= overhang 0) overhang))))))
2681 (defun company-pseudo-tooltip-frontend (command)
2682 "`company-mode' frontend similar to a tooltip but based on overlays."
2684 (pre-command (company-pseudo-tooltip-hide-temporarily))
2686 (unless (when (overlayp company-pseudo-tooltip-overlay)
2687 (let* ((ov company-pseudo-tooltip-overlay)
2688 (old-height (overlay-get ov 'company-height))
2689 (new-height (company--pseudo-tooltip-height)))
2691 (>= (* old-height new-height) 0)
2692 (>= (abs old-height) (abs new-height))
2693 (equal (company-pseudo-tooltip-guard)
2694 (overlay-get ov 'company-guard)))))
2696 (company-pseudo-tooltip-show-at-point (point) (length company-prefix))
2697 (overlay-put company-pseudo-tooltip-overlay
2698 'company-guard (company-pseudo-tooltip-guard)))
2699 (company-pseudo-tooltip-unhide))
2700 (hide (company-pseudo-tooltip-hide)
2701 (setq company-tooltip-offset 0))
2702 (update (when (overlayp company-pseudo-tooltip-overlay)
2703 (company-pseudo-tooltip-edit company-selection)))))
2705 (defun company-pseudo-tooltip-unless-just-one-frontend (command)
2706 "`company-pseudo-tooltip-frontend', but not shown for single candidates."
2707 (unless (and (eq command 'post-command)
2708 (company--show-inline-p))
2709 (company-pseudo-tooltip-frontend command)))
2711 ;;; overlay ;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;
2713 (defvar-local company-preview-overlay nil)
2715 (defun company-preview-show-at-point (pos)
2716 (company-preview-hide)
2718 (let ((completion (nth company-selection company-candidates)))
2719 (setq completion (propertize completion 'face 'company-preview))
2720 (add-text-properties 0 (length company-common)
2721 '(face company-preview-common) completion)
2723 ;; Add search string
2724 (and company-search-string
2725 (string-match (regexp-quote company-search-string) completion)
2726 (add-text-properties (match-beginning 0)
2728 '(face company-preview-search)
2731 (setq completion (company-strip-prefix completion))
2733 (and (equal pos (point))
2734 (not (equal completion ""))
2735 (add-text-properties 0 1 '(cursor 1) completion))
2738 (pto company-pseudo-tooltip-overlay)
2739 (ptf-workaround (and
2742 (eq pos (overlay-start pto)))))
2743 ;; Try to accomodate for the pseudo-tooltip overlay,
2744 ;; which may start at the same position if it's at eol.
2745 (when ptf-workaround
2747 (setq completion (concat (buffer-substring beg pos) completion)))
2749 (setq company-preview-overlay (make-overlay beg pos))
2751 (let ((ov company-preview-overlay))
2752 (overlay-put ov (if ptf-workaround 'display 'after-string)
2754 (overlay-put ov 'window (selected-window))))))
2756 (defun company-preview-hide ()
2757 (when company-preview-overlay
2758 (delete-overlay company-preview-overlay)
2759 (setq company-preview-overlay nil)))
2761 (defun company-preview-frontend (command)
2762 "`company-mode' frontend showing the selection as if it had been inserted."
2764 (`pre-command (company-preview-hide))
2765 (`post-command (company-preview-show-at-point (point)))
2766 (`hide (company-preview-hide))))
2768 (defun company-preview-if-just-one-frontend (command)
2769 "`company-preview-frontend', but only shown for single candidates."
2770 (when (or (not (eq command 'post-command))
2771 (company--show-inline-p))
2772 (company-preview-frontend command)))
2774 (defun company--show-inline-p ()
2775 (and (not (cdr company-candidates))
2777 (or (eq (company-call-backend 'ignore-case) 'keep-prefix)
2778 (string-prefix-p company-prefix company-common))))
2780 ;;; echo ;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;
2782 (defvar-local company-echo-last-msg nil)
2784 (defvar company-echo-timer nil)
2786 (defvar company-echo-delay .01)
2788 (defun company-echo-show (&optional getter)
2790 (setq company-echo-last-msg (funcall getter)))
2791 (let ((message-log-max nil))
2792 (if company-echo-last-msg
2793 (message "%s" company-echo-last-msg)
2796 (defun company-echo-show-soon (&optional getter)
2797 (company-echo-cancel)
2798 (setq company-echo-timer (run-with-timer 0 nil 'company-echo-show getter)))
2800 (defun company-echo-cancel (&optional unset)
2801 (when company-echo-timer
2802 (cancel-timer company-echo-timer))
2804 (setq company-echo-timer nil)))
2806 (defun company-echo-show-when-idle (&optional getter)
2807 (company-echo-cancel)
2808 (setq company-echo-timer
2809 (run-with-idle-timer company-echo-delay nil 'company-echo-show getter)))
2811 (defun company-echo-format ()
2813 (let ((limit (window-body-width (minibuffer-window)))
2815 ;; Roll to selection.
2816 (candidates (nthcdr company-selection company-candidates))
2817 (i (if company-show-numbers company-selection 99999))
2821 (setq comp (company-reformat (pop candidates))
2822 len (+ len 1 (length comp)))
2826 (setq comp (propertize (format "%d: %s" i comp)
2827 'face 'company-echo))
2830 (add-text-properties 3 (+ 3 (length company-common))
2831 '(face company-echo-common) comp))
2832 (setq comp (propertize comp 'face 'company-echo))
2833 (add-text-properties 0 (length company-common)
2834 '(face company-echo-common) comp))
2836 (setq candidates nil)
2839 (mapconcat 'identity (nreverse msg) " ")))
2841 (defun company-echo-strip-common-format ()
2843 (let ((limit (window-body-width (minibuffer-window)))
2844 (len (+ (length company-prefix) 2))
2845 ;; Roll to selection.
2846 (candidates (nthcdr company-selection company-candidates))
2847 (i (if company-show-numbers company-selection 99999))
2851 (setq comp (company-strip-prefix (pop candidates))
2852 len (+ len 2 (length comp)))
2855 (setq comp (format "%s (%d)" comp i))
2859 (setq candidates nil)
2860 (push (propertize comp 'face 'company-echo) msg)))
2862 (concat (propertize company-prefix 'face 'company-echo-common) "{"
2863 (mapconcat 'identity (nreverse msg) ", ")
2866 (defun company-echo-hide ()
2867 (unless (equal company-echo-last-msg "")
2868 (setq company-echo-last-msg "")
2869 (company-echo-show)))
2871 (defun company-echo-frontend (command)
2872 "`company-mode' frontend showing the candidates in the echo area."
2874 (`post-command (company-echo-show-soon 'company-echo-format))
2875 (`hide (company-echo-hide))))
2877 (defun company-echo-strip-common-frontend (command)
2878 "`company-mode' frontend showing the candidates in the echo area."
2880 (`post-command (company-echo-show-soon 'company-echo-strip-common-format))
2881 (`hide (company-echo-hide))))
2883 (defun company-echo-metadata-frontend (command)
2884 "`company-mode' frontend showing the documentation in the echo area."
2886 (`post-command (company-echo-show-when-idle 'company-fetch-metadata))
2887 (`hide (company-echo-hide))))
2890 ;;; company.el ends here