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