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