1 ;;; company.el --- Extensible inline text completion mechanism
3 ;; Copyright (C) 2009-2013 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 ;; Switching tags now works correctly in `company-etags'.
69 ;; Clang completions now include macros and are case-sensitive.
70 ;; Added `company-capf': completion adapter using
71 ;; `completion-at-point-functions'. (Stefan Monnier)
72 ;; `company-elisp' has some improvements.
73 ;; Instead of `overrriding-terminal-local-map', we're now using
74 ;; `emulation-mode-map-alists' (experimental). This largely means that when
75 ;; the completion keymap is active, other minor modes' keymaps are still
76 ;; used, so, for example, it's not as easy to circumvent `paredit-mode'
77 ;; accidentally when it's enabled.
78 ;; Fixed two old tooltip annoyances.
79 ;; Improved tooltip performance.
82 ;; `company-ropemacs' now provides location and docs. (Fernando H. Silva)
83 ;; Added `company-with-candidate-inserted' macro.
84 ;; Added `company-clang' back-end.
85 ;; Added new mechanism for non-consecutive insertion.
86 ;; (So far only used by clang for ObjC.)
87 ;; The semantic back-end now shows meta information for local symbols.
88 ;; Added compatibility for CEDET in Emacs 23.2 and from CVS. (Oleg Andreev)
91 ;; Added `company-other-backend'.
92 ;; Idle completion no longer interrupts multi-key command input.
93 ;; Added `company-ropemacs' and `company-pysmell' back-ends.
96 ;; In C modes . and -> now count towards `company-minimum-prefix-length'.
97 ;; Reverted default front-end back to `company-preview-if-just-one-frontend'.
98 ;; The pseudo tooltip will no longer be clipped at the right window edge.
99 ;; Added `company-tooltip-minimum'.
100 ;; Windows compatibility fixes.
102 ;; 2009-04-19 (0.4.1)
103 ;; Added `global-company-mode'.
104 ;; Performance enhancements.
105 ;; Added `company-eclim' back-end.
106 ;; Added safer workaround for Emacs `posn-col-row' bug.
109 ;; Automatic completion is now aborted if the prefix gets too short.
110 ;; Added option `company-dabbrev-time-limit'.
111 ;; `company-backends' now supports merging back-ends.
112 ;; Added back-end `company-dabbrev-code' for generic code.
113 ;; Fixed `company-begin-with'.
115 ;; 2009-04-15 (0.3.1)
116 ;; Added 'stop prefix to prevent dabbrev from completing inside of symbols.
117 ;; Fixed issues with tabbar-mode and line-spacing.
118 ;; Performance enhancements.
121 ;; Added `company-begin-commands' option.
122 ;; Added abbrev, tempo and Xcode back-ends.
123 ;; Back-ends are now interactive. You can start them with M-x backend-name.
124 ;; Added `company-begin-with' for starting company from elisp-code.
126 ;; Added `company-require-match' and `company-auto-complete' options.
128 ;; 2009-04-05 (0.2.1)
129 ;; Improved Emacs Lisp back-end behavior for local variables.
130 ;; Added `company-elisp-detect-function-context' option.
131 ;; The mouse can now be used for selection.
134 ;; Added `company-show-location'.
135 ;; Added etags back-end.
136 ;; Added work-around for end-of-buffer bug.
137 ;; Added `company-filter-candidates'.
138 ;; More local Lisp variables are now included in the candidates.
140 ;; 2009-03-21 (0.1.5)
141 ;; Fixed elisp documentation buffer always showing the same doc.
142 ;; Added `company-echo-strip-common-frontend'.
143 ;; Added `company-show-numbers' option and M-0 ... M-9 default bindings.
144 ;; Don't hide the echo message if it isn't shown.
151 (eval-when-compile (require 'cl))
153 (add-to-list 'debug-ignored-errors "^.* frontend cannot be used twice$")
154 (add-to-list 'debug-ignored-errors "^Echo area cannot be used twice$")
155 (add-to-list 'debug-ignored-errors "^No \\(document\\|loc\\)ation available$")
156 (add-to-list 'debug-ignored-errors "^Company not ")
157 (add-to-list 'debug-ignored-errors "^No candidate number ")
158 (add-to-list 'debug-ignored-errors "^Cannot complete at point$")
159 (add-to-list 'debug-ignored-errors "^No other back-end$")
161 (defgroup company nil
162 "Extensible inline text completion mechanism"
167 (defface company-tooltip
168 '((t :background "yellow"
169 :foreground "black"))
170 "Face used for the tool tip."
173 (defface company-tooltip-selection
174 '((default :inherit company-tooltip)
175 (((class color) (min-colors 88)) (:background "orange1"))
176 (t (:background "green")))
177 "Face used for the selection in the tool tip."
180 (defface company-tooltip-mouse
181 '((default :inherit highlight))
182 "Face used for the tool tip item under the mouse."
185 (defface company-tooltip-common
186 '((t :inherit company-tooltip
188 "Face used for the common completion in the tool tip."
191 (defface company-tooltip-common-selection
192 '((t :inherit company-tooltip-selection
194 "Face used for the selected common completion in the tool tip."
197 (defface company-preview
198 '((t :background "blue4"
199 :foreground "wheat"))
200 "Face used for the completion preview."
203 (defface company-preview-common
204 '((t :inherit company-preview
206 "Face used for the common part of the completion preview."
209 (defface company-preview-search
210 '((t :inherit company-preview
211 :background "blue1"))
212 "Face used for the search string in the completion preview."
215 (defface company-echo nil
216 "Face used for completions in the echo area."
219 (defface company-echo-common
220 '((((background dark)) (:foreground "firebrick1"))
221 (((background light)) (:background "firebrick4")))
222 "Face used for the common part of completions in the echo area."
225 (defun company-frontends-set (variable value)
227 (let ((remainder value))
228 (setcdr remainder (delq (car remainder) (cdr remainder))))
229 (and (memq 'company-pseudo-tooltip-unless-just-one-frontend value)
230 (memq 'company-pseudo-tooltip-frontend value)
231 (error "Pseudo tooltip frontend cannot be used twice"))
232 (and (memq 'company-preview-if-just-one-frontend value)
233 (memq 'company-preview-frontend value)
234 (error "Preview frontend cannot be used twice"))
235 (and (memq 'company-echo value)
236 (memq 'company-echo-metadata-frontend value)
237 (error "Echo area cannot be used twice"))
238 ;; preview must come last
239 (dolist (f '(company-preview-if-just-one-frontend company-preview-frontend))
241 (setq value (append (delq f value) (list f)))))
242 (set variable value))
244 (defcustom company-frontends '(company-pseudo-tooltip-unless-just-one-frontend
245 company-preview-if-just-one-frontend
246 company-echo-metadata-frontend)
247 "The list of active front-ends (visualizations).
248 Each front-end is a function that takes one argument. It is called with
249 one of the following arguments:
251 'show: When the visualization should start.
253 'hide: When the visualization should end.
255 'update: When the data has been updated.
257 'pre-command: Before every command that is executed while the
258 visualization is active.
260 'post-command: After every command that is executed while the
261 visualization is active.
263 The visualized data is stored in `company-prefix', `company-candidates',
264 `company-common', `company-selection', `company-point' and
265 `company-search-string'."
266 :set 'company-frontends-set
268 :type '(repeat (choice (const :tag "echo" company-echo-frontend)
269 (const :tag "echo, strip common"
270 company-echo-strip-common-frontend)
271 (const :tag "show echo meta-data in echo"
272 company-echo-metadata-frontend)
273 (const :tag "pseudo tooltip"
274 company-pseudo-tooltip-frontend)
275 (const :tag "pseudo tooltip, multiple only"
276 company-pseudo-tooltip-unless-just-one-frontend)
277 (const :tag "preview" company-preview-frontend)
278 (const :tag "preview, unique only"
279 company-preview-if-just-one-frontend)
280 (function :tag "custom function" nil))))
282 (defcustom company-tooltip-limit 10
283 "The maximum number of candidates in the tool tip"
287 (defcustom company-tooltip-minimum 6
288 "The minimum height of the tool tip.
289 If this many lines are not available, prefer to display the tooltip above."
293 (defvar company-safe-backends
294 '((company-abbrev . "Abbrev")
295 (company-clang . "clang")
296 (company-css . "CSS")
297 (company-dabbrev . "dabbrev for plain text")
298 (company-dabbrev-code . "dabbrev for code")
299 (company-eclim . "eclim (an Eclipse interace)")
300 (company-elisp . "Emacs Lisp")
301 (company-etags . "etags")
302 (company-files . "Files")
303 (company-gtags . "GNU Global")
304 (company-ispell . "ispell")
305 (company-keywords . "Programming language keywords")
306 (company-nxml . "nxml")
307 (company-oddmuse . "Oddmuse")
308 (company-pysmell . "PySmell")
309 (company-ropemacs . "ropemacs")
310 (company-semantic . "CEDET Semantic")
311 (company-tempo . "Tempo templates")
312 (company-xcode . "Xcode")))
313 (put 'company-safe-backends 'risky-local-variable t)
315 (defun company-safe-backends-p (backends)
316 (and (consp backends)
317 (not (dolist (backend backends)
318 (unless (if (consp backend)
319 (company-safe-backends-p backend)
320 (assq backend company-safe-backends))
323 (defun company-capf (command &optional arg &rest args)
324 "`company-mode' back-end using `completion-at-point-functions'.
325 Requires Emacs 24.1 or newer."
326 (interactive (list 'interactive))
328 (interactive (company-begin-backend 'company-capf))
330 (let ((res (run-hook-wrapped 'completion-at-point-functions
331 ;; Ignore misbehaving functions.
332 #'completion--capf-wrapper 'optimist)))
334 (if (> (nth 2 res) (point))
336 (buffer-substring-no-properties (nth 1 res) (point))))))
338 (let ((res (run-hook-wrapped 'completion-at-point-functions
339 ;; Ignore misbehaving functions.
340 #'completion--capf-wrapper 'optimist)))
342 (all-completions arg (nth 3 res)
343 (plist-get (nthcdr 4 res) :predicate)))))))
345 (defcustom company-backends '(company-elisp company-nxml company-css
346 company-eclim company-semantic company-clang
347 company-xcode company-ropemacs
348 (company-gtags company-etags company-dabbrev-code
349 company-pysmell company-keywords)
350 company-oddmuse company-files company-dabbrev)
351 "The list of active back-ends (completion engines).
352 Each list elements can itself be a list of back-ends. In that case their
353 completions are merged. Otherwise only the first matching back-end returns
356 `company-begin-backend' can be used to start a specific back-end,
357 `company-other-backend' will skip to the next matching back-end in the list.
359 Each back-end is a function that takes a variable number of arguments.
360 The first argument is the command requested from the back-end. It is one
363 `prefix': The back-end should return the text to be completed. It must be
364 text immediately before `point'. Returning nil passes control to the next
365 back-end. The function should return 'stop if it should complete but cannot
366 \(e.g. if it is in the middle of a string\). If the returned value is only
367 part of the prefix (e.g. the part after \"->\" in C), the back-end may return a
368 cons of prefix and prefix length, which is then used in the
369 `company-minimum-prefix-length' test.
371 `candidates': The second argument is the prefix to be completed. The
372 return value should be a list of candidates that start with the prefix.
376 `sorted': The back-end may return t here to indicate that the candidates
377 are sorted and will not need to be sorted again.
379 `duplicates': If non-nil, company will take care of removing duplicates
382 `no-cache': Usually company doesn't ask for candidates again as completion
383 progresses, unless the back-end returns t for this command. The second
384 argument is the latest prefix.
386 `meta': The second argument is a completion candidate. The back-end should
387 return a (short) documentation string for it.
389 `doc-buffer': The second argument is a completion candidate.
390 The back-end should create a buffer (preferably with `company-doc-buffer'),
391 fill it with documentation and return it.
393 `location': The second argument is a completion candidate. The back-end can
394 return the cons of buffer and buffer location, or of file and line
395 number where the completion candidate was defined.
397 `require-match': If this value is t, the user is not allowed to enter anything
398 not offering as a candidate. Use with care! The default value nil gives the
399 user that choice with `company-require-match'. Return value 'never overrides
400 that option the other way around.
402 The back-end should return nil for all commands it does not support or
403 does not know about. It should also be callable interactively and use
404 `company-begin-backend' to start itself in that case."
409 ,@(mapcar (lambda (b) `(const :tag ,(cdr b) ,(car b)))
410 company-safe-backends)
411 (symbol :tag "User defined")
412 (repeat :tag "Merged Back-ends"
413 (choice :tag "Back-end"
414 ,@(mapcar (lambda (b)
415 `(const :tag ,(cdr b) ,(car b)))
416 company-safe-backends)
417 (symbol :tag "User defined"))))))
419 (put 'company-backends 'safe-local-variable 'company-safe-backends-p)
421 (defcustom company-completion-started-hook nil
422 "Hook run when company starts completing.
423 The hook is called with one argument that is non-nil if the completion was
428 (defcustom company-completion-cancelled-hook nil
429 "Hook run when company cancels completing.
430 The hook is called with one argument that is non-nil if the completion was
435 (defcustom company-completion-finished-hook nil
436 "Hook run when company successfully completes.
437 The hook is called with the selected candidate as an argument."
441 (defcustom company-minimum-prefix-length 3
442 "The minimum prefix length for automatic completion."
444 :type '(integer :tag "prefix length"))
446 (defcustom company-require-match 'company-explicit-action-p
447 "If enabled, disallow non-matching input.
448 This can be a function do determine if a match is required.
450 This can be overridden by the back-end, if it returns t or 'never to
451 'require-match. `company-auto-complete' also takes precedence over this."
453 :type '(choice (const :tag "Off" nil)
454 (function :tag "Predicate function")
455 (const :tag "On, if user interaction took place"
456 'company-explicit-action-p)
457 (const :tag "On" t)))
459 (defcustom company-auto-complete 'company-explicit-action-p
460 "Determines when to auto-complete.
461 If this is enabled, all characters from `company-auto-complete-chars' complete
462 the selected completion. This can also be a function."
464 :type '(choice (const :tag "Off" nil)
465 (function :tag "Predicate function")
466 (const :tag "On, if user interaction took place"
467 'company-explicit-action-p)
468 (const :tag "On" t)))
470 (defcustom company-auto-complete-chars '(?\ ?\( ?\) ?. ?\" ?$ ?\' ?< ?| ?!)
471 "Determines which characters trigger an automatic completion.
472 See `company-auto-complete'. If this is a string, each string character causes
473 completion. If it is a list of syntax description characters (see
474 `modify-syntax-entry'), all characters with that syntax auto-complete.
476 This can also be a function, which is called with the new input and should
477 return non-nil if company should auto-complete.
479 A character that is part of a valid candidate never starts auto-completion."
481 :type '(choice (string :tag "Characters")
483 (const :tag "Whitespace" ?\ )
484 (const :tag "Symbol" ?_)
485 (const :tag "Opening parentheses" ?\()
486 (const :tag "Closing parentheses" ?\))
487 (const :tag "Word constituent" ?w)
488 (const :tag "Punctuation." ?.)
489 (const :tag "String quote." ?\")
490 (const :tag "Paired delimiter." ?$)
491 (const :tag "Expression quote or prefix operator." ?\')
492 (const :tag "Comment starter." ?<)
493 (const :tag "Comment ender." ?>)
494 (const :tag "Character-quote." ?/)
495 (const :tag "Generic string fence." ?|)
496 (const :tag "Generic comment fence." ?!))
497 (function :tag "Predicate function")))
499 (defcustom company-idle-delay .7
500 "The idle delay in seconds until automatic completions starts.
501 A value of nil means never complete automatically, t means complete
502 immediately when a prefix of `company-minimum-prefix-length' is reached."
504 :type '(choice (const :tag "never (nil)" nil)
505 (const :tag "immediate (t)" t)
506 (number :tag "seconds")))
508 (defcustom company-begin-commands t
509 "A list of commands following which company will start completing.
510 If this is t, it will complete after any command. See `company-idle-delay'.
512 Alternatively any command with a non-nil 'company-begin property is treated as
513 if it was on this list."
515 :type '(choice (const :tag "Any command" t)
516 (const :tag "Self insert command" '(self-insert-command))
517 (repeat :tag "Commands" function)))
519 (defcustom company-show-numbers nil
520 "If enabled, show quick-access numbers for the first ten candidates."
522 :type '(choice (const :tag "off" nil)
523 (const :tag "on" t)))
525 (defvar company-end-of-buffer-workaround t
526 "Work around a visualization bug when completing at the end of the buffer.
527 The work-around consists of adding a newline.")
529 ;;; mode ;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;
531 (defvar company-mode-map (make-sparse-keymap)
532 "Keymap used by `company-mode'.")
534 (defvar company-active-map
535 (let ((keymap (make-sparse-keymap)))
536 (define-key keymap "\e\e\e" 'company-abort)
537 (define-key keymap "\C-g" 'company-abort)
538 (define-key keymap (kbd "M-n") 'company-select-next)
539 (define-key keymap (kbd "M-p") 'company-select-previous)
540 (define-key keymap (kbd "<down>") 'company-select-next)
541 (define-key keymap (kbd "<up>") 'company-select-previous)
542 (define-key keymap [down-mouse-1] 'ignore)
543 (define-key keymap [down-mouse-3] 'ignore)
544 (define-key keymap [mouse-1] 'company-complete-mouse)
545 (define-key keymap [mouse-3] 'company-select-mouse)
546 (define-key keymap [up-mouse-1] 'ignore)
547 (define-key keymap [up-mouse-3] 'ignore)
548 (define-key keymap [return] 'company-complete-selection)
549 (define-key keymap [tab] 'company-complete-common)
550 (define-key keymap (kbd "<f1>") 'company-show-doc-buffer)
551 (define-key keymap "\C-w" 'company-show-location)
552 (define-key keymap "\C-s" 'company-search-candidates)
553 (define-key keymap "\C-\M-s" 'company-filter-candidates)
555 (define-key keymap (vector (+ (aref (kbd "M-0") 0) i))
556 `(lambda () (interactive) (company-complete-number ,i))))
559 "Keymap that is enabled during an active completion.")
561 (defvar company--disabled-backends nil)
563 (defun company-init-backend (backend)
564 (and (symbolp backend)
565 (not (fboundp backend))
566 (ignore-errors (require backend nil t)))
568 (if (or (symbolp backend)
572 (funcall backend 'init)
573 (put backend 'company-init t))
575 (put backend 'company-init 'failed)
576 (unless (memq backend company--disabled-backends)
577 (message "Company back-end '%s' could not be initialized:\n%s"
578 backend (error-message-string err)))
579 (push backend company--disabled-backends)
581 (mapc 'company-init-backend backend)))
583 (defvar company-default-lighter " company")
585 (defvar company-lighter company-default-lighter)
586 (make-variable-buffer-local 'company-lighter)
589 (define-minor-mode company-mode
590 "\"complete anything\"; is an in-buffer completion framework.
591 Completion starts automatically, depending on the values
592 `company-idle-delay' and `company-minimum-prefix-length'.
594 Completion can be controlled with the commands:
595 `company-complete-common', `company-complete-selection', `company-complete',
596 `company-select-next', `company-select-previous'. If these commands are
597 called before `company-idle-delay', completion will also start.
599 Completions can be searched with `company-search-candidates' or
600 `company-filter-candidates'. These can be used while completion is
603 The completion data is retrieved using `company-backends' and displayed using
604 `company-frontends'. If you want to start a specific back-end, call it
605 interactively or use `company-begin-backend'.
607 regular keymap (`company-mode-map'):
610 keymap during active completions (`company-active-map'):
612 \\{company-active-map}"
613 nil company-lighter company-mode-map
616 (add-hook 'pre-command-hook 'company-pre-command nil t)
617 (add-hook 'post-command-hook 'company-post-command nil t)
618 (mapc 'company-init-backend company-backends))
619 (remove-hook 'pre-command-hook 'company-pre-command t)
620 (remove-hook 'post-command-hook 'company-post-command t)
622 (kill-local-variable 'company-point)))
624 (define-globalized-minor-mode global-company-mode company-mode
625 (lambda () (company-mode 1)))
627 (defsubst company-assert-enabled ()
629 (company-uninstall-map)
630 (error "Company not enabled")))
632 ;;; keymaps ;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;
634 (defvar company-my-keymap nil)
635 (make-variable-buffer-local 'company-my-keymap)
637 (defvar company-emulation-alist '((t . nil)))
639 (defsubst company-enable-overriding-keymap (keymap)
640 (company-uninstall-map)
641 (setq company-my-keymap keymap))
643 (defun company-ensure-emulation-alist ()
644 (unless (eq 'company-emulation-alist (car emulation-mode-map-alists))
645 (setq emulation-mode-map-alists
646 (cons 'company-emulation-alist
647 (delq 'company-emulation-alist emulation-mode-map-alists)))))
649 (defun company-install-map ()
650 (unless (or (cdar company-emulation-alist)
651 (null company-my-keymap))
652 (setf (cdar company-emulation-alist) company-my-keymap)))
654 (defun company-uninstall-map ()
655 (setf (cdar company-emulation-alist) nil))
658 ;; Emacs calculates the active keymaps before reading the event. That means we
659 ;; cannot change the keymap from a timer. So we send a bogus command.
660 (defun company-ignore ()
662 (setq this-command last-command))
664 (global-set-key '[31415926] 'company-ignore)
666 (defun company-input-noop ()
667 (push 31415926 unread-command-events))
670 ;; posn-col-row is incorrect in older Emacsen when line-spacing is set
671 (defun company--col-row (&optional pos)
672 (let ((posn (posn-at-point pos)))
673 (cons (car (posn-col-row posn)) (cdr (posn-actual-col-row posn)))))
675 (defsubst company--column (&optional pos)
676 (car (posn-col-row (posn-at-point pos))))
678 (defsubst company--row (&optional pos)
679 (cdr (posn-actual-col-row (posn-at-point pos))))
681 ;;; backends ;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;
683 (defun company-grab (regexp &optional expression limit)
684 (when (looking-back regexp limit)
685 (or (match-string-no-properties (or expression 0)) "")))
687 (defun company-grab-line (regexp &optional expression)
688 (company-grab regexp expression (point-at-bol)))
690 (defun company-grab-symbol ()
691 (if (looking-at "\\_>")
692 (buffer-substring (point) (save-excursion (skip-syntax-backward "w_")
694 (unless (and (char-after) (memq (char-syntax (char-after)) '(?w ?_)))
697 (defun company-grab-word ()
698 (if (looking-at "\\>")
699 (buffer-substring (point) (save-excursion (skip-syntax-backward "w")
701 (unless (and (char-after) (eq (char-syntax (char-after)) ?w))
704 (defun company-in-string-or-comment ()
705 (let ((ppss (syntax-ppss)))
706 (or (car (setq ppss (nthcdr 3 ppss)))
707 (car (setq ppss (cdr ppss)))
710 (if (fboundp 'locate-dominating-file)
711 (defalias 'company-locate-dominating-file 'locate-dominating-file)
712 (defun company-locate-dominating-file (file name)
714 (let ((dir (file-name-directory file))
716 (while (not (equal dir prev-dir))
717 (when (file-exists-p (expand-file-name name dir))
720 dir (file-name-directory (directory-file-name dir))))))))
722 (defun company-call-backend (&rest args)
723 (if (functionp company-backend)
724 (apply company-backend args)
725 (apply 'company--multi-backend-adapter company-backend args)))
727 (defun company--multi-backend-adapter (backends command &rest args)
730 (apply 'append (mapcar (lambda (backend) (apply backend command args))
736 (dolist (backend backends)
737 (when (setq value (apply backend command args))
740 ;;; completion mechanism ;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;
742 (defvar company-backend nil)
743 (make-variable-buffer-local 'company-backend)
745 (defvar company-prefix nil)
746 (make-variable-buffer-local 'company-prefix)
748 (defvar company-candidates nil)
749 (make-variable-buffer-local 'company-candidates)
751 (defvar company-candidates-length nil)
752 (make-variable-buffer-local 'company-candidates-length)
754 (defvar company-candidates-cache nil)
755 (make-variable-buffer-local 'company-candidates-cache)
757 (defvar company-candidates-predicate nil)
758 (make-variable-buffer-local 'company-candidates-predicate)
760 (defvar company-common nil)
761 (make-variable-buffer-local 'company-common)
763 (defvar company-selection 0)
764 (make-variable-buffer-local 'company-selection)
766 (defvar company-selection-changed nil)
767 (make-variable-buffer-local 'company-selection-changed)
769 (defvar company--explicit-action nil
770 "Non-nil, if explicit completion took place.")
771 (make-variable-buffer-local 'company--explicit-action)
773 (defvar company--point-max nil)
774 (make-variable-buffer-local 'company--point-max)
776 (defvar company-point nil)
777 (make-variable-buffer-local 'company-point)
779 (defvar company-timer nil)
781 (defvar company-added-newline nil)
782 (make-variable-buffer-local 'company-added-newline)
784 (defsubst company-strip-prefix (str)
785 (substring str (length company-prefix)))
787 (defmacro company-with-candidate-inserted (candidate &rest body)
788 "Evaluate BODY with CANDIDATE temporarily inserted.
789 This is a tool for back-ends that need candidates inserted before they
790 can retrieve meta-data for them."
792 `(let ((inhibit-modification-hooks t)
793 (inhibit-point-motion-hooks t)
794 (modified-p (buffer-modified-p)))
795 (insert (company-strip-prefix ,candidate))
798 (delete-region company-point (point)))))
800 (defun company-explicit-action-p ()
801 "Return whether explicit completion action was taken by the user."
802 (or company--explicit-action
803 company-selection-changed))
805 (defsubst company-reformat (candidate)
806 ;; company-ispell needs this, because the results are always lower-case
807 ;; It's mory efficient to fix it only when they are displayed.
808 (concat company-prefix (substring candidate (length company-prefix))))
810 (defun company--should-complete ()
811 (and (not (or buffer-read-only overriding-terminal-local-map
814 ;; Check if in the middle of entering a key combination.
815 (or (equal (this-command-keys-vector) [])
816 (not (keymapp (key-binding (this-command-keys-vector)))))
817 (eq company-idle-delay t)
818 (or (eq t company-begin-commands)
819 (memq this-command company-begin-commands)
820 (and (symbolp this-command) (get this-command 'company-begin)))
821 (not (and transient-mark-mode mark-active))))
823 (defsubst company-call-frontends (command)
824 (dolist (frontend company-frontends)
826 (funcall frontend command)
827 (error (error "Company: Front-end %s error \"%s\" on command %s"
828 frontend (error-message-string err) command)))))
830 (defsubst company-set-selection (selection &optional force-update)
831 (setq selection (max 0 (min (1- company-candidates-length) selection)))
832 (when (or force-update (not (equal selection company-selection)))
833 (setq company-selection selection
834 company-selection-changed t)
835 (company-call-frontends 'update)))
837 (defun company-apply-predicate (candidates predicate)
839 (dolist (c candidates)
840 (when (funcall predicate c)
844 (defun company-update-candidates (candidates)
845 (setq company-candidates-length (length candidates))
846 (if (> company-selection 0)
847 ;; Try to restore the selection
848 (let ((selected (nth company-selection company-candidates)))
849 (setq company-selection 0
850 company-candidates candidates)
852 (while (and candidates (string< (pop candidates) selected))
853 (incf company-selection))
855 ;; Make sure selection isn't out of bounds.
856 (setq company-selection (min (1- company-candidates-length)
857 company-selection)))))
858 (setq company-selection 0
859 company-candidates candidates))
861 (push (cons company-prefix company-candidates) company-candidates-cache)
863 (let ((completion-ignore-case (company-call-backend 'ignore-case)))
864 (setq company-common (try-completion company-prefix company-candidates)))
865 (when (eq company-common t)
866 (setq company-candidates nil)))
868 (defun company-calculate-candidates (prefix)
869 (let ((candidates (cdr (assoc prefix company-candidates-cache)))
870 (ignore-case (company-call-backend 'ignore-case)))
872 (when company-candidates-cache
873 (let ((len (length prefix))
874 (completion-ignore-case ignore-case)
876 (dotimes (i (1+ len))
877 (when (setq prev (cdr (assoc (substring prefix 0 (- len i))
878 company-candidates-cache)))
879 (setq candidates (all-completions prefix prev))
881 ;; no cache match, call back-end
883 (setq candidates (company-call-backend 'candidates prefix))
884 (when company-candidates-predicate
886 (company-apply-predicate candidates
887 company-candidates-predicate)))
888 (unless (company-call-backend 'sorted)
889 (setq candidates (sort candidates 'string<)))
890 (when (company-call-backend 'duplicates)
892 (let ((c2 candidates))
894 (setcdr c2 (progn (while (equal (pop c2) (car c2)))
898 (not (eq t (compare-strings (car candidates) nil nil
899 prefix nil nil ignore-case)))))
900 ;; Don't start when already completed and unique.
902 ;; Not the right place? maybe when setting?
903 (and company-candidates t))))
905 (defun company-idle-begin (buf win tick pos)
907 (eq buf (current-buffer))
908 (eq win (selected-window))
909 (eq tick (buffer-chars-modified-tick))
911 (not company-candidates)
912 (not (equal (point) company-point))
913 (let ((company-idle-delay t)
914 (company-begin-commands t))
916 (when company-candidates
918 (company-post-command)))))
920 (defun company-auto-begin ()
921 (company-assert-enabled)
923 (not company-candidates)
924 (let ((company-idle-delay t)
925 (company-minimum-prefix-length 0)
926 (company-begin-commands t))
928 ;; Return non-nil if active.
931 (defun company-manual-begin ()
933 (setq company--explicit-action t)
934 (company-auto-begin))
936 (defun company-other-backend (&optional backward)
937 (interactive (list current-prefix-arg))
938 (company-assert-enabled)
940 (let* ((after (cdr (member company-backend company-backends)))
941 (before (cdr (member company-backend (reverse company-backends))))
943 (append before (reverse after))
944 (append after (reverse before)))))
946 (dolist (backend next)
947 (when (ignore-errors (company-begin-backend backend))
949 (company-manual-begin))
950 (unless company-candidates
951 (error "No other back-end")))
953 (defun company-require-match-p ()
954 (let ((backend-value (company-call-backend 'require-match)))
955 (or (eq backend-value t)
956 (and (if (functionp company-require-match)
957 (funcall company-require-match)
958 (eq company-require-match t))
959 (not (eq backend-value 'never))))))
961 (defun company-punctuation-p (input)
962 "Return non-nil, if input starts with punctuation or parentheses."
963 (memq (char-syntax (string-to-char input)) '(?. ?\( ?\))))
965 (defun company-auto-complete-p (input)
966 "Return non-nil, if input starts with punctuation or parentheses."
967 (and (if (functionp company-auto-complete)
968 (funcall company-auto-complete)
969 company-auto-complete)
970 (if (functionp company-auto-complete-chars)
971 (funcall company-auto-complete-chars input)
972 (if (consp company-auto-complete-chars)
973 (memq (char-syntax (string-to-char input))
974 company-auto-complete-chars)
975 (string-match (substring input 0 1) company-auto-complete-chars)))))
977 (defun company--incremental-p ()
978 (and (> (point) company-point)
979 (> (point-max) company--point-max)
980 (not (eq this-command 'backward-delete-char-untabify))
981 (equal (buffer-substring (- company-point (length company-prefix))
985 (defsubst company--string-incremental-p (old-prefix new-prefix)
986 (and (> (length new-prefix) (length old-prefix))
987 (equal old-prefix (substring new-prefix 0 (length old-prefix)))))
989 (defun company--continue-failed (new-prefix)
990 (when (company--incremental-p)
991 (let ((input (buffer-substring-no-properties (point) company-point)))
993 ((company-auto-complete-p input)
996 (goto-char company-point)
997 (company-complete-selection)
999 ((and (company--string-incremental-p company-prefix new-prefix)
1000 (company-require-match-p))
1001 ;; wrong incremental input, but required match
1002 (backward-delete-char (length input))
1004 (message "Matching input is required")
1006 ((equal company-prefix (car company-candidates))
1007 ;; last input was actually success
1008 (company-cancel company-prefix)
1011 (defun company--good-prefix-p (prefix)
1012 (and (or (company-explicit-action-p)
1013 (>= (or (cdr-safe prefix) (length prefix))
1014 company-minimum-prefix-length))
1015 (stringp (or (car-safe prefix) prefix))))
1017 (defun company--continue ()
1018 (when (company-call-backend 'no-cache company-prefix)
1019 ;; Don't complete existing candidates, fetch new ones.
1020 (setq company-candidates-cache nil))
1021 (let* ((new-prefix (company-call-backend 'prefix))
1022 (c (when (and (company--good-prefix-p new-prefix)
1023 (setq new-prefix (or (car-safe new-prefix) new-prefix))
1024 (= (- (point) (length new-prefix))
1025 (- company-point (length company-prefix))))
1026 (setq new-prefix (or (car-safe new-prefix) new-prefix))
1027 (company-calculate-candidates new-prefix))))
1030 ;; t means complete/unique.
1031 (company-cancel new-prefix)
1034 ;; incremental match
1035 (setq company-prefix new-prefix)
1036 (company-update-candidates c)
1038 (t (company--continue-failed new-prefix)))
1041 (defun company--begin-new ()
1043 (dolist (backend (if company-backend
1044 ;; prefer manual override
1045 (list company-backend)
1048 (if (or (symbolp backend)
1049 (functionp backend))
1050 (when (or (not (symbolp backend))
1051 (eq t (get backend 'company-init))
1052 (unless (get backend 'company-init)
1053 (company-init-backend backend)))
1054 (funcall backend 'prefix))
1055 (company--multi-backend-adapter backend 'prefix)))
1057 (when (company--good-prefix-p prefix)
1058 (setq prefix (or (car-safe prefix) prefix)
1059 company-backend backend
1060 c (company-calculate-candidates prefix))
1061 ;; t means complete/unique. We don't start, so no hooks.
1063 (when company--explicit-action
1064 (message "No completion found"))
1065 (setq company-prefix prefix)
1066 (when (symbolp backend)
1067 (setq company-lighter (concat " " (symbol-name backend))))
1068 (company-update-candidates c)
1069 (run-hook-with-args 'company-completion-started-hook
1070 (company-explicit-action-p))
1071 (company-call-frontends 'show)))
1074 (defun company-begin ()
1075 (or (and company-candidates (company--continue))
1076 (and (company--should-complete) (company--begin-new)))
1077 (when company-candidates
1078 (when (and company-end-of-buffer-workaround (eobp))
1079 (save-excursion (insert "\n"))
1080 (setq company-added-newline (buffer-chars-modified-tick)))
1081 (setq company-point (point)
1082 company--point-max (point-max))
1083 (company-ensure-emulation-alist)
1084 (company-enable-overriding-keymap company-active-map)
1085 (company-call-frontends 'update)))
1087 (defun company-cancel (&optional result)
1088 (and company-added-newline
1089 (> (point-max) (point-min))
1090 (let ((tick (buffer-chars-modified-tick)))
1091 (delete-region (1- (point-max)) (point-max))
1092 (equal tick company-added-newline))
1093 ;; Only set unmodified when tick remained the same since insert.
1094 (set-buffer-modified-p nil))
1095 (when company-prefix
1096 (if (stringp result)
1098 (company-call-backend 'pre-completion result)
1099 (run-hook-with-args 'company-completion-finished-hook result)
1100 (company-call-backend 'post-completion result))
1101 (run-hook-with-args 'company-completion-cancelled-hook result)))
1102 (setq company-added-newline nil
1105 company-candidates nil
1106 company-candidates-length nil
1107 company-candidates-cache nil
1108 company-candidates-predicate nil
1111 company-selection-changed nil
1112 company--explicit-action nil
1113 company-lighter company-default-lighter
1114 company--point-max nil
1117 (cancel-timer company-timer))
1118 (company-search-mode 0)
1119 (company-call-frontends 'hide)
1120 (company-enable-overriding-keymap nil))
1122 (defun company-abort ()
1125 ;; Don't start again, unless started manually.
1126 (setq company-point (point)))
1128 (defun company-finish (result)
1129 (insert (company-strip-prefix result))
1130 (company-cancel result)
1131 ;; Don't start again, unless started manually.
1132 (setq company-point (point)))
1134 (defsubst company-keep (command)
1135 (and (symbolp command) (get command 'company-keep)))
1137 (defun company-pre-command ()
1138 (unless (company-keep this-command)
1140 (when company-candidates
1141 (company-call-frontends 'pre-command))
1142 (error (message "Company: An error occurred in pre-command")
1143 (message "%s" (error-message-string err))
1146 (cancel-timer company-timer)
1147 (setq company-timer nil))
1148 (company-uninstall-map))
1150 (defun company-post-command ()
1151 (unless (company-keep this-command)
1154 (unless (equal (point) company-point)
1156 (if company-candidates
1157 (company-call-frontends 'post-command)
1158 (and (numberp company-idle-delay)
1159 (or (eq t company-begin-commands)
1160 (memq this-command company-begin-commands))
1162 (run-with-timer company-idle-delay nil
1164 (current-buffer) (selected-window)
1165 (buffer-chars-modified-tick) (point))))))
1166 (error (message "Company: An error occurred in post-command")
1167 (message "%s" (error-message-string err))
1169 (company-install-map))
1171 ;;; search ;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;
1173 (defvar company-search-string nil)
1174 (make-variable-buffer-local 'company-search-string)
1176 (defvar company-search-lighter " Search: \"\"")
1177 (make-variable-buffer-local 'company-search-lighter)
1179 (defvar company-search-old-map nil)
1180 (make-variable-buffer-local 'company-search-old-map)
1182 (defvar company-search-old-selection 0)
1183 (make-variable-buffer-local 'company-search-old-selection)
1185 (defun company-search (text lines)
1186 (let ((quoted (regexp-quote text))
1188 (dolist (line lines)
1189 (when (string-match quoted line (length company-prefix))
1193 (defun company-search-printing-char ()
1195 (company-search-assert-enabled)
1196 (setq company-search-string
1197 (concat (or company-search-string "") (string last-command-event))
1198 company-search-lighter (concat " Search: \"" company-search-string
1200 (let ((pos (company-search company-search-string
1201 (nthcdr company-selection company-candidates))))
1204 (company-set-selection (+ company-selection pos) t))))
1206 (defun company-search-repeat-forward ()
1207 "Repeat the incremental search in completion candidates forward."
1209 (company-search-assert-enabled)
1210 (let ((pos (company-search company-search-string
1211 (cdr (nthcdr company-selection
1212 company-candidates)))))
1215 (company-set-selection (+ company-selection pos 1) t))))
1217 (defun company-search-repeat-backward ()
1218 "Repeat the incremental search in completion candidates backwards."
1220 (company-search-assert-enabled)
1221 (let ((pos (company-search company-search-string
1222 (nthcdr (- company-candidates-length
1224 (reverse company-candidates)))))
1227 (company-set-selection (- company-selection pos 1) t))))
1229 (defun company-create-match-predicate ()
1230 (setq company-candidates-predicate
1231 `(lambda (candidate)
1232 ,(if company-candidates-predicate
1233 `(and (string-match ,company-search-string candidate)
1234 (funcall ,company-candidates-predicate
1236 `(string-match ,company-search-string candidate))))
1237 (company-update-candidates
1238 (company-apply-predicate company-candidates company-candidates-predicate))
1239 ;; Invalidate cache.
1240 (setq company-candidates-cache (cons company-prefix company-candidates)))
1242 (defun company-filter-printing-char ()
1244 (company-search-assert-enabled)
1245 (company-search-printing-char)
1246 (company-create-match-predicate)
1247 (company-call-frontends 'update))
1249 (defun company-search-kill-others ()
1250 "Limit the completion candidates to the ones matching the search string."
1252 (company-search-assert-enabled)
1253 (company-create-match-predicate)
1254 (company-search-mode 0)
1255 (company-call-frontends 'update))
1257 (defun company-search-abort ()
1258 "Abort searching the completion candidates."
1260 (company-search-assert-enabled)
1261 (company-set-selection company-search-old-selection t)
1262 (company-search-mode 0))
1264 (defun company-search-other-char ()
1266 (company-search-assert-enabled)
1267 (company-search-mode 0)
1268 (when last-input-event
1269 (clear-this-command-keys t)
1270 (setq unread-command-events (list last-input-event))))
1272 (defvar company-search-map
1274 (keymap (make-keymap)))
1275 (if (fboundp 'max-char)
1276 (set-char-table-range (nth 1 keymap) (cons #x100 (max-char))
1277 'company-search-printing-char)
1279 ;; obselete in Emacs 23
1280 (let ((l (generic-character-list))
1281 (table (nth 1 keymap)))
1283 (set-char-table-default table (car l) 'company-search-printing-char)
1284 (setq l (cdr l))))))
1285 (define-key keymap [t] 'company-search-other-char)
1287 (define-key keymap (make-string 1 i) 'company-search-other-char)
1290 (define-key keymap (vector i) 'company-search-printing-char)
1292 (let ((meta-map (make-sparse-keymap)))
1293 (define-key keymap (char-to-string meta-prefix-char) meta-map)
1294 (define-key keymap [escape] meta-map))
1295 (define-key keymap (vector meta-prefix-char t) 'company-search-other-char)
1296 (define-key keymap "\e\e\e" 'company-search-other-char)
1297 (define-key keymap [escape escape escape] 'company-search-other-char)
1299 (define-key keymap "\C-g" 'company-search-abort)
1300 (define-key keymap "\C-s" 'company-search-repeat-forward)
1301 (define-key keymap "\C-r" 'company-search-repeat-backward)
1302 (define-key keymap "\C-o" 'company-search-kill-others)
1304 "Keymap used for incrementally searching the completion candidates.")
1306 (define-minor-mode company-search-mode
1307 "Search mode for completion candidates.
1308 Don't start this directly, use `company-search-candidates' or
1309 `company-filter-candidates'."
1310 nil company-search-lighter nil
1311 (if company-search-mode
1312 (if (company-manual-begin)
1314 (setq company-search-old-selection company-selection)
1315 (company-call-frontends 'update))
1316 (setq company-search-mode nil))
1317 (kill-local-variable 'company-search-string)
1318 (kill-local-variable 'company-search-lighter)
1319 (kill-local-variable 'company-search-old-selection)
1320 (company-enable-overriding-keymap company-active-map)))
1322 (defsubst company-search-assert-enabled ()
1323 (company-assert-enabled)
1324 (unless company-search-mode
1325 (company-uninstall-map)
1326 (error "Company not in search mode")))
1328 (defun company-search-candidates ()
1329 "Start searching the completion candidates incrementally.
1331 \\<company-search-map>Search can be controlled with the commands:
1332 - `company-search-repeat-forward' (\\[company-search-repeat-forward])
1333 - `company-search-repeat-backward' (\\[company-search-repeat-backward])
1334 - `company-search-abort' (\\[company-search-abort])
1336 Regular characters are appended to the search string.
1338 The command `company-search-kill-others' (\\[company-search-kill-others]) uses
1339 the search string to limit the completion candidates."
1341 (company-search-mode 1)
1342 (company-enable-overriding-keymap company-search-map))
1344 (defvar company-filter-map
1345 (let ((keymap (make-keymap)))
1346 (define-key keymap [remap company-search-printing-char]
1347 'company-filter-printing-char)
1348 (set-keymap-parent keymap company-search-map)
1350 "Keymap used for incrementally searching the completion candidates.")
1352 (defun company-filter-candidates ()
1353 "Start filtering the completion candidates incrementally.
1354 This works the same way as `company-search-candidates' immediately
1355 followed by `company-search-kill-others' after each input."
1357 (company-search-mode 1)
1358 (company-enable-overriding-keymap company-filter-map))
1360 ;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;
1362 (defun company-select-next ()
1363 "Select the next candidate in the list."
1365 (when (company-manual-begin)
1366 (company-set-selection (1+ company-selection))))
1368 (defun company-select-previous ()
1369 "Select the previous candidate in the list."
1371 (when (company-manual-begin)
1372 (company-set-selection (1- company-selection))))
1374 (defun company-select-mouse (event)
1375 "Select the candidate picked by the mouse."
1377 (when (nth 4 (event-start event))
1378 (company-set-selection (- (cdr (posn-actual-col-row (event-start event)))
1383 (defun company-complete-mouse (event)
1384 "Complete the candidate picked by the mouse."
1386 (when (company-select-mouse event)
1387 (company-complete-selection)))
1389 (defun company-complete-selection ()
1390 "Complete the selected candidate."
1392 (when (company-manual-begin)
1393 (company-finish (nth company-selection company-candidates))))
1395 (defun company-complete-common ()
1396 "Complete the common part of all candidates."
1398 (when (company-manual-begin)
1399 (if (and (not (cdr company-candidates))
1400 (equal company-common (car company-candidates)))
1401 (company-complete-selection)
1402 (insert (company-strip-prefix company-common)))))
1404 (defun company-complete ()
1405 "Complete the common part of all candidates or the current selection.
1406 The first time this is called, the common part is completed, the second time, or
1407 when the selection has been changed, the selected candidate is completed."
1409 (when (company-manual-begin)
1410 (if (or company-selection-changed
1411 (eq last-command 'company-complete-common))
1412 (call-interactively 'company-complete-selection)
1413 (call-interactively 'company-complete-common)
1414 (setq this-command 'company-complete-common))))
1416 (defun company-complete-number (n)
1417 "Complete the Nth candidate.
1418 To show the number next to the candidates in some back-ends, enable
1419 `company-show-numbers'."
1420 (when (company-manual-begin)
1421 (and (< n 1) (> n company-candidates-length)
1422 (error "No candidate number %d" n))
1424 (company-finish (nth n company-candidates))))
1426 ;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;
1428 (defconst company-space-strings-limit 100)
1430 (defconst company-space-strings
1432 (dotimes (i company-space-strings-limit)
1433 (push (make-string (- company-space-strings-limit 1 i) ?\ ) lst))
1434 (apply 'vector lst)))
1436 (defsubst company-space-string (len)
1437 (if (< len company-space-strings-limit)
1438 (aref company-space-strings len)
1439 (make-string len ?\ )))
1441 (defsubst company-safe-substring (str from &optional to)
1442 (if (> from (string-width str))
1446 (move-to-column from)
1447 (let ((beg (point)))
1451 (concat (buffer-substring beg (point))
1452 (let ((padding (- to (current-column))))
1454 (company-space-string padding)))))
1455 (buffer-substring beg (point-max)))))))
1457 ;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;
1459 (defvar company-last-metadata nil)
1460 (make-variable-buffer-local 'company-last-metadata)
1462 (defun company-fetch-metadata ()
1463 (let ((selected (nth company-selection company-candidates)))
1464 (unless (equal selected (car company-last-metadata))
1465 (setq company-last-metadata
1466 (cons selected (company-call-backend 'meta selected))))
1467 (cdr company-last-metadata)))
1469 (defun company-doc-buffer (&optional string)
1470 (with-current-buffer (get-buffer-create "*Company meta-data*")
1474 (defvar company--electric-commands
1475 '(scroll-other-window scroll-other-window-down)
1476 "List of Commands that won't break out of electric commands.")
1478 (defmacro company--electric-do (&rest body)
1479 (declare (indent 0) (debug t))
1480 `(when (company-manual-begin)
1481 (save-window-excursion
1482 (let ((height (window-height))
1483 (row (company--row))
1486 (and (< (window-height) height)
1487 (< (- (window-height) row 2) company-tooltip-limit)
1488 (recenter (- (window-height) row 2)))
1489 (while (memq (setq cmd (key-binding (vector (list (read-event)))))
1490 company--electric-commands)
1491 (call-interactively cmd))
1492 (when last-input-event
1493 (clear-this-command-keys t)
1494 (setq unread-command-events (list last-input-event)))))))
1496 (defun company-show-doc-buffer ()
1497 "Temporarily show a buffer with the complete documentation for the selection."
1499 (company--electric-do
1500 (let* ((selected (nth company-selection company-candidates))
1501 (doc-buffer (or (company-call-backend 'doc-buffer selected)
1502 (error "No documentation available"))))
1503 (with-current-buffer doc-buffer
1504 (goto-char (point-min)))
1505 (display-buffer doc-buffer t))))
1506 (put 'company-show-doc-buffer 'company-keep t)
1508 (defun company-show-location ()
1509 "Temporarily display a buffer showing the selected candidate in context."
1511 (company--electric-do
1512 (let* ((selected (nth company-selection company-candidates))
1513 (location (company-call-backend 'location selected))
1514 (pos (or (cdr location) (error "No location available")))
1515 (buffer (or (and (bufferp (car location)) (car location))
1516 (find-file-noselect (car location) t))))
1517 (with-selected-window (display-buffer buffer t)
1520 (if (bufferp (car location))
1522 (goto-char (point-min))
1523 (forward-line (1- pos))))
1524 (set-window-start nil (point))))))
1525 (put 'company-show-location 'company-keep t)
1527 ;;; package functions ;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;
1529 (defvar company-callback nil)
1530 (make-variable-buffer-local 'company-callback)
1532 (defvar company-begin-with-marker nil)
1533 (make-variable-buffer-local 'company-begin-with-marker)
1535 (defun company-remove-callback (&optional ignored)
1536 (remove-hook 'company-completion-finished-hook company-callback t)
1537 (remove-hook 'company-completion-cancelled-hook 'company-remove-callback t)
1538 (remove-hook 'company-completion-finished-hook 'company-remove-callback t)
1539 (when company-begin-with-marker
1540 (set-marker company-begin-with-marker nil)))
1542 (defun company-begin-backend (backend &optional callback)
1543 "Start a completion at point using BACKEND."
1544 (interactive (let ((val (completing-read "Company back-end: "
1546 'functionp nil "company-")))
1548 (list (intern val)))))
1549 (when (setq company-callback callback)
1550 (add-hook 'company-completion-finished-hook company-callback nil t))
1551 (add-hook 'company-completion-cancelled-hook 'company-remove-callback nil t)
1552 (add-hook 'company-completion-finished-hook 'company-remove-callback nil t)
1553 (setq company-backend backend)
1554 ;; Return non-nil if active.
1555 (or (company-manual-begin)
1556 (error "Cannot complete at point")))
1558 (defun company-begin-with (candidates
1559 &optional prefix-length require-match callback)
1560 "Start a completion at point.
1561 CANDIDATES is the list of candidates to use and PREFIX-LENGTH is the length of
1562 the prefix that already is in the buffer before point. It defaults to 0.
1564 CALLBACK is a function called with the selected result if the user successfully
1565 completes the input.
1568 \(company-begin-with '\(\"foo\" \"foobar\" \"foobarbaz\"\)\)"
1569 (setq company-begin-with-marker (copy-marker (point) t))
1570 (company-begin-backend
1571 `(lambda (command &optional arg &rest ignored)
1573 ((eq command 'prefix)
1574 (when (equal (point) (marker-position company-begin-with-marker))
1575 (buffer-substring ,(- (point) (or prefix-length 0)) (point))))
1576 ((eq command 'candidates)
1577 (all-completions arg ',candidates))
1578 ((eq command 'require-match)
1582 ;;; pseudo-tooltip ;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;
1584 (defvar company-pseudo-tooltip-overlay nil)
1585 (make-variable-buffer-local 'company-pseudo-tooltip-overlay)
1587 (defvar company-tooltip-offset 0)
1588 (make-variable-buffer-local 'company-tooltip-offset)
1590 (defun company-pseudo-tooltip-update-offset (selection num-lines limit)
1593 (setq company-tooltip-offset
1594 (max (min selection company-tooltip-offset)
1595 (- selection -1 limit)))
1597 (when (<= company-tooltip-offset 1)
1599 (setq company-tooltip-offset 0))
1601 (when (>= company-tooltip-offset (- num-lines limit 1))
1603 (when (= selection (1- num-lines))
1604 (decf company-tooltip-offset)
1605 (when (<= company-tooltip-offset 1)
1606 (setq company-tooltip-offset 0)
1613 (defsubst company-round-tab (arg)
1614 (* (/ (+ arg tab-width) tab-width) tab-width))
1616 (defun company-untabify (str)
1617 (let* ((pieces (split-string str "\t"))
1620 (setcar copy (company-safe-substring
1621 (car copy) 0 (company-round-tab (string-width (car copy)))))
1623 (apply 'concat pieces)))
1625 (defun company-fill-propertize (line width selected)
1626 (setq line (company-safe-substring line 0 width))
1627 (add-text-properties 0 width '(face company-tooltip
1628 mouse-face company-tooltip-mouse)
1630 (add-text-properties 0 (length company-common)
1631 '(face company-tooltip-common
1632 mouse-face company-tooltip-mouse)
1635 (if (and company-search-string
1636 (string-match (regexp-quote company-search-string) line
1637 (length company-prefix)))
1639 (add-text-properties (match-beginning 0) (match-end 0)
1640 '(face company-tooltip-selection)
1642 (when (< (match-beginning 0) (length company-common))
1643 (add-text-properties (match-beginning 0) (length company-common)
1644 '(face company-tooltip-common-selection)
1646 (add-text-properties 0 width '(face company-tooltip-selection
1647 mouse-face company-tooltip-selection)
1649 (add-text-properties 0 (length company-common)
1650 '(face company-tooltip-common-selection
1651 mouse-face company-tooltip-selection)
1657 (defun company-buffer-lines (beg end)
1660 (while (and (zerop (forward-line 1))
1662 (push (buffer-substring beg (min end (1- (point)))) lines)
1664 (unless (eq beg end)
1665 (push (buffer-substring beg end) lines))
1668 (defsubst company-modify-line (old new offset)
1669 (concat (company-safe-substring old 0 offset)
1671 (company-safe-substring old (+ offset (length new)))))
1673 (defsubst company--length-limit (lst limit)
1674 (if (nthcdr limit lst)
1678 (defun company--replacement-string (lines old column nl &optional align-top)
1680 (let ((width (length (car lines))))
1681 (when (> width (- (window-width) column))
1682 (setq column (max 0 (- (window-width) width)))))
1686 ;; untouched lines first
1687 (dotimes (i (- (length old) (length lines)))
1688 (push (pop old) new)))
1689 ;; length into old lines.
1691 (push (company-modify-line (pop old) (pop lines) column) new))
1692 ;; Append whole new lines.
1694 (push (concat (company-space-string column) (pop lines)) new))
1696 (let ((str (concat (when nl "\n")
1697 (mapconcat 'identity (nreverse new) "\n")
1699 (font-lock-append-text-property 0 (length str) 'face 'default str)
1702 (defun company--create-lines (selection limit)
1704 (let ((len company-candidates-length)
1713 ;; Scroll to offset.
1714 (setq limit (company-pseudo-tooltip-update-offset selection len limit))
1716 (when (> company-tooltip-offset 0)
1717 (setq previous (format "...(%d)" company-tooltip-offset)))
1719 (setq remainder (- len limit company-tooltip-offset)
1720 remainder (when (> remainder 0)
1721 (setq remainder (format "...(%d)" remainder))))
1723 (decf selection company-tooltip-offset)
1724 (setq width (max (length previous) (length remainder))
1725 lines (nthcdr company-tooltip-offset company-candidates)
1730 (setq width (max (length (pop lines-copy)) width)))
1731 (setq width (min width (window-width)))
1733 (setq lines-copy lines)
1735 ;; number can make tooltip too long
1736 (when company-show-numbers
1737 (setq numbered company-tooltip-offset))
1740 (push (propertize (company-safe-substring previous 0 width)
1741 'face 'company-tooltip)
1745 (push (company-fill-propertize
1746 (if (>= numbered 10)
1747 (company-reformat (pop lines))
1750 (company-safe-substring (company-reformat (pop lines))
1753 width (equal i selection))
1757 (push (propertize (company-safe-substring remainder 0 width)
1758 'face 'company-tooltip)
1761 (setq lines (nreverse new))))
1765 (defsubst company--window-inner-height ()
1766 (let ((edges (window-inside-edges (selected-window))))
1767 (- (nth 3 edges) (nth 1 edges))))
1769 (defsubst company--pseudo-tooltip-height ()
1770 "Calculate the appropriate tooltip height.
1771 Returns a negative number if the tooltip should be displayed above point."
1772 (let* ((lines (count-lines (window-start) (point-at-bol)))
1773 (below (- (company--window-inner-height) 1 lines)))
1774 (if (and (< below (min company-tooltip-minimum company-candidates-length))
1776 (- (max 3 (min company-tooltip-limit lines)))
1777 (max 3 (min company-tooltip-limit below)))))
1779 (defun company-pseudo-tooltip-show (row column selection)
1780 (company-pseudo-tooltip-hide)
1785 (let* ((height (company--pseudo-tooltip-height))
1789 (setq row (+ row height -1)
1792 (let* ((nl (< (move-to-window-line row) row))
1794 (end (save-excursion
1795 (move-to-window-line (+ row (abs height)))
1797 (ov (make-overlay beg end))
1798 (args (list (mapcar 'company-untabify
1799 (company-buffer-lines beg end))
1802 (setq company-pseudo-tooltip-overlay ov)
1803 (overlay-put ov 'company-replacement-args args)
1804 (overlay-put ov 'company-before
1805 (apply 'company--replacement-string
1806 (company--create-lines selection (abs height))
1809 (overlay-put ov 'company-column column)
1810 (overlay-put ov 'company-height (abs height))
1811 (overlay-put ov 'window (selected-window))))))
1813 (defun company-pseudo-tooltip-show-at-point (pos)
1814 (let ((col-row (company--col-row pos)))
1816 (company-pseudo-tooltip-show (1+ (cdr col-row)) (car col-row)
1817 company-selection))))
1819 (defun company-pseudo-tooltip-edit (lines selection)
1820 (let ((column (overlay-get company-pseudo-tooltip-overlay 'company-column))
1821 (height (overlay-get company-pseudo-tooltip-overlay 'company-height)))
1822 (overlay-put company-pseudo-tooltip-overlay 'company-before
1823 (apply 'company--replacement-string
1824 (company--create-lines selection height)
1825 (overlay-get company-pseudo-tooltip-overlay
1826 'company-replacement-args)))))
1828 (defun company-pseudo-tooltip-hide ()
1829 (when company-pseudo-tooltip-overlay
1830 (delete-overlay company-pseudo-tooltip-overlay)
1831 (setq company-pseudo-tooltip-overlay nil)))
1833 (defun company-pseudo-tooltip-hide-temporarily ()
1834 (when (overlayp company-pseudo-tooltip-overlay)
1835 (overlay-put company-pseudo-tooltip-overlay 'invisible nil)
1836 (overlay-put company-pseudo-tooltip-overlay 'before-string nil)))
1838 (defun company-pseudo-tooltip-unhide ()
1839 (when company-pseudo-tooltip-overlay
1840 (overlay-put company-pseudo-tooltip-overlay 'invisible t)
1841 (overlay-put company-pseudo-tooltip-overlay 'before-string
1842 (overlay-get company-pseudo-tooltip-overlay 'company-before))
1843 (overlay-put company-pseudo-tooltip-overlay 'window (selected-window))))
1845 (defun company-pseudo-tooltip-frontend (command)
1846 "A `company-mode' front-end similar to a tool-tip but based on overlays."
1848 (pre-command (company-pseudo-tooltip-hide-temporarily))
1850 (let ((old-height (if (overlayp company-pseudo-tooltip-overlay)
1851 (overlay-get company-pseudo-tooltip-overlay
1854 (new-height (company--pseudo-tooltip-height)))
1855 (unless (and (>= (* old-height new-height) 0)
1856 (>= (abs old-height) (abs new-height)))
1858 (company-pseudo-tooltip-show-at-point (- (point)
1859 (length company-prefix)))))
1860 (company-pseudo-tooltip-unhide))
1861 (hide (company-pseudo-tooltip-hide)
1862 (setq company-tooltip-offset 0))
1863 (update (when (overlayp company-pseudo-tooltip-overlay)
1864 (company-pseudo-tooltip-edit company-candidates
1865 company-selection)))))
1867 (defun company-pseudo-tooltip-unless-just-one-frontend (command)
1868 "`company-pseudo-tooltip-frontend', but not shown for single candidates."
1869 (unless (and (eq command 'post-command)
1870 (not (cdr company-candidates)))
1871 (company-pseudo-tooltip-frontend command)))
1873 ;;; overlay ;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;
1875 (defvar company-preview-overlay nil)
1876 (make-variable-buffer-local 'company-preview-overlay)
1878 (defun company-preview-show-at-point (pos)
1879 (company-preview-hide)
1881 (setq company-preview-overlay (make-overlay pos pos))
1883 (let ((completion(nth company-selection company-candidates)))
1884 (setq completion (propertize completion 'face 'company-preview))
1885 (add-text-properties 0 (length company-common)
1886 '(face company-preview-common) completion)
1888 ;; Add search string
1889 (and company-search-string
1890 (string-match (regexp-quote company-search-string) completion)
1891 (add-text-properties (match-beginning 0)
1893 '(face company-preview-search)
1896 (setq completion (company-strip-prefix completion))
1898 (and (equal pos (point))
1899 (not (equal completion ""))
1900 (add-text-properties 0 1 '(cursor t) completion))
1902 (overlay-put company-preview-overlay 'after-string completion)
1903 (overlay-put company-preview-overlay 'window (selected-window))))
1905 (defun company-preview-hide ()
1906 (when company-preview-overlay
1907 (delete-overlay company-preview-overlay)
1908 (setq company-preview-overlay nil)))
1910 (defun company-preview-frontend (command)
1911 "A `company-mode' front-end showing the selection as if it had been inserted."
1913 (pre-command (company-preview-hide))
1914 (post-command (company-preview-show-at-point (point)))
1915 (hide (company-preview-hide))))
1917 (defun company-preview-if-just-one-frontend (command)
1918 "`company-preview-frontend', but only shown for single candidates."
1919 (unless (and (eq command 'post-command)
1920 (cdr company-candidates))
1921 (company-preview-frontend command)))
1923 ;;; echo ;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;
1925 (defvar company-echo-last-msg nil)
1926 (make-variable-buffer-local 'company-echo-last-msg)
1928 (defun company-echo-show (&optional getter)
1930 (setq company-echo-last-msg (funcall getter)))
1931 (let ((message-log-max nil))
1932 (if company-echo-last-msg
1933 (message "%s" company-echo-last-msg)
1936 (defsubst company-echo-show-soon (&optional getter)
1937 (when company-echo-timer
1938 (cancel-timer company-echo-timer))
1939 (setq company-echo-timer (run-with-timer 0 nil 'company-echo-show getter)))
1941 (defsubst company-echo-show-when-idle (&optional getter)
1943 (company-echo-show getter)))
1945 (defsubst company-echo-show-when-not-busy (&optional getter)
1946 "Run `company-echo-show' with arg GETTER once Emacs isn't busy."
1947 (when (sit-for company-echo-delay)
1948 (company-echo-show getter)))
1950 (defun company-echo-format ()
1952 (let ((limit (window-width (minibuffer-window)))
1954 ;; Roll to selection.
1955 (candidates (nthcdr company-selection company-candidates))
1956 (i (if company-show-numbers company-selection 99999))
1960 (setq comp (company-reformat (pop candidates))
1961 len (+ len 1 (length comp)))
1965 (setq comp (propertize (format "%d: %s" i comp)
1966 'face 'company-echo))
1969 (add-text-properties 3 (+ 3 (length company-common))
1970 '(face company-echo-common) comp))
1971 (setq comp (propertize comp 'face 'company-echo))
1972 (add-text-properties 0 (length company-common)
1973 '(face company-echo-common) comp))
1975 (setq candidates nil)
1978 (mapconcat 'identity (nreverse msg) " ")))
1980 (defun company-echo-strip-common-format ()
1982 (let ((limit (window-width (minibuffer-window)))
1983 (len (+ (length company-prefix) 2))
1984 ;; Roll to selection.
1985 (candidates (nthcdr company-selection company-candidates))
1986 (i (if company-show-numbers company-selection 99999))
1990 (setq comp (company-strip-prefix (pop candidates))
1991 len (+ len 2 (length comp)))
1994 (setq comp (format "%s (%d)" comp i))
1998 (setq candidates nil)
1999 (push (propertize comp 'face 'company-echo) msg)))
2001 (concat (propertize company-prefix 'face 'company-echo-common) "{"
2002 (mapconcat 'identity (nreverse msg) ", ")
2005 (defun company-echo-hide ()
2006 (unless (equal company-echo-last-msg "")
2007 (setq company-echo-last-msg "")
2008 (company-echo-show)))
2010 (defun company-echo-frontend (command)
2011 "A `company-mode' front-end showing the candidates in the echo area."
2013 (post-command (company-echo-show-soon 'company-echo-format))
2014 (hide (company-echo-hide))))
2016 (defun company-echo-strip-common-frontend (command)
2017 "A `company-mode' front-end showing the candidates in the echo area."
2019 (post-command (company-echo-show-soon 'company-echo-strip-common-format))
2020 (hide (company-echo-hide))))
2022 (defun company-echo-metadata-frontend (command)
2023 "A `company-mode' front-end showing the documentation in the echo area."
2025 (post-command (company-echo-show-when-idle 'company-fetch-metadata))
2026 (hide (company-echo-hide))))
2028 ;; templates ;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;
2030 (autoload 'company-template-declare-template "company-template")
2033 ;;; company.el ends here