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