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