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