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, GNU Emacs 24.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'.
68 ;; Added `company-capf': completion adapter using
69 ;; `completion-at-point-functions'. (Stefan Monnier)
70 ;; Switching tags now works correctly in `company-etags'.
73 ;; `company-ropemacs' now provides location and docs. (Fernando H. Silva)
74 ;; Added `company-with-candidate-inserted' macro.
75 ;; Added `company-clang' back-end.
76 ;; Added new mechanism for non-consecutive insertion.
77 ;; (So far only used by clang for ObjC.)
78 ;; The semantic back-end now shows meta information for local symbols.
79 ;; Added compatibility for CEDET in Emacs 23.2 and from CVS. (Oleg Andreev)
82 ;; Added `company-other-backend'.
83 ;; Idle completion no longer interrupts multi-key command input.
84 ;; Added `company-ropemacs' and `company-pysmell' back-ends.
87 ;; In C modes . and -> now count towards `company-minimum-prefix-length'.
88 ;; Reverted default front-end back to `company-preview-if-just-one-frontend'.
89 ;; The pseudo tooltip will no longer be clipped at the right window edge.
90 ;; Added `company-tooltip-minimum'.
91 ;; Windows compatibility fixes.
94 ;; Added `global-company-mode'.
95 ;; Performance enhancements.
96 ;; Added `company-eclim' back-end.
97 ;; Added safer workaround for Emacs `posn-col-row' bug.
100 ;; Automatic completion is now aborted if the prefix gets too short.
101 ;; Added option `company-dabbrev-time-limit'.
102 ;; `company-backends' now supports merging back-ends.
103 ;; Added back-end `company-dabbrev-code' for generic code.
104 ;; Fixed `company-begin-with'.
106 ;; 2009-04-15 (0.3.1)
107 ;; Added 'stop prefix to prevent dabbrev from completing inside of symbols.
108 ;; Fixed issues with tabbar-mode and line-spacing.
109 ;; Performance enhancements.
112 ;; Added `company-begin-commands' option.
113 ;; Added abbrev, tempo and Xcode back-ends.
114 ;; Back-ends are now interactive. You can start them with M-x backend-name.
115 ;; Added `company-begin-with' for starting company from elisp-code.
117 ;; Added `company-require-match' and `company-auto-complete' options.
119 ;; 2009-04-05 (0.2.1)
120 ;; Improved Emacs Lisp back-end behavior for local variables.
121 ;; Added `company-elisp-detect-function-context' option.
122 ;; The mouse can now be used for selection.
125 ;; Added `company-show-location'.
126 ;; Added etags back-end.
127 ;; Added work-around for end-of-buffer bug.
128 ;; Added `company-filter-candidates'.
129 ;; More local Lisp variables are now included in the candidates.
131 ;; 2009-03-21 (0.1.5)
132 ;; Fixed elisp documentation buffer always showing the same doc.
133 ;; Added `company-echo-strip-common-frontend'.
134 ;; Added `company-show-numbers' option and M-0 ... M-9 default bindings.
135 ;; Don't hide the echo message if it isn't shown.
142 (eval-when-compile (require 'cl))
144 (add-to-list 'debug-ignored-errors "^.* frontend cannot be used twice$")
145 (add-to-list 'debug-ignored-errors "^Echo area cannot be used twice$")
146 (add-to-list 'debug-ignored-errors "^No \\(document\\|loc\\)ation available$")
147 (add-to-list 'debug-ignored-errors "^Company not ")
148 (add-to-list 'debug-ignored-errors "^No candidate number ")
149 (add-to-list 'debug-ignored-errors "^Cannot complete at point$")
150 (add-to-list 'debug-ignored-errors "^No other back-end$")
152 (defgroup company nil
153 "Extensible inline text completion mechanism"
158 (defface company-tooltip
159 '((t :background "yellow"
160 :foreground "black"))
161 "*Face used for the tool tip."
164 (defface company-tooltip-selection
165 '((default :inherit company-tooltip)
166 (((class color) (min-colors 88)) (:background "orange1"))
167 (t (:background "green")))
168 "*Face used for the selection in the tool tip."
171 (defface company-tooltip-mouse
172 '((default :inherit highlight))
173 "*Face used for the tool tip item under the mouse."
176 (defface company-tooltip-common
177 '((t :inherit company-tooltip
179 "*Face used for the common completion in the tool tip."
182 (defface company-tooltip-common-selection
183 '((t :inherit company-tooltip-selection
185 "*Face used for the selected common completion in the tool tip."
188 (defface company-preview
189 '((t :background "blue4"
190 :foreground "wheat"))
191 "*Face used for the completion preview."
194 (defface company-preview-common
195 '((t :inherit company-preview
197 "*Face used for the common part of the completion preview."
200 (defface company-preview-search
201 '((t :inherit company-preview
202 :background "blue1"))
203 "*Face used for the search string in the completion preview."
206 (defface company-echo nil
207 "*Face used for completions in the echo area."
210 (defface company-echo-common
211 '((((background dark)) (:foreground "firebrick1"))
212 (((background light)) (:background "firebrick4")))
213 "*Face used for the common part of completions in the echo area."
216 (defun company-frontends-set (variable value)
218 (let ((remainder value))
219 (setcdr remainder (delq (car remainder) (cdr remainder))))
220 (and (memq 'company-pseudo-tooltip-unless-just-one-frontend value)
221 (memq 'company-pseudo-tooltip-frontend value)
222 (error "Pseudo tooltip frontend cannot be used twice"))
223 (and (memq 'company-preview-if-just-one-frontend value)
224 (memq 'company-preview-frontend value)
225 (error "Preview frontend cannot be used twice"))
226 (and (memq 'company-echo value)
227 (memq 'company-echo-metadata-frontend value)
228 (error "Echo area cannot be used twice"))
229 ;; preview must come last
230 (dolist (f '(company-preview-if-just-one-frontend company-preview-frontend))
232 (setq value (append (delq f value) (list f)))))
233 (set variable value))
235 (defcustom company-frontends '(company-pseudo-tooltip-unless-just-one-frontend
236 company-preview-if-just-one-frontend
237 company-echo-metadata-frontend)
238 "*The list of active front-ends (visualizations).
239 Each front-end is a function that takes one argument. It is called with
240 one of the following arguments:
242 'show: When the visualization should start.
244 'hide: When the visualization should end.
246 'update: When the data has been updated.
248 'pre-command: Before every command that is executed while the
249 visualization is active.
251 'post-command: After every command that is executed while the
252 visualization is active.
254 The visualized data is stored in `company-prefix', `company-candidates',
255 `company-common', `company-selection', `company-point' and
256 `company-search-string'."
257 :set 'company-frontends-set
259 :type '(repeat (choice (const :tag "echo" company-echo-frontend)
260 (const :tag "echo, strip common"
261 company-echo-strip-common-frontend)
262 (const :tag "show echo meta-data in echo"
263 company-echo-metadata-frontend)
264 (const :tag "pseudo tooltip"
265 company-pseudo-tooltip-frontend)
266 (const :tag "pseudo tooltip, multiple only"
267 company-pseudo-tooltip-unless-just-one-frontend)
268 (const :tag "preview" company-preview-frontend)
269 (const :tag "preview, unique only"
270 company-preview-if-just-one-frontend)
271 (function :tag "custom function" nil))))
273 (defcustom company-tooltip-limit 10
274 "*The maximum number of candidates in the tool tip"
278 (defcustom company-tooltip-minimum 6
279 "*The minimum height of the tool tip.
280 If this many lines are not available, prefer to display the tooltip above."
284 (defvar company-safe-backends
285 '((company-abbrev . "Abbrev")
286 (company-clang . "clang")
287 (company-css . "CSS")
288 (company-dabbrev . "dabbrev for plain text")
289 (company-dabbrev-code . "dabbrev for code")
290 (company-eclim . "eclim (an Eclipse interace)")
291 (company-elisp . "Emacs Lisp")
292 (company-etags . "etags")
293 (company-files . "Files")
294 (company-gtags . "GNU Global")
295 (company-ispell . "ispell")
296 (company-keywords . "Programming language keywords")
297 (company-nxml . "nxml")
298 (company-oddmuse . "Oddmuse")
299 (company-pysmell . "PySmell")
300 (company-ropemacs . "ropemacs")
301 (company-semantic . "CEDET Semantic")
302 (company-tempo . "Tempo templates")
303 (company-xcode . "Xcode")))
304 (put 'company-safe-backends 'risky-local-variable t)
306 (defun company-safe-backends-p (backends)
307 (and (consp backends)
308 (not (dolist (backend backends)
309 (unless (if (consp backend)
310 (company-safe-backends-p backend)
311 (assq backend company-safe-backends))
314 (defun company-capf (command &optional arg &rest args)
315 "Adapter for Company completion to use `completion-at-point-functions'."
316 (interactive (list 'interactive))
318 (interactive (company-begin-backend 'company-capf))
320 (let ((res (run-hook-wrapped 'completion-at-point-functions
321 ;; Ignore misbehaving functions.
322 #'completion--capf-wrapper 'optimist)))
324 (if (> (nth 1 res) (point))
326 (buffer-substring-no-properties (nth 0 res) (point))))))
328 (let ((res (run-hook-wrapped 'completion-at-point-functions
329 ;; Ignore misbehaving functions.
330 #'completion--capf-wrapper 'optimist)))
332 (all-completions arg (nth 2 res)
333 (plist-get (nthcdr 3 res) :predicate)))))))
335 (defcustom company-backends '(;; company-capf ;FIXME: Untested!
336 company-elisp company-nxml company-css
337 company-eclim company-semantic company-clang
338 company-xcode company-ropemacs
339 (company-gtags company-etags company-dabbrev-code
340 company-pysmell company-keywords)
341 company-oddmuse company-files company-dabbrev)
342 "*The list of active back-ends (completion engines).
343 Each list elements can itself be a list of back-ends. In that case their
344 completions are merged. Otherwise only the first matching back-end returns
347 `company-begin-backend' can be used to start a specific back-end,
348 `company-other-backend' will skip to the next matching back-end in the list.
350 Each back-end is a function that takes a variable number of arguments.
351 The first argument is the command requested from the back-end. It is one
354 `prefix': The back-end should return the text to be completed. It must be
355 text immediately before `point'. Returning nil passes control to the next
356 back-end. The function should return 'stop if it should complete but cannot
357 \(e.g. if it is in the middle of a string\). If the returned value is only
358 part of the prefix (e.g. the part after \"->\" in C), the back-end may return a
359 cons of prefix and prefix length, which is then used in the
360 `company-minimum-prefix-length' test.
362 `candidates': The second argument is the prefix to be completed. The
363 return value should be a list of candidates that start with the prefix.
367 `sorted': The back-end may return t here to indicate that the candidates
368 are sorted and will not need to be sorted again.
370 `duplicates': If non-nil, company will take care of removing duplicates
373 `no-cache': Usually company doesn't ask for candidates again as completion
374 progresses, unless the back-end returns t for this command. The second
375 argument is the latest prefix.
377 `meta': The second argument is a completion candidate. The back-end should
378 return a (short) documentation string for it.
380 `doc-buffer': The second argument is a completion candidate.
381 The back-end should create a buffer (preferably with `company-doc-buffer'),
382 fill it with documentation and return it.
384 `location': The second argument is a completion candidate. The back-end can
385 return the cons of buffer and buffer location, or of file and line
386 number where the completion candidate was defined.
388 `require-match': If this value is t, the user is not allowed to enter anything
389 not offering as a candidate. Use with care! The default value nil gives the
390 user that choice with `company-require-match'. Return value 'never overrides
391 that option the other way around.
393 The back-end should return nil for all commands it does not support or
394 does not know about. It should also be callable interactively and use
395 `company-begin-backend' to start itself in that case."
400 ,@(mapcar (lambda (b) `(const :tag ,(cdr b) ,(car b)))
401 company-safe-backends)
402 (symbol :tag "User defined")
403 (repeat :tag "Merged Back-ends"
404 (choice :tag "Back-end"
405 ,@(mapcar (lambda (b)
406 `(const :tag ,(cdr b) ,(car b)))
407 company-safe-backends)
408 (symbol :tag "User defined"))))))
410 (put 'company-backends 'safe-local-variable 'company-safe-backends-p)
412 (defcustom company-completion-started-hook nil
413 "*Hook run when company starts completing.
414 The hook is called with one argument that is non-nil if the completion was
419 (defcustom company-completion-cancelled-hook nil
420 "*Hook run when company cancels completing.
421 The hook is called with one argument that is non-nil if the completion was
426 (defcustom company-completion-finished-hook nil
427 "*Hook run when company successfully completes.
428 The hook is called with the selected candidate as an argument."
432 (defcustom company-minimum-prefix-length 3
433 "*The minimum prefix length for automatic completion."
435 :type '(integer :tag "prefix length"))
437 (defcustom company-require-match 'company-explicit-action-p
438 "*If enabled, disallow non-matching input.
439 This can be a function do determine if a match is required.
441 This can be overridden by the back-end, if it returns t or 'never to
442 'require-match. `company-auto-complete' also takes precedence over this."
444 :type '(choice (const :tag "Off" nil)
445 (function :tag "Predicate function")
446 (const :tag "On, if user interaction took place"
447 'company-explicit-action-p)
448 (const :tag "On" t)))
450 (defcustom company-auto-complete 'company-explicit-action-p
451 "Determines when to auto-complete.
452 If this is enabled, all characters from `company-auto-complete-chars' complete
453 the selected completion. This can also be a function."
455 :type '(choice (const :tag "Off" nil)
456 (function :tag "Predicate function")
457 (const :tag "On, if user interaction took place"
458 'company-explicit-action-p)
459 (const :tag "On" t)))
461 (defcustom company-auto-complete-chars '(?\ ?\( ?\) ?. ?\" ?$ ?\' ?< ?| ?!)
462 "Determines which characters trigger an automatic completion.
463 See `company-auto-complete'. If this is a string, each string character causes
464 completion. If it is a list of syntax description characters (see
465 `modify-syntax-entry'), all characters with that syntax auto-complete.
467 This can also be a function, which is called with the new input and should
468 return non-nil if company should auto-complete.
470 A character that is part of a valid candidate never starts auto-completion."
472 :type '(choice (string :tag "Characters")
474 (const :tag "Whitespace" ?\ )
475 (const :tag "Symbol" ?_)
476 (const :tag "Opening parentheses" ?\()
477 (const :tag "Closing parentheses" ?\))
478 (const :tag "Word constituent" ?w)
479 (const :tag "Punctuation." ?.)
480 (const :tag "String quote." ?\")
481 (const :tag "Paired delimiter." ?$)
482 (const :tag "Expression quote or prefix operator." ?\')
483 (const :tag "Comment starter." ?<)
484 (const :tag "Comment ender." ?>)
485 (const :tag "Character-quote." ?/)
486 (const :tag "Generic string fence." ?|)
487 (const :tag "Generic comment fence." ?!))
488 (function :tag "Predicate function")))
490 (defcustom company-idle-delay .7
491 "*The idle delay in seconds until automatic completions starts.
492 A value of nil means never complete automatically, t means complete
493 immediately when a prefix of `company-minimum-prefix-length' is reached."
495 :type '(choice (const :tag "never (nil)" nil)
496 (const :tag "immediate (t)" t)
497 (number :tag "seconds")))
499 (defcustom company-begin-commands t
500 "*A list of commands following which company will start completing.
501 If this is t, it will complete after any command. See `company-idle-delay'.
503 Alternatively any command with a non-nil 'company-begin property is treated as
504 if it was on this list."
506 :type '(choice (const :tag "Any command" t)
507 (const :tag "Self insert command" '(self-insert-command))
508 (repeat :tag "Commands" function)))
510 (defcustom company-show-numbers nil
511 "*If enabled, show quick-access numbers for the first ten candidates."
513 :type '(choice (const :tag "off" nil)
514 (const :tag "on" t)))
516 (defvar company-end-of-buffer-workaround t
517 "*Work around a visualization bug when completing at the end of the buffer.
518 The work-around consists of adding a newline.")
520 ;;; mode ;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;
522 (defvar company-mode-map (make-sparse-keymap)
523 "Keymap used by `company-mode'.")
525 (defvar company-active-map
526 (let ((keymap (make-sparse-keymap)))
527 (define-key keymap "\e\e\e" 'company-abort)
528 (define-key keymap "\C-g" 'company-abort)
529 (define-key keymap (kbd "M-n") 'company-select-next)
530 (define-key keymap (kbd "M-p") 'company-select-previous)
531 (define-key keymap (kbd "<down>") 'company-select-next)
532 (define-key keymap (kbd "<up>") 'company-select-previous)
533 (define-key keymap [down-mouse-1] 'ignore)
534 (define-key keymap [down-mouse-3] 'ignore)
535 (define-key keymap [mouse-1] 'company-complete-mouse)
536 (define-key keymap [mouse-3] 'company-select-mouse)
537 (define-key keymap [up-mouse-1] 'ignore)
538 (define-key keymap [up-mouse-3] 'ignore)
539 (define-key keymap [return] 'company-complete-selection)
540 (define-key keymap [tab] 'company-complete-common)
541 (define-key keymap (kbd "<f1>") 'company-show-doc-buffer)
542 (define-key keymap "\C-w" 'company-show-location)
543 (define-key keymap "\C-s" 'company-search-candidates)
544 (define-key keymap "\C-\M-s" 'company-filter-candidates)
546 (define-key keymap (vector (+ (aref (kbd "M-0") 0) i))
547 `(lambda () (interactive) (company-complete-number ,i))))
550 "Keymap that is enabled during an active completion.")
552 (defvar company--disabled-backends nil)
554 (defun company-init-backend (backend)
555 (and (symbolp backend)
556 (not (fboundp backend))
557 (ignore-errors (require backend nil t)))
559 (if (or (symbolp backend)
563 (funcall backend 'init)
564 (put backend 'company-init t))
566 (put backend 'company-init 'failed)
567 (unless (memq backend company--disabled-backends)
568 (message "Company back-end '%s' could not be initialized:\n%s"
569 backend (error-message-string err)))
570 (push backend company--disabled-backends)
572 (mapc 'company-init-backend backend)))
574 (defvar company-default-lighter " company")
576 (defvar company-lighter company-default-lighter)
577 (make-variable-buffer-local 'company-lighter)
580 (define-minor-mode company-mode
581 "\"complete anything\"; in in-buffer completion framework.
582 Completion starts automatically, depending on the values
583 `company-idle-delay' and `company-minimum-prefix-length'.
585 Completion can be controlled with the commands:
586 `company-complete-common', `company-complete-selection', `company-complete',
587 `company-select-next', `company-select-previous'. If these commands are
588 called before `company-idle-delay', completion will also start.
590 Completions can be searched with `company-search-candidates' or
591 `company-filter-candidates'. These can be used while completion is
594 The completion data is retrieved using `company-backends' and displayed using
595 `company-frontends'. If you want to start a specific back-end, call it
596 interactively or use `company-begin-backend'.
598 regular keymap (`company-mode-map'):
601 keymap during active completions (`company-active-map'):
603 \\{company-active-map}"
604 nil company-lighter company-mode-map
607 (add-hook 'pre-command-hook 'company-pre-command nil t)
608 (add-hook 'post-command-hook 'company-post-command nil t)
609 (mapc 'company-init-backend company-backends))
610 (remove-hook 'pre-command-hook 'company-pre-command t)
611 (remove-hook 'post-command-hook 'company-post-command t)
613 (kill-local-variable 'company-point)))
615 (define-globalized-minor-mode global-company-mode company-mode
616 (lambda () (company-mode 1)))
618 (defsubst company-assert-enabled ()
620 (company-uninstall-map)
621 (error "Company not enabled")))
623 ;;; keymaps ;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;
625 (defvar company-my-keymap nil)
626 (make-variable-buffer-local 'company-my-keymap)
628 (defvar company-emulation-alist '((t . nil)))
630 (defsubst company-enable-overriding-keymap (keymap)
631 (company-uninstall-map)
632 (setq company-my-keymap keymap))
634 (defun company-ensure-emulation-alist ()
635 (unless (eq 'company-emulation-alist (car emulation-mode-map-alists))
636 (setq emulation-mode-map-alists
637 (cons 'company-emulation-alist
638 (delq 'company-emulation-alist emulation-mode-map-alists)))))
640 (defun company-install-map ()
641 (unless (or (cdar company-emulation-alist)
642 (null company-my-keymap))
643 (setf (cdar company-emulation-alist) company-my-keymap)))
645 (defun company-uninstall-map ()
646 (setf (cdar company-emulation-alist) nil))
649 ;; Emacs calculates the active keymaps before reading the event. That means we
650 ;; cannot change the keymap from a timer. So we send a bogus command.
651 (defun company-ignore ()
653 (setq this-command last-command))
655 (global-set-key '[31415926] 'company-ignore)
657 (defun company-input-noop ()
658 (push 31415926 unread-command-events))
661 ;; posn-col-row is incorrect in older Emacsen when line-spacing is set
662 (defun company--col-row (&optional pos)
663 (let ((posn (posn-at-point pos)))
664 (cons (car (posn-col-row posn)) (cdr (posn-actual-col-row posn)))))
666 (defsubst company--column (&optional pos)
667 (car (posn-col-row (posn-at-point pos))))
669 (defsubst company--row (&optional pos)
670 (cdr (posn-actual-col-row (posn-at-point pos))))
672 ;;; backends ;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;
674 (defun company-grab (regexp &optional expression limit)
675 (when (looking-back regexp limit)
676 (or (match-string-no-properties (or expression 0)) "")))
678 (defun company-grab-line (regexp &optional expression)
679 (company-grab regexp expression (point-at-bol)))
681 (defun company-grab-symbol ()
682 (if (looking-at "\\_>")
683 (buffer-substring (point) (save-excursion (skip-syntax-backward "w_")
685 (unless (and (char-after) (memq (char-syntax (char-after)) '(?w ?_)))
688 (defun company-grab-word ()
689 (if (looking-at "\\>")
690 (buffer-substring (point) (save-excursion (skip-syntax-backward "w")
692 (unless (and (char-after) (eq (char-syntax (char-after)) ?w))
695 (defun company-in-string-or-comment ()
696 (let ((ppss (syntax-ppss)))
697 (or (car (setq ppss (nthcdr 3 ppss)))
698 (car (setq ppss (cdr ppss)))
701 (if (fboundp 'locate-dominating-file)
702 (defalias 'company-locate-dominating-file 'locate-dominating-file)
703 (defun company-locate-dominating-file (file name)
705 (let ((dir (file-name-directory file))
707 (while (not (equal dir prev-dir))
708 (when (file-exists-p (expand-file-name name dir))
711 dir (file-name-directory (directory-file-name dir))))))))
713 (defun company-call-backend (&rest args)
714 (if (functionp company-backend)
715 (apply company-backend args)
716 (apply 'company--multi-backend-adapter company-backend args)))
718 (defun company--multi-backend-adapter (backends command &rest args)
721 (apply 'append (mapcar (lambda (backend) (apply backend command args))
727 (dolist (backend backends)
728 (when (setq value (apply backend command args))
731 ;;; completion mechanism ;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;
733 (defvar company-backend nil)
734 (make-variable-buffer-local 'company-backend)
736 (defvar company-prefix nil)
737 (make-variable-buffer-local 'company-prefix)
739 (defvar company-candidates nil)
740 (make-variable-buffer-local 'company-candidates)
742 (defvar company-candidates-length nil)
743 (make-variable-buffer-local 'company-candidates-length)
745 (defvar company-candidates-cache nil)
746 (make-variable-buffer-local 'company-candidates-cache)
748 (defvar company-candidates-predicate nil)
749 (make-variable-buffer-local 'company-candidates-predicate)
751 (defvar company-common nil)
752 (make-variable-buffer-local 'company-common)
754 (defvar company-selection 0)
755 (make-variable-buffer-local 'company-selection)
757 (defvar company-selection-changed nil)
758 (make-variable-buffer-local 'company-selection-changed)
760 (defvar company--explicit-action nil
761 "Non-nil, if explicit completion took place.")
762 (make-variable-buffer-local 'company--explicit-action)
764 (defvar company--point-max nil)
765 (make-variable-buffer-local 'company--point-max)
767 (defvar company-point nil)
768 (make-variable-buffer-local 'company-point)
770 (defvar company-timer nil)
772 (defvar company-added-newline nil)
773 (make-variable-buffer-local 'company-added-newline)
775 (defsubst company-strip-prefix (str)
776 (substring str (length company-prefix)))
778 (defmacro company-with-candidate-inserted (candidate &rest body)
779 "Evaluate BODY with CANDIDATE temporarily inserted.
780 This is a tool for back-ends that need candidates inserted before they
781 can retrieve meta-data for them."
783 `(let ((inhibit-modification-hooks t)
784 (inhibit-point-motion-hooks t)
785 (modified-p (buffer-modified-p)))
786 (insert (company-strip-prefix ,candidate))
789 (delete-region company-point (point)))))
791 (defun company-explicit-action-p ()
792 "Return whether explicit completion action was taken by the user."
793 (or company--explicit-action
794 company-selection-changed))
796 (defsubst company-reformat (candidate)
797 ;; company-ispell needs this, because the results are always lower-case
798 ;; It's mory efficient to fix it only when they are displayed.
799 (concat company-prefix (substring candidate (length company-prefix))))
801 (defun company--should-complete ()
802 (and (not (or buffer-read-only overriding-terminal-local-map
803 overriding-local-map))
804 ;; Check if in the middle of entering a key combination.
805 (or (equal (this-command-keys-vector) [])
806 (not (keymapp (key-binding (this-command-keys-vector)))))
807 (eq company-idle-delay t)
808 (or (eq t company-begin-commands)
809 (memq this-command company-begin-commands)
810 (and (symbolp this-command) (get this-command 'company-begin)))
811 (not (and transient-mark-mode mark-active))))
813 (defsubst company-call-frontends (command)
814 (dolist (frontend company-frontends)
816 (funcall frontend command)
817 (error (error "Company: Front-end %s error \"%s\" on command %s"
818 frontend (error-message-string err) command)))))
820 (defsubst company-set-selection (selection &optional force-update)
821 (setq selection (max 0 (min (1- company-candidates-length) selection)))
822 (when (or force-update (not (equal selection company-selection)))
823 (setq company-selection selection
824 company-selection-changed t)
825 (company-call-frontends 'update)))
827 (defun company-apply-predicate (candidates predicate)
829 (dolist (c candidates)
830 (when (funcall predicate c)
834 (defun company-update-candidates (candidates)
835 (setq company-candidates-length (length candidates))
836 (if (> company-selection 0)
837 ;; Try to restore the selection
838 (let ((selected (nth company-selection company-candidates)))
839 (setq company-selection 0
840 company-candidates candidates)
842 (while (and candidates (string< (pop candidates) selected))
843 (incf company-selection))
845 ;; Make sure selection isn't out of bounds.
846 (setq company-selection (min (1- company-candidates-length)
847 company-selection)))))
848 (setq company-selection 0
849 company-candidates candidates))
851 (push (cons company-prefix company-candidates) company-candidates-cache)
853 (let ((completion-ignore-case (company-call-backend 'ignore-case)))
854 (setq company-common (try-completion company-prefix company-candidates)))
855 (when (eq company-common t)
856 (setq company-candidates nil)))
858 (defun company-calculate-candidates (prefix)
859 (let ((candidates (cdr (assoc prefix company-candidates-cache))))
861 (when company-candidates-cache
862 (let ((len (length prefix))
863 (completion-ignore-case (company-call-backend 'ignore-case))
865 (dotimes (i (1+ len))
866 (when (setq prev (cdr (assoc (substring prefix 0 (- len i))
867 company-candidates-cache)))
868 (setq candidates (all-completions prefix prev))
870 ;; no cache match, call back-end
872 (setq candidates (company-call-backend 'candidates prefix))
873 (when company-candidates-predicate
875 (company-apply-predicate candidates
876 company-candidates-predicate)))
877 (unless (company-call-backend 'sorted)
878 (setq candidates (sort candidates 'string<)))
879 (when (company-call-backend 'duplicates)
881 (let ((c2 candidates))
883 (setcdr c2 (progn (while (equal (pop c2) (car c2)))
885 (if (or (cdr candidates)
886 (not (equal (car candidates) prefix)))
887 ;; Don't start when already completed and unique.
889 ;; Not the right place? maybe when setting?
890 (and company-candidates t))))
892 (defun company-idle-begin (buf win tick pos)
894 (eq buf (current-buffer))
895 (eq win (selected-window))
896 (eq tick (buffer-chars-modified-tick))
898 (not company-candidates)
899 (not (equal (point) company-point))
900 (let ((company-idle-delay t)
901 (company-begin-commands t))
903 (when company-candidates
905 (company-post-command)))))
907 (defun company-auto-begin ()
908 (company-assert-enabled)
910 (not company-candidates)
911 (let ((company-idle-delay t)
912 (company-minimum-prefix-length 0)
913 (company-begin-commands t))
915 ;; Return non-nil if active.
918 (defun company-manual-begin ()
920 (setq company--explicit-action t)
921 (company-auto-begin))
923 (defun company-other-backend (&optional backward)
924 (interactive (list current-prefix-arg))
925 (company-assert-enabled)
927 (let* ((after (cdr (member company-backend company-backends)))
928 (before (cdr (member company-backend (reverse company-backends))))
930 (append before (reverse after))
931 (append after (reverse before)))))
933 (dolist (backend next)
934 (when (ignore-errors (company-begin-backend backend))
936 (company-manual-begin))
937 (unless company-candidates
938 (error "No other back-end")))
940 (defun company-require-match-p ()
941 (let ((backend-value (company-call-backend 'require-match)))
942 (or (eq backend-value t)
943 (and (if (functionp company-require-match)
944 (funcall company-require-match)
945 (eq company-require-match t))
946 (not (eq backend-value 'never))))))
948 (defun company-punctuation-p (input)
949 "Return non-nil, if input starts with punctuation or parentheses."
950 (memq (char-syntax (string-to-char input)) '(?. ?\( ?\))))
952 (defun company-auto-complete-p (input)
953 "Return non-nil, if input starts with punctuation or parentheses."
954 (and (if (functionp company-auto-complete)
955 (funcall company-auto-complete)
956 company-auto-complete)
957 (if (functionp company-auto-complete-chars)
958 (funcall company-auto-complete-chars input)
959 (if (consp company-auto-complete-chars)
960 (memq (char-syntax (string-to-char input))
961 company-auto-complete-chars)
962 (string-match (substring input 0 1) company-auto-complete-chars)))))
964 (defun company--incremental-p ()
965 (and (> (point) company-point)
966 (> (point-max) company--point-max)
967 (not (eq this-command 'backward-delete-char-untabify))
968 (equal (buffer-substring (- company-point (length company-prefix))
972 (defsubst company--string-incremental-p (old-prefix new-prefix)
973 (and (> (length new-prefix) (length old-prefix))
974 (equal old-prefix (substring new-prefix 0 (length old-prefix)))))
976 (defun company--continue-failed (new-prefix)
977 (when (company--incremental-p)
978 (let ((input (buffer-substring-no-properties (point) company-point)))
980 ((company-auto-complete-p input)
983 (goto-char company-point)
984 (company-complete-selection)
986 ((and (company--string-incremental-p company-prefix new-prefix)
987 (company-require-match-p))
988 ;; wrong incremental input, but required match
989 (backward-delete-char (length input))
991 (message "Matching input is required")
993 ((equal company-prefix (car company-candidates))
994 ;; last input was actually success
995 (company-cancel company-prefix)
998 (defun company--good-prefix-p (prefix)
999 (and (or (company-explicit-action-p)
1000 (>= (or (cdr-safe prefix) (length prefix))
1001 company-minimum-prefix-length))
1002 (stringp (or (car-safe prefix) prefix))))
1004 (defun company--continue ()
1005 (when (company-call-backend 'no-cache company-prefix)
1006 ;; Don't complete existing candidates, fetch new ones.
1007 (setq company-candidates-cache nil))
1008 (let* ((new-prefix (company-call-backend 'prefix))
1009 (c (when (and (company--good-prefix-p new-prefix)
1010 (setq new-prefix (or (car-safe new-prefix) new-prefix))
1011 (= (- (point) (length new-prefix))
1012 (- company-point (length company-prefix))))
1013 (setq new-prefix (or (car-safe new-prefix) new-prefix))
1014 (company-calculate-candidates new-prefix))))
1017 ;; t means complete/unique.
1018 (company-cancel new-prefix)
1021 ;; incremental match
1022 (setq company-prefix new-prefix)
1023 (company-update-candidates c)
1025 (t (company--continue-failed new-prefix)))
1028 (defun company--begin-new ()
1030 (dolist (backend (if company-backend
1031 ;; prefer manual override
1032 (list company-backend)
1035 (if (or (symbolp backend)
1036 (functionp backend))
1037 (when (or (not (symbolp backend))
1038 (eq t (get backend 'company-init))
1039 (unless (get backend 'company-init)
1040 (company-init-backend backend)))
1041 (funcall backend 'prefix))
1042 (company--multi-backend-adapter backend 'prefix)))
1044 (when (company--good-prefix-p prefix)
1045 (setq prefix (or (car-safe prefix) prefix)
1046 company-backend backend
1047 c (company-calculate-candidates prefix))
1048 ;; t means complete/unique. We don't start, so no hooks.
1050 (when company--explicit-action
1051 (message "No completion found"))
1052 (setq company-prefix prefix)
1053 (when (symbolp backend)
1054 (setq company-lighter (concat " " (symbol-name backend))))
1055 (company-update-candidates c)
1056 (run-hook-with-args 'company-completion-started-hook
1057 (company-explicit-action-p))
1058 (company-call-frontends 'show)))
1061 (defun company-begin ()
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-ensure-emulation-alist)
1071 (company-enable-overriding-keymap company-active-map)
1072 (company-call-frontends 'update)))
1074 (defun company-cancel (&optional result)
1075 (and company-added-newline
1076 (> (point-max) (point-min))
1077 (let ((tick (buffer-chars-modified-tick)))
1078 (delete-region (1- (point-max)) (point-max))
1079 (equal tick company-added-newline))
1080 ;; Only set unmodified when tick remained the same since insert.
1081 (set-buffer-modified-p nil))
1082 (when company-prefix
1083 (if (stringp result)
1085 (company-call-backend 'pre-completion result)
1086 (run-hook-with-args 'company-completion-finished-hook result)
1087 (company-call-backend 'post-completion result))
1088 (run-hook-with-args 'company-completion-cancelled-hook result)))
1089 (setq company-added-newline nil
1092 company-candidates nil
1093 company-candidates-length nil
1094 company-candidates-cache nil
1095 company-candidates-predicate nil
1098 company-selection-changed nil
1099 company--explicit-action nil
1100 company-lighter company-default-lighter
1101 company--point-max nil
1104 (cancel-timer company-timer))
1105 (company-search-mode 0)
1106 (company-call-frontends 'hide)
1107 (company-enable-overriding-keymap nil))
1109 (defun company-abort ()
1112 ;; Don't start again, unless started manually.
1113 (setq company-point (point)))
1115 (defun company-finish (result)
1116 (insert (company-strip-prefix result))
1117 (company-cancel result)
1118 ;; Don't start again, unless started manually.
1119 (setq company-point (point)))
1121 (defsubst company-keep (command)
1122 (and (symbolp command) (get command 'company-keep)))
1124 (defun company-pre-command ()
1125 (unless (company-keep this-command)
1127 (when company-candidates
1128 (company-call-frontends 'pre-command))
1129 (error (message "Company: An error occurred in pre-command")
1130 (message "%s" (error-message-string err))
1133 (cancel-timer company-timer)
1134 (setq company-timer nil))
1135 (company-uninstall-map))
1137 (defun company-post-command ()
1138 (unless (company-keep this-command)
1141 (unless (equal (point) company-point)
1143 (if company-candidates
1144 (company-call-frontends 'post-command)
1145 (and (numberp company-idle-delay)
1146 (or (eq t company-begin-commands)
1147 (memq this-command company-begin-commands))
1149 (run-with-timer company-idle-delay nil
1151 (current-buffer) (selected-window)
1152 (buffer-chars-modified-tick) (point))))))
1153 (error (message "Company: An error occurred in post-command")
1154 (message "%s" (error-message-string err))
1156 (company-install-map))
1158 ;;; search ;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;
1160 (defvar company-search-string nil)
1161 (make-variable-buffer-local 'company-search-string)
1163 (defvar company-search-lighter " Search: \"\"")
1164 (make-variable-buffer-local 'company-search-lighter)
1166 (defvar company-search-old-map nil)
1167 (make-variable-buffer-local 'company-search-old-map)
1169 (defvar company-search-old-selection 0)
1170 (make-variable-buffer-local 'company-search-old-selection)
1172 (defun company-search (text lines)
1173 (let ((quoted (regexp-quote text))
1175 (dolist (line lines)
1176 (when (string-match quoted line (length company-prefix))
1180 (defun company-search-printing-char ()
1182 (company-search-assert-enabled)
1183 (setq company-search-string
1184 (concat (or company-search-string "") (string last-command-event))
1185 company-search-lighter (concat " Search: \"" company-search-string
1187 (let ((pos (company-search company-search-string
1188 (nthcdr company-selection company-candidates))))
1191 (company-set-selection (+ company-selection pos) t))))
1193 (defun company-search-repeat-forward ()
1194 "Repeat the incremental search in completion candidates forward."
1196 (company-search-assert-enabled)
1197 (let ((pos (company-search company-search-string
1198 (cdr (nthcdr company-selection
1199 company-candidates)))))
1202 (company-set-selection (+ company-selection pos 1) t))))
1204 (defun company-search-repeat-backward ()
1205 "Repeat the incremental search in completion candidates backwards."
1207 (company-search-assert-enabled)
1208 (let ((pos (company-search company-search-string
1209 (nthcdr (- company-candidates-length
1211 (reverse company-candidates)))))
1214 (company-set-selection (- company-selection pos 1) t))))
1216 (defun company-create-match-predicate ()
1217 (setq company-candidates-predicate
1218 `(lambda (candidate)
1219 ,(if company-candidates-predicate
1220 `(and (string-match ,company-search-string candidate)
1221 (funcall ,company-candidates-predicate
1223 `(string-match ,company-search-string candidate))))
1224 (company-update-candidates
1225 (company-apply-predicate company-candidates company-candidates-predicate))
1226 ;; Invalidate cache.
1227 (setq company-candidates-cache (cons company-prefix company-candidates)))
1229 (defun company-filter-printing-char ()
1231 (company-search-assert-enabled)
1232 (company-search-printing-char)
1233 (company-create-match-predicate)
1234 (company-call-frontends 'update))
1236 (defun company-search-kill-others ()
1237 "Limit the completion candidates to the ones matching the search string."
1239 (company-search-assert-enabled)
1240 (company-create-match-predicate)
1241 (company-search-mode 0)
1242 (company-call-frontends 'update))
1244 (defun company-search-abort ()
1245 "Abort searching the completion candidates."
1247 (company-search-assert-enabled)
1248 (company-set-selection company-search-old-selection t)
1249 (company-search-mode 0))
1251 (defun company-search-other-char ()
1253 (company-search-assert-enabled)
1254 (company-search-mode 0)
1255 (when last-input-event
1256 (clear-this-command-keys t)
1257 (setq unread-command-events (list last-input-event))))
1259 (defvar company-search-map
1261 (keymap (make-keymap)))
1262 (if (fboundp 'max-char)
1263 (set-char-table-range (nth 1 keymap) (cons #x100 (max-char))
1264 'company-search-printing-char)
1266 ;; obselete in Emacs 23
1267 (let ((l (generic-character-list))
1268 (table (nth 1 keymap)))
1270 (set-char-table-default table (car l) 'company-search-printing-char)
1271 (setq l (cdr l))))))
1272 (define-key keymap [t] 'company-search-other-char)
1274 (define-key keymap (make-string 1 i) 'company-search-other-char)
1277 (define-key keymap (vector i) 'company-search-printing-char)
1279 (let ((meta-map (make-sparse-keymap)))
1280 (define-key keymap (char-to-string meta-prefix-char) meta-map)
1281 (define-key keymap [escape] meta-map))
1282 (define-key keymap (vector meta-prefix-char t) 'company-search-other-char)
1283 (define-key keymap "\e\e\e" 'company-search-other-char)
1284 (define-key keymap [escape escape escape] 'company-search-other-char)
1286 (define-key keymap "\C-g" 'company-search-abort)
1287 (define-key keymap "\C-s" 'company-search-repeat-forward)
1288 (define-key keymap "\C-r" 'company-search-repeat-backward)
1289 (define-key keymap "\C-o" 'company-search-kill-others)
1291 "Keymap used for incrementally searching the completion candidates.")
1293 (define-minor-mode company-search-mode
1294 "Search mode for completion candidates.
1295 Don't start this directly, use `company-search-candidates' or
1296 `company-filter-candidates'."
1297 nil company-search-lighter nil
1298 (if company-search-mode
1299 (if (company-manual-begin)
1301 (setq company-search-old-selection company-selection)
1302 (company-call-frontends 'update))
1303 (setq company-search-mode nil))
1304 (kill-local-variable 'company-search-string)
1305 (kill-local-variable 'company-search-lighter)
1306 (kill-local-variable 'company-search-old-selection)
1307 (company-enable-overriding-keymap company-active-map)))
1309 (defsubst company-search-assert-enabled ()
1310 (company-assert-enabled)
1311 (unless company-search-mode
1312 (company-uninstall-map)
1313 (error "Company not in search mode")))
1315 (defun company-search-candidates ()
1316 "Start searching the completion candidates incrementally.
1318 \\<company-search-map>Search can be controlled with the commands:
1319 - `company-search-repeat-forward' (\\[company-search-repeat-forward])
1320 - `company-search-repeat-backward' (\\[company-search-repeat-backward])
1321 - `company-search-abort' (\\[company-search-abort])
1323 Regular characters are appended to the search string.
1325 The command `company-search-kill-others' (\\[company-search-kill-others]) uses
1326 the search string to limit the completion candidates."
1328 (company-search-mode 1)
1329 (company-enable-overriding-keymap company-search-map))
1331 (defvar company-filter-map
1332 (let ((keymap (make-keymap)))
1333 (define-key keymap [remap company-search-printing-char]
1334 'company-filter-printing-char)
1335 (set-keymap-parent keymap company-search-map)
1337 "Keymap used for incrementally searching the completion candidates.")
1339 (defun company-filter-candidates ()
1340 "Start filtering the completion candidates incrementally.
1341 This works the same way as `company-search-candidates' immediately
1342 followed by `company-search-kill-others' after each input."
1344 (company-search-mode 1)
1345 (company-enable-overriding-keymap company-filter-map))
1347 ;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;
1349 (defun company-select-next ()
1350 "Select the next candidate in the list."
1352 (when (company-manual-begin)
1353 (company-set-selection (1+ company-selection))))
1355 (defun company-select-previous ()
1356 "Select the previous candidate in the list."
1358 (when (company-manual-begin)
1359 (company-set-selection (1- company-selection))))
1361 (defun company-select-mouse (event)
1362 "Select the candidate picked by the mouse."
1364 (when (nth 4 (event-start event))
1365 (company-set-selection (- (cdr (posn-actual-col-row (event-start event)))
1370 (defun company-complete-mouse (event)
1371 "Complete the candidate picked by the mouse."
1373 (when (company-select-mouse event)
1374 (company-complete-selection)))
1376 (defun company-complete-selection ()
1377 "Complete the selected candidate."
1379 (when (company-manual-begin)
1380 (company-finish (nth company-selection company-candidates))))
1382 (defun company-complete-common ()
1383 "Complete the common part of all candidates."
1385 (when (company-manual-begin)
1386 (if (and (not (cdr company-candidates))
1387 (equal company-common (car company-candidates)))
1388 (company-complete-selection)
1389 (insert (company-strip-prefix company-common)))))
1391 (defun company-complete ()
1392 "Complete the common part of all candidates or the current selection.
1393 The first time this is called, the common part is completed, the second time, or
1394 when the selection has been changed, the selected candidate is completed."
1396 (when (company-manual-begin)
1397 (if (or company-selection-changed
1398 (eq last-command 'company-complete-common))
1399 (call-interactively 'company-complete-selection)
1400 (call-interactively 'company-complete-common)
1401 (setq this-command 'company-complete-common))))
1403 (defun company-complete-number (n)
1404 "Complete the Nth candidate.
1405 To show the number next to the candidates in some back-ends, enable
1406 `company-show-numbers'."
1407 (when (company-manual-begin)
1408 (and (< n 1) (> n company-candidates-length)
1409 (error "No candidate number %d" n))
1411 (company-finish (nth n company-candidates))))
1413 ;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;
1415 (defconst company-space-strings-limit 100)
1417 (defconst company-space-strings
1419 (dotimes (i company-space-strings-limit)
1420 (push (make-string (- company-space-strings-limit 1 i) ?\ ) lst))
1421 (apply 'vector lst)))
1423 (defsubst company-space-string (len)
1424 (if (< len company-space-strings-limit)
1425 (aref company-space-strings len)
1426 (make-string len ?\ )))
1428 (defsubst company-safe-substring (str from &optional to)
1429 (let ((len (length str)))
1432 (if (and to (> to len))
1433 (concat (substring str from)
1434 (company-space-string (- to len)))
1435 (substring str from to)))))
1437 ;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;
1439 (defvar company-last-metadata nil)
1440 (make-variable-buffer-local 'company-last-metadata)
1442 (defun company-fetch-metadata ()
1443 (let ((selected (nth company-selection company-candidates)))
1444 (unless (equal selected (car company-last-metadata))
1445 (setq company-last-metadata
1446 (cons selected (company-call-backend 'meta selected))))
1447 (cdr company-last-metadata)))
1449 (defun company-doc-buffer (&optional string)
1450 (with-current-buffer (get-buffer-create "*Company meta-data*")
1454 (defvar company--electric-commands
1455 '(scroll-other-window scroll-other-window-down)
1456 "List of Commands that won't break out of electric commands.")
1458 (defmacro company--electric-do (&rest body)
1459 (declare (indent 0) (debug t))
1460 `(when (company-manual-begin)
1461 (save-window-excursion
1462 (let ((height (window-height))
1463 (row (company--row))
1466 (and (< (window-height) height)
1467 (< (- (window-height) row 2) company-tooltip-limit)
1468 (recenter (- (window-height) row 2)))
1469 (while (memq (setq cmd (key-binding (vector (list (read-event)))))
1470 company--electric-commands)
1471 (call-interactively cmd))
1472 (when last-input-event
1473 (clear-this-command-keys t)
1474 (setq unread-command-events (list last-input-event)))))))
1476 (defun company-show-doc-buffer ()
1477 "Temporarily show a buffer with the complete documentation for the selection."
1479 (company--electric-do
1480 (let* ((selected (nth company-selection company-candidates))
1481 (doc-buffer (or (company-call-backend 'doc-buffer selected)
1482 (error "No documentation available"))))
1483 (with-current-buffer doc-buffer
1484 (goto-char (point-min)))
1485 (display-buffer doc-buffer t))))
1486 (put 'company-show-doc-buffer 'company-keep t)
1488 (defun company-show-location ()
1489 "Temporarily display a buffer showing the selected candidate in context."
1491 (company--electric-do
1492 (let* ((selected (nth company-selection company-candidates))
1493 (location (company-call-backend 'location selected))
1494 (pos (or (cdr location) (error "No location available")))
1495 (buffer (or (and (bufferp (car location)) (car location))
1496 (find-file-noselect (car location) t))))
1497 (with-selected-window (display-buffer buffer t)
1500 (if (bufferp (car location))
1502 (goto-char (point-min))
1503 (forward-line (1- pos))))
1504 (set-window-start nil (point))))))
1505 (put 'company-show-location 'company-keep t)
1507 ;;; package functions ;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;
1509 (defvar company-callback nil)
1510 (make-variable-buffer-local 'company-callback)
1512 (defvar company-begin-with-marker nil)
1513 (make-variable-buffer-local 'company-begin-with-marker)
1515 (defun company-remove-callback (&optional ignored)
1516 (remove-hook 'company-completion-finished-hook company-callback t)
1517 (remove-hook 'company-completion-cancelled-hook 'company-remove-callback t)
1518 (remove-hook 'company-completion-finished-hook 'company-remove-callback t)
1519 (when company-begin-with-marker
1520 (set-marker company-begin-with-marker nil)))
1522 (defun company-begin-backend (backend &optional callback)
1523 "Start a completion at point using BACKEND."
1524 (interactive (let ((val (completing-read "Company back-end: "
1526 'functionp nil "company-")))
1528 (list (intern val)))))
1529 (when (setq company-callback callback)
1530 (add-hook 'company-completion-finished-hook company-callback nil t))
1531 (add-hook 'company-completion-cancelled-hook 'company-remove-callback nil t)
1532 (add-hook 'company-completion-finished-hook 'company-remove-callback nil t)
1533 (setq company-backend backend)
1534 ;; Return non-nil if active.
1535 (or (company-manual-begin)
1536 (error "Cannot complete at point")))
1538 (defun company-begin-with (candidates
1539 &optional prefix-length require-match callback)
1540 "Start a completion at point.
1541 CANDIDATES is the list of candidates to use and PREFIX-LENGTH is the length of
1542 the prefix that already is in the buffer before point. It defaults to 0.
1544 CALLBACK is a function called with the selected result if the user successfully
1545 completes the input.
1548 \(company-begin-with '\(\"foo\" \"foobar\" \"foobarbaz\"\)\)"
1549 (setq company-begin-with-marker (copy-marker (point) t))
1550 (company-begin-backend
1551 `(lambda (command &optional arg &rest ignored)
1553 ((eq command 'prefix)
1554 (when (equal (point) (marker-position company-begin-with-marker))
1555 (buffer-substring ,(- (point) (or prefix-length 0)) (point))))
1556 ((eq command 'candidates)
1557 (all-completions arg ',candidates))
1558 ((eq command 'require-match)
1562 ;;; pseudo-tooltip ;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;
1564 (defvar company-pseudo-tooltip-overlay nil)
1565 (make-variable-buffer-local 'company-pseudo-tooltip-overlay)
1567 (defvar company-tooltip-offset 0)
1568 (make-variable-buffer-local 'company-tooltip-offset)
1570 (defun company-pseudo-tooltip-update-offset (selection num-lines limit)
1573 (setq company-tooltip-offset
1574 (max (min selection company-tooltip-offset)
1575 (- selection -1 limit)))
1577 (when (<= company-tooltip-offset 1)
1579 (setq company-tooltip-offset 0))
1581 (when (>= company-tooltip-offset (- num-lines limit 1))
1583 (when (= selection (1- num-lines))
1584 (decf company-tooltip-offset)
1585 (when (<= company-tooltip-offset 1)
1586 (setq company-tooltip-offset 0)
1593 (defsubst company-round-tab (arg)
1594 (* (/ (+ arg tab-width) tab-width) tab-width))
1596 (defun company-untabify (str)
1597 (let* ((pieces (split-string str "\t"))
1600 (setcar copy (company-safe-substring
1601 (car copy) 0 (company-round-tab (string-width (car copy)))))
1603 (apply 'concat pieces)))
1605 (defun company-fill-propertize (line width selected)
1606 (setq line (company-safe-substring line 0 width))
1607 (add-text-properties 0 width '(face company-tooltip
1608 mouse-face company-tooltip-mouse)
1610 (add-text-properties 0 (length company-common)
1611 '(face company-tooltip-common
1612 mouse-face company-tooltip-mouse)
1615 (if (and company-search-string
1616 (string-match (regexp-quote company-search-string) line
1617 (length company-prefix)))
1619 (add-text-properties (match-beginning 0) (match-end 0)
1620 '(face company-tooltip-selection)
1622 (when (< (match-beginning 0) (length company-common))
1623 (add-text-properties (match-beginning 0) (length company-common)
1624 '(face company-tooltip-common-selection)
1626 (add-text-properties 0 width '(face company-tooltip-selection
1627 mouse-face company-tooltip-selection)
1629 (add-text-properties 0 (length company-common)
1630 '(face company-tooltip-common-selection
1631 mouse-face company-tooltip-selection)
1637 (defun company-buffer-lines (beg end)
1639 (let ((row (company--row))
1641 (while (and (equal (move-to-window-line (incf row)) row)
1643 (push (buffer-substring beg (min end (1- (point)))) lines)
1645 (unless (eq beg end)
1646 (push (buffer-substring beg end) lines))
1649 (defsubst company-modify-line (old new offset)
1650 (concat (company-safe-substring old 0 offset)
1652 (company-safe-substring old (+ offset (length new)))))
1654 (defsubst company--length-limit (lst limit)
1655 (if (nthcdr limit lst)
1659 (defun company--replacement-string (lines old column nl &optional align-top)
1661 (let ((width (length (car lines))))
1662 (when (> width (- (window-width) column))
1663 (setq column (max 0 (- (window-width) width)))))
1667 ;; untouched lines first
1668 (dotimes (i (- (length old) (length lines)))
1669 (push (pop old) new)))
1670 ;; length into old lines.
1672 (push (company-modify-line (pop old) (pop lines) column) new))
1673 ;; Append whole new lines.
1675 (push (concat (company-space-string column) (pop lines)) new))
1676 (concat (when nl "\n")
1677 (mapconcat 'identity (nreverse new) "\n")
1680 (defun company--create-lines (selection limit)
1682 (let ((len company-candidates-length)
1691 ;; Scroll to offset.
1692 (setq limit (company-pseudo-tooltip-update-offset selection len limit))
1694 (when (> company-tooltip-offset 0)
1695 (setq previous (format "...(%d)" company-tooltip-offset)))
1697 (setq remainder (- len limit company-tooltip-offset)
1698 remainder (when (> remainder 0)
1699 (setq remainder (format "...(%d)" remainder))))
1701 (decf selection company-tooltip-offset)
1702 (setq width (max (length previous) (length remainder))
1703 lines (nthcdr company-tooltip-offset company-candidates)
1708 (setq width (max (length (pop lines-copy)) width)))
1709 (setq width (min width (window-width)))
1711 (setq lines-copy lines)
1713 ;; number can make tooltip too long
1714 (when company-show-numbers
1715 (setq numbered company-tooltip-offset))
1718 (push (propertize (company-safe-substring previous 0 width)
1719 'face 'company-tooltip)
1723 (push (company-fill-propertize
1724 (if (>= numbered 10)
1725 (company-reformat (pop lines))
1728 (company-safe-substring (company-reformat (pop lines))
1731 width (equal i selection))
1735 (push (propertize (company-safe-substring remainder 0 width)
1736 'face 'company-tooltip)
1739 (setq lines (nreverse new))))
1743 (defsubst company--window-inner-height ()
1744 (let ((edges (window-inside-edges (selected-window))))
1745 (- (nth 3 edges) (nth 1 edges))))
1747 (defsubst company--pseudo-tooltip-height ()
1748 "Calculate the appropriate tooltip height.
1749 Returns a negative number if the tooltip should be displayed above point."
1750 (let* ((lines (count-lines (window-start) (point-at-bol)))
1751 (below (- (company--window-inner-height) 1 lines)))
1752 (if (and (< below (min company-tooltip-minimum company-candidates-length))
1754 (- (max 3 (min company-tooltip-limit lines)))
1755 (max 3 (min company-tooltip-limit below)))))
1757 (defun company-pseudo-tooltip-show (row column selection)
1758 (company-pseudo-tooltip-hide)
1763 (let* ((height (company--pseudo-tooltip-height))
1767 (setq row (+ row height -1)
1770 (let* ((nl (< (move-to-window-line row) row))
1772 (end (save-excursion
1773 (move-to-window-line (+ row (abs height)))
1775 (ov (make-overlay beg end))
1776 (args (list (mapcar 'company-untabify
1777 (company-buffer-lines beg end))
1780 (setq company-pseudo-tooltip-overlay ov)
1781 (overlay-put ov 'company-replacement-args args)
1782 (overlay-put ov 'company-before
1783 (apply 'company--replacement-string
1784 (company--create-lines selection (abs height))
1787 (overlay-put ov 'company-column column)
1788 (overlay-put ov 'company-height (abs height))
1789 (overlay-put ov 'window (selected-window))))))
1791 (defun company-pseudo-tooltip-show-at-point (pos)
1792 (let ((col-row (company--col-row pos)))
1794 (company-pseudo-tooltip-show (1+ (cdr col-row)) (car col-row)
1795 company-selection))))
1797 (defun company-pseudo-tooltip-edit (lines selection)
1798 (let ((column (overlay-get company-pseudo-tooltip-overlay 'company-column))
1799 (height (overlay-get company-pseudo-tooltip-overlay 'company-height)))
1800 (overlay-put company-pseudo-tooltip-overlay 'company-before
1801 (apply 'company--replacement-string
1802 (company--create-lines selection height)
1803 (overlay-get company-pseudo-tooltip-overlay
1804 'company-replacement-args)))))
1806 (defun company-pseudo-tooltip-hide ()
1807 (when company-pseudo-tooltip-overlay
1808 (delete-overlay company-pseudo-tooltip-overlay)
1809 (setq company-pseudo-tooltip-overlay nil)))
1811 (defun company-pseudo-tooltip-hide-temporarily ()
1812 (when (overlayp company-pseudo-tooltip-overlay)
1813 (overlay-put company-pseudo-tooltip-overlay 'invisible nil)
1814 (overlay-put company-pseudo-tooltip-overlay 'before-string nil)))
1816 (defun company-pseudo-tooltip-unhide ()
1817 (when company-pseudo-tooltip-overlay
1818 (overlay-put company-pseudo-tooltip-overlay 'invisible t)
1819 (overlay-put company-pseudo-tooltip-overlay 'before-string
1820 (overlay-get company-pseudo-tooltip-overlay 'company-before))
1821 (overlay-put company-pseudo-tooltip-overlay 'window (selected-window))))
1823 (defun company-pseudo-tooltip-frontend (command)
1824 "A `company-mode' front-end similar to a tool-tip but based on overlays."
1826 (pre-command (company-pseudo-tooltip-hide-temporarily))
1828 (let ((old-height (if (overlayp company-pseudo-tooltip-overlay)
1829 (overlay-get company-pseudo-tooltip-overlay
1832 (new-height (company--pseudo-tooltip-height)))
1833 (unless (and (>= (* old-height new-height) 0)
1834 (>= (abs old-height) (abs new-height)))
1836 (company-pseudo-tooltip-show-at-point (- (point)
1837 (length company-prefix)))))
1838 (company-pseudo-tooltip-unhide))
1839 (hide (company-pseudo-tooltip-hide)
1840 (setq company-tooltip-offset 0))
1841 (update (when (overlayp company-pseudo-tooltip-overlay)
1842 (company-pseudo-tooltip-edit company-candidates
1843 company-selection)))))
1845 (defun company-pseudo-tooltip-unless-just-one-frontend (command)
1846 "`company-pseudo-tooltip-frontend', but not shown for single candidates."
1847 (unless (and (eq command 'post-command)
1848 (not (cdr company-candidates)))
1849 (company-pseudo-tooltip-frontend command)))
1851 ;;; overlay ;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;
1853 (defvar company-preview-overlay nil)
1854 (make-variable-buffer-local 'company-preview-overlay)
1856 (defun company-preview-show-at-point (pos)
1857 (company-preview-hide)
1859 (setq company-preview-overlay (make-overlay pos pos))
1861 (let ((completion(nth company-selection company-candidates)))
1862 (setq completion (propertize completion 'face 'company-preview))
1863 (add-text-properties 0 (length company-common)
1864 '(face company-preview-common) completion)
1866 ;; Add search string
1867 (and company-search-string
1868 (string-match (regexp-quote company-search-string) completion)
1869 (add-text-properties (match-beginning 0)
1871 '(face company-preview-search)
1874 (setq completion (company-strip-prefix completion))
1876 (and (equal pos (point))
1877 (not (equal completion ""))
1878 (add-text-properties 0 1 '(cursor t) completion))
1880 (overlay-put company-preview-overlay 'after-string completion)
1881 (overlay-put company-preview-overlay 'window (selected-window))))
1883 (defun company-preview-hide ()
1884 (when company-preview-overlay
1885 (delete-overlay company-preview-overlay)
1886 (setq company-preview-overlay nil)))
1888 (defun company-preview-frontend (command)
1889 "A `company-mode' front-end showing the selection as if it had been inserted."
1891 (pre-command (company-preview-hide))
1892 (post-command (company-preview-show-at-point (point)))
1893 (hide (company-preview-hide))))
1895 (defun company-preview-if-just-one-frontend (command)
1896 "`company-preview-frontend', but only shown for single candidates."
1897 (unless (and (eq command 'post-command)
1898 (cdr company-candidates))
1899 (company-preview-frontend command)))
1901 ;;; echo ;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;
1903 (defvar company-echo-last-msg nil)
1904 (make-variable-buffer-local 'company-echo-last-msg)
1906 (defun company-echo-show (&optional getter)
1908 (setq company-echo-last-msg (funcall getter)))
1909 (let ((message-log-max nil))
1910 (if company-echo-last-msg
1911 (message "%s" company-echo-last-msg)
1914 (defsubst company-echo-show-soon (&optional getter)
1915 (when company-echo-timer
1916 (cancel-timer company-echo-timer))
1917 (setq company-echo-timer (run-with-timer 0 nil 'company-echo-show getter)))
1919 (defsubst company-echo-show-when-idle (&optional getter)
1921 (company-echo-show getter)))
1923 (defsubst company-echo-show-when-not-busy (&optional getter)
1924 "Run `company-echo-show' with arg GETTER once Emacs isn't busy."
1925 (when (sit-for company-echo-delay)
1926 (company-echo-show getter)))
1928 (defun company-echo-format ()
1930 (let ((limit (window-width (minibuffer-window)))
1932 ;; Roll to selection.
1933 (candidates (nthcdr company-selection company-candidates))
1934 (i (if company-show-numbers company-selection 99999))
1938 (setq comp (company-reformat (pop candidates))
1939 len (+ len 1 (length comp)))
1943 (setq comp (propertize (format "%d: %s" i comp)
1944 'face 'company-echo))
1947 (add-text-properties 3 (+ 3 (length company-common))
1948 '(face company-echo-common) comp))
1949 (setq comp (propertize comp 'face 'company-echo))
1950 (add-text-properties 0 (length company-common)
1951 '(face company-echo-common) comp))
1953 (setq candidates nil)
1956 (mapconcat 'identity (nreverse msg) " ")))
1958 (defun company-echo-strip-common-format ()
1960 (let ((limit (window-width (minibuffer-window)))
1961 (len (+ (length company-prefix) 2))
1962 ;; Roll to selection.
1963 (candidates (nthcdr company-selection company-candidates))
1964 (i (if company-show-numbers company-selection 99999))
1968 (setq comp (company-strip-prefix (pop candidates))
1969 len (+ len 2 (length comp)))
1972 (setq comp (format "%s (%d)" comp i))
1976 (setq candidates nil)
1977 (push (propertize comp 'face 'company-echo) msg)))
1979 (concat (propertize company-prefix 'face 'company-echo-common) "{"
1980 (mapconcat 'identity (nreverse msg) ", ")
1983 (defun company-echo-hide ()
1984 (unless (equal company-echo-last-msg "")
1985 (setq company-echo-last-msg "")
1986 (company-echo-show)))
1988 (defun company-echo-frontend (command)
1989 "A `company-mode' front-end showing the candidates in the echo area."
1991 (post-command (company-echo-show-soon 'company-echo-format))
1992 (hide (company-echo-hide))))
1994 (defun company-echo-strip-common-frontend (command)
1995 "A `company-mode' front-end showing the candidates in the echo area."
1997 (post-command (company-echo-show-soon 'company-echo-strip-common-format))
1998 (hide (company-echo-hide))))
2000 (defun company-echo-metadata-frontend (command)
2001 "A `company-mode' front-end showing the documentation in the echo area."
2003 (post-command (company-echo-show-when-idle 'company-fetch-metadata))
2004 (hide (company-echo-hide))))
2006 ;; templates ;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;
2008 (autoload 'company-template-declare-template "company-template")
2011 ;;; company.el ends here