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