]> code.delx.au - gnu-emacs-elpa/blob - company.el
company-complete-number: Make interactive, read the pressed digit
[gnu-emacs-elpa] / company.el
1 ;;; company.el --- Modular text completion framework -*- lexical-binding: t -*-
2
3 ;; Copyright (C) 2009-2014 Free Software Foundation, Inc.
4
5 ;; Author: Nikolaj Schumacher
6 ;; Maintainer: Dmitry Gutov <dgutov@yandex.ru>
7 ;; URL: http://company-mode.github.io/
8 ;; Version: 0.8.4-cvs
9 ;; Keywords: abbrev, convenience, matching
10 ;; Package-Requires: ((emacs "24.1") (cl-lib "0.5"))
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 ;; (pcase 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 ;;; Change Log:
62 ;;
63 ;; See NEWS.md in the repository.
64
65 ;;; Code:
66
67 (require 'cl-lib)
68 (require 'newcomment)
69
70 ;; FIXME: Use `user-error'.
71 (add-to-list 'debug-ignored-errors "^.* frontend cannot be used twice$")
72 (add-to-list 'debug-ignored-errors "^Echo area cannot be used twice$")
73 (add-to-list 'debug-ignored-errors "^No \\(document\\|loc\\)ation available$")
74 (add-to-list 'debug-ignored-errors "^Company not ")
75 (add-to-list 'debug-ignored-errors "^No candidate number ")
76 (add-to-list 'debug-ignored-errors "^Cannot complete at point$")
77 (add-to-list 'debug-ignored-errors "^No other back-end$")
78
79 ;;; Compatibility
80 (eval-and-compile
81 ;; `defvar-local' for Emacs 24.2 and below
82 (unless (fboundp 'defvar-local)
83 (defmacro defvar-local (var val &optional docstring)
84 "Define VAR as a buffer-local variable with default value VAL.
85 Like `defvar' but additionally marks the variable as being automatically
86 buffer-local wherever it is set."
87 (declare (debug defvar) (doc-string 3))
88 `(progn
89 (defvar ,var ,val ,docstring)
90 (make-variable-buffer-local ',var)))))
91
92 (defgroup company nil
93 "Extensible inline text completion mechanism"
94 :group 'abbrev
95 :group 'convenience
96 :group 'matching)
97
98 (defface company-tooltip
99 '((default :foreground "black")
100 (((class color) (min-colors 88) (background light))
101 (:background "cornsilk"))
102 (((class color) (min-colors 88) (background dark))
103 (:background "yellow")))
104 "Face used for the tooltip.")
105
106 (defface company-tooltip-selection
107 '((default :inherit company-tooltip)
108 (((class color) (min-colors 88) (background light))
109 (:background "light blue"))
110 (((class color) (min-colors 88) (background dark))
111 (:background "orange1"))
112 (t (:background "green")))
113 "Face used for the selection in the tooltip.")
114
115 (defface company-tooltip-search
116 '((default :inherit company-tooltip-selection))
117 "Face used for the search string in the tooltip.")
118
119 (defface company-tooltip-mouse
120 '((default :inherit highlight))
121 "Face used for the tooltip item under the mouse.")
122
123 (defface company-tooltip-common
124 '((default :inherit company-tooltip)
125 (((background light))
126 :foreground "darkred")
127 (((background dark))
128 :foreground "red"))
129 "Face used for the common completion in the tooltip.")
130
131 (defface company-tooltip-common-selection
132 '((default :inherit company-tooltip-selection)
133 (((background light))
134 :foreground "darkred")
135 (((background dark))
136 :foreground "red"))
137 "Face used for the selected common completion in the tooltip.")
138
139 (defface company-tooltip-annotation
140 '((default :inherit company-tooltip)
141 (((background light))
142 :foreground "firebrick4")
143 (((background dark))
144 :foreground "red4"))
145 "Face used for the annotation in the tooltip.")
146
147 (defface company-scrollbar-fg
148 '((((background light))
149 :background "darkred")
150 (((background dark))
151 :background "red"))
152 "Face used for the tooltip scrollbar thumb.")
153
154 (defface company-scrollbar-bg
155 '((default :inherit company-tooltip)
156 (((background light))
157 :background "wheat")
158 (((background dark))
159 :background "gold"))
160 "Face used for the tooltip scrollbar background.")
161
162 (defface company-preview
163 '((((background light))
164 :inherit company-tooltip-selection)
165 (((background dark))
166 :background "blue4"
167 :foreground "wheat"))
168 "Face used for the completion preview.")
169
170 (defface company-preview-common
171 '((((background light))
172 :inherit company-tooltip-selection)
173 (((background dark))
174 :inherit company-preview
175 :foreground "red"))
176 "Face used for the common part of the completion preview.")
177
178 (defface company-preview-search
179 '((((background light))
180 :inherit company-tooltip-common-selection)
181 (((background dark))
182 :inherit company-preview
183 :background "blue1"))
184 "Face used for the search string in the completion preview.")
185
186 (defface company-echo nil
187 "Face used for completions in the echo area.")
188
189 (defface company-echo-common
190 '((((background dark)) (:foreground "firebrick1"))
191 (((background light)) (:background "firebrick4")))
192 "Face used for the common part of completions in the echo area.")
193
194 (defun company-frontends-set (variable value)
195 ;; Uniquify.
196 (let ((value (delete-dups (copy-sequence value))))
197 (and (memq 'company-pseudo-tooltip-unless-just-one-frontend value)
198 (memq 'company-pseudo-tooltip-frontend value)
199 (error "Pseudo tooltip frontend cannot be used twice"))
200 (and (memq 'company-preview-if-just-one-frontend value)
201 (memq 'company-preview-frontend value)
202 (error "Preview frontend cannot be used twice"))
203 (and (memq 'company-echo value)
204 (memq 'company-echo-metadata-frontend value)
205 (error "Echo area cannot be used twice"))
206 ;; Preview must come last.
207 (dolist (f '(company-preview-if-just-one-frontend company-preview-frontend))
208 (when (cdr (memq f value))
209 (setq value (append (delq f value) (list f)))))
210 (set variable value)))
211
212 (defcustom company-frontends '(company-pseudo-tooltip-unless-just-one-frontend
213 company-preview-if-just-one-frontend
214 company-echo-metadata-frontend)
215 "The list of active front-ends (visualizations).
216 Each front-end is a function that takes one argument. It is called with
217 one of the following arguments:
218
219 `show': When the visualization should start.
220
221 `hide': When the visualization should end.
222
223 `update': When the data has been updated.
224
225 `pre-command': Before every command that is executed while the
226 visualization is active.
227
228 `post-command': After every command that is executed while the
229 visualization is active.
230
231 The visualized data is stored in `company-prefix', `company-candidates',
232 `company-common', `company-selection', `company-point' and
233 `company-search-string'."
234 :set 'company-frontends-set
235 :type '(repeat (choice (const :tag "echo" company-echo-frontend)
236 (const :tag "echo, strip common"
237 company-echo-strip-common-frontend)
238 (const :tag "show echo meta-data in echo"
239 company-echo-metadata-frontend)
240 (const :tag "pseudo tooltip"
241 company-pseudo-tooltip-frontend)
242 (const :tag "pseudo tooltip, multiple only"
243 company-pseudo-tooltip-unless-just-one-frontend)
244 (const :tag "preview" company-preview-frontend)
245 (const :tag "preview, unique only"
246 company-preview-if-just-one-frontend)
247 (function :tag "custom function" nil))))
248
249 (defcustom company-tooltip-limit 10
250 "The maximum number of candidates in the tooltip."
251 :type 'integer)
252
253 (defcustom company-tooltip-minimum 6
254 "The minimum height of the tooltip.
255 If this many lines are not available, prefer to display the tooltip above."
256 :type 'integer)
257
258 (defcustom company-tooltip-minimum-width 0
259 "The minimum width of the tooltip's inner area.
260 This doesn't include the margins and the scroll bar."
261 :type 'integer
262 :package-version '(company . "0.8.0"))
263
264 (defcustom company-tooltip-margin 1
265 "Width of margin columns to show around the toolip."
266 :type 'integer)
267
268 (defcustom company-tooltip-offset-display 'scrollbar
269 "Method using which the tooltip displays scrolling position.
270 `scrollbar' means draw a scrollbar to the right of the items.
271 `lines' means wrap items in lines with \"before\" and \"after\" counters."
272 :type '(choice (const :tag "Scrollbar" scrollbar)
273 (const :tag "Two lines" lines)))
274
275 (defcustom company-tooltip-align-annotations nil
276 "When non-nil, align annotations to the right tooltip border."
277 :type 'boolean
278 :package-version '(company . "0.7.1"))
279
280 (defcustom company-tooltip-flip-when-above nil
281 "Whether to flip the tooltip when it's above the current line."
282 :type 'boolean
283 :package-version '(company . "0.8.1"))
284
285 (defvar company-safe-backends
286 '((company-abbrev . "Abbrev")
287 (company-bbdb . "BBDB")
288 (company-capf . "completion-at-point-functions")
289 (company-clang . "Clang")
290 (company-cmake . "CMake")
291 (company-css . "CSS")
292 (company-dabbrev . "dabbrev for plain text")
293 (company-dabbrev-code . "dabbrev for code")
294 (company-eclim . "Eclim (an Eclipse interface)")
295 (company-elisp . "Emacs Lisp")
296 (company-etags . "etags")
297 (company-files . "Files")
298 (company-gtags . "GNU Global")
299 (company-ispell . "Ispell")
300 (company-keywords . "Programming language keywords")
301 (company-nxml . "nxml")
302 (company-oddmuse . "Oddmuse")
303 (company-pysmell . "PySmell")
304 (company-ropemacs . "ropemacs")
305 (company-semantic . "Semantic")
306 (company-tempo . "Tempo templates")
307 (company-xcode . "Xcode")))
308 (put 'company-safe-backends 'risky-local-variable t)
309
310 (defun company-safe-backends-p (backends)
311 (and (consp backends)
312 (not (cl-dolist (backend backends)
313 (unless (if (consp backend)
314 (company-safe-backends-p backend)
315 (assq backend company-safe-backends))
316 (cl-return t))))))
317
318 (defcustom company-backends `(,@(unless (version< "24.3.50" emacs-version)
319 (list 'company-elisp))
320 company-bbdb
321 company-nxml company-css
322 company-eclim company-semantic company-clang
323 company-xcode company-ropemacs company-cmake
324 company-capf
325 (company-dabbrev-code company-gtags company-etags
326 company-keywords)
327 company-oddmuse company-files company-dabbrev)
328 "The list of active back-ends (completion engines).
329
330 Only one back-end is used at a time. The choice depends on the order of
331 the items in this list, and on the values they return in response to the
332 `prefix' command (see below). But a back-end can also be a \"grouped\"
333 one (see below).
334
335 `company-begin-backend' can be used to start a specific back-end,
336 `company-other-backend' will skip to the next matching back-end in the list.
337
338 Each back-end is a function that takes a variable number of arguments.
339 The first argument is the command requested from the back-end. It is one
340 of the following:
341
342 `prefix': The back-end should return the text to be completed. It must be
343 text immediately before point. Returning nil passes control to the next
344 back-end. The function should return `stop' if it should complete but
345 cannot (e.g. if it is in the middle of a string). Instead of a string,
346 the back-end may return a cons where car is the prefix and cdr is used in
347 `company-minimum-prefix-length' test. It must be either number or t, and
348 in the latter case the test automatically succeeds.
349
350 `candidates': The second argument is the prefix to be completed. The
351 return value should be a list of candidates that match the prefix.
352
353 Non-prefix matches are also supported (candidates that don't start with the
354 prefix, but match it in some backend-defined way). Backends that use this
355 feature must disable cache (return t to `no-cache') and should also respond
356 to `match'.
357
358 Optional commands:
359
360 `sorted': Return t here to indicate that the candidates are sorted and will
361 not need to be sorted again.
362
363 `duplicates': If non-nil, company will take care of removing duplicates
364 from the list.
365
366 `no-cache': Usually company doesn't ask for candidates again as completion
367 progresses, unless the back-end returns t for this command. The second
368 argument is the latest prefix.
369
370 `meta': The second argument is a completion candidate. Return a (short)
371 documentation string for it.
372
373 `doc-buffer': The second argument is a completion candidate. Return a
374 buffer with documentation for it. Preferably use `company-doc-buffer',
375
376 `location': The second argument is a completion candidate. Return the cons
377 of buffer and buffer location, or of file and line number where the
378 completion candidate was defined.
379
380 `annotation': The second argument is a completion candidate. Return a
381 string to be displayed inline with the candidate in the popup. If
382 duplicates are removed by company, candidates with equal string values will
383 be kept if they have different annotations. For that to work properly,
384 backends should store the related information on candidates using text
385 properties.
386
387 `match': The second argument is a completion candidate. Backends that
388 provide non-prefix completions should return the position of the end of
389 text in the candidate that matches `prefix'. It will be used when
390 rendering the popup.
391
392 `require-match': If this returns t, the user is not allowed to enter
393 anything not offered as a candidate. Use with care! The default value nil
394 gives the user that choice with `company-require-match'. Return value
395 `never' overrides that option the other way around.
396
397 `init': Called once for each buffer. The back-end can check for external
398 programs and files and load any required libraries. Raising an error here
399 will show up in message log once, and the back-end will not be used for
400 completion.
401
402 `post-completion': Called after a completion candidate has been inserted
403 into the buffer. The second argument is the candidate. Can be used to
404 modify it, e.g. to expand a snippet.
405
406 The back-end should return nil for all commands it does not support or
407 does not know about. It should also be callable interactively and use
408 `company-begin-backend' to start itself in that case.
409
410 Grouped back-ends:
411
412 An element of `company-backends' can also itself be a list of back-ends,
413 then it's considered to be a \"grouped\" back-end.
414
415 When possible, commands taking a candidate as an argument are dispatched to
416 the back-end it came from. In other cases, the first non-nil value among
417 all the back-ends is returned.
418
419 The latter is the case for the `prefix' command. But if the group contains
420 the keyword `:with', the back-ends after it are ignored for this command.
421
422 The completions from back-ends in a group are merged (but only from those
423 that return the same `prefix').
424
425 Asynchronous back-ends:
426
427 The return value of each command can also be a cons (:async . FETCHER)
428 where FETCHER is a function of one argument, CALLBACK. When the data
429 arrives, FETCHER must call CALLBACK and pass it the appropriate return
430 value, as described above.
431
432 True asynchronous operation is only supported for command `candidates', and
433 only during idle completion. Other commands will block the user interface,
434 even if the back-end uses the asynchronous calling convention."
435 :type `(repeat
436 (choice
437 :tag "Back-end"
438 ,@(mapcar (lambda (b) `(const :tag ,(cdr b) ,(car b)))
439 company-safe-backends)
440 (symbol :tag "User defined")
441 (repeat :tag "Merged Back-ends"
442 (choice :tag "Back-end"
443 ,@(mapcar (lambda (b)
444 `(const :tag ,(cdr b) ,(car b)))
445 company-safe-backends)
446 (const :tag "With" :with)
447 (symbol :tag "User defined"))))))
448
449 (put 'company-backends 'safe-local-variable 'company-safe-backends-p)
450
451 (defcustom company-transformers nil
452 "Functions to change the list of candidates received from backends,
453 after sorting and removal of duplicates (if appropriate).
454 Each function gets called with the return value of the previous one."
455 :type '(choice
456 (const :tag "None" nil)
457 (const :tag "Sort by occurrence" (company-sort-by-occurrence))
458 (const :tag "Sort by back-end importance"
459 (company-sort-by-backend-importance))
460 (repeat :tag "User defined" (function))))
461
462 (defcustom company-completion-started-hook nil
463 "Hook run when company starts completing.
464 The hook is called with one argument that is non-nil if the completion was
465 started manually."
466 :type 'hook)
467
468 (defcustom company-completion-cancelled-hook nil
469 "Hook run when company cancels completing.
470 The hook is called with one argument that is non-nil if the completion was
471 aborted manually."
472 :type 'hook)
473
474 (defcustom company-completion-finished-hook nil
475 "Hook run when company successfully completes.
476 The hook is called with the selected candidate as an argument.
477
478 If you indend to use it to post-process candidates from a specific
479 back-end, consider using the `post-completion' command instead."
480 :type 'hook)
481
482 (defcustom company-minimum-prefix-length 3
483 "The minimum prefix length for idle completion."
484 :type '(integer :tag "prefix length"))
485
486 (defcustom company-abort-manual-when-too-short nil
487 "If enabled, cancel a manually started completion when the prefix gets
488 shorter than both `company-minimum-prefix-length' and the length of the
489 prefix it was started from."
490 :type 'boolean
491 :package-version '(company . "0.8.0"))
492
493 (defcustom company-require-match 'company-explicit-action-p
494 "If enabled, disallow non-matching input.
495 This can be a function do determine if a match is required.
496
497 This can be overridden by the back-end, if it returns t or `never' to
498 `require-match'. `company-auto-complete' also takes precedence over this."
499 :type '(choice (const :tag "Off" nil)
500 (function :tag "Predicate function")
501 (const :tag "On, if user interaction took place"
502 'company-explicit-action-p)
503 (const :tag "On" t)))
504
505 (defcustom company-auto-complete nil
506 "Determines when to auto-complete.
507 If this is enabled, all characters from `company-auto-complete-chars'
508 trigger insertion of the selected completion candidate.
509 This can also be a function."
510 :type '(choice (const :tag "Off" nil)
511 (function :tag "Predicate function")
512 (const :tag "On, if user interaction took place"
513 'company-explicit-action-p)
514 (const :tag "On" t)))
515
516 (defcustom company-auto-complete-chars '(?\ ?\) ?.)
517 "Determines which characters trigger auto-completion.
518 See `company-auto-complete'. If this is a string, each string character
519 tiggers auto-completion. If it is a list of syntax description characters (see
520 `modify-syntax-entry'), all characters with that syntax auto-complete.
521
522 This can also be a function, which is called with the new input and should
523 return non-nil if company should auto-complete.
524
525 A character that is part of a valid candidate never triggers auto-completion."
526 :type '(choice (string :tag "Characters")
527 (set :tag "Syntax"
528 (const :tag "Whitespace" ?\ )
529 (const :tag "Symbol" ?_)
530 (const :tag "Opening parentheses" ?\()
531 (const :tag "Closing parentheses" ?\))
532 (const :tag "Word constituent" ?w)
533 (const :tag "Punctuation." ?.)
534 (const :tag "String quote." ?\")
535 (const :tag "Paired delimiter." ?$)
536 (const :tag "Expression quote or prefix operator." ?\')
537 (const :tag "Comment starter." ?<)
538 (const :tag "Comment ender." ?>)
539 (const :tag "Character-quote." ?/)
540 (const :tag "Generic string fence." ?|)
541 (const :tag "Generic comment fence." ?!))
542 (function :tag "Predicate function")))
543
544 (defcustom company-idle-delay .5
545 "The idle delay in seconds until completion starts automatically.
546 The prefix still has to satisfy `company-minimum-prefix-length' before that
547 happens. The value of nil means no idle completion."
548 :type '(choice (const :tag "never (nil)" nil)
549 (const :tag "immediate (0)" 0)
550 (number :tag "seconds")))
551
552 (defcustom company-begin-commands '(self-insert-command
553 org-self-insert-command
554 c-scope-operator
555 c-electric-colon
556 c-electric-lt-gt
557 c-electric-slash)
558 "A list of commands after which idle completion is allowed.
559 If this is t, it can show completions after any command except a few from a
560 pre-defined list. See `company-idle-delay'.
561
562 Alternatively, any command with a non-nil `company-begin' property is
563 treated as if it was on this list."
564 :type '(choice (const :tag "Any command" t)
565 (const :tag "Self insert command" '(self-insert-command))
566 (repeat :tag "Commands" function))
567 :package-version '(company . "0.8.4"))
568
569 (defcustom company-continue-commands '(not save-buffer save-some-buffers
570 save-buffers-kill-terminal
571 save-buffers-kill-emacs)
572 "A list of commands that are allowed during completion.
573 If this is t, or if `company-begin-commands' is t, any command is allowed.
574 Otherwise, the value must be a list of symbols. If it starts with `not',
575 the cdr is the list of commands that abort completion. Otherwise, all
576 commands except those in that list, or in `company-begin-commands', or
577 commands in the `company-' namespace, abort completion."
578 :type '(choice (const :tag "Any command" t)
579 (cons :tag "Any except"
580 (const not)
581 (repeat :tag "Commands" function))
582 (repeat :tag "Commands" function)))
583
584 (defcustom company-show-numbers nil
585 "If enabled, show quick-access numbers for the first ten candidates."
586 :type '(choice (const :tag "off" nil)
587 (const :tag "on" t)))
588
589 (defcustom company-selection-wrap-around nil
590 "If enabled, selecting item before first or after last wraps around."
591 :type '(choice (const :tag "off" nil)
592 (const :tag "on" t)))
593
594 (defvar company-async-wait 0.03
595 "Pause between checks to see if the value's been set when turning an
596 asynchronous call into synchronous.")
597
598 (defvar company-async-timeout 2
599 "Maximum wait time for a value to be set during asynchronous call.")
600
601 ;;; mode ;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;
602
603 (defvar company-mode-map (make-sparse-keymap)
604 "Keymap used by `company-mode'.")
605
606 (defvar company-active-map
607 (let ((keymap (make-sparse-keymap)))
608 (define-key keymap "\e\e\e" 'company-abort)
609 (define-key keymap "\C-g" 'company-abort)
610 (define-key keymap (kbd "M-n") 'company-select-next)
611 (define-key keymap (kbd "M-p") 'company-select-previous)
612 (define-key keymap (kbd "<down>") 'company-select-next-or-abort)
613 (define-key keymap (kbd "<up>") 'company-select-previous-or-abort)
614 (define-key keymap [down-mouse-1] 'ignore)
615 (define-key keymap [down-mouse-3] 'ignore)
616 (define-key keymap [mouse-1] 'company-complete-mouse)
617 (define-key keymap [mouse-3] 'company-select-mouse)
618 (define-key keymap [up-mouse-1] 'ignore)
619 (define-key keymap [up-mouse-3] 'ignore)
620 (define-key keymap [return] 'company-complete-selection)
621 (define-key keymap (kbd "RET") 'company-complete-selection)
622 (define-key keymap [tab] 'company-complete-common)
623 (define-key keymap (kbd "TAB") 'company-complete-common)
624 (define-key keymap (kbd "<f1>") 'company-show-doc-buffer)
625 (define-key keymap (kbd "C-h") 'company-show-doc-buffer)
626 (define-key keymap "\C-w" 'company-show-location)
627 (define-key keymap "\C-s" 'company-search-candidates)
628 (define-key keymap "\C-\M-s" 'company-filter-candidates)
629 (dotimes (i 10)
630 (define-key keymap (kbd (format "M-%d" i)) 'company-complete-number))
631 keymap)
632 "Keymap that is enabled during an active completion.")
633
634 (defvar company--disabled-backends nil)
635
636 (defun company-init-backend (backend)
637 (and (symbolp backend)
638 (not (fboundp backend))
639 (ignore-errors (require backend nil t)))
640 (cond
641 ((symbolp backend)
642 (condition-case err
643 (progn
644 (funcall backend 'init)
645 (put backend 'company-init t))
646 (error
647 (put backend 'company-init 'failed)
648 (unless (memq backend company--disabled-backends)
649 (message "Company back-end '%s' could not be initialized:\n%s"
650 backend (error-message-string err)))
651 (cl-pushnew backend company--disabled-backends)
652 nil)))
653 ;; No initialization for lambdas.
654 ((functionp backend) t)
655 (t ;; Must be a list.
656 (cl-dolist (b backend)
657 (unless (keywordp b)
658 (company-init-backend b))))))
659
660 (defvar company-default-lighter " company")
661
662 (defvar-local company-lighter company-default-lighter)
663
664 ;;;###autoload
665 (define-minor-mode company-mode
666 "\"complete anything\"; is an in-buffer completion framework.
667 Completion starts automatically, depending on the values
668 `company-idle-delay' and `company-minimum-prefix-length'.
669
670 Completion can be controlled with the commands:
671 `company-complete-common', `company-complete-selection', `company-complete',
672 `company-select-next', `company-select-previous'. If these commands are
673 called before `company-idle-delay', completion will also start.
674
675 Completions can be searched with `company-search-candidates' or
676 `company-filter-candidates'. These can be used while completion is
677 inactive, as well.
678
679 The completion data is retrieved using `company-backends' and displayed
680 using `company-frontends'. If you want to start a specific back-end, call
681 it interactively or use `company-begin-backend'.
682
683 regular keymap (`company-mode-map'):
684
685 \\{company-mode-map}
686 keymap during active completions (`company-active-map'):
687
688 \\{company-active-map}"
689 nil company-lighter company-mode-map
690 (if company-mode
691 (progn
692 (when (eq company-idle-delay t)
693 (setq company-idle-delay 0)
694 (warn "Setting `company-idle-delay' to t is deprecated. Set it to 0 instead."))
695 (add-hook 'pre-command-hook 'company-pre-command nil t)
696 (add-hook 'post-command-hook 'company-post-command nil t)
697 (mapc 'company-init-backend company-backends))
698 (remove-hook 'pre-command-hook 'company-pre-command t)
699 (remove-hook 'post-command-hook 'company-post-command t)
700 (company-cancel)
701 (kill-local-variable 'company-point)))
702
703 (defcustom company-global-modes t
704 "Modes for which `company-mode' mode is turned on by `global-company-mode'.
705 If nil, means no modes. If t, then all major modes have it turned on.
706 If a list, it should be a list of `major-mode' symbol names for which
707 `company-mode' should be automatically turned on. The sense of the list is
708 negated if it begins with `not'. For example:
709 (c-mode c++-mode)
710 means that `company-mode' is turned on for buffers in C and C++ modes only.
711 (not message-mode)
712 means that `company-mode' is always turned on except in `message-mode' buffers."
713 :type '(choice (const :tag "none" nil)
714 (const :tag "all" t)
715 (set :menu-tag "mode specific" :tag "modes"
716 :value (not)
717 (const :tag "Except" not)
718 (repeat :inline t (symbol :tag "mode")))))
719
720 ;;;###autoload
721 (define-globalized-minor-mode global-company-mode company-mode company-mode-on)
722
723 (defun company-mode-on ()
724 (when (and (not (or noninteractive (eq (aref (buffer-name) 0) ?\s)))
725 (cond ((eq company-global-modes t)
726 t)
727 ((eq (car-safe company-global-modes) 'not)
728 (not (memq major-mode (cdr company-global-modes))))
729 (t (memq major-mode company-global-modes))))
730 (company-mode 1)))
731
732 (defsubst company-assert-enabled ()
733 (unless company-mode
734 (company-uninstall-map)
735 (error "Company not enabled")))
736
737 ;;; keymaps ;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;
738
739 (defvar-local company-my-keymap nil)
740
741 (defvar company-emulation-alist '((t . nil)))
742
743 (defsubst company-enable-overriding-keymap (keymap)
744 (company-uninstall-map)
745 (setq company-my-keymap keymap))
746
747 (defun company-ensure-emulation-alist ()
748 (unless (eq 'company-emulation-alist (car emulation-mode-map-alists))
749 (setq emulation-mode-map-alists
750 (cons 'company-emulation-alist
751 (delq 'company-emulation-alist emulation-mode-map-alists)))))
752
753 (defun company-install-map ()
754 (unless (or (cdar company-emulation-alist)
755 (null company-my-keymap))
756 (setf (cdar company-emulation-alist) company-my-keymap)))
757
758 (defun company-uninstall-map ()
759 (setf (cdar company-emulation-alist) nil))
760
761 ;; Hack:
762 ;; Emacs calculates the active keymaps before reading the event. That means we
763 ;; cannot change the keymap from a timer. So we send a bogus command.
764 ;; XXX: Even in Emacs 24.4, seems to be needed in the terminal.
765 (defun company-ignore ()
766 (interactive)
767 (setq this-command last-command))
768
769 (global-set-key '[31415926] 'company-ignore)
770
771 (defun company-input-noop ()
772 (push 31415926 unread-command-events))
773
774 (defun company--posn-col-row (posn)
775 (let ((col (car (posn-col-row posn)))
776 (row (cdr (posn-actual-col-row posn))))
777 (when (and header-line-format (version< emacs-version "24.3.93.3"))
778 ;; http://debbugs.gnu.org/18384
779 (cl-decf row))
780 (cons (+ col (window-hscroll)) row)))
781
782 (defun company--col-row (&optional pos)
783 (company--posn-col-row (posn-at-point pos)))
784
785 (defun company--row (&optional pos)
786 (cdr (company--col-row pos)))
787
788 ;;; backends ;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;
789
790 (defvar-local company-backend nil)
791
792 (defun company-grab (regexp &optional expression limit)
793 (when (looking-back regexp limit)
794 (or (match-string-no-properties (or expression 0)) "")))
795
796 (defun company-grab-line (regexp &optional expression)
797 (company-grab regexp expression (point-at-bol)))
798
799 (defun company-grab-symbol ()
800 (if (looking-at "\\_>")
801 (buffer-substring (point) (save-excursion (skip-syntax-backward "w_")
802 (point)))
803 (unless (and (char-after) (memq (char-syntax (char-after)) '(?w ?_)))
804 "")))
805
806 (defun company-grab-word ()
807 (if (looking-at "\\>")
808 (buffer-substring (point) (save-excursion (skip-syntax-backward "w")
809 (point)))
810 (unless (and (char-after) (eq (char-syntax (char-after)) ?w))
811 "")))
812
813 (defun company-grab-symbol-cons (idle-begin-after-re &optional max-len)
814 (let ((symbol (company-grab-symbol)))
815 (when symbol
816 (save-excursion
817 (forward-char (- (length symbol)))
818 (if (looking-back idle-begin-after-re (if max-len
819 (- (point) max-len)
820 (line-beginning-position)))
821 (cons symbol t)
822 symbol)))))
823
824 (defun company-in-string-or-comment ()
825 (let ((ppss (syntax-ppss)))
826 (or (car (setq ppss (nthcdr 3 ppss)))
827 (car (setq ppss (cdr ppss)))
828 (nth 3 ppss))))
829
830 (defun company-call-backend (&rest args)
831 (company--force-sync #'company-call-backend-raw args company-backend))
832
833 (defun company--force-sync (fun args backend)
834 (let ((value (apply fun args)))
835 (if (not (eq (car-safe value) :async))
836 value
837 (let ((res 'trash)
838 (start (time-to-seconds)))
839 (funcall (cdr value)
840 (lambda (result) (setq res result)))
841 (while (eq res 'trash)
842 (if (> (- (time-to-seconds) start) company-async-timeout)
843 (error "Company: Back-end %s async timeout with args %s"
844 backend args)
845 (sleep-for company-async-wait)))
846 res))))
847
848 (defun company-call-backend-raw (&rest args)
849 (condition-case err
850 (if (functionp company-backend)
851 (apply company-backend args)
852 (apply #'company--multi-backend-adapter company-backend args))
853 (error (error "Company: Back-end %s error \"%s\" with args %s"
854 company-backend (error-message-string err) args))))
855
856 (defun company--multi-backend-adapter (backends command &rest args)
857 (let ((backends (cl-loop for b in backends
858 when (not (and (symbolp b)
859 (eq 'failed (get b 'company-init))))
860 collect b)))
861 (setq backends
862 (if (eq command 'prefix)
863 (butlast backends (length (member :with backends)))
864 (delq :with backends)))
865 (pcase command
866 (`candidates
867 (company--multi-backend-adapter-candidates backends (car args)))
868 (`sorted nil)
869 (`duplicates t)
870 ((or `prefix `ignore-case `no-cache `require-match)
871 (let (value)
872 (cl-dolist (backend backends)
873 (when (setq value (company--force-sync
874 backend (cons command args) backend))
875 (cl-return value)))))
876 (_
877 (let ((arg (car args)))
878 (when (> (length arg) 0)
879 (let ((backend (or (get-text-property 0 'company-backend arg)
880 (car backends))))
881 (apply backend command args))))))))
882
883 (defun company--multi-backend-adapter-candidates (backends prefix)
884 (let ((pairs (cl-loop for backend in (cdr backends)
885 when (equal (company--prefix-str
886 (funcall backend 'prefix))
887 prefix)
888 collect (cons (funcall backend 'candidates prefix)
889 (let ((b backend))
890 (lambda (candidates)
891 (mapcar
892 (lambda (str)
893 (propertize str 'company-backend b))
894 candidates)))))))
895 (when (equal (company--prefix-str (funcall (car backends) 'prefix)) prefix)
896 ;; Small perf optimization: don't tag the candidates received
897 ;; from the first backend in the group.
898 (push (cons (funcall (car backends) 'candidates prefix)
899 'identity)
900 pairs))
901 (company--merge-async pairs (lambda (values) (apply #'append values)))))
902
903 (defun company--merge-async (pairs merger)
904 (let ((async (cl-loop for pair in pairs
905 thereis
906 (eq :async (car-safe (car pair))))))
907 (if (not async)
908 (funcall merger (cl-loop for (val . mapper) in pairs
909 collect (funcall mapper val)))
910 (cons
911 :async
912 (lambda (callback)
913 (let* (lst pending
914 (finisher (lambda ()
915 (unless pending
916 (funcall callback
917 (funcall merger
918 (nreverse lst)))))))
919 (dolist (pair pairs)
920 (let ((val (car pair))
921 (mapper (cdr pair)))
922 (if (not (eq :async (car-safe val)))
923 (push (funcall mapper val) lst)
924 (push nil lst)
925 (let ((cell lst)
926 (fetcher (cdr val)))
927 (push fetcher pending)
928 (funcall fetcher
929 (lambda (res)
930 (setq pending (delq fetcher pending))
931 (setcar cell (funcall mapper res))
932 (funcall finisher)))))))))))))
933
934 (defun company--prefix-str (prefix)
935 (or (car-safe prefix) prefix))
936
937 ;;; completion mechanism ;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;
938
939 (defvar-local company-prefix nil)
940
941 (defvar-local company-candidates nil)
942
943 (defvar-local company-candidates-length nil)
944
945 (defvar-local company-candidates-cache nil)
946
947 (defvar-local company-candidates-predicate nil)
948
949 (defvar-local company-common nil)
950
951 (defvar-local company-selection 0)
952
953 (defvar-local company-selection-changed nil)
954
955 (defvar-local company--manual-action nil
956 "Non-nil, if manual completion took place.")
957
958 (defvar-local company--manual-prefix nil)
959
960 (defvar company--auto-completion nil
961 "Non-nil when current candidate is being inserted automatically.
962 Controlled by `company-auto-complete'.")
963
964 (defvar-local company--point-max nil)
965
966 (defvar-local company-point nil)
967
968 (defvar company-timer nil)
969
970 (defsubst company-strip-prefix (str)
971 (substring str (length company-prefix)))
972
973 (defun company--insert-candidate (candidate)
974 (setq candidate (substring-no-properties candidate))
975 ;; XXX: Return value we check here is subject to change.
976 (if (eq (company-call-backend 'ignore-case) 'keep-prefix)
977 (insert (company-strip-prefix candidate))
978 (delete-region (- (point) (length company-prefix)) (point))
979 (insert candidate)))
980
981 (defmacro company-with-candidate-inserted (candidate &rest body)
982 "Evaluate BODY with CANDIDATE temporarily inserted.
983 This is a tool for back-ends that need candidates inserted before they
984 can retrieve meta-data for them."
985 (declare (indent 1))
986 `(let ((inhibit-modification-hooks t)
987 (inhibit-point-motion-hooks t)
988 (modified-p (buffer-modified-p)))
989 (company--insert-candidate ,candidate)
990 (unwind-protect
991 (progn ,@body)
992 (delete-region company-point (point)))))
993
994 (defun company-explicit-action-p ()
995 "Return whether explicit completion action was taken by the user."
996 (or company--manual-action
997 company-selection-changed))
998
999 (defun company-reformat (candidate)
1000 ;; company-ispell needs this, because the results are always lower-case
1001 ;; It's mory efficient to fix it only when they are displayed.
1002 ;; FIXME: Adopt the current text's capitalization instead?
1003 (if (eq (company-call-backend 'ignore-case) 'keep-prefix)
1004 (concat company-prefix (substring candidate (length company-prefix)))
1005 candidate))
1006
1007 (defun company--should-complete ()
1008 (and (eq company-idle-delay 'now)
1009 (not (or buffer-read-only overriding-terminal-local-map
1010 overriding-local-map))
1011 ;; Check if in the middle of entering a key combination.
1012 (or (equal (this-command-keys-vector) [])
1013 (not (keymapp (key-binding (this-command-keys-vector)))))
1014 (not (and transient-mark-mode mark-active))))
1015
1016 (defun company--should-continue ()
1017 (or (eq t company-begin-commands)
1018 (eq t company-continue-commands)
1019 (if (eq 'not (car company-continue-commands))
1020 (not (memq this-command (cdr company-continue-commands)))
1021 (or (memq this-command company-begin-commands)
1022 (memq this-command company-continue-commands)
1023 (and (symbolp this-command)
1024 (string-match-p "\\`company-" (symbol-name this-command)))))))
1025
1026 (defun company-call-frontends (command)
1027 (dolist (frontend company-frontends)
1028 (condition-case err
1029 (funcall frontend command)
1030 (error (error "Company: Front-end %s error \"%s\" on command %s"
1031 frontend (error-message-string err) command)))))
1032
1033 (defun company-set-selection (selection &optional force-update)
1034 (setq selection
1035 (if company-selection-wrap-around
1036 (mod selection company-candidates-length)
1037 (max 0 (min (1- company-candidates-length) selection))))
1038 (when (or force-update (not (equal selection company-selection)))
1039 (company--update-group-lighter (nth selection company-candidates))
1040 (setq company-selection selection
1041 company-selection-changed t)
1042 (company-call-frontends 'update)))
1043
1044 (defun company--update-group-lighter (candidate)
1045 (when (listp company-backend)
1046 (let ((backend (or (get-text-property 0 'company-backend candidate)
1047 (car company-backend))))
1048 (when (and backend (symbolp backend))
1049 (let ((name (replace-regexp-in-string "company-\\|-company" ""
1050 (symbol-name backend))))
1051 (setq company-lighter (format " company-<%s>" name)))))))
1052
1053 (defun company-apply-predicate (candidates predicate)
1054 (let (new)
1055 (dolist (c candidates)
1056 (when (funcall predicate c)
1057 (push c new)))
1058 (nreverse new)))
1059
1060 (defun company-update-candidates (candidates)
1061 (setq company-candidates-length (length candidates))
1062 (if (> company-selection 0)
1063 ;; Try to restore the selection
1064 (let ((selected (nth company-selection company-candidates)))
1065 (setq company-selection 0
1066 company-candidates candidates)
1067 (when selected
1068 (while (and candidates (string< (pop candidates) selected))
1069 (cl-incf company-selection))
1070 (unless candidates
1071 ;; Make sure selection isn't out of bounds.
1072 (setq company-selection (min (1- company-candidates-length)
1073 company-selection)))))
1074 (setq company-selection 0
1075 company-candidates candidates))
1076 ;; Save in cache:
1077 (push (cons company-prefix company-candidates) company-candidates-cache)
1078 ;; Calculate common.
1079 (let ((completion-ignore-case (company-call-backend 'ignore-case)))
1080 ;; We want to support non-prefix completion, so filtering is the
1081 ;; responsibility of each respective backend, not ours.
1082 ;; On the other hand, we don't want to replace non-prefix input in
1083 ;; `company-complete-common'.
1084 (setq company-common
1085 (if (cdr company-candidates)
1086 (let ((common (try-completion company-prefix company-candidates)))
1087 (if (eq common t)
1088 ;; Mulple equal strings, probably with different
1089 ;; annotations.
1090 company-prefix
1091 common))
1092 (car company-candidates)))))
1093
1094 (defun company-calculate-candidates (prefix)
1095 (let ((candidates (cdr (assoc prefix company-candidates-cache)))
1096 (ignore-case (company-call-backend 'ignore-case)))
1097 (or candidates
1098 (when company-candidates-cache
1099 (let ((len (length prefix))
1100 (completion-ignore-case ignore-case)
1101 prev)
1102 (cl-dotimes (i (1+ len))
1103 (when (setq prev (cdr (assoc (substring prefix 0 (- len i))
1104 company-candidates-cache)))
1105 (setq candidates (all-completions prefix prev))
1106 (cl-return t)))))
1107 ;; no cache match, call back-end
1108 (setq candidates
1109 (company--process-candidates
1110 (company--fetch-candidates prefix))))
1111 (setq candidates (company--transform-candidates candidates))
1112 (when candidates
1113 (if (or (cdr candidates)
1114 (not (eq t (compare-strings (car candidates) nil nil
1115 prefix nil nil ignore-case))))
1116 candidates
1117 ;; Already completed and unique; don't start.
1118 t))))
1119
1120 (defun company--fetch-candidates (prefix)
1121 (let ((c (if company--manual-action
1122 (company-call-backend 'candidates prefix)
1123 (company-call-backend-raw 'candidates prefix)))
1124 res)
1125 (if (not (eq (car c) :async))
1126 c
1127 (let ((buf (current-buffer))
1128 (win (selected-window))
1129 (tick (buffer-chars-modified-tick))
1130 (pt (point))
1131 (backend company-backend))
1132 (funcall
1133 (cdr c)
1134 (lambda (candidates)
1135 (if (not (and candidates (eq res 'done)))
1136 ;; Fetcher called us back right away.
1137 (setq res candidates)
1138 (setq company-backend backend
1139 company-candidates-cache
1140 (list (cons prefix
1141 (company--process-candidates
1142 candidates))))
1143 (company-idle-begin buf win tick pt)))))
1144 ;; FIXME: Relying on the fact that the callers
1145 ;; will interpret nil as "do nothing" is shaky.
1146 ;; A throw-catch would be one possible improvement.
1147 (or res
1148 (progn (setq res 'done) nil)))))
1149
1150 (defun company--process-candidates (candidates)
1151 (when company-candidates-predicate
1152 (setq candidates
1153 (company-apply-predicate candidates
1154 company-candidates-predicate)))
1155 (unless (company-call-backend 'sorted)
1156 (setq candidates (sort candidates 'string<)))
1157 (when (company-call-backend 'duplicates)
1158 (company--strip-duplicates candidates))
1159 candidates)
1160
1161 (defun company--strip-duplicates (candidates)
1162 (let ((c2 candidates))
1163 (while c2
1164 (setcdr c2
1165 (let ((str (car c2))
1166 (anno 'unk))
1167 (pop c2)
1168 (while (let ((str2 (car c2)))
1169 (if (not (equal str str2))
1170 nil
1171 (when (eq anno 'unk)
1172 (setq anno (company-call-backend
1173 'annotation str)))
1174 (equal anno
1175 (company-call-backend
1176 'annotation str2))))
1177 (pop c2))
1178 c2)))))
1179
1180 (defun company--transform-candidates (candidates)
1181 (let ((c candidates))
1182 (dolist (tr company-transformers)
1183 (setq c (funcall tr c)))
1184 c))
1185
1186 (defcustom company-occurrence-weight-function
1187 #'company-occurrence-prefer-closest-above
1188 "Function to weigh matches in `company-sort-by-occurrence'.
1189 It's called with three arguments: cursor position, the beginning and the
1190 end of the match."
1191 :type '(choice
1192 (const :tag "First above point, then below point"
1193 company-occurrence-prefer-closest-above)
1194 (const :tag "Prefer closest in any direction"
1195 company-occurrence-prefer-any-closest)))
1196
1197 (defun company-occurrence-prefer-closest-above (pos match-beg match-end)
1198 "Give priority to the matches above point, then those below point."
1199 (if (< match-beg pos)
1200 (- pos match-end)
1201 (- match-beg (window-start))))
1202
1203 (defun company-occurrence-prefer-any-closest (pos _match-beg match-end)
1204 "Give priority to the matches closest to the point."
1205 (abs (- pos match-end)))
1206
1207 (defun company-sort-by-occurrence (candidates)
1208 "Sort CANDIDATES according to their occurrences.
1209 Searches for each in the currently visible part of the current buffer and
1210 prioritizes the matches according to `company-occurrence-weight-function'.
1211 The rest of the list is appended unchanged.
1212 Keywords and function definition names are ignored."
1213 (let* ((w-start (window-start))
1214 (w-end (window-end))
1215 (start-point (point))
1216 occurs
1217 (noccurs
1218 (save-excursion
1219 (cl-delete-if
1220 (lambda (candidate)
1221 (when (catch 'done
1222 (goto-char w-start)
1223 (while (search-forward candidate w-end t)
1224 (when (and (not (eq (point) start-point))
1225 (save-match-data
1226 (company--occurrence-predicate)))
1227 (throw 'done t))))
1228 (push
1229 (cons candidate
1230 (funcall company-occurrence-weight-function
1231 start-point
1232 (match-beginning 0)
1233 (match-end 0)))
1234 occurs)
1235 t))
1236 candidates))))
1237 (nconc
1238 (mapcar #'car (sort occurs (lambda (e1 e2) (<= (cdr e1) (cdr e2)))))
1239 noccurs)))
1240
1241 (defun company--occurrence-predicate ()
1242 (let ((beg (match-beginning 0))
1243 (end (match-end 0)))
1244 (save-excursion
1245 (goto-char end)
1246 (and (not (memq (get-text-property (1- (point)) 'face)
1247 '(font-lock-function-name-face
1248 font-lock-keyword-face)))
1249 (let ((prefix (company--prefix-str
1250 (company-call-backend 'prefix))))
1251 (and (stringp prefix)
1252 (= (length prefix) (- end beg))))))))
1253
1254 (defun company-sort-by-backend-importance (candidates)
1255 "Sort CANDIDATES as two priority groups.
1256 If `company-backend' is a function, do nothing. If it's a list, move
1257 candidates from back-ends before keyword `:with' to the front. Candidates
1258 from the rest of the back-ends in the group, if any, will be left at the end."
1259 (if (functionp company-backend)
1260 candidates
1261 (let ((low-priority (cdr (memq :with company-backend))))
1262 (if (null low-priority)
1263 candidates
1264 (sort candidates
1265 (lambda (c1 c2)
1266 (and
1267 (let ((b2 (get-text-property 0 'company-backend c2)))
1268 (and b2 (memq b2 low-priority)))
1269 (let ((b1 (get-text-property 0 'company-backend c1)))
1270 (or (not b1) (not (memq b1 low-priority)))))))))))
1271
1272 (defun company-idle-begin (buf win tick pos)
1273 (and (eq buf (current-buffer))
1274 (eq win (selected-window))
1275 (eq tick (buffer-chars-modified-tick))
1276 (eq pos (point))
1277 (when (company-auto-begin)
1278 (company-input-noop)
1279 (company-post-command))))
1280
1281 (defun company-auto-begin ()
1282 (and company-mode
1283 (not company-candidates)
1284 (let ((company-idle-delay 'now))
1285 (condition-case-unless-debug err
1286 (company--perform)
1287 (error (message "Company: An error occurred in auto-begin")
1288 (message "%s" (error-message-string err))
1289 (company-cancel))
1290 (quit (company-cancel)))))
1291 (unless company-candidates
1292 (setq company-backend nil))
1293 ;; Return non-nil if active.
1294 company-candidates)
1295
1296 (defun company-manual-begin ()
1297 (interactive)
1298 (company-assert-enabled)
1299 (setq company--manual-action t)
1300 (unwind-protect
1301 (let ((company-minimum-prefix-length 0))
1302 (company-auto-begin))
1303 (unless company-candidates
1304 (setq company--manual-action nil))))
1305
1306 (defun company-other-backend (&optional backward)
1307 (interactive (list current-prefix-arg))
1308 (company-assert-enabled)
1309 (let* ((after (if company-backend
1310 (cdr (member company-backend company-backends))
1311 company-backends))
1312 (before (cdr (member company-backend (reverse company-backends))))
1313 (next (if backward
1314 (append before (reverse after))
1315 (append after (reverse before)))))
1316 (company-cancel)
1317 (cl-dolist (backend next)
1318 (when (ignore-errors (company-begin-backend backend))
1319 (cl-return t))))
1320 (unless company-candidates
1321 (error "No other back-end")))
1322
1323 (defun company-require-match-p ()
1324 (let ((backend-value (company-call-backend 'require-match)))
1325 (or (eq backend-value t)
1326 (and (not (eq backend-value 'never))
1327 (if (functionp company-require-match)
1328 (funcall company-require-match)
1329 (eq company-require-match t))))))
1330
1331 (defun company-auto-complete-p (input)
1332 "Return non-nil, if input starts with punctuation or parentheses."
1333 (and (if (functionp company-auto-complete)
1334 (funcall company-auto-complete)
1335 company-auto-complete)
1336 (if (functionp company-auto-complete-chars)
1337 (funcall company-auto-complete-chars input)
1338 (if (consp company-auto-complete-chars)
1339 (memq (char-syntax (string-to-char input))
1340 company-auto-complete-chars)
1341 (string-match (substring input 0 1) company-auto-complete-chars)))))
1342
1343 (defun company--incremental-p ()
1344 (and (> (point) company-point)
1345 (> (point-max) company--point-max)
1346 (not (eq this-command 'backward-delete-char-untabify))
1347 (equal (buffer-substring (- company-point (length company-prefix))
1348 company-point)
1349 company-prefix)))
1350
1351 (defun company--continue-failed (new-prefix)
1352 (let ((input (buffer-substring-no-properties (point) company-point)))
1353 (cond
1354 ((company-auto-complete-p input)
1355 ;; auto-complete
1356 (save-excursion
1357 (goto-char company-point)
1358 (let ((company--auto-completion t))
1359 (company-complete-selection))
1360 nil))
1361 ((and (or (not (company-require-match-p))
1362 ;; Don't require match if the new prefix
1363 ;; doesn't continue the old one, and the latter was a match.
1364 (<= (length new-prefix) (length company-prefix)))
1365 (member company-prefix company-candidates))
1366 ;; Last input was a success,
1367 ;; but we're treating it as an abort + input anyway,
1368 ;; like the `unique' case below.
1369 (company-cancel 'non-unique))
1370 ((company-require-match-p)
1371 ;; Wrong incremental input, but required match.
1372 (delete-char (- (length input)))
1373 (ding)
1374 (message "Matching input is required")
1375 company-candidates)
1376 (t (company-cancel)))))
1377
1378 (defun company--good-prefix-p (prefix)
1379 (and (stringp (company--prefix-str prefix)) ;excludes 'stop
1380 (or (eq (cdr-safe prefix) t)
1381 (let ((len (or (cdr-safe prefix) (length prefix))))
1382 (if company--manual-prefix
1383 (or (not company-abort-manual-when-too-short)
1384 ;; Must not be less than minimum or initial length.
1385 (>= len (min company-minimum-prefix-length
1386 (length company--manual-prefix))))
1387 (>= len company-minimum-prefix-length))))))
1388
1389 (defun company--continue ()
1390 (when (company-call-backend 'no-cache company-prefix)
1391 ;; Don't complete existing candidates, fetch new ones.
1392 (setq company-candidates-cache nil))
1393 (let* ((new-prefix (company-call-backend 'prefix))
1394 (c (when (and (company--good-prefix-p new-prefix)
1395 (setq new-prefix (company--prefix-str new-prefix))
1396 (= (- (point) (length new-prefix))
1397 (- company-point (length company-prefix))))
1398 (company-calculate-candidates new-prefix))))
1399 (cond
1400 ((eq c t)
1401 ;; t means complete/unique.
1402 ;; Handle it like completion was aborted, to differentiate from user
1403 ;; calling one of Company's commands to insert the candidate,
1404 ;; not to trigger template expansion, etc.
1405 (company-cancel 'unique))
1406 ((consp c)
1407 ;; incremental match
1408 (setq company-prefix new-prefix)
1409 (company-update-candidates c)
1410 c)
1411 ((not (company--incremental-p))
1412 (company-cancel))
1413 (t (company--continue-failed new-prefix)))))
1414
1415 (defun company--begin-new ()
1416 (let (prefix c)
1417 (cl-dolist (backend (if company-backend
1418 ;; prefer manual override
1419 (list company-backend)
1420 company-backends))
1421 (setq prefix
1422 (if (or (symbolp backend)
1423 (functionp backend))
1424 (when (or (not (symbolp backend))
1425 (eq t (get backend 'company-init))
1426 (unless (get backend 'company-init)
1427 (company-init-backend backend)))
1428 (funcall backend 'prefix))
1429 (company--multi-backend-adapter backend 'prefix)))
1430 (when prefix
1431 (when (company--good-prefix-p prefix)
1432 (setq company-prefix (company--prefix-str prefix)
1433 company-backend backend
1434 c (company-calculate-candidates company-prefix))
1435 ;; t means complete/unique. We don't start, so no hooks.
1436 (if (not (consp c))
1437 (when company--manual-action
1438 (message "No completion found"))
1439 (when company--manual-action
1440 (setq company--manual-prefix prefix))
1441 (if (symbolp backend)
1442 (setq company-lighter (concat " " (symbol-name backend)))
1443 (company--update-group-lighter (car c)))
1444 (company-update-candidates c)
1445 (run-hook-with-args 'company-completion-started-hook
1446 (company-explicit-action-p))
1447 (company-call-frontends 'show)))
1448 (cl-return c)))))
1449
1450 (defun company--perform ()
1451 (or (and company-candidates (company--continue))
1452 (and (company--should-complete) (company--begin-new)))
1453 (when company-candidates
1454 (setq company-point (point)
1455 company--point-max (point-max))
1456 (company-ensure-emulation-alist)
1457 (company-enable-overriding-keymap company-active-map)
1458 (company-call-frontends 'update)))
1459
1460 (defun company-cancel (&optional result)
1461 (unwind-protect
1462 (when company-prefix
1463 (if (stringp result)
1464 (progn
1465 (company-call-backend 'pre-completion result)
1466 (run-hook-with-args 'company-completion-finished-hook result)
1467 (company-call-backend 'post-completion result))
1468 (run-hook-with-args 'company-completion-cancelled-hook result)))
1469 (setq company-backend nil
1470 company-prefix nil
1471 company-candidates nil
1472 company-candidates-length nil
1473 company-candidates-cache nil
1474 company-candidates-predicate nil
1475 company-common nil
1476 company-selection 0
1477 company-selection-changed nil
1478 company--manual-action nil
1479 company--manual-prefix nil
1480 company-lighter company-default-lighter
1481 company--point-max nil
1482 company-point nil)
1483 (when company-timer
1484 (cancel-timer company-timer))
1485 (company-search-mode 0)
1486 (company-call-frontends 'hide)
1487 (company-enable-overriding-keymap nil))
1488 ;; Make return value explicit.
1489 nil)
1490
1491 (defun company-abort ()
1492 (interactive)
1493 (company-cancel 'abort))
1494
1495 (defun company-finish (result)
1496 (company--insert-candidate result)
1497 (company-cancel result))
1498
1499 (defsubst company-keep (command)
1500 (and (symbolp command) (get command 'company-keep)))
1501
1502 (defun company-pre-command ()
1503 (unless (company-keep this-command)
1504 (condition-case err
1505 (when company-candidates
1506 (company-call-frontends 'pre-command)
1507 (unless (company--should-continue)
1508 (company-abort)))
1509 (error (message "Company: An error occurred in pre-command")
1510 (message "%s" (error-message-string err))
1511 (company-cancel))))
1512 (when company-timer
1513 (cancel-timer company-timer)
1514 (setq company-timer nil))
1515 (company-uninstall-map))
1516
1517 (defun company-post-command ()
1518 (unless (company-keep this-command)
1519 (condition-case err
1520 (progn
1521 (unless (equal (point) company-point)
1522 (let (company-idle-delay) ; Against misbehavior while debugging.
1523 (company--perform)))
1524 (if company-candidates
1525 (company-call-frontends 'post-command)
1526 (and (numberp company-idle-delay)
1527 (company--should-begin)
1528 (setq company-timer
1529 (run-with-timer company-idle-delay nil
1530 'company-idle-begin
1531 (current-buffer) (selected-window)
1532 (buffer-chars-modified-tick) (point))))))
1533 (error (message "Company: An error occurred in post-command")
1534 (message "%s" (error-message-string err))
1535 (company-cancel))))
1536 (company-install-map))
1537
1538 (defvar company--begin-inhibit-commands '(company-abort
1539 company-complete-mouse
1540 company-complete
1541 company-complete-common
1542 company-complete-selection
1543 company-complete-number)
1544 "List of commands after which idle completion is (still) disabled when
1545 `company-begin-commands' is t.")
1546
1547 (defun company--should-begin ()
1548 (if (eq t company-begin-commands)
1549 (not (memq this-command company--begin-inhibit-commands))
1550 (or
1551 (memq this-command company-begin-commands)
1552 (and (symbolp this-command) (get this-command 'company-begin)))))
1553
1554 ;;; search ;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;
1555
1556 (defvar-local company-search-string nil)
1557
1558 (defvar-local company-search-lighter " Search: \"\"")
1559
1560 (defvar-local company-search-old-map nil)
1561
1562 (defvar-local company-search-old-selection 0)
1563
1564 (defun company-search (text lines)
1565 (let ((quoted (regexp-quote text))
1566 (i 0))
1567 (cl-dolist (line lines)
1568 (when (string-match quoted line (length company-prefix))
1569 (cl-return i))
1570 (cl-incf i))))
1571
1572 (defun company-search-printing-char ()
1573 (interactive)
1574 (company-search-assert-enabled)
1575 (setq company-search-string
1576 (concat (or company-search-string "") (string last-command-event))
1577 company-search-lighter (concat " Search: \"" company-search-string
1578 "\""))
1579 (let ((pos (company-search company-search-string
1580 (nthcdr company-selection company-candidates))))
1581 (if (null pos)
1582 (ding)
1583 (company-set-selection (+ company-selection pos) t))))
1584
1585 (defun company-search-repeat-forward ()
1586 "Repeat the incremental search in completion candidates forward."
1587 (interactive)
1588 (company-search-assert-enabled)
1589 (let ((pos (company-search company-search-string
1590 (cdr (nthcdr company-selection
1591 company-candidates)))))
1592 (if (null pos)
1593 (ding)
1594 (company-set-selection (+ company-selection pos 1) t))))
1595
1596 (defun company-search-repeat-backward ()
1597 "Repeat the incremental search in completion candidates backwards."
1598 (interactive)
1599 (company-search-assert-enabled)
1600 (let ((pos (company-search company-search-string
1601 (nthcdr (- company-candidates-length
1602 company-selection)
1603 (reverse company-candidates)))))
1604 (if (null pos)
1605 (ding)
1606 (company-set-selection (- company-selection pos 1) t))))
1607
1608 (defun company-create-match-predicate ()
1609 (setq company-candidates-predicate
1610 `(lambda (candidate)
1611 ,(if company-candidates-predicate
1612 `(and (string-match ,company-search-string candidate)
1613 (funcall ,company-candidates-predicate
1614 candidate))
1615 `(string-match ,company-search-string candidate))))
1616 (company-update-candidates
1617 (company-apply-predicate company-candidates company-candidates-predicate))
1618 ;; Invalidate cache.
1619 (setq company-candidates-cache (cons company-prefix company-candidates)))
1620
1621 (defun company-filter-printing-char ()
1622 (interactive)
1623 (company-search-assert-enabled)
1624 (company-search-printing-char)
1625 (company-create-match-predicate)
1626 (company-call-frontends 'update))
1627
1628 (defun company-search-kill-others ()
1629 "Limit the completion candidates to the ones matching the search string."
1630 (interactive)
1631 (company-search-assert-enabled)
1632 (company-create-match-predicate)
1633 (company-search-mode 0)
1634 (company-call-frontends 'update))
1635
1636 (defun company-search-abort ()
1637 "Abort searching the completion candidates."
1638 (interactive)
1639 (company-search-assert-enabled)
1640 (company-set-selection company-search-old-selection t)
1641 (company-search-mode 0))
1642
1643 (defun company-search-other-char ()
1644 (interactive)
1645 (company-search-assert-enabled)
1646 (company-search-mode 0)
1647 (company--unread-last-input))
1648
1649 (defvar company-search-map
1650 (let ((i 0)
1651 (keymap (make-keymap)))
1652 (if (fboundp 'max-char)
1653 (set-char-table-range (nth 1 keymap) (cons #x100 (max-char))
1654 'company-search-printing-char)
1655 (with-no-warnings
1656 ;; obsolete in Emacs 23
1657 (let ((l (generic-character-list))
1658 (table (nth 1 keymap)))
1659 (while l
1660 (set-char-table-default table (car l) 'company-search-printing-char)
1661 (setq l (cdr l))))))
1662 (define-key keymap [t] 'company-search-other-char)
1663 (while (< i ?\s)
1664 (define-key keymap (make-string 1 i) 'company-search-other-char)
1665 (cl-incf i))
1666 (while (< i 256)
1667 (define-key keymap (vector i) 'company-search-printing-char)
1668 (cl-incf i))
1669 (let ((meta-map (make-sparse-keymap)))
1670 (define-key keymap (char-to-string meta-prefix-char) meta-map)
1671 (define-key keymap [escape] meta-map))
1672 (define-key keymap (vector meta-prefix-char t) 'company-search-other-char)
1673 (define-key keymap "\e\e\e" 'company-search-other-char)
1674 (define-key keymap [escape escape escape] 'company-search-other-char)
1675 (define-key keymap (kbd "DEL") 'company-search-other-char)
1676
1677 (define-key keymap "\C-g" 'company-search-abort)
1678 (define-key keymap "\C-s" 'company-search-repeat-forward)
1679 (define-key keymap "\C-r" 'company-search-repeat-backward)
1680 (define-key keymap "\C-o" 'company-search-kill-others)
1681 keymap)
1682 "Keymap used for incrementally searching the completion candidates.")
1683
1684 (define-minor-mode company-search-mode
1685 "Search mode for completion candidates.
1686 Don't start this directly, use `company-search-candidates' or
1687 `company-filter-candidates'."
1688 nil company-search-lighter nil
1689 (if company-search-mode
1690 (if (company-manual-begin)
1691 (progn
1692 (setq company-search-old-selection company-selection)
1693 (company-call-frontends 'update))
1694 (setq company-search-mode nil))
1695 (kill-local-variable 'company-search-string)
1696 (kill-local-variable 'company-search-lighter)
1697 (kill-local-variable 'company-search-old-selection)
1698 (company-enable-overriding-keymap company-active-map)))
1699
1700 (defun company-search-assert-enabled ()
1701 (company-assert-enabled)
1702 (unless company-search-mode
1703 (company-uninstall-map)
1704 (error "Company not in search mode")))
1705
1706 (defun company-search-candidates ()
1707 "Start searching the completion candidates incrementally.
1708
1709 \\<company-search-map>Search can be controlled with the commands:
1710 - `company-search-repeat-forward' (\\[company-search-repeat-forward])
1711 - `company-search-repeat-backward' (\\[company-search-repeat-backward])
1712 - `company-search-abort' (\\[company-search-abort])
1713
1714 Regular characters are appended to the search string.
1715
1716 The command `company-search-kill-others' (\\[company-search-kill-others])
1717 uses the search string to limit the completion candidates."
1718 (interactive)
1719 (company-search-mode 1)
1720 (company-enable-overriding-keymap company-search-map))
1721
1722 (defvar company-filter-map
1723 (let ((keymap (make-keymap)))
1724 (define-key keymap [remap company-search-printing-char]
1725 'company-filter-printing-char)
1726 (set-keymap-parent keymap company-search-map)
1727 keymap)
1728 "Keymap used for incrementally searching the completion candidates.")
1729
1730 (defun company-filter-candidates ()
1731 "Start filtering the completion candidates incrementally.
1732 This works the same way as `company-search-candidates' immediately
1733 followed by `company-search-kill-others' after each input."
1734 (interactive)
1735 (company-search-mode 1)
1736 (company-enable-overriding-keymap company-filter-map))
1737
1738 ;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;
1739
1740 (defun company-select-next ()
1741 "Select the next candidate in the list."
1742 (interactive)
1743 (when (company-manual-begin)
1744 (company-set-selection (1+ company-selection))))
1745
1746 (defun company-select-previous ()
1747 "Select the previous candidate in the list."
1748 (interactive)
1749 (when (company-manual-begin)
1750 (company-set-selection (1- company-selection))))
1751
1752 (defun company-select-next-or-abort ()
1753 "Select the next candidate if more than one, else abort
1754 and invoke the normal binding."
1755 (interactive)
1756 (if (> company-candidates-length 1)
1757 (company-select-next)
1758 (company-abort)
1759 (company--unread-last-input)))
1760
1761 (defun company-select-previous-or-abort ()
1762 "Select the previous candidate if more than one, else abort
1763 and invoke the normal binding."
1764 (interactive)
1765 (if (> company-candidates-length 1)
1766 (company-select-previous)
1767 (company-abort)
1768 (company--unread-last-input)))
1769
1770 (defvar company-pseudo-tooltip-overlay)
1771
1772 (defvar company-tooltip-offset)
1773
1774 (defun company--inside-tooltip-p (event-col-row row height)
1775 (let* ((ovl company-pseudo-tooltip-overlay)
1776 (column (overlay-get ovl 'company-column))
1777 (width (overlay-get ovl 'company-width))
1778 (evt-col (car event-col-row))
1779 (evt-row (cdr event-col-row)))
1780 (and (>= evt-col column)
1781 (< evt-col (+ column width))
1782 (if (> height 0)
1783 (and (> evt-row row)
1784 (<= evt-row (+ row height) ))
1785 (and (< evt-row row)
1786 (>= evt-row (+ row height)))))))
1787
1788 (defun company--event-col-row (event)
1789 (company--posn-col-row (event-start event)))
1790
1791 (defun company-select-mouse (event)
1792 "Select the candidate picked by the mouse."
1793 (interactive "e")
1794 (let ((event-col-row (company--event-col-row event))
1795 (ovl-row (company--row))
1796 (ovl-height (and company-pseudo-tooltip-overlay
1797 (min (overlay-get company-pseudo-tooltip-overlay
1798 'company-height)
1799 company-candidates-length))))
1800 (if (and ovl-height
1801 (company--inside-tooltip-p event-col-row ovl-row ovl-height))
1802 (progn
1803 (company-set-selection (+ (cdr event-col-row)
1804 (1- company-tooltip-offset)
1805 (if (and (eq company-tooltip-offset-display 'lines)
1806 (not (zerop company-tooltip-offset)))
1807 -1 0)
1808 (- ovl-row)
1809 (if (< ovl-height 0)
1810 (- 1 ovl-height)
1811 0)))
1812 t)
1813 (company-abort)
1814 (company--unread-last-input)
1815 nil)))
1816
1817 (defun company-complete-mouse (event)
1818 "Insert the candidate picked by the mouse."
1819 (interactive "e")
1820 (when (company-select-mouse event)
1821 (company-complete-selection)))
1822
1823 (defun company-complete-selection ()
1824 "Insert the selected candidate."
1825 (interactive)
1826 (when (company-manual-begin)
1827 (let ((result (nth company-selection company-candidates)))
1828 (company-finish result))))
1829
1830 (defun company-complete-common ()
1831 "Insert the common part of all candidates."
1832 (interactive)
1833 (when (company-manual-begin)
1834 (if (and (not (cdr company-candidates))
1835 (equal company-common (car company-candidates)))
1836 (company-complete-selection)
1837 (when company-common
1838 (company--insert-candidate company-common)))))
1839
1840 (defun company-complete ()
1841 "Insert the common part of all candidates or the current selection.
1842 The first time this is called, the common part is inserted, the second
1843 time, or when the selection has been changed, the selected candidate is
1844 inserted."
1845 (interactive)
1846 (when (company-manual-begin)
1847 (if (or company-selection-changed
1848 (eq last-command 'company-complete-common))
1849 (call-interactively 'company-complete-selection)
1850 (call-interactively 'company-complete-common)
1851 (setq this-command 'company-complete-common))))
1852
1853 (defun company-complete-number (n)
1854 "Insert the Nth candidate.
1855 To show the number next to the candidates in some back-ends, enable
1856 `company-show-numbers'. When called interactively, uses the last typed
1857 character, stripping the modifiers. That character must be a digit."
1858 (interactive
1859 (list (let ((n (- (event-basic-type last-command-event) ?0)))
1860 (if (zerop n) 10 n))))
1861 (when (company-manual-begin)
1862 (and (or (< n 1) (> n company-candidates-length))
1863 (error "No candidate number %d" n))
1864 (cl-decf n)
1865 (company-finish (nth n company-candidates))))
1866
1867 ;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;
1868
1869 (defconst company-space-strings-limit 100)
1870
1871 (defconst company-space-strings
1872 (let (lst)
1873 (dotimes (i company-space-strings-limit)
1874 (push (make-string (- company-space-strings-limit 1 i) ?\ ) lst))
1875 (apply 'vector lst)))
1876
1877 (defun company-space-string (len)
1878 (if (< len company-space-strings-limit)
1879 (aref company-space-strings len)
1880 (make-string len ?\ )))
1881
1882 (defun company-safe-substring (str from &optional to)
1883 (if (> from (string-width str))
1884 ""
1885 (with-temp-buffer
1886 (insert str)
1887 (move-to-column from)
1888 (let ((beg (point)))
1889 (if to
1890 (progn
1891 (move-to-column to)
1892 (concat (buffer-substring beg (point))
1893 (let ((padding (- to (current-column))))
1894 (when (> padding 0)
1895 (company-space-string padding)))))
1896 (buffer-substring beg (point-max)))))))
1897
1898 ;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;
1899
1900 (defvar-local company-last-metadata nil)
1901
1902 (defun company-fetch-metadata ()
1903 (let ((selected (nth company-selection company-candidates)))
1904 (unless (eq selected (car company-last-metadata))
1905 (setq company-last-metadata
1906 (cons selected (company-call-backend 'meta selected))))
1907 (cdr company-last-metadata)))
1908
1909 (defun company-doc-buffer (&optional string)
1910 (with-current-buffer (get-buffer-create "*company-documentation*")
1911 (erase-buffer)
1912 (when string
1913 (save-excursion
1914 (insert string)))
1915 (current-buffer)))
1916
1917 (defvar company--electric-commands
1918 '(scroll-other-window scroll-other-window-down)
1919 "List of Commands that won't break out of electric commands.")
1920
1921 (defmacro company--electric-do (&rest body)
1922 (declare (indent 0) (debug t))
1923 `(when (company-manual-begin)
1924 (save-window-excursion
1925 (let ((height (window-height))
1926 (row (company--row))
1927 cmd)
1928 ,@body
1929 (and (< (window-height) height)
1930 (< (- (window-height) row 2) company-tooltip-limit)
1931 (recenter (- (window-height) row 2)))
1932 (while (memq (setq cmd (key-binding (vector (list (read-event)))))
1933 company--electric-commands)
1934 (call-interactively cmd))
1935 (company--unread-last-input)))))
1936
1937 (defun company--unread-last-input ()
1938 (when last-input-event
1939 (clear-this-command-keys t)
1940 (setq unread-command-events (list last-input-event))))
1941
1942 (defun company-show-doc-buffer ()
1943 "Temporarily show the documentation buffer for the selection."
1944 (interactive)
1945 (company--electric-do
1946 (let* ((selected (nth company-selection company-candidates))
1947 (doc-buffer (or (company-call-backend 'doc-buffer selected)
1948 (error "No documentation available"))))
1949 (with-current-buffer doc-buffer
1950 (goto-char (point-min)))
1951 (display-buffer doc-buffer t))))
1952 (put 'company-show-doc-buffer 'company-keep t)
1953
1954 (defun company-show-location ()
1955 "Temporarily display a buffer showing the selected candidate in context."
1956 (interactive)
1957 (company--electric-do
1958 (let* ((selected (nth company-selection company-candidates))
1959 (location (company-call-backend 'location selected))
1960 (pos (or (cdr location) (error "No location available")))
1961 (buffer (or (and (bufferp (car location)) (car location))
1962 (find-file-noselect (car location) t))))
1963 (with-selected-window (display-buffer buffer t)
1964 (save-restriction
1965 (widen)
1966 (if (bufferp (car location))
1967 (goto-char pos)
1968 (goto-char (point-min))
1969 (forward-line (1- pos))))
1970 (set-window-start nil (point))))))
1971 (put 'company-show-location 'company-keep t)
1972
1973 ;;; package functions ;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;
1974
1975 (defvar-local company-callback nil)
1976
1977 (defun company-remove-callback (&optional ignored)
1978 (remove-hook 'company-completion-finished-hook company-callback t)
1979 (remove-hook 'company-completion-cancelled-hook 'company-remove-callback t)
1980 (remove-hook 'company-completion-finished-hook 'company-remove-callback t))
1981
1982 (defun company-begin-backend (backend &optional callback)
1983 "Start a completion at point using BACKEND."
1984 (interactive (let ((val (completing-read "Company back-end: "
1985 obarray
1986 'functionp nil "company-")))
1987 (when val
1988 (list (intern val)))))
1989 (when (setq company-callback callback)
1990 (add-hook 'company-completion-finished-hook company-callback nil t))
1991 (add-hook 'company-completion-cancelled-hook 'company-remove-callback nil t)
1992 (add-hook 'company-completion-finished-hook 'company-remove-callback nil t)
1993 (setq company-backend backend)
1994 ;; Return non-nil if active.
1995 (or (company-manual-begin)
1996 (error "Cannot complete at point")))
1997
1998 (defun company-begin-with (candidates
1999 &optional prefix-length require-match callback)
2000 "Start a completion at point.
2001 CANDIDATES is the list of candidates to use and PREFIX-LENGTH is the length
2002 of the prefix that already is in the buffer before point.
2003 It defaults to 0.
2004
2005 CALLBACK is a function called with the selected result if the user
2006 successfully completes the input.
2007
2008 Example: \(company-begin-with '\(\"foo\" \"foobar\" \"foobarbaz\"\)\)"
2009 (let ((begin-marker (copy-marker (point) t)))
2010 (company-begin-backend
2011 (lambda (command &optional arg &rest ignored)
2012 (pcase command
2013 (`prefix
2014 (when (equal (point) (marker-position begin-marker))
2015 (buffer-substring (- (point) (or prefix-length 0)) (point))))
2016 (`candidates
2017 (all-completions arg candidates))
2018 (`require-match
2019 require-match)))
2020 callback)))
2021
2022 (defun company-version (&optional show-version)
2023 "Get the Company version as string.
2024
2025 If SHOW-VERSION is non-nil, show the version in the echo area."
2026 (interactive (list t))
2027 (with-temp-buffer
2028 (insert-file-contents (find-library-name "company"))
2029 (require 'lisp-mnt)
2030 (if show-version
2031 (message "Company version: %s" (lm-version))
2032 (lm-version))))
2033
2034 ;;; pseudo-tooltip ;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;
2035
2036 (defvar-local company-pseudo-tooltip-overlay nil)
2037
2038 (defvar-local company-tooltip-offset 0)
2039
2040 (defun company-tooltip--lines-update-offset (selection num-lines limit)
2041 (cl-decf limit 2)
2042 (setq company-tooltip-offset
2043 (max (min selection company-tooltip-offset)
2044 (- selection -1 limit)))
2045
2046 (when (<= company-tooltip-offset 1)
2047 (cl-incf limit)
2048 (setq company-tooltip-offset 0))
2049
2050 (when (>= company-tooltip-offset (- num-lines limit 1))
2051 (cl-incf limit)
2052 (when (= selection (1- num-lines))
2053 (cl-decf company-tooltip-offset)
2054 (when (<= company-tooltip-offset 1)
2055 (setq company-tooltip-offset 0)
2056 (cl-incf limit))))
2057
2058 limit)
2059
2060 (defun company-tooltip--simple-update-offset (selection _num-lines limit)
2061 (setq company-tooltip-offset
2062 (if (< selection company-tooltip-offset)
2063 selection
2064 (max company-tooltip-offset
2065 (- selection limit -1)))))
2066
2067 ;;; propertize
2068
2069 (defsubst company-round-tab (arg)
2070 (* (/ (+ arg tab-width) tab-width) tab-width))
2071
2072 (defun company-plainify (str)
2073 (let ((prefix (get-text-property 0 'line-prefix str)))
2074 (when prefix ; Keep the original value unmodified, for no special reason.
2075 (setq str (concat prefix str))
2076 (remove-text-properties 0 (length str) '(line-prefix) str)))
2077 (let* ((pieces (split-string str "\t"))
2078 (copy pieces))
2079 (while (cdr copy)
2080 (setcar copy (company-safe-substring
2081 (car copy) 0 (company-round-tab (string-width (car copy)))))
2082 (pop copy))
2083 (apply 'concat pieces)))
2084
2085 (defun company-fill-propertize (value annotation width selected left right)
2086 (let* ((margin (length left))
2087 (common (or (company-call-backend 'match value)
2088 (length company-common)))
2089 (ann-ralign company-tooltip-align-annotations)
2090 (ann-truncate (< width
2091 (+ (length value) (length annotation)
2092 (if ann-ralign 1 0))))
2093 (ann-start (+ margin
2094 (if ann-ralign
2095 (if ann-truncate
2096 (1+ (length value))
2097 (- width (length annotation)))
2098 (length value))))
2099 (ann-end (min (+ ann-start (length annotation)) (+ margin width)))
2100 (line (concat left
2101 (if (or ann-truncate (not ann-ralign))
2102 (company-safe-substring
2103 (concat value
2104 (when (and annotation ann-ralign) " ")
2105 annotation)
2106 0 width)
2107 (concat
2108 (company-safe-substring value 0
2109 (- width (length annotation)))
2110 annotation))
2111 right)))
2112 (setq common (+ (min common width) margin))
2113 (setq width (+ width margin (length right)))
2114
2115 (add-text-properties 0 width '(face company-tooltip
2116 mouse-face company-tooltip-mouse)
2117 line)
2118 (add-text-properties margin common
2119 '(face company-tooltip-common
2120 mouse-face company-tooltip-mouse)
2121 line)
2122 (when (< ann-start ann-end)
2123 (add-text-properties ann-start ann-end
2124 '(face company-tooltip-annotation
2125 mouse-face company-tooltip-mouse)
2126 line))
2127 (when selected
2128 (if (and company-search-string
2129 (string-match (regexp-quote company-search-string) value
2130 (length company-prefix)))
2131 (let ((beg (+ margin (match-beginning 0)))
2132 (end (+ margin (match-end 0))))
2133 (add-text-properties beg end '(face company-tooltip-search)
2134 line)
2135 (when (< beg common)
2136 (add-text-properties beg common
2137 '(face company-tooltip-common-selection)
2138 line)))
2139 (add-text-properties 0 width '(face company-tooltip-selection
2140 mouse-face company-tooltip-selection)
2141 line)
2142 (add-text-properties margin common
2143 '(face company-tooltip-common-selection
2144 mouse-face company-tooltip-selection)
2145 line)))
2146 line))
2147
2148 ;;; replace
2149
2150 (defun company-buffer-lines (beg end)
2151 (goto-char beg)
2152 (let (lines lines-moved)
2153 (while (and (> (setq lines-moved (vertical-motion 1)) 0)
2154 (<= (point) end))
2155 (let ((bound (min end (1- (point)))))
2156 ;; A visual line can contain several physical lines (e.g. with outline's
2157 ;; folding overlay). Take only the first one.
2158 (push (buffer-substring beg
2159 (save-excursion
2160 (goto-char beg)
2161 (re-search-forward "$" bound 'move)
2162 (point)))
2163 lines))
2164 ;; One physical line can be displayed as several visual ones as well:
2165 ;; add empty strings to the list, to even the count.
2166 (dotimes (_ (1- lines-moved))
2167 (push "" lines))
2168 (setq beg (point)))
2169 (unless (eq beg end)
2170 (push (buffer-substring beg end) lines))
2171 (nreverse lines)))
2172
2173 (defun company-modify-line (old new offset)
2174 (concat (company-safe-substring old 0 offset)
2175 new
2176 (company-safe-substring old (+ offset (length new)))))
2177
2178 (defsubst company--length-limit (lst limit)
2179 (if (nthcdr limit lst)
2180 limit
2181 (length lst)))
2182
2183 (defun company--replacement-string (lines old column nl &optional align-top)
2184 (cl-decf column company-tooltip-margin)
2185
2186 (when (and align-top company-tooltip-flip-when-above)
2187 (setq lines (reverse lines)))
2188
2189 (let ((width (length (car lines)))
2190 (remaining-cols (- (+ (company--window-width) (window-hscroll))
2191 column)))
2192 (when (> width remaining-cols)
2193 (cl-decf column (- width remaining-cols))))
2194
2195 (let ((offset (and (< column 0) (- column)))
2196 new)
2197 (when offset
2198 (setq column 0))
2199 (when align-top
2200 ;; untouched lines first
2201 (dotimes (_ (- (length old) (length lines)))
2202 (push (pop old) new)))
2203 ;; length into old lines.
2204 (while old
2205 (push (company-modify-line (pop old)
2206 (company--offset-line (pop lines) offset)
2207 column) new))
2208 ;; Append whole new lines.
2209 (while lines
2210 (push (concat (company-space-string column)
2211 (company--offset-line (pop lines) offset))
2212 new))
2213
2214 (let ((str (concat (when nl " ")
2215 "\n"
2216 (mapconcat 'identity (nreverse new) "\n")
2217 "\n")))
2218 (font-lock-append-text-property 0 (length str) 'face 'default str)
2219 (when nl (put-text-property 0 1 'cursor t str))
2220 str)))
2221
2222 (defun company--offset-line (line offset)
2223 (if (and offset line)
2224 (substring line offset)
2225 line))
2226
2227 (defun company--create-lines (selection limit)
2228 (let ((len company-candidates-length)
2229 (numbered 99999)
2230 (window-width (company--window-width))
2231 lines
2232 width
2233 lines-copy
2234 items
2235 previous
2236 remainder
2237 scrollbar-bounds)
2238
2239 ;; Maybe clear old offset.
2240 (when (< len (+ company-tooltip-offset limit))
2241 (setq company-tooltip-offset 0))
2242
2243 ;; Scroll to offset.
2244 (if (eq company-tooltip-offset-display 'lines)
2245 (setq limit (company-tooltip--lines-update-offset selection len limit))
2246 (company-tooltip--simple-update-offset selection len limit))
2247
2248 (cond
2249 ((eq company-tooltip-offset-display 'scrollbar)
2250 (setq scrollbar-bounds (company--scrollbar-bounds company-tooltip-offset
2251 limit len)))
2252 ((eq company-tooltip-offset-display 'lines)
2253 (when (> company-tooltip-offset 0)
2254 (setq previous (format "...(%d)" company-tooltip-offset)))
2255 (setq remainder (- len limit company-tooltip-offset)
2256 remainder (when (> remainder 0)
2257 (setq remainder (format "...(%d)" remainder))))))
2258
2259 (cl-decf selection company-tooltip-offset)
2260 (setq width (max (length previous) (length remainder))
2261 lines (nthcdr company-tooltip-offset company-candidates)
2262 len (min limit len)
2263 lines-copy lines)
2264
2265 (cl-decf window-width (* 2 company-tooltip-margin))
2266 (when scrollbar-bounds (cl-decf window-width))
2267
2268 (dotimes (_ len)
2269 (let* ((value (pop lines-copy))
2270 (annotation (company-call-backend 'annotation value)))
2271 (when (and annotation company-tooltip-align-annotations)
2272 ;; `lisp-completion-at-point' adds a space.
2273 (setq annotation (comment-string-strip annotation t nil)))
2274 (push (cons value annotation) items)
2275 (setq width (max (+ (length value)
2276 (if (and annotation company-tooltip-align-annotations)
2277 (1+ (length annotation))
2278 (length annotation)))
2279 width))))
2280
2281 (setq width (min window-width
2282 (max company-tooltip-minimum-width
2283 (if (and company-show-numbers
2284 (< company-tooltip-offset 10))
2285 (+ 2 width)
2286 width))))
2287
2288 ;; number can make tooltip too long
2289 (when company-show-numbers
2290 (setq numbered company-tooltip-offset))
2291
2292 (let ((items (nreverse items)) new)
2293 (when previous
2294 (push (company--scrollpos-line previous width) new))
2295
2296 (dotimes (i len)
2297 (let* ((item (pop items))
2298 (str (company-reformat (car item)))
2299 (annotation (cdr item))
2300 (right (company-space-string company-tooltip-margin))
2301 (width width))
2302 (when (< numbered 10)
2303 (cl-decf width 2)
2304 (cl-incf numbered)
2305 (setq right (concat (format " %d" (mod numbered 10)) right)))
2306 (push (concat
2307 (company-fill-propertize str annotation
2308 width (equal i selection)
2309 (company-space-string
2310 company-tooltip-margin)
2311 right)
2312 (when scrollbar-bounds
2313 (company--scrollbar i scrollbar-bounds)))
2314 new)))
2315
2316 (when remainder
2317 (push (company--scrollpos-line remainder width) new))
2318
2319 (nreverse new))))
2320
2321 (defun company--scrollbar-bounds (offset limit length)
2322 (when (> length limit)
2323 (let* ((size (ceiling (* limit (float limit)) length))
2324 (lower (floor (* limit (float offset)) length))
2325 (upper (+ lower size -1)))
2326 (cons lower upper))))
2327
2328 (defun company--scrollbar (i bounds)
2329 (propertize " " 'face
2330 (if (and (>= i (car bounds)) (<= i (cdr bounds)))
2331 'company-scrollbar-fg
2332 'company-scrollbar-bg)))
2333
2334 (defun company--scrollpos-line (text width)
2335 (propertize (concat (company-space-string company-tooltip-margin)
2336 (company-safe-substring text 0 width)
2337 (company-space-string company-tooltip-margin))
2338 'face 'company-tooltip))
2339
2340 ;; show
2341
2342 (defsubst company--window-height ()
2343 (if (fboundp 'window-screen-lines)
2344 (floor (window-screen-lines))
2345 (window-body-height)))
2346
2347 (defsubst company--window-width ()
2348 (let ((ww (window-body-width)))
2349 ;; Account for the line continuation column.
2350 (when (zerop (cadr (window-fringes)))
2351 (cl-decf ww))
2352 (unless (or (display-graphic-p)
2353 (version< "24.3.1" emacs-version))
2354 ;; Emacs 24.3 and earlier included margins
2355 ;; in window-width when in TTY.
2356 (cl-decf ww
2357 (let ((margins (window-margins)))
2358 (+ (or (car margins) 0)
2359 (or (cdr margins) 0)))))
2360 ww))
2361
2362 (defun company--pseudo-tooltip-height ()
2363 "Calculate the appropriate tooltip height.
2364 Returns a negative number if the tooltip should be displayed above point."
2365 (let* ((lines (company--row))
2366 (below (- (company--window-height) 1 lines)))
2367 (if (and (< below (min company-tooltip-minimum company-candidates-length))
2368 (> lines below))
2369 (- (max 3 (min company-tooltip-limit lines)))
2370 (max 3 (min company-tooltip-limit below)))))
2371
2372 (defun company-pseudo-tooltip-show (row column selection)
2373 (company-pseudo-tooltip-hide)
2374 (save-excursion
2375
2376 (let* ((height (company--pseudo-tooltip-height))
2377 above)
2378
2379 (when (< height 0)
2380 (setq row (+ row height -1)
2381 above t))
2382
2383 (let* ((nl (< (move-to-window-line row) row))
2384 (beg (point))
2385 (end (save-excursion
2386 (move-to-window-line (+ row (abs height)))
2387 (point)))
2388 (ov (make-overlay (if nl beg (1- beg)) end))
2389 (args (list (mapcar 'company-plainify
2390 (company-buffer-lines beg end))
2391 column nl above)))
2392
2393 (setq company-pseudo-tooltip-overlay ov)
2394 (overlay-put ov 'company-replacement-args args)
2395
2396 (let ((lines (company--create-lines selection (abs height))))
2397 (overlay-put ov 'company-display
2398 (apply 'company--replacement-string lines args))
2399 (overlay-put ov 'company-width (string-width (car lines))))
2400
2401 (overlay-put ov 'company-column column)
2402 (overlay-put ov 'company-height height)))))
2403
2404 (defun company-pseudo-tooltip-show-at-point (pos column-offset)
2405 (let* ((col-row (company--col-row pos))
2406 (col (- (car col-row) column-offset)))
2407 (when (< col 0) (setq col 0))
2408 (company-pseudo-tooltip-show (1+ (cdr col-row)) col company-selection)))
2409
2410 (defun company-pseudo-tooltip-edit (selection)
2411 (let* ((height (overlay-get company-pseudo-tooltip-overlay 'company-height))
2412 (lines (company--create-lines selection (abs height))))
2413 (overlay-put company-pseudo-tooltip-overlay 'company-width
2414 (string-width (car lines)))
2415 (overlay-put company-pseudo-tooltip-overlay 'company-display
2416 (apply 'company--replacement-string
2417 lines
2418 (overlay-get company-pseudo-tooltip-overlay
2419 'company-replacement-args)))))
2420
2421 (defun company-pseudo-tooltip-hide ()
2422 (when company-pseudo-tooltip-overlay
2423 (delete-overlay company-pseudo-tooltip-overlay)
2424 (setq company-pseudo-tooltip-overlay nil)))
2425
2426 (defun company-pseudo-tooltip-hide-temporarily ()
2427 (when (overlayp company-pseudo-tooltip-overlay)
2428 (overlay-put company-pseudo-tooltip-overlay 'invisible nil)
2429 (overlay-put company-pseudo-tooltip-overlay 'after-string nil)))
2430
2431 (defun company-pseudo-tooltip-unhide ()
2432 (when company-pseudo-tooltip-overlay
2433 (let* ((ov company-pseudo-tooltip-overlay)
2434 (disp (overlay-get ov 'company-display)))
2435 ;; Beat outline's folding overlays, at least.
2436 (overlay-put ov 'priority 1)
2437 ;; `display' could be better (http://debbugs.gnu.org/18285), but it
2438 ;; doesn't work when the overlay is empty, which is what happens at eob.
2439 ;; It also seems to interact badly with `cursor'.
2440 ;; We deal with priorities by having the overlay start before the newline.
2441 (overlay-put ov 'after-string disp)
2442 (overlay-put ov 'invisible t)
2443 (overlay-put ov 'window (selected-window)))))
2444
2445 (defun company-pseudo-tooltip-guard ()
2446 (list
2447 (save-excursion (beginning-of-visual-line))
2448 (let ((ov company-pseudo-tooltip-overlay))
2449 (when (>= (overlay-get ov 'company-height) 0)
2450 (buffer-substring-no-properties (point) (overlay-start ov))))))
2451
2452 (defun company-pseudo-tooltip-frontend (command)
2453 "`company-mode' front-end similar to a tooltip but based on overlays."
2454 (cl-case command
2455 (pre-command (company-pseudo-tooltip-hide-temporarily))
2456 (post-command
2457 (unless (when (overlayp company-pseudo-tooltip-overlay)
2458 (let* ((ov company-pseudo-tooltip-overlay)
2459 (old-height (overlay-get ov 'company-height))
2460 (new-height (company--pseudo-tooltip-height)))
2461 (and
2462 (>= (* old-height new-height) 0)
2463 (>= (abs old-height) (abs new-height))
2464 (equal (company-pseudo-tooltip-guard)
2465 (overlay-get ov 'company-guard)))))
2466 ;; Redraw needed.
2467 (company-pseudo-tooltip-show-at-point (point) (length company-prefix))
2468 (overlay-put company-pseudo-tooltip-overlay
2469 'company-guard (company-pseudo-tooltip-guard)))
2470 (company-pseudo-tooltip-unhide))
2471 (hide (company-pseudo-tooltip-hide)
2472 (setq company-tooltip-offset 0))
2473 (update (when (overlayp company-pseudo-tooltip-overlay)
2474 (company-pseudo-tooltip-edit company-selection)))))
2475
2476 (defun company-pseudo-tooltip-unless-just-one-frontend (command)
2477 "`company-pseudo-tooltip-frontend', but not shown for single candidates."
2478 (unless (and (eq command 'post-command)
2479 (company--show-inline-p))
2480 (company-pseudo-tooltip-frontend command)))
2481
2482 ;;; overlay ;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;
2483
2484 (defvar-local company-preview-overlay nil)
2485
2486 (defun company-preview-show-at-point (pos)
2487 (company-preview-hide)
2488
2489 (setq company-preview-overlay (make-overlay pos pos))
2490
2491 (let ((completion (nth company-selection company-candidates)))
2492 (setq completion (propertize completion 'face 'company-preview))
2493 (add-text-properties 0 (length company-common)
2494 '(face company-preview-common) completion)
2495
2496 ;; Add search string
2497 (and company-search-string
2498 (string-match (regexp-quote company-search-string) completion)
2499 (add-text-properties (match-beginning 0)
2500 (match-end 0)
2501 '(face company-preview-search)
2502 completion))
2503
2504 (setq completion (company-strip-prefix completion))
2505
2506 (and (equal pos (point))
2507 (not (equal completion ""))
2508 (add-text-properties 0 1 '(cursor t) completion))
2509
2510 (let ((ov company-preview-overlay))
2511 (overlay-put ov 'after-string completion)
2512 (overlay-put ov 'window (selected-window)))))
2513
2514 (defun company-preview-hide ()
2515 (when company-preview-overlay
2516 (delete-overlay company-preview-overlay)
2517 (setq company-preview-overlay nil)))
2518
2519 (defun company-preview-frontend (command)
2520 "`company-mode' front-end showing the selection as if it had been inserted."
2521 (pcase command
2522 (`pre-command (company-preview-hide))
2523 (`post-command (company-preview-show-at-point (point)))
2524 (`hide (company-preview-hide))))
2525
2526 (defun company-preview-if-just-one-frontend (command)
2527 "`company-preview-frontend', but only shown for single candidates."
2528 (when (or (not (eq command 'post-command))
2529 (company--show-inline-p))
2530 (company-preview-frontend command)))
2531
2532 (defun company--show-inline-p ()
2533 (and (not (cdr company-candidates))
2534 company-common
2535 (or (eq (company-call-backend 'ignore-case) 'keep-prefix)
2536 (string-prefix-p company-prefix company-common))))
2537
2538 ;;; echo ;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;
2539
2540 (defvar-local company-echo-last-msg nil)
2541
2542 (defvar company-echo-timer nil)
2543
2544 (defvar company-echo-delay .01)
2545
2546 (defun company-echo-show (&optional getter)
2547 (when getter
2548 (setq company-echo-last-msg (funcall getter)))
2549 (let ((message-log-max nil))
2550 (if company-echo-last-msg
2551 (message "%s" company-echo-last-msg)
2552 (message ""))))
2553
2554 (defun company-echo-show-soon (&optional getter)
2555 (when company-echo-timer
2556 (cancel-timer company-echo-timer))
2557 (setq company-echo-timer (run-with-timer 0 nil 'company-echo-show getter)))
2558
2559 (defsubst company-echo-show-when-idle (&optional getter)
2560 (when (sit-for company-echo-delay)
2561 (company-echo-show getter)))
2562
2563 (defun company-echo-format ()
2564
2565 (let ((limit (window-body-width (minibuffer-window)))
2566 (len -1)
2567 ;; Roll to selection.
2568 (candidates (nthcdr company-selection company-candidates))
2569 (i (if company-show-numbers company-selection 99999))
2570 comp msg)
2571
2572 (while candidates
2573 (setq comp (company-reformat (pop candidates))
2574 len (+ len 1 (length comp)))
2575 (if (< i 10)
2576 ;; Add number.
2577 (progn
2578 (setq comp (propertize (format "%d: %s" i comp)
2579 'face 'company-echo))
2580 (cl-incf len 3)
2581 (cl-incf i)
2582 (add-text-properties 3 (+ 3 (length company-common))
2583 '(face company-echo-common) comp))
2584 (setq comp (propertize comp 'face 'company-echo))
2585 (add-text-properties 0 (length company-common)
2586 '(face company-echo-common) comp))
2587 (if (>= len limit)
2588 (setq candidates nil)
2589 (push comp msg)))
2590
2591 (mapconcat 'identity (nreverse msg) " ")))
2592
2593 (defun company-echo-strip-common-format ()
2594
2595 (let ((limit (window-body-width (minibuffer-window)))
2596 (len (+ (length company-prefix) 2))
2597 ;; Roll to selection.
2598 (candidates (nthcdr company-selection company-candidates))
2599 (i (if company-show-numbers company-selection 99999))
2600 msg comp)
2601
2602 (while candidates
2603 (setq comp (company-strip-prefix (pop candidates))
2604 len (+ len 2 (length comp)))
2605 (when (< i 10)
2606 ;; Add number.
2607 (setq comp (format "%s (%d)" comp i))
2608 (cl-incf len 4)
2609 (cl-incf i))
2610 (if (>= len limit)
2611 (setq candidates nil)
2612 (push (propertize comp 'face 'company-echo) msg)))
2613
2614 (concat (propertize company-prefix 'face 'company-echo-common) "{"
2615 (mapconcat 'identity (nreverse msg) ", ")
2616 "}")))
2617
2618 (defun company-echo-hide ()
2619 (unless (equal company-echo-last-msg "")
2620 (setq company-echo-last-msg "")
2621 (company-echo-show)))
2622
2623 (defun company-echo-frontend (command)
2624 "`company-mode' front-end showing the candidates in the echo area."
2625 (pcase command
2626 (`post-command (company-echo-show-soon 'company-echo-format))
2627 (`hide (company-echo-hide))))
2628
2629 (defun company-echo-strip-common-frontend (command)
2630 "`company-mode' front-end showing the candidates in the echo area."
2631 (pcase command
2632 (`post-command (company-echo-show-soon 'company-echo-strip-common-format))
2633 (`hide (company-echo-hide))))
2634
2635 (defun company-echo-metadata-frontend (command)
2636 "`company-mode' front-end showing the documentation in the echo area."
2637 (pcase command
2638 (`post-command (company-echo-show-when-idle 'company-fetch-metadata))
2639 (`hide (company-echo-hide))))
2640
2641 (provide 'company)
2642 ;;; company.el ends here