]> code.delx.au - gnu-emacs-elpa/blob - company.el
company-search-candidates: Mention company-search-regexp-function
[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 Customize `company-search-regexp-function' to change how the input
1843 is interpreted when searching.
1844
1845 The command `company-search-toggle-filtering' (\\[company-search-toggle-filtering])
1846 uses the search string to filter the completion candidates."
1847 (interactive)
1848 (company-search-mode 1))
1849
1850 (defvar company-filter-map
1851 (let ((keymap (make-keymap)))
1852 (define-key keymap [remap company-search-printing-char]
1853 'company-filter-printing-char)
1854 (set-keymap-parent keymap company-search-map)
1855 keymap)
1856 "Keymap used for incrementally searching the completion candidates.")
1857
1858 (defun company-filter-candidates ()
1859 "Start filtering the completion candidates incrementally.
1860 This works the same way as `company-search-candidates' immediately
1861 followed by `company-search-toggle-filtering'."
1862 (interactive)
1863 (company-search-mode 1)
1864 (setq company-search-filtering t))
1865
1866 ;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;
1867
1868 (defun company-select-next (&optional arg)
1869 "Select the next candidate in the list.
1870
1871 With ARG, move by that many elements."
1872 (interactive "p")
1873 (when (company-manual-begin)
1874 (company-set-selection (+ (or arg 1) company-selection))))
1875
1876 (defun company-select-previous (&optional arg)
1877 "Select the previous candidate in the list.
1878
1879 With ARG, move by that many elements."
1880 (interactive "p")
1881 (company-select-next (if arg (- arg) -1)))
1882
1883 (defun company-select-next-or-abort (&optional arg)
1884 "Select the next candidate if more than one, else abort
1885 and invoke the normal binding.
1886
1887 With ARG, move by that many elements."
1888 (interactive "p")
1889 (if (> company-candidates-length 1)
1890 (company-select-next arg)
1891 (company-abort)
1892 (company--unread-last-input)))
1893
1894 (defun company-select-previous-or-abort (&optional arg)
1895 "Select the previous candidate if more than one, else abort
1896 and invoke the normal binding.
1897
1898 With ARG, move by that many elements."
1899 (interactive "p")
1900 (if (> company-candidates-length 1)
1901 (company-select-previous arg)
1902 (company-abort)
1903 (company--unread-last-input)))
1904
1905 (defun company-next-page ()
1906 "Select the candidate one page further."
1907 (interactive)
1908 (when (company-manual-begin)
1909 (company-set-selection (+ company-selection
1910 company-tooltip-limit))))
1911
1912 (defun company-previous-page ()
1913 "Select the candidate one page earlier."
1914 (interactive)
1915 (when (company-manual-begin)
1916 (company-set-selection (- company-selection
1917 company-tooltip-limit))))
1918
1919 (defvar company-pseudo-tooltip-overlay)
1920
1921 (defvar company-tooltip-offset)
1922
1923 (defun company--inside-tooltip-p (event-col-row row height)
1924 (let* ((ovl company-pseudo-tooltip-overlay)
1925 (column (overlay-get ovl 'company-column))
1926 (width (overlay-get ovl 'company-width))
1927 (evt-col (car event-col-row))
1928 (evt-row (cdr event-col-row)))
1929 (and (>= evt-col column)
1930 (< evt-col (+ column width))
1931 (if (> height 0)
1932 (and (> evt-row row)
1933 (<= evt-row (+ row height) ))
1934 (and (< evt-row row)
1935 (>= evt-row (+ row height)))))))
1936
1937 (defun company--event-col-row (event)
1938 (company--posn-col-row (event-start event)))
1939
1940 (defun company-select-mouse (event)
1941 "Select the candidate picked by the mouse."
1942 (interactive "e")
1943 (let ((event-col-row (company--event-col-row event))
1944 (ovl-row (company--row))
1945 (ovl-height (and company-pseudo-tooltip-overlay
1946 (min (overlay-get company-pseudo-tooltip-overlay
1947 'company-height)
1948 company-candidates-length))))
1949 (if (and ovl-height
1950 (company--inside-tooltip-p event-col-row ovl-row ovl-height))
1951 (progn
1952 (company-set-selection (+ (cdr event-col-row)
1953 (1- company-tooltip-offset)
1954 (if (and (eq company-tooltip-offset-display 'lines)
1955 (not (zerop company-tooltip-offset)))
1956 -1 0)
1957 (- ovl-row)
1958 (if (< ovl-height 0)
1959 (- 1 ovl-height)
1960 0)))
1961 t)
1962 (company-abort)
1963 (company--unread-last-input)
1964 nil)))
1965
1966 (defun company-complete-mouse (event)
1967 "Insert the candidate picked by the mouse."
1968 (interactive "e")
1969 (when (company-select-mouse event)
1970 (company-complete-selection)))
1971
1972 (defun company-complete-selection ()
1973 "Insert the selected candidate."
1974 (interactive)
1975 (when (company-manual-begin)
1976 (let ((result (nth company-selection company-candidates)))
1977 (company-finish result))))
1978
1979 (defun company-complete-common ()
1980 "Insert the common part of all candidates."
1981 (interactive)
1982 (when (company-manual-begin)
1983 (if (and (not (cdr company-candidates))
1984 (equal company-common (car company-candidates)))
1985 (company-complete-selection)
1986 (company--insert-candidate company-common))))
1987
1988 (defun company-complete-common-or-cycle (&optional arg)
1989 "Insert the common part of all candidates, or select the next one.
1990
1991 With ARG, move by that many elements."
1992 (interactive "p")
1993 (when (company-manual-begin)
1994 (let ((tick (buffer-chars-modified-tick)))
1995 (call-interactively 'company-complete-common)
1996 (when (eq tick (buffer-chars-modified-tick))
1997 (let ((company-selection-wrap-around t)
1998 (current-prefix-arg arg))
1999 (call-interactively 'company-select-next))))))
2000
2001 (defun company-indent-or-complete-common ()
2002 "Indent the current line or region, or complete the common part."
2003 (interactive)
2004 (cond
2005 ((use-region-p)
2006 (indent-region (region-beginning) (region-end)))
2007 ((let ((old-point (point))
2008 (old-tick (buffer-chars-modified-tick))
2009 (tab-always-indent t))
2010 (call-interactively #'indent-for-tab-command)
2011 (when (and (eq old-point (point))
2012 (eq old-tick (buffer-chars-modified-tick)))
2013 (company-complete-common))))))
2014
2015 (defun company-complete ()
2016 "Insert the common part of all candidates or the current selection.
2017 The first time this is called, the common part is inserted, the second
2018 time, or when the selection has been changed, the selected candidate is
2019 inserted."
2020 (interactive)
2021 (when (company-manual-begin)
2022 (if (or company-selection-changed
2023 (eq last-command 'company-complete-common))
2024 (call-interactively 'company-complete-selection)
2025 (call-interactively 'company-complete-common)
2026 (setq this-command 'company-complete-common))))
2027
2028 (defun company-complete-number (n)
2029 "Insert the Nth candidate visible in the tooltip.
2030 To show the number next to the candidates in some backends, enable
2031 `company-show-numbers'. When called interactively, uses the last typed
2032 character, stripping the modifiers. That character must be a digit."
2033 (interactive
2034 (list (let* ((type (event-basic-type last-command-event))
2035 (char (if (characterp type)
2036 ;; Number on the main row.
2037 type
2038 ;; Keypad number, if bound directly.
2039 (car (last (string-to-list (symbol-name type))))))
2040 (n (- char ?0)))
2041 (if (zerop n) 10 n))))
2042 (when (company-manual-begin)
2043 (and (or (< n 1) (> n (- company-candidates-length
2044 company-tooltip-offset)))
2045 (error "No candidate number %d" n))
2046 (cl-decf n)
2047 (company-finish (nth (+ n company-tooltip-offset)
2048 company-candidates))))
2049
2050 ;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;
2051
2052 (defconst company-space-strings-limit 100)
2053
2054 (defconst company-space-strings
2055 (let (lst)
2056 (dotimes (i company-space-strings-limit)
2057 (push (make-string (- company-space-strings-limit 1 i) ?\ ) lst))
2058 (apply 'vector lst)))
2059
2060 (defun company-space-string (len)
2061 (if (< len company-space-strings-limit)
2062 (aref company-space-strings len)
2063 (make-string len ?\ )))
2064
2065 (defun company-safe-substring (str from &optional to)
2066 (if (> from (string-width str))
2067 ""
2068 (with-temp-buffer
2069 (insert str)
2070 (move-to-column from)
2071 (let ((beg (point)))
2072 (if to
2073 (progn
2074 (move-to-column to)
2075 (concat (buffer-substring beg (point))
2076 (let ((padding (- to (current-column))))
2077 (when (> padding 0)
2078 (company-space-string padding)))))
2079 (buffer-substring beg (point-max)))))))
2080
2081 ;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;
2082
2083 (defvar-local company-last-metadata nil)
2084
2085 (defun company-fetch-metadata ()
2086 (let ((selected (nth company-selection company-candidates)))
2087 (unless (eq selected (car company-last-metadata))
2088 (setq company-last-metadata
2089 (cons selected (company-call-backend 'meta selected))))
2090 (cdr company-last-metadata)))
2091
2092 (defun company-doc-buffer (&optional string)
2093 (with-current-buffer (get-buffer-create "*company-documentation*")
2094 (erase-buffer)
2095 (when string
2096 (save-excursion
2097 (insert string)))
2098 (current-buffer)))
2099
2100 (defvar company--electric-commands
2101 '(scroll-other-window scroll-other-window-down mwheel-scroll)
2102 "List of Commands that won't break out of electric commands.")
2103
2104 (defmacro company--electric-do (&rest body)
2105 (declare (indent 0) (debug t))
2106 `(when (company-manual-begin)
2107 (save-window-excursion
2108 (let ((height (window-height))
2109 (row (company--row))
2110 cmd)
2111 ,@body
2112 (and (< (window-height) height)
2113 (< (- (window-height) row 2) company-tooltip-limit)
2114 (recenter (- (window-height) row 2)))
2115 (while (memq (setq cmd (key-binding (read-key-sequence-vector nil)))
2116 company--electric-commands)
2117 (condition-case err
2118 (call-interactively cmd)
2119 ((beginning-of-buffer end-of-buffer)
2120 (message (error-message-string err)))))
2121 (company--unread-last-input)))))
2122
2123 (defun company--unread-last-input ()
2124 (when last-input-event
2125 (clear-this-command-keys t)
2126 (setq unread-command-events (list last-input-event))))
2127
2128 (defun company-show-doc-buffer ()
2129 "Temporarily show the documentation buffer for the selection."
2130 (interactive)
2131 (let (other-window-scroll-buffer)
2132 (company--electric-do
2133 (let* ((selected (nth company-selection company-candidates))
2134 (doc-buffer (or (company-call-backend 'doc-buffer selected)
2135 (error "No documentation available")))
2136 start)
2137 (when (consp doc-buffer)
2138 (setq start (cdr doc-buffer)
2139 doc-buffer (car doc-buffer)))
2140 (setq other-window-scroll-buffer (get-buffer doc-buffer))
2141 (let ((win (display-buffer doc-buffer t)))
2142 (set-window-start win (if start start (point-min))))))))
2143 (put 'company-show-doc-buffer 'company-keep t)
2144
2145 (defun company-show-location ()
2146 "Temporarily display a buffer showing the selected candidate in context."
2147 (interactive)
2148 (let (other-window-scroll-buffer)
2149 (company--electric-do
2150 (let* ((selected (nth company-selection company-candidates))
2151 (location (company-call-backend 'location selected))
2152 (pos (or (cdr location) (error "No location available")))
2153 (buffer (or (and (bufferp (car location)) (car location))
2154 (find-file-noselect (car location) t))))
2155 (setq other-window-scroll-buffer (get-buffer buffer))
2156 (with-selected-window (display-buffer buffer t)
2157 (save-restriction
2158 (widen)
2159 (if (bufferp (car location))
2160 (goto-char pos)
2161 (goto-char (point-min))
2162 (forward-line (1- pos))))
2163 (set-window-start nil (point)))))))
2164 (put 'company-show-location 'company-keep t)
2165
2166 ;;; package functions ;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;
2167
2168 (defvar-local company-callback nil)
2169
2170 (defun company-remove-callback (&optional ignored)
2171 (remove-hook 'company-completion-finished-hook company-callback t)
2172 (remove-hook 'company-completion-cancelled-hook 'company-remove-callback t)
2173 (remove-hook 'company-completion-finished-hook 'company-remove-callback t))
2174
2175 (defun company-begin-backend (backend &optional callback)
2176 "Start a completion at point using BACKEND."
2177 (interactive (let ((val (completing-read "Company backend: "
2178 obarray
2179 'functionp nil "company-")))
2180 (when val
2181 (list (intern val)))))
2182 (when (setq company-callback callback)
2183 (add-hook 'company-completion-finished-hook company-callback nil t))
2184 (add-hook 'company-completion-cancelled-hook 'company-remove-callback nil t)
2185 (add-hook 'company-completion-finished-hook 'company-remove-callback nil t)
2186 (setq company-backend backend)
2187 ;; Return non-nil if active.
2188 (or (company-manual-begin)
2189 (error "Cannot complete at point")))
2190
2191 (defun company-begin-with (candidates
2192 &optional prefix-length require-match callback)
2193 "Start a completion at point.
2194 CANDIDATES is the list of candidates to use and PREFIX-LENGTH is the length
2195 of the prefix that already is in the buffer before point.
2196 It defaults to 0.
2197
2198 CALLBACK is a function called with the selected result if the user
2199 successfully completes the input.
2200
2201 Example: \(company-begin-with '\(\"foo\" \"foobar\" \"foobarbaz\"\)\)"
2202 (let ((begin-marker (copy-marker (point) t)))
2203 (company-begin-backend
2204 (lambda (command &optional arg &rest ignored)
2205 (pcase command
2206 (`prefix
2207 (when (equal (point) (marker-position begin-marker))
2208 (buffer-substring (- (point) (or prefix-length 0)) (point))))
2209 (`candidates
2210 (all-completions arg candidates))
2211 (`require-match
2212 require-match)))
2213 callback)))
2214
2215 (defun company-version (&optional show-version)
2216 "Get the Company version as string.
2217
2218 If SHOW-VERSION is non-nil, show the version in the echo area."
2219 (interactive (list t))
2220 (with-temp-buffer
2221 (require 'find-func)
2222 (insert-file-contents (find-library-name "company"))
2223 (require 'lisp-mnt)
2224 (if show-version
2225 (message "Company version: %s" (lm-version))
2226 (lm-version))))
2227
2228 (defun company-diag ()
2229 "Pop a buffer with information about completions at point."
2230 (interactive)
2231 (let* ((bb company-backends)
2232 backend
2233 (prefix (cl-loop for b in bb
2234 thereis (let ((company-backend b))
2235 (setq backend b)
2236 (company-call-backend 'prefix))))
2237 cc annotations)
2238 (when (stringp prefix)
2239 (let ((company-backend backend))
2240 (setq cc (company-call-backend 'candidates prefix)
2241 annotations
2242 (mapcar
2243 (lambda (c) (cons c (company-call-backend 'annotation c)))
2244 cc))))
2245 (pop-to-buffer (get-buffer-create "*company-diag*"))
2246 (setq buffer-read-only nil)
2247 (erase-buffer)
2248 (insert (format "Emacs %s (%s) of %s on %s"
2249 emacs-version system-configuration
2250 (format-time-string "%Y-%m-%d" emacs-build-time)
2251 emacs-build-system))
2252 (insert "\nCompany " (company-version) "\n\n")
2253 (insert "company-backends: " (pp-to-string bb))
2254 (insert "\n")
2255 (insert "Used backend: " (pp-to-string backend))
2256 (insert "\n")
2257 (insert "Prefix: " (pp-to-string prefix))
2258 (insert "\n")
2259 (insert (message "Completions:"))
2260 (unless cc (insert " none"))
2261 (save-excursion
2262 (dolist (c annotations)
2263 (insert "\n " (prin1-to-string (car c)))
2264 (when (cdr c)
2265 (insert " " (prin1-to-string (cdr c))))))
2266 (special-mode)))
2267
2268 ;;; pseudo-tooltip ;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;
2269
2270 (defvar-local company-pseudo-tooltip-overlay nil)
2271
2272 (defvar-local company-tooltip-offset 0)
2273
2274 (defun company-tooltip--lines-update-offset (selection num-lines limit)
2275 (cl-decf limit 2)
2276 (setq company-tooltip-offset
2277 (max (min selection company-tooltip-offset)
2278 (- selection -1 limit)))
2279
2280 (when (<= company-tooltip-offset 1)
2281 (cl-incf limit)
2282 (setq company-tooltip-offset 0))
2283
2284 (when (>= company-tooltip-offset (- num-lines limit 1))
2285 (cl-incf limit)
2286 (when (= selection (1- num-lines))
2287 (cl-decf company-tooltip-offset)
2288 (when (<= company-tooltip-offset 1)
2289 (setq company-tooltip-offset 0)
2290 (cl-incf limit))))
2291
2292 limit)
2293
2294 (defun company-tooltip--simple-update-offset (selection _num-lines limit)
2295 (setq company-tooltip-offset
2296 (if (< selection company-tooltip-offset)
2297 selection
2298 (max company-tooltip-offset
2299 (- selection limit -1)))))
2300
2301 ;;; propertize
2302
2303 (defsubst company-round-tab (arg)
2304 (* (/ (+ arg tab-width) tab-width) tab-width))
2305
2306 (defun company-plainify (str)
2307 (let ((prefix (get-text-property 0 'line-prefix str)))
2308 (when prefix ; Keep the original value unmodified, for no special reason.
2309 (setq str (concat prefix str))
2310 (remove-text-properties 0 (length str) '(line-prefix) str)))
2311 (let* ((pieces (split-string str "\t"))
2312 (copy pieces))
2313 (while (cdr copy)
2314 (setcar copy (company-safe-substring
2315 (car copy) 0 (company-round-tab (string-width (car copy)))))
2316 (pop copy))
2317 (apply 'concat pieces)))
2318
2319 (defun company-fill-propertize (value annotation width selected left right)
2320 (let* ((margin (length left))
2321 (common (or (company-call-backend 'match value)
2322 (if company-common
2323 (string-width company-common)
2324 0)))
2325 (ann-ralign company-tooltip-align-annotations)
2326 (ann-truncate (< width
2327 (+ (length value) (length annotation)
2328 (if ann-ralign 1 0))))
2329 (ann-start (+ margin
2330 (if ann-ralign
2331 (if ann-truncate
2332 (1+ (length value))
2333 (- width (length annotation)))
2334 (length value))))
2335 (ann-end (min (+ ann-start (length annotation)) (+ margin width)))
2336 (line (concat left
2337 (if (or ann-truncate (not ann-ralign))
2338 (company-safe-substring
2339 (concat value
2340 (when (and annotation ann-ralign) " ")
2341 annotation)
2342 0 width)
2343 (concat
2344 (company-safe-substring value 0
2345 (- width (length annotation)))
2346 annotation))
2347 right)))
2348 (setq common (+ (min common width) margin))
2349 (setq width (+ width margin (length right)))
2350
2351 (add-text-properties 0 width '(face company-tooltip
2352 mouse-face company-tooltip-mouse)
2353 line)
2354 (add-text-properties margin common
2355 '(face company-tooltip-common
2356 mouse-face company-tooltip-mouse)
2357 line)
2358 (when (< ann-start ann-end)
2359 (add-text-properties ann-start ann-end
2360 '(face company-tooltip-annotation
2361 mouse-face company-tooltip-mouse)
2362 line))
2363 (when selected
2364 (if (let ((re (funcall company-search-regexp-function
2365 company-search-string)))
2366 (and (not (string= re ""))
2367 (string-match re value (length company-prefix))))
2368 (pcase-dolist (`(,mbeg . ,mend) (company--search-chunks))
2369 (let ((beg (+ margin mbeg))
2370 (end (+ margin mend))
2371 (width (- width (length right))))
2372 (when (< beg width)
2373 (add-text-properties beg (min end width)
2374 '(face company-tooltip-search)
2375 line))))
2376 (add-text-properties 0 width '(face company-tooltip-selection
2377 mouse-face company-tooltip-selection)
2378 line)
2379 (add-text-properties margin common
2380 '(face company-tooltip-common-selection
2381 mouse-face company-tooltip-selection)
2382 line)))
2383 line))
2384
2385 (defun company--search-chunks ()
2386 (let ((md (match-data t))
2387 res)
2388 (if (<= (length md) 2)
2389 (push (cons (nth 0 md) (nth 1 md)) res)
2390 (while (setq md (nthcdr 2 md))
2391 (when (car md)
2392 (push (cons (car md) (cadr md)) res))))
2393 res))
2394
2395 (defun company--clean-string (str)
2396 (replace-regexp-in-string
2397 "\\([^[:graph:] ]\\)\\|\\(\ufeff\\)\\|[[:multibyte:]]"
2398 (lambda (match)
2399 (cond
2400 ((match-beginning 1)
2401 ;; FIXME: Better char for 'non-printable'?
2402 ;; We shouldn't get any of these, but sometimes we might.
2403 "\u2017")
2404 ((match-beginning 2)
2405 ;; Zero-width non-breakable space.
2406 "")
2407 ((> (string-width match) 1)
2408 (concat
2409 (make-string (1- (string-width match)) ?\ufeff)
2410 match))
2411 (t match)))
2412 str))
2413
2414 ;;; replace
2415
2416 (defun company-buffer-lines (beg end)
2417 (goto-char beg)
2418 (let (lines lines-moved)
2419 (while (and (not (eobp)) ; http://debbugs.gnu.org/19553
2420 (> (setq lines-moved (vertical-motion 1)) 0)
2421 (<= (point) end))
2422 (let ((bound (min end (point))))
2423 ;; A visual line can contain several physical lines (e.g. with outline's
2424 ;; folding overlay). Take only the first one.
2425 (push (buffer-substring beg
2426 (save-excursion
2427 (goto-char beg)
2428 (re-search-forward "$" bound 'move)
2429 (point)))
2430 lines))
2431 ;; One physical line can be displayed as several visual ones as well:
2432 ;; add empty strings to the list, to even the count.
2433 (dotimes (_ (1- lines-moved))
2434 (push "" lines))
2435 (setq beg (point)))
2436 (unless (eq beg end)
2437 (push (buffer-substring beg end) lines))
2438 (nreverse lines)))
2439
2440 (defun company-modify-line (old new offset)
2441 (concat (company-safe-substring old 0 offset)
2442 new
2443 (company-safe-substring old (+ offset (length new)))))
2444
2445 (defsubst company--length-limit (lst limit)
2446 (if (nthcdr limit lst)
2447 limit
2448 (length lst)))
2449
2450 (defsubst company--window-height ()
2451 (if (fboundp 'window-screen-lines)
2452 (floor (window-screen-lines))
2453 (window-body-height)))
2454
2455 (defun company--window-width ()
2456 (let ((ww (window-body-width)))
2457 ;; Account for the line continuation column.
2458 (when (zerop (cadr (window-fringes)))
2459 (cl-decf ww))
2460 (unless (or (display-graphic-p)
2461 (version< "24.3.1" emacs-version))
2462 ;; Emacs 24.3 and earlier included margins
2463 ;; in window-width when in TTY.
2464 (cl-decf ww
2465 (let ((margins (window-margins)))
2466 (+ (or (car margins) 0)
2467 (or (cdr margins) 0)))))
2468 (when (and word-wrap
2469 (version< emacs-version "24.4.51.5"))
2470 ;; http://debbugs.gnu.org/19300
2471 (cl-decf ww))
2472 ;; whitespace-mode with newline-mark
2473 (when (and buffer-display-table
2474 (aref buffer-display-table ?\n))
2475 (cl-decf ww (1- (length (aref buffer-display-table ?\n)))))
2476 ww))
2477
2478 (defun company--replacement-string (lines old column nl &optional align-top)
2479 (cl-decf column company-tooltip-margin)
2480
2481 (when (and align-top company-tooltip-flip-when-above)
2482 (setq lines (reverse lines)))
2483
2484 (let ((width (length (car lines)))
2485 (remaining-cols (- (+ (company--window-width) (window-hscroll))
2486 column)))
2487 (when (> width remaining-cols)
2488 (cl-decf column (- width remaining-cols))))
2489
2490 (let ((offset (and (< column 0) (- column)))
2491 new)
2492 (when offset
2493 (setq column 0))
2494 (when align-top
2495 ;; untouched lines first
2496 (dotimes (_ (- (length old) (length lines)))
2497 (push (pop old) new)))
2498 ;; length into old lines.
2499 (while old
2500 (push (company-modify-line (pop old)
2501 (company--offset-line (pop lines) offset)
2502 column)
2503 new))
2504 ;; Append whole new lines.
2505 (while lines
2506 (push (concat (company-space-string column)
2507 (company--offset-line (pop lines) offset))
2508 new))
2509
2510 (let ((str (concat (when nl " \n")
2511 (mapconcat 'identity (nreverse new) "\n")
2512 "\n")))
2513 (font-lock-append-text-property 0 (length str) 'face 'default str)
2514 (when nl (put-text-property 0 1 'cursor t str))
2515 str)))
2516
2517 (defun company--offset-line (line offset)
2518 (if (and offset line)
2519 (substring line offset)
2520 line))
2521
2522 (defun company--create-lines (selection limit)
2523 (let ((len company-candidates-length)
2524 (window-width (company--window-width))
2525 lines
2526 width
2527 lines-copy
2528 items
2529 previous
2530 remainder
2531 scrollbar-bounds)
2532
2533 ;; Maybe clear old offset.
2534 (when (< len (+ company-tooltip-offset limit))
2535 (setq company-tooltip-offset 0))
2536
2537 ;; Scroll to offset.
2538 (if (eq company-tooltip-offset-display 'lines)
2539 (setq limit (company-tooltip--lines-update-offset selection len limit))
2540 (company-tooltip--simple-update-offset selection len limit))
2541
2542 (cond
2543 ((eq company-tooltip-offset-display 'scrollbar)
2544 (setq scrollbar-bounds (company--scrollbar-bounds company-tooltip-offset
2545 limit len)))
2546 ((eq company-tooltip-offset-display 'lines)
2547 (when (> company-tooltip-offset 0)
2548 (setq previous (format "...(%d)" company-tooltip-offset)))
2549 (setq remainder (- len limit company-tooltip-offset)
2550 remainder (when (> remainder 0)
2551 (setq remainder (format "...(%d)" remainder))))))
2552
2553 (cl-decf selection company-tooltip-offset)
2554 (setq width (max (length previous) (length remainder))
2555 lines (nthcdr company-tooltip-offset company-candidates)
2556 len (min limit len)
2557 lines-copy lines)
2558
2559 (cl-decf window-width (* 2 company-tooltip-margin))
2560 (when scrollbar-bounds (cl-decf window-width))
2561
2562 (dotimes (_ len)
2563 (let* ((value (pop lines-copy))
2564 (annotation (company-call-backend 'annotation value)))
2565 (setq value (company--clean-string (company-reformat value)))
2566 (when annotation
2567 (when company-tooltip-align-annotations
2568 ;; `lisp-completion-at-point' adds a space.
2569 (setq annotation (comment-string-strip annotation t nil)))
2570 (setq annotation (company--clean-string annotation)))
2571 (push (cons value annotation) items)
2572 (setq width (max (+ (length value)
2573 (if (and annotation company-tooltip-align-annotations)
2574 (1+ (length annotation))
2575 (length annotation)))
2576 width))))
2577
2578 (setq width (min window-width
2579 (max company-tooltip-minimum-width
2580 (if company-show-numbers
2581 (+ 2 width)
2582 width))))
2583
2584 (let ((items (nreverse items))
2585 (numbered (if company-show-numbers 0 99999))
2586 new)
2587 (when previous
2588 (push (company--scrollpos-line previous width) new))
2589
2590 (dotimes (i len)
2591 (let* ((item (pop items))
2592 (str (car item))
2593 (annotation (cdr item))
2594 (right (company-space-string company-tooltip-margin))
2595 (width width))
2596 (when (< numbered 10)
2597 (cl-decf width 2)
2598 (cl-incf numbered)
2599 (setq right (concat (format " %d" (mod numbered 10)) right)))
2600 (push (concat
2601 (company-fill-propertize str annotation
2602 width (equal i selection)
2603 (company-space-string
2604 company-tooltip-margin)
2605 right)
2606 (when scrollbar-bounds
2607 (company--scrollbar i scrollbar-bounds)))
2608 new)))
2609
2610 (when remainder
2611 (push (company--scrollpos-line remainder width) new))
2612
2613 (nreverse new))))
2614
2615 (defun company--scrollbar-bounds (offset limit length)
2616 (when (> length limit)
2617 (let* ((size (ceiling (* limit (float limit)) length))
2618 (lower (floor (* limit (float offset)) length))
2619 (upper (+ lower size -1)))
2620 (cons lower upper))))
2621
2622 (defun company--scrollbar (i bounds)
2623 (propertize " " 'face
2624 (if (and (>= i (car bounds)) (<= i (cdr bounds)))
2625 'company-scrollbar-fg
2626 'company-scrollbar-bg)))
2627
2628 (defun company--scrollpos-line (text width)
2629 (propertize (concat (company-space-string company-tooltip-margin)
2630 (company-safe-substring text 0 width)
2631 (company-space-string company-tooltip-margin))
2632 'face 'company-tooltip))
2633
2634 ;; show
2635
2636 (defun company--pseudo-tooltip-height ()
2637 "Calculate the appropriate tooltip height.
2638 Returns a negative number if the tooltip should be displayed above point."
2639 (let* ((lines (company--row))
2640 (below (- (company--window-height) 1 lines)))
2641 (if (and (< below (min company-tooltip-minimum company-candidates-length))
2642 (> lines below))
2643 (- (max 3 (min company-tooltip-limit lines)))
2644 (max 3 (min company-tooltip-limit below)))))
2645
2646 (defun company-pseudo-tooltip-show (row column selection)
2647 (company-pseudo-tooltip-hide)
2648 (save-excursion
2649
2650 (let* ((height (company--pseudo-tooltip-height))
2651 above)
2652
2653 (when (< height 0)
2654 (setq row (+ row height -1)
2655 above t))
2656
2657 (let* ((nl (< (move-to-window-line row) row))
2658 (beg (point))
2659 (end (save-excursion
2660 (move-to-window-line (+ row (abs height)))
2661 (point)))
2662 (ov (make-overlay beg end nil t))
2663 (args (list (mapcar 'company-plainify
2664 (company-buffer-lines beg end))
2665 column nl above)))
2666
2667 (setq company-pseudo-tooltip-overlay ov)
2668 (overlay-put ov 'company-replacement-args args)
2669
2670 (let ((lines (company--create-lines selection (abs height))))
2671 (overlay-put ov 'company-display
2672 (apply 'company--replacement-string lines args))
2673 (overlay-put ov 'company-width (string-width (car lines))))
2674
2675 (overlay-put ov 'company-column column)
2676 (overlay-put ov 'company-height height)))))
2677
2678 (defun company-pseudo-tooltip-show-at-point (pos column-offset)
2679 (let* ((col-row (company--col-row pos))
2680 (col (- (car col-row) column-offset)))
2681 (when (< col 0) (setq col 0))
2682 (company-pseudo-tooltip-show (1+ (cdr col-row)) col company-selection)))
2683
2684 (defun company-pseudo-tooltip-edit (selection)
2685 (let* ((height (overlay-get company-pseudo-tooltip-overlay 'company-height))
2686 (lines (company--create-lines selection (abs height))))
2687 (overlay-put company-pseudo-tooltip-overlay 'company-width
2688 (string-width (car lines)))
2689 (overlay-put company-pseudo-tooltip-overlay 'company-display
2690 (apply 'company--replacement-string
2691 lines
2692 (overlay-get company-pseudo-tooltip-overlay
2693 'company-replacement-args)))))
2694
2695 (defun company-pseudo-tooltip-hide ()
2696 (when company-pseudo-tooltip-overlay
2697 (delete-overlay company-pseudo-tooltip-overlay)
2698 (setq company-pseudo-tooltip-overlay nil)))
2699
2700 (defun company-pseudo-tooltip-hide-temporarily ()
2701 (when (overlayp company-pseudo-tooltip-overlay)
2702 (overlay-put company-pseudo-tooltip-overlay 'invisible nil)
2703 (overlay-put company-pseudo-tooltip-overlay 'line-prefix nil)
2704 (overlay-put company-pseudo-tooltip-overlay 'after-string nil)
2705 (overlay-put company-pseudo-tooltip-overlay 'display nil)))
2706
2707 (defun company-pseudo-tooltip-unhide ()
2708 (when company-pseudo-tooltip-overlay
2709 (let* ((ov company-pseudo-tooltip-overlay)
2710 (disp (overlay-get ov 'company-display)))
2711 ;; Beat outline's folding overlays, at least.
2712 (overlay-put ov 'priority 1)
2713 ;; No (extra) prefix for the first line.
2714 (overlay-put ov 'line-prefix "")
2715 ;; `display' is better
2716 ;; (http://debbugs.gnu.org/18285, http://debbugs.gnu.org/20847),
2717 ;; but it doesn't work on 0-length overlays.
2718 (if (< (overlay-start ov) (overlay-end ov))
2719 (overlay-put ov 'display disp)
2720 (overlay-put ov 'after-string disp)
2721 (overlay-put ov 'invisible t))
2722 (overlay-put ov 'window (selected-window)))))
2723
2724 (defun company-pseudo-tooltip-guard ()
2725 (cons
2726 (save-excursion (beginning-of-visual-line))
2727 (let ((ov company-pseudo-tooltip-overlay)
2728 (overhang (save-excursion (end-of-visual-line)
2729 (- (line-end-position) (point)))))
2730 (when (>= (overlay-get ov 'company-height) 0)
2731 (cons
2732 (buffer-substring-no-properties (point) (overlay-start ov))
2733 (when (>= overhang 0) overhang))))))
2734
2735 (defun company-pseudo-tooltip-frontend (command)
2736 "`company-mode' frontend similar to a tooltip but based on overlays."
2737 (cl-case command
2738 (pre-command (company-pseudo-tooltip-hide-temporarily))
2739 (post-command
2740 (unless (when (overlayp company-pseudo-tooltip-overlay)
2741 (let* ((ov company-pseudo-tooltip-overlay)
2742 (old-height (overlay-get ov 'company-height))
2743 (new-height (company--pseudo-tooltip-height)))
2744 (and
2745 (>= (* old-height new-height) 0)
2746 (>= (abs old-height) (abs new-height))
2747 (equal (company-pseudo-tooltip-guard)
2748 (overlay-get ov 'company-guard)))))
2749 ;; Redraw needed.
2750 (company-pseudo-tooltip-show-at-point (point) (length company-prefix))
2751 (overlay-put company-pseudo-tooltip-overlay
2752 'company-guard (company-pseudo-tooltip-guard)))
2753 (company-pseudo-tooltip-unhide))
2754 (hide (company-pseudo-tooltip-hide)
2755 (setq company-tooltip-offset 0))
2756 (update (when (overlayp company-pseudo-tooltip-overlay)
2757 (company-pseudo-tooltip-edit company-selection)))))
2758
2759 (defun company-pseudo-tooltip-unless-just-one-frontend (command)
2760 "`company-pseudo-tooltip-frontend', but not shown for single candidates."
2761 (unless (and (eq command 'post-command)
2762 (company--show-inline-p))
2763 (company-pseudo-tooltip-frontend command)))
2764
2765 ;;; overlay ;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;
2766
2767 (defvar-local company-preview-overlay nil)
2768
2769 (defun company-preview-show-at-point (pos)
2770 (company-preview-hide)
2771
2772 (let ((completion (nth company-selection company-candidates)))
2773 (setq completion (propertize completion 'face 'company-preview))
2774 (add-text-properties 0 (length company-common)
2775 '(face company-preview-common) completion)
2776
2777 ;; Add search string
2778 (and (string-match (funcall company-search-regexp-function
2779 company-search-string)
2780 completion)
2781 (pcase-dolist (`(,mbeg . ,mend) (company--search-chunks))
2782 (add-text-properties mbeg
2783 mend
2784 '(face company-preview-search)
2785 completion)))
2786
2787 (setq completion (company-strip-prefix completion))
2788
2789 (and (equal pos (point))
2790 (not (equal completion ""))
2791 (add-text-properties 0 1 '(cursor 1) completion))
2792
2793 (let* ((beg pos)
2794 (pto company-pseudo-tooltip-overlay)
2795 (ptf-workaround (and
2796 pto
2797 (char-before pos)
2798 (eq pos (overlay-start pto)))))
2799 ;; Try to accomodate for the pseudo-tooltip overlay,
2800 ;; which may start at the same position if it's at eol.
2801 (when ptf-workaround
2802 (cl-decf beg)
2803 (setq completion (concat (buffer-substring beg pos) completion)))
2804
2805 (setq company-preview-overlay (make-overlay beg pos))
2806
2807 (let ((ov company-preview-overlay))
2808 (overlay-put ov (if ptf-workaround 'display 'after-string)
2809 completion)
2810 (overlay-put ov 'window (selected-window))))))
2811
2812 (defun company-preview-hide ()
2813 (when company-preview-overlay
2814 (delete-overlay company-preview-overlay)
2815 (setq company-preview-overlay nil)))
2816
2817 (defun company-preview-frontend (command)
2818 "`company-mode' frontend showing the selection as if it had been inserted."
2819 (pcase command
2820 (`pre-command (company-preview-hide))
2821 (`post-command (company-preview-show-at-point (point)))
2822 (`hide (company-preview-hide))))
2823
2824 (defun company-preview-if-just-one-frontend (command)
2825 "`company-preview-frontend', but only shown for single candidates."
2826 (when (or (not (eq command 'post-command))
2827 (company--show-inline-p))
2828 (company-preview-frontend command)))
2829
2830 (defun company--show-inline-p ()
2831 (and (not (cdr company-candidates))
2832 company-common
2833 (or (eq (company-call-backend 'ignore-case) 'keep-prefix)
2834 (string-prefix-p company-prefix company-common))))
2835
2836 ;;; echo ;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;
2837
2838 (defvar-local company-echo-last-msg nil)
2839
2840 (defvar company-echo-timer nil)
2841
2842 (defvar company-echo-delay .01)
2843
2844 (defun company-echo-show (&optional getter)
2845 (when getter
2846 (setq company-echo-last-msg (funcall getter)))
2847 (let ((message-log-max nil))
2848 (if company-echo-last-msg
2849 (message "%s" company-echo-last-msg)
2850 (message ""))))
2851
2852 (defun company-echo-show-soon (&optional getter)
2853 (company-echo-cancel)
2854 (setq company-echo-timer (run-with-timer 0 nil 'company-echo-show getter)))
2855
2856 (defun company-echo-cancel (&optional unset)
2857 (when company-echo-timer
2858 (cancel-timer company-echo-timer))
2859 (when unset
2860 (setq company-echo-timer nil)))
2861
2862 (defun company-echo-show-when-idle (&optional getter)
2863 (company-echo-cancel)
2864 (setq company-echo-timer
2865 (run-with-idle-timer company-echo-delay nil 'company-echo-show getter)))
2866
2867 (defun company-echo-format ()
2868
2869 (let ((limit (window-body-width (minibuffer-window)))
2870 (len -1)
2871 ;; Roll to selection.
2872 (candidates (nthcdr company-selection company-candidates))
2873 (i (if company-show-numbers company-selection 99999))
2874 comp msg)
2875
2876 (while candidates
2877 (setq comp (company-reformat (pop candidates))
2878 len (+ len 1 (length comp)))
2879 (if (< i 10)
2880 ;; Add number.
2881 (progn
2882 (setq comp (propertize (format "%d: %s" i comp)
2883 'face 'company-echo))
2884 (cl-incf len 3)
2885 (cl-incf i)
2886 (add-text-properties 3 (+ 3 (length company-common))
2887 '(face company-echo-common) comp))
2888 (setq comp (propertize comp 'face 'company-echo))
2889 (add-text-properties 0 (length company-common)
2890 '(face company-echo-common) comp))
2891 (if (>= len limit)
2892 (setq candidates nil)
2893 (push comp msg)))
2894
2895 (mapconcat 'identity (nreverse msg) " ")))
2896
2897 (defun company-echo-strip-common-format ()
2898
2899 (let ((limit (window-body-width (minibuffer-window)))
2900 (len (+ (length company-prefix) 2))
2901 ;; Roll to selection.
2902 (candidates (nthcdr company-selection company-candidates))
2903 (i (if company-show-numbers company-selection 99999))
2904 msg comp)
2905
2906 (while candidates
2907 (setq comp (company-strip-prefix (pop candidates))
2908 len (+ len 2 (length comp)))
2909 (when (< i 10)
2910 ;; Add number.
2911 (setq comp (format "%s (%d)" comp i))
2912 (cl-incf len 4)
2913 (cl-incf i))
2914 (if (>= len limit)
2915 (setq candidates nil)
2916 (push (propertize comp 'face 'company-echo) msg)))
2917
2918 (concat (propertize company-prefix 'face 'company-echo-common) "{"
2919 (mapconcat 'identity (nreverse msg) ", ")
2920 "}")))
2921
2922 (defun company-echo-hide ()
2923 (unless (equal company-echo-last-msg "")
2924 (setq company-echo-last-msg "")
2925 (company-echo-show)))
2926
2927 (defun company-echo-frontend (command)
2928 "`company-mode' frontend showing the candidates in the echo area."
2929 (pcase command
2930 (`post-command (company-echo-show-soon 'company-echo-format))
2931 (`hide (company-echo-hide))))
2932
2933 (defun company-echo-strip-common-frontend (command)
2934 "`company-mode' frontend showing the candidates in the echo area."
2935 (pcase command
2936 (`post-command (company-echo-show-soon 'company-echo-strip-common-format))
2937 (`hide (company-echo-hide))))
2938
2939 (defun company-echo-metadata-frontend (command)
2940 "`company-mode' frontend showing the documentation in the echo area."
2941 (pcase command
2942 (`post-command (company-echo-show-when-idle 'company-fetch-metadata))
2943 (`hide (company-echo-hide))))
2944
2945 (provide 'company)
2946 ;;; company.el ends here