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