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