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$")
85 "Extensible inline text completion mechanism"
90 (defface company-tooltip
91 '((default :foreground "black")
92 (((class color) (min-colors 88) (background light))
93 (:background "cornsilk"))
94 (((class color) (min-colors 88) (background dark))
95 (:background "yellow")))
96 "Face used for the tooltip.")
98 (defface company-tooltip-selection
99 '((default :inherit company-tooltip)
100 (((class color) (min-colors 88) (background light))
101 (:background "light blue"))
102 (((class color) (min-colors 88) (background dark))
103 (:background "orange1"))
104 (t (:background "green")))
105 "Face used for the selection in the tooltip.")
107 (defface company-tooltip-mouse
108 '((default :inherit highlight))
109 "Face used for the tooltip item under the mouse.")
111 (defface company-tooltip-common
112 '((default :inherit company-tooltip)
113 (((background light))
114 :foreground "darkred")
117 "Face used for the common completion in the tooltip.")
119 (defface company-tooltip-common-selection
120 '((default :inherit company-tooltip-selection)
121 (((background light))
122 :foreground "darkred")
125 "Face used for the selected common completion in the tooltip.")
127 (defface company-tooltip-annotation
128 '((default :inherit company-tooltip)
129 (((background light))
130 :foreground "firebrick4")
133 "Face used for the annotation in the tooltip.")
135 (defface company-scrollbar-fg
136 '((((background light))
137 :background "darkred")
140 "Face used for the tooltip scrollbar thumb.")
142 (defface company-scrollbar-bg
143 '((default :inherit company-tooltip)
144 (((background light))
148 "Face used for the tooltip scrollbar background.")
150 (defface company-preview
151 '((((background light))
152 :inherit company-tooltip-selection)
155 :foreground "wheat"))
156 "Face used for the completion preview.")
158 (defface company-preview-common
159 '((((background light))
160 :inherit company-tooltip-selection)
162 :inherit company-preview
164 "Face used for the common part of the completion preview.")
166 (defface company-preview-search
167 '((((background light))
168 :inherit company-tooltip-common-selection)
170 :inherit company-preview
171 :background "blue1"))
172 "Face used for the search string in the completion preview.")
174 (defface company-echo nil
175 "Face used for completions in the echo area.")
177 (defface company-echo-common
178 '((((background dark)) (:foreground "firebrick1"))
179 (((background light)) (:background "firebrick4")))
180 "Face used for the common part of completions in the echo area.")
182 (defun company-frontends-set (variable value)
184 (let ((remainder value))
185 (setcdr remainder (delq (car remainder) (cdr remainder))))
186 (and (memq 'company-pseudo-tooltip-unless-just-one-frontend value)
187 (memq 'company-pseudo-tooltip-frontend value)
188 (error "Pseudo tooltip frontend cannot be used twice"))
189 (and (memq 'company-preview-if-just-one-frontend value)
190 (memq 'company-preview-frontend value)
191 (error "Preview frontend cannot be used twice"))
192 (and (memq 'company-echo value)
193 (memq 'company-echo-metadata-frontend value)
194 (error "Echo area cannot be used twice"))
195 ;; preview must come last
196 (dolist (f '(company-preview-if-just-one-frontend company-preview-frontend))
198 (setq value (append (delq f value) (list f)))))
199 (set variable value))
201 (defcustom company-frontends '(company-pseudo-tooltip-unless-just-one-frontend
202 company-preview-if-just-one-frontend
203 company-echo-metadata-frontend)
204 "The list of active front-ends (visualizations).
205 Each front-end is a function that takes one argument. It is called with
206 one of the following arguments:
208 `show': When the visualization should start.
210 `hide': When the visualization should end.
212 `update': When the data has been updated.
214 `pre-command': Before every command that is executed while the
215 visualization is active.
217 `post-command': After every command that is executed while the
218 visualization is active.
220 The visualized data is stored in `company-prefix', `company-candidates',
221 `company-common', `company-selection', `company-point' and
222 `company-search-string'."
223 :set 'company-frontends-set
224 :type '(repeat (choice (const :tag "echo" company-echo-frontend)
225 (const :tag "echo, strip common"
226 company-echo-strip-common-frontend)
227 (const :tag "show echo meta-data in echo"
228 company-echo-metadata-frontend)
229 (const :tag "pseudo tooltip"
230 company-pseudo-tooltip-frontend)
231 (const :tag "pseudo tooltip, multiple only"
232 company-pseudo-tooltip-unless-just-one-frontend)
233 (const :tag "preview" company-preview-frontend)
234 (const :tag "preview, unique only"
235 company-preview-if-just-one-frontend)
236 (function :tag "custom function" nil))))
238 (defcustom company-tooltip-limit 10
239 "The maximum number of candidates in the tooltip"
242 (defcustom company-tooltip-minimum 6
243 "The minimum height of the tooltip.
244 If this many lines are not available, prefer to display the tooltip above."
247 (defcustom company-tooltip-minimum-width 0
248 "The minimum width of the tooltip's inner area.
249 This doesn't include the margins and the scroll bar."
252 (defcustom company-tooltip-margin 1
253 "Width of margin columns to show around the toolip."
256 (defcustom company-tooltip-offset-display 'scrollbar
257 "Method using which the tooltip displays scrolling position.
258 `scrollbar' means draw a scrollbar to the right of the items.
259 `lines' means wrap items in lines with \"before\" and \"after\" counters."
260 :type '(choice (const :tag "Scrollbar" scrollbar)
261 (const :tag "Two lines" lines)))
263 (defcustom company-tooltip-align-annotations nil
264 "When non-nil, align annotations to the right tooltip border."
267 (defvar company-safe-backends
268 '((company-abbrev . "Abbrev")
269 (company-bbdb . "BBDB")
270 (company-capf . "completion-at-point-functions")
271 (company-clang . "Clang")
272 (company-cmake . "CMake")
273 (company-css . "CSS")
274 (company-dabbrev . "dabbrev for plain text")
275 (company-dabbrev-code . "dabbrev for code")
276 (company-eclim . "Eclim (an Eclipse interface)")
277 (company-elisp . "Emacs Lisp")
278 (company-etags . "etags")
279 (company-files . "Files")
280 (company-gtags . "GNU Global")
281 (company-ispell . "Ispell")
282 (company-keywords . "Programming language keywords")
283 (company-nxml . "nxml")
284 (company-oddmuse . "Oddmuse")
285 (company-pysmell . "PySmell")
286 (company-ropemacs . "ropemacs")
287 (company-semantic . "Semantic")
288 (company-tempo . "Tempo templates")
289 (company-xcode . "Xcode")))
290 (put 'company-safe-backends 'risky-local-variable t)
292 (defun company-safe-backends-p (backends)
293 (and (consp backends)
294 (not (cl-dolist (backend backends)
295 (unless (if (consp backend)
296 (company-safe-backends-p backend)
297 (assq backend company-safe-backends))
300 (defcustom company-backends `(,@(unless (version< "24.3.50" emacs-version)
301 (list 'company-elisp))
303 company-nxml company-css
304 company-eclim company-semantic company-clang
305 company-xcode company-ropemacs company-cmake
307 (company-dabbrev-code company-gtags company-etags
309 company-oddmuse company-files company-dabbrev)
310 "The list of active back-ends (completion engines).
312 `company-begin-backend' can be used to start a specific back-end,
313 `company-other-backend' will skip to the next matching back-end in the list.
315 Each back-end is a function that takes a variable number of arguments.
316 The first argument is the command requested from the back-end. It is one
319 `prefix': The back-end should return the text to be completed. It must be
320 text immediately before point. Returning nil passes control to the next
321 back-end. The function should return `stop' if it should complete but
322 cannot \(e.g. if it is in the middle of a string\). Instead of a string,
323 the back-end may return a cons where car is the prefix and cdr is used in
324 `company-minimum-prefix-length' test. It must be either number or t, and
325 in the latter case the test automatically succeeds.
327 `candidates': The second argument is the prefix to be completed. The
328 return value should be a list of candidates that match the prefix.
330 Non-prefix matches are also supported (candidates that don't start with the
331 prefix, but match it in some backend-defined way). Backends that use this
332 feature must disable cache (return t to `no-cache') and should also respond
337 `sorted': Return t here to indicate that the candidates are sorted and will
338 not need to be sorted again.
340 `duplicates': If non-nil, company will take care of removing duplicates
343 `no-cache': Usually company doesn't ask for candidates again as completion
344 progresses, unless the back-end returns t for this command. The second
345 argument is the latest prefix.
347 `meta': The second argument is a completion candidate. Return a (short)
348 documentation string for it.
350 `doc-buffer': The second argument is a completion candidate. Return a
351 buffer with documentation for it. Preferably use `company-doc-buffer',
353 `location': The second argument is a completion candidate. Return the cons
354 of buffer and buffer location, or of file and line number where the
355 completion candidate was defined.
357 `annotation': The second argument is a completion candidate. Return a
358 string to be displayed inline with the candidate in the popup. If
359 duplicates are removed by company, candidates with equal string values will
360 be kept if they have different annotations. For that to work properly,
361 backends should store the related information on candidates using text
364 `match': The second argument is a completion candidate. Backends that
365 provide non-prefix completions should return the position of the end of
366 text in the candidate that matches `prefix'. It will be used when
369 `require-match': If this returns t, the user is not allowed to enter
370 anything not offered as a candidate. Use with care! The default value nil
371 gives the user that choice with `company-require-match'. Return value
372 `never' overrides that option the other way around.
374 `init': Called once for each buffer. The back-end can check for external
375 programs and files and load any required libraries. Raising an error here
376 will show up in message log once, and the back-end will not be used for
379 `post-completion': Called after a completion candidate has been inserted
380 into the buffer. The second argument is the candidate. Can be used to
381 modify it, e.g. to expand a snippet.
383 The back-end should return nil for all commands it does not support or
384 does not know about. It should also be callable interactively and use
385 `company-begin-backend' to start itself in that case.
389 An element of `company-backends' can also itself be a list of back-ends,
390 then it's considered to be a \"grouped\" back-end.
392 When possible, commands taking a candidate as an argument are dispatched to
393 the back-end it came from. In other cases, the first non-nil value among
394 all the back-ends is returned.
396 The latter is the case for the `prefix' command. But if the group contains
397 the keyword `:with', the back-ends after it are ignored for this command.
399 The completions from back-ends in a group are merged (but only from those
400 that return the same `prefix').
402 Asynchronous back-ends:
404 The return value of each command can also be a cons (:async . FETCHER)
405 where FETCHER is a function of one argument, CALLBACK. When the data
406 arrives, FETCHER must call CALLBACK and pass it the appropriate return
407 value, as described above.
409 True asynchronous operation is only supported for command `candidates', and
410 only during idle completion. Other commands will block the user interface,
411 even if the back-end uses the asynchronous calling convention."
415 ,@(mapcar (lambda (b) `(const :tag ,(cdr b) ,(car b)))
416 company-safe-backends)
417 (symbol :tag "User defined")
418 (repeat :tag "Merged Back-ends"
419 (choice :tag "Back-end"
420 ,@(mapcar (lambda (b)
421 `(const :tag ,(cdr b) ,(car b)))
422 company-safe-backends)
423 (const :tag "With" :with)
424 (symbol :tag "User defined"))))))
426 (put 'company-backends 'safe-local-variable 'company-safe-backends-p)
428 (defcustom company-transformers nil
429 "Functions to change the list of candidates received from backends,
430 after sorting and removal of duplicates (if appropriate).
431 Each function gets called with the return value of the previous one."
433 (const :tag "None" nil)
434 (const :tag "Sort by occurrence" (company-sort-by-occurrence))
435 (repeat :tag "User defined" (function))))
437 (defcustom company-completion-started-hook nil
438 "Hook run when company starts completing.
439 The hook is called with one argument that is non-nil if the completion was
443 (defcustom company-completion-cancelled-hook nil
444 "Hook run when company cancels completing.
445 The hook is called with one argument that is non-nil if the completion was
449 (defcustom company-completion-finished-hook nil
450 "Hook run when company successfully completes.
451 The hook is called with the selected candidate as an argument.
453 If you indend to use it to post-process candidates from a specific
454 back-end, consider using the `post-completion' command instead."
457 (defcustom company-minimum-prefix-length 3
458 "The minimum prefix length for idle completion."
459 :type '(integer :tag "prefix length"))
461 (defcustom company-abort-manual-when-too-short nil
462 "If enabled, cancel a manually started completion when the prefix gets
463 shorter than both `company-minimum-prefix-length' and the length of the
464 prefix it was started from."
467 (defcustom company-require-match 'company-explicit-action-p
468 "If enabled, disallow non-matching input.
469 This can be a function do determine if a match is required.
471 This can be overridden by the back-end, if it returns t or `never' to
472 `require-match'. `company-auto-complete' also takes precedence over this."
473 :type '(choice (const :tag "Off" nil)
474 (function :tag "Predicate function")
475 (const :tag "On, if user interaction took place"
476 'company-explicit-action-p)
477 (const :tag "On" t)))
479 (defcustom company-auto-complete nil
480 "Determines when to auto-complete.
481 If this is enabled, all characters from `company-auto-complete-chars'
482 trigger insertion of the selected completion candidate.
483 This can also be a function."
484 :type '(choice (const :tag "Off" nil)
485 (function :tag "Predicate function")
486 (const :tag "On, if user interaction took place"
487 'company-explicit-action-p)
488 (const :tag "On" t)))
490 (defcustom company-auto-complete-chars '(?\ ?\) ?.)
491 "Determines which characters trigger auto-completion.
492 See `company-auto-complete'. If this is a string, each string character
493 tiggers auto-completion. If it is a list of syntax description characters (see
494 `modify-syntax-entry'), all characters with that syntax auto-complete.
496 This can also be a function, which is called with the new input and should
497 return non-nil if company should auto-complete.
499 A character that is part of a valid candidate never triggers auto-completion."
500 :type '(choice (string :tag "Characters")
502 (const :tag "Whitespace" ?\ )
503 (const :tag "Symbol" ?_)
504 (const :tag "Opening parentheses" ?\()
505 (const :tag "Closing parentheses" ?\))
506 (const :tag "Word constituent" ?w)
507 (const :tag "Punctuation." ?.)
508 (const :tag "String quote." ?\")
509 (const :tag "Paired delimiter." ?$)
510 (const :tag "Expression quote or prefix operator." ?\')
511 (const :tag "Comment starter." ?<)
512 (const :tag "Comment ender." ?>)
513 (const :tag "Character-quote." ?/)
514 (const :tag "Generic string fence." ?|)
515 (const :tag "Generic comment fence." ?!))
516 (function :tag "Predicate function")))
518 (defcustom company-idle-delay .5
519 "The idle delay in seconds until completion starts automatically.
520 A value of nil means no idle completion, t means show candidates
521 immediately when a prefix of `company-minimum-prefix-length' is reached."
522 :type '(choice (const :tag "never (nil)" nil)
523 (const :tag "immediate (t)" t)
524 (number :tag "seconds")))
526 (defcustom company-begin-commands '(self-insert-command org-self-insert-command)
527 "A list of commands after which idle completion is allowed.
528 If this is t, it can show completions after any command. See
529 `company-idle-delay'.
531 Alternatively, any command with a non-nil `company-begin' property is
532 treated as if it was on this list."
533 :type '(choice (const :tag "Any command" t)
534 (const :tag "Self insert command" '(self-insert-command))
535 (repeat :tag "Commands" function)))
537 (defcustom company-continue-commands '(not save-buffer save-some-buffers
538 save-buffers-kill-terminal
539 save-buffers-kill-emacs)
540 "A list of commands that are allowed during completion.
541 If this is t, or if `company-begin-commands' is t, any command is allowed.
542 Otherwise, the value must be a list of symbols. If it starts with `not',
543 the cdr is the list of commands that abort completion. Otherwise, all
544 commands except those in that list, or in `company-begin-commands', or
545 commands in the `company-' namespace, abort completion."
546 :type '(choice (const :tag "Any command" t)
547 (cons :tag "Any except"
549 (repeat :tag "Commands" function))
550 (repeat :tag "Commands" function)))
552 (defcustom company-show-numbers nil
553 "If enabled, show quick-access numbers for the first ten candidates."
554 :type '(choice (const :tag "off" nil)
555 (const :tag "on" t)))
557 (defcustom company-selection-wrap-around nil
558 "If enabled, selecting item before first or after last wraps around."
559 :type '(choice (const :tag "off" nil)
560 (const :tag "on" t)))
562 (defvar company-end-of-buffer-workaround t
563 "Work around a visualization bug when completing at the end of the buffer.
564 The work-around consists of adding a newline.")
566 (defvar company-async-wait 0.03
567 "Pause between checks to see if the value's been set when turning an
568 asynchronous call into synchronous.")
570 (defvar company-async-timeout 2
571 "Maximum wait time for a value to be set during asynchronous call.")
573 ;;; mode ;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;
575 (defvar company-mode-map (make-sparse-keymap)
576 "Keymap used by `company-mode'.")
578 (defvar company-active-map
579 (let ((keymap (make-sparse-keymap)))
580 (define-key keymap "\e\e\e" 'company-abort)
581 (define-key keymap "\C-g" 'company-abort)
582 (define-key keymap (kbd "M-n") 'company-select-next)
583 (define-key keymap (kbd "M-p") 'company-select-previous)
584 (define-key keymap (kbd "<down>") 'company-select-next-or-abort)
585 (define-key keymap (kbd "<up>") 'company-select-previous-or-abort)
586 (define-key keymap [down-mouse-1] 'ignore)
587 (define-key keymap [down-mouse-3] 'ignore)
588 (define-key keymap [mouse-1] 'company-complete-mouse)
589 (define-key keymap [mouse-3] 'company-select-mouse)
590 (define-key keymap [up-mouse-1] 'ignore)
591 (define-key keymap [up-mouse-3] 'ignore)
592 (define-key keymap [return] 'company-complete-selection)
593 (define-key keymap (kbd "RET") 'company-complete-selection)
594 (define-key keymap [tab] 'company-complete-common)
595 (define-key keymap (kbd "TAB") 'company-complete-common)
596 (define-key keymap (kbd "<f1>") 'company-show-doc-buffer)
597 (define-key keymap "\C-w" 'company-show-location)
598 (define-key keymap "\C-s" 'company-search-candidates)
599 (define-key keymap "\C-\M-s" 'company-filter-candidates)
601 (define-key keymap (vector (+ (aref (kbd "M-0") 0) i))
604 (company-complete-number ,(if (zerop i) 10 i)))))
607 "Keymap that is enabled during an active completion.")
609 (defvar company--disabled-backends nil)
611 (defun company-init-backend (backend)
612 (and (symbolp backend)
613 (not (fboundp backend))
614 (ignore-errors (require backend nil t)))
619 (funcall backend 'init)
620 (put backend 'company-init t))
622 (put backend 'company-init 'failed)
623 (unless (memq backend company--disabled-backends)
624 (message "Company back-end '%s' could not be initialized:\n%s"
625 backend (error-message-string err)))
626 (cl-pushnew backend company--disabled-backends)
628 ;; No initialization for lambdas.
629 ((functionp backend) t)
630 (t ;; Must be a list.
631 (cl-dolist (b backend)
633 (company-init-backend b))))))
635 (defvar company-default-lighter " company")
637 (defvar company-lighter company-default-lighter)
638 (make-variable-buffer-local 'company-lighter)
641 (define-minor-mode company-mode
642 "\"complete anything\"; is an in-buffer completion framework.
643 Completion starts automatically, depending on the values
644 `company-idle-delay' and `company-minimum-prefix-length'.
646 Completion can be controlled with the commands:
647 `company-complete-common', `company-complete-selection', `company-complete',
648 `company-select-next', `company-select-previous'. If these commands are
649 called before `company-idle-delay', completion will also start.
651 Completions can be searched with `company-search-candidates' or
652 `company-filter-candidates'. These can be used while completion is
655 The completion data is retrieved using `company-backends' and displayed
656 using `company-frontends'. If you want to start a specific back-end, call
657 it interactively or use `company-begin-backend'.
659 regular keymap (`company-mode-map'):
662 keymap during active completions (`company-active-map'):
664 \\{company-active-map}"
665 nil company-lighter company-mode-map
668 (add-hook 'pre-command-hook 'company-pre-command nil t)
669 (add-hook 'post-command-hook 'company-post-command nil t)
670 (mapc 'company-init-backend company-backends))
671 (remove-hook 'pre-command-hook 'company-pre-command t)
672 (remove-hook 'post-command-hook 'company-post-command t)
674 (kill-local-variable 'company-point)))
676 (defcustom company-global-modes t
677 "Modes for which `company-mode' mode is turned on by `global-company-mode'.
678 If nil, means no modes. If t, then all major modes have it turned on.
679 If a list, it should be a list of `major-mode' symbol names for which
680 `company-mode' should be automatically turned on. The sense of the list is
681 negated if it begins with `not'. For example:
683 means that `company-mode' is turned on for buffers in C and C++ modes only.
685 means that `company-mode' is always turned on except in `message-mode' buffers."
686 :type '(choice (const :tag "none" nil)
688 (set :menu-tag "mode specific" :tag "modes"
690 (const :tag "Except" not)
691 (repeat :inline t (symbol :tag "mode")))))
694 (define-globalized-minor-mode global-company-mode company-mode company-mode-on)
696 (defun company-mode-on ()
697 (when (and (not (or noninteractive (eq (aref (buffer-name) 0) ?\s)))
698 (cond ((eq company-global-modes t)
700 ((eq (car-safe company-global-modes) 'not)
701 (not (memq major-mode (cdr company-global-modes))))
702 (t (memq major-mode company-global-modes))))
705 (defsubst company-assert-enabled ()
707 (company-uninstall-map)
708 (error "Company not enabled")))
710 ;;; keymaps ;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;
712 (defvar company-my-keymap nil)
713 (make-variable-buffer-local 'company-my-keymap)
715 (defvar company-emulation-alist '((t . nil)))
717 (defsubst company-enable-overriding-keymap (keymap)
718 (company-uninstall-map)
719 (setq company-my-keymap keymap))
721 (defun company-ensure-emulation-alist ()
722 (unless (eq 'company-emulation-alist (car emulation-mode-map-alists))
723 (setq emulation-mode-map-alists
724 (cons 'company-emulation-alist
725 (delq 'company-emulation-alist emulation-mode-map-alists)))))
727 (defun company-install-map ()
728 (unless (or (cdar company-emulation-alist)
729 (null company-my-keymap))
730 (setf (cdar company-emulation-alist) company-my-keymap)))
732 (defun company-uninstall-map ()
733 (setf (cdar company-emulation-alist) nil))
736 ;; Emacs calculates the active keymaps before reading the event. That means we
737 ;; cannot change the keymap from a timer. So we send a bogus command.
738 ;; XXX: Seems not to be needed anymore in Emacs 24.4
739 (defun company-ignore ()
741 (setq this-command last-command))
743 (global-set-key '[31415926] 'company-ignore)
745 (defun company-input-noop ()
746 (push 31415926 unread-command-events))
748 (defun company--column (&optional pos)
750 (when pos (goto-char pos))
754 (narrow-to-region (point) (point-max))
755 (let ((prefix (get-text-property (point) 'line-prefix)))
756 (if prefix (length prefix) 0)))
759 (defun company--row (&optional pos)
761 (when pos (goto-char pos))
762 (count-screen-lines (window-start)
763 (progn (vertical-motion 0) (point)))))
765 ;;; backends ;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;
767 (defvar company-backend nil)
768 (make-variable-buffer-local 'company-backend)
770 (defun company-grab (regexp &optional expression limit)
771 (when (looking-back regexp limit)
772 (or (match-string-no-properties (or expression 0)) "")))
774 (defun company-grab-line (regexp &optional expression)
775 (company-grab regexp expression (point-at-bol)))
777 (defun company-grab-symbol ()
778 (if (looking-at "\\_>")
779 (buffer-substring (point) (save-excursion (skip-syntax-backward "w_")
781 (unless (and (char-after) (memq (char-syntax (char-after)) '(?w ?_)))
784 (defun company-grab-word ()
785 (if (looking-at "\\>")
786 (buffer-substring (point) (save-excursion (skip-syntax-backward "w")
788 (unless (and (char-after) (eq (char-syntax (char-after)) ?w))
791 (defun company-grab-symbol-cons (idle-begin-after-re &optional max-len)
792 (let ((symbol (company-grab-symbol)))
795 (forward-char (- (length symbol)))
796 (if (looking-back idle-begin-after-re (if max-len
798 (line-beginning-position)))
802 (defun company-in-string-or-comment ()
803 (let ((ppss (syntax-ppss)))
804 (or (car (setq ppss (nthcdr 3 ppss)))
805 (car (setq ppss (cdr ppss)))
808 (defun company-call-backend (&rest args)
809 (company--force-sync #'company-call-backend-raw args company-backend))
811 (defun company--force-sync (fun args backend)
812 (let ((value (apply fun args)))
813 (if (not (eq (car-safe value) :async))
816 (start (time-to-seconds)))
818 (lambda (result) (setq res result)))
819 (while (eq res 'trash)
820 (if (> (- (time-to-seconds) start) company-async-timeout)
821 (error "Company: Back-end %s async timeout with args %s"
823 (sleep-for company-async-wait)))
826 (defun company-call-backend-raw (&rest args)
828 (if (functionp company-backend)
829 (apply company-backend args)
830 (apply #'company--multi-backend-adapter company-backend args))
831 (error (error "Company: Back-end %s error \"%s\" with args %s"
832 company-backend (error-message-string err) args))))
834 (defun company--multi-backend-adapter (backends command &rest args)
835 (let ((backends (cl-loop for b in backends
836 when (not (and (symbolp b)
837 (eq 'failed (get b 'company-init))))
840 (if (eq command 'prefix)
841 (butlast backends (length (member :with backends)))
842 (delq :with backends)))
845 (company--multi-backend-adapter-candidates backends (car args)))
848 ((or `prefix `ignore-case `no-cache `require-match)
850 (cl-dolist (backend backends)
851 (when (setq value (company--force-sync
852 backend (cons command args) backend))
853 (cl-return value)))))
855 (let ((arg (car args)))
856 (when (> (length arg) 0)
857 (let ((backend (or (get-text-property 0 'company-backend arg)
859 (apply backend command args))))))))
861 (defun company--multi-backend-adapter-candidates (backends prefix)
862 (let ((pairs (cl-loop for backend in (cdr backends)
863 when (equal (funcall backend 'prefix)
865 collect (cons (funcall backend 'candidates prefix)
870 (propertize str 'company-backend b))
872 (when (equal (funcall (car backends) 'prefix) prefix)
873 ;; Small perf optimization: don't tag the candidates received
874 ;; from the first backend in the group.
875 (push (cons (funcall (car backends) 'candidates prefix)
878 (company--merge-async pairs (lambda (values) (apply #'append values)))))
880 (defun company--merge-async (pairs merger)
881 (let ((async (cl-loop for pair in pairs
883 (eq :async (car-safe (car pair))))))
885 (funcall merger (cl-loop for (val . mapper) in pairs
886 collect (funcall mapper val)))
897 (let ((val (car pair))
899 (if (not (eq :async (car-safe val)))
900 (push (funcall mapper val) lst)
904 (push fetcher pending)
907 (setq pending (delq fetcher pending))
908 (setcar cell (funcall mapper res))
909 (funcall finisher)))))))))))))
911 ;;; completion mechanism ;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;
913 (defvar company-prefix nil)
914 (make-variable-buffer-local 'company-prefix)
916 (defvar company-candidates nil)
917 (make-variable-buffer-local 'company-candidates)
919 (defvar company-candidates-length nil)
920 (make-variable-buffer-local 'company-candidates-length)
922 (defvar company-candidates-cache nil)
923 (make-variable-buffer-local 'company-candidates-cache)
925 (defvar company-candidates-predicate nil)
926 (make-variable-buffer-local 'company-candidates-predicate)
928 (defvar company-common nil)
929 (make-variable-buffer-local 'company-common)
931 (defvar company-selection 0)
932 (make-variable-buffer-local 'company-selection)
934 (defvar company-selection-changed nil)
935 (make-variable-buffer-local 'company-selection-changed)
937 (defvar company--manual-action nil
938 "Non-nil, if manual completion took place.")
939 (make-variable-buffer-local 'company--manual-action)
941 (defvar company--manual-prefix nil)
942 (make-variable-buffer-local 'company--manual-prefix)
944 (defvar company--auto-completion nil
945 "Non-nil when current candidate is being inserted automatically.
946 Controlled by `company-auto-complete'.")
948 (defvar company--point-max nil)
949 (make-variable-buffer-local 'company--point-max)
951 (defvar company-point nil)
952 (make-variable-buffer-local 'company-point)
954 (defvar company-timer nil)
956 (defvar company-added-newline nil)
957 (make-variable-buffer-local 'company-added-newline)
959 (defsubst company-strip-prefix (str)
960 (substring str (length company-prefix)))
962 (defun company--insert-candidate (candidate)
963 (setq candidate (substring-no-properties candidate))
964 ;; XXX: Return value we check here is subject to change.
965 (if (eq (company-call-backend 'ignore-case) 'keep-prefix)
966 (insert (company-strip-prefix candidate))
967 (delete-region (- (point) (length company-prefix)) (point))
970 (defmacro company-with-candidate-inserted (candidate &rest body)
971 "Evaluate BODY with CANDIDATE temporarily inserted.
972 This is a tool for back-ends that need candidates inserted before they
973 can retrieve meta-data for them."
975 `(let ((inhibit-modification-hooks t)
976 (inhibit-point-motion-hooks t)
977 (modified-p (buffer-modified-p)))
978 (company--insert-candidate ,candidate)
981 (delete-region company-point (point)))))
983 (defun company-explicit-action-p ()
984 "Return whether explicit completion action was taken by the user."
985 (or company--manual-action
986 company-selection-changed))
988 (defun company-reformat (candidate)
989 ;; company-ispell needs this, because the results are always lower-case
990 ;; It's mory efficient to fix it only when they are displayed.
991 ;; FIXME: Adopt the current text's capitalization instead?
992 (if (eq (company-call-backend 'ignore-case) 'keep-prefix)
993 (concat company-prefix (substring candidate (length company-prefix)))
996 (defun company--should-complete ()
997 (and (not (or buffer-read-only overriding-terminal-local-map
998 overriding-local-map))
999 ;; Check if in the middle of entering a key combination.
1000 (or (equal (this-command-keys-vector) [])
1001 (not (keymapp (key-binding (this-command-keys-vector)))))
1002 (eq company-idle-delay t)
1003 (or (eq t company-begin-commands)
1004 (memq this-command company-begin-commands)
1005 (and (symbolp this-command) (get this-command 'company-begin)))
1006 (not (and transient-mark-mode mark-active))))
1008 (defun company--should-continue ()
1009 (or (eq t company-begin-commands)
1010 (eq t company-continue-commands)
1011 (if (eq 'not (car company-continue-commands))
1012 (not (memq this-command (cdr company-continue-commands)))
1013 (or (memq this-command company-begin-commands)
1014 (memq this-command company-continue-commands)
1015 (string-match-p "\\`company-" (symbol-name this-command))))))
1017 (defun company-call-frontends (command)
1018 (dolist (frontend company-frontends)
1020 (funcall frontend command)
1021 (error (error "Company: Front-end %s error \"%s\" on command %s"
1022 frontend (error-message-string err) command)))))
1024 (defun company-set-selection (selection &optional force-update)
1026 (if company-selection-wrap-around
1027 (mod selection company-candidates-length)
1028 (max 0 (min (1- company-candidates-length) selection))))
1029 (when (or force-update (not (equal selection company-selection)))
1030 (setq company-selection selection
1031 company-selection-changed t)
1032 (company-call-frontends 'update)))
1034 (defun company-apply-predicate (candidates predicate)
1036 (dolist (c candidates)
1037 (when (funcall predicate c)
1041 (defun company-update-candidates (candidates)
1042 (setq company-candidates-length (length candidates))
1043 (if (> company-selection 0)
1044 ;; Try to restore the selection
1045 (let ((selected (nth company-selection company-candidates)))
1046 (setq company-selection 0
1047 company-candidates candidates)
1049 (while (and candidates (string< (pop candidates) selected))
1050 (cl-incf company-selection))
1052 ;; Make sure selection isn't out of bounds.
1053 (setq company-selection (min (1- company-candidates-length)
1054 company-selection)))))
1055 (setq company-selection 0
1056 company-candidates candidates))
1058 (push (cons company-prefix company-candidates) company-candidates-cache)
1059 ;; Calculate common.
1060 (let ((completion-ignore-case (company-call-backend 'ignore-case)))
1061 ;; We want to support non-prefix completion, so filtering is the
1062 ;; responsibility of each respective backend, not ours.
1063 ;; On the other hand, we don't want to replace non-prefix input in
1064 ;; `company-complete-common'.
1065 (setq company-common
1066 (if (cdr company-candidates)
1067 (let ((common (try-completion company-prefix company-candidates)))
1069 ;; Mulple equal strings, probably with different
1073 (car company-candidates)))))
1075 (defun company-calculate-candidates (prefix)
1076 (let ((candidates (cdr (assoc prefix company-candidates-cache)))
1077 (ignore-case (company-call-backend 'ignore-case)))
1079 (when company-candidates-cache
1080 (let ((len (length prefix))
1081 (completion-ignore-case ignore-case)
1083 (cl-dotimes (i (1+ len))
1084 (when (setq prev (cdr (assoc (substring prefix 0 (- len i))
1085 company-candidates-cache)))
1086 (setq candidates (all-completions prefix prev))
1088 ;; no cache match, call back-end
1090 (company--process-candidates
1091 (company--fetch-candidates prefix))))
1092 (setq candidates (company--transform-candidates candidates))
1094 (if (or (cdr candidates)
1095 (not (eq t (compare-strings (car candidates) nil nil
1096 prefix nil nil ignore-case))))
1098 ;; Already completed and unique; don't start.
1101 (defun company--fetch-candidates (prefix)
1102 (let ((c (if company--manual-action
1103 (company-call-backend 'candidates prefix)
1104 (company-call-backend-raw 'candidates prefix)))
1106 (if (not (eq (car c) :async))
1108 (let ((buf (current-buffer))
1109 (win (selected-window))
1110 (tick (buffer-chars-modified-tick))
1112 (backend company-backend))
1115 (lambda (candidates)
1116 (if (not (and candidates (eq res 'done)))
1117 ;; Fetcher called us right back.
1118 (setq res candidates)
1119 (setq company-backend backend
1120 company-candidates-cache
1122 (company--process-candidates
1124 (company-idle-begin buf win tick pt)))))
1125 ;; FIXME: Relying on the fact that the callers
1126 ;; will interpret nil as "do nothing" is shaky.
1127 ;; A throw-catch would be one possible improvement.
1129 (progn (setq res 'done) nil)))))
1131 (defun company--process-candidates (candidates)
1132 (when company-candidates-predicate
1134 (company-apply-predicate candidates
1135 company-candidates-predicate)))
1136 (unless (company-call-backend 'sorted)
1137 (setq candidates (sort candidates 'string<)))
1138 (when (company-call-backend 'duplicates)
1139 (company--strip-duplicates candidates))
1142 (defun company--strip-duplicates (candidates)
1143 (let ((c2 candidates))
1146 (let ((str (car c2))
1149 (while (let ((str2 (car c2)))
1150 (if (not (equal str str2))
1152 (when (eq anno 'unk)
1153 (setq anno (company-call-backend
1156 (company-call-backend
1157 'annotation str2))))
1161 (defun company--transform-candidates (candidates)
1162 (let ((c candidates))
1163 (dolist (tr company-transformers)
1164 (setq c (funcall tr c)))
1167 (defun company-sort-by-occurrence (candidates)
1168 "Sort CANDIDATES according to their occurrences.
1169 Searches for each in the currently visible part of the current buffer and
1170 gives priority to the closest ones above point, then closest ones below
1171 point. The rest of the list is appended unchanged.
1172 Keywords and function definition names are ignored."
1179 (progn (forward-line 0)
1180 (search-backward candidate (window-start) t)))
1182 (search-forward candidate (window-end) t)))
1183 (let ((beg (match-beginning 0))
1184 (end (match-end 0)))
1185 (when (save-excursion
1187 (and (not (memq (get-text-property (point) 'face)
1188 '(font-lock-function-name-face
1189 font-lock-keyword-face)))
1190 (let* ((prefix (company-call-backend 'prefix))
1191 (prefix (or (car-safe prefix) prefix)))
1192 (and (stringp prefix)
1193 (= (length prefix) (- end beg))))))
1194 (push (cons candidate (if (< beg (point))
1196 (- beg (window-start))))
1201 (mapcar #'car (sort occurs (lambda (e1 e2) (<= (cdr e1) (cdr e2)))))
1204 (defun company-idle-begin (buf win tick pos)
1205 (and (eq buf (current-buffer))
1206 (eq win (selected-window))
1207 (eq tick (buffer-chars-modified-tick))
1209 (when (company-auto-begin)
1210 (when (version< emacs-version "24.3.50")
1211 (company-input-noop))
1212 (company-post-command))))
1214 (defun company-auto-begin ()
1216 (not company-candidates)
1217 (let ((company-idle-delay t)
1218 (company-begin-commands t))
1219 (condition-case-unless-debug err
1221 (error (message "Company: An error occurred in auto-begin")
1222 (message "%s" (error-message-string err))
1224 (quit (company-cancel)))))
1225 (unless company-candidates
1226 (setq company-backend nil))
1227 ;; Return non-nil if active.
1230 (defun company-manual-begin ()
1232 (company-assert-enabled)
1233 (setq company--manual-action t)
1235 (let ((company-minimum-prefix-length 0))
1236 (company-auto-begin))
1237 (unless company-candidates
1238 (setq company--manual-action nil))))
1240 (defun company-other-backend (&optional backward)
1241 (interactive (list current-prefix-arg))
1242 (company-assert-enabled)
1243 (let* ((after (if company-backend
1244 (cdr (member company-backend company-backends))
1246 (before (cdr (member company-backend (reverse company-backends))))
1248 (append before (reverse after))
1249 (append after (reverse before)))))
1251 (cl-dolist (backend next)
1252 (when (ignore-errors (company-begin-backend backend))
1254 (unless company-candidates
1255 (error "No other back-end")))
1257 (defun company-require-match-p ()
1258 (let ((backend-value (company-call-backend 'require-match)))
1259 (or (eq backend-value t)
1260 (and (not (eq backend-value 'never))
1261 (if (functionp company-require-match)
1262 (funcall company-require-match)
1263 (eq company-require-match t))))))
1265 (defun company-auto-complete-p (input)
1266 "Return non-nil, if input starts with punctuation or parentheses."
1267 (and (if (functionp company-auto-complete)
1268 (funcall company-auto-complete)
1269 company-auto-complete)
1270 (if (functionp company-auto-complete-chars)
1271 (funcall company-auto-complete-chars input)
1272 (if (consp company-auto-complete-chars)
1273 (memq (char-syntax (string-to-char input))
1274 company-auto-complete-chars)
1275 (string-match (substring input 0 1) company-auto-complete-chars)))))
1277 (defun company--incremental-p ()
1278 (and (> (point) company-point)
1279 (> (point-max) company--point-max)
1280 (not (eq this-command 'backward-delete-char-untabify))
1281 (equal (buffer-substring (- company-point (length company-prefix))
1285 (defun company--continue-failed ()
1286 (let ((input (buffer-substring-no-properties (point) company-point)))
1288 ((company-auto-complete-p input)
1291 (goto-char company-point)
1292 (let ((company--auto-completion t))
1293 (company-complete-selection))
1295 ((company-require-match-p)
1296 ;; wrong incremental input, but required match
1297 (delete-char (- (length input)))
1299 (message "Matching input is required")
1301 ((equal company-prefix (car company-candidates))
1302 ;; last input was actually success
1303 (company-cancel company-prefix))
1304 (t (company-cancel)))))
1306 (defun company--good-prefix-p (prefix)
1307 (and (stringp (or (car-safe prefix) prefix)) ;excludes 'stop
1308 (or (eq (cdr-safe prefix) t)
1309 (let ((len (or (cdr-safe prefix) (length prefix))))
1310 (if company--manual-prefix
1311 (or (not company-abort-manual-when-too-short)
1312 ;; Must not be less than minimum or initial length.
1313 (>= len (min company-minimum-prefix-length
1314 (length company--manual-prefix))))
1315 (>= len company-minimum-prefix-length))))))
1317 (defun company--continue ()
1318 (when (company-call-backend 'no-cache company-prefix)
1319 ;; Don't complete existing candidates, fetch new ones.
1320 (setq company-candidates-cache nil))
1321 (let* ((new-prefix (company-call-backend 'prefix))
1322 (c (when (and (company--good-prefix-p new-prefix)
1323 (setq new-prefix (or (car-safe new-prefix) new-prefix))
1324 (= (- (point) (length new-prefix))
1325 (- company-point (length company-prefix))))
1326 (company-calculate-candidates new-prefix))))
1329 ;; t means complete/unique.
1330 (company-cancel new-prefix))
1332 ;; incremental match
1333 (setq company-prefix new-prefix)
1334 (company-update-candidates c)
1336 ((not (company--incremental-p))
1338 (t (company--continue-failed)))))
1340 (defun company--begin-new ()
1342 (cl-dolist (backend (if company-backend
1343 ;; prefer manual override
1344 (list company-backend)
1347 (if (or (symbolp backend)
1348 (functionp backend))
1349 (when (or (not (symbolp backend))
1350 (eq t (get backend 'company-init))
1351 (unless (get backend 'company-init)
1352 (company-init-backend backend)))
1353 (funcall backend 'prefix))
1354 (company--multi-backend-adapter backend 'prefix)))
1356 (when (company--good-prefix-p prefix)
1357 (setq prefix (or (car-safe prefix) prefix)
1358 company-backend backend
1359 c (company-calculate-candidates prefix))
1360 ;; t means complete/unique. We don't start, so no hooks.
1362 (when company--manual-action
1363 (message "No completion found"))
1364 (setq company-prefix prefix)
1365 (when company--manual-action
1366 (setq company--manual-prefix prefix))
1367 (when (symbolp backend)
1368 (setq company-lighter (concat " " (symbol-name backend))))
1369 (company-update-candidates c)
1370 (run-hook-with-args 'company-completion-started-hook
1371 (company-explicit-action-p))
1372 (company-call-frontends 'show)))
1375 (defun company-begin ()
1376 (or (and company-candidates (company--continue))
1377 (and (company--should-complete) (company--begin-new)))
1378 (when company-candidates
1379 (let ((modified (buffer-modified-p)))
1380 (when (and company-end-of-buffer-workaround (eobp))
1381 (save-excursion (insert "\n"))
1382 (setq company-added-newline
1383 (or modified (buffer-chars-modified-tick)))))
1384 (setq company-point (point)
1385 company--point-max (point-max))
1386 (company-ensure-emulation-alist)
1387 (company-enable-overriding-keymap company-active-map)
1388 (company-call-frontends 'update)))
1390 (defun company-cancel (&optional result)
1391 (and company-added-newline
1392 (> (point-max) (point-min))
1393 (let ((tick (buffer-chars-modified-tick)))
1394 (delete-region (1- (point-max)) (point-max))
1395 (equal tick company-added-newline))
1396 ;; Only set unmodified when tick remained the same since insert,
1397 ;; and the buffer wasn't modified before.
1398 (set-buffer-modified-p nil))
1399 (when company-prefix
1400 (if (stringp result)
1402 (company-call-backend 'pre-completion result)
1403 (run-hook-with-args 'company-completion-finished-hook result)
1404 (company-call-backend 'post-completion result))
1405 (run-hook-with-args 'company-completion-cancelled-hook result)))
1406 (setq company-added-newline nil
1409 company-candidates nil
1410 company-candidates-length nil
1411 company-candidates-cache nil
1412 company-candidates-predicate nil
1415 company-selection-changed nil
1416 company--manual-action nil
1417 company--manual-prefix nil
1418 company-lighter company-default-lighter
1419 company--point-max nil
1422 (cancel-timer company-timer))
1423 (company-search-mode 0)
1424 (company-call-frontends 'hide)
1425 (company-enable-overriding-keymap nil)
1426 ;; Make return value explicit.
1429 (defun company-abort ()
1432 ;; Don't start again, unless started manually.
1433 (setq company-point (point)))
1435 (defun company-finish (result)
1436 (company--insert-candidate result)
1437 (company-cancel result)
1438 ;; Don't start again, unless started manually.
1439 (setq company-point (point)))
1441 (defsubst company-keep (command)
1442 (and (symbolp command) (get command 'company-keep)))
1444 (defun company-pre-command ()
1445 (unless (company-keep this-command)
1447 (when company-candidates
1448 (company-call-frontends 'pre-command)
1449 (unless (company--should-continue)
1451 (error (message "Company: An error occurred in pre-command")
1452 (message "%s" (error-message-string err))
1455 (cancel-timer company-timer)
1456 (setq company-timer nil))
1457 (company-uninstall-map))
1459 (defun company-post-command ()
1460 (unless (company-keep this-command)
1463 (unless (equal (point) company-point)
1465 (if company-candidates
1466 (company-call-frontends 'post-command)
1467 (and (numberp company-idle-delay)
1468 (or (eq t company-begin-commands)
1469 (memq this-command company-begin-commands))
1470 (not (equal (point) company-point))
1472 (run-with-timer company-idle-delay nil
1474 (current-buffer) (selected-window)
1475 (buffer-chars-modified-tick) (point))))))
1476 (error (message "Company: An error occurred in post-command")
1477 (message "%s" (error-message-string err))
1479 (company-install-map))
1481 ;;; search ;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;
1483 (defvar company-search-string nil)
1484 (make-variable-buffer-local 'company-search-string)
1486 (defvar company-search-lighter " Search: \"\"")
1487 (make-variable-buffer-local 'company-search-lighter)
1489 (defvar company-search-old-map nil)
1490 (make-variable-buffer-local 'company-search-old-map)
1492 (defvar company-search-old-selection 0)
1493 (make-variable-buffer-local 'company-search-old-selection)
1495 (defun company-search (text lines)
1496 (let ((quoted (regexp-quote text))
1498 (cl-dolist (line lines)
1499 (when (string-match quoted line (length company-prefix))
1503 (defun company-search-printing-char ()
1505 (company-search-assert-enabled)
1506 (setq company-search-string
1507 (concat (or company-search-string "") (string last-command-event))
1508 company-search-lighter (concat " Search: \"" company-search-string
1510 (let ((pos (company-search company-search-string
1511 (nthcdr company-selection company-candidates))))
1514 (company-set-selection (+ company-selection pos) t))))
1516 (defun company-search-repeat-forward ()
1517 "Repeat the incremental search in completion candidates forward."
1519 (company-search-assert-enabled)
1520 (let ((pos (company-search company-search-string
1521 (cdr (nthcdr company-selection
1522 company-candidates)))))
1525 (company-set-selection (+ company-selection pos 1) t))))
1527 (defun company-search-repeat-backward ()
1528 "Repeat the incremental search in completion candidates backwards."
1530 (company-search-assert-enabled)
1531 (let ((pos (company-search company-search-string
1532 (nthcdr (- company-candidates-length
1534 (reverse company-candidates)))))
1537 (company-set-selection (- company-selection pos 1) t))))
1539 (defun company-create-match-predicate ()
1540 (setq company-candidates-predicate
1541 `(lambda (candidate)
1542 ,(if company-candidates-predicate
1543 `(and (string-match ,company-search-string candidate)
1544 (funcall ,company-candidates-predicate
1546 `(string-match ,company-search-string candidate))))
1547 (company-update-candidates
1548 (company-apply-predicate company-candidates company-candidates-predicate))
1549 ;; Invalidate cache.
1550 (setq company-candidates-cache (cons company-prefix company-candidates)))
1552 (defun company-filter-printing-char ()
1554 (company-search-assert-enabled)
1555 (company-search-printing-char)
1556 (company-create-match-predicate)
1557 (company-call-frontends 'update))
1559 (defun company-search-kill-others ()
1560 "Limit the completion candidates to the ones matching the search string."
1562 (company-search-assert-enabled)
1563 (company-create-match-predicate)
1564 (company-search-mode 0)
1565 (company-call-frontends 'update))
1567 (defun company-search-abort ()
1568 "Abort searching the completion candidates."
1570 (company-search-assert-enabled)
1571 (company-set-selection company-search-old-selection t)
1572 (company-search-mode 0))
1574 (defun company-search-other-char ()
1576 (company-search-assert-enabled)
1577 (company-search-mode 0)
1578 (company--unread-last-input))
1580 (defvar company-search-map
1582 (keymap (make-keymap)))
1583 (if (fboundp 'max-char)
1584 (set-char-table-range (nth 1 keymap) (cons #x100 (max-char))
1585 'company-search-printing-char)
1587 ;; obsolete in Emacs 23
1588 (let ((l (generic-character-list))
1589 (table (nth 1 keymap)))
1591 (set-char-table-default table (car l) 'company-search-printing-char)
1592 (setq l (cdr l))))))
1593 (define-key keymap [t] 'company-search-other-char)
1595 (define-key keymap (make-string 1 i) 'company-search-other-char)
1598 (define-key keymap (vector i) 'company-search-printing-char)
1600 (let ((meta-map (make-sparse-keymap)))
1601 (define-key keymap (char-to-string meta-prefix-char) meta-map)
1602 (define-key keymap [escape] meta-map))
1603 (define-key keymap (vector meta-prefix-char t) 'company-search-other-char)
1604 (define-key keymap "\e\e\e" 'company-search-other-char)
1605 (define-key keymap [escape escape escape] 'company-search-other-char)
1607 (define-key keymap "\C-g" 'company-search-abort)
1608 (define-key keymap "\C-s" 'company-search-repeat-forward)
1609 (define-key keymap "\C-r" 'company-search-repeat-backward)
1610 (define-key keymap "\C-o" 'company-search-kill-others)
1612 "Keymap used for incrementally searching the completion candidates.")
1614 (define-minor-mode company-search-mode
1615 "Search mode for completion candidates.
1616 Don't start this directly, use `company-search-candidates' or
1617 `company-filter-candidates'."
1618 nil company-search-lighter nil
1619 (if company-search-mode
1620 (if (company-manual-begin)
1622 (setq company-search-old-selection company-selection)
1623 (company-call-frontends 'update))
1624 (setq company-search-mode nil))
1625 (kill-local-variable 'company-search-string)
1626 (kill-local-variable 'company-search-lighter)
1627 (kill-local-variable 'company-search-old-selection)
1628 (company-enable-overriding-keymap company-active-map)))
1630 (defun company-search-assert-enabled ()
1631 (company-assert-enabled)
1632 (unless company-search-mode
1633 (company-uninstall-map)
1634 (error "Company not in search mode")))
1636 (defun company-search-candidates ()
1637 "Start searching the completion candidates incrementally.
1639 \\<company-search-map>Search can be controlled with the commands:
1640 - `company-search-repeat-forward' (\\[company-search-repeat-forward])
1641 - `company-search-repeat-backward' (\\[company-search-repeat-backward])
1642 - `company-search-abort' (\\[company-search-abort])
1644 Regular characters are appended to the search string.
1646 The command `company-search-kill-others' (\\[company-search-kill-others])
1647 uses the search string to limit the completion candidates."
1649 (company-search-mode 1)
1650 (company-enable-overriding-keymap company-search-map))
1652 (defvar company-filter-map
1653 (let ((keymap (make-keymap)))
1654 (define-key keymap [remap company-search-printing-char]
1655 'company-filter-printing-char)
1656 (set-keymap-parent keymap company-search-map)
1658 "Keymap used for incrementally searching the completion candidates.")
1660 (defun company-filter-candidates ()
1661 "Start filtering the completion candidates incrementally.
1662 This works the same way as `company-search-candidates' immediately
1663 followed by `company-search-kill-others' after each input."
1665 (company-search-mode 1)
1666 (company-enable-overriding-keymap company-filter-map))
1668 ;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;
1670 (defun company-select-next ()
1671 "Select the next candidate in the list."
1673 (when (company-manual-begin)
1674 (company-set-selection (1+ company-selection))))
1676 (defun company-select-previous ()
1677 "Select the previous candidate in the list."
1679 (when (company-manual-begin)
1680 (company-set-selection (1- company-selection))))
1682 (defun company-select-next-or-abort ()
1683 "Select the next candidate if more than one, else abort
1684 and invoke the normal binding."
1686 (if (> company-candidates-length 1)
1687 (company-select-next)
1689 (company--unread-last-input)))
1691 (defun company-select-previous-or-abort ()
1692 "Select the previous candidate if more than one, else abort
1693 and invoke the normal binding."
1695 (if (> company-candidates-length 1)
1696 (company-select-previous)
1698 (company--unread-last-input)))
1700 (defvar company-pseudo-tooltip-overlay)
1702 (defvar company-tooltip-offset)
1704 (defun company--inside-tooltip-p (event-col-row row height)
1705 (let* ((ovl company-pseudo-tooltip-overlay)
1706 (column (overlay-get ovl 'company-column))
1707 (width (overlay-get ovl 'company-width))
1708 (evt-col (car event-col-row))
1709 (evt-row (cdr event-col-row)))
1710 (and (>= evt-col column)
1711 (< evt-col (+ column width))
1713 (and (> evt-row row)
1714 (<= evt-row (+ row height) ))
1715 (and (< evt-row row)
1716 (>= evt-row (+ row height)))))))
1718 (defun company--event-col-row (event)
1719 (let* ((col-row (posn-actual-col-row (event-start event)))
1721 (row (cdr col-row)))
1722 (cl-incf col (window-hscroll))
1723 (and header-line-format
1724 (version< "24" emacs-version)
1728 (defun company-select-mouse (event)
1729 "Select the candidate picked by the mouse."
1731 (let ((event-col-row (company--event-col-row event))
1732 (ovl-row (company--row))
1733 (ovl-height (and company-pseudo-tooltip-overlay
1734 (min (overlay-get company-pseudo-tooltip-overlay
1736 company-candidates-length))))
1738 (company--inside-tooltip-p event-col-row ovl-row ovl-height))
1740 (company-set-selection (+ (cdr event-col-row)
1741 (1- company-tooltip-offset)
1742 (if (and (eq company-tooltip-offset-display 'lines)
1743 (not (zerop company-tooltip-offset)))
1746 (if (< ovl-height 0)
1751 (company--unread-last-input)
1754 (defun company-complete-mouse (event)
1755 "Insert the candidate picked by the mouse."
1757 (when (company-select-mouse event)
1758 (company-complete-selection)))
1760 (defun company-complete-selection ()
1761 "Insert the selected candidate."
1763 (when (company-manual-begin)
1764 (let ((result (nth company-selection company-candidates)))
1765 (company-finish result))))
1767 (defun company-complete-common ()
1768 "Insert the common part of all candidates."
1770 (when (company-manual-begin)
1771 (if (and (not (cdr company-candidates))
1772 (equal company-common (car company-candidates)))
1773 (company-complete-selection)
1774 (when company-common
1775 (company--insert-candidate company-common)))))
1777 (defun company-complete ()
1778 "Insert the common part of all candidates or the current selection.
1779 The first time this is called, the common part is inserted, the second
1780 time, or when the selection has been changed, the selected candidate is
1783 (when (company-manual-begin)
1784 (if (or company-selection-changed
1785 (eq last-command 'company-complete-common))
1786 (call-interactively 'company-complete-selection)
1787 (call-interactively 'company-complete-common)
1788 (setq this-command 'company-complete-common))))
1790 (defun company-complete-number (n)
1791 "Insert the Nth candidate.
1792 To show the number next to the candidates in some back-ends, enable
1793 `company-show-numbers'."
1794 (when (company-manual-begin)
1795 (and (or (< n 1) (> n company-candidates-length))
1796 (error "No candidate number %d" n))
1798 (company-finish (nth n company-candidates))))
1800 ;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;
1802 (defconst company-space-strings-limit 100)
1804 (defconst company-space-strings
1806 (dotimes (i company-space-strings-limit)
1807 (push (make-string (- company-space-strings-limit 1 i) ?\ ) lst))
1808 (apply 'vector lst)))
1810 (defun company-space-string (len)
1811 (if (< len company-space-strings-limit)
1812 (aref company-space-strings len)
1813 (make-string len ?\ )))
1815 (defun company-safe-substring (str from &optional to)
1816 (if (> from (string-width str))
1820 (move-to-column from)
1821 (let ((beg (point)))
1825 (concat (buffer-substring beg (point))
1826 (let ((padding (- to (current-column))))
1828 (company-space-string padding)))))
1829 (buffer-substring beg (point-max)))))))
1831 ;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;
1833 (defvar company-last-metadata nil)
1834 (make-variable-buffer-local 'company-last-metadata)
1836 (defun company-fetch-metadata ()
1837 (let ((selected (nth company-selection company-candidates)))
1838 (unless (eq selected (car company-last-metadata))
1839 (setq company-last-metadata
1840 (cons selected (company-call-backend 'meta selected))))
1841 (cdr company-last-metadata)))
1843 (defun company-doc-buffer (&optional string)
1844 (with-current-buffer (get-buffer-create "*company-documentation*")
1851 (defvar company--electric-commands
1852 '(scroll-other-window scroll-other-window-down)
1853 "List of Commands that won't break out of electric commands.")
1855 (defmacro company--electric-do (&rest body)
1856 (declare (indent 0) (debug t))
1857 `(when (company-manual-begin)
1858 (save-window-excursion
1859 (let ((height (window-height))
1860 (row (company--row))
1863 (and (< (window-height) height)
1864 (< (- (window-height) row 2) company-tooltip-limit)
1865 (recenter (- (window-height) row 2)))
1866 (while (memq (setq cmd (key-binding (vector (list (read-event)))))
1867 company--electric-commands)
1868 (call-interactively cmd))
1869 (company--unread-last-input)))))
1871 (defun company--unread-last-input ()
1872 (when last-input-event
1873 (clear-this-command-keys t)
1874 (setq unread-command-events (list last-input-event))))
1876 (defun company-show-doc-buffer ()
1877 "Temporarily show the documentation buffer for the selection."
1879 (company--electric-do
1880 (let* ((selected (nth company-selection company-candidates))
1881 (doc-buffer (or (company-call-backend 'doc-buffer selected)
1882 (error "No documentation available"))))
1883 (with-current-buffer doc-buffer
1884 (goto-char (point-min)))
1885 (display-buffer doc-buffer t))))
1886 (put 'company-show-doc-buffer 'company-keep t)
1888 (defun company-show-location ()
1889 "Temporarily display a buffer showing the selected candidate in context."
1891 (company--electric-do
1892 (let* ((selected (nth company-selection company-candidates))
1893 (location (company-call-backend 'location selected))
1894 (pos (or (cdr location) (error "No location available")))
1895 (buffer (or (and (bufferp (car location)) (car location))
1896 (find-file-noselect (car location) t))))
1897 (with-selected-window (display-buffer buffer t)
1900 (if (bufferp (car location))
1902 (goto-char (point-min))
1903 (forward-line (1- pos))))
1904 (set-window-start nil (point))))))
1905 (put 'company-show-location 'company-keep t)
1907 ;;; package functions ;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;
1909 (defvar company-callback nil)
1910 (make-variable-buffer-local 'company-callback)
1912 (defun company-remove-callback (&optional ignored)
1913 (remove-hook 'company-completion-finished-hook company-callback t)
1914 (remove-hook 'company-completion-cancelled-hook 'company-remove-callback t)
1915 (remove-hook 'company-completion-finished-hook 'company-remove-callback t))
1917 (defun company-begin-backend (backend &optional callback)
1918 "Start a completion at point using BACKEND."
1919 (interactive (let ((val (completing-read "Company back-end: "
1921 'functionp nil "company-")))
1923 (list (intern val)))))
1924 (when (setq company-callback callback)
1925 (add-hook 'company-completion-finished-hook company-callback nil t))
1926 (add-hook 'company-completion-cancelled-hook 'company-remove-callback nil t)
1927 (add-hook 'company-completion-finished-hook 'company-remove-callback nil t)
1928 (setq company-backend backend)
1929 ;; Return non-nil if active.
1930 (or (company-manual-begin)
1931 (error "Cannot complete at point")))
1933 (defun company-begin-with (candidates
1934 &optional prefix-length require-match callback)
1935 "Start a completion at point.
1936 CANDIDATES is the list of candidates to use and PREFIX-LENGTH is the length
1937 of the prefix that already is in the buffer before point.
1940 CALLBACK is a function called with the selected result if the user
1941 successfully completes the input.
1943 Example: \(company-begin-with '\(\"foo\" \"foobar\" \"foobarbaz\"\)\)"
1944 (let ((begin-marker (copy-marker (point) t)))
1945 (company-begin-backend
1946 (lambda (command &optional arg &rest ignored)
1949 (when (equal (point) (marker-position begin-marker))
1950 (buffer-substring (- (point) (or prefix-length 0)) (point))))
1952 (all-completions arg candidates))
1957 (defun company-version (&optional show-version)
1958 "Get the Company version as string.
1960 If SHOW-VERSION is non-nil, show the version in the echo area."
1961 (interactive (list t))
1963 (insert-file-contents (find-library-name "company"))
1966 (message "Company version: %s" (lm-version))
1969 ;;; pseudo-tooltip ;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;
1971 (defvar company-pseudo-tooltip-overlay nil)
1972 (make-variable-buffer-local 'company-pseudo-tooltip-overlay)
1974 (defvar company-tooltip-offset 0)
1975 (make-variable-buffer-local 'company-tooltip-offset)
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 (let ((width (length (car lines)))
2119 (remaining-cols (- (+ (company--window-width) (window-hscroll))
2121 (when (> width remaining-cols)
2122 (cl-decf column (- width remaining-cols))))
2124 (let ((offset (and (< column 0) (- column)))
2129 ;; untouched lines first
2130 (dotimes (_ (- (length old) (length lines)))
2131 (push (pop old) new)))
2132 ;; length into old lines.
2134 (push (company-modify-line (pop old)
2135 (company--offset-line (pop lines) offset)
2137 ;; Append whole new lines.
2139 (push (concat (company-space-string column)
2140 (company--offset-line (pop lines) offset))
2143 (let ((str (concat (when nl "\n")
2144 (mapconcat 'identity (nreverse new) "\n")
2146 (font-lock-append-text-property 0 (length str) 'face 'default str)
2149 (defun company--offset-line (line offset)
2150 (if (and offset line)
2151 (substring line offset)
2154 (defun company--create-lines (selection limit)
2155 (let ((len company-candidates-length)
2157 (window-width (company--window-width))
2166 ;; Maybe clear old offset.
2167 (when (< len (+ company-tooltip-offset limit))
2168 (setq company-tooltip-offset 0))
2170 ;; Scroll to offset.
2171 (if (eq company-tooltip-offset-display 'lines)
2172 (setq limit (company-tooltip--lines-update-offset selection len limit))
2173 (company-tooltip--simple-update-offset selection len limit))
2176 ((eq company-tooltip-offset-display 'scrollbar)
2177 (setq scrollbar-bounds (company--scrollbar-bounds company-tooltip-offset
2179 ((eq company-tooltip-offset-display 'lines)
2180 (when (> company-tooltip-offset 0)
2181 (setq previous (format "...(%d)" company-tooltip-offset)))
2182 (setq remainder (- len limit company-tooltip-offset)
2183 remainder (when (> remainder 0)
2184 (setq remainder (format "...(%d)" remainder))))))
2186 (cl-decf selection company-tooltip-offset)
2187 (setq width (max (length previous) (length remainder))
2188 lines (nthcdr company-tooltip-offset company-candidates)
2192 (cl-decf window-width (* 2 company-tooltip-margin))
2193 (when scrollbar-bounds (cl-decf window-width))
2196 (let* ((value (pop lines-copy))
2197 (annotation (company-call-backend 'annotation value)))
2198 (when (and annotation company-tooltip-align-annotations)
2199 ;; `lisp-completion-at-point' adds a space.
2200 (setq annotation (comment-string-strip annotation t nil)))
2201 (push (cons value annotation) items)
2202 (setq width (max (+ (length value)
2203 (if (and annotation company-tooltip-align-annotations)
2204 (1+ (length annotation))
2205 (length annotation)))
2208 (setq width (min window-width
2209 (max company-tooltip-minimum-width
2210 (if (and company-show-numbers
2211 (< company-tooltip-offset 10))
2215 ;; number can make tooltip too long
2216 (when company-show-numbers
2217 (setq numbered company-tooltip-offset))
2219 (let ((items (nreverse items)) new)
2221 (push (company--scrollpos-line previous width) new))
2224 (let* ((item (pop items))
2225 (str (company-reformat (car item)))
2226 (annotation (cdr item))
2227 (right (company-space-string company-tooltip-margin))
2229 (when (< numbered 10)
2232 (setq right (concat (format " %d" (mod numbered 10)) right)))
2234 (company-fill-propertize str annotation
2235 width (equal i selection)
2236 (company-space-string
2237 company-tooltip-margin)
2239 (when scrollbar-bounds
2240 (company--scrollbar i scrollbar-bounds)))
2244 (push (company--scrollpos-line remainder width) new))
2248 (defun company--scrollbar-bounds (offset limit length)
2249 (when (> length limit)
2250 (let* ((size (ceiling (* limit (float limit)) length))
2251 (lower (floor (* limit (float offset)) length))
2252 (upper (+ lower size -1)))
2253 (cons lower upper))))
2255 (defun company--scrollbar (i bounds)
2256 (propertize " " 'face
2257 (if (and (>= i (car bounds)) (<= i (cdr bounds)))
2258 'company-scrollbar-fg
2259 'company-scrollbar-bg)))
2261 (defun company--scrollpos-line (text width)
2262 (propertize (concat (company-space-string company-tooltip-margin)
2263 (company-safe-substring text 0 width)
2264 (company-space-string company-tooltip-margin))
2265 'face 'company-tooltip))
2269 (defsubst company--window-inner-height ()
2270 (let ((edges (window-inside-edges)))
2271 (- (nth 3 edges) (nth 1 edges))))
2273 (defsubst company--window-width ()
2274 (let ((ww (window-width)))
2275 ;; Account for the line continuation column.
2276 (when (zerop (cadr (window-fringes)))
2278 (unless (or (display-graphic-p)
2279 (version< "24.3.1" emacs-version))
2280 ;; Emacs 24.3 and earlier included margins
2281 ;; in window-width when in TTY.
2283 (let ((margins (window-margins)))
2284 (+ (or (car margins) 0)
2285 (or (cdr margins) 0)))))
2288 (defun company--pseudo-tooltip-height ()
2289 "Calculate the appropriate tooltip height.
2290 Returns a negative number if the tooltip should be displayed above point."
2291 (let* ((lines (company--row))
2292 (below (- (company--window-inner-height) 1 lines)))
2293 (if (and (< below (min company-tooltip-minimum company-candidates-length))
2295 (- (max 3 (min company-tooltip-limit lines)))
2296 (max 3 (min company-tooltip-limit below)))))
2298 (defun company-pseudo-tooltip-show (row column selection)
2299 (company-pseudo-tooltip-hide)
2302 (let* ((height (company--pseudo-tooltip-height))
2306 (setq row (+ row height -1)
2309 (let* ((nl (< (move-to-window-line row) row))
2311 (end (save-excursion
2312 (move-to-window-line (+ row (abs height)))
2314 (ov (make-overlay beg end))
2315 (args (list (mapcar 'company-plainify
2316 (company-buffer-lines beg end))
2319 (setq company-pseudo-tooltip-overlay ov)
2320 (overlay-put ov 'company-replacement-args args)
2322 (let ((lines (company--create-lines selection (abs height))))
2323 (overlay-put ov 'company-after
2324 (apply 'company--replacement-string lines args))
2325 (overlay-put ov 'company-width (string-width (car lines))))
2327 (overlay-put ov 'company-column column)
2328 (overlay-put ov 'company-height height)))))
2330 (defun company-pseudo-tooltip-show-at-point (pos)
2331 (let ((row (company--row pos))
2332 (col (company--column pos)))
2333 (company-pseudo-tooltip-show (1+ row) col company-selection)))
2335 (defun company-pseudo-tooltip-edit (selection)
2336 (let ((height (overlay-get company-pseudo-tooltip-overlay 'company-height)))
2337 (overlay-put company-pseudo-tooltip-overlay 'company-after
2338 (apply 'company--replacement-string
2339 (company--create-lines selection (abs height))
2340 (overlay-get company-pseudo-tooltip-overlay
2341 'company-replacement-args)))))
2343 (defun company-pseudo-tooltip-hide ()
2344 (when company-pseudo-tooltip-overlay
2345 (delete-overlay company-pseudo-tooltip-overlay)
2346 (setq company-pseudo-tooltip-overlay nil)))
2348 (defun company-pseudo-tooltip-hide-temporarily ()
2349 (when (overlayp company-pseudo-tooltip-overlay)
2350 (overlay-put company-pseudo-tooltip-overlay 'invisible nil)
2351 (overlay-put company-pseudo-tooltip-overlay 'line-prefix nil)
2352 (overlay-put company-pseudo-tooltip-overlay 'after-string nil)))
2354 (defun company-pseudo-tooltip-unhide ()
2355 (when company-pseudo-tooltip-overlay
2356 (overlay-put company-pseudo-tooltip-overlay 'invisible t)
2357 ;; Beat outline's folding overlays, at least.
2358 (overlay-put company-pseudo-tooltip-overlay 'priority 1)
2359 ;; No (extra) prefix for the first line.
2360 (overlay-put company-pseudo-tooltip-overlay 'line-prefix "")
2361 (overlay-put company-pseudo-tooltip-overlay 'after-string
2362 (overlay-get company-pseudo-tooltip-overlay 'company-after))
2363 (overlay-put company-pseudo-tooltip-overlay 'window (selected-window))))
2365 (defun company-pseudo-tooltip-guard ()
2366 (buffer-substring-no-properties
2367 (point) (overlay-start company-pseudo-tooltip-overlay)))
2369 (defun company-pseudo-tooltip-frontend (command)
2370 "`company-mode' front-end similar to a tooltip but based on overlays."
2372 (pre-command (company-pseudo-tooltip-hide-temporarily))
2374 (let ((old-height (if (overlayp company-pseudo-tooltip-overlay)
2375 (overlay-get company-pseudo-tooltip-overlay
2378 (new-height (company--pseudo-tooltip-height)))
2379 (unless (and (>= (* old-height new-height) 0)
2380 (>= (abs old-height) (abs new-height))
2381 (equal (company-pseudo-tooltip-guard)
2382 (overlay-get company-pseudo-tooltip-overlay
2385 (company-pseudo-tooltip-show-at-point (- (point)
2386 (length company-prefix)))
2387 (overlay-put company-pseudo-tooltip-overlay
2388 'company-guard (company-pseudo-tooltip-guard))))
2389 (company-pseudo-tooltip-unhide))
2390 (hide (company-pseudo-tooltip-hide)
2391 (setq company-tooltip-offset 0))
2392 (update (when (overlayp company-pseudo-tooltip-overlay)
2393 (company-pseudo-tooltip-edit company-selection)))))
2395 (defun company-pseudo-tooltip-unless-just-one-frontend (command)
2396 "`company-pseudo-tooltip-frontend', but not shown for single candidates."
2397 (unless (and (eq command 'post-command)
2398 (company--show-inline-p))
2399 (company-pseudo-tooltip-frontend command)))
2401 ;;; overlay ;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;
2403 (defvar company-preview-overlay nil)
2404 (make-variable-buffer-local 'company-preview-overlay)
2406 (defun company-preview-show-at-point (pos)
2407 (company-preview-hide)
2409 (setq company-preview-overlay (make-overlay pos (1+ pos)))
2411 (let ((completion (nth company-selection company-candidates)))
2412 (setq completion (propertize completion 'face 'company-preview))
2413 (add-text-properties 0 (length company-common)
2414 '(face company-preview-common) completion)
2416 ;; Add search string
2417 (and company-search-string
2418 (string-match (regexp-quote company-search-string) completion)
2419 (add-text-properties (match-beginning 0)
2421 '(face company-preview-search)
2424 (setq completion (company-strip-prefix completion))
2426 (and (equal pos (point))
2427 (not (equal completion ""))
2428 (add-text-properties 0 1 '(cursor t) completion))
2430 (overlay-put company-preview-overlay 'display
2431 (concat completion (unless (eq pos (point-max))
2432 (buffer-substring pos (1+ pos)))))
2433 (overlay-put company-preview-overlay 'window (selected-window))))
2435 (defun company-preview-hide ()
2436 (when company-preview-overlay
2437 (delete-overlay company-preview-overlay)
2438 (setq company-preview-overlay nil)))
2440 (defun company-preview-frontend (command)
2441 "`company-mode' front-end showing the selection as if it had been inserted."
2443 (`pre-command (company-preview-hide))
2444 (`post-command (company-preview-show-at-point (point)))
2445 (`hide (company-preview-hide))))
2447 (defun company-preview-if-just-one-frontend (command)
2448 "`company-preview-frontend', but only shown for single candidates."
2449 (when (or (not (eq command 'post-command))
2450 (company--show-inline-p))
2451 (company-preview-frontend command)))
2453 (defun company--show-inline-p ()
2454 (and (not (cdr company-candidates))
2456 (string-prefix-p company-prefix company-common
2457 (company-call-backend 'ignore-case))))
2459 ;;; echo ;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;
2461 (defvar company-echo-last-msg nil)
2462 (make-variable-buffer-local 'company-echo-last-msg)
2464 (defvar company-echo-timer nil)
2466 (defvar company-echo-delay .01)
2468 (defun company-echo-show (&optional getter)
2470 (setq company-echo-last-msg (funcall getter)))
2471 (let ((message-log-max nil))
2472 (if company-echo-last-msg
2473 (message "%s" company-echo-last-msg)
2476 (defun company-echo-show-soon (&optional getter)
2477 (when company-echo-timer
2478 (cancel-timer company-echo-timer))
2479 (setq company-echo-timer (run-with-timer 0 nil 'company-echo-show getter)))
2481 (defsubst company-echo-show-when-idle (&optional getter)
2482 (when (sit-for company-echo-delay)
2483 (company-echo-show getter)))
2485 (defun company-echo-format ()
2487 (let ((limit (window-width (minibuffer-window)))
2489 ;; Roll to selection.
2490 (candidates (nthcdr company-selection company-candidates))
2491 (i (if company-show-numbers company-selection 99999))
2495 (setq comp (company-reformat (pop candidates))
2496 len (+ len 1 (length comp)))
2500 (setq comp (propertize (format "%d: %s" i comp)
2501 'face 'company-echo))
2504 (add-text-properties 3 (+ 3 (length company-common))
2505 '(face company-echo-common) comp))
2506 (setq comp (propertize comp 'face 'company-echo))
2507 (add-text-properties 0 (length company-common)
2508 '(face company-echo-common) comp))
2510 (setq candidates nil)
2513 (mapconcat 'identity (nreverse msg) " ")))
2515 (defun company-echo-strip-common-format ()
2517 (let ((limit (window-width (minibuffer-window)))
2518 (len (+ (length company-prefix) 2))
2519 ;; Roll to selection.
2520 (candidates (nthcdr company-selection company-candidates))
2521 (i (if company-show-numbers company-selection 99999))
2525 (setq comp (company-strip-prefix (pop candidates))
2526 len (+ len 2 (length comp)))
2529 (setq comp (format "%s (%d)" comp i))
2533 (setq candidates nil)
2534 (push (propertize comp 'face 'company-echo) msg)))
2536 (concat (propertize company-prefix 'face 'company-echo-common) "{"
2537 (mapconcat 'identity (nreverse msg) ", ")
2540 (defun company-echo-hide ()
2541 (unless (equal company-echo-last-msg "")
2542 (setq company-echo-last-msg "")
2543 (company-echo-show)))
2545 (defun company-echo-frontend (command)
2546 "`company-mode' front-end showing the candidates in the echo area."
2548 (`post-command (company-echo-show-soon 'company-echo-format))
2549 (`hide (company-echo-hide))))
2551 (defun company-echo-strip-common-frontend (command)
2552 "`company-mode' front-end showing the candidates in the echo area."
2554 (`post-command (company-echo-show-soon 'company-echo-strip-common-format))
2555 (`hide (company-echo-hide))))
2557 (defun company-echo-metadata-frontend (command)
2558 "`company-mode' front-end showing the documentation in the echo area."
2560 (`post-command (company-echo-show-when-idle 'company-fetch-metadata))
2561 (`hide (company-echo-hide))))
2564 ;;; company.el ends here