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