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