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