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