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