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