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.
81 ;; `company-ropemacs' now provides location and docs. (Fernando H. Silva)
82 ;; Added `company-with-candidate-inserted' macro.
83 ;; Added `company-clang' back-end.
84 ;; Added new mechanism for non-consecutive insertion.
85 ;; (So far only used by clang for ObjC.)
86 ;; The semantic back-end now shows meta information for local symbols.
87 ;; Added compatibility for CEDET in Emacs 23.2 and from CVS. (Oleg Andreev)
90 ;; Added `company-other-backend'.
91 ;; Idle completion no longer interrupts multi-key command input.
92 ;; Added `company-ropemacs' and `company-pysmell' back-ends.
95 ;; In C modes . and -> now count towards `company-minimum-prefix-length'.
96 ;; Reverted default front-end back to `company-preview-if-just-one-frontend'.
97 ;; The pseudo tooltip will no longer be clipped at the right window edge.
98 ;; Added `company-tooltip-minimum'.
99 ;; Windows compatibility fixes.
101 ;; 2009-04-19 (0.4.1)
102 ;; Added `global-company-mode'.
103 ;; Performance enhancements.
104 ;; Added `company-eclim' back-end.
105 ;; Added safer workaround for Emacs `posn-col-row' bug.
108 ;; Automatic completion is now aborted if the prefix gets too short.
109 ;; Added option `company-dabbrev-time-limit'.
110 ;; `company-backends' now supports merging back-ends.
111 ;; Added back-end `company-dabbrev-code' for generic code.
112 ;; Fixed `company-begin-with'.
114 ;; 2009-04-15 (0.3.1)
115 ;; Added 'stop prefix to prevent dabbrev from completing inside of symbols.
116 ;; Fixed issues with tabbar-mode and line-spacing.
117 ;; Performance enhancements.
120 ;; Added `company-begin-commands' option.
121 ;; Added abbrev, tempo and Xcode back-ends.
122 ;; Back-ends are now interactive. You can start them with M-x backend-name.
123 ;; Added `company-begin-with' for starting company from elisp-code.
125 ;; Added `company-require-match' and `company-auto-complete' options.
127 ;; 2009-04-05 (0.2.1)
128 ;; Improved Emacs Lisp back-end behavior for local variables.
129 ;; Added `company-elisp-detect-function-context' option.
130 ;; The mouse can now be used for selection.
133 ;; Added `company-show-location'.
134 ;; Added etags back-end.
135 ;; Added work-around for end-of-buffer bug.
136 ;; Added `company-filter-candidates'.
137 ;; More local Lisp variables are now included in the candidates.
139 ;; 2009-03-21 (0.1.5)
140 ;; Fixed elisp documentation buffer always showing the same doc.
141 ;; Added `company-echo-strip-common-frontend'.
142 ;; Added `company-show-numbers' option and M-0 ... M-9 default bindings.
143 ;; Don't hide the echo message if it isn't shown.
150 (eval-when-compile (require 'cl))
152 (add-to-list 'debug-ignored-errors "^.* frontend cannot be used twice$")
153 (add-to-list 'debug-ignored-errors "^Echo area cannot be used twice$")
154 (add-to-list 'debug-ignored-errors "^No \\(document\\|loc\\)ation available$")
155 (add-to-list 'debug-ignored-errors "^Company not ")
156 (add-to-list 'debug-ignored-errors "^No candidate number ")
157 (add-to-list 'debug-ignored-errors "^Cannot complete at point$")
158 (add-to-list 'debug-ignored-errors "^No other back-end$")
160 (defgroup company nil
161 "Extensible inline text completion mechanism"
166 (defface company-tooltip
167 '((t :background "yellow"
168 :foreground "black"))
169 "Face used for the tool tip."
172 (defface company-tooltip-selection
173 '((default :inherit company-tooltip)
174 (((class color) (min-colors 88)) (:background "orange1"))
175 (t (:background "green")))
176 "Face used for the selection in the tool tip."
179 (defface company-tooltip-mouse
180 '((default :inherit highlight))
181 "Face used for the tool tip item under the mouse."
184 (defface company-tooltip-common
185 '((t :inherit company-tooltip
187 "Face used for the common completion in the tool tip."
190 (defface company-tooltip-common-selection
191 '((t :inherit company-tooltip-selection
193 "Face used for the selected common completion in the tool tip."
196 (defface company-preview
197 '((t :background "blue4"
198 :foreground "wheat"))
199 "Face used for the completion preview."
202 (defface company-preview-common
203 '((t :inherit company-preview
205 "Face used for the common part of the completion preview."
208 (defface company-preview-search
209 '((t :inherit company-preview
210 :background "blue1"))
211 "Face used for the search string in the completion preview."
214 (defface company-echo nil
215 "Face used for completions in the echo area."
218 (defface company-echo-common
219 '((((background dark)) (:foreground "firebrick1"))
220 (((background light)) (:background "firebrick4")))
221 "Face used for the common part of completions in the echo area."
224 (defun company-frontends-set (variable value)
226 (let ((remainder value))
227 (setcdr remainder (delq (car remainder) (cdr remainder))))
228 (and (memq 'company-pseudo-tooltip-unless-just-one-frontend value)
229 (memq 'company-pseudo-tooltip-frontend value)
230 (error "Pseudo tooltip frontend cannot be used twice"))
231 (and (memq 'company-preview-if-just-one-frontend value)
232 (memq 'company-preview-frontend value)
233 (error "Preview frontend cannot be used twice"))
234 (and (memq 'company-echo value)
235 (memq 'company-echo-metadata-frontend value)
236 (error "Echo area cannot be used twice"))
237 ;; preview must come last
238 (dolist (f '(company-preview-if-just-one-frontend company-preview-frontend))
240 (setq value (append (delq f value) (list f)))))
241 (set variable value))
243 (defcustom company-frontends '(company-pseudo-tooltip-unless-just-one-frontend
244 company-preview-if-just-one-frontend
245 company-echo-metadata-frontend)
246 "The list of active front-ends (visualizations).
247 Each front-end is a function that takes one argument. It is called with
248 one of the following arguments:
250 'show: When the visualization should start.
252 'hide: When the visualization should end.
254 'update: When the data has been updated.
256 'pre-command: Before every command that is executed while the
257 visualization is active.
259 'post-command: After every command that is executed while the
260 visualization is active.
262 The visualized data is stored in `company-prefix', `company-candidates',
263 `company-common', `company-selection', `company-point' and
264 `company-search-string'."
265 :set 'company-frontends-set
267 :type '(repeat (choice (const :tag "echo" company-echo-frontend)
268 (const :tag "echo, strip common"
269 company-echo-strip-common-frontend)
270 (const :tag "show echo meta-data in echo"
271 company-echo-metadata-frontend)
272 (const :tag "pseudo tooltip"
273 company-pseudo-tooltip-frontend)
274 (const :tag "pseudo tooltip, multiple only"
275 company-pseudo-tooltip-unless-just-one-frontend)
276 (const :tag "preview" company-preview-frontend)
277 (const :tag "preview, unique only"
278 company-preview-if-just-one-frontend)
279 (function :tag "custom function" nil))))
281 (defcustom company-tooltip-limit 10
282 "The maximum number of candidates in the tool tip"
286 (defcustom company-tooltip-minimum 6
287 "The minimum height of the tool tip.
288 If this many lines are not available, prefer to display the tooltip above."
292 (defvar company-safe-backends
293 '((company-abbrev . "Abbrev")
294 (company-clang . "clang")
295 (company-css . "CSS")
296 (company-dabbrev . "dabbrev for plain text")
297 (company-dabbrev-code . "dabbrev for code")
298 (company-eclim . "eclim (an Eclipse interace)")
299 (company-elisp . "Emacs Lisp")
300 (company-etags . "etags")
301 (company-files . "Files")
302 (company-gtags . "GNU Global")
303 (company-ispell . "ispell")
304 (company-keywords . "Programming language keywords")
305 (company-nxml . "nxml")
306 (company-oddmuse . "Oddmuse")
307 (company-pysmell . "PySmell")
308 (company-ropemacs . "ropemacs")
309 (company-semantic . "CEDET Semantic")
310 (company-tempo . "Tempo templates")
311 (company-xcode . "Xcode")))
312 (put 'company-safe-backends 'risky-local-variable t)
314 (defun company-safe-backends-p (backends)
315 (and (consp backends)
316 (not (dolist (backend backends)
317 (unless (if (consp backend)
318 (company-safe-backends-p backend)
319 (assq backend company-safe-backends))
322 (defun company-capf (command &optional arg &rest args)
323 "`company-mode' back-end using `completion-at-point-functions'.
324 Requires Emacs 24.1 or newer."
325 (interactive (list 'interactive))
327 (interactive (company-begin-backend 'company-capf))
329 (let ((res (run-hook-wrapped 'completion-at-point-functions
330 ;; Ignore misbehaving functions.
331 #'completion--capf-wrapper 'optimist)))
333 (if (> (nth 2 res) (point))
335 (buffer-substring-no-properties (nth 1 res) (point))))))
337 (let ((res (run-hook-wrapped 'completion-at-point-functions
338 ;; Ignore misbehaving functions.
339 #'completion--capf-wrapper 'optimist)))
341 (all-completions arg (nth 3 res)
342 (plist-get (nthcdr 4 res) :predicate)))))))
344 (defcustom company-backends '(company-elisp company-nxml company-css
345 company-eclim company-semantic company-clang
346 company-xcode company-ropemacs
347 (company-gtags company-etags company-dabbrev-code
348 company-pysmell company-keywords)
349 company-oddmuse company-files company-dabbrev)
350 "The list of active back-ends (completion engines).
351 Each list elements can itself be a list of back-ends. In that case their
352 completions are merged. Otherwise only the first matching back-end returns
355 `company-begin-backend' can be used to start a specific back-end,
356 `company-other-backend' will skip to the next matching back-end in the list.
358 Each back-end is a function that takes a variable number of arguments.
359 The first argument is the command requested from the back-end. It is one
362 `prefix': The back-end should return the text to be completed. It must be
363 text immediately before `point'. Returning nil passes control to the next
364 back-end. The function should return 'stop if it should complete but cannot
365 \(e.g. if it is in the middle of a string\). If the returned value is only
366 part of the prefix (e.g. the part after \"->\" in C), the back-end may return a
367 cons of prefix and prefix length, which is then used in the
368 `company-minimum-prefix-length' test.
370 `candidates': The second argument is the prefix to be completed. The
371 return value should be a list of candidates that start with the prefix.
375 `sorted': The back-end may return t here to indicate that the candidates
376 are sorted and will not need to be sorted again.
378 `duplicates': If non-nil, company will take care of removing duplicates
381 `no-cache': Usually company doesn't ask for candidates again as completion
382 progresses, unless the back-end returns t for this command. The second
383 argument is the latest prefix.
385 `meta': The second argument is a completion candidate. The back-end should
386 return a (short) documentation string for it.
388 `doc-buffer': The second argument is a completion candidate.
389 The back-end should create a buffer (preferably with `company-doc-buffer'),
390 fill it with documentation and return it.
392 `location': The second argument is a completion candidate. The back-end can
393 return the cons of buffer and buffer location, or of file and line
394 number where the completion candidate was defined.
396 `require-match': If this value is t, the user is not allowed to enter anything
397 not offering as a candidate. Use with care! The default value nil gives the
398 user that choice with `company-require-match'. Return value 'never overrides
399 that option the other way around.
401 The back-end should return nil for all commands it does not support or
402 does not know about. It should also be callable interactively and use
403 `company-begin-backend' to start itself in that case."
408 ,@(mapcar (lambda (b) `(const :tag ,(cdr b) ,(car b)))
409 company-safe-backends)
410 (symbol :tag "User defined")
411 (repeat :tag "Merged Back-ends"
412 (choice :tag "Back-end"
413 ,@(mapcar (lambda (b)
414 `(const :tag ,(cdr b) ,(car b)))
415 company-safe-backends)
416 (symbol :tag "User defined"))))))
418 (put 'company-backends 'safe-local-variable 'company-safe-backends-p)
420 (defcustom company-completion-started-hook nil
421 "Hook run when company starts completing.
422 The hook is called with one argument that is non-nil if the completion was
427 (defcustom company-completion-cancelled-hook nil
428 "Hook run when company cancels completing.
429 The hook is called with one argument that is non-nil if the completion was
434 (defcustom company-completion-finished-hook nil
435 "Hook run when company successfully completes.
436 The hook is called with the selected candidate as an argument."
440 (defcustom company-minimum-prefix-length 3
441 "The minimum prefix length for automatic completion."
443 :type '(integer :tag "prefix length"))
445 (defcustom company-require-match 'company-explicit-action-p
446 "If enabled, disallow non-matching input.
447 This can be a function do determine if a match is required.
449 This can be overridden by the back-end, if it returns t or 'never to
450 'require-match. `company-auto-complete' also takes precedence over this."
452 :type '(choice (const :tag "Off" nil)
453 (function :tag "Predicate function")
454 (const :tag "On, if user interaction took place"
455 'company-explicit-action-p)
456 (const :tag "On" t)))
458 (defcustom company-auto-complete 'company-explicit-action-p
459 "Determines when to auto-complete.
460 If this is enabled, all characters from `company-auto-complete-chars' complete
461 the selected completion. This can also be a function."
463 :type '(choice (const :tag "Off" nil)
464 (function :tag "Predicate function")
465 (const :tag "On, if user interaction took place"
466 'company-explicit-action-p)
467 (const :tag "On" t)))
469 (defcustom company-auto-complete-chars '(?\ ?\( ?\) ?. ?\" ?$ ?\' ?< ?| ?!)
470 "Determines which characters trigger an automatic completion.
471 See `company-auto-complete'. If this is a string, each string character causes
472 completion. If it is a list of syntax description characters (see
473 `modify-syntax-entry'), all characters with that syntax auto-complete.
475 This can also be a function, which is called with the new input and should
476 return non-nil if company should auto-complete.
478 A character that is part of a valid candidate never starts auto-completion."
480 :type '(choice (string :tag "Characters")
482 (const :tag "Whitespace" ?\ )
483 (const :tag "Symbol" ?_)
484 (const :tag "Opening parentheses" ?\()
485 (const :tag "Closing parentheses" ?\))
486 (const :tag "Word constituent" ?w)
487 (const :tag "Punctuation." ?.)
488 (const :tag "String quote." ?\")
489 (const :tag "Paired delimiter." ?$)
490 (const :tag "Expression quote or prefix operator." ?\')
491 (const :tag "Comment starter." ?<)
492 (const :tag "Comment ender." ?>)
493 (const :tag "Character-quote." ?/)
494 (const :tag "Generic string fence." ?|)
495 (const :tag "Generic comment fence." ?!))
496 (function :tag "Predicate function")))
498 (defcustom company-idle-delay .7
499 "The idle delay in seconds until automatic completions starts.
500 A value of nil means never complete automatically, t means complete
501 immediately when a prefix of `company-minimum-prefix-length' is reached."
503 :type '(choice (const :tag "never (nil)" nil)
504 (const :tag "immediate (t)" t)
505 (number :tag "seconds")))
507 (defcustom company-begin-commands t
508 "A list of commands following which company will start completing.
509 If this is t, it will complete after any command. See `company-idle-delay'.
511 Alternatively any command with a non-nil 'company-begin property is treated as
512 if it was on this list."
514 :type '(choice (const :tag "Any command" t)
515 (const :tag "Self insert command" '(self-insert-command))
516 (repeat :tag "Commands" function)))
518 (defcustom company-show-numbers nil
519 "If enabled, show quick-access numbers for the first ten candidates."
521 :type '(choice (const :tag "off" nil)
522 (const :tag "on" t)))
524 (defvar company-end-of-buffer-workaround t
525 "Work around a visualization bug when completing at the end of the buffer.
526 The work-around consists of adding a newline.")
528 ;;; mode ;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;
530 (defvar company-mode-map (make-sparse-keymap)
531 "Keymap used by `company-mode'.")
533 (defvar company-active-map
534 (let ((keymap (make-sparse-keymap)))
535 (define-key keymap "\e\e\e" 'company-abort)
536 (define-key keymap "\C-g" 'company-abort)
537 (define-key keymap (kbd "M-n") 'company-select-next)
538 (define-key keymap (kbd "M-p") 'company-select-previous)
539 (define-key keymap (kbd "<down>") 'company-select-next)
540 (define-key keymap (kbd "<up>") 'company-select-previous)
541 (define-key keymap [down-mouse-1] 'ignore)
542 (define-key keymap [down-mouse-3] 'ignore)
543 (define-key keymap [mouse-1] 'company-complete-mouse)
544 (define-key keymap [mouse-3] 'company-select-mouse)
545 (define-key keymap [up-mouse-1] 'ignore)
546 (define-key keymap [up-mouse-3] 'ignore)
547 (define-key keymap [return] 'company-complete-selection)
548 (define-key keymap [tab] 'company-complete-common)
549 (define-key keymap (kbd "<f1>") 'company-show-doc-buffer)
550 (define-key keymap "\C-w" 'company-show-location)
551 (define-key keymap "\C-s" 'company-search-candidates)
552 (define-key keymap "\C-\M-s" 'company-filter-candidates)
554 (define-key keymap (vector (+ (aref (kbd "M-0") 0) i))
555 `(lambda () (interactive) (company-complete-number ,i))))
558 "Keymap that is enabled during an active completion.")
560 (defvar company--disabled-backends nil)
562 (defun company-init-backend (backend)
563 (and (symbolp backend)
564 (not (fboundp backend))
565 (ignore-errors (require backend nil t)))
567 (if (or (symbolp backend)
571 (funcall backend 'init)
572 (put backend 'company-init t))
574 (put backend 'company-init 'failed)
575 (unless (memq backend company--disabled-backends)
576 (message "Company back-end '%s' could not be initialized:\n%s"
577 backend (error-message-string err)))
578 (push backend company--disabled-backends)
580 (mapc 'company-init-backend backend)))
582 (defvar company-default-lighter " company")
584 (defvar company-lighter company-default-lighter)
585 (make-variable-buffer-local 'company-lighter)
588 (define-minor-mode company-mode
589 "\"complete anything\"; is an in-buffer completion framework.
590 Completion starts automatically, depending on the values
591 `company-idle-delay' and `company-minimum-prefix-length'.
593 Completion can be controlled with the commands:
594 `company-complete-common', `company-complete-selection', `company-complete',
595 `company-select-next', `company-select-previous'. If these commands are
596 called before `company-idle-delay', completion will also start.
598 Completions can be searched with `company-search-candidates' or
599 `company-filter-candidates'. These can be used while completion is
602 The completion data is retrieved using `company-backends' and displayed using
603 `company-frontends'. If you want to start a specific back-end, call it
604 interactively or use `company-begin-backend'.
606 regular keymap (`company-mode-map'):
609 keymap during active completions (`company-active-map'):
611 \\{company-active-map}"
612 nil company-lighter company-mode-map
615 (add-hook 'pre-command-hook 'company-pre-command nil t)
616 (add-hook 'post-command-hook 'company-post-command nil t)
617 (mapc 'company-init-backend company-backends))
618 (remove-hook 'pre-command-hook 'company-pre-command t)
619 (remove-hook 'post-command-hook 'company-post-command t)
621 (kill-local-variable 'company-point)))
623 (define-globalized-minor-mode global-company-mode company-mode
624 (lambda () (company-mode 1)))
626 (defsubst company-assert-enabled ()
628 (company-uninstall-map)
629 (error "Company not enabled")))
631 ;;; keymaps ;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;
633 (defvar company-my-keymap nil)
634 (make-variable-buffer-local 'company-my-keymap)
636 (defvar company-emulation-alist '((t . nil)))
638 (defsubst company-enable-overriding-keymap (keymap)
639 (company-uninstall-map)
640 (setq company-my-keymap keymap))
642 (defun company-ensure-emulation-alist ()
643 (unless (eq 'company-emulation-alist (car emulation-mode-map-alists))
644 (setq emulation-mode-map-alists
645 (cons 'company-emulation-alist
646 (delq 'company-emulation-alist emulation-mode-map-alists)))))
648 (defun company-install-map ()
649 (unless (or (cdar company-emulation-alist)
650 (null company-my-keymap))
651 (setf (cdar company-emulation-alist) company-my-keymap)))
653 (defun company-uninstall-map ()
654 (setf (cdar company-emulation-alist) nil))
657 ;; Emacs calculates the active keymaps before reading the event. That means we
658 ;; cannot change the keymap from a timer. So we send a bogus command.
659 (defun company-ignore ()
661 (setq this-command last-command))
663 (global-set-key '[31415926] 'company-ignore)
665 (defun company-input-noop ()
666 (push 31415926 unread-command-events))
669 ;; posn-col-row is incorrect in older Emacsen when line-spacing is set
670 (defun company--col-row (&optional pos)
671 (let ((posn (posn-at-point pos)))
672 (cons (car (posn-col-row posn)) (cdr (posn-actual-col-row posn)))))
674 (defsubst company--column (&optional pos)
675 (car (posn-col-row (posn-at-point pos))))
677 (defsubst company--row (&optional pos)
678 (cdr (posn-actual-col-row (posn-at-point pos))))
680 ;;; backends ;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;
682 (defun company-grab (regexp &optional expression limit)
683 (when (looking-back regexp limit)
684 (or (match-string-no-properties (or expression 0)) "")))
686 (defun company-grab-line (regexp &optional expression)
687 (company-grab regexp expression (point-at-bol)))
689 (defun company-grab-symbol ()
690 (if (looking-at "\\_>")
691 (buffer-substring (point) (save-excursion (skip-syntax-backward "w_")
693 (unless (and (char-after) (memq (char-syntax (char-after)) '(?w ?_)))
696 (defun company-grab-word ()
697 (if (looking-at "\\>")
698 (buffer-substring (point) (save-excursion (skip-syntax-backward "w")
700 (unless (and (char-after) (eq (char-syntax (char-after)) ?w))
703 (defun company-in-string-or-comment ()
704 (let ((ppss (syntax-ppss)))
705 (or (car (setq ppss (nthcdr 3 ppss)))
706 (car (setq ppss (cdr ppss)))
709 (if (fboundp 'locate-dominating-file)
710 (defalias 'company-locate-dominating-file 'locate-dominating-file)
711 (defun company-locate-dominating-file (file name)
713 (let ((dir (file-name-directory file))
715 (while (not (equal dir prev-dir))
716 (when (file-exists-p (expand-file-name name dir))
719 dir (file-name-directory (directory-file-name dir))))))))
721 (defun company-call-backend (&rest args)
722 (if (functionp company-backend)
723 (apply company-backend args)
724 (apply 'company--multi-backend-adapter company-backend args)))
726 (defun company--multi-backend-adapter (backends command &rest args)
729 (apply 'append (mapcar (lambda (backend) (apply backend command args))
735 (dolist (backend backends)
736 (when (setq value (apply backend command args))
739 ;;; completion mechanism ;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;
741 (defvar company-backend nil)
742 (make-variable-buffer-local 'company-backend)
744 (defvar company-prefix nil)
745 (make-variable-buffer-local 'company-prefix)
747 (defvar company-candidates nil)
748 (make-variable-buffer-local 'company-candidates)
750 (defvar company-candidates-length nil)
751 (make-variable-buffer-local 'company-candidates-length)
753 (defvar company-candidates-cache nil)
754 (make-variable-buffer-local 'company-candidates-cache)
756 (defvar company-candidates-predicate nil)
757 (make-variable-buffer-local 'company-candidates-predicate)
759 (defvar company-common nil)
760 (make-variable-buffer-local 'company-common)
762 (defvar company-selection 0)
763 (make-variable-buffer-local 'company-selection)
765 (defvar company-selection-changed nil)
766 (make-variable-buffer-local 'company-selection-changed)
768 (defvar company--explicit-action nil
769 "Non-nil, if explicit completion took place.")
770 (make-variable-buffer-local 'company--explicit-action)
772 (defvar company--point-max nil)
773 (make-variable-buffer-local 'company--point-max)
775 (defvar company-point nil)
776 (make-variable-buffer-local 'company-point)
778 (defvar company-timer nil)
780 (defvar company-added-newline nil)
781 (make-variable-buffer-local 'company-added-newline)
783 (defsubst company-strip-prefix (str)
784 (substring str (length company-prefix)))
786 (defmacro company-with-candidate-inserted (candidate &rest body)
787 "Evaluate BODY with CANDIDATE temporarily inserted.
788 This is a tool for back-ends that need candidates inserted before they
789 can retrieve meta-data for them."
791 `(let ((inhibit-modification-hooks t)
792 (inhibit-point-motion-hooks t)
793 (modified-p (buffer-modified-p)))
794 (insert (company-strip-prefix ,candidate))
797 (delete-region company-point (point)))))
799 (defun company-explicit-action-p ()
800 "Return whether explicit completion action was taken by the user."
801 (or company--explicit-action
802 company-selection-changed))
804 (defsubst company-reformat (candidate)
805 ;; company-ispell needs this, because the results are always lower-case
806 ;; It's mory efficient to fix it only when they are displayed.
807 (concat company-prefix (substring candidate (length company-prefix))))
809 (defun company--should-complete ()
810 (and (not (or buffer-read-only overriding-terminal-local-map
813 ;; Check if in the middle of entering a key combination.
814 (or (equal (this-command-keys-vector) [])
815 (not (keymapp (key-binding (this-command-keys-vector)))))
816 (eq company-idle-delay t)
817 (or (eq t company-begin-commands)
818 (memq this-command company-begin-commands)
819 (and (symbolp this-command) (get this-command 'company-begin)))
820 (not (and transient-mark-mode mark-active))))
822 (defsubst company-call-frontends (command)
823 (dolist (frontend company-frontends)
825 (funcall frontend command)
826 (error (error "Company: Front-end %s error \"%s\" on command %s"
827 frontend (error-message-string err) command)))))
829 (defsubst company-set-selection (selection &optional force-update)
830 (setq selection (max 0 (min (1- company-candidates-length) selection)))
831 (when (or force-update (not (equal selection company-selection)))
832 (setq company-selection selection
833 company-selection-changed t)
834 (company-call-frontends 'update)))
836 (defun company-apply-predicate (candidates predicate)
838 (dolist (c candidates)
839 (when (funcall predicate c)
843 (defun company-update-candidates (candidates)
844 (setq company-candidates-length (length candidates))
845 (if (> company-selection 0)
846 ;; Try to restore the selection
847 (let ((selected (nth company-selection company-candidates)))
848 (setq company-selection 0
849 company-candidates candidates)
851 (while (and candidates (string< (pop candidates) selected))
852 (incf company-selection))
854 ;; Make sure selection isn't out of bounds.
855 (setq company-selection (min (1- company-candidates-length)
856 company-selection)))))
857 (setq company-selection 0
858 company-candidates candidates))
860 (push (cons company-prefix company-candidates) company-candidates-cache)
862 (let ((completion-ignore-case (company-call-backend 'ignore-case)))
863 (setq company-common (try-completion company-prefix company-candidates)))
864 (when (eq company-common t)
865 (setq company-candidates nil)))
867 (defun company-calculate-candidates (prefix)
868 (let ((candidates (cdr (assoc prefix company-candidates-cache))))
870 (when company-candidates-cache
871 (let ((len (length prefix))
872 (completion-ignore-case (company-call-backend 'ignore-case))
874 (dotimes (i (1+ len))
875 (when (setq prev (cdr (assoc (substring prefix 0 (- len i))
876 company-candidates-cache)))
877 (setq candidates (all-completions prefix prev))
879 ;; no cache match, call back-end
881 (setq candidates (company-call-backend 'candidates prefix))
882 (when company-candidates-predicate
884 (company-apply-predicate candidates
885 company-candidates-predicate)))
886 (unless (company-call-backend 'sorted)
887 (setq candidates (sort candidates 'string<)))
888 (when (company-call-backend 'duplicates)
890 (let ((c2 candidates))
892 (setcdr c2 (progn (while (equal (pop c2) (car c2)))
894 (if (or (cdr candidates)
895 (not (equal (car candidates) prefix)))
896 ;; Don't start when already completed and unique.
898 ;; Not the right place? maybe when setting?
899 (and company-candidates t))))
901 (defun company-idle-begin (buf win tick pos)
903 (eq buf (current-buffer))
904 (eq win (selected-window))
905 (eq tick (buffer-chars-modified-tick))
907 (not company-candidates)
908 (not (equal (point) company-point))
909 (let ((company-idle-delay t)
910 (company-begin-commands t))
912 (when company-candidates
914 (company-post-command)))))
916 (defun company-auto-begin ()
917 (company-assert-enabled)
919 (not company-candidates)
920 (let ((company-idle-delay t)
921 (company-minimum-prefix-length 0)
922 (company-begin-commands t))
924 ;; Return non-nil if active.
927 (defun company-manual-begin ()
929 (setq company--explicit-action t)
930 (company-auto-begin))
932 (defun company-other-backend (&optional backward)
933 (interactive (list current-prefix-arg))
934 (company-assert-enabled)
936 (let* ((after (cdr (member company-backend company-backends)))
937 (before (cdr (member company-backend (reverse company-backends))))
939 (append before (reverse after))
940 (append after (reverse before)))))
942 (dolist (backend next)
943 (when (ignore-errors (company-begin-backend backend))
945 (company-manual-begin))
946 (unless company-candidates
947 (error "No other back-end")))
949 (defun company-require-match-p ()
950 (let ((backend-value (company-call-backend 'require-match)))
951 (or (eq backend-value t)
952 (and (if (functionp company-require-match)
953 (funcall company-require-match)
954 (eq company-require-match t))
955 (not (eq backend-value 'never))))))
957 (defun company-punctuation-p (input)
958 "Return non-nil, if input starts with punctuation or parentheses."
959 (memq (char-syntax (string-to-char input)) '(?. ?\( ?\))))
961 (defun company-auto-complete-p (input)
962 "Return non-nil, if input starts with punctuation or parentheses."
963 (and (if (functionp company-auto-complete)
964 (funcall company-auto-complete)
965 company-auto-complete)
966 (if (functionp company-auto-complete-chars)
967 (funcall company-auto-complete-chars input)
968 (if (consp company-auto-complete-chars)
969 (memq (char-syntax (string-to-char input))
970 company-auto-complete-chars)
971 (string-match (substring input 0 1) company-auto-complete-chars)))))
973 (defun company--incremental-p ()
974 (and (> (point) company-point)
975 (> (point-max) company--point-max)
976 (not (eq this-command 'backward-delete-char-untabify))
977 (equal (buffer-substring (- company-point (length company-prefix))
981 (defsubst company--string-incremental-p (old-prefix new-prefix)
982 (and (> (length new-prefix) (length old-prefix))
983 (equal old-prefix (substring new-prefix 0 (length old-prefix)))))
985 (defun company--continue-failed (new-prefix)
986 (when (company--incremental-p)
987 (let ((input (buffer-substring-no-properties (point) company-point)))
989 ((company-auto-complete-p input)
992 (goto-char company-point)
993 (company-complete-selection)
995 ((and (company--string-incremental-p company-prefix new-prefix)
996 (company-require-match-p))
997 ;; wrong incremental input, but required match
998 (backward-delete-char (length input))
1000 (message "Matching input is required")
1002 ((equal company-prefix (car company-candidates))
1003 ;; last input was actually success
1004 (company-cancel company-prefix)
1007 (defun company--good-prefix-p (prefix)
1008 (and (or (company-explicit-action-p)
1009 (>= (or (cdr-safe prefix) (length prefix))
1010 company-minimum-prefix-length))
1011 (stringp (or (car-safe prefix) prefix))))
1013 (defun company--continue ()
1014 (when (company-call-backend 'no-cache company-prefix)
1015 ;; Don't complete existing candidates, fetch new ones.
1016 (setq company-candidates-cache nil))
1017 (let* ((new-prefix (company-call-backend 'prefix))
1018 (c (when (and (company--good-prefix-p new-prefix)
1019 (setq new-prefix (or (car-safe new-prefix) new-prefix))
1020 (= (- (point) (length new-prefix))
1021 (- company-point (length company-prefix))))
1022 (setq new-prefix (or (car-safe new-prefix) new-prefix))
1023 (company-calculate-candidates new-prefix))))
1026 ;; t means complete/unique.
1027 (company-cancel new-prefix)
1030 ;; incremental match
1031 (setq company-prefix new-prefix)
1032 (company-update-candidates c)
1034 (t (company--continue-failed new-prefix)))
1037 (defun company--begin-new ()
1039 (dolist (backend (if company-backend
1040 ;; prefer manual override
1041 (list company-backend)
1044 (if (or (symbolp backend)
1045 (functionp backend))
1046 (when (or (not (symbolp backend))
1047 (eq t (get backend 'company-init))
1048 (unless (get backend 'company-init)
1049 (company-init-backend backend)))
1050 (funcall backend 'prefix))
1051 (company--multi-backend-adapter backend 'prefix)))
1053 (when (company--good-prefix-p prefix)
1054 (setq prefix (or (car-safe prefix) prefix)
1055 company-backend backend
1056 c (company-calculate-candidates prefix))
1057 ;; t means complete/unique. We don't start, so no hooks.
1059 (when company--explicit-action
1060 (message "No completion found"))
1061 (setq company-prefix prefix)
1062 (when (symbolp backend)
1063 (setq company-lighter (concat " " (symbol-name backend))))
1064 (company-update-candidates c)
1065 (run-hook-with-args 'company-completion-started-hook
1066 (company-explicit-action-p))
1067 (company-call-frontends 'show)))
1070 (defun company-begin ()
1071 (or (and company-candidates (company--continue))
1072 (and (company--should-complete) (company--begin-new)))
1073 (when company-candidates
1074 (when (and company-end-of-buffer-workaround (eobp))
1075 (save-excursion (insert "\n"))
1076 (setq company-added-newline (buffer-chars-modified-tick)))
1077 (setq company-point (point)
1078 company--point-max (point-max))
1079 (company-ensure-emulation-alist)
1080 (company-enable-overriding-keymap company-active-map)
1081 (company-call-frontends 'update)))
1083 (defun company-cancel (&optional result)
1084 (and company-added-newline
1085 (> (point-max) (point-min))
1086 (let ((tick (buffer-chars-modified-tick)))
1087 (delete-region (1- (point-max)) (point-max))
1088 (equal tick company-added-newline))
1089 ;; Only set unmodified when tick remained the same since insert.
1090 (set-buffer-modified-p nil))
1091 (when company-prefix
1092 (if (stringp result)
1094 (company-call-backend 'pre-completion result)
1095 (run-hook-with-args 'company-completion-finished-hook result)
1096 (company-call-backend 'post-completion result))
1097 (run-hook-with-args 'company-completion-cancelled-hook result)))
1098 (setq company-added-newline nil
1101 company-candidates nil
1102 company-candidates-length nil
1103 company-candidates-cache nil
1104 company-candidates-predicate nil
1107 company-selection-changed nil
1108 company--explicit-action nil
1109 company-lighter company-default-lighter
1110 company--point-max nil
1113 (cancel-timer company-timer))
1114 (company-search-mode 0)
1115 (company-call-frontends 'hide)
1116 (company-enable-overriding-keymap nil))
1118 (defun company-abort ()
1121 ;; Don't start again, unless started manually.
1122 (setq company-point (point)))
1124 (defun company-finish (result)
1125 (insert (company-strip-prefix result))
1126 (company-cancel result)
1127 ;; Don't start again, unless started manually.
1128 (setq company-point (point)))
1130 (defsubst company-keep (command)
1131 (and (symbolp command) (get command 'company-keep)))
1133 (defun company-pre-command ()
1134 (unless (company-keep this-command)
1136 (when company-candidates
1137 (company-call-frontends 'pre-command))
1138 (error (message "Company: An error occurred in pre-command")
1139 (message "%s" (error-message-string err))
1142 (cancel-timer company-timer)
1143 (setq company-timer nil))
1144 (company-uninstall-map))
1146 (defun company-post-command ()
1147 (unless (company-keep this-command)
1150 (unless (equal (point) company-point)
1152 (if company-candidates
1153 (company-call-frontends 'post-command)
1154 (and (numberp company-idle-delay)
1155 (or (eq t company-begin-commands)
1156 (memq this-command company-begin-commands))
1158 (run-with-timer company-idle-delay nil
1160 (current-buffer) (selected-window)
1161 (buffer-chars-modified-tick) (point))))))
1162 (error (message "Company: An error occurred in post-command")
1163 (message "%s" (error-message-string err))
1165 (company-install-map))
1167 ;;; search ;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;
1169 (defvar company-search-string nil)
1170 (make-variable-buffer-local 'company-search-string)
1172 (defvar company-search-lighter " Search: \"\"")
1173 (make-variable-buffer-local 'company-search-lighter)
1175 (defvar company-search-old-map nil)
1176 (make-variable-buffer-local 'company-search-old-map)
1178 (defvar company-search-old-selection 0)
1179 (make-variable-buffer-local 'company-search-old-selection)
1181 (defun company-search (text lines)
1182 (let ((quoted (regexp-quote text))
1184 (dolist (line lines)
1185 (when (string-match quoted line (length company-prefix))
1189 (defun company-search-printing-char ()
1191 (company-search-assert-enabled)
1192 (setq company-search-string
1193 (concat (or company-search-string "") (string last-command-event))
1194 company-search-lighter (concat " Search: \"" company-search-string
1196 (let ((pos (company-search company-search-string
1197 (nthcdr company-selection company-candidates))))
1200 (company-set-selection (+ company-selection pos) t))))
1202 (defun company-search-repeat-forward ()
1203 "Repeat the incremental search in completion candidates forward."
1205 (company-search-assert-enabled)
1206 (let ((pos (company-search company-search-string
1207 (cdr (nthcdr company-selection
1208 company-candidates)))))
1211 (company-set-selection (+ company-selection pos 1) t))))
1213 (defun company-search-repeat-backward ()
1214 "Repeat the incremental search in completion candidates backwards."
1216 (company-search-assert-enabled)
1217 (let ((pos (company-search company-search-string
1218 (nthcdr (- company-candidates-length
1220 (reverse company-candidates)))))
1223 (company-set-selection (- company-selection pos 1) t))))
1225 (defun company-create-match-predicate ()
1226 (setq company-candidates-predicate
1227 `(lambda (candidate)
1228 ,(if company-candidates-predicate
1229 `(and (string-match ,company-search-string candidate)
1230 (funcall ,company-candidates-predicate
1232 `(string-match ,company-search-string candidate))))
1233 (company-update-candidates
1234 (company-apply-predicate company-candidates company-candidates-predicate))
1235 ;; Invalidate cache.
1236 (setq company-candidates-cache (cons company-prefix company-candidates)))
1238 (defun company-filter-printing-char ()
1240 (company-search-assert-enabled)
1241 (company-search-printing-char)
1242 (company-create-match-predicate)
1243 (company-call-frontends 'update))
1245 (defun company-search-kill-others ()
1246 "Limit the completion candidates to the ones matching the search string."
1248 (company-search-assert-enabled)
1249 (company-create-match-predicate)
1250 (company-search-mode 0)
1251 (company-call-frontends 'update))
1253 (defun company-search-abort ()
1254 "Abort searching the completion candidates."
1256 (company-search-assert-enabled)
1257 (company-set-selection company-search-old-selection t)
1258 (company-search-mode 0))
1260 (defun company-search-other-char ()
1262 (company-search-assert-enabled)
1263 (company-search-mode 0)
1264 (when last-input-event
1265 (clear-this-command-keys t)
1266 (setq unread-command-events (list last-input-event))))
1268 (defvar company-search-map
1270 (keymap (make-keymap)))
1271 (if (fboundp 'max-char)
1272 (set-char-table-range (nth 1 keymap) (cons #x100 (max-char))
1273 'company-search-printing-char)
1275 ;; obselete in Emacs 23
1276 (let ((l (generic-character-list))
1277 (table (nth 1 keymap)))
1279 (set-char-table-default table (car l) 'company-search-printing-char)
1280 (setq l (cdr l))))))
1281 (define-key keymap [t] 'company-search-other-char)
1283 (define-key keymap (make-string 1 i) 'company-search-other-char)
1286 (define-key keymap (vector i) 'company-search-printing-char)
1288 (let ((meta-map (make-sparse-keymap)))
1289 (define-key keymap (char-to-string meta-prefix-char) meta-map)
1290 (define-key keymap [escape] meta-map))
1291 (define-key keymap (vector meta-prefix-char t) 'company-search-other-char)
1292 (define-key keymap "\e\e\e" 'company-search-other-char)
1293 (define-key keymap [escape escape escape] 'company-search-other-char)
1295 (define-key keymap "\C-g" 'company-search-abort)
1296 (define-key keymap "\C-s" 'company-search-repeat-forward)
1297 (define-key keymap "\C-r" 'company-search-repeat-backward)
1298 (define-key keymap "\C-o" 'company-search-kill-others)
1300 "Keymap used for incrementally searching the completion candidates.")
1302 (define-minor-mode company-search-mode
1303 "Search mode for completion candidates.
1304 Don't start this directly, use `company-search-candidates' or
1305 `company-filter-candidates'."
1306 nil company-search-lighter nil
1307 (if company-search-mode
1308 (if (company-manual-begin)
1310 (setq company-search-old-selection company-selection)
1311 (company-call-frontends 'update))
1312 (setq company-search-mode nil))
1313 (kill-local-variable 'company-search-string)
1314 (kill-local-variable 'company-search-lighter)
1315 (kill-local-variable 'company-search-old-selection)
1316 (company-enable-overriding-keymap company-active-map)))
1318 (defsubst company-search-assert-enabled ()
1319 (company-assert-enabled)
1320 (unless company-search-mode
1321 (company-uninstall-map)
1322 (error "Company not in search mode")))
1324 (defun company-search-candidates ()
1325 "Start searching the completion candidates incrementally.
1327 \\<company-search-map>Search can be controlled with the commands:
1328 - `company-search-repeat-forward' (\\[company-search-repeat-forward])
1329 - `company-search-repeat-backward' (\\[company-search-repeat-backward])
1330 - `company-search-abort' (\\[company-search-abort])
1332 Regular characters are appended to the search string.
1334 The command `company-search-kill-others' (\\[company-search-kill-others]) uses
1335 the search string to limit the completion candidates."
1337 (company-search-mode 1)
1338 (company-enable-overriding-keymap company-search-map))
1340 (defvar company-filter-map
1341 (let ((keymap (make-keymap)))
1342 (define-key keymap [remap company-search-printing-char]
1343 'company-filter-printing-char)
1344 (set-keymap-parent keymap company-search-map)
1346 "Keymap used for incrementally searching the completion candidates.")
1348 (defun company-filter-candidates ()
1349 "Start filtering the completion candidates incrementally.
1350 This works the same way as `company-search-candidates' immediately
1351 followed by `company-search-kill-others' after each input."
1353 (company-search-mode 1)
1354 (company-enable-overriding-keymap company-filter-map))
1356 ;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;
1358 (defun company-select-next ()
1359 "Select the next candidate in the list."
1361 (when (company-manual-begin)
1362 (company-set-selection (1+ company-selection))))
1364 (defun company-select-previous ()
1365 "Select the previous candidate in the list."
1367 (when (company-manual-begin)
1368 (company-set-selection (1- company-selection))))
1370 (defun company-select-mouse (event)
1371 "Select the candidate picked by the mouse."
1373 (when (nth 4 (event-start event))
1374 (company-set-selection (- (cdr (posn-actual-col-row (event-start event)))
1379 (defun company-complete-mouse (event)
1380 "Complete the candidate picked by the mouse."
1382 (when (company-select-mouse event)
1383 (company-complete-selection)))
1385 (defun company-complete-selection ()
1386 "Complete the selected candidate."
1388 (when (company-manual-begin)
1389 (company-finish (nth company-selection company-candidates))))
1391 (defun company-complete-common ()
1392 "Complete the common part of all candidates."
1394 (when (company-manual-begin)
1395 (if (and (not (cdr company-candidates))
1396 (equal company-common (car company-candidates)))
1397 (company-complete-selection)
1398 (insert (company-strip-prefix company-common)))))
1400 (defun company-complete ()
1401 "Complete the common part of all candidates or the current selection.
1402 The first time this is called, the common part is completed, the second time, or
1403 when the selection has been changed, the selected candidate is completed."
1405 (when (company-manual-begin)
1406 (if (or company-selection-changed
1407 (eq last-command 'company-complete-common))
1408 (call-interactively 'company-complete-selection)
1409 (call-interactively 'company-complete-common)
1410 (setq this-command 'company-complete-common))))
1412 (defun company-complete-number (n)
1413 "Complete the Nth candidate.
1414 To show the number next to the candidates in some back-ends, enable
1415 `company-show-numbers'."
1416 (when (company-manual-begin)
1417 (and (< n 1) (> n company-candidates-length)
1418 (error "No candidate number %d" n))
1420 (company-finish (nth n company-candidates))))
1422 ;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;
1424 (defconst company-space-strings-limit 100)
1426 (defconst company-space-strings
1428 (dotimes (i company-space-strings-limit)
1429 (push (make-string (- company-space-strings-limit 1 i) ?\ ) lst))
1430 (apply 'vector lst)))
1432 (defsubst company-space-string (len)
1433 (if (< len company-space-strings-limit)
1434 (aref company-space-strings len)
1435 (make-string len ?\ )))
1437 (defsubst company-safe-substring (str from &optional to)
1438 (if (> from (string-width str))
1441 (let* ((res (substring str from (min to (length str))))
1442 (padding (- to from (string-width res)))
1443 (cutting-comp (and (> (length str) to)
1444 (get-text-property to 'composition str))))
1446 (when (and (> padding 0) (not cutting-comp))
1447 (company-space-string padding))))
1448 (substring str from))))
1450 ;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;
1452 (defvar company-last-metadata nil)
1453 (make-variable-buffer-local 'company-last-metadata)
1455 (defun company-fetch-metadata ()
1456 (let ((selected (nth company-selection company-candidates)))
1457 (unless (equal selected (car company-last-metadata))
1458 (setq company-last-metadata
1459 (cons selected (company-call-backend 'meta selected))))
1460 (cdr company-last-metadata)))
1462 (defun company-doc-buffer (&optional string)
1463 (with-current-buffer (get-buffer-create "*Company meta-data*")
1467 (defvar company--electric-commands
1468 '(scroll-other-window scroll-other-window-down)
1469 "List of Commands that won't break out of electric commands.")
1471 (defmacro company--electric-do (&rest body)
1472 (declare (indent 0) (debug t))
1473 `(when (company-manual-begin)
1474 (save-window-excursion
1475 (let ((height (window-height))
1476 (row (company--row))
1479 (and (< (window-height) height)
1480 (< (- (window-height) row 2) company-tooltip-limit)
1481 (recenter (- (window-height) row 2)))
1482 (while (memq (setq cmd (key-binding (vector (list (read-event)))))
1483 company--electric-commands)
1484 (call-interactively cmd))
1485 (when last-input-event
1486 (clear-this-command-keys t)
1487 (setq unread-command-events (list last-input-event)))))))
1489 (defun company-show-doc-buffer ()
1490 "Temporarily show a buffer with the complete documentation for the selection."
1492 (company--electric-do
1493 (let* ((selected (nth company-selection company-candidates))
1494 (doc-buffer (or (company-call-backend 'doc-buffer selected)
1495 (error "No documentation available"))))
1496 (with-current-buffer doc-buffer
1497 (goto-char (point-min)))
1498 (display-buffer doc-buffer t))))
1499 (put 'company-show-doc-buffer 'company-keep t)
1501 (defun company-show-location ()
1502 "Temporarily display a buffer showing the selected candidate in context."
1504 (company--electric-do
1505 (let* ((selected (nth company-selection company-candidates))
1506 (location (company-call-backend 'location selected))
1507 (pos (or (cdr location) (error "No location available")))
1508 (buffer (or (and (bufferp (car location)) (car location))
1509 (find-file-noselect (car location) t))))
1510 (with-selected-window (display-buffer buffer t)
1513 (if (bufferp (car location))
1515 (goto-char (point-min))
1516 (forward-line (1- pos))))
1517 (set-window-start nil (point))))))
1518 (put 'company-show-location 'company-keep t)
1520 ;;; package functions ;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;
1522 (defvar company-callback nil)
1523 (make-variable-buffer-local 'company-callback)
1525 (defvar company-begin-with-marker nil)
1526 (make-variable-buffer-local 'company-begin-with-marker)
1528 (defun company-remove-callback (&optional ignored)
1529 (remove-hook 'company-completion-finished-hook company-callback t)
1530 (remove-hook 'company-completion-cancelled-hook 'company-remove-callback t)
1531 (remove-hook 'company-completion-finished-hook 'company-remove-callback t)
1532 (when company-begin-with-marker
1533 (set-marker company-begin-with-marker nil)))
1535 (defun company-begin-backend (backend &optional callback)
1536 "Start a completion at point using BACKEND."
1537 (interactive (let ((val (completing-read "Company back-end: "
1539 'functionp nil "company-")))
1541 (list (intern val)))))
1542 (when (setq company-callback callback)
1543 (add-hook 'company-completion-finished-hook company-callback nil t))
1544 (add-hook 'company-completion-cancelled-hook 'company-remove-callback nil t)
1545 (add-hook 'company-completion-finished-hook 'company-remove-callback nil t)
1546 (setq company-backend backend)
1547 ;; Return non-nil if active.
1548 (or (company-manual-begin)
1549 (error "Cannot complete at point")))
1551 (defun company-begin-with (candidates
1552 &optional prefix-length require-match callback)
1553 "Start a completion at point.
1554 CANDIDATES is the list of candidates to use and PREFIX-LENGTH is the length of
1555 the prefix that already is in the buffer before point. It defaults to 0.
1557 CALLBACK is a function called with the selected result if the user successfully
1558 completes the input.
1561 \(company-begin-with '\(\"foo\" \"foobar\" \"foobarbaz\"\)\)"
1562 (setq company-begin-with-marker (copy-marker (point) t))
1563 (company-begin-backend
1564 `(lambda (command &optional arg &rest ignored)
1566 ((eq command 'prefix)
1567 (when (equal (point) (marker-position company-begin-with-marker))
1568 (buffer-substring ,(- (point) (or prefix-length 0)) (point))))
1569 ((eq command 'candidates)
1570 (all-completions arg ',candidates))
1571 ((eq command 'require-match)
1575 ;;; pseudo-tooltip ;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;
1577 (defvar company-pseudo-tooltip-overlay nil)
1578 (make-variable-buffer-local 'company-pseudo-tooltip-overlay)
1580 (defvar company-tooltip-offset 0)
1581 (make-variable-buffer-local 'company-tooltip-offset)
1583 (defun company-pseudo-tooltip-update-offset (selection num-lines limit)
1586 (setq company-tooltip-offset
1587 (max (min selection company-tooltip-offset)
1588 (- selection -1 limit)))
1590 (when (<= company-tooltip-offset 1)
1592 (setq company-tooltip-offset 0))
1594 (when (>= company-tooltip-offset (- num-lines limit 1))
1596 (when (= selection (1- num-lines))
1597 (decf company-tooltip-offset)
1598 (when (<= company-tooltip-offset 1)
1599 (setq company-tooltip-offset 0)
1606 (defsubst company-round-tab (arg)
1607 (* (/ (+ arg tab-width) tab-width) tab-width))
1609 (defun company-untabify (str)
1610 (let* ((pieces (split-string str "\t"))
1613 (setcar copy (company-safe-substring
1614 (car copy) 0 (company-round-tab (string-width (car copy)))))
1616 (apply 'concat pieces)))
1618 (defun company-fill-propertize (line width selected)
1619 (setq line (company-safe-substring line 0 width))
1620 (add-text-properties 0 width '(face company-tooltip
1621 mouse-face company-tooltip-mouse)
1623 (add-text-properties 0 (length company-common)
1624 '(face company-tooltip-common
1625 mouse-face company-tooltip-mouse)
1628 (if (and company-search-string
1629 (string-match (regexp-quote company-search-string) line
1630 (length company-prefix)))
1632 (add-text-properties (match-beginning 0) (match-end 0)
1633 '(face company-tooltip-selection)
1635 (when (< (match-beginning 0) (length company-common))
1636 (add-text-properties (match-beginning 0) (length company-common)
1637 '(face company-tooltip-common-selection)
1639 (add-text-properties 0 width '(face company-tooltip-selection
1640 mouse-face company-tooltip-selection)
1642 (add-text-properties 0 (length company-common)
1643 '(face company-tooltip-common-selection
1644 mouse-face company-tooltip-selection)
1650 (defun company-buffer-lines (beg end)
1652 (let ((row (company--row))
1654 (while (and (equal (move-to-window-line (incf row)) row)
1656 (push (buffer-substring beg (min end (1- (point)))) lines)
1658 (unless (eq beg end)
1659 (push (buffer-substring beg end) lines))
1662 (defsubst company-modify-line (old new offset)
1663 (concat (company-safe-substring old 0 offset)
1665 (company-safe-substring old (+ offset (length new)))))
1667 (defsubst company--length-limit (lst limit)
1668 (if (nthcdr limit lst)
1672 (defun company--replacement-string (lines old column nl &optional align-top)
1674 (let ((width (length (car lines))))
1675 (when (> width (- (window-width) column))
1676 (setq column (max 0 (- (window-width) width)))))
1680 ;; untouched lines first
1681 (dotimes (i (- (length old) (length lines)))
1682 (push (pop old) new)))
1683 ;; length into old lines.
1685 (push (company-modify-line (pop old) (pop lines) column) new))
1686 ;; Append whole new lines.
1688 (push (concat (company-space-string column) (pop lines)) new))
1690 (let ((str (concat (when nl "\n")
1691 (mapconcat 'identity (nreverse new) "\n")
1693 (font-lock-append-text-property 0 (length str) 'face 'default str)
1696 (defun company--create-lines (selection limit)
1698 (let ((len company-candidates-length)
1707 ;; Scroll to offset.
1708 (setq limit (company-pseudo-tooltip-update-offset selection len limit))
1710 (when (> company-tooltip-offset 0)
1711 (setq previous (format "...(%d)" company-tooltip-offset)))
1713 (setq remainder (- len limit company-tooltip-offset)
1714 remainder (when (> remainder 0)
1715 (setq remainder (format "...(%d)" remainder))))
1717 (decf selection company-tooltip-offset)
1718 (setq width (max (length previous) (length remainder))
1719 lines (nthcdr company-tooltip-offset company-candidates)
1724 (setq width (max (length (pop lines-copy)) width)))
1725 (setq width (min width (window-width)))
1727 (setq lines-copy lines)
1729 ;; number can make tooltip too long
1730 (when company-show-numbers
1731 (setq numbered company-tooltip-offset))
1734 (push (propertize (company-safe-substring previous 0 width)
1735 'face 'company-tooltip)
1739 (push (company-fill-propertize
1740 (if (>= numbered 10)
1741 (company-reformat (pop lines))
1744 (company-safe-substring (company-reformat (pop lines))
1747 width (equal i selection))
1751 (push (propertize (company-safe-substring remainder 0 width)
1752 'face 'company-tooltip)
1755 (setq lines (nreverse new))))
1759 (defsubst company--window-inner-height ()
1760 (let ((edges (window-inside-edges (selected-window))))
1761 (- (nth 3 edges) (nth 1 edges))))
1763 (defsubst company--pseudo-tooltip-height ()
1764 "Calculate the appropriate tooltip height.
1765 Returns a negative number if the tooltip should be displayed above point."
1766 (let* ((lines (count-lines (window-start) (point-at-bol)))
1767 (below (- (company--window-inner-height) 1 lines)))
1768 (if (and (< below (min company-tooltip-minimum company-candidates-length))
1770 (- (max 3 (min company-tooltip-limit lines)))
1771 (max 3 (min company-tooltip-limit below)))))
1773 (defun company-pseudo-tooltip-show (row column selection)
1774 (company-pseudo-tooltip-hide)
1779 (let* ((height (company--pseudo-tooltip-height))
1783 (setq row (+ row height -1)
1786 (let* ((nl (< (move-to-window-line row) row))
1788 (end (save-excursion
1789 (move-to-window-line (+ row (abs height)))
1791 (ov (make-overlay beg end))
1792 (args (list (mapcar 'company-untabify
1793 (company-buffer-lines beg end))
1796 (setq company-pseudo-tooltip-overlay ov)
1797 (overlay-put ov 'company-replacement-args args)
1798 (overlay-put ov 'company-before
1799 (apply 'company--replacement-string
1800 (company--create-lines selection (abs height))
1803 (overlay-put ov 'company-column column)
1804 (overlay-put ov 'company-height (abs height))
1805 (overlay-put ov 'window (selected-window))))))
1807 (defun company-pseudo-tooltip-show-at-point (pos)
1808 (let ((col-row (company--col-row pos)))
1810 (company-pseudo-tooltip-show (1+ (cdr col-row)) (car col-row)
1811 company-selection))))
1813 (defun company-pseudo-tooltip-edit (lines selection)
1814 (let ((column (overlay-get company-pseudo-tooltip-overlay 'company-column))
1815 (height (overlay-get company-pseudo-tooltip-overlay 'company-height)))
1816 (overlay-put company-pseudo-tooltip-overlay 'company-before
1817 (apply 'company--replacement-string
1818 (company--create-lines selection height)
1819 (overlay-get company-pseudo-tooltip-overlay
1820 'company-replacement-args)))))
1822 (defun company-pseudo-tooltip-hide ()
1823 (when company-pseudo-tooltip-overlay
1824 (delete-overlay company-pseudo-tooltip-overlay)
1825 (setq company-pseudo-tooltip-overlay nil)))
1827 (defun company-pseudo-tooltip-hide-temporarily ()
1828 (when (overlayp company-pseudo-tooltip-overlay)
1829 (overlay-put company-pseudo-tooltip-overlay 'invisible nil)
1830 (overlay-put company-pseudo-tooltip-overlay 'before-string nil)))
1832 (defun company-pseudo-tooltip-unhide ()
1833 (when company-pseudo-tooltip-overlay
1834 (overlay-put company-pseudo-tooltip-overlay 'invisible t)
1835 (overlay-put company-pseudo-tooltip-overlay 'before-string
1836 (overlay-get company-pseudo-tooltip-overlay 'company-before))
1837 (overlay-put company-pseudo-tooltip-overlay 'window (selected-window))))
1839 (defun company-pseudo-tooltip-frontend (command)
1840 "A `company-mode' front-end similar to a tool-tip but based on overlays."
1842 (pre-command (company-pseudo-tooltip-hide-temporarily))
1844 (let ((old-height (if (overlayp company-pseudo-tooltip-overlay)
1845 (overlay-get company-pseudo-tooltip-overlay
1848 (new-height (company--pseudo-tooltip-height)))
1849 (unless (and (>= (* old-height new-height) 0)
1850 (>= (abs old-height) (abs new-height)))
1852 (company-pseudo-tooltip-show-at-point (- (point)
1853 (length company-prefix)))))
1854 (company-pseudo-tooltip-unhide))
1855 (hide (company-pseudo-tooltip-hide)
1856 (setq company-tooltip-offset 0))
1857 (update (when (overlayp company-pseudo-tooltip-overlay)
1858 (company-pseudo-tooltip-edit company-candidates
1859 company-selection)))))
1861 (defun company-pseudo-tooltip-unless-just-one-frontend (command)
1862 "`company-pseudo-tooltip-frontend', but not shown for single candidates."
1863 (unless (and (eq command 'post-command)
1864 (not (cdr company-candidates)))
1865 (company-pseudo-tooltip-frontend command)))
1867 ;;; overlay ;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;
1869 (defvar company-preview-overlay nil)
1870 (make-variable-buffer-local 'company-preview-overlay)
1872 (defun company-preview-show-at-point (pos)
1873 (company-preview-hide)
1875 (setq company-preview-overlay (make-overlay pos pos))
1877 (let ((completion(nth company-selection company-candidates)))
1878 (setq completion (propertize completion 'face 'company-preview))
1879 (add-text-properties 0 (length company-common)
1880 '(face company-preview-common) completion)
1882 ;; Add search string
1883 (and company-search-string
1884 (string-match (regexp-quote company-search-string) completion)
1885 (add-text-properties (match-beginning 0)
1887 '(face company-preview-search)
1890 (setq completion (company-strip-prefix completion))
1892 (and (equal pos (point))
1893 (not (equal completion ""))
1894 (add-text-properties 0 1 '(cursor t) completion))
1896 (overlay-put company-preview-overlay 'after-string completion)
1897 (overlay-put company-preview-overlay 'window (selected-window))))
1899 (defun company-preview-hide ()
1900 (when company-preview-overlay
1901 (delete-overlay company-preview-overlay)
1902 (setq company-preview-overlay nil)))
1904 (defun company-preview-frontend (command)
1905 "A `company-mode' front-end showing the selection as if it had been inserted."
1907 (pre-command (company-preview-hide))
1908 (post-command (company-preview-show-at-point (point)))
1909 (hide (company-preview-hide))))
1911 (defun company-preview-if-just-one-frontend (command)
1912 "`company-preview-frontend', but only shown for single candidates."
1913 (unless (and (eq command 'post-command)
1914 (cdr company-candidates))
1915 (company-preview-frontend command)))
1917 ;;; echo ;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;
1919 (defvar company-echo-last-msg nil)
1920 (make-variable-buffer-local 'company-echo-last-msg)
1922 (defun company-echo-show (&optional getter)
1924 (setq company-echo-last-msg (funcall getter)))
1925 (let ((message-log-max nil))
1926 (if company-echo-last-msg
1927 (message "%s" company-echo-last-msg)
1930 (defsubst company-echo-show-soon (&optional getter)
1931 (when company-echo-timer
1932 (cancel-timer company-echo-timer))
1933 (setq company-echo-timer (run-with-timer 0 nil 'company-echo-show getter)))
1935 (defsubst company-echo-show-when-idle (&optional getter)
1937 (company-echo-show getter)))
1939 (defsubst company-echo-show-when-not-busy (&optional getter)
1940 "Run `company-echo-show' with arg GETTER once Emacs isn't busy."
1941 (when (sit-for company-echo-delay)
1942 (company-echo-show getter)))
1944 (defun company-echo-format ()
1946 (let ((limit (window-width (minibuffer-window)))
1948 ;; Roll to selection.
1949 (candidates (nthcdr company-selection company-candidates))
1950 (i (if company-show-numbers company-selection 99999))
1954 (setq comp (company-reformat (pop candidates))
1955 len (+ len 1 (length comp)))
1959 (setq comp (propertize (format "%d: %s" i comp)
1960 'face 'company-echo))
1963 (add-text-properties 3 (+ 3 (length company-common))
1964 '(face company-echo-common) comp))
1965 (setq comp (propertize comp 'face 'company-echo))
1966 (add-text-properties 0 (length company-common)
1967 '(face company-echo-common) comp))
1969 (setq candidates nil)
1972 (mapconcat 'identity (nreverse msg) " ")))
1974 (defun company-echo-strip-common-format ()
1976 (let ((limit (window-width (minibuffer-window)))
1977 (len (+ (length company-prefix) 2))
1978 ;; Roll to selection.
1979 (candidates (nthcdr company-selection company-candidates))
1980 (i (if company-show-numbers company-selection 99999))
1984 (setq comp (company-strip-prefix (pop candidates))
1985 len (+ len 2 (length comp)))
1988 (setq comp (format "%s (%d)" comp i))
1992 (setq candidates nil)
1993 (push (propertize comp 'face 'company-echo) msg)))
1995 (concat (propertize company-prefix 'face 'company-echo-common) "{"
1996 (mapconcat 'identity (nreverse msg) ", ")
1999 (defun company-echo-hide ()
2000 (unless (equal company-echo-last-msg "")
2001 (setq company-echo-last-msg "")
2002 (company-echo-show)))
2004 (defun company-echo-frontend (command)
2005 "A `company-mode' front-end showing the candidates in the echo area."
2007 (post-command (company-echo-show-soon 'company-echo-format))
2008 (hide (company-echo-hide))))
2010 (defun company-echo-strip-common-frontend (command)
2011 "A `company-mode' front-end showing the candidates in the echo area."
2013 (post-command (company-echo-show-soon 'company-echo-strip-common-format))
2014 (hide (company-echo-hide))))
2016 (defun company-echo-metadata-frontend (command)
2017 "A `company-mode' front-end showing the documentation in the echo area."
2019 (post-command (company-echo-show-when-idle 'company-fetch-metadata))
2020 (hide (company-echo-hide))))
2022 ;; templates ;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;
2024 (autoload 'company-template-declare-template "company-template")
2027 ;;; company.el ends here