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