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