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