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