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