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