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