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