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