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