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 ;; Added `company-ropemacs' and `company-pysmell' back-ends.
71 ;; In C modes . and -> now count towards `company-minimum-prefix-length'.
72 ;; Reverted default front-end back to `company-preview-if-just-one-frontend'.
73 ;; The pseudo tooltip will no longer be clipped at the right window edge.
74 ;; Added `company-tooltip-minimum'.
75 ;; Windows compatibility fixes.
78 ;; Added `global-company-mode'.
79 ;; Performance enhancements.
80 ;; Added `company-eclim' back-end.
81 ;; Added safer workaround for Emacs `posn-col-row' bug.
84 ;; Automatic completion is now aborted if the prefix gets too short.
85 ;; Added option `company-dabbrev-time-limit'.
86 ;; `company-backends' now supports merging back-ends.
87 ;; Added back-end `company-dabbrev-code' for generic code.
88 ;; Fixed `company-begin-with'.
91 ;; Added 'stop prefix to prevent dabbrev from completing inside of symbols.
92 ;; Fixed issues with tabbar-mode and line-spacing.
93 ;; Performance enhancements.
96 ;; Added `company-begin-commands' option.
97 ;; Added abbrev, tempo and Xcode back-ends.
98 ;; Back-ends are now interactive. You can start them with M-x backend-name.
99 ;; Added `company-begin-with' for starting company from elisp-code.
101 ;; Added `company-require-match' and `company-auto-complete' options.
103 ;; 2009-04-05 (0.2.1)
104 ;; Improved Emacs Lisp back-end behavior for local variables.
105 ;; Added `company-elisp-detect-function-context' option.
106 ;; The mouse can now be used for selection.
109 ;; Added `company-show-location'.
110 ;; Added etags back-end.
111 ;; Added work-around for end-of-buffer bug.
112 ;; Added `company-filter-candidates'.
113 ;; More local Lisp variables are now included in the candidates.
115 ;; 2009-03-21 (0.1.5)
116 ;; Fixed elisp documentation buffer always showing the same doc.
117 ;; Added `company-echo-strip-common-frontend'.
118 ;; Added `company-show-numbers' option and M-0 ... M-9 default bindings.
119 ;; Don't hide the echo message if it isn't shown.
126 (eval-when-compile (require 'cl))
128 (add-to-list 'debug-ignored-errors "^.* frontend cannot be used twice$")
129 (add-to-list 'debug-ignored-errors "^Echo area cannot be used twice$")
130 (add-to-list 'debug-ignored-errors "^No \\(document\\|loc\\)ation available$")
131 (add-to-list 'debug-ignored-errors "^Company not ")
132 (add-to-list 'debug-ignored-errors "^No candidate number ")
133 (add-to-list 'debug-ignored-errors "^Cannot complete at point$")
135 (defgroup company nil
136 "Extensible inline text completion mechanism"
141 (defface company-tooltip
142 '((t :background "yellow"
143 :foreground "black"))
144 "*Face used for the tool tip."
147 (defface company-tooltip-selection
148 '((default :inherit company-tooltip)
149 (((class color) (min-colors 88)) (:background "orange1"))
150 (t (:background "green")))
151 "*Face used for the selection in the tool tip."
154 (defface company-tooltip-mouse
155 '((default :inherit highlight))
156 "*Face used for the tool tip item under the mouse."
159 (defface company-tooltip-common
160 '((t :inherit company-tooltip
162 "*Face used for the common completion in the tool tip."
165 (defface company-tooltip-common-selection
166 '((t :inherit company-tooltip-selection
168 "*Face used for the selected common completion in the tool tip."
171 (defface company-preview
172 '((t :background "blue4"
173 :foreground "wheat"))
174 "*Face used for the completion preview."
177 (defface company-preview-common
178 '((t :inherit company-preview
180 "*Face used for the common part of the completion preview."
183 (defface company-preview-search
184 '((t :inherit company-preview
185 :background "blue1"))
186 "*Face used for the search string in the completion preview."
189 (defface company-echo nil
190 "*Face used for completions in the echo area."
193 (defface company-echo-common
194 '((((background dark)) (:foreground "firebrick1"))
195 (((background light)) (:background "firebrick4")))
196 "*Face used for the common part of completions in the echo area."
199 (defun company-frontends-set (variable value)
201 (let ((remainder value))
202 (setcdr remainder (delq (car remainder) (cdr remainder))))
203 (and (memq 'company-pseudo-tooltip-unless-just-one-frontend value)
204 (memq 'company-pseudo-tooltip-frontend value)
205 (error "Pseudo tooltip frontend cannot be used twice"))
206 (and (memq 'company-preview-if-just-one-frontend value)
207 (memq 'company-preview-frontend value)
208 (error "Preview frontend cannot be used twice"))
209 (and (memq 'company-echo value)
210 (memq 'company-echo-metadata-frontend value)
211 (error "Echo area cannot be used twice"))
212 ;; preview must come last
213 (dolist (f '(company-preview-if-just-one-frontend company-preview-frontend))
215 (setq value (append (delq f value) (list f)))))
216 (set variable value))
218 (defcustom company-frontends '(company-pseudo-tooltip-unless-just-one-frontend
219 company-preview-if-just-one-frontend
220 company-echo-metadata-frontend)
221 "*The list of active front-ends (visualizations).
222 Each front-end is a function that takes one argument. It is called with
223 one of the following arguments:
225 'show: When the visualization should start.
227 'hide: When the visualization should end.
229 'update: When the data has been updated.
231 'pre-command: Before every command that is executed while the
232 visualization is active.
234 'post-command: After every command that is executed while the
235 visualization is active.
237 The visualized data is stored in `company-prefix', `company-candidates',
238 `company-common', `company-selection', `company-point' and
239 `company-search-string'."
240 :set 'company-frontends-set
242 :type '(repeat (choice (const :tag "echo" company-echo-frontend)
243 (const :tag "echo, strip common"
244 company-echo-strip-common-frontend)
245 (const :tag "show echo meta-data in echo"
246 company-echo-metadata-frontend)
247 (const :tag "pseudo tooltip"
248 company-pseudo-tooltip-frontend)
249 (const :tag "pseudo tooltip, multiple only"
250 company-pseudo-tooltip-unless-just-one-frontend)
251 (const :tag "preview" company-preview-frontend)
252 (const :tag "preview, unique only"
253 company-preview-if-just-one-frontend)
254 (function :tag "custom function" nil))))
256 (defcustom company-tooltip-limit 10
257 "*The maximum number of candidates in the tool tip"
261 (defcustom company-tooltip-minimum 6
262 "*The minimum height of the tool tip.
263 If this many lines are not available, prefer to display the tooltip above."
267 (defvar company-safe-backends
268 '((company-abbrev . "Abbrev")
269 (company-css . "CSS")
270 (company-dabbrev . "dabbrev for plain text")
271 (company-dabbrev-code . "dabbrev for code")
272 (company-eclim . "eclim (an Eclipse interace)")
273 (company-elisp . "Emacs Lisp")
274 (company-etags . "etags")
275 (company-files . "Files")
276 (company-gtags . "GNU Global")
277 (company-ispell . "ispell")
278 (company-keywords . "Programming language keywords")
279 (company-nxml . "nxml")
280 (company-oddmuse . "Oddmuse")
281 (company-pysmell . "PySmell")
282 (company-ropemacs . "ropemacs")
283 (company-semantic . "CEDET Semantic")
284 (company-tempo . "Tempo templates")
285 (company-xcode . "Xcode")))
286 (put 'company-safe-backends 'risky-local-variable t)
288 (defun company-safe-backends-p (backends)
289 (and (consp backends)
290 (not (dolist (backend backends)
291 (unless (if (consp backend)
292 (company-safe-backends-p backend)
293 (assq backend company-safe-backends))
296 (defcustom company-backends '(company-elisp company-nxml company-css
297 company-eclim company-semantic company-xcode
299 (company-gtags company-etags company-dabbrev-code
300 company-pysmell company-keywords)
301 company-oddmuse company-files company-dabbrev)
302 "*The list of active back-ends (completion engines).
303 Each list elements can itself be a list of back-ends. In that case their
304 completions are merged. Otherwise only the first matching back-end returns
307 Each back-end is a function that takes a variable number of arguments.
308 The first argument is the command requested from the back-end. It is one
311 'prefix: The back-end should return the text to be completed. It must be
312 text immediately before `point'. Returning nil passes control to the next
313 back-end. The function should return 'stop if it should complete but cannot
314 \(e.g. if it is in the middle of a string\). If the returned value is only
315 part of the prefix (e.g. the part after \"->\" in C), the back-end may return a
316 cons of prefix and prefix length, which is then used in the
317 `company-minimum-prefix-length' test.
319 'candidates: The second argument is the prefix to be completed. The
320 return value should be a list of candidates that start with the prefix.
324 'sorted: The back-end may return t here to indicate that the candidates
325 are sorted and will not need to be sorted again.
327 'duplicates: If non-nil, company will take care of removing duplicates
330 'no-cache: Usually company doesn't ask for candidates again as completion
331 progresses, unless the back-end returns t for this command. The second
332 argument is the latest prefix.
334 'meta: The second argument is a completion candidate. The back-end should
335 return a (short) documentation string for it.
337 'doc-buffer: The second argument is a completion candidate. The back-end should
338 create a buffer (preferably with `company-doc-buffer'), fill it with
339 documentation and return it.
341 'location: The second argument is a completion candidate. The back-end can
342 return the cons of buffer and buffer location, or of file and line
343 number where the completion candidate was defined.
345 'require-match: If this value is t, the user is not allowed to enter anything
346 not offering as a candidate. Use with care! The default value nil gives the
347 user that choice with `company-require-match'. Return value 'never overrides
348 that option the other way around.
350 The back-end should return nil for all commands it does not support or
351 does not know about. It should also be callable interactively and use
352 `company-begin-backend' to start itself in that case."
357 ,@(mapcar (lambda (b) `(const :tag ,(cdr b) ,(car b)))
358 company-safe-backends)
359 (symbol :tag "User defined")
360 (repeat :tag "Merged Back-ends"
361 (choice :tag "Back-end"
362 ,@(mapcar (lambda (b)
363 `(const :tag ,(cdr b) ,(car b)))
364 company-safe-backends)
365 (symbol :tag "User defined"))))))
367 (put 'company-backends 'safe-local-variable 'company-safe-backends-p)
369 (defcustom company-completion-started-hook nil
370 "*Hook run when company starts completing.
371 The hook is called with one argument that is non-nil if the completion was
376 (defcustom company-completion-cancelled-hook nil
377 "*Hook run when company cancels completing.
378 The hook is called with one argument that is non-nil if the completion was
383 (defcustom company-completion-finished-hook nil
384 "*Hook run when company successfully completes.
385 The hook is called with the selected candidate as an argument."
389 (defcustom company-minimum-prefix-length 3
390 "*The minimum prefix length for automatic completion."
392 :type '(integer :tag "prefix length"))
394 (defcustom company-require-match 'company-explicit-action-p
395 "*If enabled, disallow non-matching input.
396 This can be a function do determine if a match is required.
398 This can be overridden by the back-end, if it returns t or 'never to
399 'require-match. `company-auto-complete' also takes precedence over this."
401 :type '(choice (const :tag "Off" nil)
402 (function :tag "Predicate function")
403 (const :tag "On, if user interaction took place"
404 'company-explicit-action-p)
405 (const :tag "On" t)))
407 (defcustom company-auto-complete 'company-explicit-action-p
408 "Determines when to auto-complete.
409 If this is enabled, all characters from `company-auto-complete-chars' complete
410 the selected completion. This can also be a function."
412 :type '(choice (const :tag "Off" nil)
413 (function :tag "Predicate function")
414 (const :tag "On, if user interaction took place"
415 'company-explicit-action-p)
416 (const :tag "On" t)))
418 (defcustom company-auto-complete-chars '(?\ ?\( ?\) ?. ?\" ?$ ?\' ?< ?| ?!)
419 "Determines which characters trigger an automatic completion.
420 See `company-auto-complete'. If this is a string, each string character causes
421 completion. If it is a list of syntax description characters (see
422 `modify-syntax-entry'), all characters with that syntax auto-complete.
424 This can also be a function, which is called with the new input and should
425 return non-nil if company should auto-complete.
427 A character that is part of a valid candidate never starts auto-completion."
429 :type '(choice (string :tag "Characters")
431 (const :tag "Whitespace" ?\ )
432 (const :tag "Symbol" ?_)
433 (const :tag "Opening parentheses" ?\()
434 (const :tag "Closing parentheses" ?\))
435 (const :tag "Word constituent" ?w)
436 (const :tag "Punctuation." ?.)
437 (const :tag "String quote." ?\")
438 (const :tag "Paired delimiter." ?$)
439 (const :tag "Expression quote or prefix operator." ?\')
440 (const :tag "Comment starter." ?<)
441 (const :tag "Comment ender." ?>)
442 (const :tag "Character-quote." ?/)
443 (const :tag "Generic string fence." ?|)
444 (const :tag "Generic comment fence." ?!))
445 (function :tag "Predicate function")))
447 (defcustom company-idle-delay .7
448 "*The idle delay in seconds until automatic completions starts.
449 A value of nil means never complete automatically, t means complete
450 immediately when a prefix of `company-minimum-prefix-length' is reached."
452 :type '(choice (const :tag "never (nil)" nil)
453 (const :tag "immediate (t)" t)
454 (number :tag "seconds")))
456 (defcustom company-begin-commands t
457 "*A list of commands following which company will start completing.
458 If this is t, it will complete after any command. See `company-idle-delay'.
460 Alternatively any command with a non-nil 'company-begin property is treated as
461 if it was on this list."
463 :type '(choice (const :tag "Any command" t)
464 (const :tag "Self insert command" '(self-insert-command))
465 (repeat :tag "Commands" function)))
467 (defcustom company-show-numbers nil
468 "*If enabled, show quick-access numbers for the first ten candidates."
470 :type '(choice (const :tag "off" nil)
471 (const :tag "on" t)))
473 (defvar company-end-of-buffer-workaround t
474 "*Work around a visualization bug when completing at the end of the buffer.
475 The work-around consists of adding a newline.")
477 ;;; mode ;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;
479 (defvar company-mode-map (make-sparse-keymap)
480 "Keymap used by `company-mode'.")
482 (defvar company-active-map
483 (let ((keymap (make-sparse-keymap)))
484 (define-key keymap "\e\e\e" 'company-abort)
485 (define-key keymap "\C-g" 'company-abort)
486 (define-key keymap (kbd "M-n") 'company-select-next)
487 (define-key keymap (kbd "M-p") 'company-select-previous)
488 (define-key keymap (kbd "<down>") 'company-select-next)
489 (define-key keymap (kbd "<up>") 'company-select-previous)
490 (define-key keymap [down-mouse-1] 'ignore)
491 (define-key keymap [down-mouse-3] 'ignore)
492 (define-key keymap [mouse-1] 'company-complete-mouse)
493 (define-key keymap [mouse-3] 'company-select-mouse)
494 (define-key keymap [up-mouse-1] 'ignore)
495 (define-key keymap [up-mouse-3] 'ignore)
496 (define-key keymap "\C-m" 'company-complete-selection)
497 (define-key keymap "\t" 'company-complete-common)
498 (define-key keymap (kbd "<f1>") 'company-show-doc-buffer)
499 (define-key keymap "\C-w" 'company-show-location)
500 (define-key keymap "\C-s" 'company-search-candidates)
501 (define-key keymap "\C-\M-s" 'company-filter-candidates)
503 (define-key keymap (vector (+ (aref (kbd "M-0") 0) i))
504 `(lambda () (interactive) (company-complete-number ,i))))
507 "Keymap that is enabled during an active completion.")
509 (defvar company--disabled-backends nil)
511 (defun company-init-backend (backend)
512 (and (symbolp backend)
513 (not (fboundp backend))
514 (ignore-errors (require backend nil t)))
516 (if (or (symbolp backend)
518 (if (ignore-errors (funcall backend 'init) t)
519 (put backend 'company-init t)
520 (put backend 'company-init 'failed)
521 (unless (memq backend company--disabled-backends)
522 (message "Company back-end '%s' could not be initialized"
524 (push backend company--disabled-backends))
526 (mapc 'company-init-backend backend)))
528 (defvar company-default-lighter " company")
530 (defvar company-lighter company-default-lighter)
531 (make-variable-buffer-local 'company-lighter)
534 (define-minor-mode company-mode
535 "\"complete anything\"; in in-buffer completion framework.
536 Completion starts automatically, depending on the values
537 `company-idle-delay' and `company-minimum-prefix-length'.
539 Completion can be controlled with the commands:
540 `company-complete-common', `company-complete-selection', `company-complete',
541 `company-select-next', `company-select-previous'. If these commands are
542 called before `company-idle-delay', completion will also start.
544 Completions can be searched with `company-search-candidates' or
545 `company-filter-candidates'. These can be used while completion is
548 The completion data is retrieved using `company-backends' and displayed using
549 `company-frontends'. If you want to start a specific back-end, call it
550 interactively or use `company-begin-backend'.
552 regular keymap (`company-mode-map'):
555 keymap during active completions (`company-active-map'):
557 \\{company-active-map}"
558 nil company-lighter company-mode-map
561 (add-hook 'pre-command-hook 'company-pre-command nil t)
562 (add-hook 'post-command-hook 'company-post-command nil t)
563 (mapc 'company-init-backend company-backends))
564 (remove-hook 'pre-command-hook 'company-pre-command t)
565 (remove-hook 'post-command-hook 'company-post-command t)
567 (kill-local-variable 'company-point)))
569 (define-globalized-minor-mode global-company-mode company-mode
570 (lambda () (company-mode 1)))
572 (defsubst company-assert-enabled ()
574 (company-uninstall-map)
575 (error "Company not enabled")))
577 ;;; keymaps ;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;
579 (defvar company-overriding-keymap-bound nil)
580 (make-variable-buffer-local 'company-overriding-keymap-bound)
582 (defvar company-old-keymap nil)
583 (make-variable-buffer-local 'company-old-keymap)
585 (defvar company-my-keymap nil)
586 (make-variable-buffer-local 'company-my-keymap)
588 (defsubst company-enable-overriding-keymap (keymap)
589 (setq company-my-keymap keymap)
590 (when company-overriding-keymap-bound
591 (company-uninstall-map)))
593 (defun company-install-map ()
594 (unless (or company-overriding-keymap-bound
595 (null company-my-keymap))
596 (setq company-old-keymap overriding-terminal-local-map
597 overriding-terminal-local-map company-my-keymap
598 company-overriding-keymap-bound t)))
600 (defun company-uninstall-map ()
601 (when (eq overriding-terminal-local-map company-my-keymap)
602 (setq overriding-terminal-local-map company-old-keymap
603 company-overriding-keymap-bound nil)))
606 ;; Emacs calculates the active keymaps before reading the event. That means we
607 ;; cannot change the keymap from a timer. So we send a bogus command.
608 (defun company-ignore ()
610 (setq this-command last-command))
612 (global-set-key '[31415926] 'company-ignore)
614 (defun company-input-noop ()
615 (push 31415926 unread-command-events))
618 ;; posn-col-row is incorrect in older Emacsen when line-spacing is set
619 (defun company--col-row (&optional pos)
620 (let ((posn (posn-at-point pos)))
621 (cons (car (posn-col-row posn)) (cdr (posn-actual-col-row posn)))))
623 (defsubst company--column (&optional pos)
624 (car (posn-col-row (posn-at-point pos))))
626 (defsubst company--row (&optional pos)
627 (cdr (posn-actual-col-row (posn-at-point pos))))
629 ;;; backends ;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;
631 (defun company-grab (regexp &optional expression limit)
632 (when (looking-back regexp limit)
633 (or (match-string-no-properties (or expression 0)) "")))
635 (defun company-grab-line (regexp &optional expression)
636 (company-grab regexp expression (point-at-bol)))
638 (defun company-grab-symbol ()
639 (if (looking-at "\\_>")
640 (buffer-substring (point) (save-excursion (skip-syntax-backward "w_")
642 (unless (and (char-after) (memq (char-syntax (char-after)) '(?w ?_)))
645 (defun company-grab-word ()
646 (if (looking-at "\\>")
647 (buffer-substring (point) (save-excursion (skip-syntax-backward "w")
649 (unless (and (char-after) (eq (char-syntax (char-after)) ?w))
652 (defun company-in-string-or-comment ()
653 (let ((ppss (syntax-ppss)))
654 (or (car (setq ppss (nthcdr 3 ppss)))
655 (car (setq ppss (cdr ppss)))
658 (if (fboundp 'locate-dominating-file)
659 (defalias 'company-locate-dominating-file 'locate-dominating-file)
660 (defun company-locate-dominating-file (file name)
662 (let ((dir (file-name-directory file))
664 (while (not (equal dir prev-dir))
665 (when (file-exists-p (expand-file-name name dir))
668 dir (file-name-directory (directory-file-name dir))))))))
670 (defun company-call-backend (&rest args)
671 (if (functionp company-backend)
672 (apply company-backend args)
673 (apply 'company--multi-backend-adapter company-backend args)))
675 (defun company--multi-backend-adapter (backends command &rest args)
678 (apply 'append (mapcar (lambda (backend) (apply backend command args))
684 (dolist (backend backends)
685 (when (setq value (apply backend command args))
688 ;;; completion mechanism ;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;
690 (defvar company-backend nil)
691 (make-variable-buffer-local 'company-backend)
693 (defvar company-prefix nil)
694 (make-variable-buffer-local 'company-prefix)
696 (defvar company-candidates nil)
697 (make-variable-buffer-local 'company-candidates)
699 (defvar company-candidates-length nil)
700 (make-variable-buffer-local 'company-candidates-length)
702 (defvar company-candidates-cache nil)
703 (make-variable-buffer-local 'company-candidates-cache)
705 (defvar company-candidates-predicate nil)
706 (make-variable-buffer-local 'company-candidates-predicate)
708 (defvar company-common nil)
709 (make-variable-buffer-local 'company-common)
711 (defvar company-selection 0)
712 (make-variable-buffer-local 'company-selection)
714 (defvar company-selection-changed nil)
715 (make-variable-buffer-local 'company-selection-changed)
717 (defvar company--explicit-action nil
718 "Non-nil, if explicit completion took place.")
719 (make-variable-buffer-local 'company--explicit-action)
721 (defvar company--point-max nil)
722 (make-variable-buffer-local 'company--point-max)
724 (defvar company-point nil)
725 (make-variable-buffer-local 'company-point)
727 (defvar company-timer nil)
729 (defvar company-added-newline nil)
730 (make-variable-buffer-local 'company-added-newline)
732 (defsubst company-strip-prefix (str)
733 (substring str (length company-prefix)))
735 (defun company-explicit-action-p ()
736 "Return whether explicit completion action was taken by the user."
737 (or company--explicit-action
738 company-selection-changed))
740 (defsubst company-reformat (candidate)
741 ;; company-ispell needs this, because the results are always lower-case
742 ;; It's mory efficient to fix it only when they are displayed.
743 (concat company-prefix (substring candidate (length company-prefix))))
745 (defun company--should-complete ()
746 (and (not (or buffer-read-only overriding-terminal-local-map
747 overriding-local-map))
748 (eq company-idle-delay t)
749 (or (eq t company-begin-commands)
750 (memq this-command company-begin-commands)
751 (and (symbolp this-command) (get this-command 'company-begin)))
752 (not (and transient-mark-mode mark-active))))
754 (defsubst company-call-frontends (command)
755 (dolist (frontend company-frontends)
757 (funcall frontend command)
758 (error (error "Company: Front-end %s error \"%s\" on command %s"
759 frontend (error-message-string err) command)))))
761 (defsubst company-set-selection (selection &optional force-update)
762 (setq selection (max 0 (min (1- company-candidates-length) selection)))
763 (when (or force-update (not (equal selection company-selection)))
764 (setq company-selection selection
765 company-selection-changed t)
766 (company-call-frontends 'update)))
768 (defun company-apply-predicate (candidates predicate)
770 (dolist (c candidates)
771 (when (funcall predicate c)
775 (defun company-update-candidates (candidates)
776 (setq company-candidates-length (length candidates))
777 (if (> company-selection 0)
778 ;; Try to restore the selection
779 (let ((selected (nth company-selection company-candidates)))
780 (setq company-selection 0
781 company-candidates candidates)
783 (while (and candidates (string< (pop candidates) selected))
784 (incf company-selection))
786 ;; Make sure selection isn't out of bounds.
787 (setq company-selection (min (1- company-candidates-length)
788 company-selection)))))
789 (setq company-selection 0
790 company-candidates candidates))
792 (push (cons company-prefix company-candidates) company-candidates-cache)
794 (let ((completion-ignore-case (company-call-backend 'ignore-case)))
795 (setq company-common (try-completion company-prefix company-candidates)))
796 (when (eq company-common t)
797 (setq company-candidates nil)))
799 (defun company-calculate-candidates (prefix)
800 (let ((candidates (cdr (assoc prefix company-candidates-cache))))
802 (when company-candidates-cache
803 (let ((len (length prefix))
804 (completion-ignore-case (company-call-backend 'ignore-case))
806 (dotimes (i (1+ len))
807 (when (setq prev (cdr (assoc (substring prefix 0 (- len i))
808 company-candidates-cache)))
809 (setq candidates (all-completions prefix prev))
811 ;; no cache match, call back-end
813 (setq candidates (company-call-backend 'candidates prefix))
814 (when company-candidates-predicate
816 (company-apply-predicate candidates
817 company-candidates-predicate)))
818 (unless (company-call-backend 'sorted)
819 (setq candidates (sort candidates 'string<)))
820 (when (company-call-backend 'duplicates)
822 (let ((c2 candidates))
824 (setcdr c2 (progn (while (equal (pop c2) (car c2)))
826 (if (or (cdr candidates)
827 (not (equal (car candidates) prefix)))
828 ;; Don't start when already completed and unique.
830 ;; Not the right place? maybe when setting?
831 (and company-candidates t))))
833 (defun company-idle-begin (buf win tick pos)
835 (eq buf (current-buffer))
836 (eq win (selected-window))
837 (eq tick (buffer-chars-modified-tick))
839 (not company-candidates)
840 (not (equal (point) company-point))
841 (let ((company-idle-delay t)
842 (company-begin-commands t))
844 (when company-candidates
846 (company-post-command)))))
848 (defun company-auto-begin ()
849 (company-assert-enabled)
851 (not company-candidates)
852 (let ((company-idle-delay t)
853 (company-minimum-prefix-length 0)
854 (company-begin-commands t))
856 ;; Return non-nil if active.
859 (defun company-manual-begin ()
861 (setq company--explicit-action t)
862 (company-auto-begin))
864 (defun company-require-match-p ()
865 (let ((backend-value (company-call-backend 'require-match)))
866 (or (eq backend-value t)
867 (and (if (functionp company-require-match)
868 (funcall company-require-match)
869 (eq company-require-match t))
870 (not (eq backend-value 'never))))))
872 (defun company-punctuation-p (input)
873 "Return non-nil, if input starts with punctuation or parentheses."
874 (memq (char-syntax (string-to-char input)) '(?. ?\( ?\))))
876 (defun company-auto-complete-p (input)
877 "Return non-nil, if input starts with punctuation or parentheses."
878 (and (if (functionp company-auto-complete)
879 (funcall company-auto-complete)
880 company-auto-complete)
881 (if (functionp company-auto-complete-chars)
882 (funcall company-auto-complete-chars input)
883 (if (consp company-auto-complete-chars)
884 (memq (char-syntax (string-to-char input))
885 company-auto-complete-chars)
886 (string-match (substring input 0 1) company-auto-complete-chars)))))
888 (defun company--incremental-p ()
889 (and (> (point) company-point)
890 (> (point-max) company--point-max)
891 (not (eq this-command 'backward-delete-char-untabify))
892 (equal (buffer-substring (- company-point (length company-prefix))
896 (defsubst company--string-incremental-p (old-prefix new-prefix)
897 (and (> (length new-prefix) (length old-prefix))
898 (equal old-prefix (substring new-prefix 0 (length old-prefix)))))
900 (defun company--continue-failed (new-prefix)
901 (when (company--incremental-p)
902 (let ((input (buffer-substring-no-properties (point) company-point)))
904 ((company-auto-complete-p input)
907 (goto-char company-point)
908 (company-complete-selection)
910 ((and (company--string-incremental-p company-prefix new-prefix)
911 (company-require-match-p))
912 ;; wrong incremental input, but required match
913 (backward-delete-char (length input))
915 (message "Matching input is required")
917 ((equal company-prefix (car company-candidates))
918 ;; last input was actually success
919 (company-cancel company-prefix)
922 (defun company--good-prefix-p (prefix)
923 (and (or (company-explicit-action-p)
924 (>= (or (cdr-safe prefix) (length prefix))
925 company-minimum-prefix-length))
926 (stringp (or (car-safe prefix) prefix))))
928 (defun company--continue ()
929 (when (company-call-backend 'no-cache company-prefix)
930 ;; Don't complete existing candidates, fetch new ones.
931 (setq company-candidates-cache nil))
932 (let* ((new-prefix (company-call-backend 'prefix))
933 (c (when (and (company--good-prefix-p new-prefix)
934 (setq new-prefix (or (car-safe new-prefix) new-prefix))
935 (= (- (point) (length new-prefix))
936 (- company-point (length company-prefix))))
937 (setq new-prefix (or (car-safe new-prefix) new-prefix))
938 (company-calculate-candidates new-prefix))))
941 ;; t means complete/unique.
942 (company-cancel new-prefix)
946 (setq company-prefix new-prefix)
947 (company-update-candidates c)
949 (t (company--continue-failed new-prefix)))
952 (defun company--begin-new ()
954 (dolist (backend (if company-backend
955 ;; prefer manual override
956 (list company-backend)
959 (if (or (symbolp backend)
961 (when (or (not (symbolp backend))
962 (eq t (get backend 'company-init))
963 (unless (get backend 'company-init)
964 (company-init-backend backend)))
965 (funcall backend 'prefix))
966 (company--multi-backend-adapter backend 'prefix)))
968 (when (company--good-prefix-p prefix)
969 (setq prefix (or (car-safe prefix) prefix)
970 company-backend backend
971 c (company-calculate-candidates prefix))
972 ;; t means complete/unique. We don't start, so no hooks.
974 (setq company-prefix prefix)
975 (when (symbolp backend)
976 (setq company-lighter (concat " " (symbol-name backend))))
977 (company-update-candidates c)
978 (run-hook-with-args 'company-completion-started-hook
979 (company-explicit-action-p))
980 (company-call-frontends 'show)))
983 (defun company-begin ()
984 (setq company-candidates
985 (or (and company-candidates (company--continue))
986 (and (company--should-complete) (company--begin-new))))
987 (when company-candidates
988 (when (and company-end-of-buffer-workaround (eobp))
989 (save-excursion (insert "\n"))
990 (setq company-added-newline (buffer-chars-modified-tick)))
991 (setq company-point (point)
992 company--point-max (point-max))
993 (company-enable-overriding-keymap company-active-map)
994 (company-call-frontends 'update)))
996 (defun company-cancel (&optional result)
997 (and company-added-newline
998 (> (point-max) (point-min))
999 (let ((tick (buffer-chars-modified-tick)))
1000 (delete-region (1- (point-max)) (point-max))
1001 (equal tick company-added-newline))
1002 ;; Only set unmodified when tick remained the same since insert.
1003 (set-buffer-modified-p nil))
1004 (when company-prefix
1005 (if (stringp result)
1006 (run-hook-with-args 'company-completion-finished-hook result)
1007 (run-hook-with-args 'company-completion-cancelled-hook result)))
1008 (setq company-added-newline nil
1011 company-candidates nil
1012 company-candidates-length nil
1013 company-candidates-cache nil
1014 company-candidates-predicate nil
1017 company-selection-changed nil
1018 company--explicit-action nil
1019 company-lighter company-default-lighter
1020 company--point-max nil
1023 (cancel-timer company-timer))
1024 (company-search-mode 0)
1025 (company-call-frontends 'hide)
1026 (company-enable-overriding-keymap nil))
1028 (defun company-abort ()
1031 ;; Don't start again, unless started manually.
1032 (setq company-point (point)))
1034 (defun company-finish (result)
1035 (insert (company-strip-prefix result))
1036 (company-cancel result)
1037 ;; Don't start again, unless started manually.
1038 (setq company-point (point)))
1040 (defsubst company-keep (command)
1041 (and (symbolp command) (get command 'company-keep)))
1043 (defun company-pre-command ()
1044 (unless (company-keep this-command)
1046 (when company-candidates
1047 (company-call-frontends 'pre-command))
1048 (error (message "Company: An error occurred in pre-command")
1049 (message "%s" (error-message-string err))
1052 (cancel-timer company-timer)
1053 (setq company-timer nil))
1054 (company-uninstall-map))
1056 (defun company-post-command ()
1057 (unless (company-keep this-command)
1060 (unless (equal (point) company-point)
1062 (if company-candidates
1063 (company-call-frontends 'post-command)
1064 (and (numberp company-idle-delay)
1065 (or (eq t company-begin-commands)
1066 (memq this-command company-begin-commands))
1068 (run-with-timer company-idle-delay nil
1070 (current-buffer) (selected-window)
1071 (buffer-chars-modified-tick) (point))))))
1072 (error (message "Company: An error occurred in post-command")
1073 (message "%s" (error-message-string err))
1075 (company-install-map))
1077 ;;; search ;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;
1079 (defvar company-search-string nil)
1080 (make-variable-buffer-local 'company-search-string)
1082 (defvar company-search-lighter " Search: \"\"")
1083 (make-variable-buffer-local 'company-search-lighter)
1085 (defvar company-search-old-map nil)
1086 (make-variable-buffer-local 'company-search-old-map)
1088 (defvar company-search-old-selection 0)
1089 (make-variable-buffer-local 'company-search-old-selection)
1091 (defun company-search (text lines)
1092 (let ((quoted (regexp-quote text))
1094 (dolist (line lines)
1095 (when (string-match quoted line (length company-prefix))
1099 (defun company-search-printing-char ()
1101 (company-search-assert-enabled)
1102 (setq company-search-string
1103 (concat (or company-search-string "") (string last-command-event))
1104 company-search-lighter (concat " Search: \"" company-search-string
1106 (let ((pos (company-search company-search-string
1107 (nthcdr company-selection company-candidates))))
1110 (company-set-selection (+ company-selection pos) t))))
1112 (defun company-search-repeat-forward ()
1113 "Repeat the incremental search in completion candidates forward."
1115 (company-search-assert-enabled)
1116 (let ((pos (company-search company-search-string
1117 (cdr (nthcdr company-selection
1118 company-candidates)))))
1121 (company-set-selection (+ company-selection pos 1) t))))
1123 (defun company-search-repeat-backward ()
1124 "Repeat the incremental search in completion candidates backwards."
1126 (company-search-assert-enabled)
1127 (let ((pos (company-search company-search-string
1128 (nthcdr (- company-candidates-length
1130 (reverse company-candidates)))))
1133 (company-set-selection (- company-selection pos 1) t))))
1135 (defun company-create-match-predicate ()
1136 (setq company-candidates-predicate
1137 `(lambda (candidate)
1138 ,(if company-candidates-predicate
1139 `(and (string-match ,company-search-string candidate)
1140 (funcall ,company-candidates-predicate
1142 `(string-match ,company-search-string candidate))))
1143 (company-update-candidates
1144 (company-apply-predicate company-candidates company-candidates-predicate))
1145 ;; Invalidate cache.
1146 (setq company-candidates-cache (cons company-prefix company-candidates)))
1148 (defun company-filter-printing-char ()
1150 (company-search-assert-enabled)
1151 (company-search-printing-char)
1152 (company-create-match-predicate)
1153 (company-call-frontends 'update))
1155 (defun company-search-kill-others ()
1156 "Limit the completion candidates to the ones matching the search string."
1158 (company-search-assert-enabled)
1159 (company-create-match-predicate)
1160 (company-search-mode 0)
1161 (company-call-frontends 'update))
1163 (defun company-search-abort ()
1164 "Abort searching the completion candidates."
1166 (company-search-assert-enabled)
1167 (company-set-selection company-search-old-selection t)
1168 (company-search-mode 0))
1170 (defun company-search-other-char ()
1172 (company-search-assert-enabled)
1173 (company-search-mode 0)
1174 (when last-input-event
1175 (clear-this-command-keys t)
1176 (setq unread-command-events (list last-input-event))))
1178 (defvar company-search-map
1180 (keymap (make-keymap)))
1181 (if (fboundp 'max-char)
1182 (set-char-table-range (nth 1 keymap) (cons #x100 (max-char))
1183 'company-search-printing-char)
1185 ;; obselete in Emacs 23
1186 (let ((l (generic-character-list))
1187 (table (nth 1 keymap)))
1189 (set-char-table-default table (car l) 'company-search-printing-char)
1190 (setq l (cdr l))))))
1191 (define-key keymap [t] 'company-search-other-char)
1193 (define-key keymap (make-string 1 i) 'company-search-other-char)
1196 (define-key keymap (vector i) 'company-search-printing-char)
1198 (let ((meta-map (make-sparse-keymap)))
1199 (define-key keymap (char-to-string meta-prefix-char) meta-map)
1200 (define-key keymap [escape] meta-map))
1201 (define-key keymap (vector meta-prefix-char t) 'company-search-other-char)
1202 (define-key keymap "\e\e\e" 'company-search-other-char)
1203 (define-key keymap [escape escape escape] 'company-search-other-char)
1205 (define-key keymap "\C-g" 'company-search-abort)
1206 (define-key keymap "\C-s" 'company-search-repeat-forward)
1207 (define-key keymap "\C-r" 'company-search-repeat-backward)
1208 (define-key keymap "\C-o" 'company-search-kill-others)
1210 "Keymap used for incrementally searching the completion candidates.")
1212 (define-minor-mode company-search-mode
1213 "Search mode for completion candidates.
1214 Don't start this directly, use `company-search-candidates' or
1215 `company-filter-candidates'."
1216 nil company-search-lighter nil
1217 (if company-search-mode
1218 (if (company-manual-begin)
1220 (setq company-search-old-selection company-selection)
1221 (company-call-frontends 'update))
1222 (setq company-search-mode nil))
1223 (kill-local-variable 'company-search-string)
1224 (kill-local-variable 'company-search-lighter)
1225 (kill-local-variable 'company-search-old-selection)
1226 (company-enable-overriding-keymap company-active-map)))
1228 (defsubst company-search-assert-enabled ()
1229 (company-assert-enabled)
1230 (unless company-search-mode
1231 (company-uninstall-map)
1232 (error "Company not in search mode")))
1234 (defun company-search-candidates ()
1235 "Start searching the completion candidates incrementally.
1237 \\<company-search-map>Search can be controlled with the commands:
1238 - `company-search-repeat-forward' (\\[company-search-repeat-forward])
1239 - `company-search-repeat-backward' (\\[company-search-repeat-backward])
1240 - `company-search-abort' (\\[company-search-abort])
1242 Regular characters are appended to the search string.
1244 The command `company-search-kill-others' (\\[company-search-kill-others]) uses
1245 the search string to limit the completion candidates."
1247 (company-search-mode 1)
1248 (company-enable-overriding-keymap company-search-map))
1250 (defvar company-filter-map
1251 (let ((keymap (make-keymap)))
1252 (define-key keymap [remap company-search-printing-char]
1253 'company-filter-printing-char)
1254 (set-keymap-parent keymap company-search-map)
1256 "Keymap used for incrementally searching the completion candidates.")
1258 (defun company-filter-candidates ()
1259 "Start filtering the completion candidates incrementally.
1260 This works the same way as `company-search-candidates' immediately
1261 followed by `company-search-kill-others' after each input."
1263 (company-search-mode 1)
1264 (company-enable-overriding-keymap company-filter-map))
1266 ;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;
1268 (defun company-select-next ()
1269 "Select the next candidate in the list."
1271 (when (company-manual-begin)
1272 (company-set-selection (1+ company-selection))))
1274 (defun company-select-previous ()
1275 "Select the previous candidate in the list."
1277 (when (company-manual-begin)
1278 (company-set-selection (1- company-selection))))
1280 (defun company-select-mouse (event)
1281 "Select the candidate picked by the mouse."
1283 (when (nth 4 (event-start event))
1284 (company-set-selection (- (cdr (posn-actual-col-row (event-start event)))
1289 (defun company-complete-mouse (event)
1290 "Complete the candidate picked by the mouse."
1292 (when (company-select-mouse event)
1293 (company-complete-selection)))
1295 (defun company-complete-selection ()
1296 "Complete the selected candidate."
1298 (when (company-manual-begin)
1299 (company-finish (nth company-selection company-candidates))))
1301 (defun company-complete-common ()
1302 "Complete the common part of all candidates."
1304 (when (company-manual-begin)
1305 (if (and (not (cdr company-candidates))
1306 (equal company-common (car company-candidates)))
1307 (company-complete-selection)
1308 (insert (company-strip-prefix company-common)))))
1310 (defun company-complete ()
1311 "Complete the common part of all candidates or the current selection.
1312 The first time this is called, the common part is completed, the second time, or
1313 when the selection has been changed, the selected candidate is completed."
1315 (when (company-manual-begin)
1316 (if (or company-selection-changed
1317 (eq last-command 'company-complete-common))
1318 (call-interactively 'company-complete-selection)
1319 (call-interactively 'company-complete-common)
1320 (setq this-command 'company-complete-common))))
1322 (defun company-complete-number (n)
1323 "Complete the Nth candidate.
1324 To show the number next to the candidates in some back-ends, enable
1325 `company-show-numbers'."
1326 (when (company-manual-begin)
1327 (and (< n 1) (> n company-candidates-length)
1328 (error "No candidate number %d" n))
1330 (company-finish (nth n company-candidates))))
1332 ;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;
1334 (defconst company-space-strings-limit 100)
1336 (defconst company-space-strings
1338 (dotimes (i company-space-strings-limit)
1339 (push (make-string (- company-space-strings-limit 1 i) ?\ ) lst))
1340 (apply 'vector lst)))
1342 (defsubst company-space-string (len)
1343 (if (< len company-space-strings-limit)
1344 (aref company-space-strings len)
1345 (make-string len ?\ )))
1347 (defsubst company-safe-substring (str from &optional to)
1348 (let ((len (length str)))
1351 (if (and to (> to len))
1352 (concat (substring str from)
1353 (company-space-string (- to len)))
1354 (substring str from to)))))
1356 ;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;
1358 (defvar company-last-metadata nil)
1359 (make-variable-buffer-local 'company-last-metadata)
1361 (defun company-fetch-metadata ()
1362 (let ((selected (nth company-selection company-candidates)))
1363 (unless (equal selected (car company-last-metadata))
1364 (setq company-last-metadata
1365 (cons selected (company-call-backend 'meta selected))))
1366 (cdr company-last-metadata)))
1368 (defun company-doc-buffer (&optional string)
1369 (with-current-buffer (get-buffer-create "*Company meta-data*")
1373 (defmacro company--electric-do (&rest body)
1374 (declare (indent 0) (debug t))
1375 `(when (company-manual-begin)
1376 (save-window-excursion
1377 (let ((height (window-height))
1378 (row (company--row)))
1380 (and (< (window-height) height)
1381 (< (- (window-height) row 2) company-tooltip-limit)
1382 (recenter (- (window-height) row 2)))
1383 (while (eq 'scroll-other-window
1384 (key-binding (vector (list (read-event)))))
1385 (call-interactively 'scroll-other-window))
1386 (when last-input-event
1387 (clear-this-command-keys t)
1388 (setq unread-command-events (list last-input-event)))))))
1390 (defun company-show-doc-buffer ()
1391 "Temporarily show a buffer with the complete documentation for the selection."
1393 (company--electric-do
1394 (let ((selected (nth company-selection company-candidates)))
1395 (display-buffer (or (company-call-backend 'doc-buffer selected)
1396 (error "No documentation available")) t))))
1397 (put 'company-show-doc-buffer 'company-keep t)
1399 (defun company-show-location ()
1400 "Temporarily display a buffer showing the selected candidate in context."
1402 (company--electric-do
1403 (let* ((selected (nth company-selection company-candidates))
1404 (location (company-call-backend 'location selected))
1405 (pos (or (cdr location) (error "No location available")))
1406 (buffer (or (and (bufferp (car location)) (car location))
1407 (find-file-noselect (car location) t))))
1408 (with-selected-window (display-buffer buffer t)
1409 (if (bufferp (car location))
1412 (set-window-start nil (point))))))
1413 (put 'company-show-location 'company-keep t)
1415 ;;; package functions ;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;
1417 (defvar company-callback nil)
1418 (make-variable-buffer-local 'company-callback)
1420 (defvar company-begin-with-marker nil)
1421 (make-variable-buffer-local 'company-begin-with-marker)
1423 (defun company-remove-callback (&optional ignored)
1424 (remove-hook 'company-completion-finished-hook company-callback t)
1425 (remove-hook 'company-completion-cancelled-hook 'company-remove-callback t)
1426 (remove-hook 'company-completion-finished-hook 'company-remove-callback t)
1427 (when company-begin-with-marker
1428 (set-marker company-begin-with-marker nil)))
1430 (defun company-begin-backend (backend &optional callback)
1431 "Start a completion at point using BACKEND."
1432 (interactive (let ((val (completing-read "Company back-end: "
1434 'functionp nil "company-")))
1436 (list (intern val)))))
1437 (when (setq company-callback callback)
1438 (add-hook 'company-completion-finished-hook company-callback nil t))
1439 (add-hook 'company-completion-cancelled-hook 'company-remove-callback nil t)
1440 (add-hook 'company-completion-finished-hook 'company-remove-callback nil t)
1441 (setq company-backend backend)
1442 ;; Return non-nil if active.
1443 (or (company-manual-begin)
1444 (error "Cannot complete at point")))
1446 (defun company-begin-with (candidates
1447 &optional prefix-length require-match callback)
1448 "Start a completion at point.
1449 CANDIDATES is the list of candidates to use and PREFIX-LENGTH is the length of
1450 the prefix that already is in the buffer before point. It defaults to 0.
1452 CALLBACK is a function called with the selected result if the user successfully
1453 completes the input.
1456 \(company-begin-with '\(\"foo\" \"foobar\" \"foobarbaz\"\)\)"
1457 (setq company-begin-with-marker (copy-marker (point) t))
1458 (company-begin-backend
1459 `(lambda (command &optional arg &rest ignored)
1461 ((eq command 'prefix)
1462 (when (equal (point) (marker-position company-begin-with-marker))
1463 (buffer-substring ,(- (point) (or prefix-length 0)) (point))))
1464 ((eq command 'candidates)
1465 (all-completions arg ',candidates))
1466 ((eq command 'require-match)
1470 ;;; pseudo-tooltip ;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;
1472 (defvar company-pseudo-tooltip-overlay nil)
1473 (make-variable-buffer-local 'company-pseudo-tooltip-overlay)
1475 (defvar company-tooltip-offset 0)
1476 (make-variable-buffer-local 'company-tooltip-offset)
1478 (defun company-pseudo-tooltip-update-offset (selection num-lines limit)
1481 (setq company-tooltip-offset
1482 (max (min selection company-tooltip-offset)
1483 (- selection -1 limit)))
1485 (when (<= company-tooltip-offset 1)
1487 (setq company-tooltip-offset 0))
1489 (when (>= company-tooltip-offset (- num-lines limit 1))
1491 (when (= selection (1- num-lines))
1492 (decf company-tooltip-offset)
1493 (when (<= company-tooltip-offset 1)
1494 (setq company-tooltip-offset 0)
1501 (defsubst company-round-tab (arg)
1502 (* (/ (+ arg tab-width) tab-width) tab-width))
1504 (defun company-untabify (str)
1505 (let* ((pieces (split-string str "\t"))
1508 (setcar copy (company-safe-substring
1509 (car copy) 0 (company-round-tab (string-width (car copy)))))
1511 (apply 'concat pieces)))
1513 (defun company-fill-propertize (line width selected)
1514 (setq line (company-safe-substring line 0 width))
1515 (add-text-properties 0 width '(face company-tooltip
1516 mouse-face company-tooltip-mouse)
1518 (add-text-properties 0 (length company-common)
1519 '(face company-tooltip-common
1520 mouse-face company-tooltip-mouse)
1523 (if (and company-search-string
1524 (string-match (regexp-quote company-search-string) line
1525 (length company-prefix)))
1527 (add-text-properties (match-beginning 0) (match-end 0)
1528 '(face company-tooltip-selection)
1530 (when (< (match-beginning 0) (length company-common))
1531 (add-text-properties (match-beginning 0) (length company-common)
1532 '(face company-tooltip-common-selection)
1534 (add-text-properties 0 width '(face company-tooltip-selection
1535 mouse-face company-tooltip-selection)
1537 (add-text-properties 0 (length company-common)
1538 '(face company-tooltip-common-selection
1539 mouse-face company-tooltip-selection)
1545 (defun company-buffer-lines (beg end)
1547 (let ((row (company--row))
1549 (while (and (equal (move-to-window-line (incf row)) row)
1551 (push (buffer-substring beg (min end (1- (point)))) lines)
1553 (unless (eq beg end)
1554 (push (buffer-substring beg end) lines))
1557 (defsubst company-modify-line (old new offset)
1558 (concat (company-safe-substring old 0 offset)
1560 (company-safe-substring old (+ offset (length new)))))
1562 (defsubst company--length-limit (lst limit)
1563 (if (nthcdr limit lst)
1567 (defun company--replacement-string (lines old column nl &optional align-top)
1569 (let ((width (length (car lines))))
1570 (when (> width (- (window-width) column))
1571 (setq column (max 0 (- (window-width) width)))))
1575 ;; untouched lines first
1576 (dotimes (i (- (length old) (length lines)))
1577 (push (pop old) new)))
1578 ;; length into old lines.
1580 (push (company-modify-line (pop old) (pop lines) column) new))
1581 ;; Append whole new lines.
1583 (push (concat (company-space-string column) (pop lines)) new))
1584 (concat (when nl "\n")
1585 (mapconcat 'identity (nreverse new) "\n")
1588 (defun company--create-lines (selection limit)
1590 (let ((len company-candidates-length)
1599 ;; Scroll to offset.
1600 (setq limit (company-pseudo-tooltip-update-offset selection len limit))
1602 (when (> company-tooltip-offset 0)
1603 (setq previous (format "...(%d)" company-tooltip-offset)))
1605 (setq remainder (- len limit company-tooltip-offset)
1606 remainder (when (> remainder 0)
1607 (setq remainder (format "...(%d)" remainder))))
1609 (decf selection company-tooltip-offset)
1610 (setq width (max (length previous) (length remainder))
1611 lines (nthcdr company-tooltip-offset company-candidates)
1616 (setq width (max (length (pop lines-copy)) width)))
1617 (setq width (min width (window-width)))
1619 (setq lines-copy lines)
1621 ;; number can make tooltip too long
1622 (when company-show-numbers
1623 (setq numbered company-tooltip-offset))
1626 (push (propertize (company-safe-substring previous 0 width)
1627 'face 'company-tooltip)
1631 (push (company-fill-propertize
1632 (if (>= numbered 10)
1633 (company-reformat (pop lines))
1636 (company-safe-substring (company-reformat (pop lines))
1639 width (equal i selection))
1643 (push (propertize (company-safe-substring remainder 0 width)
1644 'face 'company-tooltip)
1647 (setq lines (nreverse new))))
1651 (defsubst company--window-inner-height ()
1652 (let ((edges (window-inside-edges (selected-window))))
1653 (- (nth 3 edges) (nth 1 edges))))
1655 (defsubst company--pseudo-tooltip-height ()
1656 "Calculate the appropriate tooltip height.
1657 Returns a negative number if the tooltip should be displayed above point."
1658 (let* ((lines (count-lines (window-start) (point-at-bol)))
1659 (below (- (company--window-inner-height) 1 lines)))
1660 (if (and (< below (min company-tooltip-minimum company-candidates-length))
1662 (- (max 3 (min company-tooltip-limit lines)))
1663 (max 3 (min company-tooltip-limit below)))))
1665 (defun company-pseudo-tooltip-show (row column selection)
1666 (company-pseudo-tooltip-hide)
1671 (let* ((height (company--pseudo-tooltip-height))
1675 (setq row (+ row height -1)
1678 (let* ((nl (< (move-to-window-line row) row))
1680 (end (save-excursion
1681 (move-to-window-line (+ row (abs height)))
1683 (ov (make-overlay beg end))
1684 (args (list (mapcar 'company-untabify
1685 (company-buffer-lines beg end))
1688 (setq company-pseudo-tooltip-overlay ov)
1689 (overlay-put ov 'company-replacement-args args)
1690 (overlay-put ov 'company-before
1691 (apply 'company--replacement-string
1692 (company--create-lines selection (abs height))
1695 (overlay-put ov 'company-column column)
1696 (overlay-put ov 'company-height (abs height))
1697 (overlay-put ov 'window (selected-window))))))
1699 (defun company-pseudo-tooltip-show-at-point (pos)
1700 (let ((col-row (company--col-row pos)))
1702 (company-pseudo-tooltip-show (1+ (cdr col-row)) (car col-row)
1703 company-selection))))
1705 (defun company-pseudo-tooltip-edit (lines selection)
1706 (let ((column (overlay-get company-pseudo-tooltip-overlay 'company-column))
1707 (height (overlay-get company-pseudo-tooltip-overlay 'company-height)))
1708 (overlay-put company-pseudo-tooltip-overlay 'company-before
1709 (apply 'company--replacement-string
1710 (company--create-lines selection height)
1711 (overlay-get company-pseudo-tooltip-overlay
1712 'company-replacement-args)))))
1714 (defun company-pseudo-tooltip-hide ()
1715 (when company-pseudo-tooltip-overlay
1716 (delete-overlay company-pseudo-tooltip-overlay)
1717 (setq company-pseudo-tooltip-overlay nil)))
1719 (defun company-pseudo-tooltip-hide-temporarily ()
1720 (when (overlayp company-pseudo-tooltip-overlay)
1721 (overlay-put company-pseudo-tooltip-overlay 'invisible nil)
1722 (overlay-put company-pseudo-tooltip-overlay 'before-string nil)))
1724 (defun company-pseudo-tooltip-unhide ()
1725 (when company-pseudo-tooltip-overlay
1726 (overlay-put company-pseudo-tooltip-overlay 'invisible t)
1727 (overlay-put company-pseudo-tooltip-overlay 'before-string
1728 (overlay-get company-pseudo-tooltip-overlay 'company-before))
1729 (overlay-put company-pseudo-tooltip-overlay 'window (selected-window))))
1731 (defun company-pseudo-tooltip-frontend (command)
1732 "A `company-mode' front-end similar to a tool-tip but based on overlays."
1734 ('pre-command (company-pseudo-tooltip-hide-temporarily))
1736 (let ((old-height (if (overlayp company-pseudo-tooltip-overlay)
1737 (overlay-get company-pseudo-tooltip-overlay
1740 (new-height (company--pseudo-tooltip-height)))
1741 (unless (and (>= (* old-height new-height) 0)
1742 (>= (abs old-height) (abs new-height)))
1744 (company-pseudo-tooltip-show-at-point (- (point)
1745 (length company-prefix)))))
1746 (company-pseudo-tooltip-unhide))
1747 ('hide (company-pseudo-tooltip-hide)
1748 (setq company-tooltip-offset 0))
1749 ('update (when (overlayp company-pseudo-tooltip-overlay)
1750 (company-pseudo-tooltip-edit company-candidates
1751 company-selection)))))
1753 (defun company-pseudo-tooltip-unless-just-one-frontend (command)
1754 "`company-pseudo-tooltip-frontend', but not shown for single candidates."
1755 (unless (and (eq command 'post-command)
1756 (not (cdr company-candidates)))
1757 (company-pseudo-tooltip-frontend command)))
1759 ;;; overlay ;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;
1761 (defvar company-preview-overlay nil)
1762 (make-variable-buffer-local 'company-preview-overlay)
1764 (defun company-preview-show-at-point (pos)
1765 (company-preview-hide)
1767 (setq company-preview-overlay (make-overlay pos pos))
1769 (let ((completion(nth company-selection company-candidates)))
1770 (setq completion (propertize completion 'face 'company-preview))
1771 (add-text-properties 0 (length company-common)
1772 '(face company-preview-common) completion)
1774 ;; Add search string
1775 (and company-search-string
1776 (string-match (regexp-quote company-search-string) completion)
1777 (add-text-properties (match-beginning 0)
1779 '(face company-preview-search)
1782 (setq completion (company-strip-prefix completion))
1784 (and (equal pos (point))
1785 (not (equal completion ""))
1786 (add-text-properties 0 1 '(cursor t) completion))
1788 (overlay-put company-preview-overlay 'after-string completion)
1789 (overlay-put company-preview-overlay 'window (selected-window))))
1791 (defun company-preview-hide ()
1792 (when company-preview-overlay
1793 (delete-overlay company-preview-overlay)
1794 (setq company-preview-overlay nil)))
1796 (defun company-preview-frontend (command)
1797 "A `company-mode' front-end showing the selection as if it had been inserted."
1799 ('pre-command (company-preview-hide))
1800 ('post-command (company-preview-show-at-point (point)))
1801 ('hide (company-preview-hide))))
1803 (defun company-preview-if-just-one-frontend (command)
1804 "`company-preview-frontend', but only shown for single candidates."
1805 (unless (and (eq command 'post-command)
1806 (cdr company-candidates))
1807 (company-preview-frontend command)))
1809 ;;; echo ;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;
1811 (defvar company-echo-last-msg nil)
1812 (make-variable-buffer-local 'company-echo-last-msg)
1814 (defvar company-echo-timer nil)
1816 (defvar company-echo-delay .1)
1818 (defun company-echo-show (&optional getter)
1820 (setq company-echo-last-msg (funcall getter)))
1821 (let ((message-log-max nil))
1822 (if company-echo-last-msg
1823 (message "%s" company-echo-last-msg)
1826 (defsubst company-echo-show-soon (&optional getter)
1827 (when company-echo-timer
1828 (cancel-timer company-echo-timer))
1829 (setq company-echo-timer (run-with-timer company-echo-delay nil
1830 'company-echo-show getter)))
1832 (defun company-echo-format ()
1834 (let ((limit (window-width (minibuffer-window)))
1836 ;; Roll to selection.
1837 (candidates (nthcdr company-selection company-candidates))
1838 (i (if company-show-numbers company-selection 99999))
1842 (setq comp (company-reformat (pop candidates))
1843 len (+ len 1 (length comp)))
1847 (setq comp (propertize (format "%d: %s" i comp)
1848 'face 'company-echo))
1851 (add-text-properties 3 (+ 3 (length company-common))
1852 '(face company-echo-common) comp))
1853 (setq comp (propertize comp 'face 'company-echo))
1854 (add-text-properties 0 (length company-common)
1855 '(face company-echo-common) comp))
1857 (setq candidates nil)
1860 (mapconcat 'identity (nreverse msg) " ")))
1862 (defun company-echo-strip-common-format ()
1864 (let ((limit (window-width (minibuffer-window)))
1865 (len (+ (length company-prefix) 2))
1866 ;; Roll to selection.
1867 (candidates (nthcdr company-selection company-candidates))
1868 (i (if company-show-numbers company-selection 99999))
1872 (setq comp (company-strip-prefix (pop candidates))
1873 len (+ len 2 (length comp)))
1876 (setq comp (format "%s (%d)" comp i))
1880 (setq candidates nil)
1881 (push (propertize comp 'face 'company-echo) msg)))
1883 (concat (propertize company-prefix 'face 'company-echo-common) "{"
1884 (mapconcat 'identity (nreverse msg) ", ")
1887 (defun company-echo-hide ()
1888 (when company-echo-timer
1889 (cancel-timer company-echo-timer))
1890 (unless (equal company-echo-last-msg "")
1891 (setq company-echo-last-msg "")
1892 (company-echo-show)))
1894 (defun company-echo-frontend (command)
1895 "A `company-mode' front-end showing the candidates in the echo area."
1897 ('pre-command (company-echo-show-soon))
1898 ('post-command (company-echo-show-soon 'company-echo-format))
1899 ('hide (company-echo-hide))))
1901 (defun company-echo-strip-common-frontend (command)
1902 "A `company-mode' front-end showing the candidates in the echo area."
1904 ('pre-command (company-echo-show-soon))
1905 ('post-command (company-echo-show-soon 'company-echo-strip-common-format))
1906 ('hide (company-echo-hide))))
1908 (defun company-echo-metadata-frontend (command)
1909 "A `company-mode' front-end showing the documentation in the echo area."
1911 ('pre-command (company-echo-show-soon))
1912 ('post-command (company-echo-show-soon 'company-fetch-metadata))
1913 ('hide (company-echo-hide))))
1916 ;;; company.el ends here