]> code.delx.au - gnu-emacs-elpa/blob - company.el
5f9d6e1218790fb65bef280517cf819fa63de102
[gnu-emacs-elpa] / company.el
1 ;;; company.el --- Modular in-buffer completion framework -*- lexical-binding: t -*-
2
3 ;; Copyright (C) 2009-2013 Free Software Foundation, Inc.
4
5 ;; Author: Nikolaj Schumacher
6 ;; Maintainer: Dmitry Gutov <dgutov@yandex.ru>
7 ;; Version: 0.6.12
8 ;; Keywords: abbrev, convenience, matching
9 ;; URL: http://company-mode.github.io/
10 ;; Compatibility: GNU Emacs 22.x, GNU Emacs 23.x, GNU Emacs 24.x
11
12 ;; This file is part of GNU Emacs.
13
14 ;; GNU Emacs is free software: you can redistribute it and/or modify
15 ;; it under the terms of the GNU General Public License as published by
16 ;; the Free Software Foundation, either version 3 of the License, or
17 ;; (at your option) any later version.
18
19 ;; GNU Emacs is distributed in the hope that it will be useful,
20 ;; but WITHOUT ANY WARRANTY; without even the implied warranty of
21 ;; MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
22 ;; GNU General Public License for more details.
23
24 ;; You should have received a copy of the GNU General Public License
25 ;; along with GNU Emacs. If not, see <http://www.gnu.org/licenses/>.
26
27 ;;; Commentary:
28 ;;
29 ;; Company is a modular completion mechanism. Modules for retrieving completion
30 ;; candidates are called back-ends, modules for displaying them are front-ends.
31 ;;
32 ;; Company comes with many back-ends, e.g. `company-elisp'. These are
33 ;; distributed in separate files and can be used individually.
34 ;;
35 ;; Place company.el and the back-ends you want to use in a directory and add the
36 ;; following to your .emacs:
37 ;; (add-to-list 'load-path "/path/to/company")
38 ;; (autoload 'company-mode "company" nil t)
39 ;;
40 ;; Enable company-mode with M-x company-mode. For further information look at
41 ;; the documentation for `company-mode' (C-h f company-mode RET)
42 ;;
43 ;; If you want to start a specific back-end, call it interactively or use
44 ;; `company-begin-backend'. For example:
45 ;; M-x company-abbrev will prompt for and insert an abbrev.
46 ;;
47 ;; To write your own back-end, look at the documentation for `company-backends'.
48 ;; Here is a simple example completing "foo":
49 ;;
50 ;; (defun company-my-backend (command &optional arg &rest ignored)
51 ;; (case command
52 ;; (prefix (when (looking-back "foo\\>")
53 ;; (match-string 0)))
54 ;; (candidates (list "foobar" "foobaz" "foobarbaz"))
55 ;; (meta (format "This value is named %s" arg))))
56 ;;
57 ;; Sometimes it is a good idea to mix several back-ends together, for example to
58 ;; enrich gtags with dabbrev-code results (to emulate local variables).
59 ;; To do this, add a list with both back-ends as an element in company-backends.
60 ;;
61 ;; Known Issues:
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'.
65 ;;
66 ;;; Change Log:
67 ;;
68 ;; See NEWS.md in the repository.
69
70 ;;; Code:
71
72 (eval-when-compile (require 'cl))
73
74 ;; FIXME: Use `user-error'.
75 (add-to-list 'debug-ignored-errors "^.* frontend cannot be used twice$")
76 (add-to-list 'debug-ignored-errors "^Echo area cannot be used twice$")
77 (add-to-list 'debug-ignored-errors "^No \\(document\\|loc\\)ation available$")
78 (add-to-list 'debug-ignored-errors "^Company not ")
79 (add-to-list 'debug-ignored-errors "^No candidate number ")
80 (add-to-list 'debug-ignored-errors "^Cannot complete at point$")
81 (add-to-list 'debug-ignored-errors "^No other back-end$")
82
83 (defgroup company nil
84 "Extensible inline text completion mechanism"
85 :group 'abbrev
86 :group 'convenience
87 :group 'matching)
88
89 (defface company-tooltip
90 '((default :foreground "black")
91 (((class color) (min-colors 88) (background light))
92 (:background "cornsilk"))
93 (((class color) (min-colors 88) (background dark))
94 (:background "yellow")))
95 "Face used for the tooltip.")
96
97 (defface company-tooltip-selection
98 '((default :inherit company-tooltip)
99 (((class color) (min-colors 88) (background light))
100 (:background "light blue"))
101 (((class color) (min-colors 88) (background dark))
102 (:background "orange1"))
103 (t (:background "green")))
104 "Face used for the selection in the tooltip.")
105
106 (defface company-tooltip-mouse
107 '((default :inherit highlight))
108 "Face used for the tooltip item under the mouse.")
109
110 (defface company-tooltip-common
111 '((default :inherit company-tooltip)
112 (((background light))
113 :foreground "darkred")
114 (((background dark))
115 :foreground "red"))
116 "Face used for the common completion in the tooltip.")
117
118 (defface company-tooltip-common-selection
119 '((default :inherit company-tooltip-selection)
120 (((background light))
121 :foreground "darkred")
122 (((background dark))
123 :foreground "red"))
124 "Face used for the selected common completion in the tooltip.")
125
126 (defface company-preview
127 '((t :background "blue4"
128 :foreground "wheat"))
129 "Face used for the completion preview.")
130
131 (defface company-preview-common
132 '((t :inherit company-preview
133 :foreground "red"))
134 "Face used for the common part of the completion preview.")
135
136 (defface company-preview-search
137 '((t :inherit company-preview
138 :background "blue1"))
139 "Face used for the search string in the completion preview.")
140
141 (defface company-echo nil
142 "Face used for completions in the echo area.")
143
144 (defface company-echo-common
145 '((((background dark)) (:foreground "firebrick1"))
146 (((background light)) (:background "firebrick4")))
147 "Face used for the common part of completions in the echo area.")
148
149 (defun company-frontends-set (variable value)
150 ;; uniquify
151 (let ((remainder value))
152 (setcdr remainder (delq (car remainder) (cdr remainder))))
153 (and (memq 'company-pseudo-tooltip-unless-just-one-frontend value)
154 (memq 'company-pseudo-tooltip-frontend value)
155 (error "Pseudo tooltip frontend cannot be used twice"))
156 (and (memq 'company-preview-if-just-one-frontend value)
157 (memq 'company-preview-frontend value)
158 (error "Preview frontend cannot be used twice"))
159 (and (memq 'company-echo value)
160 (memq 'company-echo-metadata-frontend value)
161 (error "Echo area cannot be used twice"))
162 ;; preview must come last
163 (dolist (f '(company-preview-if-just-one-frontend company-preview-frontend))
164 (when (memq f value)
165 (setq value (append (delq f value) (list f)))))
166 (set variable value))
167
168 (defcustom company-frontends '(company-pseudo-tooltip-unless-just-one-frontend
169 company-preview-if-just-one-frontend
170 company-echo-metadata-frontend)
171 "The list of active front-ends (visualizations).
172 Each front-end is a function that takes one argument. It is called with
173 one of the following arguments:
174
175 `show': When the visualization should start.
176
177 `hide': When the visualization should end.
178
179 `update': When the data has been updated.
180
181 `pre-command': Before every command that is executed while the
182 visualization is active.
183
184 `post-command': After every command that is executed while the
185 visualization is active.
186
187 The visualized data is stored in `company-prefix', `company-candidates',
188 `company-common', `company-selection', `company-point' and
189 `company-search-string'."
190 :set 'company-frontends-set
191 :type '(repeat (choice (const :tag "echo" company-echo-frontend)
192 (const :tag "echo, strip common"
193 company-echo-strip-common-frontend)
194 (const :tag "show echo meta-data in echo"
195 company-echo-metadata-frontend)
196 (const :tag "pseudo tooltip"
197 company-pseudo-tooltip-frontend)
198 (const :tag "pseudo tooltip, multiple only"
199 company-pseudo-tooltip-unless-just-one-frontend)
200 (const :tag "preview" company-preview-frontend)
201 (const :tag "preview, unique only"
202 company-preview-if-just-one-frontend)
203 (function :tag "custom function" nil))))
204
205 (defcustom company-tooltip-limit 10
206 "The maximum number of candidates in the tooltip"
207 :type 'integer)
208
209 (defcustom company-tooltip-minimum 6
210 "The minimum height of the tooltip.
211 If this many lines are not available, prefer to display the tooltip above."
212 :type 'integer)
213
214 (defvar company-safe-backends
215 '((company-abbrev . "Abbrev")
216 (company-capf . "completion-at-point-functions")
217 (company-clang . "Clang")
218 (company-cmake . "CMake")
219 (company-css . "CSS")
220 (company-dabbrev . "dabbrev for plain text")
221 (company-dabbrev-code . "dabbrev for code")
222 (company-eclim . "Eclim (an Eclipse interface)")
223 (company-elisp . "Emacs Lisp")
224 (company-etags . "etags")
225 (company-files . "Files")
226 (company-gtags . "GNU Global")
227 (company-ispell . "Ispell")
228 (company-keywords . "Programming language keywords")
229 (company-nxml . "nxml")
230 (company-oddmuse . "Oddmuse")
231 (company-pysmell . "PySmell")
232 (company-ropemacs . "ropemacs")
233 (company-semantic . "Semantic")
234 (company-tempo . "Tempo templates")
235 (company-xcode . "Xcode")))
236 (put 'company-safe-backends 'risky-local-variable t)
237
238 (defun company-safe-backends-p (backends)
239 (and (consp backends)
240 (not (dolist (backend backends)
241 (unless (if (consp backend)
242 (company-safe-backends-p backend)
243 (assq backend company-safe-backends))
244 (return t))))))
245
246 (defvar company--include-capf (version< "24.3.50" emacs-version))
247
248 (defcustom company-backends `(,@(unless company--include-capf
249 (list 'company-elisp))
250 company-nxml company-css
251 company-eclim company-semantic company-clang
252 company-xcode company-ropemacs company-cmake
253 ,@(when company--include-capf
254 (list 'company-capf))
255 (company-gtags company-etags company-dabbrev-code
256 company-keywords)
257 company-oddmuse company-files company-dabbrev)
258 "The list of active back-ends (completion engines).
259 Each list elements can itself be a list of back-ends. In that case their
260 completions are merged. Otherwise only the first matching back-end returns
261 results.
262
263 `company-begin-backend' can be used to start a specific back-end,
264 `company-other-backend' will skip to the next matching back-end in the list.
265
266 Each back-end is a function that takes a variable number of arguments.
267 The first argument is the command requested from the back-end. It is one
268 of the following:
269
270 `prefix': The back-end should return the text to be completed. It must be
271 text immediately before point. Returning nil passes control to the next
272 back-end. The function should return `stop' if it should complete but
273 cannot \(e.g. if it is in the middle of a string\). Instead of a string,
274 the back-end may return a cons where car is the prefix and cdr is used in
275 `company-minimum-prefix-length' test. It's either number or t, in which
276 case the test automatically succeeds.
277
278 `candidates': The second argument is the prefix to be completed. The
279 return value should be a list of candidates that start with the prefix.
280
281 Optional commands:
282
283 `sorted': Return t here to indicate that the candidates are sorted and will
284 not need to be sorted again.
285
286 `duplicates': If non-nil, company will take care of removing duplicates
287 from the list.
288
289 `no-cache': Usually company doesn't ask for candidates again as completion
290 progresses, unless the back-end returns t for this command. The second
291 argument is the latest prefix.
292
293 `meta': The second argument is a completion candidate. Return a (short)
294 documentation string for it.
295
296 `doc-buffer': The second argument is a completion candidate. Return a
297 buffer with documentation for it. Preferably use `company-doc-buffer',
298
299 `location': The second argument is a completion candidate. Return the cons
300 of buffer and buffer location, or of file and line number where the
301 completion candidate was defined.
302
303 `require-match': If this returns t, the user is not allowed to enter
304 anything not offered as a candidate. Use with care! The default value nil
305 gives the user that choice with `company-require-match'. Return value
306 `never' overrides that option the other way around.
307
308 `init': Called once for each buffer. The back-end can check for external
309 programs and files and load any required libraries. Raising an error here
310 will show up in message log once, and the back-end will not be used for
311 completion.
312
313 `post-completion': Called after a completion candidate has been inserted
314 into the buffer. The second argument is the candidate. Can be used to
315 modify it, e.g. to expand a snippet.
316
317 The back-end should return nil for all commands it does not support or
318 does not know about. It should also be callable interactively and use
319 `company-begin-backend' to start itself in that case."
320 :type `(repeat
321 (choice
322 :tag "Back-end"
323 ,@(mapcar (lambda (b) `(const :tag ,(cdr b) ,(car b)))
324 company-safe-backends)
325 (symbol :tag "User defined")
326 (repeat :tag "Merged Back-ends"
327 (choice :tag "Back-end"
328 ,@(mapcar (lambda (b)
329 `(const :tag ,(cdr b) ,(car b)))
330 company-safe-backends)
331 (symbol :tag "User defined"))))))
332
333 (put 'company-backends 'safe-local-variable 'company-safe-backends-p)
334
335 (defcustom company-completion-started-hook nil
336 "Hook run when company starts completing.
337 The hook is called with one argument that is non-nil if the completion was
338 started manually."
339 :type 'hook)
340
341 (defcustom company-completion-cancelled-hook nil
342 "Hook run when company cancels completing.
343 The hook is called with one argument that is non-nil if the completion was
344 aborted manually."
345 :type 'hook)
346
347 (defcustom company-completion-finished-hook nil
348 "Hook run when company successfully completes.
349 The hook is called with the selected candidate as an argument.
350
351 If you indend to use it to post-process candidates from a specific
352 back-end, consider using the `post-completion' command instead."
353 :type 'hook)
354
355 (defcustom company-minimum-prefix-length 3
356 "The minimum prefix length for automatic completion."
357 :type '(integer :tag "prefix length"))
358
359 (defcustom company-require-match 'company-explicit-action-p
360 "If enabled, disallow non-matching input.
361 This can be a function do determine if a match is required.
362
363 This can be overridden by the back-end, if it returns t or `never' to
364 `require-match'. `company-auto-complete' also takes precedence over this."
365 :type '(choice (const :tag "Off" nil)
366 (function :tag "Predicate function")
367 (const :tag "On, if user interaction took place"
368 'company-explicit-action-p)
369 (const :tag "On" t)))
370
371 (defcustom company-auto-complete nil
372 "Determines when to auto-complete.
373 If this is enabled, all characters from `company-auto-complete-chars'
374 complete the selected completion. This can also be a function."
375 :type '(choice (const :tag "Off" nil)
376 (function :tag "Predicate function")
377 (const :tag "On, if user interaction took place"
378 'company-explicit-action-p)
379 (const :tag "On" t)))
380
381 (defcustom company-auto-complete-chars '(?\ ?\) ?.)
382 "Determines which characters trigger an automatic completion.
383 See `company-auto-complete'. If this is a string, each string character
384 causes completion. If it is a list of syntax description characters (see
385 `modify-syntax-entry'), all characters with that syntax auto-complete.
386
387 This can also be a function, which is called with the new input and should
388 return non-nil if company should auto-complete.
389
390 A character that is part of a valid candidate never triggers auto-completion."
391 :type '(choice (string :tag "Characters")
392 (set :tag "Syntax"
393 (const :tag "Whitespace" ?\ )
394 (const :tag "Symbol" ?_)
395 (const :tag "Opening parentheses" ?\()
396 (const :tag "Closing parentheses" ?\))
397 (const :tag "Word constituent" ?w)
398 (const :tag "Punctuation." ?.)
399 (const :tag "String quote." ?\")
400 (const :tag "Paired delimiter." ?$)
401 (const :tag "Expression quote or prefix operator." ?\')
402 (const :tag "Comment starter." ?<)
403 (const :tag "Comment ender." ?>)
404 (const :tag "Character-quote." ?/)
405 (const :tag "Generic string fence." ?|)
406 (const :tag "Generic comment fence." ?!))
407 (function :tag "Predicate function")))
408
409 (defcustom company-idle-delay .7
410 "The idle delay in seconds until automatic completions starts.
411 A value of nil means never complete automatically, t means complete
412 immediately when a prefix of `company-minimum-prefix-length' is reached."
413 :type '(choice (const :tag "never (nil)" nil)
414 (const :tag "immediate (t)" t)
415 (number :tag "seconds")))
416
417 (defcustom company-begin-commands '(self-insert-command)
418 "A list of commands following which company will start completing.
419 If this is t, it will complete after any command. See `company-idle-delay'.
420
421 Alternatively any command with a non-nil `company-begin' property is treated
422 as if it was on this list."
423 :type '(choice (const :tag "Any command" t)
424 (const :tag "Self insert command" '(self-insert-command))
425 (repeat :tag "Commands" function)))
426
427 (defcustom company-show-numbers nil
428 "If enabled, show quick-access numbers for the first ten candidates."
429 :type '(choice (const :tag "off" nil)
430 (const :tag "on" t)))
431
432 (defcustom company-selection-wrap-around nil
433 "If enabled, selecting item before first or after last wraps around."
434 :type '(choice (const :tag "off" nil)
435 (const :tag "on" t)))
436
437 (defvar company-end-of-buffer-workaround t
438 "Work around a visualization bug when completing at the end of the buffer.
439 The work-around consists of adding a newline.")
440
441 ;;; mode ;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;
442
443 (defvar company-mode-map (make-sparse-keymap)
444 "Keymap used by `company-mode'.")
445
446 (defvar company-active-map
447 (let ((keymap (make-sparse-keymap)))
448 (define-key keymap "\e\e\e" 'company-abort)
449 (define-key keymap "\C-g" 'company-abort)
450 (define-key keymap (kbd "M-n") 'company-select-next)
451 (define-key keymap (kbd "M-p") 'company-select-previous)
452 (define-key keymap (kbd "<down>") 'company-select-next-or-abort)
453 (define-key keymap (kbd "<up>") 'company-select-previous-or-abort)
454 (define-key keymap [down-mouse-1] 'ignore)
455 (define-key keymap [down-mouse-3] 'ignore)
456 (define-key keymap [mouse-1] 'company-complete-mouse)
457 (define-key keymap [mouse-3] 'company-select-mouse)
458 (define-key keymap [up-mouse-1] 'ignore)
459 (define-key keymap [up-mouse-3] 'ignore)
460 (define-key keymap [return] 'company-complete-selection)
461 (define-key keymap (kbd "RET") 'company-complete-selection)
462 (define-key keymap [tab] 'company-complete-common)
463 (define-key keymap (kbd "TAB") 'company-complete-common)
464 (define-key keymap (kbd "<f1>") 'company-show-doc-buffer)
465 (define-key keymap "\C-w" 'company-show-location)
466 (define-key keymap "\C-s" 'company-search-candidates)
467 (define-key keymap "\C-\M-s" 'company-filter-candidates)
468 (dotimes (i 10)
469 (define-key keymap (vector (+ (aref (kbd "M-0") 0) i))
470 `(lambda () (interactive) (company-complete-number ,i))))
471
472 keymap)
473 "Keymap that is enabled during an active completion.")
474
475 (defvar company--disabled-backends nil)
476
477 (defun company-init-backend (backend)
478 (and (symbolp backend)
479 (not (fboundp backend))
480 (ignore-errors (require backend nil t)))
481
482 (if (or (symbolp backend)
483 (functionp backend))
484 (condition-case err
485 (progn
486 (funcall backend 'init)
487 (put backend 'company-init t))
488 (error
489 (put backend 'company-init 'failed)
490 (unless (memq backend company--disabled-backends)
491 (message "Company back-end '%s' could not be initialized:\n%s"
492 backend (error-message-string err)))
493 (pushnew backend company--disabled-backends)
494 nil))
495 (mapc 'company-init-backend backend)))
496
497 (defvar company-default-lighter " company")
498
499 (defvar company-lighter company-default-lighter)
500 (make-variable-buffer-local 'company-lighter)
501
502 ;;;###autoload
503 (define-minor-mode company-mode
504 "\"complete anything\"; is an in-buffer completion framework.
505 Completion starts automatically, depending on the values
506 `company-idle-delay' and `company-minimum-prefix-length'.
507
508 Completion can be controlled with the commands:
509 `company-complete-common', `company-complete-selection', `company-complete',
510 `company-select-next', `company-select-previous'. If these commands are
511 called before `company-idle-delay', completion will also start.
512
513 Completions can be searched with `company-search-candidates' or
514 `company-filter-candidates'. These can be used while completion is
515 inactive, as well.
516
517 The completion data is retrieved using `company-backends' and displayed
518 using `company-frontends'. If you want to start a specific back-end, call
519 it interactively or use `company-begin-backend'.
520
521 regular keymap (`company-mode-map'):
522
523 \\{company-mode-map}
524 keymap during active completions (`company-active-map'):
525
526 \\{company-active-map}"
527 nil company-lighter company-mode-map
528 (if company-mode
529 (progn
530 (add-hook 'pre-command-hook 'company-pre-command nil t)
531 (add-hook 'post-command-hook 'company-post-command nil t)
532 (mapc 'company-init-backend company-backends))
533 (remove-hook 'pre-command-hook 'company-pre-command t)
534 (remove-hook 'post-command-hook 'company-post-command t)
535 (company-cancel)
536 (kill-local-variable 'company-point)))
537
538 (defcustom company-global-modes t
539 "Modes for which `company-mode' mode is turned on by `global-company-mode'.
540 If nil, means no modes. If t, then all major modes have it turned on.
541 If a list, it should be a list of `major-mode' symbol names for which
542 `company-mode' should be automatically turned on. The sense of the list is
543 negated if it begins with `not'. For example:
544 (c-mode c++-mode)
545 means that `company-mode' is turned on for buffers in C and C++ modes only.
546 (not message-mode)
547 means that `company-mode' is always turned on except in `message-mode' buffers."
548 :type '(choice (const :tag "none" nil)
549 (const :tag "all" t)
550 (set :menu-tag "mode specific" :tag "modes"
551 :value (not)
552 (const :tag "Except" not)
553 (repeat :inline t (symbol :tag "mode")))))
554
555 ;;;###autoload
556 (define-globalized-minor-mode global-company-mode company-mode company-mode-on)
557
558 (defun company-mode-on ()
559 (when (and (not (or noninteractive (eq (aref (buffer-name) 0) ?\s)))
560 (cond ((eq company-global-modes t)
561 t)
562 ((eq (car-safe company-global-modes) 'not)
563 (not (memq major-mode (cdr company-global-modes))))
564 (t (memq major-mode company-global-modes))))
565 (company-mode 1)))
566
567 (defsubst company-assert-enabled ()
568 (unless company-mode
569 (company-uninstall-map)
570 (error "Company not enabled")))
571
572 ;;; keymaps ;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;
573
574 (defvar company-my-keymap nil)
575 (make-variable-buffer-local 'company-my-keymap)
576
577 (defvar company-emulation-alist '((t . nil)))
578
579 (defsubst company-enable-overriding-keymap (keymap)
580 (company-uninstall-map)
581 (setq company-my-keymap keymap))
582
583 (defun company-ensure-emulation-alist ()
584 (unless (eq 'company-emulation-alist (car emulation-mode-map-alists))
585 (setq emulation-mode-map-alists
586 (cons 'company-emulation-alist
587 (delq 'company-emulation-alist emulation-mode-map-alists)))))
588
589 (defun company-install-map ()
590 (unless (or (cdar company-emulation-alist)
591 (null company-my-keymap))
592 (setf (cdar company-emulation-alist) company-my-keymap)))
593
594 (defun company-uninstall-map ()
595 (setf (cdar company-emulation-alist) nil))
596
597 ;; Hack:
598 ;; Emacs calculates the active keymaps before reading the event. That means we
599 ;; cannot change the keymap from a timer. So we send a bogus command.
600 (defun company-ignore ()
601 (interactive)
602 (setq this-command last-command))
603
604 (global-set-key '[31415926] 'company-ignore)
605
606 (defun company-input-noop ()
607 (push 31415926 unread-command-events))
608
609 (defun company--column (&optional pos)
610 (save-excursion
611 (when pos (goto-char pos))
612 (save-restriction
613 (+ (save-excursion
614 (vertical-motion 0)
615 (narrow-to-region (point) (point-max))
616 (let ((prefix (get-text-property (point) 'line-prefix)))
617 (if prefix (length prefix) 0)))
618 (current-column)))))
619
620 (defun company--row (&optional pos)
621 (save-excursion
622 (when pos (goto-char pos))
623 (count-screen-lines (window-start)
624 (progn (vertical-motion 0) (point)))))
625
626 ;;; backends ;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;
627
628 (defvar company-backend nil)
629 (make-variable-buffer-local 'company-backend)
630
631 (defun company-grab (regexp &optional expression limit)
632 (when (looking-back regexp limit)
633 (or (match-string-no-properties (or expression 0)) "")))
634
635 (defun company-grab-line (regexp &optional expression)
636 (company-grab regexp expression (point-at-bol)))
637
638 (defun company-grab-symbol ()
639 (if (looking-at "\\_>")
640 (buffer-substring (point) (save-excursion (skip-syntax-backward "w_")
641 (point)))
642 (unless (and (char-after) (memq (char-syntax (char-after)) '(?w ?_)))
643 "")))
644
645 (defun company-grab-word ()
646 (if (looking-at "\\>")
647 (buffer-substring (point) (save-excursion (skip-syntax-backward "w")
648 (point)))
649 (unless (and (char-after) (eq (char-syntax (char-after)) ?w))
650 "")))
651
652 (defun company-in-string-or-comment ()
653 (let ((ppss (syntax-ppss)))
654 (or (car (setq ppss (nthcdr 3 ppss)))
655 (car (setq ppss (cdr ppss)))
656 (nth 3 ppss))))
657
658 (if (fboundp 'locate-dominating-file)
659 (defalias 'company-locate-dominating-file 'locate-dominating-file)
660 (defun company-locate-dominating-file (file name)
661 (catch 'root
662 (let ((dir (file-name-directory file))
663 (prev-dir nil))
664 (while (not (equal dir prev-dir))
665 (when (file-exists-p (expand-file-name name dir))
666 (throw 'root dir))
667 (setq prev-dir dir
668 dir (file-name-directory (directory-file-name dir))))))))
669
670 (defun company-call-backend (&rest args)
671 (if (functionp company-backend)
672 (apply company-backend args)
673 (apply 'company--multi-backend-adapter company-backend args)))
674
675 (defun company--multi-backend-adapter (backends command &rest args)
676 (let ((backends (loop for b in backends
677 when (not (and (symbolp b)
678 (eq 'failed (get b 'company-init))))
679 collect b)))
680 (case command
681 (candidates
682 (loop for backend in backends
683 when (equal (funcall backend 'prefix)
684 (car args))
685 append (apply backend 'candidates args)))
686 (sorted nil)
687 (duplicates t)
688 (otherwise
689 (let (value)
690 (dolist (backend backends)
691 (when (setq value (apply backend command args))
692 (return value))))))))
693
694 ;;; completion mechanism ;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;
695
696 (defvar company-prefix nil)
697 (make-variable-buffer-local 'company-prefix)
698
699 (defvar company-candidates nil)
700 (make-variable-buffer-local 'company-candidates)
701
702 (defvar company-candidates-length nil)
703 (make-variable-buffer-local 'company-candidates-length)
704
705 (defvar company-candidates-cache nil)
706 (make-variable-buffer-local 'company-candidates-cache)
707
708 (defvar company-candidates-predicate nil)
709 (make-variable-buffer-local 'company-candidates-predicate)
710
711 (defvar company-common nil)
712 (make-variable-buffer-local 'company-common)
713
714 (defvar company-selection 0)
715 (make-variable-buffer-local 'company-selection)
716
717 (defvar company-selection-changed nil)
718 (make-variable-buffer-local 'company-selection-changed)
719
720 (defvar company--explicit-action nil
721 "Non-nil, if explicit completion took place.")
722 (make-variable-buffer-local 'company--explicit-action)
723
724 (defvar company--auto-completion nil
725 "Non-nil when current candidate is being completed automatically.
726 Controlled by `company-auto-complete'.")
727
728 (defvar company--point-max nil)
729 (make-variable-buffer-local 'company--point-max)
730
731 (defvar company-point nil)
732 (make-variable-buffer-local 'company-point)
733
734 (defvar company-timer nil)
735
736 (defvar company-added-newline nil)
737 (make-variable-buffer-local 'company-added-newline)
738
739 (defsubst company-strip-prefix (str)
740 (substring str (length company-prefix)))
741
742 (defmacro company-with-candidate-inserted (candidate &rest body)
743 "Evaluate BODY with CANDIDATE temporarily inserted.
744 This is a tool for back-ends that need candidates inserted before they
745 can retrieve meta-data for them."
746 (declare (indent 1))
747 `(let ((inhibit-modification-hooks t)
748 (inhibit-point-motion-hooks t)
749 (modified-p (buffer-modified-p)))
750 (insert (company-strip-prefix ,candidate))
751 (unwind-protect
752 (progn ,@body)
753 (delete-region company-point (point)))))
754
755 (defun company-explicit-action-p ()
756 "Return whether explicit completion action was taken by the user."
757 (or company--explicit-action
758 company-selection-changed))
759
760 (defun company-reformat (candidate)
761 ;; company-ispell needs this, because the results are always lower-case
762 ;; It's mory efficient to fix it only when they are displayed.
763 (concat company-prefix (substring candidate (length company-prefix))))
764
765 (defun company--should-complete ()
766 (and (not (or buffer-read-only overriding-terminal-local-map
767 overriding-local-map))
768 ;; Check if in the middle of entering a key combination.
769 (or (equal (this-command-keys-vector) [])
770 (not (keymapp (key-binding (this-command-keys-vector)))))
771 (eq company-idle-delay t)
772 (or (eq t company-begin-commands)
773 (memq this-command company-begin-commands)
774 (and (symbolp this-command) (get this-command 'company-begin)))
775 (not (and transient-mark-mode mark-active))))
776
777 (defun company-call-frontends (command)
778 (dolist (frontend company-frontends)
779 (condition-case err
780 (funcall frontend command)
781 (error (error "Company: Front-end %s error \"%s\" on command %s"
782 frontend (error-message-string err) command)))))
783
784 (defun company-set-selection (selection &optional force-update)
785 (setq selection
786 (if company-selection-wrap-around
787 (mod selection company-candidates-length)
788 (max 0 (min (1- company-candidates-length) selection))))
789 (when (or force-update (not (equal selection company-selection)))
790 (setq company-selection selection
791 company-selection-changed t)
792 (company-call-frontends 'update)))
793
794 (defun company-apply-predicate (candidates predicate)
795 (let (new)
796 (dolist (c candidates)
797 (when (funcall predicate c)
798 (push c new)))
799 (nreverse new)))
800
801 (defun company-update-candidates (candidates)
802 (setq company-candidates-length (length candidates))
803 (if (> company-selection 0)
804 ;; Try to restore the selection
805 (let ((selected (nth company-selection company-candidates)))
806 (setq company-selection 0
807 company-candidates candidates)
808 (when selected
809 (while (and candidates (string< (pop candidates) selected))
810 (incf company-selection))
811 (unless candidates
812 ;; Make sure selection isn't out of bounds.
813 (setq company-selection (min (1- company-candidates-length)
814 company-selection)))))
815 (setq company-selection 0
816 company-candidates candidates))
817 ;; Save in cache:
818 (push (cons company-prefix company-candidates) company-candidates-cache)
819 ;; Calculate common.
820 (let ((completion-ignore-case (company-call-backend 'ignore-case)))
821 (setq company-common (company--safe-candidate
822 (try-completion company-prefix company-candidates))))
823 (when (eq company-common t)
824 (setq company-candidates nil)))
825
826 (defun company--safe-candidate (str)
827 (or (company-call-backend 'crop str)
828 str))
829
830 (defun company-calculate-candidates (prefix)
831 (let ((candidates (cdr (assoc prefix company-candidates-cache)))
832 (ignore-case (company-call-backend 'ignore-case)))
833 (or candidates
834 (when company-candidates-cache
835 (let ((len (length prefix))
836 (completion-ignore-case ignore-case)
837 prev)
838 (dotimes (i (1+ len))
839 (when (setq prev (cdr (assoc (substring prefix 0 (- len i))
840 company-candidates-cache)))
841 (setq candidates (all-completions prefix prev))
842 (return t)))))
843 ;; no cache match, call back-end
844 (progn
845 (setq candidates (company-call-backend 'candidates prefix))
846 (when company-candidates-predicate
847 (setq candidates
848 (company-apply-predicate candidates
849 company-candidates-predicate)))
850 (unless (company-call-backend 'sorted)
851 (setq candidates (sort candidates 'string<)))
852 (when (company-call-backend 'duplicates)
853 ;; strip duplicates
854 (let ((c2 candidates))
855 (while c2
856 (setcdr c2 (progn (while (equal (pop c2) (car c2)))
857 c2)))))))
858 (when candidates
859 (if (or (cdr candidates)
860 (not (eq t (compare-strings (car candidates) nil nil
861 prefix nil nil ignore-case))))
862 candidates
863 ;; Already completed and unique; don't start.
864 t))))
865
866 (defun company-idle-begin (buf win tick pos)
867 (and company-mode
868 (eq buf (current-buffer))
869 (eq win (selected-window))
870 (eq tick (buffer-chars-modified-tick))
871 (eq pos (point))
872 (not company-candidates)
873 (not (equal (point) company-point))
874 (let ((company-idle-delay t)
875 (company-begin-commands t))
876 (company-begin)
877 (when company-candidates
878 (company-input-noop)
879 (company-post-command)))))
880
881 (defun company-auto-begin ()
882 (company-assert-enabled)
883 (and company-mode
884 (not company-candidates)
885 (let ((company-idle-delay t)
886 (company-minimum-prefix-length 0)
887 (company-begin-commands t))
888 (company-begin)))
889 ;; Return non-nil if active.
890 company-candidates)
891
892 (defun company-manual-begin ()
893 (interactive)
894 (setq company--explicit-action t)
895 (unwind-protect
896 (company-auto-begin)
897 (unless company-candidates
898 (setq company--explicit-action nil))))
899
900 (defun company-other-backend (&optional backward)
901 (interactive (list current-prefix-arg))
902 (company-assert-enabled)
903 (if company-backend
904 (let* ((after (cdr (member company-backend company-backends)))
905 (before (cdr (member company-backend (reverse company-backends))))
906 (next (if backward
907 (append before (reverse after))
908 (append after (reverse before)))))
909 (company-cancel)
910 (dolist (backend next)
911 (when (ignore-errors (company-begin-backend backend))
912 (return t))))
913 (company-manual-begin))
914 (unless company-candidates
915 (error "No other back-end")))
916
917 (defun company-require-match-p ()
918 (let ((backend-value (company-call-backend 'require-match)))
919 (or (eq backend-value t)
920 (and (not (eq backend-value 'never))
921 (if (functionp company-require-match)
922 (funcall company-require-match)
923 (eq company-require-match t))))))
924
925 (defun company-auto-complete-p (input)
926 "Return non-nil, if input starts with punctuation or parentheses."
927 (and (if (functionp company-auto-complete)
928 (funcall company-auto-complete)
929 company-auto-complete)
930 (if (functionp company-auto-complete-chars)
931 (funcall company-auto-complete-chars input)
932 (if (consp company-auto-complete-chars)
933 (memq (char-syntax (string-to-char input))
934 company-auto-complete-chars)
935 (string-match (substring input 0 1) company-auto-complete-chars)))))
936
937 (defun company--incremental-p ()
938 (and (> (point) company-point)
939 (> (point-max) company--point-max)
940 (not (eq this-command 'backward-delete-char-untabify))
941 (equal (buffer-substring (- company-point (length company-prefix))
942 company-point)
943 company-prefix)))
944
945 (defsubst company--string-incremental-p (old-prefix new-prefix)
946 (and (> (length new-prefix) (length old-prefix))
947 (equal old-prefix (substring new-prefix 0 (length old-prefix)))))
948
949 (defun company--continue-failed (new-prefix)
950 (when (company--incremental-p)
951 (let ((input (buffer-substring-no-properties (point) company-point)))
952 (cond
953 ((company-auto-complete-p input)
954 ;; auto-complete
955 (save-excursion
956 (goto-char company-point)
957 (let ((company--auto-completion t))
958 (company-complete-selection))
959 nil))
960 ((and (company--string-incremental-p company-prefix new-prefix)
961 (company-require-match-p))
962 ;; wrong incremental input, but required match
963 (delete-char (- (length input)))
964 (ding)
965 (message "Matching input is required")
966 company-candidates)
967 ((equal company-prefix (car company-candidates))
968 ;; last input was actually success
969 (company-cancel company-prefix)
970 nil)))))
971
972 (defun company--good-prefix-p (prefix)
973 (and (or (company-explicit-action-p)
974 (unless (eq prefix 'stop)
975 (or (eq (cdr-safe prefix) t)
976 (>= (or (cdr-safe prefix) (length prefix))
977 company-minimum-prefix-length))))
978 (stringp (or (car-safe prefix) prefix))))
979
980 (defun company--continue ()
981 (when (company-call-backend 'no-cache company-prefix)
982 ;; Don't complete existing candidates, fetch new ones.
983 (setq company-candidates-cache nil))
984 (let* ((new-prefix (company-call-backend 'prefix))
985 (c (when (and (company--good-prefix-p new-prefix)
986 (setq new-prefix (or (car-safe new-prefix) new-prefix))
987 (= (- (point) (length new-prefix))
988 (- company-point (length company-prefix))))
989 (setq new-prefix (or (car-safe new-prefix) new-prefix))
990 (company-calculate-candidates new-prefix))))
991 (or (cond
992 ((eq c t)
993 ;; t means complete/unique.
994 (company-cancel new-prefix)
995 nil)
996 ((consp c)
997 ;; incremental match
998 (setq company-prefix new-prefix)
999 (company-update-candidates c)
1000 c)
1001 (t (company--continue-failed new-prefix)))
1002 (company-cancel))))
1003
1004 (defun company--begin-new ()
1005 (let (prefix c)
1006 (dolist (backend (if company-backend
1007 ;; prefer manual override
1008 (list company-backend)
1009 company-backends))
1010 (setq prefix
1011 (if (or (symbolp backend)
1012 (functionp backend))
1013 (when (or (not (symbolp backend))
1014 (eq t (get backend 'company-init))
1015 (unless (get backend 'company-init)
1016 (company-init-backend backend)))
1017 (funcall backend 'prefix))
1018 (company--multi-backend-adapter backend 'prefix)))
1019 (when prefix
1020 (when (company--good-prefix-p prefix)
1021 (setq prefix (or (car-safe prefix) prefix)
1022 company-backend backend
1023 c (company-calculate-candidates prefix))
1024 ;; t means complete/unique. We don't start, so no hooks.
1025 (if (not (consp c))
1026 (when company--explicit-action
1027 (message "No completion found"))
1028 (setq company-prefix prefix)
1029 (when (symbolp backend)
1030 (setq company-lighter (concat " " (symbol-name backend))))
1031 (company-update-candidates c)
1032 (run-hook-with-args 'company-completion-started-hook
1033 (company-explicit-action-p))
1034 (company-call-frontends 'show)))
1035 (return c)))))
1036
1037 (defun company-begin ()
1038 (or (and company-candidates (company--continue))
1039 (and (company--should-complete) (company--begin-new)))
1040 (when company-candidates
1041 (when (and company-end-of-buffer-workaround (eobp))
1042 (save-excursion (insert "\n"))
1043 (setq company-added-newline (buffer-chars-modified-tick)))
1044 (setq company-point (point)
1045 company--point-max (point-max))
1046 (company-ensure-emulation-alist)
1047 (company-enable-overriding-keymap company-active-map)
1048 (company-call-frontends 'update)))
1049
1050 (defun company-cancel (&optional result)
1051 (and company-added-newline
1052 (> (point-max) (point-min))
1053 (let ((tick (buffer-chars-modified-tick)))
1054 (delete-region (1- (point-max)) (point-max))
1055 (equal tick company-added-newline))
1056 ;; Only set unmodified when tick remained the same since insert.
1057 (set-buffer-modified-p nil))
1058 (when company-prefix
1059 (if (stringp result)
1060 (progn
1061 (company-call-backend 'pre-completion result)
1062 (run-hook-with-args 'company-completion-finished-hook result)
1063 (company-call-backend 'post-completion result))
1064 (run-hook-with-args 'company-completion-cancelled-hook result)))
1065 (setq company-added-newline nil
1066 company-backend nil
1067 company-prefix nil
1068 company-candidates nil
1069 company-candidates-length nil
1070 company-candidates-cache nil
1071 company-candidates-predicate nil
1072 company-common nil
1073 company-selection 0
1074 company-selection-changed nil
1075 company--explicit-action nil
1076 company-lighter company-default-lighter
1077 company--point-max nil
1078 company-point nil)
1079 (when company-timer
1080 (cancel-timer company-timer))
1081 (company-search-mode 0)
1082 (company-call-frontends 'hide)
1083 (company-enable-overriding-keymap nil))
1084
1085 (defun company-abort ()
1086 (interactive)
1087 (company-cancel t)
1088 ;; Don't start again, unless started manually.
1089 (setq company-point (point)))
1090
1091 (defun company-finish (result)
1092 (insert (company-strip-prefix result))
1093 (company-cancel result)
1094 ;; Don't start again, unless started manually.
1095 (setq company-point (point)))
1096
1097 (defsubst company-keep (command)
1098 (and (symbolp command) (get command 'company-keep)))
1099
1100 (defun company-pre-command ()
1101 (unless (company-keep this-command)
1102 (condition-case err
1103 (when company-candidates
1104 (company-call-frontends 'pre-command))
1105 (error (message "Company: An error occurred in pre-command")
1106 (message "%s" (error-message-string err))
1107 (company-cancel))))
1108 (when company-timer
1109 (cancel-timer company-timer)
1110 (setq company-timer nil))
1111 (company-uninstall-map))
1112
1113 (defun company-post-command ()
1114 (unless (company-keep this-command)
1115 (condition-case err
1116 (progn
1117 (unless (equal (point) company-point)
1118 (company-begin))
1119 (if company-candidates
1120 (company-call-frontends 'post-command)
1121 (and (numberp company-idle-delay)
1122 (or (eq t company-begin-commands)
1123 (memq this-command company-begin-commands))
1124 (setq company-timer
1125 (run-with-timer company-idle-delay nil
1126 'company-idle-begin
1127 (current-buffer) (selected-window)
1128 (buffer-chars-modified-tick) (point))))))
1129 (error (message "Company: An error occurred in post-command")
1130 (message "%s" (error-message-string err))
1131 (company-cancel))))
1132 (company-install-map))
1133
1134 ;;; search ;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;
1135
1136 (defvar company-search-string nil)
1137 (make-variable-buffer-local 'company-search-string)
1138
1139 (defvar company-search-lighter " Search: \"\"")
1140 (make-variable-buffer-local 'company-search-lighter)
1141
1142 (defvar company-search-old-map nil)
1143 (make-variable-buffer-local 'company-search-old-map)
1144
1145 (defvar company-search-old-selection 0)
1146 (make-variable-buffer-local 'company-search-old-selection)
1147
1148 (defun company-search (text lines)
1149 (let ((quoted (regexp-quote text))
1150 (i 0))
1151 (dolist (line lines)
1152 (when (string-match quoted line (length company-prefix))
1153 (return i))
1154 (incf i))))
1155
1156 (defun company-search-printing-char ()
1157 (interactive)
1158 (company-search-assert-enabled)
1159 (setq company-search-string
1160 (concat (or company-search-string "") (string last-command-event))
1161 company-search-lighter (concat " Search: \"" company-search-string
1162 "\""))
1163 (let ((pos (company-search company-search-string
1164 (nthcdr company-selection company-candidates))))
1165 (if (null pos)
1166 (ding)
1167 (company-set-selection (+ company-selection pos) t))))
1168
1169 (defun company-search-repeat-forward ()
1170 "Repeat the incremental search in completion candidates forward."
1171 (interactive)
1172 (company-search-assert-enabled)
1173 (let ((pos (company-search company-search-string
1174 (cdr (nthcdr company-selection
1175 company-candidates)))))
1176 (if (null pos)
1177 (ding)
1178 (company-set-selection (+ company-selection pos 1) t))))
1179
1180 (defun company-search-repeat-backward ()
1181 "Repeat the incremental search in completion candidates backwards."
1182 (interactive)
1183 (company-search-assert-enabled)
1184 (let ((pos (company-search company-search-string
1185 (nthcdr (- company-candidates-length
1186 company-selection)
1187 (reverse company-candidates)))))
1188 (if (null pos)
1189 (ding)
1190 (company-set-selection (- company-selection pos 1) t))))
1191
1192 (defun company-create-match-predicate ()
1193 (setq company-candidates-predicate
1194 `(lambda (candidate)
1195 ,(if company-candidates-predicate
1196 `(and (string-match ,company-search-string candidate)
1197 (funcall ,company-candidates-predicate
1198 candidate))
1199 `(string-match ,company-search-string candidate))))
1200 (company-update-candidates
1201 (company-apply-predicate company-candidates company-candidates-predicate))
1202 ;; Invalidate cache.
1203 (setq company-candidates-cache (cons company-prefix company-candidates)))
1204
1205 (defun company-filter-printing-char ()
1206 (interactive)
1207 (company-search-assert-enabled)
1208 (company-search-printing-char)
1209 (company-create-match-predicate)
1210 (company-call-frontends 'update))
1211
1212 (defun company-search-kill-others ()
1213 "Limit the completion candidates to the ones matching the search string."
1214 (interactive)
1215 (company-search-assert-enabled)
1216 (company-create-match-predicate)
1217 (company-search-mode 0)
1218 (company-call-frontends 'update))
1219
1220 (defun company-search-abort ()
1221 "Abort searching the completion candidates."
1222 (interactive)
1223 (company-search-assert-enabled)
1224 (company-set-selection company-search-old-selection t)
1225 (company-search-mode 0))
1226
1227 (defun company-search-other-char ()
1228 (interactive)
1229 (company-search-assert-enabled)
1230 (company-search-mode 0)
1231 (company--unread-last-input))
1232
1233 (defvar company-search-map
1234 (let ((i 0)
1235 (keymap (make-keymap)))
1236 (if (fboundp 'max-char)
1237 (set-char-table-range (nth 1 keymap) (cons #x100 (max-char))
1238 'company-search-printing-char)
1239 (with-no-warnings
1240 ;; obsolete in Emacs 23
1241 (let ((l (generic-character-list))
1242 (table (nth 1 keymap)))
1243 (while l
1244 (set-char-table-default table (car l) 'company-search-printing-char)
1245 (setq l (cdr l))))))
1246 (define-key keymap [t] 'company-search-other-char)
1247 (while (< i ?\s)
1248 (define-key keymap (make-string 1 i) 'company-search-other-char)
1249 (incf i))
1250 (while (< i 256)
1251 (define-key keymap (vector i) 'company-search-printing-char)
1252 (incf i))
1253 (let ((meta-map (make-sparse-keymap)))
1254 (define-key keymap (char-to-string meta-prefix-char) meta-map)
1255 (define-key keymap [escape] meta-map))
1256 (define-key keymap (vector meta-prefix-char t) 'company-search-other-char)
1257 (define-key keymap "\e\e\e" 'company-search-other-char)
1258 (define-key keymap [escape escape escape] 'company-search-other-char)
1259
1260 (define-key keymap "\C-g" 'company-search-abort)
1261 (define-key keymap "\C-s" 'company-search-repeat-forward)
1262 (define-key keymap "\C-r" 'company-search-repeat-backward)
1263 (define-key keymap "\C-o" 'company-search-kill-others)
1264 keymap)
1265 "Keymap used for incrementally searching the completion candidates.")
1266
1267 (define-minor-mode company-search-mode
1268 "Search mode for completion candidates.
1269 Don't start this directly, use `company-search-candidates' or
1270 `company-filter-candidates'."
1271 nil company-search-lighter nil
1272 (if company-search-mode
1273 (if (company-manual-begin)
1274 (progn
1275 (setq company-search-old-selection company-selection)
1276 (company-call-frontends 'update))
1277 (setq company-search-mode nil))
1278 (kill-local-variable 'company-search-string)
1279 (kill-local-variable 'company-search-lighter)
1280 (kill-local-variable 'company-search-old-selection)
1281 (company-enable-overriding-keymap company-active-map)))
1282
1283 (defun company-search-assert-enabled ()
1284 (company-assert-enabled)
1285 (unless company-search-mode
1286 (company-uninstall-map)
1287 (error "Company not in search mode")))
1288
1289 (defun company-search-candidates ()
1290 "Start searching the completion candidates incrementally.
1291
1292 \\<company-search-map>Search can be controlled with the commands:
1293 - `company-search-repeat-forward' (\\[company-search-repeat-forward])
1294 - `company-search-repeat-backward' (\\[company-search-repeat-backward])
1295 - `company-search-abort' (\\[company-search-abort])
1296
1297 Regular characters are appended to the search string.
1298
1299 The command `company-search-kill-others' (\\[company-search-kill-others])
1300 uses the search string to limit the completion candidates."
1301 (interactive)
1302 (company-search-mode 1)
1303 (company-enable-overriding-keymap company-search-map))
1304
1305 (defvar company-filter-map
1306 (let ((keymap (make-keymap)))
1307 (define-key keymap [remap company-search-printing-char]
1308 'company-filter-printing-char)
1309 (set-keymap-parent keymap company-search-map)
1310 keymap)
1311 "Keymap used for incrementally searching the completion candidates.")
1312
1313 (defun company-filter-candidates ()
1314 "Start filtering the completion candidates incrementally.
1315 This works the same way as `company-search-candidates' immediately
1316 followed by `company-search-kill-others' after each input."
1317 (interactive)
1318 (company-search-mode 1)
1319 (company-enable-overriding-keymap company-filter-map))
1320
1321 ;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;
1322
1323 (defun company-select-next ()
1324 "Select the next candidate in the list."
1325 (interactive)
1326 (when (company-manual-begin)
1327 (company-set-selection (1+ company-selection))))
1328
1329 (defun company-select-previous ()
1330 "Select the previous candidate in the list."
1331 (interactive)
1332 (when (company-manual-begin)
1333 (company-set-selection (1- company-selection))))
1334
1335 (defun company-select-next-or-abort ()
1336 "Select the next candidate if more than one, else abort
1337 and invoke the normal binding."
1338 (interactive)
1339 (if (> company-candidates-length 1)
1340 (company-select-next)
1341 (company-abort)
1342 (company--unread-last-input)))
1343
1344 (defun company-select-previous-or-abort ()
1345 "Select the previous candidate if more than one, else abort
1346 and invoke the normal binding."
1347 (interactive)
1348 (if (> company-candidates-length 1)
1349 (company-select-previous)
1350 (company-abort)
1351 (company--unread-last-input)))
1352
1353 (defvar company-pseudo-tooltip-overlay)
1354
1355 (defvar company-tooltip-offset)
1356
1357 (defun company--inside-tooltip-p (event-col-row row height)
1358 (let* ((ovl company-pseudo-tooltip-overlay)
1359 (column (overlay-get ovl 'company-column))
1360 (width (overlay-get ovl 'company-width))
1361 (evt-col (car event-col-row))
1362 (evt-row (cdr event-col-row)))
1363 (and (>= evt-col column)
1364 (< evt-col (+ column width))
1365 (if (> height 0)
1366 (and (> evt-row row)
1367 (<= evt-row (+ row height) ))
1368 (and (< evt-row row)
1369 (>= evt-row (+ row height)))))))
1370
1371 (defun company--event-col-row (event)
1372 (let* ((col-row (posn-actual-col-row (event-start event)))
1373 (col (car col-row))
1374 (row (cdr col-row)))
1375 (incf col (window-hscroll))
1376 (and header-line-format
1377 (version< "24" emacs-version)
1378 (decf row))
1379 (cons col row)))
1380
1381 (defun company-select-mouse (event)
1382 "Select the candidate picked by the mouse."
1383 (interactive "e")
1384 (let ((event-col-row (company--event-col-row event))
1385 (ovl-row (company--row))
1386 (ovl-height (and company-pseudo-tooltip-overlay
1387 (min (overlay-get company-pseudo-tooltip-overlay
1388 'company-height)
1389 company-candidates-length))))
1390 (if (and ovl-height
1391 (company--inside-tooltip-p event-col-row ovl-row ovl-height))
1392 (progn
1393 (company-set-selection (+ (cdr event-col-row)
1394 (if (zerop company-tooltip-offset)
1395 -1
1396 (- company-tooltip-offset 2))
1397 (- ovl-row)
1398 (if (< ovl-height 0)
1399 (- 1 ovl-height)
1400 0)))
1401 t)
1402 (company-abort)
1403 (company--unread-last-input)
1404 nil)))
1405
1406 (defun company-complete-mouse (event)
1407 "Complete the candidate picked by the mouse."
1408 (interactive "e")
1409 (when (company-select-mouse event)
1410 (company-complete-selection)))
1411
1412 (defun company-complete-selection ()
1413 "Complete the selected candidate."
1414 (interactive)
1415 (when (company-manual-begin)
1416 (let ((result (nth company-selection company-candidates)))
1417 (when company--auto-completion
1418 (setq result (company--safe-candidate result)))
1419 (company-finish result))))
1420
1421 (defun company-complete-common ()
1422 "Complete the common part of all candidates."
1423 (interactive)
1424 (when (company-manual-begin)
1425 (if (and (not (cdr company-candidates))
1426 (equal company-common (car company-candidates)))
1427 (company-complete-selection)
1428 (insert (company-strip-prefix company-common)))))
1429
1430 (defun company-complete ()
1431 "Complete the common part of all candidates or the current selection.
1432 The first time this is called, the common part is completed, the second
1433 time, or when the selection has been changed, the selected candidate is
1434 completed."
1435 (interactive)
1436 (when (company-manual-begin)
1437 (if (or company-selection-changed
1438 (eq last-command 'company-complete-common))
1439 (call-interactively 'company-complete-selection)
1440 (call-interactively 'company-complete-common)
1441 (setq this-command 'company-complete-common))))
1442
1443 (defun company-complete-number (n)
1444 "Complete the Nth candidate.
1445 To show the number next to the candidates in some back-ends, enable
1446 `company-show-numbers'."
1447 (when (company-manual-begin)
1448 (and (< n 1) (> n company-candidates-length)
1449 (error "No candidate number %d" n))
1450 (decf n)
1451 (company-finish (nth n company-candidates))))
1452
1453 ;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;
1454
1455 (defconst company-space-strings-limit 100)
1456
1457 (defconst company-space-strings
1458 (let (lst)
1459 (dotimes (i company-space-strings-limit)
1460 (push (make-string (- company-space-strings-limit 1 i) ?\ ) lst))
1461 (apply 'vector lst)))
1462
1463 (defun company-space-string (len)
1464 (if (< len company-space-strings-limit)
1465 (aref company-space-strings len)
1466 (make-string len ?\ )))
1467
1468 (defun company-safe-substring (str from &optional to)
1469 (if (> from (string-width str))
1470 ""
1471 (with-temp-buffer
1472 (insert str)
1473 (move-to-column from)
1474 (let ((beg (point)))
1475 (if to
1476 (progn
1477 (move-to-column to)
1478 (concat (buffer-substring beg (point))
1479 (let ((padding (- to (current-column))))
1480 (when (> padding 0)
1481 (company-space-string padding)))))
1482 (buffer-substring beg (point-max)))))))
1483
1484 ;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;
1485
1486 (defvar company-last-metadata nil)
1487 (make-variable-buffer-local 'company-last-metadata)
1488
1489 (defun company-fetch-metadata ()
1490 (let ((selected (nth company-selection company-candidates)))
1491 (unless (equal selected (car company-last-metadata))
1492 (setq company-last-metadata
1493 (cons selected (company-call-backend 'meta selected))))
1494 (cdr company-last-metadata)))
1495
1496 (defun company-doc-buffer (&optional string)
1497 (with-current-buffer (get-buffer-create "*company-documentation*")
1498 (erase-buffer)
1499 (when string
1500 (save-excursion
1501 (insert string)))
1502 (current-buffer)))
1503
1504 (defvar company--electric-commands
1505 '(scroll-other-window scroll-other-window-down)
1506 "List of Commands that won't break out of electric commands.")
1507
1508 (defmacro company--electric-do (&rest body)
1509 (declare (indent 0) (debug t))
1510 `(when (company-manual-begin)
1511 (save-window-excursion
1512 (let ((height (window-height))
1513 (row (company--row))
1514 cmd)
1515 ,@body
1516 (and (< (window-height) height)
1517 (< (- (window-height) row 2) company-tooltip-limit)
1518 (recenter (- (window-height) row 2)))
1519 (while (memq (setq cmd (key-binding (vector (list (read-event)))))
1520 company--electric-commands)
1521 (call-interactively cmd))
1522 (company--unread-last-input)))))
1523
1524 (defun company--unread-last-input ()
1525 (when last-input-event
1526 (clear-this-command-keys t)
1527 (setq unread-command-events (list last-input-event))))
1528
1529 (defun company-show-doc-buffer ()
1530 "Temporarily show the documentation buffer for the selection."
1531 (interactive)
1532 (company--electric-do
1533 (let* ((selected (nth company-selection company-candidates))
1534 (doc-buffer (or (company-call-backend 'doc-buffer selected)
1535 (error "No documentation available"))))
1536 (with-current-buffer doc-buffer
1537 (goto-char (point-min)))
1538 (display-buffer doc-buffer t))))
1539 (put 'company-show-doc-buffer 'company-keep t)
1540
1541 (defun company-show-location ()
1542 "Temporarily display a buffer showing the selected candidate in context."
1543 (interactive)
1544 (company--electric-do
1545 (let* ((selected (nth company-selection company-candidates))
1546 (location (company-call-backend 'location selected))
1547 (pos (or (cdr location) (error "No location available")))
1548 (buffer (or (and (bufferp (car location)) (car location))
1549 (find-file-noselect (car location) t))))
1550 (with-selected-window (display-buffer buffer t)
1551 (save-restriction
1552 (widen)
1553 (if (bufferp (car location))
1554 (goto-char pos)
1555 (goto-char (point-min))
1556 (forward-line (1- pos))))
1557 (set-window-start nil (point))))))
1558 (put 'company-show-location 'company-keep t)
1559
1560 ;;; package functions ;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;
1561
1562 (defvar company-callback nil)
1563 (make-variable-buffer-local 'company-callback)
1564
1565 (defvar company-begin-with-marker nil)
1566 (make-variable-buffer-local 'company-begin-with-marker)
1567
1568 (defun company-remove-callback (&optional ignored)
1569 (remove-hook 'company-completion-finished-hook company-callback t)
1570 (remove-hook 'company-completion-cancelled-hook 'company-remove-callback t)
1571 (remove-hook 'company-completion-finished-hook 'company-remove-callback t)
1572 (when company-begin-with-marker
1573 (set-marker company-begin-with-marker nil)))
1574
1575 (defun company-begin-backend (backend &optional callback)
1576 "Start a completion at point using BACKEND."
1577 (interactive (let ((val (completing-read "Company back-end: "
1578 obarray
1579 'functionp nil "company-")))
1580 (when val
1581 (list (intern val)))))
1582 (when (setq company-callback callback)
1583 (add-hook 'company-completion-finished-hook company-callback nil t))
1584 (add-hook 'company-completion-cancelled-hook 'company-remove-callback nil t)
1585 (add-hook 'company-completion-finished-hook 'company-remove-callback nil t)
1586 (setq company-backend backend)
1587 ;; Return non-nil if active.
1588 (or (company-manual-begin)
1589 (progn
1590 (setq company-backend nil)
1591 (error "Cannot complete at point"))))
1592
1593 (defun company-begin-with (candidates
1594 &optional prefix-length require-match callback)
1595 "Start a completion at point.
1596 CANDIDATES is the list of candidates to use and PREFIX-LENGTH is the length
1597 of the prefix that already is in the buffer before point.
1598 It defaults to 0.
1599
1600 CALLBACK is a function called with the selected result if the user
1601 successfully completes the input.
1602
1603 Example: \(company-begin-with '\(\"foo\" \"foobar\" \"foobarbaz\"\)\)"
1604 ;; FIXME: When Emacs 23 is no longer a concern, replace
1605 ;; `company-begin-with-marker' with a lexical variable; use a lexical closure.
1606 (setq company-begin-with-marker (copy-marker (point) t))
1607 (company-begin-backend
1608 `(lambda (command &optional arg &rest ignored)
1609 (cond
1610 ((eq command 'prefix)
1611 (when (equal (point) (marker-position company-begin-with-marker))
1612 (buffer-substring ,(- (point) (or prefix-length 0)) (point))))
1613 ((eq command 'candidates)
1614 (all-completions arg ',candidates))
1615 ((eq command 'require-match)
1616 ,require-match)))
1617 callback))
1618
1619 ;;; pseudo-tooltip ;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;
1620
1621 (defvar company-pseudo-tooltip-overlay nil)
1622 (make-variable-buffer-local 'company-pseudo-tooltip-overlay)
1623
1624 (defvar company-tooltip-offset 0)
1625 (make-variable-buffer-local 'company-tooltip-offset)
1626
1627 (defun company-pseudo-tooltip-update-offset (selection num-lines limit)
1628
1629 (decf limit 2)
1630 (setq company-tooltip-offset
1631 (max (min selection company-tooltip-offset)
1632 (- selection -1 limit)))
1633
1634 (when (<= company-tooltip-offset 1)
1635 (incf limit)
1636 (setq company-tooltip-offset 0))
1637
1638 (when (>= company-tooltip-offset (- num-lines limit 1))
1639 (incf limit)
1640 (when (= selection (1- num-lines))
1641 (decf company-tooltip-offset)
1642 (when (<= company-tooltip-offset 1)
1643 (setq company-tooltip-offset 0)
1644 (incf limit))))
1645
1646 limit)
1647
1648 ;;; propertize
1649
1650 (defsubst company-round-tab (arg)
1651 (* (/ (+ arg tab-width) tab-width) tab-width))
1652
1653 (defun company-plainify (str)
1654 (let ((prefix (get-text-property 0 'line-prefix str)))
1655 (when prefix ; Keep the original value unmodified, for no special reason.
1656 (setq str (concat prefix str))
1657 (remove-text-properties 0 (length str) '(line-prefix) str)))
1658 (let* ((pieces (split-string str "\t"))
1659 (copy pieces))
1660 (while (cdr copy)
1661 (setcar copy (company-safe-substring
1662 (car copy) 0 (company-round-tab (string-width (car copy)))))
1663 (pop copy))
1664 (apply 'concat pieces)))
1665
1666 (defun company-fill-propertize (line width selected)
1667 (setq line (company-safe-substring line 0 width))
1668 (add-text-properties 0 width '(face company-tooltip
1669 mouse-face company-tooltip-mouse)
1670 line)
1671 (add-text-properties 0 (length company-common)
1672 '(face company-tooltip-common
1673 mouse-face company-tooltip-mouse)
1674 line)
1675 (when selected
1676 (if (and company-search-string
1677 (string-match (regexp-quote company-search-string) line
1678 (length company-prefix)))
1679 (progn
1680 (add-text-properties (match-beginning 0) (match-end 0)
1681 '(face company-tooltip-selection)
1682 line)
1683 (when (< (match-beginning 0) (length company-common))
1684 (add-text-properties (match-beginning 0) (length company-common)
1685 '(face company-tooltip-common-selection)
1686 line)))
1687 (add-text-properties 0 width '(face company-tooltip-selection
1688 mouse-face company-tooltip-selection)
1689 line)
1690 (add-text-properties 0 (length company-common)
1691 '(face company-tooltip-common-selection
1692 mouse-face company-tooltip-selection)
1693 line)))
1694 line)
1695
1696 ;;; replace
1697
1698 (defun company-buffer-lines (beg end)
1699 (goto-char beg)
1700 (let (lines)
1701 (while (and (= 1 (vertical-motion 1))
1702 (<= (point) end))
1703 (let ((bound (min end (1- (point)))))
1704 ;; A visual line can contain several physical lines (e.g. with outline's
1705 ;; folding overlay). Take only the first one.
1706 (push (buffer-substring beg
1707 (save-excursion
1708 (goto-char beg)
1709 (re-search-forward "$" bound 'move)
1710 (point)))
1711 lines))
1712 (setq beg (point)))
1713 (unless (eq beg end)
1714 (push (buffer-substring beg end) lines))
1715 (nreverse lines)))
1716
1717 (defun company-modify-line (old new offset)
1718 (concat (company-safe-substring old 0 offset)
1719 new
1720 (company-safe-substring old (+ offset (length new)))))
1721
1722 (defsubst company--length-limit (lst limit)
1723 (if (nthcdr limit lst)
1724 limit
1725 (length lst)))
1726
1727 (defun company--replacement-string (lines old column nl &optional align-top)
1728
1729 (let ((width (length (car lines)))
1730 (remaining-cols (- (+ (window-width) (window-hscroll))
1731 column)))
1732 (when (> width remaining-cols)
1733 (decf column (- width remaining-cols))))
1734
1735 (let (new)
1736 (when align-top
1737 ;; untouched lines first
1738 (dotimes (_ (- (length old) (length lines)))
1739 (push (pop old) new)))
1740 ;; length into old lines.
1741 (while old
1742 (push (company-modify-line (pop old) (pop lines) column) new))
1743 ;; Append whole new lines.
1744 (while lines
1745 (push (concat (company-space-string column) (pop lines)) new))
1746
1747 (let ((str (concat (when nl "\n")
1748 (mapconcat 'identity (nreverse new) "\n")
1749 "\n")))
1750 (font-lock-append-text-property 0 (length str) 'face 'default str)
1751 str)))
1752
1753 (defun company--create-lines (selection limit)
1754
1755 (let ((len company-candidates-length)
1756 (numbered 99999)
1757 lines
1758 width
1759 lines-copy
1760 previous
1761 remainder
1762 new)
1763
1764 ;; Scroll to offset.
1765 (setq limit (company-pseudo-tooltip-update-offset selection len limit))
1766
1767 (when (> company-tooltip-offset 0)
1768 (setq previous (format "...(%d)" company-tooltip-offset)))
1769
1770 (setq remainder (- len limit company-tooltip-offset)
1771 remainder (when (> remainder 0)
1772 (setq remainder (format "...(%d)" remainder))))
1773
1774 (decf selection company-tooltip-offset)
1775 (setq width (max (length previous) (length remainder))
1776 lines (nthcdr company-tooltip-offset company-candidates)
1777 len (min limit len)
1778 lines-copy lines)
1779
1780 (dotimes (_ len)
1781 (setq width (max (length (pop lines-copy)) width)))
1782 (setq width (min (window-width)
1783 (if company-show-numbers
1784 (+ 2 width)
1785 width)))
1786 (setq lines-copy lines)
1787
1788 ;; number can make tooltip too long
1789 (when company-show-numbers
1790 (setq numbered company-tooltip-offset))
1791
1792 (when previous
1793 (push (propertize (company-safe-substring previous 0 width)
1794 'face 'company-tooltip)
1795 new))
1796
1797 (dotimes (i len)
1798 (push (company-fill-propertize
1799 (if (>= numbered 10)
1800 (company-reformat (pop lines))
1801 (incf numbered)
1802 (format "%s %d"
1803 (company-safe-substring (company-reformat (pop lines))
1804 0 (- width 2))
1805 (mod numbered 10)))
1806 width (equal i selection))
1807 new))
1808
1809 (when remainder
1810 (push (propertize (company-safe-substring remainder 0 width)
1811 'face 'company-tooltip)
1812 new))
1813
1814 (setq lines (nreverse new))))
1815
1816 ;; show
1817
1818 (defsubst company--window-inner-height ()
1819 (let ((edges (window-inside-edges)))
1820 (- (nth 3 edges) (nth 1 edges))))
1821
1822 (defun company--pseudo-tooltip-height ()
1823 "Calculate the appropriate tooltip height.
1824 Returns a negative number if the tooltip should be displayed above point."
1825 (let* ((lines (company--row))
1826 (below (- (company--window-inner-height) 1 lines)))
1827 (if (and (< below (min company-tooltip-minimum company-candidates-length))
1828 (> lines below))
1829 (- (max 3 (min company-tooltip-limit lines)))
1830 (max 3 (min company-tooltip-limit below)))))
1831
1832 (defun company-pseudo-tooltip-show (row column selection)
1833 (company-pseudo-tooltip-hide)
1834 (save-excursion
1835
1836 (let* ((height (company--pseudo-tooltip-height))
1837 above)
1838
1839 (when (< height 0)
1840 (setq row (+ row height -1)
1841 above t))
1842
1843 (let* ((nl (< (move-to-window-line row) row))
1844 (beg (point))
1845 (end (save-excursion
1846 (move-to-window-line (+ row (abs height)))
1847 (point)))
1848 (ov (make-overlay beg end))
1849 (args (list (mapcar 'company-plainify
1850 (company-buffer-lines beg end))
1851 column nl above)))
1852
1853 (setq company-pseudo-tooltip-overlay ov)
1854 (overlay-put ov 'company-replacement-args args)
1855
1856 (let ((lines (company--create-lines selection (abs height))))
1857 (overlay-put ov 'company-after
1858 (apply 'company--replacement-string lines args))
1859 (overlay-put ov 'company-width (string-width (car lines))))
1860
1861 (overlay-put ov 'company-column column)
1862 (overlay-put ov 'company-height height)))))
1863
1864 (defun company-pseudo-tooltip-show-at-point (pos)
1865 (let ((row (company--row pos))
1866 (col (company--column pos)))
1867 (company-pseudo-tooltip-show (1+ row) col company-selection)))
1868
1869 (defun company-pseudo-tooltip-edit (selection)
1870 (let ((height (overlay-get company-pseudo-tooltip-overlay 'company-height)))
1871 (overlay-put company-pseudo-tooltip-overlay 'company-after
1872 (apply 'company--replacement-string
1873 (company--create-lines selection (abs height))
1874 (overlay-get company-pseudo-tooltip-overlay
1875 'company-replacement-args)))))
1876
1877 (defun company-pseudo-tooltip-hide ()
1878 (when company-pseudo-tooltip-overlay
1879 (delete-overlay company-pseudo-tooltip-overlay)
1880 (setq company-pseudo-tooltip-overlay nil)))
1881
1882 (defun company-pseudo-tooltip-hide-temporarily ()
1883 (when (overlayp company-pseudo-tooltip-overlay)
1884 (overlay-put company-pseudo-tooltip-overlay 'invisible nil)
1885 (overlay-put company-pseudo-tooltip-overlay 'line-prefix nil)
1886 (overlay-put company-pseudo-tooltip-overlay 'after-string nil)))
1887
1888 (defun company-pseudo-tooltip-unhide ()
1889 (when company-pseudo-tooltip-overlay
1890 (overlay-put company-pseudo-tooltip-overlay 'invisible t)
1891 ;; Beat outline's folding overlays, at least.
1892 (overlay-put company-pseudo-tooltip-overlay 'priority 1)
1893 ;; No (extra) prefix for the first line.
1894 (overlay-put company-pseudo-tooltip-overlay 'line-prefix "")
1895 (overlay-put company-pseudo-tooltip-overlay 'after-string
1896 (overlay-get company-pseudo-tooltip-overlay 'company-after))
1897 (overlay-put company-pseudo-tooltip-overlay 'window (selected-window))))
1898
1899 (defun company-pseudo-tooltip-guard ()
1900 (buffer-substring-no-properties
1901 (point) (overlay-start company-pseudo-tooltip-overlay)))
1902
1903 (defun company-pseudo-tooltip-frontend (command)
1904 "`company-mode' front-end similar to a tooltip but based on overlays."
1905 (case command
1906 (pre-command (company-pseudo-tooltip-hide-temporarily))
1907 (post-command
1908 (let ((old-height (if (overlayp company-pseudo-tooltip-overlay)
1909 (overlay-get company-pseudo-tooltip-overlay
1910 'company-height)
1911 0))
1912 (new-height (company--pseudo-tooltip-height)))
1913 (unless (and (>= (* old-height new-height) 0)
1914 (>= (abs old-height) (abs new-height))
1915 (equal (company-pseudo-tooltip-guard)
1916 (overlay-get company-pseudo-tooltip-overlay
1917 'company-guard)))
1918 ;; Redraw needed.
1919 (company-pseudo-tooltip-show-at-point (- (point)
1920 (length company-prefix)))
1921 (overlay-put company-pseudo-tooltip-overlay
1922 'company-guard (company-pseudo-tooltip-guard))))
1923 (company-pseudo-tooltip-unhide))
1924 (hide (company-pseudo-tooltip-hide)
1925 (setq company-tooltip-offset 0))
1926 (update (when (overlayp company-pseudo-tooltip-overlay)
1927 (company-pseudo-tooltip-edit company-selection)))))
1928
1929 (defun company-pseudo-tooltip-unless-just-one-frontend (command)
1930 "`company-pseudo-tooltip-frontend', but not shown for single candidates."
1931 (unless (and (eq command 'post-command)
1932 (not (cdr company-candidates)))
1933 (company-pseudo-tooltip-frontend command)))
1934
1935 ;;; overlay ;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;
1936
1937 (defvar company-preview-overlay nil)
1938 (make-variable-buffer-local 'company-preview-overlay)
1939
1940 (defun company-preview-show-at-point (pos)
1941 (company-preview-hide)
1942
1943 (setq company-preview-overlay (make-overlay pos pos))
1944
1945 (let ((completion(nth company-selection company-candidates)))
1946 (setq completion (propertize completion 'face 'company-preview))
1947 (add-text-properties 0 (length company-common)
1948 '(face company-preview-common) completion)
1949
1950 ;; Add search string
1951 (and company-search-string
1952 (string-match (regexp-quote company-search-string) completion)
1953 (add-text-properties (match-beginning 0)
1954 (match-end 0)
1955 '(face company-preview-search)
1956 completion))
1957
1958 (setq completion (company-strip-prefix completion))
1959
1960 (and (equal pos (point))
1961 (not (equal completion ""))
1962 (add-text-properties 0 1 '(cursor t) completion))
1963
1964 (overlay-put company-preview-overlay 'after-string completion)
1965 (overlay-put company-preview-overlay 'window (selected-window))))
1966
1967 (defun company-preview-hide ()
1968 (when company-preview-overlay
1969 (delete-overlay company-preview-overlay)
1970 (setq company-preview-overlay nil)))
1971
1972 (defun company-preview-frontend (command)
1973 "`company-mode' front-end showing the selection as if it had been inserted."
1974 (case command
1975 (pre-command (company-preview-hide))
1976 (post-command (company-preview-show-at-point (point)))
1977 (hide (company-preview-hide))))
1978
1979 (defun company-preview-if-just-one-frontend (command)
1980 "`company-preview-frontend', but only shown for single candidates."
1981 (unless (and (eq command 'post-command)
1982 (cdr company-candidates))
1983 (company-preview-frontend command)))
1984
1985 ;;; echo ;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;
1986
1987 (defvar company-echo-last-msg nil)
1988 (make-variable-buffer-local 'company-echo-last-msg)
1989
1990 (defvar company-echo-timer nil)
1991
1992 (defvar company-echo-delay .01)
1993
1994 (defun company-echo-show (&optional getter)
1995 (when getter
1996 (setq company-echo-last-msg (funcall getter)))
1997 (let ((message-log-max nil))
1998 (if company-echo-last-msg
1999 (message "%s" company-echo-last-msg)
2000 (message ""))))
2001
2002 (defun company-echo-show-soon (&optional getter)
2003 (when company-echo-timer
2004 (cancel-timer company-echo-timer))
2005 (setq company-echo-timer (run-with-timer 0 nil 'company-echo-show getter)))
2006
2007 (defsubst company-echo-show-when-idle (&optional getter)
2008 (when (sit-for company-echo-delay)
2009 (company-echo-show getter)))
2010
2011 (defun company-echo-format ()
2012
2013 (let ((limit (window-width (minibuffer-window)))
2014 (len -1)
2015 ;; Roll to selection.
2016 (candidates (nthcdr company-selection company-candidates))
2017 (i (if company-show-numbers company-selection 99999))
2018 comp msg)
2019
2020 (while candidates
2021 (setq comp (company-reformat (pop candidates))
2022 len (+ len 1 (length comp)))
2023 (if (< i 10)
2024 ;; Add number.
2025 (progn
2026 (setq comp (propertize (format "%d: %s" i comp)
2027 'face 'company-echo))
2028 (incf len 3)
2029 (incf i)
2030 (add-text-properties 3 (+ 3 (length company-common))
2031 '(face company-echo-common) comp))
2032 (setq comp (propertize comp 'face 'company-echo))
2033 (add-text-properties 0 (length company-common)
2034 '(face company-echo-common) comp))
2035 (if (>= len limit)
2036 (setq candidates nil)
2037 (push comp msg)))
2038
2039 (mapconcat 'identity (nreverse msg) " ")))
2040
2041 (defun company-echo-strip-common-format ()
2042
2043 (let ((limit (window-width (minibuffer-window)))
2044 (len (+ (length company-prefix) 2))
2045 ;; Roll to selection.
2046 (candidates (nthcdr company-selection company-candidates))
2047 (i (if company-show-numbers company-selection 99999))
2048 msg comp)
2049
2050 (while candidates
2051 (setq comp (company-strip-prefix (pop candidates))
2052 len (+ len 2 (length comp)))
2053 (when (< i 10)
2054 ;; Add number.
2055 (setq comp (format "%s (%d)" comp i))
2056 (incf len 4)
2057 (incf i))
2058 (if (>= len limit)
2059 (setq candidates nil)
2060 (push (propertize comp 'face 'company-echo) msg)))
2061
2062 (concat (propertize company-prefix 'face 'company-echo-common) "{"
2063 (mapconcat 'identity (nreverse msg) ", ")
2064 "}")))
2065
2066 (defun company-echo-hide ()
2067 (unless (equal company-echo-last-msg "")
2068 (setq company-echo-last-msg "")
2069 (company-echo-show)))
2070
2071 (defun company-echo-frontend (command)
2072 "`company-mode' front-end showing the candidates in the echo area."
2073 (case command
2074 (post-command (company-echo-show-soon 'company-echo-format))
2075 (hide (company-echo-hide))))
2076
2077 (defun company-echo-strip-common-frontend (command)
2078 "`company-mode' front-end showing the candidates in the echo area."
2079 (case command
2080 (post-command (company-echo-show-soon 'company-echo-strip-common-format))
2081 (hide (company-echo-hide))))
2082
2083 (defun company-echo-metadata-frontend (command)
2084 "`company-mode' front-end showing the documentation in the echo area."
2085 (case command
2086 (post-command (company-echo-show-when-idle 'company-fetch-metadata))
2087 (hide (company-echo-hide))))
2088
2089 (provide 'company)
2090 ;;; company.el ends here