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