1 ;;; company.el --- Modular text completion framework -*- lexical-binding: t -*-
3 ;; Copyright (C) 2009-2015 Free Software Foundation, Inc.
5 ;; Author: Nikolaj Schumacher
6 ;; Maintainer: Dmitry Gutov <dgutov@yandex.ru>
7 ;; URL: http://company-mode.github.io/
9 ;; Keywords: abbrev, convenience, matching
10 ;; Package-Requires: ((emacs "24.1") (cl-lib "0.5"))
12 ;; This file is part of GNU Emacs.
14 ;; GNU Emacs is free software: you can redistribute it and/or modify
15 ;; it under the terms of the GNU General Public License as published by
16 ;; the Free Software Foundation, either version 3 of the License, or
17 ;; (at your option) any later version.
19 ;; GNU Emacs is distributed in the hope that it will be useful,
20 ;; but WITHOUT ANY WARRANTY; without even the implied warranty of
21 ;; MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
22 ;; GNU General Public License for more details.
24 ;; You should have received a copy of the GNU General Public License
25 ;; along with GNU Emacs. If not, see <http://www.gnu.org/licenses/>.
29 ;; Company is a modular completion mechanism. Modules for retrieving completion
30 ;; candidates are called backends, modules for displaying them are frontends.
32 ;; Company comes with many backends, e.g. `company-elisp'. These are
33 ;; distributed in separate files and can be used individually.
35 ;; Place company.el and the backends you want to use in a directory and add the
36 ;; following to your .emacs:
37 ;; (add-to-list 'load-path "/path/to/company")
38 ;; (autoload 'company-mode "company" nil t)
40 ;; Enable company-mode with M-x company-mode. For further information look at
41 ;; the documentation for `company-mode' (C-h f company-mode RET)
43 ;; If you want to start a specific backend, call it interactively or use
44 ;; `company-begin-backend'. For example:
45 ;; M-x company-abbrev will prompt for and insert an abbrev.
47 ;; To write your own backend, look at the documentation for `company-backends'.
48 ;; Here is a simple example completing "foo":
50 ;; (defun company-my-backend (command &optional arg &rest ignored)
52 ;; (`prefix (when (looking-back "foo\\>")
54 ;; (`candidates (list "foobar" "foobaz" "foobarbaz"))
55 ;; (`meta (format "This value is named %s" arg))))
57 ;; Sometimes it is a good idea to mix several backends together, for example to
58 ;; enrich gtags with dabbrev-code results (to emulate local variables).
59 ;; To do this, add a list with both backends as an element in company-backends.
63 ;; See NEWS.md in the repository.
70 ;; FIXME: Use `user-error'.
71 (add-to-list 'debug-ignored-errors "^.* frontend cannot be used twice$")
72 (add-to-list 'debug-ignored-errors "^Echo area cannot be used twice$")
73 (add-to-list 'debug-ignored-errors "^No \\(document\\|loc\\)ation available$")
74 (add-to-list 'debug-ignored-errors "^Company not ")
75 (add-to-list 'debug-ignored-errors "^No candidate number ")
76 (add-to-list 'debug-ignored-errors "^Cannot complete at point$")
77 (add-to-list 'debug-ignored-errors "^No other backend$")
81 ;; `defvar-local' for Emacs 24.2 and below
82 (unless (fboundp 'defvar-local)
83 (defmacro defvar-local (var val &optional docstring)
84 "Define VAR as a buffer-local variable with default value VAL.
85 Like `defvar' but additionally marks the variable as being automatically
86 buffer-local wherever it is set."
87 (declare (debug defvar) (doc-string 3))
89 (defvar ,var ,val ,docstring)
90 (make-variable-buffer-local ',var)))))
93 "Extensible inline text completion mechanism"
98 (defface company-tooltip
99 '((default :foreground "black")
100 (((class color) (min-colors 88) (background light))
101 (:background "cornsilk"))
102 (((class color) (min-colors 88) (background dark))
103 (:background "yellow")))
104 "Face used for the tooltip.")
106 (defface company-tooltip-selection
107 '((default :inherit company-tooltip)
108 (((class color) (min-colors 88) (background light))
109 (:background "light blue"))
110 (((class color) (min-colors 88) (background dark))
111 (:background "orange1"))
112 (t (:background "green")))
113 "Face used for the selection in the tooltip.")
115 (defface company-tooltip-search
116 '((default :inherit company-tooltip-selection))
117 "Face used for the search string in the tooltip.")
119 (defface company-tooltip-mouse
120 '((default :inherit highlight))
121 "Face used for the tooltip item under the mouse.")
123 (defface company-tooltip-common
124 '((default :inherit company-tooltip)
125 (((background light))
126 :foreground "darkred")
129 "Face used for the common completion in the tooltip.")
131 (defface company-tooltip-common-selection
132 '((default :inherit company-tooltip-selection)
133 (((background light))
134 :foreground "darkred")
137 "Face used for the selected common completion in the tooltip.")
139 (defface company-tooltip-annotation
140 '((default :inherit company-tooltip)
141 (((background light))
142 :foreground "firebrick4")
145 "Face used for the annotation in the tooltip.")
147 (defface company-scrollbar-fg
148 '((((background light))
149 :background "darkred")
152 "Face used for the tooltip scrollbar thumb.")
154 (defface company-scrollbar-bg
155 '((default :inherit company-tooltip)
156 (((background light))
160 "Face used for the tooltip scrollbar background.")
162 (defface company-preview
163 '((((background light))
164 :inherit company-tooltip-selection)
167 :foreground "wheat"))
168 "Face used for the completion preview.")
170 (defface company-preview-common
171 '((((background light))
172 :inherit company-tooltip-selection)
174 :inherit company-preview
176 "Face used for the common part of the completion preview.")
178 (defface company-preview-search
179 '((((background light))
180 :inherit company-tooltip-common-selection)
182 :inherit company-preview
183 :background "blue1"))
184 "Face used for the search string in the completion preview.")
186 (defface company-echo nil
187 "Face used for completions in the echo area.")
189 (defface company-echo-common
190 '((((background dark)) (:foreground "firebrick1"))
191 (((background light)) (:background "firebrick4")))
192 "Face used for the common part of completions in the echo area.")
194 (defun company-frontends-set (variable value)
196 (let ((value (delete-dups (copy-sequence value))))
197 (and (memq 'company-pseudo-tooltip-unless-just-one-frontend value)
198 (memq 'company-pseudo-tooltip-frontend value)
199 (error "Pseudo tooltip frontend cannot be used twice"))
200 (and (memq 'company-preview-if-just-one-frontend value)
201 (memq 'company-preview-frontend value)
202 (error "Preview frontend cannot be used twice"))
203 (and (memq 'company-echo value)
204 (memq 'company-echo-metadata-frontend value)
205 (error "Echo area cannot be used twice"))
206 ;; Preview must come last.
207 (dolist (f '(company-preview-if-just-one-frontend company-preview-frontend))
208 (when (cdr (memq f value))
209 (setq value (append (delq f value) (list f)))))
210 (set variable value)))
212 (defcustom company-frontends '(company-pseudo-tooltip-unless-just-one-frontend
213 company-preview-if-just-one-frontend
214 company-echo-metadata-frontend)
215 "The list of active frontends (visualizations).
216 Each frontend is a function that takes one argument. It is called with
217 one of the following arguments:
219 `show': When the visualization should start.
221 `hide': When the visualization should end.
223 `update': When the data has been updated.
225 `pre-command': Before every command that is executed while the
226 visualization is active.
228 `post-command': After every command that is executed while the
229 visualization is active.
231 The visualized data is stored in `company-prefix', `company-candidates',
232 `company-common', `company-selection', `company-point' and
233 `company-search-string'."
234 :set 'company-frontends-set
235 :type '(repeat (choice (const :tag "echo" company-echo-frontend)
236 (const :tag "echo, strip common"
237 company-echo-strip-common-frontend)
238 (const :tag "show echo meta-data in echo"
239 company-echo-metadata-frontend)
240 (const :tag "pseudo tooltip"
241 company-pseudo-tooltip-frontend)
242 (const :tag "pseudo tooltip, multiple only"
243 company-pseudo-tooltip-unless-just-one-frontend)
244 (const :tag "preview" company-preview-frontend)
245 (const :tag "preview, unique only"
246 company-preview-if-just-one-frontend)
247 (function :tag "custom function" nil))))
249 (defcustom company-tooltip-limit 10
250 "The maximum number of candidates in the tooltip."
253 (defcustom company-tooltip-minimum 6
254 "The minimum height of the tooltip.
255 If this many lines are not available, prefer to display the tooltip above."
258 (defcustom company-tooltip-minimum-width 0
259 "The minimum width of the tooltip's inner area.
260 This doesn't include the margins and the scroll bar."
262 :package-version '(company . "0.8.0"))
264 (defcustom company-tooltip-margin 1
265 "Width of margin columns to show around the toolip."
268 (defcustom company-tooltip-offset-display 'scrollbar
269 "Method using which the tooltip displays scrolling position.
270 `scrollbar' means draw a scrollbar to the right of the items.
271 `lines' means wrap items in lines with \"before\" and \"after\" counters."
272 :type '(choice (const :tag "Scrollbar" scrollbar)
273 (const :tag "Two lines" lines)))
275 (defcustom company-tooltip-align-annotations nil
276 "When non-nil, align annotations to the right tooltip border."
278 :package-version '(company . "0.7.1"))
280 (defcustom company-tooltip-flip-when-above nil
281 "Whether to flip the tooltip when it's above the current line."
283 :package-version '(company . "0.8.1"))
285 (defvar company-safe-backends
286 '((company-abbrev . "Abbrev")
287 (company-bbdb . "BBDB")
288 (company-capf . "completion-at-point-functions")
289 (company-clang . "Clang")
290 (company-cmake . "CMake")
291 (company-css . "CSS")
292 (company-dabbrev . "dabbrev for plain text")
293 (company-dabbrev-code . "dabbrev for code")
294 (company-eclim . "Eclim (an Eclipse interface)")
295 (company-elisp . "Emacs Lisp")
296 (company-etags . "etags")
297 (company-files . "Files")
298 (company-gtags . "GNU Global")
299 (company-ispell . "Ispell")
300 (company-keywords . "Programming language keywords")
301 (company-nxml . "nxml")
302 (company-oddmuse . "Oddmuse")
303 (company-semantic . "Semantic")
304 (company-tempo . "Tempo templates")
305 (company-xcode . "Xcode")))
306 (put 'company-safe-backends 'risky-local-variable t)
308 (defun company-safe-backends-p (backends)
309 (and (consp backends)
310 (not (cl-dolist (backend backends)
311 (unless (if (consp backend)
312 (company-safe-backends-p backend)
313 (assq backend company-safe-backends))
316 (defcustom company-backends `(,@(unless (version< "24.3.51" emacs-version)
317 (list 'company-elisp))
319 company-nxml company-css
320 company-eclim company-semantic company-clang
321 company-xcode company-cmake
323 (company-dabbrev-code company-gtags company-etags
325 company-oddmuse company-files company-dabbrev)
326 "The list of active backends (completion engines).
328 Only one backend is used at a time. The choice depends on the order of
329 the items in this list, and on the values they return in response to the
330 `prefix' command (see below). But a backend can also be a \"grouped\"
333 `company-begin-backend' can be used to start a specific backend,
334 `company-other-backend' will skip to the next matching backend in the list.
336 Each backend is a function that takes a variable number of arguments.
337 The first argument is the command requested from the backend. It is one
340 `prefix': The backend should return the text to be completed. It must be
341 text immediately before point. Returning nil from this command passes
342 control to the next backend. The function should return `stop' if it
343 should complete but cannot (e.g. if it is in the middle of a string).
344 Instead of a string, the backend may return a cons where car is the prefix
345 and cdr is used instead of the actual prefix length in the comparison
346 against `company-minimum-prefix-length'. It must be either number or t,
347 and in the latter case the test automatically succeeds.
349 `candidates': The second argument is the prefix to be completed. The
350 return value should be a list of candidates that match the prefix.
352 Non-prefix matches are also supported (candidates that don't start with the
353 prefix, but match it in some backend-defined way). Backends that use this
354 feature must disable cache (return t to `no-cache') and might also want to
360 `sorted': Return t here to indicate that the candidates are sorted and will
361 not need to be sorted again.
363 `duplicates': If non-nil, company will take care of removing duplicates
366 `no-cache': Usually company doesn't ask for candidates again as completion
367 progresses, unless the backend returns t for this command. The second
368 argument is the latest prefix.
370 `ignore-case': Return t here if the backend returns case-insensitive
371 matches. This value is used to determine the longest common prefix (as
372 used in `company-complete-common'), and to filter completions when fetching
375 `meta': The second argument is a completion candidate. Return a (short)
376 documentation string for it.
378 `doc-buffer': The second argument is a completion candidate. Return a
379 buffer with documentation for it. Preferably use `company-doc-buffer'. If
380 not all buffer contents pertain to this candidate, return a cons of buffer
381 and window start position.
383 `location': The second argument is a completion candidate. Return a cons
384 of buffer and buffer location, or of file and line number where the
385 completion candidate was defined.
387 `annotation': The second argument is a completion candidate. Return a
388 string to be displayed inline with the candidate in the popup. If
389 duplicates are removed by company, candidates with equal string values will
390 be kept if they have different annotations. For that to work properly,
391 backends should store the related information on candidates using text
394 `match': The second argument is a completion candidate. Return the index
395 after the end of text matching `prefix' within the candidate string. It
396 will be used when rendering the popup. This command only makes sense for
397 backends that provide non-prefix completion.
399 `require-match': If this returns t, the user is not allowed to enter
400 anything not offered as a candidate. Please don't use that value in normal
401 backends. The default value nil gives the user that choice with
402 `company-require-match'. Return value `never' overrides that option the
405 `init': Called once for each buffer. The backend can check for external
406 programs and files and load any required libraries. Raising an error here
407 will show up in message log once, and the backend will not be used for
410 `post-completion': Called after a completion candidate has been inserted
411 into the buffer. The second argument is the candidate. Can be used to
412 modify it, e.g. to expand a snippet.
414 The backend should return nil for all commands it does not support or
415 does not know about. It should also be callable interactively and use
416 `company-begin-backend' to start itself in that case.
421 An element of `company-backends' can also be a list of backends. The
422 completions from backends in such groups are merged, but only from those
423 backends which return the same `prefix'.
425 If a backend command takes a candidate as an argument (e.g. `meta'), the
426 call is dispatched to the backend the candidate came from. In other
427 cases (except for `duplicates' and `sorted'), the first non-nil value among
428 all the backends is returned.
430 The group can also contain keywords. Currently, `:with' and `:sorted'
431 keywords are defined. If the group contains keyword `:with', the backends
432 listed after this keyword are ignored for the purpose of the `prefix'
433 command. If the group contains keyword `:sorted', the final list of
434 candidates is not sorted after concatenation.
436 Asynchronous backends
437 =====================
439 The return value of each command can also be a cons (:async . FETCHER)
440 where FETCHER is a function of one argument, CALLBACK. When the data
441 arrives, FETCHER must call CALLBACK and pass it the appropriate return
442 value, as described above.
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 (repeat :tag "User defined" (function))))
476 (defcustom company-completion-started-hook nil
477 "Hook run when company starts completing.
478 The hook is called with one argument that is non-nil if the completion was
482 (defcustom company-completion-cancelled-hook nil
483 "Hook run when company cancels completing.
484 The hook is called with one argument that is non-nil if the completion was
488 (defcustom company-completion-finished-hook nil
489 "Hook run when company successfully completes.
490 The hook is called with the selected candidate as an argument.
492 If you indend to use it to post-process candidates from a specific
493 backend, consider using the `post-completion' command instead."
496 (defcustom company-minimum-prefix-length 3
497 "The minimum prefix length for idle completion."
498 :type '(integer :tag "prefix length"))
500 (defcustom company-abort-manual-when-too-short nil
501 "If enabled, cancel a manually started completion when the prefix gets
502 shorter than both `company-minimum-prefix-length' and the length of the
503 prefix it was started from."
505 :package-version '(company . "0.8.0"))
507 (defcustom company-require-match 'company-explicit-action-p
508 "If enabled, disallow non-matching input.
509 This can be a function do determine if a match is required.
511 This can be overridden by the backend, if it returns t or `never' to
512 `require-match'. `company-auto-complete' also takes precedence over this."
513 :type '(choice (const :tag "Off" nil)
514 (function :tag "Predicate function")
515 (const :tag "On, if user interaction took place"
516 'company-explicit-action-p)
517 (const :tag "On" t)))
519 (defcustom company-auto-complete nil
520 "Determines when to auto-complete.
521 If this is enabled, all characters from `company-auto-complete-chars'
522 trigger insertion of the selected completion candidate.
523 This can also be a function."
524 :type '(choice (const :tag "Off" nil)
525 (function :tag "Predicate function")
526 (const :tag "On, if user interaction took place"
527 'company-explicit-action-p)
528 (const :tag "On" t)))
530 (defcustom company-auto-complete-chars '(?\ ?\) ?.)
531 "Determines which characters trigger auto-completion.
532 See `company-auto-complete'. If this is a string, each string character
533 tiggers auto-completion. If it is a list of syntax description characters (see
534 `modify-syntax-entry'), all characters with that syntax auto-complete.
536 This can also be a function, which is called with the new input and should
537 return non-nil if company should auto-complete.
539 A character that is part of a valid candidate never triggers auto-completion."
540 :type '(choice (string :tag "Characters")
542 (const :tag "Whitespace" ?\ )
543 (const :tag "Symbol" ?_)
544 (const :tag "Opening parentheses" ?\()
545 (const :tag "Closing parentheses" ?\))
546 (const :tag "Word constituent" ?w)
547 (const :tag "Punctuation." ?.)
548 (const :tag "String quote." ?\")
549 (const :tag "Paired delimiter." ?$)
550 (const :tag "Expression quote or prefix operator." ?\')
551 (const :tag "Comment starter." ?<)
552 (const :tag "Comment ender." ?>)
553 (const :tag "Character-quote." ?/)
554 (const :tag "Generic string fence." ?|)
555 (const :tag "Generic comment fence." ?!))
556 (function :tag "Predicate function")))
558 (defcustom company-idle-delay .5
559 "The idle delay in seconds until completion starts automatically.
560 The prefix still has to satisfy `company-minimum-prefix-length' before that
561 happens. The value of nil means no idle completion."
562 :type '(choice (const :tag "never (nil)" nil)
563 (const :tag "immediate (0)" 0)
564 (number :tag "seconds")))
566 (defcustom company-begin-commands '(self-insert-command
567 org-self-insert-command
568 orgtbl-self-insert-command
573 "A list of commands after which idle completion is allowed.
574 If this is t, it can show completions after any command except a few from a
575 pre-defined list. See `company-idle-delay'.
577 Alternatively, any command with a non-nil `company-begin' property is
578 treated as if it was on this list."
579 :type '(choice (const :tag "Any command" t)
580 (const :tag "Self insert command" '(self-insert-command))
581 (repeat :tag "Commands" function))
582 :package-version '(company . "0.8.4"))
584 (defcustom company-continue-commands '(not save-buffer save-some-buffers
585 save-buffers-kill-terminal
586 save-buffers-kill-emacs)
587 "A list of commands that are allowed during completion.
588 If this is t, or if `company-begin-commands' is t, any command is allowed.
589 Otherwise, the value must be a list of symbols. If it starts with `not',
590 the cdr is the list of commands that abort completion. Otherwise, all
591 commands except those in that list, or in `company-begin-commands', or
592 commands in the `company-' namespace, abort completion."
593 :type '(choice (const :tag "Any command" t)
594 (cons :tag "Any except"
596 (repeat :tag "Commands" function))
597 (repeat :tag "Commands" function)))
599 (defcustom company-show-numbers nil
600 "If enabled, show quick-access numbers for the first ten candidates."
601 :type '(choice (const :tag "off" nil)
602 (const :tag "on" t)))
604 (defcustom company-selection-wrap-around nil
605 "If enabled, selecting item before first or after last wraps around."
606 :type '(choice (const :tag "off" nil)
607 (const :tag "on" t)))
609 (defvar company-async-wait 0.03
610 "Pause between checks to see if the value's been set when turning an
611 asynchronous call into synchronous.")
613 (defvar company-async-timeout 2
614 "Maximum wait time for a value to be set during asynchronous call.")
616 ;;; mode ;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;
618 (defvar company-mode-map (make-sparse-keymap)
619 "Keymap used by `company-mode'.")
621 (defvar company-active-map
622 (let ((keymap (make-sparse-keymap)))
623 (define-key keymap "\e\e\e" 'company-abort)
624 (define-key keymap "\C-g" 'company-abort)
625 (define-key keymap (kbd "M-n") 'company-select-next)
626 (define-key keymap (kbd "M-p") 'company-select-previous)
627 (define-key keymap (kbd "<down>") 'company-select-next-or-abort)
628 (define-key keymap (kbd "<up>") 'company-select-previous-or-abort)
629 (define-key keymap [remap scroll-up-command] 'company-next-page)
630 (define-key keymap [remap scroll-down-command] 'company-previous-page)
631 (define-key keymap [down-mouse-1] 'ignore)
632 (define-key keymap [down-mouse-3] 'ignore)
633 (define-key keymap [mouse-1] 'company-complete-mouse)
634 (define-key keymap [mouse-3] 'company-select-mouse)
635 (define-key keymap [up-mouse-1] 'ignore)
636 (define-key keymap [up-mouse-3] 'ignore)
637 (define-key keymap [return] 'company-complete-selection)
638 (define-key keymap (kbd "RET") 'company-complete-selection)
639 (define-key keymap [tab] 'company-complete-common)
640 (define-key keymap (kbd "TAB") 'company-complete-common)
641 (define-key keymap (kbd "<f1>") 'company-show-doc-buffer)
642 (define-key keymap (kbd "C-h") 'company-show-doc-buffer)
643 (define-key keymap "\C-w" 'company-show-location)
644 (define-key keymap "\C-s" 'company-search-candidates)
645 (define-key keymap "\C-\M-s" 'company-filter-candidates)
647 (define-key keymap (read-kbd-macro (format "M-%d" i)) 'company-complete-number))
649 "Keymap that is enabled during an active completion.")
651 (defvar company--disabled-backends nil)
653 (defun company-init-backend (backend)
654 (and (symbolp backend)
655 (not (fboundp backend))
656 (ignore-errors (require backend nil t)))
661 (funcall backend 'init)
662 (put backend 'company-init t))
664 (put backend 'company-init 'failed)
665 (unless (memq backend company--disabled-backends)
666 (message "Company backend '%s' could not be initialized:\n%s"
667 backend (error-message-string err)))
668 (cl-pushnew backend company--disabled-backends)
670 ;; No initialization for lambdas.
671 ((functionp backend) t)
672 (t ;; Must be a list.
673 (cl-dolist (b backend)
675 (company-init-backend b))))))
677 (defcustom company-lighter-base "company"
678 "Base string to use for the `company-mode' lighter."
680 :package-version '(company . "0.8.10"))
682 (defvar company-lighter '(" "
685 (if (consp company-backend)
686 (company--group-lighter (nth company-selection
688 company-lighter-base)
689 (symbol-name company-backend)))
690 company-lighter-base))
691 "Mode line lighter for Company.
693 The value of this variable is a mode line template as in
694 `mode-line-format'.")
696 (put 'company-lighter 'risky-local-variable t)
699 (define-minor-mode company-mode
700 "\"complete anything\"; is an in-buffer completion framework.
701 Completion starts automatically, depending on the values
702 `company-idle-delay' and `company-minimum-prefix-length'.
704 Completion can be controlled with the commands:
705 `company-complete-common', `company-complete-selection', `company-complete',
706 `company-select-next', `company-select-previous'. If these commands are
707 called before `company-idle-delay', completion will also start.
709 Completions can be searched with `company-search-candidates' or
710 `company-filter-candidates'. These can be used while completion is
713 The completion data is retrieved using `company-backends' and displayed
714 using `company-frontends'. If you want to start a specific backend, call
715 it interactively or use `company-begin-backend'.
717 By default, the completions list is sorted alphabetically, unless the
718 backend chooses otherwise, or `company-transformers' changes it later.
720 regular keymap (`company-mode-map'):
723 keymap during active completions (`company-active-map'):
725 \\{company-active-map}"
726 nil company-lighter company-mode-map
729 (when (eq company-idle-delay t)
730 (setq company-idle-delay 0)
731 (warn "Setting `company-idle-delay' to t is deprecated. Set it to 0 instead."))
732 (add-hook 'pre-command-hook 'company-pre-command nil t)
733 (add-hook 'post-command-hook 'company-post-command nil t)
734 (mapc 'company-init-backend company-backends))
735 (remove-hook 'pre-command-hook 'company-pre-command t)
736 (remove-hook 'post-command-hook 'company-post-command t)
738 (kill-local-variable 'company-point)))
740 (defcustom company-global-modes t
741 "Modes for which `company-mode' mode is turned on by `global-company-mode'.
742 If nil, means no modes. If t, then all major modes have it turned on.
743 If a list, it should be a list of `major-mode' symbol names for which
744 `company-mode' should be automatically turned on. The sense of the list is
745 negated if it begins with `not'. For example:
747 means that `company-mode' is turned on for buffers in C and C++ modes only.
749 means that `company-mode' is always turned on except in `message-mode' buffers."
750 :type '(choice (const :tag "none" nil)
752 (set :menu-tag "mode specific" :tag "modes"
754 (const :tag "Except" not)
755 (repeat :inline t (symbol :tag "mode")))))
758 (define-globalized-minor-mode global-company-mode company-mode company-mode-on)
760 (defun company-mode-on ()
761 (when (and (not (or noninteractive (eq (aref (buffer-name) 0) ?\s)))
762 (cond ((eq company-global-modes t)
764 ((eq (car-safe company-global-modes) 'not)
765 (not (memq major-mode (cdr company-global-modes))))
766 (t (memq major-mode company-global-modes))))
769 (defsubst company-assert-enabled ()
771 (company-uninstall-map)
772 (error "Company not enabled")))
774 ;;; keymaps ;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;
776 (defvar-local company-my-keymap nil)
778 (defvar company-emulation-alist '((t . nil)))
780 (defsubst company-enable-overriding-keymap (keymap)
781 (company-uninstall-map)
782 (setq company-my-keymap keymap))
784 (defun company-ensure-emulation-alist ()
785 (unless (eq 'company-emulation-alist (car emulation-mode-map-alists))
786 (setq emulation-mode-map-alists
787 (cons 'company-emulation-alist
788 (delq 'company-emulation-alist emulation-mode-map-alists)))))
790 (defun company-install-map ()
791 (unless (or (cdar company-emulation-alist)
792 (null company-my-keymap))
793 (setf (cdar company-emulation-alist) company-my-keymap)))
795 (defun company-uninstall-map ()
796 (setf (cdar company-emulation-alist) nil))
799 ;; Emacs calculates the active keymaps before reading the event. That means we
800 ;; cannot change the keymap from a timer. So we send a bogus command.
801 ;; XXX: Even in Emacs 24.4, seems to be needed in the terminal.
802 (defun company-ignore ()
804 (setq this-command last-command))
806 (global-set-key '[company-dummy-event] 'company-ignore)
808 (defun company-input-noop ()
809 (push 'company-dummy-event unread-command-events))
811 (defun company--posn-col-row (posn)
812 (let ((col (car (posn-col-row posn)))
813 ;; `posn-col-row' doesn't work well with lines of different height.
814 ;; `posn-actual-col-row' doesn't handle multiple-width characters.
815 (row (cdr (posn-actual-col-row posn))))
816 (when (and header-line-format (version< emacs-version "24.3.93.3"))
817 ;; http://debbugs.gnu.org/18384
819 (cons (+ col (window-hscroll)) row)))
821 (defun company--col-row (&optional pos)
822 (company--posn-col-row (posn-at-point pos)))
824 (defun company--row (&optional pos)
825 (cdr (company--col-row pos)))
827 ;;; backends ;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;
829 (defvar-local company-backend nil)
831 (defun company-grab (regexp &optional expression limit)
832 (when (looking-back regexp limit)
833 (or (match-string-no-properties (or expression 0)) "")))
835 (defun company-grab-line (regexp &optional expression)
836 (company-grab regexp expression (point-at-bol)))
838 (defun company-grab-symbol ()
839 (if (looking-at "\\_>")
840 (buffer-substring (point) (save-excursion (skip-syntax-backward "w_")
842 (unless (and (char-after) (memq (char-syntax (char-after)) '(?w ?_)))
845 (defun company-grab-word ()
846 (if (looking-at "\\>")
847 (buffer-substring (point) (save-excursion (skip-syntax-backward "w")
849 (unless (and (char-after) (eq (char-syntax (char-after)) ?w))
852 (defun company-grab-symbol-cons (idle-begin-after-re &optional max-len)
853 (let ((symbol (company-grab-symbol)))
856 (forward-char (- (length symbol)))
857 (if (looking-back idle-begin-after-re (if max-len
859 (line-beginning-position)))
863 (defun company-in-string-or-comment ()
864 (let ((ppss (syntax-ppss)))
865 (or (car (setq ppss (nthcdr 3 ppss)))
866 (car (setq ppss (cdr ppss)))
869 (defun company-call-backend (&rest args)
870 (company--force-sync #'company-call-backend-raw args company-backend))
872 (defun company--force-sync (fun args backend)
873 (let ((value (apply fun args)))
874 (if (not (eq (car-safe value) :async))
877 (start (time-to-seconds)))
879 (lambda (result) (setq res result)))
880 (while (eq res 'trash)
881 (if (> (- (time-to-seconds) start) company-async-timeout)
882 (error "Company: backend %s async timeout with args %s"
884 (sleep-for company-async-wait)))
887 (defun company-call-backend-raw (&rest args)
888 (condition-case-unless-debug err
889 (if (functionp company-backend)
890 (apply company-backend args)
891 (apply #'company--multi-backend-adapter company-backend args))
892 (error (error "Company: backend %s error \"%s\" with args %s"
893 company-backend (error-message-string err) args))))
895 (defun company--multi-backend-adapter (backends command &rest args)
896 (let ((backends (cl-loop for b in backends
897 when (not (and (symbolp b)
898 (eq 'failed (get b 'company-init))))
901 (when (eq command 'prefix)
902 (setq backends (butlast backends (length (member :with backends)))))
904 (unless (memq command '(sorted))
905 (setq backends (cl-delete-if #'keywordp backends)))
909 (company--multi-backend-adapter-candidates backends (car args)))
910 (`sorted (memq :sorted backends))
912 ((or `prefix `ignore-case `no-cache `require-match)
914 (cl-dolist (backend backends)
915 (when (setq value (company--force-sync
916 backend (cons command args) backend))
917 (cl-return value)))))
919 (let ((arg (car args)))
920 (when (> (length arg) 0)
921 (let ((backend (or (get-text-property 0 'company-backend arg)
923 (apply backend command args))))))))
925 (defun company--multi-backend-adapter-candidates (backends prefix)
926 (let ((pairs (cl-loop for backend in (cdr backends)
927 when (equal (company--prefix-str
928 (funcall backend 'prefix))
930 collect (cons (funcall backend 'candidates prefix)
935 (propertize str 'company-backend b))
937 (when (equal (company--prefix-str (funcall (car backends) 'prefix)) prefix)
938 ;; Small perf optimization: don't tag the candidates received
939 ;; from the first backend in the group.
940 (push (cons (funcall (car backends) 'candidates prefix)
943 (company--merge-async pairs (lambda (values) (apply #'append values)))))
945 (defun company--merge-async (pairs merger)
946 (let ((async (cl-loop for pair in pairs
948 (eq :async (car-safe (car pair))))))
950 (funcall merger (cl-loop for (val . mapper) in pairs
951 collect (funcall mapper val)))
956 (pending (mapcar #'car pairs))
967 (this-finisher (lambda (res)
968 (setq pending (delq val pending))
969 (setcar cell (funcall mapper res))
970 (funcall finisher))))
971 (if (not (eq :async (car-safe val)))
972 (funcall this-finisher val)
973 (let ((fetcher (cdr val)))
974 (funcall fetcher this-finisher)))))))))))
976 (defun company--prefix-str (prefix)
977 (or (car-safe prefix) prefix))
979 ;;; completion mechanism ;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;
981 (defvar-local company-prefix nil)
983 (defvar-local company-candidates nil)
985 (defvar-local company-candidates-length nil)
987 (defvar-local company-candidates-cache nil)
989 (defvar-local company-candidates-predicate nil)
991 (defvar-local company-common nil)
993 (defvar-local company-selection 0)
995 (defvar-local company-selection-changed nil)
997 (defvar-local company--manual-action nil
998 "Non-nil, if manual completion took place.")
1000 (defvar-local company--manual-prefix nil)
1002 (defvar company--auto-completion nil
1003 "Non-nil when current candidate is being inserted automatically.
1004 Controlled by `company-auto-complete'.")
1006 (defvar-local company--point-max nil)
1008 (defvar-local company-point nil)
1010 (defvar company-timer nil)
1012 (defsubst company-strip-prefix (str)
1013 (substring str (length company-prefix)))
1015 (defun company--insert-candidate (candidate)
1016 (when (> (length candidate) 0)
1017 (setq candidate (substring-no-properties candidate))
1018 ;; XXX: Return value we check here is subject to change.
1019 (if (eq (company-call-backend 'ignore-case) 'keep-prefix)
1020 (insert (company-strip-prefix candidate))
1021 (unless (equal company-prefix candidate)
1022 (delete-region (- (point) (length company-prefix)) (point))
1023 (insert candidate)))))
1025 (defmacro company-with-candidate-inserted (candidate &rest body)
1026 "Evaluate BODY with CANDIDATE temporarily inserted.
1027 This is a tool for backends that need candidates inserted before they
1028 can retrieve meta-data for them."
1029 (declare (indent 1))
1030 `(let ((inhibit-modification-hooks t)
1031 (inhibit-point-motion-hooks t)
1032 (modified-p (buffer-modified-p)))
1033 (company--insert-candidate ,candidate)
1036 (delete-region company-point (point))
1037 (set-buffer-modified-p modified-p))))
1039 (defun company-explicit-action-p ()
1040 "Return whether explicit completion action was taken by the user."
1041 (or company--manual-action
1042 company-selection-changed))
1044 (defun company-reformat (candidate)
1045 ;; company-ispell needs this, because the results are always lower-case
1046 ;; It's mory efficient to fix it only when they are displayed.
1047 ;; FIXME: Adopt the current text's capitalization instead?
1048 (if (eq (company-call-backend 'ignore-case) 'keep-prefix)
1049 (concat company-prefix (substring candidate (length company-prefix)))
1052 (defun company--should-complete ()
1053 (and (eq company-idle-delay 'now)
1054 (not (or buffer-read-only overriding-terminal-local-map
1055 overriding-local-map))
1056 ;; Check if in the middle of entering a key combination.
1057 (or (equal (this-command-keys-vector) [])
1058 (not (keymapp (key-binding (this-command-keys-vector)))))
1059 (not (and transient-mark-mode mark-active))))
1061 (defun company--should-continue ()
1062 (or (eq t company-begin-commands)
1063 (eq t company-continue-commands)
1064 (if (eq 'not (car company-continue-commands))
1065 (not (memq this-command (cdr company-continue-commands)))
1066 (or (memq this-command company-begin-commands)
1067 (memq this-command company-continue-commands)
1068 (and (symbolp this-command)
1069 (string-match-p "\\`company-" (symbol-name this-command)))))))
1071 (defun company-call-frontends (command)
1072 (dolist (frontend company-frontends)
1073 (condition-case-unless-debug err
1074 (funcall frontend command)
1075 (error (error "Company: frontend %s error \"%s\" on command %s"
1076 frontend (error-message-string err) command)))))
1078 (defun company-set-selection (selection &optional force-update)
1080 (if company-selection-wrap-around
1081 (mod selection company-candidates-length)
1082 (max 0 (min (1- company-candidates-length) selection))))
1083 (when (or force-update (not (equal selection company-selection)))
1084 (setq company-selection selection
1085 company-selection-changed t)
1086 (company-call-frontends 'update)))
1088 (defun company--group-lighter (candidate base)
1089 (let ((backend (or (get-text-property 0 'company-backend candidate)
1090 (car company-backend))))
1091 (when (and backend (symbolp backend))
1092 (let ((name (replace-regexp-in-string "company-\\|-company" ""
1093 (symbol-name backend))))
1094 (format "%s-<%s>" base name)))))
1096 (defun company-update-candidates (candidates)
1097 (setq company-candidates-length (length candidates))
1098 (if company-selection-changed
1099 ;; Try to restore the selection
1100 (let ((selected (nth company-selection company-candidates)))
1101 (setq company-selection 0
1102 company-candidates candidates)
1106 (let ((candidate (pop candidates)))
1107 (when (and (string= candidate selected)
1108 (equal (company-call-backend 'annotation candidate)
1109 (company-call-backend 'annotation selected)))
1111 (cl-incf company-selection))
1112 (setq company-selection 0
1113 company-selection-changed nil))))
1114 (setq company-selection 0
1115 company-candidates candidates))
1116 ;; Calculate common.
1117 (let ((completion-ignore-case (company-call-backend 'ignore-case)))
1118 ;; We want to support non-prefix completion, so filtering is the
1119 ;; responsibility of each respective backend, not ours.
1120 ;; On the other hand, we don't want to replace non-prefix input in
1121 ;; `company-complete-common', unless there's only one candidate.
1122 (setq company-common
1123 (if (cdr company-candidates)
1124 (let ((common (try-completion "" company-candidates)))
1125 (when (string-prefix-p company-prefix common
1126 completion-ignore-case)
1128 (car company-candidates)))))
1130 (defun company-calculate-candidates (prefix)
1131 (let ((candidates (cdr (assoc prefix company-candidates-cache)))
1132 (ignore-case (company-call-backend 'ignore-case)))
1134 (when company-candidates-cache
1135 (let ((len (length prefix))
1136 (completion-ignore-case ignore-case)
1138 (cl-dotimes (i (1+ len))
1139 (when (setq prev (cdr (assoc (substring prefix 0 (- len i))
1140 company-candidates-cache)))
1141 (setq candidates (all-completions prefix prev))
1144 ;; No cache match, call the backend.
1145 (setq candidates (company--preprocess-candidates
1146 (company--fetch-candidates prefix)))
1148 (push (cons prefix candidates) company-candidates-cache)))
1149 ;; Only now apply the predicate and transformers.
1150 (setq candidates (company--postprocess-candidates candidates))
1152 (if (or (cdr candidates)
1153 (not (eq t (compare-strings (car candidates) nil nil
1154 prefix nil nil ignore-case))))
1156 ;; Already completed and unique; don't start.
1159 (defun company--fetch-candidates (prefix)
1160 (let ((c (if company--manual-action
1161 (company-call-backend 'candidates prefix)
1162 (company-call-backend-raw 'candidates prefix)))
1164 (if (not (eq (car c) :async))
1166 (let ((buf (current-buffer))
1167 (win (selected-window))
1168 (tick (buffer-chars-modified-tick))
1170 (backend company-backend))
1173 (lambda (candidates)
1174 (if (not (and candidates (eq res 'done)))
1175 ;; There's no completions to display,
1176 ;; or the fetcher called us back right away.
1177 (setq res candidates)
1178 (setq company-backend backend
1179 company-candidates-cache
1181 (company--preprocess-candidates candidates))))
1182 (company-idle-begin buf win tick pt)))))
1183 ;; FIXME: Relying on the fact that the callers
1184 ;; will interpret nil as "do nothing" is shaky.
1185 ;; A throw-catch would be one possible improvement.
1187 (progn (setq res 'done) nil)))))
1189 (defun company--preprocess-candidates (candidates)
1190 (unless (company-call-backend 'sorted)
1191 (setq candidates (sort candidates 'string<)))
1192 (when (company-call-backend 'duplicates)
1193 (company--strip-duplicates candidates))
1196 (defun company--postprocess-candidates (candidates)
1197 (when (or company-candidates-predicate company-transformers)
1198 (setq candidates (copy-sequence candidates)))
1199 (when company-candidates-predicate
1200 (setq candidates (cl-delete-if-not company-candidates-predicate candidates)))
1201 (company--transform-candidates candidates))
1203 (defun company--strip-duplicates (candidates)
1204 (let ((c2 candidates)
1208 (let ((str (pop c2)))
1209 (while (let ((str2 (car c2)))
1210 (if (not (equal str str2))
1214 (when (eq annos 'unk)
1215 (setq annos (list (company-call-backend
1217 (let ((anno2 (company-call-backend
1219 (if (member anno2 annos)
1226 (defun company--transform-candidates (candidates)
1227 (let ((c candidates))
1228 (dolist (tr company-transformers)
1229 (setq c (funcall tr c)))
1232 (defcustom company-occurrence-weight-function
1233 #'company-occurrence-prefer-closest-above
1234 "Function to weigh matches in `company-sort-by-occurrence'.
1235 It's called with three arguments: cursor position, the beginning and the
1238 (const :tag "First above point, then below point"
1239 company-occurrence-prefer-closest-above)
1240 (const :tag "Prefer closest in any direction"
1241 company-occurrence-prefer-any-closest)))
1243 (defun company-occurrence-prefer-closest-above (pos match-beg match-end)
1244 "Give priority to the matches above point, then those below point."
1245 (if (< match-beg pos)
1247 (- match-beg (window-start))))
1249 (defun company-occurrence-prefer-any-closest (pos _match-beg match-end)
1250 "Give priority to the matches closest to the point."
1251 (abs (- pos match-end)))
1253 (defun company-sort-by-occurrence (candidates)
1254 "Sort CANDIDATES according to their occurrences.
1255 Searches for each in the currently visible part of the current buffer and
1256 prioritizes the matches according to `company-occurrence-weight-function'.
1257 The rest of the list is appended unchanged.
1258 Keywords and function definition names are ignored."
1259 (let* ((w-start (window-start))
1260 (w-end (window-end))
1261 (start-point (point))
1269 (while (search-forward candidate w-end t)
1270 (when (and (not (eq (point) start-point))
1272 (company--occurrence-predicate)))
1276 (funcall company-occurrence-weight-function
1284 (mapcar #'car (sort occurs (lambda (e1 e2) (<= (cdr e1) (cdr e2)))))
1287 (defun company--occurrence-predicate ()
1288 (let ((beg (match-beginning 0))
1289 (end (match-end 0)))
1292 (and (not (memq (get-text-property (1- (point)) 'face)
1293 '(font-lock-function-name-face
1294 font-lock-keyword-face)))
1295 (let ((prefix (company--prefix-str
1296 (company-call-backend 'prefix))))
1297 (and (stringp prefix)
1298 (= (length prefix) (- end beg))))))))
1300 (defun company-sort-by-backend-importance (candidates)
1301 "Sort CANDIDATES as two priority groups.
1302 If `company-backend' is a function, do nothing. If it's a list, move
1303 candidates from backends before keyword `:with' to the front. Candidates
1304 from the rest of the backends in the group, if any, will be left at the end."
1305 (if (functionp company-backend)
1307 (let ((low-priority (cdr (memq :with company-backend))))
1308 (if (null low-priority)
1313 (let ((b2 (get-text-property 0 'company-backend c2)))
1314 (and b2 (memq b2 low-priority)))
1315 (let ((b1 (get-text-property 0 'company-backend c1)))
1316 (or (not b1) (not (memq b1 low-priority)))))))))))
1318 (defun company-idle-begin (buf win tick pos)
1319 (and (eq buf (current-buffer))
1320 (eq win (selected-window))
1321 (eq tick (buffer-chars-modified-tick))
1323 (when (company-auto-begin)
1324 (company-input-noop)
1325 (let ((this-command 'company-idle-begin))
1326 (company-post-command)))))
1328 (defun company-auto-begin ()
1330 (not company-candidates)
1331 (let ((company-idle-delay 'now))
1332 (condition-case-unless-debug err
1335 ;; Return non-nil if active.
1337 (error (message "Company: An error occurred in auto-begin")
1338 (message "%s" (error-message-string err))
1340 (quit (company-cancel))))))
1342 (defun company-manual-begin ()
1344 (company-assert-enabled)
1345 (setq company--manual-action t)
1347 (let ((company-minimum-prefix-length 0))
1348 (or company-candidates
1349 (company-auto-begin)))
1350 (unless company-candidates
1351 (setq company--manual-action nil))))
1353 (defun company-other-backend (&optional backward)
1354 (interactive (list current-prefix-arg))
1355 (company-assert-enabled)
1356 (let* ((after (if company-backend
1357 (cdr (member company-backend company-backends))
1359 (before (cdr (member company-backend (reverse company-backends))))
1361 (append before (reverse after))
1362 (append after (reverse before)))))
1364 (cl-dolist (backend next)
1365 (when (ignore-errors (company-begin-backend backend))
1367 (unless company-candidates
1368 (error "No other backend")))
1370 (defun company-require-match-p ()
1371 (let ((backend-value (company-call-backend 'require-match)))
1372 (or (eq backend-value t)
1373 (and (not (eq backend-value 'never))
1374 (if (functionp company-require-match)
1375 (funcall company-require-match)
1376 (eq company-require-match t))))))
1378 (defun company-auto-complete-p (input)
1379 "Return non-nil, if input starts with punctuation or parentheses."
1380 (and (if (functionp company-auto-complete)
1381 (funcall company-auto-complete)
1382 company-auto-complete)
1383 (if (functionp company-auto-complete-chars)
1384 (funcall company-auto-complete-chars input)
1385 (if (consp company-auto-complete-chars)
1386 (memq (char-syntax (string-to-char input))
1387 company-auto-complete-chars)
1388 (string-match (substring input 0 1) company-auto-complete-chars)))))
1390 (defun company--incremental-p ()
1391 (and (> (point) company-point)
1392 (> (point-max) company--point-max)
1393 (not (eq this-command 'backward-delete-char-untabify))
1394 (equal (buffer-substring (- company-point (length company-prefix))
1398 (defun company--continue-failed (new-prefix)
1399 (let ((input (buffer-substring-no-properties (point) company-point)))
1401 ((company-auto-complete-p input)
1404 (goto-char company-point)
1405 (let ((company--auto-completion t))
1406 (company-complete-selection))
1408 ((and (or (not (company-require-match-p))
1409 ;; Don't require match if the new prefix
1410 ;; doesn't continue the old one, and the latter was a match.
1411 (not (stringp new-prefix))
1412 (<= (length new-prefix) (length company-prefix)))
1413 (member company-prefix company-candidates))
1414 ;; Last input was a success,
1415 ;; but we're treating it as an abort + input anyway,
1416 ;; like the `unique' case below.
1417 (company-cancel 'non-unique))
1418 ((company-require-match-p)
1419 ;; Wrong incremental input, but required match.
1420 (delete-char (- (length input)))
1422 (message "Matching input is required")
1424 (t (company-cancel)))))
1426 (defun company--good-prefix-p (prefix)
1427 (and (stringp (company--prefix-str prefix)) ;excludes 'stop
1428 (or (eq (cdr-safe prefix) t)
1429 (let ((len (or (cdr-safe prefix) (length prefix))))
1430 (if company--manual-prefix
1431 (or (not company-abort-manual-when-too-short)
1432 ;; Must not be less than minimum or initial length.
1433 (>= len (min company-minimum-prefix-length
1434 (length company--manual-prefix))))
1435 (>= len company-minimum-prefix-length))))))
1437 (defun company--continue ()
1438 (when (company-call-backend 'no-cache company-prefix)
1439 ;; Don't complete existing candidates, fetch new ones.
1440 (setq company-candidates-cache nil))
1441 (let* ((new-prefix (company-call-backend 'prefix))
1442 (c (when (and (company--good-prefix-p new-prefix)
1443 (setq new-prefix (company--prefix-str new-prefix))
1444 (= (- (point) (length new-prefix))
1445 (- company-point (length company-prefix))))
1446 (company-calculate-candidates new-prefix))))
1449 ;; t means complete/unique.
1450 ;; Handle it like completion was aborted, to differentiate from user
1451 ;; calling one of Company's commands to insert the candidate,
1452 ;; not to trigger template expansion, etc.
1453 (company-cancel 'unique))
1455 ;; incremental match
1456 (setq company-prefix new-prefix)
1457 (company-update-candidates c)
1459 ((not (company--incremental-p))
1461 (t (company--continue-failed new-prefix)))))
1463 (defun company--begin-new ()
1465 (cl-dolist (backend (if company-backend
1466 ;; prefer manual override
1467 (list company-backend)
1470 (if (or (symbolp backend)
1471 (functionp backend))
1472 (when (or (not (symbolp backend))
1473 (eq t (get backend 'company-init))
1474 (unless (get backend 'company-init)
1475 (company-init-backend backend)))
1476 (funcall backend 'prefix))
1477 (company--multi-backend-adapter backend 'prefix)))
1479 (when (company--good-prefix-p prefix)
1480 (setq company-prefix (company--prefix-str prefix)
1481 company-backend backend
1482 c (company-calculate-candidates company-prefix))
1485 (when company--manual-action
1486 (message "No completion found"))
1488 ;; t means complete/unique.
1489 ;; Run the hooks anyway, to e.g. clear the cache.
1490 (company-cancel 'unique)))
1491 (when company--manual-action
1492 (setq company--manual-prefix prefix))
1493 (company-update-candidates c)
1494 (run-hook-with-args 'company-completion-started-hook
1495 (company-explicit-action-p))
1496 (company-call-frontends 'show)))
1499 (defun company--perform ()
1500 (or (and company-candidates (company--continue))
1501 (and (company--should-complete) (company--begin-new)))
1502 (if (not company-candidates)
1503 (setq company-backend nil)
1504 (setq company-point (point)
1505 company--point-max (point-max))
1506 (company-ensure-emulation-alist)
1507 (company-enable-overriding-keymap company-active-map)
1508 (company-call-frontends 'update)))
1510 (defun company-cancel (&optional result)
1512 (when company-prefix
1513 (if (stringp result)
1515 (company-call-backend 'pre-completion result)
1516 (run-hook-with-args 'company-completion-finished-hook result)
1517 (company-call-backend 'post-completion result))
1518 (run-hook-with-args 'company-completion-cancelled-hook result)))
1519 (setq company-backend nil
1521 company-candidates nil
1522 company-candidates-length nil
1523 company-candidates-cache nil
1524 company-candidates-predicate nil
1527 company-selection-changed nil
1528 company--manual-action nil
1529 company--manual-prefix nil
1530 company--point-max nil
1533 (cancel-timer company-timer))
1534 (company-echo-cancel t)
1535 (company-search-mode 0)
1536 (company-call-frontends 'hide)
1537 (company-enable-overriding-keymap nil))
1538 ;; Make return value explicit.
1541 (defun company-abort ()
1543 (company-cancel 'abort))
1545 (defun company-finish (result)
1546 (company--insert-candidate result)
1547 (company-cancel result))
1549 (defsubst company-keep (command)
1550 (and (symbolp command) (get command 'company-keep)))
1552 (defun company-pre-command ()
1553 (unless (company-keep this-command)
1554 (condition-case-unless-debug err
1555 (when company-candidates
1556 (company-call-frontends 'pre-command)
1557 (unless (company--should-continue)
1559 (error (message "Company: An error occurred in pre-command")
1560 (message "%s" (error-message-string err))
1563 (cancel-timer company-timer)
1564 (setq company-timer nil))
1565 (company-echo-cancel t)
1566 (company-uninstall-map))
1568 (defun company-post-command ()
1569 (when (null this-command)
1570 ;; Happens when the user presses `C-g' while inside
1571 ;; `flyspell-post-command-hook', for example.
1572 ;; Or any other `post-command-hook' function that can call `sit-for',
1573 ;; or any quittable timer function.
1575 (setq this-command 'company-abort))
1576 (unless (company-keep this-command)
1577 (condition-case-unless-debug err
1579 (unless (equal (point) company-point)
1580 (let (company-idle-delay) ; Against misbehavior while debugging.
1581 (company--perform)))
1582 (if company-candidates
1583 (company-call-frontends 'post-command)
1584 (and (numberp company-idle-delay)
1585 (not defining-kbd-macro)
1586 (company--should-begin)
1588 (run-with-timer company-idle-delay nil
1590 (current-buffer) (selected-window)
1591 (buffer-chars-modified-tick) (point))))))
1592 (error (message "Company: An error occurred in post-command")
1593 (message "%s" (error-message-string err))
1595 (company-install-map))
1597 (defvar company--begin-inhibit-commands '(company-abort
1598 company-complete-mouse
1600 company-complete-common
1601 company-complete-selection
1602 company-complete-number)
1603 "List of commands after which idle completion is (still) disabled when
1604 `company-begin-commands' is t.")
1606 (defun company--should-begin ()
1607 (if (eq t company-begin-commands)
1608 (not (memq this-command company--begin-inhibit-commands))
1610 (memq this-command company-begin-commands)
1611 (and (symbolp this-command) (get this-command 'company-begin)))))
1613 ;;; search ;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;
1615 (defvar-local company-search-string "")
1617 (defvar company-search-lighter '(" "
1618 (company-search-filtering "Filter" "Search")
1620 company-search-string
1623 (defvar-local company-search-filtering nil
1624 "Non-nil to filter the completion candidates by the search string")
1626 (defvar-local company--search-old-selection 0)
1628 (defvar-local company--search-old-changed nil)
1630 (defun company--search (text lines)
1631 (let ((quoted (regexp-quote text))
1633 (cl-dolist (line lines)
1634 (when (string-match quoted line (length company-prefix))
1638 (defun company-search-keypad ()
1640 (let* ((name (symbol-name last-command-event))
1641 (last-command-event (aref name (1- (length name)))))
1642 (company-search-printing-char)))
1644 (defun company-search-printing-char ()
1646 (company--search-assert-enabled)
1647 (let ((ss (concat company-search-string (string last-command-event))))
1648 (when company-search-filtering
1649 (company--search-update-predicate ss))
1650 (company--search-update-string ss)))
1652 (defun company--search-update-predicate (&optional ss)
1653 (let* ((company-candidates-predicate
1654 (and (not (string= ss ""))
1655 company-search-filtering
1656 (lambda (candidate) (string-match ss candidate))))
1657 (cc (company-calculate-candidates company-prefix)))
1658 (unless cc (error "No match"))
1659 (company-update-candidates cc)))
1661 (defun company--search-update-string (new)
1662 (let* ((pos (company--search new (nthcdr company-selection company-candidates))))
1665 (setq company-search-string new)
1666 (company-set-selection (+ company-selection pos) t))))
1668 (defun company--search-assert-input ()
1669 (company--search-assert-enabled)
1670 (when (string= company-search-string "")
1671 (error "Empty search string")))
1673 (defun company-search-repeat-forward ()
1674 "Repeat the incremental search in completion candidates forward."
1676 (company--search-assert-input)
1677 (let ((pos (company--search company-search-string
1678 (cdr (nthcdr company-selection
1679 company-candidates)))))
1682 (company-set-selection (+ company-selection pos 1) t))))
1684 (defun company-search-repeat-backward ()
1685 "Repeat the incremental search in completion candidates backwards."
1687 (company--search-assert-input)
1688 (let ((pos (company--search company-search-string
1689 (nthcdr (- company-candidates-length
1691 (reverse company-candidates)))))
1694 (company-set-selection (- company-selection pos 1) t))))
1696 (defun company-search-toggle-filtering ()
1697 "Toggle `company-search-filtering'."
1699 (company--search-assert-enabled)
1700 (setq company-search-filtering (not company-search-filtering))
1701 (let ((ss company-search-string))
1702 (company--search-update-predicate ss)
1703 (company--search-update-string ss)))
1705 (defun company-search-abort ()
1706 "Abort searching the completion candidates."
1708 (company--search-assert-enabled)
1709 (company-search-mode 0)
1710 (company-set-selection company--search-old-selection t)
1711 (setq company-selection-changed company--search-old-changed))
1713 (defun company-search-other-char ()
1715 (company--search-assert-enabled)
1716 (company-search-mode 0)
1717 (company--unread-last-input))
1719 (defun company-search-delete-char ()
1721 (company--search-assert-enabled)
1722 (if (string= company-search-string "")
1724 (let ((ss (substring company-search-string 0 -1)))
1725 (when company-search-filtering
1726 (company--search-update-predicate ss))
1727 (company--search-update-string ss))))
1729 (defvar company-search-map
1731 (keymap (make-keymap)))
1732 (if (fboundp 'max-char)
1733 (set-char-table-range (nth 1 keymap) (cons #x100 (max-char))
1734 'company-search-printing-char)
1736 ;; obsolete in Emacs 23
1737 (let ((l (generic-character-list))
1738 (table (nth 1 keymap)))
1740 (set-char-table-default table (car l) 'company-search-printing-char)
1741 (setq l (cdr l))))))
1742 (define-key keymap [t] 'company-search-other-char)
1744 (define-key keymap (make-string 1 i) 'company-search-other-char)
1747 (define-key keymap (vector i) 'company-search-printing-char)
1750 (define-key keymap (read (format "[kp-%s]" i)) 'company-search-keypad))
1751 (let ((meta-map (make-sparse-keymap)))
1752 (define-key keymap (char-to-string meta-prefix-char) meta-map)
1753 (define-key keymap [escape] meta-map))
1754 (define-key keymap (vector meta-prefix-char t) 'company-search-other-char)
1755 (define-key keymap (kbd "M-n") 'company-select-next)
1756 (define-key keymap (kbd "M-p") 'company-select-previous)
1757 (define-key keymap (kbd "<down>") 'company-select-next-or-abort)
1758 (define-key keymap (kbd "<up>") 'company-select-previous-or-abort)
1759 (define-key keymap "\e\e\e" 'company-search-other-char)
1760 (define-key keymap [escape escape escape] 'company-search-other-char)
1761 (define-key keymap (kbd "DEL") 'company-search-delete-char)
1762 (define-key keymap [backspace] 'company-search-delete-char)
1763 (define-key keymap "\C-g" 'company-search-abort)
1764 (define-key keymap "\C-s" 'company-search-repeat-forward)
1765 (define-key keymap "\C-r" 'company-search-repeat-backward)
1766 (define-key keymap "\C-o" 'company-search-toggle-filtering)
1768 (define-key keymap (read-kbd-macro (format "M-%d" i)) 'company-complete-number))
1770 "Keymap used for incrementally searching the completion candidates.")
1772 (define-minor-mode company-search-mode
1773 "Search mode for completion candidates.
1774 Don't start this directly, use `company-search-candidates' or
1775 `company-filter-candidates'."
1776 nil company-search-lighter nil
1777 (if company-search-mode
1778 (if (company-manual-begin)
1780 (setq company--search-old-selection company-selection
1781 company--search-old-changed company-selection-changed)
1782 (company-call-frontends 'update)
1783 (company-enable-overriding-keymap company-search-map))
1784 (setq company-search-mode nil))
1785 (kill-local-variable 'company-search-string)
1786 (kill-local-variable 'company-search-filtering)
1787 (kill-local-variable 'company--search-old-selection)
1788 (kill-local-variable 'company--search-old-changed)
1789 (when company-backend
1790 (company--search-update-predicate "")
1791 (company-call-frontends 'update))
1792 (company-enable-overriding-keymap company-active-map)))
1794 (defun company--search-assert-enabled ()
1795 (company-assert-enabled)
1796 (unless company-search-mode
1797 (company-uninstall-map)
1798 (error "Company not in search mode")))
1800 (defun company-search-candidates ()
1801 "Start searching the completion candidates incrementally.
1803 \\<company-search-map>Search can be controlled with the commands:
1804 - `company-search-repeat-forward' (\\[company-search-repeat-forward])
1805 - `company-search-repeat-backward' (\\[company-search-repeat-backward])
1806 - `company-search-abort' (\\[company-search-abort])
1807 - `company-search-delete-char' (\\[company-search-delete-char])
1809 Regular characters are appended to the search string.
1811 The command `company-search-toggle-filtering' (\\[company-search-toggle-filtering])
1812 uses the search string to filter the completion candidates."
1814 (company-search-mode 1))
1816 (defvar company-filter-map
1817 (let ((keymap (make-keymap)))
1818 (define-key keymap [remap company-search-printing-char]
1819 'company-filter-printing-char)
1820 (set-keymap-parent keymap company-search-map)
1822 "Keymap used for incrementally searching the completion candidates.")
1824 (defun company-filter-candidates ()
1825 "Start filtering the completion candidates incrementally.
1826 This works the same way as `company-search-candidates' immediately
1827 followed by `company-search-toggle-filtering'."
1829 (company-search-mode 1)
1830 (setq company-search-filtering t))
1832 ;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;
1834 (defun company-select-next (&optional arg)
1835 "Select the next candidate in the list.
1837 With ARG, move by that many elements."
1839 (when (company-manual-begin)
1840 (company-set-selection (+ (or arg 1) company-selection))))
1842 (defun company-select-previous (&optional arg)
1843 "Select the previous candidate in the list.
1845 With ARG, move by that many elements."
1847 (company-select-next (if arg (- arg) -1)))
1849 (defun company-select-next-or-abort (&optional arg)
1850 "Select the next candidate if more than one, else abort
1851 and invoke the normal binding.
1853 With ARG, move by that many elements."
1855 (if (> company-candidates-length 1)
1856 (company-select-next arg)
1858 (company--unread-last-input)))
1860 (defun company-select-previous-or-abort (&optional arg)
1861 "Select the previous candidate if more than one, else abort
1862 and invoke the normal binding.
1864 With ARG, move by that many elements."
1866 (if (> company-candidates-length 1)
1867 (company-select-previous arg)
1869 (company--unread-last-input)))
1871 (defun company-next-page ()
1872 "Select the candidate one page further."
1874 (when (company-manual-begin)
1875 (company-set-selection (+ company-selection
1876 company-tooltip-limit))))
1878 (defun company-previous-page ()
1879 "Select the candidate one page earlier."
1881 (when (company-manual-begin)
1882 (company-set-selection (- company-selection
1883 company-tooltip-limit))))
1885 (defvar company-pseudo-tooltip-overlay)
1887 (defvar company-tooltip-offset)
1889 (defun company--inside-tooltip-p (event-col-row row height)
1890 (let* ((ovl company-pseudo-tooltip-overlay)
1891 (column (overlay-get ovl 'company-column))
1892 (width (overlay-get ovl 'company-width))
1893 (evt-col (car event-col-row))
1894 (evt-row (cdr event-col-row)))
1895 (and (>= evt-col column)
1896 (< evt-col (+ column width))
1898 (and (> evt-row row)
1899 (<= evt-row (+ row height) ))
1900 (and (< evt-row row)
1901 (>= evt-row (+ row height)))))))
1903 (defun company--event-col-row (event)
1904 (company--posn-col-row (event-start event)))
1906 (defun company-select-mouse (event)
1907 "Select the candidate picked by the mouse."
1909 (let ((event-col-row (company--event-col-row event))
1910 (ovl-row (company--row))
1911 (ovl-height (and company-pseudo-tooltip-overlay
1912 (min (overlay-get company-pseudo-tooltip-overlay
1914 company-candidates-length))))
1916 (company--inside-tooltip-p event-col-row ovl-row ovl-height))
1918 (company-set-selection (+ (cdr event-col-row)
1919 (1- company-tooltip-offset)
1920 (if (and (eq company-tooltip-offset-display 'lines)
1921 (not (zerop company-tooltip-offset)))
1924 (if (< ovl-height 0)
1929 (company--unread-last-input)
1932 (defun company-complete-mouse (event)
1933 "Insert the candidate picked by the mouse."
1935 (when (company-select-mouse event)
1936 (company-complete-selection)))
1938 (defun company-complete-selection ()
1939 "Insert the selected candidate."
1941 (when (company-manual-begin)
1942 (let ((result (nth company-selection company-candidates)))
1943 (company-finish result))))
1945 (defun company-complete-common ()
1946 "Insert the common part of all candidates."
1948 (when (company-manual-begin)
1949 (if (and (not (cdr company-candidates))
1950 (equal company-common (car company-candidates)))
1951 (company-complete-selection)
1952 (company--insert-candidate company-common))))
1954 (defun company-complete-common-or-cycle (&optional arg)
1955 "Insert the common part of all candidates, or select the next one.
1957 With ARG, move by that many elements."
1959 (when (company-manual-begin)
1960 (let ((tick (buffer-chars-modified-tick)))
1961 (call-interactively 'company-complete-common)
1962 (when (eq tick (buffer-chars-modified-tick))
1963 (let ((company-selection-wrap-around t)
1964 (current-prefix-arg arg))
1965 (call-interactively 'company-select-next))))))
1967 (defun company-indent-or-complete-common ()
1968 "Indent the current line or region, or complete the common part."
1972 (indent-region (region-beginning) (region-end)))
1973 ((let ((old-point (point))
1974 (old-tick (buffer-chars-modified-tick))
1975 (tab-always-indent t))
1976 (call-interactively #'indent-for-tab-command)
1977 (when (and (eq old-point (point))
1978 (eq old-tick (buffer-chars-modified-tick)))
1979 (company-complete-common))))))
1981 (defun company-complete ()
1982 "Insert the common part of all candidates or the current selection.
1983 The first time this is called, the common part is inserted, the second
1984 time, or when the selection has been changed, the selected candidate is
1987 (when (company-manual-begin)
1988 (if (or company-selection-changed
1989 (eq last-command 'company-complete-common))
1990 (call-interactively 'company-complete-selection)
1991 (call-interactively 'company-complete-common)
1992 (setq this-command 'company-complete-common))))
1994 (defun company-complete-number (n)
1995 "Insert the Nth candidate visible in the tooltip.
1996 To show the number next to the candidates in some backends, enable
1997 `company-show-numbers'. When called interactively, uses the last typed
1998 character, stripping the modifiers. That character must be a digit."
2000 (list (let* ((type (event-basic-type last-command-event))
2001 (char (if (characterp type)
2002 ;; Number on the main row.
2004 ;; Keypad number, if bound directly.
2005 (car (last (string-to-list (symbol-name type))))))
2007 (if (zerop n) 10 n))))
2008 (when (company-manual-begin)
2009 (and (or (< n 1) (> n (- company-candidates-length
2010 company-tooltip-offset)))
2011 (error "No candidate number %d" n))
2013 (company-finish (nth (+ n company-tooltip-offset)
2014 company-candidates))))
2016 ;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;
2018 (defconst company-space-strings-limit 100)
2020 (defconst company-space-strings
2022 (dotimes (i company-space-strings-limit)
2023 (push (make-string (- company-space-strings-limit 1 i) ?\ ) lst))
2024 (apply 'vector lst)))
2026 (defun company-space-string (len)
2027 (if (< len company-space-strings-limit)
2028 (aref company-space-strings len)
2029 (make-string len ?\ )))
2031 (defun company-safe-substring (str from &optional to)
2032 (if (> from (string-width str))
2036 (move-to-column from)
2037 (let ((beg (point)))
2041 (concat (buffer-substring beg (point))
2042 (let ((padding (- to (current-column))))
2044 (company-space-string padding)))))
2045 (buffer-substring beg (point-max)))))))
2047 ;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;
2049 (defvar-local company-last-metadata nil)
2051 (defun company-fetch-metadata ()
2052 (let ((selected (nth company-selection company-candidates)))
2053 (unless (eq selected (car company-last-metadata))
2054 (setq company-last-metadata
2055 (cons selected (company-call-backend 'meta selected))))
2056 (cdr company-last-metadata)))
2058 (defun company-doc-buffer (&optional string)
2059 (with-current-buffer (get-buffer-create "*company-documentation*")
2066 (defvar company--electric-commands
2067 '(scroll-other-window scroll-other-window-down mwheel-scroll)
2068 "List of Commands that won't break out of electric commands.")
2070 (defmacro company--electric-do (&rest body)
2071 (declare (indent 0) (debug t))
2072 `(when (company-manual-begin)
2073 (save-window-excursion
2074 (let ((height (window-height))
2075 (row (company--row))
2078 (and (< (window-height) height)
2079 (< (- (window-height) row 2) company-tooltip-limit)
2080 (recenter (- (window-height) row 2)))
2081 (while (memq (setq cmd (key-binding (read-key-sequence-vector nil)))
2082 company--electric-commands)
2084 (call-interactively cmd)
2085 ((beginning-of-buffer end-of-buffer)
2086 (message (error-message-string err)))))
2087 (company--unread-last-input)))))
2089 (defun company--unread-last-input ()
2090 (when last-input-event
2091 (clear-this-command-keys t)
2092 (setq unread-command-events (list last-input-event))))
2094 (defun company-show-doc-buffer ()
2095 "Temporarily show the documentation buffer for the selection."
2097 (let (other-window-scroll-buffer)
2098 (company--electric-do
2099 (let* ((selected (nth company-selection company-candidates))
2100 (doc-buffer (or (company-call-backend 'doc-buffer selected)
2101 (error "No documentation available")))
2103 (when (consp doc-buffer)
2104 (setq start (cdr doc-buffer)
2105 doc-buffer (car doc-buffer)))
2106 (setq other-window-scroll-buffer (get-buffer doc-buffer))
2107 (let ((win (display-buffer doc-buffer t)))
2108 (set-window-start win (if start start (point-min))))))))
2109 (put 'company-show-doc-buffer 'company-keep t)
2111 (defun company-show-location ()
2112 "Temporarily display a buffer showing the selected candidate in context."
2114 (let (other-window-scroll-buffer)
2115 (company--electric-do
2116 (let* ((selected (nth company-selection company-candidates))
2117 (location (company-call-backend 'location selected))
2118 (pos (or (cdr location) (error "No location available")))
2119 (buffer (or (and (bufferp (car location)) (car location))
2120 (find-file-noselect (car location) t))))
2121 (setq other-window-scroll-buffer (get-buffer buffer))
2122 (with-selected-window (display-buffer buffer t)
2125 (if (bufferp (car location))
2127 (goto-char (point-min))
2128 (forward-line (1- pos))))
2129 (set-window-start nil (point)))))))
2130 (put 'company-show-location 'company-keep t)
2132 ;;; package functions ;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;
2134 (defvar-local company-callback nil)
2136 (defun company-remove-callback (&optional ignored)
2137 (remove-hook 'company-completion-finished-hook company-callback t)
2138 (remove-hook 'company-completion-cancelled-hook 'company-remove-callback t)
2139 (remove-hook 'company-completion-finished-hook 'company-remove-callback t))
2141 (defun company-begin-backend (backend &optional callback)
2142 "Start a completion at point using BACKEND."
2143 (interactive (let ((val (completing-read "Company backend: "
2145 'functionp nil "company-")))
2147 (list (intern val)))))
2148 (when (setq company-callback callback)
2149 (add-hook 'company-completion-finished-hook company-callback nil t))
2150 (add-hook 'company-completion-cancelled-hook 'company-remove-callback nil t)
2151 (add-hook 'company-completion-finished-hook 'company-remove-callback nil t)
2152 (setq company-backend backend)
2153 ;; Return non-nil if active.
2154 (or (company-manual-begin)
2155 (error "Cannot complete at point")))
2157 (defun company-begin-with (candidates
2158 &optional prefix-length require-match callback)
2159 "Start a completion at point.
2160 CANDIDATES is the list of candidates to use and PREFIX-LENGTH is the length
2161 of the prefix that already is in the buffer before point.
2164 CALLBACK is a function called with the selected result if the user
2165 successfully completes the input.
2167 Example: \(company-begin-with '\(\"foo\" \"foobar\" \"foobarbaz\"\)\)"
2168 (let ((begin-marker (copy-marker (point) t)))
2169 (company-begin-backend
2170 (lambda (command &optional arg &rest ignored)
2173 (when (equal (point) (marker-position begin-marker))
2174 (buffer-substring (- (point) (or prefix-length 0)) (point))))
2176 (all-completions arg candidates))
2181 (defun company-version (&optional show-version)
2182 "Get the Company version as string.
2184 If SHOW-VERSION is non-nil, show the version in the echo area."
2185 (interactive (list t))
2187 (require 'find-func)
2188 (insert-file-contents (find-library-name "company"))
2191 (message "Company version: %s" (lm-version))
2194 (defun company-diag ()
2195 "Pop a buffer with information about completions at point."
2197 (let* ((bb company-backends)
2199 (prefix (cl-loop for b in bb
2200 thereis (let ((company-backend b))
2202 (company-call-backend 'prefix))))
2204 (when (stringp prefix)
2205 (let ((company-backend backend))
2206 (setq cc (company-call-backend 'candidates prefix)
2209 (lambda (c) (cons c (company-call-backend 'annotation c)))
2211 (pop-to-buffer (get-buffer-create "*company-diag*"))
2212 (setq buffer-read-only nil)
2214 (insert (format "Emacs %s (%s) of %s on %s"
2215 emacs-version system-configuration
2216 (format-time-string "%Y-%m-%d" emacs-build-time)
2217 emacs-build-system))
2218 (insert "\nCompany " (company-version) "\n\n")
2219 (insert "company-backends: " (pp-to-string bb))
2221 (insert "Used backend: " (pp-to-string backend))
2223 (insert "Prefix: " (pp-to-string prefix))
2225 (insert (message "Completions:"))
2226 (unless cc (insert " none"))
2228 (dolist (c annotations)
2229 (insert "\n " (prin1-to-string (car c)))
2231 (insert " " (prin1-to-string (cdr c))))))
2234 ;;; pseudo-tooltip ;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;
2236 (defvar-local company-pseudo-tooltip-overlay nil)
2238 (defvar-local company-tooltip-offset 0)
2240 (defun company-tooltip--lines-update-offset (selection num-lines limit)
2242 (setq company-tooltip-offset
2243 (max (min selection company-tooltip-offset)
2244 (- selection -1 limit)))
2246 (when (<= company-tooltip-offset 1)
2248 (setq company-tooltip-offset 0))
2250 (when (>= company-tooltip-offset (- num-lines limit 1))
2252 (when (= selection (1- num-lines))
2253 (cl-decf company-tooltip-offset)
2254 (when (<= company-tooltip-offset 1)
2255 (setq company-tooltip-offset 0)
2260 (defun company-tooltip--simple-update-offset (selection _num-lines limit)
2261 (setq company-tooltip-offset
2262 (if (< selection company-tooltip-offset)
2264 (max company-tooltip-offset
2265 (- selection limit -1)))))
2269 (defsubst company-round-tab (arg)
2270 (* (/ (+ arg tab-width) tab-width) tab-width))
2272 (defun company-plainify (str)
2273 (let ((prefix (get-text-property 0 'line-prefix str)))
2274 (when prefix ; Keep the original value unmodified, for no special reason.
2275 (setq str (concat prefix str))
2276 (remove-text-properties 0 (length str) '(line-prefix) str)))
2277 (let* ((pieces (split-string str "\t"))
2280 (setcar copy (company-safe-substring
2281 (car copy) 0 (company-round-tab (string-width (car copy)))))
2283 (apply 'concat pieces)))
2285 (defun company-fill-propertize (value annotation width selected left right)
2286 (let* ((margin (length left))
2287 (common (or (company-call-backend 'match value)
2289 (string-width company-common)
2291 (ann-ralign company-tooltip-align-annotations)
2292 (ann-truncate (< width
2293 (+ (length value) (length annotation)
2294 (if ann-ralign 1 0))))
2295 (ann-start (+ margin
2299 (- width (length annotation)))
2301 (ann-end (min (+ ann-start (length annotation)) (+ margin width)))
2303 (if (or ann-truncate (not ann-ralign))
2304 (company-safe-substring
2306 (when (and annotation ann-ralign) " ")
2310 (company-safe-substring value 0
2311 (- width (length annotation)))
2314 (setq common (+ (min common width) margin))
2315 (setq width (+ width margin (length right)))
2317 (add-text-properties 0 width '(face company-tooltip
2318 mouse-face company-tooltip-mouse)
2320 (add-text-properties margin common
2321 '(face company-tooltip-common
2322 mouse-face company-tooltip-mouse)
2324 (when (< ann-start ann-end)
2325 (add-text-properties ann-start ann-end
2326 '(face company-tooltip-annotation
2327 mouse-face company-tooltip-mouse)
2330 (if (and (not (string= company-search-string ""))
2331 (string-match (regexp-quote company-search-string) value
2332 (length company-prefix)))
2333 (let ((beg (+ margin (match-beginning 0)))
2334 (end (+ margin (match-end 0)))
2335 (width (- width (length right))))
2337 (add-text-properties beg (min end width)
2338 '(face company-tooltip-search)
2340 (add-text-properties 0 width '(face company-tooltip-selection
2341 mouse-face company-tooltip-selection)
2343 (add-text-properties margin common
2344 '(face company-tooltip-common-selection
2345 mouse-face company-tooltip-selection)
2349 (defun company--clean-string (str)
2350 (replace-regexp-in-string
2351 "\\([^[:graph:] ]\\)\\|\\(\ufeff\\)\\|[[:multibyte:]]"
2354 ((match-beginning 1)
2355 ;; FIXME: Better char for 'non-printable'?
2356 ;; We shouldn't get any of these, but sometimes we might.
2358 ((match-beginning 2)
2359 ;; Zero-width non-breakable space.
2361 ((> (string-width match) 1)
2363 (make-string (1- (string-width match)) ?\ufeff)
2370 (defun company-buffer-lines (beg end)
2372 (let (lines lines-moved)
2373 (while (and (not (eobp)) ; http://debbugs.gnu.org/19553
2374 (> (setq lines-moved (vertical-motion 1)) 0)
2376 (let ((bound (min end (point))))
2377 ;; A visual line can contain several physical lines (e.g. with outline's
2378 ;; folding overlay). Take only the first one.
2379 (push (buffer-substring beg
2382 (re-search-forward "$" bound 'move)
2385 ;; One physical line can be displayed as several visual ones as well:
2386 ;; add empty strings to the list, to even the count.
2387 (dotimes (_ (1- lines-moved))
2390 (unless (eq beg end)
2391 (push (buffer-substring beg end) lines))
2394 (defun company-modify-line (old new offset)
2395 (concat (company-safe-substring old 0 offset)
2397 (company-safe-substring old (+ offset (length new)))))
2399 (defsubst company--length-limit (lst limit)
2400 (if (nthcdr limit lst)
2404 (defsubst company--window-height ()
2405 (if (fboundp 'window-screen-lines)
2406 (floor (window-screen-lines))
2407 (window-body-height)))
2409 (defun company--window-width ()
2410 (let ((ww (window-body-width)))
2411 ;; Account for the line continuation column.
2412 (when (zerop (cadr (window-fringes)))
2414 (unless (or (display-graphic-p)
2415 (version< "24.3.1" emacs-version))
2416 ;; Emacs 24.3 and earlier included margins
2417 ;; in window-width when in TTY.
2419 (let ((margins (window-margins)))
2420 (+ (or (car margins) 0)
2421 (or (cdr margins) 0)))))
2422 (when (and word-wrap
2423 (version< emacs-version "24.4.51.5"))
2424 ;; http://debbugs.gnu.org/19300
2426 ;; whitespace-mode with newline-mark
2427 (when (and buffer-display-table
2428 (aref buffer-display-table ?\n))
2429 (cl-decf ww (1- (length (aref buffer-display-table ?\n)))))
2432 (defun company--replacement-string (lines old column nl &optional align-top)
2433 (cl-decf column company-tooltip-margin)
2435 (when (and align-top company-tooltip-flip-when-above)
2436 (setq lines (reverse lines)))
2438 (let ((width (length (car lines)))
2439 (remaining-cols (- (+ (company--window-width) (window-hscroll))
2441 (when (> width remaining-cols)
2442 (cl-decf column (- width remaining-cols))))
2444 (let ((offset (and (< column 0) (- column)))
2449 ;; untouched lines first
2450 (dotimes (_ (- (length old) (length lines)))
2451 (push (pop old) new)))
2452 ;; length into old lines.
2454 (push (company-modify-line (pop old)
2455 (company--offset-line (pop lines) offset)
2458 ;; Append whole new lines.
2460 (push (concat (company-space-string column)
2461 (company--offset-line (pop lines) offset))
2464 (let ((str (concat (when nl " \n")
2465 (mapconcat 'identity (nreverse new) "\n")
2467 (font-lock-append-text-property 0 (length str) 'face 'default str)
2468 (when nl (put-text-property 0 1 'cursor t str))
2471 (defun company--offset-line (line offset)
2472 (if (and offset line)
2473 (substring line offset)
2476 (defun company--create-lines (selection limit)
2477 (let ((len company-candidates-length)
2478 (window-width (company--window-width))
2487 ;; Maybe clear old offset.
2488 (when (< len (+ company-tooltip-offset limit))
2489 (setq company-tooltip-offset 0))
2491 ;; Scroll to offset.
2492 (if (eq company-tooltip-offset-display 'lines)
2493 (setq limit (company-tooltip--lines-update-offset selection len limit))
2494 (company-tooltip--simple-update-offset selection len limit))
2497 ((eq company-tooltip-offset-display 'scrollbar)
2498 (setq scrollbar-bounds (company--scrollbar-bounds company-tooltip-offset
2500 ((eq company-tooltip-offset-display 'lines)
2501 (when (> company-tooltip-offset 0)
2502 (setq previous (format "...(%d)" company-tooltip-offset)))
2503 (setq remainder (- len limit company-tooltip-offset)
2504 remainder (when (> remainder 0)
2505 (setq remainder (format "...(%d)" remainder))))))
2507 (cl-decf selection company-tooltip-offset)
2508 (setq width (max (length previous) (length remainder))
2509 lines (nthcdr company-tooltip-offset company-candidates)
2513 (cl-decf window-width (* 2 company-tooltip-margin))
2514 (when scrollbar-bounds (cl-decf window-width))
2517 (let* ((value (pop lines-copy))
2518 (annotation (company-call-backend 'annotation value)))
2519 (setq value (company--clean-string (company-reformat value)))
2521 (when company-tooltip-align-annotations
2522 ;; `lisp-completion-at-point' adds a space.
2523 (setq annotation (comment-string-strip annotation t nil)))
2524 (setq annotation (company--clean-string annotation)))
2525 (push (cons value annotation) items)
2526 (setq width (max (+ (length value)
2527 (if (and annotation company-tooltip-align-annotations)
2528 (1+ (length annotation))
2529 (length annotation)))
2532 (setq width (min window-width
2533 (max company-tooltip-minimum-width
2534 (if company-show-numbers
2538 (let ((items (nreverse items))
2539 (numbered (if company-show-numbers 0 99999))
2542 (push (company--scrollpos-line previous width) new))
2545 (let* ((item (pop items))
2547 (annotation (cdr item))
2548 (right (company-space-string company-tooltip-margin))
2550 (when (< numbered 10)
2553 (setq right (concat (format " %d" (mod numbered 10)) right)))
2555 (company-fill-propertize str annotation
2556 width (equal i selection)
2557 (company-space-string
2558 company-tooltip-margin)
2560 (when scrollbar-bounds
2561 (company--scrollbar i scrollbar-bounds)))
2565 (push (company--scrollpos-line remainder width) new))
2569 (defun company--scrollbar-bounds (offset limit length)
2570 (when (> length limit)
2571 (let* ((size (ceiling (* limit (float limit)) length))
2572 (lower (floor (* limit (float offset)) length))
2573 (upper (+ lower size -1)))
2574 (cons lower upper))))
2576 (defun company--scrollbar (i bounds)
2577 (propertize " " 'face
2578 (if (and (>= i (car bounds)) (<= i (cdr bounds)))
2579 'company-scrollbar-fg
2580 'company-scrollbar-bg)))
2582 (defun company--scrollpos-line (text width)
2583 (propertize (concat (company-space-string company-tooltip-margin)
2584 (company-safe-substring text 0 width)
2585 (company-space-string company-tooltip-margin))
2586 'face 'company-tooltip))
2590 (defun company--pseudo-tooltip-height ()
2591 "Calculate the appropriate tooltip height.
2592 Returns a negative number if the tooltip should be displayed above point."
2593 (let* ((lines (company--row))
2594 (below (- (company--window-height) 1 lines)))
2595 (if (and (< below (min company-tooltip-minimum company-candidates-length))
2597 (- (max 3 (min company-tooltip-limit lines)))
2598 (max 3 (min company-tooltip-limit below)))))
2600 (defun company-pseudo-tooltip-show (row column selection)
2601 (company-pseudo-tooltip-hide)
2604 (let* ((height (company--pseudo-tooltip-height))
2608 (setq row (+ row height -1)
2611 (let* ((nl (< (move-to-window-line row) row))
2613 (end (save-excursion
2614 (move-to-window-line (+ row (abs height)))
2616 (ov (make-overlay beg end nil t))
2617 (args (list (mapcar 'company-plainify
2618 (company-buffer-lines beg end))
2621 (setq company-pseudo-tooltip-overlay ov)
2622 (overlay-put ov 'company-replacement-args args)
2624 (let ((lines (company--create-lines selection (abs height))))
2625 (overlay-put ov 'company-display
2626 (apply 'company--replacement-string lines args))
2627 (overlay-put ov 'company-width (string-width (car lines))))
2629 (overlay-put ov 'company-column column)
2630 (overlay-put ov 'company-height height)))))
2632 (defun company-pseudo-tooltip-show-at-point (pos column-offset)
2633 (let* ((col-row (company--col-row pos))
2634 (col (- (car col-row) column-offset)))
2635 (when (< col 0) (setq col 0))
2636 (company-pseudo-tooltip-show (1+ (cdr col-row)) col company-selection)))
2638 (defun company-pseudo-tooltip-edit (selection)
2639 (let* ((height (overlay-get company-pseudo-tooltip-overlay 'company-height))
2640 (lines (company--create-lines selection (abs height))))
2641 (overlay-put company-pseudo-tooltip-overlay 'company-width
2642 (string-width (car lines)))
2643 (overlay-put company-pseudo-tooltip-overlay 'company-display
2644 (apply 'company--replacement-string
2646 (overlay-get company-pseudo-tooltip-overlay
2647 'company-replacement-args)))))
2649 (defun company-pseudo-tooltip-hide ()
2650 (when company-pseudo-tooltip-overlay
2651 (delete-overlay company-pseudo-tooltip-overlay)
2652 (setq company-pseudo-tooltip-overlay nil)))
2654 (defun company-pseudo-tooltip-hide-temporarily ()
2655 (when (overlayp company-pseudo-tooltip-overlay)
2656 (overlay-put company-pseudo-tooltip-overlay 'invisible nil)
2657 (overlay-put company-pseudo-tooltip-overlay 'line-prefix nil)
2658 (overlay-put company-pseudo-tooltip-overlay 'after-string nil)
2659 (overlay-put company-pseudo-tooltip-overlay 'display nil)))
2661 (defun company-pseudo-tooltip-unhide ()
2662 (when company-pseudo-tooltip-overlay
2663 (let* ((ov company-pseudo-tooltip-overlay)
2664 (disp (overlay-get ov 'company-display)))
2665 ;; Beat outline's folding overlays, at least.
2666 (overlay-put ov 'priority 1)
2667 ;; No (extra) prefix for the first line.
2668 (overlay-put ov 'line-prefix "")
2669 ;; `display' is better
2670 ;; (http://debbugs.gnu.org/18285, http://debbugs.gnu.org/20847),
2671 ;; but it doesn't work on 0-length overlays.
2672 (if (< (overlay-start ov) (overlay-end ov))
2673 (overlay-put ov 'display disp)
2674 (overlay-put ov 'after-string disp)
2675 (overlay-put ov 'invisible t))
2676 (overlay-put ov 'window (selected-window)))))
2678 (defun company-pseudo-tooltip-guard ()
2680 (save-excursion (beginning-of-visual-line))
2681 (let ((ov company-pseudo-tooltip-overlay)
2682 (overhang (save-excursion (end-of-visual-line)
2683 (- (line-end-position) (point)))))
2684 (when (>= (overlay-get ov 'company-height) 0)
2686 (buffer-substring-no-properties (point) (overlay-start ov))
2687 (when (>= overhang 0) overhang))))))
2689 (defun company-pseudo-tooltip-frontend (command)
2690 "`company-mode' frontend similar to a tooltip but based on overlays."
2692 (pre-command (company-pseudo-tooltip-hide-temporarily))
2694 (unless (when (overlayp company-pseudo-tooltip-overlay)
2695 (let* ((ov company-pseudo-tooltip-overlay)
2696 (old-height (overlay-get ov 'company-height))
2697 (new-height (company--pseudo-tooltip-height)))
2699 (>= (* old-height new-height) 0)
2700 (>= (abs old-height) (abs new-height))
2701 (equal (company-pseudo-tooltip-guard)
2702 (overlay-get ov 'company-guard)))))
2704 (company-pseudo-tooltip-show-at-point (point) (length company-prefix))
2705 (overlay-put company-pseudo-tooltip-overlay
2706 'company-guard (company-pseudo-tooltip-guard)))
2707 (company-pseudo-tooltip-unhide))
2708 (hide (company-pseudo-tooltip-hide)
2709 (setq company-tooltip-offset 0))
2710 (update (when (overlayp company-pseudo-tooltip-overlay)
2711 (company-pseudo-tooltip-edit company-selection)))))
2713 (defun company-pseudo-tooltip-unless-just-one-frontend (command)
2714 "`company-pseudo-tooltip-frontend', but not shown for single candidates."
2715 (unless (and (eq command 'post-command)
2716 (company--show-inline-p))
2717 (company-pseudo-tooltip-frontend command)))
2719 ;;; overlay ;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;
2721 (defvar-local company-preview-overlay nil)
2723 (defun company-preview-show-at-point (pos)
2724 (company-preview-hide)
2726 (let ((completion (nth company-selection company-candidates)))
2727 (setq completion (propertize completion 'face 'company-preview))
2728 (add-text-properties 0 (length company-common)
2729 '(face company-preview-common) completion)
2731 ;; Add search string
2732 (and company-search-string
2733 (string-match (regexp-quote company-search-string) completion)
2734 (add-text-properties (match-beginning 0)
2736 '(face company-preview-search)
2739 (setq completion (company-strip-prefix completion))
2741 (and (equal pos (point))
2742 (not (equal completion ""))
2743 (add-text-properties 0 1 '(cursor 1) completion))
2746 (pto company-pseudo-tooltip-overlay)
2747 (ptf-workaround (and
2750 (eq pos (overlay-start pto)))))
2751 ;; Try to accomodate for the pseudo-tooltip overlay,
2752 ;; which may start at the same position if it's at eol.
2753 (when ptf-workaround
2755 (setq completion (concat (buffer-substring beg pos) completion)))
2757 (setq company-preview-overlay (make-overlay beg pos))
2759 (let ((ov company-preview-overlay))
2760 (overlay-put ov (if ptf-workaround 'display 'after-string)
2762 (overlay-put ov 'window (selected-window))))))
2764 (defun company-preview-hide ()
2765 (when company-preview-overlay
2766 (delete-overlay company-preview-overlay)
2767 (setq company-preview-overlay nil)))
2769 (defun company-preview-frontend (command)
2770 "`company-mode' frontend showing the selection as if it had been inserted."
2772 (`pre-command (company-preview-hide))
2773 (`post-command (company-preview-show-at-point (point)))
2774 (`hide (company-preview-hide))))
2776 (defun company-preview-if-just-one-frontend (command)
2777 "`company-preview-frontend', but only shown for single candidates."
2778 (when (or (not (eq command 'post-command))
2779 (company--show-inline-p))
2780 (company-preview-frontend command)))
2782 (defun company--show-inline-p ()
2783 (and (not (cdr company-candidates))
2785 (or (eq (company-call-backend 'ignore-case) 'keep-prefix)
2786 (string-prefix-p company-prefix company-common))))
2788 ;;; echo ;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;
2790 (defvar-local company-echo-last-msg nil)
2792 (defvar company-echo-timer nil)
2794 (defvar company-echo-delay .01)
2796 (defun company-echo-show (&optional getter)
2798 (setq company-echo-last-msg (funcall getter)))
2799 (let ((message-log-max nil))
2800 (if company-echo-last-msg
2801 (message "%s" company-echo-last-msg)
2804 (defun company-echo-show-soon (&optional getter)
2805 (company-echo-cancel)
2806 (setq company-echo-timer (run-with-timer 0 nil 'company-echo-show getter)))
2808 (defun company-echo-cancel (&optional unset)
2809 (when company-echo-timer
2810 (cancel-timer company-echo-timer))
2812 (setq company-echo-timer nil)))
2814 (defun company-echo-show-when-idle (&optional getter)
2815 (company-echo-cancel)
2816 (setq company-echo-timer
2817 (run-with-idle-timer company-echo-delay nil 'company-echo-show getter)))
2819 (defun company-echo-format ()
2821 (let ((limit (window-body-width (minibuffer-window)))
2823 ;; Roll to selection.
2824 (candidates (nthcdr company-selection company-candidates))
2825 (i (if company-show-numbers company-selection 99999))
2829 (setq comp (company-reformat (pop candidates))
2830 len (+ len 1 (length comp)))
2834 (setq comp (propertize (format "%d: %s" i comp)
2835 'face 'company-echo))
2838 (add-text-properties 3 (+ 3 (length company-common))
2839 '(face company-echo-common) comp))
2840 (setq comp (propertize comp 'face 'company-echo))
2841 (add-text-properties 0 (length company-common)
2842 '(face company-echo-common) comp))
2844 (setq candidates nil)
2847 (mapconcat 'identity (nreverse msg) " ")))
2849 (defun company-echo-strip-common-format ()
2851 (let ((limit (window-body-width (minibuffer-window)))
2852 (len (+ (length company-prefix) 2))
2853 ;; Roll to selection.
2854 (candidates (nthcdr company-selection company-candidates))
2855 (i (if company-show-numbers company-selection 99999))
2859 (setq comp (company-strip-prefix (pop candidates))
2860 len (+ len 2 (length comp)))
2863 (setq comp (format "%s (%d)" comp i))
2867 (setq candidates nil)
2868 (push (propertize comp 'face 'company-echo) msg)))
2870 (concat (propertize company-prefix 'face 'company-echo-common) "{"
2871 (mapconcat 'identity (nreverse msg) ", ")
2874 (defun company-echo-hide ()
2875 (unless (equal company-echo-last-msg "")
2876 (setq company-echo-last-msg "")
2877 (company-echo-show)))
2879 (defun company-echo-frontend (command)
2880 "`company-mode' frontend showing the candidates in the echo area."
2882 (`post-command (company-echo-show-soon 'company-echo-format))
2883 (`hide (company-echo-hide))))
2885 (defun company-echo-strip-common-frontend (command)
2886 "`company-mode' frontend showing the candidates in the echo area."
2888 (`post-command (company-echo-show-soon 'company-echo-strip-common-format))
2889 (`hide (company-echo-hide))))
2891 (defun company-echo-metadata-frontend (command)
2892 "`company-mode' frontend showing the documentation in the echo area."
2894 (`post-command (company-echo-show-when-idle 'company-fetch-metadata))
2895 (`hide (company-echo-hide))))
2898 ;;; company.el ends here