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