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