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