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