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