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-code results (to emulate local variables):
58 ;; To do this, add a list with the merged back-ends as an element in
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 ;; The semantic back-end now shows meta information for local symbols.
69 ;; Added compatibility for CEDET in Emacs 23.2.
72 ;; Added `company-other-backend'.
73 ;; Idle completion no longer interrupts multi-key command input.
74 ;; Added `company-ropemacs' and `company-pysmell' back-ends.
77 ;; In C modes . and -> now count towards `company-minimum-prefix-length'.
78 ;; Reverted default front-end back to `company-preview-if-just-one-frontend'.
79 ;; The pseudo tooltip will no longer be clipped at the right window edge.
80 ;; Added `company-tooltip-minimum'.
81 ;; Windows compatibility fixes.
84 ;; Added `global-company-mode'.
85 ;; Performance enhancements.
86 ;; Added `company-eclim' back-end.
87 ;; Added safer workaround for Emacs `posn-col-row' bug.
90 ;; Automatic completion is now aborted if the prefix gets too short.
91 ;; Added option `company-dabbrev-time-limit'.
92 ;; `company-backends' now supports merging back-ends.
93 ;; Added back-end `company-dabbrev-code' for generic code.
94 ;; Fixed `company-begin-with'.
97 ;; Added 'stop prefix to prevent dabbrev from completing inside of symbols.
98 ;; Fixed issues with tabbar-mode and line-spacing.
99 ;; Performance enhancements.
102 ;; Added `company-begin-commands' option.
103 ;; Added abbrev, tempo and Xcode back-ends.
104 ;; Back-ends are now interactive. You can start them with M-x backend-name.
105 ;; Added `company-begin-with' for starting company from elisp-code.
107 ;; Added `company-require-match' and `company-auto-complete' options.
109 ;; 2009-04-05 (0.2.1)
110 ;; Improved Emacs Lisp back-end behavior for local variables.
111 ;; Added `company-elisp-detect-function-context' option.
112 ;; The mouse can now be used for selection.
115 ;; Added `company-show-location'.
116 ;; Added etags back-end.
117 ;; Added work-around for end-of-buffer bug.
118 ;; Added `company-filter-candidates'.
119 ;; More local Lisp variables are now included in the candidates.
121 ;; 2009-03-21 (0.1.5)
122 ;; Fixed elisp documentation buffer always showing the same doc.
123 ;; Added `company-echo-strip-common-frontend'.
124 ;; Added `company-show-numbers' option and M-0 ... M-9 default bindings.
125 ;; Don't hide the echo message if it isn't shown.
132 (eval-when-compile (require 'cl))
134 (add-to-list 'debug-ignored-errors "^.* frontend cannot be used twice$")
135 (add-to-list 'debug-ignored-errors "^Echo area cannot be used twice$")
136 (add-to-list 'debug-ignored-errors "^No \\(document\\|loc\\)ation available$")
137 (add-to-list 'debug-ignored-errors "^Company not ")
138 (add-to-list 'debug-ignored-errors "^No candidate number ")
139 (add-to-list 'debug-ignored-errors "^Cannot complete at point$")
140 (add-to-list 'debug-ignored-errors "^No other back-end$")
142 (defgroup company nil
143 "Extensible inline text completion mechanism"
148 (defface company-tooltip
149 '((t :background "yellow"
150 :foreground "black"))
151 "*Face used for the tool tip."
154 (defface company-tooltip-selection
155 '((default :inherit company-tooltip)
156 (((class color) (min-colors 88)) (:background "orange1"))
157 (t (:background "green")))
158 "*Face used for the selection in the tool tip."
161 (defface company-tooltip-mouse
162 '((default :inherit highlight))
163 "*Face used for the tool tip item under the mouse."
166 (defface company-tooltip-common
167 '((t :inherit company-tooltip
169 "*Face used for the common completion in the tool tip."
172 (defface company-tooltip-common-selection
173 '((t :inherit company-tooltip-selection
175 "*Face used for the selected common completion in the tool tip."
178 (defface company-preview
179 '((t :background "blue4"
180 :foreground "wheat"))
181 "*Face used for the completion preview."
184 (defface company-preview-common
185 '((t :inherit company-preview
187 "*Face used for the common part of the completion preview."
190 (defface company-preview-search
191 '((t :inherit company-preview
192 :background "blue1"))
193 "*Face used for the search string in the completion preview."
196 (defface company-echo nil
197 "*Face used for completions in the echo area."
200 (defface company-echo-common
201 '((((background dark)) (:foreground "firebrick1"))
202 (((background light)) (:background "firebrick4")))
203 "*Face used for the common part of completions in the echo area."
206 (defun company-frontends-set (variable value)
208 (let ((remainder value))
209 (setcdr remainder (delq (car remainder) (cdr remainder))))
210 (and (memq 'company-pseudo-tooltip-unless-just-one-frontend value)
211 (memq 'company-pseudo-tooltip-frontend value)
212 (error "Pseudo tooltip frontend cannot be used twice"))
213 (and (memq 'company-preview-if-just-one-frontend value)
214 (memq 'company-preview-frontend value)
215 (error "Preview frontend cannot be used twice"))
216 (and (memq 'company-echo value)
217 (memq 'company-echo-metadata-frontend value)
218 (error "Echo area cannot be used twice"))
219 ;; preview must come last
220 (dolist (f '(company-preview-if-just-one-frontend company-preview-frontend))
222 (setq value (append (delq f value) (list f)))))
223 (set variable value))
225 (defcustom company-frontends '(company-pseudo-tooltip-unless-just-one-frontend
226 company-preview-if-just-one-frontend
227 company-echo-metadata-frontend)
228 "*The list of active front-ends (visualizations).
229 Each front-end is a function that takes one argument. It is called with
230 one of the following arguments:
232 'show: When the visualization should start.
234 'hide: When the visualization should end.
236 'update: When the data has been updated.
238 'pre-command: Before every command that is executed while the
239 visualization is active.
241 'post-command: After every command that is executed while the
242 visualization is active.
244 The visualized data is stored in `company-prefix', `company-candidates',
245 `company-common', `company-selection', `company-point' and
246 `company-search-string'."
247 :set 'company-frontends-set
249 :type '(repeat (choice (const :tag "echo" company-echo-frontend)
250 (const :tag "echo, strip common"
251 company-echo-strip-common-frontend)
252 (const :tag "show echo meta-data in echo"
253 company-echo-metadata-frontend)
254 (const :tag "pseudo tooltip"
255 company-pseudo-tooltip-frontend)
256 (const :tag "pseudo tooltip, multiple only"
257 company-pseudo-tooltip-unless-just-one-frontend)
258 (const :tag "preview" company-preview-frontend)
259 (const :tag "preview, unique only"
260 company-preview-if-just-one-frontend)
261 (function :tag "custom function" nil))))
263 (defcustom company-tooltip-limit 10
264 "*The maximum number of candidates in the tool tip"
268 (defcustom company-tooltip-minimum 6
269 "*The minimum height of the tool tip.
270 If this many lines are not available, prefer to display the tooltip above."
274 (defvar company-safe-backends
275 '((company-abbrev . "Abbrev")
276 (company-css . "CSS")
277 (company-dabbrev . "dabbrev for plain text")
278 (company-dabbrev-code . "dabbrev for code")
279 (company-eclim . "eclim (an Eclipse interace)")
280 (company-elisp . "Emacs Lisp")
281 (company-etags . "etags")
282 (company-files . "Files")
283 (company-gtags . "GNU Global")
284 (company-ispell . "ispell")
285 (company-keywords . "Programming language keywords")
286 (company-nxml . "nxml")
287 (company-oddmuse . "Oddmuse")
288 (company-pysmell . "PySmell")
289 (company-ropemacs . "ropemacs")
290 (company-semantic . "CEDET Semantic")
291 (company-tempo . "Tempo templates")
292 (company-xcode . "Xcode")))
293 (put 'company-safe-backends 'risky-local-variable t)
295 (defun company-safe-backends-p (backends)
296 (and (consp backends)
297 (not (dolist (backend backends)
298 (unless (if (consp backend)
299 (company-safe-backends-p backend)
300 (assq backend company-safe-backends))
303 (defcustom company-backends '(company-elisp company-nxml company-css
304 company-eclim company-semantic company-xcode
306 (company-gtags company-etags company-dabbrev-code
307 company-pysmell company-keywords)
308 company-oddmuse company-files company-dabbrev)
309 "*The list of active back-ends (completion engines).
310 Each list elements can itself be a list of back-ends. In that case their
311 completions are merged. Otherwise only the first matching back-end returns
314 `company-begin-backend' can be used to start a specific back-end,
315 `company-other-backend' will skip to the next matching back-end in the list.
317 Each back-end is a function that takes a variable number of arguments.
318 The first argument is the command requested from the back-end. It is one
321 'prefix: The back-end should return the text to be completed. It must be
322 text immediately before `point'. Returning nil passes control to the next
323 back-end. The function should return 'stop if it should complete but cannot
324 \(e.g. if it is in the middle of a string\). If the returned value is only
325 part of the prefix (e.g. the part after \"->\" in C), the back-end may return a
326 cons of prefix and prefix length, which is then used in the
327 `company-minimum-prefix-length' test.
329 'candidates: The second argument is the prefix to be completed. The
330 return value should be a list of candidates that start with the prefix.
334 'sorted: The back-end may return t here to indicate that the candidates
335 are sorted and will not need to be sorted again.
337 'duplicates: If non-nil, company will take care of removing duplicates
340 'no-cache: Usually company doesn't ask for candidates again as completion
341 progresses, unless the back-end returns t for this command. The second
342 argument is the latest prefix.
344 'meta: The second argument is a completion candidate. The back-end should
345 return a (short) documentation string for it.
347 'doc-buffer: The second argument is a completion candidate. The back-end should
348 create a buffer (preferably with `company-doc-buffer'), fill it with
349 documentation and return it.
351 'location: The second argument is a completion candidate. The back-end can
352 return the cons of buffer and buffer location, or of file and line
353 number where the completion candidate was defined.
355 'require-match: If this value is t, the user is not allowed to enter anything
356 not offering as a candidate. Use with care! The default value nil gives the
357 user that choice with `company-require-match'. Return value 'never overrides
358 that option the other way around.
360 The back-end should return nil for all commands it does not support or
361 does not know about. It should also be callable interactively and use
362 `company-begin-backend' to start itself in that case."
367 ,@(mapcar (lambda (b) `(const :tag ,(cdr b) ,(car b)))
368 company-safe-backends)
369 (symbol :tag "User defined")
370 (repeat :tag "Merged Back-ends"
371 (choice :tag "Back-end"
372 ,@(mapcar (lambda (b)
373 `(const :tag ,(cdr b) ,(car b)))
374 company-safe-backends)
375 (symbol :tag "User defined"))))))
377 (put 'company-backends 'safe-local-variable 'company-safe-backends-p)
379 (defcustom company-completion-started-hook nil
380 "*Hook run when company starts completing.
381 The hook is called with one argument that is non-nil if the completion was
386 (defcustom company-completion-cancelled-hook nil
387 "*Hook run when company cancels completing.
388 The hook is called with one argument that is non-nil if the completion was
393 (defcustom company-completion-finished-hook nil
394 "*Hook run when company successfully completes.
395 The hook is called with the selected candidate as an argument."
399 (defcustom company-minimum-prefix-length 3
400 "*The minimum prefix length for automatic completion."
402 :type '(integer :tag "prefix length"))
404 (defcustom company-require-match 'company-explicit-action-p
405 "*If enabled, disallow non-matching input.
406 This can be a function do determine if a match is required.
408 This can be overridden by the back-end, if it returns t or 'never to
409 'require-match. `company-auto-complete' also takes precedence over this."
411 :type '(choice (const :tag "Off" nil)
412 (function :tag "Predicate function")
413 (const :tag "On, if user interaction took place"
414 'company-explicit-action-p)
415 (const :tag "On" t)))
417 (defcustom company-auto-complete 'company-explicit-action-p
418 "Determines when to auto-complete.
419 If this is enabled, all characters from `company-auto-complete-chars' complete
420 the selected completion. This can also be a function."
422 :type '(choice (const :tag "Off" nil)
423 (function :tag "Predicate function")
424 (const :tag "On, if user interaction took place"
425 'company-explicit-action-p)
426 (const :tag "On" t)))
428 (defcustom company-auto-complete-chars '(?\ ?\( ?\) ?. ?\" ?$ ?\' ?< ?| ?!)
429 "Determines which characters trigger an automatic completion.
430 See `company-auto-complete'. If this is a string, each string character causes
431 completion. If it is a list of syntax description characters (see
432 `modify-syntax-entry'), all characters with that syntax auto-complete.
434 This can also be a function, which is called with the new input and should
435 return non-nil if company should auto-complete.
437 A character that is part of a valid candidate never starts auto-completion."
439 :type '(choice (string :tag "Characters")
441 (const :tag "Whitespace" ?\ )
442 (const :tag "Symbol" ?_)
443 (const :tag "Opening parentheses" ?\()
444 (const :tag "Closing parentheses" ?\))
445 (const :tag "Word constituent" ?w)
446 (const :tag "Punctuation." ?.)
447 (const :tag "String quote." ?\")
448 (const :tag "Paired delimiter." ?$)
449 (const :tag "Expression quote or prefix operator." ?\')
450 (const :tag "Comment starter." ?<)
451 (const :tag "Comment ender." ?>)
452 (const :tag "Character-quote." ?/)
453 (const :tag "Generic string fence." ?|)
454 (const :tag "Generic comment fence." ?!))
455 (function :tag "Predicate function")))
457 (defcustom company-idle-delay .7
458 "*The idle delay in seconds until automatic completions starts.
459 A value of nil means never complete automatically, t means complete
460 immediately when a prefix of `company-minimum-prefix-length' is reached."
462 :type '(choice (const :tag "never (nil)" nil)
463 (const :tag "immediate (t)" t)
464 (number :tag "seconds")))
466 (defcustom company-begin-commands t
467 "*A list of commands following which company will start completing.
468 If this is t, it will complete after any command. See `company-idle-delay'.
470 Alternatively any command with a non-nil 'company-begin property is treated as
471 if it was on this list."
473 :type '(choice (const :tag "Any command" t)
474 (const :tag "Self insert command" '(self-insert-command))
475 (repeat :tag "Commands" function)))
477 (defcustom company-show-numbers nil
478 "*If enabled, show quick-access numbers for the first ten candidates."
480 :type '(choice (const :tag "off" nil)
481 (const :tag "on" t)))
483 (defvar company-end-of-buffer-workaround t
484 "*Work around a visualization bug when completing at the end of the buffer.
485 The work-around consists of adding a newline.")
487 ;;; mode ;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;
489 (defvar company-mode-map (make-sparse-keymap)
490 "Keymap used by `company-mode'.")
492 (defvar company-active-map
493 (let ((keymap (make-sparse-keymap)))
494 (define-key keymap "\e\e\e" 'company-abort)
495 (define-key keymap "\C-g" 'company-abort)
496 (define-key keymap (kbd "M-n") 'company-select-next)
497 (define-key keymap (kbd "M-p") 'company-select-previous)
498 (define-key keymap (kbd "<down>") 'company-select-next)
499 (define-key keymap (kbd "<up>") 'company-select-previous)
500 (define-key keymap [down-mouse-1] 'ignore)
501 (define-key keymap [down-mouse-3] 'ignore)
502 (define-key keymap [mouse-1] 'company-complete-mouse)
503 (define-key keymap [mouse-3] 'company-select-mouse)
504 (define-key keymap [up-mouse-1] 'ignore)
505 (define-key keymap [up-mouse-3] 'ignore)
506 (define-key keymap "\C-m" 'company-complete-selection)
507 (define-key keymap "\t" 'company-complete-common)
508 (define-key keymap (kbd "<f1>") 'company-show-doc-buffer)
509 (define-key keymap "\C-w" 'company-show-location)
510 (define-key keymap "\C-s" 'company-search-candidates)
511 (define-key keymap "\C-\M-s" 'company-filter-candidates)
513 (define-key keymap (vector (+ (aref (kbd "M-0") 0) i))
514 `(lambda () (interactive) (company-complete-number ,i))))
517 "Keymap that is enabled during an active completion.")
519 (defvar company--disabled-backends nil)
521 (defun company-init-backend (backend)
522 (and (symbolp backend)
523 (not (fboundp backend))
524 (ignore-errors (require backend nil t)))
526 (if (or (symbolp backend)
528 (if (ignore-errors (funcall backend 'init) t)
529 (put backend 'company-init t)
530 (put backend 'company-init 'failed)
531 (unless (memq backend company--disabled-backends)
532 (message "Company back-end '%s' could not be initialized"
534 (push backend company--disabled-backends))
536 (mapc 'company-init-backend backend)))
538 (defvar company-default-lighter " company")
540 (defvar company-lighter company-default-lighter)
541 (make-variable-buffer-local 'company-lighter)
544 (define-minor-mode company-mode
545 "\"complete anything\"; in in-buffer completion framework.
546 Completion starts automatically, depending on the values
547 `company-idle-delay' and `company-minimum-prefix-length'.
549 Completion can be controlled with the commands:
550 `company-complete-common', `company-complete-selection', `company-complete',
551 `company-select-next', `company-select-previous'. If these commands are
552 called before `company-idle-delay', completion will also start.
554 Completions can be searched with `company-search-candidates' or
555 `company-filter-candidates'. These can be used while completion is
558 The completion data is retrieved using `company-backends' and displayed using
559 `company-frontends'. If you want to start a specific back-end, call it
560 interactively or use `company-begin-backend'.
562 regular keymap (`company-mode-map'):
565 keymap during active completions (`company-active-map'):
567 \\{company-active-map}"
568 nil company-lighter company-mode-map
571 (add-hook 'pre-command-hook 'company-pre-command nil t)
572 (add-hook 'post-command-hook 'company-post-command nil t)
573 (mapc 'company-init-backend company-backends))
574 (remove-hook 'pre-command-hook 'company-pre-command t)
575 (remove-hook 'post-command-hook 'company-post-command t)
577 (kill-local-variable 'company-point)))
579 (define-globalized-minor-mode global-company-mode company-mode
580 (lambda () (company-mode 1)))
582 (defsubst company-assert-enabled ()
584 (company-uninstall-map)
585 (error "Company not enabled")))
587 ;;; keymaps ;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;
589 (defvar company-overriding-keymap-bound nil)
590 (make-variable-buffer-local 'company-overriding-keymap-bound)
592 (defvar company-old-keymap nil)
593 (make-variable-buffer-local 'company-old-keymap)
595 (defvar company-my-keymap nil)
596 (make-variable-buffer-local 'company-my-keymap)
598 (defsubst company-enable-overriding-keymap (keymap)
599 (setq company-my-keymap keymap)
600 (when company-overriding-keymap-bound
601 (company-uninstall-map)))
603 (defun company-install-map ()
604 (unless (or company-overriding-keymap-bound
605 (null company-my-keymap))
606 (setq company-old-keymap overriding-terminal-local-map
607 overriding-terminal-local-map company-my-keymap
608 company-overriding-keymap-bound t)))
610 (defun company-uninstall-map ()
611 (when (eq overriding-terminal-local-map company-my-keymap)
612 (setq overriding-terminal-local-map company-old-keymap
613 company-overriding-keymap-bound nil)))
616 ;; Emacs calculates the active keymaps before reading the event. That means we
617 ;; cannot change the keymap from a timer. So we send a bogus command.
618 (defun company-ignore ()
620 (setq this-command last-command))
622 (global-set-key '[31415926] 'company-ignore)
624 (defun company-input-noop ()
625 (push 31415926 unread-command-events))
628 ;; posn-col-row is incorrect in older Emacsen when line-spacing is set
629 (defun company--col-row (&optional pos)
630 (let ((posn (posn-at-point pos)))
631 (cons (car (posn-col-row posn)) (cdr (posn-actual-col-row posn)))))
633 (defsubst company--column (&optional pos)
634 (car (posn-col-row (posn-at-point pos))))
636 (defsubst company--row (&optional pos)
637 (cdr (posn-actual-col-row (posn-at-point pos))))
639 ;;; backends ;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;
641 (defun company-grab (regexp &optional expression limit)
642 (when (looking-back regexp limit)
643 (or (match-string-no-properties (or expression 0)) "")))
645 (defun company-grab-line (regexp &optional expression)
646 (company-grab regexp expression (point-at-bol)))
648 (defun company-grab-symbol ()
649 (if (looking-at "\\_>")
650 (buffer-substring (point) (save-excursion (skip-syntax-backward "w_")
652 (unless (and (char-after) (memq (char-syntax (char-after)) '(?w ?_)))
655 (defun company-grab-word ()
656 (if (looking-at "\\>")
657 (buffer-substring (point) (save-excursion (skip-syntax-backward "w")
659 (unless (and (char-after) (eq (char-syntax (char-after)) ?w))
662 (defun company-in-string-or-comment ()
663 (let ((ppss (syntax-ppss)))
664 (or (car (setq ppss (nthcdr 3 ppss)))
665 (car (setq ppss (cdr ppss)))
668 (if (fboundp 'locate-dominating-file)
669 (defalias 'company-locate-dominating-file 'locate-dominating-file)
670 (defun company-locate-dominating-file (file name)
672 (let ((dir (file-name-directory file))
674 (while (not (equal dir prev-dir))
675 (when (file-exists-p (expand-file-name name dir))
678 dir (file-name-directory (directory-file-name dir))))))))
680 (defun company-call-backend (&rest args)
681 (if (functionp company-backend)
682 (apply company-backend args)
683 (apply 'company--multi-backend-adapter company-backend args)))
685 (defun company--multi-backend-adapter (backends command &rest args)
688 (apply 'append (mapcar (lambda (backend) (apply backend command args))
694 (dolist (backend backends)
695 (when (setq value (apply backend command args))
698 ;;; completion mechanism ;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;
700 (defvar company-backend nil)
701 (make-variable-buffer-local 'company-backend)
703 (defvar company-prefix nil)
704 (make-variable-buffer-local 'company-prefix)
706 (defvar company-candidates nil)
707 (make-variable-buffer-local 'company-candidates)
709 (defvar company-candidates-length nil)
710 (make-variable-buffer-local 'company-candidates-length)
712 (defvar company-candidates-cache nil)
713 (make-variable-buffer-local 'company-candidates-cache)
715 (defvar company-candidates-predicate nil)
716 (make-variable-buffer-local 'company-candidates-predicate)
718 (defvar company-common nil)
719 (make-variable-buffer-local 'company-common)
721 (defvar company-selection 0)
722 (make-variable-buffer-local 'company-selection)
724 (defvar company-selection-changed nil)
725 (make-variable-buffer-local 'company-selection-changed)
727 (defvar company--explicit-action nil
728 "Non-nil, if explicit completion took place.")
729 (make-variable-buffer-local 'company--explicit-action)
731 (defvar company--point-max nil)
732 (make-variable-buffer-local 'company--point-max)
734 (defvar company-point nil)
735 (make-variable-buffer-local 'company-point)
737 (defvar company-timer nil)
739 (defvar company-added-newline nil)
740 (make-variable-buffer-local 'company-added-newline)
742 (defsubst company-strip-prefix (str)
743 (substring str (length company-prefix)))
745 (defun company-explicit-action-p ()
746 "Return whether explicit completion action was taken by the user."
747 (or company--explicit-action
748 company-selection-changed))
750 (defsubst company-reformat (candidate)
751 ;; company-ispell needs this, because the results are always lower-case
752 ;; It's mory efficient to fix it only when they are displayed.
753 (concat company-prefix (substring candidate (length company-prefix))))
755 (defun company--should-complete ()
756 (and (not (or buffer-read-only overriding-terminal-local-map
757 overriding-local-map))
758 ;; Check if in the middle of entering a key combination.
759 (or (equal (this-command-keys-vector) [])
760 (not (keymapp (key-binding (this-command-keys-vector)))))
761 (eq company-idle-delay t)
762 (or (eq t company-begin-commands)
763 (memq this-command company-begin-commands)
764 (and (symbolp this-command) (get this-command 'company-begin)))
765 (not (and transient-mark-mode mark-active))))
767 (defsubst company-call-frontends (command)
768 (dolist (frontend company-frontends)
770 (funcall frontend command)
771 (error (error "Company: Front-end %s error \"%s\" on command %s"
772 frontend (error-message-string err) command)))))
774 (defsubst company-set-selection (selection &optional force-update)
775 (setq selection (max 0 (min (1- company-candidates-length) selection)))
776 (when (or force-update (not (equal selection company-selection)))
777 (setq company-selection selection
778 company-selection-changed t)
779 (company-call-frontends 'update)))
781 (defun company-apply-predicate (candidates predicate)
783 (dolist (c candidates)
784 (when (funcall predicate c)
788 (defun company-update-candidates (candidates)
789 (setq company-candidates-length (length candidates))
790 (if (> company-selection 0)
791 ;; Try to restore the selection
792 (let ((selected (nth company-selection company-candidates)))
793 (setq company-selection 0
794 company-candidates candidates)
796 (while (and candidates (string< (pop candidates) selected))
797 (incf company-selection))
799 ;; Make sure selection isn't out of bounds.
800 (setq company-selection (min (1- company-candidates-length)
801 company-selection)))))
802 (setq company-selection 0
803 company-candidates candidates))
805 (push (cons company-prefix company-candidates) company-candidates-cache)
807 (let ((completion-ignore-case (company-call-backend 'ignore-case)))
808 (setq company-common (try-completion company-prefix company-candidates)))
809 (when (eq company-common t)
810 (setq company-candidates nil)))
812 (defun company-calculate-candidates (prefix)
813 (let ((candidates (cdr (assoc prefix company-candidates-cache))))
815 (when company-candidates-cache
816 (let ((len (length prefix))
817 (completion-ignore-case (company-call-backend 'ignore-case))
819 (dotimes (i (1+ len))
820 (when (setq prev (cdr (assoc (substring prefix 0 (- len i))
821 company-candidates-cache)))
822 (setq candidates (all-completions prefix prev))
824 ;; no cache match, call back-end
826 (setq candidates (company-call-backend 'candidates prefix))
827 (when company-candidates-predicate
829 (company-apply-predicate candidates
830 company-candidates-predicate)))
831 (unless (company-call-backend 'sorted)
832 (setq candidates (sort candidates 'string<)))
833 (when (company-call-backend 'duplicates)
835 (let ((c2 candidates))
837 (setcdr c2 (progn (while (equal (pop c2) (car c2)))
839 (if (or (cdr candidates)
840 (not (equal (car candidates) prefix)))
841 ;; Don't start when already completed and unique.
843 ;; Not the right place? maybe when setting?
844 (and company-candidates t))))
846 (defun company-idle-begin (buf win tick pos)
848 (eq buf (current-buffer))
849 (eq win (selected-window))
850 (eq tick (buffer-chars-modified-tick))
852 (not company-candidates)
853 (not (equal (point) company-point))
854 (let ((company-idle-delay t)
855 (company-begin-commands t))
857 (when company-candidates
859 (company-post-command)))))
861 (defun company-auto-begin ()
862 (company-assert-enabled)
864 (not company-candidates)
865 (let ((company-idle-delay t)
866 (company-minimum-prefix-length 0)
867 (company-begin-commands t))
869 ;; Return non-nil if active.
872 (defun company-manual-begin ()
874 (setq company--explicit-action t)
875 (company-auto-begin))
877 (defun company-other-backend (&optional backward)
878 (interactive (list current-prefix-arg))
879 (company-assert-enabled)
881 (let* ((after (cdr (member company-backend company-backends)))
882 (before (cdr (member company-backend (reverse company-backends))))
884 (append before (reverse after))
885 (append after (reverse before)))))
887 (dolist (backend next)
888 (when (ignore-errors (company-begin-backend backend))
890 (company-manual-begin))
891 (unless company-candidates
892 (error "No other back-end")))
894 (defun company-require-match-p ()
895 (let ((backend-value (company-call-backend 'require-match)))
896 (or (eq backend-value t)
897 (and (if (functionp company-require-match)
898 (funcall company-require-match)
899 (eq company-require-match t))
900 (not (eq backend-value 'never))))))
902 (defun company-punctuation-p (input)
903 "Return non-nil, if input starts with punctuation or parentheses."
904 (memq (char-syntax (string-to-char input)) '(?. ?\( ?\))))
906 (defun company-auto-complete-p (input)
907 "Return non-nil, if input starts with punctuation or parentheses."
908 (and (if (functionp company-auto-complete)
909 (funcall company-auto-complete)
910 company-auto-complete)
911 (if (functionp company-auto-complete-chars)
912 (funcall company-auto-complete-chars input)
913 (if (consp company-auto-complete-chars)
914 (memq (char-syntax (string-to-char input))
915 company-auto-complete-chars)
916 (string-match (substring input 0 1) company-auto-complete-chars)))))
918 (defun company--incremental-p ()
919 (and (> (point) company-point)
920 (> (point-max) company--point-max)
921 (not (eq this-command 'backward-delete-char-untabify))
922 (equal (buffer-substring (- company-point (length company-prefix))
926 (defsubst company--string-incremental-p (old-prefix new-prefix)
927 (and (> (length new-prefix) (length old-prefix))
928 (equal old-prefix (substring new-prefix 0 (length old-prefix)))))
930 (defun company--continue-failed (new-prefix)
931 (when (company--incremental-p)
932 (let ((input (buffer-substring-no-properties (point) company-point)))
934 ((company-auto-complete-p input)
937 (goto-char company-point)
938 (company-complete-selection)
940 ((and (company--string-incremental-p company-prefix new-prefix)
941 (company-require-match-p))
942 ;; wrong incremental input, but required match
943 (backward-delete-char (length input))
945 (message "Matching input is required")
947 ((equal company-prefix (car company-candidates))
948 ;; last input was actually success
949 (company-cancel company-prefix)
952 (defun company--good-prefix-p (prefix)
953 (and (or (company-explicit-action-p)
954 (>= (or (cdr-safe prefix) (length prefix))
955 company-minimum-prefix-length))
956 (stringp (or (car-safe prefix) prefix))))
958 (defun company--continue ()
959 (when (company-call-backend 'no-cache company-prefix)
960 ;; Don't complete existing candidates, fetch new ones.
961 (setq company-candidates-cache nil))
962 (let* ((new-prefix (company-call-backend 'prefix))
963 (c (when (and (company--good-prefix-p new-prefix)
964 (setq new-prefix (or (car-safe new-prefix) new-prefix))
965 (= (- (point) (length new-prefix))
966 (- company-point (length company-prefix))))
967 (setq new-prefix (or (car-safe new-prefix) new-prefix))
968 (company-calculate-candidates new-prefix))))
971 ;; t means complete/unique.
972 (company-cancel new-prefix)
976 (setq company-prefix new-prefix)
977 (company-update-candidates c)
979 (t (company--continue-failed new-prefix)))
982 (defun company--begin-new ()
984 (dolist (backend (if company-backend
985 ;; prefer manual override
986 (list company-backend)
989 (if (or (symbolp backend)
991 (when (or (not (symbolp backend))
992 (eq t (get backend 'company-init))
993 (unless (get backend 'company-init)
994 (company-init-backend backend)))
995 (funcall backend 'prefix))
996 (company--multi-backend-adapter backend 'prefix)))
998 (when (company--good-prefix-p prefix)
999 (setq prefix (or (car-safe prefix) prefix)
1000 company-backend backend
1001 c (company-calculate-candidates prefix))
1002 ;; t means complete/unique. We don't start, so no hooks.
1004 (setq company-prefix prefix)
1005 (when (symbolp backend)
1006 (setq company-lighter (concat " " (symbol-name backend))))
1007 (company-update-candidates c)
1008 (run-hook-with-args 'company-completion-started-hook
1009 (company-explicit-action-p))
1010 (company-call-frontends 'show)))
1013 (defun company-begin ()
1014 (setq company-candidates
1015 (or (and company-candidates (company--continue))
1016 (and (company--should-complete) (company--begin-new))))
1017 (when company-candidates
1018 (when (and company-end-of-buffer-workaround (eobp))
1019 (save-excursion (insert "\n"))
1020 (setq company-added-newline (buffer-chars-modified-tick)))
1021 (setq company-point (point)
1022 company--point-max (point-max))
1023 (company-enable-overriding-keymap company-active-map)
1024 (company-call-frontends 'update)))
1026 (defun company-cancel (&optional result)
1027 (and company-added-newline
1028 (> (point-max) (point-min))
1029 (let ((tick (buffer-chars-modified-tick)))
1030 (delete-region (1- (point-max)) (point-max))
1031 (equal tick company-added-newline))
1032 ;; Only set unmodified when tick remained the same since insert.
1033 (set-buffer-modified-p nil))
1034 (when company-prefix
1035 (if (stringp result)
1036 (run-hook-with-args 'company-completion-finished-hook result)
1037 (run-hook-with-args 'company-completion-cancelled-hook result)))
1038 (setq company-added-newline nil
1041 company-candidates nil
1042 company-candidates-length nil
1043 company-candidates-cache nil
1044 company-candidates-predicate nil
1047 company-selection-changed nil
1048 company--explicit-action nil
1049 company-lighter company-default-lighter
1050 company--point-max nil
1053 (cancel-timer company-timer))
1054 (company-search-mode 0)
1055 (company-call-frontends 'hide)
1056 (company-enable-overriding-keymap nil))
1058 (defun company-abort ()
1061 ;; Don't start again, unless started manually.
1062 (setq company-point (point)))
1064 (defun company-finish (result)
1065 (insert (company-strip-prefix result))
1066 (company-cancel result)
1067 ;; Don't start again, unless started manually.
1068 (setq company-point (point)))
1070 (defsubst company-keep (command)
1071 (and (symbolp command) (get command 'company-keep)))
1073 (defun company-pre-command ()
1074 (unless (company-keep this-command)
1076 (when company-candidates
1077 (company-call-frontends 'pre-command))
1078 (error (message "Company: An error occurred in pre-command")
1079 (message "%s" (error-message-string err))
1082 (cancel-timer company-timer)
1083 (setq company-timer nil))
1084 (company-uninstall-map))
1086 (defun company-post-command ()
1087 (unless (company-keep this-command)
1090 (unless (equal (point) company-point)
1092 (if company-candidates
1093 (company-call-frontends 'post-command)
1094 (and (numberp company-idle-delay)
1095 (or (eq t company-begin-commands)
1096 (memq this-command company-begin-commands))
1098 (run-with-timer company-idle-delay nil
1100 (current-buffer) (selected-window)
1101 (buffer-chars-modified-tick) (point))))))
1102 (error (message "Company: An error occurred in post-command")
1103 (message "%s" (error-message-string err))
1105 (company-install-map))
1107 ;;; search ;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;
1109 (defvar company-search-string nil)
1110 (make-variable-buffer-local 'company-search-string)
1112 (defvar company-search-lighter " Search: \"\"")
1113 (make-variable-buffer-local 'company-search-lighter)
1115 (defvar company-search-old-map nil)
1116 (make-variable-buffer-local 'company-search-old-map)
1118 (defvar company-search-old-selection 0)
1119 (make-variable-buffer-local 'company-search-old-selection)
1121 (defun company-search (text lines)
1122 (let ((quoted (regexp-quote text))
1124 (dolist (line lines)
1125 (when (string-match quoted line (length company-prefix))
1129 (defun company-search-printing-char ()
1131 (company-search-assert-enabled)
1132 (setq company-search-string
1133 (concat (or company-search-string "") (string last-command-event))
1134 company-search-lighter (concat " Search: \"" company-search-string
1136 (let ((pos (company-search company-search-string
1137 (nthcdr company-selection company-candidates))))
1140 (company-set-selection (+ company-selection pos) t))))
1142 (defun company-search-repeat-forward ()
1143 "Repeat the incremental search in completion candidates forward."
1145 (company-search-assert-enabled)
1146 (let ((pos (company-search company-search-string
1147 (cdr (nthcdr company-selection
1148 company-candidates)))))
1151 (company-set-selection (+ company-selection pos 1) t))))
1153 (defun company-search-repeat-backward ()
1154 "Repeat the incremental search in completion candidates backwards."
1156 (company-search-assert-enabled)
1157 (let ((pos (company-search company-search-string
1158 (nthcdr (- company-candidates-length
1160 (reverse company-candidates)))))
1163 (company-set-selection (- company-selection pos 1) t))))
1165 (defun company-create-match-predicate ()
1166 (setq company-candidates-predicate
1167 `(lambda (candidate)
1168 ,(if company-candidates-predicate
1169 `(and (string-match ,company-search-string candidate)
1170 (funcall ,company-candidates-predicate
1172 `(string-match ,company-search-string candidate))))
1173 (company-update-candidates
1174 (company-apply-predicate company-candidates company-candidates-predicate))
1175 ;; Invalidate cache.
1176 (setq company-candidates-cache (cons company-prefix company-candidates)))
1178 (defun company-filter-printing-char ()
1180 (company-search-assert-enabled)
1181 (company-search-printing-char)
1182 (company-create-match-predicate)
1183 (company-call-frontends 'update))
1185 (defun company-search-kill-others ()
1186 "Limit the completion candidates to the ones matching the search string."
1188 (company-search-assert-enabled)
1189 (company-create-match-predicate)
1190 (company-search-mode 0)
1191 (company-call-frontends 'update))
1193 (defun company-search-abort ()
1194 "Abort searching the completion candidates."
1196 (company-search-assert-enabled)
1197 (company-set-selection company-search-old-selection t)
1198 (company-search-mode 0))
1200 (defun company-search-other-char ()
1202 (company-search-assert-enabled)
1203 (company-search-mode 0)
1204 (when last-input-event
1205 (clear-this-command-keys t)
1206 (setq unread-command-events (list last-input-event))))
1208 (defvar company-search-map
1210 (keymap (make-keymap)))
1211 (if (fboundp 'max-char)
1212 (set-char-table-range (nth 1 keymap) (cons #x100 (max-char))
1213 'company-search-printing-char)
1215 ;; obselete in Emacs 23
1216 (let ((l (generic-character-list))
1217 (table (nth 1 keymap)))
1219 (set-char-table-default table (car l) 'company-search-printing-char)
1220 (setq l (cdr l))))))
1221 (define-key keymap [t] 'company-search-other-char)
1223 (define-key keymap (make-string 1 i) 'company-search-other-char)
1226 (define-key keymap (vector i) 'company-search-printing-char)
1228 (let ((meta-map (make-sparse-keymap)))
1229 (define-key keymap (char-to-string meta-prefix-char) meta-map)
1230 (define-key keymap [escape] meta-map))
1231 (define-key keymap (vector meta-prefix-char t) 'company-search-other-char)
1232 (define-key keymap "\e\e\e" 'company-search-other-char)
1233 (define-key keymap [escape escape escape] 'company-search-other-char)
1235 (define-key keymap "\C-g" 'company-search-abort)
1236 (define-key keymap "\C-s" 'company-search-repeat-forward)
1237 (define-key keymap "\C-r" 'company-search-repeat-backward)
1238 (define-key keymap "\C-o" 'company-search-kill-others)
1240 "Keymap used for incrementally searching the completion candidates.")
1242 (define-minor-mode company-search-mode
1243 "Search mode for completion candidates.
1244 Don't start this directly, use `company-search-candidates' or
1245 `company-filter-candidates'."
1246 nil company-search-lighter nil
1247 (if company-search-mode
1248 (if (company-manual-begin)
1250 (setq company-search-old-selection company-selection)
1251 (company-call-frontends 'update))
1252 (setq company-search-mode nil))
1253 (kill-local-variable 'company-search-string)
1254 (kill-local-variable 'company-search-lighter)
1255 (kill-local-variable 'company-search-old-selection)
1256 (company-enable-overriding-keymap company-active-map)))
1258 (defsubst company-search-assert-enabled ()
1259 (company-assert-enabled)
1260 (unless company-search-mode
1261 (company-uninstall-map)
1262 (error "Company not in search mode")))
1264 (defun company-search-candidates ()
1265 "Start searching the completion candidates incrementally.
1267 \\<company-search-map>Search can be controlled with the commands:
1268 - `company-search-repeat-forward' (\\[company-search-repeat-forward])
1269 - `company-search-repeat-backward' (\\[company-search-repeat-backward])
1270 - `company-search-abort' (\\[company-search-abort])
1272 Regular characters are appended to the search string.
1274 The command `company-search-kill-others' (\\[company-search-kill-others]) uses
1275 the search string to limit the completion candidates."
1277 (company-search-mode 1)
1278 (company-enable-overriding-keymap company-search-map))
1280 (defvar company-filter-map
1281 (let ((keymap (make-keymap)))
1282 (define-key keymap [remap company-search-printing-char]
1283 'company-filter-printing-char)
1284 (set-keymap-parent keymap company-search-map)
1286 "Keymap used for incrementally searching the completion candidates.")
1288 (defun company-filter-candidates ()
1289 "Start filtering the completion candidates incrementally.
1290 This works the same way as `company-search-candidates' immediately
1291 followed by `company-search-kill-others' after each input."
1293 (company-search-mode 1)
1294 (company-enable-overriding-keymap company-filter-map))
1296 ;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;
1298 (defun company-select-next ()
1299 "Select the next candidate in the list."
1301 (when (company-manual-begin)
1302 (company-set-selection (1+ company-selection))))
1304 (defun company-select-previous ()
1305 "Select the previous candidate in the list."
1307 (when (company-manual-begin)
1308 (company-set-selection (1- company-selection))))
1310 (defun company-select-mouse (event)
1311 "Select the candidate picked by the mouse."
1313 (when (nth 4 (event-start event))
1314 (company-set-selection (- (cdr (posn-actual-col-row (event-start event)))
1319 (defun company-complete-mouse (event)
1320 "Complete the candidate picked by the mouse."
1322 (when (company-select-mouse event)
1323 (company-complete-selection)))
1325 (defun company-complete-selection ()
1326 "Complete the selected candidate."
1328 (when (company-manual-begin)
1329 (company-finish (nth company-selection company-candidates))))
1331 (defun company-complete-common ()
1332 "Complete the common part of all candidates."
1334 (when (company-manual-begin)
1335 (if (and (not (cdr company-candidates))
1336 (equal company-common (car company-candidates)))
1337 (company-complete-selection)
1338 (insert (company-strip-prefix company-common)))))
1340 (defun company-complete ()
1341 "Complete the common part of all candidates or the current selection.
1342 The first time this is called, the common part is completed, the second time, or
1343 when the selection has been changed, the selected candidate is completed."
1345 (when (company-manual-begin)
1346 (if (or company-selection-changed
1347 (eq last-command 'company-complete-common))
1348 (call-interactively 'company-complete-selection)
1349 (call-interactively 'company-complete-common)
1350 (setq this-command 'company-complete-common))))
1352 (defun company-complete-number (n)
1353 "Complete the Nth candidate.
1354 To show the number next to the candidates in some back-ends, enable
1355 `company-show-numbers'."
1356 (when (company-manual-begin)
1357 (and (< n 1) (> n company-candidates-length)
1358 (error "No candidate number %d" n))
1360 (company-finish (nth n company-candidates))))
1362 ;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;
1364 (defconst company-space-strings-limit 100)
1366 (defconst company-space-strings
1368 (dotimes (i company-space-strings-limit)
1369 (push (make-string (- company-space-strings-limit 1 i) ?\ ) lst))
1370 (apply 'vector lst)))
1372 (defsubst company-space-string (len)
1373 (if (< len company-space-strings-limit)
1374 (aref company-space-strings len)
1375 (make-string len ?\ )))
1377 (defsubst company-safe-substring (str from &optional to)
1378 (let ((len (length str)))
1381 (if (and to (> to len))
1382 (concat (substring str from)
1383 (company-space-string (- to len)))
1384 (substring str from to)))))
1386 ;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;
1388 (defvar company-last-metadata nil)
1389 (make-variable-buffer-local 'company-last-metadata)
1391 (defun company-fetch-metadata ()
1392 (let ((selected (nth company-selection company-candidates)))
1393 (unless (equal selected (car company-last-metadata))
1394 (setq company-last-metadata
1395 (cons selected (company-call-backend 'meta selected))))
1396 (cdr company-last-metadata)))
1398 (defun company-doc-buffer (&optional string)
1399 (with-current-buffer (get-buffer-create "*Company meta-data*")
1403 (defmacro company--electric-do (&rest body)
1404 (declare (indent 0) (debug t))
1405 `(when (company-manual-begin)
1406 (save-window-excursion
1407 (let ((height (window-height))
1408 (row (company--row)))
1410 (and (< (window-height) height)
1411 (< (- (window-height) row 2) company-tooltip-limit)
1412 (recenter (- (window-height) row 2)))
1413 (while (eq 'scroll-other-window
1414 (key-binding (vector (list (read-event)))))
1415 (call-interactively 'scroll-other-window))
1416 (when last-input-event
1417 (clear-this-command-keys t)
1418 (setq unread-command-events (list last-input-event)))))))
1420 (defun company-show-doc-buffer ()
1421 "Temporarily show a buffer with the complete documentation for the selection."
1423 (company--electric-do
1424 (let ((selected (nth company-selection company-candidates)))
1425 (display-buffer (or (company-call-backend 'doc-buffer selected)
1426 (error "No documentation available")) t))))
1427 (put 'company-show-doc-buffer 'company-keep t)
1429 (defun company-show-location ()
1430 "Temporarily display a buffer showing the selected candidate in context."
1432 (company--electric-do
1433 (let* ((selected (nth company-selection company-candidates))
1434 (location (company-call-backend 'location selected))
1435 (pos (or (cdr location) (error "No location available")))
1436 (buffer (or (and (bufferp (car location)) (car location))
1437 (find-file-noselect (car location) t))))
1438 (with-selected-window (display-buffer buffer t)
1439 (if (bufferp (car location))
1442 (set-window-start nil (point))))))
1443 (put 'company-show-location 'company-keep t)
1445 ;;; package functions ;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;
1447 (defvar company-callback nil)
1448 (make-variable-buffer-local 'company-callback)
1450 (defvar company-begin-with-marker nil)
1451 (make-variable-buffer-local 'company-begin-with-marker)
1453 (defun company-remove-callback (&optional ignored)
1454 (remove-hook 'company-completion-finished-hook company-callback t)
1455 (remove-hook 'company-completion-cancelled-hook 'company-remove-callback t)
1456 (remove-hook 'company-completion-finished-hook 'company-remove-callback t)
1457 (when company-begin-with-marker
1458 (set-marker company-begin-with-marker nil)))
1460 (defun company-begin-backend (backend &optional callback)
1461 "Start a completion at point using BACKEND."
1462 (interactive (let ((val (completing-read "Company back-end: "
1464 'functionp nil "company-")))
1466 (list (intern val)))))
1467 (when (setq company-callback callback)
1468 (add-hook 'company-completion-finished-hook company-callback nil t))
1469 (add-hook 'company-completion-cancelled-hook 'company-remove-callback nil t)
1470 (add-hook 'company-completion-finished-hook 'company-remove-callback nil t)
1471 (setq company-backend backend)
1472 ;; Return non-nil if active.
1473 (or (company-manual-begin)
1474 (error "Cannot complete at point")))
1476 (defun company-begin-with (candidates
1477 &optional prefix-length require-match callback)
1478 "Start a completion at point.
1479 CANDIDATES is the list of candidates to use and PREFIX-LENGTH is the length of
1480 the prefix that already is in the buffer before point. It defaults to 0.
1482 CALLBACK is a function called with the selected result if the user successfully
1483 completes the input.
1486 \(company-begin-with '\(\"foo\" \"foobar\" \"foobarbaz\"\)\)"
1487 (setq company-begin-with-marker (copy-marker (point) t))
1488 (company-begin-backend
1489 `(lambda (command &optional arg &rest ignored)
1491 ((eq command 'prefix)
1492 (when (equal (point) (marker-position company-begin-with-marker))
1493 (buffer-substring ,(- (point) (or prefix-length 0)) (point))))
1494 ((eq command 'candidates)
1495 (all-completions arg ',candidates))
1496 ((eq command 'require-match)
1500 ;;; pseudo-tooltip ;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;
1502 (defvar company-pseudo-tooltip-overlay nil)
1503 (make-variable-buffer-local 'company-pseudo-tooltip-overlay)
1505 (defvar company-tooltip-offset 0)
1506 (make-variable-buffer-local 'company-tooltip-offset)
1508 (defun company-pseudo-tooltip-update-offset (selection num-lines limit)
1511 (setq company-tooltip-offset
1512 (max (min selection company-tooltip-offset)
1513 (- selection -1 limit)))
1515 (when (<= company-tooltip-offset 1)
1517 (setq company-tooltip-offset 0))
1519 (when (>= company-tooltip-offset (- num-lines limit 1))
1521 (when (= selection (1- num-lines))
1522 (decf company-tooltip-offset)
1523 (when (<= company-tooltip-offset 1)
1524 (setq company-tooltip-offset 0)
1531 (defsubst company-round-tab (arg)
1532 (* (/ (+ arg tab-width) tab-width) tab-width))
1534 (defun company-untabify (str)
1535 (let* ((pieces (split-string str "\t"))
1538 (setcar copy (company-safe-substring
1539 (car copy) 0 (company-round-tab (string-width (car copy)))))
1541 (apply 'concat pieces)))
1543 (defun company-fill-propertize (line width selected)
1544 (setq line (company-safe-substring line 0 width))
1545 (add-text-properties 0 width '(face company-tooltip
1546 mouse-face company-tooltip-mouse)
1548 (add-text-properties 0 (length company-common)
1549 '(face company-tooltip-common
1550 mouse-face company-tooltip-mouse)
1553 (if (and company-search-string
1554 (string-match (regexp-quote company-search-string) line
1555 (length company-prefix)))
1557 (add-text-properties (match-beginning 0) (match-end 0)
1558 '(face company-tooltip-selection)
1560 (when (< (match-beginning 0) (length company-common))
1561 (add-text-properties (match-beginning 0) (length company-common)
1562 '(face company-tooltip-common-selection)
1564 (add-text-properties 0 width '(face company-tooltip-selection
1565 mouse-face company-tooltip-selection)
1567 (add-text-properties 0 (length company-common)
1568 '(face company-tooltip-common-selection
1569 mouse-face company-tooltip-selection)
1575 (defun company-buffer-lines (beg end)
1577 (let ((row (company--row))
1579 (while (and (equal (move-to-window-line (incf row)) row)
1581 (push (buffer-substring beg (min end (1- (point)))) lines)
1583 (unless (eq beg end)
1584 (push (buffer-substring beg end) lines))
1587 (defsubst company-modify-line (old new offset)
1588 (concat (company-safe-substring old 0 offset)
1590 (company-safe-substring old (+ offset (length new)))))
1592 (defsubst company--length-limit (lst limit)
1593 (if (nthcdr limit lst)
1597 (defun company--replacement-string (lines old column nl &optional align-top)
1599 (let ((width (length (car lines))))
1600 (when (> width (- (window-width) column))
1601 (setq column (max 0 (- (window-width) width)))))
1605 ;; untouched lines first
1606 (dotimes (i (- (length old) (length lines)))
1607 (push (pop old) new)))
1608 ;; length into old lines.
1610 (push (company-modify-line (pop old) (pop lines) column) new))
1611 ;; Append whole new lines.
1613 (push (concat (company-space-string column) (pop lines)) new))
1614 (concat (when nl "\n")
1615 (mapconcat 'identity (nreverse new) "\n")
1618 (defun company--create-lines (selection limit)
1620 (let ((len company-candidates-length)
1629 ;; Scroll to offset.
1630 (setq limit (company-pseudo-tooltip-update-offset selection len limit))
1632 (when (> company-tooltip-offset 0)
1633 (setq previous (format "...(%d)" company-tooltip-offset)))
1635 (setq remainder (- len limit company-tooltip-offset)
1636 remainder (when (> remainder 0)
1637 (setq remainder (format "...(%d)" remainder))))
1639 (decf selection company-tooltip-offset)
1640 (setq width (max (length previous) (length remainder))
1641 lines (nthcdr company-tooltip-offset company-candidates)
1646 (setq width (max (length (pop lines-copy)) width)))
1647 (setq width (min width (window-width)))
1649 (setq lines-copy lines)
1651 ;; number can make tooltip too long
1652 (when company-show-numbers
1653 (setq numbered company-tooltip-offset))
1656 (push (propertize (company-safe-substring previous 0 width)
1657 'face 'company-tooltip)
1661 (push (company-fill-propertize
1662 (if (>= numbered 10)
1663 (company-reformat (pop lines))
1666 (company-safe-substring (company-reformat (pop lines))
1669 width (equal i selection))
1673 (push (propertize (company-safe-substring remainder 0 width)
1674 'face 'company-tooltip)
1677 (setq lines (nreverse new))))
1681 (defsubst company--window-inner-height ()
1682 (let ((edges (window-inside-edges (selected-window))))
1683 (- (nth 3 edges) (nth 1 edges))))
1685 (defsubst company--pseudo-tooltip-height ()
1686 "Calculate the appropriate tooltip height.
1687 Returns a negative number if the tooltip should be displayed above point."
1688 (let* ((lines (count-lines (window-start) (point-at-bol)))
1689 (below (- (company--window-inner-height) 1 lines)))
1690 (if (and (< below (min company-tooltip-minimum company-candidates-length))
1692 (- (max 3 (min company-tooltip-limit lines)))
1693 (max 3 (min company-tooltip-limit below)))))
1695 (defun company-pseudo-tooltip-show (row column selection)
1696 (company-pseudo-tooltip-hide)
1701 (let* ((height (company--pseudo-tooltip-height))
1705 (setq row (+ row height -1)
1708 (let* ((nl (< (move-to-window-line row) row))
1710 (end (save-excursion
1711 (move-to-window-line (+ row (abs height)))
1713 (ov (make-overlay beg end))
1714 (args (list (mapcar 'company-untabify
1715 (company-buffer-lines beg end))
1718 (setq company-pseudo-tooltip-overlay ov)
1719 (overlay-put ov 'company-replacement-args args)
1720 (overlay-put ov 'company-before
1721 (apply 'company--replacement-string
1722 (company--create-lines selection (abs height))
1725 (overlay-put ov 'company-column column)
1726 (overlay-put ov 'company-height (abs height))
1727 (overlay-put ov 'window (selected-window))))))
1729 (defun company-pseudo-tooltip-show-at-point (pos)
1730 (let ((col-row (company--col-row pos)))
1732 (company-pseudo-tooltip-show (1+ (cdr col-row)) (car col-row)
1733 company-selection))))
1735 (defun company-pseudo-tooltip-edit (lines selection)
1736 (let ((column (overlay-get company-pseudo-tooltip-overlay 'company-column))
1737 (height (overlay-get company-pseudo-tooltip-overlay 'company-height)))
1738 (overlay-put company-pseudo-tooltip-overlay 'company-before
1739 (apply 'company--replacement-string
1740 (company--create-lines selection height)
1741 (overlay-get company-pseudo-tooltip-overlay
1742 'company-replacement-args)))))
1744 (defun company-pseudo-tooltip-hide ()
1745 (when company-pseudo-tooltip-overlay
1746 (delete-overlay company-pseudo-tooltip-overlay)
1747 (setq company-pseudo-tooltip-overlay nil)))
1749 (defun company-pseudo-tooltip-hide-temporarily ()
1750 (when (overlayp company-pseudo-tooltip-overlay)
1751 (overlay-put company-pseudo-tooltip-overlay 'invisible nil)
1752 (overlay-put company-pseudo-tooltip-overlay 'before-string nil)))
1754 (defun company-pseudo-tooltip-unhide ()
1755 (when company-pseudo-tooltip-overlay
1756 (overlay-put company-pseudo-tooltip-overlay 'invisible t)
1757 (overlay-put company-pseudo-tooltip-overlay 'before-string
1758 (overlay-get company-pseudo-tooltip-overlay 'company-before))
1759 (overlay-put company-pseudo-tooltip-overlay 'window (selected-window))))
1761 (defun company-pseudo-tooltip-frontend (command)
1762 "A `company-mode' front-end similar to a tool-tip but based on overlays."
1764 ('pre-command (company-pseudo-tooltip-hide-temporarily))
1766 (let ((old-height (if (overlayp company-pseudo-tooltip-overlay)
1767 (overlay-get company-pseudo-tooltip-overlay
1770 (new-height (company--pseudo-tooltip-height)))
1771 (unless (and (>= (* old-height new-height) 0)
1772 (>= (abs old-height) (abs new-height)))
1774 (company-pseudo-tooltip-show-at-point (- (point)
1775 (length company-prefix)))))
1776 (company-pseudo-tooltip-unhide))
1777 ('hide (company-pseudo-tooltip-hide)
1778 (setq company-tooltip-offset 0))
1779 ('update (when (overlayp company-pseudo-tooltip-overlay)
1780 (company-pseudo-tooltip-edit company-candidates
1781 company-selection)))))
1783 (defun company-pseudo-tooltip-unless-just-one-frontend (command)
1784 "`company-pseudo-tooltip-frontend', but not shown for single candidates."
1785 (unless (and (eq command 'post-command)
1786 (not (cdr company-candidates)))
1787 (company-pseudo-tooltip-frontend command)))
1789 ;;; overlay ;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;
1791 (defvar company-preview-overlay nil)
1792 (make-variable-buffer-local 'company-preview-overlay)
1794 (defun company-preview-show-at-point (pos)
1795 (company-preview-hide)
1797 (setq company-preview-overlay (make-overlay pos pos))
1799 (let ((completion(nth company-selection company-candidates)))
1800 (setq completion (propertize completion 'face 'company-preview))
1801 (add-text-properties 0 (length company-common)
1802 '(face company-preview-common) completion)
1804 ;; Add search string
1805 (and company-search-string
1806 (string-match (regexp-quote company-search-string) completion)
1807 (add-text-properties (match-beginning 0)
1809 '(face company-preview-search)
1812 (setq completion (company-strip-prefix completion))
1814 (and (equal pos (point))
1815 (not (equal completion ""))
1816 (add-text-properties 0 1 '(cursor t) completion))
1818 (overlay-put company-preview-overlay 'after-string completion)
1819 (overlay-put company-preview-overlay 'window (selected-window))))
1821 (defun company-preview-hide ()
1822 (when company-preview-overlay
1823 (delete-overlay company-preview-overlay)
1824 (setq company-preview-overlay nil)))
1826 (defun company-preview-frontend (command)
1827 "A `company-mode' front-end showing the selection as if it had been inserted."
1829 ('pre-command (company-preview-hide))
1830 ('post-command (company-preview-show-at-point (point)))
1831 ('hide (company-preview-hide))))
1833 (defun company-preview-if-just-one-frontend (command)
1834 "`company-preview-frontend', but only shown for single candidates."
1835 (unless (and (eq command 'post-command)
1836 (cdr company-candidates))
1837 (company-preview-frontend command)))
1839 ;;; echo ;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;
1841 (defvar company-echo-last-msg nil)
1842 (make-variable-buffer-local 'company-echo-last-msg)
1844 (defvar company-echo-timer nil)
1846 (defvar company-echo-delay .01)
1848 (defun company-echo-show (&optional getter)
1850 (setq company-echo-last-msg (funcall getter)))
1851 (let ((message-log-max nil))
1852 (if company-echo-last-msg
1853 (message "%s" company-echo-last-msg)
1856 (defsubst company-echo-show-soon (&optional getter)
1857 (when company-echo-timer
1858 (cancel-timer company-echo-timer))
1859 (setq company-echo-timer (run-with-timer company-echo-delay nil
1860 'company-echo-show getter)))
1862 (defun company-echo-format ()
1864 (let ((limit (window-width (minibuffer-window)))
1866 ;; Roll to selection.
1867 (candidates (nthcdr company-selection company-candidates))
1868 (i (if company-show-numbers company-selection 99999))
1872 (setq comp (company-reformat (pop candidates))
1873 len (+ len 1 (length comp)))
1877 (setq comp (propertize (format "%d: %s" i comp)
1878 'face 'company-echo))
1881 (add-text-properties 3 (+ 3 (length company-common))
1882 '(face company-echo-common) comp))
1883 (setq comp (propertize comp 'face 'company-echo))
1884 (add-text-properties 0 (length company-common)
1885 '(face company-echo-common) comp))
1887 (setq candidates nil)
1890 (mapconcat 'identity (nreverse msg) " ")))
1892 (defun company-echo-strip-common-format ()
1894 (let ((limit (window-width (minibuffer-window)))
1895 (len (+ (length company-prefix) 2))
1896 ;; Roll to selection.
1897 (candidates (nthcdr company-selection company-candidates))
1898 (i (if company-show-numbers company-selection 99999))
1902 (setq comp (company-strip-prefix (pop candidates))
1903 len (+ len 2 (length comp)))
1906 (setq comp (format "%s (%d)" comp i))
1910 (setq candidates nil)
1911 (push (propertize comp 'face 'company-echo) msg)))
1913 (concat (propertize company-prefix 'face 'company-echo-common) "{"
1914 (mapconcat 'identity (nreverse msg) ", ")
1917 (defun company-echo-hide ()
1918 (when company-echo-timer
1919 (cancel-timer company-echo-timer))
1920 (unless (equal company-echo-last-msg "")
1921 (setq company-echo-last-msg "")
1922 (company-echo-show)))
1924 (defun company-echo-frontend (command)
1925 "A `company-mode' front-end showing the candidates in the echo area."
1927 ('pre-command (company-echo-show-soon))
1928 ('post-command (company-echo-show-soon 'company-echo-format))
1929 ('hide (company-echo-hide))))
1931 (defun company-echo-strip-common-frontend (command)
1932 "A `company-mode' front-end showing the candidates in the echo area."
1934 ('pre-command (company-echo-show-soon))
1935 ('post-command (company-echo-show-soon 'company-echo-strip-common-format))
1936 ('hide (company-echo-hide))))
1938 (defun company-echo-metadata-frontend (command)
1939 "A `company-mode' front-end showing the documentation in the echo area."
1941 ('pre-command (company-echo-show-soon))
1942 ('post-command (company-echo-show-soon 'company-fetch-metadata))
1943 ('hide (company-echo-hide))))
1946 ;;; company.el ends here