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