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