1 ;;; company.el --- Modular text completion framework -*- lexical-binding: t -*-
3 ;; Copyright (C) 2009-2016 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 framework. Modules for retrieving completion
30 ;; candidates are called backends, modules for displaying them are frontends.
32 ;; Company comes with many backends, e.g. `company-etags'. These are
33 ;; distributed in separate files and can be used individually.
35 ;; Enable `company-mode' in all buffers with M-x global-company-mode. For
36 ;; further information look at the documentation for `company-mode' (C-h f
39 ;; If you want to start a specific backend, call it interactively or use
40 ;; `company-begin-backend'. For example:
41 ;; M-x company-abbrev will prompt for and insert an abbrev.
43 ;; To write your own backend, look at the documentation for `company-backends'.
44 ;; Here is a simple example completing "foo":
46 ;; (defun company-my-backend (command &optional arg &rest ignored)
48 ;; (`prefix (company-grab-symbol))
49 ;; (`candidates (list "foobar" "foobaz" "foobarbaz"))
50 ;; (`meta (format "This value is named %s" arg))))
52 ;; Sometimes it is a good idea to mix several backends together, for example to
53 ;; enrich gtags with dabbrev-code results (to emulate local variables). To do
54 ;; this, add a list with both backends as an element in `company-backends'.
58 ;; See NEWS.md in the repository.
66 ;; FIXME: Use `user-error'.
67 (add-to-list 'debug-ignored-errors "^.* frontend cannot be used twice$")
68 (add-to-list 'debug-ignored-errors "^Echo area cannot be used twice$")
69 (add-to-list 'debug-ignored-errors "^No \\(document\\|loc\\)ation available$")
70 (add-to-list 'debug-ignored-errors "^Company not ")
71 (add-to-list 'debug-ignored-errors "^No candidate number ")
72 (add-to-list 'debug-ignored-errors "^Cannot complete at point$")
73 (add-to-list 'debug-ignored-errors "^No other backend$")
77 ;; `defvar-local' for Emacs 24.2 and below
78 (unless (fboundp 'defvar-local)
79 (defmacro defvar-local (var val &optional docstring)
80 "Define VAR as a buffer-local variable with default value VAL.
81 Like `defvar' but additionally marks the variable as being automatically
82 buffer-local wherever it is set."
83 (declare (debug defvar) (doc-string 3))
85 (defvar ,var ,val ,docstring)
86 (make-variable-buffer-local ',var)))))
89 "Extensible inline text completion mechanism"
94 (defface company-tooltip
95 '((default :foreground "black")
96 (((class color) (min-colors 88) (background light))
97 (:background "cornsilk"))
98 (((class color) (min-colors 88) (background dark))
99 (:background "yellow")))
100 "Face used for the tooltip.")
102 (defface company-tooltip-selection
103 '((((class color) (min-colors 88) (background light))
104 (:background "light blue"))
105 (((class color) (min-colors 88) (background dark))
106 (:background "orange1"))
107 (t (:background "green")))
108 "Face used for the selection in the tooltip.")
110 (defface company-tooltip-search
111 '((default :inherit company-tooltip-selection))
112 "Face used for the search string in the tooltip.")
114 (defface company-tooltip-mouse
115 '((default :inherit highlight))
116 "Face used for the tooltip item under the mouse.")
118 (defface company-tooltip-common
119 '((((background light))
120 :foreground "darkred")
123 "Face used for the common completion in the tooltip.")
125 (defface company-tooltip-common-selection
126 '((default :inherit company-tooltip-common))
127 "Face used for the selected common completion in the tooltip.")
129 (defface company-tooltip-annotation
130 '((((background light))
131 :foreground "firebrick4")
134 "Face used for the completion annotation in the tooltip.")
136 (defface company-tooltip-annotation-selection
137 '((default :inherit company-tooltip-annotation))
138 "Face used for the selected completion annotation in the tooltip.")
140 (defface company-scrollbar-fg
141 '((((background light))
142 :background "darkred")
145 "Face used for the tooltip scrollbar thumb.")
147 (defface company-scrollbar-bg
148 '((((background light))
152 "Face used for the tooltip scrollbar background.")
154 (defface company-preview
155 '((((background light))
156 :inherit (company-tooltip-selection company-tooltip))
159 :foreground "wheat"))
160 "Face used for the completion preview.")
162 (defface company-preview-common
163 '((((background light))
164 :inherit company-tooltip-common-selection)
166 :inherit company-preview
168 "Face used for the common part of the completion preview.")
170 (defface company-preview-search
171 '((((background light))
172 :inherit company-tooltip-common-selection)
174 :inherit company-preview
175 :background "blue1"))
176 "Face used for the search string in the completion preview.")
178 (defface company-echo nil
179 "Face used for completions in the echo area.")
181 (defface company-echo-common
182 '((((background dark)) (:foreground "firebrick1"))
183 (((background light)) (:background "firebrick4")))
184 "Face used for the common part of completions in the echo area.")
186 (defun company-frontends-set (variable value)
188 (let ((value (delete-dups (copy-sequence value))))
189 (and (memq 'company-pseudo-tooltip-unless-just-one-frontend value)
190 (memq 'company-pseudo-tooltip-frontend value)
191 (error "Pseudo tooltip frontend cannot be used twice"))
192 (and (memq 'company-preview-if-just-one-frontend value)
193 (memq 'company-preview-frontend value)
194 (error "Preview frontend cannot be used twice"))
195 (and (memq 'company-echo value)
196 (memq 'company-echo-metadata-frontend value)
197 (error "Echo area cannot be used twice"))
198 ;; Preview must come last.
199 (dolist (f '(company-preview-if-just-one-frontend company-preview-frontend))
200 (when (cdr (memq f value))
201 (setq value (append (delq f value) (list f)))))
202 (set variable value)))
204 (defcustom company-frontends '(company-pseudo-tooltip-unless-just-one-frontend
205 company-preview-if-just-one-frontend
206 company-echo-metadata-frontend)
207 "The list of active frontends (visualizations).
208 Each frontend is a function that takes one argument. It is called with
209 one of the following arguments:
211 `show': When the visualization should start.
213 `hide': When the visualization should end.
215 `update': When the data has been updated.
217 `pre-command': Before every command that is executed while the
218 visualization is active.
220 `post-command': After every command that is executed while the
221 visualization is active.
223 The visualized data is stored in `company-prefix', `company-candidates',
224 `company-common', `company-selection', `company-point' and
225 `company-search-string'."
226 :set 'company-frontends-set
227 :type '(repeat (choice (const :tag "echo" company-echo-frontend)
228 (const :tag "echo, strip common"
229 company-echo-strip-common-frontend)
230 (const :tag "show echo meta-data in echo"
231 company-echo-metadata-frontend)
232 (const :tag "pseudo tooltip"
233 company-pseudo-tooltip-frontend)
234 (const :tag "pseudo tooltip, multiple only"
235 company-pseudo-tooltip-unless-just-one-frontend)
236 (const :tag "preview" company-preview-frontend)
237 (const :tag "preview, unique only"
238 company-preview-if-just-one-frontend)
239 (function :tag "custom function" nil))))
241 (defcustom company-tooltip-limit 10
242 "The maximum number of candidates in the tooltip."
245 (defcustom company-tooltip-minimum 6
246 "The minimum height of the tooltip.
247 If this many lines are not available, prefer to display the tooltip above."
250 (defcustom company-tooltip-minimum-width 0
251 "The minimum width of the tooltip's inner area.
252 This doesn't include the margins and the scroll bar."
254 :package-version '(company . "0.8.0"))
256 (defcustom company-tooltip-margin 1
257 "Width of margin columns to show around the toolip."
260 (defcustom company-tooltip-offset-display 'scrollbar
261 "Method using which the tooltip displays scrolling position.
262 `scrollbar' means draw a scrollbar to the right of the items.
263 `lines' means wrap items in lines with \"before\" and \"after\" counters."
264 :type '(choice (const :tag "Scrollbar" scrollbar)
265 (const :tag "Two lines" lines)))
267 (defcustom company-tooltip-align-annotations nil
268 "When non-nil, align annotations to the right tooltip border."
270 :package-version '(company . "0.7.1"))
272 (defcustom company-tooltip-flip-when-above nil
273 "Whether to flip the tooltip when it's above the current line."
275 :package-version '(company . "0.8.1"))
277 (defvar company-safe-backends
278 '((company-abbrev . "Abbrev")
279 (company-bbdb . "BBDB")
280 (company-capf . "completion-at-point-functions")
281 (company-clang . "Clang")
282 (company-cmake . "CMake")
283 (company-css . "CSS")
284 (company-dabbrev . "dabbrev for plain text")
285 (company-dabbrev-code . "dabbrev for code")
286 (company-eclim . "Eclim (an Eclipse interface)")
287 (company-elisp . "Emacs Lisp")
288 (company-etags . "etags")
289 (company-files . "Files")
290 (company-gtags . "GNU Global")
291 (company-ispell . "Ispell")
292 (company-keywords . "Programming language keywords")
293 (company-nxml . "nxml")
294 (company-oddmuse . "Oddmuse")
295 (company-semantic . "Semantic")
296 (company-tempo . "Tempo templates")
297 (company-xcode . "Xcode")))
298 (put 'company-safe-backends 'risky-local-variable t)
300 (defun company-safe-backends-p (backends)
301 (and (consp backends)
302 (not (cl-dolist (backend backends)
303 (unless (if (consp backend)
304 (company-safe-backends-p backend)
305 (assq backend company-safe-backends))
308 (defcustom company-backends `(,@(unless (version< "24.3.51" emacs-version)
309 (list 'company-elisp))
311 company-nxml company-css
312 company-eclim company-semantic company-clang
313 company-xcode company-cmake
316 (company-dabbrev-code company-gtags company-etags
318 company-oddmuse company-dabbrev)
319 "The list of active backends (completion engines).
321 Only one backend is used at a time. The choice depends on the order of
322 the items in this list, and on the values they return in response to the
323 `prefix' command (see below). But a backend can also be a \"grouped\"
326 `company-begin-backend' can be used to start a specific backend,
327 `company-other-backend' will skip to the next matching backend in the list.
329 Each backend is a function that takes a variable number of arguments.
330 The first argument is the command requested from the backend. It is one
333 `prefix': The backend should return the text to be completed. It must be
334 text immediately before point. Returning nil from this command passes
335 control to the next backend. The function should return `stop' if it
336 should complete but cannot (e.g. if it is in the middle of a string).
337 Instead of a string, the backend may return a cons (PREFIX . LENGTH)
338 where LENGTH is a number used in place of PREFIX's length when
339 comparing against `company-minimum-prefix-length'. LENGTH can also
340 be just t, and in the latter case the test automatically succeeds.
342 `candidates': The second argument is the prefix to be completed. The
343 return value should be a list of candidates that match the prefix.
345 Non-prefix matches are also supported (candidates that don't start with the
346 prefix, but match it in some backend-defined way). Backends that use this
347 feature must disable cache (return t to `no-cache') and might also want to
353 `sorted': Return t here to indicate that the candidates are sorted and will
354 not need to be sorted again.
356 `duplicates': If non-nil, company will take care of removing duplicates
359 `no-cache': Usually company doesn't ask for candidates again as completion
360 progresses, unless the backend returns t for this command. The second
361 argument is the latest prefix.
363 `ignore-case': Return t here if the backend returns case-insensitive
364 matches. This value is used to determine the longest common prefix (as
365 used in `company-complete-common'), and to filter completions when fetching
368 `meta': The second argument is a completion candidate. Return a (short)
369 documentation string for it.
371 `doc-buffer': The second argument is a completion candidate. Return a
372 buffer with documentation for it. Preferably use `company-doc-buffer'. If
373 not all buffer contents pertain to this candidate, return a cons of buffer
374 and window start position.
376 `location': The second argument is a completion candidate. Return a cons
377 of buffer and buffer location, or of file and line number where the
378 completion candidate was defined.
380 `annotation': The second argument is a completion candidate. Return a
381 string to be displayed inline with the candidate in the popup. If
382 duplicates are removed by company, candidates with equal string values will
383 be kept if they have different annotations. For that to work properly,
384 backends should store the related information on candidates using text
387 `match': The second argument is a completion candidate. Return the index
388 after the end of text matching `prefix' within the candidate string. It
389 will be used when rendering the popup. This command only makes sense for
390 backends that provide non-prefix completion.
392 `require-match': If this returns t, the user is not allowed to enter
393 anything not offered as a candidate. Please don't use that value in normal
394 backends. The default value nil gives the user that choice with
395 `company-require-match'. Return value `never' overrides that option the
398 `init': Called once for each buffer. The backend can check for external
399 programs and files and load any required libraries. Raising an error here
400 will show up in message log once, and the backend will not be used for
403 `post-completion': Called after a completion candidate has been inserted
404 into the buffer. The second argument is the candidate. Can be used to
405 modify it, e.g. to expand a snippet.
407 The backend should return nil for all commands it does not support or
408 does not know about. It should also be callable interactively and use
409 `company-begin-backend' to start itself in that case.
414 An element of `company-backends' can also be a list of backends. The
415 completions from backends in such groups are merged, but only from those
416 backends which return the same `prefix'.
418 If a backend command takes a candidate as an argument (e.g. `meta'), the
419 call is dispatched to the backend the candidate came from. In other
420 cases (except for `duplicates' and `sorted'), the first non-nil value among
421 all the backends is returned.
423 The group can also contain keywords. Currently, `:with' and `:sorted'
424 keywords are defined. If the group contains keyword `:with', the backends
425 listed after this keyword are ignored for the purpose of the `prefix'
426 command. If the group contains keyword `:sorted', the final list of
427 candidates is not sorted after concatenation.
429 Asynchronous backends
430 =====================
432 The return value of each command can also be a cons (:async . FETCHER)
433 where FETCHER is a function of one argument, CALLBACK. When the data
434 arrives, FETCHER must call CALLBACK and pass it the appropriate return
435 value, as described above. That call must happen in the same buffer as
436 where completion was initiated.
438 True asynchronous operation is only supported for command `candidates', and
439 only during idle completion. Other commands will block the user interface,
440 even if the backend uses the asynchronous calling convention."
444 ,@(mapcar (lambda (b) `(const :tag ,(cdr b) ,(car b)))
445 company-safe-backends)
446 (symbol :tag "User defined")
447 (repeat :tag "Merged backends"
448 (choice :tag "backend"
449 ,@(mapcar (lambda (b)
450 `(const :tag ,(cdr b) ,(car b)))
451 company-safe-backends)
452 (const :tag "With" :with)
453 (symbol :tag "User defined"))))))
455 (put 'company-backends 'safe-local-variable 'company-safe-backends-p)
457 (defcustom company-transformers nil
458 "Functions to change the list of candidates received from backends.
460 Each function gets called with the return value of the previous one.
461 The first one gets passed the list of candidates, already sorted and
464 (const :tag "None" nil)
465 (const :tag "Sort by occurrence" (company-sort-by-occurrence))
466 (const :tag "Sort by backend importance"
467 (company-sort-by-backend-importance))
468 (repeat :tag "User defined" (function))))
470 (defcustom company-completion-started-hook nil
471 "Hook run when company starts completing.
472 The hook is called with one argument that is non-nil if the completion was
476 (defcustom company-completion-cancelled-hook nil
477 "Hook run when company cancels completing.
478 The hook is called with one argument that is non-nil if the completion was
482 (defcustom company-completion-finished-hook nil
483 "Hook run when company successfully completes.
484 The hook is called with the selected candidate as an argument.
486 If you indend to use it to post-process candidates from a specific
487 backend, consider using the `post-completion' command instead."
490 (defcustom company-minimum-prefix-length 3
491 "The minimum prefix length for idle completion."
492 :type '(integer :tag "prefix length"))
494 (defcustom company-abort-manual-when-too-short nil
495 "If enabled, cancel a manually started completion when the prefix gets
496 shorter than both `company-minimum-prefix-length' and the length of the
497 prefix it was started from."
499 :package-version '(company . "0.8.0"))
501 (defcustom company-require-match 'company-explicit-action-p
502 "If enabled, disallow non-matching input.
503 This can be a function do determine if a match is required.
505 This can be overridden by the backend, if it returns t or `never' to
506 `require-match'. `company-auto-complete' also takes precedence over this."
507 :type '(choice (const :tag "Off" nil)
508 (function :tag "Predicate function")
509 (const :tag "On, if user interaction took place"
510 'company-explicit-action-p)
511 (const :tag "On" t)))
513 (defcustom company-auto-complete nil
514 "Determines when to auto-complete.
515 If this is enabled, all characters from `company-auto-complete-chars'
516 trigger insertion of the selected completion candidate.
517 This can also be a function."
518 :type '(choice (const :tag "Off" nil)
519 (function :tag "Predicate function")
520 (const :tag "On, if user interaction took place"
521 'company-explicit-action-p)
522 (const :tag "On" t)))
524 (defcustom company-auto-complete-chars '(?\ ?\) ?.)
525 "Determines which characters trigger auto-completion.
526 See `company-auto-complete'. If this is a string, each string character
527 tiggers auto-completion. If it is a list of syntax description characters (see
528 `modify-syntax-entry'), all characters with that syntax auto-complete.
530 This can also be a function, which is called with the new input and should
531 return non-nil if company should auto-complete.
533 A character that is part of a valid candidate never triggers auto-completion."
534 :type '(choice (string :tag "Characters")
536 (const :tag "Whitespace" ?\ )
537 (const :tag "Symbol" ?_)
538 (const :tag "Opening parentheses" ?\()
539 (const :tag "Closing parentheses" ?\))
540 (const :tag "Word constituent" ?w)
541 (const :tag "Punctuation." ?.)
542 (const :tag "String quote." ?\")
543 (const :tag "Paired delimiter." ?$)
544 (const :tag "Expression quote or prefix operator." ?\')
545 (const :tag "Comment starter." ?<)
546 (const :tag "Comment ender." ?>)
547 (const :tag "Character-quote." ?/)
548 (const :tag "Generic string fence." ?|)
549 (const :tag "Generic comment fence." ?!))
550 (function :tag "Predicate function")))
552 (defcustom company-idle-delay .5
553 "The idle delay in seconds until completion starts automatically.
554 The prefix still has to satisfy `company-minimum-prefix-length' before that
555 happens. The value of nil means no idle completion."
556 :type '(choice (const :tag "never (nil)" nil)
557 (const :tag "immediate (0)" 0)
558 (number :tag "seconds")))
560 (defcustom company-begin-commands '(self-insert-command
561 org-self-insert-command
562 orgtbl-self-insert-command
567 "A list of commands after which idle completion is allowed.
568 If this is t, it can show completions after any command except a few from a
569 pre-defined list. See `company-idle-delay'.
571 Alternatively, any command with a non-nil `company-begin' property is
572 treated as if it was on this list."
573 :type '(choice (const :tag "Any command" t)
574 (const :tag "Self insert command" '(self-insert-command))
575 (repeat :tag "Commands" function))
576 :package-version '(company . "0.8.4"))
578 (defcustom company-continue-commands '(not save-buffer save-some-buffers
579 save-buffers-kill-terminal
580 save-buffers-kill-emacs)
581 "A list of commands that are allowed during completion.
582 If this is t, or if `company-begin-commands' is t, any command is allowed.
583 Otherwise, the value must be a list of symbols. If it starts with `not',
584 the cdr is the list of commands that abort completion. Otherwise, all
585 commands except those in that list, or in `company-begin-commands', or
586 commands in the `company-' namespace, abort completion."
587 :type '(choice (const :tag "Any command" t)
588 (cons :tag "Any except"
590 (repeat :tag "Commands" function))
591 (repeat :tag "Commands" function)))
593 (defcustom company-show-numbers nil
594 "If enabled, show quick-access numbers for the first ten candidates."
595 :type '(choice (const :tag "off" nil)
596 (const :tag "on" t)))
598 (defcustom company-selection-wrap-around nil
599 "If enabled, selecting item before first or after last wraps around."
600 :type '(choice (const :tag "off" nil)
601 (const :tag "on" t)))
603 (defvar company-async-wait 0.03
604 "Pause between checks to see if the value's been set when turning an
605 asynchronous call into synchronous.")
607 (defvar company-async-timeout 2
608 "Maximum wait time for a value to be set during asynchronous call.")
610 ;;; mode ;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;
612 (defvar company-mode-map (make-sparse-keymap)
613 "Keymap used by `company-mode'.")
615 (defvar company-active-map
616 (let ((keymap (make-sparse-keymap)))
617 (define-key keymap "\e\e\e" 'company-abort)
618 (define-key keymap "\C-g" 'company-abort)
619 (define-key keymap (kbd "M-n") 'company-select-next)
620 (define-key keymap (kbd "M-p") 'company-select-previous)
621 (define-key keymap (kbd "<down>") 'company-select-next-or-abort)
622 (define-key keymap (kbd "<up>") 'company-select-previous-or-abort)
623 (define-key keymap [remap scroll-up-command] 'company-next-page)
624 (define-key keymap [remap scroll-down-command] 'company-previous-page)
625 (define-key keymap [down-mouse-1] 'ignore)
626 (define-key keymap [down-mouse-3] 'ignore)
627 (define-key keymap [mouse-1] 'company-complete-mouse)
628 (define-key keymap [mouse-3] 'company-select-mouse)
629 (define-key keymap [up-mouse-1] 'ignore)
630 (define-key keymap [up-mouse-3] 'ignore)
631 (define-key keymap [return] 'company-complete-selection)
632 (define-key keymap (kbd "RET") 'company-complete-selection)
633 (define-key keymap [tab] 'company-complete-common)
634 (define-key keymap (kbd "TAB") 'company-complete-common)
635 (define-key keymap (kbd "<f1>") 'company-show-doc-buffer)
636 (define-key keymap (kbd "C-h") 'company-show-doc-buffer)
637 (define-key keymap "\C-w" 'company-show-location)
638 (define-key keymap "\C-s" 'company-search-candidates)
639 (define-key keymap "\C-\M-s" 'company-filter-candidates)
641 (define-key keymap (read-kbd-macro (format "M-%d" i)) 'company-complete-number))
643 "Keymap that is enabled during an active completion.")
645 (defvar company--disabled-backends nil)
647 (defun company-init-backend (backend)
648 (and (symbolp backend)
649 (not (fboundp backend))
650 (ignore-errors (require backend nil t)))
655 (funcall backend 'init)
656 (put backend 'company-init t))
658 (put backend 'company-init 'failed)
659 (unless (memq backend company--disabled-backends)
660 (message "Company backend '%s' could not be initialized:\n%s"
661 backend (error-message-string err)))
662 (cl-pushnew backend company--disabled-backends)
664 ;; No initialization for lambdas.
665 ((functionp backend) t)
666 (t ;; Must be a list.
667 (cl-dolist (b backend)
669 (company-init-backend b))))))
671 (defcustom company-lighter-base "company"
672 "Base string to use for the `company-mode' lighter."
674 :package-version '(company . "0.8.10"))
676 (defvar company-lighter '(" "
679 (if (consp company-backend)
680 (company--group-lighter (nth company-selection
682 company-lighter-base)
683 (symbol-name company-backend)))
684 company-lighter-base))
685 "Mode line lighter for Company.
687 The value of this variable is a mode line template as in
688 `mode-line-format'.")
690 (put 'company-lighter 'risky-local-variable t)
693 (define-minor-mode company-mode
694 "\"complete anything\"; is an in-buffer completion framework.
695 Completion starts automatically, depending on the values
696 `company-idle-delay' and `company-minimum-prefix-length'.
698 Completion can be controlled with the commands:
699 `company-complete-common', `company-complete-selection', `company-complete',
700 `company-select-next', `company-select-previous'. If these commands are
701 called before `company-idle-delay', completion will also start.
703 Completions can be searched with `company-search-candidates' or
704 `company-filter-candidates'. These can be used while completion is
707 The completion data is retrieved using `company-backends' and displayed
708 using `company-frontends'. If you want to start a specific backend, call
709 it interactively or use `company-begin-backend'.
711 By default, the completions list is sorted alphabetically, unless the
712 backend chooses otherwise, or `company-transformers' changes it later.
714 regular keymap (`company-mode-map'):
717 keymap during active completions (`company-active-map'):
719 \\{company-active-map}"
720 nil company-lighter company-mode-map
723 (when (eq company-idle-delay t)
724 (setq company-idle-delay 0)
725 (warn "Setting `company-idle-delay' to t is deprecated. Set it to 0 instead."))
726 (add-hook 'pre-command-hook 'company-pre-command nil t)
727 (add-hook 'post-command-hook 'company-post-command nil t)
728 (mapc 'company-init-backend company-backends))
729 (remove-hook 'pre-command-hook 'company-pre-command t)
730 (remove-hook 'post-command-hook 'company-post-command t)
732 (kill-local-variable 'company-point)))
734 (defcustom company-global-modes t
735 "Modes for which `company-mode' mode is turned on by `global-company-mode'.
736 If nil, means no modes. If t, then all major modes have it turned on.
737 If a list, it should be a list of `major-mode' symbol names for which
738 `company-mode' should be automatically turned on. The sense of the list is
739 negated if it begins with `not'. For example:
741 means that `company-mode' is turned on for buffers in C and C++ modes only.
743 means that `company-mode' is always turned on except in `message-mode' buffers."
744 :type '(choice (const :tag "none" nil)
746 (set :menu-tag "mode specific" :tag "modes"
748 (const :tag "Except" not)
749 (repeat :inline t (symbol :tag "mode")))))
752 (define-globalized-minor-mode global-company-mode company-mode company-mode-on)
754 (defun company-mode-on ()
755 (when (and (not (or noninteractive (eq (aref (buffer-name) 0) ?\s)))
756 (cond ((eq company-global-modes t)
758 ((eq (car-safe company-global-modes) 'not)
759 (not (memq major-mode (cdr company-global-modes))))
760 (t (memq major-mode company-global-modes))))
763 (defsubst company-assert-enabled ()
765 (company-uninstall-map)
766 (error "Company not enabled")))
768 ;;; keymaps ;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;
770 (defvar-local company-my-keymap nil)
772 (defvar company-emulation-alist '((t . nil)))
774 (defsubst company-enable-overriding-keymap (keymap)
775 (company-uninstall-map)
776 (setq company-my-keymap keymap))
778 (defun company-ensure-emulation-alist ()
779 (unless (eq 'company-emulation-alist (car emulation-mode-map-alists))
780 (setq emulation-mode-map-alists
781 (cons 'company-emulation-alist
782 (delq 'company-emulation-alist emulation-mode-map-alists)))))
784 (defun company-install-map ()
785 (unless (or (cdar company-emulation-alist)
786 (null company-my-keymap))
787 (setf (cdar company-emulation-alist) company-my-keymap)))
789 (defun company-uninstall-map ()
790 (setf (cdar company-emulation-alist) nil))
793 ;; Emacs calculates the active keymaps before reading the event. That means we
794 ;; cannot change the keymap from a timer. So we send a bogus command.
795 ;; XXX: Even in Emacs 24.4, seems to be needed in the terminal.
796 (defun company-ignore ()
798 (setq this-command last-command))
800 (global-set-key '[company-dummy-event] 'company-ignore)
802 (defun company-input-noop ()
803 (push 'company-dummy-event unread-command-events))
805 (defun company--posn-col-row (posn)
806 (let ((col (car (posn-col-row posn)))
807 ;; `posn-col-row' doesn't work well with lines of different height.
808 ;; `posn-actual-col-row' doesn't handle multiple-width characters.
809 (row (cdr (or (posn-actual-col-row posn)
810 ;; When position is non-visible for some reason.
811 (posn-col-row posn)))))
812 (when (and header-line-format (version< emacs-version "24.3.93.3"))
813 ;; http://debbugs.gnu.org/18384
815 (cons (+ col (window-hscroll)) row)))
817 (defun company--col-row (&optional pos)
818 (company--posn-col-row (posn-at-point pos)))
820 (defun company--row (&optional pos)
821 (cdr (company--col-row pos)))
823 ;;; backends ;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;
825 (defvar-local company-backend nil)
827 (defun company-grab (regexp &optional expression limit)
828 (when (looking-back regexp limit)
829 (or (match-string-no-properties (or expression 0)) "")))
831 (defun company-grab-line (regexp &optional expression)
832 "Return a match string for REGEXP if it matches text before point.
833 If EXPRESSION is non-nil, return the match string for the respective
834 parenthesized expression in REGEXP.
835 Matching is limited to the current line."
836 (let ((inhibit-field-text-motion t))
837 (company-grab regexp expression (point-at-bol))))
839 (defun company-grab-symbol ()
840 "If point is at the end of a symbol, return it.
841 Otherwise, if point is not inside a symbol, return an empty string."
842 (if (looking-at "\\_>")
843 (buffer-substring (point) (save-excursion (skip-syntax-backward "w_")
845 (unless (and (char-after) (memq (char-syntax (char-after)) '(?w ?_)))
848 (defun company-grab-word ()
849 "If point is at the end of a word, return it.
850 Otherwise, if point is not inside a symbol, return an empty string."
851 (if (looking-at "\\>")
852 (buffer-substring (point) (save-excursion (skip-syntax-backward "w")
854 (unless (and (char-after) (eq (char-syntax (char-after)) ?w))
857 (defun company-grab-symbol-cons (idle-begin-after-re &optional max-len)
858 "Return a string SYMBOL or a cons (SYMBOL . t).
859 SYMBOL is as returned by `company-grab-symbol'. If the text before point
860 matches IDLE-BEGIN-AFTER-RE, return it wrapped in a cons."
861 (let ((symbol (company-grab-symbol)))
864 (forward-char (- (length symbol)))
865 (if (looking-back idle-begin-after-re (if max-len
867 (line-beginning-position)))
871 (defun company-in-string-or-comment ()
872 "Return non-nil if point is within a string or comment."
873 (let ((ppss (syntax-ppss)))
874 (or (car (setq ppss (nthcdr 3 ppss)))
875 (car (setq ppss (cdr ppss)))
878 (defun company-call-backend (&rest args)
879 (company--force-sync #'company-call-backend-raw args company-backend))
881 (defun company--force-sync (fun args backend)
882 (let ((value (apply fun args)))
883 (if (not (eq (car-safe value) :async))
886 (start (time-to-seconds)))
888 (lambda (result) (setq res result)))
889 (while (eq res 'trash)
890 (if (> (- (time-to-seconds) start) company-async-timeout)
891 (error "Company: backend %s async timeout with args %s"
893 (sleep-for company-async-wait)))
896 (defun company-call-backend-raw (&rest args)
897 (condition-case-unless-debug err
898 (if (functionp company-backend)
899 (apply company-backend args)
900 (apply #'company--multi-backend-adapter company-backend args))
901 (error (error "Company: backend %s error \"%s\" with args %s"
902 company-backend (error-message-string err) args))))
904 (defun company--multi-backend-adapter (backends command &rest args)
905 (let ((backends (cl-loop for b in backends
906 when (not (and (symbolp b)
907 (eq 'failed (get b 'company-init))))
910 (when (eq command 'prefix)
911 (setq backends (butlast backends (length (member :with backends)))))
913 (unless (memq command '(sorted))
914 (setq backends (cl-delete-if #'keywordp backends)))
918 (company--multi-backend-adapter-candidates backends (car args)))
919 (`sorted (memq :sorted backends))
921 ((or `prefix `ignore-case `no-cache `require-match)
923 (cl-dolist (backend backends)
924 (when (setq value (company--force-sync
925 backend (cons command args) backend))
926 (cl-return value)))))
928 (let ((arg (car args)))
929 (when (> (length arg) 0)
930 (let ((backend (or (get-text-property 0 'company-backend arg)
932 (apply backend command args))))))))
934 (defun company--multi-backend-adapter-candidates (backends prefix)
935 (let ((pairs (cl-loop for backend in (cdr backends)
936 when (equal (company--prefix-str
937 (funcall backend 'prefix))
939 collect (cons (funcall backend 'candidates prefix)
944 (propertize str 'company-backend b))
946 (when (equal (company--prefix-str (funcall (car backends) 'prefix)) prefix)
947 ;; Small perf optimization: don't tag the candidates received
948 ;; from the first backend in the group.
949 (push (cons (funcall (car backends) 'candidates prefix)
952 (company--merge-async pairs (lambda (values) (apply #'append values)))))
954 (defun company--merge-async (pairs merger)
955 (let ((async (cl-loop for pair in pairs
957 (eq :async (car-safe (car pair))))))
959 (funcall merger (cl-loop for (val . mapper) in pairs
960 collect (funcall mapper val)))
965 (pending (mapcar #'car pairs))
976 (this-finisher (lambda (res)
977 (setq pending (delq val pending))
978 (setcar cell (funcall mapper res))
979 (funcall finisher))))
980 (if (not (eq :async (car-safe val)))
981 (funcall this-finisher val)
982 (let ((fetcher (cdr val)))
983 (funcall fetcher this-finisher)))))))))))
985 (defun company--prefix-str (prefix)
986 (or (car-safe prefix) prefix))
988 ;;; completion mechanism ;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;
990 (defvar-local company-prefix nil)
992 (defvar-local company-candidates nil)
994 (defvar-local company-candidates-length nil)
996 (defvar-local company-candidates-cache nil)
998 (defvar-local company-candidates-predicate nil)
1000 (defvar-local company-common nil)
1002 (defvar-local company-selection 0)
1004 (defvar-local company-selection-changed nil)
1006 (defvar-local company--manual-action nil
1007 "Non-nil, if manual completion took place.")
1009 (defvar-local company--manual-prefix nil)
1011 (defvar company--auto-completion nil
1012 "Non-nil when current candidate is being inserted automatically.
1013 Controlled by `company-auto-complete'.")
1015 (defvar-local company--point-max nil)
1017 (defvar-local company-point nil)
1019 (defvar company-timer nil)
1021 (defsubst company-strip-prefix (str)
1022 (substring str (length company-prefix)))
1024 (defun company--insert-candidate (candidate)
1025 (when (> (length candidate) 0)
1026 (setq candidate (substring-no-properties candidate))
1027 ;; XXX: Return value we check here is subject to change.
1028 (if (eq (company-call-backend 'ignore-case) 'keep-prefix)
1029 (insert (company-strip-prefix candidate))
1030 (unless (equal company-prefix candidate)
1031 (delete-region (- (point) (length company-prefix)) (point))
1032 (insert candidate)))))
1034 (defmacro company-with-candidate-inserted (candidate &rest body)
1035 "Evaluate BODY with CANDIDATE temporarily inserted.
1036 This is a tool for backends that need candidates inserted before they
1037 can retrieve meta-data for them."
1038 (declare (indent 1))
1039 `(let ((inhibit-modification-hooks t)
1040 (inhibit-point-motion-hooks t)
1041 (modified-p (buffer-modified-p)))
1042 (company--insert-candidate ,candidate)
1045 (delete-region company-point (point))
1046 (set-buffer-modified-p modified-p))))
1048 (defun company-explicit-action-p ()
1049 "Return whether explicit completion action was taken by the user."
1050 (or company--manual-action
1051 company-selection-changed))
1053 (defun company-reformat (candidate)
1054 ;; company-ispell needs this, because the results are always lower-case
1055 ;; It's mory efficient to fix it only when they are displayed.
1056 ;; FIXME: Adopt the current text's capitalization instead?
1057 (if (eq (company-call-backend 'ignore-case) 'keep-prefix)
1058 (concat company-prefix (substring candidate (length company-prefix)))
1061 (defun company--should-complete ()
1062 (and (eq company-idle-delay 'now)
1063 (not (or buffer-read-only overriding-terminal-local-map
1064 overriding-local-map))
1065 ;; Check if in the middle of entering a key combination.
1066 (or (equal (this-command-keys-vector) [])
1067 (not (keymapp (key-binding (this-command-keys-vector)))))
1068 (not (and transient-mark-mode mark-active))))
1070 (defun company--should-continue ()
1071 (or (eq t company-begin-commands)
1072 (eq t company-continue-commands)
1073 (if (eq 'not (car company-continue-commands))
1074 (not (memq this-command (cdr company-continue-commands)))
1075 (or (memq this-command company-begin-commands)
1076 (memq this-command company-continue-commands)
1077 (and (symbolp this-command)
1078 (string-match-p "\\`company-" (symbol-name this-command)))))))
1080 (defun company-call-frontends (command)
1081 (dolist (frontend company-frontends)
1082 (condition-case-unless-debug err
1083 (funcall frontend command)
1084 (error (error "Company: frontend %s error \"%s\" on command %s"
1085 frontend (error-message-string err) command)))))
1087 (defun company-set-selection (selection &optional force-update)
1089 (if company-selection-wrap-around
1090 (mod selection company-candidates-length)
1091 (max 0 (min (1- company-candidates-length) selection))))
1092 (when (or force-update (not (equal selection company-selection)))
1093 (setq company-selection selection
1094 company-selection-changed t)
1095 (company-call-frontends 'update)))
1097 (defun company--group-lighter (candidate base)
1098 (let ((backend (or (get-text-property 0 'company-backend candidate)
1099 (car company-backend))))
1100 (when (and backend (symbolp backend))
1101 (let ((name (replace-regexp-in-string "company-\\|-company" ""
1102 (symbol-name backend))))
1103 (format "%s-<%s>" base name)))))
1105 (defun company-update-candidates (candidates)
1106 (setq company-candidates-length (length candidates))
1107 (if company-selection-changed
1108 ;; Try to restore the selection
1109 (let ((selected (nth company-selection company-candidates)))
1110 (setq company-selection 0
1111 company-candidates candidates)
1115 (let ((candidate (pop candidates)))
1116 (when (and (string= candidate selected)
1117 (equal (company-call-backend 'annotation candidate)
1118 (company-call-backend 'annotation selected)))
1120 (cl-incf company-selection))
1121 (setq company-selection 0
1122 company-selection-changed nil))))
1123 (setq company-selection 0
1124 company-candidates candidates))
1125 ;; Calculate common.
1126 (let ((completion-ignore-case (company-call-backend 'ignore-case)))
1127 ;; We want to support non-prefix completion, so filtering is the
1128 ;; responsibility of each respective backend, not ours.
1129 ;; On the other hand, we don't want to replace non-prefix input in
1130 ;; `company-complete-common', unless there's only one candidate.
1131 (setq company-common
1132 (if (cdr company-candidates)
1133 (let ((common (try-completion "" company-candidates)))
1134 (when (string-prefix-p company-prefix common
1135 completion-ignore-case)
1137 (car company-candidates)))))
1139 (defun company-calculate-candidates (prefix)
1140 (let ((candidates (cdr (assoc prefix company-candidates-cache)))
1141 (ignore-case (company-call-backend 'ignore-case)))
1143 (when company-candidates-cache
1144 (let ((len (length prefix))
1145 (completion-ignore-case ignore-case)
1147 (cl-dotimes (i (1+ len))
1148 (when (setq prev (cdr (assoc (substring prefix 0 (- len i))
1149 company-candidates-cache)))
1150 (setq candidates (all-completions prefix prev))
1153 ;; No cache match, call the backend.
1154 (setq candidates (company--preprocess-candidates
1155 (company--fetch-candidates prefix)))
1157 (push (cons prefix candidates) company-candidates-cache)))
1158 ;; Only now apply the predicate and transformers.
1159 (setq candidates (company--postprocess-candidates candidates))
1161 (if (or (cdr candidates)
1162 (not (eq t (compare-strings (car candidates) nil nil
1163 prefix nil nil ignore-case))))
1165 ;; Already completed and unique; don't start.
1168 (defun company--fetch-candidates (prefix)
1169 (let ((c (if company--manual-action
1170 (company-call-backend 'candidates prefix)
1171 (company-call-backend-raw 'candidates prefix)))
1173 (if (not (eq (car c) :async))
1175 (let ((buf (current-buffer))
1176 (win (selected-window))
1177 (tick (buffer-chars-modified-tick))
1179 (backend company-backend))
1182 (lambda (candidates)
1183 (if (not (and candidates (eq res 'done)))
1184 ;; There's no completions to display,
1185 ;; or the fetcher called us back right away.
1186 (setq res candidates)
1187 (setq company-backend backend
1188 company-candidates-cache
1190 (company--preprocess-candidates candidates))))
1192 (company-idle-begin buf win tick pt)
1193 (unless company-candidates
1194 (setq company-backend nil
1195 company-candidates-cache nil)))))))
1196 ;; FIXME: Relying on the fact that the callers
1197 ;; will interpret nil as "do nothing" is shaky.
1198 ;; A throw-catch would be one possible improvement.
1200 (progn (setq res 'done) nil)))))
1202 (defun company--preprocess-candidates (candidates)
1203 (unless (company-call-backend 'sorted)
1204 (setq candidates (sort candidates 'string<)))
1205 (when (company-call-backend 'duplicates)
1206 (setq candidates (company--strip-duplicates candidates)))
1209 (defun company--postprocess-candidates (candidates)
1210 (when (or company-candidates-predicate company-transformers)
1211 (setq candidates (copy-sequence candidates)))
1212 (when company-candidates-predicate
1213 (setq candidates (cl-delete-if-not company-candidates-predicate candidates)))
1214 (company--transform-candidates candidates))
1216 (defun company--strip-duplicates (candidates)
1218 (str (car candidates))
1219 (ref (cdr candidates))
1222 (setq str2 (pop ref))
1223 (if (not (equal str str2))
1228 (setq anno2 (company-call-backend
1231 ((null anno2)) ; Skip it.
1232 ((when (eq annos 'unk)
1233 (let ((ann1 (company-call-backend 'annotation str)))
1235 ;; No annotation on the earlier element, drop it.
1237 (setq annos (list ann1))
1239 (setq annos (list anno2))
1241 ((member anno2 annos)) ; Also skip.
1244 (push str res) ; Maintain ordering.
1246 (when str (push str res))
1249 (defun company--transform-candidates (candidates)
1250 (let ((c candidates))
1251 (dolist (tr company-transformers)
1252 (setq c (funcall tr c)))
1255 (defcustom company-occurrence-weight-function
1256 #'company-occurrence-prefer-closest-above
1257 "Function to weigh matches in `company-sort-by-occurrence'.
1258 It's called with three arguments: cursor position, the beginning and the
1261 (const :tag "First above point, then below point"
1262 company-occurrence-prefer-closest-above)
1263 (const :tag "Prefer closest in any direction"
1264 company-occurrence-prefer-any-closest)))
1266 (defun company-occurrence-prefer-closest-above (pos match-beg match-end)
1267 "Give priority to the matches above point, then those below point."
1268 (if (< match-beg pos)
1270 (- match-beg (window-start))))
1272 (defun company-occurrence-prefer-any-closest (pos _match-beg match-end)
1273 "Give priority to the matches closest to the point."
1274 (abs (- pos match-end)))
1276 (defun company-sort-by-occurrence (candidates)
1277 "Sort CANDIDATES according to their occurrences.
1278 Searches for each in the currently visible part of the current buffer and
1279 prioritizes the matches according to `company-occurrence-weight-function'.
1280 The rest of the list is appended unchanged.
1281 Keywords and function definition names are ignored."
1282 (let* ((w-start (window-start))
1283 (w-end (window-end))
1284 (start-point (point))
1292 (while (search-forward candidate w-end t)
1293 (when (and (not (eq (point) start-point))
1295 (company--occurrence-predicate)))
1299 (funcall company-occurrence-weight-function
1307 (mapcar #'car (sort occurs (lambda (e1 e2) (<= (cdr e1) (cdr e2)))))
1310 (defun company--occurrence-predicate ()
1311 (let ((beg (match-beginning 0))
1312 (end (match-end 0)))
1315 (and (not (memq (get-text-property (1- (point)) 'face)
1316 '(font-lock-function-name-face
1317 font-lock-keyword-face)))
1318 (let ((prefix (company--prefix-str
1319 (company-call-backend 'prefix))))
1320 (and (stringp prefix)
1321 (= (length prefix) (- end beg))))))))
1323 (defun company-sort-by-backend-importance (candidates)
1324 "Sort CANDIDATES as two priority groups.
1325 If `company-backend' is a function, do nothing. If it's a list, move
1326 candidates from backends before keyword `:with' to the front. Candidates
1327 from the rest of the backends in the group, if any, will be left at the end."
1328 (if (functionp company-backend)
1330 (let ((low-priority (cdr (memq :with company-backend))))
1331 (if (null low-priority)
1336 (let ((b2 (get-text-property 0 'company-backend c2)))
1337 (and b2 (memq b2 low-priority)))
1338 (let ((b1 (get-text-property 0 'company-backend c1)))
1339 (or (not b1) (not (memq b1 low-priority)))))))))))
1341 (defun company-idle-begin (buf win tick pos)
1342 (and (eq buf (current-buffer))
1343 (eq win (selected-window))
1344 (eq tick (buffer-chars-modified-tick))
1346 (when (company-auto-begin)
1347 (company-input-noop)
1348 (let ((this-command 'company-idle-begin))
1349 (company-post-command)))))
1351 (defun company-auto-begin ()
1353 (not company-candidates)
1354 (let ((company-idle-delay 'now))
1355 (condition-case-unless-debug err
1358 ;; Return non-nil if active.
1360 (error (message "Company: An error occurred in auto-begin")
1361 (message "%s" (error-message-string err))
1363 (quit (company-cancel))))))
1365 (defun company-manual-begin ()
1367 (company-assert-enabled)
1368 (setq company--manual-action t)
1370 (let ((company-minimum-prefix-length 0))
1371 (or company-candidates
1372 (company-auto-begin)))
1373 (unless company-candidates
1374 (setq company--manual-action nil))))
1376 (defun company-other-backend (&optional backward)
1377 (interactive (list current-prefix-arg))
1378 (company-assert-enabled)
1379 (let* ((after (if company-backend
1380 (cdr (member company-backend company-backends))
1382 (before (cdr (member company-backend (reverse company-backends))))
1384 (append before (reverse after))
1385 (append after (reverse before)))))
1387 (cl-dolist (backend next)
1388 (when (ignore-errors (company-begin-backend backend))
1390 (unless company-candidates
1391 (error "No other backend")))
1393 (defun company-require-match-p ()
1394 (let ((backend-value (company-call-backend 'require-match)))
1395 (or (eq backend-value t)
1396 (and (not (eq backend-value 'never))
1397 (if (functionp company-require-match)
1398 (funcall company-require-match)
1399 (eq company-require-match t))))))
1401 (defun company-auto-complete-p (input)
1402 "Return non-nil, if input starts with punctuation or parentheses."
1403 (and (if (functionp company-auto-complete)
1404 (funcall company-auto-complete)
1405 company-auto-complete)
1406 (if (functionp company-auto-complete-chars)
1407 (funcall company-auto-complete-chars input)
1408 (if (consp company-auto-complete-chars)
1409 (memq (char-syntax (string-to-char input))
1410 company-auto-complete-chars)
1411 (string-match (substring input 0 1) company-auto-complete-chars)))))
1413 (defun company--incremental-p ()
1414 (and (> (point) company-point)
1415 (> (point-max) company--point-max)
1416 (not (eq this-command 'backward-delete-char-untabify))
1417 (equal (buffer-substring (- company-point (length company-prefix))
1421 (defun company--continue-failed (new-prefix)
1422 (let ((input (buffer-substring-no-properties (point) company-point)))
1424 ((company-auto-complete-p input)
1427 (goto-char company-point)
1428 (let ((company--auto-completion t))
1429 (company-complete-selection))
1431 ((and (or (not (company-require-match-p))
1432 ;; Don't require match if the new prefix
1433 ;; doesn't continue the old one, and the latter was a match.
1434 (not (stringp new-prefix))
1435 (<= (length new-prefix) (length company-prefix)))
1436 (member company-prefix company-candidates))
1437 ;; Last input was a success,
1438 ;; but we're treating it as an abort + input anyway,
1439 ;; like the `unique' case below.
1440 (company-cancel 'non-unique))
1441 ((company-require-match-p)
1442 ;; Wrong incremental input, but required match.
1443 (delete-char (- (length input)))
1445 (message "Matching input is required")
1447 (t (company-cancel)))))
1449 (defun company--good-prefix-p (prefix)
1450 (and (stringp (company--prefix-str prefix)) ;excludes 'stop
1451 (or (eq (cdr-safe prefix) t)
1452 (let ((len (or (cdr-safe prefix) (length prefix))))
1453 (if company--manual-prefix
1454 (or (not company-abort-manual-when-too-short)
1455 ;; Must not be less than minimum or initial length.
1456 (>= len (min company-minimum-prefix-length
1457 (length company--manual-prefix))))
1458 (>= len company-minimum-prefix-length))))))
1460 (defun company--continue ()
1461 (when (company-call-backend 'no-cache company-prefix)
1462 ;; Don't complete existing candidates, fetch new ones.
1463 (setq company-candidates-cache nil))
1464 (let* ((new-prefix (company-call-backend 'prefix))
1465 (c (when (and (company--good-prefix-p new-prefix)
1466 (setq new-prefix (company--prefix-str new-prefix))
1467 (= (- (point) (length new-prefix))
1468 (- company-point (length company-prefix))))
1469 (company-calculate-candidates new-prefix))))
1472 ;; t means complete/unique.
1473 ;; Handle it like completion was aborted, to differentiate from user
1474 ;; calling one of Company's commands to insert the candidate,
1475 ;; not to trigger template expansion, etc.
1476 (company-cancel 'unique))
1478 ;; incremental match
1479 (setq company-prefix new-prefix)
1480 (company-update-candidates c)
1482 ((not (company--incremental-p))
1484 (t (company--continue-failed new-prefix)))))
1486 (defun company--begin-new ()
1488 (cl-dolist (backend (if company-backend
1489 ;; prefer manual override
1490 (list company-backend)
1493 (if (or (symbolp backend)
1494 (functionp backend))
1495 (when (or (not (symbolp backend))
1496 (eq t (get backend 'company-init))
1497 (unless (get backend 'company-init)
1498 (company-init-backend backend)))
1499 (funcall backend 'prefix))
1500 (company--multi-backend-adapter backend 'prefix)))
1502 (when (company--good-prefix-p prefix)
1503 (setq company-prefix (company--prefix-str prefix)
1504 company-backend backend
1505 c (company-calculate-candidates company-prefix))
1508 (when company--manual-action
1509 (message "No completion found"))
1511 ;; t means complete/unique.
1512 ;; Run the hooks anyway, to e.g. clear the cache.
1513 (company-cancel 'unique)))
1514 (when company--manual-action
1515 (setq company--manual-prefix prefix))
1516 (company-update-candidates c)
1517 (run-hook-with-args 'company-completion-started-hook
1518 (company-explicit-action-p))
1519 (company-call-frontends 'show)))
1522 (defun company--perform ()
1523 (or (and company-candidates (company--continue))
1524 (and (company--should-complete) (company--begin-new)))
1525 (if (not company-candidates)
1526 (setq company-backend nil)
1527 (setq company-point (point)
1528 company--point-max (point-max))
1529 (company-ensure-emulation-alist)
1530 (company-enable-overriding-keymap company-active-map)
1531 (company-call-frontends 'update)))
1533 (defun company-cancel (&optional result)
1534 (let ((prefix company-prefix)
1535 (backend company-backend))
1536 (setq company-backend nil
1538 company-candidates nil
1539 company-candidates-length nil
1540 company-candidates-cache nil
1541 company-candidates-predicate nil
1544 company-selection-changed nil
1545 company--manual-action nil
1546 company--manual-prefix nil
1547 company--point-max nil
1550 (cancel-timer company-timer))
1551 (company-echo-cancel t)
1552 (company-search-mode 0)
1553 (company-call-frontends 'hide)
1554 (company-enable-overriding-keymap nil)
1556 ;; FIXME: RESULT can also be e.g. `unique'. We should call
1557 ;; `company-completion-finished-hook' in that case, with right argument.
1558 (if (stringp result)
1559 (let ((company-backend backend))
1560 (company-call-backend 'pre-completion result)
1561 (run-hook-with-args 'company-completion-finished-hook result)
1562 (company-call-backend 'post-completion result))
1563 (run-hook-with-args 'company-completion-cancelled-hook result))))
1564 ;; Make return value explicit.
1567 (defun company-abort ()
1569 (company-cancel 'abort))
1571 (defun company-finish (result)
1572 (company--insert-candidate result)
1573 (company-cancel result))
1575 (defsubst company-keep (command)
1576 (and (symbolp command) (get command 'company-keep)))
1578 (defun company-pre-command ()
1579 (company--electric-restore-window-configuration)
1580 (unless (company-keep this-command)
1581 (condition-case-unless-debug err
1582 (when company-candidates
1583 (company-call-frontends 'pre-command)
1584 (unless (company--should-continue)
1586 (error (message "Company: An error occurred in pre-command")
1587 (message "%s" (error-message-string err))
1590 (cancel-timer company-timer)
1591 (setq company-timer nil))
1592 (company-echo-cancel t)
1593 (company-uninstall-map))
1595 (defun company-post-command ()
1596 (when (null this-command)
1597 ;; Happens when the user presses `C-g' while inside
1598 ;; `flyspell-post-command-hook', for example.
1599 ;; Or any other `post-command-hook' function that can call `sit-for',
1600 ;; or any quittable timer function.
1602 (setq this-command 'company-abort))
1603 (unless (company-keep this-command)
1604 (condition-case-unless-debug err
1606 (unless (equal (point) company-point)
1607 (let (company-idle-delay) ; Against misbehavior while debugging.
1608 (company--perform)))
1609 (if company-candidates
1610 (company-call-frontends 'post-command)
1611 (and (numberp company-idle-delay)
1612 (not defining-kbd-macro)
1613 (company--should-begin)
1615 (run-with-timer company-idle-delay nil
1617 (current-buffer) (selected-window)
1618 (buffer-chars-modified-tick) (point))))))
1619 (error (message "Company: An error occurred in post-command")
1620 (message "%s" (error-message-string err))
1622 (company-install-map))
1624 (defvar company--begin-inhibit-commands '(company-abort
1625 company-complete-mouse
1627 company-complete-common
1628 company-complete-selection
1629 company-complete-number)
1630 "List of commands after which idle completion is (still) disabled when
1631 `company-begin-commands' is t.")
1633 (defun company--should-begin ()
1634 (if (eq t company-begin-commands)
1635 (not (memq this-command company--begin-inhibit-commands))
1637 (memq this-command company-begin-commands)
1638 (and (symbolp this-command) (get this-command 'company-begin)))))
1640 ;;; search ;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;
1642 (defcustom company-search-regexp-function #'regexp-quote
1643 "Function to construct the search regexp from input.
1644 It's called with one argument, the current search input. It must return
1645 either a regexp without groups, or one where groups don't intersect and
1646 each one wraps a part of the input string."
1648 (const :tag "Exact match" regexp-quote)
1649 (const :tag "Words separated with spaces" company-search-words-regexp)
1650 (const :tag "Words separated with spaces, in any order"
1651 company-search-words-in-any-order-regexp)
1652 (const :tag "All characters in given order, with anything in between"
1653 company-search-flex-regexp)))
1655 (defvar-local company-search-string "")
1657 (defvar company-search-lighter '(" "
1658 (company-search-filtering "Filter" "Search")
1660 company-search-string
1663 (defvar-local company-search-filtering nil
1664 "Non-nil to filter the completion candidates by the search string")
1666 (defvar-local company--search-old-selection 0)
1668 (defvar-local company--search-old-changed nil)
1670 (defun company-search-words-regexp (input)
1671 (mapconcat (lambda (word) (format "\\(%s\\)" (regexp-quote word)))
1672 (split-string input " +" t) ".*"))
1674 (defun company-search-words-in-any-order-regexp (input)
1675 (let* ((words (mapcar (lambda (word) (format "\\(%s\\)" (regexp-quote word)))
1676 (split-string input " +" t)))
1677 (permutations (company--permutations words)))
1678 (mapconcat (lambda (words)
1679 (mapconcat #'identity words ".*"))
1683 (defun company-search-flex-regexp (input)
1684 (if (zerop (length input))
1686 (concat (regexp-quote (string (aref input 0)))
1687 (mapconcat (lambda (c)
1688 (concat "[^" (string c) "]*"
1689 (regexp-quote (string c))))
1690 (substring input 1) ""))))
1692 (defun company--permutations (lst)
1697 (mapcar (lambda (perm) (cons e perm))
1698 (company--permutations (cl-remove e lst :count 1))))
1701 (defun company--search (text lines)
1702 (let ((re (funcall company-search-regexp-function text))
1704 (cl-dolist (line lines)
1705 (when (string-match-p re line (length company-prefix))
1709 (defun company-search-keypad ()
1711 (let* ((name (symbol-name last-command-event))
1712 (last-command-event (aref name (1- (length name)))))
1713 (company-search-printing-char)))
1715 (defun company-search-printing-char ()
1717 (company--search-assert-enabled)
1718 (let ((ss (concat company-search-string (string last-command-event))))
1719 (when company-search-filtering
1720 (company--search-update-predicate ss))
1721 (company--search-update-string ss)))
1723 (defun company--search-update-predicate (ss)
1724 (let* ((re (funcall company-search-regexp-function ss))
1725 (company-candidates-predicate
1726 (and (not (string= re ""))
1727 company-search-filtering
1728 (lambda (candidate) (string-match re candidate))))
1729 (cc (company-calculate-candidates company-prefix)))
1730 (unless cc (error "No match"))
1731 (company-update-candidates cc)))
1733 (defun company--search-update-string (new)
1734 (let* ((pos (company--search new (nthcdr company-selection company-candidates))))
1737 (setq company-search-string new)
1738 (company-set-selection (+ company-selection pos) t))))
1740 (defun company--search-assert-input ()
1741 (company--search-assert-enabled)
1742 (when (string= company-search-string "")
1743 (error "Empty search string")))
1745 (defun company-search-repeat-forward ()
1746 "Repeat the incremental search in completion candidates forward."
1748 (company--search-assert-input)
1749 (let ((pos (company--search company-search-string
1750 (cdr (nthcdr company-selection
1751 company-candidates)))))
1754 (company-set-selection (+ company-selection pos 1) t))))
1756 (defun company-search-repeat-backward ()
1757 "Repeat the incremental search in completion candidates backwards."
1759 (company--search-assert-input)
1760 (let ((pos (company--search company-search-string
1761 (nthcdr (- company-candidates-length
1763 (reverse company-candidates)))))
1766 (company-set-selection (- company-selection pos 1) t))))
1768 (defun company-search-toggle-filtering ()
1769 "Toggle `company-search-filtering'."
1771 (company--search-assert-enabled)
1772 (setq company-search-filtering (not company-search-filtering))
1773 (let ((ss company-search-string))
1774 (company--search-update-predicate ss)
1775 (company--search-update-string ss)))
1777 (defun company-search-abort ()
1778 "Abort searching the completion candidates."
1780 (company--search-assert-enabled)
1781 (company-search-mode 0)
1782 (company-set-selection company--search-old-selection t)
1783 (setq company-selection-changed company--search-old-changed))
1785 (defun company-search-other-char ()
1787 (company--search-assert-enabled)
1788 (company-search-mode 0)
1789 (company--unread-last-input))
1791 (defun company-search-delete-char ()
1793 (company--search-assert-enabled)
1794 (if (string= company-search-string "")
1796 (let ((ss (substring company-search-string 0 -1)))
1797 (when company-search-filtering
1798 (company--search-update-predicate ss))
1799 (company--search-update-string ss))))
1801 (defvar company-search-map
1803 (keymap (make-keymap)))
1804 (if (fboundp 'max-char)
1805 (set-char-table-range (nth 1 keymap) (cons #x100 (max-char))
1806 'company-search-printing-char)
1808 ;; obsolete in Emacs 23
1809 (let ((l (generic-character-list))
1810 (table (nth 1 keymap)))
1812 (set-char-table-default table (car l) 'company-search-printing-char)
1813 (setq l (cdr l))))))
1814 (define-key keymap [t] 'company-search-other-char)
1816 (define-key keymap (make-string 1 i) 'company-search-other-char)
1819 (define-key keymap (vector i) 'company-search-printing-char)
1822 (define-key keymap (read (format "[kp-%s]" i)) 'company-search-keypad))
1823 (let ((meta-map (make-sparse-keymap)))
1824 (define-key keymap (char-to-string meta-prefix-char) meta-map)
1825 (define-key keymap [escape] meta-map))
1826 (define-key keymap (vector meta-prefix-char t) 'company-search-other-char)
1827 (define-key keymap (kbd "M-n") 'company-select-next)
1828 (define-key keymap (kbd "M-p") 'company-select-previous)
1829 (define-key keymap (kbd "<down>") 'company-select-next-or-abort)
1830 (define-key keymap (kbd "<up>") 'company-select-previous-or-abort)
1831 (define-key keymap "\e\e\e" 'company-search-other-char)
1832 (define-key keymap [escape escape escape] 'company-search-other-char)
1833 (define-key keymap (kbd "DEL") 'company-search-delete-char)
1834 (define-key keymap [backspace] 'company-search-delete-char)
1835 (define-key keymap "\C-g" 'company-search-abort)
1836 (define-key keymap "\C-s" 'company-search-repeat-forward)
1837 (define-key keymap "\C-r" 'company-search-repeat-backward)
1838 (define-key keymap "\C-o" 'company-search-toggle-filtering)
1840 (define-key keymap (read-kbd-macro (format "M-%d" i)) 'company-complete-number))
1842 "Keymap used for incrementally searching the completion candidates.")
1844 (define-minor-mode company-search-mode
1845 "Search mode for completion candidates.
1846 Don't start this directly, use `company-search-candidates' or
1847 `company-filter-candidates'."
1848 nil company-search-lighter nil
1849 (if company-search-mode
1850 (if (company-manual-begin)
1852 (setq company--search-old-selection company-selection
1853 company--search-old-changed company-selection-changed)
1854 (company-call-frontends 'update)
1855 (company-enable-overriding-keymap company-search-map))
1856 (setq company-search-mode nil))
1857 (kill-local-variable 'company-search-string)
1858 (kill-local-variable 'company-search-filtering)
1859 (kill-local-variable 'company--search-old-selection)
1860 (kill-local-variable 'company--search-old-changed)
1861 (when company-backend
1862 (company--search-update-predicate "")
1863 (company-call-frontends 'update))
1864 (company-enable-overriding-keymap company-active-map)))
1866 (defun company--search-assert-enabled ()
1867 (company-assert-enabled)
1868 (unless company-search-mode
1869 (company-uninstall-map)
1870 (error "Company not in search mode")))
1872 (defun company-search-candidates ()
1873 "Start searching the completion candidates incrementally.
1875 \\<company-search-map>Search can be controlled with the commands:
1876 - `company-search-repeat-forward' (\\[company-search-repeat-forward])
1877 - `company-search-repeat-backward' (\\[company-search-repeat-backward])
1878 - `company-search-abort' (\\[company-search-abort])
1879 - `company-search-delete-char' (\\[company-search-delete-char])
1881 Regular characters are appended to the search string.
1883 Customize `company-search-regexp-function' to change how the input
1884 is interpreted when searching.
1886 The command `company-search-toggle-filtering' (\\[company-search-toggle-filtering])
1887 uses the search string to filter the completion candidates."
1889 (company-search-mode 1))
1891 (defvar company-filter-map
1892 (let ((keymap (make-keymap)))
1893 (define-key keymap [remap company-search-printing-char]
1894 'company-filter-printing-char)
1895 (set-keymap-parent keymap company-search-map)
1897 "Keymap used for incrementally searching the completion candidates.")
1899 (defun company-filter-candidates ()
1900 "Start filtering the completion candidates incrementally.
1901 This works the same way as `company-search-candidates' immediately
1902 followed by `company-search-toggle-filtering'."
1904 (company-search-mode 1)
1905 (setq company-search-filtering t))
1907 ;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;
1909 (defun company-select-next (&optional arg)
1910 "Select the next candidate in the list.
1912 With ARG, move by that many elements."
1914 (when (company-manual-begin)
1915 (company-set-selection (+ (or arg 1) company-selection))))
1917 (defun company-select-previous (&optional arg)
1918 "Select the previous candidate in the list.
1920 With ARG, move by that many elements."
1922 (company-select-next (if arg (- arg) -1)))
1924 (defun company-select-next-or-abort (&optional arg)
1925 "Select the next candidate if more than one, else abort
1926 and invoke the normal binding.
1928 With ARG, move by that many elements."
1930 (if (> company-candidates-length 1)
1931 (company-select-next arg)
1933 (company--unread-last-input)))
1935 (defun company-select-previous-or-abort (&optional arg)
1936 "Select the previous candidate if more than one, else abort
1937 and invoke the normal binding.
1939 With ARG, move by that many elements."
1941 (if (> company-candidates-length 1)
1942 (company-select-previous arg)
1944 (company--unread-last-input)))
1946 (defun company-next-page ()
1947 "Select the candidate one page further."
1949 (when (company-manual-begin)
1950 (company-set-selection (+ company-selection
1951 company-tooltip-limit))))
1953 (defun company-previous-page ()
1954 "Select the candidate one page earlier."
1956 (when (company-manual-begin)
1957 (company-set-selection (- company-selection
1958 company-tooltip-limit))))
1960 (defvar company-pseudo-tooltip-overlay)
1962 (defvar company-tooltip-offset)
1964 (defun company--inside-tooltip-p (event-col-row row height)
1965 (let* ((ovl company-pseudo-tooltip-overlay)
1966 (column (overlay-get ovl 'company-column))
1967 (width (overlay-get ovl 'company-width))
1968 (evt-col (car event-col-row))
1969 (evt-row (cdr event-col-row)))
1970 (and (>= evt-col column)
1971 (< evt-col (+ column width))
1973 (and (> evt-row row)
1974 (<= evt-row (+ row height) ))
1975 (and (< evt-row row)
1976 (>= evt-row (+ row height)))))))
1978 (defun company--event-col-row (event)
1979 (company--posn-col-row (event-start event)))
1981 (defun company-select-mouse (event)
1982 "Select the candidate picked by the mouse."
1984 (let ((event-col-row (company--event-col-row event))
1985 (ovl-row (company--row))
1986 (ovl-height (and company-pseudo-tooltip-overlay
1987 (min (overlay-get company-pseudo-tooltip-overlay
1989 company-candidates-length))))
1991 (company--inside-tooltip-p event-col-row ovl-row ovl-height))
1993 (company-set-selection (+ (cdr event-col-row)
1994 (1- company-tooltip-offset)
1995 (if (and (eq company-tooltip-offset-display 'lines)
1996 (not (zerop company-tooltip-offset)))
1999 (if (< ovl-height 0)
2004 (company--unread-last-input)
2007 (defun company-complete-mouse (event)
2008 "Insert the candidate picked by the mouse."
2010 (when (company-select-mouse event)
2011 (company-complete-selection)))
2013 (defun company-complete-selection ()
2014 "Insert the selected candidate."
2016 (when (company-manual-begin)
2017 (let ((result (nth company-selection company-candidates)))
2018 (company-finish result))))
2020 (defun company-complete-common ()
2021 "Insert the common part of all candidates."
2023 (when (company-manual-begin)
2024 (if (and (not (cdr company-candidates))
2025 (equal company-common (car company-candidates)))
2026 (company-complete-selection)
2027 (company--insert-candidate company-common))))
2029 (defun company-complete-common-or-cycle (&optional arg)
2030 "Insert the common part of all candidates, or select the next one.
2032 With ARG, move by that many elements."
2034 (when (company-manual-begin)
2035 (let ((tick (buffer-chars-modified-tick)))
2036 (call-interactively 'company-complete-common)
2037 (when (eq tick (buffer-chars-modified-tick))
2038 (let ((company-selection-wrap-around t)
2039 (current-prefix-arg arg))
2040 (call-interactively 'company-select-next))))))
2042 (defun company-indent-or-complete-common ()
2043 "Indent the current line or region, or complete the common part."
2047 (indent-region (region-beginning) (region-end)))
2048 ((let ((old-point (point))
2049 (old-tick (buffer-chars-modified-tick))
2050 (tab-always-indent t))
2051 (call-interactively #'indent-for-tab-command)
2052 (when (and (eq old-point (point))
2053 (eq old-tick (buffer-chars-modified-tick)))
2054 (company-complete-common))))))
2056 (defun company-complete ()
2057 "Insert the common part of all candidates or the current selection.
2058 The first time this is called, the common part is inserted, the second
2059 time, or when the selection has been changed, the selected candidate is
2062 (when (company-manual-begin)
2063 (if (or company-selection-changed
2064 (eq last-command 'company-complete-common))
2065 (call-interactively 'company-complete-selection)
2066 (call-interactively 'company-complete-common)
2067 (setq this-command 'company-complete-common))))
2069 (defun company-complete-number (n)
2070 "Insert the Nth candidate visible in the tooltip.
2071 To show the number next to the candidates in some backends, enable
2072 `company-show-numbers'. When called interactively, uses the last typed
2073 character, stripping the modifiers. That character must be a digit."
2075 (list (let* ((type (event-basic-type last-command-event))
2076 (char (if (characterp type)
2077 ;; Number on the main row.
2079 ;; Keypad number, if bound directly.
2080 (car (last (string-to-list (symbol-name type))))))
2082 (if (zerop n) 10 n))))
2083 (when (company-manual-begin)
2084 (and (or (< n 1) (> n (- company-candidates-length
2085 company-tooltip-offset)))
2086 (error "No candidate number %d" n))
2088 (company-finish (nth (+ n company-tooltip-offset)
2089 company-candidates))))
2091 ;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;
2093 (defconst company-space-strings-limit 100)
2095 (defconst company-space-strings
2097 (dotimes (i company-space-strings-limit)
2098 (push (make-string (- company-space-strings-limit 1 i) ?\ ) lst))
2099 (apply 'vector lst)))
2101 (defun company-space-string (len)
2102 (if (< len company-space-strings-limit)
2103 (aref company-space-strings len)
2104 (make-string len ?\ )))
2106 (defun company-safe-substring (str from &optional to)
2107 (if (> from (string-width str))
2111 (move-to-column from)
2112 (let ((beg (point)))
2116 (concat (buffer-substring beg (point))
2117 (let ((padding (- to (current-column))))
2119 (company-space-string padding)))))
2120 (buffer-substring beg (point-max)))))))
2122 ;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;
2124 (defvar-local company-last-metadata nil)
2126 (defun company-fetch-metadata ()
2127 (let ((selected (nth company-selection company-candidates)))
2128 (unless (eq selected (car company-last-metadata))
2129 (setq company-last-metadata
2130 (cons selected (company-call-backend 'meta selected))))
2131 (cdr company-last-metadata)))
2133 (defun company-doc-buffer (&optional string)
2134 (with-current-buffer (get-buffer-create "*company-documentation*")
2141 (defvar company--electric-saved-window-configuration nil)
2143 (defvar company--electric-commands
2144 '(scroll-other-window scroll-other-window-down mwheel-scroll)
2145 "List of Commands that won't break out of electric commands.")
2147 (defun company--electric-restore-window-configuration ()
2148 "Restore window configuration (after electric commands)."
2149 (when (and company--electric-saved-window-configuration
2150 (not (memq this-command company--electric-commands)))
2151 (set-window-configuration company--electric-saved-window-configuration)
2152 (setq company--electric-saved-window-configuration nil)))
2154 (defmacro company--electric-do (&rest body)
2155 (declare (indent 0) (debug t))
2156 `(when (company-manual-begin)
2157 (cl-assert (null company--electric-saved-window-configuration))
2158 (setq company--electric-saved-window-configuration (current-window-configuration))
2159 (let ((height (window-height))
2160 (row (company--row)))
2162 (and (< (window-height) height)
2163 (< (- (window-height) row 2) company-tooltip-limit)
2164 (recenter (- (window-height) row 2))))))
2166 (defun company--unread-last-input ()
2167 (when last-input-event
2168 (clear-this-command-keys t)
2169 (setq unread-command-events (list last-input-event))))
2171 (defun company-show-doc-buffer ()
2172 "Temporarily show the documentation buffer for the selection."
2174 (let (other-window-scroll-buffer)
2175 (company--electric-do
2176 (let* ((selected (nth company-selection company-candidates))
2177 (doc-buffer (or (company-call-backend 'doc-buffer selected)
2178 (error "No documentation available")))
2180 (when (consp doc-buffer)
2181 (setq start (cdr doc-buffer)
2182 doc-buffer (car doc-buffer)))
2183 (setq other-window-scroll-buffer (get-buffer doc-buffer))
2184 (let ((win (display-buffer doc-buffer t)))
2185 (set-window-start win (if start start (point-min))))))))
2186 (put 'company-show-doc-buffer 'company-keep t)
2188 (defun company-show-location ()
2189 "Temporarily display a buffer showing the selected candidate in context."
2191 (let (other-window-scroll-buffer)
2192 (company--electric-do
2193 (let* ((selected (nth company-selection company-candidates))
2194 (location (company-call-backend 'location selected))
2195 (pos (or (cdr location) (error "No location available")))
2196 (buffer (or (and (bufferp (car location)) (car location))
2197 (find-file-noselect (car location) t))))
2198 (setq other-window-scroll-buffer (get-buffer buffer))
2199 (with-selected-window (display-buffer buffer t)
2202 (if (bufferp (car location))
2204 (goto-char (point-min))
2205 (forward-line (1- pos))))
2206 (set-window-start nil (point)))))))
2207 (put 'company-show-location 'company-keep t)
2209 ;;; package functions ;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;
2211 (defvar-local company-callback nil)
2213 (defun company-remove-callback (&optional ignored)
2214 (remove-hook 'company-completion-finished-hook company-callback t)
2215 (remove-hook 'company-completion-cancelled-hook 'company-remove-callback t)
2216 (remove-hook 'company-completion-finished-hook 'company-remove-callback t))
2218 (defun company-begin-backend (backend &optional callback)
2219 "Start a completion at point using BACKEND."
2220 (interactive (let ((val (completing-read "Company backend: "
2222 'functionp nil "company-")))
2224 (list (intern val)))))
2225 (when (setq company-callback callback)
2226 (add-hook 'company-completion-finished-hook company-callback nil t))
2227 (add-hook 'company-completion-cancelled-hook 'company-remove-callback nil t)
2228 (add-hook 'company-completion-finished-hook 'company-remove-callback nil t)
2229 (setq company-backend backend)
2230 ;; Return non-nil if active.
2231 (or (company-manual-begin)
2232 (error "Cannot complete at point")))
2234 (defun company-begin-with (candidates
2235 &optional prefix-length require-match callback)
2236 "Start a completion at point.
2237 CANDIDATES is the list of candidates to use and PREFIX-LENGTH is the length
2238 of the prefix that already is in the buffer before point.
2241 CALLBACK is a function called with the selected result if the user
2242 successfully completes the input.
2244 Example: \(company-begin-with '\(\"foo\" \"foobar\" \"foobarbaz\"\)\)"
2245 (let ((begin-marker (copy-marker (point) t)))
2246 (company-begin-backend
2247 (lambda (command &optional arg &rest ignored)
2250 (when (equal (point) (marker-position begin-marker))
2251 (buffer-substring (- (point) (or prefix-length 0)) (point))))
2253 (all-completions arg candidates))
2258 (declare-function find-library-name "find-func")
2259 (declare-function lm-version "lisp-mnt")
2261 (defun company-version (&optional show-version)
2262 "Get the Company version as string.
2264 If SHOW-VERSION is non-nil, show the version in the echo area."
2265 (interactive (list t))
2267 (require 'find-func)
2268 (insert-file-contents (find-library-name "company"))
2271 (message "Company version: %s" (lm-version))
2274 (defun company-diag ()
2275 "Pop a buffer with information about completions at point."
2277 (let* ((bb company-backends)
2279 (prefix (cl-loop for b in bb
2280 thereis (let ((company-backend b))
2282 (company-call-backend 'prefix))))
2284 (when (stringp prefix)
2285 (let ((company-backend backend))
2286 (setq cc (company-call-backend 'candidates prefix)
2289 (lambda (c) (cons c (company-call-backend 'annotation c)))
2291 (pop-to-buffer (get-buffer-create "*company-diag*"))
2292 (setq buffer-read-only nil)
2294 (insert (format "Emacs %s (%s) of %s on %s"
2295 emacs-version system-configuration
2296 (format-time-string "%Y-%m-%d" emacs-build-time)
2297 emacs-build-system))
2298 (insert "\nCompany " (company-version) "\n\n")
2299 (insert "company-backends: " (pp-to-string bb))
2301 (insert "Used backend: " (pp-to-string backend))
2303 (insert "Prefix: " (pp-to-string prefix))
2305 (insert (message "Completions:"))
2306 (unless cc (insert " none"))
2308 (dolist (c annotations)
2309 (insert "\n " (prin1-to-string (car c)))
2311 (insert " " (prin1-to-string (cdr c))))))
2314 ;;; pseudo-tooltip ;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;
2316 (defvar-local company-pseudo-tooltip-overlay nil)
2318 (defvar-local company-tooltip-offset 0)
2320 (defun company-tooltip--lines-update-offset (selection num-lines limit)
2322 (setq company-tooltip-offset
2323 (max (min selection company-tooltip-offset)
2324 (- selection -1 limit)))
2326 (when (<= company-tooltip-offset 1)
2328 (setq company-tooltip-offset 0))
2330 (when (>= company-tooltip-offset (- num-lines limit 1))
2332 (when (= selection (1- num-lines))
2333 (cl-decf company-tooltip-offset)
2334 (when (<= company-tooltip-offset 1)
2335 (setq company-tooltip-offset 0)
2340 (defun company-tooltip--simple-update-offset (selection _num-lines limit)
2341 (setq company-tooltip-offset
2342 (if (< selection company-tooltip-offset)
2344 (max company-tooltip-offset
2345 (- selection limit -1)))))
2349 (defsubst company-round-tab (arg)
2350 (* (/ (+ arg tab-width) tab-width) tab-width))
2352 (defun company-plainify (str)
2353 (let ((prefix (get-text-property 0 'line-prefix str)))
2354 (when prefix ; Keep the original value unmodified, for no special reason.
2355 (setq str (concat prefix str))
2356 (remove-text-properties 0 (length str) '(line-prefix) str)))
2357 (let* ((pieces (split-string str "\t"))
2360 (setcar copy (company-safe-substring
2361 (car copy) 0 (company-round-tab (string-width (car copy)))))
2363 (apply 'concat pieces)))
2365 (defun company-fill-propertize (value annotation width selected left right)
2366 (let* ((margin (length left))
2367 (common (or (company-call-backend 'match value)
2369 (string-width company-common)
2371 (_ (setq value (company--pre-render value)
2372 annotation (and annotation (company--pre-render annotation t))))
2373 (ann-ralign company-tooltip-align-annotations)
2374 (ann-truncate (< width
2375 (+ (length value) (length annotation)
2376 (if ann-ralign 1 0))))
2377 (ann-start (+ margin
2381 (- width (length annotation)))
2383 (ann-end (min (+ ann-start (length annotation)) (+ margin width)))
2385 (if (or ann-truncate (not ann-ralign))
2386 (company-safe-substring
2388 (when (and annotation ann-ralign) " ")
2392 (company-safe-substring value 0
2393 (- width (length annotation)))
2396 (setq common (+ (min common width) margin))
2397 (setq width (+ width margin (length right)))
2399 (font-lock-append-text-property 0 width 'mouse-face
2400 'company-tooltip-mouse
2402 (when (< ann-start ann-end)
2403 (font-lock-append-text-property ann-start ann-end 'face
2405 'company-tooltip-annotation-selection
2406 'company-tooltip-annotation)
2408 (font-lock-prepend-text-property margin common 'face
2410 'company-tooltip-common-selection
2411 'company-tooltip-common)
2414 (if (let ((re (funcall company-search-regexp-function
2415 company-search-string)))
2416 (and (not (string= re ""))
2417 (string-match re value (length company-prefix))))
2418 (pcase-dolist (`(,mbeg . ,mend) (company--search-chunks))
2419 (let ((beg (+ margin mbeg))
2420 (end (+ margin mend))
2421 (width (- width (length right))))
2423 (font-lock-prepend-text-property beg (min end width)
2424 'face 'company-tooltip-search
2426 (font-lock-append-text-property 0 width 'face
2427 'company-tooltip-selection
2429 (font-lock-append-text-property 0 width 'face
2434 (defun company--search-chunks ()
2435 (let ((md (match-data t))
2437 (if (<= (length md) 2)
2438 (push (cons (nth 0 md) (nth 1 md)) res)
2439 (while (setq md (nthcdr 2 md))
2441 (push (cons (car md) (cadr md)) res))))
2444 (defun company--pre-render (str &optional annotation-p)
2445 (or (company-call-backend 'pre-render str annotation-p)
2447 (when (or (text-property-not-all 0 (length str) 'face nil str)
2448 (text-property-not-all 0 (length str) 'mouse-face nil str))
2449 (setq str (copy-sequence str))
2450 (remove-text-properties 0 (length str)
2451 '(face nil font-lock-face nil mouse-face nil)
2455 (defun company--clean-string (str)
2456 (replace-regexp-in-string
2457 "\\([^[:graph:] ]\\)\\|\\(\ufeff\\)\\|[[:multibyte:]]"
2460 ((match-beginning 1)
2461 ;; FIXME: Better char for 'non-printable'?
2462 ;; We shouldn't get any of these, but sometimes we might.
2464 ((match-beginning 2)
2465 ;; Zero-width non-breakable space.
2467 ((> (string-width match) 1)
2469 (make-string (1- (string-width match)) ?\ufeff)
2476 (defun company-buffer-lines (beg end)
2478 (let (lines lines-moved)
2479 (while (and (not (eobp)) ; http://debbugs.gnu.org/19553
2480 (> (setq lines-moved (vertical-motion 1)) 0)
2482 (let ((bound (min end (point))))
2483 ;; A visual line can contain several physical lines (e.g. with outline's
2484 ;; folding overlay). Take only the first one.
2485 (push (buffer-substring beg
2488 (re-search-forward "$" bound 'move)
2491 ;; One physical line can be displayed as several visual ones as well:
2492 ;; add empty strings to the list, to even the count.
2493 (dotimes (_ (1- lines-moved))
2496 (unless (eq beg end)
2497 (push (buffer-substring beg end) lines))
2500 (defun company-modify-line (old new offset)
2501 (concat (company-safe-substring old 0 offset)
2503 (company-safe-substring old (+ offset (length new)))))
2505 (defsubst company--length-limit (lst limit)
2506 (if (nthcdr limit lst)
2510 (defsubst company--window-height ()
2511 (if (fboundp 'window-screen-lines)
2512 (floor (window-screen-lines))
2513 (window-body-height)))
2515 (defun company--window-width ()
2516 (let ((ww (window-body-width)))
2517 ;; Account for the line continuation column.
2518 (when (zerop (cadr (window-fringes)))
2520 (unless (or (display-graphic-p)
2521 (version< "24.3.1" emacs-version))
2522 ;; Emacs 24.3 and earlier included margins
2523 ;; in window-width when in TTY.
2525 (let ((margins (window-margins)))
2526 (+ (or (car margins) 0)
2527 (or (cdr margins) 0)))))
2528 (when (and word-wrap
2529 (version< emacs-version "24.4.51.5"))
2530 ;; http://debbugs.gnu.org/19300
2532 ;; whitespace-mode with newline-mark
2533 (when (and buffer-display-table
2534 (aref buffer-display-table ?\n))
2535 (cl-decf ww (1- (length (aref buffer-display-table ?\n)))))
2538 (defun company--replacement-string (lines old column nl &optional align-top)
2539 (cl-decf column company-tooltip-margin)
2541 (when (and align-top company-tooltip-flip-when-above)
2542 (setq lines (reverse lines)))
2544 (let ((width (length (car lines)))
2545 (remaining-cols (- (+ (company--window-width) (window-hscroll))
2547 (when (> width remaining-cols)
2548 (cl-decf column (- width remaining-cols))))
2550 (let ((offset (and (< column 0) (- column)))
2555 ;; untouched lines first
2556 (dotimes (_ (- (length old) (length lines)))
2557 (push (pop old) new)))
2558 ;; length into old lines.
2560 (push (company-modify-line (pop old)
2561 (company--offset-line (pop lines) offset)
2564 ;; Append whole new lines.
2566 (push (concat (company-space-string column)
2567 (company--offset-line (pop lines) offset))
2570 (let ((str (concat (when nl " \n")
2571 (mapconcat 'identity (nreverse new) "\n")
2573 (font-lock-append-text-property 0 (length str) 'face 'default str)
2574 (when nl (put-text-property 0 1 'cursor t str))
2577 (defun company--offset-line (line offset)
2578 (if (and offset line)
2579 (substring line offset)
2582 (defun company--create-lines (selection limit)
2583 (let ((len company-candidates-length)
2584 (window-width (company--window-width))
2593 ;; Maybe clear old offset.
2594 (when (< len (+ company-tooltip-offset limit))
2595 (setq company-tooltip-offset 0))
2597 ;; Scroll to offset.
2598 (if (eq company-tooltip-offset-display 'lines)
2599 (setq limit (company-tooltip--lines-update-offset selection len limit))
2600 (company-tooltip--simple-update-offset selection len limit))
2603 ((eq company-tooltip-offset-display 'scrollbar)
2604 (setq scrollbar-bounds (company--scrollbar-bounds company-tooltip-offset
2606 ((eq company-tooltip-offset-display 'lines)
2607 (when (> company-tooltip-offset 0)
2608 (setq previous (format "...(%d)" company-tooltip-offset)))
2609 (setq remainder (- len limit company-tooltip-offset)
2610 remainder (when (> remainder 0)
2611 (setq remainder (format "...(%d)" remainder))))))
2613 (cl-decf selection company-tooltip-offset)
2614 (setq width (max (length previous) (length remainder))
2615 lines (nthcdr company-tooltip-offset company-candidates)
2619 (cl-decf window-width (* 2 company-tooltip-margin))
2620 (when scrollbar-bounds (cl-decf window-width))
2623 (let* ((value (pop lines-copy))
2624 (annotation (company-call-backend 'annotation value)))
2625 (setq value (company--clean-string (company-reformat value)))
2627 (when company-tooltip-align-annotations
2628 ;; `lisp-completion-at-point' adds a space.
2629 (setq annotation (comment-string-strip annotation t nil)))
2630 (setq annotation (company--clean-string annotation)))
2631 (push (cons value annotation) items)
2632 (setq width (max (+ (length value)
2633 (if (and annotation company-tooltip-align-annotations)
2634 (1+ (length annotation))
2635 (length annotation)))
2638 (setq width (min window-width
2639 (max company-tooltip-minimum-width
2640 (if company-show-numbers
2644 (let ((items (nreverse items))
2645 (numbered (if company-show-numbers 0 99999))
2648 (push (company--scrollpos-line previous width) new))
2651 (let* ((item (pop items))
2653 (annotation (cdr item))
2654 (right (company-space-string company-tooltip-margin))
2656 (when (< numbered 10)
2659 (setq right (concat (format " %d" (mod numbered 10)) right)))
2661 (company-fill-propertize str annotation
2662 width (equal i selection)
2663 (company-space-string
2664 company-tooltip-margin)
2666 (when scrollbar-bounds
2667 (company--scrollbar i scrollbar-bounds)))
2671 (push (company--scrollpos-line remainder width) new))
2675 (defun company--scrollbar-bounds (offset limit length)
2676 (when (> length limit)
2677 (let* ((size (ceiling (* limit (float limit)) length))
2678 (lower (floor (* limit (float offset)) length))
2679 (upper (+ lower size -1)))
2680 (cons lower upper))))
2682 (defun company--scrollbar (i bounds)
2683 (propertize " " 'face
2684 (if (and (>= i (car bounds)) (<= i (cdr bounds)))
2685 'company-scrollbar-fg
2686 'company-scrollbar-bg)))
2688 (defun company--scrollpos-line (text width)
2689 (propertize (concat (company-space-string company-tooltip-margin)
2690 (company-safe-substring text 0 width)
2691 (company-space-string company-tooltip-margin))
2692 'face 'company-tooltip))
2696 (defun company--pseudo-tooltip-height ()
2697 "Calculate the appropriate tooltip height.
2698 Returns a negative number if the tooltip should be displayed above point."
2699 (let* ((lines (company--row))
2700 (below (- (company--window-height) 1 lines)))
2701 (if (and (< below (min company-tooltip-minimum company-candidates-length))
2703 (- (max 3 (min company-tooltip-limit lines)))
2704 (max 3 (min company-tooltip-limit below)))))
2706 (defun company-pseudo-tooltip-show (row column selection)
2707 (company-pseudo-tooltip-hide)
2710 (let* ((height (company--pseudo-tooltip-height))
2714 (setq row (+ row height -1)
2717 (let* ((nl (< (move-to-window-line row) row))
2719 (end (save-excursion
2720 (move-to-window-line (+ row (abs height)))
2722 (ov (make-overlay beg end nil t))
2723 (args (list (mapcar 'company-plainify
2724 (company-buffer-lines beg end))
2727 (setq company-pseudo-tooltip-overlay ov)
2728 (overlay-put ov 'company-replacement-args args)
2730 (let ((lines (company--create-lines selection (abs height))))
2731 (overlay-put ov 'company-display
2732 (apply 'company--replacement-string lines args))
2733 (overlay-put ov 'company-width (string-width (car lines))))
2735 (overlay-put ov 'company-column column)
2736 (overlay-put ov 'company-height height)))))
2738 (defun company-pseudo-tooltip-show-at-point (pos column-offset)
2739 (let* ((col-row (company--col-row pos))
2740 (col (- (car col-row) column-offset)))
2741 (when (< col 0) (setq col 0))
2742 (company-pseudo-tooltip-show (1+ (cdr col-row)) col company-selection)))
2744 (defun company-pseudo-tooltip-edit (selection)
2745 (let* ((height (overlay-get company-pseudo-tooltip-overlay 'company-height))
2746 (lines (company--create-lines selection (abs height))))
2747 (overlay-put company-pseudo-tooltip-overlay 'company-width
2748 (string-width (car lines)))
2749 (overlay-put company-pseudo-tooltip-overlay 'company-display
2750 (apply 'company--replacement-string
2752 (overlay-get company-pseudo-tooltip-overlay
2753 'company-replacement-args)))))
2755 (defun company-pseudo-tooltip-hide ()
2756 (when company-pseudo-tooltip-overlay
2757 (delete-overlay company-pseudo-tooltip-overlay)
2758 (setq company-pseudo-tooltip-overlay nil)))
2760 (defun company-pseudo-tooltip-hide-temporarily ()
2761 (when (overlayp company-pseudo-tooltip-overlay)
2762 (overlay-put company-pseudo-tooltip-overlay 'invisible nil)
2763 (overlay-put company-pseudo-tooltip-overlay 'line-prefix nil)
2764 (overlay-put company-pseudo-tooltip-overlay 'after-string nil)
2765 (overlay-put company-pseudo-tooltip-overlay 'display nil)))
2767 (defun company-pseudo-tooltip-unhide ()
2768 (when company-pseudo-tooltip-overlay
2769 (let* ((ov company-pseudo-tooltip-overlay)
2770 (disp (overlay-get ov 'company-display)))
2771 ;; Beat outline's folding overlays, at least.
2772 (overlay-put ov 'priority 1)
2773 ;; No (extra) prefix for the first line.
2774 (overlay-put ov 'line-prefix "")
2775 ;; `display' is better
2776 ;; (http://debbugs.gnu.org/18285, http://debbugs.gnu.org/20847),
2777 ;; but it doesn't work on 0-length overlays.
2778 (if (< (overlay-start ov) (overlay-end ov))
2779 (overlay-put ov 'display disp)
2780 (overlay-put ov 'after-string disp)
2781 (overlay-put ov 'invisible t))
2782 (overlay-put ov 'window (selected-window)))))
2784 (defun company-pseudo-tooltip-guard ()
2786 (save-excursion (beginning-of-visual-line))
2787 (let ((ov company-pseudo-tooltip-overlay)
2788 (overhang (save-excursion (end-of-visual-line)
2789 (- (line-end-position) (point)))))
2790 (when (>= (overlay-get ov 'company-height) 0)
2792 (buffer-substring-no-properties (point) (overlay-start ov))
2793 (when (>= overhang 0) overhang))))))
2795 (defun company-pseudo-tooltip-frontend (command)
2796 "`company-mode' frontend similar to a tooltip but based on overlays."
2798 (pre-command (company-pseudo-tooltip-hide-temporarily))
2800 (unless (when (overlayp company-pseudo-tooltip-overlay)
2801 (let* ((ov company-pseudo-tooltip-overlay)
2802 (old-height (overlay-get ov 'company-height))
2803 (new-height (company--pseudo-tooltip-height)))
2805 (>= (* old-height new-height) 0)
2806 (>= (abs old-height) (abs new-height))
2807 (equal (company-pseudo-tooltip-guard)
2808 (overlay-get ov 'company-guard)))))
2810 (company-pseudo-tooltip-show-at-point (point) (length company-prefix))
2811 (overlay-put company-pseudo-tooltip-overlay
2812 'company-guard (company-pseudo-tooltip-guard)))
2813 (company-pseudo-tooltip-unhide))
2814 (hide (company-pseudo-tooltip-hide)
2815 (setq company-tooltip-offset 0))
2816 (update (when (overlayp company-pseudo-tooltip-overlay)
2817 (company-pseudo-tooltip-edit company-selection)))))
2819 (defun company-pseudo-tooltip-unless-just-one-frontend (command)
2820 "`company-pseudo-tooltip-frontend', but not shown for single candidates."
2821 (unless (and (eq command 'post-command)
2822 (company--show-inline-p))
2823 (company-pseudo-tooltip-frontend command)))
2825 ;;; overlay ;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;
2827 (defvar-local company-preview-overlay nil)
2829 (defun company-preview-show-at-point (pos)
2830 (company-preview-hide)
2832 (let ((completion (nth company-selection company-candidates)))
2833 (setq completion (copy-sequence (company--pre-render completion)))
2834 (font-lock-append-text-property 0 (length completion)
2835 'face 'company-preview
2837 (font-lock-prepend-text-property 0 (length company-common)
2838 'face 'company-preview-common
2841 ;; Add search string
2842 (and (string-match (funcall company-search-regexp-function
2843 company-search-string)
2845 (pcase-dolist (`(,mbeg . ,mend) (company--search-chunks))
2846 (font-lock-prepend-text-property mbeg mend
2847 'face 'company-preview-search
2850 (setq completion (company-strip-prefix completion))
2852 (and (equal pos (point))
2853 (not (equal completion ""))
2854 (add-text-properties 0 1 '(cursor 1) completion))
2857 (pto company-pseudo-tooltip-overlay)
2858 (ptf-workaround (and
2861 (eq pos (overlay-start pto)))))
2862 ;; Try to accomodate for the pseudo-tooltip overlay,
2863 ;; which may start at the same position if it's at eol.
2864 (when ptf-workaround
2866 (setq completion (concat (buffer-substring beg pos) completion)))
2868 (setq company-preview-overlay (make-overlay beg pos))
2870 (let ((ov company-preview-overlay))
2871 (overlay-put ov (if ptf-workaround 'display 'after-string)
2873 (overlay-put ov 'window (selected-window))))))
2875 (defun company-preview-hide ()
2876 (when company-preview-overlay
2877 (delete-overlay company-preview-overlay)
2878 (setq company-preview-overlay nil)))
2880 (defun company-preview-frontend (command)
2881 "`company-mode' frontend showing the selection as if it had been inserted."
2883 (`pre-command (company-preview-hide))
2884 (`post-command (company-preview-show-at-point (point)))
2885 (`hide (company-preview-hide))))
2887 (defun company-preview-if-just-one-frontend (command)
2888 "`company-preview-frontend', but only shown for single candidates."
2889 (when (or (not (eq command 'post-command))
2890 (company--show-inline-p))
2891 (company-preview-frontend command)))
2893 (defun company--show-inline-p ()
2894 (and (not (cdr company-candidates))
2896 (or (eq (company-call-backend 'ignore-case) 'keep-prefix)
2897 (string-prefix-p company-prefix company-common))))
2899 ;;; echo ;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;
2901 (defvar-local company-echo-last-msg nil)
2903 (defvar company-echo-timer nil)
2905 (defvar company-echo-delay .01)
2907 (defun company-echo-show (&optional getter)
2909 (setq company-echo-last-msg (funcall getter)))
2910 (let ((message-log-max nil))
2911 (if company-echo-last-msg
2912 (message "%s" company-echo-last-msg)
2915 (defun company-echo-show-soon (&optional getter)
2916 (company-echo-cancel)
2917 (setq company-echo-timer (run-with-timer 0 nil 'company-echo-show getter)))
2919 (defun company-echo-cancel (&optional unset)
2920 (when company-echo-timer
2921 (cancel-timer company-echo-timer))
2923 (setq company-echo-timer nil)))
2925 (defun company-echo-show-when-idle (&optional getter)
2926 (company-echo-cancel)
2927 (setq company-echo-timer
2928 (run-with-idle-timer company-echo-delay nil 'company-echo-show getter)))
2930 (defun company-echo-format ()
2932 (let ((limit (window-body-width (minibuffer-window)))
2934 ;; Roll to selection.
2935 (candidates (nthcdr company-selection company-candidates))
2936 (i (if company-show-numbers company-selection 99999))
2940 (setq comp (company-reformat (pop candidates))
2941 len (+ len 1 (length comp)))
2945 (setq comp (propertize (format "%d: %s" i comp)
2946 'face 'company-echo))
2949 (add-text-properties 3 (+ 3 (length company-common))
2950 '(face company-echo-common) comp))
2951 (setq comp (propertize comp 'face 'company-echo))
2952 (add-text-properties 0 (length company-common)
2953 '(face company-echo-common) comp))
2955 (setq candidates nil)
2958 (mapconcat 'identity (nreverse msg) " ")))
2960 (defun company-echo-strip-common-format ()
2962 (let ((limit (window-body-width (minibuffer-window)))
2963 (len (+ (length company-prefix) 2))
2964 ;; Roll to selection.
2965 (candidates (nthcdr company-selection company-candidates))
2966 (i (if company-show-numbers company-selection 99999))
2970 (setq comp (company-strip-prefix (pop candidates))
2971 len (+ len 2 (length comp)))
2974 (setq comp (format "%s (%d)" comp i))
2978 (setq candidates nil)
2979 (push (propertize comp 'face 'company-echo) msg)))
2981 (concat (propertize company-prefix 'face 'company-echo-common) "{"
2982 (mapconcat 'identity (nreverse msg) ", ")
2985 (defun company-echo-hide ()
2986 (unless (equal company-echo-last-msg "")
2987 (setq company-echo-last-msg "")
2988 (company-echo-show)))
2990 (defun company-echo-frontend (command)
2991 "`company-mode' frontend showing the candidates in the echo area."
2993 (`post-command (company-echo-show-soon 'company-echo-format))
2994 (`hide (company-echo-hide))))
2996 (defun company-echo-strip-common-frontend (command)
2997 "`company-mode' frontend showing the candidates in the echo area."
2999 (`post-command (company-echo-show-soon 'company-echo-strip-common-format))
3000 (`hide (company-echo-hide))))
3002 (defun company-echo-metadata-frontend (command)
3003 "`company-mode' frontend showing the documentation in the echo area."
3005 (`post-command (company-echo-show-when-idle 'company-fetch-metadata))
3006 (`hide (company-echo-hide))))
3009 ;;; company.el ends here