]> code.delx.au - gnu-emacs-elpa/blob - company.el
+1 char, -1 line
[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 A value of nil means no idle completion, t means show candidates
548 immediately when a prefix of `company-minimum-prefix-length' is reached."
549 :type '(choice (const :tag "never (nil)" nil)
550 (const :tag "immediate (t)" t)
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 (add-hook 'pre-command-hook 'company-pre-command nil t)
696 (add-hook 'post-command-hook 'company-post-command nil t)
697 (mapc 'company-init-backend company-backends))
698 (remove-hook 'pre-command-hook 'company-pre-command t)
699 (remove-hook 'post-command-hook 'company-post-command t)
700 (company-cancel)
701 (kill-local-variable 'company-point)))
702
703 (defcustom company-global-modes t
704 "Modes for which `company-mode' mode is turned on by `global-company-mode'.
705 If nil, means no modes. If t, then all major modes have it turned on.
706 If a list, it should be a list of `major-mode' symbol names for which
707 `company-mode' should be automatically turned on. The sense of the list is
708 negated if it begins with `not'. For example:
709 (c-mode c++-mode)
710 means that `company-mode' is turned on for buffers in C and C++ modes only.
711 (not message-mode)
712 means that `company-mode' is always turned on except in `message-mode' buffers."
713 :type '(choice (const :tag "none" nil)
714 (const :tag "all" t)
715 (set :menu-tag "mode specific" :tag "modes"
716 :value (not)
717 (const :tag "Except" not)
718 (repeat :inline t (symbol :tag "mode")))))
719
720 ;;;###autoload
721 (define-globalized-minor-mode global-company-mode company-mode company-mode-on)
722
723 (defun company-mode-on ()
724 (when (and (not (or noninteractive (eq (aref (buffer-name) 0) ?\s)))
725 (cond ((eq company-global-modes t)
726 t)
727 ((eq (car-safe company-global-modes) 'not)
728 (not (memq major-mode (cdr company-global-modes))))
729 (t (memq major-mode company-global-modes))))
730 (company-mode 1)))
731
732 (defsubst company-assert-enabled ()
733 (unless company-mode
734 (company-uninstall-map)
735 (error "Company not enabled")))
736
737 ;;; keymaps ;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;
738
739 (defvar-local company-my-keymap nil)
740
741 (defvar company-emulation-alist '((t . nil)))
742
743 (defsubst company-enable-overriding-keymap (keymap)
744 (company-uninstall-map)
745 (setq company-my-keymap keymap))
746
747 (defun company-ensure-emulation-alist ()
748 (unless (eq 'company-emulation-alist (car emulation-mode-map-alists))
749 (setq emulation-mode-map-alists
750 (cons 'company-emulation-alist
751 (delq 'company-emulation-alist emulation-mode-map-alists)))))
752
753 (defun company-install-map ()
754 (unless (or (cdar company-emulation-alist)
755 (null company-my-keymap))
756 (setf (cdar company-emulation-alist) company-my-keymap)))
757
758 (defun company-uninstall-map ()
759 (setf (cdar company-emulation-alist) nil))
760
761 ;; Hack:
762 ;; Emacs calculates the active keymaps before reading the event. That means we
763 ;; cannot change the keymap from a timer. So we send a bogus command.
764 ;; XXX: Seems not to be needed anymore in Emacs 24.4
765 (defun company-ignore ()
766 (interactive)
767 (setq this-command last-command))
768
769 (global-set-key '[31415926] 'company-ignore)
770
771 (defun company-input-noop ()
772 (push 31415926 unread-command-events))
773
774 (defun company--column (&optional pos)
775 (save-excursion
776 (when pos (goto-char pos))
777 (save-restriction
778 (+ (save-excursion
779 (vertical-motion 0)
780 (narrow-to-region (point) (point-max))
781 (let ((prefix (get-text-property (point) 'line-prefix)))
782 (if prefix (length prefix) 0)))
783 (current-column)))))
784
785 (defun company--row (&optional pos)
786 (save-excursion
787 (when pos (goto-char pos))
788 (count-screen-lines (window-start)
789 (progn (vertical-motion 0) (point)))))
790
791 ;;; backends ;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;
792
793 (defvar-local company-backend nil)
794
795 (defun company-grab (regexp &optional expression limit)
796 (when (looking-back regexp limit)
797 (or (match-string-no-properties (or expression 0)) "")))
798
799 (defun company-grab-line (regexp &optional expression)
800 (company-grab regexp expression (point-at-bol)))
801
802 (defun company-grab-symbol ()
803 (if (looking-at "\\_>")
804 (buffer-substring (point) (save-excursion (skip-syntax-backward "w_")
805 (point)))
806 (unless (and (char-after) (memq (char-syntax (char-after)) '(?w ?_)))
807 "")))
808
809 (defun company-grab-word ()
810 (if (looking-at "\\>")
811 (buffer-substring (point) (save-excursion (skip-syntax-backward "w")
812 (point)))
813 (unless (and (char-after) (eq (char-syntax (char-after)) ?w))
814 "")))
815
816 (defun company-grab-symbol-cons (idle-begin-after-re &optional max-len)
817 (let ((symbol (company-grab-symbol)))
818 (when symbol
819 (save-excursion
820 (forward-char (- (length symbol)))
821 (if (looking-back idle-begin-after-re (if max-len
822 (- (point) max-len)
823 (line-beginning-position)))
824 (cons symbol t)
825 symbol)))))
826
827 (defun company-in-string-or-comment ()
828 (let ((ppss (syntax-ppss)))
829 (or (car (setq ppss (nthcdr 3 ppss)))
830 (car (setq ppss (cdr ppss)))
831 (nth 3 ppss))))
832
833 (defun company-call-backend (&rest args)
834 (company--force-sync #'company-call-backend-raw args company-backend))
835
836 (defun company--force-sync (fun args backend)
837 (let ((value (apply fun args)))
838 (if (not (eq (car-safe value) :async))
839 value
840 (let ((res 'trash)
841 (start (time-to-seconds)))
842 (funcall (cdr value)
843 (lambda (result) (setq res result)))
844 (while (eq res 'trash)
845 (if (> (- (time-to-seconds) start) company-async-timeout)
846 (error "Company: Back-end %s async timeout with args %s"
847 backend args)
848 (sleep-for company-async-wait)))
849 res))))
850
851 (defun company-call-backend-raw (&rest args)
852 (condition-case err
853 (if (functionp company-backend)
854 (apply company-backend args)
855 (apply #'company--multi-backend-adapter company-backend args))
856 (error (error "Company: Back-end %s error \"%s\" with args %s"
857 company-backend (error-message-string err) args))))
858
859 (defun company--multi-backend-adapter (backends command &rest args)
860 (let ((backends (cl-loop for b in backends
861 when (not (and (symbolp b)
862 (eq 'failed (get b 'company-init))))
863 collect b)))
864 (setq backends
865 (if (eq command 'prefix)
866 (butlast backends (length (member :with backends)))
867 (delq :with backends)))
868 (pcase command
869 (`candidates
870 (company--multi-backend-adapter-candidates backends (car args)))
871 (`sorted nil)
872 (`duplicates t)
873 ((or `prefix `ignore-case `no-cache `require-match)
874 (let (value)
875 (cl-dolist (backend backends)
876 (when (setq value (company--force-sync
877 backend (cons command args) backend))
878 (cl-return value)))))
879 (_
880 (let ((arg (car args)))
881 (when (> (length arg) 0)
882 (let ((backend (or (get-text-property 0 'company-backend arg)
883 (car backends))))
884 (apply backend command args))))))))
885
886 (defun company--multi-backend-adapter-candidates (backends prefix)
887 (let ((pairs (cl-loop for backend in (cdr backends)
888 when (equal (company--prefix-str
889 (funcall backend 'prefix))
890 prefix)
891 collect (cons (funcall backend 'candidates prefix)
892 (let ((b backend))
893 (lambda (candidates)
894 (mapcar
895 (lambda (str)
896 (propertize str 'company-backend b))
897 candidates)))))))
898 (when (equal (company--prefix-str (funcall (car backends) 'prefix)) prefix)
899 ;; Small perf optimization: don't tag the candidates received
900 ;; from the first backend in the group.
901 (push (cons (funcall (car backends) 'candidates prefix)
902 'identity)
903 pairs))
904 (company--merge-async pairs (lambda (values) (apply #'append values)))))
905
906 (defun company--merge-async (pairs merger)
907 (let ((async (cl-loop for pair in pairs
908 thereis
909 (eq :async (car-safe (car pair))))))
910 (if (not async)
911 (funcall merger (cl-loop for (val . mapper) in pairs
912 collect (funcall mapper val)))
913 (cons
914 :async
915 (lambda (callback)
916 (let* (lst pending
917 (finisher (lambda ()
918 (unless pending
919 (funcall callback
920 (funcall merger
921 (nreverse lst)))))))
922 (dolist (pair pairs)
923 (let ((val (car pair))
924 (mapper (cdr pair)))
925 (if (not (eq :async (car-safe val)))
926 (push (funcall mapper val) lst)
927 (push nil lst)
928 (let ((cell lst)
929 (fetcher (cdr val)))
930 (push fetcher pending)
931 (funcall fetcher
932 (lambda (res)
933 (setq pending (delq fetcher pending))
934 (setcar cell (funcall mapper res))
935 (funcall finisher)))))))))))))
936
937 (defun company--prefix-str (prefix)
938 (or (car-safe prefix) prefix))
939
940 ;;; completion mechanism ;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;
941
942 (defvar-local company-prefix nil)
943
944 (defvar-local company-candidates nil)
945
946 (defvar-local company-candidates-length nil)
947
948 (defvar-local company-candidates-cache nil)
949
950 (defvar-local company-candidates-predicate nil)
951
952 (defvar-local company-common nil)
953
954 (defvar-local company-selection 0)
955
956 (defvar-local company-selection-changed nil)
957
958 (defvar-local company--manual-action nil
959 "Non-nil, if manual completion took place.")
960
961 (defvar-local company--manual-prefix nil)
962
963 (defvar company--auto-completion nil
964 "Non-nil when current candidate is being inserted automatically.
965 Controlled by `company-auto-complete'.")
966
967 (defvar-local company--point-max nil)
968
969 (defvar-local company-point nil)
970
971 (defvar company-timer nil)
972
973 (defvar-local company-added-newline nil)
974
975 (defsubst company-strip-prefix (str)
976 (substring str (length company-prefix)))
977
978 (defun company--insert-candidate (candidate)
979 (setq candidate (substring-no-properties candidate))
980 ;; XXX: Return value we check here is subject to change.
981 (if (eq (company-call-backend 'ignore-case) 'keep-prefix)
982 (insert (company-strip-prefix candidate))
983 (delete-region (- (point) (length company-prefix)) (point))
984 (insert candidate)))
985
986 (defmacro company-with-candidate-inserted (candidate &rest body)
987 "Evaluate BODY with CANDIDATE temporarily inserted.
988 This is a tool for back-ends that need candidates inserted before they
989 can retrieve meta-data for them."
990 (declare (indent 1))
991 `(let ((inhibit-modification-hooks t)
992 (inhibit-point-motion-hooks t)
993 (modified-p (buffer-modified-p)))
994 (company--insert-candidate ,candidate)
995 (unwind-protect
996 (progn ,@body)
997 (delete-region company-point (point)))))
998
999 (defun company-explicit-action-p ()
1000 "Return whether explicit completion action was taken by the user."
1001 (or company--manual-action
1002 company-selection-changed))
1003
1004 (defun company-reformat (candidate)
1005 ;; company-ispell needs this, because the results are always lower-case
1006 ;; It's mory efficient to fix it only when they are displayed.
1007 ;; FIXME: Adopt the current text's capitalization instead?
1008 (if (eq (company-call-backend 'ignore-case) 'keep-prefix)
1009 (concat company-prefix (substring candidate (length company-prefix)))
1010 candidate))
1011
1012 (defun company--should-complete ()
1013 (and (eq company-idle-delay t)
1014 (not (or buffer-read-only overriding-terminal-local-map
1015 overriding-local-map))
1016 ;; Check if in the middle of entering a key combination.
1017 (or (equal (this-command-keys-vector) [])
1018 (not (keymapp (key-binding (this-command-keys-vector)))))
1019 (not (and transient-mark-mode mark-active))))
1020
1021 (defun company--should-continue ()
1022 (or (eq t company-begin-commands)
1023 (eq t company-continue-commands)
1024 (if (eq 'not (car company-continue-commands))
1025 (not (memq this-command (cdr company-continue-commands)))
1026 (or (memq this-command company-begin-commands)
1027 (memq this-command company-continue-commands)
1028 (and (symbolp this-command)
1029 (string-match-p "\\`company-" (symbol-name this-command)))))))
1030
1031 (defun company-call-frontends (command)
1032 (dolist (frontend company-frontends)
1033 (condition-case err
1034 (funcall frontend command)
1035 (error (error "Company: Front-end %s error \"%s\" on command %s"
1036 frontend (error-message-string err) command)))))
1037
1038 (defun company-set-selection (selection &optional force-update)
1039 (setq selection
1040 (if company-selection-wrap-around
1041 (mod selection company-candidates-length)
1042 (max 0 (min (1- company-candidates-length) selection))))
1043 (when (or force-update (not (equal selection company-selection)))
1044 (company--update-group-lighter (nth selection company-candidates))
1045 (setq company-selection selection
1046 company-selection-changed t)
1047 (company-call-frontends 'update)))
1048
1049 (defun company--update-group-lighter (candidate)
1050 (when (listp company-backend)
1051 (let ((backend (or (get-text-property 0 'company-backend candidate)
1052 (car company-backend))))
1053 (when (and backend (symbolp backend))
1054 (let ((name (replace-regexp-in-string "company-\\|-company" ""
1055 (symbol-name backend))))
1056 (setq company-lighter (format " company-<%s>" name)))))))
1057
1058 (defun company-apply-predicate (candidates predicate)
1059 (let (new)
1060 (dolist (c candidates)
1061 (when (funcall predicate c)
1062 (push c new)))
1063 (nreverse new)))
1064
1065 (defun company-update-candidates (candidates)
1066 (setq company-candidates-length (length candidates))
1067 (if (> company-selection 0)
1068 ;; Try to restore the selection
1069 (let ((selected (nth company-selection company-candidates)))
1070 (setq company-selection 0
1071 company-candidates candidates)
1072 (when selected
1073 (while (and candidates (string< (pop candidates) selected))
1074 (cl-incf company-selection))
1075 (unless candidates
1076 ;; Make sure selection isn't out of bounds.
1077 (setq company-selection (min (1- company-candidates-length)
1078 company-selection)))))
1079 (setq company-selection 0
1080 company-candidates candidates))
1081 ;; Save in cache:
1082 (push (cons company-prefix company-candidates) company-candidates-cache)
1083 ;; Calculate common.
1084 (let ((completion-ignore-case (company-call-backend 'ignore-case)))
1085 ;; We want to support non-prefix completion, so filtering is the
1086 ;; responsibility of each respective backend, not ours.
1087 ;; On the other hand, we don't want to replace non-prefix input in
1088 ;; `company-complete-common'.
1089 (setq company-common
1090 (if (cdr company-candidates)
1091 (let ((common (try-completion company-prefix company-candidates)))
1092 (if (eq common t)
1093 ;; Mulple equal strings, probably with different
1094 ;; annotations.
1095 company-prefix
1096 common))
1097 (car company-candidates)))))
1098
1099 (defun company-calculate-candidates (prefix)
1100 (let ((candidates (cdr (assoc prefix company-candidates-cache)))
1101 (ignore-case (company-call-backend 'ignore-case)))
1102 (or candidates
1103 (when company-candidates-cache
1104 (let ((len (length prefix))
1105 (completion-ignore-case ignore-case)
1106 prev)
1107 (cl-dotimes (i (1+ len))
1108 (when (setq prev (cdr (assoc (substring prefix 0 (- len i))
1109 company-candidates-cache)))
1110 (setq candidates (all-completions prefix prev))
1111 (cl-return t)))))
1112 ;; no cache match, call back-end
1113 (setq candidates
1114 (company--process-candidates
1115 (company--fetch-candidates prefix))))
1116 (setq candidates (company--transform-candidates candidates))
1117 (when candidates
1118 (if (or (cdr candidates)
1119 (not (eq t (compare-strings (car candidates) nil nil
1120 prefix nil nil ignore-case))))
1121 candidates
1122 ;; Already completed and unique; don't start.
1123 t))))
1124
1125 (defun company--fetch-candidates (prefix)
1126 (let ((c (if company--manual-action
1127 (company-call-backend 'candidates prefix)
1128 (company-call-backend-raw 'candidates prefix)))
1129 res)
1130 (if (not (eq (car c) :async))
1131 c
1132 (let ((buf (current-buffer))
1133 (win (selected-window))
1134 (tick (buffer-chars-modified-tick))
1135 (pt (point))
1136 (backend company-backend))
1137 (funcall
1138 (cdr c)
1139 (lambda (candidates)
1140 (if (not (and candidates (eq res 'done)))
1141 ;; Fetcher called us back right away.
1142 (setq res candidates)
1143 (setq company-backend backend
1144 company-candidates-cache
1145 (list (cons prefix
1146 (company--process-candidates
1147 candidates))))
1148 (company-idle-begin buf win tick pt)))))
1149 ;; FIXME: Relying on the fact that the callers
1150 ;; will interpret nil as "do nothing" is shaky.
1151 ;; A throw-catch would be one possible improvement.
1152 (or res
1153 (progn (setq res 'done) nil)))))
1154
1155 (defun company--process-candidates (candidates)
1156 (when company-candidates-predicate
1157 (setq candidates
1158 (company-apply-predicate candidates
1159 company-candidates-predicate)))
1160 (unless (company-call-backend 'sorted)
1161 (setq candidates (sort candidates 'string<)))
1162 (when (company-call-backend 'duplicates)
1163 (company--strip-duplicates candidates))
1164 candidates)
1165
1166 (defun company--strip-duplicates (candidates)
1167 (let ((c2 candidates))
1168 (while c2
1169 (setcdr c2
1170 (let ((str (car c2))
1171 (anno 'unk))
1172 (pop c2)
1173 (while (let ((str2 (car c2)))
1174 (if (not (equal str str2))
1175 nil
1176 (when (eq anno 'unk)
1177 (setq anno (company-call-backend
1178 'annotation str)))
1179 (equal anno
1180 (company-call-backend
1181 'annotation str2))))
1182 (pop c2))
1183 c2)))))
1184
1185 (defun company--transform-candidates (candidates)
1186 (let ((c candidates))
1187 (dolist (tr company-transformers)
1188 (setq c (funcall tr c)))
1189 c))
1190
1191 (defun company-sort-by-occurrence (candidates)
1192 "Sort CANDIDATES according to their occurrences.
1193 Searches for each in the currently visible part of the current buffer and
1194 gives priority to the closest ones above point, then closest ones below
1195 point. The rest of the list is appended unchanged.
1196 Keywords and function definition names are ignored."
1197 (let* (occurs
1198 (noccurs
1199 (cl-delete-if
1200 (lambda (candidate)
1201 (when (or
1202 (save-excursion
1203 (progn (forward-char (- (length company-prefix)))
1204 (search-backward candidate (window-start) t)))
1205 (save-excursion
1206 (search-forward candidate (window-end) t)))
1207 (let ((beg (match-beginning 0))
1208 (end (match-end 0)))
1209 (when (save-excursion
1210 (goto-char end)
1211 (and (not (memq (get-text-property (point) 'face)
1212 '(font-lock-function-name-face
1213 font-lock-keyword-face)))
1214 (let ((prefix (company--prefix-str
1215 (company-call-backend 'prefix))))
1216 (and (stringp prefix)
1217 (= (length prefix) (- end beg))))))
1218 (push (cons candidate (if (< beg (point))
1219 (- (point) end)
1220 (- beg (window-start))))
1221 occurs)
1222 t))))
1223 candidates)))
1224 (nconc
1225 (mapcar #'car (sort occurs (lambda (e1 e2) (<= (cdr e1) (cdr e2)))))
1226 noccurs)))
1227
1228 (defun company-sort-by-backend-importance (candidates)
1229 "Sort CANDIDATES as two priority groups.
1230 If `company-backend' is a function, do nothing. If it's a list, move
1231 candidates from back-ends before keyword `:with' to the front. Candidates
1232 from the rest of the back-ends in the group, if any, will be left at the end."
1233 (if (functionp company-backend)
1234 candidates
1235 (let ((low-priority (cdr (memq :with company-backend))))
1236 (if (null low-priority)
1237 candidates
1238 (sort candidates
1239 (lambda (c1 c2)
1240 (and
1241 (let ((b2 (get-text-property 0 'company-backend c2)))
1242 (and b2 (memq b2 low-priority)))
1243 (let ((b1 (get-text-property 0 'company-backend c1)))
1244 (or (not b1) (not (memq b1 low-priority)))))))))))
1245
1246 (defun company-idle-begin (buf win tick pos)
1247 (and (eq buf (current-buffer))
1248 (eq win (selected-window))
1249 (eq tick (buffer-chars-modified-tick))
1250 (eq pos (point))
1251 (when (company-auto-begin)
1252 (when (version< emacs-version "24.3.50")
1253 (company-input-noop))
1254 (company-post-command))))
1255
1256 (defun company-auto-begin ()
1257 (and company-mode
1258 (not company-candidates)
1259 (let ((company-idle-delay t))
1260 (condition-case-unless-debug err
1261 (company--perform)
1262 (error (message "Company: An error occurred in auto-begin")
1263 (message "%s" (error-message-string err))
1264 (company-cancel))
1265 (quit (company-cancel)))))
1266 (unless company-candidates
1267 (setq company-backend nil))
1268 ;; Return non-nil if active.
1269 company-candidates)
1270
1271 (defun company-manual-begin ()
1272 (interactive)
1273 (company-assert-enabled)
1274 (setq company--manual-action t)
1275 (unwind-protect
1276 (let ((company-minimum-prefix-length 0))
1277 (company-auto-begin))
1278 (unless company-candidates
1279 (setq company--manual-action nil))))
1280
1281 (defun company-other-backend (&optional backward)
1282 (interactive (list current-prefix-arg))
1283 (company-assert-enabled)
1284 (let* ((after (if company-backend
1285 (cdr (member company-backend company-backends))
1286 company-backends))
1287 (before (cdr (member company-backend (reverse company-backends))))
1288 (next (if backward
1289 (append before (reverse after))
1290 (append after (reverse before)))))
1291 (company-cancel)
1292 (cl-dolist (backend next)
1293 (when (ignore-errors (company-begin-backend backend))
1294 (cl-return t))))
1295 (unless company-candidates
1296 (error "No other back-end")))
1297
1298 (defun company-require-match-p ()
1299 (let ((backend-value (company-call-backend 'require-match)))
1300 (or (eq backend-value t)
1301 (and (not (eq backend-value 'never))
1302 (if (functionp company-require-match)
1303 (funcall company-require-match)
1304 (eq company-require-match t))))))
1305
1306 (defun company-auto-complete-p (input)
1307 "Return non-nil, if input starts with punctuation or parentheses."
1308 (and (if (functionp company-auto-complete)
1309 (funcall company-auto-complete)
1310 company-auto-complete)
1311 (if (functionp company-auto-complete-chars)
1312 (funcall company-auto-complete-chars input)
1313 (if (consp company-auto-complete-chars)
1314 (memq (char-syntax (string-to-char input))
1315 company-auto-complete-chars)
1316 (string-match (substring input 0 1) company-auto-complete-chars)))))
1317
1318 (defun company--incremental-p ()
1319 (and (> (point) company-point)
1320 (> (point-max) company--point-max)
1321 (not (eq this-command 'backward-delete-char-untabify))
1322 (equal (buffer-substring (- company-point (length company-prefix))
1323 company-point)
1324 company-prefix)))
1325
1326 (defun company--continue-failed (new-prefix)
1327 (let ((input (buffer-substring-no-properties (point) company-point)))
1328 (cond
1329 ((company-auto-complete-p input)
1330 ;; auto-complete
1331 (save-excursion
1332 (goto-char company-point)
1333 (let ((company--auto-completion t))
1334 (company-complete-selection))
1335 nil))
1336 ((and (or (not (company-require-match-p))
1337 ;; Don't require match if the new prefix
1338 ;; doesn't continue the old one, and the latter was a match.
1339 (<= (length new-prefix) (length company-prefix)))
1340 (member company-prefix company-candidates))
1341 ;; Last input was a success,
1342 ;; but we're treating it as an abort + input anyway,
1343 ;; like the `unique' case below.
1344 (company-cancel 'non-unique))
1345 ((company-require-match-p)
1346 ;; Wrong incremental input, but required match.
1347 (delete-char (- (length input)))
1348 (ding)
1349 (message "Matching input is required")
1350 company-candidates)
1351 (t (company-cancel)))))
1352
1353 (defun company--good-prefix-p (prefix)
1354 (and (stringp (company--prefix-str prefix)) ;excludes 'stop
1355 (or (eq (cdr-safe prefix) t)
1356 (let ((len (or (cdr-safe prefix) (length prefix))))
1357 (if company--manual-prefix
1358 (or (not company-abort-manual-when-too-short)
1359 ;; Must not be less than minimum or initial length.
1360 (>= len (min company-minimum-prefix-length
1361 (length company--manual-prefix))))
1362 (>= len company-minimum-prefix-length))))))
1363
1364 (defun company--continue ()
1365 (when (company-call-backend 'no-cache company-prefix)
1366 ;; Don't complete existing candidates, fetch new ones.
1367 (setq company-candidates-cache nil))
1368 (let* ((new-prefix (company-call-backend 'prefix))
1369 (c (when (and (company--good-prefix-p new-prefix)
1370 (setq new-prefix (company--prefix-str new-prefix))
1371 (= (- (point) (length new-prefix))
1372 (- company-point (length company-prefix))))
1373 (company-calculate-candidates new-prefix))))
1374 (cond
1375 ((eq c t)
1376 ;; t means complete/unique.
1377 ;; Handle it like completion was aborted, to differentiate from user
1378 ;; calling one of Company's commands to insert the candidate,
1379 ;; not to trigger template expansion, etc.
1380 (company-cancel 'unique))
1381 ((consp c)
1382 ;; incremental match
1383 (setq company-prefix new-prefix)
1384 (company-update-candidates c)
1385 c)
1386 ((not (company--incremental-p))
1387 (company-cancel))
1388 (t (company--continue-failed new-prefix)))))
1389
1390 (defun company--begin-new ()
1391 (let (prefix c)
1392 (cl-dolist (backend (if company-backend
1393 ;; prefer manual override
1394 (list company-backend)
1395 company-backends))
1396 (setq prefix
1397 (if (or (symbolp backend)
1398 (functionp backend))
1399 (when (or (not (symbolp backend))
1400 (eq t (get backend 'company-init))
1401 (unless (get backend 'company-init)
1402 (company-init-backend backend)))
1403 (funcall backend 'prefix))
1404 (company--multi-backend-adapter backend 'prefix)))
1405 (when prefix
1406 (when (company--good-prefix-p prefix)
1407 (setq company-prefix (company--prefix-str prefix)
1408 company-backend backend
1409 c (company-calculate-candidates company-prefix))
1410 ;; t means complete/unique. We don't start, so no hooks.
1411 (if (not (consp c))
1412 (when company--manual-action
1413 (message "No completion found"))
1414 (when company--manual-action
1415 (setq company--manual-prefix prefix))
1416 (if (symbolp backend)
1417 (setq company-lighter (concat " " (symbol-name backend)))
1418 (company--update-group-lighter (car c)))
1419 (company-update-candidates c)
1420 (run-hook-with-args 'company-completion-started-hook
1421 (company-explicit-action-p))
1422 (company-call-frontends 'show)))
1423 (cl-return c)))))
1424
1425 (defun company--perform ()
1426 (or (and company-candidates (company--continue))
1427 (and (company--should-complete) (company--begin-new)))
1428 (when company-candidates
1429 (let ((modified (buffer-modified-p)))
1430 (when (and company-end-of-buffer-workaround (eobp))
1431 (save-excursion (insert "\n"))
1432 (setq company-added-newline
1433 (or modified (buffer-chars-modified-tick)))))
1434 (setq company-point (point)
1435 company--point-max (point-max))
1436 (company-ensure-emulation-alist)
1437 (company-enable-overriding-keymap company-active-map)
1438 (company-call-frontends 'update)))
1439
1440 (defun company-cancel (&optional result)
1441 (and company-added-newline
1442 (> (point-max) (point-min))
1443 (let ((tick (buffer-chars-modified-tick)))
1444 (delete-region (1- (point-max)) (point-max))
1445 (equal tick company-added-newline))
1446 ;; Only set unmodified when tick remained the same since insert,
1447 ;; and the buffer wasn't modified before.
1448 (set-buffer-modified-p nil))
1449 (unwind-protect
1450 (when company-prefix
1451 (if (stringp result)
1452 (progn
1453 (company-call-backend 'pre-completion result)
1454 (run-hook-with-args 'company-completion-finished-hook result)
1455 (company-call-backend 'post-completion result))
1456 (run-hook-with-args 'company-completion-cancelled-hook result)))
1457 (setq company-added-newline nil
1458 company-backend nil
1459 company-prefix nil
1460 company-candidates nil
1461 company-candidates-length nil
1462 company-candidates-cache nil
1463 company-candidates-predicate nil
1464 company-common nil
1465 company-selection 0
1466 company-selection-changed nil
1467 company--manual-action nil
1468 company--manual-prefix nil
1469 company-lighter company-default-lighter
1470 company--point-max nil
1471 company-point nil)
1472 (when company-timer
1473 (cancel-timer company-timer))
1474 (company-search-mode 0)
1475 (company-call-frontends 'hide)
1476 (company-enable-overriding-keymap nil))
1477 ;; Make return value explicit.
1478 nil)
1479
1480 (defun company-abort ()
1481 (interactive)
1482 (company-cancel 'abort))
1483
1484 (defun company-finish (result)
1485 (company--insert-candidate result)
1486 (company-cancel result))
1487
1488 (defsubst company-keep (command)
1489 (and (symbolp command) (get command 'company-keep)))
1490
1491 (defun company-pre-command ()
1492 (unless (company-keep this-command)
1493 (condition-case err
1494 (when company-candidates
1495 (company-call-frontends 'pre-command)
1496 (unless (company--should-continue)
1497 (company-abort)))
1498 (error (message "Company: An error occurred in pre-command")
1499 (message "%s" (error-message-string err))
1500 (company-cancel))))
1501 (when company-timer
1502 (cancel-timer company-timer)
1503 (setq company-timer nil))
1504 (company-uninstall-map))
1505
1506 (defun company-post-command ()
1507 (unless (company-keep this-command)
1508 (condition-case err
1509 (progn
1510 (unless (equal (point) company-point)
1511 (let ((company-idle-delay (and (eq company-idle-delay t)
1512 (company--should-begin)
1513 t)))
1514 (company--perform)))
1515 (if company-candidates
1516 (company-call-frontends 'post-command)
1517 (and (numberp company-idle-delay)
1518 (company--should-begin)
1519 (setq company-timer
1520 (run-with-timer company-idle-delay nil
1521 'company-idle-begin
1522 (current-buffer) (selected-window)
1523 (buffer-chars-modified-tick) (point))))))
1524 (error (message "Company: An error occurred in post-command")
1525 (message "%s" (error-message-string err))
1526 (company-cancel))))
1527 (company-install-map))
1528
1529 (defvar company--begin-inhibit-commands '(company-abort
1530 company-complete-mouse
1531 company-complete
1532 company-complete-common
1533 company-complete-selection
1534 company-complete-number)
1535 "List of commands after which idle completion is (still) disabled when
1536 `company-begin-commands' is t.")
1537
1538 (defun company--should-begin ()
1539 (if (eq t company-begin-commands)
1540 (not (memq this-command company--begin-inhibit-commands))
1541 (or
1542 (memq this-command company-begin-commands)
1543 (and (symbolp this-command) (get this-command 'company-begin)))))
1544
1545 ;;; search ;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;
1546
1547 (defvar-local company-search-string nil)
1548
1549 (defvar-local company-search-lighter " Search: \"\"")
1550
1551 (defvar-local company-search-old-map nil)
1552
1553 (defvar-local company-search-old-selection 0)
1554
1555 (defun company-search (text lines)
1556 (let ((quoted (regexp-quote text))
1557 (i 0))
1558 (cl-dolist (line lines)
1559 (when (string-match quoted line (length company-prefix))
1560 (cl-return i))
1561 (cl-incf i))))
1562
1563 (defun company-search-printing-char ()
1564 (interactive)
1565 (company-search-assert-enabled)
1566 (setq company-search-string
1567 (concat (or company-search-string "") (string last-command-event))
1568 company-search-lighter (concat " Search: \"" company-search-string
1569 "\""))
1570 (let ((pos (company-search company-search-string
1571 (nthcdr company-selection company-candidates))))
1572 (if (null pos)
1573 (ding)
1574 (company-set-selection (+ company-selection pos) t))))
1575
1576 (defun company-search-repeat-forward ()
1577 "Repeat the incremental search in completion candidates forward."
1578 (interactive)
1579 (company-search-assert-enabled)
1580 (let ((pos (company-search company-search-string
1581 (cdr (nthcdr company-selection
1582 company-candidates)))))
1583 (if (null pos)
1584 (ding)
1585 (company-set-selection (+ company-selection pos 1) t))))
1586
1587 (defun company-search-repeat-backward ()
1588 "Repeat the incremental search in completion candidates backwards."
1589 (interactive)
1590 (company-search-assert-enabled)
1591 (let ((pos (company-search company-search-string
1592 (nthcdr (- company-candidates-length
1593 company-selection)
1594 (reverse company-candidates)))))
1595 (if (null pos)
1596 (ding)
1597 (company-set-selection (- company-selection pos 1) t))))
1598
1599 (defun company-create-match-predicate ()
1600 (setq company-candidates-predicate
1601 `(lambda (candidate)
1602 ,(if company-candidates-predicate
1603 `(and (string-match ,company-search-string candidate)
1604 (funcall ,company-candidates-predicate
1605 candidate))
1606 `(string-match ,company-search-string candidate))))
1607 (company-update-candidates
1608 (company-apply-predicate company-candidates company-candidates-predicate))
1609 ;; Invalidate cache.
1610 (setq company-candidates-cache (cons company-prefix company-candidates)))
1611
1612 (defun company-filter-printing-char ()
1613 (interactive)
1614 (company-search-assert-enabled)
1615 (company-search-printing-char)
1616 (company-create-match-predicate)
1617 (company-call-frontends 'update))
1618
1619 (defun company-search-kill-others ()
1620 "Limit the completion candidates to the ones matching the search string."
1621 (interactive)
1622 (company-search-assert-enabled)
1623 (company-create-match-predicate)
1624 (company-search-mode 0)
1625 (company-call-frontends 'update))
1626
1627 (defun company-search-abort ()
1628 "Abort searching the completion candidates."
1629 (interactive)
1630 (company-search-assert-enabled)
1631 (company-set-selection company-search-old-selection t)
1632 (company-search-mode 0))
1633
1634 (defun company-search-other-char ()
1635 (interactive)
1636 (company-search-assert-enabled)
1637 (company-search-mode 0)
1638 (company--unread-last-input))
1639
1640 (defvar company-search-map
1641 (let ((i 0)
1642 (keymap (make-keymap)))
1643 (if (fboundp 'max-char)
1644 (set-char-table-range (nth 1 keymap) (cons #x100 (max-char))
1645 'company-search-printing-char)
1646 (with-no-warnings
1647 ;; obsolete in Emacs 23
1648 (let ((l (generic-character-list))
1649 (table (nth 1 keymap)))
1650 (while l
1651 (set-char-table-default table (car l) 'company-search-printing-char)
1652 (setq l (cdr l))))))
1653 (define-key keymap [t] 'company-search-other-char)
1654 (while (< i ?\s)
1655 (define-key keymap (make-string 1 i) 'company-search-other-char)
1656 (cl-incf i))
1657 (while (< i 256)
1658 (define-key keymap (vector i) 'company-search-printing-char)
1659 (cl-incf i))
1660 (let ((meta-map (make-sparse-keymap)))
1661 (define-key keymap (char-to-string meta-prefix-char) meta-map)
1662 (define-key keymap [escape] meta-map))
1663 (define-key keymap (vector meta-prefix-char t) 'company-search-other-char)
1664 (define-key keymap "\e\e\e" 'company-search-other-char)
1665 (define-key keymap [escape escape escape] 'company-search-other-char)
1666 (define-key keymap (kbd "DEL") 'company-search-other-char)
1667
1668 (define-key keymap "\C-g" 'company-search-abort)
1669 (define-key keymap "\C-s" 'company-search-repeat-forward)
1670 (define-key keymap "\C-r" 'company-search-repeat-backward)
1671 (define-key keymap "\C-o" 'company-search-kill-others)
1672 keymap)
1673 "Keymap used for incrementally searching the completion candidates.")
1674
1675 (define-minor-mode company-search-mode
1676 "Search mode for completion candidates.
1677 Don't start this directly, use `company-search-candidates' or
1678 `company-filter-candidates'."
1679 nil company-search-lighter nil
1680 (if company-search-mode
1681 (if (company-manual-begin)
1682 (progn
1683 (setq company-search-old-selection company-selection)
1684 (company-call-frontends 'update))
1685 (setq company-search-mode nil))
1686 (kill-local-variable 'company-search-string)
1687 (kill-local-variable 'company-search-lighter)
1688 (kill-local-variable 'company-search-old-selection)
1689 (company-enable-overriding-keymap company-active-map)))
1690
1691 (defun company-search-assert-enabled ()
1692 (company-assert-enabled)
1693 (unless company-search-mode
1694 (company-uninstall-map)
1695 (error "Company not in search mode")))
1696
1697 (defun company-search-candidates ()
1698 "Start searching the completion candidates incrementally.
1699
1700 \\<company-search-map>Search can be controlled with the commands:
1701 - `company-search-repeat-forward' (\\[company-search-repeat-forward])
1702 - `company-search-repeat-backward' (\\[company-search-repeat-backward])
1703 - `company-search-abort' (\\[company-search-abort])
1704
1705 Regular characters are appended to the search string.
1706
1707 The command `company-search-kill-others' (\\[company-search-kill-others])
1708 uses the search string to limit the completion candidates."
1709 (interactive)
1710 (company-search-mode 1)
1711 (company-enable-overriding-keymap company-search-map))
1712
1713 (defvar company-filter-map
1714 (let ((keymap (make-keymap)))
1715 (define-key keymap [remap company-search-printing-char]
1716 'company-filter-printing-char)
1717 (set-keymap-parent keymap company-search-map)
1718 keymap)
1719 "Keymap used for incrementally searching the completion candidates.")
1720
1721 (defun company-filter-candidates ()
1722 "Start filtering the completion candidates incrementally.
1723 This works the same way as `company-search-candidates' immediately
1724 followed by `company-search-kill-others' after each input."
1725 (interactive)
1726 (company-search-mode 1)
1727 (company-enable-overriding-keymap company-filter-map))
1728
1729 ;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;
1730
1731 (defun company-select-next ()
1732 "Select the next candidate in the list."
1733 (interactive)
1734 (when (company-manual-begin)
1735 (company-set-selection (1+ company-selection))))
1736
1737 (defun company-select-previous ()
1738 "Select the previous candidate in the list."
1739 (interactive)
1740 (when (company-manual-begin)
1741 (company-set-selection (1- company-selection))))
1742
1743 (defun company-select-next-or-abort ()
1744 "Select the next candidate if more than one, else abort
1745 and invoke the normal binding."
1746 (interactive)
1747 (if (> company-candidates-length 1)
1748 (company-select-next)
1749 (company-abort)
1750 (company--unread-last-input)))
1751
1752 (defun company-select-previous-or-abort ()
1753 "Select the previous candidate if more than one, else abort
1754 and invoke the normal binding."
1755 (interactive)
1756 (if (> company-candidates-length 1)
1757 (company-select-previous)
1758 (company-abort)
1759 (company--unread-last-input)))
1760
1761 (defvar company-pseudo-tooltip-overlay)
1762
1763 (defvar company-tooltip-offset)
1764
1765 (defun company--inside-tooltip-p (event-col-row row height)
1766 (let* ((ovl company-pseudo-tooltip-overlay)
1767 (column (overlay-get ovl 'company-column))
1768 (width (overlay-get ovl 'company-width))
1769 (evt-col (car event-col-row))
1770 (evt-row (cdr event-col-row)))
1771 (and (>= evt-col column)
1772 (< evt-col (+ column width))
1773 (if (> height 0)
1774 (and (> evt-row row)
1775 (<= evt-row (+ row height) ))
1776 (and (< evt-row row)
1777 (>= evt-row (+ row height)))))))
1778
1779 (defun company--event-col-row (event)
1780 (let* ((col-row (posn-actual-col-row (event-start event)))
1781 (col (car col-row))
1782 (row (cdr col-row)))
1783 (cl-incf col (window-hscroll))
1784 (and header-line-format
1785 (version< "24" emacs-version)
1786 (cl-decf row))
1787 (cons col row)))
1788
1789 (defun company-select-mouse (event)
1790 "Select the candidate picked by the mouse."
1791 (interactive "e")
1792 (let ((event-col-row (company--event-col-row event))
1793 (ovl-row (company--row))
1794 (ovl-height (and company-pseudo-tooltip-overlay
1795 (min (overlay-get company-pseudo-tooltip-overlay
1796 'company-height)
1797 company-candidates-length))))
1798 (if (and ovl-height
1799 (company--inside-tooltip-p event-col-row ovl-row ovl-height))
1800 (progn
1801 (company-set-selection (+ (cdr event-col-row)
1802 (1- company-tooltip-offset)
1803 (if (and (eq company-tooltip-offset-display 'lines)
1804 (not (zerop company-tooltip-offset)))
1805 -1 0)
1806 (- ovl-row)
1807 (if (< ovl-height 0)
1808 (- 1 ovl-height)
1809 0)))
1810 t)
1811 (company-abort)
1812 (company--unread-last-input)
1813 nil)))
1814
1815 (defun company-complete-mouse (event)
1816 "Insert the candidate picked by the mouse."
1817 (interactive "e")
1818 (when (company-select-mouse event)
1819 (company-complete-selection)))
1820
1821 (defun company-complete-selection ()
1822 "Insert the selected candidate."
1823 (interactive)
1824 (when (company-manual-begin)
1825 (let ((result (nth company-selection company-candidates)))
1826 (company-finish result))))
1827
1828 (defun company-complete-common ()
1829 "Insert the common part of all candidates."
1830 (interactive)
1831 (when (company-manual-begin)
1832 (if (and (not (cdr company-candidates))
1833 (equal company-common (car company-candidates)))
1834 (company-complete-selection)
1835 (when company-common
1836 (company--insert-candidate company-common)))))
1837
1838 (defun company-complete ()
1839 "Insert the common part of all candidates or the current selection.
1840 The first time this is called, the common part is inserted, the second
1841 time, or when the selection has been changed, the selected candidate is
1842 inserted."
1843 (interactive)
1844 (when (company-manual-begin)
1845 (if (or company-selection-changed
1846 (eq last-command 'company-complete-common))
1847 (call-interactively 'company-complete-selection)
1848 (call-interactively 'company-complete-common)
1849 (setq this-command 'company-complete-common))))
1850
1851 (defun company-complete-number (n)
1852 "Insert the Nth candidate.
1853 To show the number next to the candidates in some back-ends, enable
1854 `company-show-numbers'."
1855 (when (company-manual-begin)
1856 (and (or (< n 1) (> n company-candidates-length))
1857 (error "No candidate number %d" n))
1858 (cl-decf n)
1859 (company-finish (nth n company-candidates))))
1860
1861 ;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;
1862
1863 (defconst company-space-strings-limit 100)
1864
1865 (defconst company-space-strings
1866 (let (lst)
1867 (dotimes (i company-space-strings-limit)
1868 (push (make-string (- company-space-strings-limit 1 i) ?\ ) lst))
1869 (apply 'vector lst)))
1870
1871 (defun company-space-string (len)
1872 (if (< len company-space-strings-limit)
1873 (aref company-space-strings len)
1874 (make-string len ?\ )))
1875
1876 (defun company-safe-substring (str from &optional to)
1877 (if (> from (string-width str))
1878 ""
1879 (with-temp-buffer
1880 (insert str)
1881 (move-to-column from)
1882 (let ((beg (point)))
1883 (if to
1884 (progn
1885 (move-to-column to)
1886 (concat (buffer-substring beg (point))
1887 (let ((padding (- to (current-column))))
1888 (when (> padding 0)
1889 (company-space-string padding)))))
1890 (buffer-substring beg (point-max)))))))
1891
1892 ;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;
1893
1894 (defvar-local company-last-metadata nil)
1895
1896 (defun company-fetch-metadata ()
1897 (let ((selected (nth company-selection company-candidates)))
1898 (unless (eq selected (car company-last-metadata))
1899 (setq company-last-metadata
1900 (cons selected (company-call-backend 'meta selected))))
1901 (cdr company-last-metadata)))
1902
1903 (defun company-doc-buffer (&optional string)
1904 (with-current-buffer (get-buffer-create "*company-documentation*")
1905 (erase-buffer)
1906 (when string
1907 (save-excursion
1908 (insert string)))
1909 (current-buffer)))
1910
1911 (defvar company--electric-commands
1912 '(scroll-other-window scroll-other-window-down)
1913 "List of Commands that won't break out of electric commands.")
1914
1915 (defmacro company--electric-do (&rest body)
1916 (declare (indent 0) (debug t))
1917 `(when (company-manual-begin)
1918 (save-window-excursion
1919 (let ((height (window-height))
1920 (row (company--row))
1921 cmd)
1922 ,@body
1923 (and (< (window-height) height)
1924 (< (- (window-height) row 2) company-tooltip-limit)
1925 (recenter (- (window-height) row 2)))
1926 (while (memq (setq cmd (key-binding (vector (list (read-event)))))
1927 company--electric-commands)
1928 (call-interactively cmd))
1929 (company--unread-last-input)))))
1930
1931 (defun company--unread-last-input ()
1932 (when last-input-event
1933 (clear-this-command-keys t)
1934 (setq unread-command-events (list last-input-event))))
1935
1936 (defun company-show-doc-buffer ()
1937 "Temporarily show the documentation buffer for the selection."
1938 (interactive)
1939 (company--electric-do
1940 (let* ((selected (nth company-selection company-candidates))
1941 (doc-buffer (or (company-call-backend 'doc-buffer selected)
1942 (error "No documentation available"))))
1943 (with-current-buffer doc-buffer
1944 (goto-char (point-min)))
1945 (display-buffer doc-buffer t))))
1946 (put 'company-show-doc-buffer 'company-keep t)
1947
1948 (defun company-show-location ()
1949 "Temporarily display a buffer showing the selected candidate in context."
1950 (interactive)
1951 (company--electric-do
1952 (let* ((selected (nth company-selection company-candidates))
1953 (location (company-call-backend 'location selected))
1954 (pos (or (cdr location) (error "No location available")))
1955 (buffer (or (and (bufferp (car location)) (car location))
1956 (find-file-noselect (car location) t))))
1957 (with-selected-window (display-buffer buffer t)
1958 (save-restriction
1959 (widen)
1960 (if (bufferp (car location))
1961 (goto-char pos)
1962 (goto-char (point-min))
1963 (forward-line (1- pos))))
1964 (set-window-start nil (point))))))
1965 (put 'company-show-location 'company-keep t)
1966
1967 ;;; package functions ;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;
1968
1969 (defvar-local company-callback nil)
1970
1971 (defun company-remove-callback (&optional ignored)
1972 (remove-hook 'company-completion-finished-hook company-callback t)
1973 (remove-hook 'company-completion-cancelled-hook 'company-remove-callback t)
1974 (remove-hook 'company-completion-finished-hook 'company-remove-callback t))
1975
1976 (defun company-begin-backend (backend &optional callback)
1977 "Start a completion at point using BACKEND."
1978 (interactive (let ((val (completing-read "Company back-end: "
1979 obarray
1980 'functionp nil "company-")))
1981 (when val
1982 (list (intern val)))))
1983 (when (setq company-callback callback)
1984 (add-hook 'company-completion-finished-hook company-callback nil t))
1985 (add-hook 'company-completion-cancelled-hook 'company-remove-callback nil t)
1986 (add-hook 'company-completion-finished-hook 'company-remove-callback nil t)
1987 (setq company-backend backend)
1988 ;; Return non-nil if active.
1989 (or (company-manual-begin)
1990 (error "Cannot complete at point")))
1991
1992 (defun company-begin-with (candidates
1993 &optional prefix-length require-match callback)
1994 "Start a completion at point.
1995 CANDIDATES is the list of candidates to use and PREFIX-LENGTH is the length
1996 of the prefix that already is in the buffer before point.
1997 It defaults to 0.
1998
1999 CALLBACK is a function called with the selected result if the user
2000 successfully completes the input.
2001
2002 Example: \(company-begin-with '\(\"foo\" \"foobar\" \"foobarbaz\"\)\)"
2003 (let ((begin-marker (copy-marker (point) t)))
2004 (company-begin-backend
2005 (lambda (command &optional arg &rest ignored)
2006 (pcase command
2007 (`prefix
2008 (when (equal (point) (marker-position begin-marker))
2009 (buffer-substring (- (point) (or prefix-length 0)) (point))))
2010 (`candidates
2011 (all-completions arg candidates))
2012 (`require-match
2013 require-match)))
2014 callback)))
2015
2016 (defun company-version (&optional show-version)
2017 "Get the Company version as string.
2018
2019 If SHOW-VERSION is non-nil, show the version in the echo area."
2020 (interactive (list t))
2021 (with-temp-buffer
2022 (insert-file-contents (find-library-name "company"))
2023 (require 'lisp-mnt)
2024 (if show-version
2025 (message "Company version: %s" (lm-version))
2026 (lm-version))))
2027
2028 ;;; pseudo-tooltip ;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;
2029
2030 (defvar-local company-pseudo-tooltip-overlay nil)
2031
2032 (defvar-local company-tooltip-offset 0)
2033
2034 (defun company-tooltip--lines-update-offset (selection num-lines limit)
2035 (cl-decf limit 2)
2036 (setq company-tooltip-offset
2037 (max (min selection company-tooltip-offset)
2038 (- selection -1 limit)))
2039
2040 (when (<= company-tooltip-offset 1)
2041 (cl-incf limit)
2042 (setq company-tooltip-offset 0))
2043
2044 (when (>= company-tooltip-offset (- num-lines limit 1))
2045 (cl-incf limit)
2046 (when (= selection (1- num-lines))
2047 (cl-decf company-tooltip-offset)
2048 (when (<= company-tooltip-offset 1)
2049 (setq company-tooltip-offset 0)
2050 (cl-incf limit))))
2051
2052 limit)
2053
2054 (defun company-tooltip--simple-update-offset (selection _num-lines limit)
2055 (setq company-tooltip-offset
2056 (if (< selection company-tooltip-offset)
2057 selection
2058 (max company-tooltip-offset
2059 (- selection limit -1)))))
2060
2061 ;;; propertize
2062
2063 (defsubst company-round-tab (arg)
2064 (* (/ (+ arg tab-width) tab-width) tab-width))
2065
2066 (defun company-plainify (str)
2067 (let ((prefix (get-text-property 0 'line-prefix str)))
2068 (when prefix ; Keep the original value unmodified, for no special reason.
2069 (setq str (concat prefix str))
2070 (remove-text-properties 0 (length str) '(line-prefix) str)))
2071 (let* ((pieces (split-string str "\t"))
2072 (copy pieces))
2073 (while (cdr copy)
2074 (setcar copy (company-safe-substring
2075 (car copy) 0 (company-round-tab (string-width (car copy)))))
2076 (pop copy))
2077 (apply 'concat pieces)))
2078
2079 (defun company-fill-propertize (value annotation width selected left right)
2080 (let* ((margin (length left))
2081 (common (+ (or (company-call-backend 'match value)
2082 (length company-common)) margin))
2083 (ann-ralign company-tooltip-align-annotations)
2084 (ann-truncate (< width
2085 (+ (length value) (length annotation)
2086 (if ann-ralign 1 0))))
2087 (ann-start (+ margin
2088 (if ann-ralign
2089 (if ann-truncate
2090 (1+ (length value))
2091 (- width (length annotation)))
2092 (length value))))
2093 (ann-end (min (+ ann-start (length annotation)) (+ margin width)))
2094 (line (concat left
2095 (if (or ann-truncate (not ann-ralign))
2096 (company-safe-substring
2097 (concat value
2098 (when (and annotation ann-ralign) " ")
2099 annotation)
2100 0 width)
2101 (concat
2102 (company-safe-substring value 0
2103 (- width (length annotation)))
2104 annotation))
2105 right)))
2106 (setq width (+ width margin (length right)))
2107
2108 (add-text-properties 0 width '(face company-tooltip
2109 mouse-face company-tooltip-mouse)
2110 line)
2111 (add-text-properties margin common
2112 '(face company-tooltip-common
2113 mouse-face company-tooltip-mouse)
2114 line)
2115 (when (< ann-start ann-end)
2116 (add-text-properties ann-start ann-end
2117 '(face company-tooltip-annotation
2118 mouse-face company-tooltip-mouse)
2119 line))
2120 (when selected
2121 (if (and company-search-string
2122 (string-match (regexp-quote company-search-string) value
2123 (length company-prefix)))
2124 (let ((beg (+ margin (match-beginning 0)))
2125 (end (+ margin (match-end 0))))
2126 (add-text-properties beg end '(face company-tooltip-selection)
2127 line)
2128 (when (< beg common)
2129 (add-text-properties beg common
2130 '(face company-tooltip-common-selection)
2131 line)))
2132 (add-text-properties 0 width '(face company-tooltip-selection
2133 mouse-face company-tooltip-selection)
2134 line)
2135 (add-text-properties margin common
2136 '(face company-tooltip-common-selection
2137 mouse-face company-tooltip-selection)
2138 line)))
2139 line))
2140
2141 ;;; replace
2142
2143 (defun company-buffer-lines (beg end)
2144 (goto-char beg)
2145 (let (lines)
2146 (while (and (= 1 (vertical-motion 1))
2147 (<= (point) end))
2148 (let ((bound (min end (1- (point)))))
2149 ;; A visual line can contain several physical lines (e.g. with outline's
2150 ;; folding overlay). Take only the first one.
2151 (push (buffer-substring beg
2152 (save-excursion
2153 (goto-char beg)
2154 (re-search-forward "$" bound 'move)
2155 (point)))
2156 lines))
2157 (setq beg (point)))
2158 (unless (eq beg end)
2159 (push (buffer-substring beg end) lines))
2160 (nreverse lines)))
2161
2162 (defun company-modify-line (old new offset)
2163 (concat (company-safe-substring old 0 offset)
2164 new
2165 (company-safe-substring old (+ offset (length new)))))
2166
2167 (defsubst company--length-limit (lst limit)
2168 (if (nthcdr limit lst)
2169 limit
2170 (length lst)))
2171
2172 (defun company--replacement-string (lines old column nl &optional align-top)
2173 (cl-decf column company-tooltip-margin)
2174
2175 (when (and align-top company-tooltip-flip-when-above)
2176 (setq lines (reverse lines)))
2177
2178 (let ((width (length (car lines)))
2179 (remaining-cols (- (+ (company--window-width) (window-hscroll))
2180 column)))
2181 (when (> width remaining-cols)
2182 (cl-decf column (- width remaining-cols))))
2183
2184 (let ((offset (and (< column 0) (- column)))
2185 new)
2186 (when offset
2187 (setq column 0))
2188 (when align-top
2189 ;; untouched lines first
2190 (dotimes (_ (- (length old) (length lines)))
2191 (push (pop old) new)))
2192 ;; length into old lines.
2193 (while old
2194 (push (company-modify-line (pop old)
2195 (company--offset-line (pop lines) offset)
2196 column) new))
2197 ;; Append whole new lines.
2198 (while lines
2199 (push (concat (company-space-string column)
2200 (company--offset-line (pop lines) offset))
2201 new))
2202
2203 (let ((str (concat (when nl "\n")
2204 (mapconcat 'identity (nreverse new) "\n")
2205 "\n")))
2206 (font-lock-append-text-property 0 (length str) 'face 'default str)
2207 str)))
2208
2209 (defun company--offset-line (line offset)
2210 (if (and offset line)
2211 (substring line offset)
2212 line))
2213
2214 (defun company--create-lines (selection limit)
2215 (let ((len company-candidates-length)
2216 (numbered 99999)
2217 (window-width (company--window-width))
2218 lines
2219 width
2220 lines-copy
2221 items
2222 previous
2223 remainder
2224 scrollbar-bounds)
2225
2226 ;; Maybe clear old offset.
2227 (when (< len (+ company-tooltip-offset limit))
2228 (setq company-tooltip-offset 0))
2229
2230 ;; Scroll to offset.
2231 (if (eq company-tooltip-offset-display 'lines)
2232 (setq limit (company-tooltip--lines-update-offset selection len limit))
2233 (company-tooltip--simple-update-offset selection len limit))
2234
2235 (cond
2236 ((eq company-tooltip-offset-display 'scrollbar)
2237 (setq scrollbar-bounds (company--scrollbar-bounds company-tooltip-offset
2238 limit len)))
2239 ((eq company-tooltip-offset-display 'lines)
2240 (when (> company-tooltip-offset 0)
2241 (setq previous (format "...(%d)" company-tooltip-offset)))
2242 (setq remainder (- len limit company-tooltip-offset)
2243 remainder (when (> remainder 0)
2244 (setq remainder (format "...(%d)" remainder))))))
2245
2246 (cl-decf selection company-tooltip-offset)
2247 (setq width (max (length previous) (length remainder))
2248 lines (nthcdr company-tooltip-offset company-candidates)
2249 len (min limit len)
2250 lines-copy lines)
2251
2252 (cl-decf window-width (* 2 company-tooltip-margin))
2253 (when scrollbar-bounds (cl-decf window-width))
2254
2255 (dotimes (_ len)
2256 (let* ((value (pop lines-copy))
2257 (annotation (company-call-backend 'annotation value)))
2258 (when (and annotation company-tooltip-align-annotations)
2259 ;; `lisp-completion-at-point' adds a space.
2260 (setq annotation (comment-string-strip annotation t nil)))
2261 (push (cons value annotation) items)
2262 (setq width (max (+ (length value)
2263 (if (and annotation company-tooltip-align-annotations)
2264 (1+ (length annotation))
2265 (length annotation)))
2266 width))))
2267
2268 (setq width (min window-width
2269 (max company-tooltip-minimum-width
2270 (if (and company-show-numbers
2271 (< company-tooltip-offset 10))
2272 (+ 2 width)
2273 width))))
2274
2275 ;; number can make tooltip too long
2276 (when company-show-numbers
2277 (setq numbered company-tooltip-offset))
2278
2279 (let ((items (nreverse items)) new)
2280 (when previous
2281 (push (company--scrollpos-line previous width) new))
2282
2283 (dotimes (i len)
2284 (let* ((item (pop items))
2285 (str (company-reformat (car item)))
2286 (annotation (cdr item))
2287 (right (company-space-string company-tooltip-margin))
2288 (width width))
2289 (when (< numbered 10)
2290 (cl-decf width 2)
2291 (cl-incf numbered)
2292 (setq right (concat (format " %d" (mod numbered 10)) right)))
2293 (push (concat
2294 (company-fill-propertize str annotation
2295 width (equal i selection)
2296 (company-space-string
2297 company-tooltip-margin)
2298 right)
2299 (when scrollbar-bounds
2300 (company--scrollbar i scrollbar-bounds)))
2301 new)))
2302
2303 (when remainder
2304 (push (company--scrollpos-line remainder width) new))
2305
2306 (nreverse new))))
2307
2308 (defun company--scrollbar-bounds (offset limit length)
2309 (when (> length limit)
2310 (let* ((size (ceiling (* limit (float limit)) length))
2311 (lower (floor (* limit (float offset)) length))
2312 (upper (+ lower size -1)))
2313 (cons lower upper))))
2314
2315 (defun company--scrollbar (i bounds)
2316 (propertize " " 'face
2317 (if (and (>= i (car bounds)) (<= i (cdr bounds)))
2318 'company-scrollbar-fg
2319 'company-scrollbar-bg)))
2320
2321 (defun company--scrollpos-line (text width)
2322 (propertize (concat (company-space-string company-tooltip-margin)
2323 (company-safe-substring text 0 width)
2324 (company-space-string company-tooltip-margin))
2325 'face 'company-tooltip))
2326
2327 ;; show
2328
2329 (defsubst company--window-inner-height ()
2330 (let ((edges (window-inside-edges)))
2331 (- (nth 3 edges) (nth 1 edges))))
2332
2333 (defsubst company--window-width ()
2334 (let ((ww (window-width)))
2335 ;; Account for the line continuation column.
2336 (when (zerop (cadr (window-fringes)))
2337 (cl-decf ww))
2338 (unless (or (display-graphic-p)
2339 (version< "24.3.1" emacs-version))
2340 ;; Emacs 24.3 and earlier included margins
2341 ;; in window-width when in TTY.
2342 (cl-decf ww
2343 (let ((margins (window-margins)))
2344 (+ (or (car margins) 0)
2345 (or (cdr margins) 0)))))
2346 ww))
2347
2348 (defun company--pseudo-tooltip-height ()
2349 "Calculate the appropriate tooltip height.
2350 Returns a negative number if the tooltip should be displayed above point."
2351 (let* ((lines (company--row))
2352 (below (- (company--window-inner-height) 1 lines)))
2353 (if (and (< below (min company-tooltip-minimum company-candidates-length))
2354 (> lines below))
2355 (- (max 3 (min company-tooltip-limit lines)))
2356 (max 3 (min company-tooltip-limit below)))))
2357
2358 (defun company-pseudo-tooltip-show (row column selection)
2359 (company-pseudo-tooltip-hide)
2360 (save-excursion
2361
2362 (let* ((height (company--pseudo-tooltip-height))
2363 above)
2364
2365 (when (< height 0)
2366 (setq row (+ row height -1)
2367 above t))
2368
2369 (let* ((nl (< (move-to-window-line row) row))
2370 (beg (point))
2371 (end (save-excursion
2372 (move-to-window-line (+ row (abs height)))
2373 (point)))
2374 (ov (make-overlay beg end))
2375 (args (list (mapcar 'company-plainify
2376 (company-buffer-lines beg end))
2377 column nl above)))
2378
2379 (setq company-pseudo-tooltip-overlay ov)
2380 (overlay-put ov 'company-replacement-args args)
2381
2382 (let ((lines (company--create-lines selection (abs height))))
2383 (overlay-put ov 'company-after
2384 (apply 'company--replacement-string lines args))
2385 (overlay-put ov 'company-width (string-width (car lines))))
2386
2387 (overlay-put ov 'company-column column)
2388 (overlay-put ov 'company-height height)))))
2389
2390 (defun company-pseudo-tooltip-show-at-point (pos column-offset)
2391 (let ((row (company--row pos))
2392 (col (- (company--column pos) column-offset)))
2393 (when (< col 0) (setq col 0))
2394 (company-pseudo-tooltip-show (1+ row) col company-selection)))
2395
2396 (defun company-pseudo-tooltip-edit (selection)
2397 (let* ((height (overlay-get company-pseudo-tooltip-overlay 'company-height))
2398 (lines (company--create-lines selection (abs height))))
2399 (overlay-put company-pseudo-tooltip-overlay 'company-width
2400 (string-width (car lines)))
2401 (overlay-put company-pseudo-tooltip-overlay 'company-after
2402 (apply 'company--replacement-string
2403 lines
2404 (overlay-get company-pseudo-tooltip-overlay
2405 'company-replacement-args)))))
2406
2407 (defun company-pseudo-tooltip-hide ()
2408 (when company-pseudo-tooltip-overlay
2409 (delete-overlay company-pseudo-tooltip-overlay)
2410 (setq company-pseudo-tooltip-overlay nil)))
2411
2412 (defun company-pseudo-tooltip-hide-temporarily ()
2413 (when (overlayp company-pseudo-tooltip-overlay)
2414 (overlay-put company-pseudo-tooltip-overlay 'invisible nil)
2415 (overlay-put company-pseudo-tooltip-overlay 'line-prefix nil)
2416 (overlay-put company-pseudo-tooltip-overlay 'after-string nil)))
2417
2418 (defun company-pseudo-tooltip-unhide ()
2419 (when company-pseudo-tooltip-overlay
2420 (overlay-put company-pseudo-tooltip-overlay 'invisible t)
2421 ;; Beat outline's folding overlays, at least.
2422 (overlay-put company-pseudo-tooltip-overlay 'priority 1)
2423 ;; No (extra) prefix for the first line.
2424 (overlay-put company-pseudo-tooltip-overlay 'line-prefix "")
2425 (overlay-put company-pseudo-tooltip-overlay 'after-string
2426 (overlay-get company-pseudo-tooltip-overlay 'company-after))
2427 (overlay-put company-pseudo-tooltip-overlay 'window (selected-window))))
2428
2429 (defun company-pseudo-tooltip-guard ()
2430 (list
2431 (save-excursion (beginning-of-visual-line))
2432 (let ((ov company-pseudo-tooltip-overlay))
2433 (when (>= (overlay-get ov 'company-height) 0)
2434 (buffer-substring-no-properties (point) (overlay-start ov))))))
2435
2436 (defun company-pseudo-tooltip-frontend (command)
2437 "`company-mode' front-end similar to a tooltip but based on overlays."
2438 (cl-case command
2439 (pre-command (company-pseudo-tooltip-hide-temporarily))
2440 (post-command
2441 (unless (when (overlayp company-pseudo-tooltip-overlay)
2442 (let* ((ov company-pseudo-tooltip-overlay)
2443 (old-height (overlay-get ov 'company-height))
2444 (new-height (company--pseudo-tooltip-height)))
2445 (and
2446 (>= (* old-height new-height) 0)
2447 (>= (abs old-height) (abs new-height))
2448 (equal (company-pseudo-tooltip-guard)
2449 (overlay-get ov 'company-guard)))))
2450 ;; Redraw needed.
2451 (company-pseudo-tooltip-show-at-point (point) (length company-prefix))
2452 (overlay-put company-pseudo-tooltip-overlay
2453 'company-guard (company-pseudo-tooltip-guard)))
2454 (company-pseudo-tooltip-unhide))
2455 (hide (company-pseudo-tooltip-hide)
2456 (setq company-tooltip-offset 0))
2457 (update (when (overlayp company-pseudo-tooltip-overlay)
2458 (company-pseudo-tooltip-edit company-selection)))))
2459
2460 (defun company-pseudo-tooltip-unless-just-one-frontend (command)
2461 "`company-pseudo-tooltip-frontend', but not shown for single candidates."
2462 (unless (and (eq command 'post-command)
2463 (company--show-inline-p))
2464 (company-pseudo-tooltip-frontend command)))
2465
2466 ;;; overlay ;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;
2467
2468 (defvar-local company-preview-overlay nil)
2469
2470 (defun company-preview-show-at-point (pos)
2471 (company-preview-hide)
2472
2473 (setq company-preview-overlay (make-overlay pos (1+ pos)))
2474
2475 (let ((completion (nth company-selection company-candidates)))
2476 (setq completion (propertize completion 'face 'company-preview))
2477 (add-text-properties 0 (length company-common)
2478 '(face company-preview-common) completion)
2479
2480 ;; Add search string
2481 (and company-search-string
2482 (string-match (regexp-quote company-search-string) completion)
2483 (add-text-properties (match-beginning 0)
2484 (match-end 0)
2485 '(face company-preview-search)
2486 completion))
2487
2488 (setq completion (company-strip-prefix completion))
2489
2490 (and (equal pos (point))
2491 (not (equal completion ""))
2492 (add-text-properties 0 1 '(cursor t) completion))
2493
2494 (overlay-put company-preview-overlay 'display
2495 (concat completion (unless (eq pos (point-max))
2496 (buffer-substring pos (1+ pos)))))
2497 (overlay-put company-preview-overlay 'window (selected-window))))
2498
2499 (defun company-preview-hide ()
2500 (when company-preview-overlay
2501 (delete-overlay company-preview-overlay)
2502 (setq company-preview-overlay nil)))
2503
2504 (defun company-preview-frontend (command)
2505 "`company-mode' front-end showing the selection as if it had been inserted."
2506 (pcase command
2507 (`pre-command (company-preview-hide))
2508 (`post-command (company-preview-show-at-point (point)))
2509 (`hide (company-preview-hide))))
2510
2511 (defun company-preview-if-just-one-frontend (command)
2512 "`company-preview-frontend', but only shown for single candidates."
2513 (when (or (not (eq command 'post-command))
2514 (company--show-inline-p))
2515 (company-preview-frontend command)))
2516
2517 (defun company--show-inline-p ()
2518 (and (not (cdr company-candidates))
2519 company-common
2520 (string-prefix-p company-prefix company-common
2521 (company-call-backend 'ignore-case))))
2522
2523 ;;; echo ;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;
2524
2525 (defvar-local company-echo-last-msg nil)
2526
2527 (defvar company-echo-timer nil)
2528
2529 (defvar company-echo-delay .01)
2530
2531 (defun company-echo-show (&optional getter)
2532 (when getter
2533 (setq company-echo-last-msg (funcall getter)))
2534 (let ((message-log-max nil))
2535 (if company-echo-last-msg
2536 (message "%s" company-echo-last-msg)
2537 (message ""))))
2538
2539 (defun company-echo-show-soon (&optional getter)
2540 (when company-echo-timer
2541 (cancel-timer company-echo-timer))
2542 (setq company-echo-timer (run-with-timer 0 nil 'company-echo-show getter)))
2543
2544 (defsubst company-echo-show-when-idle (&optional getter)
2545 (when (sit-for company-echo-delay)
2546 (company-echo-show getter)))
2547
2548 (defun company-echo-format ()
2549
2550 (let ((limit (window-width (minibuffer-window)))
2551 (len -1)
2552 ;; Roll to selection.
2553 (candidates (nthcdr company-selection company-candidates))
2554 (i (if company-show-numbers company-selection 99999))
2555 comp msg)
2556
2557 (while candidates
2558 (setq comp (company-reformat (pop candidates))
2559 len (+ len 1 (length comp)))
2560 (if (< i 10)
2561 ;; Add number.
2562 (progn
2563 (setq comp (propertize (format "%d: %s" i comp)
2564 'face 'company-echo))
2565 (cl-incf len 3)
2566 (cl-incf i)
2567 (add-text-properties 3 (+ 3 (length company-common))
2568 '(face company-echo-common) comp))
2569 (setq comp (propertize comp 'face 'company-echo))
2570 (add-text-properties 0 (length company-common)
2571 '(face company-echo-common) comp))
2572 (if (>= len limit)
2573 (setq candidates nil)
2574 (push comp msg)))
2575
2576 (mapconcat 'identity (nreverse msg) " ")))
2577
2578 (defun company-echo-strip-common-format ()
2579
2580 (let ((limit (window-width (minibuffer-window)))
2581 (len (+ (length company-prefix) 2))
2582 ;; Roll to selection.
2583 (candidates (nthcdr company-selection company-candidates))
2584 (i (if company-show-numbers company-selection 99999))
2585 msg comp)
2586
2587 (while candidates
2588 (setq comp (company-strip-prefix (pop candidates))
2589 len (+ len 2 (length comp)))
2590 (when (< i 10)
2591 ;; Add number.
2592 (setq comp (format "%s (%d)" comp i))
2593 (cl-incf len 4)
2594 (cl-incf i))
2595 (if (>= len limit)
2596 (setq candidates nil)
2597 (push (propertize comp 'face 'company-echo) msg)))
2598
2599 (concat (propertize company-prefix 'face 'company-echo-common) "{"
2600 (mapconcat 'identity (nreverse msg) ", ")
2601 "}")))
2602
2603 (defun company-echo-hide ()
2604 (unless (equal company-echo-last-msg "")
2605 (setq company-echo-last-msg "")
2606 (company-echo-show)))
2607
2608 (defun company-echo-frontend (command)
2609 "`company-mode' front-end showing the candidates in the echo area."
2610 (pcase command
2611 (`post-command (company-echo-show-soon 'company-echo-format))
2612 (`hide (company-echo-hide))))
2613
2614 (defun company-echo-strip-common-frontend (command)
2615 "`company-mode' front-end showing the candidates in the echo area."
2616 (pcase command
2617 (`post-command (company-echo-show-soon 'company-echo-strip-common-format))
2618 (`hide (company-echo-hide))))
2619
2620 (defun company-echo-metadata-frontend (command)
2621 "`company-mode' front-end showing the documentation in the echo area."
2622 (pcase command
2623 (`post-command (company-echo-show-when-idle 'company-fetch-metadata))
2624 (`hide (company-echo-hide))))
2625
2626 (provide 'company)
2627 ;;; company.el ends here