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