]> rtime.felk.cvut.cz Git - sojka/company-mode.git/blob - company.el
Make sure hooks are called when finishing by character input.
[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.2.1
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 ;; To write your own back-end, look at the documentation for `company-backends'.
43 ;; Here is a simple example completing "foo":
44 ;;
45 ;; (defun company-my-backend (command &optional arg &rest ignored)
46 ;;   (case command
47 ;;     ('prefix (when (looking-back "foo\\>")
48 ;;                (match-string 0)))
49 ;;     ('candidates (list "foobar" "foobaz" "foobarbaz"))
50 ;;     ('meta (format "This value is named %s" arg))))
51 ;;
52 ;; Sometimes it is a good idea to mix two back-ends together, for example to
53 ;; enrich gtags with dabbrev text (to emulate local variables):
54 ;;
55 ;; (defun gtags-gtags-dabbrev-backend (command &optional arg &rest ignored)
56 ;;   (case command
57 ;;     (prefix (company-gtags 'prefix))
58 ;;     (candidates (append (company-gtags 'candidates arg)
59 ;;                         (company-dabbrev 'candidates arg)))))
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 ;;    Added hooks.
69 ;;    Added `company-require-match' option.
70 ;;
71 ;; 2009-04-05 (0.2.1)
72 ;;    Improved Emacs Lisp back-end behavior for local variables.
73 ;;    Added `company-elisp-detect-function-context' option.
74 ;;    The mouse can now be used for selection.
75 ;;
76 ;; 2009-03-22 (0.2)
77 ;;    Added `company-show-location'.
78 ;;    Added etags back-end.
79 ;;    Added work-around for end-of-buffer bug.
80 ;;    Added `company-filter-candidates'.
81 ;;    More local Lisp variables are now included in the candidates.
82 ;;
83 ;; 2009-03-21 (0.1.5)
84 ;;    Fixed elisp documentation buffer always showing the same doc.
85 ;;    Added `company-echo-strip-common-frontend'.
86 ;;    Added `company-show-numbers' option and M-0 ... M-9 default bindings.
87 ;;    Don't hide the echo message if it isn't shown.
88 ;;
89 ;; 2009-03-20 (0.1)
90 ;;    Initial release.
91 ;;
92 ;;; Code:
93
94 (eval-when-compile (require 'cl))
95
96 (add-to-list 'debug-ignored-errors "^.* frontend cannot be used twice$")
97 (add-to-list 'debug-ignored-errors "^Echo area cannot be used twice$")
98 (add-to-list 'debug-ignored-errors "^No \\(document\\|loc\\)ation available$")
99 (add-to-list 'debug-ignored-errors "^Company not ")
100 (add-to-list 'debug-ignored-errors "^No candidate number ")
101
102 (defgroup company nil
103   "Extensible inline text completion mechanism"
104   :group 'abbrev
105   :group 'convenience
106   :group 'maching)
107
108 (defface company-tooltip
109   '((t :background "yellow"
110        :foreground "black"))
111   "*Face used for the tool tip."
112   :group 'company)
113
114 (defface company-tooltip-selection
115   '((default :inherit company-tooltip)
116     (((class color) (min-colors 88)) (:background "orange1"))
117     (t (:background "green")))
118   "*Face used for the selection in the tool tip."
119   :group 'company)
120
121 (defface company-tooltip-mouse
122   '((default :inherit highlight))
123   "*Face used for the tool tip item under the mouse."
124   :group 'company)
125
126 (defface company-tooltip-common
127   '((t :inherit company-tooltip
128        :foreground "red"))
129   "*Face used for the common completion in the tool tip."
130   :group 'company)
131
132 (defface company-tooltip-common-selection
133   '((t :inherit company-tooltip-selection
134        :foreground "red"))
135   "*Face used for the selected common completion in the tool tip."
136   :group 'company)
137
138 (defcustom company-tooltip-limit 10
139   "*The maximum number of candidates in the tool tip"
140   :group 'company
141   :type 'integer)
142
143 (defface company-preview
144   '((t :background "blue4"
145        :foreground "wheat"))
146   "*Face used for the completion preview."
147   :group 'company)
148
149 (defface company-preview-common
150   '((t :inherit company-preview
151        :foreground "red"))
152   "*Face used for the common part of the completion preview."
153   :group 'company)
154
155 (defface company-preview-search
156   '((t :inherit company-preview
157        :background "blue1"))
158   "*Face used for the search string in the completion preview."
159   :group 'company)
160
161 (defface company-echo nil
162   "*Face used for completions in the echo area."
163   :group 'company)
164
165 (defface company-echo-common
166   '((((background dark)) (:foreground "firebrick1"))
167     (((background light)) (:background "firebrick4")))
168   "*Face used for the common part of completions in the echo area."
169   :group 'company)
170
171 (defun company-frontends-set (variable value)
172   ;; uniquify
173   (let ((remainder value))
174     (setcdr remainder (delq (car remainder) (cdr remainder))))
175   (and (memq 'company-pseudo-tooltip-unless-just-one-frontend value)
176        (memq 'company-pseudo-tooltip-frontend value)
177        (error "Pseudo tooltip frontend cannot be used twice"))
178   (and (memq 'company-preview-if-just-one-frontend value)
179        (memq 'company-preview-frontend value)
180        (error "Preview frontend cannot be used twice"))
181   (and (memq 'company-echo value)
182        (memq 'company-echo-metadata-frontend value)
183        (error "Echo area cannot be used twice"))
184   ;; preview must come last
185   (dolist (f '(company-preview-if-just-one-frontend company-preview-frontend))
186     (when (memq f value)
187       (setq value (append (delq f value) (list f)))))
188   (set variable value))
189
190 (defcustom company-frontends '(company-pseudo-tooltip-unless-just-one-frontend
191                                company-preview-frontend
192                                company-echo-metadata-frontend)
193   "*The list of active front-ends (visualizations).
194 Each front-end is a function that takes one argument.  It is called with
195 one of the following arguments:
196
197 'show: When the visualization should start.
198
199 'hide: When the visualization should end.
200
201 'update: When the data has been updated.
202
203 'pre-command: Before every command that is executed while the
204 visualization is active.
205
206 'post-command: After every command that is executed while the
207 visualization is active.
208
209 The visualized data is stored in `company-prefix', `company-candidates',
210 `company-common', `company-selection', `company-point' and
211 `company-search-string'."
212   :set 'company-frontends-set
213   :group 'company
214   :type '(repeat (choice (const :tag "echo" company-echo-frontend)
215                          (const :tag "echo, strip common"
216                                 company-echo-strip-common-frontend)
217                          (const :tag "show echo meta-data in echo"
218                                 company-echo-metadata-frontend)
219                          (const :tag "pseudo tooltip"
220                                 company-pseudo-tooltip-frontend)
221                          (const :tag "pseudo tooltip, multiple only"
222                                 company-pseudo-tooltip-unless-just-one-frontend)
223                          (const :tag "preview" company-preview-frontend)
224                          (const :tag "preview, unique only"
225                                 company-preview-if-just-one-frontend)
226                          (function :tag "custom function" nil))))
227
228 (defcustom company-backends '(company-elisp company-nxml company-css
229                               company-semantic company-gtags company-etags
230                               company-oddmuse company-files company-dabbrev)
231   "*The list of active back-ends (completion engines).
232 Each back-end is a function that takes a variable number of arguments.
233 The first argument is the command requested from the back-end.  It is one
234 of the following:
235
236 'prefix: The back-end should return the text to be completed.  It must be
237 text immediately before `point'.  Returning nil passes control to the next
238 back-end.
239
240 'candidates: The second argument is the prefix to be completed.  The
241 return value should be a list of candidates that start with the prefix.
242
243 Optional commands:
244
245 'sorted: The back-end may return t here to indicate that the candidates
246 are sorted and will not need to be sorted again.
247
248 'no-cache: Usually company doesn't ask for candidates again as completion
249 progresses, unless the back-end returns t for this command.  The second
250 argument is the latest prefix.
251
252 'meta: The second argument is a completion candidate.  The back-end should
253 return a (short) documentation string for it.
254
255 'doc-buffer: The second argument is a completion candidate.  The back-end should
256 create a buffer (preferably with `company-doc-buffer'), fill it with
257 documentation and return it.
258
259 'location: The second argument is a completion candidate.  The back-end can
260 return the cons of buffer and buffer location, or of file and line
261 number where the completion candidate was defined.
262
263 'require-match: If this value is t, the user is not allowed to enter anything
264 not offering as a candidate.  Use with care!  The default value nil gives the
265 user that choice with `company-require-match'.  Return value 'never overrides
266 that option the other way around.
267
268 The back-end should return nil for all commands it does not support or
269 does not know about."
270   :group 'company
271   :type '(repeat (function :tag "function" nil)))
272
273 (defvar start-count 0)
274
275 (defcustom company-completion-started-hook nil
276   "*Hook run when company starts completing.
277 The hook is called with one argument that is non-nil if the completion was
278 started manually."
279   :group 'company
280   :type 'hook)
281
282 (defcustom company-completion-cancelled-hook nil
283   "*Hook run when company cancels completing.
284 The hook is called with one argument that is non-nil if the completion was
285 aborted manually."
286   :group 'company
287   :type 'hook)
288
289 (defcustom company-completion-finished-hook nil
290   "*Hook run when company successfully completes.
291 The hook is called with the selected candidate as an argument."
292   :group 'company
293   :type 'hook)
294
295 (defcustom company-minimum-prefix-length 3
296   "*The minimum prefix length for automatic completion."
297   :group 'company
298   :type '(integer :tag "prefix length"))
299
300 (defcustom company-require-match 'company-explicit-action-p
301   "*If enabled, disallow non-matching input.
302 This can be a function do determine if a match is required.
303
304 This can be overridden by the back-end, if it returns t or 'never to
305 'require-match."
306   :group 'company
307   :type '(choice (const :tag "Off" nil)
308                  (function :tag "Predicate function")
309                  (const :tag "On, if user interaction took place"
310                         'company-explicit-action-p)
311                  (const :tag "On" t)))
312
313 (defcustom company-idle-delay .7
314   "*The idle delay in seconds until automatic completions starts.
315 A value of nil means never complete automatically, t means complete
316 immediately when a prefix of `company-minimum-prefix-length' is reached."
317   :group 'company
318   :type '(choice (const :tag "never (nil)" nil)
319                  (const :tag "immediate (t)" t)
320                  (number :tag "seconds")))
321
322 (defcustom company-show-numbers nil
323   "*If enabled, show quick-access numbers for the first ten candidates."
324   :group 'company
325   :type '(choice (const :tag "off" nil)
326                  (const :tag "on" t)))
327
328 (defvar company-end-of-buffer-workaround t
329   "*Work around a visualization bug when completing at the end of the buffer.
330 The work-around consists of adding a newline.")
331
332 ;;; mode ;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;
333
334 (defvar company-mode-map (make-sparse-keymap)
335   "Keymap used by `company-mode'.")
336
337 (defvar company-active-map
338   (let ((keymap (make-sparse-keymap)))
339     (define-key keymap (kbd "M-n") 'company-select-next)
340     (define-key keymap (kbd "M-p") 'company-select-previous)
341     (define-key keymap (kbd "<down>") 'company-select-next)
342     (define-key keymap (kbd "<up>") 'company-select-previous)
343     (define-key keymap [down-mouse-1] 'ignore)
344     (define-key keymap [down-mouse-3] 'ignore)
345     (define-key keymap [mouse-1] 'company-complete-mouse)
346     (define-key keymap [mouse-3] 'company-select-mouse)
347     (define-key keymap [up-mouse-1] 'ignore)
348     (define-key keymap [up-mouse-3] 'ignore)
349     (define-key keymap "\C-m" 'company-complete-selection)
350     (define-key keymap "\t" 'company-complete-common)
351     (define-key keymap (kbd "<f1>") 'company-show-doc-buffer)
352     (define-key keymap "\C-w" 'company-show-location)
353     (define-key keymap "\C-s" 'company-search-candidates)
354     (define-key keymap "\C-\M-s" 'company-filter-candidates)
355     (dotimes (i 10)
356       (define-key keymap (vector (+ (aref (kbd "M-0") 0) i))
357         `(lambda () (interactive) (company-complete-number ,i))))
358
359     keymap)
360   "Keymap that is enabled during an active completion.")
361
362 ;;;###autoload
363 (define-minor-mode company-mode
364   "\"complete anything\"; in in-buffer completion framework.
365 Completion starts automatically, depending on the values
366 `company-idle-delay' and `company-minimum-prefix-length'.
367
368 Completion can be controlled with the commands:
369 `company-complete-common', `company-complete-selection', `company-complete',
370 `company-select-next', `company-select-previous'.  If these commands are
371 called before `company-idle-delay', completion will also start.
372
373 Completions can be searched with `company-search-candidates' or
374 `company-filter-candidates'.  These can be used while completion is
375 inactive, as well.
376
377 The completion data is retrieved using `company-backends' and displayed using
378 `company-frontends'.
379
380 regular keymap (`company-mode-map'):
381
382 \\{company-mode-map}
383 keymap during active completions (`company-active-map'):
384
385 \\{company-active-map}"
386   nil " comp" company-mode-map
387   (if company-mode
388       (progn
389         (add-hook 'pre-command-hook 'company-pre-command nil t)
390         (add-hook 'post-command-hook 'company-post-command nil t)
391         (dolist (backend company-backends)
392           (unless (fboundp backend)
393             (ignore-errors (require backend nil t)))
394           (unless (fboundp backend)
395             (message "Company back-end '%s' could not be initialized"
396                      backend))))
397     (remove-hook 'pre-command-hook 'company-pre-command t)
398     (remove-hook 'post-command-hook 'company-post-command t)
399     (company-cancel)
400     (kill-local-variable 'company-point)))
401
402 (defsubst company-assert-enabled ()
403   (unless company-mode
404     (company-uninstall-map)
405     (error "Company not enabled")))
406
407 ;;; keymaps ;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;
408
409 (defvar company-overriding-keymap-bound nil)
410 (make-variable-buffer-local 'company-overriding-keymap-bound)
411
412 (defvar company-old-keymap nil)
413 (make-variable-buffer-local 'company-old-keymap)
414
415 (defvar company-my-keymap nil)
416 (make-variable-buffer-local 'company-my-keymap)
417
418 (defsubst company-enable-overriding-keymap (keymap)
419   (setq company-my-keymap keymap)
420   (when company-overriding-keymap-bound
421     (company-uninstall-map)))
422
423 (defun company-install-map ()
424   (unless (or company-overriding-keymap-bound
425               (null company-my-keymap))
426     (setq company-old-keymap overriding-terminal-local-map
427           overriding-terminal-local-map company-my-keymap
428           company-overriding-keymap-bound t)))
429
430 (defun company-uninstall-map ()
431   (when (eq overriding-terminal-local-map company-my-keymap)
432     (setq overriding-terminal-local-map company-old-keymap
433           company-overriding-keymap-bound nil)))
434
435 ;; Hack:
436 ;; Emacs calculates the active keymaps before reading the event.  That means we
437 ;; cannot change the keymap from a timer.  So we send a bogus command.
438 (defun company-ignore ()
439   (interactive))
440
441 (global-set-key '[31415926] 'company-ignore)
442
443 (defun company-input-noop ()
444   (push 31415926 unread-command-events))
445
446 ;;; backends ;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;
447
448 (defun company-grab (regexp &optional expression)
449   (when (looking-back regexp)
450     (or (match-string-no-properties (or expression 0)) "")))
451
452 (defun company-in-string-or-comment (&optional point)
453   (let ((pos (syntax-ppss)))
454     (or (nth 3 pos) (nth 4 pos) (nth 7 pos))))
455
456 ;;; completion mechanism ;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;
457
458 (defvar company-backend nil)
459 (make-variable-buffer-local 'company-backend)
460
461 (defvar company-prefix nil)
462 (make-variable-buffer-local 'company-prefix)
463
464 (defvar company-candidates nil)
465 (make-variable-buffer-local 'company-candidates)
466
467 (defvar company-candidates-length nil)
468 (make-variable-buffer-local 'company-candidates-length)
469
470 (defvar company-candidates-cache nil)
471 (make-variable-buffer-local 'company-candidates-cache)
472
473 (defvar company-candidates-predicate nil)
474 (make-variable-buffer-local 'company-candidates-predicate)
475
476 (defvar company-common nil)
477 (make-variable-buffer-local 'company-common)
478
479 (defvar company-selection 0)
480 (make-variable-buffer-local 'company-selection)
481
482 (defvar company-selection-changed nil)
483 (make-variable-buffer-local 'company-selection-changed)
484
485 (defvar company--explicit-action nil
486   "Non-nil, if explicit completion took place.")
487 (make-variable-buffer-local 'company--explicit-action)
488
489 (defvar company-point nil)
490 (make-variable-buffer-local 'company-point)
491
492 (defvar company-timer nil)
493
494 (defvar company-added-newline nil)
495 (make-variable-buffer-local 'company-added-newline)
496
497 (defsubst company-strip-prefix (str)
498   (substring str (length company-prefix)))
499
500 (defun company-explicit-action-p ()
501   "Return whether explicit completion action was taken by the user."
502   (or company--explicit-action
503       company-selection-changed))
504
505 (defsubst company-reformat (candidate)
506   ;; company-ispell needs this, because the results are always lower-case
507   ;; It's mory efficient to fix it only when they are displayed.
508   (concat company-prefix (substring candidate (length company-prefix))))
509
510 (defsubst company-should-complete (prefix)
511   (and (eq company-idle-delay t)
512        (>= (length prefix) company-minimum-prefix-length)))
513
514 (defsubst company-call-frontends (command)
515   (dolist (frontend company-frontends)
516     (condition-case err
517         (funcall frontend command)
518       (error (error "Company: Front-end %s error \"%s\" on command %s"
519                     frontend (error-message-string err) command)))))
520
521 (defsubst company-set-selection (selection &optional force-update)
522   (setq selection (max 0 (min (1- company-candidates-length) selection)))
523   (when (or force-update (not (equal selection company-selection)))
524     (setq company-selection selection
525           company-selection-changed t)
526     (company-call-frontends 'update)))
527
528 (defun company-apply-predicate (candidates predicate)
529   (let (new)
530     (dolist (c candidates)
531       (when (funcall predicate c)
532         (push c new)))
533     (nreverse new)))
534
535 (defun company-update-candidates (candidates)
536   (setq company-candidates-length (length candidates))
537   (if (> company-selection 0)
538       ;; Try to restore the selection
539       (let ((selected (nth company-selection company-candidates)))
540         (setq company-selection 0
541               company-candidates candidates)
542         (when selected
543           (while (and candidates (string< (pop candidates) selected))
544             (incf company-selection))
545           (unless candidates
546             ;; Make sure selection isn't out of bounds.
547             (setq company-selection (min (1- company-candidates-length)
548                                          company-selection)))))
549     (setq company-selection 0
550           company-candidates candidates))
551   ;; Save in cache:
552   (push (cons company-prefix company-candidates) company-candidates-cache)
553   ;; Calculate common.
554   (let ((completion-ignore-case (funcall company-backend 'ignore-case)))
555     (setq company-common (try-completion company-prefix company-candidates)))
556   (when (eq company-common t)
557     (setq company-candidates nil)))
558
559 (defun company-calculate-candidates (prefix)
560   (let ((candidates
561          (or (cdr (assoc prefix company-candidates-cache))
562              (when company-candidates-cache
563                (let ((len (length prefix))
564                      (completion-ignore-case (funcall company-backend
565                                                       'ignore-case))
566                      prev)
567                  (dotimes (i len)
568                    (when (setq prev (cdr (assoc (substring prefix 0 (- len i))
569                                                 company-candidates-cache)))
570                      (return (all-completions prefix prev))))))
571              (let ((c (funcall company-backend 'candidates prefix)))
572                (when company-candidates-predicate
573                  (setq c (company-apply-predicate
574                           c company-candidates-predicate)))
575                (unless (funcall company-backend 'sorted)
576                  (setq c (sort c 'string<)))
577                c))))
578     (if (or (cdr candidates)
579             (not (equal (car candidates) prefix)))
580         ;; Don't start when already completed and unique.
581         candidates
582       ;; Not the right place? maybe when setting?
583       (and company-candidates t))))
584
585 (defun company-idle-begin (buf win tick pos)
586   (and company-mode
587        (eq buf (current-buffer))
588        (eq win (selected-window))
589        (eq tick (buffer-chars-modified-tick))
590        (eq pos (point))
591        (not company-candidates)
592        (not (equal (point) company-point))
593        (let ((company-idle-delay t))
594          (company-begin)
595          (when company-candidates
596            (company-input-noop)
597            (company-post-command)))))
598
599 (defun company-manual-begin ()
600   (interactive)
601   (company-assert-enabled)
602   (and company-mode
603        (not company-candidates)
604        (let ((company-idle-delay t)
605              (company-minimum-prefix-length 0))
606          (setq company--explicit-action t)
607          (company-begin)))
608   ;; Return non-nil if active.
609   company-candidates)
610
611 (defsubst company-incremental-p (old-prefix new-prefix)
612   (and (> (length new-prefix) (length old-prefix))
613        (equal old-prefix (substring new-prefix 0 (length old-prefix)))))
614
615 (defun company-require-match-p ()
616   (let ((backend-value (funcall company-backend 'require-match)))
617     (or (eq backend-value t)
618         (and (if (functionp company-require-match)
619                  (funcall company-require-match)
620                (eq company-require-match t))
621              (not (eq backend-value 'never))))))
622
623 (defun company-continue ()
624   (when company-candidates
625     (when (funcall company-backend 'no-cache company-prefix)
626       ;; Don't complete existing candidates, fetch new ones.
627       (setq company-candidates-cache nil))
628     (let ((new-prefix (funcall company-backend 'prefix)))
629       (unless (and (= (- (point) (length new-prefix))
630                       (- company-point (length company-prefix)))
631                    (or (equal company-prefix new-prefix)
632                        (let ((c (company-calculate-candidates new-prefix)))
633                          ;; t means complete/unique.
634                          (if (eq c t)
635                              (progn (company-cancel new-prefix) t)
636                            (when (consp c)
637                              (setq company-prefix new-prefix)
638                              (company-update-candidates c)
639                              t)))))
640         (if (not (and (company-incremental-p company-prefix new-prefix)
641                       (company-require-match-p)))
642             (progn
643               (when (equal company-prefix (car company-candidates))
644                 ;; cancel, but last input was actually success
645                 (company-cancel company-prefix))
646               (setq company-candidates nil))
647           (backward-delete-char (length new-prefix))
648           (insert company-prefix)
649           (ding)
650           (message "Matching input is required")
651           company-candidates)))))
652
653 (defun company-begin ()
654   (if (or buffer-read-only overriding-terminal-local-map overriding-local-map)
655       ;; Don't complete in these cases.
656       (setq company-candidates nil)
657     (company-continue)
658     (unless company-candidates
659       (let (prefix)
660         (dolist (backend company-backends)
661           (when (and (fboundp backend)
662                      (setq prefix (funcall backend 'prefix)))
663             (setq company-backend backend)
664             (when (company-should-complete prefix)
665               (let ((c (company-calculate-candidates prefix)))
666                 ;; t means complete/unique.  We don't start, so no hooks.
667                 (when (consp c)
668                   (setq company-prefix prefix)
669                   (company-update-candidates c)
670                   (run-hook-with-args 'company-completion-started-hook
671                                       (company-explicit-action-p))
672                   (company-call-frontends 'show))))
673             (return prefix))))))
674   (if company-candidates
675       (progn
676         (when (and company-end-of-buffer-workaround (eobp))
677           (save-excursion (insert "\n"))
678           (setq company-added-newline (buffer-chars-modified-tick)))
679         (setq company-point (point))
680         (company-enable-overriding-keymap company-active-map)
681         (company-call-frontends 'update))
682     (company-cancel)))
683
684 (defun company-cancel (&optional result)
685   (and company-added-newline
686        (> (point-max) (point-min))
687        (let ((tick (buffer-chars-modified-tick)))
688          (delete-region (1- (point-max)) (point-max))
689          (equal tick company-added-newline))
690        ;; Only set unmodified when tick remained the same since insert.
691        (set-buffer-modified-p nil))
692   (when company-prefix
693     (if (stringp result)
694         (run-hook-with-args 'company-completion-finished-hook result)
695       (run-hook-with-args 'company-completion-cancelled-hook result)))
696   (setq company-added-newline nil
697         company-backend nil
698         company-prefix nil
699         company-candidates nil
700         company-candidates-length nil
701         company-candidates-cache nil
702         company-candidates-predicate nil
703         company-common nil
704         company-selection 0
705         company-selection-changed nil
706         company--explicit-action nil
707         company-point nil)
708   (when company-timer
709     (cancel-timer company-timer))
710   (company-search-mode 0)
711   (company-call-frontends 'hide)
712   (company-enable-overriding-keymap nil))
713
714 (defun company-abort ()
715   (company-cancel t)
716   ;; Don't start again, unless started manually.
717   (setq company-point (point)))
718
719 (defun company-finish (result)
720   (insert (company-strip-prefix result))
721   (company-cancel result)
722   ;; Don't start again, unless started manually.
723   (setq company-point (point)))
724
725 (defsubst company-keep (command)
726   (and (symbolp command) (get command 'company-keep)))
727
728 (defun company-pre-command ()
729   (unless (company-keep this-command)
730     (condition-case err
731         (when company-candidates
732           (company-call-frontends 'pre-command))
733       (error (message "Company: An error occurred in pre-command")
734              (message "%s" (error-message-string err))
735              (company-cancel))))
736   (when company-timer
737     (cancel-timer company-timer))
738   (company-uninstall-map))
739
740 (defun company-post-command ()
741   (unless (company-keep this-command)
742     (condition-case err
743         (progn
744           (unless (equal (point) company-point)
745             (company-begin))
746           (when company-candidates
747             (company-call-frontends 'post-command))
748           (when (numberp company-idle-delay)
749             (setq company-timer
750                   (run-with-timer company-idle-delay nil 'company-idle-begin
751                                   (current-buffer) (selected-window)
752                                   (buffer-chars-modified-tick) (point)))))
753       (error (message "Company: An error occurred in post-command")
754              (message "%s" (error-message-string err))
755              (company-cancel))))
756   (company-install-map))
757
758 ;;; search ;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;
759
760 (defvar company-search-string nil)
761 (make-variable-buffer-local 'company-search-string)
762
763 (defvar company-search-lighter " Search: \"\"")
764 (make-variable-buffer-local 'company-search-lighter)
765
766 (defvar company-search-old-map nil)
767 (make-variable-buffer-local 'company-search-old-map)
768
769 (defvar company-search-old-selection 0)
770 (make-variable-buffer-local 'company-search-old-selection)
771
772 (defun company-search (text lines)
773   (let ((quoted (regexp-quote text))
774         (i 0))
775     (dolist (line lines)
776       (when (string-match quoted line (length company-prefix))
777         (return i))
778       (incf i))))
779
780 (defun company-search-printing-char ()
781   (interactive)
782   (company-search-assert-enabled)
783   (setq company-search-string
784         (concat (or company-search-string "") (string last-command-event))
785         company-search-lighter (concat " Search: \"" company-search-string
786                                         "\""))
787   (let ((pos (company-search company-search-string
788                               (nthcdr company-selection company-candidates))))
789     (if (null pos)
790         (ding)
791       (company-set-selection (+ company-selection pos) t))))
792
793 (defun company-search-repeat-forward ()
794   "Repeat the incremental search in completion candidates forward."
795   (interactive)
796   (company-search-assert-enabled)
797   (let ((pos (company-search company-search-string
798                               (cdr (nthcdr company-selection
799                                            company-candidates)))))
800     (if (null pos)
801         (ding)
802       (company-set-selection (+ company-selection pos 1) t))))
803
804 (defun company-search-repeat-backward ()
805   "Repeat the incremental search in completion candidates backwards."
806   (interactive)
807   (company-search-assert-enabled)
808   (let ((pos (company-search company-search-string
809                               (nthcdr (- company-candidates-length
810                                          company-selection)
811                                       (reverse company-candidates)))))
812     (if (null pos)
813         (ding)
814       (company-set-selection (- company-selection pos 1) t))))
815
816 (defun company-create-match-predicate ()
817   (setq company-candidates-predicate
818         `(lambda (candidate)
819            ,(if company-candidates-predicate
820                 `(and (string-match ,company-search-string candidate)
821                       (funcall ,company-candidates-predicate
822                                candidate))
823               `(string-match ,company-search-string candidate))))
824   (company-update-candidates
825    (company-apply-predicate company-candidates company-candidates-predicate))
826   ;; Invalidate cache.
827   (setq company-candidates-cache (cons company-prefix company-candidates)))
828
829 (defun company-filter-printing-char ()
830   (interactive)
831   (company-search-assert-enabled)
832   (company-search-printing-char)
833   (company-create-match-predicate)
834   (company-call-frontends 'update))
835
836 (defun company-search-kill-others ()
837   "Limit the completion candidates to the ones matching the search string."
838   (interactive)
839   (company-search-assert-enabled)
840   (company-create-match-predicate)
841   (company-search-mode 0)
842   (company-call-frontends 'update))
843
844 (defun company-search-abort ()
845   "Abort searching the completion candidates."
846   (interactive)
847   (company-search-assert-enabled)
848   (company-set-selection company-search-old-selection t)
849   (company-search-mode 0))
850
851 (defun company-search-other-char ()
852   (interactive)
853   (company-search-assert-enabled)
854   (company-search-mode 0)
855   (when last-input-event
856     (clear-this-command-keys t)
857     (setq unread-command-events (list last-input-event))))
858
859 (defvar company-search-map
860   (let ((i 0)
861         (keymap (make-keymap)))
862     (if (fboundp 'max-char)
863         (set-char-table-range (nth 1 keymap) (cons #x100 (max-char))
864                               'company-search-printing-char)
865       (with-no-warnings
866         ;; obselete in Emacs 23
867         (let ((l (generic-character-list))
868               (table (nth 1 keymap)))
869           (while l
870             (set-char-table-default table (car l) 'company-search-printing-char)
871             (setq l (cdr l))))))
872     (define-key keymap [t] 'company-search-other-char)
873     (while (< i ?\s)
874       (define-key keymap (make-string 1 i) 'company-search-other-char)
875       (incf i))
876     (while (< i 256)
877       (define-key keymap (vector i) 'company-search-printing-char)
878       (incf i))
879     (let ((meta-map (make-sparse-keymap)))
880       (define-key keymap (char-to-string meta-prefix-char) meta-map)
881       (define-key keymap [escape] meta-map))
882     (define-key keymap (vector meta-prefix-char t) 'company-search-other-char)
883     (define-key keymap "\e\e\e" 'company-search-other-char)
884     (define-key keymap  [escape escape escape] 'company-search-other-char)
885
886     (define-key keymap "\C-g" 'company-search-abort)
887     (define-key keymap "\C-s" 'company-search-repeat-forward)
888     (define-key keymap "\C-r" 'company-search-repeat-backward)
889     (define-key keymap "\C-o" 'company-search-kill-others)
890     keymap)
891   "Keymap used for incrementally searching the completion candidates.")
892
893 (define-minor-mode company-search-mode
894   "Search mode for completion candidates.
895 Don't start this directly, use `company-search-candidates' or
896 `company-filter-candidates'."
897   nil company-search-lighter nil
898   (if company-search-mode
899       (if (company-manual-begin)
900           (progn
901             (setq company-search-old-selection company-selection)
902             (company-call-frontends 'update))
903         (setq company-search-mode nil))
904     (kill-local-variable 'company-search-string)
905     (kill-local-variable 'company-search-lighter)
906     (kill-local-variable 'company-search-old-selection)
907     (company-enable-overriding-keymap company-active-map)))
908
909 (defsubst company-search-assert-enabled ()
910   (company-assert-enabled)
911   (unless company-search-mode
912     (company-uninstall-map)
913     (error "Company not in search mode")))
914
915 (defun company-search-candidates ()
916   "Start searching the completion candidates incrementally.
917
918 \\<company-search-map>Search can be controlled with the commands:
919 - `company-search-repeat-forward' (\\[company-search-repeat-forward])
920 - `company-search-repeat-backward' (\\[company-search-repeat-backward])
921 - `company-search-abort' (\\[company-search-abort])
922
923 Regular characters are appended to the search string.
924
925 The command `company-search-kill-others' (\\[company-search-kill-others]) uses
926  the search string to limit the completion candidates."
927   (interactive)
928   (company-search-mode 1)
929   (company-enable-overriding-keymap company-search-map))
930
931 (defvar company-filter-map
932   (let ((keymap (make-keymap)))
933     (define-key keymap [remap company-search-printing-char]
934       'company-filter-printing-char)
935     (set-keymap-parent keymap company-search-map)
936     keymap)
937   "Keymap used for incrementally searching the completion candidates.")
938
939 (defun company-filter-candidates ()
940   "Start filtering the completion candidates incrementally.
941 This works the same way as `company-search-candidates' immediately
942 followed by `company-search-kill-others' after each input."
943   (interactive)
944   (company-search-mode 1)
945   (company-enable-overriding-keymap company-filter-map))
946
947 ;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;
948
949 (defun company-select-next ()
950   "Select the next candidate in the list."
951   (interactive)
952   (when (company-manual-begin)
953     (company-set-selection (1+ company-selection))))
954
955 (defun company-select-previous ()
956   "Select the previous candidate in the list."
957   (interactive)
958   (when (company-manual-begin)
959     (company-set-selection (1- company-selection))))
960
961 (defun company-select-mouse (event)
962   "Select the candidate picked by the mouse."
963   (interactive "e")
964   (when (nth 4 (event-start event))
965     (company-set-selection (- (cdr (posn-col-row (event-start event)))
966                               (cdr (posn-col-row (posn-at-point)))
967                               1))
968     t))
969
970 (defun company-complete-mouse (event)
971   "Complete the candidate picked by the mouse."
972   (interactive "e")
973   (when (company-select-mouse event)
974     (company-complete-selection)))
975
976 (defun company-complete-selection ()
977   "Complete the selected candidate."
978   (interactive)
979   (when (company-manual-begin)
980     (company-finish (nth company-selection company-candidates))))
981
982 (defun company-complete-common ()
983   "Complete the common part of all candidates."
984   (interactive)
985   (when (company-manual-begin)
986     (if (equal company-common (car company-candidates))
987         ;; for success message
988         (company-complete-selection)
989       (insert (company-strip-prefix company-common)))))
990
991 (defun company-complete ()
992   "Complete the common part of all candidates or the current selection.
993 The first time this is called, the common part is completed, the second time, or
994 when the selection has been changed, the selected candidate is completed."
995   (interactive)
996   (when (company-manual-begin)
997     (if (or company-selection-changed
998             (eq last-command 'company-complete-common))
999         (call-interactively 'company-complete-selection)
1000       (call-interactively 'company-complete-common)
1001       (setq this-command 'company-complete-common))))
1002
1003 (defun company-complete-number (n)
1004   "Complete the Nth candidate."
1005   (when (company-manual-begin)
1006     (and (< n 1) (> n company-candidates-length)
1007          (error "No candidate number %d" n))
1008     (decf n)
1009     (company-finish (nth n company-candidates))))
1010
1011 ;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;
1012
1013 (defconst company-space-strings-limit 100)
1014
1015 (defconst company-space-strings
1016   (let (lst)
1017     (dotimes (i company-space-strings-limit)
1018       (push (make-string (- company-space-strings-limit 1 i) ?\  ) lst))
1019     (apply 'vector lst)))
1020
1021 (defsubst company-space-string (len)
1022   (if (< len company-space-strings-limit)
1023       (aref company-space-strings len)
1024     (make-string len ?\ )))
1025
1026 (defsubst company-safe-substring (str from &optional to)
1027   (let ((len (length str)))
1028     (if (> from len)
1029         ""
1030       (if (and to (> to len))
1031           (concat (substring str from)
1032                   (company-space-string (- to len)))
1033         (substring str from to)))))
1034
1035 ;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;
1036
1037 (defvar company-last-metadata nil)
1038 (make-variable-buffer-local 'company-last-metadata)
1039
1040 (defun company-fetch-metadata ()
1041   (let ((selected (nth company-selection company-candidates)))
1042     (unless (equal selected (car company-last-metadata))
1043       (setq company-last-metadata
1044             (cons selected (funcall company-backend 'meta selected))))
1045     (cdr company-last-metadata)))
1046
1047 (defun company-doc-buffer (&optional string)
1048   (with-current-buffer (get-buffer-create "*Company meta-data*")
1049     (erase-buffer)
1050     (current-buffer)))
1051
1052 (defmacro company-electric (&rest body)
1053   (declare (indent 0) (debug t))
1054   `(when (company-manual-begin)
1055      (save-window-excursion
1056        (let ((height (window-height))
1057              (row (cdr (posn-col-row (posn-at-point)))))
1058          ,@body
1059          (and (< (window-height) height)
1060               (< (- (window-height) row 2) company-tooltip-limit)
1061               (recenter (- (window-height) row 2)))
1062          (while (eq 'scroll-other-window
1063                     (key-binding (vector (list (read-event)))))
1064            (call-interactively 'scroll-other-window))
1065          (when last-input-event
1066            (clear-this-command-keys t)
1067            (setq unread-command-events (list last-input-event)))))))
1068
1069 (defun company-show-doc-buffer ()
1070   "Temporarily show a buffer with the complete documentation for the selection."
1071   (interactive)
1072   (company-electric
1073     (let ((selected (nth company-selection company-candidates)))
1074       (display-buffer (or (funcall company-backend 'doc-buffer selected)
1075                           (error "No documentation available")) t))))
1076 (put 'company-show-doc-buffer 'company-keep t)
1077
1078 (defun company-show-location ()
1079   "Temporarily display a buffer showing the selected candidate in context."
1080   (interactive)
1081   (company-electric
1082     (let* ((selected (nth company-selection company-candidates))
1083            (location (funcall company-backend 'location selected))
1084            (pos (or (cdr location) (error "No location available")))
1085            (buffer (or (and (bufferp (car location)) (car location))
1086                        (find-file-noselect (car location) t))))
1087       (with-selected-window (display-buffer buffer t)
1088         (if (bufferp (car location))
1089             (goto-char pos)
1090           (goto-line pos))
1091         (set-window-start nil (point))))))
1092 (put 'company-show-location 'company-keep t)
1093
1094 ;;; pseudo-tooltip ;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;
1095
1096 (defvar company-pseudo-tooltip-overlay nil)
1097 (make-variable-buffer-local 'company-pseudo-tooltip-overlay)
1098
1099 (defvar company-tooltip-offset 0)
1100 (make-variable-buffer-local 'company-tooltip-offset)
1101
1102 (defun company-pseudo-tooltip-update-offset (selection num-lines limit)
1103
1104   (decf limit 2)
1105   (setq company-tooltip-offset
1106         (max (min selection company-tooltip-offset)
1107              (- selection -1 limit)))
1108
1109   (when (<= company-tooltip-offset 1)
1110     (incf limit)
1111     (setq company-tooltip-offset 0))
1112
1113   (when (>= company-tooltip-offset (- num-lines limit 1))
1114     (incf limit)
1115     (when (= selection (1- num-lines))
1116       (decf company-tooltip-offset)
1117       (when (<= company-tooltip-offset 1)
1118         (setq company-tooltip-offset 0)
1119         (incf limit))))
1120
1121   limit)
1122
1123 ;;; propertize
1124
1125 (defsubst company-round-tab (arg)
1126   (* (/ (+ arg tab-width) tab-width) tab-width))
1127
1128 (defun company-untabify (str)
1129   (let* ((pieces (split-string str "\t"))
1130          (copy pieces))
1131     (while (cdr copy)
1132       (setcar copy (company-safe-substring
1133                     (car copy) 0 (company-round-tab (string-width (car copy)))))
1134       (pop copy))
1135     (apply 'concat pieces)))
1136
1137 (defun company-fill-propertize (line width selected)
1138   (setq line (company-safe-substring line 0 width))
1139   (add-text-properties 0 width '(face company-tooltip
1140                                  mouse-face company-tooltip-mouse)
1141                        line)
1142   (add-text-properties 0 (length company-common)
1143                        '(face company-tooltip-common
1144                          mouse-face company-tooltip-mouse)
1145                        line)
1146   (when selected
1147     (if (and company-search-string
1148              (string-match (regexp-quote company-search-string) line
1149                            (length company-prefix)))
1150         (progn
1151           (add-text-properties (match-beginning 0) (match-end 0)
1152                                '(face company-tooltip-selection)
1153                                line)
1154           (when (< (match-beginning 0) (length company-common))
1155             (add-text-properties (match-beginning 0) (length company-common)
1156                                  '(face company-tooltip-common-selection)
1157                                  line)))
1158       (add-text-properties 0 width '(face company-tooltip-selection
1159                                           mouse-face company-tooltip-selection)
1160                            line)
1161       (add-text-properties 0 (length company-common)
1162                            '(face company-tooltip-common-selection
1163                              mouse-face company-tooltip-selection)
1164                            line)))
1165   line)
1166
1167 ;;; replace
1168
1169 (defun company-buffer-lines (beg end)
1170   (goto-char beg)
1171   (let ((row (cdr (posn-col-row (posn-at-point))))
1172         lines)
1173     (while (and (equal (move-to-window-line (incf row)) row)
1174                 (<= (point) end))
1175       (push (buffer-substring beg (min end (1- (point)))) lines)
1176       (setq beg (point)))
1177     (unless (eq beg end)
1178       (push (buffer-substring beg end) lines))
1179     (nreverse lines)))
1180
1181 (defsubst company-modify-line (old new offset)
1182   (concat (company-safe-substring old 0 offset)
1183           new
1184           (company-safe-substring old (+ offset (length new)))))
1185
1186 (defun company-replacement-string (old lines column nl)
1187   (let (new)
1188     ;; Inject into old lines.
1189     (while old
1190       (push (company-modify-line (pop old) (pop lines) column) new))
1191     ;; Append whole new lines.
1192     (while lines
1193       (push (concat (company-space-string column) (pop lines)) new))
1194     (concat (when nl "\n")
1195             (mapconcat 'identity (nreverse new) "\n")
1196             "\n")))
1197
1198 (defun company-create-lines (column selection limit)
1199
1200   (let ((len company-candidates-length)
1201         (numbered 99999)
1202         lines
1203         width
1204         lines-copy
1205         previous
1206         remainder
1207         new)
1208
1209     ;; Scroll to offset.
1210     (setq limit (company-pseudo-tooltip-update-offset selection len limit))
1211
1212     (when (> company-tooltip-offset 0)
1213       (setq previous (format "...(%d)" company-tooltip-offset)))
1214
1215     (setq remainder (- len limit company-tooltip-offset)
1216           remainder (when (> remainder 0)
1217                       (setq remainder (format "...(%d)" remainder))))
1218
1219     (decf selection company-tooltip-offset)
1220     (setq width (min (length previous) (length remainder))
1221           lines (nthcdr company-tooltip-offset company-candidates)
1222           len (min limit len)
1223           lines-copy lines)
1224
1225     (dotimes (i len)
1226       (setq width (max (length (pop lines-copy)) width)))
1227     (setq width (min width (- (window-width) column)))
1228
1229     (setq lines-copy lines)
1230
1231     ;; number can make tooltip too long
1232     (and company-show-numbers
1233          (< (setq numbered company-tooltip-offset) 10)
1234          (incf width 2))
1235
1236     (when previous
1237       (push (propertize (company-safe-substring previous 0 width)
1238                         'face 'company-tooltip)
1239             new))
1240
1241     (dotimes (i len)
1242       (push (company-fill-propertize
1243              (if (>= numbered 10)
1244                  (company-reformat (pop lines))
1245                (incf numbered)
1246                (format "%s %d"
1247                        (company-safe-substring (company-reformat (pop lines))
1248                                                0 (- width 2))
1249                        (mod numbered 10)))
1250              width (equal i selection))
1251             new))
1252
1253     (when remainder
1254       (push (propertize (company-safe-substring remainder 0 width)
1255                         'face 'company-tooltip)
1256             new))
1257
1258     (setq lines (nreverse new))))
1259
1260 ;; show
1261
1262 (defsubst company-pseudo-tooltip-height ()
1263   "Calculate the appropriate tooltip height."
1264   (max 3 (min company-tooltip-limit
1265               (- (window-height) 2
1266                  (count-lines (window-start) (point-at-bol))))))
1267
1268 (defun company-pseudo-tooltip-show (row column selection)
1269   (company-pseudo-tooltip-hide)
1270   (save-excursion
1271
1272     (move-to-column 0)
1273
1274     (let* ((height (company-pseudo-tooltip-height))
1275            (lines (company-create-lines column selection height))
1276            (nl (< (move-to-window-line row) row))
1277            (beg (point))
1278            (end (save-excursion
1279                   (move-to-window-line (+ row height))
1280                   (point)))
1281            (old-string
1282             (mapcar 'company-untabify (company-buffer-lines beg end)))
1283            str)
1284
1285       (setq company-pseudo-tooltip-overlay (make-overlay beg end))
1286
1287       (overlay-put company-pseudo-tooltip-overlay 'company-old old-string)
1288       (overlay-put company-pseudo-tooltip-overlay 'company-column column)
1289       (overlay-put company-pseudo-tooltip-overlay 'company-nl nl)
1290       (overlay-put company-pseudo-tooltip-overlay 'company-before
1291                    (company-replacement-string old-string lines column nl))
1292       (overlay-put company-pseudo-tooltip-overlay 'company-height height)
1293
1294       (overlay-put company-pseudo-tooltip-overlay 'window (selected-window)))))
1295
1296 (defun company-pseudo-tooltip-show-at-point (pos)
1297   (let ((col-row (posn-col-row (posn-at-point pos))))
1298     (company-pseudo-tooltip-show (1+ (cdr col-row)) (car col-row) company-selection)))
1299
1300 (defun company-pseudo-tooltip-edit (lines selection)
1301   (let* ((old-string (overlay-get company-pseudo-tooltip-overlay 'company-old))
1302          (column (overlay-get company-pseudo-tooltip-overlay 'company-column))
1303          (nl (overlay-get company-pseudo-tooltip-overlay 'company-nl))
1304          (height (overlay-get company-pseudo-tooltip-overlay 'company-height))
1305          (lines (company-create-lines column selection height)))
1306     (overlay-put company-pseudo-tooltip-overlay 'company-before
1307                  (company-replacement-string old-string lines column nl))))
1308
1309 (defun company-pseudo-tooltip-hide ()
1310   (when company-pseudo-tooltip-overlay
1311     (delete-overlay company-pseudo-tooltip-overlay)
1312     (setq company-pseudo-tooltip-overlay nil)))
1313
1314 (defun company-pseudo-tooltip-hide-temporarily ()
1315   (when (overlayp company-pseudo-tooltip-overlay)
1316     (overlay-put company-pseudo-tooltip-overlay 'invisible nil)
1317     (overlay-put company-pseudo-tooltip-overlay 'before-string nil)))
1318
1319 (defun company-pseudo-tooltip-unhide ()
1320   (when company-pseudo-tooltip-overlay
1321     (overlay-put company-pseudo-tooltip-overlay 'invisible t)
1322     (overlay-put company-pseudo-tooltip-overlay 'before-string
1323                  (overlay-get company-pseudo-tooltip-overlay 'company-before))
1324     (overlay-put company-pseudo-tooltip-overlay 'window (selected-window))))
1325
1326 (defun company-pseudo-tooltip-frontend (command)
1327   "A `company-mode' front-end similar to a tool-tip but based on overlays."
1328   (case command
1329     ('pre-command (company-pseudo-tooltip-hide-temporarily))
1330     ('post-command
1331      (unless (and (overlayp company-pseudo-tooltip-overlay)
1332                   (equal (overlay-get company-pseudo-tooltip-overlay
1333                                       'company-height)
1334                          (company-pseudo-tooltip-height)))
1335        ;; Redraw needed.
1336        (company-pseudo-tooltip-show-at-point (- (point)
1337                                                 (length company-prefix))))
1338      (company-pseudo-tooltip-unhide))
1339     ('hide (company-pseudo-tooltip-hide)
1340            (setq company-tooltip-offset 0))
1341     ('update (when (overlayp company-pseudo-tooltip-overlay)
1342                (company-pseudo-tooltip-edit company-candidates
1343                                             company-selection)))))
1344
1345 (defun company-pseudo-tooltip-unless-just-one-frontend (command)
1346   "`company-pseudo-tooltip-frontend', but not shown for single candidates."
1347   (unless (and (eq command 'post-command)
1348                (not (cdr company-candidates)))
1349     (company-pseudo-tooltip-frontend command)))
1350
1351 ;;; overlay ;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;
1352
1353 (defvar company-preview-overlay nil)
1354 (make-variable-buffer-local 'company-preview-overlay)
1355
1356 (defun company-preview-show-at-point (pos)
1357   (company-preview-hide)
1358
1359   (setq company-preview-overlay (make-overlay pos pos))
1360
1361   (let ((completion(nth company-selection company-candidates)))
1362     (setq completion (propertize completion 'face 'company-preview))
1363     (add-text-properties 0 (length company-common)
1364                          '(face company-preview-common) completion)
1365
1366     ;; Add search string
1367     (and company-search-string
1368          (string-match (regexp-quote company-search-string) completion)
1369          (add-text-properties (match-beginning 0)
1370                               (match-end 0)
1371                               '(face company-preview-search)
1372                               completion))
1373
1374     (setq completion (company-strip-prefix completion))
1375
1376     (and (equal pos (point))
1377          (not (equal completion ""))
1378          (add-text-properties 0 1 '(cursor t) completion))
1379
1380     (overlay-put company-preview-overlay 'after-string completion)
1381     (overlay-put company-preview-overlay 'window (selected-window))))
1382
1383 (defun company-preview-hide ()
1384   (when company-preview-overlay
1385     (delete-overlay company-preview-overlay)
1386     (setq company-preview-overlay nil)))
1387
1388 (defun company-preview-frontend (command)
1389   "A `company-mode' front-end showing the selection as if it had been inserted."
1390   (case command
1391     ('pre-command (company-preview-hide))
1392     ('post-command (company-preview-show-at-point (point)))
1393     ('hide (company-preview-hide))))
1394
1395 (defun company-preview-if-just-one-frontend (command)
1396   "`company-preview-frontend', but only shown for single candidates."
1397   (unless (and (eq command 'post-command)
1398                (cdr company-candidates))
1399     (company-preview-frontend command)))
1400
1401 ;;; echo ;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;
1402
1403 (defvar company-echo-last-msg nil)
1404 (make-variable-buffer-local 'company-echo-last-msg)
1405
1406 (defvar company-echo-timer nil)
1407
1408 (defvar company-echo-delay .1)
1409
1410 (defun company-echo-show (&optional getter)
1411   (when getter
1412     (setq company-echo-last-msg (funcall getter)))
1413   (let ((message-log-max nil))
1414     (if company-echo-last-msg
1415         (message "%s" company-echo-last-msg)
1416       (message ""))))
1417
1418 (defsubst company-echo-show-soon (&optional getter)
1419   (when company-echo-timer
1420     (cancel-timer company-echo-timer))
1421   (setq company-echo-timer (run-with-timer company-echo-delay nil
1422                                            'company-echo-show getter)))
1423
1424 (defun company-echo-format ()
1425
1426   (let ((limit (window-width (minibuffer-window)))
1427         (len -1)
1428         ;; Roll to selection.
1429         (candidates (nthcdr company-selection company-candidates))
1430         (i (if company-show-numbers company-selection 99999))
1431         comp msg)
1432
1433     (while candidates
1434       (setq comp (company-reformat (pop candidates))
1435             len (+ len 1 (length comp)))
1436       (if (< i 10)
1437           ;; Add number.
1438           (progn
1439             (setq comp (propertize (format "%d: %s" i comp)
1440                                    'face 'company-echo))
1441             (incf len 3)
1442             (incf i)
1443             (add-text-properties 3 (+ 3 (length company-common))
1444                                  '(face company-echo-common) comp))
1445         (setq comp (propertize comp 'face 'company-echo))
1446         (add-text-properties 0 (length company-common)
1447                              '(face company-echo-common) comp))
1448       (if (>= len limit)
1449           (setq candidates nil)
1450         (push comp msg)))
1451
1452     (mapconcat 'identity (nreverse msg) " ")))
1453
1454 (defun company-echo-strip-common-format ()
1455
1456   (let ((limit (window-width (minibuffer-window)))
1457         (len (+ (length company-prefix) 2))
1458         ;; Roll to selection.
1459         (candidates (nthcdr company-selection company-candidates))
1460         (i (if company-show-numbers company-selection 99999))
1461         msg comp)
1462
1463     (while candidates
1464       (setq comp (company-strip-prefix (pop candidates))
1465             len (+ len 2 (length comp)))
1466       (when (< i 10)
1467         ;; Add number.
1468         (setq comp (format "%s (%d)" comp i))
1469         (incf len 4)
1470         (incf i))
1471       (if (>= len limit)
1472           (setq candidates nil)
1473         (push (propertize comp 'face 'company-echo) msg)))
1474
1475     (concat (propertize company-prefix 'face 'company-echo-common) "{"
1476             (mapconcat 'identity (nreverse msg) ", ")
1477             "}")))
1478
1479 (defun company-echo-hide ()
1480   (when company-echo-timer
1481     (cancel-timer company-echo-timer))
1482   (unless (equal company-echo-last-msg "")
1483     (setq company-echo-last-msg "")
1484     (company-echo-show)))
1485
1486 (defun company-echo-frontend (command)
1487   "A `company-mode' front-end showing the candidates in the echo area."
1488   (case command
1489     ('pre-command (company-echo-show-soon))
1490     ('post-command (company-echo-show-soon 'company-echo-format))
1491     ('hide (company-echo-hide))))
1492
1493 (defun company-echo-strip-common-frontend (command)
1494   "A `company-mode' front-end showing the candidates in the echo area."
1495   (case command
1496     ('pre-command (company-echo-show-soon))
1497     ('post-command (company-echo-show-soon 'company-echo-strip-common-format))
1498     ('hide (company-echo-hide))))
1499
1500 (defun company-echo-metadata-frontend (command)
1501   "A `company-mode' front-end showing the documentation in the echo area."
1502   (case command
1503     ('pre-command (company-echo-show-soon))
1504     ('post-command (company-echo-show-soon 'company-fetch-metadata))
1505     ('hide (company-echo-hide))))
1506
1507 (provide 'company)
1508 ;;; company.el ends here