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