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 back-ends, modules for displaying them are front-ends.
32 ;; Company comes with many back-ends, e.g. `company-elisp'. These are
33 ;; distributed in separate files and can be used individually.
35 ;; Place company.el and the back-ends you want to use in a directory and add the
36 ;; following to your .emacs:
37 ;; (add-to-list 'load-path "/path/to/company")
38 ;; (autoload 'company-mode "company" nil t)
40 ;; Enable company-mode with M-x company-mode. For further information look at
41 ;; the documentation for `company-mode' (C-h f company-mode RET)
43 ;; If you want to start a specific back-end, call it interactively or use
44 ;; `company-begin-backend'. For example:
45 ;; M-x company-abbrev will prompt for and insert an abbrev.
47 ;; To write your own back-end, look at the documentation for `company-backends'.
48 ;; Here is a simple example completing "foo":
50 ;; (defun company-my-backend (command &optional arg &rest ignored)
52 ;; (`prefix (when (looking-back "foo\\>")
54 ;; (`candidates (list "foobar" "foobaz" "foobarbaz"))
55 ;; (`meta (format "This value is named %s" arg))))
57 ;; Sometimes it is a good idea to mix several back-ends together, for example to
58 ;; enrich gtags with dabbrev-code results (to emulate local variables).
59 ;; To do this, add a list with both back-ends as an element in company-backends.
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 back-end$")
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 front-ends (visualizations).
216 Each front-end 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 back-ends (completion engines).
328 Only one back-end 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 back-end can also be a \"grouped\"
333 `company-begin-backend' can be used to start a specific back-end,
334 `company-other-backend' will skip to the next matching back-end in the list.
336 Each back-end is a function that takes a variable number of arguments.
337 The first argument is the command requested from the back-end. It is one
340 `prefix': The back-end 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 back-end. 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 back-end may return a cons where car is the prefix
345 and cdr is used in `company-minimum-prefix-length' test. It must be either
346 number or t, and in the latter case the test automatically succeeds.
348 `candidates': The second argument is the prefix to be completed. The
349 return value should be a list of candidates that match the prefix.
351 Non-prefix matches are also supported (candidates that don't start with the
352 prefix, but match it in some backend-defined way). Backends that use this
353 feature must disable cache (return t to `no-cache') and might also want to
358 `sorted': Return t here to indicate that the candidates are sorted and will
359 not need to be sorted again.
361 `duplicates': If non-nil, company will take care of removing duplicates
364 `no-cache': Usually company doesn't ask for candidates again as completion
365 progresses, unless the back-end returns t for this command. The second
366 argument is the latest prefix.
368 `meta': The second argument is a completion candidate. Return a (short)
369 documentation string for it.
371 `doc-buffer': The second argument is a completion candidate. Return a
372 buffer with documentation for it. Preferably use `company-doc-buffer',
374 `location': The second argument is a completion candidate. Return the cons
375 of buffer and buffer location, or of file and line number where the
376 completion candidate was defined.
378 `annotation': The second argument is a completion candidate. Return a
379 string to be displayed inline with the candidate in the popup. If
380 duplicates are removed by company, candidates with equal string values will
381 be kept if they have different annotations. For that to work properly,
382 backends should store the related information on candidates using text
385 `match': The second argument is a completion candidate. Return the index
386 after the end of text matching `prefix' within the candidate string. It
387 will be used when rendering the popup. This command only makes sense for
388 backends that provide non-prefix completion.
390 `require-match': If this returns t, the user is not allowed to enter
391 anything not offered as a candidate. Use with care! The default value nil
392 gives the user that choice with `company-require-match'. Return value
393 `never' overrides that option the other way around.
395 `init': Called once for each buffer. The back-end can check for external
396 programs and files and load any required libraries. Raising an error here
397 will show up in message log once, and the back-end will not be used for
400 `post-completion': Called after a completion candidate has been inserted
401 into the buffer. The second argument is the candidate. Can be used to
402 modify it, e.g. to expand a snippet.
404 The back-end should return nil for all commands it does not support or
405 does not know about. It should also be callable interactively and use
406 `company-begin-backend' to start itself in that case.
410 An element of `company-backends' can also itself be a list of back-ends,
411 then it's considered to be a \"grouped\" back-end.
413 When possible, commands taking a candidate as an argument are dispatched to
414 the back-end it came from. In other cases, the first non-nil value among
415 all the back-ends is returned.
417 The latter is the case for the `prefix' command. But if the group contains
418 the keyword `:with', the back-ends after it are ignored for this command.
420 The completions from back-ends in a group are merged (but only from those
421 that return the same `prefix').
423 Asynchronous back-ends:
425 The return value of each command can also be a cons (:async . FETCHER)
426 where FETCHER is a function of one argument, CALLBACK. When the data
427 arrives, FETCHER must call CALLBACK and pass it the appropriate return
428 value, as described above.
430 True asynchronous operation is only supported for command `candidates', and
431 only during idle completion. Other commands will block the user interface,
432 even if the back-end uses the asynchronous calling convention."
436 ,@(mapcar (lambda (b) `(const :tag ,(cdr b) ,(car b)))
437 company-safe-backends)
438 (symbol :tag "User defined")
439 (repeat :tag "Merged Back-ends"
440 (choice :tag "Back-end"
441 ,@(mapcar (lambda (b)
442 `(const :tag ,(cdr b) ,(car b)))
443 company-safe-backends)
444 (const :tag "With" :with)
445 (symbol :tag "User defined"))))))
447 (put 'company-backends 'safe-local-variable 'company-safe-backends-p)
449 (defcustom company-transformers nil
450 "Functions to change the list of candidates received from backends.
452 Each function gets called with the return value of the previous one.
453 The first one gets passed the list of candidates, already sorted and
456 (const :tag "None" nil)
457 (const :tag "Sort by occurrence" (company-sort-by-occurrence))
458 (const :tag "Sort by back-end importance"
459 (company-sort-by-backend-importance))
460 (repeat :tag "User defined" (function))))
462 (defcustom company-completion-started-hook nil
463 "Hook run when company starts completing.
464 The hook is called with one argument that is non-nil if the completion was
468 (defcustom company-completion-cancelled-hook nil
469 "Hook run when company cancels completing.
470 The hook is called with one argument that is non-nil if the completion was
474 (defcustom company-completion-finished-hook nil
475 "Hook run when company successfully completes.
476 The hook is called with the selected candidate as an argument.
478 If you indend to use it to post-process candidates from a specific
479 back-end, consider using the `post-completion' command instead."
482 (defcustom company-minimum-prefix-length 3
483 "The minimum prefix length for idle completion."
484 :type '(integer :tag "prefix length"))
486 (defcustom company-abort-manual-when-too-short nil
487 "If enabled, cancel a manually started completion when the prefix gets
488 shorter than both `company-minimum-prefix-length' and the length of the
489 prefix it was started from."
491 :package-version '(company . "0.8.0"))
493 (defcustom company-require-match 'company-explicit-action-p
494 "If enabled, disallow non-matching input.
495 This can be a function do determine if a match is required.
497 This can be overridden by the back-end, if it returns t or `never' to
498 `require-match'. `company-auto-complete' also takes precedence over this."
499 :type '(choice (const :tag "Off" nil)
500 (function :tag "Predicate function")
501 (const :tag "On, if user interaction took place"
502 'company-explicit-action-p)
503 (const :tag "On" t)))
505 (defcustom company-auto-complete nil
506 "Determines when to auto-complete.
507 If this is enabled, all characters from `company-auto-complete-chars'
508 trigger insertion of the selected completion candidate.
509 This can also be a function."
510 :type '(choice (const :tag "Off" nil)
511 (function :tag "Predicate function")
512 (const :tag "On, if user interaction took place"
513 'company-explicit-action-p)
514 (const :tag "On" t)))
516 (defcustom company-auto-complete-chars '(?\ ?\) ?.)
517 "Determines which characters trigger auto-completion.
518 See `company-auto-complete'. If this is a string, each string character
519 tiggers auto-completion. If it is a list of syntax description characters (see
520 `modify-syntax-entry'), all characters with that syntax auto-complete.
522 This can also be a function, which is called with the new input and should
523 return non-nil if company should auto-complete.
525 A character that is part of a valid candidate never triggers auto-completion."
526 :type '(choice (string :tag "Characters")
528 (const :tag "Whitespace" ?\ )
529 (const :tag "Symbol" ?_)
530 (const :tag "Opening parentheses" ?\()
531 (const :tag "Closing parentheses" ?\))
532 (const :tag "Word constituent" ?w)
533 (const :tag "Punctuation." ?.)
534 (const :tag "String quote." ?\")
535 (const :tag "Paired delimiter." ?$)
536 (const :tag "Expression quote or prefix operator." ?\')
537 (const :tag "Comment starter." ?<)
538 (const :tag "Comment ender." ?>)
539 (const :tag "Character-quote." ?/)
540 (const :tag "Generic string fence." ?|)
541 (const :tag "Generic comment fence." ?!))
542 (function :tag "Predicate function")))
544 (defcustom company-idle-delay .5
545 "The idle delay in seconds until completion starts automatically.
546 The prefix still has to satisfy `company-minimum-prefix-length' before that
547 happens. The value of nil means no idle completion."
548 :type '(choice (const :tag "never (nil)" nil)
549 (const :tag "immediate (0)" 0)
550 (number :tag "seconds")))
552 (defcustom company-begin-commands '(self-insert-command
553 org-self-insert-command
554 orgtbl-self-insert-command
559 "A list of commands after which idle completion is allowed.
560 If this is t, it can show completions after any command except a few from a
561 pre-defined list. See `company-idle-delay'.
563 Alternatively, any command with a non-nil `company-begin' property is
564 treated as if it was on this list."
565 :type '(choice (const :tag "Any command" t)
566 (const :tag "Self insert command" '(self-insert-command))
567 (repeat :tag "Commands" function))
568 :package-version '(company . "0.8.4"))
570 (defcustom company-continue-commands '(not save-buffer save-some-buffers
571 save-buffers-kill-terminal
572 save-buffers-kill-emacs)
573 "A list of commands that are allowed during completion.
574 If this is t, or if `company-begin-commands' is t, any command is allowed.
575 Otherwise, the value must be a list of symbols. If it starts with `not',
576 the cdr is the list of commands that abort completion. Otherwise, all
577 commands except those in that list, or in `company-begin-commands', or
578 commands in the `company-' namespace, abort completion."
579 :type '(choice (const :tag "Any command" t)
580 (cons :tag "Any except"
582 (repeat :tag "Commands" function))
583 (repeat :tag "Commands" function)))
585 (defcustom company-show-numbers nil
586 "If enabled, show quick-access numbers for the first ten candidates."
587 :type '(choice (const :tag "off" nil)
588 (const :tag "on" t)))
590 (defcustom company-selection-wrap-around nil
591 "If enabled, selecting item before first or after last wraps around."
592 :type '(choice (const :tag "off" nil)
593 (const :tag "on" t)))
595 (defvar company-async-wait 0.03
596 "Pause between checks to see if the value's been set when turning an
597 asynchronous call into synchronous.")
599 (defvar company-async-timeout 2
600 "Maximum wait time for a value to be set during asynchronous call.")
602 ;;; mode ;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;
604 (defvar company-mode-map (make-sparse-keymap)
605 "Keymap used by `company-mode'.")
607 (defvar company-active-map
608 (let ((keymap (make-sparse-keymap)))
609 (define-key keymap "\e\e\e" 'company-abort)
610 (define-key keymap "\C-g" 'company-abort)
611 (define-key keymap (kbd "M-n") 'company-select-next)
612 (define-key keymap (kbd "M-p") 'company-select-previous)
613 (define-key keymap (kbd "<down>") 'company-select-next-or-abort)
614 (define-key keymap (kbd "<up>") 'company-select-previous-or-abort)
615 (define-key keymap [remap scroll-up-command] 'company-next-page)
616 (define-key keymap [remap scroll-down-command] 'company-previous-page)
617 (define-key keymap [down-mouse-1] 'ignore)
618 (define-key keymap [down-mouse-3] 'ignore)
619 (define-key keymap [mouse-1] 'company-complete-mouse)
620 (define-key keymap [mouse-3] 'company-select-mouse)
621 (define-key keymap [up-mouse-1] 'ignore)
622 (define-key keymap [up-mouse-3] 'ignore)
623 (define-key keymap [return] 'company-complete-selection)
624 (define-key keymap (kbd "RET") 'company-complete-selection)
625 (define-key keymap [tab] 'company-complete-common)
626 (define-key keymap (kbd "TAB") 'company-complete-common)
627 (define-key keymap (kbd "<f1>") 'company-show-doc-buffer)
628 (define-key keymap (kbd "C-h") 'company-show-doc-buffer)
629 (define-key keymap "\C-w" 'company-show-location)
630 (define-key keymap "\C-s" 'company-search-candidates)
631 (define-key keymap "\C-\M-s" 'company-filter-candidates)
633 (define-key keymap (read-kbd-macro (format "M-%d" i)) 'company-complete-number))
635 "Keymap that is enabled during an active completion.")
637 (defvar company--disabled-backends nil)
639 (defun company-init-backend (backend)
640 (and (symbolp backend)
641 (not (fboundp backend))
642 (ignore-errors (require backend nil t)))
647 (funcall backend 'init)
648 (put backend 'company-init t))
650 (put backend 'company-init 'failed)
651 (unless (memq backend company--disabled-backends)
652 (message "Company back-end '%s' could not be initialized:\n%s"
653 backend (error-message-string err)))
654 (cl-pushnew backend company--disabled-backends)
656 ;; No initialization for lambdas.
657 ((functionp backend) t)
658 (t ;; Must be a list.
659 (cl-dolist (b backend)
661 (company-init-backend b))))))
663 (defcustom company-lighter-base "company"
664 "Base string to use for the `company-mode' lighter."
666 :package-version '(company . "0.8.10"))
668 (defvar company-lighter '(" "
671 (if (consp company-backend)
672 (company--group-lighter (nth company-selection
674 company-lighter-base)
675 (symbol-name company-backend)))
676 company-lighter-base))
677 "Mode line lighter for Company.
679 The value of this variable is a mode line template as in
680 `mode-line-format'.")
682 (put 'company-lighter 'risky-local-variable t)
685 (define-minor-mode company-mode
686 "\"complete anything\"; is an in-buffer completion framework.
687 Completion starts automatically, depending on the values
688 `company-idle-delay' and `company-minimum-prefix-length'.
690 Completion can be controlled with the commands:
691 `company-complete-common', `company-complete-selection', `company-complete',
692 `company-select-next', `company-select-previous'. If these commands are
693 called before `company-idle-delay', completion will also start.
695 Completions can be searched with `company-search-candidates' or
696 `company-filter-candidates'. These can be used while completion is
699 The completion data is retrieved using `company-backends' and displayed
700 using `company-frontends'. If you want to start a specific back-end, call
701 it interactively or use `company-begin-backend'.
703 regular keymap (`company-mode-map'):
706 keymap during active completions (`company-active-map'):
708 \\{company-active-map}"
709 nil company-lighter company-mode-map
712 (when (eq company-idle-delay t)
713 (setq company-idle-delay 0)
714 (warn "Setting `company-idle-delay' to t is deprecated. Set it to 0 instead."))
715 (add-hook 'pre-command-hook 'company-pre-command nil t)
716 (add-hook 'post-command-hook 'company-post-command nil t)
717 (mapc 'company-init-backend company-backends))
718 (remove-hook 'pre-command-hook 'company-pre-command t)
719 (remove-hook 'post-command-hook 'company-post-command t)
721 (kill-local-variable 'company-point)))
723 (defcustom company-global-modes t
724 "Modes for which `company-mode' mode is turned on by `global-company-mode'.
725 If nil, means no modes. If t, then all major modes have it turned on.
726 If a list, it should be a list of `major-mode' symbol names for which
727 `company-mode' should be automatically turned on. The sense of the list is
728 negated if it begins with `not'. For example:
730 means that `company-mode' is turned on for buffers in C and C++ modes only.
732 means that `company-mode' is always turned on except in `message-mode' buffers."
733 :type '(choice (const :tag "none" nil)
735 (set :menu-tag "mode specific" :tag "modes"
737 (const :tag "Except" not)
738 (repeat :inline t (symbol :tag "mode")))))
741 (define-globalized-minor-mode global-company-mode company-mode company-mode-on)
743 (defun company-mode-on ()
744 (when (and (not (or noninteractive (eq (aref (buffer-name) 0) ?\s)))
745 (cond ((eq company-global-modes t)
747 ((eq (car-safe company-global-modes) 'not)
748 (not (memq major-mode (cdr company-global-modes))))
749 (t (memq major-mode company-global-modes))))
752 (defsubst company-assert-enabled ()
754 (company-uninstall-map)
755 (error "Company not enabled")))
757 ;;; keymaps ;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;
759 (defvar-local company-my-keymap nil)
761 (defvar company-emulation-alist '((t . nil)))
763 (defsubst company-enable-overriding-keymap (keymap)
764 (company-uninstall-map)
765 (setq company-my-keymap keymap))
767 (defun company-ensure-emulation-alist ()
768 (unless (eq 'company-emulation-alist (car emulation-mode-map-alists))
769 (setq emulation-mode-map-alists
770 (cons 'company-emulation-alist
771 (delq 'company-emulation-alist emulation-mode-map-alists)))))
773 (defun company-install-map ()
774 (unless (or (cdar company-emulation-alist)
775 (null company-my-keymap))
776 (setf (cdar company-emulation-alist) company-my-keymap)))
778 (defun company-uninstall-map ()
779 (setf (cdar company-emulation-alist) nil))
782 ;; Emacs calculates the active keymaps before reading the event. That means we
783 ;; cannot change the keymap from a timer. So we send a bogus command.
784 ;; XXX: Even in Emacs 24.4, seems to be needed in the terminal.
785 (defun company-ignore ()
787 (setq this-command last-command))
789 (global-set-key '[company-dummy-event] 'company-ignore)
791 (defun company-input-noop ()
792 (push 'company-dummy-event unread-command-events))
794 (defun company--posn-col-row (posn)
795 (let ((col (car (posn-col-row posn)))
796 ;; `posn-col-row' doesn't work well with lines of different height.
797 ;; `posn-actual-col-row' doesn't handle multiple-width characters.
798 (row (cdr (posn-actual-col-row posn))))
799 (when (and header-line-format (version< emacs-version "24.3.93.3"))
800 ;; http://debbugs.gnu.org/18384
802 (cons (+ col (window-hscroll)) row)))
804 (defun company--col-row (&optional pos)
805 (company--posn-col-row (posn-at-point pos)))
807 (defun company--row (&optional pos)
808 (cdr (company--col-row pos)))
810 ;;; backends ;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;
812 (defvar-local company-backend nil)
814 (defun company-grab (regexp &optional expression limit)
815 (when (looking-back regexp limit)
816 (or (match-string-no-properties (or expression 0)) "")))
818 (defun company-grab-line (regexp &optional expression)
819 (company-grab regexp expression (point-at-bol)))
821 (defun company-grab-symbol ()
822 (if (looking-at "\\_>")
823 (buffer-substring (point) (save-excursion (skip-syntax-backward "w_")
825 (unless (and (char-after) (memq (char-syntax (char-after)) '(?w ?_)))
828 (defun company-grab-word ()
829 (if (looking-at "\\>")
830 (buffer-substring (point) (save-excursion (skip-syntax-backward "w")
832 (unless (and (char-after) (eq (char-syntax (char-after)) ?w))
835 (defun company-grab-symbol-cons (idle-begin-after-re &optional max-len)
836 (let ((symbol (company-grab-symbol)))
839 (forward-char (- (length symbol)))
840 (if (looking-back idle-begin-after-re (if max-len
842 (line-beginning-position)))
846 (defun company-in-string-or-comment ()
847 (let ((ppss (syntax-ppss)))
848 (or (car (setq ppss (nthcdr 3 ppss)))
849 (car (setq ppss (cdr ppss)))
852 (defun company-call-backend (&rest args)
853 (company--force-sync #'company-call-backend-raw args company-backend))
855 (defun company--force-sync (fun args backend)
856 (let ((value (apply fun args)))
857 (if (not (eq (car-safe value) :async))
860 (start (time-to-seconds)))
862 (lambda (result) (setq res result)))
863 (while (eq res 'trash)
864 (if (> (- (time-to-seconds) start) company-async-timeout)
865 (error "Company: Back-end %s async timeout with args %s"
867 (sleep-for company-async-wait)))
870 (defun company-call-backend-raw (&rest args)
871 (condition-case-unless-debug err
872 (if (functionp company-backend)
873 (apply company-backend args)
874 (apply #'company--multi-backend-adapter company-backend args))
875 (error (error "Company: Back-end %s error \"%s\" with args %s"
876 company-backend (error-message-string err) args))))
878 (defun company--multi-backend-adapter (backends command &rest args)
879 (let ((backends (cl-loop for b in backends
880 when (not (and (symbolp b)
881 (eq 'failed (get b 'company-init))))
884 (if (eq command 'prefix)
885 (butlast backends (length (member :with backends)))
886 (delq :with backends)))
889 (company--multi-backend-adapter-candidates backends (car args)))
892 ((or `prefix `ignore-case `no-cache `require-match)
894 (cl-dolist (backend backends)
895 (when (setq value (company--force-sync
896 backend (cons command args) backend))
897 (cl-return value)))))
899 (let ((arg (car args)))
900 (when (> (length arg) 0)
901 (let ((backend (or (get-text-property 0 'company-backend arg)
903 (apply backend command args))))))))
905 (defun company--multi-backend-adapter-candidates (backends prefix)
906 (let ((pairs (cl-loop for backend in (cdr backends)
907 when (equal (company--prefix-str
908 (funcall backend 'prefix))
910 collect (cons (funcall backend 'candidates prefix)
915 (propertize str 'company-backend b))
917 (when (equal (company--prefix-str (funcall (car backends) 'prefix)) prefix)
918 ;; Small perf optimization: don't tag the candidates received
919 ;; from the first backend in the group.
920 (push (cons (funcall (car backends) 'candidates prefix)
923 (company--merge-async pairs (lambda (values) (apply #'append values)))))
925 (defun company--merge-async (pairs merger)
926 (let ((async (cl-loop for pair in pairs
928 (eq :async (car-safe (car pair))))))
930 (funcall merger (cl-loop for (val . mapper) in pairs
931 collect (funcall mapper val)))
936 (pending (mapcar #'car pairs))
947 (this-finisher (lambda (res)
948 (setq pending (delq val pending))
949 (setcar cell (funcall mapper res))
950 (funcall finisher))))
951 (if (not (eq :async (car-safe val)))
952 (funcall this-finisher val)
953 (let ((fetcher (cdr val)))
954 (funcall fetcher this-finisher)))))))))))
956 (defun company--prefix-str (prefix)
957 (or (car-safe prefix) prefix))
959 ;;; completion mechanism ;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;
961 (defvar-local company-prefix nil)
963 (defvar-local company-candidates nil)
965 (defvar-local company-candidates-length nil)
967 (defvar-local company-candidates-cache nil)
969 (defvar-local company-candidates-predicate nil)
971 (defvar-local company-common nil)
973 (defvar-local company-selection 0)
975 (defvar-local company-selection-changed nil)
977 (defvar-local company--manual-action nil
978 "Non-nil, if manual completion took place.")
980 (defvar-local company--manual-prefix nil)
982 (defvar company--auto-completion nil
983 "Non-nil when current candidate is being inserted automatically.
984 Controlled by `company-auto-complete'.")
986 (defvar-local company--point-max nil)
988 (defvar-local company-point nil)
990 (defvar company-timer nil)
992 (defsubst company-strip-prefix (str)
993 (substring str (length company-prefix)))
995 (defun company--insert-candidate (candidate)
996 (setq candidate (substring-no-properties candidate))
997 ;; XXX: Return value we check here is subject to change.
998 (if (eq (company-call-backend 'ignore-case) 'keep-prefix)
999 (insert (company-strip-prefix candidate))
1000 (unless (equal company-prefix candidate)
1001 (delete-region (- (point) (length company-prefix)) (point))
1002 (insert candidate))))
1004 (defmacro company-with-candidate-inserted (candidate &rest body)
1005 "Evaluate BODY with CANDIDATE temporarily inserted.
1006 This is a tool for back-ends that need candidates inserted before they
1007 can retrieve meta-data for them."
1008 (declare (indent 1))
1009 `(let ((inhibit-modification-hooks t)
1010 (inhibit-point-motion-hooks t)
1011 (modified-p (buffer-modified-p)))
1012 (company--insert-candidate ,candidate)
1015 (delete-region company-point (point))
1016 (set-buffer-modified-p modified-p))))
1018 (defun company-explicit-action-p ()
1019 "Return whether explicit completion action was taken by the user."
1020 (or company--manual-action
1021 company-selection-changed))
1023 (defun company-reformat (candidate)
1024 ;; company-ispell needs this, because the results are always lower-case
1025 ;; It's mory efficient to fix it only when they are displayed.
1026 ;; FIXME: Adopt the current text's capitalization instead?
1027 (if (eq (company-call-backend 'ignore-case) 'keep-prefix)
1028 (concat company-prefix (substring candidate (length company-prefix)))
1031 (defun company--should-complete ()
1032 (and (eq company-idle-delay 'now)
1033 (not (or buffer-read-only overriding-terminal-local-map
1034 overriding-local-map))
1035 ;; Check if in the middle of entering a key combination.
1036 (or (equal (this-command-keys-vector) [])
1037 (not (keymapp (key-binding (this-command-keys-vector)))))
1038 (not (and transient-mark-mode mark-active))))
1040 (defun company--should-continue ()
1041 (or (eq t company-begin-commands)
1042 (eq t company-continue-commands)
1043 (if (eq 'not (car company-continue-commands))
1044 (not (memq this-command (cdr company-continue-commands)))
1045 (or (memq this-command company-begin-commands)
1046 (memq this-command company-continue-commands)
1047 (and (symbolp this-command)
1048 (string-match-p "\\`company-" (symbol-name this-command)))))))
1050 (defun company-call-frontends (command)
1051 (dolist (frontend company-frontends)
1052 (condition-case-unless-debug err
1053 (funcall frontend command)
1054 (error (error "Company: Front-end %s error \"%s\" on command %s"
1055 frontend (error-message-string err) command)))))
1057 (defun company-set-selection (selection &optional force-update)
1059 (if company-selection-wrap-around
1060 (mod selection company-candidates-length)
1061 (max 0 (min (1- company-candidates-length) selection))))
1062 (when (or force-update (not (equal selection company-selection)))
1063 (setq company-selection selection
1064 company-selection-changed t)
1065 (company-call-frontends 'update)))
1067 (defun company--group-lighter (candidate base)
1068 (let ((backend (or (get-text-property 0 'company-backend candidate)
1069 (car company-backend))))
1070 (when (and backend (symbolp backend))
1071 (let ((name (replace-regexp-in-string "company-\\|-company" ""
1072 (symbol-name backend))))
1073 (format "%s-<%s>" base name)))))
1075 (defun company-update-candidates (candidates)
1076 (setq company-candidates-length (length candidates))
1077 (if company-selection-changed
1078 ;; Try to restore the selection
1079 (let ((selected (nth company-selection company-candidates)))
1080 (setq company-selection 0
1081 company-candidates candidates)
1085 (let ((candidate (pop candidates)))
1086 (when (and (string= candidate selected)
1087 (equal (company-call-backend 'annotation candidate)
1088 (company-call-backend 'annotation selected)))
1090 (cl-incf company-selection))
1091 (setq company-selection 0
1092 company-selection-changed nil))))
1093 (setq company-selection 0
1094 company-candidates candidates))
1095 ;; Calculate common.
1096 (let ((completion-ignore-case (company-call-backend 'ignore-case)))
1097 ;; We want to support non-prefix completion, so filtering is the
1098 ;; responsibility of each respective backend, not ours.
1099 ;; On the other hand, we don't want to replace non-prefix input in
1100 ;; `company-complete-common', unless there's only one candidate.
1101 (setq company-common
1102 (if (cdr company-candidates)
1103 (let ((common (try-completion "" company-candidates)))
1104 (when (string-prefix-p company-prefix common
1105 completion-ignore-case)
1107 (car company-candidates)))))
1109 (defun company-calculate-candidates (prefix)
1110 (let ((candidates (cdr (assoc prefix company-candidates-cache)))
1111 (ignore-case (company-call-backend 'ignore-case)))
1113 (when company-candidates-cache
1114 (let ((len (length prefix))
1115 (completion-ignore-case ignore-case)
1117 (cl-dotimes (i (1+ len))
1118 (when (setq prev (cdr (assoc (substring prefix 0 (- len i))
1119 company-candidates-cache)))
1120 (setq candidates (all-completions prefix prev))
1123 ;; No cache match, call the backend.
1124 (setq candidates (company--preprocess-candidates
1125 (company--fetch-candidates prefix)))
1127 (push (cons prefix candidates) company-candidates-cache)))
1128 ;; Only now apply the predicate and transformers.
1129 (setq candidates (company--postprocess-candidates candidates))
1131 (if (or (cdr candidates)
1132 (not (eq t (compare-strings (car candidates) nil nil
1133 prefix nil nil ignore-case))))
1135 ;; Already completed and unique; don't start.
1138 (defun company--fetch-candidates (prefix)
1139 (let ((c (if company--manual-action
1140 (company-call-backend 'candidates prefix)
1141 (company-call-backend-raw 'candidates prefix)))
1143 (if (not (eq (car c) :async))
1145 (let ((buf (current-buffer))
1146 (win (selected-window))
1147 (tick (buffer-chars-modified-tick))
1149 (backend company-backend))
1152 (lambda (candidates)
1153 (if (not (and candidates (eq res 'done)))
1154 ;; There's no completions to display,
1155 ;; or the fetcher called us back right away.
1156 (setq res candidates)
1157 (setq company-backend backend
1158 company-candidates-cache
1160 (company--preprocess-candidates candidates))))
1161 (company-idle-begin buf win tick pt)))))
1162 ;; FIXME: Relying on the fact that the callers
1163 ;; will interpret nil as "do nothing" is shaky.
1164 ;; A throw-catch would be one possible improvement.
1166 (progn (setq res 'done) nil)))))
1168 (defun company--preprocess-candidates (candidates)
1169 (unless (company-call-backend 'sorted)
1170 (setq candidates (sort candidates 'string<)))
1171 (when (company-call-backend 'duplicates)
1172 (company--strip-duplicates candidates))
1175 (defun company--postprocess-candidates (candidates)
1176 (when (or company-candidates-predicate company-transformers)
1177 (setq candidates (copy-sequence candidates)))
1178 (when company-candidates-predicate
1179 (setq candidates (cl-delete-if-not company-candidates-predicate candidates)))
1180 (company--transform-candidates candidates))
1182 (defun company--strip-duplicates (candidates)
1183 (let ((c2 candidates)
1187 (let ((str (pop c2)))
1188 (while (let ((str2 (car c2)))
1189 (if (not (equal str str2))
1193 (when (eq annos 'unk)
1194 (setq annos (list (company-call-backend
1196 (let ((anno2 (company-call-backend
1198 (if (member anno2 annos)
1205 (defun company--transform-candidates (candidates)
1206 (let ((c candidates))
1207 (dolist (tr company-transformers)
1208 (setq c (funcall tr c)))
1211 (defcustom company-occurrence-weight-function
1212 #'company-occurrence-prefer-closest-above
1213 "Function to weigh matches in `company-sort-by-occurrence'.
1214 It's called with three arguments: cursor position, the beginning and the
1217 (const :tag "First above point, then below point"
1218 company-occurrence-prefer-closest-above)
1219 (const :tag "Prefer closest in any direction"
1220 company-occurrence-prefer-any-closest)))
1222 (defun company-occurrence-prefer-closest-above (pos match-beg match-end)
1223 "Give priority to the matches above point, then those below point."
1224 (if (< match-beg pos)
1226 (- match-beg (window-start))))
1228 (defun company-occurrence-prefer-any-closest (pos _match-beg match-end)
1229 "Give priority to the matches closest to the point."
1230 (abs (- pos match-end)))
1232 (defun company-sort-by-occurrence (candidates)
1233 "Sort CANDIDATES according to their occurrences.
1234 Searches for each in the currently visible part of the current buffer and
1235 prioritizes the matches according to `company-occurrence-weight-function'.
1236 The rest of the list is appended unchanged.
1237 Keywords and function definition names are ignored."
1238 (let* ((w-start (window-start))
1239 (w-end (window-end))
1240 (start-point (point))
1248 (while (search-forward candidate w-end t)
1249 (when (and (not (eq (point) start-point))
1251 (company--occurrence-predicate)))
1255 (funcall company-occurrence-weight-function
1263 (mapcar #'car (sort occurs (lambda (e1 e2) (<= (cdr e1) (cdr e2)))))
1266 (defun company--occurrence-predicate ()
1267 (let ((beg (match-beginning 0))
1268 (end (match-end 0)))
1271 (and (not (memq (get-text-property (1- (point)) 'face)
1272 '(font-lock-function-name-face
1273 font-lock-keyword-face)))
1274 (let ((prefix (company--prefix-str
1275 (company-call-backend 'prefix))))
1276 (and (stringp prefix)
1277 (= (length prefix) (- end beg))))))))
1279 (defun company-sort-by-backend-importance (candidates)
1280 "Sort CANDIDATES as two priority groups.
1281 If `company-backend' is a function, do nothing. If it's a list, move
1282 candidates from back-ends before keyword `:with' to the front. Candidates
1283 from the rest of the back-ends in the group, if any, will be left at the end."
1284 (if (functionp company-backend)
1286 (let ((low-priority (cdr (memq :with company-backend))))
1287 (if (null low-priority)
1292 (let ((b2 (get-text-property 0 'company-backend c2)))
1293 (and b2 (memq b2 low-priority)))
1294 (let ((b1 (get-text-property 0 'company-backend c1)))
1295 (or (not b1) (not (memq b1 low-priority)))))))))))
1297 (defun company-idle-begin (buf win tick pos)
1298 (and (eq buf (current-buffer))
1299 (eq win (selected-window))
1300 (eq tick (buffer-chars-modified-tick))
1302 (when (company-auto-begin)
1303 (company-input-noop)
1304 (let ((this-command 'company-idle-begin))
1305 (company-post-command)))))
1307 (defun company-auto-begin ()
1309 (not company-candidates)
1310 (let ((company-idle-delay 'now))
1311 (condition-case-unless-debug err
1314 ;; Return non-nil if active.
1316 (error (message "Company: An error occurred in auto-begin")
1317 (message "%s" (error-message-string err))
1319 (quit (company-cancel))))))
1321 (defun company-manual-begin ()
1323 (company-assert-enabled)
1324 (setq company--manual-action t)
1326 (let ((company-minimum-prefix-length 0))
1327 (or company-candidates
1328 (company-auto-begin)))
1329 (unless company-candidates
1330 (setq company--manual-action nil))))
1332 (defun company-other-backend (&optional backward)
1333 (interactive (list current-prefix-arg))
1334 (company-assert-enabled)
1335 (let* ((after (if company-backend
1336 (cdr (member company-backend company-backends))
1338 (before (cdr (member company-backend (reverse company-backends))))
1340 (append before (reverse after))
1341 (append after (reverse before)))))
1343 (cl-dolist (backend next)
1344 (when (ignore-errors (company-begin-backend backend))
1346 (unless company-candidates
1347 (error "No other back-end")))
1349 (defun company-require-match-p ()
1350 (let ((backend-value (company-call-backend 'require-match)))
1351 (or (eq backend-value t)
1352 (and (not (eq backend-value 'never))
1353 (if (functionp company-require-match)
1354 (funcall company-require-match)
1355 (eq company-require-match t))))))
1357 (defun company-auto-complete-p (input)
1358 "Return non-nil, if input starts with punctuation or parentheses."
1359 (and (if (functionp company-auto-complete)
1360 (funcall company-auto-complete)
1361 company-auto-complete)
1362 (if (functionp company-auto-complete-chars)
1363 (funcall company-auto-complete-chars input)
1364 (if (consp company-auto-complete-chars)
1365 (memq (char-syntax (string-to-char input))
1366 company-auto-complete-chars)
1367 (string-match (substring input 0 1) company-auto-complete-chars)))))
1369 (defun company--incremental-p ()
1370 (and (> (point) company-point)
1371 (> (point-max) company--point-max)
1372 (not (eq this-command 'backward-delete-char-untabify))
1373 (equal (buffer-substring (- company-point (length company-prefix))
1377 (defun company--continue-failed (new-prefix)
1378 (let ((input (buffer-substring-no-properties (point) company-point)))
1380 ((company-auto-complete-p input)
1383 (goto-char company-point)
1384 (let ((company--auto-completion t))
1385 (company-complete-selection))
1387 ((and (or (not (company-require-match-p))
1388 ;; Don't require match if the new prefix
1389 ;; doesn't continue the old one, and the latter was a match.
1390 (not (stringp new-prefix))
1391 (<= (length new-prefix) (length company-prefix)))
1392 (member company-prefix company-candidates))
1393 ;; Last input was a success,
1394 ;; but we're treating it as an abort + input anyway,
1395 ;; like the `unique' case below.
1396 (company-cancel 'non-unique))
1397 ((company-require-match-p)
1398 ;; Wrong incremental input, but required match.
1399 (delete-char (- (length input)))
1401 (message "Matching input is required")
1403 (t (company-cancel)))))
1405 (defun company--good-prefix-p (prefix)
1406 (and (stringp (company--prefix-str prefix)) ;excludes 'stop
1407 (or (eq (cdr-safe prefix) t)
1408 (let ((len (or (cdr-safe prefix) (length prefix))))
1409 (if company--manual-prefix
1410 (or (not company-abort-manual-when-too-short)
1411 ;; Must not be less than minimum or initial length.
1412 (>= len (min company-minimum-prefix-length
1413 (length company--manual-prefix))))
1414 (>= len company-minimum-prefix-length))))))
1416 (defun company--continue ()
1417 (when (company-call-backend 'no-cache company-prefix)
1418 ;; Don't complete existing candidates, fetch new ones.
1419 (setq company-candidates-cache nil))
1420 (let* ((new-prefix (company-call-backend 'prefix))
1421 (c (when (and (company--good-prefix-p new-prefix)
1422 (setq new-prefix (company--prefix-str new-prefix))
1423 (= (- (point) (length new-prefix))
1424 (- company-point (length company-prefix))))
1425 (company-calculate-candidates new-prefix))))
1428 ;; t means complete/unique.
1429 ;; Handle it like completion was aborted, to differentiate from user
1430 ;; calling one of Company's commands to insert the candidate,
1431 ;; not to trigger template expansion, etc.
1432 (company-cancel 'unique))
1434 ;; incremental match
1435 (setq company-prefix new-prefix)
1436 (company-update-candidates c)
1438 ((not (company--incremental-p))
1440 (t (company--continue-failed new-prefix)))))
1442 (defun company--begin-new ()
1444 (cl-dolist (backend (if company-backend
1445 ;; prefer manual override
1446 (list company-backend)
1449 (if (or (symbolp backend)
1450 (functionp backend))
1451 (when (or (not (symbolp backend))
1452 (eq t (get backend 'company-init))
1453 (unless (get backend 'company-init)
1454 (company-init-backend backend)))
1455 (funcall backend 'prefix))
1456 (company--multi-backend-adapter backend 'prefix)))
1458 (when (company--good-prefix-p prefix)
1459 (setq company-prefix (company--prefix-str prefix)
1460 company-backend backend
1461 c (company-calculate-candidates company-prefix))
1462 ;; t means complete/unique. We don't start, so no hooks.
1464 (when company--manual-action
1465 (message "No completion found"))
1466 (when company--manual-action
1467 (setq company--manual-prefix prefix))
1468 (company-update-candidates c)
1469 (run-hook-with-args 'company-completion-started-hook
1470 (company-explicit-action-p))
1471 (company-call-frontends 'show)))
1474 (defun company--perform ()
1475 (or (and company-candidates (company--continue))
1476 (and (company--should-complete) (company--begin-new)))
1477 (if (not company-candidates)
1478 (setq company-backend nil)
1479 (setq company-point (point)
1480 company--point-max (point-max))
1481 (company-ensure-emulation-alist)
1482 (company-enable-overriding-keymap company-active-map)
1483 (company-call-frontends 'update)))
1485 (defun company-cancel (&optional result)
1487 (when company-prefix
1488 (if (stringp result)
1490 (company-call-backend 'pre-completion result)
1491 (run-hook-with-args 'company-completion-finished-hook result)
1492 (company-call-backend 'post-completion result))
1493 (run-hook-with-args 'company-completion-cancelled-hook result)))
1494 (setq company-backend nil
1496 company-candidates nil
1497 company-candidates-length nil
1498 company-candidates-cache nil
1499 company-candidates-predicate nil
1502 company-selection-changed nil
1503 company--manual-action nil
1504 company--manual-prefix nil
1505 company--point-max nil
1508 (cancel-timer company-timer))
1509 (company-search-mode 0)
1510 (company-call-frontends 'hide)
1511 (company-enable-overriding-keymap nil))
1512 ;; Make return value explicit.
1515 (defun company-abort ()
1517 (company-cancel 'abort))
1519 (defun company-finish (result)
1520 (company--insert-candidate result)
1521 (company-cancel result))
1523 (defsubst company-keep (command)
1524 (and (symbolp command) (get command 'company-keep)))
1526 (defun company-pre-command ()
1527 (unless (company-keep this-command)
1528 (condition-case-unless-debug err
1529 (when company-candidates
1530 (company-call-frontends 'pre-command)
1531 (unless (company--should-continue)
1533 (error (message "Company: An error occurred in pre-command")
1534 (message "%s" (error-message-string err))
1537 (cancel-timer company-timer)
1538 (setq company-timer nil))
1539 (company-uninstall-map))
1541 (defun company-post-command ()
1542 (when (null this-command)
1543 ;; Happens when the user presses `C-g' while inside
1544 ;; `flyspell-post-command-hook', for example.
1545 ;; Or any other `post-command-hook' function that can call `sit-for',
1546 ;; or any quittable timer function.
1548 (setq this-command 'company-abort))
1549 (unless (company-keep this-command)
1550 (condition-case-unless-debug err
1552 (unless (equal (point) company-point)
1553 (let (company-idle-delay) ; Against misbehavior while debugging.
1554 (company--perform)))
1555 (if company-candidates
1556 (company-call-frontends 'post-command)
1557 (and (numberp company-idle-delay)
1558 (company--should-begin)
1560 (run-with-timer company-idle-delay nil
1562 (current-buffer) (selected-window)
1563 (buffer-chars-modified-tick) (point))))))
1564 (error (message "Company: An error occurred in post-command")
1565 (message "%s" (error-message-string err))
1567 (company-install-map))
1569 (defvar company--begin-inhibit-commands '(company-abort
1570 company-complete-mouse
1572 company-complete-common
1573 company-complete-selection
1574 company-complete-number)
1575 "List of commands after which idle completion is (still) disabled when
1576 `company-begin-commands' is t.")
1578 (defun company--should-begin ()
1579 (if (eq t company-begin-commands)
1580 (not (memq this-command company--begin-inhibit-commands))
1582 (memq this-command company-begin-commands)
1583 (and (symbolp this-command) (get this-command 'company-begin)))))
1585 ;;; search ;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;
1587 (defvar-local company-search-string "")
1589 (defvar company-search-lighter '(" "
1590 (company-search-filtering "Filter" "Search")
1592 company-search-string
1595 (defvar-local company-search-filtering nil
1596 "Non-nil to filter the completion candidates by the search string")
1598 (defvar-local company--search-old-selection 0)
1600 (defvar-local company--search-old-changed nil)
1602 (defun company--search (text lines)
1603 (let ((quoted (regexp-quote text))
1605 (cl-dolist (line lines)
1606 (when (string-match quoted line (length company-prefix))
1610 (defun company-search-keypad ()
1612 (let* ((name (symbol-name last-command-event))
1613 (last-command-event (aref name (1- (length name)))))
1614 (company-search-printing-char)))
1616 (defun company-search-printing-char ()
1618 (company--search-assert-enabled)
1619 (let ((ss (concat company-search-string (string last-command-event))))
1620 (when company-search-filtering
1621 (company--search-update-predicate ss))
1622 (company--search-update-string ss)))
1624 (defun company--search-update-predicate (&optional ss)
1625 (let* ((company-candidates-predicate
1626 (and (not (string= ss ""))
1627 company-search-filtering
1628 (lambda (candidate) (string-match ss candidate))))
1629 (cc (company-calculate-candidates company-prefix)))
1630 (unless cc (error "No match"))
1631 (company-update-candidates cc)))
1633 (defun company--search-update-string (new)
1634 (let* ((pos (company--search new (nthcdr company-selection company-candidates))))
1637 (setq company-search-string new)
1638 (company-set-selection (+ company-selection pos) t))))
1640 (defun company--search-assert-input ()
1641 (company--search-assert-enabled)
1642 (when (string= company-search-string "")
1643 (error "Empty search string")))
1645 (defun company-search-repeat-forward ()
1646 "Repeat the incremental search in completion candidates forward."
1648 (company--search-assert-input)
1649 (let ((pos (company--search company-search-string
1650 (cdr (nthcdr company-selection
1651 company-candidates)))))
1654 (company-set-selection (+ company-selection pos 1) t))))
1656 (defun company-search-repeat-backward ()
1657 "Repeat the incremental search in completion candidates backwards."
1659 (company--search-assert-input)
1660 (let ((pos (company--search company-search-string
1661 (nthcdr (- company-candidates-length
1663 (reverse company-candidates)))))
1666 (company-set-selection (- company-selection pos 1) t))))
1668 (defun company-search-toggle-filtering ()
1669 "Toggle `company-search-filtering'."
1671 (company--search-assert-enabled)
1672 (setq company-search-filtering (not company-search-filtering))
1673 (let ((ss company-search-string))
1674 (company--search-update-predicate ss)
1675 (company--search-update-string ss)))
1677 (defun company-search-abort ()
1678 "Abort searching the completion candidates."
1680 (company--search-assert-enabled)
1681 (company-search-mode 0)
1682 (company-set-selection company--search-old-selection t)
1683 (setq company-selection-changed company--search-old-changed))
1685 (defun company-search-other-char ()
1687 (company--search-assert-enabled)
1688 (company-search-mode 0)
1689 (company--unread-last-input))
1691 (defun company-search-delete-char ()
1693 (company--search-assert-enabled)
1694 (if (string= company-search-string "")
1696 (let ((ss (substring company-search-string 0 -1)))
1697 (when company-search-filtering
1698 (company--search-update-predicate ss))
1699 (company--search-update-string ss))))
1701 (defvar company-search-map
1703 (keymap (make-keymap)))
1704 (if (fboundp 'max-char)
1705 (set-char-table-range (nth 1 keymap) (cons #x100 (max-char))
1706 'company-search-printing-char)
1708 ;; obsolete in Emacs 23
1709 (let ((l (generic-character-list))
1710 (table (nth 1 keymap)))
1712 (set-char-table-default table (car l) 'company-search-printing-char)
1713 (setq l (cdr l))))))
1714 (define-key keymap [t] 'company-search-other-char)
1716 (define-key keymap (make-string 1 i) 'company-search-other-char)
1719 (define-key keymap (vector i) 'company-search-printing-char)
1722 (define-key keymap (read (format "[kp-%s]" i)) 'company-search-keypad))
1723 (let ((meta-map (make-sparse-keymap)))
1724 (define-key keymap (char-to-string meta-prefix-char) meta-map)
1725 (define-key keymap [escape] meta-map))
1726 (define-key keymap (vector meta-prefix-char t) 'company-search-other-char)
1727 (define-key keymap (kbd "M-n") 'company-select-next)
1728 (define-key keymap (kbd "M-p") 'company-select-previous)
1729 (define-key keymap (kbd "<down>") 'company-select-next-or-abort)
1730 (define-key keymap (kbd "<up>") 'company-select-previous-or-abort)
1731 (define-key keymap "\e\e\e" 'company-search-other-char)
1732 (define-key keymap [escape escape escape] 'company-search-other-char)
1733 (define-key keymap (kbd "DEL") 'company-search-delete-char)
1734 (define-key keymap [backspace] 'company-search-delete-char)
1735 (define-key keymap "\C-g" 'company-search-abort)
1736 (define-key keymap "\C-s" 'company-search-repeat-forward)
1737 (define-key keymap "\C-r" 'company-search-repeat-backward)
1738 (define-key keymap "\C-o" 'company-search-toggle-filtering)
1740 (define-key keymap (read-kbd-macro (format "M-%d" i)) 'company-complete-number))
1742 "Keymap used for incrementally searching the completion candidates.")
1744 (define-minor-mode company-search-mode
1745 "Search mode for completion candidates.
1746 Don't start this directly, use `company-search-candidates' or
1747 `company-filter-candidates'."
1748 nil company-search-lighter nil
1749 (if company-search-mode
1750 (if (company-manual-begin)
1752 (setq company--search-old-selection company-selection
1753 company--search-old-changed company-selection-changed)
1754 (company-call-frontends 'update)
1755 (company-enable-overriding-keymap company-search-map))
1756 (setq company-search-mode nil))
1757 (kill-local-variable 'company-search-string)
1758 (kill-local-variable 'company-search-filtering)
1759 (kill-local-variable 'company--search-old-selection)
1760 (kill-local-variable 'company--search-old-changed)
1761 (when company-backend
1762 (company--search-update-predicate "")
1763 (company-call-frontends 'update))
1764 (company-enable-overriding-keymap company-active-map)))
1766 (defun company--search-assert-enabled ()
1767 (company-assert-enabled)
1768 (unless company-search-mode
1769 (company-uninstall-map)
1770 (error "Company not in search mode")))
1772 (defun company-search-candidates ()
1773 "Start searching the completion candidates incrementally.
1775 \\<company-search-map>Search can be controlled with the commands:
1776 - `company-search-repeat-forward' (\\[company-search-repeat-forward])
1777 - `company-search-repeat-backward' (\\[company-search-repeat-backward])
1778 - `company-search-abort' (\\[company-search-abort])
1779 - `company-search-delete-char' (\\[company-search-delete-char])
1781 Regular characters are appended to the search string.
1783 The command `company-search-toggle-filtering' (\\[company-search-toggle-filtering])
1784 uses the search string to filter the completion candidates."
1786 (company-search-mode 1))
1788 (defvar company-filter-map
1789 (let ((keymap (make-keymap)))
1790 (define-key keymap [remap company-search-printing-char]
1791 'company-filter-printing-char)
1792 (set-keymap-parent keymap company-search-map)
1794 "Keymap used for incrementally searching the completion candidates.")
1796 (defun company-filter-candidates ()
1797 "Start filtering the completion candidates incrementally.
1798 This works the same way as `company-search-candidates' immediately
1799 followed by `company-search-toggle-filtering'."
1801 (company-search-mode 1)
1802 (setq company-search-filtering t))
1804 ;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;
1806 (defun company-select-next (&optional arg)
1807 "Select the next candidate in the list.
1809 With ARG, move by that many elements."
1811 (when (company-manual-begin)
1812 (company-set-selection (+ (or arg 1) company-selection))))
1814 (defun company-select-previous (&optional arg)
1815 "Select the previous candidate in the list.
1817 With ARG, move by that many elements."
1819 (company-select-next (if arg (- arg) -1)))
1821 (defun company-select-next-or-abort (&optional arg)
1822 "Select the next candidate if more than one, else abort
1823 and invoke the normal binding.
1825 With ARG, move by that many elements."
1827 (if (> company-candidates-length 1)
1828 (company-select-next arg)
1830 (company--unread-last-input)))
1832 (defun company-select-previous-or-abort (&optional arg)
1833 "Select the previous candidate if more than one, else abort
1834 and invoke the normal binding.
1836 With ARG, move by that many elements."
1838 (if (> company-candidates-length 1)
1839 (company-select-previous arg)
1841 (company--unread-last-input)))
1843 (defun company-next-page ()
1844 "Select the candidate one page further."
1846 (when (company-manual-begin)
1847 (company-set-selection (+ company-selection
1848 company-tooltip-limit))))
1850 (defun company-previous-page ()
1851 "Select the candidate one page earlier."
1853 (when (company-manual-begin)
1854 (company-set-selection (- company-selection
1855 company-tooltip-limit))))
1857 (defvar company-pseudo-tooltip-overlay)
1859 (defvar company-tooltip-offset)
1861 (defun company--inside-tooltip-p (event-col-row row height)
1862 (let* ((ovl company-pseudo-tooltip-overlay)
1863 (column (overlay-get ovl 'company-column))
1864 (width (overlay-get ovl 'company-width))
1865 (evt-col (car event-col-row))
1866 (evt-row (cdr event-col-row)))
1867 (and (>= evt-col column)
1868 (< evt-col (+ column width))
1870 (and (> evt-row row)
1871 (<= evt-row (+ row height) ))
1872 (and (< evt-row row)
1873 (>= evt-row (+ row height)))))))
1875 (defun company--event-col-row (event)
1876 (company--posn-col-row (event-start event)))
1878 (defun company-select-mouse (event)
1879 "Select the candidate picked by the mouse."
1881 (let ((event-col-row (company--event-col-row event))
1882 (ovl-row (company--row))
1883 (ovl-height (and company-pseudo-tooltip-overlay
1884 (min (overlay-get company-pseudo-tooltip-overlay
1886 company-candidates-length))))
1888 (company--inside-tooltip-p event-col-row ovl-row ovl-height))
1890 (company-set-selection (+ (cdr event-col-row)
1891 (1- company-tooltip-offset)
1892 (if (and (eq company-tooltip-offset-display 'lines)
1893 (not (zerop company-tooltip-offset)))
1896 (if (< ovl-height 0)
1901 (company--unread-last-input)
1904 (defun company-complete-mouse (event)
1905 "Insert the candidate picked by the mouse."
1907 (when (company-select-mouse event)
1908 (company-complete-selection)))
1910 (defun company-complete-selection ()
1911 "Insert the selected candidate."
1913 (when (company-manual-begin)
1914 (let ((result (nth company-selection company-candidates)))
1915 (company-finish result))))
1917 (defun company-complete-common ()
1918 "Insert the common part of all candidates."
1920 (when (company-manual-begin)
1921 (if (and (not (cdr company-candidates))
1922 (equal company-common (car company-candidates)))
1923 (company-complete-selection)
1924 (when company-common
1925 (company--insert-candidate company-common)))))
1927 (defun company-complete-common-or-cycle (&optional arg)
1928 "Insert the common part of all candidates, or select the next one.
1930 With ARG, move by that many elements."
1932 (when (company-manual-begin)
1933 (let ((tick (buffer-chars-modified-tick)))
1934 (call-interactively 'company-complete-common)
1935 (when (eq tick (buffer-chars-modified-tick))
1936 (let ((company-selection-wrap-around t)
1937 (current-prefix-arg arg))
1938 (call-interactively 'company-select-next))))))
1940 (defun company-complete ()
1941 "Insert the common part of all candidates or the current selection.
1942 The first time this is called, the common part is inserted, the second
1943 time, or when the selection has been changed, the selected candidate is
1946 (when (company-manual-begin)
1947 (if (or company-selection-changed
1948 (eq last-command 'company-complete-common))
1949 (call-interactively 'company-complete-selection)
1950 (call-interactively 'company-complete-common)
1951 (setq this-command 'company-complete-common))))
1953 (defun company-complete-number (n)
1954 "Insert the Nth candidate visible in the tooltip.
1955 To show the number next to the candidates in some back-ends, enable
1956 `company-show-numbers'. When called interactively, uses the last typed
1957 character, stripping the modifiers. That character must be a digit."
1959 (list (let* ((type (event-basic-type last-command-event))
1960 (char (if (characterp type)
1961 ;; Number on the main row.
1963 ;; Keypad number, if bound directly.
1964 (car (last (string-to-list (symbol-name type))))))
1966 (if (zerop n) 10 n))))
1967 (when (company-manual-begin)
1968 (and (or (< n 1) (> n (- company-candidates-length
1969 company-tooltip-offset)))
1970 (error "No candidate number %d" n))
1972 (company-finish (nth (+ n company-tooltip-offset)
1973 company-candidates))))
1975 ;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;
1977 (defconst company-space-strings-limit 100)
1979 (defconst company-space-strings
1981 (dotimes (i company-space-strings-limit)
1982 (push (make-string (- company-space-strings-limit 1 i) ?\ ) lst))
1983 (apply 'vector lst)))
1985 (defun company-space-string (len)
1986 (if (< len company-space-strings-limit)
1987 (aref company-space-strings len)
1988 (make-string len ?\ )))
1990 (defun company-safe-substring (str from &optional to)
1991 (if (> from (string-width str))
1995 (move-to-column from)
1996 (let ((beg (point)))
2000 (concat (buffer-substring beg (point))
2001 (let ((padding (- to (current-column))))
2003 (company-space-string padding)))))
2004 (buffer-substring beg (point-max)))))))
2006 ;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;
2008 (defvar-local company-last-metadata nil)
2010 (defun company-fetch-metadata ()
2011 (let ((selected (nth company-selection company-candidates)))
2012 (unless (eq selected (car company-last-metadata))
2013 (setq company-last-metadata
2014 (cons selected (company-call-backend 'meta selected))))
2015 (cdr company-last-metadata)))
2017 (defun company-doc-buffer (&optional string)
2018 (with-current-buffer (get-buffer-create "*company-documentation*")
2025 (defvar company--electric-commands
2026 '(scroll-other-window scroll-other-window-down mwheel-scroll)
2027 "List of Commands that won't break out of electric commands.")
2029 (defmacro company--electric-do (&rest body)
2030 (declare (indent 0) (debug t))
2031 `(when (company-manual-begin)
2032 (save-window-excursion
2033 (let ((height (window-height))
2034 (row (company--row))
2037 (and (< (window-height) height)
2038 (< (- (window-height) row 2) company-tooltip-limit)
2039 (recenter (- (window-height) row 2)))
2040 (while (memq (setq cmd (key-binding (read-key-sequence-vector nil)))
2041 company--electric-commands)
2043 (call-interactively cmd)
2044 ((beginning-of-buffer end-of-buffer)
2045 (message (error-message-string err)))))
2046 (company--unread-last-input)))))
2048 (defun company--unread-last-input ()
2049 (when last-input-event
2050 (clear-this-command-keys t)
2051 (setq unread-command-events (list last-input-event))))
2053 (defun company-show-doc-buffer ()
2054 "Temporarily show the documentation buffer for the selection."
2056 (let (other-window-scroll-buffer)
2057 (company--electric-do
2058 (let* ((selected (nth company-selection company-candidates))
2059 (doc-buffer (or (company-call-backend 'doc-buffer selected)
2060 (error "No documentation available"))))
2061 (setq other-window-scroll-buffer (get-buffer doc-buffer))
2062 (with-current-buffer doc-buffer
2063 (goto-char (point-min)))
2064 (display-buffer doc-buffer t)))))
2065 (put 'company-show-doc-buffer 'company-keep t)
2067 (defun company-show-location ()
2068 "Temporarily display a buffer showing the selected candidate in context."
2070 (let (other-window-scroll-buffer)
2071 (company--electric-do
2072 (let* ((selected (nth company-selection company-candidates))
2073 (location (company-call-backend 'location selected))
2074 (pos (or (cdr location) (error "No location available")))
2075 (buffer (or (and (bufferp (car location)) (car location))
2076 (find-file-noselect (car location) t))))
2077 (setq other-window-scroll-buffer (get-buffer buffer))
2078 (with-selected-window (display-buffer buffer t)
2081 (if (bufferp (car location))
2083 (goto-char (point-min))
2084 (forward-line (1- pos))))
2085 (set-window-start nil (point)))))))
2086 (put 'company-show-location 'company-keep t)
2088 ;;; package functions ;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;
2090 (defvar-local company-callback nil)
2092 (defun company-remove-callback (&optional ignored)
2093 (remove-hook 'company-completion-finished-hook company-callback t)
2094 (remove-hook 'company-completion-cancelled-hook 'company-remove-callback t)
2095 (remove-hook 'company-completion-finished-hook 'company-remove-callback t))
2097 (defun company-begin-backend (backend &optional callback)
2098 "Start a completion at point using BACKEND."
2099 (interactive (let ((val (completing-read "Company back-end: "
2101 'functionp nil "company-")))
2103 (list (intern val)))))
2104 (when (setq company-callback callback)
2105 (add-hook 'company-completion-finished-hook company-callback nil t))
2106 (add-hook 'company-completion-cancelled-hook 'company-remove-callback nil t)
2107 (add-hook 'company-completion-finished-hook 'company-remove-callback nil t)
2108 (setq company-backend backend)
2109 ;; Return non-nil if active.
2110 (or (company-manual-begin)
2111 (error "Cannot complete at point")))
2113 (defun company-begin-with (candidates
2114 &optional prefix-length require-match callback)
2115 "Start a completion at point.
2116 CANDIDATES is the list of candidates to use and PREFIX-LENGTH is the length
2117 of the prefix that already is in the buffer before point.
2120 CALLBACK is a function called with the selected result if the user
2121 successfully completes the input.
2123 Example: \(company-begin-with '\(\"foo\" \"foobar\" \"foobarbaz\"\)\)"
2124 (let ((begin-marker (copy-marker (point) t)))
2125 (company-begin-backend
2126 (lambda (command &optional arg &rest ignored)
2129 (when (equal (point) (marker-position begin-marker))
2130 (buffer-substring (- (point) (or prefix-length 0)) (point))))
2132 (all-completions arg candidates))
2137 (defun company-version (&optional show-version)
2138 "Get the Company version as string.
2140 If SHOW-VERSION is non-nil, show the version in the echo area."
2141 (interactive (list t))
2143 (insert-file-contents (find-library-name "company"))
2146 (message "Company version: %s" (lm-version))
2149 (defun company-diag ()
2151 "Pop a buffer with information about completions at point."
2152 (let* ((bb company-backends)
2154 (prefix (cl-loop for b in bb
2155 thereis (let ((company-backend b))
2157 (company-call-backend 'prefix))))
2159 (when (stringp prefix)
2160 (let ((company-backend backend))
2161 (setq cc (company-call-backend 'candidates prefix)
2164 (lambda (c) (cons c (company-call-backend 'annotation c)))
2166 (pop-to-buffer (get-buffer-create "*company-diag*"))
2167 (setq buffer-read-only nil)
2169 (insert (format "Emacs %s (%s) of %s on %s"
2170 emacs-version system-configuration
2171 (format-time-string "%Y-%m-%d" emacs-build-time)
2172 emacs-build-system))
2173 (insert "\nCompany " (company-version) "\n\n")
2174 (insert "company-backends: " (pp-to-string bb))
2176 (insert "Used backend: " (pp-to-string backend))
2178 (insert "Prefix: " (pp-to-string prefix))
2180 (insert (message "Completions:"))
2181 (unless cc (insert " none"))
2183 (dolist (c annotations)
2184 (insert "\n " (prin1-to-string (car c)))
2186 (insert " " (prin1-to-string (cdr c))))))
2189 ;;; pseudo-tooltip ;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;
2191 (defvar-local company-pseudo-tooltip-overlay nil)
2193 (defvar-local company-tooltip-offset 0)
2195 (defun company-tooltip--lines-update-offset (selection num-lines limit)
2197 (setq company-tooltip-offset
2198 (max (min selection company-tooltip-offset)
2199 (- selection -1 limit)))
2201 (when (<= company-tooltip-offset 1)
2203 (setq company-tooltip-offset 0))
2205 (when (>= company-tooltip-offset (- num-lines limit 1))
2207 (when (= selection (1- num-lines))
2208 (cl-decf company-tooltip-offset)
2209 (when (<= company-tooltip-offset 1)
2210 (setq company-tooltip-offset 0)
2215 (defun company-tooltip--simple-update-offset (selection _num-lines limit)
2216 (setq company-tooltip-offset
2217 (if (< selection company-tooltip-offset)
2219 (max company-tooltip-offset
2220 (- selection limit -1)))))
2224 (defsubst company-round-tab (arg)
2225 (* (/ (+ arg tab-width) tab-width) tab-width))
2227 (defun company-plainify (str)
2228 (let ((prefix (get-text-property 0 'line-prefix str)))
2229 (when prefix ; Keep the original value unmodified, for no special reason.
2230 (setq str (concat prefix str))
2231 (remove-text-properties 0 (length str) '(line-prefix) str)))
2232 (let* ((pieces (split-string str "\t"))
2235 (setcar copy (company-safe-substring
2236 (car copy) 0 (company-round-tab (string-width (car copy)))))
2238 (apply 'concat pieces)))
2240 (defun company-fill-propertize (value annotation width selected left right)
2241 (let* ((margin (length left))
2242 (common (or (company-call-backend 'match value)
2244 (string-width company-common)
2246 (ann-ralign company-tooltip-align-annotations)
2247 (ann-truncate (< width
2248 (+ (length value) (length annotation)
2249 (if ann-ralign 1 0))))
2250 (ann-start (+ margin
2254 (- width (length annotation)))
2256 (ann-end (min (+ ann-start (length annotation)) (+ margin width)))
2258 (if (or ann-truncate (not ann-ralign))
2259 (company-safe-substring
2261 (when (and annotation ann-ralign) " ")
2265 (company-safe-substring value 0
2266 (- width (length annotation)))
2269 (setq common (+ (min common width) margin))
2270 (setq width (+ width margin (length right)))
2272 (add-text-properties 0 width '(face company-tooltip
2273 mouse-face company-tooltip-mouse)
2275 (add-text-properties margin common
2276 '(face company-tooltip-common
2277 mouse-face company-tooltip-mouse)
2279 (when (< ann-start ann-end)
2280 (add-text-properties ann-start ann-end
2281 '(face company-tooltip-annotation
2282 mouse-face company-tooltip-mouse)
2285 (if (and (not (string= company-search-string ""))
2286 (string-match (regexp-quote company-search-string) value
2287 (length company-prefix)))
2288 (let ((beg (+ margin (match-beginning 0)))
2289 (end (+ margin (match-end 0)))
2290 (width (- width (length right))))
2292 (add-text-properties beg (min end width)
2293 '(face company-tooltip-search)
2295 (add-text-properties 0 width '(face company-tooltip-selection
2296 mouse-face company-tooltip-selection)
2298 (add-text-properties margin common
2299 '(face company-tooltip-common-selection
2300 mouse-face company-tooltip-selection)
2304 (defun company--clean-string (str)
2305 (replace-regexp-in-string
2306 "\\([^[:graph:] ]\\)\\|\\(\ufeff\\)\\|[[:multibyte:]]"
2309 ((match-beginning 1)
2310 ;; FIXME: Better char for 'non-printable'?
2311 ;; We shouldn't get any of these, but sometimes we might.
2313 ((match-beginning 2)
2314 ;; Zero-width non-breakable space.
2316 ((> (string-width match) 1)
2318 (make-string (1- (string-width match)) ?\ufeff)
2325 (defun company-buffer-lines (beg end)
2327 (let (lines lines-moved)
2328 (while (and (not (eobp)) ; http://debbugs.gnu.org/19553
2329 (> (setq lines-moved (vertical-motion 1)) 0)
2331 (let ((bound (min end (1- (point)))))
2332 ;; A visual line can contain several physical lines (e.g. with outline's
2333 ;; folding overlay). Take only the first one.
2334 (push (buffer-substring beg
2337 (re-search-forward "$" bound 'move)
2340 ;; One physical line can be displayed as several visual ones as well:
2341 ;; add empty strings to the list, to even the count.
2342 (dotimes (_ (1- lines-moved))
2345 (unless (eq beg end)
2346 (push (buffer-substring beg end) lines))
2349 (defun company-modify-line (old new offset)
2350 (concat (company-safe-substring old 0 offset)
2352 (company-safe-substring old (+ offset (length new)))))
2354 (defsubst company--length-limit (lst limit)
2355 (if (nthcdr limit lst)
2359 (defsubst company--window-height ()
2360 (if (fboundp 'window-screen-lines)
2361 (floor (window-screen-lines))
2362 (window-body-height)))
2364 (defun company--window-width ()
2365 (let ((ww (window-body-width)))
2366 ;; Account for the line continuation column.
2367 (when (zerop (cadr (window-fringes)))
2369 (unless (or (display-graphic-p)
2370 (version< "24.3.1" emacs-version))
2371 ;; Emacs 24.3 and earlier included margins
2372 ;; in window-width when in TTY.
2374 (let ((margins (window-margins)))
2375 (+ (or (car margins) 0)
2376 (or (cdr margins) 0)))))
2377 (when (and word-wrap
2378 (version< emacs-version "24.4.51.5"))
2379 ;; http://debbugs.gnu.org/18384
2383 (defun company--replacement-string (lines old column nl &optional align-top)
2384 (cl-decf column company-tooltip-margin)
2386 (when (and align-top company-tooltip-flip-when-above)
2387 (setq lines (reverse lines)))
2389 (let ((width (length (car lines)))
2390 (remaining-cols (- (+ (company--window-width) (window-hscroll))
2392 (when (> width remaining-cols)
2393 (cl-decf column (- width remaining-cols))))
2395 (let ((offset (and (< column 0) (- column)))
2400 ;; untouched lines first
2401 (dotimes (_ (- (length old) (length lines)))
2402 (push (pop old) new)))
2403 ;; length into old lines.
2405 (push (company-modify-line (pop old)
2406 (company--offset-line (pop lines) offset)
2409 ;; Append whole new lines.
2411 (push (concat (company-space-string column)
2412 (company--offset-line (pop lines) offset))
2415 (let ((str (concat (when nl " ")
2417 (mapconcat 'identity (nreverse new) "\n")
2419 (font-lock-append-text-property 0 (length str) 'face 'default str)
2420 (when nl (put-text-property 0 1 'cursor t str))
2423 (defun company--offset-line (line offset)
2424 (if (and offset line)
2425 (substring line offset)
2428 (defun company--create-lines (selection limit)
2429 (let ((len company-candidates-length)
2430 (window-width (company--window-width))
2439 ;; Maybe clear old offset.
2440 (when (< len (+ company-tooltip-offset limit))
2441 (setq company-tooltip-offset 0))
2443 ;; Scroll to offset.
2444 (if (eq company-tooltip-offset-display 'lines)
2445 (setq limit (company-tooltip--lines-update-offset selection len limit))
2446 (company-tooltip--simple-update-offset selection len limit))
2449 ((eq company-tooltip-offset-display 'scrollbar)
2450 (setq scrollbar-bounds (company--scrollbar-bounds company-tooltip-offset
2452 ((eq company-tooltip-offset-display 'lines)
2453 (when (> company-tooltip-offset 0)
2454 (setq previous (format "...(%d)" company-tooltip-offset)))
2455 (setq remainder (- len limit company-tooltip-offset)
2456 remainder (when (> remainder 0)
2457 (setq remainder (format "...(%d)" remainder))))))
2459 (cl-decf selection company-tooltip-offset)
2460 (setq width (max (length previous) (length remainder))
2461 lines (nthcdr company-tooltip-offset company-candidates)
2465 (cl-decf window-width (* 2 company-tooltip-margin))
2466 (when scrollbar-bounds (cl-decf window-width))
2469 (let* ((value (pop lines-copy))
2470 (annotation (company-call-backend 'annotation value)))
2471 (setq value (company--clean-string (company-reformat value)))
2473 (when company-tooltip-align-annotations
2474 ;; `lisp-completion-at-point' adds a space.
2475 (setq annotation (comment-string-strip annotation t nil)))
2476 (setq annotation (company--clean-string annotation)))
2477 (push (cons value annotation) items)
2478 (setq width (max (+ (length value)
2479 (if (and annotation company-tooltip-align-annotations)
2480 (1+ (length annotation))
2481 (length annotation)))
2484 (setq width (min window-width
2485 (max company-tooltip-minimum-width
2486 (if company-show-numbers
2490 (let ((items (nreverse items))
2491 (numbered (if company-show-numbers 0 99999))
2494 (push (company--scrollpos-line previous width) new))
2497 (let* ((item (pop items))
2499 (annotation (cdr item))
2500 (right (company-space-string company-tooltip-margin))
2502 (when (< numbered 10)
2505 (setq right (concat (format " %d" (mod numbered 10)) right)))
2507 (company-fill-propertize str annotation
2508 width (equal i selection)
2509 (company-space-string
2510 company-tooltip-margin)
2512 (when scrollbar-bounds
2513 (company--scrollbar i scrollbar-bounds)))
2517 (push (company--scrollpos-line remainder width) new))
2521 (defun company--scrollbar-bounds (offset limit length)
2522 (when (> length limit)
2523 (let* ((size (ceiling (* limit (float limit)) length))
2524 (lower (floor (* limit (float offset)) length))
2525 (upper (+ lower size -1)))
2526 (cons lower upper))))
2528 (defun company--scrollbar (i bounds)
2529 (propertize " " 'face
2530 (if (and (>= i (car bounds)) (<= i (cdr bounds)))
2531 'company-scrollbar-fg
2532 'company-scrollbar-bg)))
2534 (defun company--scrollpos-line (text width)
2535 (propertize (concat (company-space-string company-tooltip-margin)
2536 (company-safe-substring text 0 width)
2537 (company-space-string company-tooltip-margin))
2538 'face 'company-tooltip))
2542 (defun company--pseudo-tooltip-height ()
2543 "Calculate the appropriate tooltip height.
2544 Returns a negative number if the tooltip should be displayed above point."
2545 (let* ((lines (company--row))
2546 (below (- (company--window-height) 1 lines)))
2547 (if (and (< below (min company-tooltip-minimum company-candidates-length))
2549 (- (max 3 (min company-tooltip-limit lines)))
2550 (max 3 (min company-tooltip-limit below)))))
2552 (defun company-pseudo-tooltip-show (row column selection)
2553 (company-pseudo-tooltip-hide)
2556 (let* ((height (company--pseudo-tooltip-height))
2560 (setq row (+ row height -1)
2563 (let* ((nl (< (move-to-window-line row) row))
2565 (end (save-excursion
2566 (move-to-window-line (+ row (abs height)))
2568 (ov (make-overlay (if nl beg (1- beg)) end nil t))
2569 (args (list (mapcar 'company-plainify
2570 (company-buffer-lines beg end))
2573 (setq company-pseudo-tooltip-overlay ov)
2574 (overlay-put ov 'company-replacement-args args)
2576 (let ((lines (company--create-lines selection (abs height))))
2577 (overlay-put ov 'company-display
2578 (apply 'company--replacement-string lines args))
2579 (overlay-put ov 'company-width (string-width (car lines))))
2581 (overlay-put ov 'company-column column)
2582 (overlay-put ov 'company-height height)))))
2584 (defun company-pseudo-tooltip-show-at-point (pos column-offset)
2585 (let* ((col-row (company--col-row pos))
2586 (col (- (car col-row) column-offset)))
2587 (when (< col 0) (setq col 0))
2588 (company-pseudo-tooltip-show (1+ (cdr col-row)) col company-selection)))
2590 (defun company-pseudo-tooltip-edit (selection)
2591 (let* ((height (overlay-get company-pseudo-tooltip-overlay 'company-height))
2592 (lines (company--create-lines selection (abs height))))
2593 (overlay-put company-pseudo-tooltip-overlay 'company-width
2594 (string-width (car lines)))
2595 (overlay-put company-pseudo-tooltip-overlay 'company-display
2596 (apply 'company--replacement-string
2598 (overlay-get company-pseudo-tooltip-overlay
2599 'company-replacement-args)))))
2601 (defun company-pseudo-tooltip-hide ()
2602 (when company-pseudo-tooltip-overlay
2603 (delete-overlay company-pseudo-tooltip-overlay)
2604 (setq company-pseudo-tooltip-overlay nil)))
2606 (defun company-pseudo-tooltip-hide-temporarily ()
2607 (when (overlayp company-pseudo-tooltip-overlay)
2608 (overlay-put company-pseudo-tooltip-overlay 'invisible nil)
2609 (overlay-put company-pseudo-tooltip-overlay 'after-string nil)))
2611 (defun company-pseudo-tooltip-unhide ()
2612 (when company-pseudo-tooltip-overlay
2613 (let* ((ov company-pseudo-tooltip-overlay)
2614 (disp (overlay-get ov 'company-display)))
2615 ;; Beat outline's folding overlays, at least.
2616 (overlay-put ov 'priority 1)
2617 ;; `display' could be better (http://debbugs.gnu.org/18285), but it
2618 ;; doesn't work when the overlay is empty, which is what happens at eob.
2619 ;; It also seems to interact badly with `cursor'.
2620 ;; We deal with priorities by having the overlay start before the newline.
2621 (overlay-put ov 'after-string disp)
2622 (overlay-put ov 'invisible t)
2623 (overlay-put ov 'window (selected-window)))))
2625 (defun company-pseudo-tooltip-guard ()
2627 (save-excursion (beginning-of-visual-line))
2628 (let ((ov company-pseudo-tooltip-overlay)
2629 (overhang (save-excursion (end-of-visual-line)
2630 (- (line-end-position) (point)))))
2631 (when (>= (overlay-get ov 'company-height) 0)
2633 (buffer-substring-no-properties (point) (overlay-start ov))
2634 (when (>= overhang 0) overhang))))))
2636 (defun company-pseudo-tooltip-frontend (command)
2637 "`company-mode' front-end similar to a tooltip but based on overlays."
2639 (pre-command (company-pseudo-tooltip-hide-temporarily))
2641 (unless (when (overlayp company-pseudo-tooltip-overlay)
2642 (let* ((ov company-pseudo-tooltip-overlay)
2643 (old-height (overlay-get ov 'company-height))
2644 (new-height (company--pseudo-tooltip-height)))
2646 (>= (* old-height new-height) 0)
2647 (>= (abs old-height) (abs new-height))
2648 (equal (company-pseudo-tooltip-guard)
2649 (overlay-get ov 'company-guard)))))
2651 (company-pseudo-tooltip-show-at-point (point) (length company-prefix))
2652 (overlay-put company-pseudo-tooltip-overlay
2653 'company-guard (company-pseudo-tooltip-guard)))
2654 (company-pseudo-tooltip-unhide))
2655 (hide (company-pseudo-tooltip-hide)
2656 (setq company-tooltip-offset 0))
2657 (update (when (overlayp company-pseudo-tooltip-overlay)
2658 (company-pseudo-tooltip-edit company-selection)))))
2660 (defun company-pseudo-tooltip-unless-just-one-frontend (command)
2661 "`company-pseudo-tooltip-frontend', but not shown for single candidates."
2662 (unless (and (eq command 'post-command)
2663 (company--show-inline-p))
2664 (company-pseudo-tooltip-frontend command)))
2666 ;;; overlay ;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;
2668 (defvar-local company-preview-overlay nil)
2670 (defun company-preview-show-at-point (pos)
2671 (company-preview-hide)
2673 (let ((completion (nth company-selection company-candidates)))
2674 (setq completion (propertize completion 'face 'company-preview))
2675 (add-text-properties 0 (length company-common)
2676 '(face company-preview-common) completion)
2678 ;; Add search string
2679 (and company-search-string
2680 (string-match (regexp-quote company-search-string) completion)
2681 (add-text-properties (match-beginning 0)
2683 '(face company-preview-search)
2686 (setq completion (company-strip-prefix completion))
2688 (and (equal pos (point))
2689 (not (equal completion ""))
2690 (add-text-properties 0 1 '(cursor 1) completion))
2693 (pto company-pseudo-tooltip-overlay)
2694 (ptf-workaround (and
2697 (eq pos (overlay-start pto)))))
2698 ;; Try to accomodate for the pseudo-tooltip overlay,
2699 ;; which may start at the same position if it's at eol.
2700 (when ptf-workaround
2702 (setq completion (concat (buffer-substring beg pos) completion)))
2704 (setq company-preview-overlay (make-overlay beg pos))
2706 (let ((ov company-preview-overlay))
2707 (overlay-put ov (if ptf-workaround 'display 'after-string)
2709 (overlay-put ov 'window (selected-window))))))
2711 (defun company-preview-hide ()
2712 (when company-preview-overlay
2713 (delete-overlay company-preview-overlay)
2714 (setq company-preview-overlay nil)))
2716 (defun company-preview-frontend (command)
2717 "`company-mode' front-end showing the selection as if it had been inserted."
2719 (`pre-command (company-preview-hide))
2720 (`post-command (company-preview-show-at-point (point)))
2721 (`hide (company-preview-hide))))
2723 (defun company-preview-if-just-one-frontend (command)
2724 "`company-preview-frontend', but only shown for single candidates."
2725 (when (or (not (eq command 'post-command))
2726 (company--show-inline-p))
2727 (company-preview-frontend command)))
2729 (defun company--show-inline-p ()
2730 (and (not (cdr company-candidates))
2732 (or (eq (company-call-backend 'ignore-case) 'keep-prefix)
2733 (string-prefix-p company-prefix company-common))))
2735 ;;; echo ;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;
2737 (defvar-local company-echo-last-msg nil)
2739 (defvar company-echo-timer nil)
2741 (defvar company-echo-delay .01)
2743 (defun company-echo-show (&optional getter)
2745 (setq company-echo-last-msg (funcall getter)))
2746 (let ((message-log-max nil))
2747 (if company-echo-last-msg
2748 (message "%s" company-echo-last-msg)
2751 (defun company-echo-show-soon (&optional getter)
2752 (when company-echo-timer
2753 (cancel-timer company-echo-timer))
2754 (setq company-echo-timer (run-with-timer 0 nil 'company-echo-show getter)))
2756 (defsubst company-echo-show-when-idle (&optional getter)
2757 (when (sit-for company-echo-delay)
2758 (company-echo-show getter)))
2760 (defun company-echo-format ()
2762 (let ((limit (window-body-width (minibuffer-window)))
2764 ;; Roll to selection.
2765 (candidates (nthcdr company-selection company-candidates))
2766 (i (if company-show-numbers company-selection 99999))
2770 (setq comp (company-reformat (pop candidates))
2771 len (+ len 1 (length comp)))
2775 (setq comp (propertize (format "%d: %s" i comp)
2776 'face 'company-echo))
2779 (add-text-properties 3 (+ 3 (length company-common))
2780 '(face company-echo-common) comp))
2781 (setq comp (propertize comp 'face 'company-echo))
2782 (add-text-properties 0 (length company-common)
2783 '(face company-echo-common) comp))
2785 (setq candidates nil)
2788 (mapconcat 'identity (nreverse msg) " ")))
2790 (defun company-echo-strip-common-format ()
2792 (let ((limit (window-body-width (minibuffer-window)))
2793 (len (+ (length company-prefix) 2))
2794 ;; Roll to selection.
2795 (candidates (nthcdr company-selection company-candidates))
2796 (i (if company-show-numbers company-selection 99999))
2800 (setq comp (company-strip-prefix (pop candidates))
2801 len (+ len 2 (length comp)))
2804 (setq comp (format "%s (%d)" comp i))
2808 (setq candidates nil)
2809 (push (propertize comp 'face 'company-echo) msg)))
2811 (concat (propertize company-prefix 'face 'company-echo-common) "{"
2812 (mapconcat 'identity (nreverse msg) ", ")
2815 (defun company-echo-hide ()
2816 (unless (equal company-echo-last-msg "")
2817 (setq company-echo-last-msg "")
2818 (company-echo-show)))
2820 (defun company-echo-frontend (command)
2821 "`company-mode' front-end showing the candidates in the echo area."
2823 (`post-command (company-echo-show-soon 'company-echo-format))
2824 (`hide (company-echo-hide))))
2826 (defun company-echo-strip-common-frontend (command)
2827 "`company-mode' front-end showing the candidates in the echo area."
2829 (`post-command (company-echo-show-soon 'company-echo-strip-common-format))
2830 (`hide (company-echo-hide))))
2832 (defun company-echo-metadata-frontend (command)
2833 "`company-mode' front-end showing the documentation in the echo area."
2835 (`post-command (company-echo-show-when-idle 'company-fetch-metadata))
2836 (`hide (company-echo-hide))))
2839 ;;; company.el ends here