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