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