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