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