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