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