1 ;;; company.el --- extensible inline text completion mechanism
3 ;; Copyright (C) 2009-2010 Nikolaj Schumacher
5 ;; Author: Nikolaj Schumacher <bugs * nschum de>
7 ;; Keywords: abbrev, convenience, matching
8 ;; URL: http://nschum.de/src/emacs/company/
9 ;; Compatibility: GNU Emacs 22.x, GNU Emacs 23.x
11 ;; This file is NOT part of GNU Emacs.
13 ;; This program is free software; you can redistribute it and/or
14 ;; modify it under the terms of the GNU General Public License
15 ;; as published by the Free Software Foundation; either version 2
16 ;; of the License, or (at your option) any later version.
18 ;; This program is distributed in the hope that it will be useful,
19 ;; but WITHOUT ANY WARRANTY; without even the implied warranty of
20 ;; MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
21 ;; GNU General Public License for more details.
23 ;; You should have received a copy of the GNU General Public License
24 ;; along with this program. If not, see <http://www.gnu.org/licenses/>.
28 ;; Company is a modular completion mechanism. Modules for retrieving completion
29 ;; candidates are called back-ends, modules for displaying them are front-ends.
31 ;; Company comes with many back-ends, e.g. `company-elisp'. These are
32 ;; distributed in individual files and can be used individually.
34 ;; Place company.el and the back-ends you want to use in a directory and add the
35 ;; following to your .emacs:
36 ;; (add-to-list 'load-path "/path/to/company")
37 ;; (autoload 'company-mode "company" nil t)
39 ;; Enable company-mode with M-x company-mode. For further information look at
40 ;; the documentation for `company-mode' (C-h f company-mode RET)
42 ;; If you want to start a specific back-end, call it interactively or use
43 ;; `company-begin-backend'. For example:
44 ;; M-x company-abbrev will prompt for and insert an abbrev.
46 ;; To write your own back-end, look at the documentation for `company-backends'.
47 ;; Here is a simple example completing "foo":
49 ;; (defun company-my-backend (command &optional arg &rest ignored)
51 ;; ('prefix (when (looking-back "foo\\>")
53 ;; ('candidates (list "foobar" "foobaz" "foobarbaz"))
54 ;; ('meta (format "This value is named %s" arg))))
56 ;; Sometimes it is a good idea to mix two back-ends together, for example to
57 ;; enrich gtags with dabbrev-code results (to emulate local variables):
58 ;; To do this, add a list with the merged back-ends as an element in
62 ;; When point is at the very end of the buffer, the pseudo-tooltip appears very
63 ;; wrong, unless company is allowed to temporarily insert a fake newline.
64 ;; This behavior is enabled by `company-end-of-buffer-workaround'.
69 ;; `company-ropemacs' now provides location and docs. (Fernando H. Silva)
70 ;; Added `company-with-candidate-inserted' macro.
71 ;; Added `company-clang' back-end.
72 ;; Added new mechanism for non-consecutive insertion.
73 ;; (So far only used by clang for ObjC.)
74 ;; The semantic back-end now shows meta information for local symbols.
75 ;; Added compatibility for CEDET in Emacs 23.2 and from CVS. (Oleg Andreev)
78 ;; Added `company-other-backend'.
79 ;; Idle completion no longer interrupts multi-key command input.
80 ;; Added `company-ropemacs' and `company-pysmell' back-ends.
83 ;; In C modes . and -> now count towards `company-minimum-prefix-length'.
84 ;; Reverted default front-end back to `company-preview-if-just-one-frontend'.
85 ;; The pseudo tooltip will no longer be clipped at the right window edge.
86 ;; Added `company-tooltip-minimum'.
87 ;; Windows compatibility fixes.
90 ;; Added `global-company-mode'.
91 ;; Performance enhancements.
92 ;; Added `company-eclim' back-end.
93 ;; Added safer workaround for Emacs `posn-col-row' bug.
96 ;; Automatic completion is now aborted if the prefix gets too short.
97 ;; Added option `company-dabbrev-time-limit'.
98 ;; `company-backends' now supports merging back-ends.
99 ;; Added back-end `company-dabbrev-code' for generic code.
100 ;; Fixed `company-begin-with'.
102 ;; 2009-04-15 (0.3.1)
103 ;; Added 'stop prefix to prevent dabbrev from completing inside of symbols.
104 ;; Fixed issues with tabbar-mode and line-spacing.
105 ;; Performance enhancements.
108 ;; Added `company-begin-commands' option.
109 ;; Added abbrev, tempo and Xcode back-ends.
110 ;; Back-ends are now interactive. You can start them with M-x backend-name.
111 ;; Added `company-begin-with' for starting company from elisp-code.
113 ;; Added `company-require-match' and `company-auto-complete' options.
115 ;; 2009-04-05 (0.2.1)
116 ;; Improved Emacs Lisp back-end behavior for local variables.
117 ;; Added `company-elisp-detect-function-context' option.
118 ;; The mouse can now be used for selection.
121 ;; Added `company-show-location'.
122 ;; Added etags back-end.
123 ;; Added work-around for end-of-buffer bug.
124 ;; Added `company-filter-candidates'.
125 ;; More local Lisp variables are now included in the candidates.
127 ;; 2009-03-21 (0.1.5)
128 ;; Fixed elisp documentation buffer always showing the same doc.
129 ;; Added `company-echo-strip-common-frontend'.
130 ;; Added `company-show-numbers' option and M-0 ... M-9 default bindings.
131 ;; Don't hide the echo message if it isn't shown.
138 (eval-when-compile (require 'cl))
140 (add-to-list 'debug-ignored-errors "^.* frontend cannot be used twice$")
141 (add-to-list 'debug-ignored-errors "^Echo area cannot be used twice$")
142 (add-to-list 'debug-ignored-errors "^No \\(document\\|loc\\)ation available$")
143 (add-to-list 'debug-ignored-errors "^Company not ")
144 (add-to-list 'debug-ignored-errors "^No candidate number ")
145 (add-to-list 'debug-ignored-errors "^Cannot complete at point$")
146 (add-to-list 'debug-ignored-errors "^No other back-end$")
148 (defgroup company nil
149 "Extensible inline text completion mechanism"
154 (defface company-tooltip
155 '((t :background "yellow"
156 :foreground "black"))
157 "*Face used for the tool tip."
160 (defface company-tooltip-selection
161 '((default :inherit company-tooltip)
162 (((class color) (min-colors 88)) (:background "orange1"))
163 (t (:background "green")))
164 "*Face used for the selection in the tool tip."
167 (defface company-tooltip-mouse
168 '((default :inherit highlight))
169 "*Face used for the tool tip item under the mouse."
172 (defface company-tooltip-common
173 '((t :inherit company-tooltip
175 "*Face used for the common completion in the tool tip."
178 (defface company-tooltip-common-selection
179 '((t :inherit company-tooltip-selection
181 "*Face used for the selected common completion in the tool tip."
184 (defface company-preview
185 '((t :background "blue4"
186 :foreground "wheat"))
187 "*Face used for the completion preview."
190 (defface company-preview-common
191 '((t :inherit company-preview
193 "*Face used for the common part of the completion preview."
196 (defface company-preview-search
197 '((t :inherit company-preview
198 :background "blue1"))
199 "*Face used for the search string in the completion preview."
202 (defface company-echo nil
203 "*Face used for completions in the echo area."
206 (defface company-echo-common
207 '((((background dark)) (:foreground "firebrick1"))
208 (((background light)) (:background "firebrick4")))
209 "*Face used for the common part of completions in the echo area."
212 (defun company-frontends-set (variable value)
214 (let ((remainder value))
215 (setcdr remainder (delq (car remainder) (cdr remainder))))
216 (and (memq 'company-pseudo-tooltip-unless-just-one-frontend value)
217 (memq 'company-pseudo-tooltip-frontend value)
218 (error "Pseudo tooltip frontend cannot be used twice"))
219 (and (memq 'company-preview-if-just-one-frontend value)
220 (memq 'company-preview-frontend value)
221 (error "Preview frontend cannot be used twice"))
222 (and (memq 'company-echo value)
223 (memq 'company-echo-metadata-frontend value)
224 (error "Echo area cannot be used twice"))
225 ;; preview must come last
226 (dolist (f '(company-preview-if-just-one-frontend company-preview-frontend))
228 (setq value (append (delq f value) (list f)))))
229 (set variable value))
231 (defcustom company-frontends '(company-pseudo-tooltip-unless-just-one-frontend
232 company-preview-if-just-one-frontend
233 company-echo-metadata-frontend)
234 "*The list of active front-ends (visualizations).
235 Each front-end is a function that takes one argument. It is called with
236 one of the following arguments:
238 'show: When the visualization should start.
240 'hide: When the visualization should end.
242 'update: When the data has been updated.
244 'pre-command: Before every command that is executed while the
245 visualization is active.
247 'post-command: After every command that is executed while the
248 visualization is active.
250 The visualized data is stored in `company-prefix', `company-candidates',
251 `company-common', `company-selection', `company-point' and
252 `company-search-string'."
253 :set 'company-frontends-set
255 :type '(repeat (choice (const :tag "echo" company-echo-frontend)
256 (const :tag "echo, strip common"
257 company-echo-strip-common-frontend)
258 (const :tag "show echo meta-data in echo"
259 company-echo-metadata-frontend)
260 (const :tag "pseudo tooltip"
261 company-pseudo-tooltip-frontend)
262 (const :tag "pseudo tooltip, multiple only"
263 company-pseudo-tooltip-unless-just-one-frontend)
264 (const :tag "preview" company-preview-frontend)
265 (const :tag "preview, unique only"
266 company-preview-if-just-one-frontend)
267 (function :tag "custom function" nil))))
269 (defcustom company-tooltip-limit 10
270 "*The maximum number of candidates in the tool tip"
274 (defcustom company-tooltip-minimum 6
275 "*The minimum height of the tool tip.
276 If this many lines are not available, prefer to display the tooltip above."
280 (defvar company-safe-backends
281 '((company-abbrev . "Abbrev")
282 (company-clang . "clang")
283 (company-css . "CSS")
284 (company-dabbrev . "dabbrev for plain text")
285 (company-dabbrev-code . "dabbrev for code")
286 (company-eclim . "eclim (an Eclipse interace)")
287 (company-elisp . "Emacs Lisp")
288 (company-etags . "etags")
289 (company-files . "Files")
290 (company-gtags . "GNU Global")
291 (company-ispell . "ispell")
292 (company-keywords . "Programming language keywords")
293 (company-nxml . "nxml")
294 (company-oddmuse . "Oddmuse")
295 (company-pysmell . "PySmell")
296 (company-ropemacs . "ropemacs")
297 (company-semantic . "CEDET Semantic")
298 (company-tempo . "Tempo templates")
299 (company-xcode . "Xcode")))
300 (put 'company-safe-backends 'risky-local-variable t)
302 (defun company-safe-backends-p (backends)
303 (and (consp backends)
304 (not (dolist (backend backends)
305 (unless (if (consp backend)
306 (company-safe-backends-p backend)
307 (assq backend company-safe-backends))
310 (defcustom company-backends '(company-elisp company-nxml company-css
311 company-eclim company-semantic company-clang
312 company-xcode company-ropemacs
313 (company-gtags company-etags company-dabbrev-code
314 company-pysmell company-keywords)
315 company-oddmuse company-files company-dabbrev)
316 "*The list of active back-ends (completion engines).
317 Each list elements can itself be a list of back-ends. In that case their
318 completions are merged. Otherwise only the first matching back-end returns
321 `company-begin-backend' can be used to start a specific back-end,
322 `company-other-backend' will skip to the next matching back-end in the list.
324 Each back-end is a function that takes a variable number of arguments.
325 The first argument is the command requested from the back-end. It is one
328 'prefix: The back-end should return the text to be completed. It must be
329 text immediately before `point'. Returning nil passes control to the next
330 back-end. The function should return 'stop if it should complete but cannot
331 \(e.g. if it is in the middle of a string\). If the returned value is only
332 part of the prefix (e.g. the part after \"->\" in C), the back-end may return a
333 cons of prefix and prefix length, which is then used in the
334 `company-minimum-prefix-length' test.
336 'candidates: The second argument is the prefix to be completed. The
337 return value should be a list of candidates that start with the prefix.
341 'sorted: The back-end may return t here to indicate that the candidates
342 are sorted and will not need to be sorted again.
344 'duplicates: If non-nil, company will take care of removing duplicates
347 'no-cache: Usually company doesn't ask for candidates again as completion
348 progresses, unless the back-end returns t for this command. The second
349 argument is the latest prefix.
351 'meta: The second argument is a completion candidate. The back-end should
352 return a (short) documentation string for it.
354 'doc-buffer: The second argument is a completion candidate. The back-end should
355 create a buffer (preferably with `company-doc-buffer'), fill it with
356 documentation and return it.
358 'location: The second argument is a completion candidate. The back-end can
359 return the cons of buffer and buffer location, or of file and line
360 number where the completion candidate was defined.
362 'require-match: If this value is t, the user is not allowed to enter anything
363 not offering as a candidate. Use with care! The default value nil gives the
364 user that choice with `company-require-match'. Return value 'never overrides
365 that option the other way around.
367 The back-end should return nil for all commands it does not support or
368 does not know about. It should also be callable interactively and use
369 `company-begin-backend' to start itself in that case."
374 ,@(mapcar (lambda (b) `(const :tag ,(cdr b) ,(car b)))
375 company-safe-backends)
376 (symbol :tag "User defined")
377 (repeat :tag "Merged Back-ends"
378 (choice :tag "Back-end"
379 ,@(mapcar (lambda (b)
380 `(const :tag ,(cdr b) ,(car b)))
381 company-safe-backends)
382 (symbol :tag "User defined"))))))
384 (put 'company-backends 'safe-local-variable 'company-safe-backends-p)
386 (defcustom company-completion-started-hook nil
387 "*Hook run when company starts completing.
388 The hook is called with one argument that is non-nil if the completion was
393 (defcustom company-completion-cancelled-hook nil
394 "*Hook run when company cancels completing.
395 The hook is called with one argument that is non-nil if the completion was
400 (defcustom company-completion-finished-hook nil
401 "*Hook run when company successfully completes.
402 The hook is called with the selected candidate as an argument."
406 (defcustom company-minimum-prefix-length 3
407 "*The minimum prefix length for automatic completion."
409 :type '(integer :tag "prefix length"))
411 (defcustom company-require-match 'company-explicit-action-p
412 "*If enabled, disallow non-matching input.
413 This can be a function do determine if a match is required.
415 This can be overridden by the back-end, if it returns t or 'never to
416 'require-match. `company-auto-complete' also takes precedence over this."
418 :type '(choice (const :tag "Off" nil)
419 (function :tag "Predicate function")
420 (const :tag "On, if user interaction took place"
421 'company-explicit-action-p)
422 (const :tag "On" t)))
424 (defcustom company-auto-complete 'company-explicit-action-p
425 "Determines when to auto-complete.
426 If this is enabled, all characters from `company-auto-complete-chars' complete
427 the selected completion. This can also be a function."
429 :type '(choice (const :tag "Off" nil)
430 (function :tag "Predicate function")
431 (const :tag "On, if user interaction took place"
432 'company-explicit-action-p)
433 (const :tag "On" t)))
435 (defcustom company-auto-complete-chars '(?\ ?\( ?\) ?. ?\" ?$ ?\' ?< ?| ?!)
436 "Determines which characters trigger an automatic completion.
437 See `company-auto-complete'. If this is a string, each string character causes
438 completion. If it is a list of syntax description characters (see
439 `modify-syntax-entry'), all characters with that syntax auto-complete.
441 This can also be a function, which is called with the new input and should
442 return non-nil if company should auto-complete.
444 A character that is part of a valid candidate never starts auto-completion."
446 :type '(choice (string :tag "Characters")
448 (const :tag "Whitespace" ?\ )
449 (const :tag "Symbol" ?_)
450 (const :tag "Opening parentheses" ?\()
451 (const :tag "Closing parentheses" ?\))
452 (const :tag "Word constituent" ?w)
453 (const :tag "Punctuation." ?.)
454 (const :tag "String quote." ?\")
455 (const :tag "Paired delimiter." ?$)
456 (const :tag "Expression quote or prefix operator." ?\')
457 (const :tag "Comment starter." ?<)
458 (const :tag "Comment ender." ?>)
459 (const :tag "Character-quote." ?/)
460 (const :tag "Generic string fence." ?|)
461 (const :tag "Generic comment fence." ?!))
462 (function :tag "Predicate function")))
464 (defcustom company-idle-delay .7
465 "*The idle delay in seconds until automatic completions starts.
466 A value of nil means never complete automatically, t means complete
467 immediately when a prefix of `company-minimum-prefix-length' is reached."
469 :type '(choice (const :tag "never (nil)" nil)
470 (const :tag "immediate (t)" t)
471 (number :tag "seconds")))
473 (defcustom company-begin-commands t
474 "*A list of commands following which company will start completing.
475 If this is t, it will complete after any command. See `company-idle-delay'.
477 Alternatively any command with a non-nil 'company-begin property is treated as
478 if it was on this list."
480 :type '(choice (const :tag "Any command" t)
481 (const :tag "Self insert command" '(self-insert-command))
482 (repeat :tag "Commands" function)))
484 (defcustom company-show-numbers nil
485 "*If enabled, show quick-access numbers for the first ten candidates."
487 :type '(choice (const :tag "off" nil)
488 (const :tag "on" t)))
490 (defvar company-end-of-buffer-workaround t
491 "*Work around a visualization bug when completing at the end of the buffer.
492 The work-around consists of adding a newline.")
494 ;;; mode ;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;
496 (defvar company-mode-map (make-sparse-keymap)
497 "Keymap used by `company-mode'.")
499 (defvar company-active-map
500 (let ((keymap (make-sparse-keymap)))
501 (define-key keymap "\e\e\e" 'company-abort)
502 (define-key keymap "\C-g" 'company-abort)
503 (define-key keymap (kbd "M-n") 'company-select-next)
504 (define-key keymap (kbd "M-p") 'company-select-previous)
505 (define-key keymap (kbd "<down>") 'company-select-next)
506 (define-key keymap (kbd "<up>") 'company-select-previous)
507 (define-key keymap [down-mouse-1] 'ignore)
508 (define-key keymap [down-mouse-3] 'ignore)
509 (define-key keymap [mouse-1] 'company-complete-mouse)
510 (define-key keymap [mouse-3] 'company-select-mouse)
511 (define-key keymap [up-mouse-1] 'ignore)
512 (define-key keymap [up-mouse-3] 'ignore)
513 (define-key keymap "\C-m" 'company-complete-selection)
514 (define-key keymap "\t" 'company-complete-common)
515 (define-key keymap (kbd "<f1>") 'company-show-doc-buffer)
516 (define-key keymap "\C-w" 'company-show-location)
517 (define-key keymap "\C-s" 'company-search-candidates)
518 (define-key keymap "\C-\M-s" 'company-filter-candidates)
520 (define-key keymap (vector (+ (aref (kbd "M-0") 0) i))
521 `(lambda () (interactive) (company-complete-number ,i))))
524 "Keymap that is enabled during an active completion.")
526 (defvar company--disabled-backends nil)
528 (defun company-init-backend (backend)
529 (and (symbolp backend)
530 (not (fboundp backend))
531 (ignore-errors (require backend nil t)))
533 (if (or (symbolp backend)
537 (funcall backend 'init)
538 (put backend 'company-init t))
540 (put backend 'company-init 'failed)
541 (unless (memq backend company--disabled-backends)
542 (message "Company back-end '%s' could not be initialized:\n%s"
543 backend (error-message-string err)))
544 (push backend company--disabled-backends)
546 (mapc 'company-init-backend backend)))
548 (defvar company-default-lighter " company")
550 (defvar company-lighter company-default-lighter)
551 (make-variable-buffer-local 'company-lighter)
554 (define-minor-mode company-mode
555 "\"complete anything\"; in in-buffer completion framework.
556 Completion starts automatically, depending on the values
557 `company-idle-delay' and `company-minimum-prefix-length'.
559 Completion can be controlled with the commands:
560 `company-complete-common', `company-complete-selection', `company-complete',
561 `company-select-next', `company-select-previous'. If these commands are
562 called before `company-idle-delay', completion will also start.
564 Completions can be searched with `company-search-candidates' or
565 `company-filter-candidates'. These can be used while completion is
568 The completion data is retrieved using `company-backends' and displayed using
569 `company-frontends'. If you want to start a specific back-end, call it
570 interactively or use `company-begin-backend'.
572 regular keymap (`company-mode-map'):
575 keymap during active completions (`company-active-map'):
577 \\{company-active-map}"
578 nil company-lighter company-mode-map
581 (add-hook 'pre-command-hook 'company-pre-command nil t)
582 (add-hook 'post-command-hook 'company-post-command nil t)
583 (mapc 'company-init-backend company-backends))
584 (remove-hook 'pre-command-hook 'company-pre-command t)
585 (remove-hook 'post-command-hook 'company-post-command t)
587 (kill-local-variable 'company-point)))
589 (define-globalized-minor-mode global-company-mode company-mode
590 (lambda () (company-mode 1)))
592 (defsubst company-assert-enabled ()
594 (company-uninstall-map)
595 (error "Company not enabled")))
597 ;;; keymaps ;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;
599 (defvar company-overriding-keymap-bound nil)
600 (make-variable-buffer-local 'company-overriding-keymap-bound)
602 (defvar company-old-keymap nil)
603 (make-variable-buffer-local 'company-old-keymap)
605 (defvar company-my-keymap nil)
606 (make-variable-buffer-local 'company-my-keymap)
608 (defsubst company-enable-overriding-keymap (keymap)
609 (setq company-my-keymap keymap)
610 (when company-overriding-keymap-bound
611 (company-uninstall-map)))
613 (defun company-install-map ()
614 (unless (or company-overriding-keymap-bound
615 (null company-my-keymap))
616 (setq company-old-keymap overriding-terminal-local-map
617 overriding-terminal-local-map company-my-keymap
618 company-overriding-keymap-bound t)))
620 (defun company-uninstall-map ()
621 (when (eq overriding-terminal-local-map company-my-keymap)
622 (setq overriding-terminal-local-map company-old-keymap
623 company-overriding-keymap-bound nil)))
626 ;; Emacs calculates the active keymaps before reading the event. That means we
627 ;; cannot change the keymap from a timer. So we send a bogus command.
628 (defun company-ignore ()
630 (setq this-command last-command))
632 (global-set-key '[31415926] 'company-ignore)
634 (defun company-input-noop ()
635 (push 31415926 unread-command-events))
638 ;; posn-col-row is incorrect in older Emacsen when line-spacing is set
639 (defun company--col-row (&optional pos)
640 (let ((posn (posn-at-point pos)))
641 (cons (car (posn-col-row posn)) (cdr (posn-actual-col-row posn)))))
643 (defsubst company--column (&optional pos)
644 (car (posn-col-row (posn-at-point pos))))
646 (defsubst company--row (&optional pos)
647 (cdr (posn-actual-col-row (posn-at-point pos))))
649 ;;; backends ;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;
651 (defun company-grab (regexp &optional expression limit)
652 (when (looking-back regexp limit)
653 (or (match-string-no-properties (or expression 0)) "")))
655 (defun company-grab-line (regexp &optional expression)
656 (company-grab regexp expression (point-at-bol)))
658 (defun company-grab-symbol ()
659 (if (looking-at "\\_>")
660 (buffer-substring (point) (save-excursion (skip-syntax-backward "w_")
662 (unless (and (char-after) (memq (char-syntax (char-after)) '(?w ?_)))
665 (defun company-grab-word ()
666 (if (looking-at "\\>")
667 (buffer-substring (point) (save-excursion (skip-syntax-backward "w")
669 (unless (and (char-after) (eq (char-syntax (char-after)) ?w))
672 (defun company-in-string-or-comment ()
673 (let ((ppss (syntax-ppss)))
674 (or (car (setq ppss (nthcdr 3 ppss)))
675 (car (setq ppss (cdr ppss)))
678 (if (fboundp 'locate-dominating-file)
679 (defalias 'company-locate-dominating-file 'locate-dominating-file)
680 (defun company-locate-dominating-file (file name)
682 (let ((dir (file-name-directory file))
684 (while (not (equal dir prev-dir))
685 (when (file-exists-p (expand-file-name name dir))
688 dir (file-name-directory (directory-file-name dir))))))))
690 (defun company-call-backend (&rest args)
691 (if (functionp company-backend)
692 (apply company-backend args)
693 (apply 'company--multi-backend-adapter company-backend args)))
695 (defun company--multi-backend-adapter (backends command &rest args)
698 (apply 'append (mapcar (lambda (backend) (apply backend command args))
704 (dolist (backend backends)
705 (when (setq value (apply backend command args))
708 ;;; completion mechanism ;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;
710 (defvar company-backend nil)
711 (make-variable-buffer-local 'company-backend)
713 (defvar company-prefix nil)
714 (make-variable-buffer-local 'company-prefix)
716 (defvar company-candidates nil)
717 (make-variable-buffer-local 'company-candidates)
719 (defvar company-candidates-length nil)
720 (make-variable-buffer-local 'company-candidates-length)
722 (defvar company-candidates-cache nil)
723 (make-variable-buffer-local 'company-candidates-cache)
725 (defvar company-candidates-predicate nil)
726 (make-variable-buffer-local 'company-candidates-predicate)
728 (defvar company-common nil)
729 (make-variable-buffer-local 'company-common)
731 (defvar company-selection 0)
732 (make-variable-buffer-local 'company-selection)
734 (defvar company-selection-changed nil)
735 (make-variable-buffer-local 'company-selection-changed)
737 (defvar company--explicit-action nil
738 "Non-nil, if explicit completion took place.")
739 (make-variable-buffer-local 'company--explicit-action)
741 (defvar company--point-max nil)
742 (make-variable-buffer-local 'company--point-max)
744 (defvar company-point nil)
745 (make-variable-buffer-local 'company-point)
747 (defvar company-timer nil)
749 (defvar company-added-newline nil)
750 (make-variable-buffer-local 'company-added-newline)
752 (defsubst company-strip-prefix (str)
753 (substring str (length company-prefix)))
755 (defmacro company-with-candidate-inserted (candidate &rest body)
756 "Evaluate BODY with CANDIDATE temporarily inserted.
757 This is a tool for back-ends that need candidates inserted before they
758 can retrieve meta-data for them."
760 `(let ((inhibit-modification-hooks t)
761 (inhibit-point-motion-hooks t)
762 (modified-p (buffer-modified-p)))
763 (insert (company-strip-prefix ,candidate))
766 (delete-region company-point (point)))))
768 (defun company-explicit-action-p ()
769 "Return whether explicit completion action was taken by the user."
770 (or company--explicit-action
771 company-selection-changed))
773 (defsubst company-reformat (candidate)
774 ;; company-ispell needs this, because the results are always lower-case
775 ;; It's mory efficient to fix it only when they are displayed.
776 (concat company-prefix (substring candidate (length company-prefix))))
778 (defun company--should-complete ()
779 (and (not (or buffer-read-only overriding-terminal-local-map
780 overriding-local-map))
781 ;; Check if in the middle of entering a key combination.
782 (or (equal (this-command-keys-vector) [])
783 (not (keymapp (key-binding (this-command-keys-vector)))))
784 (eq company-idle-delay t)
785 (or (eq t company-begin-commands)
786 (memq this-command company-begin-commands)
787 (and (symbolp this-command) (get this-command 'company-begin)))
788 (not (and transient-mark-mode mark-active))))
790 (defsubst company-call-frontends (command)
791 (dolist (frontend company-frontends)
793 (funcall frontend command)
794 (error (error "Company: Front-end %s error \"%s\" on command %s"
795 frontend (error-message-string err) command)))))
797 (defsubst company-set-selection (selection &optional force-update)
798 (setq selection (max 0 (min (1- company-candidates-length) selection)))
799 (when (or force-update (not (equal selection company-selection)))
800 (setq company-selection selection
801 company-selection-changed t)
802 (company-call-frontends 'update)))
804 (defun company-apply-predicate (candidates predicate)
806 (dolist (c candidates)
807 (when (funcall predicate c)
811 (defun company-update-candidates (candidates)
812 (setq company-candidates-length (length candidates))
813 (if (> company-selection 0)
814 ;; Try to restore the selection
815 (let ((selected (nth company-selection company-candidates)))
816 (setq company-selection 0
817 company-candidates candidates)
819 (while (and candidates (string< (pop candidates) selected))
820 (incf company-selection))
822 ;; Make sure selection isn't out of bounds.
823 (setq company-selection (min (1- company-candidates-length)
824 company-selection)))))
825 (setq company-selection 0
826 company-candidates candidates))
828 (push (cons company-prefix company-candidates) company-candidates-cache)
830 (let ((completion-ignore-case (company-call-backend 'ignore-case)))
831 (setq company-common (try-completion company-prefix company-candidates)))
832 (when (eq company-common t)
833 (setq company-candidates nil)))
835 (defun company-calculate-candidates (prefix)
836 (let ((candidates (cdr (assoc prefix company-candidates-cache))))
838 (when company-candidates-cache
839 (let ((len (length prefix))
840 (completion-ignore-case (company-call-backend 'ignore-case))
842 (dotimes (i (1+ len))
843 (when (setq prev (cdr (assoc (substring prefix 0 (- len i))
844 company-candidates-cache)))
845 (setq candidates (all-completions prefix prev))
847 ;; no cache match, call back-end
849 (setq candidates (company-call-backend 'candidates prefix))
850 (when company-candidates-predicate
852 (company-apply-predicate candidates
853 company-candidates-predicate)))
854 (unless (company-call-backend 'sorted)
855 (setq candidates (sort candidates 'string<)))
856 (when (company-call-backend 'duplicates)
858 (let ((c2 candidates))
860 (setcdr c2 (progn (while (equal (pop c2) (car c2)))
862 (if (or (cdr candidates)
863 (not (equal (car candidates) prefix)))
864 ;; Don't start when already completed and unique.
866 ;; Not the right place? maybe when setting?
867 (and company-candidates t))))
869 (defun company-idle-begin (buf win tick pos)
871 (eq buf (current-buffer))
872 (eq win (selected-window))
873 (eq tick (buffer-chars-modified-tick))
875 (not company-candidates)
876 (not (equal (point) company-point))
877 (let ((company-idle-delay t)
878 (company-begin-commands t))
880 (when company-candidates
882 (company-post-command)))))
884 (defun company-auto-begin ()
885 (company-assert-enabled)
887 (not company-candidates)
888 (let ((company-idle-delay t)
889 (company-minimum-prefix-length 0)
890 (company-begin-commands t))
892 ;; Return non-nil if active.
895 (defun company-manual-begin ()
897 (setq company--explicit-action t)
898 (company-auto-begin))
900 (defun company-other-backend (&optional backward)
901 (interactive (list current-prefix-arg))
902 (company-assert-enabled)
904 (let* ((after (cdr (member company-backend company-backends)))
905 (before (cdr (member company-backend (reverse company-backends))))
907 (append before (reverse after))
908 (append after (reverse before)))))
910 (dolist (backend next)
911 (when (ignore-errors (company-begin-backend backend))
913 (company-manual-begin))
914 (unless company-candidates
915 (error "No other back-end")))
917 (defun company-require-match-p ()
918 (let ((backend-value (company-call-backend 'require-match)))
919 (or (eq backend-value t)
920 (and (if (functionp company-require-match)
921 (funcall company-require-match)
922 (eq company-require-match t))
923 (not (eq backend-value 'never))))))
925 (defun company-punctuation-p (input)
926 "Return non-nil, if input starts with punctuation or parentheses."
927 (memq (char-syntax (string-to-char input)) '(?. ?\( ?\))))
929 (defun company-auto-complete-p (input)
930 "Return non-nil, if input starts with punctuation or parentheses."
931 (and (if (functionp company-auto-complete)
932 (funcall company-auto-complete)
933 company-auto-complete)
934 (if (functionp company-auto-complete-chars)
935 (funcall company-auto-complete-chars input)
936 (if (consp company-auto-complete-chars)
937 (memq (char-syntax (string-to-char input))
938 company-auto-complete-chars)
939 (string-match (substring input 0 1) company-auto-complete-chars)))))
941 (defun company--incremental-p ()
942 (and (> (point) company-point)
943 (> (point-max) company--point-max)
944 (not (eq this-command 'backward-delete-char-untabify))
945 (equal (buffer-substring (- company-point (length company-prefix))
949 (defsubst company--string-incremental-p (old-prefix new-prefix)
950 (and (> (length new-prefix) (length old-prefix))
951 (equal old-prefix (substring new-prefix 0 (length old-prefix)))))
953 (defun company--continue-failed (new-prefix)
954 (when (company--incremental-p)
955 (let ((input (buffer-substring-no-properties (point) company-point)))
957 ((company-auto-complete-p input)
960 (goto-char company-point)
961 (company-complete-selection)
963 ((and (company--string-incremental-p company-prefix new-prefix)
964 (company-require-match-p))
965 ;; wrong incremental input, but required match
966 (backward-delete-char (length input))
968 (message "Matching input is required")
970 ((equal company-prefix (car company-candidates))
971 ;; last input was actually success
972 (company-cancel company-prefix)
975 (defun company--good-prefix-p (prefix)
976 (and (or (company-explicit-action-p)
977 (>= (or (cdr-safe prefix) (length prefix))
978 company-minimum-prefix-length))
979 (stringp (or (car-safe prefix) prefix))))
981 (defun company--continue ()
982 (when (company-call-backend 'no-cache company-prefix)
983 ;; Don't complete existing candidates, fetch new ones.
984 (setq company-candidates-cache nil))
985 (let* ((new-prefix (company-call-backend 'prefix))
986 (c (when (and (company--good-prefix-p new-prefix)
987 (setq new-prefix (or (car-safe new-prefix) new-prefix))
988 (= (- (point) (length new-prefix))
989 (- company-point (length company-prefix))))
990 (setq new-prefix (or (car-safe new-prefix) new-prefix))
991 (company-calculate-candidates new-prefix))))
994 ;; t means complete/unique.
995 (company-cancel new-prefix)
999 (setq company-prefix new-prefix)
1000 (company-update-candidates c)
1002 (t (company--continue-failed new-prefix)))
1005 (defun company--begin-new ()
1007 (dolist (backend (if company-backend
1008 ;; prefer manual override
1009 (list company-backend)
1012 (if (or (symbolp backend)
1013 (functionp backend))
1014 (when (or (not (symbolp backend))
1015 (eq t (get backend 'company-init))
1016 (unless (get backend 'company-init)
1017 (company-init-backend backend)))
1018 (funcall backend 'prefix))
1019 (company--multi-backend-adapter backend 'prefix)))
1021 (when (company--good-prefix-p prefix)
1022 (setq prefix (or (car-safe prefix) prefix)
1023 company-backend backend
1024 c (company-calculate-candidates prefix))
1025 ;; t means complete/unique. We don't start, so no hooks.
1027 (when company--explicit-action
1028 (message "No completion found"))
1029 (setq company-prefix prefix)
1030 (when (symbolp backend)
1031 (setq company-lighter (concat " " (symbol-name backend))))
1032 (company-update-candidates c)
1033 (run-hook-with-args 'company-completion-started-hook
1034 (company-explicit-action-p))
1035 (company-call-frontends 'show)))
1038 (defun company-begin ()
1039 (setq company-candidates
1040 (or (and company-candidates (company--continue))
1041 (and (company--should-complete) (company--begin-new))))
1042 (when company-candidates
1043 (when (and company-end-of-buffer-workaround (eobp))
1044 (save-excursion (insert "\n"))
1045 (setq company-added-newline (buffer-chars-modified-tick)))
1046 (setq company-point (point)
1047 company--point-max (point-max))
1048 (company-enable-overriding-keymap company-active-map)
1049 (company-call-frontends 'update)))
1051 (defun company-cancel (&optional result)
1052 (and company-added-newline
1053 (> (point-max) (point-min))
1054 (let ((tick (buffer-chars-modified-tick)))
1055 (delete-region (1- (point-max)) (point-max))
1056 (equal tick company-added-newline))
1057 ;; Only set unmodified when tick remained the same since insert.
1058 (set-buffer-modified-p nil))
1059 (when company-prefix
1060 (if (stringp result)
1062 (company-call-backend 'pre-completion result)
1063 (run-hook-with-args 'company-completion-finished-hook result)
1064 (company-call-backend 'post-completion result))
1065 (run-hook-with-args 'company-completion-cancelled-hook result)))
1066 (setq company-added-newline nil
1069 company-candidates nil
1070 company-candidates-length nil
1071 company-candidates-cache nil
1072 company-candidates-predicate nil
1075 company-selection-changed nil
1076 company--explicit-action nil
1077 company-lighter company-default-lighter
1078 company--point-max nil
1081 (cancel-timer company-timer))
1082 (company-search-mode 0)
1083 (company-call-frontends 'hide)
1084 (company-enable-overriding-keymap nil))
1086 (defun company-abort ()
1089 ;; Don't start again, unless started manually.
1090 (setq company-point (point)))
1092 (defun company-finish (result)
1093 (insert (company-strip-prefix result))
1094 (company-cancel result)
1095 ;; Don't start again, unless started manually.
1096 (setq company-point (point)))
1098 (defsubst company-keep (command)
1099 (and (symbolp command) (get command 'company-keep)))
1101 (defun company-pre-command ()
1102 (unless (company-keep this-command)
1104 (when company-candidates
1105 (company-call-frontends 'pre-command))
1106 (error (message "Company: An error occurred in pre-command")
1107 (message "%s" (error-message-string err))
1110 (cancel-timer company-timer)
1111 (setq company-timer nil))
1112 (company-uninstall-map))
1114 (defun company-post-command ()
1115 (unless (company-keep this-command)
1118 (unless (equal (point) company-point)
1120 (if company-candidates
1121 (company-call-frontends 'post-command)
1122 (and (numberp company-idle-delay)
1123 (or (eq t company-begin-commands)
1124 (memq this-command company-begin-commands))
1126 (run-with-timer company-idle-delay nil
1128 (current-buffer) (selected-window)
1129 (buffer-chars-modified-tick) (point))))))
1130 (error (message "Company: An error occurred in post-command")
1131 (message "%s" (error-message-string err))
1133 (company-install-map))
1135 ;;; search ;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;
1137 (defvar company-search-string nil)
1138 (make-variable-buffer-local 'company-search-string)
1140 (defvar company-search-lighter " Search: \"\"")
1141 (make-variable-buffer-local 'company-search-lighter)
1143 (defvar company-search-old-map nil)
1144 (make-variable-buffer-local 'company-search-old-map)
1146 (defvar company-search-old-selection 0)
1147 (make-variable-buffer-local 'company-search-old-selection)
1149 (defun company-search (text lines)
1150 (let ((quoted (regexp-quote text))
1152 (dolist (line lines)
1153 (when (string-match quoted line (length company-prefix))
1157 (defun company-search-printing-char ()
1159 (company-search-assert-enabled)
1160 (setq company-search-string
1161 (concat (or company-search-string "") (string last-command-event))
1162 company-search-lighter (concat " Search: \"" company-search-string
1164 (let ((pos (company-search company-search-string
1165 (nthcdr company-selection company-candidates))))
1168 (company-set-selection (+ company-selection pos) t))))
1170 (defun company-search-repeat-forward ()
1171 "Repeat the incremental search in completion candidates forward."
1173 (company-search-assert-enabled)
1174 (let ((pos (company-search company-search-string
1175 (cdr (nthcdr company-selection
1176 company-candidates)))))
1179 (company-set-selection (+ company-selection pos 1) t))))
1181 (defun company-search-repeat-backward ()
1182 "Repeat the incremental search in completion candidates backwards."
1184 (company-search-assert-enabled)
1185 (let ((pos (company-search company-search-string
1186 (nthcdr (- company-candidates-length
1188 (reverse company-candidates)))))
1191 (company-set-selection (- company-selection pos 1) t))))
1193 (defun company-create-match-predicate ()
1194 (setq company-candidates-predicate
1195 `(lambda (candidate)
1196 ,(if company-candidates-predicate
1197 `(and (string-match ,company-search-string candidate)
1198 (funcall ,company-candidates-predicate
1200 `(string-match ,company-search-string candidate))))
1201 (company-update-candidates
1202 (company-apply-predicate company-candidates company-candidates-predicate))
1203 ;; Invalidate cache.
1204 (setq company-candidates-cache (cons company-prefix company-candidates)))
1206 (defun company-filter-printing-char ()
1208 (company-search-assert-enabled)
1209 (company-search-printing-char)
1210 (company-create-match-predicate)
1211 (company-call-frontends 'update))
1213 (defun company-search-kill-others ()
1214 "Limit the completion candidates to the ones matching the search string."
1216 (company-search-assert-enabled)
1217 (company-create-match-predicate)
1218 (company-search-mode 0)
1219 (company-call-frontends 'update))
1221 (defun company-search-abort ()
1222 "Abort searching the completion candidates."
1224 (company-search-assert-enabled)
1225 (company-set-selection company-search-old-selection t)
1226 (company-search-mode 0))
1228 (defun company-search-other-char ()
1230 (company-search-assert-enabled)
1231 (company-search-mode 0)
1232 (when last-input-event
1233 (clear-this-command-keys t)
1234 (setq unread-command-events (list last-input-event))))
1236 (defvar company-search-map
1238 (keymap (make-keymap)))
1239 (if (fboundp 'max-char)
1240 (set-char-table-range (nth 1 keymap) (cons #x100 (max-char))
1241 'company-search-printing-char)
1243 ;; obselete in Emacs 23
1244 (let ((l (generic-character-list))
1245 (table (nth 1 keymap)))
1247 (set-char-table-default table (car l) 'company-search-printing-char)
1248 (setq l (cdr l))))))
1249 (define-key keymap [t] 'company-search-other-char)
1251 (define-key keymap (make-string 1 i) 'company-search-other-char)
1254 (define-key keymap (vector i) 'company-search-printing-char)
1256 (let ((meta-map (make-sparse-keymap)))
1257 (define-key keymap (char-to-string meta-prefix-char) meta-map)
1258 (define-key keymap [escape] meta-map))
1259 (define-key keymap (vector meta-prefix-char t) 'company-search-other-char)
1260 (define-key keymap "\e\e\e" 'company-search-other-char)
1261 (define-key keymap [escape escape escape] 'company-search-other-char)
1263 (define-key keymap "\C-g" 'company-search-abort)
1264 (define-key keymap "\C-s" 'company-search-repeat-forward)
1265 (define-key keymap "\C-r" 'company-search-repeat-backward)
1266 (define-key keymap "\C-o" 'company-search-kill-others)
1268 "Keymap used for incrementally searching the completion candidates.")
1270 (define-minor-mode company-search-mode
1271 "Search mode for completion candidates.
1272 Don't start this directly, use `company-search-candidates' or
1273 `company-filter-candidates'."
1274 nil company-search-lighter nil
1275 (if company-search-mode
1276 (if (company-manual-begin)
1278 (setq company-search-old-selection company-selection)
1279 (company-call-frontends 'update))
1280 (setq company-search-mode nil))
1281 (kill-local-variable 'company-search-string)
1282 (kill-local-variable 'company-search-lighter)
1283 (kill-local-variable 'company-search-old-selection)
1284 (company-enable-overriding-keymap company-active-map)))
1286 (defsubst company-search-assert-enabled ()
1287 (company-assert-enabled)
1288 (unless company-search-mode
1289 (company-uninstall-map)
1290 (error "Company not in search mode")))
1292 (defun company-search-candidates ()
1293 "Start searching the completion candidates incrementally.
1295 \\<company-search-map>Search can be controlled with the commands:
1296 - `company-search-repeat-forward' (\\[company-search-repeat-forward])
1297 - `company-search-repeat-backward' (\\[company-search-repeat-backward])
1298 - `company-search-abort' (\\[company-search-abort])
1300 Regular characters are appended to the search string.
1302 The command `company-search-kill-others' (\\[company-search-kill-others]) uses
1303 the search string to limit the completion candidates."
1305 (company-search-mode 1)
1306 (company-enable-overriding-keymap company-search-map))
1308 (defvar company-filter-map
1309 (let ((keymap (make-keymap)))
1310 (define-key keymap [remap company-search-printing-char]
1311 'company-filter-printing-char)
1312 (set-keymap-parent keymap company-search-map)
1314 "Keymap used for incrementally searching the completion candidates.")
1316 (defun company-filter-candidates ()
1317 "Start filtering the completion candidates incrementally.
1318 This works the same way as `company-search-candidates' immediately
1319 followed by `company-search-kill-others' after each input."
1321 (company-search-mode 1)
1322 (company-enable-overriding-keymap company-filter-map))
1324 ;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;
1326 (defun company-select-next ()
1327 "Select the next candidate in the list."
1329 (when (company-manual-begin)
1330 (company-set-selection (1+ company-selection))))
1332 (defun company-select-previous ()
1333 "Select the previous candidate in the list."
1335 (when (company-manual-begin)
1336 (company-set-selection (1- company-selection))))
1338 (defun company-select-mouse (event)
1339 "Select the candidate picked by the mouse."
1341 (when (nth 4 (event-start event))
1342 (company-set-selection (- (cdr (posn-actual-col-row (event-start event)))
1347 (defun company-complete-mouse (event)
1348 "Complete the candidate picked by the mouse."
1350 (when (company-select-mouse event)
1351 (company-complete-selection)))
1353 (defun company-complete-selection ()
1354 "Complete the selected candidate."
1356 (when (company-manual-begin)
1357 (company-finish (nth company-selection company-candidates))))
1359 (defun company-complete-common ()
1360 "Complete the common part of all candidates."
1362 (when (company-manual-begin)
1363 (if (and (not (cdr company-candidates))
1364 (equal company-common (car company-candidates)))
1365 (company-complete-selection)
1366 (insert (company-strip-prefix company-common)))))
1368 (defun company-complete ()
1369 "Complete the common part of all candidates or the current selection.
1370 The first time this is called, the common part is completed, the second time, or
1371 when the selection has been changed, the selected candidate is completed."
1373 (when (company-manual-begin)
1374 (if (or company-selection-changed
1375 (eq last-command 'company-complete-common))
1376 (call-interactively 'company-complete-selection)
1377 (call-interactively 'company-complete-common)
1378 (setq this-command 'company-complete-common))))
1380 (defun company-complete-number (n)
1381 "Complete the Nth candidate.
1382 To show the number next to the candidates in some back-ends, enable
1383 `company-show-numbers'."
1384 (when (company-manual-begin)
1385 (and (< n 1) (> n company-candidates-length)
1386 (error "No candidate number %d" n))
1388 (company-finish (nth n company-candidates))))
1390 ;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;
1392 (defconst company-space-strings-limit 100)
1394 (defconst company-space-strings
1396 (dotimes (i company-space-strings-limit)
1397 (push (make-string (- company-space-strings-limit 1 i) ?\ ) lst))
1398 (apply 'vector lst)))
1400 (defsubst company-space-string (len)
1401 (if (< len company-space-strings-limit)
1402 (aref company-space-strings len)
1403 (make-string len ?\ )))
1405 (defsubst company-safe-substring (str from &optional to)
1406 (let ((len (length str)))
1409 (if (and to (> to len))
1410 (concat (substring str from)
1411 (company-space-string (- to len)))
1412 (substring str from to)))))
1414 ;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;
1416 (defvar company-last-metadata nil)
1417 (make-variable-buffer-local 'company-last-metadata)
1419 (defun company-fetch-metadata ()
1420 (let ((selected (nth company-selection company-candidates)))
1421 (unless (equal selected (car company-last-metadata))
1422 (setq company-last-metadata
1423 (cons selected (company-call-backend 'meta selected))))
1424 (cdr company-last-metadata)))
1426 (defun company-doc-buffer (&optional string)
1427 (with-current-buffer (get-buffer-create "*Company meta-data*")
1431 (defvar company--electric-commands
1432 '(scroll-other-window scroll-other-window-down)
1433 "List of Commands that won't break out of electric commands.")
1435 (defmacro company--electric-do (&rest body)
1436 (declare (indent 0) (debug t))
1437 `(when (company-manual-begin)
1438 (save-window-excursion
1439 (let ((height (window-height))
1440 (row (company--row))
1443 (and (< (window-height) height)
1444 (< (- (window-height) row 2) company-tooltip-limit)
1445 (recenter (- (window-height) row 2)))
1446 (while (memq (setq cmd (key-binding (vector (list (read-event)))))
1447 company--electric-commands)
1448 (call-interactively cmd))
1449 (when last-input-event
1450 (clear-this-command-keys t)
1451 (setq unread-command-events (list last-input-event)))))))
1453 (defun company-show-doc-buffer ()
1454 "Temporarily show a buffer with the complete documentation for the selection."
1456 (company--electric-do
1457 (let* ((selected (nth company-selection company-candidates))
1458 (doc-buffer (or (company-call-backend 'doc-buffer selected)
1459 (error "No documentation available"))))
1460 (with-current-buffer doc-buffer
1461 (goto-char (point-min)))
1462 (display-buffer doc-buffer t))))
1463 (put 'company-show-doc-buffer 'company-keep t)
1465 (defun company-show-location ()
1466 "Temporarily display a buffer showing the selected candidate in context."
1468 (company--electric-do
1469 (let* ((selected (nth company-selection company-candidates))
1470 (location (company-call-backend 'location selected))
1471 (pos (or (cdr location) (error "No location available")))
1472 (buffer (or (and (bufferp (car location)) (car location))
1473 (find-file-noselect (car location) t))))
1474 (with-selected-window (display-buffer buffer t)
1477 (if (bufferp (car location))
1479 (goto-char (point-min))
1480 (forward-line (1- pos))))
1481 (set-window-start nil (point))))))
1482 (put 'company-show-location 'company-keep t)
1484 ;;; package functions ;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;
1486 (defvar company-callback nil)
1487 (make-variable-buffer-local 'company-callback)
1489 (defvar company-begin-with-marker nil)
1490 (make-variable-buffer-local 'company-begin-with-marker)
1492 (defun company-remove-callback (&optional ignored)
1493 (remove-hook 'company-completion-finished-hook company-callback t)
1494 (remove-hook 'company-completion-cancelled-hook 'company-remove-callback t)
1495 (remove-hook 'company-completion-finished-hook 'company-remove-callback t)
1496 (when company-begin-with-marker
1497 (set-marker company-begin-with-marker nil)))
1499 (defun company-begin-backend (backend &optional callback)
1500 "Start a completion at point using BACKEND."
1501 (interactive (let ((val (completing-read "Company back-end: "
1503 'functionp nil "company-")))
1505 (list (intern val)))))
1506 (when (setq company-callback callback)
1507 (add-hook 'company-completion-finished-hook company-callback nil t))
1508 (add-hook 'company-completion-cancelled-hook 'company-remove-callback nil t)
1509 (add-hook 'company-completion-finished-hook 'company-remove-callback nil t)
1510 (setq company-backend backend)
1511 ;; Return non-nil if active.
1512 (or (company-manual-begin)
1513 (error "Cannot complete at point")))
1515 (defun company-begin-with (candidates
1516 &optional prefix-length require-match callback)
1517 "Start a completion at point.
1518 CANDIDATES is the list of candidates to use and PREFIX-LENGTH is the length of
1519 the prefix that already is in the buffer before point. It defaults to 0.
1521 CALLBACK is a function called with the selected result if the user successfully
1522 completes the input.
1525 \(company-begin-with '\(\"foo\" \"foobar\" \"foobarbaz\"\)\)"
1526 (setq company-begin-with-marker (copy-marker (point) t))
1527 (company-begin-backend
1528 `(lambda (command &optional arg &rest ignored)
1530 ((eq command 'prefix)
1531 (when (equal (point) (marker-position company-begin-with-marker))
1532 (buffer-substring ,(- (point) (or prefix-length 0)) (point))))
1533 ((eq command 'candidates)
1534 (all-completions arg ',candidates))
1535 ((eq command 'require-match)
1539 ;;; pseudo-tooltip ;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;
1541 (defvar company-pseudo-tooltip-overlay nil)
1542 (make-variable-buffer-local 'company-pseudo-tooltip-overlay)
1544 (defvar company-tooltip-offset 0)
1545 (make-variable-buffer-local 'company-tooltip-offset)
1547 (defun company-pseudo-tooltip-update-offset (selection num-lines limit)
1550 (setq company-tooltip-offset
1551 (max (min selection company-tooltip-offset)
1552 (- selection -1 limit)))
1554 (when (<= company-tooltip-offset 1)
1556 (setq company-tooltip-offset 0))
1558 (when (>= company-tooltip-offset (- num-lines limit 1))
1560 (when (= selection (1- num-lines))
1561 (decf company-tooltip-offset)
1562 (when (<= company-tooltip-offset 1)
1563 (setq company-tooltip-offset 0)
1570 (defsubst company-round-tab (arg)
1571 (* (/ (+ arg tab-width) tab-width) tab-width))
1573 (defun company-untabify (str)
1574 (let* ((pieces (split-string str "\t"))
1577 (setcar copy (company-safe-substring
1578 (car copy) 0 (company-round-tab (string-width (car copy)))))
1580 (apply 'concat pieces)))
1582 (defun company-fill-propertize (line width selected)
1583 (setq line (company-safe-substring line 0 width))
1584 (add-text-properties 0 width '(face company-tooltip
1585 mouse-face company-tooltip-mouse)
1587 (add-text-properties 0 (length company-common)
1588 '(face company-tooltip-common
1589 mouse-face company-tooltip-mouse)
1592 (if (and company-search-string
1593 (string-match (regexp-quote company-search-string) line
1594 (length company-prefix)))
1596 (add-text-properties (match-beginning 0) (match-end 0)
1597 '(face company-tooltip-selection)
1599 (when (< (match-beginning 0) (length company-common))
1600 (add-text-properties (match-beginning 0) (length company-common)
1601 '(face company-tooltip-common-selection)
1603 (add-text-properties 0 width '(face company-tooltip-selection
1604 mouse-face company-tooltip-selection)
1606 (add-text-properties 0 (length company-common)
1607 '(face company-tooltip-common-selection
1608 mouse-face company-tooltip-selection)
1614 (defun company-buffer-lines (beg end)
1616 (let ((row (company--row))
1618 (while (and (equal (move-to-window-line (incf row)) row)
1620 (push (buffer-substring beg (min end (1- (point)))) lines)
1622 (unless (eq beg end)
1623 (push (buffer-substring beg end) lines))
1626 (defsubst company-modify-line (old new offset)
1627 (concat (company-safe-substring old 0 offset)
1629 (company-safe-substring old (+ offset (length new)))))
1631 (defsubst company--length-limit (lst limit)
1632 (if (nthcdr limit lst)
1636 (defun company--replacement-string (lines old column nl &optional align-top)
1638 (let ((width (length (car lines))))
1639 (when (> width (- (window-width) column))
1640 (setq column (max 0 (- (window-width) width)))))
1644 ;; untouched lines first
1645 (dotimes (i (- (length old) (length lines)))
1646 (push (pop old) new)))
1647 ;; length into old lines.
1649 (push (company-modify-line (pop old) (pop lines) column) new))
1650 ;; Append whole new lines.
1652 (push (concat (company-space-string column) (pop lines)) new))
1653 (concat (when nl "\n")
1654 (mapconcat 'identity (nreverse new) "\n")
1657 (defun company--create-lines (selection limit)
1659 (let ((len company-candidates-length)
1668 ;; Scroll to offset.
1669 (setq limit (company-pseudo-tooltip-update-offset selection len limit))
1671 (when (> company-tooltip-offset 0)
1672 (setq previous (format "...(%d)" company-tooltip-offset)))
1674 (setq remainder (- len limit company-tooltip-offset)
1675 remainder (when (> remainder 0)
1676 (setq remainder (format "...(%d)" remainder))))
1678 (decf selection company-tooltip-offset)
1679 (setq width (max (length previous) (length remainder))
1680 lines (nthcdr company-tooltip-offset company-candidates)
1685 (setq width (max (length (pop lines-copy)) width)))
1686 (setq width (min width (window-width)))
1688 (setq lines-copy lines)
1690 ;; number can make tooltip too long
1691 (when company-show-numbers
1692 (setq numbered company-tooltip-offset))
1695 (push (propertize (company-safe-substring previous 0 width)
1696 'face 'company-tooltip)
1700 (push (company-fill-propertize
1701 (if (>= numbered 10)
1702 (company-reformat (pop lines))
1705 (company-safe-substring (company-reformat (pop lines))
1708 width (equal i selection))
1712 (push (propertize (company-safe-substring remainder 0 width)
1713 'face 'company-tooltip)
1716 (setq lines (nreverse new))))
1720 (defsubst company--window-inner-height ()
1721 (let ((edges (window-inside-edges (selected-window))))
1722 (- (nth 3 edges) (nth 1 edges))))
1724 (defsubst company--pseudo-tooltip-height ()
1725 "Calculate the appropriate tooltip height.
1726 Returns a negative number if the tooltip should be displayed above point."
1727 (let* ((lines (count-lines (window-start) (point-at-bol)))
1728 (below (- (company--window-inner-height) 1 lines)))
1729 (if (and (< below (min company-tooltip-minimum company-candidates-length))
1731 (- (max 3 (min company-tooltip-limit lines)))
1732 (max 3 (min company-tooltip-limit below)))))
1734 (defun company-pseudo-tooltip-show (row column selection)
1735 (company-pseudo-tooltip-hide)
1740 (let* ((height (company--pseudo-tooltip-height))
1744 (setq row (+ row height -1)
1747 (let* ((nl (< (move-to-window-line row) row))
1749 (end (save-excursion
1750 (move-to-window-line (+ row (abs height)))
1752 (ov (make-overlay beg end))
1753 (args (list (mapcar 'company-untabify
1754 (company-buffer-lines beg end))
1757 (setq company-pseudo-tooltip-overlay ov)
1758 (overlay-put ov 'company-replacement-args args)
1759 (overlay-put ov 'company-before
1760 (apply 'company--replacement-string
1761 (company--create-lines selection (abs height))
1764 (overlay-put ov 'company-column column)
1765 (overlay-put ov 'company-height (abs height))
1766 (overlay-put ov 'window (selected-window))))))
1768 (defun company-pseudo-tooltip-show-at-point (pos)
1769 (let ((col-row (company--col-row pos)))
1771 (company-pseudo-tooltip-show (1+ (cdr col-row)) (car col-row)
1772 company-selection))))
1774 (defun company-pseudo-tooltip-edit (lines selection)
1775 (let ((column (overlay-get company-pseudo-tooltip-overlay 'company-column))
1776 (height (overlay-get company-pseudo-tooltip-overlay 'company-height)))
1777 (overlay-put company-pseudo-tooltip-overlay 'company-before
1778 (apply 'company--replacement-string
1779 (company--create-lines selection height)
1780 (overlay-get company-pseudo-tooltip-overlay
1781 'company-replacement-args)))))
1783 (defun company-pseudo-tooltip-hide ()
1784 (when company-pseudo-tooltip-overlay
1785 (delete-overlay company-pseudo-tooltip-overlay)
1786 (setq company-pseudo-tooltip-overlay nil)))
1788 (defun company-pseudo-tooltip-hide-temporarily ()
1789 (when (overlayp company-pseudo-tooltip-overlay)
1790 (overlay-put company-pseudo-tooltip-overlay 'invisible nil)
1791 (overlay-put company-pseudo-tooltip-overlay 'before-string nil)))
1793 (defun company-pseudo-tooltip-unhide ()
1794 (when company-pseudo-tooltip-overlay
1795 (overlay-put company-pseudo-tooltip-overlay 'invisible t)
1796 (overlay-put company-pseudo-tooltip-overlay 'before-string
1797 (overlay-get company-pseudo-tooltip-overlay 'company-before))
1798 (overlay-put company-pseudo-tooltip-overlay 'window (selected-window))))
1800 (defun company-pseudo-tooltip-frontend (command)
1801 "A `company-mode' front-end similar to a tool-tip but based on overlays."
1803 ('pre-command (company-pseudo-tooltip-hide-temporarily))
1805 (let ((old-height (if (overlayp company-pseudo-tooltip-overlay)
1806 (overlay-get company-pseudo-tooltip-overlay
1809 (new-height (company--pseudo-tooltip-height)))
1810 (unless (and (>= (* old-height new-height) 0)
1811 (>= (abs old-height) (abs new-height)))
1813 (company-pseudo-tooltip-show-at-point (- (point)
1814 (length company-prefix)))))
1815 (company-pseudo-tooltip-unhide))
1816 ('hide (company-pseudo-tooltip-hide)
1817 (setq company-tooltip-offset 0))
1818 ('update (when (overlayp company-pseudo-tooltip-overlay)
1819 (company-pseudo-tooltip-edit company-candidates
1820 company-selection)))))
1822 (defun company-pseudo-tooltip-unless-just-one-frontend (command)
1823 "`company-pseudo-tooltip-frontend', but not shown for single candidates."
1824 (unless (and (eq command 'post-command)
1825 (not (cdr company-candidates)))
1826 (company-pseudo-tooltip-frontend command)))
1828 ;;; overlay ;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;
1830 (defvar company-preview-overlay nil)
1831 (make-variable-buffer-local 'company-preview-overlay)
1833 (defun company-preview-show-at-point (pos)
1834 (company-preview-hide)
1836 (setq company-preview-overlay (make-overlay pos pos))
1838 (let ((completion(nth company-selection company-candidates)))
1839 (setq completion (propertize completion 'face 'company-preview))
1840 (add-text-properties 0 (length company-common)
1841 '(face company-preview-common) completion)
1843 ;; Add search string
1844 (and company-search-string
1845 (string-match (regexp-quote company-search-string) completion)
1846 (add-text-properties (match-beginning 0)
1848 '(face company-preview-search)
1851 (setq completion (company-strip-prefix completion))
1853 (and (equal pos (point))
1854 (not (equal completion ""))
1855 (add-text-properties 0 1 '(cursor t) completion))
1857 (overlay-put company-preview-overlay 'after-string completion)
1858 (overlay-put company-preview-overlay 'window (selected-window))))
1860 (defun company-preview-hide ()
1861 (when company-preview-overlay
1862 (delete-overlay company-preview-overlay)
1863 (setq company-preview-overlay nil)))
1865 (defun company-preview-frontend (command)
1866 "A `company-mode' front-end showing the selection as if it had been inserted."
1868 ('pre-command (company-preview-hide))
1869 ('post-command (company-preview-show-at-point (point)))
1870 ('hide (company-preview-hide))))
1872 (defun company-preview-if-just-one-frontend (command)
1873 "`company-preview-frontend', but only shown for single candidates."
1874 (unless (and (eq command 'post-command)
1875 (cdr company-candidates))
1876 (company-preview-frontend command)))
1878 ;;; echo ;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;
1880 (defvar company-echo-last-msg nil)
1881 (make-variable-buffer-local 'company-echo-last-msg)
1883 (defvar company-echo-timer nil)
1885 (defvar company-echo-delay .01)
1887 (defun company-echo-show (&optional getter)
1889 (setq company-echo-last-msg (funcall getter)))
1890 (let ((message-log-max nil))
1891 (if company-echo-last-msg
1892 (message "%s" company-echo-last-msg)
1895 (defsubst company-echo-show-soon (&optional getter)
1896 (when company-echo-timer
1897 (cancel-timer company-echo-timer))
1898 (setq company-echo-timer (run-with-timer company-echo-delay nil
1899 'company-echo-show getter)))
1901 (defun company-echo-format ()
1903 (let ((limit (window-width (minibuffer-window)))
1905 ;; Roll to selection.
1906 (candidates (nthcdr company-selection company-candidates))
1907 (i (if company-show-numbers company-selection 99999))
1911 (setq comp (company-reformat (pop candidates))
1912 len (+ len 1 (length comp)))
1916 (setq comp (propertize (format "%d: %s" i comp)
1917 'face 'company-echo))
1920 (add-text-properties 3 (+ 3 (length company-common))
1921 '(face company-echo-common) comp))
1922 (setq comp (propertize comp 'face 'company-echo))
1923 (add-text-properties 0 (length company-common)
1924 '(face company-echo-common) comp))
1926 (setq candidates nil)
1929 (mapconcat 'identity (nreverse msg) " ")))
1931 (defun company-echo-strip-common-format ()
1933 (let ((limit (window-width (minibuffer-window)))
1934 (len (+ (length company-prefix) 2))
1935 ;; Roll to selection.
1936 (candidates (nthcdr company-selection company-candidates))
1937 (i (if company-show-numbers company-selection 99999))
1941 (setq comp (company-strip-prefix (pop candidates))
1942 len (+ len 2 (length comp)))
1945 (setq comp (format "%s (%d)" comp i))
1949 (setq candidates nil)
1950 (push (propertize comp 'face 'company-echo) msg)))
1952 (concat (propertize company-prefix 'face 'company-echo-common) "{"
1953 (mapconcat 'identity (nreverse msg) ", ")
1956 (defun company-echo-hide ()
1957 (when company-echo-timer
1958 (cancel-timer company-echo-timer))
1959 (unless (equal company-echo-last-msg "")
1960 (setq company-echo-last-msg "")
1961 (company-echo-show)))
1963 (defun company-echo-frontend (command)
1964 "A `company-mode' front-end showing the candidates in the echo area."
1966 ('pre-command (company-echo-show-soon))
1967 ('post-command (company-echo-show-soon 'company-echo-format))
1968 ('hide (company-echo-hide))))
1970 (defun company-echo-strip-common-frontend (command)
1971 "A `company-mode' front-end showing the candidates in the echo area."
1973 ('pre-command (company-echo-show-soon))
1974 ('post-command (company-echo-show-soon 'company-echo-strip-common-format))
1975 ('hide (company-echo-hide))))
1977 (defun company-echo-metadata-frontend (command)
1978 "A `company-mode' front-end showing the documentation in the echo area."
1980 ('pre-command (company-echo-show-soon))
1981 ('post-command (company-echo-show-soon 'company-fetch-metadata))
1982 ('hide (company-echo-hide))))
1984 ;; templates ;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;
1986 (autoload 'company-template-declare-template "company-template")
1989 ;;; company.el ends here