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