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