]> code.delx.au - gnu-emacs-elpa/blob - company.el
Render company-preview-frontend after the cursor
[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-transformers nil
362 "Functions to change the list of candidates received from backends,
363 after sorting and removal of duplicates (if appropriate).
364 Each function gets called with the return value of the previous one."
365 :type '(choice
366 (const :tag "None" nil)
367 (const :tag "Sort by occurrence" (company-sort-by-occurrence))
368 (repeat :tag "User defined" (function))))
369
370 (defcustom company-completion-started-hook nil
371 "Hook run when company starts completing.
372 The hook is called with one argument that is non-nil if the completion was
373 started manually."
374 :type 'hook)
375
376 (defcustom company-completion-cancelled-hook nil
377 "Hook run when company cancels completing.
378 The hook is called with one argument that is non-nil if the completion was
379 aborted manually."
380 :type 'hook)
381
382 (defcustom company-completion-finished-hook nil
383 "Hook run when company successfully completes.
384 The hook is called with the selected candidate as an argument.
385
386 If you indend to use it to post-process candidates from a specific
387 back-end, consider using the `post-completion' command instead."
388 :type 'hook)
389
390 (defcustom company-minimum-prefix-length 3
391 "The minimum prefix length for idle completion."
392 :type '(integer :tag "prefix length"))
393
394 (defcustom company-require-match 'company-explicit-action-p
395 "If enabled, disallow non-matching input.
396 This can be a function do determine if a match is required.
397
398 This can be overridden by the back-end, if it returns t or `never' to
399 `require-match'. `company-auto-complete' also takes precedence over this."
400 :type '(choice (const :tag "Off" nil)
401 (function :tag "Predicate function")
402 (const :tag "On, if user interaction took place"
403 'company-explicit-action-p)
404 (const :tag "On" t)))
405
406 (defcustom company-auto-complete nil
407 "Determines when to auto-complete.
408 If this is enabled, all characters from `company-auto-complete-chars'
409 trigger insertion of the selected completion candidate.
410 This can also be a function."
411 :type '(choice (const :tag "Off" nil)
412 (function :tag "Predicate function")
413 (const :tag "On, if user interaction took place"
414 'company-explicit-action-p)
415 (const :tag "On" t)))
416
417 (defcustom company-auto-complete-chars '(?\ ?\) ?.)
418 "Determines which characters trigger auto-completion.
419 See `company-auto-complete'. If this is a string, each string character
420 tiggers auto-completion. If it is a list of syntax description characters (see
421 `modify-syntax-entry'), all characters with that syntax auto-complete.
422
423 This can also be a function, which is called with the new input and should
424 return non-nil if company should auto-complete.
425
426 A character that is part of a valid candidate never triggers auto-completion."
427 :type '(choice (string :tag "Characters")
428 (set :tag "Syntax"
429 (const :tag "Whitespace" ?\ )
430 (const :tag "Symbol" ?_)
431 (const :tag "Opening parentheses" ?\()
432 (const :tag "Closing parentheses" ?\))
433 (const :tag "Word constituent" ?w)
434 (const :tag "Punctuation." ?.)
435 (const :tag "String quote." ?\")
436 (const :tag "Paired delimiter." ?$)
437 (const :tag "Expression quote or prefix operator." ?\')
438 (const :tag "Comment starter." ?<)
439 (const :tag "Comment ender." ?>)
440 (const :tag "Character-quote." ?/)
441 (const :tag "Generic string fence." ?|)
442 (const :tag "Generic comment fence." ?!))
443 (function :tag "Predicate function")))
444
445 (defcustom company-idle-delay .7
446 "The idle delay in seconds until completion starts automatically.
447 A value of nil means no idle completion, t means show candidates
448 immediately when a prefix of `company-minimum-prefix-length' is reached."
449 :type '(choice (const :tag "never (nil)" nil)
450 (const :tag "immediate (t)" t)
451 (number :tag "seconds")))
452
453 (defcustom company-begin-commands '(self-insert-command org-self-insert-command)
454 "A list of commands after which idle completion is allowed.
455 If this is t, it can show completions after any command. See
456 `company-idle-delay'.
457
458 Alternatively, any command with a non-nil `company-begin' property is
459 treated as if it was on this list."
460 :type '(choice (const :tag "Any command" t)
461 (const :tag "Self insert command" '(self-insert-command))
462 (repeat :tag "Commands" function)))
463
464 (defcustom company-show-numbers nil
465 "If enabled, show quick-access numbers for the first ten candidates."
466 :type '(choice (const :tag "off" nil)
467 (const :tag "on" t)))
468
469 (defcustom company-selection-wrap-around nil
470 "If enabled, selecting item before first or after last wraps around."
471 :type '(choice (const :tag "off" nil)
472 (const :tag "on" t)))
473
474 (defvar company-end-of-buffer-workaround t
475 "Work around a visualization bug when completing at the end of the buffer.
476 The work-around consists of adding a newline.")
477
478 ;;; mode ;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;
479
480 (defvar company-mode-map (make-sparse-keymap)
481 "Keymap used by `company-mode'.")
482
483 (defvar company-active-map
484 (let ((keymap (make-sparse-keymap)))
485 (define-key keymap "\e\e\e" 'company-abort)
486 (define-key keymap "\C-g" 'company-abort)
487 (define-key keymap (kbd "M-n") 'company-select-next)
488 (define-key keymap (kbd "M-p") 'company-select-previous)
489 (define-key keymap (kbd "<down>") 'company-select-next-or-abort)
490 (define-key keymap (kbd "<up>") 'company-select-previous-or-abort)
491 (define-key keymap [down-mouse-1] 'ignore)
492 (define-key keymap [down-mouse-3] 'ignore)
493 (define-key keymap [mouse-1] 'company-complete-mouse)
494 (define-key keymap [mouse-3] 'company-select-mouse)
495 (define-key keymap [up-mouse-1] 'ignore)
496 (define-key keymap [up-mouse-3] 'ignore)
497 (define-key keymap [return] 'company-complete-selection)
498 (define-key keymap (kbd "RET") 'company-complete-selection)
499 (define-key keymap [tab] 'company-complete-common)
500 (define-key keymap (kbd "TAB") 'company-complete-common)
501 (define-key keymap (kbd "<f1>") 'company-show-doc-buffer)
502 (define-key keymap "\C-w" 'company-show-location)
503 (define-key keymap "\C-s" 'company-search-candidates)
504 (define-key keymap "\C-\M-s" 'company-filter-candidates)
505 (dotimes (i 10)
506 (define-key keymap (vector (+ (aref (kbd "M-0") 0) i))
507 `(lambda () (interactive) (company-complete-number ,i))))
508
509 keymap)
510 "Keymap that is enabled during an active completion.")
511
512 (defvar company--disabled-backends nil)
513
514 (defun company-init-backend (backend)
515 (and (symbolp backend)
516 (not (fboundp backend))
517 (ignore-errors (require backend nil t)))
518
519 (if (or (symbolp backend)
520 (functionp backend))
521 (condition-case err
522 (progn
523 (funcall backend 'init)
524 (put backend 'company-init t))
525 (error
526 (put backend 'company-init 'failed)
527 (unless (memq backend company--disabled-backends)
528 (message "Company back-end '%s' could not be initialized:\n%s"
529 backend (error-message-string err)))
530 (pushnew backend company--disabled-backends)
531 nil))
532 (mapc 'company-init-backend backend)))
533
534 (defvar company-default-lighter " company")
535
536 (defvar company-lighter company-default-lighter)
537 (make-variable-buffer-local 'company-lighter)
538
539 ;;;###autoload
540 (define-minor-mode company-mode
541 "\"complete anything\"; is an in-buffer completion framework.
542 Completion starts automatically, depending on the values
543 `company-idle-delay' and `company-minimum-prefix-length'.
544
545 Completion can be controlled with the commands:
546 `company-complete-common', `company-complete-selection', `company-complete',
547 `company-select-next', `company-select-previous'. If these commands are
548 called before `company-idle-delay', completion will also start.
549
550 Completions can be searched with `company-search-candidates' or
551 `company-filter-candidates'. These can be used while completion is
552 inactive, as well.
553
554 The completion data is retrieved using `company-backends' and displayed
555 using `company-frontends'. If you want to start a specific back-end, call
556 it interactively or use `company-begin-backend'.
557
558 regular keymap (`company-mode-map'):
559
560 \\{company-mode-map}
561 keymap during active completions (`company-active-map'):
562
563 \\{company-active-map}"
564 nil company-lighter company-mode-map
565 (if company-mode
566 (progn
567 (add-hook 'pre-command-hook 'company-pre-command nil t)
568 (add-hook 'post-command-hook 'company-post-command nil t)
569 (mapc 'company-init-backend company-backends))
570 (remove-hook 'pre-command-hook 'company-pre-command t)
571 (remove-hook 'post-command-hook 'company-post-command t)
572 (company-cancel)
573 (kill-local-variable 'company-point)))
574
575 (defcustom company-global-modes t
576 "Modes for which `company-mode' mode is turned on by `global-company-mode'.
577 If nil, means no modes. If t, then all major modes have it turned on.
578 If a list, it should be a list of `major-mode' symbol names for which
579 `company-mode' should be automatically turned on. The sense of the list is
580 negated if it begins with `not'. For example:
581 (c-mode c++-mode)
582 means that `company-mode' is turned on for buffers in C and C++ modes only.
583 (not message-mode)
584 means that `company-mode' is always turned on except in `message-mode' buffers."
585 :type '(choice (const :tag "none" nil)
586 (const :tag "all" t)
587 (set :menu-tag "mode specific" :tag "modes"
588 :value (not)
589 (const :tag "Except" not)
590 (repeat :inline t (symbol :tag "mode")))))
591
592 ;;;###autoload
593 (define-globalized-minor-mode global-company-mode company-mode company-mode-on)
594
595 (defun company-mode-on ()
596 (when (and (not (or noninteractive (eq (aref (buffer-name) 0) ?\s)))
597 (cond ((eq company-global-modes t)
598 t)
599 ((eq (car-safe company-global-modes) 'not)
600 (not (memq major-mode (cdr company-global-modes))))
601 (t (memq major-mode company-global-modes))))
602 (company-mode 1)))
603
604 (defsubst company-assert-enabled ()
605 (unless company-mode
606 (company-uninstall-map)
607 (error "Company not enabled")))
608
609 ;;; keymaps ;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;
610
611 (defvar company-my-keymap nil)
612 (make-variable-buffer-local 'company-my-keymap)
613
614 (defvar company-emulation-alist '((t . nil)))
615
616 (defsubst company-enable-overriding-keymap (keymap)
617 (company-uninstall-map)
618 (setq company-my-keymap keymap))
619
620 (defun company-ensure-emulation-alist ()
621 (unless (eq 'company-emulation-alist (car emulation-mode-map-alists))
622 (setq emulation-mode-map-alists
623 (cons 'company-emulation-alist
624 (delq 'company-emulation-alist emulation-mode-map-alists)))))
625
626 (defun company-install-map ()
627 (unless (or (cdar company-emulation-alist)
628 (null company-my-keymap))
629 (setf (cdar company-emulation-alist) company-my-keymap)))
630
631 (defun company-uninstall-map ()
632 (setf (cdar company-emulation-alist) nil))
633
634 ;; Hack:
635 ;; Emacs calculates the active keymaps before reading the event. That means we
636 ;; cannot change the keymap from a timer. So we send a bogus command.
637 ;; XXX: Seems not to be needed anymore in Emacs 24.4
638 (defun company-ignore ()
639 (interactive)
640 (setq this-command last-command))
641
642 (global-set-key '[31415926] 'company-ignore)
643
644 (defun company-input-noop ()
645 (push 31415926 unread-command-events))
646
647 (defun company--column (&optional pos)
648 (save-excursion
649 (when pos (goto-char pos))
650 (save-restriction
651 (+ (save-excursion
652 (vertical-motion 0)
653 (narrow-to-region (point) (point-max))
654 (let ((prefix (get-text-property (point) 'line-prefix)))
655 (if prefix (length prefix) 0)))
656 (current-column)))))
657
658 (defun company--row (&optional pos)
659 (save-excursion
660 (when pos (goto-char pos))
661 (count-screen-lines (window-start)
662 (progn (vertical-motion 0) (point)))))
663
664 ;;; backends ;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;
665
666 (defvar company-backend nil)
667 (make-variable-buffer-local 'company-backend)
668
669 (defun company-grab (regexp &optional expression limit)
670 (when (looking-back regexp limit)
671 (or (match-string-no-properties (or expression 0)) "")))
672
673 (defun company-grab-line (regexp &optional expression)
674 (company-grab regexp expression (point-at-bol)))
675
676 (defun company-grab-symbol ()
677 (if (looking-at "\\_>")
678 (buffer-substring (point) (save-excursion (skip-syntax-backward "w_")
679 (point)))
680 (unless (and (char-after) (memq (char-syntax (char-after)) '(?w ?_)))
681 "")))
682
683 (defun company-grab-word ()
684 (if (looking-at "\\>")
685 (buffer-substring (point) (save-excursion (skip-syntax-backward "w")
686 (point)))
687 (unless (and (char-after) (eq (char-syntax (char-after)) ?w))
688 "")))
689
690 (defun company-in-string-or-comment ()
691 (let ((ppss (syntax-ppss)))
692 (or (car (setq ppss (nthcdr 3 ppss)))
693 (car (setq ppss (cdr ppss)))
694 (nth 3 ppss))))
695
696 (if (fboundp 'locate-dominating-file)
697 (defalias 'company-locate-dominating-file 'locate-dominating-file)
698 (defun company-locate-dominating-file (file name)
699 (catch 'root
700 (let ((dir (file-name-directory file))
701 (prev-dir nil))
702 (while (not (equal dir prev-dir))
703 (when (file-exists-p (expand-file-name name dir))
704 (throw 'root dir))
705 (setq prev-dir dir
706 dir (file-name-directory (directory-file-name dir))))))))
707
708 (defun company-call-backend (&rest args)
709 (if (functionp company-backend)
710 (apply company-backend args)
711 (apply 'company--multi-backend-adapter company-backend args)))
712
713 (defun company--multi-backend-adapter (backends command &rest args)
714 (let ((backends (loop for b in backends
715 when (not (and (symbolp b)
716 (eq 'failed (get b 'company-init))))
717 collect b)))
718 (case command
719 (candidates
720 (loop for backend in backends
721 when (equal (funcall backend 'prefix)
722 (car args))
723 append (apply backend 'candidates args)))
724 (sorted nil)
725 (duplicates t)
726 (otherwise
727 (let (value)
728 (dolist (backend backends)
729 (when (setq value (apply backend command args))
730 (return value))))))))
731
732 ;;; completion mechanism ;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;
733
734 (defvar company-prefix nil)
735 (make-variable-buffer-local 'company-prefix)
736
737 (defvar company-candidates nil)
738 (make-variable-buffer-local 'company-candidates)
739
740 (defvar company-candidates-length nil)
741 (make-variable-buffer-local 'company-candidates-length)
742
743 (defvar company-candidates-cache nil)
744 (make-variable-buffer-local 'company-candidates-cache)
745
746 (defvar company-candidates-predicate nil)
747 (make-variable-buffer-local 'company-candidates-predicate)
748
749 (defvar company-common nil)
750 (make-variable-buffer-local 'company-common)
751
752 (defvar company-selection 0)
753 (make-variable-buffer-local 'company-selection)
754
755 (defvar company-selection-changed nil)
756 (make-variable-buffer-local 'company-selection-changed)
757
758 (defvar company--explicit-action nil
759 "Non-nil, if explicit completion took place.")
760 (make-variable-buffer-local 'company--explicit-action)
761
762 (defvar company--auto-completion nil
763 "Non-nil when current candidate is being inserted automatically.
764 Controlled by `company-auto-complete'.")
765
766 (defvar company--point-max nil)
767 (make-variable-buffer-local 'company--point-max)
768
769 (defvar company-point nil)
770 (make-variable-buffer-local 'company-point)
771
772 (defvar company-timer nil)
773
774 (defvar company-added-newline nil)
775 (make-variable-buffer-local 'company-added-newline)
776
777 (defsubst company-strip-prefix (str)
778 (substring str (length company-prefix)))
779
780 (defun company--insert-candidate (candidate)
781 ;; XXX: Return value we check here is subject to change.
782 (set-text-properties 0 (length candidate) nil candidate)
783 (if (eq (company-call-backend 'ignore-case) 'keep-prefix)
784 (insert (company-strip-prefix candidate))
785 (delete-region (- (point) (length company-prefix)) (point))
786 (insert candidate)))
787
788 (defmacro company-with-candidate-inserted (candidate &rest body)
789 "Evaluate BODY with CANDIDATE temporarily inserted.
790 This is a tool for back-ends that need candidates inserted before they
791 can retrieve meta-data for them."
792 (declare (indent 1))
793 `(let ((inhibit-modification-hooks t)
794 (inhibit-point-motion-hooks t)
795 (modified-p (buffer-modified-p)))
796 (company--insert-candidate ,candidate)
797 (unwind-protect
798 (progn ,@body)
799 (delete-region company-point (point)))))
800
801 (defun company-explicit-action-p ()
802 "Return whether explicit completion action was taken by the user."
803 (or company--explicit-action
804 company-selection-changed))
805
806 (defun company-reformat (candidate)
807 ;; company-ispell needs this, because the results are always lower-case
808 ;; It's mory efficient to fix it only when they are displayed.
809 ;; FIXME: Adopt the current text's capitalization instead?
810 (if (eq (company-call-backend 'ignore-case) 'keep-prefix)
811 (concat company-prefix (substring candidate (length company-prefix)))
812 candidate))
813
814 (defun company--should-complete ()
815 (and (not (or buffer-read-only overriding-terminal-local-map
816 overriding-local-map))
817 ;; Check if in the middle of entering a key combination.
818 (or (equal (this-command-keys-vector) [])
819 (not (keymapp (key-binding (this-command-keys-vector)))))
820 (eq company-idle-delay t)
821 (or (eq t company-begin-commands)
822 (memq this-command company-begin-commands)
823 (and (symbolp this-command) (get this-command 'company-begin)))
824 (not (and transient-mark-mode mark-active))))
825
826 (defun company-call-frontends (command)
827 (dolist (frontend company-frontends)
828 (condition-case err
829 (funcall frontend command)
830 (error (error "Company: Front-end %s error \"%s\" on command %s"
831 frontend (error-message-string err) command)))))
832
833 (defun company-set-selection (selection &optional force-update)
834 (setq selection
835 (if company-selection-wrap-around
836 (mod selection company-candidates-length)
837 (max 0 (min (1- company-candidates-length) selection))))
838 (when (or force-update (not (equal selection company-selection)))
839 (setq company-selection selection
840 company-selection-changed t)
841 (company-call-frontends 'update)))
842
843 (defun company-apply-predicate (candidates predicate)
844 (let (new)
845 (dolist (c candidates)
846 (when (funcall predicate c)
847 (push c new)))
848 (nreverse new)))
849
850 (defun company-update-candidates (candidates)
851 (setq company-candidates-length (length candidates))
852 (if (> company-selection 0)
853 ;; Try to restore the selection
854 (let ((selected (nth company-selection company-candidates)))
855 (setq company-selection 0
856 company-candidates candidates)
857 (when selected
858 (while (and candidates (string< (pop candidates) selected))
859 (incf company-selection))
860 (unless candidates
861 ;; Make sure selection isn't out of bounds.
862 (setq company-selection (min (1- company-candidates-length)
863 company-selection)))))
864 (setq company-selection 0
865 company-candidates candidates))
866 ;; Save in cache:
867 (push (cons company-prefix company-candidates) company-candidates-cache)
868 ;; Calculate common.
869 (let ((completion-ignore-case (company-call-backend 'ignore-case)))
870 ;; We want to support non-prefix completion, so filtering is the
871 ;; responsibility of each respective backend, not ours.
872 ;; On the other hand, we don't want to replace non-prefix input in
873 ;; `company-complete-common'.
874 (setq company-common
875 (if (cdr company-candidates)
876 (company--safe-candidate
877 (try-completion company-prefix company-candidates))
878 (car company-candidates)))))
879
880 (defun company--safe-candidate (str)
881 (or (company-call-backend 'crop str)
882 str))
883
884 (defun company-calculate-candidates (prefix)
885 (let ((candidates (cdr (assoc prefix company-candidates-cache)))
886 (ignore-case (company-call-backend 'ignore-case)))
887 (or candidates
888 (when company-candidates-cache
889 (let ((len (length prefix))
890 (completion-ignore-case ignore-case)
891 prev)
892 (dotimes (i (1+ len))
893 (when (setq prev (cdr (assoc (substring prefix 0 (- len i))
894 company-candidates-cache)))
895 (setq candidates (all-completions prefix prev))
896 (return t)))))
897 ;; no cache match, call back-end
898 (progn
899 (setq candidates (company-call-backend 'candidates prefix))
900 (when company-candidates-predicate
901 (setq candidates
902 (company-apply-predicate candidates
903 company-candidates-predicate)))
904 (unless (company-call-backend 'sorted)
905 (setq candidates (sort candidates 'string<)))
906 (when (company-call-backend 'duplicates)
907 ;; strip duplicates
908 (let ((c2 candidates))
909 (while c2
910 (setcdr c2 (progn (while (equal (pop c2) (car c2)))
911 c2)))))))
912 (setq candidates (company--transform-candidates candidates))
913 (when candidates
914 (if (or (cdr candidates)
915 (not (eq t (compare-strings (car candidates) nil nil
916 prefix nil nil ignore-case))))
917 (company--transform-candidates candidates)
918 ;; Already completed and unique; don't start.
919 t))))
920
921 (defun company--transform-candidates (candidates)
922 (let ((c candidates))
923 (dolist (tr company-transformers)
924 (setq c (funcall tr c)))
925 c))
926
927 (defun company-sort-by-occurrence (candidates)
928 "Sort CANDIDATES according to their occurrences.
929 Searches for each in the currently visible part of the current buffer and
930 gives priority to the closest ones above point, then closest ones below
931 point. The rest of the list is appended unchanged.
932 Keywords and function definition names are ignored."
933 (let* (occurs
934 (noccurs
935 (delete-if
936 (lambda (candidate)
937 (when (or
938 (save-excursion
939 (and (zerop (forward-line -1))
940 (search-backward candidate (window-start) t)))
941 (save-excursion
942 (search-forward candidate (window-end) t)))
943 (let ((beg (match-beginning 0))
944 (end (match-end 0)))
945 (when (save-excursion
946 (goto-char end)
947 (and (not (memq (get-text-property (point) 'face)
948 '(font-lock-function-name-face
949 font-lock-keyword-face)))
950 (let* ((prefix (company-call-backend 'prefix))
951 (prefix (or (car-safe prefix) prefix)))
952 (and (stringp prefix)
953 (= (length prefix) (- end beg))))))
954 (push (cons candidate (if (< beg (point))
955 (- (point) end)
956 (- beg (window-start))))
957 occurs)
958 t))))
959 candidates)))
960 (nconc
961 (mapcar #'car (sort occurs (lambda (e1 e2) (< (cdr e1) (cdr e2)))))
962 noccurs)))
963
964 (defun company-idle-begin (buf win tick pos)
965 (and company-mode
966 (eq buf (current-buffer))
967 (eq win (selected-window))
968 (eq tick (buffer-chars-modified-tick))
969 (eq pos (point))
970 (not company-candidates)
971 (not (equal (point) company-point))
972 (let ((company-idle-delay t)
973 (company-begin-commands t))
974 (company-begin)
975 (when company-candidates
976 (when (version< emacs-version "24.3.50")
977 (company-input-noop))
978 (company-post-command)))))
979
980 (defun company-auto-begin ()
981 (company-assert-enabled)
982 (and company-mode
983 (not company-candidates)
984 (let ((company-idle-delay t)
985 (company-minimum-prefix-length 0)
986 (company-begin-commands t))
987 (company-begin)))
988 ;; Return non-nil if active.
989 company-candidates)
990
991 (defun company-manual-begin ()
992 (interactive)
993 (setq company--explicit-action t)
994 (unwind-protect
995 (company-auto-begin)
996 (unless company-candidates
997 (setq company--explicit-action nil))))
998
999 (defun company-other-backend (&optional backward)
1000 (interactive (list current-prefix-arg))
1001 (company-assert-enabled)
1002 (if company-backend
1003 (let* ((after (cdr (member company-backend company-backends)))
1004 (before (cdr (member company-backend (reverse company-backends))))
1005 (next (if backward
1006 (append before (reverse after))
1007 (append after (reverse before)))))
1008 (company-cancel)
1009 (dolist (backend next)
1010 (when (ignore-errors (company-begin-backend backend))
1011 (return t))))
1012 (company-manual-begin))
1013 (unless company-candidates
1014 (error "No other back-end")))
1015
1016 (defun company-require-match-p ()
1017 (let ((backend-value (company-call-backend 'require-match)))
1018 (or (eq backend-value t)
1019 (and (not (eq backend-value 'never))
1020 (if (functionp company-require-match)
1021 (funcall company-require-match)
1022 (eq company-require-match t))))))
1023
1024 (defun company-auto-complete-p (input)
1025 "Return non-nil, if input starts with punctuation or parentheses."
1026 (and (if (functionp company-auto-complete)
1027 (funcall company-auto-complete)
1028 company-auto-complete)
1029 (if (functionp company-auto-complete-chars)
1030 (funcall company-auto-complete-chars input)
1031 (if (consp company-auto-complete-chars)
1032 (memq (char-syntax (string-to-char input))
1033 company-auto-complete-chars)
1034 (string-match (substring input 0 1) company-auto-complete-chars)))))
1035
1036 (defun company--incremental-p ()
1037 (and (> (point) company-point)
1038 (> (point-max) company--point-max)
1039 (not (eq this-command 'backward-delete-char-untabify))
1040 (equal (buffer-substring (- company-point (length company-prefix))
1041 company-point)
1042 company-prefix)))
1043
1044 (defsubst company--string-incremental-p (old-prefix new-prefix)
1045 (and (> (length new-prefix) (length old-prefix))
1046 (equal old-prefix (substring new-prefix 0 (length old-prefix)))))
1047
1048 (defun company--continue-failed (new-prefix)
1049 (when (company--incremental-p)
1050 (let ((input (buffer-substring-no-properties (point) company-point)))
1051 (cond
1052 ((company-auto-complete-p input)
1053 ;; auto-complete
1054 (save-excursion
1055 (goto-char company-point)
1056 (let ((company--auto-completion t))
1057 (company-complete-selection))
1058 nil))
1059 ((and (company--string-incremental-p company-prefix new-prefix)
1060 (company-require-match-p))
1061 ;; wrong incremental input, but required match
1062 (delete-char (- (length input)))
1063 (ding)
1064 (message "Matching input is required")
1065 company-candidates)
1066 ((equal company-prefix (car company-candidates))
1067 ;; last input was actually success
1068 (company-cancel company-prefix)
1069 nil)))))
1070
1071 (defun company--good-prefix-p (prefix)
1072 (and (or (company-explicit-action-p)
1073 (unless (eq prefix 'stop)
1074 (or (eq (cdr-safe prefix) t)
1075 (>= (or (cdr-safe prefix) (length prefix))
1076 company-minimum-prefix-length))))
1077 (stringp (or (car-safe prefix) prefix))))
1078
1079 (defun company--continue ()
1080 (when (company-call-backend 'no-cache company-prefix)
1081 ;; Don't complete existing candidates, fetch new ones.
1082 (setq company-candidates-cache nil))
1083 (let* ((new-prefix (company-call-backend 'prefix))
1084 (c (when (and (company--good-prefix-p new-prefix)
1085 (setq new-prefix (or (car-safe new-prefix) new-prefix))
1086 (= (- (point) (length new-prefix))
1087 (- company-point (length company-prefix))))
1088 (setq new-prefix (or (car-safe new-prefix) new-prefix))
1089 (company-calculate-candidates new-prefix))))
1090 (or (cond
1091 ((eq c t)
1092 ;; t means complete/unique.
1093 (company-cancel new-prefix)
1094 nil)
1095 ((consp c)
1096 ;; incremental match
1097 (setq company-prefix new-prefix)
1098 (company-update-candidates c)
1099 c)
1100 (t (company--continue-failed new-prefix)))
1101 (company-cancel))))
1102
1103 (defun company--begin-new ()
1104 (let (prefix c)
1105 (dolist (backend (if company-backend
1106 ;; prefer manual override
1107 (list company-backend)
1108 company-backends))
1109 (setq prefix
1110 (if (or (symbolp backend)
1111 (functionp backend))
1112 (when (or (not (symbolp backend))
1113 (eq t (get backend 'company-init))
1114 (unless (get backend 'company-init)
1115 (company-init-backend backend)))
1116 (funcall backend 'prefix))
1117 (company--multi-backend-adapter backend 'prefix)))
1118 (when prefix
1119 (when (company--good-prefix-p prefix)
1120 (setq prefix (or (car-safe prefix) prefix)
1121 company-backend backend
1122 c (company-calculate-candidates prefix))
1123 ;; t means complete/unique. We don't start, so no hooks.
1124 (if (not (consp c))
1125 (when company--explicit-action
1126 (message "No completion found"))
1127 (setq company-prefix prefix)
1128 (when (symbolp backend)
1129 (setq company-lighter (concat " " (symbol-name backend))))
1130 (company-update-candidates c)
1131 (run-hook-with-args 'company-completion-started-hook
1132 (company-explicit-action-p))
1133 (company-call-frontends 'show)))
1134 (return c)))))
1135
1136 (defun company-begin ()
1137 (or (and company-candidates (company--continue))
1138 (and (company--should-complete) (company--begin-new)))
1139 (when company-candidates
1140 (when (and company-end-of-buffer-workaround (eobp))
1141 (save-excursion (insert "\n"))
1142 (setq company-added-newline (buffer-chars-modified-tick)))
1143 (setq company-point (point)
1144 company--point-max (point-max))
1145 (company-ensure-emulation-alist)
1146 (company-enable-overriding-keymap company-active-map)
1147 (company-call-frontends 'update)))
1148
1149 (defun company-cancel (&optional result)
1150 (and company-added-newline
1151 (> (point-max) (point-min))
1152 (let ((tick (buffer-chars-modified-tick)))
1153 (delete-region (1- (point-max)) (point-max))
1154 (equal tick company-added-newline))
1155 ;; Only set unmodified when tick remained the same since insert.
1156 (set-buffer-modified-p nil))
1157 (when company-prefix
1158 (if (stringp result)
1159 (progn
1160 (company-call-backend 'pre-completion result)
1161 (run-hook-with-args 'company-completion-finished-hook result)
1162 (company-call-backend 'post-completion result))
1163 (run-hook-with-args 'company-completion-cancelled-hook result)))
1164 (setq company-added-newline nil
1165 company-backend nil
1166 company-prefix nil
1167 company-candidates nil
1168 company-candidates-length nil
1169 company-candidates-cache nil
1170 company-candidates-predicate nil
1171 company-common nil
1172 company-selection 0
1173 company-selection-changed nil
1174 company--explicit-action nil
1175 company-lighter company-default-lighter
1176 company--point-max nil
1177 company-point nil)
1178 (when company-timer
1179 (cancel-timer company-timer))
1180 (company-search-mode 0)
1181 (company-call-frontends 'hide)
1182 (company-enable-overriding-keymap nil))
1183
1184 (defun company-abort ()
1185 (interactive)
1186 (company-cancel t)
1187 ;; Don't start again, unless started manually.
1188 (setq company-point (point)))
1189
1190 (defun company-finish (result)
1191 (company--insert-candidate result)
1192 (company-cancel result)
1193 ;; Don't start again, unless started manually.
1194 (setq company-point (point)))
1195
1196 (defsubst company-keep (command)
1197 (and (symbolp command) (get command 'company-keep)))
1198
1199 (defun company-pre-command ()
1200 (unless (company-keep this-command)
1201 (condition-case err
1202 (when company-candidates
1203 (company-call-frontends 'pre-command))
1204 (error (message "Company: An error occurred in pre-command")
1205 (message "%s" (error-message-string err))
1206 (company-cancel))))
1207 (when company-timer
1208 (cancel-timer company-timer)
1209 (setq company-timer nil))
1210 (company-uninstall-map))
1211
1212 (defun company-post-command ()
1213 (unless (company-keep this-command)
1214 (condition-case err
1215 (progn
1216 (unless (equal (point) company-point)
1217 (company-begin))
1218 (if company-candidates
1219 (company-call-frontends 'post-command)
1220 (and (numberp company-idle-delay)
1221 (or (eq t company-begin-commands)
1222 (memq this-command company-begin-commands))
1223 (setq company-timer
1224 (run-with-timer company-idle-delay nil
1225 'company-idle-begin
1226 (current-buffer) (selected-window)
1227 (buffer-chars-modified-tick) (point))))))
1228 (error (message "Company: An error occurred in post-command")
1229 (message "%s" (error-message-string err))
1230 (company-cancel))))
1231 (company-install-map))
1232
1233 ;;; search ;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;
1234
1235 (defvar company-search-string nil)
1236 (make-variable-buffer-local 'company-search-string)
1237
1238 (defvar company-search-lighter " Search: \"\"")
1239 (make-variable-buffer-local 'company-search-lighter)
1240
1241 (defvar company-search-old-map nil)
1242 (make-variable-buffer-local 'company-search-old-map)
1243
1244 (defvar company-search-old-selection 0)
1245 (make-variable-buffer-local 'company-search-old-selection)
1246
1247 (defun company-search (text lines)
1248 (let ((quoted (regexp-quote text))
1249 (i 0))
1250 (dolist (line lines)
1251 (when (string-match quoted line (length company-prefix))
1252 (return i))
1253 (incf i))))
1254
1255 (defun company-search-printing-char ()
1256 (interactive)
1257 (company-search-assert-enabled)
1258 (setq company-search-string
1259 (concat (or company-search-string "") (string last-command-event))
1260 company-search-lighter (concat " Search: \"" company-search-string
1261 "\""))
1262 (let ((pos (company-search company-search-string
1263 (nthcdr company-selection company-candidates))))
1264 (if (null pos)
1265 (ding)
1266 (company-set-selection (+ company-selection pos) t))))
1267
1268 (defun company-search-repeat-forward ()
1269 "Repeat the incremental search in completion candidates forward."
1270 (interactive)
1271 (company-search-assert-enabled)
1272 (let ((pos (company-search company-search-string
1273 (cdr (nthcdr company-selection
1274 company-candidates)))))
1275 (if (null pos)
1276 (ding)
1277 (company-set-selection (+ company-selection pos 1) t))))
1278
1279 (defun company-search-repeat-backward ()
1280 "Repeat the incremental search in completion candidates backwards."
1281 (interactive)
1282 (company-search-assert-enabled)
1283 (let ((pos (company-search company-search-string
1284 (nthcdr (- company-candidates-length
1285 company-selection)
1286 (reverse company-candidates)))))
1287 (if (null pos)
1288 (ding)
1289 (company-set-selection (- company-selection pos 1) t))))
1290
1291 (defun company-create-match-predicate ()
1292 (setq company-candidates-predicate
1293 `(lambda (candidate)
1294 ,(if company-candidates-predicate
1295 `(and (string-match ,company-search-string candidate)
1296 (funcall ,company-candidates-predicate
1297 candidate))
1298 `(string-match ,company-search-string candidate))))
1299 (company-update-candidates
1300 (company-apply-predicate company-candidates company-candidates-predicate))
1301 ;; Invalidate cache.
1302 (setq company-candidates-cache (cons company-prefix company-candidates)))
1303
1304 (defun company-filter-printing-char ()
1305 (interactive)
1306 (company-search-assert-enabled)
1307 (company-search-printing-char)
1308 (company-create-match-predicate)
1309 (company-call-frontends 'update))
1310
1311 (defun company-search-kill-others ()
1312 "Limit the completion candidates to the ones matching the search string."
1313 (interactive)
1314 (company-search-assert-enabled)
1315 (company-create-match-predicate)
1316 (company-search-mode 0)
1317 (company-call-frontends 'update))
1318
1319 (defun company-search-abort ()
1320 "Abort searching the completion candidates."
1321 (interactive)
1322 (company-search-assert-enabled)
1323 (company-set-selection company-search-old-selection t)
1324 (company-search-mode 0))
1325
1326 (defun company-search-other-char ()
1327 (interactive)
1328 (company-search-assert-enabled)
1329 (company-search-mode 0)
1330 (company--unread-last-input))
1331
1332 (defvar company-search-map
1333 (let ((i 0)
1334 (keymap (make-keymap)))
1335 (if (fboundp 'max-char)
1336 (set-char-table-range (nth 1 keymap) (cons #x100 (max-char))
1337 'company-search-printing-char)
1338 (with-no-warnings
1339 ;; obsolete in Emacs 23
1340 (let ((l (generic-character-list))
1341 (table (nth 1 keymap)))
1342 (while l
1343 (set-char-table-default table (car l) 'company-search-printing-char)
1344 (setq l (cdr l))))))
1345 (define-key keymap [t] 'company-search-other-char)
1346 (while (< i ?\s)
1347 (define-key keymap (make-string 1 i) 'company-search-other-char)
1348 (incf i))
1349 (while (< i 256)
1350 (define-key keymap (vector i) 'company-search-printing-char)
1351 (incf i))
1352 (let ((meta-map (make-sparse-keymap)))
1353 (define-key keymap (char-to-string meta-prefix-char) meta-map)
1354 (define-key keymap [escape] meta-map))
1355 (define-key keymap (vector meta-prefix-char t) 'company-search-other-char)
1356 (define-key keymap "\e\e\e" 'company-search-other-char)
1357 (define-key keymap [escape escape escape] 'company-search-other-char)
1358
1359 (define-key keymap "\C-g" 'company-search-abort)
1360 (define-key keymap "\C-s" 'company-search-repeat-forward)
1361 (define-key keymap "\C-r" 'company-search-repeat-backward)
1362 (define-key keymap "\C-o" 'company-search-kill-others)
1363 keymap)
1364 "Keymap used for incrementally searching the completion candidates.")
1365
1366 (define-minor-mode company-search-mode
1367 "Search mode for completion candidates.
1368 Don't start this directly, use `company-search-candidates' or
1369 `company-filter-candidates'."
1370 nil company-search-lighter nil
1371 (if company-search-mode
1372 (if (company-manual-begin)
1373 (progn
1374 (setq company-search-old-selection company-selection)
1375 (company-call-frontends 'update))
1376 (setq company-search-mode nil))
1377 (kill-local-variable 'company-search-string)
1378 (kill-local-variable 'company-search-lighter)
1379 (kill-local-variable 'company-search-old-selection)
1380 (company-enable-overriding-keymap company-active-map)))
1381
1382 (defun company-search-assert-enabled ()
1383 (company-assert-enabled)
1384 (unless company-search-mode
1385 (company-uninstall-map)
1386 (error "Company not in search mode")))
1387
1388 (defun company-search-candidates ()
1389 "Start searching the completion candidates incrementally.
1390
1391 \\<company-search-map>Search can be controlled with the commands:
1392 - `company-search-repeat-forward' (\\[company-search-repeat-forward])
1393 - `company-search-repeat-backward' (\\[company-search-repeat-backward])
1394 - `company-search-abort' (\\[company-search-abort])
1395
1396 Regular characters are appended to the search string.
1397
1398 The command `company-search-kill-others' (\\[company-search-kill-others])
1399 uses the search string to limit the completion candidates."
1400 (interactive)
1401 (company-search-mode 1)
1402 (company-enable-overriding-keymap company-search-map))
1403
1404 (defvar company-filter-map
1405 (let ((keymap (make-keymap)))
1406 (define-key keymap [remap company-search-printing-char]
1407 'company-filter-printing-char)
1408 (set-keymap-parent keymap company-search-map)
1409 keymap)
1410 "Keymap used for incrementally searching the completion candidates.")
1411
1412 (defun company-filter-candidates ()
1413 "Start filtering the completion candidates incrementally.
1414 This works the same way as `company-search-candidates' immediately
1415 followed by `company-search-kill-others' after each input."
1416 (interactive)
1417 (company-search-mode 1)
1418 (company-enable-overriding-keymap company-filter-map))
1419
1420 ;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;
1421
1422 (defun company-select-next ()
1423 "Select the next candidate in the list."
1424 (interactive)
1425 (when (company-manual-begin)
1426 (company-set-selection (1+ company-selection))))
1427
1428 (defun company-select-previous ()
1429 "Select the previous candidate in the list."
1430 (interactive)
1431 (when (company-manual-begin)
1432 (company-set-selection (1- company-selection))))
1433
1434 (defun company-select-next-or-abort ()
1435 "Select the next candidate if more than one, else abort
1436 and invoke the normal binding."
1437 (interactive)
1438 (if (> company-candidates-length 1)
1439 (company-select-next)
1440 (company-abort)
1441 (company--unread-last-input)))
1442
1443 (defun company-select-previous-or-abort ()
1444 "Select the previous candidate if more than one, else abort
1445 and invoke the normal binding."
1446 (interactive)
1447 (if (> company-candidates-length 1)
1448 (company-select-previous)
1449 (company-abort)
1450 (company--unread-last-input)))
1451
1452 (defvar company-pseudo-tooltip-overlay)
1453
1454 (defvar company-tooltip-offset)
1455
1456 (defun company--inside-tooltip-p (event-col-row row height)
1457 (let* ((ovl company-pseudo-tooltip-overlay)
1458 (column (overlay-get ovl 'company-column))
1459 (width (overlay-get ovl 'company-width))
1460 (evt-col (car event-col-row))
1461 (evt-row (cdr event-col-row)))
1462 (and (>= evt-col column)
1463 (< evt-col (+ column width))
1464 (if (> height 0)
1465 (and (> evt-row row)
1466 (<= evt-row (+ row height) ))
1467 (and (< evt-row row)
1468 (>= evt-row (+ row height)))))))
1469
1470 (defun company--event-col-row (event)
1471 (let* ((col-row (posn-actual-col-row (event-start event)))
1472 (col (car col-row))
1473 (row (cdr col-row)))
1474 (incf col (window-hscroll))
1475 (and header-line-format
1476 (version< "24" emacs-version)
1477 (decf row))
1478 (cons col row)))
1479
1480 (defun company-select-mouse (event)
1481 "Select the candidate picked by the mouse."
1482 (interactive "e")
1483 (let ((event-col-row (company--event-col-row event))
1484 (ovl-row (company--row))
1485 (ovl-height (and company-pseudo-tooltip-overlay
1486 (min (overlay-get company-pseudo-tooltip-overlay
1487 'company-height)
1488 company-candidates-length))))
1489 (if (and ovl-height
1490 (company--inside-tooltip-p event-col-row ovl-row ovl-height))
1491 (progn
1492 (company-set-selection (+ (cdr event-col-row)
1493 (1- company-tooltip-offset)
1494 (if (and (eq company-tooltip-offset-display 'lines)
1495 (not (zerop company-tooltip-offset)))
1496 -1 0)
1497 (- ovl-row)
1498 (if (< ovl-height 0)
1499 (- 1 ovl-height)
1500 0)))
1501 t)
1502 (company-abort)
1503 (company--unread-last-input)
1504 nil)))
1505
1506 (defun company-complete-mouse (event)
1507 "Insert the candidate picked by the mouse."
1508 (interactive "e")
1509 (when (company-select-mouse event)
1510 (company-complete-selection)))
1511
1512 (defun company-complete-selection ()
1513 "Insert the selected candidate."
1514 (interactive)
1515 (when (company-manual-begin)
1516 (let ((result (nth company-selection company-candidates)))
1517 (when company--auto-completion
1518 (setq result (company--safe-candidate result)))
1519 (company-finish result))))
1520
1521 (defun company-complete-common ()
1522 "Insert the common part of all candidates."
1523 (interactive)
1524 (when (company-manual-begin)
1525 (if (and (not (cdr company-candidates))
1526 (equal company-common (car company-candidates)))
1527 (company-complete-selection)
1528 (when company-common
1529 (company--insert-candidate company-common)))))
1530
1531 (defun company-complete ()
1532 "Insert the common part of all candidates or the current selection.
1533 The first time this is called, the common part is inserted, the second
1534 time, or when the selection has been changed, the selected candidate is
1535 inserted."
1536 (interactive)
1537 (when (company-manual-begin)
1538 (if (or company-selection-changed
1539 (eq last-command 'company-complete-common))
1540 (call-interactively 'company-complete-selection)
1541 (call-interactively 'company-complete-common)
1542 (setq this-command 'company-complete-common))))
1543
1544 (defun company-complete-number (n)
1545 "Insert the Nth candidate.
1546 To show the number next to the candidates in some back-ends, enable
1547 `company-show-numbers'."
1548 (when (company-manual-begin)
1549 (and (< n 1) (> n company-candidates-length)
1550 (error "No candidate number %d" n))
1551 (decf n)
1552 (company-finish (nth n company-candidates))))
1553
1554 ;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;
1555
1556 (defconst company-space-strings-limit 100)
1557
1558 (defconst company-space-strings
1559 (let (lst)
1560 (dotimes (i company-space-strings-limit)
1561 (push (make-string (- company-space-strings-limit 1 i) ?\ ) lst))
1562 (apply 'vector lst)))
1563
1564 (defun company-space-string (len)
1565 (if (< len company-space-strings-limit)
1566 (aref company-space-strings len)
1567 (make-string len ?\ )))
1568
1569 (defun company-safe-substring (str from &optional to)
1570 (if (> from (string-width str))
1571 ""
1572 (with-temp-buffer
1573 (insert str)
1574 (move-to-column from)
1575 (let ((beg (point)))
1576 (if to
1577 (progn
1578 (move-to-column to)
1579 (concat (buffer-substring beg (point))
1580 (let ((padding (- to (current-column))))
1581 (when (> padding 0)
1582 (company-space-string padding)))))
1583 (buffer-substring beg (point-max)))))))
1584
1585 ;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;
1586
1587 (defvar company-last-metadata nil)
1588 (make-variable-buffer-local 'company-last-metadata)
1589
1590 (defun company-fetch-metadata ()
1591 (let ((selected (nth company-selection company-candidates)))
1592 (unless (equal selected (car company-last-metadata))
1593 (setq company-last-metadata
1594 (cons selected (company-call-backend 'meta selected))))
1595 (cdr company-last-metadata)))
1596
1597 (defun company-doc-buffer (&optional string)
1598 (with-current-buffer (get-buffer-create "*company-documentation*")
1599 (erase-buffer)
1600 (when string
1601 (save-excursion
1602 (insert string)))
1603 (current-buffer)))
1604
1605 (defvar company--electric-commands
1606 '(scroll-other-window scroll-other-window-down)
1607 "List of Commands that won't break out of electric commands.")
1608
1609 (defmacro company--electric-do (&rest body)
1610 (declare (indent 0) (debug t))
1611 `(when (company-manual-begin)
1612 (save-window-excursion
1613 (let ((height (window-height))
1614 (row (company--row))
1615 cmd)
1616 ,@body
1617 (and (< (window-height) height)
1618 (< (- (window-height) row 2) company-tooltip-limit)
1619 (recenter (- (window-height) row 2)))
1620 (while (memq (setq cmd (key-binding (vector (list (read-event)))))
1621 company--electric-commands)
1622 (call-interactively cmd))
1623 (company--unread-last-input)))))
1624
1625 (defun company--unread-last-input ()
1626 (when last-input-event
1627 (clear-this-command-keys t)
1628 (setq unread-command-events (list last-input-event))))
1629
1630 (defun company-show-doc-buffer ()
1631 "Temporarily show the documentation buffer for the selection."
1632 (interactive)
1633 (company--electric-do
1634 (let* ((selected (nth company-selection company-candidates))
1635 (doc-buffer (or (company-call-backend 'doc-buffer selected)
1636 (error "No documentation available"))))
1637 (with-current-buffer doc-buffer
1638 (goto-char (point-min)))
1639 (display-buffer doc-buffer t))))
1640 (put 'company-show-doc-buffer 'company-keep t)
1641
1642 (defun company-show-location ()
1643 "Temporarily display a buffer showing the selected candidate in context."
1644 (interactive)
1645 (company--electric-do
1646 (let* ((selected (nth company-selection company-candidates))
1647 (location (company-call-backend 'location selected))
1648 (pos (or (cdr location) (error "No location available")))
1649 (buffer (or (and (bufferp (car location)) (car location))
1650 (find-file-noselect (car location) t))))
1651 (with-selected-window (display-buffer buffer t)
1652 (save-restriction
1653 (widen)
1654 (if (bufferp (car location))
1655 (goto-char pos)
1656 (goto-char (point-min))
1657 (forward-line (1- pos))))
1658 (set-window-start nil (point))))))
1659 (put 'company-show-location 'company-keep t)
1660
1661 ;;; package functions ;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;
1662
1663 (defvar company-callback nil)
1664 (make-variable-buffer-local 'company-callback)
1665
1666 (defvar company-begin-with-marker nil)
1667 (make-variable-buffer-local 'company-begin-with-marker)
1668
1669 (defun company-remove-callback (&optional ignored)
1670 (remove-hook 'company-completion-finished-hook company-callback t)
1671 (remove-hook 'company-completion-cancelled-hook 'company-remove-callback t)
1672 (remove-hook 'company-completion-finished-hook 'company-remove-callback t)
1673 (when company-begin-with-marker
1674 (set-marker company-begin-with-marker nil)))
1675
1676 (defun company-begin-backend (backend &optional callback)
1677 "Start a completion at point using BACKEND."
1678 (interactive (let ((val (completing-read "Company back-end: "
1679 obarray
1680 'functionp nil "company-")))
1681 (when val
1682 (list (intern val)))))
1683 (when (setq company-callback callback)
1684 (add-hook 'company-completion-finished-hook company-callback nil t))
1685 (add-hook 'company-completion-cancelled-hook 'company-remove-callback nil t)
1686 (add-hook 'company-completion-finished-hook 'company-remove-callback nil t)
1687 (setq company-backend backend)
1688 ;; Return non-nil if active.
1689 (or (company-manual-begin)
1690 (progn
1691 (setq company-backend nil)
1692 (error "Cannot complete at point"))))
1693
1694 (defun company-begin-with (candidates
1695 &optional prefix-length require-match callback)
1696 "Start a completion at point.
1697 CANDIDATES is the list of candidates to use and PREFIX-LENGTH is the length
1698 of the prefix that already is in the buffer before point.
1699 It defaults to 0.
1700
1701 CALLBACK is a function called with the selected result if the user
1702 successfully completes the input.
1703
1704 Example: \(company-begin-with '\(\"foo\" \"foobar\" \"foobarbaz\"\)\)"
1705 ;; FIXME: When Emacs 23 is no longer a concern, replace
1706 ;; `company-begin-with-marker' with a lexical variable; use a lexical closure.
1707 (setq company-begin-with-marker (copy-marker (point) t))
1708 (company-begin-backend
1709 `(lambda (command &optional arg &rest ignored)
1710 (cond
1711 ((eq command 'prefix)
1712 (when (equal (point) (marker-position company-begin-with-marker))
1713 (buffer-substring ,(- (point) (or prefix-length 0)) (point))))
1714 ((eq command 'candidates)
1715 (all-completions arg ',candidates))
1716 ((eq command 'require-match)
1717 ,require-match)))
1718 callback))
1719
1720 ;;; pseudo-tooltip ;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;
1721
1722 (defvar company-pseudo-tooltip-overlay nil)
1723 (make-variable-buffer-local 'company-pseudo-tooltip-overlay)
1724
1725 (defvar company-tooltip-offset 0)
1726 (make-variable-buffer-local 'company-tooltip-offset)
1727
1728 (defun company-tooltip--lines-update-offset (selection num-lines limit)
1729 (decf limit 2)
1730 (setq company-tooltip-offset
1731 (max (min selection company-tooltip-offset)
1732 (- selection -1 limit)))
1733
1734 (when (<= company-tooltip-offset 1)
1735 (incf limit)
1736 (setq company-tooltip-offset 0))
1737
1738 (when (>= company-tooltip-offset (- num-lines limit 1))
1739 (incf limit)
1740 (when (= selection (1- num-lines))
1741 (decf company-tooltip-offset)
1742 (when (<= company-tooltip-offset 1)
1743 (setq company-tooltip-offset 0)
1744 (incf limit))))
1745
1746 limit)
1747
1748 (defun company-tooltip--simple-update-offset (selection num-lines limit)
1749 (setq company-tooltip-offset
1750 (if (< selection company-tooltip-offset)
1751 selection
1752 (max company-tooltip-offset
1753 (- selection limit -1)))))
1754
1755 ;;; propertize
1756
1757 (defsubst company-round-tab (arg)
1758 (* (/ (+ arg tab-width) tab-width) tab-width))
1759
1760 (defun company-plainify (str)
1761 (let ((prefix (get-text-property 0 'line-prefix str)))
1762 (when prefix ; Keep the original value unmodified, for no special reason.
1763 (setq str (concat prefix str))
1764 (remove-text-properties 0 (length str) '(line-prefix) str)))
1765 (let* ((pieces (split-string str "\t"))
1766 (copy pieces))
1767 (while (cdr copy)
1768 (setcar copy (company-safe-substring
1769 (car copy) 0 (company-round-tab (string-width (car copy)))))
1770 (pop copy))
1771 (apply 'concat pieces)))
1772
1773 (defun company--highlight-common (line properties)
1774 ;; XXX: Subject to change.
1775 (let ((common (or (company-call-backend 'common-part line)
1776 (length company-common))))
1777 (add-text-properties 0 common properties line)))
1778
1779 (defun company-fill-propertize (line width selected)
1780 (let* ((margin company-tooltip-margin)
1781 (common (+ (or (company-call-backend 'common-part line)
1782 (length company-common)) margin)))
1783 (setq line (concat (company-space-string company-tooltip-margin)
1784 (company-safe-substring
1785 line 0 (+ width company-tooltip-margin)))
1786 width (+ width (* 2 margin)))
1787
1788 (add-text-properties 0 width '(face company-tooltip
1789 mouse-face company-tooltip-mouse)
1790 line)
1791 (add-text-properties margin common
1792 '(face company-tooltip-common
1793 mouse-face company-tooltip-mouse)
1794 line)
1795 (when selected
1796 (if (and company-search-string
1797 (string-match (regexp-quote company-search-string) line
1798 (length company-prefix)))
1799 (progn
1800 (add-text-properties (match-beginning 0) (match-end 0)
1801 '(face company-tooltip-selection)
1802 line)
1803 (when (< (match-beginning 0) common)
1804 (add-text-properties (match-beginning 0) common
1805 '(face company-tooltip-common-selection)
1806 line)))
1807 (add-text-properties 0 width '(face company-tooltip-selection
1808 mouse-face company-tooltip-selection)
1809 line)
1810 (add-text-properties margin common
1811 '(face company-tooltip-common-selection
1812 mouse-face company-tooltip-selection)
1813 line))))
1814 line)
1815
1816 ;;; replace
1817
1818 (defun company-buffer-lines (beg end)
1819 (goto-char beg)
1820 (let (lines)
1821 (while (and (= 1 (vertical-motion 1))
1822 (<= (point) end))
1823 (let ((bound (min end (1- (point)))))
1824 ;; A visual line can contain several physical lines (e.g. with outline's
1825 ;; folding overlay). Take only the first one.
1826 (push (buffer-substring beg
1827 (save-excursion
1828 (goto-char beg)
1829 (re-search-forward "$" bound 'move)
1830 (point)))
1831 lines))
1832 (setq beg (point)))
1833 (unless (eq beg end)
1834 (push (buffer-substring beg end) lines))
1835 (nreverse lines)))
1836
1837 (defun company-modify-line (old new offset)
1838 (concat (company-safe-substring old 0 offset)
1839 new
1840 (company-safe-substring old (+ offset (length new)))))
1841
1842 (defsubst company--length-limit (lst limit)
1843 (if (nthcdr limit lst)
1844 limit
1845 (length lst)))
1846
1847 (defun company--replacement-string (lines old column nl &optional align-top)
1848 (decf column company-tooltip-margin)
1849
1850 (let ((width (length (car lines)))
1851 (remaining-cols (- (+ (company--window-width) (window-hscroll))
1852 column)))
1853 (when (> width remaining-cols)
1854 (decf column (- width remaining-cols))))
1855
1856 (let ((offset (and (< column 0) (- column)))
1857 new)
1858 (when offset
1859 (setq column 0))
1860 (when align-top
1861 ;; untouched lines first
1862 (dotimes (_ (- (length old) (length lines)))
1863 (push (pop old) new)))
1864 ;; length into old lines.
1865 (while old
1866 (push (company-modify-line (pop old)
1867 (company--offset-line (pop lines) offset)
1868 column) new))
1869 ;; Append whole new lines.
1870 (while lines
1871 (push (concat (company-space-string column)
1872 (company--offset-line (pop lines) offset))
1873 new))
1874
1875 (let ((str (concat (when nl "\n")
1876 (mapconcat 'identity (nreverse new) "\n")
1877 "\n")))
1878 (font-lock-append-text-property 0 (length str) 'face 'default str)
1879 str)))
1880
1881 (defun company--offset-line (line offset)
1882 (if (and offset line)
1883 (substring line offset)
1884 line))
1885
1886 (defun company--create-lines (selection limit)
1887
1888 (let ((len company-candidates-length)
1889 (numbered 99999)
1890 (window-width (company--window-width))
1891 lines
1892 width
1893 lines-copy
1894 previous
1895 remainder
1896 scrollbar-bounds
1897 new)
1898
1899 ;; Maybe clear old offset.
1900 (when (<= len (+ company-tooltip-offset limit))
1901 (setq company-tooltip-offset 0))
1902
1903 ;; Scroll to offset.
1904 (if (eq company-tooltip-offset-display 'lines)
1905 (setq limit (company-tooltip--lines-update-offset selection len limit))
1906 (company-tooltip--simple-update-offset selection len limit))
1907
1908 (cond
1909 ((eq company-tooltip-offset-display 'scrollbar)
1910 (setq scrollbar-bounds (company--scrollbar-bounds company-tooltip-offset
1911 limit len)))
1912 ((eq company-tooltip-offset-display 'lines)
1913 (when (> company-tooltip-offset 0)
1914 (setq previous (format "...(%d)" company-tooltip-offset)))
1915 (setq remainder (- len limit company-tooltip-offset)
1916 remainder (when (> remainder 0)
1917 (setq remainder (format "...(%d)" remainder))))))
1918
1919 (decf selection company-tooltip-offset)
1920 (setq width (max (length previous) (length remainder))
1921 lines (nthcdr company-tooltip-offset company-candidates)
1922 len (min limit len)
1923 lines-copy lines)
1924
1925 (decf window-width (* 2 company-tooltip-margin))
1926 (when scrollbar-bounds (decf window-width))
1927
1928 (dotimes (_ len)
1929 (setq width (max (length (pop lines-copy)) width)))
1930 (setq width (min window-width
1931 (if (and company-show-numbers
1932 (< company-tooltip-offset 10))
1933 (+ 2 width)
1934 width)))
1935 (setq lines-copy lines)
1936
1937 ;; number can make tooltip too long
1938 (when company-show-numbers
1939 (setq numbered company-tooltip-offset))
1940
1941 (when previous
1942 (push (company--scrollpos-line previous width) new))
1943
1944 (dotimes (i len)
1945 (let ((line (company-fill-propertize
1946 (if (>= numbered 10)
1947 (company-reformat (pop lines))
1948 (incf numbered)
1949 (format "%s %d"
1950 (company-safe-substring
1951 (company-reformat (pop lines)) 0 (- width 2))
1952 (mod numbered 10)))
1953 width (equal i selection))))
1954 (push (if scrollbar-bounds
1955 (company--scrollbarize line i scrollbar-bounds)
1956 line)
1957 new)))
1958
1959 (when remainder
1960 (push (company--scrollpos-line remainder width) new))
1961
1962 (setq lines (nreverse new))))
1963
1964 (defun company--scrollbar-bounds (offset limit length)
1965 (when (> length limit)
1966 (let* ((size (ceiling (* limit (float limit)) length))
1967 (lower (floor (* limit (float offset)) length))
1968 (upper (+ lower size -1)))
1969 (cons lower upper))))
1970
1971 (defun company--scrollbarize (line i bounds)
1972 (concat line
1973 (propertize " " 'face
1974 (if (and (>= i (car bounds)) (<= i (cdr bounds)))
1975 'company-scrollbar-fg
1976 'company-scrollbar-bg))))
1977
1978 (defun company--scrollpos-line (text width)
1979 (propertize (concat (company-space-string company-tooltip-margin)
1980 (company-safe-substring text 0 width)
1981 (company-space-string company-tooltip-margin))
1982 'face 'company-tooltip))
1983
1984 ;; show
1985
1986 (defsubst company--window-inner-height ()
1987 (let ((edges (window-inside-edges)))
1988 (- (nth 3 edges) (nth 1 edges))))
1989
1990 (defsubst company--window-width ()
1991 (- (window-width)
1992 (cond
1993 ((display-graphic-p) 0)
1994 ;; Account for the line continuation column.
1995 ((version< "24.3.1" emacs-version) 1)
1996 ;; Emacs 24.3 and earlier included margins
1997 ;; in window-width when in TTY.
1998 (t (1+ (let ((margins (window-margins)))
1999 (+ (or (car margins) 0)
2000 (or (cdr margins) 0))))))))
2001
2002 (defun company--pseudo-tooltip-height ()
2003 "Calculate the appropriate tooltip height.
2004 Returns a negative number if the tooltip should be displayed above point."
2005 (let* ((lines (company--row))
2006 (below (- (company--window-inner-height) 1 lines)))
2007 (if (and (< below (min company-tooltip-minimum company-candidates-length))
2008 (> lines below))
2009 (- (max 3 (min company-tooltip-limit lines)))
2010 (max 3 (min company-tooltip-limit below)))))
2011
2012 (defun company-pseudo-tooltip-show (row column selection)
2013 (company-pseudo-tooltip-hide)
2014 (save-excursion
2015
2016 (let* ((height (company--pseudo-tooltip-height))
2017 above)
2018
2019 (when (< height 0)
2020 (setq row (+ row height -1)
2021 above t))
2022
2023 (let* ((nl (< (move-to-window-line row) row))
2024 (beg (point))
2025 (end (save-excursion
2026 (move-to-window-line (+ row (abs height)))
2027 (point)))
2028 (ov (make-overlay beg end))
2029 (args (list (mapcar 'company-plainify
2030 (company-buffer-lines beg end))
2031 column nl above)))
2032
2033 (setq company-pseudo-tooltip-overlay ov)
2034 (overlay-put ov 'company-replacement-args args)
2035
2036 (let ((lines (company--create-lines selection (abs height))))
2037 (overlay-put ov 'company-after
2038 (apply 'company--replacement-string lines args))
2039 (overlay-put ov 'company-width (string-width (car lines))))
2040
2041 (overlay-put ov 'company-column column)
2042 (overlay-put ov 'company-height height)))))
2043
2044 (defun company-pseudo-tooltip-show-at-point (pos)
2045 (let ((row (company--row pos))
2046 (col (company--column pos)))
2047 (company-pseudo-tooltip-show (1+ row) col company-selection)))
2048
2049 (defun company-pseudo-tooltip-edit (selection)
2050 (let ((height (overlay-get company-pseudo-tooltip-overlay 'company-height)))
2051 (overlay-put company-pseudo-tooltip-overlay 'company-after
2052 (apply 'company--replacement-string
2053 (company--create-lines selection (abs height))
2054 (overlay-get company-pseudo-tooltip-overlay
2055 'company-replacement-args)))))
2056
2057 (defun company-pseudo-tooltip-hide ()
2058 (when company-pseudo-tooltip-overlay
2059 (delete-overlay company-pseudo-tooltip-overlay)
2060 (setq company-pseudo-tooltip-overlay nil)))
2061
2062 (defun company-pseudo-tooltip-hide-temporarily ()
2063 (when (overlayp company-pseudo-tooltip-overlay)
2064 (overlay-put company-pseudo-tooltip-overlay 'invisible nil)
2065 (overlay-put company-pseudo-tooltip-overlay 'line-prefix nil)
2066 (overlay-put company-pseudo-tooltip-overlay 'after-string nil)))
2067
2068 (defun company-pseudo-tooltip-unhide ()
2069 (when company-pseudo-tooltip-overlay
2070 (overlay-put company-pseudo-tooltip-overlay 'invisible t)
2071 ;; Beat outline's folding overlays, at least.
2072 (overlay-put company-pseudo-tooltip-overlay 'priority 1)
2073 ;; No (extra) prefix for the first line.
2074 (overlay-put company-pseudo-tooltip-overlay 'line-prefix "")
2075 (overlay-put company-pseudo-tooltip-overlay 'after-string
2076 (overlay-get company-pseudo-tooltip-overlay 'company-after))
2077 (overlay-put company-pseudo-tooltip-overlay 'window (selected-window))))
2078
2079 (defun company-pseudo-tooltip-guard ()
2080 (buffer-substring-no-properties
2081 (point) (overlay-start company-pseudo-tooltip-overlay)))
2082
2083 (defun company-pseudo-tooltip-frontend (command)
2084 "`company-mode' front-end similar to a tooltip but based on overlays."
2085 (case command
2086 (pre-command (company-pseudo-tooltip-hide-temporarily))
2087 (post-command
2088 (let ((old-height (if (overlayp company-pseudo-tooltip-overlay)
2089 (overlay-get company-pseudo-tooltip-overlay
2090 'company-height)
2091 0))
2092 (new-height (company--pseudo-tooltip-height)))
2093 (unless (and (>= (* old-height new-height) 0)
2094 (>= (abs old-height) (abs new-height))
2095 (equal (company-pseudo-tooltip-guard)
2096 (overlay-get company-pseudo-tooltip-overlay
2097 'company-guard)))
2098 ;; Redraw needed.
2099 (company-pseudo-tooltip-show-at-point (- (point)
2100 (length company-prefix)))
2101 (overlay-put company-pseudo-tooltip-overlay
2102 'company-guard (company-pseudo-tooltip-guard))))
2103 (company-pseudo-tooltip-unhide))
2104 (hide (company-pseudo-tooltip-hide)
2105 (setq company-tooltip-offset 0))
2106 (update (when (overlayp company-pseudo-tooltip-overlay)
2107 (company-pseudo-tooltip-edit company-selection)))))
2108
2109 (defun company-pseudo-tooltip-unless-just-one-frontend (command)
2110 "`company-pseudo-tooltip-frontend', but not shown for single candidates."
2111 (unless (and (eq command 'post-command)
2112 (company--show-inline-p))
2113 (company-pseudo-tooltip-frontend command)))
2114
2115 ;;; overlay ;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;
2116
2117 (defvar company-preview-overlay nil)
2118 (make-variable-buffer-local 'company-preview-overlay)
2119
2120 (defun company-preview-show-at-point (pos)
2121 (company-preview-hide)
2122
2123 (setq company-preview-overlay (make-overlay pos (1+ pos)))
2124
2125 (let ((completion (nth company-selection company-candidates)))
2126 (setq completion (propertize completion 'face 'company-preview))
2127 (add-text-properties 0 (length company-common)
2128 '(face company-preview-common) completion)
2129
2130 ;; Add search string
2131 (and company-search-string
2132 (string-match (regexp-quote company-search-string) completion)
2133 (add-text-properties (match-beginning 0)
2134 (match-end 0)
2135 '(face company-preview-search)
2136 completion))
2137
2138 (setq completion (company-strip-prefix completion))
2139
2140 (and (equal pos (point))
2141 (not (equal completion ""))
2142 (add-text-properties 0 1 '(cursor t) completion))
2143
2144 (overlay-put company-preview-overlay 'display
2145 (concat completion (unless (eq pos (point-max))
2146 (buffer-substring pos (1+ pos)))))
2147 (overlay-put company-preview-overlay 'window (selected-window))))
2148
2149 (defun company-preview-hide ()
2150 (when company-preview-overlay
2151 (delete-overlay company-preview-overlay)
2152 (setq company-preview-overlay nil)))
2153
2154 (defun company-preview-frontend (command)
2155 "`company-mode' front-end showing the selection as if it had been inserted."
2156 (case command
2157 (pre-command (company-preview-hide))
2158 (post-command (company-preview-show-at-point (point)))
2159 (hide (company-preview-hide))))
2160
2161 (defun company-preview-if-just-one-frontend (command)
2162 "`company-preview-frontend', but only shown for single candidates."
2163 (when (or (not (eq command 'post-command))
2164 (company--show-inline-p))
2165 (company-preview-frontend command)))
2166
2167 (defun company--show-inline-p ()
2168 (and (not (cdr company-candidates))
2169 company-common
2170 (string-prefix-p company-prefix company-common
2171 (company-call-backend 'ignore-case))))
2172
2173 ;;; echo ;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;
2174
2175 (defvar company-echo-last-msg nil)
2176 (make-variable-buffer-local 'company-echo-last-msg)
2177
2178 (defvar company-echo-timer nil)
2179
2180 (defvar company-echo-delay .01)
2181
2182 (defun company-echo-show (&optional getter)
2183 (when getter
2184 (setq company-echo-last-msg (funcall getter)))
2185 (let ((message-log-max nil))
2186 (if company-echo-last-msg
2187 (message "%s" company-echo-last-msg)
2188 (message ""))))
2189
2190 (defun company-echo-show-soon (&optional getter)
2191 (when company-echo-timer
2192 (cancel-timer company-echo-timer))
2193 (setq company-echo-timer (run-with-timer 0 nil 'company-echo-show getter)))
2194
2195 (defsubst company-echo-show-when-idle (&optional getter)
2196 (when (sit-for company-echo-delay)
2197 (company-echo-show getter)))
2198
2199 (defun company-echo-format ()
2200
2201 (let ((limit (window-width (minibuffer-window)))
2202 (len -1)
2203 ;; Roll to selection.
2204 (candidates (nthcdr company-selection company-candidates))
2205 (i (if company-show-numbers company-selection 99999))
2206 comp msg)
2207
2208 (while candidates
2209 (setq comp (company-reformat (pop candidates))
2210 len (+ len 1 (length comp)))
2211 (if (< i 10)
2212 ;; Add number.
2213 (progn
2214 (setq comp (propertize (format "%d: %s" i comp)
2215 'face 'company-echo))
2216 (incf len 3)
2217 (incf i)
2218 (add-text-properties 3 (+ 3 (length company-common))
2219 '(face company-echo-common) comp))
2220 (setq comp (propertize comp 'face 'company-echo))
2221 (add-text-properties 0 (length company-common)
2222 '(face company-echo-common) comp))
2223 (if (>= len limit)
2224 (setq candidates nil)
2225 (push comp msg)))
2226
2227 (mapconcat 'identity (nreverse msg) " ")))
2228
2229 (defun company-echo-strip-common-format ()
2230
2231 (let ((limit (window-width (minibuffer-window)))
2232 (len (+ (length company-prefix) 2))
2233 ;; Roll to selection.
2234 (candidates (nthcdr company-selection company-candidates))
2235 (i (if company-show-numbers company-selection 99999))
2236 msg comp)
2237
2238 (while candidates
2239 (setq comp (company-strip-prefix (pop candidates))
2240 len (+ len 2 (length comp)))
2241 (when (< i 10)
2242 ;; Add number.
2243 (setq comp (format "%s (%d)" comp i))
2244 (incf len 4)
2245 (incf i))
2246 (if (>= len limit)
2247 (setq candidates nil)
2248 (push (propertize comp 'face 'company-echo) msg)))
2249
2250 (concat (propertize company-prefix 'face 'company-echo-common) "{"
2251 (mapconcat 'identity (nreverse msg) ", ")
2252 "}")))
2253
2254 (defun company-echo-hide ()
2255 (unless (equal company-echo-last-msg "")
2256 (setq company-echo-last-msg "")
2257 (company-echo-show)))
2258
2259 (defun company-echo-frontend (command)
2260 "`company-mode' front-end showing the candidates in the echo area."
2261 (case command
2262 (post-command (company-echo-show-soon 'company-echo-format))
2263 (hide (company-echo-hide))))
2264
2265 (defun company-echo-strip-common-frontend (command)
2266 "`company-mode' front-end showing the candidates in the echo area."
2267 (case command
2268 (post-command (company-echo-show-soon 'company-echo-strip-common-format))
2269 (hide (company-echo-hide))))
2270
2271 (defun company-echo-metadata-frontend (command)
2272 "`company-mode' front-end showing the documentation in the echo area."
2273 (case command
2274 (post-command (company-echo-show-when-idle 'company-fetch-metadata))
2275 (hide (company-echo-hide))))
2276
2277 (provide 'company)
2278 ;;; company.el ends here