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.
63 ;; See NEWS.md in the repository.
70 ;; FIXME: Use `user-error'.
71 (add-to-list 'debug-ignored-errors "^.* frontend cannot be used twice$")
72 (add-to-list 'debug-ignored-errors "^Echo area cannot be used twice$")
73 (add-to-list 'debug-ignored-errors "^No \\(document\\|loc\\)ation available$")
74 (add-to-list 'debug-ignored-errors "^Company not ")
75 (add-to-list 'debug-ignored-errors "^No candidate number ")
76 (add-to-list 'debug-ignored-errors "^Cannot complete at point$")
77 (add-to-list 'debug-ignored-errors "^No other back-end$")
81 ;; `defvar-local' for Emacs 24.2 and below
82 (unless (fboundp 'defvar-local)
83 (defmacro defvar-local (var val &optional docstring)
84 "Define VAR as a buffer-local variable with default value VAL.
85 Like `defvar' but additionally marks the variable as being automatically
86 buffer-local wherever it is set."
87 (declare (debug defvar) (doc-string 3))
89 (defvar ,var ,val ,docstring)
90 (make-variable-buffer-local ',var)))))
93 "Extensible inline text completion mechanism"
98 (defface company-tooltip
99 '((default :foreground "black")
100 (((class color) (min-colors 88) (background light))
101 (:background "cornsilk"))
102 (((class color) (min-colors 88) (background dark))
103 (:background "yellow")))
104 "Face used for the tooltip.")
106 (defface company-tooltip-selection
107 '((default :inherit company-tooltip)
108 (((class color) (min-colors 88) (background light))
109 (:background "light blue"))
110 (((class color) (min-colors 88) (background dark))
111 (:background "orange1"))
112 (t (:background "green")))
113 "Face used for the selection in the tooltip.")
115 (defface company-tooltip-search
116 '((default :inherit company-tooltip-selection))
117 "Face used for the search string in the tooltip.")
119 (defface company-tooltip-mouse
120 '((default :inherit highlight))
121 "Face used for the tooltip item under the mouse.")
123 (defface company-tooltip-common
124 '((default :inherit company-tooltip)
125 (((background light))
126 :foreground "darkred")
129 "Face used for the common completion in the tooltip.")
131 (defface company-tooltip-common-selection
132 '((default :inherit company-tooltip-selection)
133 (((background light))
134 :foreground "darkred")
137 "Face used for the selected common completion in the tooltip.")
139 (defface company-tooltip-annotation
140 '((default :inherit company-tooltip)
141 (((background light))
142 :foreground "firebrick4")
145 "Face used for the annotation in the tooltip.")
147 (defface company-scrollbar-fg
148 '((((background light))
149 :background "darkred")
152 "Face used for the tooltip scrollbar thumb.")
154 (defface company-scrollbar-bg
155 '((default :inherit company-tooltip)
156 (((background light))
160 "Face used for the tooltip scrollbar background.")
162 (defface company-preview
163 '((((background light))
164 :inherit company-tooltip-selection)
167 :foreground "wheat"))
168 "Face used for the completion preview.")
170 (defface company-preview-common
171 '((((background light))
172 :inherit company-tooltip-selection)
174 :inherit company-preview
176 "Face used for the common part of the completion preview.")
178 (defface company-preview-search
179 '((((background light))
180 :inherit company-tooltip-common-selection)
182 :inherit company-preview
183 :background "blue1"))
184 "Face used for the search string in the completion preview.")
186 (defface company-echo nil
187 "Face used for completions in the echo area.")
189 (defface company-echo-common
190 '((((background dark)) (:foreground "firebrick1"))
191 (((background light)) (:background "firebrick4")))
192 "Face used for the common part of completions in the echo area.")
194 (defun company-frontends-set (variable value)
196 (let ((value (delete-dups (copy-sequence value))))
197 (and (memq 'company-pseudo-tooltip-unless-just-one-frontend value)
198 (memq 'company-pseudo-tooltip-frontend value)
199 (error "Pseudo tooltip frontend cannot be used twice"))
200 (and (memq 'company-preview-if-just-one-frontend value)
201 (memq 'company-preview-frontend value)
202 (error "Preview frontend cannot be used twice"))
203 (and (memq 'company-echo value)
204 (memq 'company-echo-metadata-frontend value)
205 (error "Echo area cannot be used twice"))
206 ;; Preview must come last.
207 (dolist (f '(company-preview-if-just-one-frontend company-preview-frontend))
208 (when (cdr (memq f value))
209 (setq value (append (delq f value) (list f)))))
210 (set variable value)))
212 (defcustom company-frontends '(company-pseudo-tooltip-unless-just-one-frontend
213 company-preview-if-just-one-frontend
214 company-echo-metadata-frontend)
215 "The list of active front-ends (visualizations).
216 Each front-end is a function that takes one argument. It is called with
217 one of the following arguments:
219 `show': When the visualization should start.
221 `hide': When the visualization should end.
223 `update': When the data has been updated.
225 `pre-command': Before every command that is executed while the
226 visualization is active.
228 `post-command': After every command that is executed while the
229 visualization is active.
231 The visualized data is stored in `company-prefix', `company-candidates',
232 `company-common', `company-selection', `company-point' and
233 `company-search-string'."
234 :set 'company-frontends-set
235 :type '(repeat (choice (const :tag "echo" company-echo-frontend)
236 (const :tag "echo, strip common"
237 company-echo-strip-common-frontend)
238 (const :tag "show echo meta-data in echo"
239 company-echo-metadata-frontend)
240 (const :tag "pseudo tooltip"
241 company-pseudo-tooltip-frontend)
242 (const :tag "pseudo tooltip, multiple only"
243 company-pseudo-tooltip-unless-just-one-frontend)
244 (const :tag "preview" company-preview-frontend)
245 (const :tag "preview, unique only"
246 company-preview-if-just-one-frontend)
247 (function :tag "custom function" nil))))
249 (defcustom company-tooltip-limit 10
250 "The maximum number of candidates in the tooltip."
253 (defcustom company-tooltip-minimum 6
254 "The minimum height of the tooltip.
255 If this many lines are not available, prefer to display the tooltip above."
258 (defcustom company-tooltip-minimum-width 0
259 "The minimum width of the tooltip's inner area.
260 This doesn't include the margins and the scroll bar."
262 :package-version '(company . "0.8.0"))
264 (defcustom company-tooltip-margin 1
265 "Width of margin columns to show around the toolip."
268 (defcustom company-tooltip-offset-display 'scrollbar
269 "Method using which the tooltip displays scrolling position.
270 `scrollbar' means draw a scrollbar to the right of the items.
271 `lines' means wrap items in lines with \"before\" and \"after\" counters."
272 :type '(choice (const :tag "Scrollbar" scrollbar)
273 (const :tag "Two lines" lines)))
275 (defcustom company-tooltip-align-annotations nil
276 "When non-nil, align annotations to the right tooltip border."
278 :package-version '(company . "0.7.1"))
280 (defcustom company-tooltip-flip-when-above nil
281 "Whether to flip the tooltip when it's above the current line."
283 :package-version '(company . "0.8.1"))
285 (defvar company-safe-backends
286 '((company-abbrev . "Abbrev")
287 (company-bbdb . "BBDB")
288 (company-capf . "completion-at-point-functions")
289 (company-clang . "Clang")
290 (company-cmake . "CMake")
291 (company-css . "CSS")
292 (company-dabbrev . "dabbrev for plain text")
293 (company-dabbrev-code . "dabbrev for code")
294 (company-eclim . "Eclim (an Eclipse interface)")
295 (company-elisp . "Emacs Lisp")
296 (company-etags . "etags")
297 (company-files . "Files")
298 (company-gtags . "GNU Global")
299 (company-ispell . "Ispell")
300 (company-keywords . "Programming language keywords")
301 (company-nxml . "nxml")
302 (company-oddmuse . "Oddmuse")
303 (company-pysmell . "PySmell")
304 (company-ropemacs . "ropemacs")
305 (company-semantic . "Semantic")
306 (company-tempo . "Tempo templates")
307 (company-xcode . "Xcode")))
308 (put 'company-safe-backends 'risky-local-variable t)
310 (defun company-safe-backends-p (backends)
311 (and (consp backends)
312 (not (cl-dolist (backend backends)
313 (unless (if (consp backend)
314 (company-safe-backends-p backend)
315 (assq backend company-safe-backends))
318 (defcustom company-backends `(,@(unless (version< "24.3.50" emacs-version)
319 (list 'company-elisp))
321 company-nxml company-css
322 company-eclim company-semantic company-clang
323 company-xcode company-ropemacs company-cmake
325 (company-dabbrev-code company-gtags company-etags
327 company-oddmuse company-files company-dabbrev)
328 "The list of active back-ends (completion engines).
330 Only one back-end is used at a time. The choice depends on the order of
331 the items in this list, and on the values they return in response to the
332 `prefix' command (see below). But a back-end can also be a \"grouped\"
335 `company-begin-backend' can be used to start a specific back-end,
336 `company-other-backend' will skip to the next matching back-end in the list.
338 Each back-end is a function that takes a variable number of arguments.
339 The first argument is the command requested from the back-end. It is one
342 `prefix': The back-end should return the text to be completed. It must be
343 text immediately before point. Returning nil from this command passes
344 control to the next back-end. The function should return `stop' if it
345 should complete but cannot (e.g. if it is in the middle of a string).
346 Instead of a string, the back-end may return a cons where car is the prefix
347 and cdr is used in `company-minimum-prefix-length' test. It must be either
348 number or t, and in the latter case the test automatically succeeds.
350 `candidates': The second argument is the prefix to be completed. The
351 return value should be a list of candidates that match the prefix.
353 Non-prefix matches are also supported (candidates that don't start with the
354 prefix, but match it in some backend-defined way). Backends that use this
355 feature must disable cache (return t to `no-cache') and might also want to
360 `sorted': Return t here to indicate that the candidates are sorted and will
361 not need to be sorted again.
363 `duplicates': If non-nil, company will take care of removing duplicates
366 `no-cache': Usually company doesn't ask for candidates again as completion
367 progresses, unless the back-end returns t for this command. The second
368 argument is the latest prefix.
370 `meta': The second argument is a completion candidate. Return a (short)
371 documentation string for it.
373 `doc-buffer': The second argument is a completion candidate. Return a
374 buffer with documentation for it. Preferably use `company-doc-buffer',
376 `location': The second argument is a completion candidate. Return the cons
377 of buffer and buffer location, or of file and line number where the
378 completion candidate was defined.
380 `annotation': The second argument is a completion candidate. Return a
381 string to be displayed inline with the candidate in the popup. If
382 duplicates are removed by company, candidates with equal string values will
383 be kept if they have different annotations. For that to work properly,
384 backends should store the related information on candidates using text
387 `match': The second argument is a completion candidate. Return the index
388 after the end of text matching `prefix' within the candidate string. It
389 will be used when rendering the popup. This command only makes sense for
390 backends that provide non-prefix completion.
392 `require-match': If this returns t, the user is not allowed to enter
393 anything not offered as a candidate. Use with care! The default value nil
394 gives the user that choice with `company-require-match'. Return value
395 `never' overrides that option the other way around.
397 `init': Called once for each buffer. The back-end can check for external
398 programs and files and load any required libraries. Raising an error here
399 will show up in message log once, and the back-end will not be used for
402 `post-completion': Called after a completion candidate has been inserted
403 into the buffer. The second argument is the candidate. Can be used to
404 modify it, e.g. to expand a snippet.
406 The back-end should return nil for all commands it does not support or
407 does not know about. It should also be callable interactively and use
408 `company-begin-backend' to start itself in that case.
412 An element of `company-backends' can also itself be a list of back-ends,
413 then it's considered to be a \"grouped\" back-end.
415 When possible, commands taking a candidate as an argument are dispatched to
416 the back-end it came from. In other cases, the first non-nil value among
417 all the back-ends is returned.
419 The latter is the case for the `prefix' command. But if the group contains
420 the keyword `:with', the back-ends after it are ignored for this command.
422 The completions from back-ends in a group are merged (but only from those
423 that return the same `prefix').
425 Asynchronous back-ends:
427 The return value of each command can also be a cons (:async . FETCHER)
428 where FETCHER is a function of one argument, CALLBACK. When the data
429 arrives, FETCHER must call CALLBACK and pass it the appropriate return
430 value, as described above.
432 True asynchronous operation is only supported for command `candidates', and
433 only during idle completion. Other commands will block the user interface,
434 even if the back-end uses the asynchronous calling convention."
438 ,@(mapcar (lambda (b) `(const :tag ,(cdr b) ,(car b)))
439 company-safe-backends)
440 (symbol :tag "User defined")
441 (repeat :tag "Merged Back-ends"
442 (choice :tag "Back-end"
443 ,@(mapcar (lambda (b)
444 `(const :tag ,(cdr b) ,(car b)))
445 company-safe-backends)
446 (const :tag "With" :with)
447 (symbol :tag "User defined"))))))
449 (put 'company-backends 'safe-local-variable 'company-safe-backends-p)
451 (defcustom company-transformers nil
452 "Functions to change the list of candidates received from backends,
453 after sorting and removal of duplicates (if appropriate).
454 Each function gets called with the return value of the previous one."
456 (const :tag "None" nil)
457 (const :tag "Sort by occurrence" (company-sort-by-occurrence))
458 (const :tag "Sort by back-end importance"
459 (company-sort-by-backend-importance))
460 (repeat :tag "User defined" (function))))
462 (defcustom company-completion-started-hook nil
463 "Hook run when company starts completing.
464 The hook is called with one argument that is non-nil if the completion was
468 (defcustom company-completion-cancelled-hook nil
469 "Hook run when company cancels completing.
470 The hook is called with one argument that is non-nil if the completion was
474 (defcustom company-completion-finished-hook nil
475 "Hook run when company successfully completes.
476 The hook is called with the selected candidate as an argument.
478 If you indend to use it to post-process candidates from a specific
479 back-end, consider using the `post-completion' command instead."
482 (defcustom company-minimum-prefix-length 3
483 "The minimum prefix length for idle completion."
484 :type '(integer :tag "prefix length"))
486 (defcustom company-abort-manual-when-too-short nil
487 "If enabled, cancel a manually started completion when the prefix gets
488 shorter than both `company-minimum-prefix-length' and the length of the
489 prefix it was started from."
491 :package-version '(company . "0.8.0"))
493 (defcustom company-require-match 'company-explicit-action-p
494 "If enabled, disallow non-matching input.
495 This can be a function do determine if a match is required.
497 This can be overridden by the back-end, if it returns t or `never' to
498 `require-match'. `company-auto-complete' also takes precedence over this."
499 :type '(choice (const :tag "Off" nil)
500 (function :tag "Predicate function")
501 (const :tag "On, if user interaction took place"
502 'company-explicit-action-p)
503 (const :tag "On" t)))
505 (defcustom company-auto-complete nil
506 "Determines when to auto-complete.
507 If this is enabled, all characters from `company-auto-complete-chars'
508 trigger insertion of the selected completion candidate.
509 This can also be a function."
510 :type '(choice (const :tag "Off" nil)
511 (function :tag "Predicate function")
512 (const :tag "On, if user interaction took place"
513 'company-explicit-action-p)
514 (const :tag "On" t)))
516 (defcustom company-auto-complete-chars '(?\ ?\) ?.)
517 "Determines which characters trigger auto-completion.
518 See `company-auto-complete'. If this is a string, each string character
519 tiggers auto-completion. If it is a list of syntax description characters (see
520 `modify-syntax-entry'), all characters with that syntax auto-complete.
522 This can also be a function, which is called with the new input and should
523 return non-nil if company should auto-complete.
525 A character that is part of a valid candidate never triggers auto-completion."
526 :type '(choice (string :tag "Characters")
528 (const :tag "Whitespace" ?\ )
529 (const :tag "Symbol" ?_)
530 (const :tag "Opening parentheses" ?\()
531 (const :tag "Closing parentheses" ?\))
532 (const :tag "Word constituent" ?w)
533 (const :tag "Punctuation." ?.)
534 (const :tag "String quote." ?\")
535 (const :tag "Paired delimiter." ?$)
536 (const :tag "Expression quote or prefix operator." ?\')
537 (const :tag "Comment starter." ?<)
538 (const :tag "Comment ender." ?>)
539 (const :tag "Character-quote." ?/)
540 (const :tag "Generic string fence." ?|)
541 (const :tag "Generic comment fence." ?!))
542 (function :tag "Predicate function")))
544 (defcustom company-idle-delay .5
545 "The idle delay in seconds until completion starts automatically.
546 The prefix still has to satisfy `company-minimum-prefix-length' before that
547 happens. The value of nil means no idle completion."
548 :type '(choice (const :tag "never (nil)" nil)
549 (const :tag "immediate (0)" 0)
550 (number :tag "seconds")))
552 (defcustom company-begin-commands '(self-insert-command
553 org-self-insert-command
554 orgtbl-self-insert-command
559 "A list of commands after which idle completion is allowed.
560 If this is t, it can show completions after any command except a few from a
561 pre-defined list. See `company-idle-delay'.
563 Alternatively, any command with a non-nil `company-begin' property is
564 treated as if it was on this list."
565 :type '(choice (const :tag "Any command" t)
566 (const :tag "Self insert command" '(self-insert-command))
567 (repeat :tag "Commands" function))
568 :package-version '(company . "0.8.4"))
570 (defcustom company-continue-commands '(not save-buffer save-some-buffers
571 save-buffers-kill-terminal
572 save-buffers-kill-emacs)
573 "A list of commands that are allowed during completion.
574 If this is t, or if `company-begin-commands' is t, any command is allowed.
575 Otherwise, the value must be a list of symbols. If it starts with `not',
576 the cdr is the list of commands that abort completion. Otherwise, all
577 commands except those in that list, or in `company-begin-commands', or
578 commands in the `company-' namespace, abort completion."
579 :type '(choice (const :tag "Any command" t)
580 (cons :tag "Any except"
582 (repeat :tag "Commands" function))
583 (repeat :tag "Commands" function)))
585 (defcustom company-show-numbers nil
586 "If enabled, show quick-access numbers for the first ten candidates."
587 :type '(choice (const :tag "off" nil)
588 (const :tag "on" t)))
590 (defcustom company-selection-wrap-around nil
591 "If enabled, selecting item before first or after last wraps around."
592 :type '(choice (const :tag "off" nil)
593 (const :tag "on" t)))
595 (defvar company-async-wait 0.03
596 "Pause between checks to see if the value's been set when turning an
597 asynchronous call into synchronous.")
599 (defvar company-async-timeout 2
600 "Maximum wait time for a value to be set during asynchronous call.")
602 ;;; mode ;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;
604 (defvar company-mode-map (make-sparse-keymap)
605 "Keymap used by `company-mode'.")
607 (defvar company-active-map
608 (let ((keymap (make-sparse-keymap)))
609 (define-key keymap "\e\e\e" 'company-abort)
610 (define-key keymap "\C-g" 'company-abort)
611 (define-key keymap (kbd "M-n") 'company-select-next)
612 (define-key keymap (kbd "M-p") 'company-select-previous)
613 (define-key keymap (kbd "<down>") 'company-select-next-or-abort)
614 (define-key keymap (kbd "<up>") 'company-select-previous-or-abort)
615 (define-key keymap [down-mouse-1] 'ignore)
616 (define-key keymap [down-mouse-3] 'ignore)
617 (define-key keymap [mouse-1] 'company-complete-mouse)
618 (define-key keymap [mouse-3] 'company-select-mouse)
619 (define-key keymap [up-mouse-1] 'ignore)
620 (define-key keymap [up-mouse-3] 'ignore)
621 (define-key keymap [return] 'company-complete-selection)
622 (define-key keymap (kbd "RET") 'company-complete-selection)
623 (define-key keymap [tab] 'company-complete-common)
624 (define-key keymap (kbd "TAB") 'company-complete-common)
625 (define-key keymap (kbd "<f1>") 'company-show-doc-buffer)
626 (define-key keymap (kbd "C-h") 'company-show-doc-buffer)
627 (define-key keymap "\C-w" 'company-show-location)
628 (define-key keymap "\C-s" 'company-search-candidates)
629 (define-key keymap "\C-\M-s" 'company-filter-candidates)
631 (define-key keymap (read-kbd-macro (format "M-%d" i)) 'company-complete-number))
633 "Keymap that is enabled during an active completion.")
635 (defvar company--disabled-backends nil)
637 (defun company-init-backend (backend)
638 (and (symbolp backend)
639 (not (fboundp backend))
640 (ignore-errors (require backend nil t)))
645 (funcall backend 'init)
646 (put backend 'company-init t))
648 (put backend 'company-init 'failed)
649 (unless (memq backend company--disabled-backends)
650 (message "Company back-end '%s' could not be initialized:\n%s"
651 backend (error-message-string err)))
652 (cl-pushnew backend company--disabled-backends)
654 ;; No initialization for lambdas.
655 ((functionp backend) t)
656 (t ;; Must be a list.
657 (cl-dolist (b backend)
659 (company-init-backend b))))))
661 (defvar company-default-lighter " company")
663 (defvar-local company-lighter company-default-lighter)
666 (define-minor-mode company-mode
667 "\"complete anything\"; is an in-buffer completion framework.
668 Completion starts automatically, depending on the values
669 `company-idle-delay' and `company-minimum-prefix-length'.
671 Completion can be controlled with the commands:
672 `company-complete-common', `company-complete-selection', `company-complete',
673 `company-select-next', `company-select-previous'. If these commands are
674 called before `company-idle-delay', completion will also start.
676 Completions can be searched with `company-search-candidates' or
677 `company-filter-candidates'. These can be used while completion is
680 The completion data is retrieved using `company-backends' and displayed
681 using `company-frontends'. If you want to start a specific back-end, call
682 it interactively or use `company-begin-backend'.
684 regular keymap (`company-mode-map'):
687 keymap during active completions (`company-active-map'):
689 \\{company-active-map}"
690 nil company-lighter company-mode-map
693 (when (eq company-idle-delay t)
694 (setq company-idle-delay 0)
695 (warn "Setting `company-idle-delay' to t is deprecated. Set it to 0 instead."))
696 (add-hook 'pre-command-hook 'company-pre-command nil t)
697 (add-hook 'post-command-hook 'company-post-command nil t)
698 (mapc 'company-init-backend company-backends))
699 (remove-hook 'pre-command-hook 'company-pre-command t)
700 (remove-hook 'post-command-hook 'company-post-command t)
702 (kill-local-variable 'company-point)))
704 (defcustom company-global-modes t
705 "Modes for which `company-mode' mode is turned on by `global-company-mode'.
706 If nil, means no modes. If t, then all major modes have it turned on.
707 If a list, it should be a list of `major-mode' symbol names for which
708 `company-mode' should be automatically turned on. The sense of the list is
709 negated if it begins with `not'. For example:
711 means that `company-mode' is turned on for buffers in C and C++ modes only.
713 means that `company-mode' is always turned on except in `message-mode' buffers."
714 :type '(choice (const :tag "none" nil)
716 (set :menu-tag "mode specific" :tag "modes"
718 (const :tag "Except" not)
719 (repeat :inline t (symbol :tag "mode")))))
722 (define-globalized-minor-mode global-company-mode company-mode company-mode-on)
724 (defun company-mode-on ()
725 (when (and (not (or noninteractive (eq (aref (buffer-name) 0) ?\s)))
726 (cond ((eq company-global-modes t)
728 ((eq (car-safe company-global-modes) 'not)
729 (not (memq major-mode (cdr company-global-modes))))
730 (t (memq major-mode company-global-modes))))
733 (defsubst company-assert-enabled ()
735 (company-uninstall-map)
736 (error "Company not enabled")))
738 ;;; keymaps ;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;
740 (defvar-local company-my-keymap nil)
742 (defvar company-emulation-alist '((t . nil)))
744 (defsubst company-enable-overriding-keymap (keymap)
745 (company-uninstall-map)
746 (setq company-my-keymap keymap))
748 (defun company-ensure-emulation-alist ()
749 (unless (eq 'company-emulation-alist (car emulation-mode-map-alists))
750 (setq emulation-mode-map-alists
751 (cons 'company-emulation-alist
752 (delq 'company-emulation-alist emulation-mode-map-alists)))))
754 (defun company-install-map ()
755 (unless (or (cdar company-emulation-alist)
756 (null company-my-keymap))
757 (setf (cdar company-emulation-alist) company-my-keymap)))
759 (defun company-uninstall-map ()
760 (setf (cdar company-emulation-alist) nil))
763 ;; Emacs calculates the active keymaps before reading the event. That means we
764 ;; cannot change the keymap from a timer. So we send a bogus command.
765 ;; XXX: Even in Emacs 24.4, seems to be needed in the terminal.
766 (defun company-ignore ()
768 (setq this-command last-command))
770 (global-set-key '[company-dummy-event] 'company-ignore)
772 (defun company-input-noop ()
773 (push 'company-dummy-event unread-command-events))
775 (defun company--posn-col-row (posn)
776 (let ((col (car (posn-col-row posn)))
777 ;; `posn-col-row' doesn't work well with lines of different height.
778 ;; `posn-actual-col-row' doesn't handle multiple-width characters.
779 (row (cdr (posn-actual-col-row posn))))
780 (when (and header-line-format (version< emacs-version "24.3.93.3"))
781 ;; http://debbugs.gnu.org/18384
783 (cons (+ col (window-hscroll)) row)))
785 (defun company--col-row (&optional pos)
786 (company--posn-col-row (posn-at-point pos)))
788 (defun company--row (&optional pos)
789 (cdr (company--col-row pos)))
791 ;;; backends ;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;
793 (defvar-local company-backend nil)
795 (defun company-grab (regexp &optional expression limit)
796 (when (looking-back regexp limit)
797 (or (match-string-no-properties (or expression 0)) "")))
799 (defun company-grab-line (regexp &optional expression)
800 (company-grab regexp expression (point-at-bol)))
802 (defun company-grab-symbol ()
803 (if (looking-at "\\_>")
804 (buffer-substring (point) (save-excursion (skip-syntax-backward "w_")
806 (unless (and (char-after) (memq (char-syntax (char-after)) '(?w ?_)))
809 (defun company-grab-word ()
810 (if (looking-at "\\>")
811 (buffer-substring (point) (save-excursion (skip-syntax-backward "w")
813 (unless (and (char-after) (eq (char-syntax (char-after)) ?w))
816 (defun company-grab-symbol-cons (idle-begin-after-re &optional max-len)
817 (let ((symbol (company-grab-symbol)))
820 (forward-char (- (length symbol)))
821 (if (looking-back idle-begin-after-re (if max-len
823 (line-beginning-position)))
827 (defun company-in-string-or-comment ()
828 (let ((ppss (syntax-ppss)))
829 (or (car (setq ppss (nthcdr 3 ppss)))
830 (car (setq ppss (cdr ppss)))
833 (defun company-call-backend (&rest args)
834 (company--force-sync #'company-call-backend-raw args company-backend))
836 (defun company--force-sync (fun args backend)
837 (let ((value (apply fun args)))
838 (if (not (eq (car-safe value) :async))
841 (start (time-to-seconds)))
843 (lambda (result) (setq res result)))
844 (while (eq res 'trash)
845 (if (> (- (time-to-seconds) start) company-async-timeout)
846 (error "Company: Back-end %s async timeout with args %s"
848 (sleep-for company-async-wait)))
851 (defun company-call-backend-raw (&rest args)
852 (condition-case-unless-debug err
853 (if (functionp company-backend)
854 (apply company-backend args)
855 (apply #'company--multi-backend-adapter company-backend args))
856 (error (error "Company: Back-end %s error \"%s\" with args %s"
857 company-backend (error-message-string err) args))))
859 (defun company--multi-backend-adapter (backends command &rest args)
860 (let ((backends (cl-loop for b in backends
861 when (not (and (symbolp b)
862 (eq 'failed (get b 'company-init))))
865 (if (eq command 'prefix)
866 (butlast backends (length (member :with backends)))
867 (delq :with backends)))
870 (company--multi-backend-adapter-candidates backends (car args)))
873 ((or `prefix `ignore-case `no-cache `require-match)
875 (cl-dolist (backend backends)
876 (when (setq value (company--force-sync
877 backend (cons command args) backend))
878 (cl-return value)))))
880 (let ((arg (car args)))
881 (when (> (length arg) 0)
882 (let ((backend (or (get-text-property 0 'company-backend arg)
884 (apply backend command args))))))))
886 (defun company--multi-backend-adapter-candidates (backends prefix)
887 (let ((pairs (cl-loop for backend in (cdr backends)
888 when (equal (company--prefix-str
889 (funcall backend 'prefix))
891 collect (cons (funcall backend 'candidates prefix)
896 (propertize str 'company-backend b))
898 (when (equal (company--prefix-str (funcall (car backends) 'prefix)) prefix)
899 ;; Small perf optimization: don't tag the candidates received
900 ;; from the first backend in the group.
901 (push (cons (funcall (car backends) 'candidates prefix)
904 (company--merge-async pairs (lambda (values) (apply #'append values)))))
906 (defun company--merge-async (pairs merger)
907 (let ((async (cl-loop for pair in pairs
909 (eq :async (car-safe (car pair))))))
911 (funcall merger (cl-loop for (val . mapper) in pairs
912 collect (funcall mapper val)))
923 (let ((val (car pair))
925 (if (not (eq :async (car-safe val)))
926 (push (funcall mapper val) lst)
930 (push fetcher pending)
933 (setq pending (delq fetcher pending))
934 (setcar cell (funcall mapper res))
935 (funcall finisher)))))))))))))
937 (defun company--prefix-str (prefix)
938 (or (car-safe prefix) prefix))
940 ;;; completion mechanism ;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;
942 (defvar-local company-prefix nil)
944 (defvar-local company-candidates nil)
946 (defvar-local company-candidates-length nil)
948 (defvar-local company-candidates-cache nil)
950 (defvar-local company-candidates-predicate nil)
952 (defvar-local company-common nil)
954 (defvar-local company-selection 0)
956 (defvar-local company-selection-changed nil)
958 (defvar-local company--manual-action nil
959 "Non-nil, if manual completion took place.")
961 (defvar-local company--manual-prefix nil)
963 (defvar company--auto-completion nil
964 "Non-nil when current candidate is being inserted automatically.
965 Controlled by `company-auto-complete'.")
967 (defvar-local company--point-max nil)
969 (defvar-local company-point nil)
971 (defvar company-timer nil)
973 (defsubst company-strip-prefix (str)
974 (substring str (length company-prefix)))
976 (defun company--insert-candidate (candidate)
977 (setq candidate (substring-no-properties candidate))
978 ;; XXX: Return value we check here is subject to change.
979 (if (eq (company-call-backend 'ignore-case) 'keep-prefix)
980 (insert (company-strip-prefix candidate))
981 (unless (equal company-prefix candidate)
982 (delete-region (- (point) (length company-prefix)) (point))
983 (insert candidate))))
985 (defmacro company-with-candidate-inserted (candidate &rest body)
986 "Evaluate BODY with CANDIDATE temporarily inserted.
987 This is a tool for back-ends that need candidates inserted before they
988 can retrieve meta-data for them."
990 `(let ((inhibit-modification-hooks t)
991 (inhibit-point-motion-hooks t)
992 (modified-p (buffer-modified-p)))
993 (company--insert-candidate ,candidate)
996 (delete-region company-point (point))
997 (set-buffer-modified-p modified-p))))
999 (defun company-explicit-action-p ()
1000 "Return whether explicit completion action was taken by the user."
1001 (or company--manual-action
1002 company-selection-changed))
1004 (defun company-reformat (candidate)
1005 ;; company-ispell needs this, because the results are always lower-case
1006 ;; It's mory efficient to fix it only when they are displayed.
1007 ;; FIXME: Adopt the current text's capitalization instead?
1008 (if (eq (company-call-backend 'ignore-case) 'keep-prefix)
1009 (concat company-prefix (substring candidate (length company-prefix)))
1012 (defun company--should-complete ()
1013 (and (eq company-idle-delay 'now)
1014 (not (or buffer-read-only overriding-terminal-local-map
1015 overriding-local-map))
1016 ;; Check if in the middle of entering a key combination.
1017 (or (equal (this-command-keys-vector) [])
1018 (not (keymapp (key-binding (this-command-keys-vector)))))
1019 (not (and transient-mark-mode mark-active))))
1021 (defun company--should-continue ()
1022 (or (eq t company-begin-commands)
1023 (eq t company-continue-commands)
1024 (if (eq 'not (car company-continue-commands))
1025 (not (memq this-command (cdr company-continue-commands)))
1026 (or (memq this-command company-begin-commands)
1027 (memq this-command company-continue-commands)
1028 (and (symbolp this-command)
1029 (string-match-p "\\`company-" (symbol-name this-command)))))))
1031 (defun company-call-frontends (command)
1032 (dolist (frontend company-frontends)
1033 (condition-case-unless-debug err
1034 (funcall frontend command)
1035 (error (error "Company: Front-end %s error \"%s\" on command %s"
1036 frontend (error-message-string err) command)))))
1038 (defun company-set-selection (selection &optional force-update)
1040 (if company-selection-wrap-around
1041 (mod selection company-candidates-length)
1042 (max 0 (min (1- company-candidates-length) selection))))
1043 (when (or force-update (not (equal selection company-selection)))
1044 (company--update-group-lighter (nth selection company-candidates))
1045 (setq company-selection selection
1046 company-selection-changed t)
1047 (company-call-frontends 'update)))
1049 (defun company--update-group-lighter (candidate)
1050 (when (listp company-backend)
1051 (let ((backend (or (get-text-property 0 'company-backend candidate)
1052 (car company-backend))))
1053 (when (and backend (symbolp backend))
1054 (let ((name (replace-regexp-in-string "company-\\|-company" ""
1055 (symbol-name backend))))
1056 (setq company-lighter (format " company-<%s>" name)))))))
1058 (defun company-apply-predicate (candidates predicate)
1060 (dolist (c candidates)
1061 (when (funcall predicate c)
1065 (defun company-update-candidates (candidates)
1066 (setq company-candidates-length (length candidates))
1067 (if (> company-selection 0)
1068 ;; Try to restore the selection
1069 (let ((selected (nth company-selection company-candidates)))
1070 (setq company-selection 0
1071 company-candidates candidates)
1073 (while (and candidates (string< (pop candidates) selected))
1074 (cl-incf company-selection))
1076 ;; Make sure selection isn't out of bounds.
1077 (setq company-selection (min (1- company-candidates-length)
1078 company-selection)))))
1079 (setq company-selection 0
1080 company-candidates candidates))
1081 ;; Calculate common.
1082 (let ((completion-ignore-case (company-call-backend 'ignore-case)))
1083 ;; We want to support non-prefix completion, so filtering is the
1084 ;; responsibility of each respective backend, not ours.
1085 ;; On the other hand, we don't want to replace non-prefix input in
1086 ;; `company-complete-common', unless there's only one candidate.
1087 (setq company-common
1088 (if (cdr company-candidates)
1089 (let ((common (try-completion "" company-candidates)))
1090 (when (string-prefix-p company-prefix common
1091 completion-ignore-case)
1093 (car company-candidates)))))
1095 (defun company-calculate-candidates (prefix)
1096 (let ((candidates (cdr (assoc prefix company-candidates-cache)))
1097 (ignore-case (company-call-backend 'ignore-case)))
1099 (when company-candidates-cache
1100 (let ((len (length prefix))
1101 (completion-ignore-case ignore-case)
1103 (cl-dotimes (i (1+ len))
1104 (when (setq prev (cdr (assoc (substring prefix 0 (- len i))
1105 company-candidates-cache)))
1106 (setq candidates (all-completions prefix prev))
1109 ;; No cache match, call the backend.
1110 (setq candidates (company--fetch-candidates prefix))
1111 ;; Save in cache (without the predicate applied).
1112 (push (cons prefix candidates) company-candidates-cache)))
1113 (setq candidates (company--process-candidates candidates))
1115 (if (or (cdr candidates)
1116 (not (eq t (compare-strings (car candidates) nil nil
1117 prefix nil nil ignore-case))))
1119 ;; Already completed and unique; don't start.
1122 (defun company--fetch-candidates (prefix)
1123 (let ((c (if company--manual-action
1124 (company-call-backend 'candidates prefix)
1125 (company-call-backend-raw 'candidates prefix)))
1127 (if (not (eq (car c) :async))
1129 (let ((buf (current-buffer))
1130 (win (selected-window))
1131 (tick (buffer-chars-modified-tick))
1133 (backend company-backend))
1136 (lambda (candidates)
1137 (if (not (and candidates (eq res 'done)))
1138 ;; There's no completions to display,
1139 ;; or the fetcher called us back right away.
1140 (setq res candidates)
1141 (setq company-backend backend
1142 company-candidates-cache (list (cons prefix candidates)))
1143 (company-idle-begin buf win tick pt)))))
1144 ;; FIXME: Relying on the fact that the callers
1145 ;; will interpret nil as "do nothing" is shaky.
1146 ;; A throw-catch would be one possible improvement.
1148 (progn (setq res 'done) nil)))))
1150 (defun company--process-candidates (candidates)
1151 (when company-candidates-predicate
1153 (company-apply-predicate candidates
1154 company-candidates-predicate)))
1155 (unless (company-call-backend 'sorted)
1156 (setq candidates (sort (copy-sequence candidates) 'string<)))
1157 (when (company-call-backend 'duplicates)
1158 (company--strip-duplicates candidates))
1159 (company--transform-candidates candidates))
1161 (defun company--strip-duplicates (candidates)
1162 (let ((c2 candidates))
1165 (let ((str (car c2))
1168 (while (let ((str2 (car c2)))
1169 (if (not (equal str str2))
1171 (when (eq anno 'unk)
1172 (setq anno (company-call-backend
1175 (company-call-backend
1176 'annotation str2))))
1180 (defun company--transform-candidates (candidates)
1181 (let ((c candidates))
1182 (dolist (tr company-transformers)
1183 (setq c (funcall tr c)))
1186 (defcustom company-occurrence-weight-function
1187 #'company-occurrence-prefer-closest-above
1188 "Function to weigh matches in `company-sort-by-occurrence'.
1189 It's called with three arguments: cursor position, the beginning and the
1192 (const :tag "First above point, then below point"
1193 company-occurrence-prefer-closest-above)
1194 (const :tag "Prefer closest in any direction"
1195 company-occurrence-prefer-any-closest)))
1197 (defun company-occurrence-prefer-closest-above (pos match-beg match-end)
1198 "Give priority to the matches above point, then those below point."
1199 (if (< match-beg pos)
1201 (- match-beg (window-start))))
1203 (defun company-occurrence-prefer-any-closest (pos _match-beg match-end)
1204 "Give priority to the matches closest to the point."
1205 (abs (- pos match-end)))
1207 (defun company-sort-by-occurrence (candidates)
1208 "Sort CANDIDATES according to their occurrences.
1209 Searches for each in the currently visible part of the current buffer and
1210 prioritizes the matches according to `company-occurrence-weight-function'.
1211 The rest of the list is appended unchanged.
1212 Keywords and function definition names are ignored."
1213 (let* ((w-start (window-start))
1214 (w-end (window-end))
1215 (start-point (point))
1223 (while (search-forward candidate w-end t)
1224 (when (and (not (eq (point) start-point))
1226 (company--occurrence-predicate)))
1230 (funcall company-occurrence-weight-function
1238 (mapcar #'car (sort occurs (lambda (e1 e2) (<= (cdr e1) (cdr e2)))))
1241 (defun company--occurrence-predicate ()
1242 (let ((beg (match-beginning 0))
1243 (end (match-end 0)))
1246 (and (not (memq (get-text-property (1- (point)) 'face)
1247 '(font-lock-function-name-face
1248 font-lock-keyword-face)))
1249 (let ((prefix (company--prefix-str
1250 (company-call-backend 'prefix))))
1251 (and (stringp prefix)
1252 (= (length prefix) (- end beg))))))))
1254 (defun company-sort-by-backend-importance (candidates)
1255 "Sort CANDIDATES as two priority groups.
1256 If `company-backend' is a function, do nothing. If it's a list, move
1257 candidates from back-ends before keyword `:with' to the front. Candidates
1258 from the rest of the back-ends in the group, if any, will be left at the end."
1259 (if (functionp company-backend)
1261 (let ((low-priority (cdr (memq :with company-backend))))
1262 (if (null low-priority)
1267 (let ((b2 (get-text-property 0 'company-backend c2)))
1268 (and b2 (memq b2 low-priority)))
1269 (let ((b1 (get-text-property 0 'company-backend c1)))
1270 (or (not b1) (not (memq b1 low-priority)))))))))))
1272 (defun company-idle-begin (buf win tick pos)
1273 (and (eq buf (current-buffer))
1274 (eq win (selected-window))
1275 (eq tick (buffer-chars-modified-tick))
1277 (when (company-auto-begin)
1278 (company-input-noop)
1279 (let ((this-command 'company-idle-begin))
1280 (company-post-command)))))
1282 (defun company-auto-begin ()
1284 (not company-candidates)
1285 (let ((company-idle-delay 'now))
1286 (condition-case-unless-debug err
1289 ;; Return non-nil if active.
1291 (error (message "Company: An error occurred in auto-begin")
1292 (message "%s" (error-message-string err))
1294 (quit (company-cancel))))))
1296 (defun company-manual-begin ()
1298 (company-assert-enabled)
1299 (setq company--manual-action t)
1301 (let ((company-minimum-prefix-length 0))
1302 (or company-candidates
1303 (company-auto-begin)))
1304 (unless company-candidates
1305 (setq company--manual-action nil))))
1307 (defun company-other-backend (&optional backward)
1308 (interactive (list current-prefix-arg))
1309 (company-assert-enabled)
1310 (let* ((after (if company-backend
1311 (cdr (member company-backend company-backends))
1313 (before (cdr (member company-backend (reverse company-backends))))
1315 (append before (reverse after))
1316 (append after (reverse before)))))
1318 (cl-dolist (backend next)
1319 (when (ignore-errors (company-begin-backend backend))
1321 (unless company-candidates
1322 (error "No other back-end")))
1324 (defun company-require-match-p ()
1325 (let ((backend-value (company-call-backend 'require-match)))
1326 (or (eq backend-value t)
1327 (and (not (eq backend-value 'never))
1328 (if (functionp company-require-match)
1329 (funcall company-require-match)
1330 (eq company-require-match t))))))
1332 (defun company-auto-complete-p (input)
1333 "Return non-nil, if input starts with punctuation or parentheses."
1334 (and (if (functionp company-auto-complete)
1335 (funcall company-auto-complete)
1336 company-auto-complete)
1337 (if (functionp company-auto-complete-chars)
1338 (funcall company-auto-complete-chars input)
1339 (if (consp company-auto-complete-chars)
1340 (memq (char-syntax (string-to-char input))
1341 company-auto-complete-chars)
1342 (string-match (substring input 0 1) company-auto-complete-chars)))))
1344 (defun company--incremental-p ()
1345 (and (> (point) company-point)
1346 (> (point-max) company--point-max)
1347 (not (eq this-command 'backward-delete-char-untabify))
1348 (equal (buffer-substring (- company-point (length company-prefix))
1352 (defun company--continue-failed (new-prefix)
1353 (let ((input (buffer-substring-no-properties (point) company-point)))
1355 ((company-auto-complete-p input)
1358 (goto-char company-point)
1359 (let ((company--auto-completion t))
1360 (company-complete-selection))
1362 ((and (or (not (company-require-match-p))
1363 ;; Don't require match if the new prefix
1364 ;; doesn't continue the old one, and the latter was a match.
1365 (not (stringp new-prefix))
1366 (<= (length new-prefix) (length company-prefix)))
1367 (member company-prefix company-candidates))
1368 ;; Last input was a success,
1369 ;; but we're treating it as an abort + input anyway,
1370 ;; like the `unique' case below.
1371 (company-cancel 'non-unique))
1372 ((company-require-match-p)
1373 ;; Wrong incremental input, but required match.
1374 (delete-char (- (length input)))
1376 (message "Matching input is required")
1378 (t (company-cancel)))))
1380 (defun company--good-prefix-p (prefix)
1381 (and (stringp (company--prefix-str prefix)) ;excludes 'stop
1382 (or (eq (cdr-safe prefix) t)
1383 (let ((len (or (cdr-safe prefix) (length prefix))))
1384 (if company--manual-prefix
1385 (or (not company-abort-manual-when-too-short)
1386 ;; Must not be less than minimum or initial length.
1387 (>= len (min company-minimum-prefix-length
1388 (length company--manual-prefix))))
1389 (>= len company-minimum-prefix-length))))))
1391 (defun company--continue ()
1392 (when (company-call-backend 'no-cache company-prefix)
1393 ;; Don't complete existing candidates, fetch new ones.
1394 (setq company-candidates-cache nil))
1395 (let* ((new-prefix (company-call-backend 'prefix))
1396 (c (when (and (company--good-prefix-p new-prefix)
1397 (setq new-prefix (company--prefix-str new-prefix))
1398 (= (- (point) (length new-prefix))
1399 (- company-point (length company-prefix))))
1400 (company-calculate-candidates new-prefix))))
1403 ;; t means complete/unique.
1404 ;; Handle it like completion was aborted, to differentiate from user
1405 ;; calling one of Company's commands to insert the candidate,
1406 ;; not to trigger template expansion, etc.
1407 (company-cancel 'unique))
1409 ;; incremental match
1410 (setq company-prefix new-prefix)
1411 (company-update-candidates c)
1413 ((not (company--incremental-p))
1415 (t (company--continue-failed new-prefix)))))
1417 (defun company--begin-new ()
1419 (cl-dolist (backend (if company-backend
1420 ;; prefer manual override
1421 (list company-backend)
1424 (if (or (symbolp backend)
1425 (functionp backend))
1426 (when (or (not (symbolp backend))
1427 (eq t (get backend 'company-init))
1428 (unless (get backend 'company-init)
1429 (company-init-backend backend)))
1430 (funcall backend 'prefix))
1431 (company--multi-backend-adapter backend 'prefix)))
1433 (when (company--good-prefix-p prefix)
1434 (setq company-prefix (company--prefix-str prefix)
1435 company-backend backend
1436 c (company-calculate-candidates company-prefix))
1437 ;; t means complete/unique. We don't start, so no hooks.
1439 (when company--manual-action
1440 (message "No completion found"))
1441 (when company--manual-action
1442 (setq company--manual-prefix prefix))
1443 (if (symbolp backend)
1444 (setq company-lighter (concat " " (symbol-name backend)))
1445 (company--update-group-lighter (car c)))
1446 (company-update-candidates c)
1447 (run-hook-with-args 'company-completion-started-hook
1448 (company-explicit-action-p))
1449 (company-call-frontends 'show)))
1452 (defun company--perform ()
1453 (or (and company-candidates (company--continue))
1454 (and (company--should-complete) (company--begin-new)))
1455 (if (not company-candidates)
1456 (setq company-backend nil)
1457 (setq company-point (point)
1458 company--point-max (point-max))
1459 (company-ensure-emulation-alist)
1460 (company-enable-overriding-keymap company-active-map)
1461 (company-call-frontends 'update)))
1463 (defun company-cancel (&optional result)
1465 (when company-prefix
1466 (if (stringp result)
1468 (company-call-backend 'pre-completion result)
1469 (run-hook-with-args 'company-completion-finished-hook result)
1470 (company-call-backend 'post-completion result))
1471 (run-hook-with-args 'company-completion-cancelled-hook result)))
1472 (setq company-backend nil
1474 company-candidates nil
1475 company-candidates-length nil
1476 company-candidates-cache nil
1477 company-candidates-predicate nil
1480 company-selection-changed nil
1481 company--manual-action nil
1482 company--manual-prefix nil
1483 company-lighter company-default-lighter
1484 company--point-max nil
1487 (cancel-timer company-timer))
1488 (company-search-mode 0)
1489 (company-call-frontends 'hide)
1490 (company-enable-overriding-keymap nil))
1491 ;; Make return value explicit.
1494 (defun company-abort ()
1496 (company-cancel 'abort))
1498 (defun company-finish (result)
1499 (company--insert-candidate result)
1500 (company-cancel result))
1502 (defsubst company-keep (command)
1503 (and (symbolp command) (get command 'company-keep)))
1505 (defun company-pre-command ()
1506 (unless (company-keep this-command)
1507 (condition-case-unless-debug err
1508 (when company-candidates
1509 (company-call-frontends 'pre-command)
1510 (unless (company--should-continue)
1512 (error (message "Company: An error occurred in pre-command")
1513 (message "%s" (error-message-string err))
1516 (cancel-timer company-timer)
1517 (setq company-timer nil))
1518 (company-uninstall-map))
1520 (defun company-post-command ()
1521 (when (null this-command)
1522 ;; Happens when the user presses `C-g' while inside
1523 ;; `flyspell-post-command-hook', for example.
1524 ;; Or any other `post-command-hook' function that can call `sit-for',
1525 ;; or any quittable timer function.
1527 (setq this-command 'company-abort))
1528 (unless (company-keep this-command)
1529 (condition-case-unless-debug err
1531 (unless (equal (point) company-point)
1532 (let (company-idle-delay) ; Against misbehavior while debugging.
1533 (company--perform)))
1534 (if company-candidates
1535 (company-call-frontends 'post-command)
1536 (and (numberp company-idle-delay)
1537 (company--should-begin)
1539 (run-with-timer company-idle-delay nil
1541 (current-buffer) (selected-window)
1542 (buffer-chars-modified-tick) (point))))))
1543 (error (message "Company: An error occurred in post-command")
1544 (message "%s" (error-message-string err))
1546 (company-install-map))
1548 (defvar company--begin-inhibit-commands '(company-abort
1549 company-complete-mouse
1551 company-complete-common
1552 company-complete-selection
1553 company-complete-number)
1554 "List of commands after which idle completion is (still) disabled when
1555 `company-begin-commands' is t.")
1557 (defun company--should-begin ()
1558 (if (eq t company-begin-commands)
1559 (not (memq this-command company--begin-inhibit-commands))
1561 (memq this-command company-begin-commands)
1562 (and (symbolp this-command) (get this-command 'company-begin)))))
1564 ;;; search ;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;
1566 (defvar-local company-search-string "")
1568 (defvar-local company-search-lighter " Search: \"\"")
1570 (defvar-local company-search-filtering nil
1571 "Non-nil to filter the completion candidates by the search string")
1573 (defvar-local company--search-old-selection 0)
1575 (defun company--search (text lines)
1576 (let ((quoted (regexp-quote text))
1578 (cl-dolist (line lines)
1579 (when (string-match quoted line (length company-prefix))
1583 (defun company-search-keypad ()
1585 (let* ((name (symbol-name last-command-event))
1586 (last-command-event (aref name (1- (length name)))))
1587 (company-search-printing-char)))
1589 (defun company-search-printing-char ()
1591 (company--search-assert-enabled)
1592 (let ((ss (concat company-search-string (string last-command-event))))
1593 (when company-search-filtering
1594 (company--search-update-predicate ss))
1595 (company--search-update-string ss)))
1597 (defun company--search-update-predicate (&optional ss)
1598 (let* ((company-candidates-predicate
1599 (and (not (string= ss ""))
1600 company-search-filtering
1601 (lambda (candidate) (string-match ss candidate))))
1602 (cc (company-calculate-candidates company-prefix)))
1603 (unless cc (error "No match"))
1604 (company-update-candidates cc)))
1606 (defun company--search-update-string (new)
1607 (let* ((pos (company--search new (nthcdr company-selection company-candidates))))
1610 (setq company-search-string new
1611 company-search-lighter (format " %s: \"%s\""
1612 (if company-search-filtering
1616 (company-set-selection (+ company-selection pos) t))))
1618 (defun company--search-assert-input ()
1619 (company--search-assert-enabled)
1620 (when (string= company-search-string "")
1621 (error "Empty search string")))
1623 (defun company-search-repeat-forward ()
1624 "Repeat the incremental search in completion candidates forward."
1626 (company--search-assert-input)
1627 (let ((pos (company--search company-search-string
1628 (cdr (nthcdr company-selection
1629 company-candidates)))))
1632 (company-set-selection (+ company-selection pos 1) t))))
1634 (defun company-search-repeat-backward ()
1635 "Repeat the incremental search in completion candidates backwards."
1637 (company--search-assert-input)
1638 (let ((pos (company--search company-search-string
1639 (nthcdr (- company-candidates-length
1641 (reverse company-candidates)))))
1644 (company-set-selection (- company-selection pos 1) t))))
1646 (defun company-search-toggle-filtering ()
1647 "Toggle `company-search-filtering'."
1649 (company--search-assert-enabled)
1650 (setq company-search-filtering (not company-search-filtering))
1651 (let ((ss company-search-string))
1652 (company--search-update-predicate ss)
1653 (company--search-update-string ss)))
1655 (defun company-search-abort ()
1656 "Abort searching the completion candidates."
1658 (company--search-assert-enabled)
1659 (company-search-mode 0)
1660 (company-set-selection company--search-old-selection t))
1662 (defun company-search-other-char ()
1664 (company--search-assert-enabled)
1665 (company-search-mode 0)
1666 (company--unread-last-input))
1668 (defun company-search-delete-char ()
1670 (company--search-assert-enabled)
1671 (if (string= company-search-string "")
1673 (let ((ss (substring company-search-string 0 -1)))
1674 (when company-search-filtering
1675 (company--search-update-predicate ss))
1676 (company--search-update-string ss))))
1678 (defvar company-search-map
1680 (keymap (make-keymap)))
1681 (if (fboundp 'max-char)
1682 (set-char-table-range (nth 1 keymap) (cons #x100 (max-char))
1683 'company-search-printing-char)
1685 ;; obsolete in Emacs 23
1686 (let ((l (generic-character-list))
1687 (table (nth 1 keymap)))
1689 (set-char-table-default table (car l) 'company-search-printing-char)
1690 (setq l (cdr l))))))
1691 (define-key keymap [t] 'company-search-other-char)
1693 (define-key keymap (make-string 1 i) 'company-search-other-char)
1696 (define-key keymap (vector i) 'company-search-printing-char)
1699 (define-key keymap (read (format "[kp-%s]" i)) 'company-search-keypad))
1700 (let ((meta-map (make-sparse-keymap)))
1701 (define-key keymap (char-to-string meta-prefix-char) meta-map)
1702 (define-key keymap [escape] meta-map))
1703 (define-key keymap (vector meta-prefix-char t) 'company-search-other-char)
1704 (define-key keymap (kbd "M-n") 'company-select-next)
1705 (define-key keymap (kbd "M-p") 'company-select-previous)
1706 (define-key keymap "\e\e\e" 'company-search-other-char)
1707 (define-key keymap [escape escape escape] 'company-search-other-char)
1708 (define-key keymap (kbd "DEL") 'company-search-delete-char)
1709 (define-key keymap [backspace] 'company-search-delete-char)
1710 (define-key keymap "\C-g" 'company-search-abort)
1711 (define-key keymap "\C-s" 'company-search-repeat-forward)
1712 (define-key keymap "\C-r" 'company-search-repeat-backward)
1713 (define-key keymap "\C-o" 'company-search-toggle-filtering)
1715 "Keymap used for incrementally searching the completion candidates.")
1717 (define-minor-mode company-search-mode
1718 "Search mode for completion candidates.
1719 Don't start this directly, use `company-search-candidates' or
1720 `company-filter-candidates'."
1721 nil company-search-lighter nil
1722 (if company-search-mode
1723 (if (company-manual-begin)
1725 (setq company--search-old-selection company-selection)
1726 (company-call-frontends 'update))
1727 (setq company-search-mode nil))
1728 (kill-local-variable 'company-search-string)
1729 (kill-local-variable 'company-search-lighter)
1730 (kill-local-variable 'company-search-filtering)
1731 (kill-local-variable 'company--search-old-selection)
1732 (when company-backend
1733 (company--search-update-predicate "")
1734 (company-call-frontends 'update))
1735 (company-enable-overriding-keymap company-active-map)))
1737 (defun company--search-assert-enabled ()
1738 (company-assert-enabled)
1739 (unless company-search-mode
1740 (company-uninstall-map)
1741 (error "Company not in search mode")))
1743 (defun company-search-candidates ()
1744 "Start searching the completion candidates incrementally.
1746 \\<company-search-map>Search can be controlled with the commands:
1747 - `company-search-repeat-forward' (\\[company-search-repeat-forward])
1748 - `company-search-repeat-backward' (\\[company-search-repeat-backward])
1749 - `company-search-abort' (\\[company-search-abort])
1750 - `company-search-delete-char' (\\[company-search-delete-char])
1752 Regular characters are appended to the search string.
1754 The command `company-search-toggle-filtering' (\\[company-search-toggle-filtering])
1755 uses the search string to filter the completion candidates."
1757 (company-search-mode 1)
1758 (company-enable-overriding-keymap company-search-map))
1760 (defvar company-filter-map
1761 (let ((keymap (make-keymap)))
1762 (define-key keymap [remap company-search-printing-char]
1763 'company-filter-printing-char)
1764 (set-keymap-parent keymap company-search-map)
1766 "Keymap used for incrementally searching the completion candidates.")
1768 (defun company-filter-candidates ()
1769 "Start filtering the completion candidates incrementally.
1770 This works the same way as `company-search-candidates' immediately
1771 followed by `company-search-toggle-filtering'."
1773 (company-search-mode 1)
1774 (setq company-search-filtering t))
1776 ;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;
1778 (defun company-select-next ()
1779 "Select the next candidate in the list."
1781 (when (company-manual-begin)
1782 (company-set-selection (1+ company-selection))))
1784 (defun company-select-previous ()
1785 "Select the previous candidate in the list."
1787 (when (company-manual-begin)
1788 (company-set-selection (1- company-selection))))
1790 (defun company-select-next-or-abort ()
1791 "Select the next candidate if more than one, else abort
1792 and invoke the normal binding."
1794 (if (> company-candidates-length 1)
1795 (company-select-next)
1797 (company--unread-last-input)))
1799 (defun company-select-previous-or-abort ()
1800 "Select the previous candidate if more than one, else abort
1801 and invoke the normal binding."
1803 (if (> company-candidates-length 1)
1804 (company-select-previous)
1806 (company--unread-last-input)))
1808 (defvar company-pseudo-tooltip-overlay)
1810 (defvar company-tooltip-offset)
1812 (defun company--inside-tooltip-p (event-col-row row height)
1813 (let* ((ovl company-pseudo-tooltip-overlay)
1814 (column (overlay-get ovl 'company-column))
1815 (width (overlay-get ovl 'company-width))
1816 (evt-col (car event-col-row))
1817 (evt-row (cdr event-col-row)))
1818 (and (>= evt-col column)
1819 (< evt-col (+ column width))
1821 (and (> evt-row row)
1822 (<= evt-row (+ row height) ))
1823 (and (< evt-row row)
1824 (>= evt-row (+ row height)))))))
1826 (defun company--event-col-row (event)
1827 (company--posn-col-row (event-start event)))
1829 (defun company-select-mouse (event)
1830 "Select the candidate picked by the mouse."
1832 (let ((event-col-row (company--event-col-row event))
1833 (ovl-row (company--row))
1834 (ovl-height (and company-pseudo-tooltip-overlay
1835 (min (overlay-get company-pseudo-tooltip-overlay
1837 company-candidates-length))))
1839 (company--inside-tooltip-p event-col-row ovl-row ovl-height))
1841 (company-set-selection (+ (cdr event-col-row)
1842 (1- company-tooltip-offset)
1843 (if (and (eq company-tooltip-offset-display 'lines)
1844 (not (zerop company-tooltip-offset)))
1847 (if (< ovl-height 0)
1852 (company--unread-last-input)
1855 (defun company-complete-mouse (event)
1856 "Insert the candidate picked by the mouse."
1858 (when (company-select-mouse event)
1859 (company-complete-selection)))
1861 (defun company-complete-selection ()
1862 "Insert the selected candidate."
1864 (when (company-manual-begin)
1865 (let ((result (nth company-selection company-candidates)))
1866 (company-finish result))))
1868 (defun company-complete-common ()
1869 "Insert the common part of all candidates."
1871 (when (company-manual-begin)
1872 (if (and (not (cdr company-candidates))
1873 (equal company-common (car company-candidates)))
1874 (company-complete-selection)
1875 (when company-common
1876 (company--insert-candidate company-common)))))
1878 (defun company-complete-common-or-cycle ()
1879 "Insert the common part of all candidates, or select the next one."
1881 (when (company-manual-begin)
1882 (let ((tick (buffer-chars-modified-tick)))
1883 (call-interactively 'company-complete-common)
1884 (when (eq tick (buffer-chars-modified-tick))
1885 (let ((company-selection-wrap-around t))
1886 (call-interactively 'company-select-next))))))
1888 (defun company-complete ()
1889 "Insert the common part of all candidates or the current selection.
1890 The first time this is called, the common part is inserted, the second
1891 time, or when the selection has been changed, the selected candidate is
1894 (when (company-manual-begin)
1895 (if (or company-selection-changed
1896 (eq last-command 'company-complete-common))
1897 (call-interactively 'company-complete-selection)
1898 (call-interactively 'company-complete-common)
1899 (setq this-command 'company-complete-common))))
1901 (defun company-complete-number (n)
1902 "Insert the Nth candidate visible in the tooltip.
1903 To show the number next to the candidates in some back-ends, enable
1904 `company-show-numbers'. When called interactively, uses the last typed
1905 character, stripping the modifiers. That character must be a digit."
1907 (list (let* ((type (event-basic-type last-command-event))
1908 (char (if (characterp type)
1909 ;; Number on the main row.
1911 ;; Keypad number, if bound directly.
1912 (car (last (string-to-list (symbol-name type))))))
1914 (if (zerop n) 10 n))))
1915 (when (company-manual-begin)
1916 (and (or (< n 1) (> n (- company-candidates-length
1917 company-tooltip-offset)))
1918 (error "No candidate number %d" n))
1920 (company-finish (nth (+ n company-tooltip-offset)
1921 company-candidates))))
1923 ;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;
1925 (defconst company-space-strings-limit 100)
1927 (defconst company-space-strings
1929 (dotimes (i company-space-strings-limit)
1930 (push (make-string (- company-space-strings-limit 1 i) ?\ ) lst))
1931 (apply 'vector lst)))
1933 (defun company-space-string (len)
1934 (if (< len company-space-strings-limit)
1935 (aref company-space-strings len)
1936 (make-string len ?\ )))
1938 (defun company-safe-substring (str from &optional to)
1939 (if (> from (string-width str))
1943 (move-to-column from)
1944 (let ((beg (point)))
1948 (concat (buffer-substring beg (point))
1949 (let ((padding (- to (current-column))))
1951 (company-space-string padding)))))
1952 (buffer-substring beg (point-max)))))))
1954 ;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;
1956 (defvar-local company-last-metadata nil)
1958 (defun company-fetch-metadata ()
1959 (let ((selected (nth company-selection company-candidates)))
1960 (unless (eq selected (car company-last-metadata))
1961 (setq company-last-metadata
1962 (cons selected (company-call-backend 'meta selected))))
1963 (cdr company-last-metadata)))
1965 (defun company-doc-buffer (&optional string)
1966 (with-current-buffer (get-buffer-create "*company-documentation*")
1973 (defvar company--electric-commands
1974 '(scroll-other-window scroll-other-window-down)
1975 "List of Commands that won't break out of electric commands.")
1977 (defmacro company--electric-do (&rest body)
1978 (declare (indent 0) (debug t))
1979 `(when (company-manual-begin)
1980 (save-window-excursion
1981 (let ((height (window-height))
1982 (row (company--row))
1985 (and (< (window-height) height)
1986 (< (- (window-height) row 2) company-tooltip-limit)
1987 (recenter (- (window-height) row 2)))
1988 (while (memq (setq cmd (key-binding (vector (list (read-event)))))
1989 company--electric-commands)
1990 (call-interactively cmd))
1991 (company--unread-last-input)))))
1993 (defun company--unread-last-input ()
1994 (when last-input-event
1995 (clear-this-command-keys t)
1996 (setq unread-command-events (list last-input-event))))
1998 (defun company-show-doc-buffer ()
1999 "Temporarily show the documentation buffer for the selection."
2001 (company--electric-do
2002 (let* ((selected (nth company-selection company-candidates))
2003 (doc-buffer (or (company-call-backend 'doc-buffer selected)
2004 (error "No documentation available"))))
2005 (with-current-buffer doc-buffer
2006 (goto-char (point-min)))
2007 (display-buffer doc-buffer t))))
2008 (put 'company-show-doc-buffer 'company-keep t)
2010 (defun company-show-location ()
2011 "Temporarily display a buffer showing the selected candidate in context."
2013 (company--electric-do
2014 (let* ((selected (nth company-selection company-candidates))
2015 (location (company-call-backend 'location selected))
2016 (pos (or (cdr location) (error "No location available")))
2017 (buffer (or (and (bufferp (car location)) (car location))
2018 (find-file-noselect (car location) t))))
2019 (with-selected-window (display-buffer buffer t)
2022 (if (bufferp (car location))
2024 (goto-char (point-min))
2025 (forward-line (1- pos))))
2026 (set-window-start nil (point))))))
2027 (put 'company-show-location 'company-keep t)
2029 ;;; package functions ;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;
2031 (defvar-local company-callback nil)
2033 (defun company-remove-callback (&optional ignored)
2034 (remove-hook 'company-completion-finished-hook company-callback t)
2035 (remove-hook 'company-completion-cancelled-hook 'company-remove-callback t)
2036 (remove-hook 'company-completion-finished-hook 'company-remove-callback t))
2038 (defun company-begin-backend (backend &optional callback)
2039 "Start a completion at point using BACKEND."
2040 (interactive (let ((val (completing-read "Company back-end: "
2042 'functionp nil "company-")))
2044 (list (intern val)))))
2045 (when (setq company-callback callback)
2046 (add-hook 'company-completion-finished-hook company-callback nil t))
2047 (add-hook 'company-completion-cancelled-hook 'company-remove-callback nil t)
2048 (add-hook 'company-completion-finished-hook 'company-remove-callback nil t)
2049 (setq company-backend backend)
2050 ;; Return non-nil if active.
2051 (or (company-manual-begin)
2052 (error "Cannot complete at point")))
2054 (defun company-begin-with (candidates
2055 &optional prefix-length require-match callback)
2056 "Start a completion at point.
2057 CANDIDATES is the list of candidates to use and PREFIX-LENGTH is the length
2058 of the prefix that already is in the buffer before point.
2061 CALLBACK is a function called with the selected result if the user
2062 successfully completes the input.
2064 Example: \(company-begin-with '\(\"foo\" \"foobar\" \"foobarbaz\"\)\)"
2065 (let ((begin-marker (copy-marker (point) t)))
2066 (company-begin-backend
2067 (lambda (command &optional arg &rest ignored)
2070 (when (equal (point) (marker-position begin-marker))
2071 (buffer-substring (- (point) (or prefix-length 0)) (point))))
2073 (all-completions arg candidates))
2078 (defun company-version (&optional show-version)
2079 "Get the Company version as string.
2081 If SHOW-VERSION is non-nil, show the version in the echo area."
2082 (interactive (list t))
2084 (insert-file-contents (find-library-name "company"))
2087 (message "Company version: %s" (lm-version))
2090 ;;; pseudo-tooltip ;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;
2092 (defvar-local company-pseudo-tooltip-overlay nil)
2094 (defvar-local company-tooltip-offset 0)
2096 (defun company-tooltip--lines-update-offset (selection num-lines limit)
2098 (setq company-tooltip-offset
2099 (max (min selection company-tooltip-offset)
2100 (- selection -1 limit)))
2102 (when (<= company-tooltip-offset 1)
2104 (setq company-tooltip-offset 0))
2106 (when (>= company-tooltip-offset (- num-lines limit 1))
2108 (when (= selection (1- num-lines))
2109 (cl-decf company-tooltip-offset)
2110 (when (<= company-tooltip-offset 1)
2111 (setq company-tooltip-offset 0)
2116 (defun company-tooltip--simple-update-offset (selection _num-lines limit)
2117 (setq company-tooltip-offset
2118 (if (< selection company-tooltip-offset)
2120 (max company-tooltip-offset
2121 (- selection limit -1)))))
2125 (defsubst company-round-tab (arg)
2126 (* (/ (+ arg tab-width) tab-width) tab-width))
2128 (defun company-plainify (str)
2129 (let ((prefix (get-text-property 0 'line-prefix str)))
2130 (when prefix ; Keep the original value unmodified, for no special reason.
2131 (setq str (concat prefix str))
2132 (remove-text-properties 0 (length str) '(line-prefix) str)))
2133 (let* ((pieces (split-string str "\t"))
2136 (setcar copy (company-safe-substring
2137 (car copy) 0 (company-round-tab (string-width (car copy)))))
2139 (apply 'concat pieces)))
2141 (defun company-fill-propertize (value annotation width selected left right)
2142 (let* ((margin (length left))
2143 (common (or (company-call-backend 'match value)
2145 (string-width company-common)
2147 (ann-ralign company-tooltip-align-annotations)
2148 (ann-truncate (< width
2149 (+ (length value) (length annotation)
2150 (if ann-ralign 1 0))))
2151 (ann-start (+ margin
2155 (- width (length annotation)))
2157 (ann-end (min (+ ann-start (length annotation)) (+ margin width)))
2159 (if (or ann-truncate (not ann-ralign))
2160 (company-safe-substring
2162 (when (and annotation ann-ralign) " ")
2166 (company-safe-substring value 0
2167 (- width (length annotation)))
2170 (setq common (+ (min common width) margin))
2171 (setq width (+ width margin (length right)))
2173 (add-text-properties 0 width '(face company-tooltip
2174 mouse-face company-tooltip-mouse)
2176 (add-text-properties margin common
2177 '(face company-tooltip-common
2178 mouse-face company-tooltip-mouse)
2180 (when (< ann-start ann-end)
2181 (add-text-properties ann-start ann-end
2182 '(face company-tooltip-annotation
2183 mouse-face company-tooltip-mouse)
2186 (if (and (not (string= company-search-string ""))
2187 (string-match (regexp-quote company-search-string) value
2188 (length company-prefix)))
2189 (let ((beg (+ margin (match-beginning 0)))
2190 (end (+ margin (match-end 0))))
2191 (add-text-properties beg end '(face company-tooltip-search)
2193 (add-text-properties 0 width '(face company-tooltip-selection
2194 mouse-face company-tooltip-selection)
2196 (add-text-properties margin common
2197 '(face company-tooltip-common-selection
2198 mouse-face company-tooltip-selection)
2202 (defun company--clean-string (str)
2203 (replace-regexp-in-string
2204 "\\([^[:graph:] ]\\)\\|\\(\ufeff\\)\\|[[:multibyte:]]"
2207 ((match-beginning 1)
2208 ;; FIXME: Better char for 'non-printable'?
2209 ;; We shouldn't get any of these, but sometimes we might.
2211 ((match-beginning 2)
2212 ;; Zero-width non-breakable space.
2214 ((> (string-width match) 1)
2216 (make-string (1- (string-width match)) ?\ufeff)
2223 (defun company-buffer-lines (beg end)
2225 (let (lines lines-moved)
2226 (while (and (not (eobp)) ; http://debbugs.gnu.org/19553
2227 (> (setq lines-moved (vertical-motion 1)) 0)
2229 (let ((bound (min end (1- (point)))))
2230 ;; A visual line can contain several physical lines (e.g. with outline's
2231 ;; folding overlay). Take only the first one.
2232 (push (buffer-substring beg
2235 (re-search-forward "$" bound 'move)
2238 ;; One physical line can be displayed as several visual ones as well:
2239 ;; add empty strings to the list, to even the count.
2240 (dotimes (_ (1- lines-moved))
2243 (unless (eq beg end)
2244 (push (buffer-substring beg end) lines))
2247 (defun company-modify-line (old new offset)
2248 (concat (company-safe-substring old 0 offset)
2250 (company-safe-substring old (+ offset (length new)))))
2252 (defsubst company--length-limit (lst limit)
2253 (if (nthcdr limit lst)
2257 (defsubst company--window-height ()
2258 (if (fboundp 'window-screen-lines)
2259 (floor (window-screen-lines))
2260 (window-body-height)))
2262 (defun company--window-width ()
2263 (let ((ww (window-body-width)))
2264 ;; Account for the line continuation column.
2265 (when (zerop (cadr (window-fringes)))
2267 (unless (or (display-graphic-p)
2268 (version< "24.3.1" emacs-version))
2269 ;; Emacs 24.3 and earlier included margins
2270 ;; in window-width when in TTY.
2272 (let ((margins (window-margins)))
2273 (+ (or (car margins) 0)
2274 (or (cdr margins) 0)))))
2275 (when (and word-wrap
2276 (version< emacs-version "24.4.51.5"))
2277 ;; http://debbugs.gnu.org/18384
2281 (defun company--replacement-string (lines old column nl &optional align-top)
2282 (cl-decf column company-tooltip-margin)
2284 (when (and align-top company-tooltip-flip-when-above)
2285 (setq lines (reverse lines)))
2287 (let ((width (length (car lines)))
2288 (remaining-cols (- (+ (company--window-width) (window-hscroll))
2290 (when (> width remaining-cols)
2291 (cl-decf column (- width remaining-cols))))
2293 (let ((offset (and (< column 0) (- column)))
2298 ;; untouched lines first
2299 (dotimes (_ (- (length old) (length lines)))
2300 (push (pop old) new)))
2301 ;; length into old lines.
2303 (push (company-modify-line (pop old)
2304 (company--offset-line (pop lines) offset)
2307 ;; Append whole new lines.
2309 (push (concat (company-space-string column)
2310 (company--offset-line (pop lines) offset))
2313 (let ((str (concat (when nl " ")
2315 (mapconcat 'identity (nreverse new) "\n")
2317 (font-lock-append-text-property 0 (length str) 'face 'default str)
2318 (when nl (put-text-property 0 1 'cursor t str))
2321 (defun company--offset-line (line offset)
2322 (if (and offset line)
2323 (substring line offset)
2326 (defun company--create-lines (selection limit)
2327 (let ((len company-candidates-length)
2328 (window-width (company--window-width))
2337 ;; Maybe clear old offset.
2338 (when (< len (+ company-tooltip-offset limit))
2339 (setq company-tooltip-offset 0))
2341 ;; Scroll to offset.
2342 (if (eq company-tooltip-offset-display 'lines)
2343 (setq limit (company-tooltip--lines-update-offset selection len limit))
2344 (company-tooltip--simple-update-offset selection len limit))
2347 ((eq company-tooltip-offset-display 'scrollbar)
2348 (setq scrollbar-bounds (company--scrollbar-bounds company-tooltip-offset
2350 ((eq company-tooltip-offset-display 'lines)
2351 (when (> company-tooltip-offset 0)
2352 (setq previous (format "...(%d)" company-tooltip-offset)))
2353 (setq remainder (- len limit company-tooltip-offset)
2354 remainder (when (> remainder 0)
2355 (setq remainder (format "...(%d)" remainder))))))
2357 (cl-decf selection company-tooltip-offset)
2358 (setq width (max (length previous) (length remainder))
2359 lines (nthcdr company-tooltip-offset company-candidates)
2363 (cl-decf window-width (* 2 company-tooltip-margin))
2364 (when scrollbar-bounds (cl-decf window-width))
2367 (let* ((value (pop lines-copy))
2368 (annotation (company-call-backend 'annotation value)))
2369 (setq value (company--clean-string value))
2371 (when company-tooltip-align-annotations
2372 ;; `lisp-completion-at-point' adds a space.
2373 (setq annotation (comment-string-strip annotation t nil)))
2374 (setq annotation (company--clean-string annotation)))
2375 (push (cons value annotation) items)
2376 (setq width (max (+ (length value)
2377 (if (and annotation company-tooltip-align-annotations)
2378 (1+ (length annotation))
2379 (length annotation)))
2382 (setq width (min window-width
2383 (max company-tooltip-minimum-width
2384 (if company-show-numbers
2388 (let ((items (nreverse items))
2389 (numbered (if company-show-numbers 0 99999))
2392 (push (company--scrollpos-line previous width) new))
2395 (let* ((item (pop items))
2396 (str (company-reformat (car item)))
2397 (annotation (cdr item))
2398 (right (company-space-string company-tooltip-margin))
2400 (when (< numbered 10)
2403 (setq right (concat (format " %d" (mod numbered 10)) right)))
2405 (company-fill-propertize str annotation
2406 width (equal i selection)
2407 (company-space-string
2408 company-tooltip-margin)
2410 (when scrollbar-bounds
2411 (company--scrollbar i scrollbar-bounds)))
2415 (push (company--scrollpos-line remainder width) new))
2419 (defun company--scrollbar-bounds (offset limit length)
2420 (when (> length limit)
2421 (let* ((size (ceiling (* limit (float limit)) length))
2422 (lower (floor (* limit (float offset)) length))
2423 (upper (+ lower size -1)))
2424 (cons lower upper))))
2426 (defun company--scrollbar (i bounds)
2427 (propertize " " 'face
2428 (if (and (>= i (car bounds)) (<= i (cdr bounds)))
2429 'company-scrollbar-fg
2430 'company-scrollbar-bg)))
2432 (defun company--scrollpos-line (text width)
2433 (propertize (concat (company-space-string company-tooltip-margin)
2434 (company-safe-substring text 0 width)
2435 (company-space-string company-tooltip-margin))
2436 'face 'company-tooltip))
2440 (defun company--pseudo-tooltip-height ()
2441 "Calculate the appropriate tooltip height.
2442 Returns a negative number if the tooltip should be displayed above point."
2443 (let* ((lines (company--row))
2444 (below (- (company--window-height) 1 lines)))
2445 (if (and (< below (min company-tooltip-minimum company-candidates-length))
2447 (- (max 3 (min company-tooltip-limit lines)))
2448 (max 3 (min company-tooltip-limit below)))))
2450 (defun company-pseudo-tooltip-show (row column selection)
2451 (company-pseudo-tooltip-hide)
2454 (let* ((height (company--pseudo-tooltip-height))
2458 (setq row (+ row height -1)
2461 (let* ((nl (< (move-to-window-line row) row))
2463 (end (save-excursion
2464 (move-to-window-line (+ row (abs height)))
2466 (ov (make-overlay (if nl beg (1- beg)) end nil t))
2467 (args (list (mapcar 'company-plainify
2468 (company-buffer-lines beg end))
2471 (setq company-pseudo-tooltip-overlay ov)
2472 (overlay-put ov 'company-replacement-args args)
2474 (let ((lines (company--create-lines selection (abs height))))
2475 (overlay-put ov 'company-display
2476 (apply 'company--replacement-string lines args))
2477 (overlay-put ov 'company-width (string-width (car lines))))
2479 (overlay-put ov 'company-column column)
2480 (overlay-put ov 'company-height height)))))
2482 (defun company-pseudo-tooltip-show-at-point (pos column-offset)
2483 (let* ((col-row (company--col-row pos))
2484 (col (- (car col-row) column-offset)))
2485 (when (< col 0) (setq col 0))
2486 (company-pseudo-tooltip-show (1+ (cdr col-row)) col company-selection)))
2488 (defun company-pseudo-tooltip-edit (selection)
2489 (let* ((height (overlay-get company-pseudo-tooltip-overlay 'company-height))
2490 (lines (company--create-lines selection (abs height))))
2491 (overlay-put company-pseudo-tooltip-overlay 'company-width
2492 (string-width (car lines)))
2493 (overlay-put company-pseudo-tooltip-overlay 'company-display
2494 (apply 'company--replacement-string
2496 (overlay-get company-pseudo-tooltip-overlay
2497 'company-replacement-args)))))
2499 (defun company-pseudo-tooltip-hide ()
2500 (when company-pseudo-tooltip-overlay
2501 (delete-overlay company-pseudo-tooltip-overlay)
2502 (setq company-pseudo-tooltip-overlay nil)))
2504 (defun company-pseudo-tooltip-hide-temporarily ()
2505 (when (overlayp company-pseudo-tooltip-overlay)
2506 (overlay-put company-pseudo-tooltip-overlay 'invisible nil)
2507 (overlay-put company-pseudo-tooltip-overlay 'after-string nil)))
2509 (defun company-pseudo-tooltip-unhide ()
2510 (when company-pseudo-tooltip-overlay
2511 (let* ((ov company-pseudo-tooltip-overlay)
2512 (disp (overlay-get ov 'company-display)))
2513 ;; Beat outline's folding overlays, at least.
2514 (overlay-put ov 'priority 1)
2515 ;; `display' could be better (http://debbugs.gnu.org/18285), but it
2516 ;; doesn't work when the overlay is empty, which is what happens at eob.
2517 ;; It also seems to interact badly with `cursor'.
2518 ;; We deal with priorities by having the overlay start before the newline.
2519 (overlay-put ov 'after-string disp)
2520 (overlay-put ov 'invisible t)
2521 (overlay-put ov 'window (selected-window)))))
2523 (defun company-pseudo-tooltip-guard ()
2525 (save-excursion (beginning-of-visual-line))
2526 (let ((ov company-pseudo-tooltip-overlay)
2527 (overhang (save-excursion (end-of-visual-line)
2528 (- (line-end-position) (point)))))
2529 (when (>= (overlay-get ov 'company-height) 0)
2531 (buffer-substring-no-properties (point) (overlay-start ov))
2532 (when (>= overhang 0) overhang))))))
2534 (defun company-pseudo-tooltip-frontend (command)
2535 "`company-mode' front-end similar to a tooltip but based on overlays."
2537 (pre-command (company-pseudo-tooltip-hide-temporarily))
2539 (unless (when (overlayp company-pseudo-tooltip-overlay)
2540 (let* ((ov company-pseudo-tooltip-overlay)
2541 (old-height (overlay-get ov 'company-height))
2542 (new-height (company--pseudo-tooltip-height)))
2544 (>= (* old-height new-height) 0)
2545 (>= (abs old-height) (abs new-height))
2546 (equal (company-pseudo-tooltip-guard)
2547 (overlay-get ov 'company-guard)))))
2549 (company-pseudo-tooltip-show-at-point (point) (length company-prefix))
2550 (overlay-put company-pseudo-tooltip-overlay
2551 'company-guard (company-pseudo-tooltip-guard)))
2552 (company-pseudo-tooltip-unhide))
2553 (hide (company-pseudo-tooltip-hide)
2554 (setq company-tooltip-offset 0))
2555 (update (when (overlayp company-pseudo-tooltip-overlay)
2556 (company-pseudo-tooltip-edit company-selection)))))
2558 (defun company-pseudo-tooltip-unless-just-one-frontend (command)
2559 "`company-pseudo-tooltip-frontend', but not shown for single candidates."
2560 (unless (and (eq command 'post-command)
2561 (company--show-inline-p))
2562 (company-pseudo-tooltip-frontend command)))
2564 ;;; overlay ;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;
2566 (defvar-local company-preview-overlay nil)
2568 (defun company-preview-show-at-point (pos)
2569 (company-preview-hide)
2571 (let ((completion (nth company-selection company-candidates)))
2572 (setq completion (propertize completion 'face 'company-preview))
2573 (add-text-properties 0 (length company-common)
2574 '(face company-preview-common) completion)
2576 ;; Add search string
2577 (and company-search-string
2578 (string-match (regexp-quote company-search-string) completion)
2579 (add-text-properties (match-beginning 0)
2581 '(face company-preview-search)
2584 (setq completion (company-strip-prefix completion))
2586 (and (equal pos (point))
2587 (not (equal completion ""))
2588 (add-text-properties 0 1 '(cursor 1) completion))
2591 (pto company-pseudo-tooltip-overlay)
2592 (ptf-workaround (and
2595 (eq pos (overlay-start pto)))))
2596 ;; Try to accomodate for the pseudo-tooltip overlay,
2597 ;; which may start at the same position if it's at eol.
2598 (when ptf-workaround
2600 (setq completion (concat (buffer-substring beg pos) completion)))
2602 (setq company-preview-overlay (make-overlay beg pos))
2604 (let ((ov company-preview-overlay))
2605 (overlay-put ov (if ptf-workaround 'display 'after-string)
2607 (overlay-put ov 'window (selected-window))))))
2609 (defun company-preview-hide ()
2610 (when company-preview-overlay
2611 (delete-overlay company-preview-overlay)
2612 (setq company-preview-overlay nil)))
2614 (defun company-preview-frontend (command)
2615 "`company-mode' front-end showing the selection as if it had been inserted."
2617 (`pre-command (company-preview-hide))
2618 (`post-command (company-preview-show-at-point (point)))
2619 (`hide (company-preview-hide))))
2621 (defun company-preview-if-just-one-frontend (command)
2622 "`company-preview-frontend', but only shown for single candidates."
2623 (when (or (not (eq command 'post-command))
2624 (company--show-inline-p))
2625 (company-preview-frontend command)))
2627 (defun company--show-inline-p ()
2628 (and (not (cdr company-candidates))
2630 (or (eq (company-call-backend 'ignore-case) 'keep-prefix)
2631 (string-prefix-p company-prefix company-common))))
2633 ;;; echo ;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;
2635 (defvar-local company-echo-last-msg nil)
2637 (defvar company-echo-timer nil)
2639 (defvar company-echo-delay .01)
2641 (defun company-echo-show (&optional getter)
2643 (setq company-echo-last-msg (funcall getter)))
2644 (let ((message-log-max nil))
2645 (if company-echo-last-msg
2646 (message "%s" company-echo-last-msg)
2649 (defun company-echo-show-soon (&optional getter)
2650 (when company-echo-timer
2651 (cancel-timer company-echo-timer))
2652 (setq company-echo-timer (run-with-timer 0 nil 'company-echo-show getter)))
2654 (defsubst company-echo-show-when-idle (&optional getter)
2655 (when (sit-for company-echo-delay)
2656 (company-echo-show getter)))
2658 (defun company-echo-format ()
2660 (let ((limit (window-body-width (minibuffer-window)))
2662 ;; Roll to selection.
2663 (candidates (nthcdr company-selection company-candidates))
2664 (i (if company-show-numbers company-selection 99999))
2668 (setq comp (company-reformat (pop candidates))
2669 len (+ len 1 (length comp)))
2673 (setq comp (propertize (format "%d: %s" i comp)
2674 'face 'company-echo))
2677 (add-text-properties 3 (+ 3 (length company-common))
2678 '(face company-echo-common) comp))
2679 (setq comp (propertize comp 'face 'company-echo))
2680 (add-text-properties 0 (length company-common)
2681 '(face company-echo-common) comp))
2683 (setq candidates nil)
2686 (mapconcat 'identity (nreverse msg) " ")))
2688 (defun company-echo-strip-common-format ()
2690 (let ((limit (window-body-width (minibuffer-window)))
2691 (len (+ (length company-prefix) 2))
2692 ;; Roll to selection.
2693 (candidates (nthcdr company-selection company-candidates))
2694 (i (if company-show-numbers company-selection 99999))
2698 (setq comp (company-strip-prefix (pop candidates))
2699 len (+ len 2 (length comp)))
2702 (setq comp (format "%s (%d)" comp i))
2706 (setq candidates nil)
2707 (push (propertize comp 'face 'company-echo) msg)))
2709 (concat (propertize company-prefix 'face 'company-echo-common) "{"
2710 (mapconcat 'identity (nreverse msg) ", ")
2713 (defun company-echo-hide ()
2714 (unless (equal company-echo-last-msg "")
2715 (setq company-echo-last-msg "")
2716 (company-echo-show)))
2718 (defun company-echo-frontend (command)
2719 "`company-mode' front-end showing the candidates in the echo area."
2721 (`post-command (company-echo-show-soon 'company-echo-format))
2722 (`hide (company-echo-hide))))
2724 (defun company-echo-strip-common-frontend (command)
2725 "`company-mode' front-end showing the candidates in the echo area."
2727 (`post-command (company-echo-show-soon 'company-echo-strip-common-format))
2728 (`hide (company-echo-hide))))
2730 (defun company-echo-metadata-frontend (command)
2731 "`company-mode' front-end showing the documentation in the echo area."
2733 (`post-command (company-echo-show-when-idle 'company-fetch-metadata))
2734 (`hide (company-echo-hide))))
2737 ;;; company.el ends here