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'.
69 ;; In C modes . and -> now count towards `company-minimum-prefix-length'.
70 ;; Reverted default front-end back to `company-preview-if-just-one-frontend'.
71 ;; The pseudo tooltip will no longer be clipped at the right window edge.
72 ;; Added `company-tooltip-minimum'.
73 ;; Windows compatibility fixes.
76 ;; Added `global-company-mode'.
77 ;; Performance enhancements.
78 ;; Added `company-eclim' back-end.
79 ;; Added safer workaround for Emacs `posn-col-row' bug.
82 ;; Automatic completion is now aborted if the prefix gets too short.
83 ;; Added option `company-dabbrev-time-limit'.
84 ;; `company-backends' now supports merging back-ends.
85 ;; Added back-end `company-dabbrev-code' for generic code.
86 ;; Fixed `company-begin-with'.
89 ;; Added 'stop prefix to prevent dabbrev from completing inside of symbols.
90 ;; Fixed issues with tabbar-mode and line-spacing.
91 ;; Performance enhancements.
94 ;; Added `company-begin-commands' option.
95 ;; Added abbrev, tempo and Xcode back-ends.
96 ;; Back-ends are now interactive. You can start them with M-x backend-name.
97 ;; Added `company-begin-with' for starting company from elisp-code.
99 ;; Added `company-require-match' and `company-auto-complete' options.
101 ;; 2009-04-05 (0.2.1)
102 ;; Improved Emacs Lisp back-end behavior for local variables.
103 ;; Added `company-elisp-detect-function-context' option.
104 ;; The mouse can now be used for selection.
107 ;; Added `company-show-location'.
108 ;; Added etags back-end.
109 ;; Added work-around for end-of-buffer bug.
110 ;; Added `company-filter-candidates'.
111 ;; More local Lisp variables are now included in the candidates.
113 ;; 2009-03-21 (0.1.5)
114 ;; Fixed elisp documentation buffer always showing the same doc.
115 ;; Added `company-echo-strip-common-frontend'.
116 ;; Added `company-show-numbers' option and M-0 ... M-9 default bindings.
117 ;; Don't hide the echo message if it isn't shown.
124 (eval-when-compile (require 'cl))
126 (add-to-list 'debug-ignored-errors "^.* frontend cannot be used twice$")
127 (add-to-list 'debug-ignored-errors "^Echo area cannot be used twice$")
128 (add-to-list 'debug-ignored-errors "^No \\(document\\|loc\\)ation available$")
129 (add-to-list 'debug-ignored-errors "^Company not ")
130 (add-to-list 'debug-ignored-errors "^No candidate number ")
131 (add-to-list 'debug-ignored-errors "^Cannot complete at point$")
133 (defgroup company nil
134 "Extensible inline text completion mechanism"
139 (defface company-tooltip
140 '((t :background "yellow"
141 :foreground "black"))
142 "*Face used for the tool tip."
145 (defface company-tooltip-selection
146 '((default :inherit company-tooltip)
147 (((class color) (min-colors 88)) (:background "orange1"))
148 (t (:background "green")))
149 "*Face used for the selection in the tool tip."
152 (defface company-tooltip-mouse
153 '((default :inherit highlight))
154 "*Face used for the tool tip item under the mouse."
157 (defface company-tooltip-common
158 '((t :inherit company-tooltip
160 "*Face used for the common completion in the tool tip."
163 (defface company-tooltip-common-selection
164 '((t :inherit company-tooltip-selection
166 "*Face used for the selected common completion in the tool tip."
169 (defface company-preview
170 '((t :background "blue4"
171 :foreground "wheat"))
172 "*Face used for the completion preview."
175 (defface company-preview-common
176 '((t :inherit company-preview
178 "*Face used for the common part of the completion preview."
181 (defface company-preview-search
182 '((t :inherit company-preview
183 :background "blue1"))
184 "*Face used for the search string in the completion preview."
187 (defface company-echo nil
188 "*Face used for completions in the echo area."
191 (defface company-echo-common
192 '((((background dark)) (:foreground "firebrick1"))
193 (((background light)) (:background "firebrick4")))
194 "*Face used for the common part of completions in the echo area."
197 (defun company-frontends-set (variable value)
199 (let ((remainder value))
200 (setcdr remainder (delq (car remainder) (cdr remainder))))
201 (and (memq 'company-pseudo-tooltip-unless-just-one-frontend value)
202 (memq 'company-pseudo-tooltip-frontend value)
203 (error "Pseudo tooltip frontend cannot be used twice"))
204 (and (memq 'company-preview-if-just-one-frontend value)
205 (memq 'company-preview-frontend value)
206 (error "Preview frontend cannot be used twice"))
207 (and (memq 'company-echo value)
208 (memq 'company-echo-metadata-frontend value)
209 (error "Echo area cannot be used twice"))
210 ;; preview must come last
211 (dolist (f '(company-preview-if-just-one-frontend company-preview-frontend))
213 (setq value (append (delq f value) (list f)))))
214 (set variable value))
216 (defcustom company-frontends '(company-pseudo-tooltip-unless-just-one-frontend
217 company-preview-if-just-one-frontend
218 company-echo-metadata-frontend)
219 "*The list of active front-ends (visualizations).
220 Each front-end is a function that takes one argument. It is called with
221 one of the following arguments:
223 'show: When the visualization should start.
225 'hide: When the visualization should end.
227 'update: When the data has been updated.
229 'pre-command: Before every command that is executed while the
230 visualization is active.
232 'post-command: After every command that is executed while the
233 visualization is active.
235 The visualized data is stored in `company-prefix', `company-candidates',
236 `company-common', `company-selection', `company-point' and
237 `company-search-string'."
238 :set 'company-frontends-set
240 :type '(repeat (choice (const :tag "echo" company-echo-frontend)
241 (const :tag "echo, strip common"
242 company-echo-strip-common-frontend)
243 (const :tag "show echo meta-data in echo"
244 company-echo-metadata-frontend)
245 (const :tag "pseudo tooltip"
246 company-pseudo-tooltip-frontend)
247 (const :tag "pseudo tooltip, multiple only"
248 company-pseudo-tooltip-unless-just-one-frontend)
249 (const :tag "preview" company-preview-frontend)
250 (const :tag "preview, unique only"
251 company-preview-if-just-one-frontend)
252 (function :tag "custom function" nil))))
254 (defcustom company-tooltip-limit 10
255 "*The maximum number of candidates in the tool tip"
259 (defcustom company-tooltip-minimum 6
260 "*The minimum height of the tool tip.
261 If this many lines are not available, prefer to display the tooltip above."
265 (defvar company-safe-backends
266 '((company-abbrev . "Abbrev")
267 (company-css . "CSS")
268 (company-dabbrev . "dabbrev for plain text")
269 (company-dabbrev-code . "dabbrev for code")
270 (company-eclim . "eclim (an Eclipse interace)")
271 (company-elisp . "Emacs Lisp")
272 (company-etags . "etags")
273 (company-files . "Files")
274 (company-gtags . "GNU Global")
275 (company-ispell . "ispell")
276 (company-keywords . "Programming language keywords")
277 (company-nxml . "nxml")
278 (company-oddmuse . "Oddmuse")
279 (company-semantic . "CEDET Semantic")
280 (company-tempo . "Tempo templates")
281 (company-xcode . "Xcode")))
282 (put 'company-safe-backends 'risky-local-variable t)
284 (defun company-safe-backends-p (backends)
285 (and (consp backends)
286 (not (dolist (backend backends)
287 (unless (if (consp backend)
288 (company-safe-backends-p backend)
289 (assq backend company-safe-backends))
292 (defcustom company-backends '(company-elisp company-nxml company-css
293 company-eclim company-semantic company-xcode
294 (company-gtags company-etags company-dabbrev-code
296 company-oddmuse company-files company-dabbrev)
297 "*The list of active back-ends (completion engines).
298 Each list elements can itself be a list of back-ends. In that case their
299 completions are merged. Otherwise only the first matching back-end returns
302 Each back-end is a function that takes a variable number of arguments.
303 The first argument is the command requested from the back-end. It is one
306 'prefix: The back-end should return the text to be completed. It must be
307 text immediately before `point'. Returning nil passes control to the next
308 back-end. The function should return 'stop if it should complete but cannot
309 \(e.g. if it is in the middle of a string\). If the returned value is only
310 part of the prefix (e.g. the part after \"->\" in C), the back-end may return a
311 cons of prefix and prefix length, which is then used in the
312 `company-minimum-prefix-length' test.
314 'candidates: The second argument is the prefix to be completed. The
315 return value should be a list of candidates that start with the prefix.
319 'sorted: The back-end may return t here to indicate that the candidates
320 are sorted and will not need to be sorted again.
322 'duplicates: If non-nil, company will take care of removing duplicates
325 'no-cache: Usually company doesn't ask for candidates again as completion
326 progresses, unless the back-end returns t for this command. The second
327 argument is the latest prefix.
329 'meta: The second argument is a completion candidate. The back-end should
330 return a (short) documentation string for it.
332 'doc-buffer: The second argument is a completion candidate. The back-end should
333 create a buffer (preferably with `company-doc-buffer'), fill it with
334 documentation and return it.
336 'location: The second argument is a completion candidate. The back-end can
337 return the cons of buffer and buffer location, or of file and line
338 number where the completion candidate was defined.
340 'require-match: If this value is t, the user is not allowed to enter anything
341 not offering as a candidate. Use with care! The default value nil gives the
342 user that choice with `company-require-match'. Return value 'never overrides
343 that option the other way around.
345 The back-end should return nil for all commands it does not support or
346 does not know about. It should also be callable interactively and use
347 `company-begin-backend' to start itself in that case."
352 ,@(mapcar (lambda (b) `(const :tag ,(cdr b) ,(car b)))
353 company-safe-backends)
354 (symbol :tag "User defined")
355 (repeat :tag "Merged Back-ends"
356 (choice :tag "Back-end"
357 ,@(mapcar (lambda (b)
358 `(const :tag ,(cdr b) ,(car b)))
359 company-safe-backends)
360 (symbol :tag "User defined"))))))
362 (put 'company-backends 'safe-local-variable 'company-safe-backends-p)
364 (defcustom company-completion-started-hook nil
365 "*Hook run when company starts completing.
366 The hook is called with one argument that is non-nil if the completion was
371 (defcustom company-completion-cancelled-hook nil
372 "*Hook run when company cancels completing.
373 The hook is called with one argument that is non-nil if the completion was
378 (defcustom company-completion-finished-hook nil
379 "*Hook run when company successfully completes.
380 The hook is called with the selected candidate as an argument."
384 (defcustom company-minimum-prefix-length 3
385 "*The minimum prefix length for automatic completion."
387 :type '(integer :tag "prefix length"))
389 (defcustom company-require-match 'company-explicit-action-p
390 "*If enabled, disallow non-matching input.
391 This can be a function do determine if a match is required.
393 This can be overridden by the back-end, if it returns t or 'never to
394 'require-match. `company-auto-complete' also takes precedence over this."
396 :type '(choice (const :tag "Off" nil)
397 (function :tag "Predicate function")
398 (const :tag "On, if user interaction took place"
399 'company-explicit-action-p)
400 (const :tag "On" t)))
402 (defcustom company-auto-complete 'company-explicit-action-p
403 "Determines when to auto-complete.
404 If this is enabled, all characters from `company-auto-complete-chars' complete
405 the selected completion. This can also be a function."
407 :type '(choice (const :tag "Off" nil)
408 (function :tag "Predicate function")
409 (const :tag "On, if user interaction took place"
410 'company-explicit-action-p)
411 (const :tag "On" t)))
413 (defcustom company-auto-complete-chars '(?\ ?\( ?\) ?. ?\" ?$ ?\' ?< ?| ?!)
414 "Determines which characters trigger an automatic completion.
415 See `company-auto-complete'. If this is a string, each string character causes
416 completion. If it is a list of syntax description characters (see
417 `modify-syntax-entry'), all characters with that syntax auto-complete.
419 This can also be a function, which is called with the new input and should
420 return non-nil if company should auto-complete.
422 A character that is part of a valid candidate never starts auto-completion."
424 :type '(choice (string :tag "Characters")
426 (const :tag "Whitespace" ?\ )
427 (const :tag "Symbol" ?_)
428 (const :tag "Opening parentheses" ?\()
429 (const :tag "Closing parentheses" ?\))
430 (const :tag "Word constituent" ?w)
431 (const :tag "Punctuation." ?.)
432 (const :tag "String quote." ?\")
433 (const :tag "Paired delimiter." ?$)
434 (const :tag "Expression quote or prefix operator." ?\')
435 (const :tag "Comment starter." ?<)
436 (const :tag "Comment ender." ?>)
437 (const :tag "Character-quote." ?/)
438 (const :tag "Generic string fence." ?|)
439 (const :tag "Generic comment fence." ?!))
440 (function :tag "Predicate function")))
442 (defcustom company-idle-delay .7
443 "*The idle delay in seconds until automatic completions starts.
444 A value of nil means never complete automatically, t means complete
445 immediately when a prefix of `company-minimum-prefix-length' is reached."
447 :type '(choice (const :tag "never (nil)" nil)
448 (const :tag "immediate (t)" t)
449 (number :tag "seconds")))
451 (defcustom company-begin-commands t
452 "*A list of commands following which company will start completing.
453 If this is t, it will complete after any command. See `company-idle-delay'.
455 Alternatively any command with a non-nil 'company-begin property is treated as
456 if it was on this list."
458 :type '(choice (const :tag "Any command" t)
459 (const :tag "Self insert command" '(self-insert-command))
460 (repeat :tag "Commands" function)))
462 (defcustom company-show-numbers nil
463 "*If enabled, show quick-access numbers for the first ten candidates."
465 :type '(choice (const :tag "off" nil)
466 (const :tag "on" t)))
468 (defvar company-end-of-buffer-workaround t
469 "*Work around a visualization bug when completing at the end of the buffer.
470 The work-around consists of adding a newline.")
472 ;;; mode ;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;
474 (defvar company-mode-map (make-sparse-keymap)
475 "Keymap used by `company-mode'.")
477 (defvar company-active-map
478 (let ((keymap (make-sparse-keymap)))
479 (define-key keymap "\e\e\e" 'company-abort)
480 (define-key keymap "\C-g" 'company-abort)
481 (define-key keymap (kbd "M-n") 'company-select-next)
482 (define-key keymap (kbd "M-p") 'company-select-previous)
483 (define-key keymap (kbd "<down>") 'company-select-next)
484 (define-key keymap (kbd "<up>") 'company-select-previous)
485 (define-key keymap [down-mouse-1] 'ignore)
486 (define-key keymap [down-mouse-3] 'ignore)
487 (define-key keymap [mouse-1] 'company-complete-mouse)
488 (define-key keymap [mouse-3] 'company-select-mouse)
489 (define-key keymap [up-mouse-1] 'ignore)
490 (define-key keymap [up-mouse-3] 'ignore)
491 (define-key keymap "\C-m" 'company-complete-selection)
492 (define-key keymap "\t" 'company-complete-common)
493 (define-key keymap (kbd "<f1>") 'company-show-doc-buffer)
494 (define-key keymap "\C-w" 'company-show-location)
495 (define-key keymap "\C-s" 'company-search-candidates)
496 (define-key keymap "\C-\M-s" 'company-filter-candidates)
498 (define-key keymap (vector (+ (aref (kbd "M-0") 0) i))
499 `(lambda () (interactive) (company-complete-number ,i))))
502 "Keymap that is enabled during an active completion.")
504 (defvar company--disabled-backends nil)
506 (defun company-init-backend (backend)
507 (and (symbolp backend)
508 (not (fboundp backend))
509 (ignore-errors (require backend nil t)))
511 (if (or (symbolp backend)
513 (if (ignore-errors (funcall backend 'init) t)
514 (put backend 'company-init t)
515 (put backend 'company-init 'failed)
516 (unless (memq backend company--disabled-backends)
517 (message "Company back-end '%s' could not be initialized"
519 (push backend company--disabled-backends))
521 (mapc 'company-init-backend backend)))
523 (defvar company-default-lighter " company")
525 (defvar company-lighter company-default-lighter)
526 (make-variable-buffer-local 'company-lighter)
529 (define-minor-mode company-mode
530 "\"complete anything\"; in in-buffer completion framework.
531 Completion starts automatically, depending on the values
532 `company-idle-delay' and `company-minimum-prefix-length'.
534 Completion can be controlled with the commands:
535 `company-complete-common', `company-complete-selection', `company-complete',
536 `company-select-next', `company-select-previous'. If these commands are
537 called before `company-idle-delay', completion will also start.
539 Completions can be searched with `company-search-candidates' or
540 `company-filter-candidates'. These can be used while completion is
543 The completion data is retrieved using `company-backends' and displayed using
544 `company-frontends'. If you want to start a specific back-end, call it
545 interactively or use `company-begin-backend'.
547 regular keymap (`company-mode-map'):
550 keymap during active completions (`company-active-map'):
552 \\{company-active-map}"
553 nil company-lighter company-mode-map
556 (add-hook 'pre-command-hook 'company-pre-command nil t)
557 (add-hook 'post-command-hook 'company-post-command nil t)
558 (mapc 'company-init-backend company-backends))
559 (remove-hook 'pre-command-hook 'company-pre-command t)
560 (remove-hook 'post-command-hook 'company-post-command t)
562 (kill-local-variable 'company-point)))
564 (define-globalized-minor-mode global-company-mode company-mode
565 (lambda () (company-mode 1)))
567 (defsubst company-assert-enabled ()
569 (company-uninstall-map)
570 (error "Company not enabled")))
572 ;;; keymaps ;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;
574 (defvar company-overriding-keymap-bound nil)
575 (make-variable-buffer-local 'company-overriding-keymap-bound)
577 (defvar company-old-keymap nil)
578 (make-variable-buffer-local 'company-old-keymap)
580 (defvar company-my-keymap nil)
581 (make-variable-buffer-local 'company-my-keymap)
583 (defsubst company-enable-overriding-keymap (keymap)
584 (setq company-my-keymap keymap)
585 (when company-overriding-keymap-bound
586 (company-uninstall-map)))
588 (defun company-install-map ()
589 (unless (or company-overriding-keymap-bound
590 (null company-my-keymap))
591 (setq company-old-keymap overriding-terminal-local-map
592 overriding-terminal-local-map company-my-keymap
593 company-overriding-keymap-bound t)))
595 (defun company-uninstall-map ()
596 (when (eq overriding-terminal-local-map company-my-keymap)
597 (setq overriding-terminal-local-map company-old-keymap
598 company-overriding-keymap-bound nil)))
601 ;; Emacs calculates the active keymaps before reading the event. That means we
602 ;; cannot change the keymap from a timer. So we send a bogus command.
603 (defun company-ignore ()
605 (setq this-command last-command))
607 (global-set-key '[31415926] 'company-ignore)
609 (defun company-input-noop ()
610 (push 31415926 unread-command-events))
613 ;; posn-col-row is incorrect in older Emacsen when line-spacing is set
614 (defun company--col-row (&optional pos)
615 (let ((posn (posn-at-point pos)))
616 (cons (car (posn-col-row posn)) (cdr (posn-actual-col-row posn)))))
618 (defsubst company--column (&optional pos)
619 (car (posn-col-row (posn-at-point pos))))
621 (defsubst company--row (&optional pos)
622 (cdr (posn-actual-col-row (posn-at-point pos))))
624 ;;; backends ;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;
626 (defun company-grab (regexp &optional expression limit)
627 (when (looking-back regexp limit)
628 (or (match-string-no-properties (or expression 0)) "")))
630 (defun company-grab-line (regexp &optional expression)
631 (company-grab regexp expression (point-at-bol)))
633 (defun company-grab-symbol ()
634 (if (looking-at "\\_>")
635 (buffer-substring (point) (save-excursion (skip-syntax-backward "w_")
637 (unless (and (char-after) (memq (char-syntax (char-after)) '(?w ?_)))
640 (defun company-grab-word ()
641 (if (looking-at "\\>")
642 (buffer-substring (point) (save-excursion (skip-syntax-backward "w")
644 (unless (and (char-after) (eq (char-syntax (char-after)) ?w))
647 (defun company-in-string-or-comment ()
648 (let ((ppss (syntax-ppss)))
649 (or (car (setq ppss (nthcdr 3 ppss)))
650 (car (setq ppss (cdr ppss)))
653 (if (fboundp 'locate-dominating-file)
654 (defalias 'company-locate-dominating-file 'locate-dominating-file)
655 (defun company-locate-dominating-file (file name)
657 (let ((dir (file-name-directory file))
659 (while (not (equal dir prev-dir))
660 (when (file-exists-p (expand-file-name name dir))
663 dir (file-name-directory (directory-file-name dir))))))))
665 (defun company-call-backend (&rest args)
666 (if (functionp company-backend)
667 (apply company-backend args)
668 (apply 'company--multi-backend-adapter company-backend args)))
670 (defun company--multi-backend-adapter (backends command &rest args)
673 (apply 'append (mapcar (lambda (backend) (apply backend command args))
679 (dolist (backend backends)
680 (when (setq value (apply backend command args))
683 ;;; completion mechanism ;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;
685 (defvar company-backend nil)
686 (make-variable-buffer-local 'company-backend)
688 (defvar company-prefix nil)
689 (make-variable-buffer-local 'company-prefix)
691 (defvar company-candidates nil)
692 (make-variable-buffer-local 'company-candidates)
694 (defvar company-candidates-length nil)
695 (make-variable-buffer-local 'company-candidates-length)
697 (defvar company-candidates-cache nil)
698 (make-variable-buffer-local 'company-candidates-cache)
700 (defvar company-candidates-predicate nil)
701 (make-variable-buffer-local 'company-candidates-predicate)
703 (defvar company-common nil)
704 (make-variable-buffer-local 'company-common)
706 (defvar company-selection 0)
707 (make-variable-buffer-local 'company-selection)
709 (defvar company-selection-changed nil)
710 (make-variable-buffer-local 'company-selection-changed)
712 (defvar company--explicit-action nil
713 "Non-nil, if explicit completion took place.")
714 (make-variable-buffer-local 'company--explicit-action)
716 (defvar company--point-max nil)
717 (make-variable-buffer-local 'company--point-max)
719 (defvar company-point nil)
720 (make-variable-buffer-local 'company-point)
722 (defvar company-timer nil)
724 (defvar company-added-newline nil)
725 (make-variable-buffer-local 'company-added-newline)
727 (defsubst company-strip-prefix (str)
728 (substring str (length company-prefix)))
730 (defun company-explicit-action-p ()
731 "Return whether explicit completion action was taken by the user."
732 (or company--explicit-action
733 company-selection-changed))
735 (defsubst company-reformat (candidate)
736 ;; company-ispell needs this, because the results are always lower-case
737 ;; It's mory efficient to fix it only when they are displayed.
738 (concat company-prefix (substring candidate (length company-prefix))))
740 (defun company--should-complete ()
741 (and (not (or buffer-read-only overriding-terminal-local-map
742 overriding-local-map))
743 (eq company-idle-delay t)
744 (or (eq t company-begin-commands)
745 (memq this-command company-begin-commands)
746 (and (symbolp this-command) (get this-command 'company-begin)))
747 (not (and transient-mark-mode mark-active))))
749 (defsubst company-call-frontends (command)
750 (dolist (frontend company-frontends)
752 (funcall frontend command)
753 (error (error "Company: Front-end %s error \"%s\" on command %s"
754 frontend (error-message-string err) command)))))
756 (defsubst company-set-selection (selection &optional force-update)
757 (setq selection (max 0 (min (1- company-candidates-length) selection)))
758 (when (or force-update (not (equal selection company-selection)))
759 (setq company-selection selection
760 company-selection-changed t)
761 (company-call-frontends 'update)))
763 (defun company-apply-predicate (candidates predicate)
765 (dolist (c candidates)
766 (when (funcall predicate c)
770 (defun company-update-candidates (candidates)
771 (setq company-candidates-length (length candidates))
772 (if (> company-selection 0)
773 ;; Try to restore the selection
774 (let ((selected (nth company-selection company-candidates)))
775 (setq company-selection 0
776 company-candidates candidates)
778 (while (and candidates (string< (pop candidates) selected))
779 (incf company-selection))
781 ;; Make sure selection isn't out of bounds.
782 (setq company-selection (min (1- company-candidates-length)
783 company-selection)))))
784 (setq company-selection 0
785 company-candidates candidates))
787 (push (cons company-prefix company-candidates) company-candidates-cache)
789 (let ((completion-ignore-case (company-call-backend 'ignore-case)))
790 (setq company-common (try-completion company-prefix company-candidates)))
791 (when (eq company-common t)
792 (setq company-candidates nil)))
794 (defun company-calculate-candidates (prefix)
795 (let ((candidates (cdr (assoc prefix company-candidates-cache))))
797 (when company-candidates-cache
798 (let ((len (length prefix))
799 (completion-ignore-case (company-call-backend 'ignore-case))
801 (dotimes (i (1+ len))
802 (when (setq prev (cdr (assoc (substring prefix 0 (- len i))
803 company-candidates-cache)))
804 (setq candidates (all-completions prefix prev))
806 ;; no cache match, call back-end
808 (setq candidates (company-call-backend 'candidates prefix))
809 (when company-candidates-predicate
811 (company-apply-predicate candidates
812 company-candidates-predicate)))
813 (unless (company-call-backend 'sorted)
814 (setq candidates (sort candidates 'string<)))
815 (when (company-call-backend 'duplicates)
817 (let ((c2 candidates))
819 (setcdr c2 (progn (while (equal (pop c2) (car c2)))
821 (if (or (cdr candidates)
822 (not (equal (car candidates) prefix)))
823 ;; Don't start when already completed and unique.
825 ;; Not the right place? maybe when setting?
826 (and company-candidates t))))
828 (defun company-idle-begin (buf win tick pos)
830 (eq buf (current-buffer))
831 (eq win (selected-window))
832 (eq tick (buffer-chars-modified-tick))
834 (not company-candidates)
835 (not (equal (point) company-point))
836 (let ((company-idle-delay t)
837 (company-begin-commands t))
839 (when company-candidates
841 (company-post-command)))))
843 (defun company-auto-begin ()
844 (company-assert-enabled)
846 (not company-candidates)
847 (let ((company-idle-delay t)
848 (company-minimum-prefix-length 0)
849 (company-begin-commands t))
851 ;; Return non-nil if active.
854 (defun company-manual-begin ()
856 (setq company--explicit-action t)
857 (company-auto-begin))
859 (defun company-require-match-p ()
860 (let ((backend-value (company-call-backend 'require-match)))
861 (or (eq backend-value t)
862 (and (if (functionp company-require-match)
863 (funcall company-require-match)
864 (eq company-require-match t))
865 (not (eq backend-value 'never))))))
867 (defun company-punctuation-p (input)
868 "Return non-nil, if input starts with punctuation or parentheses."
869 (memq (char-syntax (string-to-char input)) '(?. ?\( ?\))))
871 (defun company-auto-complete-p (input)
872 "Return non-nil, if input starts with punctuation or parentheses."
873 (and (if (functionp company-auto-complete)
874 (funcall company-auto-complete)
875 company-auto-complete)
876 (if (functionp company-auto-complete-chars)
877 (funcall company-auto-complete-chars input)
878 (if (consp company-auto-complete-chars)
879 (memq (char-syntax (string-to-char input))
880 company-auto-complete-chars)
881 (string-match (substring input 0 1) company-auto-complete-chars)))))
883 (defun company--incremental-p ()
884 (and (> (point) company-point)
885 (> (point-max) company--point-max)
886 (not (eq this-command 'backward-delete-char-untabify))
887 (equal (buffer-substring (- company-point (length company-prefix))
891 (defsubst company--string-incremental-p (old-prefix new-prefix)
892 (and (> (length new-prefix) (length old-prefix))
893 (equal old-prefix (substring new-prefix 0 (length old-prefix)))))
895 (defun company--continue-failed (new-prefix)
896 (when (company--incremental-p)
897 (let ((input (buffer-substring-no-properties (point) company-point)))
899 ((company-auto-complete-p input)
902 (goto-char company-point)
903 (company-complete-selection)
905 ((and (company--string-incremental-p company-prefix new-prefix)
906 (company-require-match-p))
907 ;; wrong incremental input, but required match
908 (backward-delete-char (length input))
910 (message "Matching input is required")
912 ((equal company-prefix (car company-candidates))
913 ;; last input was actually success
914 (company-cancel company-prefix)
917 (defun company--good-prefix-p (prefix)
918 (and (or (company-explicit-action-p)
919 (>= (or (cdr-safe prefix) (length prefix))
920 company-minimum-prefix-length))
921 (stringp (or (car-safe prefix) prefix))))
923 (defun company--continue ()
924 (when (company-call-backend 'no-cache company-prefix)
925 ;; Don't complete existing candidates, fetch new ones.
926 (setq company-candidates-cache nil))
927 (let* ((new-prefix (company-call-backend 'prefix))
928 (c (when (and (company--good-prefix-p new-prefix)
929 (setq new-prefix (or (car-safe new-prefix) new-prefix))
930 (= (- (point) (length new-prefix))
931 (- company-point (length company-prefix))))
932 (setq new-prefix (or (car-safe new-prefix) new-prefix))
933 (company-calculate-candidates new-prefix))))
936 ;; t means complete/unique.
937 (company-cancel new-prefix)
941 (setq company-prefix new-prefix)
942 (company-update-candidates c)
944 (t (company--continue-failed new-prefix)))
947 (defun company--begin-new ()
949 (dolist (backend (if company-backend
950 ;; prefer manual override
951 (list company-backend)
954 (if (or (symbolp backend)
956 (when (or (not (symbolp backend))
957 (eq t (get backend 'company-init))
958 (unless (get backend 'company-init)
959 (company-init-backend backend)))
960 (funcall backend 'prefix))
961 (company--multi-backend-adapter backend 'prefix)))
963 (when (company--good-prefix-p prefix)
964 (setq prefix (or (car-safe prefix) prefix)
965 company-backend backend
966 c (company-calculate-candidates prefix))
967 ;; t means complete/unique. We don't start, so no hooks.
969 (setq company-prefix prefix
970 company-lighter (concat " " (symbol-name backend)))
971 (company-update-candidates c)
972 (run-hook-with-args 'company-completion-started-hook
973 (company-explicit-action-p))
974 (company-call-frontends 'show)))
977 (defun company-begin ()
978 (setq company-candidates
979 (or (and company-candidates (company--continue))
980 (and (company--should-complete) (company--begin-new))))
981 (when company-candidates
982 (when (and company-end-of-buffer-workaround (eobp))
983 (save-excursion (insert "\n"))
984 (setq company-added-newline (buffer-chars-modified-tick)))
985 (setq company-point (point)
986 company--point-max (point-max))
987 (company-enable-overriding-keymap company-active-map)
988 (company-call-frontends 'update)))
990 (defun company-cancel (&optional result)
991 (and company-added-newline
992 (> (point-max) (point-min))
993 (let ((tick (buffer-chars-modified-tick)))
994 (delete-region (1- (point-max)) (point-max))
995 (equal tick company-added-newline))
996 ;; Only set unmodified when tick remained the same since insert.
997 (set-buffer-modified-p nil))
1000 (run-hook-with-args 'company-completion-finished-hook result)
1001 (run-hook-with-args 'company-completion-cancelled-hook result)))
1002 (setq company-added-newline nil
1005 company-candidates nil
1006 company-candidates-length nil
1007 company-candidates-cache nil
1008 company-candidates-predicate nil
1011 company-selection-changed nil
1012 company--explicit-action nil
1013 company-lighter company-default-lighter
1014 company--point-max nil
1017 (cancel-timer company-timer))
1018 (company-search-mode 0)
1019 (company-call-frontends 'hide)
1020 (company-enable-overriding-keymap nil))
1022 (defun company-abort ()
1025 ;; Don't start again, unless started manually.
1026 (setq company-point (point)))
1028 (defun company-finish (result)
1029 (insert (company-strip-prefix result))
1030 (company-cancel result)
1031 ;; Don't start again, unless started manually.
1032 (setq company-point (point)))
1034 (defsubst company-keep (command)
1035 (and (symbolp command) (get command 'company-keep)))
1037 (defun company-pre-command ()
1038 (unless (company-keep this-command)
1040 (when company-candidates
1041 (company-call-frontends 'pre-command))
1042 (error (message "Company: An error occurred in pre-command")
1043 (message "%s" (error-message-string err))
1046 (cancel-timer company-timer)
1047 (setq company-timer nil))
1048 (company-uninstall-map))
1050 (defun company-post-command ()
1051 (unless (company-keep this-command)
1054 (unless (equal (point) company-point)
1056 (if company-candidates
1057 (company-call-frontends 'post-command)
1058 (and (numberp company-idle-delay)
1059 (or (eq t company-begin-commands)
1060 (memq this-command company-begin-commands))
1062 (run-with-timer company-idle-delay nil
1064 (current-buffer) (selected-window)
1065 (buffer-chars-modified-tick) (point))))))
1066 (error (message "Company: An error occurred in post-command")
1067 (message "%s" (error-message-string err))
1069 (company-install-map))
1071 ;;; search ;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;
1073 (defvar company-search-string nil)
1074 (make-variable-buffer-local 'company-search-string)
1076 (defvar company-search-lighter " Search: \"\"")
1077 (make-variable-buffer-local 'company-search-lighter)
1079 (defvar company-search-old-map nil)
1080 (make-variable-buffer-local 'company-search-old-map)
1082 (defvar company-search-old-selection 0)
1083 (make-variable-buffer-local 'company-search-old-selection)
1085 (defun company-search (text lines)
1086 (let ((quoted (regexp-quote text))
1088 (dolist (line lines)
1089 (when (string-match quoted line (length company-prefix))
1093 (defun company-search-printing-char ()
1095 (company-search-assert-enabled)
1096 (setq company-search-string
1097 (concat (or company-search-string "") (string last-command-event))
1098 company-search-lighter (concat " Search: \"" company-search-string
1100 (let ((pos (company-search company-search-string
1101 (nthcdr company-selection company-candidates))))
1104 (company-set-selection (+ company-selection pos) t))))
1106 (defun company-search-repeat-forward ()
1107 "Repeat the incremental search in completion candidates forward."
1109 (company-search-assert-enabled)
1110 (let ((pos (company-search company-search-string
1111 (cdr (nthcdr company-selection
1112 company-candidates)))))
1115 (company-set-selection (+ company-selection pos 1) t))))
1117 (defun company-search-repeat-backward ()
1118 "Repeat the incremental search in completion candidates backwards."
1120 (company-search-assert-enabled)
1121 (let ((pos (company-search company-search-string
1122 (nthcdr (- company-candidates-length
1124 (reverse company-candidates)))))
1127 (company-set-selection (- company-selection pos 1) t))))
1129 (defun company-create-match-predicate ()
1130 (setq company-candidates-predicate
1131 `(lambda (candidate)
1132 ,(if company-candidates-predicate
1133 `(and (string-match ,company-search-string candidate)
1134 (funcall ,company-candidates-predicate
1136 `(string-match ,company-search-string candidate))))
1137 (company-update-candidates
1138 (company-apply-predicate company-candidates company-candidates-predicate))
1139 ;; Invalidate cache.
1140 (setq company-candidates-cache (cons company-prefix company-candidates)))
1142 (defun company-filter-printing-char ()
1144 (company-search-assert-enabled)
1145 (company-search-printing-char)
1146 (company-create-match-predicate)
1147 (company-call-frontends 'update))
1149 (defun company-search-kill-others ()
1150 "Limit the completion candidates to the ones matching the search string."
1152 (company-search-assert-enabled)
1153 (company-create-match-predicate)
1154 (company-search-mode 0)
1155 (company-call-frontends 'update))
1157 (defun company-search-abort ()
1158 "Abort searching the completion candidates."
1160 (company-search-assert-enabled)
1161 (company-set-selection company-search-old-selection t)
1162 (company-search-mode 0))
1164 (defun company-search-other-char ()
1166 (company-search-assert-enabled)
1167 (company-search-mode 0)
1168 (when last-input-event
1169 (clear-this-command-keys t)
1170 (setq unread-command-events (list last-input-event))))
1172 (defvar company-search-map
1174 (keymap (make-keymap)))
1175 (if (fboundp 'max-char)
1176 (set-char-table-range (nth 1 keymap) (cons #x100 (max-char))
1177 'company-search-printing-char)
1179 ;; obselete in Emacs 23
1180 (let ((l (generic-character-list))
1181 (table (nth 1 keymap)))
1183 (set-char-table-default table (car l) 'company-search-printing-char)
1184 (setq l (cdr l))))))
1185 (define-key keymap [t] 'company-search-other-char)
1187 (define-key keymap (make-string 1 i) 'company-search-other-char)
1190 (define-key keymap (vector i) 'company-search-printing-char)
1192 (let ((meta-map (make-sparse-keymap)))
1193 (define-key keymap (char-to-string meta-prefix-char) meta-map)
1194 (define-key keymap [escape] meta-map))
1195 (define-key keymap (vector meta-prefix-char t) 'company-search-other-char)
1196 (define-key keymap "\e\e\e" 'company-search-other-char)
1197 (define-key keymap [escape escape escape] 'company-search-other-char)
1199 (define-key keymap "\C-g" 'company-search-abort)
1200 (define-key keymap "\C-s" 'company-search-repeat-forward)
1201 (define-key keymap "\C-r" 'company-search-repeat-backward)
1202 (define-key keymap "\C-o" 'company-search-kill-others)
1204 "Keymap used for incrementally searching the completion candidates.")
1206 (define-minor-mode company-search-mode
1207 "Search mode for completion candidates.
1208 Don't start this directly, use `company-search-candidates' or
1209 `company-filter-candidates'."
1210 nil company-search-lighter nil
1211 (if company-search-mode
1212 (if (company-manual-begin)
1214 (setq company-search-old-selection company-selection)
1215 (company-call-frontends 'update))
1216 (setq company-search-mode nil))
1217 (kill-local-variable 'company-search-string)
1218 (kill-local-variable 'company-search-lighter)
1219 (kill-local-variable 'company-search-old-selection)
1220 (company-enable-overriding-keymap company-active-map)))
1222 (defsubst company-search-assert-enabled ()
1223 (company-assert-enabled)
1224 (unless company-search-mode
1225 (company-uninstall-map)
1226 (error "Company not in search mode")))
1228 (defun company-search-candidates ()
1229 "Start searching the completion candidates incrementally.
1231 \\<company-search-map>Search can be controlled with the commands:
1232 - `company-search-repeat-forward' (\\[company-search-repeat-forward])
1233 - `company-search-repeat-backward' (\\[company-search-repeat-backward])
1234 - `company-search-abort' (\\[company-search-abort])
1236 Regular characters are appended to the search string.
1238 The command `company-search-kill-others' (\\[company-search-kill-others]) uses
1239 the search string to limit the completion candidates."
1241 (company-search-mode 1)
1242 (company-enable-overriding-keymap company-search-map))
1244 (defvar company-filter-map
1245 (let ((keymap (make-keymap)))
1246 (define-key keymap [remap company-search-printing-char]
1247 'company-filter-printing-char)
1248 (set-keymap-parent keymap company-search-map)
1250 "Keymap used for incrementally searching the completion candidates.")
1252 (defun company-filter-candidates ()
1253 "Start filtering the completion candidates incrementally.
1254 This works the same way as `company-search-candidates' immediately
1255 followed by `company-search-kill-others' after each input."
1257 (company-search-mode 1)
1258 (company-enable-overriding-keymap company-filter-map))
1260 ;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;
1262 (defun company-select-next ()
1263 "Select the next candidate in the list."
1265 (when (company-manual-begin)
1266 (company-set-selection (1+ company-selection))))
1268 (defun company-select-previous ()
1269 "Select the previous candidate in the list."
1271 (when (company-manual-begin)
1272 (company-set-selection (1- company-selection))))
1274 (defun company-select-mouse (event)
1275 "Select the candidate picked by the mouse."
1277 (when (nth 4 (event-start event))
1278 (company-set-selection (- (cdr (posn-actual-col-row (event-start event)))
1283 (defun company-complete-mouse (event)
1284 "Complete the candidate picked by the mouse."
1286 (when (company-select-mouse event)
1287 (company-complete-selection)))
1289 (defun company-complete-selection ()
1290 "Complete the selected candidate."
1292 (when (company-manual-begin)
1293 (company-finish (nth company-selection company-candidates))))
1295 (defun company-complete-common ()
1296 "Complete the common part of all candidates."
1298 (when (company-manual-begin)
1299 (if (and (not (cdr company-candidates))
1300 (equal company-common (car company-candidates)))
1301 (company-complete-selection)
1302 (insert (company-strip-prefix company-common)))))
1304 (defun company-complete ()
1305 "Complete the common part of all candidates or the current selection.
1306 The first time this is called, the common part is completed, the second time, or
1307 when the selection has been changed, the selected candidate is completed."
1309 (when (company-manual-begin)
1310 (if (or company-selection-changed
1311 (eq last-command 'company-complete-common))
1312 (call-interactively 'company-complete-selection)
1313 (call-interactively 'company-complete-common)
1314 (setq this-command 'company-complete-common))))
1316 (defun company-complete-number (n)
1317 "Complete the Nth candidate.
1318 To show the number next to the candidates in some back-ends, enable
1319 `company-show-numbers'."
1320 (when (company-manual-begin)
1321 (and (< n 1) (> n company-candidates-length)
1322 (error "No candidate number %d" n))
1324 (company-finish (nth n company-candidates))))
1326 ;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;
1328 (defconst company-space-strings-limit 100)
1330 (defconst company-space-strings
1332 (dotimes (i company-space-strings-limit)
1333 (push (make-string (- company-space-strings-limit 1 i) ?\ ) lst))
1334 (apply 'vector lst)))
1336 (defsubst company-space-string (len)
1337 (if (< len company-space-strings-limit)
1338 (aref company-space-strings len)
1339 (make-string len ?\ )))
1341 (defsubst company-safe-substring (str from &optional to)
1342 (let ((len (length str)))
1345 (if (and to (> to len))
1346 (concat (substring str from)
1347 (company-space-string (- to len)))
1348 (substring str from to)))))
1350 ;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;
1352 (defvar company-last-metadata nil)
1353 (make-variable-buffer-local 'company-last-metadata)
1355 (defun company-fetch-metadata ()
1356 (let ((selected (nth company-selection company-candidates)))
1357 (unless (equal selected (car company-last-metadata))
1358 (setq company-last-metadata
1359 (cons selected (company-call-backend 'meta selected))))
1360 (cdr company-last-metadata)))
1362 (defun company-doc-buffer (&optional string)
1363 (with-current-buffer (get-buffer-create "*Company meta-data*")
1367 (defmacro company--electric-do (&rest body)
1368 (declare (indent 0) (debug t))
1369 `(when (company-manual-begin)
1370 (save-window-excursion
1371 (let ((height (window-height))
1372 (row (company--row)))
1374 (and (< (window-height) height)
1375 (< (- (window-height) row 2) company-tooltip-limit)
1376 (recenter (- (window-height) row 2)))
1377 (while (eq 'scroll-other-window
1378 (key-binding (vector (list (read-event)))))
1379 (call-interactively 'scroll-other-window))
1380 (when last-input-event
1381 (clear-this-command-keys t)
1382 (setq unread-command-events (list last-input-event)))))))
1384 (defun company-show-doc-buffer ()
1385 "Temporarily show a buffer with the complete documentation for the selection."
1387 (company--electric-do
1388 (let ((selected (nth company-selection company-candidates)))
1389 (display-buffer (or (company-call-backend 'doc-buffer selected)
1390 (error "No documentation available")) t))))
1391 (put 'company-show-doc-buffer 'company-keep t)
1393 (defun company-show-location ()
1394 "Temporarily display a buffer showing the selected candidate in context."
1396 (company--electric-do
1397 (let* ((selected (nth company-selection company-candidates))
1398 (location (company-call-backend 'location selected))
1399 (pos (or (cdr location) (error "No location available")))
1400 (buffer (or (and (bufferp (car location)) (car location))
1401 (find-file-noselect (car location) t))))
1402 (with-selected-window (display-buffer buffer t)
1403 (if (bufferp (car location))
1406 (set-window-start nil (point))))))
1407 (put 'company-show-location 'company-keep t)
1409 ;;; package functions ;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;
1411 (defvar company-callback nil)
1412 (make-variable-buffer-local 'company-callback)
1414 (defvar company-begin-with-marker nil)
1415 (make-variable-buffer-local 'company-begin-with-marker)
1417 (defun company-remove-callback (&optional ignored)
1418 (remove-hook 'company-completion-finished-hook company-callback t)
1419 (remove-hook 'company-completion-cancelled-hook 'company-remove-callback t)
1420 (remove-hook 'company-completion-finished-hook 'company-remove-callback t)
1421 (when company-begin-with-marker
1422 (set-marker company-begin-with-marker nil)))
1424 (defun company-begin-backend (backend &optional callback)
1425 "Start a completion at point using BACKEND."
1426 (interactive (let ((val (completing-read "Company back-end: "
1428 'functionp nil "company-")))
1430 (list (intern val)))))
1431 (when (setq company-callback callback)
1432 (add-hook 'company-completion-finished-hook company-callback nil t))
1433 (add-hook 'company-completion-cancelled-hook 'company-remove-callback nil t)
1434 (add-hook 'company-completion-finished-hook 'company-remove-callback nil t)
1435 (setq company-backend backend)
1436 ;; Return non-nil if active.
1437 (or (company-manual-begin)
1438 (error "Cannot complete at point")))
1440 (defun company-begin-with (candidates
1441 &optional prefix-length require-match callback)
1442 "Start a completion at point.
1443 CANDIDATES is the list of candidates to use and PREFIX-LENGTH is the length of
1444 the prefix that already is in the buffer before point. It defaults to 0.
1446 CALLBACK is a function called with the selected result if the user successfully
1447 completes the input.
1450 \(company-begin-with '\(\"foo\" \"foobar\" \"foobarbaz\"\)\)"
1451 (setq company-begin-with-marker (copy-marker (point) t))
1452 (company-begin-backend
1453 `(lambda (command &optional arg &rest ignored)
1455 ((eq command 'prefix)
1456 (when (equal (point) (marker-position company-begin-with-marker))
1457 (buffer-substring ,(- (point) (or prefix-length 0)) (point))))
1458 ((eq command 'candidates)
1459 (all-completions arg ',candidates))
1460 ((eq command 'require-match)
1464 ;;; pseudo-tooltip ;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;
1466 (defvar company-pseudo-tooltip-overlay nil)
1467 (make-variable-buffer-local 'company-pseudo-tooltip-overlay)
1469 (defvar company-tooltip-offset 0)
1470 (make-variable-buffer-local 'company-tooltip-offset)
1472 (defun company-pseudo-tooltip-update-offset (selection num-lines limit)
1475 (setq company-tooltip-offset
1476 (max (min selection company-tooltip-offset)
1477 (- selection -1 limit)))
1479 (when (<= company-tooltip-offset 1)
1481 (setq company-tooltip-offset 0))
1483 (when (>= company-tooltip-offset (- num-lines limit 1))
1485 (when (= selection (1- num-lines))
1486 (decf company-tooltip-offset)
1487 (when (<= company-tooltip-offset 1)
1488 (setq company-tooltip-offset 0)
1495 (defsubst company-round-tab (arg)
1496 (* (/ (+ arg tab-width) tab-width) tab-width))
1498 (defun company-untabify (str)
1499 (let* ((pieces (split-string str "\t"))
1502 (setcar copy (company-safe-substring
1503 (car copy) 0 (company-round-tab (string-width (car copy)))))
1505 (apply 'concat pieces)))
1507 (defun company-fill-propertize (line width selected)
1508 (setq line (company-safe-substring line 0 width))
1509 (add-text-properties 0 width '(face company-tooltip
1510 mouse-face company-tooltip-mouse)
1512 (add-text-properties 0 (length company-common)
1513 '(face company-tooltip-common
1514 mouse-face company-tooltip-mouse)
1517 (if (and company-search-string
1518 (string-match (regexp-quote company-search-string) line
1519 (length company-prefix)))
1521 (add-text-properties (match-beginning 0) (match-end 0)
1522 '(face company-tooltip-selection)
1524 (when (< (match-beginning 0) (length company-common))
1525 (add-text-properties (match-beginning 0) (length company-common)
1526 '(face company-tooltip-common-selection)
1528 (add-text-properties 0 width '(face company-tooltip-selection
1529 mouse-face company-tooltip-selection)
1531 (add-text-properties 0 (length company-common)
1532 '(face company-tooltip-common-selection
1533 mouse-face company-tooltip-selection)
1539 (defun company-buffer-lines (beg end)
1541 (let ((row (company--row))
1543 (while (and (equal (move-to-window-line (incf row)) row)
1545 (push (buffer-substring beg (min end (1- (point)))) lines)
1547 (unless (eq beg end)
1548 (push (buffer-substring beg end) lines))
1551 (defsubst company-modify-line (old new offset)
1552 (concat (company-safe-substring old 0 offset)
1554 (company-safe-substring old (+ offset (length new)))))
1556 (defsubst company--length-limit (lst limit)
1557 (if (nthcdr limit lst)
1561 (defun company--replacement-string (lines old column nl &optional align-top)
1563 (let ((width (length (car lines))))
1564 (when (> width (- (window-width) column))
1565 (setq column (max 0 (- (window-width) width)))))
1569 ;; untouched lines first
1570 (dotimes (i (- (length old) (length lines)))
1571 (push (pop old) new)))
1572 ;; length into old lines.
1574 (push (company-modify-line (pop old) (pop lines) column) new))
1575 ;; Append whole new lines.
1577 (push (concat (company-space-string column) (pop lines)) new))
1578 (concat (when nl "\n")
1579 (mapconcat 'identity (nreverse new) "\n")
1582 (defun company--create-lines (selection limit)
1584 (let ((len company-candidates-length)
1593 ;; Scroll to offset.
1594 (setq limit (company-pseudo-tooltip-update-offset selection len limit))
1596 (when (> company-tooltip-offset 0)
1597 (setq previous (format "...(%d)" company-tooltip-offset)))
1599 (setq remainder (- len limit company-tooltip-offset)
1600 remainder (when (> remainder 0)
1601 (setq remainder (format "...(%d)" remainder))))
1603 (decf selection company-tooltip-offset)
1604 (setq width (max (length previous) (length remainder))
1605 lines (nthcdr company-tooltip-offset company-candidates)
1610 (setq width (max (length (pop lines-copy)) width)))
1611 (setq width (min width (window-width)))
1613 (setq lines-copy lines)
1615 ;; number can make tooltip too long
1616 (when company-show-numbers
1617 (setq numbered company-tooltip-offset))
1620 (push (propertize (company-safe-substring previous 0 width)
1621 'face 'company-tooltip)
1625 (push (company-fill-propertize
1626 (if (>= numbered 10)
1627 (company-reformat (pop lines))
1630 (company-safe-substring (company-reformat (pop lines))
1633 width (equal i selection))
1637 (push (propertize (company-safe-substring remainder 0 width)
1638 'face 'company-tooltip)
1641 (setq lines (nreverse new))))
1645 (defsubst company--window-inner-height ()
1646 (let ((edges (window-inside-edges (selected-window))))
1647 (- (nth 3 edges) (nth 1 edges))))
1649 (defsubst company--pseudo-tooltip-height ()
1650 "Calculate the appropriate tooltip height.
1651 Returns a negative number if the tooltip should be displayed above point."
1652 (let* ((lines (count-lines (window-start) (point-at-bol)))
1653 (below (- (company--window-inner-height) 1 lines)))
1654 (if (and (< below (min company-tooltip-minimum company-candidates-length))
1656 (- (max 3 (min company-tooltip-limit lines)))
1657 (max 3 (min company-tooltip-limit below)))))
1659 (defun company-pseudo-tooltip-show (row column selection)
1660 (company-pseudo-tooltip-hide)
1665 (let* ((height (company--pseudo-tooltip-height))
1669 (setq row (+ row height -1)
1672 (let* ((nl (< (move-to-window-line row) row))
1674 (end (save-excursion
1675 (move-to-window-line (+ row (abs height)))
1677 (ov (make-overlay beg end))
1678 (args (list (mapcar 'company-untabify
1679 (company-buffer-lines beg end))
1682 (setq company-pseudo-tooltip-overlay ov)
1683 (overlay-put ov 'company-replacement-args args)
1684 (overlay-put ov 'company-before
1685 (apply 'company--replacement-string
1686 (company--create-lines selection (abs height))
1689 (overlay-put ov 'company-column column)
1690 (overlay-put ov 'company-height (abs height))
1691 (overlay-put ov 'window (selected-window))))))
1693 (defun company-pseudo-tooltip-show-at-point (pos)
1694 (let ((col-row (company--col-row pos)))
1696 (company-pseudo-tooltip-show (1+ (cdr col-row)) (car col-row)
1697 company-selection))))
1699 (defun company-pseudo-tooltip-edit (lines selection)
1700 (let ((column (overlay-get company-pseudo-tooltip-overlay 'company-column))
1701 (height (overlay-get company-pseudo-tooltip-overlay 'company-height)))
1702 (overlay-put company-pseudo-tooltip-overlay 'company-before
1703 (apply 'company--replacement-string
1704 (company--create-lines selection height)
1705 (overlay-get company-pseudo-tooltip-overlay
1706 'company-replacement-args)))))
1708 (defun company-pseudo-tooltip-hide ()
1709 (when company-pseudo-tooltip-overlay
1710 (delete-overlay company-pseudo-tooltip-overlay)
1711 (setq company-pseudo-tooltip-overlay nil)))
1713 (defun company-pseudo-tooltip-hide-temporarily ()
1714 (when (overlayp company-pseudo-tooltip-overlay)
1715 (overlay-put company-pseudo-tooltip-overlay 'invisible nil)
1716 (overlay-put company-pseudo-tooltip-overlay 'before-string nil)))
1718 (defun company-pseudo-tooltip-unhide ()
1719 (when company-pseudo-tooltip-overlay
1720 (overlay-put company-pseudo-tooltip-overlay 'invisible t)
1721 (overlay-put company-pseudo-tooltip-overlay 'before-string
1722 (overlay-get company-pseudo-tooltip-overlay 'company-before))
1723 (overlay-put company-pseudo-tooltip-overlay 'window (selected-window))))
1725 (defun company-pseudo-tooltip-frontend (command)
1726 "A `company-mode' front-end similar to a tool-tip but based on overlays."
1728 ('pre-command (company-pseudo-tooltip-hide-temporarily))
1730 (let ((old-height (if (overlayp company-pseudo-tooltip-overlay)
1731 (overlay-get company-pseudo-tooltip-overlay
1734 (new-height (company--pseudo-tooltip-height)))
1735 (unless (and (>= (* old-height new-height) 0)
1736 (>= (abs old-height) (abs new-height)))
1738 (company-pseudo-tooltip-show-at-point (- (point)
1739 (length company-prefix)))))
1740 (company-pseudo-tooltip-unhide))
1741 ('hide (company-pseudo-tooltip-hide)
1742 (setq company-tooltip-offset 0))
1743 ('update (when (overlayp company-pseudo-tooltip-overlay)
1744 (company-pseudo-tooltip-edit company-candidates
1745 company-selection)))))
1747 (defun company-pseudo-tooltip-unless-just-one-frontend (command)
1748 "`company-pseudo-tooltip-frontend', but not shown for single candidates."
1749 (unless (and (eq command 'post-command)
1750 (not (cdr company-candidates)))
1751 (company-pseudo-tooltip-frontend command)))
1753 ;;; overlay ;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;
1755 (defvar company-preview-overlay nil)
1756 (make-variable-buffer-local 'company-preview-overlay)
1758 (defun company-preview-show-at-point (pos)
1759 (company-preview-hide)
1761 (setq company-preview-overlay (make-overlay pos pos))
1763 (let ((completion(nth company-selection company-candidates)))
1764 (setq completion (propertize completion 'face 'company-preview))
1765 (add-text-properties 0 (length company-common)
1766 '(face company-preview-common) completion)
1768 ;; Add search string
1769 (and company-search-string
1770 (string-match (regexp-quote company-search-string) completion)
1771 (add-text-properties (match-beginning 0)
1773 '(face company-preview-search)
1776 (setq completion (company-strip-prefix completion))
1778 (and (equal pos (point))
1779 (not (equal completion ""))
1780 (add-text-properties 0 1 '(cursor t) completion))
1782 (overlay-put company-preview-overlay 'after-string completion)
1783 (overlay-put company-preview-overlay 'window (selected-window))))
1785 (defun company-preview-hide ()
1786 (when company-preview-overlay
1787 (delete-overlay company-preview-overlay)
1788 (setq company-preview-overlay nil)))
1790 (defun company-preview-frontend (command)
1791 "A `company-mode' front-end showing the selection as if it had been inserted."
1793 ('pre-command (company-preview-hide))
1794 ('post-command (company-preview-show-at-point (point)))
1795 ('hide (company-preview-hide))))
1797 (defun company-preview-if-just-one-frontend (command)
1798 "`company-preview-frontend', but only shown for single candidates."
1799 (unless (and (eq command 'post-command)
1800 (cdr company-candidates))
1801 (company-preview-frontend command)))
1803 ;;; echo ;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;
1805 (defvar company-echo-last-msg nil)
1806 (make-variable-buffer-local 'company-echo-last-msg)
1808 (defvar company-echo-timer nil)
1810 (defvar company-echo-delay .1)
1812 (defun company-echo-show (&optional getter)
1814 (setq company-echo-last-msg (funcall getter)))
1815 (let ((message-log-max nil))
1816 (if company-echo-last-msg
1817 (message "%s" company-echo-last-msg)
1820 (defsubst company-echo-show-soon (&optional getter)
1821 (when company-echo-timer
1822 (cancel-timer company-echo-timer))
1823 (setq company-echo-timer (run-with-timer company-echo-delay nil
1824 'company-echo-show getter)))
1826 (defun company-echo-format ()
1828 (let ((limit (window-width (minibuffer-window)))
1830 ;; Roll to selection.
1831 (candidates (nthcdr company-selection company-candidates))
1832 (i (if company-show-numbers company-selection 99999))
1836 (setq comp (company-reformat (pop candidates))
1837 len (+ len 1 (length comp)))
1841 (setq comp (propertize (format "%d: %s" i comp)
1842 'face 'company-echo))
1845 (add-text-properties 3 (+ 3 (length company-common))
1846 '(face company-echo-common) comp))
1847 (setq comp (propertize comp 'face 'company-echo))
1848 (add-text-properties 0 (length company-common)
1849 '(face company-echo-common) comp))
1851 (setq candidates nil)
1854 (mapconcat 'identity (nreverse msg) " ")))
1856 (defun company-echo-strip-common-format ()
1858 (let ((limit (window-width (minibuffer-window)))
1859 (len (+ (length company-prefix) 2))
1860 ;; Roll to selection.
1861 (candidates (nthcdr company-selection company-candidates))
1862 (i (if company-show-numbers company-selection 99999))
1866 (setq comp (company-strip-prefix (pop candidates))
1867 len (+ len 2 (length comp)))
1870 (setq comp (format "%s (%d)" comp i))
1874 (setq candidates nil)
1875 (push (propertize comp 'face 'company-echo) msg)))
1877 (concat (propertize company-prefix 'face 'company-echo-common) "{"
1878 (mapconcat 'identity (nreverse msg) ", ")
1881 (defun company-echo-hide ()
1882 (when company-echo-timer
1883 (cancel-timer company-echo-timer))
1884 (unless (equal company-echo-last-msg "")
1885 (setq company-echo-last-msg "")
1886 (company-echo-show)))
1888 (defun company-echo-frontend (command)
1889 "A `company-mode' front-end showing the candidates in the echo area."
1891 ('pre-command (company-echo-show-soon))
1892 ('post-command (company-echo-show-soon 'company-echo-format))
1893 ('hide (company-echo-hide))))
1895 (defun company-echo-strip-common-frontend (command)
1896 "A `company-mode' front-end showing the candidates in the echo area."
1898 ('pre-command (company-echo-show-soon))
1899 ('post-command (company-echo-show-soon 'company-echo-strip-common-format))
1900 ('hide (company-echo-hide))))
1902 (defun company-echo-metadata-frontend (command)
1903 "A `company-mode' front-end showing the documentation in the echo area."
1905 ('pre-command (company-echo-show-soon))
1906 ('post-command (company-echo-show-soon 'company-fetch-metadata))
1907 ('hide (company-echo-hide))))
1910 ;;; company.el ends here