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