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