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