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