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