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