]> code.delx.au - gnu-emacs-elpa/blob - company.el
company-sort-by-occurrence: allow customizing the weighing logic
[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-cvs
9 ;; Keywords: abbrev, convenience, matching
10 ;; Package-Requires: ((emacs "24.1") (cl-lib "0.5"))
11
12 ;; This file is part of GNU Emacs.
13
14 ;; GNU Emacs is free software: you can redistribute it and/or modify
15 ;; it under the terms of the GNU General Public License as published by
16 ;; the Free Software Foundation, either version 3 of the License, or
17 ;; (at your option) any later version.
18
19 ;; GNU Emacs is distributed in the hope that it will be useful,
20 ;; but WITHOUT ANY WARRANTY; without even the implied warranty of
21 ;; MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
22 ;; GNU General Public License for more details.
23
24 ;; You should have received a copy of the GNU General Public License
25 ;; along with GNU Emacs. If not, see <http://www.gnu.org/licenses/>.
26
27 ;;; Commentary:
28 ;;
29 ;; Company is a modular completion mechanism. Modules for retrieving completion
30 ;; candidates are called back-ends, modules for displaying them are front-ends.
31 ;;
32 ;; Company comes with many back-ends, e.g. `company-elisp'. These are
33 ;; distributed in separate files and can be used individually.
34 ;;
35 ;; Place company.el and the back-ends you want to use in a directory and add the
36 ;; following to your .emacs:
37 ;; (add-to-list 'load-path "/path/to/company")
38 ;; (autoload 'company-mode "company" nil t)
39 ;;
40 ;; Enable company-mode with M-x company-mode. For further information look at
41 ;; the documentation for `company-mode' (C-h f company-mode RET)
42 ;;
43 ;; If you want to start a specific back-end, call it interactively or use
44 ;; `company-begin-backend'. For example:
45 ;; M-x company-abbrev will prompt for and insert an abbrev.
46 ;;
47 ;; To write your own back-end, look at the documentation for `company-backends'.
48 ;; Here is a simple example completing "foo":
49 ;;
50 ;; (defun company-my-backend (command &optional arg &rest ignored)
51 ;; (pcase command
52 ;; (`prefix (when (looking-back "foo\\>")
53 ;; (match-string 0)))
54 ;; (`candidates (list "foobar" "foobaz" "foobarbaz"))
55 ;; (`meta (format "This value is named %s" arg))))
56 ;;
57 ;; Sometimes it is a good idea to mix several back-ends together, for example to
58 ;; enrich gtags with dabbrev-code results (to emulate local variables).
59 ;; To do this, add a list with both back-ends as an element in company-backends.
60 ;;
61 ;; Known Issues:
62 ;; When point is at the very end of the buffer, the pseudo-tooltip appears very
63 ;; wrong, unless company is allowed to temporarily insert a fake newline.
64 ;; This behavior is enabled by `company-end-of-buffer-workaround'.
65 ;;
66 ;;; Change Log:
67 ;;
68 ;; See NEWS.md in the repository.
69
70 ;;; Code:
71
72 (require 'cl-lib)
73 (require 'newcomment)
74
75 ;; FIXME: Use `user-error'.
76 (add-to-list 'debug-ignored-errors "^.* frontend cannot be used twice$")
77 (add-to-list 'debug-ignored-errors "^Echo area cannot be used twice$")
78 (add-to-list 'debug-ignored-errors "^No \\(document\\|loc\\)ation available$")
79 (add-to-list 'debug-ignored-errors "^Company not ")
80 (add-to-list 'debug-ignored-errors "^No candidate number ")
81 (add-to-list 'debug-ignored-errors "^Cannot complete at point$")
82 (add-to-list 'debug-ignored-errors "^No other back-end$")
83
84 ;;; Compatibility
85 (eval-and-compile
86 ;; `defvar-local' for Emacs 24.2 and below
87 (unless (fboundp 'defvar-local)
88 (defmacro defvar-local (var val &optional docstring)
89 "Define VAR as a buffer-local variable with default value VAL.
90 Like `defvar' but additionally marks the variable as being automatically
91 buffer-local wherever it is set."
92 (declare (debug defvar) (doc-string 3))
93 `(progn
94 (defvar ,var ,val ,docstring)
95 (make-variable-buffer-local ',var)))))
96
97 (defgroup company nil
98 "Extensible inline text completion mechanism"
99 :group 'abbrev
100 :group 'convenience
101 :group 'matching)
102
103 (defface company-tooltip
104 '((default :foreground "black")
105 (((class color) (min-colors 88) (background light))
106 (:background "cornsilk"))
107 (((class color) (min-colors 88) (background dark))
108 (:background "yellow")))
109 "Face used for the tooltip.")
110
111 (defface company-tooltip-selection
112 '((default :inherit company-tooltip)
113 (((class color) (min-colors 88) (background light))
114 (:background "light blue"))
115 (((class color) (min-colors 88) (background dark))
116 (:background "orange1"))
117 (t (:background "green")))
118 "Face used for the selection in the tooltip.")
119
120 (defface company-tooltip-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 two arguments: the beginning and the end of the match."
1198 :type '(choice
1199 (const :tag "First above point, then below point"
1200 company-occurrence-prefer-closest-above)
1201 (const :tag "Prefer closest in any direction"
1202 company-occurrence-prefer-any-closest)))
1203
1204 (defun company-occurrence-prefer-closest-above (match-beg match-end)
1205 "Give priority to the matches above point, then those below point."
1206 (if (< match-beg (point))
1207 (- (point) match-end)
1208 (- match-beg (window-start))))
1209
1210 (defun company-occurrence-prefer-any-closest (_match-beg match-end)
1211 "Give priority to the matches closest to the point."
1212 (abs (- (point) match-end)))
1213
1214 (defun company-sort-by-occurrence (candidates)
1215 "Sort CANDIDATES according to their occurrences.
1216 Searches for each in the currently visible part of the current buffer and
1217 prioritizes the matches according to `company-occurrence-weight-function'.
1218 The rest of the list is appended unchanged.
1219 Keywords and function definition names are ignored."
1220 (let* (occurs
1221 (noccurs
1222 (cl-delete-if
1223 (lambda (candidate)
1224 (when (or
1225 (save-excursion
1226 (forward-char (- (length company-prefix)))
1227 (search-backward candidate (window-start) t))
1228 (save-excursion
1229 (search-forward candidate (window-end) t)))
1230 (let ((beg (match-beginning 0))
1231 (end (match-end 0)))
1232 (when (save-excursion
1233 (goto-char end)
1234 (and (not (memq (get-text-property (point) 'face)
1235 '(font-lock-function-name-face
1236 font-lock-keyword-face)))
1237 (let ((prefix (company--prefix-str
1238 (company-call-backend 'prefix))))
1239 (and (stringp prefix)
1240 (= (length prefix) (- end beg))))))
1241 (push
1242 (cons candidate
1243 (funcall company-occurrence-weight-function beg end))
1244 occurs)
1245 t))))
1246 candidates)))
1247 (nconc
1248 (mapcar #'car (sort occurs (lambda (e1 e2) (<= (cdr e1) (cdr e2)))))
1249 noccurs)))
1250
1251 (defun company-sort-by-backend-importance (candidates)
1252 "Sort CANDIDATES as two priority groups.
1253 If `company-backend' is a function, do nothing. If it's a list, move
1254 candidates from back-ends before keyword `:with' to the front. Candidates
1255 from the rest of the back-ends in the group, if any, will be left at the end."
1256 (if (functionp company-backend)
1257 candidates
1258 (let ((low-priority (cdr (memq :with company-backend))))
1259 (if (null low-priority)
1260 candidates
1261 (sort candidates
1262 (lambda (c1 c2)
1263 (and
1264 (let ((b2 (get-text-property 0 'company-backend c2)))
1265 (and b2 (memq b2 low-priority)))
1266 (let ((b1 (get-text-property 0 'company-backend c1)))
1267 (or (not b1) (not (memq b1 low-priority)))))))))))
1268
1269 (defun company-idle-begin (buf win tick pos)
1270 (and (eq buf (current-buffer))
1271 (eq win (selected-window))
1272 (eq tick (buffer-chars-modified-tick))
1273 (eq pos (point))
1274 (when (company-auto-begin)
1275 (when (version< emacs-version "24.3.50")
1276 (company-input-noop))
1277 (company-post-command))))
1278
1279 (defun company-auto-begin ()
1280 (and company-mode
1281 (not company-candidates)
1282 (let ((company-idle-delay 'now))
1283 (condition-case-unless-debug err
1284 (company--perform)
1285 (error (message "Company: An error occurred in auto-begin")
1286 (message "%s" (error-message-string err))
1287 (company-cancel))
1288 (quit (company-cancel)))))
1289 (unless company-candidates
1290 (setq company-backend nil))
1291 ;; Return non-nil if active.
1292 company-candidates)
1293
1294 (defun company-manual-begin ()
1295 (interactive)
1296 (company-assert-enabled)
1297 (setq company--manual-action t)
1298 (unwind-protect
1299 (let ((company-minimum-prefix-length 0))
1300 (company-auto-begin))
1301 (unless company-candidates
1302 (setq company--manual-action nil))))
1303
1304 (defun company-other-backend (&optional backward)
1305 (interactive (list current-prefix-arg))
1306 (company-assert-enabled)
1307 (let* ((after (if company-backend
1308 (cdr (member company-backend company-backends))
1309 company-backends))
1310 (before (cdr (member company-backend (reverse company-backends))))
1311 (next (if backward
1312 (append before (reverse after))
1313 (append after (reverse before)))))
1314 (company-cancel)
1315 (cl-dolist (backend next)
1316 (when (ignore-errors (company-begin-backend backend))
1317 (cl-return t))))
1318 (unless company-candidates
1319 (error "No other back-end")))
1320
1321 (defun company-require-match-p ()
1322 (let ((backend-value (company-call-backend 'require-match)))
1323 (or (eq backend-value t)
1324 (and (not (eq backend-value 'never))
1325 (if (functionp company-require-match)
1326 (funcall company-require-match)
1327 (eq company-require-match t))))))
1328
1329 (defun company-auto-complete-p (input)
1330 "Return non-nil, if input starts with punctuation or parentheses."
1331 (and (if (functionp company-auto-complete)
1332 (funcall company-auto-complete)
1333 company-auto-complete)
1334 (if (functionp company-auto-complete-chars)
1335 (funcall company-auto-complete-chars input)
1336 (if (consp company-auto-complete-chars)
1337 (memq (char-syntax (string-to-char input))
1338 company-auto-complete-chars)
1339 (string-match (substring input 0 1) company-auto-complete-chars)))))
1340
1341 (defun company--incremental-p ()
1342 (and (> (point) company-point)
1343 (> (point-max) company--point-max)
1344 (not (eq this-command 'backward-delete-char-untabify))
1345 (equal (buffer-substring (- company-point (length company-prefix))
1346 company-point)
1347 company-prefix)))
1348
1349 (defun company--continue-failed (new-prefix)
1350 (let ((input (buffer-substring-no-properties (point) company-point)))
1351 (cond
1352 ((company-auto-complete-p input)
1353 ;; auto-complete
1354 (save-excursion
1355 (goto-char company-point)
1356 (let ((company--auto-completion t))
1357 (company-complete-selection))
1358 nil))
1359 ((and (or (not (company-require-match-p))
1360 ;; Don't require match if the new prefix
1361 ;; doesn't continue the old one, and the latter was a match.
1362 (<= (length new-prefix) (length company-prefix)))
1363 (member company-prefix company-candidates))
1364 ;; Last input was a success,
1365 ;; but we're treating it as an abort + input anyway,
1366 ;; like the `unique' case below.
1367 (company-cancel 'non-unique))
1368 ((company-require-match-p)
1369 ;; Wrong incremental input, but required match.
1370 (delete-char (- (length input)))
1371 (ding)
1372 (message "Matching input is required")
1373 company-candidates)
1374 (t (company-cancel)))))
1375
1376 (defun company--good-prefix-p (prefix)
1377 (and (stringp (company--prefix-str prefix)) ;excludes 'stop
1378 (or (eq (cdr-safe prefix) t)
1379 (let ((len (or (cdr-safe prefix) (length prefix))))
1380 (if company--manual-prefix
1381 (or (not company-abort-manual-when-too-short)
1382 ;; Must not be less than minimum or initial length.
1383 (>= len (min company-minimum-prefix-length
1384 (length company--manual-prefix))))
1385 (>= len company-minimum-prefix-length))))))
1386
1387 (defun company--continue ()
1388 (when (company-call-backend 'no-cache company-prefix)
1389 ;; Don't complete existing candidates, fetch new ones.
1390 (setq company-candidates-cache nil))
1391 (let* ((new-prefix (company-call-backend 'prefix))
1392 (c (when (and (company--good-prefix-p new-prefix)
1393 (setq new-prefix (company--prefix-str new-prefix))
1394 (= (- (point) (length new-prefix))
1395 (- company-point (length company-prefix))))
1396 (company-calculate-candidates new-prefix))))
1397 (cond
1398 ((eq c t)
1399 ;; t means complete/unique.
1400 ;; Handle it like completion was aborted, to differentiate from user
1401 ;; calling one of Company's commands to insert the candidate,
1402 ;; not to trigger template expansion, etc.
1403 (company-cancel 'unique))
1404 ((consp c)
1405 ;; incremental match
1406 (setq company-prefix new-prefix)
1407 (company-update-candidates c)
1408 c)
1409 ((not (company--incremental-p))
1410 (company-cancel))
1411 (t (company--continue-failed new-prefix)))))
1412
1413 (defun company--begin-new ()
1414 (let (prefix c)
1415 (cl-dolist (backend (if company-backend
1416 ;; prefer manual override
1417 (list company-backend)
1418 company-backends))
1419 (setq prefix
1420 (if (or (symbolp backend)
1421 (functionp backend))
1422 (when (or (not (symbolp backend))
1423 (eq t (get backend 'company-init))
1424 (unless (get backend 'company-init)
1425 (company-init-backend backend)))
1426 (funcall backend 'prefix))
1427 (company--multi-backend-adapter backend 'prefix)))
1428 (when prefix
1429 (when (company--good-prefix-p prefix)
1430 (setq company-prefix (company--prefix-str prefix)
1431 company-backend backend
1432 c (company-calculate-candidates company-prefix))
1433 ;; t means complete/unique. We don't start, so no hooks.
1434 (if (not (consp c))
1435 (when company--manual-action
1436 (message "No completion found"))
1437 (when company--manual-action
1438 (setq company--manual-prefix prefix))
1439 (if (symbolp backend)
1440 (setq company-lighter (concat " " (symbol-name backend)))
1441 (company--update-group-lighter (car c)))
1442 (company-update-candidates c)
1443 (run-hook-with-args 'company-completion-started-hook
1444 (company-explicit-action-p))
1445 (company-call-frontends 'show)))
1446 (cl-return c)))))
1447
1448 (defun company--perform ()
1449 (or (and company-candidates (company--continue))
1450 (and (company--should-complete) (company--begin-new)))
1451 (when company-candidates
1452 (let ((modified (buffer-modified-p)))
1453 (when (and company-end-of-buffer-workaround (eobp))
1454 (save-excursion (insert "\n"))
1455 (setq company-added-newline
1456 (or modified (buffer-chars-modified-tick)))))
1457 (setq company-point (point)
1458 company--point-max (point-max))
1459 (company-ensure-emulation-alist)
1460 (company-enable-overriding-keymap company-active-map)
1461 (company-call-frontends 'update)))
1462
1463 (defun company-cancel (&optional result)
1464 (and company-added-newline
1465 (> (point-max) (point-min))
1466 (let ((tick (buffer-chars-modified-tick)))
1467 (delete-region (1- (point-max)) (point-max))
1468 (equal tick company-added-newline))
1469 ;; Only set unmodified when tick remained the same since insert,
1470 ;; and the buffer wasn't modified before.
1471 (set-buffer-modified-p nil))
1472 (unwind-protect
1473 (when company-prefix
1474 (if (stringp result)
1475 (progn
1476 (company-call-backend 'pre-completion result)
1477 (run-hook-with-args 'company-completion-finished-hook result)
1478 (company-call-backend 'post-completion result))
1479 (run-hook-with-args 'company-completion-cancelled-hook result)))
1480 (setq company-added-newline nil
1481 company-backend nil
1482 company-prefix nil
1483 company-candidates nil
1484 company-candidates-length nil
1485 company-candidates-cache nil
1486 company-candidates-predicate nil
1487 company-common nil
1488 company-selection 0
1489 company-selection-changed nil
1490 company--manual-action nil
1491 company--manual-prefix nil
1492 company-lighter company-default-lighter
1493 company--point-max nil
1494 company-point nil)
1495 (when company-timer
1496 (cancel-timer company-timer))
1497 (company-search-mode 0)
1498 (company-call-frontends 'hide)
1499 (company-enable-overriding-keymap nil))
1500 ;; Make return value explicit.
1501 nil)
1502
1503 (defun company-abort ()
1504 (interactive)
1505 (company-cancel 'abort))
1506
1507 (defun company-finish (result)
1508 (company--insert-candidate result)
1509 (company-cancel result))
1510
1511 (defsubst company-keep (command)
1512 (and (symbolp command) (get command 'company-keep)))
1513
1514 (defun company-pre-command ()
1515 (unless (company-keep this-command)
1516 (condition-case err
1517 (when company-candidates
1518 (company-call-frontends 'pre-command)
1519 (unless (company--should-continue)
1520 (company-abort)))
1521 (error (message "Company: An error occurred in pre-command")
1522 (message "%s" (error-message-string err))
1523 (company-cancel))))
1524 (when company-timer
1525 (cancel-timer company-timer)
1526 (setq company-timer nil))
1527 (company-uninstall-map))
1528
1529 (defun company-post-command ()
1530 (unless (company-keep this-command)
1531 (condition-case err
1532 (progn
1533 (unless (equal (point) company-point)
1534 (let (company-idle-delay) ; Against misbehavior while debugging.
1535 (company--perform)))
1536 (if company-candidates
1537 (company-call-frontends 'post-command)
1538 (and (numberp company-idle-delay)
1539 (company--should-begin)
1540 (setq company-timer
1541 (run-with-timer company-idle-delay nil
1542 'company-idle-begin
1543 (current-buffer) (selected-window)
1544 (buffer-chars-modified-tick) (point))))))
1545 (error (message "Company: An error occurred in post-command")
1546 (message "%s" (error-message-string err))
1547 (company-cancel))))
1548 (company-install-map))
1549
1550 (defvar company--begin-inhibit-commands '(company-abort
1551 company-complete-mouse
1552 company-complete
1553 company-complete-common
1554 company-complete-selection
1555 company-complete-number)
1556 "List of commands after which idle completion is (still) disabled when
1557 `company-begin-commands' is t.")
1558
1559 (defun company--should-begin ()
1560 (if (eq t company-begin-commands)
1561 (not (memq this-command company--begin-inhibit-commands))
1562 (or
1563 (memq this-command company-begin-commands)
1564 (and (symbolp this-command) (get this-command 'company-begin)))))
1565
1566 ;;; search ;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;
1567
1568 (defvar-local company-search-string nil)
1569
1570 (defvar-local company-search-lighter " Search: \"\"")
1571
1572 (defvar-local company-search-old-map nil)
1573
1574 (defvar-local company-search-old-selection 0)
1575
1576 (defun company-search (text lines)
1577 (let ((quoted (regexp-quote text))
1578 (i 0))
1579 (cl-dolist (line lines)
1580 (when (string-match quoted line (length company-prefix))
1581 (cl-return i))
1582 (cl-incf i))))
1583
1584 (defun company-search-printing-char ()
1585 (interactive)
1586 (company-search-assert-enabled)
1587 (setq company-search-string
1588 (concat (or company-search-string "") (string last-command-event))
1589 company-search-lighter (concat " Search: \"" company-search-string
1590 "\""))
1591 (let ((pos (company-search company-search-string
1592 (nthcdr company-selection company-candidates))))
1593 (if (null pos)
1594 (ding)
1595 (company-set-selection (+ company-selection pos) t))))
1596
1597 (defun company-search-repeat-forward ()
1598 "Repeat the incremental search in completion candidates forward."
1599 (interactive)
1600 (company-search-assert-enabled)
1601 (let ((pos (company-search company-search-string
1602 (cdr (nthcdr company-selection
1603 company-candidates)))))
1604 (if (null pos)
1605 (ding)
1606 (company-set-selection (+ company-selection pos 1) t))))
1607
1608 (defun company-search-repeat-backward ()
1609 "Repeat the incremental search in completion candidates backwards."
1610 (interactive)
1611 (company-search-assert-enabled)
1612 (let ((pos (company-search company-search-string
1613 (nthcdr (- company-candidates-length
1614 company-selection)
1615 (reverse company-candidates)))))
1616 (if (null pos)
1617 (ding)
1618 (company-set-selection (- company-selection pos 1) t))))
1619
1620 (defun company-create-match-predicate ()
1621 (setq company-candidates-predicate
1622 `(lambda (candidate)
1623 ,(if company-candidates-predicate
1624 `(and (string-match ,company-search-string candidate)
1625 (funcall ,company-candidates-predicate
1626 candidate))
1627 `(string-match ,company-search-string candidate))))
1628 (company-update-candidates
1629 (company-apply-predicate company-candidates company-candidates-predicate))
1630 ;; Invalidate cache.
1631 (setq company-candidates-cache (cons company-prefix company-candidates)))
1632
1633 (defun company-filter-printing-char ()
1634 (interactive)
1635 (company-search-assert-enabled)
1636 (company-search-printing-char)
1637 (company-create-match-predicate)
1638 (company-call-frontends 'update))
1639
1640 (defun company-search-kill-others ()
1641 "Limit the completion candidates to the ones matching the search string."
1642 (interactive)
1643 (company-search-assert-enabled)
1644 (company-create-match-predicate)
1645 (company-search-mode 0)
1646 (company-call-frontends 'update))
1647
1648 (defun company-search-abort ()
1649 "Abort searching the completion candidates."
1650 (interactive)
1651 (company-search-assert-enabled)
1652 (company-set-selection company-search-old-selection t)
1653 (company-search-mode 0))
1654
1655 (defun company-search-other-char ()
1656 (interactive)
1657 (company-search-assert-enabled)
1658 (company-search-mode 0)
1659 (company--unread-last-input))
1660
1661 (defvar company-search-map
1662 (let ((i 0)
1663 (keymap (make-keymap)))
1664 (if (fboundp 'max-char)
1665 (set-char-table-range (nth 1 keymap) (cons #x100 (max-char))
1666 'company-search-printing-char)
1667 (with-no-warnings
1668 ;; obsolete in Emacs 23
1669 (let ((l (generic-character-list))
1670 (table (nth 1 keymap)))
1671 (while l
1672 (set-char-table-default table (car l) 'company-search-printing-char)
1673 (setq l (cdr l))))))
1674 (define-key keymap [t] 'company-search-other-char)
1675 (while (< i ?\s)
1676 (define-key keymap (make-string 1 i) 'company-search-other-char)
1677 (cl-incf i))
1678 (while (< i 256)
1679 (define-key keymap (vector i) 'company-search-printing-char)
1680 (cl-incf i))
1681 (let ((meta-map (make-sparse-keymap)))
1682 (define-key keymap (char-to-string meta-prefix-char) meta-map)
1683 (define-key keymap [escape] meta-map))
1684 (define-key keymap (vector meta-prefix-char t) 'company-search-other-char)
1685 (define-key keymap "\e\e\e" 'company-search-other-char)
1686 (define-key keymap [escape escape escape] 'company-search-other-char)
1687 (define-key keymap (kbd "DEL") 'company-search-other-char)
1688
1689 (define-key keymap "\C-g" 'company-search-abort)
1690 (define-key keymap "\C-s" 'company-search-repeat-forward)
1691 (define-key keymap "\C-r" 'company-search-repeat-backward)
1692 (define-key keymap "\C-o" 'company-search-kill-others)
1693 keymap)
1694 "Keymap used for incrementally searching the completion candidates.")
1695
1696 (define-minor-mode company-search-mode
1697 "Search mode for completion candidates.
1698 Don't start this directly, use `company-search-candidates' or
1699 `company-filter-candidates'."
1700 nil company-search-lighter nil
1701 (if company-search-mode
1702 (if (company-manual-begin)
1703 (progn
1704 (setq company-search-old-selection company-selection)
1705 (company-call-frontends 'update))
1706 (setq company-search-mode nil))
1707 (kill-local-variable 'company-search-string)
1708 (kill-local-variable 'company-search-lighter)
1709 (kill-local-variable 'company-search-old-selection)
1710 (company-enable-overriding-keymap company-active-map)))
1711
1712 (defun company-search-assert-enabled ()
1713 (company-assert-enabled)
1714 (unless company-search-mode
1715 (company-uninstall-map)
1716 (error "Company not in search mode")))
1717
1718 (defun company-search-candidates ()
1719 "Start searching the completion candidates incrementally.
1720
1721 \\<company-search-map>Search can be controlled with the commands:
1722 - `company-search-repeat-forward' (\\[company-search-repeat-forward])
1723 - `company-search-repeat-backward' (\\[company-search-repeat-backward])
1724 - `company-search-abort' (\\[company-search-abort])
1725
1726 Regular characters are appended to the search string.
1727
1728 The command `company-search-kill-others' (\\[company-search-kill-others])
1729 uses the search string to limit the completion candidates."
1730 (interactive)
1731 (company-search-mode 1)
1732 (company-enable-overriding-keymap company-search-map))
1733
1734 (defvar company-filter-map
1735 (let ((keymap (make-keymap)))
1736 (define-key keymap [remap company-search-printing-char]
1737 'company-filter-printing-char)
1738 (set-keymap-parent keymap company-search-map)
1739 keymap)
1740 "Keymap used for incrementally searching the completion candidates.")
1741
1742 (defun company-filter-candidates ()
1743 "Start filtering the completion candidates incrementally.
1744 This works the same way as `company-search-candidates' immediately
1745 followed by `company-search-kill-others' after each input."
1746 (interactive)
1747 (company-search-mode 1)
1748 (company-enable-overriding-keymap company-filter-map))
1749
1750 ;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;
1751
1752 (defun company-select-next ()
1753 "Select the next candidate in the list."
1754 (interactive)
1755 (when (company-manual-begin)
1756 (company-set-selection (1+ company-selection))))
1757
1758 (defun company-select-previous ()
1759 "Select the previous candidate in the list."
1760 (interactive)
1761 (when (company-manual-begin)
1762 (company-set-selection (1- company-selection))))
1763
1764 (defun company-select-next-or-abort ()
1765 "Select the next candidate if more than one, else abort
1766 and invoke the normal binding."
1767 (interactive)
1768 (if (> company-candidates-length 1)
1769 (company-select-next)
1770 (company-abort)
1771 (company--unread-last-input)))
1772
1773 (defun company-select-previous-or-abort ()
1774 "Select the previous candidate if more than one, else abort
1775 and invoke the normal binding."
1776 (interactive)
1777 (if (> company-candidates-length 1)
1778 (company-select-previous)
1779 (company-abort)
1780 (company--unread-last-input)))
1781
1782 (defvar company-pseudo-tooltip-overlay)
1783
1784 (defvar company-tooltip-offset)
1785
1786 (defun company--inside-tooltip-p (event-col-row row height)
1787 (let* ((ovl company-pseudo-tooltip-overlay)
1788 (column (overlay-get ovl 'company-column))
1789 (width (overlay-get ovl 'company-width))
1790 (evt-col (car event-col-row))
1791 (evt-row (cdr event-col-row)))
1792 (and (>= evt-col column)
1793 (< evt-col (+ column width))
1794 (if (> height 0)
1795 (and (> evt-row row)
1796 (<= evt-row (+ row height) ))
1797 (and (< evt-row row)
1798 (>= evt-row (+ row height)))))))
1799
1800 (defun company--event-col-row (event)
1801 (let* ((col-row (posn-actual-col-row (event-start event)))
1802 (col (car col-row))
1803 (row (cdr col-row)))
1804 (cl-incf col (window-hscroll))
1805 (and header-line-format
1806 (version< "24" emacs-version)
1807 (cl-decf row))
1808 (cons col row)))
1809
1810 (defun company-select-mouse (event)
1811 "Select the candidate picked by the mouse."
1812 (interactive "e")
1813 (let ((event-col-row (company--event-col-row event))
1814 (ovl-row (company--row))
1815 (ovl-height (and company-pseudo-tooltip-overlay
1816 (min (overlay-get company-pseudo-tooltip-overlay
1817 'company-height)
1818 company-candidates-length))))
1819 (if (and ovl-height
1820 (company--inside-tooltip-p event-col-row ovl-row ovl-height))
1821 (progn
1822 (company-set-selection (+ (cdr event-col-row)
1823 (1- company-tooltip-offset)
1824 (if (and (eq company-tooltip-offset-display 'lines)
1825 (not (zerop company-tooltip-offset)))
1826 -1 0)
1827 (- ovl-row)
1828 (if (< ovl-height 0)
1829 (- 1 ovl-height)
1830 0)))
1831 t)
1832 (company-abort)
1833 (company--unread-last-input)
1834 nil)))
1835
1836 (defun company-complete-mouse (event)
1837 "Insert the candidate picked by the mouse."
1838 (interactive "e")
1839 (when (company-select-mouse event)
1840 (company-complete-selection)))
1841
1842 (defun company-complete-selection ()
1843 "Insert the selected candidate."
1844 (interactive)
1845 (when (company-manual-begin)
1846 (let ((result (nth company-selection company-candidates)))
1847 (company-finish result))))
1848
1849 (defun company-complete-common ()
1850 "Insert the common part of all candidates."
1851 (interactive)
1852 (when (company-manual-begin)
1853 (if (and (not (cdr company-candidates))
1854 (equal company-common (car company-candidates)))
1855 (company-complete-selection)
1856 (when company-common
1857 (company--insert-candidate company-common)))))
1858
1859 (defun company-complete ()
1860 "Insert the common part of all candidates or the current selection.
1861 The first time this is called, the common part is inserted, the second
1862 time, or when the selection has been changed, the selected candidate is
1863 inserted."
1864 (interactive)
1865 (when (company-manual-begin)
1866 (if (or company-selection-changed
1867 (eq last-command 'company-complete-common))
1868 (call-interactively 'company-complete-selection)
1869 (call-interactively 'company-complete-common)
1870 (setq this-command 'company-complete-common))))
1871
1872 (defun company-complete-number (n)
1873 "Insert the Nth candidate.
1874 To show the number next to the candidates in some back-ends, enable
1875 `company-show-numbers'."
1876 (when (company-manual-begin)
1877 (and (or (< n 1) (> n company-candidates-length))
1878 (error "No candidate number %d" n))
1879 (cl-decf n)
1880 (company-finish (nth n company-candidates))))
1881
1882 ;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;
1883
1884 (defconst company-space-strings-limit 100)
1885
1886 (defconst company-space-strings
1887 (let (lst)
1888 (dotimes (i company-space-strings-limit)
1889 (push (make-string (- company-space-strings-limit 1 i) ?\ ) lst))
1890 (apply 'vector lst)))
1891
1892 (defun company-space-string (len)
1893 (if (< len company-space-strings-limit)
1894 (aref company-space-strings len)
1895 (make-string len ?\ )))
1896
1897 (defun company-safe-substring (str from &optional to)
1898 (if (> from (string-width str))
1899 ""
1900 (with-temp-buffer
1901 (insert str)
1902 (move-to-column from)
1903 (let ((beg (point)))
1904 (if to
1905 (progn
1906 (move-to-column to)
1907 (concat (buffer-substring beg (point))
1908 (let ((padding (- to (current-column))))
1909 (when (> padding 0)
1910 (company-space-string padding)))))
1911 (buffer-substring beg (point-max)))))))
1912
1913 ;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;
1914
1915 (defvar-local company-last-metadata nil)
1916
1917 (defun company-fetch-metadata ()
1918 (let ((selected (nth company-selection company-candidates)))
1919 (unless (eq selected (car company-last-metadata))
1920 (setq company-last-metadata
1921 (cons selected (company-call-backend 'meta selected))))
1922 (cdr company-last-metadata)))
1923
1924 (defun company-doc-buffer (&optional string)
1925 (with-current-buffer (get-buffer-create "*company-documentation*")
1926 (erase-buffer)
1927 (when string
1928 (save-excursion
1929 (insert string)))
1930 (current-buffer)))
1931
1932 (defvar company--electric-commands
1933 '(scroll-other-window scroll-other-window-down)
1934 "List of Commands that won't break out of electric commands.")
1935
1936 (defmacro company--electric-do (&rest body)
1937 (declare (indent 0) (debug t))
1938 `(when (company-manual-begin)
1939 (save-window-excursion
1940 (let ((height (window-height))
1941 (row (company--row))
1942 cmd)
1943 ,@body
1944 (and (< (window-height) height)
1945 (< (- (window-height) row 2) company-tooltip-limit)
1946 (recenter (- (window-height) row 2)))
1947 (while (memq (setq cmd (key-binding (vector (list (read-event)))))
1948 company--electric-commands)
1949 (call-interactively cmd))
1950 (company--unread-last-input)))))
1951
1952 (defun company--unread-last-input ()
1953 (when last-input-event
1954 (clear-this-command-keys t)
1955 (setq unread-command-events (list last-input-event))))
1956
1957 (defun company-show-doc-buffer ()
1958 "Temporarily show the documentation buffer for the selection."
1959 (interactive)
1960 (company--electric-do
1961 (let* ((selected (nth company-selection company-candidates))
1962 (doc-buffer (or (company-call-backend 'doc-buffer selected)
1963 (error "No documentation available"))))
1964 (with-current-buffer doc-buffer
1965 (goto-char (point-min)))
1966 (display-buffer doc-buffer t))))
1967 (put 'company-show-doc-buffer 'company-keep t)
1968
1969 (defun company-show-location ()
1970 "Temporarily display a buffer showing the selected candidate in context."
1971 (interactive)
1972 (company--electric-do
1973 (let* ((selected (nth company-selection company-candidates))
1974 (location (company-call-backend 'location selected))
1975 (pos (or (cdr location) (error "No location available")))
1976 (buffer (or (and (bufferp (car location)) (car location))
1977 (find-file-noselect (car location) t))))
1978 (with-selected-window (display-buffer buffer t)
1979 (save-restriction
1980 (widen)
1981 (if (bufferp (car location))
1982 (goto-char pos)
1983 (goto-char (point-min))
1984 (forward-line (1- pos))))
1985 (set-window-start nil (point))))))
1986 (put 'company-show-location 'company-keep t)
1987
1988 ;;; package functions ;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;
1989
1990 (defvar-local company-callback nil)
1991
1992 (defun company-remove-callback (&optional ignored)
1993 (remove-hook 'company-completion-finished-hook company-callback t)
1994 (remove-hook 'company-completion-cancelled-hook 'company-remove-callback t)
1995 (remove-hook 'company-completion-finished-hook 'company-remove-callback t))
1996
1997 (defun company-begin-backend (backend &optional callback)
1998 "Start a completion at point using BACKEND."
1999 (interactive (let ((val (completing-read "Company back-end: "
2000 obarray
2001 'functionp nil "company-")))
2002 (when val
2003 (list (intern val)))))
2004 (when (setq company-callback callback)
2005 (add-hook 'company-completion-finished-hook company-callback nil t))
2006 (add-hook 'company-completion-cancelled-hook 'company-remove-callback nil t)
2007 (add-hook 'company-completion-finished-hook 'company-remove-callback nil t)
2008 (setq company-backend backend)
2009 ;; Return non-nil if active.
2010 (or (company-manual-begin)
2011 (error "Cannot complete at point")))
2012
2013 (defun company-begin-with (candidates
2014 &optional prefix-length require-match callback)
2015 "Start a completion at point.
2016 CANDIDATES is the list of candidates to use and PREFIX-LENGTH is the length
2017 of the prefix that already is in the buffer before point.
2018 It defaults to 0.
2019
2020 CALLBACK is a function called with the selected result if the user
2021 successfully completes the input.
2022
2023 Example: \(company-begin-with '\(\"foo\" \"foobar\" \"foobarbaz\"\)\)"
2024 (let ((begin-marker (copy-marker (point) t)))
2025 (company-begin-backend
2026 (lambda (command &optional arg &rest ignored)
2027 (pcase command
2028 (`prefix
2029 (when (equal (point) (marker-position begin-marker))
2030 (buffer-substring (- (point) (or prefix-length 0)) (point))))
2031 (`candidates
2032 (all-completions arg candidates))
2033 (`require-match
2034 require-match)))
2035 callback)))
2036
2037 (defun company-version (&optional show-version)
2038 "Get the Company version as string.
2039
2040 If SHOW-VERSION is non-nil, show the version in the echo area."
2041 (interactive (list t))
2042 (with-temp-buffer
2043 (insert-file-contents (find-library-name "company"))
2044 (require 'lisp-mnt)
2045 (if show-version
2046 (message "Company version: %s" (lm-version))
2047 (lm-version))))
2048
2049 ;;; pseudo-tooltip ;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;
2050
2051 (defvar-local company-pseudo-tooltip-overlay nil)
2052
2053 (defvar-local company-tooltip-offset 0)
2054
2055 (defun company-tooltip--lines-update-offset (selection num-lines limit)
2056 (cl-decf limit 2)
2057 (setq company-tooltip-offset
2058 (max (min selection company-tooltip-offset)
2059 (- selection -1 limit)))
2060
2061 (when (<= company-tooltip-offset 1)
2062 (cl-incf limit)
2063 (setq company-tooltip-offset 0))
2064
2065 (when (>= company-tooltip-offset (- num-lines limit 1))
2066 (cl-incf limit)
2067 (when (= selection (1- num-lines))
2068 (cl-decf company-tooltip-offset)
2069 (when (<= company-tooltip-offset 1)
2070 (setq company-tooltip-offset 0)
2071 (cl-incf limit))))
2072
2073 limit)
2074
2075 (defun company-tooltip--simple-update-offset (selection _num-lines limit)
2076 (setq company-tooltip-offset
2077 (if (< selection company-tooltip-offset)
2078 selection
2079 (max company-tooltip-offset
2080 (- selection limit -1)))))
2081
2082 ;;; propertize
2083
2084 (defsubst company-round-tab (arg)
2085 (* (/ (+ arg tab-width) tab-width) tab-width))
2086
2087 (defun company-plainify (str)
2088 (let ((prefix (get-text-property 0 'line-prefix str)))
2089 (when prefix ; Keep the original value unmodified, for no special reason.
2090 (setq str (concat prefix str))
2091 (remove-text-properties 0 (length str) '(line-prefix) str)))
2092 (let* ((pieces (split-string str "\t"))
2093 (copy pieces))
2094 (while (cdr copy)
2095 (setcar copy (company-safe-substring
2096 (car copy) 0 (company-round-tab (string-width (car copy)))))
2097 (pop copy))
2098 (apply 'concat pieces)))
2099
2100 (defun company-fill-propertize (value annotation width selected left right)
2101 (let* ((margin (length left))
2102 (common (+ (or (company-call-backend 'match value)
2103 (length company-common)) margin))
2104 (ann-ralign company-tooltip-align-annotations)
2105 (ann-truncate (< width
2106 (+ (length value) (length annotation)
2107 (if ann-ralign 1 0))))
2108 (ann-start (+ margin
2109 (if ann-ralign
2110 (if ann-truncate
2111 (1+ (length value))
2112 (- width (length annotation)))
2113 (length value))))
2114 (ann-end (min (+ ann-start (length annotation)) (+ margin width)))
2115 (line (concat left
2116 (if (or ann-truncate (not ann-ralign))
2117 (company-safe-substring
2118 (concat value
2119 (when (and annotation ann-ralign) " ")
2120 annotation)
2121 0 width)
2122 (concat
2123 (company-safe-substring value 0
2124 (- width (length annotation)))
2125 annotation))
2126 right)))
2127 (setq width (+ width margin (length right)))
2128
2129 (add-text-properties 0 width '(face company-tooltip
2130 mouse-face company-tooltip-mouse)
2131 line)
2132 (add-text-properties margin common
2133 '(face company-tooltip-common
2134 mouse-face company-tooltip-mouse)
2135 line)
2136 (when (< ann-start ann-end)
2137 (add-text-properties ann-start ann-end
2138 '(face company-tooltip-annotation
2139 mouse-face company-tooltip-mouse)
2140 line))
2141 (when selected
2142 (if (and company-search-string
2143 (string-match (regexp-quote company-search-string) value
2144 (length company-prefix)))
2145 (let ((beg (+ margin (match-beginning 0)))
2146 (end (+ margin (match-end 0))))
2147 (add-text-properties beg end '(face company-tooltip-selection)
2148 line)
2149 (when (< beg common)
2150 (add-text-properties beg common
2151 '(face company-tooltip-common-selection)
2152 line)))
2153 (add-text-properties 0 width '(face company-tooltip-selection
2154 mouse-face company-tooltip-selection)
2155 line)
2156 (add-text-properties margin common
2157 '(face company-tooltip-common-selection
2158 mouse-face company-tooltip-selection)
2159 line)))
2160 line))
2161
2162 ;;; replace
2163
2164 (defun company-buffer-lines (beg end)
2165 (goto-char beg)
2166 (let (lines)
2167 (while (and (= 1 (vertical-motion 1))
2168 (<= (point) end))
2169 (let ((bound (min end (1- (point)))))
2170 ;; A visual line can contain several physical lines (e.g. with outline's
2171 ;; folding overlay). Take only the first one.
2172 (push (buffer-substring beg
2173 (save-excursion
2174 (goto-char beg)
2175 (re-search-forward "$" bound 'move)
2176 (point)))
2177 lines))
2178 (setq beg (point)))
2179 (unless (eq beg end)
2180 (push (buffer-substring beg end) lines))
2181 (nreverse lines)))
2182
2183 (defun company-modify-line (old new offset)
2184 (concat (company-safe-substring old 0 offset)
2185 new
2186 (company-safe-substring old (+ offset (length new)))))
2187
2188 (defsubst company--length-limit (lst limit)
2189 (if (nthcdr limit lst)
2190 limit
2191 (length lst)))
2192
2193 (defun company--replacement-string (lines old column nl &optional align-top)
2194 (cl-decf column company-tooltip-margin)
2195
2196 (when (and align-top company-tooltip-flip-when-above)
2197 (setq lines (reverse lines)))
2198
2199 (let ((width (length (car lines)))
2200 (remaining-cols (- (+ (company--window-width) (window-hscroll))
2201 column)))
2202 (when (> width remaining-cols)
2203 (cl-decf column (- width remaining-cols))))
2204
2205 (let ((offset (and (< column 0) (- column)))
2206 new)
2207 (when offset
2208 (setq column 0))
2209 (when align-top
2210 ;; untouched lines first
2211 (dotimes (_ (- (length old) (length lines)))
2212 (push (pop old) new)))
2213 ;; length into old lines.
2214 (while old
2215 (push (company-modify-line (pop old)
2216 (company--offset-line (pop lines) offset)
2217 column) new))
2218 ;; Append whole new lines.
2219 (while lines
2220 (push (concat (company-space-string column)
2221 (company--offset-line (pop lines) offset))
2222 new))
2223
2224 (let ((str (concat (when nl "\n")
2225 (mapconcat 'identity (nreverse new) "\n")
2226 "\n")))
2227 (font-lock-append-text-property 0 (length str) 'face 'default str)
2228 str)))
2229
2230 (defun company--offset-line (line offset)
2231 (if (and offset line)
2232 (substring line offset)
2233 line))
2234
2235 (defun company--create-lines (selection limit)
2236 (let ((len company-candidates-length)
2237 (numbered 99999)
2238 (window-width (company--window-width))
2239 lines
2240 width
2241 lines-copy
2242 items
2243 previous
2244 remainder
2245 scrollbar-bounds)
2246
2247 ;; Maybe clear old offset.
2248 (when (< len (+ company-tooltip-offset limit))
2249 (setq company-tooltip-offset 0))
2250
2251 ;; Scroll to offset.
2252 (if (eq company-tooltip-offset-display 'lines)
2253 (setq limit (company-tooltip--lines-update-offset selection len limit))
2254 (company-tooltip--simple-update-offset selection len limit))
2255
2256 (cond
2257 ((eq company-tooltip-offset-display 'scrollbar)
2258 (setq scrollbar-bounds (company--scrollbar-bounds company-tooltip-offset
2259 limit len)))
2260 ((eq company-tooltip-offset-display 'lines)
2261 (when (> company-tooltip-offset 0)
2262 (setq previous (format "...(%d)" company-tooltip-offset)))
2263 (setq remainder (- len limit company-tooltip-offset)
2264 remainder (when (> remainder 0)
2265 (setq remainder (format "...(%d)" remainder))))))
2266
2267 (cl-decf selection company-tooltip-offset)
2268 (setq width (max (length previous) (length remainder))
2269 lines (nthcdr company-tooltip-offset company-candidates)
2270 len (min limit len)
2271 lines-copy lines)
2272
2273 (cl-decf window-width (* 2 company-tooltip-margin))
2274 (when scrollbar-bounds (cl-decf window-width))
2275
2276 (dotimes (_ len)
2277 (let* ((value (pop lines-copy))
2278 (annotation (company-call-backend 'annotation value)))
2279 (when (and annotation company-tooltip-align-annotations)
2280 ;; `lisp-completion-at-point' adds a space.
2281 (setq annotation (comment-string-strip annotation t nil)))
2282 (push (cons value annotation) items)
2283 (setq width (max (+ (length value)
2284 (if (and annotation company-tooltip-align-annotations)
2285 (1+ (length annotation))
2286 (length annotation)))
2287 width))))
2288
2289 (setq width (min window-width
2290 (max company-tooltip-minimum-width
2291 (if (and company-show-numbers
2292 (< company-tooltip-offset 10))
2293 (+ 2 width)
2294 width))))
2295
2296 ;; number can make tooltip too long
2297 (when company-show-numbers
2298 (setq numbered company-tooltip-offset))
2299
2300 (let ((items (nreverse items)) new)
2301 (when previous
2302 (push (company--scrollpos-line previous width) new))
2303
2304 (dotimes (i len)
2305 (let* ((item (pop items))
2306 (str (company-reformat (car item)))
2307 (annotation (cdr item))
2308 (right (company-space-string company-tooltip-margin))
2309 (width width))
2310 (when (< numbered 10)
2311 (cl-decf width 2)
2312 (cl-incf numbered)
2313 (setq right (concat (format " %d" (mod numbered 10)) right)))
2314 (push (concat
2315 (company-fill-propertize str annotation
2316 width (equal i selection)
2317 (company-space-string
2318 company-tooltip-margin)
2319 right)
2320 (when scrollbar-bounds
2321 (company--scrollbar i scrollbar-bounds)))
2322 new)))
2323
2324 (when remainder
2325 (push (company--scrollpos-line remainder width) new))
2326
2327 (nreverse new))))
2328
2329 (defun company--scrollbar-bounds (offset limit length)
2330 (when (> length limit)
2331 (let* ((size (ceiling (* limit (float limit)) length))
2332 (lower (floor (* limit (float offset)) length))
2333 (upper (+ lower size -1)))
2334 (cons lower upper))))
2335
2336 (defun company--scrollbar (i bounds)
2337 (propertize " " 'face
2338 (if (and (>= i (car bounds)) (<= i (cdr bounds)))
2339 'company-scrollbar-fg
2340 'company-scrollbar-bg)))
2341
2342 (defun company--scrollpos-line (text width)
2343 (propertize (concat (company-space-string company-tooltip-margin)
2344 (company-safe-substring text 0 width)
2345 (company-space-string company-tooltip-margin))
2346 'face 'company-tooltip))
2347
2348 ;; show
2349
2350 (defsubst company--window-inner-height ()
2351 (let ((edges (window-inside-edges)))
2352 (- (nth 3 edges) (nth 1 edges))))
2353
2354 (defsubst company--window-width ()
2355 (let ((ww (window-width)))
2356 ;; Account for the line continuation column.
2357 (when (zerop (cadr (window-fringes)))
2358 (cl-decf ww))
2359 (unless (or (display-graphic-p)
2360 (version< "24.3.1" emacs-version))
2361 ;; Emacs 24.3 and earlier included margins
2362 ;; in window-width when in TTY.
2363 (cl-decf ww
2364 (let ((margins (window-margins)))
2365 (+ (or (car margins) 0)
2366 (or (cdr margins) 0)))))
2367 ww))
2368
2369 (defun company--pseudo-tooltip-height ()
2370 "Calculate the appropriate tooltip height.
2371 Returns a negative number if the tooltip should be displayed above point."
2372 (let* ((lines (company--row))
2373 (below (- (company--window-inner-height) 1 lines)))
2374 (if (and (< below (min company-tooltip-minimum company-candidates-length))
2375 (> lines below))
2376 (- (max 3 (min company-tooltip-limit lines)))
2377 (max 3 (min company-tooltip-limit below)))))
2378
2379 (defun company-pseudo-tooltip-show (row column selection)
2380 (company-pseudo-tooltip-hide)
2381 (save-excursion
2382
2383 (let* ((height (company--pseudo-tooltip-height))
2384 above)
2385
2386 (when (< height 0)
2387 (setq row (+ row height -1)
2388 above t))
2389
2390 (let* ((nl (< (move-to-window-line row) row))
2391 (beg (point))
2392 (end (save-excursion
2393 (move-to-window-line (+ row (abs height)))
2394 (point)))
2395 (ov (make-overlay beg end))
2396 (args (list (mapcar 'company-plainify
2397 (company-buffer-lines beg end))
2398 column nl above)))
2399
2400 (setq company-pseudo-tooltip-overlay ov)
2401 (overlay-put ov 'company-replacement-args args)
2402
2403 (let ((lines (company--create-lines selection (abs height))))
2404 (overlay-put ov 'company-after
2405 (apply 'company--replacement-string lines args))
2406 (overlay-put ov 'company-width (string-width (car lines))))
2407
2408 (overlay-put ov 'company-column column)
2409 (overlay-put ov 'company-height height)))))
2410
2411 (defun company-pseudo-tooltip-show-at-point (pos column-offset)
2412 (let ((row (company--row pos))
2413 (col (- (company--column pos) column-offset)))
2414 (when (< col 0) (setq col 0))
2415 (company-pseudo-tooltip-show (1+ row) col company-selection)))
2416
2417 (defun company-pseudo-tooltip-edit (selection)
2418 (let* ((height (overlay-get company-pseudo-tooltip-overlay 'company-height))
2419 (lines (company--create-lines selection (abs height))))
2420 (overlay-put company-pseudo-tooltip-overlay 'company-width
2421 (string-width (car lines)))
2422 (overlay-put company-pseudo-tooltip-overlay 'company-after
2423 (apply 'company--replacement-string
2424 lines
2425 (overlay-get company-pseudo-tooltip-overlay
2426 'company-replacement-args)))))
2427
2428 (defun company-pseudo-tooltip-hide ()
2429 (when company-pseudo-tooltip-overlay
2430 (delete-overlay company-pseudo-tooltip-overlay)
2431 (setq company-pseudo-tooltip-overlay nil)))
2432
2433 (defun company-pseudo-tooltip-hide-temporarily ()
2434 (when (overlayp company-pseudo-tooltip-overlay)
2435 (overlay-put company-pseudo-tooltip-overlay 'invisible nil)
2436 (overlay-put company-pseudo-tooltip-overlay 'line-prefix nil)
2437 (overlay-put company-pseudo-tooltip-overlay 'after-string nil)))
2438
2439 (defun company-pseudo-tooltip-unhide ()
2440 (when company-pseudo-tooltip-overlay
2441 (overlay-put company-pseudo-tooltip-overlay 'invisible t)
2442 ;; Beat outline's folding overlays, at least.
2443 (overlay-put company-pseudo-tooltip-overlay 'priority 1)
2444 ;; No (extra) prefix for the first line.
2445 (overlay-put company-pseudo-tooltip-overlay 'line-prefix "")
2446 (overlay-put company-pseudo-tooltip-overlay 'after-string
2447 (overlay-get company-pseudo-tooltip-overlay 'company-after))
2448 (overlay-put company-pseudo-tooltip-overlay 'window (selected-window))))
2449
2450 (defun company-pseudo-tooltip-guard ()
2451 (list
2452 (save-excursion (beginning-of-visual-line))
2453 (let ((ov company-pseudo-tooltip-overlay))
2454 (when (>= (overlay-get ov 'company-height) 0)
2455 (buffer-substring-no-properties (point) (overlay-start ov))))))
2456
2457 (defun company-pseudo-tooltip-frontend (command)
2458 "`company-mode' front-end similar to a tooltip but based on overlays."
2459 (cl-case command
2460 (pre-command (company-pseudo-tooltip-hide-temporarily))
2461 (post-command
2462 (unless (when (overlayp company-pseudo-tooltip-overlay)
2463 (let* ((ov company-pseudo-tooltip-overlay)
2464 (old-height (overlay-get ov 'company-height))
2465 (new-height (company--pseudo-tooltip-height)))
2466 (and
2467 (>= (* old-height new-height) 0)
2468 (>= (abs old-height) (abs new-height))
2469 (equal (company-pseudo-tooltip-guard)
2470 (overlay-get ov 'company-guard)))))
2471 ;; Redraw needed.
2472 (company-pseudo-tooltip-show-at-point (point) (length company-prefix))
2473 (overlay-put company-pseudo-tooltip-overlay
2474 'company-guard (company-pseudo-tooltip-guard)))
2475 (company-pseudo-tooltip-unhide))
2476 (hide (company-pseudo-tooltip-hide)
2477 (setq company-tooltip-offset 0))
2478 (update (when (overlayp company-pseudo-tooltip-overlay)
2479 (company-pseudo-tooltip-edit company-selection)))))
2480
2481 (defun company-pseudo-tooltip-unless-just-one-frontend (command)
2482 "`company-pseudo-tooltip-frontend', but not shown for single candidates."
2483 (unless (and (eq command 'post-command)
2484 (company--show-inline-p))
2485 (company-pseudo-tooltip-frontend command)))
2486
2487 ;;; overlay ;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;
2488
2489 (defvar-local company-preview-overlay nil)
2490
2491 (defun company-preview-show-at-point (pos)
2492 (company-preview-hide)
2493
2494 (setq company-preview-overlay (make-overlay pos (1+ pos)))
2495
2496 (let ((completion (nth company-selection company-candidates)))
2497 (setq completion (propertize completion 'face 'company-preview))
2498 (add-text-properties 0 (length company-common)
2499 '(face company-preview-common) completion)
2500
2501 ;; Add search string
2502 (and company-search-string
2503 (string-match (regexp-quote company-search-string) completion)
2504 (add-text-properties (match-beginning 0)
2505 (match-end 0)
2506 '(face company-preview-search)
2507 completion))
2508
2509 (setq completion (company-strip-prefix completion))
2510
2511 (and (equal pos (point))
2512 (not (equal completion ""))
2513 (add-text-properties 0 1 '(cursor t) completion))
2514
2515 (overlay-put company-preview-overlay 'display
2516 (concat completion (unless (eq pos (point-max))
2517 (buffer-substring pos (1+ pos)))))
2518 (overlay-put company-preview-overlay 'window (selected-window))))
2519
2520 (defun company-preview-hide ()
2521 (when company-preview-overlay
2522 (delete-overlay company-preview-overlay)
2523 (setq company-preview-overlay nil)))
2524
2525 (defun company-preview-frontend (command)
2526 "`company-mode' front-end showing the selection as if it had been inserted."
2527 (pcase command
2528 (`pre-command (company-preview-hide))
2529 (`post-command (company-preview-show-at-point (point)))
2530 (`hide (company-preview-hide))))
2531
2532 (defun company-preview-if-just-one-frontend (command)
2533 "`company-preview-frontend', but only shown for single candidates."
2534 (when (or (not (eq command 'post-command))
2535 (company--show-inline-p))
2536 (company-preview-frontend command)))
2537
2538 (defun company--show-inline-p ()
2539 (and (not (cdr company-candidates))
2540 company-common
2541 (string-prefix-p company-prefix company-common
2542 (company-call-backend 'ignore-case))))
2543
2544 ;;; echo ;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;
2545
2546 (defvar-local company-echo-last-msg nil)
2547
2548 (defvar company-echo-timer nil)
2549
2550 (defvar company-echo-delay .01)
2551
2552 (defun company-echo-show (&optional getter)
2553 (when getter
2554 (setq company-echo-last-msg (funcall getter)))
2555 (let ((message-log-max nil))
2556 (if company-echo-last-msg
2557 (message "%s" company-echo-last-msg)
2558 (message ""))))
2559
2560 (defun company-echo-show-soon (&optional getter)
2561 (when company-echo-timer
2562 (cancel-timer company-echo-timer))
2563 (setq company-echo-timer (run-with-timer 0 nil 'company-echo-show getter)))
2564
2565 (defsubst company-echo-show-when-idle (&optional getter)
2566 (when (sit-for company-echo-delay)
2567 (company-echo-show getter)))
2568
2569 (defun company-echo-format ()
2570
2571 (let ((limit (window-width (minibuffer-window)))
2572 (len -1)
2573 ;; Roll to selection.
2574 (candidates (nthcdr company-selection company-candidates))
2575 (i (if company-show-numbers company-selection 99999))
2576 comp msg)
2577
2578 (while candidates
2579 (setq comp (company-reformat (pop candidates))
2580 len (+ len 1 (length comp)))
2581 (if (< i 10)
2582 ;; Add number.
2583 (progn
2584 (setq comp (propertize (format "%d: %s" i comp)
2585 'face 'company-echo))
2586 (cl-incf len 3)
2587 (cl-incf i)
2588 (add-text-properties 3 (+ 3 (length company-common))
2589 '(face company-echo-common) comp))
2590 (setq comp (propertize comp 'face 'company-echo))
2591 (add-text-properties 0 (length company-common)
2592 '(face company-echo-common) comp))
2593 (if (>= len limit)
2594 (setq candidates nil)
2595 (push comp msg)))
2596
2597 (mapconcat 'identity (nreverse msg) " ")))
2598
2599 (defun company-echo-strip-common-format ()
2600
2601 (let ((limit (window-width (minibuffer-window)))
2602 (len (+ (length company-prefix) 2))
2603 ;; Roll to selection.
2604 (candidates (nthcdr company-selection company-candidates))
2605 (i (if company-show-numbers company-selection 99999))
2606 msg comp)
2607
2608 (while candidates
2609 (setq comp (company-strip-prefix (pop candidates))
2610 len (+ len 2 (length comp)))
2611 (when (< i 10)
2612 ;; Add number.
2613 (setq comp (format "%s (%d)" comp i))
2614 (cl-incf len 4)
2615 (cl-incf i))
2616 (if (>= len limit)
2617 (setq candidates nil)
2618 (push (propertize comp 'face 'company-echo) msg)))
2619
2620 (concat (propertize company-prefix 'face 'company-echo-common) "{"
2621 (mapconcat 'identity (nreverse msg) ", ")
2622 "}")))
2623
2624 (defun company-echo-hide ()
2625 (unless (equal company-echo-last-msg "")
2626 (setq company-echo-last-msg "")
2627 (company-echo-show)))
2628
2629 (defun company-echo-frontend (command)
2630 "`company-mode' front-end showing the candidates in the echo area."
2631 (pcase command
2632 (`post-command (company-echo-show-soon 'company-echo-format))
2633 (`hide (company-echo-hide))))
2634
2635 (defun company-echo-strip-common-frontend (command)
2636 "`company-mode' front-end showing the candidates in the echo area."
2637 (pcase command
2638 (`post-command (company-echo-show-soon 'company-echo-strip-common-format))
2639 (`hide (company-echo-hide))))
2640
2641 (defun company-echo-metadata-frontend (command)
2642 "`company-mode' front-end showing the documentation in the echo area."
2643 (pcase command
2644 (`post-command (company-echo-show-when-idle 'company-fetch-metadata))
2645 (`hide (company-echo-hide))))
2646
2647 (provide 'company)
2648 ;;; company.el ends here