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