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