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$")
85 "Extensible inline text completion mechanism"
90 (defface company-tooltip
91 '((default :foreground "black")
92 (((class color) (min-colors 88) (background light))
93 (:background "cornsilk"))
94 (((class color) (min-colors 88) (background dark))
95 (:background "yellow")))
96 "Face used for the tooltip.")
98 (defface company-tooltip-selection
99 '((default :inherit company-tooltip)
100 (((class color) (min-colors 88) (background light))
101 (:background "light blue"))
102 (((class color) (min-colors 88) (background dark))
103 (:background "orange1"))
104 (t (:background "green")))
105 "Face used for the selection in the tooltip.")
107 (defface company-tooltip-mouse
108 '((default :inherit highlight))
109 "Face used for the tooltip item under the mouse.")
111 (defface company-tooltip-common
112 '((default :inherit company-tooltip)
113 (((background light))
114 :foreground "darkred")
117 "Face used for the common completion in the tooltip.")
119 (defface company-tooltip-common-selection
120 '((default :inherit company-tooltip-selection)
121 (((background light))
122 :foreground "darkred")
125 "Face used for the selected common completion in the tooltip.")
127 (defface company-tooltip-annotation
128 '((default :inherit company-tooltip)
129 (((background light))
130 :foreground "firebrick4")
133 "Face used for the annotation in the tooltip.")
135 (defface company-scrollbar-fg
136 '((((background light))
137 :background "darkred")
140 "Face used for the tooltip scrollbar thumb.")
142 (defface company-scrollbar-bg
143 '((default :inherit company-tooltip)
144 (((background light))
148 "Face used for the tooltip scrollbar background.")
150 (defface company-preview
151 '((((background light))
152 :inherit company-tooltip-selection)
155 :foreground "wheat"))
156 "Face used for the completion preview.")
158 (defface company-preview-common
159 '((((background light))
160 :inherit company-tooltip-selection)
162 :inherit company-preview
164 "Face used for the common part of the completion preview.")
166 (defface company-preview-search
167 '((((background light))
168 :inherit company-tooltip-common-selection)
170 :inherit company-preview
171 :background "blue1"))
172 "Face used for the search string in the completion preview.")
174 (defface company-echo nil
175 "Face used for completions in the echo area.")
177 (defface company-echo-common
178 '((((background dark)) (:foreground "firebrick1"))
179 (((background light)) (:background "firebrick4")))
180 "Face used for the common part of completions in the echo area.")
182 (defun company-frontends-set (variable value)
184 (let ((remainder value))
185 (setcdr remainder (delq (car remainder) (cdr remainder))))
186 (and (memq 'company-pseudo-tooltip-unless-just-one-frontend value)
187 (memq 'company-pseudo-tooltip-frontend value)
188 (error "Pseudo tooltip frontend cannot be used twice"))
189 (and (memq 'company-preview-if-just-one-frontend value)
190 (memq 'company-preview-frontend value)
191 (error "Preview frontend cannot be used twice"))
192 (and (memq 'company-echo value)
193 (memq 'company-echo-metadata-frontend value)
194 (error "Echo area cannot be used twice"))
195 ;; preview must come last
196 (dolist (f '(company-preview-if-just-one-frontend company-preview-frontend))
198 (setq value (append (delq f value) (list f)))))
199 (set variable value))
201 (defcustom company-frontends '(company-pseudo-tooltip-unless-just-one-frontend
202 company-preview-if-just-one-frontend
203 company-echo-metadata-frontend)
204 "The list of active front-ends (visualizations).
205 Each front-end is a function that takes one argument. It is called with
206 one of the following arguments:
208 `show': When the visualization should start.
210 `hide': When the visualization should end.
212 `update': When the data has been updated.
214 `pre-command': Before every command that is executed while the
215 visualization is active.
217 `post-command': After every command that is executed while the
218 visualization is active.
220 The visualized data is stored in `company-prefix', `company-candidates',
221 `company-common', `company-selection', `company-point' and
222 `company-search-string'."
223 :set 'company-frontends-set
224 :type '(repeat (choice (const :tag "echo" company-echo-frontend)
225 (const :tag "echo, strip common"
226 company-echo-strip-common-frontend)
227 (const :tag "show echo meta-data in echo"
228 company-echo-metadata-frontend)
229 (const :tag "pseudo tooltip"
230 company-pseudo-tooltip-frontend)
231 (const :tag "pseudo tooltip, multiple only"
232 company-pseudo-tooltip-unless-just-one-frontend)
233 (const :tag "preview" company-preview-frontend)
234 (const :tag "preview, unique only"
235 company-preview-if-just-one-frontend)
236 (function :tag "custom function" nil))))
238 (defcustom company-tooltip-limit 10
239 "The maximum number of candidates in the tooltip."
242 (defcustom company-tooltip-minimum 6
243 "The minimum height of the tooltip.
244 If this many lines are not available, prefer to display the tooltip above."
247 (defcustom company-tooltip-minimum-width 0
248 "The minimum width of the tooltip's inner area.
249 This doesn't include the margins and the scroll bar."
252 (defcustom company-tooltip-margin 1
253 "Width of margin columns to show around the toolip."
256 (defcustom company-tooltip-offset-display 'scrollbar
257 "Method using which the tooltip displays scrolling position.
258 `scrollbar' means draw a scrollbar to the right of the items.
259 `lines' means wrap items in lines with \"before\" and \"after\" counters."
260 :type '(choice (const :tag "Scrollbar" scrollbar)
261 (const :tag "Two lines" lines)))
263 (defcustom company-tooltip-align-annotations nil
264 "When non-nil, align annotations to the right tooltip border."
267 (defcustom company-tooltip-flip-when-above nil
268 "Whether to flip the tooltip when it's above the current line."
270 :package-version '(company . "0.8.1"))
272 (defvar company-safe-backends
273 '((company-abbrev . "Abbrev")
274 (company-bbdb . "BBDB")
275 (company-capf . "completion-at-point-functions")
276 (company-clang . "Clang")
277 (company-cmake . "CMake")
278 (company-css . "CSS")
279 (company-dabbrev . "dabbrev for plain text")
280 (company-dabbrev-code . "dabbrev for code")
281 (company-eclim . "Eclim (an Eclipse interface)")
282 (company-elisp . "Emacs Lisp")
283 (company-etags . "etags")
284 (company-files . "Files")
285 (company-gtags . "GNU Global")
286 (company-ispell . "Ispell")
287 (company-keywords . "Programming language keywords")
288 (company-nxml . "nxml")
289 (company-oddmuse . "Oddmuse")
290 (company-pysmell . "PySmell")
291 (company-ropemacs . "ropemacs")
292 (company-semantic . "Semantic")
293 (company-tempo . "Tempo templates")
294 (company-xcode . "Xcode")))
295 (put 'company-safe-backends 'risky-local-variable t)
297 (defun company-safe-backends-p (backends)
298 (and (consp backends)
299 (not (cl-dolist (backend backends)
300 (unless (if (consp backend)
301 (company-safe-backends-p backend)
302 (assq backend company-safe-backends))
305 (defcustom company-backends `(,@(unless (version< "24.3.50" emacs-version)
306 (list 'company-elisp))
308 company-nxml company-css
309 company-eclim company-semantic company-clang
310 company-xcode company-ropemacs company-cmake
312 (company-dabbrev-code company-gtags company-etags
314 company-oddmuse company-files company-dabbrev)
315 "The list of active back-ends (completion engines).
317 `company-begin-backend' can be used to start a specific back-end,
318 `company-other-backend' will skip to the next matching back-end in the list.
320 Each back-end is a function that takes a variable number of arguments.
321 The first argument is the command requested from the back-end. It is one
324 `prefix': The back-end should return the text to be completed. It must be
325 text immediately before point. Returning nil passes control to the next
326 back-end. The function should return `stop' if it should complete but
327 cannot \(e.g. if it is in the middle of a string\). Instead of a string,
328 the back-end may return a cons where car is the prefix and cdr is used in
329 `company-minimum-prefix-length' test. It must be either number or t, and
330 in the latter case the test automatically succeeds.
332 `candidates': The second argument is the prefix to be completed. The
333 return value should be a list of candidates that match the prefix.
335 Non-prefix matches are also supported (candidates that don't start with the
336 prefix, but match it in some backend-defined way). Backends that use this
337 feature must disable cache (return t to `no-cache') and should also respond
342 `sorted': Return t here to indicate that the candidates are sorted and will
343 not need to be sorted again.
345 `duplicates': If non-nil, company will take care of removing duplicates
348 `no-cache': Usually company doesn't ask for candidates again as completion
349 progresses, unless the back-end returns t for this command. The second
350 argument is the latest prefix.
352 `meta': The second argument is a completion candidate. Return a (short)
353 documentation string for it.
355 `doc-buffer': The second argument is a completion candidate. Return a
356 buffer with documentation for it. Preferably use `company-doc-buffer',
358 `location': The second argument is a completion candidate. Return the cons
359 of buffer and buffer location, or of file and line number where the
360 completion candidate was defined.
362 `annotation': The second argument is a completion candidate. Return a
363 string to be displayed inline with the candidate in the popup. If
364 duplicates are removed by company, candidates with equal string values will
365 be kept if they have different annotations. For that to work properly,
366 backends should store the related information on candidates using text
369 `match': The second argument is a completion candidate. Backends that
370 provide non-prefix completions should return the position of the end of
371 text in the candidate that matches `prefix'. It will be used when
374 `require-match': If this returns t, the user is not allowed to enter
375 anything not offered as a candidate. Use with care! The default value nil
376 gives the user that choice with `company-require-match'. Return value
377 `never' overrides that option the other way around.
379 `init': Called once for each buffer. The back-end can check for external
380 programs and files and load any required libraries. Raising an error here
381 will show up in message log once, and the back-end will not be used for
384 `post-completion': Called after a completion candidate has been inserted
385 into the buffer. The second argument is the candidate. Can be used to
386 modify it, e.g. to expand a snippet.
388 The back-end should return nil for all commands it does not support or
389 does not know about. It should also be callable interactively and use
390 `company-begin-backend' to start itself in that case.
394 An element of `company-backends' can also itself be a list of back-ends,
395 then it's considered to be a \"grouped\" back-end.
397 When possible, commands taking a candidate as an argument are dispatched to
398 the back-end it came from. In other cases, the first non-nil value among
399 all the back-ends is returned.
401 The latter is the case for the `prefix' command. But if the group contains
402 the keyword `:with', the back-ends after it are ignored for this command.
404 The completions from back-ends in a group are merged (but only from those
405 that return the same `prefix').
407 Asynchronous back-ends:
409 The return value of each command can also be a cons (:async . FETCHER)
410 where FETCHER is a function of one argument, CALLBACK. When the data
411 arrives, FETCHER must call CALLBACK and pass it the appropriate return
412 value, as described above.
414 True asynchronous operation is only supported for command `candidates', and
415 only during idle completion. Other commands will block the user interface,
416 even if the back-end uses the asynchronous calling convention."
420 ,@(mapcar (lambda (b) `(const :tag ,(cdr b) ,(car b)))
421 company-safe-backends)
422 (symbol :tag "User defined")
423 (repeat :tag "Merged Back-ends"
424 (choice :tag "Back-end"
425 ,@(mapcar (lambda (b)
426 `(const :tag ,(cdr b) ,(car b)))
427 company-safe-backends)
428 (const :tag "With" :with)
429 (symbol :tag "User defined"))))))
431 (put 'company-backends 'safe-local-variable 'company-safe-backends-p)
433 (defcustom company-transformers nil
434 "Functions to change the list of candidates received from backends,
435 after sorting and removal of duplicates (if appropriate).
436 Each function gets called with the return value of the previous one."
438 (const :tag "None" nil)
439 (const :tag "Sort by occurrence" (company-sort-by-occurrence))
440 (repeat :tag "User defined" (function))))
442 (defcustom company-completion-started-hook nil
443 "Hook run when company starts completing.
444 The hook is called with one argument that is non-nil if the completion was
448 (defcustom company-completion-cancelled-hook nil
449 "Hook run when company cancels completing.
450 The hook is called with one argument that is non-nil if the completion was
454 (defcustom company-completion-finished-hook nil
455 "Hook run when company successfully completes.
456 The hook is called with the selected candidate as an argument.
458 If you indend to use it to post-process candidates from a specific
459 back-end, consider using the `post-completion' command instead."
462 (defcustom company-minimum-prefix-length 3
463 "The minimum prefix length for idle completion."
464 :type '(integer :tag "prefix length"))
466 (defcustom company-abort-manual-when-too-short nil
467 "If enabled, cancel a manually started completion when the prefix gets
468 shorter than both `company-minimum-prefix-length' and the length of the
469 prefix it was started from."
472 (defcustom company-require-match 'company-explicit-action-p
473 "If enabled, disallow non-matching input.
474 This can be a function do determine if a match is required.
476 This can be overridden by the back-end, if it returns t or `never' to
477 `require-match'. `company-auto-complete' also takes precedence over this."
478 :type '(choice (const :tag "Off" nil)
479 (function :tag "Predicate function")
480 (const :tag "On, if user interaction took place"
481 'company-explicit-action-p)
482 (const :tag "On" t)))
484 (defcustom company-auto-complete nil
485 "Determines when to auto-complete.
486 If this is enabled, all characters from `company-auto-complete-chars'
487 trigger insertion of the selected completion candidate.
488 This can also be a function."
489 :type '(choice (const :tag "Off" nil)
490 (function :tag "Predicate function")
491 (const :tag "On, if user interaction took place"
492 'company-explicit-action-p)
493 (const :tag "On" t)))
495 (defcustom company-auto-complete-chars '(?\ ?\) ?.)
496 "Determines which characters trigger auto-completion.
497 See `company-auto-complete'. If this is a string, each string character
498 tiggers auto-completion. If it is a list of syntax description characters (see
499 `modify-syntax-entry'), all characters with that syntax auto-complete.
501 This can also be a function, which is called with the new input and should
502 return non-nil if company should auto-complete.
504 A character that is part of a valid candidate never triggers auto-completion."
505 :type '(choice (string :tag "Characters")
507 (const :tag "Whitespace" ?\ )
508 (const :tag "Symbol" ?_)
509 (const :tag "Opening parentheses" ?\()
510 (const :tag "Closing parentheses" ?\))
511 (const :tag "Word constituent" ?w)
512 (const :tag "Punctuation." ?.)
513 (const :tag "String quote." ?\")
514 (const :tag "Paired delimiter." ?$)
515 (const :tag "Expression quote or prefix operator." ?\')
516 (const :tag "Comment starter." ?<)
517 (const :tag "Comment ender." ?>)
518 (const :tag "Character-quote." ?/)
519 (const :tag "Generic string fence." ?|)
520 (const :tag "Generic comment fence." ?!))
521 (function :tag "Predicate function")))
523 (defcustom company-idle-delay .5
524 "The idle delay in seconds until completion starts automatically.
525 A value of nil means no idle completion, t means show candidates
526 immediately when a prefix of `company-minimum-prefix-length' is reached."
527 :type '(choice (const :tag "never (nil)" nil)
528 (const :tag "immediate (t)" t)
529 (number :tag "seconds")))
531 (defcustom company-begin-commands '(self-insert-command org-self-insert-command)
532 "A list of commands after which idle completion is allowed.
533 If this is t, it can show completions after any command. See
534 `company-idle-delay'.
536 Alternatively, any command with a non-nil `company-begin' property is
537 treated as if it was on this list."
538 :type '(choice (const :tag "Any command" t)
539 (const :tag "Self insert command" '(self-insert-command))
540 (repeat :tag "Commands" function)))
542 (defcustom company-continue-commands '(not save-buffer save-some-buffers
543 save-buffers-kill-terminal
544 save-buffers-kill-emacs)
545 "A list of commands that are allowed during completion.
546 If this is t, or if `company-begin-commands' is t, any command is allowed.
547 Otherwise, the value must be a list of symbols. If it starts with `not',
548 the cdr is the list of commands that abort completion. Otherwise, all
549 commands except those in that list, or in `company-begin-commands', or
550 commands in the `company-' namespace, abort completion."
551 :type '(choice (const :tag "Any command" t)
552 (cons :tag "Any except"
554 (repeat :tag "Commands" function))
555 (repeat :tag "Commands" function)))
557 (defcustom company-show-numbers nil
558 "If enabled, show quick-access numbers for the first ten candidates."
559 :type '(choice (const :tag "off" nil)
560 (const :tag "on" t)))
562 (defcustom company-selection-wrap-around nil
563 "If enabled, selecting item before first or after last wraps around."
564 :type '(choice (const :tag "off" nil)
565 (const :tag "on" t)))
567 (defvar company-end-of-buffer-workaround t
568 "Work around a visualization bug when completing at the end of the buffer.
569 The work-around consists of adding a newline.")
571 (defvar company-async-wait 0.03
572 "Pause between checks to see if the value's been set when turning an
573 asynchronous call into synchronous.")
575 (defvar company-async-timeout 2
576 "Maximum wait time for a value to be set during asynchronous call.")
578 ;;; mode ;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;
580 (defvar company-mode-map (make-sparse-keymap)
581 "Keymap used by `company-mode'.")
583 (defvar company-active-map
584 (let ((keymap (make-sparse-keymap)))
585 (define-key keymap "\e\e\e" 'company-abort)
586 (define-key keymap "\C-g" 'company-abort)
587 (define-key keymap (kbd "M-n") 'company-select-next)
588 (define-key keymap (kbd "M-p") 'company-select-previous)
589 (define-key keymap (kbd "<down>") 'company-select-next-or-abort)
590 (define-key keymap (kbd "<up>") 'company-select-previous-or-abort)
591 (define-key keymap [down-mouse-1] 'ignore)
592 (define-key keymap [down-mouse-3] 'ignore)
593 (define-key keymap [mouse-1] 'company-complete-mouse)
594 (define-key keymap [mouse-3] 'company-select-mouse)
595 (define-key keymap [up-mouse-1] 'ignore)
596 (define-key keymap [up-mouse-3] 'ignore)
597 (define-key keymap [return] 'company-complete-selection)
598 (define-key keymap (kbd "RET") 'company-complete-selection)
599 (define-key keymap [tab] 'company-complete-common)
600 (define-key keymap (kbd "TAB") 'company-complete-common)
601 (define-key keymap (kbd "<f1>") 'company-show-doc-buffer)
602 (define-key keymap "\C-w" 'company-show-location)
603 (define-key keymap "\C-s" 'company-search-candidates)
604 (define-key keymap "\C-\M-s" 'company-filter-candidates)
606 (define-key keymap (vector (+ (aref (kbd "M-0") 0) i))
609 (company-complete-number ,(if (zerop i) 10 i)))))
612 "Keymap that is enabled during an active completion.")
614 (defvar company--disabled-backends nil)
616 (defun company-init-backend (backend)
617 (and (symbolp backend)
618 (not (fboundp backend))
619 (ignore-errors (require backend nil t)))
624 (funcall backend 'init)
625 (put backend 'company-init t))
627 (put backend 'company-init 'failed)
628 (unless (memq backend company--disabled-backends)
629 (message "Company back-end '%s' could not be initialized:\n%s"
630 backend (error-message-string err)))
631 (cl-pushnew backend company--disabled-backends)
633 ;; No initialization for lambdas.
634 ((functionp backend) t)
635 (t ;; Must be a list.
636 (cl-dolist (b backend)
638 (company-init-backend b))))))
640 (defvar company-default-lighter " company")
642 (defvar company-lighter company-default-lighter)
643 (make-variable-buffer-local 'company-lighter)
646 (define-minor-mode company-mode
647 "\"complete anything\"; is an in-buffer completion framework.
648 Completion starts automatically, depending on the values
649 `company-idle-delay' and `company-minimum-prefix-length'.
651 Completion can be controlled with the commands:
652 `company-complete-common', `company-complete-selection', `company-complete',
653 `company-select-next', `company-select-previous'. If these commands are
654 called before `company-idle-delay', completion will also start.
656 Completions can be searched with `company-search-candidates' or
657 `company-filter-candidates'. These can be used while completion is
660 The completion data is retrieved using `company-backends' and displayed
661 using `company-frontends'. If you want to start a specific back-end, call
662 it interactively or use `company-begin-backend'.
664 regular keymap (`company-mode-map'):
667 keymap during active completions (`company-active-map'):
669 \\{company-active-map}"
670 nil company-lighter company-mode-map
673 (add-hook 'pre-command-hook 'company-pre-command nil t)
674 (add-hook 'post-command-hook 'company-post-command nil t)
675 (mapc 'company-init-backend company-backends))
676 (remove-hook 'pre-command-hook 'company-pre-command t)
677 (remove-hook 'post-command-hook 'company-post-command t)
679 (kill-local-variable 'company-point)))
681 (defcustom company-global-modes t
682 "Modes for which `company-mode' mode is turned on by `global-company-mode'.
683 If nil, means no modes. If t, then all major modes have it turned on.
684 If a list, it should be a list of `major-mode' symbol names for which
685 `company-mode' should be automatically turned on. The sense of the list is
686 negated if it begins with `not'. For example:
688 means that `company-mode' is turned on for buffers in C and C++ modes only.
690 means that `company-mode' is always turned on except in `message-mode' buffers."
691 :type '(choice (const :tag "none" nil)
693 (set :menu-tag "mode specific" :tag "modes"
695 (const :tag "Except" not)
696 (repeat :inline t (symbol :tag "mode")))))
699 (define-globalized-minor-mode global-company-mode company-mode company-mode-on)
701 (defun company-mode-on ()
702 (when (and (not (or noninteractive (eq (aref (buffer-name) 0) ?\s)))
703 (cond ((eq company-global-modes t)
705 ((eq (car-safe company-global-modes) 'not)
706 (not (memq major-mode (cdr company-global-modes))))
707 (t (memq major-mode company-global-modes))))
710 (defsubst company-assert-enabled ()
712 (company-uninstall-map)
713 (error "Company not enabled")))
715 ;;; keymaps ;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;
717 (defvar company-my-keymap nil)
718 (make-variable-buffer-local 'company-my-keymap)
720 (defvar company-emulation-alist '((t . nil)))
722 (defsubst company-enable-overriding-keymap (keymap)
723 (company-uninstall-map)
724 (setq company-my-keymap keymap))
726 (defun company-ensure-emulation-alist ()
727 (unless (eq 'company-emulation-alist (car emulation-mode-map-alists))
728 (setq emulation-mode-map-alists
729 (cons 'company-emulation-alist
730 (delq 'company-emulation-alist emulation-mode-map-alists)))))
732 (defun company-install-map ()
733 (unless (or (cdar company-emulation-alist)
734 (null company-my-keymap))
735 (setf (cdar company-emulation-alist) company-my-keymap)))
737 (defun company-uninstall-map ()
738 (setf (cdar company-emulation-alist) nil))
741 ;; Emacs calculates the active keymaps before reading the event. That means we
742 ;; cannot change the keymap from a timer. So we send a bogus command.
743 ;; XXX: Seems not to be needed anymore in Emacs 24.4
744 (defun company-ignore ()
746 (setq this-command last-command))
748 (global-set-key '[31415926] 'company-ignore)
750 (defun company-input-noop ()
751 (push 31415926 unread-command-events))
753 (defun company--column (&optional pos)
755 (when pos (goto-char pos))
759 (narrow-to-region (point) (point-max))
760 (let ((prefix (get-text-property (point) 'line-prefix)))
761 (if prefix (length prefix) 0)))
764 (defun company--row (&optional pos)
766 (when pos (goto-char pos))
767 (count-screen-lines (window-start)
768 (progn (vertical-motion 0) (point)))))
770 ;;; backends ;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;
772 (defvar company-backend nil)
773 (make-variable-buffer-local 'company-backend)
775 (defun company-grab (regexp &optional expression limit)
776 (when (looking-back regexp limit)
777 (or (match-string-no-properties (or expression 0)) "")))
779 (defun company-grab-line (regexp &optional expression)
780 (company-grab regexp expression (point-at-bol)))
782 (defun company-grab-symbol ()
783 (if (looking-at "\\_>")
784 (buffer-substring (point) (save-excursion (skip-syntax-backward "w_")
786 (unless (and (char-after) (memq (char-syntax (char-after)) '(?w ?_)))
789 (defun company-grab-word ()
790 (if (looking-at "\\>")
791 (buffer-substring (point) (save-excursion (skip-syntax-backward "w")
793 (unless (and (char-after) (eq (char-syntax (char-after)) ?w))
796 (defun company-grab-symbol-cons (idle-begin-after-re &optional max-len)
797 (let ((symbol (company-grab-symbol)))
800 (forward-char (- (length symbol)))
801 (if (looking-back idle-begin-after-re (if max-len
803 (line-beginning-position)))
807 (defun company-in-string-or-comment ()
808 (let ((ppss (syntax-ppss)))
809 (or (car (setq ppss (nthcdr 3 ppss)))
810 (car (setq ppss (cdr ppss)))
813 (defun company-call-backend (&rest args)
814 (company--force-sync #'company-call-backend-raw args company-backend))
816 (defun company--force-sync (fun args backend)
817 (let ((value (apply fun args)))
818 (if (not (eq (car-safe value) :async))
821 (start (time-to-seconds)))
823 (lambda (result) (setq res result)))
824 (while (eq res 'trash)
825 (if (> (- (time-to-seconds) start) company-async-timeout)
826 (error "Company: Back-end %s async timeout with args %s"
828 (sleep-for company-async-wait)))
831 (defun company-call-backend-raw (&rest args)
833 (if (functionp company-backend)
834 (apply company-backend args)
835 (apply #'company--multi-backend-adapter company-backend args))
836 (error (error "Company: Back-end %s error \"%s\" with args %s"
837 company-backend (error-message-string err) args))))
839 (defun company--multi-backend-adapter (backends command &rest args)
840 (let ((backends (cl-loop for b in backends
841 when (not (and (symbolp b)
842 (eq 'failed (get b 'company-init))))
845 (if (eq command 'prefix)
846 (butlast backends (length (member :with backends)))
847 (delq :with backends)))
850 (company--multi-backend-adapter-candidates backends (car args)))
853 ((or `prefix `ignore-case `no-cache `require-match)
855 (cl-dolist (backend backends)
856 (when (setq value (company--force-sync
857 backend (cons command args) backend))
858 (cl-return value)))))
860 (let ((arg (car args)))
861 (when (> (length arg) 0)
862 (let ((backend (or (get-text-property 0 'company-backend arg)
864 (apply backend command args))))))))
866 (defun company--multi-backend-adapter-candidates (backends prefix)
867 (let ((pairs (cl-loop for backend in (cdr backends)
868 when (equal (company--prefix-str
869 (funcall backend 'prefix))
871 collect (cons (funcall backend 'candidates prefix)
876 (propertize str 'company-backend b))
878 (when (equal (company--prefix-str (funcall (car backends) 'prefix)) prefix)
879 ;; Small perf optimization: don't tag the candidates received
880 ;; from the first backend in the group.
881 (push (cons (funcall (car backends) 'candidates prefix)
884 (company--merge-async pairs (lambda (values) (apply #'append values)))))
886 (defun company--merge-async (pairs merger)
887 (let ((async (cl-loop for pair in pairs
889 (eq :async (car-safe (car pair))))))
891 (funcall merger (cl-loop for (val . mapper) in pairs
892 collect (funcall mapper val)))
903 (let ((val (car pair))
905 (if (not (eq :async (car-safe val)))
906 (push (funcall mapper val) lst)
910 (push fetcher pending)
913 (setq pending (delq fetcher pending))
914 (setcar cell (funcall mapper res))
915 (funcall finisher)))))))))))))
917 (defun company--prefix-str (prefix)
918 (or (car-safe prefix) prefix))
920 ;;; completion mechanism ;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;
922 (defvar company-prefix nil)
923 (make-variable-buffer-local 'company-prefix)
925 (defvar company-candidates nil)
926 (make-variable-buffer-local 'company-candidates)
928 (defvar company-candidates-length nil)
929 (make-variable-buffer-local 'company-candidates-length)
931 (defvar company-candidates-cache nil)
932 (make-variable-buffer-local 'company-candidates-cache)
934 (defvar company-candidates-predicate nil)
935 (make-variable-buffer-local 'company-candidates-predicate)
937 (defvar company-common nil)
938 (make-variable-buffer-local 'company-common)
940 (defvar company-selection 0)
941 (make-variable-buffer-local 'company-selection)
943 (defvar company-selection-changed nil)
944 (make-variable-buffer-local 'company-selection-changed)
946 (defvar company--manual-action nil
947 "Non-nil, if manual completion took place.")
948 (make-variable-buffer-local 'company--manual-action)
950 (defvar company--manual-prefix nil)
951 (make-variable-buffer-local 'company--manual-prefix)
953 (defvar company--auto-completion nil
954 "Non-nil when current candidate is being inserted automatically.
955 Controlled by `company-auto-complete'.")
957 (defvar company--point-max nil)
958 (make-variable-buffer-local 'company--point-max)
960 (defvar company-point nil)
961 (make-variable-buffer-local 'company-point)
963 (defvar company-timer nil)
965 (defvar company-added-newline nil)
966 (make-variable-buffer-local 'company-added-newline)
968 (defsubst company-strip-prefix (str)
969 (substring str (length company-prefix)))
971 (defun company--insert-candidate (candidate)
972 (setq candidate (substring-no-properties candidate))
973 ;; XXX: Return value we check here is subject to change.
974 (if (eq (company-call-backend 'ignore-case) 'keep-prefix)
975 (insert (company-strip-prefix candidate))
976 (delete-region (- (point) (length company-prefix)) (point))
979 (defmacro company-with-candidate-inserted (candidate &rest body)
980 "Evaluate BODY with CANDIDATE temporarily inserted.
981 This is a tool for back-ends that need candidates inserted before they
982 can retrieve meta-data for them."
984 `(let ((inhibit-modification-hooks t)
985 (inhibit-point-motion-hooks t)
986 (modified-p (buffer-modified-p)))
987 (company--insert-candidate ,candidate)
990 (delete-region company-point (point)))))
992 (defun company-explicit-action-p ()
993 "Return whether explicit completion action was taken by the user."
994 (or company--manual-action
995 company-selection-changed))
997 (defun company-reformat (candidate)
998 ;; company-ispell needs this, because the results are always lower-case
999 ;; It's mory efficient to fix it only when they are displayed.
1000 ;; FIXME: Adopt the current text's capitalization instead?
1001 (if (eq (company-call-backend 'ignore-case) 'keep-prefix)
1002 (concat company-prefix (substring candidate (length company-prefix)))
1005 (defun company--should-complete ()
1006 (and (not (or buffer-read-only overriding-terminal-local-map
1007 overriding-local-map))
1008 ;; Check if in the middle of entering a key combination.
1009 (or (equal (this-command-keys-vector) [])
1010 (not (keymapp (key-binding (this-command-keys-vector)))))
1011 (eq company-idle-delay t)
1012 (or (eq t company-begin-commands)
1013 (memq this-command company-begin-commands)
1014 (and (symbolp this-command) (get this-command 'company-begin)))
1015 (not (and transient-mark-mode mark-active))))
1017 (defun company--should-continue ()
1018 (or (eq t company-begin-commands)
1019 (eq t company-continue-commands)
1020 (if (eq 'not (car company-continue-commands))
1021 (not (memq this-command (cdr company-continue-commands)))
1022 (or (memq this-command company-begin-commands)
1023 (memq this-command company-continue-commands)
1024 (string-match-p "\\`company-" (symbol-name this-command))))))
1026 (defun company-call-frontends (command)
1027 (dolist (frontend company-frontends)
1029 (funcall frontend command)
1030 (error (error "Company: Front-end %s error \"%s\" on command %s"
1031 frontend (error-message-string err) command)))))
1033 (defun company-set-selection (selection &optional force-update)
1035 (if company-selection-wrap-around
1036 (mod selection company-candidates-length)
1037 (max 0 (min (1- company-candidates-length) selection))))
1038 (when (or force-update (not (equal selection company-selection)))
1039 (setq company-selection selection
1040 company-selection-changed t)
1041 (company-call-frontends 'update)))
1043 (defun company-apply-predicate (candidates predicate)
1045 (dolist (c candidates)
1046 (when (funcall predicate c)
1050 (defun company-update-candidates (candidates)
1051 (setq company-candidates-length (length candidates))
1052 (if (> company-selection 0)
1053 ;; Try to restore the selection
1054 (let ((selected (nth company-selection company-candidates)))
1055 (setq company-selection 0
1056 company-candidates candidates)
1058 (while (and candidates (string< (pop candidates) selected))
1059 (cl-incf company-selection))
1061 ;; Make sure selection isn't out of bounds.
1062 (setq company-selection (min (1- company-candidates-length)
1063 company-selection)))))
1064 (setq company-selection 0
1065 company-candidates candidates))
1067 (push (cons company-prefix company-candidates) company-candidates-cache)
1068 ;; Calculate common.
1069 (let ((completion-ignore-case (company-call-backend 'ignore-case)))
1070 ;; We want to support non-prefix completion, so filtering is the
1071 ;; responsibility of each respective backend, not ours.
1072 ;; On the other hand, we don't want to replace non-prefix input in
1073 ;; `company-complete-common'.
1074 (setq company-common
1075 (if (cdr company-candidates)
1076 (let ((common (try-completion company-prefix company-candidates)))
1078 ;; Mulple equal strings, probably with different
1082 (car company-candidates)))))
1084 (defun company-calculate-candidates (prefix)
1085 (let ((candidates (cdr (assoc prefix company-candidates-cache)))
1086 (ignore-case (company-call-backend 'ignore-case)))
1088 (when company-candidates-cache
1089 (let ((len (length prefix))
1090 (completion-ignore-case ignore-case)
1092 (cl-dotimes (i (1+ len))
1093 (when (setq prev (cdr (assoc (substring prefix 0 (- len i))
1094 company-candidates-cache)))
1095 (setq candidates (all-completions prefix prev))
1097 ;; no cache match, call back-end
1099 (company--process-candidates
1100 (company--fetch-candidates prefix))))
1101 (setq candidates (company--transform-candidates candidates))
1103 (if (or (cdr candidates)
1104 (not (eq t (compare-strings (car candidates) nil nil
1105 prefix nil nil ignore-case))))
1107 ;; Already completed and unique; don't start.
1110 (defun company--fetch-candidates (prefix)
1111 (let ((c (if company--manual-action
1112 (company-call-backend 'candidates prefix)
1113 (company-call-backend-raw 'candidates prefix)))
1115 (if (not (eq (car c) :async))
1117 (let ((buf (current-buffer))
1118 (win (selected-window))
1119 (tick (buffer-chars-modified-tick))
1121 (backend company-backend))
1124 (lambda (candidates)
1125 (if (not (and candidates (eq res 'done)))
1126 ;; Fetcher called us right back.
1127 (setq res candidates)
1128 (setq company-backend backend
1129 company-candidates-cache
1131 (company--process-candidates
1133 (company-idle-begin buf win tick pt)))))
1134 ;; FIXME: Relying on the fact that the callers
1135 ;; will interpret nil as "do nothing" is shaky.
1136 ;; A throw-catch would be one possible improvement.
1138 (progn (setq res 'done) nil)))))
1140 (defun company--process-candidates (candidates)
1141 (when company-candidates-predicate
1143 (company-apply-predicate candidates
1144 company-candidates-predicate)))
1145 (unless (company-call-backend 'sorted)
1146 (setq candidates (sort candidates 'string<)))
1147 (when (company-call-backend 'duplicates)
1148 (company--strip-duplicates candidates))
1151 (defun company--strip-duplicates (candidates)
1152 (let ((c2 candidates))
1155 (let ((str (car c2))
1158 (while (let ((str2 (car c2)))
1159 (if (not (equal str str2))
1161 (when (eq anno 'unk)
1162 (setq anno (company-call-backend
1165 (company-call-backend
1166 'annotation str2))))
1170 (defun company--transform-candidates (candidates)
1171 (let ((c candidates))
1172 (dolist (tr company-transformers)
1173 (setq c (funcall tr c)))
1176 (defun company-sort-by-occurrence (candidates)
1177 "Sort CANDIDATES according to their occurrences.
1178 Searches for each in the currently visible part of the current buffer and
1179 gives priority to the closest ones above point, then closest ones below
1180 point. The rest of the list is appended unchanged.
1181 Keywords and function definition names are ignored."
1188 (progn (forward-char (- (length company-prefix)))
1189 (search-backward candidate (window-start) t)))
1191 (search-forward candidate (window-end) t)))
1192 (let ((beg (match-beginning 0))
1193 (end (match-end 0)))
1194 (when (save-excursion
1196 (and (not (memq (get-text-property (point) 'face)
1197 '(font-lock-function-name-face
1198 font-lock-keyword-face)))
1199 (let ((prefix (company--prefix-str
1200 (company-call-backend 'prefix))))
1201 (and (stringp prefix)
1202 (= (length prefix) (- end beg))))))
1203 (push (cons candidate (if (< beg (point))
1205 (- beg (window-start))))
1210 (mapcar #'car (sort occurs (lambda (e1 e2) (<= (cdr e1) (cdr e2)))))
1213 (defun company-idle-begin (buf win tick pos)
1214 (and (eq buf (current-buffer))
1215 (eq win (selected-window))
1216 (eq tick (buffer-chars-modified-tick))
1218 (when (company-auto-begin)
1219 (when (version< emacs-version "24.3.50")
1220 (company-input-noop))
1221 (company-post-command))))
1223 (defun company-auto-begin ()
1225 (not company-candidates)
1226 (let ((company-idle-delay t)
1227 (company-begin-commands t))
1228 (condition-case-unless-debug err
1230 (error (message "Company: An error occurred in auto-begin")
1231 (message "%s" (error-message-string err))
1233 (quit (company-cancel)))))
1234 (unless company-candidates
1235 (setq company-backend nil))
1236 ;; Return non-nil if active.
1239 (defun company-manual-begin ()
1241 (company-assert-enabled)
1242 (setq company--manual-action t)
1244 (let ((company-minimum-prefix-length 0))
1245 (company-auto-begin))
1246 (unless company-candidates
1247 (setq company--manual-action nil))))
1249 (defun company-other-backend (&optional backward)
1250 (interactive (list current-prefix-arg))
1251 (company-assert-enabled)
1252 (let* ((after (if company-backend
1253 (cdr (member company-backend company-backends))
1255 (before (cdr (member company-backend (reverse company-backends))))
1257 (append before (reverse after))
1258 (append after (reverse before)))))
1260 (cl-dolist (backend next)
1261 (when (ignore-errors (company-begin-backend backend))
1263 (unless company-candidates
1264 (error "No other back-end")))
1266 (defun company-require-match-p ()
1267 (let ((backend-value (company-call-backend 'require-match)))
1268 (or (eq backend-value t)
1269 (and (not (eq backend-value 'never))
1270 (if (functionp company-require-match)
1271 (funcall company-require-match)
1272 (eq company-require-match t))))))
1274 (defun company-auto-complete-p (input)
1275 "Return non-nil, if input starts with punctuation or parentheses."
1276 (and (if (functionp company-auto-complete)
1277 (funcall company-auto-complete)
1278 company-auto-complete)
1279 (if (functionp company-auto-complete-chars)
1280 (funcall company-auto-complete-chars input)
1281 (if (consp company-auto-complete-chars)
1282 (memq (char-syntax (string-to-char input))
1283 company-auto-complete-chars)
1284 (string-match (substring input 0 1) company-auto-complete-chars)))))
1286 (defun company--incremental-p ()
1287 (and (> (point) company-point)
1288 (> (point-max) company--point-max)
1289 (not (eq this-command 'backward-delete-char-untabify))
1290 (equal (buffer-substring (- company-point (length company-prefix))
1294 (defun company--continue-failed ()
1295 (let ((input (buffer-substring-no-properties (point) company-point)))
1297 ((company-auto-complete-p input)
1300 (goto-char company-point)
1301 (let ((company--auto-completion t))
1302 (company-complete-selection))
1304 ((company-require-match-p)
1305 ;; wrong incremental input, but required match
1306 (delete-char (- (length input)))
1308 (message "Matching input is required")
1310 ((equal company-prefix (car company-candidates))
1311 ;; last input was actually success
1312 (company-cancel company-prefix))
1313 (t (company-cancel)))))
1315 (defun company--good-prefix-p (prefix)
1316 (and (stringp (company--prefix-str prefix)) ;excludes 'stop
1317 (or (eq (cdr-safe prefix) t)
1318 (let ((len (or (cdr-safe prefix) (length prefix))))
1319 (if company--manual-prefix
1320 (or (not company-abort-manual-when-too-short)
1321 ;; Must not be less than minimum or initial length.
1322 (>= len (min company-minimum-prefix-length
1323 (length company--manual-prefix))))
1324 (>= len company-minimum-prefix-length))))))
1326 (defun company--continue ()
1327 (when (company-call-backend 'no-cache company-prefix)
1328 ;; Don't complete existing candidates, fetch new ones.
1329 (setq company-candidates-cache nil))
1330 (let* ((new-prefix (company-call-backend 'prefix))
1331 (c (when (and (company--good-prefix-p new-prefix)
1332 (setq new-prefix (company--prefix-str new-prefix))
1333 (= (- (point) (length new-prefix))
1334 (- company-point (length company-prefix))))
1335 (company-calculate-candidates new-prefix))))
1338 ;; t means complete/unique.
1339 ;; Handle it like completion was aborted, to differentiate from user
1340 ;; calling one of Company's commands to insert the candidate.
1341 (company-cancel 'unique))
1343 ;; incremental match
1344 (setq company-prefix new-prefix)
1345 (company-update-candidates c)
1347 ((not (company--incremental-p))
1349 (t (company--continue-failed)))))
1351 (defun company--begin-new ()
1353 (cl-dolist (backend (if company-backend
1354 ;; prefer manual override
1355 (list company-backend)
1358 (if (or (symbolp backend)
1359 (functionp backend))
1360 (when (or (not (symbolp backend))
1361 (eq t (get backend 'company-init))
1362 (unless (get backend 'company-init)
1363 (company-init-backend backend)))
1364 (funcall backend 'prefix))
1365 (company--multi-backend-adapter backend 'prefix)))
1367 (when (company--good-prefix-p prefix)
1368 (setq company-prefix (company--prefix-str prefix)
1369 company-backend backend
1370 c (company-calculate-candidates company-prefix))
1371 ;; t means complete/unique. We don't start, so no hooks.
1373 (when company--manual-action
1374 (message "No completion found"))
1375 (when company--manual-action
1376 (setq company--manual-prefix prefix))
1377 (when (symbolp backend)
1378 (setq company-lighter (concat " " (symbol-name backend))))
1379 (company-update-candidates c)
1380 (run-hook-with-args 'company-completion-started-hook
1381 (company-explicit-action-p))
1382 (company-call-frontends 'show)))
1385 (defun company-begin ()
1386 (or (and company-candidates (company--continue))
1387 (and (company--should-complete) (company--begin-new)))
1388 (when company-candidates
1389 (let ((modified (buffer-modified-p)))
1390 (when (and company-end-of-buffer-workaround (eobp))
1391 (save-excursion (insert "\n"))
1392 (setq company-added-newline
1393 (or modified (buffer-chars-modified-tick)))))
1394 (setq company-point (point)
1395 company--point-max (point-max))
1396 (company-ensure-emulation-alist)
1397 (company-enable-overriding-keymap company-active-map)
1398 (company-call-frontends 'update)))
1400 (defun company-cancel (&optional result)
1401 (and company-added-newline
1402 (> (point-max) (point-min))
1403 (let ((tick (buffer-chars-modified-tick)))
1404 (delete-region (1- (point-max)) (point-max))
1405 (equal tick company-added-newline))
1406 ;; Only set unmodified when tick remained the same since insert,
1407 ;; and the buffer wasn't modified before.
1408 (set-buffer-modified-p nil))
1409 (when company-prefix
1410 (if (stringp result)
1412 (company-call-backend 'pre-completion result)
1413 (run-hook-with-args 'company-completion-finished-hook result)
1414 (company-call-backend 'post-completion result))
1415 (run-hook-with-args 'company-completion-cancelled-hook result)))
1416 (setq company-added-newline nil
1419 company-candidates nil
1420 company-candidates-length nil
1421 company-candidates-cache nil
1422 company-candidates-predicate nil
1425 company-selection-changed nil
1426 company--manual-action nil
1427 company--manual-prefix nil
1428 company-lighter company-default-lighter
1429 company--point-max nil
1432 (cancel-timer company-timer))
1433 (company-search-mode 0)
1434 (company-call-frontends 'hide)
1435 (company-enable-overriding-keymap nil)
1436 ;; Make return value explicit.
1439 (defun company-abort ()
1442 ;; Don't start again, unless started manually.
1443 (setq company-point (point)))
1445 (defun company-finish (result)
1446 (company--insert-candidate result)
1447 (company-cancel result)
1448 ;; Don't start again, unless started manually.
1449 (setq company-point (point)))
1451 (defsubst company-keep (command)
1452 (and (symbolp command) (get command 'company-keep)))
1454 (defun company-pre-command ()
1455 (unless (company-keep this-command)
1457 (when company-candidates
1458 (company-call-frontends 'pre-command)
1459 (unless (company--should-continue)
1461 (error (message "Company: An error occurred in pre-command")
1462 (message "%s" (error-message-string err))
1465 (cancel-timer company-timer)
1466 (setq company-timer nil))
1467 (company-uninstall-map))
1469 (defun company-post-command ()
1470 (unless (company-keep this-command)
1473 (unless (equal (point) company-point)
1475 (if company-candidates
1476 (company-call-frontends 'post-command)
1477 (and (numberp company-idle-delay)
1478 (or (eq t company-begin-commands)
1479 (memq this-command company-begin-commands))
1480 (not (equal (point) company-point))
1482 (run-with-timer company-idle-delay nil
1484 (current-buffer) (selected-window)
1485 (buffer-chars-modified-tick) (point))))))
1486 (error (message "Company: An error occurred in post-command")
1487 (message "%s" (error-message-string err))
1489 (company-install-map))
1491 ;;; search ;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;
1493 (defvar company-search-string nil)
1494 (make-variable-buffer-local 'company-search-string)
1496 (defvar company-search-lighter " Search: \"\"")
1497 (make-variable-buffer-local 'company-search-lighter)
1499 (defvar company-search-old-map nil)
1500 (make-variable-buffer-local 'company-search-old-map)
1502 (defvar company-search-old-selection 0)
1503 (make-variable-buffer-local 'company-search-old-selection)
1505 (defun company-search (text lines)
1506 (let ((quoted (regexp-quote text))
1508 (cl-dolist (line lines)
1509 (when (string-match quoted line (length company-prefix))
1513 (defun company-search-printing-char ()
1515 (company-search-assert-enabled)
1516 (setq company-search-string
1517 (concat (or company-search-string "") (string last-command-event))
1518 company-search-lighter (concat " Search: \"" company-search-string
1520 (let ((pos (company-search company-search-string
1521 (nthcdr company-selection company-candidates))))
1524 (company-set-selection (+ company-selection pos) t))))
1526 (defun company-search-repeat-forward ()
1527 "Repeat the incremental search in completion candidates forward."
1529 (company-search-assert-enabled)
1530 (let ((pos (company-search company-search-string
1531 (cdr (nthcdr company-selection
1532 company-candidates)))))
1535 (company-set-selection (+ company-selection pos 1) t))))
1537 (defun company-search-repeat-backward ()
1538 "Repeat the incremental search in completion candidates backwards."
1540 (company-search-assert-enabled)
1541 (let ((pos (company-search company-search-string
1542 (nthcdr (- company-candidates-length
1544 (reverse company-candidates)))))
1547 (company-set-selection (- company-selection pos 1) t))))
1549 (defun company-create-match-predicate ()
1550 (setq company-candidates-predicate
1551 `(lambda (candidate)
1552 ,(if company-candidates-predicate
1553 `(and (string-match ,company-search-string candidate)
1554 (funcall ,company-candidates-predicate
1556 `(string-match ,company-search-string candidate))))
1557 (company-update-candidates
1558 (company-apply-predicate company-candidates company-candidates-predicate))
1559 ;; Invalidate cache.
1560 (setq company-candidates-cache (cons company-prefix company-candidates)))
1562 (defun company-filter-printing-char ()
1564 (company-search-assert-enabled)
1565 (company-search-printing-char)
1566 (company-create-match-predicate)
1567 (company-call-frontends 'update))
1569 (defun company-search-kill-others ()
1570 "Limit the completion candidates to the ones matching the search string."
1572 (company-search-assert-enabled)
1573 (company-create-match-predicate)
1574 (company-search-mode 0)
1575 (company-call-frontends 'update))
1577 (defun company-search-abort ()
1578 "Abort searching the completion candidates."
1580 (company-search-assert-enabled)
1581 (company-set-selection company-search-old-selection t)
1582 (company-search-mode 0))
1584 (defun company-search-other-char ()
1586 (company-search-assert-enabled)
1587 (company-search-mode 0)
1588 (company--unread-last-input))
1590 (defvar company-search-map
1592 (keymap (make-keymap)))
1593 (if (fboundp 'max-char)
1594 (set-char-table-range (nth 1 keymap) (cons #x100 (max-char))
1595 'company-search-printing-char)
1597 ;; obsolete in Emacs 23
1598 (let ((l (generic-character-list))
1599 (table (nth 1 keymap)))
1601 (set-char-table-default table (car l) 'company-search-printing-char)
1602 (setq l (cdr l))))))
1603 (define-key keymap [t] 'company-search-other-char)
1605 (define-key keymap (make-string 1 i) 'company-search-other-char)
1608 (define-key keymap (vector i) 'company-search-printing-char)
1610 (let ((meta-map (make-sparse-keymap)))
1611 (define-key keymap (char-to-string meta-prefix-char) meta-map)
1612 (define-key keymap [escape] meta-map))
1613 (define-key keymap (vector meta-prefix-char t) 'company-search-other-char)
1614 (define-key keymap "\e\e\e" 'company-search-other-char)
1615 (define-key keymap [escape escape escape] 'company-search-other-char)
1616 (define-key keymap (kbd "DEL") 'company-search-other-char)
1618 (define-key keymap "\C-g" 'company-search-abort)
1619 (define-key keymap "\C-s" 'company-search-repeat-forward)
1620 (define-key keymap "\C-r" 'company-search-repeat-backward)
1621 (define-key keymap "\C-o" 'company-search-kill-others)
1623 "Keymap used for incrementally searching the completion candidates.")
1625 (define-minor-mode company-search-mode
1626 "Search mode for completion candidates.
1627 Don't start this directly, use `company-search-candidates' or
1628 `company-filter-candidates'."
1629 nil company-search-lighter nil
1630 (if company-search-mode
1631 (if (company-manual-begin)
1633 (setq company-search-old-selection company-selection)
1634 (company-call-frontends 'update))
1635 (setq company-search-mode nil))
1636 (kill-local-variable 'company-search-string)
1637 (kill-local-variable 'company-search-lighter)
1638 (kill-local-variable 'company-search-old-selection)
1639 (company-enable-overriding-keymap company-active-map)))
1641 (defun company-search-assert-enabled ()
1642 (company-assert-enabled)
1643 (unless company-search-mode
1644 (company-uninstall-map)
1645 (error "Company not in search mode")))
1647 (defun company-search-candidates ()
1648 "Start searching the completion candidates incrementally.
1650 \\<company-search-map>Search can be controlled with the commands:
1651 - `company-search-repeat-forward' (\\[company-search-repeat-forward])
1652 - `company-search-repeat-backward' (\\[company-search-repeat-backward])
1653 - `company-search-abort' (\\[company-search-abort])
1655 Regular characters are appended to the search string.
1657 The command `company-search-kill-others' (\\[company-search-kill-others])
1658 uses the search string to limit the completion candidates."
1660 (company-search-mode 1)
1661 (company-enable-overriding-keymap company-search-map))
1663 (defvar company-filter-map
1664 (let ((keymap (make-keymap)))
1665 (define-key keymap [remap company-search-printing-char]
1666 'company-filter-printing-char)
1667 (set-keymap-parent keymap company-search-map)
1669 "Keymap used for incrementally searching the completion candidates.")
1671 (defun company-filter-candidates ()
1672 "Start filtering the completion candidates incrementally.
1673 This works the same way as `company-search-candidates' immediately
1674 followed by `company-search-kill-others' after each input."
1676 (company-search-mode 1)
1677 (company-enable-overriding-keymap company-filter-map))
1679 ;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;
1681 (defun company-select-next ()
1682 "Select the next candidate in the list."
1684 (when (company-manual-begin)
1685 (company-set-selection (1+ company-selection))))
1687 (defun company-select-previous ()
1688 "Select the previous candidate in the list."
1690 (when (company-manual-begin)
1691 (company-set-selection (1- company-selection))))
1693 (defun company-select-next-or-abort ()
1694 "Select the next candidate if more than one, else abort
1695 and invoke the normal binding."
1697 (if (> company-candidates-length 1)
1698 (company-select-next)
1700 (company--unread-last-input)))
1702 (defun company-select-previous-or-abort ()
1703 "Select the previous candidate if more than one, else abort
1704 and invoke the normal binding."
1706 (if (> company-candidates-length 1)
1707 (company-select-previous)
1709 (company--unread-last-input)))
1711 (defvar company-pseudo-tooltip-overlay)
1713 (defvar company-tooltip-offset)
1715 (defun company--inside-tooltip-p (event-col-row row height)
1716 (let* ((ovl company-pseudo-tooltip-overlay)
1717 (column (overlay-get ovl 'company-column))
1718 (width (overlay-get ovl 'company-width))
1719 (evt-col (car event-col-row))
1720 (evt-row (cdr event-col-row)))
1721 (and (>= evt-col column)
1722 (< evt-col (+ column width))
1724 (and (> evt-row row)
1725 (<= evt-row (+ row height) ))
1726 (and (< evt-row row)
1727 (>= evt-row (+ row height)))))))
1729 (defun company--event-col-row (event)
1730 (let* ((col-row (posn-actual-col-row (event-start event)))
1732 (row (cdr col-row)))
1733 (cl-incf col (window-hscroll))
1734 (and header-line-format
1735 (version< "24" emacs-version)
1739 (defun company-select-mouse (event)
1740 "Select the candidate picked by the mouse."
1742 (let ((event-col-row (company--event-col-row event))
1743 (ovl-row (company--row))
1744 (ovl-height (and company-pseudo-tooltip-overlay
1745 (min (overlay-get company-pseudo-tooltip-overlay
1747 company-candidates-length))))
1749 (company--inside-tooltip-p event-col-row ovl-row ovl-height))
1751 (company-set-selection (+ (cdr event-col-row)
1752 (1- company-tooltip-offset)
1753 (if (and (eq company-tooltip-offset-display 'lines)
1754 (not (zerop company-tooltip-offset)))
1757 (if (< ovl-height 0)
1762 (company--unread-last-input)
1765 (defun company-complete-mouse (event)
1766 "Insert the candidate picked by the mouse."
1768 (when (company-select-mouse event)
1769 (company-complete-selection)))
1771 (defun company-complete-selection ()
1772 "Insert the selected candidate."
1774 (when (company-manual-begin)
1775 (let ((result (nth company-selection company-candidates)))
1776 (company-finish result))))
1778 (defun company-complete-common ()
1779 "Insert the common part of all candidates."
1781 (when (company-manual-begin)
1782 (if (and (not (cdr company-candidates))
1783 (equal company-common (car company-candidates)))
1784 (company-complete-selection)
1785 (when company-common
1786 (company--insert-candidate company-common)))))
1788 (defun company-complete ()
1789 "Insert the common part of all candidates or the current selection.
1790 The first time this is called, the common part is inserted, the second
1791 time, or when the selection has been changed, the selected candidate is
1794 (when (company-manual-begin)
1795 (if (or company-selection-changed
1796 (eq last-command 'company-complete-common))
1797 (call-interactively 'company-complete-selection)
1798 (call-interactively 'company-complete-common)
1799 (setq this-command 'company-complete-common))))
1801 (defun company-complete-number (n)
1802 "Insert the Nth candidate.
1803 To show the number next to the candidates in some back-ends, enable
1804 `company-show-numbers'."
1805 (when (company-manual-begin)
1806 (and (or (< n 1) (> n company-candidates-length))
1807 (error "No candidate number %d" n))
1809 (company-finish (nth n company-candidates))))
1811 ;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;
1813 (defconst company-space-strings-limit 100)
1815 (defconst company-space-strings
1817 (dotimes (i company-space-strings-limit)
1818 (push (make-string (- company-space-strings-limit 1 i) ?\ ) lst))
1819 (apply 'vector lst)))
1821 (defun company-space-string (len)
1822 (if (< len company-space-strings-limit)
1823 (aref company-space-strings len)
1824 (make-string len ?\ )))
1826 (defun company-safe-substring (str from &optional to)
1827 (if (> from (string-width str))
1831 (move-to-column from)
1832 (let ((beg (point)))
1836 (concat (buffer-substring beg (point))
1837 (let ((padding (- to (current-column))))
1839 (company-space-string padding)))))
1840 (buffer-substring beg (point-max)))))))
1842 ;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;
1844 (defvar company-last-metadata nil)
1845 (make-variable-buffer-local 'company-last-metadata)
1847 (defun company-fetch-metadata ()
1848 (let ((selected (nth company-selection company-candidates)))
1849 (unless (eq selected (car company-last-metadata))
1850 (setq company-last-metadata
1851 (cons selected (company-call-backend 'meta selected))))
1852 (cdr company-last-metadata)))
1854 (defun company-doc-buffer (&optional string)
1855 (with-current-buffer (get-buffer-create "*company-documentation*")
1862 (defvar company--electric-commands
1863 '(scroll-other-window scroll-other-window-down)
1864 "List of Commands that won't break out of electric commands.")
1866 (defmacro company--electric-do (&rest body)
1867 (declare (indent 0) (debug t))
1868 `(when (company-manual-begin)
1869 (save-window-excursion
1870 (let ((height (window-height))
1871 (row (company--row))
1874 (and (< (window-height) height)
1875 (< (- (window-height) row 2) company-tooltip-limit)
1876 (recenter (- (window-height) row 2)))
1877 (while (memq (setq cmd (key-binding (vector (list (read-event)))))
1878 company--electric-commands)
1879 (call-interactively cmd))
1880 (company--unread-last-input)))))
1882 (defun company--unread-last-input ()
1883 (when last-input-event
1884 (clear-this-command-keys t)
1885 (setq unread-command-events (list last-input-event))))
1887 (defun company-show-doc-buffer ()
1888 "Temporarily show the documentation buffer for the selection."
1890 (company--electric-do
1891 (let* ((selected (nth company-selection company-candidates))
1892 (doc-buffer (or (company-call-backend 'doc-buffer selected)
1893 (error "No documentation available"))))
1894 (with-current-buffer doc-buffer
1895 (goto-char (point-min)))
1896 (display-buffer doc-buffer t))))
1897 (put 'company-show-doc-buffer 'company-keep t)
1899 (defun company-show-location ()
1900 "Temporarily display a buffer showing the selected candidate in context."
1902 (company--electric-do
1903 (let* ((selected (nth company-selection company-candidates))
1904 (location (company-call-backend 'location selected))
1905 (pos (or (cdr location) (error "No location available")))
1906 (buffer (or (and (bufferp (car location)) (car location))
1907 (find-file-noselect (car location) t))))
1908 (with-selected-window (display-buffer buffer t)
1911 (if (bufferp (car location))
1913 (goto-char (point-min))
1914 (forward-line (1- pos))))
1915 (set-window-start nil (point))))))
1916 (put 'company-show-location 'company-keep t)
1918 ;;; package functions ;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;
1920 (defvar company-callback nil)
1921 (make-variable-buffer-local 'company-callback)
1923 (defun company-remove-callback (&optional ignored)
1924 (remove-hook 'company-completion-finished-hook company-callback t)
1925 (remove-hook 'company-completion-cancelled-hook 'company-remove-callback t)
1926 (remove-hook 'company-completion-finished-hook 'company-remove-callback t))
1928 (defun company-begin-backend (backend &optional callback)
1929 "Start a completion at point using BACKEND."
1930 (interactive (let ((val (completing-read "Company back-end: "
1932 'functionp nil "company-")))
1934 (list (intern val)))))
1935 (when (setq company-callback callback)
1936 (add-hook 'company-completion-finished-hook company-callback nil t))
1937 (add-hook 'company-completion-cancelled-hook 'company-remove-callback nil t)
1938 (add-hook 'company-completion-finished-hook 'company-remove-callback nil t)
1939 (setq company-backend backend)
1940 ;; Return non-nil if active.
1941 (or (company-manual-begin)
1942 (error "Cannot complete at point")))
1944 (defun company-begin-with (candidates
1945 &optional prefix-length require-match callback)
1946 "Start a completion at point.
1947 CANDIDATES is the list of candidates to use and PREFIX-LENGTH is the length
1948 of the prefix that already is in the buffer before point.
1951 CALLBACK is a function called with the selected result if the user
1952 successfully completes the input.
1954 Example: \(company-begin-with '\(\"foo\" \"foobar\" \"foobarbaz\"\)\)"
1955 (let ((begin-marker (copy-marker (point) t)))
1956 (company-begin-backend
1957 (lambda (command &optional arg &rest ignored)
1960 (when (equal (point) (marker-position begin-marker))
1961 (buffer-substring (- (point) (or prefix-length 0)) (point))))
1963 (all-completions arg candidates))
1968 (defun company-version (&optional show-version)
1969 "Get the Company version as string.
1971 If SHOW-VERSION is non-nil, show the version in the echo area."
1972 (interactive (list t))
1974 (insert-file-contents (find-library-name "company"))
1977 (message "Company version: %s" (lm-version))
1980 ;;; pseudo-tooltip ;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;
1982 (defvar company-pseudo-tooltip-overlay nil)
1983 (make-variable-buffer-local 'company-pseudo-tooltip-overlay)
1985 (defvar company-tooltip-offset 0)
1986 (make-variable-buffer-local 'company-tooltip-offset)
1988 (defun company-tooltip--lines-update-offset (selection num-lines limit)
1990 (setq company-tooltip-offset
1991 (max (min selection company-tooltip-offset)
1992 (- selection -1 limit)))
1994 (when (<= company-tooltip-offset 1)
1996 (setq company-tooltip-offset 0))
1998 (when (>= company-tooltip-offset (- num-lines limit 1))
2000 (when (= selection (1- num-lines))
2001 (cl-decf company-tooltip-offset)
2002 (when (<= company-tooltip-offset 1)
2003 (setq company-tooltip-offset 0)
2008 (defun company-tooltip--simple-update-offset (selection _num-lines limit)
2009 (setq company-tooltip-offset
2010 (if (< selection company-tooltip-offset)
2012 (max company-tooltip-offset
2013 (- selection limit -1)))))
2017 (defsubst company-round-tab (arg)
2018 (* (/ (+ arg tab-width) tab-width) tab-width))
2020 (defun company-plainify (str)
2021 (let ((prefix (get-text-property 0 'line-prefix str)))
2022 (when prefix ; Keep the original value unmodified, for no special reason.
2023 (setq str (concat prefix str))
2024 (remove-text-properties 0 (length str) '(line-prefix) str)))
2025 (let* ((pieces (split-string str "\t"))
2028 (setcar copy (company-safe-substring
2029 (car copy) 0 (company-round-tab (string-width (car copy)))))
2031 (apply 'concat pieces)))
2033 (defun company-fill-propertize (value annotation width selected left right)
2034 (let* ((margin (length left))
2035 (common (+ (or (company-call-backend 'match value)
2036 (length company-common)) margin))
2037 (ann-ralign company-tooltip-align-annotations)
2038 (ann-truncate (< width
2039 (+ (length value) (length annotation)
2040 (if ann-ralign 1 0))))
2041 (ann-start (+ margin
2045 (- width (length annotation)))
2047 (ann-end (min (+ ann-start (length annotation)) (+ margin width)))
2049 (if (or ann-truncate (not ann-ralign))
2050 (company-safe-substring
2052 (when (and annotation ann-ralign) " ")
2056 (company-safe-substring value 0
2057 (- width (length annotation)))
2060 (setq width (+ width margin (length right)))
2062 (add-text-properties 0 width '(face company-tooltip
2063 mouse-face company-tooltip-mouse)
2065 (add-text-properties margin common
2066 '(face company-tooltip-common
2067 mouse-face company-tooltip-mouse)
2069 (when (< ann-start ann-end)
2070 (add-text-properties ann-start ann-end
2071 '(face company-tooltip-annotation
2072 mouse-face company-tooltip-mouse)
2075 (if (and company-search-string
2076 (string-match (regexp-quote company-search-string) value
2077 (length company-prefix)))
2078 (let ((beg (+ margin (match-beginning 0)))
2079 (end (+ margin (match-end 0))))
2080 (add-text-properties beg end '(face company-tooltip-selection)
2082 (when (< beg common)
2083 (add-text-properties beg common
2084 '(face company-tooltip-common-selection)
2086 (add-text-properties 0 width '(face company-tooltip-selection
2087 mouse-face company-tooltip-selection)
2089 (add-text-properties margin common
2090 '(face company-tooltip-common-selection
2091 mouse-face company-tooltip-selection)
2097 (defun company-buffer-lines (beg end)
2100 (while (and (= 1 (vertical-motion 1))
2102 (let ((bound (min end (1- (point)))))
2103 ;; A visual line can contain several physical lines (e.g. with outline's
2104 ;; folding overlay). Take only the first one.
2105 (push (buffer-substring beg
2108 (re-search-forward "$" bound 'move)
2112 (unless (eq beg end)
2113 (push (buffer-substring beg end) lines))
2116 (defun company-modify-line (old new offset)
2117 (concat (company-safe-substring old 0 offset)
2119 (company-safe-substring old (+ offset (length new)))))
2121 (defsubst company--length-limit (lst limit)
2122 (if (nthcdr limit lst)
2126 (defun company--replacement-string (lines old column nl &optional align-top)
2127 (cl-decf column company-tooltip-margin)
2129 (when (and align-top company-tooltip-flip-when-above)
2130 (setq lines (reverse lines)))
2132 (let ((width (length (car lines)))
2133 (remaining-cols (- (+ (company--window-width) (window-hscroll))
2135 (when (> width remaining-cols)
2136 (cl-decf column (- width remaining-cols))))
2138 (let ((offset (and (< column 0) (- column)))
2143 ;; untouched lines first
2144 (dotimes (_ (- (length old) (length lines)))
2145 (push (pop old) new)))
2146 ;; length into old lines.
2148 (push (company-modify-line (pop old)
2149 (company--offset-line (pop lines) offset)
2151 ;; Append whole new lines.
2153 (push (concat (company-space-string column)
2154 (company--offset-line (pop lines) offset))
2157 (let ((str (concat (when nl "\n")
2158 (mapconcat 'identity (nreverse new) "\n")
2160 (font-lock-append-text-property 0 (length str) 'face 'default str)
2163 (defun company--offset-line (line offset)
2164 (if (and offset line)
2165 (substring line offset)
2168 (defun company--create-lines (selection limit)
2169 (let ((len company-candidates-length)
2171 (window-width (company--window-width))
2180 ;; Maybe clear old offset.
2181 (when (< len (+ company-tooltip-offset limit))
2182 (setq company-tooltip-offset 0))
2184 ;; Scroll to offset.
2185 (if (eq company-tooltip-offset-display 'lines)
2186 (setq limit (company-tooltip--lines-update-offset selection len limit))
2187 (company-tooltip--simple-update-offset selection len limit))
2190 ((eq company-tooltip-offset-display 'scrollbar)
2191 (setq scrollbar-bounds (company--scrollbar-bounds company-tooltip-offset
2193 ((eq company-tooltip-offset-display 'lines)
2194 (when (> company-tooltip-offset 0)
2195 (setq previous (format "...(%d)" company-tooltip-offset)))
2196 (setq remainder (- len limit company-tooltip-offset)
2197 remainder (when (> remainder 0)
2198 (setq remainder (format "...(%d)" remainder))))))
2200 (cl-decf selection company-tooltip-offset)
2201 (setq width (max (length previous) (length remainder))
2202 lines (nthcdr company-tooltip-offset company-candidates)
2206 (cl-decf window-width (* 2 company-tooltip-margin))
2207 (when scrollbar-bounds (cl-decf window-width))
2210 (let* ((value (pop lines-copy))
2211 (annotation (company-call-backend 'annotation value)))
2212 (when (and annotation company-tooltip-align-annotations)
2213 ;; `lisp-completion-at-point' adds a space.
2214 (setq annotation (comment-string-strip annotation t nil)))
2215 (push (cons value annotation) items)
2216 (setq width (max (+ (length value)
2217 (if (and annotation company-tooltip-align-annotations)
2218 (1+ (length annotation))
2219 (length annotation)))
2222 (setq width (min window-width
2223 (max company-tooltip-minimum-width
2224 (if (and company-show-numbers
2225 (< company-tooltip-offset 10))
2229 ;; number can make tooltip too long
2230 (when company-show-numbers
2231 (setq numbered company-tooltip-offset))
2233 (let ((items (nreverse items)) new)
2235 (push (company--scrollpos-line previous width) new))
2238 (let* ((item (pop items))
2239 (str (company-reformat (car item)))
2240 (annotation (cdr item))
2241 (right (company-space-string company-tooltip-margin))
2243 (when (< numbered 10)
2246 (setq right (concat (format " %d" (mod numbered 10)) right)))
2248 (company-fill-propertize str annotation
2249 width (equal i selection)
2250 (company-space-string
2251 company-tooltip-margin)
2253 (when scrollbar-bounds
2254 (company--scrollbar i scrollbar-bounds)))
2258 (push (company--scrollpos-line remainder width) new))
2262 (defun company--scrollbar-bounds (offset limit length)
2263 (when (> length limit)
2264 (let* ((size (ceiling (* limit (float limit)) length))
2265 (lower (floor (* limit (float offset)) length))
2266 (upper (+ lower size -1)))
2267 (cons lower upper))))
2269 (defun company--scrollbar (i bounds)
2270 (propertize " " 'face
2271 (if (and (>= i (car bounds)) (<= i (cdr bounds)))
2272 'company-scrollbar-fg
2273 'company-scrollbar-bg)))
2275 (defun company--scrollpos-line (text width)
2276 (propertize (concat (company-space-string company-tooltip-margin)
2277 (company-safe-substring text 0 width)
2278 (company-space-string company-tooltip-margin))
2279 'face 'company-tooltip))
2283 (defsubst company--window-inner-height ()
2284 (let ((edges (window-inside-edges)))
2285 (- (nth 3 edges) (nth 1 edges))))
2287 (defsubst company--window-width ()
2288 (let ((ww (window-width)))
2289 ;; Account for the line continuation column.
2290 (when (zerop (cadr (window-fringes)))
2292 (unless (or (display-graphic-p)
2293 (version< "24.3.1" emacs-version))
2294 ;; Emacs 24.3 and earlier included margins
2295 ;; in window-width when in TTY.
2297 (let ((margins (window-margins)))
2298 (+ (or (car margins) 0)
2299 (or (cdr margins) 0)))))
2302 (defun company--pseudo-tooltip-height ()
2303 "Calculate the appropriate tooltip height.
2304 Returns a negative number if the tooltip should be displayed above point."
2305 (let* ((lines (company--row))
2306 (below (- (company--window-inner-height) 1 lines)))
2307 (if (and (< below (min company-tooltip-minimum company-candidates-length))
2309 (- (max 3 (min company-tooltip-limit lines)))
2310 (max 3 (min company-tooltip-limit below)))))
2312 (defun company-pseudo-tooltip-show (row column selection)
2313 (company-pseudo-tooltip-hide)
2316 (let* ((height (company--pseudo-tooltip-height))
2320 (setq row (+ row height -1)
2323 (let* ((nl (< (move-to-window-line row) row))
2325 (end (save-excursion
2326 (move-to-window-line (+ row (abs height)))
2328 (ov (make-overlay beg end))
2329 (args (list (mapcar 'company-plainify
2330 (company-buffer-lines beg end))
2333 (setq company-pseudo-tooltip-overlay ov)
2334 (overlay-put ov 'company-replacement-args args)
2336 (let ((lines (company--create-lines selection (abs height))))
2337 (overlay-put ov 'company-after
2338 (apply 'company--replacement-string lines args))
2339 (overlay-put ov 'company-width (string-width (car lines))))
2341 (overlay-put ov 'company-column column)
2342 (overlay-put ov 'company-height height)))))
2344 (defun company-pseudo-tooltip-show-at-point (pos)
2345 (let ((row (company--row pos))
2346 (col (company--column pos)))
2347 (company-pseudo-tooltip-show (1+ row) col company-selection)))
2349 (defun company-pseudo-tooltip-edit (selection)
2350 (let ((height (overlay-get company-pseudo-tooltip-overlay 'company-height)))
2351 (overlay-put company-pseudo-tooltip-overlay 'company-after
2352 (apply 'company--replacement-string
2353 (company--create-lines selection (abs height))
2354 (overlay-get company-pseudo-tooltip-overlay
2355 'company-replacement-args)))))
2357 (defun company-pseudo-tooltip-hide ()
2358 (when company-pseudo-tooltip-overlay
2359 (delete-overlay company-pseudo-tooltip-overlay)
2360 (setq company-pseudo-tooltip-overlay nil)))
2362 (defun company-pseudo-tooltip-hide-temporarily ()
2363 (when (overlayp company-pseudo-tooltip-overlay)
2364 (overlay-put company-pseudo-tooltip-overlay 'invisible nil)
2365 (overlay-put company-pseudo-tooltip-overlay 'line-prefix nil)
2366 (overlay-put company-pseudo-tooltip-overlay 'after-string nil)))
2368 (defun company-pseudo-tooltip-unhide ()
2369 (when company-pseudo-tooltip-overlay
2370 (overlay-put company-pseudo-tooltip-overlay 'invisible t)
2371 ;; Beat outline's folding overlays, at least.
2372 (overlay-put company-pseudo-tooltip-overlay 'priority 1)
2373 ;; No (extra) prefix for the first line.
2374 (overlay-put company-pseudo-tooltip-overlay 'line-prefix "")
2375 (overlay-put company-pseudo-tooltip-overlay 'after-string
2376 (overlay-get company-pseudo-tooltip-overlay 'company-after))
2377 (overlay-put company-pseudo-tooltip-overlay 'window (selected-window))))
2379 (defun company-pseudo-tooltip-guard ()
2380 (buffer-substring-no-properties
2381 (point) (overlay-start company-pseudo-tooltip-overlay)))
2383 (defun company-pseudo-tooltip-frontend (command)
2384 "`company-mode' front-end similar to a tooltip but based on overlays."
2386 (pre-command (company-pseudo-tooltip-hide-temporarily))
2388 (let ((old-height (if (overlayp company-pseudo-tooltip-overlay)
2389 (overlay-get company-pseudo-tooltip-overlay
2392 (new-height (company--pseudo-tooltip-height)))
2393 (unless (and (>= (* old-height new-height) 0)
2394 (>= (abs old-height) (abs new-height))
2395 (equal (company-pseudo-tooltip-guard)
2396 (overlay-get company-pseudo-tooltip-overlay
2399 (company-pseudo-tooltip-show-at-point (- (point)
2400 (length company-prefix)))
2401 (overlay-put company-pseudo-tooltip-overlay
2402 'company-guard (company-pseudo-tooltip-guard))))
2403 (company-pseudo-tooltip-unhide))
2404 (hide (company-pseudo-tooltip-hide)
2405 (setq company-tooltip-offset 0))
2406 (update (when (overlayp company-pseudo-tooltip-overlay)
2407 (company-pseudo-tooltip-edit company-selection)))))
2409 (defun company-pseudo-tooltip-unless-just-one-frontend (command)
2410 "`company-pseudo-tooltip-frontend', but not shown for single candidates."
2411 (unless (and (eq command 'post-command)
2412 (company--show-inline-p))
2413 (company-pseudo-tooltip-frontend command)))
2415 ;;; overlay ;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;
2417 (defvar company-preview-overlay nil)
2418 (make-variable-buffer-local 'company-preview-overlay)
2420 (defun company-preview-show-at-point (pos)
2421 (company-preview-hide)
2423 (setq company-preview-overlay (make-overlay pos (1+ pos)))
2425 (let ((completion (nth company-selection company-candidates)))
2426 (setq completion (propertize completion 'face 'company-preview))
2427 (add-text-properties 0 (length company-common)
2428 '(face company-preview-common) completion)
2430 ;; Add search string
2431 (and company-search-string
2432 (string-match (regexp-quote company-search-string) completion)
2433 (add-text-properties (match-beginning 0)
2435 '(face company-preview-search)
2438 (setq completion (company-strip-prefix completion))
2440 (and (equal pos (point))
2441 (not (equal completion ""))
2442 (add-text-properties 0 1 '(cursor t) completion))
2444 (overlay-put company-preview-overlay 'display
2445 (concat completion (unless (eq pos (point-max))
2446 (buffer-substring pos (1+ pos)))))
2447 (overlay-put company-preview-overlay 'window (selected-window))))
2449 (defun company-preview-hide ()
2450 (when company-preview-overlay
2451 (delete-overlay company-preview-overlay)
2452 (setq company-preview-overlay nil)))
2454 (defun company-preview-frontend (command)
2455 "`company-mode' front-end showing the selection as if it had been inserted."
2457 (`pre-command (company-preview-hide))
2458 (`post-command (company-preview-show-at-point (point)))
2459 (`hide (company-preview-hide))))
2461 (defun company-preview-if-just-one-frontend (command)
2462 "`company-preview-frontend', but only shown for single candidates."
2463 (when (or (not (eq command 'post-command))
2464 (company--show-inline-p))
2465 (company-preview-frontend command)))
2467 (defun company--show-inline-p ()
2468 (and (not (cdr company-candidates))
2470 (string-prefix-p company-prefix company-common
2471 (company-call-backend 'ignore-case))))
2473 ;;; echo ;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;
2475 (defvar company-echo-last-msg nil)
2476 (make-variable-buffer-local 'company-echo-last-msg)
2478 (defvar company-echo-timer nil)
2480 (defvar company-echo-delay .01)
2482 (defun company-echo-show (&optional getter)
2484 (setq company-echo-last-msg (funcall getter)))
2485 (let ((message-log-max nil))
2486 (if company-echo-last-msg
2487 (message "%s" company-echo-last-msg)
2490 (defun company-echo-show-soon (&optional getter)
2491 (when company-echo-timer
2492 (cancel-timer company-echo-timer))
2493 (setq company-echo-timer (run-with-timer 0 nil 'company-echo-show getter)))
2495 (defsubst company-echo-show-when-idle (&optional getter)
2496 (when (sit-for company-echo-delay)
2497 (company-echo-show getter)))
2499 (defun company-echo-format ()
2501 (let ((limit (window-width (minibuffer-window)))
2503 ;; Roll to selection.
2504 (candidates (nthcdr company-selection company-candidates))
2505 (i (if company-show-numbers company-selection 99999))
2509 (setq comp (company-reformat (pop candidates))
2510 len (+ len 1 (length comp)))
2514 (setq comp (propertize (format "%d: %s" i comp)
2515 'face 'company-echo))
2518 (add-text-properties 3 (+ 3 (length company-common))
2519 '(face company-echo-common) comp))
2520 (setq comp (propertize comp 'face 'company-echo))
2521 (add-text-properties 0 (length company-common)
2522 '(face company-echo-common) comp))
2524 (setq candidates nil)
2527 (mapconcat 'identity (nreverse msg) " ")))
2529 (defun company-echo-strip-common-format ()
2531 (let ((limit (window-width (minibuffer-window)))
2532 (len (+ (length company-prefix) 2))
2533 ;; Roll to selection.
2534 (candidates (nthcdr company-selection company-candidates))
2535 (i (if company-show-numbers company-selection 99999))
2539 (setq comp (company-strip-prefix (pop candidates))
2540 len (+ len 2 (length comp)))
2543 (setq comp (format "%s (%d)" comp i))
2547 (setq candidates nil)
2548 (push (propertize comp 'face 'company-echo) msg)))
2550 (concat (propertize company-prefix 'face 'company-echo-common) "{"
2551 (mapconcat 'identity (nreverse msg) ", ")
2554 (defun company-echo-hide ()
2555 (unless (equal company-echo-last-msg "")
2556 (setq company-echo-last-msg "")
2557 (company-echo-show)))
2559 (defun company-echo-frontend (command)
2560 "`company-mode' front-end showing the candidates in the echo area."
2562 (`post-command (company-echo-show-soon 'company-echo-format))
2563 (`hide (company-echo-hide))))
2565 (defun company-echo-strip-common-frontend (command)
2566 "`company-mode' front-end showing the candidates in the echo area."
2568 (`post-command (company-echo-show-soon 'company-echo-strip-common-format))
2569 (`hide (company-echo-hide))))
2571 (defun company-echo-metadata-frontend (command)
2572 "`company-mode' front-end showing the documentation in the echo area."
2574 (`post-command (company-echo-show-when-idle 'company-fetch-metadata))
2575 (`hide (company-echo-hide))))
2578 ;;; company.el ends here