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