]> code.delx.au - gnu-emacs-elpa/blob - company.el
Starting no longer interrupts commands that depend on last-command.
[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 (setq this-command last-command))
570
571 (global-set-key '[31415926] 'company-ignore)
572
573 (defun company-input-noop ()
574 (push 31415926 unread-command-events))
575
576 ;;; backends ;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;
577
578 (defun company-grab (regexp &optional expression limit)
579 (when (looking-back regexp limit)
580 (or (match-string-no-properties (or expression 0)) "")))
581
582 (defun company-grab-line (regexp &optional expression)
583 (company-grab regexp expression (point-at-bol)))
584
585 (defun company-grab-symbol ()
586 (if (looking-at "\\_>")
587 (buffer-substring (point) (save-excursion (skip-syntax-backward "w_")
588 (point)))
589 (unless (and (char-after) (memq (char-syntax (char-after)) '(?w ?_)))
590 "")))
591
592 (defun company-grab-word ()
593 (if (looking-at "\\>")
594 (buffer-substring (point) (save-excursion (skip-syntax-backward "w")
595 (point)))
596 (unless (and (char-after) (eq (char-syntax (char-after)) ?w))
597 "")))
598
599 (defun company-in-string-or-comment ()
600 (let ((ppss (syntax-ppss)))
601 (or (car (setq ppss (nthcdr 3 ppss)))
602 (car (setq ppss (cdr ppss)))
603 (nth 3 ppss))))
604
605 (defun company-call-backend (&rest args)
606 (if (functionp company-backend)
607 (apply company-backend args)
608 (apply 'company--multi-backend-adapter company-backend args)))
609
610 (defun company--multi-backend-adapter (backends command &rest args)
611 (case command
612 ('candidates
613 (apply 'append (mapcar (lambda (backend) (apply backend command args))
614 backends)))
615 ('sorted nil)
616 ('duplicates t)
617 (otherwise
618 (let (value)
619 (dolist (backend backends)
620 (when (setq value (apply backend command args))
621 (return value)))))))
622
623 ;;; completion mechanism ;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;
624
625 (defvar company-backend nil)
626 (make-variable-buffer-local 'company-backend)
627
628 (defvar company-prefix nil)
629 (make-variable-buffer-local 'company-prefix)
630
631 (defvar company-candidates nil)
632 (make-variable-buffer-local 'company-candidates)
633
634 (defvar company-candidates-length nil)
635 (make-variable-buffer-local 'company-candidates-length)
636
637 (defvar company-candidates-cache nil)
638 (make-variable-buffer-local 'company-candidates-cache)
639
640 (defvar company-candidates-predicate nil)
641 (make-variable-buffer-local 'company-candidates-predicate)
642
643 (defvar company-common nil)
644 (make-variable-buffer-local 'company-common)
645
646 (defvar company-selection 0)
647 (make-variable-buffer-local 'company-selection)
648
649 (defvar company-selection-changed nil)
650 (make-variable-buffer-local 'company-selection-changed)
651
652 (defvar company--explicit-action nil
653 "Non-nil, if explicit completion took place.")
654 (make-variable-buffer-local 'company--explicit-action)
655
656 (defvar company--point-max nil)
657 (make-variable-buffer-local 'company--point-max)
658
659 (defvar company--this-command nil)
660
661 (defvar company-point nil)
662 (make-variable-buffer-local 'company-point)
663
664 (defvar company-timer nil)
665
666 (defvar company-added-newline nil)
667 (make-variable-buffer-local 'company-added-newline)
668
669 (defsubst company-strip-prefix (str)
670 (substring str (length company-prefix)))
671
672 (defun company-explicit-action-p ()
673 "Return whether explicit completion action was taken by the user."
674 (or company--explicit-action
675 company-selection-changed))
676
677 (defsubst company-reformat (candidate)
678 ;; company-ispell needs this, because the results are always lower-case
679 ;; It's mory efficient to fix it only when they are displayed.
680 (concat company-prefix (substring candidate (length company-prefix))))
681
682 (defun company--should-complete ()
683 (and (not (or buffer-read-only overriding-terminal-local-map
684 overriding-local-map))
685 (eq company-idle-delay t)
686 (or (eq t company-begin-commands)
687 (memq company--this-command company-begin-commands)
688 (and (symbolp this-command) (get this-command 'company-begin)))
689 (not (and transient-mark-mode mark-active))))
690
691 (defsubst company-call-frontends (command)
692 (dolist (frontend company-frontends)
693 (condition-case err
694 (funcall frontend command)
695 (error (error "Company: Front-end %s error \"%s\" on command %s"
696 frontend (error-message-string err) command)))))
697
698 (defsubst company-set-selection (selection &optional force-update)
699 (setq selection (max 0 (min (1- company-candidates-length) selection)))
700 (when (or force-update (not (equal selection company-selection)))
701 (setq company-selection selection
702 company-selection-changed t)
703 (company-call-frontends 'update)))
704
705 (defun company-apply-predicate (candidates predicate)
706 (let (new)
707 (dolist (c candidates)
708 (when (funcall predicate c)
709 (push c new)))
710 (nreverse new)))
711
712 (defun company-update-candidates (candidates)
713 (setq company-candidates-length (length candidates))
714 (if (> company-selection 0)
715 ;; Try to restore the selection
716 (let ((selected (nth company-selection company-candidates)))
717 (setq company-selection 0
718 company-candidates candidates)
719 (when selected
720 (while (and candidates (string< (pop candidates) selected))
721 (incf company-selection))
722 (unless candidates
723 ;; Make sure selection isn't out of bounds.
724 (setq company-selection (min (1- company-candidates-length)
725 company-selection)))))
726 (setq company-selection 0
727 company-candidates candidates))
728 ;; Save in cache:
729 (push (cons company-prefix company-candidates) company-candidates-cache)
730 ;; Calculate common.
731 (let ((completion-ignore-case (company-call-backend 'ignore-case)))
732 (setq company-common (try-completion company-prefix company-candidates)))
733 (when (eq company-common t)
734 (setq company-candidates nil)))
735
736 (defun company-calculate-candidates (prefix)
737 (let ((candidates
738 (or (cdr (assoc prefix company-candidates-cache))
739 (when company-candidates-cache
740 (let ((len (length prefix))
741 (completion-ignore-case (company-call-backend
742 'ignore-case))
743 prev)
744 (dotimes (i (1+ len))
745 (when (setq prev (cdr (assoc (substring prefix 0 (- len i))
746 company-candidates-cache)))
747 (return (all-completions prefix prev))))))
748 (let ((c (company-call-backend 'candidates prefix)))
749 (when company-candidates-predicate
750 (setq c (company-apply-predicate
751 c company-candidates-predicate)))
752 (unless (company-call-backend 'sorted)
753 (setq c (sort c 'string<)))
754 (when (company-call-backend 'duplicates)
755 ;; strip duplicates
756 (let ((c2 c))
757 (while c2
758 (setcdr c2 (progn (while (equal (pop c2) (car c2)))
759 c2)))))
760 c))))
761 (if (or (cdr candidates)
762 (not (equal (car candidates) prefix)))
763 ;; Don't start when already completed and unique.
764 candidates
765 ;; Not the right place? maybe when setting?
766 (and company-candidates t))))
767
768 (defun company-idle-begin (buf win tick pos)
769 (and company-mode
770 (eq buf (current-buffer))
771 (eq win (selected-window))
772 (eq tick (buffer-chars-modified-tick))
773 (eq pos (point))
774 (not company-candidates)
775 (not (equal (point) company-point))
776 (let ((company-idle-delay t))
777 (company-begin)
778 (when company-candidates
779 (company-input-noop)
780 (company-post-command)))))
781
782 (defun company-manual-begin ()
783 (interactive)
784 (company-assert-enabled)
785 (and company-mode
786 (not company-candidates)
787 (let ((company-idle-delay t)
788 (company-minimum-prefix-length 0)
789 (company-begin-commands t))
790 (setq company--explicit-action t)
791 (company-begin)))
792 ;; Return non-nil if active.
793 company-candidates)
794
795 (defun company-require-match-p ()
796 (let ((backend-value (company-call-backend 'require-match)))
797 (or (eq backend-value t)
798 (and (if (functionp company-require-match)
799 (funcall company-require-match)
800 (eq company-require-match t))
801 (not (eq backend-value 'never))))))
802
803 (defun company-punctuation-p (input)
804 "Return non-nil, if input starts with punctuation or parentheses."
805 (memq (char-syntax (string-to-char input)) '(?. ?\( ?\))))
806
807 (defun company-auto-complete-p (input)
808 "Return non-nil, if input starts with punctuation or parentheses."
809 (and (if (functionp company-auto-complete)
810 (funcall company-auto-complete)
811 company-auto-complete)
812 (if (functionp company-auto-complete-chars)
813 (funcall company-auto-complete-chars input)
814 (if (consp company-auto-complete-chars)
815 (memq (char-syntax (string-to-char input))
816 company-auto-complete-chars)
817 (string-match (substring input 0 1) company-auto-complete-chars)))))
818
819 (defun company--incremental-p ()
820 (and (> (point) company-point)
821 (> (point-max) company--point-max)
822 (equal (buffer-substring (- company-point (length company-prefix))
823 company-point)
824 company-prefix)))
825
826 (defsubst company--string-incremental-p (old-prefix new-prefix)
827 (and (> (length new-prefix) (length old-prefix))
828 (equal old-prefix (substring new-prefix 0 (length old-prefix)))))
829
830 (defun company--continue-failed (new-prefix)
831 (when (company--incremental-p)
832 (let ((input (buffer-substring-no-properties (point) company-point)))
833 (cond
834 ((company-auto-complete-p input)
835 ;; auto-complete
836 (save-excursion
837 (goto-char company-point)
838 (company-complete-selection)
839 nil))
840 ((and (company--string-incremental-p company-prefix new-prefix)
841 (company-require-match-p))
842 ;; wrong incremental input, but required match
843 (backward-delete-char (length input))
844 (ding)
845 (message "Matching input is required")
846 company-candidates)
847 ((equal company-prefix (car company-candidates))
848 ;; last input was actually success
849 (company-cancel company-prefix)
850 nil)))))
851
852 (defun company--continue ()
853 (when (company-call-backend 'no-cache company-prefix)
854 ;; Don't complete existing candidates, fetch new ones.
855 (setq company-candidates-cache nil))
856 (let* ((new-prefix (company-call-backend 'prefix))
857 (c (when (and (stringp new-prefix)
858 (or (company-explicit-action-p)
859 (>= (length new-prefix)
860 company-minimum-prefix-length))
861 (= (- (point) (length new-prefix))
862 (- company-point (length company-prefix))))
863 (company-calculate-candidates new-prefix))))
864 (cond
865 ((eq c t)
866 ;; t means complete/unique.
867 (company-cancel new-prefix)
868 nil)
869 ((consp c)
870 ;; incremental match
871 (setq company-prefix new-prefix)
872 (company-update-candidates c)
873 c)
874 (t (company--continue-failed new-prefix)))))
875
876 (defun company--begin-new ()
877 (let (prefix c)
878 (dolist (backend (if company-backend
879 ;; prefer manual override
880 (list company-backend)
881 company-backends))
882 (setq prefix
883 (if (or (symbolp backend)
884 (functionp backend))
885 (when (or (not (symbolp backend))
886 (get backend 'company-init))
887 (funcall backend 'prefix))
888 (company--multi-backend-adapter backend 'prefix)))
889 (when prefix
890 (when (and (stringp prefix)
891 (>= (length prefix) company-minimum-prefix-length))
892 (setq company-backend backend
893 company-prefix prefix
894 c (company-calculate-candidates prefix))
895 ;; t means complete/unique. We don't start, so no hooks.
896 (when (consp c)
897 (company-update-candidates c)
898 (run-hook-with-args 'company-completion-started-hook
899 (company-explicit-action-p))
900 (company-call-frontends 'show)))
901 (return c)))))
902
903 (defun company-begin ()
904 (setq company-candidates
905 (or (and company-candidates (company--continue))
906 (and (company--should-complete) (company--begin-new))))
907 (if company-candidates
908 (progn
909 (when (and company-end-of-buffer-workaround (eobp))
910 (save-excursion (insert "\n"))
911 (setq company-added-newline (buffer-chars-modified-tick)))
912 (setq company-point (point)
913 company--point-max (point-max))
914 (company-enable-overriding-keymap company-active-map)
915 (company-call-frontends 'update))
916 (company-cancel)))
917
918 (defun company-cancel (&optional result)
919 (and company-added-newline
920 (> (point-max) (point-min))
921 (let ((tick (buffer-chars-modified-tick)))
922 (delete-region (1- (point-max)) (point-max))
923 (equal tick company-added-newline))
924 ;; Only set unmodified when tick remained the same since insert.
925 (set-buffer-modified-p nil))
926 (when company-prefix
927 (if (stringp result)
928 (run-hook-with-args 'company-completion-finished-hook result)
929 (run-hook-with-args 'company-completion-cancelled-hook result)))
930 (setq company-added-newline nil
931 company-backend nil
932 company-prefix nil
933 company-candidates nil
934 company-candidates-length nil
935 company-candidates-cache nil
936 company-candidates-predicate nil
937 company-common nil
938 company-selection 0
939 company-selection-changed nil
940 company--explicit-action nil
941 company--point-max nil
942 company-point nil)
943 (when company-timer
944 (cancel-timer company-timer))
945 (company-search-mode 0)
946 (company-call-frontends 'hide)
947 (company-enable-overriding-keymap nil))
948
949 (defun company-abort ()
950 (interactive)
951 (company-cancel t)
952 ;; Don't start again, unless started manually.
953 (setq company-point (point)))
954
955 (defun company-finish (result)
956 (insert (company-strip-prefix result))
957 (company-cancel result)
958 ;; Don't start again, unless started manually.
959 (setq company-point (point)))
960
961 (defsubst company-keep (command)
962 (and (symbolp command) (get command 'company-keep)))
963
964 (defun company-pre-command ()
965 (unless (company-keep this-command)
966 (condition-case err
967 (when company-candidates
968 (company-call-frontends 'pre-command))
969 (error (message "Company: An error occurred in pre-command")
970 (message "%s" (error-message-string err))
971 (company-cancel))))
972 (when company-timer
973 (cancel-timer company-timer))
974 (company-uninstall-map))
975
976 (defun company-post-command ()
977 (unless (company-keep this-command)
978 (condition-case err
979 (progn
980 (setq company--this-command this-command)
981 (unless (equal (point) company-point)
982 (company-begin))
983 (when company-candidates
984 (company-call-frontends 'post-command))
985 (when (numberp company-idle-delay)
986 (setq company-timer
987 (run-with-timer company-idle-delay nil 'company-idle-begin
988 (current-buffer) (selected-window)
989 (buffer-chars-modified-tick) (point)))))
990 (error (message "Company: An error occurred in post-command")
991 (message "%s" (error-message-string err))
992 (company-cancel))))
993 (company-install-map))
994
995 ;;; search ;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;
996
997 (defvar company-search-string nil)
998 (make-variable-buffer-local 'company-search-string)
999
1000 (defvar company-search-lighter " Search: \"\"")
1001 (make-variable-buffer-local 'company-search-lighter)
1002
1003 (defvar company-search-old-map nil)
1004 (make-variable-buffer-local 'company-search-old-map)
1005
1006 (defvar company-search-old-selection 0)
1007 (make-variable-buffer-local 'company-search-old-selection)
1008
1009 (defun company-search (text lines)
1010 (let ((quoted (regexp-quote text))
1011 (i 0))
1012 (dolist (line lines)
1013 (when (string-match quoted line (length company-prefix))
1014 (return i))
1015 (incf i))))
1016
1017 (defun company-search-printing-char ()
1018 (interactive)
1019 (company-search-assert-enabled)
1020 (setq company-search-string
1021 (concat (or company-search-string "") (string last-command-event))
1022 company-search-lighter (concat " Search: \"" company-search-string
1023 "\""))
1024 (let ((pos (company-search company-search-string
1025 (nthcdr company-selection company-candidates))))
1026 (if (null pos)
1027 (ding)
1028 (company-set-selection (+ company-selection pos) t))))
1029
1030 (defun company-search-repeat-forward ()
1031 "Repeat the incremental search in completion candidates forward."
1032 (interactive)
1033 (company-search-assert-enabled)
1034 (let ((pos (company-search company-search-string
1035 (cdr (nthcdr company-selection
1036 company-candidates)))))
1037 (if (null pos)
1038 (ding)
1039 (company-set-selection (+ company-selection pos 1) t))))
1040
1041 (defun company-search-repeat-backward ()
1042 "Repeat the incremental search in completion candidates backwards."
1043 (interactive)
1044 (company-search-assert-enabled)
1045 (let ((pos (company-search company-search-string
1046 (nthcdr (- company-candidates-length
1047 company-selection)
1048 (reverse company-candidates)))))
1049 (if (null pos)
1050 (ding)
1051 (company-set-selection (- company-selection pos 1) t))))
1052
1053 (defun company-create-match-predicate ()
1054 (setq company-candidates-predicate
1055 `(lambda (candidate)
1056 ,(if company-candidates-predicate
1057 `(and (string-match ,company-search-string candidate)
1058 (funcall ,company-candidates-predicate
1059 candidate))
1060 `(string-match ,company-search-string candidate))))
1061 (company-update-candidates
1062 (company-apply-predicate company-candidates company-candidates-predicate))
1063 ;; Invalidate cache.
1064 (setq company-candidates-cache (cons company-prefix company-candidates)))
1065
1066 (defun company-filter-printing-char ()
1067 (interactive)
1068 (company-search-assert-enabled)
1069 (company-search-printing-char)
1070 (company-create-match-predicate)
1071 (company-call-frontends 'update))
1072
1073 (defun company-search-kill-others ()
1074 "Limit the completion candidates to the ones matching the search string."
1075 (interactive)
1076 (company-search-assert-enabled)
1077 (company-create-match-predicate)
1078 (company-search-mode 0)
1079 (company-call-frontends 'update))
1080
1081 (defun company-search-abort ()
1082 "Abort searching the completion candidates."
1083 (interactive)
1084 (company-search-assert-enabled)
1085 (company-set-selection company-search-old-selection t)
1086 (company-search-mode 0))
1087
1088 (defun company-search-other-char ()
1089 (interactive)
1090 (company-search-assert-enabled)
1091 (company-search-mode 0)
1092 (when last-input-event
1093 (clear-this-command-keys t)
1094 (setq unread-command-events (list last-input-event))))
1095
1096 (defvar company-search-map
1097 (let ((i 0)
1098 (keymap (make-keymap)))
1099 (if (fboundp 'max-char)
1100 (set-char-table-range (nth 1 keymap) (cons #x100 (max-char))
1101 'company-search-printing-char)
1102 (with-no-warnings
1103 ;; obselete in Emacs 23
1104 (let ((l (generic-character-list))
1105 (table (nth 1 keymap)))
1106 (while l
1107 (set-char-table-default table (car l) 'company-search-printing-char)
1108 (setq l (cdr l))))))
1109 (define-key keymap [t] 'company-search-other-char)
1110 (while (< i ?\s)
1111 (define-key keymap (make-string 1 i) 'company-search-other-char)
1112 (incf i))
1113 (while (< i 256)
1114 (define-key keymap (vector i) 'company-search-printing-char)
1115 (incf i))
1116 (let ((meta-map (make-sparse-keymap)))
1117 (define-key keymap (char-to-string meta-prefix-char) meta-map)
1118 (define-key keymap [escape] meta-map))
1119 (define-key keymap (vector meta-prefix-char t) 'company-search-other-char)
1120 (define-key keymap "\e\e\e" 'company-search-other-char)
1121 (define-key keymap [escape escape escape] 'company-search-other-char)
1122
1123 (define-key keymap "\C-g" 'company-search-abort)
1124 (define-key keymap "\C-s" 'company-search-repeat-forward)
1125 (define-key keymap "\C-r" 'company-search-repeat-backward)
1126 (define-key keymap "\C-o" 'company-search-kill-others)
1127 keymap)
1128 "Keymap used for incrementally searching the completion candidates.")
1129
1130 (define-minor-mode company-search-mode
1131 "Search mode for completion candidates.
1132 Don't start this directly, use `company-search-candidates' or
1133 `company-filter-candidates'."
1134 nil company-search-lighter nil
1135 (if company-search-mode
1136 (if (company-manual-begin)
1137 (progn
1138 (setq company-search-old-selection company-selection)
1139 (company-call-frontends 'update))
1140 (setq company-search-mode nil))
1141 (kill-local-variable 'company-search-string)
1142 (kill-local-variable 'company-search-lighter)
1143 (kill-local-variable 'company-search-old-selection)
1144 (company-enable-overriding-keymap company-active-map)))
1145
1146 (defsubst company-search-assert-enabled ()
1147 (company-assert-enabled)
1148 (unless company-search-mode
1149 (company-uninstall-map)
1150 (error "Company not in search mode")))
1151
1152 (defun company-search-candidates ()
1153 "Start searching the completion candidates incrementally.
1154
1155 \\<company-search-map>Search can be controlled with the commands:
1156 - `company-search-repeat-forward' (\\[company-search-repeat-forward])
1157 - `company-search-repeat-backward' (\\[company-search-repeat-backward])
1158 - `company-search-abort' (\\[company-search-abort])
1159
1160 Regular characters are appended to the search string.
1161
1162 The command `company-search-kill-others' (\\[company-search-kill-others]) uses
1163 the search string to limit the completion candidates."
1164 (interactive)
1165 (company-search-mode 1)
1166 (company-enable-overriding-keymap company-search-map))
1167
1168 (defvar company-filter-map
1169 (let ((keymap (make-keymap)))
1170 (define-key keymap [remap company-search-printing-char]
1171 'company-filter-printing-char)
1172 (set-keymap-parent keymap company-search-map)
1173 keymap)
1174 "Keymap used for incrementally searching the completion candidates.")
1175
1176 (defun company-filter-candidates ()
1177 "Start filtering the completion candidates incrementally.
1178 This works the same way as `company-search-candidates' immediately
1179 followed by `company-search-kill-others' after each input."
1180 (interactive)
1181 (company-search-mode 1)
1182 (company-enable-overriding-keymap company-filter-map))
1183
1184 ;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;
1185
1186 (defun company-select-next ()
1187 "Select the next candidate in the list."
1188 (interactive)
1189 (when (company-manual-begin)
1190 (company-set-selection (1+ company-selection))))
1191
1192 (defun company-select-previous ()
1193 "Select the previous candidate in the list."
1194 (interactive)
1195 (when (company-manual-begin)
1196 (company-set-selection (1- company-selection))))
1197
1198 (defun company-select-mouse (event)
1199 "Select the candidate picked by the mouse."
1200 (interactive "e")
1201 (when (nth 4 (event-start event))
1202 (company-set-selection (- (cdr (posn-actual-col-row (event-start event)))
1203 (cdr (posn-actual-col-row (posn-at-point)))
1204 1))
1205 t))
1206
1207 (defun company-complete-mouse (event)
1208 "Complete the candidate picked by the mouse."
1209 (interactive "e")
1210 (when (company-select-mouse event)
1211 (company-complete-selection)))
1212
1213 (defun company-complete-selection ()
1214 "Complete the selected candidate."
1215 (interactive)
1216 (when (company-manual-begin)
1217 (company-finish (nth company-selection company-candidates))))
1218
1219 (defun company-complete-common ()
1220 "Complete the common part of all candidates."
1221 (interactive)
1222 (when (company-manual-begin)
1223 (if (and (not (cdr company-candidates))
1224 (equal company-common (car company-candidates)))
1225 (company-complete-selection)
1226 (insert (company-strip-prefix company-common)))))
1227
1228 (defun company-complete ()
1229 "Complete the common part of all candidates or the current selection.
1230 The first time this is called, the common part is completed, the second time, or
1231 when the selection has been changed, the selected candidate is completed."
1232 (interactive)
1233 (when (company-manual-begin)
1234 (if (or company-selection-changed
1235 (eq last-command 'company-complete-common))
1236 (call-interactively 'company-complete-selection)
1237 (call-interactively 'company-complete-common)
1238 (setq this-command 'company-complete-common))))
1239
1240 (defun company-complete-number (n)
1241 "Complete the Nth candidate.
1242 To show the number next to the candidates in some back-ends, enable
1243 `company-show-numbers'."
1244 (when (company-manual-begin)
1245 (and (< n 1) (> n company-candidates-length)
1246 (error "No candidate number %d" n))
1247 (decf n)
1248 (company-finish (nth n company-candidates))))
1249
1250 ;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;
1251
1252 (defconst company-space-strings-limit 100)
1253
1254 (defconst company-space-strings
1255 (let (lst)
1256 (dotimes (i company-space-strings-limit)
1257 (push (make-string (- company-space-strings-limit 1 i) ?\ ) lst))
1258 (apply 'vector lst)))
1259
1260 (defsubst company-space-string (len)
1261 (if (< len company-space-strings-limit)
1262 (aref company-space-strings len)
1263 (make-string len ?\ )))
1264
1265 (defsubst company-safe-substring (str from &optional to)
1266 (let ((len (length str)))
1267 (if (> from len)
1268 ""
1269 (if (and to (> to len))
1270 (concat (substring str from)
1271 (company-space-string (- to len)))
1272 (substring str from to)))))
1273
1274 ;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;
1275
1276 (defvar company-last-metadata nil)
1277 (make-variable-buffer-local 'company-last-metadata)
1278
1279 (defun company-fetch-metadata ()
1280 (let ((selected (nth company-selection company-candidates)))
1281 (unless (equal selected (car company-last-metadata))
1282 (setq company-last-metadata
1283 (cons selected (company-call-backend 'meta selected))))
1284 (cdr company-last-metadata)))
1285
1286 (defun company-doc-buffer (&optional string)
1287 (with-current-buffer (get-buffer-create "*Company meta-data*")
1288 (erase-buffer)
1289 (current-buffer)))
1290
1291 (defmacro company-electric (&rest body)
1292 (declare (indent 0) (debug t))
1293 `(when (company-manual-begin)
1294 (save-window-excursion
1295 (let ((height (window-height))
1296 (row (cdr (posn-actual-col-row (posn-at-point)))))
1297 ,@body
1298 (and (< (window-height) height)
1299 (< (- (window-height) row 2) company-tooltip-limit)
1300 (recenter (- (window-height) row 2)))
1301 (while (eq 'scroll-other-window
1302 (key-binding (vector (list (read-event)))))
1303 (call-interactively 'scroll-other-window))
1304 (when last-input-event
1305 (clear-this-command-keys t)
1306 (setq unread-command-events (list last-input-event)))))))
1307
1308 (defun company-show-doc-buffer ()
1309 "Temporarily show a buffer with the complete documentation for the selection."
1310 (interactive)
1311 (company-electric
1312 (let ((selected (nth company-selection company-candidates)))
1313 (display-buffer (or (company-call-backend 'doc-buffer selected)
1314 (error "No documentation available")) t))))
1315 (put 'company-show-doc-buffer 'company-keep t)
1316
1317 (defun company-show-location ()
1318 "Temporarily display a buffer showing the selected candidate in context."
1319 (interactive)
1320 (company-electric
1321 (let* ((selected (nth company-selection company-candidates))
1322 (location (company-call-backend 'location selected))
1323 (pos (or (cdr location) (error "No location available")))
1324 (buffer (or (and (bufferp (car location)) (car location))
1325 (find-file-noselect (car location) t))))
1326 (with-selected-window (display-buffer buffer t)
1327 (if (bufferp (car location))
1328 (goto-char pos)
1329 (goto-line pos))
1330 (set-window-start nil (point))))))
1331 (put 'company-show-location 'company-keep t)
1332
1333 ;;; package functions ;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;
1334
1335 (defvar company-callback nil)
1336 (make-variable-buffer-local 'company-callback)
1337
1338 (defvar company-begin-with-marker nil)
1339 (make-variable-buffer-local 'company-begin-with-marker)
1340
1341 (defun company-remove-callback (&optional ignored)
1342 (remove-hook 'company-completion-finished-hook company-callback t)
1343 (remove-hook 'company-completion-cancelled-hook 'company-remove-callback t)
1344 (remove-hook 'company-completion-finished-hook 'company-remove-callback t)
1345 (set-marker company-begin-with-marker nil))
1346
1347 (defun company-begin-backend (backend &optional callback)
1348 "Start a completion at point using BACKEND."
1349 (interactive (let ((val (completing-read "Company back-end: "
1350 obarray
1351 'functionp nil "company-")))
1352 (when val
1353 (list (intern val)))))
1354 (when (setq company-callback callback)
1355 (add-hook 'company-completion-finished-hook company-callback nil t))
1356 (add-hook 'company-completion-cancelled-hook 'company-remove-callback nil t)
1357 (add-hook 'company-completion-finished-hook 'company-remove-callback nil t)
1358 (setq company-backend backend)
1359 ;; Return non-nil if active.
1360 (or (company-manual-begin)
1361 (error "Cannot complete at point")))
1362
1363 (defun company-begin-with (candidates
1364 &optional prefix-length require-match callback)
1365 "Start a completion at point.
1366 CANDIDATES is the list of candidates to use and PREFIX-LENGTH is the length of
1367 the prefix that already is in the buffer before point. It defaults to 0.
1368
1369 CALLBACK is a function called with the selected result if the user successfully
1370 completes the input.
1371
1372 Example:
1373 \(company-begin-with '\(\"foo\" \"foobar\" \"foobarbaz\"\)\)"
1374 (setq company-begin-with-marker (copy-marker (point) t))
1375 (company-begin-backend
1376 `(lambda (command &optional arg &rest ignored)
1377 (cond
1378 ((eq command 'prefix)
1379 (when (equal (point) (marker-position company-begin-with-marker))
1380 (buffer-substring ,(- (point) (or prefix-length 0)) (point))))
1381 ((eq command 'candidates)
1382 (all-completions arg ',candidates))
1383 ((eq command 'require-match)
1384 ,require-match)))
1385 callback))
1386
1387 ;;; pseudo-tooltip ;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;
1388
1389 (defvar company-pseudo-tooltip-overlay nil)
1390 (make-variable-buffer-local 'company-pseudo-tooltip-overlay)
1391
1392 (defvar company-tooltip-offset 0)
1393 (make-variable-buffer-local 'company-tooltip-offset)
1394
1395 (defun company-pseudo-tooltip-update-offset (selection num-lines limit)
1396
1397 (decf limit 2)
1398 (setq company-tooltip-offset
1399 (max (min selection company-tooltip-offset)
1400 (- selection -1 limit)))
1401
1402 (when (<= company-tooltip-offset 1)
1403 (incf limit)
1404 (setq company-tooltip-offset 0))
1405
1406 (when (>= company-tooltip-offset (- num-lines limit 1))
1407 (incf limit)
1408 (when (= selection (1- num-lines))
1409 (decf company-tooltip-offset)
1410 (when (<= company-tooltip-offset 1)
1411 (setq company-tooltip-offset 0)
1412 (incf limit))))
1413
1414 limit)
1415
1416 ;;; propertize
1417
1418 (defsubst company-round-tab (arg)
1419 (* (/ (+ arg tab-width) tab-width) tab-width))
1420
1421 (defun company-untabify (str)
1422 (let* ((pieces (split-string str "\t"))
1423 (copy pieces))
1424 (while (cdr copy)
1425 (setcar copy (company-safe-substring
1426 (car copy) 0 (company-round-tab (string-width (car copy)))))
1427 (pop copy))
1428 (apply 'concat pieces)))
1429
1430 (defun company-fill-propertize (line width selected)
1431 (setq line (company-safe-substring line 0 width))
1432 (add-text-properties 0 width '(face company-tooltip
1433 mouse-face company-tooltip-mouse)
1434 line)
1435 (add-text-properties 0 (length company-common)
1436 '(face company-tooltip-common
1437 mouse-face company-tooltip-mouse)
1438 line)
1439 (when selected
1440 (if (and company-search-string
1441 (string-match (regexp-quote company-search-string) line
1442 (length company-prefix)))
1443 (progn
1444 (add-text-properties (match-beginning 0) (match-end 0)
1445 '(face company-tooltip-selection)
1446 line)
1447 (when (< (match-beginning 0) (length company-common))
1448 (add-text-properties (match-beginning 0) (length company-common)
1449 '(face company-tooltip-common-selection)
1450 line)))
1451 (add-text-properties 0 width '(face company-tooltip-selection
1452 mouse-face company-tooltip-selection)
1453 line)
1454 (add-text-properties 0 (length company-common)
1455 '(face company-tooltip-common-selection
1456 mouse-face company-tooltip-selection)
1457 line)))
1458 line)
1459
1460 ;;; replace
1461
1462 (defun company-buffer-lines (beg end)
1463 (goto-char beg)
1464 (let ((row (cdr (posn-actual-col-row (posn-at-point))))
1465 lines)
1466 (while (and (equal (move-to-window-line (incf row)) row)
1467 (<= (point) end))
1468 (push (buffer-substring beg (min end (1- (point)))) lines)
1469 (setq beg (point)))
1470 (unless (eq beg end)
1471 (push (buffer-substring beg end) lines))
1472 (nreverse lines)))
1473
1474 (defsubst company-modify-line (old new offset)
1475 (concat (company-safe-substring old 0 offset)
1476 new
1477 (company-safe-substring old (+ offset (length new)))))
1478
1479 (defun company-replacement-string (old lines column nl)
1480 (let (new)
1481 ;; Inject into old lines.
1482 (while old
1483 (push (company-modify-line (pop old) (pop lines) column) new))
1484 ;; Append whole new lines.
1485 (while lines
1486 (push (concat (company-space-string column) (pop lines)) new))
1487 (concat (when nl "\n")
1488 (mapconcat 'identity (nreverse new) "\n")
1489 "\n")))
1490
1491 (defun company-create-lines (column selection limit)
1492
1493 (let ((len company-candidates-length)
1494 (numbered 99999)
1495 lines
1496 width
1497 lines-copy
1498 previous
1499 remainder
1500 new)
1501
1502 ;; Scroll to offset.
1503 (setq limit (company-pseudo-tooltip-update-offset selection len limit))
1504
1505 (when (> company-tooltip-offset 0)
1506 (setq previous (format "...(%d)" company-tooltip-offset)))
1507
1508 (setq remainder (- len limit company-tooltip-offset)
1509 remainder (when (> remainder 0)
1510 (setq remainder (format "...(%d)" remainder))))
1511
1512 (decf selection company-tooltip-offset)
1513 (setq width (max (length previous) (length remainder))
1514 lines (nthcdr company-tooltip-offset company-candidates)
1515 len (min limit len)
1516 lines-copy lines)
1517
1518 (dotimes (i len)
1519 (setq width (max (length (pop lines-copy)) width)))
1520 (setq width (min width (- (window-width) column)))
1521
1522 (setq lines-copy lines)
1523
1524 ;; number can make tooltip too long
1525 (when company-show-numbers
1526 (setq numbered company-tooltip-offset))
1527
1528 (when previous
1529 (push (propertize (company-safe-substring previous 0 width)
1530 'face 'company-tooltip)
1531 new))
1532
1533 (dotimes (i len)
1534 (push (company-fill-propertize
1535 (if (>= numbered 10)
1536 (company-reformat (pop lines))
1537 (incf numbered)
1538 (format "%s %d"
1539 (company-safe-substring (company-reformat (pop lines))
1540 0 (- width 2))
1541 (mod numbered 10)))
1542 width (equal i selection))
1543 new))
1544
1545 (when remainder
1546 (push (propertize (company-safe-substring remainder 0 width)
1547 'face 'company-tooltip)
1548 new))
1549
1550 (setq lines (nreverse new))))
1551
1552 ;; show
1553
1554 (defsubst company-pseudo-tooltip-height ()
1555 "Calculate the appropriate tooltip height."
1556 (max 3 (min company-tooltip-limit
1557 (- (window-height) 2
1558 (count-lines (window-start) (point-at-bol))))))
1559
1560 (defun company-pseudo-tooltip-show (row column selection)
1561 (company-pseudo-tooltip-hide)
1562 (save-excursion
1563
1564 (move-to-column 0)
1565
1566 (let* ((height (company-pseudo-tooltip-height))
1567 (lines (company-create-lines column selection height))
1568 (nl (< (move-to-window-line row) row))
1569 (beg (point))
1570 (end (save-excursion
1571 (move-to-window-line (+ row height))
1572 (point)))
1573 (old-string
1574 (mapcar 'company-untabify (company-buffer-lines beg end)))
1575 str)
1576
1577 (setq company-pseudo-tooltip-overlay (make-overlay beg end))
1578
1579 (overlay-put company-pseudo-tooltip-overlay 'company-old old-string)
1580 (overlay-put company-pseudo-tooltip-overlay 'company-column column)
1581 (overlay-put company-pseudo-tooltip-overlay 'company-nl nl)
1582 (overlay-put company-pseudo-tooltip-overlay 'company-before
1583 (company-replacement-string old-string lines column nl))
1584 (overlay-put company-pseudo-tooltip-overlay 'company-height height)
1585
1586 (overlay-put company-pseudo-tooltip-overlay 'window (selected-window)))))
1587
1588 (defun company-pseudo-tooltip-show-at-point (pos)
1589 (let ((col-row (posn-actual-col-row (posn-at-point pos))))
1590 (when col-row
1591 (company-pseudo-tooltip-show (1+ (cdr col-row)) (car col-row)
1592 company-selection))))
1593
1594 (defun company-pseudo-tooltip-edit (lines selection)
1595 (let* ((old-string (overlay-get company-pseudo-tooltip-overlay 'company-old))
1596 (column (overlay-get company-pseudo-tooltip-overlay 'company-column))
1597 (nl (overlay-get company-pseudo-tooltip-overlay 'company-nl))
1598 (height (overlay-get company-pseudo-tooltip-overlay 'company-height))
1599 (lines (company-create-lines column selection height)))
1600 (overlay-put company-pseudo-tooltip-overlay 'company-before
1601 (company-replacement-string old-string lines column nl))))
1602
1603 (defun company-pseudo-tooltip-hide ()
1604 (when company-pseudo-tooltip-overlay
1605 (delete-overlay company-pseudo-tooltip-overlay)
1606 (setq company-pseudo-tooltip-overlay nil)))
1607
1608 (defun company-pseudo-tooltip-hide-temporarily ()
1609 (when (overlayp company-pseudo-tooltip-overlay)
1610 (overlay-put company-pseudo-tooltip-overlay 'invisible nil)
1611 (overlay-put company-pseudo-tooltip-overlay 'before-string nil)))
1612
1613 (defun company-pseudo-tooltip-unhide ()
1614 (when company-pseudo-tooltip-overlay
1615 (overlay-put company-pseudo-tooltip-overlay 'invisible t)
1616 (overlay-put company-pseudo-tooltip-overlay 'before-string
1617 (overlay-get company-pseudo-tooltip-overlay 'company-before))
1618 (overlay-put company-pseudo-tooltip-overlay 'window (selected-window))))
1619
1620 (defun company-pseudo-tooltip-frontend (command)
1621 "A `company-mode' front-end similar to a tool-tip but based on overlays."
1622 (case command
1623 ('pre-command (company-pseudo-tooltip-hide-temporarily))
1624 ('post-command
1625 (unless (and (overlayp company-pseudo-tooltip-overlay)
1626 (equal (overlay-get company-pseudo-tooltip-overlay
1627 'company-height)
1628 (company-pseudo-tooltip-height)))
1629 ;; Redraw needed.
1630 (company-pseudo-tooltip-show-at-point (- (point)
1631 (length company-prefix))))
1632 (company-pseudo-tooltip-unhide))
1633 ('hide (company-pseudo-tooltip-hide)
1634 (setq company-tooltip-offset 0))
1635 ('update (when (overlayp company-pseudo-tooltip-overlay)
1636 (company-pseudo-tooltip-edit company-candidates
1637 company-selection)))))
1638
1639 (defun company-pseudo-tooltip-unless-just-one-frontend (command)
1640 "`company-pseudo-tooltip-frontend', but not shown for single candidates."
1641 (unless (and (eq command 'post-command)
1642 (not (cdr company-candidates)))
1643 (company-pseudo-tooltip-frontend command)))
1644
1645 ;;; overlay ;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;
1646
1647 (defvar company-preview-overlay nil)
1648 (make-variable-buffer-local 'company-preview-overlay)
1649
1650 (defun company-preview-show-at-point (pos)
1651 (company-preview-hide)
1652
1653 (setq company-preview-overlay (make-overlay pos pos))
1654
1655 (let ((completion(nth company-selection company-candidates)))
1656 (setq completion (propertize completion 'face 'company-preview))
1657 (add-text-properties 0 (length company-common)
1658 '(face company-preview-common) completion)
1659
1660 ;; Add search string
1661 (and company-search-string
1662 (string-match (regexp-quote company-search-string) completion)
1663 (add-text-properties (match-beginning 0)
1664 (match-end 0)
1665 '(face company-preview-search)
1666 completion))
1667
1668 (setq completion (company-strip-prefix completion))
1669
1670 (and (equal pos (point))
1671 (not (equal completion ""))
1672 (add-text-properties 0 1 '(cursor t) completion))
1673
1674 (overlay-put company-preview-overlay 'after-string completion)
1675 (overlay-put company-preview-overlay 'window (selected-window))))
1676
1677 (defun company-preview-hide ()
1678 (when company-preview-overlay
1679 (delete-overlay company-preview-overlay)
1680 (setq company-preview-overlay nil)))
1681
1682 (defun company-preview-frontend (command)
1683 "A `company-mode' front-end showing the selection as if it had been inserted."
1684 (case command
1685 ('pre-command (company-preview-hide))
1686 ('post-command (company-preview-show-at-point (point)))
1687 ('hide (company-preview-hide))))
1688
1689 (defun company-preview-if-just-one-frontend (command)
1690 "`company-preview-frontend', but only shown for single candidates."
1691 (unless (and (eq command 'post-command)
1692 (cdr company-candidates))
1693 (company-preview-frontend command)))
1694
1695 ;;; echo ;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;
1696
1697 (defvar company-echo-last-msg nil)
1698 (make-variable-buffer-local 'company-echo-last-msg)
1699
1700 (defvar company-echo-timer nil)
1701
1702 (defvar company-echo-delay .1)
1703
1704 (defun company-echo-show (&optional getter)
1705 (when getter
1706 (setq company-echo-last-msg (funcall getter)))
1707 (let ((message-log-max nil))
1708 (if company-echo-last-msg
1709 (message "%s" company-echo-last-msg)
1710 (message ""))))
1711
1712 (defsubst company-echo-show-soon (&optional getter)
1713 (when company-echo-timer
1714 (cancel-timer company-echo-timer))
1715 (setq company-echo-timer (run-with-timer company-echo-delay nil
1716 'company-echo-show getter)))
1717
1718 (defun company-echo-format ()
1719
1720 (let ((limit (window-width (minibuffer-window)))
1721 (len -1)
1722 ;; Roll to selection.
1723 (candidates (nthcdr company-selection company-candidates))
1724 (i (if company-show-numbers company-selection 99999))
1725 comp msg)
1726
1727 (while candidates
1728 (setq comp (company-reformat (pop candidates))
1729 len (+ len 1 (length comp)))
1730 (if (< i 10)
1731 ;; Add number.
1732 (progn
1733 (setq comp (propertize (format "%d: %s" i comp)
1734 'face 'company-echo))
1735 (incf len 3)
1736 (incf i)
1737 (add-text-properties 3 (+ 3 (length company-common))
1738 '(face company-echo-common) comp))
1739 (setq comp (propertize comp 'face 'company-echo))
1740 (add-text-properties 0 (length company-common)
1741 '(face company-echo-common) comp))
1742 (if (>= len limit)
1743 (setq candidates nil)
1744 (push comp msg)))
1745
1746 (mapconcat 'identity (nreverse msg) " ")))
1747
1748 (defun company-echo-strip-common-format ()
1749
1750 (let ((limit (window-width (minibuffer-window)))
1751 (len (+ (length company-prefix) 2))
1752 ;; Roll to selection.
1753 (candidates (nthcdr company-selection company-candidates))
1754 (i (if company-show-numbers company-selection 99999))
1755 msg comp)
1756
1757 (while candidates
1758 (setq comp (company-strip-prefix (pop candidates))
1759 len (+ len 2 (length comp)))
1760 (when (< i 10)
1761 ;; Add number.
1762 (setq comp (format "%s (%d)" comp i))
1763 (incf len 4)
1764 (incf i))
1765 (if (>= len limit)
1766 (setq candidates nil)
1767 (push (propertize comp 'face 'company-echo) msg)))
1768
1769 (concat (propertize company-prefix 'face 'company-echo-common) "{"
1770 (mapconcat 'identity (nreverse msg) ", ")
1771 "}")))
1772
1773 (defun company-echo-hide ()
1774 (when company-echo-timer
1775 (cancel-timer company-echo-timer))
1776 (unless (equal company-echo-last-msg "")
1777 (setq company-echo-last-msg "")
1778 (company-echo-show)))
1779
1780 (defun company-echo-frontend (command)
1781 "A `company-mode' front-end showing the candidates in the echo area."
1782 (case command
1783 ('pre-command (company-echo-show-soon))
1784 ('post-command (company-echo-show-soon 'company-echo-format))
1785 ('hide (company-echo-hide))))
1786
1787 (defun company-echo-strip-common-frontend (command)
1788 "A `company-mode' front-end showing the candidates in the echo area."
1789 (case command
1790 ('pre-command (company-echo-show-soon))
1791 ('post-command (company-echo-show-soon 'company-echo-strip-common-format))
1792 ('hide (company-echo-hide))))
1793
1794 (defun company-echo-metadata-frontend (command)
1795 "A `company-mode' front-end showing the documentation in the echo area."
1796 (case command
1797 ('pre-command (company-echo-show-soon))
1798 ('post-command (company-echo-show-soon 'company-fetch-metadata))
1799 ('hide (company-echo-hide))))
1800
1801 (provide 'company)
1802 ;;; company.el ends here