1 ;;; company.el --- extensible inline text completion mechanism
3 ;; Copyright (C) 2009 Nikolaj Schumacher
5 ;; Author: Nikolaj Schumacher <bugs * nschum de>
7 ;; Keywords: abbrev, convenience, matchis
8 ;; URL: http://nschum.de/src/emacs/company/
9 ;; Compatibility: GNU Emacs 22.x, GNU Emacs 23.x
11 ;; This file is NOT part of GNU Emacs.
13 ;; This program is free software; you can redistribute it and/or
14 ;; modify it under the terms of the GNU General Public License
15 ;; as published by the Free Software Foundation; either version 2
16 ;; of the License, or (at your option) any later version.
18 ;; This program is distributed in the hope that it will be useful,
19 ;; but WITHOUT ANY WARRANTY; without even the implied warranty of
20 ;; MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
21 ;; GNU General Public License for more details.
23 ;; You should have received a copy of the GNU General Public License
24 ;; along with this program. If not, see <http://www.gnu.org/licenses/>.
28 ;; Company is a modular completion mechanism. Modules for retrieving completion
29 ;; candidates are called back-ends, modules for displaying them are front-ends.
31 ;; Company comes with many back-ends, e.g. `company-elisp'. These are
32 ;; distributed in individual files and can be used individually.
34 ;; Place company.el and the back-ends you want to use in a directory and add the
35 ;; following to your .emacs:
36 ;; (add-to-list 'load-path "/path/to/company")
37 ;; (autoload 'company-mode "company" nil t)
39 ;; Enable company-mode with M-x company-mode. For further information look at
40 ;; the documentation for `company-mode' (C-h f company-mode RET)
42 ;; If you want to start a specific back-end, call it interactively or use
43 ;; `company-begin-backend'. For example:
44 ;; M-x company-abbrev will prompt for and insert an abbrev.
46 ;; To write your own back-end, look at the documentation for `company-backends'.
47 ;; Here is a simple example completing "foo":
49 ;; (defun company-my-backend (command &optional arg &rest ignored)
51 ;; ('prefix (when (looking-back "foo\\>")
53 ;; ('candidates (list "foobar" "foobaz" "foobarbaz"))
54 ;; ('meta (format "This value is named %s" arg))))
56 ;; Sometimes it is a good idea to mix two back-ends together, for example to
57 ;; enrich gtags with dabbrev-code results (to emulate local variables):
58 ;; To do this, add a list with the merged back-ends as an element in
62 ;; When point is at the very end of the buffer, the pseudo-tooltip appears very
63 ;; wrong, unless company is allowed to temporarily insert a fake newline.
64 ;; This behavior is enabled by `company-end-of-buffer-workaround'.
68 ;; Added compatibility for CEDET in Emacs 23.2.
71 ;; Added `company-other-backend'.
72 ;; Idle completion no longer interrupts multi-key command input.
73 ;; Added `company-ropemacs' and `company-pysmell' back-ends.
76 ;; In C modes . and -> now count towards `company-minimum-prefix-length'.
77 ;; Reverted default front-end back to `company-preview-if-just-one-frontend'.
78 ;; The pseudo tooltip will no longer be clipped at the right window edge.
79 ;; Added `company-tooltip-minimum'.
80 ;; Windows compatibility fixes.
83 ;; Added `global-company-mode'.
84 ;; Performance enhancements.
85 ;; Added `company-eclim' back-end.
86 ;; Added safer workaround for Emacs `posn-col-row' bug.
89 ;; Automatic completion is now aborted if the prefix gets too short.
90 ;; Added option `company-dabbrev-time-limit'.
91 ;; `company-backends' now supports merging back-ends.
92 ;; Added back-end `company-dabbrev-code' for generic code.
93 ;; Fixed `company-begin-with'.
96 ;; Added 'stop prefix to prevent dabbrev from completing inside of symbols.
97 ;; Fixed issues with tabbar-mode and line-spacing.
98 ;; Performance enhancements.
101 ;; Added `company-begin-commands' option.
102 ;; Added abbrev, tempo and Xcode back-ends.
103 ;; Back-ends are now interactive. You can start them with M-x backend-name.
104 ;; Added `company-begin-with' for starting company from elisp-code.
106 ;; Added `company-require-match' and `company-auto-complete' options.
108 ;; 2009-04-05 (0.2.1)
109 ;; Improved Emacs Lisp back-end behavior for local variables.
110 ;; Added `company-elisp-detect-function-context' option.
111 ;; The mouse can now be used for selection.
114 ;; Added `company-show-location'.
115 ;; Added etags back-end.
116 ;; Added work-around for end-of-buffer bug.
117 ;; Added `company-filter-candidates'.
118 ;; More local Lisp variables are now included in the candidates.
120 ;; 2009-03-21 (0.1.5)
121 ;; Fixed elisp documentation buffer always showing the same doc.
122 ;; Added `company-echo-strip-common-frontend'.
123 ;; Added `company-show-numbers' option and M-0 ... M-9 default bindings.
124 ;; Don't hide the echo message if it isn't shown.
131 (eval-when-compile (require 'cl))
133 (add-to-list 'debug-ignored-errors "^.* frontend cannot be used twice$")
134 (add-to-list 'debug-ignored-errors "^Echo area cannot be used twice$")
135 (add-to-list 'debug-ignored-errors "^No \\(document\\|loc\\)ation available$")
136 (add-to-list 'debug-ignored-errors "^Company not ")
137 (add-to-list 'debug-ignored-errors "^No candidate number ")
138 (add-to-list 'debug-ignored-errors "^Cannot complete at point$")
139 (add-to-list 'debug-ignored-errors "^No other back-end$")
141 (defgroup company nil
142 "Extensible inline text completion mechanism"
147 (defface company-tooltip
148 '((t :background "yellow"
149 :foreground "black"))
150 "*Face used for the tool tip."
153 (defface company-tooltip-selection
154 '((default :inherit company-tooltip)
155 (((class color) (min-colors 88)) (:background "orange1"))
156 (t (:background "green")))
157 "*Face used for the selection in the tool tip."
160 (defface company-tooltip-mouse
161 '((default :inherit highlight))
162 "*Face used for the tool tip item under the mouse."
165 (defface company-tooltip-common
166 '((t :inherit company-tooltip
168 "*Face used for the common completion in the tool tip."
171 (defface company-tooltip-common-selection
172 '((t :inherit company-tooltip-selection
174 "*Face used for the selected common completion in the tool tip."
177 (defface company-preview
178 '((t :background "blue4"
179 :foreground "wheat"))
180 "*Face used for the completion preview."
183 (defface company-preview-common
184 '((t :inherit company-preview
186 "*Face used for the common part of the completion preview."
189 (defface company-preview-search
190 '((t :inherit company-preview
191 :background "blue1"))
192 "*Face used for the search string in the completion preview."
195 (defface company-echo nil
196 "*Face used for completions in the echo area."
199 (defface company-echo-common
200 '((((background dark)) (:foreground "firebrick1"))
201 (((background light)) (:background "firebrick4")))
202 "*Face used for the common part of completions in the echo area."
205 (defun company-frontends-set (variable value)
207 (let ((remainder value))
208 (setcdr remainder (delq (car remainder) (cdr remainder))))
209 (and (memq 'company-pseudo-tooltip-unless-just-one-frontend value)
210 (memq 'company-pseudo-tooltip-frontend value)
211 (error "Pseudo tooltip frontend cannot be used twice"))
212 (and (memq 'company-preview-if-just-one-frontend value)
213 (memq 'company-preview-frontend value)
214 (error "Preview frontend cannot be used twice"))
215 (and (memq 'company-echo value)
216 (memq 'company-echo-metadata-frontend value)
217 (error "Echo area cannot be used twice"))
218 ;; preview must come last
219 (dolist (f '(company-preview-if-just-one-frontend company-preview-frontend))
221 (setq value (append (delq f value) (list f)))))
222 (set variable value))
224 (defcustom company-frontends '(company-pseudo-tooltip-unless-just-one-frontend
225 company-preview-if-just-one-frontend
226 company-echo-metadata-frontend)
227 "*The list of active front-ends (visualizations).
228 Each front-end is a function that takes one argument. It is called with
229 one of the following arguments:
231 'show: When the visualization should start.
233 'hide: When the visualization should end.
235 'update: When the data has been updated.
237 'pre-command: Before every command that is executed while the
238 visualization is active.
240 'post-command: After every command that is executed while the
241 visualization is active.
243 The visualized data is stored in `company-prefix', `company-candidates',
244 `company-common', `company-selection', `company-point' and
245 `company-search-string'."
246 :set 'company-frontends-set
248 :type '(repeat (choice (const :tag "echo" company-echo-frontend)
249 (const :tag "echo, strip common"
250 company-echo-strip-common-frontend)
251 (const :tag "show echo meta-data in echo"
252 company-echo-metadata-frontend)
253 (const :tag "pseudo tooltip"
254 company-pseudo-tooltip-frontend)
255 (const :tag "pseudo tooltip, multiple only"
256 company-pseudo-tooltip-unless-just-one-frontend)
257 (const :tag "preview" company-preview-frontend)
258 (const :tag "preview, unique only"
259 company-preview-if-just-one-frontend)
260 (function :tag "custom function" nil))))
262 (defcustom company-tooltip-limit 10
263 "*The maximum number of candidates in the tool tip"
267 (defcustom company-tooltip-minimum 6
268 "*The minimum height of the tool tip.
269 If this many lines are not available, prefer to display the tooltip above."
273 (defvar company-safe-backends
274 '((company-abbrev . "Abbrev")
275 (company-css . "CSS")
276 (company-dabbrev . "dabbrev for plain text")
277 (company-dabbrev-code . "dabbrev for code")
278 (company-eclim . "eclim (an Eclipse interace)")
279 (company-elisp . "Emacs Lisp")
280 (company-etags . "etags")
281 (company-files . "Files")
282 (company-gtags . "GNU Global")
283 (company-ispell . "ispell")
284 (company-keywords . "Programming language keywords")
285 (company-nxml . "nxml")
286 (company-oddmuse . "Oddmuse")
287 (company-pysmell . "PySmell")
288 (company-ropemacs . "ropemacs")
289 (company-semantic . "CEDET Semantic")
290 (company-tempo . "Tempo templates")
291 (company-xcode . "Xcode")))
292 (put 'company-safe-backends 'risky-local-variable t)
294 (defun company-safe-backends-p (backends)
295 (and (consp backends)
296 (not (dolist (backend backends)
297 (unless (if (consp backend)
298 (company-safe-backends-p backend)
299 (assq backend company-safe-backends))
302 (defcustom company-backends '(company-elisp company-nxml company-css
303 company-eclim company-semantic company-xcode
305 (company-gtags company-etags company-dabbrev-code
306 company-pysmell company-keywords)
307 company-oddmuse company-files company-dabbrev)
308 "*The list of active back-ends (completion engines).
309 Each list elements can itself be a list of back-ends. In that case their
310 completions are merged. Otherwise only the first matching back-end returns
313 `company-begin-backend' can be used to start a specific back-end,
314 `company-other-backend' will skip to the next matching back-end in the list.
316 Each back-end is a function that takes a variable number of arguments.
317 The first argument is the command requested from the back-end. It is one
320 'prefix: The back-end should return the text to be completed. It must be
321 text immediately before `point'. Returning nil passes control to the next
322 back-end. The function should return 'stop if it should complete but cannot
323 \(e.g. if it is in the middle of a string\). If the returned value is only
324 part of the prefix (e.g. the part after \"->\" in C), the back-end may return a
325 cons of prefix and prefix length, which is then used in the
326 `company-minimum-prefix-length' test.
328 'candidates: The second argument is the prefix to be completed. The
329 return value should be a list of candidates that start with the prefix.
333 'sorted: The back-end may return t here to indicate that the candidates
334 are sorted and will not need to be sorted again.
336 'duplicates: If non-nil, company will take care of removing duplicates
339 'no-cache: Usually company doesn't ask for candidates again as completion
340 progresses, unless the back-end returns t for this command. The second
341 argument is the latest prefix.
343 'meta: The second argument is a completion candidate. The back-end should
344 return a (short) documentation string for it.
346 'doc-buffer: The second argument is a completion candidate. The back-end should
347 create a buffer (preferably with `company-doc-buffer'), fill it with
348 documentation and return it.
350 'location: The second argument is a completion candidate. The back-end can
351 return the cons of buffer and buffer location, or of file and line
352 number where the completion candidate was defined.
354 'require-match: If this value is t, the user is not allowed to enter anything
355 not offering as a candidate. Use with care! The default value nil gives the
356 user that choice with `company-require-match'. Return value 'never overrides
357 that option the other way around.
359 The back-end should return nil for all commands it does not support or
360 does not know about. It should also be callable interactively and use
361 `company-begin-backend' to start itself in that case."
366 ,@(mapcar (lambda (b) `(const :tag ,(cdr b) ,(car b)))
367 company-safe-backends)
368 (symbol :tag "User defined")
369 (repeat :tag "Merged Back-ends"
370 (choice :tag "Back-end"
371 ,@(mapcar (lambda (b)
372 `(const :tag ,(cdr b) ,(car b)))
373 company-safe-backends)
374 (symbol :tag "User defined"))))))
376 (put 'company-backends 'safe-local-variable 'company-safe-backends-p)
378 (defcustom company-completion-started-hook nil
379 "*Hook run when company starts completing.
380 The hook is called with one argument that is non-nil if the completion was
385 (defcustom company-completion-cancelled-hook nil
386 "*Hook run when company cancels completing.
387 The hook is called with one argument that is non-nil if the completion was
392 (defcustom company-completion-finished-hook nil
393 "*Hook run when company successfully completes.
394 The hook is called with the selected candidate as an argument."
398 (defcustom company-minimum-prefix-length 3
399 "*The minimum prefix length for automatic completion."
401 :type '(integer :tag "prefix length"))
403 (defcustom company-require-match 'company-explicit-action-p
404 "*If enabled, disallow non-matching input.
405 This can be a function do determine if a match is required.
407 This can be overridden by the back-end, if it returns t or 'never to
408 'require-match. `company-auto-complete' also takes precedence over this."
410 :type '(choice (const :tag "Off" nil)
411 (function :tag "Predicate function")
412 (const :tag "On, if user interaction took place"
413 'company-explicit-action-p)
414 (const :tag "On" t)))
416 (defcustom company-auto-complete 'company-explicit-action-p
417 "Determines when to auto-complete.
418 If this is enabled, all characters from `company-auto-complete-chars' complete
419 the selected completion. This can also be a function."
421 :type '(choice (const :tag "Off" nil)
422 (function :tag "Predicate function")
423 (const :tag "On, if user interaction took place"
424 'company-explicit-action-p)
425 (const :tag "On" t)))
427 (defcustom company-auto-complete-chars '(?\ ?\( ?\) ?. ?\" ?$ ?\' ?< ?| ?!)
428 "Determines which characters trigger an automatic completion.
429 See `company-auto-complete'. If this is a string, each string character causes
430 completion. If it is a list of syntax description characters (see
431 `modify-syntax-entry'), all characters with that syntax auto-complete.
433 This can also be a function, which is called with the new input and should
434 return non-nil if company should auto-complete.
436 A character that is part of a valid candidate never starts auto-completion."
438 :type '(choice (string :tag "Characters")
440 (const :tag "Whitespace" ?\ )
441 (const :tag "Symbol" ?_)
442 (const :tag "Opening parentheses" ?\()
443 (const :tag "Closing parentheses" ?\))
444 (const :tag "Word constituent" ?w)
445 (const :tag "Punctuation." ?.)
446 (const :tag "String quote." ?\")
447 (const :tag "Paired delimiter." ?$)
448 (const :tag "Expression quote or prefix operator." ?\')
449 (const :tag "Comment starter." ?<)
450 (const :tag "Comment ender." ?>)
451 (const :tag "Character-quote." ?/)
452 (const :tag "Generic string fence." ?|)
453 (const :tag "Generic comment fence." ?!))
454 (function :tag "Predicate function")))
456 (defcustom company-idle-delay .7
457 "*The idle delay in seconds until automatic completions starts.
458 A value of nil means never complete automatically, t means complete
459 immediately when a prefix of `company-minimum-prefix-length' is reached."
461 :type '(choice (const :tag "never (nil)" nil)
462 (const :tag "immediate (t)" t)
463 (number :tag "seconds")))
465 (defcustom company-begin-commands t
466 "*A list of commands following which company will start completing.
467 If this is t, it will complete after any command. See `company-idle-delay'.
469 Alternatively any command with a non-nil 'company-begin property is treated as
470 if it was on this list."
472 :type '(choice (const :tag "Any command" t)
473 (const :tag "Self insert command" '(self-insert-command))
474 (repeat :tag "Commands" function)))
476 (defcustom company-show-numbers nil
477 "*If enabled, show quick-access numbers for the first ten candidates."
479 :type '(choice (const :tag "off" nil)
480 (const :tag "on" t)))
482 (defvar company-end-of-buffer-workaround t
483 "*Work around a visualization bug when completing at the end of the buffer.
484 The work-around consists of adding a newline.")
486 ;;; mode ;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;
488 (defvar company-mode-map (make-sparse-keymap)
489 "Keymap used by `company-mode'.")
491 (defvar company-active-map
492 (let ((keymap (make-sparse-keymap)))
493 (define-key keymap "\e\e\e" 'company-abort)
494 (define-key keymap "\C-g" 'company-abort)
495 (define-key keymap (kbd "M-n") 'company-select-next)
496 (define-key keymap (kbd "M-p") 'company-select-previous)
497 (define-key keymap (kbd "<down>") 'company-select-next)
498 (define-key keymap (kbd "<up>") 'company-select-previous)
499 (define-key keymap [down-mouse-1] 'ignore)
500 (define-key keymap [down-mouse-3] 'ignore)
501 (define-key keymap [mouse-1] 'company-complete-mouse)
502 (define-key keymap [mouse-3] 'company-select-mouse)
503 (define-key keymap [up-mouse-1] 'ignore)
504 (define-key keymap [up-mouse-3] 'ignore)
505 (define-key keymap "\C-m" 'company-complete-selection)
506 (define-key keymap "\t" 'company-complete-common)
507 (define-key keymap (kbd "<f1>") 'company-show-doc-buffer)
508 (define-key keymap "\C-w" 'company-show-location)
509 (define-key keymap "\C-s" 'company-search-candidates)
510 (define-key keymap "\C-\M-s" 'company-filter-candidates)
512 (define-key keymap (vector (+ (aref (kbd "M-0") 0) i))
513 `(lambda () (interactive) (company-complete-number ,i))))
516 "Keymap that is enabled during an active completion.")
518 (defvar company--disabled-backends nil)
520 (defun company-init-backend (backend)
521 (and (symbolp backend)
522 (not (fboundp backend))
523 (ignore-errors (require backend nil t)))
525 (if (or (symbolp backend)
527 (if (ignore-errors (funcall backend 'init) t)
528 (put backend 'company-init t)
529 (put backend 'company-init 'failed)
530 (unless (memq backend company--disabled-backends)
531 (message "Company back-end '%s' could not be initialized"
533 (push backend company--disabled-backends))
535 (mapc 'company-init-backend backend)))
537 (defvar company-default-lighter " company")
539 (defvar company-lighter company-default-lighter)
540 (make-variable-buffer-local 'company-lighter)
543 (define-minor-mode company-mode
544 "\"complete anything\"; in in-buffer completion framework.
545 Completion starts automatically, depending on the values
546 `company-idle-delay' and `company-minimum-prefix-length'.
548 Completion can be controlled with the commands:
549 `company-complete-common', `company-complete-selection', `company-complete',
550 `company-select-next', `company-select-previous'. If these commands are
551 called before `company-idle-delay', completion will also start.
553 Completions can be searched with `company-search-candidates' or
554 `company-filter-candidates'. These can be used while completion is
557 The completion data is retrieved using `company-backends' and displayed using
558 `company-frontends'. If you want to start a specific back-end, call it
559 interactively or use `company-begin-backend'.
561 regular keymap (`company-mode-map'):
564 keymap during active completions (`company-active-map'):
566 \\{company-active-map}"
567 nil company-lighter company-mode-map
570 (add-hook 'pre-command-hook 'company-pre-command nil t)
571 (add-hook 'post-command-hook 'company-post-command nil t)
572 (mapc 'company-init-backend company-backends))
573 (remove-hook 'pre-command-hook 'company-pre-command t)
574 (remove-hook 'post-command-hook 'company-post-command t)
576 (kill-local-variable 'company-point)))
578 (define-globalized-minor-mode global-company-mode company-mode
579 (lambda () (company-mode 1)))
581 (defsubst company-assert-enabled ()
583 (company-uninstall-map)
584 (error "Company not enabled")))
586 ;;; keymaps ;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;
588 (defvar company-overriding-keymap-bound nil)
589 (make-variable-buffer-local 'company-overriding-keymap-bound)
591 (defvar company-old-keymap nil)
592 (make-variable-buffer-local 'company-old-keymap)
594 (defvar company-my-keymap nil)
595 (make-variable-buffer-local 'company-my-keymap)
597 (defsubst company-enable-overriding-keymap (keymap)
598 (setq company-my-keymap keymap)
599 (when company-overriding-keymap-bound
600 (company-uninstall-map)))
602 (defun company-install-map ()
603 (unless (or company-overriding-keymap-bound
604 (null company-my-keymap))
605 (setq company-old-keymap overriding-terminal-local-map
606 overriding-terminal-local-map company-my-keymap
607 company-overriding-keymap-bound t)))
609 (defun company-uninstall-map ()
610 (when (eq overriding-terminal-local-map company-my-keymap)
611 (setq overriding-terminal-local-map company-old-keymap
612 company-overriding-keymap-bound nil)))
615 ;; Emacs calculates the active keymaps before reading the event. That means we
616 ;; cannot change the keymap from a timer. So we send a bogus command.
617 (defun company-ignore ()
619 (setq this-command last-command))
621 (global-set-key '[31415926] 'company-ignore)
623 (defun company-input-noop ()
624 (push 31415926 unread-command-events))
627 ;; posn-col-row is incorrect in older Emacsen when line-spacing is set
628 (defun company--col-row (&optional pos)
629 (let ((posn (posn-at-point pos)))
630 (cons (car (posn-col-row posn)) (cdr (posn-actual-col-row posn)))))
632 (defsubst company--column (&optional pos)
633 (car (posn-col-row (posn-at-point pos))))
635 (defsubst company--row (&optional pos)
636 (cdr (posn-actual-col-row (posn-at-point pos))))
638 ;;; backends ;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;
640 (defun company-grab (regexp &optional expression limit)
641 (when (looking-back regexp limit)
642 (or (match-string-no-properties (or expression 0)) "")))
644 (defun company-grab-line (regexp &optional expression)
645 (company-grab regexp expression (point-at-bol)))
647 (defun company-grab-symbol ()
648 (if (looking-at "\\_>")
649 (buffer-substring (point) (save-excursion (skip-syntax-backward "w_")
651 (unless (and (char-after) (memq (char-syntax (char-after)) '(?w ?_)))
654 (defun company-grab-word ()
655 (if (looking-at "\\>")
656 (buffer-substring (point) (save-excursion (skip-syntax-backward "w")
658 (unless (and (char-after) (eq (char-syntax (char-after)) ?w))
661 (defun company-in-string-or-comment ()
662 (let ((ppss (syntax-ppss)))
663 (or (car (setq ppss (nthcdr 3 ppss)))
664 (car (setq ppss (cdr ppss)))
667 (if (fboundp 'locate-dominating-file)
668 (defalias 'company-locate-dominating-file 'locate-dominating-file)
669 (defun company-locate-dominating-file (file name)
671 (let ((dir (file-name-directory file))
673 (while (not (equal dir prev-dir))
674 (when (file-exists-p (expand-file-name name dir))
677 dir (file-name-directory (directory-file-name dir))))))))
679 (defun company-call-backend (&rest args)
680 (if (functionp company-backend)
681 (apply company-backend args)
682 (apply 'company--multi-backend-adapter company-backend args)))
684 (defun company--multi-backend-adapter (backends command &rest args)
687 (apply 'append (mapcar (lambda (backend) (apply backend command args))
693 (dolist (backend backends)
694 (when (setq value (apply backend command args))
697 ;;; completion mechanism ;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;
699 (defvar company-backend nil)
700 (make-variable-buffer-local 'company-backend)
702 (defvar company-prefix nil)
703 (make-variable-buffer-local 'company-prefix)
705 (defvar company-candidates nil)
706 (make-variable-buffer-local 'company-candidates)
708 (defvar company-candidates-length nil)
709 (make-variable-buffer-local 'company-candidates-length)
711 (defvar company-candidates-cache nil)
712 (make-variable-buffer-local 'company-candidates-cache)
714 (defvar company-candidates-predicate nil)
715 (make-variable-buffer-local 'company-candidates-predicate)
717 (defvar company-common nil)
718 (make-variable-buffer-local 'company-common)
720 (defvar company-selection 0)
721 (make-variable-buffer-local 'company-selection)
723 (defvar company-selection-changed nil)
724 (make-variable-buffer-local 'company-selection-changed)
726 (defvar company--explicit-action nil
727 "Non-nil, if explicit completion took place.")
728 (make-variable-buffer-local 'company--explicit-action)
730 (defvar company--point-max nil)
731 (make-variable-buffer-local 'company--point-max)
733 (defvar company-point nil)
734 (make-variable-buffer-local 'company-point)
736 (defvar company-timer nil)
738 (defvar company-added-newline nil)
739 (make-variable-buffer-local 'company-added-newline)
741 (defsubst company-strip-prefix (str)
742 (substring str (length company-prefix)))
744 (defun company-explicit-action-p ()
745 "Return whether explicit completion action was taken by the user."
746 (or company--explicit-action
747 company-selection-changed))
749 (defsubst company-reformat (candidate)
750 ;; company-ispell needs this, because the results are always lower-case
751 ;; It's mory efficient to fix it only when they are displayed.
752 (concat company-prefix (substring candidate (length company-prefix))))
754 (defun company--should-complete ()
755 (and (not (or buffer-read-only overriding-terminal-local-map
756 overriding-local-map))
757 ;; Check if in the middle of entering a key combination.
758 (or (equal (this-command-keys-vector) [])
759 (not (keymapp (key-binding (this-command-keys-vector)))))
760 (eq company-idle-delay t)
761 (or (eq t company-begin-commands)
762 (memq this-command company-begin-commands)
763 (and (symbolp this-command) (get this-command 'company-begin)))
764 (not (and transient-mark-mode mark-active))))
766 (defsubst company-call-frontends (command)
767 (dolist (frontend company-frontends)
769 (funcall frontend command)
770 (error (error "Company: Front-end %s error \"%s\" on command %s"
771 frontend (error-message-string err) command)))))
773 (defsubst company-set-selection (selection &optional force-update)
774 (setq selection (max 0 (min (1- company-candidates-length) selection)))
775 (when (or force-update (not (equal selection company-selection)))
776 (setq company-selection selection
777 company-selection-changed t)
778 (company-call-frontends 'update)))
780 (defun company-apply-predicate (candidates predicate)
782 (dolist (c candidates)
783 (when (funcall predicate c)
787 (defun company-update-candidates (candidates)
788 (setq company-candidates-length (length candidates))
789 (if (> company-selection 0)
790 ;; Try to restore the selection
791 (let ((selected (nth company-selection company-candidates)))
792 (setq company-selection 0
793 company-candidates candidates)
795 (while (and candidates (string< (pop candidates) selected))
796 (incf company-selection))
798 ;; Make sure selection isn't out of bounds.
799 (setq company-selection (min (1- company-candidates-length)
800 company-selection)))))
801 (setq company-selection 0
802 company-candidates candidates))
804 (push (cons company-prefix company-candidates) company-candidates-cache)
806 (let ((completion-ignore-case (company-call-backend 'ignore-case)))
807 (setq company-common (try-completion company-prefix company-candidates)))
808 (when (eq company-common t)
809 (setq company-candidates nil)))
811 (defun company-calculate-candidates (prefix)
812 (let ((candidates (cdr (assoc prefix company-candidates-cache))))
814 (when company-candidates-cache
815 (let ((len (length prefix))
816 (completion-ignore-case (company-call-backend 'ignore-case))
818 (dotimes (i (1+ len))
819 (when (setq prev (cdr (assoc (substring prefix 0 (- len i))
820 company-candidates-cache)))
821 (setq candidates (all-completions prefix prev))
823 ;; no cache match, call back-end
825 (setq candidates (company-call-backend 'candidates prefix))
826 (when company-candidates-predicate
828 (company-apply-predicate candidates
829 company-candidates-predicate)))
830 (unless (company-call-backend 'sorted)
831 (setq candidates (sort candidates 'string<)))
832 (when (company-call-backend 'duplicates)
834 (let ((c2 candidates))
836 (setcdr c2 (progn (while (equal (pop c2) (car c2)))
838 (if (or (cdr candidates)
839 (not (equal (car candidates) prefix)))
840 ;; Don't start when already completed and unique.
842 ;; Not the right place? maybe when setting?
843 (and company-candidates t))))
845 (defun company-idle-begin (buf win tick pos)
847 (eq buf (current-buffer))
848 (eq win (selected-window))
849 (eq tick (buffer-chars-modified-tick))
851 (not company-candidates)
852 (not (equal (point) company-point))
853 (let ((company-idle-delay t)
854 (company-begin-commands t))
856 (when company-candidates
858 (company-post-command)))))
860 (defun company-auto-begin ()
861 (company-assert-enabled)
863 (not company-candidates)
864 (let ((company-idle-delay t)
865 (company-minimum-prefix-length 0)
866 (company-begin-commands t))
868 ;; Return non-nil if active.
871 (defun company-manual-begin ()
873 (setq company--explicit-action t)
874 (company-auto-begin))
876 (defun company-other-backend (&optional backward)
877 (interactive (list current-prefix-arg))
878 (company-assert-enabled)
880 (let* ((after (cdr (member company-backend company-backends)))
881 (before (cdr (member company-backend (reverse company-backends))))
883 (append before (reverse after))
884 (append after (reverse before)))))
886 (dolist (backend next)
887 (when (ignore-errors (company-begin-backend backend))
889 (company-manual-begin))
890 (unless company-candidates
891 (error "No other back-end")))
893 (defun company-require-match-p ()
894 (let ((backend-value (company-call-backend 'require-match)))
895 (or (eq backend-value t)
896 (and (if (functionp company-require-match)
897 (funcall company-require-match)
898 (eq company-require-match t))
899 (not (eq backend-value 'never))))))
901 (defun company-punctuation-p (input)
902 "Return non-nil, if input starts with punctuation or parentheses."
903 (memq (char-syntax (string-to-char input)) '(?. ?\( ?\))))
905 (defun company-auto-complete-p (input)
906 "Return non-nil, if input starts with punctuation or parentheses."
907 (and (if (functionp company-auto-complete)
908 (funcall company-auto-complete)
909 company-auto-complete)
910 (if (functionp company-auto-complete-chars)
911 (funcall company-auto-complete-chars input)
912 (if (consp company-auto-complete-chars)
913 (memq (char-syntax (string-to-char input))
914 company-auto-complete-chars)
915 (string-match (substring input 0 1) company-auto-complete-chars)))))
917 (defun company--incremental-p ()
918 (and (> (point) company-point)
919 (> (point-max) company--point-max)
920 (not (eq this-command 'backward-delete-char-untabify))
921 (equal (buffer-substring (- company-point (length company-prefix))
925 (defsubst company--string-incremental-p (old-prefix new-prefix)
926 (and (> (length new-prefix) (length old-prefix))
927 (equal old-prefix (substring new-prefix 0 (length old-prefix)))))
929 (defun company--continue-failed (new-prefix)
930 (when (company--incremental-p)
931 (let ((input (buffer-substring-no-properties (point) company-point)))
933 ((company-auto-complete-p input)
936 (goto-char company-point)
937 (company-complete-selection)
939 ((and (company--string-incremental-p company-prefix new-prefix)
940 (company-require-match-p))
941 ;; wrong incremental input, but required match
942 (backward-delete-char (length input))
944 (message "Matching input is required")
946 ((equal company-prefix (car company-candidates))
947 ;; last input was actually success
948 (company-cancel company-prefix)
951 (defun company--good-prefix-p (prefix)
952 (and (or (company-explicit-action-p)
953 (>= (or (cdr-safe prefix) (length prefix))
954 company-minimum-prefix-length))
955 (stringp (or (car-safe prefix) prefix))))
957 (defun company--continue ()
958 (when (company-call-backend 'no-cache company-prefix)
959 ;; Don't complete existing candidates, fetch new ones.
960 (setq company-candidates-cache nil))
961 (let* ((new-prefix (company-call-backend 'prefix))
962 (c (when (and (company--good-prefix-p new-prefix)
963 (setq new-prefix (or (car-safe new-prefix) new-prefix))
964 (= (- (point) (length new-prefix))
965 (- company-point (length company-prefix))))
966 (setq new-prefix (or (car-safe new-prefix) new-prefix))
967 (company-calculate-candidates new-prefix))))
970 ;; t means complete/unique.
971 (company-cancel new-prefix)
975 (setq company-prefix new-prefix)
976 (company-update-candidates c)
978 (t (company--continue-failed new-prefix)))
981 (defun company--begin-new ()
983 (dolist (backend (if company-backend
984 ;; prefer manual override
985 (list company-backend)
988 (if (or (symbolp backend)
990 (when (or (not (symbolp backend))
991 (eq t (get backend 'company-init))
992 (unless (get backend 'company-init)
993 (company-init-backend backend)))
994 (funcall backend 'prefix))
995 (company--multi-backend-adapter backend 'prefix)))
997 (when (company--good-prefix-p prefix)
998 (setq prefix (or (car-safe prefix) prefix)
999 company-backend backend
1000 c (company-calculate-candidates prefix))
1001 ;; t means complete/unique. We don't start, so no hooks.
1003 (setq company-prefix prefix)
1004 (when (symbolp backend)
1005 (setq company-lighter (concat " " (symbol-name backend))))
1006 (company-update-candidates c)
1007 (run-hook-with-args 'company-completion-started-hook
1008 (company-explicit-action-p))
1009 (company-call-frontends 'show)))
1012 (defun company-begin ()
1013 (setq company-candidates
1014 (or (and company-candidates (company--continue))
1015 (and (company--should-complete) (company--begin-new))))
1016 (when company-candidates
1017 (when (and company-end-of-buffer-workaround (eobp))
1018 (save-excursion (insert "\n"))
1019 (setq company-added-newline (buffer-chars-modified-tick)))
1020 (setq company-point (point)
1021 company--point-max (point-max))
1022 (company-enable-overriding-keymap company-active-map)
1023 (company-call-frontends 'update)))
1025 (defun company-cancel (&optional result)
1026 (and company-added-newline
1027 (> (point-max) (point-min))
1028 (let ((tick (buffer-chars-modified-tick)))
1029 (delete-region (1- (point-max)) (point-max))
1030 (equal tick company-added-newline))
1031 ;; Only set unmodified when tick remained the same since insert.
1032 (set-buffer-modified-p nil))
1033 (when company-prefix
1034 (if (stringp result)
1035 (run-hook-with-args 'company-completion-finished-hook result)
1036 (run-hook-with-args 'company-completion-cancelled-hook result)))
1037 (setq company-added-newline nil
1040 company-candidates nil
1041 company-candidates-length nil
1042 company-candidates-cache nil
1043 company-candidates-predicate nil
1046 company-selection-changed nil
1047 company--explicit-action nil
1048 company-lighter company-default-lighter
1049 company--point-max nil
1052 (cancel-timer company-timer))
1053 (company-search-mode 0)
1054 (company-call-frontends 'hide)
1055 (company-enable-overriding-keymap nil))
1057 (defun company-abort ()
1060 ;; Don't start again, unless started manually.
1061 (setq company-point (point)))
1063 (defun company-finish (result)
1064 (insert (company-strip-prefix result))
1065 (company-cancel result)
1066 ;; Don't start again, unless started manually.
1067 (setq company-point (point)))
1069 (defsubst company-keep (command)
1070 (and (symbolp command) (get command 'company-keep)))
1072 (defun company-pre-command ()
1073 (unless (company-keep this-command)
1075 (when company-candidates
1076 (company-call-frontends 'pre-command))
1077 (error (message "Company: An error occurred in pre-command")
1078 (message "%s" (error-message-string err))
1081 (cancel-timer company-timer)
1082 (setq company-timer nil))
1083 (company-uninstall-map))
1085 (defun company-post-command ()
1086 (unless (company-keep this-command)
1089 (unless (equal (point) company-point)
1091 (if company-candidates
1092 (company-call-frontends 'post-command)
1093 (and (numberp company-idle-delay)
1094 (or (eq t company-begin-commands)
1095 (memq this-command company-begin-commands))
1097 (run-with-timer company-idle-delay nil
1099 (current-buffer) (selected-window)
1100 (buffer-chars-modified-tick) (point))))))
1101 (error (message "Company: An error occurred in post-command")
1102 (message "%s" (error-message-string err))
1104 (company-install-map))
1106 ;;; search ;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;
1108 (defvar company-search-string nil)
1109 (make-variable-buffer-local 'company-search-string)
1111 (defvar company-search-lighter " Search: \"\"")
1112 (make-variable-buffer-local 'company-search-lighter)
1114 (defvar company-search-old-map nil)
1115 (make-variable-buffer-local 'company-search-old-map)
1117 (defvar company-search-old-selection 0)
1118 (make-variable-buffer-local 'company-search-old-selection)
1120 (defun company-search (text lines)
1121 (let ((quoted (regexp-quote text))
1123 (dolist (line lines)
1124 (when (string-match quoted line (length company-prefix))
1128 (defun company-search-printing-char ()
1130 (company-search-assert-enabled)
1131 (setq company-search-string
1132 (concat (or company-search-string "") (string last-command-event))
1133 company-search-lighter (concat " Search: \"" company-search-string
1135 (let ((pos (company-search company-search-string
1136 (nthcdr company-selection company-candidates))))
1139 (company-set-selection (+ company-selection pos) t))))
1141 (defun company-search-repeat-forward ()
1142 "Repeat the incremental search in completion candidates forward."
1144 (company-search-assert-enabled)
1145 (let ((pos (company-search company-search-string
1146 (cdr (nthcdr company-selection
1147 company-candidates)))))
1150 (company-set-selection (+ company-selection pos 1) t))))
1152 (defun company-search-repeat-backward ()
1153 "Repeat the incremental search in completion candidates backwards."
1155 (company-search-assert-enabled)
1156 (let ((pos (company-search company-search-string
1157 (nthcdr (- company-candidates-length
1159 (reverse company-candidates)))))
1162 (company-set-selection (- company-selection pos 1) t))))
1164 (defun company-create-match-predicate ()
1165 (setq company-candidates-predicate
1166 `(lambda (candidate)
1167 ,(if company-candidates-predicate
1168 `(and (string-match ,company-search-string candidate)
1169 (funcall ,company-candidates-predicate
1171 `(string-match ,company-search-string candidate))))
1172 (company-update-candidates
1173 (company-apply-predicate company-candidates company-candidates-predicate))
1174 ;; Invalidate cache.
1175 (setq company-candidates-cache (cons company-prefix company-candidates)))
1177 (defun company-filter-printing-char ()
1179 (company-search-assert-enabled)
1180 (company-search-printing-char)
1181 (company-create-match-predicate)
1182 (company-call-frontends 'update))
1184 (defun company-search-kill-others ()
1185 "Limit the completion candidates to the ones matching the search string."
1187 (company-search-assert-enabled)
1188 (company-create-match-predicate)
1189 (company-search-mode 0)
1190 (company-call-frontends 'update))
1192 (defun company-search-abort ()
1193 "Abort searching the completion candidates."
1195 (company-search-assert-enabled)
1196 (company-set-selection company-search-old-selection t)
1197 (company-search-mode 0))
1199 (defun company-search-other-char ()
1201 (company-search-assert-enabled)
1202 (company-search-mode 0)
1203 (when last-input-event
1204 (clear-this-command-keys t)
1205 (setq unread-command-events (list last-input-event))))
1207 (defvar company-search-map
1209 (keymap (make-keymap)))
1210 (if (fboundp 'max-char)
1211 (set-char-table-range (nth 1 keymap) (cons #x100 (max-char))
1212 'company-search-printing-char)
1214 ;; obselete in Emacs 23
1215 (let ((l (generic-character-list))
1216 (table (nth 1 keymap)))
1218 (set-char-table-default table (car l) 'company-search-printing-char)
1219 (setq l (cdr l))))))
1220 (define-key keymap [t] 'company-search-other-char)
1222 (define-key keymap (make-string 1 i) 'company-search-other-char)
1225 (define-key keymap (vector i) 'company-search-printing-char)
1227 (let ((meta-map (make-sparse-keymap)))
1228 (define-key keymap (char-to-string meta-prefix-char) meta-map)
1229 (define-key keymap [escape] meta-map))
1230 (define-key keymap (vector meta-prefix-char t) 'company-search-other-char)
1231 (define-key keymap "\e\e\e" 'company-search-other-char)
1232 (define-key keymap [escape escape escape] 'company-search-other-char)
1234 (define-key keymap "\C-g" 'company-search-abort)
1235 (define-key keymap "\C-s" 'company-search-repeat-forward)
1236 (define-key keymap "\C-r" 'company-search-repeat-backward)
1237 (define-key keymap "\C-o" 'company-search-kill-others)
1239 "Keymap used for incrementally searching the completion candidates.")
1241 (define-minor-mode company-search-mode
1242 "Search mode for completion candidates.
1243 Don't start this directly, use `company-search-candidates' or
1244 `company-filter-candidates'."
1245 nil company-search-lighter nil
1246 (if company-search-mode
1247 (if (company-manual-begin)
1249 (setq company-search-old-selection company-selection)
1250 (company-call-frontends 'update))
1251 (setq company-search-mode nil))
1252 (kill-local-variable 'company-search-string)
1253 (kill-local-variable 'company-search-lighter)
1254 (kill-local-variable 'company-search-old-selection)
1255 (company-enable-overriding-keymap company-active-map)))
1257 (defsubst company-search-assert-enabled ()
1258 (company-assert-enabled)
1259 (unless company-search-mode
1260 (company-uninstall-map)
1261 (error "Company not in search mode")))
1263 (defun company-search-candidates ()
1264 "Start searching the completion candidates incrementally.
1266 \\<company-search-map>Search can be controlled with the commands:
1267 - `company-search-repeat-forward' (\\[company-search-repeat-forward])
1268 - `company-search-repeat-backward' (\\[company-search-repeat-backward])
1269 - `company-search-abort' (\\[company-search-abort])
1271 Regular characters are appended to the search string.
1273 The command `company-search-kill-others' (\\[company-search-kill-others]) uses
1274 the search string to limit the completion candidates."
1276 (company-search-mode 1)
1277 (company-enable-overriding-keymap company-search-map))
1279 (defvar company-filter-map
1280 (let ((keymap (make-keymap)))
1281 (define-key keymap [remap company-search-printing-char]
1282 'company-filter-printing-char)
1283 (set-keymap-parent keymap company-search-map)
1285 "Keymap used for incrementally searching the completion candidates.")
1287 (defun company-filter-candidates ()
1288 "Start filtering the completion candidates incrementally.
1289 This works the same way as `company-search-candidates' immediately
1290 followed by `company-search-kill-others' after each input."
1292 (company-search-mode 1)
1293 (company-enable-overriding-keymap company-filter-map))
1295 ;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;
1297 (defun company-select-next ()
1298 "Select the next candidate in the list."
1300 (when (company-manual-begin)
1301 (company-set-selection (1+ company-selection))))
1303 (defun company-select-previous ()
1304 "Select the previous candidate in the list."
1306 (when (company-manual-begin)
1307 (company-set-selection (1- company-selection))))
1309 (defun company-select-mouse (event)
1310 "Select the candidate picked by the mouse."
1312 (when (nth 4 (event-start event))
1313 (company-set-selection (- (cdr (posn-actual-col-row (event-start event)))
1318 (defun company-complete-mouse (event)
1319 "Complete the candidate picked by the mouse."
1321 (when (company-select-mouse event)
1322 (company-complete-selection)))
1324 (defun company-complete-selection ()
1325 "Complete the selected candidate."
1327 (when (company-manual-begin)
1328 (company-finish (nth company-selection company-candidates))))
1330 (defun company-complete-common ()
1331 "Complete the common part of all candidates."
1333 (when (company-manual-begin)
1334 (if (and (not (cdr company-candidates))
1335 (equal company-common (car company-candidates)))
1336 (company-complete-selection)
1337 (insert (company-strip-prefix company-common)))))
1339 (defun company-complete ()
1340 "Complete the common part of all candidates or the current selection.
1341 The first time this is called, the common part is completed, the second time, or
1342 when the selection has been changed, the selected candidate is completed."
1344 (when (company-manual-begin)
1345 (if (or company-selection-changed
1346 (eq last-command 'company-complete-common))
1347 (call-interactively 'company-complete-selection)
1348 (call-interactively 'company-complete-common)
1349 (setq this-command 'company-complete-common))))
1351 (defun company-complete-number (n)
1352 "Complete the Nth candidate.
1353 To show the number next to the candidates in some back-ends, enable
1354 `company-show-numbers'."
1355 (when (company-manual-begin)
1356 (and (< n 1) (> n company-candidates-length)
1357 (error "No candidate number %d" n))
1359 (company-finish (nth n company-candidates))))
1361 ;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;
1363 (defconst company-space-strings-limit 100)
1365 (defconst company-space-strings
1367 (dotimes (i company-space-strings-limit)
1368 (push (make-string (- company-space-strings-limit 1 i) ?\ ) lst))
1369 (apply 'vector lst)))
1371 (defsubst company-space-string (len)
1372 (if (< len company-space-strings-limit)
1373 (aref company-space-strings len)
1374 (make-string len ?\ )))
1376 (defsubst company-safe-substring (str from &optional to)
1377 (let ((len (length str)))
1380 (if (and to (> to len))
1381 (concat (substring str from)
1382 (company-space-string (- to len)))
1383 (substring str from to)))))
1385 ;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;
1387 (defvar company-last-metadata nil)
1388 (make-variable-buffer-local 'company-last-metadata)
1390 (defun company-fetch-metadata ()
1391 (let ((selected (nth company-selection company-candidates)))
1392 (unless (equal selected (car company-last-metadata))
1393 (setq company-last-metadata
1394 (cons selected (company-call-backend 'meta selected))))
1395 (cdr company-last-metadata)))
1397 (defun company-doc-buffer (&optional string)
1398 (with-current-buffer (get-buffer-create "*Company meta-data*")
1402 (defmacro company--electric-do (&rest body)
1403 (declare (indent 0) (debug t))
1404 `(when (company-manual-begin)
1405 (save-window-excursion
1406 (let ((height (window-height))
1407 (row (company--row)))
1409 (and (< (window-height) height)
1410 (< (- (window-height) row 2) company-tooltip-limit)
1411 (recenter (- (window-height) row 2)))
1412 (while (eq 'scroll-other-window
1413 (key-binding (vector (list (read-event)))))
1414 (call-interactively 'scroll-other-window))
1415 (when last-input-event
1416 (clear-this-command-keys t)
1417 (setq unread-command-events (list last-input-event)))))))
1419 (defun company-show-doc-buffer ()
1420 "Temporarily show a buffer with the complete documentation for the selection."
1422 (company--electric-do
1423 (let ((selected (nth company-selection company-candidates)))
1424 (display-buffer (or (company-call-backend 'doc-buffer selected)
1425 (error "No documentation available")) t))))
1426 (put 'company-show-doc-buffer 'company-keep t)
1428 (defun company-show-location ()
1429 "Temporarily display a buffer showing the selected candidate in context."
1431 (company--electric-do
1432 (let* ((selected (nth company-selection company-candidates))
1433 (location (company-call-backend 'location selected))
1434 (pos (or (cdr location) (error "No location available")))
1435 (buffer (or (and (bufferp (car location)) (car location))
1436 (find-file-noselect (car location) t))))
1437 (with-selected-window (display-buffer buffer t)
1438 (if (bufferp (car location))
1441 (set-window-start nil (point))))))
1442 (put 'company-show-location 'company-keep t)
1444 ;;; package functions ;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;
1446 (defvar company-callback nil)
1447 (make-variable-buffer-local 'company-callback)
1449 (defvar company-begin-with-marker nil)
1450 (make-variable-buffer-local 'company-begin-with-marker)
1452 (defun company-remove-callback (&optional ignored)
1453 (remove-hook 'company-completion-finished-hook company-callback t)
1454 (remove-hook 'company-completion-cancelled-hook 'company-remove-callback t)
1455 (remove-hook 'company-completion-finished-hook 'company-remove-callback t)
1456 (when company-begin-with-marker
1457 (set-marker company-begin-with-marker nil)))
1459 (defun company-begin-backend (backend &optional callback)
1460 "Start a completion at point using BACKEND."
1461 (interactive (let ((val (completing-read "Company back-end: "
1463 'functionp nil "company-")))
1465 (list (intern val)))))
1466 (when (setq company-callback callback)
1467 (add-hook 'company-completion-finished-hook company-callback nil t))
1468 (add-hook 'company-completion-cancelled-hook 'company-remove-callback nil t)
1469 (add-hook 'company-completion-finished-hook 'company-remove-callback nil t)
1470 (setq company-backend backend)
1471 ;; Return non-nil if active.
1472 (or (company-manual-begin)
1473 (error "Cannot complete at point")))
1475 (defun company-begin-with (candidates
1476 &optional prefix-length require-match callback)
1477 "Start a completion at point.
1478 CANDIDATES is the list of candidates to use and PREFIX-LENGTH is the length of
1479 the prefix that already is in the buffer before point. It defaults to 0.
1481 CALLBACK is a function called with the selected result if the user successfully
1482 completes the input.
1485 \(company-begin-with '\(\"foo\" \"foobar\" \"foobarbaz\"\)\)"
1486 (setq company-begin-with-marker (copy-marker (point) t))
1487 (company-begin-backend
1488 `(lambda (command &optional arg &rest ignored)
1490 ((eq command 'prefix)
1491 (when (equal (point) (marker-position company-begin-with-marker))
1492 (buffer-substring ,(- (point) (or prefix-length 0)) (point))))
1493 ((eq command 'candidates)
1494 (all-completions arg ',candidates))
1495 ((eq command 'require-match)
1499 ;;; pseudo-tooltip ;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;
1501 (defvar company-pseudo-tooltip-overlay nil)
1502 (make-variable-buffer-local 'company-pseudo-tooltip-overlay)
1504 (defvar company-tooltip-offset 0)
1505 (make-variable-buffer-local 'company-tooltip-offset)
1507 (defun company-pseudo-tooltip-update-offset (selection num-lines limit)
1510 (setq company-tooltip-offset
1511 (max (min selection company-tooltip-offset)
1512 (- selection -1 limit)))
1514 (when (<= company-tooltip-offset 1)
1516 (setq company-tooltip-offset 0))
1518 (when (>= company-tooltip-offset (- num-lines limit 1))
1520 (when (= selection (1- num-lines))
1521 (decf company-tooltip-offset)
1522 (when (<= company-tooltip-offset 1)
1523 (setq company-tooltip-offset 0)
1530 (defsubst company-round-tab (arg)
1531 (* (/ (+ arg tab-width) tab-width) tab-width))
1533 (defun company-untabify (str)
1534 (let* ((pieces (split-string str "\t"))
1537 (setcar copy (company-safe-substring
1538 (car copy) 0 (company-round-tab (string-width (car copy)))))
1540 (apply 'concat pieces)))
1542 (defun company-fill-propertize (line width selected)
1543 (setq line (company-safe-substring line 0 width))
1544 (add-text-properties 0 width '(face company-tooltip
1545 mouse-face company-tooltip-mouse)
1547 (add-text-properties 0 (length company-common)
1548 '(face company-tooltip-common
1549 mouse-face company-tooltip-mouse)
1552 (if (and company-search-string
1553 (string-match (regexp-quote company-search-string) line
1554 (length company-prefix)))
1556 (add-text-properties (match-beginning 0) (match-end 0)
1557 '(face company-tooltip-selection)
1559 (when (< (match-beginning 0) (length company-common))
1560 (add-text-properties (match-beginning 0) (length company-common)
1561 '(face company-tooltip-common-selection)
1563 (add-text-properties 0 width '(face company-tooltip-selection
1564 mouse-face company-tooltip-selection)
1566 (add-text-properties 0 (length company-common)
1567 '(face company-tooltip-common-selection
1568 mouse-face company-tooltip-selection)
1574 (defun company-buffer-lines (beg end)
1576 (let ((row (company--row))
1578 (while (and (equal (move-to-window-line (incf row)) row)
1580 (push (buffer-substring beg (min end (1- (point)))) lines)
1582 (unless (eq beg end)
1583 (push (buffer-substring beg end) lines))
1586 (defsubst company-modify-line (old new offset)
1587 (concat (company-safe-substring old 0 offset)
1589 (company-safe-substring old (+ offset (length new)))))
1591 (defsubst company--length-limit (lst limit)
1592 (if (nthcdr limit lst)
1596 (defun company--replacement-string (lines old column nl &optional align-top)
1598 (let ((width (length (car lines))))
1599 (when (> width (- (window-width) column))
1600 (setq column (max 0 (- (window-width) width)))))
1604 ;; untouched lines first
1605 (dotimes (i (- (length old) (length lines)))
1606 (push (pop old) new)))
1607 ;; length into old lines.
1609 (push (company-modify-line (pop old) (pop lines) column) new))
1610 ;; Append whole new lines.
1612 (push (concat (company-space-string column) (pop lines)) new))
1613 (concat (when nl "\n")
1614 (mapconcat 'identity (nreverse new) "\n")
1617 (defun company--create-lines (selection limit)
1619 (let ((len company-candidates-length)
1628 ;; Scroll to offset.
1629 (setq limit (company-pseudo-tooltip-update-offset selection len limit))
1631 (when (> company-tooltip-offset 0)
1632 (setq previous (format "...(%d)" company-tooltip-offset)))
1634 (setq remainder (- len limit company-tooltip-offset)
1635 remainder (when (> remainder 0)
1636 (setq remainder (format "...(%d)" remainder))))
1638 (decf selection company-tooltip-offset)
1639 (setq width (max (length previous) (length remainder))
1640 lines (nthcdr company-tooltip-offset company-candidates)
1645 (setq width (max (length (pop lines-copy)) width)))
1646 (setq width (min width (window-width)))
1648 (setq lines-copy lines)
1650 ;; number can make tooltip too long
1651 (when company-show-numbers
1652 (setq numbered company-tooltip-offset))
1655 (push (propertize (company-safe-substring previous 0 width)
1656 'face 'company-tooltip)
1660 (push (company-fill-propertize
1661 (if (>= numbered 10)
1662 (company-reformat (pop lines))
1665 (company-safe-substring (company-reformat (pop lines))
1668 width (equal i selection))
1672 (push (propertize (company-safe-substring remainder 0 width)
1673 'face 'company-tooltip)
1676 (setq lines (nreverse new))))
1680 (defsubst company--window-inner-height ()
1681 (let ((edges (window-inside-edges (selected-window))))
1682 (- (nth 3 edges) (nth 1 edges))))
1684 (defsubst company--pseudo-tooltip-height ()
1685 "Calculate the appropriate tooltip height.
1686 Returns a negative number if the tooltip should be displayed above point."
1687 (let* ((lines (count-lines (window-start) (point-at-bol)))
1688 (below (- (company--window-inner-height) 1 lines)))
1689 (if (and (< below (min company-tooltip-minimum company-candidates-length))
1691 (- (max 3 (min company-tooltip-limit lines)))
1692 (max 3 (min company-tooltip-limit below)))))
1694 (defun company-pseudo-tooltip-show (row column selection)
1695 (company-pseudo-tooltip-hide)
1700 (let* ((height (company--pseudo-tooltip-height))
1704 (setq row (+ row height -1)
1707 (let* ((nl (< (move-to-window-line row) row))
1709 (end (save-excursion
1710 (move-to-window-line (+ row (abs height)))
1712 (ov (make-overlay beg end))
1713 (args (list (mapcar 'company-untabify
1714 (company-buffer-lines beg end))
1717 (setq company-pseudo-tooltip-overlay ov)
1718 (overlay-put ov 'company-replacement-args args)
1719 (overlay-put ov 'company-before
1720 (apply 'company--replacement-string
1721 (company--create-lines selection (abs height))
1724 (overlay-put ov 'company-column column)
1725 (overlay-put ov 'company-height (abs height))
1726 (overlay-put ov 'window (selected-window))))))
1728 (defun company-pseudo-tooltip-show-at-point (pos)
1729 (let ((col-row (company--col-row pos)))
1731 (company-pseudo-tooltip-show (1+ (cdr col-row)) (car col-row)
1732 company-selection))))
1734 (defun company-pseudo-tooltip-edit (lines selection)
1735 (let ((column (overlay-get company-pseudo-tooltip-overlay 'company-column))
1736 (height (overlay-get company-pseudo-tooltip-overlay 'company-height)))
1737 (overlay-put company-pseudo-tooltip-overlay 'company-before
1738 (apply 'company--replacement-string
1739 (company--create-lines selection height)
1740 (overlay-get company-pseudo-tooltip-overlay
1741 'company-replacement-args)))))
1743 (defun company-pseudo-tooltip-hide ()
1744 (when company-pseudo-tooltip-overlay
1745 (delete-overlay company-pseudo-tooltip-overlay)
1746 (setq company-pseudo-tooltip-overlay nil)))
1748 (defun company-pseudo-tooltip-hide-temporarily ()
1749 (when (overlayp company-pseudo-tooltip-overlay)
1750 (overlay-put company-pseudo-tooltip-overlay 'invisible nil)
1751 (overlay-put company-pseudo-tooltip-overlay 'before-string nil)))
1753 (defun company-pseudo-tooltip-unhide ()
1754 (when company-pseudo-tooltip-overlay
1755 (overlay-put company-pseudo-tooltip-overlay 'invisible t)
1756 (overlay-put company-pseudo-tooltip-overlay 'before-string
1757 (overlay-get company-pseudo-tooltip-overlay 'company-before))
1758 (overlay-put company-pseudo-tooltip-overlay 'window (selected-window))))
1760 (defun company-pseudo-tooltip-frontend (command)
1761 "A `company-mode' front-end similar to a tool-tip but based on overlays."
1763 ('pre-command (company-pseudo-tooltip-hide-temporarily))
1765 (let ((old-height (if (overlayp company-pseudo-tooltip-overlay)
1766 (overlay-get company-pseudo-tooltip-overlay
1769 (new-height (company--pseudo-tooltip-height)))
1770 (unless (and (>= (* old-height new-height) 0)
1771 (>= (abs old-height) (abs new-height)))
1773 (company-pseudo-tooltip-show-at-point (- (point)
1774 (length company-prefix)))))
1775 (company-pseudo-tooltip-unhide))
1776 ('hide (company-pseudo-tooltip-hide)
1777 (setq company-tooltip-offset 0))
1778 ('update (when (overlayp company-pseudo-tooltip-overlay)
1779 (company-pseudo-tooltip-edit company-candidates
1780 company-selection)))))
1782 (defun company-pseudo-tooltip-unless-just-one-frontend (command)
1783 "`company-pseudo-tooltip-frontend', but not shown for single candidates."
1784 (unless (and (eq command 'post-command)
1785 (not (cdr company-candidates)))
1786 (company-pseudo-tooltip-frontend command)))
1788 ;;; overlay ;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;
1790 (defvar company-preview-overlay nil)
1791 (make-variable-buffer-local 'company-preview-overlay)
1793 (defun company-preview-show-at-point (pos)
1794 (company-preview-hide)
1796 (setq company-preview-overlay (make-overlay pos pos))
1798 (let ((completion(nth company-selection company-candidates)))
1799 (setq completion (propertize completion 'face 'company-preview))
1800 (add-text-properties 0 (length company-common)
1801 '(face company-preview-common) completion)
1803 ;; Add search string
1804 (and company-search-string
1805 (string-match (regexp-quote company-search-string) completion)
1806 (add-text-properties (match-beginning 0)
1808 '(face company-preview-search)
1811 (setq completion (company-strip-prefix completion))
1813 (and (equal pos (point))
1814 (not (equal completion ""))
1815 (add-text-properties 0 1 '(cursor t) completion))
1817 (overlay-put company-preview-overlay 'after-string completion)
1818 (overlay-put company-preview-overlay 'window (selected-window))))
1820 (defun company-preview-hide ()
1821 (when company-preview-overlay
1822 (delete-overlay company-preview-overlay)
1823 (setq company-preview-overlay nil)))
1825 (defun company-preview-frontend (command)
1826 "A `company-mode' front-end showing the selection as if it had been inserted."
1828 ('pre-command (company-preview-hide))
1829 ('post-command (company-preview-show-at-point (point)))
1830 ('hide (company-preview-hide))))
1832 (defun company-preview-if-just-one-frontend (command)
1833 "`company-preview-frontend', but only shown for single candidates."
1834 (unless (and (eq command 'post-command)
1835 (cdr company-candidates))
1836 (company-preview-frontend command)))
1838 ;;; echo ;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;
1840 (defvar company-echo-last-msg nil)
1841 (make-variable-buffer-local 'company-echo-last-msg)
1843 (defvar company-echo-timer nil)
1845 (defvar company-echo-delay .1)
1847 (defun company-echo-show (&optional getter)
1849 (setq company-echo-last-msg (funcall getter)))
1850 (let ((message-log-max nil))
1851 (if company-echo-last-msg
1852 (message "%s" company-echo-last-msg)
1855 (defsubst company-echo-show-soon (&optional getter)
1856 (when company-echo-timer
1857 (cancel-timer company-echo-timer))
1858 (setq company-echo-timer (run-with-timer company-echo-delay nil
1859 'company-echo-show getter)))
1861 (defun company-echo-format ()
1863 (let ((limit (window-width (minibuffer-window)))
1865 ;; Roll to selection.
1866 (candidates (nthcdr company-selection company-candidates))
1867 (i (if company-show-numbers company-selection 99999))
1871 (setq comp (company-reformat (pop candidates))
1872 len (+ len 1 (length comp)))
1876 (setq comp (propertize (format "%d: %s" i comp)
1877 'face 'company-echo))
1880 (add-text-properties 3 (+ 3 (length company-common))
1881 '(face company-echo-common) comp))
1882 (setq comp (propertize comp 'face 'company-echo))
1883 (add-text-properties 0 (length company-common)
1884 '(face company-echo-common) comp))
1886 (setq candidates nil)
1889 (mapconcat 'identity (nreverse msg) " ")))
1891 (defun company-echo-strip-common-format ()
1893 (let ((limit (window-width (minibuffer-window)))
1894 (len (+ (length company-prefix) 2))
1895 ;; Roll to selection.
1896 (candidates (nthcdr company-selection company-candidates))
1897 (i (if company-show-numbers company-selection 99999))
1901 (setq comp (company-strip-prefix (pop candidates))
1902 len (+ len 2 (length comp)))
1905 (setq comp (format "%s (%d)" comp i))
1909 (setq candidates nil)
1910 (push (propertize comp 'face 'company-echo) msg)))
1912 (concat (propertize company-prefix 'face 'company-echo-common) "{"
1913 (mapconcat 'identity (nreverse msg) ", ")
1916 (defun company-echo-hide ()
1917 (when company-echo-timer
1918 (cancel-timer company-echo-timer))
1919 (unless (equal company-echo-last-msg "")
1920 (setq company-echo-last-msg "")
1921 (company-echo-show)))
1923 (defun company-echo-frontend (command)
1924 "A `company-mode' front-end showing the candidates in the echo area."
1926 ('pre-command (company-echo-show-soon))
1927 ('post-command (company-echo-show-soon 'company-echo-format))
1928 ('hide (company-echo-hide))))
1930 (defun company-echo-strip-common-frontend (command)
1931 "A `company-mode' front-end showing the candidates in the echo area."
1933 ('pre-command (company-echo-show-soon))
1934 ('post-command (company-echo-show-soon 'company-echo-strip-common-format))
1935 ('hide (company-echo-hide))))
1937 (defun company-echo-metadata-frontend (command)
1938 "A `company-mode' front-end showing the documentation in the echo area."
1940 ('pre-command (company-echo-show-soon))
1941 ('post-command (company-echo-show-soon 'company-fetch-metadata))
1942 ('hide (company-echo-hide))))
1945 ;;; company.el ends here