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