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