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