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