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