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/
8 ;; Version: 0.8.0-snapshot
9 ;; Keywords: abbrev, convenience, matching
10 ;; Package-Requires: ((emacs "24.1"))
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.
72 (eval-when-compile (require 'cl))
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 (dolist (backend backends)
295 (unless (if (consp backend)
296 (company-safe-backends-p backend)
297 (assq backend company-safe-backends))
300 (defvar company--include-capf (version< "24.3.50" emacs-version))
302 (defcustom company-backends `(,@(unless company--include-capf
303 (list 'company-elisp))
305 company-nxml company-css
306 company-eclim company-semantic company-clang
307 company-xcode company-ropemacs company-cmake
308 ,@(when company--include-capf
309 (list 'company-capf))
310 (company-dabbrev-code company-gtags company-etags
312 company-oddmuse company-files company-dabbrev)
313 "The list of active back-ends (completion engines).
315 `company-begin-backend' can be used to start a specific back-end,
316 `company-other-backend' will skip to the next matching back-end in the list.
318 Each back-end is a function that takes a variable number of arguments.
319 The first argument is the command requested from the back-end. It is one
322 `prefix': The back-end should return the text to be completed. It must be
323 text immediately before point. Returning nil passes control to the next
324 back-end. The function should return `stop' if it should complete but
325 cannot \(e.g. if it is in the middle of a string\). Instead of a string,
326 the back-end may return a cons where car is the prefix and cdr is used in
327 `company-minimum-prefix-length' test. It must be either number or t, and
328 in the latter case the test automatically succeeds.
330 `candidates': The second argument is the prefix to be completed. The
331 return value should be a list of candidates that match the prefix.
333 Non-prefix matches are also supported (candidates that don't start with the
334 prefix, but match it in some backend-defined way). Backends that use this
335 feature must disable cache (return t to `no-cache') and should also respond
340 `sorted': Return t here to indicate that the candidates are sorted and will
341 not need to be sorted again.
343 `duplicates': If non-nil, company will take care of removing duplicates
346 `no-cache': Usually company doesn't ask for candidates again as completion
347 progresses, unless the back-end returns t for this command. The second
348 argument is the latest prefix.
350 `meta': The second argument is a completion candidate. Return a (short)
351 documentation string for it.
353 `doc-buffer': The second argument is a completion candidate. Return a
354 buffer with documentation for it. Preferably use `company-doc-buffer',
356 `location': The second argument is a completion candidate. Return the cons
357 of buffer and buffer location, or of file and line number where the
358 completion candidate was defined.
360 `annotation': The second argument is a completion candidate. Return a
361 string to be displayed inline with the candidate in the popup. If
362 duplicates are removed by company, candidates with equal string values will
363 be kept if they have different annotations. For that to work properly,
364 backends should store the related information on candidates using text
367 `match': The second argument is a completion candidate. Backends that
368 provide non-prefix completions should return the position of the end of
369 text in the candidate that matches `prefix'. It will be used when
372 `require-match': If this returns t, the user is not allowed to enter
373 anything not offered as a candidate. Use with care! The default value nil
374 gives the user that choice with `company-require-match'. Return value
375 `never' overrides that option the other way around.
377 `init': Called once for each buffer. The back-end can check for external
378 programs and files and load any required libraries. Raising an error here
379 will show up in message log once, and the back-end will not be used for
382 `post-completion': Called after a completion candidate has been inserted
383 into the buffer. The second argument is the candidate. Can be used to
384 modify it, e.g. to expand a snippet.
386 The back-end should return nil for all commands it does not support or
387 does not know about. It should also be callable interactively and use
388 `company-begin-backend' to start itself in that case.
392 An element of `company-backends' can also itself be a list of back-ends,
393 then it's considered to be a \"grouped\" back-end.
395 When possible, commands taking a candidate as an argument are dispatched to
396 the back-end it came from. In other cases, the first non-nil value among
397 all the back-ends is returned.
399 The latter is the case for the `prefix' command. But if the group contains
400 the keyword `:with', the back-ends after it are ignored for this command.
402 The completions from back-ends in a group are merged (but only from those
403 that return the same `prefix').
405 Asynchronous back-ends:
407 The return value of each command can also be a cons (:async . FETCHER)
408 where FETCHER is a function of one argument, CALLBACK. When the data
409 arrives, FETCHER must call CALLBACK and pass it the appropriate return
410 value, as described above.
412 True asynchronous operation is only supported for command `candidates', and
413 only during idle completion. Other commands will block the user interface,
414 even if the back-end uses the asynchronous calling convention."
418 ,@(mapcar (lambda (b) `(const :tag ,(cdr b) ,(car b)))
419 company-safe-backends)
420 (symbol :tag "User defined")
421 (repeat :tag "Merged Back-ends"
422 (choice :tag "Back-end"
423 ,@(mapcar (lambda (b)
424 `(const :tag ,(cdr b) ,(car b)))
425 company-safe-backends)
426 (const :tag "With" :with)
427 (symbol :tag "User defined"))))))
429 (put 'company-backends 'safe-local-variable 'company-safe-backends-p)
431 (defcustom company-transformers nil
432 "Functions to change the list of candidates received from backends,
433 after sorting and removal of duplicates (if appropriate).
434 Each function gets called with the return value of the previous one."
436 (const :tag "None" nil)
437 (const :tag "Sort by occurrence" (company-sort-by-occurrence))
438 (repeat :tag "User defined" (function))))
440 (defcustom company-completion-started-hook nil
441 "Hook run when company starts completing.
442 The hook is called with one argument that is non-nil if the completion was
446 (defcustom company-completion-cancelled-hook nil
447 "Hook run when company cancels completing.
448 The hook is called with one argument that is non-nil if the completion was
452 (defcustom company-completion-finished-hook nil
453 "Hook run when company successfully completes.
454 The hook is called with the selected candidate as an argument.
456 If you indend to use it to post-process candidates from a specific
457 back-end, consider using the `post-completion' command instead."
460 (defcustom company-minimum-prefix-length 3
461 "The minimum prefix length for idle completion."
462 :type '(integer :tag "prefix length"))
464 (defcustom company-abort-manual-when-too-short nil
465 "If enabled, cancel a manually started completion when the prefix gets
466 shorter than both `company-minimum-prefix-length' and the length of the
467 prefix it was started from."
470 (defcustom company-require-match 'company-explicit-action-p
471 "If enabled, disallow non-matching input.
472 This can be a function do determine if a match is required.
474 This can be overridden by the back-end, if it returns t or `never' to
475 `require-match'. `company-auto-complete' also takes precedence over this."
476 :type '(choice (const :tag "Off" nil)
477 (function :tag "Predicate function")
478 (const :tag "On, if user interaction took place"
479 'company-explicit-action-p)
480 (const :tag "On" t)))
482 (defcustom company-auto-complete nil
483 "Determines when to auto-complete.
484 If this is enabled, all characters from `company-auto-complete-chars'
485 trigger insertion of the selected completion candidate.
486 This can also be a function."
487 :type '(choice (const :tag "Off" nil)
488 (function :tag "Predicate function")
489 (const :tag "On, if user interaction took place"
490 'company-explicit-action-p)
491 (const :tag "On" t)))
493 (defcustom company-auto-complete-chars '(?\ ?\) ?.)
494 "Determines which characters trigger auto-completion.
495 See `company-auto-complete'. If this is a string, each string character
496 tiggers auto-completion. If it is a list of syntax description characters (see
497 `modify-syntax-entry'), all characters with that syntax auto-complete.
499 This can also be a function, which is called with the new input and should
500 return non-nil if company should auto-complete.
502 A character that is part of a valid candidate never triggers auto-completion."
503 :type '(choice (string :tag "Characters")
505 (const :tag "Whitespace" ?\ )
506 (const :tag "Symbol" ?_)
507 (const :tag "Opening parentheses" ?\()
508 (const :tag "Closing parentheses" ?\))
509 (const :tag "Word constituent" ?w)
510 (const :tag "Punctuation." ?.)
511 (const :tag "String quote." ?\")
512 (const :tag "Paired delimiter." ?$)
513 (const :tag "Expression quote or prefix operator." ?\')
514 (const :tag "Comment starter." ?<)
515 (const :tag "Comment ender." ?>)
516 (const :tag "Character-quote." ?/)
517 (const :tag "Generic string fence." ?|)
518 (const :tag "Generic comment fence." ?!))
519 (function :tag "Predicate function")))
521 (defcustom company-idle-delay .7
522 "The idle delay in seconds until completion starts automatically.
523 A value of nil means no idle completion, t means show candidates
524 immediately when a prefix of `company-minimum-prefix-length' is reached."
525 :type '(choice (const :tag "never (nil)" nil)
526 (const :tag "immediate (t)" t)
527 (number :tag "seconds")))
529 (defcustom company-begin-commands '(self-insert-command org-self-insert-command)
530 "A list of commands after which idle completion is allowed.
531 If this is t, it can show completions after any command. See
532 `company-idle-delay'.
534 Alternatively, any command with a non-nil `company-begin' property is
535 treated as if it was on this list."
536 :type '(choice (const :tag "Any command" t)
537 (const :tag "Self insert command" '(self-insert-command))
538 (repeat :tag "Commands" function)))
540 (defcustom company-continue-commands '(not save-buffer save-some-buffers
541 save-buffers-kill-terminal
542 save-buffers-kill-emacs)
543 "A list of commands that are allowed during completion.
544 If this is t, or if `company-begin-commands' is t, any command is allowed.
545 Otherwise, the value must be a list of symbols. If it starts with `not',
546 the cdr is the list of commands that abort completion. Otherwise, all
547 commands except those in that list, or in `company-begin-commands', or
548 commands in the `company-' namespace, abort completion."
549 :type '(choice (const :tag "Any command" t)
550 (cons :tag "Any except"
552 (repeat :tag "Commands" function))
553 (repeat :tag "Commands" function)))
555 (defcustom company-show-numbers nil
556 "If enabled, show quick-access numbers for the first ten candidates."
557 :type '(choice (const :tag "off" nil)
558 (const :tag "on" t)))
560 (defcustom company-selection-wrap-around nil
561 "If enabled, selecting item before first or after last wraps around."
562 :type '(choice (const :tag "off" nil)
563 (const :tag "on" t)))
565 (defvar company-end-of-buffer-workaround t
566 "Work around a visualization bug when completing at the end of the buffer.
567 The work-around consists of adding a newline.")
569 (defvar company-async-wait 0.03
570 "Pause between checks to see if the value's been set when turning an
571 asynchronous call into synchronous.")
573 (defvar company-async-timeout 2
574 "Maximum wait time for a value to be set during asynchronous call.")
576 ;;; mode ;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;
578 (defvar company-mode-map (make-sparse-keymap)
579 "Keymap used by `company-mode'.")
581 (defvar company-active-map
582 (let ((keymap (make-sparse-keymap)))
583 (define-key keymap "\e\e\e" 'company-abort)
584 (define-key keymap "\C-g" 'company-abort)
585 (define-key keymap (kbd "M-n") 'company-select-next)
586 (define-key keymap (kbd "M-p") 'company-select-previous)
587 (define-key keymap (kbd "<down>") 'company-select-next-or-abort)
588 (define-key keymap (kbd "<up>") 'company-select-previous-or-abort)
589 (define-key keymap [down-mouse-1] 'ignore)
590 (define-key keymap [down-mouse-3] 'ignore)
591 (define-key keymap [mouse-1] 'company-complete-mouse)
592 (define-key keymap [mouse-3] 'company-select-mouse)
593 (define-key keymap [up-mouse-1] 'ignore)
594 (define-key keymap [up-mouse-3] 'ignore)
595 (define-key keymap [return] 'company-complete-selection)
596 (define-key keymap (kbd "RET") 'company-complete-selection)
597 (define-key keymap [tab] 'company-complete-common)
598 (define-key keymap (kbd "TAB") 'company-complete-common)
599 (define-key keymap (kbd "<f1>") 'company-show-doc-buffer)
600 (define-key keymap "\C-w" 'company-show-location)
601 (define-key keymap "\C-s" 'company-search-candidates)
602 (define-key keymap "\C-\M-s" 'company-filter-candidates)
604 (define-key keymap (vector (+ (aref (kbd "M-0") 0) i))
605 `(lambda () (interactive) (company-complete-number ,i))))
608 "Keymap that is enabled during an active completion.")
610 (defvar company--disabled-backends nil)
612 (defun company-init-backend (backend)
613 (and (symbolp backend)
614 (not (fboundp backend))
615 (ignore-errors (require backend nil t)))
620 (funcall backend 'init)
621 (put backend 'company-init t))
623 (put backend 'company-init 'failed)
624 (unless (memq backend company--disabled-backends)
625 (message "Company back-end '%s' could not be initialized:\n%s"
626 backend (error-message-string err)))
627 (pushnew backend company--disabled-backends)
629 ;; No initialization for lambdas.
630 ((functionp backend) t)
631 (t ;; Must be a list.
634 (company-init-backend b))))))
636 (defvar company-default-lighter " company")
638 (defvar company-lighter company-default-lighter)
639 (make-variable-buffer-local 'company-lighter)
642 (define-minor-mode company-mode
643 "\"complete anything\"; is an in-buffer completion framework.
644 Completion starts automatically, depending on the values
645 `company-idle-delay' and `company-minimum-prefix-length'.
647 Completion can be controlled with the commands:
648 `company-complete-common', `company-complete-selection', `company-complete',
649 `company-select-next', `company-select-previous'. If these commands are
650 called before `company-idle-delay', completion will also start.
652 Completions can be searched with `company-search-candidates' or
653 `company-filter-candidates'. These can be used while completion is
656 The completion data is retrieved using `company-backends' and displayed
657 using `company-frontends'. If you want to start a specific back-end, call
658 it interactively or use `company-begin-backend'.
660 regular keymap (`company-mode-map'):
663 keymap during active completions (`company-active-map'):
665 \\{company-active-map}"
666 nil company-lighter company-mode-map
669 (add-hook 'pre-command-hook 'company-pre-command nil t)
670 (add-hook 'post-command-hook 'company-post-command nil t)
671 (mapc 'company-init-backend company-backends))
672 (remove-hook 'pre-command-hook 'company-pre-command t)
673 (remove-hook 'post-command-hook 'company-post-command t)
675 (kill-local-variable 'company-point)))
677 (defcustom company-global-modes t
678 "Modes for which `company-mode' mode is turned on by `global-company-mode'.
679 If nil, means no modes. If t, then all major modes have it turned on.
680 If a list, it should be a list of `major-mode' symbol names for which
681 `company-mode' should be automatically turned on. The sense of the list is
682 negated if it begins with `not'. For example:
684 means that `company-mode' is turned on for buffers in C and C++ modes only.
686 means that `company-mode' is always turned on except in `message-mode' buffers."
687 :type '(choice (const :tag "none" nil)
689 (set :menu-tag "mode specific" :tag "modes"
691 (const :tag "Except" not)
692 (repeat :inline t (symbol :tag "mode")))))
695 (define-globalized-minor-mode global-company-mode company-mode company-mode-on)
697 (defun company-mode-on ()
698 (when (and (not (or noninteractive (eq (aref (buffer-name) 0) ?\s)))
699 (cond ((eq company-global-modes t)
701 ((eq (car-safe company-global-modes) 'not)
702 (not (memq major-mode (cdr company-global-modes))))
703 (t (memq major-mode company-global-modes))))
706 (defsubst company-assert-enabled ()
708 (company-uninstall-map)
709 (error "Company not enabled")))
711 ;;; keymaps ;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;
713 (defvar company-my-keymap nil)
714 (make-variable-buffer-local 'company-my-keymap)
716 (defvar company-emulation-alist '((t . nil)))
718 (defsubst company-enable-overriding-keymap (keymap)
719 (company-uninstall-map)
720 (setq company-my-keymap keymap))
722 (defun company-ensure-emulation-alist ()
723 (unless (eq 'company-emulation-alist (car emulation-mode-map-alists))
724 (setq emulation-mode-map-alists
725 (cons 'company-emulation-alist
726 (delq 'company-emulation-alist emulation-mode-map-alists)))))
728 (defun company-install-map ()
729 (unless (or (cdar company-emulation-alist)
730 (null company-my-keymap))
731 (setf (cdar company-emulation-alist) company-my-keymap)))
733 (defun company-uninstall-map ()
734 (setf (cdar company-emulation-alist) nil))
737 ;; Emacs calculates the active keymaps before reading the event. That means we
738 ;; cannot change the keymap from a timer. So we send a bogus command.
739 ;; XXX: Seems not to be needed anymore in Emacs 24.4
740 (defun company-ignore ()
742 (setq this-command last-command))
744 (global-set-key '[31415926] 'company-ignore)
746 (defun company-input-noop ()
747 (push 31415926 unread-command-events))
749 (defun company--column (&optional pos)
751 (when pos (goto-char pos))
755 (narrow-to-region (point) (point-max))
756 (let ((prefix (get-text-property (point) 'line-prefix)))
757 (if prefix (length prefix) 0)))
760 (defun company--row (&optional pos)
762 (when pos (goto-char pos))
763 (count-screen-lines (window-start)
764 (progn (vertical-motion 0) (point)))))
766 ;;; backends ;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;
768 (defvar company-backend nil)
769 (make-variable-buffer-local 'company-backend)
771 (defun company-grab (regexp &optional expression limit)
772 (when (looking-back regexp limit)
773 (or (match-string-no-properties (or expression 0)) "")))
775 (defun company-grab-line (regexp &optional expression)
776 (company-grab regexp expression (point-at-bol)))
778 (defun company-grab-symbol ()
779 (if (looking-at "\\_>")
780 (buffer-substring (point) (save-excursion (skip-syntax-backward "w_")
782 (unless (and (char-after) (memq (char-syntax (char-after)) '(?w ?_)))
785 (defun company-grab-word ()
786 (if (looking-at "\\>")
787 (buffer-substring (point) (save-excursion (skip-syntax-backward "w")
789 (unless (and (char-after) (eq (char-syntax (char-after)) ?w))
792 (defun company-grab-symbol-cons (idle-begin-after-re &optional max-len)
793 (let ((symbol (company-grab-symbol)))
796 (forward-char (- (length symbol)))
797 (if (looking-back idle-begin-after-re (if max-len
799 (line-beginning-position)))
803 (defun company-in-string-or-comment ()
804 (let ((ppss (syntax-ppss)))
805 (or (car (setq ppss (nthcdr 3 ppss)))
806 (car (setq ppss (cdr ppss)))
809 (defun company-call-backend (&rest args)
810 (company--force-sync #'company-call-backend-raw args company-backend))
812 (defun company--force-sync (fun args backend)
813 (let ((value (apply fun args)))
814 (if (not (eq (car-safe value) :async))
817 (start (time-to-seconds)))
819 (lambda (result) (setq res result)))
820 (while (eq res 'trash)
821 (if (> (- (time-to-seconds) start) company-async-timeout)
822 (error "Company: Back-end %s async timeout with args %s"
824 (sleep-for company-async-wait)))
827 (defun company-call-backend-raw (&rest args)
829 (if (functionp company-backend)
830 (apply company-backend args)
831 (apply #'company--multi-backend-adapter company-backend args))
832 (error (error "Company: Back-end %s error \"%s\" with args %s"
833 company-backend (error-message-string err) args))))
835 (defun company--multi-backend-adapter (backends command &rest args)
836 (let ((backends (loop for b in backends
837 when (not (and (symbolp b)
838 (eq 'failed (get b 'company-init))))
841 (if (eq command 'prefix)
842 (butlast backends (length (member :with backends)))
843 (delq :with backends)))
846 (company--multi-backend-adapter-candidates backends (car args)))
849 ((or `prefix `ignore-case `no-cache `require-match)
851 (dolist (backend backends)
852 (when (setq value (company--force-sync
853 backend (cons command args) backend))
856 (let ((arg (car args)))
857 (when (> (length arg) 0)
858 (let ((backend (or (get-text-property 0 'company-backend arg)
860 (apply backend command args))))))))
862 (defun company--multi-backend-adapter-candidates (backends prefix)
863 (let ((pairs (loop for backend in (cdr backends)
864 when (equal (funcall backend 'prefix)
866 collect (cons (funcall backend 'candidates prefix)
871 (propertize str 'company-backend b))
873 (when (equal (funcall (car backends) 'prefix) prefix)
874 ;; Small perf optimization: don't tag the candidates received
875 ;; from the first backend in the group.
876 (push (cons (funcall (car backends) 'candidates prefix)
879 (company--merge-async pairs (lambda (values) (apply #'append values)))))
881 (defun company--merge-async (pairs merger)
882 (let ((async (loop for pair in pairs
884 (eq :async (car-safe (car pair))))))
886 (funcall merger (loop for (val . mapper) in pairs
887 collect (funcall mapper val)))
898 (let ((val (car pair))
900 (if (not (eq :async (car-safe val)))
901 (push (funcall mapper val) lst)
905 (push fetcher pending)
908 (setq pending (delq fetcher pending))
909 (setcar cell (funcall mapper res))
910 (funcall finisher)))))))))))))
912 ;;; completion mechanism ;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;
914 (defvar company-prefix nil)
915 (make-variable-buffer-local 'company-prefix)
917 (defvar company-candidates nil)
918 (make-variable-buffer-local 'company-candidates)
920 (defvar company-candidates-length nil)
921 (make-variable-buffer-local 'company-candidates-length)
923 (defvar company-candidates-cache nil)
924 (make-variable-buffer-local 'company-candidates-cache)
926 (defvar company-candidates-predicate nil)
927 (make-variable-buffer-local 'company-candidates-predicate)
929 (defvar company-common nil)
930 (make-variable-buffer-local 'company-common)
932 (defvar company-selection 0)
933 (make-variable-buffer-local 'company-selection)
935 (defvar company-selection-changed nil)
936 (make-variable-buffer-local 'company-selection-changed)
938 (defvar company--manual-action nil
939 "Non-nil, if manual completion took place.")
940 (make-variable-buffer-local 'company--manual-action)
942 (defvar company--manual-prefix nil)
943 (make-variable-buffer-local 'company--manual-prefix)
945 (defvar company--auto-completion nil
946 "Non-nil when current candidate is being inserted automatically.
947 Controlled by `company-auto-complete'.")
949 (defvar company--point-max nil)
950 (make-variable-buffer-local 'company--point-max)
952 (defvar company-point nil)
953 (make-variable-buffer-local 'company-point)
955 (defvar company-timer nil)
957 (defvar company-added-newline nil)
958 (make-variable-buffer-local 'company-added-newline)
960 (defsubst company-strip-prefix (str)
961 (substring str (length company-prefix)))
963 (defun company--insert-candidate (candidate)
964 (setq candidate (substring-no-properties candidate))
965 ;; XXX: Return value we check here is subject to change.
966 (if (eq (company-call-backend 'ignore-case) 'keep-prefix)
967 (insert (company-strip-prefix candidate))
968 (delete-region (- (point) (length company-prefix)) (point))
971 (defmacro company-with-candidate-inserted (candidate &rest body)
972 "Evaluate BODY with CANDIDATE temporarily inserted.
973 This is a tool for back-ends that need candidates inserted before they
974 can retrieve meta-data for them."
976 `(let ((inhibit-modification-hooks t)
977 (inhibit-point-motion-hooks t)
978 (modified-p (buffer-modified-p)))
979 (company--insert-candidate ,candidate)
982 (delete-region company-point (point)))))
984 (defun company-explicit-action-p ()
985 "Return whether explicit completion action was taken by the user."
986 (or company--manual-action
987 company-selection-changed))
989 (defun company-reformat (candidate)
990 ;; company-ispell needs this, because the results are always lower-case
991 ;; It's mory efficient to fix it only when they are displayed.
992 ;; FIXME: Adopt the current text's capitalization instead?
993 (if (eq (company-call-backend 'ignore-case) 'keep-prefix)
994 (concat company-prefix (substring candidate (length company-prefix)))
997 (defun company--should-complete ()
998 (and (not (or buffer-read-only overriding-terminal-local-map
999 overriding-local-map))
1000 ;; Check if in the middle of entering a key combination.
1001 (or (equal (this-command-keys-vector) [])
1002 (not (keymapp (key-binding (this-command-keys-vector)))))
1003 (eq company-idle-delay t)
1004 (or (eq t company-begin-commands)
1005 (memq this-command company-begin-commands)
1006 (and (symbolp this-command) (get this-command 'company-begin)))
1007 (not (and transient-mark-mode mark-active))))
1009 (defun company--should-continue ()
1010 (or (eq t company-begin-commands)
1011 (eq t company-continue-commands)
1012 (if (eq 'not (car company-continue-commands))
1013 (not (memq this-command (cdr company-continue-commands)))
1014 (or (memq this-command company-begin-commands)
1015 (memq this-command company-continue-commands)
1016 (string-match-p "\\`company-" (symbol-name this-command))))))
1018 (defun company-call-frontends (command)
1019 (dolist (frontend company-frontends)
1021 (funcall frontend command)
1022 (error (error "Company: Front-end %s error \"%s\" on command %s"
1023 frontend (error-message-string err) command)))))
1025 (defun company-set-selection (selection &optional force-update)
1027 (if company-selection-wrap-around
1028 (mod selection company-candidates-length)
1029 (max 0 (min (1- company-candidates-length) selection))))
1030 (when (or force-update (not (equal selection company-selection)))
1031 (setq company-selection selection
1032 company-selection-changed t)
1033 (company-call-frontends 'update)))
1035 (defun company-apply-predicate (candidates predicate)
1037 (dolist (c candidates)
1038 (when (funcall predicate c)
1042 (defun company-update-candidates (candidates)
1043 (setq company-candidates-length (length candidates))
1044 (if (> company-selection 0)
1045 ;; Try to restore the selection
1046 (let ((selected (nth company-selection company-candidates)))
1047 (setq company-selection 0
1048 company-candidates candidates)
1050 (while (and candidates (string< (pop candidates) selected))
1051 (incf company-selection))
1053 ;; Make sure selection isn't out of bounds.
1054 (setq company-selection (min (1- company-candidates-length)
1055 company-selection)))))
1056 (setq company-selection 0
1057 company-candidates candidates))
1059 (push (cons company-prefix company-candidates) company-candidates-cache)
1060 ;; Calculate common.
1061 (let ((completion-ignore-case (company-call-backend 'ignore-case)))
1062 ;; We want to support non-prefix completion, so filtering is the
1063 ;; responsibility of each respective backend, not ours.
1064 ;; On the other hand, we don't want to replace non-prefix input in
1065 ;; `company-complete-common'.
1066 (setq company-common
1067 (if (cdr company-candidates)
1068 (let ((common (try-completion company-prefix company-candidates)))
1070 ;; Mulple equal strings, probably with different
1074 (car company-candidates)))))
1076 (defun company-calculate-candidates (prefix)
1077 (let ((candidates (cdr (assoc prefix company-candidates-cache)))
1078 (ignore-case (company-call-backend 'ignore-case)))
1080 (when company-candidates-cache
1081 (let ((len (length prefix))
1082 (completion-ignore-case ignore-case)
1084 (dotimes (i (1+ len))
1085 (when (setq prev (cdr (assoc (substring prefix 0 (- len i))
1086 company-candidates-cache)))
1087 (setq candidates (all-completions prefix prev))
1089 ;; no cache match, call back-end
1091 (company--process-candidates
1092 (company--fetch-candidates prefix))))
1093 (setq candidates (company--transform-candidates candidates))
1095 (if (or (cdr candidates)
1096 (not (eq t (compare-strings (car candidates) nil nil
1097 prefix nil nil ignore-case))))
1099 ;; Already completed and unique; don't start.
1102 (defun company--fetch-candidates (prefix)
1103 (let ((c (if company--manual-action
1104 (company-call-backend 'candidates prefix)
1105 (company-call-backend-raw 'candidates prefix)))
1107 (if (not (eq (car c) :async))
1109 (let ((buf (current-buffer))
1110 (win (selected-window))
1111 (tick (buffer-chars-modified-tick))
1113 (backend company-backend))
1116 (lambda (candidates)
1117 (if (not (and candidates (eq res 'done)))
1118 ;; Fetcher called us right back.
1119 (setq res candidates)
1120 (setq company-backend backend
1121 company-candidates-cache
1123 (company--process-candidates
1125 (company-idle-begin buf win tick pt)))))
1126 ;; FIXME: Relying on the fact that the callers
1127 ;; will interpret nil as "do nothing" is shaky.
1128 ;; A throw-catch would be one possible improvement.
1130 (progn (setq res 'done) nil)))))
1132 (defun company--process-candidates (candidates)
1133 (when company-candidates-predicate
1135 (company-apply-predicate candidates
1136 company-candidates-predicate)))
1137 (unless (company-call-backend 'sorted)
1138 (setq candidates (sort candidates 'string<)))
1139 (when (company-call-backend 'duplicates)
1140 (company--strip-duplicates candidates))
1143 (defun company--strip-duplicates (candidates)
1144 (let ((c2 candidates))
1147 (let ((str (car c2))
1150 (while (let ((str2 (car c2)))
1151 (if (not (equal str str2))
1153 (when (eq anno 'unk)
1154 (setq anno (company-call-backend
1157 (company-call-backend
1158 'annotation str2))))
1162 (defun company--transform-candidates (candidates)
1163 (let ((c candidates))
1164 (dolist (tr company-transformers)
1165 (setq c (funcall tr c)))
1168 (defun company-sort-by-occurrence (candidates)
1169 "Sort CANDIDATES according to their occurrences.
1170 Searches for each in the currently visible part of the current buffer and
1171 gives priority to the closest ones above point, then closest ones below
1172 point. The rest of the list is appended unchanged.
1173 Keywords and function definition names are ignored."
1180 (progn (forward-line 0)
1181 (search-backward candidate (window-start) t)))
1183 (search-forward candidate (window-end) t)))
1184 (let ((beg (match-beginning 0))
1185 (end (match-end 0)))
1186 (when (save-excursion
1188 (and (not (memq (get-text-property (point) 'face)
1189 '(font-lock-function-name-face
1190 font-lock-keyword-face)))
1191 (let* ((prefix (company-call-backend 'prefix))
1192 (prefix (or (car-safe prefix) prefix)))
1193 (and (stringp prefix)
1194 (= (length prefix) (- end beg))))))
1195 (push (cons candidate (if (< beg (point))
1197 (- beg (window-start))))
1202 (mapcar #'car (sort occurs (lambda (e1 e2) (<= (cdr e1) (cdr e2)))))
1205 (defun company-idle-begin (buf win tick pos)
1206 (and (eq buf (current-buffer))
1207 (eq win (selected-window))
1208 (eq tick (buffer-chars-modified-tick))
1210 (when (company-auto-begin)
1211 (when (version< emacs-version "24.3.50")
1212 (company-input-noop))
1213 (company-post-command))))
1215 (defun company-auto-begin ()
1217 (not company-candidates)
1218 (let ((company-idle-delay t)
1219 (company-begin-commands t))
1220 (condition-case-unless-debug err
1222 (error (message "Company: An error occurred in auto-begin")
1223 (message "%s" (error-message-string err))
1225 (quit (company-cancel)))))
1226 (unless company-candidates
1227 (setq company-backend nil))
1228 ;; Return non-nil if active.
1231 (defun company-manual-begin ()
1233 (company-assert-enabled)
1234 (setq company--manual-action t)
1236 (let ((company-minimum-prefix-length 0))
1237 (company-auto-begin))
1238 (unless company-candidates
1239 (setq company--manual-action nil))))
1241 (defun company-other-backend (&optional backward)
1242 (interactive (list current-prefix-arg))
1243 (company-assert-enabled)
1245 (let* ((after (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 (dolist (backend next)
1252 (when (ignore-errors (company-begin-backend backend))
1254 (company-manual-begin))
1255 (unless company-candidates
1256 (error "No other back-end")))
1258 (defun company-require-match-p ()
1259 (let ((backend-value (company-call-backend 'require-match)))
1260 (or (eq backend-value t)
1261 (and (not (eq backend-value 'never))
1262 (if (functionp company-require-match)
1263 (funcall company-require-match)
1264 (eq company-require-match t))))))
1266 (defun company-auto-complete-p (input)
1267 "Return non-nil, if input starts with punctuation or parentheses."
1268 (and (if (functionp company-auto-complete)
1269 (funcall company-auto-complete)
1270 company-auto-complete)
1271 (if (functionp company-auto-complete-chars)
1272 (funcall company-auto-complete-chars input)
1273 (if (consp company-auto-complete-chars)
1274 (memq (char-syntax (string-to-char input))
1275 company-auto-complete-chars)
1276 (string-match (substring input 0 1) company-auto-complete-chars)))))
1278 (defun company--incremental-p ()
1279 (and (> (point) company-point)
1280 (> (point-max) company--point-max)
1281 (not (eq this-command 'backward-delete-char-untabify))
1282 (equal (buffer-substring (- company-point (length company-prefix))
1286 (defun company--continue-failed ()
1287 (let ((input (buffer-substring-no-properties (point) company-point)))
1289 ((company-auto-complete-p input)
1292 (goto-char company-point)
1293 (let ((company--auto-completion t))
1294 (company-complete-selection))
1296 ((company-require-match-p)
1297 ;; wrong incremental input, but required match
1298 (delete-char (- (length input)))
1300 (message "Matching input is required")
1302 ((equal company-prefix (car company-candidates))
1303 ;; last input was actually success
1304 (company-cancel company-prefix))
1305 (t (company-cancel)))))
1307 (defun company--good-prefix-p (prefix)
1308 (and (stringp (or (car-safe prefix) prefix)) ;excludes 'stop
1309 (or (eq (cdr-safe prefix) t)
1310 (let ((len (or (cdr-safe prefix) (length prefix))))
1311 (if company--manual-prefix
1312 (or (not company-abort-manual-when-too-short)
1313 ;; Must not be less than minimum or initial length.
1314 (>= len (min company-minimum-prefix-length
1315 (length company--manual-prefix))))
1316 (>= len company-minimum-prefix-length))))))
1318 (defun company--continue ()
1319 (when (company-call-backend 'no-cache company-prefix)
1320 ;; Don't complete existing candidates, fetch new ones.
1321 (setq company-candidates-cache nil))
1322 (let* ((new-prefix (company-call-backend 'prefix))
1323 (c (when (and (company--good-prefix-p new-prefix)
1324 (setq new-prefix (or (car-safe new-prefix) new-prefix))
1325 (= (- (point) (length new-prefix))
1326 (- company-point (length company-prefix))))
1327 (company-calculate-candidates new-prefix))))
1330 ;; t means complete/unique.
1331 (company-cancel new-prefix))
1333 ;; incremental match
1334 (setq company-prefix new-prefix)
1335 (company-update-candidates c)
1337 ((not (company--incremental-p))
1339 (t (company--continue-failed)))))
1341 (defun company--begin-new ()
1343 (dolist (backend (if company-backend
1344 ;; prefer manual override
1345 (list company-backend)
1348 (if (or (symbolp backend)
1349 (functionp backend))
1350 (when (or (not (symbolp backend))
1351 (eq t (get backend 'company-init))
1352 (unless (get backend 'company-init)
1353 (company-init-backend backend)))
1354 (funcall backend 'prefix))
1355 (company--multi-backend-adapter backend 'prefix)))
1357 (when (company--good-prefix-p prefix)
1358 (setq prefix (or (car-safe prefix) prefix)
1359 company-backend backend
1360 c (company-calculate-candidates prefix))
1361 ;; t means complete/unique. We don't start, so no hooks.
1363 (when company--manual-action
1364 (message "No completion found"))
1365 (setq company-prefix prefix)
1366 (when company--manual-action
1367 (setq company--manual-prefix prefix))
1368 (when (symbolp backend)
1369 (setq company-lighter (concat " " (symbol-name backend))))
1370 (company-update-candidates c)
1371 (run-hook-with-args 'company-completion-started-hook
1372 (company-explicit-action-p))
1373 (company-call-frontends 'show)))
1376 (defun company-begin ()
1377 (or (and company-candidates (company--continue))
1378 (and (company--should-complete) (company--begin-new)))
1379 (when company-candidates
1380 (let ((modified (buffer-modified-p)))
1381 (when (and company-end-of-buffer-workaround (eobp))
1382 (save-excursion (insert "\n"))
1383 (setq company-added-newline
1384 (or modified (buffer-chars-modified-tick)))))
1385 (setq company-point (point)
1386 company--point-max (point-max))
1387 (company-ensure-emulation-alist)
1388 (company-enable-overriding-keymap company-active-map)
1389 (company-call-frontends 'update)))
1391 (defun company-cancel (&optional result)
1392 (and company-added-newline
1393 (> (point-max) (point-min))
1394 (let ((tick (buffer-chars-modified-tick)))
1395 (delete-region (1- (point-max)) (point-max))
1396 (equal tick company-added-newline))
1397 ;; Only set unmodified when tick remained the same since insert,
1398 ;; and the buffer wasn't modified before.
1399 (set-buffer-modified-p nil))
1400 (when company-prefix
1401 (if (stringp result)
1403 (company-call-backend 'pre-completion result)
1404 (run-hook-with-args 'company-completion-finished-hook result)
1405 (company-call-backend 'post-completion result))
1406 (run-hook-with-args 'company-completion-cancelled-hook result)))
1407 (setq company-added-newline nil
1410 company-candidates nil
1411 company-candidates-length nil
1412 company-candidates-cache nil
1413 company-candidates-predicate nil
1416 company-selection-changed nil
1417 company--manual-action nil
1418 company--manual-prefix nil
1419 company-lighter company-default-lighter
1420 company--point-max nil
1423 (cancel-timer company-timer))
1424 (company-search-mode 0)
1425 (company-call-frontends 'hide)
1426 (company-enable-overriding-keymap nil)
1427 ;; Make return value explicit.
1430 (defun company-abort ()
1433 ;; Don't start again, unless started manually.
1434 (setq company-point (point)))
1436 (defun company-finish (result)
1437 (company--insert-candidate result)
1438 (company-cancel result)
1439 ;; Don't start again, unless started manually.
1440 (setq company-point (point)))
1442 (defsubst company-keep (command)
1443 (and (symbolp command) (get command 'company-keep)))
1445 (defun company-pre-command ()
1446 (unless (company-keep this-command)
1448 (when company-candidates
1449 (company-call-frontends 'pre-command)
1450 (unless (company--should-continue)
1452 (error (message "Company: An error occurred in pre-command")
1453 (message "%s" (error-message-string err))
1456 (cancel-timer company-timer)
1457 (setq company-timer nil))
1458 (company-uninstall-map))
1460 (defun company-post-command ()
1461 (unless (company-keep this-command)
1464 (unless (equal (point) company-point)
1466 (if company-candidates
1467 (company-call-frontends 'post-command)
1468 (and (numberp company-idle-delay)
1469 (or (eq t company-begin-commands)
1470 (memq this-command company-begin-commands))
1471 (not (equal (point) company-point))
1473 (run-with-timer company-idle-delay nil
1475 (current-buffer) (selected-window)
1476 (buffer-chars-modified-tick) (point))))))
1477 (error (message "Company: An error occurred in post-command")
1478 (message "%s" (error-message-string err))
1480 (company-install-map))
1482 ;;; search ;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;
1484 (defvar company-search-string nil)
1485 (make-variable-buffer-local 'company-search-string)
1487 (defvar company-search-lighter " Search: \"\"")
1488 (make-variable-buffer-local 'company-search-lighter)
1490 (defvar company-search-old-map nil)
1491 (make-variable-buffer-local 'company-search-old-map)
1493 (defvar company-search-old-selection 0)
1494 (make-variable-buffer-local 'company-search-old-selection)
1496 (defun company-search (text lines)
1497 (let ((quoted (regexp-quote text))
1499 (dolist (line lines)
1500 (when (string-match quoted line (length company-prefix))
1504 (defun company-search-printing-char ()
1506 (company-search-assert-enabled)
1507 (setq company-search-string
1508 (concat (or company-search-string "") (string last-command-event))
1509 company-search-lighter (concat " Search: \"" company-search-string
1511 (let ((pos (company-search company-search-string
1512 (nthcdr company-selection company-candidates))))
1515 (company-set-selection (+ company-selection pos) t))))
1517 (defun company-search-repeat-forward ()
1518 "Repeat the incremental search in completion candidates forward."
1520 (company-search-assert-enabled)
1521 (let ((pos (company-search company-search-string
1522 (cdr (nthcdr company-selection
1523 company-candidates)))))
1526 (company-set-selection (+ company-selection pos 1) t))))
1528 (defun company-search-repeat-backward ()
1529 "Repeat the incremental search in completion candidates backwards."
1531 (company-search-assert-enabled)
1532 (let ((pos (company-search company-search-string
1533 (nthcdr (- company-candidates-length
1535 (reverse company-candidates)))))
1538 (company-set-selection (- company-selection pos 1) t))))
1540 (defun company-create-match-predicate ()
1541 (setq company-candidates-predicate
1542 `(lambda (candidate)
1543 ,(if company-candidates-predicate
1544 `(and (string-match ,company-search-string candidate)
1545 (funcall ,company-candidates-predicate
1547 `(string-match ,company-search-string candidate))))
1548 (company-update-candidates
1549 (company-apply-predicate company-candidates company-candidates-predicate))
1550 ;; Invalidate cache.
1551 (setq company-candidates-cache (cons company-prefix company-candidates)))
1553 (defun company-filter-printing-char ()
1555 (company-search-assert-enabled)
1556 (company-search-printing-char)
1557 (company-create-match-predicate)
1558 (company-call-frontends 'update))
1560 (defun company-search-kill-others ()
1561 "Limit the completion candidates to the ones matching the search string."
1563 (company-search-assert-enabled)
1564 (company-create-match-predicate)
1565 (company-search-mode 0)
1566 (company-call-frontends 'update))
1568 (defun company-search-abort ()
1569 "Abort searching the completion candidates."
1571 (company-search-assert-enabled)
1572 (company-set-selection company-search-old-selection t)
1573 (company-search-mode 0))
1575 (defun company-search-other-char ()
1577 (company-search-assert-enabled)
1578 (company-search-mode 0)
1579 (company--unread-last-input))
1581 (defvar company-search-map
1583 (keymap (make-keymap)))
1584 (if (fboundp 'max-char)
1585 (set-char-table-range (nth 1 keymap) (cons #x100 (max-char))
1586 'company-search-printing-char)
1588 ;; obsolete in Emacs 23
1589 (let ((l (generic-character-list))
1590 (table (nth 1 keymap)))
1592 (set-char-table-default table (car l) 'company-search-printing-char)
1593 (setq l (cdr l))))))
1594 (define-key keymap [t] 'company-search-other-char)
1596 (define-key keymap (make-string 1 i) 'company-search-other-char)
1599 (define-key keymap (vector i) 'company-search-printing-char)
1601 (let ((meta-map (make-sparse-keymap)))
1602 (define-key keymap (char-to-string meta-prefix-char) meta-map)
1603 (define-key keymap [escape] meta-map))
1604 (define-key keymap (vector meta-prefix-char t) 'company-search-other-char)
1605 (define-key keymap "\e\e\e" 'company-search-other-char)
1606 (define-key keymap [escape escape escape] 'company-search-other-char)
1608 (define-key keymap "\C-g" 'company-search-abort)
1609 (define-key keymap "\C-s" 'company-search-repeat-forward)
1610 (define-key keymap "\C-r" 'company-search-repeat-backward)
1611 (define-key keymap "\C-o" 'company-search-kill-others)
1613 "Keymap used for incrementally searching the completion candidates.")
1615 (define-minor-mode company-search-mode
1616 "Search mode for completion candidates.
1617 Don't start this directly, use `company-search-candidates' or
1618 `company-filter-candidates'."
1619 nil company-search-lighter nil
1620 (if company-search-mode
1621 (if (company-manual-begin)
1623 (setq company-search-old-selection company-selection)
1624 (company-call-frontends 'update))
1625 (setq company-search-mode nil))
1626 (kill-local-variable 'company-search-string)
1627 (kill-local-variable 'company-search-lighter)
1628 (kill-local-variable 'company-search-old-selection)
1629 (company-enable-overriding-keymap company-active-map)))
1631 (defun company-search-assert-enabled ()
1632 (company-assert-enabled)
1633 (unless company-search-mode
1634 (company-uninstall-map)
1635 (error "Company not in search mode")))
1637 (defun company-search-candidates ()
1638 "Start searching the completion candidates incrementally.
1640 \\<company-search-map>Search can be controlled with the commands:
1641 - `company-search-repeat-forward' (\\[company-search-repeat-forward])
1642 - `company-search-repeat-backward' (\\[company-search-repeat-backward])
1643 - `company-search-abort' (\\[company-search-abort])
1645 Regular characters are appended to the search string.
1647 The command `company-search-kill-others' (\\[company-search-kill-others])
1648 uses the search string to limit the completion candidates."
1650 (company-search-mode 1)
1651 (company-enable-overriding-keymap company-search-map))
1653 (defvar company-filter-map
1654 (let ((keymap (make-keymap)))
1655 (define-key keymap [remap company-search-printing-char]
1656 'company-filter-printing-char)
1657 (set-keymap-parent keymap company-search-map)
1659 "Keymap used for incrementally searching the completion candidates.")
1661 (defun company-filter-candidates ()
1662 "Start filtering the completion candidates incrementally.
1663 This works the same way as `company-search-candidates' immediately
1664 followed by `company-search-kill-others' after each input."
1666 (company-search-mode 1)
1667 (company-enable-overriding-keymap company-filter-map))
1669 ;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;
1671 (defun company-select-next ()
1672 "Select the next candidate in the list."
1674 (when (company-manual-begin)
1675 (company-set-selection (1+ company-selection))))
1677 (defun company-select-previous ()
1678 "Select the previous candidate in the list."
1680 (when (company-manual-begin)
1681 (company-set-selection (1- company-selection))))
1683 (defun company-select-next-or-abort ()
1684 "Select the next candidate if more than one, else abort
1685 and invoke the normal binding."
1687 (if (> company-candidates-length 1)
1688 (company-select-next)
1690 (company--unread-last-input)))
1692 (defun company-select-previous-or-abort ()
1693 "Select the previous candidate if more than one, else abort
1694 and invoke the normal binding."
1696 (if (> company-candidates-length 1)
1697 (company-select-previous)
1699 (company--unread-last-input)))
1701 (defvar company-pseudo-tooltip-overlay)
1703 (defvar company-tooltip-offset)
1705 (defun company--inside-tooltip-p (event-col-row row height)
1706 (let* ((ovl company-pseudo-tooltip-overlay)
1707 (column (overlay-get ovl 'company-column))
1708 (width (overlay-get ovl 'company-width))
1709 (evt-col (car event-col-row))
1710 (evt-row (cdr event-col-row)))
1711 (and (>= evt-col column)
1712 (< evt-col (+ column width))
1714 (and (> evt-row row)
1715 (<= evt-row (+ row height) ))
1716 (and (< evt-row row)
1717 (>= evt-row (+ row height)))))))
1719 (defun company--event-col-row (event)
1720 (let* ((col-row (posn-actual-col-row (event-start event)))
1722 (row (cdr col-row)))
1723 (incf col (window-hscroll))
1724 (and header-line-format
1725 (version< "24" emacs-version)
1729 (defun company-select-mouse (event)
1730 "Select the candidate picked by the mouse."
1732 (let ((event-col-row (company--event-col-row event))
1733 (ovl-row (company--row))
1734 (ovl-height (and company-pseudo-tooltip-overlay
1735 (min (overlay-get company-pseudo-tooltip-overlay
1737 company-candidates-length))))
1739 (company--inside-tooltip-p event-col-row ovl-row ovl-height))
1741 (company-set-selection (+ (cdr event-col-row)
1742 (1- company-tooltip-offset)
1743 (if (and (eq company-tooltip-offset-display 'lines)
1744 (not (zerop company-tooltip-offset)))
1747 (if (< ovl-height 0)
1752 (company--unread-last-input)
1755 (defun company-complete-mouse (event)
1756 "Insert the candidate picked by the mouse."
1758 (when (company-select-mouse event)
1759 (company-complete-selection)))
1761 (defun company-complete-selection ()
1762 "Insert the selected candidate."
1764 (when (company-manual-begin)
1765 (let ((result (nth company-selection company-candidates)))
1766 (company-finish result))))
1768 (defun company-complete-common ()
1769 "Insert the common part of all candidates."
1771 (when (company-manual-begin)
1772 (if (and (not (cdr company-candidates))
1773 (equal company-common (car company-candidates)))
1774 (company-complete-selection)
1775 (when company-common
1776 (company--insert-candidate company-common)))))
1778 (defun company-complete ()
1779 "Insert the common part of all candidates or the current selection.
1780 The first time this is called, the common part is inserted, the second
1781 time, or when the selection has been changed, the selected candidate is
1784 (when (company-manual-begin)
1785 (if (or company-selection-changed
1786 (eq last-command 'company-complete-common))
1787 (call-interactively 'company-complete-selection)
1788 (call-interactively 'company-complete-common)
1789 (setq this-command 'company-complete-common))))
1791 (defun company-complete-number (n)
1792 "Insert the Nth candidate.
1793 To show the number next to the candidates in some back-ends, enable
1794 `company-show-numbers'."
1795 (when (company-manual-begin)
1796 (and (< n 1) (> n company-candidates-length)
1797 (error "No candidate number %d" n))
1799 (company-finish (nth n company-candidates))))
1801 ;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;
1803 (defconst company-space-strings-limit 100)
1805 (defconst company-space-strings
1807 (dotimes (i company-space-strings-limit)
1808 (push (make-string (- company-space-strings-limit 1 i) ?\ ) lst))
1809 (apply 'vector lst)))
1811 (defun company-space-string (len)
1812 (if (< len company-space-strings-limit)
1813 (aref company-space-strings len)
1814 (make-string len ?\ )))
1816 (defun company-safe-substring (str from &optional to)
1817 (if (> from (string-width str))
1821 (move-to-column from)
1822 (let ((beg (point)))
1826 (concat (buffer-substring beg (point))
1827 (let ((padding (- to (current-column))))
1829 (company-space-string padding)))))
1830 (buffer-substring beg (point-max)))))))
1832 ;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;
1834 (defvar company-last-metadata nil)
1835 (make-variable-buffer-local 'company-last-metadata)
1837 (defun company-fetch-metadata ()
1838 (let ((selected (nth company-selection company-candidates)))
1839 (unless (eq selected (car company-last-metadata))
1840 (setq company-last-metadata
1841 (cons selected (company-call-backend 'meta selected))))
1842 (cdr company-last-metadata)))
1844 (defun company-doc-buffer (&optional string)
1845 (with-current-buffer (get-buffer-create "*company-documentation*")
1852 (defvar company--electric-commands
1853 '(scroll-other-window scroll-other-window-down)
1854 "List of Commands that won't break out of electric commands.")
1856 (defmacro company--electric-do (&rest body)
1857 (declare (indent 0) (debug t))
1858 `(when (company-manual-begin)
1859 (save-window-excursion
1860 (let ((height (window-height))
1861 (row (company--row))
1864 (and (< (window-height) height)
1865 (< (- (window-height) row 2) company-tooltip-limit)
1866 (recenter (- (window-height) row 2)))
1867 (while (memq (setq cmd (key-binding (vector (list (read-event)))))
1868 company--electric-commands)
1869 (call-interactively cmd))
1870 (company--unread-last-input)))))
1872 (defun company--unread-last-input ()
1873 (when last-input-event
1874 (clear-this-command-keys t)
1875 (setq unread-command-events (list last-input-event))))
1877 (defun company-show-doc-buffer ()
1878 "Temporarily show the documentation buffer for the selection."
1880 (company--electric-do
1881 (let* ((selected (nth company-selection company-candidates))
1882 (doc-buffer (or (company-call-backend 'doc-buffer selected)
1883 (error "No documentation available"))))
1884 (with-current-buffer doc-buffer
1885 (goto-char (point-min)))
1886 (display-buffer doc-buffer t))))
1887 (put 'company-show-doc-buffer 'company-keep t)
1889 (defun company-show-location ()
1890 "Temporarily display a buffer showing the selected candidate in context."
1892 (company--electric-do
1893 (let* ((selected (nth company-selection company-candidates))
1894 (location (company-call-backend 'location selected))
1895 (pos (or (cdr location) (error "No location available")))
1896 (buffer (or (and (bufferp (car location)) (car location))
1897 (find-file-noselect (car location) t))))
1898 (with-selected-window (display-buffer buffer t)
1901 (if (bufferp (car location))
1903 (goto-char (point-min))
1904 (forward-line (1- pos))))
1905 (set-window-start nil (point))))))
1906 (put 'company-show-location 'company-keep t)
1908 ;;; package functions ;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;
1910 (defvar company-callback nil)
1911 (make-variable-buffer-local 'company-callback)
1913 (defun company-remove-callback (&optional ignored)
1914 (remove-hook 'company-completion-finished-hook company-callback t)
1915 (remove-hook 'company-completion-cancelled-hook 'company-remove-callback t)
1916 (remove-hook 'company-completion-finished-hook 'company-remove-callback t))
1918 (defun company-begin-backend (backend &optional callback)
1919 "Start a completion at point using BACKEND."
1920 (interactive (let ((val (completing-read "Company back-end: "
1922 'functionp nil "company-")))
1924 (list (intern val)))))
1925 (when (setq company-callback callback)
1926 (add-hook 'company-completion-finished-hook company-callback nil t))
1927 (add-hook 'company-completion-cancelled-hook 'company-remove-callback nil t)
1928 (add-hook 'company-completion-finished-hook 'company-remove-callback nil t)
1929 (setq company-backend backend)
1930 ;; Return non-nil if active.
1931 (or (company-manual-begin)
1932 (error "Cannot complete at point")))
1934 (defun company-begin-with (candidates
1935 &optional prefix-length require-match callback)
1936 "Start a completion at point.
1937 CANDIDATES is the list of candidates to use and PREFIX-LENGTH is the length
1938 of the prefix that already is in the buffer before point.
1941 CALLBACK is a function called with the selected result if the user
1942 successfully completes the input.
1944 Example: \(company-begin-with '\(\"foo\" \"foobar\" \"foobarbaz\"\)\)"
1945 (let ((begin-marker (copy-marker (point) t)))
1946 (company-begin-backend
1947 (lambda (command &optional arg &rest ignored)
1950 (when (equal (point) (marker-position begin-marker))
1951 (buffer-substring (- (point) (or prefix-length 0)) (point))))
1953 (all-completions arg candidates))
1958 (defun company-version (&optional show-version)
1959 "Get the Company version as string.
1961 If SHOW-VERSION is non-nil, show the version in the echo area."
1962 (interactive (list t))
1964 (insert-file-contents (find-library-name "company"))
1967 (message "Company version: %s" (lm-version))
1970 ;;; pseudo-tooltip ;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;
1972 (defvar company-pseudo-tooltip-overlay nil)
1973 (make-variable-buffer-local 'company-pseudo-tooltip-overlay)
1975 (defvar company-tooltip-offset 0)
1976 (make-variable-buffer-local 'company-tooltip-offset)
1978 (defun company-tooltip--lines-update-offset (selection num-lines limit)
1980 (setq company-tooltip-offset
1981 (max (min selection company-tooltip-offset)
1982 (- selection -1 limit)))
1984 (when (<= company-tooltip-offset 1)
1986 (setq company-tooltip-offset 0))
1988 (when (>= company-tooltip-offset (- num-lines limit 1))
1990 (when (= selection (1- num-lines))
1991 (decf company-tooltip-offset)
1992 (when (<= company-tooltip-offset 1)
1993 (setq company-tooltip-offset 0)
1998 (defun company-tooltip--simple-update-offset (selection num-lines limit)
1999 (setq company-tooltip-offset
2000 (if (< selection company-tooltip-offset)
2002 (max company-tooltip-offset
2003 (- selection limit -1)))))
2007 (defsubst company-round-tab (arg)
2008 (* (/ (+ arg tab-width) tab-width) tab-width))
2010 (defun company-plainify (str)
2011 (let ((prefix (get-text-property 0 'line-prefix str)))
2012 (when prefix ; Keep the original value unmodified, for no special reason.
2013 (setq str (concat prefix str))
2014 (remove-text-properties 0 (length str) '(line-prefix) str)))
2015 (let* ((pieces (split-string str "\t"))
2018 (setcar copy (company-safe-substring
2019 (car copy) 0 (company-round-tab (string-width (car copy)))))
2021 (apply 'concat pieces)))
2023 (defun company-fill-propertize (value annotation width selected left right)
2024 (let* ((margin (length left))
2025 (common (+ (or (company-call-backend 'match value)
2026 (length company-common)) margin))
2027 (ann-ralign company-tooltip-align-annotations)
2028 (ann-truncate (< width
2029 (+ (length value) (length annotation)
2030 (if ann-ralign 1 0))))
2031 (ann-start (+ margin
2035 (- width (length annotation)))
2037 (ann-end (min (+ ann-start (length annotation)) (+ margin width)))
2039 (if (or ann-truncate (not ann-ralign))
2040 (company-safe-substring
2042 (when (and annotation ann-ralign) " ")
2046 (company-safe-substring value 0
2047 (- width (length annotation)))
2050 (setq width (+ width margin (length right)))
2052 (add-text-properties 0 width '(face company-tooltip
2053 mouse-face company-tooltip-mouse)
2055 (add-text-properties margin common
2056 '(face company-tooltip-common
2057 mouse-face company-tooltip-mouse)
2059 (when (< ann-start ann-end)
2060 (add-text-properties ann-start ann-end
2061 '(face company-tooltip-annotation
2062 mouse-face company-tooltip-mouse)
2065 (if (and company-search-string
2066 (string-match (regexp-quote company-search-string) value
2067 (length company-prefix)))
2068 (let ((beg (+ margin (match-beginning 0)))
2069 (end (+ margin (match-end 0))))
2070 (add-text-properties beg end '(face company-tooltip-selection)
2072 (when (< beg common)
2073 (add-text-properties beg common
2074 '(face company-tooltip-common-selection)
2076 (add-text-properties 0 width '(face company-tooltip-selection
2077 mouse-face company-tooltip-selection)
2079 (add-text-properties margin common
2080 '(face company-tooltip-common-selection
2081 mouse-face company-tooltip-selection)
2087 (defun company-buffer-lines (beg end)
2090 (while (and (= 1 (vertical-motion 1))
2092 (let ((bound (min end (1- (point)))))
2093 ;; A visual line can contain several physical lines (e.g. with outline's
2094 ;; folding overlay). Take only the first one.
2095 (push (buffer-substring beg
2098 (re-search-forward "$" bound 'move)
2102 (unless (eq beg end)
2103 (push (buffer-substring beg end) lines))
2106 (defun company-modify-line (old new offset)
2107 (concat (company-safe-substring old 0 offset)
2109 (company-safe-substring old (+ offset (length new)))))
2111 (defsubst company--length-limit (lst limit)
2112 (if (nthcdr limit lst)
2116 (defun company--replacement-string (lines old column nl &optional align-top)
2117 (decf column company-tooltip-margin)
2119 (let ((width (length (car lines)))
2120 (remaining-cols (- (+ (company--window-width) (window-hscroll))
2122 (when (> width remaining-cols)
2123 (decf column (- width remaining-cols))))
2125 (let ((offset (and (< column 0) (- column)))
2130 ;; untouched lines first
2131 (dotimes (_ (- (length old) (length lines)))
2132 (push (pop old) new)))
2133 ;; length into old lines.
2135 (push (company-modify-line (pop old)
2136 (company--offset-line (pop lines) offset)
2138 ;; Append whole new lines.
2140 (push (concat (company-space-string column)
2141 (company--offset-line (pop lines) offset))
2144 (let ((str (concat (when nl "\n")
2145 (mapconcat 'identity (nreverse new) "\n")
2147 (font-lock-append-text-property 0 (length str) 'face 'default str)
2150 (defun company--offset-line (line offset)
2151 (if (and offset line)
2152 (substring line offset)
2155 (defun company--create-lines (selection limit)
2156 (let ((len company-candidates-length)
2158 (window-width (company--window-width))
2167 ;; Maybe clear old offset.
2168 (when (< len (+ company-tooltip-offset limit))
2169 (setq company-tooltip-offset 0))
2171 ;; Scroll to offset.
2172 (if (eq company-tooltip-offset-display 'lines)
2173 (setq limit (company-tooltip--lines-update-offset selection len limit))
2174 (company-tooltip--simple-update-offset selection len limit))
2177 ((eq company-tooltip-offset-display 'scrollbar)
2178 (setq scrollbar-bounds (company--scrollbar-bounds company-tooltip-offset
2180 ((eq company-tooltip-offset-display 'lines)
2181 (when (> company-tooltip-offset 0)
2182 (setq previous (format "...(%d)" company-tooltip-offset)))
2183 (setq remainder (- len limit company-tooltip-offset)
2184 remainder (when (> remainder 0)
2185 (setq remainder (format "...(%d)" remainder))))))
2187 (decf selection company-tooltip-offset)
2188 (setq width (max (length previous) (length remainder))
2189 lines (nthcdr company-tooltip-offset company-candidates)
2193 (decf window-width (* 2 company-tooltip-margin))
2194 (when scrollbar-bounds (decf window-width))
2197 (let* ((value (pop lines-copy))
2198 (annotation (company-call-backend 'annotation value)))
2199 (when (and annotation company-tooltip-align-annotations)
2200 ;; `lisp-completion-at-point' adds a space.
2201 (setq annotation (comment-string-strip annotation t nil)))
2202 (push (cons value annotation) items)
2203 (setq width (max (+ (length value)
2204 (if (and annotation company-tooltip-align-annotations)
2205 (1+ (length annotation))
2206 (length annotation)))
2209 (setq width (min window-width
2210 (max company-tooltip-minimum-width
2211 (if (and company-show-numbers
2212 (< company-tooltip-offset 10))
2216 ;; number can make tooltip too long
2217 (when company-show-numbers
2218 (setq numbered company-tooltip-offset))
2220 (let ((items (nreverse items)) new)
2222 (push (company--scrollpos-line previous width) new))
2225 (let* ((item (pop items))
2226 (str (company-reformat (car item)))
2227 (annotation (cdr item))
2228 (right (company-space-string company-tooltip-margin))
2230 (when (< numbered 10)
2233 (setq right (concat (format " %d" (mod numbered 10)) right)))
2235 (company-fill-propertize str annotation
2236 width (equal i selection)
2237 (company-space-string
2238 company-tooltip-margin)
2240 (when scrollbar-bounds
2241 (company--scrollbar i scrollbar-bounds)))
2245 (push (company--scrollpos-line remainder width) new))
2249 (defun company--scrollbar-bounds (offset limit length)
2250 (when (> length limit)
2251 (let* ((size (ceiling (* limit (float limit)) length))
2252 (lower (floor (* limit (float offset)) length))
2253 (upper (+ lower size -1)))
2254 (cons lower upper))))
2256 (defun company--scrollbar (i bounds)
2257 (propertize " " 'face
2258 (if (and (>= i (car bounds)) (<= i (cdr bounds)))
2259 'company-scrollbar-fg
2260 'company-scrollbar-bg)))
2262 (defun company--scrollpos-line (text width)
2263 (propertize (concat (company-space-string company-tooltip-margin)
2264 (company-safe-substring text 0 width)
2265 (company-space-string company-tooltip-margin))
2266 'face 'company-tooltip))
2270 (defsubst company--window-inner-height ()
2271 (let ((edges (window-inside-edges)))
2272 (- (nth 3 edges) (nth 1 edges))))
2274 (defsubst company--window-width ()
2277 ((display-graphic-p) 0)
2278 ;; Account for the line continuation column.
2279 ((version< "24.3.1" emacs-version) 1)
2280 ;; Emacs 24.3 and earlier included margins
2281 ;; in window-width when in TTY.
2282 (t (1+ (let ((margins (window-margins)))
2283 (+ (or (car margins) 0)
2284 (or (cdr margins) 0))))))))
2286 (defun company--pseudo-tooltip-height ()
2287 "Calculate the appropriate tooltip height.
2288 Returns a negative number if the tooltip should be displayed above point."
2289 (let* ((lines (company--row))
2290 (below (- (company--window-inner-height) 1 lines)))
2291 (if (and (< below (min company-tooltip-minimum company-candidates-length))
2293 (- (max 3 (min company-tooltip-limit lines)))
2294 (max 3 (min company-tooltip-limit below)))))
2296 (defun company-pseudo-tooltip-show (row column selection)
2297 (company-pseudo-tooltip-hide)
2300 (let* ((height (company--pseudo-tooltip-height))
2304 (setq row (+ row height -1)
2307 (let* ((nl (< (move-to-window-line row) row))
2309 (end (save-excursion
2310 (move-to-window-line (+ row (abs height)))
2312 (ov (make-overlay beg end))
2313 (args (list (mapcar 'company-plainify
2314 (company-buffer-lines beg end))
2317 (setq company-pseudo-tooltip-overlay ov)
2318 (overlay-put ov 'company-replacement-args args)
2320 (let ((lines (company--create-lines selection (abs height))))
2321 (overlay-put ov 'company-after
2322 (apply 'company--replacement-string lines args))
2323 (overlay-put ov 'company-width (string-width (car lines))))
2325 (overlay-put ov 'company-column column)
2326 (overlay-put ov 'company-height height)))))
2328 (defun company-pseudo-tooltip-show-at-point (pos)
2329 (let ((row (company--row pos))
2330 (col (company--column pos)))
2331 (company-pseudo-tooltip-show (1+ row) col company-selection)))
2333 (defun company-pseudo-tooltip-edit (selection)
2334 (let ((height (overlay-get company-pseudo-tooltip-overlay 'company-height)))
2335 (overlay-put company-pseudo-tooltip-overlay 'company-after
2336 (apply 'company--replacement-string
2337 (company--create-lines selection (abs height))
2338 (overlay-get company-pseudo-tooltip-overlay
2339 'company-replacement-args)))))
2341 (defun company-pseudo-tooltip-hide ()
2342 (when company-pseudo-tooltip-overlay
2343 (delete-overlay company-pseudo-tooltip-overlay)
2344 (setq company-pseudo-tooltip-overlay nil)))
2346 (defun company-pseudo-tooltip-hide-temporarily ()
2347 (when (overlayp company-pseudo-tooltip-overlay)
2348 (overlay-put company-pseudo-tooltip-overlay 'invisible nil)
2349 (overlay-put company-pseudo-tooltip-overlay 'line-prefix nil)
2350 (overlay-put company-pseudo-tooltip-overlay 'after-string nil)))
2352 (defun company-pseudo-tooltip-unhide ()
2353 (when company-pseudo-tooltip-overlay
2354 (overlay-put company-pseudo-tooltip-overlay 'invisible t)
2355 ;; Beat outline's folding overlays, at least.
2356 (overlay-put company-pseudo-tooltip-overlay 'priority 1)
2357 ;; No (extra) prefix for the first line.
2358 (overlay-put company-pseudo-tooltip-overlay 'line-prefix "")
2359 (overlay-put company-pseudo-tooltip-overlay 'after-string
2360 (overlay-get company-pseudo-tooltip-overlay 'company-after))
2361 (overlay-put company-pseudo-tooltip-overlay 'window (selected-window))))
2363 (defun company-pseudo-tooltip-guard ()
2364 (buffer-substring-no-properties
2365 (point) (overlay-start company-pseudo-tooltip-overlay)))
2367 (defun company-pseudo-tooltip-frontend (command)
2368 "`company-mode' front-end similar to a tooltip but based on overlays."
2370 (pre-command (company-pseudo-tooltip-hide-temporarily))
2372 (let ((old-height (if (overlayp company-pseudo-tooltip-overlay)
2373 (overlay-get company-pseudo-tooltip-overlay
2376 (new-height (company--pseudo-tooltip-height)))
2377 (unless (and (>= (* old-height new-height) 0)
2378 (>= (abs old-height) (abs new-height))
2379 (equal (company-pseudo-tooltip-guard)
2380 (overlay-get company-pseudo-tooltip-overlay
2383 (company-pseudo-tooltip-show-at-point (- (point)
2384 (length company-prefix)))
2385 (overlay-put company-pseudo-tooltip-overlay
2386 'company-guard (company-pseudo-tooltip-guard))))
2387 (company-pseudo-tooltip-unhide))
2388 (hide (company-pseudo-tooltip-hide)
2389 (setq company-tooltip-offset 0))
2390 (update (when (overlayp company-pseudo-tooltip-overlay)
2391 (company-pseudo-tooltip-edit company-selection)))))
2393 (defun company-pseudo-tooltip-unless-just-one-frontend (command)
2394 "`company-pseudo-tooltip-frontend', but not shown for single candidates."
2395 (unless (and (eq command 'post-command)
2396 (company--show-inline-p))
2397 (company-pseudo-tooltip-frontend command)))
2399 ;;; overlay ;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;
2401 (defvar company-preview-overlay nil)
2402 (make-variable-buffer-local 'company-preview-overlay)
2404 (defun company-preview-show-at-point (pos)
2405 (company-preview-hide)
2407 (setq company-preview-overlay (make-overlay pos (1+ pos)))
2409 (let ((completion (nth company-selection company-candidates)))
2410 (setq completion (propertize completion 'face 'company-preview))
2411 (add-text-properties 0 (length company-common)
2412 '(face company-preview-common) completion)
2414 ;; Add search string
2415 (and company-search-string
2416 (string-match (regexp-quote company-search-string) completion)
2417 (add-text-properties (match-beginning 0)
2419 '(face company-preview-search)
2422 (setq completion (company-strip-prefix completion))
2424 (and (equal pos (point))
2425 (not (equal completion ""))
2426 (add-text-properties 0 1 '(cursor t) completion))
2428 (overlay-put company-preview-overlay 'display
2429 (concat completion (unless (eq pos (point-max))
2430 (buffer-substring pos (1+ pos)))))
2431 (overlay-put company-preview-overlay 'window (selected-window))))
2433 (defun company-preview-hide ()
2434 (when company-preview-overlay
2435 (delete-overlay company-preview-overlay)
2436 (setq company-preview-overlay nil)))
2438 (defun company-preview-frontend (command)
2439 "`company-mode' front-end showing the selection as if it had been inserted."
2441 (`pre-command (company-preview-hide))
2442 (`post-command (company-preview-show-at-point (point)))
2443 (`hide (company-preview-hide))))
2445 (defun company-preview-if-just-one-frontend (command)
2446 "`company-preview-frontend', but only shown for single candidates."
2447 (when (or (not (eq command 'post-command))
2448 (company--show-inline-p))
2449 (company-preview-frontend command)))
2451 (defun company--show-inline-p ()
2452 (and (not (cdr company-candidates))
2454 (string-prefix-p company-prefix company-common
2455 (company-call-backend 'ignore-case))))
2457 ;;; echo ;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;
2459 (defvar company-echo-last-msg nil)
2460 (make-variable-buffer-local 'company-echo-last-msg)
2462 (defvar company-echo-timer nil)
2464 (defvar company-echo-delay .01)
2466 (defun company-echo-show (&optional getter)
2468 (setq company-echo-last-msg (funcall getter)))
2469 (let ((message-log-max nil))
2470 (if company-echo-last-msg
2471 (message "%s" company-echo-last-msg)
2474 (defun company-echo-show-soon (&optional getter)
2475 (when company-echo-timer
2476 (cancel-timer company-echo-timer))
2477 (setq company-echo-timer (run-with-timer 0 nil 'company-echo-show getter)))
2479 (defsubst company-echo-show-when-idle (&optional getter)
2480 (when (sit-for company-echo-delay)
2481 (company-echo-show getter)))
2483 (defun company-echo-format ()
2485 (let ((limit (window-width (minibuffer-window)))
2487 ;; Roll to selection.
2488 (candidates (nthcdr company-selection company-candidates))
2489 (i (if company-show-numbers company-selection 99999))
2493 (setq comp (company-reformat (pop candidates))
2494 len (+ len 1 (length comp)))
2498 (setq comp (propertize (format "%d: %s" i comp)
2499 'face 'company-echo))
2502 (add-text-properties 3 (+ 3 (length company-common))
2503 '(face company-echo-common) comp))
2504 (setq comp (propertize comp 'face 'company-echo))
2505 (add-text-properties 0 (length company-common)
2506 '(face company-echo-common) comp))
2508 (setq candidates nil)
2511 (mapconcat 'identity (nreverse msg) " ")))
2513 (defun company-echo-strip-common-format ()
2515 (let ((limit (window-width (minibuffer-window)))
2516 (len (+ (length company-prefix) 2))
2517 ;; Roll to selection.
2518 (candidates (nthcdr company-selection company-candidates))
2519 (i (if company-show-numbers company-selection 99999))
2523 (setq comp (company-strip-prefix (pop candidates))
2524 len (+ len 2 (length comp)))
2527 (setq comp (format "%s (%d)" comp i))
2531 (setq candidates nil)
2532 (push (propertize comp 'face 'company-echo) msg)))
2534 (concat (propertize company-prefix 'face 'company-echo-common) "{"
2535 (mapconcat 'identity (nreverse msg) ", ")
2538 (defun company-echo-hide ()
2539 (unless (equal company-echo-last-msg "")
2540 (setq company-echo-last-msg "")
2541 (company-echo-show)))
2543 (defun company-echo-frontend (command)
2544 "`company-mode' front-end showing the candidates in the echo area."
2546 (`post-command (company-echo-show-soon 'company-echo-format))
2547 (`hide (company-echo-hide))))
2549 (defun company-echo-strip-common-frontend (command)
2550 "`company-mode' front-end showing the candidates in the echo area."
2552 (`post-command (company-echo-show-soon 'company-echo-strip-common-format))
2553 (`hide (company-echo-hide))))
2555 (defun company-echo-metadata-frontend (command)
2556 "`company-mode' front-end showing the documentation in the echo area."
2558 (`post-command (company-echo-show-when-idle 'company-fetch-metadata))
2559 (`hide (company-echo-hide))))
2562 ;;; company.el ends here