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