1 ;;; company.el --- Modular text completion framework -*- lexical-binding: t -*-
3 ;; Copyright (C) 2009-2016 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 ;; FIXME: We could use a version-test to exclude
322 ;; company-nxml, but we don't know yet if that
323 ;; version will be called 25.2 or 26.1.
324 company-nxml company-css
325 company-eclim company-semantic company-clang
326 company-xcode company-ropemacs company-cmake
328 (company-dabbrev-code company-gtags company-etags
330 company-oddmuse company-files company-dabbrev)
331 "The list of active back-ends (completion engines).
333 Only one back-end is used at a time. The choice depends on the order of
334 the items in this list, and on the values they return in response to the
335 `prefix' command (see below). But a back-end can also be a \"grouped\"
338 `company-begin-backend' can be used to start a specific back-end,
339 `company-other-backend' will skip to the next matching back-end in the list.
341 Each back-end is a function that takes a variable number of arguments.
342 The first argument is the command requested from the back-end. It is one
345 `prefix': The back-end should return the text to be completed. It must be
346 text immediately before point. Returning nil from this command passes
347 control to the next back-end. The function should return `stop' if it
348 should complete but cannot (e.g. if it is in the middle of a string).
349 Instead of a string, the back-end may return a cons where car is the prefix
350 and cdr is used in `company-minimum-prefix-length' test. It must be either
351 number or t, and in the latter case the test automatically succeeds.
353 `candidates': The second argument is the prefix to be completed. The
354 return value should be a list of candidates that match the prefix.
356 Non-prefix matches are also supported (candidates that don't start with the
357 prefix, but match it in some backend-defined way). Backends that use this
358 feature must disable cache (return t to `no-cache') and might also want to
363 `sorted': Return t here to indicate that the candidates are sorted and will
364 not need to be sorted again.
366 `duplicates': If non-nil, company will take care of removing duplicates
369 `no-cache': Usually company doesn't ask for candidates again as completion
370 progresses, unless the back-end returns t for this command. The second
371 argument is the latest prefix.
373 `meta': The second argument is a completion candidate. Return a (short)
374 documentation string for it.
376 `doc-buffer': The second argument is a completion candidate. Return a
377 buffer with documentation for it. Preferably use `company-doc-buffer',
379 `location': The second argument is a completion candidate. Return the cons
380 of buffer and buffer location, or of file and line number where the
381 completion candidate was defined.
383 `annotation': The second argument is a completion candidate. Return a
384 string to be displayed inline with the candidate in the popup. If
385 duplicates are removed by company, candidates with equal string values will
386 be kept if they have different annotations. For that to work properly,
387 backends should store the related information on candidates using text
390 `match': The second argument is a completion candidate. Return the index
391 after the end of text matching `prefix' within the candidate string. It
392 will be used when rendering the popup. This command only makes sense for
393 backends that provide non-prefix completion.
395 `require-match': If this returns t, the user is not allowed to enter
396 anything not offered as a candidate. Use with care! The default value nil
397 gives the user that choice with `company-require-match'. Return value
398 `never' overrides that option the other way around.
400 `init': Called once for each buffer. The back-end can check for external
401 programs and files and load any required libraries. Raising an error here
402 will show up in message log once, and the back-end will not be used for
405 `post-completion': Called after a completion candidate has been inserted
406 into the buffer. The second argument is the candidate. Can be used to
407 modify it, e.g. to expand a snippet.
409 The back-end should return nil for all commands it does not support or
410 does not know about. It should also be callable interactively and use
411 `company-begin-backend' to start itself in that case.
415 An element of `company-backends' can also itself be a list of back-ends,
416 then it's considered to be a \"grouped\" back-end.
418 When possible, commands taking a candidate as an argument are dispatched to
419 the back-end it came from. In other cases, the first non-nil value among
420 all the back-ends is returned.
422 The latter is the case for the `prefix' command. But if the group contains
423 the keyword `:with', the back-ends after it are ignored for this command.
425 The completions from back-ends in a group are merged (but only from those
426 that return the same `prefix').
428 Asynchronous back-ends:
430 The return value of each command can also be a cons (:async . FETCHER)
431 where FETCHER is a function of one argument, CALLBACK. When the data
432 arrives, FETCHER must call CALLBACK and pass it the appropriate return
433 value, as described above.
435 True asynchronous operation is only supported for command `candidates', and
436 only during idle completion. Other commands will block the user interface,
437 even if the back-end uses the asynchronous calling convention."
441 ,@(mapcar (lambda (b) `(const :tag ,(cdr b) ,(car b)))
442 company-safe-backends)
443 (symbol :tag "User defined")
444 (repeat :tag "Merged Back-ends"
445 (choice :tag "Back-end"
446 ,@(mapcar (lambda (b)
447 `(const :tag ,(cdr b) ,(car b)))
448 company-safe-backends)
449 (const :tag "With" :with)
450 (symbol :tag "User defined"))))))
452 (put 'company-backends 'safe-local-variable 'company-safe-backends-p)
454 (defcustom company-transformers nil
455 "Functions to change the list of candidates received from backends.
457 Each function gets called with the return value of the previous one.
458 The first one gets passed the list of candidates, already sorted and
461 (const :tag "None" nil)
462 (const :tag "Sort by occurrence" (company-sort-by-occurrence))
463 (const :tag "Sort by back-end importance"
464 (company-sort-by-backend-importance))
465 (repeat :tag "User defined" (function))))
467 (defcustom company-completion-started-hook nil
468 "Hook run when company starts completing.
469 The hook is called with one argument that is non-nil if the completion was
473 (defcustom company-completion-cancelled-hook nil
474 "Hook run when company cancels completing.
475 The hook is called with one argument that is non-nil if the completion was
479 (defcustom company-completion-finished-hook nil
480 "Hook run when company successfully completes.
481 The hook is called with the selected candidate as an argument.
483 If you indend to use it to post-process candidates from a specific
484 back-end, consider using the `post-completion' command instead."
487 (defcustom company-minimum-prefix-length 3
488 "The minimum prefix length for idle completion."
489 :type '(integer :tag "prefix length"))
491 (defcustom company-abort-manual-when-too-short nil
492 "If enabled, cancel a manually started completion when the prefix gets
493 shorter than both `company-minimum-prefix-length' and the length of the
494 prefix it was started from."
496 :package-version '(company . "0.8.0"))
498 (defcustom company-require-match 'company-explicit-action-p
499 "If enabled, disallow non-matching input.
500 This can be a function do determine if a match is required.
502 This can be overridden by the back-end, if it returns t or `never' to
503 `require-match'. `company-auto-complete' also takes precedence over this."
504 :type '(choice (const :tag "Off" nil)
505 (function :tag "Predicate function")
506 (const :tag "On, if user interaction took place"
507 'company-explicit-action-p)
508 (const :tag "On" t)))
510 (defcustom company-auto-complete nil
511 "Determines when to auto-complete.
512 If this is enabled, all characters from `company-auto-complete-chars'
513 trigger insertion of the selected completion candidate.
514 This can also be a function."
515 :type '(choice (const :tag "Off" nil)
516 (function :tag "Predicate function")
517 (const :tag "On, if user interaction took place"
518 'company-explicit-action-p)
519 (const :tag "On" t)))
521 (defcustom company-auto-complete-chars '(?\ ?\) ?.)
522 "Determines which characters trigger auto-completion.
523 See `company-auto-complete'. If this is a string, each string character
524 tiggers auto-completion. If it is a list of syntax description characters (see
525 `modify-syntax-entry'), all characters with that syntax auto-complete.
527 This can also be a function, which is called with the new input and should
528 return non-nil if company should auto-complete.
530 A character that is part of a valid candidate never triggers auto-completion."
531 :type '(choice (string :tag "Characters")
533 (const :tag "Whitespace" ?\ )
534 (const :tag "Symbol" ?_)
535 (const :tag "Opening parentheses" ?\()
536 (const :tag "Closing parentheses" ?\))
537 (const :tag "Word constituent" ?w)
538 (const :tag "Punctuation." ?.)
539 (const :tag "String quote." ?\")
540 (const :tag "Paired delimiter." ?$)
541 (const :tag "Expression quote or prefix operator." ?\')
542 (const :tag "Comment starter." ?<)
543 (const :tag "Comment ender." ?>)
544 (const :tag "Character-quote." ?/)
545 (const :tag "Generic string fence." ?|)
546 (const :tag "Generic comment fence." ?!))
547 (function :tag "Predicate function")))
549 (defcustom company-idle-delay .5
550 "The idle delay in seconds until completion starts automatically.
551 The prefix still has to satisfy `company-minimum-prefix-length' before that
552 happens. The value of nil means no idle completion."
553 :type '(choice (const :tag "never (nil)" nil)
554 (const :tag "immediate (0)" 0)
555 (number :tag "seconds")))
557 (defcustom company-begin-commands '(self-insert-command
558 org-self-insert-command
559 orgtbl-self-insert-command
564 "A list of commands after which idle completion is allowed.
565 If this is t, it can show completions after any command except a few from a
566 pre-defined list. See `company-idle-delay'.
568 Alternatively, any command with a non-nil `company-begin' property is
569 treated as if it was on this list."
570 :type '(choice (const :tag "Any command" t)
571 (const :tag "Self insert command" '(self-insert-command))
572 (repeat :tag "Commands" function))
573 :package-version '(company . "0.8.4"))
575 (defcustom company-continue-commands '(not save-buffer save-some-buffers
576 save-buffers-kill-terminal
577 save-buffers-kill-emacs)
578 "A list of commands that are allowed during completion.
579 If this is t, or if `company-begin-commands' is t, any command is allowed.
580 Otherwise, the value must be a list of symbols. If it starts with `not',
581 the cdr is the list of commands that abort completion. Otherwise, all
582 commands except those in that list, or in `company-begin-commands', or
583 commands in the `company-' namespace, abort completion."
584 :type '(choice (const :tag "Any command" t)
585 (cons :tag "Any except"
587 (repeat :tag "Commands" function))
588 (repeat :tag "Commands" function)))
590 (defcustom company-show-numbers nil
591 "If enabled, show quick-access numbers for the first ten candidates."
592 :type '(choice (const :tag "off" nil)
593 (const :tag "on" t)))
595 (defcustom company-selection-wrap-around nil
596 "If enabled, selecting item before first or after last wraps around."
597 :type '(choice (const :tag "off" nil)
598 (const :tag "on" t)))
600 (defvar company-async-wait 0.03
601 "Pause between checks to see if the value's been set when turning an
602 asynchronous call into synchronous.")
604 (defvar company-async-timeout 2
605 "Maximum wait time for a value to be set during asynchronous call.")
607 ;;; mode ;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;
609 (defvar company-mode-map (make-sparse-keymap)
610 "Keymap used by `company-mode'.")
612 (defvar company-active-map
613 (let ((keymap (make-sparse-keymap)))
614 (define-key keymap "\e\e\e" 'company-abort)
615 (define-key keymap "\C-g" 'company-abort)
616 (define-key keymap (kbd "M-n") 'company-select-next)
617 (define-key keymap (kbd "M-p") 'company-select-previous)
618 (define-key keymap (kbd "<down>") 'company-select-next-or-abort)
619 (define-key keymap (kbd "<up>") 'company-select-previous-or-abort)
620 (define-key keymap [remap scroll-up-command] 'company-next-page)
621 (define-key keymap [remap scroll-down-command] 'company-previous-page)
622 (define-key keymap [down-mouse-1] 'ignore)
623 (define-key keymap [down-mouse-3] 'ignore)
624 (define-key keymap [mouse-1] 'company-complete-mouse)
625 (define-key keymap [mouse-3] 'company-select-mouse)
626 (define-key keymap [up-mouse-1] 'ignore)
627 (define-key keymap [up-mouse-3] 'ignore)
628 (define-key keymap [return] 'company-complete-selection)
629 (define-key keymap (kbd "RET") 'company-complete-selection)
630 (define-key keymap [tab] 'company-complete-common)
631 (define-key keymap (kbd "TAB") 'company-complete-common)
632 (define-key keymap (kbd "<f1>") 'company-show-doc-buffer)
633 (define-key keymap (kbd "C-h") 'company-show-doc-buffer)
634 (define-key keymap "\C-w" 'company-show-location)
635 (define-key keymap "\C-s" 'company-search-candidates)
636 (define-key keymap "\C-\M-s" 'company-filter-candidates)
638 (define-key keymap (read-kbd-macro (format "M-%d" i)) 'company-complete-number))
640 "Keymap that is enabled during an active completion.")
642 (defvar company--disabled-backends nil)
644 (defun company-init-backend (backend)
645 (and (symbolp backend)
646 (not (fboundp backend))
647 (ignore-errors (require backend nil t)))
652 (funcall backend 'init)
653 (put backend 'company-init t))
655 (put backend 'company-init 'failed)
656 (unless (memq backend company--disabled-backends)
657 (message "Company back-end '%s' could not be initialized:\n%s"
658 backend (error-message-string err)))
659 (cl-pushnew backend company--disabled-backends)
661 ;; No initialization for lambdas.
662 ((functionp backend) t)
663 (t ;; Must be a list.
664 (cl-dolist (b backend)
666 (company-init-backend b))))))
668 (defcustom company-lighter-base "company"
669 "Base string to use for the `company-mode' lighter."
671 :package-version '(company . "0.8.10"))
673 (defvar company-lighter '(" "
676 (if (consp company-backend)
677 (company--group-lighter (nth company-selection
679 company-lighter-base)
680 (symbol-name company-backend)))
681 company-lighter-base))
682 "Mode line lighter for Company.
684 The value of this variable is a mode line template as in
685 `mode-line-format'.")
687 (put 'company-lighter 'risky-local-variable t)
690 (define-minor-mode company-mode
691 "\"complete anything\"; is an in-buffer completion framework.
692 Completion starts automatically, depending on the values
693 `company-idle-delay' and `company-minimum-prefix-length'.
695 Completion can be controlled with the commands:
696 `company-complete-common', `company-complete-selection', `company-complete',
697 `company-select-next', `company-select-previous'. If these commands are
698 called before `company-idle-delay', completion will also start.
700 Completions can be searched with `company-search-candidates' or
701 `company-filter-candidates'. These can be used while completion is
704 The completion data is retrieved using `company-backends' and displayed
705 using `company-frontends'. If you want to start a specific back-end, call
706 it interactively or use `company-begin-backend'.
708 regular keymap (`company-mode-map'):
711 keymap during active completions (`company-active-map'):
713 \\{company-active-map}"
714 nil company-lighter company-mode-map
717 (when (eq company-idle-delay t)
718 (setq company-idle-delay 0)
719 (warn "Setting `company-idle-delay' to t is deprecated. Set it to 0 instead."))
720 (add-hook 'pre-command-hook 'company-pre-command nil t)
721 (add-hook 'post-command-hook 'company-post-command nil t)
722 (mapc 'company-init-backend company-backends))
723 (remove-hook 'pre-command-hook 'company-pre-command t)
724 (remove-hook 'post-command-hook 'company-post-command t)
726 (kill-local-variable 'company-point)))
728 (defcustom company-global-modes t
729 "Modes for which `company-mode' mode is turned on by `global-company-mode'.
730 If nil, means no modes. If t, then all major modes have it turned on.
731 If a list, it should be a list of `major-mode' symbol names for which
732 `company-mode' should be automatically turned on. The sense of the list is
733 negated if it begins with `not'. For example:
735 means that `company-mode' is turned on for buffers in C and C++ modes only.
737 means that `company-mode' is always turned on except in `message-mode' buffers."
738 :type '(choice (const :tag "none" nil)
740 (set :menu-tag "mode specific" :tag "modes"
742 (const :tag "Except" not)
743 (repeat :inline t (symbol :tag "mode")))))
746 (define-globalized-minor-mode global-company-mode company-mode company-mode-on)
748 (defun company-mode-on ()
749 (when (and (not (or noninteractive (eq (aref (buffer-name) 0) ?\s)))
750 (cond ((eq company-global-modes t)
752 ((eq (car-safe company-global-modes) 'not)
753 (not (memq major-mode (cdr company-global-modes))))
754 (t (memq major-mode company-global-modes))))
757 (defsubst company-assert-enabled ()
759 (company-uninstall-map)
760 (error "Company not enabled")))
762 ;;; keymaps ;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;
764 (defvar-local company-my-keymap nil)
766 (defvar company-emulation-alist '((t . nil)))
768 (defsubst company-enable-overriding-keymap (keymap)
769 (company-uninstall-map)
770 (setq company-my-keymap keymap))
772 (defun company-ensure-emulation-alist ()
773 (unless (eq 'company-emulation-alist (car emulation-mode-map-alists))
774 (setq emulation-mode-map-alists
775 (cons 'company-emulation-alist
776 (delq 'company-emulation-alist emulation-mode-map-alists)))))
778 (defun company-install-map ()
779 (unless (or (cdar company-emulation-alist)
780 (null company-my-keymap))
781 (setf (cdar company-emulation-alist) company-my-keymap)))
783 (defun company-uninstall-map ()
784 (setf (cdar company-emulation-alist) nil))
787 ;; Emacs calculates the active keymaps before reading the event. That means we
788 ;; cannot change the keymap from a timer. So we send a bogus command.
789 ;; XXX: Even in Emacs 24.4, seems to be needed in the terminal.
790 (defun company-ignore ()
792 (setq this-command last-command))
794 (global-set-key '[company-dummy-event] 'company-ignore)
796 (defun company-input-noop ()
797 (push 'company-dummy-event unread-command-events))
799 (defun company--posn-col-row (posn)
800 (let ((col (car (posn-col-row posn)))
801 ;; `posn-col-row' doesn't work well with lines of different height.
802 ;; `posn-actual-col-row' doesn't handle multiple-width characters.
803 (row (cdr (posn-actual-col-row posn))))
804 (when (and header-line-format (version< emacs-version "24.3.93.3"))
805 ;; http://debbugs.gnu.org/18384
807 (cons (+ col (window-hscroll)) row)))
809 (defun company--col-row (&optional pos)
810 (company--posn-col-row (posn-at-point pos)))
812 (defun company--row (&optional pos)
813 (cdr (company--col-row pos)))
815 ;;; backends ;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;
817 (defvar-local company-backend nil)
819 (defun company-grab (regexp &optional expression limit)
820 (when (looking-back regexp limit)
821 (or (match-string-no-properties (or expression 0)) "")))
823 (defun company-grab-line (regexp &optional expression)
824 (company-grab regexp expression (point-at-bol)))
826 (defun company-grab-symbol ()
827 (if (looking-at "\\_>")
828 (buffer-substring (point) (save-excursion (skip-syntax-backward "w_")
830 (unless (and (char-after) (memq (char-syntax (char-after)) '(?w ?_)))
833 (defun company-grab-word ()
834 (if (looking-at "\\>")
835 (buffer-substring (point) (save-excursion (skip-syntax-backward "w")
837 (unless (and (char-after) (eq (char-syntax (char-after)) ?w))
840 (defun company-grab-symbol-cons (idle-begin-after-re &optional max-len)
841 (let ((symbol (company-grab-symbol)))
844 (forward-char (- (length symbol)))
845 (if (looking-back idle-begin-after-re (if max-len
847 (line-beginning-position)))
851 (defun company-in-string-or-comment ()
852 (let ((ppss (syntax-ppss)))
853 (or (car (setq ppss (nthcdr 3 ppss)))
854 (car (setq ppss (cdr ppss)))
857 (defun company-call-backend (&rest args)
858 (company--force-sync #'company-call-backend-raw args company-backend))
860 (defun company--force-sync (fun args backend)
861 (let ((value (apply fun args)))
862 (if (not (eq (car-safe value) :async))
865 (start (time-to-seconds)))
867 (lambda (result) (setq res result)))
868 (while (eq res 'trash)
869 (if (> (- (time-to-seconds) start) company-async-timeout)
870 (error "Company: Back-end %s async timeout with args %s"
872 (sleep-for company-async-wait)))
875 (defun company-call-backend-raw (&rest args)
876 (condition-case-unless-debug err
877 (if (functionp company-backend)
878 (apply company-backend args)
879 (apply #'company--multi-backend-adapter company-backend args))
880 (error (error "Company: Back-end %s error \"%s\" with args %s"
881 company-backend (error-message-string err) args))))
883 (defun company--multi-backend-adapter (backends command &rest args)
884 (let ((backends (cl-loop for b in backends
885 when (not (and (symbolp b)
886 (eq 'failed (get b 'company-init))))
889 (if (eq command 'prefix)
890 (butlast backends (length (member :with backends)))
891 (delq :with backends)))
894 (company--multi-backend-adapter-candidates backends (car args)))
897 ((or `prefix `ignore-case `no-cache `require-match)
899 (cl-dolist (backend backends)
900 (when (setq value (company--force-sync
901 backend (cons command args) backend))
902 (cl-return value)))))
904 (let ((arg (car args)))
905 (when (> (length arg) 0)
906 (let ((backend (or (get-text-property 0 'company-backend arg)
908 (apply backend command args))))))))
910 (defun company--multi-backend-adapter-candidates (backends prefix)
911 (let ((pairs (cl-loop for backend in (cdr backends)
912 when (equal (company--prefix-str
913 (funcall backend 'prefix))
915 collect (cons (funcall backend 'candidates prefix)
920 (propertize str 'company-backend b))
922 (when (equal (company--prefix-str (funcall (car backends) 'prefix)) prefix)
923 ;; Small perf optimization: don't tag the candidates received
924 ;; from the first backend in the group.
925 (push (cons (funcall (car backends) 'candidates prefix)
928 (company--merge-async pairs (lambda (values) (apply #'append values)))))
930 (defun company--merge-async (pairs merger)
931 (let ((async (cl-loop for pair in pairs
933 (eq :async (car-safe (car pair))))))
935 (funcall merger (cl-loop for (val . mapper) in pairs
936 collect (funcall mapper val)))
941 (pending (mapcar #'car pairs))
952 (this-finisher (lambda (res)
953 (setq pending (delq val pending))
954 (setcar cell (funcall mapper res))
955 (funcall finisher))))
956 (if (not (eq :async (car-safe val)))
957 (funcall this-finisher val)
958 (let ((fetcher (cdr val)))
959 (funcall fetcher this-finisher)))))))))))
961 (defun company--prefix-str (prefix)
962 (or (car-safe prefix) prefix))
964 ;;; completion mechanism ;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;
966 (defvar-local company-prefix nil)
968 (defvar-local company-candidates nil)
970 (defvar-local company-candidates-length nil)
972 (defvar-local company-candidates-cache nil)
974 (defvar-local company-candidates-predicate nil)
976 (defvar-local company-common nil)
978 (defvar-local company-selection 0)
980 (defvar-local company-selection-changed nil)
982 (defvar-local company--manual-action nil
983 "Non-nil, if manual completion took place.")
985 (defvar-local company--manual-prefix nil)
987 (defvar company--auto-completion nil
988 "Non-nil when current candidate is being inserted automatically.
989 Controlled by `company-auto-complete'.")
991 (defvar-local company--point-max nil)
993 (defvar-local company-point nil)
995 (defvar company-timer nil)
997 (defsubst company-strip-prefix (str)
998 (substring str (length company-prefix)))
1000 (defun company--insert-candidate (candidate)
1001 (setq candidate (substring-no-properties candidate))
1002 ;; XXX: Return value we check here is subject to change.
1003 (if (eq (company-call-backend 'ignore-case) 'keep-prefix)
1004 (insert (company-strip-prefix candidate))
1005 (unless (equal company-prefix candidate)
1006 (delete-region (- (point) (length company-prefix)) (point))
1007 (insert candidate))))
1009 (defmacro company-with-candidate-inserted (candidate &rest body)
1010 "Evaluate BODY with CANDIDATE temporarily inserted.
1011 This is a tool for back-ends that need candidates inserted before they
1012 can retrieve meta-data for them."
1013 (declare (indent 1))
1014 `(let ((inhibit-modification-hooks t)
1015 (inhibit-point-motion-hooks t)
1016 (modified-p (buffer-modified-p)))
1017 (company--insert-candidate ,candidate)
1020 (delete-region company-point (point))
1021 (set-buffer-modified-p modified-p))))
1023 (defun company-explicit-action-p ()
1024 "Return whether explicit completion action was taken by the user."
1025 (or company--manual-action
1026 company-selection-changed))
1028 (defun company-reformat (candidate)
1029 ;; company-ispell needs this, because the results are always lower-case
1030 ;; It's mory efficient to fix it only when they are displayed.
1031 ;; FIXME: Adopt the current text's capitalization instead?
1032 (if (eq (company-call-backend 'ignore-case) 'keep-prefix)
1033 (concat company-prefix (substring candidate (length company-prefix)))
1036 (defun company--should-complete ()
1037 (and (eq company-idle-delay 'now)
1038 (not (or buffer-read-only overriding-terminal-local-map
1039 overriding-local-map))
1040 ;; Check if in the middle of entering a key combination.
1041 (or (equal (this-command-keys-vector) [])
1042 (not (keymapp (key-binding (this-command-keys-vector)))))
1043 (not (and transient-mark-mode mark-active))))
1045 (defun company--should-continue ()
1046 (or (eq t company-begin-commands)
1047 (eq t company-continue-commands)
1048 (if (eq 'not (car company-continue-commands))
1049 (not (memq this-command (cdr company-continue-commands)))
1050 (or (memq this-command company-begin-commands)
1051 (memq this-command company-continue-commands)
1052 (and (symbolp this-command)
1053 (string-match-p "\\`company-" (symbol-name this-command)))))))
1055 (defun company-call-frontends (command)
1056 (dolist (frontend company-frontends)
1057 (condition-case-unless-debug err
1058 (funcall frontend command)
1059 (error (error "Company: Front-end %s error \"%s\" on command %s"
1060 frontend (error-message-string err) command)))))
1062 (defun company-set-selection (selection &optional force-update)
1064 (if company-selection-wrap-around
1065 (mod selection company-candidates-length)
1066 (max 0 (min (1- company-candidates-length) selection))))
1067 (when (or force-update (not (equal selection company-selection)))
1068 (setq company-selection selection
1069 company-selection-changed t)
1070 (company-call-frontends 'update)))
1072 (defun company--group-lighter (candidate base)
1073 (let ((backend (or (get-text-property 0 'company-backend candidate)
1074 (car company-backend))))
1075 (when (and backend (symbolp backend))
1076 (let ((name (replace-regexp-in-string "company-\\|-company" ""
1077 (symbol-name backend))))
1078 (format "%s-<%s>" base name)))))
1080 (defun company-update-candidates (candidates)
1081 (setq company-candidates-length (length candidates))
1082 (if company-selection-changed
1083 ;; Try to restore the selection
1084 (let ((selected (nth company-selection company-candidates)))
1085 (setq company-selection 0
1086 company-candidates candidates)
1090 (let ((candidate (pop candidates)))
1091 (when (and (string= candidate selected)
1092 (equal (company-call-backend 'annotation candidate)
1093 (company-call-backend 'annotation selected)))
1095 (cl-incf company-selection))
1096 (setq company-selection 0
1097 company-selection-changed nil))))
1098 (setq company-selection 0
1099 company-candidates candidates))
1100 ;; Calculate common.
1101 (let ((completion-ignore-case (company-call-backend 'ignore-case)))
1102 ;; We want to support non-prefix completion, so filtering is the
1103 ;; responsibility of each respective backend, not ours.
1104 ;; On the other hand, we don't want to replace non-prefix input in
1105 ;; `company-complete-common', unless there's only one candidate.
1106 (setq company-common
1107 (if (cdr company-candidates)
1108 (let ((common (try-completion "" company-candidates)))
1109 (when (string-prefix-p company-prefix common
1110 completion-ignore-case)
1112 (car company-candidates)))))
1114 (defun company-calculate-candidates (prefix)
1115 (let ((candidates (cdr (assoc prefix company-candidates-cache)))
1116 (ignore-case (company-call-backend 'ignore-case)))
1118 (when company-candidates-cache
1119 (let ((len (length prefix))
1120 (completion-ignore-case ignore-case)
1122 (cl-dotimes (i (1+ len))
1123 (when (setq prev (cdr (assoc (substring prefix 0 (- len i))
1124 company-candidates-cache)))
1125 (setq candidates (all-completions prefix prev))
1128 ;; No cache match, call the backend.
1129 (setq candidates (company--preprocess-candidates
1130 (company--fetch-candidates prefix)))
1132 (push (cons prefix candidates) company-candidates-cache)))
1133 ;; Only now apply the predicate and transformers.
1134 (setq candidates (company--postprocess-candidates candidates))
1136 (if (or (cdr candidates)
1137 (not (eq t (compare-strings (car candidates) nil nil
1138 prefix nil nil ignore-case))))
1140 ;; Already completed and unique; don't start.
1143 (defun company--fetch-candidates (prefix)
1144 (let ((c (if company--manual-action
1145 (company-call-backend 'candidates prefix)
1146 (company-call-backend-raw 'candidates prefix)))
1148 (if (not (eq (car c) :async))
1150 (let ((buf (current-buffer))
1151 (win (selected-window))
1152 (tick (buffer-chars-modified-tick))
1154 (backend company-backend))
1157 (lambda (candidates)
1158 (if (not (and candidates (eq res 'done)))
1159 ;; There's no completions to display,
1160 ;; or the fetcher called us back right away.
1161 (setq res candidates)
1162 (setq company-backend backend
1163 company-candidates-cache
1165 (company--preprocess-candidates candidates))))
1166 (company-idle-begin buf win tick pt)))))
1167 ;; FIXME: Relying on the fact that the callers
1168 ;; will interpret nil as "do nothing" is shaky.
1169 ;; A throw-catch would be one possible improvement.
1171 (progn (setq res 'done) nil)))))
1173 (defun company--preprocess-candidates (candidates)
1174 (unless (company-call-backend 'sorted)
1175 (setq candidates (sort candidates 'string<)))
1176 (when (company-call-backend 'duplicates)
1177 (company--strip-duplicates candidates))
1180 (defun company--postprocess-candidates (candidates)
1181 (when (or company-candidates-predicate company-transformers)
1182 (setq candidates (copy-sequence candidates)))
1183 (when company-candidates-predicate
1184 (setq candidates (cl-delete-if-not company-candidates-predicate candidates)))
1185 (company--transform-candidates candidates))
1187 (defun company--strip-duplicates (candidates)
1188 (let ((c2 candidates)
1192 (let ((str (pop c2)))
1193 (while (let ((str2 (car c2)))
1194 (if (not (equal str str2))
1198 (when (eq annos 'unk)
1199 (setq annos (list (company-call-backend
1201 (let ((anno2 (company-call-backend
1203 (if (member anno2 annos)
1210 (defun company--transform-candidates (candidates)
1211 (let ((c candidates))
1212 (dolist (tr company-transformers)
1213 (setq c (funcall tr c)))
1216 (defcustom company-occurrence-weight-function
1217 #'company-occurrence-prefer-closest-above
1218 "Function to weigh matches in `company-sort-by-occurrence'.
1219 It's called with three arguments: cursor position, the beginning and the
1222 (const :tag "First above point, then below point"
1223 company-occurrence-prefer-closest-above)
1224 (const :tag "Prefer closest in any direction"
1225 company-occurrence-prefer-any-closest)))
1227 (defun company-occurrence-prefer-closest-above (pos match-beg match-end)
1228 "Give priority to the matches above point, then those below point."
1229 (if (< match-beg pos)
1231 (- match-beg (window-start))))
1233 (defun company-occurrence-prefer-any-closest (pos _match-beg match-end)
1234 "Give priority to the matches closest to the point."
1235 (abs (- pos match-end)))
1237 (defun company-sort-by-occurrence (candidates)
1238 "Sort CANDIDATES according to their occurrences.
1239 Searches for each in the currently visible part of the current buffer and
1240 prioritizes the matches according to `company-occurrence-weight-function'.
1241 The rest of the list is appended unchanged.
1242 Keywords and function definition names are ignored."
1243 (let* ((w-start (window-start))
1244 (w-end (window-end))
1245 (start-point (point))
1253 (while (search-forward candidate w-end t)
1254 (when (and (not (eq (point) start-point))
1256 (company--occurrence-predicate)))
1260 (funcall company-occurrence-weight-function
1268 (mapcar #'car (sort occurs (lambda (e1 e2) (<= (cdr e1) (cdr e2)))))
1271 (defun company--occurrence-predicate ()
1272 (let ((beg (match-beginning 0))
1273 (end (match-end 0)))
1276 (and (not (memq (get-text-property (1- (point)) 'face)
1277 '(font-lock-function-name-face
1278 font-lock-keyword-face)))
1279 (let ((prefix (company--prefix-str
1280 (company-call-backend 'prefix))))
1281 (and (stringp prefix)
1282 (= (length prefix) (- end beg))))))))
1284 (defun company-sort-by-backend-importance (candidates)
1285 "Sort CANDIDATES as two priority groups.
1286 If `company-backend' is a function, do nothing. If it's a list, move
1287 candidates from back-ends before keyword `:with' to the front. Candidates
1288 from the rest of the back-ends in the group, if any, will be left at the end."
1289 (if (functionp company-backend)
1291 (let ((low-priority (cdr (memq :with company-backend))))
1292 (if (null low-priority)
1297 (let ((b2 (get-text-property 0 'company-backend c2)))
1298 (and b2 (memq b2 low-priority)))
1299 (let ((b1 (get-text-property 0 'company-backend c1)))
1300 (or (not b1) (not (memq b1 low-priority)))))))))))
1302 (defun company-idle-begin (buf win tick pos)
1303 (and (eq buf (current-buffer))
1304 (eq win (selected-window))
1305 (eq tick (buffer-chars-modified-tick))
1307 (when (company-auto-begin)
1308 (company-input-noop)
1309 (let ((this-command 'company-idle-begin))
1310 (company-post-command)))))
1312 (defun company-auto-begin ()
1314 (not company-candidates)
1315 (let ((company-idle-delay 'now))
1316 (condition-case-unless-debug err
1319 ;; Return non-nil if active.
1321 (error (message "Company: An error occurred in auto-begin")
1322 (message "%s" (error-message-string err))
1324 (quit (company-cancel))))))
1326 (defun company-manual-begin ()
1328 (company-assert-enabled)
1329 (setq company--manual-action t)
1331 (let ((company-minimum-prefix-length 0))
1332 (or company-candidates
1333 (company-auto-begin)))
1334 (unless company-candidates
1335 (setq company--manual-action nil))))
1337 (defun company-other-backend (&optional backward)
1338 (interactive (list current-prefix-arg))
1339 (company-assert-enabled)
1340 (let* ((after (if company-backend
1341 (cdr (member company-backend company-backends))
1343 (before (cdr (member company-backend (reverse company-backends))))
1345 (append before (reverse after))
1346 (append after (reverse before)))))
1348 (cl-dolist (backend next)
1349 (when (ignore-errors (company-begin-backend backend))
1351 (unless company-candidates
1352 (error "No other back-end")))
1354 (defun company-require-match-p ()
1355 (let ((backend-value (company-call-backend 'require-match)))
1356 (or (eq backend-value t)
1357 (and (not (eq backend-value 'never))
1358 (if (functionp company-require-match)
1359 (funcall company-require-match)
1360 (eq company-require-match t))))))
1362 (defun company-auto-complete-p (input)
1363 "Return non-nil, if input starts with punctuation or parentheses."
1364 (and (if (functionp company-auto-complete)
1365 (funcall company-auto-complete)
1366 company-auto-complete)
1367 (if (functionp company-auto-complete-chars)
1368 (funcall company-auto-complete-chars input)
1369 (if (consp company-auto-complete-chars)
1370 (memq (char-syntax (string-to-char input))
1371 company-auto-complete-chars)
1372 (string-match (substring input 0 1) company-auto-complete-chars)))))
1374 (defun company--incremental-p ()
1375 (and (> (point) company-point)
1376 (> (point-max) company--point-max)
1377 (not (eq this-command 'backward-delete-char-untabify))
1378 (equal (buffer-substring (- company-point (length company-prefix))
1382 (defun company--continue-failed (new-prefix)
1383 (let ((input (buffer-substring-no-properties (point) company-point)))
1385 ((company-auto-complete-p input)
1388 (goto-char company-point)
1389 (let ((company--auto-completion t))
1390 (company-complete-selection))
1392 ((and (or (not (company-require-match-p))
1393 ;; Don't require match if the new prefix
1394 ;; doesn't continue the old one, and the latter was a match.
1395 (not (stringp new-prefix))
1396 (<= (length new-prefix) (length company-prefix)))
1397 (member company-prefix company-candidates))
1398 ;; Last input was a success,
1399 ;; but we're treating it as an abort + input anyway,
1400 ;; like the `unique' case below.
1401 (company-cancel 'non-unique))
1402 ((company-require-match-p)
1403 ;; Wrong incremental input, but required match.
1404 (delete-char (- (length input)))
1406 (message "Matching input is required")
1408 (t (company-cancel)))))
1410 (defun company--good-prefix-p (prefix)
1411 (and (stringp (company--prefix-str prefix)) ;excludes 'stop
1412 (or (eq (cdr-safe prefix) t)
1413 (let ((len (or (cdr-safe prefix) (length prefix))))
1414 (if company--manual-prefix
1415 (or (not company-abort-manual-when-too-short)
1416 ;; Must not be less than minimum or initial length.
1417 (>= len (min company-minimum-prefix-length
1418 (length company--manual-prefix))))
1419 (>= len company-minimum-prefix-length))))))
1421 (defun company--continue ()
1422 (when (company-call-backend 'no-cache company-prefix)
1423 ;; Don't complete existing candidates, fetch new ones.
1424 (setq company-candidates-cache nil))
1425 (let* ((new-prefix (company-call-backend 'prefix))
1426 (c (when (and (company--good-prefix-p new-prefix)
1427 (setq new-prefix (company--prefix-str new-prefix))
1428 (= (- (point) (length new-prefix))
1429 (- company-point (length company-prefix))))
1430 (company-calculate-candidates new-prefix))))
1433 ;; t means complete/unique.
1434 ;; Handle it like completion was aborted, to differentiate from user
1435 ;; calling one of Company's commands to insert the candidate,
1436 ;; not to trigger template expansion, etc.
1437 (company-cancel 'unique))
1439 ;; incremental match
1440 (setq company-prefix new-prefix)
1441 (company-update-candidates c)
1443 ((not (company--incremental-p))
1445 (t (company--continue-failed new-prefix)))))
1447 (defun company--begin-new ()
1449 (cl-dolist (backend (if company-backend
1450 ;; prefer manual override
1451 (list company-backend)
1454 (if (or (symbolp backend)
1455 (functionp backend))
1456 (when (or (not (symbolp backend))
1457 (eq t (get backend 'company-init))
1458 (unless (get backend 'company-init)
1459 (company-init-backend backend)))
1460 (funcall backend 'prefix))
1461 (company--multi-backend-adapter backend 'prefix)))
1463 (when (company--good-prefix-p prefix)
1464 (setq company-prefix (company--prefix-str prefix)
1465 company-backend backend
1466 c (company-calculate-candidates company-prefix))
1467 ;; t means complete/unique. We don't start, so no hooks.
1469 (when company--manual-action
1470 (message "No completion found"))
1471 (when company--manual-action
1472 (setq company--manual-prefix prefix))
1473 (company-update-candidates c)
1474 (run-hook-with-args 'company-completion-started-hook
1475 (company-explicit-action-p))
1476 (company-call-frontends 'show)))
1479 (defun company--perform ()
1480 (or (and company-candidates (company--continue))
1481 (and (company--should-complete) (company--begin-new)))
1482 (if (not company-candidates)
1483 (setq company-backend nil)
1484 (setq company-point (point)
1485 company--point-max (point-max))
1486 (company-ensure-emulation-alist)
1487 (company-enable-overriding-keymap company-active-map)
1488 (company-call-frontends 'update)))
1490 (defun company-cancel (&optional result)
1492 (when company-prefix
1493 (if (stringp result)
1495 (company-call-backend 'pre-completion result)
1496 (run-hook-with-args 'company-completion-finished-hook result)
1497 (company-call-backend 'post-completion result))
1498 (run-hook-with-args 'company-completion-cancelled-hook result)))
1499 (setq company-backend nil
1501 company-candidates nil
1502 company-candidates-length nil
1503 company-candidates-cache nil
1504 company-candidates-predicate nil
1507 company-selection-changed nil
1508 company--manual-action nil
1509 company--manual-prefix nil
1510 company--point-max nil
1513 (cancel-timer company-timer))
1514 (company-search-mode 0)
1515 (company-call-frontends 'hide)
1516 (company-enable-overriding-keymap nil))
1517 ;; Make return value explicit.
1520 (defun company-abort ()
1522 (company-cancel 'abort))
1524 (defun company-finish (result)
1525 (company--insert-candidate result)
1526 (company-cancel result))
1528 (defsubst company-keep (command)
1529 (and (symbolp command) (get command 'company-keep)))
1531 (defun company-pre-command ()
1532 (unless (company-keep this-command)
1533 (condition-case-unless-debug err
1534 (when company-candidates
1535 (company-call-frontends 'pre-command)
1536 (unless (company--should-continue)
1538 (error (message "Company: An error occurred in pre-command")
1539 (message "%s" (error-message-string err))
1542 (cancel-timer company-timer)
1543 (setq company-timer nil))
1544 (company-uninstall-map))
1546 (defun company-post-command ()
1547 (when (null this-command)
1548 ;; Happens when the user presses `C-g' while inside
1549 ;; `flyspell-post-command-hook', for example.
1550 ;; Or any other `post-command-hook' function that can call `sit-for',
1551 ;; or any quittable timer function.
1553 (setq this-command 'company-abort))
1554 (unless (company-keep this-command)
1555 (condition-case-unless-debug err
1557 (unless (equal (point) company-point)
1558 (let (company-idle-delay) ; Against misbehavior while debugging.
1559 (company--perform)))
1560 (if company-candidates
1561 (company-call-frontends 'post-command)
1562 (and (numberp company-idle-delay)
1563 (company--should-begin)
1565 (run-with-timer company-idle-delay nil
1567 (current-buffer) (selected-window)
1568 (buffer-chars-modified-tick) (point))))))
1569 (error (message "Company: An error occurred in post-command")
1570 (message "%s" (error-message-string err))
1572 (company-install-map))
1574 (defvar company--begin-inhibit-commands '(company-abort
1575 company-complete-mouse
1577 company-complete-common
1578 company-complete-selection
1579 company-complete-number)
1580 "List of commands after which idle completion is (still) disabled when
1581 `company-begin-commands' is t.")
1583 (defun company--should-begin ()
1584 (if (eq t company-begin-commands)
1585 (not (memq this-command company--begin-inhibit-commands))
1587 (memq this-command company-begin-commands)
1588 (and (symbolp this-command) (get this-command 'company-begin)))))
1590 ;;; search ;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;
1592 (defvar-local company-search-string "")
1594 (defvar company-search-lighter '(" "
1595 (company-search-filtering "Filter" "Search")
1597 company-search-string
1600 (defvar-local company-search-filtering nil
1601 "Non-nil to filter the completion candidates by the search string")
1603 (defvar-local company--search-old-selection 0)
1605 (defvar-local company--search-old-changed nil)
1607 (defun company--search (text lines)
1608 (let ((quoted (regexp-quote text))
1610 (cl-dolist (line lines)
1611 (when (string-match quoted line (length company-prefix))
1615 (defun company-search-keypad ()
1617 (let* ((name (symbol-name last-command-event))
1618 (last-command-event (aref name (1- (length name)))))
1619 (company-search-printing-char)))
1621 (defun company-search-printing-char ()
1623 (company--search-assert-enabled)
1624 (let ((ss (concat company-search-string (string last-command-event))))
1625 (when company-search-filtering
1626 (company--search-update-predicate ss))
1627 (company--search-update-string ss)))
1629 (defun company--search-update-predicate (&optional ss)
1630 (let* ((company-candidates-predicate
1631 (and (not (string= ss ""))
1632 company-search-filtering
1633 (lambda (candidate) (string-match ss candidate))))
1634 (cc (company-calculate-candidates company-prefix)))
1635 (unless cc (error "No match"))
1636 (company-update-candidates cc)))
1638 (defun company--search-update-string (new)
1639 (let* ((pos (company--search new (nthcdr company-selection company-candidates))))
1642 (setq company-search-string new)
1643 (company-set-selection (+ company-selection pos) t))))
1645 (defun company--search-assert-input ()
1646 (company--search-assert-enabled)
1647 (when (string= company-search-string "")
1648 (error "Empty search string")))
1650 (defun company-search-repeat-forward ()
1651 "Repeat the incremental search in completion candidates forward."
1653 (company--search-assert-input)
1654 (let ((pos (company--search company-search-string
1655 (cdr (nthcdr company-selection
1656 company-candidates)))))
1659 (company-set-selection (+ company-selection pos 1) t))))
1661 (defun company-search-repeat-backward ()
1662 "Repeat the incremental search in completion candidates backwards."
1664 (company--search-assert-input)
1665 (let ((pos (company--search company-search-string
1666 (nthcdr (- company-candidates-length
1668 (reverse company-candidates)))))
1671 (company-set-selection (- company-selection pos 1) t))))
1673 (defun company-search-toggle-filtering ()
1674 "Toggle `company-search-filtering'."
1676 (company--search-assert-enabled)
1677 (setq company-search-filtering (not company-search-filtering))
1678 (let ((ss company-search-string))
1679 (company--search-update-predicate ss)
1680 (company--search-update-string ss)))
1682 (defun company-search-abort ()
1683 "Abort searching the completion candidates."
1685 (company--search-assert-enabled)
1686 (company-search-mode 0)
1687 (company-set-selection company--search-old-selection t)
1688 (setq company-selection-changed company--search-old-changed))
1690 (defun company-search-other-char ()
1692 (company--search-assert-enabled)
1693 (company-search-mode 0)
1694 (company--unread-last-input))
1696 (defun company-search-delete-char ()
1698 (company--search-assert-enabled)
1699 (if (string= company-search-string "")
1701 (let ((ss (substring company-search-string 0 -1)))
1702 (when company-search-filtering
1703 (company--search-update-predicate ss))
1704 (company--search-update-string ss))))
1706 (defvar company-search-map
1708 (keymap (make-keymap)))
1709 (if (fboundp 'max-char)
1710 (set-char-table-range (nth 1 keymap) (cons #x100 (max-char))
1711 'company-search-printing-char)
1713 ;; obsolete in Emacs 23
1714 (let ((l (generic-character-list))
1715 (table (nth 1 keymap)))
1717 (set-char-table-default table (car l) 'company-search-printing-char)
1718 (setq l (cdr l))))))
1719 (define-key keymap [t] 'company-search-other-char)
1721 (define-key keymap (make-string 1 i) 'company-search-other-char)
1724 (define-key keymap (vector i) 'company-search-printing-char)
1727 (define-key keymap (read (format "[kp-%s]" i)) 'company-search-keypad))
1728 (let ((meta-map (make-sparse-keymap)))
1729 (define-key keymap (char-to-string meta-prefix-char) meta-map)
1730 (define-key keymap [escape] meta-map))
1731 (define-key keymap (vector meta-prefix-char t) 'company-search-other-char)
1732 (define-key keymap (kbd "M-n") 'company-select-next)
1733 (define-key keymap (kbd "M-p") 'company-select-previous)
1734 (define-key keymap (kbd "<down>") 'company-select-next-or-abort)
1735 (define-key keymap (kbd "<up>") 'company-select-previous-or-abort)
1736 (define-key keymap "\e\e\e" 'company-search-other-char)
1737 (define-key keymap [escape escape escape] 'company-search-other-char)
1738 (define-key keymap (kbd "DEL") 'company-search-delete-char)
1739 (define-key keymap [backspace] 'company-search-delete-char)
1740 (define-key keymap "\C-g" 'company-search-abort)
1741 (define-key keymap "\C-s" 'company-search-repeat-forward)
1742 (define-key keymap "\C-r" 'company-search-repeat-backward)
1743 (define-key keymap "\C-o" 'company-search-toggle-filtering)
1745 (define-key keymap (read-kbd-macro (format "M-%d" i)) 'company-complete-number))
1747 "Keymap used for incrementally searching the completion candidates.")
1749 (define-minor-mode company-search-mode
1750 "Search mode for completion candidates.
1751 Don't start this directly, use `company-search-candidates' or
1752 `company-filter-candidates'."
1753 nil company-search-lighter nil
1754 (if company-search-mode
1755 (if (company-manual-begin)
1757 (setq company--search-old-selection company-selection
1758 company--search-old-changed company-selection-changed)
1759 (company-call-frontends 'update)
1760 (company-enable-overriding-keymap company-search-map))
1761 (setq company-search-mode nil))
1762 (kill-local-variable 'company-search-string)
1763 (kill-local-variable 'company-search-filtering)
1764 (kill-local-variable 'company--search-old-selection)
1765 (kill-local-variable 'company--search-old-changed)
1766 (when company-backend
1767 (company--search-update-predicate "")
1768 (company-call-frontends 'update))
1769 (company-enable-overriding-keymap company-active-map)))
1771 (defun company--search-assert-enabled ()
1772 (company-assert-enabled)
1773 (unless company-search-mode
1774 (company-uninstall-map)
1775 (error "Company not in search mode")))
1777 (defun company-search-candidates ()
1778 "Start searching the completion candidates incrementally.
1780 \\<company-search-map>Search can be controlled with the commands:
1781 - `company-search-repeat-forward' (\\[company-search-repeat-forward])
1782 - `company-search-repeat-backward' (\\[company-search-repeat-backward])
1783 - `company-search-abort' (\\[company-search-abort])
1784 - `company-search-delete-char' (\\[company-search-delete-char])
1786 Regular characters are appended to the search string.
1788 The command `company-search-toggle-filtering' (\\[company-search-toggle-filtering])
1789 uses the search string to filter the completion candidates."
1791 (company-search-mode 1))
1793 (defvar company-filter-map
1794 (let ((keymap (make-keymap)))
1795 (define-key keymap [remap company-search-printing-char]
1796 'company-filter-printing-char)
1797 (set-keymap-parent keymap company-search-map)
1799 "Keymap used for incrementally searching the completion candidates.")
1801 (defun company-filter-candidates ()
1802 "Start filtering the completion candidates incrementally.
1803 This works the same way as `company-search-candidates' immediately
1804 followed by `company-search-toggle-filtering'."
1806 (company-search-mode 1)
1807 (setq company-search-filtering t))
1809 ;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;
1811 (defun company-select-next ()
1812 "Select the next candidate in the list."
1814 (when (company-manual-begin)
1815 (company-set-selection (1+ company-selection))))
1817 (defun company-select-previous ()
1818 "Select the previous candidate in the list."
1820 (when (company-manual-begin)
1821 (company-set-selection (1- company-selection))))
1823 (defun company-select-next-or-abort ()
1824 "Select the next candidate if more than one, else abort
1825 and invoke the normal binding."
1827 (if (> company-candidates-length 1)
1828 (company-select-next)
1830 (company--unread-last-input)))
1832 (defun company-select-previous-or-abort ()
1833 "Select the previous candidate if more than one, else abort
1834 and invoke the normal binding."
1836 (if (> company-candidates-length 1)
1837 (company-select-previous)
1839 (company--unread-last-input)))
1841 (defun company-next-page ()
1842 "Select the candidate one page further."
1844 (when (company-manual-begin)
1845 (company-set-selection (+ company-selection
1846 company-tooltip-limit))))
1848 (defun company-previous-page ()
1849 "Select the candidate one page earlier."
1851 (when (company-manual-begin)
1852 (company-set-selection (- company-selection
1853 company-tooltip-limit))))
1855 (defvar company-pseudo-tooltip-overlay)
1857 (defvar company-tooltip-offset)
1859 (defun company--inside-tooltip-p (event-col-row row height)
1860 (let* ((ovl company-pseudo-tooltip-overlay)
1861 (column (overlay-get ovl 'company-column))
1862 (width (overlay-get ovl 'company-width))
1863 (evt-col (car event-col-row))
1864 (evt-row (cdr event-col-row)))
1865 (and (>= evt-col column)
1866 (< evt-col (+ column width))
1868 (and (> evt-row row)
1869 (<= evt-row (+ row height) ))
1870 (and (< evt-row row)
1871 (>= evt-row (+ row height)))))))
1873 (defun company--event-col-row (event)
1874 (company--posn-col-row (event-start event)))
1876 (defun company-select-mouse (event)
1877 "Select the candidate picked by the mouse."
1879 (let ((event-col-row (company--event-col-row event))
1880 (ovl-row (company--row))
1881 (ovl-height (and company-pseudo-tooltip-overlay
1882 (min (overlay-get company-pseudo-tooltip-overlay
1884 company-candidates-length))))
1886 (company--inside-tooltip-p event-col-row ovl-row ovl-height))
1888 (company-set-selection (+ (cdr event-col-row)
1889 (1- company-tooltip-offset)
1890 (if (and (eq company-tooltip-offset-display 'lines)
1891 (not (zerop company-tooltip-offset)))
1894 (if (< ovl-height 0)
1899 (company--unread-last-input)
1902 (defun company-complete-mouse (event)
1903 "Insert the candidate picked by the mouse."
1905 (when (company-select-mouse event)
1906 (company-complete-selection)))
1908 (defun company-complete-selection ()
1909 "Insert the selected candidate."
1911 (when (company-manual-begin)
1912 (let ((result (nth company-selection company-candidates)))
1913 (company-finish result))))
1915 (defun company-complete-common ()
1916 "Insert the common part of all candidates."
1918 (when (company-manual-begin)
1919 (if (and (not (cdr company-candidates))
1920 (equal company-common (car company-candidates)))
1921 (company-complete-selection)
1922 (when company-common
1923 (company--insert-candidate company-common)))))
1925 (defun company-complete-common-or-cycle ()
1926 "Insert the common part of all candidates, or select the next one."
1928 (when (company-manual-begin)
1929 (let ((tick (buffer-chars-modified-tick)))
1930 (call-interactively 'company-complete-common)
1931 (when (eq tick (buffer-chars-modified-tick))
1932 (let ((company-selection-wrap-around t))
1933 (call-interactively 'company-select-next))))))
1935 (defun company-complete ()
1936 "Insert the common part of all candidates or the current selection.
1937 The first time this is called, the common part is inserted, the second
1938 time, or when the selection has been changed, the selected candidate is
1941 (when (company-manual-begin)
1942 (if (or company-selection-changed
1943 (eq last-command 'company-complete-common))
1944 (call-interactively 'company-complete-selection)
1945 (call-interactively 'company-complete-common)
1946 (setq this-command 'company-complete-common))))
1948 (defun company-complete-number (n)
1949 "Insert the Nth candidate visible in the tooltip.
1950 To show the number next to the candidates in some back-ends, enable
1951 `company-show-numbers'. When called interactively, uses the last typed
1952 character, stripping the modifiers. That character must be a digit."
1954 (list (let* ((type (event-basic-type last-command-event))
1955 (char (if (characterp type)
1956 ;; Number on the main row.
1958 ;; Keypad number, if bound directly.
1959 (car (last (string-to-list (symbol-name type))))))
1961 (if (zerop n) 10 n))))
1962 (when (company-manual-begin)
1963 (and (or (< n 1) (> n (- company-candidates-length
1964 company-tooltip-offset)))
1965 (error "No candidate number %d" n))
1967 (company-finish (nth (+ n company-tooltip-offset)
1968 company-candidates))))
1970 ;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;
1972 (defconst company-space-strings-limit 100)
1974 (defconst company-space-strings
1976 (dotimes (i company-space-strings-limit)
1977 (push (make-string (- company-space-strings-limit 1 i) ?\ ) lst))
1978 (apply 'vector lst)))
1980 (defun company-space-string (len)
1981 (if (< len company-space-strings-limit)
1982 (aref company-space-strings len)
1983 (make-string len ?\ )))
1985 (defun company-safe-substring (str from &optional to)
1986 (if (> from (string-width str))
1990 (move-to-column from)
1991 (let ((beg (point)))
1995 (concat (buffer-substring beg (point))
1996 (let ((padding (- to (current-column))))
1998 (company-space-string padding)))))
1999 (buffer-substring beg (point-max)))))))
2001 ;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;
2003 (defvar-local company-last-metadata nil)
2005 (defun company-fetch-metadata ()
2006 (let ((selected (nth company-selection company-candidates)))
2007 (unless (eq selected (car company-last-metadata))
2008 (setq company-last-metadata
2009 (cons selected (company-call-backend 'meta selected))))
2010 (cdr company-last-metadata)))
2012 (defun company-doc-buffer (&optional string)
2013 (with-current-buffer (get-buffer-create "*company-documentation*")
2020 (defvar company--electric-commands
2021 '(scroll-other-window scroll-other-window-down)
2022 "List of Commands that won't break out of electric commands.")
2024 (defmacro company--electric-do (&rest body)
2025 (declare (indent 0) (debug t))
2026 `(when (company-manual-begin)
2027 (save-window-excursion
2028 (let ((height (window-height))
2029 (row (company--row))
2032 (and (< (window-height) height)
2033 (< (- (window-height) row 2) company-tooltip-limit)
2034 (recenter (- (window-height) row 2)))
2035 (while (memq (setq cmd (key-binding (vector (list (read-event)))))
2036 company--electric-commands)
2037 (call-interactively cmd))
2038 (company--unread-last-input)))))
2040 (defun company--unread-last-input ()
2041 (when last-input-event
2042 (clear-this-command-keys t)
2043 (setq unread-command-events (list last-input-event))))
2045 (defun company-show-doc-buffer ()
2046 "Temporarily show the documentation buffer for the selection."
2048 (company--electric-do
2049 (let* ((selected (nth company-selection company-candidates))
2050 (doc-buffer (or (company-call-backend 'doc-buffer selected)
2051 (error "No documentation available"))))
2052 (with-current-buffer doc-buffer
2053 (goto-char (point-min)))
2054 (display-buffer doc-buffer t))))
2055 (put 'company-show-doc-buffer 'company-keep t)
2057 (defun company-show-location ()
2058 "Temporarily display a buffer showing the selected candidate in context."
2060 (company--electric-do
2061 (let* ((selected (nth company-selection company-candidates))
2062 (location (company-call-backend 'location selected))
2063 (pos (or (cdr location) (error "No location available")))
2064 (buffer (or (and (bufferp (car location)) (car location))
2065 (find-file-noselect (car location) t))))
2066 (with-selected-window (display-buffer buffer t)
2069 (if (bufferp (car location))
2071 (goto-char (point-min))
2072 (forward-line (1- pos))))
2073 (set-window-start nil (point))))))
2074 (put 'company-show-location 'company-keep t)
2076 ;;; package functions ;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;
2078 (defvar-local company-callback nil)
2080 (defun company-remove-callback (&optional ignored)
2081 (remove-hook 'company-completion-finished-hook company-callback t)
2082 (remove-hook 'company-completion-cancelled-hook 'company-remove-callback t)
2083 (remove-hook 'company-completion-finished-hook 'company-remove-callback t))
2085 (defun company-begin-backend (backend &optional callback)
2086 "Start a completion at point using BACKEND."
2087 (interactive (let ((val (completing-read "Company back-end: "
2089 'functionp nil "company-")))
2091 (list (intern val)))))
2092 (when (setq company-callback callback)
2093 (add-hook 'company-completion-finished-hook company-callback nil t))
2094 (add-hook 'company-completion-cancelled-hook 'company-remove-callback nil t)
2095 (add-hook 'company-completion-finished-hook 'company-remove-callback nil t)
2096 (setq company-backend backend)
2097 ;; Return non-nil if active.
2098 (or (company-manual-begin)
2099 (error "Cannot complete at point")))
2101 (defun company-begin-with (candidates
2102 &optional prefix-length require-match callback)
2103 "Start a completion at point.
2104 CANDIDATES is the list of candidates to use and PREFIX-LENGTH is the length
2105 of the prefix that already is in the buffer before point.
2108 CALLBACK is a function called with the selected result if the user
2109 successfully completes the input.
2111 Example: \(company-begin-with '\(\"foo\" \"foobar\" \"foobarbaz\"\)\)"
2112 (let ((begin-marker (copy-marker (point) t)))
2113 (company-begin-backend
2114 (lambda (command &optional arg &rest ignored)
2117 (when (equal (point) (marker-position begin-marker))
2118 (buffer-substring (- (point) (or prefix-length 0)) (point))))
2120 (all-completions arg candidates))
2125 (defun company-version (&optional show-version)
2126 "Get the Company version as string.
2128 If SHOW-VERSION is non-nil, show the version in the echo area."
2129 (interactive (list t))
2131 (insert-file-contents (find-library-name "company"))
2134 (message "Company version: %s" (lm-version))
2137 ;;; pseudo-tooltip ;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;
2139 (defvar-local company-pseudo-tooltip-overlay nil)
2141 (defvar-local company-tooltip-offset 0)
2143 (defun company-tooltip--lines-update-offset (selection num-lines limit)
2145 (setq company-tooltip-offset
2146 (max (min selection company-tooltip-offset)
2147 (- selection -1 limit)))
2149 (when (<= company-tooltip-offset 1)
2151 (setq company-tooltip-offset 0))
2153 (when (>= company-tooltip-offset (- num-lines limit 1))
2155 (when (= selection (1- num-lines))
2156 (cl-decf company-tooltip-offset)
2157 (when (<= company-tooltip-offset 1)
2158 (setq company-tooltip-offset 0)
2163 (defun company-tooltip--simple-update-offset (selection _num-lines limit)
2164 (setq company-tooltip-offset
2165 (if (< selection company-tooltip-offset)
2167 (max company-tooltip-offset
2168 (- selection limit -1)))))
2172 (defsubst company-round-tab (arg)
2173 (* (/ (+ arg tab-width) tab-width) tab-width))
2175 (defun company-plainify (str)
2176 (let ((prefix (get-text-property 0 'line-prefix str)))
2177 (when prefix ; Keep the original value unmodified, for no special reason.
2178 (setq str (concat prefix str))
2179 (remove-text-properties 0 (length str) '(line-prefix) str)))
2180 (let* ((pieces (split-string str "\t"))
2183 (setcar copy (company-safe-substring
2184 (car copy) 0 (company-round-tab (string-width (car copy)))))
2186 (apply 'concat pieces)))
2188 (defun company-fill-propertize (value annotation width selected left right)
2189 (let* ((margin (length left))
2190 (common (or (company-call-backend 'match value)
2192 (string-width company-common)
2194 (ann-ralign company-tooltip-align-annotations)
2195 (ann-truncate (< width
2196 (+ (length value) (length annotation)
2197 (if ann-ralign 1 0))))
2198 (ann-start (+ margin
2202 (- width (length annotation)))
2204 (ann-end (min (+ ann-start (length annotation)) (+ margin width)))
2206 (if (or ann-truncate (not ann-ralign))
2207 (company-safe-substring
2209 (when (and annotation ann-ralign) " ")
2213 (company-safe-substring value 0
2214 (- width (length annotation)))
2217 (setq common (+ (min common width) margin))
2218 (setq width (+ width margin (length right)))
2220 (add-text-properties 0 width '(face company-tooltip
2221 mouse-face company-tooltip-mouse)
2223 (add-text-properties margin common
2224 '(face company-tooltip-common
2225 mouse-face company-tooltip-mouse)
2227 (when (< ann-start ann-end)
2228 (add-text-properties ann-start ann-end
2229 '(face company-tooltip-annotation
2230 mouse-face company-tooltip-mouse)
2233 (if (and (not (string= company-search-string ""))
2234 (string-match (regexp-quote company-search-string) value
2235 (length company-prefix)))
2236 (let ((beg (+ margin (match-beginning 0)))
2237 (end (+ margin (match-end 0)))
2238 (width (- width (length right))))
2240 (add-text-properties beg (min end width)
2241 '(face company-tooltip-search)
2243 (add-text-properties 0 width '(face company-tooltip-selection
2244 mouse-face company-tooltip-selection)
2246 (add-text-properties margin common
2247 '(face company-tooltip-common-selection
2248 mouse-face company-tooltip-selection)
2252 (defun company--clean-string (str)
2253 (replace-regexp-in-string
2254 "\\([^[:graph:] ]\\)\\|\\(\ufeff\\)\\|[[:multibyte:]]"
2257 ((match-beginning 1)
2258 ;; FIXME: Better char for 'non-printable'?
2259 ;; We shouldn't get any of these, but sometimes we might.
2261 ((match-beginning 2)
2262 ;; Zero-width non-breakable space.
2264 ((> (string-width match) 1)
2266 (make-string (1- (string-width match)) ?\ufeff)
2273 (defun company-buffer-lines (beg end)
2275 (let (lines lines-moved)
2276 (while (and (not (eobp)) ; http://debbugs.gnu.org/19553
2277 (> (setq lines-moved (vertical-motion 1)) 0)
2279 (let ((bound (min end (1- (point)))))
2280 ;; A visual line can contain several physical lines (e.g. with outline's
2281 ;; folding overlay). Take only the first one.
2282 (push (buffer-substring beg
2285 (re-search-forward "$" bound 'move)
2288 ;; One physical line can be displayed as several visual ones as well:
2289 ;; add empty strings to the list, to even the count.
2290 (dotimes (_ (1- lines-moved))
2293 (unless (eq beg end)
2294 (push (buffer-substring beg end) lines))
2297 (defun company-modify-line (old new offset)
2298 (concat (company-safe-substring old 0 offset)
2300 (company-safe-substring old (+ offset (length new)))))
2302 (defsubst company--length-limit (lst limit)
2303 (if (nthcdr limit lst)
2307 (defsubst company--window-height ()
2308 (if (fboundp 'window-screen-lines)
2309 (floor (window-screen-lines))
2310 (window-body-height)))
2312 (defun company--window-width ()
2313 (let ((ww (window-body-width)))
2314 ;; Account for the line continuation column.
2315 (when (zerop (cadr (window-fringes)))
2317 (unless (or (display-graphic-p)
2318 (version< "24.3.1" emacs-version))
2319 ;; Emacs 24.3 and earlier included margins
2320 ;; in window-width when in TTY.
2322 (let ((margins (window-margins)))
2323 (+ (or (car margins) 0)
2324 (or (cdr margins) 0)))))
2325 (when (and word-wrap
2326 (version< emacs-version "24.4.51.5"))
2327 ;; http://debbugs.gnu.org/18384
2331 (defun company--replacement-string (lines old column nl &optional align-top)
2332 (cl-decf column company-tooltip-margin)
2334 (when (and align-top company-tooltip-flip-when-above)
2335 (setq lines (reverse lines)))
2337 (let ((width (length (car lines)))
2338 (remaining-cols (- (+ (company--window-width) (window-hscroll))
2340 (when (> width remaining-cols)
2341 (cl-decf column (- width remaining-cols))))
2343 (let ((offset (and (< column 0) (- column)))
2348 ;; untouched lines first
2349 (dotimes (_ (- (length old) (length lines)))
2350 (push (pop old) new)))
2351 ;; length into old lines.
2353 (push (company-modify-line (pop old)
2354 (company--offset-line (pop lines) offset)
2357 ;; Append whole new lines.
2359 (push (concat (company-space-string column)
2360 (company--offset-line (pop lines) offset))
2363 (let ((str (concat (when nl " ")
2365 (mapconcat 'identity (nreverse new) "\n")
2367 (font-lock-append-text-property 0 (length str) 'face 'default str)
2368 (when nl (put-text-property 0 1 'cursor t str))
2371 (defun company--offset-line (line offset)
2372 (if (and offset line)
2373 (substring line offset)
2376 (defun company--create-lines (selection limit)
2377 (let ((len company-candidates-length)
2378 (window-width (company--window-width))
2387 ;; Maybe clear old offset.
2388 (when (< len (+ company-tooltip-offset limit))
2389 (setq company-tooltip-offset 0))
2391 ;; Scroll to offset.
2392 (if (eq company-tooltip-offset-display 'lines)
2393 (setq limit (company-tooltip--lines-update-offset selection len limit))
2394 (company-tooltip--simple-update-offset selection len limit))
2397 ((eq company-tooltip-offset-display 'scrollbar)
2398 (setq scrollbar-bounds (company--scrollbar-bounds company-tooltip-offset
2400 ((eq company-tooltip-offset-display 'lines)
2401 (when (> company-tooltip-offset 0)
2402 (setq previous (format "...(%d)" company-tooltip-offset)))
2403 (setq remainder (- len limit company-tooltip-offset)
2404 remainder (when (> remainder 0)
2405 (setq remainder (format "...(%d)" remainder))))))
2407 (cl-decf selection company-tooltip-offset)
2408 (setq width (max (length previous) (length remainder))
2409 lines (nthcdr company-tooltip-offset company-candidates)
2413 (cl-decf window-width (* 2 company-tooltip-margin))
2414 (when scrollbar-bounds (cl-decf window-width))
2417 (let* ((value (pop lines-copy))
2418 (annotation (company-call-backend 'annotation value)))
2419 (setq value (company--clean-string (company-reformat value)))
2421 (when company-tooltip-align-annotations
2422 ;; `lisp-completion-at-point' adds a space.
2423 (setq annotation (comment-string-strip annotation t nil)))
2424 (setq annotation (company--clean-string annotation)))
2425 (push (cons value annotation) items)
2426 (setq width (max (+ (length value)
2427 (if (and annotation company-tooltip-align-annotations)
2428 (1+ (length annotation))
2429 (length annotation)))
2432 (setq width (min window-width
2433 (max company-tooltip-minimum-width
2434 (if company-show-numbers
2438 (let ((items (nreverse items))
2439 (numbered (if company-show-numbers 0 99999))
2442 (push (company--scrollpos-line previous width) new))
2445 (let* ((item (pop items))
2447 (annotation (cdr item))
2448 (right (company-space-string company-tooltip-margin))
2450 (when (< numbered 10)
2453 (setq right (concat (format " %d" (mod numbered 10)) right)))
2455 (company-fill-propertize str annotation
2456 width (equal i selection)
2457 (company-space-string
2458 company-tooltip-margin)
2460 (when scrollbar-bounds
2461 (company--scrollbar i scrollbar-bounds)))
2465 (push (company--scrollpos-line remainder width) new))
2469 (defun company--scrollbar-bounds (offset limit length)
2470 (when (> length limit)
2471 (let* ((size (ceiling (* limit (float limit)) length))
2472 (lower (floor (* limit (float offset)) length))
2473 (upper (+ lower size -1)))
2474 (cons lower upper))))
2476 (defun company--scrollbar (i bounds)
2477 (propertize " " 'face
2478 (if (and (>= i (car bounds)) (<= i (cdr bounds)))
2479 'company-scrollbar-fg
2480 'company-scrollbar-bg)))
2482 (defun company--scrollpos-line (text width)
2483 (propertize (concat (company-space-string company-tooltip-margin)
2484 (company-safe-substring text 0 width)
2485 (company-space-string company-tooltip-margin))
2486 'face 'company-tooltip))
2490 (defun company--pseudo-tooltip-height ()
2491 "Calculate the appropriate tooltip height.
2492 Returns a negative number if the tooltip should be displayed above point."
2493 (let* ((lines (company--row))
2494 (below (- (company--window-height) 1 lines)))
2495 (if (and (< below (min company-tooltip-minimum company-candidates-length))
2497 (- (max 3 (min company-tooltip-limit lines)))
2498 (max 3 (min company-tooltip-limit below)))))
2500 (defun company-pseudo-tooltip-show (row column selection)
2501 (company-pseudo-tooltip-hide)
2504 (let* ((height (company--pseudo-tooltip-height))
2508 (setq row (+ row height -1)
2511 (let* ((nl (< (move-to-window-line row) row))
2513 (end (save-excursion
2514 (move-to-window-line (+ row (abs height)))
2516 (ov (make-overlay (if nl beg (1- beg)) end nil t))
2517 (args (list (mapcar 'company-plainify
2518 (company-buffer-lines beg end))
2521 (setq company-pseudo-tooltip-overlay ov)
2522 (overlay-put ov 'company-replacement-args args)
2524 (let ((lines (company--create-lines selection (abs height))))
2525 (overlay-put ov 'company-display
2526 (apply 'company--replacement-string lines args))
2527 (overlay-put ov 'company-width (string-width (car lines))))
2529 (overlay-put ov 'company-column column)
2530 (overlay-put ov 'company-height height)))))
2532 (defun company-pseudo-tooltip-show-at-point (pos column-offset)
2533 (let* ((col-row (company--col-row pos))
2534 (col (- (car col-row) column-offset)))
2535 (when (< col 0) (setq col 0))
2536 (company-pseudo-tooltip-show (1+ (cdr col-row)) col company-selection)))
2538 (defun company-pseudo-tooltip-edit (selection)
2539 (let* ((height (overlay-get company-pseudo-tooltip-overlay 'company-height))
2540 (lines (company--create-lines selection (abs height))))
2541 (overlay-put company-pseudo-tooltip-overlay 'company-width
2542 (string-width (car lines)))
2543 (overlay-put company-pseudo-tooltip-overlay 'company-display
2544 (apply 'company--replacement-string
2546 (overlay-get company-pseudo-tooltip-overlay
2547 'company-replacement-args)))))
2549 (defun company-pseudo-tooltip-hide ()
2550 (when company-pseudo-tooltip-overlay
2551 (delete-overlay company-pseudo-tooltip-overlay)
2552 (setq company-pseudo-tooltip-overlay nil)))
2554 (defun company-pseudo-tooltip-hide-temporarily ()
2555 (when (overlayp company-pseudo-tooltip-overlay)
2556 (overlay-put company-pseudo-tooltip-overlay 'invisible nil)
2557 (overlay-put company-pseudo-tooltip-overlay 'after-string nil)))
2559 (defun company-pseudo-tooltip-unhide ()
2560 (when company-pseudo-tooltip-overlay
2561 (let* ((ov company-pseudo-tooltip-overlay)
2562 (disp (overlay-get ov 'company-display)))
2563 ;; Beat outline's folding overlays, at least.
2564 (overlay-put ov 'priority 1)
2565 ;; `display' could be better (http://debbugs.gnu.org/18285), but it
2566 ;; doesn't work when the overlay is empty, which is what happens at eob.
2567 ;; It also seems to interact badly with `cursor'.
2568 ;; We deal with priorities by having the overlay start before the newline.
2569 (overlay-put ov 'after-string disp)
2570 (overlay-put ov 'invisible t)
2571 (overlay-put ov 'window (selected-window)))))
2573 (defun company-pseudo-tooltip-guard ()
2575 (save-excursion (beginning-of-visual-line))
2576 (let ((ov company-pseudo-tooltip-overlay)
2577 (overhang (save-excursion (end-of-visual-line)
2578 (- (line-end-position) (point)))))
2579 (when (>= (overlay-get ov 'company-height) 0)
2581 (buffer-substring-no-properties (point) (overlay-start ov))
2582 (when (>= overhang 0) overhang))))))
2584 (defun company-pseudo-tooltip-frontend (command)
2585 "`company-mode' front-end similar to a tooltip but based on overlays."
2587 (pre-command (company-pseudo-tooltip-hide-temporarily))
2589 (unless (when (overlayp company-pseudo-tooltip-overlay)
2590 (let* ((ov company-pseudo-tooltip-overlay)
2591 (old-height (overlay-get ov 'company-height))
2592 (new-height (company--pseudo-tooltip-height)))
2594 (>= (* old-height new-height) 0)
2595 (>= (abs old-height) (abs new-height))
2596 (equal (company-pseudo-tooltip-guard)
2597 (overlay-get ov 'company-guard)))))
2599 (company-pseudo-tooltip-show-at-point (point) (length company-prefix))
2600 (overlay-put company-pseudo-tooltip-overlay
2601 'company-guard (company-pseudo-tooltip-guard)))
2602 (company-pseudo-tooltip-unhide))
2603 (hide (company-pseudo-tooltip-hide)
2604 (setq company-tooltip-offset 0))
2605 (update (when (overlayp company-pseudo-tooltip-overlay)
2606 (company-pseudo-tooltip-edit company-selection)))))
2608 (defun company-pseudo-tooltip-unless-just-one-frontend (command)
2609 "`company-pseudo-tooltip-frontend', but not shown for single candidates."
2610 (unless (and (eq command 'post-command)
2611 (company--show-inline-p))
2612 (company-pseudo-tooltip-frontend command)))
2614 ;;; overlay ;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;
2616 (defvar-local company-preview-overlay nil)
2618 (defun company-preview-show-at-point (pos)
2619 (company-preview-hide)
2621 (let ((completion (nth company-selection company-candidates)))
2622 (setq completion (propertize completion 'face 'company-preview))
2623 (add-text-properties 0 (length company-common)
2624 '(face company-preview-common) completion)
2626 ;; Add search string
2627 (and company-search-string
2628 (string-match (regexp-quote company-search-string) completion)
2629 (add-text-properties (match-beginning 0)
2631 '(face company-preview-search)
2634 (setq completion (company-strip-prefix completion))
2636 (and (equal pos (point))
2637 (not (equal completion ""))
2638 (add-text-properties 0 1 '(cursor 1) completion))
2641 (pto company-pseudo-tooltip-overlay)
2642 (ptf-workaround (and
2645 (eq pos (overlay-start pto)))))
2646 ;; Try to accomodate for the pseudo-tooltip overlay,
2647 ;; which may start at the same position if it's at eol.
2648 (when ptf-workaround
2650 (setq completion (concat (buffer-substring beg pos) completion)))
2652 (setq company-preview-overlay (make-overlay beg pos))
2654 (let ((ov company-preview-overlay))
2655 (overlay-put ov (if ptf-workaround 'display 'after-string)
2657 (overlay-put ov 'window (selected-window))))))
2659 (defun company-preview-hide ()
2660 (when company-preview-overlay
2661 (delete-overlay company-preview-overlay)
2662 (setq company-preview-overlay nil)))
2664 (defun company-preview-frontend (command)
2665 "`company-mode' front-end showing the selection as if it had been inserted."
2667 (`pre-command (company-preview-hide))
2668 (`post-command (company-preview-show-at-point (point)))
2669 (`hide (company-preview-hide))))
2671 (defun company-preview-if-just-one-frontend (command)
2672 "`company-preview-frontend', but only shown for single candidates."
2673 (when (or (not (eq command 'post-command))
2674 (company--show-inline-p))
2675 (company-preview-frontend command)))
2677 (defun company--show-inline-p ()
2678 (and (not (cdr company-candidates))
2680 (or (eq (company-call-backend 'ignore-case) 'keep-prefix)
2681 (string-prefix-p company-prefix company-common))))
2683 ;;; echo ;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;
2685 (defvar-local company-echo-last-msg nil)
2687 (defvar company-echo-timer nil)
2689 (defvar company-echo-delay .01)
2691 (defun company-echo-show (&optional getter)
2693 (setq company-echo-last-msg (funcall getter)))
2694 (let ((message-log-max nil))
2695 (if company-echo-last-msg
2696 (message "%s" company-echo-last-msg)
2699 (defun company-echo-show-soon (&optional getter)
2700 (when company-echo-timer
2701 (cancel-timer company-echo-timer))
2702 (setq company-echo-timer (run-with-timer 0 nil 'company-echo-show getter)))
2704 (defsubst company-echo-show-when-idle (&optional getter)
2705 (when (sit-for company-echo-delay)
2706 (company-echo-show getter)))
2708 (defun company-echo-format ()
2710 (let ((limit (window-body-width (minibuffer-window)))
2712 ;; Roll to selection.
2713 (candidates (nthcdr company-selection company-candidates))
2714 (i (if company-show-numbers company-selection 99999))
2718 (setq comp (company-reformat (pop candidates))
2719 len (+ len 1 (length comp)))
2723 (setq comp (propertize (format "%d: %s" i comp)
2724 'face 'company-echo))
2727 (add-text-properties 3 (+ 3 (length company-common))
2728 '(face company-echo-common) comp))
2729 (setq comp (propertize comp 'face 'company-echo))
2730 (add-text-properties 0 (length company-common)
2731 '(face company-echo-common) comp))
2733 (setq candidates nil)
2736 (mapconcat 'identity (nreverse msg) " ")))
2738 (defun company-echo-strip-common-format ()
2740 (let ((limit (window-body-width (minibuffer-window)))
2741 (len (+ (length company-prefix) 2))
2742 ;; Roll to selection.
2743 (candidates (nthcdr company-selection company-candidates))
2744 (i (if company-show-numbers company-selection 99999))
2748 (setq comp (company-strip-prefix (pop candidates))
2749 len (+ len 2 (length comp)))
2752 (setq comp (format "%s (%d)" comp i))
2756 (setq candidates nil)
2757 (push (propertize comp 'face 'company-echo) msg)))
2759 (concat (propertize company-prefix 'face 'company-echo-common) "{"
2760 (mapconcat 'identity (nreverse msg) ", ")
2763 (defun company-echo-hide ()
2764 (unless (equal company-echo-last-msg "")
2765 (setq company-echo-last-msg "")
2766 (company-echo-show)))
2768 (defun company-echo-frontend (command)
2769 "`company-mode' front-end showing the candidates in the echo area."
2771 (`post-command (company-echo-show-soon 'company-echo-format))
2772 (`hide (company-echo-hide))))
2774 (defun company-echo-strip-common-frontend (command)
2775 "`company-mode' front-end showing the candidates in the echo area."
2777 (`post-command (company-echo-show-soon 'company-echo-strip-common-format))
2778 (`hide (company-echo-hide))))
2780 (defun company-echo-metadata-frontend (command)
2781 "`company-mode' front-end showing the documentation in the echo area."
2783 (`post-command (company-echo-show-when-idle 'company-fetch-metadata))
2784 (`hide (company-echo-hide))))
2787 ;;; company.el ends here