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