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