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