1 ;;; company.el --- extensible inline text completion mechanism
3 ;; Copyright (C) 2009 Nikolaj Schumacher
5 ;; Author: Nikolaj Schumacher <bugs * nschum de>
7 ;; Keywords: abbrev, convenience, matchis
8 ;; URL: http://nschum.de/src/emacs/company/
9 ;; Compatibility: GNU Emacs 22.x, GNU Emacs 23.x
11 ;; This file is NOT part of GNU Emacs.
13 ;; This program is free software; you can redistribute it and/or
14 ;; modify it under the terms of the GNU General Public License
15 ;; as published by the Free Software Foundation; either version 2
16 ;; of the License, or (at your option) any later version.
18 ;; This program is distributed in the hope that it will be useful,
19 ;; but WITHOUT ANY WARRANTY; without even the implied warranty of
20 ;; MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
21 ;; GNU General Public License for more details.
23 ;; You should have received a copy of the GNU General Public License
24 ;; along with this program. If not, see <http://www.gnu.org/licenses/>.
28 ;; Company is a modular completion mechanism. Modules for retrieving completion
29 ;; candidates are called back-ends, modules for displaying them are front-ends.
31 ;; Company comes with many back-ends, e.g. `company-elisp'. These are
32 ;; distributed in individual files and can be used individually.
34 ;; Place company.el and the back-ends you want to use in a directory and add the
35 ;; following to your .emacs:
36 ;; (add-to-list 'load-path "/path/to/company")
37 ;; (autoload 'company-mode "company" nil t)
39 ;; Enable company-mode with M-x company-mode. For further information look at
40 ;; the documentation for `company-mode' (C-h f company-mode RET)
42 ;; If you want to start a specific back-end, call it interactively or use
43 ;; `company-begin-backend'. For example:
44 ;; M-x company-abbrev will prompt for and insert an abbrev.
46 ;; To write your own back-end, look at the documentation for `company-backends'.
47 ;; Here is a simple example completing "foo":
49 ;; (defun company-my-backend (command &optional arg &rest ignored)
51 ;; ('prefix (when (looking-back "foo\\>")
53 ;; ('candidates (list "foobar" "foobaz" "foobarbaz"))
54 ;; ('meta (format "This value is named %s" arg))))
56 ;; Sometimes it is a good idea to mix two back-ends together, for example to
57 ;; enrich gtags with dabbrev text (to emulate local variables):
59 ;; (defun gtags-gtags-dabbrev-backend (command &optional arg &rest ignored)
61 ;; (prefix (company-gtags 'prefix))
62 ;; (candidates (append (company-gtags 'candidates arg)
63 ;; (company-dabbrev 'candidates arg)))))
66 ;; When point is at the very end of the buffer, the pseudo-tooltip appears very
67 ;; wrong, unless company is allowed to temporarily insert a fake newline.
68 ;; This behavior is enabled by `company-end-of-buffer-workaround'.
72 ;; The pseudo tooltip will no longer be clipped at the right window edge.
73 ;; Added `company-tooltip-minimum'.
74 ;; Windows compatibility fixes.
77 ;; Added `global-company-mode'.
78 ;; Performance enhancements.
79 ;; Added `company-eclim' back-end.
80 ;; Added safer workaround for Emacs `posn-col-row' bug.
83 ;; Automatic completion is now aborted if the prefix gets too short.
84 ;; Added option `company-dabbrev-time-limit'.
85 ;; `company-backends' now supports merging back-ends.
86 ;; Added back-end `company-dabbrev-code' for generic code.
87 ;; Fixed `company-begin-with'.
90 ;; Added 'stop prefix to prevent dabbrev from completing inside of symbols.
91 ;; Fixed issues with tabbar-mode and line-spacing.
92 ;; Performance enhancements.
95 ;; Added `company-begin-commands' option.
96 ;; Added abbrev, tempo and Xcode back-ends.
97 ;; Back-ends are now interactive. You can start them with M-x backend-name.
98 ;; Added `company-begin-with' for starting company from elisp-code.
100 ;; Added `company-require-match' and `company-auto-complete' options.
102 ;; 2009-04-05 (0.2.1)
103 ;; Improved Emacs Lisp back-end behavior for local variables.
104 ;; Added `company-elisp-detect-function-context' option.
105 ;; The mouse can now be used for selection.
108 ;; Added `company-show-location'.
109 ;; Added etags back-end.
110 ;; Added work-around for end-of-buffer bug.
111 ;; Added `company-filter-candidates'.
112 ;; More local Lisp variables are now included in the candidates.
114 ;; 2009-03-21 (0.1.5)
115 ;; Fixed elisp documentation buffer always showing the same doc.
116 ;; Added `company-echo-strip-common-frontend'.
117 ;; Added `company-show-numbers' option and M-0 ... M-9 default bindings.
118 ;; Don't hide the echo message if it isn't shown.
125 (eval-when-compile (require 'cl))
127 (add-to-list 'debug-ignored-errors "^.* frontend cannot be used twice$")
128 (add-to-list 'debug-ignored-errors "^Echo area cannot be used twice$")
129 (add-to-list 'debug-ignored-errors "^No \\(document\\|loc\\)ation available$")
130 (add-to-list 'debug-ignored-errors "^Company not ")
131 (add-to-list 'debug-ignored-errors "^No candidate number ")
132 (add-to-list 'debug-ignored-errors "^Cannot complete at point$")
134 (defgroup company nil
135 "Extensible inline text completion mechanism"
140 (defface company-tooltip
141 '((t :background "yellow"
142 :foreground "black"))
143 "*Face used for the tool tip."
146 (defface company-tooltip-selection
147 '((default :inherit company-tooltip)
148 (((class color) (min-colors 88)) (:background "orange1"))
149 (t (:background "green")))
150 "*Face used for the selection in the tool tip."
153 (defface company-tooltip-mouse
154 '((default :inherit highlight))
155 "*Face used for the tool tip item under the mouse."
158 (defface company-tooltip-common
159 '((t :inherit company-tooltip
161 "*Face used for the common completion in the tool tip."
164 (defface company-tooltip-common-selection
165 '((t :inherit company-tooltip-selection
167 "*Face used for the selected common completion in the tool tip."
170 (defface company-preview
171 '((t :background "blue4"
172 :foreground "wheat"))
173 "*Face used for the completion preview."
176 (defface company-preview-common
177 '((t :inherit company-preview
179 "*Face used for the common part of the completion preview."
182 (defface company-preview-search
183 '((t :inherit company-preview
184 :background "blue1"))
185 "*Face used for the search string in the completion preview."
188 (defface company-echo nil
189 "*Face used for completions in the echo area."
192 (defface company-echo-common
193 '((((background dark)) (:foreground "firebrick1"))
194 (((background light)) (:background "firebrick4")))
195 "*Face used for the common part of completions in the echo area."
198 (defun company-frontends-set (variable value)
200 (let ((remainder value))
201 (setcdr remainder (delq (car remainder) (cdr remainder))))
202 (and (memq 'company-pseudo-tooltip-unless-just-one-frontend value)
203 (memq 'company-pseudo-tooltip-frontend value)
204 (error "Pseudo tooltip frontend cannot be used twice"))
205 (and (memq 'company-preview-if-just-one-frontend value)
206 (memq 'company-preview-frontend value)
207 (error "Preview frontend cannot be used twice"))
208 (and (memq 'company-echo value)
209 (memq 'company-echo-metadata-frontend value)
210 (error "Echo area cannot be used twice"))
211 ;; preview must come last
212 (dolist (f '(company-preview-if-just-one-frontend company-preview-frontend))
214 (setq value (append (delq f value) (list f)))))
215 (set variable value))
217 (defcustom company-frontends '(company-pseudo-tooltip-unless-just-one-frontend
218 company-preview-frontend
219 company-echo-metadata-frontend)
220 "*The list of active front-ends (visualizations).
221 Each front-end is a function that takes one argument. It is called with
222 one of the following arguments:
224 'show: When the visualization should start.
226 'hide: When the visualization should end.
228 'update: When the data has been updated.
230 'pre-command: Before every command that is executed while the
231 visualization is active.
233 'post-command: After every command that is executed while the
234 visualization is active.
236 The visualized data is stored in `company-prefix', `company-candidates',
237 `company-common', `company-selection', `company-point' and
238 `company-search-string'."
239 :set 'company-frontends-set
241 :type '(repeat (choice (const :tag "echo" company-echo-frontend)
242 (const :tag "echo, strip common"
243 company-echo-strip-common-frontend)
244 (const :tag "show echo meta-data in echo"
245 company-echo-metadata-frontend)
246 (const :tag "pseudo tooltip"
247 company-pseudo-tooltip-frontend)
248 (const :tag "pseudo tooltip, multiple only"
249 company-pseudo-tooltip-unless-just-one-frontend)
250 (const :tag "preview" company-preview-frontend)
251 (const :tag "preview, unique only"
252 company-preview-if-just-one-frontend)
253 (function :tag "custom function" nil))))
255 (defcustom company-tooltip-limit 10
256 "*The maximum number of candidates in the tool tip"
260 (defcustom company-tooltip-minimum 6
261 "*The minimum height of the tool tip.
262 If this many lines are not available, prefer to display the tooltip above."
266 (defvar company-safe-backends
267 '((company-abbrev . "Abbrev")
268 (company-css . "CSS")
269 (company-dabbrev . "dabbrev for plain text")
270 (company-dabbrev-code . "dabbrev for code")
271 (company-eclim . "eclim (an Eclipse interace)")
272 (company-elisp . "Emacs Lisp")
273 (company-etags . "etags")
274 (company-files . "Files")
275 (company-gtags . "GNU Global")
276 (company-ispell . "ispell")
277 (company-keywords . "Programming language keywords")
278 (company-nxml . "nxml")
279 (company-oddmuse . "Oddmuse")
280 (company-semantic . "CEDET Semantic")
281 (company-tempo . "Tempo templates")
282 (company-xcode . "Xcode")))
283 (put 'company-safe-backends 'risky-local-variable t)
285 (defun company-safe-backends-p (backends)
286 (and (consp backends)
287 (not (dolist (backend backends)
288 (unless (if (consp backend)
289 (company-safe-backends-p backend)
290 (assq backend company-safe-backends))
293 (defcustom company-backends '(company-elisp company-nxml company-css
294 company-eclim company-semantic company-xcode
295 (company-gtags company-etags company-dabbrev-code
297 company-oddmuse company-files company-dabbrev)
298 "*The list of active back-ends (completion engines).
299 Each list elements can itself be a list of back-ends. In that case their
300 completions are merged. Otherwise only the first matching back-end returns
303 Each back-end is a function that takes a variable number of arguments.
304 The first argument is the command requested from the back-end. It is one
307 'prefix: The back-end should return the text to be completed. It must be
308 text immediately before `point'. Returning nil passes control to the next
309 back-end. The function should return 'stop if it should complete but cannot
310 \(e.g. if it is in the middle of a string\).
312 'candidates: The second argument is the prefix to be completed. The
313 return value should be a list of candidates that start with the prefix.
317 'sorted: The back-end may return t here to indicate that the candidates
318 are sorted and will not need to be sorted again.
320 'duplicates: If non-nil, company will take care of removing duplicates
323 'no-cache: Usually company doesn't ask for candidates again as completion
324 progresses, unless the back-end returns t for this command. The second
325 argument is the latest prefix.
327 'meta: The second argument is a completion candidate. The back-end should
328 return a (short) documentation string for it.
330 'doc-buffer: The second argument is a completion candidate. The back-end should
331 create a buffer (preferably with `company-doc-buffer'), fill it with
332 documentation and return it.
334 'location: The second argument is a completion candidate. The back-end can
335 return the cons of buffer and buffer location, or of file and line
336 number where the completion candidate was defined.
338 'require-match: If this value is t, the user is not allowed to enter anything
339 not offering as a candidate. Use with care! The default value nil gives the
340 user that choice with `company-require-match'. Return value 'never overrides
341 that option the other way around.
343 The back-end should return nil for all commands it does not support or
344 does not know about. It should also be callable interactively and use
345 `company-begin-backend' to start itself in that case."
350 ,@(mapcar (lambda (b) `(const :tag ,(cdr b) ,(car b)))
351 company-safe-backends)
352 (symbol :tag "User defined")
353 (repeat :tag "Merged Back-ends"
354 (choice :tag "Back-end"
355 ,@(mapcar (lambda (b)
356 `(const :tag ,(cdr b) ,(car b)))
357 company-safe-backends)
358 (symbol :tag "User defined"))))))
360 (put 'company-backends 'safe-local-variable 'company-safe-backend-p)
362 (defcustom company-completion-started-hook nil
363 "*Hook run when company starts completing.
364 The hook is called with one argument that is non-nil if the completion was
369 (defcustom company-completion-cancelled-hook nil
370 "*Hook run when company cancels completing.
371 The hook is called with one argument that is non-nil if the completion was
376 (defcustom company-completion-finished-hook nil
377 "*Hook run when company successfully completes.
378 The hook is called with the selected candidate as an argument."
382 (defcustom company-minimum-prefix-length 3
383 "*The minimum prefix length for automatic completion."
385 :type '(integer :tag "prefix length"))
387 (defcustom company-require-match 'company-explicit-action-p
388 "*If enabled, disallow non-matching input.
389 This can be a function do determine if a match is required.
391 This can be overridden by the back-end, if it returns t or 'never to
392 'require-match. `company-auto-complete' also takes precedence over this."
394 :type '(choice (const :tag "Off" nil)
395 (function :tag "Predicate function")
396 (const :tag "On, if user interaction took place"
397 'company-explicit-action-p)
398 (const :tag "On" t)))
400 (defcustom company-auto-complete 'company-explicit-action-p
401 "Determines when to auto-complete.
402 If this is enabled, all characters from `company-auto-complete-chars' complete
403 the selected completion. This can also be a function."
405 :type '(choice (const :tag "Off" nil)
406 (function :tag "Predicate function")
407 (const :tag "On, if user interaction took place"
408 'company-explicit-action-p)
409 (const :tag "On" t)))
411 (defcustom company-auto-complete-chars '(?\ ?\( ?\) ?. ?\" ?$ ?\' ?< ?| ?!)
412 "Determines which characters trigger an automatic completion.
413 See `company-auto-complete'. If this is a string, each string character causes
414 completion. If it is a list of syntax description characters (see
415 `modify-syntax-entry'), all characters with that syntax auto-complete.
417 This can also be a function, which is called with the new input and should
418 return non-nil if company should auto-complete.
420 A character that is part of a valid candidate never starts auto-completion."
422 :type '(choice (string :tag "Characters")
424 (const :tag "Whitespace" ?\ )
425 (const :tag "Symbol" ?_)
426 (const :tag "Opening parentheses" ?\()
427 (const :tag "Closing parentheses" ?\))
428 (const :tag "Word constituent" ?w)
429 (const :tag "Punctuation." ?.)
430 (const :tag "String quote." ?\")
431 (const :tag "Paired delimiter." ?$)
432 (const :tag "Expression quote or prefix operator." ?\')
433 (const :tag "Comment starter." ?<)
434 (const :tag "Comment ender." ?>)
435 (const :tag "Character-quote." ?/)
436 (const :tag "Generic string fence." ?|)
437 (const :tag "Generic comment fence." ?!))
438 (function :tag "Predicate function")))
440 (defcustom company-idle-delay .7
441 "*The idle delay in seconds until automatic completions starts.
442 A value of nil means never complete automatically, t means complete
443 immediately when a prefix of `company-minimum-prefix-length' is reached."
445 :type '(choice (const :tag "never (nil)" nil)
446 (const :tag "immediate (t)" t)
447 (number :tag "seconds")))
449 (defcustom company-begin-commands t
450 "*A list of commands following which company will start completing.
451 If this is t, it will complete after any command. See `company-idle-delay'.
453 Alternatively any command with a non-nil 'company-begin property is treated as
454 if it was on this list."
456 :type '(choice (const :tag "Any command" t)
457 (const :tag "Self insert command" '(self-insert-command))
458 (repeat :tag "Commands" function)))
460 (defcustom company-show-numbers nil
461 "*If enabled, show quick-access numbers for the first ten candidates."
463 :type '(choice (const :tag "off" nil)
464 (const :tag "on" t)))
466 (defvar company-end-of-buffer-workaround t
467 "*Work around a visualization bug when completing at the end of the buffer.
468 The work-around consists of adding a newline.")
470 ;;; mode ;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;
472 (defvar company-mode-map (make-sparse-keymap)
473 "Keymap used by `company-mode'.")
475 (defvar company-active-map
476 (let ((keymap (make-sparse-keymap)))
477 (define-key keymap "\e\e\e" 'company-abort)
478 (define-key keymap "\C-g" 'company-abort)
479 (define-key keymap (kbd "M-n") 'company-select-next)
480 (define-key keymap (kbd "M-p") 'company-select-previous)
481 (define-key keymap (kbd "<down>") 'company-select-next)
482 (define-key keymap (kbd "<up>") 'company-select-previous)
483 (define-key keymap [down-mouse-1] 'ignore)
484 (define-key keymap [down-mouse-3] 'ignore)
485 (define-key keymap [mouse-1] 'company-complete-mouse)
486 (define-key keymap [mouse-3] 'company-select-mouse)
487 (define-key keymap [up-mouse-1] 'ignore)
488 (define-key keymap [up-mouse-3] 'ignore)
489 (define-key keymap "\C-m" 'company-complete-selection)
490 (define-key keymap "\t" 'company-complete-common)
491 (define-key keymap (kbd "<f1>") 'company-show-doc-buffer)
492 (define-key keymap "\C-w" 'company-show-location)
493 (define-key keymap "\C-s" 'company-search-candidates)
494 (define-key keymap "\C-\M-s" 'company-filter-candidates)
496 (define-key keymap (vector (+ (aref (kbd "M-0") 0) i))
497 `(lambda () (interactive) (company-complete-number ,i))))
500 "Keymap that is enabled during an active completion.")
502 (defvar company--disabled-backends nil)
504 (defun company-init-backend (backend)
505 (and (symbolp backend)
506 (not (fboundp backend))
507 (ignore-errors (require backend nil t)))
509 (if (or (symbolp backend)
511 (if (ignore-errors (funcall backend 'init) t)
512 (put backend 'company-init t)
513 (put backend 'company-init 'failed)
514 (unless (memq backend company--disabled-backends)
515 (message "Company back-end '%s' could not be initialized"
517 (push backend company--disabled-backends))
519 (mapc 'company-init-backend backend)))
521 (defvar company-default-lighter " company")
523 (defvar company-lighter company-default-lighter)
524 (make-variable-buffer-local 'company-lighter)
527 (define-minor-mode company-mode
528 "\"complete anything\"; in in-buffer completion framework.
529 Completion starts automatically, depending on the values
530 `company-idle-delay' and `company-minimum-prefix-length'.
532 Completion can be controlled with the commands:
533 `company-complete-common', `company-complete-selection', `company-complete',
534 `company-select-next', `company-select-previous'. If these commands are
535 called before `company-idle-delay', completion will also start.
537 Completions can be searched with `company-search-candidates' or
538 `company-filter-candidates'. These can be used while completion is
541 The completion data is retrieved using `company-backends' and displayed using
542 `company-frontends'. If you want to start a specific back-end, call it
543 interactively or use `company-begin-backend'.
545 regular keymap (`company-mode-map'):
548 keymap during active completions (`company-active-map'):
550 \\{company-active-map}"
551 nil company-lighter company-mode-map
554 (add-hook 'pre-command-hook 'company-pre-command nil t)
555 (add-hook 'post-command-hook 'company-post-command nil t)
556 (mapc 'company-init-backend company-backends))
557 (remove-hook 'pre-command-hook 'company-pre-command t)
558 (remove-hook 'post-command-hook 'company-post-command t)
560 (kill-local-variable 'company-point)))
562 (define-globalized-minor-mode global-company-mode company-mode
563 (lambda () (company-mode 1)))
565 (defsubst company-assert-enabled ()
567 (company-uninstall-map)
568 (error "Company not enabled")))
570 ;;; keymaps ;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;
572 (defvar company-overriding-keymap-bound nil)
573 (make-variable-buffer-local 'company-overriding-keymap-bound)
575 (defvar company-old-keymap nil)
576 (make-variable-buffer-local 'company-old-keymap)
578 (defvar company-my-keymap nil)
579 (make-variable-buffer-local 'company-my-keymap)
581 (defsubst company-enable-overriding-keymap (keymap)
582 (setq company-my-keymap keymap)
583 (when company-overriding-keymap-bound
584 (company-uninstall-map)))
586 (defun company-install-map ()
587 (unless (or company-overriding-keymap-bound
588 (null company-my-keymap))
589 (setq company-old-keymap overriding-terminal-local-map
590 overriding-terminal-local-map company-my-keymap
591 company-overriding-keymap-bound t)))
593 (defun company-uninstall-map ()
594 (when (eq overriding-terminal-local-map company-my-keymap)
595 (setq overriding-terminal-local-map company-old-keymap
596 company-overriding-keymap-bound nil)))
599 ;; Emacs calculates the active keymaps before reading the event. That means we
600 ;; cannot change the keymap from a timer. So we send a bogus command.
601 (defun company-ignore ()
603 (setq this-command last-command))
605 (global-set-key '[31415926] 'company-ignore)
607 (defun company-input-noop ()
608 (push 31415926 unread-command-events))
611 ;; posn-col-row is incorrect in older Emacsen when line-spacing is set
612 (defun company--col-row (&optional pos)
613 (let ((posn (posn-at-point pos)))
614 (cons (car (posn-col-row posn)) (cdr (posn-actual-col-row posn)))))
616 (defsubst company--column (&optional pos)
617 (car (posn-col-row (posn-at-point pos))))
619 (defsubst company--row (&optional pos)
620 (cdr (posn-actual-col-row (posn-at-point pos))))
622 ;;; backends ;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;
624 (defun company-grab (regexp &optional expression limit)
625 (when (looking-back regexp limit)
626 (or (match-string-no-properties (or expression 0)) "")))
628 (defun company-grab-line (regexp &optional expression)
629 (company-grab regexp expression (point-at-bol)))
631 (defun company-grab-symbol ()
632 (if (looking-at "\\_>")
633 (buffer-substring (point) (save-excursion (skip-syntax-backward "w_")
635 (unless (and (char-after) (memq (char-syntax (char-after)) '(?w ?_)))
638 (defun company-grab-word ()
639 (if (looking-at "\\>")
640 (buffer-substring (point) (save-excursion (skip-syntax-backward "w")
642 (unless (and (char-after) (eq (char-syntax (char-after)) ?w))
645 (defun company-in-string-or-comment ()
646 (let ((ppss (syntax-ppss)))
647 (or (car (setq ppss (nthcdr 3 ppss)))
648 (car (setq ppss (cdr ppss)))
651 (if (fboundp 'locate-dominating-file)
652 (defalias 'company-locate-dominating-file 'locate-dominating-file)
653 (defun company-locate-dominating-file (file name)
655 (let ((dir (file-name-directory file))
657 (while (not (equal dir prev-dir))
658 (when (file-exists-p (expand-file-name name dir))
661 dir (file-name-directory (directory-file-name dir))))))))
663 (defun company-call-backend (&rest args)
664 (if (functionp company-backend)
665 (apply company-backend args)
666 (apply 'company--multi-backend-adapter company-backend args)))
668 (defun company--multi-backend-adapter (backends command &rest args)
671 (apply 'append (mapcar (lambda (backend) (apply backend command args))
677 (dolist (backend backends)
678 (when (setq value (apply backend command args))
681 ;;; completion mechanism ;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;
683 (defvar company-backend nil)
684 (make-variable-buffer-local 'company-backend)
686 (defvar company-prefix nil)
687 (make-variable-buffer-local 'company-prefix)
689 (defvar company-candidates nil)
690 (make-variable-buffer-local 'company-candidates)
692 (defvar company-candidates-length nil)
693 (make-variable-buffer-local 'company-candidates-length)
695 (defvar company-candidates-cache nil)
696 (make-variable-buffer-local 'company-candidates-cache)
698 (defvar company-candidates-predicate nil)
699 (make-variable-buffer-local 'company-candidates-predicate)
701 (defvar company-common nil)
702 (make-variable-buffer-local 'company-common)
704 (defvar company-selection 0)
705 (make-variable-buffer-local 'company-selection)
707 (defvar company-selection-changed nil)
708 (make-variable-buffer-local 'company-selection-changed)
710 (defvar company--explicit-action nil
711 "Non-nil, if explicit completion took place.")
712 (make-variable-buffer-local 'company--explicit-action)
714 (defvar company--point-max nil)
715 (make-variable-buffer-local 'company--point-max)
717 (defvar company-point nil)
718 (make-variable-buffer-local 'company-point)
720 (defvar company-timer nil)
722 (defvar company-added-newline nil)
723 (make-variable-buffer-local 'company-added-newline)
725 (defsubst company-strip-prefix (str)
726 (substring str (length company-prefix)))
728 (defun company-explicit-action-p ()
729 "Return whether explicit completion action was taken by the user."
730 (or company--explicit-action
731 company-selection-changed))
733 (defsubst company-reformat (candidate)
734 ;; company-ispell needs this, because the results are always lower-case
735 ;; It's mory efficient to fix it only when they are displayed.
736 (concat company-prefix (substring candidate (length company-prefix))))
738 (defun company--should-complete ()
739 (and (not (or buffer-read-only overriding-terminal-local-map
740 overriding-local-map))
741 (eq company-idle-delay t)
742 (or (eq t company-begin-commands)
743 (memq this-command company-begin-commands)
744 (and (symbolp this-command) (get this-command 'company-begin)))
745 (not (and transient-mark-mode mark-active))))
747 (defsubst company-call-frontends (command)
748 (dolist (frontend company-frontends)
750 (funcall frontend command)
751 (error (error "Company: Front-end %s error \"%s\" on command %s"
752 frontend (error-message-string err) command)))))
754 (defsubst company-set-selection (selection &optional force-update)
755 (setq selection (max 0 (min (1- company-candidates-length) selection)))
756 (when (or force-update (not (equal selection company-selection)))
757 (setq company-selection selection
758 company-selection-changed t)
759 (company-call-frontends 'update)))
761 (defun company-apply-predicate (candidates predicate)
763 (dolist (c candidates)
764 (when (funcall predicate c)
768 (defun company-update-candidates (candidates)
769 (setq company-candidates-length (length candidates))
770 (if (> company-selection 0)
771 ;; Try to restore the selection
772 (let ((selected (nth company-selection company-candidates)))
773 (setq company-selection 0
774 company-candidates candidates)
776 (while (and candidates (string< (pop candidates) selected))
777 (incf company-selection))
779 ;; Make sure selection isn't out of bounds.
780 (setq company-selection (min (1- company-candidates-length)
781 company-selection)))))
782 (setq company-selection 0
783 company-candidates candidates))
785 (push (cons company-prefix company-candidates) company-candidates-cache)
787 (let ((completion-ignore-case (company-call-backend 'ignore-case)))
788 (setq company-common (try-completion company-prefix company-candidates)))
789 (when (eq company-common t)
790 (setq company-candidates nil)))
792 (defun company-calculate-candidates (prefix)
793 (let ((candidates (cdr (assoc prefix company-candidates-cache))))
795 (when company-candidates-cache
796 (let ((len (length prefix))
797 (completion-ignore-case (company-call-backend 'ignore-case))
799 (dotimes (i (1+ len))
800 (when (setq prev (cdr (assoc (substring prefix 0 (- len i))
801 company-candidates-cache)))
802 (setq candidates (all-completions prefix prev))
804 ;; no cache match, call back-end
806 (setq candidates (company-call-backend 'candidates prefix))
807 (when company-candidates-predicate
809 (company-apply-predicate candidates
810 company-candidates-predicate)))
811 (unless (company-call-backend 'sorted)
812 (setq candidates (sort candidates 'string<)))
813 (when (company-call-backend 'duplicates)
815 (let ((c2 candidates))
817 (setcdr c2 (progn (while (equal (pop c2) (car c2)))
819 (if (or (cdr candidates)
820 (not (equal (car candidates) prefix)))
821 ;; Don't start when already completed and unique.
823 ;; Not the right place? maybe when setting?
824 (and company-candidates t))))
826 (defun company-idle-begin (buf win tick pos)
828 (eq buf (current-buffer))
829 (eq win (selected-window))
830 (eq tick (buffer-chars-modified-tick))
832 (not company-candidates)
833 (not (equal (point) company-point))
834 (let ((company-idle-delay t)
835 (company-begin-commands t))
837 (when company-candidates
839 (company-post-command)))))
841 (defun company-auto-begin ()
842 (company-assert-enabled)
844 (not company-candidates)
845 (let ((company-idle-delay t)
846 (company-minimum-prefix-length 0)
847 (company-begin-commands t))
849 ;; Return non-nil if active.
852 (defun company-manual-begin ()
854 (setq company--explicit-action t)
855 (company-auto-begin))
857 (defun company-require-match-p ()
858 (let ((backend-value (company-call-backend 'require-match)))
859 (or (eq backend-value t)
860 (and (if (functionp company-require-match)
861 (funcall company-require-match)
862 (eq company-require-match t))
863 (not (eq backend-value 'never))))))
865 (defun company-punctuation-p (input)
866 "Return non-nil, if input starts with punctuation or parentheses."
867 (memq (char-syntax (string-to-char input)) '(?. ?\( ?\))))
869 (defun company-auto-complete-p (input)
870 "Return non-nil, if input starts with punctuation or parentheses."
871 (and (if (functionp company-auto-complete)
872 (funcall company-auto-complete)
873 company-auto-complete)
874 (if (functionp company-auto-complete-chars)
875 (funcall company-auto-complete-chars input)
876 (if (consp company-auto-complete-chars)
877 (memq (char-syntax (string-to-char input))
878 company-auto-complete-chars)
879 (string-match (substring input 0 1) company-auto-complete-chars)))))
881 (defun company--incremental-p ()
882 (and (> (point) company-point)
883 (> (point-max) company--point-max)
884 (not (eq this-command 'backward-delete-char-untabify))
885 (equal (buffer-substring (- company-point (length company-prefix))
889 (defsubst company--string-incremental-p (old-prefix new-prefix)
890 (and (> (length new-prefix) (length old-prefix))
891 (equal old-prefix (substring new-prefix 0 (length old-prefix)))))
893 (defun company--continue-failed (new-prefix)
894 (when (company--incremental-p)
895 (let ((input (buffer-substring-no-properties (point) company-point)))
897 ((company-auto-complete-p input)
900 (goto-char company-point)
901 (company-complete-selection)
903 ((and (company--string-incremental-p company-prefix new-prefix)
904 (company-require-match-p))
905 ;; wrong incremental input, but required match
906 (backward-delete-char (length input))
908 (message "Matching input is required")
910 ((equal company-prefix (car company-candidates))
911 ;; last input was actually success
912 (company-cancel company-prefix)
915 (defun company--continue ()
916 (when (company-call-backend 'no-cache company-prefix)
917 ;; Don't complete existing candidates, fetch new ones.
918 (setq company-candidates-cache nil))
919 (let* ((new-prefix (company-call-backend 'prefix))
920 (c (when (and (stringp new-prefix)
921 (or (company-explicit-action-p)
922 (>= (length new-prefix)
923 company-minimum-prefix-length))
924 (= (- (point) (length new-prefix))
925 (- company-point (length company-prefix))))
926 (company-calculate-candidates new-prefix))))
929 ;; t means complete/unique.
930 (company-cancel new-prefix)
934 (setq company-prefix new-prefix)
935 (company-update-candidates c)
937 (t (company--continue-failed new-prefix)))
940 (defun company--begin-new ()
942 (dolist (backend (if company-backend
943 ;; prefer manual override
944 (list company-backend)
947 (if (or (symbolp backend)
949 (when (or (not (symbolp backend))
950 (eq t (get backend 'company-init))
951 (unless (get backend 'company-init)
952 (company-init-backend backend)))
953 (funcall backend 'prefix))
954 (company--multi-backend-adapter backend 'prefix)))
956 (when (and (stringp prefix)
957 (>= (length prefix) company-minimum-prefix-length))
958 (setq company-backend backend
959 c (company-calculate-candidates prefix))
960 ;; t means complete/unique. We don't start, so no hooks.
962 (setq company-prefix prefix
963 company-lighter (concat " " (symbol-name backend)))
964 (company-update-candidates c)
965 (run-hook-with-args 'company-completion-started-hook
966 (company-explicit-action-p))
967 (company-call-frontends 'show)))
970 (defun company-begin ()
971 (setq company-candidates
972 (or (and company-candidates (company--continue))
973 (and (company--should-complete) (company--begin-new))))
974 (when company-candidates
975 (when (and company-end-of-buffer-workaround (eobp))
976 (save-excursion (insert "\n"))
977 (setq company-added-newline (buffer-chars-modified-tick)))
978 (setq company-point (point)
979 company--point-max (point-max))
980 (company-enable-overriding-keymap company-active-map)
981 (company-call-frontends 'update)))
983 (defun company-cancel (&optional result)
984 (and company-added-newline
985 (> (point-max) (point-min))
986 (let ((tick (buffer-chars-modified-tick)))
987 (delete-region (1- (point-max)) (point-max))
988 (equal tick company-added-newline))
989 ;; Only set unmodified when tick remained the same since insert.
990 (set-buffer-modified-p nil))
993 (run-hook-with-args 'company-completion-finished-hook result)
994 (run-hook-with-args 'company-completion-cancelled-hook result)))
995 (setq company-added-newline nil
998 company-candidates nil
999 company-candidates-length nil
1000 company-candidates-cache nil
1001 company-candidates-predicate nil
1004 company-selection-changed nil
1005 company--explicit-action nil
1006 company-lighter company-default-lighter
1007 company--point-max nil
1010 (cancel-timer company-timer))
1011 (company-search-mode 0)
1012 (company-call-frontends 'hide)
1013 (company-enable-overriding-keymap nil))
1015 (defun company-abort ()
1018 ;; Don't start again, unless started manually.
1019 (setq company-point (point)))
1021 (defun company-finish (result)
1022 (insert (company-strip-prefix result))
1023 (company-cancel result)
1024 ;; Don't start again, unless started manually.
1025 (setq company-point (point)))
1027 (defsubst company-keep (command)
1028 (and (symbolp command) (get command 'company-keep)))
1030 (defun company-pre-command ()
1031 (unless (company-keep this-command)
1033 (when company-candidates
1034 (company-call-frontends 'pre-command))
1035 (error (message "Company: An error occurred in pre-command")
1036 (message "%s" (error-message-string err))
1039 (cancel-timer company-timer)
1040 (setq company-timer nil))
1041 (company-uninstall-map))
1043 (defun company-post-command ()
1044 (unless (company-keep this-command)
1047 (unless (equal (point) company-point)
1049 (if company-candidates
1050 (company-call-frontends 'post-command)
1051 (and (numberp company-idle-delay)
1052 (or (eq t company-begin-commands)
1053 (memq this-command company-begin-commands))
1055 (run-with-timer company-idle-delay nil
1057 (current-buffer) (selected-window)
1058 (buffer-chars-modified-tick) (point))))))
1059 (error (message "Company: An error occurred in post-command")
1060 (message "%s" (error-message-string err))
1062 (company-install-map))
1064 ;;; search ;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;
1066 (defvar company-search-string nil)
1067 (make-variable-buffer-local 'company-search-string)
1069 (defvar company-search-lighter " Search: \"\"")
1070 (make-variable-buffer-local 'company-search-lighter)
1072 (defvar company-search-old-map nil)
1073 (make-variable-buffer-local 'company-search-old-map)
1075 (defvar company-search-old-selection 0)
1076 (make-variable-buffer-local 'company-search-old-selection)
1078 (defun company-search (text lines)
1079 (let ((quoted (regexp-quote text))
1081 (dolist (line lines)
1082 (when (string-match quoted line (length company-prefix))
1086 (defun company-search-printing-char ()
1088 (company-search-assert-enabled)
1089 (setq company-search-string
1090 (concat (or company-search-string "") (string last-command-event))
1091 company-search-lighter (concat " Search: \"" company-search-string
1093 (let ((pos (company-search company-search-string
1094 (nthcdr company-selection company-candidates))))
1097 (company-set-selection (+ company-selection pos) t))))
1099 (defun company-search-repeat-forward ()
1100 "Repeat the incremental search in completion candidates forward."
1102 (company-search-assert-enabled)
1103 (let ((pos (company-search company-search-string
1104 (cdr (nthcdr company-selection
1105 company-candidates)))))
1108 (company-set-selection (+ company-selection pos 1) t))))
1110 (defun company-search-repeat-backward ()
1111 "Repeat the incremental search in completion candidates backwards."
1113 (company-search-assert-enabled)
1114 (let ((pos (company-search company-search-string
1115 (nthcdr (- company-candidates-length
1117 (reverse company-candidates)))))
1120 (company-set-selection (- company-selection pos 1) t))))
1122 (defun company-create-match-predicate ()
1123 (setq company-candidates-predicate
1124 `(lambda (candidate)
1125 ,(if company-candidates-predicate
1126 `(and (string-match ,company-search-string candidate)
1127 (funcall ,company-candidates-predicate
1129 `(string-match ,company-search-string candidate))))
1130 (company-update-candidates
1131 (company-apply-predicate company-candidates company-candidates-predicate))
1132 ;; Invalidate cache.
1133 (setq company-candidates-cache (cons company-prefix company-candidates)))
1135 (defun company-filter-printing-char ()
1137 (company-search-assert-enabled)
1138 (company-search-printing-char)
1139 (company-create-match-predicate)
1140 (company-call-frontends 'update))
1142 (defun company-search-kill-others ()
1143 "Limit the completion candidates to the ones matching the search string."
1145 (company-search-assert-enabled)
1146 (company-create-match-predicate)
1147 (company-search-mode 0)
1148 (company-call-frontends 'update))
1150 (defun company-search-abort ()
1151 "Abort searching the completion candidates."
1153 (company-search-assert-enabled)
1154 (company-set-selection company-search-old-selection t)
1155 (company-search-mode 0))
1157 (defun company-search-other-char ()
1159 (company-search-assert-enabled)
1160 (company-search-mode 0)
1161 (when last-input-event
1162 (clear-this-command-keys t)
1163 (setq unread-command-events (list last-input-event))))
1165 (defvar company-search-map
1167 (keymap (make-keymap)))
1168 (if (fboundp 'max-char)
1169 (set-char-table-range (nth 1 keymap) (cons #x100 (max-char))
1170 'company-search-printing-char)
1172 ;; obselete in Emacs 23
1173 (let ((l (generic-character-list))
1174 (table (nth 1 keymap)))
1176 (set-char-table-default table (car l) 'company-search-printing-char)
1177 (setq l (cdr l))))))
1178 (define-key keymap [t] 'company-search-other-char)
1180 (define-key keymap (make-string 1 i) 'company-search-other-char)
1183 (define-key keymap (vector i) 'company-search-printing-char)
1185 (let ((meta-map (make-sparse-keymap)))
1186 (define-key keymap (char-to-string meta-prefix-char) meta-map)
1187 (define-key keymap [escape] meta-map))
1188 (define-key keymap (vector meta-prefix-char t) 'company-search-other-char)
1189 (define-key keymap "\e\e\e" 'company-search-other-char)
1190 (define-key keymap [escape escape escape] 'company-search-other-char)
1192 (define-key keymap "\C-g" 'company-search-abort)
1193 (define-key keymap "\C-s" 'company-search-repeat-forward)
1194 (define-key keymap "\C-r" 'company-search-repeat-backward)
1195 (define-key keymap "\C-o" 'company-search-kill-others)
1197 "Keymap used for incrementally searching the completion candidates.")
1199 (define-minor-mode company-search-mode
1200 "Search mode for completion candidates.
1201 Don't start this directly, use `company-search-candidates' or
1202 `company-filter-candidates'."
1203 nil company-search-lighter nil
1204 (if company-search-mode
1205 (if (company-manual-begin)
1207 (setq company-search-old-selection company-selection)
1208 (company-call-frontends 'update))
1209 (setq company-search-mode nil))
1210 (kill-local-variable 'company-search-string)
1211 (kill-local-variable 'company-search-lighter)
1212 (kill-local-variable 'company-search-old-selection)
1213 (company-enable-overriding-keymap company-active-map)))
1215 (defsubst company-search-assert-enabled ()
1216 (company-assert-enabled)
1217 (unless company-search-mode
1218 (company-uninstall-map)
1219 (error "Company not in search mode")))
1221 (defun company-search-candidates ()
1222 "Start searching the completion candidates incrementally.
1224 \\<company-search-map>Search can be controlled with the commands:
1225 - `company-search-repeat-forward' (\\[company-search-repeat-forward])
1226 - `company-search-repeat-backward' (\\[company-search-repeat-backward])
1227 - `company-search-abort' (\\[company-search-abort])
1229 Regular characters are appended to the search string.
1231 The command `company-search-kill-others' (\\[company-search-kill-others]) uses
1232 the search string to limit the completion candidates."
1234 (company-search-mode 1)
1235 (company-enable-overriding-keymap company-search-map))
1237 (defvar company-filter-map
1238 (let ((keymap (make-keymap)))
1239 (define-key keymap [remap company-search-printing-char]
1240 'company-filter-printing-char)
1241 (set-keymap-parent keymap company-search-map)
1243 "Keymap used for incrementally searching the completion candidates.")
1245 (defun company-filter-candidates ()
1246 "Start filtering the completion candidates incrementally.
1247 This works the same way as `company-search-candidates' immediately
1248 followed by `company-search-kill-others' after each input."
1250 (company-search-mode 1)
1251 (company-enable-overriding-keymap company-filter-map))
1253 ;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;
1255 (defun company-select-next ()
1256 "Select the next candidate in the list."
1258 (when (company-manual-begin)
1259 (company-set-selection (1+ company-selection))))
1261 (defun company-select-previous ()
1262 "Select the previous candidate in the list."
1264 (when (company-manual-begin)
1265 (company-set-selection (1- company-selection))))
1267 (defun company-select-mouse (event)
1268 "Select the candidate picked by the mouse."
1270 (when (nth 4 (event-start event))
1271 (company-set-selection (- (cdr (posn-actual-col-row (event-start event)))
1276 (defun company-complete-mouse (event)
1277 "Complete the candidate picked by the mouse."
1279 (when (company-select-mouse event)
1280 (company-complete-selection)))
1282 (defun company-complete-selection ()
1283 "Complete the selected candidate."
1285 (when (company-manual-begin)
1286 (company-finish (nth company-selection company-candidates))))
1288 (defun company-complete-common ()
1289 "Complete the common part of all candidates."
1291 (when (company-manual-begin)
1292 (if (and (not (cdr company-candidates))
1293 (equal company-common (car company-candidates)))
1294 (company-complete-selection)
1295 (insert (company-strip-prefix company-common)))))
1297 (defun company-complete ()
1298 "Complete the common part of all candidates or the current selection.
1299 The first time this is called, the common part is completed, the second time, or
1300 when the selection has been changed, the selected candidate is completed."
1302 (when (company-manual-begin)
1303 (if (or company-selection-changed
1304 (eq last-command 'company-complete-common))
1305 (call-interactively 'company-complete-selection)
1306 (call-interactively 'company-complete-common)
1307 (setq this-command 'company-complete-common))))
1309 (defun company-complete-number (n)
1310 "Complete the Nth candidate.
1311 To show the number next to the candidates in some back-ends, enable
1312 `company-show-numbers'."
1313 (when (company-manual-begin)
1314 (and (< n 1) (> n company-candidates-length)
1315 (error "No candidate number %d" n))
1317 (company-finish (nth n company-candidates))))
1319 ;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;
1321 (defconst company-space-strings-limit 100)
1323 (defconst company-space-strings
1325 (dotimes (i company-space-strings-limit)
1326 (push (make-string (- company-space-strings-limit 1 i) ?\ ) lst))
1327 (apply 'vector lst)))
1329 (defsubst company-space-string (len)
1330 (if (< len company-space-strings-limit)
1331 (aref company-space-strings len)
1332 (make-string len ?\ )))
1334 (defsubst company-safe-substring (str from &optional to)
1335 (let ((len (length str)))
1338 (if (and to (> to len))
1339 (concat (substring str from)
1340 (company-space-string (- to len)))
1341 (substring str from to)))))
1343 ;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;
1345 (defvar company-last-metadata nil)
1346 (make-variable-buffer-local 'company-last-metadata)
1348 (defun company-fetch-metadata ()
1349 (let ((selected (nth company-selection company-candidates)))
1350 (unless (equal selected (car company-last-metadata))
1351 (setq company-last-metadata
1352 (cons selected (company-call-backend 'meta selected))))
1353 (cdr company-last-metadata)))
1355 (defun company-doc-buffer (&optional string)
1356 (with-current-buffer (get-buffer-create "*Company meta-data*")
1360 (defmacro company-electric (&rest body)
1361 (declare (indent 0) (debug t))
1362 `(when (company-manual-begin)
1363 (save-window-excursion
1364 (let ((height (window-height))
1365 (row (company--row)))
1367 (and (< (window-height) height)
1368 (< (- (window-height) row 2) company-tooltip-limit)
1369 (recenter (- (window-height) row 2)))
1370 (while (eq 'scroll-other-window
1371 (key-binding (vector (list (read-event)))))
1372 (call-interactively 'scroll-other-window))
1373 (when last-input-event
1374 (clear-this-command-keys t)
1375 (setq unread-command-events (list last-input-event)))))))
1377 (defun company-show-doc-buffer ()
1378 "Temporarily show a buffer with the complete documentation for the selection."
1381 (let ((selected (nth company-selection company-candidates)))
1382 (display-buffer (or (company-call-backend 'doc-buffer selected)
1383 (error "No documentation available")) t))))
1384 (put 'company-show-doc-buffer 'company-keep t)
1386 (defun company-show-location ()
1387 "Temporarily display a buffer showing the selected candidate in context."
1390 (let* ((selected (nth company-selection company-candidates))
1391 (location (company-call-backend 'location selected))
1392 (pos (or (cdr location) (error "No location available")))
1393 (buffer (or (and (bufferp (car location)) (car location))
1394 (find-file-noselect (car location) t))))
1395 (with-selected-window (display-buffer buffer t)
1396 (if (bufferp (car location))
1399 (set-window-start nil (point))))))
1400 (put 'company-show-location 'company-keep t)
1402 ;;; package functions ;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;
1404 (defvar company-callback nil)
1405 (make-variable-buffer-local 'company-callback)
1407 (defvar company-begin-with-marker nil)
1408 (make-variable-buffer-local 'company-begin-with-marker)
1410 (defun company-remove-callback (&optional ignored)
1411 (remove-hook 'company-completion-finished-hook company-callback t)
1412 (remove-hook 'company-completion-cancelled-hook 'company-remove-callback t)
1413 (remove-hook 'company-completion-finished-hook 'company-remove-callback t)
1414 (set-marker company-begin-with-marker nil))
1416 (defun company-begin-backend (backend &optional callback)
1417 "Start a completion at point using BACKEND."
1418 (interactive (let ((val (completing-read "Company back-end: "
1420 'functionp nil "company-")))
1422 (list (intern val)))))
1423 (when (setq company-callback callback)
1424 (add-hook 'company-completion-finished-hook company-callback nil t))
1425 (add-hook 'company-completion-cancelled-hook 'company-remove-callback nil t)
1426 (add-hook 'company-completion-finished-hook 'company-remove-callback nil t)
1427 (setq company-backend backend)
1428 ;; Return non-nil if active.
1429 (or (company-manual-begin)
1430 (error "Cannot complete at point")))
1432 (defun company-begin-with (candidates
1433 &optional prefix-length require-match callback)
1434 "Start a completion at point.
1435 CANDIDATES is the list of candidates to use and PREFIX-LENGTH is the length of
1436 the prefix that already is in the buffer before point. It defaults to 0.
1438 CALLBACK is a function called with the selected result if the user successfully
1439 completes the input.
1442 \(company-begin-with '\(\"foo\" \"foobar\" \"foobarbaz\"\)\)"
1443 (setq company-begin-with-marker (copy-marker (point) t))
1444 (company-begin-backend
1445 `(lambda (command &optional arg &rest ignored)
1447 ((eq command 'prefix)
1448 (when (equal (point) (marker-position company-begin-with-marker))
1449 (buffer-substring ,(- (point) (or prefix-length 0)) (point))))
1450 ((eq command 'candidates)
1451 (all-completions arg ',candidates))
1452 ((eq command 'require-match)
1456 ;;; pseudo-tooltip ;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;
1458 (defvar company-pseudo-tooltip-overlay nil)
1459 (make-variable-buffer-local 'company-pseudo-tooltip-overlay)
1461 (defvar company-tooltip-offset 0)
1462 (make-variable-buffer-local 'company-tooltip-offset)
1464 (defun company-pseudo-tooltip-update-offset (selection num-lines limit)
1467 (setq company-tooltip-offset
1468 (max (min selection company-tooltip-offset)
1469 (- selection -1 limit)))
1471 (when (<= company-tooltip-offset 1)
1473 (setq company-tooltip-offset 0))
1475 (when (>= company-tooltip-offset (- num-lines limit 1))
1477 (when (= selection (1- num-lines))
1478 (decf company-tooltip-offset)
1479 (when (<= company-tooltip-offset 1)
1480 (setq company-tooltip-offset 0)
1487 (defsubst company-round-tab (arg)
1488 (* (/ (+ arg tab-width) tab-width) tab-width))
1490 (defun company-untabify (str)
1491 (let* ((pieces (split-string str "\t"))
1494 (setcar copy (company-safe-substring
1495 (car copy) 0 (company-round-tab (string-width (car copy)))))
1497 (apply 'concat pieces)))
1499 (defun company-fill-propertize (line width selected)
1500 (setq line (company-safe-substring line 0 width))
1501 (add-text-properties 0 width '(face company-tooltip
1502 mouse-face company-tooltip-mouse)
1504 (add-text-properties 0 (length company-common)
1505 '(face company-tooltip-common
1506 mouse-face company-tooltip-mouse)
1509 (if (and company-search-string
1510 (string-match (regexp-quote company-search-string) line
1511 (length company-prefix)))
1513 (add-text-properties (match-beginning 0) (match-end 0)
1514 '(face company-tooltip-selection)
1516 (when (< (match-beginning 0) (length company-common))
1517 (add-text-properties (match-beginning 0) (length company-common)
1518 '(face company-tooltip-common-selection)
1520 (add-text-properties 0 width '(face company-tooltip-selection
1521 mouse-face company-tooltip-selection)
1523 (add-text-properties 0 (length company-common)
1524 '(face company-tooltip-common-selection
1525 mouse-face company-tooltip-selection)
1531 (defun company-buffer-lines (beg end)
1533 (let ((row (company--row))
1535 (while (and (equal (move-to-window-line (incf row)) row)
1537 (push (buffer-substring beg (min end (1- (point)))) lines)
1539 (unless (eq beg end)
1540 (push (buffer-substring beg end) lines))
1543 (defsubst company-modify-line (old new offset)
1544 (concat (company-safe-substring old 0 offset)
1546 (company-safe-substring old (+ offset (length new)))))
1548 (defsubst company--length-limit (lst limit)
1549 (if (nthcdr limit lst)
1553 (defun company--replacement-string (lines old column nl &optional align-top)
1555 (let ((width (length (car lines))))
1556 (when (> width (- (window-width) column))
1557 (setq column (max 0 (- (window-width) width)))))
1561 ;; untouched lines first
1562 (dotimes (i (- (length old) (length lines)))
1563 (push (pop old) new)))
1564 ;; length into old lines.
1566 (push (company-modify-line (pop old) (pop lines) column) new))
1567 ;; Append whole new lines.
1569 (push (concat (company-space-string column) (pop lines)) new))
1570 (concat (when nl "\n")
1571 (mapconcat 'identity (nreverse new) "\n")
1574 (defun company--create-lines (selection limit)
1576 (let ((len company-candidates-length)
1585 ;; Scroll to offset.
1586 (setq limit (company-pseudo-tooltip-update-offset selection len limit))
1588 (when (> company-tooltip-offset 0)
1589 (setq previous (format "...(%d)" company-tooltip-offset)))
1591 (setq remainder (- len limit company-tooltip-offset)
1592 remainder (when (> remainder 0)
1593 (setq remainder (format "...(%d)" remainder))))
1595 (decf selection company-tooltip-offset)
1596 (setq width (max (length previous) (length remainder))
1597 lines (nthcdr company-tooltip-offset company-candidates)
1602 (setq width (max (length (pop lines-copy)) width)))
1603 (setq width (min width (window-width)))
1605 (setq lines-copy lines)
1607 ;; number can make tooltip too long
1608 (when company-show-numbers
1609 (setq numbered company-tooltip-offset))
1612 (push (propertize (company-safe-substring previous 0 width)
1613 'face 'company-tooltip)
1617 (push (company-fill-propertize
1618 (if (>= numbered 10)
1619 (company-reformat (pop lines))
1622 (company-safe-substring (company-reformat (pop lines))
1625 width (equal i selection))
1629 (push (propertize (company-safe-substring remainder 0 width)
1630 'face 'company-tooltip)
1633 (setq lines (nreverse new))))
1637 (defsubst company--pseudo-tooltip-height ()
1638 "Calculate the appropriate tooltip height.
1639 Returns a negative number if the tooltip should be displayed above point."
1640 (let* ((lines (1- (count-lines (window-start) (point-at-bol))))
1641 (below (- (window-height) 3 lines)))
1642 (if (and (< below (min company-tooltip-minimum company-candidates-length))
1644 (- (max 3 (min company-tooltip-limit lines)))
1645 (max 3 (min company-tooltip-limit below)))))
1647 (defun company-pseudo-tooltip-show (row column selection)
1648 (company-pseudo-tooltip-hide)
1653 (let* ((height (company--pseudo-tooltip-height))
1657 (setq row (+ row height -1)
1660 (let* ((nl (< (move-to-window-line row) row))
1662 (end (save-excursion
1663 (move-to-window-line (+ row (abs height)))
1665 (ov (make-overlay beg end))
1666 (args (list (mapcar 'company-untabify
1667 (company-buffer-lines beg end))
1670 (setq company-pseudo-tooltip-overlay ov)
1671 (overlay-put ov 'company-replacement-args args)
1672 (overlay-put ov 'company-before
1673 (apply 'company--replacement-string
1674 (company--create-lines selection (abs height))
1677 (overlay-put ov 'company-column column)
1678 (overlay-put ov 'company-height (abs height))
1679 (overlay-put ov 'window (selected-window))))))
1681 (defun company-pseudo-tooltip-show-at-point (pos)
1682 (let ((col-row (company--col-row pos)))
1684 (company-pseudo-tooltip-show (1+ (cdr col-row)) (car col-row)
1685 company-selection))))
1687 (defun company-pseudo-tooltip-edit (lines selection)
1688 (let ((column (overlay-get company-pseudo-tooltip-overlay 'company-column))
1689 (height (overlay-get company-pseudo-tooltip-overlay 'company-height)))
1690 (overlay-put company-pseudo-tooltip-overlay 'company-before
1691 (apply 'company--replacement-string
1692 (company--create-lines selection height)
1693 (overlay-get company-pseudo-tooltip-overlay
1694 'company-replacement-args)))))
1696 (defun company-pseudo-tooltip-hide ()
1697 (when company-pseudo-tooltip-overlay
1698 (delete-overlay company-pseudo-tooltip-overlay)
1699 (setq company-pseudo-tooltip-overlay nil)))
1701 (defun company-pseudo-tooltip-hide-temporarily ()
1702 (when (overlayp company-pseudo-tooltip-overlay)
1703 (overlay-put company-pseudo-tooltip-overlay 'invisible nil)
1704 (overlay-put company-pseudo-tooltip-overlay 'before-string nil)))
1706 (defun company-pseudo-tooltip-unhide ()
1707 (when company-pseudo-tooltip-overlay
1708 (overlay-put company-pseudo-tooltip-overlay 'invisible t)
1709 (overlay-put company-pseudo-tooltip-overlay 'before-string
1710 (overlay-get company-pseudo-tooltip-overlay 'company-before))
1711 (overlay-put company-pseudo-tooltip-overlay 'window (selected-window))))
1713 (defun company-pseudo-tooltip-frontend (command)
1714 "A `company-mode' front-end similar to a tool-tip but based on overlays."
1716 ('pre-command (company-pseudo-tooltip-hide-temporarily))
1718 (let ((old-height (if (overlayp company-pseudo-tooltip-overlay)
1719 (overlay-get company-pseudo-tooltip-overlay
1722 (new-height (company--pseudo-tooltip-height)))
1723 (unless (and (>= (* old-height new-height) 0)
1724 (>= (abs old-height) (abs new-height)))
1726 (company-pseudo-tooltip-show-at-point (- (point)
1727 (length company-prefix)))))
1728 (company-pseudo-tooltip-unhide))
1729 ('hide (company-pseudo-tooltip-hide)
1730 (setq company-tooltip-offset 0))
1731 ('update (when (overlayp company-pseudo-tooltip-overlay)
1732 (company-pseudo-tooltip-edit company-candidates
1733 company-selection)))))
1735 (defun company-pseudo-tooltip-unless-just-one-frontend (command)
1736 "`company-pseudo-tooltip-frontend', but not shown for single candidates."
1737 (unless (and (eq command 'post-command)
1738 (not (cdr company-candidates)))
1739 (company-pseudo-tooltip-frontend command)))
1741 ;;; overlay ;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;
1743 (defvar company-preview-overlay nil)
1744 (make-variable-buffer-local 'company-preview-overlay)
1746 (defun company-preview-show-at-point (pos)
1747 (company-preview-hide)
1749 (setq company-preview-overlay (make-overlay pos pos))
1751 (let ((completion(nth company-selection company-candidates)))
1752 (setq completion (propertize completion 'face 'company-preview))
1753 (add-text-properties 0 (length company-common)
1754 '(face company-preview-common) completion)
1756 ;; Add search string
1757 (and company-search-string
1758 (string-match (regexp-quote company-search-string) completion)
1759 (add-text-properties (match-beginning 0)
1761 '(face company-preview-search)
1764 (setq completion (company-strip-prefix completion))
1766 (and (equal pos (point))
1767 (not (equal completion ""))
1768 (add-text-properties 0 1 '(cursor t) completion))
1770 (overlay-put company-preview-overlay 'after-string completion)
1771 (overlay-put company-preview-overlay 'window (selected-window))))
1773 (defun company-preview-hide ()
1774 (when company-preview-overlay
1775 (delete-overlay company-preview-overlay)
1776 (setq company-preview-overlay nil)))
1778 (defun company-preview-frontend (command)
1779 "A `company-mode' front-end showing the selection as if it had been inserted."
1781 ('pre-command (company-preview-hide))
1782 ('post-command (company-preview-show-at-point (point)))
1783 ('hide (company-preview-hide))))
1785 (defun company-preview-if-just-one-frontend (command)
1786 "`company-preview-frontend', but only shown for single candidates."
1787 (unless (and (eq command 'post-command)
1788 (cdr company-candidates))
1789 (company-preview-frontend command)))
1791 ;;; echo ;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;
1793 (defvar company-echo-last-msg nil)
1794 (make-variable-buffer-local 'company-echo-last-msg)
1796 (defvar company-echo-timer nil)
1798 (defvar company-echo-delay .1)
1800 (defun company-echo-show (&optional getter)
1802 (setq company-echo-last-msg (funcall getter)))
1803 (let ((message-log-max nil))
1804 (if company-echo-last-msg
1805 (message "%s" company-echo-last-msg)
1808 (defsubst company-echo-show-soon (&optional getter)
1809 (when company-echo-timer
1810 (cancel-timer company-echo-timer))
1811 (setq company-echo-timer (run-with-timer company-echo-delay nil
1812 'company-echo-show getter)))
1814 (defun company-echo-format ()
1816 (let ((limit (window-width (minibuffer-window)))
1818 ;; Roll to selection.
1819 (candidates (nthcdr company-selection company-candidates))
1820 (i (if company-show-numbers company-selection 99999))
1824 (setq comp (company-reformat (pop candidates))
1825 len (+ len 1 (length comp)))
1829 (setq comp (propertize (format "%d: %s" i comp)
1830 'face 'company-echo))
1833 (add-text-properties 3 (+ 3 (length company-common))
1834 '(face company-echo-common) comp))
1835 (setq comp (propertize comp 'face 'company-echo))
1836 (add-text-properties 0 (length company-common)
1837 '(face company-echo-common) comp))
1839 (setq candidates nil)
1842 (mapconcat 'identity (nreverse msg) " ")))
1844 (defun company-echo-strip-common-format ()
1846 (let ((limit (window-width (minibuffer-window)))
1847 (len (+ (length company-prefix) 2))
1848 ;; Roll to selection.
1849 (candidates (nthcdr company-selection company-candidates))
1850 (i (if company-show-numbers company-selection 99999))
1854 (setq comp (company-strip-prefix (pop candidates))
1855 len (+ len 2 (length comp)))
1858 (setq comp (format "%s (%d)" comp i))
1862 (setq candidates nil)
1863 (push (propertize comp 'face 'company-echo) msg)))
1865 (concat (propertize company-prefix 'face 'company-echo-common) "{"
1866 (mapconcat 'identity (nreverse msg) ", ")
1869 (defun company-echo-hide ()
1870 (when company-echo-timer
1871 (cancel-timer company-echo-timer))
1872 (unless (equal company-echo-last-msg "")
1873 (setq company-echo-last-msg "")
1874 (company-echo-show)))
1876 (defun company-echo-frontend (command)
1877 "A `company-mode' front-end showing the candidates in the echo area."
1879 ('pre-command (company-echo-show-soon))
1880 ('post-command (company-echo-show-soon 'company-echo-format))
1881 ('hide (company-echo-hide))))
1883 (defun company-echo-strip-common-frontend (command)
1884 "A `company-mode' front-end showing the candidates in the echo area."
1886 ('pre-command (company-echo-show-soon))
1887 ('post-command (company-echo-show-soon 'company-echo-strip-common-format))
1888 ('hide (company-echo-hide))))
1890 (defun company-echo-metadata-frontend (command)
1891 "A `company-mode' front-end showing the documentation in the echo area."
1893 ('pre-command (company-echo-show-soon))
1894 ('post-command (company-echo-show-soon 'company-fetch-metadata))
1895 ('hide (company-echo-hide))))
1898 ;;; company.el ends here