1 ;;; company.el --- Modular in-buffer completion framework
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.com/
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 (add-to-list 'debug-ignored-errors "^.* frontend cannot be used twice$")
75 (add-to-list 'debug-ignored-errors "^Echo area cannot be used twice$")
76 (add-to-list 'debug-ignored-errors "^No \\(document\\|loc\\)ation available$")
77 (add-to-list 'debug-ignored-errors "^Company not ")
78 (add-to-list 'debug-ignored-errors "^No candidate number ")
79 (add-to-list 'debug-ignored-errors "^Cannot complete at point$")
80 (add-to-list 'debug-ignored-errors "^No other back-end$")
83 "Extensible inline text completion mechanism"
88 (defface company-tooltip
89 '((t :background "yellow"
91 "Face used for the tool tip."
94 (defface company-tooltip-selection
95 '((default :inherit company-tooltip)
96 (((class color) (min-colors 88)) (:background "orange1"))
97 (t (:background "green")))
98 "Face used for the selection in the tool tip."
101 (defface company-tooltip-mouse
102 '((default :inherit highlight))
103 "Face used for the tool tip item under the mouse."
106 (defface company-tooltip-common
107 '((t :inherit company-tooltip
109 "Face used for the common completion in the tool tip."
112 (defface company-tooltip-common-selection
113 '((t :inherit company-tooltip-selection
115 "Face used for the selected common completion in the tool tip."
118 (defface company-preview
119 '((t :background "blue4"
120 :foreground "wheat"))
121 "Face used for the completion preview."
124 (defface company-preview-common
125 '((t :inherit company-preview
127 "Face used for the common part of the completion preview."
130 (defface company-preview-search
131 '((t :inherit company-preview
132 :background "blue1"))
133 "Face used for the search string in the completion preview."
136 (defface company-echo nil
137 "Face used for completions in the echo area."
140 (defface company-echo-common
141 '((((background dark)) (:foreground "firebrick1"))
142 (((background light)) (:background "firebrick4")))
143 "Face used for the common part of completions in the echo area."
146 (defun company-frontends-set (variable value)
148 (let ((remainder value))
149 (setcdr remainder (delq (car remainder) (cdr remainder))))
150 (and (memq 'company-pseudo-tooltip-unless-just-one-frontend value)
151 (memq 'company-pseudo-tooltip-frontend value)
152 (error "Pseudo tooltip frontend cannot be used twice"))
153 (and (memq 'company-preview-if-just-one-frontend value)
154 (memq 'company-preview-frontend value)
155 (error "Preview frontend cannot be used twice"))
156 (and (memq 'company-echo value)
157 (memq 'company-echo-metadata-frontend value)
158 (error "Echo area cannot be used twice"))
159 ;; preview must come last
160 (dolist (f '(company-preview-if-just-one-frontend company-preview-frontend))
162 (setq value (append (delq f value) (list f)))))
163 (set variable value))
165 (defcustom company-frontends '(company-pseudo-tooltip-unless-just-one-frontend
166 company-preview-if-just-one-frontend
167 company-echo-metadata-frontend)
168 "The list of active front-ends (visualizations).
169 Each front-end is a function that takes one argument. It is called with
170 one of the following arguments:
172 'show: When the visualization should start.
174 'hide: When the visualization should end.
176 'update: When the data has been updated.
178 'pre-command: Before every command that is executed while the
179 visualization is active.
181 'post-command: After every command that is executed while the
182 visualization is active.
184 The visualized data is stored in `company-prefix', `company-candidates',
185 `company-common', `company-selection', `company-point' and
186 `company-search-string'."
187 :set 'company-frontends-set
189 :type '(repeat (choice (const :tag "echo" company-echo-frontend)
190 (const :tag "echo, strip common"
191 company-echo-strip-common-frontend)
192 (const :tag "show echo meta-data in echo"
193 company-echo-metadata-frontend)
194 (const :tag "pseudo tooltip"
195 company-pseudo-tooltip-frontend)
196 (const :tag "pseudo tooltip, multiple only"
197 company-pseudo-tooltip-unless-just-one-frontend)
198 (const :tag "preview" company-preview-frontend)
199 (const :tag "preview, unique only"
200 company-preview-if-just-one-frontend)
201 (function :tag "custom function" nil))))
203 (defcustom company-tooltip-limit 10
204 "The maximum number of candidates in the tool tip"
208 (defcustom company-tooltip-minimum 6
209 "The minimum height of the tool tip.
210 If this many lines are not available, prefer to display the tooltip above."
214 (defvar company-safe-backends
215 '((company-abbrev . "Abbrev")
216 (company-clang . "clang")
217 (company-css . "CSS")
218 (company-dabbrev . "dabbrev for plain text")
219 (company-dabbrev-code . "dabbrev for code")
220 (company-eclim . "eclim (an Eclipse interace)")
221 (company-elisp . "Emacs Lisp")
222 (company-etags . "etags")
223 (company-files . "Files")
224 (company-gtags . "GNU Global")
225 (company-ispell . "ispell")
226 (company-keywords . "Programming language keywords")
227 (company-nxml . "nxml")
228 (company-oddmuse . "Oddmuse")
229 (company-pysmell . "PySmell")
230 (company-ropemacs . "ropemacs")
231 (company-semantic . "CEDET Semantic")
232 (company-tempo . "Tempo templates")
233 (company-xcode . "Xcode")))
234 (put 'company-safe-backends 'risky-local-variable t)
236 (defun company-safe-backends-p (backends)
237 (and (consp backends)
238 (not (dolist (backend backends)
239 (unless (if (consp backend)
240 (company-safe-backends-p backend)
241 (assq backend company-safe-backends))
244 (defun company-capf (command &optional arg &rest args)
245 "`company-mode' back-end using `completion-at-point-functions'.
246 Requires Emacs 24.1 or newer."
247 (interactive (list 'interactive))
249 (interactive (company-begin-backend 'company-capf))
251 (let ((res (run-hook-wrapped 'completion-at-point-functions
252 ;; Ignore misbehaving functions.
253 #'completion--capf-wrapper 'optimist)))
255 (if (> (nth 2 res) (point))
257 (buffer-substring-no-properties (nth 1 res) (point))))))
259 (let ((res (run-hook-wrapped 'completion-at-point-functions
260 ;; Ignore misbehaving functions.
261 #'completion--capf-wrapper 'optimist)))
263 (all-completions arg (nth 3 res)
264 (plist-get (nthcdr 4 res) :predicate)))))))
266 (defcustom company-backends '(company-elisp company-nxml company-css
267 company-clang company-semantic company-eclim
268 company-xcode company-ropemacs
269 (company-gtags company-etags company-dabbrev-code
271 company-oddmuse company-files company-dabbrev)
272 "The list of active back-ends (completion engines).
273 Each list elements can itself be a list of back-ends. In that case their
274 completions are merged. Otherwise only the first matching back-end returns
277 `company-begin-backend' can be used to start a specific back-end,
278 `company-other-backend' will skip to the next matching back-end in the list.
280 Each back-end is a function that takes a variable number of arguments.
281 The first argument is the command requested from the back-end. It is one
284 `prefix': The back-end should return the text to be completed. It must be
285 text immediately before `point'. Returning nil passes control to the next
286 back-end. The function should return 'stop if it should complete but cannot
287 \(e.g. if it is in the middle of a string\). If the returned value is only
288 part of the prefix (e.g. the part after \"->\" in C), the back-end may return a
289 cons of prefix and prefix length, which is then used in the
290 `company-minimum-prefix-length' test.
292 `candidates': The second argument is the prefix to be completed. The
293 return value should be a list of candidates that start with the prefix.
297 `sorted': The back-end may return t here to indicate that the candidates
298 are sorted and will not need to be sorted again.
300 `duplicates': If non-nil, company will take care of removing duplicates
303 `no-cache': Usually company doesn't ask for candidates again as completion
304 progresses, unless the back-end returns t for this command. The second
305 argument is the latest prefix.
307 `meta': The second argument is a completion candidate. The back-end should
308 return a (short) documentation string for it.
310 `doc-buffer': The second argument is a completion candidate.
311 The back-end should create a buffer (preferably with `company-doc-buffer'),
312 fill it with documentation and return it.
314 `location': The second argument is a completion candidate. The back-end can
315 return the cons of buffer and buffer location, or of file and line
316 number where the completion candidate was defined.
318 `require-match': If this value is t, the user is not allowed to enter anything
319 not offering as a candidate. Use with care! The default value nil gives the
320 user that choice with `company-require-match'. Return value 'never overrides
321 that option the other way around.
323 The back-end should return nil for all commands it does not support or
324 does not know about. It should also be callable interactively and use
325 `company-begin-backend' to start itself in that case."
330 ,@(mapcar (lambda (b) `(const :tag ,(cdr b) ,(car b)))
331 company-safe-backends)
332 (symbol :tag "User defined")
333 (repeat :tag "Merged Back-ends"
334 (choice :tag "Back-end"
335 ,@(mapcar (lambda (b)
336 `(const :tag ,(cdr b) ,(car b)))
337 company-safe-backends)
338 (symbol :tag "User defined"))))))
340 (put 'company-backends 'safe-local-variable 'company-safe-backends-p)
342 (defcustom company-completion-started-hook nil
343 "Hook run when company starts completing.
344 The hook is called with one argument that is non-nil if the completion was
349 (defcustom company-completion-cancelled-hook nil
350 "Hook run when company cancels completing.
351 The hook is called with one argument that is non-nil if the completion was
356 (defcustom company-completion-finished-hook nil
357 "Hook run when company successfully completes.
358 The hook is called with the selected candidate as an argument."
362 (defcustom company-minimum-prefix-length 3
363 "The minimum prefix length for automatic completion."
365 :type '(integer :tag "prefix length"))
367 (defcustom company-require-match 'company-explicit-action-p
368 "If enabled, disallow non-matching input.
369 This can be a function do determine if a match is required.
371 This can be overridden by the back-end, if it returns t or 'never to
372 'require-match. `company-auto-complete' also takes precedence over this."
374 :type '(choice (const :tag "Off" nil)
375 (function :tag "Predicate function")
376 (const :tag "On, if user interaction took place"
377 'company-explicit-action-p)
378 (const :tag "On" t)))
380 (defcustom company-auto-complete 'company-explicit-action-p
381 "Determines when to auto-complete.
382 If this is enabled, all characters from `company-auto-complete-chars' complete
383 the selected completion. This can also be a function."
385 :type '(choice (const :tag "Off" nil)
386 (function :tag "Predicate function")
387 (const :tag "On, if user interaction took place"
388 'company-explicit-action-p)
389 (const :tag "On" t)))
391 (defcustom company-auto-complete-chars '(?\ ?\( ?\) ?. ?\" ?$ ?\' ?< ?| ?!)
392 "Determines which characters trigger an automatic completion.
393 See `company-auto-complete'. If this is a string, each string character causes
394 completion. If it is a list of syntax description characters (see
395 `modify-syntax-entry'), all characters with that syntax auto-complete.
397 This can also be a function, which is called with the new input and should
398 return non-nil if company should auto-complete.
400 A character that is part of a valid candidate never starts auto-completion."
402 :type '(choice (string :tag "Characters")
404 (const :tag "Whitespace" ?\ )
405 (const :tag "Symbol" ?_)
406 (const :tag "Opening parentheses" ?\()
407 (const :tag "Closing parentheses" ?\))
408 (const :tag "Word constituent" ?w)
409 (const :tag "Punctuation." ?.)
410 (const :tag "String quote." ?\")
411 (const :tag "Paired delimiter." ?$)
412 (const :tag "Expression quote or prefix operator." ?\')
413 (const :tag "Comment starter." ?<)
414 (const :tag "Comment ender." ?>)
415 (const :tag "Character-quote." ?/)
416 (const :tag "Generic string fence." ?|)
417 (const :tag "Generic comment fence." ?!))
418 (function :tag "Predicate function")))
420 (defcustom company-idle-delay .7
421 "The idle delay in seconds until automatic completions starts.
422 A value of nil means never complete automatically, t means complete
423 immediately when a prefix of `company-minimum-prefix-length' is reached."
425 :type '(choice (const :tag "never (nil)" nil)
426 (const :tag "immediate (t)" t)
427 (number :tag "seconds")))
429 (defcustom company-begin-commands t
430 "A list of commands following which company will start completing.
431 If this is t, it will complete after any command. See `company-idle-delay'.
433 Alternatively any command with a non-nil 'company-begin property is treated as
434 if it was on this list."
436 :type '(choice (const :tag "Any command" t)
437 (const :tag "Self insert command" '(self-insert-command))
438 (repeat :tag "Commands" function)))
440 (defcustom company-show-numbers nil
441 "If enabled, show quick-access numbers for the first ten candidates."
443 :type '(choice (const :tag "off" nil)
444 (const :tag "on" t)))
446 (defvar company-end-of-buffer-workaround t
447 "Work around a visualization bug when completing at the end of the buffer.
448 The work-around consists of adding a newline.")
450 ;;; mode ;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;
452 (defvar company-mode-map (make-sparse-keymap)
453 "Keymap used by `company-mode'.")
455 (defvar company-active-map
456 (let ((keymap (make-sparse-keymap)))
457 (define-key keymap "\e\e\e" 'company-abort)
458 (define-key keymap "\C-g" 'company-abort)
459 (define-key keymap (kbd "M-n") 'company-select-next)
460 (define-key keymap (kbd "M-p") 'company-select-previous)
461 (define-key keymap (kbd "<down>") 'company-select-next-or-abort)
462 (define-key keymap (kbd "<up>") 'company-select-previous-or-abort)
463 (define-key keymap [down-mouse-1] 'ignore)
464 (define-key keymap [down-mouse-3] 'ignore)
465 (define-key keymap [mouse-1] 'company-complete-mouse)
466 (define-key keymap [mouse-3] 'company-select-mouse)
467 (define-key keymap [up-mouse-1] 'ignore)
468 (define-key keymap [up-mouse-3] 'ignore)
469 (define-key keymap [return] 'company-complete-selection)
470 (define-key keymap [tab] 'company-complete-common)
471 (define-key keymap (kbd "<f1>") 'company-show-doc-buffer)
472 (define-key keymap "\C-w" 'company-show-location)
473 (define-key keymap "\C-s" 'company-search-candidates)
474 (define-key keymap "\C-\M-s" 'company-filter-candidates)
476 (define-key keymap (vector (+ (aref (kbd "M-0") 0) i))
477 `(lambda () (interactive) (company-complete-number ,i))))
480 "Keymap that is enabled during an active completion.")
482 (defvar company--disabled-backends nil)
484 (defun company-init-backend (backend)
485 (and (symbolp backend)
486 (not (fboundp backend))
487 (ignore-errors (require backend nil t)))
489 (if (or (symbolp backend)
493 (funcall backend 'init)
494 (put backend 'company-init t))
496 (put backend 'company-init 'failed)
497 (unless (memq backend company--disabled-backends)
498 (message "Company back-end '%s' could not be initialized:\n%s"
499 backend (error-message-string err)))
500 (pushnew backend company--disabled-backends)
502 (mapc 'company-init-backend backend)))
504 (defvar company-default-lighter " company")
506 (defvar company-lighter company-default-lighter)
507 (make-variable-buffer-local 'company-lighter)
510 (define-minor-mode company-mode
511 "\"complete anything\"; is an in-buffer completion framework.
512 Completion starts automatically, depending on the values
513 `company-idle-delay' and `company-minimum-prefix-length'.
515 Completion can be controlled with the commands:
516 `company-complete-common', `company-complete-selection', `company-complete',
517 `company-select-next', `company-select-previous'. If these commands are
518 called before `company-idle-delay', completion will also start.
520 Completions can be searched with `company-search-candidates' or
521 `company-filter-candidates'. These can be used while completion is
524 The completion data is retrieved using `company-backends' and displayed using
525 `company-frontends'. If you want to start a specific back-end, call it
526 interactively or use `company-begin-backend'.
528 regular keymap (`company-mode-map'):
531 keymap during active completions (`company-active-map'):
533 \\{company-active-map}"
534 nil company-lighter company-mode-map
537 (add-hook 'pre-command-hook 'company-pre-command nil t)
538 (add-hook 'post-command-hook 'company-post-command nil t)
539 (mapc 'company-init-backend company-backends))
540 (remove-hook 'pre-command-hook 'company-pre-command t)
541 (remove-hook 'post-command-hook 'company-post-command t)
543 (kill-local-variable 'company-point)))
545 (define-globalized-minor-mode global-company-mode company-mode
546 (lambda () (unless (or noninteractive (eq (aref (buffer-name) 0) ?\s))
549 (defsubst company-assert-enabled ()
551 (company-uninstall-map)
552 (error "Company not enabled")))
554 ;;; keymaps ;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;
556 (defvar company-my-keymap nil)
557 (make-variable-buffer-local 'company-my-keymap)
559 (defvar company-emulation-alist '((t . nil)))
561 (defsubst company-enable-overriding-keymap (keymap)
562 (company-uninstall-map)
563 (setq company-my-keymap keymap))
565 (defun company-ensure-emulation-alist ()
566 (unless (eq 'company-emulation-alist (car emulation-mode-map-alists))
567 (setq emulation-mode-map-alists
568 (cons 'company-emulation-alist
569 (delq 'company-emulation-alist emulation-mode-map-alists)))))
571 (defun company-install-map ()
572 (unless (or (cdar company-emulation-alist)
573 (null company-my-keymap))
574 (setf (cdar company-emulation-alist) company-my-keymap)))
576 (defun company-uninstall-map ()
577 (setf (cdar company-emulation-alist) nil))
580 ;; Emacs calculates the active keymaps before reading the event. That means we
581 ;; cannot change the keymap from a timer. So we send a bogus command.
582 (defun company-ignore ()
584 (setq this-command last-command))
586 (global-set-key '[31415926] 'company-ignore)
588 (defun company-input-noop ()
589 (push 31415926 unread-command-events))
592 ;; posn-col-row is incorrect in older Emacsen when line-spacing is set
593 (defun company--col-row (&optional pos)
594 (let ((posn (posn-at-point pos)))
595 (cons (car (posn-col-row posn)) (cdr (posn-actual-col-row posn)))))
597 (defsubst company--column (&optional pos)
598 (car (posn-col-row (posn-at-point pos))))
600 (defsubst company--row (&optional pos)
601 (cdr (posn-actual-col-row (posn-at-point pos))))
603 ;;; backends ;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;
605 (defun company-grab (regexp &optional expression limit)
606 (when (looking-back regexp limit)
607 (or (match-string-no-properties (or expression 0)) "")))
609 (defun company-grab-line (regexp &optional expression)
610 (company-grab regexp expression (point-at-bol)))
612 (defun company-grab-symbol ()
613 (if (looking-at "\\_>")
614 (buffer-substring (point) (save-excursion (skip-syntax-backward "w_")
616 (unless (and (char-after) (memq (char-syntax (char-after)) '(?w ?_)))
619 (defun company-grab-word ()
620 (if (looking-at "\\>")
621 (buffer-substring (point) (save-excursion (skip-syntax-backward "w")
623 (unless (and (char-after) (eq (char-syntax (char-after)) ?w))
626 (defun company-in-string-or-comment ()
627 (let ((ppss (syntax-ppss)))
628 (or (car (setq ppss (nthcdr 3 ppss)))
629 (car (setq ppss (cdr ppss)))
632 (if (fboundp 'locate-dominating-file)
633 (defalias 'company-locate-dominating-file 'locate-dominating-file)
634 (defun company-locate-dominating-file (file name)
636 (let ((dir (file-name-directory file))
638 (while (not (equal dir prev-dir))
639 (when (file-exists-p (expand-file-name name dir))
642 dir (file-name-directory (directory-file-name dir))))))))
644 (defun company-call-backend (&rest args)
645 (if (functionp company-backend)
646 (apply company-backend args)
647 (apply 'company--multi-backend-adapter company-backend args)))
649 (defun company--multi-backend-adapter (backends command &rest args)
650 (let ((backends (remove-if (lambda (b) (eq 'failed (get b 'company-init)))
654 (loop for backend in backends
655 when (equal (funcall backend 'prefix)
657 nconc (apply backend 'candidates args)))
662 (dolist (backend backends)
663 (when (setq value (apply backend command args))
664 (return value))))))))
666 ;;; completion mechanism ;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;
668 (defvar company-backend nil)
669 (make-variable-buffer-local 'company-backend)
671 (defvar company-prefix nil)
672 (make-variable-buffer-local 'company-prefix)
674 (defvar company-candidates nil)
675 (make-variable-buffer-local 'company-candidates)
677 (defvar company-candidates-length nil)
678 (make-variable-buffer-local 'company-candidates-length)
680 (defvar company-candidates-cache nil)
681 (make-variable-buffer-local 'company-candidates-cache)
683 (defvar company-candidates-predicate nil)
684 (make-variable-buffer-local 'company-candidates-predicate)
686 (defvar company-common nil)
687 (make-variable-buffer-local 'company-common)
689 (defvar company-selection 0)
690 (make-variable-buffer-local 'company-selection)
692 (defvar company-selection-changed nil)
693 (make-variable-buffer-local 'company-selection-changed)
695 (defvar company--explicit-action nil
696 "Non-nil, if explicit completion took place.")
697 (make-variable-buffer-local 'company--explicit-action)
699 (defvar company--point-max nil)
700 (make-variable-buffer-local 'company--point-max)
702 (defvar company-point nil)
703 (make-variable-buffer-local 'company-point)
705 (defvar company-timer nil)
707 (defvar company-added-newline nil)
708 (make-variable-buffer-local 'company-added-newline)
710 (defsubst company-strip-prefix (str)
711 (substring str (length company-prefix)))
713 (defmacro company-with-candidate-inserted (candidate &rest body)
714 "Evaluate BODY with CANDIDATE temporarily inserted.
715 This is a tool for back-ends that need candidates inserted before they
716 can retrieve meta-data for them."
718 `(let ((inhibit-modification-hooks t)
719 (inhibit-point-motion-hooks t)
720 (modified-p (buffer-modified-p)))
721 (insert (company-strip-prefix ,candidate))
724 (delete-region company-point (point)))))
726 (defun company-explicit-action-p ()
727 "Return whether explicit completion action was taken by the user."
728 (or company--explicit-action
729 company-selection-changed))
731 (defsubst company-reformat (candidate)
732 ;; company-ispell needs this, because the results are always lower-case
733 ;; It's mory efficient to fix it only when they are displayed.
734 (concat company-prefix (substring candidate (length company-prefix))))
736 (defun company--should-complete ()
737 (and (not (or buffer-read-only overriding-terminal-local-map
740 ;; Check if in the middle of entering a key combination.
741 (or (equal (this-command-keys-vector) [])
742 (not (keymapp (key-binding (this-command-keys-vector)))))
743 (eq company-idle-delay t)
744 (or (eq t company-begin-commands)
745 (memq this-command company-begin-commands)
746 (and (symbolp this-command) (get this-command 'company-begin)))
747 (not (and transient-mark-mode mark-active))))
749 (defsubst company-call-frontends (command)
750 (dolist (frontend company-frontends)
752 (funcall frontend command)
753 (error (error "Company: Front-end %s error \"%s\" on command %s"
754 frontend (error-message-string err) command)))))
756 (defsubst company-set-selection (selection &optional force-update)
757 (setq selection (max 0 (min (1- company-candidates-length) selection)))
758 (when (or force-update (not (equal selection company-selection)))
759 (setq company-selection selection
760 company-selection-changed t)
761 (company-call-frontends 'update)))
763 (defun company-apply-predicate (candidates predicate)
765 (dolist (c candidates)
766 (when (funcall predicate c)
770 (defun company-update-candidates (candidates)
771 (setq company-candidates-length (length candidates))
772 (if (> company-selection 0)
773 ;; Try to restore the selection
774 (let ((selected (nth company-selection company-candidates)))
775 (setq company-selection 0
776 company-candidates candidates)
778 (while (and candidates (string< (pop candidates) selected))
779 (incf company-selection))
781 ;; Make sure selection isn't out of bounds.
782 (setq company-selection (min (1- company-candidates-length)
783 company-selection)))))
784 (setq company-selection 0
785 company-candidates candidates))
787 (push (cons company-prefix company-candidates) company-candidates-cache)
789 (let ((completion-ignore-case (company-call-backend 'ignore-case)))
790 (setq company-common (try-completion company-prefix company-candidates)))
791 (when (eq company-common t)
792 (setq company-candidates nil)))
794 (defun company-calculate-candidates (prefix)
795 (let ((candidates (cdr (assoc prefix company-candidates-cache)))
796 (ignore-case (company-call-backend 'ignore-case)))
798 (when company-candidates-cache
799 (let ((len (length prefix))
800 (completion-ignore-case ignore-case)
802 (dotimes (i (1+ len))
803 (when (setq prev (cdr (assoc (substring prefix 0 (- len i))
804 company-candidates-cache)))
805 (setq candidates (all-completions prefix prev))
807 ;; no cache match, call back-end
809 (setq candidates (company-call-backend 'candidates prefix))
810 (when company-candidates-predicate
812 (company-apply-predicate candidates
813 company-candidates-predicate)))
814 (unless (company-call-backend 'sorted)
815 (setq candidates (sort candidates 'string<)))
816 (when (company-call-backend 'duplicates)
818 (let ((c2 candidates))
820 (setcdr c2 (progn (while (equal (pop c2) (car c2)))
824 (not (eq t (compare-strings (car candidates) nil nil
825 prefix nil nil ignore-case)))))
826 ;; Don't start when already completed and unique.
828 ;; Not the right place? maybe when setting?
829 (and company-candidates t))))
831 (defun company-idle-begin (buf win tick pos)
833 (eq buf (current-buffer))
834 (eq win (selected-window))
835 (eq tick (buffer-chars-modified-tick))
837 (not company-candidates)
838 (not (equal (point) company-point))
839 (let ((company-idle-delay t)
840 (company-begin-commands t))
842 (when company-candidates
844 (company-post-command)))))
846 (defun company-auto-begin ()
847 (company-assert-enabled)
849 (not company-candidates)
850 (let ((company-idle-delay t)
851 (company-minimum-prefix-length 0)
852 (company-begin-commands t))
854 ;; Return non-nil if active.
857 (defun company-manual-begin ()
859 (setq company--explicit-action t)
860 (company-auto-begin))
862 (defun company-other-backend (&optional backward)
863 (interactive (list current-prefix-arg))
864 (company-assert-enabled)
866 (let* ((after (cdr (member company-backend company-backends)))
867 (before (cdr (member company-backend (reverse company-backends))))
869 (append before (reverse after))
870 (append after (reverse before)))))
872 (dolist (backend next)
873 (when (ignore-errors (company-begin-backend backend))
875 (company-manual-begin))
876 (unless company-candidates
877 (error "No other back-end")))
879 (defun company-require-match-p ()
880 (let ((backend-value (company-call-backend 'require-match)))
881 (or (eq backend-value t)
882 (and (if (functionp company-require-match)
883 (funcall company-require-match)
884 (eq company-require-match t))
885 (not (eq backend-value 'never))))))
887 (defun company-punctuation-p (input)
888 "Return non-nil, if input starts with punctuation or parentheses."
889 (memq (char-syntax (string-to-char input)) '(?. ?\( ?\))))
891 (defun company-auto-complete-p (input)
892 "Return non-nil, if input starts with punctuation or parentheses."
893 (and (if (functionp company-auto-complete)
894 (funcall company-auto-complete)
895 company-auto-complete)
896 (if (functionp company-auto-complete-chars)
897 (funcall company-auto-complete-chars input)
898 (if (consp company-auto-complete-chars)
899 (memq (char-syntax (string-to-char input))
900 company-auto-complete-chars)
901 (string-match (substring input 0 1) company-auto-complete-chars)))))
903 (defun company--incremental-p ()
904 (and (> (point) company-point)
905 (> (point-max) company--point-max)
906 (not (eq this-command 'backward-delete-char-untabify))
907 (equal (buffer-substring (- company-point (length company-prefix))
911 (defsubst company--string-incremental-p (old-prefix new-prefix)
912 (and (> (length new-prefix) (length old-prefix))
913 (equal old-prefix (substring new-prefix 0 (length old-prefix)))))
915 (defun company--continue-failed (new-prefix)
916 (when (company--incremental-p)
917 (let ((input (buffer-substring-no-properties (point) company-point)))
919 ((company-auto-complete-p input)
922 (goto-char company-point)
923 (company-complete-selection)
925 ((and (company--string-incremental-p company-prefix new-prefix)
926 (company-require-match-p))
927 ;; wrong incremental input, but required match
928 (backward-delete-char (length input))
930 (message "Matching input is required")
932 ((equal company-prefix (car company-candidates))
933 ;; last input was actually success
934 (company-cancel company-prefix)
937 (defun company--good-prefix-p (prefix)
938 (and (or (company-explicit-action-p)
939 (>= (or (cdr-safe prefix) (length prefix))
940 company-minimum-prefix-length))
941 (stringp (or (car-safe prefix) prefix))))
943 (defun company--continue ()
944 (when (company-call-backend 'no-cache company-prefix)
945 ;; Don't complete existing candidates, fetch new ones.
946 (setq company-candidates-cache nil))
947 (let* ((new-prefix (company-call-backend 'prefix))
948 (c (when (and (company--good-prefix-p new-prefix)
949 (setq new-prefix (or (car-safe new-prefix) new-prefix))
950 (= (- (point) (length new-prefix))
951 (- company-point (length company-prefix))))
952 (setq new-prefix (or (car-safe new-prefix) new-prefix))
953 (company-calculate-candidates new-prefix))))
956 ;; t means complete/unique.
957 (company-cancel new-prefix)
961 (setq company-prefix new-prefix)
962 (company-update-candidates c)
964 (t (company--continue-failed new-prefix)))
967 (defun company--begin-new ()
969 (dolist (backend (if company-backend
970 ;; prefer manual override
971 (list company-backend)
974 (if (or (symbolp backend)
976 (when (or (not (symbolp backend))
977 (eq t (get backend 'company-init))
978 (unless (get backend 'company-init)
979 (company-init-backend backend)))
980 (funcall backend 'prefix))
981 (company--multi-backend-adapter backend 'prefix)))
983 (when (company--good-prefix-p prefix)
984 (setq prefix (or (car-safe prefix) prefix)
985 company-backend backend
986 c (company-calculate-candidates prefix))
987 ;; t means complete/unique. We don't start, so no hooks.
989 (when company--explicit-action
990 (message "No completion found"))
991 (setq company-prefix prefix)
992 (when (symbolp backend)
993 (setq company-lighter (concat " " (symbol-name backend))))
994 (company-update-candidates c)
995 (run-hook-with-args 'company-completion-started-hook
996 (company-explicit-action-p))
997 (company-call-frontends 'show)))
1000 (defun company-begin ()
1001 (or (and company-candidates (company--continue))
1002 (and (company--should-complete) (company--begin-new)))
1003 (when company-candidates
1004 (when (and company-end-of-buffer-workaround (eobp))
1005 (save-excursion (insert "\n"))
1006 (setq company-added-newline (buffer-chars-modified-tick)))
1007 (setq company-point (point)
1008 company--point-max (point-max))
1009 (company-ensure-emulation-alist)
1010 (company-enable-overriding-keymap company-active-map)
1011 (company-call-frontends 'update)))
1013 (defun company-cancel (&optional result)
1014 (and company-added-newline
1015 (> (point-max) (point-min))
1016 (let ((tick (buffer-chars-modified-tick)))
1017 (delete-region (1- (point-max)) (point-max))
1018 (equal tick company-added-newline))
1019 ;; Only set unmodified when tick remained the same since insert.
1020 (set-buffer-modified-p nil))
1021 (when company-prefix
1022 (if (stringp result)
1024 (company-call-backend 'pre-completion result)
1025 (run-hook-with-args 'company-completion-finished-hook result)
1026 (company-call-backend 'post-completion result))
1027 (run-hook-with-args 'company-completion-cancelled-hook result)))
1028 (setq company-added-newline nil
1031 company-candidates nil
1032 company-candidates-length nil
1033 company-candidates-cache nil
1034 company-candidates-predicate nil
1037 company-selection-changed nil
1038 company--explicit-action nil
1039 company-lighter company-default-lighter
1040 company--point-max nil
1043 (cancel-timer company-timer))
1044 (company-search-mode 0)
1045 (company-call-frontends 'hide)
1046 (company-enable-overriding-keymap nil))
1048 (defun company-abort ()
1051 ;; Don't start again, unless started manually.
1052 (setq company-point (point)))
1054 (defun company-finish (result)
1055 (insert (company-strip-prefix result))
1056 (company-cancel result)
1057 ;; Don't start again, unless started manually.
1058 (setq company-point (point)))
1060 (defsubst company-keep (command)
1061 (and (symbolp command) (get command 'company-keep)))
1063 (defun company-pre-command ()
1064 (unless (company-keep this-command)
1066 (when company-candidates
1067 (company-call-frontends 'pre-command))
1068 (error (message "Company: An error occurred in pre-command")
1069 (message "%s" (error-message-string err))
1072 (cancel-timer company-timer)
1073 (setq company-timer nil))
1074 (company-uninstall-map))
1076 (defun company-post-command ()
1077 (unless (company-keep this-command)
1080 (unless (equal (point) company-point)
1082 (if company-candidates
1083 (company-call-frontends 'post-command)
1084 (and (numberp company-idle-delay)
1085 (or (eq t company-begin-commands)
1086 (memq this-command company-begin-commands))
1088 (run-with-timer company-idle-delay nil
1090 (current-buffer) (selected-window)
1091 (buffer-chars-modified-tick) (point))))))
1092 (error (message "Company: An error occurred in post-command")
1093 (message "%s" (error-message-string err))
1095 (company-install-map))
1097 ;;; search ;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;
1099 (defvar company-search-string nil)
1100 (make-variable-buffer-local 'company-search-string)
1102 (defvar company-search-lighter " Search: \"\"")
1103 (make-variable-buffer-local 'company-search-lighter)
1105 (defvar company-search-old-map nil)
1106 (make-variable-buffer-local 'company-search-old-map)
1108 (defvar company-search-old-selection 0)
1109 (make-variable-buffer-local 'company-search-old-selection)
1111 (defun company-search (text lines)
1112 (let ((quoted (regexp-quote text))
1114 (dolist (line lines)
1115 (when (string-match quoted line (length company-prefix))
1119 (defun company-search-printing-char ()
1121 (company-search-assert-enabled)
1122 (setq company-search-string
1123 (concat (or company-search-string "") (string last-command-event))
1124 company-search-lighter (concat " Search: \"" company-search-string
1126 (let ((pos (company-search company-search-string
1127 (nthcdr company-selection company-candidates))))
1130 (company-set-selection (+ company-selection pos) t))))
1132 (defun company-search-repeat-forward ()
1133 "Repeat the incremental search in completion candidates forward."
1135 (company-search-assert-enabled)
1136 (let ((pos (company-search company-search-string
1137 (cdr (nthcdr company-selection
1138 company-candidates)))))
1141 (company-set-selection (+ company-selection pos 1) t))))
1143 (defun company-search-repeat-backward ()
1144 "Repeat the incremental search in completion candidates backwards."
1146 (company-search-assert-enabled)
1147 (let ((pos (company-search company-search-string
1148 (nthcdr (- company-candidates-length
1150 (reverse company-candidates)))))
1153 (company-set-selection (- company-selection pos 1) t))))
1155 (defun company-create-match-predicate ()
1156 (setq company-candidates-predicate
1157 `(lambda (candidate)
1158 ,(if company-candidates-predicate
1159 `(and (string-match ,company-search-string candidate)
1160 (funcall ,company-candidates-predicate
1162 `(string-match ,company-search-string candidate))))
1163 (company-update-candidates
1164 (company-apply-predicate company-candidates company-candidates-predicate))
1165 ;; Invalidate cache.
1166 (setq company-candidates-cache (cons company-prefix company-candidates)))
1168 (defun company-filter-printing-char ()
1170 (company-search-assert-enabled)
1171 (company-search-printing-char)
1172 (company-create-match-predicate)
1173 (company-call-frontends 'update))
1175 (defun company-search-kill-others ()
1176 "Limit the completion candidates to the ones matching the search string."
1178 (company-search-assert-enabled)
1179 (company-create-match-predicate)
1180 (company-search-mode 0)
1181 (company-call-frontends 'update))
1183 (defun company-search-abort ()
1184 "Abort searching the completion candidates."
1186 (company-search-assert-enabled)
1187 (company-set-selection company-search-old-selection t)
1188 (company-search-mode 0))
1190 (defun company-search-other-char ()
1192 (company-search-assert-enabled)
1193 (company-search-mode 0)
1194 (company--unread-last-input))
1196 (defvar company-search-map
1198 (keymap (make-keymap)))
1199 (if (fboundp 'max-char)
1200 (set-char-table-range (nth 1 keymap) (cons #x100 (max-char))
1201 'company-search-printing-char)
1203 ;; obsolete in Emacs 23
1204 (let ((l (generic-character-list))
1205 (table (nth 1 keymap)))
1207 (set-char-table-default table (car l) 'company-search-printing-char)
1208 (setq l (cdr l))))))
1209 (define-key keymap [t] 'company-search-other-char)
1211 (define-key keymap (make-string 1 i) 'company-search-other-char)
1214 (define-key keymap (vector i) 'company-search-printing-char)
1216 (let ((meta-map (make-sparse-keymap)))
1217 (define-key keymap (char-to-string meta-prefix-char) meta-map)
1218 (define-key keymap [escape] meta-map))
1219 (define-key keymap (vector meta-prefix-char t) 'company-search-other-char)
1220 (define-key keymap "\e\e\e" 'company-search-other-char)
1221 (define-key keymap [escape escape escape] 'company-search-other-char)
1223 (define-key keymap "\C-g" 'company-search-abort)
1224 (define-key keymap "\C-s" 'company-search-repeat-forward)
1225 (define-key keymap "\C-r" 'company-search-repeat-backward)
1226 (define-key keymap "\C-o" 'company-search-kill-others)
1228 "Keymap used for incrementally searching the completion candidates.")
1230 (define-minor-mode company-search-mode
1231 "Search mode for completion candidates.
1232 Don't start this directly, use `company-search-candidates' or
1233 `company-filter-candidates'."
1234 nil company-search-lighter nil
1235 (if company-search-mode
1236 (if (company-manual-begin)
1238 (setq company-search-old-selection company-selection)
1239 (company-call-frontends 'update))
1240 (setq company-search-mode nil))
1241 (kill-local-variable 'company-search-string)
1242 (kill-local-variable 'company-search-lighter)
1243 (kill-local-variable 'company-search-old-selection)
1244 (company-enable-overriding-keymap company-active-map)))
1246 (defsubst company-search-assert-enabled ()
1247 (company-assert-enabled)
1248 (unless company-search-mode
1249 (company-uninstall-map)
1250 (error "Company not in search mode")))
1252 (defun company-search-candidates ()
1253 "Start searching the completion candidates incrementally.
1255 \\<company-search-map>Search can be controlled with the commands:
1256 - `company-search-repeat-forward' (\\[company-search-repeat-forward])
1257 - `company-search-repeat-backward' (\\[company-search-repeat-backward])
1258 - `company-search-abort' (\\[company-search-abort])
1260 Regular characters are appended to the search string.
1262 The command `company-search-kill-others' (\\[company-search-kill-others]) uses
1263 the search string to limit the completion candidates."
1265 (company-search-mode 1)
1266 (company-enable-overriding-keymap company-search-map))
1268 (defvar company-filter-map
1269 (let ((keymap (make-keymap)))
1270 (define-key keymap [remap company-search-printing-char]
1271 'company-filter-printing-char)
1272 (set-keymap-parent keymap company-search-map)
1274 "Keymap used for incrementally searching the completion candidates.")
1276 (defun company-filter-candidates ()
1277 "Start filtering the completion candidates incrementally.
1278 This works the same way as `company-search-candidates' immediately
1279 followed by `company-search-kill-others' after each input."
1281 (company-search-mode 1)
1282 (company-enable-overriding-keymap company-filter-map))
1284 ;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;
1286 (defun company-select-next ()
1287 "Select the next candidate in the list."
1289 (when (company-manual-begin)
1290 (company-set-selection (1+ company-selection))))
1292 (defun company-select-previous ()
1293 "Select the previous candidate in the list."
1295 (when (company-manual-begin)
1296 (company-set-selection (1- company-selection))))
1298 (defun company-select-next-or-abort ()
1299 "Select the next candidate if more than one, else abort
1300 and invoke the normal binding."
1302 (if (> company-candidates-length 1)
1303 (company-select-next)
1305 (company--unread-last-input)))
1307 (defun company-select-previous-or-abort ()
1308 "Select the previous candidate if more than one, else abort
1309 and invoke the normal binding."
1311 (if (> company-candidates-length 1)
1312 (company-select-previous)
1314 (company--unread-last-input)))
1316 (defun company-select-mouse (event)
1317 "Select the candidate picked by the mouse."
1319 (when (nth 4 (event-start event))
1320 (company-set-selection (- (cdr (posn-actual-col-row (event-start event)))
1325 (defun company-complete-mouse (event)
1326 "Complete the candidate picked by the mouse."
1328 (when (company-select-mouse event)
1329 (company-complete-selection)))
1331 (defun company-complete-selection ()
1332 "Complete the selected candidate."
1334 (when (company-manual-begin)
1335 (company-finish (nth company-selection company-candidates))))
1337 (defun company-complete-common ()
1338 "Complete the common part of all candidates."
1340 (when (company-manual-begin)
1341 (if (and (not (cdr company-candidates))
1342 (equal company-common (car company-candidates)))
1343 (company-complete-selection)
1344 (insert (company-strip-prefix company-common)))))
1346 (defun company-complete ()
1347 "Complete the common part of all candidates or the current selection.
1348 The first time this is called, the common part is completed, the second time, or
1349 when the selection has been changed, the selected candidate is completed."
1351 (when (company-manual-begin)
1352 (if (or company-selection-changed
1353 (eq last-command 'company-complete-common))
1354 (call-interactively 'company-complete-selection)
1355 (call-interactively 'company-complete-common)
1356 (setq this-command 'company-complete-common))))
1358 (defun company-complete-number (n)
1359 "Complete the Nth candidate.
1360 To show the number next to the candidates in some back-ends, enable
1361 `company-show-numbers'."
1362 (when (company-manual-begin)
1363 (and (< n 1) (> n company-candidates-length)
1364 (error "No candidate number %d" n))
1366 (company-finish (nth n company-candidates))))
1368 ;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;
1370 (defconst company-space-strings-limit 100)
1372 (defconst company-space-strings
1374 (dotimes (i company-space-strings-limit)
1375 (push (make-string (- company-space-strings-limit 1 i) ?\ ) lst))
1376 (apply 'vector lst)))
1378 (defsubst company-space-string (len)
1379 (if (< len company-space-strings-limit)
1380 (aref company-space-strings len)
1381 (make-string len ?\ )))
1383 (defsubst company-safe-substring (str from &optional to)
1384 (if (> from (string-width str))
1388 (move-to-column from)
1389 (let ((beg (point)))
1393 (concat (buffer-substring beg (point))
1394 (let ((padding (- to (current-column))))
1396 (company-space-string padding)))))
1397 (buffer-substring beg (point-max)))))))
1399 ;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;
1401 (defvar company-last-metadata nil)
1402 (make-variable-buffer-local 'company-last-metadata)
1404 (defun company-fetch-metadata ()
1405 (let ((selected (nth company-selection company-candidates)))
1406 (unless (equal selected (car company-last-metadata))
1407 (setq company-last-metadata
1408 (cons selected (company-call-backend 'meta selected))))
1409 (cdr company-last-metadata)))
1411 (defun company-doc-buffer (&optional string)
1412 (with-current-buffer (get-buffer-create "*Company meta-data*")
1416 (defvar company--electric-commands
1417 '(scroll-other-window scroll-other-window-down)
1418 "List of Commands that won't break out of electric commands.")
1420 (defmacro company--electric-do (&rest body)
1421 (declare (indent 0) (debug t))
1422 `(when (company-manual-begin)
1423 (save-window-excursion
1424 (let ((height (window-height))
1425 (row (company--row))
1428 (and (< (window-height) height)
1429 (< (- (window-height) row 2) company-tooltip-limit)
1430 (recenter (- (window-height) row 2)))
1431 (while (memq (setq cmd (key-binding (vector (list (read-event)))))
1432 company--electric-commands)
1433 (call-interactively cmd))
1434 (company--unread-last-input)))))
1436 (defun company--unread-last-input ()
1437 (when last-input-event
1438 (clear-this-command-keys t)
1439 (setq unread-command-events (list last-input-event))))
1441 (defun company-show-doc-buffer ()
1442 "Temporarily show a buffer with the complete documentation for the selection."
1444 (company--electric-do
1445 (let* ((selected (nth company-selection company-candidates))
1446 (doc-buffer (or (company-call-backend 'doc-buffer selected)
1447 (error "No documentation available"))))
1448 (with-current-buffer doc-buffer
1449 (goto-char (point-min)))
1450 (display-buffer doc-buffer t))))
1451 (put 'company-show-doc-buffer 'company-keep t)
1453 (defun company-show-location ()
1454 "Temporarily display a buffer showing the selected candidate in context."
1456 (company--electric-do
1457 (let* ((selected (nth company-selection company-candidates))
1458 (location (company-call-backend 'location selected))
1459 (pos (or (cdr location) (error "No location available")))
1460 (buffer (or (and (bufferp (car location)) (car location))
1461 (find-file-noselect (car location) t))))
1462 (with-selected-window (display-buffer buffer t)
1465 (if (bufferp (car location))
1467 (goto-char (point-min))
1468 (forward-line (1- pos))))
1469 (set-window-start nil (point))))))
1470 (put 'company-show-location 'company-keep t)
1472 ;;; package functions ;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;
1474 (defvar company-callback nil)
1475 (make-variable-buffer-local 'company-callback)
1477 (defvar company-begin-with-marker nil)
1478 (make-variable-buffer-local 'company-begin-with-marker)
1480 (defun company-remove-callback (&optional ignored)
1481 (remove-hook 'company-completion-finished-hook company-callback t)
1482 (remove-hook 'company-completion-cancelled-hook 'company-remove-callback t)
1483 (remove-hook 'company-completion-finished-hook 'company-remove-callback t)
1484 (when company-begin-with-marker
1485 (set-marker company-begin-with-marker nil)))
1487 (defun company-begin-backend (backend &optional callback)
1488 "Start a completion at point using BACKEND."
1489 (interactive (let ((val (completing-read "Company back-end: "
1491 'functionp nil "company-")))
1493 (list (intern val)))))
1494 (when (setq company-callback callback)
1495 (add-hook 'company-completion-finished-hook company-callback nil t))
1496 (add-hook 'company-completion-cancelled-hook 'company-remove-callback nil t)
1497 (add-hook 'company-completion-finished-hook 'company-remove-callback nil t)
1498 (setq company-backend backend)
1499 ;; Return non-nil if active.
1500 (or (company-manual-begin)
1501 (error "Cannot complete at point")))
1503 (defun company-begin-with (candidates
1504 &optional prefix-length require-match callback)
1505 "Start a completion at point.
1506 CANDIDATES is the list of candidates to use and PREFIX-LENGTH is the length of
1507 the prefix that already is in the buffer before point. It defaults to 0.
1509 CALLBACK is a function called with the selected result if the user successfully
1510 completes the input.
1513 \(company-begin-with '\(\"foo\" \"foobar\" \"foobarbaz\"\)\)"
1514 (setq company-begin-with-marker (copy-marker (point) t))
1515 (company-begin-backend
1516 `(lambda (command &optional arg &rest ignored)
1518 ((eq command 'prefix)
1519 (when (equal (point) (marker-position company-begin-with-marker))
1520 (buffer-substring ,(- (point) (or prefix-length 0)) (point))))
1521 ((eq command 'candidates)
1522 (all-completions arg ',candidates))
1523 ((eq command 'require-match)
1527 ;;; pseudo-tooltip ;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;
1529 (defvar company-pseudo-tooltip-overlay nil)
1530 (make-variable-buffer-local 'company-pseudo-tooltip-overlay)
1532 (defvar company-tooltip-offset 0)
1533 (make-variable-buffer-local 'company-tooltip-offset)
1535 (defun company-pseudo-tooltip-update-offset (selection num-lines limit)
1538 (setq company-tooltip-offset
1539 (max (min selection company-tooltip-offset)
1540 (- selection -1 limit)))
1542 (when (<= company-tooltip-offset 1)
1544 (setq company-tooltip-offset 0))
1546 (when (>= company-tooltip-offset (- num-lines limit 1))
1548 (when (= selection (1- num-lines))
1549 (decf company-tooltip-offset)
1550 (when (<= company-tooltip-offset 1)
1551 (setq company-tooltip-offset 0)
1558 (defsubst company-round-tab (arg)
1559 (* (/ (+ arg tab-width) tab-width) tab-width))
1561 (defun company-untabify (str)
1562 (let* ((pieces (split-string str "\t"))
1565 (setcar copy (company-safe-substring
1566 (car copy) 0 (company-round-tab (string-width (car copy)))))
1568 (apply 'concat pieces)))
1570 (defun company-fill-propertize (line width selected)
1571 (setq line (company-safe-substring line 0 width))
1572 (add-text-properties 0 width '(face company-tooltip
1573 mouse-face company-tooltip-mouse)
1575 (add-text-properties 0 (length company-common)
1576 '(face company-tooltip-common
1577 mouse-face company-tooltip-mouse)
1580 (if (and company-search-string
1581 (string-match (regexp-quote company-search-string) line
1582 (length company-prefix)))
1584 (add-text-properties (match-beginning 0) (match-end 0)
1585 '(face company-tooltip-selection)
1587 (when (< (match-beginning 0) (length company-common))
1588 (add-text-properties (match-beginning 0) (length company-common)
1589 '(face company-tooltip-common-selection)
1591 (add-text-properties 0 width '(face company-tooltip-selection
1592 mouse-face company-tooltip-selection)
1594 (add-text-properties 0 (length company-common)
1595 '(face company-tooltip-common-selection
1596 mouse-face company-tooltip-selection)
1602 (defun company-buffer-lines (beg end)
1605 (while (and (= 1 (vertical-motion 1))
1607 (push (buffer-substring beg (min end (1- (point)))) lines)
1609 (unless (eq beg end)
1610 (push (buffer-substring beg end) lines))
1613 (defsubst company-modify-line (old new offset)
1614 (concat (company-safe-substring old 0 offset)
1616 (company-safe-substring old (+ offset (length new)))))
1618 (defsubst company--length-limit (lst limit)
1619 (if (nthcdr limit lst)
1623 (defun company--replacement-string (lines old column nl &optional align-top)
1625 (let ((width (length (car lines))))
1626 (when (> width (- (window-width) column))
1627 (setq column (max 0 (- (window-width) width)))))
1631 ;; untouched lines first
1632 (dotimes (i (- (length old) (length lines)))
1633 (push (pop old) new)))
1634 ;; length into old lines.
1636 (push (company-modify-line (pop old) (pop lines) column) new))
1637 ;; Append whole new lines.
1639 (push (concat (company-space-string column) (pop lines)) new))
1641 (let ((str (concat (when nl "\n")
1642 (mapconcat 'identity (nreverse new) "\n")
1644 (font-lock-append-text-property 0 (length str) 'face 'default str)
1647 (defun company--create-lines (selection limit)
1649 (let ((len company-candidates-length)
1658 ;; Scroll to offset.
1659 (setq limit (company-pseudo-tooltip-update-offset selection len limit))
1661 (when (> company-tooltip-offset 0)
1662 (setq previous (format "...(%d)" company-tooltip-offset)))
1664 (setq remainder (- len limit company-tooltip-offset)
1665 remainder (when (> remainder 0)
1666 (setq remainder (format "...(%d)" remainder))))
1668 (decf selection company-tooltip-offset)
1669 (setq width (max (length previous) (length remainder))
1670 lines (nthcdr company-tooltip-offset company-candidates)
1675 (setq width (max (length (pop lines-copy)) width)))
1676 (setq width (min width (window-width)))
1678 (setq lines-copy lines)
1680 ;; number can make tooltip too long
1681 (when company-show-numbers
1682 (setq numbered company-tooltip-offset))
1685 (push (propertize (company-safe-substring previous 0 width)
1686 'face 'company-tooltip)
1690 (push (company-fill-propertize
1691 (if (>= numbered 10)
1692 (company-reformat (pop lines))
1695 (company-safe-substring (company-reformat (pop lines))
1698 width (equal i selection))
1702 (push (propertize (company-safe-substring remainder 0 width)
1703 'face 'company-tooltip)
1706 (setq lines (nreverse new))))
1710 (defsubst company--window-inner-height ()
1711 (let ((edges (window-inside-edges (selected-window))))
1712 (- (nth 3 edges) (nth 1 edges))))
1714 (defsubst company--pseudo-tooltip-height ()
1715 "Calculate the appropriate tooltip height.
1716 Returns a negative number if the tooltip should be displayed above point."
1717 (let* ((lines (company--row))
1718 (below (- (company--window-inner-height) 1 lines)))
1719 (if (and (< below (min company-tooltip-minimum company-candidates-length))
1721 (- (max 3 (min company-tooltip-limit lines)))
1722 (max 3 (min company-tooltip-limit below)))))
1724 (defun company-pseudo-tooltip-show (row column selection)
1725 (company-pseudo-tooltip-hide)
1730 (let* ((height (company--pseudo-tooltip-height))
1734 (setq row (+ row height -1)
1737 (let* ((nl (< (move-to-window-line row) row))
1739 (end (save-excursion
1740 (move-to-window-line (+ row (abs height)))
1742 (ov (make-overlay beg end))
1743 (args (list (mapcar 'company-untabify
1744 (company-buffer-lines beg end))
1747 (setq company-pseudo-tooltip-overlay ov)
1748 (overlay-put ov 'company-replacement-args args)
1749 (overlay-put ov 'company-before
1750 (apply 'company--replacement-string
1751 (company--create-lines selection (abs height))
1754 (overlay-put ov 'company-column column)
1755 (overlay-put ov 'company-height (abs height))))))
1757 (defun company-pseudo-tooltip-show-at-point (pos)
1758 (let ((col-row (company--col-row pos)))
1760 (company-pseudo-tooltip-show (1+ (cdr col-row)) (car col-row)
1761 company-selection))))
1763 (defun company-pseudo-tooltip-edit (lines selection)
1764 (let ((column (overlay-get company-pseudo-tooltip-overlay 'company-column))
1765 (height (overlay-get company-pseudo-tooltip-overlay 'company-height)))
1766 (overlay-put company-pseudo-tooltip-overlay 'company-before
1767 (apply 'company--replacement-string
1768 (company--create-lines selection height)
1769 (overlay-get company-pseudo-tooltip-overlay
1770 'company-replacement-args)))))
1772 (defun company-pseudo-tooltip-hide ()
1773 (when company-pseudo-tooltip-overlay
1774 (delete-overlay company-pseudo-tooltip-overlay)
1775 (setq company-pseudo-tooltip-overlay nil)))
1777 (defun company-pseudo-tooltip-hide-temporarily ()
1778 (when (overlayp company-pseudo-tooltip-overlay)
1779 (overlay-put company-pseudo-tooltip-overlay 'invisible nil)
1780 (overlay-put company-pseudo-tooltip-overlay 'before-string nil)))
1782 (defun company-pseudo-tooltip-unhide ()
1783 (when company-pseudo-tooltip-overlay
1784 (overlay-put company-pseudo-tooltip-overlay 'invisible t)
1785 (overlay-put company-pseudo-tooltip-overlay 'before-string
1786 (overlay-get company-pseudo-tooltip-overlay 'company-before))
1787 (overlay-put company-pseudo-tooltip-overlay 'window (selected-window))))
1789 (defun company-pseudo-tooltip-frontend (command)
1790 "A `company-mode' front-end similar to a tool-tip but based on overlays."
1792 (pre-command (company-pseudo-tooltip-hide-temporarily))
1794 (let ((old-height (if (overlayp company-pseudo-tooltip-overlay)
1795 (overlay-get company-pseudo-tooltip-overlay
1798 (new-height (company--pseudo-tooltip-height)))
1799 (unless (and (>= (* old-height new-height) 0)
1800 (>= (abs old-height) (abs new-height)))
1802 (company-pseudo-tooltip-show-at-point (- (point)
1803 (length company-prefix)))))
1804 (company-pseudo-tooltip-unhide))
1805 (hide (company-pseudo-tooltip-hide)
1806 (setq company-tooltip-offset 0))
1807 (update (when (overlayp company-pseudo-tooltip-overlay)
1808 (company-pseudo-tooltip-edit company-candidates
1809 company-selection)))))
1811 (defun company-pseudo-tooltip-unless-just-one-frontend (command)
1812 "`company-pseudo-tooltip-frontend', but not shown for single candidates."
1813 (unless (and (eq command 'post-command)
1814 (not (cdr company-candidates)))
1815 (company-pseudo-tooltip-frontend command)))
1817 ;;; overlay ;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;
1819 (defvar company-preview-overlay nil)
1820 (make-variable-buffer-local 'company-preview-overlay)
1822 (defun company-preview-show-at-point (pos)
1823 (company-preview-hide)
1825 (setq company-preview-overlay (make-overlay pos pos))
1827 (let ((completion(nth company-selection company-candidates)))
1828 (setq completion (propertize completion 'face 'company-preview))
1829 (add-text-properties 0 (length company-common)
1830 '(face company-preview-common) completion)
1832 ;; Add search string
1833 (and company-search-string
1834 (string-match (regexp-quote company-search-string) completion)
1835 (add-text-properties (match-beginning 0)
1837 '(face company-preview-search)
1840 (setq completion (company-strip-prefix completion))
1842 (and (equal pos (point))
1843 (not (equal completion ""))
1844 (add-text-properties 0 1 '(cursor t) completion))
1846 (overlay-put company-preview-overlay 'after-string completion)
1847 (overlay-put company-preview-overlay 'window (selected-window))))
1849 (defun company-preview-hide ()
1850 (when company-preview-overlay
1851 (delete-overlay company-preview-overlay)
1852 (setq company-preview-overlay nil)))
1854 (defun company-preview-frontend (command)
1855 "A `company-mode' front-end showing the selection as if it had been inserted."
1857 (pre-command (company-preview-hide))
1858 (post-command (company-preview-show-at-point (point)))
1859 (hide (company-preview-hide))))
1861 (defun company-preview-if-just-one-frontend (command)
1862 "`company-preview-frontend', but only shown for single candidates."
1863 (unless (and (eq command 'post-command)
1864 (cdr company-candidates))
1865 (company-preview-frontend command)))
1867 ;;; echo ;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;
1869 (defvar company-echo-last-msg nil)
1870 (make-variable-buffer-local 'company-echo-last-msg)
1872 (defvar company-echo-timer nil)
1874 (defvar company-echo-delay .01)
1876 (defun company-echo-show (&optional getter)
1878 (setq company-echo-last-msg (funcall getter)))
1879 (let ((message-log-max nil))
1880 (if company-echo-last-msg
1881 (message "%s" company-echo-last-msg)
1884 (defsubst company-echo-show-soon (&optional getter)
1885 (when company-echo-timer
1886 (cancel-timer company-echo-timer))
1887 (setq company-echo-timer (run-with-timer 0 nil 'company-echo-show getter)))
1889 (defsubst company-echo-show-when-idle (&optional getter)
1891 (company-echo-show getter)))
1893 (defsubst company-echo-show-when-not-busy (&optional getter)
1894 "Run `company-echo-show' with arg GETTER once Emacs isn't busy."
1895 (when (sit-for company-echo-delay)
1896 (company-echo-show getter)))
1898 (defun company-echo-format ()
1900 (let ((limit (window-width (minibuffer-window)))
1902 ;; Roll to selection.
1903 (candidates (nthcdr company-selection company-candidates))
1904 (i (if company-show-numbers company-selection 99999))
1908 (setq comp (company-reformat (pop candidates))
1909 len (+ len 1 (length comp)))
1913 (setq comp (propertize (format "%d: %s" i comp)
1914 'face 'company-echo))
1917 (add-text-properties 3 (+ 3 (length company-common))
1918 '(face company-echo-common) comp))
1919 (setq comp (propertize comp 'face 'company-echo))
1920 (add-text-properties 0 (length company-common)
1921 '(face company-echo-common) comp))
1923 (setq candidates nil)
1926 (mapconcat 'identity (nreverse msg) " ")))
1928 (defun company-echo-strip-common-format ()
1930 (let ((limit (window-width (minibuffer-window)))
1931 (len (+ (length company-prefix) 2))
1932 ;; Roll to selection.
1933 (candidates (nthcdr company-selection company-candidates))
1934 (i (if company-show-numbers company-selection 99999))
1938 (setq comp (company-strip-prefix (pop candidates))
1939 len (+ len 2 (length comp)))
1942 (setq comp (format "%s (%d)" comp i))
1946 (setq candidates nil)
1947 (push (propertize comp 'face 'company-echo) msg)))
1949 (concat (propertize company-prefix 'face 'company-echo-common) "{"
1950 (mapconcat 'identity (nreverse msg) ", ")
1953 (defun company-echo-hide ()
1954 (unless (equal company-echo-last-msg "")
1955 (setq company-echo-last-msg "")
1956 (company-echo-show)))
1958 (defun company-echo-frontend (command)
1959 "A `company-mode' front-end showing the candidates in the echo area."
1961 (post-command (company-echo-show-soon 'company-echo-format))
1962 (hide (company-echo-hide))))
1964 (defun company-echo-strip-common-frontend (command)
1965 "A `company-mode' front-end showing the candidates in the echo area."
1967 (post-command (company-echo-show-soon 'company-echo-strip-common-format))
1968 (hide (company-echo-hide))))
1970 (defun company-echo-metadata-frontend (command)
1971 "A `company-mode' front-end showing the documentation in the echo area."
1973 (post-command (company-echo-show-when-idle 'company-fetch-metadata))
1974 (hide (company-echo-hide))))
1976 ;; templates ;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;
1978 (autoload 'company-template-declare-template "company-template")
1981 ;;; company.el ends here