1 ;;; company.el --- extensible inline text completion mechanism
3 ;; Copyright (C) 2009 Nikolaj Schumacher
5 ;; Author: Nikolaj Schumacher <bugs * nschum de>
7 ;; Keywords: abbrev, convenience, matchis
8 ;; URL: http://nschum.de/src/emacs/company/
9 ;; Compatibility: GNU Emacs 22.x, GNU Emacs 23.x
11 ;; This file is NOT part of GNU Emacs.
13 ;; This program is free software; you can redistribute it and/or
14 ;; modify it under the terms of the GNU General Public License
15 ;; as published by the Free Software Foundation; either version 2
16 ;; of the License, or (at your option) any later version.
18 ;; This program is distributed in the hope that it will be useful,
19 ;; but WITHOUT ANY WARRANTY; without even the implied warranty of
20 ;; MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
21 ;; GNU General Public License for more details.
23 ;; You should have received a copy of the GNU General Public License
24 ;; along with this program. If not, see <http://www.gnu.org/licenses/>.
28 ;; Company is a modular completion mechanism. Modules for retrieving completion
29 ;; candidates are called back-ends, modules for displaying them are front-ends.
31 ;; Company comes with many back-ends, e.g. `company-elisp'. These are
32 ;; distributed in individual files and can be used individually.
34 ;; Place company.el and the back-ends you want to use in a directory and add the
35 ;; following to your .emacs:
36 ;; (add-to-list 'load-path "/path/to/company")
37 ;; (autoload 'company-mode "company" nil t)
39 ;; Enable company-mode with M-x company-mode. For further information look at
40 ;; the documentation for `company-mode' (C-h f company-mode RET)
42 ;; If you want to start a specific back-end, call it interactively or use
43 ;; `company-begin-backend'. For example:
44 ;; M-x company-abbrev will prompt for and insert an abbrev.
46 ;; To write your own back-end, look at the documentation for `company-backends'.
47 ;; Here is a simple example completing "foo":
49 ;; (defun company-my-backend (command &optional arg &rest ignored)
51 ;; ('prefix (when (looking-back "foo\\>")
53 ;; ('candidates (list "foobar" "foobaz" "foobarbaz"))
54 ;; ('meta (format "This value is named %s" arg))))
56 ;; Sometimes it is a good idea to mix two back-ends together, for example to
57 ;; enrich gtags with dabbrev-code results (to emulate local variables):
58 ;; To do this, add a list with the merged back-ends as an element in
62 ;; When point is at the very end of the buffer, the pseudo-tooltip appears very
63 ;; wrong, unless company is allowed to temporarily insert a fake newline.
64 ;; This behavior is enabled by `company-end-of-buffer-workaround'.
68 ;; Added `company-clang' back-end.
69 ;; The semantic back-end now shows meta information for local symbols.
70 ;; Added compatibility for CEDET in Emacs 23.2.
73 ;; Added `company-other-backend'.
74 ;; Idle completion no longer interrupts multi-key command input.
75 ;; Added `company-ropemacs' and `company-pysmell' back-ends.
78 ;; In C modes . and -> now count towards `company-minimum-prefix-length'.
79 ;; Reverted default front-end back to `company-preview-if-just-one-frontend'.
80 ;; The pseudo tooltip will no longer be clipped at the right window edge.
81 ;; Added `company-tooltip-minimum'.
82 ;; Windows compatibility fixes.
85 ;; Added `global-company-mode'.
86 ;; Performance enhancements.
87 ;; Added `company-eclim' back-end.
88 ;; Added safer workaround for Emacs `posn-col-row' bug.
91 ;; Automatic completion is now aborted if the prefix gets too short.
92 ;; Added option `company-dabbrev-time-limit'.
93 ;; `company-backends' now supports merging back-ends.
94 ;; Added back-end `company-dabbrev-code' for generic code.
95 ;; Fixed `company-begin-with'.
98 ;; Added 'stop prefix to prevent dabbrev from completing inside of symbols.
99 ;; Fixed issues with tabbar-mode and line-spacing.
100 ;; Performance enhancements.
103 ;; Added `company-begin-commands' option.
104 ;; Added abbrev, tempo and Xcode back-ends.
105 ;; Back-ends are now interactive. You can start them with M-x backend-name.
106 ;; Added `company-begin-with' for starting company from elisp-code.
108 ;; Added `company-require-match' and `company-auto-complete' options.
110 ;; 2009-04-05 (0.2.1)
111 ;; Improved Emacs Lisp back-end behavior for local variables.
112 ;; Added `company-elisp-detect-function-context' option.
113 ;; The mouse can now be used for selection.
116 ;; Added `company-show-location'.
117 ;; Added etags back-end.
118 ;; Added work-around for end-of-buffer bug.
119 ;; Added `company-filter-candidates'.
120 ;; More local Lisp variables are now included in the candidates.
122 ;; 2009-03-21 (0.1.5)
123 ;; Fixed elisp documentation buffer always showing the same doc.
124 ;; Added `company-echo-strip-common-frontend'.
125 ;; Added `company-show-numbers' option and M-0 ... M-9 default bindings.
126 ;; Don't hide the echo message if it isn't shown.
133 (eval-when-compile (require 'cl))
135 (add-to-list 'debug-ignored-errors "^.* frontend cannot be used twice$")
136 (add-to-list 'debug-ignored-errors "^Echo area cannot be used twice$")
137 (add-to-list 'debug-ignored-errors "^No \\(document\\|loc\\)ation available$")
138 (add-to-list 'debug-ignored-errors "^Company not ")
139 (add-to-list 'debug-ignored-errors "^No candidate number ")
140 (add-to-list 'debug-ignored-errors "^Cannot complete at point$")
141 (add-to-list 'debug-ignored-errors "^No other back-end$")
143 (defgroup company nil
144 "Extensible inline text completion mechanism"
149 (defface company-tooltip
150 '((t :background "yellow"
151 :foreground "black"))
152 "*Face used for the tool tip."
155 (defface company-tooltip-selection
156 '((default :inherit company-tooltip)
157 (((class color) (min-colors 88)) (:background "orange1"))
158 (t (:background "green")))
159 "*Face used for the selection in the tool tip."
162 (defface company-tooltip-mouse
163 '((default :inherit highlight))
164 "*Face used for the tool tip item under the mouse."
167 (defface company-tooltip-common
168 '((t :inherit company-tooltip
170 "*Face used for the common completion in the tool tip."
173 (defface company-tooltip-common-selection
174 '((t :inherit company-tooltip-selection
176 "*Face used for the selected common completion in the tool tip."
179 (defface company-preview
180 '((t :background "blue4"
181 :foreground "wheat"))
182 "*Face used for the completion preview."
185 (defface company-preview-common
186 '((t :inherit company-preview
188 "*Face used for the common part of the completion preview."
191 (defface company-preview-search
192 '((t :inherit company-preview
193 :background "blue1"))
194 "*Face used for the search string in the completion preview."
197 (defface company-echo nil
198 "*Face used for completions in the echo area."
201 (defface company-echo-common
202 '((((background dark)) (:foreground "firebrick1"))
203 (((background light)) (:background "firebrick4")))
204 "*Face used for the common part of completions in the echo area."
207 (defun company-frontends-set (variable value)
209 (let ((remainder value))
210 (setcdr remainder (delq (car remainder) (cdr remainder))))
211 (and (memq 'company-pseudo-tooltip-unless-just-one-frontend value)
212 (memq 'company-pseudo-tooltip-frontend value)
213 (error "Pseudo tooltip frontend cannot be used twice"))
214 (and (memq 'company-preview-if-just-one-frontend value)
215 (memq 'company-preview-frontend value)
216 (error "Preview frontend cannot be used twice"))
217 (and (memq 'company-echo value)
218 (memq 'company-echo-metadata-frontend value)
219 (error "Echo area cannot be used twice"))
220 ;; preview must come last
221 (dolist (f '(company-preview-if-just-one-frontend company-preview-frontend))
223 (setq value (append (delq f value) (list f)))))
224 (set variable value))
226 (defcustom company-frontends '(company-pseudo-tooltip-unless-just-one-frontend
227 company-preview-if-just-one-frontend
228 company-echo-metadata-frontend)
229 "*The list of active front-ends (visualizations).
230 Each front-end is a function that takes one argument. It is called with
231 one of the following arguments:
233 'show: When the visualization should start.
235 'hide: When the visualization should end.
237 'update: When the data has been updated.
239 'pre-command: Before every command that is executed while the
240 visualization is active.
242 'post-command: After every command that is executed while the
243 visualization is active.
245 The visualized data is stored in `company-prefix', `company-candidates',
246 `company-common', `company-selection', `company-point' and
247 `company-search-string'."
248 :set 'company-frontends-set
250 :type '(repeat (choice (const :tag "echo" company-echo-frontend)
251 (const :tag "echo, strip common"
252 company-echo-strip-common-frontend)
253 (const :tag "show echo meta-data in echo"
254 company-echo-metadata-frontend)
255 (const :tag "pseudo tooltip"
256 company-pseudo-tooltip-frontend)
257 (const :tag "pseudo tooltip, multiple only"
258 company-pseudo-tooltip-unless-just-one-frontend)
259 (const :tag "preview" company-preview-frontend)
260 (const :tag "preview, unique only"
261 company-preview-if-just-one-frontend)
262 (function :tag "custom function" nil))))
264 (defcustom company-tooltip-limit 10
265 "*The maximum number of candidates in the tool tip"
269 (defcustom company-tooltip-minimum 6
270 "*The minimum height of the tool tip.
271 If this many lines are not available, prefer to display the tooltip above."
275 (defvar company-safe-backends
276 '((company-abbrev . "Abbrev")
277 (company-clang . "clang")
278 (company-css . "CSS")
279 (company-dabbrev . "dabbrev for plain text")
280 (company-dabbrev-code . "dabbrev for code")
281 (company-eclim . "eclim (an Eclipse interace)")
282 (company-elisp . "Emacs Lisp")
283 (company-etags . "etags")
284 (company-files . "Files")
285 (company-gtags . "GNU Global")
286 (company-ispell . "ispell")
287 (company-keywords . "Programming language keywords")
288 (company-nxml . "nxml")
289 (company-oddmuse . "Oddmuse")
290 (company-pysmell . "PySmell")
291 (company-ropemacs . "ropemacs")
292 (company-semantic . "CEDET Semantic")
293 (company-tempo . "Tempo templates")
294 (company-xcode . "Xcode")))
295 (put 'company-safe-backends 'risky-local-variable t)
297 (defun company-safe-backends-p (backends)
298 (and (consp backends)
299 (not (dolist (backend backends)
300 (unless (if (consp backend)
301 (company-safe-backends-p backend)
302 (assq backend company-safe-backends))
305 (defcustom company-backends '(company-elisp company-nxml company-css
306 company-eclim company-semantic company-clang
307 company-xcode company-ropemacs
308 (company-gtags company-etags company-dabbrev-code
309 company-pysmell company-keywords)
310 company-oddmuse company-files company-dabbrev)
311 "*The list of active back-ends (completion engines).
312 Each list elements can itself be a list of back-ends. In that case their
313 completions are merged. Otherwise only the first matching back-end returns
316 `company-begin-backend' can be used to start a specific back-end,
317 `company-other-backend' will skip to the next matching back-end in the list.
319 Each back-end is a function that takes a variable number of arguments.
320 The first argument is the command requested from the back-end. It is one
323 'prefix: The back-end should return the text to be completed. It must be
324 text immediately before `point'. Returning nil passes control to the next
325 back-end. The function should return 'stop if it should complete but cannot
326 \(e.g. if it is in the middle of a string\). If the returned value is only
327 part of the prefix (e.g. the part after \"->\" in C), the back-end may return a
328 cons of prefix and prefix length, which is then used in the
329 `company-minimum-prefix-length' test.
331 'candidates: The second argument is the prefix to be completed. The
332 return value should be a list of candidates that start with the prefix.
336 'sorted: The back-end may return t here to indicate that the candidates
337 are sorted and will not need to be sorted again.
339 'duplicates: If non-nil, company will take care of removing duplicates
342 'no-cache: Usually company doesn't ask for candidates again as completion
343 progresses, unless the back-end returns t for this command. The second
344 argument is the latest prefix.
346 'meta: The second argument is a completion candidate. The back-end should
347 return a (short) documentation string for it.
349 'doc-buffer: The second argument is a completion candidate. The back-end should
350 create a buffer (preferably with `company-doc-buffer'), fill it with
351 documentation and return it.
353 'location: The second argument is a completion candidate. The back-end can
354 return the cons of buffer and buffer location, or of file and line
355 number where the completion candidate was defined.
357 'require-match: If this value is t, the user is not allowed to enter anything
358 not offering as a candidate. Use with care! The default value nil gives the
359 user that choice with `company-require-match'. Return value 'never overrides
360 that option the other way around.
362 The back-end should return nil for all commands it does not support or
363 does not know about. It should also be callable interactively and use
364 `company-begin-backend' to start itself in that case."
369 ,@(mapcar (lambda (b) `(const :tag ,(cdr b) ,(car b)))
370 company-safe-backends)
371 (symbol :tag "User defined")
372 (repeat :tag "Merged Back-ends"
373 (choice :tag "Back-end"
374 ,@(mapcar (lambda (b)
375 `(const :tag ,(cdr b) ,(car b)))
376 company-safe-backends)
377 (symbol :tag "User defined"))))))
379 (put 'company-backends 'safe-local-variable 'company-safe-backends-p)
381 (defcustom company-completion-started-hook nil
382 "*Hook run when company starts completing.
383 The hook is called with one argument that is non-nil if the completion was
388 (defcustom company-completion-cancelled-hook nil
389 "*Hook run when company cancels completing.
390 The hook is called with one argument that is non-nil if the completion was
395 (defcustom company-completion-finished-hook nil
396 "*Hook run when company successfully completes.
397 The hook is called with the selected candidate as an argument."
401 (defcustom company-minimum-prefix-length 3
402 "*The minimum prefix length for automatic completion."
404 :type '(integer :tag "prefix length"))
406 (defcustom company-require-match 'company-explicit-action-p
407 "*If enabled, disallow non-matching input.
408 This can be a function do determine if a match is required.
410 This can be overridden by the back-end, if it returns t or 'never to
411 'require-match. `company-auto-complete' also takes precedence over this."
413 :type '(choice (const :tag "Off" nil)
414 (function :tag "Predicate function")
415 (const :tag "On, if user interaction took place"
416 'company-explicit-action-p)
417 (const :tag "On" t)))
419 (defcustom company-auto-complete 'company-explicit-action-p
420 "Determines when to auto-complete.
421 If this is enabled, all characters from `company-auto-complete-chars' complete
422 the selected completion. This can also be a function."
424 :type '(choice (const :tag "Off" nil)
425 (function :tag "Predicate function")
426 (const :tag "On, if user interaction took place"
427 'company-explicit-action-p)
428 (const :tag "On" t)))
430 (defcustom company-auto-complete-chars '(?\ ?\( ?\) ?. ?\" ?$ ?\' ?< ?| ?!)
431 "Determines which characters trigger an automatic completion.
432 See `company-auto-complete'. If this is a string, each string character causes
433 completion. If it is a list of syntax description characters (see
434 `modify-syntax-entry'), all characters with that syntax auto-complete.
436 This can also be a function, which is called with the new input and should
437 return non-nil if company should auto-complete.
439 A character that is part of a valid candidate never starts auto-completion."
441 :type '(choice (string :tag "Characters")
443 (const :tag "Whitespace" ?\ )
444 (const :tag "Symbol" ?_)
445 (const :tag "Opening parentheses" ?\()
446 (const :tag "Closing parentheses" ?\))
447 (const :tag "Word constituent" ?w)
448 (const :tag "Punctuation." ?.)
449 (const :tag "String quote." ?\")
450 (const :tag "Paired delimiter." ?$)
451 (const :tag "Expression quote or prefix operator." ?\')
452 (const :tag "Comment starter." ?<)
453 (const :tag "Comment ender." ?>)
454 (const :tag "Character-quote." ?/)
455 (const :tag "Generic string fence." ?|)
456 (const :tag "Generic comment fence." ?!))
457 (function :tag "Predicate function")))
459 (defcustom company-idle-delay .7
460 "*The idle delay in seconds until automatic completions starts.
461 A value of nil means never complete automatically, t means complete
462 immediately when a prefix of `company-minimum-prefix-length' is reached."
464 :type '(choice (const :tag "never (nil)" nil)
465 (const :tag "immediate (t)" t)
466 (number :tag "seconds")))
468 (defcustom company-begin-commands t
469 "*A list of commands following which company will start completing.
470 If this is t, it will complete after any command. See `company-idle-delay'.
472 Alternatively any command with a non-nil 'company-begin property is treated as
473 if it was on this list."
475 :type '(choice (const :tag "Any command" t)
476 (const :tag "Self insert command" '(self-insert-command))
477 (repeat :tag "Commands" function)))
479 (defcustom company-show-numbers nil
480 "*If enabled, show quick-access numbers for the first ten candidates."
482 :type '(choice (const :tag "off" nil)
483 (const :tag "on" t)))
485 (defvar company-end-of-buffer-workaround t
486 "*Work around a visualization bug when completing at the end of the buffer.
487 The work-around consists of adding a newline.")
489 ;;; mode ;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;
491 (defvar company-mode-map (make-sparse-keymap)
492 "Keymap used by `company-mode'.")
494 (defvar company-active-map
495 (let ((keymap (make-sparse-keymap)))
496 (define-key keymap "\e\e\e" 'company-abort)
497 (define-key keymap "\C-g" 'company-abort)
498 (define-key keymap (kbd "M-n") 'company-select-next)
499 (define-key keymap (kbd "M-p") 'company-select-previous)
500 (define-key keymap (kbd "<down>") 'company-select-next)
501 (define-key keymap (kbd "<up>") 'company-select-previous)
502 (define-key keymap [down-mouse-1] 'ignore)
503 (define-key keymap [down-mouse-3] 'ignore)
504 (define-key keymap [mouse-1] 'company-complete-mouse)
505 (define-key keymap [mouse-3] 'company-select-mouse)
506 (define-key keymap [up-mouse-1] 'ignore)
507 (define-key keymap [up-mouse-3] 'ignore)
508 (define-key keymap "\C-m" 'company-complete-selection)
509 (define-key keymap "\t" 'company-complete-common)
510 (define-key keymap (kbd "<f1>") 'company-show-doc-buffer)
511 (define-key keymap "\C-w" 'company-show-location)
512 (define-key keymap "\C-s" 'company-search-candidates)
513 (define-key keymap "\C-\M-s" 'company-filter-candidates)
515 (define-key keymap (vector (+ (aref (kbd "M-0") 0) i))
516 `(lambda () (interactive) (company-complete-number ,i))))
519 "Keymap that is enabled during an active completion.")
521 (defvar company--disabled-backends nil)
523 (defun company-init-backend (backend)
524 (and (symbolp backend)
525 (not (fboundp backend))
526 (ignore-errors (require backend nil t)))
528 (if (or (symbolp backend)
532 (funcall backend 'init)
533 (put backend 'company-init t))
535 (put backend 'company-init 'failed)
536 (unless (memq backend company--disabled-backends)
537 (message "Company back-end '%s' could not be initialized:\n%s"
538 backend (error-message-string err)))
539 (push backend company--disabled-backends)
541 (mapc 'company-init-backend backend)))
543 (defvar company-default-lighter " company")
545 (defvar company-lighter company-default-lighter)
546 (make-variable-buffer-local 'company-lighter)
549 (define-minor-mode company-mode
550 "\"complete anything\"; in in-buffer completion framework.
551 Completion starts automatically, depending on the values
552 `company-idle-delay' and `company-minimum-prefix-length'.
554 Completion can be controlled with the commands:
555 `company-complete-common', `company-complete-selection', `company-complete',
556 `company-select-next', `company-select-previous'. If these commands are
557 called before `company-idle-delay', completion will also start.
559 Completions can be searched with `company-search-candidates' or
560 `company-filter-candidates'. These can be used while completion is
563 The completion data is retrieved using `company-backends' and displayed using
564 `company-frontends'. If you want to start a specific back-end, call it
565 interactively or use `company-begin-backend'.
567 regular keymap (`company-mode-map'):
570 keymap during active completions (`company-active-map'):
572 \\{company-active-map}"
573 nil company-lighter company-mode-map
576 (add-hook 'pre-command-hook 'company-pre-command nil t)
577 (add-hook 'post-command-hook 'company-post-command nil t)
578 (mapc 'company-init-backend company-backends))
579 (remove-hook 'pre-command-hook 'company-pre-command t)
580 (remove-hook 'post-command-hook 'company-post-command t)
582 (kill-local-variable 'company-point)))
584 (define-globalized-minor-mode global-company-mode company-mode
585 (lambda () (company-mode 1)))
587 (defsubst company-assert-enabled ()
589 (company-uninstall-map)
590 (error "Company not enabled")))
592 ;;; keymaps ;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;
594 (defvar company-overriding-keymap-bound nil)
595 (make-variable-buffer-local 'company-overriding-keymap-bound)
597 (defvar company-old-keymap nil)
598 (make-variable-buffer-local 'company-old-keymap)
600 (defvar company-my-keymap nil)
601 (make-variable-buffer-local 'company-my-keymap)
603 (defsubst company-enable-overriding-keymap (keymap)
604 (setq company-my-keymap keymap)
605 (when company-overriding-keymap-bound
606 (company-uninstall-map)))
608 (defun company-install-map ()
609 (unless (or company-overriding-keymap-bound
610 (null company-my-keymap))
611 (setq company-old-keymap overriding-terminal-local-map
612 overriding-terminal-local-map company-my-keymap
613 company-overriding-keymap-bound t)))
615 (defun company-uninstall-map ()
616 (when (eq overriding-terminal-local-map company-my-keymap)
617 (setq overriding-terminal-local-map company-old-keymap
618 company-overriding-keymap-bound nil)))
621 ;; Emacs calculates the active keymaps before reading the event. That means we
622 ;; cannot change the keymap from a timer. So we send a bogus command.
623 (defun company-ignore ()
625 (setq this-command last-command))
627 (global-set-key '[31415926] 'company-ignore)
629 (defun company-input-noop ()
630 (push 31415926 unread-command-events))
633 ;; posn-col-row is incorrect in older Emacsen when line-spacing is set
634 (defun company--col-row (&optional pos)
635 (let ((posn (posn-at-point pos)))
636 (cons (car (posn-col-row posn)) (cdr (posn-actual-col-row posn)))))
638 (defsubst company--column (&optional pos)
639 (car (posn-col-row (posn-at-point pos))))
641 (defsubst company--row (&optional pos)
642 (cdr (posn-actual-col-row (posn-at-point pos))))
644 ;;; backends ;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;
646 (defun company-grab (regexp &optional expression limit)
647 (when (looking-back regexp limit)
648 (or (match-string-no-properties (or expression 0)) "")))
650 (defun company-grab-line (regexp &optional expression)
651 (company-grab regexp expression (point-at-bol)))
653 (defun company-grab-symbol ()
654 (if (looking-at "\\_>")
655 (buffer-substring (point) (save-excursion (skip-syntax-backward "w_")
657 (unless (and (char-after) (memq (char-syntax (char-after)) '(?w ?_)))
660 (defun company-grab-word ()
661 (if (looking-at "\\>")
662 (buffer-substring (point) (save-excursion (skip-syntax-backward "w")
664 (unless (and (char-after) (eq (char-syntax (char-after)) ?w))
667 (defun company-in-string-or-comment ()
668 (let ((ppss (syntax-ppss)))
669 (or (car (setq ppss (nthcdr 3 ppss)))
670 (car (setq ppss (cdr ppss)))
673 (if (fboundp 'locate-dominating-file)
674 (defalias 'company-locate-dominating-file 'locate-dominating-file)
675 (defun company-locate-dominating-file (file name)
677 (let ((dir (file-name-directory file))
679 (while (not (equal dir prev-dir))
680 (when (file-exists-p (expand-file-name name dir))
683 dir (file-name-directory (directory-file-name dir))))))))
685 (defun company-call-backend (&rest args)
686 (if (functionp company-backend)
687 (apply company-backend args)
688 (apply 'company--multi-backend-adapter company-backend args)))
690 (defun company--multi-backend-adapter (backends command &rest args)
693 (apply 'append (mapcar (lambda (backend) (apply backend command args))
699 (dolist (backend backends)
700 (when (setq value (apply backend command args))
703 ;;; completion mechanism ;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;
705 (defvar company-backend nil)
706 (make-variable-buffer-local 'company-backend)
708 (defvar company-prefix nil)
709 (make-variable-buffer-local 'company-prefix)
711 (defvar company-candidates nil)
712 (make-variable-buffer-local 'company-candidates)
714 (defvar company-candidates-length nil)
715 (make-variable-buffer-local 'company-candidates-length)
717 (defvar company-candidates-cache nil)
718 (make-variable-buffer-local 'company-candidates-cache)
720 (defvar company-candidates-predicate nil)
721 (make-variable-buffer-local 'company-candidates-predicate)
723 (defvar company-common nil)
724 (make-variable-buffer-local 'company-common)
726 (defvar company-selection 0)
727 (make-variable-buffer-local 'company-selection)
729 (defvar company-selection-changed nil)
730 (make-variable-buffer-local 'company-selection-changed)
732 (defvar company--explicit-action nil
733 "Non-nil, if explicit completion took place.")
734 (make-variable-buffer-local 'company--explicit-action)
736 (defvar company--point-max nil)
737 (make-variable-buffer-local 'company--point-max)
739 (defvar company-point nil)
740 (make-variable-buffer-local 'company-point)
742 (defvar company-timer nil)
744 (defvar company-added-newline nil)
745 (make-variable-buffer-local 'company-added-newline)
747 (defsubst company-strip-prefix (str)
748 (substring str (length company-prefix)))
750 (defun company-explicit-action-p ()
751 "Return whether explicit completion action was taken by the user."
752 (or company--explicit-action
753 company-selection-changed))
755 (defsubst company-reformat (candidate)
756 ;; company-ispell needs this, because the results are always lower-case
757 ;; It's mory efficient to fix it only when they are displayed.
758 (concat company-prefix (substring candidate (length company-prefix))))
760 (defun company--should-complete ()
761 (and (not (or buffer-read-only overriding-terminal-local-map
762 overriding-local-map))
763 ;; Check if in the middle of entering a key combination.
764 (or (equal (this-command-keys-vector) [])
765 (not (keymapp (key-binding (this-command-keys-vector)))))
766 (eq company-idle-delay t)
767 (or (eq t company-begin-commands)
768 (memq this-command company-begin-commands)
769 (and (symbolp this-command) (get this-command 'company-begin)))
770 (not (and transient-mark-mode mark-active))))
772 (defsubst company-call-frontends (command)
773 (dolist (frontend company-frontends)
775 (funcall frontend command)
776 (error (error "Company: Front-end %s error \"%s\" on command %s"
777 frontend (error-message-string err) command)))))
779 (defsubst company-set-selection (selection &optional force-update)
780 (setq selection (max 0 (min (1- company-candidates-length) selection)))
781 (when (or force-update (not (equal selection company-selection)))
782 (setq company-selection selection
783 company-selection-changed t)
784 (company-call-frontends 'update)))
786 (defun company-apply-predicate (candidates predicate)
788 (dolist (c candidates)
789 (when (funcall predicate c)
793 (defun company-update-candidates (candidates)
794 (setq company-candidates-length (length candidates))
795 (if (> company-selection 0)
796 ;; Try to restore the selection
797 (let ((selected (nth company-selection company-candidates)))
798 (setq company-selection 0
799 company-candidates candidates)
801 (while (and candidates (string< (pop candidates) selected))
802 (incf company-selection))
804 ;; Make sure selection isn't out of bounds.
805 (setq company-selection (min (1- company-candidates-length)
806 company-selection)))))
807 (setq company-selection 0
808 company-candidates candidates))
810 (push (cons company-prefix company-candidates) company-candidates-cache)
812 (let ((completion-ignore-case (company-call-backend 'ignore-case)))
813 (setq company-common (try-completion company-prefix company-candidates)))
814 (when (eq company-common t)
815 (setq company-candidates nil)))
817 (defun company-calculate-candidates (prefix)
818 (let ((candidates (cdr (assoc prefix company-candidates-cache))))
820 (when company-candidates-cache
821 (let ((len (length prefix))
822 (completion-ignore-case (company-call-backend 'ignore-case))
824 (dotimes (i (1+ len))
825 (when (setq prev (cdr (assoc (substring prefix 0 (- len i))
826 company-candidates-cache)))
827 (setq candidates (all-completions prefix prev))
829 ;; no cache match, call back-end
831 (setq candidates (company-call-backend 'candidates prefix))
832 (when company-candidates-predicate
834 (company-apply-predicate candidates
835 company-candidates-predicate)))
836 (unless (company-call-backend 'sorted)
837 (setq candidates (sort candidates 'string<)))
838 (when (company-call-backend 'duplicates)
840 (let ((c2 candidates))
842 (setcdr c2 (progn (while (equal (pop c2) (car c2)))
844 (if (or (cdr candidates)
845 (not (equal (car candidates) prefix)))
846 ;; Don't start when already completed and unique.
848 ;; Not the right place? maybe when setting?
849 (and company-candidates t))))
851 (defun company-idle-begin (buf win tick pos)
853 (eq buf (current-buffer))
854 (eq win (selected-window))
855 (eq tick (buffer-chars-modified-tick))
857 (not company-candidates)
858 (not (equal (point) company-point))
859 (let ((company-idle-delay t)
860 (company-begin-commands t))
862 (when company-candidates
864 (company-post-command)))))
866 (defun company-auto-begin ()
867 (company-assert-enabled)
869 (not company-candidates)
870 (let ((company-idle-delay t)
871 (company-minimum-prefix-length 0)
872 (company-begin-commands t))
874 ;; Return non-nil if active.
877 (defun company-manual-begin ()
879 (setq company--explicit-action t)
880 (company-auto-begin))
882 (defun company-other-backend (&optional backward)
883 (interactive (list current-prefix-arg))
884 (company-assert-enabled)
886 (let* ((after (cdr (member company-backend company-backends)))
887 (before (cdr (member company-backend (reverse company-backends))))
889 (append before (reverse after))
890 (append after (reverse before)))))
892 (dolist (backend next)
893 (when (ignore-errors (company-begin-backend backend))
895 (company-manual-begin))
896 (unless company-candidates
897 (error "No other back-end")))
899 (defun company-require-match-p ()
900 (let ((backend-value (company-call-backend 'require-match)))
901 (or (eq backend-value t)
902 (and (if (functionp company-require-match)
903 (funcall company-require-match)
904 (eq company-require-match t))
905 (not (eq backend-value 'never))))))
907 (defun company-punctuation-p (input)
908 "Return non-nil, if input starts with punctuation or parentheses."
909 (memq (char-syntax (string-to-char input)) '(?. ?\( ?\))))
911 (defun company-auto-complete-p (input)
912 "Return non-nil, if input starts with punctuation or parentheses."
913 (and (if (functionp company-auto-complete)
914 (funcall company-auto-complete)
915 company-auto-complete)
916 (if (functionp company-auto-complete-chars)
917 (funcall company-auto-complete-chars input)
918 (if (consp company-auto-complete-chars)
919 (memq (char-syntax (string-to-char input))
920 company-auto-complete-chars)
921 (string-match (substring input 0 1) company-auto-complete-chars)))))
923 (defun company--incremental-p ()
924 (and (> (point) company-point)
925 (> (point-max) company--point-max)
926 (not (eq this-command 'backward-delete-char-untabify))
927 (equal (buffer-substring (- company-point (length company-prefix))
931 (defsubst company--string-incremental-p (old-prefix new-prefix)
932 (and (> (length new-prefix) (length old-prefix))
933 (equal old-prefix (substring new-prefix 0 (length old-prefix)))))
935 (defun company--continue-failed (new-prefix)
936 (when (company--incremental-p)
937 (let ((input (buffer-substring-no-properties (point) company-point)))
939 ((company-auto-complete-p input)
942 (goto-char company-point)
943 (company-complete-selection)
945 ((and (company--string-incremental-p company-prefix new-prefix)
946 (company-require-match-p))
947 ;; wrong incremental input, but required match
948 (backward-delete-char (length input))
950 (message "Matching input is required")
952 ((equal company-prefix (car company-candidates))
953 ;; last input was actually success
954 (company-cancel company-prefix)
957 (defun company--good-prefix-p (prefix)
958 (and (or (company-explicit-action-p)
959 (>= (or (cdr-safe prefix) (length prefix))
960 company-minimum-prefix-length))
961 (stringp (or (car-safe prefix) prefix))))
963 (defun company--continue ()
964 (when (company-call-backend 'no-cache company-prefix)
965 ;; Don't complete existing candidates, fetch new ones.
966 (setq company-candidates-cache nil))
967 (let* ((new-prefix (company-call-backend 'prefix))
968 (c (when (and (company--good-prefix-p new-prefix)
969 (setq new-prefix (or (car-safe new-prefix) new-prefix))
970 (= (- (point) (length new-prefix))
971 (- company-point (length company-prefix))))
972 (setq new-prefix (or (car-safe new-prefix) new-prefix))
973 (company-calculate-candidates new-prefix))))
976 ;; t means complete/unique.
977 (company-cancel new-prefix)
981 (setq company-prefix new-prefix)
982 (company-update-candidates c)
984 (t (company--continue-failed new-prefix)))
987 (defun company--begin-new ()
989 (dolist (backend (if company-backend
990 ;; prefer manual override
991 (list company-backend)
994 (if (or (symbolp backend)
996 (when (or (not (symbolp backend))
997 (eq t (get backend 'company-init))
998 (unless (get backend 'company-init)
999 (company-init-backend backend)))
1000 (funcall backend 'prefix))
1001 (company--multi-backend-adapter backend 'prefix)))
1003 (when (company--good-prefix-p prefix)
1004 (setq prefix (or (car-safe prefix) prefix)
1005 company-backend backend
1006 c (company-calculate-candidates prefix))
1007 ;; t means complete/unique. We don't start, so no hooks.
1009 (setq company-prefix prefix)
1010 (when (symbolp backend)
1011 (setq company-lighter (concat " " (symbol-name backend))))
1012 (company-update-candidates c)
1013 (run-hook-with-args 'company-completion-started-hook
1014 (company-explicit-action-p))
1015 (company-call-frontends 'show)))
1018 (defun company-begin ()
1019 (setq company-candidates
1020 (or (and company-candidates (company--continue))
1021 (and (company--should-complete) (company--begin-new))))
1022 (when company-candidates
1023 (when (and company-end-of-buffer-workaround (eobp))
1024 (save-excursion (insert "\n"))
1025 (setq company-added-newline (buffer-chars-modified-tick)))
1026 (setq company-point (point)
1027 company--point-max (point-max))
1028 (company-enable-overriding-keymap company-active-map)
1029 (company-call-frontends 'update)))
1031 (defun company-cancel (&optional result)
1032 (and company-added-newline
1033 (> (point-max) (point-min))
1034 (let ((tick (buffer-chars-modified-tick)))
1035 (delete-region (1- (point-max)) (point-max))
1036 (equal tick company-added-newline))
1037 ;; Only set unmodified when tick remained the same since insert.
1038 (set-buffer-modified-p nil))
1039 (when company-prefix
1040 (if (stringp result)
1041 (run-hook-with-args 'company-completion-finished-hook result)
1042 (run-hook-with-args 'company-completion-cancelled-hook result)))
1043 (setq company-added-newline nil
1046 company-candidates nil
1047 company-candidates-length nil
1048 company-candidates-cache nil
1049 company-candidates-predicate nil
1052 company-selection-changed nil
1053 company--explicit-action nil
1054 company-lighter company-default-lighter
1055 company--point-max nil
1058 (cancel-timer company-timer))
1059 (company-search-mode 0)
1060 (company-call-frontends 'hide)
1061 (company-enable-overriding-keymap nil))
1063 (defun company-abort ()
1066 ;; Don't start again, unless started manually.
1067 (setq company-point (point)))
1069 (defun company-finish (result)
1070 (insert (company-strip-prefix result))
1071 (company-cancel result)
1072 ;; Don't start again, unless started manually.
1073 (setq company-point (point)))
1075 (defsubst company-keep (command)
1076 (and (symbolp command) (get command 'company-keep)))
1078 (defun company-pre-command ()
1079 (unless (company-keep this-command)
1081 (when company-candidates
1082 (company-call-frontends 'pre-command))
1083 (error (message "Company: An error occurred in pre-command")
1084 (message "%s" (error-message-string err))
1087 (cancel-timer company-timer)
1088 (setq company-timer nil))
1089 (company-uninstall-map))
1091 (defun company-post-command ()
1092 (unless (company-keep this-command)
1095 (unless (equal (point) company-point)
1097 (if company-candidates
1098 (company-call-frontends 'post-command)
1099 (and (numberp company-idle-delay)
1100 (or (eq t company-begin-commands)
1101 (memq this-command company-begin-commands))
1103 (run-with-timer company-idle-delay nil
1105 (current-buffer) (selected-window)
1106 (buffer-chars-modified-tick) (point))))))
1107 (error (message "Company: An error occurred in post-command")
1108 (message "%s" (error-message-string err))
1110 (company-install-map))
1112 ;;; search ;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;
1114 (defvar company-search-string nil)
1115 (make-variable-buffer-local 'company-search-string)
1117 (defvar company-search-lighter " Search: \"\"")
1118 (make-variable-buffer-local 'company-search-lighter)
1120 (defvar company-search-old-map nil)
1121 (make-variable-buffer-local 'company-search-old-map)
1123 (defvar company-search-old-selection 0)
1124 (make-variable-buffer-local 'company-search-old-selection)
1126 (defun company-search (text lines)
1127 (let ((quoted (regexp-quote text))
1129 (dolist (line lines)
1130 (when (string-match quoted line (length company-prefix))
1134 (defun company-search-printing-char ()
1136 (company-search-assert-enabled)
1137 (setq company-search-string
1138 (concat (or company-search-string "") (string last-command-event))
1139 company-search-lighter (concat " Search: \"" company-search-string
1141 (let ((pos (company-search company-search-string
1142 (nthcdr company-selection company-candidates))))
1145 (company-set-selection (+ company-selection pos) t))))
1147 (defun company-search-repeat-forward ()
1148 "Repeat the incremental search in completion candidates forward."
1150 (company-search-assert-enabled)
1151 (let ((pos (company-search company-search-string
1152 (cdr (nthcdr company-selection
1153 company-candidates)))))
1156 (company-set-selection (+ company-selection pos 1) t))))
1158 (defun company-search-repeat-backward ()
1159 "Repeat the incremental search in completion candidates backwards."
1161 (company-search-assert-enabled)
1162 (let ((pos (company-search company-search-string
1163 (nthcdr (- company-candidates-length
1165 (reverse company-candidates)))))
1168 (company-set-selection (- company-selection pos 1) t))))
1170 (defun company-create-match-predicate ()
1171 (setq company-candidates-predicate
1172 `(lambda (candidate)
1173 ,(if company-candidates-predicate
1174 `(and (string-match ,company-search-string candidate)
1175 (funcall ,company-candidates-predicate
1177 `(string-match ,company-search-string candidate))))
1178 (company-update-candidates
1179 (company-apply-predicate company-candidates company-candidates-predicate))
1180 ;; Invalidate cache.
1181 (setq company-candidates-cache (cons company-prefix company-candidates)))
1183 (defun company-filter-printing-char ()
1185 (company-search-assert-enabled)
1186 (company-search-printing-char)
1187 (company-create-match-predicate)
1188 (company-call-frontends 'update))
1190 (defun company-search-kill-others ()
1191 "Limit the completion candidates to the ones matching the search string."
1193 (company-search-assert-enabled)
1194 (company-create-match-predicate)
1195 (company-search-mode 0)
1196 (company-call-frontends 'update))
1198 (defun company-search-abort ()
1199 "Abort searching the completion candidates."
1201 (company-search-assert-enabled)
1202 (company-set-selection company-search-old-selection t)
1203 (company-search-mode 0))
1205 (defun company-search-other-char ()
1207 (company-search-assert-enabled)
1208 (company-search-mode 0)
1209 (when last-input-event
1210 (clear-this-command-keys t)
1211 (setq unread-command-events (list last-input-event))))
1213 (defvar company-search-map
1215 (keymap (make-keymap)))
1216 (if (fboundp 'max-char)
1217 (set-char-table-range (nth 1 keymap) (cons #x100 (max-char))
1218 'company-search-printing-char)
1220 ;; obselete in Emacs 23
1221 (let ((l (generic-character-list))
1222 (table (nth 1 keymap)))
1224 (set-char-table-default table (car l) 'company-search-printing-char)
1225 (setq l (cdr l))))))
1226 (define-key keymap [t] 'company-search-other-char)
1228 (define-key keymap (make-string 1 i) 'company-search-other-char)
1231 (define-key keymap (vector i) 'company-search-printing-char)
1233 (let ((meta-map (make-sparse-keymap)))
1234 (define-key keymap (char-to-string meta-prefix-char) meta-map)
1235 (define-key keymap [escape] meta-map))
1236 (define-key keymap (vector meta-prefix-char t) 'company-search-other-char)
1237 (define-key keymap "\e\e\e" 'company-search-other-char)
1238 (define-key keymap [escape escape escape] 'company-search-other-char)
1240 (define-key keymap "\C-g" 'company-search-abort)
1241 (define-key keymap "\C-s" 'company-search-repeat-forward)
1242 (define-key keymap "\C-r" 'company-search-repeat-backward)
1243 (define-key keymap "\C-o" 'company-search-kill-others)
1245 "Keymap used for incrementally searching the completion candidates.")
1247 (define-minor-mode company-search-mode
1248 "Search mode for completion candidates.
1249 Don't start this directly, use `company-search-candidates' or
1250 `company-filter-candidates'."
1251 nil company-search-lighter nil
1252 (if company-search-mode
1253 (if (company-manual-begin)
1255 (setq company-search-old-selection company-selection)
1256 (company-call-frontends 'update))
1257 (setq company-search-mode nil))
1258 (kill-local-variable 'company-search-string)
1259 (kill-local-variable 'company-search-lighter)
1260 (kill-local-variable 'company-search-old-selection)
1261 (company-enable-overriding-keymap company-active-map)))
1263 (defsubst company-search-assert-enabled ()
1264 (company-assert-enabled)
1265 (unless company-search-mode
1266 (company-uninstall-map)
1267 (error "Company not in search mode")))
1269 (defun company-search-candidates ()
1270 "Start searching the completion candidates incrementally.
1272 \\<company-search-map>Search can be controlled with the commands:
1273 - `company-search-repeat-forward' (\\[company-search-repeat-forward])
1274 - `company-search-repeat-backward' (\\[company-search-repeat-backward])
1275 - `company-search-abort' (\\[company-search-abort])
1277 Regular characters are appended to the search string.
1279 The command `company-search-kill-others' (\\[company-search-kill-others]) uses
1280 the search string to limit the completion candidates."
1282 (company-search-mode 1)
1283 (company-enable-overriding-keymap company-search-map))
1285 (defvar company-filter-map
1286 (let ((keymap (make-keymap)))
1287 (define-key keymap [remap company-search-printing-char]
1288 'company-filter-printing-char)
1289 (set-keymap-parent keymap company-search-map)
1291 "Keymap used for incrementally searching the completion candidates.")
1293 (defun company-filter-candidates ()
1294 "Start filtering the completion candidates incrementally.
1295 This works the same way as `company-search-candidates' immediately
1296 followed by `company-search-kill-others' after each input."
1298 (company-search-mode 1)
1299 (company-enable-overriding-keymap company-filter-map))
1301 ;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;
1303 (defun company-select-next ()
1304 "Select the next candidate in the list."
1306 (when (company-manual-begin)
1307 (company-set-selection (1+ company-selection))))
1309 (defun company-select-previous ()
1310 "Select the previous candidate in the list."
1312 (when (company-manual-begin)
1313 (company-set-selection (1- company-selection))))
1315 (defun company-select-mouse (event)
1316 "Select the candidate picked by the mouse."
1318 (when (nth 4 (event-start event))
1319 (company-set-selection (- (cdr (posn-actual-col-row (event-start event)))
1324 (defun company-complete-mouse (event)
1325 "Complete the candidate picked by the mouse."
1327 (when (company-select-mouse event)
1328 (company-complete-selection)))
1330 (defun company-complete-selection ()
1331 "Complete the selected candidate."
1333 (when (company-manual-begin)
1334 (company-finish (nth company-selection company-candidates))))
1336 (defun company-complete-common ()
1337 "Complete the common part of all candidates."
1339 (when (company-manual-begin)
1340 (if (and (not (cdr company-candidates))
1341 (equal company-common (car company-candidates)))
1342 (company-complete-selection)
1343 (insert (company-strip-prefix company-common)))))
1345 (defun company-complete ()
1346 "Complete the common part of all candidates or the current selection.
1347 The first time this is called, the common part is completed, the second time, or
1348 when the selection has been changed, the selected candidate is completed."
1350 (when (company-manual-begin)
1351 (if (or company-selection-changed
1352 (eq last-command 'company-complete-common))
1353 (call-interactively 'company-complete-selection)
1354 (call-interactively 'company-complete-common)
1355 (setq this-command 'company-complete-common))))
1357 (defun company-complete-number (n)
1358 "Complete the Nth candidate.
1359 To show the number next to the candidates in some back-ends, enable
1360 `company-show-numbers'."
1361 (when (company-manual-begin)
1362 (and (< n 1) (> n company-candidates-length)
1363 (error "No candidate number %d" n))
1365 (company-finish (nth n company-candidates))))
1367 ;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;
1369 (defconst company-space-strings-limit 100)
1371 (defconst company-space-strings
1373 (dotimes (i company-space-strings-limit)
1374 (push (make-string (- company-space-strings-limit 1 i) ?\ ) lst))
1375 (apply 'vector lst)))
1377 (defsubst company-space-string (len)
1378 (if (< len company-space-strings-limit)
1379 (aref company-space-strings len)
1380 (make-string len ?\ )))
1382 (defsubst company-safe-substring (str from &optional to)
1383 (let ((len (length str)))
1386 (if (and to (> to len))
1387 (concat (substring str from)
1388 (company-space-string (- to len)))
1389 (substring str from to)))))
1391 ;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;
1393 (defvar company-last-metadata nil)
1394 (make-variable-buffer-local 'company-last-metadata)
1396 (defun company-fetch-metadata ()
1397 (let ((selected (nth company-selection company-candidates)))
1398 (unless (equal selected (car company-last-metadata))
1399 (setq company-last-metadata
1400 (cons selected (company-call-backend 'meta selected))))
1401 (cdr company-last-metadata)))
1403 (defun company-doc-buffer (&optional string)
1404 (with-current-buffer (get-buffer-create "*Company meta-data*")
1408 (defmacro company--electric-do (&rest body)
1409 (declare (indent 0) (debug t))
1410 `(when (company-manual-begin)
1411 (save-window-excursion
1412 (let ((height (window-height))
1413 (row (company--row)))
1415 (and (< (window-height) height)
1416 (< (- (window-height) row 2) company-tooltip-limit)
1417 (recenter (- (window-height) row 2)))
1418 (while (eq 'scroll-other-window
1419 (key-binding (vector (list (read-event)))))
1420 (call-interactively 'scroll-other-window))
1421 (when last-input-event
1422 (clear-this-command-keys t)
1423 (setq unread-command-events (list last-input-event)))))))
1425 (defun company-show-doc-buffer ()
1426 "Temporarily show a buffer with the complete documentation for the selection."
1428 (company--electric-do
1429 (let ((selected (nth company-selection company-candidates)))
1430 (display-buffer (or (company-call-backend 'doc-buffer selected)
1431 (error "No documentation available")) t))))
1432 (put 'company-show-doc-buffer 'company-keep t)
1434 (defun company-show-location ()
1435 "Temporarily display a buffer showing the selected candidate in context."
1437 (company--electric-do
1438 (let* ((selected (nth company-selection company-candidates))
1439 (location (company-call-backend 'location selected))
1440 (pos (or (cdr location) (error "No location available")))
1441 (buffer (or (and (bufferp (car location)) (car location))
1442 (find-file-noselect (car location) t))))
1443 (with-selected-window (display-buffer buffer t)
1444 (if (bufferp (car location))
1447 (set-window-start nil (point))))))
1448 (put 'company-show-location 'company-keep t)
1450 ;;; package functions ;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;
1452 (defvar company-callback nil)
1453 (make-variable-buffer-local 'company-callback)
1455 (defvar company-begin-with-marker nil)
1456 (make-variable-buffer-local 'company-begin-with-marker)
1458 (defun company-remove-callback (&optional ignored)
1459 (remove-hook 'company-completion-finished-hook company-callback t)
1460 (remove-hook 'company-completion-cancelled-hook 'company-remove-callback t)
1461 (remove-hook 'company-completion-finished-hook 'company-remove-callback t)
1462 (when company-begin-with-marker
1463 (set-marker company-begin-with-marker nil)))
1465 (defun company-begin-backend (backend &optional callback)
1466 "Start a completion at point using BACKEND."
1467 (interactive (let ((val (completing-read "Company back-end: "
1469 'functionp nil "company-")))
1471 (list (intern val)))))
1472 (when (setq company-callback callback)
1473 (add-hook 'company-completion-finished-hook company-callback nil t))
1474 (add-hook 'company-completion-cancelled-hook 'company-remove-callback nil t)
1475 (add-hook 'company-completion-finished-hook 'company-remove-callback nil t)
1476 (setq company-backend backend)
1477 ;; Return non-nil if active.
1478 (or (company-manual-begin)
1479 (error "Cannot complete at point")))
1481 (defun company-begin-with (candidates
1482 &optional prefix-length require-match callback)
1483 "Start a completion at point.
1484 CANDIDATES is the list of candidates to use and PREFIX-LENGTH is the length of
1485 the prefix that already is in the buffer before point. It defaults to 0.
1487 CALLBACK is a function called with the selected result if the user successfully
1488 completes the input.
1491 \(company-begin-with '\(\"foo\" \"foobar\" \"foobarbaz\"\)\)"
1492 (setq company-begin-with-marker (copy-marker (point) t))
1493 (company-begin-backend
1494 `(lambda (command &optional arg &rest ignored)
1496 ((eq command 'prefix)
1497 (when (equal (point) (marker-position company-begin-with-marker))
1498 (buffer-substring ,(- (point) (or prefix-length 0)) (point))))
1499 ((eq command 'candidates)
1500 (all-completions arg ',candidates))
1501 ((eq command 'require-match)
1505 ;;; pseudo-tooltip ;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;
1507 (defvar company-pseudo-tooltip-overlay nil)
1508 (make-variable-buffer-local 'company-pseudo-tooltip-overlay)
1510 (defvar company-tooltip-offset 0)
1511 (make-variable-buffer-local 'company-tooltip-offset)
1513 (defun company-pseudo-tooltip-update-offset (selection num-lines limit)
1516 (setq company-tooltip-offset
1517 (max (min selection company-tooltip-offset)
1518 (- selection -1 limit)))
1520 (when (<= company-tooltip-offset 1)
1522 (setq company-tooltip-offset 0))
1524 (when (>= company-tooltip-offset (- num-lines limit 1))
1526 (when (= selection (1- num-lines))
1527 (decf company-tooltip-offset)
1528 (when (<= company-tooltip-offset 1)
1529 (setq company-tooltip-offset 0)
1536 (defsubst company-round-tab (arg)
1537 (* (/ (+ arg tab-width) tab-width) tab-width))
1539 (defun company-untabify (str)
1540 (let* ((pieces (split-string str "\t"))
1543 (setcar copy (company-safe-substring
1544 (car copy) 0 (company-round-tab (string-width (car copy)))))
1546 (apply 'concat pieces)))
1548 (defun company-fill-propertize (line width selected)
1549 (setq line (company-safe-substring line 0 width))
1550 (add-text-properties 0 width '(face company-tooltip
1551 mouse-face company-tooltip-mouse)
1553 (add-text-properties 0 (length company-common)
1554 '(face company-tooltip-common
1555 mouse-face company-tooltip-mouse)
1558 (if (and company-search-string
1559 (string-match (regexp-quote company-search-string) line
1560 (length company-prefix)))
1562 (add-text-properties (match-beginning 0) (match-end 0)
1563 '(face company-tooltip-selection)
1565 (when (< (match-beginning 0) (length company-common))
1566 (add-text-properties (match-beginning 0) (length company-common)
1567 '(face company-tooltip-common-selection)
1569 (add-text-properties 0 width '(face company-tooltip-selection
1570 mouse-face company-tooltip-selection)
1572 (add-text-properties 0 (length company-common)
1573 '(face company-tooltip-common-selection
1574 mouse-face company-tooltip-selection)
1580 (defun company-buffer-lines (beg end)
1582 (let ((row (company--row))
1584 (while (and (equal (move-to-window-line (incf row)) row)
1586 (push (buffer-substring beg (min end (1- (point)))) lines)
1588 (unless (eq beg end)
1589 (push (buffer-substring beg end) lines))
1592 (defsubst company-modify-line (old new offset)
1593 (concat (company-safe-substring old 0 offset)
1595 (company-safe-substring old (+ offset (length new)))))
1597 (defsubst company--length-limit (lst limit)
1598 (if (nthcdr limit lst)
1602 (defun company--replacement-string (lines old column nl &optional align-top)
1604 (let ((width (length (car lines))))
1605 (when (> width (- (window-width) column))
1606 (setq column (max 0 (- (window-width) width)))))
1610 ;; untouched lines first
1611 (dotimes (i (- (length old) (length lines)))
1612 (push (pop old) new)))
1613 ;; length into old lines.
1615 (push (company-modify-line (pop old) (pop lines) column) new))
1616 ;; Append whole new lines.
1618 (push (concat (company-space-string column) (pop lines)) new))
1619 (concat (when nl "\n")
1620 (mapconcat 'identity (nreverse new) "\n")
1623 (defun company--create-lines (selection limit)
1625 (let ((len company-candidates-length)
1634 ;; Scroll to offset.
1635 (setq limit (company-pseudo-tooltip-update-offset selection len limit))
1637 (when (> company-tooltip-offset 0)
1638 (setq previous (format "...(%d)" company-tooltip-offset)))
1640 (setq remainder (- len limit company-tooltip-offset)
1641 remainder (when (> remainder 0)
1642 (setq remainder (format "...(%d)" remainder))))
1644 (decf selection company-tooltip-offset)
1645 (setq width (max (length previous) (length remainder))
1646 lines (nthcdr company-tooltip-offset company-candidates)
1651 (setq width (max (length (pop lines-copy)) width)))
1652 (setq width (min width (window-width)))
1654 (setq lines-copy lines)
1656 ;; number can make tooltip too long
1657 (when company-show-numbers
1658 (setq numbered company-tooltip-offset))
1661 (push (propertize (company-safe-substring previous 0 width)
1662 'face 'company-tooltip)
1666 (push (company-fill-propertize
1667 (if (>= numbered 10)
1668 (company-reformat (pop lines))
1671 (company-safe-substring (company-reformat (pop lines))
1674 width (equal i selection))
1678 (push (propertize (company-safe-substring remainder 0 width)
1679 'face 'company-tooltip)
1682 (setq lines (nreverse new))))
1686 (defsubst company--window-inner-height ()
1687 (let ((edges (window-inside-edges (selected-window))))
1688 (- (nth 3 edges) (nth 1 edges))))
1690 (defsubst company--pseudo-tooltip-height ()
1691 "Calculate the appropriate tooltip height.
1692 Returns a negative number if the tooltip should be displayed above point."
1693 (let* ((lines (count-lines (window-start) (point-at-bol)))
1694 (below (- (company--window-inner-height) 1 lines)))
1695 (if (and (< below (min company-tooltip-minimum company-candidates-length))
1697 (- (max 3 (min company-tooltip-limit lines)))
1698 (max 3 (min company-tooltip-limit below)))))
1700 (defun company-pseudo-tooltip-show (row column selection)
1701 (company-pseudo-tooltip-hide)
1706 (let* ((height (company--pseudo-tooltip-height))
1710 (setq row (+ row height -1)
1713 (let* ((nl (< (move-to-window-line row) row))
1715 (end (save-excursion
1716 (move-to-window-line (+ row (abs height)))
1718 (ov (make-overlay beg end))
1719 (args (list (mapcar 'company-untabify
1720 (company-buffer-lines beg end))
1723 (setq company-pseudo-tooltip-overlay ov)
1724 (overlay-put ov 'company-replacement-args args)
1725 (overlay-put ov 'company-before
1726 (apply 'company--replacement-string
1727 (company--create-lines selection (abs height))
1730 (overlay-put ov 'company-column column)
1731 (overlay-put ov 'company-height (abs height))
1732 (overlay-put ov 'window (selected-window))))))
1734 (defun company-pseudo-tooltip-show-at-point (pos)
1735 (let ((col-row (company--col-row pos)))
1737 (company-pseudo-tooltip-show (1+ (cdr col-row)) (car col-row)
1738 company-selection))))
1740 (defun company-pseudo-tooltip-edit (lines selection)
1741 (let ((column (overlay-get company-pseudo-tooltip-overlay 'company-column))
1742 (height (overlay-get company-pseudo-tooltip-overlay 'company-height)))
1743 (overlay-put company-pseudo-tooltip-overlay 'company-before
1744 (apply 'company--replacement-string
1745 (company--create-lines selection height)
1746 (overlay-get company-pseudo-tooltip-overlay
1747 'company-replacement-args)))))
1749 (defun company-pseudo-tooltip-hide ()
1750 (when company-pseudo-tooltip-overlay
1751 (delete-overlay company-pseudo-tooltip-overlay)
1752 (setq company-pseudo-tooltip-overlay nil)))
1754 (defun company-pseudo-tooltip-hide-temporarily ()
1755 (when (overlayp company-pseudo-tooltip-overlay)
1756 (overlay-put company-pseudo-tooltip-overlay 'invisible nil)
1757 (overlay-put company-pseudo-tooltip-overlay 'before-string nil)))
1759 (defun company-pseudo-tooltip-unhide ()
1760 (when company-pseudo-tooltip-overlay
1761 (overlay-put company-pseudo-tooltip-overlay 'invisible t)
1762 (overlay-put company-pseudo-tooltip-overlay 'before-string
1763 (overlay-get company-pseudo-tooltip-overlay 'company-before))
1764 (overlay-put company-pseudo-tooltip-overlay 'window (selected-window))))
1766 (defun company-pseudo-tooltip-frontend (command)
1767 "A `company-mode' front-end similar to a tool-tip but based on overlays."
1769 ('pre-command (company-pseudo-tooltip-hide-temporarily))
1771 (let ((old-height (if (overlayp company-pseudo-tooltip-overlay)
1772 (overlay-get company-pseudo-tooltip-overlay
1775 (new-height (company--pseudo-tooltip-height)))
1776 (unless (and (>= (* old-height new-height) 0)
1777 (>= (abs old-height) (abs new-height)))
1779 (company-pseudo-tooltip-show-at-point (- (point)
1780 (length company-prefix)))))
1781 (company-pseudo-tooltip-unhide))
1782 ('hide (company-pseudo-tooltip-hide)
1783 (setq company-tooltip-offset 0))
1784 ('update (when (overlayp company-pseudo-tooltip-overlay)
1785 (company-pseudo-tooltip-edit company-candidates
1786 company-selection)))))
1788 (defun company-pseudo-tooltip-unless-just-one-frontend (command)
1789 "`company-pseudo-tooltip-frontend', but not shown for single candidates."
1790 (unless (and (eq command 'post-command)
1791 (not (cdr company-candidates)))
1792 (company-pseudo-tooltip-frontend command)))
1794 ;;; overlay ;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;
1796 (defvar company-preview-overlay nil)
1797 (make-variable-buffer-local 'company-preview-overlay)
1799 (defun company-preview-show-at-point (pos)
1800 (company-preview-hide)
1802 (setq company-preview-overlay (make-overlay pos pos))
1804 (let ((completion(nth company-selection company-candidates)))
1805 (setq completion (propertize completion 'face 'company-preview))
1806 (add-text-properties 0 (length company-common)
1807 '(face company-preview-common) completion)
1809 ;; Add search string
1810 (and company-search-string
1811 (string-match (regexp-quote company-search-string) completion)
1812 (add-text-properties (match-beginning 0)
1814 '(face company-preview-search)
1817 (setq completion (company-strip-prefix completion))
1819 (and (equal pos (point))
1820 (not (equal completion ""))
1821 (add-text-properties 0 1 '(cursor t) completion))
1823 (overlay-put company-preview-overlay 'after-string completion)
1824 (overlay-put company-preview-overlay 'window (selected-window))))
1826 (defun company-preview-hide ()
1827 (when company-preview-overlay
1828 (delete-overlay company-preview-overlay)
1829 (setq company-preview-overlay nil)))
1831 (defun company-preview-frontend (command)
1832 "A `company-mode' front-end showing the selection as if it had been inserted."
1834 ('pre-command (company-preview-hide))
1835 ('post-command (company-preview-show-at-point (point)))
1836 ('hide (company-preview-hide))))
1838 (defun company-preview-if-just-one-frontend (command)
1839 "`company-preview-frontend', but only shown for single candidates."
1840 (unless (and (eq command 'post-command)
1841 (cdr company-candidates))
1842 (company-preview-frontend command)))
1844 ;;; echo ;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;
1846 (defvar company-echo-last-msg nil)
1847 (make-variable-buffer-local 'company-echo-last-msg)
1849 (defvar company-echo-timer nil)
1851 (defvar company-echo-delay .01)
1853 (defun company-echo-show (&optional getter)
1855 (setq company-echo-last-msg (funcall getter)))
1856 (let ((message-log-max nil))
1857 (if company-echo-last-msg
1858 (message "%s" company-echo-last-msg)
1861 (defsubst company-echo-show-soon (&optional getter)
1862 (when company-echo-timer
1863 (cancel-timer company-echo-timer))
1864 (setq company-echo-timer (run-with-timer company-echo-delay nil
1865 'company-echo-show getter)))
1867 (defun company-echo-format ()
1869 (let ((limit (window-width (minibuffer-window)))
1871 ;; Roll to selection.
1872 (candidates (nthcdr company-selection company-candidates))
1873 (i (if company-show-numbers company-selection 99999))
1877 (setq comp (company-reformat (pop candidates))
1878 len (+ len 1 (length comp)))
1882 (setq comp (propertize (format "%d: %s" i comp)
1883 'face 'company-echo))
1886 (add-text-properties 3 (+ 3 (length company-common))
1887 '(face company-echo-common) comp))
1888 (setq comp (propertize comp 'face 'company-echo))
1889 (add-text-properties 0 (length company-common)
1890 '(face company-echo-common) comp))
1892 (setq candidates nil)
1895 (mapconcat 'identity (nreverse msg) " ")))
1897 (defun company-echo-strip-common-format ()
1899 (let ((limit (window-width (minibuffer-window)))
1900 (len (+ (length company-prefix) 2))
1901 ;; Roll to selection.
1902 (candidates (nthcdr company-selection company-candidates))
1903 (i (if company-show-numbers company-selection 99999))
1907 (setq comp (company-strip-prefix (pop candidates))
1908 len (+ len 2 (length comp)))
1911 (setq comp (format "%s (%d)" comp i))
1915 (setq candidates nil)
1916 (push (propertize comp 'face 'company-echo) msg)))
1918 (concat (propertize company-prefix 'face 'company-echo-common) "{"
1919 (mapconcat 'identity (nreverse msg) ", ")
1922 (defun company-echo-hide ()
1923 (when company-echo-timer
1924 (cancel-timer company-echo-timer))
1925 (unless (equal company-echo-last-msg "")
1926 (setq company-echo-last-msg "")
1927 (company-echo-show)))
1929 (defun company-echo-frontend (command)
1930 "A `company-mode' front-end showing the candidates in the echo area."
1932 ('pre-command (company-echo-show-soon))
1933 ('post-command (company-echo-show-soon 'company-echo-format))
1934 ('hide (company-echo-hide))))
1936 (defun company-echo-strip-common-frontend (command)
1937 "A `company-mode' front-end showing the candidates in the echo area."
1939 ('pre-command (company-echo-show-soon))
1940 ('post-command (company-echo-show-soon 'company-echo-strip-common-format))
1941 ('hide (company-echo-hide))))
1943 (defun company-echo-metadata-frontend (command)
1944 "A `company-mode' front-end showing the documentation in the echo area."
1946 ('pre-command (company-echo-show-soon))
1947 ('post-command (company-echo-show-soon 'company-fetch-metadata))
1948 ('hide (company-echo-hide))))
1951 ;;; company.el ends here