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