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