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