1 ;;; company.el --- Modular in-buffer completion framework -*- lexical-binding: t -*-
3 ;; Copyright (C) 2009-2013 Free Software Foundation, Inc.
5 ;; Author: Nikolaj Schumacher
6 ;; Maintainer: Dmitry Gutov <dgutov@yandex.ru>
8 ;; Keywords: abbrev, convenience, matching
9 ;; URL: http://company-mode.github.io/
10 ;; Compatibility: GNU Emacs 22.x, GNU Emacs 23.x, GNU Emacs 24.x
12 ;; This file is part of GNU Emacs.
14 ;; GNU Emacs is free software: you can redistribute it and/or modify
15 ;; it under the terms of the GNU General Public License as published by
16 ;; the Free Software Foundation, either version 3 of the License, or
17 ;; (at your option) any later version.
19 ;; GNU Emacs is distributed in the hope that it will be useful,
20 ;; but WITHOUT ANY WARRANTY; without even the implied warranty of
21 ;; MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
22 ;; GNU General Public License for more details.
24 ;; You should have received a copy of the GNU General Public License
25 ;; along with GNU Emacs. If not, see <http://www.gnu.org/licenses/>.
29 ;; Company is a modular completion mechanism. Modules for retrieving completion
30 ;; candidates are called back-ends, modules for displaying them are front-ends.
32 ;; Company comes with many back-ends, e.g. `company-elisp'. These are
33 ;; distributed in separate files and can be used individually.
35 ;; Place company.el and the back-ends you want to use in a directory and add the
36 ;; following to your .emacs:
37 ;; (add-to-list 'load-path "/path/to/company")
38 ;; (autoload 'company-mode "company" nil t)
40 ;; Enable company-mode with M-x company-mode. For further information look at
41 ;; the documentation for `company-mode' (C-h f company-mode RET)
43 ;; If you want to start a specific back-end, call it interactively or use
44 ;; `company-begin-backend'. For example:
45 ;; M-x company-abbrev will prompt for and insert an abbrev.
47 ;; To write your own back-end, look at the documentation for `company-backends'.
48 ;; Here is a simple example completing "foo":
50 ;; (defun company-my-backend (command &optional arg &rest ignored)
52 ;; (prefix (when (looking-back "foo\\>")
54 ;; (candidates (list "foobar" "foobaz" "foobarbaz"))
55 ;; (meta (format "This value is named %s" arg))))
57 ;; Sometimes it is a good idea to mix several back-ends together, for example to
58 ;; enrich gtags with dabbrev-code results (to emulate local variables).
59 ;; To do this, add a list with both back-ends as an element in company-backends.
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 ;; See NEWS.md in the repository.
72 (eval-when-compile (require 'cl))
74 ;; FIXME: Use `user-error'.
75 (add-to-list 'debug-ignored-errors "^.* frontend cannot be used twice$")
76 (add-to-list 'debug-ignored-errors "^Echo area cannot be used twice$")
77 (add-to-list 'debug-ignored-errors "^No \\(document\\|loc\\)ation available$")
78 (add-to-list 'debug-ignored-errors "^Company not ")
79 (add-to-list 'debug-ignored-errors "^No candidate number ")
80 (add-to-list 'debug-ignored-errors "^Cannot complete at point$")
81 (add-to-list 'debug-ignored-errors "^No other back-end$")
84 "Extensible inline text completion mechanism"
89 (defface company-tooltip
90 '((default :foreground "black")
91 (((class color) (min-colors 88) (background light))
92 (:background "cornsilk"))
93 (((class color) (min-colors 88) (background dark))
94 (:background "yellow")))
95 "Face used for the tooltip.")
97 (defface company-tooltip-selection
98 '((default :inherit company-tooltip)
99 (((class color) (min-colors 88) (background light))
100 (:background "light blue"))
101 (((class color) (min-colors 88) (background dark))
102 (:background "orange1"))
103 (t (:background "green")))
104 "Face used for the selection in the tooltip.")
106 (defface company-tooltip-mouse
107 '((default :inherit highlight))
108 "Face used for the tooltip item under the mouse.")
110 (defface company-tooltip-common
111 '((default :inherit company-tooltip)
112 (((background light))
113 :foreground "darkred")
116 "Face used for the common completion in the tooltip.")
118 (defface company-tooltip-common-selection
119 '((default :inherit company-tooltip-selection)
120 (((background light))
121 :foreground "darkred")
124 "Face used for the selected common completion in the tooltip.")
126 (defface company-preview
127 '((t :background "blue4"
128 :foreground "wheat"))
129 "Face used for the completion preview.")
131 (defface company-preview-common
132 '((t :inherit company-preview
134 "Face used for the common part of the completion preview.")
136 (defface company-preview-search
137 '((t :inherit company-preview
138 :background "blue1"))
139 "Face used for the search string in the completion preview.")
141 (defface company-echo nil
142 "Face used for completions in the echo area.")
144 (defface company-echo-common
145 '((((background dark)) (:foreground "firebrick1"))
146 (((background light)) (:background "firebrick4")))
147 "Face used for the common part of completions in the echo area.")
149 (defun company-frontends-set (variable value)
151 (let ((remainder value))
152 (setcdr remainder (delq (car remainder) (cdr remainder))))
153 (and (memq 'company-pseudo-tooltip-unless-just-one-frontend value)
154 (memq 'company-pseudo-tooltip-frontend value)
155 (error "Pseudo tooltip frontend cannot be used twice"))
156 (and (memq 'company-preview-if-just-one-frontend value)
157 (memq 'company-preview-frontend value)
158 (error "Preview frontend cannot be used twice"))
159 (and (memq 'company-echo value)
160 (memq 'company-echo-metadata-frontend value)
161 (error "Echo area cannot be used twice"))
162 ;; preview must come last
163 (dolist (f '(company-preview-if-just-one-frontend company-preview-frontend))
165 (setq value (append (delq f value) (list f)))))
166 (set variable value))
168 (defcustom company-frontends '(company-pseudo-tooltip-unless-just-one-frontend
169 company-preview-if-just-one-frontend
170 company-echo-metadata-frontend)
171 "The list of active front-ends (visualizations).
172 Each front-end is a function that takes one argument. It is called with
173 one of the following arguments:
175 `show': When the visualization should start.
177 `hide': When the visualization should end.
179 `update': When the data has been updated.
181 `pre-command': Before every command that is executed while the
182 visualization is active.
184 `post-command': After every command that is executed while the
185 visualization is active.
187 The visualized data is stored in `company-prefix', `company-candidates',
188 `company-common', `company-selection', `company-point' and
189 `company-search-string'."
190 :set 'company-frontends-set
191 :type '(repeat (choice (const :tag "echo" company-echo-frontend)
192 (const :tag "echo, strip common"
193 company-echo-strip-common-frontend)
194 (const :tag "show echo meta-data in echo"
195 company-echo-metadata-frontend)
196 (const :tag "pseudo tooltip"
197 company-pseudo-tooltip-frontend)
198 (const :tag "pseudo tooltip, multiple only"
199 company-pseudo-tooltip-unless-just-one-frontend)
200 (const :tag "preview" company-preview-frontend)
201 (const :tag "preview, unique only"
202 company-preview-if-just-one-frontend)
203 (function :tag "custom function" nil))))
205 (defcustom company-tooltip-limit 10
206 "The maximum number of candidates in the tooltip"
209 (defcustom company-tooltip-minimum 6
210 "The minimum height of the tooltip.
211 If this many lines are not available, prefer to display the tooltip above."
214 (defvar company-safe-backends
215 '((company-abbrev . "Abbrev")
216 (company-capf . "completion-at-point-functions")
217 (company-clang . "Clang")
218 (company-cmake . "CMake")
219 (company-css . "CSS")
220 (company-dabbrev . "dabbrev for plain text")
221 (company-dabbrev-code . "dabbrev for code")
222 (company-eclim . "Eclim (an Eclipse interface)")
223 (company-elisp . "Emacs Lisp")
224 (company-etags . "etags")
225 (company-files . "Files")
226 (company-gtags . "GNU Global")
227 (company-ispell . "Ispell")
228 (company-keywords . "Programming language keywords")
229 (company-nxml . "nxml")
230 (company-oddmuse . "Oddmuse")
231 (company-pysmell . "PySmell")
232 (company-ropemacs . "ropemacs")
233 (company-semantic . "Semantic")
234 (company-tempo . "Tempo templates")
235 (company-xcode . "Xcode")))
236 (put 'company-safe-backends 'risky-local-variable t)
238 (defun company-safe-backends-p (backends)
239 (and (consp backends)
240 (not (dolist (backend backends)
241 (unless (if (consp backend)
242 (company-safe-backends-p backend)
243 (assq backend company-safe-backends))
246 (defcustom company-backends '(company-elisp company-nxml company-css
247 company-eclim company-semantic company-clang
248 company-xcode company-ropemacs company-cmake
249 (company-gtags company-etags company-dabbrev-code
251 company-oddmuse company-files company-dabbrev)
252 "The list of active back-ends (completion engines).
253 Each list elements can itself be a list of back-ends. In that case their
254 completions are merged. Otherwise only the first matching back-end returns
257 `company-begin-backend' can be used to start a specific back-end,
258 `company-other-backend' will skip to the next matching back-end in the list.
260 Each back-end is a function that takes a variable number of arguments.
261 The first argument is the command requested from the back-end. It is one
264 `prefix': The back-end should return the text to be completed. It must be
265 text immediately before point. Returning nil passes control to the next
266 back-end. The function should return `stop' if it should complete but
267 cannot \(e.g. if it is in the middle of a string\). Instead of a string,
268 the back-end may return a cons where car is the prefix and cdr is used in
269 `company-minimum-prefix-length' test. It's either number or t, in which
270 case the test automatically succeeds.
272 `candidates': The second argument is the prefix to be completed. The
273 return value should be a list of candidates that start with the prefix.
277 `sorted': Return t here to indicate that the candidates are sorted and will
278 not need to be sorted again.
280 `duplicates': If non-nil, company will take care of removing duplicates
283 `no-cache': Usually company doesn't ask for candidates again as completion
284 progresses, unless the back-end returns t for this command. The second
285 argument is the latest prefix.
287 `meta': The second argument is a completion candidate. Return a (short)
288 documentation string for it.
290 `doc-buffer': The second argument is a completion candidate. Return a
291 buffer with documentation for it. Preferably use `company-doc-buffer',
293 `location': The second argument is a completion candidate. Return the cons
294 of buffer and buffer location, or of file and line number where the
295 completion candidate was defined.
297 `require-match': If this returns t, the user is not allowed to enter
298 anything not offered as a candidate. Use with care! The default value nil
299 gives the user that choice with `company-require-match'. Return value
300 `never' overrides that option the other way around.
302 `init': Called once for each buffer. The back-end can check for external
303 programs and files and load any required libraries. Raising an error here
304 will show up in message log once, and the back-end will not be used for
307 `post-completion': Called after a completion candidate has been inserted
308 into the buffer. The second argument is the candidate. Can be used to
309 modify it, e.g. to expand a snippet.
311 The back-end should return nil for all commands it does not support or
312 does not know about. It should also be callable interactively and use
313 `company-begin-backend' to start itself in that case."
317 ,@(mapcar (lambda (b) `(const :tag ,(cdr b) ,(car b)))
318 company-safe-backends)
319 (symbol :tag "User defined")
320 (repeat :tag "Merged Back-ends"
321 (choice :tag "Back-end"
322 ,@(mapcar (lambda (b)
323 `(const :tag ,(cdr b) ,(car b)))
324 company-safe-backends)
325 (symbol :tag "User defined"))))))
327 (put 'company-backends 'safe-local-variable 'company-safe-backends-p)
329 (defcustom company-completion-started-hook nil
330 "Hook run when company starts completing.
331 The hook is called with one argument that is non-nil if the completion was
335 (defcustom company-completion-cancelled-hook nil
336 "Hook run when company cancels completing.
337 The hook is called with one argument that is non-nil if the completion was
341 (defcustom company-completion-finished-hook nil
342 "Hook run when company successfully completes.
343 The hook is called with the selected candidate as an argument.
345 If you indend to use it to post-process candidates from a specific
346 back-end, consider using the `post-completion' command instead."
349 (defcustom company-minimum-prefix-length 3
350 "The minimum prefix length for automatic completion."
351 :type '(integer :tag "prefix length"))
353 (defcustom company-require-match 'company-explicit-action-p
354 "If enabled, disallow non-matching input.
355 This can be a function do determine if a match is required.
357 This can be overridden by the back-end, if it returns t or `never' to
358 `require-match'. `company-auto-complete' also takes precedence over this."
359 :type '(choice (const :tag "Off" nil)
360 (function :tag "Predicate function")
361 (const :tag "On, if user interaction took place"
362 'company-explicit-action-p)
363 (const :tag "On" t)))
365 (defcustom company-auto-complete nil
366 "Determines when to auto-complete.
367 If this is enabled, all characters from `company-auto-complete-chars'
368 complete the selected completion. This can also be a function."
369 :type '(choice (const :tag "Off" nil)
370 (function :tag "Predicate function")
371 (const :tag "On, if user interaction took place"
372 'company-explicit-action-p)
373 (const :tag "On" t)))
375 (defcustom company-auto-complete-chars '(?\ ?\) ?.)
376 "Determines which characters trigger an automatic completion.
377 See `company-auto-complete'. If this is a string, each string character
378 causes completion. If it is a list of syntax description characters (see
379 `modify-syntax-entry'), all characters with that syntax auto-complete.
381 This can also be a function, which is called with the new input and should
382 return non-nil if company should auto-complete.
384 A character that is part of a valid candidate never triggers auto-completion."
385 :type '(choice (string :tag "Characters")
387 (const :tag "Whitespace" ?\ )
388 (const :tag "Symbol" ?_)
389 (const :tag "Opening parentheses" ?\()
390 (const :tag "Closing parentheses" ?\))
391 (const :tag "Word constituent" ?w)
392 (const :tag "Punctuation." ?.)
393 (const :tag "String quote." ?\")
394 (const :tag "Paired delimiter." ?$)
395 (const :tag "Expression quote or prefix operator." ?\')
396 (const :tag "Comment starter." ?<)
397 (const :tag "Comment ender." ?>)
398 (const :tag "Character-quote." ?/)
399 (const :tag "Generic string fence." ?|)
400 (const :tag "Generic comment fence." ?!))
401 (function :tag "Predicate function")))
403 (defcustom company-idle-delay .7
404 "The idle delay in seconds until automatic completions starts.
405 A value of nil means never complete automatically, t means complete
406 immediately when a prefix of `company-minimum-prefix-length' is reached."
407 :type '(choice (const :tag "never (nil)" nil)
408 (const :tag "immediate (t)" t)
409 (number :tag "seconds")))
411 (defcustom company-begin-commands t
412 "A list of commands following which company will start completing.
413 If this is t, it will complete after any command. See `company-idle-delay'.
415 Alternatively any command with a non-nil `company-begin' property is treated
416 as if it was on this list."
417 :type '(choice (const :tag "Any command" t)
418 (const :tag "Self insert command" '(self-insert-command))
419 (repeat :tag "Commands" function)))
421 (defcustom company-show-numbers nil
422 "If enabled, show quick-access numbers for the first ten candidates."
423 :type '(choice (const :tag "off" nil)
424 (const :tag "on" t)))
426 (defvar company-end-of-buffer-workaround t
427 "Work around a visualization bug when completing at the end of the buffer.
428 The work-around consists of adding a newline.")
430 ;;; mode ;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;
432 (defvar company-mode-map (make-sparse-keymap)
433 "Keymap used by `company-mode'.")
435 (defvar company-active-map
436 (let ((keymap (make-sparse-keymap)))
437 (define-key keymap "\e\e\e" 'company-abort)
438 (define-key keymap "\C-g" 'company-abort)
439 (define-key keymap (kbd "M-n") 'company-select-next)
440 (define-key keymap (kbd "M-p") 'company-select-previous)
441 (define-key keymap (kbd "<down>") 'company-select-next-or-abort)
442 (define-key keymap (kbd "<up>") 'company-select-previous-or-abort)
443 (define-key keymap [down-mouse-1] 'ignore)
444 (define-key keymap [down-mouse-3] 'ignore)
445 (define-key keymap [mouse-1] 'company-complete-mouse)
446 (define-key keymap [mouse-3] 'company-select-mouse)
447 (define-key keymap [up-mouse-1] 'ignore)
448 (define-key keymap [up-mouse-3] 'ignore)
449 (define-key keymap [return] 'company-complete-selection)
450 (define-key keymap (kbd "RET") 'company-complete-selection)
451 (define-key keymap [tab] 'company-complete-common)
452 (define-key keymap (kbd "TAB") 'company-complete-common)
453 (define-key keymap (kbd "<f1>") 'company-show-doc-buffer)
454 (define-key keymap "\C-w" 'company-show-location)
455 (define-key keymap "\C-s" 'company-search-candidates)
456 (define-key keymap "\C-\M-s" 'company-filter-candidates)
458 (define-key keymap (vector (+ (aref (kbd "M-0") 0) i))
459 `(lambda () (interactive) (company-complete-number ,i))))
462 "Keymap that is enabled during an active completion.")
464 (defvar company--disabled-backends nil)
466 (defun company-init-backend (backend)
467 (and (symbolp backend)
468 (not (fboundp backend))
469 (ignore-errors (require backend nil t)))
471 (if (or (symbolp backend)
475 (funcall backend 'init)
476 (put backend 'company-init t))
478 (put backend 'company-init 'failed)
479 (unless (memq backend company--disabled-backends)
480 (message "Company back-end '%s' could not be initialized:\n%s"
481 backend (error-message-string err)))
482 (pushnew backend company--disabled-backends)
484 (mapc 'company-init-backend backend)))
486 (defvar company-default-lighter " company")
488 (defvar company-lighter company-default-lighter)
489 (make-variable-buffer-local 'company-lighter)
492 (define-minor-mode company-mode
493 "\"complete anything\"; is an in-buffer completion framework.
494 Completion starts automatically, depending on the values
495 `company-idle-delay' and `company-minimum-prefix-length'.
497 Completion can be controlled with the commands:
498 `company-complete-common', `company-complete-selection', `company-complete',
499 `company-select-next', `company-select-previous'. If these commands are
500 called before `company-idle-delay', completion will also start.
502 Completions can be searched with `company-search-candidates' or
503 `company-filter-candidates'. These can be used while completion is
506 The completion data is retrieved using `company-backends' and displayed
507 using `company-frontends'. If you want to start a specific back-end, call
508 it interactively or use `company-begin-backend'.
510 regular keymap (`company-mode-map'):
513 keymap during active completions (`company-active-map'):
515 \\{company-active-map}"
516 nil company-lighter company-mode-map
519 (add-hook 'pre-command-hook 'company-pre-command nil t)
520 (add-hook 'post-command-hook 'company-post-command nil t)
521 (mapc 'company-init-backend company-backends))
522 (remove-hook 'pre-command-hook 'company-pre-command t)
523 (remove-hook 'post-command-hook 'company-post-command t)
525 (kill-local-variable 'company-point)))
527 (defcustom company-global-modes t
528 "Modes for which `company-mode' mode is turned on by `global-company-mode'.
529 If nil, means no modes. If t, then all major modes have it turned on.
530 If a list, it should be a list of `major-mode' symbol names for which
531 `company-mode' should be automatically turned on. The sense of the list is
532 negated if it begins with `not'. For example:
534 means that `company-mode' is turned on for buffers in C and C++ modes only.
536 means that `company-mode' is always turned on except in `message-mode' buffers."
537 :type '(choice (const :tag "none" nil)
539 (set :menu-tag "mode specific" :tag "modes"
541 (const :tag "Except" not)
542 (repeat :inline t (symbol :tag "mode")))))
545 (define-globalized-minor-mode global-company-mode company-mode company-mode-on)
547 (defun company-mode-on ()
548 (when (and (not (or noninteractive (eq (aref (buffer-name) 0) ?\s)))
549 (cond ((eq company-global-modes t)
551 ((eq (car-safe company-global-modes) 'not)
552 (not (memq major-mode (cdr company-global-modes))))
553 (t (memq major-mode company-global-modes))))
556 (defsubst company-assert-enabled ()
558 (company-uninstall-map)
559 (error "Company not enabled")))
561 ;;; keymaps ;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;
563 (defvar company-my-keymap nil)
564 (make-variable-buffer-local 'company-my-keymap)
566 (defvar company-emulation-alist '((t . nil)))
568 (defsubst company-enable-overriding-keymap (keymap)
569 (company-uninstall-map)
570 (setq company-my-keymap keymap))
572 (defun company-ensure-emulation-alist ()
573 (unless (eq 'company-emulation-alist (car emulation-mode-map-alists))
574 (setq emulation-mode-map-alists
575 (cons 'company-emulation-alist
576 (delq 'company-emulation-alist emulation-mode-map-alists)))))
578 (defun company-install-map ()
579 (unless (or (cdar company-emulation-alist)
580 (null company-my-keymap))
581 (setf (cdar company-emulation-alist) company-my-keymap)))
583 (defun company-uninstall-map ()
584 (setf (cdar company-emulation-alist) nil))
587 ;; Emacs calculates the active keymaps before reading the event. That means we
588 ;; cannot change the keymap from a timer. So we send a bogus command.
589 (defun company-ignore ()
591 (setq this-command last-command))
593 (global-set-key '[31415926] 'company-ignore)
595 (defun company-input-noop ()
596 (push 31415926 unread-command-events))
598 (defun company--column (&optional pos)
600 (when pos (goto-char pos))
604 (narrow-to-region (point) (point-max))
605 (let ((prefix (get-text-property (point) 'line-prefix)))
606 (if prefix (length prefix) 0)))
609 (defun company--row (&optional pos)
611 (when pos (goto-char pos))
612 (count-screen-lines (window-start)
613 (progn (vertical-motion 0) (point)))))
615 ;;; backends ;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;
617 (defvar company-backend nil)
618 (make-variable-buffer-local 'company-backend)
620 (defun company-grab (regexp &optional expression limit)
621 (when (looking-back regexp limit)
622 (or (match-string-no-properties (or expression 0)) "")))
624 (defun company-grab-line (regexp &optional expression)
625 (company-grab regexp expression (point-at-bol)))
627 (defun company-grab-symbol ()
628 (if (looking-at "\\_>")
629 (buffer-substring (point) (save-excursion (skip-syntax-backward "w_")
631 (unless (and (char-after) (memq (char-syntax (char-after)) '(?w ?_)))
634 (defun company-grab-word ()
635 (if (looking-at "\\>")
636 (buffer-substring (point) (save-excursion (skip-syntax-backward "w")
638 (unless (and (char-after) (eq (char-syntax (char-after)) ?w))
641 (defun company-in-string-or-comment ()
642 (let ((ppss (syntax-ppss)))
643 (or (car (setq ppss (nthcdr 3 ppss)))
644 (car (setq ppss (cdr ppss)))
647 (if (fboundp 'locate-dominating-file)
648 (defalias 'company-locate-dominating-file 'locate-dominating-file)
649 (defun company-locate-dominating-file (file name)
651 (let ((dir (file-name-directory file))
653 (while (not (equal dir prev-dir))
654 (when (file-exists-p (expand-file-name name dir))
657 dir (file-name-directory (directory-file-name dir))))))))
659 (defun company-call-backend (&rest args)
660 (if (functionp company-backend)
661 (apply company-backend args)
662 (apply 'company--multi-backend-adapter company-backend args)))
664 (defun company--multi-backend-adapter (backends command &rest args)
665 (let ((backends (loop for b in backends
666 when (not (and (symbolp b)
667 (eq 'failed (get b 'company-init))))
671 (loop for backend in backends
672 when (equal (funcall backend 'prefix)
674 append (apply backend 'candidates args)))
679 (dolist (backend backends)
680 (when (setq value (apply backend command args))
681 (return value))))))))
683 ;;; completion mechanism ;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;
685 (defvar company-prefix nil)
686 (make-variable-buffer-local 'company-prefix)
688 (defvar company-candidates nil)
689 (make-variable-buffer-local 'company-candidates)
691 (defvar company-candidates-length nil)
692 (make-variable-buffer-local 'company-candidates-length)
694 (defvar company-candidates-cache nil)
695 (make-variable-buffer-local 'company-candidates-cache)
697 (defvar company-candidates-predicate nil)
698 (make-variable-buffer-local 'company-candidates-predicate)
700 (defvar company-common nil)
701 (make-variable-buffer-local 'company-common)
703 (defvar company-selection 0)
704 (make-variable-buffer-local 'company-selection)
706 (defvar company-selection-changed nil)
707 (make-variable-buffer-local 'company-selection-changed)
709 (defvar company--explicit-action nil
710 "Non-nil, if explicit completion took place.")
711 (make-variable-buffer-local 'company--explicit-action)
713 (defvar company--auto-completion nil
714 "Non-nil when current candidate is being completed automatically.
715 Controlled by `company-auto-complete'.")
717 (defvar company--point-max nil)
718 (make-variable-buffer-local 'company--point-max)
720 (defvar company-point nil)
721 (make-variable-buffer-local 'company-point)
723 (defvar company-timer nil)
725 (defvar company-added-newline nil)
726 (make-variable-buffer-local 'company-added-newline)
728 (defsubst company-strip-prefix (str)
729 (substring str (length company-prefix)))
731 (defmacro company-with-candidate-inserted (candidate &rest body)
732 "Evaluate BODY with CANDIDATE temporarily inserted.
733 This is a tool for back-ends that need candidates inserted before they
734 can retrieve meta-data for them."
736 `(let ((inhibit-modification-hooks t)
737 (inhibit-point-motion-hooks t)
738 (modified-p (buffer-modified-p)))
739 (insert (company-strip-prefix ,candidate))
742 (delete-region company-point (point)))))
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 (defun 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
758 ;; Check if in the middle of entering a key combination.
759 (or (equal (this-command-keys-vector) [])
760 (not (keymapp (key-binding (this-command-keys-vector)))))
761 (eq company-idle-delay t)
762 (or (eq t company-begin-commands)
763 (memq this-command company-begin-commands)
764 (and (symbolp this-command) (get this-command 'company-begin)))
765 (not (and transient-mark-mode mark-active))))
767 (defun company-call-frontends (command)
768 (dolist (frontend company-frontends)
770 (funcall frontend command)
771 (error (error "Company: Front-end %s error \"%s\" on command %s"
772 frontend (error-message-string err) command)))))
774 (defun company-set-selection (selection &optional force-update)
775 (setq selection (max 0 (min (1- company-candidates-length) selection)))
776 (when (or force-update (not (equal selection company-selection)))
777 (setq company-selection selection
778 company-selection-changed t)
779 (company-call-frontends 'update)))
781 (defun company-apply-predicate (candidates predicate)
783 (dolist (c candidates)
784 (when (funcall predicate c)
788 (defun company-update-candidates (candidates)
789 (setq company-candidates-length (length candidates))
790 (if (> company-selection 0)
791 ;; Try to restore the selection
792 (let ((selected (nth company-selection company-candidates)))
793 (setq company-selection 0
794 company-candidates candidates)
796 (while (and candidates (string< (pop candidates) selected))
797 (incf company-selection))
799 ;; Make sure selection isn't out of bounds.
800 (setq company-selection (min (1- company-candidates-length)
801 company-selection)))))
802 (setq company-selection 0
803 company-candidates candidates))
805 (push (cons company-prefix company-candidates) company-candidates-cache)
807 (let ((completion-ignore-case (company-call-backend 'ignore-case)))
808 (setq company-common (company--safe-candidate
809 (try-completion company-prefix company-candidates))))
810 (when (eq company-common t)
811 (setq company-candidates nil)))
813 (defun company--safe-candidate (str)
814 (or (company-call-backend 'crop str)
817 (defun company-calculate-candidates (prefix)
818 (let ((candidates (cdr (assoc prefix company-candidates-cache)))
819 (ignore-case (company-call-backend 'ignore-case)))
821 (when company-candidates-cache
822 (let ((len (length prefix))
823 (completion-ignore-case ignore-case)
825 (dotimes (i (1+ len))
826 (when (setq prev (cdr (assoc (substring prefix 0 (- len i))
827 company-candidates-cache)))
828 (setq candidates (all-completions prefix prev))
830 ;; no cache match, call back-end
832 (setq candidates (company-call-backend 'candidates prefix))
833 (when company-candidates-predicate
835 (company-apply-predicate candidates
836 company-candidates-predicate)))
837 (unless (company-call-backend 'sorted)
838 (setq candidates (sort candidates 'string<)))
839 (when (company-call-backend 'duplicates)
841 (let ((c2 candidates))
843 (setcdr c2 (progn (while (equal (pop c2) (car c2)))
846 (if (or (cdr candidates)
847 (not (eq t (compare-strings (car candidates) nil nil
848 prefix nil nil ignore-case))))
850 ;; Already completed and unique; don't start.
853 (defun company-idle-begin (buf win tick pos)
855 (eq buf (current-buffer))
856 (eq win (selected-window))
857 (eq tick (buffer-chars-modified-tick))
859 (not company-candidates)
860 (not (equal (point) company-point))
861 (let ((company-idle-delay t)
862 (company-begin-commands t))
864 (when company-candidates
866 (company-post-command)))))
868 (defun company-auto-begin ()
869 (company-assert-enabled)
871 (not company-candidates)
872 (let ((company-idle-delay t)
873 (company-minimum-prefix-length 0)
874 (company-begin-commands t))
876 ;; Return non-nil if active.
879 (defun company-manual-begin ()
881 (setq company--explicit-action t)
884 (unless company-candidates
885 (setq company--explicit-action nil))))
887 (defun company-other-backend (&optional backward)
888 (interactive (list current-prefix-arg))
889 (company-assert-enabled)
891 (let* ((after (cdr (member company-backend company-backends)))
892 (before (cdr (member company-backend (reverse company-backends))))
894 (append before (reverse after))
895 (append after (reverse before)))))
897 (dolist (backend next)
898 (when (ignore-errors (company-begin-backend backend))
900 (company-manual-begin))
901 (unless company-candidates
902 (error "No other back-end")))
904 (defun company-require-match-p ()
905 (let ((backend-value (company-call-backend 'require-match)))
906 (or (eq backend-value t)
907 (and (not (eq backend-value 'never))
908 (if (functionp company-require-match)
909 (funcall company-require-match)
910 (eq company-require-match t))))))
912 (defun company-auto-complete-p (input)
913 "Return non-nil, if input starts with punctuation or parentheses."
914 (and (if (functionp company-auto-complete)
915 (funcall company-auto-complete)
916 company-auto-complete)
917 (if (functionp company-auto-complete-chars)
918 (funcall company-auto-complete-chars input)
919 (if (consp company-auto-complete-chars)
920 (memq (char-syntax (string-to-char input))
921 company-auto-complete-chars)
922 (string-match (substring input 0 1) company-auto-complete-chars)))))
924 (defun company--incremental-p ()
925 (and (> (point) company-point)
926 (> (point-max) company--point-max)
927 (not (eq this-command 'backward-delete-char-untabify))
928 (equal (buffer-substring (- company-point (length company-prefix))
932 (defsubst company--string-incremental-p (old-prefix new-prefix)
933 (and (> (length new-prefix) (length old-prefix))
934 (equal old-prefix (substring new-prefix 0 (length old-prefix)))))
936 (defun company--continue-failed (new-prefix)
937 (when (company--incremental-p)
938 (let ((input (buffer-substring-no-properties (point) company-point)))
940 ((company-auto-complete-p input)
943 (goto-char company-point)
944 (let ((company--auto-completion t))
945 (company-complete-selection))
947 ((and (company--string-incremental-p company-prefix new-prefix)
948 (company-require-match-p))
949 ;; wrong incremental input, but required match
950 (delete-char (- (length input)))
952 (message "Matching input is required")
954 ((equal company-prefix (car company-candidates))
955 ;; last input was actually success
956 (company-cancel company-prefix)
959 (defun company--good-prefix-p (prefix)
960 (and (or (company-explicit-action-p)
961 (unless (eq prefix 'stop)
962 (or (eq (cdr-safe prefix) t)
963 (>= (or (cdr-safe prefix) (length prefix))
964 company-minimum-prefix-length))))
965 (stringp (or (car-safe prefix) prefix))))
967 (defun company--continue ()
968 (when (company-call-backend 'no-cache company-prefix)
969 ;; Don't complete existing candidates, fetch new ones.
970 (setq company-candidates-cache nil))
971 (let* ((new-prefix (company-call-backend 'prefix))
972 (c (when (and (company--good-prefix-p new-prefix)
973 (setq new-prefix (or (car-safe new-prefix) new-prefix))
974 (= (- (point) (length new-prefix))
975 (- company-point (length company-prefix))))
976 (setq new-prefix (or (car-safe new-prefix) new-prefix))
977 (company-calculate-candidates new-prefix))))
980 ;; t means complete/unique.
981 (company-cancel new-prefix)
985 (setq company-prefix new-prefix)
986 (company-update-candidates c)
988 (t (company--continue-failed new-prefix)))
991 (defun company--begin-new ()
993 (dolist (backend (if company-backend
994 ;; prefer manual override
995 (list company-backend)
998 (if (or (symbolp backend)
1000 (when (or (not (symbolp backend))
1001 (eq t (get backend 'company-init))
1002 (unless (get backend 'company-init)
1003 (company-init-backend backend)))
1004 (funcall backend 'prefix))
1005 (company--multi-backend-adapter backend 'prefix)))
1007 (when (company--good-prefix-p prefix)
1008 (setq prefix (or (car-safe prefix) prefix)
1009 company-backend backend
1010 c (company-calculate-candidates prefix))
1011 ;; t means complete/unique. We don't start, so no hooks.
1013 (when company--explicit-action
1014 (message "No completion found"))
1015 (setq company-prefix prefix)
1016 (when (symbolp backend)
1017 (setq company-lighter (concat " " (symbol-name backend))))
1018 (company-update-candidates c)
1019 (run-hook-with-args 'company-completion-started-hook
1020 (company-explicit-action-p))
1021 (company-call-frontends 'show)))
1024 (defun company-begin ()
1025 (or (and company-candidates (company--continue))
1026 (and (company--should-complete) (company--begin-new)))
1027 (when company-candidates
1028 (when (and company-end-of-buffer-workaround (eobp))
1029 (save-excursion (insert "\n"))
1030 (setq company-added-newline (buffer-chars-modified-tick)))
1031 (setq company-point (point)
1032 company--point-max (point-max))
1033 (company-ensure-emulation-alist)
1034 (company-enable-overriding-keymap company-active-map)
1035 (company-call-frontends 'update)))
1037 (defun company-cancel (&optional result)
1038 (and company-added-newline
1039 (> (point-max) (point-min))
1040 (let ((tick (buffer-chars-modified-tick)))
1041 (delete-region (1- (point-max)) (point-max))
1042 (equal tick company-added-newline))
1043 ;; Only set unmodified when tick remained the same since insert.
1044 (set-buffer-modified-p nil))
1045 (when company-prefix
1046 (if (stringp result)
1048 (company-call-backend 'pre-completion result)
1049 (run-hook-with-args 'company-completion-finished-hook result)
1050 (company-call-backend 'post-completion result))
1051 (run-hook-with-args 'company-completion-cancelled-hook result)))
1052 (setq company-added-newline nil
1055 company-candidates nil
1056 company-candidates-length nil
1057 company-candidates-cache nil
1058 company-candidates-predicate nil
1061 company-selection-changed nil
1062 company--explicit-action nil
1063 company-lighter company-default-lighter
1064 company--point-max nil
1067 (cancel-timer company-timer))
1068 (company-search-mode 0)
1069 (company-call-frontends 'hide)
1070 (company-enable-overriding-keymap nil))
1072 (defun company-abort ()
1075 ;; Don't start again, unless started manually.
1076 (setq company-point (point)))
1078 (defun company-finish (result)
1079 (insert (company-strip-prefix result))
1080 (company-cancel result)
1081 ;; Don't start again, unless started manually.
1082 (setq company-point (point)))
1084 (defsubst company-keep (command)
1085 (and (symbolp command) (get command 'company-keep)))
1087 (defun company-pre-command ()
1088 (unless (company-keep this-command)
1090 (when company-candidates
1091 (company-call-frontends 'pre-command))
1092 (error (message "Company: An error occurred in pre-command")
1093 (message "%s" (error-message-string err))
1096 (cancel-timer company-timer)
1097 (setq company-timer nil))
1098 (company-uninstall-map))
1100 (defun company-post-command ()
1101 (unless (company-keep this-command)
1104 (unless (equal (point) company-point)
1106 (if company-candidates
1107 (company-call-frontends 'post-command)
1108 (and (numberp company-idle-delay)
1109 (or (eq t company-begin-commands)
1110 (memq this-command company-begin-commands))
1112 (run-with-timer company-idle-delay nil
1114 (current-buffer) (selected-window)
1115 (buffer-chars-modified-tick) (point))))))
1116 (error (message "Company: An error occurred in post-command")
1117 (message "%s" (error-message-string err))
1119 (company-install-map))
1121 ;;; search ;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;
1123 (defvar company-search-string nil)
1124 (make-variable-buffer-local 'company-search-string)
1126 (defvar company-search-lighter " Search: \"\"")
1127 (make-variable-buffer-local 'company-search-lighter)
1129 (defvar company-search-old-map nil)
1130 (make-variable-buffer-local 'company-search-old-map)
1132 (defvar company-search-old-selection 0)
1133 (make-variable-buffer-local 'company-search-old-selection)
1135 (defun company-search (text lines)
1136 (let ((quoted (regexp-quote text))
1138 (dolist (line lines)
1139 (when (string-match quoted line (length company-prefix))
1143 (defun company-search-printing-char ()
1145 (company-search-assert-enabled)
1146 (setq company-search-string
1147 (concat (or company-search-string "") (string last-command-event))
1148 company-search-lighter (concat " Search: \"" company-search-string
1150 (let ((pos (company-search company-search-string
1151 (nthcdr company-selection company-candidates))))
1154 (company-set-selection (+ company-selection pos) t))))
1156 (defun company-search-repeat-forward ()
1157 "Repeat the incremental search in completion candidates forward."
1159 (company-search-assert-enabled)
1160 (let ((pos (company-search company-search-string
1161 (cdr (nthcdr company-selection
1162 company-candidates)))))
1165 (company-set-selection (+ company-selection pos 1) t))))
1167 (defun company-search-repeat-backward ()
1168 "Repeat the incremental search in completion candidates backwards."
1170 (company-search-assert-enabled)
1171 (let ((pos (company-search company-search-string
1172 (nthcdr (- company-candidates-length
1174 (reverse company-candidates)))))
1177 (company-set-selection (- company-selection pos 1) t))))
1179 (defun company-create-match-predicate ()
1180 (setq company-candidates-predicate
1181 `(lambda (candidate)
1182 ,(if company-candidates-predicate
1183 `(and (string-match ,company-search-string candidate)
1184 (funcall ,company-candidates-predicate
1186 `(string-match ,company-search-string candidate))))
1187 (company-update-candidates
1188 (company-apply-predicate company-candidates company-candidates-predicate))
1189 ;; Invalidate cache.
1190 (setq company-candidates-cache (cons company-prefix company-candidates)))
1192 (defun company-filter-printing-char ()
1194 (company-search-assert-enabled)
1195 (company-search-printing-char)
1196 (company-create-match-predicate)
1197 (company-call-frontends 'update))
1199 (defun company-search-kill-others ()
1200 "Limit the completion candidates to the ones matching the search string."
1202 (company-search-assert-enabled)
1203 (company-create-match-predicate)
1204 (company-search-mode 0)
1205 (company-call-frontends 'update))
1207 (defun company-search-abort ()
1208 "Abort searching the completion candidates."
1210 (company-search-assert-enabled)
1211 (company-set-selection company-search-old-selection t)
1212 (company-search-mode 0))
1214 (defun company-search-other-char ()
1216 (company-search-assert-enabled)
1217 (company-search-mode 0)
1218 (company--unread-last-input))
1220 (defvar company-search-map
1222 (keymap (make-keymap)))
1223 (if (fboundp 'max-char)
1224 (set-char-table-range (nth 1 keymap) (cons #x100 (max-char))
1225 'company-search-printing-char)
1227 ;; obsolete in Emacs 23
1228 (let ((l (generic-character-list))
1229 (table (nth 1 keymap)))
1231 (set-char-table-default table (car l) 'company-search-printing-char)
1232 (setq l (cdr l))))))
1233 (define-key keymap [t] 'company-search-other-char)
1235 (define-key keymap (make-string 1 i) 'company-search-other-char)
1238 (define-key keymap (vector i) 'company-search-printing-char)
1240 (let ((meta-map (make-sparse-keymap)))
1241 (define-key keymap (char-to-string meta-prefix-char) meta-map)
1242 (define-key keymap [escape] meta-map))
1243 (define-key keymap (vector meta-prefix-char t) 'company-search-other-char)
1244 (define-key keymap "\e\e\e" 'company-search-other-char)
1245 (define-key keymap [escape escape escape] 'company-search-other-char)
1247 (define-key keymap "\C-g" 'company-search-abort)
1248 (define-key keymap "\C-s" 'company-search-repeat-forward)
1249 (define-key keymap "\C-r" 'company-search-repeat-backward)
1250 (define-key keymap "\C-o" 'company-search-kill-others)
1252 "Keymap used for incrementally searching the completion candidates.")
1254 (define-minor-mode company-search-mode
1255 "Search mode for completion candidates.
1256 Don't start this directly, use `company-search-candidates' or
1257 `company-filter-candidates'."
1258 nil company-search-lighter nil
1259 (if company-search-mode
1260 (if (company-manual-begin)
1262 (setq company-search-old-selection company-selection)
1263 (company-call-frontends 'update))
1264 (setq company-search-mode nil))
1265 (kill-local-variable 'company-search-string)
1266 (kill-local-variable 'company-search-lighter)
1267 (kill-local-variable 'company-search-old-selection)
1268 (company-enable-overriding-keymap company-active-map)))
1270 (defun company-search-assert-enabled ()
1271 (company-assert-enabled)
1272 (unless company-search-mode
1273 (company-uninstall-map)
1274 (error "Company not in search mode")))
1276 (defun company-search-candidates ()
1277 "Start searching the completion candidates incrementally.
1279 \\<company-search-map>Search can be controlled with the commands:
1280 - `company-search-repeat-forward' (\\[company-search-repeat-forward])
1281 - `company-search-repeat-backward' (\\[company-search-repeat-backward])
1282 - `company-search-abort' (\\[company-search-abort])
1284 Regular characters are appended to the search string.
1286 The command `company-search-kill-others' (\\[company-search-kill-others])
1287 uses the search string to limit the completion candidates."
1289 (company-search-mode 1)
1290 (company-enable-overriding-keymap company-search-map))
1292 (defvar company-filter-map
1293 (let ((keymap (make-keymap)))
1294 (define-key keymap [remap company-search-printing-char]
1295 'company-filter-printing-char)
1296 (set-keymap-parent keymap company-search-map)
1298 "Keymap used for incrementally searching the completion candidates.")
1300 (defun company-filter-candidates ()
1301 "Start filtering the completion candidates incrementally.
1302 This works the same way as `company-search-candidates' immediately
1303 followed by `company-search-kill-others' after each input."
1305 (company-search-mode 1)
1306 (company-enable-overriding-keymap company-filter-map))
1308 ;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;
1310 (defun company-select-next ()
1311 "Select the next candidate in the list."
1313 (when (company-manual-begin)
1314 (company-set-selection (1+ company-selection))))
1316 (defun company-select-previous ()
1317 "Select the previous candidate in the list."
1319 (when (company-manual-begin)
1320 (company-set-selection (1- company-selection))))
1322 (defun company-select-next-or-abort ()
1323 "Select the next candidate if more than one, else abort
1324 and invoke the normal binding."
1326 (if (> company-candidates-length 1)
1327 (company-select-next)
1329 (company--unread-last-input)))
1331 (defun company-select-previous-or-abort ()
1332 "Select the previous candidate if more than one, else abort
1333 and invoke the normal binding."
1335 (if (> company-candidates-length 1)
1336 (company-select-previous)
1338 (company--unread-last-input)))
1340 (defvar company-pseudo-tooltip-overlay)
1342 (defvar company-tooltip-offset)
1344 (defun company--inside-tooltip-p (event-col-row row height)
1345 (let* ((ovl company-pseudo-tooltip-overlay)
1346 (column (overlay-get ovl 'company-column))
1347 (width (overlay-get ovl 'company-width))
1348 (evt-col (car event-col-row))
1349 (evt-row (cdr event-col-row)))
1350 (and (>= evt-col column)
1351 (< evt-col (+ column width))
1353 (and (> evt-row row)
1354 (<= evt-row (+ row height) ))
1355 (and (< evt-row row)
1356 (>= evt-row (+ row height)))))))
1358 (defun company--event-col-row (event)
1359 (let* ((col-row (posn-actual-col-row (event-start event)))
1361 (row (cdr col-row)))
1362 (incf col (window-hscroll))
1363 (and header-line-format
1364 (version< "24" emacs-version)
1368 (defun company-select-mouse (event)
1369 "Select the candidate picked by the mouse."
1371 (let ((event-col-row (company--event-col-row event))
1372 (ovl-row (company--row))
1373 (ovl-height (and company-pseudo-tooltip-overlay
1374 (min (overlay-get company-pseudo-tooltip-overlay
1376 company-candidates-length))))
1378 (company--inside-tooltip-p event-col-row ovl-row ovl-height))
1380 (company-set-selection (+ (cdr event-col-row)
1381 (if (zerop company-tooltip-offset)
1383 (- company-tooltip-offset 2))
1385 (if (< ovl-height 0)
1390 (company--unread-last-input)
1393 (defun company-complete-mouse (event)
1394 "Complete the candidate picked by the mouse."
1396 (when (company-select-mouse event)
1397 (company-complete-selection)))
1399 (defun company-complete-selection ()
1400 "Complete the selected candidate."
1402 (when (company-manual-begin)
1403 (let ((result (nth company-selection company-candidates)))
1404 (when company--auto-completion
1405 (setq result (company--safe-candidate result)))
1406 (company-finish result))))
1408 (defun company-complete-common ()
1409 "Complete the common part of all candidates."
1411 (when (company-manual-begin)
1412 (if (and (not (cdr company-candidates))
1413 (equal company-common (car company-candidates)))
1414 (company-complete-selection)
1415 (insert (company-strip-prefix company-common)))))
1417 (defun company-complete ()
1418 "Complete the common part of all candidates or the current selection.
1419 The first time this is called, the common part is completed, the second
1420 time, or when the selection has been changed, the selected candidate is
1423 (when (company-manual-begin)
1424 (if (or company-selection-changed
1425 (eq last-command 'company-complete-common))
1426 (call-interactively 'company-complete-selection)
1427 (call-interactively 'company-complete-common)
1428 (setq this-command 'company-complete-common))))
1430 (defun company-complete-number (n)
1431 "Complete the Nth candidate.
1432 To show the number next to the candidates in some back-ends, enable
1433 `company-show-numbers'."
1434 (when (company-manual-begin)
1435 (and (< n 1) (> n company-candidates-length)
1436 (error "No candidate number %d" n))
1438 (company-finish (nth n company-candidates))))
1440 ;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;
1442 (defconst company-space-strings-limit 100)
1444 (defconst company-space-strings
1446 (dotimes (i company-space-strings-limit)
1447 (push (make-string (- company-space-strings-limit 1 i) ?\ ) lst))
1448 (apply 'vector lst)))
1450 (defun company-space-string (len)
1451 (if (< len company-space-strings-limit)
1452 (aref company-space-strings len)
1453 (make-string len ?\ )))
1455 (defun company-safe-substring (str from &optional to)
1456 (if (> from (string-width str))
1460 (move-to-column from)
1461 (let ((beg (point)))
1465 (concat (buffer-substring beg (point))
1466 (let ((padding (- to (current-column))))
1468 (company-space-string padding)))))
1469 (buffer-substring beg (point-max)))))))
1471 ;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;
1473 (defvar company-last-metadata nil)
1474 (make-variable-buffer-local 'company-last-metadata)
1476 (defun company-fetch-metadata ()
1477 (let ((selected (nth company-selection company-candidates)))
1478 (unless (equal selected (car company-last-metadata))
1479 (setq company-last-metadata
1480 (cons selected (company-call-backend 'meta selected))))
1481 (cdr company-last-metadata)))
1483 (defun company-doc-buffer (&optional string)
1484 (with-current-buffer (get-buffer-create "*company-documentation*")
1491 (defvar company--electric-commands
1492 '(scroll-other-window scroll-other-window-down)
1493 "List of Commands that won't break out of electric commands.")
1495 (defmacro company--electric-do (&rest body)
1496 (declare (indent 0) (debug t))
1497 `(when (company-manual-begin)
1498 (save-window-excursion
1499 (let ((height (window-height))
1500 (row (company--row))
1503 (and (< (window-height) height)
1504 (< (- (window-height) row 2) company-tooltip-limit)
1505 (recenter (- (window-height) row 2)))
1506 (while (memq (setq cmd (key-binding (vector (list (read-event)))))
1507 company--electric-commands)
1508 (call-interactively cmd))
1509 (company--unread-last-input)))))
1511 (defun company--unread-last-input ()
1512 (when last-input-event
1513 (clear-this-command-keys t)
1514 (setq unread-command-events (list last-input-event))))
1516 (defun company-show-doc-buffer ()
1517 "Temporarily show the documentation buffer for the selection."
1519 (company--electric-do
1520 (let* ((selected (nth company-selection company-candidates))
1521 (doc-buffer (or (company-call-backend 'doc-buffer selected)
1522 (error "No documentation available"))))
1523 (with-current-buffer doc-buffer
1524 (goto-char (point-min)))
1525 (display-buffer doc-buffer t))))
1526 (put 'company-show-doc-buffer 'company-keep t)
1528 (defun company-show-location ()
1529 "Temporarily display a buffer showing the selected candidate in context."
1531 (company--electric-do
1532 (let* ((selected (nth company-selection company-candidates))
1533 (location (company-call-backend 'location selected))
1534 (pos (or (cdr location) (error "No location available")))
1535 (buffer (or (and (bufferp (car location)) (car location))
1536 (find-file-noselect (car location) t))))
1537 (with-selected-window (display-buffer buffer t)
1540 (if (bufferp (car location))
1542 (goto-char (point-min))
1543 (forward-line (1- pos))))
1544 (set-window-start nil (point))))))
1545 (put 'company-show-location 'company-keep t)
1547 ;;; package functions ;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;
1549 (defvar company-callback nil)
1550 (make-variable-buffer-local 'company-callback)
1552 (defvar company-begin-with-marker nil)
1553 (make-variable-buffer-local 'company-begin-with-marker)
1555 (defun company-remove-callback (&optional ignored)
1556 (remove-hook 'company-completion-finished-hook company-callback t)
1557 (remove-hook 'company-completion-cancelled-hook 'company-remove-callback t)
1558 (remove-hook 'company-completion-finished-hook 'company-remove-callback t)
1559 (when company-begin-with-marker
1560 (set-marker company-begin-with-marker nil)))
1562 (defun company-begin-backend (backend &optional callback)
1563 "Start a completion at point using BACKEND."
1564 (interactive (let ((val (completing-read "Company back-end: "
1566 'functionp nil "company-")))
1568 (list (intern val)))))
1569 (when (setq company-callback callback)
1570 (add-hook 'company-completion-finished-hook company-callback nil t))
1571 (add-hook 'company-completion-cancelled-hook 'company-remove-callback nil t)
1572 (add-hook 'company-completion-finished-hook 'company-remove-callback nil t)
1573 (setq company-backend backend)
1574 ;; Return non-nil if active.
1575 (or (company-manual-begin)
1577 (setq company-backend nil)
1578 (error "Cannot complete at point"))))
1580 (defun company-begin-with (candidates
1581 &optional prefix-length require-match callback)
1582 "Start a completion at point.
1583 CANDIDATES is the list of candidates to use and PREFIX-LENGTH is the length
1584 of the prefix that already is in the buffer before point.
1587 CALLBACK is a function called with the selected result if the user
1588 successfully completes the input.
1590 Example: \(company-begin-with '\(\"foo\" \"foobar\" \"foobarbaz\"\)\)"
1591 ;; FIXME: When Emacs 23 is no longer a concern, replace
1592 ;; `company-begin-with-marker' with a lexical variable; use a lexical closure.
1593 (setq company-begin-with-marker (copy-marker (point) t))
1594 (company-begin-backend
1595 `(lambda (command &optional arg &rest ignored)
1597 ((eq command 'prefix)
1598 (when (equal (point) (marker-position company-begin-with-marker))
1599 (buffer-substring ,(- (point) (or prefix-length 0)) (point))))
1600 ((eq command 'candidates)
1601 (all-completions arg ',candidates))
1602 ((eq command 'require-match)
1606 ;;; pseudo-tooltip ;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;
1608 (defvar company-pseudo-tooltip-overlay nil)
1609 (make-variable-buffer-local 'company-pseudo-tooltip-overlay)
1611 (defvar company-tooltip-offset 0)
1612 (make-variable-buffer-local 'company-tooltip-offset)
1614 (defun company-pseudo-tooltip-update-offset (selection num-lines limit)
1617 (setq company-tooltip-offset
1618 (max (min selection company-tooltip-offset)
1619 (- selection -1 limit)))
1621 (when (<= company-tooltip-offset 1)
1623 (setq company-tooltip-offset 0))
1625 (when (>= company-tooltip-offset (- num-lines limit 1))
1627 (when (= selection (1- num-lines))
1628 (decf company-tooltip-offset)
1629 (when (<= company-tooltip-offset 1)
1630 (setq company-tooltip-offset 0)
1637 (defsubst company-round-tab (arg)
1638 (* (/ (+ arg tab-width) tab-width) tab-width))
1640 (defun company-untabify (str)
1641 (let* ((pieces (split-string str "\t"))
1644 (setcar copy (company-safe-substring
1645 (car copy) 0 (company-round-tab (string-width (car copy)))))
1647 (apply 'concat pieces)))
1649 (defun company-fill-propertize (line width selected)
1650 (setq line (company-safe-substring line 0 width))
1651 (add-text-properties 0 width '(face company-tooltip
1652 mouse-face company-tooltip-mouse)
1654 (add-text-properties 0 (length company-common)
1655 '(face company-tooltip-common
1656 mouse-face company-tooltip-mouse)
1659 (if (and company-search-string
1660 (string-match (regexp-quote company-search-string) line
1661 (length company-prefix)))
1663 (add-text-properties (match-beginning 0) (match-end 0)
1664 '(face company-tooltip-selection)
1666 (when (< (match-beginning 0) (length company-common))
1667 (add-text-properties (match-beginning 0) (length company-common)
1668 '(face company-tooltip-common-selection)
1670 (add-text-properties 0 width '(face company-tooltip-selection
1671 mouse-face company-tooltip-selection)
1673 (add-text-properties 0 (length company-common)
1674 '(face company-tooltip-common-selection
1675 mouse-face company-tooltip-selection)
1681 (defun company-buffer-lines (beg end)
1684 (while (and (= 1 (vertical-motion 1))
1686 (let ((bound (min end (1- (point)))))
1687 ;; A visual line can contain several physical lines (e.g. with outline's
1688 ;; folding overlay). Take only the first one.
1689 (push (buffer-substring beg
1692 (re-search-forward "$" bound 'move)
1696 (unless (eq beg end)
1697 (push (buffer-substring beg end) lines))
1700 (defun company-modify-line (old new offset)
1701 (let ((prefix (get-text-property 0 'line-prefix old)))
1702 (when prefix ; Keep the original value unmodified, for no special reason.
1703 (setq old (concat prefix old))
1704 (remove-text-properties 0 (length old) '(line-prefix) old)))
1705 (concat (company-safe-substring old 0 offset)
1707 (company-safe-substring old (+ offset (length new)))))
1709 (defsubst company--length-limit (lst limit)
1710 (if (nthcdr limit lst)
1714 (defun company--replacement-string (lines old column nl &optional align-top)
1716 (let ((width (length (car lines)))
1717 (remaining-cols (- (+ (window-width) (window-hscroll))
1719 (when (> width remaining-cols)
1720 (decf column (- width remaining-cols))))
1724 ;; untouched lines first
1725 (dotimes (_ (- (length old) (length lines)))
1726 (push (pop old) new)))
1727 ;; length into old lines.
1729 (push (company-modify-line (pop old) (pop lines) column) new))
1730 ;; Append whole new lines.
1732 (push (concat (company-space-string column) (pop lines)) new))
1734 (let ((str (concat (when nl "\n")
1735 (mapconcat 'identity (nreverse new) "\n")
1737 (font-lock-append-text-property 0 (length str) 'face 'default str)
1740 (defun company--create-lines (selection limit)
1742 (let ((len company-candidates-length)
1751 ;; Scroll to offset.
1752 (setq limit (company-pseudo-tooltip-update-offset selection len limit))
1754 (when (> company-tooltip-offset 0)
1755 (setq previous (format "...(%d)" company-tooltip-offset)))
1757 (setq remainder (- len limit company-tooltip-offset)
1758 remainder (when (> remainder 0)
1759 (setq remainder (format "...(%d)" remainder))))
1761 (decf selection company-tooltip-offset)
1762 (setq width (max (length previous) (length remainder))
1763 lines (nthcdr company-tooltip-offset company-candidates)
1768 (setq width (max (length (pop lines-copy)) width)))
1769 (setq width (min width (window-width)))
1771 (setq lines-copy lines)
1773 ;; number can make tooltip too long
1774 (when company-show-numbers
1775 (setq numbered company-tooltip-offset))
1778 (push (propertize (company-safe-substring previous 0 width)
1779 'face 'company-tooltip)
1783 (push (company-fill-propertize
1784 (if (>= numbered 10)
1785 (company-reformat (pop lines))
1788 (company-safe-substring (company-reformat (pop lines))
1791 width (equal i selection))
1795 (push (propertize (company-safe-substring remainder 0 width)
1796 'face 'company-tooltip)
1799 (setq lines (nreverse new))))
1803 (defsubst company--window-inner-height ()
1804 (let ((edges (window-inside-edges)))
1805 (- (nth 3 edges) (nth 1 edges))))
1807 (defun company--pseudo-tooltip-height ()
1808 "Calculate the appropriate tooltip height.
1809 Returns a negative number if the tooltip should be displayed above point."
1810 (let* ((lines (company--row))
1811 (below (- (company--window-inner-height) 1 lines)))
1812 (if (and (< below (min company-tooltip-minimum company-candidates-length))
1814 (- (max 3 (min company-tooltip-limit lines)))
1815 (max 3 (min company-tooltip-limit below)))))
1817 (defun company-pseudo-tooltip-show (row column selection)
1818 (company-pseudo-tooltip-hide)
1821 (let* ((height (company--pseudo-tooltip-height))
1825 (setq row (+ row height -1)
1828 (let* ((nl (< (move-to-window-line row) row))
1830 (end (save-excursion
1831 (move-to-window-line (+ row (abs height)))
1833 (ov (make-overlay beg end))
1834 (args (list (mapcar 'company-untabify
1835 (company-buffer-lines beg end))
1838 (setq company-pseudo-tooltip-overlay ov)
1839 (overlay-put ov 'company-replacement-args args)
1841 (let ((lines (company--create-lines selection (abs height))))
1842 (overlay-put ov 'company-after
1843 (apply 'company--replacement-string lines args))
1844 (overlay-put ov 'company-width (string-width (car lines))))
1846 (overlay-put ov 'company-column column)
1847 (overlay-put ov 'company-height height)))))
1849 (defun company-pseudo-tooltip-show-at-point (pos)
1850 (let ((row (company--row pos))
1851 (col (company--column pos)))
1852 (company-pseudo-tooltip-show (1+ row) col company-selection)))
1854 (defun company-pseudo-tooltip-edit (selection)
1855 (let ((height (overlay-get company-pseudo-tooltip-overlay 'company-height)))
1856 (overlay-put company-pseudo-tooltip-overlay 'company-after
1857 (apply 'company--replacement-string
1858 (company--create-lines selection (abs height))
1859 (overlay-get company-pseudo-tooltip-overlay
1860 'company-replacement-args)))))
1862 (defun company-pseudo-tooltip-hide ()
1863 (when company-pseudo-tooltip-overlay
1864 (delete-overlay company-pseudo-tooltip-overlay)
1865 (setq company-pseudo-tooltip-overlay nil)))
1867 (defun company-pseudo-tooltip-hide-temporarily ()
1868 (when (overlayp company-pseudo-tooltip-overlay)
1869 (overlay-put company-pseudo-tooltip-overlay 'invisible nil)
1870 (overlay-put company-pseudo-tooltip-overlay 'line-prefix nil)
1871 (overlay-put company-pseudo-tooltip-overlay 'after-string nil)))
1873 (defun company-pseudo-tooltip-unhide ()
1874 (when company-pseudo-tooltip-overlay
1875 (overlay-put company-pseudo-tooltip-overlay 'invisible t)
1876 ;; Beat outline's folding overlays, at least.
1877 (overlay-put company-pseudo-tooltip-overlay 'priority 1)
1878 ;; No (extra) prefix for the first line.
1879 (overlay-put company-pseudo-tooltip-overlay 'line-prefix "")
1880 (overlay-put company-pseudo-tooltip-overlay 'after-string
1881 (overlay-get company-pseudo-tooltip-overlay 'company-after))
1882 (overlay-put company-pseudo-tooltip-overlay 'window (selected-window))))
1884 (defun company-pseudo-tooltip-guard ()
1885 (buffer-substring-no-properties
1886 (point) (overlay-start company-pseudo-tooltip-overlay)))
1888 (defun company-pseudo-tooltip-frontend (command)
1889 "`company-mode' front-end similar to a tooltip but based on overlays."
1891 (pre-command (company-pseudo-tooltip-hide-temporarily))
1893 (let ((old-height (if (overlayp company-pseudo-tooltip-overlay)
1894 (overlay-get company-pseudo-tooltip-overlay
1897 (new-height (company--pseudo-tooltip-height)))
1898 (unless (and (>= (* old-height new-height) 0)
1899 (>= (abs old-height) (abs new-height))
1900 (equal (company-pseudo-tooltip-guard)
1901 (overlay-get company-pseudo-tooltip-overlay
1904 (company-pseudo-tooltip-show-at-point (- (point)
1905 (length company-prefix)))
1906 (overlay-put company-pseudo-tooltip-overlay
1907 'company-guard (company-pseudo-tooltip-guard))))
1908 (company-pseudo-tooltip-unhide))
1909 (hide (company-pseudo-tooltip-hide)
1910 (setq company-tooltip-offset 0))
1911 (update (when (overlayp company-pseudo-tooltip-overlay)
1912 (company-pseudo-tooltip-edit company-selection)))))
1914 (defun company-pseudo-tooltip-unless-just-one-frontend (command)
1915 "`company-pseudo-tooltip-frontend', but not shown for single candidates."
1916 (unless (and (eq command 'post-command)
1917 (not (cdr company-candidates)))
1918 (company-pseudo-tooltip-frontend command)))
1920 ;;; overlay ;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;
1922 (defvar company-preview-overlay nil)
1923 (make-variable-buffer-local 'company-preview-overlay)
1925 (defun company-preview-show-at-point (pos)
1926 (company-preview-hide)
1928 (setq company-preview-overlay (make-overlay pos pos))
1930 (let ((completion(nth company-selection company-candidates)))
1931 (setq completion (propertize completion 'face 'company-preview))
1932 (add-text-properties 0 (length company-common)
1933 '(face company-preview-common) completion)
1935 ;; Add search string
1936 (and company-search-string
1937 (string-match (regexp-quote company-search-string) completion)
1938 (add-text-properties (match-beginning 0)
1940 '(face company-preview-search)
1943 (setq completion (company-strip-prefix completion))
1945 (and (equal pos (point))
1946 (not (equal completion ""))
1947 (add-text-properties 0 1 '(cursor t) completion))
1949 (overlay-put company-preview-overlay 'after-string completion)
1950 (overlay-put company-preview-overlay 'window (selected-window))))
1952 (defun company-preview-hide ()
1953 (when company-preview-overlay
1954 (delete-overlay company-preview-overlay)
1955 (setq company-preview-overlay nil)))
1957 (defun company-preview-frontend (command)
1958 "`company-mode' front-end showing the selection as if it had been inserted."
1960 (pre-command (company-preview-hide))
1961 (post-command (company-preview-show-at-point (point)))
1962 (hide (company-preview-hide))))
1964 (defun company-preview-if-just-one-frontend (command)
1965 "`company-preview-frontend', but only shown for single candidates."
1966 (unless (and (eq command 'post-command)
1967 (cdr company-candidates))
1968 (company-preview-frontend command)))
1970 ;;; echo ;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;
1972 (defvar company-echo-last-msg nil)
1973 (make-variable-buffer-local 'company-echo-last-msg)
1975 (defvar company-echo-timer nil)
1977 (defvar company-echo-delay .01)
1979 (defun company-echo-show (&optional getter)
1981 (setq company-echo-last-msg (funcall getter)))
1982 (let ((message-log-max nil))
1983 (if company-echo-last-msg
1984 (message "%s" company-echo-last-msg)
1987 (defun company-echo-show-soon (&optional getter)
1988 (when company-echo-timer
1989 (cancel-timer company-echo-timer))
1990 (setq company-echo-timer (run-with-timer 0 nil 'company-echo-show getter)))
1992 (defsubst company-echo-show-when-idle (&optional getter)
1993 (when (sit-for company-echo-delay)
1994 (company-echo-show getter)))
1996 (defun company-echo-format ()
1998 (let ((limit (window-width (minibuffer-window)))
2000 ;; Roll to selection.
2001 (candidates (nthcdr company-selection company-candidates))
2002 (i (if company-show-numbers company-selection 99999))
2006 (setq comp (company-reformat (pop candidates))
2007 len (+ len 1 (length comp)))
2011 (setq comp (propertize (format "%d: %s" i comp)
2012 'face 'company-echo))
2015 (add-text-properties 3 (+ 3 (length company-common))
2016 '(face company-echo-common) comp))
2017 (setq comp (propertize comp 'face 'company-echo))
2018 (add-text-properties 0 (length company-common)
2019 '(face company-echo-common) comp))
2021 (setq candidates nil)
2024 (mapconcat 'identity (nreverse msg) " ")))
2026 (defun company-echo-strip-common-format ()
2028 (let ((limit (window-width (minibuffer-window)))
2029 (len (+ (length company-prefix) 2))
2030 ;; Roll to selection.
2031 (candidates (nthcdr company-selection company-candidates))
2032 (i (if company-show-numbers company-selection 99999))
2036 (setq comp (company-strip-prefix (pop candidates))
2037 len (+ len 2 (length comp)))
2040 (setq comp (format "%s (%d)" comp i))
2044 (setq candidates nil)
2045 (push (propertize comp 'face 'company-echo) msg)))
2047 (concat (propertize company-prefix 'face 'company-echo-common) "{"
2048 (mapconcat 'identity (nreverse msg) ", ")
2051 (defun company-echo-hide ()
2052 (unless (equal company-echo-last-msg "")
2053 (setq company-echo-last-msg "")
2054 (company-echo-show)))
2056 (defun company-echo-frontend (command)
2057 "`company-mode' front-end showing the candidates in the echo area."
2059 (post-command (company-echo-show-soon 'company-echo-format))
2060 (hide (company-echo-hide))))
2062 (defun company-echo-strip-common-frontend (command)
2063 "`company-mode' front-end showing the candidates in the echo area."
2065 (post-command (company-echo-show-soon 'company-echo-strip-common-format))
2066 (hide (company-echo-hide))))
2068 (defun company-echo-metadata-frontend (command)
2069 "`company-mode' front-end showing the documentation in the echo area."
2071 (post-command (company-echo-show-when-idle 'company-fetch-metadata))
2072 (hide (company-echo-hide))))
2075 ;;; company.el ends here