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