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