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