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 ((value (delete-dups (copy-sequence value))))
198 (and (memq 'company-pseudo-tooltip-unless-just-one-frontend value)
199 (memq 'company-pseudo-tooltip-frontend value)
200 (error "Pseudo tooltip frontend cannot be used twice"))
201 (and (memq 'company-preview-if-just-one-frontend value)
202 (memq 'company-preview-frontend value)
203 (error "Preview frontend cannot be used twice"))
204 (and (memq 'company-echo value)
205 (memq 'company-echo-metadata-frontend value)
206 (error "Echo area cannot be used twice"))
207 ;; Preview must come last.
208 (dolist (f '(company-preview-if-just-one-frontend company-preview-frontend))
209 (when (cdr (memq f value))
210 (setq value (append (delq f value) (list f)))))
211 (set variable value)))
213 (defcustom company-frontends '(company-pseudo-tooltip-unless-just-one-frontend
214 company-preview-if-just-one-frontend
215 company-echo-metadata-frontend)
216 "The list of active front-ends (visualizations).
217 Each front-end is a function that takes one argument. It is called with
218 one of the following arguments:
220 `show': When the visualization should start.
222 `hide': When the visualization should end.
224 `update': When the data has been updated.
226 `pre-command': Before every command that is executed while the
227 visualization is active.
229 `post-command': After every command that is executed while the
230 visualization is active.
232 The visualized data is stored in `company-prefix', `company-candidates',
233 `company-common', `company-selection', `company-point' and
234 `company-search-string'."
235 :set 'company-frontends-set
236 :type '(repeat (choice (const :tag "echo" company-echo-frontend)
237 (const :tag "echo, strip common"
238 company-echo-strip-common-frontend)
239 (const :tag "show echo meta-data in echo"
240 company-echo-metadata-frontend)
241 (const :tag "pseudo tooltip"
242 company-pseudo-tooltip-frontend)
243 (const :tag "pseudo tooltip, multiple only"
244 company-pseudo-tooltip-unless-just-one-frontend)
245 (const :tag "preview" company-preview-frontend)
246 (const :tag "preview, unique only"
247 company-preview-if-just-one-frontend)
248 (function :tag "custom function" nil))))
250 (defcustom company-tooltip-limit 10
251 "The maximum number of candidates in the tooltip."
254 (defcustom company-tooltip-minimum 6
255 "The minimum height of the tooltip.
256 If this many lines are not available, prefer to display the tooltip above."
259 (defcustom company-tooltip-minimum-width 0
260 "The minimum width of the tooltip's inner area.
261 This doesn't include the margins and the scroll bar."
263 :package-version '(company . "0.8.0"))
265 (defcustom company-tooltip-margin 1
266 "Width of margin columns to show around the toolip."
269 (defcustom company-tooltip-offset-display 'scrollbar
270 "Method using which the tooltip displays scrolling position.
271 `scrollbar' means draw a scrollbar to the right of the items.
272 `lines' means wrap items in lines with \"before\" and \"after\" counters."
273 :type '(choice (const :tag "Scrollbar" scrollbar)
274 (const :tag "Two lines" lines)))
276 (defcustom company-tooltip-align-annotations nil
277 "When non-nil, align annotations to the right tooltip border."
279 :package-version '(company . "0.7.1"))
281 (defcustom company-tooltip-flip-when-above nil
282 "Whether to flip the tooltip when it's above the current line."
284 :package-version '(company . "0.8.1"))
286 (defvar company-safe-backends
287 '((company-abbrev . "Abbrev")
288 (company-bbdb . "BBDB")
289 (company-capf . "completion-at-point-functions")
290 (company-clang . "Clang")
291 (company-cmake . "CMake")
292 (company-css . "CSS")
293 (company-dabbrev . "dabbrev for plain text")
294 (company-dabbrev-code . "dabbrev for code")
295 (company-eclim . "Eclim (an Eclipse interface)")
296 (company-elisp . "Emacs Lisp")
297 (company-etags . "etags")
298 (company-files . "Files")
299 (company-gtags . "GNU Global")
300 (company-ispell . "Ispell")
301 (company-keywords . "Programming language keywords")
302 (company-nxml . "nxml")
303 (company-oddmuse . "Oddmuse")
304 (company-pysmell . "PySmell")
305 (company-ropemacs . "ropemacs")
306 (company-semantic . "Semantic")
307 (company-tempo . "Tempo templates")
308 (company-xcode . "Xcode")))
309 (put 'company-safe-backends 'risky-local-variable t)
311 (defun company-safe-backends-p (backends)
312 (and (consp backends)
313 (not (cl-dolist (backend backends)
314 (unless (if (consp backend)
315 (company-safe-backends-p backend)
316 (assq backend company-safe-backends))
319 (defcustom company-backends `(,@(unless (version< "24.3.50" emacs-version)
320 (list 'company-elisp))
322 company-nxml company-css
323 company-eclim company-semantic company-clang
324 company-xcode company-ropemacs company-cmake
326 (company-dabbrev-code company-gtags company-etags
328 company-oddmuse company-files company-dabbrev)
329 "The list of active back-ends (completion engines).
331 Only one back-end is used at a time. The choice depends on the order of
332 the items in this list, and on the values they return in response to the
333 `prefix' command (see below). But a back-end can also be a \"grouped\"
336 `company-begin-backend' can be used to start a specific back-end,
337 `company-other-backend' will skip to the next matching back-end in the list.
339 Each back-end is a function that takes a variable number of arguments.
340 The first argument is the command requested from the back-end. It is one
343 `prefix': The back-end should return the text to be completed. It must be
344 text immediately before point. Returning nil passes control to the next
345 back-end. The function should return `stop' if it should complete but
346 cannot (e.g. if it is in the middle of a string). Instead of a string,
347 the back-end may return a cons where car is the prefix and cdr is used in
348 `company-minimum-prefix-length' test. It must be either number or t, and
349 in the latter case the test automatically succeeds.
351 `candidates': The second argument is the prefix to be completed. The
352 return value should be a list of candidates that match the prefix.
354 Non-prefix matches are also supported (candidates that don't start with the
355 prefix, but match it in some backend-defined way). Backends that use this
356 feature must disable cache (return t to `no-cache') and should also respond
361 `sorted': Return t here to indicate that the candidates are sorted and will
362 not need to be sorted again.
364 `duplicates': If non-nil, company will take care of removing duplicates
367 `no-cache': Usually company doesn't ask for candidates again as completion
368 progresses, unless the back-end returns t for this command. The second
369 argument is the latest prefix.
371 `meta': The second argument is a completion candidate. Return a (short)
372 documentation string for it.
374 `doc-buffer': The second argument is a completion candidate. Return a
375 buffer with documentation for it. Preferably use `company-doc-buffer',
377 `location': The second argument is a completion candidate. Return the cons
378 of buffer and buffer location, or of file and line number where the
379 completion candidate was defined.
381 `annotation': The second argument is a completion candidate. Return a
382 string to be displayed inline with the candidate in the popup. If
383 duplicates are removed by company, candidates with equal string values will
384 be kept if they have different annotations. For that to work properly,
385 backends should store the related information on candidates using text
388 `match': The second argument is a completion candidate. Backends that
389 provide non-prefix completions should return the position of the end of
390 text in the candidate that matches `prefix'. It will be used when
393 `require-match': If this returns t, the user is not allowed to enter
394 anything not offered as a candidate. Use with care! The default value nil
395 gives the user that choice with `company-require-match'. Return value
396 `never' overrides that option the other way around.
398 `init': Called once for each buffer. The back-end can check for external
399 programs and files and load any required libraries. Raising an error here
400 will show up in message log once, and the back-end will not be used for
403 `post-completion': Called after a completion candidate has been inserted
404 into the buffer. The second argument is the candidate. Can be used to
405 modify it, e.g. to expand a snippet.
407 The back-end should return nil for all commands it does not support or
408 does not know about. It should also be callable interactively and use
409 `company-begin-backend' to start itself in that case.
413 An element of `company-backends' can also itself be a list of back-ends,
414 then it's considered to be a \"grouped\" back-end.
416 When possible, commands taking a candidate as an argument are dispatched to
417 the back-end it came from. In other cases, the first non-nil value among
418 all the back-ends is returned.
420 The latter is the case for the `prefix' command. But if the group contains
421 the keyword `:with', the back-ends after it are ignored for this command.
423 The completions from back-ends in a group are merged (but only from those
424 that return the same `prefix').
426 Asynchronous back-ends:
428 The return value of each command can also be a cons (:async . FETCHER)
429 where FETCHER is a function of one argument, CALLBACK. When the data
430 arrives, FETCHER must call CALLBACK and pass it the appropriate return
431 value, as described above.
433 True asynchronous operation is only supported for command `candidates', and
434 only during idle completion. Other commands will block the user interface,
435 even if the back-end uses the asynchronous calling convention."
439 ,@(mapcar (lambda (b) `(const :tag ,(cdr b) ,(car b)))
440 company-safe-backends)
441 (symbol :tag "User defined")
442 (repeat :tag "Merged Back-ends"
443 (choice :tag "Back-end"
444 ,@(mapcar (lambda (b)
445 `(const :tag ,(cdr b) ,(car b)))
446 company-safe-backends)
447 (const :tag "With" :with)
448 (symbol :tag "User defined"))))))
450 (put 'company-backends 'safe-local-variable 'company-safe-backends-p)
452 (defcustom company-transformers nil
453 "Functions to change the list of candidates received from backends,
454 after sorting and removal of duplicates (if appropriate).
455 Each function gets called with the return value of the previous one."
457 (const :tag "None" nil)
458 (const :tag "Sort by occurrence" (company-sort-by-occurrence))
459 (const :tag "Sort by back-end importance"
460 (company-sort-by-backend-importance))
461 (repeat :tag "User defined" (function))))
463 (defcustom company-completion-started-hook nil
464 "Hook run when company starts completing.
465 The hook is called with one argument that is non-nil if the completion was
469 (defcustom company-completion-cancelled-hook nil
470 "Hook run when company cancels completing.
471 The hook is called with one argument that is non-nil if the completion was
475 (defcustom company-completion-finished-hook nil
476 "Hook run when company successfully completes.
477 The hook is called with the selected candidate as an argument.
479 If you indend to use it to post-process candidates from a specific
480 back-end, consider using the `post-completion' command instead."
483 (defcustom company-minimum-prefix-length 3
484 "The minimum prefix length for idle completion."
485 :type '(integer :tag "prefix length"))
487 (defcustom company-abort-manual-when-too-short nil
488 "If enabled, cancel a manually started completion when the prefix gets
489 shorter than both `company-minimum-prefix-length' and the length of the
490 prefix it was started from."
492 :package-version '(company . "0.8.0"))
494 (defcustom company-require-match 'company-explicit-action-p
495 "If enabled, disallow non-matching input.
496 This can be a function do determine if a match is required.
498 This can be overridden by the back-end, if it returns t or `never' to
499 `require-match'. `company-auto-complete' also takes precedence over this."
500 :type '(choice (const :tag "Off" nil)
501 (function :tag "Predicate function")
502 (const :tag "On, if user interaction took place"
503 'company-explicit-action-p)
504 (const :tag "On" t)))
506 (defcustom company-auto-complete nil
507 "Determines when to auto-complete.
508 If this is enabled, all characters from `company-auto-complete-chars'
509 trigger insertion of the selected completion candidate.
510 This can also be a function."
511 :type '(choice (const :tag "Off" nil)
512 (function :tag "Predicate function")
513 (const :tag "On, if user interaction took place"
514 'company-explicit-action-p)
515 (const :tag "On" t)))
517 (defcustom company-auto-complete-chars '(?\ ?\) ?.)
518 "Determines which characters trigger auto-completion.
519 See `company-auto-complete'. If this is a string, each string character
520 tiggers auto-completion. If it is a list of syntax description characters (see
521 `modify-syntax-entry'), all characters with that syntax auto-complete.
523 This can also be a function, which is called with the new input and should
524 return non-nil if company should auto-complete.
526 A character that is part of a valid candidate never triggers auto-completion."
527 :type '(choice (string :tag "Characters")
529 (const :tag "Whitespace" ?\ )
530 (const :tag "Symbol" ?_)
531 (const :tag "Opening parentheses" ?\()
532 (const :tag "Closing parentheses" ?\))
533 (const :tag "Word constituent" ?w)
534 (const :tag "Punctuation." ?.)
535 (const :tag "String quote." ?\")
536 (const :tag "Paired delimiter." ?$)
537 (const :tag "Expression quote or prefix operator." ?\')
538 (const :tag "Comment starter." ?<)
539 (const :tag "Comment ender." ?>)
540 (const :tag "Character-quote." ?/)
541 (const :tag "Generic string fence." ?|)
542 (const :tag "Generic comment fence." ?!))
543 (function :tag "Predicate function")))
545 (defcustom company-idle-delay .5
546 "The idle delay in seconds until completion starts automatically.
547 The prefix still has to satisfy `company-minimum-prefix-length' before that
548 happens. The value of nil means no idle completion."
549 :type '(choice (const :tag "never (nil)" nil)
550 (const :tag "immediate (0)" 0)
551 (number :tag "seconds")))
553 (defcustom company-begin-commands '(self-insert-command org-self-insert-command)
554 "A list of commands after which idle completion is allowed.
555 If this is t, it can show completions after any command except a few from a
556 pre-defined list. See `company-idle-delay'.
558 Alternatively, any command with a non-nil `company-begin' property is
559 treated as if it was on this list."
560 :type '(choice (const :tag "Any command" t)
561 (const :tag "Self insert command" '(self-insert-command))
562 (repeat :tag "Commands" function)))
564 (defcustom company-continue-commands '(not save-buffer save-some-buffers
565 save-buffers-kill-terminal
566 save-buffers-kill-emacs)
567 "A list of commands that are allowed during completion.
568 If this is t, or if `company-begin-commands' is t, any command is allowed.
569 Otherwise, the value must be a list of symbols. If it starts with `not',
570 the cdr is the list of commands that abort completion. Otherwise, all
571 commands except those in that list, or in `company-begin-commands', or
572 commands in the `company-' namespace, abort completion."
573 :type '(choice (const :tag "Any command" t)
574 (cons :tag "Any except"
576 (repeat :tag "Commands" function))
577 (repeat :tag "Commands" function)))
579 (defcustom company-show-numbers nil
580 "If enabled, show quick-access numbers for the first ten candidates."
581 :type '(choice (const :tag "off" nil)
582 (const :tag "on" t)))
584 (defcustom company-selection-wrap-around nil
585 "If enabled, selecting item before first or after last wraps around."
586 :type '(choice (const :tag "off" nil)
587 (const :tag "on" t)))
589 (defvar company-end-of-buffer-workaround t
590 "Work around a visualization bug when completing at the end of the buffer.
591 The work-around consists of adding a newline.")
593 (defvar company-async-wait 0.03
594 "Pause between checks to see if the value's been set when turning an
595 asynchronous call into synchronous.")
597 (defvar company-async-timeout 2
598 "Maximum wait time for a value to be set during asynchronous call.")
600 ;;; mode ;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;
602 (defvar company-mode-map (make-sparse-keymap)
603 "Keymap used by `company-mode'.")
605 (defvar company-active-map
606 (let ((keymap (make-sparse-keymap)))
607 (define-key keymap "\e\e\e" 'company-abort)
608 (define-key keymap "\C-g" 'company-abort)
609 (define-key keymap (kbd "M-n") 'company-select-next)
610 (define-key keymap (kbd "M-p") 'company-select-previous)
611 (define-key keymap (kbd "<down>") 'company-select-next-or-abort)
612 (define-key keymap (kbd "<up>") 'company-select-previous-or-abort)
613 (define-key keymap [down-mouse-1] 'ignore)
614 (define-key keymap [down-mouse-3] 'ignore)
615 (define-key keymap [mouse-1] 'company-complete-mouse)
616 (define-key keymap [mouse-3] 'company-select-mouse)
617 (define-key keymap [up-mouse-1] 'ignore)
618 (define-key keymap [up-mouse-3] 'ignore)
619 (define-key keymap [return] 'company-complete-selection)
620 (define-key keymap (kbd "RET") 'company-complete-selection)
621 (define-key keymap [tab] 'company-complete-common)
622 (define-key keymap (kbd "TAB") 'company-complete-common)
623 (define-key keymap (kbd "<f1>") 'company-show-doc-buffer)
624 (define-key keymap (kbd "C-h") 'company-show-doc-buffer)
625 (define-key keymap "\C-w" 'company-show-location)
626 (define-key keymap "\C-s" 'company-search-candidates)
627 (define-key keymap "\C-\M-s" 'company-filter-candidates)
629 (define-key keymap (vector (+ (aref (kbd "M-0") 0) i))
632 (company-complete-number ,(if (zerop i) 10 i)))))
635 "Keymap that is enabled during an active completion.")
637 (defvar company--disabled-backends nil)
639 (defun company-init-backend (backend)
640 (and (symbolp backend)
641 (not (fboundp backend))
642 (ignore-errors (require backend nil t)))
647 (funcall backend 'init)
648 (put backend 'company-init t))
650 (put backend 'company-init 'failed)
651 (unless (memq backend company--disabled-backends)
652 (message "Company back-end '%s' could not be initialized:\n%s"
653 backend (error-message-string err)))
654 (cl-pushnew backend company--disabled-backends)
656 ;; No initialization for lambdas.
657 ((functionp backend) t)
658 (t ;; Must be a list.
659 (cl-dolist (b backend)
661 (company-init-backend b))))))
663 (defvar company-default-lighter " company")
665 (defvar-local company-lighter company-default-lighter)
668 (define-minor-mode company-mode
669 "\"complete anything\"; is an in-buffer completion framework.
670 Completion starts automatically, depending on the values
671 `company-idle-delay' and `company-minimum-prefix-length'.
673 Completion can be controlled with the commands:
674 `company-complete-common', `company-complete-selection', `company-complete',
675 `company-select-next', `company-select-previous'. If these commands are
676 called before `company-idle-delay', completion will also start.
678 Completions can be searched with `company-search-candidates' or
679 `company-filter-candidates'. These can be used while completion is
682 The completion data is retrieved using `company-backends' and displayed
683 using `company-frontends'. If you want to start a specific back-end, call
684 it interactively or use `company-begin-backend'.
686 regular keymap (`company-mode-map'):
689 keymap during active completions (`company-active-map'):
691 \\{company-active-map}"
692 nil company-lighter company-mode-map
695 (when (eq company-idle-delay t)
696 (setq company-idle-delay 0)
697 (warn "Setting `company-idle-delay' to t is deprecated. Set it to 0 instead."))
698 (add-hook 'pre-command-hook 'company-pre-command nil t)
699 (add-hook 'post-command-hook 'company-post-command nil t)
700 (mapc 'company-init-backend company-backends))
701 (remove-hook 'pre-command-hook 'company-pre-command t)
702 (remove-hook 'post-command-hook 'company-post-command t)
704 (kill-local-variable 'company-point)))
706 (defcustom company-global-modes t
707 "Modes for which `company-mode' mode is turned on by `global-company-mode'.
708 If nil, means no modes. If t, then all major modes have it turned on.
709 If a list, it should be a list of `major-mode' symbol names for which
710 `company-mode' should be automatically turned on. The sense of the list is
711 negated if it begins with `not'. For example:
713 means that `company-mode' is turned on for buffers in C and C++ modes only.
715 means that `company-mode' is always turned on except in `message-mode' buffers."
716 :type '(choice (const :tag "none" nil)
718 (set :menu-tag "mode specific" :tag "modes"
720 (const :tag "Except" not)
721 (repeat :inline t (symbol :tag "mode")))))
724 (define-globalized-minor-mode global-company-mode company-mode company-mode-on)
726 (defun company-mode-on ()
727 (when (and (not (or noninteractive (eq (aref (buffer-name) 0) ?\s)))
728 (cond ((eq company-global-modes t)
730 ((eq (car-safe company-global-modes) 'not)
731 (not (memq major-mode (cdr company-global-modes))))
732 (t (memq major-mode company-global-modes))))
735 (defsubst company-assert-enabled ()
737 (company-uninstall-map)
738 (error "Company not enabled")))
740 ;;; keymaps ;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;
742 (defvar-local company-my-keymap nil)
744 (defvar company-emulation-alist '((t . nil)))
746 (defsubst company-enable-overriding-keymap (keymap)
747 (company-uninstall-map)
748 (setq company-my-keymap keymap))
750 (defun company-ensure-emulation-alist ()
751 (unless (eq 'company-emulation-alist (car emulation-mode-map-alists))
752 (setq emulation-mode-map-alists
753 (cons 'company-emulation-alist
754 (delq 'company-emulation-alist emulation-mode-map-alists)))))
756 (defun company-install-map ()
757 (unless (or (cdar company-emulation-alist)
758 (null company-my-keymap))
759 (setf (cdar company-emulation-alist) company-my-keymap)))
761 (defun company-uninstall-map ()
762 (setf (cdar company-emulation-alist) nil))
765 ;; Emacs calculates the active keymaps before reading the event. That means we
766 ;; cannot change the keymap from a timer. So we send a bogus command.
767 ;; XXX: Seems not to be needed anymore in Emacs 24.4
768 (defun company-ignore ()
770 (setq this-command last-command))
772 (global-set-key '[31415926] 'company-ignore)
774 (defun company-input-noop ()
775 (push 31415926 unread-command-events))
777 (defun company--column (&optional pos)
779 (when pos (goto-char pos))
783 (narrow-to-region (point) (point-max))
784 (let ((prefix (get-text-property (point) 'line-prefix)))
785 (if prefix (length prefix) 0)))
788 (defun company--row (&optional pos)
790 (when pos (goto-char pos))
791 (count-screen-lines (window-start)
792 (progn (vertical-motion 0) (point)))))
794 ;;; backends ;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;
796 (defvar-local company-backend nil)
798 (defun company-grab (regexp &optional expression limit)
799 (when (looking-back regexp limit)
800 (or (match-string-no-properties (or expression 0)) "")))
802 (defun company-grab-line (regexp &optional expression)
803 (company-grab regexp expression (point-at-bol)))
805 (defun company-grab-symbol ()
806 (if (looking-at "\\_>")
807 (buffer-substring (point) (save-excursion (skip-syntax-backward "w_")
809 (unless (and (char-after) (memq (char-syntax (char-after)) '(?w ?_)))
812 (defun company-grab-word ()
813 (if (looking-at "\\>")
814 (buffer-substring (point) (save-excursion (skip-syntax-backward "w")
816 (unless (and (char-after) (eq (char-syntax (char-after)) ?w))
819 (defun company-grab-symbol-cons (idle-begin-after-re &optional max-len)
820 (let ((symbol (company-grab-symbol)))
823 (forward-char (- (length symbol)))
824 (if (looking-back idle-begin-after-re (if max-len
826 (line-beginning-position)))
830 (defun company-in-string-or-comment ()
831 (let ((ppss (syntax-ppss)))
832 (or (car (setq ppss (nthcdr 3 ppss)))
833 (car (setq ppss (cdr ppss)))
836 (defun company-call-backend (&rest args)
837 (company--force-sync #'company-call-backend-raw args company-backend))
839 (defun company--force-sync (fun args backend)
840 (let ((value (apply fun args)))
841 (if (not (eq (car-safe value) :async))
844 (start (time-to-seconds)))
846 (lambda (result) (setq res result)))
847 (while (eq res 'trash)
848 (if (> (- (time-to-seconds) start) company-async-timeout)
849 (error "Company: Back-end %s async timeout with args %s"
851 (sleep-for company-async-wait)))
854 (defun company-call-backend-raw (&rest args)
856 (if (functionp company-backend)
857 (apply company-backend args)
858 (apply #'company--multi-backend-adapter company-backend args))
859 (error (error "Company: Back-end %s error \"%s\" with args %s"
860 company-backend (error-message-string err) args))))
862 (defun company--multi-backend-adapter (backends command &rest args)
863 (let ((backends (cl-loop for b in backends
864 when (not (and (symbolp b)
865 (eq 'failed (get b 'company-init))))
868 (if (eq command 'prefix)
869 (butlast backends (length (member :with backends)))
870 (delq :with backends)))
873 (company--multi-backend-adapter-candidates backends (car args)))
876 ((or `prefix `ignore-case `no-cache `require-match)
878 (cl-dolist (backend backends)
879 (when (setq value (company--force-sync
880 backend (cons command args) backend))
881 (cl-return value)))))
883 (let ((arg (car args)))
884 (when (> (length arg) 0)
885 (let ((backend (or (get-text-property 0 'company-backend arg)
887 (apply backend command args))))))))
889 (defun company--multi-backend-adapter-candidates (backends prefix)
890 (let ((pairs (cl-loop for backend in (cdr backends)
891 when (equal (company--prefix-str
892 (funcall backend 'prefix))
894 collect (cons (funcall backend 'candidates prefix)
899 (propertize str 'company-backend b))
901 (when (equal (company--prefix-str (funcall (car backends) 'prefix)) prefix)
902 ;; Small perf optimization: don't tag the candidates received
903 ;; from the first backend in the group.
904 (push (cons (funcall (car backends) 'candidates prefix)
907 (company--merge-async pairs (lambda (values) (apply #'append values)))))
909 (defun company--merge-async (pairs merger)
910 (let ((async (cl-loop for pair in pairs
912 (eq :async (car-safe (car pair))))))
914 (funcall merger (cl-loop for (val . mapper) in pairs
915 collect (funcall mapper val)))
926 (let ((val (car pair))
928 (if (not (eq :async (car-safe val)))
929 (push (funcall mapper val) lst)
933 (push fetcher pending)
936 (setq pending (delq fetcher pending))
937 (setcar cell (funcall mapper res))
938 (funcall finisher)))))))))))))
940 (defun company--prefix-str (prefix)
941 (or (car-safe prefix) prefix))
943 ;;; completion mechanism ;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;
945 (defvar-local company-prefix nil)
947 (defvar-local company-candidates nil)
949 (defvar-local company-candidates-length nil)
951 (defvar-local company-candidates-cache nil)
953 (defvar-local company-candidates-predicate nil)
955 (defvar-local company-common nil)
957 (defvar-local company-selection 0)
959 (defvar-local company-selection-changed nil)
961 (defvar-local company--manual-action nil
962 "Non-nil, if manual completion took place.")
964 (defvar-local company--manual-prefix nil)
966 (defvar company--auto-completion nil
967 "Non-nil when current candidate is being inserted automatically.
968 Controlled by `company-auto-complete'.")
970 (defvar-local company--point-max nil)
972 (defvar-local company-point nil)
974 (defvar company-timer nil)
976 (defvar-local company-added-newline nil)
978 (defsubst company-strip-prefix (str)
979 (substring str (length company-prefix)))
981 (defun company--insert-candidate (candidate)
982 (setq candidate (substring-no-properties candidate))
983 ;; XXX: Return value we check here is subject to change.
984 (if (eq (company-call-backend 'ignore-case) 'keep-prefix)
985 (insert (company-strip-prefix candidate))
986 (delete-region (- (point) (length company-prefix)) (point))
989 (defmacro company-with-candidate-inserted (candidate &rest body)
990 "Evaluate BODY with CANDIDATE temporarily inserted.
991 This is a tool for back-ends that need candidates inserted before they
992 can retrieve meta-data for them."
994 `(let ((inhibit-modification-hooks t)
995 (inhibit-point-motion-hooks t)
996 (modified-p (buffer-modified-p)))
997 (company--insert-candidate ,candidate)
1000 (delete-region company-point (point)))))
1002 (defun company-explicit-action-p ()
1003 "Return whether explicit completion action was taken by the user."
1004 (or company--manual-action
1005 company-selection-changed))
1007 (defun company-reformat (candidate)
1008 ;; company-ispell needs this, because the results are always lower-case
1009 ;; It's mory efficient to fix it only when they are displayed.
1010 ;; FIXME: Adopt the current text's capitalization instead?
1011 (if (eq (company-call-backend 'ignore-case) 'keep-prefix)
1012 (concat company-prefix (substring candidate (length company-prefix)))
1015 (defun company--should-complete ()
1016 (and (eq company-idle-delay 'now)
1017 (not (or buffer-read-only overriding-terminal-local-map
1018 overriding-local-map))
1019 ;; Check if in the middle of entering a key combination.
1020 (or (equal (this-command-keys-vector) [])
1021 (not (keymapp (key-binding (this-command-keys-vector)))))
1022 (not (and transient-mark-mode mark-active))))
1024 (defun company--should-continue ()
1025 (or (eq t company-begin-commands)
1026 (eq t company-continue-commands)
1027 (if (eq 'not (car company-continue-commands))
1028 (not (memq this-command (cdr company-continue-commands)))
1029 (or (memq this-command company-begin-commands)
1030 (memq this-command company-continue-commands)
1031 (and (symbolp this-command)
1032 (string-match-p "\\`company-" (symbol-name this-command)))))))
1034 (defun company-call-frontends (command)
1035 (dolist (frontend company-frontends)
1037 (funcall frontend command)
1038 (error (error "Company: Front-end %s error \"%s\" on command %s"
1039 frontend (error-message-string err) command)))))
1041 (defun company-set-selection (selection &optional force-update)
1043 (if company-selection-wrap-around
1044 (mod selection company-candidates-length)
1045 (max 0 (min (1- company-candidates-length) selection))))
1046 (when (or force-update (not (equal selection company-selection)))
1047 (company--update-group-lighter (nth selection company-candidates))
1048 (setq company-selection selection
1049 company-selection-changed t)
1050 (company-call-frontends 'update)))
1052 (defun company--update-group-lighter (candidate)
1053 (when (listp company-backend)
1054 (let ((backend (or (get-text-property 0 'company-backend candidate)
1055 (car company-backend))))
1056 (when (and backend (symbolp backend))
1057 (let ((name (replace-regexp-in-string "company-\\|-company" ""
1058 (symbol-name backend))))
1059 (setq company-lighter (format " company-<%s>" name)))))))
1061 (defun company-apply-predicate (candidates predicate)
1063 (dolist (c candidates)
1064 (when (funcall predicate c)
1068 (defun company-update-candidates (candidates)
1069 (setq company-candidates-length (length candidates))
1070 (if (> company-selection 0)
1071 ;; Try to restore the selection
1072 (let ((selected (nth company-selection company-candidates)))
1073 (setq company-selection 0
1074 company-candidates candidates)
1076 (while (and candidates (string< (pop candidates) selected))
1077 (cl-incf company-selection))
1079 ;; Make sure selection isn't out of bounds.
1080 (setq company-selection (min (1- company-candidates-length)
1081 company-selection)))))
1082 (setq company-selection 0
1083 company-candidates candidates))
1085 (push (cons company-prefix company-candidates) company-candidates-cache)
1086 ;; Calculate common.
1087 (let ((completion-ignore-case (company-call-backend 'ignore-case)))
1088 ;; We want to support non-prefix completion, so filtering is the
1089 ;; responsibility of each respective backend, not ours.
1090 ;; On the other hand, we don't want to replace non-prefix input in
1091 ;; `company-complete-common'.
1092 (setq company-common
1093 (if (cdr company-candidates)
1094 (let ((common (try-completion company-prefix company-candidates)))
1096 ;; Mulple equal strings, probably with different
1100 (car company-candidates)))))
1102 (defun company-calculate-candidates (prefix)
1103 (let ((candidates (cdr (assoc prefix company-candidates-cache)))
1104 (ignore-case (company-call-backend 'ignore-case)))
1106 (when company-candidates-cache
1107 (let ((len (length prefix))
1108 (completion-ignore-case ignore-case)
1110 (cl-dotimes (i (1+ len))
1111 (when (setq prev (cdr (assoc (substring prefix 0 (- len i))
1112 company-candidates-cache)))
1113 (setq candidates (all-completions prefix prev))
1115 ;; no cache match, call back-end
1117 (company--process-candidates
1118 (company--fetch-candidates prefix))))
1119 (setq candidates (company--transform-candidates candidates))
1121 (if (or (cdr candidates)
1122 (not (eq t (compare-strings (car candidates) nil nil
1123 prefix nil nil ignore-case))))
1125 ;; Already completed and unique; don't start.
1128 (defun company--fetch-candidates (prefix)
1129 (let ((c (if company--manual-action
1130 (company-call-backend 'candidates prefix)
1131 (company-call-backend-raw 'candidates prefix)))
1133 (if (not (eq (car c) :async))
1135 (let ((buf (current-buffer))
1136 (win (selected-window))
1137 (tick (buffer-chars-modified-tick))
1139 (backend company-backend))
1142 (lambda (candidates)
1143 (if (not (and candidates (eq res 'done)))
1144 ;; Fetcher called us back right away.
1145 (setq res candidates)
1146 (setq company-backend backend
1147 company-candidates-cache
1149 (company--process-candidates
1151 (company-idle-begin buf win tick pt)))))
1152 ;; FIXME: Relying on the fact that the callers
1153 ;; will interpret nil as "do nothing" is shaky.
1154 ;; A throw-catch would be one possible improvement.
1156 (progn (setq res 'done) nil)))))
1158 (defun company--process-candidates (candidates)
1159 (when company-candidates-predicate
1161 (company-apply-predicate candidates
1162 company-candidates-predicate)))
1163 (unless (company-call-backend 'sorted)
1164 (setq candidates (sort candidates 'string<)))
1165 (when (company-call-backend 'duplicates)
1166 (company--strip-duplicates candidates))
1169 (defun company--strip-duplicates (candidates)
1170 (let ((c2 candidates))
1173 (let ((str (car c2))
1176 (while (let ((str2 (car c2)))
1177 (if (not (equal str str2))
1179 (when (eq anno 'unk)
1180 (setq anno (company-call-backend
1183 (company-call-backend
1184 'annotation str2))))
1188 (defun company--transform-candidates (candidates)
1189 (let ((c candidates))
1190 (dolist (tr company-transformers)
1191 (setq c (funcall tr c)))
1194 (defcustom company-occurrence-weight-function
1195 #'company-occurrence-prefer-closest-above
1196 "Function to weigh matches in `company-sort-by-occurrence'.
1197 It's called with three arguments: cursor position, the beginning and the
1200 (const :tag "First above point, then below point"
1201 company-occurrence-prefer-closest-above)
1202 (const :tag "Prefer closest in any direction"
1203 company-occurrence-prefer-any-closest)))
1205 (defun company-occurrence-prefer-closest-above (pos match-beg match-end)
1206 "Give priority to the matches above point, then those below point."
1207 (if (< match-beg pos)
1209 (- match-beg (window-start))))
1211 (defun company-occurrence-prefer-any-closest (pos _match-beg match-end)
1212 "Give priority to the matches closest to the point."
1213 (abs (- pos match-end)))
1215 (defun company-sort-by-occurrence (candidates)
1216 "Sort CANDIDATES according to their occurrences.
1217 Searches for each in the currently visible part of the current buffer and
1218 prioritizes the matches according to `company-occurrence-weight-function'.
1219 The rest of the list is appended unchanged.
1220 Keywords and function definition names are ignored."
1221 (let* ((w-start (window-start))
1222 (w-end (window-end))
1223 (start-point (point))
1231 (while (search-forward candidate w-end t)
1232 (when (and (not (eq (point) start-point))
1234 (company--occurrence-predicate)))
1238 (funcall company-occurrence-weight-function
1246 (mapcar #'car (sort occurs (lambda (e1 e2) (<= (cdr e1) (cdr e2)))))
1249 (defun company--occurrence-predicate ()
1250 (let ((beg (match-beginning 0))
1251 (end (match-end 0)))
1254 (and (not (memq (get-text-property (1- (point)) 'face)
1255 '(font-lock-function-name-face
1256 font-lock-keyword-face)))
1257 (let ((prefix (company--prefix-str
1258 (company-call-backend 'prefix))))
1259 (and (stringp prefix)
1260 (= (length prefix) (- end beg))))))))
1262 (defun company-sort-by-backend-importance (candidates)
1263 "Sort CANDIDATES as two priority groups.
1264 If `company-backend' is a function, do nothing. If it's a list, move
1265 candidates from back-ends before keyword `:with' to the front. Candidates
1266 from the rest of the back-ends in the group, if any, will be left at the end."
1267 (if (functionp company-backend)
1269 (let ((low-priority (cdr (memq :with company-backend))))
1270 (if (null low-priority)
1275 (let ((b2 (get-text-property 0 'company-backend c2)))
1276 (and b2 (memq b2 low-priority)))
1277 (let ((b1 (get-text-property 0 'company-backend c1)))
1278 (or (not b1) (not (memq b1 low-priority)))))))))))
1280 (defun company-idle-begin (buf win tick pos)
1281 (and (eq buf (current-buffer))
1282 (eq win (selected-window))
1283 (eq tick (buffer-chars-modified-tick))
1285 (when (company-auto-begin)
1286 (when (version< emacs-version "24.3.50")
1287 (company-input-noop))
1288 (company-post-command))))
1290 (defun company-auto-begin ()
1292 (not company-candidates)
1293 (let ((company-idle-delay 'now))
1294 (condition-case-unless-debug err
1296 (error (message "Company: An error occurred in auto-begin")
1297 (message "%s" (error-message-string err))
1299 (quit (company-cancel)))))
1300 (unless company-candidates
1301 (setq company-backend nil))
1302 ;; Return non-nil if active.
1305 (defun company-manual-begin ()
1307 (company-assert-enabled)
1308 (setq company--manual-action t)
1310 (let ((company-minimum-prefix-length 0))
1311 (company-auto-begin))
1312 (unless company-candidates
1313 (setq company--manual-action nil))))
1315 (defun company-other-backend (&optional backward)
1316 (interactive (list current-prefix-arg))
1317 (company-assert-enabled)
1318 (let* ((after (if company-backend
1319 (cdr (member company-backend company-backends))
1321 (before (cdr (member company-backend (reverse company-backends))))
1323 (append before (reverse after))
1324 (append after (reverse before)))))
1326 (cl-dolist (backend next)
1327 (when (ignore-errors (company-begin-backend backend))
1329 (unless company-candidates
1330 (error "No other back-end")))
1332 (defun company-require-match-p ()
1333 (let ((backend-value (company-call-backend 'require-match)))
1334 (or (eq backend-value t)
1335 (and (not (eq backend-value 'never))
1336 (if (functionp company-require-match)
1337 (funcall company-require-match)
1338 (eq company-require-match t))))))
1340 (defun company-auto-complete-p (input)
1341 "Return non-nil, if input starts with punctuation or parentheses."
1342 (and (if (functionp company-auto-complete)
1343 (funcall company-auto-complete)
1344 company-auto-complete)
1345 (if (functionp company-auto-complete-chars)
1346 (funcall company-auto-complete-chars input)
1347 (if (consp company-auto-complete-chars)
1348 (memq (char-syntax (string-to-char input))
1349 company-auto-complete-chars)
1350 (string-match (substring input 0 1) company-auto-complete-chars)))))
1352 (defun company--incremental-p ()
1353 (and (> (point) company-point)
1354 (> (point-max) company--point-max)
1355 (not (eq this-command 'backward-delete-char-untabify))
1356 (equal (buffer-substring (- company-point (length company-prefix))
1360 (defun company--continue-failed (new-prefix)
1361 (let ((input (buffer-substring-no-properties (point) company-point)))
1363 ((company-auto-complete-p input)
1366 (goto-char company-point)
1367 (let ((company--auto-completion t))
1368 (company-complete-selection))
1370 ((and (or (not (company-require-match-p))
1371 ;; Don't require match if the new prefix
1372 ;; doesn't continue the old one, and the latter was a match.
1373 (<= (length new-prefix) (length company-prefix)))
1374 (member company-prefix company-candidates))
1375 ;; Last input was a success,
1376 ;; but we're treating it as an abort + input anyway,
1377 ;; like the `unique' case below.
1378 (company-cancel 'non-unique))
1379 ((company-require-match-p)
1380 ;; Wrong incremental input, but required match.
1381 (delete-char (- (length input)))
1383 (message "Matching input is required")
1385 (t (company-cancel)))))
1387 (defun company--good-prefix-p (prefix)
1388 (and (stringp (company--prefix-str prefix)) ;excludes 'stop
1389 (or (eq (cdr-safe prefix) t)
1390 (let ((len (or (cdr-safe prefix) (length prefix))))
1391 (if company--manual-prefix
1392 (or (not company-abort-manual-when-too-short)
1393 ;; Must not be less than minimum or initial length.
1394 (>= len (min company-minimum-prefix-length
1395 (length company--manual-prefix))))
1396 (>= len company-minimum-prefix-length))))))
1398 (defun company--continue ()
1399 (when (company-call-backend 'no-cache company-prefix)
1400 ;; Don't complete existing candidates, fetch new ones.
1401 (setq company-candidates-cache nil))
1402 (let* ((new-prefix (company-call-backend 'prefix))
1403 (c (when (and (company--good-prefix-p new-prefix)
1404 (setq new-prefix (company--prefix-str new-prefix))
1405 (= (- (point) (length new-prefix))
1406 (- company-point (length company-prefix))))
1407 (company-calculate-candidates new-prefix))))
1410 ;; t means complete/unique.
1411 ;; Handle it like completion was aborted, to differentiate from user
1412 ;; calling one of Company's commands to insert the candidate,
1413 ;; not to trigger template expansion, etc.
1414 (company-cancel 'unique))
1416 ;; incremental match
1417 (setq company-prefix new-prefix)
1418 (company-update-candidates c)
1420 ((not (company--incremental-p))
1422 (t (company--continue-failed new-prefix)))))
1424 (defun company--begin-new ()
1426 (cl-dolist (backend (if company-backend
1427 ;; prefer manual override
1428 (list company-backend)
1431 (if (or (symbolp backend)
1432 (functionp backend))
1433 (when (or (not (symbolp backend))
1434 (eq t (get backend 'company-init))
1435 (unless (get backend 'company-init)
1436 (company-init-backend backend)))
1437 (funcall backend 'prefix))
1438 (company--multi-backend-adapter backend 'prefix)))
1440 (when (company--good-prefix-p prefix)
1441 (setq company-prefix (company--prefix-str prefix)
1442 company-backend backend
1443 c (company-calculate-candidates company-prefix))
1444 ;; t means complete/unique. We don't start, so no hooks.
1446 (when company--manual-action
1447 (message "No completion found"))
1448 (when company--manual-action
1449 (setq company--manual-prefix prefix))
1450 (if (symbolp backend)
1451 (setq company-lighter (concat " " (symbol-name backend)))
1452 (company--update-group-lighter (car c)))
1453 (company-update-candidates c)
1454 (run-hook-with-args 'company-completion-started-hook
1455 (company-explicit-action-p))
1456 (company-call-frontends 'show)))
1459 (defun company--perform ()
1460 (or (and company-candidates (company--continue))
1461 (and (company--should-complete) (company--begin-new)))
1462 (when company-candidates
1463 (let ((modified (buffer-modified-p)))
1464 (when (and company-end-of-buffer-workaround (eobp))
1465 (save-excursion (insert "\n"))
1466 (setq company-added-newline
1467 (or modified (buffer-chars-modified-tick)))))
1468 (setq company-point (point)
1469 company--point-max (point-max))
1470 (company-ensure-emulation-alist)
1471 (company-enable-overriding-keymap company-active-map)
1472 (company-call-frontends 'update)))
1474 (defun company-cancel (&optional result)
1475 (and company-added-newline
1476 (> (point-max) (point-min))
1477 (let ((tick (buffer-chars-modified-tick)))
1478 (delete-region (1- (point-max)) (point-max))
1479 (equal tick company-added-newline))
1480 ;; Only set unmodified when tick remained the same since insert,
1481 ;; and the buffer wasn't modified before.
1482 (set-buffer-modified-p nil))
1484 (when company-prefix
1485 (if (stringp result)
1487 (company-call-backend 'pre-completion result)
1488 (run-hook-with-args 'company-completion-finished-hook result)
1489 (company-call-backend 'post-completion result))
1490 (run-hook-with-args 'company-completion-cancelled-hook result)))
1491 (setq company-added-newline nil
1494 company-candidates nil
1495 company-candidates-length nil
1496 company-candidates-cache nil
1497 company-candidates-predicate nil
1500 company-selection-changed nil
1501 company--manual-action nil
1502 company--manual-prefix nil
1503 company-lighter company-default-lighter
1504 company--point-max nil
1507 (cancel-timer company-timer))
1508 (company-search-mode 0)
1509 (company-call-frontends 'hide)
1510 (company-enable-overriding-keymap nil))
1511 ;; Make return value explicit.
1514 (defun company-abort ()
1516 (company-cancel 'abort))
1518 (defun company-finish (result)
1519 (company--insert-candidate result)
1520 (company-cancel result))
1522 (defsubst company-keep (command)
1523 (and (symbolp command) (get command 'company-keep)))
1525 (defun company-pre-command ()
1526 (unless (company-keep this-command)
1528 (when company-candidates
1529 (company-call-frontends 'pre-command)
1530 (unless (company--should-continue)
1532 (error (message "Company: An error occurred in pre-command")
1533 (message "%s" (error-message-string err))
1536 (cancel-timer company-timer)
1537 (setq company-timer nil))
1538 (company-uninstall-map))
1540 (defun company-post-command ()
1541 (unless (company-keep this-command)
1544 (unless (equal (point) company-point)
1545 (let (company-idle-delay) ; Against misbehavior while debugging.
1546 (company--perform)))
1547 (if company-candidates
1548 (company-call-frontends 'post-command)
1549 (and (numberp company-idle-delay)
1550 (company--should-begin)
1552 (run-with-timer company-idle-delay nil
1554 (current-buffer) (selected-window)
1555 (buffer-chars-modified-tick) (point))))))
1556 (error (message "Company: An error occurred in post-command")
1557 (message "%s" (error-message-string err))
1559 (company-install-map))
1561 (defvar company--begin-inhibit-commands '(company-abort
1562 company-complete-mouse
1564 company-complete-common
1565 company-complete-selection
1566 company-complete-number)
1567 "List of commands after which idle completion is (still) disabled when
1568 `company-begin-commands' is t.")
1570 (defun company--should-begin ()
1571 (if (eq t company-begin-commands)
1572 (not (memq this-command company--begin-inhibit-commands))
1574 (memq this-command company-begin-commands)
1575 (and (symbolp this-command) (get this-command 'company-begin)))))
1577 ;;; search ;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;
1579 (defvar-local company-search-string nil)
1581 (defvar-local company-search-lighter " Search: \"\"")
1583 (defvar-local company-search-old-map nil)
1585 (defvar-local company-search-old-selection 0)
1587 (defun company-search (text lines)
1588 (let ((quoted (regexp-quote text))
1590 (cl-dolist (line lines)
1591 (when (string-match quoted line (length company-prefix))
1595 (defun company-search-printing-char ()
1597 (company-search-assert-enabled)
1598 (setq company-search-string
1599 (concat (or company-search-string "") (string last-command-event))
1600 company-search-lighter (concat " Search: \"" company-search-string
1602 (let ((pos (company-search company-search-string
1603 (nthcdr company-selection company-candidates))))
1606 (company-set-selection (+ company-selection pos) t))))
1608 (defun company-search-repeat-forward ()
1609 "Repeat the incremental search in completion candidates forward."
1611 (company-search-assert-enabled)
1612 (let ((pos (company-search company-search-string
1613 (cdr (nthcdr company-selection
1614 company-candidates)))))
1617 (company-set-selection (+ company-selection pos 1) t))))
1619 (defun company-search-repeat-backward ()
1620 "Repeat the incremental search in completion candidates backwards."
1622 (company-search-assert-enabled)
1623 (let ((pos (company-search company-search-string
1624 (nthcdr (- company-candidates-length
1626 (reverse company-candidates)))))
1629 (company-set-selection (- company-selection pos 1) t))))
1631 (defun company-create-match-predicate ()
1632 (setq company-candidates-predicate
1633 `(lambda (candidate)
1634 ,(if company-candidates-predicate
1635 `(and (string-match ,company-search-string candidate)
1636 (funcall ,company-candidates-predicate
1638 `(string-match ,company-search-string candidate))))
1639 (company-update-candidates
1640 (company-apply-predicate company-candidates company-candidates-predicate))
1641 ;; Invalidate cache.
1642 (setq company-candidates-cache (cons company-prefix company-candidates)))
1644 (defun company-filter-printing-char ()
1646 (company-search-assert-enabled)
1647 (company-search-printing-char)
1648 (company-create-match-predicate)
1649 (company-call-frontends 'update))
1651 (defun company-search-kill-others ()
1652 "Limit the completion candidates to the ones matching the search string."
1654 (company-search-assert-enabled)
1655 (company-create-match-predicate)
1656 (company-search-mode 0)
1657 (company-call-frontends 'update))
1659 (defun company-search-abort ()
1660 "Abort searching the completion candidates."
1662 (company-search-assert-enabled)
1663 (company-set-selection company-search-old-selection t)
1664 (company-search-mode 0))
1666 (defun company-search-other-char ()
1668 (company-search-assert-enabled)
1669 (company-search-mode 0)
1670 (company--unread-last-input))
1672 (defvar company-search-map
1674 (keymap (make-keymap)))
1675 (if (fboundp 'max-char)
1676 (set-char-table-range (nth 1 keymap) (cons #x100 (max-char))
1677 'company-search-printing-char)
1679 ;; obsolete in Emacs 23
1680 (let ((l (generic-character-list))
1681 (table (nth 1 keymap)))
1683 (set-char-table-default table (car l) 'company-search-printing-char)
1684 (setq l (cdr l))))))
1685 (define-key keymap [t] 'company-search-other-char)
1687 (define-key keymap (make-string 1 i) 'company-search-other-char)
1690 (define-key keymap (vector i) 'company-search-printing-char)
1692 (let ((meta-map (make-sparse-keymap)))
1693 (define-key keymap (char-to-string meta-prefix-char) meta-map)
1694 (define-key keymap [escape] meta-map))
1695 (define-key keymap (vector meta-prefix-char t) 'company-search-other-char)
1696 (define-key keymap "\e\e\e" 'company-search-other-char)
1697 (define-key keymap [escape escape escape] 'company-search-other-char)
1698 (define-key keymap (kbd "DEL") 'company-search-other-char)
1700 (define-key keymap "\C-g" 'company-search-abort)
1701 (define-key keymap "\C-s" 'company-search-repeat-forward)
1702 (define-key keymap "\C-r" 'company-search-repeat-backward)
1703 (define-key keymap "\C-o" 'company-search-kill-others)
1705 "Keymap used for incrementally searching the completion candidates.")
1707 (define-minor-mode company-search-mode
1708 "Search mode for completion candidates.
1709 Don't start this directly, use `company-search-candidates' or
1710 `company-filter-candidates'."
1711 nil company-search-lighter nil
1712 (if company-search-mode
1713 (if (company-manual-begin)
1715 (setq company-search-old-selection company-selection)
1716 (company-call-frontends 'update))
1717 (setq company-search-mode nil))
1718 (kill-local-variable 'company-search-string)
1719 (kill-local-variable 'company-search-lighter)
1720 (kill-local-variable 'company-search-old-selection)
1721 (company-enable-overriding-keymap company-active-map)))
1723 (defun company-search-assert-enabled ()
1724 (company-assert-enabled)
1725 (unless company-search-mode
1726 (company-uninstall-map)
1727 (error "Company not in search mode")))
1729 (defun company-search-candidates ()
1730 "Start searching the completion candidates incrementally.
1732 \\<company-search-map>Search can be controlled with the commands:
1733 - `company-search-repeat-forward' (\\[company-search-repeat-forward])
1734 - `company-search-repeat-backward' (\\[company-search-repeat-backward])
1735 - `company-search-abort' (\\[company-search-abort])
1737 Regular characters are appended to the search string.
1739 The command `company-search-kill-others' (\\[company-search-kill-others])
1740 uses the search string to limit the completion candidates."
1742 (company-search-mode 1)
1743 (company-enable-overriding-keymap company-search-map))
1745 (defvar company-filter-map
1746 (let ((keymap (make-keymap)))
1747 (define-key keymap [remap company-search-printing-char]
1748 'company-filter-printing-char)
1749 (set-keymap-parent keymap company-search-map)
1751 "Keymap used for incrementally searching the completion candidates.")
1753 (defun company-filter-candidates ()
1754 "Start filtering the completion candidates incrementally.
1755 This works the same way as `company-search-candidates' immediately
1756 followed by `company-search-kill-others' after each input."
1758 (company-search-mode 1)
1759 (company-enable-overriding-keymap company-filter-map))
1761 ;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;
1763 (defun company-select-next ()
1764 "Select the next candidate in the list."
1766 (when (company-manual-begin)
1767 (company-set-selection (1+ company-selection))))
1769 (defun company-select-previous ()
1770 "Select the previous candidate in the list."
1772 (when (company-manual-begin)
1773 (company-set-selection (1- company-selection))))
1775 (defun company-select-next-or-abort ()
1776 "Select the next candidate if more than one, else abort
1777 and invoke the normal binding."
1779 (if (> company-candidates-length 1)
1780 (company-select-next)
1782 (company--unread-last-input)))
1784 (defun company-select-previous-or-abort ()
1785 "Select the previous candidate if more than one, else abort
1786 and invoke the normal binding."
1788 (if (> company-candidates-length 1)
1789 (company-select-previous)
1791 (company--unread-last-input)))
1793 (defvar company-pseudo-tooltip-overlay)
1795 (defvar company-tooltip-offset)
1797 (defun company--inside-tooltip-p (event-col-row row height)
1798 (let* ((ovl company-pseudo-tooltip-overlay)
1799 (column (overlay-get ovl 'company-column))
1800 (width (overlay-get ovl 'company-width))
1801 (evt-col (car event-col-row))
1802 (evt-row (cdr event-col-row)))
1803 (and (>= evt-col column)
1804 (< evt-col (+ column width))
1806 (and (> evt-row row)
1807 (<= evt-row (+ row height) ))
1808 (and (< evt-row row)
1809 (>= evt-row (+ row height)))))))
1811 (defun company--event-col-row (event)
1812 (let* ((col-row (posn-actual-col-row (event-start event)))
1814 (row (cdr col-row)))
1815 (cl-incf col (window-hscroll))
1816 (and header-line-format
1817 (version< "24" emacs-version)
1821 (defun company-select-mouse (event)
1822 "Select the candidate picked by the mouse."
1824 (let ((event-col-row (company--event-col-row event))
1825 (ovl-row (company--row))
1826 (ovl-height (and company-pseudo-tooltip-overlay
1827 (min (overlay-get company-pseudo-tooltip-overlay
1829 company-candidates-length))))
1831 (company--inside-tooltip-p event-col-row ovl-row ovl-height))
1833 (company-set-selection (+ (cdr event-col-row)
1834 (1- company-tooltip-offset)
1835 (if (and (eq company-tooltip-offset-display 'lines)
1836 (not (zerop company-tooltip-offset)))
1839 (if (< ovl-height 0)
1844 (company--unread-last-input)
1847 (defun company-complete-mouse (event)
1848 "Insert the candidate picked by the mouse."
1850 (when (company-select-mouse event)
1851 (company-complete-selection)))
1853 (defun company-complete-selection ()
1854 "Insert the selected candidate."
1856 (when (company-manual-begin)
1857 (let ((result (nth company-selection company-candidates)))
1858 (company-finish result))))
1860 (defun company-complete-common ()
1861 "Insert the common part of all candidates."
1863 (when (company-manual-begin)
1864 (if (and (not (cdr company-candidates))
1865 (equal company-common (car company-candidates)))
1866 (company-complete-selection)
1867 (when company-common
1868 (company--insert-candidate company-common)))))
1870 (defun company-complete ()
1871 "Insert the common part of all candidates or the current selection.
1872 The first time this is called, the common part is inserted, the second
1873 time, or when the selection has been changed, the selected candidate is
1876 (when (company-manual-begin)
1877 (if (or company-selection-changed
1878 (eq last-command 'company-complete-common))
1879 (call-interactively 'company-complete-selection)
1880 (call-interactively 'company-complete-common)
1881 (setq this-command 'company-complete-common))))
1883 (defun company-complete-number (n)
1884 "Insert the Nth candidate.
1885 To show the number next to the candidates in some back-ends, enable
1886 `company-show-numbers'."
1887 (when (company-manual-begin)
1888 (and (or (< n 1) (> n company-candidates-length))
1889 (error "No candidate number %d" n))
1891 (company-finish (nth n company-candidates))))
1893 ;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;
1895 (defconst company-space-strings-limit 100)
1897 (defconst company-space-strings
1899 (dotimes (i company-space-strings-limit)
1900 (push (make-string (- company-space-strings-limit 1 i) ?\ ) lst))
1901 (apply 'vector lst)))
1903 (defun company-space-string (len)
1904 (if (< len company-space-strings-limit)
1905 (aref company-space-strings len)
1906 (make-string len ?\ )))
1908 (defun company-safe-substring (str from &optional to)
1909 (if (> from (string-width str))
1913 (move-to-column from)
1914 (let ((beg (point)))
1918 (concat (buffer-substring beg (point))
1919 (let ((padding (- to (current-column))))
1921 (company-space-string padding)))))
1922 (buffer-substring beg (point-max)))))))
1924 ;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;
1926 (defvar-local company-last-metadata nil)
1928 (defun company-fetch-metadata ()
1929 (let ((selected (nth company-selection company-candidates)))
1930 (unless (eq selected (car company-last-metadata))
1931 (setq company-last-metadata
1932 (cons selected (company-call-backend 'meta selected))))
1933 (cdr company-last-metadata)))
1935 (defun company-doc-buffer (&optional string)
1936 (with-current-buffer (get-buffer-create "*company-documentation*")
1943 (defvar company--electric-commands
1944 '(scroll-other-window scroll-other-window-down)
1945 "List of Commands that won't break out of electric commands.")
1947 (defmacro company--electric-do (&rest body)
1948 (declare (indent 0) (debug t))
1949 `(when (company-manual-begin)
1950 (save-window-excursion
1951 (let ((height (window-height))
1952 (row (company--row))
1955 (and (< (window-height) height)
1956 (< (- (window-height) row 2) company-tooltip-limit)
1957 (recenter (- (window-height) row 2)))
1958 (while (memq (setq cmd (key-binding (vector (list (read-event)))))
1959 company--electric-commands)
1960 (call-interactively cmd))
1961 (company--unread-last-input)))))
1963 (defun company--unread-last-input ()
1964 (when last-input-event
1965 (clear-this-command-keys t)
1966 (setq unread-command-events (list last-input-event))))
1968 (defun company-show-doc-buffer ()
1969 "Temporarily show the documentation buffer for the selection."
1971 (company--electric-do
1972 (let* ((selected (nth company-selection company-candidates))
1973 (doc-buffer (or (company-call-backend 'doc-buffer selected)
1974 (error "No documentation available"))))
1975 (with-current-buffer doc-buffer
1976 (goto-char (point-min)))
1977 (display-buffer doc-buffer t))))
1978 (put 'company-show-doc-buffer 'company-keep t)
1980 (defun company-show-location ()
1981 "Temporarily display a buffer showing the selected candidate in context."
1983 (company--electric-do
1984 (let* ((selected (nth company-selection company-candidates))
1985 (location (company-call-backend 'location selected))
1986 (pos (or (cdr location) (error "No location available")))
1987 (buffer (or (and (bufferp (car location)) (car location))
1988 (find-file-noselect (car location) t))))
1989 (with-selected-window (display-buffer buffer t)
1992 (if (bufferp (car location))
1994 (goto-char (point-min))
1995 (forward-line (1- pos))))
1996 (set-window-start nil (point))))))
1997 (put 'company-show-location 'company-keep t)
1999 ;;; package functions ;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;
2001 (defvar-local company-callback nil)
2003 (defun company-remove-callback (&optional ignored)
2004 (remove-hook 'company-completion-finished-hook company-callback t)
2005 (remove-hook 'company-completion-cancelled-hook 'company-remove-callback t)
2006 (remove-hook 'company-completion-finished-hook 'company-remove-callback t))
2008 (defun company-begin-backend (backend &optional callback)
2009 "Start a completion at point using BACKEND."
2010 (interactive (let ((val (completing-read "Company back-end: "
2012 'functionp nil "company-")))
2014 (list (intern val)))))
2015 (when (setq company-callback callback)
2016 (add-hook 'company-completion-finished-hook company-callback nil t))
2017 (add-hook 'company-completion-cancelled-hook 'company-remove-callback nil t)
2018 (add-hook 'company-completion-finished-hook 'company-remove-callback nil t)
2019 (setq company-backend backend)
2020 ;; Return non-nil if active.
2021 (or (company-manual-begin)
2022 (error "Cannot complete at point")))
2024 (defun company-begin-with (candidates
2025 &optional prefix-length require-match callback)
2026 "Start a completion at point.
2027 CANDIDATES is the list of candidates to use and PREFIX-LENGTH is the length
2028 of the prefix that already is in the buffer before point.
2031 CALLBACK is a function called with the selected result if the user
2032 successfully completes the input.
2034 Example: \(company-begin-with '\(\"foo\" \"foobar\" \"foobarbaz\"\)\)"
2035 (let ((begin-marker (copy-marker (point) t)))
2036 (company-begin-backend
2037 (lambda (command &optional arg &rest ignored)
2040 (when (equal (point) (marker-position begin-marker))
2041 (buffer-substring (- (point) (or prefix-length 0)) (point))))
2043 (all-completions arg candidates))
2048 (defun company-version (&optional show-version)
2049 "Get the Company version as string.
2051 If SHOW-VERSION is non-nil, show the version in the echo area."
2052 (interactive (list t))
2054 (insert-file-contents (find-library-name "company"))
2057 (message "Company version: %s" (lm-version))
2060 ;;; pseudo-tooltip ;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;
2062 (defvar-local company-pseudo-tooltip-overlay nil)
2064 (defvar-local company-tooltip-offset 0)
2066 (defun company-tooltip--lines-update-offset (selection num-lines limit)
2068 (setq company-tooltip-offset
2069 (max (min selection company-tooltip-offset)
2070 (- selection -1 limit)))
2072 (when (<= company-tooltip-offset 1)
2074 (setq company-tooltip-offset 0))
2076 (when (>= company-tooltip-offset (- num-lines limit 1))
2078 (when (= selection (1- num-lines))
2079 (cl-decf company-tooltip-offset)
2080 (when (<= company-tooltip-offset 1)
2081 (setq company-tooltip-offset 0)
2086 (defun company-tooltip--simple-update-offset (selection _num-lines limit)
2087 (setq company-tooltip-offset
2088 (if (< selection company-tooltip-offset)
2090 (max company-tooltip-offset
2091 (- selection limit -1)))))
2095 (defsubst company-round-tab (arg)
2096 (* (/ (+ arg tab-width) tab-width) tab-width))
2098 (defun company-plainify (str)
2099 (let ((prefix (get-text-property 0 'line-prefix str)))
2100 (when prefix ; Keep the original value unmodified, for no special reason.
2101 (setq str (concat prefix str))
2102 (remove-text-properties 0 (length str) '(line-prefix) str)))
2103 (let* ((pieces (split-string str "\t"))
2106 (setcar copy (company-safe-substring
2107 (car copy) 0 (company-round-tab (string-width (car copy)))))
2109 (apply 'concat pieces)))
2111 (defun company-fill-propertize (value annotation width selected left right)
2112 (let* ((margin (length left))
2113 (common (+ (or (company-call-backend 'match value)
2114 (length company-common)) margin))
2115 (ann-ralign company-tooltip-align-annotations)
2116 (ann-truncate (< width
2117 (+ (length value) (length annotation)
2118 (if ann-ralign 1 0))))
2119 (ann-start (+ margin
2123 (- width (length annotation)))
2125 (ann-end (min (+ ann-start (length annotation)) (+ margin width)))
2127 (if (or ann-truncate (not ann-ralign))
2128 (company-safe-substring
2130 (when (and annotation ann-ralign) " ")
2134 (company-safe-substring value 0
2135 (- width (length annotation)))
2138 (setq width (+ width margin (length right)))
2140 (add-text-properties 0 width '(face company-tooltip
2141 mouse-face company-tooltip-mouse)
2143 (add-text-properties margin common
2144 '(face company-tooltip-common
2145 mouse-face company-tooltip-mouse)
2147 (when (< ann-start ann-end)
2148 (add-text-properties ann-start ann-end
2149 '(face company-tooltip-annotation
2150 mouse-face company-tooltip-mouse)
2153 (if (and company-search-string
2154 (string-match (regexp-quote company-search-string) value
2155 (length company-prefix)))
2156 (let ((beg (+ margin (match-beginning 0)))
2157 (end (+ margin (match-end 0))))
2158 (add-text-properties beg end '(face company-tooltip-selection)
2160 (when (< beg common)
2161 (add-text-properties beg common
2162 '(face company-tooltip-common-selection)
2164 (add-text-properties 0 width '(face company-tooltip-selection
2165 mouse-face company-tooltip-selection)
2167 (add-text-properties margin common
2168 '(face company-tooltip-common-selection
2169 mouse-face company-tooltip-selection)
2175 (defun company-buffer-lines (beg end)
2178 (while (and (= 1 (vertical-motion 1))
2180 (let ((bound (min end (1- (point)))))
2181 ;; A visual line can contain several physical lines (e.g. with outline's
2182 ;; folding overlay). Take only the first one.
2183 (push (buffer-substring beg
2186 (re-search-forward "$" bound 'move)
2190 (unless (eq beg end)
2191 (push (buffer-substring beg end) lines))
2194 (defun company-modify-line (old new offset)
2195 (concat (company-safe-substring old 0 offset)
2197 (company-safe-substring old (+ offset (length new)))))
2199 (defsubst company--length-limit (lst limit)
2200 (if (nthcdr limit lst)
2204 (defun company--replacement-string (lines old column nl &optional align-top)
2205 (cl-decf column company-tooltip-margin)
2207 (when (and align-top company-tooltip-flip-when-above)
2208 (setq lines (reverse lines)))
2210 (let ((width (length (car lines)))
2211 (remaining-cols (- (+ (company--window-width) (window-hscroll))
2213 (when (> width remaining-cols)
2214 (cl-decf column (- width remaining-cols))))
2216 (let ((offset (and (< column 0) (- column)))
2221 ;; untouched lines first
2222 (dotimes (_ (- (length old) (length lines)))
2223 (push (pop old) new)))
2224 ;; length into old lines.
2226 (push (company-modify-line (pop old)
2227 (company--offset-line (pop lines) offset)
2229 ;; Append whole new lines.
2231 (push (concat (company-space-string column)
2232 (company--offset-line (pop lines) offset))
2235 (let ((str (concat (when nl "\n")
2236 (mapconcat 'identity (nreverse new) "\n")
2238 (font-lock-append-text-property 0 (length str) 'face 'default str)
2241 (defun company--offset-line (line offset)
2242 (if (and offset line)
2243 (substring line offset)
2246 (defun company--create-lines (selection limit)
2247 (let ((len company-candidates-length)
2249 (window-width (company--window-width))
2258 ;; Maybe clear old offset.
2259 (when (< len (+ company-tooltip-offset limit))
2260 (setq company-tooltip-offset 0))
2262 ;; Scroll to offset.
2263 (if (eq company-tooltip-offset-display 'lines)
2264 (setq limit (company-tooltip--lines-update-offset selection len limit))
2265 (company-tooltip--simple-update-offset selection len limit))
2268 ((eq company-tooltip-offset-display 'scrollbar)
2269 (setq scrollbar-bounds (company--scrollbar-bounds company-tooltip-offset
2271 ((eq company-tooltip-offset-display 'lines)
2272 (when (> company-tooltip-offset 0)
2273 (setq previous (format "...(%d)" company-tooltip-offset)))
2274 (setq remainder (- len limit company-tooltip-offset)
2275 remainder (when (> remainder 0)
2276 (setq remainder (format "...(%d)" remainder))))))
2278 (cl-decf selection company-tooltip-offset)
2279 (setq width (max (length previous) (length remainder))
2280 lines (nthcdr company-tooltip-offset company-candidates)
2284 (cl-decf window-width (* 2 company-tooltip-margin))
2285 (when scrollbar-bounds (cl-decf window-width))
2288 (let* ((value (pop lines-copy))
2289 (annotation (company-call-backend 'annotation value)))
2290 (when (and annotation company-tooltip-align-annotations)
2291 ;; `lisp-completion-at-point' adds a space.
2292 (setq annotation (comment-string-strip annotation t nil)))
2293 (push (cons value annotation) items)
2294 (setq width (max (+ (length value)
2295 (if (and annotation company-tooltip-align-annotations)
2296 (1+ (length annotation))
2297 (length annotation)))
2300 (setq width (min window-width
2301 (max company-tooltip-minimum-width
2302 (if (and company-show-numbers
2303 (< company-tooltip-offset 10))
2307 ;; number can make tooltip too long
2308 (when company-show-numbers
2309 (setq numbered company-tooltip-offset))
2311 (let ((items (nreverse items)) new)
2313 (push (company--scrollpos-line previous width) new))
2316 (let* ((item (pop items))
2317 (str (company-reformat (car item)))
2318 (annotation (cdr item))
2319 (right (company-space-string company-tooltip-margin))
2321 (when (< numbered 10)
2324 (setq right (concat (format " %d" (mod numbered 10)) right)))
2326 (company-fill-propertize str annotation
2327 width (equal i selection)
2328 (company-space-string
2329 company-tooltip-margin)
2331 (when scrollbar-bounds
2332 (company--scrollbar i scrollbar-bounds)))
2336 (push (company--scrollpos-line remainder width) new))
2340 (defun company--scrollbar-bounds (offset limit length)
2341 (when (> length limit)
2342 (let* ((size (ceiling (* limit (float limit)) length))
2343 (lower (floor (* limit (float offset)) length))
2344 (upper (+ lower size -1)))
2345 (cons lower upper))))
2347 (defun company--scrollbar (i bounds)
2348 (propertize " " 'face
2349 (if (and (>= i (car bounds)) (<= i (cdr bounds)))
2350 'company-scrollbar-fg
2351 'company-scrollbar-bg)))
2353 (defun company--scrollpos-line (text width)
2354 (propertize (concat (company-space-string company-tooltip-margin)
2355 (company-safe-substring text 0 width)
2356 (company-space-string company-tooltip-margin))
2357 'face 'company-tooltip))
2361 (defsubst company--window-inner-height ()
2362 (let ((edges (window-inside-edges)))
2363 (- (nth 3 edges) (nth 1 edges))))
2365 (defsubst company--window-width ()
2366 (let ((ww (window-width)))
2367 ;; Account for the line continuation column.
2368 (when (zerop (cadr (window-fringes)))
2370 (unless (or (display-graphic-p)
2371 (version< "24.3.1" emacs-version))
2372 ;; Emacs 24.3 and earlier included margins
2373 ;; in window-width when in TTY.
2375 (let ((margins (window-margins)))
2376 (+ (or (car margins) 0)
2377 (or (cdr margins) 0)))))
2380 (defun company--pseudo-tooltip-height ()
2381 "Calculate the appropriate tooltip height.
2382 Returns a negative number if the tooltip should be displayed above point."
2383 (let* ((lines (company--row))
2384 (below (- (company--window-inner-height) 1 lines)))
2385 (if (and (< below (min company-tooltip-minimum company-candidates-length))
2387 (- (max 3 (min company-tooltip-limit lines)))
2388 (max 3 (min company-tooltip-limit below)))))
2390 (defun company-pseudo-tooltip-show (row column selection)
2391 (company-pseudo-tooltip-hide)
2394 (let* ((height (company--pseudo-tooltip-height))
2398 (setq row (+ row height -1)
2401 (let* ((nl (< (move-to-window-line row) row))
2403 (end (save-excursion
2404 (move-to-window-line (+ row (abs height)))
2406 (ov (make-overlay beg end))
2407 (args (list (mapcar 'company-plainify
2408 (company-buffer-lines beg end))
2411 (setq company-pseudo-tooltip-overlay ov)
2412 (overlay-put ov 'company-replacement-args args)
2414 (let ((lines (company--create-lines selection (abs height))))
2415 (overlay-put ov 'company-after
2416 (apply 'company--replacement-string lines args))
2417 (overlay-put ov 'company-width (string-width (car lines))))
2419 (overlay-put ov 'company-column column)
2420 (overlay-put ov 'company-height height)))))
2422 (defun company-pseudo-tooltip-show-at-point (pos column-offset)
2423 (let ((row (company--row pos))
2424 (col (- (company--column pos) column-offset)))
2425 (when (< col 0) (setq col 0))
2426 (company-pseudo-tooltip-show (1+ row) col company-selection)))
2428 (defun company-pseudo-tooltip-edit (selection)
2429 (let* ((height (overlay-get company-pseudo-tooltip-overlay 'company-height))
2430 (lines (company--create-lines selection (abs height))))
2431 (overlay-put company-pseudo-tooltip-overlay 'company-width
2432 (string-width (car lines)))
2433 (overlay-put company-pseudo-tooltip-overlay 'company-after
2434 (apply 'company--replacement-string
2436 (overlay-get company-pseudo-tooltip-overlay
2437 'company-replacement-args)))))
2439 (defun company-pseudo-tooltip-hide ()
2440 (when company-pseudo-tooltip-overlay
2441 (delete-overlay company-pseudo-tooltip-overlay)
2442 (setq company-pseudo-tooltip-overlay nil)))
2444 (defun company-pseudo-tooltip-hide-temporarily ()
2445 (when (overlayp company-pseudo-tooltip-overlay)
2446 (overlay-put company-pseudo-tooltip-overlay 'invisible nil)
2447 (overlay-put company-pseudo-tooltip-overlay 'line-prefix nil)
2448 (overlay-put company-pseudo-tooltip-overlay 'after-string nil)))
2450 (defun company-pseudo-tooltip-unhide ()
2451 (when company-pseudo-tooltip-overlay
2452 (overlay-put company-pseudo-tooltip-overlay 'invisible t)
2453 ;; Beat outline's folding overlays, at least.
2454 (overlay-put company-pseudo-tooltip-overlay 'priority 1)
2455 ;; No (extra) prefix for the first line.
2456 (overlay-put company-pseudo-tooltip-overlay 'line-prefix "")
2457 (overlay-put company-pseudo-tooltip-overlay 'after-string
2458 (overlay-get company-pseudo-tooltip-overlay 'company-after))
2459 (overlay-put company-pseudo-tooltip-overlay 'window (selected-window))))
2461 (defun company-pseudo-tooltip-guard ()
2463 (save-excursion (beginning-of-visual-line))
2464 (let ((ov company-pseudo-tooltip-overlay))
2465 (when (>= (overlay-get ov 'company-height) 0)
2466 (buffer-substring-no-properties (point) (overlay-start ov))))))
2468 (defun company-pseudo-tooltip-frontend (command)
2469 "`company-mode' front-end similar to a tooltip but based on overlays."
2471 (pre-command (company-pseudo-tooltip-hide-temporarily))
2473 (unless (when (overlayp company-pseudo-tooltip-overlay)
2474 (let* ((ov company-pseudo-tooltip-overlay)
2475 (old-height (overlay-get ov 'company-height))
2476 (new-height (company--pseudo-tooltip-height)))
2478 (>= (* old-height new-height) 0)
2479 (>= (abs old-height) (abs new-height))
2480 (equal (company-pseudo-tooltip-guard)
2481 (overlay-get ov 'company-guard)))))
2483 (company-pseudo-tooltip-show-at-point (point) (length company-prefix))
2484 (overlay-put company-pseudo-tooltip-overlay
2485 'company-guard (company-pseudo-tooltip-guard)))
2486 (company-pseudo-tooltip-unhide))
2487 (hide (company-pseudo-tooltip-hide)
2488 (setq company-tooltip-offset 0))
2489 (update (when (overlayp company-pseudo-tooltip-overlay)
2490 (company-pseudo-tooltip-edit company-selection)))))
2492 (defun company-pseudo-tooltip-unless-just-one-frontend (command)
2493 "`company-pseudo-tooltip-frontend', but not shown for single candidates."
2494 (unless (and (eq command 'post-command)
2495 (company--show-inline-p))
2496 (company-pseudo-tooltip-frontend command)))
2498 ;;; overlay ;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;
2500 (defvar-local company-preview-overlay nil)
2502 (defun company-preview-show-at-point (pos)
2503 (company-preview-hide)
2505 (setq company-preview-overlay (make-overlay pos (1+ pos)))
2507 (let ((completion (nth company-selection company-candidates)))
2508 (setq completion (propertize completion 'face 'company-preview))
2509 (add-text-properties 0 (length company-common)
2510 '(face company-preview-common) completion)
2512 ;; Add search string
2513 (and company-search-string
2514 (string-match (regexp-quote company-search-string) completion)
2515 (add-text-properties (match-beginning 0)
2517 '(face company-preview-search)
2520 (setq completion (company-strip-prefix completion))
2522 (and (equal pos (point))
2523 (not (equal completion ""))
2524 (add-text-properties 0 1 '(cursor t) completion))
2526 (overlay-put company-preview-overlay 'display
2527 (concat completion (unless (eq pos (point-max))
2528 (buffer-substring pos (1+ pos)))))
2529 (overlay-put company-preview-overlay 'window (selected-window))))
2531 (defun company-preview-hide ()
2532 (when company-preview-overlay
2533 (delete-overlay company-preview-overlay)
2534 (setq company-preview-overlay nil)))
2536 (defun company-preview-frontend (command)
2537 "`company-mode' front-end showing the selection as if it had been inserted."
2539 (`pre-command (company-preview-hide))
2540 (`post-command (company-preview-show-at-point (point)))
2541 (`hide (company-preview-hide))))
2543 (defun company-preview-if-just-one-frontend (command)
2544 "`company-preview-frontend', but only shown for single candidates."
2545 (when (or (not (eq command 'post-command))
2546 (company--show-inline-p))
2547 (company-preview-frontend command)))
2549 (defun company--show-inline-p ()
2550 (and (not (cdr company-candidates))
2552 (string-prefix-p company-prefix company-common
2553 (company-call-backend 'ignore-case))))
2555 ;;; echo ;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;
2557 (defvar-local company-echo-last-msg nil)
2559 (defvar company-echo-timer nil)
2561 (defvar company-echo-delay .01)
2563 (defun company-echo-show (&optional getter)
2565 (setq company-echo-last-msg (funcall getter)))
2566 (let ((message-log-max nil))
2567 (if company-echo-last-msg
2568 (message "%s" company-echo-last-msg)
2571 (defun company-echo-show-soon (&optional getter)
2572 (when company-echo-timer
2573 (cancel-timer company-echo-timer))
2574 (setq company-echo-timer (run-with-timer 0 nil 'company-echo-show getter)))
2576 (defsubst company-echo-show-when-idle (&optional getter)
2577 (when (sit-for company-echo-delay)
2578 (company-echo-show getter)))
2580 (defun company-echo-format ()
2582 (let ((limit (window-width (minibuffer-window)))
2584 ;; Roll to selection.
2585 (candidates (nthcdr company-selection company-candidates))
2586 (i (if company-show-numbers company-selection 99999))
2590 (setq comp (company-reformat (pop candidates))
2591 len (+ len 1 (length comp)))
2595 (setq comp (propertize (format "%d: %s" i comp)
2596 'face 'company-echo))
2599 (add-text-properties 3 (+ 3 (length company-common))
2600 '(face company-echo-common) comp))
2601 (setq comp (propertize comp 'face 'company-echo))
2602 (add-text-properties 0 (length company-common)
2603 '(face company-echo-common) comp))
2605 (setq candidates nil)
2608 (mapconcat 'identity (nreverse msg) " ")))
2610 (defun company-echo-strip-common-format ()
2612 (let ((limit (window-width (minibuffer-window)))
2613 (len (+ (length company-prefix) 2))
2614 ;; Roll to selection.
2615 (candidates (nthcdr company-selection company-candidates))
2616 (i (if company-show-numbers company-selection 99999))
2620 (setq comp (company-strip-prefix (pop candidates))
2621 len (+ len 2 (length comp)))
2624 (setq comp (format "%s (%d)" comp i))
2628 (setq candidates nil)
2629 (push (propertize comp 'face 'company-echo) msg)))
2631 (concat (propertize company-prefix 'face 'company-echo-common) "{"
2632 (mapconcat 'identity (nreverse msg) ", ")
2635 (defun company-echo-hide ()
2636 (unless (equal company-echo-last-msg "")
2637 (setq company-echo-last-msg "")
2638 (company-echo-show)))
2640 (defun company-echo-frontend (command)
2641 "`company-mode' front-end showing the candidates in the echo area."
2643 (`post-command (company-echo-show-soon 'company-echo-format))
2644 (`hide (company-echo-hide))))
2646 (defun company-echo-strip-common-frontend (command)
2647 "`company-mode' front-end showing the candidates in the echo area."
2649 (`post-command (company-echo-show-soon 'company-echo-strip-common-format))
2650 (`hide (company-echo-hide))))
2652 (defun company-echo-metadata-frontend (command)
2653 "`company-mode' front-end showing the documentation in the echo area."
2655 (`post-command (company-echo-show-when-idle 'company-fetch-metadata))
2656 (`hide (company-echo-hide))))
2659 ;;; company.el ends here