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