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-ropemacs . "ropemacs")
304 (company-semantic . "Semantic")
305 (company-tempo . "Tempo templates")
306 (company-xcode . "Xcode")))
307 (put 'company-safe-backends 'risky-local-variable t)
309 (defun company-safe-backends-p (backends)
310 (and (consp backends)
311 (not (cl-dolist (backend backends)
312 (unless (if (consp backend)
313 (company-safe-backends-p backend)
314 (assq backend company-safe-backends))
317 (defcustom company-backends `(,@(unless (version< "24.3.51" emacs-version)
318 (list 'company-elisp))
320 company-nxml company-css
321 company-eclim company-semantic company-clang
322 company-xcode company-ropemacs company-cmake
324 (company-dabbrev-code company-gtags company-etags
326 company-oddmuse company-files company-dabbrev)
327 "The list of active back-ends (completion engines).
329 Only one back-end is used at a time. The choice depends on the order of
330 the items in this list, and on the values they return in response to the
331 `prefix' command (see below). But a back-end can also be a \"grouped\"
334 `company-begin-backend' can be used to start a specific back-end,
335 `company-other-backend' will skip to the next matching back-end in the list.
337 Each back-end is a function that takes a variable number of arguments.
338 The first argument is the command requested from the back-end. It is one
341 `prefix': The back-end should return the text to be completed. It must be
342 text immediately before point. Returning nil from this command passes
343 control to the next back-end. The function should return `stop' if it
344 should complete but cannot (e.g. if it is in the middle of a string).
345 Instead of a string, the back-end may return a cons where car is the prefix
346 and cdr is used in `company-minimum-prefix-length' test. It must be either
347 number or t, and in the latter case the test automatically succeeds.
349 `candidates': The second argument is the prefix to be completed. The
350 return value should be a list of candidates that match the prefix.
352 Non-prefix matches are also supported (candidates that don't start with the
353 prefix, but match it in some backend-defined way). Backends that use this
354 feature must disable cache (return t to `no-cache') and might also want to
359 `sorted': Return t here to indicate that the candidates are sorted and will
360 not need to be sorted again.
362 `duplicates': If non-nil, company will take care of removing duplicates
365 `no-cache': Usually company doesn't ask for candidates again as completion
366 progresses, unless the back-end returns t for this command. The second
367 argument is the latest prefix.
369 `meta': The second argument is a completion candidate. Return a (short)
370 documentation string for it.
372 `doc-buffer': The second argument is a completion candidate. Return a
373 buffer with documentation for it. Preferably use `company-doc-buffer',
375 `location': The second argument is a completion candidate. Return the cons
376 of buffer and buffer location, or of file and line number where the
377 completion candidate was defined.
379 `annotation': The second argument is a completion candidate. Return a
380 string to be displayed inline with the candidate in the popup. If
381 duplicates are removed by company, candidates with equal string values will
382 be kept if they have different annotations. For that to work properly,
383 backends should store the related information on candidates using text
386 `match': The second argument is a completion candidate. Return the index
387 after the end of text matching `prefix' within the candidate string. It
388 will be used when rendering the popup. This command only makes sense for
389 backends that provide non-prefix completion.
391 `require-match': If this returns t, the user is not allowed to enter
392 anything not offered as a candidate. Use with care! The default value nil
393 gives the user that choice with `company-require-match'. Return value
394 `never' overrides that option the other way around.
396 `init': Called once for each buffer. The back-end can check for external
397 programs and files and load any required libraries. Raising an error here
398 will show up in message log once, and the back-end will not be used for
401 `post-completion': Called after a completion candidate has been inserted
402 into the buffer. The second argument is the candidate. Can be used to
403 modify it, e.g. to expand a snippet.
405 The back-end should return nil for all commands it does not support or
406 does not know about. It should also be callable interactively and use
407 `company-begin-backend' to start itself in that case.
411 An element of `company-backends' can also itself be a list of back-ends,
412 then it's considered to be a \"grouped\" back-end.
414 When possible, commands taking a candidate as an argument are dispatched to
415 the back-end it came from. In other cases, the first non-nil value among
416 all the back-ends is returned.
418 The latter is the case for the `prefix' command. But if the group contains
419 the keyword `:with', the back-ends after it are ignored for this command.
421 The completions from back-ends in a group are merged (but only from those
422 that return the same `prefix').
424 Asynchronous back-ends:
426 The return value of each command can also be a cons (:async . FETCHER)
427 where FETCHER is a function of one argument, CALLBACK. When the data
428 arrives, FETCHER must call CALLBACK and pass it the appropriate return
429 value, as described above.
431 True asynchronous operation is only supported for command `candidates', and
432 only during idle completion. Other commands will block the user interface,
433 even if the back-end uses the asynchronous calling convention."
437 ,@(mapcar (lambda (b) `(const :tag ,(cdr b) ,(car b)))
438 company-safe-backends)
439 (symbol :tag "User defined")
440 (repeat :tag "Merged Back-ends"
441 (choice :tag "Back-end"
442 ,@(mapcar (lambda (b)
443 `(const :tag ,(cdr b) ,(car b)))
444 company-safe-backends)
445 (const :tag "With" :with)
446 (symbol :tag "User defined"))))))
448 (put 'company-backends 'safe-local-variable 'company-safe-backends-p)
450 (defcustom company-transformers nil
451 "Functions to change the list of candidates received from backends.
453 Each function gets called with the return value of the previous one.
454 The first one gets passed the list of candidates, already sorted and
457 (const :tag "None" nil)
458 (const :tag "Sort by occurrence" (company-sort-by-occurrence))
459 (const :tag "Sort by back-end importance"
460 (company-sort-by-backend-importance))
461 (repeat :tag "User defined" (function))))
463 (defcustom company-completion-started-hook nil
464 "Hook run when company starts completing.
465 The hook is called with one argument that is non-nil if the completion was
469 (defcustom company-completion-cancelled-hook nil
470 "Hook run when company cancels completing.
471 The hook is called with one argument that is non-nil if the completion was
475 (defcustom company-completion-finished-hook nil
476 "Hook run when company successfully completes.
477 The hook is called with the selected candidate as an argument.
479 If you indend to use it to post-process candidates from a specific
480 back-end, consider using the `post-completion' command instead."
483 (defcustom company-minimum-prefix-length 3
484 "The minimum prefix length for idle completion."
485 :type '(integer :tag "prefix length"))
487 (defcustom company-abort-manual-when-too-short nil
488 "If enabled, cancel a manually started completion when the prefix gets
489 shorter than both `company-minimum-prefix-length' and the length of the
490 prefix it was started from."
492 :package-version '(company . "0.8.0"))
494 (defcustom company-require-match 'company-explicit-action-p
495 "If enabled, disallow non-matching input.
496 This can be a function do determine if a match is required.
498 This can be overridden by the back-end, if it returns t or `never' to
499 `require-match'. `company-auto-complete' also takes precedence over this."
500 :type '(choice (const :tag "Off" nil)
501 (function :tag "Predicate function")
502 (const :tag "On, if user interaction took place"
503 'company-explicit-action-p)
504 (const :tag "On" t)))
506 (defcustom company-auto-complete nil
507 "Determines when to auto-complete.
508 If this is enabled, all characters from `company-auto-complete-chars'
509 trigger insertion of the selected completion candidate.
510 This can also be a function."
511 :type '(choice (const :tag "Off" nil)
512 (function :tag "Predicate function")
513 (const :tag "On, if user interaction took place"
514 'company-explicit-action-p)
515 (const :tag "On" t)))
517 (defcustom company-auto-complete-chars '(?\ ?\) ?.)
518 "Determines which characters trigger auto-completion.
519 See `company-auto-complete'. If this is a string, each string character
520 tiggers auto-completion. If it is a list of syntax description characters (see
521 `modify-syntax-entry'), all characters with that syntax auto-complete.
523 This can also be a function, which is called with the new input and should
524 return non-nil if company should auto-complete.
526 A character that is part of a valid candidate never triggers auto-completion."
527 :type '(choice (string :tag "Characters")
529 (const :tag "Whitespace" ?\ )
530 (const :tag "Symbol" ?_)
531 (const :tag "Opening parentheses" ?\()
532 (const :tag "Closing parentheses" ?\))
533 (const :tag "Word constituent" ?w)
534 (const :tag "Punctuation." ?.)
535 (const :tag "String quote." ?\")
536 (const :tag "Paired delimiter." ?$)
537 (const :tag "Expression quote or prefix operator." ?\')
538 (const :tag "Comment starter." ?<)
539 (const :tag "Comment ender." ?>)
540 (const :tag "Character-quote." ?/)
541 (const :tag "Generic string fence." ?|)
542 (const :tag "Generic comment fence." ?!))
543 (function :tag "Predicate function")))
545 (defcustom company-idle-delay .5
546 "The idle delay in seconds until completion starts automatically.
547 The prefix still has to satisfy `company-minimum-prefix-length' before that
548 happens. The value of nil means no idle completion."
549 :type '(choice (const :tag "never (nil)" nil)
550 (const :tag "immediate (0)" 0)
551 (number :tag "seconds")))
553 (defcustom company-begin-commands '(self-insert-command
554 org-self-insert-command
555 orgtbl-self-insert-command
560 "A list of commands after which idle completion is allowed.
561 If this is t, it can show completions after any command except a few from a
562 pre-defined list. See `company-idle-delay'.
564 Alternatively, any command with a non-nil `company-begin' property is
565 treated as if it was on this list."
566 :type '(choice (const :tag "Any command" t)
567 (const :tag "Self insert command" '(self-insert-command))
568 (repeat :tag "Commands" function))
569 :package-version '(company . "0.8.4"))
571 (defcustom company-continue-commands '(not save-buffer save-some-buffers
572 save-buffers-kill-terminal
573 save-buffers-kill-emacs)
574 "A list of commands that are allowed during completion.
575 If this is t, or if `company-begin-commands' is t, any command is allowed.
576 Otherwise, the value must be a list of symbols. If it starts with `not',
577 the cdr is the list of commands that abort completion. Otherwise, all
578 commands except those in that list, or in `company-begin-commands', or
579 commands in the `company-' namespace, abort completion."
580 :type '(choice (const :tag "Any command" t)
581 (cons :tag "Any except"
583 (repeat :tag "Commands" function))
584 (repeat :tag "Commands" function)))
586 (defcustom company-show-numbers nil
587 "If enabled, show quick-access numbers for the first ten candidates."
588 :type '(choice (const :tag "off" nil)
589 (const :tag "on" t)))
591 (defcustom company-selection-wrap-around nil
592 "If enabled, selecting item before first or after last wraps around."
593 :type '(choice (const :tag "off" nil)
594 (const :tag "on" t)))
596 (defvar company-async-wait 0.03
597 "Pause between checks to see if the value's been set when turning an
598 asynchronous call into synchronous.")
600 (defvar company-async-timeout 2
601 "Maximum wait time for a value to be set during asynchronous call.")
603 ;;; mode ;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;
605 (defvar company-mode-map (make-sparse-keymap)
606 "Keymap used by `company-mode'.")
608 (defvar company-active-map
609 (let ((keymap (make-sparse-keymap)))
610 (define-key keymap "\e\e\e" 'company-abort)
611 (define-key keymap "\C-g" 'company-abort)
612 (define-key keymap (kbd "M-n") 'company-select-next)
613 (define-key keymap (kbd "M-p") 'company-select-previous)
614 (define-key keymap (kbd "<down>") 'company-select-next-or-abort)
615 (define-key keymap (kbd "<up>") 'company-select-previous-or-abort)
616 (define-key keymap [remap scroll-up-command] 'company-next-page)
617 (define-key keymap [remap scroll-down-command] 'company-previous-page)
618 (define-key keymap [down-mouse-1] 'ignore)
619 (define-key keymap [down-mouse-3] 'ignore)
620 (define-key keymap [mouse-1] 'company-complete-mouse)
621 (define-key keymap [mouse-3] 'company-select-mouse)
622 (define-key keymap [up-mouse-1] 'ignore)
623 (define-key keymap [up-mouse-3] 'ignore)
624 (define-key keymap [return] 'company-complete-selection)
625 (define-key keymap (kbd "RET") 'company-complete-selection)
626 (define-key keymap [tab] 'company-complete-common)
627 (define-key keymap (kbd "TAB") 'company-complete-common)
628 (define-key keymap (kbd "<f1>") 'company-show-doc-buffer)
629 (define-key keymap (kbd "C-h") 'company-show-doc-buffer)
630 (define-key keymap "\C-w" 'company-show-location)
631 (define-key keymap "\C-s" 'company-search-candidates)
632 (define-key keymap "\C-\M-s" 'company-filter-candidates)
634 (define-key keymap (read-kbd-macro (format "M-%d" i)) 'company-complete-number))
636 "Keymap that is enabled during an active completion.")
638 (defvar company--disabled-backends nil)
640 (defun company-init-backend (backend)
641 (and (symbolp backend)
642 (not (fboundp backend))
643 (ignore-errors (require backend nil t)))
648 (funcall backend 'init)
649 (put backend 'company-init t))
651 (put backend 'company-init 'failed)
652 (unless (memq backend company--disabled-backends)
653 (message "Company back-end '%s' could not be initialized:\n%s"
654 backend (error-message-string err)))
655 (cl-pushnew backend company--disabled-backends)
657 ;; No initialization for lambdas.
658 ((functionp backend) t)
659 (t ;; Must be a list.
660 (cl-dolist (b backend)
662 (company-init-backend b))))))
664 (defcustom company-lighter-base "company"
665 "Base string to use for the `company-mode' lighter."
667 :package-version '(company . "0.8.10"))
669 (defvar company-lighter '(" "
672 (if (consp company-backend)
673 (company--group-lighter (nth company-selection
675 company-lighter-base)
676 (symbol-name company-backend)))
677 company-lighter-base))
678 "Mode line lighter for Company.
680 The value of this variable is a mode line template as in
681 `mode-line-format'.")
683 (put 'company-lighter 'risky-local-variable t)
686 (define-minor-mode company-mode
687 "\"complete anything\"; is an in-buffer completion framework.
688 Completion starts automatically, depending on the values
689 `company-idle-delay' and `company-minimum-prefix-length'.
691 Completion can be controlled with the commands:
692 `company-complete-common', `company-complete-selection', `company-complete',
693 `company-select-next', `company-select-previous'. If these commands are
694 called before `company-idle-delay', completion will also start.
696 Completions can be searched with `company-search-candidates' or
697 `company-filter-candidates'. These can be used while completion is
700 The completion data is retrieved using `company-backends' and displayed
701 using `company-frontends'. If you want to start a specific back-end, call
702 it interactively or use `company-begin-backend'.
704 regular keymap (`company-mode-map'):
707 keymap during active completions (`company-active-map'):
709 \\{company-active-map}"
710 nil company-lighter company-mode-map
713 (when (eq company-idle-delay t)
714 (setq company-idle-delay 0)
715 (warn "Setting `company-idle-delay' to t is deprecated. Set it to 0 instead."))
716 (add-hook 'pre-command-hook 'company-pre-command nil t)
717 (add-hook 'post-command-hook 'company-post-command nil t)
718 (mapc 'company-init-backend company-backends))
719 (remove-hook 'pre-command-hook 'company-pre-command t)
720 (remove-hook 'post-command-hook 'company-post-command t)
722 (kill-local-variable 'company-point)))
724 (defcustom company-global-modes t
725 "Modes for which `company-mode' mode is turned on by `global-company-mode'.
726 If nil, means no modes. If t, then all major modes have it turned on.
727 If a list, it should be a list of `major-mode' symbol names for which
728 `company-mode' should be automatically turned on. The sense of the list is
729 negated if it begins with `not'. For example:
731 means that `company-mode' is turned on for buffers in C and C++ modes only.
733 means that `company-mode' is always turned on except in `message-mode' buffers."
734 :type '(choice (const :tag "none" nil)
736 (set :menu-tag "mode specific" :tag "modes"
738 (const :tag "Except" not)
739 (repeat :inline t (symbol :tag "mode")))))
742 (define-globalized-minor-mode global-company-mode company-mode company-mode-on)
744 (defun company-mode-on ()
745 (when (and (not (or noninteractive (eq (aref (buffer-name) 0) ?\s)))
746 (cond ((eq company-global-modes t)
748 ((eq (car-safe company-global-modes) 'not)
749 (not (memq major-mode (cdr company-global-modes))))
750 (t (memq major-mode company-global-modes))))
753 (defsubst company-assert-enabled ()
755 (company-uninstall-map)
756 (error "Company not enabled")))
758 ;;; keymaps ;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;
760 (defvar-local company-my-keymap nil)
762 (defvar company-emulation-alist '((t . nil)))
764 (defsubst company-enable-overriding-keymap (keymap)
765 (company-uninstall-map)
766 (setq company-my-keymap keymap))
768 (defun company-ensure-emulation-alist ()
769 (unless (eq 'company-emulation-alist (car emulation-mode-map-alists))
770 (setq emulation-mode-map-alists
771 (cons 'company-emulation-alist
772 (delq 'company-emulation-alist emulation-mode-map-alists)))))
774 (defun company-install-map ()
775 (unless (or (cdar company-emulation-alist)
776 (null company-my-keymap))
777 (setf (cdar company-emulation-alist) company-my-keymap)))
779 (defun company-uninstall-map ()
780 (setf (cdar company-emulation-alist) nil))
783 ;; Emacs calculates the active keymaps before reading the event. That means we
784 ;; cannot change the keymap from a timer. So we send a bogus command.
785 ;; XXX: Even in Emacs 24.4, seems to be needed in the terminal.
786 (defun company-ignore ()
788 (setq this-command last-command))
790 (global-set-key '[company-dummy-event] 'company-ignore)
792 (defun company-input-noop ()
793 (push 'company-dummy-event unread-command-events))
795 (defun company--posn-col-row (posn)
796 (let ((col (car (posn-col-row posn)))
797 ;; `posn-col-row' doesn't work well with lines of different height.
798 ;; `posn-actual-col-row' doesn't handle multiple-width characters.
799 (row (cdr (posn-actual-col-row posn))))
800 (when (and header-line-format (version< emacs-version "24.3.93.3"))
801 ;; http://debbugs.gnu.org/18384
803 (cons (+ col (window-hscroll)) row)))
805 (defun company--col-row (&optional pos)
806 (company--posn-col-row (posn-at-point pos)))
808 (defun company--row (&optional pos)
809 (cdr (company--col-row pos)))
811 ;;; backends ;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;
813 (defvar-local company-backend nil)
815 (defun company-grab (regexp &optional expression limit)
816 (when (looking-back regexp limit)
817 (or (match-string-no-properties (or expression 0)) "")))
819 (defun company-grab-line (regexp &optional expression)
820 (company-grab regexp expression (point-at-bol)))
822 (defun company-grab-symbol ()
823 (if (looking-at "\\_>")
824 (buffer-substring (point) (save-excursion (skip-syntax-backward "w_")
826 (unless (and (char-after) (memq (char-syntax (char-after)) '(?w ?_)))
829 (defun company-grab-word ()
830 (if (looking-at "\\>")
831 (buffer-substring (point) (save-excursion (skip-syntax-backward "w")
833 (unless (and (char-after) (eq (char-syntax (char-after)) ?w))
836 (defun company-grab-symbol-cons (idle-begin-after-re &optional max-len)
837 (let ((symbol (company-grab-symbol)))
840 (forward-char (- (length symbol)))
841 (if (looking-back idle-begin-after-re (if max-len
843 (line-beginning-position)))
847 (defun company-in-string-or-comment ()
848 (let ((ppss (syntax-ppss)))
849 (or (car (setq ppss (nthcdr 3 ppss)))
850 (car (setq ppss (cdr ppss)))
853 (defun company-call-backend (&rest args)
854 (company--force-sync #'company-call-backend-raw args company-backend))
856 (defun company--force-sync (fun args backend)
857 (let ((value (apply fun args)))
858 (if (not (eq (car-safe value) :async))
861 (start (time-to-seconds)))
863 (lambda (result) (setq res result)))
864 (while (eq res 'trash)
865 (if (> (- (time-to-seconds) start) company-async-timeout)
866 (error "Company: Back-end %s async timeout with args %s"
868 (sleep-for company-async-wait)))
871 (defun company-call-backend-raw (&rest args)
872 (condition-case-unless-debug err
873 (if (functionp company-backend)
874 (apply company-backend args)
875 (apply #'company--multi-backend-adapter company-backend args))
876 (error (error "Company: Back-end %s error \"%s\" with args %s"
877 company-backend (error-message-string err) args))))
879 (defun company--multi-backend-adapter (backends command &rest args)
880 (let ((backends (cl-loop for b in backends
881 when (not (and (symbolp b)
882 (eq 'failed (get b 'company-init))))
885 (if (eq command 'prefix)
886 (butlast backends (length (member :with backends)))
887 (delq :with backends)))
890 (company--multi-backend-adapter-candidates backends (car args)))
893 ((or `prefix `ignore-case `no-cache `require-match)
895 (cl-dolist (backend backends)
896 (when (setq value (company--force-sync
897 backend (cons command args) backend))
898 (cl-return value)))))
900 (let ((arg (car args)))
901 (when (> (length arg) 0)
902 (let ((backend (or (get-text-property 0 'company-backend arg)
904 (apply backend command args))))))))
906 (defun company--multi-backend-adapter-candidates (backends prefix)
907 (let ((pairs (cl-loop for backend in (cdr backends)
908 when (equal (company--prefix-str
909 (funcall backend 'prefix))
911 collect (cons (funcall backend 'candidates prefix)
916 (propertize str 'company-backend b))
918 (when (equal (company--prefix-str (funcall (car backends) 'prefix)) prefix)
919 ;; Small perf optimization: don't tag the candidates received
920 ;; from the first backend in the group.
921 (push (cons (funcall (car backends) 'candidates prefix)
924 (company--merge-async pairs (lambda (values) (apply #'append values)))))
926 (defun company--merge-async (pairs merger)
927 (let ((async (cl-loop for pair in pairs
929 (eq :async (car-safe (car pair))))))
931 (funcall merger (cl-loop for (val . mapper) in pairs
932 collect (funcall mapper val)))
937 (pending (mapcar #'car pairs))
948 (this-finisher (lambda (res)
949 (setq pending (delq val pending))
950 (setcar cell (funcall mapper res))
951 (funcall finisher))))
952 (if (not (eq :async (car-safe val)))
953 (funcall this-finisher val)
954 (let ((fetcher (cdr val)))
955 (funcall fetcher this-finisher)))))))))))
957 (defun company--prefix-str (prefix)
958 (or (car-safe prefix) prefix))
960 ;;; completion mechanism ;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;
962 (defvar-local company-prefix nil)
964 (defvar-local company-candidates nil)
966 (defvar-local company-candidates-length nil)
968 (defvar-local company-candidates-cache nil)
970 (defvar-local company-candidates-predicate nil)
972 (defvar-local company-common nil)
974 (defvar-local company-selection 0)
976 (defvar-local company-selection-changed nil)
978 (defvar-local company--manual-action nil
979 "Non-nil, if manual completion took place.")
981 (defvar-local company--manual-prefix nil)
983 (defvar company--auto-completion nil
984 "Non-nil when current candidate is being inserted automatically.
985 Controlled by `company-auto-complete'.")
987 (defvar-local company--point-max nil)
989 (defvar-local company-point nil)
991 (defvar company-timer nil)
993 (defsubst company-strip-prefix (str)
994 (substring str (length company-prefix)))
996 (defun company--insert-candidate (candidate)
997 (setq candidate (substring-no-properties candidate))
998 ;; XXX: Return value we check here is subject to change.
999 (if (eq (company-call-backend 'ignore-case) 'keep-prefix)
1000 (insert (company-strip-prefix candidate))
1001 (unless (equal company-prefix candidate)
1002 (delete-region (- (point) (length company-prefix)) (point))
1003 (insert candidate))))
1005 (defmacro company-with-candidate-inserted (candidate &rest body)
1006 "Evaluate BODY with CANDIDATE temporarily inserted.
1007 This is a tool for back-ends that need candidates inserted before they
1008 can retrieve meta-data for them."
1009 (declare (indent 1))
1010 `(let ((inhibit-modification-hooks t)
1011 (inhibit-point-motion-hooks t)
1012 (modified-p (buffer-modified-p)))
1013 (company--insert-candidate ,candidate)
1016 (delete-region company-point (point))
1017 (set-buffer-modified-p modified-p))))
1019 (defun company-explicit-action-p ()
1020 "Return whether explicit completion action was taken by the user."
1021 (or company--manual-action
1022 company-selection-changed))
1024 (defun company-reformat (candidate)
1025 ;; company-ispell needs this, because the results are always lower-case
1026 ;; It's mory efficient to fix it only when they are displayed.
1027 ;; FIXME: Adopt the current text's capitalization instead?
1028 (if (eq (company-call-backend 'ignore-case) 'keep-prefix)
1029 (concat company-prefix (substring candidate (length company-prefix)))
1032 (defun company--should-complete ()
1033 (and (eq company-idle-delay 'now)
1034 (not (or buffer-read-only overriding-terminal-local-map
1035 overriding-local-map))
1036 ;; Check if in the middle of entering a key combination.
1037 (or (equal (this-command-keys-vector) [])
1038 (not (keymapp (key-binding (this-command-keys-vector)))))
1039 (not (and transient-mark-mode mark-active))))
1041 (defun company--should-continue ()
1042 (or (eq t company-begin-commands)
1043 (eq t company-continue-commands)
1044 (if (eq 'not (car company-continue-commands))
1045 (not (memq this-command (cdr company-continue-commands)))
1046 (or (memq this-command company-begin-commands)
1047 (memq this-command company-continue-commands)
1048 (and (symbolp this-command)
1049 (string-match-p "\\`company-" (symbol-name this-command)))))))
1051 (defun company-call-frontends (command)
1052 (dolist (frontend company-frontends)
1053 (condition-case-unless-debug err
1054 (funcall frontend command)
1055 (error (error "Company: Front-end %s error \"%s\" on command %s"
1056 frontend (error-message-string err) command)))))
1058 (defun company-set-selection (selection &optional force-update)
1060 (if company-selection-wrap-around
1061 (mod selection company-candidates-length)
1062 (max 0 (min (1- company-candidates-length) selection))))
1063 (when (or force-update (not (equal selection company-selection)))
1064 (setq company-selection selection
1065 company-selection-changed t)
1066 (company-call-frontends 'update)))
1068 (defun company--group-lighter (candidate base)
1069 (let ((backend (or (get-text-property 0 'company-backend candidate)
1070 (car company-backend))))
1071 (when (and backend (symbolp backend))
1072 (let ((name (replace-regexp-in-string "company-\\|-company" ""
1073 (symbol-name backend))))
1074 (format "%s-<%s>" base name)))))
1076 (defun company-update-candidates (candidates)
1077 (setq company-candidates-length (length candidates))
1078 (if company-selection-changed
1079 ;; Try to restore the selection
1080 (let ((selected (nth company-selection company-candidates)))
1081 (setq company-selection 0
1082 company-candidates candidates)
1086 (let ((candidate (pop candidates)))
1087 (when (and (string= candidate selected)
1088 (equal (company-call-backend 'annotation candidate)
1089 (company-call-backend 'annotation selected)))
1091 (cl-incf company-selection))
1092 (setq company-selection 0
1093 company-selection-changed nil))))
1094 (setq company-selection 0
1095 company-candidates candidates))
1096 ;; Calculate common.
1097 (let ((completion-ignore-case (company-call-backend 'ignore-case)))
1098 ;; We want to support non-prefix completion, so filtering is the
1099 ;; responsibility of each respective backend, not ours.
1100 ;; On the other hand, we don't want to replace non-prefix input in
1101 ;; `company-complete-common', unless there's only one candidate.
1102 (setq company-common
1103 (if (cdr company-candidates)
1104 (let ((common (try-completion "" company-candidates)))
1105 (when (string-prefix-p company-prefix common
1106 completion-ignore-case)
1108 (car company-candidates)))))
1110 (defun company-calculate-candidates (prefix)
1111 (let ((candidates (cdr (assoc prefix company-candidates-cache)))
1112 (ignore-case (company-call-backend 'ignore-case)))
1114 (when company-candidates-cache
1115 (let ((len (length prefix))
1116 (completion-ignore-case ignore-case)
1118 (cl-dotimes (i (1+ len))
1119 (when (setq prev (cdr (assoc (substring prefix 0 (- len i))
1120 company-candidates-cache)))
1121 (setq candidates (all-completions prefix prev))
1124 ;; No cache match, call the backend.
1125 (setq candidates (company--preprocess-candidates
1126 (company--fetch-candidates prefix)))
1128 (push (cons prefix candidates) company-candidates-cache)))
1129 ;; Only now apply the predicate and transformers.
1130 (setq candidates (company--postprocess-candidates candidates))
1132 (if (or (cdr candidates)
1133 (not (eq t (compare-strings (car candidates) nil nil
1134 prefix nil nil ignore-case))))
1136 ;; Already completed and unique; don't start.
1139 (defun company--fetch-candidates (prefix)
1140 (let ((c (if company--manual-action
1141 (company-call-backend 'candidates prefix)
1142 (company-call-backend-raw 'candidates prefix)))
1144 (if (not (eq (car c) :async))
1146 (let ((buf (current-buffer))
1147 (win (selected-window))
1148 (tick (buffer-chars-modified-tick))
1150 (backend company-backend))
1153 (lambda (candidates)
1154 (if (not (and candidates (eq res 'done)))
1155 ;; There's no completions to display,
1156 ;; or the fetcher called us back right away.
1157 (setq res candidates)
1158 (setq company-backend backend
1159 company-candidates-cache
1161 (company--preprocess-candidates candidates))))
1162 (company-idle-begin buf win tick pt)))))
1163 ;; FIXME: Relying on the fact that the callers
1164 ;; will interpret nil as "do nothing" is shaky.
1165 ;; A throw-catch would be one possible improvement.
1167 (progn (setq res 'done) nil)))))
1169 (defun company--preprocess-candidates (candidates)
1170 (unless (company-call-backend 'sorted)
1171 (setq candidates (sort candidates 'string<)))
1172 (when (company-call-backend 'duplicates)
1173 (company--strip-duplicates candidates))
1176 (defun company--postprocess-candidates (candidates)
1177 (when (or company-candidates-predicate company-transformers)
1178 (setq candidates (copy-sequence candidates)))
1179 (when company-candidates-predicate
1180 (setq candidates (cl-delete-if-not company-candidates-predicate candidates)))
1181 (company--transform-candidates candidates))
1183 (defun company--strip-duplicates (candidates)
1184 (let ((c2 candidates)
1188 (let ((str (pop c2)))
1189 (while (let ((str2 (car c2)))
1190 (if (not (equal str str2))
1194 (when (eq annos 'unk)
1195 (setq annos (list (company-call-backend
1197 (let ((anno2 (company-call-backend
1199 (if (member anno2 annos)
1206 (defun company--transform-candidates (candidates)
1207 (let ((c candidates))
1208 (dolist (tr company-transformers)
1209 (setq c (funcall tr c)))
1212 (defcustom company-occurrence-weight-function
1213 #'company-occurrence-prefer-closest-above
1214 "Function to weigh matches in `company-sort-by-occurrence'.
1215 It's called with three arguments: cursor position, the beginning and the
1218 (const :tag "First above point, then below point"
1219 company-occurrence-prefer-closest-above)
1220 (const :tag "Prefer closest in any direction"
1221 company-occurrence-prefer-any-closest)))
1223 (defun company-occurrence-prefer-closest-above (pos match-beg match-end)
1224 "Give priority to the matches above point, then those below point."
1225 (if (< match-beg pos)
1227 (- match-beg (window-start))))
1229 (defun company-occurrence-prefer-any-closest (pos _match-beg match-end)
1230 "Give priority to the matches closest to the point."
1231 (abs (- pos match-end)))
1233 (defun company-sort-by-occurrence (candidates)
1234 "Sort CANDIDATES according to their occurrences.
1235 Searches for each in the currently visible part of the current buffer and
1236 prioritizes the matches according to `company-occurrence-weight-function'.
1237 The rest of the list is appended unchanged.
1238 Keywords and function definition names are ignored."
1239 (let* ((w-start (window-start))
1240 (w-end (window-end))
1241 (start-point (point))
1249 (while (search-forward candidate w-end t)
1250 (when (and (not (eq (point) start-point))
1252 (company--occurrence-predicate)))
1256 (funcall company-occurrence-weight-function
1264 (mapcar #'car (sort occurs (lambda (e1 e2) (<= (cdr e1) (cdr e2)))))
1267 (defun company--occurrence-predicate ()
1268 (let ((beg (match-beginning 0))
1269 (end (match-end 0)))
1272 (and (not (memq (get-text-property (1- (point)) 'face)
1273 '(font-lock-function-name-face
1274 font-lock-keyword-face)))
1275 (let ((prefix (company--prefix-str
1276 (company-call-backend 'prefix))))
1277 (and (stringp prefix)
1278 (= (length prefix) (- end beg))))))))
1280 (defun company-sort-by-backend-importance (candidates)
1281 "Sort CANDIDATES as two priority groups.
1282 If `company-backend' is a function, do nothing. If it's a list, move
1283 candidates from back-ends before keyword `:with' to the front. Candidates
1284 from the rest of the back-ends in the group, if any, will be left at the end."
1285 (if (functionp company-backend)
1287 (let ((low-priority (cdr (memq :with company-backend))))
1288 (if (null low-priority)
1293 (let ((b2 (get-text-property 0 'company-backend c2)))
1294 (and b2 (memq b2 low-priority)))
1295 (let ((b1 (get-text-property 0 'company-backend c1)))
1296 (or (not b1) (not (memq b1 low-priority)))))))))))
1298 (defun company-idle-begin (buf win tick pos)
1299 (and (eq buf (current-buffer))
1300 (eq win (selected-window))
1301 (eq tick (buffer-chars-modified-tick))
1303 (when (company-auto-begin)
1304 (company-input-noop)
1305 (let ((this-command 'company-idle-begin))
1306 (company-post-command)))))
1308 (defun company-auto-begin ()
1310 (not company-candidates)
1311 (let ((company-idle-delay 'now))
1312 (condition-case-unless-debug err
1315 ;; Return non-nil if active.
1317 (error (message "Company: An error occurred in auto-begin")
1318 (message "%s" (error-message-string err))
1320 (quit (company-cancel))))))
1322 (defun company-manual-begin ()
1324 (company-assert-enabled)
1325 (setq company--manual-action t)
1327 (let ((company-minimum-prefix-length 0))
1328 (or company-candidates
1329 (company-auto-begin)))
1330 (unless company-candidates
1331 (setq company--manual-action nil))))
1333 (defun company-other-backend (&optional backward)
1334 (interactive (list current-prefix-arg))
1335 (company-assert-enabled)
1336 (let* ((after (if company-backend
1337 (cdr (member company-backend company-backends))
1339 (before (cdr (member company-backend (reverse company-backends))))
1341 (append before (reverse after))
1342 (append after (reverse before)))))
1344 (cl-dolist (backend next)
1345 (when (ignore-errors (company-begin-backend backend))
1347 (unless company-candidates
1348 (error "No other back-end")))
1350 (defun company-require-match-p ()
1351 (let ((backend-value (company-call-backend 'require-match)))
1352 (or (eq backend-value t)
1353 (and (not (eq backend-value 'never))
1354 (if (functionp company-require-match)
1355 (funcall company-require-match)
1356 (eq company-require-match t))))))
1358 (defun company-auto-complete-p (input)
1359 "Return non-nil, if input starts with punctuation or parentheses."
1360 (and (if (functionp company-auto-complete)
1361 (funcall company-auto-complete)
1362 company-auto-complete)
1363 (if (functionp company-auto-complete-chars)
1364 (funcall company-auto-complete-chars input)
1365 (if (consp company-auto-complete-chars)
1366 (memq (char-syntax (string-to-char input))
1367 company-auto-complete-chars)
1368 (string-match (substring input 0 1) company-auto-complete-chars)))))
1370 (defun company--incremental-p ()
1371 (and (> (point) company-point)
1372 (> (point-max) company--point-max)
1373 (not (eq this-command 'backward-delete-char-untabify))
1374 (equal (buffer-substring (- company-point (length company-prefix))
1378 (defun company--continue-failed (new-prefix)
1379 (let ((input (buffer-substring-no-properties (point) company-point)))
1381 ((company-auto-complete-p input)
1384 (goto-char company-point)
1385 (let ((company--auto-completion t))
1386 (company-complete-selection))
1388 ((and (or (not (company-require-match-p))
1389 ;; Don't require match if the new prefix
1390 ;; doesn't continue the old one, and the latter was a match.
1391 (not (stringp new-prefix))
1392 (<= (length new-prefix) (length company-prefix)))
1393 (member company-prefix company-candidates))
1394 ;; Last input was a success,
1395 ;; but we're treating it as an abort + input anyway,
1396 ;; like the `unique' case below.
1397 (company-cancel 'non-unique))
1398 ((company-require-match-p)
1399 ;; Wrong incremental input, but required match.
1400 (delete-char (- (length input)))
1402 (message "Matching input is required")
1404 (t (company-cancel)))))
1406 (defun company--good-prefix-p (prefix)
1407 (and (stringp (company--prefix-str prefix)) ;excludes 'stop
1408 (or (eq (cdr-safe prefix) t)
1409 (let ((len (or (cdr-safe prefix) (length prefix))))
1410 (if company--manual-prefix
1411 (or (not company-abort-manual-when-too-short)
1412 ;; Must not be less than minimum or initial length.
1413 (>= len (min company-minimum-prefix-length
1414 (length company--manual-prefix))))
1415 (>= len company-minimum-prefix-length))))))
1417 (defun company--continue ()
1418 (when (company-call-backend 'no-cache company-prefix)
1419 ;; Don't complete existing candidates, fetch new ones.
1420 (setq company-candidates-cache nil))
1421 (let* ((new-prefix (company-call-backend 'prefix))
1422 (c (when (and (company--good-prefix-p new-prefix)
1423 (setq new-prefix (company--prefix-str new-prefix))
1424 (= (- (point) (length new-prefix))
1425 (- company-point (length company-prefix))))
1426 (company-calculate-candidates new-prefix))))
1429 ;; t means complete/unique.
1430 ;; Handle it like completion was aborted, to differentiate from user
1431 ;; calling one of Company's commands to insert the candidate,
1432 ;; not to trigger template expansion, etc.
1433 (company-cancel 'unique))
1435 ;; incremental match
1436 (setq company-prefix new-prefix)
1437 (company-update-candidates c)
1439 ((not (company--incremental-p))
1441 (t (company--continue-failed new-prefix)))))
1443 (defun company--begin-new ()
1445 (cl-dolist (backend (if company-backend
1446 ;; prefer manual override
1447 (list company-backend)
1450 (if (or (symbolp backend)
1451 (functionp backend))
1452 (when (or (not (symbolp backend))
1453 (eq t (get backend 'company-init))
1454 (unless (get backend 'company-init)
1455 (company-init-backend backend)))
1456 (funcall backend 'prefix))
1457 (company--multi-backend-adapter backend 'prefix)))
1459 (when (company--good-prefix-p prefix)
1460 (setq company-prefix (company--prefix-str prefix)
1461 company-backend backend
1462 c (company-calculate-candidates company-prefix))
1463 ;; t means complete/unique. We don't start, so no hooks.
1465 (when company--manual-action
1466 (message "No completion found"))
1467 (when company--manual-action
1468 (setq company--manual-prefix prefix))
1469 (company-update-candidates c)
1470 (run-hook-with-args 'company-completion-started-hook
1471 (company-explicit-action-p))
1472 (company-call-frontends 'show)))
1475 (defun company--perform ()
1476 (or (and company-candidates (company--continue))
1477 (and (company--should-complete) (company--begin-new)))
1478 (if (not company-candidates)
1479 (setq company-backend nil)
1480 (setq company-point (point)
1481 company--point-max (point-max))
1482 (company-ensure-emulation-alist)
1483 (company-enable-overriding-keymap company-active-map)
1484 (company-call-frontends 'update)))
1486 (defun company-cancel (&optional result)
1488 (when company-prefix
1489 (if (stringp result)
1491 (company-call-backend 'pre-completion result)
1492 (run-hook-with-args 'company-completion-finished-hook result)
1493 (company-call-backend 'post-completion result))
1494 (run-hook-with-args 'company-completion-cancelled-hook result)))
1495 (setq company-backend nil
1497 company-candidates nil
1498 company-candidates-length nil
1499 company-candidates-cache nil
1500 company-candidates-predicate nil
1503 company-selection-changed nil
1504 company--manual-action nil
1505 company--manual-prefix nil
1506 company--point-max nil
1509 (cancel-timer company-timer))
1510 (company-search-mode 0)
1511 (company-call-frontends 'hide)
1512 (company-enable-overriding-keymap nil))
1513 ;; Make return value explicit.
1516 (defun company-abort ()
1518 (company-cancel 'abort))
1520 (defun company-finish (result)
1521 (company--insert-candidate result)
1522 (company-cancel result))
1524 (defsubst company-keep (command)
1525 (and (symbolp command) (get command 'company-keep)))
1527 (defun company-pre-command ()
1528 (unless (company-keep this-command)
1529 (condition-case-unless-debug err
1530 (when company-candidates
1531 (company-call-frontends 'pre-command)
1532 (unless (company--should-continue)
1534 (error (message "Company: An error occurred in pre-command")
1535 (message "%s" (error-message-string err))
1538 (cancel-timer company-timer)
1539 (setq company-timer nil))
1540 (company-uninstall-map))
1542 (defun company-post-command ()
1543 (when (null this-command)
1544 ;; Happens when the user presses `C-g' while inside
1545 ;; `flyspell-post-command-hook', for example.
1546 ;; Or any other `post-command-hook' function that can call `sit-for',
1547 ;; or any quittable timer function.
1549 (setq this-command 'company-abort))
1550 (unless (company-keep this-command)
1551 (condition-case-unless-debug err
1553 (unless (equal (point) company-point)
1554 (let (company-idle-delay) ; Against misbehavior while debugging.
1555 (company--perform)))
1556 (if company-candidates
1557 (company-call-frontends 'post-command)
1558 (and (numberp company-idle-delay)
1559 (company--should-begin)
1561 (run-with-timer company-idle-delay nil
1563 (current-buffer) (selected-window)
1564 (buffer-chars-modified-tick) (point))))))
1565 (error (message "Company: An error occurred in post-command")
1566 (message "%s" (error-message-string err))
1568 (company-install-map))
1570 (defvar company--begin-inhibit-commands '(company-abort
1571 company-complete-mouse
1573 company-complete-common
1574 company-complete-selection
1575 company-complete-number)
1576 "List of commands after which idle completion is (still) disabled when
1577 `company-begin-commands' is t.")
1579 (defun company--should-begin ()
1580 (if (eq t company-begin-commands)
1581 (not (memq this-command company--begin-inhibit-commands))
1583 (memq this-command company-begin-commands)
1584 (and (symbolp this-command) (get this-command 'company-begin)))))
1586 ;;; search ;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;
1588 (defvar-local company-search-string "")
1590 (defvar company-search-lighter '(" "
1591 (company-search-filtering "Filter" "Search")
1593 company-search-string
1596 (defvar-local company-search-filtering nil
1597 "Non-nil to filter the completion candidates by the search string")
1599 (defvar-local company--search-old-selection 0)
1601 (defvar-local company--search-old-changed nil)
1603 (defun company--search (text lines)
1604 (let ((quoted (regexp-quote text))
1606 (cl-dolist (line lines)
1607 (when (string-match quoted line (length company-prefix))
1611 (defun company-search-keypad ()
1613 (let* ((name (symbol-name last-command-event))
1614 (last-command-event (aref name (1- (length name)))))
1615 (company-search-printing-char)))
1617 (defun company-search-printing-char ()
1619 (company--search-assert-enabled)
1620 (let ((ss (concat company-search-string (string last-command-event))))
1621 (when company-search-filtering
1622 (company--search-update-predicate ss))
1623 (company--search-update-string ss)))
1625 (defun company--search-update-predicate (&optional ss)
1626 (let* ((company-candidates-predicate
1627 (and (not (string= ss ""))
1628 company-search-filtering
1629 (lambda (candidate) (string-match ss candidate))))
1630 (cc (company-calculate-candidates company-prefix)))
1631 (unless cc (error "No match"))
1632 (company-update-candidates cc)))
1634 (defun company--search-update-string (new)
1635 (let* ((pos (company--search new (nthcdr company-selection company-candidates))))
1638 (setq company-search-string new)
1639 (company-set-selection (+ company-selection pos) t))))
1641 (defun company--search-assert-input ()
1642 (company--search-assert-enabled)
1643 (when (string= company-search-string "")
1644 (error "Empty search string")))
1646 (defun company-search-repeat-forward ()
1647 "Repeat the incremental search in completion candidates forward."
1649 (company--search-assert-input)
1650 (let ((pos (company--search company-search-string
1651 (cdr (nthcdr company-selection
1652 company-candidates)))))
1655 (company-set-selection (+ company-selection pos 1) t))))
1657 (defun company-search-repeat-backward ()
1658 "Repeat the incremental search in completion candidates backwards."
1660 (company--search-assert-input)
1661 (let ((pos (company--search company-search-string
1662 (nthcdr (- company-candidates-length
1664 (reverse company-candidates)))))
1667 (company-set-selection (- company-selection pos 1) t))))
1669 (defun company-search-toggle-filtering ()
1670 "Toggle `company-search-filtering'."
1672 (company--search-assert-enabled)
1673 (setq company-search-filtering (not company-search-filtering))
1674 (let ((ss company-search-string))
1675 (company--search-update-predicate ss)
1676 (company--search-update-string ss)))
1678 (defun company-search-abort ()
1679 "Abort searching the completion candidates."
1681 (company--search-assert-enabled)
1682 (company-search-mode 0)
1683 (company-set-selection company--search-old-selection t)
1684 (setq company-selection-changed company--search-old-changed))
1686 (defun company-search-other-char ()
1688 (company--search-assert-enabled)
1689 (company-search-mode 0)
1690 (company--unread-last-input))
1692 (defun company-search-delete-char ()
1694 (company--search-assert-enabled)
1695 (if (string= company-search-string "")
1697 (let ((ss (substring company-search-string 0 -1)))
1698 (when company-search-filtering
1699 (company--search-update-predicate ss))
1700 (company--search-update-string ss))))
1702 (defvar company-search-map
1704 (keymap (make-keymap)))
1705 (if (fboundp 'max-char)
1706 (set-char-table-range (nth 1 keymap) (cons #x100 (max-char))
1707 'company-search-printing-char)
1709 ;; obsolete in Emacs 23
1710 (let ((l (generic-character-list))
1711 (table (nth 1 keymap)))
1713 (set-char-table-default table (car l) 'company-search-printing-char)
1714 (setq l (cdr l))))))
1715 (define-key keymap [t] 'company-search-other-char)
1717 (define-key keymap (make-string 1 i) 'company-search-other-char)
1720 (define-key keymap (vector i) 'company-search-printing-char)
1723 (define-key keymap (read (format "[kp-%s]" i)) 'company-search-keypad))
1724 (let ((meta-map (make-sparse-keymap)))
1725 (define-key keymap (char-to-string meta-prefix-char) meta-map)
1726 (define-key keymap [escape] meta-map))
1727 (define-key keymap (vector meta-prefix-char t) 'company-search-other-char)
1728 (define-key keymap (kbd "M-n") 'company-select-next)
1729 (define-key keymap (kbd "M-p") 'company-select-previous)
1730 (define-key keymap (kbd "<down>") 'company-select-next-or-abort)
1731 (define-key keymap (kbd "<up>") 'company-select-previous-or-abort)
1732 (define-key keymap "\e\e\e" 'company-search-other-char)
1733 (define-key keymap [escape escape escape] 'company-search-other-char)
1734 (define-key keymap (kbd "DEL") 'company-search-delete-char)
1735 (define-key keymap [backspace] 'company-search-delete-char)
1736 (define-key keymap "\C-g" 'company-search-abort)
1737 (define-key keymap "\C-s" 'company-search-repeat-forward)
1738 (define-key keymap "\C-r" 'company-search-repeat-backward)
1739 (define-key keymap "\C-o" 'company-search-toggle-filtering)
1741 (define-key keymap (read-kbd-macro (format "M-%d" i)) 'company-complete-number))
1743 "Keymap used for incrementally searching the completion candidates.")
1745 (define-minor-mode company-search-mode
1746 "Search mode for completion candidates.
1747 Don't start this directly, use `company-search-candidates' or
1748 `company-filter-candidates'."
1749 nil company-search-lighter nil
1750 (if company-search-mode
1751 (if (company-manual-begin)
1753 (setq company--search-old-selection company-selection
1754 company--search-old-changed company-selection-changed)
1755 (company-call-frontends 'update)
1756 (company-enable-overriding-keymap company-search-map))
1757 (setq company-search-mode nil))
1758 (kill-local-variable 'company-search-string)
1759 (kill-local-variable 'company-search-filtering)
1760 (kill-local-variable 'company--search-old-selection)
1761 (kill-local-variable 'company--search-old-changed)
1762 (when company-backend
1763 (company--search-update-predicate "")
1764 (company-call-frontends 'update))
1765 (company-enable-overriding-keymap company-active-map)))
1767 (defun company--search-assert-enabled ()
1768 (company-assert-enabled)
1769 (unless company-search-mode
1770 (company-uninstall-map)
1771 (error "Company not in search mode")))
1773 (defun company-search-candidates ()
1774 "Start searching the completion candidates incrementally.
1776 \\<company-search-map>Search can be controlled with the commands:
1777 - `company-search-repeat-forward' (\\[company-search-repeat-forward])
1778 - `company-search-repeat-backward' (\\[company-search-repeat-backward])
1779 - `company-search-abort' (\\[company-search-abort])
1780 - `company-search-delete-char' (\\[company-search-delete-char])
1782 Regular characters are appended to the search string.
1784 The command `company-search-toggle-filtering' (\\[company-search-toggle-filtering])
1785 uses the search string to filter the completion candidates."
1787 (company-search-mode 1))
1789 (defvar company-filter-map
1790 (let ((keymap (make-keymap)))
1791 (define-key keymap [remap company-search-printing-char]
1792 'company-filter-printing-char)
1793 (set-keymap-parent keymap company-search-map)
1795 "Keymap used for incrementally searching the completion candidates.")
1797 (defun company-filter-candidates ()
1798 "Start filtering the completion candidates incrementally.
1799 This works the same way as `company-search-candidates' immediately
1800 followed by `company-search-toggle-filtering'."
1802 (company-search-mode 1)
1803 (setq company-search-filtering t))
1805 ;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;
1807 (defun company-select-next (&optional arg)
1808 "Select the next candidate in the list.
1810 With ARG, move by that many elements."
1812 (when (company-manual-begin)
1813 (company-set-selection (+ (or arg 1) company-selection))))
1815 (defun company-select-previous (&optional arg)
1816 "Select the previous candidate in the list.
1818 With ARG, move by that many elements."
1820 (company-select-next (if arg (- arg) -1)))
1822 (defun company-select-next-or-abort (&optional arg)
1823 "Select the next candidate if more than one, else abort
1824 and invoke the normal binding.
1826 With ARG, move by that many elements."
1828 (if (> company-candidates-length 1)
1829 (company-select-next arg)
1831 (company--unread-last-input)))
1833 (defun company-select-previous-or-abort (&optional arg)
1834 "Select the previous candidate if more than one, else abort
1835 and invoke the normal binding.
1837 With ARG, move by that many elements."
1839 (if (> company-candidates-length 1)
1840 (company-select-previous arg)
1842 (company--unread-last-input)))
1844 (defun company-next-page ()
1845 "Select the candidate one page further."
1847 (when (company-manual-begin)
1848 (company-set-selection (+ company-selection
1849 company-tooltip-limit))))
1851 (defun company-previous-page ()
1852 "Select the candidate one page earlier."
1854 (when (company-manual-begin)
1855 (company-set-selection (- company-selection
1856 company-tooltip-limit))))
1858 (defvar company-pseudo-tooltip-overlay)
1860 (defvar company-tooltip-offset)
1862 (defun company--inside-tooltip-p (event-col-row row height)
1863 (let* ((ovl company-pseudo-tooltip-overlay)
1864 (column (overlay-get ovl 'company-column))
1865 (width (overlay-get ovl 'company-width))
1866 (evt-col (car event-col-row))
1867 (evt-row (cdr event-col-row)))
1868 (and (>= evt-col column)
1869 (< evt-col (+ column width))
1871 (and (> evt-row row)
1872 (<= evt-row (+ row height) ))
1873 (and (< evt-row row)
1874 (>= evt-row (+ row height)))))))
1876 (defun company--event-col-row (event)
1877 (company--posn-col-row (event-start event)))
1879 (defun company-select-mouse (event)
1880 "Select the candidate picked by the mouse."
1882 (let ((event-col-row (company--event-col-row event))
1883 (ovl-row (company--row))
1884 (ovl-height (and company-pseudo-tooltip-overlay
1885 (min (overlay-get company-pseudo-tooltip-overlay
1887 company-candidates-length))))
1889 (company--inside-tooltip-p event-col-row ovl-row ovl-height))
1891 (company-set-selection (+ (cdr event-col-row)
1892 (1- company-tooltip-offset)
1893 (if (and (eq company-tooltip-offset-display 'lines)
1894 (not (zerop company-tooltip-offset)))
1897 (if (< ovl-height 0)
1902 (company--unread-last-input)
1905 (defun company-complete-mouse (event)
1906 "Insert the candidate picked by the mouse."
1908 (when (company-select-mouse event)
1909 (company-complete-selection)))
1911 (defun company-complete-selection ()
1912 "Insert the selected candidate."
1914 (when (company-manual-begin)
1915 (let ((result (nth company-selection company-candidates)))
1916 (company-finish result))))
1918 (defun company-complete-common ()
1919 "Insert the common part of all candidates."
1921 (when (company-manual-begin)
1922 (if (and (not (cdr company-candidates))
1923 (equal company-common (car company-candidates)))
1924 (company-complete-selection)
1925 (when company-common
1926 (company--insert-candidate company-common)))))
1928 (defun company-complete-common-or-cycle (&optional arg)
1929 "Insert the common part of all candidates, or select the next one.
1931 With ARG, move by that many elements."
1933 (when (company-manual-begin)
1934 (let ((tick (buffer-chars-modified-tick)))
1935 (call-interactively 'company-complete-common)
1936 (when (eq tick (buffer-chars-modified-tick))
1937 (let ((company-selection-wrap-around t)
1938 (current-prefix-arg arg))
1939 (call-interactively 'company-select-next))))))
1941 (defun company-complete ()
1942 "Insert the common part of all candidates or the current selection.
1943 The first time this is called, the common part is inserted, the second
1944 time, or when the selection has been changed, the selected candidate is
1947 (when (company-manual-begin)
1948 (if (or company-selection-changed
1949 (eq last-command 'company-complete-common))
1950 (call-interactively 'company-complete-selection)
1951 (call-interactively 'company-complete-common)
1952 (setq this-command 'company-complete-common))))
1954 (defun company-complete-number (n)
1955 "Insert the Nth candidate visible in the tooltip.
1956 To show the number next to the candidates in some back-ends, enable
1957 `company-show-numbers'. When called interactively, uses the last typed
1958 character, stripping the modifiers. That character must be a digit."
1960 (list (let* ((type (event-basic-type last-command-event))
1961 (char (if (characterp type)
1962 ;; Number on the main row.
1964 ;; Keypad number, if bound directly.
1965 (car (last (string-to-list (symbol-name type))))))
1967 (if (zerop n) 10 n))))
1968 (when (company-manual-begin)
1969 (and (or (< n 1) (> n (- company-candidates-length
1970 company-tooltip-offset)))
1971 (error "No candidate number %d" n))
1973 (company-finish (nth (+ n company-tooltip-offset)
1974 company-candidates))))
1976 ;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;
1978 (defconst company-space-strings-limit 100)
1980 (defconst company-space-strings
1982 (dotimes (i company-space-strings-limit)
1983 (push (make-string (- company-space-strings-limit 1 i) ?\ ) lst))
1984 (apply 'vector lst)))
1986 (defun company-space-string (len)
1987 (if (< len company-space-strings-limit)
1988 (aref company-space-strings len)
1989 (make-string len ?\ )))
1991 (defun company-safe-substring (str from &optional to)
1992 (if (> from (string-width str))
1996 (move-to-column from)
1997 (let ((beg (point)))
2001 (concat (buffer-substring beg (point))
2002 (let ((padding (- to (current-column))))
2004 (company-space-string padding)))))
2005 (buffer-substring beg (point-max)))))))
2007 ;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;
2009 (defvar-local company-last-metadata nil)
2011 (defun company-fetch-metadata ()
2012 (let ((selected (nth company-selection company-candidates)))
2013 (unless (eq selected (car company-last-metadata))
2014 (setq company-last-metadata
2015 (cons selected (company-call-backend 'meta selected))))
2016 (cdr company-last-metadata)))
2018 (defun company-doc-buffer (&optional string)
2019 (with-current-buffer (get-buffer-create "*company-documentation*")
2026 (defvar company--electric-commands
2027 '(scroll-other-window scroll-other-window-down mwheel-scroll)
2028 "List of Commands that won't break out of electric commands.")
2030 (defmacro company--electric-do (&rest body)
2031 (declare (indent 0) (debug t))
2032 `(when (company-manual-begin)
2033 (save-window-excursion
2034 (let ((height (window-height))
2035 (row (company--row))
2038 (and (< (window-height) height)
2039 (< (- (window-height) row 2) company-tooltip-limit)
2040 (recenter (- (window-height) row 2)))
2041 (while (memq (setq cmd (key-binding (read-key-sequence-vector nil)))
2042 company--electric-commands)
2044 (call-interactively cmd)
2045 ((beginning-of-buffer end-of-buffer)
2046 (message (error-message-string err)))))
2047 (company--unread-last-input)))))
2049 (defun company--unread-last-input ()
2050 (when last-input-event
2051 (clear-this-command-keys t)
2052 (setq unread-command-events (list last-input-event))))
2054 (defun company-show-doc-buffer ()
2055 "Temporarily show the documentation buffer for the selection."
2057 (let (other-window-scroll-buffer)
2058 (company--electric-do
2059 (let* ((selected (nth company-selection company-candidates))
2060 (doc-buffer (or (company-call-backend 'doc-buffer selected)
2061 (error "No documentation available"))))
2062 (setq other-window-scroll-buffer (get-buffer doc-buffer))
2063 (with-current-buffer doc-buffer
2064 (goto-char (point-min)))
2065 (display-buffer doc-buffer t)))))
2066 (put 'company-show-doc-buffer 'company-keep t)
2068 (defun company-show-location ()
2069 "Temporarily display a buffer showing the selected candidate in context."
2071 (let (other-window-scroll-buffer)
2072 (company--electric-do
2073 (let* ((selected (nth company-selection company-candidates))
2074 (location (company-call-backend 'location selected))
2075 (pos (or (cdr location) (error "No location available")))
2076 (buffer (or (and (bufferp (car location)) (car location))
2077 (find-file-noselect (car location) t))))
2078 (setq other-window-scroll-buffer (get-buffer buffer))
2079 (with-selected-window (display-buffer buffer t)
2082 (if (bufferp (car location))
2084 (goto-char (point-min))
2085 (forward-line (1- pos))))
2086 (set-window-start nil (point)))))))
2087 (put 'company-show-location 'company-keep t)
2089 ;;; package functions ;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;
2091 (defvar-local company-callback nil)
2093 (defun company-remove-callback (&optional ignored)
2094 (remove-hook 'company-completion-finished-hook company-callback t)
2095 (remove-hook 'company-completion-cancelled-hook 'company-remove-callback t)
2096 (remove-hook 'company-completion-finished-hook 'company-remove-callback t))
2098 (defun company-begin-backend (backend &optional callback)
2099 "Start a completion at point using BACKEND."
2100 (interactive (let ((val (completing-read "Company back-end: "
2102 'functionp nil "company-")))
2104 (list (intern val)))))
2105 (when (setq company-callback callback)
2106 (add-hook 'company-completion-finished-hook company-callback nil t))
2107 (add-hook 'company-completion-cancelled-hook 'company-remove-callback nil t)
2108 (add-hook 'company-completion-finished-hook 'company-remove-callback nil t)
2109 (setq company-backend backend)
2110 ;; Return non-nil if active.
2111 (or (company-manual-begin)
2112 (error "Cannot complete at point")))
2114 (defun company-begin-with (candidates
2115 &optional prefix-length require-match callback)
2116 "Start a completion at point.
2117 CANDIDATES is the list of candidates to use and PREFIX-LENGTH is the length
2118 of the prefix that already is in the buffer before point.
2121 CALLBACK is a function called with the selected result if the user
2122 successfully completes the input.
2124 Example: \(company-begin-with '\(\"foo\" \"foobar\" \"foobarbaz\"\)\)"
2125 (let ((begin-marker (copy-marker (point) t)))
2126 (company-begin-backend
2127 (lambda (command &optional arg &rest ignored)
2130 (when (equal (point) (marker-position begin-marker))
2131 (buffer-substring (- (point) (or prefix-length 0)) (point))))
2133 (all-completions arg candidates))
2138 (defun company-version (&optional show-version)
2139 "Get the Company version as string.
2141 If SHOW-VERSION is non-nil, show the version in the echo area."
2142 (interactive (list t))
2144 (insert-file-contents (find-library-name "company"))
2147 (message "Company version: %s" (lm-version))
2150 (defun company-diag ()
2152 "Pop a buffer with information about completions at point."
2153 (let* ((bb company-backends)
2155 (prefix (cl-loop for b in bb
2156 thereis (let ((company-backend b))
2158 (company-call-backend 'prefix))))
2160 (when (stringp prefix)
2161 (let ((company-backend backend))
2162 (setq cc (company-call-backend 'candidates prefix)
2165 (lambda (c) (cons c (company-call-backend 'annotation c)))
2167 (pop-to-buffer (get-buffer-create "*company-diag*"))
2168 (setq buffer-read-only nil)
2170 (insert (format "Emacs %s (%s) of %s on %s"
2171 emacs-version system-configuration
2172 (format-time-string "%Y-%m-%d" emacs-build-time)
2173 emacs-build-system))
2174 (insert "\nCompany " (company-version) "\n\n")
2175 (insert "company-backends: " (pp-to-string bb))
2177 (insert "Used backend: " (pp-to-string backend))
2179 (insert "Prefix: " (pp-to-string prefix))
2181 (insert (message "Completions:"))
2182 (unless cc (insert " none"))
2184 (dolist (c annotations)
2185 (insert "\n " (prin1-to-string (car c)))
2187 (insert " " (prin1-to-string (cdr c))))))
2190 ;;; pseudo-tooltip ;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;
2192 (defvar-local company-pseudo-tooltip-overlay nil)
2194 (defvar-local company-tooltip-offset 0)
2196 (defun company-tooltip--lines-update-offset (selection num-lines limit)
2198 (setq company-tooltip-offset
2199 (max (min selection company-tooltip-offset)
2200 (- selection -1 limit)))
2202 (when (<= company-tooltip-offset 1)
2204 (setq company-tooltip-offset 0))
2206 (when (>= company-tooltip-offset (- num-lines limit 1))
2208 (when (= selection (1- num-lines))
2209 (cl-decf company-tooltip-offset)
2210 (when (<= company-tooltip-offset 1)
2211 (setq company-tooltip-offset 0)
2216 (defun company-tooltip--simple-update-offset (selection _num-lines limit)
2217 (setq company-tooltip-offset
2218 (if (< selection company-tooltip-offset)
2220 (max company-tooltip-offset
2221 (- selection limit -1)))))
2225 (defsubst company-round-tab (arg)
2226 (* (/ (+ arg tab-width) tab-width) tab-width))
2228 (defun company-plainify (str)
2229 (let ((prefix (get-text-property 0 'line-prefix str)))
2230 (when prefix ; Keep the original value unmodified, for no special reason.
2231 (setq str (concat prefix str))
2232 (remove-text-properties 0 (length str) '(line-prefix) str)))
2233 (let* ((pieces (split-string str "\t"))
2236 (setcar copy (company-safe-substring
2237 (car copy) 0 (company-round-tab (string-width (car copy)))))
2239 (apply 'concat pieces)))
2241 (defun company-fill-propertize (value annotation width selected left right)
2242 (let* ((margin (length left))
2243 (common (or (company-call-backend 'match value)
2245 (string-width company-common)
2247 (ann-ralign company-tooltip-align-annotations)
2248 (ann-truncate (< width
2249 (+ (length value) (length annotation)
2250 (if ann-ralign 1 0))))
2251 (ann-start (+ margin
2255 (- width (length annotation)))
2257 (ann-end (min (+ ann-start (length annotation)) (+ margin width)))
2259 (if (or ann-truncate (not ann-ralign))
2260 (company-safe-substring
2262 (when (and annotation ann-ralign) " ")
2266 (company-safe-substring value 0
2267 (- width (length annotation)))
2270 (setq common (+ (min common width) margin))
2271 (setq width (+ width margin (length right)))
2273 (add-text-properties 0 width '(face company-tooltip
2274 mouse-face company-tooltip-mouse)
2276 (add-text-properties margin common
2277 '(face company-tooltip-common
2278 mouse-face company-tooltip-mouse)
2280 (when (< ann-start ann-end)
2281 (add-text-properties ann-start ann-end
2282 '(face company-tooltip-annotation
2283 mouse-face company-tooltip-mouse)
2286 (if (and (not (string= company-search-string ""))
2287 (string-match (regexp-quote company-search-string) value
2288 (length company-prefix)))
2289 (let ((beg (+ margin (match-beginning 0)))
2290 (end (+ margin (match-end 0)))
2291 (width (- width (length right))))
2293 (add-text-properties beg (min end width)
2294 '(face company-tooltip-search)
2296 (add-text-properties 0 width '(face company-tooltip-selection
2297 mouse-face company-tooltip-selection)
2299 (add-text-properties margin common
2300 '(face company-tooltip-common-selection
2301 mouse-face company-tooltip-selection)
2305 (defun company--clean-string (str)
2306 (replace-regexp-in-string
2307 "\\([^[:graph:] ]\\)\\|\\(\ufeff\\)\\|[[:multibyte:]]"
2310 ((match-beginning 1)
2311 ;; FIXME: Better char for 'non-printable'?
2312 ;; We shouldn't get any of these, but sometimes we might.
2314 ((match-beginning 2)
2315 ;; Zero-width non-breakable space.
2317 ((> (string-width match) 1)
2319 (make-string (1- (string-width match)) ?\ufeff)
2326 (defun company-buffer-lines (beg end)
2328 (let (lines lines-moved)
2329 (while (and (not (eobp)) ; http://debbugs.gnu.org/19553
2330 (> (setq lines-moved (vertical-motion 1)) 0)
2332 (let ((bound (min end (1- (point)))))
2333 ;; A visual line can contain several physical lines (e.g. with outline's
2334 ;; folding overlay). Take only the first one.
2335 (push (buffer-substring beg
2338 (re-search-forward "$" bound 'move)
2341 ;; One physical line can be displayed as several visual ones as well:
2342 ;; add empty strings to the list, to even the count.
2343 (dotimes (_ (1- lines-moved))
2346 (unless (eq beg end)
2347 (push (buffer-substring beg end) lines))
2350 (defun company-modify-line (old new offset)
2351 (concat (company-safe-substring old 0 offset)
2353 (company-safe-substring old (+ offset (length new)))))
2355 (defsubst company--length-limit (lst limit)
2356 (if (nthcdr limit lst)
2360 (defsubst company--window-height ()
2361 (if (fboundp 'window-screen-lines)
2362 (floor (window-screen-lines))
2363 (window-body-height)))
2365 (defun company--window-width ()
2366 (let ((ww (window-body-width)))
2367 ;; Account for the line continuation column.
2368 (when (zerop (cadr (window-fringes)))
2370 (unless (or (display-graphic-p)
2371 (version< "24.3.1" emacs-version))
2372 ;; Emacs 24.3 and earlier included margins
2373 ;; in window-width when in TTY.
2375 (let ((margins (window-margins)))
2376 (+ (or (car margins) 0)
2377 (or (cdr margins) 0)))))
2378 (when (and word-wrap
2379 (version< emacs-version "24.4.51.5"))
2380 ;; http://debbugs.gnu.org/18384
2384 (defun company--replacement-string (lines old column nl &optional align-top)
2385 (cl-decf column company-tooltip-margin)
2387 (when (and align-top company-tooltip-flip-when-above)
2388 (setq lines (reverse lines)))
2390 (let ((width (length (car lines)))
2391 (remaining-cols (- (+ (company--window-width) (window-hscroll))
2393 (when (> width remaining-cols)
2394 (cl-decf column (- width remaining-cols))))
2396 (let ((offset (and (< column 0) (- column)))
2401 ;; untouched lines first
2402 (dotimes (_ (- (length old) (length lines)))
2403 (push (pop old) new)))
2404 ;; length into old lines.
2406 (push (company-modify-line (pop old)
2407 (company--offset-line (pop lines) offset)
2410 ;; Append whole new lines.
2412 (push (concat (company-space-string column)
2413 (company--offset-line (pop lines) offset))
2416 (let ((str (concat (when nl " ")
2418 (mapconcat 'identity (nreverse new) "\n")
2420 (font-lock-append-text-property 0 (length str) 'face 'default str)
2421 (when nl (put-text-property 0 1 'cursor t str))
2424 (defun company--offset-line (line offset)
2425 (if (and offset line)
2426 (substring line offset)
2429 (defun company--create-lines (selection limit)
2430 (let ((len company-candidates-length)
2431 (window-width (company--window-width))
2440 ;; Maybe clear old offset.
2441 (when (< len (+ company-tooltip-offset limit))
2442 (setq company-tooltip-offset 0))
2444 ;; Scroll to offset.
2445 (if (eq company-tooltip-offset-display 'lines)
2446 (setq limit (company-tooltip--lines-update-offset selection len limit))
2447 (company-tooltip--simple-update-offset selection len limit))
2450 ((eq company-tooltip-offset-display 'scrollbar)
2451 (setq scrollbar-bounds (company--scrollbar-bounds company-tooltip-offset
2453 ((eq company-tooltip-offset-display 'lines)
2454 (when (> company-tooltip-offset 0)
2455 (setq previous (format "...(%d)" company-tooltip-offset)))
2456 (setq remainder (- len limit company-tooltip-offset)
2457 remainder (when (> remainder 0)
2458 (setq remainder (format "...(%d)" remainder))))))
2460 (cl-decf selection company-tooltip-offset)
2461 (setq width (max (length previous) (length remainder))
2462 lines (nthcdr company-tooltip-offset company-candidates)
2466 (cl-decf window-width (* 2 company-tooltip-margin))
2467 (when scrollbar-bounds (cl-decf window-width))
2470 (let* ((value (pop lines-copy))
2471 (annotation (company-call-backend 'annotation value)))
2472 (setq value (company--clean-string (company-reformat value)))
2474 (when company-tooltip-align-annotations
2475 ;; `lisp-completion-at-point' adds a space.
2476 (setq annotation (comment-string-strip annotation t nil)))
2477 (setq annotation (company--clean-string annotation)))
2478 (push (cons value annotation) items)
2479 (setq width (max (+ (length value)
2480 (if (and annotation company-tooltip-align-annotations)
2481 (1+ (length annotation))
2482 (length annotation)))
2485 (setq width (min window-width
2486 (max company-tooltip-minimum-width
2487 (if company-show-numbers
2491 (let ((items (nreverse items))
2492 (numbered (if company-show-numbers 0 99999))
2495 (push (company--scrollpos-line previous width) new))
2498 (let* ((item (pop items))
2500 (annotation (cdr item))
2501 (right (company-space-string company-tooltip-margin))
2503 (when (< numbered 10)
2506 (setq right (concat (format " %d" (mod numbered 10)) right)))
2508 (company-fill-propertize str annotation
2509 width (equal i selection)
2510 (company-space-string
2511 company-tooltip-margin)
2513 (when scrollbar-bounds
2514 (company--scrollbar i scrollbar-bounds)))
2518 (push (company--scrollpos-line remainder width) new))
2522 (defun company--scrollbar-bounds (offset limit length)
2523 (when (> length limit)
2524 (let* ((size (ceiling (* limit (float limit)) length))
2525 (lower (floor (* limit (float offset)) length))
2526 (upper (+ lower size -1)))
2527 (cons lower upper))))
2529 (defun company--scrollbar (i bounds)
2530 (propertize " " 'face
2531 (if (and (>= i (car bounds)) (<= i (cdr bounds)))
2532 'company-scrollbar-fg
2533 'company-scrollbar-bg)))
2535 (defun company--scrollpos-line (text width)
2536 (propertize (concat (company-space-string company-tooltip-margin)
2537 (company-safe-substring text 0 width)
2538 (company-space-string company-tooltip-margin))
2539 'face 'company-tooltip))
2543 (defun company--pseudo-tooltip-height ()
2544 "Calculate the appropriate tooltip height.
2545 Returns a negative number if the tooltip should be displayed above point."
2546 (let* ((lines (company--row))
2547 (below (- (company--window-height) 1 lines)))
2548 (if (and (< below (min company-tooltip-minimum company-candidates-length))
2550 (- (max 3 (min company-tooltip-limit lines)))
2551 (max 3 (min company-tooltip-limit below)))))
2553 (defun company-pseudo-tooltip-show (row column selection)
2554 (company-pseudo-tooltip-hide)
2557 (let* ((height (company--pseudo-tooltip-height))
2561 (setq row (+ row height -1)
2564 (let* ((nl (< (move-to-window-line row) row))
2566 (end (save-excursion
2567 (move-to-window-line (+ row (abs height)))
2569 (ov (make-overlay (if nl beg (1- beg)) end nil t))
2570 (args (list (mapcar 'company-plainify
2571 (company-buffer-lines beg end))
2574 (setq company-pseudo-tooltip-overlay ov)
2575 (overlay-put ov 'company-replacement-args args)
2577 (let ((lines (company--create-lines selection (abs height))))
2578 (overlay-put ov 'company-display
2579 (apply 'company--replacement-string lines args))
2580 (overlay-put ov 'company-width (string-width (car lines))))
2582 (overlay-put ov 'company-column column)
2583 (overlay-put ov 'company-height height)))))
2585 (defun company-pseudo-tooltip-show-at-point (pos column-offset)
2586 (let* ((col-row (company--col-row pos))
2587 (col (- (car col-row) column-offset)))
2588 (when (< col 0) (setq col 0))
2589 (company-pseudo-tooltip-show (1+ (cdr col-row)) col company-selection)))
2591 (defun company-pseudo-tooltip-edit (selection)
2592 (let* ((height (overlay-get company-pseudo-tooltip-overlay 'company-height))
2593 (lines (company--create-lines selection (abs height))))
2594 (overlay-put company-pseudo-tooltip-overlay 'company-width
2595 (string-width (car lines)))
2596 (overlay-put company-pseudo-tooltip-overlay 'company-display
2597 (apply 'company--replacement-string
2599 (overlay-get company-pseudo-tooltip-overlay
2600 'company-replacement-args)))))
2602 (defun company-pseudo-tooltip-hide ()
2603 (when company-pseudo-tooltip-overlay
2604 (delete-overlay company-pseudo-tooltip-overlay)
2605 (setq company-pseudo-tooltip-overlay nil)))
2607 (defun company-pseudo-tooltip-hide-temporarily ()
2608 (when (overlayp company-pseudo-tooltip-overlay)
2609 (overlay-put company-pseudo-tooltip-overlay 'invisible nil)
2610 (overlay-put company-pseudo-tooltip-overlay 'after-string nil)))
2612 (defun company-pseudo-tooltip-unhide ()
2613 (when company-pseudo-tooltip-overlay
2614 (let* ((ov company-pseudo-tooltip-overlay)
2615 (disp (overlay-get ov 'company-display)))
2616 ;; Beat outline's folding overlays, at least.
2617 (overlay-put ov 'priority 1)
2618 ;; `display' could be better (http://debbugs.gnu.org/18285), but it
2619 ;; doesn't work when the overlay is empty, which is what happens at eob.
2620 ;; It also seems to interact badly with `cursor'.
2621 ;; We deal with priorities by having the overlay start before the newline.
2622 (overlay-put ov 'after-string disp)
2623 (overlay-put ov 'invisible t)
2624 (overlay-put ov 'window (selected-window)))))
2626 (defun company-pseudo-tooltip-guard ()
2628 (save-excursion (beginning-of-visual-line))
2629 (let ((ov company-pseudo-tooltip-overlay)
2630 (overhang (save-excursion (end-of-visual-line)
2631 (- (line-end-position) (point)))))
2632 (when (>= (overlay-get ov 'company-height) 0)
2634 (buffer-substring-no-properties (point) (overlay-start ov))
2635 (when (>= overhang 0) overhang))))))
2637 (defun company-pseudo-tooltip-frontend (command)
2638 "`company-mode' front-end similar to a tooltip but based on overlays."
2640 (pre-command (company-pseudo-tooltip-hide-temporarily))
2642 (unless (when (overlayp company-pseudo-tooltip-overlay)
2643 (let* ((ov company-pseudo-tooltip-overlay)
2644 (old-height (overlay-get ov 'company-height))
2645 (new-height (company--pseudo-tooltip-height)))
2647 (>= (* old-height new-height) 0)
2648 (>= (abs old-height) (abs new-height))
2649 (equal (company-pseudo-tooltip-guard)
2650 (overlay-get ov 'company-guard)))))
2652 (company-pseudo-tooltip-show-at-point (point) (length company-prefix))
2653 (overlay-put company-pseudo-tooltip-overlay
2654 'company-guard (company-pseudo-tooltip-guard)))
2655 (company-pseudo-tooltip-unhide))
2656 (hide (company-pseudo-tooltip-hide)
2657 (setq company-tooltip-offset 0))
2658 (update (when (overlayp company-pseudo-tooltip-overlay)
2659 (company-pseudo-tooltip-edit company-selection)))))
2661 (defun company-pseudo-tooltip-unless-just-one-frontend (command)
2662 "`company-pseudo-tooltip-frontend', but not shown for single candidates."
2663 (unless (and (eq command 'post-command)
2664 (company--show-inline-p))
2665 (company-pseudo-tooltip-frontend command)))
2667 ;;; overlay ;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;
2669 (defvar-local company-preview-overlay nil)
2671 (defun company-preview-show-at-point (pos)
2672 (company-preview-hide)
2674 (let ((completion (nth company-selection company-candidates)))
2675 (setq completion (propertize completion 'face 'company-preview))
2676 (add-text-properties 0 (length company-common)
2677 '(face company-preview-common) completion)
2679 ;; Add search string
2680 (and company-search-string
2681 (string-match (regexp-quote company-search-string) completion)
2682 (add-text-properties (match-beginning 0)
2684 '(face company-preview-search)
2687 (setq completion (company-strip-prefix completion))
2689 (and (equal pos (point))
2690 (not (equal completion ""))
2691 (add-text-properties 0 1 '(cursor 1) completion))
2694 (pto company-pseudo-tooltip-overlay)
2695 (ptf-workaround (and
2698 (eq pos (overlay-start pto)))))
2699 ;; Try to accomodate for the pseudo-tooltip overlay,
2700 ;; which may start at the same position if it's at eol.
2701 (when ptf-workaround
2703 (setq completion (concat (buffer-substring beg pos) completion)))
2705 (setq company-preview-overlay (make-overlay beg pos))
2707 (let ((ov company-preview-overlay))
2708 (overlay-put ov (if ptf-workaround 'display 'after-string)
2710 (overlay-put ov 'window (selected-window))))))
2712 (defun company-preview-hide ()
2713 (when company-preview-overlay
2714 (delete-overlay company-preview-overlay)
2715 (setq company-preview-overlay nil)))
2717 (defun company-preview-frontend (command)
2718 "`company-mode' front-end showing the selection as if it had been inserted."
2720 (`pre-command (company-preview-hide))
2721 (`post-command (company-preview-show-at-point (point)))
2722 (`hide (company-preview-hide))))
2724 (defun company-preview-if-just-one-frontend (command)
2725 "`company-preview-frontend', but only shown for single candidates."
2726 (when (or (not (eq command 'post-command))
2727 (company--show-inline-p))
2728 (company-preview-frontend command)))
2730 (defun company--show-inline-p ()
2731 (and (not (cdr company-candidates))
2733 (or (eq (company-call-backend 'ignore-case) 'keep-prefix)
2734 (string-prefix-p company-prefix company-common))))
2736 ;;; echo ;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;
2738 (defvar-local company-echo-last-msg nil)
2740 (defvar company-echo-timer nil)
2742 (defvar company-echo-delay .01)
2744 (defun company-echo-show (&optional getter)
2746 (setq company-echo-last-msg (funcall getter)))
2747 (let ((message-log-max nil))
2748 (if company-echo-last-msg
2749 (message "%s" company-echo-last-msg)
2752 (defun company-echo-show-soon (&optional getter)
2753 (when company-echo-timer
2754 (cancel-timer company-echo-timer))
2755 (setq company-echo-timer (run-with-timer 0 nil 'company-echo-show getter)))
2757 (defsubst company-echo-show-when-idle (&optional getter)
2758 (when (sit-for company-echo-delay)
2759 (company-echo-show getter)))
2761 (defun company-echo-format ()
2763 (let ((limit (window-body-width (minibuffer-window)))
2765 ;; Roll to selection.
2766 (candidates (nthcdr company-selection company-candidates))
2767 (i (if company-show-numbers company-selection 99999))
2771 (setq comp (company-reformat (pop candidates))
2772 len (+ len 1 (length comp)))
2776 (setq comp (propertize (format "%d: %s" i comp)
2777 'face 'company-echo))
2780 (add-text-properties 3 (+ 3 (length company-common))
2781 '(face company-echo-common) comp))
2782 (setq comp (propertize comp 'face 'company-echo))
2783 (add-text-properties 0 (length company-common)
2784 '(face company-echo-common) comp))
2786 (setq candidates nil)
2789 (mapconcat 'identity (nreverse msg) " ")))
2791 (defun company-echo-strip-common-format ()
2793 (let ((limit (window-body-width (minibuffer-window)))
2794 (len (+ (length company-prefix) 2))
2795 ;; Roll to selection.
2796 (candidates (nthcdr company-selection company-candidates))
2797 (i (if company-show-numbers company-selection 99999))
2801 (setq comp (company-strip-prefix (pop candidates))
2802 len (+ len 2 (length comp)))
2805 (setq comp (format "%s (%d)" comp i))
2809 (setq candidates nil)
2810 (push (propertize comp 'face 'company-echo) msg)))
2812 (concat (propertize company-prefix 'face 'company-echo-common) "{"
2813 (mapconcat 'identity (nreverse msg) ", ")
2816 (defun company-echo-hide ()
2817 (unless (equal company-echo-last-msg "")
2818 (setq company-echo-last-msg "")
2819 (company-echo-show)))
2821 (defun company-echo-frontend (command)
2822 "`company-mode' front-end showing the candidates in the echo area."
2824 (`post-command (company-echo-show-soon 'company-echo-format))
2825 (`hide (company-echo-hide))))
2827 (defun company-echo-strip-common-frontend (command)
2828 "`company-mode' front-end showing the candidates in the echo area."
2830 (`post-command (company-echo-show-soon 'company-echo-strip-common-format))
2831 (`hide (company-echo-hide))))
2833 (defun company-echo-metadata-frontend (command)
2834 "`company-mode' front-end showing the documentation in the echo area."
2836 (`post-command (company-echo-show-when-idle 'company-fetch-metadata))
2837 (`hide (company-echo-hide))))
2840 ;;; company.el ends here