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