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