]> code.delx.au - gnu-emacs-elpa/blob - company.el
Release 0.6.13
[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 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 (setq company-common
837 (if (cdr company-candidates)
838 (company--safe-candidate
839 (try-completion company-prefix company-candidates))
840 (car company-candidates)))))
841
842 (defun company--safe-candidate (str)
843 (or (company-call-backend 'crop str)
844 str))
845
846 (defun company-calculate-candidates (prefix)
847 (let ((candidates (cdr (assoc prefix company-candidates-cache)))
848 (ignore-case (company-call-backend 'ignore-case)))
849 (or candidates
850 (when company-candidates-cache
851 (let ((len (length prefix))
852 (completion-ignore-case ignore-case)
853 prev)
854 (dotimes (i (1+ len))
855 (when (setq prev (cdr (assoc (substring prefix 0 (- len i))
856 company-candidates-cache)))
857 (setq candidates (all-completions prefix prev))
858 (return t)))))
859 ;; no cache match, call back-end
860 (progn
861 (setq candidates (company-call-backend 'candidates prefix))
862 (when company-candidates-predicate
863 (setq candidates
864 (company-apply-predicate candidates
865 company-candidates-predicate)))
866 (unless (company-call-backend 'sorted)
867 (setq candidates (sort candidates 'string<)))
868 (when (company-call-backend 'duplicates)
869 ;; strip duplicates
870 (let ((c2 candidates))
871 (while c2
872 (setcdr c2 (progn (while (equal (pop c2) (car c2)))
873 c2)))))))
874 (when candidates
875 (if (or (cdr candidates)
876 (not (eq t (compare-strings (car candidates) nil nil
877 prefix nil nil ignore-case))))
878 candidates
879 ;; Already completed and unique; don't start.
880 t))))
881
882 (defun company-idle-begin (buf win tick pos)
883 (and company-mode
884 (eq buf (current-buffer))
885 (eq win (selected-window))
886 (eq tick (buffer-chars-modified-tick))
887 (eq pos (point))
888 (not company-candidates)
889 (not (equal (point) company-point))
890 (let ((company-idle-delay t)
891 (company-begin-commands t))
892 (company-begin)
893 (when company-candidates
894 (company-input-noop)
895 (company-post-command)))))
896
897 (defun company-auto-begin ()
898 (company-assert-enabled)
899 (and company-mode
900 (not company-candidates)
901 (let ((company-idle-delay t)
902 (company-minimum-prefix-length 0)
903 (company-begin-commands t))
904 (company-begin)))
905 ;; Return non-nil if active.
906 company-candidates)
907
908 (defun company-manual-begin ()
909 (interactive)
910 (setq company--explicit-action t)
911 (unwind-protect
912 (company-auto-begin)
913 (unless company-candidates
914 (setq company--explicit-action nil))))
915
916 (defun company-other-backend (&optional backward)
917 (interactive (list current-prefix-arg))
918 (company-assert-enabled)
919 (if company-backend
920 (let* ((after (cdr (member company-backend company-backends)))
921 (before (cdr (member company-backend (reverse company-backends))))
922 (next (if backward
923 (append before (reverse after))
924 (append after (reverse before)))))
925 (company-cancel)
926 (dolist (backend next)
927 (when (ignore-errors (company-begin-backend backend))
928 (return t))))
929 (company-manual-begin))
930 (unless company-candidates
931 (error "No other back-end")))
932
933 (defun company-require-match-p ()
934 (let ((backend-value (company-call-backend 'require-match)))
935 (or (eq backend-value t)
936 (and (not (eq backend-value 'never))
937 (if (functionp company-require-match)
938 (funcall company-require-match)
939 (eq company-require-match t))))))
940
941 (defun company-auto-complete-p (input)
942 "Return non-nil, if input starts with punctuation or parentheses."
943 (and (if (functionp company-auto-complete)
944 (funcall company-auto-complete)
945 company-auto-complete)
946 (if (functionp company-auto-complete-chars)
947 (funcall company-auto-complete-chars input)
948 (if (consp company-auto-complete-chars)
949 (memq (char-syntax (string-to-char input))
950 company-auto-complete-chars)
951 (string-match (substring input 0 1) company-auto-complete-chars)))))
952
953 (defun company--incremental-p ()
954 (and (> (point) company-point)
955 (> (point-max) company--point-max)
956 (not (eq this-command 'backward-delete-char-untabify))
957 (equal (buffer-substring (- company-point (length company-prefix))
958 company-point)
959 company-prefix)))
960
961 (defsubst company--string-incremental-p (old-prefix new-prefix)
962 (and (> (length new-prefix) (length old-prefix))
963 (equal old-prefix (substring new-prefix 0 (length old-prefix)))))
964
965 (defun company--continue-failed (new-prefix)
966 (when (company--incremental-p)
967 (let ((input (buffer-substring-no-properties (point) company-point)))
968 (cond
969 ((company-auto-complete-p input)
970 ;; auto-complete
971 (save-excursion
972 (goto-char company-point)
973 (let ((company--auto-completion t))
974 (company-complete-selection))
975 nil))
976 ((and (company--string-incremental-p company-prefix new-prefix)
977 (company-require-match-p))
978 ;; wrong incremental input, but required match
979 (delete-char (- (length input)))
980 (ding)
981 (message "Matching input is required")
982 company-candidates)
983 ((equal company-prefix (car company-candidates))
984 ;; last input was actually success
985 (company-cancel company-prefix)
986 nil)))))
987
988 (defun company--good-prefix-p (prefix)
989 (and (or (company-explicit-action-p)
990 (unless (eq prefix 'stop)
991 (or (eq (cdr-safe prefix) t)
992 (>= (or (cdr-safe prefix) (length prefix))
993 company-minimum-prefix-length))))
994 (stringp (or (car-safe prefix) prefix))))
995
996 (defun company--continue ()
997 (when (company-call-backend 'no-cache company-prefix)
998 ;; Don't complete existing candidates, fetch new ones.
999 (setq company-candidates-cache nil))
1000 (let* ((new-prefix (company-call-backend 'prefix))
1001 (c (when (and (company--good-prefix-p new-prefix)
1002 (setq new-prefix (or (car-safe new-prefix) new-prefix))
1003 (= (- (point) (length new-prefix))
1004 (- company-point (length company-prefix))))
1005 (setq new-prefix (or (car-safe new-prefix) new-prefix))
1006 (company-calculate-candidates new-prefix))))
1007 (or (cond
1008 ((eq c t)
1009 ;; t means complete/unique.
1010 (company-cancel new-prefix)
1011 nil)
1012 ((consp c)
1013 ;; incremental match
1014 (setq company-prefix new-prefix)
1015 (company-update-candidates c)
1016 c)
1017 (t (company--continue-failed new-prefix)))
1018 (company-cancel))))
1019
1020 (defun company--begin-new ()
1021 (let (prefix c)
1022 (dolist (backend (if company-backend
1023 ;; prefer manual override
1024 (list company-backend)
1025 company-backends))
1026 (setq prefix
1027 (if (or (symbolp backend)
1028 (functionp backend))
1029 (when (or (not (symbolp backend))
1030 (eq t (get backend 'company-init))
1031 (unless (get backend 'company-init)
1032 (company-init-backend backend)))
1033 (funcall backend 'prefix))
1034 (company--multi-backend-adapter backend 'prefix)))
1035 (when prefix
1036 (when (company--good-prefix-p prefix)
1037 (setq prefix (or (car-safe prefix) prefix)
1038 company-backend backend
1039 c (company-calculate-candidates prefix))
1040 ;; t means complete/unique. We don't start, so no hooks.
1041 (if (not (consp c))
1042 (when company--explicit-action
1043 (message "No completion found"))
1044 (setq company-prefix prefix)
1045 (when (symbolp backend)
1046 (setq company-lighter (concat " " (symbol-name backend))))
1047 (company-update-candidates c)
1048 (run-hook-with-args 'company-completion-started-hook
1049 (company-explicit-action-p))
1050 (company-call-frontends 'show)))
1051 (return c)))))
1052
1053 (defun company-begin ()
1054 (or (and company-candidates (company--continue))
1055 (and (company--should-complete) (company--begin-new)))
1056 (when company-candidates
1057 (when (and company-end-of-buffer-workaround (eobp))
1058 (save-excursion (insert "\n"))
1059 (setq company-added-newline (buffer-chars-modified-tick)))
1060 (setq company-point (point)
1061 company--point-max (point-max))
1062 (company-ensure-emulation-alist)
1063 (company-enable-overriding-keymap company-active-map)
1064 (company-call-frontends 'update)))
1065
1066 (defun company-cancel (&optional result)
1067 (and company-added-newline
1068 (> (point-max) (point-min))
1069 (let ((tick (buffer-chars-modified-tick)))
1070 (delete-region (1- (point-max)) (point-max))
1071 (equal tick company-added-newline))
1072 ;; Only set unmodified when tick remained the same since insert.
1073 (set-buffer-modified-p nil))
1074 (when company-prefix
1075 (if (stringp result)
1076 (progn
1077 (company-call-backend 'pre-completion result)
1078 (run-hook-with-args 'company-completion-finished-hook result)
1079 (company-call-backend 'post-completion result))
1080 (run-hook-with-args 'company-completion-cancelled-hook result)))
1081 (setq company-added-newline nil
1082 company-backend nil
1083 company-prefix nil
1084 company-candidates nil
1085 company-candidates-length nil
1086 company-candidates-cache nil
1087 company-candidates-predicate nil
1088 company-common nil
1089 company-selection 0
1090 company-selection-changed nil
1091 company--explicit-action nil
1092 company-lighter company-default-lighter
1093 company--point-max nil
1094 company-point nil)
1095 (when company-timer
1096 (cancel-timer company-timer))
1097 (company-search-mode 0)
1098 (company-call-frontends 'hide)
1099 (company-enable-overriding-keymap nil))
1100
1101 (defun company-abort ()
1102 (interactive)
1103 (company-cancel t)
1104 ;; Don't start again, unless started manually.
1105 (setq company-point (point)))
1106
1107 (defun company-finish (result)
1108 (company--insert-candidate result)
1109 (company-cancel result)
1110 ;; Don't start again, unless started manually.
1111 (setq company-point (point)))
1112
1113 (defsubst company-keep (command)
1114 (and (symbolp command) (get command 'company-keep)))
1115
1116 (defun company-pre-command ()
1117 (unless (company-keep this-command)
1118 (condition-case err
1119 (when company-candidates
1120 (company-call-frontends 'pre-command))
1121 (error (message "Company: An error occurred in pre-command")
1122 (message "%s" (error-message-string err))
1123 (company-cancel))))
1124 (when company-timer
1125 (cancel-timer company-timer)
1126 (setq company-timer nil))
1127 (company-uninstall-map))
1128
1129 (defun company-post-command ()
1130 (unless (company-keep this-command)
1131 (condition-case err
1132 (progn
1133 (unless (equal (point) company-point)
1134 (company-begin))
1135 (if company-candidates
1136 (company-call-frontends 'post-command)
1137 (and (numberp company-idle-delay)
1138 (or (eq t company-begin-commands)
1139 (memq this-command company-begin-commands))
1140 (setq company-timer
1141 (run-with-timer company-idle-delay nil
1142 'company-idle-begin
1143 (current-buffer) (selected-window)
1144 (buffer-chars-modified-tick) (point))))))
1145 (error (message "Company: An error occurred in post-command")
1146 (message "%s" (error-message-string err))
1147 (company-cancel))))
1148 (company-install-map))
1149
1150 ;;; search ;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;
1151
1152 (defvar company-search-string nil)
1153 (make-variable-buffer-local 'company-search-string)
1154
1155 (defvar company-search-lighter " Search: \"\"")
1156 (make-variable-buffer-local 'company-search-lighter)
1157
1158 (defvar company-search-old-map nil)
1159 (make-variable-buffer-local 'company-search-old-map)
1160
1161 (defvar company-search-old-selection 0)
1162 (make-variable-buffer-local 'company-search-old-selection)
1163
1164 (defun company-search (text lines)
1165 (let ((quoted (regexp-quote text))
1166 (i 0))
1167 (dolist (line lines)
1168 (when (string-match quoted line (length company-prefix))
1169 (return i))
1170 (incf i))))
1171
1172 (defun company-search-printing-char ()
1173 (interactive)
1174 (company-search-assert-enabled)
1175 (setq company-search-string
1176 (concat (or company-search-string "") (string last-command-event))
1177 company-search-lighter (concat " Search: \"" company-search-string
1178 "\""))
1179 (let ((pos (company-search company-search-string
1180 (nthcdr company-selection company-candidates))))
1181 (if (null pos)
1182 (ding)
1183 (company-set-selection (+ company-selection pos) t))))
1184
1185 (defun company-search-repeat-forward ()
1186 "Repeat the incremental search in completion candidates forward."
1187 (interactive)
1188 (company-search-assert-enabled)
1189 (let ((pos (company-search company-search-string
1190 (cdr (nthcdr company-selection
1191 company-candidates)))))
1192 (if (null pos)
1193 (ding)
1194 (company-set-selection (+ company-selection pos 1) t))))
1195
1196 (defun company-search-repeat-backward ()
1197 "Repeat the incremental search in completion candidates backwards."
1198 (interactive)
1199 (company-search-assert-enabled)
1200 (let ((pos (company-search company-search-string
1201 (nthcdr (- company-candidates-length
1202 company-selection)
1203 (reverse company-candidates)))))
1204 (if (null pos)
1205 (ding)
1206 (company-set-selection (- company-selection pos 1) t))))
1207
1208 (defun company-create-match-predicate ()
1209 (setq company-candidates-predicate
1210 `(lambda (candidate)
1211 ,(if company-candidates-predicate
1212 `(and (string-match ,company-search-string candidate)
1213 (funcall ,company-candidates-predicate
1214 candidate))
1215 `(string-match ,company-search-string candidate))))
1216 (company-update-candidates
1217 (company-apply-predicate company-candidates company-candidates-predicate))
1218 ;; Invalidate cache.
1219 (setq company-candidates-cache (cons company-prefix company-candidates)))
1220
1221 (defun company-filter-printing-char ()
1222 (interactive)
1223 (company-search-assert-enabled)
1224 (company-search-printing-char)
1225 (company-create-match-predicate)
1226 (company-call-frontends 'update))
1227
1228 (defun company-search-kill-others ()
1229 "Limit the completion candidates to the ones matching the search string."
1230 (interactive)
1231 (company-search-assert-enabled)
1232 (company-create-match-predicate)
1233 (company-search-mode 0)
1234 (company-call-frontends 'update))
1235
1236 (defun company-search-abort ()
1237 "Abort searching the completion candidates."
1238 (interactive)
1239 (company-search-assert-enabled)
1240 (company-set-selection company-search-old-selection t)
1241 (company-search-mode 0))
1242
1243 (defun company-search-other-char ()
1244 (interactive)
1245 (company-search-assert-enabled)
1246 (company-search-mode 0)
1247 (company--unread-last-input))
1248
1249 (defvar company-search-map
1250 (let ((i 0)
1251 (keymap (make-keymap)))
1252 (if (fboundp 'max-char)
1253 (set-char-table-range (nth 1 keymap) (cons #x100 (max-char))
1254 'company-search-printing-char)
1255 (with-no-warnings
1256 ;; obsolete in Emacs 23
1257 (let ((l (generic-character-list))
1258 (table (nth 1 keymap)))
1259 (while l
1260 (set-char-table-default table (car l) 'company-search-printing-char)
1261 (setq l (cdr l))))))
1262 (define-key keymap [t] 'company-search-other-char)
1263 (while (< i ?\s)
1264 (define-key keymap (make-string 1 i) 'company-search-other-char)
1265 (incf i))
1266 (while (< i 256)
1267 (define-key keymap (vector i) 'company-search-printing-char)
1268 (incf i))
1269 (let ((meta-map (make-sparse-keymap)))
1270 (define-key keymap (char-to-string meta-prefix-char) meta-map)
1271 (define-key keymap [escape] meta-map))
1272 (define-key keymap (vector meta-prefix-char t) 'company-search-other-char)
1273 (define-key keymap "\e\e\e" 'company-search-other-char)
1274 (define-key keymap [escape escape escape] 'company-search-other-char)
1275
1276 (define-key keymap "\C-g" 'company-search-abort)
1277 (define-key keymap "\C-s" 'company-search-repeat-forward)
1278 (define-key keymap "\C-r" 'company-search-repeat-backward)
1279 (define-key keymap "\C-o" 'company-search-kill-others)
1280 keymap)
1281 "Keymap used for incrementally searching the completion candidates.")
1282
1283 (define-minor-mode company-search-mode
1284 "Search mode for completion candidates.
1285 Don't start this directly, use `company-search-candidates' or
1286 `company-filter-candidates'."
1287 nil company-search-lighter nil
1288 (if company-search-mode
1289 (if (company-manual-begin)
1290 (progn
1291 (setq company-search-old-selection company-selection)
1292 (company-call-frontends 'update))
1293 (setq company-search-mode nil))
1294 (kill-local-variable 'company-search-string)
1295 (kill-local-variable 'company-search-lighter)
1296 (kill-local-variable 'company-search-old-selection)
1297 (company-enable-overriding-keymap company-active-map)))
1298
1299 (defun company-search-assert-enabled ()
1300 (company-assert-enabled)
1301 (unless company-search-mode
1302 (company-uninstall-map)
1303 (error "Company not in search mode")))
1304
1305 (defun company-search-candidates ()
1306 "Start searching the completion candidates incrementally.
1307
1308 \\<company-search-map>Search can be controlled with the commands:
1309 - `company-search-repeat-forward' (\\[company-search-repeat-forward])
1310 - `company-search-repeat-backward' (\\[company-search-repeat-backward])
1311 - `company-search-abort' (\\[company-search-abort])
1312
1313 Regular characters are appended to the search string.
1314
1315 The command `company-search-kill-others' (\\[company-search-kill-others])
1316 uses the search string to limit the completion candidates."
1317 (interactive)
1318 (company-search-mode 1)
1319 (company-enable-overriding-keymap company-search-map))
1320
1321 (defvar company-filter-map
1322 (let ((keymap (make-keymap)))
1323 (define-key keymap [remap company-search-printing-char]
1324 'company-filter-printing-char)
1325 (set-keymap-parent keymap company-search-map)
1326 keymap)
1327 "Keymap used for incrementally searching the completion candidates.")
1328
1329 (defun company-filter-candidates ()
1330 "Start filtering the completion candidates incrementally.
1331 This works the same way as `company-search-candidates' immediately
1332 followed by `company-search-kill-others' after each input."
1333 (interactive)
1334 (company-search-mode 1)
1335 (company-enable-overriding-keymap company-filter-map))
1336
1337 ;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;
1338
1339 (defun company-select-next ()
1340 "Select the next candidate in the list."
1341 (interactive)
1342 (when (company-manual-begin)
1343 (company-set-selection (1+ company-selection))))
1344
1345 (defun company-select-previous ()
1346 "Select the previous candidate in the list."
1347 (interactive)
1348 (when (company-manual-begin)
1349 (company-set-selection (1- company-selection))))
1350
1351 (defun company-select-next-or-abort ()
1352 "Select the next candidate if more than one, else abort
1353 and invoke the normal binding."
1354 (interactive)
1355 (if (> company-candidates-length 1)
1356 (company-select-next)
1357 (company-abort)
1358 (company--unread-last-input)))
1359
1360 (defun company-select-previous-or-abort ()
1361 "Select the previous candidate if more than one, else abort
1362 and invoke the normal binding."
1363 (interactive)
1364 (if (> company-candidates-length 1)
1365 (company-select-previous)
1366 (company-abort)
1367 (company--unread-last-input)))
1368
1369 (defvar company-pseudo-tooltip-overlay)
1370
1371 (defvar company-tooltip-offset)
1372
1373 (defun company--inside-tooltip-p (event-col-row row height)
1374 (let* ((ovl company-pseudo-tooltip-overlay)
1375 (column (overlay-get ovl 'company-column))
1376 (width (overlay-get ovl 'company-width))
1377 (evt-col (car event-col-row))
1378 (evt-row (cdr event-col-row)))
1379 (and (>= evt-col column)
1380 (< evt-col (+ column width))
1381 (if (> height 0)
1382 (and (> evt-row row)
1383 (<= evt-row (+ row height) ))
1384 (and (< evt-row row)
1385 (>= evt-row (+ row height)))))))
1386
1387 (defun company--event-col-row (event)
1388 (let* ((col-row (posn-actual-col-row (event-start event)))
1389 (col (car col-row))
1390 (row (cdr col-row)))
1391 (incf col (window-hscroll))
1392 (and header-line-format
1393 (version< "24" emacs-version)
1394 (decf row))
1395 (cons col row)))
1396
1397 (defun company-select-mouse (event)
1398 "Select the candidate picked by the mouse."
1399 (interactive "e")
1400 (let ((event-col-row (company--event-col-row event))
1401 (ovl-row (company--row))
1402 (ovl-height (and company-pseudo-tooltip-overlay
1403 (min (overlay-get company-pseudo-tooltip-overlay
1404 'company-height)
1405 company-candidates-length))))
1406 (if (and ovl-height
1407 (company--inside-tooltip-p event-col-row ovl-row ovl-height))
1408 (progn
1409 (company-set-selection (+ (cdr event-col-row)
1410 (if (zerop company-tooltip-offset)
1411 -1
1412 (- company-tooltip-offset 2))
1413 (- ovl-row)
1414 (if (< ovl-height 0)
1415 (- 1 ovl-height)
1416 0)))
1417 t)
1418 (company-abort)
1419 (company--unread-last-input)
1420 nil)))
1421
1422 (defun company-complete-mouse (event)
1423 "Complete the candidate picked by the mouse."
1424 (interactive "e")
1425 (when (company-select-mouse event)
1426 (company-complete-selection)))
1427
1428 (defun company-complete-selection ()
1429 "Complete the selected candidate."
1430 (interactive)
1431 (when (company-manual-begin)
1432 (let ((result (nth company-selection company-candidates)))
1433 (when company--auto-completion
1434 (setq result (company--safe-candidate result)))
1435 (company-finish result))))
1436
1437 (defun company-complete-common ()
1438 "Complete the common part of all candidates."
1439 (interactive)
1440 (when (company-manual-begin)
1441 (if (and (not (cdr company-candidates))
1442 (equal company-common (car company-candidates)))
1443 (company-complete-selection)
1444 (when company-common
1445 (company--insert-candidate company-common)))))
1446
1447 (defun company-complete ()
1448 "Complete the common part of all candidates or the current selection.
1449 The first time this is called, the common part is completed, the second
1450 time, or when the selection has been changed, the selected candidate is
1451 completed."
1452 (interactive)
1453 (when (company-manual-begin)
1454 (if (or company-selection-changed
1455 (eq last-command 'company-complete-common))
1456 (call-interactively 'company-complete-selection)
1457 (call-interactively 'company-complete-common)
1458 (setq this-command 'company-complete-common))))
1459
1460 (defun company-complete-number (n)
1461 "Complete the Nth candidate.
1462 To show the number next to the candidates in some back-ends, enable
1463 `company-show-numbers'."
1464 (when (company-manual-begin)
1465 (and (< n 1) (> n company-candidates-length)
1466 (error "No candidate number %d" n))
1467 (decf n)
1468 (company-finish (nth n company-candidates))))
1469
1470 ;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;
1471
1472 (defconst company-space-strings-limit 100)
1473
1474 (defconst company-space-strings
1475 (let (lst)
1476 (dotimes (i company-space-strings-limit)
1477 (push (make-string (- company-space-strings-limit 1 i) ?\ ) lst))
1478 (apply 'vector lst)))
1479
1480 (defun company-space-string (len)
1481 (if (< len company-space-strings-limit)
1482 (aref company-space-strings len)
1483 (make-string len ?\ )))
1484
1485 (defun company-safe-substring (str from &optional to)
1486 (if (> from (string-width str))
1487 ""
1488 (with-temp-buffer
1489 (insert str)
1490 (move-to-column from)
1491 (let ((beg (point)))
1492 (if to
1493 (progn
1494 (move-to-column to)
1495 (concat (buffer-substring beg (point))
1496 (let ((padding (- to (current-column))))
1497 (when (> padding 0)
1498 (company-space-string padding)))))
1499 (buffer-substring beg (point-max)))))))
1500
1501 ;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;
1502
1503 (defvar company-last-metadata nil)
1504 (make-variable-buffer-local 'company-last-metadata)
1505
1506 (defun company-fetch-metadata ()
1507 (let ((selected (nth company-selection company-candidates)))
1508 (unless (equal selected (car company-last-metadata))
1509 (setq company-last-metadata
1510 (cons selected (company-call-backend 'meta selected))))
1511 (cdr company-last-metadata)))
1512
1513 (defun company-doc-buffer (&optional string)
1514 (with-current-buffer (get-buffer-create "*company-documentation*")
1515 (erase-buffer)
1516 (when string
1517 (save-excursion
1518 (insert string)))
1519 (current-buffer)))
1520
1521 (defvar company--electric-commands
1522 '(scroll-other-window scroll-other-window-down)
1523 "List of Commands that won't break out of electric commands.")
1524
1525 (defmacro company--electric-do (&rest body)
1526 (declare (indent 0) (debug t))
1527 `(when (company-manual-begin)
1528 (save-window-excursion
1529 (let ((height (window-height))
1530 (row (company--row))
1531 cmd)
1532 ,@body
1533 (and (< (window-height) height)
1534 (< (- (window-height) row 2) company-tooltip-limit)
1535 (recenter (- (window-height) row 2)))
1536 (while (memq (setq cmd (key-binding (vector (list (read-event)))))
1537 company--electric-commands)
1538 (call-interactively cmd))
1539 (company--unread-last-input)))))
1540
1541 (defun company--unread-last-input ()
1542 (when last-input-event
1543 (clear-this-command-keys t)
1544 (setq unread-command-events (list last-input-event))))
1545
1546 (defun company-show-doc-buffer ()
1547 "Temporarily show the documentation buffer for the selection."
1548 (interactive)
1549 (company--electric-do
1550 (let* ((selected (nth company-selection company-candidates))
1551 (doc-buffer (or (company-call-backend 'doc-buffer selected)
1552 (error "No documentation available"))))
1553 (with-current-buffer doc-buffer
1554 (goto-char (point-min)))
1555 (display-buffer doc-buffer t))))
1556 (put 'company-show-doc-buffer 'company-keep t)
1557
1558 (defun company-show-location ()
1559 "Temporarily display a buffer showing the selected candidate in context."
1560 (interactive)
1561 (company--electric-do
1562 (let* ((selected (nth company-selection company-candidates))
1563 (location (company-call-backend 'location selected))
1564 (pos (or (cdr location) (error "No location available")))
1565 (buffer (or (and (bufferp (car location)) (car location))
1566 (find-file-noselect (car location) t))))
1567 (with-selected-window (display-buffer buffer t)
1568 (save-restriction
1569 (widen)
1570 (if (bufferp (car location))
1571 (goto-char pos)
1572 (goto-char (point-min))
1573 (forward-line (1- pos))))
1574 (set-window-start nil (point))))))
1575 (put 'company-show-location 'company-keep t)
1576
1577 ;;; package functions ;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;
1578
1579 (defvar company-callback nil)
1580 (make-variable-buffer-local 'company-callback)
1581
1582 (defvar company-begin-with-marker nil)
1583 (make-variable-buffer-local 'company-begin-with-marker)
1584
1585 (defun company-remove-callback (&optional ignored)
1586 (remove-hook 'company-completion-finished-hook company-callback t)
1587 (remove-hook 'company-completion-cancelled-hook 'company-remove-callback t)
1588 (remove-hook 'company-completion-finished-hook 'company-remove-callback t)
1589 (when company-begin-with-marker
1590 (set-marker company-begin-with-marker nil)))
1591
1592 (defun company-begin-backend (backend &optional callback)
1593 "Start a completion at point using BACKEND."
1594 (interactive (let ((val (completing-read "Company back-end: "
1595 obarray
1596 'functionp nil "company-")))
1597 (when val
1598 (list (intern val)))))
1599 (when (setq company-callback callback)
1600 (add-hook 'company-completion-finished-hook company-callback nil t))
1601 (add-hook 'company-completion-cancelled-hook 'company-remove-callback nil t)
1602 (add-hook 'company-completion-finished-hook 'company-remove-callback nil t)
1603 (setq company-backend backend)
1604 ;; Return non-nil if active.
1605 (or (company-manual-begin)
1606 (progn
1607 (setq company-backend nil)
1608 (error "Cannot complete at point"))))
1609
1610 (defun company-begin-with (candidates
1611 &optional prefix-length require-match callback)
1612 "Start a completion at point.
1613 CANDIDATES is the list of candidates to use and PREFIX-LENGTH is the length
1614 of the prefix that already is in the buffer before point.
1615 It defaults to 0.
1616
1617 CALLBACK is a function called with the selected result if the user
1618 successfully completes the input.
1619
1620 Example: \(company-begin-with '\(\"foo\" \"foobar\" \"foobarbaz\"\)\)"
1621 ;; FIXME: When Emacs 23 is no longer a concern, replace
1622 ;; `company-begin-with-marker' with a lexical variable; use a lexical closure.
1623 (setq company-begin-with-marker (copy-marker (point) t))
1624 (company-begin-backend
1625 `(lambda (command &optional arg &rest ignored)
1626 (cond
1627 ((eq command 'prefix)
1628 (when (equal (point) (marker-position company-begin-with-marker))
1629 (buffer-substring ,(- (point) (or prefix-length 0)) (point))))
1630 ((eq command 'candidates)
1631 (all-completions arg ',candidates))
1632 ((eq command 'require-match)
1633 ,require-match)))
1634 callback))
1635
1636 ;;; pseudo-tooltip ;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;
1637
1638 (defvar company-pseudo-tooltip-overlay nil)
1639 (make-variable-buffer-local 'company-pseudo-tooltip-overlay)
1640
1641 (defvar company-tooltip-offset 0)
1642 (make-variable-buffer-local 'company-tooltip-offset)
1643
1644 (defun company-pseudo-tooltip-update-offset (selection num-lines limit)
1645
1646 (decf limit 2)
1647 (setq company-tooltip-offset
1648 (max (min selection company-tooltip-offset)
1649 (- selection -1 limit)))
1650
1651 (when (<= company-tooltip-offset 1)
1652 (incf limit)
1653 (setq company-tooltip-offset 0))
1654
1655 (when (>= company-tooltip-offset (- num-lines limit 1))
1656 (incf limit)
1657 (when (= selection (1- num-lines))
1658 (decf company-tooltip-offset)
1659 (when (<= company-tooltip-offset 1)
1660 (setq company-tooltip-offset 0)
1661 (incf limit))))
1662
1663 limit)
1664
1665 ;;; propertize
1666
1667 (defsubst company-round-tab (arg)
1668 (* (/ (+ arg tab-width) tab-width) tab-width))
1669
1670 (defun company-plainify (str)
1671 (let ((prefix (get-text-property 0 'line-prefix str)))
1672 (when prefix ; Keep the original value unmodified, for no special reason.
1673 (setq str (concat prefix str))
1674 (remove-text-properties 0 (length str) '(line-prefix) str)))
1675 (let* ((pieces (split-string str "\t"))
1676 (copy pieces))
1677 (while (cdr copy)
1678 (setcar copy (company-safe-substring
1679 (car copy) 0 (company-round-tab (string-width (car copy)))))
1680 (pop copy))
1681 (apply 'concat pieces)))
1682
1683 (defun company--highlight-common (line properties)
1684 ;; XXX: Subject to change.
1685 (let ((common (or (company-call-backend 'common-part line)
1686 (length company-common))))
1687 (add-text-properties 0 common properties line)))
1688
1689 (defun company-fill-propertize (line width selected)
1690 (let ((common (or (company-call-backend 'common-part line)
1691 (length company-common))))
1692 (setq line (company-safe-substring line 0 width))
1693 (add-text-properties 0 width '(face company-tooltip
1694 mouse-face company-tooltip-mouse)
1695 line)
1696 (add-text-properties 0 common '(face company-tooltip-common
1697 mouse-face company-tooltip-mouse)
1698 line)
1699 (when selected
1700 (if (and company-search-string
1701 (string-match (regexp-quote company-search-string) line
1702 (length company-prefix)))
1703 (progn
1704 (add-text-properties (match-beginning 0) (match-end 0)
1705 '(face company-tooltip-selection)
1706 line)
1707 (when (< (match-beginning 0) common)
1708 (add-text-properties (match-beginning 0) common
1709 '(face company-tooltip-common-selection)
1710 line)))
1711 (add-text-properties 0 width '(face company-tooltip-selection
1712 mouse-face company-tooltip-selection)
1713 line)
1714 (add-text-properties 0 common '(face company-tooltip-common-selection
1715 mouse-face company-tooltip-selection)
1716 line))))
1717 line)
1718
1719 ;;; replace
1720
1721 (defun company-buffer-lines (beg end)
1722 (goto-char beg)
1723 (let (lines)
1724 (while (and (= 1 (vertical-motion 1))
1725 (<= (point) end))
1726 (let ((bound (min end (1- (point)))))
1727 ;; A visual line can contain several physical lines (e.g. with outline's
1728 ;; folding overlay). Take only the first one.
1729 (push (buffer-substring beg
1730 (save-excursion
1731 (goto-char beg)
1732 (re-search-forward "$" bound 'move)
1733 (point)))
1734 lines))
1735 (setq beg (point)))
1736 (unless (eq beg end)
1737 (push (buffer-substring beg end) lines))
1738 (nreverse lines)))
1739
1740 (defun company-modify-line (old new offset)
1741 (concat (company-safe-substring old 0 offset)
1742 new
1743 (company-safe-substring old (+ offset (length new)))))
1744
1745 (defsubst company--length-limit (lst limit)
1746 (if (nthcdr limit lst)
1747 limit
1748 (length lst)))
1749
1750 (defun company--replacement-string (lines old column nl &optional align-top)
1751
1752 (let ((width (length (car lines)))
1753 (remaining-cols (- (+ (window-width) (window-hscroll))
1754 column)))
1755 (when (> width remaining-cols)
1756 (decf column (- width remaining-cols))))
1757
1758 (let (new)
1759 (when align-top
1760 ;; untouched lines first
1761 (dotimes (_ (- (length old) (length lines)))
1762 (push (pop old) new)))
1763 ;; length into old lines.
1764 (while old
1765 (push (company-modify-line (pop old) (pop lines) column) new))
1766 ;; Append whole new lines.
1767 (while lines
1768 (push (concat (company-space-string column) (pop lines)) new))
1769
1770 (let ((str (concat (when nl "\n")
1771 (mapconcat 'identity (nreverse new) "\n")
1772 "\n")))
1773 (font-lock-append-text-property 0 (length str) 'face 'default str)
1774 str)))
1775
1776 (defun company--create-lines (selection limit)
1777
1778 (let ((len company-candidates-length)
1779 (numbered 99999)
1780 lines
1781 width
1782 lines-copy
1783 previous
1784 remainder
1785 new)
1786
1787 ;; Scroll to offset.
1788 (setq limit (company-pseudo-tooltip-update-offset selection len limit))
1789
1790 (when (> company-tooltip-offset 0)
1791 (setq previous (format "...(%d)" company-tooltip-offset)))
1792
1793 (setq remainder (- len limit company-tooltip-offset)
1794 remainder (when (> remainder 0)
1795 (setq remainder (format "...(%d)" remainder))))
1796
1797 (decf selection company-tooltip-offset)
1798 (setq width (max (length previous) (length remainder))
1799 lines (nthcdr company-tooltip-offset company-candidates)
1800 len (min limit len)
1801 lines-copy lines)
1802
1803 (dotimes (_ len)
1804 (setq width (max (length (pop lines-copy)) width)))
1805 (setq width (min (window-width)
1806 (if company-show-numbers
1807 (+ 2 width)
1808 width)))
1809 (setq lines-copy lines)
1810
1811 ;; number can make tooltip too long
1812 (when company-show-numbers
1813 (setq numbered company-tooltip-offset))
1814
1815 (when previous
1816 (push (propertize (company-safe-substring previous 0 width)
1817 'face 'company-tooltip)
1818 new))
1819
1820 (dotimes (i len)
1821 (push (company-fill-propertize
1822 (if (>= numbered 10)
1823 (company-reformat (pop lines))
1824 (incf numbered)
1825 (format "%s %d"
1826 (company-safe-substring (company-reformat (pop lines))
1827 0 (- width 2))
1828 (mod numbered 10)))
1829 width (equal i selection))
1830 new))
1831
1832 (when remainder
1833 (push (propertize (company-safe-substring remainder 0 width)
1834 'face 'company-tooltip)
1835 new))
1836
1837 (setq lines (nreverse new))))
1838
1839 ;; show
1840
1841 (defsubst company--window-inner-height ()
1842 (let ((edges (window-inside-edges)))
1843 (- (nth 3 edges) (nth 1 edges))))
1844
1845 (defun company--pseudo-tooltip-height ()
1846 "Calculate the appropriate tooltip height.
1847 Returns a negative number if the tooltip should be displayed above point."
1848 (let* ((lines (company--row))
1849 (below (- (company--window-inner-height) 1 lines)))
1850 (if (and (< below (min company-tooltip-minimum company-candidates-length))
1851 (> lines below))
1852 (- (max 3 (min company-tooltip-limit lines)))
1853 (max 3 (min company-tooltip-limit below)))))
1854
1855 (defun company-pseudo-tooltip-show (row column selection)
1856 (company-pseudo-tooltip-hide)
1857 (save-excursion
1858
1859 (let* ((height (company--pseudo-tooltip-height))
1860 above)
1861
1862 (when (< height 0)
1863 (setq row (+ row height -1)
1864 above t))
1865
1866 (let* ((nl (< (move-to-window-line row) row))
1867 (beg (point))
1868 (end (save-excursion
1869 (move-to-window-line (+ row (abs height)))
1870 (point)))
1871 (ov (make-overlay beg end))
1872 (args (list (mapcar 'company-plainify
1873 (company-buffer-lines beg end))
1874 column nl above)))
1875
1876 (setq company-pseudo-tooltip-overlay ov)
1877 (overlay-put ov 'company-replacement-args args)
1878
1879 (let ((lines (company--create-lines selection (abs height))))
1880 (overlay-put ov 'company-after
1881 (apply 'company--replacement-string lines args))
1882 (overlay-put ov 'company-width (string-width (car lines))))
1883
1884 (overlay-put ov 'company-column column)
1885 (overlay-put ov 'company-height height)))))
1886
1887 (defun company-pseudo-tooltip-show-at-point (pos)
1888 (let ((row (company--row pos))
1889 (col (company--column pos)))
1890 (company-pseudo-tooltip-show (1+ row) col company-selection)))
1891
1892 (defun company-pseudo-tooltip-edit (selection)
1893 (let ((height (overlay-get company-pseudo-tooltip-overlay 'company-height)))
1894 (overlay-put company-pseudo-tooltip-overlay 'company-after
1895 (apply 'company--replacement-string
1896 (company--create-lines selection (abs height))
1897 (overlay-get company-pseudo-tooltip-overlay
1898 'company-replacement-args)))))
1899
1900 (defun company-pseudo-tooltip-hide ()
1901 (when company-pseudo-tooltip-overlay
1902 (delete-overlay company-pseudo-tooltip-overlay)
1903 (setq company-pseudo-tooltip-overlay nil)))
1904
1905 (defun company-pseudo-tooltip-hide-temporarily ()
1906 (when (overlayp company-pseudo-tooltip-overlay)
1907 (overlay-put company-pseudo-tooltip-overlay 'invisible nil)
1908 (overlay-put company-pseudo-tooltip-overlay 'line-prefix nil)
1909 (overlay-put company-pseudo-tooltip-overlay 'after-string nil)))
1910
1911 (defun company-pseudo-tooltip-unhide ()
1912 (when company-pseudo-tooltip-overlay
1913 (overlay-put company-pseudo-tooltip-overlay 'invisible t)
1914 ;; Beat outline's folding overlays, at least.
1915 (overlay-put company-pseudo-tooltip-overlay 'priority 1)
1916 ;; No (extra) prefix for the first line.
1917 (overlay-put company-pseudo-tooltip-overlay 'line-prefix "")
1918 (overlay-put company-pseudo-tooltip-overlay 'after-string
1919 (overlay-get company-pseudo-tooltip-overlay 'company-after))
1920 (overlay-put company-pseudo-tooltip-overlay 'window (selected-window))))
1921
1922 (defun company-pseudo-tooltip-guard ()
1923 (buffer-substring-no-properties
1924 (point) (overlay-start company-pseudo-tooltip-overlay)))
1925
1926 (defun company-pseudo-tooltip-frontend (command)
1927 "`company-mode' front-end similar to a tooltip but based on overlays."
1928 (case command
1929 (pre-command (company-pseudo-tooltip-hide-temporarily))
1930 (post-command
1931 (let ((old-height (if (overlayp company-pseudo-tooltip-overlay)
1932 (overlay-get company-pseudo-tooltip-overlay
1933 'company-height)
1934 0))
1935 (new-height (company--pseudo-tooltip-height)))
1936 (unless (and (>= (* old-height new-height) 0)
1937 (>= (abs old-height) (abs new-height))
1938 (equal (company-pseudo-tooltip-guard)
1939 (overlay-get company-pseudo-tooltip-overlay
1940 'company-guard)))
1941 ;; Redraw needed.
1942 (company-pseudo-tooltip-show-at-point (- (point)
1943 (length company-prefix)))
1944 (overlay-put company-pseudo-tooltip-overlay
1945 'company-guard (company-pseudo-tooltip-guard))))
1946 (company-pseudo-tooltip-unhide))
1947 (hide (company-pseudo-tooltip-hide)
1948 (setq company-tooltip-offset 0))
1949 (update (when (overlayp company-pseudo-tooltip-overlay)
1950 (company-pseudo-tooltip-edit company-selection)))))
1951
1952 (defun company-pseudo-tooltip-unless-just-one-frontend (command)
1953 "`company-pseudo-tooltip-frontend', but not shown for single candidates."
1954 (unless (and (eq command 'post-command)
1955 (company--show-inline-p))
1956 (company-pseudo-tooltip-frontend command)))
1957
1958 ;;; overlay ;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;
1959
1960 (defvar company-preview-overlay nil)
1961 (make-variable-buffer-local 'company-preview-overlay)
1962
1963 (defun company-preview-show-at-point (pos)
1964 (company-preview-hide)
1965
1966 (setq company-preview-overlay (make-overlay pos pos))
1967
1968 (let ((completion(nth company-selection company-candidates)))
1969 (setq completion (propertize completion 'face 'company-preview))
1970 (add-text-properties 0 (length company-common)
1971 '(face company-preview-common) completion)
1972
1973 ;; Add search string
1974 (and company-search-string
1975 (string-match (regexp-quote company-search-string) completion)
1976 (add-text-properties (match-beginning 0)
1977 (match-end 0)
1978 '(face company-preview-search)
1979 completion))
1980
1981 (setq completion (company-strip-prefix completion))
1982
1983 (and (equal pos (point))
1984 (not (equal completion ""))
1985 (add-text-properties 0 1 '(cursor t) completion))
1986
1987 (overlay-put company-preview-overlay 'after-string completion)
1988 (overlay-put company-preview-overlay 'window (selected-window))))
1989
1990 (defun company-preview-hide ()
1991 (when company-preview-overlay
1992 (delete-overlay company-preview-overlay)
1993 (setq company-preview-overlay nil)))
1994
1995 (defun company-preview-frontend (command)
1996 "`company-mode' front-end showing the selection as if it had been inserted."
1997 (case command
1998 (pre-command (company-preview-hide))
1999 (post-command (company-preview-show-at-point (point)))
2000 (hide (company-preview-hide))))
2001
2002 (defun company-preview-if-just-one-frontend (command)
2003 "`company-preview-frontend', but only shown for single candidates."
2004 (when (or (not (eq command 'post-command))
2005 (company--show-inline-p))
2006 (company-preview-frontend command)))
2007
2008 (defun company--show-inline-p ()
2009 (and (not (cdr company-candidates))
2010 company-common
2011 (string-prefix-p company-prefix company-common
2012 (company-call-backend 'ignore-case))))
2013
2014 ;;; echo ;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;
2015
2016 (defvar company-echo-last-msg nil)
2017 (make-variable-buffer-local 'company-echo-last-msg)
2018
2019 (defvar company-echo-timer nil)
2020
2021 (defvar company-echo-delay .01)
2022
2023 (defun company-echo-show (&optional getter)
2024 (when getter
2025 (setq company-echo-last-msg (funcall getter)))
2026 (let ((message-log-max nil))
2027 (if company-echo-last-msg
2028 (message "%s" company-echo-last-msg)
2029 (message ""))))
2030
2031 (defun company-echo-show-soon (&optional getter)
2032 (when company-echo-timer
2033 (cancel-timer company-echo-timer))
2034 (setq company-echo-timer (run-with-timer 0 nil 'company-echo-show getter)))
2035
2036 (defsubst company-echo-show-when-idle (&optional getter)
2037 (when (sit-for company-echo-delay)
2038 (company-echo-show getter)))
2039
2040 (defun company-echo-format ()
2041
2042 (let ((limit (window-width (minibuffer-window)))
2043 (len -1)
2044 ;; Roll to selection.
2045 (candidates (nthcdr company-selection company-candidates))
2046 (i (if company-show-numbers company-selection 99999))
2047 comp msg)
2048
2049 (while candidates
2050 (setq comp (company-reformat (pop candidates))
2051 len (+ len 1 (length comp)))
2052 (if (< i 10)
2053 ;; Add number.
2054 (progn
2055 (setq comp (propertize (format "%d: %s" i comp)
2056 'face 'company-echo))
2057 (incf len 3)
2058 (incf i)
2059 (add-text-properties 3 (+ 3 (length company-common))
2060 '(face company-echo-common) comp))
2061 (setq comp (propertize comp 'face 'company-echo))
2062 (add-text-properties 0 (length company-common)
2063 '(face company-echo-common) comp))
2064 (if (>= len limit)
2065 (setq candidates nil)
2066 (push comp msg)))
2067
2068 (mapconcat 'identity (nreverse msg) " ")))
2069
2070 (defun company-echo-strip-common-format ()
2071
2072 (let ((limit (window-width (minibuffer-window)))
2073 (len (+ (length company-prefix) 2))
2074 ;; Roll to selection.
2075 (candidates (nthcdr company-selection company-candidates))
2076 (i (if company-show-numbers company-selection 99999))
2077 msg comp)
2078
2079 (while candidates
2080 (setq comp (company-strip-prefix (pop candidates))
2081 len (+ len 2 (length comp)))
2082 (when (< i 10)
2083 ;; Add number.
2084 (setq comp (format "%s (%d)" comp i))
2085 (incf len 4)
2086 (incf i))
2087 (if (>= len limit)
2088 (setq candidates nil)
2089 (push (propertize comp 'face 'company-echo) msg)))
2090
2091 (concat (propertize company-prefix 'face 'company-echo-common) "{"
2092 (mapconcat 'identity (nreverse msg) ", ")
2093 "}")))
2094
2095 (defun company-echo-hide ()
2096 (unless (equal company-echo-last-msg "")
2097 (setq company-echo-last-msg "")
2098 (company-echo-show)))
2099
2100 (defun company-echo-frontend (command)
2101 "`company-mode' front-end showing the candidates in the echo area."
2102 (case command
2103 (post-command (company-echo-show-soon 'company-echo-format))
2104 (hide (company-echo-hide))))
2105
2106 (defun company-echo-strip-common-frontend (command)
2107 "`company-mode' front-end showing the candidates in the echo area."
2108 (case command
2109 (post-command (company-echo-show-soon 'company-echo-strip-common-format))
2110 (hide (company-echo-hide))))
2111
2112 (defun company-echo-metadata-frontend (command)
2113 "`company-mode' front-end showing the documentation in the echo area."
2114 (case command
2115 (post-command (company-echo-show-when-idle 'company-fetch-metadata))
2116 (hide (company-echo-hide))))
2117
2118 (provide 'company)
2119 ;;; company.el ends here