]> code.delx.au - gnu-emacs-elpa/blob - packages/company/company.el
company: Release 0.6.7
[gnu-emacs-elpa] / packages / company / 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.7
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 (unwind-protect
899 (company-auto-begin)
900 (unless company-candidates
901 (setq company--explicit-action nil))))
902
903 (defun company-other-backend (&optional backward)
904 (interactive (list current-prefix-arg))
905 (company-assert-enabled)
906 (if company-backend
907 (let* ((after (cdr (member company-backend company-backends)))
908 (before (cdr (member company-backend (reverse company-backends))))
909 (next (if backward
910 (append before (reverse after))
911 (append after (reverse before)))))
912 (company-cancel)
913 (dolist (backend next)
914 (when (ignore-errors (company-begin-backend backend))
915 (return t))))
916 (company-manual-begin))
917 (unless company-candidates
918 (error "No other back-end")))
919
920 (defun company-require-match-p ()
921 (let ((backend-value (company-call-backend 'require-match)))
922 (or (eq backend-value t)
923 (and (if (functionp company-require-match)
924 (funcall company-require-match)
925 (eq company-require-match t))
926 (not (eq backend-value 'never))))))
927
928 (defun company-punctuation-p (input)
929 "Return non-nil, if input starts with punctuation or parentheses."
930 (memq (char-syntax (string-to-char input)) '(?. ?\( ?\))))
931
932 (defun company-auto-complete-p (input)
933 "Return non-nil, if input starts with punctuation or parentheses."
934 (and (if (functionp company-auto-complete)
935 (funcall company-auto-complete)
936 company-auto-complete)
937 (if (functionp company-auto-complete-chars)
938 (funcall company-auto-complete-chars input)
939 (if (consp company-auto-complete-chars)
940 (memq (char-syntax (string-to-char input))
941 company-auto-complete-chars)
942 (string-match (substring input 0 1) company-auto-complete-chars)))))
943
944 (defun company--incremental-p ()
945 (and (> (point) company-point)
946 (> (point-max) company--point-max)
947 (not (eq this-command 'backward-delete-char-untabify))
948 (equal (buffer-substring (- company-point (length company-prefix))
949 company-point)
950 company-prefix)))
951
952 (defsubst company--string-incremental-p (old-prefix new-prefix)
953 (and (> (length new-prefix) (length old-prefix))
954 (equal old-prefix (substring new-prefix 0 (length old-prefix)))))
955
956 (defun company--continue-failed (new-prefix)
957 (when (company--incremental-p)
958 (let ((input (buffer-substring-no-properties (point) company-point)))
959 (cond
960 ((company-auto-complete-p input)
961 ;; auto-complete
962 (save-excursion
963 (goto-char company-point)
964 (let ((company--auto-completion t))
965 (company-complete-selection))
966 nil))
967 ((and (company--string-incremental-p company-prefix new-prefix)
968 (company-require-match-p))
969 ;; wrong incremental input, but required match
970 (backward-delete-char (length input))
971 (ding)
972 (message "Matching input is required")
973 company-candidates)
974 ((equal company-prefix (car company-candidates))
975 ;; last input was actually success
976 (company-cancel company-prefix)
977 nil)))))
978
979 (defun company--good-prefix-p (prefix)
980 (and (or (company-explicit-action-p)
981 (unless (eq prefix 'stop)
982 (>= (or (cdr-safe prefix) (length prefix))
983 company-minimum-prefix-length)))
984 (stringp (or (car-safe prefix) prefix))))
985
986 (defun company--continue ()
987 (when (company-call-backend 'no-cache company-prefix)
988 ;; Don't complete existing candidates, fetch new ones.
989 (setq company-candidates-cache nil))
990 (let* ((new-prefix (company-call-backend 'prefix))
991 (c (when (and (company--good-prefix-p new-prefix)
992 (setq new-prefix (or (car-safe new-prefix) new-prefix))
993 (= (- (point) (length new-prefix))
994 (- company-point (length company-prefix))))
995 (setq new-prefix (or (car-safe new-prefix) new-prefix))
996 (company-calculate-candidates new-prefix))))
997 (or (cond
998 ((eq c t)
999 ;; t means complete/unique.
1000 (company-cancel new-prefix)
1001 nil)
1002 ((consp c)
1003 ;; incremental match
1004 (setq company-prefix new-prefix)
1005 (company-update-candidates c)
1006 c)
1007 (t (company--continue-failed new-prefix)))
1008 (company-cancel))))
1009
1010 (defun company--begin-new ()
1011 (let (prefix c)
1012 (dolist (backend (if company-backend
1013 ;; prefer manual override
1014 (list company-backend)
1015 company-backends))
1016 (setq prefix
1017 (if (or (symbolp backend)
1018 (functionp backend))
1019 (when (or (not (symbolp backend))
1020 (eq t (get backend 'company-init))
1021 (unless (get backend 'company-init)
1022 (company-init-backend backend)))
1023 (funcall backend 'prefix))
1024 (company--multi-backend-adapter backend 'prefix)))
1025 (when prefix
1026 (when (company--good-prefix-p prefix)
1027 (setq prefix (or (car-safe prefix) prefix)
1028 company-backend backend
1029 c (company-calculate-candidates prefix))
1030 ;; t means complete/unique. We don't start, so no hooks.
1031 (if (not (consp c))
1032 (when company--explicit-action
1033 (message "No completion found"))
1034 (setq company-prefix prefix)
1035 (when (symbolp backend)
1036 (setq company-lighter (concat " " (symbol-name backend))))
1037 (company-update-candidates c)
1038 (run-hook-with-args 'company-completion-started-hook
1039 (company-explicit-action-p))
1040 (company-call-frontends 'show)))
1041 (return c)))))
1042
1043 (defun company-begin ()
1044 (or (and company-candidates (company--continue))
1045 (and (company--should-complete) (company--begin-new)))
1046 (when company-candidates
1047 (when (and company-end-of-buffer-workaround (eobp))
1048 (save-excursion (insert "\n"))
1049 (setq company-added-newline (buffer-chars-modified-tick)))
1050 (setq company-point (point)
1051 company--point-max (point-max))
1052 (company-ensure-emulation-alist)
1053 (company-enable-overriding-keymap company-active-map)
1054 (company-call-frontends 'update)))
1055
1056 (defun company-cancel (&optional result)
1057 (and company-added-newline
1058 (> (point-max) (point-min))
1059 (let ((tick (buffer-chars-modified-tick)))
1060 (delete-region (1- (point-max)) (point-max))
1061 (equal tick company-added-newline))
1062 ;; Only set unmodified when tick remained the same since insert.
1063 (set-buffer-modified-p nil))
1064 (when company-prefix
1065 (if (stringp result)
1066 (progn
1067 (company-call-backend 'pre-completion result)
1068 (run-hook-with-args 'company-completion-finished-hook result)
1069 (company-call-backend 'post-completion result))
1070 (run-hook-with-args 'company-completion-cancelled-hook result)))
1071 (setq company-added-newline nil
1072 company-backend nil
1073 company-prefix nil
1074 company-candidates nil
1075 company-candidates-length nil
1076 company-candidates-cache nil
1077 company-candidates-predicate nil
1078 company-common nil
1079 company-selection 0
1080 company-selection-changed nil
1081 company--explicit-action nil
1082 company-lighter company-default-lighter
1083 company--point-max nil
1084 company-point nil)
1085 (when company-timer
1086 (cancel-timer company-timer))
1087 (company-search-mode 0)
1088 (company-call-frontends 'hide)
1089 (company-enable-overriding-keymap nil))
1090
1091 (defun company-abort ()
1092 (interactive)
1093 (company-cancel t)
1094 ;; Don't start again, unless started manually.
1095 (setq company-point (point)))
1096
1097 (defun company-finish (result)
1098 (insert (company-strip-prefix result))
1099 (company-cancel result)
1100 ;; Don't start again, unless started manually.
1101 (setq company-point (point)))
1102
1103 (defsubst company-keep (command)
1104 (and (symbolp command) (get command 'company-keep)))
1105
1106 (defun company-pre-command ()
1107 (unless (company-keep this-command)
1108 (condition-case err
1109 (when company-candidates
1110 (company-call-frontends 'pre-command))
1111 (error (message "Company: An error occurred in pre-command")
1112 (message "%s" (error-message-string err))
1113 (company-cancel))))
1114 (when company-timer
1115 (cancel-timer company-timer)
1116 (setq company-timer nil))
1117 (company-uninstall-map))
1118
1119 (defun company-post-command ()
1120 (unless (company-keep this-command)
1121 (condition-case err
1122 (progn
1123 (unless (equal (point) company-point)
1124 (company-begin))
1125 (if company-candidates
1126 (company-call-frontends 'post-command)
1127 (and (numberp company-idle-delay)
1128 (or (eq t company-begin-commands)
1129 (memq this-command company-begin-commands))
1130 (setq company-timer
1131 (run-with-timer company-idle-delay nil
1132 'company-idle-begin
1133 (current-buffer) (selected-window)
1134 (buffer-chars-modified-tick) (point))))))
1135 (error (message "Company: An error occurred in post-command")
1136 (message "%s" (error-message-string err))
1137 (company-cancel))))
1138 (company-install-map))
1139
1140 ;;; search ;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;
1141
1142 (defvar company-search-string nil)
1143 (make-variable-buffer-local 'company-search-string)
1144
1145 (defvar company-search-lighter " Search: \"\"")
1146 (make-variable-buffer-local 'company-search-lighter)
1147
1148 (defvar company-search-old-map nil)
1149 (make-variable-buffer-local 'company-search-old-map)
1150
1151 (defvar company-search-old-selection 0)
1152 (make-variable-buffer-local 'company-search-old-selection)
1153
1154 (defun company-search (text lines)
1155 (let ((quoted (regexp-quote text))
1156 (i 0))
1157 (dolist (line lines)
1158 (when (string-match quoted line (length company-prefix))
1159 (return i))
1160 (incf i))))
1161
1162 (defun company-search-printing-char ()
1163 (interactive)
1164 (company-search-assert-enabled)
1165 (setq company-search-string
1166 (concat (or company-search-string "") (string last-command-event))
1167 company-search-lighter (concat " Search: \"" company-search-string
1168 "\""))
1169 (let ((pos (company-search company-search-string
1170 (nthcdr company-selection company-candidates))))
1171 (if (null pos)
1172 (ding)
1173 (company-set-selection (+ company-selection pos) t))))
1174
1175 (defun company-search-repeat-forward ()
1176 "Repeat the incremental search in completion candidates forward."
1177 (interactive)
1178 (company-search-assert-enabled)
1179 (let ((pos (company-search company-search-string
1180 (cdr (nthcdr company-selection
1181 company-candidates)))))
1182 (if (null pos)
1183 (ding)
1184 (company-set-selection (+ company-selection pos 1) t))))
1185
1186 (defun company-search-repeat-backward ()
1187 "Repeat the incremental search in completion candidates backwards."
1188 (interactive)
1189 (company-search-assert-enabled)
1190 (let ((pos (company-search company-search-string
1191 (nthcdr (- company-candidates-length
1192 company-selection)
1193 (reverse company-candidates)))))
1194 (if (null pos)
1195 (ding)
1196 (company-set-selection (- company-selection pos 1) t))))
1197
1198 (defun company-create-match-predicate ()
1199 (setq company-candidates-predicate
1200 `(lambda (candidate)
1201 ,(if company-candidates-predicate
1202 `(and (string-match ,company-search-string candidate)
1203 (funcall ,company-candidates-predicate
1204 candidate))
1205 `(string-match ,company-search-string candidate))))
1206 (company-update-candidates
1207 (company-apply-predicate company-candidates company-candidates-predicate))
1208 ;; Invalidate cache.
1209 (setq company-candidates-cache (cons company-prefix company-candidates)))
1210
1211 (defun company-filter-printing-char ()
1212 (interactive)
1213 (company-search-assert-enabled)
1214 (company-search-printing-char)
1215 (company-create-match-predicate)
1216 (company-call-frontends 'update))
1217
1218 (defun company-search-kill-others ()
1219 "Limit the completion candidates to the ones matching the search string."
1220 (interactive)
1221 (company-search-assert-enabled)
1222 (company-create-match-predicate)
1223 (company-search-mode 0)
1224 (company-call-frontends 'update))
1225
1226 (defun company-search-abort ()
1227 "Abort searching the completion candidates."
1228 (interactive)
1229 (company-search-assert-enabled)
1230 (company-set-selection company-search-old-selection t)
1231 (company-search-mode 0))
1232
1233 (defun company-search-other-char ()
1234 (interactive)
1235 (company-search-assert-enabled)
1236 (company-search-mode 0)
1237 (company--unread-last-input))
1238
1239 (defvar company-search-map
1240 (let ((i 0)
1241 (keymap (make-keymap)))
1242 (if (fboundp 'max-char)
1243 (set-char-table-range (nth 1 keymap) (cons #x100 (max-char))
1244 'company-search-printing-char)
1245 (with-no-warnings
1246 ;; obsolete in Emacs 23
1247 (let ((l (generic-character-list))
1248 (table (nth 1 keymap)))
1249 (while l
1250 (set-char-table-default table (car l) 'company-search-printing-char)
1251 (setq l (cdr l))))))
1252 (define-key keymap [t] 'company-search-other-char)
1253 (while (< i ?\s)
1254 (define-key keymap (make-string 1 i) 'company-search-other-char)
1255 (incf i))
1256 (while (< i 256)
1257 (define-key keymap (vector i) 'company-search-printing-char)
1258 (incf i))
1259 (let ((meta-map (make-sparse-keymap)))
1260 (define-key keymap (char-to-string meta-prefix-char) meta-map)
1261 (define-key keymap [escape] meta-map))
1262 (define-key keymap (vector meta-prefix-char t) 'company-search-other-char)
1263 (define-key keymap "\e\e\e" 'company-search-other-char)
1264 (define-key keymap [escape escape escape] 'company-search-other-char)
1265
1266 (define-key keymap "\C-g" 'company-search-abort)
1267 (define-key keymap "\C-s" 'company-search-repeat-forward)
1268 (define-key keymap "\C-r" 'company-search-repeat-backward)
1269 (define-key keymap "\C-o" 'company-search-kill-others)
1270 keymap)
1271 "Keymap used for incrementally searching the completion candidates.")
1272
1273 (define-minor-mode company-search-mode
1274 "Search mode for completion candidates.
1275 Don't start this directly, use `company-search-candidates' or
1276 `company-filter-candidates'."
1277 nil company-search-lighter nil
1278 (if company-search-mode
1279 (if (company-manual-begin)
1280 (progn
1281 (setq company-search-old-selection company-selection)
1282 (company-call-frontends 'update))
1283 (setq company-search-mode nil))
1284 (kill-local-variable 'company-search-string)
1285 (kill-local-variable 'company-search-lighter)
1286 (kill-local-variable 'company-search-old-selection)
1287 (company-enable-overriding-keymap company-active-map)))
1288
1289 (defsubst company-search-assert-enabled ()
1290 (company-assert-enabled)
1291 (unless company-search-mode
1292 (company-uninstall-map)
1293 (error "Company not in search mode")))
1294
1295 (defun company-search-candidates ()
1296 "Start searching the completion candidates incrementally.
1297
1298 \\<company-search-map>Search can be controlled with the commands:
1299 - `company-search-repeat-forward' (\\[company-search-repeat-forward])
1300 - `company-search-repeat-backward' (\\[company-search-repeat-backward])
1301 - `company-search-abort' (\\[company-search-abort])
1302
1303 Regular characters are appended to the search string.
1304
1305 The command `company-search-kill-others' (\\[company-search-kill-others]) uses
1306 the search string to limit the completion candidates."
1307 (interactive)
1308 (company-search-mode 1)
1309 (company-enable-overriding-keymap company-search-map))
1310
1311 (defvar company-filter-map
1312 (let ((keymap (make-keymap)))
1313 (define-key keymap [remap company-search-printing-char]
1314 'company-filter-printing-char)
1315 (set-keymap-parent keymap company-search-map)
1316 keymap)
1317 "Keymap used for incrementally searching the completion candidates.")
1318
1319 (defun company-filter-candidates ()
1320 "Start filtering the completion candidates incrementally.
1321 This works the same way as `company-search-candidates' immediately
1322 followed by `company-search-kill-others' after each input."
1323 (interactive)
1324 (company-search-mode 1)
1325 (company-enable-overriding-keymap company-filter-map))
1326
1327 ;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;
1328
1329 (defun company-select-next ()
1330 "Select the next candidate in the list."
1331 (interactive)
1332 (when (company-manual-begin)
1333 (company-set-selection (1+ company-selection))))
1334
1335 (defun company-select-previous ()
1336 "Select the previous candidate in the list."
1337 (interactive)
1338 (when (company-manual-begin)
1339 (company-set-selection (1- company-selection))))
1340
1341 (defun company-select-next-or-abort ()
1342 "Select the next candidate if more than one, else abort
1343 and invoke the normal binding."
1344 (interactive)
1345 (if (> company-candidates-length 1)
1346 (company-select-next)
1347 (company-abort)
1348 (company--unread-last-input)))
1349
1350 (defun company-select-previous-or-abort ()
1351 "Select the previous candidate if more than one, else abort
1352 and invoke the normal binding."
1353 (interactive)
1354 (if (> company-candidates-length 1)
1355 (company-select-previous)
1356 (company-abort)
1357 (company--unread-last-input)))
1358
1359 (defun company-select-mouse (event)
1360 "Select the candidate picked by the mouse."
1361 (interactive "e")
1362 (when (nth 4 (event-start event))
1363 (company-set-selection (- (cdr (posn-actual-col-row (event-start event)))
1364 (company--row)
1365 1))
1366 t))
1367
1368 (defun company-complete-mouse (event)
1369 "Complete the candidate picked by the mouse."
1370 (interactive "e")
1371 (when (company-select-mouse event)
1372 (company-complete-selection)))
1373
1374 (defun company-complete-selection ()
1375 "Complete the selected candidate."
1376 (interactive)
1377 (when (company-manual-begin)
1378 (let ((result (nth company-selection company-candidates)))
1379 (when company--auto-completion
1380 (setq result (company--safe-candidate result)))
1381 (company-finish result))))
1382
1383 (defun company-complete-common ()
1384 "Complete the common part of all candidates."
1385 (interactive)
1386 (when (company-manual-begin)
1387 (if (and (not (cdr company-candidates))
1388 (equal company-common (car company-candidates)))
1389 (company-complete-selection)
1390 (insert (company-strip-prefix company-common)))))
1391
1392 (defun company-complete ()
1393 "Complete the common part of all candidates or the current selection.
1394 The first time this is called, the common part is completed, the second time, or
1395 when the selection has been changed, the selected candidate is completed."
1396 (interactive)
1397 (when (company-manual-begin)
1398 (if (or company-selection-changed
1399 (eq last-command 'company-complete-common))
1400 (call-interactively 'company-complete-selection)
1401 (call-interactively 'company-complete-common)
1402 (setq this-command 'company-complete-common))))
1403
1404 (defun company-complete-number (n)
1405 "Complete the Nth candidate.
1406 To show the number next to the candidates in some back-ends, enable
1407 `company-show-numbers'."
1408 (when (company-manual-begin)
1409 (and (< n 1) (> n company-candidates-length)
1410 (error "No candidate number %d" n))
1411 (decf n)
1412 (company-finish (nth n company-candidates))))
1413
1414 ;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;
1415
1416 (defconst company-space-strings-limit 100)
1417
1418 (defconst company-space-strings
1419 (let (lst)
1420 (dotimes (i company-space-strings-limit)
1421 (push (make-string (- company-space-strings-limit 1 i) ?\ ) lst))
1422 (apply 'vector lst)))
1423
1424 (defsubst company-space-string (len)
1425 (if (< len company-space-strings-limit)
1426 (aref company-space-strings len)
1427 (make-string len ?\ )))
1428
1429 (defsubst company-safe-substring (str from &optional to)
1430 (if (> from (string-width str))
1431 ""
1432 (with-temp-buffer
1433 (insert str)
1434 (move-to-column from)
1435 (let ((beg (point)))
1436 (if to
1437 (progn
1438 (move-to-column to)
1439 (concat (buffer-substring beg (point))
1440 (let ((padding (- to (current-column))))
1441 (when (> padding 0)
1442 (company-space-string padding)))))
1443 (buffer-substring beg (point-max)))))))
1444
1445 ;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;
1446
1447 (defvar company-last-metadata nil)
1448 (make-variable-buffer-local 'company-last-metadata)
1449
1450 (defun company-fetch-metadata ()
1451 (let ((selected (nth company-selection company-candidates)))
1452 (unless (equal selected (car company-last-metadata))
1453 (setq company-last-metadata
1454 (cons selected (company-call-backend 'meta selected))))
1455 (cdr company-last-metadata)))
1456
1457 (defun company-doc-buffer (&optional string)
1458 (with-current-buffer (get-buffer-create "*Company meta-data*")
1459 (erase-buffer)
1460 (current-buffer)))
1461
1462 (defvar company--electric-commands
1463 '(scroll-other-window scroll-other-window-down)
1464 "List of Commands that won't break out of electric commands.")
1465
1466 (defmacro company--electric-do (&rest body)
1467 (declare (indent 0) (debug t))
1468 `(when (company-manual-begin)
1469 (save-window-excursion
1470 (let ((height (window-height))
1471 (row (company--row))
1472 cmd)
1473 ,@body
1474 (and (< (window-height) height)
1475 (< (- (window-height) row 2) company-tooltip-limit)
1476 (recenter (- (window-height) row 2)))
1477 (while (memq (setq cmd (key-binding (vector (list (read-event)))))
1478 company--electric-commands)
1479 (call-interactively cmd))
1480 (company--unread-last-input)))))
1481
1482 (defun company--unread-last-input ()
1483 (when last-input-event
1484 (clear-this-command-keys t)
1485 (setq unread-command-events (list last-input-event))))
1486
1487 (defun company-show-doc-buffer ()
1488 "Temporarily show a buffer with the complete documentation for the selection."
1489 (interactive)
1490 (company--electric-do
1491 (let* ((selected (nth company-selection company-candidates))
1492 (doc-buffer (or (company-call-backend 'doc-buffer selected)
1493 (error "No documentation available"))))
1494 (with-current-buffer doc-buffer
1495 (goto-char (point-min)))
1496 (display-buffer doc-buffer t))))
1497 (put 'company-show-doc-buffer 'company-keep t)
1498
1499 (defun company-show-location ()
1500 "Temporarily display a buffer showing the selected candidate in context."
1501 (interactive)
1502 (company--electric-do
1503 (let* ((selected (nth company-selection company-candidates))
1504 (location (company-call-backend 'location selected))
1505 (pos (or (cdr location) (error "No location available")))
1506 (buffer (or (and (bufferp (car location)) (car location))
1507 (find-file-noselect (car location) t))))
1508 (with-selected-window (display-buffer buffer t)
1509 (save-restriction
1510 (widen)
1511 (if (bufferp (car location))
1512 (goto-char pos)
1513 (goto-char (point-min))
1514 (forward-line (1- pos))))
1515 (set-window-start nil (point))))))
1516 (put 'company-show-location 'company-keep t)
1517
1518 ;;; package functions ;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;
1519
1520 (defvar company-callback nil)
1521 (make-variable-buffer-local 'company-callback)
1522
1523 (defvar company-begin-with-marker nil)
1524 (make-variable-buffer-local 'company-begin-with-marker)
1525
1526 (defun company-remove-callback (&optional ignored)
1527 (remove-hook 'company-completion-finished-hook company-callback t)
1528 (remove-hook 'company-completion-cancelled-hook 'company-remove-callback t)
1529 (remove-hook 'company-completion-finished-hook 'company-remove-callback t)
1530 (when company-begin-with-marker
1531 (set-marker company-begin-with-marker nil)))
1532
1533 (defun company-begin-backend (backend &optional callback)
1534 "Start a completion at point using BACKEND."
1535 (interactive (let ((val (completing-read "Company back-end: "
1536 obarray
1537 'functionp nil "company-")))
1538 (when val
1539 (list (intern val)))))
1540 (when (setq company-callback callback)
1541 (add-hook 'company-completion-finished-hook company-callback nil t))
1542 (add-hook 'company-completion-cancelled-hook 'company-remove-callback nil t)
1543 (add-hook 'company-completion-finished-hook 'company-remove-callback nil t)
1544 (setq company-backend backend)
1545 ;; Return non-nil if active.
1546 (or (company-manual-begin)
1547 (progn
1548 (setq company-backend nil)
1549 (error "Cannot complete at point"))))
1550
1551 (defun company-begin-with (candidates
1552 &optional prefix-length require-match callback)
1553 "Start a completion at point.
1554 CANDIDATES is the list of candidates to use and PREFIX-LENGTH is the length of
1555 the prefix that already is in the buffer before point. It defaults to 0.
1556
1557 CALLBACK is a function called with the selected result if the user successfully
1558 completes the input.
1559
1560 Example:
1561 \(company-begin-with '\(\"foo\" \"foobar\" \"foobarbaz\"\)\)"
1562 (setq company-begin-with-marker (copy-marker (point) t))
1563 (company-begin-backend
1564 `(lambda (command &optional arg &rest ignored)
1565 (cond
1566 ((eq command 'prefix)
1567 (when (equal (point) (marker-position company-begin-with-marker))
1568 (buffer-substring ,(- (point) (or prefix-length 0)) (point))))
1569 ((eq command 'candidates)
1570 (all-completions arg ',candidates))
1571 ((eq command 'require-match)
1572 ,require-match)))
1573 callback))
1574
1575 ;;; pseudo-tooltip ;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;
1576
1577 (defvar company-pseudo-tooltip-overlay nil)
1578 (make-variable-buffer-local 'company-pseudo-tooltip-overlay)
1579
1580 (defvar company-tooltip-offset 0)
1581 (make-variable-buffer-local 'company-tooltip-offset)
1582
1583 (defun company-pseudo-tooltip-update-offset (selection num-lines limit)
1584
1585 (decf limit 2)
1586 (setq company-tooltip-offset
1587 (max (min selection company-tooltip-offset)
1588 (- selection -1 limit)))
1589
1590 (when (<= company-tooltip-offset 1)
1591 (incf limit)
1592 (setq company-tooltip-offset 0))
1593
1594 (when (>= company-tooltip-offset (- num-lines limit 1))
1595 (incf limit)
1596 (when (= selection (1- num-lines))
1597 (decf company-tooltip-offset)
1598 (when (<= company-tooltip-offset 1)
1599 (setq company-tooltip-offset 0)
1600 (incf limit))))
1601
1602 limit)
1603
1604 ;;; propertize
1605
1606 (defsubst company-round-tab (arg)
1607 (* (/ (+ arg tab-width) tab-width) tab-width))
1608
1609 (defun company-untabify (str)
1610 (let* ((pieces (split-string str "\t"))
1611 (copy pieces))
1612 (while (cdr copy)
1613 (setcar copy (company-safe-substring
1614 (car copy) 0 (company-round-tab (string-width (car copy)))))
1615 (pop copy))
1616 (apply 'concat pieces)))
1617
1618 (defun company-fill-propertize (line width selected)
1619 (setq line (company-safe-substring line 0 width))
1620 (add-text-properties 0 width '(face company-tooltip
1621 mouse-face company-tooltip-mouse)
1622 line)
1623 (add-text-properties 0 (length company-common)
1624 '(face company-tooltip-common
1625 mouse-face company-tooltip-mouse)
1626 line)
1627 (when selected
1628 (if (and company-search-string
1629 (string-match (regexp-quote company-search-string) line
1630 (length company-prefix)))
1631 (progn
1632 (add-text-properties (match-beginning 0) (match-end 0)
1633 '(face company-tooltip-selection)
1634 line)
1635 (when (< (match-beginning 0) (length company-common))
1636 (add-text-properties (match-beginning 0) (length company-common)
1637 '(face company-tooltip-common-selection)
1638 line)))
1639 (add-text-properties 0 width '(face company-tooltip-selection
1640 mouse-face company-tooltip-selection)
1641 line)
1642 (add-text-properties 0 (length company-common)
1643 '(face company-tooltip-common-selection
1644 mouse-face company-tooltip-selection)
1645 line)))
1646 line)
1647
1648 ;;; replace
1649
1650 (defun company-buffer-lines (beg end)
1651 (goto-char beg)
1652 (let (lines)
1653 (while (and (= 1 (vertical-motion 1))
1654 (<= (point) end))
1655 (push (buffer-substring beg (min end (1- (point)))) lines)
1656 (setq beg (point)))
1657 (unless (eq beg end)
1658 (push (buffer-substring beg end) lines))
1659 (nreverse lines)))
1660
1661 (defsubst company-modify-line (old new offset)
1662 (concat (company-safe-substring old 0 offset)
1663 new
1664 (company-safe-substring old (+ offset (length new)))))
1665
1666 (defsubst company--length-limit (lst limit)
1667 (if (nthcdr limit lst)
1668 limit
1669 (length lst)))
1670
1671 (defun company--replacement-string (lines old column nl &optional align-top)
1672
1673 (let ((width (length (car lines))))
1674 (when (> width (- (window-width) column))
1675 (setq column (max 0 (- (window-width) width)))))
1676
1677 (let (new)
1678 (when align-top
1679 ;; untouched lines first
1680 (dotimes (i (- (length old) (length lines)))
1681 (push (pop old) new)))
1682 ;; length into old lines.
1683 (while old
1684 (push (company-modify-line (pop old) (pop lines) column) new))
1685 ;; Append whole new lines.
1686 (while lines
1687 (push (concat (company-space-string column) (pop lines)) new))
1688
1689 (let ((str (concat (when nl "\n")
1690 (mapconcat 'identity (nreverse new) "\n")
1691 "\n")))
1692 (font-lock-append-text-property 0 (length str) 'face 'default str)
1693 str)))
1694
1695 (defun company--create-lines (selection limit)
1696
1697 (let ((len company-candidates-length)
1698 (numbered 99999)
1699 lines
1700 width
1701 lines-copy
1702 previous
1703 remainder
1704 new)
1705
1706 ;; Scroll to offset.
1707 (setq limit (company-pseudo-tooltip-update-offset selection len limit))
1708
1709 (when (> company-tooltip-offset 0)
1710 (setq previous (format "...(%d)" company-tooltip-offset)))
1711
1712 (setq remainder (- len limit company-tooltip-offset)
1713 remainder (when (> remainder 0)
1714 (setq remainder (format "...(%d)" remainder))))
1715
1716 (decf selection company-tooltip-offset)
1717 (setq width (max (length previous) (length remainder))
1718 lines (nthcdr company-tooltip-offset company-candidates)
1719 len (min limit len)
1720 lines-copy lines)
1721
1722 (dotimes (i len)
1723 (setq width (max (length (pop lines-copy)) width)))
1724 (setq width (min width (window-width)))
1725
1726 (setq lines-copy lines)
1727
1728 ;; number can make tooltip too long
1729 (when company-show-numbers
1730 (setq numbered company-tooltip-offset))
1731
1732 (when previous
1733 (push (propertize (company-safe-substring previous 0 width)
1734 'face 'company-tooltip)
1735 new))
1736
1737 (dotimes (i len)
1738 (push (company-fill-propertize
1739 (if (>= numbered 10)
1740 (company-reformat (pop lines))
1741 (incf numbered)
1742 (format "%s %d"
1743 (company-safe-substring (company-reformat (pop lines))
1744 0 (- width 2))
1745 (mod numbered 10)))
1746 width (equal i selection))
1747 new))
1748
1749 (when remainder
1750 (push (propertize (company-safe-substring remainder 0 width)
1751 'face 'company-tooltip)
1752 new))
1753
1754 (setq lines (nreverse new))))
1755
1756 ;; show
1757
1758 (defsubst company--window-inner-height ()
1759 (let ((edges (window-inside-edges (selected-window))))
1760 (- (nth 3 edges) (nth 1 edges))))
1761
1762 (defsubst company--pseudo-tooltip-height ()
1763 "Calculate the appropriate tooltip height.
1764 Returns a negative number if the tooltip should be displayed above point."
1765 (let* ((lines (company--row))
1766 (below (- (company--window-inner-height) 1 lines)))
1767 (if (and (< below (min company-tooltip-minimum company-candidates-length))
1768 (> lines below))
1769 (- (max 3 (min company-tooltip-limit lines)))
1770 (max 3 (min company-tooltip-limit below)))))
1771
1772 (defun company-pseudo-tooltip-show (row column selection)
1773 (company-pseudo-tooltip-hide)
1774 (save-excursion
1775
1776 (move-to-column 0)
1777
1778 (let* ((height (company--pseudo-tooltip-height))
1779 above)
1780
1781 (when (< height 0)
1782 (setq row (+ row height -1)
1783 above t))
1784
1785 (let* ((nl (< (move-to-window-line row) row))
1786 (beg (point))
1787 (end (save-excursion
1788 (move-to-window-line (+ row (abs height)))
1789 (point)))
1790 (ov (make-overlay beg end))
1791 (args (list (mapcar 'company-untabify
1792 (company-buffer-lines beg end))
1793 column nl above)))
1794
1795 (setq company-pseudo-tooltip-overlay ov)
1796 (overlay-put ov 'company-replacement-args args)
1797 (overlay-put ov 'company-before
1798 (apply 'company--replacement-string
1799 (company--create-lines selection (abs height))
1800 args))
1801
1802 (overlay-put ov 'company-column column)
1803 (overlay-put ov 'company-height height)))))
1804
1805 (defun company-pseudo-tooltip-show-at-point (pos)
1806 (let ((col-row (company--col-row pos)))
1807 (when col-row
1808 (company-pseudo-tooltip-show (1+ (cdr col-row)) (car col-row)
1809 company-selection))))
1810
1811 (defun company-pseudo-tooltip-edit (lines selection)
1812 (let ((column (overlay-get company-pseudo-tooltip-overlay 'company-column))
1813 (height (overlay-get company-pseudo-tooltip-overlay 'company-height)))
1814 (overlay-put company-pseudo-tooltip-overlay 'company-before
1815 (apply 'company--replacement-string
1816 (company--create-lines selection (abs height))
1817 (overlay-get company-pseudo-tooltip-overlay
1818 'company-replacement-args)))))
1819
1820 (defun company-pseudo-tooltip-hide ()
1821 (when company-pseudo-tooltip-overlay
1822 (delete-overlay company-pseudo-tooltip-overlay)
1823 (setq company-pseudo-tooltip-overlay nil)))
1824
1825 (defun company-pseudo-tooltip-hide-temporarily ()
1826 (when (overlayp company-pseudo-tooltip-overlay)
1827 (overlay-put company-pseudo-tooltip-overlay 'invisible nil)
1828 (overlay-put company-pseudo-tooltip-overlay 'before-string nil)))
1829
1830 (defun company-pseudo-tooltip-unhide ()
1831 (when company-pseudo-tooltip-overlay
1832 (overlay-put company-pseudo-tooltip-overlay 'invisible t)
1833 (overlay-put company-pseudo-tooltip-overlay 'before-string
1834 (overlay-get company-pseudo-tooltip-overlay 'company-before))
1835 (overlay-put company-pseudo-tooltip-overlay 'window (selected-window))))
1836
1837 (defun company-pseudo-tooltip-guard ()
1838 (buffer-substring-no-properties
1839 (point) (overlay-start company-pseudo-tooltip-overlay)))
1840
1841 (defun company-pseudo-tooltip-frontend (command)
1842 "A `company-mode' front-end similar to a tool-tip but based on overlays."
1843 (case command
1844 (pre-command (company-pseudo-tooltip-hide-temporarily))
1845 (post-command
1846 (let ((old-height (if (overlayp company-pseudo-tooltip-overlay)
1847 (overlay-get company-pseudo-tooltip-overlay
1848 'company-height)
1849 0))
1850 (new-height (company--pseudo-tooltip-height)))
1851 (unless (and (>= (* old-height new-height) 0)
1852 (>= (abs old-height) (abs new-height))
1853 (equal (company-pseudo-tooltip-guard)
1854 (overlay-get company-pseudo-tooltip-overlay
1855 'company-guard)))
1856 ;; Redraw needed.
1857 (company-pseudo-tooltip-show-at-point (- (point)
1858 (length company-prefix)))
1859 (overlay-put company-pseudo-tooltip-overlay
1860 'company-guard (company-pseudo-tooltip-guard))))
1861 (company-pseudo-tooltip-unhide))
1862 (hide (company-pseudo-tooltip-hide)
1863 (setq company-tooltip-offset 0))
1864 (update (when (overlayp company-pseudo-tooltip-overlay)
1865 (company-pseudo-tooltip-edit company-candidates
1866 company-selection)))))
1867
1868 (defun company-pseudo-tooltip-unless-just-one-frontend (command)
1869 "`company-pseudo-tooltip-frontend', but not shown for single candidates."
1870 (unless (and (eq command 'post-command)
1871 (not (cdr company-candidates)))
1872 (company-pseudo-tooltip-frontend command)))
1873
1874 ;;; overlay ;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;
1875
1876 (defvar company-preview-overlay nil)
1877 (make-variable-buffer-local 'company-preview-overlay)
1878
1879 (defun company-preview-show-at-point (pos)
1880 (company-preview-hide)
1881
1882 (setq company-preview-overlay (make-overlay pos pos))
1883
1884 (let ((completion(nth company-selection company-candidates)))
1885 (setq completion (propertize completion 'face 'company-preview))
1886 (add-text-properties 0 (length company-common)
1887 '(face company-preview-common) completion)
1888
1889 ;; Add search string
1890 (and company-search-string
1891 (string-match (regexp-quote company-search-string) completion)
1892 (add-text-properties (match-beginning 0)
1893 (match-end 0)
1894 '(face company-preview-search)
1895 completion))
1896
1897 (setq completion (company-strip-prefix completion))
1898
1899 (and (equal pos (point))
1900 (not (equal completion ""))
1901 (add-text-properties 0 1 '(cursor t) completion))
1902
1903 (overlay-put company-preview-overlay 'after-string completion)
1904 (overlay-put company-preview-overlay 'window (selected-window))))
1905
1906 (defun company-preview-hide ()
1907 (when company-preview-overlay
1908 (delete-overlay company-preview-overlay)
1909 (setq company-preview-overlay nil)))
1910
1911 (defun company-preview-frontend (command)
1912 "A `company-mode' front-end showing the selection as if it had been inserted."
1913 (case command
1914 (pre-command (company-preview-hide))
1915 (post-command (company-preview-show-at-point (point)))
1916 (hide (company-preview-hide))))
1917
1918 (defun company-preview-if-just-one-frontend (command)
1919 "`company-preview-frontend', but only shown for single candidates."
1920 (unless (and (eq command 'post-command)
1921 (cdr company-candidates))
1922 (company-preview-frontend command)))
1923
1924 ;;; echo ;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;
1925
1926 (defvar company-echo-last-msg nil)
1927 (make-variable-buffer-local 'company-echo-last-msg)
1928
1929 (defvar company-echo-timer nil)
1930
1931 (defvar company-echo-delay .01)
1932
1933 (defun company-echo-show (&optional getter)
1934 (when getter
1935 (setq company-echo-last-msg (funcall getter)))
1936 (let ((message-log-max nil))
1937 (if company-echo-last-msg
1938 (message "%s" company-echo-last-msg)
1939 (message ""))))
1940
1941 (defsubst company-echo-show-soon (&optional getter)
1942 (when company-echo-timer
1943 (cancel-timer company-echo-timer))
1944 (setq company-echo-timer (run-with-timer 0 nil 'company-echo-show getter)))
1945
1946 (defsubst company-echo-show-when-idle (&optional getter)
1947 (when (sit-for .01)
1948 (company-echo-show getter)))
1949
1950 (defsubst company-echo-show-when-not-busy (&optional getter)
1951 "Run `company-echo-show' with arg GETTER once Emacs isn't busy."
1952 (when (sit-for company-echo-delay)
1953 (company-echo-show getter)))
1954
1955 (defun company-echo-format ()
1956
1957 (let ((limit (window-width (minibuffer-window)))
1958 (len -1)
1959 ;; Roll to selection.
1960 (candidates (nthcdr company-selection company-candidates))
1961 (i (if company-show-numbers company-selection 99999))
1962 comp msg)
1963
1964 (while candidates
1965 (setq comp (company-reformat (pop candidates))
1966 len (+ len 1 (length comp)))
1967 (if (< i 10)
1968 ;; Add number.
1969 (progn
1970 (setq comp (propertize (format "%d: %s" i comp)
1971 'face 'company-echo))
1972 (incf len 3)
1973 (incf i)
1974 (add-text-properties 3 (+ 3 (length company-common))
1975 '(face company-echo-common) comp))
1976 (setq comp (propertize comp 'face 'company-echo))
1977 (add-text-properties 0 (length company-common)
1978 '(face company-echo-common) comp))
1979 (if (>= len limit)
1980 (setq candidates nil)
1981 (push comp msg)))
1982
1983 (mapconcat 'identity (nreverse msg) " ")))
1984
1985 (defun company-echo-strip-common-format ()
1986
1987 (let ((limit (window-width (minibuffer-window)))
1988 (len (+ (length company-prefix) 2))
1989 ;; Roll to selection.
1990 (candidates (nthcdr company-selection company-candidates))
1991 (i (if company-show-numbers company-selection 99999))
1992 msg comp)
1993
1994 (while candidates
1995 (setq comp (company-strip-prefix (pop candidates))
1996 len (+ len 2 (length comp)))
1997 (when (< i 10)
1998 ;; Add number.
1999 (setq comp (format "%s (%d)" comp i))
2000 (incf len 4)
2001 (incf i))
2002 (if (>= len limit)
2003 (setq candidates nil)
2004 (push (propertize comp 'face 'company-echo) msg)))
2005
2006 (concat (propertize company-prefix 'face 'company-echo-common) "{"
2007 (mapconcat 'identity (nreverse msg) ", ")
2008 "}")))
2009
2010 (defun company-echo-hide ()
2011 (unless (equal company-echo-last-msg "")
2012 (setq company-echo-last-msg "")
2013 (company-echo-show)))
2014
2015 (defun company-echo-frontend (command)
2016 "A `company-mode' front-end showing the candidates in the echo area."
2017 (case command
2018 (post-command (company-echo-show-soon 'company-echo-format))
2019 (hide (company-echo-hide))))
2020
2021 (defun company-echo-strip-common-frontend (command)
2022 "A `company-mode' front-end showing the candidates in the echo area."
2023 (case command
2024 (post-command (company-echo-show-soon 'company-echo-strip-common-format))
2025 (hide (company-echo-hide))))
2026
2027 (defun company-echo-metadata-frontend (command)
2028 "A `company-mode' front-end showing the documentation in the echo area."
2029 (case command
2030 (post-command (company-echo-show-when-idle 'company-fetch-metadata))
2031 (hide (company-echo-hide))))
2032
2033 (provide 'company)
2034 ;;; company.el ends here