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