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