]> rtime.felk.cvut.cz Git - sojka/company-mode.git/blob - company.el
Don't interrupt multi-key command input by starting idle completion.
[sojka/company-mode.git] / company.el
1 ;;; company.el --- extensible inline text completion mechanism
2 ;;
3 ;; Copyright (C) 2009 Nikolaj Schumacher
4 ;;
5 ;; Author: Nikolaj Schumacher <bugs * nschum de>
6 ;; Version: 0.4.2
7 ;; Keywords: abbrev, convenience, matchis
8 ;; URL: http://nschum.de/src/emacs/company/
9 ;; Compatibility: GNU Emacs 22.x, GNU Emacs 23.x
10 ;;
11 ;; This file is NOT part of GNU Emacs.
12 ;;
13 ;; This program is free software; you can redistribute it and/or
14 ;; modify it under the terms of the GNU General Public License
15 ;; as published by the Free Software Foundation; either version 2
16 ;; of the License, or (at your option) any later version.
17 ;;
18 ;; This program is distributed in the hope that it will be useful,
19 ;; but WITHOUT ANY WARRANTY; without even the implied warranty of
20 ;; MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
21 ;; GNU General Public License for more details.
22 ;;
23 ;; You should have received a copy of the GNU General Public License
24 ;; along with this program.  If not, see <http://www.gnu.org/licenses/>.
25 ;;
26 ;;; Commentary:
27 ;;
28 ;; Company is a modular completion mechanism.  Modules for retrieving completion
29 ;; candidates are called back-ends, modules for displaying them are front-ends.
30 ;;
31 ;; Company comes with many back-ends, e.g. `company-elisp'.  These are
32 ;; distributed in individual files and can be used individually.
33 ;;
34 ;; Place company.el and the back-ends you want to use in a directory and add the
35 ;; following to your .emacs:
36 ;; (add-to-list 'load-path "/path/to/company")
37 ;; (autoload 'company-mode "company" nil t)
38 ;;
39 ;; Enable company-mode with M-x company-mode.  For further information look at
40 ;; the documentation for `company-mode' (C-h f company-mode RET)
41 ;;
42 ;; If you want to start a specific back-end, call it interactively or use
43 ;; `company-begin-backend'.  For example:
44 ;; M-x company-abbrev will prompt for and insert an abbrev.
45 ;;
46 ;; To write your own back-end, look at the documentation for `company-backends'.
47 ;; Here is a simple example completing "foo":
48 ;;
49 ;; (defun company-my-backend (command &optional arg &rest ignored)
50 ;;   (case command
51 ;;     ('prefix (when (looking-back "foo\\>")
52 ;;                (match-string 0)))
53 ;;     ('candidates (list "foobar" "foobaz" "foobarbaz"))
54 ;;     ('meta (format "This value is named %s" arg))))
55 ;;
56 ;; Sometimes it is a good idea to mix two back-ends together, for example to
57 ;; enrich gtags with dabbrev-code results (to emulate local variables):
58 ;; To do this, add a list with the merged back-ends as an element in
59 ;; 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 ;;    Idle completion no longer interrupts multi-key command input.
69 ;;    Added `company-ropemacs' and `company-pysmell' back-ends.
70 ;;
71 ;; 2009-04-25 (0.4.2)
72 ;;    In C modes . and -> now count towards `company-minimum-prefix-length'.
73 ;;    Reverted default front-end back to `company-preview-if-just-one-frontend'.
74 ;;    The pseudo tooltip will no longer be clipped at the right window edge.
75 ;;    Added `company-tooltip-minimum'.
76 ;;    Windows compatibility fixes.
77 ;;
78 ;; 2009-04-19 (0.4.1)
79 ;;    Added `global-company-mode'.
80 ;;    Performance enhancements.
81 ;;    Added `company-eclim' back-end.
82 ;;    Added safer workaround for Emacs `posn-col-row' bug.
83 ;;
84 ;; 2009-04-18 (0.4)
85 ;;    Automatic completion is now aborted if the prefix gets too short.
86 ;;    Added option `company-dabbrev-time-limit'.
87 ;;    `company-backends' now supports merging back-ends.
88 ;;    Added back-end `company-dabbrev-code' for generic code.
89 ;;    Fixed `company-begin-with'.
90 ;;
91 ;; 2009-04-15 (0.3.1)
92 ;;    Added 'stop prefix to prevent dabbrev from completing inside of symbols.
93 ;;    Fixed issues with tabbar-mode and line-spacing.
94 ;;    Performance enhancements.
95 ;;
96 ;; 2009-04-12 (0.3)
97 ;;    Added `company-begin-commands' option.
98 ;;    Added abbrev, tempo and Xcode back-ends.
99 ;;    Back-ends are now interactive.  You can start them with M-x backend-name.
100 ;;    Added `company-begin-with' for starting company from elisp-code.
101 ;;    Added hooks.
102 ;;    Added `company-require-match' and `company-auto-complete' options.
103 ;;
104 ;; 2009-04-05 (0.2.1)
105 ;;    Improved Emacs Lisp back-end behavior for local variables.
106 ;;    Added `company-elisp-detect-function-context' option.
107 ;;    The mouse can now be used for selection.
108 ;;
109 ;; 2009-03-22 (0.2)
110 ;;    Added `company-show-location'.
111 ;;    Added etags back-end.
112 ;;    Added work-around for end-of-buffer bug.
113 ;;    Added `company-filter-candidates'.
114 ;;    More local Lisp variables are now included in the candidates.
115 ;;
116 ;; 2009-03-21 (0.1.5)
117 ;;    Fixed elisp documentation buffer always showing the same doc.
118 ;;    Added `company-echo-strip-common-frontend'.
119 ;;    Added `company-show-numbers' option and M-0 ... M-9 default bindings.
120 ;;    Don't hide the echo message if it isn't shown.
121 ;;
122 ;; 2009-03-20 (0.1)
123 ;;    Initial release.
124 ;;
125 ;;; Code:
126
127 (eval-when-compile (require 'cl))
128
129 (add-to-list 'debug-ignored-errors "^.* frontend cannot be used twice$")
130 (add-to-list 'debug-ignored-errors "^Echo area cannot be used twice$")
131 (add-to-list 'debug-ignored-errors "^No \\(document\\|loc\\)ation available$")
132 (add-to-list 'debug-ignored-errors "^Company not ")
133 (add-to-list 'debug-ignored-errors "^No candidate number ")
134 (add-to-list 'debug-ignored-errors "^Cannot complete at point$")
135
136 (defgroup company nil
137   "Extensible inline text completion mechanism"
138   :group 'abbrev
139   :group 'convenience
140   :group 'maching)
141
142 (defface company-tooltip
143   '((t :background "yellow"
144        :foreground "black"))
145   "*Face used for the tool tip."
146   :group 'company)
147
148 (defface company-tooltip-selection
149   '((default :inherit company-tooltip)
150     (((class color) (min-colors 88)) (:background "orange1"))
151     (t (:background "green")))
152   "*Face used for the selection in the tool tip."
153   :group 'company)
154
155 (defface company-tooltip-mouse
156   '((default :inherit highlight))
157   "*Face used for the tool tip item under the mouse."
158   :group 'company)
159
160 (defface company-tooltip-common
161   '((t :inherit company-tooltip
162        :foreground "red"))
163   "*Face used for the common completion in the tool tip."
164   :group 'company)
165
166 (defface company-tooltip-common-selection
167   '((t :inherit company-tooltip-selection
168        :foreground "red"))
169   "*Face used for the selected common completion in the tool tip."
170   :group 'company)
171
172 (defface company-preview
173   '((t :background "blue4"
174        :foreground "wheat"))
175   "*Face used for the completion preview."
176   :group 'company)
177
178 (defface company-preview-common
179   '((t :inherit company-preview
180        :foreground "red"))
181   "*Face used for the common part of the completion preview."
182   :group 'company)
183
184 (defface company-preview-search
185   '((t :inherit company-preview
186        :background "blue1"))
187   "*Face used for the search string in the completion preview."
188   :group 'company)
189
190 (defface company-echo nil
191   "*Face used for completions in the echo area."
192   :group 'company)
193
194 (defface company-echo-common
195   '((((background dark)) (:foreground "firebrick1"))
196     (((background light)) (:background "firebrick4")))
197   "*Face used for the common part of completions in the echo area."
198   :group 'company)
199
200 (defun company-frontends-set (variable value)
201   ;; uniquify
202   (let ((remainder value))
203     (setcdr remainder (delq (car remainder) (cdr remainder))))
204   (and (memq 'company-pseudo-tooltip-unless-just-one-frontend value)
205        (memq 'company-pseudo-tooltip-frontend value)
206        (error "Pseudo tooltip frontend cannot be used twice"))
207   (and (memq 'company-preview-if-just-one-frontend value)
208        (memq 'company-preview-frontend value)
209        (error "Preview frontend cannot be used twice"))
210   (and (memq 'company-echo value)
211        (memq 'company-echo-metadata-frontend value)
212        (error "Echo area cannot be used twice"))
213   ;; preview must come last
214   (dolist (f '(company-preview-if-just-one-frontend company-preview-frontend))
215     (when (memq f value)
216       (setq value (append (delq f value) (list f)))))
217   (set variable value))
218
219 (defcustom company-frontends '(company-pseudo-tooltip-unless-just-one-frontend
220                                company-preview-if-just-one-frontend
221                                company-echo-metadata-frontend)
222   "*The list of active front-ends (visualizations).
223 Each front-end is a function that takes one argument.  It is called with
224 one of the following arguments:
225
226 'show: When the visualization should start.
227
228 'hide: When the visualization should end.
229
230 'update: When the data has been updated.
231
232 'pre-command: Before every command that is executed while the
233 visualization is active.
234
235 'post-command: After every command that is executed while the
236 visualization is active.
237
238 The visualized data is stored in `company-prefix', `company-candidates',
239 `company-common', `company-selection', `company-point' and
240 `company-search-string'."
241   :set 'company-frontends-set
242   :group 'company
243   :type '(repeat (choice (const :tag "echo" company-echo-frontend)
244                          (const :tag "echo, strip common"
245                                 company-echo-strip-common-frontend)
246                          (const :tag "show echo meta-data in echo"
247                                 company-echo-metadata-frontend)
248                          (const :tag "pseudo tooltip"
249                                 company-pseudo-tooltip-frontend)
250                          (const :tag "pseudo tooltip, multiple only"
251                                 company-pseudo-tooltip-unless-just-one-frontend)
252                          (const :tag "preview" company-preview-frontend)
253                          (const :tag "preview, unique only"
254                                 company-preview-if-just-one-frontend)
255                          (function :tag "custom function" nil))))
256
257 (defcustom company-tooltip-limit 10
258   "*The maximum number of candidates in the tool tip"
259   :group 'company
260   :type 'integer)
261
262 (defcustom company-tooltip-minimum 6
263   "*The minimum height of the tool tip.
264 If this many lines are not available, prefer to display the tooltip above."
265   :group 'company
266   :type 'integer)
267
268 (defvar company-safe-backends
269   '((company-abbrev . "Abbrev")
270     (company-css . "CSS")
271     (company-dabbrev . "dabbrev for plain text")
272     (company-dabbrev-code . "dabbrev for code")
273     (company-eclim . "eclim (an Eclipse interace)")
274     (company-elisp . "Emacs Lisp")
275     (company-etags . "etags")
276     (company-files . "Files")
277     (company-gtags . "GNU Global")
278     (company-ispell . "ispell")
279     (company-keywords . "Programming language keywords")
280     (company-nxml . "nxml")
281     (company-oddmuse . "Oddmuse")
282     (company-pysmell . "PySmell")
283     (company-ropemacs . "ropemacs")
284     (company-semantic . "CEDET Semantic")
285     (company-tempo . "Tempo templates")
286     (company-xcode . "Xcode")))
287 (put 'company-safe-backends 'risky-local-variable t)
288
289 (defun company-safe-backends-p (backends)
290   (and (consp backends)
291        (not (dolist (backend backends)
292               (unless (if (consp backend)
293                           (company-safe-backends-p backend)
294                         (assq backend company-safe-backends))
295                 (return t))))))
296
297 (defcustom company-backends '(company-elisp company-nxml company-css
298                               company-eclim company-semantic company-xcode
299                               company-ropemacs
300                               (company-gtags company-etags company-dabbrev-code
301                                company-pysmell company-keywords)
302                               company-oddmuse company-files company-dabbrev)
303   "*The list of active back-ends (completion engines).
304 Each list elements can itself be a list of back-ends.  In that case their
305 completions are merged.  Otherwise only the first matching back-end returns
306 results.
307
308 Each back-end is a function that takes a variable number of arguments.
309 The first argument is the command requested from the back-end.  It is one
310 of the following:
311
312 'prefix: The back-end should return the text to be completed.  It must be
313 text immediately before `point'.  Returning nil passes control to the next
314 back-end.  The function should return 'stop if it should complete but cannot
315 \(e.g. if it is in the middle of a string\).  If the returned value is only
316 part of the prefix (e.g. the part after \"->\" in C), the back-end may return a
317 cons of prefix and prefix length, which is then used in the
318 `company-minimum-prefix-length' test.
319
320 'candidates: The second argument is the prefix to be completed.  The
321 return value should be a list of candidates that start with the prefix.
322
323 Optional commands:
324
325 'sorted: The back-end may return t here to indicate that the candidates
326 are sorted and will not need to be sorted again.
327
328 'duplicates: If non-nil, company will take care of removing duplicates
329 from the list.
330
331 'no-cache: Usually company doesn't ask for candidates again as completion
332 progresses, unless the back-end returns t for this command.  The second
333 argument is the latest prefix.
334
335 'meta: The second argument is a completion candidate.  The back-end should
336 return a (short) documentation string for it.
337
338 'doc-buffer: The second argument is a completion candidate.  The back-end should
339 create a buffer (preferably with `company-doc-buffer'), fill it with
340 documentation and return it.
341
342 'location: The second argument is a completion candidate.  The back-end can
343 return the cons of buffer and buffer location, or of file and line
344 number where the completion candidate was defined.
345
346 'require-match: If this value is t, the user is not allowed to enter anything
347 not offering as a candidate.  Use with care!  The default value nil gives the
348 user that choice with `company-require-match'.  Return value 'never overrides
349 that option the other way around.
350
351 The back-end should return nil for all commands it does not support or
352 does not know about.  It should also be callable interactively and use
353 `company-begin-backend' to start itself in that case."
354   :group 'company
355   :type `(repeat
356           (choice
357            :tag "Back-end"
358            ,@(mapcar (lambda (b) `(const :tag ,(cdr b) ,(car b)))
359                      company-safe-backends)
360            (symbol :tag "User defined")
361            (repeat :tag "Merged Back-ends"
362                    (choice :tag "Back-end"
363                            ,@(mapcar (lambda (b)
364                                        `(const :tag ,(cdr b) ,(car b)))
365                                      company-safe-backends)
366                            (symbol :tag "User defined"))))))
367
368 (put 'company-backends 'safe-local-variable 'company-safe-backends-p)
369
370 (defcustom company-completion-started-hook nil
371   "*Hook run when company starts completing.
372 The hook is called with one argument that is non-nil if the completion was
373 started manually."
374   :group 'company
375   :type 'hook)
376
377 (defcustom company-completion-cancelled-hook nil
378   "*Hook run when company cancels completing.
379 The hook is called with one argument that is non-nil if the completion was
380 aborted manually."
381   :group 'company
382   :type 'hook)
383
384 (defcustom company-completion-finished-hook nil
385   "*Hook run when company successfully completes.
386 The hook is called with the selected candidate as an argument."
387   :group 'company
388   :type 'hook)
389
390 (defcustom company-minimum-prefix-length 3
391   "*The minimum prefix length for automatic completion."
392   :group 'company
393   :type '(integer :tag "prefix length"))
394
395 (defcustom company-require-match 'company-explicit-action-p
396   "*If enabled, disallow non-matching input.
397 This can be a function do determine if a match is required.
398
399 This can be overridden by the back-end, if it returns t or 'never to
400 'require-match.  `company-auto-complete' also takes precedence over this."
401   :group 'company
402   :type '(choice (const :tag "Off" nil)
403                  (function :tag "Predicate function")
404                  (const :tag "On, if user interaction took place"
405                         'company-explicit-action-p)
406                  (const :tag "On" t)))
407
408 (defcustom company-auto-complete 'company-explicit-action-p
409   "Determines when to auto-complete.
410 If this is enabled, all characters from `company-auto-complete-chars' complete
411 the selected completion.  This can also be a function."
412   :group 'company
413   :type '(choice (const :tag "Off" nil)
414                  (function :tag "Predicate function")
415                  (const :tag "On, if user interaction took place"
416                         'company-explicit-action-p)
417                  (const :tag "On" t)))
418
419 (defcustom company-auto-complete-chars '(?\  ?\( ?\) ?. ?\" ?$ ?\' ?< ?| ?!)
420   "Determines which characters trigger an automatic completion.
421 See `company-auto-complete'.  If this is a string, each string character causes
422 completion.  If it is a list of syntax description characters (see
423 `modify-syntax-entry'), all characters with that syntax auto-complete.
424
425 This can also be a function, which is called with the new input and should
426 return non-nil if company should auto-complete.
427
428 A character that is part of a valid candidate never starts auto-completion."
429   :group 'company
430   :type '(choice (string :tag "Characters")
431                  (set :tag "Syntax"
432                       (const :tag "Whitespace" ?\ )
433                       (const :tag "Symbol" ?_)
434                       (const :tag "Opening parentheses" ?\()
435                       (const :tag "Closing parentheses" ?\))
436                       (const :tag "Word constituent" ?w)
437                       (const :tag "Punctuation." ?.)
438                       (const :tag "String quote." ?\")
439                       (const :tag "Paired delimiter." ?$)
440                       (const :tag "Expression quote or prefix operator." ?\')
441                       (const :tag "Comment starter." ?<)
442                       (const :tag "Comment ender." ?>)
443                       (const :tag "Character-quote." ?/)
444                       (const :tag "Generic string fence." ?|)
445                       (const :tag "Generic comment fence." ?!))
446                  (function :tag "Predicate function")))
447
448 (defcustom company-idle-delay .7
449   "*The idle delay in seconds until automatic completions starts.
450 A value of nil means never complete automatically, t means complete
451 immediately when a prefix of `company-minimum-prefix-length' is reached."
452   :group 'company
453   :type '(choice (const :tag "never (nil)" nil)
454                  (const :tag "immediate (t)" t)
455                  (number :tag "seconds")))
456
457 (defcustom company-begin-commands t
458   "*A list of commands following which company will start completing.
459 If this is t, it will complete after any command.  See `company-idle-delay'.
460
461 Alternatively any command with a non-nil 'company-begin property is treated as
462 if it was on this list."
463   :group 'company
464   :type '(choice (const :tag "Any command" t)
465                  (const :tag "Self insert command" '(self-insert-command))
466                  (repeat :tag "Commands" function)))
467
468 (defcustom company-show-numbers nil
469   "*If enabled, show quick-access numbers for the first ten candidates."
470   :group 'company
471   :type '(choice (const :tag "off" nil)
472                  (const :tag "on" t)))
473
474 (defvar company-end-of-buffer-workaround t
475   "*Work around a visualization bug when completing at the end of the buffer.
476 The work-around consists of adding a newline.")
477
478 ;;; mode ;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;
479
480 (defvar company-mode-map (make-sparse-keymap)
481   "Keymap used by `company-mode'.")
482
483 (defvar company-active-map
484   (let ((keymap (make-sparse-keymap)))
485     (define-key keymap "\e\e\e" 'company-abort)
486     (define-key keymap "\C-g" 'company-abort)
487     (define-key keymap (kbd "M-n") 'company-select-next)
488     (define-key keymap (kbd "M-p") 'company-select-previous)
489     (define-key keymap (kbd "<down>") 'company-select-next)
490     (define-key keymap (kbd "<up>") 'company-select-previous)
491     (define-key keymap [down-mouse-1] 'ignore)
492     (define-key keymap [down-mouse-3] 'ignore)
493     (define-key keymap [mouse-1] 'company-complete-mouse)
494     (define-key keymap [mouse-3] 'company-select-mouse)
495     (define-key keymap [up-mouse-1] 'ignore)
496     (define-key keymap [up-mouse-3] 'ignore)
497     (define-key keymap "\C-m" 'company-complete-selection)
498     (define-key keymap "\t" 'company-complete-common)
499     (define-key keymap (kbd "<f1>") 'company-show-doc-buffer)
500     (define-key keymap "\C-w" 'company-show-location)
501     (define-key keymap "\C-s" 'company-search-candidates)
502     (define-key keymap "\C-\M-s" 'company-filter-candidates)
503     (dotimes (i 10)
504       (define-key keymap (vector (+ (aref (kbd "M-0") 0) i))
505         `(lambda () (interactive) (company-complete-number ,i))))
506
507     keymap)
508   "Keymap that is enabled during an active completion.")
509
510 (defvar company--disabled-backends nil)
511
512 (defun company-init-backend (backend)
513   (and (symbolp backend)
514        (not (fboundp backend))
515        (ignore-errors (require backend nil t)))
516
517   (if (or (symbolp backend)
518           (functionp backend))
519       (if (ignore-errors (funcall backend 'init) t)
520           (put backend 'company-init t)
521         (put backend 'company-init 'failed)
522         (unless (memq backend company--disabled-backends)
523           (message "Company back-end '%s' could not be initialized"
524                    backend)
525           (push backend company--disabled-backends))
526         nil)
527     (mapc 'company-init-backend backend)))
528
529 (defvar company-default-lighter " company")
530
531 (defvar company-lighter company-default-lighter)
532 (make-variable-buffer-local 'company-lighter)
533
534 ;;;###autoload
535 (define-minor-mode company-mode
536   "\"complete anything\"; in in-buffer completion framework.
537 Completion starts automatically, depending on the values
538 `company-idle-delay' and `company-minimum-prefix-length'.
539
540 Completion can be controlled with the commands:
541 `company-complete-common', `company-complete-selection', `company-complete',
542 `company-select-next', `company-select-previous'.  If these commands are
543 called before `company-idle-delay', completion will also start.
544
545 Completions can be searched with `company-search-candidates' or
546 `company-filter-candidates'.  These can be used while completion is
547 inactive, as well.
548
549 The completion data is retrieved using `company-backends' and displayed using
550 `company-frontends'.  If you want to start a specific back-end, call it
551 interactively or use `company-begin-backend'.
552
553 regular keymap (`company-mode-map'):
554
555 \\{company-mode-map}
556 keymap during active completions (`company-active-map'):
557
558 \\{company-active-map}"
559   nil company-lighter company-mode-map
560   (if company-mode
561       (progn
562         (add-hook 'pre-command-hook 'company-pre-command nil t)
563         (add-hook 'post-command-hook 'company-post-command nil t)
564         (mapc 'company-init-backend company-backends))
565     (remove-hook 'pre-command-hook 'company-pre-command t)
566     (remove-hook 'post-command-hook 'company-post-command t)
567     (company-cancel)
568     (kill-local-variable 'company-point)))
569
570 (define-globalized-minor-mode global-company-mode company-mode
571   (lambda () (company-mode 1)))
572
573 (defsubst company-assert-enabled ()
574   (unless company-mode
575     (company-uninstall-map)
576     (error "Company not enabled")))
577
578 ;;; keymaps ;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;
579
580 (defvar company-overriding-keymap-bound nil)
581 (make-variable-buffer-local 'company-overriding-keymap-bound)
582
583 (defvar company-old-keymap nil)
584 (make-variable-buffer-local 'company-old-keymap)
585
586 (defvar company-my-keymap nil)
587 (make-variable-buffer-local 'company-my-keymap)
588
589 (defsubst company-enable-overriding-keymap (keymap)
590   (setq company-my-keymap keymap)
591   (when company-overriding-keymap-bound
592     (company-uninstall-map)))
593
594 (defun company-install-map ()
595   (unless (or company-overriding-keymap-bound
596               (null company-my-keymap))
597     (setq company-old-keymap overriding-terminal-local-map
598           overriding-terminal-local-map company-my-keymap
599           company-overriding-keymap-bound t)))
600
601 (defun company-uninstall-map ()
602   (when (eq overriding-terminal-local-map company-my-keymap)
603     (setq overriding-terminal-local-map company-old-keymap
604           company-overriding-keymap-bound nil)))
605
606 ;; Hack:
607 ;; Emacs calculates the active keymaps before reading the event.  That means we
608 ;; cannot change the keymap from a timer.  So we send a bogus command.
609 (defun company-ignore ()
610   (interactive)
611   (setq this-command last-command))
612
613 (global-set-key '[31415926] 'company-ignore)
614
615 (defun company-input-noop ()
616   (push 31415926 unread-command-events))
617
618 ;; Hack:
619 ;; posn-col-row is incorrect in older Emacsen when line-spacing is set
620 (defun company--col-row (&optional pos)
621   (let ((posn (posn-at-point pos)))
622     (cons (car (posn-col-row posn)) (cdr (posn-actual-col-row posn)))))
623
624 (defsubst company--column (&optional pos)
625   (car (posn-col-row (posn-at-point pos))))
626
627 (defsubst company--row (&optional pos)
628   (cdr (posn-actual-col-row (posn-at-point pos))))
629
630 ;;; backends ;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;
631
632 (defun company-grab (regexp &optional expression limit)
633   (when (looking-back regexp limit)
634     (or (match-string-no-properties (or expression 0)) "")))
635
636 (defun company-grab-line (regexp &optional expression)
637   (company-grab regexp expression (point-at-bol)))
638
639 (defun company-grab-symbol ()
640   (if (looking-at "\\_>")
641       (buffer-substring (point) (save-excursion (skip-syntax-backward "w_")
642                                                 (point)))
643     (unless (and (char-after) (memq (char-syntax (char-after)) '(?w ?_)))
644       "")))
645
646 (defun company-grab-word ()
647   (if (looking-at "\\>")
648       (buffer-substring (point) (save-excursion (skip-syntax-backward "w")
649                                                 (point)))
650     (unless (and (char-after) (eq (char-syntax (char-after)) ?w))
651       "")))
652
653 (defun company-in-string-or-comment ()
654   (let ((ppss (syntax-ppss)))
655     (or (car (setq ppss (nthcdr 3 ppss)))
656         (car (setq ppss (cdr ppss)))
657         (nth 3 ppss))))
658
659 (if (fboundp 'locate-dominating-file)
660     (defalias 'company-locate-dominating-file 'locate-dominating-file)
661   (defun company-locate-dominating-file (file name)
662     (catch 'root
663       (let ((dir (file-name-directory file))
664             (prev-dir nil))
665         (while (not (equal dir prev-dir))
666           (when (file-exists-p (expand-file-name name dir))
667             (throw 'root dir))
668           (setq prev-dir dir
669                 dir (file-name-directory (directory-file-name dir))))))))
670
671 (defun company-call-backend (&rest args)
672   (if (functionp company-backend)
673       (apply company-backend args)
674     (apply 'company--multi-backend-adapter company-backend args)))
675
676 (defun company--multi-backend-adapter (backends command &rest args)
677   (case command
678     ('candidates
679      (apply 'append (mapcar (lambda (backend) (apply backend command args))
680                             backends)))
681     ('sorted nil)
682     ('duplicates t)
683     (otherwise
684      (let (value)
685        (dolist (backend backends)
686          (when (setq value (apply backend command args))
687            (return value)))))))
688
689 ;;; completion mechanism ;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;
690
691 (defvar company-backend nil)
692 (make-variable-buffer-local 'company-backend)
693
694 (defvar company-prefix nil)
695 (make-variable-buffer-local 'company-prefix)
696
697 (defvar company-candidates nil)
698 (make-variable-buffer-local 'company-candidates)
699
700 (defvar company-candidates-length nil)
701 (make-variable-buffer-local 'company-candidates-length)
702
703 (defvar company-candidates-cache nil)
704 (make-variable-buffer-local 'company-candidates-cache)
705
706 (defvar company-candidates-predicate nil)
707 (make-variable-buffer-local 'company-candidates-predicate)
708
709 (defvar company-common nil)
710 (make-variable-buffer-local 'company-common)
711
712 (defvar company-selection 0)
713 (make-variable-buffer-local 'company-selection)
714
715 (defvar company-selection-changed nil)
716 (make-variable-buffer-local 'company-selection-changed)
717
718 (defvar company--explicit-action nil
719   "Non-nil, if explicit completion took place.")
720 (make-variable-buffer-local 'company--explicit-action)
721
722 (defvar company--point-max nil)
723 (make-variable-buffer-local 'company--point-max)
724
725 (defvar company-point nil)
726 (make-variable-buffer-local 'company-point)
727
728 (defvar company-timer nil)
729
730 (defvar company-added-newline nil)
731 (make-variable-buffer-local 'company-added-newline)
732
733 (defsubst company-strip-prefix (str)
734   (substring str (length company-prefix)))
735
736 (defun company-explicit-action-p ()
737   "Return whether explicit completion action was taken by the user."
738   (or company--explicit-action
739       company-selection-changed))
740
741 (defsubst company-reformat (candidate)
742   ;; company-ispell needs this, because the results are always lower-case
743   ;; It's mory efficient to fix it only when they are displayed.
744   (concat company-prefix (substring candidate (length company-prefix))))
745
746 (defun company--should-complete ()
747   (and (not (or buffer-read-only overriding-terminal-local-map
748                 overriding-local-map))
749        ;; Check if in the middle of entering a key combination.
750        (or (equal (this-command-keys-vector) [])
751            (not (keymapp (key-binding (this-command-keys-vector)))))
752        (eq company-idle-delay t)
753        (or (eq t company-begin-commands)
754            (memq this-command company-begin-commands)
755            (and (symbolp this-command) (get this-command 'company-begin)))
756        (not (and transient-mark-mode mark-active))))
757
758 (defsubst company-call-frontends (command)
759   (dolist (frontend company-frontends)
760     (condition-case err
761         (funcall frontend command)
762       (error (error "Company: Front-end %s error \"%s\" on command %s"
763                     frontend (error-message-string err) command)))))
764
765 (defsubst company-set-selection (selection &optional force-update)
766   (setq selection (max 0 (min (1- company-candidates-length) selection)))
767   (when (or force-update (not (equal selection company-selection)))
768     (setq company-selection selection
769           company-selection-changed t)
770     (company-call-frontends 'update)))
771
772 (defun company-apply-predicate (candidates predicate)
773   (let (new)
774     (dolist (c candidates)
775       (when (funcall predicate c)
776         (push c new)))
777     (nreverse new)))
778
779 (defun company-update-candidates (candidates)
780   (setq company-candidates-length (length candidates))
781   (if (> company-selection 0)
782       ;; Try to restore the selection
783       (let ((selected (nth company-selection company-candidates)))
784         (setq company-selection 0
785               company-candidates candidates)
786         (when selected
787           (while (and candidates (string< (pop candidates) selected))
788             (incf company-selection))
789           (unless candidates
790             ;; Make sure selection isn't out of bounds.
791             (setq company-selection (min (1- company-candidates-length)
792                                          company-selection)))))
793     (setq company-selection 0
794           company-candidates candidates))
795   ;; Save in cache:
796   (push (cons company-prefix company-candidates) company-candidates-cache)
797   ;; Calculate common.
798   (let ((completion-ignore-case (company-call-backend 'ignore-case)))
799     (setq company-common (try-completion company-prefix company-candidates)))
800   (when (eq company-common t)
801     (setq company-candidates nil)))
802
803 (defun company-calculate-candidates (prefix)
804   (let ((candidates (cdr (assoc prefix company-candidates-cache))))
805     (or candidates
806         (when company-candidates-cache
807           (let ((len (length prefix))
808                 (completion-ignore-case (company-call-backend 'ignore-case))
809                 prev)
810             (dotimes (i (1+ len))
811               (when (setq prev (cdr (assoc (substring prefix 0 (- len i))
812                                            company-candidates-cache)))
813                 (setq candidates (all-completions prefix prev))
814                 (return t)))))
815         ;; no cache match, call back-end
816         (progn
817           (setq candidates (company-call-backend 'candidates prefix))
818           (when company-candidates-predicate
819             (setq candidates
820                   (company-apply-predicate candidates
821                                            company-candidates-predicate)))
822           (unless (company-call-backend 'sorted)
823             (setq candidates (sort candidates 'string<)))
824           (when (company-call-backend 'duplicates)
825             ;; strip duplicates
826             (let ((c2 candidates))
827               (while c2
828                 (setcdr c2 (progn (while (equal (pop c2) (car c2)))
829                                   c2)))))))
830     (if (or (cdr candidates)
831             (not (equal (car candidates) prefix)))
832         ;; Don't start when already completed and unique.
833         candidates
834       ;; Not the right place? maybe when setting?
835       (and company-candidates t))))
836
837 (defun company-idle-begin (buf win tick pos)
838   (and company-mode
839        (eq buf (current-buffer))
840        (eq win (selected-window))
841        (eq tick (buffer-chars-modified-tick))
842        (eq pos (point))
843        (not company-candidates)
844        (not (equal (point) company-point))
845        (let ((company-idle-delay t)
846              (company-begin-commands t))
847          (company-begin)
848          (when company-candidates
849            (company-input-noop)
850            (company-post-command)))))
851
852 (defun company-auto-begin ()
853   (company-assert-enabled)
854   (and company-mode
855        (not company-candidates)
856        (let ((company-idle-delay t)
857              (company-minimum-prefix-length 0)
858              (company-begin-commands t))
859          (company-begin)))
860   ;; Return non-nil if active.
861   company-candidates)
862
863 (defun company-manual-begin ()
864   (interactive)
865   (setq company--explicit-action t)
866   (company-auto-begin))
867
868 (defun company-require-match-p ()
869   (let ((backend-value (company-call-backend 'require-match)))
870     (or (eq backend-value t)
871         (and (if (functionp company-require-match)
872                  (funcall company-require-match)
873                (eq company-require-match t))
874              (not (eq backend-value 'never))))))
875
876 (defun company-punctuation-p (input)
877   "Return non-nil, if input starts with punctuation or parentheses."
878   (memq (char-syntax (string-to-char input)) '(?. ?\( ?\))))
879
880 (defun company-auto-complete-p (input)
881   "Return non-nil, if input starts with punctuation or parentheses."
882   (and (if (functionp company-auto-complete)
883            (funcall company-auto-complete)
884          company-auto-complete)
885        (if (functionp company-auto-complete-chars)
886            (funcall company-auto-complete-chars input)
887          (if (consp company-auto-complete-chars)
888              (memq (char-syntax (string-to-char input))
889                    company-auto-complete-chars)
890            (string-match (substring input 0 1) company-auto-complete-chars)))))
891
892 (defun company--incremental-p ()
893   (and (> (point) company-point)
894        (> (point-max) company--point-max)
895        (not (eq this-command 'backward-delete-char-untabify))
896        (equal (buffer-substring (- company-point (length company-prefix))
897                                 company-point)
898               company-prefix)))
899
900 (defsubst company--string-incremental-p (old-prefix new-prefix)
901   (and (> (length new-prefix) (length old-prefix))
902        (equal old-prefix (substring new-prefix 0 (length old-prefix)))))
903
904 (defun company--continue-failed (new-prefix)
905   (when (company--incremental-p)
906     (let ((input (buffer-substring-no-properties (point) company-point)))
907       (cond
908        ((company-auto-complete-p input)
909         ;; auto-complete
910         (save-excursion
911           (goto-char company-point)
912           (company-complete-selection)
913           nil))
914        ((and (company--string-incremental-p company-prefix new-prefix)
915              (company-require-match-p))
916         ;; wrong incremental input, but required match
917         (backward-delete-char (length input))
918         (ding)
919         (message "Matching input is required")
920         company-candidates)
921        ((equal company-prefix (car company-candidates))
922         ;; last input was actually success
923         (company-cancel company-prefix)
924         nil)))))
925
926 (defun company--good-prefix-p (prefix)
927   (and (or (company-explicit-action-p)
928            (>= (or (cdr-safe prefix) (length prefix))
929                company-minimum-prefix-length))
930        (stringp (or (car-safe prefix) prefix))))
931
932 (defun company--continue ()
933   (when (company-call-backend 'no-cache company-prefix)
934     ;; Don't complete existing candidates, fetch new ones.
935     (setq company-candidates-cache nil))
936   (let* ((new-prefix (company-call-backend 'prefix))
937          (c (when (and (company--good-prefix-p new-prefix)
938                        (setq new-prefix (or (car-safe new-prefix) new-prefix))
939                        (= (- (point) (length new-prefix))
940                           (- company-point (length company-prefix))))
941               (setq new-prefix (or (car-safe new-prefix) new-prefix))
942               (company-calculate-candidates new-prefix))))
943     (or (cond
944          ((eq c t)
945           ;; t means complete/unique.
946           (company-cancel new-prefix)
947           nil)
948          ((consp c)
949           ;; incremental match
950           (setq company-prefix new-prefix)
951           (company-update-candidates c)
952           c)
953          (t (company--continue-failed new-prefix)))
954         (company-cancel))))
955
956 (defun company--begin-new ()
957   (let (prefix c)
958     (dolist (backend (if company-backend
959                          ;; prefer manual override
960                          (list company-backend)
961                        company-backends))
962       (setq prefix
963             (if (or (symbolp backend)
964                     (functionp backend))
965                 (when (or (not (symbolp backend))
966                           (eq t (get backend 'company-init))
967                           (unless (get backend 'company-init)
968                             (company-init-backend backend)))
969                   (funcall backend 'prefix))
970               (company--multi-backend-adapter backend 'prefix)))
971       (when prefix
972         (when (company--good-prefix-p prefix)
973           (setq prefix (or (car-safe prefix) prefix)
974                 company-backend backend
975                 c (company-calculate-candidates prefix))
976           ;; t means complete/unique.  We don't start, so no hooks.
977           (when (consp c)
978             (setq company-prefix prefix)
979             (when (symbolp backend)
980               (setq company-lighter (concat " " (symbol-name backend))))
981             (company-update-candidates c)
982             (run-hook-with-args 'company-completion-started-hook
983                                 (company-explicit-action-p))
984             (company-call-frontends 'show)))
985         (return c)))))
986
987 (defun company-begin ()
988   (setq company-candidates
989         (or (and company-candidates (company--continue))
990             (and (company--should-complete) (company--begin-new))))
991   (when company-candidates
992     (when (and company-end-of-buffer-workaround (eobp))
993       (save-excursion (insert "\n"))
994       (setq company-added-newline (buffer-chars-modified-tick)))
995     (setq company-point (point)
996           company--point-max (point-max))
997     (company-enable-overriding-keymap company-active-map)
998     (company-call-frontends 'update)))
999
1000 (defun company-cancel (&optional result)
1001   (and company-added-newline
1002        (> (point-max) (point-min))
1003        (let ((tick (buffer-chars-modified-tick)))
1004          (delete-region (1- (point-max)) (point-max))
1005          (equal tick company-added-newline))
1006        ;; Only set unmodified when tick remained the same since insert.
1007        (set-buffer-modified-p nil))
1008   (when company-prefix
1009     (if (stringp result)
1010         (run-hook-with-args 'company-completion-finished-hook result)
1011       (run-hook-with-args 'company-completion-cancelled-hook result)))
1012   (setq company-added-newline nil
1013         company-backend nil
1014         company-prefix nil
1015         company-candidates nil
1016         company-candidates-length nil
1017         company-candidates-cache nil
1018         company-candidates-predicate nil
1019         company-common nil
1020         company-selection 0
1021         company-selection-changed nil
1022         company--explicit-action nil
1023         company-lighter company-default-lighter
1024         company--point-max nil
1025         company-point nil)
1026   (when company-timer
1027     (cancel-timer company-timer))
1028   (company-search-mode 0)
1029   (company-call-frontends 'hide)
1030   (company-enable-overriding-keymap nil))
1031
1032 (defun company-abort ()
1033   (interactive)
1034   (company-cancel t)
1035   ;; Don't start again, unless started manually.
1036   (setq company-point (point)))
1037
1038 (defun company-finish (result)
1039   (insert (company-strip-prefix result))
1040   (company-cancel result)
1041   ;; Don't start again, unless started manually.
1042   (setq company-point (point)))
1043
1044 (defsubst company-keep (command)
1045   (and (symbolp command) (get command 'company-keep)))
1046
1047 (defun company-pre-command ()
1048   (unless (company-keep this-command)
1049     (condition-case err
1050         (when company-candidates
1051           (company-call-frontends 'pre-command))
1052       (error (message "Company: An error occurred in pre-command")
1053              (message "%s" (error-message-string err))
1054              (company-cancel))))
1055   (when company-timer
1056     (cancel-timer company-timer)
1057     (setq company-timer nil))
1058   (company-uninstall-map))
1059
1060 (defun company-post-command ()
1061   (unless (company-keep this-command)
1062     (condition-case err
1063         (progn
1064           (unless (equal (point) company-point)
1065             (company-begin))
1066           (if company-candidates
1067               (company-call-frontends 'post-command)
1068             (and (numberp company-idle-delay)
1069                  (or (eq t company-begin-commands)
1070                      (memq this-command company-begin-commands))
1071                  (setq company-timer
1072                        (run-with-timer company-idle-delay nil
1073                                        'company-idle-begin
1074                                        (current-buffer) (selected-window)
1075                                        (buffer-chars-modified-tick) (point))))))
1076       (error (message "Company: An error occurred in post-command")
1077              (message "%s" (error-message-string err))
1078              (company-cancel))))
1079   (company-install-map))
1080
1081 ;;; search ;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;
1082
1083 (defvar company-search-string nil)
1084 (make-variable-buffer-local 'company-search-string)
1085
1086 (defvar company-search-lighter " Search: \"\"")
1087 (make-variable-buffer-local 'company-search-lighter)
1088
1089 (defvar company-search-old-map nil)
1090 (make-variable-buffer-local 'company-search-old-map)
1091
1092 (defvar company-search-old-selection 0)
1093 (make-variable-buffer-local 'company-search-old-selection)
1094
1095 (defun company-search (text lines)
1096   (let ((quoted (regexp-quote text))
1097         (i 0))
1098     (dolist (line lines)
1099       (when (string-match quoted line (length company-prefix))
1100         (return i))
1101       (incf i))))
1102
1103 (defun company-search-printing-char ()
1104   (interactive)
1105   (company-search-assert-enabled)
1106   (setq company-search-string
1107         (concat (or company-search-string "") (string last-command-event))
1108         company-search-lighter (concat " Search: \"" company-search-string
1109                                         "\""))
1110   (let ((pos (company-search company-search-string
1111                               (nthcdr company-selection company-candidates))))
1112     (if (null pos)
1113         (ding)
1114       (company-set-selection (+ company-selection pos) t))))
1115
1116 (defun company-search-repeat-forward ()
1117   "Repeat the incremental search in completion candidates forward."
1118   (interactive)
1119   (company-search-assert-enabled)
1120   (let ((pos (company-search company-search-string
1121                               (cdr (nthcdr company-selection
1122                                            company-candidates)))))
1123     (if (null pos)
1124         (ding)
1125       (company-set-selection (+ company-selection pos 1) t))))
1126
1127 (defun company-search-repeat-backward ()
1128   "Repeat the incremental search in completion candidates backwards."
1129   (interactive)
1130   (company-search-assert-enabled)
1131   (let ((pos (company-search company-search-string
1132                               (nthcdr (- company-candidates-length
1133                                          company-selection)
1134                                       (reverse company-candidates)))))
1135     (if (null pos)
1136         (ding)
1137       (company-set-selection (- company-selection pos 1) t))))
1138
1139 (defun company-create-match-predicate ()
1140   (setq company-candidates-predicate
1141         `(lambda (candidate)
1142            ,(if company-candidates-predicate
1143                 `(and (string-match ,company-search-string candidate)
1144                       (funcall ,company-candidates-predicate
1145                                candidate))
1146               `(string-match ,company-search-string candidate))))
1147   (company-update-candidates
1148    (company-apply-predicate company-candidates company-candidates-predicate))
1149   ;; Invalidate cache.
1150   (setq company-candidates-cache (cons company-prefix company-candidates)))
1151
1152 (defun company-filter-printing-char ()
1153   (interactive)
1154   (company-search-assert-enabled)
1155   (company-search-printing-char)
1156   (company-create-match-predicate)
1157   (company-call-frontends 'update))
1158
1159 (defun company-search-kill-others ()
1160   "Limit the completion candidates to the ones matching the search string."
1161   (interactive)
1162   (company-search-assert-enabled)
1163   (company-create-match-predicate)
1164   (company-search-mode 0)
1165   (company-call-frontends 'update))
1166
1167 (defun company-search-abort ()
1168   "Abort searching the completion candidates."
1169   (interactive)
1170   (company-search-assert-enabled)
1171   (company-set-selection company-search-old-selection t)
1172   (company-search-mode 0))
1173
1174 (defun company-search-other-char ()
1175   (interactive)
1176   (company-search-assert-enabled)
1177   (company-search-mode 0)
1178   (when last-input-event
1179     (clear-this-command-keys t)
1180     (setq unread-command-events (list last-input-event))))
1181
1182 (defvar company-search-map
1183   (let ((i 0)
1184         (keymap (make-keymap)))
1185     (if (fboundp 'max-char)
1186         (set-char-table-range (nth 1 keymap) (cons #x100 (max-char))
1187                               'company-search-printing-char)
1188       (with-no-warnings
1189         ;; obselete in Emacs 23
1190         (let ((l (generic-character-list))
1191               (table (nth 1 keymap)))
1192           (while l
1193             (set-char-table-default table (car l) 'company-search-printing-char)
1194             (setq l (cdr l))))))
1195     (define-key keymap [t] 'company-search-other-char)
1196     (while (< i ?\s)
1197       (define-key keymap (make-string 1 i) 'company-search-other-char)
1198       (incf i))
1199     (while (< i 256)
1200       (define-key keymap (vector i) 'company-search-printing-char)
1201       (incf i))
1202     (let ((meta-map (make-sparse-keymap)))
1203       (define-key keymap (char-to-string meta-prefix-char) meta-map)
1204       (define-key keymap [escape] meta-map))
1205     (define-key keymap (vector meta-prefix-char t) 'company-search-other-char)
1206     (define-key keymap "\e\e\e" 'company-search-other-char)
1207     (define-key keymap  [escape escape escape] 'company-search-other-char)
1208
1209     (define-key keymap "\C-g" 'company-search-abort)
1210     (define-key keymap "\C-s" 'company-search-repeat-forward)
1211     (define-key keymap "\C-r" 'company-search-repeat-backward)
1212     (define-key keymap "\C-o" 'company-search-kill-others)
1213     keymap)
1214   "Keymap used for incrementally searching the completion candidates.")
1215
1216 (define-minor-mode company-search-mode
1217   "Search mode for completion candidates.
1218 Don't start this directly, use `company-search-candidates' or
1219 `company-filter-candidates'."
1220   nil company-search-lighter nil
1221   (if company-search-mode
1222       (if (company-manual-begin)
1223           (progn
1224             (setq company-search-old-selection company-selection)
1225             (company-call-frontends 'update))
1226         (setq company-search-mode nil))
1227     (kill-local-variable 'company-search-string)
1228     (kill-local-variable 'company-search-lighter)
1229     (kill-local-variable 'company-search-old-selection)
1230     (company-enable-overriding-keymap company-active-map)))
1231
1232 (defsubst company-search-assert-enabled ()
1233   (company-assert-enabled)
1234   (unless company-search-mode
1235     (company-uninstall-map)
1236     (error "Company not in search mode")))
1237
1238 (defun company-search-candidates ()
1239   "Start searching the completion candidates incrementally.
1240
1241 \\<company-search-map>Search can be controlled with the commands:
1242 - `company-search-repeat-forward' (\\[company-search-repeat-forward])
1243 - `company-search-repeat-backward' (\\[company-search-repeat-backward])
1244 - `company-search-abort' (\\[company-search-abort])
1245
1246 Regular characters are appended to the search string.
1247
1248 The command `company-search-kill-others' (\\[company-search-kill-others]) uses
1249  the search string to limit the completion candidates."
1250   (interactive)
1251   (company-search-mode 1)
1252   (company-enable-overriding-keymap company-search-map))
1253
1254 (defvar company-filter-map
1255   (let ((keymap (make-keymap)))
1256     (define-key keymap [remap company-search-printing-char]
1257       'company-filter-printing-char)
1258     (set-keymap-parent keymap company-search-map)
1259     keymap)
1260   "Keymap used for incrementally searching the completion candidates.")
1261
1262 (defun company-filter-candidates ()
1263   "Start filtering the completion candidates incrementally.
1264 This works the same way as `company-search-candidates' immediately
1265 followed by `company-search-kill-others' after each input."
1266   (interactive)
1267   (company-search-mode 1)
1268   (company-enable-overriding-keymap company-filter-map))
1269
1270 ;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;
1271
1272 (defun company-select-next ()
1273   "Select the next candidate in the list."
1274   (interactive)
1275   (when (company-manual-begin)
1276     (company-set-selection (1+ company-selection))))
1277
1278 (defun company-select-previous ()
1279   "Select the previous candidate in the list."
1280   (interactive)
1281   (when (company-manual-begin)
1282     (company-set-selection (1- company-selection))))
1283
1284 (defun company-select-mouse (event)
1285   "Select the candidate picked by the mouse."
1286   (interactive "e")
1287   (when (nth 4 (event-start event))
1288     (company-set-selection (- (cdr (posn-actual-col-row (event-start event)))
1289                               (company--row)
1290                               1))
1291     t))
1292
1293 (defun company-complete-mouse (event)
1294   "Complete the candidate picked by the mouse."
1295   (interactive "e")
1296   (when (company-select-mouse event)
1297     (company-complete-selection)))
1298
1299 (defun company-complete-selection ()
1300   "Complete the selected candidate."
1301   (interactive)
1302   (when (company-manual-begin)
1303     (company-finish (nth company-selection company-candidates))))
1304
1305 (defun company-complete-common ()
1306   "Complete the common part of all candidates."
1307   (interactive)
1308   (when (company-manual-begin)
1309     (if (and (not (cdr company-candidates))
1310              (equal company-common (car company-candidates)))
1311         (company-complete-selection)
1312       (insert (company-strip-prefix company-common)))))
1313
1314 (defun company-complete ()
1315   "Complete the common part of all candidates or the current selection.
1316 The first time this is called, the common part is completed, the second time, or
1317 when the selection has been changed, the selected candidate is completed."
1318   (interactive)
1319   (when (company-manual-begin)
1320     (if (or company-selection-changed
1321             (eq last-command 'company-complete-common))
1322         (call-interactively 'company-complete-selection)
1323       (call-interactively 'company-complete-common)
1324       (setq this-command 'company-complete-common))))
1325
1326 (defun company-complete-number (n)
1327   "Complete the Nth candidate.
1328 To show the number next to the candidates in some back-ends, enable
1329 `company-show-numbers'."
1330   (when (company-manual-begin)
1331     (and (< n 1) (> n company-candidates-length)
1332          (error "No candidate number %d" n))
1333     (decf n)
1334     (company-finish (nth n company-candidates))))
1335
1336 ;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;
1337
1338 (defconst company-space-strings-limit 100)
1339
1340 (defconst company-space-strings
1341   (let (lst)
1342     (dotimes (i company-space-strings-limit)
1343       (push (make-string (- company-space-strings-limit 1 i) ?\  ) lst))
1344     (apply 'vector lst)))
1345
1346 (defsubst company-space-string (len)
1347   (if (< len company-space-strings-limit)
1348       (aref company-space-strings len)
1349     (make-string len ?\ )))
1350
1351 (defsubst company-safe-substring (str from &optional to)
1352   (let ((len (length str)))
1353     (if (> from len)
1354         ""
1355       (if (and to (> to len))
1356           (concat (substring str from)
1357                   (company-space-string (- to len)))
1358         (substring str from to)))))
1359
1360 ;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;
1361
1362 (defvar company-last-metadata nil)
1363 (make-variable-buffer-local 'company-last-metadata)
1364
1365 (defun company-fetch-metadata ()
1366   (let ((selected (nth company-selection company-candidates)))
1367     (unless (equal selected (car company-last-metadata))
1368       (setq company-last-metadata
1369             (cons selected (company-call-backend 'meta selected))))
1370     (cdr company-last-metadata)))
1371
1372 (defun company-doc-buffer (&optional string)
1373   (with-current-buffer (get-buffer-create "*Company meta-data*")
1374     (erase-buffer)
1375     (current-buffer)))
1376
1377 (defmacro company--electric-do (&rest body)
1378   (declare (indent 0) (debug t))
1379   `(when (company-manual-begin)
1380      (save-window-excursion
1381        (let ((height (window-height))
1382              (row (company--row)))
1383          ,@body
1384          (and (< (window-height) height)
1385               (< (- (window-height) row 2) company-tooltip-limit)
1386               (recenter (- (window-height) row 2)))
1387          (while (eq 'scroll-other-window
1388                     (key-binding (vector (list (read-event)))))
1389            (call-interactively 'scroll-other-window))
1390          (when last-input-event
1391            (clear-this-command-keys t)
1392            (setq unread-command-events (list last-input-event)))))))
1393
1394 (defun company-show-doc-buffer ()
1395   "Temporarily show a buffer with the complete documentation for the selection."
1396   (interactive)
1397   (company--electric-do
1398     (let ((selected (nth company-selection company-candidates)))
1399       (display-buffer (or (company-call-backend 'doc-buffer selected)
1400                           (error "No documentation available")) t))))
1401 (put 'company-show-doc-buffer 'company-keep t)
1402
1403 (defun company-show-location ()
1404   "Temporarily display a buffer showing the selected candidate in context."
1405   (interactive)
1406   (company--electric-do
1407     (let* ((selected (nth company-selection company-candidates))
1408            (location (company-call-backend 'location selected))
1409            (pos (or (cdr location) (error "No location available")))
1410            (buffer (or (and (bufferp (car location)) (car location))
1411                        (find-file-noselect (car location) t))))
1412       (with-selected-window (display-buffer buffer t)
1413         (if (bufferp (car location))
1414             (goto-char pos)
1415           (goto-line pos))
1416         (set-window-start nil (point))))))
1417 (put 'company-show-location 'company-keep t)
1418
1419 ;;; package functions ;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;
1420
1421 (defvar company-callback nil)
1422 (make-variable-buffer-local 'company-callback)
1423
1424 (defvar company-begin-with-marker nil)
1425 (make-variable-buffer-local 'company-begin-with-marker)
1426
1427 (defun company-remove-callback (&optional ignored)
1428   (remove-hook 'company-completion-finished-hook company-callback t)
1429   (remove-hook 'company-completion-cancelled-hook 'company-remove-callback t)
1430   (remove-hook 'company-completion-finished-hook 'company-remove-callback t)
1431   (when company-begin-with-marker
1432     (set-marker company-begin-with-marker nil)))
1433
1434 (defun company-begin-backend (backend &optional callback)
1435   "Start a completion at point using BACKEND."
1436   (interactive (let ((val (completing-read "Company back-end: "
1437                                            obarray
1438                                            'functionp nil "company-")))
1439                  (when val
1440                    (list (intern val)))))
1441   (when (setq company-callback callback)
1442     (add-hook 'company-completion-finished-hook company-callback nil t))
1443   (add-hook 'company-completion-cancelled-hook 'company-remove-callback nil t)
1444   (add-hook 'company-completion-finished-hook 'company-remove-callback nil t)
1445   (setq company-backend backend)
1446   ;; Return non-nil if active.
1447   (or (company-manual-begin)
1448       (error "Cannot complete at point")))
1449
1450 (defun company-begin-with (candidates
1451                            &optional prefix-length require-match callback)
1452   "Start a completion at point.
1453 CANDIDATES is the list of candidates to use and PREFIX-LENGTH is the length of
1454 the prefix that already is in the buffer before point.  It defaults to 0.
1455
1456 CALLBACK is a function called with the selected result if the user successfully
1457 completes the input.
1458
1459 Example:
1460 \(company-begin-with '\(\"foo\" \"foobar\" \"foobarbaz\"\)\)"
1461   (setq company-begin-with-marker (copy-marker (point) t))
1462   (company-begin-backend
1463    `(lambda (command &optional arg &rest ignored)
1464       (cond
1465        ((eq command 'prefix)
1466         (when (equal (point) (marker-position company-begin-with-marker))
1467           (buffer-substring ,(- (point) (or prefix-length 0)) (point))))
1468        ((eq command 'candidates)
1469         (all-completions arg ',candidates))
1470        ((eq command 'require-match)
1471         ,require-match)))
1472    callback))
1473
1474 ;;; pseudo-tooltip ;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;
1475
1476 (defvar company-pseudo-tooltip-overlay nil)
1477 (make-variable-buffer-local 'company-pseudo-tooltip-overlay)
1478
1479 (defvar company-tooltip-offset 0)
1480 (make-variable-buffer-local 'company-tooltip-offset)
1481
1482 (defun company-pseudo-tooltip-update-offset (selection num-lines limit)
1483
1484   (decf limit 2)
1485   (setq company-tooltip-offset
1486         (max (min selection company-tooltip-offset)
1487              (- selection -1 limit)))
1488
1489   (when (<= company-tooltip-offset 1)
1490     (incf limit)
1491     (setq company-tooltip-offset 0))
1492
1493   (when (>= company-tooltip-offset (- num-lines limit 1))
1494     (incf limit)
1495     (when (= selection (1- num-lines))
1496       (decf company-tooltip-offset)
1497       (when (<= company-tooltip-offset 1)
1498         (setq company-tooltip-offset 0)
1499         (incf limit))))
1500
1501   limit)
1502
1503 ;;; propertize
1504
1505 (defsubst company-round-tab (arg)
1506   (* (/ (+ arg tab-width) tab-width) tab-width))
1507
1508 (defun company-untabify (str)
1509   (let* ((pieces (split-string str "\t"))
1510          (copy pieces))
1511     (while (cdr copy)
1512       (setcar copy (company-safe-substring
1513                     (car copy) 0 (company-round-tab (string-width (car copy)))))
1514       (pop copy))
1515     (apply 'concat pieces)))
1516
1517 (defun company-fill-propertize (line width selected)
1518   (setq line (company-safe-substring line 0 width))
1519   (add-text-properties 0 width '(face company-tooltip
1520                                  mouse-face company-tooltip-mouse)
1521                        line)
1522   (add-text-properties 0 (length company-common)
1523                        '(face company-tooltip-common
1524                          mouse-face company-tooltip-mouse)
1525                        line)
1526   (when selected
1527     (if (and company-search-string
1528              (string-match (regexp-quote company-search-string) line
1529                            (length company-prefix)))
1530         (progn
1531           (add-text-properties (match-beginning 0) (match-end 0)
1532                                '(face company-tooltip-selection)
1533                                line)
1534           (when (< (match-beginning 0) (length company-common))
1535             (add-text-properties (match-beginning 0) (length company-common)
1536                                  '(face company-tooltip-common-selection)
1537                                  line)))
1538       (add-text-properties 0 width '(face company-tooltip-selection
1539                                           mouse-face company-tooltip-selection)
1540                            line)
1541       (add-text-properties 0 (length company-common)
1542                            '(face company-tooltip-common-selection
1543                              mouse-face company-tooltip-selection)
1544                            line)))
1545   line)
1546
1547 ;;; replace
1548
1549 (defun company-buffer-lines (beg end)
1550   (goto-char beg)
1551   (let ((row (company--row))
1552         lines)
1553     (while (and (equal (move-to-window-line (incf row)) row)
1554                 (<= (point) end))
1555       (push (buffer-substring beg (min end (1- (point)))) lines)
1556       (setq beg (point)))
1557     (unless (eq beg end)
1558       (push (buffer-substring beg end) lines))
1559     (nreverse lines)))
1560
1561 (defsubst company-modify-line (old new offset)
1562   (concat (company-safe-substring old 0 offset)
1563           new
1564           (company-safe-substring old (+ offset (length new)))))
1565
1566 (defsubst company--length-limit (lst limit)
1567   (if (nthcdr limit lst)
1568       limit
1569     (length lst)))
1570
1571 (defun company--replacement-string (lines old column nl &optional align-top)
1572
1573   (let ((width (length (car lines))))
1574     (when (> width (- (window-width) column))
1575       (setq column (max 0 (- (window-width) width)))))
1576
1577   (let (new)
1578     (when align-top
1579       ;; untouched lines first
1580       (dotimes (i (- (length old) (length lines)))
1581         (push (pop old) new)))
1582     ;; length into old lines.
1583     (while old
1584       (push (company-modify-line (pop old) (pop lines) column) new))
1585     ;; Append whole new lines.
1586     (while lines
1587       (push (concat (company-space-string column) (pop lines)) new))
1588     (concat (when nl "\n")
1589             (mapconcat 'identity (nreverse new) "\n")
1590             "\n")))
1591
1592 (defun company--create-lines (selection limit)
1593
1594   (let ((len company-candidates-length)
1595         (numbered 99999)
1596         lines
1597         width
1598         lines-copy
1599         previous
1600         remainder
1601         new)
1602
1603     ;; Scroll to offset.
1604     (setq limit (company-pseudo-tooltip-update-offset selection len limit))
1605
1606     (when (> company-tooltip-offset 0)
1607       (setq previous (format "...(%d)" company-tooltip-offset)))
1608
1609     (setq remainder (- len limit company-tooltip-offset)
1610           remainder (when (> remainder 0)
1611                       (setq remainder (format "...(%d)" remainder))))
1612
1613     (decf selection company-tooltip-offset)
1614     (setq width (max (length previous) (length remainder))
1615           lines (nthcdr company-tooltip-offset company-candidates)
1616           len (min limit len)
1617           lines-copy lines)
1618
1619     (dotimes (i len)
1620       (setq width (max (length (pop lines-copy)) width)))
1621     (setq width (min width (window-width)))
1622
1623     (setq lines-copy lines)
1624
1625     ;; number can make tooltip too long
1626     (when company-show-numbers
1627       (setq numbered company-tooltip-offset))
1628
1629     (when previous
1630       (push (propertize (company-safe-substring previous 0 width)
1631                         'face 'company-tooltip)
1632             new))
1633
1634     (dotimes (i len)
1635       (push (company-fill-propertize
1636              (if (>= numbered 10)
1637                  (company-reformat (pop lines))
1638                (incf numbered)
1639                (format "%s %d"
1640                        (company-safe-substring (company-reformat (pop lines))
1641                                                0 (- width 2))
1642                        (mod numbered 10)))
1643              width (equal i selection))
1644             new))
1645
1646     (when remainder
1647       (push (propertize (company-safe-substring remainder 0 width)
1648                         'face 'company-tooltip)
1649             new))
1650
1651     (setq lines (nreverse new))))
1652
1653 ;; show
1654
1655 (defsubst company--window-inner-height ()
1656   (let ((edges (window-inside-edges (selected-window))))
1657     (- (nth 3 edges) (nth 1 edges))))
1658
1659 (defsubst company--pseudo-tooltip-height ()
1660   "Calculate the appropriate tooltip height.
1661 Returns a negative number if the tooltip should be displayed above point."
1662   (let* ((lines (count-lines (window-start) (point-at-bol)))
1663          (below (- (company--window-inner-height) 1 lines)))
1664     (if (and (< below (min company-tooltip-minimum company-candidates-length))
1665              (> lines below))
1666         (- (max 3 (min company-tooltip-limit lines)))
1667       (max 3 (min company-tooltip-limit below)))))
1668
1669 (defun company-pseudo-tooltip-show (row column selection)
1670   (company-pseudo-tooltip-hide)
1671   (save-excursion
1672
1673     (move-to-column 0)
1674
1675     (let* ((height (company--pseudo-tooltip-height))
1676            above)
1677
1678       (when (< height 0)
1679         (setq row (+ row height -1)
1680               above t))
1681
1682       (let* ((nl (< (move-to-window-line row) row))
1683              (beg (point))
1684              (end (save-excursion
1685                     (move-to-window-line (+ row (abs height)))
1686                     (point)))
1687              (ov (make-overlay beg end))
1688              (args (list (mapcar 'company-untabify
1689                                  (company-buffer-lines beg end))
1690                          column nl above)))
1691
1692         (setq company-pseudo-tooltip-overlay ov)
1693         (overlay-put ov 'company-replacement-args args)
1694         (overlay-put ov 'company-before
1695                      (apply 'company--replacement-string
1696                             (company--create-lines selection (abs height))
1697                             args))
1698
1699         (overlay-put ov 'company-column column)
1700         (overlay-put ov 'company-height (abs height))
1701         (overlay-put ov 'window (selected-window))))))
1702
1703 (defun company-pseudo-tooltip-show-at-point (pos)
1704   (let ((col-row (company--col-row pos)))
1705     (when col-row
1706       (company-pseudo-tooltip-show (1+ (cdr col-row)) (car col-row)
1707                                    company-selection))))
1708
1709 (defun company-pseudo-tooltip-edit (lines selection)
1710   (let ((column (overlay-get company-pseudo-tooltip-overlay 'company-column))
1711         (height (overlay-get company-pseudo-tooltip-overlay 'company-height)))
1712     (overlay-put company-pseudo-tooltip-overlay 'company-before
1713                  (apply 'company--replacement-string
1714                         (company--create-lines selection height)
1715                         (overlay-get company-pseudo-tooltip-overlay
1716                                      'company-replacement-args)))))
1717
1718 (defun company-pseudo-tooltip-hide ()
1719   (when company-pseudo-tooltip-overlay
1720     (delete-overlay company-pseudo-tooltip-overlay)
1721     (setq company-pseudo-tooltip-overlay nil)))
1722
1723 (defun company-pseudo-tooltip-hide-temporarily ()
1724   (when (overlayp company-pseudo-tooltip-overlay)
1725     (overlay-put company-pseudo-tooltip-overlay 'invisible nil)
1726     (overlay-put company-pseudo-tooltip-overlay 'before-string nil)))
1727
1728 (defun company-pseudo-tooltip-unhide ()
1729   (when company-pseudo-tooltip-overlay
1730     (overlay-put company-pseudo-tooltip-overlay 'invisible t)
1731     (overlay-put company-pseudo-tooltip-overlay 'before-string
1732                  (overlay-get company-pseudo-tooltip-overlay 'company-before))
1733     (overlay-put company-pseudo-tooltip-overlay 'window (selected-window))))
1734
1735 (defun company-pseudo-tooltip-frontend (command)
1736   "A `company-mode' front-end similar to a tool-tip but based on overlays."
1737   (case command
1738     ('pre-command (company-pseudo-tooltip-hide-temporarily))
1739     ('post-command
1740      (let ((old-height (if (overlayp company-pseudo-tooltip-overlay)
1741                            (overlay-get company-pseudo-tooltip-overlay
1742                                         'company-height)
1743                          0))
1744            (new-height (company--pseudo-tooltip-height)))
1745        (unless (and (>= (* old-height new-height) 0)
1746                     (>= (abs old-height) (abs new-height)))
1747          ;; Redraw needed.
1748          (company-pseudo-tooltip-show-at-point (- (point)
1749                                                   (length company-prefix)))))
1750      (company-pseudo-tooltip-unhide))
1751     ('hide (company-pseudo-tooltip-hide)
1752            (setq company-tooltip-offset 0))
1753     ('update (when (overlayp company-pseudo-tooltip-overlay)
1754                (company-pseudo-tooltip-edit company-candidates
1755                                             company-selection)))))
1756
1757 (defun company-pseudo-tooltip-unless-just-one-frontend (command)
1758   "`company-pseudo-tooltip-frontend', but not shown for single candidates."
1759   (unless (and (eq command 'post-command)
1760                (not (cdr company-candidates)))
1761     (company-pseudo-tooltip-frontend command)))
1762
1763 ;;; overlay ;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;
1764
1765 (defvar company-preview-overlay nil)
1766 (make-variable-buffer-local 'company-preview-overlay)
1767
1768 (defun company-preview-show-at-point (pos)
1769   (company-preview-hide)
1770
1771   (setq company-preview-overlay (make-overlay pos pos))
1772
1773   (let ((completion(nth company-selection company-candidates)))
1774     (setq completion (propertize completion 'face 'company-preview))
1775     (add-text-properties 0 (length company-common)
1776                          '(face company-preview-common) completion)
1777
1778     ;; Add search string
1779     (and company-search-string
1780          (string-match (regexp-quote company-search-string) completion)
1781          (add-text-properties (match-beginning 0)
1782                               (match-end 0)
1783                               '(face company-preview-search)
1784                               completion))
1785
1786     (setq completion (company-strip-prefix completion))
1787
1788     (and (equal pos (point))
1789          (not (equal completion ""))
1790          (add-text-properties 0 1 '(cursor t) completion))
1791
1792     (overlay-put company-preview-overlay 'after-string completion)
1793     (overlay-put company-preview-overlay 'window (selected-window))))
1794
1795 (defun company-preview-hide ()
1796   (when company-preview-overlay
1797     (delete-overlay company-preview-overlay)
1798     (setq company-preview-overlay nil)))
1799
1800 (defun company-preview-frontend (command)
1801   "A `company-mode' front-end showing the selection as if it had been inserted."
1802   (case command
1803     ('pre-command (company-preview-hide))
1804     ('post-command (company-preview-show-at-point (point)))
1805     ('hide (company-preview-hide))))
1806
1807 (defun company-preview-if-just-one-frontend (command)
1808   "`company-preview-frontend', but only shown for single candidates."
1809   (unless (and (eq command 'post-command)
1810                (cdr company-candidates))
1811     (company-preview-frontend command)))
1812
1813 ;;; echo ;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;
1814
1815 (defvar company-echo-last-msg nil)
1816 (make-variable-buffer-local 'company-echo-last-msg)
1817
1818 (defvar company-echo-timer nil)
1819
1820 (defvar company-echo-delay .1)
1821
1822 (defun company-echo-show (&optional getter)
1823   (when getter
1824     (setq company-echo-last-msg (funcall getter)))
1825   (let ((message-log-max nil))
1826     (if company-echo-last-msg
1827         (message "%s" company-echo-last-msg)
1828       (message ""))))
1829
1830 (defsubst company-echo-show-soon (&optional getter)
1831   (when company-echo-timer
1832     (cancel-timer company-echo-timer))
1833   (setq company-echo-timer (run-with-timer company-echo-delay nil
1834                                            'company-echo-show getter)))
1835
1836 (defun company-echo-format ()
1837
1838   (let ((limit (window-width (minibuffer-window)))
1839         (len -1)
1840         ;; Roll to selection.
1841         (candidates (nthcdr company-selection company-candidates))
1842         (i (if company-show-numbers company-selection 99999))
1843         comp msg)
1844
1845     (while candidates
1846       (setq comp (company-reformat (pop candidates))
1847             len (+ len 1 (length comp)))
1848       (if (< i 10)
1849           ;; Add number.
1850           (progn
1851             (setq comp (propertize (format "%d: %s" i comp)
1852                                    'face 'company-echo))
1853             (incf len 3)
1854             (incf i)
1855             (add-text-properties 3 (+ 3 (length company-common))
1856                                  '(face company-echo-common) comp))
1857         (setq comp (propertize comp 'face 'company-echo))
1858         (add-text-properties 0 (length company-common)
1859                              '(face company-echo-common) comp))
1860       (if (>= len limit)
1861           (setq candidates nil)
1862         (push comp msg)))
1863
1864     (mapconcat 'identity (nreverse msg) " ")))
1865
1866 (defun company-echo-strip-common-format ()
1867
1868   (let ((limit (window-width (minibuffer-window)))
1869         (len (+ (length company-prefix) 2))
1870         ;; Roll to selection.
1871         (candidates (nthcdr company-selection company-candidates))
1872         (i (if company-show-numbers company-selection 99999))
1873         msg comp)
1874
1875     (while candidates
1876       (setq comp (company-strip-prefix (pop candidates))
1877             len (+ len 2 (length comp)))
1878       (when (< i 10)
1879         ;; Add number.
1880         (setq comp (format "%s (%d)" comp i))
1881         (incf len 4)
1882         (incf i))
1883       (if (>= len limit)
1884           (setq candidates nil)
1885         (push (propertize comp 'face 'company-echo) msg)))
1886
1887     (concat (propertize company-prefix 'face 'company-echo-common) "{"
1888             (mapconcat 'identity (nreverse msg) ", ")
1889             "}")))
1890
1891 (defun company-echo-hide ()
1892   (when company-echo-timer
1893     (cancel-timer company-echo-timer))
1894   (unless (equal company-echo-last-msg "")
1895     (setq company-echo-last-msg "")
1896     (company-echo-show)))
1897
1898 (defun company-echo-frontend (command)
1899   "A `company-mode' front-end showing the candidates in the echo area."
1900   (case command
1901     ('pre-command (company-echo-show-soon))
1902     ('post-command (company-echo-show-soon 'company-echo-format))
1903     ('hide (company-echo-hide))))
1904
1905 (defun company-echo-strip-common-frontend (command)
1906   "A `company-mode' front-end showing the candidates in the echo area."
1907   (case command
1908     ('pre-command (company-echo-show-soon))
1909     ('post-command (company-echo-show-soon 'company-echo-strip-common-format))
1910     ('hide (company-echo-hide))))
1911
1912 (defun company-echo-metadata-frontend (command)
1913   "A `company-mode' front-end showing the documentation in the echo area."
1914   (case command
1915     ('pre-command (company-echo-show-soon))
1916     ('post-command (company-echo-show-soon 'company-fetch-metadata))
1917     ('hide (company-echo-hide))))
1918
1919 (provide 'company)
1920 ;;; company.el ends here