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'.
68 ;; Switching tags now works correctly in `company-etags'.
71 ;; `company-ropemacs' now provides location and docs. (Fernando H. Silva)
72 ;; Added `company-with-candidate-inserted' macro.
73 ;; Added `company-clang' back-end.
74 ;; Added new mechanism for non-consecutive insertion.
75 ;; (So far only used by clang for ObjC.)
76 ;; The semantic back-end now shows meta information for local symbols.
77 ;; Added compatibility for CEDET in Emacs 23.2 and from CVS. (Oleg Andreev)
80 ;; Added `company-other-backend'.
81 ;; Idle completion no longer interrupts multi-key command input.
82 ;; Added `company-ropemacs' and `company-pysmell' back-ends.
85 ;; In C modes . and -> now count towards `company-minimum-prefix-length'.
86 ;; Reverted default front-end back to `company-preview-if-just-one-frontend'.
87 ;; The pseudo tooltip will no longer be clipped at the right window edge.
88 ;; Added `company-tooltip-minimum'.
89 ;; Windows compatibility fixes.
92 ;; Added `global-company-mode'.
93 ;; Performance enhancements.
94 ;; Added `company-eclim' back-end.
95 ;; Added safer workaround for Emacs `posn-col-row' bug.
98 ;; Automatic completion is now aborted if the prefix gets too short.
99 ;; Added option `company-dabbrev-time-limit'.
100 ;; `company-backends' now supports merging back-ends.
101 ;; Added back-end `company-dabbrev-code' for generic code.
102 ;; Fixed `company-begin-with'.
104 ;; 2009-04-15 (0.3.1)
105 ;; Added 'stop prefix to prevent dabbrev from completing inside of symbols.
106 ;; Fixed issues with tabbar-mode and line-spacing.
107 ;; Performance enhancements.
110 ;; Added `company-begin-commands' option.
111 ;; Added abbrev, tempo and Xcode back-ends.
112 ;; Back-ends are now interactive. You can start them with M-x backend-name.
113 ;; Added `company-begin-with' for starting company from elisp-code.
115 ;; Added `company-require-match' and `company-auto-complete' options.
117 ;; 2009-04-05 (0.2.1)
118 ;; Improved Emacs Lisp back-end behavior for local variables.
119 ;; Added `company-elisp-detect-function-context' option.
120 ;; The mouse can now be used for selection.
123 ;; Added `company-show-location'.
124 ;; Added etags back-end.
125 ;; Added work-around for end-of-buffer bug.
126 ;; Added `company-filter-candidates'.
127 ;; More local Lisp variables are now included in the candidates.
129 ;; 2009-03-21 (0.1.5)
130 ;; Fixed elisp documentation buffer always showing the same doc.
131 ;; Added `company-echo-strip-common-frontend'.
132 ;; Added `company-show-numbers' option and M-0 ... M-9 default bindings.
133 ;; Don't hide the echo message if it isn't shown.
140 (eval-when-compile (require 'cl))
142 (add-to-list 'debug-ignored-errors "^.* frontend cannot be used twice$")
143 (add-to-list 'debug-ignored-errors "^Echo area cannot be used twice$")
144 (add-to-list 'debug-ignored-errors "^No \\(document\\|loc\\)ation available$")
145 (add-to-list 'debug-ignored-errors "^Company not ")
146 (add-to-list 'debug-ignored-errors "^No candidate number ")
147 (add-to-list 'debug-ignored-errors "^Cannot complete at point$")
148 (add-to-list 'debug-ignored-errors "^No other back-end$")
150 (defgroup company nil
151 "Extensible inline text completion mechanism"
156 (defface company-tooltip
157 '((t :background "yellow"
158 :foreground "black"))
159 "*Face used for the tool tip."
162 (defface company-tooltip-selection
163 '((default :inherit company-tooltip)
164 (((class color) (min-colors 88)) (:background "orange1"))
165 (t (:background "green")))
166 "*Face used for the selection in the tool tip."
169 (defface company-tooltip-mouse
170 '((default :inherit highlight))
171 "*Face used for the tool tip item under the mouse."
174 (defface company-tooltip-common
175 '((t :inherit company-tooltip
177 "*Face used for the common completion in the tool tip."
180 (defface company-tooltip-common-selection
181 '((t :inherit company-tooltip-selection
183 "*Face used for the selected common completion in the tool tip."
186 (defface company-preview
187 '((t :background "blue4"
188 :foreground "wheat"))
189 "*Face used for the completion preview."
192 (defface company-preview-common
193 '((t :inherit company-preview
195 "*Face used for the common part of the completion preview."
198 (defface company-preview-search
199 '((t :inherit company-preview
200 :background "blue1"))
201 "*Face used for the search string in the completion preview."
204 (defface company-echo nil
205 "*Face used for completions in the echo area."
208 (defface company-echo-common
209 '((((background dark)) (:foreground "firebrick1"))
210 (((background light)) (:background "firebrick4")))
211 "*Face used for the common part of completions in the echo area."
214 (defun company-frontends-set (variable value)
216 (let ((remainder value))
217 (setcdr remainder (delq (car remainder) (cdr remainder))))
218 (and (memq 'company-pseudo-tooltip-unless-just-one-frontend value)
219 (memq 'company-pseudo-tooltip-frontend value)
220 (error "Pseudo tooltip frontend cannot be used twice"))
221 (and (memq 'company-preview-if-just-one-frontend value)
222 (memq 'company-preview-frontend value)
223 (error "Preview frontend cannot be used twice"))
224 (and (memq 'company-echo value)
225 (memq 'company-echo-metadata-frontend value)
226 (error "Echo area cannot be used twice"))
227 ;; preview must come last
228 (dolist (f '(company-preview-if-just-one-frontend company-preview-frontend))
230 (setq value (append (delq f value) (list f)))))
231 (set variable value))
233 (defcustom company-frontends '(company-pseudo-tooltip-unless-just-one-frontend
234 company-preview-if-just-one-frontend
235 company-echo-metadata-frontend)
236 "*The list of active front-ends (visualizations).
237 Each front-end is a function that takes one argument. It is called with
238 one of the following arguments:
240 'show: When the visualization should start.
242 'hide: When the visualization should end.
244 'update: When the data has been updated.
246 'pre-command: Before every command that is executed while the
247 visualization is active.
249 'post-command: After every command that is executed while the
250 visualization is active.
252 The visualized data is stored in `company-prefix', `company-candidates',
253 `company-common', `company-selection', `company-point' and
254 `company-search-string'."
255 :set 'company-frontends-set
257 :type '(repeat (choice (const :tag "echo" company-echo-frontend)
258 (const :tag "echo, strip common"
259 company-echo-strip-common-frontend)
260 (const :tag "show echo meta-data in echo"
261 company-echo-metadata-frontend)
262 (const :tag "pseudo tooltip"
263 company-pseudo-tooltip-frontend)
264 (const :tag "pseudo tooltip, multiple only"
265 company-pseudo-tooltip-unless-just-one-frontend)
266 (const :tag "preview" company-preview-frontend)
267 (const :tag "preview, unique only"
268 company-preview-if-just-one-frontend)
269 (function :tag "custom function" nil))))
271 (defcustom company-tooltip-limit 10
272 "*The maximum number of candidates in the tool tip"
276 (defcustom company-tooltip-minimum 6
277 "*The minimum height of the tool tip.
278 If this many lines are not available, prefer to display the tooltip above."
282 (defvar company-safe-backends
283 '((company-abbrev . "Abbrev")
284 (company-clang . "clang")
285 (company-css . "CSS")
286 (company-dabbrev . "dabbrev for plain text")
287 (company-dabbrev-code . "dabbrev for code")
288 (company-eclim . "eclim (an Eclipse interace)")
289 (company-elisp . "Emacs Lisp")
290 (company-etags . "etags")
291 (company-files . "Files")
292 (company-gtags . "GNU Global")
293 (company-ispell . "ispell")
294 (company-keywords . "Programming language keywords")
295 (company-nxml . "nxml")
296 (company-oddmuse . "Oddmuse")
297 (company-pysmell . "PySmell")
298 (company-ropemacs . "ropemacs")
299 (company-semantic . "CEDET Semantic")
300 (company-tempo . "Tempo templates")
301 (company-xcode . "Xcode")))
302 (put 'company-safe-backends 'risky-local-variable t)
304 (defun company-safe-backends-p (backends)
305 (and (consp backends)
306 (not (dolist (backend backends)
307 (unless (if (consp backend)
308 (company-safe-backends-p backend)
309 (assq backend company-safe-backends))
312 (defcustom company-backends '(company-elisp company-nxml company-css
313 company-eclim company-semantic company-clang
314 company-xcode company-ropemacs
315 (company-gtags company-etags company-dabbrev-code
316 company-pysmell company-keywords)
317 company-oddmuse company-files company-dabbrev)
318 "*The list of active back-ends (completion engines).
319 Each list elements can itself be a list of back-ends. In that case their
320 completions are merged. Otherwise only the first matching back-end returns
323 `company-begin-backend' can be used to start a specific back-end,
324 `company-other-backend' will skip to the next matching back-end in the list.
326 Each back-end is a function that takes a variable number of arguments.
327 The first argument is the command requested from the back-end. It is one
330 'prefix: The back-end should return the text to be completed. It must be
331 text immediately before `point'. Returning nil passes control to the next
332 back-end. The function should return 'stop if it should complete but cannot
333 \(e.g. if it is in the middle of a string\). If the returned value is only
334 part of the prefix (e.g. the part after \"->\" in C), the back-end may return a
335 cons of prefix and prefix length, which is then used in the
336 `company-minimum-prefix-length' test.
338 'candidates: The second argument is the prefix to be completed. The
339 return value should be a list of candidates that start with the prefix.
343 'sorted: The back-end may return t here to indicate that the candidates
344 are sorted and will not need to be sorted again.
346 'duplicates: If non-nil, company will take care of removing duplicates
349 'no-cache: Usually company doesn't ask for candidates again as completion
350 progresses, unless the back-end returns t for this command. The second
351 argument is the latest prefix.
353 'meta: The second argument is a completion candidate. The back-end should
354 return a (short) documentation string for it.
356 'doc-buffer: The second argument is a completion candidate. The back-end should
357 create a buffer (preferably with `company-doc-buffer'), fill it with
358 documentation and return it.
360 'location: The second argument is a completion candidate. The back-end can
361 return the cons of buffer and buffer location, or of file and line
362 number where the completion candidate was defined.
364 'require-match: If this value is t, the user is not allowed to enter anything
365 not offering as a candidate. Use with care! The default value nil gives the
366 user that choice with `company-require-match'. Return value 'never overrides
367 that option the other way around.
369 The back-end should return nil for all commands it does not support or
370 does not know about. It should also be callable interactively and use
371 `company-begin-backend' to start itself in that case."
376 ,@(mapcar (lambda (b) `(const :tag ,(cdr b) ,(car b)))
377 company-safe-backends)
378 (symbol :tag "User defined")
379 (repeat :tag "Merged Back-ends"
380 (choice :tag "Back-end"
381 ,@(mapcar (lambda (b)
382 `(const :tag ,(cdr b) ,(car b)))
383 company-safe-backends)
384 (symbol :tag "User defined"))))))
386 (put 'company-backends 'safe-local-variable 'company-safe-backends-p)
388 (defcustom company-completion-started-hook nil
389 "*Hook run when company starts completing.
390 The hook is called with one argument that is non-nil if the completion was
395 (defcustom company-completion-cancelled-hook nil
396 "*Hook run when company cancels completing.
397 The hook is called with one argument that is non-nil if the completion was
402 (defcustom company-completion-finished-hook nil
403 "*Hook run when company successfully completes.
404 The hook is called with the selected candidate as an argument."
408 (defcustom company-minimum-prefix-length 3
409 "*The minimum prefix length for automatic completion."
411 :type '(integer :tag "prefix length"))
413 (defcustom company-require-match 'company-explicit-action-p
414 "*If enabled, disallow non-matching input.
415 This can be a function do determine if a match is required.
417 This can be overridden by the back-end, if it returns t or 'never to
418 'require-match. `company-auto-complete' also takes precedence over this."
420 :type '(choice (const :tag "Off" nil)
421 (function :tag "Predicate function")
422 (const :tag "On, if user interaction took place"
423 'company-explicit-action-p)
424 (const :tag "On" t)))
426 (defcustom company-auto-complete 'company-explicit-action-p
427 "Determines when to auto-complete.
428 If this is enabled, all characters from `company-auto-complete-chars' complete
429 the selected completion. This can also be a function."
431 :type '(choice (const :tag "Off" nil)
432 (function :tag "Predicate function")
433 (const :tag "On, if user interaction took place"
434 'company-explicit-action-p)
435 (const :tag "On" t)))
437 (defcustom company-auto-complete-chars '(?\ ?\( ?\) ?. ?\" ?$ ?\' ?< ?| ?!)
438 "Determines which characters trigger an automatic completion.
439 See `company-auto-complete'. If this is a string, each string character causes
440 completion. If it is a list of syntax description characters (see
441 `modify-syntax-entry'), all characters with that syntax auto-complete.
443 This can also be a function, which is called with the new input and should
444 return non-nil if company should auto-complete.
446 A character that is part of a valid candidate never starts auto-completion."
448 :type '(choice (string :tag "Characters")
450 (const :tag "Whitespace" ?\ )
451 (const :tag "Symbol" ?_)
452 (const :tag "Opening parentheses" ?\()
453 (const :tag "Closing parentheses" ?\))
454 (const :tag "Word constituent" ?w)
455 (const :tag "Punctuation." ?.)
456 (const :tag "String quote." ?\")
457 (const :tag "Paired delimiter." ?$)
458 (const :tag "Expression quote or prefix operator." ?\')
459 (const :tag "Comment starter." ?<)
460 (const :tag "Comment ender." ?>)
461 (const :tag "Character-quote." ?/)
462 (const :tag "Generic string fence." ?|)
463 (const :tag "Generic comment fence." ?!))
464 (function :tag "Predicate function")))
466 (defcustom company-idle-delay .7
467 "*The idle delay in seconds until automatic completions starts.
468 A value of nil means never complete automatically, t means complete
469 immediately when a prefix of `company-minimum-prefix-length' is reached."
471 :type '(choice (const :tag "never (nil)" nil)
472 (const :tag "immediate (t)" t)
473 (number :tag "seconds")))
475 (defcustom company-begin-commands t
476 "*A list of commands following which company will start completing.
477 If this is t, it will complete after any command. See `company-idle-delay'.
479 Alternatively any command with a non-nil 'company-begin property is treated as
480 if it was on this list."
482 :type '(choice (const :tag "Any command" t)
483 (const :tag "Self insert command" '(self-insert-command))
484 (repeat :tag "Commands" function)))
486 (defcustom company-show-numbers nil
487 "*If enabled, show quick-access numbers for the first ten candidates."
489 :type '(choice (const :tag "off" nil)
490 (const :tag "on" t)))
492 (defvar company-end-of-buffer-workaround t
493 "*Work around a visualization bug when completing at the end of the buffer.
494 The work-around consists of adding a newline.")
496 ;;; mode ;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;
498 (defvar company-mode-map (make-sparse-keymap)
499 "Keymap used by `company-mode'.")
501 (defvar company-active-map
502 (let ((keymap (make-sparse-keymap)))
503 (define-key keymap "\e\e\e" 'company-abort)
504 (define-key keymap "\C-g" 'company-abort)
505 (define-key keymap (kbd "M-n") 'company-select-next)
506 (define-key keymap (kbd "M-p") 'company-select-previous)
507 (define-key keymap (kbd "<down>") 'company-select-next)
508 (define-key keymap (kbd "<up>") 'company-select-previous)
509 (define-key keymap [down-mouse-1] 'ignore)
510 (define-key keymap [down-mouse-3] 'ignore)
511 (define-key keymap [mouse-1] 'company-complete-mouse)
512 (define-key keymap [mouse-3] 'company-select-mouse)
513 (define-key keymap [up-mouse-1] 'ignore)
514 (define-key keymap [up-mouse-3] 'ignore)
515 (define-key keymap "\C-m" 'company-complete-selection)
516 (define-key keymap "\t" 'company-complete-common)
517 (define-key keymap (kbd "<f1>") 'company-show-doc-buffer)
518 (define-key keymap "\C-w" 'company-show-location)
519 (define-key keymap "\C-s" 'company-search-candidates)
520 (define-key keymap "\C-\M-s" 'company-filter-candidates)
522 (define-key keymap (vector (+ (aref (kbd "M-0") 0) i))
523 `(lambda () (interactive) (company-complete-number ,i))))
526 "Keymap that is enabled during an active completion.")
528 (defvar company--disabled-backends nil)
530 (defun company-init-backend (backend)
531 (and (symbolp backend)
532 (not (fboundp backend))
533 (ignore-errors (require backend nil t)))
535 (if (or (symbolp backend)
539 (funcall backend 'init)
540 (put backend 'company-init t))
542 (put backend 'company-init 'failed)
543 (unless (memq backend company--disabled-backends)
544 (message "Company back-end '%s' could not be initialized:\n%s"
545 backend (error-message-string err)))
546 (push backend company--disabled-backends)
548 (mapc 'company-init-backend backend)))
550 (defvar company-default-lighter " company")
552 (defvar company-lighter company-default-lighter)
553 (make-variable-buffer-local 'company-lighter)
556 (define-minor-mode company-mode
557 "\"complete anything\"; in in-buffer completion framework.
558 Completion starts automatically, depending on the values
559 `company-idle-delay' and `company-minimum-prefix-length'.
561 Completion can be controlled with the commands:
562 `company-complete-common', `company-complete-selection', `company-complete',
563 `company-select-next', `company-select-previous'. If these commands are
564 called before `company-idle-delay', completion will also start.
566 Completions can be searched with `company-search-candidates' or
567 `company-filter-candidates'. These can be used while completion is
570 The completion data is retrieved using `company-backends' and displayed using
571 `company-frontends'. If you want to start a specific back-end, call it
572 interactively or use `company-begin-backend'.
574 regular keymap (`company-mode-map'):
577 keymap during active completions (`company-active-map'):
579 \\{company-active-map}"
580 nil company-lighter company-mode-map
583 (add-hook 'pre-command-hook 'company-pre-command nil t)
584 (add-hook 'post-command-hook 'company-post-command nil t)
585 (mapc 'company-init-backend company-backends))
586 (remove-hook 'pre-command-hook 'company-pre-command t)
587 (remove-hook 'post-command-hook 'company-post-command t)
589 (kill-local-variable 'company-point)))
591 (define-globalized-minor-mode global-company-mode company-mode
592 (lambda () (company-mode 1)))
594 (defsubst company-assert-enabled ()
596 (company-uninstall-map)
597 (error "Company not enabled")))
599 ;;; keymaps ;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;
601 (defvar company-overriding-keymap-bound nil)
602 (make-variable-buffer-local 'company-overriding-keymap-bound)
604 (defvar company-old-keymap nil)
605 (make-variable-buffer-local 'company-old-keymap)
607 (defvar company-my-keymap nil)
608 (make-variable-buffer-local 'company-my-keymap)
610 (defsubst company-enable-overriding-keymap (keymap)
611 (setq company-my-keymap keymap)
612 (when company-overriding-keymap-bound
613 (company-uninstall-map)))
615 (defun company-install-map ()
616 (unless (or company-overriding-keymap-bound
617 (null company-my-keymap))
618 (setq company-old-keymap overriding-terminal-local-map
619 overriding-terminal-local-map company-my-keymap
620 company-overriding-keymap-bound t)))
622 (defun company-uninstall-map ()
623 (when (eq overriding-terminal-local-map company-my-keymap)
624 (setq overriding-terminal-local-map company-old-keymap
625 company-overriding-keymap-bound nil)))
628 ;; Emacs calculates the active keymaps before reading the event. That means we
629 ;; cannot change the keymap from a timer. So we send a bogus command.
630 (defun company-ignore ()
632 (setq this-command last-command))
634 (global-set-key '[31415926] 'company-ignore)
636 (defun company-input-noop ()
637 (push 31415926 unread-command-events))
640 ;; posn-col-row is incorrect in older Emacsen when line-spacing is set
641 (defun company--col-row (&optional pos)
642 (let ((posn (posn-at-point pos)))
643 (cons (car (posn-col-row posn)) (cdr (posn-actual-col-row posn)))))
645 (defsubst company--column (&optional pos)
646 (car (posn-col-row (posn-at-point pos))))
648 (defsubst company--row (&optional pos)
649 (cdr (posn-actual-col-row (posn-at-point pos))))
651 ;;; backends ;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;
653 (defun company-grab (regexp &optional expression limit)
654 (when (looking-back regexp limit)
655 (or (match-string-no-properties (or expression 0)) "")))
657 (defun company-grab-line (regexp &optional expression)
658 (company-grab regexp expression (point-at-bol)))
660 (defun company-grab-symbol ()
661 (if (looking-at "\\_>")
662 (buffer-substring (point) (save-excursion (skip-syntax-backward "w_")
664 (unless (and (char-after) (memq (char-syntax (char-after)) '(?w ?_)))
667 (defun company-grab-word ()
668 (if (looking-at "\\>")
669 (buffer-substring (point) (save-excursion (skip-syntax-backward "w")
671 (unless (and (char-after) (eq (char-syntax (char-after)) ?w))
674 (defun company-in-string-or-comment ()
675 (let ((ppss (syntax-ppss)))
676 (or (car (setq ppss (nthcdr 3 ppss)))
677 (car (setq ppss (cdr ppss)))
680 (if (fboundp 'locate-dominating-file)
681 (defalias 'company-locate-dominating-file 'locate-dominating-file)
682 (defun company-locate-dominating-file (file name)
684 (let ((dir (file-name-directory file))
686 (while (not (equal dir prev-dir))
687 (when (file-exists-p (expand-file-name name dir))
690 dir (file-name-directory (directory-file-name dir))))))))
692 (defun company-call-backend (&rest args)
693 (if (functionp company-backend)
694 (apply company-backend args)
695 (apply 'company--multi-backend-adapter company-backend args)))
697 (defun company--multi-backend-adapter (backends command &rest args)
700 (apply 'append (mapcar (lambda (backend) (apply backend command args))
706 (dolist (backend backends)
707 (when (setq value (apply backend command args))
710 ;;; completion mechanism ;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;
712 (defvar company-backend nil)
713 (make-variable-buffer-local 'company-backend)
715 (defvar company-prefix nil)
716 (make-variable-buffer-local 'company-prefix)
718 (defvar company-candidates nil)
719 (make-variable-buffer-local 'company-candidates)
721 (defvar company-candidates-length nil)
722 (make-variable-buffer-local 'company-candidates-length)
724 (defvar company-candidates-cache nil)
725 (make-variable-buffer-local 'company-candidates-cache)
727 (defvar company-candidates-predicate nil)
728 (make-variable-buffer-local 'company-candidates-predicate)
730 (defvar company-common nil)
731 (make-variable-buffer-local 'company-common)
733 (defvar company-selection 0)
734 (make-variable-buffer-local 'company-selection)
736 (defvar company-selection-changed nil)
737 (make-variable-buffer-local 'company-selection-changed)
739 (defvar company--explicit-action nil
740 "Non-nil, if explicit completion took place.")
741 (make-variable-buffer-local 'company--explicit-action)
743 (defvar company--point-max nil)
744 (make-variable-buffer-local 'company--point-max)
746 (defvar company-point nil)
747 (make-variable-buffer-local 'company-point)
749 (defvar company-timer nil)
751 (defvar company-added-newline nil)
752 (make-variable-buffer-local 'company-added-newline)
754 (defsubst company-strip-prefix (str)
755 (substring str (length company-prefix)))
757 (defmacro company-with-candidate-inserted (candidate &rest body)
758 "Evaluate BODY with CANDIDATE temporarily inserted.
759 This is a tool for back-ends that need candidates inserted before they
760 can retrieve meta-data for them."
762 `(let ((inhibit-modification-hooks t)
763 (inhibit-point-motion-hooks t)
764 (modified-p (buffer-modified-p)))
765 (insert (company-strip-prefix ,candidate))
768 (delete-region company-point (point)))))
770 (defun company-explicit-action-p ()
771 "Return whether explicit completion action was taken by the user."
772 (or company--explicit-action
773 company-selection-changed))
775 (defsubst company-reformat (candidate)
776 ;; company-ispell needs this, because the results are always lower-case
777 ;; It's mory efficient to fix it only when they are displayed.
778 (concat company-prefix (substring candidate (length company-prefix))))
780 (defun company--should-complete ()
781 (and (not (or buffer-read-only overriding-terminal-local-map
782 overriding-local-map))
783 ;; Check if in the middle of entering a key combination.
784 (or (equal (this-command-keys-vector) [])
785 (not (keymapp (key-binding (this-command-keys-vector)))))
786 (eq company-idle-delay t)
787 (or (eq t company-begin-commands)
788 (memq this-command company-begin-commands)
789 (and (symbolp this-command) (get this-command 'company-begin)))
790 (not (and transient-mark-mode mark-active))))
792 (defsubst company-call-frontends (command)
793 (dolist (frontend company-frontends)
795 (funcall frontend command)
796 (error (error "Company: Front-end %s error \"%s\" on command %s"
797 frontend (error-message-string err) command)))))
799 (defsubst company-set-selection (selection &optional force-update)
800 (setq selection (max 0 (min (1- company-candidates-length) selection)))
801 (when (or force-update (not (equal selection company-selection)))
802 (setq company-selection selection
803 company-selection-changed t)
804 (company-call-frontends 'update)))
806 (defun company-apply-predicate (candidates predicate)
808 (dolist (c candidates)
809 (when (funcall predicate c)
813 (defun company-update-candidates (candidates)
814 (setq company-candidates-length (length candidates))
815 (if (> company-selection 0)
816 ;; Try to restore the selection
817 (let ((selected (nth company-selection company-candidates)))
818 (setq company-selection 0
819 company-candidates candidates)
821 (while (and candidates (string< (pop candidates) selected))
822 (incf company-selection))
824 ;; Make sure selection isn't out of bounds.
825 (setq company-selection (min (1- company-candidates-length)
826 company-selection)))))
827 (setq company-selection 0
828 company-candidates candidates))
830 (push (cons company-prefix company-candidates) company-candidates-cache)
832 (let ((completion-ignore-case (company-call-backend 'ignore-case)))
833 (setq company-common (try-completion company-prefix company-candidates)))
834 (when (eq company-common t)
835 (setq company-candidates nil)))
837 (defun company-calculate-candidates (prefix)
838 (let ((candidates (cdr (assoc prefix company-candidates-cache))))
840 (when company-candidates-cache
841 (let ((len (length prefix))
842 (completion-ignore-case (company-call-backend 'ignore-case))
844 (dotimes (i (1+ len))
845 (when (setq prev (cdr (assoc (substring prefix 0 (- len i))
846 company-candidates-cache)))
847 (setq candidates (all-completions prefix prev))
849 ;; no cache match, call back-end
851 (setq candidates (company-call-backend 'candidates prefix))
852 (when company-candidates-predicate
854 (company-apply-predicate candidates
855 company-candidates-predicate)))
856 (unless (company-call-backend 'sorted)
857 (setq candidates (sort candidates 'string<)))
858 (when (company-call-backend 'duplicates)
860 (let ((c2 candidates))
862 (setcdr c2 (progn (while (equal (pop c2) (car c2)))
864 (if (or (cdr candidates)
865 (not (equal (car candidates) prefix)))
866 ;; Don't start when already completed and unique.
868 ;; Not the right place? maybe when setting?
869 (and company-candidates t))))
871 (defun company-idle-begin (buf win tick pos)
873 (eq buf (current-buffer))
874 (eq win (selected-window))
875 (eq tick (buffer-chars-modified-tick))
877 (not company-candidates)
878 (not (equal (point) company-point))
879 (let ((company-idle-delay t)
880 (company-begin-commands t))
882 (when company-candidates
884 (company-post-command)))))
886 (defun company-auto-begin ()
887 (company-assert-enabled)
889 (not company-candidates)
890 (let ((company-idle-delay t)
891 (company-minimum-prefix-length 0)
892 (company-begin-commands t))
894 ;; Return non-nil if active.
897 (defun company-manual-begin ()
899 (setq company--explicit-action t)
900 (company-auto-begin))
902 (defun company-other-backend (&optional backward)
903 (interactive (list current-prefix-arg))
904 (company-assert-enabled)
906 (let* ((after (cdr (member company-backend company-backends)))
907 (before (cdr (member company-backend (reverse company-backends))))
909 (append before (reverse after))
910 (append after (reverse before)))))
912 (dolist (backend next)
913 (when (ignore-errors (company-begin-backend backend))
915 (company-manual-begin))
916 (unless company-candidates
917 (error "No other back-end")))
919 (defun company-require-match-p ()
920 (let ((backend-value (company-call-backend 'require-match)))
921 (or (eq backend-value t)
922 (and (if (functionp company-require-match)
923 (funcall company-require-match)
924 (eq company-require-match t))
925 (not (eq backend-value 'never))))))
927 (defun company-punctuation-p (input)
928 "Return non-nil, if input starts with punctuation or parentheses."
929 (memq (char-syntax (string-to-char input)) '(?. ?\( ?\))))
931 (defun company-auto-complete-p (input)
932 "Return non-nil, if input starts with punctuation or parentheses."
933 (and (if (functionp company-auto-complete)
934 (funcall company-auto-complete)
935 company-auto-complete)
936 (if (functionp company-auto-complete-chars)
937 (funcall company-auto-complete-chars input)
938 (if (consp company-auto-complete-chars)
939 (memq (char-syntax (string-to-char input))
940 company-auto-complete-chars)
941 (string-match (substring input 0 1) company-auto-complete-chars)))))
943 (defun company--incremental-p ()
944 (and (> (point) company-point)
945 (> (point-max) company--point-max)
946 (not (eq this-command 'backward-delete-char-untabify))
947 (equal (buffer-substring (- company-point (length company-prefix))
951 (defsubst company--string-incremental-p (old-prefix new-prefix)
952 (and (> (length new-prefix) (length old-prefix))
953 (equal old-prefix (substring new-prefix 0 (length old-prefix)))))
955 (defun company--continue-failed (new-prefix)
956 (when (company--incremental-p)
957 (let ((input (buffer-substring-no-properties (point) company-point)))
959 ((company-auto-complete-p input)
962 (goto-char company-point)
963 (company-complete-selection)
965 ((and (company--string-incremental-p company-prefix new-prefix)
966 (company-require-match-p))
967 ;; wrong incremental input, but required match
968 (backward-delete-char (length input))
970 (message "Matching input is required")
972 ((equal company-prefix (car company-candidates))
973 ;; last input was actually success
974 (company-cancel company-prefix)
977 (defun company--good-prefix-p (prefix)
978 (and (or (company-explicit-action-p)
979 (>= (or (cdr-safe prefix) (length prefix))
980 company-minimum-prefix-length))
981 (stringp (or (car-safe prefix) prefix))))
983 (defun company--continue ()
984 (when (company-call-backend 'no-cache company-prefix)
985 ;; Don't complete existing candidates, fetch new ones.
986 (setq company-candidates-cache nil))
987 (let* ((new-prefix (company-call-backend 'prefix))
988 (c (when (and (company--good-prefix-p new-prefix)
989 (setq new-prefix (or (car-safe new-prefix) new-prefix))
990 (= (- (point) (length new-prefix))
991 (- company-point (length company-prefix))))
992 (setq new-prefix (or (car-safe new-prefix) new-prefix))
993 (company-calculate-candidates new-prefix))))
996 ;; t means complete/unique.
997 (company-cancel new-prefix)
1000 ;; incremental match
1001 (setq company-prefix new-prefix)
1002 (company-update-candidates c)
1004 (t (company--continue-failed new-prefix)))
1007 (defun company--begin-new ()
1009 (dolist (backend (if company-backend
1010 ;; prefer manual override
1011 (list company-backend)
1014 (if (or (symbolp backend)
1015 (functionp backend))
1016 (when (or (not (symbolp backend))
1017 (eq t (get backend 'company-init))
1018 (unless (get backend 'company-init)
1019 (company-init-backend backend)))
1020 (funcall backend 'prefix))
1021 (company--multi-backend-adapter backend 'prefix)))
1023 (when (company--good-prefix-p prefix)
1024 (setq prefix (or (car-safe prefix) prefix)
1025 company-backend backend
1026 c (company-calculate-candidates prefix))
1027 ;; t means complete/unique. We don't start, so no hooks.
1029 (when company--explicit-action
1030 (message "No completion found"))
1031 (setq company-prefix prefix)
1032 (when (symbolp backend)
1033 (setq company-lighter (concat " " (symbol-name backend))))
1034 (company-update-candidates c)
1035 (run-hook-with-args 'company-completion-started-hook
1036 (company-explicit-action-p))
1037 (company-call-frontends 'show)))
1040 (defun company-begin ()
1041 (setq company-candidates
1042 (or (and company-candidates (company--continue))
1043 (and (company--should-complete) (company--begin-new))))
1044 (when company-candidates
1045 (when (and company-end-of-buffer-workaround (eobp))
1046 (save-excursion (insert "\n"))
1047 (setq company-added-newline (buffer-chars-modified-tick)))
1048 (setq company-point (point)
1049 company--point-max (point-max))
1050 (company-enable-overriding-keymap company-active-map)
1051 (company-call-frontends 'update)))
1053 (defun company-cancel (&optional result)
1054 (and company-added-newline
1055 (> (point-max) (point-min))
1056 (let ((tick (buffer-chars-modified-tick)))
1057 (delete-region (1- (point-max)) (point-max))
1058 (equal tick company-added-newline))
1059 ;; Only set unmodified when tick remained the same since insert.
1060 (set-buffer-modified-p nil))
1061 (when company-prefix
1062 (if (stringp result)
1064 (company-call-backend 'pre-completion result)
1065 (run-hook-with-args 'company-completion-finished-hook result)
1066 (company-call-backend 'post-completion result))
1067 (run-hook-with-args 'company-completion-cancelled-hook result)))
1068 (setq company-added-newline nil
1071 company-candidates nil
1072 company-candidates-length nil
1073 company-candidates-cache nil
1074 company-candidates-predicate nil
1077 company-selection-changed nil
1078 company--explicit-action nil
1079 company-lighter company-default-lighter
1080 company--point-max nil
1083 (cancel-timer company-timer))
1084 (company-search-mode 0)
1085 (company-call-frontends 'hide)
1086 (company-enable-overriding-keymap nil))
1088 (defun company-abort ()
1091 ;; Don't start again, unless started manually.
1092 (setq company-point (point)))
1094 (defun company-finish (result)
1095 (insert (company-strip-prefix result))
1096 (company-cancel result)
1097 ;; Don't start again, unless started manually.
1098 (setq company-point (point)))
1100 (defsubst company-keep (command)
1101 (and (symbolp command) (get command 'company-keep)))
1103 (defun company-pre-command ()
1104 (unless (company-keep this-command)
1106 (when company-candidates
1107 (company-call-frontends 'pre-command))
1108 (error (message "Company: An error occurred in pre-command")
1109 (message "%s" (error-message-string err))
1112 (cancel-timer company-timer)
1113 (setq company-timer nil))
1114 (company-uninstall-map))
1116 (defun company-post-command ()
1117 (unless (company-keep this-command)
1120 (unless (equal (point) company-point)
1122 (if company-candidates
1123 (company-call-frontends 'post-command)
1124 (and (numberp company-idle-delay)
1125 (or (eq t company-begin-commands)
1126 (memq this-command company-begin-commands))
1128 (run-with-timer company-idle-delay nil
1130 (current-buffer) (selected-window)
1131 (buffer-chars-modified-tick) (point))))))
1132 (error (message "Company: An error occurred in post-command")
1133 (message "%s" (error-message-string err))
1135 (company-install-map))
1137 ;;; search ;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;
1139 (defvar company-search-string nil)
1140 (make-variable-buffer-local 'company-search-string)
1142 (defvar company-search-lighter " Search: \"\"")
1143 (make-variable-buffer-local 'company-search-lighter)
1145 (defvar company-search-old-map nil)
1146 (make-variable-buffer-local 'company-search-old-map)
1148 (defvar company-search-old-selection 0)
1149 (make-variable-buffer-local 'company-search-old-selection)
1151 (defun company-search (text lines)
1152 (let ((quoted (regexp-quote text))
1154 (dolist (line lines)
1155 (when (string-match quoted line (length company-prefix))
1159 (defun company-search-printing-char ()
1161 (company-search-assert-enabled)
1162 (setq company-search-string
1163 (concat (or company-search-string "") (string last-command-event))
1164 company-search-lighter (concat " Search: \"" company-search-string
1166 (let ((pos (company-search company-search-string
1167 (nthcdr company-selection company-candidates))))
1170 (company-set-selection (+ company-selection pos) t))))
1172 (defun company-search-repeat-forward ()
1173 "Repeat the incremental search in completion candidates forward."
1175 (company-search-assert-enabled)
1176 (let ((pos (company-search company-search-string
1177 (cdr (nthcdr company-selection
1178 company-candidates)))))
1181 (company-set-selection (+ company-selection pos 1) t))))
1183 (defun company-search-repeat-backward ()
1184 "Repeat the incremental search in completion candidates backwards."
1186 (company-search-assert-enabled)
1187 (let ((pos (company-search company-search-string
1188 (nthcdr (- company-candidates-length
1190 (reverse company-candidates)))))
1193 (company-set-selection (- company-selection pos 1) t))))
1195 (defun company-create-match-predicate ()
1196 (setq company-candidates-predicate
1197 `(lambda (candidate)
1198 ,(if company-candidates-predicate
1199 `(and (string-match ,company-search-string candidate)
1200 (funcall ,company-candidates-predicate
1202 `(string-match ,company-search-string candidate))))
1203 (company-update-candidates
1204 (company-apply-predicate company-candidates company-candidates-predicate))
1205 ;; Invalidate cache.
1206 (setq company-candidates-cache (cons company-prefix company-candidates)))
1208 (defun company-filter-printing-char ()
1210 (company-search-assert-enabled)
1211 (company-search-printing-char)
1212 (company-create-match-predicate)
1213 (company-call-frontends 'update))
1215 (defun company-search-kill-others ()
1216 "Limit the completion candidates to the ones matching the search string."
1218 (company-search-assert-enabled)
1219 (company-create-match-predicate)
1220 (company-search-mode 0)
1221 (company-call-frontends 'update))
1223 (defun company-search-abort ()
1224 "Abort searching the completion candidates."
1226 (company-search-assert-enabled)
1227 (company-set-selection company-search-old-selection t)
1228 (company-search-mode 0))
1230 (defun company-search-other-char ()
1232 (company-search-assert-enabled)
1233 (company-search-mode 0)
1234 (when last-input-event
1235 (clear-this-command-keys t)
1236 (setq unread-command-events (list last-input-event))))
1238 (defvar company-search-map
1240 (keymap (make-keymap)))
1241 (if (fboundp 'max-char)
1242 (set-char-table-range (nth 1 keymap) (cons #x100 (max-char))
1243 'company-search-printing-char)
1245 ;; obselete in Emacs 23
1246 (let ((l (generic-character-list))
1247 (table (nth 1 keymap)))
1249 (set-char-table-default table (car l) 'company-search-printing-char)
1250 (setq l (cdr l))))))
1251 (define-key keymap [t] 'company-search-other-char)
1253 (define-key keymap (make-string 1 i) 'company-search-other-char)
1256 (define-key keymap (vector i) 'company-search-printing-char)
1258 (let ((meta-map (make-sparse-keymap)))
1259 (define-key keymap (char-to-string meta-prefix-char) meta-map)
1260 (define-key keymap [escape] meta-map))
1261 (define-key keymap (vector meta-prefix-char t) 'company-search-other-char)
1262 (define-key keymap "\e\e\e" 'company-search-other-char)
1263 (define-key keymap [escape escape escape] 'company-search-other-char)
1265 (define-key keymap "\C-g" 'company-search-abort)
1266 (define-key keymap "\C-s" 'company-search-repeat-forward)
1267 (define-key keymap "\C-r" 'company-search-repeat-backward)
1268 (define-key keymap "\C-o" 'company-search-kill-others)
1270 "Keymap used for incrementally searching the completion candidates.")
1272 (define-minor-mode company-search-mode
1273 "Search mode for completion candidates.
1274 Don't start this directly, use `company-search-candidates' or
1275 `company-filter-candidates'."
1276 nil company-search-lighter nil
1277 (if company-search-mode
1278 (if (company-manual-begin)
1280 (setq company-search-old-selection company-selection)
1281 (company-call-frontends 'update))
1282 (setq company-search-mode nil))
1283 (kill-local-variable 'company-search-string)
1284 (kill-local-variable 'company-search-lighter)
1285 (kill-local-variable 'company-search-old-selection)
1286 (company-enable-overriding-keymap company-active-map)))
1288 (defsubst company-search-assert-enabled ()
1289 (company-assert-enabled)
1290 (unless company-search-mode
1291 (company-uninstall-map)
1292 (error "Company not in search mode")))
1294 (defun company-search-candidates ()
1295 "Start searching the completion candidates incrementally.
1297 \\<company-search-map>Search can be controlled with the commands:
1298 - `company-search-repeat-forward' (\\[company-search-repeat-forward])
1299 - `company-search-repeat-backward' (\\[company-search-repeat-backward])
1300 - `company-search-abort' (\\[company-search-abort])
1302 Regular characters are appended to the search string.
1304 The command `company-search-kill-others' (\\[company-search-kill-others]) uses
1305 the search string to limit the completion candidates."
1307 (company-search-mode 1)
1308 (company-enable-overriding-keymap company-search-map))
1310 (defvar company-filter-map
1311 (let ((keymap (make-keymap)))
1312 (define-key keymap [remap company-search-printing-char]
1313 'company-filter-printing-char)
1314 (set-keymap-parent keymap company-search-map)
1316 "Keymap used for incrementally searching the completion candidates.")
1318 (defun company-filter-candidates ()
1319 "Start filtering the completion candidates incrementally.
1320 This works the same way as `company-search-candidates' immediately
1321 followed by `company-search-kill-others' after each input."
1323 (company-search-mode 1)
1324 (company-enable-overriding-keymap company-filter-map))
1326 ;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;
1328 (defun company-select-next ()
1329 "Select the next candidate in the list."
1331 (when (company-manual-begin)
1332 (company-set-selection (1+ company-selection))))
1334 (defun company-select-previous ()
1335 "Select the previous candidate in the list."
1337 (when (company-manual-begin)
1338 (company-set-selection (1- company-selection))))
1340 (defun company-select-mouse (event)
1341 "Select the candidate picked by the mouse."
1343 (when (nth 4 (event-start event))
1344 (company-set-selection (- (cdr (posn-actual-col-row (event-start event)))
1349 (defun company-complete-mouse (event)
1350 "Complete the candidate picked by the mouse."
1352 (when (company-select-mouse event)
1353 (company-complete-selection)))
1355 (defun company-complete-selection ()
1356 "Complete the selected candidate."
1358 (when (company-manual-begin)
1359 (company-finish (nth company-selection company-candidates))))
1361 (defun company-complete-common ()
1362 "Complete the common part of all candidates."
1364 (when (company-manual-begin)
1365 (if (and (not (cdr company-candidates))
1366 (equal company-common (car company-candidates)))
1367 (company-complete-selection)
1368 (insert (company-strip-prefix company-common)))))
1370 (defun company-complete ()
1371 "Complete the common part of all candidates or the current selection.
1372 The first time this is called, the common part is completed, the second time, or
1373 when the selection has been changed, the selected candidate is completed."
1375 (when (company-manual-begin)
1376 (if (or company-selection-changed
1377 (eq last-command 'company-complete-common))
1378 (call-interactively 'company-complete-selection)
1379 (call-interactively 'company-complete-common)
1380 (setq this-command 'company-complete-common))))
1382 (defun company-complete-number (n)
1383 "Complete the Nth candidate.
1384 To show the number next to the candidates in some back-ends, enable
1385 `company-show-numbers'."
1386 (when (company-manual-begin)
1387 (and (< n 1) (> n company-candidates-length)
1388 (error "No candidate number %d" n))
1390 (company-finish (nth n company-candidates))))
1392 ;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;
1394 (defconst company-space-strings-limit 100)
1396 (defconst company-space-strings
1398 (dotimes (i company-space-strings-limit)
1399 (push (make-string (- company-space-strings-limit 1 i) ?\ ) lst))
1400 (apply 'vector lst)))
1402 (defsubst company-space-string (len)
1403 (if (< len company-space-strings-limit)
1404 (aref company-space-strings len)
1405 (make-string len ?\ )))
1407 (defsubst company-safe-substring (str from &optional to)
1408 (let ((len (length str)))
1411 (if (and to (> to len))
1412 (concat (substring str from)
1413 (company-space-string (- to len)))
1414 (substring str from to)))))
1416 ;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;
1418 (defvar company-last-metadata nil)
1419 (make-variable-buffer-local 'company-last-metadata)
1421 (defun company-fetch-metadata ()
1422 (let ((selected (nth company-selection company-candidates)))
1423 (unless (equal selected (car company-last-metadata))
1424 (setq company-last-metadata
1425 (cons selected (company-call-backend 'meta selected))))
1426 (cdr company-last-metadata)))
1428 (defun company-doc-buffer (&optional string)
1429 (with-current-buffer (get-buffer-create "*Company meta-data*")
1433 (defvar company--electric-commands
1434 '(scroll-other-window scroll-other-window-down)
1435 "List of Commands that won't break out of electric commands.")
1437 (defmacro company--electric-do (&rest body)
1438 (declare (indent 0) (debug t))
1439 `(when (company-manual-begin)
1440 (save-window-excursion
1441 (let ((height (window-height))
1442 (row (company--row))
1445 (and (< (window-height) height)
1446 (< (- (window-height) row 2) company-tooltip-limit)
1447 (recenter (- (window-height) row 2)))
1448 (while (memq (setq cmd (key-binding (vector (list (read-event)))))
1449 company--electric-commands)
1450 (call-interactively cmd))
1451 (when last-input-event
1452 (clear-this-command-keys t)
1453 (setq unread-command-events (list last-input-event)))))))
1455 (defun company-show-doc-buffer ()
1456 "Temporarily show a buffer with the complete documentation for the selection."
1458 (company--electric-do
1459 (let* ((selected (nth company-selection company-candidates))
1460 (doc-buffer (or (company-call-backend 'doc-buffer selected)
1461 (error "No documentation available"))))
1462 (with-current-buffer doc-buffer
1463 (goto-char (point-min)))
1464 (display-buffer doc-buffer t))))
1465 (put 'company-show-doc-buffer 'company-keep t)
1467 (defun company-show-location ()
1468 "Temporarily display a buffer showing the selected candidate in context."
1470 (company--electric-do
1471 (let* ((selected (nth company-selection company-candidates))
1472 (location (company-call-backend 'location selected))
1473 (pos (or (cdr location) (error "No location available")))
1474 (buffer (or (and (bufferp (car location)) (car location))
1475 (find-file-noselect (car location) t))))
1476 (with-selected-window (display-buffer buffer t)
1479 (if (bufferp (car location))
1481 (goto-char (point-min))
1482 (forward-line (1- pos))))
1483 (set-window-start nil (point))))))
1484 (put 'company-show-location 'company-keep t)
1486 ;;; package functions ;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;
1488 (defvar company-callback nil)
1489 (make-variable-buffer-local 'company-callback)
1491 (defvar company-begin-with-marker nil)
1492 (make-variable-buffer-local 'company-begin-with-marker)
1494 (defun company-remove-callback (&optional ignored)
1495 (remove-hook 'company-completion-finished-hook company-callback t)
1496 (remove-hook 'company-completion-cancelled-hook 'company-remove-callback t)
1497 (remove-hook 'company-completion-finished-hook 'company-remove-callback t)
1498 (when company-begin-with-marker
1499 (set-marker company-begin-with-marker nil)))
1501 (defun company-begin-backend (backend &optional callback)
1502 "Start a completion at point using BACKEND."
1503 (interactive (let ((val (completing-read "Company back-end: "
1505 'functionp nil "company-")))
1507 (list (intern val)))))
1508 (when (setq company-callback callback)
1509 (add-hook 'company-completion-finished-hook company-callback nil t))
1510 (add-hook 'company-completion-cancelled-hook 'company-remove-callback nil t)
1511 (add-hook 'company-completion-finished-hook 'company-remove-callback nil t)
1512 (setq company-backend backend)
1513 ;; Return non-nil if active.
1514 (or (company-manual-begin)
1515 (error "Cannot complete at point")))
1517 (defun company-begin-with (candidates
1518 &optional prefix-length require-match callback)
1519 "Start a completion at point.
1520 CANDIDATES is the list of candidates to use and PREFIX-LENGTH is the length of
1521 the prefix that already is in the buffer before point. It defaults to 0.
1523 CALLBACK is a function called with the selected result if the user successfully
1524 completes the input.
1527 \(company-begin-with '\(\"foo\" \"foobar\" \"foobarbaz\"\)\)"
1528 (setq company-begin-with-marker (copy-marker (point) t))
1529 (company-begin-backend
1530 `(lambda (command &optional arg &rest ignored)
1532 ((eq command 'prefix)
1533 (when (equal (point) (marker-position company-begin-with-marker))
1534 (buffer-substring ,(- (point) (or prefix-length 0)) (point))))
1535 ((eq command 'candidates)
1536 (all-completions arg ',candidates))
1537 ((eq command 'require-match)
1541 ;;; pseudo-tooltip ;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;
1543 (defvar company-pseudo-tooltip-overlay nil)
1544 (make-variable-buffer-local 'company-pseudo-tooltip-overlay)
1546 (defvar company-tooltip-offset 0)
1547 (make-variable-buffer-local 'company-tooltip-offset)
1549 (defun company-pseudo-tooltip-update-offset (selection num-lines limit)
1552 (setq company-tooltip-offset
1553 (max (min selection company-tooltip-offset)
1554 (- selection -1 limit)))
1556 (when (<= company-tooltip-offset 1)
1558 (setq company-tooltip-offset 0))
1560 (when (>= company-tooltip-offset (- num-lines limit 1))
1562 (when (= selection (1- num-lines))
1563 (decf company-tooltip-offset)
1564 (when (<= company-tooltip-offset 1)
1565 (setq company-tooltip-offset 0)
1572 (defsubst company-round-tab (arg)
1573 (* (/ (+ arg tab-width) tab-width) tab-width))
1575 (defun company-untabify (str)
1576 (let* ((pieces (split-string str "\t"))
1579 (setcar copy (company-safe-substring
1580 (car copy) 0 (company-round-tab (string-width (car copy)))))
1582 (apply 'concat pieces)))
1584 (defun company-fill-propertize (line width selected)
1585 (setq line (company-safe-substring line 0 width))
1586 (add-text-properties 0 width '(face company-tooltip
1587 mouse-face company-tooltip-mouse)
1589 (add-text-properties 0 (length company-common)
1590 '(face company-tooltip-common
1591 mouse-face company-tooltip-mouse)
1594 (if (and company-search-string
1595 (string-match (regexp-quote company-search-string) line
1596 (length company-prefix)))
1598 (add-text-properties (match-beginning 0) (match-end 0)
1599 '(face company-tooltip-selection)
1601 (when (< (match-beginning 0) (length company-common))
1602 (add-text-properties (match-beginning 0) (length company-common)
1603 '(face company-tooltip-common-selection)
1605 (add-text-properties 0 width '(face company-tooltip-selection
1606 mouse-face company-tooltip-selection)
1608 (add-text-properties 0 (length company-common)
1609 '(face company-tooltip-common-selection
1610 mouse-face company-tooltip-selection)
1616 (defun company-buffer-lines (beg end)
1618 (let ((row (company--row))
1620 (while (and (equal (move-to-window-line (incf row)) row)
1622 (push (buffer-substring beg (min end (1- (point)))) lines)
1624 (unless (eq beg end)
1625 (push (buffer-substring beg end) lines))
1628 (defsubst company-modify-line (old new offset)
1629 (concat (company-safe-substring old 0 offset)
1631 (company-safe-substring old (+ offset (length new)))))
1633 (defsubst company--length-limit (lst limit)
1634 (if (nthcdr limit lst)
1638 (defun company--replacement-string (lines old column nl &optional align-top)
1640 (let ((width (length (car lines))))
1641 (when (> width (- (window-width) column))
1642 (setq column (max 0 (- (window-width) width)))))
1646 ;; untouched lines first
1647 (dotimes (i (- (length old) (length lines)))
1648 (push (pop old) new)))
1649 ;; length into old lines.
1651 (push (company-modify-line (pop old) (pop lines) column) new))
1652 ;; Append whole new lines.
1654 (push (concat (company-space-string column) (pop lines)) new))
1655 (concat (when nl "\n")
1656 (mapconcat 'identity (nreverse new) "\n")
1659 (defun company--create-lines (selection limit)
1661 (let ((len company-candidates-length)
1670 ;; Scroll to offset.
1671 (setq limit (company-pseudo-tooltip-update-offset selection len limit))
1673 (when (> company-tooltip-offset 0)
1674 (setq previous (format "...(%d)" company-tooltip-offset)))
1676 (setq remainder (- len limit company-tooltip-offset)
1677 remainder (when (> remainder 0)
1678 (setq remainder (format "...(%d)" remainder))))
1680 (decf selection company-tooltip-offset)
1681 (setq width (max (length previous) (length remainder))
1682 lines (nthcdr company-tooltip-offset company-candidates)
1687 (setq width (max (length (pop lines-copy)) width)))
1688 (setq width (min width (window-width)))
1690 (setq lines-copy lines)
1692 ;; number can make tooltip too long
1693 (when company-show-numbers
1694 (setq numbered company-tooltip-offset))
1697 (push (propertize (company-safe-substring previous 0 width)
1698 'face 'company-tooltip)
1702 (push (company-fill-propertize
1703 (if (>= numbered 10)
1704 (company-reformat (pop lines))
1707 (company-safe-substring (company-reformat (pop lines))
1710 width (equal i selection))
1714 (push (propertize (company-safe-substring remainder 0 width)
1715 'face 'company-tooltip)
1718 (setq lines (nreverse new))))
1722 (defsubst company--window-inner-height ()
1723 (let ((edges (window-inside-edges (selected-window))))
1724 (- (nth 3 edges) (nth 1 edges))))
1726 (defsubst company--pseudo-tooltip-height ()
1727 "Calculate the appropriate tooltip height.
1728 Returns a negative number if the tooltip should be displayed above point."
1729 (let* ((lines (count-lines (window-start) (point-at-bol)))
1730 (below (- (company--window-inner-height) 1 lines)))
1731 (if (and (< below (min company-tooltip-minimum company-candidates-length))
1733 (- (max 3 (min company-tooltip-limit lines)))
1734 (max 3 (min company-tooltip-limit below)))))
1736 (defun company-pseudo-tooltip-show (row column selection)
1737 (company-pseudo-tooltip-hide)
1742 (let* ((height (company--pseudo-tooltip-height))
1746 (setq row (+ row height -1)
1749 (let* ((nl (< (move-to-window-line row) row))
1751 (end (save-excursion
1752 (move-to-window-line (+ row (abs height)))
1754 (ov (make-overlay beg end))
1755 (args (list (mapcar 'company-untabify
1756 (company-buffer-lines beg end))
1759 (setq company-pseudo-tooltip-overlay ov)
1760 (overlay-put ov 'company-replacement-args args)
1761 (overlay-put ov 'company-before
1762 (apply 'company--replacement-string
1763 (company--create-lines selection (abs height))
1766 (overlay-put ov 'company-column column)
1767 (overlay-put ov 'company-height (abs height))
1768 (overlay-put ov 'window (selected-window))))))
1770 (defun company-pseudo-tooltip-show-at-point (pos)
1771 (let ((col-row (company--col-row pos)))
1773 (company-pseudo-tooltip-show (1+ (cdr col-row)) (car col-row)
1774 company-selection))))
1776 (defun company-pseudo-tooltip-edit (lines selection)
1777 (let ((column (overlay-get company-pseudo-tooltip-overlay 'company-column))
1778 (height (overlay-get company-pseudo-tooltip-overlay 'company-height)))
1779 (overlay-put company-pseudo-tooltip-overlay 'company-before
1780 (apply 'company--replacement-string
1781 (company--create-lines selection height)
1782 (overlay-get company-pseudo-tooltip-overlay
1783 'company-replacement-args)))))
1785 (defun company-pseudo-tooltip-hide ()
1786 (when company-pseudo-tooltip-overlay
1787 (delete-overlay company-pseudo-tooltip-overlay)
1788 (setq company-pseudo-tooltip-overlay nil)))
1790 (defun company-pseudo-tooltip-hide-temporarily ()
1791 (when (overlayp company-pseudo-tooltip-overlay)
1792 (overlay-put company-pseudo-tooltip-overlay 'invisible nil)
1793 (overlay-put company-pseudo-tooltip-overlay 'before-string nil)))
1795 (defun company-pseudo-tooltip-unhide ()
1796 (when company-pseudo-tooltip-overlay
1797 (overlay-put company-pseudo-tooltip-overlay 'invisible t)
1798 (overlay-put company-pseudo-tooltip-overlay 'before-string
1799 (overlay-get company-pseudo-tooltip-overlay 'company-before))
1800 (overlay-put company-pseudo-tooltip-overlay 'window (selected-window))))
1802 (defun company-pseudo-tooltip-frontend (command)
1803 "A `company-mode' front-end similar to a tool-tip but based on overlays."
1805 ('pre-command (company-pseudo-tooltip-hide-temporarily))
1807 (let ((old-height (if (overlayp company-pseudo-tooltip-overlay)
1808 (overlay-get company-pseudo-tooltip-overlay
1811 (new-height (company--pseudo-tooltip-height)))
1812 (unless (and (>= (* old-height new-height) 0)
1813 (>= (abs old-height) (abs new-height)))
1815 (company-pseudo-tooltip-show-at-point (- (point)
1816 (length company-prefix)))))
1817 (company-pseudo-tooltip-unhide))
1818 ('hide (company-pseudo-tooltip-hide)
1819 (setq company-tooltip-offset 0))
1820 ('update (when (overlayp company-pseudo-tooltip-overlay)
1821 (company-pseudo-tooltip-edit company-candidates
1822 company-selection)))))
1824 (defun company-pseudo-tooltip-unless-just-one-frontend (command)
1825 "`company-pseudo-tooltip-frontend', but not shown for single candidates."
1826 (unless (and (eq command 'post-command)
1827 (not (cdr company-candidates)))
1828 (company-pseudo-tooltip-frontend command)))
1830 ;;; overlay ;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;
1832 (defvar company-preview-overlay nil)
1833 (make-variable-buffer-local 'company-preview-overlay)
1835 (defun company-preview-show-at-point (pos)
1836 (company-preview-hide)
1838 (setq company-preview-overlay (make-overlay pos pos))
1840 (let ((completion(nth company-selection company-candidates)))
1841 (setq completion (propertize completion 'face 'company-preview))
1842 (add-text-properties 0 (length company-common)
1843 '(face company-preview-common) completion)
1845 ;; Add search string
1846 (and company-search-string
1847 (string-match (regexp-quote company-search-string) completion)
1848 (add-text-properties (match-beginning 0)
1850 '(face company-preview-search)
1853 (setq completion (company-strip-prefix completion))
1855 (and (equal pos (point))
1856 (not (equal completion ""))
1857 (add-text-properties 0 1 '(cursor t) completion))
1859 (overlay-put company-preview-overlay 'after-string completion)
1860 (overlay-put company-preview-overlay 'window (selected-window))))
1862 (defun company-preview-hide ()
1863 (when company-preview-overlay
1864 (delete-overlay company-preview-overlay)
1865 (setq company-preview-overlay nil)))
1867 (defun company-preview-frontend (command)
1868 "A `company-mode' front-end showing the selection as if it had been inserted."
1870 ('pre-command (company-preview-hide))
1871 ('post-command (company-preview-show-at-point (point)))
1872 ('hide (company-preview-hide))))
1874 (defun company-preview-if-just-one-frontend (command)
1875 "`company-preview-frontend', but only shown for single candidates."
1876 (unless (and (eq command 'post-command)
1877 (cdr company-candidates))
1878 (company-preview-frontend command)))
1880 ;;; echo ;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;
1882 (defvar company-echo-last-msg nil)
1883 (make-variable-buffer-local 'company-echo-last-msg)
1885 (defun company-echo-show (&optional getter)
1887 (setq company-echo-last-msg (funcall getter)))
1888 (let ((message-log-max nil))
1889 (if company-echo-last-msg
1890 (message "%s" company-echo-last-msg)
1893 (defsubst company-echo-show-soon (&optional getter)
1894 (when company-echo-timer
1895 (cancel-timer company-echo-timer))
1896 (setq company-echo-timer (run-with-timer 0 nil 'company-echo-show getter)))
1898 (defsubst company-echo-show-when-idle (&optional getter)
1900 (company-echo-show getter)))
1902 (defsubst company-echo-show-when-not-busy (&optional getter)
1903 "Run `company-echo-show' with arg GETTER once Emacs isn't busy."
1904 (when (sit-for company-echo-delay)
1905 (company-echo-show getter)))
1907 (defun company-echo-format ()
1909 (let ((limit (window-width (minibuffer-window)))
1911 ;; Roll to selection.
1912 (candidates (nthcdr company-selection company-candidates))
1913 (i (if company-show-numbers company-selection 99999))
1917 (setq comp (company-reformat (pop candidates))
1918 len (+ len 1 (length comp)))
1922 (setq comp (propertize (format "%d: %s" i comp)
1923 'face 'company-echo))
1926 (add-text-properties 3 (+ 3 (length company-common))
1927 '(face company-echo-common) comp))
1928 (setq comp (propertize comp 'face 'company-echo))
1929 (add-text-properties 0 (length company-common)
1930 '(face company-echo-common) comp))
1932 (setq candidates nil)
1935 (mapconcat 'identity (nreverse msg) " ")))
1937 (defun company-echo-strip-common-format ()
1939 (let ((limit (window-width (minibuffer-window)))
1940 (len (+ (length company-prefix) 2))
1941 ;; Roll to selection.
1942 (candidates (nthcdr company-selection company-candidates))
1943 (i (if company-show-numbers company-selection 99999))
1947 (setq comp (company-strip-prefix (pop candidates))
1948 len (+ len 2 (length comp)))
1951 (setq comp (format "%s (%d)" comp i))
1955 (setq candidates nil)
1956 (push (propertize comp 'face 'company-echo) msg)))
1958 (concat (propertize company-prefix 'face 'company-echo-common) "{"
1959 (mapconcat 'identity (nreverse msg) ", ")
1962 (defun company-echo-hide ()
1963 (unless (equal company-echo-last-msg "")
1964 (setq company-echo-last-msg "")
1965 (company-echo-show)))
1967 (defun company-echo-frontend (command)
1968 "A `company-mode' front-end showing the candidates in the echo area."
1970 ('post-command (company-echo-show-soon 'company-echo-format))
1971 ('hide (company-echo-hide))))
1973 (defun company-echo-strip-common-frontend (command)
1974 "A `company-mode' front-end showing the candidates in the echo area."
1976 ('post-command (company-echo-show-soon 'company-echo-strip-common-format))
1977 ('hide (company-echo-hide))))
1979 (defun company-echo-metadata-frontend (command)
1980 "A `company-mode' front-end showing the documentation in the echo area."
1982 ('post-command (company-echo-show-when-idle 'company-fetch-metadata))
1983 ('hide (company-echo-hide))))
1985 ;; templates ;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;
1987 (autoload 'company-template-declare-template "company-template")
1990 ;;; company.el ends here