1 ;;; company.el --- Extensible inline text completion mechanism
3 ;; Copyright (C) 2009-2013 Free Software Foundation, Inc.
5 ;; Author: Nikolaj Schumacher
6 ;; Maintainer: Dmitry Gutov <dgutov@yandex.ru>
8 ;; Keywords: abbrev, convenience, matching
9 ;; URL: http://company-mode.github.com/
10 ;; Compatibility: GNU Emacs 22.x, GNU Emacs 23.x, GNU Emacs 24.x
12 ;; This file is part of GNU Emacs.
14 ;; GNU Emacs is free software: you can redistribute it and/or modify
15 ;; it under the terms of the GNU General Public License as published by
16 ;; the Free Software Foundation, either version 3 of the License, or
17 ;; (at your option) any later version.
19 ;; GNU Emacs is distributed in the hope that it will be useful,
20 ;; but WITHOUT ANY WARRANTY; without even the implied warranty of
21 ;; MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
22 ;; GNU General Public License for more details.
24 ;; You should have received a copy of the GNU General Public License
25 ;; along with GNU Emacs. If not, see <http://www.gnu.org/licenses/>.
29 ;; Company is a modular completion mechanism. Modules for retrieving completion
30 ;; candidates are called back-ends, modules for displaying them are front-ends.
32 ;; Company comes with many back-ends, e.g. `company-elisp'. These are
33 ;; distributed in separate files and can be used individually.
35 ;; Place company.el and the back-ends you want to use in a directory and add the
36 ;; following to your .emacs:
37 ;; (add-to-list 'load-path "/path/to/company")
38 ;; (autoload 'company-mode "company" nil t)
40 ;; Enable company-mode with M-x company-mode. For further information look at
41 ;; the documentation for `company-mode' (C-h f company-mode RET)
43 ;; If you want to start a specific back-end, call it interactively or use
44 ;; `company-begin-backend'. For example:
45 ;; M-x company-abbrev will prompt for and insert an abbrev.
47 ;; To write your own back-end, look at the documentation for `company-backends'.
48 ;; Here is a simple example completing "foo":
50 ;; (defun company-my-backend (command &optional arg &rest ignored)
52 ;; (prefix (when (looking-back "foo\\>")
54 ;; (candidates (list "foobar" "foobaz" "foobarbaz"))
55 ;; (meta (format "This value is named %s" arg))))
57 ;; Sometimes it is a good idea to mix several back-ends together, for example to
58 ;; enrich gtags with dabbrev-code results (to emulate local variables).
59 ;; To do this, add a list with both back-ends as an element in company-backends.
62 ;; When point is at the very end of the buffer, the pseudo-tooltip appears very
63 ;; wrong, unless company is allowed to temporarily insert a fake newline.
64 ;; This behavior is enabled by `company-end-of-buffer-workaround'.
69 ;; Switching between tag files now works correctly with `company-etags'.
70 ;; Clang completions now include macros and are case-sensitive.
71 ;; Added `company-capf': completion adapter using
72 ;; `completion-at-point-functions'. (Stefan Monnier)
73 ;; `company-elisp' has some improvements.
74 ;; Instead of `overrriding-terminal-local-map', we're now using
75 ;; `emulation-mode-map-alists' (experimental). This largely means that when
76 ;; the completion keymap is active, other minor modes' keymaps are still
77 ;; used, so, for example, it's not as easy to circumvent `paredit-mode'
78 ;; accidentally when it's enabled.
79 ;; Fixed two old tooltip annoyances.
80 ;; Some performance improvements.
81 ;; `company-clang' now shows meta information, too.
82 ;; Candidates from grouped back-ends are merged more conservatively: only
83 ;; back-ends that return the same prefix at point are used.
84 ;; Loading of `nxml', `semantic', `pymacs' and `ropemacs' is now deferred.
85 ;; `company-pysmell' is not used by default anymore.
86 ;; Across-the-board bugfixing.
89 ;; `company-ropemacs' now provides location and docs. (Fernando H. Silva)
90 ;; Added `company-with-candidate-inserted' macro.
91 ;; Added `company-clang' back-end.
92 ;; Added new mechanism for non-consecutive insertion.
93 ;; (So far only used by clang for ObjC.)
94 ;; The semantic back-end now shows meta information for local symbols.
95 ;; Added compatibility for CEDET in Emacs 23.2 and from CVS. (Oleg Andreev)
98 ;; Added `company-other-backend'.
99 ;; Idle completion no longer interrupts multi-key command input.
100 ;; Added `company-ropemacs' and `company-pysmell' back-ends.
102 ;; 2009-04-25 (0.4.2)
103 ;; In C modes . and -> now count towards `company-minimum-prefix-length'.
104 ;; Reverted default front-end back to `company-preview-if-just-one-frontend'.
105 ;; The pseudo tooltip will no longer be clipped at the right window edge.
106 ;; Added `company-tooltip-minimum'.
107 ;; Windows compatibility fixes.
109 ;; 2009-04-19 (0.4.1)
110 ;; Added `global-company-mode'.
111 ;; Performance enhancements.
112 ;; Added `company-eclim' back-end.
113 ;; Added safer workaround for Emacs `posn-col-row' bug.
116 ;; Automatic completion is now aborted if the prefix gets too short.
117 ;; Added option `company-dabbrev-time-limit'.
118 ;; `company-backends' now supports merging back-ends.
119 ;; Added back-end `company-dabbrev-code' for generic code.
120 ;; Fixed `company-begin-with'.
122 ;; 2009-04-15 (0.3.1)
123 ;; Added 'stop prefix to prevent dabbrev from completing inside of symbols.
124 ;; Fixed issues with tabbar-mode and line-spacing.
125 ;; Performance enhancements.
128 ;; Added `company-begin-commands' option.
129 ;; Added abbrev, tempo and Xcode back-ends.
130 ;; Back-ends are now interactive. You can start them with M-x backend-name.
131 ;; Added `company-begin-with' for starting company from elisp-code.
133 ;; Added `company-require-match' and `company-auto-complete' options.
135 ;; 2009-04-05 (0.2.1)
136 ;; Improved Emacs Lisp back-end behavior for local variables.
137 ;; Added `company-elisp-detect-function-context' option.
138 ;; The mouse can now be used for selection.
141 ;; Added `company-show-location'.
142 ;; Added etags back-end.
143 ;; Added work-around for end-of-buffer bug.
144 ;; Added `company-filter-candidates'.
145 ;; More local Lisp variables are now included in the candidates.
147 ;; 2009-03-21 (0.1.5)
148 ;; Fixed elisp documentation buffer always showing the same doc.
149 ;; Added `company-echo-strip-common-frontend'.
150 ;; Added `company-show-numbers' option and M-0 ... M-9 default bindings.
151 ;; Don't hide the echo message if it isn't shown.
158 (eval-when-compile (require 'cl))
160 (add-to-list 'debug-ignored-errors "^.* frontend cannot be used twice$")
161 (add-to-list 'debug-ignored-errors "^Echo area cannot be used twice$")
162 (add-to-list 'debug-ignored-errors "^No \\(document\\|loc\\)ation available$")
163 (add-to-list 'debug-ignored-errors "^Company not ")
164 (add-to-list 'debug-ignored-errors "^No candidate number ")
165 (add-to-list 'debug-ignored-errors "^Cannot complete at point$")
166 (add-to-list 'debug-ignored-errors "^No other back-end$")
168 (defgroup company nil
169 "Extensible inline text completion mechanism"
174 (defface company-tooltip
175 '((t :background "yellow"
176 :foreground "black"))
177 "Face used for the tool tip."
180 (defface company-tooltip-selection
181 '((default :inherit company-tooltip)
182 (((class color) (min-colors 88)) (:background "orange1"))
183 (t (:background "green")))
184 "Face used for the selection in the tool tip."
187 (defface company-tooltip-mouse
188 '((default :inherit highlight))
189 "Face used for the tool tip item under the mouse."
192 (defface company-tooltip-common
193 '((t :inherit company-tooltip
195 "Face used for the common completion in the tool tip."
198 (defface company-tooltip-common-selection
199 '((t :inherit company-tooltip-selection
201 "Face used for the selected common completion in the tool tip."
204 (defface company-preview
205 '((t :background "blue4"
206 :foreground "wheat"))
207 "Face used for the completion preview."
210 (defface company-preview-common
211 '((t :inherit company-preview
213 "Face used for the common part of the completion preview."
216 (defface company-preview-search
217 '((t :inherit company-preview
218 :background "blue1"))
219 "Face used for the search string in the completion preview."
222 (defface company-echo nil
223 "Face used for completions in the echo area."
226 (defface company-echo-common
227 '((((background dark)) (:foreground "firebrick1"))
228 (((background light)) (:background "firebrick4")))
229 "Face used for the common part of completions in the echo area."
232 (defun company-frontends-set (variable value)
234 (let ((remainder value))
235 (setcdr remainder (delq (car remainder) (cdr remainder))))
236 (and (memq 'company-pseudo-tooltip-unless-just-one-frontend value)
237 (memq 'company-pseudo-tooltip-frontend value)
238 (error "Pseudo tooltip frontend cannot be used twice"))
239 (and (memq 'company-preview-if-just-one-frontend value)
240 (memq 'company-preview-frontend value)
241 (error "Preview frontend cannot be used twice"))
242 (and (memq 'company-echo value)
243 (memq 'company-echo-metadata-frontend value)
244 (error "Echo area cannot be used twice"))
245 ;; preview must come last
246 (dolist (f '(company-preview-if-just-one-frontend company-preview-frontend))
248 (setq value (append (delq f value) (list f)))))
249 (set variable value))
251 (defcustom company-frontends '(company-pseudo-tooltip-unless-just-one-frontend
252 company-preview-if-just-one-frontend
253 company-echo-metadata-frontend)
254 "The list of active front-ends (visualizations).
255 Each front-end is a function that takes one argument. It is called with
256 one of the following arguments:
258 'show: When the visualization should start.
260 'hide: When the visualization should end.
262 'update: When the data has been updated.
264 'pre-command: Before every command that is executed while the
265 visualization is active.
267 'post-command: After every command that is executed while the
268 visualization is active.
270 The visualized data is stored in `company-prefix', `company-candidates',
271 `company-common', `company-selection', `company-point' and
272 `company-search-string'."
273 :set 'company-frontends-set
275 :type '(repeat (choice (const :tag "echo" company-echo-frontend)
276 (const :tag "echo, strip common"
277 company-echo-strip-common-frontend)
278 (const :tag "show echo meta-data in echo"
279 company-echo-metadata-frontend)
280 (const :tag "pseudo tooltip"
281 company-pseudo-tooltip-frontend)
282 (const :tag "pseudo tooltip, multiple only"
283 company-pseudo-tooltip-unless-just-one-frontend)
284 (const :tag "preview" company-preview-frontend)
285 (const :tag "preview, unique only"
286 company-preview-if-just-one-frontend)
287 (function :tag "custom function" nil))))
289 (defcustom company-tooltip-limit 10
290 "The maximum number of candidates in the tool tip"
294 (defcustom company-tooltip-minimum 6
295 "The minimum height of the tool tip.
296 If this many lines are not available, prefer to display the tooltip above."
300 (defvar company-safe-backends
301 '((company-abbrev . "Abbrev")
302 (company-clang . "clang")
303 (company-css . "CSS")
304 (company-dabbrev . "dabbrev for plain text")
305 (company-dabbrev-code . "dabbrev for code")
306 (company-eclim . "eclim (an Eclipse interace)")
307 (company-elisp . "Emacs Lisp")
308 (company-etags . "etags")
309 (company-files . "Files")
310 (company-gtags . "GNU Global")
311 (company-ispell . "ispell")
312 (company-keywords . "Programming language keywords")
313 (company-nxml . "nxml")
314 (company-oddmuse . "Oddmuse")
315 (company-pysmell . "PySmell")
316 (company-ropemacs . "ropemacs")
317 (company-semantic . "CEDET Semantic")
318 (company-tempo . "Tempo templates")
319 (company-xcode . "Xcode")))
320 (put 'company-safe-backends 'risky-local-variable t)
322 (defun company-safe-backends-p (backends)
323 (and (consp backends)
324 (not (dolist (backend backends)
325 (unless (if (consp backend)
326 (company-safe-backends-p backend)
327 (assq backend company-safe-backends))
330 (defun company-capf (command &optional arg &rest args)
331 "`company-mode' back-end using `completion-at-point-functions'.
332 Requires Emacs 24.1 or newer."
333 (interactive (list 'interactive))
335 (interactive (company-begin-backend 'company-capf))
337 (let ((res (run-hook-wrapped 'completion-at-point-functions
338 ;; Ignore misbehaving functions.
339 #'completion--capf-wrapper 'optimist)))
341 (if (> (nth 2 res) (point))
343 (buffer-substring-no-properties (nth 1 res) (point))))))
345 (let ((res (run-hook-wrapped 'completion-at-point-functions
346 ;; Ignore misbehaving functions.
347 #'completion--capf-wrapper 'optimist)))
349 (all-completions arg (nth 3 res)
350 (plist-get (nthcdr 4 res) :predicate)))))))
352 (defcustom company-backends '(company-elisp company-nxml company-css
353 company-clang company-semantic company-eclim
354 company-xcode company-ropemacs
355 (company-gtags company-etags company-dabbrev-code
357 company-oddmuse company-files company-dabbrev)
358 "The list of active back-ends (completion engines).
359 Each list elements can itself be a list of back-ends. In that case their
360 completions are merged. Otherwise only the first matching back-end returns
363 `company-begin-backend' can be used to start a specific back-end,
364 `company-other-backend' will skip to the next matching back-end in the list.
366 Each back-end is a function that takes a variable number of arguments.
367 The first argument is the command requested from the back-end. It is one
370 `prefix': The back-end should return the text to be completed. It must be
371 text immediately before `point'. Returning nil passes control to the next
372 back-end. The function should return 'stop if it should complete but cannot
373 \(e.g. if it is in the middle of a string\). If the returned value is only
374 part of the prefix (e.g. the part after \"->\" in C), the back-end may return a
375 cons of prefix and prefix length, which is then used in the
376 `company-minimum-prefix-length' test.
378 `candidates': The second argument is the prefix to be completed. The
379 return value should be a list of candidates that start with the prefix.
383 `sorted': The back-end may return t here to indicate that the candidates
384 are sorted and will not need to be sorted again.
386 `duplicates': If non-nil, company will take care of removing duplicates
389 `no-cache': Usually company doesn't ask for candidates again as completion
390 progresses, unless the back-end returns t for this command. The second
391 argument is the latest prefix.
393 `meta': The second argument is a completion candidate. The back-end should
394 return a (short) documentation string for it.
396 `doc-buffer': The second argument is a completion candidate.
397 The back-end should create a buffer (preferably with `company-doc-buffer'),
398 fill it with documentation and return it.
400 `location': The second argument is a completion candidate. The back-end can
401 return the cons of buffer and buffer location, or of file and line
402 number where the completion candidate was defined.
404 `require-match': If this value is t, the user is not allowed to enter anything
405 not offering as a candidate. Use with care! The default value nil gives the
406 user that choice with `company-require-match'. Return value 'never overrides
407 that option the other way around.
409 The back-end should return nil for all commands it does not support or
410 does not know about. It should also be callable interactively and use
411 `company-begin-backend' to start itself in that case."
416 ,@(mapcar (lambda (b) `(const :tag ,(cdr b) ,(car b)))
417 company-safe-backends)
418 (symbol :tag "User defined")
419 (repeat :tag "Merged Back-ends"
420 (choice :tag "Back-end"
421 ,@(mapcar (lambda (b)
422 `(const :tag ,(cdr b) ,(car b)))
423 company-safe-backends)
424 (symbol :tag "User defined"))))))
426 (put 'company-backends 'safe-local-variable 'company-safe-backends-p)
428 (defcustom company-completion-started-hook nil
429 "Hook run when company starts completing.
430 The hook is called with one argument that is non-nil if the completion was
435 (defcustom company-completion-cancelled-hook nil
436 "Hook run when company cancels completing.
437 The hook is called with one argument that is non-nil if the completion was
442 (defcustom company-completion-finished-hook nil
443 "Hook run when company successfully completes.
444 The hook is called with the selected candidate as an argument."
448 (defcustom company-minimum-prefix-length 3
449 "The minimum prefix length for automatic completion."
451 :type '(integer :tag "prefix length"))
453 (defcustom company-require-match 'company-explicit-action-p
454 "If enabled, disallow non-matching input.
455 This can be a function do determine if a match is required.
457 This can be overridden by the back-end, if it returns t or 'never to
458 'require-match. `company-auto-complete' also takes precedence over this."
460 :type '(choice (const :tag "Off" nil)
461 (function :tag "Predicate function")
462 (const :tag "On, if user interaction took place"
463 'company-explicit-action-p)
464 (const :tag "On" t)))
466 (defcustom company-auto-complete 'company-explicit-action-p
467 "Determines when to auto-complete.
468 If this is enabled, all characters from `company-auto-complete-chars' complete
469 the selected completion. This can also be a function."
471 :type '(choice (const :tag "Off" nil)
472 (function :tag "Predicate function")
473 (const :tag "On, if user interaction took place"
474 'company-explicit-action-p)
475 (const :tag "On" t)))
477 (defcustom company-auto-complete-chars '(?\ ?\( ?\) ?. ?\" ?$ ?\' ?< ?| ?!)
478 "Determines which characters trigger an automatic completion.
479 See `company-auto-complete'. If this is a string, each string character causes
480 completion. If it is a list of syntax description characters (see
481 `modify-syntax-entry'), all characters with that syntax auto-complete.
483 This can also be a function, which is called with the new input and should
484 return non-nil if company should auto-complete.
486 A character that is part of a valid candidate never starts auto-completion."
488 :type '(choice (string :tag "Characters")
490 (const :tag "Whitespace" ?\ )
491 (const :tag "Symbol" ?_)
492 (const :tag "Opening parentheses" ?\()
493 (const :tag "Closing parentheses" ?\))
494 (const :tag "Word constituent" ?w)
495 (const :tag "Punctuation." ?.)
496 (const :tag "String quote." ?\")
497 (const :tag "Paired delimiter." ?$)
498 (const :tag "Expression quote or prefix operator." ?\')
499 (const :tag "Comment starter." ?<)
500 (const :tag "Comment ender." ?>)
501 (const :tag "Character-quote." ?/)
502 (const :tag "Generic string fence." ?|)
503 (const :tag "Generic comment fence." ?!))
504 (function :tag "Predicate function")))
506 (defcustom company-idle-delay .7
507 "The idle delay in seconds until automatic completions starts.
508 A value of nil means never complete automatically, t means complete
509 immediately when a prefix of `company-minimum-prefix-length' is reached."
511 :type '(choice (const :tag "never (nil)" nil)
512 (const :tag "immediate (t)" t)
513 (number :tag "seconds")))
515 (defcustom company-begin-commands t
516 "A list of commands following which company will start completing.
517 If this is t, it will complete after any command. See `company-idle-delay'.
519 Alternatively any command with a non-nil 'company-begin property is treated as
520 if it was on this list."
522 :type '(choice (const :tag "Any command" t)
523 (const :tag "Self insert command" '(self-insert-command))
524 (repeat :tag "Commands" function)))
526 (defcustom company-show-numbers nil
527 "If enabled, show quick-access numbers for the first ten candidates."
529 :type '(choice (const :tag "off" nil)
530 (const :tag "on" t)))
532 (defvar company-end-of-buffer-workaround t
533 "Work around a visualization bug when completing at the end of the buffer.
534 The work-around consists of adding a newline.")
536 ;;; mode ;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;
538 (defvar company-mode-map (make-sparse-keymap)
539 "Keymap used by `company-mode'.")
541 (defvar company-active-map
542 (let ((keymap (make-sparse-keymap)))
543 (define-key keymap "\e\e\e" 'company-abort)
544 (define-key keymap "\C-g" 'company-abort)
545 (define-key keymap (kbd "M-n") 'company-select-next)
546 (define-key keymap (kbd "M-p") 'company-select-previous)
547 (define-key keymap (kbd "<down>") 'company-select-next)
548 (define-key keymap (kbd "<up>") 'company-select-previous)
549 (define-key keymap [down-mouse-1] 'ignore)
550 (define-key keymap [down-mouse-3] 'ignore)
551 (define-key keymap [mouse-1] 'company-complete-mouse)
552 (define-key keymap [mouse-3] 'company-select-mouse)
553 (define-key keymap [up-mouse-1] 'ignore)
554 (define-key keymap [up-mouse-3] 'ignore)
555 (define-key keymap [return] 'company-complete-selection)
556 (define-key keymap [tab] 'company-complete-common)
557 (define-key keymap (kbd "<f1>") 'company-show-doc-buffer)
558 (define-key keymap "\C-w" 'company-show-location)
559 (define-key keymap "\C-s" 'company-search-candidates)
560 (define-key keymap "\C-\M-s" 'company-filter-candidates)
562 (define-key keymap (vector (+ (aref (kbd "M-0") 0) i))
563 `(lambda () (interactive) (company-complete-number ,i))))
566 "Keymap that is enabled during an active completion.")
568 (defvar company--disabled-backends nil)
570 (defun company-init-backend (backend)
571 (and (symbolp backend)
572 (not (fboundp backend))
573 (ignore-errors (require backend nil t)))
575 (if (or (symbolp backend)
579 (funcall backend 'init)
580 (put backend 'company-init t))
582 (put backend 'company-init 'failed)
583 (unless (memq backend company--disabled-backends)
584 (message "Company back-end '%s' could not be initialized:\n%s"
585 backend (error-message-string err)))
586 (pushnew backend company--disabled-backends)
588 (mapc 'company-init-backend backend)))
590 (defvar company-default-lighter " company")
592 (defvar company-lighter company-default-lighter)
593 (make-variable-buffer-local 'company-lighter)
596 (define-minor-mode company-mode
597 "\"complete anything\"; is an in-buffer completion framework.
598 Completion starts automatically, depending on the values
599 `company-idle-delay' and `company-minimum-prefix-length'.
601 Completion can be controlled with the commands:
602 `company-complete-common', `company-complete-selection', `company-complete',
603 `company-select-next', `company-select-previous'. If these commands are
604 called before `company-idle-delay', completion will also start.
606 Completions can be searched with `company-search-candidates' or
607 `company-filter-candidates'. These can be used while completion is
610 The completion data is retrieved using `company-backends' and displayed using
611 `company-frontends'. If you want to start a specific back-end, call it
612 interactively or use `company-begin-backend'.
614 regular keymap (`company-mode-map'):
617 keymap during active completions (`company-active-map'):
619 \\{company-active-map}"
620 nil company-lighter company-mode-map
623 (add-hook 'pre-command-hook 'company-pre-command nil t)
624 (add-hook 'post-command-hook 'company-post-command nil t)
625 (mapc 'company-init-backend company-backends))
626 (remove-hook 'pre-command-hook 'company-pre-command t)
627 (remove-hook 'post-command-hook 'company-post-command t)
629 (kill-local-variable 'company-point)))
631 (define-globalized-minor-mode global-company-mode company-mode
632 (lambda () (unless (or noninteractive (eq (aref (buffer-name) 0) ?\s))
635 (defsubst company-assert-enabled ()
637 (company-uninstall-map)
638 (error "Company not enabled")))
640 ;;; keymaps ;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;
642 (defvar company-my-keymap nil)
643 (make-variable-buffer-local 'company-my-keymap)
645 (defvar company-emulation-alist '((t . nil)))
647 (defsubst company-enable-overriding-keymap (keymap)
648 (company-uninstall-map)
649 (setq company-my-keymap keymap))
651 (defun company-ensure-emulation-alist ()
652 (unless (eq 'company-emulation-alist (car emulation-mode-map-alists))
653 (setq emulation-mode-map-alists
654 (cons 'company-emulation-alist
655 (delq 'company-emulation-alist emulation-mode-map-alists)))))
657 (defun company-install-map ()
658 (unless (or (cdar company-emulation-alist)
659 (null company-my-keymap))
660 (setf (cdar company-emulation-alist) company-my-keymap)))
662 (defun company-uninstall-map ()
663 (setf (cdar company-emulation-alist) nil))
666 ;; Emacs calculates the active keymaps before reading the event. That means we
667 ;; cannot change the keymap from a timer. So we send a bogus command.
668 (defun company-ignore ()
670 (setq this-command last-command))
672 (global-set-key '[31415926] 'company-ignore)
674 (defun company-input-noop ()
675 (push 31415926 unread-command-events))
678 ;; posn-col-row is incorrect in older Emacsen when line-spacing is set
679 (defun company--col-row (&optional pos)
680 (let ((posn (posn-at-point pos)))
681 (cons (car (posn-col-row posn)) (cdr (posn-actual-col-row posn)))))
683 (defsubst company--column (&optional pos)
684 (car (posn-col-row (posn-at-point pos))))
686 (defsubst company--row (&optional pos)
687 (cdr (posn-actual-col-row (posn-at-point pos))))
689 ;;; backends ;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;
691 (defun company-grab (regexp &optional expression limit)
692 (when (looking-back regexp limit)
693 (or (match-string-no-properties (or expression 0)) "")))
695 (defun company-grab-line (regexp &optional expression)
696 (company-grab regexp expression (point-at-bol)))
698 (defun company-grab-symbol ()
699 (if (looking-at "\\_>")
700 (buffer-substring (point) (save-excursion (skip-syntax-backward "w_")
702 (unless (and (char-after) (memq (char-syntax (char-after)) '(?w ?_)))
705 (defun company-grab-word ()
706 (if (looking-at "\\>")
707 (buffer-substring (point) (save-excursion (skip-syntax-backward "w")
709 (unless (and (char-after) (eq (char-syntax (char-after)) ?w))
712 (defun company-in-string-or-comment ()
713 (let ((ppss (syntax-ppss)))
714 (or (car (setq ppss (nthcdr 3 ppss)))
715 (car (setq ppss (cdr ppss)))
718 (if (fboundp 'locate-dominating-file)
719 (defalias 'company-locate-dominating-file 'locate-dominating-file)
720 (defun company-locate-dominating-file (file name)
722 (let ((dir (file-name-directory file))
724 (while (not (equal dir prev-dir))
725 (when (file-exists-p (expand-file-name name dir))
728 dir (file-name-directory (directory-file-name dir))))))))
730 (defun company-call-backend (&rest args)
731 (if (functionp company-backend)
732 (apply company-backend args)
733 (apply 'company--multi-backend-adapter company-backend args)))
735 (defun company--multi-backend-adapter (backends command &rest args)
736 (let ((backends (remove-if (lambda (b) (eq 'failed (get b 'company-init)))
740 (loop for backend in backends
741 when (equal (funcall backend 'prefix)
743 nconc (apply backend 'candidates args)))
748 (dolist (backend backends)
749 (when (setq value (apply backend command args))
750 (return value))))))))
752 ;;; completion mechanism ;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;
754 (defvar company-backend nil)
755 (make-variable-buffer-local 'company-backend)
757 (defvar company-prefix nil)
758 (make-variable-buffer-local 'company-prefix)
760 (defvar company-candidates nil)
761 (make-variable-buffer-local 'company-candidates)
763 (defvar company-candidates-length nil)
764 (make-variable-buffer-local 'company-candidates-length)
766 (defvar company-candidates-cache nil)
767 (make-variable-buffer-local 'company-candidates-cache)
769 (defvar company-candidates-predicate nil)
770 (make-variable-buffer-local 'company-candidates-predicate)
772 (defvar company-common nil)
773 (make-variable-buffer-local 'company-common)
775 (defvar company-selection 0)
776 (make-variable-buffer-local 'company-selection)
778 (defvar company-selection-changed nil)
779 (make-variable-buffer-local 'company-selection-changed)
781 (defvar company--explicit-action nil
782 "Non-nil, if explicit completion took place.")
783 (make-variable-buffer-local 'company--explicit-action)
785 (defvar company--point-max nil)
786 (make-variable-buffer-local 'company--point-max)
788 (defvar company-point nil)
789 (make-variable-buffer-local 'company-point)
791 (defvar company-timer nil)
793 (defvar company-added-newline nil)
794 (make-variable-buffer-local 'company-added-newline)
796 (defsubst company-strip-prefix (str)
797 (substring str (length company-prefix)))
799 (defmacro company-with-candidate-inserted (candidate &rest body)
800 "Evaluate BODY with CANDIDATE temporarily inserted.
801 This is a tool for back-ends that need candidates inserted before they
802 can retrieve meta-data for them."
804 `(let ((inhibit-modification-hooks t)
805 (inhibit-point-motion-hooks t)
806 (modified-p (buffer-modified-p)))
807 (insert (company-strip-prefix ,candidate))
810 (delete-region company-point (point)))))
812 (defun company-explicit-action-p ()
813 "Return whether explicit completion action was taken by the user."
814 (or company--explicit-action
815 company-selection-changed))
817 (defsubst company-reformat (candidate)
818 ;; company-ispell needs this, because the results are always lower-case
819 ;; It's mory efficient to fix it only when they are displayed.
820 (concat company-prefix (substring candidate (length company-prefix))))
822 (defun company--should-complete ()
823 (and (not (or buffer-read-only overriding-terminal-local-map
826 ;; Check if in the middle of entering a key combination.
827 (or (equal (this-command-keys-vector) [])
828 (not (keymapp (key-binding (this-command-keys-vector)))))
829 (eq company-idle-delay t)
830 (or (eq t company-begin-commands)
831 (memq this-command company-begin-commands)
832 (and (symbolp this-command) (get this-command 'company-begin)))
833 (not (and transient-mark-mode mark-active))))
835 (defsubst company-call-frontends (command)
836 (dolist (frontend company-frontends)
838 (funcall frontend command)
839 (error (error "Company: Front-end %s error \"%s\" on command %s"
840 frontend (error-message-string err) command)))))
842 (defsubst company-set-selection (selection &optional force-update)
843 (setq selection (max 0 (min (1- company-candidates-length) selection)))
844 (when (or force-update (not (equal selection company-selection)))
845 (setq company-selection selection
846 company-selection-changed t)
847 (company-call-frontends 'update)))
849 (defun company-apply-predicate (candidates predicate)
851 (dolist (c candidates)
852 (when (funcall predicate c)
856 (defun company-update-candidates (candidates)
857 (setq company-candidates-length (length candidates))
858 (if (> company-selection 0)
859 ;; Try to restore the selection
860 (let ((selected (nth company-selection company-candidates)))
861 (setq company-selection 0
862 company-candidates candidates)
864 (while (and candidates (string< (pop candidates) selected))
865 (incf company-selection))
867 ;; Make sure selection isn't out of bounds.
868 (setq company-selection (min (1- company-candidates-length)
869 company-selection)))))
870 (setq company-selection 0
871 company-candidates candidates))
873 (push (cons company-prefix company-candidates) company-candidates-cache)
875 (let ((completion-ignore-case (company-call-backend 'ignore-case)))
876 (setq company-common (try-completion company-prefix company-candidates)))
877 (when (eq company-common t)
878 (setq company-candidates nil)))
880 (defun company-calculate-candidates (prefix)
881 (let ((candidates (cdr (assoc prefix company-candidates-cache)))
882 (ignore-case (company-call-backend 'ignore-case)))
884 (when company-candidates-cache
885 (let ((len (length prefix))
886 (completion-ignore-case ignore-case)
888 (dotimes (i (1+ len))
889 (when (setq prev (cdr (assoc (substring prefix 0 (- len i))
890 company-candidates-cache)))
891 (setq candidates (all-completions prefix prev))
893 ;; no cache match, call back-end
895 (setq candidates (company-call-backend 'candidates prefix))
896 (when company-candidates-predicate
898 (company-apply-predicate candidates
899 company-candidates-predicate)))
900 (unless (company-call-backend 'sorted)
901 (setq candidates (sort candidates 'string<)))
902 (when (company-call-backend 'duplicates)
904 (let ((c2 candidates))
906 (setcdr c2 (progn (while (equal (pop c2) (car c2)))
910 (not (eq t (compare-strings (car candidates) nil nil
911 prefix nil nil ignore-case)))))
912 ;; Don't start when already completed and unique.
914 ;; Not the right place? maybe when setting?
915 (and company-candidates t))))
917 (defun company-idle-begin (buf win tick pos)
919 (eq buf (current-buffer))
920 (eq win (selected-window))
921 (eq tick (buffer-chars-modified-tick))
923 (not company-candidates)
924 (not (equal (point) company-point))
925 (let ((company-idle-delay t)
926 (company-begin-commands t))
928 (when company-candidates
930 (company-post-command)))))
932 (defun company-auto-begin ()
933 (company-assert-enabled)
935 (not company-candidates)
936 (let ((company-idle-delay t)
937 (company-minimum-prefix-length 0)
938 (company-begin-commands t))
940 ;; Return non-nil if active.
943 (defun company-manual-begin ()
945 (setq company--explicit-action t)
946 (company-auto-begin))
948 (defun company-other-backend (&optional backward)
949 (interactive (list current-prefix-arg))
950 (company-assert-enabled)
952 (let* ((after (cdr (member company-backend company-backends)))
953 (before (cdr (member company-backend (reverse company-backends))))
955 (append before (reverse after))
956 (append after (reverse before)))))
958 (dolist (backend next)
959 (when (ignore-errors (company-begin-backend backend))
961 (company-manual-begin))
962 (unless company-candidates
963 (error "No other back-end")))
965 (defun company-require-match-p ()
966 (let ((backend-value (company-call-backend 'require-match)))
967 (or (eq backend-value t)
968 (and (if (functionp company-require-match)
969 (funcall company-require-match)
970 (eq company-require-match t))
971 (not (eq backend-value 'never))))))
973 (defun company-punctuation-p (input)
974 "Return non-nil, if input starts with punctuation or parentheses."
975 (memq (char-syntax (string-to-char input)) '(?. ?\( ?\))))
977 (defun company-auto-complete-p (input)
978 "Return non-nil, if input starts with punctuation or parentheses."
979 (and (if (functionp company-auto-complete)
980 (funcall company-auto-complete)
981 company-auto-complete)
982 (if (functionp company-auto-complete-chars)
983 (funcall company-auto-complete-chars input)
984 (if (consp company-auto-complete-chars)
985 (memq (char-syntax (string-to-char input))
986 company-auto-complete-chars)
987 (string-match (substring input 0 1) company-auto-complete-chars)))))
989 (defun company--incremental-p ()
990 (and (> (point) company-point)
991 (> (point-max) company--point-max)
992 (not (eq this-command 'backward-delete-char-untabify))
993 (equal (buffer-substring (- company-point (length company-prefix))
997 (defsubst company--string-incremental-p (old-prefix new-prefix)
998 (and (> (length new-prefix) (length old-prefix))
999 (equal old-prefix (substring new-prefix 0 (length old-prefix)))))
1001 (defun company--continue-failed (new-prefix)
1002 (when (company--incremental-p)
1003 (let ((input (buffer-substring-no-properties (point) company-point)))
1005 ((company-auto-complete-p input)
1008 (goto-char company-point)
1009 (company-complete-selection)
1011 ((and (company--string-incremental-p company-prefix new-prefix)
1012 (company-require-match-p))
1013 ;; wrong incremental input, but required match
1014 (backward-delete-char (length input))
1016 (message "Matching input is required")
1018 ((equal company-prefix (car company-candidates))
1019 ;; last input was actually success
1020 (company-cancel company-prefix)
1023 (defun company--good-prefix-p (prefix)
1024 (and (or (company-explicit-action-p)
1025 (>= (or (cdr-safe prefix) (length prefix))
1026 company-minimum-prefix-length))
1027 (stringp (or (car-safe prefix) prefix))))
1029 (defun company--continue ()
1030 (when (company-call-backend 'no-cache company-prefix)
1031 ;; Don't complete existing candidates, fetch new ones.
1032 (setq company-candidates-cache nil))
1033 (let* ((new-prefix (company-call-backend 'prefix))
1034 (c (when (and (company--good-prefix-p new-prefix)
1035 (setq new-prefix (or (car-safe new-prefix) new-prefix))
1036 (= (- (point) (length new-prefix))
1037 (- company-point (length company-prefix))))
1038 (setq new-prefix (or (car-safe new-prefix) new-prefix))
1039 (company-calculate-candidates new-prefix))))
1042 ;; t means complete/unique.
1043 (company-cancel new-prefix)
1046 ;; incremental match
1047 (setq company-prefix new-prefix)
1048 (company-update-candidates c)
1050 (t (company--continue-failed new-prefix)))
1053 (defun company--begin-new ()
1055 (dolist (backend (if company-backend
1056 ;; prefer manual override
1057 (list company-backend)
1060 (if (or (symbolp backend)
1061 (functionp backend))
1062 (when (or (not (symbolp backend))
1063 (eq t (get backend 'company-init))
1064 (unless (get backend 'company-init)
1065 (company-init-backend backend)))
1066 (funcall backend 'prefix))
1067 (company--multi-backend-adapter backend 'prefix)))
1069 (when (company--good-prefix-p prefix)
1070 (setq prefix (or (car-safe prefix) prefix)
1071 company-backend backend
1072 c (company-calculate-candidates prefix))
1073 ;; t means complete/unique. We don't start, so no hooks.
1075 (when company--explicit-action
1076 (message "No completion found"))
1077 (setq company-prefix prefix)
1078 (when (symbolp backend)
1079 (setq company-lighter (concat " " (symbol-name backend))))
1080 (company-update-candidates c)
1081 (run-hook-with-args 'company-completion-started-hook
1082 (company-explicit-action-p))
1083 (company-call-frontends 'show)))
1086 (defun company-begin ()
1087 (or (and company-candidates (company--continue))
1088 (and (company--should-complete) (company--begin-new)))
1089 (when company-candidates
1090 (when (and company-end-of-buffer-workaround (eobp))
1091 (save-excursion (insert "\n"))
1092 (setq company-added-newline (buffer-chars-modified-tick)))
1093 (setq company-point (point)
1094 company--point-max (point-max))
1095 (company-ensure-emulation-alist)
1096 (company-enable-overriding-keymap company-active-map)
1097 (company-call-frontends 'update)))
1099 (defun company-cancel (&optional result)
1100 (and company-added-newline
1101 (> (point-max) (point-min))
1102 (let ((tick (buffer-chars-modified-tick)))
1103 (delete-region (1- (point-max)) (point-max))
1104 (equal tick company-added-newline))
1105 ;; Only set unmodified when tick remained the same since insert.
1106 (set-buffer-modified-p nil))
1107 (when company-prefix
1108 (if (stringp result)
1110 (company-call-backend 'pre-completion result)
1111 (run-hook-with-args 'company-completion-finished-hook result)
1112 (company-call-backend 'post-completion result))
1113 (run-hook-with-args 'company-completion-cancelled-hook result)))
1114 (setq company-added-newline nil
1117 company-candidates nil
1118 company-candidates-length nil
1119 company-candidates-cache nil
1120 company-candidates-predicate nil
1123 company-selection-changed nil
1124 company--explicit-action nil
1125 company-lighter company-default-lighter
1126 company--point-max nil
1129 (cancel-timer company-timer))
1130 (company-search-mode 0)
1131 (company-call-frontends 'hide)
1132 (company-enable-overriding-keymap nil))
1134 (defun company-abort ()
1137 ;; Don't start again, unless started manually.
1138 (setq company-point (point)))
1140 (defun company-finish (result)
1141 (insert (company-strip-prefix result))
1142 (company-cancel result)
1143 ;; Don't start again, unless started manually.
1144 (setq company-point (point)))
1146 (defsubst company-keep (command)
1147 (and (symbolp command) (get command 'company-keep)))
1149 (defun company-pre-command ()
1150 (unless (company-keep this-command)
1152 (when company-candidates
1153 (company-call-frontends 'pre-command))
1154 (error (message "Company: An error occurred in pre-command")
1155 (message "%s" (error-message-string err))
1158 (cancel-timer company-timer)
1159 (setq company-timer nil))
1160 (company-uninstall-map))
1162 (defun company-post-command ()
1163 (unless (company-keep this-command)
1166 (unless (equal (point) company-point)
1168 (if company-candidates
1169 (company-call-frontends 'post-command)
1170 (and (numberp company-idle-delay)
1171 (or (eq t company-begin-commands)
1172 (memq this-command company-begin-commands))
1174 (run-with-timer company-idle-delay nil
1176 (current-buffer) (selected-window)
1177 (buffer-chars-modified-tick) (point))))))
1178 (error (message "Company: An error occurred in post-command")
1179 (message "%s" (error-message-string err))
1181 (company-install-map))
1183 ;;; search ;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;
1185 (defvar company-search-string nil)
1186 (make-variable-buffer-local 'company-search-string)
1188 (defvar company-search-lighter " Search: \"\"")
1189 (make-variable-buffer-local 'company-search-lighter)
1191 (defvar company-search-old-map nil)
1192 (make-variable-buffer-local 'company-search-old-map)
1194 (defvar company-search-old-selection 0)
1195 (make-variable-buffer-local 'company-search-old-selection)
1197 (defun company-search (text lines)
1198 (let ((quoted (regexp-quote text))
1200 (dolist (line lines)
1201 (when (string-match quoted line (length company-prefix))
1205 (defun company-search-printing-char ()
1207 (company-search-assert-enabled)
1208 (setq company-search-string
1209 (concat (or company-search-string "") (string last-command-event))
1210 company-search-lighter (concat " Search: \"" company-search-string
1212 (let ((pos (company-search company-search-string
1213 (nthcdr company-selection company-candidates))))
1216 (company-set-selection (+ company-selection pos) t))))
1218 (defun company-search-repeat-forward ()
1219 "Repeat the incremental search in completion candidates forward."
1221 (company-search-assert-enabled)
1222 (let ((pos (company-search company-search-string
1223 (cdr (nthcdr company-selection
1224 company-candidates)))))
1227 (company-set-selection (+ company-selection pos 1) t))))
1229 (defun company-search-repeat-backward ()
1230 "Repeat the incremental search in completion candidates backwards."
1232 (company-search-assert-enabled)
1233 (let ((pos (company-search company-search-string
1234 (nthcdr (- company-candidates-length
1236 (reverse company-candidates)))))
1239 (company-set-selection (- company-selection pos 1) t))))
1241 (defun company-create-match-predicate ()
1242 (setq company-candidates-predicate
1243 `(lambda (candidate)
1244 ,(if company-candidates-predicate
1245 `(and (string-match ,company-search-string candidate)
1246 (funcall ,company-candidates-predicate
1248 `(string-match ,company-search-string candidate))))
1249 (company-update-candidates
1250 (company-apply-predicate company-candidates company-candidates-predicate))
1251 ;; Invalidate cache.
1252 (setq company-candidates-cache (cons company-prefix company-candidates)))
1254 (defun company-filter-printing-char ()
1256 (company-search-assert-enabled)
1257 (company-search-printing-char)
1258 (company-create-match-predicate)
1259 (company-call-frontends 'update))
1261 (defun company-search-kill-others ()
1262 "Limit the completion candidates to the ones matching the search string."
1264 (company-search-assert-enabled)
1265 (company-create-match-predicate)
1266 (company-search-mode 0)
1267 (company-call-frontends 'update))
1269 (defun company-search-abort ()
1270 "Abort searching the completion candidates."
1272 (company-search-assert-enabled)
1273 (company-set-selection company-search-old-selection t)
1274 (company-search-mode 0))
1276 (defun company-search-other-char ()
1278 (company-search-assert-enabled)
1279 (company-search-mode 0)
1280 (when last-input-event
1281 (clear-this-command-keys t)
1282 (setq unread-command-events (list last-input-event))))
1284 (defvar company-search-map
1286 (keymap (make-keymap)))
1287 (if (fboundp 'max-char)
1288 (set-char-table-range (nth 1 keymap) (cons #x100 (max-char))
1289 'company-search-printing-char)
1291 ;; obselete in Emacs 23
1292 (let ((l (generic-character-list))
1293 (table (nth 1 keymap)))
1295 (set-char-table-default table (car l) 'company-search-printing-char)
1296 (setq l (cdr l))))))
1297 (define-key keymap [t] 'company-search-other-char)
1299 (define-key keymap (make-string 1 i) 'company-search-other-char)
1302 (define-key keymap (vector i) 'company-search-printing-char)
1304 (let ((meta-map (make-sparse-keymap)))
1305 (define-key keymap (char-to-string meta-prefix-char) meta-map)
1306 (define-key keymap [escape] meta-map))
1307 (define-key keymap (vector meta-prefix-char t) 'company-search-other-char)
1308 (define-key keymap "\e\e\e" 'company-search-other-char)
1309 (define-key keymap [escape escape escape] 'company-search-other-char)
1311 (define-key keymap "\C-g" 'company-search-abort)
1312 (define-key keymap "\C-s" 'company-search-repeat-forward)
1313 (define-key keymap "\C-r" 'company-search-repeat-backward)
1314 (define-key keymap "\C-o" 'company-search-kill-others)
1316 "Keymap used for incrementally searching the completion candidates.")
1318 (define-minor-mode company-search-mode
1319 "Search mode for completion candidates.
1320 Don't start this directly, use `company-search-candidates' or
1321 `company-filter-candidates'."
1322 nil company-search-lighter nil
1323 (if company-search-mode
1324 (if (company-manual-begin)
1326 (setq company-search-old-selection company-selection)
1327 (company-call-frontends 'update))
1328 (setq company-search-mode nil))
1329 (kill-local-variable 'company-search-string)
1330 (kill-local-variable 'company-search-lighter)
1331 (kill-local-variable 'company-search-old-selection)
1332 (company-enable-overriding-keymap company-active-map)))
1334 (defsubst company-search-assert-enabled ()
1335 (company-assert-enabled)
1336 (unless company-search-mode
1337 (company-uninstall-map)
1338 (error "Company not in search mode")))
1340 (defun company-search-candidates ()
1341 "Start searching the completion candidates incrementally.
1343 \\<company-search-map>Search can be controlled with the commands:
1344 - `company-search-repeat-forward' (\\[company-search-repeat-forward])
1345 - `company-search-repeat-backward' (\\[company-search-repeat-backward])
1346 - `company-search-abort' (\\[company-search-abort])
1348 Regular characters are appended to the search string.
1350 The command `company-search-kill-others' (\\[company-search-kill-others]) uses
1351 the search string to limit the completion candidates."
1353 (company-search-mode 1)
1354 (company-enable-overriding-keymap company-search-map))
1356 (defvar company-filter-map
1357 (let ((keymap (make-keymap)))
1358 (define-key keymap [remap company-search-printing-char]
1359 'company-filter-printing-char)
1360 (set-keymap-parent keymap company-search-map)
1362 "Keymap used for incrementally searching the completion candidates.")
1364 (defun company-filter-candidates ()
1365 "Start filtering the completion candidates incrementally.
1366 This works the same way as `company-search-candidates' immediately
1367 followed by `company-search-kill-others' after each input."
1369 (company-search-mode 1)
1370 (company-enable-overriding-keymap company-filter-map))
1372 ;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;
1374 (defun company-select-next ()
1375 "Select the next candidate in the list."
1377 (when (company-manual-begin)
1378 (company-set-selection (1+ company-selection))))
1380 (defun company-select-previous ()
1381 "Select the previous candidate in the list."
1383 (when (company-manual-begin)
1384 (company-set-selection (1- company-selection))))
1386 (defun company-select-mouse (event)
1387 "Select the candidate picked by the mouse."
1389 (when (nth 4 (event-start event))
1390 (company-set-selection (- (cdr (posn-actual-col-row (event-start event)))
1395 (defun company-complete-mouse (event)
1396 "Complete the candidate picked by the mouse."
1398 (when (company-select-mouse event)
1399 (company-complete-selection)))
1401 (defun company-complete-selection ()
1402 "Complete the selected candidate."
1404 (when (company-manual-begin)
1405 (company-finish (nth company-selection company-candidates))))
1407 (defun company-complete-common ()
1408 "Complete the common part of all candidates."
1410 (when (company-manual-begin)
1411 (if (and (not (cdr company-candidates))
1412 (equal company-common (car company-candidates)))
1413 (company-complete-selection)
1414 (insert (company-strip-prefix company-common)))))
1416 (defun company-complete ()
1417 "Complete the common part of all candidates or the current selection.
1418 The first time this is called, the common part is completed, the second time, or
1419 when the selection has been changed, the selected candidate is completed."
1421 (when (company-manual-begin)
1422 (if (or company-selection-changed
1423 (eq last-command 'company-complete-common))
1424 (call-interactively 'company-complete-selection)
1425 (call-interactively 'company-complete-common)
1426 (setq this-command 'company-complete-common))))
1428 (defun company-complete-number (n)
1429 "Complete the Nth candidate.
1430 To show the number next to the candidates in some back-ends, enable
1431 `company-show-numbers'."
1432 (when (company-manual-begin)
1433 (and (< n 1) (> n company-candidates-length)
1434 (error "No candidate number %d" n))
1436 (company-finish (nth n company-candidates))))
1438 ;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;
1440 (defconst company-space-strings-limit 100)
1442 (defconst company-space-strings
1444 (dotimes (i company-space-strings-limit)
1445 (push (make-string (- company-space-strings-limit 1 i) ?\ ) lst))
1446 (apply 'vector lst)))
1448 (defsubst company-space-string (len)
1449 (if (< len company-space-strings-limit)
1450 (aref company-space-strings len)
1451 (make-string len ?\ )))
1453 (defsubst company-safe-substring (str from &optional to)
1454 (if (> from (string-width str))
1458 (move-to-column from)
1459 (let ((beg (point)))
1463 (concat (buffer-substring beg (point))
1464 (let ((padding (- to (current-column))))
1466 (company-space-string padding)))))
1467 (buffer-substring beg (point-max)))))))
1469 ;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;
1471 (defvar company-last-metadata nil)
1472 (make-variable-buffer-local 'company-last-metadata)
1474 (defun company-fetch-metadata ()
1475 (let ((selected (nth company-selection company-candidates)))
1476 (unless (equal selected (car company-last-metadata))
1477 (setq company-last-metadata
1478 (cons selected (company-call-backend 'meta selected))))
1479 (cdr company-last-metadata)))
1481 (defun company-doc-buffer (&optional string)
1482 (with-current-buffer (get-buffer-create "*Company meta-data*")
1486 (defvar company--electric-commands
1487 '(scroll-other-window scroll-other-window-down)
1488 "List of Commands that won't break out of electric commands.")
1490 (defmacro company--electric-do (&rest body)
1491 (declare (indent 0) (debug t))
1492 `(when (company-manual-begin)
1493 (save-window-excursion
1494 (let ((height (window-height))
1495 (row (company--row))
1498 (and (< (window-height) height)
1499 (< (- (window-height) row 2) company-tooltip-limit)
1500 (recenter (- (window-height) row 2)))
1501 (while (memq (setq cmd (key-binding (vector (list (read-event)))))
1502 company--electric-commands)
1503 (call-interactively cmd))
1504 (when last-input-event
1505 (clear-this-command-keys t)
1506 (setq unread-command-events (list last-input-event)))))))
1508 (defun company-show-doc-buffer ()
1509 "Temporarily show a buffer with the complete documentation for the selection."
1511 (company--electric-do
1512 (let* ((selected (nth company-selection company-candidates))
1513 (doc-buffer (or (company-call-backend 'doc-buffer selected)
1514 (error "No documentation available"))))
1515 (with-current-buffer doc-buffer
1516 (goto-char (point-min)))
1517 (display-buffer doc-buffer t))))
1518 (put 'company-show-doc-buffer 'company-keep t)
1520 (defun company-show-location ()
1521 "Temporarily display a buffer showing the selected candidate in context."
1523 (company--electric-do
1524 (let* ((selected (nth company-selection company-candidates))
1525 (location (company-call-backend 'location selected))
1526 (pos (or (cdr location) (error "No location available")))
1527 (buffer (or (and (bufferp (car location)) (car location))
1528 (find-file-noselect (car location) t))))
1529 (with-selected-window (display-buffer buffer t)
1532 (if (bufferp (car location))
1534 (goto-char (point-min))
1535 (forward-line (1- pos))))
1536 (set-window-start nil (point))))))
1537 (put 'company-show-location 'company-keep t)
1539 ;;; package functions ;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;
1541 (defvar company-callback nil)
1542 (make-variable-buffer-local 'company-callback)
1544 (defvar company-begin-with-marker nil)
1545 (make-variable-buffer-local 'company-begin-with-marker)
1547 (defun company-remove-callback (&optional ignored)
1548 (remove-hook 'company-completion-finished-hook company-callback t)
1549 (remove-hook 'company-completion-cancelled-hook 'company-remove-callback t)
1550 (remove-hook 'company-completion-finished-hook 'company-remove-callback t)
1551 (when company-begin-with-marker
1552 (set-marker company-begin-with-marker nil)))
1554 (defun company-begin-backend (backend &optional callback)
1555 "Start a completion at point using BACKEND."
1556 (interactive (let ((val (completing-read "Company back-end: "
1558 'functionp nil "company-")))
1560 (list (intern val)))))
1561 (when (setq company-callback callback)
1562 (add-hook 'company-completion-finished-hook company-callback nil t))
1563 (add-hook 'company-completion-cancelled-hook 'company-remove-callback nil t)
1564 (add-hook 'company-completion-finished-hook 'company-remove-callback nil t)
1565 (setq company-backend backend)
1566 ;; Return non-nil if active.
1567 (or (company-manual-begin)
1568 (error "Cannot complete at point")))
1570 (defun company-begin-with (candidates
1571 &optional prefix-length require-match callback)
1572 "Start a completion at point.
1573 CANDIDATES is the list of candidates to use and PREFIX-LENGTH is the length of
1574 the prefix that already is in the buffer before point. It defaults to 0.
1576 CALLBACK is a function called with the selected result if the user successfully
1577 completes the input.
1580 \(company-begin-with '\(\"foo\" \"foobar\" \"foobarbaz\"\)\)"
1581 (setq company-begin-with-marker (copy-marker (point) t))
1582 (company-begin-backend
1583 `(lambda (command &optional arg &rest ignored)
1585 ((eq command 'prefix)
1586 (when (equal (point) (marker-position company-begin-with-marker))
1587 (buffer-substring ,(- (point) (or prefix-length 0)) (point))))
1588 ((eq command 'candidates)
1589 (all-completions arg ',candidates))
1590 ((eq command 'require-match)
1594 ;;; pseudo-tooltip ;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;
1596 (defvar company-pseudo-tooltip-overlay nil)
1597 (make-variable-buffer-local 'company-pseudo-tooltip-overlay)
1599 (defvar company-tooltip-offset 0)
1600 (make-variable-buffer-local 'company-tooltip-offset)
1602 (defun company-pseudo-tooltip-update-offset (selection num-lines limit)
1605 (setq company-tooltip-offset
1606 (max (min selection company-tooltip-offset)
1607 (- selection -1 limit)))
1609 (when (<= company-tooltip-offset 1)
1611 (setq company-tooltip-offset 0))
1613 (when (>= company-tooltip-offset (- num-lines limit 1))
1615 (when (= selection (1- num-lines))
1616 (decf company-tooltip-offset)
1617 (when (<= company-tooltip-offset 1)
1618 (setq company-tooltip-offset 0)
1625 (defsubst company-round-tab (arg)
1626 (* (/ (+ arg tab-width) tab-width) tab-width))
1628 (defun company-untabify (str)
1629 (let* ((pieces (split-string str "\t"))
1632 (setcar copy (company-safe-substring
1633 (car copy) 0 (company-round-tab (string-width (car copy)))))
1635 (apply 'concat pieces)))
1637 (defun company-fill-propertize (line width selected)
1638 (setq line (company-safe-substring line 0 width))
1639 (add-text-properties 0 width '(face company-tooltip
1640 mouse-face company-tooltip-mouse)
1642 (add-text-properties 0 (length company-common)
1643 '(face company-tooltip-common
1644 mouse-face company-tooltip-mouse)
1647 (if (and company-search-string
1648 (string-match (regexp-quote company-search-string) line
1649 (length company-prefix)))
1651 (add-text-properties (match-beginning 0) (match-end 0)
1652 '(face company-tooltip-selection)
1654 (when (< (match-beginning 0) (length company-common))
1655 (add-text-properties (match-beginning 0) (length company-common)
1656 '(face company-tooltip-common-selection)
1658 (add-text-properties 0 width '(face company-tooltip-selection
1659 mouse-face company-tooltip-selection)
1661 (add-text-properties 0 (length company-common)
1662 '(face company-tooltip-common-selection
1663 mouse-face company-tooltip-selection)
1669 (defun company-buffer-lines (beg end)
1672 (while (and (= 1 (vertical-motion 1))
1674 (push (buffer-substring beg (min end (1- (point)))) lines)
1676 (unless (eq beg end)
1677 (push (buffer-substring beg end) lines))
1680 (defsubst company-modify-line (old new offset)
1681 (concat (company-safe-substring old 0 offset)
1683 (company-safe-substring old (+ offset (length new)))))
1685 (defsubst company--length-limit (lst limit)
1686 (if (nthcdr limit lst)
1690 (defun company--replacement-string (lines old column nl &optional align-top)
1692 (let ((width (length (car lines))))
1693 (when (> width (- (window-width) column))
1694 (setq column (max 0 (- (window-width) width)))))
1698 ;; untouched lines first
1699 (dotimes (i (- (length old) (length lines)))
1700 (push (pop old) new)))
1701 ;; length into old lines.
1703 (push (company-modify-line (pop old) (pop lines) column) new))
1704 ;; Append whole new lines.
1706 (push (concat (company-space-string column) (pop lines)) new))
1708 (let ((str (concat (when nl "\n")
1709 (mapconcat 'identity (nreverse new) "\n")
1711 (font-lock-append-text-property 0 (length str) 'face 'default str)
1714 (defun company--create-lines (selection limit)
1716 (let ((len company-candidates-length)
1725 ;; Scroll to offset.
1726 (setq limit (company-pseudo-tooltip-update-offset selection len limit))
1728 (when (> company-tooltip-offset 0)
1729 (setq previous (format "...(%d)" company-tooltip-offset)))
1731 (setq remainder (- len limit company-tooltip-offset)
1732 remainder (when (> remainder 0)
1733 (setq remainder (format "...(%d)" remainder))))
1735 (decf selection company-tooltip-offset)
1736 (setq width (max (length previous) (length remainder))
1737 lines (nthcdr company-tooltip-offset company-candidates)
1742 (setq width (max (length (pop lines-copy)) width)))
1743 (setq width (min width (window-width)))
1745 (setq lines-copy lines)
1747 ;; number can make tooltip too long
1748 (when company-show-numbers
1749 (setq numbered company-tooltip-offset))
1752 (push (propertize (company-safe-substring previous 0 width)
1753 'face 'company-tooltip)
1757 (push (company-fill-propertize
1758 (if (>= numbered 10)
1759 (company-reformat (pop lines))
1762 (company-safe-substring (company-reformat (pop lines))
1765 width (equal i selection))
1769 (push (propertize (company-safe-substring remainder 0 width)
1770 'face 'company-tooltip)
1773 (setq lines (nreverse new))))
1777 (defsubst company--window-inner-height ()
1778 (let ((edges (window-inside-edges (selected-window))))
1779 (- (nth 3 edges) (nth 1 edges))))
1781 (defsubst company--pseudo-tooltip-height ()
1782 "Calculate the appropriate tooltip height.
1783 Returns a negative number if the tooltip should be displayed above point."
1784 (let* ((lines (company--row))
1785 (below (- (company--window-inner-height) 1 lines)))
1786 (if (and (< below (min company-tooltip-minimum company-candidates-length))
1788 (- (max 3 (min company-tooltip-limit lines)))
1789 (max 3 (min company-tooltip-limit below)))))
1791 (defun company-pseudo-tooltip-show (row column selection)
1792 (company-pseudo-tooltip-hide)
1797 (let* ((height (company--pseudo-tooltip-height))
1801 (setq row (+ row height -1)
1804 (let* ((nl (< (move-to-window-line row) row))
1806 (end (save-excursion
1807 (move-to-window-line (+ row (abs height)))
1809 (ov (make-overlay beg end))
1810 (args (list (mapcar 'company-untabify
1811 (company-buffer-lines beg end))
1814 (setq company-pseudo-tooltip-overlay ov)
1815 (overlay-put ov 'company-replacement-args args)
1816 (overlay-put ov 'company-before
1817 (apply 'company--replacement-string
1818 (company--create-lines selection (abs height))
1821 (overlay-put ov 'company-column column)
1822 (overlay-put ov 'company-height (abs height))
1823 (overlay-put ov 'window (selected-window))))))
1825 (defun company-pseudo-tooltip-show-at-point (pos)
1826 (let ((col-row (company--col-row pos)))
1828 (company-pseudo-tooltip-show (1+ (cdr col-row)) (car col-row)
1829 company-selection))))
1831 (defun company-pseudo-tooltip-edit (lines selection)
1832 (let ((column (overlay-get company-pseudo-tooltip-overlay 'company-column))
1833 (height (overlay-get company-pseudo-tooltip-overlay 'company-height)))
1834 (overlay-put company-pseudo-tooltip-overlay 'company-before
1835 (apply 'company--replacement-string
1836 (company--create-lines selection height)
1837 (overlay-get company-pseudo-tooltip-overlay
1838 'company-replacement-args)))))
1840 (defun company-pseudo-tooltip-hide ()
1841 (when company-pseudo-tooltip-overlay
1842 (delete-overlay company-pseudo-tooltip-overlay)
1843 (setq company-pseudo-tooltip-overlay nil)))
1845 (defun company-pseudo-tooltip-hide-temporarily ()
1846 (when (overlayp company-pseudo-tooltip-overlay)
1847 (overlay-put company-pseudo-tooltip-overlay 'invisible nil)
1848 (overlay-put company-pseudo-tooltip-overlay 'before-string nil)))
1850 (defun company-pseudo-tooltip-unhide ()
1851 (when company-pseudo-tooltip-overlay
1852 (overlay-put company-pseudo-tooltip-overlay 'invisible t)
1853 (overlay-put company-pseudo-tooltip-overlay 'before-string
1854 (overlay-get company-pseudo-tooltip-overlay 'company-before))
1855 (overlay-put company-pseudo-tooltip-overlay 'window (selected-window))))
1857 (defun company-pseudo-tooltip-frontend (command)
1858 "A `company-mode' front-end similar to a tool-tip but based on overlays."
1860 (pre-command (company-pseudo-tooltip-hide-temporarily))
1862 (let ((old-height (if (overlayp company-pseudo-tooltip-overlay)
1863 (overlay-get company-pseudo-tooltip-overlay
1866 (new-height (company--pseudo-tooltip-height)))
1867 (unless (and (>= (* old-height new-height) 0)
1868 (>= (abs old-height) (abs new-height)))
1870 (company-pseudo-tooltip-show-at-point (- (point)
1871 (length company-prefix)))))
1872 (company-pseudo-tooltip-unhide))
1873 (hide (company-pseudo-tooltip-hide)
1874 (setq company-tooltip-offset 0))
1875 (update (when (overlayp company-pseudo-tooltip-overlay)
1876 (company-pseudo-tooltip-edit company-candidates
1877 company-selection)))))
1879 (defun company-pseudo-tooltip-unless-just-one-frontend (command)
1880 "`company-pseudo-tooltip-frontend', but not shown for single candidates."
1881 (unless (and (eq command 'post-command)
1882 (not (cdr company-candidates)))
1883 (company-pseudo-tooltip-frontend command)))
1885 ;;; overlay ;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;
1887 (defvar company-preview-overlay nil)
1888 (make-variable-buffer-local 'company-preview-overlay)
1890 (defun company-preview-show-at-point (pos)
1891 (company-preview-hide)
1893 (setq company-preview-overlay (make-overlay pos pos))
1895 (let ((completion(nth company-selection company-candidates)))
1896 (setq completion (propertize completion 'face 'company-preview))
1897 (add-text-properties 0 (length company-common)
1898 '(face company-preview-common) completion)
1900 ;; Add search string
1901 (and company-search-string
1902 (string-match (regexp-quote company-search-string) completion)
1903 (add-text-properties (match-beginning 0)
1905 '(face company-preview-search)
1908 (setq completion (company-strip-prefix completion))
1910 (and (equal pos (point))
1911 (not (equal completion ""))
1912 (add-text-properties 0 1 '(cursor t) completion))
1914 (overlay-put company-preview-overlay 'after-string completion)
1915 (overlay-put company-preview-overlay 'window (selected-window))))
1917 (defun company-preview-hide ()
1918 (when company-preview-overlay
1919 (delete-overlay company-preview-overlay)
1920 (setq company-preview-overlay nil)))
1922 (defun company-preview-frontend (command)
1923 "A `company-mode' front-end showing the selection as if it had been inserted."
1925 (pre-command (company-preview-hide))
1926 (post-command (company-preview-show-at-point (point)))
1927 (hide (company-preview-hide))))
1929 (defun company-preview-if-just-one-frontend (command)
1930 "`company-preview-frontend', but only shown for single candidates."
1931 (unless (and (eq command 'post-command)
1932 (cdr company-candidates))
1933 (company-preview-frontend command)))
1935 ;;; echo ;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;
1937 (defvar company-echo-last-msg nil)
1938 (make-variable-buffer-local 'company-echo-last-msg)
1940 (defvar company-echo-timer nil)
1942 (defvar company-echo-delay .01)
1944 (defun company-echo-show (&optional getter)
1946 (setq company-echo-last-msg (funcall getter)))
1947 (let ((message-log-max nil))
1948 (if company-echo-last-msg
1949 (message "%s" company-echo-last-msg)
1952 (defsubst company-echo-show-soon (&optional getter)
1953 (when company-echo-timer
1954 (cancel-timer company-echo-timer))
1955 (setq company-echo-timer (run-with-timer 0 nil 'company-echo-show getter)))
1957 (defsubst company-echo-show-when-idle (&optional getter)
1959 (company-echo-show getter)))
1961 (defsubst company-echo-show-when-not-busy (&optional getter)
1962 "Run `company-echo-show' with arg GETTER once Emacs isn't busy."
1963 (when (sit-for company-echo-delay)
1964 (company-echo-show getter)))
1966 (defun company-echo-format ()
1968 (let ((limit (window-width (minibuffer-window)))
1970 ;; Roll to selection.
1971 (candidates (nthcdr company-selection company-candidates))
1972 (i (if company-show-numbers company-selection 99999))
1976 (setq comp (company-reformat (pop candidates))
1977 len (+ len 1 (length comp)))
1981 (setq comp (propertize (format "%d: %s" i comp)
1982 'face 'company-echo))
1985 (add-text-properties 3 (+ 3 (length company-common))
1986 '(face company-echo-common) comp))
1987 (setq comp (propertize comp 'face 'company-echo))
1988 (add-text-properties 0 (length company-common)
1989 '(face company-echo-common) comp))
1991 (setq candidates nil)
1994 (mapconcat 'identity (nreverse msg) " ")))
1996 (defun company-echo-strip-common-format ()
1998 (let ((limit (window-width (minibuffer-window)))
1999 (len (+ (length company-prefix) 2))
2000 ;; Roll to selection.
2001 (candidates (nthcdr company-selection company-candidates))
2002 (i (if company-show-numbers company-selection 99999))
2006 (setq comp (company-strip-prefix (pop candidates))
2007 len (+ len 2 (length comp)))
2010 (setq comp (format "%s (%d)" comp i))
2014 (setq candidates nil)
2015 (push (propertize comp 'face 'company-echo) msg)))
2017 (concat (propertize company-prefix 'face 'company-echo-common) "{"
2018 (mapconcat 'identity (nreverse msg) ", ")
2021 (defun company-echo-hide ()
2022 (unless (equal company-echo-last-msg "")
2023 (setq company-echo-last-msg "")
2024 (company-echo-show)))
2026 (defun company-echo-frontend (command)
2027 "A `company-mode' front-end showing the candidates in the echo area."
2029 (post-command (company-echo-show-soon 'company-echo-format))
2030 (hide (company-echo-hide))))
2032 (defun company-echo-strip-common-frontend (command)
2033 "A `company-mode' front-end showing the candidates in the echo area."
2035 (post-command (company-echo-show-soon 'company-echo-strip-common-format))
2036 (hide (company-echo-hide))))
2038 (defun company-echo-metadata-frontend (command)
2039 "A `company-mode' front-end showing the documentation in the echo area."
2041 (post-command (company-echo-show-when-idle 'company-fetch-metadata))
2042 (hide (company-echo-hide))))
2044 ;; templates ;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;
2046 (autoload 'company-template-declare-template "company-template")
2049 ;;; company.el ends here