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