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 (or (and (memq 'company-pseudo-tooltip-unless-just-one-frontend value)
190 (memq 'company-pseudo-tooltip-frontend value))
191 (and (memq 'company-pseudo-tooltip-unless-just-one-frontend-with-delay value)
192 (memq 'company-pseudo-tooltip-frontend value))
193 (and (memq 'company-pseudo-tooltip-unless-just-one-frontend-with-delay value)
194 (memq 'company-pseudo-tooltip-unless-just-one-frontend value)))
195 (error "Pseudo tooltip frontend cannot be used more than once"))
196 (and (memq 'company-preview-if-just-one-frontend value)
197 (memq 'company-preview-frontend value)
198 (error "Preview frontend cannot be used twice"))
199 (and (memq 'company-echo value)
200 (memq 'company-echo-metadata-frontend value)
201 (error "Echo area cannot be used twice"))
202 ;; Preview must come last.
203 (dolist (f '(company-preview-if-just-one-frontend company-preview-frontend))
204 (when (cdr (memq f value))
205 (setq value (append (delq f value) (list f)))))
206 (set variable value)))
208 (defcustom company-frontends '(company-pseudo-tooltip-unless-just-one-frontend
209 company-preview-if-just-one-frontend
210 company-echo-metadata-frontend)
211 "The list of active frontends (visualizations).
212 Each frontend is a function that takes one argument. It is called with
213 one of the following arguments:
215 `show': When the visualization should start.
217 `hide': When the visualization should end.
219 `update': When the data has been updated.
221 `pre-command': Before every command that is executed while the
222 visualization is active.
224 `post-command': After every command that is executed while the
225 visualization is active.
227 The visualized data is stored in `company-prefix', `company-candidates',
228 `company-common', `company-selection', `company-point' and
229 `company-search-string'."
230 :set 'company-frontends-set
231 :type '(repeat (choice (const :tag "echo" company-echo-frontend)
232 (const :tag "echo, strip common"
233 company-echo-strip-common-frontend)
234 (const :tag "show echo meta-data in echo"
235 company-echo-metadata-frontend)
236 (const :tag "pseudo tooltip"
237 company-pseudo-tooltip-frontend)
238 (const :tag "pseudo tooltip, multiple only"
239 company-pseudo-tooltip-unless-just-one-frontend)
240 (const :tag "pseudo tooltip, multiple only, delayed"
241 company-pseudo-tooltip-unless-just-one-frontend-with-delay)
242 (const :tag "preview" company-preview-frontend)
243 (const :tag "preview, unique only"
244 company-preview-if-just-one-frontend)
245 (function :tag "custom function" nil))))
247 (defcustom company-tooltip-limit 10
248 "The maximum number of candidates in the tooltip."
251 (defcustom company-tooltip-minimum 6
252 "The minimum height of the tooltip.
253 If this many lines are not available, prefer to display the tooltip above."
256 (defcustom company-tooltip-minimum-width 0
257 "The minimum width of the tooltip's inner area.
258 This doesn't include the margins and the scroll bar."
260 :package-version '(company . "0.8.0"))
262 (defcustom company-tooltip-margin 1
263 "Width of margin columns to show around the toolip."
266 (defcustom company-tooltip-offset-display 'scrollbar
267 "Method using which the tooltip displays scrolling position.
268 `scrollbar' means draw a scrollbar to the right of the items.
269 `lines' means wrap items in lines with \"before\" and \"after\" counters."
270 :type '(choice (const :tag "Scrollbar" scrollbar)
271 (const :tag "Two lines" lines)))
273 (defcustom company-tooltip-align-annotations nil
274 "When non-nil, align annotations to the right tooltip border."
276 :package-version '(company . "0.7.1"))
278 (defcustom company-tooltip-flip-when-above nil
279 "Whether to flip the tooltip when it's above the current line."
281 :package-version '(company . "0.8.1"))
283 (defvar company-safe-backends
284 '((company-abbrev . "Abbrev")
285 (company-bbdb . "BBDB")
286 (company-capf . "completion-at-point-functions")
287 (company-clang . "Clang")
288 (company-cmake . "CMake")
289 (company-css . "CSS")
290 (company-dabbrev . "dabbrev for plain text")
291 (company-dabbrev-code . "dabbrev for code")
292 (company-eclim . "Eclim (an Eclipse interface)")
293 (company-elisp . "Emacs Lisp")
294 (company-etags . "etags")
295 (company-files . "Files")
296 (company-gtags . "GNU Global")
297 (company-ispell . "Ispell")
298 (company-keywords . "Programming language keywords")
299 (company-nxml . "nxml")
300 (company-oddmuse . "Oddmuse")
301 (company-semantic . "Semantic")
302 (company-tempo . "Tempo templates")
303 (company-xcode . "Xcode")))
304 (put 'company-safe-backends 'risky-local-variable t)
306 (defun company-safe-backends-p (backends)
307 (and (consp backends)
308 (not (cl-dolist (backend backends)
309 (unless (if (consp backend)
310 (company-safe-backends-p backend)
311 (assq backend company-safe-backends))
314 (defcustom company-backends `(,@(unless (version< "24.3.51" emacs-version)
315 (list 'company-elisp))
317 company-nxml company-css
318 company-eclim company-semantic company-clang
319 company-xcode company-cmake
322 (company-dabbrev-code company-gtags company-etags
324 company-oddmuse company-dabbrev)
325 "The list of active backends (completion engines).
327 Only one backend is used at a time. The choice depends on the order of
328 the items in this list, and on the values they return in response to the
329 `prefix' command (see below). But a backend can also be a \"grouped\"
332 `company-begin-backend' can be used to start a specific backend,
333 `company-other-backend' will skip to the next matching backend in the list.
335 Each backend is a function that takes a variable number of arguments.
336 The first argument is the command requested from the backend. It is one
339 `prefix': The backend should return the text to be completed. It must be
340 text immediately before point. Returning nil from this command passes
341 control to the next backend. The function should return `stop' if it
342 should complete but cannot (e.g. if it is in the middle of a string).
343 Instead of a string, the backend may return a cons (PREFIX . LENGTH)
344 where LENGTH is a number used in place of PREFIX's length when
345 comparing against `company-minimum-prefix-length'. LENGTH can also
346 be just t, and in the latter case the test automatically succeeds.
348 `candidates': The second argument is the prefix to be completed. The
349 return value should be a list of candidates that match the prefix.
351 Non-prefix matches are also supported (candidates that don't start with the
352 prefix, but match it in some backend-defined way). Backends that use this
353 feature must disable cache (return t to `no-cache') and might also want to
359 `sorted': Return t here to indicate that the candidates are sorted and will
360 not need to be sorted again.
362 `duplicates': If non-nil, company will take care of removing duplicates
365 `no-cache': Usually company doesn't ask for candidates again as completion
366 progresses, unless the backend returns t for this command. The second
367 argument is the latest prefix.
369 `ignore-case': Return t here if the backend returns case-insensitive
370 matches. This value is used to determine the longest common prefix (as
371 used in `company-complete-common'), and to filter completions when fetching
374 `meta': The second argument is a completion candidate. Return a (short)
375 documentation string for it.
377 `doc-buffer': The second argument is a completion candidate. Return a
378 buffer with documentation for it. Preferably use `company-doc-buffer'. If
379 not all buffer contents pertain to this candidate, return a cons of buffer
380 and window start position.
382 `location': The second argument is a completion candidate. Return a cons
383 of buffer and buffer location, or of file and line number where the
384 completion candidate was defined.
386 `annotation': The second argument is a completion candidate. Return a
387 string to be displayed inline with the candidate in the popup. If
388 duplicates are removed by company, candidates with equal string values will
389 be kept if they have different annotations. For that to work properly,
390 backends should store the related information on candidates using text
393 `match': The second argument is a completion candidate. Return the index
394 after the end of text matching `prefix' within the candidate string. It
395 will be used when rendering the popup. This command only makes sense for
396 backends that provide non-prefix completion.
398 `require-match': If this returns t, the user is not allowed to enter
399 anything not offered as a candidate. Please don't use that value in normal
400 backends. The default value nil gives the user that choice with
401 `company-require-match'. Return value `never' overrides that option the
404 `init': Called once for each buffer. The backend can check for external
405 programs and files and load any required libraries. Raising an error here
406 will show up in message log once, and the backend will not be used for
409 `post-completion': Called after a completion candidate has been inserted
410 into the buffer. The second argument is the candidate. Can be used to
411 modify it, e.g. to expand a snippet.
413 The backend should return nil for all commands it does not support or
414 does not know about. It should also be callable interactively and use
415 `company-begin-backend' to start itself in that case.
420 An element of `company-backends' can also be a list of backends. The
421 completions from backends in such groups are merged, but only from those
422 backends which return the same `prefix'.
424 If a backend command takes a candidate as an argument (e.g. `meta'), the
425 call is dispatched to the backend the candidate came from. In other
426 cases (except for `duplicates' and `sorted'), the first non-nil value among
427 all the backends is returned.
429 The group can also contain keywords. Currently, `:with' and `:separate'
430 keywords are defined. If the group contains keyword `:with', the backends
431 listed after this keyword are ignored for the purpose of the `prefix'
432 command. If the group contains keyword `:separate', the candidates that
433 come from different backends are sorted separately in the combined list.
435 Asynchronous backends
436 =====================
438 The return value of each command can also be a cons (:async . FETCHER)
439 where FETCHER is a function of one argument, CALLBACK. When the data
440 arrives, FETCHER must call CALLBACK and pass it the appropriate return
441 value, as described above. That call must happen in the same buffer as
442 where completion was initiated.
444 True asynchronous operation is only supported for command `candidates', and
445 only during idle completion. Other commands will block the user interface,
446 even if the backend uses the asynchronous calling convention."
450 ,@(mapcar (lambda (b) `(const :tag ,(cdr b) ,(car b)))
451 company-safe-backends)
452 (symbol :tag "User defined")
453 (repeat :tag "Merged backends"
454 (choice :tag "backend"
455 ,@(mapcar (lambda (b)
456 `(const :tag ,(cdr b) ,(car b)))
457 company-safe-backends)
458 (const :tag "With" :with)
459 (symbol :tag "User defined"))))))
461 (put 'company-backends 'safe-local-variable 'company-safe-backends-p)
463 (defcustom company-transformers nil
464 "Functions to change the list of candidates received from backends.
466 Each function gets called with the return value of the previous one.
467 The first one gets passed the list of candidates, already sorted and
470 (const :tag "None" nil)
471 (const :tag "Sort by occurrence" (company-sort-by-occurrence))
472 (const :tag "Sort by backend importance"
473 (company-sort-by-backend-importance))
474 (const :tag "Prefer case sensitive prefix"
475 (company-sort-prefer-same-case-prefix))
476 (repeat :tag "User defined" (function))))
478 (defcustom company-completion-started-hook nil
479 "Hook run when company starts completing.
480 The hook is called with one argument that is non-nil if the completion was
484 (defcustom company-completion-cancelled-hook nil
485 "Hook run when company cancels completing.
486 The hook is called with one argument that is non-nil if the completion was
490 (defcustom company-completion-finished-hook nil
491 "Hook run when company successfully completes.
492 The hook is called with the selected candidate as an argument.
494 If you indend to use it to post-process candidates from a specific
495 backend, consider using the `post-completion' command instead."
498 (defcustom company-minimum-prefix-length 3
499 "The minimum prefix length for idle completion."
500 :type '(integer :tag "prefix length"))
502 (defcustom company-abort-manual-when-too-short nil
503 "If enabled, cancel a manually started completion when the prefix gets
504 shorter than both `company-minimum-prefix-length' and the length of the
505 prefix it was started from."
507 :package-version '(company . "0.8.0"))
509 (defcustom company-require-match 'company-explicit-action-p
510 "If enabled, disallow non-matching input.
511 This can be a function do determine if a match is required.
513 This can be overridden by the backend, if it returns t or `never' to
514 `require-match'. `company-auto-complete' also takes precedence over this."
515 :type '(choice (const :tag "Off" nil)
516 (function :tag "Predicate function")
517 (const :tag "On, if user interaction took place"
518 'company-explicit-action-p)
519 (const :tag "On" t)))
521 (defcustom company-auto-complete nil
522 "Determines when to auto-complete.
523 If this is enabled, all characters from `company-auto-complete-chars'
524 trigger insertion of the selected completion candidate.
525 This can also be a function."
526 :type '(choice (const :tag "Off" nil)
527 (function :tag "Predicate function")
528 (const :tag "On, if user interaction took place"
529 'company-explicit-action-p)
530 (const :tag "On" t)))
532 (defcustom company-auto-complete-chars '(?\ ?\) ?.)
533 "Determines which characters trigger auto-completion.
534 See `company-auto-complete'. If this is a string, each string character
535 tiggers auto-completion. If it is a list of syntax description characters (see
536 `modify-syntax-entry'), all characters with that syntax auto-complete.
538 This can also be a function, which is called with the new input and should
539 return non-nil if company should auto-complete.
541 A character that is part of a valid candidate never triggers auto-completion."
542 :type '(choice (string :tag "Characters")
544 (const :tag "Whitespace" ?\ )
545 (const :tag "Symbol" ?_)
546 (const :tag "Opening parentheses" ?\()
547 (const :tag "Closing parentheses" ?\))
548 (const :tag "Word constituent" ?w)
549 (const :tag "Punctuation." ?.)
550 (const :tag "String quote." ?\")
551 (const :tag "Paired delimiter." ?$)
552 (const :tag "Expression quote or prefix operator." ?\')
553 (const :tag "Comment starter." ?<)
554 (const :tag "Comment ender." ?>)
555 (const :tag "Character-quote." ?/)
556 (const :tag "Generic string fence." ?|)
557 (const :tag "Generic comment fence." ?!))
558 (function :tag "Predicate function")))
560 (defcustom company-idle-delay .5
561 "The idle delay in seconds until completion starts automatically.
562 The prefix still has to satisfy `company-minimum-prefix-length' before that
563 happens. The value of nil means no idle completion."
564 :type '(choice (const :tag "never (nil)" nil)
565 (const :tag "immediate (0)" 0)
566 (number :tag "seconds")))
568 (defcustom company-tooltip-idle-delay .5
569 "The idle delay in seconds until tooltip is shown when using
570 `company-pseudo-tooltip-unless-just-one-frontend-with-delay'."
571 :type '(choice (const :tag "never (nil)" nil)
572 (const :tag "immediate (0)" 0)
573 (number :tag "seconds")))
575 (defcustom company-begin-commands '(self-insert-command
576 org-self-insert-command
577 orgtbl-self-insert-command
582 "A list of commands after which idle completion is allowed.
583 If this is t, it can show completions after any command except a few from a
584 pre-defined list. See `company-idle-delay'.
586 Alternatively, any command with a non-nil `company-begin' property is
587 treated as if it was on this list."
588 :type '(choice (const :tag "Any command" t)
589 (const :tag "Self insert command" '(self-insert-command))
590 (repeat :tag "Commands" function))
591 :package-version '(company . "0.8.4"))
593 (defcustom company-continue-commands '(not save-buffer save-some-buffers
594 save-buffers-kill-terminal
595 save-buffers-kill-emacs)
596 "A list of commands that are allowed during completion.
597 If this is t, or if `company-begin-commands' is t, any command is allowed.
598 Otherwise, the value must be a list of symbols. If it starts with `not',
599 the cdr is the list of commands that abort completion. Otherwise, all
600 commands except those in that list, or in `company-begin-commands', or
601 commands in the `company-' namespace, abort completion."
602 :type '(choice (const :tag "Any command" t)
603 (cons :tag "Any except"
605 (repeat :tag "Commands" function))
606 (repeat :tag "Commands" function)))
608 (defcustom company-show-numbers nil
609 "If enabled, show quick-access numbers for the first ten candidates."
610 :type '(choice (const :tag "off" nil)
611 (const :tag "on" t)))
613 (defcustom company-selection-wrap-around nil
614 "If enabled, selecting item before first or after last wraps around."
615 :type '(choice (const :tag "off" nil)
616 (const :tag "on" t)))
618 (defvar company-async-wait 0.03
619 "Pause between checks to see if the value's been set when turning an
620 asynchronous call into synchronous.")
622 (defvar company-async-timeout 2
623 "Maximum wait time for a value to be set during asynchronous call.")
625 ;;; mode ;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;
627 (defvar company-mode-map (make-sparse-keymap)
628 "Keymap used by `company-mode'.")
630 (defvar company-active-map
631 (let ((keymap (make-sparse-keymap)))
632 (define-key keymap "\e\e\e" 'company-abort)
633 (define-key keymap "\C-g" 'company-abort)
634 (define-key keymap (kbd "M-n") 'company-select-next)
635 (define-key keymap (kbd "M-p") 'company-select-previous)
636 (define-key keymap (kbd "<down>") 'company-select-next-or-abort)
637 (define-key keymap (kbd "<up>") 'company-select-previous-or-abort)
638 (define-key keymap [remap scroll-up-command] 'company-next-page)
639 (define-key keymap [remap scroll-down-command] 'company-previous-page)
640 (define-key keymap [down-mouse-1] 'ignore)
641 (define-key keymap [down-mouse-3] 'ignore)
642 (define-key keymap [mouse-1] 'company-complete-mouse)
643 (define-key keymap [mouse-3] 'company-select-mouse)
644 (define-key keymap [up-mouse-1] 'ignore)
645 (define-key keymap [up-mouse-3] 'ignore)
646 (define-key keymap [return] 'company-complete-selection)
647 (define-key keymap (kbd "RET") 'company-complete-selection)
648 (define-key keymap [tab] 'company-complete-common)
649 (define-key keymap (kbd "TAB") 'company-complete-common)
650 (define-key keymap (kbd "<f1>") 'company-show-doc-buffer)
651 (define-key keymap (kbd "C-h") 'company-show-doc-buffer)
652 (define-key keymap "\C-w" 'company-show-location)
653 (define-key keymap "\C-s" 'company-search-candidates)
654 (define-key keymap "\C-\M-s" 'company-filter-candidates)
656 (define-key keymap (read-kbd-macro (format "M-%d" i)) 'company-complete-number))
658 "Keymap that is enabled during an active completion.")
660 (defvar company--disabled-backends nil)
662 (defun company-init-backend (backend)
663 (and (symbolp backend)
664 (not (fboundp backend))
665 (ignore-errors (require backend nil t)))
670 (funcall backend 'init)
671 (put backend 'company-init t))
673 (put backend 'company-init 'failed)
674 (unless (memq backend company--disabled-backends)
675 (message "Company backend '%s' could not be initialized:\n%s"
676 backend (error-message-string err)))
677 (cl-pushnew backend company--disabled-backends)
679 ;; No initialization for lambdas.
680 ((functionp backend) t)
681 (t ;; Must be a list.
682 (cl-dolist (b backend)
684 (company-init-backend b))))))
686 (defcustom company-lighter-base "company"
687 "Base string to use for the `company-mode' lighter."
689 :package-version '(company . "0.8.10"))
691 (defvar company-lighter '(" "
694 (if (consp company-backend)
695 (company--group-lighter (nth company-selection
697 company-lighter-base)
698 (symbol-name company-backend)))
699 company-lighter-base))
700 "Mode line lighter for Company.
702 The value of this variable is a mode line template as in
703 `mode-line-format'.")
705 (put 'company-lighter 'risky-local-variable t)
708 (define-minor-mode company-mode
709 "\"complete anything\"; is an in-buffer completion framework.
710 Completion starts automatically, depending on the values
711 `company-idle-delay' and `company-minimum-prefix-length'.
713 Completion can be controlled with the commands:
714 `company-complete-common', `company-complete-selection', `company-complete',
715 `company-select-next', `company-select-previous'. If these commands are
716 called before `company-idle-delay', completion will also start.
718 Completions can be searched with `company-search-candidates' or
719 `company-filter-candidates'. These can be used while completion is
722 The completion data is retrieved using `company-backends' and displayed
723 using `company-frontends'. If you want to start a specific backend, call
724 it interactively or use `company-begin-backend'.
726 By default, the completions list is sorted alphabetically, unless the
727 backend chooses otherwise, or `company-transformers' changes it later.
729 regular keymap (`company-mode-map'):
732 keymap during active completions (`company-active-map'):
734 \\{company-active-map}"
735 nil company-lighter company-mode-map
738 (when (eq company-idle-delay t)
739 (setq company-idle-delay 0)
740 (warn "Setting `company-idle-delay' to t is deprecated. Set it to 0 instead."))
741 (add-hook 'pre-command-hook 'company-pre-command nil t)
742 (add-hook 'post-command-hook 'company-post-command nil t)
743 (mapc 'company-init-backend company-backends))
744 (remove-hook 'pre-command-hook 'company-pre-command t)
745 (remove-hook 'post-command-hook 'company-post-command t)
747 (kill-local-variable 'company-point)))
749 (defcustom company-global-modes t
750 "Modes for which `company-mode' mode is turned on by `global-company-mode'.
751 If nil, means no modes. If t, then all major modes have it turned on.
752 If a list, it should be a list of `major-mode' symbol names for which
753 `company-mode' should be automatically turned on. The sense of the list is
754 negated if it begins with `not'. For example:
756 means that `company-mode' is turned on for buffers in C and C++ modes only.
758 means that `company-mode' is always turned on except in `message-mode' buffers."
759 :type '(choice (const :tag "none" nil)
761 (set :menu-tag "mode specific" :tag "modes"
763 (const :tag "Except" not)
764 (repeat :inline t (symbol :tag "mode")))))
767 (define-globalized-minor-mode global-company-mode company-mode company-mode-on)
769 (defun company-mode-on ()
770 (when (and (not (or noninteractive (eq (aref (buffer-name) 0) ?\s)))
771 (cond ((eq company-global-modes t)
773 ((eq (car-safe company-global-modes) 'not)
774 (not (memq major-mode (cdr company-global-modes))))
775 (t (memq major-mode company-global-modes))))
778 (defsubst company-assert-enabled ()
780 (company-uninstall-map)
781 (error "Company not enabled")))
783 ;;; keymaps ;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;
785 (defvar-local company-my-keymap nil)
787 (defvar company-emulation-alist '((t . nil)))
789 (defsubst company-enable-overriding-keymap (keymap)
790 (company-uninstall-map)
791 (setq company-my-keymap keymap))
793 (defun company-ensure-emulation-alist ()
794 (unless (eq 'company-emulation-alist (car emulation-mode-map-alists))
795 (setq emulation-mode-map-alists
796 (cons 'company-emulation-alist
797 (delq 'company-emulation-alist emulation-mode-map-alists)))))
799 (defun company-install-map ()
800 (unless (or (cdar company-emulation-alist)
801 (null company-my-keymap))
802 (setf (cdar company-emulation-alist) company-my-keymap)))
804 (defun company-uninstall-map ()
805 (setf (cdar company-emulation-alist) nil))
808 ;; Emacs calculates the active keymaps before reading the event. That means we
809 ;; cannot change the keymap from a timer. So we send a bogus command.
810 ;; XXX: Even in Emacs 24.4, seems to be needed in the terminal.
811 (defun company-ignore ()
813 (setq this-command last-command))
815 (global-set-key '[company-dummy-event] 'company-ignore)
817 (defun company-input-noop ()
818 (push 'company-dummy-event unread-command-events))
820 (defun company--posn-col-row (posn)
821 (let ((col (car (posn-col-row posn)))
822 ;; `posn-col-row' doesn't work well with lines of different height.
823 ;; `posn-actual-col-row' doesn't handle multiple-width characters.
824 (row (cdr (or (posn-actual-col-row posn)
825 ;; When position is non-visible for some reason.
826 (posn-col-row posn)))))
827 (when (and header-line-format (version< emacs-version "24.3.93.3"))
828 ;; http://debbugs.gnu.org/18384
830 (cons (+ col (window-hscroll)) row)))
832 (defun company--col-row (&optional pos)
833 (company--posn-col-row (posn-at-point pos)))
835 (defun company--row (&optional pos)
836 (cdr (company--col-row pos)))
838 ;;; backends ;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;
840 (defvar-local company-backend nil)
842 (defun company-grab (regexp &optional expression limit)
843 (when (looking-back regexp limit)
844 (or (match-string-no-properties (or expression 0)) "")))
846 (defun company-grab-line (regexp &optional expression)
847 "Return a match string for REGEXP if it matches text before point.
848 If EXPRESSION is non-nil, return the match string for the respective
849 parenthesized expression in REGEXP.
850 Matching is limited to the current line."
851 (let ((inhibit-field-text-motion t))
852 (company-grab regexp expression (point-at-bol))))
854 (defun company-grab-symbol ()
855 "If point is at the end of a symbol, return it.
856 Otherwise, if point is not inside a symbol, return an empty string."
857 (if (looking-at "\\_>")
858 (buffer-substring (point) (save-excursion (skip-syntax-backward "w_")
860 (unless (and (char-after) (memq (char-syntax (char-after)) '(?w ?_)))
863 (defun company-grab-word ()
864 "If point is at the end of a word, return it.
865 Otherwise, if point is not inside a symbol, return an empty string."
866 (if (looking-at "\\>")
867 (buffer-substring (point) (save-excursion (skip-syntax-backward "w")
869 (unless (and (char-after) (eq (char-syntax (char-after)) ?w))
872 (defun company-grab-symbol-cons (idle-begin-after-re &optional max-len)
873 "Return a string SYMBOL or a cons (SYMBOL . t).
874 SYMBOL is as returned by `company-grab-symbol'. If the text before point
875 matches IDLE-BEGIN-AFTER-RE, return it wrapped in a cons."
876 (let ((symbol (company-grab-symbol)))
879 (forward-char (- (length symbol)))
880 (if (looking-back idle-begin-after-re (if max-len
882 (line-beginning-position)))
886 (defun company-in-string-or-comment ()
887 "Return non-nil if point is within a string or comment."
888 (let ((ppss (syntax-ppss)))
889 (or (car (setq ppss (nthcdr 3 ppss)))
890 (car (setq ppss (cdr ppss)))
893 (defun company-call-backend (&rest args)
894 (company--force-sync #'company-call-backend-raw args company-backend))
896 (defun company--force-sync (fun args backend)
897 (let ((value (apply fun args)))
898 (if (not (eq (car-safe value) :async))
901 (start (time-to-seconds)))
903 (lambda (result) (setq res result)))
904 (while (eq res 'trash)
905 (if (> (- (time-to-seconds) start) company-async-timeout)
906 (error "Company: backend %s async timeout with args %s"
908 (sleep-for company-async-wait)))
911 (defun company-call-backend-raw (&rest args)
912 (condition-case-unless-debug err
913 (if (functionp company-backend)
914 (apply company-backend args)
915 (apply #'company--multi-backend-adapter company-backend args))
916 (error (error "Company: backend %s error \"%s\" with args %s"
917 company-backend (error-message-string err) args))))
919 (defun company--multi-backend-adapter (backends command &rest args)
920 (let ((backends (cl-loop for b in backends
921 when (not (and (symbolp b)
922 (eq 'failed (get b 'company-init))))
924 (separate (memq :separate backends)))
926 (when (eq command 'prefix)
927 (setq backends (butlast backends (length (member :with backends)))))
929 (setq backends (cl-delete-if #'keywordp backends))
933 (company--multi-backend-adapter-candidates backends (car args) separate))
935 (`duplicates (not separate))
936 ((or `prefix `ignore-case `no-cache `require-match)
938 (cl-dolist (backend backends)
939 (when (setq value (company--force-sync
940 backend (cons command args) backend))
941 (cl-return value)))))
943 (let ((arg (car args)))
944 (when (> (length arg) 0)
945 (let ((backend (or (get-text-property 0 'company-backend arg)
947 (apply backend command args))))))))
949 (defun company--multi-backend-adapter-candidates (backends prefix separate)
950 (let ((pairs (cl-loop for backend in backends
951 when (equal (company--prefix-str
952 (funcall backend 'prefix))
954 collect (cons (funcall backend 'candidates prefix)
955 (company--multi-candidates-mapper
958 ;; Small perf optimization: don't tag the
959 ;; candidates received from the first
960 ;; backend in the group.
961 (not (eq backend (car backends))))))))
962 (company--merge-async pairs (lambda (values) (apply #'append values)))))
964 (defun company--multi-candidates-mapper (backend separate tag)
967 (let ((company-backend backend))
969 (company--preprocess-candidates candidates))))
974 (propertize str 'company-backend backend))
978 (defun company--merge-async (pairs merger)
979 (let ((async (cl-loop for pair in pairs
981 (eq :async (car-safe (car pair))))))
983 (funcall merger (cl-loop for (val . mapper) in pairs
984 collect (funcall mapper val)))
989 (pending (mapcar #'car pairs))
1000 (this-finisher (lambda (res)
1001 (setq pending (delq val pending))
1002 (setcar cell (funcall mapper res))
1003 (funcall finisher))))
1004 (if (not (eq :async (car-safe val)))
1005 (funcall this-finisher val)
1006 (let ((fetcher (cdr val)))
1007 (funcall fetcher this-finisher)))))))))))
1009 (defun company--prefix-str (prefix)
1010 (or (car-safe prefix) prefix))
1012 ;;; completion mechanism ;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;
1014 (defvar-local company-prefix nil)
1016 (defvar-local company-candidates nil)
1018 (defvar-local company-candidates-length nil)
1020 (defvar-local company-candidates-cache nil)
1022 (defvar-local company-candidates-predicate nil)
1024 (defvar-local company-common nil)
1026 (defvar-local company-selection 0)
1028 (defvar-local company-selection-changed nil)
1030 (defvar-local company--manual-action nil
1031 "Non-nil, if manual completion took place.")
1033 (defvar-local company--manual-prefix nil)
1035 (defvar company--auto-completion nil
1036 "Non-nil when current candidate is being inserted automatically.
1037 Controlled by `company-auto-complete'.")
1039 (defvar-local company--point-max nil)
1041 (defvar-local company-point nil)
1043 (defvar company-timer nil)
1044 (defvar company-tooltip-timer nil)
1046 (defsubst company-strip-prefix (str)
1047 (substring str (length company-prefix)))
1049 (defun company--insert-candidate (candidate)
1050 (when (> (length candidate) 0)
1051 (setq candidate (substring-no-properties candidate))
1052 ;; XXX: Return value we check here is subject to change.
1053 (if (eq (company-call-backend 'ignore-case) 'keep-prefix)
1054 (insert (company-strip-prefix candidate))
1055 (unless (equal company-prefix candidate)
1056 (delete-region (- (point) (length company-prefix)) (point))
1057 (insert candidate)))))
1059 (defmacro company-with-candidate-inserted (candidate &rest body)
1060 "Evaluate BODY with CANDIDATE temporarily inserted.
1061 This is a tool for backends that need candidates inserted before they
1062 can retrieve meta-data for them."
1063 (declare (indent 1))
1064 `(let ((inhibit-modification-hooks t)
1065 (inhibit-point-motion-hooks t)
1066 (modified-p (buffer-modified-p)))
1067 (company--insert-candidate ,candidate)
1070 (delete-region company-point (point))
1071 (set-buffer-modified-p modified-p))))
1073 (defun company-explicit-action-p ()
1074 "Return whether explicit completion action was taken by the user."
1075 (or company--manual-action
1076 company-selection-changed))
1078 (defun company-reformat (candidate)
1079 ;; company-ispell needs this, because the results are always lower-case
1080 ;; It's mory efficient to fix it only when they are displayed.
1081 ;; FIXME: Adopt the current text's capitalization instead?
1082 (if (eq (company-call-backend 'ignore-case) 'keep-prefix)
1083 (concat company-prefix (substring candidate (length company-prefix)))
1086 (defun company--should-complete ()
1087 (and (eq company-idle-delay 'now)
1088 (not (or buffer-read-only overriding-terminal-local-map
1089 overriding-local-map))
1090 ;; Check if in the middle of entering a key combination.
1091 (or (equal (this-command-keys-vector) [])
1092 (not (keymapp (key-binding (this-command-keys-vector)))))
1093 (not (and transient-mark-mode mark-active))))
1095 (defun company--should-continue ()
1096 (or (eq t company-begin-commands)
1097 (eq t company-continue-commands)
1098 (if (eq 'not (car company-continue-commands))
1099 (not (memq this-command (cdr company-continue-commands)))
1100 (or (memq this-command company-begin-commands)
1101 (memq this-command company-continue-commands)
1102 (and (symbolp this-command)
1103 (string-match-p "\\`company-" (symbol-name this-command)))))))
1105 (defun company-call-frontends (command)
1106 (dolist (frontend company-frontends)
1107 (condition-case-unless-debug err
1108 (funcall frontend command)
1109 (error (error "Company: frontend %s error \"%s\" on command %s"
1110 frontend (error-message-string err) command)))))
1112 (defun company-set-selection (selection &optional force-update)
1114 (if company-selection-wrap-around
1115 (mod selection company-candidates-length)
1116 (max 0 (min (1- company-candidates-length) selection))))
1117 (when (or force-update (not (equal selection company-selection)))
1118 (setq company-selection selection
1119 company-selection-changed t)
1120 (company-call-frontends 'update)))
1122 (defun company--group-lighter (candidate base)
1123 (let ((backend (or (get-text-property 0 'company-backend candidate)
1124 (cl-some (lambda (x) (and (not (keywordp x)) x))
1126 (when (and backend (symbolp backend))
1127 (let ((name (replace-regexp-in-string "company-\\|-company" ""
1128 (symbol-name backend))))
1129 (format "%s-<%s>" base name)))))
1131 (defun company-update-candidates (candidates)
1132 (setq company-candidates-length (length candidates))
1133 (if company-selection-changed
1134 ;; Try to restore the selection
1135 (let ((selected (nth company-selection company-candidates)))
1136 (setq company-selection 0
1137 company-candidates candidates)
1141 (let ((candidate (pop candidates)))
1142 (when (and (string= candidate selected)
1143 (equal (company-call-backend 'annotation candidate)
1144 (company-call-backend 'annotation selected)))
1146 (cl-incf company-selection))
1147 (setq company-selection 0
1148 company-selection-changed nil))))
1149 (setq company-selection 0
1150 company-candidates candidates))
1151 ;; Calculate common.
1152 (let ((completion-ignore-case (company-call-backend 'ignore-case)))
1153 ;; We want to support non-prefix completion, so filtering is the
1154 ;; responsibility of each respective backend, not ours.
1155 ;; On the other hand, we don't want to replace non-prefix input in
1156 ;; `company-complete-common', unless there's only one candidate.
1157 (setq company-common
1158 (if (cdr company-candidates)
1159 (let ((common (try-completion "" company-candidates)))
1160 (when (string-prefix-p company-prefix common
1161 completion-ignore-case)
1163 (car company-candidates)))))
1165 (defun company-calculate-candidates (prefix)
1166 (let ((candidates (cdr (assoc prefix company-candidates-cache)))
1167 (ignore-case (company-call-backend 'ignore-case)))
1169 (when company-candidates-cache
1170 (let ((len (length prefix))
1171 (completion-ignore-case ignore-case)
1173 (cl-dotimes (i (1+ len))
1174 (when (setq prev (cdr (assoc (substring prefix 0 (- len i))
1175 company-candidates-cache)))
1176 (setq candidates (all-completions prefix prev))
1179 ;; No cache match, call the backend.
1180 (setq candidates (company--preprocess-candidates
1181 (company--fetch-candidates prefix)))
1183 (push (cons prefix candidates) company-candidates-cache)))
1184 ;; Only now apply the predicate and transformers.
1185 (setq candidates (company--postprocess-candidates candidates))
1187 (if (or (cdr candidates)
1188 (not (eq t (compare-strings (car candidates) nil nil
1189 prefix nil nil ignore-case))))
1191 ;; Already completed and unique; don't start.
1194 (defun company--fetch-candidates (prefix)
1195 (let* ((non-essential (not (company-explicit-action-p)))
1196 (c (if company--manual-action
1197 (company-call-backend 'candidates prefix)
1198 (company-call-backend-raw 'candidates prefix)))
1200 (if (not (eq (car c) :async))
1202 (let ((buf (current-buffer))
1203 (win (selected-window))
1204 (tick (buffer-chars-modified-tick))
1206 (backend company-backend))
1209 (lambda (candidates)
1210 (if (not (and candidates (eq res 'done)))
1211 ;; There's no completions to display,
1212 ;; or the fetcher called us back right away.
1213 (setq res candidates)
1214 (setq company-backend backend
1215 company-candidates-cache
1217 (company--preprocess-candidates candidates))))
1219 (company-idle-begin buf win tick pt)
1220 (unless company-candidates
1221 (setq company-backend nil
1222 company-candidates-cache nil)))))))
1223 ;; FIXME: Relying on the fact that the callers
1224 ;; will interpret nil as "do nothing" is shaky.
1225 ;; A throw-catch would be one possible improvement.
1227 (progn (setq res 'done) nil)))))
1229 (defun company--preprocess-candidates (candidates)
1230 (cl-assert (cl-every #'stringp candidates))
1231 (unless (company-call-backend 'sorted)
1232 (setq candidates (sort candidates 'string<)))
1233 (when (company-call-backend 'duplicates)
1234 (company--strip-duplicates candidates))
1237 (defun company--postprocess-candidates (candidates)
1238 (when (or company-candidates-predicate company-transformers)
1239 (setq candidates (copy-sequence candidates)))
1240 (when company-candidates-predicate
1241 (setq candidates (cl-delete-if-not company-candidates-predicate candidates)))
1242 (company--transform-candidates candidates))
1244 (defun company--strip-duplicates (candidates)
1245 (let ((c2 candidates)
1249 (let ((str (pop c2)))
1250 (while (let ((str2 (car c2)))
1251 (if (not (equal str str2))
1255 (when (eq annos 'unk)
1256 (setq annos (list (company-call-backend
1258 (let ((anno2 (company-call-backend
1260 (if (member anno2 annos)
1267 (defun company--transform-candidates (candidates)
1268 (let ((c candidates))
1269 (dolist (tr company-transformers)
1270 (setq c (funcall tr c)))
1273 (defcustom company-occurrence-weight-function
1274 #'company-occurrence-prefer-closest-above
1275 "Function to weigh matches in `company-sort-by-occurrence'.
1276 It's called with three arguments: cursor position, the beginning and the
1279 (const :tag "First above point, then below point"
1280 company-occurrence-prefer-closest-above)
1281 (const :tag "Prefer closest in any direction"
1282 company-occurrence-prefer-any-closest)))
1284 (defun company-occurrence-prefer-closest-above (pos match-beg match-end)
1285 "Give priority to the matches above point, then those below point."
1286 (if (< match-beg pos)
1288 (- match-beg (window-start))))
1290 (defun company-occurrence-prefer-any-closest (pos _match-beg match-end)
1291 "Give priority to the matches closest to the point."
1292 (abs (- pos match-end)))
1294 (defun company-sort-by-occurrence (candidates)
1295 "Sort CANDIDATES according to their occurrences.
1296 Searches for each in the currently visible part of the current buffer and
1297 prioritizes the matches according to `company-occurrence-weight-function'.
1298 The rest of the list is appended unchanged.
1299 Keywords and function definition names are ignored."
1300 (let* ((w-start (window-start))
1301 (w-end (window-end))
1302 (start-point (point))
1310 (while (search-forward candidate w-end t)
1311 (when (and (not (eq (point) start-point))
1313 (company--occurrence-predicate)))
1317 (funcall company-occurrence-weight-function
1325 (mapcar #'car (sort occurs (lambda (e1 e2) (<= (cdr e1) (cdr e2)))))
1328 (defun company--occurrence-predicate ()
1329 (let ((beg (match-beginning 0))
1330 (end (match-end 0)))
1333 (and (not (memq (get-text-property (1- (point)) 'face)
1334 '(font-lock-function-name-face
1335 font-lock-keyword-face)))
1336 (let ((prefix (company--prefix-str
1337 (company-call-backend 'prefix))))
1338 (and (stringp prefix)
1339 (= (length prefix) (- end beg))))))))
1341 (defun company-sort-by-backend-importance (candidates)
1342 "Sort CANDIDATES as two priority groups.
1343 If `company-backend' is a function, do nothing. If it's a list, move
1344 candidates from backends before keyword `:with' to the front. Candidates
1345 from the rest of the backends in the group, if any, will be left at the end."
1346 (if (functionp company-backend)
1348 (let ((low-priority (cdr (memq :with company-backend))))
1349 (if (null low-priority)
1354 (let ((b2 (get-text-property 0 'company-backend c2)))
1355 (and b2 (memq b2 low-priority)))
1356 (let ((b1 (get-text-property 0 'company-backend c1)))
1357 (or (not b1) (not (memq b1 low-priority)))))))))))
1359 (defun company-sort-prefer-same-case-prefix (candidates)
1360 "Prefer CANDIDATES with the exact same prefix.
1361 If a backend returns case insensitive matches, candidates with the an exact
1362 prefix match (same case) will be prioritized."
1363 (cl-loop for candidate in candidates
1364 if (string-prefix-p company-prefix candidate)
1365 collect candidate into same-case
1366 else collect candidate into other-case
1367 finally return (append same-case other-case)))
1369 (defun company-idle-begin (buf win tick pos)
1370 (and (eq buf (current-buffer))
1371 (eq win (selected-window))
1372 (eq tick (buffer-chars-modified-tick))
1374 (when (company-auto-begin)
1375 (company-input-noop)
1376 (let ((this-command 'company-idle-begin))
1377 (company-post-command)))))
1379 (defun company-auto-begin ()
1381 (not company-candidates)
1382 (let ((company-idle-delay 'now))
1383 (condition-case-unless-debug err
1386 ;; Return non-nil if active.
1388 (error (message "Company: An error occurred in auto-begin")
1389 (message "%s" (error-message-string err))
1391 (quit (company-cancel))))))
1394 (defun company-manual-begin ()
1396 (company-assert-enabled)
1397 (setq company--manual-action t)
1399 (let ((company-minimum-prefix-length 0))
1400 (or company-candidates
1401 (company-auto-begin)))
1402 (unless company-candidates
1403 (setq company--manual-action nil))))
1405 (defun company-other-backend (&optional backward)
1406 (interactive (list current-prefix-arg))
1407 (company-assert-enabled)
1408 (let* ((after (if company-backend
1409 (cdr (member company-backend company-backends))
1411 (before (cdr (member company-backend (reverse company-backends))))
1413 (append before (reverse after))
1414 (append after (reverse before)))))
1416 (cl-dolist (backend next)
1417 (when (ignore-errors (company-begin-backend backend))
1419 (unless company-candidates
1420 (error "No other backend")))
1422 (defun company-require-match-p ()
1423 (let ((backend-value (company-call-backend 'require-match)))
1424 (or (eq backend-value t)
1425 (and (not (eq backend-value 'never))
1426 (if (functionp company-require-match)
1427 (funcall company-require-match)
1428 (eq company-require-match t))))))
1430 (defun company-auto-complete-p (input)
1431 "Return non-nil, if input starts with punctuation or parentheses."
1432 (and (if (functionp company-auto-complete)
1433 (funcall company-auto-complete)
1434 company-auto-complete)
1435 (if (functionp company-auto-complete-chars)
1436 (funcall company-auto-complete-chars input)
1437 (if (consp company-auto-complete-chars)
1438 (memq (char-syntax (string-to-char input))
1439 company-auto-complete-chars)
1440 (string-match (substring input 0 1) company-auto-complete-chars)))))
1442 (defun company--incremental-p ()
1443 (and (> (point) company-point)
1444 (> (point-max) company--point-max)
1445 (not (eq this-command 'backward-delete-char-untabify))
1446 (equal (buffer-substring (- company-point (length company-prefix))
1450 (defun company--continue-failed (new-prefix)
1451 (let ((input (buffer-substring-no-properties (point) company-point)))
1453 ((company-auto-complete-p input)
1456 (goto-char company-point)
1457 (let ((company--auto-completion t))
1458 (company-complete-selection))
1460 ((and (or (not (company-require-match-p))
1461 ;; Don't require match if the new prefix
1462 ;; doesn't continue the old one, and the latter was a match.
1463 (not (stringp new-prefix))
1464 (<= (length new-prefix) (length company-prefix)))
1465 (member company-prefix company-candidates))
1466 ;; Last input was a success,
1467 ;; but we're treating it as an abort + input anyway,
1468 ;; like the `unique' case below.
1469 (company-cancel 'non-unique))
1470 ((company-require-match-p)
1471 ;; Wrong incremental input, but required match.
1472 (delete-char (- (length input)))
1474 (message "Matching input is required")
1476 (t (company-cancel)))))
1478 (defun company--good-prefix-p (prefix)
1479 (and (stringp (company--prefix-str prefix)) ;excludes 'stop
1480 (or (eq (cdr-safe prefix) t)
1481 (let ((len (or (cdr-safe prefix) (length prefix))))
1482 (if company--manual-prefix
1483 (or (not company-abort-manual-when-too-short)
1484 ;; Must not be less than minimum or initial length.
1485 (>= len (min company-minimum-prefix-length
1486 (length company--manual-prefix))))
1487 (>= len company-minimum-prefix-length))))))
1489 (defun company--continue ()
1490 (when (company-call-backend 'no-cache company-prefix)
1491 ;; Don't complete existing candidates, fetch new ones.
1492 (setq company-candidates-cache nil))
1493 (let* ((new-prefix (company-call-backend 'prefix))
1494 (c (when (and (company--good-prefix-p new-prefix)
1495 (setq new-prefix (company--prefix-str new-prefix))
1496 (= (- (point) (length new-prefix))
1497 (- company-point (length company-prefix))))
1498 (company-calculate-candidates new-prefix))))
1501 ;; t means complete/unique.
1502 ;; Handle it like completion was aborted, to differentiate from user
1503 ;; calling one of Company's commands to insert the candidate,
1504 ;; not to trigger template expansion, etc.
1505 (company-cancel 'unique))
1507 ;; incremental match
1508 (setq company-prefix new-prefix)
1509 (company-update-candidates c)
1511 ((not (company--incremental-p))
1513 (t (company--continue-failed new-prefix)))))
1515 (defun company--begin-new ()
1517 (cl-dolist (backend (if company-backend
1518 ;; prefer manual override
1519 (list company-backend)
1522 (if (or (symbolp backend)
1523 (functionp backend))
1524 (when (or (not (symbolp backend))
1525 (eq t (get backend 'company-init))
1526 (unless (get backend 'company-init)
1527 (company-init-backend backend)))
1528 (funcall backend 'prefix))
1529 (company--multi-backend-adapter backend 'prefix)))
1531 (when (company--good-prefix-p prefix)
1532 (setq company-prefix (company--prefix-str prefix)
1533 company-backend backend
1534 c (company-calculate-candidates company-prefix))
1537 (when company--manual-action
1538 (message "No completion found"))
1540 ;; t means complete/unique.
1541 ;; Run the hooks anyway, to e.g. clear the cache.
1542 (company-cancel 'unique)))
1543 (when company--manual-action
1544 (setq company--manual-prefix prefix))
1545 (company-update-candidates c)
1546 (run-hook-with-args 'company-completion-started-hook
1547 (company-explicit-action-p))
1548 (company-call-frontends 'show)))
1551 (defun company--perform ()
1552 (or (and company-candidates (company--continue))
1553 (and (company--should-complete) (company--begin-new)))
1554 (if (not company-candidates)
1555 (setq company-backend nil)
1556 (setq company-point (point)
1557 company--point-max (point-max))
1558 (company-ensure-emulation-alist)
1559 (company-enable-overriding-keymap company-active-map)
1560 (company-call-frontends 'update)))
1562 (defun company-cancel (&optional result)
1563 (let ((prefix company-prefix)
1564 (backend company-backend))
1565 (setq company-backend nil
1567 company-candidates nil
1568 company-candidates-length nil
1569 company-candidates-cache nil
1570 company-candidates-predicate nil
1573 company-selection-changed nil
1574 company--manual-action nil
1575 company--manual-prefix nil
1576 company--point-max nil
1579 (cancel-timer company-timer))
1580 (company-echo-cancel t)
1581 (company-search-mode 0)
1582 (company-call-frontends 'hide)
1583 (company-enable-overriding-keymap nil)
1585 ;; FIXME: RESULT can also be e.g. `unique'. We should call
1586 ;; `company-completion-finished-hook' in that case, with right argument.
1587 (if (stringp result)
1588 (let ((company-backend backend))
1589 (company-call-backend 'pre-completion result)
1590 (run-hook-with-args 'company-completion-finished-hook result)
1591 (company-call-backend 'post-completion result))
1592 (run-hook-with-args 'company-completion-cancelled-hook result))))
1593 ;; Make return value explicit.
1596 (defun company-abort ()
1598 (company-cancel 'abort))
1600 (defun company-finish (result)
1601 (company--insert-candidate result)
1602 (company-cancel result))
1604 (defsubst company-keep (command)
1605 (and (symbolp command) (get command 'company-keep)))
1607 (defun company-pre-command ()
1608 (company--electric-restore-window-configuration)
1609 (unless (company-keep this-command)
1610 (condition-case-unless-debug err
1611 (when company-candidates
1612 (company-call-frontends 'pre-command)
1613 (unless (company--should-continue)
1615 (error (message "Company: An error occurred in pre-command")
1616 (message "%s" (error-message-string err))
1619 (cancel-timer company-timer)
1620 (setq company-timer nil))
1621 (company-echo-cancel t)
1622 (company-uninstall-map))
1624 (defun company-post-command ()
1625 (when (and company-candidates
1626 (null this-command))
1627 ;; Happens when the user presses `C-g' while inside
1628 ;; `flyspell-post-command-hook', for example.
1629 ;; Or any other `post-command-hook' function that can call `sit-for',
1630 ;; or any quittable timer function.
1632 (setq this-command 'company-abort))
1633 (unless (company-keep this-command)
1634 (condition-case-unless-debug err
1636 (unless (equal (point) company-point)
1637 (let (company-idle-delay) ; Against misbehavior while debugging.
1638 (company--perform)))
1639 (if company-candidates
1640 (company-call-frontends 'post-command)
1641 (and (numberp company-idle-delay)
1642 (not defining-kbd-macro)
1643 (company--should-begin)
1645 (run-with-timer company-idle-delay nil
1647 (current-buffer) (selected-window)
1648 (buffer-chars-modified-tick) (point))))))
1649 (error (message "Company: An error occurred in post-command")
1650 (message "%s" (error-message-string err))
1652 (company-install-map))
1654 (defvar company--begin-inhibit-commands '(company-abort
1655 company-complete-mouse
1657 company-complete-common
1658 company-complete-selection
1659 company-complete-number)
1660 "List of commands after which idle completion is (still) disabled when
1661 `company-begin-commands' is t.")
1663 (defun company--should-begin ()
1664 (if (eq t company-begin-commands)
1665 (not (memq this-command company--begin-inhibit-commands))
1667 (memq this-command company-begin-commands)
1668 (and (symbolp this-command) (get this-command 'company-begin)))))
1670 ;;; search ;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;
1672 (defcustom company-search-regexp-function #'regexp-quote
1673 "Function to construct the search regexp from input.
1674 It's called with one argument, the current search input. It must return
1675 either a regexp without groups, or one where groups don't intersect and
1676 each one wraps a part of the input string."
1678 (const :tag "Exact match" regexp-quote)
1679 (const :tag "Words separated with spaces" company-search-words-regexp)
1680 (const :tag "Words separated with spaces, in any order"
1681 company-search-words-in-any-order-regexp)
1682 (const :tag "All characters in given order, with anything in between"
1683 company-search-flex-regexp)))
1685 (defvar-local company-search-string "")
1687 (defvar company-search-lighter '(" "
1688 (company-search-filtering "Filter" "Search")
1690 company-search-string
1693 (defvar-local company-search-filtering nil
1694 "Non-nil to filter the completion candidates by the search string")
1696 (defvar-local company--search-old-selection 0)
1698 (defvar-local company--search-old-changed nil)
1700 (defun company-search-words-regexp (input)
1701 (mapconcat (lambda (word) (format "\\(%s\\)" (regexp-quote word)))
1702 (split-string input " +" t) ".*"))
1704 (defun company-search-words-in-any-order-regexp (input)
1705 (let* ((words (mapcar (lambda (word) (format "\\(%s\\)" (regexp-quote word)))
1706 (split-string input " +" t)))
1707 (permutations (company--permutations words)))
1708 (mapconcat (lambda (words)
1709 (mapconcat #'identity words ".*"))
1713 (defun company-search-flex-regexp (input)
1714 (if (zerop (length input))
1716 (concat (regexp-quote (string (aref input 0)))
1717 (mapconcat (lambda (c)
1718 (concat "[^" (string c) "]*"
1719 (regexp-quote (string c))))
1720 (substring input 1) ""))))
1722 (defun company--permutations (lst)
1727 (mapcar (lambda (perm) (cons e perm))
1728 (company--permutations (cl-remove e lst :count 1))))
1731 (defun company--search (text lines)
1732 (let ((re (funcall company-search-regexp-function text))
1734 (cl-dolist (line lines)
1735 (when (string-match-p re line (length company-prefix))
1739 (defun company-search-keypad ()
1741 (let* ((name (symbol-name last-command-event))
1742 (last-command-event (aref name (1- (length name)))))
1743 (company-search-printing-char)))
1745 (defun company-search-printing-char ()
1747 (company--search-assert-enabled)
1748 (let ((ss (concat company-search-string (string last-command-event))))
1749 (when company-search-filtering
1750 (company--search-update-predicate ss))
1751 (company--search-update-string ss)))
1753 (defun company--search-update-predicate (ss)
1754 (let* ((re (funcall company-search-regexp-function ss))
1755 (company-candidates-predicate
1756 (and (not (string= re ""))
1757 company-search-filtering
1758 (lambda (candidate) (string-match re candidate))))
1759 (cc (company-calculate-candidates company-prefix)))
1760 (unless cc (error "No match"))
1761 (company-update-candidates cc)))
1763 (defun company--search-update-string (new)
1764 (let* ((pos (company--search new (nthcdr company-selection company-candidates))))
1767 (setq company-search-string new)
1768 (company-set-selection (+ company-selection pos) t))))
1770 (defun company--search-assert-input ()
1771 (company--search-assert-enabled)
1772 (when (string= company-search-string "")
1773 (error "Empty search string")))
1775 (defun company-search-repeat-forward ()
1776 "Repeat the incremental search in completion candidates forward."
1778 (company--search-assert-input)
1779 (let ((pos (company--search company-search-string
1780 (cdr (nthcdr company-selection
1781 company-candidates)))))
1784 (company-set-selection (+ company-selection pos 1) t))))
1786 (defun company-search-repeat-backward ()
1787 "Repeat the incremental search in completion candidates backwards."
1789 (company--search-assert-input)
1790 (let ((pos (company--search company-search-string
1791 (nthcdr (- company-candidates-length
1793 (reverse company-candidates)))))
1796 (company-set-selection (- company-selection pos 1) t))))
1798 (defun company-search-toggle-filtering ()
1799 "Toggle `company-search-filtering'."
1801 (company--search-assert-enabled)
1802 (setq company-search-filtering (not company-search-filtering))
1803 (let ((ss company-search-string))
1804 (company--search-update-predicate ss)
1805 (company--search-update-string ss)))
1807 (defun company-search-abort ()
1808 "Abort searching the completion candidates."
1810 (company--search-assert-enabled)
1811 (company-search-mode 0)
1812 (company-set-selection company--search-old-selection t)
1813 (setq company-selection-changed company--search-old-changed))
1815 (defun company-search-other-char ()
1817 (company--search-assert-enabled)
1818 (company-search-mode 0)
1819 (company--unread-last-input))
1821 (defun company-search-delete-char ()
1823 (company--search-assert-enabled)
1824 (if (string= company-search-string "")
1826 (let ((ss (substring company-search-string 0 -1)))
1827 (when company-search-filtering
1828 (company--search-update-predicate ss))
1829 (company--search-update-string ss))))
1831 (defvar company-search-map
1833 (keymap (make-keymap)))
1834 (if (fboundp 'max-char)
1835 (set-char-table-range (nth 1 keymap) (cons #x100 (max-char))
1836 'company-search-printing-char)
1838 ;; obsolete in Emacs 23
1839 (let ((l (generic-character-list))
1840 (table (nth 1 keymap)))
1842 (set-char-table-default table (car l) 'company-search-printing-char)
1843 (setq l (cdr l))))))
1844 (define-key keymap [t] 'company-search-other-char)
1846 (define-key keymap (make-string 1 i) 'company-search-other-char)
1849 (define-key keymap (vector i) 'company-search-printing-char)
1852 (define-key keymap (read (format "[kp-%s]" i)) 'company-search-keypad))
1853 (let ((meta-map (make-sparse-keymap)))
1854 (define-key keymap (char-to-string meta-prefix-char) meta-map)
1855 (define-key keymap [escape] meta-map))
1856 (define-key keymap (vector meta-prefix-char t) 'company-search-other-char)
1857 (define-key keymap (kbd "M-n") 'company-select-next)
1858 (define-key keymap (kbd "M-p") 'company-select-previous)
1859 (define-key keymap (kbd "<down>") 'company-select-next-or-abort)
1860 (define-key keymap (kbd "<up>") 'company-select-previous-or-abort)
1861 (define-key keymap "\e\e\e" 'company-search-other-char)
1862 (define-key keymap [escape escape escape] 'company-search-other-char)
1863 (define-key keymap (kbd "DEL") 'company-search-delete-char)
1864 (define-key keymap [backspace] 'company-search-delete-char)
1865 (define-key keymap "\C-g" 'company-search-abort)
1866 (define-key keymap "\C-s" 'company-search-repeat-forward)
1867 (define-key keymap "\C-r" 'company-search-repeat-backward)
1868 (define-key keymap "\C-o" 'company-search-toggle-filtering)
1870 (define-key keymap (read-kbd-macro (format "M-%d" i)) 'company-complete-number))
1872 "Keymap used for incrementally searching the completion candidates.")
1874 (define-minor-mode company-search-mode
1875 "Search mode for completion candidates.
1876 Don't start this directly, use `company-search-candidates' or
1877 `company-filter-candidates'."
1878 nil company-search-lighter nil
1879 (if company-search-mode
1880 (if (company-manual-begin)
1882 (setq company--search-old-selection company-selection
1883 company--search-old-changed company-selection-changed)
1884 (company-call-frontends 'update)
1885 (company-enable-overriding-keymap company-search-map))
1886 (setq company-search-mode nil))
1887 (kill-local-variable 'company-search-string)
1888 (kill-local-variable 'company-search-filtering)
1889 (kill-local-variable 'company--search-old-selection)
1890 (kill-local-variable 'company--search-old-changed)
1891 (when company-backend
1892 (company--search-update-predicate "")
1893 (company-call-frontends 'update))
1894 (company-enable-overriding-keymap company-active-map)))
1896 (defun company--search-assert-enabled ()
1897 (company-assert-enabled)
1898 (unless company-search-mode
1899 (company-uninstall-map)
1900 (error "Company not in search mode")))
1902 (defun company-search-candidates ()
1903 "Start searching the completion candidates incrementally.
1905 \\<company-search-map>Search can be controlled with the commands:
1906 - `company-search-repeat-forward' (\\[company-search-repeat-forward])
1907 - `company-search-repeat-backward' (\\[company-search-repeat-backward])
1908 - `company-search-abort' (\\[company-search-abort])
1909 - `company-search-delete-char' (\\[company-search-delete-char])
1911 Regular characters are appended to the search string.
1913 Customize `company-search-regexp-function' to change how the input
1914 is interpreted when searching.
1916 The command `company-search-toggle-filtering' (\\[company-search-toggle-filtering])
1917 uses the search string to filter the completion candidates."
1919 (company-search-mode 1))
1921 (defvar company-filter-map
1922 (let ((keymap (make-keymap)))
1923 (define-key keymap [remap company-search-printing-char]
1924 'company-filter-printing-char)
1925 (set-keymap-parent keymap company-search-map)
1927 "Keymap used for incrementally searching the completion candidates.")
1929 (defun company-filter-candidates ()
1930 "Start filtering the completion candidates incrementally.
1931 This works the same way as `company-search-candidates' immediately
1932 followed by `company-search-toggle-filtering'."
1934 (company-search-mode 1)
1935 (setq company-search-filtering t))
1937 ;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;
1939 (defun company-select-next (&optional arg)
1940 "Select the next candidate in the list.
1942 With ARG, move by that many elements."
1944 (when (company-manual-begin)
1945 (company-set-selection (+ (or arg 1) company-selection))))
1947 (defun company-select-previous (&optional arg)
1948 "Select the previous candidate in the list.
1950 With ARG, move by that many elements."
1952 (company-select-next (if arg (- arg) -1)))
1954 (defun company-select-next-or-abort (&optional arg)
1955 "Select the next candidate if more than one, else abort
1956 and invoke the normal binding.
1958 With ARG, move by that many elements."
1960 (if (> company-candidates-length 1)
1961 (company-select-next arg)
1963 (company--unread-last-input)))
1965 (defun company-select-previous-or-abort (&optional arg)
1966 "Select the previous candidate if more than one, else abort
1967 and invoke the normal binding.
1969 With ARG, move by that many elements."
1971 (if (> company-candidates-length 1)
1972 (company-select-previous arg)
1974 (company--unread-last-input)))
1976 (defun company-next-page ()
1977 "Select the candidate one page further."
1979 (when (company-manual-begin)
1980 (company-set-selection (+ company-selection
1981 company-tooltip-limit))))
1983 (defun company-previous-page ()
1984 "Select the candidate one page earlier."
1986 (when (company-manual-begin)
1987 (company-set-selection (- company-selection
1988 company-tooltip-limit))))
1990 (defvar company-pseudo-tooltip-overlay)
1992 (defvar company-tooltip-offset)
1994 (defun company--inside-tooltip-p (event-col-row row height)
1995 (let* ((ovl company-pseudo-tooltip-overlay)
1996 (column (overlay-get ovl 'company-column))
1997 (width (overlay-get ovl 'company-width))
1998 (evt-col (car event-col-row))
1999 (evt-row (cdr event-col-row)))
2000 (and (>= evt-col column)
2001 (< evt-col (+ column width))
2003 (and (> evt-row row)
2004 (<= evt-row (+ row height) ))
2005 (and (< evt-row row)
2006 (>= evt-row (+ row height)))))))
2008 (defun company--event-col-row (event)
2009 (company--posn-col-row (event-start event)))
2011 (defun company-select-mouse (event)
2012 "Select the candidate picked by the mouse."
2014 (let ((event-col-row (company--event-col-row event))
2015 (ovl-row (company--row))
2016 (ovl-height (and company-pseudo-tooltip-overlay
2017 (min (overlay-get company-pseudo-tooltip-overlay
2019 company-candidates-length))))
2021 (company--inside-tooltip-p event-col-row ovl-row ovl-height))
2023 (company-set-selection (+ (cdr event-col-row)
2024 (1- company-tooltip-offset)
2025 (if (and (eq company-tooltip-offset-display 'lines)
2026 (not (zerop company-tooltip-offset)))
2029 (if (< ovl-height 0)
2034 (company--unread-last-input)
2037 (defun company-complete-mouse (event)
2038 "Insert the candidate picked by the mouse."
2040 (when (company-select-mouse event)
2041 (company-complete-selection)))
2043 (defun company-complete-selection ()
2044 "Insert the selected candidate."
2046 (when (company-manual-begin)
2047 (let ((result (nth company-selection company-candidates)))
2048 (company-finish result))))
2050 (defun company-complete-common ()
2051 "Insert the common part of all candidates."
2053 (when (company-manual-begin)
2054 (if (and (not (cdr company-candidates))
2055 (equal company-common (car company-candidates)))
2056 (company-complete-selection)
2057 (company--insert-candidate company-common))))
2059 (defun company-complete-common-or-cycle (&optional arg)
2060 "Insert the common part of all candidates, or select the next one.
2062 With ARG, move by that many elements."
2064 (when (company-manual-begin)
2065 (let ((tick (buffer-chars-modified-tick)))
2066 (call-interactively 'company-complete-common)
2067 (when (eq tick (buffer-chars-modified-tick))
2068 (let ((company-selection-wrap-around t)
2069 (current-prefix-arg arg))
2070 (call-interactively 'company-select-next))))))
2072 (defun company-indent-or-complete-common ()
2073 "Indent the current line or region, or complete the common part."
2077 (indent-region (region-beginning) (region-end)))
2078 ((let ((old-point (point))
2079 (old-tick (buffer-chars-modified-tick))
2080 (tab-always-indent t))
2081 (call-interactively #'indent-for-tab-command)
2082 (when (and (eq old-point (point))
2083 (eq old-tick (buffer-chars-modified-tick)))
2084 (company-complete-common))))))
2086 (defun company-select-next-if-tooltip-visible-or-complete-selection ()
2087 "Insert selection if appropriate, or select the next candidate.
2088 Insert selection if only preview is showing or only one candidate,
2089 otherwise select the next candidate."
2091 (if (and (company-tooltip-visible-p) (> company-candidates-length 1))
2092 (call-interactively 'company-select-next)
2093 (call-interactively 'company-complete-selection)))
2096 (defun company-complete ()
2097 "Insert the common part of all candidates or the current selection.
2098 The first time this is called, the common part is inserted, the second
2099 time, or when the selection has been changed, the selected candidate is
2102 (when (company-manual-begin)
2103 (if (or company-selection-changed
2104 (eq last-command 'company-complete-common))
2105 (call-interactively 'company-complete-selection)
2106 (call-interactively 'company-complete-common)
2107 (setq this-command 'company-complete-common))))
2109 (defun company-complete-number (n)
2110 "Insert the Nth candidate visible in the tooltip.
2111 To show the number next to the candidates in some backends, enable
2112 `company-show-numbers'. When called interactively, uses the last typed
2113 character, stripping the modifiers. That character must be a digit."
2115 (list (let* ((type (event-basic-type last-command-event))
2116 (char (if (characterp type)
2117 ;; Number on the main row.
2119 ;; Keypad number, if bound directly.
2120 (car (last (string-to-list (symbol-name type))))))
2122 (if (zerop n) 10 n))))
2123 (when (company-manual-begin)
2124 (and (or (< n 1) (> n (- company-candidates-length
2125 company-tooltip-offset)))
2126 (error "No candidate number %d" n))
2128 (company-finish (nth (+ n company-tooltip-offset)
2129 company-candidates))))
2131 ;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;
2133 (defconst company-space-strings-limit 100)
2135 (defconst company-space-strings
2137 (dotimes (i company-space-strings-limit)
2138 (push (make-string (- company-space-strings-limit 1 i) ?\ ) lst))
2139 (apply 'vector lst)))
2141 (defun company-space-string (len)
2142 (if (< len company-space-strings-limit)
2143 (aref company-space-strings len)
2144 (make-string len ?\ )))
2146 (defun company-safe-substring (str from &optional to)
2147 (if (> from (string-width str))
2151 (move-to-column from)
2152 (let ((beg (point)))
2156 (concat (buffer-substring beg (point))
2157 (let ((padding (- to (current-column))))
2159 (company-space-string padding)))))
2160 (buffer-substring beg (point-max)))))))
2162 ;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;
2164 (defvar-local company-last-metadata nil)
2166 (defun company-fetch-metadata ()
2167 (let ((selected (nth company-selection company-candidates)))
2168 (unless (eq selected (car company-last-metadata))
2169 (setq company-last-metadata
2170 (cons selected (company-call-backend 'meta selected))))
2171 (cdr company-last-metadata)))
2173 (defun company-doc-buffer (&optional string)
2174 (with-current-buffer (get-buffer-create "*company-documentation*")
2181 (defvar company--electric-saved-window-configuration nil)
2183 (defvar company--electric-commands
2184 '(scroll-other-window scroll-other-window-down mwheel-scroll)
2185 "List of Commands that won't break out of electric commands.")
2187 (defun company--electric-restore-window-configuration ()
2188 "Restore window configuration (after electric commands)."
2189 (when (and company--electric-saved-window-configuration
2190 (not (memq this-command company--electric-commands)))
2191 (set-window-configuration company--electric-saved-window-configuration)
2192 (setq company--electric-saved-window-configuration nil)))
2194 (defmacro company--electric-do (&rest body)
2195 (declare (indent 0) (debug t))
2196 `(when (company-manual-begin)
2197 (cl-assert (null company--electric-saved-window-configuration))
2198 (setq company--electric-saved-window-configuration (current-window-configuration))
2199 (let ((height (window-height))
2200 (row (company--row)))
2202 (and (< (window-height) height)
2203 (< (- (window-height) row 2) company-tooltip-limit)
2204 (recenter (- (window-height) row 2))))))
2206 (defun company--unread-last-input ()
2207 (when last-input-event
2208 (clear-this-command-keys t)
2209 (setq unread-command-events (list last-input-event))))
2211 (defun company-show-doc-buffer ()
2212 "Temporarily show the documentation buffer for the selection."
2214 (let (other-window-scroll-buffer)
2215 (company--electric-do
2216 (let* ((selected (nth company-selection company-candidates))
2217 (doc-buffer (or (company-call-backend 'doc-buffer selected)
2218 (error "No documentation available")))
2220 (when (consp doc-buffer)
2221 (setq start (cdr doc-buffer)
2222 doc-buffer (car doc-buffer)))
2223 (setq other-window-scroll-buffer (get-buffer doc-buffer))
2224 (let ((win (display-buffer doc-buffer t)))
2225 (set-window-start win (if start start (point-min))))))))
2226 (put 'company-show-doc-buffer 'company-keep t)
2228 (defun company-show-location ()
2229 "Temporarily display a buffer showing the selected candidate in context."
2231 (let (other-window-scroll-buffer)
2232 (company--electric-do
2233 (let* ((selected (nth company-selection company-candidates))
2234 (location (company-call-backend 'location selected))
2235 (pos (or (cdr location) (error "No location available")))
2236 (buffer (or (and (bufferp (car location)) (car location))
2237 (find-file-noselect (car location) t))))
2238 (setq other-window-scroll-buffer (get-buffer buffer))
2239 (with-selected-window (display-buffer buffer t)
2242 (if (bufferp (car location))
2244 (goto-char (point-min))
2245 (forward-line (1- pos))))
2246 (set-window-start nil (point)))))))
2247 (put 'company-show-location 'company-keep t)
2249 ;;; package functions ;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;
2251 (defvar-local company-callback nil)
2253 (defun company-remove-callback (&optional ignored)
2254 (remove-hook 'company-completion-finished-hook company-callback t)
2255 (remove-hook 'company-completion-cancelled-hook 'company-remove-callback t)
2256 (remove-hook 'company-completion-finished-hook 'company-remove-callback t))
2258 (defun company-begin-backend (backend &optional callback)
2259 "Start a completion at point using BACKEND."
2260 (interactive (let ((val (completing-read "Company backend: "
2262 'functionp nil "company-")))
2264 (list (intern val)))))
2265 (when (setq company-callback callback)
2266 (add-hook 'company-completion-finished-hook company-callback nil t))
2267 (add-hook 'company-completion-cancelled-hook 'company-remove-callback nil t)
2268 (add-hook 'company-completion-finished-hook 'company-remove-callback nil t)
2269 (setq company-backend backend)
2270 ;; Return non-nil if active.
2271 (or (company-manual-begin)
2272 (error "Cannot complete at point")))
2274 (defun company-begin-with (candidates
2275 &optional prefix-length require-match callback)
2276 "Start a completion at point.
2277 CANDIDATES is the list of candidates to use and PREFIX-LENGTH is the length
2278 of the prefix that already is in the buffer before point.
2281 CALLBACK is a function called with the selected result if the user
2282 successfully completes the input.
2284 Example: \(company-begin-with \\='\(\"foo\" \"foobar\" \"foobarbaz\"\)\)"
2285 (let ((begin-marker (copy-marker (point) t)))
2286 (company-begin-backend
2287 (lambda (command &optional arg &rest ignored)
2290 (when (equal (point) (marker-position begin-marker))
2291 (buffer-substring (- (point) (or prefix-length 0)) (point))))
2293 (all-completions arg candidates))
2298 (declare-function find-library-name "find-func")
2299 (declare-function lm-version "lisp-mnt")
2301 (defun company-version (&optional show-version)
2302 "Get the Company version as string.
2304 If SHOW-VERSION is non-nil, show the version in the echo area."
2305 (interactive (list t))
2307 (require 'find-func)
2308 (insert-file-contents (find-library-name "company"))
2311 (message "Company version: %s" (lm-version))
2314 (defun company-diag ()
2315 "Pop a buffer with information about completions at point."
2317 (let* ((bb company-backends)
2319 (prefix (cl-loop for b in bb
2320 thereis (let ((company-backend b))
2322 (company-call-backend 'prefix))))
2324 (when (stringp prefix)
2325 (let ((company-backend backend))
2326 (setq cc (company-call-backend 'candidates prefix)
2329 (lambda (c) (cons c (company-call-backend 'annotation c)))
2331 (pop-to-buffer (get-buffer-create "*company-diag*"))
2332 (setq buffer-read-only nil)
2334 (insert (format "Emacs %s (%s) of %s on %s"
2335 emacs-version system-configuration
2336 (format-time-string "%Y-%m-%d" emacs-build-time)
2337 emacs-build-system))
2338 (insert "\nCompany " (company-version) "\n\n")
2339 (insert "company-backends: " (pp-to-string bb))
2341 (insert "Used backend: " (pp-to-string backend))
2343 (insert "Prefix: " (pp-to-string prefix))
2345 (insert (message "Completions:"))
2346 (unless cc (insert " none"))
2348 (dolist (c annotations)
2349 (insert "\n " (prin1-to-string (car c)))
2351 (insert " " (prin1-to-string (cdr c))))))
2354 ;;; pseudo-tooltip ;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;
2356 (defvar-local company-pseudo-tooltip-overlay nil)
2358 (defvar-local company-tooltip-offset 0)
2360 (defun company-tooltip--lines-update-offset (selection num-lines limit)
2362 (setq company-tooltip-offset
2363 (max (min selection company-tooltip-offset)
2364 (- selection -1 limit)))
2366 (when (<= company-tooltip-offset 1)
2368 (setq company-tooltip-offset 0))
2370 (when (>= company-tooltip-offset (- num-lines limit 1))
2372 (when (= selection (1- num-lines))
2373 (cl-decf company-tooltip-offset)
2374 (when (<= company-tooltip-offset 1)
2375 (setq company-tooltip-offset 0)
2380 (defun company-tooltip--simple-update-offset (selection _num-lines limit)
2381 (setq company-tooltip-offset
2382 (if (< selection company-tooltip-offset)
2384 (max company-tooltip-offset
2385 (- selection limit -1)))))
2389 (defsubst company-round-tab (arg)
2390 (* (/ (+ arg tab-width) tab-width) tab-width))
2392 (defun company-plainify (str)
2393 (let ((prefix (get-text-property 0 'line-prefix str)))
2394 (when prefix ; Keep the original value unmodified, for no special reason.
2395 (setq str (concat prefix str))
2396 (remove-text-properties 0 (length str) '(line-prefix) str)))
2397 (let* ((pieces (split-string str "\t"))
2400 (setcar copy (company-safe-substring
2401 (car copy) 0 (company-round-tab (string-width (car copy)))))
2403 (apply 'concat pieces)))
2405 (defun company-fill-propertize (value annotation width selected left right)
2406 (let* ((margin (length left))
2407 (common (or (company-call-backend 'match value)
2409 (string-width company-common)
2411 (_ (setq value (company--pre-render value)
2412 annotation (and annotation (company--pre-render annotation t))))
2413 (ann-ralign company-tooltip-align-annotations)
2414 (ann-truncate (< width
2415 (+ (length value) (length annotation)
2416 (if ann-ralign 1 0))))
2417 (ann-start (+ margin
2421 (- width (length annotation)))
2423 (ann-end (min (+ ann-start (length annotation)) (+ margin width)))
2425 (if (or ann-truncate (not ann-ralign))
2426 (company-safe-substring
2428 (when (and annotation ann-ralign) " ")
2432 (company-safe-substring value 0
2433 (- width (length annotation)))
2436 (setq common (+ (min common width) margin))
2437 (setq width (+ width margin (length right)))
2439 (font-lock-append-text-property 0 width 'mouse-face
2440 'company-tooltip-mouse
2442 (when (< ann-start ann-end)
2443 (font-lock-append-text-property ann-start ann-end 'face
2445 'company-tooltip-annotation-selection
2446 'company-tooltip-annotation)
2448 (font-lock-prepend-text-property margin common 'face
2450 'company-tooltip-common-selection
2451 'company-tooltip-common)
2454 (if (let ((re (funcall company-search-regexp-function
2455 company-search-string)))
2456 (and (not (string= re ""))
2457 (string-match re value (length company-prefix))))
2458 (pcase-dolist (`(,mbeg . ,mend) (company--search-chunks))
2459 (let ((beg (+ margin mbeg))
2460 (end (+ margin mend))
2461 (width (- width (length right))))
2463 (font-lock-prepend-text-property beg (min end width)
2464 'face 'company-tooltip-search
2466 (font-lock-append-text-property 0 width 'face
2467 'company-tooltip-selection
2469 (font-lock-append-text-property 0 width 'face
2474 (defun company--search-chunks ()
2475 (let ((md (match-data t))
2477 (if (<= (length md) 2)
2478 (push (cons (nth 0 md) (nth 1 md)) res)
2479 (while (setq md (nthcdr 2 md))
2481 (push (cons (car md) (cadr md)) res))))
2484 (defun company--pre-render (str &optional annotation-p)
2485 (or (company-call-backend 'pre-render str annotation-p)
2487 (when (or (text-property-not-all 0 (length str) 'face nil str)
2488 (text-property-not-all 0 (length str) 'mouse-face nil str))
2489 (setq str (copy-sequence str))
2490 (remove-text-properties 0 (length str)
2491 '(face nil font-lock-face nil mouse-face nil)
2495 (defun company--clean-string (str)
2496 (replace-regexp-in-string
2497 "\\([^[:graph:] ]\\)\\|\\(\ufeff\\)\\|[[:multibyte:]]"
2500 ((match-beginning 1)
2501 ;; FIXME: Better char for 'non-printable'?
2502 ;; We shouldn't get any of these, but sometimes we might.
2504 ((match-beginning 2)
2505 ;; Zero-width non-breakable space.
2507 ((> (string-width match) 1)
2509 (make-string (1- (string-width match)) ?\ufeff)
2516 (defun company-buffer-lines (beg end)
2518 (let (lines lines-moved)
2519 (while (and (not (eobp)) ; http://debbugs.gnu.org/19553
2520 (> (setq lines-moved (vertical-motion 1)) 0)
2522 (let ((bound (min end (point))))
2523 ;; A visual line can contain several physical lines (e.g. with outline's
2524 ;; folding overlay). Take only the first one.
2525 (push (buffer-substring beg
2528 (re-search-forward "$" bound 'move)
2531 ;; One physical line can be displayed as several visual ones as well:
2532 ;; add empty strings to the list, to even the count.
2533 (dotimes (_ (1- lines-moved))
2536 (unless (eq beg end)
2537 (push (buffer-substring beg end) lines))
2540 (defun company-modify-line (old new offset)
2541 (concat (company-safe-substring old 0 offset)
2543 (company-safe-substring old (+ offset (length new)))))
2545 (defsubst company--length-limit (lst limit)
2546 (if (nthcdr limit lst)
2550 (defsubst company--window-height ()
2551 (if (fboundp 'window-screen-lines)
2552 (floor (window-screen-lines))
2553 (window-body-height)))
2555 (defun company--window-width ()
2556 (let ((ww (window-body-width)))
2557 ;; Account for the line continuation column.
2558 (when (zerop (cadr (window-fringes)))
2560 (unless (or (display-graphic-p)
2561 (version< "24.3.1" emacs-version))
2562 ;; Emacs 24.3 and earlier included margins
2563 ;; in window-width when in TTY.
2565 (let ((margins (window-margins)))
2566 (+ (or (car margins) 0)
2567 (or (cdr margins) 0)))))
2568 (when (and word-wrap
2569 (version< emacs-version "24.4.51.5"))
2570 ;; http://debbugs.gnu.org/19300
2572 ;; whitespace-mode with newline-mark
2573 (when (and buffer-display-table
2574 (aref buffer-display-table ?\n))
2575 (cl-decf ww (1- (length (aref buffer-display-table ?\n)))))
2578 (defun company--replacement-string (lines old column nl &optional align-top)
2579 (cl-decf column company-tooltip-margin)
2581 (when (and align-top company-tooltip-flip-when-above)
2582 (setq lines (reverse lines)))
2584 (let ((width (length (car lines)))
2585 (remaining-cols (- (+ (company--window-width) (window-hscroll))
2587 (when (> width remaining-cols)
2588 (cl-decf column (- width remaining-cols))))
2590 (let ((offset (and (< column 0) (- column)))
2595 ;; untouched lines first
2596 (dotimes (_ (- (length old) (length lines)))
2597 (push (pop old) new)))
2598 ;; length into old lines.
2600 (push (company-modify-line (pop old)
2601 (company--offset-line (pop lines) offset)
2604 ;; Append whole new lines.
2606 (push (concat (company-space-string column)
2607 (company--offset-line (pop lines) offset))
2610 (let ((str (concat (when nl " \n")
2611 (mapconcat 'identity (nreverse new) "\n")
2613 (font-lock-append-text-property 0 (length str) 'face 'default str)
2614 (when nl (put-text-property 0 1 'cursor t str))
2617 (defun company--offset-line (line offset)
2618 (if (and offset line)
2619 (substring line offset)
2622 (defun company--create-lines (selection limit)
2623 (let ((len company-candidates-length)
2624 (window-width (company--window-width))
2633 ;; Maybe clear old offset.
2634 (when (< len (+ company-tooltip-offset limit))
2635 (setq company-tooltip-offset 0))
2637 ;; Scroll to offset.
2638 (if (eq company-tooltip-offset-display 'lines)
2639 (setq limit (company-tooltip--lines-update-offset selection len limit))
2640 (company-tooltip--simple-update-offset selection len limit))
2643 ((eq company-tooltip-offset-display 'scrollbar)
2644 (setq scrollbar-bounds (company--scrollbar-bounds company-tooltip-offset
2646 ((eq company-tooltip-offset-display 'lines)
2647 (when (> company-tooltip-offset 0)
2648 (setq previous (format "...(%d)" company-tooltip-offset)))
2649 (setq remainder (- len limit company-tooltip-offset)
2650 remainder (when (> remainder 0)
2651 (setq remainder (format "...(%d)" remainder))))))
2653 (cl-decf selection company-tooltip-offset)
2654 (setq width (max (length previous) (length remainder))
2655 lines (nthcdr company-tooltip-offset company-candidates)
2659 (cl-decf window-width (* 2 company-tooltip-margin))
2660 (when scrollbar-bounds (cl-decf window-width))
2663 (let* ((value (pop lines-copy))
2664 (annotation (company-call-backend 'annotation value)))
2665 (setq value (company--clean-string (company-reformat value)))
2667 (when company-tooltip-align-annotations
2668 ;; `lisp-completion-at-point' adds a space.
2669 (setq annotation (comment-string-strip annotation t nil)))
2670 (setq annotation (company--clean-string annotation)))
2671 (push (cons value annotation) items)
2672 (setq width (max (+ (length value)
2673 (if (and annotation company-tooltip-align-annotations)
2674 (1+ (length annotation))
2675 (length annotation)))
2678 (setq width (min window-width
2679 (max company-tooltip-minimum-width
2680 (if company-show-numbers
2684 (let ((items (nreverse items))
2685 (numbered (if company-show-numbers 0 99999))
2688 (push (company--scrollpos-line previous width) new))
2691 (let* ((item (pop items))
2693 (annotation (cdr item))
2694 (right (company-space-string company-tooltip-margin))
2696 (when (< numbered 10)
2699 (setq right (concat (format " %d" (mod numbered 10)) right)))
2701 (company-fill-propertize str annotation
2702 width (equal i selection)
2703 (company-space-string
2704 company-tooltip-margin)
2706 (when scrollbar-bounds
2707 (company--scrollbar i scrollbar-bounds)))
2711 (push (company--scrollpos-line remainder width) new))
2715 (defun company--scrollbar-bounds (offset limit length)
2716 (when (> length limit)
2717 (let* ((size (ceiling (* limit (float limit)) length))
2718 (lower (floor (* limit (float offset)) length))
2719 (upper (+ lower size -1)))
2720 (cons lower upper))))
2722 (defun company--scrollbar (i bounds)
2723 (propertize " " 'face
2724 (if (and (>= i (car bounds)) (<= i (cdr bounds)))
2725 'company-scrollbar-fg
2726 'company-scrollbar-bg)))
2728 (defun company--scrollpos-line (text width)
2729 (propertize (concat (company-space-string company-tooltip-margin)
2730 (company-safe-substring text 0 width)
2731 (company-space-string company-tooltip-margin))
2732 'face 'company-tooltip))
2736 (defun company--pseudo-tooltip-height ()
2737 "Calculate the appropriate tooltip height.
2738 Returns a negative number if the tooltip should be displayed above point."
2739 (let* ((lines (company--row))
2740 (below (- (company--window-height) 1 lines)))
2741 (if (and (< below (min company-tooltip-minimum company-candidates-length))
2743 (- (max 3 (min company-tooltip-limit lines)))
2744 (max 3 (min company-tooltip-limit below)))))
2746 (defun company-pseudo-tooltip-show (row column selection)
2747 (company-pseudo-tooltip-hide)
2750 (let* ((height (company--pseudo-tooltip-height))
2754 (setq row (+ row height -1)
2757 (let* ((nl (< (move-to-window-line row) row))
2759 (end (save-excursion
2760 (move-to-window-line (+ row (abs height)))
2762 (ov (make-overlay beg end nil t))
2763 (args (list (mapcar 'company-plainify
2764 (company-buffer-lines beg end))
2767 (setq company-pseudo-tooltip-overlay ov)
2768 (overlay-put ov 'company-replacement-args args)
2770 (let ((lines (company--create-lines selection (abs height))))
2771 (overlay-put ov 'company-display
2772 (apply 'company--replacement-string lines args))
2773 (overlay-put ov 'company-width (string-width (car lines))))
2775 (overlay-put ov 'company-column column)
2776 (overlay-put ov 'company-height height)))))
2778 (defun company-pseudo-tooltip-show-at-point (pos column-offset)
2779 (let* ((col-row (company--col-row pos))
2780 (col (- (car col-row) column-offset)))
2781 (when (< col 0) (setq col 0))
2782 (company-pseudo-tooltip-show (1+ (cdr col-row)) col company-selection)))
2784 (defun company-pseudo-tooltip-edit (selection)
2785 (let* ((height (overlay-get company-pseudo-tooltip-overlay 'company-height))
2786 (lines (company--create-lines selection (abs height))))
2787 (overlay-put company-pseudo-tooltip-overlay 'company-width
2788 (string-width (car lines)))
2789 (overlay-put company-pseudo-tooltip-overlay 'company-display
2790 (apply 'company--replacement-string
2792 (overlay-get company-pseudo-tooltip-overlay
2793 'company-replacement-args)))))
2795 (defun company-pseudo-tooltip-hide ()
2796 (when company-pseudo-tooltip-overlay
2797 (delete-overlay company-pseudo-tooltip-overlay)
2798 (setq company-pseudo-tooltip-overlay nil)))
2800 (defun company-pseudo-tooltip-hide-temporarily ()
2801 (when (overlayp company-pseudo-tooltip-overlay)
2802 (overlay-put company-pseudo-tooltip-overlay 'invisible nil)
2803 (overlay-put company-pseudo-tooltip-overlay 'line-prefix nil)
2804 (overlay-put company-pseudo-tooltip-overlay 'after-string nil)
2805 (overlay-put company-pseudo-tooltip-overlay 'display nil)))
2807 (defun company-pseudo-tooltip-unhide ()
2808 (when company-pseudo-tooltip-overlay
2809 (let* ((ov company-pseudo-tooltip-overlay)
2810 (disp (overlay-get ov 'company-display)))
2811 ;; Beat outline's folding overlays, at least.
2812 (overlay-put ov 'priority 1)
2813 ;; No (extra) prefix for the first line.
2814 (overlay-put ov 'line-prefix "")
2815 ;; `display' is better
2816 ;; (http://debbugs.gnu.org/18285, http://debbugs.gnu.org/20847),
2817 ;; but it doesn't work on 0-length overlays.
2818 (if (< (overlay-start ov) (overlay-end ov))
2819 (overlay-put ov 'display disp)
2820 (overlay-put ov 'after-string disp)
2821 (overlay-put ov 'invisible t))
2822 (overlay-put ov 'window (selected-window)))))
2824 (defun company-pseudo-tooltip-guard ()
2826 (save-excursion (beginning-of-visual-line))
2827 (let ((ov company-pseudo-tooltip-overlay)
2828 (overhang (save-excursion (end-of-visual-line)
2829 (- (line-end-position) (point)))))
2830 (when (>= (overlay-get ov 'company-height) 0)
2832 (buffer-substring-no-properties (point) (overlay-start ov))
2833 (when (>= overhang 0) overhang))))))
2835 (defun company-pseudo-tooltip-frontend (command)
2836 "`company-mode' frontend similar to a tooltip but based on overlays."
2838 (pre-command (company-pseudo-tooltip-hide-temporarily))
2840 (unless (when (overlayp company-pseudo-tooltip-overlay)
2841 (let* ((ov company-pseudo-tooltip-overlay)
2842 (old-height (overlay-get ov 'company-height))
2843 (new-height (company--pseudo-tooltip-height)))
2845 (>= (* old-height new-height) 0)
2846 (>= (abs old-height) (abs new-height))
2847 (equal (company-pseudo-tooltip-guard)
2848 (overlay-get ov 'company-guard)))))
2850 (company-pseudo-tooltip-show-at-point (point) (length company-prefix))
2851 (overlay-put company-pseudo-tooltip-overlay
2852 'company-guard (company-pseudo-tooltip-guard)))
2853 (company-pseudo-tooltip-unhide))
2854 (hide (company-pseudo-tooltip-hide)
2855 (setq company-tooltip-offset 0))
2856 (update (when (overlayp company-pseudo-tooltip-overlay)
2857 (company-pseudo-tooltip-edit company-selection)))))
2859 (defun company-pseudo-tooltip-unless-just-one-frontend (command)
2860 "`company-pseudo-tooltip-frontend', but not shown for single candidates."
2861 (unless (and (eq command 'post-command)
2862 (company--show-inline-p))
2863 (company-pseudo-tooltip-frontend command)))
2865 (defun company-pseudo-tooltip-unless-just-one-frontend-with-delay (command)
2866 "`compandy-pseudo-tooltip-frontend', but shown after a delay.
2867 Delay is determined by `company-tooltip-idle-delay'."
2870 (company-pseudo-tooltip-unless-just-one-frontend command)
2871 (when company-tooltip-timer
2872 (cancel-timer company-tooltip-timer)
2873 (setq company-tooltip-timer nil)))
2875 (if (or company-tooltip-timer
2876 (overlayp company-pseudo-tooltip-overlay))
2877 (if (not (memq 'company-preview-frontend company-frontends))
2878 (company-pseudo-tooltip-unless-just-one-frontend command)
2879 (company-preview-frontend 'pre-command)
2880 (company-pseudo-tooltip-unless-just-one-frontend command)
2881 (company-preview-frontend 'post-command))
2882 (setq company-tooltip-timer
2883 (run-with-timer company-tooltip-idle-delay nil
2884 'company-pseudo-tooltip-unless-just-one-frontend-with-delay
2887 (company-pseudo-tooltip-unless-just-one-frontend command))))
2889 ;;; overlay ;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;
2891 (defvar-local company-preview-overlay nil)
2893 (defun company-preview-show-at-point (pos)
2894 (company-preview-hide)
2896 (let ((completion (nth company-selection company-candidates)))
2897 (setq completion (copy-sequence (company--pre-render completion)))
2898 (font-lock-append-text-property 0 (length completion)
2899 'face 'company-preview
2901 (font-lock-prepend-text-property 0 (length company-common)
2902 'face 'company-preview-common
2905 ;; Add search string
2906 (and (string-match (funcall company-search-regexp-function
2907 company-search-string)
2909 (pcase-dolist (`(,mbeg . ,mend) (company--search-chunks))
2910 (font-lock-prepend-text-property mbeg mend
2911 'face 'company-preview-search
2914 (setq completion (company-strip-prefix completion))
2916 (and (equal pos (point))
2917 (not (equal completion ""))
2918 (add-text-properties 0 1 '(cursor 1) completion))
2921 (pto company-pseudo-tooltip-overlay)
2922 (ptf-workaround (and
2925 (eq pos (overlay-start pto)))))
2926 ;; Try to accomodate for the pseudo-tooltip overlay,
2927 ;; which may start at the same position if it's at eol.
2928 (when ptf-workaround
2930 (setq completion (concat (buffer-substring beg pos) completion)))
2932 (setq company-preview-overlay (make-overlay beg pos))
2934 (let ((ov company-preview-overlay))
2935 (overlay-put ov (if ptf-workaround 'display 'after-string)
2937 (overlay-put ov 'window (selected-window))))))
2939 (defun company-preview-hide ()
2940 (when company-preview-overlay
2941 (delete-overlay company-preview-overlay)
2942 (setq company-preview-overlay nil)))
2944 (defun company-preview-frontend (command)
2945 "`company-mode' frontend showing the selection as if it had been inserted."
2947 (`pre-command (company-preview-hide))
2948 (`post-command (company-preview-show-at-point (point)))
2949 (`hide (company-preview-hide))))
2951 (defun company-preview-if-just-one-frontend (command)
2952 "`company-preview-frontend', but only shown for single candidates."
2953 (when (or (not (eq command 'post-command))
2954 (company--show-inline-p))
2955 (company-preview-frontend command)))
2957 (defun company--show-inline-p ()
2958 (and (not (cdr company-candidates))
2960 (or (eq (company-call-backend 'ignore-case) 'keep-prefix)
2961 (string-prefix-p company-prefix company-common))))
2963 (defun company-tooltip-visible-p ()
2964 "Returns whether the tooltip is visible."
2965 (when (overlayp company-pseudo-tooltip-overlay)
2966 (not (overlay-get company-pseudo-tooltip-overlay 'invisible))))
2968 ;;; echo ;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;
2970 (defvar-local company-echo-last-msg nil)
2972 (defvar company-echo-timer nil)
2974 (defvar company-echo-delay .01)
2976 (defun company-echo-show (&optional getter)
2978 (setq company-echo-last-msg (funcall getter)))
2979 (let ((message-log-max nil))
2980 (if company-echo-last-msg
2981 (message "%s" company-echo-last-msg)
2984 (defun company-echo-show-soon (&optional getter)
2985 (company-echo-cancel)
2986 (setq company-echo-timer (run-with-timer 0 nil 'company-echo-show getter)))
2988 (defun company-echo-cancel (&optional unset)
2989 (when company-echo-timer
2990 (cancel-timer company-echo-timer))
2992 (setq company-echo-timer nil)))
2994 (defun company-echo-show-when-idle (&optional getter)
2995 (company-echo-cancel)
2996 (setq company-echo-timer
2997 (run-with-idle-timer company-echo-delay nil 'company-echo-show getter)))
2999 (defun company-echo-format ()
3001 (let ((limit (window-body-width (minibuffer-window)))
3003 ;; Roll to selection.
3004 (candidates (nthcdr company-selection company-candidates))
3005 (i (if company-show-numbers company-selection 99999))
3009 (setq comp (company-reformat (pop candidates))
3010 len (+ len 1 (length comp)))
3014 (setq comp (propertize (format "%d: %s" i comp)
3015 'face 'company-echo))
3018 (add-text-properties 3 (+ 3 (length company-common))
3019 '(face company-echo-common) comp))
3020 (setq comp (propertize comp 'face 'company-echo))
3021 (add-text-properties 0 (length company-common)
3022 '(face company-echo-common) comp))
3024 (setq candidates nil)
3027 (mapconcat 'identity (nreverse msg) " ")))
3029 (defun company-echo-strip-common-format ()
3031 (let ((limit (window-body-width (minibuffer-window)))
3032 (len (+ (length company-prefix) 2))
3033 ;; Roll to selection.
3034 (candidates (nthcdr company-selection company-candidates))
3035 (i (if company-show-numbers company-selection 99999))
3039 (setq comp (company-strip-prefix (pop candidates))
3040 len (+ len 2 (length comp)))
3043 (setq comp (format "%s (%d)" comp i))
3047 (setq candidates nil)
3048 (push (propertize comp 'face 'company-echo) msg)))
3050 (concat (propertize company-prefix 'face 'company-echo-common) "{"
3051 (mapconcat 'identity (nreverse msg) ", ")
3054 (defun company-echo-hide ()
3055 (unless (equal company-echo-last-msg "")
3056 (setq company-echo-last-msg "")
3057 (company-echo-show)))
3059 (defun company-echo-frontend (command)
3060 "`company-mode' frontend showing the candidates in the echo area."
3062 (`post-command (company-echo-show-soon 'company-echo-format))
3063 (`hide (company-echo-hide))))
3065 (defun company-echo-strip-common-frontend (command)
3066 "`company-mode' frontend showing the candidates in the echo area."
3068 (`post-command (company-echo-show-soon 'company-echo-strip-common-format))
3069 (`hide (company-echo-hide))))
3071 (defun company-echo-metadata-frontend (command)
3072 "`company-mode' frontend showing the documentation in the echo area."
3074 (`post-command (company-echo-show-when-idle 'company-fetch-metadata))
3075 (`hide (company-echo-hide))))
3078 ;;; company.el ends here