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