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