1 ;;; company.el --- Extensible inline text completion mechanism
3 ;; Copyright (C) 2009-2011 Free Software Foundation, Inc.
5 ;; Author: Nikolaj Schumacher
7 ;; Keywords: abbrev, convenience, matching
8 ;; URL: http://nschum.de/src/emacs/company-mode/
9 ;; Compatibility: GNU Emacs 22.x, GNU Emacs 23.x
11 ;; This file is part of GNU Emacs.
13 ;; GNU Emacs is free software: you can redistribute it and/or modify
14 ;; it under the terms of the GNU General Public License as published by
15 ;; the Free Software Foundation, either version 3 of the License, or
16 ;; (at your option) any later version.
18 ;; GNU Emacs 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 GNU Emacs. 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'.
69 ;; `company-ropemacs' now provides location and docs. (Fernando H. Silva)
70 ;; Added `company-with-candidate-inserted' macro.
71 ;; Added `company-clang' back-end.
72 ;; Added new mechanism for non-consecutive insertion.
73 ;; (So far only used by clang for ObjC.)
74 ;; The semantic back-end now shows meta information for local symbols.
75 ;; Added compatibility for CEDET in Emacs 23.2 and from CVS. (Oleg Andreev)
78 ;; Added `company-other-backend'.
79 ;; Idle completion no longer interrupts multi-key command input.
80 ;; Added `company-ropemacs' and `company-pysmell' back-ends.
83 ;; In C modes . and -> now count towards `company-minimum-prefix-length'.
84 ;; Reverted default front-end back to `company-preview-if-just-one-frontend'.
85 ;; The pseudo tooltip will no longer be clipped at the right window edge.
86 ;; Added `company-tooltip-minimum'.
87 ;; Windows compatibility fixes.
90 ;; Added `global-company-mode'.
91 ;; Performance enhancements.
92 ;; Added `company-eclim' back-end.
93 ;; Added safer workaround for Emacs `posn-col-row' bug.
96 ;; Automatic completion is now aborted if the prefix gets too short.
97 ;; Added option `company-dabbrev-time-limit'.
98 ;; `company-backends' now supports merging back-ends.
99 ;; Added back-end `company-dabbrev-code' for generic code.
100 ;; Fixed `company-begin-with'.
102 ;; 2009-04-15 (0.3.1)
103 ;; Added 'stop prefix to prevent dabbrev from completing inside of symbols.
104 ;; Fixed issues with tabbar-mode and line-spacing.
105 ;; Performance enhancements.
108 ;; Added `company-begin-commands' option.
109 ;; Added abbrev, tempo and Xcode back-ends.
110 ;; Back-ends are now interactive. You can start them with M-x backend-name.
111 ;; Added `company-begin-with' for starting company from elisp-code.
113 ;; Added `company-require-match' and `company-auto-complete' options.
115 ;; 2009-04-05 (0.2.1)
116 ;; Improved Emacs Lisp back-end behavior for local variables.
117 ;; Added `company-elisp-detect-function-context' option.
118 ;; The mouse can now be used for selection.
121 ;; Added `company-show-location'.
122 ;; Added etags back-end.
123 ;; Added work-around for end-of-buffer bug.
124 ;; Added `company-filter-candidates'.
125 ;; More local Lisp variables are now included in the candidates.
127 ;; 2009-03-21 (0.1.5)
128 ;; Fixed elisp documentation buffer always showing the same doc.
129 ;; Added `company-echo-strip-common-frontend'.
130 ;; Added `company-show-numbers' option and M-0 ... M-9 default bindings.
131 ;; Don't hide the echo message if it isn't shown.
138 (eval-when-compile (require 'cl))
140 (add-to-list 'debug-ignored-errors "^.* frontend cannot be used twice$")
141 (add-to-list 'debug-ignored-errors "^Echo area cannot be used twice$")
142 (add-to-list 'debug-ignored-errors "^No \\(document\\|loc\\)ation available$")
143 (add-to-list 'debug-ignored-errors "^Company not ")
144 (add-to-list 'debug-ignored-errors "^No candidate number ")
145 (add-to-list 'debug-ignored-errors "^Cannot complete at point$")
146 (add-to-list 'debug-ignored-errors "^No other back-end$")
148 (defgroup company nil
149 "Extensible inline text completion mechanism"
154 (defface company-tooltip
155 '((t :background "yellow"
156 :foreground "black"))
157 "*Face used for the tool tip."
160 (defface company-tooltip-selection
161 '((default :inherit company-tooltip)
162 (((class color) (min-colors 88)) (:background "orange1"))
163 (t (:background "green")))
164 "*Face used for the selection in the tool tip."
167 (defface company-tooltip-mouse
168 '((default :inherit highlight))
169 "*Face used for the tool tip item under the mouse."
172 (defface company-tooltip-common
173 '((t :inherit company-tooltip
175 "*Face used for the common completion in the tool tip."
178 (defface company-tooltip-common-selection
179 '((t :inherit company-tooltip-selection
181 "*Face used for the selected common completion in the tool tip."
184 (defface company-preview
185 '((t :background "blue4"
186 :foreground "wheat"))
187 "*Face used for the completion preview."
190 (defface company-preview-common
191 '((t :inherit company-preview
193 "*Face used for the common part of the completion preview."
196 (defface company-preview-search
197 '((t :inherit company-preview
198 :background "blue1"))
199 "*Face used for the search string in the completion preview."
202 (defface company-echo nil
203 "*Face used for completions in the echo area."
206 (defface company-echo-common
207 '((((background dark)) (:foreground "firebrick1"))
208 (((background light)) (:background "firebrick4")))
209 "*Face used for the common part of completions in the echo area."
212 (defun company-frontends-set (variable value)
214 (let ((remainder value))
215 (setcdr remainder (delq (car remainder) (cdr remainder))))
216 (and (memq 'company-pseudo-tooltip-unless-just-one-frontend value)
217 (memq 'company-pseudo-tooltip-frontend value)
218 (error "Pseudo tooltip frontend cannot be used twice"))
219 (and (memq 'company-preview-if-just-one-frontend value)
220 (memq 'company-preview-frontend value)
221 (error "Preview frontend cannot be used twice"))
222 (and (memq 'company-echo value)
223 (memq 'company-echo-metadata-frontend value)
224 (error "Echo area cannot be used twice"))
225 ;; preview must come last
226 (dolist (f '(company-preview-if-just-one-frontend company-preview-frontend))
228 (setq value (append (delq f value) (list f)))))
229 (set variable value))
231 (defcustom company-frontends '(company-pseudo-tooltip-unless-just-one-frontend
232 company-preview-if-just-one-frontend
233 company-echo-metadata-frontend)
234 "*The list of active front-ends (visualizations).
235 Each front-end is a function that takes one argument. It is called with
236 one of the following arguments:
238 'show: When the visualization should start.
240 'hide: When the visualization should end.
242 'update: When the data has been updated.
244 'pre-command: Before every command that is executed while the
245 visualization is active.
247 'post-command: After every command that is executed while the
248 visualization is active.
250 The visualized data is stored in `company-prefix', `company-candidates',
251 `company-common', `company-selection', `company-point' and
252 `company-search-string'."
253 :set 'company-frontends-set
255 :type '(repeat (choice (const :tag "echo" company-echo-frontend)
256 (const :tag "echo, strip common"
257 company-echo-strip-common-frontend)
258 (const :tag "show echo meta-data in echo"
259 company-echo-metadata-frontend)
260 (const :tag "pseudo tooltip"
261 company-pseudo-tooltip-frontend)
262 (const :tag "pseudo tooltip, multiple only"
263 company-pseudo-tooltip-unless-just-one-frontend)
264 (const :tag "preview" company-preview-frontend)
265 (const :tag "preview, unique only"
266 company-preview-if-just-one-frontend)
267 (function :tag "custom function" nil))))
269 (defcustom company-tooltip-limit 10
270 "*The maximum number of candidates in the tool tip"
274 (defcustom company-tooltip-minimum 6
275 "*The minimum height of the tool tip.
276 If this many lines are not available, prefer to display the tooltip above."
280 (defvar company-safe-backends
281 '((company-abbrev . "Abbrev")
282 (company-clang . "clang")
283 (company-css . "CSS")
284 (company-dabbrev . "dabbrev for plain text")
285 (company-dabbrev-code . "dabbrev for code")
286 (company-eclim . "eclim (an Eclipse interace)")
287 (company-elisp . "Emacs Lisp")
288 (company-etags . "etags")
289 (company-files . "Files")
290 (company-gtags . "GNU Global")
291 (company-ispell . "ispell")
292 (company-keywords . "Programming language keywords")
293 (company-nxml . "nxml")
294 (company-oddmuse . "Oddmuse")
295 (company-pysmell . "PySmell")
296 (company-ropemacs . "ropemacs")
297 (company-semantic . "CEDET Semantic")
298 (company-tempo . "Tempo templates")
299 (company-xcode . "Xcode")))
300 (put 'company-safe-backends 'risky-local-variable t)
302 (defun company-safe-backends-p (backends)
303 (and (consp backends)
304 (not (dolist (backend backends)
305 (unless (if (consp backend)
306 (company-safe-backends-p backend)
307 (assq backend company-safe-backends))
310 (defun company-capf (command &optional arg &rest args)
311 "Adapter for Company completion to use `completion-at-point-functions'."
312 (interactive (list 'interactive))
314 (interactive (company-begin-backend 'company-capf))
316 (let ((res (run-hook-wrapped 'completion-at-point-functions
317 ;; Ignore misbehaving functions.
318 #'completion--capf-wrapper 'optimist)))
320 (if (> (nth 1 res) (point))
322 (buffer-substring-no-properties (nth 0 res) (point))))))
324 (let ((res (run-hook-wrapped 'completion-at-point-functions
325 ;; Ignore misbehaving functions.
326 #'completion--capf-wrapper 'optimist)))
328 (all-completions arg (nth 2 res)
329 (plist-get (nthcdr 3 res) :predicate)))))))
331 (defcustom company-backends '(;; company-capf ;FIXME: Untested!
332 company-elisp company-nxml company-css
333 company-eclim company-semantic company-clang
334 company-xcode company-ropemacs
335 (company-gtags company-etags company-dabbrev-code
336 company-pysmell company-keywords)
337 company-oddmuse company-files company-dabbrev)
338 "*The list of active back-ends (completion engines).
339 Each list elements can itself be a list of back-ends. In that case their
340 completions are merged. Otherwise only the first matching back-end returns
343 `company-begin-backend' can be used to start a specific back-end,
344 `company-other-backend' will skip to the next matching back-end in the list.
346 Each back-end is a function that takes a variable number of arguments.
347 The first argument is the command requested from the back-end. It is one
350 `prefix': The back-end should return the text to be completed. It must be
351 text immediately before `point'. Returning nil passes control to the next
352 back-end. The function should return 'stop if it should complete but cannot
353 \(e.g. if it is in the middle of a string\). If the returned value is only
354 part of the prefix (e.g. the part after \"->\" in C), the back-end may return a
355 cons of prefix and prefix length, which is then used in the
356 `company-minimum-prefix-length' test.
358 `candidates': The second argument is the prefix to be completed. The
359 return value should be a list of candidates that start with the prefix.
363 `sorted': The back-end may return t here to indicate that the candidates
364 are sorted and will not need to be sorted again.
366 `duplicates': If non-nil, company will take care of removing duplicates
369 `no-cache': Usually company doesn't ask for candidates again as completion
370 progresses, unless the back-end returns t for this command. The second
371 argument is the latest prefix.
373 `meta': The second argument is a completion candidate. The back-end should
374 return a (short) documentation string for it.
376 `doc-buffer': The second argument is a completion candidate.
377 The back-end should create a buffer (preferably with `company-doc-buffer'),
378 fill it with documentation and return it.
380 `location': The second argument is a completion candidate. The back-end can
381 return the cons of buffer and buffer location, or of file and line
382 number where the completion candidate was defined.
384 `require-match': If this value is t, the user is not allowed to enter anything
385 not offering as a candidate. Use with care! The default value nil gives the
386 user that choice with `company-require-match'. Return value 'never overrides
387 that option the other way around.
389 The back-end should return nil for all commands it does not support or
390 does not know about. It should also be callable interactively and use
391 `company-begin-backend' to start itself in that case."
396 ,@(mapcar (lambda (b) `(const :tag ,(cdr b) ,(car b)))
397 company-safe-backends)
398 (symbol :tag "User defined")
399 (repeat :tag "Merged Back-ends"
400 (choice :tag "Back-end"
401 ,@(mapcar (lambda (b)
402 `(const :tag ,(cdr b) ,(car b)))
403 company-safe-backends)
404 (symbol :tag "User defined"))))))
406 (put 'company-backends 'safe-local-variable 'company-safe-backends-p)
408 (defcustom company-completion-started-hook nil
409 "*Hook run when company starts completing.
410 The hook is called with one argument that is non-nil if the completion was
415 (defcustom company-completion-cancelled-hook nil
416 "*Hook run when company cancels completing.
417 The hook is called with one argument that is non-nil if the completion was
422 (defcustom company-completion-finished-hook nil
423 "*Hook run when company successfully completes.
424 The hook is called with the selected candidate as an argument."
428 (defcustom company-minimum-prefix-length 3
429 "*The minimum prefix length for automatic completion."
431 :type '(integer :tag "prefix length"))
433 (defcustom company-require-match 'company-explicit-action-p
434 "*If enabled, disallow non-matching input.
435 This can be a function do determine if a match is required.
437 This can be overridden by the back-end, if it returns t or 'never to
438 'require-match. `company-auto-complete' also takes precedence over this."
440 :type '(choice (const :tag "Off" nil)
441 (function :tag "Predicate function")
442 (const :tag "On, if user interaction took place"
443 'company-explicit-action-p)
444 (const :tag "On" t)))
446 (defcustom company-auto-complete 'company-explicit-action-p
447 "Determines when to auto-complete.
448 If this is enabled, all characters from `company-auto-complete-chars' complete
449 the selected completion. This can also be a function."
451 :type '(choice (const :tag "Off" nil)
452 (function :tag "Predicate function")
453 (const :tag "On, if user interaction took place"
454 'company-explicit-action-p)
455 (const :tag "On" t)))
457 (defcustom company-auto-complete-chars '(?\ ?\( ?\) ?. ?\" ?$ ?\' ?< ?| ?!)
458 "Determines which characters trigger an automatic completion.
459 See `company-auto-complete'. If this is a string, each string character causes
460 completion. If it is a list of syntax description characters (see
461 `modify-syntax-entry'), all characters with that syntax auto-complete.
463 This can also be a function, which is called with the new input and should
464 return non-nil if company should auto-complete.
466 A character that is part of a valid candidate never starts auto-completion."
468 :type '(choice (string :tag "Characters")
470 (const :tag "Whitespace" ?\ )
471 (const :tag "Symbol" ?_)
472 (const :tag "Opening parentheses" ?\()
473 (const :tag "Closing parentheses" ?\))
474 (const :tag "Word constituent" ?w)
475 (const :tag "Punctuation." ?.)
476 (const :tag "String quote." ?\")
477 (const :tag "Paired delimiter." ?$)
478 (const :tag "Expression quote or prefix operator." ?\')
479 (const :tag "Comment starter." ?<)
480 (const :tag "Comment ender." ?>)
481 (const :tag "Character-quote." ?/)
482 (const :tag "Generic string fence." ?|)
483 (const :tag "Generic comment fence." ?!))
484 (function :tag "Predicate function")))
486 (defcustom company-idle-delay .7
487 "*The idle delay in seconds until automatic completions starts.
488 A value of nil means never complete automatically, t means complete
489 immediately when a prefix of `company-minimum-prefix-length' is reached."
491 :type '(choice (const :tag "never (nil)" nil)
492 (const :tag "immediate (t)" t)
493 (number :tag "seconds")))
495 (defcustom company-begin-commands t
496 "*A list of commands following which company will start completing.
497 If this is t, it will complete after any command. See `company-idle-delay'.
499 Alternatively any command with a non-nil 'company-begin property is treated as
500 if it was on this list."
502 :type '(choice (const :tag "Any command" t)
503 (const :tag "Self insert command" '(self-insert-command))
504 (repeat :tag "Commands" function)))
506 (defcustom company-show-numbers nil
507 "*If enabled, show quick-access numbers for the first ten candidates."
509 :type '(choice (const :tag "off" nil)
510 (const :tag "on" t)))
512 (defvar company-end-of-buffer-workaround t
513 "*Work around a visualization bug when completing at the end of the buffer.
514 The work-around consists of adding a newline.")
516 ;;; mode ;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;
518 (defvar company-mode-map (make-sparse-keymap)
519 "Keymap used by `company-mode'.")
521 (defvar company-active-map
522 (let ((keymap (make-sparse-keymap)))
523 (define-key keymap "\e\e\e" 'company-abort)
524 (define-key keymap "\C-g" 'company-abort)
525 (define-key keymap (kbd "M-n") 'company-select-next)
526 (define-key keymap (kbd "M-p") 'company-select-previous)
527 (define-key keymap (kbd "<down>") 'company-select-next)
528 (define-key keymap (kbd "<up>") 'company-select-previous)
529 (define-key keymap [down-mouse-1] 'ignore)
530 (define-key keymap [down-mouse-3] 'ignore)
531 (define-key keymap [mouse-1] 'company-complete-mouse)
532 (define-key keymap [mouse-3] 'company-select-mouse)
533 (define-key keymap [up-mouse-1] 'ignore)
534 (define-key keymap [up-mouse-3] 'ignore)
535 (define-key keymap "\C-m" 'company-complete-selection)
536 (define-key keymap "\t" 'company-complete-common)
537 (define-key keymap (kbd "<f1>") 'company-show-doc-buffer)
538 (define-key keymap "\C-w" 'company-show-location)
539 (define-key keymap "\C-s" 'company-search-candidates)
540 (define-key keymap "\C-\M-s" 'company-filter-candidates)
542 (define-key keymap (vector (+ (aref (kbd "M-0") 0) i))
543 `(lambda () (interactive) (company-complete-number ,i))))
546 "Keymap that is enabled during an active completion.")
548 (defvar company--disabled-backends nil)
550 (defun company-init-backend (backend)
551 (and (symbolp backend)
552 (not (fboundp backend))
553 (ignore-errors (require backend nil t)))
555 (if (or (symbolp backend)
559 (funcall backend 'init)
560 (put backend 'company-init t))
562 (put backend 'company-init 'failed)
563 (unless (memq backend company--disabled-backends)
564 (message "Company back-end '%s' could not be initialized:\n%s"
565 backend (error-message-string err)))
566 (push backend company--disabled-backends)
568 (mapc 'company-init-backend backend)))
570 (defvar company-default-lighter " company")
572 (defvar company-lighter company-default-lighter)
573 (make-variable-buffer-local 'company-lighter)
576 (define-minor-mode company-mode
577 "\"complete anything\"; in in-buffer completion framework.
578 Completion starts automatically, depending on the values
579 `company-idle-delay' and `company-minimum-prefix-length'.
581 Completion can be controlled with the commands:
582 `company-complete-common', `company-complete-selection', `company-complete',
583 `company-select-next', `company-select-previous'. If these commands are
584 called before `company-idle-delay', completion will also start.
586 Completions can be searched with `company-search-candidates' or
587 `company-filter-candidates'. These can be used while completion is
590 The completion data is retrieved using `company-backends' and displayed using
591 `company-frontends'. If you want to start a specific back-end, call it
592 interactively or use `company-begin-backend'.
594 regular keymap (`company-mode-map'):
597 keymap during active completions (`company-active-map'):
599 \\{company-active-map}"
600 nil company-lighter company-mode-map
603 (add-hook 'pre-command-hook 'company-pre-command nil t)
604 (add-hook 'post-command-hook 'company-post-command nil t)
605 (mapc 'company-init-backend company-backends))
606 (remove-hook 'pre-command-hook 'company-pre-command t)
607 (remove-hook 'post-command-hook 'company-post-command t)
609 (kill-local-variable 'company-point)))
611 (define-globalized-minor-mode global-company-mode company-mode
612 (lambda () (company-mode 1)))
614 (defsubst company-assert-enabled ()
616 (company-uninstall-map)
617 (error "Company not enabled")))
619 ;;; keymaps ;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;
621 (defvar company-overriding-keymap-bound nil)
622 (make-variable-buffer-local 'company-overriding-keymap-bound)
624 (defvar company-old-keymap nil)
625 (make-variable-buffer-local 'company-old-keymap)
627 (defvar company-my-keymap nil)
628 (make-variable-buffer-local 'company-my-keymap)
630 (defsubst company-enable-overriding-keymap (keymap)
631 (setq company-my-keymap keymap)
632 (when company-overriding-keymap-bound
633 (company-uninstall-map)))
635 (defun company-install-map ()
636 (unless (or company-overriding-keymap-bound
637 (null company-my-keymap))
638 (setq company-old-keymap overriding-terminal-local-map
639 overriding-terminal-local-map company-my-keymap
640 company-overriding-keymap-bound t)))
642 (defun company-uninstall-map ()
643 (when (eq overriding-terminal-local-map company-my-keymap)
644 (setq overriding-terminal-local-map company-old-keymap
645 company-overriding-keymap-bound nil)))
648 ;; Emacs calculates the active keymaps before reading the event. That means we
649 ;; cannot change the keymap from a timer. So we send a bogus command.
650 (defun company-ignore ()
652 (setq this-command last-command))
654 (global-set-key '[31415926] 'company-ignore)
656 (defun company-input-noop ()
657 (push 31415926 unread-command-events))
660 ;; posn-col-row is incorrect in older Emacsen when line-spacing is set
661 (defun company--col-row (&optional pos)
662 (let ((posn (posn-at-point pos)))
663 (cons (car (posn-col-row posn)) (cdr (posn-actual-col-row posn)))))
665 (defsubst company--column (&optional pos)
666 (car (posn-col-row (posn-at-point pos))))
668 (defsubst company--row (&optional pos)
669 (cdr (posn-actual-col-row (posn-at-point pos))))
671 ;;; backends ;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;
673 (defun company-grab (regexp &optional expression limit)
674 (when (looking-back regexp limit)
675 (or (match-string-no-properties (or expression 0)) "")))
677 (defun company-grab-line (regexp &optional expression)
678 (company-grab regexp expression (point-at-bol)))
680 (defun company-grab-symbol ()
681 (if (looking-at "\\_>")
682 (buffer-substring (point) (save-excursion (skip-syntax-backward "w_")
684 (unless (and (char-after) (memq (char-syntax (char-after)) '(?w ?_)))
687 (defun company-grab-word ()
688 (if (looking-at "\\>")
689 (buffer-substring (point) (save-excursion (skip-syntax-backward "w")
691 (unless (and (char-after) (eq (char-syntax (char-after)) ?w))
694 (defun company-in-string-or-comment ()
695 (let ((ppss (syntax-ppss)))
696 (or (car (setq ppss (nthcdr 3 ppss)))
697 (car (setq ppss (cdr ppss)))
700 (if (fboundp 'locate-dominating-file)
701 (defalias 'company-locate-dominating-file 'locate-dominating-file)
702 (defun company-locate-dominating-file (file name)
704 (let ((dir (file-name-directory file))
706 (while (not (equal dir prev-dir))
707 (when (file-exists-p (expand-file-name name dir))
710 dir (file-name-directory (directory-file-name dir))))))))
712 (defun company-call-backend (&rest args)
713 (if (functionp company-backend)
714 (apply company-backend args)
715 (apply 'company--multi-backend-adapter company-backend args)))
717 (defun company--multi-backend-adapter (backends command &rest args)
720 (apply 'append (mapcar (lambda (backend) (apply backend command args))
726 (dolist (backend backends)
727 (when (setq value (apply backend command args))
730 ;;; completion mechanism ;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;
732 (defvar company-backend nil)
733 (make-variable-buffer-local 'company-backend)
735 (defvar company-prefix nil)
736 (make-variable-buffer-local 'company-prefix)
738 (defvar company-candidates nil)
739 (make-variable-buffer-local 'company-candidates)
741 (defvar company-candidates-length nil)
742 (make-variable-buffer-local 'company-candidates-length)
744 (defvar company-candidates-cache nil)
745 (make-variable-buffer-local 'company-candidates-cache)
747 (defvar company-candidates-predicate nil)
748 (make-variable-buffer-local 'company-candidates-predicate)
750 (defvar company-common nil)
751 (make-variable-buffer-local 'company-common)
753 (defvar company-selection 0)
754 (make-variable-buffer-local 'company-selection)
756 (defvar company-selection-changed nil)
757 (make-variable-buffer-local 'company-selection-changed)
759 (defvar company--explicit-action nil
760 "Non-nil, if explicit completion took place.")
761 (make-variable-buffer-local 'company--explicit-action)
763 (defvar company--point-max nil)
764 (make-variable-buffer-local 'company--point-max)
766 (defvar company-point nil)
767 (make-variable-buffer-local 'company-point)
769 (defvar company-timer nil)
771 (defvar company-added-newline nil)
772 (make-variable-buffer-local 'company-added-newline)
774 (defsubst company-strip-prefix (str)
775 (substring str (length company-prefix)))
777 (defmacro company-with-candidate-inserted (candidate &rest body)
778 "Evaluate BODY with CANDIDATE temporarily inserted.
779 This is a tool for back-ends that need candidates inserted before they
780 can retrieve meta-data for them."
782 `(let ((inhibit-modification-hooks t)
783 (inhibit-point-motion-hooks t)
784 (modified-p (buffer-modified-p)))
785 (insert (company-strip-prefix ,candidate))
788 (delete-region company-point (point)))))
790 (defun company-explicit-action-p ()
791 "Return whether explicit completion action was taken by the user."
792 (or company--explicit-action
793 company-selection-changed))
795 (defsubst company-reformat (candidate)
796 ;; company-ispell needs this, because the results are always lower-case
797 ;; It's mory efficient to fix it only when they are displayed.
798 (concat company-prefix (substring candidate (length company-prefix))))
800 (defun company--should-complete ()
801 (and (not (or buffer-read-only overriding-terminal-local-map
802 overriding-local-map))
803 ;; Check if in the middle of entering a key combination.
804 (or (equal (this-command-keys-vector) [])
805 (not (keymapp (key-binding (this-command-keys-vector)))))
806 (eq company-idle-delay t)
807 (or (eq t company-begin-commands)
808 (memq this-command company-begin-commands)
809 (and (symbolp this-command) (get this-command 'company-begin)))
810 (not (and transient-mark-mode mark-active))))
812 (defsubst company-call-frontends (command)
813 (dolist (frontend company-frontends)
815 (funcall frontend command)
816 (error (error "Company: Front-end %s error \"%s\" on command %s"
817 frontend (error-message-string err) command)))))
819 (defsubst company-set-selection (selection &optional force-update)
820 (setq selection (max 0 (min (1- company-candidates-length) selection)))
821 (when (or force-update (not (equal selection company-selection)))
822 (setq company-selection selection
823 company-selection-changed t)
824 (company-call-frontends 'update)))
826 (defun company-apply-predicate (candidates predicate)
828 (dolist (c candidates)
829 (when (funcall predicate c)
833 (defun company-update-candidates (candidates)
834 (setq company-candidates-length (length candidates))
835 (if (> company-selection 0)
836 ;; Try to restore the selection
837 (let ((selected (nth company-selection company-candidates)))
838 (setq company-selection 0
839 company-candidates candidates)
841 (while (and candidates (string< (pop candidates) selected))
842 (incf company-selection))
844 ;; Make sure selection isn't out of bounds.
845 (setq company-selection (min (1- company-candidates-length)
846 company-selection)))))
847 (setq company-selection 0
848 company-candidates candidates))
850 (push (cons company-prefix company-candidates) company-candidates-cache)
852 (let ((completion-ignore-case (company-call-backend 'ignore-case)))
853 (setq company-common (try-completion company-prefix company-candidates)))
854 (when (eq company-common t)
855 (setq company-candidates nil)))
857 (defun company-calculate-candidates (prefix)
858 (let ((candidates (cdr (assoc prefix company-candidates-cache))))
860 (when company-candidates-cache
861 (let ((len (length prefix))
862 (completion-ignore-case (company-call-backend 'ignore-case))
864 (dotimes (i (1+ len))
865 (when (setq prev (cdr (assoc (substring prefix 0 (- len i))
866 company-candidates-cache)))
867 (setq candidates (all-completions prefix prev))
869 ;; no cache match, call back-end
871 (setq candidates (company-call-backend 'candidates prefix))
872 (when company-candidates-predicate
874 (company-apply-predicate candidates
875 company-candidates-predicate)))
876 (unless (company-call-backend 'sorted)
877 (setq candidates (sort candidates 'string<)))
878 (when (company-call-backend 'duplicates)
880 (let ((c2 candidates))
882 (setcdr c2 (progn (while (equal (pop c2) (car c2)))
884 (if (or (cdr candidates)
885 (not (equal (car candidates) prefix)))
886 ;; Don't start when already completed and unique.
888 ;; Not the right place? maybe when setting?
889 (and company-candidates t))))
891 (defun company-idle-begin (buf win tick pos)
893 (eq buf (current-buffer))
894 (eq win (selected-window))
895 (eq tick (buffer-chars-modified-tick))
897 (not company-candidates)
898 (not (equal (point) company-point))
899 (let ((company-idle-delay t)
900 (company-begin-commands t))
902 (when company-candidates
904 (company-post-command)))))
906 (defun company-auto-begin ()
907 (company-assert-enabled)
909 (not company-candidates)
910 (let ((company-idle-delay t)
911 (company-minimum-prefix-length 0)
912 (company-begin-commands t))
914 ;; Return non-nil if active.
917 (defun company-manual-begin ()
919 (setq company--explicit-action t)
920 (company-auto-begin))
922 (defun company-other-backend (&optional backward)
923 (interactive (list current-prefix-arg))
924 (company-assert-enabled)
926 (let* ((after (cdr (member company-backend company-backends)))
927 (before (cdr (member company-backend (reverse company-backends))))
929 (append before (reverse after))
930 (append after (reverse before)))))
932 (dolist (backend next)
933 (when (ignore-errors (company-begin-backend backend))
935 (company-manual-begin))
936 (unless company-candidates
937 (error "No other back-end")))
939 (defun company-require-match-p ()
940 (let ((backend-value (company-call-backend 'require-match)))
941 (or (eq backend-value t)
942 (and (if (functionp company-require-match)
943 (funcall company-require-match)
944 (eq company-require-match t))
945 (not (eq backend-value 'never))))))
947 (defun company-punctuation-p (input)
948 "Return non-nil, if input starts with punctuation or parentheses."
949 (memq (char-syntax (string-to-char input)) '(?. ?\( ?\))))
951 (defun company-auto-complete-p (input)
952 "Return non-nil, if input starts with punctuation or parentheses."
953 (and (if (functionp company-auto-complete)
954 (funcall company-auto-complete)
955 company-auto-complete)
956 (if (functionp company-auto-complete-chars)
957 (funcall company-auto-complete-chars input)
958 (if (consp company-auto-complete-chars)
959 (memq (char-syntax (string-to-char input))
960 company-auto-complete-chars)
961 (string-match (substring input 0 1) company-auto-complete-chars)))))
963 (defun company--incremental-p ()
964 (and (> (point) company-point)
965 (> (point-max) company--point-max)
966 (not (eq this-command 'backward-delete-char-untabify))
967 (equal (buffer-substring (- company-point (length company-prefix))
971 (defsubst company--string-incremental-p (old-prefix new-prefix)
972 (and (> (length new-prefix) (length old-prefix))
973 (equal old-prefix (substring new-prefix 0 (length old-prefix)))))
975 (defun company--continue-failed (new-prefix)
976 (when (company--incremental-p)
977 (let ((input (buffer-substring-no-properties (point) company-point)))
979 ((company-auto-complete-p input)
982 (goto-char company-point)
983 (company-complete-selection)
985 ((and (company--string-incremental-p company-prefix new-prefix)
986 (company-require-match-p))
987 ;; wrong incremental input, but required match
988 (backward-delete-char (length input))
990 (message "Matching input is required")
992 ((equal company-prefix (car company-candidates))
993 ;; last input was actually success
994 (company-cancel company-prefix)
997 (defun company--good-prefix-p (prefix)
998 (and (or (company-explicit-action-p)
999 (>= (or (cdr-safe prefix) (length prefix))
1000 company-minimum-prefix-length))
1001 (stringp (or (car-safe prefix) prefix))))
1003 (defun company--continue ()
1004 (when (company-call-backend 'no-cache company-prefix)
1005 ;; Don't complete existing candidates, fetch new ones.
1006 (setq company-candidates-cache nil))
1007 (let* ((new-prefix (company-call-backend 'prefix))
1008 (c (when (and (company--good-prefix-p new-prefix)
1009 (setq new-prefix (or (car-safe new-prefix) new-prefix))
1010 (= (- (point) (length new-prefix))
1011 (- company-point (length company-prefix))))
1012 (setq new-prefix (or (car-safe new-prefix) new-prefix))
1013 (company-calculate-candidates new-prefix))))
1016 ;; t means complete/unique.
1017 (company-cancel new-prefix)
1020 ;; incremental match
1021 (setq company-prefix new-prefix)
1022 (company-update-candidates c)
1024 (t (company--continue-failed new-prefix)))
1027 (defun company--begin-new ()
1029 (dolist (backend (if company-backend
1030 ;; prefer manual override
1031 (list company-backend)
1034 (if (or (symbolp backend)
1035 (functionp backend))
1036 (when (or (not (symbolp backend))
1037 (eq t (get backend 'company-init))
1038 (unless (get backend 'company-init)
1039 (company-init-backend backend)))
1040 (funcall backend 'prefix))
1041 (company--multi-backend-adapter backend 'prefix)))
1043 (when (company--good-prefix-p prefix)
1044 (setq prefix (or (car-safe prefix) prefix)
1045 company-backend backend
1046 c (company-calculate-candidates prefix))
1047 ;; t means complete/unique. We don't start, so no hooks.
1049 (when company--explicit-action
1050 (message "No completion found"))
1051 (setq company-prefix prefix)
1052 (when (symbolp backend)
1053 (setq company-lighter (concat " " (symbol-name backend))))
1054 (company-update-candidates c)
1055 (run-hook-with-args 'company-completion-started-hook
1056 (company-explicit-action-p))
1057 (company-call-frontends 'show)))
1060 (defun company-begin ()
1061 (setq company-candidates
1062 (or (and company-candidates (company--continue))
1063 (and (company--should-complete) (company--begin-new))))
1064 (when company-candidates
1065 (when (and company-end-of-buffer-workaround (eobp))
1066 (save-excursion (insert "\n"))
1067 (setq company-added-newline (buffer-chars-modified-tick)))
1068 (setq company-point (point)
1069 company--point-max (point-max))
1070 (company-enable-overriding-keymap company-active-map)
1071 (company-call-frontends 'update)))
1073 (defun company-cancel (&optional result)
1074 (and company-added-newline
1075 (> (point-max) (point-min))
1076 (let ((tick (buffer-chars-modified-tick)))
1077 (delete-region (1- (point-max)) (point-max))
1078 (equal tick company-added-newline))
1079 ;; Only set unmodified when tick remained the same since insert.
1080 (set-buffer-modified-p nil))
1081 (when company-prefix
1082 (if (stringp result)
1084 (company-call-backend 'pre-completion result)
1085 (run-hook-with-args 'company-completion-finished-hook result)
1086 (company-call-backend 'post-completion result))
1087 (run-hook-with-args 'company-completion-cancelled-hook result)))
1088 (setq company-added-newline nil
1091 company-candidates nil
1092 company-candidates-length nil
1093 company-candidates-cache nil
1094 company-candidates-predicate nil
1097 company-selection-changed nil
1098 company--explicit-action nil
1099 company-lighter company-default-lighter
1100 company--point-max nil
1103 (cancel-timer company-timer))
1104 (company-search-mode 0)
1105 (company-call-frontends 'hide)
1106 (company-enable-overriding-keymap nil))
1108 (defun company-abort ()
1111 ;; Don't start again, unless started manually.
1112 (setq company-point (point)))
1114 (defun company-finish (result)
1115 (insert (company-strip-prefix result))
1116 (company-cancel result)
1117 ;; Don't start again, unless started manually.
1118 (setq company-point (point)))
1120 (defsubst company-keep (command)
1121 (and (symbolp command) (get command 'company-keep)))
1123 (defun company-pre-command ()
1124 (unless (company-keep this-command)
1126 (when company-candidates
1127 (company-call-frontends 'pre-command))
1128 (error (message "Company: An error occurred in pre-command")
1129 (message "%s" (error-message-string err))
1132 (cancel-timer company-timer)
1133 (setq company-timer nil))
1134 (company-uninstall-map))
1136 (defun company-post-command ()
1137 (unless (company-keep this-command)
1140 (unless (equal (point) company-point)
1142 (if company-candidates
1143 (company-call-frontends 'post-command)
1144 (and (numberp company-idle-delay)
1145 (or (eq t company-begin-commands)
1146 (memq this-command company-begin-commands))
1148 (run-with-timer company-idle-delay nil
1150 (current-buffer) (selected-window)
1151 (buffer-chars-modified-tick) (point))))))
1152 (error (message "Company: An error occurred in post-command")
1153 (message "%s" (error-message-string err))
1155 (company-install-map))
1157 ;;; search ;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;
1159 (defvar company-search-string nil)
1160 (make-variable-buffer-local 'company-search-string)
1162 (defvar company-search-lighter " Search: \"\"")
1163 (make-variable-buffer-local 'company-search-lighter)
1165 (defvar company-search-old-map nil)
1166 (make-variable-buffer-local 'company-search-old-map)
1168 (defvar company-search-old-selection 0)
1169 (make-variable-buffer-local 'company-search-old-selection)
1171 (defun company-search (text lines)
1172 (let ((quoted (regexp-quote text))
1174 (dolist (line lines)
1175 (when (string-match quoted line (length company-prefix))
1179 (defun company-search-printing-char ()
1181 (company-search-assert-enabled)
1182 (setq company-search-string
1183 (concat (or company-search-string "") (string last-command-event))
1184 company-search-lighter (concat " Search: \"" company-search-string
1186 (let ((pos (company-search company-search-string
1187 (nthcdr company-selection company-candidates))))
1190 (company-set-selection (+ company-selection pos) t))))
1192 (defun company-search-repeat-forward ()
1193 "Repeat the incremental search in completion candidates forward."
1195 (company-search-assert-enabled)
1196 (let ((pos (company-search company-search-string
1197 (cdr (nthcdr company-selection
1198 company-candidates)))))
1201 (company-set-selection (+ company-selection pos 1) t))))
1203 (defun company-search-repeat-backward ()
1204 "Repeat the incremental search in completion candidates backwards."
1206 (company-search-assert-enabled)
1207 (let ((pos (company-search company-search-string
1208 (nthcdr (- company-candidates-length
1210 (reverse company-candidates)))))
1213 (company-set-selection (- company-selection pos 1) t))))
1215 (defun company-create-match-predicate ()
1216 (setq company-candidates-predicate
1217 `(lambda (candidate)
1218 ,(if company-candidates-predicate
1219 `(and (string-match ,company-search-string candidate)
1220 (funcall ,company-candidates-predicate
1222 `(string-match ,company-search-string candidate))))
1223 (company-update-candidates
1224 (company-apply-predicate company-candidates company-candidates-predicate))
1225 ;; Invalidate cache.
1226 (setq company-candidates-cache (cons company-prefix company-candidates)))
1228 (defun company-filter-printing-char ()
1230 (company-search-assert-enabled)
1231 (company-search-printing-char)
1232 (company-create-match-predicate)
1233 (company-call-frontends 'update))
1235 (defun company-search-kill-others ()
1236 "Limit the completion candidates to the ones matching the search string."
1238 (company-search-assert-enabled)
1239 (company-create-match-predicate)
1240 (company-search-mode 0)
1241 (company-call-frontends 'update))
1243 (defun company-search-abort ()
1244 "Abort searching the completion candidates."
1246 (company-search-assert-enabled)
1247 (company-set-selection company-search-old-selection t)
1248 (company-search-mode 0))
1250 (defun company-search-other-char ()
1252 (company-search-assert-enabled)
1253 (company-search-mode 0)
1254 (when last-input-event
1255 (clear-this-command-keys t)
1256 (setq unread-command-events (list last-input-event))))
1258 (defvar company-search-map
1260 (keymap (make-keymap)))
1261 (if (fboundp 'max-char)
1262 (set-char-table-range (nth 1 keymap) (cons #x100 (max-char))
1263 'company-search-printing-char)
1265 ;; obselete in Emacs 23
1266 (let ((l (generic-character-list))
1267 (table (nth 1 keymap)))
1269 (set-char-table-default table (car l) 'company-search-printing-char)
1270 (setq l (cdr l))))))
1271 (define-key keymap [t] 'company-search-other-char)
1273 (define-key keymap (make-string 1 i) 'company-search-other-char)
1276 (define-key keymap (vector i) 'company-search-printing-char)
1278 (let ((meta-map (make-sparse-keymap)))
1279 (define-key keymap (char-to-string meta-prefix-char) meta-map)
1280 (define-key keymap [escape] meta-map))
1281 (define-key keymap (vector meta-prefix-char t) 'company-search-other-char)
1282 (define-key keymap "\e\e\e" 'company-search-other-char)
1283 (define-key keymap [escape escape escape] 'company-search-other-char)
1285 (define-key keymap "\C-g" 'company-search-abort)
1286 (define-key keymap "\C-s" 'company-search-repeat-forward)
1287 (define-key keymap "\C-r" 'company-search-repeat-backward)
1288 (define-key keymap "\C-o" 'company-search-kill-others)
1290 "Keymap used for incrementally searching the completion candidates.")
1292 (define-minor-mode company-search-mode
1293 "Search mode for completion candidates.
1294 Don't start this directly, use `company-search-candidates' or
1295 `company-filter-candidates'."
1296 nil company-search-lighter nil
1297 (if company-search-mode
1298 (if (company-manual-begin)
1300 (setq company-search-old-selection company-selection)
1301 (company-call-frontends 'update))
1302 (setq company-search-mode nil))
1303 (kill-local-variable 'company-search-string)
1304 (kill-local-variable 'company-search-lighter)
1305 (kill-local-variable 'company-search-old-selection)
1306 (company-enable-overriding-keymap company-active-map)))
1308 (defsubst company-search-assert-enabled ()
1309 (company-assert-enabled)
1310 (unless company-search-mode
1311 (company-uninstall-map)
1312 (error "Company not in search mode")))
1314 (defun company-search-candidates ()
1315 "Start searching the completion candidates incrementally.
1317 \\<company-search-map>Search can be controlled with the commands:
1318 - `company-search-repeat-forward' (\\[company-search-repeat-forward])
1319 - `company-search-repeat-backward' (\\[company-search-repeat-backward])
1320 - `company-search-abort' (\\[company-search-abort])
1322 Regular characters are appended to the search string.
1324 The command `company-search-kill-others' (\\[company-search-kill-others]) uses
1325 the search string to limit the completion candidates."
1327 (company-search-mode 1)
1328 (company-enable-overriding-keymap company-search-map))
1330 (defvar company-filter-map
1331 (let ((keymap (make-keymap)))
1332 (define-key keymap [remap company-search-printing-char]
1333 'company-filter-printing-char)
1334 (set-keymap-parent keymap company-search-map)
1336 "Keymap used for incrementally searching the completion candidates.")
1338 (defun company-filter-candidates ()
1339 "Start filtering the completion candidates incrementally.
1340 This works the same way as `company-search-candidates' immediately
1341 followed by `company-search-kill-others' after each input."
1343 (company-search-mode 1)
1344 (company-enable-overriding-keymap company-filter-map))
1346 ;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;
1348 (defun company-select-next ()
1349 "Select the next candidate in the list."
1351 (when (company-manual-begin)
1352 (company-set-selection (1+ company-selection))))
1354 (defun company-select-previous ()
1355 "Select the previous candidate in the list."
1357 (when (company-manual-begin)
1358 (company-set-selection (1- company-selection))))
1360 (defun company-select-mouse (event)
1361 "Select the candidate picked by the mouse."
1363 (when (nth 4 (event-start event))
1364 (company-set-selection (- (cdr (posn-actual-col-row (event-start event)))
1369 (defun company-complete-mouse (event)
1370 "Complete the candidate picked by the mouse."
1372 (when (company-select-mouse event)
1373 (company-complete-selection)))
1375 (defun company-complete-selection ()
1376 "Complete the selected candidate."
1378 (when (company-manual-begin)
1379 (company-finish (nth company-selection company-candidates))))
1381 (defun company-complete-common ()
1382 "Complete the common part of all candidates."
1384 (when (company-manual-begin)
1385 (if (and (not (cdr company-candidates))
1386 (equal company-common (car company-candidates)))
1387 (company-complete-selection)
1388 (insert (company-strip-prefix company-common)))))
1390 (defun company-complete ()
1391 "Complete the common part of all candidates or the current selection.
1392 The first time this is called, the common part is completed, the second time, or
1393 when the selection has been changed, the selected candidate is completed."
1395 (when (company-manual-begin)
1396 (if (or company-selection-changed
1397 (eq last-command 'company-complete-common))
1398 (call-interactively 'company-complete-selection)
1399 (call-interactively 'company-complete-common)
1400 (setq this-command 'company-complete-common))))
1402 (defun company-complete-number (n)
1403 "Complete the Nth candidate.
1404 To show the number next to the candidates in some back-ends, enable
1405 `company-show-numbers'."
1406 (when (company-manual-begin)
1407 (and (< n 1) (> n company-candidates-length)
1408 (error "No candidate number %d" n))
1410 (company-finish (nth n company-candidates))))
1412 ;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;
1414 (defconst company-space-strings-limit 100)
1416 (defconst company-space-strings
1418 (dotimes (i company-space-strings-limit)
1419 (push (make-string (- company-space-strings-limit 1 i) ?\ ) lst))
1420 (apply 'vector lst)))
1422 (defsubst company-space-string (len)
1423 (if (< len company-space-strings-limit)
1424 (aref company-space-strings len)
1425 (make-string len ?\ )))
1427 (defsubst company-safe-substring (str from &optional to)
1428 (let ((len (length str)))
1431 (if (and to (> to len))
1432 (concat (substring str from)
1433 (company-space-string (- to len)))
1434 (substring str from to)))))
1436 ;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;
1438 (defvar company-last-metadata nil)
1439 (make-variable-buffer-local 'company-last-metadata)
1441 (defun company-fetch-metadata ()
1442 (let ((selected (nth company-selection company-candidates)))
1443 (unless (equal selected (car company-last-metadata))
1444 (setq company-last-metadata
1445 (cons selected (company-call-backend 'meta selected))))
1446 (cdr company-last-metadata)))
1448 (defun company-doc-buffer (&optional string)
1449 (with-current-buffer (get-buffer-create "*Company meta-data*")
1453 (defvar company--electric-commands
1454 '(scroll-other-window scroll-other-window-down)
1455 "List of Commands that won't break out of electric commands.")
1457 (defmacro company--electric-do (&rest body)
1458 (declare (indent 0) (debug t))
1459 `(when (company-manual-begin)
1460 (save-window-excursion
1461 (let ((height (window-height))
1462 (row (company--row))
1465 (and (< (window-height) height)
1466 (< (- (window-height) row 2) company-tooltip-limit)
1467 (recenter (- (window-height) row 2)))
1468 (while (memq (setq cmd (key-binding (vector (list (read-event)))))
1469 company--electric-commands)
1470 (call-interactively cmd))
1471 (when last-input-event
1472 (clear-this-command-keys t)
1473 (setq unread-command-events (list last-input-event)))))))
1475 (defun company-show-doc-buffer ()
1476 "Temporarily show a buffer with the complete documentation for the selection."
1478 (company--electric-do
1479 (let* ((selected (nth company-selection company-candidates))
1480 (doc-buffer (or (company-call-backend 'doc-buffer selected)
1481 (error "No documentation available"))))
1482 (with-current-buffer doc-buffer
1483 (goto-char (point-min)))
1484 (display-buffer doc-buffer t))))
1485 (put 'company-show-doc-buffer 'company-keep t)
1487 (defun company-show-location ()
1488 "Temporarily display a buffer showing the selected candidate in context."
1490 (company--electric-do
1491 (let* ((selected (nth company-selection company-candidates))
1492 (location (company-call-backend 'location selected))
1493 (pos (or (cdr location) (error "No location available")))
1494 (buffer (or (and (bufferp (car location)) (car location))
1495 (find-file-noselect (car location) t))))
1496 (with-selected-window (display-buffer buffer t)
1499 (if (bufferp (car location))
1501 (goto-char (point-min))
1502 (forward-line (1- pos))))
1503 (set-window-start nil (point))))))
1504 (put 'company-show-location 'company-keep t)
1506 ;;; package functions ;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;
1508 (defvar company-callback nil)
1509 (make-variable-buffer-local 'company-callback)
1511 (defvar company-begin-with-marker nil)
1512 (make-variable-buffer-local 'company-begin-with-marker)
1514 (defun company-remove-callback (&optional ignored)
1515 (remove-hook 'company-completion-finished-hook company-callback t)
1516 (remove-hook 'company-completion-cancelled-hook 'company-remove-callback t)
1517 (remove-hook 'company-completion-finished-hook 'company-remove-callback t)
1518 (when company-begin-with-marker
1519 (set-marker company-begin-with-marker nil)))
1521 (defun company-begin-backend (backend &optional callback)
1522 "Start a completion at point using BACKEND."
1523 (interactive (let ((val (completing-read "Company back-end: "
1525 'functionp nil "company-")))
1527 (list (intern val)))))
1528 (when (setq company-callback callback)
1529 (add-hook 'company-completion-finished-hook company-callback nil t))
1530 (add-hook 'company-completion-cancelled-hook 'company-remove-callback nil t)
1531 (add-hook 'company-completion-finished-hook 'company-remove-callback nil t)
1532 (setq company-backend backend)
1533 ;; Return non-nil if active.
1534 (or (company-manual-begin)
1535 (error "Cannot complete at point")))
1537 (defun company-begin-with (candidates
1538 &optional prefix-length require-match callback)
1539 "Start a completion at point.
1540 CANDIDATES is the list of candidates to use and PREFIX-LENGTH is the length of
1541 the prefix that already is in the buffer before point. It defaults to 0.
1543 CALLBACK is a function called with the selected result if the user successfully
1544 completes the input.
1547 \(company-begin-with '\(\"foo\" \"foobar\" \"foobarbaz\"\)\)"
1548 (setq company-begin-with-marker (copy-marker (point) t))
1549 (company-begin-backend
1550 `(lambda (command &optional arg &rest ignored)
1552 ((eq command 'prefix)
1553 (when (equal (point) (marker-position company-begin-with-marker))
1554 (buffer-substring ,(- (point) (or prefix-length 0)) (point))))
1555 ((eq command 'candidates)
1556 (all-completions arg ',candidates))
1557 ((eq command 'require-match)
1561 ;;; pseudo-tooltip ;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;
1563 (defvar company-pseudo-tooltip-overlay nil)
1564 (make-variable-buffer-local 'company-pseudo-tooltip-overlay)
1566 (defvar company-tooltip-offset 0)
1567 (make-variable-buffer-local 'company-tooltip-offset)
1569 (defun company-pseudo-tooltip-update-offset (selection num-lines limit)
1572 (setq company-tooltip-offset
1573 (max (min selection company-tooltip-offset)
1574 (- selection -1 limit)))
1576 (when (<= company-tooltip-offset 1)
1578 (setq company-tooltip-offset 0))
1580 (when (>= company-tooltip-offset (- num-lines limit 1))
1582 (when (= selection (1- num-lines))
1583 (decf company-tooltip-offset)
1584 (when (<= company-tooltip-offset 1)
1585 (setq company-tooltip-offset 0)
1592 (defsubst company-round-tab (arg)
1593 (* (/ (+ arg tab-width) tab-width) tab-width))
1595 (defun company-untabify (str)
1596 (let* ((pieces (split-string str "\t"))
1599 (setcar copy (company-safe-substring
1600 (car copy) 0 (company-round-tab (string-width (car copy)))))
1602 (apply 'concat pieces)))
1604 (defun company-fill-propertize (line width selected)
1605 (setq line (company-safe-substring line 0 width))
1606 (add-text-properties 0 width '(face company-tooltip
1607 mouse-face company-tooltip-mouse)
1609 (add-text-properties 0 (length company-common)
1610 '(face company-tooltip-common
1611 mouse-face company-tooltip-mouse)
1614 (if (and company-search-string
1615 (string-match (regexp-quote company-search-string) line
1616 (length company-prefix)))
1618 (add-text-properties (match-beginning 0) (match-end 0)
1619 '(face company-tooltip-selection)
1621 (when (< (match-beginning 0) (length company-common))
1622 (add-text-properties (match-beginning 0) (length company-common)
1623 '(face company-tooltip-common-selection)
1625 (add-text-properties 0 width '(face company-tooltip-selection
1626 mouse-face company-tooltip-selection)
1628 (add-text-properties 0 (length company-common)
1629 '(face company-tooltip-common-selection
1630 mouse-face company-tooltip-selection)
1636 (defun company-buffer-lines (beg end)
1638 (let ((row (company--row))
1640 (while (and (equal (move-to-window-line (incf row)) row)
1642 (push (buffer-substring beg (min end (1- (point)))) lines)
1644 (unless (eq beg end)
1645 (push (buffer-substring beg end) lines))
1648 (defsubst company-modify-line (old new offset)
1649 (concat (company-safe-substring old 0 offset)
1651 (company-safe-substring old (+ offset (length new)))))
1653 (defsubst company--length-limit (lst limit)
1654 (if (nthcdr limit lst)
1658 (defun company--replacement-string (lines old column nl &optional align-top)
1660 (let ((width (length (car lines))))
1661 (when (> width (- (window-width) column))
1662 (setq column (max 0 (- (window-width) width)))))
1666 ;; untouched lines first
1667 (dotimes (i (- (length old) (length lines)))
1668 (push (pop old) new)))
1669 ;; length into old lines.
1671 (push (company-modify-line (pop old) (pop lines) column) new))
1672 ;; Append whole new lines.
1674 (push (concat (company-space-string column) (pop lines)) new))
1675 (concat (when nl "\n")
1676 (mapconcat 'identity (nreverse new) "\n")
1679 (defun company--create-lines (selection limit)
1681 (let ((len company-candidates-length)
1690 ;; Scroll to offset.
1691 (setq limit (company-pseudo-tooltip-update-offset selection len limit))
1693 (when (> company-tooltip-offset 0)
1694 (setq previous (format "...(%d)" company-tooltip-offset)))
1696 (setq remainder (- len limit company-tooltip-offset)
1697 remainder (when (> remainder 0)
1698 (setq remainder (format "...(%d)" remainder))))
1700 (decf selection company-tooltip-offset)
1701 (setq width (max (length previous) (length remainder))
1702 lines (nthcdr company-tooltip-offset company-candidates)
1707 (setq width (max (length (pop lines-copy)) width)))
1708 (setq width (min width (window-width)))
1710 (setq lines-copy lines)
1712 ;; number can make tooltip too long
1713 (when company-show-numbers
1714 (setq numbered company-tooltip-offset))
1717 (push (propertize (company-safe-substring previous 0 width)
1718 'face 'company-tooltip)
1722 (push (company-fill-propertize
1723 (if (>= numbered 10)
1724 (company-reformat (pop lines))
1727 (company-safe-substring (company-reformat (pop lines))
1730 width (equal i selection))
1734 (push (propertize (company-safe-substring remainder 0 width)
1735 'face 'company-tooltip)
1738 (setq lines (nreverse new))))
1742 (defsubst company--window-inner-height ()
1743 (let ((edges (window-inside-edges (selected-window))))
1744 (- (nth 3 edges) (nth 1 edges))))
1746 (defsubst company--pseudo-tooltip-height ()
1747 "Calculate the appropriate tooltip height.
1748 Returns a negative number if the tooltip should be displayed above point."
1749 (let* ((lines (count-lines (window-start) (point-at-bol)))
1750 (below (- (company--window-inner-height) 1 lines)))
1751 (if (and (< below (min company-tooltip-minimum company-candidates-length))
1753 (- (max 3 (min company-tooltip-limit lines)))
1754 (max 3 (min company-tooltip-limit below)))))
1756 (defun company-pseudo-tooltip-show (row column selection)
1757 (company-pseudo-tooltip-hide)
1762 (let* ((height (company--pseudo-tooltip-height))
1766 (setq row (+ row height -1)
1769 (let* ((nl (< (move-to-window-line row) row))
1771 (end (save-excursion
1772 (move-to-window-line (+ row (abs height)))
1774 (ov (make-overlay beg end))
1775 (args (list (mapcar 'company-untabify
1776 (company-buffer-lines beg end))
1779 (setq company-pseudo-tooltip-overlay ov)
1780 (overlay-put ov 'company-replacement-args args)
1781 (overlay-put ov 'company-before
1782 (apply 'company--replacement-string
1783 (company--create-lines selection (abs height))
1786 (overlay-put ov 'company-column column)
1787 (overlay-put ov 'company-height (abs height))
1788 (overlay-put ov 'window (selected-window))))))
1790 (defun company-pseudo-tooltip-show-at-point (pos)
1791 (let ((col-row (company--col-row pos)))
1793 (company-pseudo-tooltip-show (1+ (cdr col-row)) (car col-row)
1794 company-selection))))
1796 (defun company-pseudo-tooltip-edit (lines selection)
1797 (let ((column (overlay-get company-pseudo-tooltip-overlay 'company-column))
1798 (height (overlay-get company-pseudo-tooltip-overlay 'company-height)))
1799 (overlay-put company-pseudo-tooltip-overlay 'company-before
1800 (apply 'company--replacement-string
1801 (company--create-lines selection height)
1802 (overlay-get company-pseudo-tooltip-overlay
1803 'company-replacement-args)))))
1805 (defun company-pseudo-tooltip-hide ()
1806 (when company-pseudo-tooltip-overlay
1807 (delete-overlay company-pseudo-tooltip-overlay)
1808 (setq company-pseudo-tooltip-overlay nil)))
1810 (defun company-pseudo-tooltip-hide-temporarily ()
1811 (when (overlayp company-pseudo-tooltip-overlay)
1812 (overlay-put company-pseudo-tooltip-overlay 'invisible nil)
1813 (overlay-put company-pseudo-tooltip-overlay 'before-string nil)))
1815 (defun company-pseudo-tooltip-unhide ()
1816 (when company-pseudo-tooltip-overlay
1817 (overlay-put company-pseudo-tooltip-overlay 'invisible t)
1818 (overlay-put company-pseudo-tooltip-overlay 'before-string
1819 (overlay-get company-pseudo-tooltip-overlay 'company-before))
1820 (overlay-put company-pseudo-tooltip-overlay 'window (selected-window))))
1822 (defun company-pseudo-tooltip-frontend (command)
1823 "A `company-mode' front-end similar to a tool-tip but based on overlays."
1825 (pre-command (company-pseudo-tooltip-hide-temporarily))
1827 (let ((old-height (if (overlayp company-pseudo-tooltip-overlay)
1828 (overlay-get company-pseudo-tooltip-overlay
1831 (new-height (company--pseudo-tooltip-height)))
1832 (unless (and (>= (* old-height new-height) 0)
1833 (>= (abs old-height) (abs new-height)))
1835 (company-pseudo-tooltip-show-at-point (- (point)
1836 (length company-prefix)))))
1837 (company-pseudo-tooltip-unhide))
1838 (hide (company-pseudo-tooltip-hide)
1839 (setq company-tooltip-offset 0))
1840 (update (when (overlayp company-pseudo-tooltip-overlay)
1841 (company-pseudo-tooltip-edit company-candidates
1842 company-selection)))))
1844 (defun company-pseudo-tooltip-unless-just-one-frontend (command)
1845 "`company-pseudo-tooltip-frontend', but not shown for single candidates."
1846 (unless (and (eq command 'post-command)
1847 (not (cdr company-candidates)))
1848 (company-pseudo-tooltip-frontend command)))
1850 ;;; overlay ;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;
1852 (defvar company-preview-overlay nil)
1853 (make-variable-buffer-local 'company-preview-overlay)
1855 (defun company-preview-show-at-point (pos)
1856 (company-preview-hide)
1858 (setq company-preview-overlay (make-overlay pos pos))
1860 (let ((completion(nth company-selection company-candidates)))
1861 (setq completion (propertize completion 'face 'company-preview))
1862 (add-text-properties 0 (length company-common)
1863 '(face company-preview-common) completion)
1865 ;; Add search string
1866 (and company-search-string
1867 (string-match (regexp-quote company-search-string) completion)
1868 (add-text-properties (match-beginning 0)
1870 '(face company-preview-search)
1873 (setq completion (company-strip-prefix completion))
1875 (and (equal pos (point))
1876 (not (equal completion ""))
1877 (add-text-properties 0 1 '(cursor t) completion))
1879 (overlay-put company-preview-overlay 'after-string completion)
1880 (overlay-put company-preview-overlay 'window (selected-window))))
1882 (defun company-preview-hide ()
1883 (when company-preview-overlay
1884 (delete-overlay company-preview-overlay)
1885 (setq company-preview-overlay nil)))
1887 (defun company-preview-frontend (command)
1888 "A `company-mode' front-end showing the selection as if it had been inserted."
1890 (pre-command (company-preview-hide))
1891 (post-command (company-preview-show-at-point (point)))
1892 (hide (company-preview-hide))))
1894 (defun company-preview-if-just-one-frontend (command)
1895 "`company-preview-frontend', but only shown for single candidates."
1896 (unless (and (eq command 'post-command)
1897 (cdr company-candidates))
1898 (company-preview-frontend command)))
1900 ;;; echo ;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;
1902 (defvar company-echo-last-msg nil)
1903 (make-variable-buffer-local 'company-echo-last-msg)
1905 (defvar company-echo-timer nil)
1907 (defvar company-echo-delay .01)
1909 (defun company-echo-show (&optional getter)
1911 (setq company-echo-last-msg (funcall getter)))
1912 (let ((message-log-max nil))
1913 (if company-echo-last-msg
1914 (message "%s" company-echo-last-msg)
1917 (defsubst company-echo-show-soon (&optional getter)
1918 (when company-echo-timer
1919 (cancel-timer company-echo-timer))
1920 (setq company-echo-timer (run-with-timer company-echo-delay nil
1921 'company-echo-show getter)))
1923 (defun company-echo-format ()
1925 (let ((limit (window-width (minibuffer-window)))
1927 ;; Roll to selection.
1928 (candidates (nthcdr company-selection company-candidates))
1929 (i (if company-show-numbers company-selection 99999))
1933 (setq comp (company-reformat (pop candidates))
1934 len (+ len 1 (length comp)))
1938 (setq comp (propertize (format "%d: %s" i comp)
1939 'face 'company-echo))
1942 (add-text-properties 3 (+ 3 (length company-common))
1943 '(face company-echo-common) comp))
1944 (setq comp (propertize comp 'face 'company-echo))
1945 (add-text-properties 0 (length company-common)
1946 '(face company-echo-common) comp))
1948 (setq candidates nil)
1951 (mapconcat 'identity (nreverse msg) " ")))
1953 (defun company-echo-strip-common-format ()
1955 (let ((limit (window-width (minibuffer-window)))
1956 (len (+ (length company-prefix) 2))
1957 ;; Roll to selection.
1958 (candidates (nthcdr company-selection company-candidates))
1959 (i (if company-show-numbers company-selection 99999))
1963 (setq comp (company-strip-prefix (pop candidates))
1964 len (+ len 2 (length comp)))
1967 (setq comp (format "%s (%d)" comp i))
1971 (setq candidates nil)
1972 (push (propertize comp 'face 'company-echo) msg)))
1974 (concat (propertize company-prefix 'face 'company-echo-common) "{"
1975 (mapconcat 'identity (nreverse msg) ", ")
1978 (defun company-echo-hide ()
1979 (when company-echo-timer
1980 (cancel-timer company-echo-timer))
1981 (unless (equal company-echo-last-msg "")
1982 (setq company-echo-last-msg "")
1983 (company-echo-show)))
1985 (defun company-echo-frontend (command)
1986 "A `company-mode' front-end showing the candidates in the echo area."
1988 (pre-command (company-echo-show-soon))
1989 (post-command (company-echo-show-soon 'company-echo-format))
1990 (hide (company-echo-hide))))
1992 (defun company-echo-strip-common-frontend (command)
1993 "A `company-mode' front-end showing the candidates in the echo area."
1995 (pre-command (company-echo-show-soon))
1996 (post-command (company-echo-show-soon 'company-echo-strip-common-format))
1997 (hide (company-echo-hide))))
1999 (defun company-echo-metadata-frontend (command)
2000 "A `company-mode' front-end showing the documentation in the echo area."
2002 (pre-command (company-echo-show-soon))
2003 (post-command (company-echo-show-soon 'company-fetch-metadata))
2004 (hide (company-echo-hide))))
2006 ;; templates ;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;
2008 (autoload 'company-template-declare-template "company-template")
2011 ;;; company.el ends here