]> code.delx.au - gnu-emacs-elpa/blob - company.el
Fix a bug reference
[gnu-emacs-elpa] / company.el
1 ;;; company.el --- Modular text completion framework -*- lexical-binding: t -*-
2
3 ;; Copyright (C) 2009-2015 Free Software Foundation, Inc.
4
5 ;; Author: Nikolaj Schumacher
6 ;; Maintainer: Dmitry Gutov <dgutov@yandex.ru>
7 ;; URL: http://company-mode.github.io/
8 ;; Version: 0.9.0-cvs
9 ;; Keywords: abbrev, convenience, matching
10 ;; Package-Requires: ((emacs "24.1") (cl-lib "0.5"))
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 ;; (pcase 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 ;;; Change Log:
62 ;;
63 ;; See NEWS.md in the repository.
64
65 ;;; Code:
66
67 (require 'cl-lib)
68 (require 'newcomment)
69
70 ;; FIXME: Use `user-error'.
71 (add-to-list 'debug-ignored-errors "^.* frontend cannot be used twice$")
72 (add-to-list 'debug-ignored-errors "^Echo area cannot be used twice$")
73 (add-to-list 'debug-ignored-errors "^No \\(document\\|loc\\)ation available$")
74 (add-to-list 'debug-ignored-errors "^Company not ")
75 (add-to-list 'debug-ignored-errors "^No candidate number ")
76 (add-to-list 'debug-ignored-errors "^Cannot complete at point$")
77 (add-to-list 'debug-ignored-errors "^No other back-end$")
78
79 ;;; Compatibility
80 (eval-and-compile
81 ;; `defvar-local' for Emacs 24.2 and below
82 (unless (fboundp 'defvar-local)
83 (defmacro defvar-local (var val &optional docstring)
84 "Define VAR as a buffer-local variable with default value VAL.
85 Like `defvar' but additionally marks the variable as being automatically
86 buffer-local wherever it is set."
87 (declare (debug defvar) (doc-string 3))
88 `(progn
89 (defvar ,var ,val ,docstring)
90 (make-variable-buffer-local ',var)))))
91
92 (defgroup company nil
93 "Extensible inline text completion mechanism"
94 :group 'abbrev
95 :group 'convenience
96 :group 'matching)
97
98 (defface company-tooltip
99 '((default :foreground "black")
100 (((class color) (min-colors 88) (background light))
101 (:background "cornsilk"))
102 (((class color) (min-colors 88) (background dark))
103 (:background "yellow")))
104 "Face used for the tooltip.")
105
106 (defface company-tooltip-selection
107 '((default :inherit company-tooltip)
108 (((class color) (min-colors 88) (background light))
109 (:background "light blue"))
110 (((class color) (min-colors 88) (background dark))
111 (:background "orange1"))
112 (t (:background "green")))
113 "Face used for the selection in the tooltip.")
114
115 (defface company-tooltip-search
116 '((default :inherit company-tooltip-selection))
117 "Face used for the search string in the tooltip.")
118
119 (defface company-tooltip-mouse
120 '((default :inherit highlight))
121 "Face used for the tooltip item under the mouse.")
122
123 (defface company-tooltip-common
124 '((default :inherit company-tooltip)
125 (((background light))
126 :foreground "darkred")
127 (((background dark))
128 :foreground "red"))
129 "Face used for the common completion in the tooltip.")
130
131 (defface company-tooltip-common-selection
132 '((default :inherit company-tooltip-selection)
133 (((background light))
134 :foreground "darkred")
135 (((background dark))
136 :foreground "red"))
137 "Face used for the selected common completion in the tooltip.")
138
139 (defface company-tooltip-annotation
140 '((default :inherit company-tooltip)
141 (((background light))
142 :foreground "firebrick4")
143 (((background dark))
144 :foreground "red4"))
145 "Face used for the annotation in the tooltip.")
146
147 (defface company-scrollbar-fg
148 '((((background light))
149 :background "darkred")
150 (((background dark))
151 :background "red"))
152 "Face used for the tooltip scrollbar thumb.")
153
154 (defface company-scrollbar-bg
155 '((default :inherit company-tooltip)
156 (((background light))
157 :background "wheat")
158 (((background dark))
159 :background "gold"))
160 "Face used for the tooltip scrollbar background.")
161
162 (defface company-preview
163 '((((background light))
164 :inherit company-tooltip-selection)
165 (((background dark))
166 :background "blue4"
167 :foreground "wheat"))
168 "Face used for the completion preview.")
169
170 (defface company-preview-common
171 '((((background light))
172 :inherit company-tooltip-selection)
173 (((background dark))
174 :inherit company-preview
175 :foreground "red"))
176 "Face used for the common part of the completion preview.")
177
178 (defface company-preview-search
179 '((((background light))
180 :inherit company-tooltip-common-selection)
181 (((background dark))
182 :inherit company-preview
183 :background "blue1"))
184 "Face used for the search string in the completion preview.")
185
186 (defface company-echo nil
187 "Face used for completions in the echo area.")
188
189 (defface company-echo-common
190 '((((background dark)) (:foreground "firebrick1"))
191 (((background light)) (:background "firebrick4")))
192 "Face used for the common part of completions in the echo area.")
193
194 (defun company-frontends-set (variable value)
195 ;; Uniquify.
196 (let ((value (delete-dups (copy-sequence value))))
197 (and (memq 'company-pseudo-tooltip-unless-just-one-frontend value)
198 (memq 'company-pseudo-tooltip-frontend value)
199 (error "Pseudo tooltip frontend cannot be used twice"))
200 (and (memq 'company-preview-if-just-one-frontend value)
201 (memq 'company-preview-frontend value)
202 (error "Preview frontend cannot be used twice"))
203 (and (memq 'company-echo value)
204 (memq 'company-echo-metadata-frontend value)
205 (error "Echo area cannot be used twice"))
206 ;; Preview must come last.
207 (dolist (f '(company-preview-if-just-one-frontend company-preview-frontend))
208 (when (cdr (memq f value))
209 (setq value (append (delq f value) (list f)))))
210 (set variable value)))
211
212 (defcustom company-frontends '(company-pseudo-tooltip-unless-just-one-frontend
213 company-preview-if-just-one-frontend
214 company-echo-metadata-frontend)
215 "The list of active front-ends (visualizations).
216 Each front-end is a function that takes one argument. It is called with
217 one of the following arguments:
218
219 `show': When the visualization should start.
220
221 `hide': When the visualization should end.
222
223 `update': When the data has been updated.
224
225 `pre-command': Before every command that is executed while the
226 visualization is active.
227
228 `post-command': After every command that is executed while the
229 visualization is active.
230
231 The visualized data is stored in `company-prefix', `company-candidates',
232 `company-common', `company-selection', `company-point' and
233 `company-search-string'."
234 :set 'company-frontends-set
235 :type '(repeat (choice (const :tag "echo" company-echo-frontend)
236 (const :tag "echo, strip common"
237 company-echo-strip-common-frontend)
238 (const :tag "show echo meta-data in echo"
239 company-echo-metadata-frontend)
240 (const :tag "pseudo tooltip"
241 company-pseudo-tooltip-frontend)
242 (const :tag "pseudo tooltip, multiple only"
243 company-pseudo-tooltip-unless-just-one-frontend)
244 (const :tag "preview" company-preview-frontend)
245 (const :tag "preview, unique only"
246 company-preview-if-just-one-frontend)
247 (function :tag "custom function" nil))))
248
249 (defcustom company-tooltip-limit 10
250 "The maximum number of candidates in the tooltip."
251 :type 'integer)
252
253 (defcustom company-tooltip-minimum 6
254 "The minimum height of the tooltip.
255 If this many lines are not available, prefer to display the tooltip above."
256 :type 'integer)
257
258 (defcustom company-tooltip-minimum-width 0
259 "The minimum width of the tooltip's inner area.
260 This doesn't include the margins and the scroll bar."
261 :type 'integer
262 :package-version '(company . "0.8.0"))
263
264 (defcustom company-tooltip-margin 1
265 "Width of margin columns to show around the toolip."
266 :type 'integer)
267
268 (defcustom company-tooltip-offset-display 'scrollbar
269 "Method using which the tooltip displays scrolling position.
270 `scrollbar' means draw a scrollbar to the right of the items.
271 `lines' means wrap items in lines with \"before\" and \"after\" counters."
272 :type '(choice (const :tag "Scrollbar" scrollbar)
273 (const :tag "Two lines" lines)))
274
275 (defcustom company-tooltip-align-annotations nil
276 "When non-nil, align annotations to the right tooltip border."
277 :type 'boolean
278 :package-version '(company . "0.7.1"))
279
280 (defcustom company-tooltip-flip-when-above nil
281 "Whether to flip the tooltip when it's above the current line."
282 :type 'boolean
283 :package-version '(company . "0.8.1"))
284
285 (defvar company-safe-backends
286 '((company-abbrev . "Abbrev")
287 (company-bbdb . "BBDB")
288 (company-capf . "completion-at-point-functions")
289 (company-clang . "Clang")
290 (company-cmake . "CMake")
291 (company-css . "CSS")
292 (company-dabbrev . "dabbrev for plain text")
293 (company-dabbrev-code . "dabbrev for code")
294 (company-eclim . "Eclim (an Eclipse interface)")
295 (company-elisp . "Emacs Lisp")
296 (company-etags . "etags")
297 (company-files . "Files")
298 (company-gtags . "GNU Global")
299 (company-ispell . "Ispell")
300 (company-keywords . "Programming language keywords")
301 (company-nxml . "nxml")
302 (company-oddmuse . "Oddmuse")
303 (company-semantic . "Semantic")
304 (company-tempo . "Tempo templates")
305 (company-xcode . "Xcode")))
306 (put 'company-safe-backends 'risky-local-variable t)
307
308 (defun company-safe-backends-p (backends)
309 (and (consp backends)
310 (not (cl-dolist (backend backends)
311 (unless (if (consp backend)
312 (company-safe-backends-p backend)
313 (assq backend company-safe-backends))
314 (cl-return t))))))
315
316 (defcustom company-backends `(,@(unless (version< "24.3.51" emacs-version)
317 (list 'company-elisp))
318 company-bbdb
319 company-nxml company-css
320 company-eclim company-semantic company-clang
321 company-xcode company-cmake
322 company-capf
323 (company-dabbrev-code company-gtags company-etags
324 company-keywords)
325 company-oddmuse company-files company-dabbrev)
326 "The list of active back-ends (completion engines).
327
328 Only one back-end is used at a time. The choice depends on the order of
329 the items in this list, and on the values they return in response to the
330 `prefix' command (see below). But a back-end can also be a \"grouped\"
331 one (see below).
332
333 `company-begin-backend' can be used to start a specific back-end,
334 `company-other-backend' will skip to the next matching back-end in the list.
335
336 Each back-end is a function that takes a variable number of arguments.
337 The first argument is the command requested from the back-end. It is one
338 of the following:
339
340 `prefix': The back-end should return the text to be completed. It must be
341 text immediately before point. Returning nil from this command passes
342 control to the next back-end. The function should return `stop' if it
343 should complete but cannot (e.g. if it is in the middle of a string).
344 Instead of a string, the back-end may return a cons where car is the prefix
345 and cdr is used instead of the actual prefix length in the comparison
346 against `company-minimum-prefix-length'. It must be either number or t,
347 and in the latter case the test automatically succeeds.
348
349 `candidates': The second argument is the prefix to be completed. The
350 return value should be a list of candidates that match the prefix.
351
352 Non-prefix matches are also supported (candidates that don't start with the
353 prefix, but match it in some backend-defined way). Backends that use this
354 feature must disable cache (return t to `no-cache') and might also want to
355 respond to `match'.
356
357 Optional commands:
358
359 `sorted': Return t here to indicate that the candidates are sorted and will
360 not need to be sorted again.
361
362 `duplicates': If non-nil, company will take care of removing duplicates
363 from the list.
364
365 `no-cache': Usually company doesn't ask for candidates again as completion
366 progresses, unless the back-end returns t for this command. The second
367 argument is the latest prefix.
368
369 `ignore-case': Return t here if the backend returns case-insensitive
370 matches. This value is used to determine the longest common prefix (as
371 used in `company-complete-common'), and to filter completions when fetching
372 them from cache.
373
374 `meta': The second argument is a completion candidate. Return a (short)
375 documentation string for it.
376
377 `doc-buffer': The second argument is a completion candidate. Return a
378 buffer with documentation for it. Preferably use `company-doc-buffer'. If
379 not all buffer contents pertain to this candidate, return a cons of buffer
380 and window start position.
381
382 `location': The second argument is a completion candidate. Return a cons
383 of buffer and buffer location, or of file and line number where the
384 completion candidate was defined.
385
386 `annotation': The second argument is a completion candidate. Return a
387 string to be displayed inline with the candidate in the popup. If
388 duplicates are removed by company, candidates with equal string values will
389 be kept if they have different annotations. For that to work properly,
390 backends should store the related information on candidates using text
391 properties.
392
393 `match': The second argument is a completion candidate. Return the index
394 after the end of text matching `prefix' within the candidate string. It
395 will be used when rendering the popup. This command only makes sense for
396 backends that provide non-prefix completion.
397
398 `require-match': If this returns t, the user is not allowed to enter
399 anything not offered as a candidate. Please don't use that value in normal
400 backends. The default value nil gives the user that choice with
401 `company-require-match'. Return value `never' overrides that option the
402 other way around.
403
404 `init': Called once for each buffer. The back-end can check for external
405 programs and files and load any required libraries. Raising an error here
406 will show up in message log once, and the back-end will not be used for
407 completion.
408
409 `post-completion': Called after a completion candidate has been inserted
410 into the buffer. The second argument is the candidate. Can be used to
411 modify it, e.g. to expand a snippet.
412
413 The back-end should return nil for all commands it does not support or
414 does not know about. It should also be callable interactively and use
415 `company-begin-backend' to start itself in that case.
416
417 Grouped back-ends:
418
419 An element of `company-backends' can also itself be a list of back-ends,
420 then it's considered to be a \"grouped\" back-end.
421
422 When possible, commands taking a candidate as an argument are dispatched to
423 the back-end it came from. In other cases, the first non-nil value among
424 all the back-ends is returned.
425
426 The latter is the case for the `prefix' command. But if the group contains
427 the keyword `:with', the back-ends after it are ignored for this command.
428
429 The completions from back-ends in a group are merged (but only from those
430 that return the same `prefix').
431
432 Asynchronous back-ends:
433
434 The return value of each command can also be a cons (:async . FETCHER)
435 where FETCHER is a function of one argument, CALLBACK. When the data
436 arrives, FETCHER must call CALLBACK and pass it the appropriate return
437 value, as described above.
438
439 True asynchronous operation is only supported for command `candidates', and
440 only during idle completion. Other commands will block the user interface,
441 even if the back-end uses the asynchronous calling convention."
442 :type `(repeat
443 (choice
444 :tag "Back-end"
445 ,@(mapcar (lambda (b) `(const :tag ,(cdr b) ,(car b)))
446 company-safe-backends)
447 (symbol :tag "User defined")
448 (repeat :tag "Merged Back-ends"
449 (choice :tag "Back-end"
450 ,@(mapcar (lambda (b)
451 `(const :tag ,(cdr b) ,(car b)))
452 company-safe-backends)
453 (const :tag "With" :with)
454 (symbol :tag "User defined"))))))
455
456 (put 'company-backends 'safe-local-variable 'company-safe-backends-p)
457
458 (defcustom company-transformers nil
459 "Functions to change the list of candidates received from backends.
460
461 Each function gets called with the return value of the previous one.
462 The first one gets passed the list of candidates, already sorted and
463 without duplicates."
464 :type '(choice
465 (const :tag "None" nil)
466 (const :tag "Sort by occurrence" (company-sort-by-occurrence))
467 (const :tag "Sort by back-end importance"
468 (company-sort-by-backend-importance))
469 (repeat :tag "User defined" (function))))
470
471 (defcustom company-completion-started-hook nil
472 "Hook run when company starts completing.
473 The hook is called with one argument that is non-nil if the completion was
474 started manually."
475 :type 'hook)
476
477 (defcustom company-completion-cancelled-hook nil
478 "Hook run when company cancels completing.
479 The hook is called with one argument that is non-nil if the completion was
480 aborted manually."
481 :type 'hook)
482
483 (defcustom company-completion-finished-hook nil
484 "Hook run when company successfully completes.
485 The hook is called with the selected candidate as an argument.
486
487 If you indend to use it to post-process candidates from a specific
488 back-end, consider using the `post-completion' command instead."
489 :type 'hook)
490
491 (defcustom company-minimum-prefix-length 3
492 "The minimum prefix length for idle completion."
493 :type '(integer :tag "prefix length"))
494
495 (defcustom company-abort-manual-when-too-short nil
496 "If enabled, cancel a manually started completion when the prefix gets
497 shorter than both `company-minimum-prefix-length' and the length of the
498 prefix it was started from."
499 :type 'boolean
500 :package-version '(company . "0.8.0"))
501
502 (defcustom company-require-match 'company-explicit-action-p
503 "If enabled, disallow non-matching input.
504 This can be a function do determine if a match is required.
505
506 This can be overridden by the back-end, if it returns t or `never' to
507 `require-match'. `company-auto-complete' also takes precedence over this."
508 :type '(choice (const :tag "Off" nil)
509 (function :tag "Predicate function")
510 (const :tag "On, if user interaction took place"
511 'company-explicit-action-p)
512 (const :tag "On" t)))
513
514 (defcustom company-auto-complete nil
515 "Determines when to auto-complete.
516 If this is enabled, all characters from `company-auto-complete-chars'
517 trigger insertion of the selected completion candidate.
518 This can also be a function."
519 :type '(choice (const :tag "Off" nil)
520 (function :tag "Predicate function")
521 (const :tag "On, if user interaction took place"
522 'company-explicit-action-p)
523 (const :tag "On" t)))
524
525 (defcustom company-auto-complete-chars '(?\ ?\) ?.)
526 "Determines which characters trigger auto-completion.
527 See `company-auto-complete'. If this is a string, each string character
528 tiggers auto-completion. If it is a list of syntax description characters (see
529 `modify-syntax-entry'), all characters with that syntax auto-complete.
530
531 This can also be a function, which is called with the new input and should
532 return non-nil if company should auto-complete.
533
534 A character that is part of a valid candidate never triggers auto-completion."
535 :type '(choice (string :tag "Characters")
536 (set :tag "Syntax"
537 (const :tag "Whitespace" ?\ )
538 (const :tag "Symbol" ?_)
539 (const :tag "Opening parentheses" ?\()
540 (const :tag "Closing parentheses" ?\))
541 (const :tag "Word constituent" ?w)
542 (const :tag "Punctuation." ?.)
543 (const :tag "String quote." ?\")
544 (const :tag "Paired delimiter." ?$)
545 (const :tag "Expression quote or prefix operator." ?\')
546 (const :tag "Comment starter." ?<)
547 (const :tag "Comment ender." ?>)
548 (const :tag "Character-quote." ?/)
549 (const :tag "Generic string fence." ?|)
550 (const :tag "Generic comment fence." ?!))
551 (function :tag "Predicate function")))
552
553 (defcustom company-idle-delay .5
554 "The idle delay in seconds until completion starts automatically.
555 The prefix still has to satisfy `company-minimum-prefix-length' before that
556 happens. The value of nil means no idle completion."
557 :type '(choice (const :tag "never (nil)" nil)
558 (const :tag "immediate (0)" 0)
559 (number :tag "seconds")))
560
561 (defcustom company-begin-commands '(self-insert-command
562 org-self-insert-command
563 orgtbl-self-insert-command
564 c-scope-operator
565 c-electric-colon
566 c-electric-lt-gt
567 c-electric-slash)
568 "A list of commands after which idle completion is allowed.
569 If this is t, it can show completions after any command except a few from a
570 pre-defined list. See `company-idle-delay'.
571
572 Alternatively, any command with a non-nil `company-begin' property is
573 treated as if it was on this list."
574 :type '(choice (const :tag "Any command" t)
575 (const :tag "Self insert command" '(self-insert-command))
576 (repeat :tag "Commands" function))
577 :package-version '(company . "0.8.4"))
578
579 (defcustom company-continue-commands '(not save-buffer save-some-buffers
580 save-buffers-kill-terminal
581 save-buffers-kill-emacs)
582 "A list of commands that are allowed during completion.
583 If this is t, or if `company-begin-commands' is t, any command is allowed.
584 Otherwise, the value must be a list of symbols. If it starts with `not',
585 the cdr is the list of commands that abort completion. Otherwise, all
586 commands except those in that list, or in `company-begin-commands', or
587 commands in the `company-' namespace, abort completion."
588 :type '(choice (const :tag "Any command" t)
589 (cons :tag "Any except"
590 (const not)
591 (repeat :tag "Commands" function))
592 (repeat :tag "Commands" function)))
593
594 (defcustom company-show-numbers nil
595 "If enabled, show quick-access numbers for the first ten candidates."
596 :type '(choice (const :tag "off" nil)
597 (const :tag "on" t)))
598
599 (defcustom company-selection-wrap-around nil
600 "If enabled, selecting item before first or after last wraps around."
601 :type '(choice (const :tag "off" nil)
602 (const :tag "on" t)))
603
604 (defvar company-async-wait 0.03
605 "Pause between checks to see if the value's been set when turning an
606 asynchronous call into synchronous.")
607
608 (defvar company-async-timeout 2
609 "Maximum wait time for a value to be set during asynchronous call.")
610
611 ;;; mode ;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;
612
613 (defvar company-mode-map (make-sparse-keymap)
614 "Keymap used by `company-mode'.")
615
616 (defvar company-active-map
617 (let ((keymap (make-sparse-keymap)))
618 (define-key keymap "\e\e\e" 'company-abort)
619 (define-key keymap "\C-g" 'company-abort)
620 (define-key keymap (kbd "M-n") 'company-select-next)
621 (define-key keymap (kbd "M-p") 'company-select-previous)
622 (define-key keymap (kbd "<down>") 'company-select-next-or-abort)
623 (define-key keymap (kbd "<up>") 'company-select-previous-or-abort)
624 (define-key keymap [remap scroll-up-command] 'company-next-page)
625 (define-key keymap [remap scroll-down-command] 'company-previous-page)
626 (define-key keymap [down-mouse-1] 'ignore)
627 (define-key keymap [down-mouse-3] 'ignore)
628 (define-key keymap [mouse-1] 'company-complete-mouse)
629 (define-key keymap [mouse-3] 'company-select-mouse)
630 (define-key keymap [up-mouse-1] 'ignore)
631 (define-key keymap [up-mouse-3] 'ignore)
632 (define-key keymap [return] 'company-complete-selection)
633 (define-key keymap (kbd "RET") 'company-complete-selection)
634 (define-key keymap [tab] 'company-complete-common)
635 (define-key keymap (kbd "TAB") 'company-complete-common)
636 (define-key keymap (kbd "<f1>") 'company-show-doc-buffer)
637 (define-key keymap (kbd "C-h") 'company-show-doc-buffer)
638 (define-key keymap "\C-w" 'company-show-location)
639 (define-key keymap "\C-s" 'company-search-candidates)
640 (define-key keymap "\C-\M-s" 'company-filter-candidates)
641 (dotimes (i 10)
642 (define-key keymap (read-kbd-macro (format "M-%d" i)) 'company-complete-number))
643 keymap)
644 "Keymap that is enabled during an active completion.")
645
646 (defvar company--disabled-backends nil)
647
648 (defun company-init-backend (backend)
649 (and (symbolp backend)
650 (not (fboundp backend))
651 (ignore-errors (require backend nil t)))
652 (cond
653 ((symbolp backend)
654 (condition-case err
655 (progn
656 (funcall backend 'init)
657 (put backend 'company-init t))
658 (error
659 (put backend 'company-init 'failed)
660 (unless (memq backend company--disabled-backends)
661 (message "Company back-end '%s' could not be initialized:\n%s"
662 backend (error-message-string err)))
663 (cl-pushnew backend company--disabled-backends)
664 nil)))
665 ;; No initialization for lambdas.
666 ((functionp backend) t)
667 (t ;; Must be a list.
668 (cl-dolist (b backend)
669 (unless (keywordp b)
670 (company-init-backend b))))))
671
672 (defcustom company-lighter-base "company"
673 "Base string to use for the `company-mode' lighter."
674 :type 'string
675 :package-version '(company . "0.8.10"))
676
677 (defvar company-lighter '(" "
678 (company-candidates
679 (:eval
680 (if (consp company-backend)
681 (company--group-lighter (nth company-selection
682 company-candidates)
683 company-lighter-base)
684 (symbol-name company-backend)))
685 company-lighter-base))
686 "Mode line lighter for Company.
687
688 The value of this variable is a mode line template as in
689 `mode-line-format'.")
690
691 (put 'company-lighter 'risky-local-variable t)
692
693 ;;;###autoload
694 (define-minor-mode company-mode
695 "\"complete anything\"; is an in-buffer completion framework.
696 Completion starts automatically, depending on the values
697 `company-idle-delay' and `company-minimum-prefix-length'.
698
699 Completion can be controlled with the commands:
700 `company-complete-common', `company-complete-selection', `company-complete',
701 `company-select-next', `company-select-previous'. If these commands are
702 called before `company-idle-delay', completion will also start.
703
704 Completions can be searched with `company-search-candidates' or
705 `company-filter-candidates'. These can be used while completion is
706 inactive, as well.
707
708 The completion data is retrieved using `company-backends' and displayed
709 using `company-frontends'. If you want to start a specific back-end, call
710 it interactively or use `company-begin-backend'.
711
712 By default, the completions list is sorted alphabetically, unless the
713 backend chooses otherwise, or `company-transformers' changes it later.
714
715 regular keymap (`company-mode-map'):
716
717 \\{company-mode-map}
718 keymap during active completions (`company-active-map'):
719
720 \\{company-active-map}"
721 nil company-lighter company-mode-map
722 (if company-mode
723 (progn
724 (when (eq company-idle-delay t)
725 (setq company-idle-delay 0)
726 (warn "Setting `company-idle-delay' to t is deprecated. Set it to 0 instead."))
727 (add-hook 'pre-command-hook 'company-pre-command nil t)
728 (add-hook 'post-command-hook 'company-post-command nil t)
729 (mapc 'company-init-backend company-backends))
730 (remove-hook 'pre-command-hook 'company-pre-command t)
731 (remove-hook 'post-command-hook 'company-post-command t)
732 (company-cancel)
733 (kill-local-variable 'company-point)))
734
735 (defcustom company-global-modes t
736 "Modes for which `company-mode' mode is turned on by `global-company-mode'.
737 If nil, means no modes. If t, then all major modes have it turned on.
738 If a list, it should be a list of `major-mode' symbol names for which
739 `company-mode' should be automatically turned on. The sense of the list is
740 negated if it begins with `not'. For example:
741 (c-mode c++-mode)
742 means that `company-mode' is turned on for buffers in C and C++ modes only.
743 (not message-mode)
744 means that `company-mode' is always turned on except in `message-mode' buffers."
745 :type '(choice (const :tag "none" nil)
746 (const :tag "all" t)
747 (set :menu-tag "mode specific" :tag "modes"
748 :value (not)
749 (const :tag "Except" not)
750 (repeat :inline t (symbol :tag "mode")))))
751
752 ;;;###autoload
753 (define-globalized-minor-mode global-company-mode company-mode company-mode-on)
754
755 (defun company-mode-on ()
756 (when (and (not (or noninteractive (eq (aref (buffer-name) 0) ?\s)))
757 (cond ((eq company-global-modes t)
758 t)
759 ((eq (car-safe company-global-modes) 'not)
760 (not (memq major-mode (cdr company-global-modes))))
761 (t (memq major-mode company-global-modes))))
762 (company-mode 1)))
763
764 (defsubst company-assert-enabled ()
765 (unless company-mode
766 (company-uninstall-map)
767 (error "Company not enabled")))
768
769 ;;; keymaps ;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;
770
771 (defvar-local company-my-keymap nil)
772
773 (defvar company-emulation-alist '((t . nil)))
774
775 (defsubst company-enable-overriding-keymap (keymap)
776 (company-uninstall-map)
777 (setq company-my-keymap keymap))
778
779 (defun company-ensure-emulation-alist ()
780 (unless (eq 'company-emulation-alist (car emulation-mode-map-alists))
781 (setq emulation-mode-map-alists
782 (cons 'company-emulation-alist
783 (delq 'company-emulation-alist emulation-mode-map-alists)))))
784
785 (defun company-install-map ()
786 (unless (or (cdar company-emulation-alist)
787 (null company-my-keymap))
788 (setf (cdar company-emulation-alist) company-my-keymap)))
789
790 (defun company-uninstall-map ()
791 (setf (cdar company-emulation-alist) nil))
792
793 ;; Hack:
794 ;; Emacs calculates the active keymaps before reading the event. That means we
795 ;; cannot change the keymap from a timer. So we send a bogus command.
796 ;; XXX: Even in Emacs 24.4, seems to be needed in the terminal.
797 (defun company-ignore ()
798 (interactive)
799 (setq this-command last-command))
800
801 (global-set-key '[company-dummy-event] 'company-ignore)
802
803 (defun company-input-noop ()
804 (push 'company-dummy-event unread-command-events))
805
806 (defun company--posn-col-row (posn)
807 (let ((col (car (posn-col-row posn)))
808 ;; `posn-col-row' doesn't work well with lines of different height.
809 ;; `posn-actual-col-row' doesn't handle multiple-width characters.
810 (row (cdr (posn-actual-col-row posn))))
811 (when (and header-line-format (version< emacs-version "24.3.93.3"))
812 ;; http://debbugs.gnu.org/18384
813 (cl-decf row))
814 (cons (+ col (window-hscroll)) row)))
815
816 (defun company--col-row (&optional pos)
817 (company--posn-col-row (posn-at-point pos)))
818
819 (defun company--row (&optional pos)
820 (cdr (company--col-row pos)))
821
822 ;;; backends ;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;
823
824 (defvar-local company-backend nil)
825
826 (defun company-grab (regexp &optional expression limit)
827 (when (looking-back regexp limit)
828 (or (match-string-no-properties (or expression 0)) "")))
829
830 (defun company-grab-line (regexp &optional expression)
831 (company-grab regexp expression (point-at-bol)))
832
833 (defun company-grab-symbol ()
834 (if (looking-at "\\_>")
835 (buffer-substring (point) (save-excursion (skip-syntax-backward "w_")
836 (point)))
837 (unless (and (char-after) (memq (char-syntax (char-after)) '(?w ?_)))
838 "")))
839
840 (defun company-grab-word ()
841 (if (looking-at "\\>")
842 (buffer-substring (point) (save-excursion (skip-syntax-backward "w")
843 (point)))
844 (unless (and (char-after) (eq (char-syntax (char-after)) ?w))
845 "")))
846
847 (defun company-grab-symbol-cons (idle-begin-after-re &optional max-len)
848 (let ((symbol (company-grab-symbol)))
849 (when symbol
850 (save-excursion
851 (forward-char (- (length symbol)))
852 (if (looking-back idle-begin-after-re (if max-len
853 (- (point) max-len)
854 (line-beginning-position)))
855 (cons symbol t)
856 symbol)))))
857
858 (defun company-in-string-or-comment ()
859 (let ((ppss (syntax-ppss)))
860 (or (car (setq ppss (nthcdr 3 ppss)))
861 (car (setq ppss (cdr ppss)))
862 (nth 3 ppss))))
863
864 (defun company-call-backend (&rest args)
865 (company--force-sync #'company-call-backend-raw args company-backend))
866
867 (defun company--force-sync (fun args backend)
868 (let ((value (apply fun args)))
869 (if (not (eq (car-safe value) :async))
870 value
871 (let ((res 'trash)
872 (start (time-to-seconds)))
873 (funcall (cdr value)
874 (lambda (result) (setq res result)))
875 (while (eq res 'trash)
876 (if (> (- (time-to-seconds) start) company-async-timeout)
877 (error "Company: Back-end %s async timeout with args %s"
878 backend args)
879 (sleep-for company-async-wait)))
880 res))))
881
882 (defun company-call-backend-raw (&rest args)
883 (condition-case-unless-debug err
884 (if (functionp company-backend)
885 (apply company-backend args)
886 (apply #'company--multi-backend-adapter company-backend args))
887 (error (error "Company: Back-end %s error \"%s\" with args %s"
888 company-backend (error-message-string err) args))))
889
890 (defun company--multi-backend-adapter (backends command &rest args)
891 (let ((backends (cl-loop for b in backends
892 when (not (and (symbolp b)
893 (eq 'failed (get b 'company-init))))
894 collect b)))
895 (setq backends
896 (if (eq command 'prefix)
897 (butlast backends (length (member :with backends)))
898 (delq :with backends)))
899 (pcase command
900 (`candidates
901 (company--multi-backend-adapter-candidates backends (car args)))
902 (`sorted nil)
903 (`duplicates t)
904 ((or `prefix `ignore-case `no-cache `require-match)
905 (let (value)
906 (cl-dolist (backend backends)
907 (when (setq value (company--force-sync
908 backend (cons command args) backend))
909 (cl-return value)))))
910 (_
911 (let ((arg (car args)))
912 (when (> (length arg) 0)
913 (let ((backend (or (get-text-property 0 'company-backend arg)
914 (car backends))))
915 (apply backend command args))))))))
916
917 (defun company--multi-backend-adapter-candidates (backends prefix)
918 (let ((pairs (cl-loop for backend in (cdr backends)
919 when (equal (company--prefix-str
920 (funcall backend 'prefix))
921 prefix)
922 collect (cons (funcall backend 'candidates prefix)
923 (let ((b backend))
924 (lambda (candidates)
925 (mapcar
926 (lambda (str)
927 (propertize str 'company-backend b))
928 candidates)))))))
929 (when (equal (company--prefix-str (funcall (car backends) 'prefix)) prefix)
930 ;; Small perf optimization: don't tag the candidates received
931 ;; from the first backend in the group.
932 (push (cons (funcall (car backends) 'candidates prefix)
933 'identity)
934 pairs))
935 (company--merge-async pairs (lambda (values) (apply #'append values)))))
936
937 (defun company--merge-async (pairs merger)
938 (let ((async (cl-loop for pair in pairs
939 thereis
940 (eq :async (car-safe (car pair))))))
941 (if (not async)
942 (funcall merger (cl-loop for (val . mapper) in pairs
943 collect (funcall mapper val)))
944 (cons
945 :async
946 (lambda (callback)
947 (let* (lst
948 (pending (mapcar #'car pairs))
949 (finisher (lambda ()
950 (unless pending
951 (funcall callback
952 (funcall merger
953 (nreverse lst)))))))
954 (dolist (pair pairs)
955 (push nil lst)
956 (let* ((cell lst)
957 (val (car pair))
958 (mapper (cdr pair))
959 (this-finisher (lambda (res)
960 (setq pending (delq val pending))
961 (setcar cell (funcall mapper res))
962 (funcall finisher))))
963 (if (not (eq :async (car-safe val)))
964 (funcall this-finisher val)
965 (let ((fetcher (cdr val)))
966 (funcall fetcher this-finisher)))))))))))
967
968 (defun company--prefix-str (prefix)
969 (or (car-safe prefix) prefix))
970
971 ;;; completion mechanism ;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;
972
973 (defvar-local company-prefix nil)
974
975 (defvar-local company-candidates nil)
976
977 (defvar-local company-candidates-length nil)
978
979 (defvar-local company-candidates-cache nil)
980
981 (defvar-local company-candidates-predicate nil)
982
983 (defvar-local company-common nil)
984
985 (defvar-local company-selection 0)
986
987 (defvar-local company-selection-changed nil)
988
989 (defvar-local company--manual-action nil
990 "Non-nil, if manual completion took place.")
991
992 (defvar-local company--manual-prefix nil)
993
994 (defvar company--auto-completion nil
995 "Non-nil when current candidate is being inserted automatically.
996 Controlled by `company-auto-complete'.")
997
998 (defvar-local company--point-max nil)
999
1000 (defvar-local company-point nil)
1001
1002 (defvar company-timer nil)
1003
1004 (defsubst company-strip-prefix (str)
1005 (substring str (length company-prefix)))
1006
1007 (defun company--insert-candidate (candidate)
1008 (when (> (length candidate) 0)
1009 (setq candidate (substring-no-properties candidate))
1010 ;; XXX: Return value we check here is subject to change.
1011 (if (eq (company-call-backend 'ignore-case) 'keep-prefix)
1012 (insert (company-strip-prefix candidate))
1013 (unless (equal company-prefix candidate)
1014 (delete-region (- (point) (length company-prefix)) (point))
1015 (insert candidate)))))
1016
1017 (defmacro company-with-candidate-inserted (candidate &rest body)
1018 "Evaluate BODY with CANDIDATE temporarily inserted.
1019 This is a tool for back-ends that need candidates inserted before they
1020 can retrieve meta-data for them."
1021 (declare (indent 1))
1022 `(let ((inhibit-modification-hooks t)
1023 (inhibit-point-motion-hooks t)
1024 (modified-p (buffer-modified-p)))
1025 (company--insert-candidate ,candidate)
1026 (unwind-protect
1027 (progn ,@body)
1028 (delete-region company-point (point))
1029 (set-buffer-modified-p modified-p))))
1030
1031 (defun company-explicit-action-p ()
1032 "Return whether explicit completion action was taken by the user."
1033 (or company--manual-action
1034 company-selection-changed))
1035
1036 (defun company-reformat (candidate)
1037 ;; company-ispell needs this, because the results are always lower-case
1038 ;; It's mory efficient to fix it only when they are displayed.
1039 ;; FIXME: Adopt the current text's capitalization instead?
1040 (if (eq (company-call-backend 'ignore-case) 'keep-prefix)
1041 (concat company-prefix (substring candidate (length company-prefix)))
1042 candidate))
1043
1044 (defun company--should-complete ()
1045 (and (eq company-idle-delay 'now)
1046 (not (or buffer-read-only overriding-terminal-local-map
1047 overriding-local-map))
1048 ;; Check if in the middle of entering a key combination.
1049 (or (equal (this-command-keys-vector) [])
1050 (not (keymapp (key-binding (this-command-keys-vector)))))
1051 (not (and transient-mark-mode mark-active))))
1052
1053 (defun company--should-continue ()
1054 (or (eq t company-begin-commands)
1055 (eq t company-continue-commands)
1056 (if (eq 'not (car company-continue-commands))
1057 (not (memq this-command (cdr company-continue-commands)))
1058 (or (memq this-command company-begin-commands)
1059 (memq this-command company-continue-commands)
1060 (and (symbolp this-command)
1061 (string-match-p "\\`company-" (symbol-name this-command)))))))
1062
1063 (defun company-call-frontends (command)
1064 (dolist (frontend company-frontends)
1065 (condition-case-unless-debug err
1066 (funcall frontend command)
1067 (error (error "Company: Front-end %s error \"%s\" on command %s"
1068 frontend (error-message-string err) command)))))
1069
1070 (defun company-set-selection (selection &optional force-update)
1071 (setq selection
1072 (if company-selection-wrap-around
1073 (mod selection company-candidates-length)
1074 (max 0 (min (1- company-candidates-length) selection))))
1075 (when (or force-update (not (equal selection company-selection)))
1076 (setq company-selection selection
1077 company-selection-changed t)
1078 (company-call-frontends 'update)))
1079
1080 (defun company--group-lighter (candidate base)
1081 (let ((backend (or (get-text-property 0 'company-backend candidate)
1082 (car company-backend))))
1083 (when (and backend (symbolp backend))
1084 (let ((name (replace-regexp-in-string "company-\\|-company" ""
1085 (symbol-name backend))))
1086 (format "%s-<%s>" base name)))))
1087
1088 (defun company-update-candidates (candidates)
1089 (setq company-candidates-length (length candidates))
1090 (if company-selection-changed
1091 ;; Try to restore the selection
1092 (let ((selected (nth company-selection company-candidates)))
1093 (setq company-selection 0
1094 company-candidates candidates)
1095 (when selected
1096 (catch 'found
1097 (while candidates
1098 (let ((candidate (pop candidates)))
1099 (when (and (string= candidate selected)
1100 (equal (company-call-backend 'annotation candidate)
1101 (company-call-backend 'annotation selected)))
1102 (throw 'found t)))
1103 (cl-incf company-selection))
1104 (setq company-selection 0
1105 company-selection-changed nil))))
1106 (setq company-selection 0
1107 company-candidates candidates))
1108 ;; Calculate common.
1109 (let ((completion-ignore-case (company-call-backend 'ignore-case)))
1110 ;; We want to support non-prefix completion, so filtering is the
1111 ;; responsibility of each respective backend, not ours.
1112 ;; On the other hand, we don't want to replace non-prefix input in
1113 ;; `company-complete-common', unless there's only one candidate.
1114 (setq company-common
1115 (if (cdr company-candidates)
1116 (let ((common (try-completion "" company-candidates)))
1117 (when (string-prefix-p company-prefix common
1118 completion-ignore-case)
1119 common))
1120 (car company-candidates)))))
1121
1122 (defun company-calculate-candidates (prefix)
1123 (let ((candidates (cdr (assoc prefix company-candidates-cache)))
1124 (ignore-case (company-call-backend 'ignore-case)))
1125 (or candidates
1126 (when company-candidates-cache
1127 (let ((len (length prefix))
1128 (completion-ignore-case ignore-case)
1129 prev)
1130 (cl-dotimes (i (1+ len))
1131 (when (setq prev (cdr (assoc (substring prefix 0 (- len i))
1132 company-candidates-cache)))
1133 (setq candidates (all-completions prefix prev))
1134 (cl-return t)))))
1135 (progn
1136 ;; No cache match, call the backend.
1137 (setq candidates (company--preprocess-candidates
1138 (company--fetch-candidates prefix)))
1139 ;; Save in cache.
1140 (push (cons prefix candidates) company-candidates-cache)))
1141 ;; Only now apply the predicate and transformers.
1142 (setq candidates (company--postprocess-candidates candidates))
1143 (when candidates
1144 (if (or (cdr candidates)
1145 (not (eq t (compare-strings (car candidates) nil nil
1146 prefix nil nil ignore-case))))
1147 candidates
1148 ;; Already completed and unique; don't start.
1149 t))))
1150
1151 (defun company--fetch-candidates (prefix)
1152 (let ((c (if company--manual-action
1153 (company-call-backend 'candidates prefix)
1154 (company-call-backend-raw 'candidates prefix)))
1155 res)
1156 (if (not (eq (car c) :async))
1157 c
1158 (let ((buf (current-buffer))
1159 (win (selected-window))
1160 (tick (buffer-chars-modified-tick))
1161 (pt (point))
1162 (backend company-backend))
1163 (funcall
1164 (cdr c)
1165 (lambda (candidates)
1166 (if (not (and candidates (eq res 'done)))
1167 ;; There's no completions to display,
1168 ;; or the fetcher called us back right away.
1169 (setq res candidates)
1170 (setq company-backend backend
1171 company-candidates-cache
1172 (list (cons prefix
1173 (company--preprocess-candidates candidates))))
1174 (company-idle-begin buf win tick pt)))))
1175 ;; FIXME: Relying on the fact that the callers
1176 ;; will interpret nil as "do nothing" is shaky.
1177 ;; A throw-catch would be one possible improvement.
1178 (or res
1179 (progn (setq res 'done) nil)))))
1180
1181 (defun company--preprocess-candidates (candidates)
1182 (unless (company-call-backend 'sorted)
1183 (setq candidates (sort candidates 'string<)))
1184 (when (company-call-backend 'duplicates)
1185 (company--strip-duplicates candidates))
1186 candidates)
1187
1188 (defun company--postprocess-candidates (candidates)
1189 (when (or company-candidates-predicate company-transformers)
1190 (setq candidates (copy-sequence candidates)))
1191 (when company-candidates-predicate
1192 (setq candidates (cl-delete-if-not company-candidates-predicate candidates)))
1193 (company--transform-candidates candidates))
1194
1195 (defun company--strip-duplicates (candidates)
1196 (let ((c2 candidates)
1197 (annos 'unk))
1198 (while c2
1199 (setcdr c2
1200 (let ((str (pop c2)))
1201 (while (let ((str2 (car c2)))
1202 (if (not (equal str str2))
1203 (progn
1204 (setq annos 'unk)
1205 nil)
1206 (when (eq annos 'unk)
1207 (setq annos (list (company-call-backend
1208 'annotation str))))
1209 (let ((anno2 (company-call-backend
1210 'annotation str2)))
1211 (if (member anno2 annos)
1212 t
1213 (push anno2 annos)
1214 nil))))
1215 (pop c2))
1216 c2)))))
1217
1218 (defun company--transform-candidates (candidates)
1219 (let ((c candidates))
1220 (dolist (tr company-transformers)
1221 (setq c (funcall tr c)))
1222 c))
1223
1224 (defcustom company-occurrence-weight-function
1225 #'company-occurrence-prefer-closest-above
1226 "Function to weigh matches in `company-sort-by-occurrence'.
1227 It's called with three arguments: cursor position, the beginning and the
1228 end of the match."
1229 :type '(choice
1230 (const :tag "First above point, then below point"
1231 company-occurrence-prefer-closest-above)
1232 (const :tag "Prefer closest in any direction"
1233 company-occurrence-prefer-any-closest)))
1234
1235 (defun company-occurrence-prefer-closest-above (pos match-beg match-end)
1236 "Give priority to the matches above point, then those below point."
1237 (if (< match-beg pos)
1238 (- pos match-end)
1239 (- match-beg (window-start))))
1240
1241 (defun company-occurrence-prefer-any-closest (pos _match-beg match-end)
1242 "Give priority to the matches closest to the point."
1243 (abs (- pos match-end)))
1244
1245 (defun company-sort-by-occurrence (candidates)
1246 "Sort CANDIDATES according to their occurrences.
1247 Searches for each in the currently visible part of the current buffer and
1248 prioritizes the matches according to `company-occurrence-weight-function'.
1249 The rest of the list is appended unchanged.
1250 Keywords and function definition names are ignored."
1251 (let* ((w-start (window-start))
1252 (w-end (window-end))
1253 (start-point (point))
1254 occurs
1255 (noccurs
1256 (save-excursion
1257 (cl-delete-if
1258 (lambda (candidate)
1259 (when (catch 'done
1260 (goto-char w-start)
1261 (while (search-forward candidate w-end t)
1262 (when (and (not (eq (point) start-point))
1263 (save-match-data
1264 (company--occurrence-predicate)))
1265 (throw 'done t))))
1266 (push
1267 (cons candidate
1268 (funcall company-occurrence-weight-function
1269 start-point
1270 (match-beginning 0)
1271 (match-end 0)))
1272 occurs)
1273 t))
1274 candidates))))
1275 (nconc
1276 (mapcar #'car (sort occurs (lambda (e1 e2) (<= (cdr e1) (cdr e2)))))
1277 noccurs)))
1278
1279 (defun company--occurrence-predicate ()
1280 (let ((beg (match-beginning 0))
1281 (end (match-end 0)))
1282 (save-excursion
1283 (goto-char end)
1284 (and (not (memq (get-text-property (1- (point)) 'face)
1285 '(font-lock-function-name-face
1286 font-lock-keyword-face)))
1287 (let ((prefix (company--prefix-str
1288 (company-call-backend 'prefix))))
1289 (and (stringp prefix)
1290 (= (length prefix) (- end beg))))))))
1291
1292 (defun company-sort-by-backend-importance (candidates)
1293 "Sort CANDIDATES as two priority groups.
1294 If `company-backend' is a function, do nothing. If it's a list, move
1295 candidates from back-ends before keyword `:with' to the front. Candidates
1296 from the rest of the back-ends in the group, if any, will be left at the end."
1297 (if (functionp company-backend)
1298 candidates
1299 (let ((low-priority (cdr (memq :with company-backend))))
1300 (if (null low-priority)
1301 candidates
1302 (sort candidates
1303 (lambda (c1 c2)
1304 (and
1305 (let ((b2 (get-text-property 0 'company-backend c2)))
1306 (and b2 (memq b2 low-priority)))
1307 (let ((b1 (get-text-property 0 'company-backend c1)))
1308 (or (not b1) (not (memq b1 low-priority)))))))))))
1309
1310 (defun company-idle-begin (buf win tick pos)
1311 (and (eq buf (current-buffer))
1312 (eq win (selected-window))
1313 (eq tick (buffer-chars-modified-tick))
1314 (eq pos (point))
1315 (when (company-auto-begin)
1316 (company-input-noop)
1317 (let ((this-command 'company-idle-begin))
1318 (company-post-command)))))
1319
1320 (defun company-auto-begin ()
1321 (and company-mode
1322 (not company-candidates)
1323 (let ((company-idle-delay 'now))
1324 (condition-case-unless-debug err
1325 (progn
1326 (company--perform)
1327 ;; Return non-nil if active.
1328 company-candidates)
1329 (error (message "Company: An error occurred in auto-begin")
1330 (message "%s" (error-message-string err))
1331 (company-cancel))
1332 (quit (company-cancel))))))
1333
1334 (defun company-manual-begin ()
1335 (interactive)
1336 (company-assert-enabled)
1337 (setq company--manual-action t)
1338 (unwind-protect
1339 (let ((company-minimum-prefix-length 0))
1340 (or company-candidates
1341 (company-auto-begin)))
1342 (unless company-candidates
1343 (setq company--manual-action nil))))
1344
1345 (defun company-other-backend (&optional backward)
1346 (interactive (list current-prefix-arg))
1347 (company-assert-enabled)
1348 (let* ((after (if company-backend
1349 (cdr (member company-backend company-backends))
1350 company-backends))
1351 (before (cdr (member company-backend (reverse company-backends))))
1352 (next (if backward
1353 (append before (reverse after))
1354 (append after (reverse before)))))
1355 (company-cancel)
1356 (cl-dolist (backend next)
1357 (when (ignore-errors (company-begin-backend backend))
1358 (cl-return t))))
1359 (unless company-candidates
1360 (error "No other back-end")))
1361
1362 (defun company-require-match-p ()
1363 (let ((backend-value (company-call-backend 'require-match)))
1364 (or (eq backend-value t)
1365 (and (not (eq backend-value 'never))
1366 (if (functionp company-require-match)
1367 (funcall company-require-match)
1368 (eq company-require-match t))))))
1369
1370 (defun company-auto-complete-p (input)
1371 "Return non-nil, if input starts with punctuation or parentheses."
1372 (and (if (functionp company-auto-complete)
1373 (funcall company-auto-complete)
1374 company-auto-complete)
1375 (if (functionp company-auto-complete-chars)
1376 (funcall company-auto-complete-chars input)
1377 (if (consp company-auto-complete-chars)
1378 (memq (char-syntax (string-to-char input))
1379 company-auto-complete-chars)
1380 (string-match (substring input 0 1) company-auto-complete-chars)))))
1381
1382 (defun company--incremental-p ()
1383 (and (> (point) company-point)
1384 (> (point-max) company--point-max)
1385 (not (eq this-command 'backward-delete-char-untabify))
1386 (equal (buffer-substring (- company-point (length company-prefix))
1387 company-point)
1388 company-prefix)))
1389
1390 (defun company--continue-failed (new-prefix)
1391 (let ((input (buffer-substring-no-properties (point) company-point)))
1392 (cond
1393 ((company-auto-complete-p input)
1394 ;; auto-complete
1395 (save-excursion
1396 (goto-char company-point)
1397 (let ((company--auto-completion t))
1398 (company-complete-selection))
1399 nil))
1400 ((and (or (not (company-require-match-p))
1401 ;; Don't require match if the new prefix
1402 ;; doesn't continue the old one, and the latter was a match.
1403 (not (stringp new-prefix))
1404 (<= (length new-prefix) (length company-prefix)))
1405 (member company-prefix company-candidates))
1406 ;; Last input was a success,
1407 ;; but we're treating it as an abort + input anyway,
1408 ;; like the `unique' case below.
1409 (company-cancel 'non-unique))
1410 ((company-require-match-p)
1411 ;; Wrong incremental input, but required match.
1412 (delete-char (- (length input)))
1413 (ding)
1414 (message "Matching input is required")
1415 company-candidates)
1416 (t (company-cancel)))))
1417
1418 (defun company--good-prefix-p (prefix)
1419 (and (stringp (company--prefix-str prefix)) ;excludes 'stop
1420 (or (eq (cdr-safe prefix) t)
1421 (let ((len (or (cdr-safe prefix) (length prefix))))
1422 (if company--manual-prefix
1423 (or (not company-abort-manual-when-too-short)
1424 ;; Must not be less than minimum or initial length.
1425 (>= len (min company-minimum-prefix-length
1426 (length company--manual-prefix))))
1427 (>= len company-minimum-prefix-length))))))
1428
1429 (defun company--continue ()
1430 (when (company-call-backend 'no-cache company-prefix)
1431 ;; Don't complete existing candidates, fetch new ones.
1432 (setq company-candidates-cache nil))
1433 (let* ((new-prefix (company-call-backend 'prefix))
1434 (c (when (and (company--good-prefix-p new-prefix)
1435 (setq new-prefix (company--prefix-str new-prefix))
1436 (= (- (point) (length new-prefix))
1437 (- company-point (length company-prefix))))
1438 (company-calculate-candidates new-prefix))))
1439 (cond
1440 ((eq c t)
1441 ;; t means complete/unique.
1442 ;; Handle it like completion was aborted, to differentiate from user
1443 ;; calling one of Company's commands to insert the candidate,
1444 ;; not to trigger template expansion, etc.
1445 (company-cancel 'unique))
1446 ((consp c)
1447 ;; incremental match
1448 (setq company-prefix new-prefix)
1449 (company-update-candidates c)
1450 c)
1451 ((not (company--incremental-p))
1452 (company-cancel))
1453 (t (company--continue-failed new-prefix)))))
1454
1455 (defun company--begin-new ()
1456 (let (prefix c)
1457 (cl-dolist (backend (if company-backend
1458 ;; prefer manual override
1459 (list company-backend)
1460 company-backends))
1461 (setq prefix
1462 (if (or (symbolp backend)
1463 (functionp backend))
1464 (when (or (not (symbolp backend))
1465 (eq t (get backend 'company-init))
1466 (unless (get backend 'company-init)
1467 (company-init-backend backend)))
1468 (funcall backend 'prefix))
1469 (company--multi-backend-adapter backend 'prefix)))
1470 (when prefix
1471 (when (company--good-prefix-p prefix)
1472 (setq company-prefix (company--prefix-str prefix)
1473 company-backend backend
1474 c (company-calculate-candidates company-prefix))
1475 (if (not (consp c))
1476 (progn
1477 (when company--manual-action
1478 (message "No completion found"))
1479 (when (eq c t)
1480 ;; t means complete/unique.
1481 ;; Run the hooks anyway, to e.g. clear the cache.
1482 (company-cancel 'unique)))
1483 (when company--manual-action
1484 (setq company--manual-prefix prefix))
1485 (company-update-candidates c)
1486 (run-hook-with-args 'company-completion-started-hook
1487 (company-explicit-action-p))
1488 (company-call-frontends 'show)))
1489 (cl-return c)))))
1490
1491 (defun company--perform ()
1492 (or (and company-candidates (company--continue))
1493 (and (company--should-complete) (company--begin-new)))
1494 (if (not company-candidates)
1495 (setq company-backend nil)
1496 (setq company-point (point)
1497 company--point-max (point-max))
1498 (company-ensure-emulation-alist)
1499 (company-enable-overriding-keymap company-active-map)
1500 (company-call-frontends 'update)))
1501
1502 (defun company-cancel (&optional result)
1503 (unwind-protect
1504 (when company-prefix
1505 (if (stringp result)
1506 (progn
1507 (company-call-backend 'pre-completion result)
1508 (run-hook-with-args 'company-completion-finished-hook result)
1509 (company-call-backend 'post-completion result))
1510 (run-hook-with-args 'company-completion-cancelled-hook result)))
1511 (setq company-backend nil
1512 company-prefix nil
1513 company-candidates nil
1514 company-candidates-length nil
1515 company-candidates-cache nil
1516 company-candidates-predicate nil
1517 company-common nil
1518 company-selection 0
1519 company-selection-changed nil
1520 company--manual-action nil
1521 company--manual-prefix nil
1522 company--point-max nil
1523 company-point nil)
1524 (when company-timer
1525 (cancel-timer company-timer))
1526 (company-echo-cancel t)
1527 (company-search-mode 0)
1528 (company-call-frontends 'hide)
1529 (company-enable-overriding-keymap nil))
1530 ;; Make return value explicit.
1531 nil)
1532
1533 (defun company-abort ()
1534 (interactive)
1535 (company-cancel 'abort))
1536
1537 (defun company-finish (result)
1538 (company--insert-candidate result)
1539 (company-cancel result))
1540
1541 (defsubst company-keep (command)
1542 (and (symbolp command) (get command 'company-keep)))
1543
1544 (defun company-pre-command ()
1545 (unless (company-keep this-command)
1546 (condition-case-unless-debug err
1547 (when company-candidates
1548 (company-call-frontends 'pre-command)
1549 (unless (company--should-continue)
1550 (company-abort)))
1551 (error (message "Company: An error occurred in pre-command")
1552 (message "%s" (error-message-string err))
1553 (company-cancel))))
1554 (when company-timer
1555 (cancel-timer company-timer)
1556 (setq company-timer nil))
1557 (company-echo-cancel t)
1558 (company-uninstall-map))
1559
1560 (defun company-post-command ()
1561 (when (null this-command)
1562 ;; Happens when the user presses `C-g' while inside
1563 ;; `flyspell-post-command-hook', for example.
1564 ;; Or any other `post-command-hook' function that can call `sit-for',
1565 ;; or any quittable timer function.
1566 (company-abort)
1567 (setq this-command 'company-abort))
1568 (unless (company-keep this-command)
1569 (condition-case-unless-debug err
1570 (progn
1571 (unless (equal (point) company-point)
1572 (let (company-idle-delay) ; Against misbehavior while debugging.
1573 (company--perform)))
1574 (if company-candidates
1575 (company-call-frontends 'post-command)
1576 (and (numberp company-idle-delay)
1577 (company--should-begin)
1578 (setq company-timer
1579 (run-with-timer company-idle-delay nil
1580 'company-idle-begin
1581 (current-buffer) (selected-window)
1582 (buffer-chars-modified-tick) (point))))))
1583 (error (message "Company: An error occurred in post-command")
1584 (message "%s" (error-message-string err))
1585 (company-cancel))))
1586 (company-install-map))
1587
1588 (defvar company--begin-inhibit-commands '(company-abort
1589 company-complete-mouse
1590 company-complete
1591 company-complete-common
1592 company-complete-selection
1593 company-complete-number)
1594 "List of commands after which idle completion is (still) disabled when
1595 `company-begin-commands' is t.")
1596
1597 (defun company--should-begin ()
1598 (if (eq t company-begin-commands)
1599 (not (memq this-command company--begin-inhibit-commands))
1600 (or
1601 (memq this-command company-begin-commands)
1602 (and (symbolp this-command) (get this-command 'company-begin)))))
1603
1604 ;;; search ;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;
1605
1606 (defvar-local company-search-string "")
1607
1608 (defvar company-search-lighter '(" "
1609 (company-search-filtering "Filter" "Search")
1610 ": \""
1611 company-search-string
1612 "\""))
1613
1614 (defvar-local company-search-filtering nil
1615 "Non-nil to filter the completion candidates by the search string")
1616
1617 (defvar-local company--search-old-selection 0)
1618
1619 (defvar-local company--search-old-changed nil)
1620
1621 (defun company--search (text lines)
1622 (let ((quoted (regexp-quote text))
1623 (i 0))
1624 (cl-dolist (line lines)
1625 (when (string-match quoted line (length company-prefix))
1626 (cl-return i))
1627 (cl-incf i))))
1628
1629 (defun company-search-keypad ()
1630 (interactive)
1631 (let* ((name (symbol-name last-command-event))
1632 (last-command-event (aref name (1- (length name)))))
1633 (company-search-printing-char)))
1634
1635 (defun company-search-printing-char ()
1636 (interactive)
1637 (company--search-assert-enabled)
1638 (let ((ss (concat company-search-string (string last-command-event))))
1639 (when company-search-filtering
1640 (company--search-update-predicate ss))
1641 (company--search-update-string ss)))
1642
1643 (defun company--search-update-predicate (&optional ss)
1644 (let* ((company-candidates-predicate
1645 (and (not (string= ss ""))
1646 company-search-filtering
1647 (lambda (candidate) (string-match ss candidate))))
1648 (cc (company-calculate-candidates company-prefix)))
1649 (unless cc (error "No match"))
1650 (company-update-candidates cc)))
1651
1652 (defun company--search-update-string (new)
1653 (let* ((pos (company--search new (nthcdr company-selection company-candidates))))
1654 (if (null pos)
1655 (ding)
1656 (setq company-search-string new)
1657 (company-set-selection (+ company-selection pos) t))))
1658
1659 (defun company--search-assert-input ()
1660 (company--search-assert-enabled)
1661 (when (string= company-search-string "")
1662 (error "Empty search string")))
1663
1664 (defun company-search-repeat-forward ()
1665 "Repeat the incremental search in completion candidates forward."
1666 (interactive)
1667 (company--search-assert-input)
1668 (let ((pos (company--search company-search-string
1669 (cdr (nthcdr company-selection
1670 company-candidates)))))
1671 (if (null pos)
1672 (ding)
1673 (company-set-selection (+ company-selection pos 1) t))))
1674
1675 (defun company-search-repeat-backward ()
1676 "Repeat the incremental search in completion candidates backwards."
1677 (interactive)
1678 (company--search-assert-input)
1679 (let ((pos (company--search company-search-string
1680 (nthcdr (- company-candidates-length
1681 company-selection)
1682 (reverse company-candidates)))))
1683 (if (null pos)
1684 (ding)
1685 (company-set-selection (- company-selection pos 1) t))))
1686
1687 (defun company-search-toggle-filtering ()
1688 "Toggle `company-search-filtering'."
1689 (interactive)
1690 (company--search-assert-enabled)
1691 (setq company-search-filtering (not company-search-filtering))
1692 (let ((ss company-search-string))
1693 (company--search-update-predicate ss)
1694 (company--search-update-string ss)))
1695
1696 (defun company-search-abort ()
1697 "Abort searching the completion candidates."
1698 (interactive)
1699 (company--search-assert-enabled)
1700 (company-search-mode 0)
1701 (company-set-selection company--search-old-selection t)
1702 (setq company-selection-changed company--search-old-changed))
1703
1704 (defun company-search-other-char ()
1705 (interactive)
1706 (company--search-assert-enabled)
1707 (company-search-mode 0)
1708 (company--unread-last-input))
1709
1710 (defun company-search-delete-char ()
1711 (interactive)
1712 (company--search-assert-enabled)
1713 (if (string= company-search-string "")
1714 (ding)
1715 (let ((ss (substring company-search-string 0 -1)))
1716 (when company-search-filtering
1717 (company--search-update-predicate ss))
1718 (company--search-update-string ss))))
1719
1720 (defvar company-search-map
1721 (let ((i 0)
1722 (keymap (make-keymap)))
1723 (if (fboundp 'max-char)
1724 (set-char-table-range (nth 1 keymap) (cons #x100 (max-char))
1725 'company-search-printing-char)
1726 (with-no-warnings
1727 ;; obsolete in Emacs 23
1728 (let ((l (generic-character-list))
1729 (table (nth 1 keymap)))
1730 (while l
1731 (set-char-table-default table (car l) 'company-search-printing-char)
1732 (setq l (cdr l))))))
1733 (define-key keymap [t] 'company-search-other-char)
1734 (while (< i ?\s)
1735 (define-key keymap (make-string 1 i) 'company-search-other-char)
1736 (cl-incf i))
1737 (while (< i 256)
1738 (define-key keymap (vector i) 'company-search-printing-char)
1739 (cl-incf i))
1740 (dotimes (i 10)
1741 (define-key keymap (read (format "[kp-%s]" i)) 'company-search-keypad))
1742 (let ((meta-map (make-sparse-keymap)))
1743 (define-key keymap (char-to-string meta-prefix-char) meta-map)
1744 (define-key keymap [escape] meta-map))
1745 (define-key keymap (vector meta-prefix-char t) 'company-search-other-char)
1746 (define-key keymap (kbd "M-n") 'company-select-next)
1747 (define-key keymap (kbd "M-p") 'company-select-previous)
1748 (define-key keymap (kbd "<down>") 'company-select-next-or-abort)
1749 (define-key keymap (kbd "<up>") 'company-select-previous-or-abort)
1750 (define-key keymap "\e\e\e" 'company-search-other-char)
1751 (define-key keymap [escape escape escape] 'company-search-other-char)
1752 (define-key keymap (kbd "DEL") 'company-search-delete-char)
1753 (define-key keymap [backspace] 'company-search-delete-char)
1754 (define-key keymap "\C-g" 'company-search-abort)
1755 (define-key keymap "\C-s" 'company-search-repeat-forward)
1756 (define-key keymap "\C-r" 'company-search-repeat-backward)
1757 (define-key keymap "\C-o" 'company-search-toggle-filtering)
1758 (dotimes (i 10)
1759 (define-key keymap (read-kbd-macro (format "M-%d" i)) 'company-complete-number))
1760 keymap)
1761 "Keymap used for incrementally searching the completion candidates.")
1762
1763 (define-minor-mode company-search-mode
1764 "Search mode for completion candidates.
1765 Don't start this directly, use `company-search-candidates' or
1766 `company-filter-candidates'."
1767 nil company-search-lighter nil
1768 (if company-search-mode
1769 (if (company-manual-begin)
1770 (progn
1771 (setq company--search-old-selection company-selection
1772 company--search-old-changed company-selection-changed)
1773 (company-call-frontends 'update)
1774 (company-enable-overriding-keymap company-search-map))
1775 (setq company-search-mode nil))
1776 (kill-local-variable 'company-search-string)
1777 (kill-local-variable 'company-search-filtering)
1778 (kill-local-variable 'company--search-old-selection)
1779 (kill-local-variable 'company--search-old-changed)
1780 (when company-backend
1781 (company--search-update-predicate "")
1782 (company-call-frontends 'update))
1783 (company-enable-overriding-keymap company-active-map)))
1784
1785 (defun company--search-assert-enabled ()
1786 (company-assert-enabled)
1787 (unless company-search-mode
1788 (company-uninstall-map)
1789 (error "Company not in search mode")))
1790
1791 (defun company-search-candidates ()
1792 "Start searching the completion candidates incrementally.
1793
1794 \\<company-search-map>Search can be controlled with the commands:
1795 - `company-search-repeat-forward' (\\[company-search-repeat-forward])
1796 - `company-search-repeat-backward' (\\[company-search-repeat-backward])
1797 - `company-search-abort' (\\[company-search-abort])
1798 - `company-search-delete-char' (\\[company-search-delete-char])
1799
1800 Regular characters are appended to the search string.
1801
1802 The command `company-search-toggle-filtering' (\\[company-search-toggle-filtering])
1803 uses the search string to filter the completion candidates."
1804 (interactive)
1805 (company-search-mode 1))
1806
1807 (defvar company-filter-map
1808 (let ((keymap (make-keymap)))
1809 (define-key keymap [remap company-search-printing-char]
1810 'company-filter-printing-char)
1811 (set-keymap-parent keymap company-search-map)
1812 keymap)
1813 "Keymap used for incrementally searching the completion candidates.")
1814
1815 (defun company-filter-candidates ()
1816 "Start filtering the completion candidates incrementally.
1817 This works the same way as `company-search-candidates' immediately
1818 followed by `company-search-toggle-filtering'."
1819 (interactive)
1820 (company-search-mode 1)
1821 (setq company-search-filtering t))
1822
1823 ;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;
1824
1825 (defun company-select-next (&optional arg)
1826 "Select the next candidate in the list.
1827
1828 With ARG, move by that many elements."
1829 (interactive "p")
1830 (when (company-manual-begin)
1831 (company-set-selection (+ (or arg 1) company-selection))))
1832
1833 (defun company-select-previous (&optional arg)
1834 "Select the previous candidate in the list.
1835
1836 With ARG, move by that many elements."
1837 (interactive "p")
1838 (company-select-next (if arg (- arg) -1)))
1839
1840 (defun company-select-next-or-abort (&optional arg)
1841 "Select the next candidate if more than one, else abort
1842 and invoke the normal binding.
1843
1844 With ARG, move by that many elements."
1845 (interactive "p")
1846 (if (> company-candidates-length 1)
1847 (company-select-next arg)
1848 (company-abort)
1849 (company--unread-last-input)))
1850
1851 (defun company-select-previous-or-abort (&optional arg)
1852 "Select the previous candidate if more than one, else abort
1853 and invoke the normal binding.
1854
1855 With ARG, move by that many elements."
1856 (interactive "p")
1857 (if (> company-candidates-length 1)
1858 (company-select-previous arg)
1859 (company-abort)
1860 (company--unread-last-input)))
1861
1862 (defun company-next-page ()
1863 "Select the candidate one page further."
1864 (interactive)
1865 (when (company-manual-begin)
1866 (company-set-selection (+ company-selection
1867 company-tooltip-limit))))
1868
1869 (defun company-previous-page ()
1870 "Select the candidate one page earlier."
1871 (interactive)
1872 (when (company-manual-begin)
1873 (company-set-selection (- company-selection
1874 company-tooltip-limit))))
1875
1876 (defvar company-pseudo-tooltip-overlay)
1877
1878 (defvar company-tooltip-offset)
1879
1880 (defun company--inside-tooltip-p (event-col-row row height)
1881 (let* ((ovl company-pseudo-tooltip-overlay)
1882 (column (overlay-get ovl 'company-column))
1883 (width (overlay-get ovl 'company-width))
1884 (evt-col (car event-col-row))
1885 (evt-row (cdr event-col-row)))
1886 (and (>= evt-col column)
1887 (< evt-col (+ column width))
1888 (if (> height 0)
1889 (and (> evt-row row)
1890 (<= evt-row (+ row height) ))
1891 (and (< evt-row row)
1892 (>= evt-row (+ row height)))))))
1893
1894 (defun company--event-col-row (event)
1895 (company--posn-col-row (event-start event)))
1896
1897 (defun company-select-mouse (event)
1898 "Select the candidate picked by the mouse."
1899 (interactive "e")
1900 (let ((event-col-row (company--event-col-row event))
1901 (ovl-row (company--row))
1902 (ovl-height (and company-pseudo-tooltip-overlay
1903 (min (overlay-get company-pseudo-tooltip-overlay
1904 'company-height)
1905 company-candidates-length))))
1906 (if (and ovl-height
1907 (company--inside-tooltip-p event-col-row ovl-row ovl-height))
1908 (progn
1909 (company-set-selection (+ (cdr event-col-row)
1910 (1- company-tooltip-offset)
1911 (if (and (eq company-tooltip-offset-display 'lines)
1912 (not (zerop company-tooltip-offset)))
1913 -1 0)
1914 (- ovl-row)
1915 (if (< ovl-height 0)
1916 (- 1 ovl-height)
1917 0)))
1918 t)
1919 (company-abort)
1920 (company--unread-last-input)
1921 nil)))
1922
1923 (defun company-complete-mouse (event)
1924 "Insert the candidate picked by the mouse."
1925 (interactive "e")
1926 (when (company-select-mouse event)
1927 (company-complete-selection)))
1928
1929 (defun company-complete-selection ()
1930 "Insert the selected candidate."
1931 (interactive)
1932 (when (company-manual-begin)
1933 (let ((result (nth company-selection company-candidates)))
1934 (company-finish result))))
1935
1936 (defun company-complete-common ()
1937 "Insert the common part of all candidates."
1938 (interactive)
1939 (when (company-manual-begin)
1940 (if (and (not (cdr company-candidates))
1941 (equal company-common (car company-candidates)))
1942 (company-complete-selection)
1943 (company--insert-candidate company-common))))
1944
1945 (defun company-complete-common-or-cycle (&optional arg)
1946 "Insert the common part of all candidates, or select the next one.
1947
1948 With ARG, move by that many elements."
1949 (interactive "p")
1950 (when (company-manual-begin)
1951 (let ((tick (buffer-chars-modified-tick)))
1952 (call-interactively 'company-complete-common)
1953 (when (eq tick (buffer-chars-modified-tick))
1954 (let ((company-selection-wrap-around t)
1955 (current-prefix-arg arg))
1956 (call-interactively 'company-select-next))))))
1957
1958 (defun company-complete ()
1959 "Insert the common part of all candidates or the current selection.
1960 The first time this is called, the common part is inserted, the second
1961 time, or when the selection has been changed, the selected candidate is
1962 inserted."
1963 (interactive)
1964 (when (company-manual-begin)
1965 (if (or company-selection-changed
1966 (eq last-command 'company-complete-common))
1967 (call-interactively 'company-complete-selection)
1968 (call-interactively 'company-complete-common)
1969 (setq this-command 'company-complete-common))))
1970
1971 (defun company-complete-number (n)
1972 "Insert the Nth candidate visible in the tooltip.
1973 To show the number next to the candidates in some back-ends, enable
1974 `company-show-numbers'. When called interactively, uses the last typed
1975 character, stripping the modifiers. That character must be a digit."
1976 (interactive
1977 (list (let* ((type (event-basic-type last-command-event))
1978 (char (if (characterp type)
1979 ;; Number on the main row.
1980 type
1981 ;; Keypad number, if bound directly.
1982 (car (last (string-to-list (symbol-name type))))))
1983 (n (- char ?0)))
1984 (if (zerop n) 10 n))))
1985 (when (company-manual-begin)
1986 (and (or (< n 1) (> n (- company-candidates-length
1987 company-tooltip-offset)))
1988 (error "No candidate number %d" n))
1989 (cl-decf n)
1990 (company-finish (nth (+ n company-tooltip-offset)
1991 company-candidates))))
1992
1993 ;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;
1994
1995 (defconst company-space-strings-limit 100)
1996
1997 (defconst company-space-strings
1998 (let (lst)
1999 (dotimes (i company-space-strings-limit)
2000 (push (make-string (- company-space-strings-limit 1 i) ?\ ) lst))
2001 (apply 'vector lst)))
2002
2003 (defun company-space-string (len)
2004 (if (< len company-space-strings-limit)
2005 (aref company-space-strings len)
2006 (make-string len ?\ )))
2007
2008 (defun company-safe-substring (str from &optional to)
2009 (if (> from (string-width str))
2010 ""
2011 (with-temp-buffer
2012 (insert str)
2013 (move-to-column from)
2014 (let ((beg (point)))
2015 (if to
2016 (progn
2017 (move-to-column to)
2018 (concat (buffer-substring beg (point))
2019 (let ((padding (- to (current-column))))
2020 (when (> padding 0)
2021 (company-space-string padding)))))
2022 (buffer-substring beg (point-max)))))))
2023
2024 ;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;
2025
2026 (defvar-local company-last-metadata nil)
2027
2028 (defun company-fetch-metadata ()
2029 (let ((selected (nth company-selection company-candidates)))
2030 (unless (eq selected (car company-last-metadata))
2031 (setq company-last-metadata
2032 (cons selected (company-call-backend 'meta selected))))
2033 (cdr company-last-metadata)))
2034
2035 (defun company-doc-buffer (&optional string)
2036 (with-current-buffer (get-buffer-create "*company-documentation*")
2037 (erase-buffer)
2038 (when string
2039 (save-excursion
2040 (insert string)))
2041 (current-buffer)))
2042
2043 (defvar company--electric-commands
2044 '(scroll-other-window scroll-other-window-down mwheel-scroll)
2045 "List of Commands that won't break out of electric commands.")
2046
2047 (defmacro company--electric-do (&rest body)
2048 (declare (indent 0) (debug t))
2049 `(when (company-manual-begin)
2050 (save-window-excursion
2051 (let ((height (window-height))
2052 (row (company--row))
2053 cmd)
2054 ,@body
2055 (and (< (window-height) height)
2056 (< (- (window-height) row 2) company-tooltip-limit)
2057 (recenter (- (window-height) row 2)))
2058 (while (memq (setq cmd (key-binding (read-key-sequence-vector nil)))
2059 company--electric-commands)
2060 (condition-case err
2061 (call-interactively cmd)
2062 ((beginning-of-buffer end-of-buffer)
2063 (message (error-message-string err)))))
2064 (company--unread-last-input)))))
2065
2066 (defun company--unread-last-input ()
2067 (when last-input-event
2068 (clear-this-command-keys t)
2069 (setq unread-command-events (list last-input-event))))
2070
2071 (defun company-show-doc-buffer ()
2072 "Temporarily show the documentation buffer for the selection."
2073 (interactive)
2074 (let (other-window-scroll-buffer)
2075 (company--electric-do
2076 (let* ((selected (nth company-selection company-candidates))
2077 (doc-buffer (or (company-call-backend 'doc-buffer selected)
2078 (error "No documentation available")))
2079 start)
2080 (when (consp doc-buffer)
2081 (setq start (cdr doc-buffer)
2082 doc-buffer (car doc-buffer)))
2083 (setq other-window-scroll-buffer (get-buffer doc-buffer))
2084 (let ((win (display-buffer doc-buffer t)))
2085 (set-window-start win (if start start (point-min))))))))
2086 (put 'company-show-doc-buffer 'company-keep t)
2087
2088 (defun company-show-location ()
2089 "Temporarily display a buffer showing the selected candidate in context."
2090 (interactive)
2091 (let (other-window-scroll-buffer)
2092 (company--electric-do
2093 (let* ((selected (nth company-selection company-candidates))
2094 (location (company-call-backend 'location selected))
2095 (pos (or (cdr location) (error "No location available")))
2096 (buffer (or (and (bufferp (car location)) (car location))
2097 (find-file-noselect (car location) t))))
2098 (setq other-window-scroll-buffer (get-buffer buffer))
2099 (with-selected-window (display-buffer buffer t)
2100 (save-restriction
2101 (widen)
2102 (if (bufferp (car location))
2103 (goto-char pos)
2104 (goto-char (point-min))
2105 (forward-line (1- pos))))
2106 (set-window-start nil (point)))))))
2107 (put 'company-show-location 'company-keep t)
2108
2109 ;;; package functions ;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;
2110
2111 (defvar-local company-callback nil)
2112
2113 (defun company-remove-callback (&optional ignored)
2114 (remove-hook 'company-completion-finished-hook company-callback t)
2115 (remove-hook 'company-completion-cancelled-hook 'company-remove-callback t)
2116 (remove-hook 'company-completion-finished-hook 'company-remove-callback t))
2117
2118 (defun company-begin-backend (backend &optional callback)
2119 "Start a completion at point using BACKEND."
2120 (interactive (let ((val (completing-read "Company back-end: "
2121 obarray
2122 'functionp nil "company-")))
2123 (when val
2124 (list (intern val)))))
2125 (when (setq company-callback callback)
2126 (add-hook 'company-completion-finished-hook company-callback nil t))
2127 (add-hook 'company-completion-cancelled-hook 'company-remove-callback nil t)
2128 (add-hook 'company-completion-finished-hook 'company-remove-callback nil t)
2129 (setq company-backend backend)
2130 ;; Return non-nil if active.
2131 (or (company-manual-begin)
2132 (error "Cannot complete at point")))
2133
2134 (defun company-begin-with (candidates
2135 &optional prefix-length require-match callback)
2136 "Start a completion at point.
2137 CANDIDATES is the list of candidates to use and PREFIX-LENGTH is the length
2138 of the prefix that already is in the buffer before point.
2139 It defaults to 0.
2140
2141 CALLBACK is a function called with the selected result if the user
2142 successfully completes the input.
2143
2144 Example: \(company-begin-with '\(\"foo\" \"foobar\" \"foobarbaz\"\)\)"
2145 (let ((begin-marker (copy-marker (point) t)))
2146 (company-begin-backend
2147 (lambda (command &optional arg &rest ignored)
2148 (pcase command
2149 (`prefix
2150 (when (equal (point) (marker-position begin-marker))
2151 (buffer-substring (- (point) (or prefix-length 0)) (point))))
2152 (`candidates
2153 (all-completions arg candidates))
2154 (`require-match
2155 require-match)))
2156 callback)))
2157
2158 (defun company-version (&optional show-version)
2159 "Get the Company version as string.
2160
2161 If SHOW-VERSION is non-nil, show the version in the echo area."
2162 (interactive (list t))
2163 (with-temp-buffer
2164 (require 'find-func)
2165 (insert-file-contents (find-library-name "company"))
2166 (require 'lisp-mnt)
2167 (if show-version
2168 (message "Company version: %s" (lm-version))
2169 (lm-version))))
2170
2171 (defun company-diag ()
2172 "Pop a buffer with information about completions at point."
2173 (interactive)
2174 (let* ((bb company-backends)
2175 backend
2176 (prefix (cl-loop for b in bb
2177 thereis (let ((company-backend b))
2178 (setq backend b)
2179 (company-call-backend 'prefix))))
2180 cc annotations)
2181 (when (stringp prefix)
2182 (let ((company-backend backend))
2183 (setq cc (company-call-backend 'candidates prefix)
2184 annotations
2185 (mapcar
2186 (lambda (c) (cons c (company-call-backend 'annotation c)))
2187 cc))))
2188 (pop-to-buffer (get-buffer-create "*company-diag*"))
2189 (setq buffer-read-only nil)
2190 (erase-buffer)
2191 (insert (format "Emacs %s (%s) of %s on %s"
2192 emacs-version system-configuration
2193 (format-time-string "%Y-%m-%d" emacs-build-time)
2194 emacs-build-system))
2195 (insert "\nCompany " (company-version) "\n\n")
2196 (insert "company-backends: " (pp-to-string bb))
2197 (insert "\n")
2198 (insert "Used backend: " (pp-to-string backend))
2199 (insert "\n")
2200 (insert "Prefix: " (pp-to-string prefix))
2201 (insert "\n")
2202 (insert (message "Completions:"))
2203 (unless cc (insert " none"))
2204 (save-excursion
2205 (dolist (c annotations)
2206 (insert "\n " (prin1-to-string (car c)))
2207 (when (cdr c)
2208 (insert " " (prin1-to-string (cdr c))))))
2209 (special-mode)))
2210
2211 ;;; pseudo-tooltip ;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;
2212
2213 (defvar-local company-pseudo-tooltip-overlay nil)
2214
2215 (defvar-local company-tooltip-offset 0)
2216
2217 (defun company-tooltip--lines-update-offset (selection num-lines limit)
2218 (cl-decf limit 2)
2219 (setq company-tooltip-offset
2220 (max (min selection company-tooltip-offset)
2221 (- selection -1 limit)))
2222
2223 (when (<= company-tooltip-offset 1)
2224 (cl-incf limit)
2225 (setq company-tooltip-offset 0))
2226
2227 (when (>= company-tooltip-offset (- num-lines limit 1))
2228 (cl-incf limit)
2229 (when (= selection (1- num-lines))
2230 (cl-decf company-tooltip-offset)
2231 (when (<= company-tooltip-offset 1)
2232 (setq company-tooltip-offset 0)
2233 (cl-incf limit))))
2234
2235 limit)
2236
2237 (defun company-tooltip--simple-update-offset (selection _num-lines limit)
2238 (setq company-tooltip-offset
2239 (if (< selection company-tooltip-offset)
2240 selection
2241 (max company-tooltip-offset
2242 (- selection limit -1)))))
2243
2244 ;;; propertize
2245
2246 (defsubst company-round-tab (arg)
2247 (* (/ (+ arg tab-width) tab-width) tab-width))
2248
2249 (defun company-plainify (str)
2250 (let ((prefix (get-text-property 0 'line-prefix str)))
2251 (when prefix ; Keep the original value unmodified, for no special reason.
2252 (setq str (concat prefix str))
2253 (remove-text-properties 0 (length str) '(line-prefix) str)))
2254 (let* ((pieces (split-string str "\t"))
2255 (copy pieces))
2256 (while (cdr copy)
2257 (setcar copy (company-safe-substring
2258 (car copy) 0 (company-round-tab (string-width (car copy)))))
2259 (pop copy))
2260 (apply 'concat pieces)))
2261
2262 (defun company-fill-propertize (value annotation width selected left right)
2263 (let* ((margin (length left))
2264 (common (or (company-call-backend 'match value)
2265 (if company-common
2266 (string-width company-common)
2267 0)))
2268 (ann-ralign company-tooltip-align-annotations)
2269 (ann-truncate (< width
2270 (+ (length value) (length annotation)
2271 (if ann-ralign 1 0))))
2272 (ann-start (+ margin
2273 (if ann-ralign
2274 (if ann-truncate
2275 (1+ (length value))
2276 (- width (length annotation)))
2277 (length value))))
2278 (ann-end (min (+ ann-start (length annotation)) (+ margin width)))
2279 (line (concat left
2280 (if (or ann-truncate (not ann-ralign))
2281 (company-safe-substring
2282 (concat value
2283 (when (and annotation ann-ralign) " ")
2284 annotation)
2285 0 width)
2286 (concat
2287 (company-safe-substring value 0
2288 (- width (length annotation)))
2289 annotation))
2290 right)))
2291 (setq common (+ (min common width) margin))
2292 (setq width (+ width margin (length right)))
2293
2294 (add-text-properties 0 width '(face company-tooltip
2295 mouse-face company-tooltip-mouse)
2296 line)
2297 (add-text-properties margin common
2298 '(face company-tooltip-common
2299 mouse-face company-tooltip-mouse)
2300 line)
2301 (when (< ann-start ann-end)
2302 (add-text-properties ann-start ann-end
2303 '(face company-tooltip-annotation
2304 mouse-face company-tooltip-mouse)
2305 line))
2306 (when selected
2307 (if (and (not (string= company-search-string ""))
2308 (string-match (regexp-quote company-search-string) value
2309 (length company-prefix)))
2310 (let ((beg (+ margin (match-beginning 0)))
2311 (end (+ margin (match-end 0)))
2312 (width (- width (length right))))
2313 (when (< beg width)
2314 (add-text-properties beg (min end width)
2315 '(face company-tooltip-search)
2316 line)))
2317 (add-text-properties 0 width '(face company-tooltip-selection
2318 mouse-face company-tooltip-selection)
2319 line)
2320 (add-text-properties margin common
2321 '(face company-tooltip-common-selection
2322 mouse-face company-tooltip-selection)
2323 line)))
2324 line))
2325
2326 (defun company--clean-string (str)
2327 (replace-regexp-in-string
2328 "\\([^[:graph:] ]\\)\\|\\(\ufeff\\)\\|[[:multibyte:]]"
2329 (lambda (match)
2330 (cond
2331 ((match-beginning 1)
2332 ;; FIXME: Better char for 'non-printable'?
2333 ;; We shouldn't get any of these, but sometimes we might.
2334 "\u2017")
2335 ((match-beginning 2)
2336 ;; Zero-width non-breakable space.
2337 "")
2338 ((> (string-width match) 1)
2339 (concat
2340 (make-string (1- (string-width match)) ?\ufeff)
2341 match))
2342 (t match)))
2343 str))
2344
2345 ;;; replace
2346
2347 (defun company-buffer-lines (beg end)
2348 (goto-char beg)
2349 (let (lines lines-moved)
2350 (while (and (not (eobp)) ; http://debbugs.gnu.org/19553
2351 (> (setq lines-moved (vertical-motion 1)) 0)
2352 (<= (point) end))
2353 (let ((bound (min end (point))))
2354 ;; A visual line can contain several physical lines (e.g. with outline's
2355 ;; folding overlay). Take only the first one.
2356 (push (buffer-substring beg
2357 (save-excursion
2358 (goto-char beg)
2359 (re-search-forward "$" bound 'move)
2360 (point)))
2361 lines))
2362 ;; One physical line can be displayed as several visual ones as well:
2363 ;; add empty strings to the list, to even the count.
2364 (dotimes (_ (1- lines-moved))
2365 (push "" lines))
2366 (setq beg (point)))
2367 (unless (eq beg end)
2368 (push (buffer-substring beg end) lines))
2369 (nreverse lines)))
2370
2371 (defun company-modify-line (old new offset)
2372 (concat (company-safe-substring old 0 offset)
2373 new
2374 (company-safe-substring old (+ offset (length new)))))
2375
2376 (defsubst company--length-limit (lst limit)
2377 (if (nthcdr limit lst)
2378 limit
2379 (length lst)))
2380
2381 (defsubst company--window-height ()
2382 (if (fboundp 'window-screen-lines)
2383 (floor (window-screen-lines))
2384 (window-body-height)))
2385
2386 (defun company--window-width ()
2387 (let ((ww (window-body-width)))
2388 ;; Account for the line continuation column.
2389 (when (zerop (cadr (window-fringes)))
2390 (cl-decf ww))
2391 (unless (or (display-graphic-p)
2392 (version< "24.3.1" emacs-version))
2393 ;; Emacs 24.3 and earlier included margins
2394 ;; in window-width when in TTY.
2395 (cl-decf ww
2396 (let ((margins (window-margins)))
2397 (+ (or (car margins) 0)
2398 (or (cdr margins) 0)))))
2399 (when (and word-wrap
2400 (version< emacs-version "24.4.51.5"))
2401 ;; http://debbugs.gnu.org/19300
2402 (cl-decf ww))
2403 ;; whitespace-mode with newline-mark
2404 (when (and buffer-display-table
2405 (aref buffer-display-table ?\n))
2406 (cl-decf ww (1- (length (aref buffer-display-table ?\n)))))
2407 ww))
2408
2409 (defun company--replacement-string (lines old column nl &optional align-top)
2410 (cl-decf column company-tooltip-margin)
2411
2412 (when (and align-top company-tooltip-flip-when-above)
2413 (setq lines (reverse lines)))
2414
2415 (let ((width (length (car lines)))
2416 (remaining-cols (- (+ (company--window-width) (window-hscroll))
2417 column)))
2418 (when (> width remaining-cols)
2419 (cl-decf column (- width remaining-cols))))
2420
2421 (let ((offset (and (< column 0) (- column)))
2422 new)
2423 (when offset
2424 (setq column 0))
2425 (when align-top
2426 ;; untouched lines first
2427 (dotimes (_ (- (length old) (length lines)))
2428 (push (pop old) new)))
2429 ;; length into old lines.
2430 (while old
2431 (push (company-modify-line (pop old)
2432 (company--offset-line (pop lines) offset)
2433 column)
2434 new))
2435 ;; Append whole new lines.
2436 (while lines
2437 (push (concat (company-space-string column)
2438 (company--offset-line (pop lines) offset))
2439 new))
2440
2441 (let ((str (concat (when nl " ")
2442 "\n"
2443 (mapconcat 'identity (nreverse new) "\n")
2444 "\n")))
2445 (font-lock-append-text-property 0 (length str) 'face 'default str)
2446 (when nl (put-text-property 0 1 'cursor t str))
2447 str)))
2448
2449 (defun company--offset-line (line offset)
2450 (if (and offset line)
2451 (substring line offset)
2452 line))
2453
2454 (defun company--create-lines (selection limit)
2455 (let ((len company-candidates-length)
2456 (window-width (company--window-width))
2457 lines
2458 width
2459 lines-copy
2460 items
2461 previous
2462 remainder
2463 scrollbar-bounds)
2464
2465 ;; Maybe clear old offset.
2466 (when (< len (+ company-tooltip-offset limit))
2467 (setq company-tooltip-offset 0))
2468
2469 ;; Scroll to offset.
2470 (if (eq company-tooltip-offset-display 'lines)
2471 (setq limit (company-tooltip--lines-update-offset selection len limit))
2472 (company-tooltip--simple-update-offset selection len limit))
2473
2474 (cond
2475 ((eq company-tooltip-offset-display 'scrollbar)
2476 (setq scrollbar-bounds (company--scrollbar-bounds company-tooltip-offset
2477 limit len)))
2478 ((eq company-tooltip-offset-display 'lines)
2479 (when (> company-tooltip-offset 0)
2480 (setq previous (format "...(%d)" company-tooltip-offset)))
2481 (setq remainder (- len limit company-tooltip-offset)
2482 remainder (when (> remainder 0)
2483 (setq remainder (format "...(%d)" remainder))))))
2484
2485 (cl-decf selection company-tooltip-offset)
2486 (setq width (max (length previous) (length remainder))
2487 lines (nthcdr company-tooltip-offset company-candidates)
2488 len (min limit len)
2489 lines-copy lines)
2490
2491 (cl-decf window-width (* 2 company-tooltip-margin))
2492 (when scrollbar-bounds (cl-decf window-width))
2493
2494 (dotimes (_ len)
2495 (let* ((value (pop lines-copy))
2496 (annotation (company-call-backend 'annotation value)))
2497 (setq value (company--clean-string (company-reformat value)))
2498 (when annotation
2499 (when company-tooltip-align-annotations
2500 ;; `lisp-completion-at-point' adds a space.
2501 (setq annotation (comment-string-strip annotation t nil)))
2502 (setq annotation (company--clean-string annotation)))
2503 (push (cons value annotation) items)
2504 (setq width (max (+ (length value)
2505 (if (and annotation company-tooltip-align-annotations)
2506 (1+ (length annotation))
2507 (length annotation)))
2508 width))))
2509
2510 (setq width (min window-width
2511 (max company-tooltip-minimum-width
2512 (if company-show-numbers
2513 (+ 2 width)
2514 width))))
2515
2516 (let ((items (nreverse items))
2517 (numbered (if company-show-numbers 0 99999))
2518 new)
2519 (when previous
2520 (push (company--scrollpos-line previous width) new))
2521
2522 (dotimes (i len)
2523 (let* ((item (pop items))
2524 (str (car item))
2525 (annotation (cdr item))
2526 (right (company-space-string company-tooltip-margin))
2527 (width width))
2528 (when (< numbered 10)
2529 (cl-decf width 2)
2530 (cl-incf numbered)
2531 (setq right (concat (format " %d" (mod numbered 10)) right)))
2532 (push (concat
2533 (company-fill-propertize str annotation
2534 width (equal i selection)
2535 (company-space-string
2536 company-tooltip-margin)
2537 right)
2538 (when scrollbar-bounds
2539 (company--scrollbar i scrollbar-bounds)))
2540 new)))
2541
2542 (when remainder
2543 (push (company--scrollpos-line remainder width) new))
2544
2545 (nreverse new))))
2546
2547 (defun company--scrollbar-bounds (offset limit length)
2548 (when (> length limit)
2549 (let* ((size (ceiling (* limit (float limit)) length))
2550 (lower (floor (* limit (float offset)) length))
2551 (upper (+ lower size -1)))
2552 (cons lower upper))))
2553
2554 (defun company--scrollbar (i bounds)
2555 (propertize " " 'face
2556 (if (and (>= i (car bounds)) (<= i (cdr bounds)))
2557 'company-scrollbar-fg
2558 'company-scrollbar-bg)))
2559
2560 (defun company--scrollpos-line (text width)
2561 (propertize (concat (company-space-string company-tooltip-margin)
2562 (company-safe-substring text 0 width)
2563 (company-space-string company-tooltip-margin))
2564 'face 'company-tooltip))
2565
2566 ;; show
2567
2568 (defun company--pseudo-tooltip-height ()
2569 "Calculate the appropriate tooltip height.
2570 Returns a negative number if the tooltip should be displayed above point."
2571 (let* ((lines (company--row))
2572 (below (- (company--window-height) 1 lines)))
2573 (if (and (< below (min company-tooltip-minimum company-candidates-length))
2574 (> lines below))
2575 (- (max 3 (min company-tooltip-limit lines)))
2576 (max 3 (min company-tooltip-limit below)))))
2577
2578 (defun company-pseudo-tooltip-show (row column selection)
2579 (company-pseudo-tooltip-hide)
2580 (save-excursion
2581
2582 (let* ((height (company--pseudo-tooltip-height))
2583 above)
2584
2585 (when (< height 0)
2586 (setq row (+ row height -1)
2587 above t))
2588
2589 (let* ((nl (< (move-to-window-line row) row))
2590 (beg (point))
2591 (end (save-excursion
2592 (move-to-window-line (+ row (abs height)))
2593 (point)))
2594 (ov (make-overlay (if nl beg (1- beg)) end nil t))
2595 (args (list (mapcar 'company-plainify
2596 (company-buffer-lines beg end))
2597 column nl above)))
2598
2599 (setq company-pseudo-tooltip-overlay ov)
2600 (overlay-put ov 'company-replacement-args args)
2601
2602 (let ((lines (company--create-lines selection (abs height))))
2603 (overlay-put ov 'company-display
2604 (apply 'company--replacement-string lines args))
2605 (overlay-put ov 'company-width (string-width (car lines))))
2606
2607 (overlay-put ov 'company-column column)
2608 (overlay-put ov 'company-height height)))))
2609
2610 (defun company-pseudo-tooltip-show-at-point (pos column-offset)
2611 (let* ((col-row (company--col-row pos))
2612 (col (- (car col-row) column-offset)))
2613 (when (< col 0) (setq col 0))
2614 (company-pseudo-tooltip-show (1+ (cdr col-row)) col company-selection)))
2615
2616 (defun company-pseudo-tooltip-edit (selection)
2617 (let* ((height (overlay-get company-pseudo-tooltip-overlay 'company-height))
2618 (lines (company--create-lines selection (abs height))))
2619 (overlay-put company-pseudo-tooltip-overlay 'company-width
2620 (string-width (car lines)))
2621 (overlay-put company-pseudo-tooltip-overlay 'company-display
2622 (apply 'company--replacement-string
2623 lines
2624 (overlay-get company-pseudo-tooltip-overlay
2625 'company-replacement-args)))))
2626
2627 (defun company-pseudo-tooltip-hide ()
2628 (when company-pseudo-tooltip-overlay
2629 (delete-overlay company-pseudo-tooltip-overlay)
2630 (setq company-pseudo-tooltip-overlay nil)))
2631
2632 (defun company-pseudo-tooltip-hide-temporarily ()
2633 (when (overlayp company-pseudo-tooltip-overlay)
2634 (overlay-put company-pseudo-tooltip-overlay 'invisible nil)
2635 (overlay-put company-pseudo-tooltip-overlay 'after-string nil)))
2636
2637 (defun company-pseudo-tooltip-unhide ()
2638 (when company-pseudo-tooltip-overlay
2639 (let* ((ov company-pseudo-tooltip-overlay)
2640 (disp (overlay-get ov 'company-display)))
2641 ;; Beat outline's folding overlays, at least.
2642 (overlay-put ov 'priority 1)
2643 ;; `display' could be better (http://debbugs.gnu.org/18285), but it
2644 ;; doesn't work when the overlay is empty, which is what happens at eob.
2645 ;; It also seems to interact badly with `cursor'.
2646 ;; We deal with priorities by having the overlay start before the newline.
2647 (overlay-put ov 'after-string disp)
2648 (overlay-put ov 'invisible t)
2649 (overlay-put ov 'window (selected-window)))))
2650
2651 (defun company-pseudo-tooltip-guard ()
2652 (cons
2653 (save-excursion (beginning-of-visual-line))
2654 (let ((ov company-pseudo-tooltip-overlay)
2655 (overhang (save-excursion (end-of-visual-line)
2656 (- (line-end-position) (point)))))
2657 (when (>= (overlay-get ov 'company-height) 0)
2658 (cons
2659 (buffer-substring-no-properties (point) (overlay-start ov))
2660 (when (>= overhang 0) overhang))))))
2661
2662 (defun company-pseudo-tooltip-frontend (command)
2663 "`company-mode' front-end similar to a tooltip but based on overlays."
2664 (cl-case command
2665 (pre-command (company-pseudo-tooltip-hide-temporarily))
2666 (post-command
2667 (unless (when (overlayp company-pseudo-tooltip-overlay)
2668 (let* ((ov company-pseudo-tooltip-overlay)
2669 (old-height (overlay-get ov 'company-height))
2670 (new-height (company--pseudo-tooltip-height)))
2671 (and
2672 (>= (* old-height new-height) 0)
2673 (>= (abs old-height) (abs new-height))
2674 (equal (company-pseudo-tooltip-guard)
2675 (overlay-get ov 'company-guard)))))
2676 ;; Redraw needed.
2677 (company-pseudo-tooltip-show-at-point (point) (length company-prefix))
2678 (overlay-put company-pseudo-tooltip-overlay
2679 'company-guard (company-pseudo-tooltip-guard)))
2680 (company-pseudo-tooltip-unhide))
2681 (hide (company-pseudo-tooltip-hide)
2682 (setq company-tooltip-offset 0))
2683 (update (when (overlayp company-pseudo-tooltip-overlay)
2684 (company-pseudo-tooltip-edit company-selection)))))
2685
2686 (defun company-pseudo-tooltip-unless-just-one-frontend (command)
2687 "`company-pseudo-tooltip-frontend', but not shown for single candidates."
2688 (unless (and (eq command 'post-command)
2689 (company--show-inline-p))
2690 (company-pseudo-tooltip-frontend command)))
2691
2692 ;;; overlay ;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;
2693
2694 (defvar-local company-preview-overlay nil)
2695
2696 (defun company-preview-show-at-point (pos)
2697 (company-preview-hide)
2698
2699 (let ((completion (nth company-selection company-candidates)))
2700 (setq completion (propertize completion 'face 'company-preview))
2701 (add-text-properties 0 (length company-common)
2702 '(face company-preview-common) completion)
2703
2704 ;; Add search string
2705 (and company-search-string
2706 (string-match (regexp-quote company-search-string) completion)
2707 (add-text-properties (match-beginning 0)
2708 (match-end 0)
2709 '(face company-preview-search)
2710 completion))
2711
2712 (setq completion (company-strip-prefix completion))
2713
2714 (and (equal pos (point))
2715 (not (equal completion ""))
2716 (add-text-properties 0 1 '(cursor 1) completion))
2717
2718 (let* ((beg pos)
2719 (pto company-pseudo-tooltip-overlay)
2720 (ptf-workaround (and
2721 pto
2722 (char-before pos)
2723 (eq pos (overlay-start pto)))))
2724 ;; Try to accomodate for the pseudo-tooltip overlay,
2725 ;; which may start at the same position if it's at eol.
2726 (when ptf-workaround
2727 (cl-decf beg)
2728 (setq completion (concat (buffer-substring beg pos) completion)))
2729
2730 (setq company-preview-overlay (make-overlay beg pos))
2731
2732 (let ((ov company-preview-overlay))
2733 (overlay-put ov (if ptf-workaround 'display 'after-string)
2734 completion)
2735 (overlay-put ov 'window (selected-window))))))
2736
2737 (defun company-preview-hide ()
2738 (when company-preview-overlay
2739 (delete-overlay company-preview-overlay)
2740 (setq company-preview-overlay nil)))
2741
2742 (defun company-preview-frontend (command)
2743 "`company-mode' front-end showing the selection as if it had been inserted."
2744 (pcase command
2745 (`pre-command (company-preview-hide))
2746 (`post-command (company-preview-show-at-point (point)))
2747 (`hide (company-preview-hide))))
2748
2749 (defun company-preview-if-just-one-frontend (command)
2750 "`company-preview-frontend', but only shown for single candidates."
2751 (when (or (not (eq command 'post-command))
2752 (company--show-inline-p))
2753 (company-preview-frontend command)))
2754
2755 (defun company--show-inline-p ()
2756 (and (not (cdr company-candidates))
2757 company-common
2758 (or (eq (company-call-backend 'ignore-case) 'keep-prefix)
2759 (string-prefix-p company-prefix company-common))))
2760
2761 ;;; echo ;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;
2762
2763 (defvar-local company-echo-last-msg nil)
2764
2765 (defvar company-echo-timer nil)
2766
2767 (defvar company-echo-delay .01)
2768
2769 (defun company-echo-show (&optional getter)
2770 (when getter
2771 (setq company-echo-last-msg (funcall getter)))
2772 (let ((message-log-max nil))
2773 (if company-echo-last-msg
2774 (message "%s" company-echo-last-msg)
2775 (message ""))))
2776
2777 (defun company-echo-show-soon (&optional getter)
2778 (company-echo-cancel)
2779 (setq company-echo-timer (run-with-timer 0 nil 'company-echo-show getter)))
2780
2781 (defun company-echo-cancel (&optional unset)
2782 (when company-echo-timer
2783 (cancel-timer company-echo-timer))
2784 (when unset
2785 (setq company-echo-timer nil)))
2786
2787 (defun company-echo-show-when-idle (&optional getter)
2788 (company-echo-cancel)
2789 (setq company-echo-timer
2790 (run-with-idle-timer company-echo-delay nil 'company-echo-show getter)))
2791
2792 (defun company-echo-format ()
2793
2794 (let ((limit (window-body-width (minibuffer-window)))
2795 (len -1)
2796 ;; Roll to selection.
2797 (candidates (nthcdr company-selection company-candidates))
2798 (i (if company-show-numbers company-selection 99999))
2799 comp msg)
2800
2801 (while candidates
2802 (setq comp (company-reformat (pop candidates))
2803 len (+ len 1 (length comp)))
2804 (if (< i 10)
2805 ;; Add number.
2806 (progn
2807 (setq comp (propertize (format "%d: %s" i comp)
2808 'face 'company-echo))
2809 (cl-incf len 3)
2810 (cl-incf i)
2811 (add-text-properties 3 (+ 3 (length company-common))
2812 '(face company-echo-common) comp))
2813 (setq comp (propertize comp 'face 'company-echo))
2814 (add-text-properties 0 (length company-common)
2815 '(face company-echo-common) comp))
2816 (if (>= len limit)
2817 (setq candidates nil)
2818 (push comp msg)))
2819
2820 (mapconcat 'identity (nreverse msg) " ")))
2821
2822 (defun company-echo-strip-common-format ()
2823
2824 (let ((limit (window-body-width (minibuffer-window)))
2825 (len (+ (length company-prefix) 2))
2826 ;; Roll to selection.
2827 (candidates (nthcdr company-selection company-candidates))
2828 (i (if company-show-numbers company-selection 99999))
2829 msg comp)
2830
2831 (while candidates
2832 (setq comp (company-strip-prefix (pop candidates))
2833 len (+ len 2 (length comp)))
2834 (when (< i 10)
2835 ;; Add number.
2836 (setq comp (format "%s (%d)" comp i))
2837 (cl-incf len 4)
2838 (cl-incf i))
2839 (if (>= len limit)
2840 (setq candidates nil)
2841 (push (propertize comp 'face 'company-echo) msg)))
2842
2843 (concat (propertize company-prefix 'face 'company-echo-common) "{"
2844 (mapconcat 'identity (nreverse msg) ", ")
2845 "}")))
2846
2847 (defun company-echo-hide ()
2848 (unless (equal company-echo-last-msg "")
2849 (setq company-echo-last-msg "")
2850 (company-echo-show)))
2851
2852 (defun company-echo-frontend (command)
2853 "`company-mode' front-end showing the candidates in the echo area."
2854 (pcase command
2855 (`post-command (company-echo-show-soon 'company-echo-format))
2856 (`hide (company-echo-hide))))
2857
2858 (defun company-echo-strip-common-frontend (command)
2859 "`company-mode' front-end showing the candidates in the echo area."
2860 (pcase command
2861 (`post-command (company-echo-show-soon 'company-echo-strip-common-format))
2862 (`hide (company-echo-hide))))
2863
2864 (defun company-echo-metadata-frontend (command)
2865 "`company-mode' front-end showing the documentation in the echo area."
2866 (pcase command
2867 (`post-command (company-echo-show-when-idle 'company-fetch-metadata))
2868 (`hide (company-echo-hide))))
2869
2870 (provide 'company)
2871 ;;; company.el ends here