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