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