]> code.delx.au - gnu-emacs-elpa/blob - company.el
Extracted company--begin-new.
[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-new ()
876 (let (prefix c)
877 (dolist (backend (if company-backend
878 ;; prefer manual override
879 (list company-backend)
880 company-backends))
881 (setq prefix
882 (if (or (symbolp backend)
883 (functionp backend))
884 (when (or (not (symbolp backend))
885 (get backend 'company-init))
886 (funcall backend 'prefix))
887 (company--multi-backend-adapter backend 'prefix)))
888 (when prefix
889 (when (and (stringp prefix)
890 (>= (length prefix) company-minimum-prefix-length))
891 (setq company-backend backend
892 company-prefix prefix
893 c (company-calculate-candidates prefix))
894 ;; t means complete/unique. We don't start, so no hooks.
895 (when (consp c)
896 (company-update-candidates c)
897 (run-hook-with-args 'company-completion-started-hook
898 (company-explicit-action-p))
899 (company-call-frontends 'show)))
900 (return c)))))
901
902 (defun company-begin ()
903 (setq company-candidates
904 (or (and company-candidates (company--continue))
905 (and (company--should-complete) (company--begin-new))))
906 (if company-candidates
907 (progn
908 (when (and company-end-of-buffer-workaround (eobp))
909 (save-excursion (insert "\n"))
910 (setq company-added-newline (buffer-chars-modified-tick)))
911 (setq company-point (point)
912 company--point-max (point-max))
913 (company-enable-overriding-keymap company-active-map)
914 (company-call-frontends 'update))
915 (company-cancel)))
916
917 (defun company-cancel (&optional result)
918 (and company-added-newline
919 (> (point-max) (point-min))
920 (let ((tick (buffer-chars-modified-tick)))
921 (delete-region (1- (point-max)) (point-max))
922 (equal tick company-added-newline))
923 ;; Only set unmodified when tick remained the same since insert.
924 (set-buffer-modified-p nil))
925 (when company-prefix
926 (if (stringp result)
927 (run-hook-with-args 'company-completion-finished-hook result)
928 (run-hook-with-args 'company-completion-cancelled-hook result)))
929 (setq company-added-newline nil
930 company-backend nil
931 company-prefix nil
932 company-candidates nil
933 company-candidates-length nil
934 company-candidates-cache nil
935 company-candidates-predicate nil
936 company-common nil
937 company-selection 0
938 company-selection-changed nil
939 company--explicit-action nil
940 company--point-max nil
941 company-point nil)
942 (when company-timer
943 (cancel-timer company-timer))
944 (company-search-mode 0)
945 (company-call-frontends 'hide)
946 (company-enable-overriding-keymap nil))
947
948 (defun company-abort ()
949 (interactive)
950 (company-cancel t)
951 ;; Don't start again, unless started manually.
952 (setq company-point (point)))
953
954 (defun company-finish (result)
955 (insert (company-strip-prefix result))
956 (company-cancel result)
957 ;; Don't start again, unless started manually.
958 (setq company-point (point)))
959
960 (defsubst company-keep (command)
961 (and (symbolp command) (get command 'company-keep)))
962
963 (defun company-pre-command ()
964 (unless (company-keep this-command)
965 (condition-case err
966 (when company-candidates
967 (company-call-frontends 'pre-command))
968 (error (message "Company: An error occurred in pre-command")
969 (message "%s" (error-message-string err))
970 (company-cancel))))
971 (when company-timer
972 (cancel-timer company-timer))
973 (company-uninstall-map))
974
975 (defun company-post-command ()
976 (unless (company-keep this-command)
977 (condition-case err
978 (progn
979 (setq company--this-command this-command)
980 (unless (equal (point) company-point)
981 (company-begin))
982 (when company-candidates
983 (company-call-frontends 'post-command))
984 (when (numberp company-idle-delay)
985 (setq company-timer
986 (run-with-timer company-idle-delay nil 'company-idle-begin
987 (current-buffer) (selected-window)
988 (buffer-chars-modified-tick) (point)))))
989 (error (message "Company: An error occurred in post-command")
990 (message "%s" (error-message-string err))
991 (company-cancel))))
992 (company-install-map))
993
994 ;;; search ;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;
995
996 (defvar company-search-string nil)
997 (make-variable-buffer-local 'company-search-string)
998
999 (defvar company-search-lighter " Search: \"\"")
1000 (make-variable-buffer-local 'company-search-lighter)
1001
1002 (defvar company-search-old-map nil)
1003 (make-variable-buffer-local 'company-search-old-map)
1004
1005 (defvar company-search-old-selection 0)
1006 (make-variable-buffer-local 'company-search-old-selection)
1007
1008 (defun company-search (text lines)
1009 (let ((quoted (regexp-quote text))
1010 (i 0))
1011 (dolist (line lines)
1012 (when (string-match quoted line (length company-prefix))
1013 (return i))
1014 (incf i))))
1015
1016 (defun company-search-printing-char ()
1017 (interactive)
1018 (company-search-assert-enabled)
1019 (setq company-search-string
1020 (concat (or company-search-string "") (string last-command-event))
1021 company-search-lighter (concat " Search: \"" company-search-string
1022 "\""))
1023 (let ((pos (company-search company-search-string
1024 (nthcdr company-selection company-candidates))))
1025 (if (null pos)
1026 (ding)
1027 (company-set-selection (+ company-selection pos) t))))
1028
1029 (defun company-search-repeat-forward ()
1030 "Repeat the incremental search in completion candidates forward."
1031 (interactive)
1032 (company-search-assert-enabled)
1033 (let ((pos (company-search company-search-string
1034 (cdr (nthcdr company-selection
1035 company-candidates)))))
1036 (if (null pos)
1037 (ding)
1038 (company-set-selection (+ company-selection pos 1) t))))
1039
1040 (defun company-search-repeat-backward ()
1041 "Repeat the incremental search in completion candidates backwards."
1042 (interactive)
1043 (company-search-assert-enabled)
1044 (let ((pos (company-search company-search-string
1045 (nthcdr (- company-candidates-length
1046 company-selection)
1047 (reverse company-candidates)))))
1048 (if (null pos)
1049 (ding)
1050 (company-set-selection (- company-selection pos 1) t))))
1051
1052 (defun company-create-match-predicate ()
1053 (setq company-candidates-predicate
1054 `(lambda (candidate)
1055 ,(if company-candidates-predicate
1056 `(and (string-match ,company-search-string candidate)
1057 (funcall ,company-candidates-predicate
1058 candidate))
1059 `(string-match ,company-search-string candidate))))
1060 (company-update-candidates
1061 (company-apply-predicate company-candidates company-candidates-predicate))
1062 ;; Invalidate cache.
1063 (setq company-candidates-cache (cons company-prefix company-candidates)))
1064
1065 (defun company-filter-printing-char ()
1066 (interactive)
1067 (company-search-assert-enabled)
1068 (company-search-printing-char)
1069 (company-create-match-predicate)
1070 (company-call-frontends 'update))
1071
1072 (defun company-search-kill-others ()
1073 "Limit the completion candidates to the ones matching the search string."
1074 (interactive)
1075 (company-search-assert-enabled)
1076 (company-create-match-predicate)
1077 (company-search-mode 0)
1078 (company-call-frontends 'update))
1079
1080 (defun company-search-abort ()
1081 "Abort searching the completion candidates."
1082 (interactive)
1083 (company-search-assert-enabled)
1084 (company-set-selection company-search-old-selection t)
1085 (company-search-mode 0))
1086
1087 (defun company-search-other-char ()
1088 (interactive)
1089 (company-search-assert-enabled)
1090 (company-search-mode 0)
1091 (when last-input-event
1092 (clear-this-command-keys t)
1093 (setq unread-command-events (list last-input-event))))
1094
1095 (defvar company-search-map
1096 (let ((i 0)
1097 (keymap (make-keymap)))
1098 (if (fboundp 'max-char)
1099 (set-char-table-range (nth 1 keymap) (cons #x100 (max-char))
1100 'company-search-printing-char)
1101 (with-no-warnings
1102 ;; obselete in Emacs 23
1103 (let ((l (generic-character-list))
1104 (table (nth 1 keymap)))
1105 (while l
1106 (set-char-table-default table (car l) 'company-search-printing-char)
1107 (setq l (cdr l))))))
1108 (define-key keymap [t] 'company-search-other-char)
1109 (while (< i ?\s)
1110 (define-key keymap (make-string 1 i) 'company-search-other-char)
1111 (incf i))
1112 (while (< i 256)
1113 (define-key keymap (vector i) 'company-search-printing-char)
1114 (incf i))
1115 (let ((meta-map (make-sparse-keymap)))
1116 (define-key keymap (char-to-string meta-prefix-char) meta-map)
1117 (define-key keymap [escape] meta-map))
1118 (define-key keymap (vector meta-prefix-char t) 'company-search-other-char)
1119 (define-key keymap "\e\e\e" 'company-search-other-char)
1120 (define-key keymap [escape escape escape] 'company-search-other-char)
1121
1122 (define-key keymap "\C-g" 'company-search-abort)
1123 (define-key keymap "\C-s" 'company-search-repeat-forward)
1124 (define-key keymap "\C-r" 'company-search-repeat-backward)
1125 (define-key keymap "\C-o" 'company-search-kill-others)
1126 keymap)
1127 "Keymap used for incrementally searching the completion candidates.")
1128
1129 (define-minor-mode company-search-mode
1130 "Search mode for completion candidates.
1131 Don't start this directly, use `company-search-candidates' or
1132 `company-filter-candidates'."
1133 nil company-search-lighter nil
1134 (if company-search-mode
1135 (if (company-manual-begin)
1136 (progn
1137 (setq company-search-old-selection company-selection)
1138 (company-call-frontends 'update))
1139 (setq company-search-mode nil))
1140 (kill-local-variable 'company-search-string)
1141 (kill-local-variable 'company-search-lighter)
1142 (kill-local-variable 'company-search-old-selection)
1143 (company-enable-overriding-keymap company-active-map)))
1144
1145 (defsubst company-search-assert-enabled ()
1146 (company-assert-enabled)
1147 (unless company-search-mode
1148 (company-uninstall-map)
1149 (error "Company not in search mode")))
1150
1151 (defun company-search-candidates ()
1152 "Start searching the completion candidates incrementally.
1153
1154 \\<company-search-map>Search can be controlled with the commands:
1155 - `company-search-repeat-forward' (\\[company-search-repeat-forward])
1156 - `company-search-repeat-backward' (\\[company-search-repeat-backward])
1157 - `company-search-abort' (\\[company-search-abort])
1158
1159 Regular characters are appended to the search string.
1160
1161 The command `company-search-kill-others' (\\[company-search-kill-others]) uses
1162 the search string to limit the completion candidates."
1163 (interactive)
1164 (company-search-mode 1)
1165 (company-enable-overriding-keymap company-search-map))
1166
1167 (defvar company-filter-map
1168 (let ((keymap (make-keymap)))
1169 (define-key keymap [remap company-search-printing-char]
1170 'company-filter-printing-char)
1171 (set-keymap-parent keymap company-search-map)
1172 keymap)
1173 "Keymap used for incrementally searching the completion candidates.")
1174
1175 (defun company-filter-candidates ()
1176 "Start filtering the completion candidates incrementally.
1177 This works the same way as `company-search-candidates' immediately
1178 followed by `company-search-kill-others' after each input."
1179 (interactive)
1180 (company-search-mode 1)
1181 (company-enable-overriding-keymap company-filter-map))
1182
1183 ;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;
1184
1185 (defun company-select-next ()
1186 "Select the next candidate in the list."
1187 (interactive)
1188 (when (company-manual-begin)
1189 (company-set-selection (1+ company-selection))))
1190
1191 (defun company-select-previous ()
1192 "Select the previous candidate in the list."
1193 (interactive)
1194 (when (company-manual-begin)
1195 (company-set-selection (1- company-selection))))
1196
1197 (defun company-select-mouse (event)
1198 "Select the candidate picked by the mouse."
1199 (interactive "e")
1200 (when (nth 4 (event-start event))
1201 (company-set-selection (- (cdr (posn-actual-col-row (event-start event)))
1202 (cdr (posn-actual-col-row (posn-at-point)))
1203 1))
1204 t))
1205
1206 (defun company-complete-mouse (event)
1207 "Complete the candidate picked by the mouse."
1208 (interactive "e")
1209 (when (company-select-mouse event)
1210 (company-complete-selection)))
1211
1212 (defun company-complete-selection ()
1213 "Complete the selected candidate."
1214 (interactive)
1215 (when (company-manual-begin)
1216 (company-finish (nth company-selection company-candidates))))
1217
1218 (defun company-complete-common ()
1219 "Complete the common part of all candidates."
1220 (interactive)
1221 (when (company-manual-begin)
1222 (if (and (not (cdr company-candidates))
1223 (equal company-common (car company-candidates)))
1224 (company-complete-selection)
1225 (insert (company-strip-prefix company-common)))))
1226
1227 (defun company-complete ()
1228 "Complete the common part of all candidates or the current selection.
1229 The first time this is called, the common part is completed, the second time, or
1230 when the selection has been changed, the selected candidate is completed."
1231 (interactive)
1232 (when (company-manual-begin)
1233 (if (or company-selection-changed
1234 (eq last-command 'company-complete-common))
1235 (call-interactively 'company-complete-selection)
1236 (call-interactively 'company-complete-common)
1237 (setq this-command 'company-complete-common))))
1238
1239 (defun company-complete-number (n)
1240 "Complete the Nth candidate.
1241 To show the number next to the candidates in some back-ends, enable
1242 `company-show-numbers'."
1243 (when (company-manual-begin)
1244 (and (< n 1) (> n company-candidates-length)
1245 (error "No candidate number %d" n))
1246 (decf n)
1247 (company-finish (nth n company-candidates))))
1248
1249 ;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;
1250
1251 (defconst company-space-strings-limit 100)
1252
1253 (defconst company-space-strings
1254 (let (lst)
1255 (dotimes (i company-space-strings-limit)
1256 (push (make-string (- company-space-strings-limit 1 i) ?\ ) lst))
1257 (apply 'vector lst)))
1258
1259 (defsubst company-space-string (len)
1260 (if (< len company-space-strings-limit)
1261 (aref company-space-strings len)
1262 (make-string len ?\ )))
1263
1264 (defsubst company-safe-substring (str from &optional to)
1265 (let ((len (length str)))
1266 (if (> from len)
1267 ""
1268 (if (and to (> to len))
1269 (concat (substring str from)
1270 (company-space-string (- to len)))
1271 (substring str from to)))))
1272
1273 ;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;
1274
1275 (defvar company-last-metadata nil)
1276 (make-variable-buffer-local 'company-last-metadata)
1277
1278 (defun company-fetch-metadata ()
1279 (let ((selected (nth company-selection company-candidates)))
1280 (unless (equal selected (car company-last-metadata))
1281 (setq company-last-metadata
1282 (cons selected (company-call-backend 'meta selected))))
1283 (cdr company-last-metadata)))
1284
1285 (defun company-doc-buffer (&optional string)
1286 (with-current-buffer (get-buffer-create "*Company meta-data*")
1287 (erase-buffer)
1288 (current-buffer)))
1289
1290 (defmacro company-electric (&rest body)
1291 (declare (indent 0) (debug t))
1292 `(when (company-manual-begin)
1293 (save-window-excursion
1294 (let ((height (window-height))
1295 (row (cdr (posn-actual-col-row (posn-at-point)))))
1296 ,@body
1297 (and (< (window-height) height)
1298 (< (- (window-height) row 2) company-tooltip-limit)
1299 (recenter (- (window-height) row 2)))
1300 (while (eq 'scroll-other-window
1301 (key-binding (vector (list (read-event)))))
1302 (call-interactively 'scroll-other-window))
1303 (when last-input-event
1304 (clear-this-command-keys t)
1305 (setq unread-command-events (list last-input-event)))))))
1306
1307 (defun company-show-doc-buffer ()
1308 "Temporarily show a buffer with the complete documentation for the selection."
1309 (interactive)
1310 (company-electric
1311 (let ((selected (nth company-selection company-candidates)))
1312 (display-buffer (or (company-call-backend 'doc-buffer selected)
1313 (error "No documentation available")) t))))
1314 (put 'company-show-doc-buffer 'company-keep t)
1315
1316 (defun company-show-location ()
1317 "Temporarily display a buffer showing the selected candidate in context."
1318 (interactive)
1319 (company-electric
1320 (let* ((selected (nth company-selection company-candidates))
1321 (location (company-call-backend 'location selected))
1322 (pos (or (cdr location) (error "No location available")))
1323 (buffer (or (and (bufferp (car location)) (car location))
1324 (find-file-noselect (car location) t))))
1325 (with-selected-window (display-buffer buffer t)
1326 (if (bufferp (car location))
1327 (goto-char pos)
1328 (goto-line pos))
1329 (set-window-start nil (point))))))
1330 (put 'company-show-location 'company-keep t)
1331
1332 ;;; package functions ;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;
1333
1334 (defvar company-callback nil)
1335 (make-variable-buffer-local 'company-callback)
1336
1337 (defvar company-begin-with-marker nil)
1338 (make-variable-buffer-local 'company-begin-with-marker)
1339
1340 (defun company-remove-callback (&optional ignored)
1341 (remove-hook 'company-completion-finished-hook company-callback t)
1342 (remove-hook 'company-completion-cancelled-hook 'company-remove-callback t)
1343 (remove-hook 'company-completion-finished-hook 'company-remove-callback t)
1344 (set-marker company-begin-with-marker nil))
1345
1346 (defun company-begin-backend (backend &optional callback)
1347 "Start a completion at point using BACKEND."
1348 (interactive (let ((val (completing-read "Company back-end: "
1349 obarray
1350 'functionp nil "company-")))
1351 (when val
1352 (list (intern val)))))
1353 (when (setq company-callback callback)
1354 (add-hook 'company-completion-finished-hook company-callback nil t))
1355 (add-hook 'company-completion-cancelled-hook 'company-remove-callback nil t)
1356 (add-hook 'company-completion-finished-hook 'company-remove-callback nil t)
1357 (setq company-backend backend)
1358 ;; Return non-nil if active.
1359 (or (company-manual-begin)
1360 (error "Cannot complete at point")))
1361
1362 (defun company-begin-with (candidates
1363 &optional prefix-length require-match callback)
1364 "Start a completion at point.
1365 CANDIDATES is the list of candidates to use and PREFIX-LENGTH is the length of
1366 the prefix that already is in the buffer before point. It defaults to 0.
1367
1368 CALLBACK is a function called with the selected result if the user successfully
1369 completes the input.
1370
1371 Example:
1372 \(company-begin-with '\(\"foo\" \"foobar\" \"foobarbaz\"\)\)"
1373 (setq company-begin-with-marker (copy-marker (point) t))
1374 (company-begin-backend
1375 `(lambda (command &optional arg &rest ignored)
1376 (cond
1377 ((eq command 'prefix)
1378 (when (equal (point) (marker-position company-begin-with-marker))
1379 (buffer-substring ,(- (point) (or prefix-length 0)) (point))))
1380 ((eq command 'candidates)
1381 (all-completions arg ',candidates))
1382 ((eq command 'require-match)
1383 ,require-match)))
1384 callback))
1385
1386 ;;; pseudo-tooltip ;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;
1387
1388 (defvar company-pseudo-tooltip-overlay nil)
1389 (make-variable-buffer-local 'company-pseudo-tooltip-overlay)
1390
1391 (defvar company-tooltip-offset 0)
1392 (make-variable-buffer-local 'company-tooltip-offset)
1393
1394 (defun company-pseudo-tooltip-update-offset (selection num-lines limit)
1395
1396 (decf limit 2)
1397 (setq company-tooltip-offset
1398 (max (min selection company-tooltip-offset)
1399 (- selection -1 limit)))
1400
1401 (when (<= company-tooltip-offset 1)
1402 (incf limit)
1403 (setq company-tooltip-offset 0))
1404
1405 (when (>= company-tooltip-offset (- num-lines limit 1))
1406 (incf limit)
1407 (when (= selection (1- num-lines))
1408 (decf company-tooltip-offset)
1409 (when (<= company-tooltip-offset 1)
1410 (setq company-tooltip-offset 0)
1411 (incf limit))))
1412
1413 limit)
1414
1415 ;;; propertize
1416
1417 (defsubst company-round-tab (arg)
1418 (* (/ (+ arg tab-width) tab-width) tab-width))
1419
1420 (defun company-untabify (str)
1421 (let* ((pieces (split-string str "\t"))
1422 (copy pieces))
1423 (while (cdr copy)
1424 (setcar copy (company-safe-substring
1425 (car copy) 0 (company-round-tab (string-width (car copy)))))
1426 (pop copy))
1427 (apply 'concat pieces)))
1428
1429 (defun company-fill-propertize (line width selected)
1430 (setq line (company-safe-substring line 0 width))
1431 (add-text-properties 0 width '(face company-tooltip
1432 mouse-face company-tooltip-mouse)
1433 line)
1434 (add-text-properties 0 (length company-common)
1435 '(face company-tooltip-common
1436 mouse-face company-tooltip-mouse)
1437 line)
1438 (when selected
1439 (if (and company-search-string
1440 (string-match (regexp-quote company-search-string) line
1441 (length company-prefix)))
1442 (progn
1443 (add-text-properties (match-beginning 0) (match-end 0)
1444 '(face company-tooltip-selection)
1445 line)
1446 (when (< (match-beginning 0) (length company-common))
1447 (add-text-properties (match-beginning 0) (length company-common)
1448 '(face company-tooltip-common-selection)
1449 line)))
1450 (add-text-properties 0 width '(face company-tooltip-selection
1451 mouse-face company-tooltip-selection)
1452 line)
1453 (add-text-properties 0 (length company-common)
1454 '(face company-tooltip-common-selection
1455 mouse-face company-tooltip-selection)
1456 line)))
1457 line)
1458
1459 ;;; replace
1460
1461 (defun company-buffer-lines (beg end)
1462 (goto-char beg)
1463 (let ((row (cdr (posn-actual-col-row (posn-at-point))))
1464 lines)
1465 (while (and (equal (move-to-window-line (incf row)) row)
1466 (<= (point) end))
1467 (push (buffer-substring beg (min end (1- (point)))) lines)
1468 (setq beg (point)))
1469 (unless (eq beg end)
1470 (push (buffer-substring beg end) lines))
1471 (nreverse lines)))
1472
1473 (defsubst company-modify-line (old new offset)
1474 (concat (company-safe-substring old 0 offset)
1475 new
1476 (company-safe-substring old (+ offset (length new)))))
1477
1478 (defun company-replacement-string (old lines column nl)
1479 (let (new)
1480 ;; Inject into old lines.
1481 (while old
1482 (push (company-modify-line (pop old) (pop lines) column) new))
1483 ;; Append whole new lines.
1484 (while lines
1485 (push (concat (company-space-string column) (pop lines)) new))
1486 (concat (when nl "\n")
1487 (mapconcat 'identity (nreverse new) "\n")
1488 "\n")))
1489
1490 (defun company-create-lines (column selection limit)
1491
1492 (let ((len company-candidates-length)
1493 (numbered 99999)
1494 lines
1495 width
1496 lines-copy
1497 previous
1498 remainder
1499 new)
1500
1501 ;; Scroll to offset.
1502 (setq limit (company-pseudo-tooltip-update-offset selection len limit))
1503
1504 (when (> company-tooltip-offset 0)
1505 (setq previous (format "...(%d)" company-tooltip-offset)))
1506
1507 (setq remainder (- len limit company-tooltip-offset)
1508 remainder (when (> remainder 0)
1509 (setq remainder (format "...(%d)" remainder))))
1510
1511 (decf selection company-tooltip-offset)
1512 (setq width (max (length previous) (length remainder))
1513 lines (nthcdr company-tooltip-offset company-candidates)
1514 len (min limit len)
1515 lines-copy lines)
1516
1517 (dotimes (i len)
1518 (setq width (max (length (pop lines-copy)) width)))
1519 (setq width (min width (- (window-width) column)))
1520
1521 (setq lines-copy lines)
1522
1523 ;; number can make tooltip too long
1524 (when company-show-numbers
1525 (setq numbered company-tooltip-offset))
1526
1527 (when previous
1528 (push (propertize (company-safe-substring previous 0 width)
1529 'face 'company-tooltip)
1530 new))
1531
1532 (dotimes (i len)
1533 (push (company-fill-propertize
1534 (if (>= numbered 10)
1535 (company-reformat (pop lines))
1536 (incf numbered)
1537 (format "%s %d"
1538 (company-safe-substring (company-reformat (pop lines))
1539 0 (- width 2))
1540 (mod numbered 10)))
1541 width (equal i selection))
1542 new))
1543
1544 (when remainder
1545 (push (propertize (company-safe-substring remainder 0 width)
1546 'face 'company-tooltip)
1547 new))
1548
1549 (setq lines (nreverse new))))
1550
1551 ;; show
1552
1553 (defsubst company-pseudo-tooltip-height ()
1554 "Calculate the appropriate tooltip height."
1555 (max 3 (min company-tooltip-limit
1556 (- (window-height) 2
1557 (count-lines (window-start) (point-at-bol))))))
1558
1559 (defun company-pseudo-tooltip-show (row column selection)
1560 (company-pseudo-tooltip-hide)
1561 (save-excursion
1562
1563 (move-to-column 0)
1564
1565 (let* ((height (company-pseudo-tooltip-height))
1566 (lines (company-create-lines column selection height))
1567 (nl (< (move-to-window-line row) row))
1568 (beg (point))
1569 (end (save-excursion
1570 (move-to-window-line (+ row height))
1571 (point)))
1572 (old-string
1573 (mapcar 'company-untabify (company-buffer-lines beg end)))
1574 str)
1575
1576 (setq company-pseudo-tooltip-overlay (make-overlay beg end))
1577
1578 (overlay-put company-pseudo-tooltip-overlay 'company-old old-string)
1579 (overlay-put company-pseudo-tooltip-overlay 'company-column column)
1580 (overlay-put company-pseudo-tooltip-overlay 'company-nl nl)
1581 (overlay-put company-pseudo-tooltip-overlay 'company-before
1582 (company-replacement-string old-string lines column nl))
1583 (overlay-put company-pseudo-tooltip-overlay 'company-height height)
1584
1585 (overlay-put company-pseudo-tooltip-overlay 'window (selected-window)))))
1586
1587 (defun company-pseudo-tooltip-show-at-point (pos)
1588 (let ((col-row (posn-actual-col-row (posn-at-point pos))))
1589 (when col-row
1590 (company-pseudo-tooltip-show (1+ (cdr col-row)) (car col-row)
1591 company-selection))))
1592
1593 (defun company-pseudo-tooltip-edit (lines selection)
1594 (let* ((old-string (overlay-get company-pseudo-tooltip-overlay 'company-old))
1595 (column (overlay-get company-pseudo-tooltip-overlay 'company-column))
1596 (nl (overlay-get company-pseudo-tooltip-overlay 'company-nl))
1597 (height (overlay-get company-pseudo-tooltip-overlay 'company-height))
1598 (lines (company-create-lines column selection height)))
1599 (overlay-put company-pseudo-tooltip-overlay 'company-before
1600 (company-replacement-string old-string lines column nl))))
1601
1602 (defun company-pseudo-tooltip-hide ()
1603 (when company-pseudo-tooltip-overlay
1604 (delete-overlay company-pseudo-tooltip-overlay)
1605 (setq company-pseudo-tooltip-overlay nil)))
1606
1607 (defun company-pseudo-tooltip-hide-temporarily ()
1608 (when (overlayp company-pseudo-tooltip-overlay)
1609 (overlay-put company-pseudo-tooltip-overlay 'invisible nil)
1610 (overlay-put company-pseudo-tooltip-overlay 'before-string nil)))
1611
1612 (defun company-pseudo-tooltip-unhide ()
1613 (when company-pseudo-tooltip-overlay
1614 (overlay-put company-pseudo-tooltip-overlay 'invisible t)
1615 (overlay-put company-pseudo-tooltip-overlay 'before-string
1616 (overlay-get company-pseudo-tooltip-overlay 'company-before))
1617 (overlay-put company-pseudo-tooltip-overlay 'window (selected-window))))
1618
1619 (defun company-pseudo-tooltip-frontend (command)
1620 "A `company-mode' front-end similar to a tool-tip but based on overlays."
1621 (case command
1622 ('pre-command (company-pseudo-tooltip-hide-temporarily))
1623 ('post-command
1624 (unless (and (overlayp company-pseudo-tooltip-overlay)
1625 (equal (overlay-get company-pseudo-tooltip-overlay
1626 'company-height)
1627 (company-pseudo-tooltip-height)))
1628 ;; Redraw needed.
1629 (company-pseudo-tooltip-show-at-point (- (point)
1630 (length company-prefix))))
1631 (company-pseudo-tooltip-unhide))
1632 ('hide (company-pseudo-tooltip-hide)
1633 (setq company-tooltip-offset 0))
1634 ('update (when (overlayp company-pseudo-tooltip-overlay)
1635 (company-pseudo-tooltip-edit company-candidates
1636 company-selection)))))
1637
1638 (defun company-pseudo-tooltip-unless-just-one-frontend (command)
1639 "`company-pseudo-tooltip-frontend', but not shown for single candidates."
1640 (unless (and (eq command 'post-command)
1641 (not (cdr company-candidates)))
1642 (company-pseudo-tooltip-frontend command)))
1643
1644 ;;; overlay ;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;
1645
1646 (defvar company-preview-overlay nil)
1647 (make-variable-buffer-local 'company-preview-overlay)
1648
1649 (defun company-preview-show-at-point (pos)
1650 (company-preview-hide)
1651
1652 (setq company-preview-overlay (make-overlay pos pos))
1653
1654 (let ((completion(nth company-selection company-candidates)))
1655 (setq completion (propertize completion 'face 'company-preview))
1656 (add-text-properties 0 (length company-common)
1657 '(face company-preview-common) completion)
1658
1659 ;; Add search string
1660 (and company-search-string
1661 (string-match (regexp-quote company-search-string) completion)
1662 (add-text-properties (match-beginning 0)
1663 (match-end 0)
1664 '(face company-preview-search)
1665 completion))
1666
1667 (setq completion (company-strip-prefix completion))
1668
1669 (and (equal pos (point))
1670 (not (equal completion ""))
1671 (add-text-properties 0 1 '(cursor t) completion))
1672
1673 (overlay-put company-preview-overlay 'after-string completion)
1674 (overlay-put company-preview-overlay 'window (selected-window))))
1675
1676 (defun company-preview-hide ()
1677 (when company-preview-overlay
1678 (delete-overlay company-preview-overlay)
1679 (setq company-preview-overlay nil)))
1680
1681 (defun company-preview-frontend (command)
1682 "A `company-mode' front-end showing the selection as if it had been inserted."
1683 (case command
1684 ('pre-command (company-preview-hide))
1685 ('post-command (company-preview-show-at-point (point)))
1686 ('hide (company-preview-hide))))
1687
1688 (defun company-preview-if-just-one-frontend (command)
1689 "`company-preview-frontend', but only shown for single candidates."
1690 (unless (and (eq command 'post-command)
1691 (cdr company-candidates))
1692 (company-preview-frontend command)))
1693
1694 ;;; echo ;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;
1695
1696 (defvar company-echo-last-msg nil)
1697 (make-variable-buffer-local 'company-echo-last-msg)
1698
1699 (defvar company-echo-timer nil)
1700
1701 (defvar company-echo-delay .1)
1702
1703 (defun company-echo-show (&optional getter)
1704 (when getter
1705 (setq company-echo-last-msg (funcall getter)))
1706 (let ((message-log-max nil))
1707 (if company-echo-last-msg
1708 (message "%s" company-echo-last-msg)
1709 (message ""))))
1710
1711 (defsubst company-echo-show-soon (&optional getter)
1712 (when company-echo-timer
1713 (cancel-timer company-echo-timer))
1714 (setq company-echo-timer (run-with-timer company-echo-delay nil
1715 'company-echo-show getter)))
1716
1717 (defun company-echo-format ()
1718
1719 (let ((limit (window-width (minibuffer-window)))
1720 (len -1)
1721 ;; Roll to selection.
1722 (candidates (nthcdr company-selection company-candidates))
1723 (i (if company-show-numbers company-selection 99999))
1724 comp msg)
1725
1726 (while candidates
1727 (setq comp (company-reformat (pop candidates))
1728 len (+ len 1 (length comp)))
1729 (if (< i 10)
1730 ;; Add number.
1731 (progn
1732 (setq comp (propertize (format "%d: %s" i comp)
1733 'face 'company-echo))
1734 (incf len 3)
1735 (incf i)
1736 (add-text-properties 3 (+ 3 (length company-common))
1737 '(face company-echo-common) comp))
1738 (setq comp (propertize comp 'face 'company-echo))
1739 (add-text-properties 0 (length company-common)
1740 '(face company-echo-common) comp))
1741 (if (>= len limit)
1742 (setq candidates nil)
1743 (push comp msg)))
1744
1745 (mapconcat 'identity (nreverse msg) " ")))
1746
1747 (defun company-echo-strip-common-format ()
1748
1749 (let ((limit (window-width (minibuffer-window)))
1750 (len (+ (length company-prefix) 2))
1751 ;; Roll to selection.
1752 (candidates (nthcdr company-selection company-candidates))
1753 (i (if company-show-numbers company-selection 99999))
1754 msg comp)
1755
1756 (while candidates
1757 (setq comp (company-strip-prefix (pop candidates))
1758 len (+ len 2 (length comp)))
1759 (when (< i 10)
1760 ;; Add number.
1761 (setq comp (format "%s (%d)" comp i))
1762 (incf len 4)
1763 (incf i))
1764 (if (>= len limit)
1765 (setq candidates nil)
1766 (push (propertize comp 'face 'company-echo) msg)))
1767
1768 (concat (propertize company-prefix 'face 'company-echo-common) "{"
1769 (mapconcat 'identity (nreverse msg) ", ")
1770 "}")))
1771
1772 (defun company-echo-hide ()
1773 (when company-echo-timer
1774 (cancel-timer company-echo-timer))
1775 (unless (equal company-echo-last-msg "")
1776 (setq company-echo-last-msg "")
1777 (company-echo-show)))
1778
1779 (defun company-echo-frontend (command)
1780 "A `company-mode' front-end showing the candidates in the echo area."
1781 (case command
1782 ('pre-command (company-echo-show-soon))
1783 ('post-command (company-echo-show-soon 'company-echo-format))
1784 ('hide (company-echo-hide))))
1785
1786 (defun company-echo-strip-common-frontend (command)
1787 "A `company-mode' front-end showing the candidates in the echo area."
1788 (case command
1789 ('pre-command (company-echo-show-soon))
1790 ('post-command (company-echo-show-soon 'company-echo-strip-common-format))
1791 ('hide (company-echo-hide))))
1792
1793 (defun company-echo-metadata-frontend (command)
1794 "A `company-mode' front-end showing the documentation in the echo area."
1795 (case command
1796 ('pre-command (company-echo-show-soon))
1797 ('post-command (company-echo-show-soon 'company-fetch-metadata))
1798 ('hide (company-echo-hide))))
1799
1800 (provide 'company)
1801 ;;; company.el ends here