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