1 ;;; company.el --- Modular text completion framework -*- lexical-binding: t -*-
3 ;; Copyright (C) 2009-2014 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.
62 ;; When point is at the very end of the buffer, the pseudo-tooltip appears very
63 ;; wrong, unless company is allowed to temporarily insert a fake newline.
64 ;; This behavior is enabled by `company-end-of-buffer-workaround'.
68 ;; See NEWS.md in the repository.
75 ;; FIXME: Use `user-error'.
76 (add-to-list 'debug-ignored-errors "^.* frontend cannot be used twice$")
77 (add-to-list 'debug-ignored-errors "^Echo area cannot be used twice$")
78 (add-to-list 'debug-ignored-errors "^No \\(document\\|loc\\)ation available$")
79 (add-to-list 'debug-ignored-errors "^Company not ")
80 (add-to-list 'debug-ignored-errors "^No candidate number ")
81 (add-to-list 'debug-ignored-errors "^Cannot complete at point$")
82 (add-to-list 'debug-ignored-errors "^No other back-end$")
86 ;; `defvar-local' for Emacs 24.2 and below
87 (unless (fboundp 'defvar-local)
88 (defmacro defvar-local (var val &optional docstring)
89 "Define VAR as a buffer-local variable with default value VAL.
90 Like `defvar' but additionally marks the variable as being automatically
91 buffer-local wherever it is set."
92 (declare (debug defvar) (doc-string 3))
94 (defvar ,var ,val ,docstring)
95 (make-variable-buffer-local ',var)))))
98 "Extensible inline text completion mechanism"
103 (defface company-tooltip
104 '((default :foreground "black")
105 (((class color) (min-colors 88) (background light))
106 (:background "cornsilk"))
107 (((class color) (min-colors 88) (background dark))
108 (:background "yellow")))
109 "Face used for the tooltip.")
111 (defface company-tooltip-selection
112 '((default :inherit company-tooltip)
113 (((class color) (min-colors 88) (background light))
114 (:background "light blue"))
115 (((class color) (min-colors 88) (background dark))
116 (:background "orange1"))
117 (t (:background "green")))
118 "Face used for the selection in the tooltip.")
120 (defface company-tooltip-mouse
121 '((default :inherit highlight))
122 "Face used for the tooltip item under the mouse.")
124 (defface company-tooltip-common
125 '((default :inherit company-tooltip)
126 (((background light))
127 :foreground "darkred")
130 "Face used for the common completion in the tooltip.")
132 (defface company-tooltip-common-selection
133 '((default :inherit company-tooltip-selection)
134 (((background light))
135 :foreground "darkred")
138 "Face used for the selected common completion in the tooltip.")
140 (defface company-tooltip-annotation
141 '((default :inherit company-tooltip)
142 (((background light))
143 :foreground "firebrick4")
146 "Face used for the annotation in the tooltip.")
148 (defface company-scrollbar-fg
149 '((((background light))
150 :background "darkred")
153 "Face used for the tooltip scrollbar thumb.")
155 (defface company-scrollbar-bg
156 '((default :inherit company-tooltip)
157 (((background light))
161 "Face used for the tooltip scrollbar background.")
163 (defface company-preview
164 '((((background light))
165 :inherit company-tooltip-selection)
168 :foreground "wheat"))
169 "Face used for the completion preview.")
171 (defface company-preview-common
172 '((((background light))
173 :inherit company-tooltip-selection)
175 :inherit company-preview
177 "Face used for the common part of the completion preview.")
179 (defface company-preview-search
180 '((((background light))
181 :inherit company-tooltip-common-selection)
183 :inherit company-preview
184 :background "blue1"))
185 "Face used for the search string in the completion preview.")
187 (defface company-echo nil
188 "Face used for completions in the echo area.")
190 (defface company-echo-common
191 '((((background dark)) (:foreground "firebrick1"))
192 (((background light)) (:background "firebrick4")))
193 "Face used for the common part of completions in the echo area.")
195 (defun company-frontends-set (variable value)
197 (let ((remainder value))
198 (setcdr remainder (delq (car remainder) (cdr remainder))))
199 (and (memq 'company-pseudo-tooltip-unless-just-one-frontend value)
200 (memq 'company-pseudo-tooltip-frontend value)
201 (error "Pseudo tooltip frontend cannot be used twice"))
202 (and (memq 'company-preview-if-just-one-frontend value)
203 (memq 'company-preview-frontend value)
204 (error "Preview frontend cannot be used twice"))
205 (and (memq 'company-echo value)
206 (memq 'company-echo-metadata-frontend value)
207 (error "Echo area cannot be used twice"))
208 ;; preview must come last
209 (dolist (f '(company-preview-if-just-one-frontend company-preview-frontend))
211 (setq value (append (delq f value) (list f)))))
212 (set variable value))
214 (defcustom company-frontends '(company-pseudo-tooltip-unless-just-one-frontend
215 company-preview-if-just-one-frontend
216 company-echo-metadata-frontend)
217 "The list of active front-ends (visualizations).
218 Each front-end is a function that takes one argument. It is called with
219 one of the following arguments:
221 `show': When the visualization should start.
223 `hide': When the visualization should end.
225 `update': When the data has been updated.
227 `pre-command': Before every command that is executed while the
228 visualization is active.
230 `post-command': After every command that is executed while the
231 visualization is active.
233 The visualized data is stored in `company-prefix', `company-candidates',
234 `company-common', `company-selection', `company-point' and
235 `company-search-string'."
236 :set 'company-frontends-set
237 :type '(repeat (choice (const :tag "echo" company-echo-frontend)
238 (const :tag "echo, strip common"
239 company-echo-strip-common-frontend)
240 (const :tag "show echo meta-data in echo"
241 company-echo-metadata-frontend)
242 (const :tag "pseudo tooltip"
243 company-pseudo-tooltip-frontend)
244 (const :tag "pseudo tooltip, multiple only"
245 company-pseudo-tooltip-unless-just-one-frontend)
246 (const :tag "preview" company-preview-frontend)
247 (const :tag "preview, unique only"
248 company-preview-if-just-one-frontend)
249 (function :tag "custom function" nil))))
251 (defcustom company-tooltip-limit 10
252 "The maximum number of candidates in the tooltip."
255 (defcustom company-tooltip-minimum 6
256 "The minimum height of the tooltip.
257 If this many lines are not available, prefer to display the tooltip above."
260 (defcustom company-tooltip-minimum-width 0
261 "The minimum width of the tooltip's inner area.
262 This doesn't include the margins and the scroll bar."
265 (defcustom company-tooltip-margin 1
266 "Width of margin columns to show around the toolip."
269 (defcustom company-tooltip-offset-display 'scrollbar
270 "Method using which the tooltip displays scrolling position.
271 `scrollbar' means draw a scrollbar to the right of the items.
272 `lines' means wrap items in lines with \"before\" and \"after\" counters."
273 :type '(choice (const :tag "Scrollbar" scrollbar)
274 (const :tag "Two lines" lines)))
276 (defcustom company-tooltip-align-annotations nil
277 "When non-nil, align annotations to the right tooltip border."
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-pysmell . "PySmell")
304 (company-ropemacs . "ropemacs")
305 (company-semantic . "Semantic")
306 (company-tempo . "Tempo templates")
307 (company-xcode . "Xcode")))
308 (put 'company-safe-backends 'risky-local-variable t)
310 (defun company-safe-backends-p (backends)
311 (and (consp backends)
312 (not (cl-dolist (backend backends)
313 (unless (if (consp backend)
314 (company-safe-backends-p backend)
315 (assq backend company-safe-backends))
318 (defcustom company-backends `(,@(unless (version< "24.3.50" emacs-version)
319 (list 'company-elisp))
321 company-nxml company-css
322 company-eclim company-semantic company-clang
323 company-xcode company-ropemacs company-cmake
325 (company-dabbrev-code company-gtags company-etags
327 company-oddmuse company-files company-dabbrev)
328 "The list of active back-ends (completion engines).
330 `company-begin-backend' can be used to start a specific back-end,
331 `company-other-backend' will skip to the next matching back-end in the list.
333 Each back-end is a function that takes a variable number of arguments.
334 The first argument is the command requested from the back-end. It is one
337 `prefix': The back-end should return the text to be completed. It must be
338 text immediately before point. Returning nil passes control to the next
339 back-end. The function should return `stop' if it should complete but
340 cannot \(e.g. if it is in the middle of a string\). Instead of a string,
341 the back-end may return a cons where car is the prefix and cdr is used in
342 `company-minimum-prefix-length' test. It must be either number or t, and
343 in the latter case the test automatically succeeds.
345 `candidates': The second argument is the prefix to be completed. The
346 return value should be a list of candidates that match the prefix.
348 Non-prefix matches are also supported (candidates that don't start with the
349 prefix, but match it in some backend-defined way). Backends that use this
350 feature must disable cache (return t to `no-cache') and should also respond
355 `sorted': Return t here to indicate that the candidates are sorted and will
356 not need to be sorted again.
358 `duplicates': If non-nil, company will take care of removing duplicates
361 `no-cache': Usually company doesn't ask for candidates again as completion
362 progresses, unless the back-end returns t for this command. The second
363 argument is the latest prefix.
365 `meta': The second argument is a completion candidate. Return a (short)
366 documentation string for it.
368 `doc-buffer': The second argument is a completion candidate. Return a
369 buffer with documentation for it. Preferably use `company-doc-buffer',
371 `location': The second argument is a completion candidate. Return the cons
372 of buffer and buffer location, or of file and line number where the
373 completion candidate was defined.
375 `annotation': The second argument is a completion candidate. Return a
376 string to be displayed inline with the candidate in the popup. If
377 duplicates are removed by company, candidates with equal string values will
378 be kept if they have different annotations. For that to work properly,
379 backends should store the related information on candidates using text
382 `match': The second argument is a completion candidate. Backends that
383 provide non-prefix completions should return the position of the end of
384 text in the candidate that matches `prefix'. It will be used when
387 `require-match': If this returns t, the user is not allowed to enter
388 anything not offered as a candidate. Use with care! The default value nil
389 gives the user that choice with `company-require-match'. Return value
390 `never' overrides that option the other way around.
392 `init': Called once for each buffer. The back-end can check for external
393 programs and files and load any required libraries. Raising an error here
394 will show up in message log once, and the back-end will not be used for
397 `post-completion': Called after a completion candidate has been inserted
398 into the buffer. The second argument is the candidate. Can be used to
399 modify it, e.g. to expand a snippet.
401 The back-end should return nil for all commands it does not support or
402 does not know about. It should also be callable interactively and use
403 `company-begin-backend' to start itself in that case.
407 An element of `company-backends' can also itself be a list of back-ends,
408 then it's considered to be a \"grouped\" back-end.
410 When possible, commands taking a candidate as an argument are dispatched to
411 the back-end it came from. In other cases, the first non-nil value among
412 all the back-ends is returned.
414 The latter is the case for the `prefix' command. But if the group contains
415 the keyword `:with', the back-ends after it are ignored for this command.
417 The completions from back-ends in a group are merged (but only from those
418 that return the same `prefix').
420 Asynchronous back-ends:
422 The return value of each command can also be a cons (:async . FETCHER)
423 where FETCHER is a function of one argument, CALLBACK. When the data
424 arrives, FETCHER must call CALLBACK and pass it the appropriate return
425 value, as described above.
427 True asynchronous operation is only supported for command `candidates', and
428 only during idle completion. Other commands will block the user interface,
429 even if the back-end uses the asynchronous calling convention."
433 ,@(mapcar (lambda (b) `(const :tag ,(cdr b) ,(car b)))
434 company-safe-backends)
435 (symbol :tag "User defined")
436 (repeat :tag "Merged Back-ends"
437 (choice :tag "Back-end"
438 ,@(mapcar (lambda (b)
439 `(const :tag ,(cdr b) ,(car b)))
440 company-safe-backends)
441 (const :tag "With" :with)
442 (symbol :tag "User defined"))))))
444 (put 'company-backends 'safe-local-variable 'company-safe-backends-p)
446 (defcustom company-transformers nil
447 "Functions to change the list of candidates received from backends,
448 after sorting and removal of duplicates (if appropriate).
449 Each function gets called with the return value of the previous one."
451 (const :tag "None" nil)
452 (const :tag "Sort by occurrence" (company-sort-by-occurrence))
453 (repeat :tag "User defined" (function))))
455 (defcustom company-completion-started-hook nil
456 "Hook run when company starts completing.
457 The hook is called with one argument that is non-nil if the completion was
461 (defcustom company-completion-cancelled-hook nil
462 "Hook run when company cancels completing.
463 The hook is called with one argument that is non-nil if the completion was
467 (defcustom company-completion-finished-hook nil
468 "Hook run when company successfully completes.
469 The hook is called with the selected candidate as an argument.
471 If you indend to use it to post-process candidates from a specific
472 back-end, consider using the `post-completion' command instead."
475 (defcustom company-minimum-prefix-length 3
476 "The minimum prefix length for idle completion."
477 :type '(integer :tag "prefix length"))
479 (defcustom company-abort-manual-when-too-short nil
480 "If enabled, cancel a manually started completion when the prefix gets
481 shorter than both `company-minimum-prefix-length' and the length of the
482 prefix it was started from."
485 (defcustom company-require-match 'company-explicit-action-p
486 "If enabled, disallow non-matching input.
487 This can be a function do determine if a match is required.
489 This can be overridden by the back-end, if it returns t or `never' to
490 `require-match'. `company-auto-complete' also takes precedence over this."
491 :type '(choice (const :tag "Off" nil)
492 (function :tag "Predicate function")
493 (const :tag "On, if user interaction took place"
494 'company-explicit-action-p)
495 (const :tag "On" t)))
497 (defcustom company-auto-complete nil
498 "Determines when to auto-complete.
499 If this is enabled, all characters from `company-auto-complete-chars'
500 trigger insertion of the selected completion candidate.
501 This can also be a function."
502 :type '(choice (const :tag "Off" nil)
503 (function :tag "Predicate function")
504 (const :tag "On, if user interaction took place"
505 'company-explicit-action-p)
506 (const :tag "On" t)))
508 (defcustom company-auto-complete-chars '(?\ ?\) ?.)
509 "Determines which characters trigger auto-completion.
510 See `company-auto-complete'. If this is a string, each string character
511 tiggers auto-completion. If it is a list of syntax description characters (see
512 `modify-syntax-entry'), all characters with that syntax auto-complete.
514 This can also be a function, which is called with the new input and should
515 return non-nil if company should auto-complete.
517 A character that is part of a valid candidate never triggers auto-completion."
518 :type '(choice (string :tag "Characters")
520 (const :tag "Whitespace" ?\ )
521 (const :tag "Symbol" ?_)
522 (const :tag "Opening parentheses" ?\()
523 (const :tag "Closing parentheses" ?\))
524 (const :tag "Word constituent" ?w)
525 (const :tag "Punctuation." ?.)
526 (const :tag "String quote." ?\")
527 (const :tag "Paired delimiter." ?$)
528 (const :tag "Expression quote or prefix operator." ?\')
529 (const :tag "Comment starter." ?<)
530 (const :tag "Comment ender." ?>)
531 (const :tag "Character-quote." ?/)
532 (const :tag "Generic string fence." ?|)
533 (const :tag "Generic comment fence." ?!))
534 (function :tag "Predicate function")))
536 (defcustom company-idle-delay .5
537 "The idle delay in seconds until completion starts automatically.
538 A value of nil means no idle completion, t means show candidates
539 immediately when a prefix of `company-minimum-prefix-length' is reached."
540 :type '(choice (const :tag "never (nil)" nil)
541 (const :tag "immediate (t)" t)
542 (number :tag "seconds")))
544 (defcustom company-begin-commands '(self-insert-command org-self-insert-command)
545 "A list of commands after which idle completion is allowed.
546 If this is t, it can show completions after any command. See
547 `company-idle-delay'.
549 Alternatively, any command with a non-nil `company-begin' property is
550 treated as if it was on this list."
551 :type '(choice (const :tag "Any command" t)
552 (const :tag "Self insert command" '(self-insert-command))
553 (repeat :tag "Commands" function)))
555 (defcustom company-continue-commands '(not save-buffer save-some-buffers
556 save-buffers-kill-terminal
557 save-buffers-kill-emacs)
558 "A list of commands that are allowed during completion.
559 If this is t, or if `company-begin-commands' is t, any command is allowed.
560 Otherwise, the value must be a list of symbols. If it starts with `not',
561 the cdr is the list of commands that abort completion. Otherwise, all
562 commands except those in that list, or in `company-begin-commands', or
563 commands in the `company-' namespace, abort completion."
564 :type '(choice (const :tag "Any command" t)
565 (cons :tag "Any except"
567 (repeat :tag "Commands" function))
568 (repeat :tag "Commands" function)))
570 (defcustom company-show-numbers nil
571 "If enabled, show quick-access numbers for the first ten candidates."
572 :type '(choice (const :tag "off" nil)
573 (const :tag "on" t)))
575 (defcustom company-selection-wrap-around nil
576 "If enabled, selecting item before first or after last wraps around."
577 :type '(choice (const :tag "off" nil)
578 (const :tag "on" t)))
580 (defvar company-end-of-buffer-workaround t
581 "Work around a visualization bug when completing at the end of the buffer.
582 The work-around consists of adding a newline.")
584 (defvar company-async-wait 0.03
585 "Pause between checks to see if the value's been set when turning an
586 asynchronous call into synchronous.")
588 (defvar company-async-timeout 2
589 "Maximum wait time for a value to be set during asynchronous call.")
591 ;;; mode ;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;
593 (defvar company-mode-map (make-sparse-keymap)
594 "Keymap used by `company-mode'.")
596 (defvar company-active-map
597 (let ((keymap (make-sparse-keymap)))
598 (define-key keymap "\e\e\e" 'company-abort)
599 (define-key keymap "\C-g" 'company-abort)
600 (define-key keymap (kbd "M-n") 'company-select-next)
601 (define-key keymap (kbd "M-p") 'company-select-previous)
602 (define-key keymap (kbd "<down>") 'company-select-next-or-abort)
603 (define-key keymap (kbd "<up>") 'company-select-previous-or-abort)
604 (define-key keymap [down-mouse-1] 'ignore)
605 (define-key keymap [down-mouse-3] 'ignore)
606 (define-key keymap [mouse-1] 'company-complete-mouse)
607 (define-key keymap [mouse-3] 'company-select-mouse)
608 (define-key keymap [up-mouse-1] 'ignore)
609 (define-key keymap [up-mouse-3] 'ignore)
610 (define-key keymap [return] 'company-complete-selection)
611 (define-key keymap (kbd "RET") 'company-complete-selection)
612 (define-key keymap [tab] 'company-complete-common)
613 (define-key keymap (kbd "TAB") 'company-complete-common)
614 (define-key keymap (kbd "<f1>") 'company-show-doc-buffer)
615 (define-key keymap "\C-w" 'company-show-location)
616 (define-key keymap "\C-s" 'company-search-candidates)
617 (define-key keymap "\C-\M-s" 'company-filter-candidates)
619 (define-key keymap (vector (+ (aref (kbd "M-0") 0) i))
622 (company-complete-number ,(if (zerop i) 10 i)))))
625 "Keymap that is enabled during an active completion.")
627 (defvar company--disabled-backends nil)
629 (defun company-init-backend (backend)
630 (and (symbolp backend)
631 (not (fboundp backend))
632 (ignore-errors (require backend nil t)))
637 (funcall backend 'init)
638 (put backend 'company-init t))
640 (put backend 'company-init 'failed)
641 (unless (memq backend company--disabled-backends)
642 (message "Company back-end '%s' could not be initialized:\n%s"
643 backend (error-message-string err)))
644 (cl-pushnew backend company--disabled-backends)
646 ;; No initialization for lambdas.
647 ((functionp backend) t)
648 (t ;; Must be a list.
649 (cl-dolist (b backend)
651 (company-init-backend b))))))
653 (defvar company-default-lighter " company")
655 (defvar-local company-lighter company-default-lighter)
658 (define-minor-mode company-mode
659 "\"complete anything\"; is an in-buffer completion framework.
660 Completion starts automatically, depending on the values
661 `company-idle-delay' and `company-minimum-prefix-length'.
663 Completion can be controlled with the commands:
664 `company-complete-common', `company-complete-selection', `company-complete',
665 `company-select-next', `company-select-previous'. If these commands are
666 called before `company-idle-delay', completion will also start.
668 Completions can be searched with `company-search-candidates' or
669 `company-filter-candidates'. These can be used while completion is
672 The completion data is retrieved using `company-backends' and displayed
673 using `company-frontends'. If you want to start a specific back-end, call
674 it interactively or use `company-begin-backend'.
676 regular keymap (`company-mode-map'):
679 keymap during active completions (`company-active-map'):
681 \\{company-active-map}"
682 nil company-lighter company-mode-map
685 (add-hook 'pre-command-hook 'company-pre-command nil t)
686 (add-hook 'post-command-hook 'company-post-command nil t)
687 (mapc 'company-init-backend company-backends))
688 (remove-hook 'pre-command-hook 'company-pre-command t)
689 (remove-hook 'post-command-hook 'company-post-command t)
691 (kill-local-variable 'company-point)))
693 (defcustom company-global-modes t
694 "Modes for which `company-mode' mode is turned on by `global-company-mode'.
695 If nil, means no modes. If t, then all major modes have it turned on.
696 If a list, it should be a list of `major-mode' symbol names for which
697 `company-mode' should be automatically turned on. The sense of the list is
698 negated if it begins with `not'. For example:
700 means that `company-mode' is turned on for buffers in C and C++ modes only.
702 means that `company-mode' is always turned on except in `message-mode' buffers."
703 :type '(choice (const :tag "none" nil)
705 (set :menu-tag "mode specific" :tag "modes"
707 (const :tag "Except" not)
708 (repeat :inline t (symbol :tag "mode")))))
711 (define-globalized-minor-mode global-company-mode company-mode company-mode-on)
713 (defun company-mode-on ()
714 (when (and (not (or noninteractive (eq (aref (buffer-name) 0) ?\s)))
715 (cond ((eq company-global-modes t)
717 ((eq (car-safe company-global-modes) 'not)
718 (not (memq major-mode (cdr company-global-modes))))
719 (t (memq major-mode company-global-modes))))
722 (defsubst company-assert-enabled ()
724 (company-uninstall-map)
725 (error "Company not enabled")))
727 ;;; keymaps ;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;
729 (defvar-local company-my-keymap nil)
731 (defvar company-emulation-alist '((t . nil)))
733 (defsubst company-enable-overriding-keymap (keymap)
734 (company-uninstall-map)
735 (setq company-my-keymap keymap))
737 (defun company-ensure-emulation-alist ()
738 (unless (eq 'company-emulation-alist (car emulation-mode-map-alists))
739 (setq emulation-mode-map-alists
740 (cons 'company-emulation-alist
741 (delq 'company-emulation-alist emulation-mode-map-alists)))))
743 (defun company-install-map ()
744 (unless (or (cdar company-emulation-alist)
745 (null company-my-keymap))
746 (setf (cdar company-emulation-alist) company-my-keymap)))
748 (defun company-uninstall-map ()
749 (setf (cdar company-emulation-alist) nil))
752 ;; Emacs calculates the active keymaps before reading the event. That means we
753 ;; cannot change the keymap from a timer. So we send a bogus command.
754 ;; XXX: Seems not to be needed anymore in Emacs 24.4
755 (defun company-ignore ()
757 (setq this-command last-command))
759 (global-set-key '[31415926] 'company-ignore)
761 (defun company-input-noop ()
762 (push 31415926 unread-command-events))
764 (defun company--column (&optional pos)
766 (when pos (goto-char pos))
770 (narrow-to-region (point) (point-max))
771 (let ((prefix (get-text-property (point) 'line-prefix)))
772 (if prefix (length prefix) 0)))
775 (defun company--row (&optional pos)
777 (when pos (goto-char pos))
778 (count-screen-lines (window-start)
779 (progn (vertical-motion 0) (point)))))
781 ;;; backends ;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;
783 (defvar-local company-backend nil)
785 (defun company-grab (regexp &optional expression limit)
786 (when (looking-back regexp limit)
787 (or (match-string-no-properties (or expression 0)) "")))
789 (defun company-grab-line (regexp &optional expression)
790 (company-grab regexp expression (point-at-bol)))
792 (defun company-grab-symbol ()
793 (if (looking-at "\\_>")
794 (buffer-substring (point) (save-excursion (skip-syntax-backward "w_")
796 (unless (and (char-after) (memq (char-syntax (char-after)) '(?w ?_)))
799 (defun company-grab-word ()
800 (if (looking-at "\\>")
801 (buffer-substring (point) (save-excursion (skip-syntax-backward "w")
803 (unless (and (char-after) (eq (char-syntax (char-after)) ?w))
806 (defun company-grab-symbol-cons (idle-begin-after-re &optional max-len)
807 (let ((symbol (company-grab-symbol)))
810 (forward-char (- (length symbol)))
811 (if (looking-back idle-begin-after-re (if max-len
813 (line-beginning-position)))
817 (defun company-in-string-or-comment ()
818 (let ((ppss (syntax-ppss)))
819 (or (car (setq ppss (nthcdr 3 ppss)))
820 (car (setq ppss (cdr ppss)))
823 (defun company-call-backend (&rest args)
824 (company--force-sync #'company-call-backend-raw args company-backend))
826 (defun company--force-sync (fun args backend)
827 (let ((value (apply fun args)))
828 (if (not (eq (car-safe value) :async))
831 (start (time-to-seconds)))
833 (lambda (result) (setq res result)))
834 (while (eq res 'trash)
835 (if (> (- (time-to-seconds) start) company-async-timeout)
836 (error "Company: Back-end %s async timeout with args %s"
838 (sleep-for company-async-wait)))
841 (defun company-call-backend-raw (&rest args)
843 (if (functionp company-backend)
844 (apply company-backend args)
845 (apply #'company--multi-backend-adapter company-backend args))
846 (error (error "Company: Back-end %s error \"%s\" with args %s"
847 company-backend (error-message-string err) args))))
849 (defun company--multi-backend-adapter (backends command &rest args)
850 (let ((backends (cl-loop for b in backends
851 when (not (and (symbolp b)
852 (eq 'failed (get b 'company-init))))
855 (if (eq command 'prefix)
856 (butlast backends (length (member :with backends)))
857 (delq :with backends)))
860 (company--multi-backend-adapter-candidates backends (car args)))
863 ((or `prefix `ignore-case `no-cache `require-match)
865 (cl-dolist (backend backends)
866 (when (setq value (company--force-sync
867 backend (cons command args) backend))
868 (cl-return value)))))
870 (let ((arg (car args)))
871 (when (> (length arg) 0)
872 (let ((backend (or (get-text-property 0 'company-backend arg)
874 (apply backend command args))))))))
876 (defun company--multi-backend-adapter-candidates (backends prefix)
877 (let ((pairs (cl-loop for backend in (cdr backends)
878 when (equal (company--prefix-str
879 (funcall backend 'prefix))
881 collect (cons (funcall backend 'candidates prefix)
886 (propertize str 'company-backend b))
888 (when (equal (company--prefix-str (funcall (car backends) 'prefix)) prefix)
889 ;; Small perf optimization: don't tag the candidates received
890 ;; from the first backend in the group.
891 (push (cons (funcall (car backends) 'candidates prefix)
894 (company--merge-async pairs (lambda (values) (apply #'append values)))))
896 (defun company--merge-async (pairs merger)
897 (let ((async (cl-loop for pair in pairs
899 (eq :async (car-safe (car pair))))))
901 (funcall merger (cl-loop for (val . mapper) in pairs
902 collect (funcall mapper val)))
913 (let ((val (car pair))
915 (if (not (eq :async (car-safe val)))
916 (push (funcall mapper val) lst)
920 (push fetcher pending)
923 (setq pending (delq fetcher pending))
924 (setcar cell (funcall mapper res))
925 (funcall finisher)))))))))))))
927 (defun company--prefix-str (prefix)
928 (or (car-safe prefix) prefix))
930 ;;; completion mechanism ;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;
932 (defvar-local company-prefix nil)
934 (defvar-local company-candidates nil)
936 (defvar-local company-candidates-length nil)
938 (defvar-local company-candidates-cache nil)
940 (defvar-local company-candidates-predicate nil)
942 (defvar-local company-common nil)
944 (defvar-local company-selection 0)
946 (defvar-local company-selection-changed nil)
948 (defvar-local company--manual-action nil
949 "Non-nil, if manual completion took place.")
951 (defvar-local company--manual-prefix nil)
953 (defvar company--auto-completion nil
954 "Non-nil when current candidate is being inserted automatically.
955 Controlled by `company-auto-complete'.")
957 (defvar-local company--point-max nil)
959 (defvar-local company-point nil)
961 (defvar company-timer nil)
963 (defvar-local company-added-newline nil)
965 (defsubst company-strip-prefix (str)
966 (substring str (length company-prefix)))
968 (defun company--insert-candidate (candidate)
969 (setq candidate (substring-no-properties candidate))
970 ;; XXX: Return value we check here is subject to change.
971 (if (eq (company-call-backend 'ignore-case) 'keep-prefix)
972 (insert (company-strip-prefix candidate))
973 (delete-region (- (point) (length company-prefix)) (point))
976 (defmacro company-with-candidate-inserted (candidate &rest body)
977 "Evaluate BODY with CANDIDATE temporarily inserted.
978 This is a tool for back-ends that need candidates inserted before they
979 can retrieve meta-data for them."
981 `(let ((inhibit-modification-hooks t)
982 (inhibit-point-motion-hooks t)
983 (modified-p (buffer-modified-p)))
984 (company--insert-candidate ,candidate)
987 (delete-region company-point (point)))))
989 (defun company-explicit-action-p ()
990 "Return whether explicit completion action was taken by the user."
991 (or company--manual-action
992 company-selection-changed))
994 (defun company-reformat (candidate)
995 ;; company-ispell needs this, because the results are always lower-case
996 ;; It's mory efficient to fix it only when they are displayed.
997 ;; FIXME: Adopt the current text's capitalization instead?
998 (if (eq (company-call-backend 'ignore-case) 'keep-prefix)
999 (concat company-prefix (substring candidate (length company-prefix)))
1002 (defun company--should-complete ()
1003 (and (not (or buffer-read-only overriding-terminal-local-map
1004 overriding-local-map))
1005 ;; Check if in the middle of entering a key combination.
1006 (or (equal (this-command-keys-vector) [])
1007 (not (keymapp (key-binding (this-command-keys-vector)))))
1008 (eq company-idle-delay t)
1009 (or (eq t company-begin-commands)
1010 (memq this-command company-begin-commands)
1011 (and (symbolp this-command) (get this-command 'company-begin)))
1012 (not (and transient-mark-mode mark-active))))
1014 (defun company--should-continue ()
1015 (or (eq t company-begin-commands)
1016 (eq t company-continue-commands)
1017 (if (eq 'not (car company-continue-commands))
1018 (not (memq this-command (cdr company-continue-commands)))
1019 (or (memq this-command company-begin-commands)
1020 (memq this-command company-continue-commands)
1021 (string-match-p "\\`company-" (symbol-name this-command))))))
1023 (defun company-call-frontends (command)
1024 (dolist (frontend company-frontends)
1026 (funcall frontend command)
1027 (error (error "Company: Front-end %s error \"%s\" on command %s"
1028 frontend (error-message-string err) command)))))
1030 (defun company-set-selection (selection &optional force-update)
1032 (if company-selection-wrap-around
1033 (mod selection company-candidates-length)
1034 (max 0 (min (1- company-candidates-length) selection))))
1035 (when (or force-update (not (equal selection company-selection)))
1036 (setq company-selection selection
1037 company-selection-changed t)
1038 (company-call-frontends 'update)))
1040 (defun company-apply-predicate (candidates predicate)
1042 (dolist (c candidates)
1043 (when (funcall predicate c)
1047 (defun company-update-candidates (candidates)
1048 (setq company-candidates-length (length candidates))
1049 (if (> company-selection 0)
1050 ;; Try to restore the selection
1051 (let ((selected (nth company-selection company-candidates)))
1052 (setq company-selection 0
1053 company-candidates candidates)
1055 (while (and candidates (string< (pop candidates) selected))
1056 (cl-incf company-selection))
1058 ;; Make sure selection isn't out of bounds.
1059 (setq company-selection (min (1- company-candidates-length)
1060 company-selection)))))
1061 (setq company-selection 0
1062 company-candidates candidates))
1064 (push (cons company-prefix company-candidates) company-candidates-cache)
1065 ;; Calculate common.
1066 (let ((completion-ignore-case (company-call-backend 'ignore-case)))
1067 ;; We want to support non-prefix completion, so filtering is the
1068 ;; responsibility of each respective backend, not ours.
1069 ;; On the other hand, we don't want to replace non-prefix input in
1070 ;; `company-complete-common'.
1071 (setq company-common
1072 (if (cdr company-candidates)
1073 (let ((common (try-completion company-prefix company-candidates)))
1075 ;; Mulple equal strings, probably with different
1079 (car company-candidates)))))
1081 (defun company-calculate-candidates (prefix)
1082 (let ((candidates (cdr (assoc prefix company-candidates-cache)))
1083 (ignore-case (company-call-backend 'ignore-case)))
1085 (when company-candidates-cache
1086 (let ((len (length prefix))
1087 (completion-ignore-case ignore-case)
1089 (cl-dotimes (i (1+ len))
1090 (when (setq prev (cdr (assoc (substring prefix 0 (- len i))
1091 company-candidates-cache)))
1092 (setq candidates (all-completions prefix prev))
1094 ;; no cache match, call back-end
1096 (company--process-candidates
1097 (company--fetch-candidates prefix))))
1098 (setq candidates (company--transform-candidates candidates))
1100 (if (or (cdr candidates)
1101 (not (eq t (compare-strings (car candidates) nil nil
1102 prefix nil nil ignore-case))))
1104 ;; Already completed and unique; don't start.
1107 (defun company--fetch-candidates (prefix)
1108 (let ((c (if company--manual-action
1109 (company-call-backend 'candidates prefix)
1110 (company-call-backend-raw 'candidates prefix)))
1112 (if (not (eq (car c) :async))
1114 (let ((buf (current-buffer))
1115 (win (selected-window))
1116 (tick (buffer-chars-modified-tick))
1118 (backend company-backend))
1121 (lambda (candidates)
1122 (if (not (and candidates (eq res 'done)))
1123 ;; Fetcher called us right back.
1124 (setq res candidates)
1125 (setq company-backend backend
1126 company-candidates-cache
1128 (company--process-candidates
1130 (company-idle-begin buf win tick pt)))))
1131 ;; FIXME: Relying on the fact that the callers
1132 ;; will interpret nil as "do nothing" is shaky.
1133 ;; A throw-catch would be one possible improvement.
1135 (progn (setq res 'done) nil)))))
1137 (defun company--process-candidates (candidates)
1138 (when company-candidates-predicate
1140 (company-apply-predicate candidates
1141 company-candidates-predicate)))
1142 (unless (company-call-backend 'sorted)
1143 (setq candidates (sort candidates 'string<)))
1144 (when (company-call-backend 'duplicates)
1145 (company--strip-duplicates candidates))
1148 (defun company--strip-duplicates (candidates)
1149 (let ((c2 candidates))
1152 (let ((str (car c2))
1155 (while (let ((str2 (car c2)))
1156 (if (not (equal str str2))
1158 (when (eq anno 'unk)
1159 (setq anno (company-call-backend
1162 (company-call-backend
1163 'annotation str2))))
1167 (defun company--transform-candidates (candidates)
1168 (let ((c candidates))
1169 (dolist (tr company-transformers)
1170 (setq c (funcall tr c)))
1173 (defun company-sort-by-occurrence (candidates)
1174 "Sort CANDIDATES according to their occurrences.
1175 Searches for each in the currently visible part of the current buffer and
1176 gives priority to the closest ones above point, then closest ones below
1177 point. The rest of the list is appended unchanged.
1178 Keywords and function definition names are ignored."
1185 (progn (forward-char (- (length company-prefix)))
1186 (search-backward candidate (window-start) t)))
1188 (search-forward candidate (window-end) t)))
1189 (let ((beg (match-beginning 0))
1190 (end (match-end 0)))
1191 (when (save-excursion
1193 (and (not (memq (get-text-property (point) 'face)
1194 '(font-lock-function-name-face
1195 font-lock-keyword-face)))
1196 (let ((prefix (company--prefix-str
1197 (company-call-backend 'prefix))))
1198 (and (stringp prefix)
1199 (= (length prefix) (- end beg))))))
1200 (push (cons candidate (if (< beg (point))
1202 (- beg (window-start))))
1207 (mapcar #'car (sort occurs (lambda (e1 e2) (<= (cdr e1) (cdr e2)))))
1210 (defun company-idle-begin (buf win tick pos)
1211 (and (eq buf (current-buffer))
1212 (eq win (selected-window))
1213 (eq tick (buffer-chars-modified-tick))
1215 (when (company-auto-begin)
1216 (when (version< emacs-version "24.3.50")
1217 (company-input-noop))
1218 (company-post-command))))
1220 (defun company-auto-begin ()
1222 (not company-candidates)
1223 (let ((company-idle-delay t)
1224 (company-begin-commands t))
1225 (condition-case-unless-debug err
1227 (error (message "Company: An error occurred in auto-begin")
1228 (message "%s" (error-message-string err))
1230 (quit (company-cancel)))))
1231 (unless company-candidates
1232 (setq company-backend nil))
1233 ;; Return non-nil if active.
1236 (defun company-manual-begin ()
1238 (company-assert-enabled)
1239 (setq company--manual-action t)
1241 (let ((company-minimum-prefix-length 0))
1242 (company-auto-begin))
1243 (unless company-candidates
1244 (setq company--manual-action nil))))
1246 (defun company-other-backend (&optional backward)
1247 (interactive (list current-prefix-arg))
1248 (company-assert-enabled)
1249 (let* ((after (if company-backend
1250 (cdr (member company-backend company-backends))
1252 (before (cdr (member company-backend (reverse company-backends))))
1254 (append before (reverse after))
1255 (append after (reverse before)))))
1257 (cl-dolist (backend next)
1258 (when (ignore-errors (company-begin-backend backend))
1260 (unless company-candidates
1261 (error "No other back-end")))
1263 (defun company-require-match-p ()
1264 (let ((backend-value (company-call-backend 'require-match)))
1265 (or (eq backend-value t)
1266 (and (not (eq backend-value 'never))
1267 (if (functionp company-require-match)
1268 (funcall company-require-match)
1269 (eq company-require-match t))))))
1271 (defun company-auto-complete-p (input)
1272 "Return non-nil, if input starts with punctuation or parentheses."
1273 (and (if (functionp company-auto-complete)
1274 (funcall company-auto-complete)
1275 company-auto-complete)
1276 (if (functionp company-auto-complete-chars)
1277 (funcall company-auto-complete-chars input)
1278 (if (consp company-auto-complete-chars)
1279 (memq (char-syntax (string-to-char input))
1280 company-auto-complete-chars)
1281 (string-match (substring input 0 1) company-auto-complete-chars)))))
1283 (defun company--incremental-p ()
1284 (and (> (point) company-point)
1285 (> (point-max) company--point-max)
1286 (not (eq this-command 'backward-delete-char-untabify))
1287 (equal (buffer-substring (- company-point (length company-prefix))
1291 (defun company--continue-failed ()
1292 (let ((input (buffer-substring-no-properties (point) company-point)))
1294 ((company-auto-complete-p input)
1297 (goto-char company-point)
1298 (let ((company--auto-completion t))
1299 (company-complete-selection))
1301 ((company-require-match-p)
1302 ;; wrong incremental input, but required match
1303 (delete-char (- (length input)))
1305 (message "Matching input is required")
1307 ((equal company-prefix (car company-candidates))
1308 ;; last input was actually success
1309 (company-cancel company-prefix))
1310 (t (company-cancel)))))
1312 (defun company--good-prefix-p (prefix)
1313 (and (stringp (company--prefix-str prefix)) ;excludes 'stop
1314 (or (eq (cdr-safe prefix) t)
1315 (let ((len (or (cdr-safe prefix) (length prefix))))
1316 (if company--manual-prefix
1317 (or (not company-abort-manual-when-too-short)
1318 ;; Must not be less than minimum or initial length.
1319 (>= len (min company-minimum-prefix-length
1320 (length company--manual-prefix))))
1321 (>= len company-minimum-prefix-length))))))
1323 (defun company--continue ()
1324 (when (company-call-backend 'no-cache company-prefix)
1325 ;; Don't complete existing candidates, fetch new ones.
1326 (setq company-candidates-cache nil))
1327 (let* ((new-prefix (company-call-backend 'prefix))
1328 (c (when (and (company--good-prefix-p new-prefix)
1329 (setq new-prefix (company--prefix-str new-prefix))
1330 (= (- (point) (length new-prefix))
1331 (- company-point (length company-prefix))))
1332 (company-calculate-candidates new-prefix))))
1335 ;; t means complete/unique.
1336 ;; Handle it like completion was aborted, to differentiate from user
1337 ;; calling one of Company's commands to insert the candidate.
1338 (company-cancel 'unique))
1340 ;; incremental match
1341 (setq company-prefix new-prefix)
1342 (company-update-candidates c)
1344 ((not (company--incremental-p))
1346 (t (company--continue-failed)))))
1348 (defun company--begin-new ()
1350 (cl-dolist (backend (if company-backend
1351 ;; prefer manual override
1352 (list company-backend)
1355 (if (or (symbolp backend)
1356 (functionp backend))
1357 (when (or (not (symbolp backend))
1358 (eq t (get backend 'company-init))
1359 (unless (get backend 'company-init)
1360 (company-init-backend backend)))
1361 (funcall backend 'prefix))
1362 (company--multi-backend-adapter backend 'prefix)))
1364 (when (company--good-prefix-p prefix)
1365 (setq company-prefix (company--prefix-str prefix)
1366 company-backend backend
1367 c (company-calculate-candidates company-prefix))
1368 ;; t means complete/unique. We don't start, so no hooks.
1370 (when company--manual-action
1371 (message "No completion found"))
1372 (when company--manual-action
1373 (setq company--manual-prefix prefix))
1374 (when (symbolp backend)
1375 (setq company-lighter (concat " " (symbol-name backend))))
1376 (company-update-candidates c)
1377 (run-hook-with-args 'company-completion-started-hook
1378 (company-explicit-action-p))
1379 (company-call-frontends 'show)))
1382 (defun company-begin ()
1383 (or (and company-candidates (company--continue))
1384 (and (company--should-complete) (company--begin-new)))
1385 (when company-candidates
1386 (let ((modified (buffer-modified-p)))
1387 (when (and company-end-of-buffer-workaround (eobp))
1388 (save-excursion (insert "\n"))
1389 (setq company-added-newline
1390 (or modified (buffer-chars-modified-tick)))))
1391 (setq company-point (point)
1392 company--point-max (point-max))
1393 (company-ensure-emulation-alist)
1394 (company-enable-overriding-keymap company-active-map)
1395 (company-call-frontends 'update)))
1397 (defun company-cancel (&optional result)
1398 (and company-added-newline
1399 (> (point-max) (point-min))
1400 (let ((tick (buffer-chars-modified-tick)))
1401 (delete-region (1- (point-max)) (point-max))
1402 (equal tick company-added-newline))
1403 ;; Only set unmodified when tick remained the same since insert,
1404 ;; and the buffer wasn't modified before.
1405 (set-buffer-modified-p nil))
1406 (when company-prefix
1407 (if (stringp result)
1409 (company-call-backend 'pre-completion result)
1410 (run-hook-with-args 'company-completion-finished-hook result)
1411 (company-call-backend 'post-completion result))
1412 (run-hook-with-args 'company-completion-cancelled-hook result)))
1413 (setq company-added-newline nil
1416 company-candidates nil
1417 company-candidates-length nil
1418 company-candidates-cache nil
1419 company-candidates-predicate nil
1422 company-selection-changed nil
1423 company--manual-action nil
1424 company--manual-prefix nil
1425 company-lighter company-default-lighter
1426 company--point-max nil
1429 (cancel-timer company-timer))
1430 (company-search-mode 0)
1431 (company-call-frontends 'hide)
1432 (company-enable-overriding-keymap nil)
1433 ;; Make return value explicit.
1436 (defun company-abort ()
1439 ;; Don't start again, unless started manually.
1440 (setq company-point (point)))
1442 (defun company-finish (result)
1443 (company--insert-candidate result)
1444 (company-cancel result)
1445 ;; Don't start again, unless started manually.
1446 (setq company-point (point)))
1448 (defsubst company-keep (command)
1449 (and (symbolp command) (get command 'company-keep)))
1451 (defun company-pre-command ()
1452 (unless (company-keep this-command)
1454 (when company-candidates
1455 (company-call-frontends 'pre-command)
1456 (unless (company--should-continue)
1458 (error (message "Company: An error occurred in pre-command")
1459 (message "%s" (error-message-string err))
1462 (cancel-timer company-timer)
1463 (setq company-timer nil))
1464 (company-uninstall-map))
1466 (defun company-post-command ()
1467 (unless (company-keep this-command)
1470 (unless (equal (point) company-point)
1472 (if company-candidates
1473 (company-call-frontends 'post-command)
1474 (and (numberp company-idle-delay)
1475 (or (eq t company-begin-commands)
1476 (memq this-command company-begin-commands))
1477 (not (equal (point) company-point))
1479 (run-with-timer company-idle-delay nil
1481 (current-buffer) (selected-window)
1482 (buffer-chars-modified-tick) (point))))))
1483 (error (message "Company: An error occurred in post-command")
1484 (message "%s" (error-message-string err))
1486 (company-install-map))
1488 ;;; search ;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;
1490 (defvar-local company-search-string nil)
1492 (defvar-local company-search-lighter " Search: \"\"")
1494 (defvar-local company-search-old-map nil)
1496 (defvar-local company-search-old-selection 0)
1498 (defun company-search (text lines)
1499 (let ((quoted (regexp-quote text))
1501 (cl-dolist (line lines)
1502 (when (string-match quoted line (length company-prefix))
1506 (defun company-search-printing-char ()
1508 (company-search-assert-enabled)
1509 (setq company-search-string
1510 (concat (or company-search-string "") (string last-command-event))
1511 company-search-lighter (concat " Search: \"" company-search-string
1513 (let ((pos (company-search company-search-string
1514 (nthcdr company-selection company-candidates))))
1517 (company-set-selection (+ company-selection pos) t))))
1519 (defun company-search-repeat-forward ()
1520 "Repeat the incremental search in completion candidates forward."
1522 (company-search-assert-enabled)
1523 (let ((pos (company-search company-search-string
1524 (cdr (nthcdr company-selection
1525 company-candidates)))))
1528 (company-set-selection (+ company-selection pos 1) t))))
1530 (defun company-search-repeat-backward ()
1531 "Repeat the incremental search in completion candidates backwards."
1533 (company-search-assert-enabled)
1534 (let ((pos (company-search company-search-string
1535 (nthcdr (- company-candidates-length
1537 (reverse company-candidates)))))
1540 (company-set-selection (- company-selection pos 1) t))))
1542 (defun company-create-match-predicate ()
1543 (setq company-candidates-predicate
1544 `(lambda (candidate)
1545 ,(if company-candidates-predicate
1546 `(and (string-match ,company-search-string candidate)
1547 (funcall ,company-candidates-predicate
1549 `(string-match ,company-search-string candidate))))
1550 (company-update-candidates
1551 (company-apply-predicate company-candidates company-candidates-predicate))
1552 ;; Invalidate cache.
1553 (setq company-candidates-cache (cons company-prefix company-candidates)))
1555 (defun company-filter-printing-char ()
1557 (company-search-assert-enabled)
1558 (company-search-printing-char)
1559 (company-create-match-predicate)
1560 (company-call-frontends 'update))
1562 (defun company-search-kill-others ()
1563 "Limit the completion candidates to the ones matching the search string."
1565 (company-search-assert-enabled)
1566 (company-create-match-predicate)
1567 (company-search-mode 0)
1568 (company-call-frontends 'update))
1570 (defun company-search-abort ()
1571 "Abort searching the completion candidates."
1573 (company-search-assert-enabled)
1574 (company-set-selection company-search-old-selection t)
1575 (company-search-mode 0))
1577 (defun company-search-other-char ()
1579 (company-search-assert-enabled)
1580 (company-search-mode 0)
1581 (company--unread-last-input))
1583 (defvar company-search-map
1585 (keymap (make-keymap)))
1586 (if (fboundp 'max-char)
1587 (set-char-table-range (nth 1 keymap) (cons #x100 (max-char))
1588 'company-search-printing-char)
1590 ;; obsolete in Emacs 23
1591 (let ((l (generic-character-list))
1592 (table (nth 1 keymap)))
1594 (set-char-table-default table (car l) 'company-search-printing-char)
1595 (setq l (cdr l))))))
1596 (define-key keymap [t] 'company-search-other-char)
1598 (define-key keymap (make-string 1 i) 'company-search-other-char)
1601 (define-key keymap (vector i) 'company-search-printing-char)
1603 (let ((meta-map (make-sparse-keymap)))
1604 (define-key keymap (char-to-string meta-prefix-char) meta-map)
1605 (define-key keymap [escape] meta-map))
1606 (define-key keymap (vector meta-prefix-char t) 'company-search-other-char)
1607 (define-key keymap "\e\e\e" 'company-search-other-char)
1608 (define-key keymap [escape escape escape] 'company-search-other-char)
1609 (define-key keymap (kbd "DEL") 'company-search-other-char)
1611 (define-key keymap "\C-g" 'company-search-abort)
1612 (define-key keymap "\C-s" 'company-search-repeat-forward)
1613 (define-key keymap "\C-r" 'company-search-repeat-backward)
1614 (define-key keymap "\C-o" 'company-search-kill-others)
1616 "Keymap used for incrementally searching the completion candidates.")
1618 (define-minor-mode company-search-mode
1619 "Search mode for completion candidates.
1620 Don't start this directly, use `company-search-candidates' or
1621 `company-filter-candidates'."
1622 nil company-search-lighter nil
1623 (if company-search-mode
1624 (if (company-manual-begin)
1626 (setq company-search-old-selection company-selection)
1627 (company-call-frontends 'update))
1628 (setq company-search-mode nil))
1629 (kill-local-variable 'company-search-string)
1630 (kill-local-variable 'company-search-lighter)
1631 (kill-local-variable 'company-search-old-selection)
1632 (company-enable-overriding-keymap company-active-map)))
1634 (defun company-search-assert-enabled ()
1635 (company-assert-enabled)
1636 (unless company-search-mode
1637 (company-uninstall-map)
1638 (error "Company not in search mode")))
1640 (defun company-search-candidates ()
1641 "Start searching the completion candidates incrementally.
1643 \\<company-search-map>Search can be controlled with the commands:
1644 - `company-search-repeat-forward' (\\[company-search-repeat-forward])
1645 - `company-search-repeat-backward' (\\[company-search-repeat-backward])
1646 - `company-search-abort' (\\[company-search-abort])
1648 Regular characters are appended to the search string.
1650 The command `company-search-kill-others' (\\[company-search-kill-others])
1651 uses the search string to limit the completion candidates."
1653 (company-search-mode 1)
1654 (company-enable-overriding-keymap company-search-map))
1656 (defvar company-filter-map
1657 (let ((keymap (make-keymap)))
1658 (define-key keymap [remap company-search-printing-char]
1659 'company-filter-printing-char)
1660 (set-keymap-parent keymap company-search-map)
1662 "Keymap used for incrementally searching the completion candidates.")
1664 (defun company-filter-candidates ()
1665 "Start filtering the completion candidates incrementally.
1666 This works the same way as `company-search-candidates' immediately
1667 followed by `company-search-kill-others' after each input."
1669 (company-search-mode 1)
1670 (company-enable-overriding-keymap company-filter-map))
1672 ;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;
1674 (defun company-select-next ()
1675 "Select the next candidate in the list."
1677 (when (company-manual-begin)
1678 (company-set-selection (1+ company-selection))))
1680 (defun company-select-previous ()
1681 "Select the previous candidate in the list."
1683 (when (company-manual-begin)
1684 (company-set-selection (1- company-selection))))
1686 (defun company-select-next-or-abort ()
1687 "Select the next candidate if more than one, else abort
1688 and invoke the normal binding."
1690 (if (> company-candidates-length 1)
1691 (company-select-next)
1693 (company--unread-last-input)))
1695 (defun company-select-previous-or-abort ()
1696 "Select the previous candidate if more than one, else abort
1697 and invoke the normal binding."
1699 (if (> company-candidates-length 1)
1700 (company-select-previous)
1702 (company--unread-last-input)))
1704 (defvar company-pseudo-tooltip-overlay)
1706 (defvar company-tooltip-offset)
1708 (defun company--inside-tooltip-p (event-col-row row height)
1709 (let* ((ovl company-pseudo-tooltip-overlay)
1710 (column (overlay-get ovl 'company-column))
1711 (width (overlay-get ovl 'company-width))
1712 (evt-col (car event-col-row))
1713 (evt-row (cdr event-col-row)))
1714 (and (>= evt-col column)
1715 (< evt-col (+ column width))
1717 (and (> evt-row row)
1718 (<= evt-row (+ row height) ))
1719 (and (< evt-row row)
1720 (>= evt-row (+ row height)))))))
1722 (defun company--event-col-row (event)
1723 (let* ((col-row (posn-actual-col-row (event-start event)))
1725 (row (cdr col-row)))
1726 (cl-incf col (window-hscroll))
1727 (and header-line-format
1728 (version< "24" emacs-version)
1732 (defun company-select-mouse (event)
1733 "Select the candidate picked by the mouse."
1735 (let ((event-col-row (company--event-col-row event))
1736 (ovl-row (company--row))
1737 (ovl-height (and company-pseudo-tooltip-overlay
1738 (min (overlay-get company-pseudo-tooltip-overlay
1740 company-candidates-length))))
1742 (company--inside-tooltip-p event-col-row ovl-row ovl-height))
1744 (company-set-selection (+ (cdr event-col-row)
1745 (1- company-tooltip-offset)
1746 (if (and (eq company-tooltip-offset-display 'lines)
1747 (not (zerop company-tooltip-offset)))
1750 (if (< ovl-height 0)
1755 (company--unread-last-input)
1758 (defun company-complete-mouse (event)
1759 "Insert the candidate picked by the mouse."
1761 (when (company-select-mouse event)
1762 (company-complete-selection)))
1764 (defun company-complete-selection ()
1765 "Insert the selected candidate."
1767 (when (company-manual-begin)
1768 (let ((result (nth company-selection company-candidates)))
1769 (company-finish result))))
1771 (defun company-complete-common ()
1772 "Insert the common part of all candidates."
1774 (when (company-manual-begin)
1775 (if (and (not (cdr company-candidates))
1776 (equal company-common (car company-candidates)))
1777 (company-complete-selection)
1778 (when company-common
1779 (company--insert-candidate company-common)))))
1781 (defun company-complete ()
1782 "Insert the common part of all candidates or the current selection.
1783 The first time this is called, the common part is inserted, the second
1784 time, or when the selection has been changed, the selected candidate is
1787 (when (company-manual-begin)
1788 (if (or company-selection-changed
1789 (eq last-command 'company-complete-common))
1790 (call-interactively 'company-complete-selection)
1791 (call-interactively 'company-complete-common)
1792 (setq this-command 'company-complete-common))))
1794 (defun company-complete-number (n)
1795 "Insert the Nth candidate.
1796 To show the number next to the candidates in some back-ends, enable
1797 `company-show-numbers'."
1798 (when (company-manual-begin)
1799 (and (or (< n 1) (> n company-candidates-length))
1800 (error "No candidate number %d" n))
1802 (company-finish (nth n company-candidates))))
1804 ;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;
1806 (defconst company-space-strings-limit 100)
1808 (defconst company-space-strings
1810 (dotimes (i company-space-strings-limit)
1811 (push (make-string (- company-space-strings-limit 1 i) ?\ ) lst))
1812 (apply 'vector lst)))
1814 (defun company-space-string (len)
1815 (if (< len company-space-strings-limit)
1816 (aref company-space-strings len)
1817 (make-string len ?\ )))
1819 (defun company-safe-substring (str from &optional to)
1820 (if (> from (string-width str))
1824 (move-to-column from)
1825 (let ((beg (point)))
1829 (concat (buffer-substring beg (point))
1830 (let ((padding (- to (current-column))))
1832 (company-space-string padding)))))
1833 (buffer-substring beg (point-max)))))))
1835 ;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;
1837 (defvar-local company-last-metadata nil)
1839 (defun company-fetch-metadata ()
1840 (let ((selected (nth company-selection company-candidates)))
1841 (unless (eq selected (car company-last-metadata))
1842 (setq company-last-metadata
1843 (cons selected (company-call-backend 'meta selected))))
1844 (cdr company-last-metadata)))
1846 (defun company-doc-buffer (&optional string)
1847 (with-current-buffer (get-buffer-create "*company-documentation*")
1854 (defvar company--electric-commands
1855 '(scroll-other-window scroll-other-window-down)
1856 "List of Commands that won't break out of electric commands.")
1858 (defmacro company--electric-do (&rest body)
1859 (declare (indent 0) (debug t))
1860 `(when (company-manual-begin)
1861 (save-window-excursion
1862 (let ((height (window-height))
1863 (row (company--row))
1866 (and (< (window-height) height)
1867 (< (- (window-height) row 2) company-tooltip-limit)
1868 (recenter (- (window-height) row 2)))
1869 (while (memq (setq cmd (key-binding (vector (list (read-event)))))
1870 company--electric-commands)
1871 (call-interactively cmd))
1872 (company--unread-last-input)))))
1874 (defun company--unread-last-input ()
1875 (when last-input-event
1876 (clear-this-command-keys t)
1877 (setq unread-command-events (list last-input-event))))
1879 (defun company-show-doc-buffer ()
1880 "Temporarily show the documentation buffer for the selection."
1882 (company--electric-do
1883 (let* ((selected (nth company-selection company-candidates))
1884 (doc-buffer (or (company-call-backend 'doc-buffer selected)
1885 (error "No documentation available"))))
1886 (with-current-buffer doc-buffer
1887 (goto-char (point-min)))
1888 (display-buffer doc-buffer t))))
1889 (put 'company-show-doc-buffer 'company-keep t)
1891 (defun company-show-location ()
1892 "Temporarily display a buffer showing the selected candidate in context."
1894 (company--electric-do
1895 (let* ((selected (nth company-selection company-candidates))
1896 (location (company-call-backend 'location selected))
1897 (pos (or (cdr location) (error "No location available")))
1898 (buffer (or (and (bufferp (car location)) (car location))
1899 (find-file-noselect (car location) t))))
1900 (with-selected-window (display-buffer buffer t)
1903 (if (bufferp (car location))
1905 (goto-char (point-min))
1906 (forward-line (1- pos))))
1907 (set-window-start nil (point))))))
1908 (put 'company-show-location 'company-keep t)
1910 ;;; package functions ;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;
1912 (defvar-local company-callback nil)
1914 (defun company-remove-callback (&optional ignored)
1915 (remove-hook 'company-completion-finished-hook company-callback t)
1916 (remove-hook 'company-completion-cancelled-hook 'company-remove-callback t)
1917 (remove-hook 'company-completion-finished-hook 'company-remove-callback t))
1919 (defun company-begin-backend (backend &optional callback)
1920 "Start a completion at point using BACKEND."
1921 (interactive (let ((val (completing-read "Company back-end: "
1923 'functionp nil "company-")))
1925 (list (intern val)))))
1926 (when (setq company-callback callback)
1927 (add-hook 'company-completion-finished-hook company-callback nil t))
1928 (add-hook 'company-completion-cancelled-hook 'company-remove-callback nil t)
1929 (add-hook 'company-completion-finished-hook 'company-remove-callback nil t)
1930 (setq company-backend backend)
1931 ;; Return non-nil if active.
1932 (or (company-manual-begin)
1933 (error "Cannot complete at point")))
1935 (defun company-begin-with (candidates
1936 &optional prefix-length require-match callback)
1937 "Start a completion at point.
1938 CANDIDATES is the list of candidates to use and PREFIX-LENGTH is the length
1939 of the prefix that already is in the buffer before point.
1942 CALLBACK is a function called with the selected result if the user
1943 successfully completes the input.
1945 Example: \(company-begin-with '\(\"foo\" \"foobar\" \"foobarbaz\"\)\)"
1946 (let ((begin-marker (copy-marker (point) t)))
1947 (company-begin-backend
1948 (lambda (command &optional arg &rest ignored)
1951 (when (equal (point) (marker-position begin-marker))
1952 (buffer-substring (- (point) (or prefix-length 0)) (point))))
1954 (all-completions arg candidates))
1959 (defun company-version (&optional show-version)
1960 "Get the Company version as string.
1962 If SHOW-VERSION is non-nil, show the version in the echo area."
1963 (interactive (list t))
1965 (insert-file-contents (find-library-name "company"))
1968 (message "Company version: %s" (lm-version))
1971 ;;; pseudo-tooltip ;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;
1973 (defvar-local company-pseudo-tooltip-overlay nil)
1975 (defvar-local company-tooltip-offset 0)
1977 (defun company-tooltip--lines-update-offset (selection num-lines limit)
1979 (setq company-tooltip-offset
1980 (max (min selection company-tooltip-offset)
1981 (- selection -1 limit)))
1983 (when (<= company-tooltip-offset 1)
1985 (setq company-tooltip-offset 0))
1987 (when (>= company-tooltip-offset (- num-lines limit 1))
1989 (when (= selection (1- num-lines))
1990 (cl-decf company-tooltip-offset)
1991 (when (<= company-tooltip-offset 1)
1992 (setq company-tooltip-offset 0)
1997 (defun company-tooltip--simple-update-offset (selection _num-lines limit)
1998 (setq company-tooltip-offset
1999 (if (< selection company-tooltip-offset)
2001 (max company-tooltip-offset
2002 (- selection limit -1)))))
2006 (defsubst company-round-tab (arg)
2007 (* (/ (+ arg tab-width) tab-width) tab-width))
2009 (defun company-plainify (str)
2010 (let ((prefix (get-text-property 0 'line-prefix str)))
2011 (when prefix ; Keep the original value unmodified, for no special reason.
2012 (setq str (concat prefix str))
2013 (remove-text-properties 0 (length str) '(line-prefix) str)))
2014 (let* ((pieces (split-string str "\t"))
2017 (setcar copy (company-safe-substring
2018 (car copy) 0 (company-round-tab (string-width (car copy)))))
2020 (apply 'concat pieces)))
2022 (defun company-fill-propertize (value annotation width selected left right)
2023 (let* ((margin (length left))
2024 (common (+ (or (company-call-backend 'match value)
2025 (length company-common)) margin))
2026 (ann-ralign company-tooltip-align-annotations)
2027 (ann-truncate (< width
2028 (+ (length value) (length annotation)
2029 (if ann-ralign 1 0))))
2030 (ann-start (+ margin
2034 (- width (length annotation)))
2036 (ann-end (min (+ ann-start (length annotation)) (+ margin width)))
2038 (if (or ann-truncate (not ann-ralign))
2039 (company-safe-substring
2041 (when (and annotation ann-ralign) " ")
2045 (company-safe-substring value 0
2046 (- width (length annotation)))
2049 (setq width (+ width margin (length right)))
2051 (add-text-properties 0 width '(face company-tooltip
2052 mouse-face company-tooltip-mouse)
2054 (add-text-properties margin common
2055 '(face company-tooltip-common
2056 mouse-face company-tooltip-mouse)
2058 (when (< ann-start ann-end)
2059 (add-text-properties ann-start ann-end
2060 '(face company-tooltip-annotation
2061 mouse-face company-tooltip-mouse)
2064 (if (and company-search-string
2065 (string-match (regexp-quote company-search-string) value
2066 (length company-prefix)))
2067 (let ((beg (+ margin (match-beginning 0)))
2068 (end (+ margin (match-end 0))))
2069 (add-text-properties beg end '(face company-tooltip-selection)
2071 (when (< beg common)
2072 (add-text-properties beg common
2073 '(face company-tooltip-common-selection)
2075 (add-text-properties 0 width '(face company-tooltip-selection
2076 mouse-face company-tooltip-selection)
2078 (add-text-properties margin common
2079 '(face company-tooltip-common-selection
2080 mouse-face company-tooltip-selection)
2086 (defun company-buffer-lines (beg end)
2089 (while (and (= 1 (vertical-motion 1))
2091 (let ((bound (min end (1- (point)))))
2092 ;; A visual line can contain several physical lines (e.g. with outline's
2093 ;; folding overlay). Take only the first one.
2094 (push (buffer-substring beg
2097 (re-search-forward "$" bound 'move)
2101 (unless (eq beg end)
2102 (push (buffer-substring beg end) lines))
2105 (defun company-modify-line (old new offset)
2106 (concat (company-safe-substring old 0 offset)
2108 (company-safe-substring old (+ offset (length new)))))
2110 (defsubst company--length-limit (lst limit)
2111 (if (nthcdr limit lst)
2115 (defun company--replacement-string (lines old column nl &optional align-top)
2116 (cl-decf column company-tooltip-margin)
2118 (when (and align-top company-tooltip-flip-when-above)
2119 (setq lines (reverse lines)))
2121 (let ((width (length (car lines)))
2122 (remaining-cols (- (+ (company--window-width) (window-hscroll))
2124 (when (> width remaining-cols)
2125 (cl-decf column (- width remaining-cols))))
2127 (let ((offset (and (< column 0) (- column)))
2132 ;; untouched lines first
2133 (dotimes (_ (- (length old) (length lines)))
2134 (push (pop old) new)))
2135 ;; length into old lines.
2137 (push (company-modify-line (pop old)
2138 (company--offset-line (pop lines) offset)
2140 ;; Append whole new lines.
2142 (push (concat (company-space-string column)
2143 (company--offset-line (pop lines) offset))
2146 (let ((str (concat (when nl "\n")
2147 (mapconcat 'identity (nreverse new) "\n")
2149 (font-lock-append-text-property 0 (length str) 'face 'default str)
2152 (defun company--offset-line (line offset)
2153 (if (and offset line)
2154 (substring line offset)
2157 (defun company--create-lines (selection limit)
2158 (let ((len company-candidates-length)
2160 (window-width (company--window-width))
2169 ;; Maybe clear old offset.
2170 (when (< len (+ company-tooltip-offset limit))
2171 (setq company-tooltip-offset 0))
2173 ;; Scroll to offset.
2174 (if (eq company-tooltip-offset-display 'lines)
2175 (setq limit (company-tooltip--lines-update-offset selection len limit))
2176 (company-tooltip--simple-update-offset selection len limit))
2179 ((eq company-tooltip-offset-display 'scrollbar)
2180 (setq scrollbar-bounds (company--scrollbar-bounds company-tooltip-offset
2182 ((eq company-tooltip-offset-display 'lines)
2183 (when (> company-tooltip-offset 0)
2184 (setq previous (format "...(%d)" company-tooltip-offset)))
2185 (setq remainder (- len limit company-tooltip-offset)
2186 remainder (when (> remainder 0)
2187 (setq remainder (format "...(%d)" remainder))))))
2189 (cl-decf selection company-tooltip-offset)
2190 (setq width (max (length previous) (length remainder))
2191 lines (nthcdr company-tooltip-offset company-candidates)
2195 (cl-decf window-width (* 2 company-tooltip-margin))
2196 (when scrollbar-bounds (cl-decf window-width))
2199 (let* ((value (pop lines-copy))
2200 (annotation (company-call-backend 'annotation value)))
2201 (when (and annotation company-tooltip-align-annotations)
2202 ;; `lisp-completion-at-point' adds a space.
2203 (setq annotation (comment-string-strip annotation t nil)))
2204 (push (cons value annotation) items)
2205 (setq width (max (+ (length value)
2206 (if (and annotation company-tooltip-align-annotations)
2207 (1+ (length annotation))
2208 (length annotation)))
2211 (setq width (min window-width
2212 (max company-tooltip-minimum-width
2213 (if (and company-show-numbers
2214 (< company-tooltip-offset 10))
2218 ;; number can make tooltip too long
2219 (when company-show-numbers
2220 (setq numbered company-tooltip-offset))
2222 (let ((items (nreverse items)) new)
2224 (push (company--scrollpos-line previous width) new))
2227 (let* ((item (pop items))
2228 (str (company-reformat (car item)))
2229 (annotation (cdr item))
2230 (right (company-space-string company-tooltip-margin))
2232 (when (< numbered 10)
2235 (setq right (concat (format " %d" (mod numbered 10)) right)))
2237 (company-fill-propertize str annotation
2238 width (equal i selection)
2239 (company-space-string
2240 company-tooltip-margin)
2242 (when scrollbar-bounds
2243 (company--scrollbar i scrollbar-bounds)))
2247 (push (company--scrollpos-line remainder width) new))
2251 (defun company--scrollbar-bounds (offset limit length)
2252 (when (> length limit)
2253 (let* ((size (ceiling (* limit (float limit)) length))
2254 (lower (floor (* limit (float offset)) length))
2255 (upper (+ lower size -1)))
2256 (cons lower upper))))
2258 (defun company--scrollbar (i bounds)
2259 (propertize " " 'face
2260 (if (and (>= i (car bounds)) (<= i (cdr bounds)))
2261 'company-scrollbar-fg
2262 'company-scrollbar-bg)))
2264 (defun company--scrollpos-line (text width)
2265 (propertize (concat (company-space-string company-tooltip-margin)
2266 (company-safe-substring text 0 width)
2267 (company-space-string company-tooltip-margin))
2268 'face 'company-tooltip))
2272 (defsubst company--window-inner-height ()
2273 (let ((edges (window-inside-edges)))
2274 (- (nth 3 edges) (nth 1 edges))))
2276 (defsubst company--window-width ()
2277 (let ((ww (window-width)))
2278 ;; Account for the line continuation column.
2279 (when (zerop (cadr (window-fringes)))
2281 (unless (or (display-graphic-p)
2282 (version< "24.3.1" emacs-version))
2283 ;; Emacs 24.3 and earlier included margins
2284 ;; in window-width when in TTY.
2286 (let ((margins (window-margins)))
2287 (+ (or (car margins) 0)
2288 (or (cdr margins) 0)))))
2291 (defun company--pseudo-tooltip-height ()
2292 "Calculate the appropriate tooltip height.
2293 Returns a negative number if the tooltip should be displayed above point."
2294 (let* ((lines (company--row))
2295 (below (- (company--window-inner-height) 1 lines)))
2296 (if (and (< below (min company-tooltip-minimum company-candidates-length))
2298 (- (max 3 (min company-tooltip-limit lines)))
2299 (max 3 (min company-tooltip-limit below)))))
2301 (defun company-pseudo-tooltip-show (row column selection)
2302 (company-pseudo-tooltip-hide)
2305 (let* ((height (company--pseudo-tooltip-height))
2309 (setq row (+ row height -1)
2312 (let* ((nl (< (move-to-window-line row) row))
2314 (end (save-excursion
2315 (move-to-window-line (+ row (abs height)))
2317 (ov (make-overlay beg end))
2318 (args (list (mapcar 'company-plainify
2319 (company-buffer-lines beg end))
2322 (setq company-pseudo-tooltip-overlay ov)
2323 (overlay-put ov 'company-replacement-args args)
2325 (let ((lines (company--create-lines selection (abs height))))
2326 (overlay-put ov 'company-after
2327 (apply 'company--replacement-string lines args))
2328 (overlay-put ov 'company-width (string-width (car lines))))
2330 (overlay-put ov 'company-column column)
2331 (overlay-put ov 'company-height height)))))
2333 (defun company-pseudo-tooltip-show-at-point (pos)
2334 (let ((row (company--row pos))
2335 (col (company--column pos)))
2336 (company-pseudo-tooltip-show (1+ row) col company-selection)))
2338 (defun company-pseudo-tooltip-edit (selection)
2339 (let ((height (overlay-get company-pseudo-tooltip-overlay 'company-height)))
2340 (overlay-put company-pseudo-tooltip-overlay 'company-after
2341 (apply 'company--replacement-string
2342 (company--create-lines selection (abs height))
2343 (overlay-get company-pseudo-tooltip-overlay
2344 'company-replacement-args)))))
2346 (defun company-pseudo-tooltip-hide ()
2347 (when company-pseudo-tooltip-overlay
2348 (delete-overlay company-pseudo-tooltip-overlay)
2349 (setq company-pseudo-tooltip-overlay nil)))
2351 (defun company-pseudo-tooltip-hide-temporarily ()
2352 (when (overlayp company-pseudo-tooltip-overlay)
2353 (overlay-put company-pseudo-tooltip-overlay 'invisible nil)
2354 (overlay-put company-pseudo-tooltip-overlay 'line-prefix nil)
2355 (overlay-put company-pseudo-tooltip-overlay 'after-string nil)))
2357 (defun company-pseudo-tooltip-unhide ()
2358 (when company-pseudo-tooltip-overlay
2359 (overlay-put company-pseudo-tooltip-overlay 'invisible t)
2360 ;; Beat outline's folding overlays, at least.
2361 (overlay-put company-pseudo-tooltip-overlay 'priority 1)
2362 ;; No (extra) prefix for the first line.
2363 (overlay-put company-pseudo-tooltip-overlay 'line-prefix "")
2364 (overlay-put company-pseudo-tooltip-overlay 'after-string
2365 (overlay-get company-pseudo-tooltip-overlay 'company-after))
2366 (overlay-put company-pseudo-tooltip-overlay 'window (selected-window))))
2368 (defun company-pseudo-tooltip-guard ()
2369 (buffer-substring-no-properties
2370 (point) (overlay-start company-pseudo-tooltip-overlay)))
2372 (defun company-pseudo-tooltip-frontend (command)
2373 "`company-mode' front-end similar to a tooltip but based on overlays."
2375 (pre-command (company-pseudo-tooltip-hide-temporarily))
2377 (let ((old-height (if (overlayp company-pseudo-tooltip-overlay)
2378 (overlay-get company-pseudo-tooltip-overlay
2381 (new-height (company--pseudo-tooltip-height)))
2382 (unless (and (>= (* old-height new-height) 0)
2383 (>= (abs old-height) (abs new-height))
2384 (equal (company-pseudo-tooltip-guard)
2385 (overlay-get company-pseudo-tooltip-overlay
2388 (company-pseudo-tooltip-show-at-point (- (point)
2389 (length company-prefix)))
2390 (overlay-put company-pseudo-tooltip-overlay
2391 'company-guard (company-pseudo-tooltip-guard))))
2392 (company-pseudo-tooltip-unhide))
2393 (hide (company-pseudo-tooltip-hide)
2394 (setq company-tooltip-offset 0))
2395 (update (when (overlayp company-pseudo-tooltip-overlay)
2396 (company-pseudo-tooltip-edit company-selection)))))
2398 (defun company-pseudo-tooltip-unless-just-one-frontend (command)
2399 "`company-pseudo-tooltip-frontend', but not shown for single candidates."
2400 (unless (and (eq command 'post-command)
2401 (company--show-inline-p))
2402 (company-pseudo-tooltip-frontend command)))
2404 ;;; overlay ;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;
2406 (defvar-local company-preview-overlay nil)
2408 (defun company-preview-show-at-point (pos)
2409 (company-preview-hide)
2411 (setq company-preview-overlay (make-overlay pos (1+ pos)))
2413 (let ((completion (nth company-selection company-candidates)))
2414 (setq completion (propertize completion 'face 'company-preview))
2415 (add-text-properties 0 (length company-common)
2416 '(face company-preview-common) completion)
2418 ;; Add search string
2419 (and company-search-string
2420 (string-match (regexp-quote company-search-string) completion)
2421 (add-text-properties (match-beginning 0)
2423 '(face company-preview-search)
2426 (setq completion (company-strip-prefix completion))
2428 (and (equal pos (point))
2429 (not (equal completion ""))
2430 (add-text-properties 0 1 '(cursor t) completion))
2432 (overlay-put company-preview-overlay 'display
2433 (concat completion (unless (eq pos (point-max))
2434 (buffer-substring pos (1+ pos)))))
2435 (overlay-put company-preview-overlay 'window (selected-window))))
2437 (defun company-preview-hide ()
2438 (when company-preview-overlay
2439 (delete-overlay company-preview-overlay)
2440 (setq company-preview-overlay nil)))
2442 (defun company-preview-frontend (command)
2443 "`company-mode' front-end showing the selection as if it had been inserted."
2445 (`pre-command (company-preview-hide))
2446 (`post-command (company-preview-show-at-point (point)))
2447 (`hide (company-preview-hide))))
2449 (defun company-preview-if-just-one-frontend (command)
2450 "`company-preview-frontend', but only shown for single candidates."
2451 (when (or (not (eq command 'post-command))
2452 (company--show-inline-p))
2453 (company-preview-frontend command)))
2455 (defun company--show-inline-p ()
2456 (and (not (cdr company-candidates))
2458 (string-prefix-p company-prefix company-common
2459 (company-call-backend 'ignore-case))))
2461 ;;; echo ;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;
2463 (defvar-local company-echo-last-msg nil)
2465 (defvar company-echo-timer nil)
2467 (defvar company-echo-delay .01)
2469 (defun company-echo-show (&optional getter)
2471 (setq company-echo-last-msg (funcall getter)))
2472 (let ((message-log-max nil))
2473 (if company-echo-last-msg
2474 (message "%s" company-echo-last-msg)
2477 (defun company-echo-show-soon (&optional getter)
2478 (when company-echo-timer
2479 (cancel-timer company-echo-timer))
2480 (setq company-echo-timer (run-with-timer 0 nil 'company-echo-show getter)))
2482 (defsubst company-echo-show-when-idle (&optional getter)
2483 (when (sit-for company-echo-delay)
2484 (company-echo-show getter)))
2486 (defun company-echo-format ()
2488 (let ((limit (window-width (minibuffer-window)))
2490 ;; Roll to selection.
2491 (candidates (nthcdr company-selection company-candidates))
2492 (i (if company-show-numbers company-selection 99999))
2496 (setq comp (company-reformat (pop candidates))
2497 len (+ len 1 (length comp)))
2501 (setq comp (propertize (format "%d: %s" i comp)
2502 'face 'company-echo))
2505 (add-text-properties 3 (+ 3 (length company-common))
2506 '(face company-echo-common) comp))
2507 (setq comp (propertize comp 'face 'company-echo))
2508 (add-text-properties 0 (length company-common)
2509 '(face company-echo-common) comp))
2511 (setq candidates nil)
2514 (mapconcat 'identity (nreverse msg) " ")))
2516 (defun company-echo-strip-common-format ()
2518 (let ((limit (window-width (minibuffer-window)))
2519 (len (+ (length company-prefix) 2))
2520 ;; Roll to selection.
2521 (candidates (nthcdr company-selection company-candidates))
2522 (i (if company-show-numbers company-selection 99999))
2526 (setq comp (company-strip-prefix (pop candidates))
2527 len (+ len 2 (length comp)))
2530 (setq comp (format "%s (%d)" comp i))
2534 (setq candidates nil)
2535 (push (propertize comp 'face 'company-echo) msg)))
2537 (concat (propertize company-prefix 'face 'company-echo-common) "{"
2538 (mapconcat 'identity (nreverse msg) ", ")
2541 (defun company-echo-hide ()
2542 (unless (equal company-echo-last-msg "")
2543 (setq company-echo-last-msg "")
2544 (company-echo-show)))
2546 (defun company-echo-frontend (command)
2547 "`company-mode' front-end showing the candidates in the echo area."
2549 (`post-command (company-echo-show-soon 'company-echo-format))
2550 (`hide (company-echo-hide))))
2552 (defun company-echo-strip-common-frontend (command)
2553 "`company-mode' front-end showing the candidates in the echo area."
2555 (`post-command (company-echo-show-soon 'company-echo-strip-common-format))
2556 (`hide (company-echo-hide))))
2558 (defun company-echo-metadata-frontend (command)
2559 "`company-mode' front-end showing the documentation in the echo area."
2561 (`post-command (company-echo-show-when-idle 'company-fetch-metadata))
2562 (`hide (company-echo-hide))))
2565 ;;; company.el ends here