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