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