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 ;; `company-ropemacs' now provides location and docs. (Fernando H. Silva)
69 ;; Added `company-with-candidate-inserted' macro.
70 ;; Added `company-clang' back-end.
71 ;; The semantic back-end now shows meta information for local symbols.
72 ;; Added compatibility for CEDET in Emacs 23.2.
75 ;; Added `company-other-backend'.
76 ;; Idle completion no longer interrupts multi-key command input.
77 ;; Added `company-ropemacs' and `company-pysmell' back-ends.
80 ;; In C modes . and -> now count towards `company-minimum-prefix-length'.
81 ;; Reverted default front-end back to `company-preview-if-just-one-frontend'.
82 ;; The pseudo tooltip will no longer be clipped at the right window edge.
83 ;; Added `company-tooltip-minimum'.
84 ;; Windows compatibility fixes.
87 ;; Added `global-company-mode'.
88 ;; Performance enhancements.
89 ;; Added `company-eclim' back-end.
90 ;; Added safer workaround for Emacs `posn-col-row' bug.
93 ;; Automatic completion is now aborted if the prefix gets too short.
94 ;; Added option `company-dabbrev-time-limit'.
95 ;; `company-backends' now supports merging back-ends.
96 ;; Added back-end `company-dabbrev-code' for generic code.
97 ;; Fixed `company-begin-with'.
100 ;; Added 'stop prefix to prevent dabbrev from completing inside of symbols.
101 ;; Fixed issues with tabbar-mode and line-spacing.
102 ;; Performance enhancements.
105 ;; Added `company-begin-commands' option.
106 ;; Added abbrev, tempo and Xcode back-ends.
107 ;; Back-ends are now interactive. You can start them with M-x backend-name.
108 ;; Added `company-begin-with' for starting company from elisp-code.
110 ;; Added `company-require-match' and `company-auto-complete' options.
112 ;; 2009-04-05 (0.2.1)
113 ;; Improved Emacs Lisp back-end behavior for local variables.
114 ;; Added `company-elisp-detect-function-context' option.
115 ;; The mouse can now be used for selection.
118 ;; Added `company-show-location'.
119 ;; Added etags back-end.
120 ;; Added work-around for end-of-buffer bug.
121 ;; Added `company-filter-candidates'.
122 ;; More local Lisp variables are now included in the candidates.
124 ;; 2009-03-21 (0.1.5)
125 ;; Fixed elisp documentation buffer always showing the same doc.
126 ;; Added `company-echo-strip-common-frontend'.
127 ;; Added `company-show-numbers' option and M-0 ... M-9 default bindings.
128 ;; Don't hide the echo message if it isn't shown.
135 (eval-when-compile (require 'cl))
137 (add-to-list 'debug-ignored-errors "^.* frontend cannot be used twice$")
138 (add-to-list 'debug-ignored-errors "^Echo area cannot be used twice$")
139 (add-to-list 'debug-ignored-errors "^No \\(document\\|loc\\)ation available$")
140 (add-to-list 'debug-ignored-errors "^Company not ")
141 (add-to-list 'debug-ignored-errors "^No candidate number ")
142 (add-to-list 'debug-ignored-errors "^Cannot complete at point$")
143 (add-to-list 'debug-ignored-errors "^No other back-end$")
145 (defgroup company nil
146 "Extensible inline text completion mechanism"
151 (defface company-tooltip
152 '((t :background "yellow"
153 :foreground "black"))
154 "*Face used for the tool tip."
157 (defface company-tooltip-selection
158 '((default :inherit company-tooltip)
159 (((class color) (min-colors 88)) (:background "orange1"))
160 (t (:background "green")))
161 "*Face used for the selection in the tool tip."
164 (defface company-tooltip-mouse
165 '((default :inherit highlight))
166 "*Face used for the tool tip item under the mouse."
169 (defface company-tooltip-common
170 '((t :inherit company-tooltip
172 "*Face used for the common completion in the tool tip."
175 (defface company-tooltip-common-selection
176 '((t :inherit company-tooltip-selection
178 "*Face used for the selected common completion in the tool tip."
181 (defface company-preview
182 '((t :background "blue4"
183 :foreground "wheat"))
184 "*Face used for the completion preview."
187 (defface company-preview-common
188 '((t :inherit company-preview
190 "*Face used for the common part of the completion preview."
193 (defface company-preview-search
194 '((t :inherit company-preview
195 :background "blue1"))
196 "*Face used for the search string in the completion preview."
199 (defface company-echo nil
200 "*Face used for completions in the echo area."
203 (defface company-echo-common
204 '((((background dark)) (:foreground "firebrick1"))
205 (((background light)) (:background "firebrick4")))
206 "*Face used for the common part of completions in the echo area."
209 (defun company-frontends-set (variable value)
211 (let ((remainder value))
212 (setcdr remainder (delq (car remainder) (cdr remainder))))
213 (and (memq 'company-pseudo-tooltip-unless-just-one-frontend value)
214 (memq 'company-pseudo-tooltip-frontend value)
215 (error "Pseudo tooltip frontend cannot be used twice"))
216 (and (memq 'company-preview-if-just-one-frontend value)
217 (memq 'company-preview-frontend value)
218 (error "Preview frontend cannot be used twice"))
219 (and (memq 'company-echo value)
220 (memq 'company-echo-metadata-frontend value)
221 (error "Echo area cannot be used twice"))
222 ;; preview must come last
223 (dolist (f '(company-preview-if-just-one-frontend company-preview-frontend))
225 (setq value (append (delq f value) (list f)))))
226 (set variable value))
228 (defcustom company-frontends '(company-pseudo-tooltip-unless-just-one-frontend
229 company-preview-if-just-one-frontend
230 company-echo-metadata-frontend)
231 "*The list of active front-ends (visualizations).
232 Each front-end is a function that takes one argument. It is called with
233 one of the following arguments:
235 'show: When the visualization should start.
237 'hide: When the visualization should end.
239 'update: When the data has been updated.
241 'pre-command: Before every command that is executed while the
242 visualization is active.
244 'post-command: After every command that is executed while the
245 visualization is active.
247 The visualized data is stored in `company-prefix', `company-candidates',
248 `company-common', `company-selection', `company-point' and
249 `company-search-string'."
250 :set 'company-frontends-set
252 :type '(repeat (choice (const :tag "echo" company-echo-frontend)
253 (const :tag "echo, strip common"
254 company-echo-strip-common-frontend)
255 (const :tag "show echo meta-data in echo"
256 company-echo-metadata-frontend)
257 (const :tag "pseudo tooltip"
258 company-pseudo-tooltip-frontend)
259 (const :tag "pseudo tooltip, multiple only"
260 company-pseudo-tooltip-unless-just-one-frontend)
261 (const :tag "preview" company-preview-frontend)
262 (const :tag "preview, unique only"
263 company-preview-if-just-one-frontend)
264 (function :tag "custom function" nil))))
266 (defcustom company-tooltip-limit 10
267 "*The maximum number of candidates in the tool tip"
271 (defcustom company-tooltip-minimum 6
272 "*The minimum height of the tool tip.
273 If this many lines are not available, prefer to display the tooltip above."
277 (defvar company-safe-backends
278 '((company-abbrev . "Abbrev")
279 (company-clang . "clang")
280 (company-css . "CSS")
281 (company-dabbrev . "dabbrev for plain text")
282 (company-dabbrev-code . "dabbrev for code")
283 (company-eclim . "eclim (an Eclipse interace)")
284 (company-elisp . "Emacs Lisp")
285 (company-etags . "etags")
286 (company-files . "Files")
287 (company-gtags . "GNU Global")
288 (company-ispell . "ispell")
289 (company-keywords . "Programming language keywords")
290 (company-nxml . "nxml")
291 (company-oddmuse . "Oddmuse")
292 (company-pysmell . "PySmell")
293 (company-ropemacs . "ropemacs")
294 (company-semantic . "CEDET Semantic")
295 (company-tempo . "Tempo templates")
296 (company-xcode . "Xcode")))
297 (put 'company-safe-backends 'risky-local-variable t)
299 (defun company-safe-backends-p (backends)
300 (and (consp backends)
301 (not (dolist (backend backends)
302 (unless (if (consp backend)
303 (company-safe-backends-p backend)
304 (assq backend company-safe-backends))
307 (defcustom company-backends '(company-elisp company-nxml company-css
308 company-eclim company-semantic company-clang
309 company-xcode company-ropemacs
310 (company-gtags company-etags company-dabbrev-code
311 company-pysmell company-keywords)
312 company-oddmuse company-files company-dabbrev)
313 "*The list of active back-ends (completion engines).
314 Each list elements can itself be a list of back-ends. In that case their
315 completions are merged. Otherwise only the first matching back-end returns
318 `company-begin-backend' can be used to start a specific back-end,
319 `company-other-backend' will skip to the next matching back-end in the list.
321 Each back-end is a function that takes a variable number of arguments.
322 The first argument is the command requested from the back-end. It is one
325 'prefix: The back-end should return the text to be completed. It must be
326 text immediately before `point'. Returning nil passes control to the next
327 back-end. The function should return 'stop if it should complete but cannot
328 \(e.g. if it is in the middle of a string\). If the returned value is only
329 part of the prefix (e.g. the part after \"->\" in C), the back-end may return a
330 cons of prefix and prefix length, which is then used in the
331 `company-minimum-prefix-length' test.
333 'candidates: The second argument is the prefix to be completed. The
334 return value should be a list of candidates that start with the prefix.
338 'sorted: The back-end may return t here to indicate that the candidates
339 are sorted and will not need to be sorted again.
341 'duplicates: If non-nil, company will take care of removing duplicates
344 'no-cache: Usually company doesn't ask for candidates again as completion
345 progresses, unless the back-end returns t for this command. The second
346 argument is the latest prefix.
348 'meta: The second argument is a completion candidate. The back-end should
349 return a (short) documentation string for it.
351 'doc-buffer: The second argument is a completion candidate. The back-end should
352 create a buffer (preferably with `company-doc-buffer'), fill it with
353 documentation and return it.
355 'location: The second argument is a completion candidate. The back-end can
356 return the cons of buffer and buffer location, or of file and line
357 number where the completion candidate was defined.
359 'require-match: If this value is t, the user is not allowed to enter anything
360 not offering as a candidate. Use with care! The default value nil gives the
361 user that choice with `company-require-match'. Return value 'never overrides
362 that option the other way around.
364 The back-end should return nil for all commands it does not support or
365 does not know about. It should also be callable interactively and use
366 `company-begin-backend' to start itself in that case."
371 ,@(mapcar (lambda (b) `(const :tag ,(cdr b) ,(car b)))
372 company-safe-backends)
373 (symbol :tag "User defined")
374 (repeat :tag "Merged Back-ends"
375 (choice :tag "Back-end"
376 ,@(mapcar (lambda (b)
377 `(const :tag ,(cdr b) ,(car b)))
378 company-safe-backends)
379 (symbol :tag "User defined"))))))
381 (put 'company-backends 'safe-local-variable 'company-safe-backends-p)
383 (defcustom company-completion-started-hook nil
384 "*Hook run when company starts completing.
385 The hook is called with one argument that is non-nil if the completion was
390 (defcustom company-completion-cancelled-hook nil
391 "*Hook run when company cancels completing.
392 The hook is called with one argument that is non-nil if the completion was
397 (defcustom company-completion-finished-hook nil
398 "*Hook run when company successfully completes.
399 The hook is called with the selected candidate as an argument."
403 (defcustom company-minimum-prefix-length 3
404 "*The minimum prefix length for automatic completion."
406 :type '(integer :tag "prefix length"))
408 (defcustom company-require-match 'company-explicit-action-p
409 "*If enabled, disallow non-matching input.
410 This can be a function do determine if a match is required.
412 This can be overridden by the back-end, if it returns t or 'never to
413 'require-match. `company-auto-complete' also takes precedence over this."
415 :type '(choice (const :tag "Off" nil)
416 (function :tag "Predicate function")
417 (const :tag "On, if user interaction took place"
418 'company-explicit-action-p)
419 (const :tag "On" t)))
421 (defcustom company-auto-complete 'company-explicit-action-p
422 "Determines when to auto-complete.
423 If this is enabled, all characters from `company-auto-complete-chars' complete
424 the selected completion. This can also be a function."
426 :type '(choice (const :tag "Off" nil)
427 (function :tag "Predicate function")
428 (const :tag "On, if user interaction took place"
429 'company-explicit-action-p)
430 (const :tag "On" t)))
432 (defcustom company-auto-complete-chars '(?\ ?\( ?\) ?. ?\" ?$ ?\' ?< ?| ?!)
433 "Determines which characters trigger an automatic completion.
434 See `company-auto-complete'. If this is a string, each string character causes
435 completion. If it is a list of syntax description characters (see
436 `modify-syntax-entry'), all characters with that syntax auto-complete.
438 This can also be a function, which is called with the new input and should
439 return non-nil if company should auto-complete.
441 A character that is part of a valid candidate never starts auto-completion."
443 :type '(choice (string :tag "Characters")
445 (const :tag "Whitespace" ?\ )
446 (const :tag "Symbol" ?_)
447 (const :tag "Opening parentheses" ?\()
448 (const :tag "Closing parentheses" ?\))
449 (const :tag "Word constituent" ?w)
450 (const :tag "Punctuation." ?.)
451 (const :tag "String quote." ?\")
452 (const :tag "Paired delimiter." ?$)
453 (const :tag "Expression quote or prefix operator." ?\')
454 (const :tag "Comment starter." ?<)
455 (const :tag "Comment ender." ?>)
456 (const :tag "Character-quote." ?/)
457 (const :tag "Generic string fence." ?|)
458 (const :tag "Generic comment fence." ?!))
459 (function :tag "Predicate function")))
461 (defcustom company-idle-delay .7
462 "*The idle delay in seconds until automatic completions starts.
463 A value of nil means never complete automatically, t means complete
464 immediately when a prefix of `company-minimum-prefix-length' is reached."
466 :type '(choice (const :tag "never (nil)" nil)
467 (const :tag "immediate (t)" t)
468 (number :tag "seconds")))
470 (defcustom company-begin-commands t
471 "*A list of commands following which company will start completing.
472 If this is t, it will complete after any command. See `company-idle-delay'.
474 Alternatively any command with a non-nil 'company-begin property is treated as
475 if it was on this list."
477 :type '(choice (const :tag "Any command" t)
478 (const :tag "Self insert command" '(self-insert-command))
479 (repeat :tag "Commands" function)))
481 (defcustom company-show-numbers nil
482 "*If enabled, show quick-access numbers for the first ten candidates."
484 :type '(choice (const :tag "off" nil)
485 (const :tag "on" t)))
487 (defvar company-end-of-buffer-workaround t
488 "*Work around a visualization bug when completing at the end of the buffer.
489 The work-around consists of adding a newline.")
491 ;;; mode ;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;
493 (defvar company-mode-map (make-sparse-keymap)
494 "Keymap used by `company-mode'.")
496 (defvar company-active-map
497 (let ((keymap (make-sparse-keymap)))
498 (define-key keymap "\e\e\e" 'company-abort)
499 (define-key keymap "\C-g" 'company-abort)
500 (define-key keymap (kbd "M-n") 'company-select-next)
501 (define-key keymap (kbd "M-p") 'company-select-previous)
502 (define-key keymap (kbd "<down>") 'company-select-next)
503 (define-key keymap (kbd "<up>") 'company-select-previous)
504 (define-key keymap [down-mouse-1] 'ignore)
505 (define-key keymap [down-mouse-3] 'ignore)
506 (define-key keymap [mouse-1] 'company-complete-mouse)
507 (define-key keymap [mouse-3] 'company-select-mouse)
508 (define-key keymap [up-mouse-1] 'ignore)
509 (define-key keymap [up-mouse-3] 'ignore)
510 (define-key keymap "\C-m" 'company-complete-selection)
511 (define-key keymap "\t" 'company-complete-common)
512 (define-key keymap (kbd "<f1>") 'company-show-doc-buffer)
513 (define-key keymap "\C-w" 'company-show-location)
514 (define-key keymap "\C-s" 'company-search-candidates)
515 (define-key keymap "\C-\M-s" 'company-filter-candidates)
517 (define-key keymap (vector (+ (aref (kbd "M-0") 0) i))
518 `(lambda () (interactive) (company-complete-number ,i))))
521 "Keymap that is enabled during an active completion.")
523 (defvar company--disabled-backends nil)
525 (defun company-init-backend (backend)
526 (and (symbolp backend)
527 (not (fboundp backend))
528 (ignore-errors (require backend nil t)))
530 (if (or (symbolp backend)
534 (funcall backend 'init)
535 (put backend 'company-init t))
537 (put backend 'company-init 'failed)
538 (unless (memq backend company--disabled-backends)
539 (message "Company back-end '%s' could not be initialized:\n%s"
540 backend (error-message-string err)))
541 (push backend company--disabled-backends)
543 (mapc 'company-init-backend backend)))
545 (defvar company-default-lighter " company")
547 (defvar company-lighter company-default-lighter)
548 (make-variable-buffer-local 'company-lighter)
551 (define-minor-mode company-mode
552 "\"complete anything\"; in in-buffer completion framework.
553 Completion starts automatically, depending on the values
554 `company-idle-delay' and `company-minimum-prefix-length'.
556 Completion can be controlled with the commands:
557 `company-complete-common', `company-complete-selection', `company-complete',
558 `company-select-next', `company-select-previous'. If these commands are
559 called before `company-idle-delay', completion will also start.
561 Completions can be searched with `company-search-candidates' or
562 `company-filter-candidates'. These can be used while completion is
565 The completion data is retrieved using `company-backends' and displayed using
566 `company-frontends'. If you want to start a specific back-end, call it
567 interactively or use `company-begin-backend'.
569 regular keymap (`company-mode-map'):
572 keymap during active completions (`company-active-map'):
574 \\{company-active-map}"
575 nil company-lighter company-mode-map
578 (add-hook 'pre-command-hook 'company-pre-command nil t)
579 (add-hook 'post-command-hook 'company-post-command nil t)
580 (mapc 'company-init-backend company-backends))
581 (remove-hook 'pre-command-hook 'company-pre-command t)
582 (remove-hook 'post-command-hook 'company-post-command t)
584 (kill-local-variable 'company-point)))
586 (define-globalized-minor-mode global-company-mode company-mode
587 (lambda () (company-mode 1)))
589 (defsubst company-assert-enabled ()
591 (company-uninstall-map)
592 (error "Company not enabled")))
594 ;;; keymaps ;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;
596 (defvar company-overriding-keymap-bound nil)
597 (make-variable-buffer-local 'company-overriding-keymap-bound)
599 (defvar company-old-keymap nil)
600 (make-variable-buffer-local 'company-old-keymap)
602 (defvar company-my-keymap nil)
603 (make-variable-buffer-local 'company-my-keymap)
605 (defsubst company-enable-overriding-keymap (keymap)
606 (setq company-my-keymap keymap)
607 (when company-overriding-keymap-bound
608 (company-uninstall-map)))
610 (defun company-install-map ()
611 (unless (or company-overriding-keymap-bound
612 (null company-my-keymap))
613 (setq company-old-keymap overriding-terminal-local-map
614 overriding-terminal-local-map company-my-keymap
615 company-overriding-keymap-bound t)))
617 (defun company-uninstall-map ()
618 (when (eq overriding-terminal-local-map company-my-keymap)
619 (setq overriding-terminal-local-map company-old-keymap
620 company-overriding-keymap-bound nil)))
623 ;; Emacs calculates the active keymaps before reading the event. That means we
624 ;; cannot change the keymap from a timer. So we send a bogus command.
625 (defun company-ignore ()
627 (setq this-command last-command))
629 (global-set-key '[31415926] 'company-ignore)
631 (defun company-input-noop ()
632 (push 31415926 unread-command-events))
635 ;; posn-col-row is incorrect in older Emacsen when line-spacing is set
636 (defun company--col-row (&optional pos)
637 (let ((posn (posn-at-point pos)))
638 (cons (car (posn-col-row posn)) (cdr (posn-actual-col-row posn)))))
640 (defsubst company--column (&optional pos)
641 (car (posn-col-row (posn-at-point pos))))
643 (defsubst company--row (&optional pos)
644 (cdr (posn-actual-col-row (posn-at-point pos))))
646 ;;; backends ;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;
648 (defun company-grab (regexp &optional expression limit)
649 (when (looking-back regexp limit)
650 (or (match-string-no-properties (or expression 0)) "")))
652 (defun company-grab-line (regexp &optional expression)
653 (company-grab regexp expression (point-at-bol)))
655 (defun company-grab-symbol ()
656 (if (looking-at "\\_>")
657 (buffer-substring (point) (save-excursion (skip-syntax-backward "w_")
659 (unless (and (char-after) (memq (char-syntax (char-after)) '(?w ?_)))
662 (defun company-grab-word ()
663 (if (looking-at "\\>")
664 (buffer-substring (point) (save-excursion (skip-syntax-backward "w")
666 (unless (and (char-after) (eq (char-syntax (char-after)) ?w))
669 (defun company-in-string-or-comment ()
670 (let ((ppss (syntax-ppss)))
671 (or (car (setq ppss (nthcdr 3 ppss)))
672 (car (setq ppss (cdr ppss)))
675 (if (fboundp 'locate-dominating-file)
676 (defalias 'company-locate-dominating-file 'locate-dominating-file)
677 (defun company-locate-dominating-file (file name)
679 (let ((dir (file-name-directory file))
681 (while (not (equal dir prev-dir))
682 (when (file-exists-p (expand-file-name name dir))
685 dir (file-name-directory (directory-file-name dir))))))))
687 (defun company-call-backend (&rest args)
688 (if (functionp company-backend)
689 (apply company-backend args)
690 (apply 'company--multi-backend-adapter company-backend args)))
692 (defun company--multi-backend-adapter (backends command &rest args)
695 (apply 'append (mapcar (lambda (backend) (apply backend command args))
701 (dolist (backend backends)
702 (when (setq value (apply backend command args))
705 ;;; completion mechanism ;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;
707 (defvar company-backend nil)
708 (make-variable-buffer-local 'company-backend)
710 (defvar company-prefix nil)
711 (make-variable-buffer-local 'company-prefix)
713 (defvar company-candidates nil)
714 (make-variable-buffer-local 'company-candidates)
716 (defvar company-candidates-length nil)
717 (make-variable-buffer-local 'company-candidates-length)
719 (defvar company-candidates-cache nil)
720 (make-variable-buffer-local 'company-candidates-cache)
722 (defvar company-candidates-predicate nil)
723 (make-variable-buffer-local 'company-candidates-predicate)
725 (defvar company-common nil)
726 (make-variable-buffer-local 'company-common)
728 (defvar company-selection 0)
729 (make-variable-buffer-local 'company-selection)
731 (defvar company-selection-changed nil)
732 (make-variable-buffer-local 'company-selection-changed)
734 (defvar company--explicit-action nil
735 "Non-nil, if explicit completion took place.")
736 (make-variable-buffer-local 'company--explicit-action)
738 (defvar company--point-max nil)
739 (make-variable-buffer-local 'company--point-max)
741 (defvar company-point nil)
742 (make-variable-buffer-local 'company-point)
744 (defvar company-timer nil)
746 (defvar company-added-newline nil)
747 (make-variable-buffer-local 'company-added-newline)
749 (defsubst company-strip-prefix (str)
750 (substring str (length company-prefix)))
752 (defmacro company-with-candidate-inserted (candidate &rest body)
753 "Evaluate BODY with CANDIDATE temporarily inserted.
754 This is a tool for back-ends that need candidates inserted before they
755 can retrieve meta-data for them."
757 `(let ((inhibit-modification-hooks t)
758 (inhibit-point-motion-hooks t)
759 (modified-p (buffer-modified-p)))
760 (insert (company-strip-prefix ,candidate))
763 (delete-region company-point (point)))))
765 (defun company-explicit-action-p ()
766 "Return whether explicit completion action was taken by the user."
767 (or company--explicit-action
768 company-selection-changed))
770 (defsubst company-reformat (candidate)
771 ;; company-ispell needs this, because the results are always lower-case
772 ;; It's mory efficient to fix it only when they are displayed.
773 (concat company-prefix (substring candidate (length company-prefix))))
775 (defun company--should-complete ()
776 (and (not (or buffer-read-only overriding-terminal-local-map
777 overriding-local-map))
778 ;; Check if in the middle of entering a key combination.
779 (or (equal (this-command-keys-vector) [])
780 (not (keymapp (key-binding (this-command-keys-vector)))))
781 (eq company-idle-delay t)
782 (or (eq t company-begin-commands)
783 (memq this-command company-begin-commands)
784 (and (symbolp this-command) (get this-command 'company-begin)))
785 (not (and transient-mark-mode mark-active))))
787 (defsubst company-call-frontends (command)
788 (dolist (frontend company-frontends)
790 (funcall frontend command)
791 (error (error "Company: Front-end %s error \"%s\" on command %s"
792 frontend (error-message-string err) command)))))
794 (defsubst company-set-selection (selection &optional force-update)
795 (setq selection (max 0 (min (1- company-candidates-length) selection)))
796 (when (or force-update (not (equal selection company-selection)))
797 (setq company-selection selection
798 company-selection-changed t)
799 (company-call-frontends 'update)))
801 (defun company-apply-predicate (candidates predicate)
803 (dolist (c candidates)
804 (when (funcall predicate c)
808 (defun company-update-candidates (candidates)
809 (setq company-candidates-length (length candidates))
810 (if (> company-selection 0)
811 ;; Try to restore the selection
812 (let ((selected (nth company-selection company-candidates)))
813 (setq company-selection 0
814 company-candidates candidates)
816 (while (and candidates (string< (pop candidates) selected))
817 (incf company-selection))
819 ;; Make sure selection isn't out of bounds.
820 (setq company-selection (min (1- company-candidates-length)
821 company-selection)))))
822 (setq company-selection 0
823 company-candidates candidates))
825 (push (cons company-prefix company-candidates) company-candidates-cache)
827 (let ((completion-ignore-case (company-call-backend 'ignore-case)))
828 (setq company-common (try-completion company-prefix company-candidates)))
829 (when (eq company-common t)
830 (setq company-candidates nil)))
832 (defun company-calculate-candidates (prefix)
833 (let ((candidates (cdr (assoc prefix company-candidates-cache))))
835 (when company-candidates-cache
836 (let ((len (length prefix))
837 (completion-ignore-case (company-call-backend 'ignore-case))
839 (dotimes (i (1+ len))
840 (when (setq prev (cdr (assoc (substring prefix 0 (- len i))
841 company-candidates-cache)))
842 (setq candidates (all-completions prefix prev))
844 ;; no cache match, call back-end
846 (setq candidates (company-call-backend 'candidates prefix))
847 (when company-candidates-predicate
849 (company-apply-predicate candidates
850 company-candidates-predicate)))
851 (unless (company-call-backend 'sorted)
852 (setq candidates (sort candidates 'string<)))
853 (when (company-call-backend 'duplicates)
855 (let ((c2 candidates))
857 (setcdr c2 (progn (while (equal (pop c2) (car c2)))
859 (if (or (cdr candidates)
860 (not (equal (car candidates) prefix)))
861 ;; Don't start when already completed and unique.
863 ;; Not the right place? maybe when setting?
864 (and company-candidates t))))
866 (defun company-idle-begin (buf win tick pos)
868 (eq buf (current-buffer))
869 (eq win (selected-window))
870 (eq tick (buffer-chars-modified-tick))
872 (not company-candidates)
873 (not (equal (point) company-point))
874 (let ((company-idle-delay t)
875 (company-begin-commands t))
877 (when company-candidates
879 (company-post-command)))))
881 (defun company-auto-begin ()
882 (company-assert-enabled)
884 (not company-candidates)
885 (let ((company-idle-delay t)
886 (company-minimum-prefix-length 0)
887 (company-begin-commands t))
889 ;; Return non-nil if active.
892 (defun company-manual-begin ()
894 (setq company--explicit-action t)
895 (company-auto-begin))
897 (defun company-other-backend (&optional backward)
898 (interactive (list current-prefix-arg))
899 (company-assert-enabled)
901 (let* ((after (cdr (member company-backend company-backends)))
902 (before (cdr (member company-backend (reverse company-backends))))
904 (append before (reverse after))
905 (append after (reverse before)))))
907 (dolist (backend next)
908 (when (ignore-errors (company-begin-backend backend))
910 (company-manual-begin))
911 (unless company-candidates
912 (error "No other back-end")))
914 (defun company-require-match-p ()
915 (let ((backend-value (company-call-backend 'require-match)))
916 (or (eq backend-value t)
917 (and (if (functionp company-require-match)
918 (funcall company-require-match)
919 (eq company-require-match t))
920 (not (eq backend-value 'never))))))
922 (defun company-punctuation-p (input)
923 "Return non-nil, if input starts with punctuation or parentheses."
924 (memq (char-syntax (string-to-char input)) '(?. ?\( ?\))))
926 (defun company-auto-complete-p (input)
927 "Return non-nil, if input starts with punctuation or parentheses."
928 (and (if (functionp company-auto-complete)
929 (funcall company-auto-complete)
930 company-auto-complete)
931 (if (functionp company-auto-complete-chars)
932 (funcall company-auto-complete-chars input)
933 (if (consp company-auto-complete-chars)
934 (memq (char-syntax (string-to-char input))
935 company-auto-complete-chars)
936 (string-match (substring input 0 1) company-auto-complete-chars)))))
938 (defun company--incremental-p ()
939 (and (> (point) company-point)
940 (> (point-max) company--point-max)
941 (not (eq this-command 'backward-delete-char-untabify))
942 (equal (buffer-substring (- company-point (length company-prefix))
946 (defsubst company--string-incremental-p (old-prefix new-prefix)
947 (and (> (length new-prefix) (length old-prefix))
948 (equal old-prefix (substring new-prefix 0 (length old-prefix)))))
950 (defun company--continue-failed (new-prefix)
951 (when (company--incremental-p)
952 (let ((input (buffer-substring-no-properties (point) company-point)))
954 ((company-auto-complete-p input)
957 (goto-char company-point)
958 (company-complete-selection)
960 ((and (company--string-incremental-p company-prefix new-prefix)
961 (company-require-match-p))
962 ;; wrong incremental input, but required match
963 (backward-delete-char (length input))
965 (message "Matching input is required")
967 ((equal company-prefix (car company-candidates))
968 ;; last input was actually success
969 (company-cancel company-prefix)
972 (defun company--good-prefix-p (prefix)
973 (and (or (company-explicit-action-p)
974 (>= (or (cdr-safe prefix) (length prefix))
975 company-minimum-prefix-length))
976 (stringp (or (car-safe prefix) prefix))))
978 (defun company--continue ()
979 (when (company-call-backend 'no-cache company-prefix)
980 ;; Don't complete existing candidates, fetch new ones.
981 (setq company-candidates-cache nil))
982 (let* ((new-prefix (company-call-backend 'prefix))
983 (c (when (and (company--good-prefix-p new-prefix)
984 (setq new-prefix (or (car-safe new-prefix) new-prefix))
985 (= (- (point) (length new-prefix))
986 (- company-point (length company-prefix))))
987 (setq new-prefix (or (car-safe new-prefix) new-prefix))
988 (company-calculate-candidates new-prefix))))
991 ;; t means complete/unique.
992 (company-cancel new-prefix)
996 (setq company-prefix new-prefix)
997 (company-update-candidates c)
999 (t (company--continue-failed new-prefix)))
1002 (defun company--begin-new ()
1004 (dolist (backend (if company-backend
1005 ;; prefer manual override
1006 (list company-backend)
1009 (if (or (symbolp backend)
1010 (functionp backend))
1011 (when (or (not (symbolp backend))
1012 (eq t (get backend 'company-init))
1013 (unless (get backend 'company-init)
1014 (company-init-backend backend)))
1015 (funcall backend 'prefix))
1016 (company--multi-backend-adapter backend 'prefix)))
1018 (when (company--good-prefix-p prefix)
1019 (setq prefix (or (car-safe prefix) prefix)
1020 company-backend backend
1021 c (company-calculate-candidates prefix))
1022 ;; t means complete/unique. We don't start, so no hooks.
1024 (when company--explicit-action
1025 (message "No completion found"))
1026 (setq company-prefix prefix)
1027 (when (symbolp backend)
1028 (setq company-lighter (concat " " (symbol-name backend))))
1029 (company-update-candidates c)
1030 (run-hook-with-args 'company-completion-started-hook
1031 (company-explicit-action-p))
1032 (company-call-frontends 'show)))
1035 (defun company-begin ()
1036 (setq company-candidates
1037 (or (and company-candidates (company--continue))
1038 (and (company--should-complete) (company--begin-new))))
1039 (when company-candidates
1040 (when (and company-end-of-buffer-workaround (eobp))
1041 (save-excursion (insert "\n"))
1042 (setq company-added-newline (buffer-chars-modified-tick)))
1043 (setq company-point (point)
1044 company--point-max (point-max))
1045 (company-enable-overriding-keymap company-active-map)
1046 (company-call-frontends 'update)))
1048 (defun company-cancel (&optional result)
1049 (and company-added-newline
1050 (> (point-max) (point-min))
1051 (let ((tick (buffer-chars-modified-tick)))
1052 (delete-region (1- (point-max)) (point-max))
1053 (equal tick company-added-newline))
1054 ;; Only set unmodified when tick remained the same since insert.
1055 (set-buffer-modified-p nil))
1056 (when company-prefix
1057 (if (stringp result)
1059 (company-call-backend 'pre-completion result)
1060 (run-hook-with-args 'company-completion-finished-hook result)
1061 (company-call-backend 'post-completion result))
1062 (run-hook-with-args 'company-completion-cancelled-hook result)))
1063 (setq company-added-newline nil
1066 company-candidates nil
1067 company-candidates-length nil
1068 company-candidates-cache nil
1069 company-candidates-predicate nil
1072 company-selection-changed nil
1073 company--explicit-action nil
1074 company-lighter company-default-lighter
1075 company--point-max nil
1078 (cancel-timer company-timer))
1079 (company-search-mode 0)
1080 (company-call-frontends 'hide)
1081 (company-enable-overriding-keymap nil))
1083 (defun company-abort ()
1086 ;; Don't start again, unless started manually.
1087 (setq company-point (point)))
1089 (defun company-finish (result)
1090 (insert (company-strip-prefix result))
1091 (company-cancel result)
1092 ;; Don't start again, unless started manually.
1093 (setq company-point (point)))
1095 (defsubst company-keep (command)
1096 (and (symbolp command) (get command 'company-keep)))
1098 (defun company-pre-command ()
1099 (unless (company-keep this-command)
1101 (when company-candidates
1102 (company-call-frontends 'pre-command))
1103 (error (message "Company: An error occurred in pre-command")
1104 (message "%s" (error-message-string err))
1107 (cancel-timer company-timer)
1108 (setq company-timer nil))
1109 (company-uninstall-map))
1111 (defun company-post-command ()
1112 (unless (company-keep this-command)
1115 (unless (equal (point) company-point)
1117 (if company-candidates
1118 (company-call-frontends 'post-command)
1119 (and (numberp company-idle-delay)
1120 (or (eq t company-begin-commands)
1121 (memq this-command company-begin-commands))
1123 (run-with-timer company-idle-delay nil
1125 (current-buffer) (selected-window)
1126 (buffer-chars-modified-tick) (point))))))
1127 (error (message "Company: An error occurred in post-command")
1128 (message "%s" (error-message-string err))
1130 (company-install-map))
1132 ;;; search ;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;
1134 (defvar company-search-string nil)
1135 (make-variable-buffer-local 'company-search-string)
1137 (defvar company-search-lighter " Search: \"\"")
1138 (make-variable-buffer-local 'company-search-lighter)
1140 (defvar company-search-old-map nil)
1141 (make-variable-buffer-local 'company-search-old-map)
1143 (defvar company-search-old-selection 0)
1144 (make-variable-buffer-local 'company-search-old-selection)
1146 (defun company-search (text lines)
1147 (let ((quoted (regexp-quote text))
1149 (dolist (line lines)
1150 (when (string-match quoted line (length company-prefix))
1154 (defun company-search-printing-char ()
1156 (company-search-assert-enabled)
1157 (setq company-search-string
1158 (concat (or company-search-string "") (string last-command-event))
1159 company-search-lighter (concat " Search: \"" company-search-string
1161 (let ((pos (company-search company-search-string
1162 (nthcdr company-selection company-candidates))))
1165 (company-set-selection (+ company-selection pos) t))))
1167 (defun company-search-repeat-forward ()
1168 "Repeat the incremental search in completion candidates forward."
1170 (company-search-assert-enabled)
1171 (let ((pos (company-search company-search-string
1172 (cdr (nthcdr company-selection
1173 company-candidates)))))
1176 (company-set-selection (+ company-selection pos 1) t))))
1178 (defun company-search-repeat-backward ()
1179 "Repeat the incremental search in completion candidates backwards."
1181 (company-search-assert-enabled)
1182 (let ((pos (company-search company-search-string
1183 (nthcdr (- company-candidates-length
1185 (reverse company-candidates)))))
1188 (company-set-selection (- company-selection pos 1) t))))
1190 (defun company-create-match-predicate ()
1191 (setq company-candidates-predicate
1192 `(lambda (candidate)
1193 ,(if company-candidates-predicate
1194 `(and (string-match ,company-search-string candidate)
1195 (funcall ,company-candidates-predicate
1197 `(string-match ,company-search-string candidate))))
1198 (company-update-candidates
1199 (company-apply-predicate company-candidates company-candidates-predicate))
1200 ;; Invalidate cache.
1201 (setq company-candidates-cache (cons company-prefix company-candidates)))
1203 (defun company-filter-printing-char ()
1205 (company-search-assert-enabled)
1206 (company-search-printing-char)
1207 (company-create-match-predicate)
1208 (company-call-frontends 'update))
1210 (defun company-search-kill-others ()
1211 "Limit the completion candidates to the ones matching the search string."
1213 (company-search-assert-enabled)
1214 (company-create-match-predicate)
1215 (company-search-mode 0)
1216 (company-call-frontends 'update))
1218 (defun company-search-abort ()
1219 "Abort searching the completion candidates."
1221 (company-search-assert-enabled)
1222 (company-set-selection company-search-old-selection t)
1223 (company-search-mode 0))
1225 (defun company-search-other-char ()
1227 (company-search-assert-enabled)
1228 (company-search-mode 0)
1229 (when last-input-event
1230 (clear-this-command-keys t)
1231 (setq unread-command-events (list last-input-event))))
1233 (defvar company-search-map
1235 (keymap (make-keymap)))
1236 (if (fboundp 'max-char)
1237 (set-char-table-range (nth 1 keymap) (cons #x100 (max-char))
1238 'company-search-printing-char)
1240 ;; obselete in Emacs 23
1241 (let ((l (generic-character-list))
1242 (table (nth 1 keymap)))
1244 (set-char-table-default table (car l) 'company-search-printing-char)
1245 (setq l (cdr l))))))
1246 (define-key keymap [t] 'company-search-other-char)
1248 (define-key keymap (make-string 1 i) 'company-search-other-char)
1251 (define-key keymap (vector i) 'company-search-printing-char)
1253 (let ((meta-map (make-sparse-keymap)))
1254 (define-key keymap (char-to-string meta-prefix-char) meta-map)
1255 (define-key keymap [escape] meta-map))
1256 (define-key keymap (vector meta-prefix-char t) 'company-search-other-char)
1257 (define-key keymap "\e\e\e" 'company-search-other-char)
1258 (define-key keymap [escape escape escape] 'company-search-other-char)
1260 (define-key keymap "\C-g" 'company-search-abort)
1261 (define-key keymap "\C-s" 'company-search-repeat-forward)
1262 (define-key keymap "\C-r" 'company-search-repeat-backward)
1263 (define-key keymap "\C-o" 'company-search-kill-others)
1265 "Keymap used for incrementally searching the completion candidates.")
1267 (define-minor-mode company-search-mode
1268 "Search mode for completion candidates.
1269 Don't start this directly, use `company-search-candidates' or
1270 `company-filter-candidates'."
1271 nil company-search-lighter nil
1272 (if company-search-mode
1273 (if (company-manual-begin)
1275 (setq company-search-old-selection company-selection)
1276 (company-call-frontends 'update))
1277 (setq company-search-mode nil))
1278 (kill-local-variable 'company-search-string)
1279 (kill-local-variable 'company-search-lighter)
1280 (kill-local-variable 'company-search-old-selection)
1281 (company-enable-overriding-keymap company-active-map)))
1283 (defsubst company-search-assert-enabled ()
1284 (company-assert-enabled)
1285 (unless company-search-mode
1286 (company-uninstall-map)
1287 (error "Company not in search mode")))
1289 (defun company-search-candidates ()
1290 "Start searching the completion candidates incrementally.
1292 \\<company-search-map>Search can be controlled with the commands:
1293 - `company-search-repeat-forward' (\\[company-search-repeat-forward])
1294 - `company-search-repeat-backward' (\\[company-search-repeat-backward])
1295 - `company-search-abort' (\\[company-search-abort])
1297 Regular characters are appended to the search string.
1299 The command `company-search-kill-others' (\\[company-search-kill-others]) uses
1300 the search string to limit the completion candidates."
1302 (company-search-mode 1)
1303 (company-enable-overriding-keymap company-search-map))
1305 (defvar company-filter-map
1306 (let ((keymap (make-keymap)))
1307 (define-key keymap [remap company-search-printing-char]
1308 'company-filter-printing-char)
1309 (set-keymap-parent keymap company-search-map)
1311 "Keymap used for incrementally searching the completion candidates.")
1313 (defun company-filter-candidates ()
1314 "Start filtering the completion candidates incrementally.
1315 This works the same way as `company-search-candidates' immediately
1316 followed by `company-search-kill-others' after each input."
1318 (company-search-mode 1)
1319 (company-enable-overriding-keymap company-filter-map))
1321 ;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;
1323 (defun company-select-next ()
1324 "Select the next candidate in the list."
1326 (when (company-manual-begin)
1327 (company-set-selection (1+ company-selection))))
1329 (defun company-select-previous ()
1330 "Select the previous candidate in the list."
1332 (when (company-manual-begin)
1333 (company-set-selection (1- company-selection))))
1335 (defun company-select-mouse (event)
1336 "Select the candidate picked by the mouse."
1338 (when (nth 4 (event-start event))
1339 (company-set-selection (- (cdr (posn-actual-col-row (event-start event)))
1344 (defun company-complete-mouse (event)
1345 "Complete the candidate picked by the mouse."
1347 (when (company-select-mouse event)
1348 (company-complete-selection)))
1350 (defun company-complete-selection ()
1351 "Complete the selected candidate."
1353 (when (company-manual-begin)
1354 (company-finish (nth company-selection company-candidates))))
1356 (defun company-complete-common ()
1357 "Complete the common part of all candidates."
1359 (when (company-manual-begin)
1360 (if (and (not (cdr company-candidates))
1361 (equal company-common (car company-candidates)))
1362 (company-complete-selection)
1363 (insert (company-strip-prefix company-common)))))
1365 (defun company-complete ()
1366 "Complete the common part of all candidates or the current selection.
1367 The first time this is called, the common part is completed, the second time, or
1368 when the selection has been changed, the selected candidate is completed."
1370 (when (company-manual-begin)
1371 (if (or company-selection-changed
1372 (eq last-command 'company-complete-common))
1373 (call-interactively 'company-complete-selection)
1374 (call-interactively 'company-complete-common)
1375 (setq this-command 'company-complete-common))))
1377 (defun company-complete-number (n)
1378 "Complete the Nth candidate.
1379 To show the number next to the candidates in some back-ends, enable
1380 `company-show-numbers'."
1381 (when (company-manual-begin)
1382 (and (< n 1) (> n company-candidates-length)
1383 (error "No candidate number %d" n))
1385 (company-finish (nth n company-candidates))))
1387 ;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;
1389 (defconst company-space-strings-limit 100)
1391 (defconst company-space-strings
1393 (dotimes (i company-space-strings-limit)
1394 (push (make-string (- company-space-strings-limit 1 i) ?\ ) lst))
1395 (apply 'vector lst)))
1397 (defsubst company-space-string (len)
1398 (if (< len company-space-strings-limit)
1399 (aref company-space-strings len)
1400 (make-string len ?\ )))
1402 (defsubst company-safe-substring (str from &optional to)
1403 (let ((len (length str)))
1406 (if (and to (> to len))
1407 (concat (substring str from)
1408 (company-space-string (- to len)))
1409 (substring str from to)))))
1411 ;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;
1413 (defvar company-last-metadata nil)
1414 (make-variable-buffer-local 'company-last-metadata)
1416 (defun company-fetch-metadata ()
1417 (let ((selected (nth company-selection company-candidates)))
1418 (unless (equal selected (car company-last-metadata))
1419 (setq company-last-metadata
1420 (cons selected (company-call-backend 'meta selected))))
1421 (cdr company-last-metadata)))
1423 (defun company-doc-buffer (&optional string)
1424 (with-current-buffer (get-buffer-create "*Company meta-data*")
1428 (defvar company--electric-commands
1429 '(scroll-other-window scroll-other-window-down)
1430 "List of Commands that won't break out of electric commands.")
1432 (defmacro company--electric-do (&rest body)
1433 (declare (indent 0) (debug t))
1434 `(when (company-manual-begin)
1435 (save-window-excursion
1436 (let ((height (window-height))
1437 (row (company--row))
1440 (and (< (window-height) height)
1441 (< (- (window-height) row 2) company-tooltip-limit)
1442 (recenter (- (window-height) row 2)))
1443 (while (memq (setq cmd (key-binding (vector (list (read-event)))))
1444 company--electric-commands)
1445 (call-interactively cmd))
1446 (when last-input-event
1447 (clear-this-command-keys t)
1448 (setq unread-command-events (list last-input-event)))))))
1450 (defun company-show-doc-buffer ()
1451 "Temporarily show a buffer with the complete documentation for the selection."
1453 (company--electric-do
1454 (let* ((selected (nth company-selection company-candidates))
1455 (doc-buffer (or (company-call-backend 'doc-buffer selected)
1456 (error "No documentation available"))))
1457 (with-current-buffer doc-buffer
1458 (goto-char (point-min)))
1459 (display-buffer doc-buffer t))))
1460 (put 'company-show-doc-buffer 'company-keep t)
1462 (defun company-show-location ()
1463 "Temporarily display a buffer showing the selected candidate in context."
1465 (company--electric-do
1466 (let* ((selected (nth company-selection company-candidates))
1467 (location (company-call-backend 'location selected))
1468 (pos (or (cdr location) (error "No location available")))
1469 (buffer (or (and (bufferp (car location)) (car location))
1470 (find-file-noselect (car location) t))))
1471 (with-selected-window (display-buffer buffer t)
1474 (if (bufferp (car location))
1476 (goto-char (point-min))
1477 (forward-line (1- pos))))
1478 (set-window-start nil (point))))))
1479 (put 'company-show-location 'company-keep t)
1481 ;;; package functions ;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;
1483 (defvar company-callback nil)
1484 (make-variable-buffer-local 'company-callback)
1486 (defvar company-begin-with-marker nil)
1487 (make-variable-buffer-local 'company-begin-with-marker)
1489 (defun company-remove-callback (&optional ignored)
1490 (remove-hook 'company-completion-finished-hook company-callback t)
1491 (remove-hook 'company-completion-cancelled-hook 'company-remove-callback t)
1492 (remove-hook 'company-completion-finished-hook 'company-remove-callback t)
1493 (when company-begin-with-marker
1494 (set-marker company-begin-with-marker nil)))
1496 (defun company-begin-backend (backend &optional callback)
1497 "Start a completion at point using BACKEND."
1498 (interactive (let ((val (completing-read "Company back-end: "
1500 'functionp nil "company-")))
1502 (list (intern val)))))
1503 (when (setq company-callback callback)
1504 (add-hook 'company-completion-finished-hook company-callback nil t))
1505 (add-hook 'company-completion-cancelled-hook 'company-remove-callback nil t)
1506 (add-hook 'company-completion-finished-hook 'company-remove-callback nil t)
1507 (setq company-backend backend)
1508 ;; Return non-nil if active.
1509 (or (company-manual-begin)
1510 (error "Cannot complete at point")))
1512 (defun company-begin-with (candidates
1513 &optional prefix-length require-match callback)
1514 "Start a completion at point.
1515 CANDIDATES is the list of candidates to use and PREFIX-LENGTH is the length of
1516 the prefix that already is in the buffer before point. It defaults to 0.
1518 CALLBACK is a function called with the selected result if the user successfully
1519 completes the input.
1522 \(company-begin-with '\(\"foo\" \"foobar\" \"foobarbaz\"\)\)"
1523 (setq company-begin-with-marker (copy-marker (point) t))
1524 (company-begin-backend
1525 `(lambda (command &optional arg &rest ignored)
1527 ((eq command 'prefix)
1528 (when (equal (point) (marker-position company-begin-with-marker))
1529 (buffer-substring ,(- (point) (or prefix-length 0)) (point))))
1530 ((eq command 'candidates)
1531 (all-completions arg ',candidates))
1532 ((eq command 'require-match)
1536 ;;; pseudo-tooltip ;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;
1538 (defvar company-pseudo-tooltip-overlay nil)
1539 (make-variable-buffer-local 'company-pseudo-tooltip-overlay)
1541 (defvar company-tooltip-offset 0)
1542 (make-variable-buffer-local 'company-tooltip-offset)
1544 (defun company-pseudo-tooltip-update-offset (selection num-lines limit)
1547 (setq company-tooltip-offset
1548 (max (min selection company-tooltip-offset)
1549 (- selection -1 limit)))
1551 (when (<= company-tooltip-offset 1)
1553 (setq company-tooltip-offset 0))
1555 (when (>= company-tooltip-offset (- num-lines limit 1))
1557 (when (= selection (1- num-lines))
1558 (decf company-tooltip-offset)
1559 (when (<= company-tooltip-offset 1)
1560 (setq company-tooltip-offset 0)
1567 (defsubst company-round-tab (arg)
1568 (* (/ (+ arg tab-width) tab-width) tab-width))
1570 (defun company-untabify (str)
1571 (let* ((pieces (split-string str "\t"))
1574 (setcar copy (company-safe-substring
1575 (car copy) 0 (company-round-tab (string-width (car copy)))))
1577 (apply 'concat pieces)))
1579 (defun company-fill-propertize (line width selected)
1580 (setq line (company-safe-substring line 0 width))
1581 (add-text-properties 0 width '(face company-tooltip
1582 mouse-face company-tooltip-mouse)
1584 (add-text-properties 0 (length company-common)
1585 '(face company-tooltip-common
1586 mouse-face company-tooltip-mouse)
1589 (if (and company-search-string
1590 (string-match (regexp-quote company-search-string) line
1591 (length company-prefix)))
1593 (add-text-properties (match-beginning 0) (match-end 0)
1594 '(face company-tooltip-selection)
1596 (when (< (match-beginning 0) (length company-common))
1597 (add-text-properties (match-beginning 0) (length company-common)
1598 '(face company-tooltip-common-selection)
1600 (add-text-properties 0 width '(face company-tooltip-selection
1601 mouse-face company-tooltip-selection)
1603 (add-text-properties 0 (length company-common)
1604 '(face company-tooltip-common-selection
1605 mouse-face company-tooltip-selection)
1611 (defun company-buffer-lines (beg end)
1613 (let ((row (company--row))
1615 (while (and (equal (move-to-window-line (incf row)) row)
1617 (push (buffer-substring beg (min end (1- (point)))) lines)
1619 (unless (eq beg end)
1620 (push (buffer-substring beg end) lines))
1623 (defsubst company-modify-line (old new offset)
1624 (concat (company-safe-substring old 0 offset)
1626 (company-safe-substring old (+ offset (length new)))))
1628 (defsubst company--length-limit (lst limit)
1629 (if (nthcdr limit lst)
1633 (defun company--replacement-string (lines old column nl &optional align-top)
1635 (let ((width (length (car lines))))
1636 (when (> width (- (window-width) column))
1637 (setq column (max 0 (- (window-width) width)))))
1641 ;; untouched lines first
1642 (dotimes (i (- (length old) (length lines)))
1643 (push (pop old) new)))
1644 ;; length into old lines.
1646 (push (company-modify-line (pop old) (pop lines) column) new))
1647 ;; Append whole new lines.
1649 (push (concat (company-space-string column) (pop lines)) new))
1650 (concat (when nl "\n")
1651 (mapconcat 'identity (nreverse new) "\n")
1654 (defun company--create-lines (selection limit)
1656 (let ((len company-candidates-length)
1665 ;; Scroll to offset.
1666 (setq limit (company-pseudo-tooltip-update-offset selection len limit))
1668 (when (> company-tooltip-offset 0)
1669 (setq previous (format "...(%d)" company-tooltip-offset)))
1671 (setq remainder (- len limit company-tooltip-offset)
1672 remainder (when (> remainder 0)
1673 (setq remainder (format "...(%d)" remainder))))
1675 (decf selection company-tooltip-offset)
1676 (setq width (max (length previous) (length remainder))
1677 lines (nthcdr company-tooltip-offset company-candidates)
1682 (setq width (max (length (pop lines-copy)) width)))
1683 (setq width (min width (window-width)))
1685 (setq lines-copy lines)
1687 ;; number can make tooltip too long
1688 (when company-show-numbers
1689 (setq numbered company-tooltip-offset))
1692 (push (propertize (company-safe-substring previous 0 width)
1693 'face 'company-tooltip)
1697 (push (company-fill-propertize
1698 (if (>= numbered 10)
1699 (company-reformat (pop lines))
1702 (company-safe-substring (company-reformat (pop lines))
1705 width (equal i selection))
1709 (push (propertize (company-safe-substring remainder 0 width)
1710 'face 'company-tooltip)
1713 (setq lines (nreverse new))))
1717 (defsubst company--window-inner-height ()
1718 (let ((edges (window-inside-edges (selected-window))))
1719 (- (nth 3 edges) (nth 1 edges))))
1721 (defsubst company--pseudo-tooltip-height ()
1722 "Calculate the appropriate tooltip height.
1723 Returns a negative number if the tooltip should be displayed above point."
1724 (let* ((lines (count-lines (window-start) (point-at-bol)))
1725 (below (- (company--window-inner-height) 1 lines)))
1726 (if (and (< below (min company-tooltip-minimum company-candidates-length))
1728 (- (max 3 (min company-tooltip-limit lines)))
1729 (max 3 (min company-tooltip-limit below)))))
1731 (defun company-pseudo-tooltip-show (row column selection)
1732 (company-pseudo-tooltip-hide)
1737 (let* ((height (company--pseudo-tooltip-height))
1741 (setq row (+ row height -1)
1744 (let* ((nl (< (move-to-window-line row) row))
1746 (end (save-excursion
1747 (move-to-window-line (+ row (abs height)))
1749 (ov (make-overlay beg end))
1750 (args (list (mapcar 'company-untabify
1751 (company-buffer-lines beg end))
1754 (setq company-pseudo-tooltip-overlay ov)
1755 (overlay-put ov 'company-replacement-args args)
1756 (overlay-put ov 'company-before
1757 (apply 'company--replacement-string
1758 (company--create-lines selection (abs height))
1761 (overlay-put ov 'company-column column)
1762 (overlay-put ov 'company-height (abs height))
1763 (overlay-put ov 'window (selected-window))))))
1765 (defun company-pseudo-tooltip-show-at-point (pos)
1766 (let ((col-row (company--col-row pos)))
1768 (company-pseudo-tooltip-show (1+ (cdr col-row)) (car col-row)
1769 company-selection))))
1771 (defun company-pseudo-tooltip-edit (lines selection)
1772 (let ((column (overlay-get company-pseudo-tooltip-overlay 'company-column))
1773 (height (overlay-get company-pseudo-tooltip-overlay 'company-height)))
1774 (overlay-put company-pseudo-tooltip-overlay 'company-before
1775 (apply 'company--replacement-string
1776 (company--create-lines selection height)
1777 (overlay-get company-pseudo-tooltip-overlay
1778 'company-replacement-args)))))
1780 (defun company-pseudo-tooltip-hide ()
1781 (when company-pseudo-tooltip-overlay
1782 (delete-overlay company-pseudo-tooltip-overlay)
1783 (setq company-pseudo-tooltip-overlay nil)))
1785 (defun company-pseudo-tooltip-hide-temporarily ()
1786 (when (overlayp company-pseudo-tooltip-overlay)
1787 (overlay-put company-pseudo-tooltip-overlay 'invisible nil)
1788 (overlay-put company-pseudo-tooltip-overlay 'before-string nil)))
1790 (defun company-pseudo-tooltip-unhide ()
1791 (when company-pseudo-tooltip-overlay
1792 (overlay-put company-pseudo-tooltip-overlay 'invisible t)
1793 (overlay-put company-pseudo-tooltip-overlay 'before-string
1794 (overlay-get company-pseudo-tooltip-overlay 'company-before))
1795 (overlay-put company-pseudo-tooltip-overlay 'window (selected-window))))
1797 (defun company-pseudo-tooltip-frontend (command)
1798 "A `company-mode' front-end similar to a tool-tip but based on overlays."
1800 ('pre-command (company-pseudo-tooltip-hide-temporarily))
1802 (let ((old-height (if (overlayp company-pseudo-tooltip-overlay)
1803 (overlay-get company-pseudo-tooltip-overlay
1806 (new-height (company--pseudo-tooltip-height)))
1807 (unless (and (>= (* old-height new-height) 0)
1808 (>= (abs old-height) (abs new-height)))
1810 (company-pseudo-tooltip-show-at-point (- (point)
1811 (length company-prefix)))))
1812 (company-pseudo-tooltip-unhide))
1813 ('hide (company-pseudo-tooltip-hide)
1814 (setq company-tooltip-offset 0))
1815 ('update (when (overlayp company-pseudo-tooltip-overlay)
1816 (company-pseudo-tooltip-edit company-candidates
1817 company-selection)))))
1819 (defun company-pseudo-tooltip-unless-just-one-frontend (command)
1820 "`company-pseudo-tooltip-frontend', but not shown for single candidates."
1821 (unless (and (eq command 'post-command)
1822 (not (cdr company-candidates)))
1823 (company-pseudo-tooltip-frontend command)))
1825 ;;; overlay ;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;
1827 (defvar company-preview-overlay nil)
1828 (make-variable-buffer-local 'company-preview-overlay)
1830 (defun company-preview-show-at-point (pos)
1831 (company-preview-hide)
1833 (setq company-preview-overlay (make-overlay pos pos))
1835 (let ((completion(nth company-selection company-candidates)))
1836 (setq completion (propertize completion 'face 'company-preview))
1837 (add-text-properties 0 (length company-common)
1838 '(face company-preview-common) completion)
1840 ;; Add search string
1841 (and company-search-string
1842 (string-match (regexp-quote company-search-string) completion)
1843 (add-text-properties (match-beginning 0)
1845 '(face company-preview-search)
1848 (setq completion (company-strip-prefix completion))
1850 (and (equal pos (point))
1851 (not (equal completion ""))
1852 (add-text-properties 0 1 '(cursor t) completion))
1854 (overlay-put company-preview-overlay 'after-string completion)
1855 (overlay-put company-preview-overlay 'window (selected-window))))
1857 (defun company-preview-hide ()
1858 (when company-preview-overlay
1859 (delete-overlay company-preview-overlay)
1860 (setq company-preview-overlay nil)))
1862 (defun company-preview-frontend (command)
1863 "A `company-mode' front-end showing the selection as if it had been inserted."
1865 ('pre-command (company-preview-hide))
1866 ('post-command (company-preview-show-at-point (point)))
1867 ('hide (company-preview-hide))))
1869 (defun company-preview-if-just-one-frontend (command)
1870 "`company-preview-frontend', but only shown for single candidates."
1871 (unless (and (eq command 'post-command)
1872 (cdr company-candidates))
1873 (company-preview-frontend command)))
1875 ;;; echo ;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;
1877 (defvar company-echo-last-msg nil)
1878 (make-variable-buffer-local 'company-echo-last-msg)
1880 (defvar company-echo-timer nil)
1882 (defvar company-echo-delay .01)
1884 (defun company-echo-show (&optional getter)
1886 (setq company-echo-last-msg (funcall getter)))
1887 (let ((message-log-max nil))
1888 (if company-echo-last-msg
1889 (message "%s" company-echo-last-msg)
1892 (defsubst company-echo-show-soon (&optional getter)
1893 (when company-echo-timer
1894 (cancel-timer company-echo-timer))
1895 (setq company-echo-timer (run-with-timer company-echo-delay nil
1896 'company-echo-show getter)))
1898 (defun company-echo-format ()
1900 (let ((limit (window-width (minibuffer-window)))
1902 ;; Roll to selection.
1903 (candidates (nthcdr company-selection company-candidates))
1904 (i (if company-show-numbers company-selection 99999))
1908 (setq comp (company-reformat (pop candidates))
1909 len (+ len 1 (length comp)))
1913 (setq comp (propertize (format "%d: %s" i comp)
1914 'face 'company-echo))
1917 (add-text-properties 3 (+ 3 (length company-common))
1918 '(face company-echo-common) comp))
1919 (setq comp (propertize comp 'face 'company-echo))
1920 (add-text-properties 0 (length company-common)
1921 '(face company-echo-common) comp))
1923 (setq candidates nil)
1926 (mapconcat 'identity (nreverse msg) " ")))
1928 (defun company-echo-strip-common-format ()
1930 (let ((limit (window-width (minibuffer-window)))
1931 (len (+ (length company-prefix) 2))
1932 ;; Roll to selection.
1933 (candidates (nthcdr company-selection company-candidates))
1934 (i (if company-show-numbers company-selection 99999))
1938 (setq comp (company-strip-prefix (pop candidates))
1939 len (+ len 2 (length comp)))
1942 (setq comp (format "%s (%d)" comp i))
1946 (setq candidates nil)
1947 (push (propertize comp 'face 'company-echo) msg)))
1949 (concat (propertize company-prefix 'face 'company-echo-common) "{"
1950 (mapconcat 'identity (nreverse msg) ", ")
1953 (defun company-echo-hide ()
1954 (when company-echo-timer
1955 (cancel-timer company-echo-timer))
1956 (unless (equal company-echo-last-msg "")
1957 (setq company-echo-last-msg "")
1958 (company-echo-show)))
1960 (defun company-echo-frontend (command)
1961 "A `company-mode' front-end showing the candidates in the echo area."
1963 ('pre-command (company-echo-show-soon))
1964 ('post-command (company-echo-show-soon 'company-echo-format))
1965 ('hide (company-echo-hide))))
1967 (defun company-echo-strip-common-frontend (command)
1968 "A `company-mode' front-end showing the candidates in the echo area."
1970 ('pre-command (company-echo-show-soon))
1971 ('post-command (company-echo-show-soon 'company-echo-strip-common-format))
1972 ('hide (company-echo-hide))))
1974 (defun company-echo-metadata-frontend (command)
1975 "A `company-mode' front-end showing the documentation in the echo area."
1977 ('pre-command (company-echo-show-soon))
1978 ('post-command (company-echo-show-soon 'company-fetch-metadata))
1979 ('hide (company-echo-hide))))
1982 ;;; company.el ends here