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-with-candidate-inserted' macro.
69 ;; Added `company-clang' back-end.
70 ;; The semantic back-end now shows meta information for local symbols.
71 ;; Added compatibility for CEDET in Emacs 23.2.
74 ;; Added `company-other-backend'.
75 ;; Idle completion no longer interrupts multi-key command input.
76 ;; Added `company-ropemacs' and `company-pysmell' back-ends.
79 ;; In C modes . and -> now count towards `company-minimum-prefix-length'.
80 ;; Reverted default front-end back to `company-preview-if-just-one-frontend'.
81 ;; The pseudo tooltip will no longer be clipped at the right window edge.
82 ;; Added `company-tooltip-minimum'.
83 ;; Windows compatibility fixes.
86 ;; Added `global-company-mode'.
87 ;; Performance enhancements.
88 ;; Added `company-eclim' back-end.
89 ;; Added safer workaround for Emacs `posn-col-row' bug.
92 ;; Automatic completion is now aborted if the prefix gets too short.
93 ;; Added option `company-dabbrev-time-limit'.
94 ;; `company-backends' now supports merging back-ends.
95 ;; Added back-end `company-dabbrev-code' for generic code.
96 ;; Fixed `company-begin-with'.
99 ;; Added 'stop prefix to prevent dabbrev from completing inside of symbols.
100 ;; Fixed issues with tabbar-mode and line-spacing.
101 ;; Performance enhancements.
104 ;; Added `company-begin-commands' option.
105 ;; Added abbrev, tempo and Xcode back-ends.
106 ;; Back-ends are now interactive. You can start them with M-x backend-name.
107 ;; Added `company-begin-with' for starting company from elisp-code.
109 ;; Added `company-require-match' and `company-auto-complete' options.
111 ;; 2009-04-05 (0.2.1)
112 ;; Improved Emacs Lisp back-end behavior for local variables.
113 ;; Added `company-elisp-detect-function-context' option.
114 ;; The mouse can now be used for selection.
117 ;; Added `company-show-location'.
118 ;; Added etags back-end.
119 ;; Added work-around for end-of-buffer bug.
120 ;; Added `company-filter-candidates'.
121 ;; More local Lisp variables are now included in the candidates.
123 ;; 2009-03-21 (0.1.5)
124 ;; Fixed elisp documentation buffer always showing the same doc.
125 ;; Added `company-echo-strip-common-frontend'.
126 ;; Added `company-show-numbers' option and M-0 ... M-9 default bindings.
127 ;; Don't hide the echo message if it isn't shown.
134 (eval-when-compile (require 'cl))
136 (add-to-list 'debug-ignored-errors "^.* frontend cannot be used twice$")
137 (add-to-list 'debug-ignored-errors "^Echo area cannot be used twice$")
138 (add-to-list 'debug-ignored-errors "^No \\(document\\|loc\\)ation available$")
139 (add-to-list 'debug-ignored-errors "^Company not ")
140 (add-to-list 'debug-ignored-errors "^No candidate number ")
141 (add-to-list 'debug-ignored-errors "^Cannot complete at point$")
142 (add-to-list 'debug-ignored-errors "^No other back-end$")
144 (defgroup company nil
145 "Extensible inline text completion mechanism"
150 (defface company-tooltip
151 '((t :background "yellow"
152 :foreground "black"))
153 "*Face used for the tool tip."
156 (defface company-tooltip-selection
157 '((default :inherit company-tooltip)
158 (((class color) (min-colors 88)) (:background "orange1"))
159 (t (:background "green")))
160 "*Face used for the selection in the tool tip."
163 (defface company-tooltip-mouse
164 '((default :inherit highlight))
165 "*Face used for the tool tip item under the mouse."
168 (defface company-tooltip-common
169 '((t :inherit company-tooltip
171 "*Face used for the common completion in the tool tip."
174 (defface company-tooltip-common-selection
175 '((t :inherit company-tooltip-selection
177 "*Face used for the selected common completion in the tool tip."
180 (defface company-preview
181 '((t :background "blue4"
182 :foreground "wheat"))
183 "*Face used for the completion preview."
186 (defface company-preview-common
187 '((t :inherit company-preview
189 "*Face used for the common part of the completion preview."
192 (defface company-preview-search
193 '((t :inherit company-preview
194 :background "blue1"))
195 "*Face used for the search string in the completion preview."
198 (defface company-echo nil
199 "*Face used for completions in the echo area."
202 (defface company-echo-common
203 '((((background dark)) (:foreground "firebrick1"))
204 (((background light)) (:background "firebrick4")))
205 "*Face used for the common part of completions in the echo area."
208 (defun company-frontends-set (variable value)
210 (let ((remainder value))
211 (setcdr remainder (delq (car remainder) (cdr remainder))))
212 (and (memq 'company-pseudo-tooltip-unless-just-one-frontend value)
213 (memq 'company-pseudo-tooltip-frontend value)
214 (error "Pseudo tooltip frontend cannot be used twice"))
215 (and (memq 'company-preview-if-just-one-frontend value)
216 (memq 'company-preview-frontend value)
217 (error "Preview frontend cannot be used twice"))
218 (and (memq 'company-echo value)
219 (memq 'company-echo-metadata-frontend value)
220 (error "Echo area cannot be used twice"))
221 ;; preview must come last
222 (dolist (f '(company-preview-if-just-one-frontend company-preview-frontend))
224 (setq value (append (delq f value) (list f)))))
225 (set variable value))
227 (defcustom company-frontends '(company-pseudo-tooltip-unless-just-one-frontend
228 company-preview-if-just-one-frontend
229 company-echo-metadata-frontend)
230 "*The list of active front-ends (visualizations).
231 Each front-end is a function that takes one argument. It is called with
232 one of the following arguments:
234 'show: When the visualization should start.
236 'hide: When the visualization should end.
238 'update: When the data has been updated.
240 'pre-command: Before every command that is executed while the
241 visualization is active.
243 'post-command: After every command that is executed while the
244 visualization is active.
246 The visualized data is stored in `company-prefix', `company-candidates',
247 `company-common', `company-selection', `company-point' and
248 `company-search-string'."
249 :set 'company-frontends-set
251 :type '(repeat (choice (const :tag "echo" company-echo-frontend)
252 (const :tag "echo, strip common"
253 company-echo-strip-common-frontend)
254 (const :tag "show echo meta-data in echo"
255 company-echo-metadata-frontend)
256 (const :tag "pseudo tooltip"
257 company-pseudo-tooltip-frontend)
258 (const :tag "pseudo tooltip, multiple only"
259 company-pseudo-tooltip-unless-just-one-frontend)
260 (const :tag "preview" company-preview-frontend)
261 (const :tag "preview, unique only"
262 company-preview-if-just-one-frontend)
263 (function :tag "custom function" nil))))
265 (defcustom company-tooltip-limit 10
266 "*The maximum number of candidates in the tool tip"
270 (defcustom company-tooltip-minimum 6
271 "*The minimum height of the tool tip.
272 If this many lines are not available, prefer to display the tooltip above."
276 (defvar company-safe-backends
277 '((company-abbrev . "Abbrev")
278 (company-clang . "clang")
279 (company-css . "CSS")
280 (company-dabbrev . "dabbrev for plain text")
281 (company-dabbrev-code . "dabbrev for code")
282 (company-eclim . "eclim (an Eclipse interace)")
283 (company-elisp . "Emacs Lisp")
284 (company-etags . "etags")
285 (company-files . "Files")
286 (company-gtags . "GNU Global")
287 (company-ispell . "ispell")
288 (company-keywords . "Programming language keywords")
289 (company-nxml . "nxml")
290 (company-oddmuse . "Oddmuse")
291 (company-pysmell . "PySmell")
292 (company-ropemacs . "ropemacs")
293 (company-semantic . "CEDET Semantic")
294 (company-tempo . "Tempo templates")
295 (company-xcode . "Xcode")))
296 (put 'company-safe-backends 'risky-local-variable t)
298 (defun company-safe-backends-p (backends)
299 (and (consp backends)
300 (not (dolist (backend backends)
301 (unless (if (consp backend)
302 (company-safe-backends-p backend)
303 (assq backend company-safe-backends))
306 (defcustom company-backends '(company-elisp company-nxml company-css
307 company-eclim company-semantic company-clang
308 company-xcode company-ropemacs
309 (company-gtags company-etags company-dabbrev-code
310 company-pysmell company-keywords)
311 company-oddmuse company-files company-dabbrev)
312 "*The list of active back-ends (completion engines).
313 Each list elements can itself be a list of back-ends. In that case their
314 completions are merged. Otherwise only the first matching back-end returns
317 `company-begin-backend' can be used to start a specific back-end,
318 `company-other-backend' will skip to the next matching back-end in the list.
320 Each back-end is a function that takes a variable number of arguments.
321 The first argument is the command requested from the back-end. It is one
324 'prefix: The back-end should return the text to be completed. It must be
325 text immediately before `point'. Returning nil passes control to the next
326 back-end. The function should return 'stop if it should complete but cannot
327 \(e.g. if it is in the middle of a string\). If the returned value is only
328 part of the prefix (e.g. the part after \"->\" in C), the back-end may return a
329 cons of prefix and prefix length, which is then used in the
330 `company-minimum-prefix-length' test.
332 'candidates: The second argument is the prefix to be completed. The
333 return value should be a list of candidates that start with the prefix.
337 'sorted: The back-end may return t here to indicate that the candidates
338 are sorted and will not need to be sorted again.
340 'duplicates: If non-nil, company will take care of removing duplicates
343 'no-cache: Usually company doesn't ask for candidates again as completion
344 progresses, unless the back-end returns t for this command. The second
345 argument is the latest prefix.
347 'meta: The second argument is a completion candidate. The back-end should
348 return a (short) documentation string for it.
350 'doc-buffer: The second argument is a completion candidate. The back-end should
351 create a buffer (preferably with `company-doc-buffer'), fill it with
352 documentation and return it.
354 'location: The second argument is a completion candidate. The back-end can
355 return the cons of buffer and buffer location, or of file and line
356 number where the completion candidate was defined.
358 'require-match: If this value is t, the user is not allowed to enter anything
359 not offering as a candidate. Use with care! The default value nil gives the
360 user that choice with `company-require-match'. Return value 'never overrides
361 that option the other way around.
363 The back-end should return nil for all commands it does not support or
364 does not know about. It should also be callable interactively and use
365 `company-begin-backend' to start itself in that case."
370 ,@(mapcar (lambda (b) `(const :tag ,(cdr b) ,(car b)))
371 company-safe-backends)
372 (symbol :tag "User defined")
373 (repeat :tag "Merged Back-ends"
374 (choice :tag "Back-end"
375 ,@(mapcar (lambda (b)
376 `(const :tag ,(cdr b) ,(car b)))
377 company-safe-backends)
378 (symbol :tag "User defined"))))))
380 (put 'company-backends 'safe-local-variable 'company-safe-backends-p)
382 (defcustom company-completion-started-hook nil
383 "*Hook run when company starts completing.
384 The hook is called with one argument that is non-nil if the completion was
389 (defcustom company-completion-cancelled-hook nil
390 "*Hook run when company cancels completing.
391 The hook is called with one argument that is non-nil if the completion was
396 (defcustom company-completion-finished-hook nil
397 "*Hook run when company successfully completes.
398 The hook is called with the selected candidate as an argument."
402 (defcustom company-minimum-prefix-length 3
403 "*The minimum prefix length for automatic completion."
405 :type '(integer :tag "prefix length"))
407 (defcustom company-require-match 'company-explicit-action-p
408 "*If enabled, disallow non-matching input.
409 This can be a function do determine if a match is required.
411 This can be overridden by the back-end, if it returns t or 'never to
412 'require-match. `company-auto-complete' also takes precedence over this."
414 :type '(choice (const :tag "Off" nil)
415 (function :tag "Predicate function")
416 (const :tag "On, if user interaction took place"
417 'company-explicit-action-p)
418 (const :tag "On" t)))
420 (defcustom company-auto-complete 'company-explicit-action-p
421 "Determines when to auto-complete.
422 If this is enabled, all characters from `company-auto-complete-chars' complete
423 the selected completion. This can also be a function."
425 :type '(choice (const :tag "Off" nil)
426 (function :tag "Predicate function")
427 (const :tag "On, if user interaction took place"
428 'company-explicit-action-p)
429 (const :tag "On" t)))
431 (defcustom company-auto-complete-chars '(?\ ?\( ?\) ?. ?\" ?$ ?\' ?< ?| ?!)
432 "Determines which characters trigger an automatic completion.
433 See `company-auto-complete'. If this is a string, each string character causes
434 completion. If it is a list of syntax description characters (see
435 `modify-syntax-entry'), all characters with that syntax auto-complete.
437 This can also be a function, which is called with the new input and should
438 return non-nil if company should auto-complete.
440 A character that is part of a valid candidate never starts auto-completion."
442 :type '(choice (string :tag "Characters")
444 (const :tag "Whitespace" ?\ )
445 (const :tag "Symbol" ?_)
446 (const :tag "Opening parentheses" ?\()
447 (const :tag "Closing parentheses" ?\))
448 (const :tag "Word constituent" ?w)
449 (const :tag "Punctuation." ?.)
450 (const :tag "String quote." ?\")
451 (const :tag "Paired delimiter." ?$)
452 (const :tag "Expression quote or prefix operator." ?\')
453 (const :tag "Comment starter." ?<)
454 (const :tag "Comment ender." ?>)
455 (const :tag "Character-quote." ?/)
456 (const :tag "Generic string fence." ?|)
457 (const :tag "Generic comment fence." ?!))
458 (function :tag "Predicate function")))
460 (defcustom company-idle-delay .7
461 "*The idle delay in seconds until automatic completions starts.
462 A value of nil means never complete automatically, t means complete
463 immediately when a prefix of `company-minimum-prefix-length' is reached."
465 :type '(choice (const :tag "never (nil)" nil)
466 (const :tag "immediate (t)" t)
467 (number :tag "seconds")))
469 (defcustom company-begin-commands t
470 "*A list of commands following which company will start completing.
471 If this is t, it will complete after any command. See `company-idle-delay'.
473 Alternatively any command with a non-nil 'company-begin property is treated as
474 if it was on this list."
476 :type '(choice (const :tag "Any command" t)
477 (const :tag "Self insert command" '(self-insert-command))
478 (repeat :tag "Commands" function)))
480 (defcustom company-show-numbers nil
481 "*If enabled, show quick-access numbers for the first ten candidates."
483 :type '(choice (const :tag "off" nil)
484 (const :tag "on" t)))
486 (defvar company-end-of-buffer-workaround t
487 "*Work around a visualization bug when completing at the end of the buffer.
488 The work-around consists of adding a newline.")
490 ;;; mode ;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;
492 (defvar company-mode-map (make-sparse-keymap)
493 "Keymap used by `company-mode'.")
495 (defvar company-active-map
496 (let ((keymap (make-sparse-keymap)))
497 (define-key keymap "\e\e\e" 'company-abort)
498 (define-key keymap "\C-g" 'company-abort)
499 (define-key keymap (kbd "M-n") 'company-select-next)
500 (define-key keymap (kbd "M-p") 'company-select-previous)
501 (define-key keymap (kbd "<down>") 'company-select-next)
502 (define-key keymap (kbd "<up>") 'company-select-previous)
503 (define-key keymap [down-mouse-1] 'ignore)
504 (define-key keymap [down-mouse-3] 'ignore)
505 (define-key keymap [mouse-1] 'company-complete-mouse)
506 (define-key keymap [mouse-3] 'company-select-mouse)
507 (define-key keymap [up-mouse-1] 'ignore)
508 (define-key keymap [up-mouse-3] 'ignore)
509 (define-key keymap "\C-m" 'company-complete-selection)
510 (define-key keymap "\t" 'company-complete-common)
511 (define-key keymap (kbd "<f1>") 'company-show-doc-buffer)
512 (define-key keymap "\C-w" 'company-show-location)
513 (define-key keymap "\C-s" 'company-search-candidates)
514 (define-key keymap "\C-\M-s" 'company-filter-candidates)
516 (define-key keymap (vector (+ (aref (kbd "M-0") 0) i))
517 `(lambda () (interactive) (company-complete-number ,i))))
520 "Keymap that is enabled during an active completion.")
522 (defvar company--disabled-backends nil)
524 (defun company-init-backend (backend)
525 (and (symbolp backend)
526 (not (fboundp backend))
527 (ignore-errors (require backend nil t)))
529 (if (or (symbolp backend)
533 (funcall backend 'init)
534 (put backend 'company-init t))
536 (put backend 'company-init 'failed)
537 (unless (memq backend company--disabled-backends)
538 (message "Company back-end '%s' could not be initialized:\n%s"
539 backend (error-message-string err)))
540 (push backend company--disabled-backends)
542 (mapc 'company-init-backend backend)))
544 (defvar company-default-lighter " company")
546 (defvar company-lighter company-default-lighter)
547 (make-variable-buffer-local 'company-lighter)
550 (define-minor-mode company-mode
551 "\"complete anything\"; in in-buffer completion framework.
552 Completion starts automatically, depending on the values
553 `company-idle-delay' and `company-minimum-prefix-length'.
555 Completion can be controlled with the commands:
556 `company-complete-common', `company-complete-selection', `company-complete',
557 `company-select-next', `company-select-previous'. If these commands are
558 called before `company-idle-delay', completion will also start.
560 Completions can be searched with `company-search-candidates' or
561 `company-filter-candidates'. These can be used while completion is
564 The completion data is retrieved using `company-backends' and displayed using
565 `company-frontends'. If you want to start a specific back-end, call it
566 interactively or use `company-begin-backend'.
568 regular keymap (`company-mode-map'):
571 keymap during active completions (`company-active-map'):
573 \\{company-active-map}"
574 nil company-lighter company-mode-map
577 (add-hook 'pre-command-hook 'company-pre-command nil t)
578 (add-hook 'post-command-hook 'company-post-command nil t)
579 (mapc 'company-init-backend company-backends))
580 (remove-hook 'pre-command-hook 'company-pre-command t)
581 (remove-hook 'post-command-hook 'company-post-command t)
583 (kill-local-variable 'company-point)))
585 (define-globalized-minor-mode global-company-mode company-mode
586 (lambda () (company-mode 1)))
588 (defsubst company-assert-enabled ()
590 (company-uninstall-map)
591 (error "Company not enabled")))
593 ;;; keymaps ;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;
595 (defvar company-overriding-keymap-bound nil)
596 (make-variable-buffer-local 'company-overriding-keymap-bound)
598 (defvar company-old-keymap nil)
599 (make-variable-buffer-local 'company-old-keymap)
601 (defvar company-my-keymap nil)
602 (make-variable-buffer-local 'company-my-keymap)
604 (defsubst company-enable-overriding-keymap (keymap)
605 (setq company-my-keymap keymap)
606 (when company-overriding-keymap-bound
607 (company-uninstall-map)))
609 (defun company-install-map ()
610 (unless (or company-overriding-keymap-bound
611 (null company-my-keymap))
612 (setq company-old-keymap overriding-terminal-local-map
613 overriding-terminal-local-map company-my-keymap
614 company-overriding-keymap-bound t)))
616 (defun company-uninstall-map ()
617 (when (eq overriding-terminal-local-map company-my-keymap)
618 (setq overriding-terminal-local-map company-old-keymap
619 company-overriding-keymap-bound nil)))
622 ;; Emacs calculates the active keymaps before reading the event. That means we
623 ;; cannot change the keymap from a timer. So we send a bogus command.
624 (defun company-ignore ()
626 (setq this-command last-command))
628 (global-set-key '[31415926] 'company-ignore)
630 (defun company-input-noop ()
631 (push 31415926 unread-command-events))
634 ;; posn-col-row is incorrect in older Emacsen when line-spacing is set
635 (defun company--col-row (&optional pos)
636 (let ((posn (posn-at-point pos)))
637 (cons (car (posn-col-row posn)) (cdr (posn-actual-col-row posn)))))
639 (defsubst company--column (&optional pos)
640 (car (posn-col-row (posn-at-point pos))))
642 (defsubst company--row (&optional pos)
643 (cdr (posn-actual-col-row (posn-at-point pos))))
645 ;;; backends ;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;
647 (defun company-grab (regexp &optional expression limit)
648 (when (looking-back regexp limit)
649 (or (match-string-no-properties (or expression 0)) "")))
651 (defun company-grab-line (regexp &optional expression)
652 (company-grab regexp expression (point-at-bol)))
654 (defun company-grab-symbol ()
655 (if (looking-at "\\_>")
656 (buffer-substring (point) (save-excursion (skip-syntax-backward "w_")
658 (unless (and (char-after) (memq (char-syntax (char-after)) '(?w ?_)))
661 (defun company-grab-word ()
662 (if (looking-at "\\>")
663 (buffer-substring (point) (save-excursion (skip-syntax-backward "w")
665 (unless (and (char-after) (eq (char-syntax (char-after)) ?w))
668 (defun company-in-string-or-comment ()
669 (let ((ppss (syntax-ppss)))
670 (or (car (setq ppss (nthcdr 3 ppss)))
671 (car (setq ppss (cdr ppss)))
674 (if (fboundp 'locate-dominating-file)
675 (defalias 'company-locate-dominating-file 'locate-dominating-file)
676 (defun company-locate-dominating-file (file name)
678 (let ((dir (file-name-directory file))
680 (while (not (equal dir prev-dir))
681 (when (file-exists-p (expand-file-name name dir))
684 dir (file-name-directory (directory-file-name dir))))))))
686 (defun company-call-backend (&rest args)
687 (if (functionp company-backend)
688 (apply company-backend args)
689 (apply 'company--multi-backend-adapter company-backend args)))
691 (defun company--multi-backend-adapter (backends command &rest args)
694 (apply 'append (mapcar (lambda (backend) (apply backend command args))
700 (dolist (backend backends)
701 (when (setq value (apply backend command args))
704 ;;; completion mechanism ;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;
706 (defvar company-backend nil)
707 (make-variable-buffer-local 'company-backend)
709 (defvar company-prefix nil)
710 (make-variable-buffer-local 'company-prefix)
712 (defvar company-candidates nil)
713 (make-variable-buffer-local 'company-candidates)
715 (defvar company-candidates-length nil)
716 (make-variable-buffer-local 'company-candidates-length)
718 (defvar company-candidates-cache nil)
719 (make-variable-buffer-local 'company-candidates-cache)
721 (defvar company-candidates-predicate nil)
722 (make-variable-buffer-local 'company-candidates-predicate)
724 (defvar company-common nil)
725 (make-variable-buffer-local 'company-common)
727 (defvar company-selection 0)
728 (make-variable-buffer-local 'company-selection)
730 (defvar company-selection-changed nil)
731 (make-variable-buffer-local 'company-selection-changed)
733 (defvar company--explicit-action nil
734 "Non-nil, if explicit completion took place.")
735 (make-variable-buffer-local 'company--explicit-action)
737 (defvar company--point-max nil)
738 (make-variable-buffer-local 'company--point-max)
740 (defvar company-point nil)
741 (make-variable-buffer-local 'company-point)
743 (defvar company-timer nil)
745 (defvar company-added-newline nil)
746 (make-variable-buffer-local 'company-added-newline)
748 (defsubst company-strip-prefix (str)
749 (substring str (length company-prefix)))
751 (defmacro company-with-candidate-inserted (candidate &rest body)
752 "Evaluate BODY with CANDIDATE temporarily inserted.
753 This is a tool for back-ends that need candidates inserted before they
754 can retrieve meta-data for them."
756 `(let ((inhibit-modification-hooks t)
757 (inhibit-point-motion-hooks t)
758 (modified-p (buffer-modified-p)))
759 (insert (company-strip-prefix ,candidate))
762 (delete-region company-point (point)))))
764 (defun company-explicit-action-p ()
765 "Return whether explicit completion action was taken by the user."
766 (or company--explicit-action
767 company-selection-changed))
769 (defsubst company-reformat (candidate)
770 ;; company-ispell needs this, because the results are always lower-case
771 ;; It's mory efficient to fix it only when they are displayed.
772 (concat company-prefix (substring candidate (length company-prefix))))
774 (defun company--should-complete ()
775 (and (not (or buffer-read-only overriding-terminal-local-map
776 overriding-local-map))
777 ;; Check if in the middle of entering a key combination.
778 (or (equal (this-command-keys-vector) [])
779 (not (keymapp (key-binding (this-command-keys-vector)))))
780 (eq company-idle-delay t)
781 (or (eq t company-begin-commands)
782 (memq this-command company-begin-commands)
783 (and (symbolp this-command) (get this-command 'company-begin)))
784 (not (and transient-mark-mode mark-active))))
786 (defsubst company-call-frontends (command)
787 (dolist (frontend company-frontends)
789 (funcall frontend command)
790 (error (error "Company: Front-end %s error \"%s\" on command %s"
791 frontend (error-message-string err) command)))))
793 (defsubst company-set-selection (selection &optional force-update)
794 (setq selection (max 0 (min (1- company-candidates-length) selection)))
795 (when (or force-update (not (equal selection company-selection)))
796 (setq company-selection selection
797 company-selection-changed t)
798 (company-call-frontends 'update)))
800 (defun company-apply-predicate (candidates predicate)
802 (dolist (c candidates)
803 (when (funcall predicate c)
807 (defun company-update-candidates (candidates)
808 (setq company-candidates-length (length candidates))
809 (if (> company-selection 0)
810 ;; Try to restore the selection
811 (let ((selected (nth company-selection company-candidates)))
812 (setq company-selection 0
813 company-candidates candidates)
815 (while (and candidates (string< (pop candidates) selected))
816 (incf company-selection))
818 ;; Make sure selection isn't out of bounds.
819 (setq company-selection (min (1- company-candidates-length)
820 company-selection)))))
821 (setq company-selection 0
822 company-candidates candidates))
824 (push (cons company-prefix company-candidates) company-candidates-cache)
826 (let ((completion-ignore-case (company-call-backend 'ignore-case)))
827 (setq company-common (try-completion company-prefix company-candidates)))
828 (when (eq company-common t)
829 (setq company-candidates nil)))
831 (defun company-calculate-candidates (prefix)
832 (let ((candidates (cdr (assoc prefix company-candidates-cache))))
834 (when company-candidates-cache
835 (let ((len (length prefix))
836 (completion-ignore-case (company-call-backend 'ignore-case))
838 (dotimes (i (1+ len))
839 (when (setq prev (cdr (assoc (substring prefix 0 (- len i))
840 company-candidates-cache)))
841 (setq candidates (all-completions prefix prev))
843 ;; no cache match, call back-end
845 (setq candidates (company-call-backend 'candidates prefix))
846 (when company-candidates-predicate
848 (company-apply-predicate candidates
849 company-candidates-predicate)))
850 (unless (company-call-backend 'sorted)
851 (setq candidates (sort candidates 'string<)))
852 (when (company-call-backend 'duplicates)
854 (let ((c2 candidates))
856 (setcdr c2 (progn (while (equal (pop c2) (car c2)))
858 (if (or (cdr candidates)
859 (not (equal (car candidates) prefix)))
860 ;; Don't start when already completed and unique.
862 ;; Not the right place? maybe when setting?
863 (and company-candidates t))))
865 (defun company-idle-begin (buf win tick pos)
867 (eq buf (current-buffer))
868 (eq win (selected-window))
869 (eq tick (buffer-chars-modified-tick))
871 (not company-candidates)
872 (not (equal (point) company-point))
873 (let ((company-idle-delay t)
874 (company-begin-commands t))
876 (when company-candidates
878 (company-post-command)))))
880 (defun company-auto-begin ()
881 (company-assert-enabled)
883 (not company-candidates)
884 (let ((company-idle-delay t)
885 (company-minimum-prefix-length 0)
886 (company-begin-commands t))
888 ;; Return non-nil if active.
891 (defun company-manual-begin ()
893 (setq company--explicit-action t)
894 (company-auto-begin))
896 (defun company-other-backend (&optional backward)
897 (interactive (list current-prefix-arg))
898 (company-assert-enabled)
900 (let* ((after (cdr (member company-backend company-backends)))
901 (before (cdr (member company-backend (reverse company-backends))))
903 (append before (reverse after))
904 (append after (reverse before)))))
906 (dolist (backend next)
907 (when (ignore-errors (company-begin-backend backend))
909 (company-manual-begin))
910 (unless company-candidates
911 (error "No other back-end")))
913 (defun company-require-match-p ()
914 (let ((backend-value (company-call-backend 'require-match)))
915 (or (eq backend-value t)
916 (and (if (functionp company-require-match)
917 (funcall company-require-match)
918 (eq company-require-match t))
919 (not (eq backend-value 'never))))))
921 (defun company-punctuation-p (input)
922 "Return non-nil, if input starts with punctuation or parentheses."
923 (memq (char-syntax (string-to-char input)) '(?. ?\( ?\))))
925 (defun company-auto-complete-p (input)
926 "Return non-nil, if input starts with punctuation or parentheses."
927 (and (if (functionp company-auto-complete)
928 (funcall company-auto-complete)
929 company-auto-complete)
930 (if (functionp company-auto-complete-chars)
931 (funcall company-auto-complete-chars input)
932 (if (consp company-auto-complete-chars)
933 (memq (char-syntax (string-to-char input))
934 company-auto-complete-chars)
935 (string-match (substring input 0 1) company-auto-complete-chars)))))
937 (defun company--incremental-p ()
938 (and (> (point) company-point)
939 (> (point-max) company--point-max)
940 (not (eq this-command 'backward-delete-char-untabify))
941 (equal (buffer-substring (- company-point (length company-prefix))
945 (defsubst company--string-incremental-p (old-prefix new-prefix)
946 (and (> (length new-prefix) (length old-prefix))
947 (equal old-prefix (substring new-prefix 0 (length old-prefix)))))
949 (defun company--continue-failed (new-prefix)
950 (when (company--incremental-p)
951 (let ((input (buffer-substring-no-properties (point) company-point)))
953 ((company-auto-complete-p input)
956 (goto-char company-point)
957 (company-complete-selection)
959 ((and (company--string-incremental-p company-prefix new-prefix)
960 (company-require-match-p))
961 ;; wrong incremental input, but required match
962 (backward-delete-char (length input))
964 (message "Matching input is required")
966 ((equal company-prefix (car company-candidates))
967 ;; last input was actually success
968 (company-cancel company-prefix)
971 (defun company--good-prefix-p (prefix)
972 (and (or (company-explicit-action-p)
973 (>= (or (cdr-safe prefix) (length prefix))
974 company-minimum-prefix-length))
975 (stringp (or (car-safe prefix) prefix))))
977 (defun company--continue ()
978 (when (company-call-backend 'no-cache company-prefix)
979 ;; Don't complete existing candidates, fetch new ones.
980 (setq company-candidates-cache nil))
981 (let* ((new-prefix (company-call-backend 'prefix))
982 (c (when (and (company--good-prefix-p new-prefix)
983 (setq new-prefix (or (car-safe new-prefix) new-prefix))
984 (= (- (point) (length new-prefix))
985 (- company-point (length company-prefix))))
986 (setq new-prefix (or (car-safe new-prefix) new-prefix))
987 (company-calculate-candidates new-prefix))))
990 ;; t means complete/unique.
991 (company-cancel new-prefix)
995 (setq company-prefix new-prefix)
996 (company-update-candidates c)
998 (t (company--continue-failed new-prefix)))
1001 (defun company--begin-new ()
1003 (dolist (backend (if company-backend
1004 ;; prefer manual override
1005 (list company-backend)
1008 (if (or (symbolp backend)
1009 (functionp backend))
1010 (when (or (not (symbolp backend))
1011 (eq t (get backend 'company-init))
1012 (unless (get backend 'company-init)
1013 (company-init-backend backend)))
1014 (funcall backend 'prefix))
1015 (company--multi-backend-adapter backend 'prefix)))
1017 (when (company--good-prefix-p prefix)
1018 (setq prefix (or (car-safe prefix) prefix)
1019 company-backend backend
1020 c (company-calculate-candidates prefix))
1021 ;; t means complete/unique. We don't start, so no hooks.
1023 (when company--explicit-action
1024 (message "No completion found"))
1025 (setq company-prefix prefix)
1026 (when (symbolp backend)
1027 (setq company-lighter (concat " " (symbol-name backend))))
1028 (company-update-candidates c)
1029 (run-hook-with-args 'company-completion-started-hook
1030 (company-explicit-action-p))
1031 (company-call-frontends 'show)))
1034 (defun company-begin ()
1035 (setq company-candidates
1036 (or (and company-candidates (company--continue))
1037 (and (company--should-complete) (company--begin-new))))
1038 (when company-candidates
1039 (when (and company-end-of-buffer-workaround (eobp))
1040 (save-excursion (insert "\n"))
1041 (setq company-added-newline (buffer-chars-modified-tick)))
1042 (setq company-point (point)
1043 company--point-max (point-max))
1044 (company-enable-overriding-keymap company-active-map)
1045 (company-call-frontends 'update)))
1047 (defun company-cancel (&optional result)
1048 (and company-added-newline
1049 (> (point-max) (point-min))
1050 (let ((tick (buffer-chars-modified-tick)))
1051 (delete-region (1- (point-max)) (point-max))
1052 (equal tick company-added-newline))
1053 ;; Only set unmodified when tick remained the same since insert.
1054 (set-buffer-modified-p nil))
1055 (when company-prefix
1056 (if (stringp result)
1057 (run-hook-with-args 'company-completion-finished-hook result)
1058 (run-hook-with-args 'company-completion-cancelled-hook result)))
1059 (setq company-added-newline nil
1062 company-candidates nil
1063 company-candidates-length nil
1064 company-candidates-cache nil
1065 company-candidates-predicate nil
1068 company-selection-changed nil
1069 company--explicit-action nil
1070 company-lighter company-default-lighter
1071 company--point-max nil
1074 (cancel-timer company-timer))
1075 (company-search-mode 0)
1076 (company-call-frontends 'hide)
1077 (company-enable-overriding-keymap nil))
1079 (defun company-abort ()
1082 ;; Don't start again, unless started manually.
1083 (setq company-point (point)))
1085 (defun company-finish (result)
1086 (insert (company-strip-prefix result))
1087 (company-cancel result)
1088 ;; Don't start again, unless started manually.
1089 (setq company-point (point)))
1091 (defsubst company-keep (command)
1092 (and (symbolp command) (get command 'company-keep)))
1094 (defun company-pre-command ()
1095 (unless (company-keep this-command)
1097 (when company-candidates
1098 (company-call-frontends 'pre-command))
1099 (error (message "Company: An error occurred in pre-command")
1100 (message "%s" (error-message-string err))
1103 (cancel-timer company-timer)
1104 (setq company-timer nil))
1105 (company-uninstall-map))
1107 (defun company-post-command ()
1108 (unless (company-keep this-command)
1111 (unless (equal (point) company-point)
1113 (if company-candidates
1114 (company-call-frontends 'post-command)
1115 (and (numberp company-idle-delay)
1116 (or (eq t company-begin-commands)
1117 (memq this-command company-begin-commands))
1119 (run-with-timer company-idle-delay nil
1121 (current-buffer) (selected-window)
1122 (buffer-chars-modified-tick) (point))))))
1123 (error (message "Company: An error occurred in post-command")
1124 (message "%s" (error-message-string err))
1126 (company-install-map))
1128 ;;; search ;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;
1130 (defvar company-search-string nil)
1131 (make-variable-buffer-local 'company-search-string)
1133 (defvar company-search-lighter " Search: \"\"")
1134 (make-variable-buffer-local 'company-search-lighter)
1136 (defvar company-search-old-map nil)
1137 (make-variable-buffer-local 'company-search-old-map)
1139 (defvar company-search-old-selection 0)
1140 (make-variable-buffer-local 'company-search-old-selection)
1142 (defun company-search (text lines)
1143 (let ((quoted (regexp-quote text))
1145 (dolist (line lines)
1146 (when (string-match quoted line (length company-prefix))
1150 (defun company-search-printing-char ()
1152 (company-search-assert-enabled)
1153 (setq company-search-string
1154 (concat (or company-search-string "") (string last-command-event))
1155 company-search-lighter (concat " Search: \"" company-search-string
1157 (let ((pos (company-search company-search-string
1158 (nthcdr company-selection company-candidates))))
1161 (company-set-selection (+ company-selection pos) t))))
1163 (defun company-search-repeat-forward ()
1164 "Repeat the incremental search in completion candidates forward."
1166 (company-search-assert-enabled)
1167 (let ((pos (company-search company-search-string
1168 (cdr (nthcdr company-selection
1169 company-candidates)))))
1172 (company-set-selection (+ company-selection pos 1) t))))
1174 (defun company-search-repeat-backward ()
1175 "Repeat the incremental search in completion candidates backwards."
1177 (company-search-assert-enabled)
1178 (let ((pos (company-search company-search-string
1179 (nthcdr (- company-candidates-length
1181 (reverse company-candidates)))))
1184 (company-set-selection (- company-selection pos 1) t))))
1186 (defun company-create-match-predicate ()
1187 (setq company-candidates-predicate
1188 `(lambda (candidate)
1189 ,(if company-candidates-predicate
1190 `(and (string-match ,company-search-string candidate)
1191 (funcall ,company-candidates-predicate
1193 `(string-match ,company-search-string candidate))))
1194 (company-update-candidates
1195 (company-apply-predicate company-candidates company-candidates-predicate))
1196 ;; Invalidate cache.
1197 (setq company-candidates-cache (cons company-prefix company-candidates)))
1199 (defun company-filter-printing-char ()
1201 (company-search-assert-enabled)
1202 (company-search-printing-char)
1203 (company-create-match-predicate)
1204 (company-call-frontends 'update))
1206 (defun company-search-kill-others ()
1207 "Limit the completion candidates to the ones matching the search string."
1209 (company-search-assert-enabled)
1210 (company-create-match-predicate)
1211 (company-search-mode 0)
1212 (company-call-frontends 'update))
1214 (defun company-search-abort ()
1215 "Abort searching the completion candidates."
1217 (company-search-assert-enabled)
1218 (company-set-selection company-search-old-selection t)
1219 (company-search-mode 0))
1221 (defun company-search-other-char ()
1223 (company-search-assert-enabled)
1224 (company-search-mode 0)
1225 (when last-input-event
1226 (clear-this-command-keys t)
1227 (setq unread-command-events (list last-input-event))))
1229 (defvar company-search-map
1231 (keymap (make-keymap)))
1232 (if (fboundp 'max-char)
1233 (set-char-table-range (nth 1 keymap) (cons #x100 (max-char))
1234 'company-search-printing-char)
1236 ;; obselete in Emacs 23
1237 (let ((l (generic-character-list))
1238 (table (nth 1 keymap)))
1240 (set-char-table-default table (car l) 'company-search-printing-char)
1241 (setq l (cdr l))))))
1242 (define-key keymap [t] 'company-search-other-char)
1244 (define-key keymap (make-string 1 i) 'company-search-other-char)
1247 (define-key keymap (vector i) 'company-search-printing-char)
1249 (let ((meta-map (make-sparse-keymap)))
1250 (define-key keymap (char-to-string meta-prefix-char) meta-map)
1251 (define-key keymap [escape] meta-map))
1252 (define-key keymap (vector meta-prefix-char t) 'company-search-other-char)
1253 (define-key keymap "\e\e\e" 'company-search-other-char)
1254 (define-key keymap [escape escape escape] 'company-search-other-char)
1256 (define-key keymap "\C-g" 'company-search-abort)
1257 (define-key keymap "\C-s" 'company-search-repeat-forward)
1258 (define-key keymap "\C-r" 'company-search-repeat-backward)
1259 (define-key keymap "\C-o" 'company-search-kill-others)
1261 "Keymap used for incrementally searching the completion candidates.")
1263 (define-minor-mode company-search-mode
1264 "Search mode for completion candidates.
1265 Don't start this directly, use `company-search-candidates' or
1266 `company-filter-candidates'."
1267 nil company-search-lighter nil
1268 (if company-search-mode
1269 (if (company-manual-begin)
1271 (setq company-search-old-selection company-selection)
1272 (company-call-frontends 'update))
1273 (setq company-search-mode nil))
1274 (kill-local-variable 'company-search-string)
1275 (kill-local-variable 'company-search-lighter)
1276 (kill-local-variable 'company-search-old-selection)
1277 (company-enable-overriding-keymap company-active-map)))
1279 (defsubst company-search-assert-enabled ()
1280 (company-assert-enabled)
1281 (unless company-search-mode
1282 (company-uninstall-map)
1283 (error "Company not in search mode")))
1285 (defun company-search-candidates ()
1286 "Start searching the completion candidates incrementally.
1288 \\<company-search-map>Search can be controlled with the commands:
1289 - `company-search-repeat-forward' (\\[company-search-repeat-forward])
1290 - `company-search-repeat-backward' (\\[company-search-repeat-backward])
1291 - `company-search-abort' (\\[company-search-abort])
1293 Regular characters are appended to the search string.
1295 The command `company-search-kill-others' (\\[company-search-kill-others]) uses
1296 the search string to limit the completion candidates."
1298 (company-search-mode 1)
1299 (company-enable-overriding-keymap company-search-map))
1301 (defvar company-filter-map
1302 (let ((keymap (make-keymap)))
1303 (define-key keymap [remap company-search-printing-char]
1304 'company-filter-printing-char)
1305 (set-keymap-parent keymap company-search-map)
1307 "Keymap used for incrementally searching the completion candidates.")
1309 (defun company-filter-candidates ()
1310 "Start filtering the completion candidates incrementally.
1311 This works the same way as `company-search-candidates' immediately
1312 followed by `company-search-kill-others' after each input."
1314 (company-search-mode 1)
1315 (company-enable-overriding-keymap company-filter-map))
1317 ;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;
1319 (defun company-select-next ()
1320 "Select the next candidate in the list."
1322 (when (company-manual-begin)
1323 (company-set-selection (1+ company-selection))))
1325 (defun company-select-previous ()
1326 "Select the previous candidate in the list."
1328 (when (company-manual-begin)
1329 (company-set-selection (1- company-selection))))
1331 (defun company-select-mouse (event)
1332 "Select the candidate picked by the mouse."
1334 (when (nth 4 (event-start event))
1335 (company-set-selection (- (cdr (posn-actual-col-row (event-start event)))
1340 (defun company-complete-mouse (event)
1341 "Complete the candidate picked by the mouse."
1343 (when (company-select-mouse event)
1344 (company-complete-selection)))
1346 (defun company-complete-selection ()
1347 "Complete the selected candidate."
1349 (when (company-manual-begin)
1350 (company-finish (nth company-selection company-candidates))))
1352 (defun company-complete-common ()
1353 "Complete the common part of all candidates."
1355 (when (company-manual-begin)
1356 (if (and (not (cdr company-candidates))
1357 (equal company-common (car company-candidates)))
1358 (company-complete-selection)
1359 (insert (company-strip-prefix company-common)))))
1361 (defun company-complete ()
1362 "Complete the common part of all candidates or the current selection.
1363 The first time this is called, the common part is completed, the second time, or
1364 when the selection has been changed, the selected candidate is completed."
1366 (when (company-manual-begin)
1367 (if (or company-selection-changed
1368 (eq last-command 'company-complete-common))
1369 (call-interactively 'company-complete-selection)
1370 (call-interactively 'company-complete-common)
1371 (setq this-command 'company-complete-common))))
1373 (defun company-complete-number (n)
1374 "Complete the Nth candidate.
1375 To show the number next to the candidates in some back-ends, enable
1376 `company-show-numbers'."
1377 (when (company-manual-begin)
1378 (and (< n 1) (> n company-candidates-length)
1379 (error "No candidate number %d" n))
1381 (company-finish (nth n company-candidates))))
1383 ;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;
1385 (defconst company-space-strings-limit 100)
1387 (defconst company-space-strings
1389 (dotimes (i company-space-strings-limit)
1390 (push (make-string (- company-space-strings-limit 1 i) ?\ ) lst))
1391 (apply 'vector lst)))
1393 (defsubst company-space-string (len)
1394 (if (< len company-space-strings-limit)
1395 (aref company-space-strings len)
1396 (make-string len ?\ )))
1398 (defsubst company-safe-substring (str from &optional to)
1399 (let ((len (length str)))
1402 (if (and to (> to len))
1403 (concat (substring str from)
1404 (company-space-string (- to len)))
1405 (substring str from to)))))
1407 ;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;
1409 (defvar company-last-metadata nil)
1410 (make-variable-buffer-local 'company-last-metadata)
1412 (defun company-fetch-metadata ()
1413 (let ((selected (nth company-selection company-candidates)))
1414 (unless (equal selected (car company-last-metadata))
1415 (setq company-last-metadata
1416 (cons selected (company-call-backend 'meta selected))))
1417 (cdr company-last-metadata)))
1419 (defun company-doc-buffer (&optional string)
1420 (with-current-buffer (get-buffer-create "*Company meta-data*")
1424 (defvar company--electric-commands
1425 '(scroll-other-window scroll-other-window-down)
1426 "List of Commands that won't break out of electric commands.")
1428 (defmacro company--electric-do (&rest body)
1429 (declare (indent 0) (debug t))
1430 `(when (company-manual-begin)
1431 (save-window-excursion
1432 (let ((height (window-height))
1433 (row (company--row))
1436 (and (< (window-height) height)
1437 (< (- (window-height) row 2) company-tooltip-limit)
1438 (recenter (- (window-height) row 2)))
1439 (while (memq (setq cmd (key-binding (vector (list (read-event)))))
1440 company--electric-commands)
1441 (call-interactively cmd))
1442 (when last-input-event
1443 (clear-this-command-keys t)
1444 (setq unread-command-events (list last-input-event)))))))
1446 (defun company-show-doc-buffer ()
1447 "Temporarily show a buffer with the complete documentation for the selection."
1449 (company--electric-do
1450 (let ((selected (nth company-selection company-candidates)))
1451 (display-buffer (or (company-call-backend 'doc-buffer selected)
1452 (error "No documentation available")) t))))
1453 (put 'company-show-doc-buffer 'company-keep t)
1455 (defun company-show-location ()
1456 "Temporarily display a buffer showing the selected candidate in context."
1458 (company--electric-do
1459 (let* ((selected (nth company-selection company-candidates))
1460 (location (company-call-backend 'location selected))
1461 (pos (or (cdr location) (error "No location available")))
1462 (buffer (or (and (bufferp (car location)) (car location))
1463 (find-file-noselect (car location) t))))
1464 (with-selected-window (display-buffer buffer t)
1465 (if (bufferp (car location))
1468 (set-window-start nil (point))))))
1469 (put 'company-show-location 'company-keep t)
1471 ;;; package functions ;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;
1473 (defvar company-callback nil)
1474 (make-variable-buffer-local 'company-callback)
1476 (defvar company-begin-with-marker nil)
1477 (make-variable-buffer-local 'company-begin-with-marker)
1479 (defun company-remove-callback (&optional ignored)
1480 (remove-hook 'company-completion-finished-hook company-callback t)
1481 (remove-hook 'company-completion-cancelled-hook 'company-remove-callback t)
1482 (remove-hook 'company-completion-finished-hook 'company-remove-callback t)
1483 (when company-begin-with-marker
1484 (set-marker company-begin-with-marker nil)))
1486 (defun company-begin-backend (backend &optional callback)
1487 "Start a completion at point using BACKEND."
1488 (interactive (let ((val (completing-read "Company back-end: "
1490 'functionp nil "company-")))
1492 (list (intern val)))))
1493 (when (setq company-callback callback)
1494 (add-hook 'company-completion-finished-hook company-callback nil t))
1495 (add-hook 'company-completion-cancelled-hook 'company-remove-callback nil t)
1496 (add-hook 'company-completion-finished-hook 'company-remove-callback nil t)
1497 (setq company-backend backend)
1498 ;; Return non-nil if active.
1499 (or (company-manual-begin)
1500 (error "Cannot complete at point")))
1502 (defun company-begin-with (candidates
1503 &optional prefix-length require-match callback)
1504 "Start a completion at point.
1505 CANDIDATES is the list of candidates to use and PREFIX-LENGTH is the length of
1506 the prefix that already is in the buffer before point. It defaults to 0.
1508 CALLBACK is a function called with the selected result if the user successfully
1509 completes the input.
1512 \(company-begin-with '\(\"foo\" \"foobar\" \"foobarbaz\"\)\)"
1513 (setq company-begin-with-marker (copy-marker (point) t))
1514 (company-begin-backend
1515 `(lambda (command &optional arg &rest ignored)
1517 ((eq command 'prefix)
1518 (when (equal (point) (marker-position company-begin-with-marker))
1519 (buffer-substring ,(- (point) (or prefix-length 0)) (point))))
1520 ((eq command 'candidates)
1521 (all-completions arg ',candidates))
1522 ((eq command 'require-match)
1526 ;;; pseudo-tooltip ;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;
1528 (defvar company-pseudo-tooltip-overlay nil)
1529 (make-variable-buffer-local 'company-pseudo-tooltip-overlay)
1531 (defvar company-tooltip-offset 0)
1532 (make-variable-buffer-local 'company-tooltip-offset)
1534 (defun company-pseudo-tooltip-update-offset (selection num-lines limit)
1537 (setq company-tooltip-offset
1538 (max (min selection company-tooltip-offset)
1539 (- selection -1 limit)))
1541 (when (<= company-tooltip-offset 1)
1543 (setq company-tooltip-offset 0))
1545 (when (>= company-tooltip-offset (- num-lines limit 1))
1547 (when (= selection (1- num-lines))
1548 (decf company-tooltip-offset)
1549 (when (<= company-tooltip-offset 1)
1550 (setq company-tooltip-offset 0)
1557 (defsubst company-round-tab (arg)
1558 (* (/ (+ arg tab-width) tab-width) tab-width))
1560 (defun company-untabify (str)
1561 (let* ((pieces (split-string str "\t"))
1564 (setcar copy (company-safe-substring
1565 (car copy) 0 (company-round-tab (string-width (car copy)))))
1567 (apply 'concat pieces)))
1569 (defun company-fill-propertize (line width selected)
1570 (setq line (company-safe-substring line 0 width))
1571 (add-text-properties 0 width '(face company-tooltip
1572 mouse-face company-tooltip-mouse)
1574 (add-text-properties 0 (length company-common)
1575 '(face company-tooltip-common
1576 mouse-face company-tooltip-mouse)
1579 (if (and company-search-string
1580 (string-match (regexp-quote company-search-string) line
1581 (length company-prefix)))
1583 (add-text-properties (match-beginning 0) (match-end 0)
1584 '(face company-tooltip-selection)
1586 (when (< (match-beginning 0) (length company-common))
1587 (add-text-properties (match-beginning 0) (length company-common)
1588 '(face company-tooltip-common-selection)
1590 (add-text-properties 0 width '(face company-tooltip-selection
1591 mouse-face company-tooltip-selection)
1593 (add-text-properties 0 (length company-common)
1594 '(face company-tooltip-common-selection
1595 mouse-face company-tooltip-selection)
1601 (defun company-buffer-lines (beg end)
1603 (let ((row (company--row))
1605 (while (and (equal (move-to-window-line (incf row)) row)
1607 (push (buffer-substring beg (min end (1- (point)))) lines)
1609 (unless (eq beg end)
1610 (push (buffer-substring beg end) lines))
1613 (defsubst company-modify-line (old new offset)
1614 (concat (company-safe-substring old 0 offset)
1616 (company-safe-substring old (+ offset (length new)))))
1618 (defsubst company--length-limit (lst limit)
1619 (if (nthcdr limit lst)
1623 (defun company--replacement-string (lines old column nl &optional align-top)
1625 (let ((width (length (car lines))))
1626 (when (> width (- (window-width) column))
1627 (setq column (max 0 (- (window-width) width)))))
1631 ;; untouched lines first
1632 (dotimes (i (- (length old) (length lines)))
1633 (push (pop old) new)))
1634 ;; length into old lines.
1636 (push (company-modify-line (pop old) (pop lines) column) new))
1637 ;; Append whole new lines.
1639 (push (concat (company-space-string column) (pop lines)) new))
1640 (concat (when nl "\n")
1641 (mapconcat 'identity (nreverse new) "\n")
1644 (defun company--create-lines (selection limit)
1646 (let ((len company-candidates-length)
1655 ;; Scroll to offset.
1656 (setq limit (company-pseudo-tooltip-update-offset selection len limit))
1658 (when (> company-tooltip-offset 0)
1659 (setq previous (format "...(%d)" company-tooltip-offset)))
1661 (setq remainder (- len limit company-tooltip-offset)
1662 remainder (when (> remainder 0)
1663 (setq remainder (format "...(%d)" remainder))))
1665 (decf selection company-tooltip-offset)
1666 (setq width (max (length previous) (length remainder))
1667 lines (nthcdr company-tooltip-offset company-candidates)
1672 (setq width (max (length (pop lines-copy)) width)))
1673 (setq width (min width (window-width)))
1675 (setq lines-copy lines)
1677 ;; number can make tooltip too long
1678 (when company-show-numbers
1679 (setq numbered company-tooltip-offset))
1682 (push (propertize (company-safe-substring previous 0 width)
1683 'face 'company-tooltip)
1687 (push (company-fill-propertize
1688 (if (>= numbered 10)
1689 (company-reformat (pop lines))
1692 (company-safe-substring (company-reformat (pop lines))
1695 width (equal i selection))
1699 (push (propertize (company-safe-substring remainder 0 width)
1700 'face 'company-tooltip)
1703 (setq lines (nreverse new))))
1707 (defsubst company--window-inner-height ()
1708 (let ((edges (window-inside-edges (selected-window))))
1709 (- (nth 3 edges) (nth 1 edges))))
1711 (defsubst company--pseudo-tooltip-height ()
1712 "Calculate the appropriate tooltip height.
1713 Returns a negative number if the tooltip should be displayed above point."
1714 (let* ((lines (count-lines (window-start) (point-at-bol)))
1715 (below (- (company--window-inner-height) 1 lines)))
1716 (if (and (< below (min company-tooltip-minimum company-candidates-length))
1718 (- (max 3 (min company-tooltip-limit lines)))
1719 (max 3 (min company-tooltip-limit below)))))
1721 (defun company-pseudo-tooltip-show (row column selection)
1722 (company-pseudo-tooltip-hide)
1727 (let* ((height (company--pseudo-tooltip-height))
1731 (setq row (+ row height -1)
1734 (let* ((nl (< (move-to-window-line row) row))
1736 (end (save-excursion
1737 (move-to-window-line (+ row (abs height)))
1739 (ov (make-overlay beg end))
1740 (args (list (mapcar 'company-untabify
1741 (company-buffer-lines beg end))
1744 (setq company-pseudo-tooltip-overlay ov)
1745 (overlay-put ov 'company-replacement-args args)
1746 (overlay-put ov 'company-before
1747 (apply 'company--replacement-string
1748 (company--create-lines selection (abs height))
1751 (overlay-put ov 'company-column column)
1752 (overlay-put ov 'company-height (abs height))
1753 (overlay-put ov 'window (selected-window))))))
1755 (defun company-pseudo-tooltip-show-at-point (pos)
1756 (let ((col-row (company--col-row pos)))
1758 (company-pseudo-tooltip-show (1+ (cdr col-row)) (car col-row)
1759 company-selection))))
1761 (defun company-pseudo-tooltip-edit (lines selection)
1762 (let ((column (overlay-get company-pseudo-tooltip-overlay 'company-column))
1763 (height (overlay-get company-pseudo-tooltip-overlay 'company-height)))
1764 (overlay-put company-pseudo-tooltip-overlay 'company-before
1765 (apply 'company--replacement-string
1766 (company--create-lines selection height)
1767 (overlay-get company-pseudo-tooltip-overlay
1768 'company-replacement-args)))))
1770 (defun company-pseudo-tooltip-hide ()
1771 (when company-pseudo-tooltip-overlay
1772 (delete-overlay company-pseudo-tooltip-overlay)
1773 (setq company-pseudo-tooltip-overlay nil)))
1775 (defun company-pseudo-tooltip-hide-temporarily ()
1776 (when (overlayp company-pseudo-tooltip-overlay)
1777 (overlay-put company-pseudo-tooltip-overlay 'invisible nil)
1778 (overlay-put company-pseudo-tooltip-overlay 'before-string nil)))
1780 (defun company-pseudo-tooltip-unhide ()
1781 (when company-pseudo-tooltip-overlay
1782 (overlay-put company-pseudo-tooltip-overlay 'invisible t)
1783 (overlay-put company-pseudo-tooltip-overlay 'before-string
1784 (overlay-get company-pseudo-tooltip-overlay 'company-before))
1785 (overlay-put company-pseudo-tooltip-overlay 'window (selected-window))))
1787 (defun company-pseudo-tooltip-frontend (command)
1788 "A `company-mode' front-end similar to a tool-tip but based on overlays."
1790 ('pre-command (company-pseudo-tooltip-hide-temporarily))
1792 (let ((old-height (if (overlayp company-pseudo-tooltip-overlay)
1793 (overlay-get company-pseudo-tooltip-overlay
1796 (new-height (company--pseudo-tooltip-height)))
1797 (unless (and (>= (* old-height new-height) 0)
1798 (>= (abs old-height) (abs new-height)))
1800 (company-pseudo-tooltip-show-at-point (- (point)
1801 (length company-prefix)))))
1802 (company-pseudo-tooltip-unhide))
1803 ('hide (company-pseudo-tooltip-hide)
1804 (setq company-tooltip-offset 0))
1805 ('update (when (overlayp company-pseudo-tooltip-overlay)
1806 (company-pseudo-tooltip-edit company-candidates
1807 company-selection)))))
1809 (defun company-pseudo-tooltip-unless-just-one-frontend (command)
1810 "`company-pseudo-tooltip-frontend', but not shown for single candidates."
1811 (unless (and (eq command 'post-command)
1812 (not (cdr company-candidates)))
1813 (company-pseudo-tooltip-frontend command)))
1815 ;;; overlay ;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;
1817 (defvar company-preview-overlay nil)
1818 (make-variable-buffer-local 'company-preview-overlay)
1820 (defun company-preview-show-at-point (pos)
1821 (company-preview-hide)
1823 (setq company-preview-overlay (make-overlay pos pos))
1825 (let ((completion(nth company-selection company-candidates)))
1826 (setq completion (propertize completion 'face 'company-preview))
1827 (add-text-properties 0 (length company-common)
1828 '(face company-preview-common) completion)
1830 ;; Add search string
1831 (and company-search-string
1832 (string-match (regexp-quote company-search-string) completion)
1833 (add-text-properties (match-beginning 0)
1835 '(face company-preview-search)
1838 (setq completion (company-strip-prefix completion))
1840 (and (equal pos (point))
1841 (not (equal completion ""))
1842 (add-text-properties 0 1 '(cursor t) completion))
1844 (overlay-put company-preview-overlay 'after-string completion)
1845 (overlay-put company-preview-overlay 'window (selected-window))))
1847 (defun company-preview-hide ()
1848 (when company-preview-overlay
1849 (delete-overlay company-preview-overlay)
1850 (setq company-preview-overlay nil)))
1852 (defun company-preview-frontend (command)
1853 "A `company-mode' front-end showing the selection as if it had been inserted."
1855 ('pre-command (company-preview-hide))
1856 ('post-command (company-preview-show-at-point (point)))
1857 ('hide (company-preview-hide))))
1859 (defun company-preview-if-just-one-frontend (command)
1860 "`company-preview-frontend', but only shown for single candidates."
1861 (unless (and (eq command 'post-command)
1862 (cdr company-candidates))
1863 (company-preview-frontend command)))
1865 ;;; echo ;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;
1867 (defvar company-echo-last-msg nil)
1868 (make-variable-buffer-local 'company-echo-last-msg)
1870 (defvar company-echo-timer nil)
1872 (defvar company-echo-delay .01)
1874 (defun company-echo-show (&optional getter)
1876 (setq company-echo-last-msg (funcall getter)))
1877 (let ((message-log-max nil))
1878 (if company-echo-last-msg
1879 (message "%s" company-echo-last-msg)
1882 (defsubst company-echo-show-soon (&optional getter)
1883 (when company-echo-timer
1884 (cancel-timer company-echo-timer))
1885 (setq company-echo-timer (run-with-timer company-echo-delay nil
1886 'company-echo-show getter)))
1888 (defun company-echo-format ()
1890 (let ((limit (window-width (minibuffer-window)))
1892 ;; Roll to selection.
1893 (candidates (nthcdr company-selection company-candidates))
1894 (i (if company-show-numbers company-selection 99999))
1898 (setq comp (company-reformat (pop candidates))
1899 len (+ len 1 (length comp)))
1903 (setq comp (propertize (format "%d: %s" i comp)
1904 'face 'company-echo))
1907 (add-text-properties 3 (+ 3 (length company-common))
1908 '(face company-echo-common) comp))
1909 (setq comp (propertize comp 'face 'company-echo))
1910 (add-text-properties 0 (length company-common)
1911 '(face company-echo-common) comp))
1913 (setq candidates nil)
1916 (mapconcat 'identity (nreverse msg) " ")))
1918 (defun company-echo-strip-common-format ()
1920 (let ((limit (window-width (minibuffer-window)))
1921 (len (+ (length company-prefix) 2))
1922 ;; Roll to selection.
1923 (candidates (nthcdr company-selection company-candidates))
1924 (i (if company-show-numbers company-selection 99999))
1928 (setq comp (company-strip-prefix (pop candidates))
1929 len (+ len 2 (length comp)))
1932 (setq comp (format "%s (%d)" comp i))
1936 (setq candidates nil)
1937 (push (propertize comp 'face 'company-echo) msg)))
1939 (concat (propertize company-prefix 'face 'company-echo-common) "{"
1940 (mapconcat 'identity (nreverse msg) ", ")
1943 (defun company-echo-hide ()
1944 (when company-echo-timer
1945 (cancel-timer company-echo-timer))
1946 (unless (equal company-echo-last-msg "")
1947 (setq company-echo-last-msg "")
1948 (company-echo-show)))
1950 (defun company-echo-frontend (command)
1951 "A `company-mode' front-end showing the candidates in the echo area."
1953 ('pre-command (company-echo-show-soon))
1954 ('post-command (company-echo-show-soon 'company-echo-format))
1955 ('hide (company-echo-hide))))
1957 (defun company-echo-strip-common-frontend (command)
1958 "A `company-mode' front-end showing the candidates in the echo area."
1960 ('pre-command (company-echo-show-soon))
1961 ('post-command (company-echo-show-soon 'company-echo-strip-common-format))
1962 ('hide (company-echo-hide))))
1964 (defun company-echo-metadata-frontend (command)
1965 "A `company-mode' front-end showing the documentation in the echo area."
1967 ('pre-command (company-echo-show-soon))
1968 ('post-command (company-echo-show-soon 'company-fetch-metadata))
1969 ('hide (company-echo-hide))))
1972 ;;; company.el ends here