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