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