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