1 ;;; company.el --- Modular text completion framework -*- lexical-binding: t -*-
3 ;; Copyright (C) 2009-2014 Free Software Foundation, Inc.
5 ;; Author: Nikolaj Schumacher
6 ;; Maintainer: Dmitry Gutov <dgutov@yandex.ru>
7 ;; URL: http://company-mode.github.io/
9 ;; Keywords: abbrev, convenience, matching
10 ;; Package-Requires: ((emacs "24.1") (cl-lib "0.5"))
12 ;; This file is part of GNU Emacs.
14 ;; GNU Emacs is free software: you can redistribute it and/or modify
15 ;; it under the terms of the GNU General Public License as published by
16 ;; the Free Software Foundation, either version 3 of the License, or
17 ;; (at your option) any later version.
19 ;; GNU Emacs is distributed in the hope that it will be useful,
20 ;; but WITHOUT ANY WARRANTY; without even the implied warranty of
21 ;; MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
22 ;; GNU General Public License for more details.
24 ;; You should have received a copy of the GNU General Public License
25 ;; along with GNU Emacs. If not, see <http://www.gnu.org/licenses/>.
29 ;; Company is a modular completion mechanism. Modules for retrieving completion
30 ;; candidates are called back-ends, modules for displaying them are front-ends.
32 ;; Company comes with many back-ends, e.g. `company-elisp'. These are
33 ;; distributed in separate files and can be used individually.
35 ;; Place company.el and the back-ends you want to use in a directory and add the
36 ;; following to your .emacs:
37 ;; (add-to-list 'load-path "/path/to/company")
38 ;; (autoload 'company-mode "company" nil t)
40 ;; Enable company-mode with M-x company-mode. For further information look at
41 ;; the documentation for `company-mode' (C-h f company-mode RET)
43 ;; If you want to start a specific back-end, call it interactively or use
44 ;; `company-begin-backend'. For example:
45 ;; M-x company-abbrev will prompt for and insert an abbrev.
47 ;; To write your own back-end, look at the documentation for `company-backends'.
48 ;; Here is a simple example completing "foo":
50 ;; (defun company-my-backend (command &optional arg &rest ignored)
52 ;; (`prefix (when (looking-back "foo\\>")
54 ;; (`candidates (list "foobar" "foobaz" "foobarbaz"))
55 ;; (`meta (format "This value is named %s" arg))))
57 ;; Sometimes it is a good idea to mix several back-ends together, for example to
58 ;; enrich gtags with dabbrev-code results (to emulate local variables).
59 ;; To do this, add a list with both back-ends as an element in company-backends.
62 ;; When point is at the very end of the buffer, the pseudo-tooltip appears very
63 ;; wrong, unless company is allowed to temporarily insert a fake newline.
64 ;; This behavior is enabled by `company-end-of-buffer-workaround'.
68 ;; See NEWS.md in the repository.
75 ;; FIXME: Use `user-error'.
76 (add-to-list 'debug-ignored-errors "^.* frontend cannot be used twice$")
77 (add-to-list 'debug-ignored-errors "^Echo area cannot be used twice$")
78 (add-to-list 'debug-ignored-errors "^No \\(document\\|loc\\)ation available$")
79 (add-to-list 'debug-ignored-errors "^Company not ")
80 (add-to-list 'debug-ignored-errors "^No candidate number ")
81 (add-to-list 'debug-ignored-errors "^Cannot complete at point$")
82 (add-to-list 'debug-ignored-errors "^No other back-end$")
86 ;; `defvar-local' for Emacs 24.2 and below
87 (unless (fboundp 'defvar-local)
88 (defmacro defvar-local (var val &optional docstring)
89 "Define VAR as a buffer-local variable with default value VAL.
90 Like `defvar' but additionally marks the variable as being automatically
91 buffer-local wherever it is set."
92 (declare (debug defvar) (doc-string 3))
94 (defvar ,var ,val ,docstring)
95 (make-variable-buffer-local ',var)))))
98 "Extensible inline text completion mechanism"
103 (defface company-tooltip
104 '((default :foreground "black")
105 (((class color) (min-colors 88) (background light))
106 (:background "cornsilk"))
107 (((class color) (min-colors 88) (background dark))
108 (:background "yellow")))
109 "Face used for the tooltip.")
111 (defface company-tooltip-selection
112 '((default :inherit company-tooltip)
113 (((class color) (min-colors 88) (background light))
114 (:background "light blue"))
115 (((class color) (min-colors 88) (background dark))
116 (:background "orange1"))
117 (t (:background "green")))
118 "Face used for the selection in the tooltip.")
120 (defface company-tooltip-mouse
121 '((default :inherit highlight))
122 "Face used for the tooltip item under the mouse.")
124 (defface company-tooltip-common
125 '((default :inherit company-tooltip)
126 (((background light))
127 :foreground "darkred")
130 "Face used for the common completion in the tooltip.")
132 (defface company-tooltip-common-selection
133 '((default :inherit company-tooltip-selection)
134 (((background light))
135 :foreground "darkred")
138 "Face used for the selected common completion in the tooltip.")
140 (defface company-tooltip-annotation
141 '((default :inherit company-tooltip)
142 (((background light))
143 :foreground "firebrick4")
146 "Face used for the annotation in the tooltip.")
148 (defface company-scrollbar-fg
149 '((((background light))
150 :background "darkred")
153 "Face used for the tooltip scrollbar thumb.")
155 (defface company-scrollbar-bg
156 '((default :inherit company-tooltip)
157 (((background light))
161 "Face used for the tooltip scrollbar background.")
163 (defface company-preview
164 '((((background light))
165 :inherit company-tooltip-selection)
168 :foreground "wheat"))
169 "Face used for the completion preview.")
171 (defface company-preview-common
172 '((((background light))
173 :inherit company-tooltip-selection)
175 :inherit company-preview
177 "Face used for the common part of the completion preview.")
179 (defface company-preview-search
180 '((((background light))
181 :inherit company-tooltip-common-selection)
183 :inherit company-preview
184 :background "blue1"))
185 "Face used for the search string in the completion preview.")
187 (defface company-echo nil
188 "Face used for completions in the echo area.")
190 (defface company-echo-common
191 '((((background dark)) (:foreground "firebrick1"))
192 (((background light)) (:background "firebrick4")))
193 "Face used for the common part of completions in the echo area.")
195 (defun company-frontends-set (variable value)
197 (let ((remainder value))
198 (setcdr remainder (delq (car remainder) (cdr remainder))))
199 (and (memq 'company-pseudo-tooltip-unless-just-one-frontend value)
200 (memq 'company-pseudo-tooltip-frontend value)
201 (error "Pseudo tooltip frontend cannot be used twice"))
202 (and (memq 'company-preview-if-just-one-frontend value)
203 (memq 'company-preview-frontend value)
204 (error "Preview frontend cannot be used twice"))
205 (and (memq 'company-echo value)
206 (memq 'company-echo-metadata-frontend value)
207 (error "Echo area cannot be used twice"))
208 ;; preview must come last
209 (dolist (f '(company-preview-if-just-one-frontend company-preview-frontend))
211 (setq value (append (delq f value) (list f)))))
212 (set variable value))
214 (defcustom company-frontends '(company-pseudo-tooltip-unless-just-one-frontend
215 company-preview-if-just-one-frontend
216 company-echo-metadata-frontend)
217 "The list of active front-ends (visualizations).
218 Each front-end is a function that takes one argument. It is called with
219 one of the following arguments:
221 `show': When the visualization should start.
223 `hide': When the visualization should end.
225 `update': When the data has been updated.
227 `pre-command': Before every command that is executed while the
228 visualization is active.
230 `post-command': After every command that is executed while the
231 visualization is active.
233 The visualized data is stored in `company-prefix', `company-candidates',
234 `company-common', `company-selection', `company-point' and
235 `company-search-string'."
236 :set 'company-frontends-set
237 :type '(repeat (choice (const :tag "echo" company-echo-frontend)
238 (const :tag "echo, strip common"
239 company-echo-strip-common-frontend)
240 (const :tag "show echo meta-data in echo"
241 company-echo-metadata-frontend)
242 (const :tag "pseudo tooltip"
243 company-pseudo-tooltip-frontend)
244 (const :tag "pseudo tooltip, multiple only"
245 company-pseudo-tooltip-unless-just-one-frontend)
246 (const :tag "preview" company-preview-frontend)
247 (const :tag "preview, unique only"
248 company-preview-if-just-one-frontend)
249 (function :tag "custom function" nil))))
251 (defcustom company-tooltip-limit 10
252 "The maximum number of candidates in the tooltip."
255 (defcustom company-tooltip-minimum 6
256 "The minimum height of the tooltip.
257 If this many lines are not available, prefer to display the tooltip above."
260 (defcustom company-tooltip-minimum-width 0
261 "The minimum width of the tooltip's inner area.
262 This doesn't include the margins and the scroll bar."
264 :package-version '(company . "0.8.0"))
266 (defcustom company-tooltip-margin 1
267 "Width of margin columns to show around the toolip."
270 (defcustom company-tooltip-offset-display 'scrollbar
271 "Method using which the tooltip displays scrolling position.
272 `scrollbar' means draw a scrollbar to the right of the items.
273 `lines' means wrap items in lines with \"before\" and \"after\" counters."
274 :type '(choice (const :tag "Scrollbar" scrollbar)
275 (const :tag "Two lines" lines)))
277 (defcustom company-tooltip-align-annotations nil
278 "When non-nil, align annotations to the right tooltip border."
280 :package-version '(company . "0.7.1"))
282 (defcustom company-tooltip-flip-when-above nil
283 "Whether to flip the tooltip when it's above the current line."
285 :package-version '(company . "0.8.1"))
287 (defvar company-safe-backends
288 '((company-abbrev . "Abbrev")
289 (company-bbdb . "BBDB")
290 (company-capf . "completion-at-point-functions")
291 (company-clang . "Clang")
292 (company-cmake . "CMake")
293 (company-css . "CSS")
294 (company-dabbrev . "dabbrev for plain text")
295 (company-dabbrev-code . "dabbrev for code")
296 (company-eclim . "Eclim (an Eclipse interface)")
297 (company-elisp . "Emacs Lisp")
298 (company-etags . "etags")
299 (company-files . "Files")
300 (company-gtags . "GNU Global")
301 (company-ispell . "Ispell")
302 (company-keywords . "Programming language keywords")
303 (company-nxml . "nxml")
304 (company-oddmuse . "Oddmuse")
305 (company-pysmell . "PySmell")
306 (company-ropemacs . "ropemacs")
307 (company-semantic . "Semantic")
308 (company-tempo . "Tempo templates")
309 (company-xcode . "Xcode")))
310 (put 'company-safe-backends 'risky-local-variable t)
312 (defun company-safe-backends-p (backends)
313 (and (consp backends)
314 (not (cl-dolist (backend backends)
315 (unless (if (consp backend)
316 (company-safe-backends-p backend)
317 (assq backend company-safe-backends))
320 (defcustom company-backends `(,@(unless (version< "24.3.50" emacs-version)
321 (list 'company-elisp))
323 company-nxml company-css
324 company-eclim company-semantic company-clang
325 company-xcode company-ropemacs company-cmake
327 (company-dabbrev-code company-gtags company-etags
329 company-oddmuse company-files company-dabbrev)
330 "The list of active back-ends (completion engines).
332 Only one back-end is used at a time. The choice depends on the order of
333 the items in this list, and on the values they return in response to the
334 `prefix' command (see below). But a back-end can also be a \"grouped\"
337 `company-begin-backend' can be used to start a specific back-end,
338 `company-other-backend' will skip to the next matching back-end in the list.
340 Each back-end is a function that takes a variable number of arguments.
341 The first argument is the command requested from the back-end. It is one
344 `prefix': The back-end should return the text to be completed. It must be
345 text immediately before point. Returning nil passes control to the next
346 back-end. The function should return `stop' if it should complete but
347 cannot (e.g. if it is in the middle of a string). Instead of a string,
348 the back-end may return a cons where car is the prefix and cdr is used in
349 `company-minimum-prefix-length' test. It must be either number or t, and
350 in the latter case the test automatically succeeds.
352 `candidates': The second argument is the prefix to be completed. The
353 return value should be a list of candidates that match the prefix.
355 Non-prefix matches are also supported (candidates that don't start with the
356 prefix, but match it in some backend-defined way). Backends that use this
357 feature must disable cache (return t to `no-cache') and should also respond
362 `sorted': Return t here to indicate that the candidates are sorted and will
363 not need to be sorted again.
365 `duplicates': If non-nil, company will take care of removing duplicates
368 `no-cache': Usually company doesn't ask for candidates again as completion
369 progresses, unless the back-end returns t for this command. The second
370 argument is the latest prefix.
372 `meta': The second argument is a completion candidate. Return a (short)
373 documentation string for it.
375 `doc-buffer': The second argument is a completion candidate. Return a
376 buffer with documentation for it. Preferably use `company-doc-buffer',
378 `location': The second argument is a completion candidate. Return the cons
379 of buffer and buffer location, or of file and line number where the
380 completion candidate was defined.
382 `annotation': The second argument is a completion candidate. Return a
383 string to be displayed inline with the candidate in the popup. If
384 duplicates are removed by company, candidates with equal string values will
385 be kept if they have different annotations. For that to work properly,
386 backends should store the related information on candidates using text
389 `match': The second argument is a completion candidate. Backends that
390 provide non-prefix completions should return the position of the end of
391 text in the candidate that matches `prefix'. It will be used when
394 `require-match': If this returns t, the user is not allowed to enter
395 anything not offered as a candidate. Use with care! The default value nil
396 gives the user that choice with `company-require-match'. Return value
397 `never' overrides that option the other way around.
399 `init': Called once for each buffer. The back-end can check for external
400 programs and files and load any required libraries. Raising an error here
401 will show up in message log once, and the back-end will not be used for
404 `post-completion': Called after a completion candidate has been inserted
405 into the buffer. The second argument is the candidate. Can be used to
406 modify it, e.g. to expand a snippet.
408 The back-end should return nil for all commands it does not support or
409 does not know about. It should also be callable interactively and use
410 `company-begin-backend' to start itself in that case.
414 An element of `company-backends' can also itself be a list of back-ends,
415 then it's considered to be a \"grouped\" back-end.
417 When possible, commands taking a candidate as an argument are dispatched to
418 the back-end it came from. In other cases, the first non-nil value among
419 all the back-ends is returned.
421 The latter is the case for the `prefix' command. But if the group contains
422 the keyword `:with', the back-ends after it are ignored for this command.
424 The completions from back-ends in a group are merged (but only from those
425 that return the same `prefix').
427 Asynchronous back-ends:
429 The return value of each command can also be a cons (:async . FETCHER)
430 where FETCHER is a function of one argument, CALLBACK. When the data
431 arrives, FETCHER must call CALLBACK and pass it the appropriate return
432 value, as described above.
434 True asynchronous operation is only supported for command `candidates', and
435 only during idle completion. Other commands will block the user interface,
436 even if the back-end uses the asynchronous calling convention."
440 ,@(mapcar (lambda (b) `(const :tag ,(cdr b) ,(car b)))
441 company-safe-backends)
442 (symbol :tag "User defined")
443 (repeat :tag "Merged Back-ends"
444 (choice :tag "Back-end"
445 ,@(mapcar (lambda (b)
446 `(const :tag ,(cdr b) ,(car b)))
447 company-safe-backends)
448 (const :tag "With" :with)
449 (symbol :tag "User defined"))))))
451 (put 'company-backends 'safe-local-variable 'company-safe-backends-p)
453 (defcustom company-transformers nil
454 "Functions to change the list of candidates received from backends,
455 after sorting and removal of duplicates (if appropriate).
456 Each function gets called with the return value of the previous one."
458 (const :tag "None" nil)
459 (const :tag "Sort by occurrence" (company-sort-by-occurrence))
460 (const :tag "Sort by back-end importance"
461 (company-sort-by-backend-importance))
462 (repeat :tag "User defined" (function))))
464 (defcustom company-completion-started-hook nil
465 "Hook run when company starts completing.
466 The hook is called with one argument that is non-nil if the completion was
470 (defcustom company-completion-cancelled-hook nil
471 "Hook run when company cancels completing.
472 The hook is called with one argument that is non-nil if the completion was
476 (defcustom company-completion-finished-hook nil
477 "Hook run when company successfully completes.
478 The hook is called with the selected candidate as an argument.
480 If you indend to use it to post-process candidates from a specific
481 back-end, consider using the `post-completion' command instead."
484 (defcustom company-minimum-prefix-length 3
485 "The minimum prefix length for idle completion."
486 :type '(integer :tag "prefix length"))
488 (defcustom company-abort-manual-when-too-short nil
489 "If enabled, cancel a manually started completion when the prefix gets
490 shorter than both `company-minimum-prefix-length' and the length of the
491 prefix it was started from."
493 :package-version '(company . "0.8.0"))
495 (defcustom company-require-match 'company-explicit-action-p
496 "If enabled, disallow non-matching input.
497 This can be a function do determine if a match is required.
499 This can be overridden by the back-end, if it returns t or `never' to
500 `require-match'. `company-auto-complete' also takes precedence over this."
501 :type '(choice (const :tag "Off" nil)
502 (function :tag "Predicate function")
503 (const :tag "On, if user interaction took place"
504 'company-explicit-action-p)
505 (const :tag "On" t)))
507 (defcustom company-auto-complete nil
508 "Determines when to auto-complete.
509 If this is enabled, all characters from `company-auto-complete-chars'
510 trigger insertion of the selected completion candidate.
511 This can also be a function."
512 :type '(choice (const :tag "Off" nil)
513 (function :tag "Predicate function")
514 (const :tag "On, if user interaction took place"
515 'company-explicit-action-p)
516 (const :tag "On" t)))
518 (defcustom company-auto-complete-chars '(?\ ?\) ?.)
519 "Determines which characters trigger auto-completion.
520 See `company-auto-complete'. If this is a string, each string character
521 tiggers auto-completion. If it is a list of syntax description characters (see
522 `modify-syntax-entry'), all characters with that syntax auto-complete.
524 This can also be a function, which is called with the new input and should
525 return non-nil if company should auto-complete.
527 A character that is part of a valid candidate never triggers auto-completion."
528 :type '(choice (string :tag "Characters")
530 (const :tag "Whitespace" ?\ )
531 (const :tag "Symbol" ?_)
532 (const :tag "Opening parentheses" ?\()
533 (const :tag "Closing parentheses" ?\))
534 (const :tag "Word constituent" ?w)
535 (const :tag "Punctuation." ?.)
536 (const :tag "String quote." ?\")
537 (const :tag "Paired delimiter." ?$)
538 (const :tag "Expression quote or prefix operator." ?\')
539 (const :tag "Comment starter." ?<)
540 (const :tag "Comment ender." ?>)
541 (const :tag "Character-quote." ?/)
542 (const :tag "Generic string fence." ?|)
543 (const :tag "Generic comment fence." ?!))
544 (function :tag "Predicate function")))
546 (defcustom company-idle-delay .5
547 "The idle delay in seconds until completion starts automatically.
548 A value of nil means no idle completion, t means show candidates
549 immediately when a prefix of `company-minimum-prefix-length' is reached."
550 :type '(choice (const :tag "never (nil)" nil)
551 (const :tag "immediate (t)" t)
552 (number :tag "seconds")))
554 (defcustom company-begin-commands '(self-insert-command org-self-insert-command)
555 "A list of commands after which idle completion is allowed.
556 If this is t, it can show completions after any command except a few from a
557 pre-defined list. See `company-idle-delay'.
559 Alternatively, any command with a non-nil `company-begin' property is
560 treated as if it was on this list."
561 :type '(choice (const :tag "Any command" t)
562 (const :tag "Self insert command" '(self-insert-command))
563 (repeat :tag "Commands" function)))
565 (defcustom company-continue-commands '(not save-buffer save-some-buffers
566 save-buffers-kill-terminal
567 save-buffers-kill-emacs)
568 "A list of commands that are allowed during completion.
569 If this is t, or if `company-begin-commands' is t, any command is allowed.
570 Otherwise, the value must be a list of symbols. If it starts with `not',
571 the cdr is the list of commands that abort completion. Otherwise, all
572 commands except those in that list, or in `company-begin-commands', or
573 commands in the `company-' namespace, abort completion."
574 :type '(choice (const :tag "Any command" t)
575 (cons :tag "Any except"
577 (repeat :tag "Commands" function))
578 (repeat :tag "Commands" function)))
580 (defcustom company-show-numbers nil
581 "If enabled, show quick-access numbers for the first ten candidates."
582 :type '(choice (const :tag "off" nil)
583 (const :tag "on" t)))
585 (defcustom company-selection-wrap-around nil
586 "If enabled, selecting item before first or after last wraps around."
587 :type '(choice (const :tag "off" nil)
588 (const :tag "on" t)))
590 (defvar company-end-of-buffer-workaround t
591 "Work around a visualization bug when completing at the end of the buffer.
592 The work-around consists of adding a newline.")
594 (defvar company-async-wait 0.03
595 "Pause between checks to see if the value's been set when turning an
596 asynchronous call into synchronous.")
598 (defvar company-async-timeout 2
599 "Maximum wait time for a value to be set during asynchronous call.")
601 ;;; mode ;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;
603 (defvar company-mode-map (make-sparse-keymap)
604 "Keymap used by `company-mode'.")
606 (defvar company-active-map
607 (let ((keymap (make-sparse-keymap)))
608 (define-key keymap "\e\e\e" 'company-abort)
609 (define-key keymap "\C-g" 'company-abort)
610 (define-key keymap (kbd "M-n") 'company-select-next)
611 (define-key keymap (kbd "M-p") 'company-select-previous)
612 (define-key keymap (kbd "<down>") 'company-select-next-or-abort)
613 (define-key keymap (kbd "<up>") 'company-select-previous-or-abort)
614 (define-key keymap [down-mouse-1] 'ignore)
615 (define-key keymap [down-mouse-3] 'ignore)
616 (define-key keymap [mouse-1] 'company-complete-mouse)
617 (define-key keymap [mouse-3] 'company-select-mouse)
618 (define-key keymap [up-mouse-1] 'ignore)
619 (define-key keymap [up-mouse-3] 'ignore)
620 (define-key keymap [return] 'company-complete-selection)
621 (define-key keymap (kbd "RET") 'company-complete-selection)
622 (define-key keymap [tab] 'company-complete-common)
623 (define-key keymap (kbd "TAB") 'company-complete-common)
624 (define-key keymap (kbd "<f1>") 'company-show-doc-buffer)
625 (define-key keymap (kbd "C-h") 'company-show-doc-buffer)
626 (define-key keymap "\C-w" 'company-show-location)
627 (define-key keymap "\C-s" 'company-search-candidates)
628 (define-key keymap "\C-\M-s" 'company-filter-candidates)
630 (define-key keymap (vector (+ (aref (kbd "M-0") 0) i))
633 (company-complete-number ,(if (zerop i) 10 i)))))
636 "Keymap that is enabled during an active completion.")
638 (defvar company--disabled-backends nil)
640 (defun company-init-backend (backend)
641 (and (symbolp backend)
642 (not (fboundp backend))
643 (ignore-errors (require backend nil t)))
648 (funcall backend 'init)
649 (put backend 'company-init t))
651 (put backend 'company-init 'failed)
652 (unless (memq backend company--disabled-backends)
653 (message "Company back-end '%s' could not be initialized:\n%s"
654 backend (error-message-string err)))
655 (cl-pushnew backend company--disabled-backends)
657 ;; No initialization for lambdas.
658 ((functionp backend) t)
659 (t ;; Must be a list.
660 (cl-dolist (b backend)
662 (company-init-backend b))))))
664 (defvar company-default-lighter " company")
666 (defvar-local company-lighter company-default-lighter)
669 (define-minor-mode company-mode
670 "\"complete anything\"; is an in-buffer completion framework.
671 Completion starts automatically, depending on the values
672 `company-idle-delay' and `company-minimum-prefix-length'.
674 Completion can be controlled with the commands:
675 `company-complete-common', `company-complete-selection', `company-complete',
676 `company-select-next', `company-select-previous'. If these commands are
677 called before `company-idle-delay', completion will also start.
679 Completions can be searched with `company-search-candidates' or
680 `company-filter-candidates'. These can be used while completion is
683 The completion data is retrieved using `company-backends' and displayed
684 using `company-frontends'. If you want to start a specific back-end, call
685 it interactively or use `company-begin-backend'.
687 regular keymap (`company-mode-map'):
690 keymap during active completions (`company-active-map'):
692 \\{company-active-map}"
693 nil company-lighter company-mode-map
696 (add-hook 'pre-command-hook 'company-pre-command nil t)
697 (add-hook 'post-command-hook 'company-post-command nil t)
698 (mapc 'company-init-backend company-backends))
699 (remove-hook 'pre-command-hook 'company-pre-command t)
700 (remove-hook 'post-command-hook 'company-post-command t)
702 (kill-local-variable 'company-point)))
704 (defcustom company-global-modes t
705 "Modes for which `company-mode' mode is turned on by `global-company-mode'.
706 If nil, means no modes. If t, then all major modes have it turned on.
707 If a list, it should be a list of `major-mode' symbol names for which
708 `company-mode' should be automatically turned on. The sense of the list is
709 negated if it begins with `not'. For example:
711 means that `company-mode' is turned on for buffers in C and C++ modes only.
713 means that `company-mode' is always turned on except in `message-mode' buffers."
714 :type '(choice (const :tag "none" nil)
716 (set :menu-tag "mode specific" :tag "modes"
718 (const :tag "Except" not)
719 (repeat :inline t (symbol :tag "mode")))))
722 (define-globalized-minor-mode global-company-mode company-mode company-mode-on)
724 (defun company-mode-on ()
725 (when (and (not (or noninteractive (eq (aref (buffer-name) 0) ?\s)))
726 (cond ((eq company-global-modes t)
728 ((eq (car-safe company-global-modes) 'not)
729 (not (memq major-mode (cdr company-global-modes))))
730 (t (memq major-mode company-global-modes))))
733 (defsubst company-assert-enabled ()
735 (company-uninstall-map)
736 (error "Company not enabled")))
738 ;;; keymaps ;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;
740 (defvar-local company-my-keymap nil)
742 (defvar company-emulation-alist '((t . nil)))
744 (defsubst company-enable-overriding-keymap (keymap)
745 (company-uninstall-map)
746 (setq company-my-keymap keymap))
748 (defun company-ensure-emulation-alist ()
749 (unless (eq 'company-emulation-alist (car emulation-mode-map-alists))
750 (setq emulation-mode-map-alists
751 (cons 'company-emulation-alist
752 (delq 'company-emulation-alist emulation-mode-map-alists)))))
754 (defun company-install-map ()
755 (unless (or (cdar company-emulation-alist)
756 (null company-my-keymap))
757 (setf (cdar company-emulation-alist) company-my-keymap)))
759 (defun company-uninstall-map ()
760 (setf (cdar company-emulation-alist) nil))
763 ;; Emacs calculates the active keymaps before reading the event. That means we
764 ;; cannot change the keymap from a timer. So we send a bogus command.
765 ;; XXX: Seems not to be needed anymore in Emacs 24.4
766 (defun company-ignore ()
768 (setq this-command last-command))
770 (global-set-key '[31415926] 'company-ignore)
772 (defun company-input-noop ()
773 (push 31415926 unread-command-events))
775 (defun company--column (&optional pos)
777 (when pos (goto-char pos))
781 (narrow-to-region (point) (point-max))
782 (let ((prefix (get-text-property (point) 'line-prefix)))
783 (if prefix (length prefix) 0)))
786 (defun company--row (&optional pos)
788 (when pos (goto-char pos))
789 (count-screen-lines (window-start)
790 (progn (vertical-motion 0) (point)))))
792 ;;; backends ;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;
794 (defvar-local company-backend nil)
796 (defun company-grab (regexp &optional expression limit)
797 (when (looking-back regexp limit)
798 (or (match-string-no-properties (or expression 0)) "")))
800 (defun company-grab-line (regexp &optional expression)
801 (company-grab regexp expression (point-at-bol)))
803 (defun company-grab-symbol ()
804 (if (looking-at "\\_>")
805 (buffer-substring (point) (save-excursion (skip-syntax-backward "w_")
807 (unless (and (char-after) (memq (char-syntax (char-after)) '(?w ?_)))
810 (defun company-grab-word ()
811 (if (looking-at "\\>")
812 (buffer-substring (point) (save-excursion (skip-syntax-backward "w")
814 (unless (and (char-after) (eq (char-syntax (char-after)) ?w))
817 (defun company-grab-symbol-cons (idle-begin-after-re &optional max-len)
818 (let ((symbol (company-grab-symbol)))
821 (forward-char (- (length symbol)))
822 (if (looking-back idle-begin-after-re (if max-len
824 (line-beginning-position)))
828 (defun company-in-string-or-comment ()
829 (let ((ppss (syntax-ppss)))
830 (or (car (setq ppss (nthcdr 3 ppss)))
831 (car (setq ppss (cdr ppss)))
834 (defun company-call-backend (&rest args)
835 (company--force-sync #'company-call-backend-raw args company-backend))
837 (defun company--force-sync (fun args backend)
838 (let ((value (apply fun args)))
839 (if (not (eq (car-safe value) :async))
842 (start (time-to-seconds)))
844 (lambda (result) (setq res result)))
845 (while (eq res 'trash)
846 (if (> (- (time-to-seconds) start) company-async-timeout)
847 (error "Company: Back-end %s async timeout with args %s"
849 (sleep-for company-async-wait)))
852 (defun company-call-backend-raw (&rest args)
854 (if (functionp company-backend)
855 (apply company-backend args)
856 (apply #'company--multi-backend-adapter company-backend args))
857 (error (error "Company: Back-end %s error \"%s\" with args %s"
858 company-backend (error-message-string err) args))))
860 (defun company--multi-backend-adapter (backends command &rest args)
861 (let ((backends (cl-loop for b in backends
862 when (not (and (symbolp b)
863 (eq 'failed (get b 'company-init))))
866 (if (eq command 'prefix)
867 (butlast backends (length (member :with backends)))
868 (delq :with backends)))
871 (company--multi-backend-adapter-candidates backends (car args)))
874 ((or `prefix `ignore-case `no-cache `require-match)
876 (cl-dolist (backend backends)
877 (when (setq value (company--force-sync
878 backend (cons command args) backend))
879 (cl-return value)))))
881 (let ((arg (car args)))
882 (when (> (length arg) 0)
883 (let ((backend (or (get-text-property 0 'company-backend arg)
885 (apply backend command args))))))))
887 (defun company--multi-backend-adapter-candidates (backends prefix)
888 (let ((pairs (cl-loop for backend in (cdr backends)
889 when (equal (company--prefix-str
890 (funcall backend 'prefix))
892 collect (cons (funcall backend 'candidates prefix)
897 (propertize str 'company-backend b))
899 (when (equal (company--prefix-str (funcall (car backends) 'prefix)) prefix)
900 ;; Small perf optimization: don't tag the candidates received
901 ;; from the first backend in the group.
902 (push (cons (funcall (car backends) 'candidates prefix)
905 (company--merge-async pairs (lambda (values) (apply #'append values)))))
907 (defun company--merge-async (pairs merger)
908 (let ((async (cl-loop for pair in pairs
910 (eq :async (car-safe (car pair))))))
912 (funcall merger (cl-loop for (val . mapper) in pairs
913 collect (funcall mapper val)))
924 (let ((val (car pair))
926 (if (not (eq :async (car-safe val)))
927 (push (funcall mapper val) lst)
931 (push fetcher pending)
934 (setq pending (delq fetcher pending))
935 (setcar cell (funcall mapper res))
936 (funcall finisher)))))))))))))
938 (defun company--prefix-str (prefix)
939 (or (car-safe prefix) prefix))
941 ;;; completion mechanism ;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;
943 (defvar-local company-prefix nil)
945 (defvar-local company-candidates nil)
947 (defvar-local company-candidates-length nil)
949 (defvar-local company-candidates-cache nil)
951 (defvar-local company-candidates-predicate nil)
953 (defvar-local company-common nil)
955 (defvar-local company-selection 0)
957 (defvar-local company-selection-changed nil)
959 (defvar-local company--manual-action nil
960 "Non-nil, if manual completion took place.")
962 (defvar-local company--manual-prefix nil)
964 (defvar company--auto-completion nil
965 "Non-nil when current candidate is being inserted automatically.
966 Controlled by `company-auto-complete'.")
968 (defvar-local company--point-max nil)
970 (defvar-local company-point nil)
972 (defvar company-timer nil)
974 (defvar-local company-added-newline nil)
976 (defsubst company-strip-prefix (str)
977 (substring str (length company-prefix)))
979 (defun company--insert-candidate (candidate)
980 (setq candidate (substring-no-properties candidate))
981 ;; XXX: Return value we check here is subject to change.
982 (if (eq (company-call-backend 'ignore-case) 'keep-prefix)
983 (insert (company-strip-prefix candidate))
984 (delete-region (- (point) (length company-prefix)) (point))
987 (defmacro company-with-candidate-inserted (candidate &rest body)
988 "Evaluate BODY with CANDIDATE temporarily inserted.
989 This is a tool for back-ends that need candidates inserted before they
990 can retrieve meta-data for them."
992 `(let ((inhibit-modification-hooks t)
993 (inhibit-point-motion-hooks t)
994 (modified-p (buffer-modified-p)))
995 (company--insert-candidate ,candidate)
998 (delete-region company-point (point)))))
1000 (defun company-explicit-action-p ()
1001 "Return whether explicit completion action was taken by the user."
1002 (or company--manual-action
1003 company-selection-changed))
1005 (defun company-reformat (candidate)
1006 ;; company-ispell needs this, because the results are always lower-case
1007 ;; It's mory efficient to fix it only when they are displayed.
1008 ;; FIXME: Adopt the current text's capitalization instead?
1009 (if (eq (company-call-backend 'ignore-case) 'keep-prefix)
1010 (concat company-prefix (substring candidate (length company-prefix)))
1013 (defun company--should-complete ()
1014 (and (eq company-idle-delay t)
1015 (not (or buffer-read-only overriding-terminal-local-map
1016 overriding-local-map))
1017 ;; Check if in the middle of entering a key combination.
1018 (or (equal (this-command-keys-vector) [])
1019 (not (keymapp (key-binding (this-command-keys-vector)))))
1020 (not (and transient-mark-mode mark-active))))
1022 (defun company--should-continue ()
1023 (or (eq t company-begin-commands)
1024 (eq t company-continue-commands)
1025 (if (eq 'not (car company-continue-commands))
1026 (not (memq this-command (cdr company-continue-commands)))
1027 (or (memq this-command company-begin-commands)
1028 (memq this-command company-continue-commands)
1029 (and (symbolp this-command)
1030 (string-match-p "\\`company-" (symbol-name this-command)))))))
1032 (defun company-call-frontends (command)
1033 (dolist (frontend company-frontends)
1035 (funcall frontend command)
1036 (error (error "Company: Front-end %s error \"%s\" on command %s"
1037 frontend (error-message-string err) command)))))
1039 (defun company-set-selection (selection &optional force-update)
1041 (if company-selection-wrap-around
1042 (mod selection company-candidates-length)
1043 (max 0 (min (1- company-candidates-length) selection))))
1044 (when (or force-update (not (equal selection company-selection)))
1045 (company--update-group-lighter (nth selection company-candidates))
1046 (setq company-selection selection
1047 company-selection-changed t)
1048 (company-call-frontends 'update)))
1050 (defun company--update-group-lighter (candidate)
1051 (when (listp company-backend)
1052 (let ((backend (or (get-text-property 0 'company-backend candidate)
1053 (car company-backend))))
1054 (when (and backend (symbolp backend))
1055 (let ((name (replace-regexp-in-string "company-\\|-company" ""
1056 (symbol-name backend))))
1057 (setq company-lighter (format " company-<%s>" name)))))))
1059 (defun company-apply-predicate (candidates predicate)
1061 (dolist (c candidates)
1062 (when (funcall predicate c)
1066 (defun company-update-candidates (candidates)
1067 (setq company-candidates-length (length candidates))
1068 (if (> company-selection 0)
1069 ;; Try to restore the selection
1070 (let ((selected (nth company-selection company-candidates)))
1071 (setq company-selection 0
1072 company-candidates candidates)
1074 (while (and candidates (string< (pop candidates) selected))
1075 (cl-incf company-selection))
1077 ;; Make sure selection isn't out of bounds.
1078 (setq company-selection (min (1- company-candidates-length)
1079 company-selection)))))
1080 (setq company-selection 0
1081 company-candidates candidates))
1083 (push (cons company-prefix company-candidates) company-candidates-cache)
1084 ;; Calculate common.
1085 (let ((completion-ignore-case (company-call-backend 'ignore-case)))
1086 ;; We want to support non-prefix completion, so filtering is the
1087 ;; responsibility of each respective backend, not ours.
1088 ;; On the other hand, we don't want to replace non-prefix input in
1089 ;; `company-complete-common'.
1090 (setq company-common
1091 (if (cdr company-candidates)
1092 (let ((common (try-completion company-prefix company-candidates)))
1094 ;; Mulple equal strings, probably with different
1098 (car company-candidates)))))
1100 (defun company-calculate-candidates (prefix)
1101 (let ((candidates (cdr (assoc prefix company-candidates-cache)))
1102 (ignore-case (company-call-backend 'ignore-case)))
1104 (when company-candidates-cache
1105 (let ((len (length prefix))
1106 (completion-ignore-case ignore-case)
1108 (cl-dotimes (i (1+ len))
1109 (when (setq prev (cdr (assoc (substring prefix 0 (- len i))
1110 company-candidates-cache)))
1111 (setq candidates (all-completions prefix prev))
1113 ;; no cache match, call back-end
1115 (company--process-candidates
1116 (company--fetch-candidates prefix))))
1117 (setq candidates (company--transform-candidates candidates))
1119 (if (or (cdr candidates)
1120 (not (eq t (compare-strings (car candidates) nil nil
1121 prefix nil nil ignore-case))))
1123 ;; Already completed and unique; don't start.
1126 (defun company--fetch-candidates (prefix)
1127 (let ((c (if company--manual-action
1128 (company-call-backend 'candidates prefix)
1129 (company-call-backend-raw 'candidates prefix)))
1131 (if (not (eq (car c) :async))
1133 (let ((buf (current-buffer))
1134 (win (selected-window))
1135 (tick (buffer-chars-modified-tick))
1137 (backend company-backend))
1140 (lambda (candidates)
1141 (if (not (and candidates (eq res 'done)))
1142 ;; Fetcher called us back right away.
1143 (setq res candidates)
1144 (setq company-backend backend
1145 company-candidates-cache
1147 (company--process-candidates
1149 (company-idle-begin buf win tick pt)))))
1150 ;; FIXME: Relying on the fact that the callers
1151 ;; will interpret nil as "do nothing" is shaky.
1152 ;; A throw-catch would be one possible improvement.
1154 (progn (setq res 'done) nil)))))
1156 (defun company--process-candidates (candidates)
1157 (when company-candidates-predicate
1159 (company-apply-predicate candidates
1160 company-candidates-predicate)))
1161 (unless (company-call-backend 'sorted)
1162 (setq candidates (sort candidates 'string<)))
1163 (when (company-call-backend 'duplicates)
1164 (company--strip-duplicates candidates))
1167 (defun company--strip-duplicates (candidates)
1168 (let ((c2 candidates))
1171 (let ((str (car c2))
1174 (while (let ((str2 (car c2)))
1175 (if (not (equal str str2))
1177 (when (eq anno 'unk)
1178 (setq anno (company-call-backend
1181 (company-call-backend
1182 'annotation str2))))
1186 (defun company--transform-candidates (candidates)
1187 (let ((c candidates))
1188 (dolist (tr company-transformers)
1189 (setq c (funcall tr c)))
1192 (defun company-sort-by-occurrence (candidates)
1193 "Sort CANDIDATES according to their occurrences.
1194 Searches for each in the currently visible part of the current buffer and
1195 gives priority to the closest ones above point, then closest ones below
1196 point. The rest of the list is appended unchanged.
1197 Keywords and function definition names are ignored."
1204 (progn (forward-char (- (length company-prefix)))
1205 (search-backward candidate (window-start) t)))
1207 (search-forward candidate (window-end) t)))
1208 (let ((beg (match-beginning 0))
1209 (end (match-end 0)))
1210 (when (save-excursion
1212 (and (not (memq (get-text-property (point) 'face)
1213 '(font-lock-function-name-face
1214 font-lock-keyword-face)))
1215 (let ((prefix (company--prefix-str
1216 (company-call-backend 'prefix))))
1217 (and (stringp prefix)
1218 (= (length prefix) (- end beg))))))
1219 (push (cons candidate (if (< beg (point))
1221 (- beg (window-start))))
1226 (mapcar #'car (sort occurs (lambda (e1 e2) (<= (cdr e1) (cdr e2)))))
1229 (defun company-sort-by-backend-importance (candidates)
1230 "Sort CANDIDATES as two priority groups.
1231 If `company-backend' is a function, do nothing. If it's a list, move
1232 candidates from back-ends before keyword `:with' to the front. Candidates
1233 from the rest of the back-ends in the group, if any, will be left at the end."
1234 (if (functionp company-backend)
1236 (let ((low-priority (cdr (memq :with company-backend))))
1237 (if (null low-priority)
1242 (let ((b2 (get-text-property 0 'company-backend c2)))
1243 (and b2 (memq b2 low-priority)))
1244 (let ((b1 (get-text-property 0 'company-backend c1)))
1245 (or (not b1) (not (memq b1 low-priority)))))))))))
1247 (defun company-idle-begin (buf win tick pos)
1248 (and (eq buf (current-buffer))
1249 (eq win (selected-window))
1250 (eq tick (buffer-chars-modified-tick))
1252 (when (company-auto-begin)
1253 (when (version< emacs-version "24.3.50")
1254 (company-input-noop))
1255 (company-post-command))))
1257 (defun company-auto-begin ()
1259 (not company-candidates)
1260 (let ((company-idle-delay t))
1261 (condition-case-unless-debug err
1263 (error (message "Company: An error occurred in auto-begin")
1264 (message "%s" (error-message-string err))
1266 (quit (company-cancel)))))
1267 (unless company-candidates
1268 (setq company-backend nil))
1269 ;; Return non-nil if active.
1272 (defun company-manual-begin ()
1274 (company-assert-enabled)
1275 (setq company--manual-action t)
1277 (let ((company-minimum-prefix-length 0))
1278 (company-auto-begin))
1279 (unless company-candidates
1280 (setq company--manual-action nil))))
1282 (defun company-other-backend (&optional backward)
1283 (interactive (list current-prefix-arg))
1284 (company-assert-enabled)
1285 (let* ((after (if company-backend
1286 (cdr (member company-backend company-backends))
1288 (before (cdr (member company-backend (reverse company-backends))))
1290 (append before (reverse after))
1291 (append after (reverse before)))))
1293 (cl-dolist (backend next)
1294 (when (ignore-errors (company-begin-backend backend))
1296 (unless company-candidates
1297 (error "No other back-end")))
1299 (defun company-require-match-p ()
1300 (let ((backend-value (company-call-backend 'require-match)))
1301 (or (eq backend-value t)
1302 (and (not (eq backend-value 'never))
1303 (if (functionp company-require-match)
1304 (funcall company-require-match)
1305 (eq company-require-match t))))))
1307 (defun company-auto-complete-p (input)
1308 "Return non-nil, if input starts with punctuation or parentheses."
1309 (and (if (functionp company-auto-complete)
1310 (funcall company-auto-complete)
1311 company-auto-complete)
1312 (if (functionp company-auto-complete-chars)
1313 (funcall company-auto-complete-chars input)
1314 (if (consp company-auto-complete-chars)
1315 (memq (char-syntax (string-to-char input))
1316 company-auto-complete-chars)
1317 (string-match (substring input 0 1) company-auto-complete-chars)))))
1319 (defun company--incremental-p ()
1320 (and (> (point) company-point)
1321 (> (point-max) company--point-max)
1322 (not (eq this-command 'backward-delete-char-untabify))
1323 (equal (buffer-substring (- company-point (length company-prefix))
1327 (defun company--continue-failed (new-prefix)
1328 (let ((input (buffer-substring-no-properties (point) company-point)))
1330 ((company-auto-complete-p input)
1333 (goto-char company-point)
1334 (let ((company--auto-completion t))
1335 (company-complete-selection))
1337 ((and (or (not (company-require-match-p))
1338 ;; Don't require match if the new prefix
1339 ;; doesn't continue the old one, and the latter was a match.
1340 (<= (length new-prefix) (length company-prefix)))
1341 (member company-prefix company-candidates))
1342 ;; Last input was a success,
1343 ;; but we're treating it as an abort + input anyway,
1344 ;; like the `unique' case below.
1345 (company-cancel 'non-unique))
1346 ((company-require-match-p)
1347 ;; Wrong incremental input, but required match.
1348 (delete-char (- (length input)))
1350 (message "Matching input is required")
1352 (t (company-cancel)))))
1354 (defun company--good-prefix-p (prefix)
1355 (and (stringp (company--prefix-str prefix)) ;excludes 'stop
1356 (or (eq (cdr-safe prefix) t)
1357 (let ((len (or (cdr-safe prefix) (length prefix))))
1358 (if company--manual-prefix
1359 (or (not company-abort-manual-when-too-short)
1360 ;; Must not be less than minimum or initial length.
1361 (>= len (min company-minimum-prefix-length
1362 (length company--manual-prefix))))
1363 (>= len company-minimum-prefix-length))))))
1365 (defun company--continue ()
1366 (when (company-call-backend 'no-cache company-prefix)
1367 ;; Don't complete existing candidates, fetch new ones.
1368 (setq company-candidates-cache nil))
1369 (let* ((new-prefix (company-call-backend 'prefix))
1370 (c (when (and (company--good-prefix-p new-prefix)
1371 (setq new-prefix (company--prefix-str new-prefix))
1372 (= (- (point) (length new-prefix))
1373 (- company-point (length company-prefix))))
1374 (company-calculate-candidates new-prefix))))
1377 ;; t means complete/unique.
1378 ;; Handle it like completion was aborted, to differentiate from user
1379 ;; calling one of Company's commands to insert the candidate,
1380 ;; not to trigger template expansion, etc.
1381 (company-cancel 'unique))
1383 ;; incremental match
1384 (setq company-prefix new-prefix)
1385 (company-update-candidates c)
1387 ((not (company--incremental-p))
1389 (t (company--continue-failed new-prefix)))))
1391 (defun company--begin-new ()
1393 (cl-dolist (backend (if company-backend
1394 ;; prefer manual override
1395 (list company-backend)
1398 (if (or (symbolp backend)
1399 (functionp backend))
1400 (when (or (not (symbolp backend))
1401 (eq t (get backend 'company-init))
1402 (unless (get backend 'company-init)
1403 (company-init-backend backend)))
1404 (funcall backend 'prefix))
1405 (company--multi-backend-adapter backend 'prefix)))
1407 (when (company--good-prefix-p prefix)
1408 (setq company-prefix (company--prefix-str prefix)
1409 company-backend backend
1410 c (company-calculate-candidates company-prefix))
1411 ;; t means complete/unique. We don't start, so no hooks.
1413 (when company--manual-action
1414 (message "No completion found"))
1415 (when company--manual-action
1416 (setq company--manual-prefix prefix))
1417 (if (symbolp backend)
1418 (setq company-lighter (concat " " (symbol-name backend)))
1419 (company--update-group-lighter (car c)))
1420 (company-update-candidates c)
1421 (run-hook-with-args 'company-completion-started-hook
1422 (company-explicit-action-p))
1423 (company-call-frontends 'show)))
1426 (defun company--perform ()
1427 (or (and company-candidates (company--continue))
1428 (and (company--should-complete) (company--begin-new)))
1429 (when company-candidates
1430 (let ((modified (buffer-modified-p)))
1431 (when (and company-end-of-buffer-workaround (eobp))
1432 (save-excursion (insert "\n"))
1433 (setq company-added-newline
1434 (or modified (buffer-chars-modified-tick)))))
1435 (setq company-point (point)
1436 company--point-max (point-max))
1437 (company-ensure-emulation-alist)
1438 (company-enable-overriding-keymap company-active-map)
1439 (company-call-frontends 'update)))
1441 (defun company-cancel (&optional result)
1442 (and company-added-newline
1443 (> (point-max) (point-min))
1444 (let ((tick (buffer-chars-modified-tick)))
1445 (delete-region (1- (point-max)) (point-max))
1446 (equal tick company-added-newline))
1447 ;; Only set unmodified when tick remained the same since insert,
1448 ;; and the buffer wasn't modified before.
1449 (set-buffer-modified-p nil))
1451 (when company-prefix
1452 (if (stringp result)
1454 (company-call-backend 'pre-completion result)
1455 (run-hook-with-args 'company-completion-finished-hook result)
1456 (company-call-backend 'post-completion result))
1457 (run-hook-with-args 'company-completion-cancelled-hook result)))
1458 (setq company-added-newline nil
1461 company-candidates nil
1462 company-candidates-length nil
1463 company-candidates-cache nil
1464 company-candidates-predicate nil
1467 company-selection-changed nil
1468 company--manual-action nil
1469 company--manual-prefix nil
1470 company-lighter company-default-lighter
1471 company--point-max nil
1474 (cancel-timer company-timer))
1475 (company-search-mode 0)
1476 (company-call-frontends 'hide)
1477 (company-enable-overriding-keymap nil))
1478 ;; Make return value explicit.
1481 (defun company-abort ()
1483 (company-cancel 'abort))
1485 (defun company-finish (result)
1486 (company--insert-candidate result)
1487 (company-cancel result))
1489 (defsubst company-keep (command)
1490 (and (symbolp command) (get command 'company-keep)))
1492 (defun company-pre-command ()
1493 (unless (company-keep this-command)
1495 (when company-candidates
1496 (company-call-frontends 'pre-command)
1497 (unless (company--should-continue)
1499 (error (message "Company: An error occurred in pre-command")
1500 (message "%s" (error-message-string err))
1503 (cancel-timer company-timer)
1504 (setq company-timer nil))
1505 (company-uninstall-map))
1507 (defun company-post-command ()
1508 (unless (company-keep this-command)
1511 (unless (equal (point) company-point)
1512 (let ((company-idle-delay (and (eq company-idle-delay t)
1513 (company--should-begin)
1515 (company--perform)))
1516 (if company-candidates
1517 (company-call-frontends 'post-command)
1518 (and (numberp company-idle-delay)
1519 (company--should-begin)
1521 (run-with-timer company-idle-delay nil
1523 (current-buffer) (selected-window)
1524 (buffer-chars-modified-tick) (point))))))
1525 (error (message "Company: An error occurred in post-command")
1526 (message "%s" (error-message-string err))
1528 (company-install-map))
1530 (defvar company--begin-inhibit-commands '(company-abort
1531 company-complete-mouse
1533 company-complete-common
1534 company-complete-selection
1535 company-complete-number)
1536 "List of commands after which idle completion is (still) disabled when
1537 `company-begin-commands' is t.")
1539 (defun company--should-begin ()
1540 (if (eq t company-begin-commands)
1541 (not (memq this-command company--begin-inhibit-commands))
1543 (memq this-command company-begin-commands)
1544 (and (symbolp this-command) (get this-command 'company-begin)))))
1546 ;;; search ;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;
1548 (defvar-local company-search-string nil)
1550 (defvar-local company-search-lighter " Search: \"\"")
1552 (defvar-local company-search-old-map nil)
1554 (defvar-local company-search-old-selection 0)
1556 (defun company-search (text lines)
1557 (let ((quoted (regexp-quote text))
1559 (cl-dolist (line lines)
1560 (when (string-match quoted line (length company-prefix))
1564 (defun company-search-printing-char ()
1566 (company-search-assert-enabled)
1567 (setq company-search-string
1568 (concat (or company-search-string "") (string last-command-event))
1569 company-search-lighter (concat " Search: \"" company-search-string
1571 (let ((pos (company-search company-search-string
1572 (nthcdr company-selection company-candidates))))
1575 (company-set-selection (+ company-selection pos) t))))
1577 (defun company-search-repeat-forward ()
1578 "Repeat the incremental search in completion candidates forward."
1580 (company-search-assert-enabled)
1581 (let ((pos (company-search company-search-string
1582 (cdr (nthcdr company-selection
1583 company-candidates)))))
1586 (company-set-selection (+ company-selection pos 1) t))))
1588 (defun company-search-repeat-backward ()
1589 "Repeat the incremental search in completion candidates backwards."
1591 (company-search-assert-enabled)
1592 (let ((pos (company-search company-search-string
1593 (nthcdr (- company-candidates-length
1595 (reverse company-candidates)))))
1598 (company-set-selection (- company-selection pos 1) t))))
1600 (defun company-create-match-predicate ()
1601 (setq company-candidates-predicate
1602 `(lambda (candidate)
1603 ,(if company-candidates-predicate
1604 `(and (string-match ,company-search-string candidate)
1605 (funcall ,company-candidates-predicate
1607 `(string-match ,company-search-string candidate))))
1608 (company-update-candidates
1609 (company-apply-predicate company-candidates company-candidates-predicate))
1610 ;; Invalidate cache.
1611 (setq company-candidates-cache (cons company-prefix company-candidates)))
1613 (defun company-filter-printing-char ()
1615 (company-search-assert-enabled)
1616 (company-search-printing-char)
1617 (company-create-match-predicate)
1618 (company-call-frontends 'update))
1620 (defun company-search-kill-others ()
1621 "Limit the completion candidates to the ones matching the search string."
1623 (company-search-assert-enabled)
1624 (company-create-match-predicate)
1625 (company-search-mode 0)
1626 (company-call-frontends 'update))
1628 (defun company-search-abort ()
1629 "Abort searching the completion candidates."
1631 (company-search-assert-enabled)
1632 (company-set-selection company-search-old-selection t)
1633 (company-search-mode 0))
1635 (defun company-search-other-char ()
1637 (company-search-assert-enabled)
1638 (company-search-mode 0)
1639 (company--unread-last-input))
1641 (defvar company-search-map
1643 (keymap (make-keymap)))
1644 (if (fboundp 'max-char)
1645 (set-char-table-range (nth 1 keymap) (cons #x100 (max-char))
1646 'company-search-printing-char)
1648 ;; obsolete in Emacs 23
1649 (let ((l (generic-character-list))
1650 (table (nth 1 keymap)))
1652 (set-char-table-default table (car l) 'company-search-printing-char)
1653 (setq l (cdr l))))))
1654 (define-key keymap [t] 'company-search-other-char)
1656 (define-key keymap (make-string 1 i) 'company-search-other-char)
1659 (define-key keymap (vector i) 'company-search-printing-char)
1661 (let ((meta-map (make-sparse-keymap)))
1662 (define-key keymap (char-to-string meta-prefix-char) meta-map)
1663 (define-key keymap [escape] meta-map))
1664 (define-key keymap (vector meta-prefix-char t) 'company-search-other-char)
1665 (define-key keymap "\e\e\e" 'company-search-other-char)
1666 (define-key keymap [escape escape escape] 'company-search-other-char)
1667 (define-key keymap (kbd "DEL") 'company-search-other-char)
1669 (define-key keymap "\C-g" 'company-search-abort)
1670 (define-key keymap "\C-s" 'company-search-repeat-forward)
1671 (define-key keymap "\C-r" 'company-search-repeat-backward)
1672 (define-key keymap "\C-o" 'company-search-kill-others)
1674 "Keymap used for incrementally searching the completion candidates.")
1676 (define-minor-mode company-search-mode
1677 "Search mode for completion candidates.
1678 Don't start this directly, use `company-search-candidates' or
1679 `company-filter-candidates'."
1680 nil company-search-lighter nil
1681 (if company-search-mode
1682 (if (company-manual-begin)
1684 (setq company-search-old-selection company-selection)
1685 (company-call-frontends 'update))
1686 (setq company-search-mode nil))
1687 (kill-local-variable 'company-search-string)
1688 (kill-local-variable 'company-search-lighter)
1689 (kill-local-variable 'company-search-old-selection)
1690 (company-enable-overriding-keymap company-active-map)))
1692 (defun company-search-assert-enabled ()
1693 (company-assert-enabled)
1694 (unless company-search-mode
1695 (company-uninstall-map)
1696 (error "Company not in search mode")))
1698 (defun company-search-candidates ()
1699 "Start searching the completion candidates incrementally.
1701 \\<company-search-map>Search can be controlled with the commands:
1702 - `company-search-repeat-forward' (\\[company-search-repeat-forward])
1703 - `company-search-repeat-backward' (\\[company-search-repeat-backward])
1704 - `company-search-abort' (\\[company-search-abort])
1706 Regular characters are appended to the search string.
1708 The command `company-search-kill-others' (\\[company-search-kill-others])
1709 uses the search string to limit the completion candidates."
1711 (company-search-mode 1)
1712 (company-enable-overriding-keymap company-search-map))
1714 (defvar company-filter-map
1715 (let ((keymap (make-keymap)))
1716 (define-key keymap [remap company-search-printing-char]
1717 'company-filter-printing-char)
1718 (set-keymap-parent keymap company-search-map)
1720 "Keymap used for incrementally searching the completion candidates.")
1722 (defun company-filter-candidates ()
1723 "Start filtering the completion candidates incrementally.
1724 This works the same way as `company-search-candidates' immediately
1725 followed by `company-search-kill-others' after each input."
1727 (company-search-mode 1)
1728 (company-enable-overriding-keymap company-filter-map))
1730 ;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;
1732 (defun company-select-next ()
1733 "Select the next candidate in the list."
1735 (when (company-manual-begin)
1736 (company-set-selection (1+ company-selection))))
1738 (defun company-select-previous ()
1739 "Select the previous candidate in the list."
1741 (when (company-manual-begin)
1742 (company-set-selection (1- company-selection))))
1744 (defun company-select-next-or-abort ()
1745 "Select the next candidate if more than one, else abort
1746 and invoke the normal binding."
1748 (if (> company-candidates-length 1)
1749 (company-select-next)
1751 (company--unread-last-input)))
1753 (defun company-select-previous-or-abort ()
1754 "Select the previous candidate if more than one, else abort
1755 and invoke the normal binding."
1757 (if (> company-candidates-length 1)
1758 (company-select-previous)
1760 (company--unread-last-input)))
1762 (defvar company-pseudo-tooltip-overlay)
1764 (defvar company-tooltip-offset)
1766 (defun company--inside-tooltip-p (event-col-row row height)
1767 (let* ((ovl company-pseudo-tooltip-overlay)
1768 (column (overlay-get ovl 'company-column))
1769 (width (overlay-get ovl 'company-width))
1770 (evt-col (car event-col-row))
1771 (evt-row (cdr event-col-row)))
1772 (and (>= evt-col column)
1773 (< evt-col (+ column width))
1775 (and (> evt-row row)
1776 (<= evt-row (+ row height) ))
1777 (and (< evt-row row)
1778 (>= evt-row (+ row height)))))))
1780 (defun company--event-col-row (event)
1781 (let* ((col-row (posn-actual-col-row (event-start event)))
1783 (row (cdr col-row)))
1784 (cl-incf col (window-hscroll))
1785 (and header-line-format
1786 (version< "24" emacs-version)
1790 (defun company-select-mouse (event)
1791 "Select the candidate picked by the mouse."
1793 (let ((event-col-row (company--event-col-row event))
1794 (ovl-row (company--row))
1795 (ovl-height (and company-pseudo-tooltip-overlay
1796 (min (overlay-get company-pseudo-tooltip-overlay
1798 company-candidates-length))))
1800 (company--inside-tooltip-p event-col-row ovl-row ovl-height))
1802 (company-set-selection (+ (cdr event-col-row)
1803 (1- company-tooltip-offset)
1804 (if (and (eq company-tooltip-offset-display 'lines)
1805 (not (zerop company-tooltip-offset)))
1808 (if (< ovl-height 0)
1813 (company--unread-last-input)
1816 (defun company-complete-mouse (event)
1817 "Insert the candidate picked by the mouse."
1819 (when (company-select-mouse event)
1820 (company-complete-selection)))
1822 (defun company-complete-selection ()
1823 "Insert the selected candidate."
1825 (when (company-manual-begin)
1826 (let ((result (nth company-selection company-candidates)))
1827 (company-finish result))))
1829 (defun company-complete-common ()
1830 "Insert the common part of all candidates."
1832 (when (company-manual-begin)
1833 (if (and (not (cdr company-candidates))
1834 (equal company-common (car company-candidates)))
1835 (company-complete-selection)
1836 (when company-common
1837 (company--insert-candidate company-common)))))
1839 (defun company-complete ()
1840 "Insert the common part of all candidates or the current selection.
1841 The first time this is called, the common part is inserted, the second
1842 time, or when the selection has been changed, the selected candidate is
1845 (when (company-manual-begin)
1846 (if (or company-selection-changed
1847 (eq last-command 'company-complete-common))
1848 (call-interactively 'company-complete-selection)
1849 (call-interactively 'company-complete-common)
1850 (setq this-command 'company-complete-common))))
1852 (defun company-complete-number (n)
1853 "Insert the Nth candidate.
1854 To show the number next to the candidates in some back-ends, enable
1855 `company-show-numbers'."
1856 (when (company-manual-begin)
1857 (and (or (< n 1) (> n company-candidates-length))
1858 (error "No candidate number %d" n))
1860 (company-finish (nth n company-candidates))))
1862 ;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;
1864 (defconst company-space-strings-limit 100)
1866 (defconst company-space-strings
1868 (dotimes (i company-space-strings-limit)
1869 (push (make-string (- company-space-strings-limit 1 i) ?\ ) lst))
1870 (apply 'vector lst)))
1872 (defun company-space-string (len)
1873 (if (< len company-space-strings-limit)
1874 (aref company-space-strings len)
1875 (make-string len ?\ )))
1877 (defun company-safe-substring (str from &optional to)
1878 (if (> from (string-width str))
1882 (move-to-column from)
1883 (let ((beg (point)))
1887 (concat (buffer-substring beg (point))
1888 (let ((padding (- to (current-column))))
1890 (company-space-string padding)))))
1891 (buffer-substring beg (point-max)))))))
1893 ;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;
1895 (defvar-local company-last-metadata nil)
1897 (defun company-fetch-metadata ()
1898 (let ((selected (nth company-selection company-candidates)))
1899 (unless (eq selected (car company-last-metadata))
1900 (setq company-last-metadata
1901 (cons selected (company-call-backend 'meta selected))))
1902 (cdr company-last-metadata)))
1904 (defun company-doc-buffer (&optional string)
1905 (with-current-buffer (get-buffer-create "*company-documentation*")
1912 (defvar company--electric-commands
1913 '(scroll-other-window scroll-other-window-down)
1914 "List of Commands that won't break out of electric commands.")
1916 (defmacro company--electric-do (&rest body)
1917 (declare (indent 0) (debug t))
1918 `(when (company-manual-begin)
1919 (save-window-excursion
1920 (let ((height (window-height))
1921 (row (company--row))
1924 (and (< (window-height) height)
1925 (< (- (window-height) row 2) company-tooltip-limit)
1926 (recenter (- (window-height) row 2)))
1927 (while (memq (setq cmd (key-binding (vector (list (read-event)))))
1928 company--electric-commands)
1929 (call-interactively cmd))
1930 (company--unread-last-input)))))
1932 (defun company--unread-last-input ()
1933 (when last-input-event
1934 (clear-this-command-keys t)
1935 (setq unread-command-events (list last-input-event))))
1937 (defun company-show-doc-buffer ()
1938 "Temporarily show the documentation buffer for the selection."
1940 (company--electric-do
1941 (let* ((selected (nth company-selection company-candidates))
1942 (doc-buffer (or (company-call-backend 'doc-buffer selected)
1943 (error "No documentation available"))))
1944 (with-current-buffer doc-buffer
1945 (goto-char (point-min)))
1946 (display-buffer doc-buffer t))))
1947 (put 'company-show-doc-buffer 'company-keep t)
1949 (defun company-show-location ()
1950 "Temporarily display a buffer showing the selected candidate in context."
1952 (company--electric-do
1953 (let* ((selected (nth company-selection company-candidates))
1954 (location (company-call-backend 'location selected))
1955 (pos (or (cdr location) (error "No location available")))
1956 (buffer (or (and (bufferp (car location)) (car location))
1957 (find-file-noselect (car location) t))))
1958 (with-selected-window (display-buffer buffer t)
1961 (if (bufferp (car location))
1963 (goto-char (point-min))
1964 (forward-line (1- pos))))
1965 (set-window-start nil (point))))))
1966 (put 'company-show-location 'company-keep t)
1968 ;;; package functions ;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;
1970 (defvar-local company-callback nil)
1972 (defun company-remove-callback (&optional ignored)
1973 (remove-hook 'company-completion-finished-hook company-callback t)
1974 (remove-hook 'company-completion-cancelled-hook 'company-remove-callback t)
1975 (remove-hook 'company-completion-finished-hook 'company-remove-callback t))
1977 (defun company-begin-backend (backend &optional callback)
1978 "Start a completion at point using BACKEND."
1979 (interactive (let ((val (completing-read "Company back-end: "
1981 'functionp nil "company-")))
1983 (list (intern val)))))
1984 (when (setq company-callback callback)
1985 (add-hook 'company-completion-finished-hook company-callback nil t))
1986 (add-hook 'company-completion-cancelled-hook 'company-remove-callback nil t)
1987 (add-hook 'company-completion-finished-hook 'company-remove-callback nil t)
1988 (setq company-backend backend)
1989 ;; Return non-nil if active.
1990 (or (company-manual-begin)
1991 (error "Cannot complete at point")))
1993 (defun company-begin-with (candidates
1994 &optional prefix-length require-match callback)
1995 "Start a completion at point.
1996 CANDIDATES is the list of candidates to use and PREFIX-LENGTH is the length
1997 of the prefix that already is in the buffer before point.
2000 CALLBACK is a function called with the selected result if the user
2001 successfully completes the input.
2003 Example: \(company-begin-with '\(\"foo\" \"foobar\" \"foobarbaz\"\)\)"
2004 (let ((begin-marker (copy-marker (point) t)))
2005 (company-begin-backend
2006 (lambda (command &optional arg &rest ignored)
2009 (when (equal (point) (marker-position begin-marker))
2010 (buffer-substring (- (point) (or prefix-length 0)) (point))))
2012 (all-completions arg candidates))
2017 (defun company-version (&optional show-version)
2018 "Get the Company version as string.
2020 If SHOW-VERSION is non-nil, show the version in the echo area."
2021 (interactive (list t))
2023 (insert-file-contents (find-library-name "company"))
2026 (message "Company version: %s" (lm-version))
2029 ;;; pseudo-tooltip ;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;
2031 (defvar-local company-pseudo-tooltip-overlay nil)
2033 (defvar-local company-tooltip-offset 0)
2035 (defun company-tooltip--lines-update-offset (selection num-lines limit)
2037 (setq company-tooltip-offset
2038 (max (min selection company-tooltip-offset)
2039 (- selection -1 limit)))
2041 (when (<= company-tooltip-offset 1)
2043 (setq company-tooltip-offset 0))
2045 (when (>= company-tooltip-offset (- num-lines limit 1))
2047 (when (= selection (1- num-lines))
2048 (cl-decf company-tooltip-offset)
2049 (when (<= company-tooltip-offset 1)
2050 (setq company-tooltip-offset 0)
2055 (defun company-tooltip--simple-update-offset (selection _num-lines limit)
2056 (setq company-tooltip-offset
2057 (if (< selection company-tooltip-offset)
2059 (max company-tooltip-offset
2060 (- selection limit -1)))))
2064 (defsubst company-round-tab (arg)
2065 (* (/ (+ arg tab-width) tab-width) tab-width))
2067 (defun company-plainify (str)
2068 (let ((prefix (get-text-property 0 'line-prefix str)))
2069 (when prefix ; Keep the original value unmodified, for no special reason.
2070 (setq str (concat prefix str))
2071 (remove-text-properties 0 (length str) '(line-prefix) str)))
2072 (let* ((pieces (split-string str "\t"))
2075 (setcar copy (company-safe-substring
2076 (car copy) 0 (company-round-tab (string-width (car copy)))))
2078 (apply 'concat pieces)))
2080 (defun company-fill-propertize (value annotation width selected left right)
2081 (let* ((margin (length left))
2082 (common (+ (or (company-call-backend 'match value)
2083 (length company-common)) margin))
2084 (ann-ralign company-tooltip-align-annotations)
2085 (ann-truncate (< width
2086 (+ (length value) (length annotation)
2087 (if ann-ralign 1 0))))
2088 (ann-start (+ margin
2092 (- width (length annotation)))
2094 (ann-end (min (+ ann-start (length annotation)) (+ margin width)))
2096 (if (or ann-truncate (not ann-ralign))
2097 (company-safe-substring
2099 (when (and annotation ann-ralign) " ")
2103 (company-safe-substring value 0
2104 (- width (length annotation)))
2107 (setq width (+ width margin (length right)))
2109 (add-text-properties 0 width '(face company-tooltip
2110 mouse-face company-tooltip-mouse)
2112 (add-text-properties margin common
2113 '(face company-tooltip-common
2114 mouse-face company-tooltip-mouse)
2116 (when (< ann-start ann-end)
2117 (add-text-properties ann-start ann-end
2118 '(face company-tooltip-annotation
2119 mouse-face company-tooltip-mouse)
2122 (if (and company-search-string
2123 (string-match (regexp-quote company-search-string) value
2124 (length company-prefix)))
2125 (let ((beg (+ margin (match-beginning 0)))
2126 (end (+ margin (match-end 0))))
2127 (add-text-properties beg end '(face company-tooltip-selection)
2129 (when (< beg common)
2130 (add-text-properties beg common
2131 '(face company-tooltip-common-selection)
2133 (add-text-properties 0 width '(face company-tooltip-selection
2134 mouse-face company-tooltip-selection)
2136 (add-text-properties margin common
2137 '(face company-tooltip-common-selection
2138 mouse-face company-tooltip-selection)
2144 (defun company-buffer-lines (beg end)
2147 (while (and (= 1 (vertical-motion 1))
2149 (let ((bound (min end (1- (point)))))
2150 ;; A visual line can contain several physical lines (e.g. with outline's
2151 ;; folding overlay). Take only the first one.
2152 (push (buffer-substring beg
2155 (re-search-forward "$" bound 'move)
2159 (unless (eq beg end)
2160 (push (buffer-substring beg end) lines))
2163 (defun company-modify-line (old new offset)
2164 (concat (company-safe-substring old 0 offset)
2166 (company-safe-substring old (+ offset (length new)))))
2168 (defsubst company--length-limit (lst limit)
2169 (if (nthcdr limit lst)
2173 (defun company--replacement-string (lines old column nl &optional align-top)
2174 (cl-decf column company-tooltip-margin)
2176 (when (and align-top company-tooltip-flip-when-above)
2177 (setq lines (reverse lines)))
2179 (let ((width (length (car lines)))
2180 (remaining-cols (- (+ (company--window-width) (window-hscroll))
2182 (when (> width remaining-cols)
2183 (cl-decf column (- width remaining-cols))))
2185 (let ((offset (and (< column 0) (- column)))
2190 ;; untouched lines first
2191 (dotimes (_ (- (length old) (length lines)))
2192 (push (pop old) new)))
2193 ;; length into old lines.
2195 (push (company-modify-line (pop old)
2196 (company--offset-line (pop lines) offset)
2198 ;; Append whole new lines.
2200 (push (concat (company-space-string column)
2201 (company--offset-line (pop lines) offset))
2204 (let ((str (concat (when nl "\n")
2205 (mapconcat 'identity (nreverse new) "\n")
2207 (font-lock-append-text-property 0 (length str) 'face 'default str)
2210 (defun company--offset-line (line offset)
2211 (if (and offset line)
2212 (substring line offset)
2215 (defun company--create-lines (selection limit)
2216 (let ((len company-candidates-length)
2218 (window-width (company--window-width))
2227 ;; Maybe clear old offset.
2228 (when (< len (+ company-tooltip-offset limit))
2229 (setq company-tooltip-offset 0))
2231 ;; Scroll to offset.
2232 (if (eq company-tooltip-offset-display 'lines)
2233 (setq limit (company-tooltip--lines-update-offset selection len limit))
2234 (company-tooltip--simple-update-offset selection len limit))
2237 ((eq company-tooltip-offset-display 'scrollbar)
2238 (setq scrollbar-bounds (company--scrollbar-bounds company-tooltip-offset
2240 ((eq company-tooltip-offset-display 'lines)
2241 (when (> company-tooltip-offset 0)
2242 (setq previous (format "...(%d)" company-tooltip-offset)))
2243 (setq remainder (- len limit company-tooltip-offset)
2244 remainder (when (> remainder 0)
2245 (setq remainder (format "...(%d)" remainder))))))
2247 (cl-decf selection company-tooltip-offset)
2248 (setq width (max (length previous) (length remainder))
2249 lines (nthcdr company-tooltip-offset company-candidates)
2253 (cl-decf window-width (* 2 company-tooltip-margin))
2254 (when scrollbar-bounds (cl-decf window-width))
2257 (let* ((value (pop lines-copy))
2258 (annotation (company-call-backend 'annotation value)))
2259 (when (and annotation company-tooltip-align-annotations)
2260 ;; `lisp-completion-at-point' adds a space.
2261 (setq annotation (comment-string-strip annotation t nil)))
2262 (push (cons value annotation) items)
2263 (setq width (max (+ (length value)
2264 (if (and annotation company-tooltip-align-annotations)
2265 (1+ (length annotation))
2266 (length annotation)))
2269 (setq width (min window-width
2270 (max company-tooltip-minimum-width
2271 (if (and company-show-numbers
2272 (< company-tooltip-offset 10))
2276 ;; number can make tooltip too long
2277 (when company-show-numbers
2278 (setq numbered company-tooltip-offset))
2280 (let ((items (nreverse items)) new)
2282 (push (company--scrollpos-line previous width) new))
2285 (let* ((item (pop items))
2286 (str (company-reformat (car item)))
2287 (annotation (cdr item))
2288 (right (company-space-string company-tooltip-margin))
2290 (when (< numbered 10)
2293 (setq right (concat (format " %d" (mod numbered 10)) right)))
2295 (company-fill-propertize str annotation
2296 width (equal i selection)
2297 (company-space-string
2298 company-tooltip-margin)
2300 (when scrollbar-bounds
2301 (company--scrollbar i scrollbar-bounds)))
2305 (push (company--scrollpos-line remainder width) new))
2309 (defun company--scrollbar-bounds (offset limit length)
2310 (when (> length limit)
2311 (let* ((size (ceiling (* limit (float limit)) length))
2312 (lower (floor (* limit (float offset)) length))
2313 (upper (+ lower size -1)))
2314 (cons lower upper))))
2316 (defun company--scrollbar (i bounds)
2317 (propertize " " 'face
2318 (if (and (>= i (car bounds)) (<= i (cdr bounds)))
2319 'company-scrollbar-fg
2320 'company-scrollbar-bg)))
2322 (defun company--scrollpos-line (text width)
2323 (propertize (concat (company-space-string company-tooltip-margin)
2324 (company-safe-substring text 0 width)
2325 (company-space-string company-tooltip-margin))
2326 'face 'company-tooltip))
2330 (defsubst company--window-inner-height ()
2331 (let ((edges (window-inside-edges)))
2332 (- (nth 3 edges) (nth 1 edges))))
2334 (defsubst company--window-width ()
2335 (let ((ww (window-width)))
2336 ;; Account for the line continuation column.
2337 (when (zerop (cadr (window-fringes)))
2339 (unless (or (display-graphic-p)
2340 (version< "24.3.1" emacs-version))
2341 ;; Emacs 24.3 and earlier included margins
2342 ;; in window-width when in TTY.
2344 (let ((margins (window-margins)))
2345 (+ (or (car margins) 0)
2346 (or (cdr margins) 0)))))
2349 (defun company--pseudo-tooltip-height ()
2350 "Calculate the appropriate tooltip height.
2351 Returns a negative number if the tooltip should be displayed above point."
2352 (let* ((lines (company--row))
2353 (below (- (company--window-inner-height) 1 lines)))
2354 (if (and (< below (min company-tooltip-minimum company-candidates-length))
2356 (- (max 3 (min company-tooltip-limit lines)))
2357 (max 3 (min company-tooltip-limit below)))))
2359 (defun company-pseudo-tooltip-show (row column selection)
2360 (company-pseudo-tooltip-hide)
2363 (let* ((height (company--pseudo-tooltip-height))
2367 (setq row (+ row height -1)
2370 (let* ((nl (< (move-to-window-line row) row))
2372 (end (save-excursion
2373 (move-to-window-line (+ row (abs height)))
2375 (ov (make-overlay beg end))
2376 (args (list (mapcar 'company-plainify
2377 (company-buffer-lines beg end))
2380 (setq company-pseudo-tooltip-overlay ov)
2381 (overlay-put ov 'company-replacement-args args)
2383 (let ((lines (company--create-lines selection (abs height))))
2384 (overlay-put ov 'company-after
2385 (apply 'company--replacement-string lines args))
2386 (overlay-put ov 'company-width (string-width (car lines))))
2388 (overlay-put ov 'company-column column)
2389 (overlay-put ov 'company-height height)))))
2391 (defun company-pseudo-tooltip-show-at-point (pos)
2392 (let ((row (company--row pos))
2393 (col (company--column pos)))
2394 (company-pseudo-tooltip-show (1+ row) col company-selection)))
2396 (defun company-pseudo-tooltip-edit (selection)
2397 (let* ((height (overlay-get company-pseudo-tooltip-overlay 'company-height))
2398 (lines (company--create-lines selection (abs height))))
2399 (overlay-put company-pseudo-tooltip-overlay 'company-width
2400 (string-width (car lines)))
2401 (overlay-put company-pseudo-tooltip-overlay 'company-after
2402 (apply 'company--replacement-string
2404 (overlay-get company-pseudo-tooltip-overlay
2405 'company-replacement-args)))))
2407 (defun company-pseudo-tooltip-hide ()
2408 (when company-pseudo-tooltip-overlay
2409 (delete-overlay company-pseudo-tooltip-overlay)
2410 (setq company-pseudo-tooltip-overlay nil)))
2412 (defun company-pseudo-tooltip-hide-temporarily ()
2413 (when (overlayp company-pseudo-tooltip-overlay)
2414 (overlay-put company-pseudo-tooltip-overlay 'invisible nil)
2415 (overlay-put company-pseudo-tooltip-overlay 'line-prefix nil)
2416 (overlay-put company-pseudo-tooltip-overlay 'after-string nil)))
2418 (defun company-pseudo-tooltip-unhide ()
2419 (when company-pseudo-tooltip-overlay
2420 (overlay-put company-pseudo-tooltip-overlay 'invisible t)
2421 ;; Beat outline's folding overlays, at least.
2422 (overlay-put company-pseudo-tooltip-overlay 'priority 1)
2423 ;; No (extra) prefix for the first line.
2424 (overlay-put company-pseudo-tooltip-overlay 'line-prefix "")
2425 (overlay-put company-pseudo-tooltip-overlay 'after-string
2426 (overlay-get company-pseudo-tooltip-overlay 'company-after))
2427 (overlay-put company-pseudo-tooltip-overlay 'window (selected-window))))
2429 (defun company-pseudo-tooltip-guard ()
2430 (buffer-substring-no-properties
2431 (point) (overlay-start company-pseudo-tooltip-overlay)))
2433 (defun company-pseudo-tooltip-frontend (command)
2434 "`company-mode' front-end similar to a tooltip but based on overlays."
2436 (pre-command (company-pseudo-tooltip-hide-temporarily))
2438 (let ((old-height (if (overlayp company-pseudo-tooltip-overlay)
2439 (overlay-get company-pseudo-tooltip-overlay
2442 (new-height (company--pseudo-tooltip-height)))
2443 (unless (and (>= (* old-height new-height) 0)
2444 (>= (abs old-height) (abs new-height))
2445 (equal (company-pseudo-tooltip-guard)
2446 (overlay-get company-pseudo-tooltip-overlay
2449 (company-pseudo-tooltip-show-at-point (- (point)
2450 (length company-prefix)))
2451 (overlay-put company-pseudo-tooltip-overlay
2452 'company-guard (company-pseudo-tooltip-guard))))
2453 (company-pseudo-tooltip-unhide))
2454 (hide (company-pseudo-tooltip-hide)
2455 (setq company-tooltip-offset 0))
2456 (update (when (overlayp company-pseudo-tooltip-overlay)
2457 (company-pseudo-tooltip-edit company-selection)))))
2459 (defun company-pseudo-tooltip-unless-just-one-frontend (command)
2460 "`company-pseudo-tooltip-frontend', but not shown for single candidates."
2461 (unless (and (eq command 'post-command)
2462 (company--show-inline-p))
2463 (company-pseudo-tooltip-frontend command)))
2465 ;;; overlay ;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;
2467 (defvar-local company-preview-overlay nil)
2469 (defun company-preview-show-at-point (pos)
2470 (company-preview-hide)
2472 (setq company-preview-overlay (make-overlay pos (1+ pos)))
2474 (let ((completion (nth company-selection company-candidates)))
2475 (setq completion (propertize completion 'face 'company-preview))
2476 (add-text-properties 0 (length company-common)
2477 '(face company-preview-common) completion)
2479 ;; Add search string
2480 (and company-search-string
2481 (string-match (regexp-quote company-search-string) completion)
2482 (add-text-properties (match-beginning 0)
2484 '(face company-preview-search)
2487 (setq completion (company-strip-prefix completion))
2489 (and (equal pos (point))
2490 (not (equal completion ""))
2491 (add-text-properties 0 1 '(cursor t) completion))
2493 (overlay-put company-preview-overlay 'display
2494 (concat completion (unless (eq pos (point-max))
2495 (buffer-substring pos (1+ pos)))))
2496 (overlay-put company-preview-overlay 'window (selected-window))))
2498 (defun company-preview-hide ()
2499 (when company-preview-overlay
2500 (delete-overlay company-preview-overlay)
2501 (setq company-preview-overlay nil)))
2503 (defun company-preview-frontend (command)
2504 "`company-mode' front-end showing the selection as if it had been inserted."
2506 (`pre-command (company-preview-hide))
2507 (`post-command (company-preview-show-at-point (point)))
2508 (`hide (company-preview-hide))))
2510 (defun company-preview-if-just-one-frontend (command)
2511 "`company-preview-frontend', but only shown for single candidates."
2512 (when (or (not (eq command 'post-command))
2513 (company--show-inline-p))
2514 (company-preview-frontend command)))
2516 (defun company--show-inline-p ()
2517 (and (not (cdr company-candidates))
2519 (string-prefix-p company-prefix company-common
2520 (company-call-backend 'ignore-case))))
2522 ;;; echo ;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;
2524 (defvar-local company-echo-last-msg nil)
2526 (defvar company-echo-timer nil)
2528 (defvar company-echo-delay .01)
2530 (defun company-echo-show (&optional getter)
2532 (setq company-echo-last-msg (funcall getter)))
2533 (let ((message-log-max nil))
2534 (if company-echo-last-msg
2535 (message "%s" company-echo-last-msg)
2538 (defun company-echo-show-soon (&optional getter)
2539 (when company-echo-timer
2540 (cancel-timer company-echo-timer))
2541 (setq company-echo-timer (run-with-timer 0 nil 'company-echo-show getter)))
2543 (defsubst company-echo-show-when-idle (&optional getter)
2544 (when (sit-for company-echo-delay)
2545 (company-echo-show getter)))
2547 (defun company-echo-format ()
2549 (let ((limit (window-width (minibuffer-window)))
2551 ;; Roll to selection.
2552 (candidates (nthcdr company-selection company-candidates))
2553 (i (if company-show-numbers company-selection 99999))
2557 (setq comp (company-reformat (pop candidates))
2558 len (+ len 1 (length comp)))
2562 (setq comp (propertize (format "%d: %s" i comp)
2563 'face 'company-echo))
2566 (add-text-properties 3 (+ 3 (length company-common))
2567 '(face company-echo-common) comp))
2568 (setq comp (propertize comp 'face 'company-echo))
2569 (add-text-properties 0 (length company-common)
2570 '(face company-echo-common) comp))
2572 (setq candidates nil)
2575 (mapconcat 'identity (nreverse msg) " ")))
2577 (defun company-echo-strip-common-format ()
2579 (let ((limit (window-width (minibuffer-window)))
2580 (len (+ (length company-prefix) 2))
2581 ;; Roll to selection.
2582 (candidates (nthcdr company-selection company-candidates))
2583 (i (if company-show-numbers company-selection 99999))
2587 (setq comp (company-strip-prefix (pop candidates))
2588 len (+ len 2 (length comp)))
2591 (setq comp (format "%s (%d)" comp i))
2595 (setq candidates nil)
2596 (push (propertize comp 'face 'company-echo) msg)))
2598 (concat (propertize company-prefix 'face 'company-echo-common) "{"
2599 (mapconcat 'identity (nreverse msg) ", ")
2602 (defun company-echo-hide ()
2603 (unless (equal company-echo-last-msg "")
2604 (setq company-echo-last-msg "")
2605 (company-echo-show)))
2607 (defun company-echo-frontend (command)
2608 "`company-mode' front-end showing the candidates in the echo area."
2610 (`post-command (company-echo-show-soon 'company-echo-format))
2611 (`hide (company-echo-hide))))
2613 (defun company-echo-strip-common-frontend (command)
2614 "`company-mode' front-end showing the candidates in the echo area."
2616 (`post-command (company-echo-show-soon 'company-echo-strip-common-format))
2617 (`hide (company-echo-hide))))
2619 (defun company-echo-metadata-frontend (command)
2620 "`company-mode' front-end showing the documentation in the echo area."
2622 (`post-command (company-echo-show-when-idle 'company-fetch-metadata))
2623 (`hide (company-echo-hide))))
2626 ;;; company.el ends here