]> code.delx.au - gnu-emacs-elpa/blob - company.el
Remove `company-locate-dominating-file'
[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 (defun company-call-backend (&rest args)
796 (let ((val (apply #'company-call-backend-raw args)))
797 (if (not (eq (car-safe val) :async))
798 val
799 (let ((res 'trash)
800 (start (time-to-seconds)))
801 (funcall (cdr val)
802 (lambda (result) (setq res result)))
803 (while (eq res 'trash)
804 (if (> (- (time-to-seconds) start) company-async-timeout)
805 (error "Company: Back-end %s async timeout with args %s"
806 company-backend args)
807 (sleep-for company-async-wait)))
808 res))))
809
810 (defun company-call-backend-raw (&rest args)
811 (condition-case err
812 (if (functionp company-backend)
813 (apply company-backend args)
814 (apply #'company--multi-backend-adapter company-backend args))
815 (error (error "Company: Back-end %s error \"%s\" with args %s"
816 company-backend (error-message-string err) args))))
817
818 (defun company--multi-backend-adapter (backends command &rest args)
819 (let ((backends (loop for b in backends
820 when (not (and (symbolp b)
821 (eq 'failed (get b 'company-init))))
822 collect b)))
823 (setq backends
824 (if (eq command 'prefix)
825 (butlast backends (length (member :with backends)))
826 (delq :with backends)))
827 (pcase command
828 (`candidates
829 ;; Small perf optimization: don't tag the candidates received
830 ;; from the first backend in the group.
831 (append (apply (car backends) 'candidates args)
832 (loop for backend in (cdr backends)
833 when (equal (funcall backend 'prefix)
834 (car args))
835 append (mapcar
836 (lambda (str)
837 (propertize str 'company-backend backend))
838 (apply backend 'candidates args)))))
839 (`sorted nil)
840 (`duplicates t)
841 ((or `prefix `ignore-case `no-cache `require-match)
842 (let (value)
843 (dolist (backend backends)
844 (when (setq value (apply backend command args))
845 (return value)))))
846 (_
847 (let ((arg (car args)))
848 (when (> (length arg) 0)
849 (let ((backend (or (get-text-property 0 'company-backend arg)
850 (car backends))))
851 (apply backend command args))))))))
852
853 ;;; completion mechanism ;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;
854
855 (defvar company-prefix nil)
856 (make-variable-buffer-local 'company-prefix)
857
858 (defvar company-candidates nil)
859 (make-variable-buffer-local 'company-candidates)
860
861 (defvar company-candidates-length nil)
862 (make-variable-buffer-local 'company-candidates-length)
863
864 (defvar company-candidates-cache nil)
865 (make-variable-buffer-local 'company-candidates-cache)
866
867 (defvar company-candidates-predicate nil)
868 (make-variable-buffer-local 'company-candidates-predicate)
869
870 (defvar company-common nil)
871 (make-variable-buffer-local 'company-common)
872
873 (defvar company-selection 0)
874 (make-variable-buffer-local 'company-selection)
875
876 (defvar company-selection-changed nil)
877 (make-variable-buffer-local 'company-selection-changed)
878
879 (defvar company--manual-action nil
880 "Non-nil, if manual completion took place.")
881 (make-variable-buffer-local 'company--manual-action)
882
883 (defvar company--manual-prefix nil)
884 (make-variable-buffer-local 'company--manual-prefix)
885
886 (defvar company--auto-completion nil
887 "Non-nil when current candidate is being inserted automatically.
888 Controlled by `company-auto-complete'.")
889
890 (defvar company--point-max nil)
891 (make-variable-buffer-local 'company--point-max)
892
893 (defvar company-point nil)
894 (make-variable-buffer-local 'company-point)
895
896 (defvar company-timer nil)
897
898 (defvar company-added-newline nil)
899 (make-variable-buffer-local 'company-added-newline)
900
901 (defsubst company-strip-prefix (str)
902 (substring str (length company-prefix)))
903
904 (defun company--insert-candidate (candidate)
905 (setq candidate (substring-no-properties candidate))
906 ;; XXX: Return value we check here is subject to change.
907 (if (eq (company-call-backend 'ignore-case) 'keep-prefix)
908 (insert (company-strip-prefix candidate))
909 (delete-region (- (point) (length company-prefix)) (point))
910 (insert candidate)))
911
912 (defmacro company-with-candidate-inserted (candidate &rest body)
913 "Evaluate BODY with CANDIDATE temporarily inserted.
914 This is a tool for back-ends that need candidates inserted before they
915 can retrieve meta-data for them."
916 (declare (indent 1))
917 `(let ((inhibit-modification-hooks t)
918 (inhibit-point-motion-hooks t)
919 (modified-p (buffer-modified-p)))
920 (company--insert-candidate ,candidate)
921 (unwind-protect
922 (progn ,@body)
923 (delete-region company-point (point)))))
924
925 (defun company-explicit-action-p ()
926 "Return whether explicit completion action was taken by the user."
927 (or company--manual-action
928 company-selection-changed))
929
930 (defun company-reformat (candidate)
931 ;; company-ispell needs this, because the results are always lower-case
932 ;; It's mory efficient to fix it only when they are displayed.
933 ;; FIXME: Adopt the current text's capitalization instead?
934 (if (eq (company-call-backend 'ignore-case) 'keep-prefix)
935 (concat company-prefix (substring candidate (length company-prefix)))
936 candidate))
937
938 (defun company--should-complete ()
939 (and (not (or buffer-read-only overriding-terminal-local-map
940 overriding-local-map))
941 ;; Check if in the middle of entering a key combination.
942 (or (equal (this-command-keys-vector) [])
943 (not (keymapp (key-binding (this-command-keys-vector)))))
944 (eq company-idle-delay t)
945 (or (eq t company-begin-commands)
946 (memq this-command company-begin-commands)
947 (and (symbolp this-command) (get this-command 'company-begin)))
948 (not (and transient-mark-mode mark-active))))
949
950 (defun company--should-continue ()
951 (or (eq t company-begin-commands)
952 (eq t company-continue-commands)
953 (if (eq 'not (car company-continue-commands))
954 (not (memq this-command (cdr company-continue-commands)))
955 (or (memq this-command company-begin-commands)
956 (memq this-command company-continue-commands)
957 (string-match-p "\\`company-" (symbol-name this-command))))))
958
959 (defun company-call-frontends (command)
960 (dolist (frontend company-frontends)
961 (condition-case err
962 (funcall frontend command)
963 (error (error "Company: Front-end %s error \"%s\" on command %s"
964 frontend (error-message-string err) command)))))
965
966 (defun company-set-selection (selection &optional force-update)
967 (setq selection
968 (if company-selection-wrap-around
969 (mod selection company-candidates-length)
970 (max 0 (min (1- company-candidates-length) selection))))
971 (when (or force-update (not (equal selection company-selection)))
972 (setq company-selection selection
973 company-selection-changed t)
974 (company-call-frontends 'update)))
975
976 (defun company-apply-predicate (candidates predicate)
977 (let (new)
978 (dolist (c candidates)
979 (when (funcall predicate c)
980 (push c new)))
981 (nreverse new)))
982
983 (defun company-update-candidates (candidates)
984 (setq company-candidates-length (length candidates))
985 (if (> company-selection 0)
986 ;; Try to restore the selection
987 (let ((selected (nth company-selection company-candidates)))
988 (setq company-selection 0
989 company-candidates candidates)
990 (when selected
991 (while (and candidates (string< (pop candidates) selected))
992 (incf company-selection))
993 (unless candidates
994 ;; Make sure selection isn't out of bounds.
995 (setq company-selection (min (1- company-candidates-length)
996 company-selection)))))
997 (setq company-selection 0
998 company-candidates candidates))
999 ;; Save in cache:
1000 (push (cons company-prefix company-candidates) company-candidates-cache)
1001 ;; Calculate common.
1002 (let ((completion-ignore-case (company-call-backend 'ignore-case)))
1003 ;; We want to support non-prefix completion, so filtering is the
1004 ;; responsibility of each respective backend, not ours.
1005 ;; On the other hand, we don't want to replace non-prefix input in
1006 ;; `company-complete-common'.
1007 (setq company-common
1008 (if (cdr company-candidates)
1009 (let ((common (try-completion company-prefix company-candidates)))
1010 (if (eq common t)
1011 ;; Mulple equal strings, probably with different
1012 ;; annotations.
1013 company-prefix
1014 common))
1015 (car company-candidates)))))
1016
1017 (defun company-calculate-candidates (prefix)
1018 (let ((candidates (cdr (assoc prefix company-candidates-cache)))
1019 (ignore-case (company-call-backend 'ignore-case)))
1020 (or candidates
1021 (when company-candidates-cache
1022 (let ((len (length prefix))
1023 (completion-ignore-case ignore-case)
1024 prev)
1025 (dotimes (i (1+ len))
1026 (when (setq prev (cdr (assoc (substring prefix 0 (- len i))
1027 company-candidates-cache)))
1028 (setq candidates (all-completions prefix prev))
1029 (return t)))))
1030 ;; no cache match, call back-end
1031 (setq candidates
1032 (company--process-candidates
1033 (company--fetch-candidates prefix))))
1034 (setq candidates (company--transform-candidates candidates))
1035 (when candidates
1036 (if (or (cdr candidates)
1037 (not (eq t (compare-strings (car candidates) nil nil
1038 prefix nil nil ignore-case))))
1039 candidates
1040 ;; Already completed and unique; don't start.
1041 t))))
1042
1043 (defun company--fetch-candidates (prefix)
1044 (let ((c (if company--manual-action
1045 (company-call-backend 'candidates prefix)
1046 (company-call-backend-raw 'candidates prefix)))
1047 res)
1048 (if (not (eq (car c) :async))
1049 c
1050 (let ((buf (current-buffer))
1051 (win (selected-window))
1052 (tick (buffer-chars-modified-tick))
1053 (pt (point))
1054 (backend company-backend))
1055 (funcall
1056 (cdr c)
1057 (lambda (candidates)
1058 (if (not (and candidates (eq res 'done)))
1059 ;; Fetcher called us right back.
1060 (setq res candidates)
1061 (setq company-backend backend
1062 company-candidates-cache
1063 (list (cons prefix
1064 (company--process-candidates
1065 candidates))))
1066 (company-idle-begin buf win tick pt)))))
1067 ;; FIXME: Relying on the fact that the callers
1068 ;; will interpret nil as "do nothing" is shaky.
1069 ;; A throw-catch would be one possible improvement.
1070 (or res
1071 (progn (setq res 'done) nil)))))
1072
1073 (defun company--process-candidates (candidates)
1074 (when company-candidates-predicate
1075 (setq candidates
1076 (company-apply-predicate candidates
1077 company-candidates-predicate)))
1078 (unless (company-call-backend 'sorted)
1079 (setq candidates (sort candidates 'string<)))
1080 (when (company-call-backend 'duplicates)
1081 (company--strip-duplicates candidates))
1082 candidates)
1083
1084 (defun company--strip-duplicates (candidates)
1085 (let ((c2 candidates))
1086 (while c2
1087 (setcdr c2
1088 (let ((str (car c2))
1089 (anno 'unk))
1090 (pop c2)
1091 (while (let ((str2 (car c2)))
1092 (if (not (equal str str2))
1093 nil
1094 (when (eq anno 'unk)
1095 (setq anno (company-call-backend
1096 'annotation str)))
1097 (equal anno
1098 (company-call-backend
1099 'annotation str2))))
1100 (pop c2))
1101 c2)))))
1102
1103 (defun company--transform-candidates (candidates)
1104 (let ((c candidates))
1105 (dolist (tr company-transformers)
1106 (setq c (funcall tr c)))
1107 c))
1108
1109 (defun company-sort-by-occurrence (candidates)
1110 "Sort CANDIDATES according to their occurrences.
1111 Searches for each in the currently visible part of the current buffer and
1112 gives priority to the closest ones above point, then closest ones below
1113 point. The rest of the list is appended unchanged.
1114 Keywords and function definition names are ignored."
1115 (let* (occurs
1116 (noccurs
1117 (delete-if
1118 (lambda (candidate)
1119 (when (or
1120 (save-excursion
1121 (progn (forward-line 0)
1122 (search-backward candidate (window-start) t)))
1123 (save-excursion
1124 (search-forward candidate (window-end) t)))
1125 (let ((beg (match-beginning 0))
1126 (end (match-end 0)))
1127 (when (save-excursion
1128 (goto-char end)
1129 (and (not (memq (get-text-property (point) 'face)
1130 '(font-lock-function-name-face
1131 font-lock-keyword-face)))
1132 (let* ((prefix (company-call-backend 'prefix))
1133 (prefix (or (car-safe prefix) prefix)))
1134 (and (stringp prefix)
1135 (= (length prefix) (- end beg))))))
1136 (push (cons candidate (if (< beg (point))
1137 (- (point) end)
1138 (- beg (window-start))))
1139 occurs)
1140 t))))
1141 candidates)))
1142 (nconc
1143 (mapcar #'car (sort occurs (lambda (e1 e2) (<= (cdr e1) (cdr e2)))))
1144 noccurs)))
1145
1146 (defun company-idle-begin (buf win tick pos)
1147 (and (eq buf (current-buffer))
1148 (eq win (selected-window))
1149 (eq tick (buffer-chars-modified-tick))
1150 (eq pos (point))
1151 (when (company-auto-begin)
1152 (when (version< emacs-version "24.3.50")
1153 (company-input-noop))
1154 (company-post-command))))
1155
1156 (defun company-auto-begin ()
1157 (and company-mode
1158 (not company-candidates)
1159 (let ((company-idle-delay t)
1160 (company-begin-commands t))
1161 (condition-case-unless-debug err
1162 (company-begin)
1163 (error (message "Company: An error occurred in auto-begin")
1164 (message "%s" (error-message-string err))
1165 (company-cancel))
1166 (quit (company-cancel)))))
1167 (unless company-candidates
1168 (setq company-backend nil))
1169 ;; Return non-nil if active.
1170 company-candidates)
1171
1172 (defun company-manual-begin ()
1173 (interactive)
1174 (company-assert-enabled)
1175 (setq company--manual-action t)
1176 (unwind-protect
1177 (let ((company-minimum-prefix-length 0))
1178 (company-auto-begin))
1179 (unless company-candidates
1180 (setq company--manual-action nil))))
1181
1182 (defun company-other-backend (&optional backward)
1183 (interactive (list current-prefix-arg))
1184 (company-assert-enabled)
1185 (if company-backend
1186 (let* ((after (cdr (member company-backend company-backends)))
1187 (before (cdr (member company-backend (reverse company-backends))))
1188 (next (if backward
1189 (append before (reverse after))
1190 (append after (reverse before)))))
1191 (company-cancel)
1192 (dolist (backend next)
1193 (when (ignore-errors (company-begin-backend backend))
1194 (return t))))
1195 (company-manual-begin))
1196 (unless company-candidates
1197 (error "No other back-end")))
1198
1199 (defun company-require-match-p ()
1200 (let ((backend-value (company-call-backend 'require-match)))
1201 (or (eq backend-value t)
1202 (and (not (eq backend-value 'never))
1203 (if (functionp company-require-match)
1204 (funcall company-require-match)
1205 (eq company-require-match t))))))
1206
1207 (defun company-auto-complete-p (input)
1208 "Return non-nil, if input starts with punctuation or parentheses."
1209 (and (if (functionp company-auto-complete)
1210 (funcall company-auto-complete)
1211 company-auto-complete)
1212 (if (functionp company-auto-complete-chars)
1213 (funcall company-auto-complete-chars input)
1214 (if (consp company-auto-complete-chars)
1215 (memq (char-syntax (string-to-char input))
1216 company-auto-complete-chars)
1217 (string-match (substring input 0 1) company-auto-complete-chars)))))
1218
1219 (defun company--incremental-p ()
1220 (and (> (point) company-point)
1221 (> (point-max) company--point-max)
1222 (not (eq this-command 'backward-delete-char-untabify))
1223 (equal (buffer-substring (- company-point (length company-prefix))
1224 company-point)
1225 company-prefix)))
1226
1227 (defun company--continue-failed ()
1228 (let ((input (buffer-substring-no-properties (point) company-point)))
1229 (cond
1230 ((company-auto-complete-p input)
1231 ;; auto-complete
1232 (save-excursion
1233 (goto-char company-point)
1234 (let ((company--auto-completion t))
1235 (company-complete-selection))
1236 nil))
1237 ((company-require-match-p)
1238 ;; wrong incremental input, but required match
1239 (delete-char (- (length input)))
1240 (ding)
1241 (message "Matching input is required")
1242 company-candidates)
1243 ((equal company-prefix (car company-candidates))
1244 ;; last input was actually success
1245 (company-cancel company-prefix))
1246 (t (company-cancel)))))
1247
1248 (defun company--good-prefix-p (prefix)
1249 (and (stringp (or (car-safe prefix) prefix)) ;excludes 'stop
1250 (or (eq (cdr-safe prefix) t)
1251 (let ((len (or (cdr-safe prefix) (length prefix))))
1252 (if company--manual-prefix
1253 (or (not company-abort-manual-when-too-short)
1254 ;; Must not be less than minimum or initial length.
1255 (>= len (min company-minimum-prefix-length
1256 (length company--manual-prefix))))
1257 (>= len company-minimum-prefix-length))))))
1258
1259 (defun company--continue ()
1260 (when (company-call-backend 'no-cache company-prefix)
1261 ;; Don't complete existing candidates, fetch new ones.
1262 (setq company-candidates-cache nil))
1263 (let* ((new-prefix (company-call-backend 'prefix))
1264 (c (when (and (company--good-prefix-p new-prefix)
1265 (setq new-prefix (or (car-safe new-prefix) new-prefix))
1266 (= (- (point) (length new-prefix))
1267 (- company-point (length company-prefix))))
1268 (company-calculate-candidates new-prefix))))
1269 (cond
1270 ((eq c t)
1271 ;; t means complete/unique.
1272 (company-cancel new-prefix))
1273 ((consp c)
1274 ;; incremental match
1275 (setq company-prefix new-prefix)
1276 (company-update-candidates c)
1277 c)
1278 ((not (company--incremental-p))
1279 (company-cancel))
1280 (t (company--continue-failed)))))
1281
1282 (defun company--begin-new ()
1283 (let (prefix c)
1284 (dolist (backend (if company-backend
1285 ;; prefer manual override
1286 (list company-backend)
1287 company-backends))
1288 (setq prefix
1289 (if (or (symbolp backend)
1290 (functionp backend))
1291 (when (or (not (symbolp backend))
1292 (eq t (get backend 'company-init))
1293 (unless (get backend 'company-init)
1294 (company-init-backend backend)))
1295 (funcall backend 'prefix))
1296 (company--multi-backend-adapter backend 'prefix)))
1297 (when prefix
1298 (when (company--good-prefix-p prefix)
1299 (setq prefix (or (car-safe prefix) prefix)
1300 company-backend backend
1301 c (company-calculate-candidates prefix))
1302 ;; t means complete/unique. We don't start, so no hooks.
1303 (if (not (consp c))
1304 (when company--manual-action
1305 (message "No completion found"))
1306 (setq company-prefix prefix)
1307 (when company--manual-action
1308 (setq company--manual-prefix prefix))
1309 (when (symbolp backend)
1310 (setq company-lighter (concat " " (symbol-name backend))))
1311 (company-update-candidates c)
1312 (run-hook-with-args 'company-completion-started-hook
1313 (company-explicit-action-p))
1314 (company-call-frontends 'show)))
1315 (return c)))))
1316
1317 (defun company-begin ()
1318 (or (and company-candidates (company--continue))
1319 (and (company--should-complete) (company--begin-new)))
1320 (when company-candidates
1321 (let ((modified (buffer-modified-p)))
1322 (when (and company-end-of-buffer-workaround (eobp))
1323 (save-excursion (insert "\n"))
1324 (setq company-added-newline
1325 (or modified (buffer-chars-modified-tick)))))
1326 (setq company-point (point)
1327 company--point-max (point-max))
1328 (company-ensure-emulation-alist)
1329 (company-enable-overriding-keymap company-active-map)
1330 (company-call-frontends 'update)))
1331
1332 (defun company-cancel (&optional result)
1333 (and company-added-newline
1334 (> (point-max) (point-min))
1335 (let ((tick (buffer-chars-modified-tick)))
1336 (delete-region (1- (point-max)) (point-max))
1337 (equal tick company-added-newline))
1338 ;; Only set unmodified when tick remained the same since insert,
1339 ;; and the buffer wasn't modified before.
1340 (set-buffer-modified-p nil))
1341 (when company-prefix
1342 (if (stringp result)
1343 (progn
1344 (company-call-backend 'pre-completion result)
1345 (run-hook-with-args 'company-completion-finished-hook result)
1346 (company-call-backend 'post-completion result))
1347 (run-hook-with-args 'company-completion-cancelled-hook result)))
1348 (setq company-added-newline nil
1349 company-backend nil
1350 company-prefix nil
1351 company-candidates nil
1352 company-candidates-length nil
1353 company-candidates-cache nil
1354 company-candidates-predicate nil
1355 company-common nil
1356 company-selection 0
1357 company-selection-changed nil
1358 company--manual-action nil
1359 company--manual-prefix nil
1360 company-lighter company-default-lighter
1361 company--point-max nil
1362 company-point nil)
1363 (when company-timer
1364 (cancel-timer company-timer))
1365 (company-search-mode 0)
1366 (company-call-frontends 'hide)
1367 (company-enable-overriding-keymap nil)
1368 ;; Make return value explicit.
1369 nil)
1370
1371 (defun company-abort ()
1372 (interactive)
1373 (company-cancel t)
1374 ;; Don't start again, unless started manually.
1375 (setq company-point (point)))
1376
1377 (defun company-finish (result)
1378 (company--insert-candidate result)
1379 (company-cancel result)
1380 ;; Don't start again, unless started manually.
1381 (setq company-point (point)))
1382
1383 (defsubst company-keep (command)
1384 (and (symbolp command) (get command 'company-keep)))
1385
1386 (defun company-pre-command ()
1387 (unless (company-keep this-command)
1388 (condition-case err
1389 (when company-candidates
1390 (company-call-frontends 'pre-command)
1391 (unless (company--should-continue)
1392 (company-abort)))
1393 (error (message "Company: An error occurred in pre-command")
1394 (message "%s" (error-message-string err))
1395 (company-cancel))))
1396 (when company-timer
1397 (cancel-timer company-timer)
1398 (setq company-timer nil))
1399 (company-uninstall-map))
1400
1401 (defun company-post-command ()
1402 (unless (company-keep this-command)
1403 (condition-case err
1404 (progn
1405 (unless (equal (point) company-point)
1406 (company-begin))
1407 (if company-candidates
1408 (company-call-frontends 'post-command)
1409 (and (numberp company-idle-delay)
1410 (or (eq t company-begin-commands)
1411 (memq this-command company-begin-commands))
1412 (not (equal (point) company-point))
1413 (setq company-timer
1414 (run-with-timer company-idle-delay nil
1415 'company-idle-begin
1416 (current-buffer) (selected-window)
1417 (buffer-chars-modified-tick) (point))))))
1418 (error (message "Company: An error occurred in post-command")
1419 (message "%s" (error-message-string err))
1420 (company-cancel))))
1421 (company-install-map))
1422
1423 ;;; search ;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;
1424
1425 (defvar company-search-string nil)
1426 (make-variable-buffer-local 'company-search-string)
1427
1428 (defvar company-search-lighter " Search: \"\"")
1429 (make-variable-buffer-local 'company-search-lighter)
1430
1431 (defvar company-search-old-map nil)
1432 (make-variable-buffer-local 'company-search-old-map)
1433
1434 (defvar company-search-old-selection 0)
1435 (make-variable-buffer-local 'company-search-old-selection)
1436
1437 (defun company-search (text lines)
1438 (let ((quoted (regexp-quote text))
1439 (i 0))
1440 (dolist (line lines)
1441 (when (string-match quoted line (length company-prefix))
1442 (return i))
1443 (incf i))))
1444
1445 (defun company-search-printing-char ()
1446 (interactive)
1447 (company-search-assert-enabled)
1448 (setq company-search-string
1449 (concat (or company-search-string "") (string last-command-event))
1450 company-search-lighter (concat " Search: \"" company-search-string
1451 "\""))
1452 (let ((pos (company-search company-search-string
1453 (nthcdr company-selection company-candidates))))
1454 (if (null pos)
1455 (ding)
1456 (company-set-selection (+ company-selection pos) t))))
1457
1458 (defun company-search-repeat-forward ()
1459 "Repeat the incremental search in completion candidates forward."
1460 (interactive)
1461 (company-search-assert-enabled)
1462 (let ((pos (company-search company-search-string
1463 (cdr (nthcdr company-selection
1464 company-candidates)))))
1465 (if (null pos)
1466 (ding)
1467 (company-set-selection (+ company-selection pos 1) t))))
1468
1469 (defun company-search-repeat-backward ()
1470 "Repeat the incremental search in completion candidates backwards."
1471 (interactive)
1472 (company-search-assert-enabled)
1473 (let ((pos (company-search company-search-string
1474 (nthcdr (- company-candidates-length
1475 company-selection)
1476 (reverse company-candidates)))))
1477 (if (null pos)
1478 (ding)
1479 (company-set-selection (- company-selection pos 1) t))))
1480
1481 (defun company-create-match-predicate ()
1482 (setq company-candidates-predicate
1483 `(lambda (candidate)
1484 ,(if company-candidates-predicate
1485 `(and (string-match ,company-search-string candidate)
1486 (funcall ,company-candidates-predicate
1487 candidate))
1488 `(string-match ,company-search-string candidate))))
1489 (company-update-candidates
1490 (company-apply-predicate company-candidates company-candidates-predicate))
1491 ;; Invalidate cache.
1492 (setq company-candidates-cache (cons company-prefix company-candidates)))
1493
1494 (defun company-filter-printing-char ()
1495 (interactive)
1496 (company-search-assert-enabled)
1497 (company-search-printing-char)
1498 (company-create-match-predicate)
1499 (company-call-frontends 'update))
1500
1501 (defun company-search-kill-others ()
1502 "Limit the completion candidates to the ones matching the search string."
1503 (interactive)
1504 (company-search-assert-enabled)
1505 (company-create-match-predicate)
1506 (company-search-mode 0)
1507 (company-call-frontends 'update))
1508
1509 (defun company-search-abort ()
1510 "Abort searching the completion candidates."
1511 (interactive)
1512 (company-search-assert-enabled)
1513 (company-set-selection company-search-old-selection t)
1514 (company-search-mode 0))
1515
1516 (defun company-search-other-char ()
1517 (interactive)
1518 (company-search-assert-enabled)
1519 (company-search-mode 0)
1520 (company--unread-last-input))
1521
1522 (defvar company-search-map
1523 (let ((i 0)
1524 (keymap (make-keymap)))
1525 (if (fboundp 'max-char)
1526 (set-char-table-range (nth 1 keymap) (cons #x100 (max-char))
1527 'company-search-printing-char)
1528 (with-no-warnings
1529 ;; obsolete in Emacs 23
1530 (let ((l (generic-character-list))
1531 (table (nth 1 keymap)))
1532 (while l
1533 (set-char-table-default table (car l) 'company-search-printing-char)
1534 (setq l (cdr l))))))
1535 (define-key keymap [t] 'company-search-other-char)
1536 (while (< i ?\s)
1537 (define-key keymap (make-string 1 i) 'company-search-other-char)
1538 (incf i))
1539 (while (< i 256)
1540 (define-key keymap (vector i) 'company-search-printing-char)
1541 (incf i))
1542 (let ((meta-map (make-sparse-keymap)))
1543 (define-key keymap (char-to-string meta-prefix-char) meta-map)
1544 (define-key keymap [escape] meta-map))
1545 (define-key keymap (vector meta-prefix-char t) 'company-search-other-char)
1546 (define-key keymap "\e\e\e" 'company-search-other-char)
1547 (define-key keymap [escape escape escape] 'company-search-other-char)
1548
1549 (define-key keymap "\C-g" 'company-search-abort)
1550 (define-key keymap "\C-s" 'company-search-repeat-forward)
1551 (define-key keymap "\C-r" 'company-search-repeat-backward)
1552 (define-key keymap "\C-o" 'company-search-kill-others)
1553 keymap)
1554 "Keymap used for incrementally searching the completion candidates.")
1555
1556 (define-minor-mode company-search-mode
1557 "Search mode for completion candidates.
1558 Don't start this directly, use `company-search-candidates' or
1559 `company-filter-candidates'."
1560 nil company-search-lighter nil
1561 (if company-search-mode
1562 (if (company-manual-begin)
1563 (progn
1564 (setq company-search-old-selection company-selection)
1565 (company-call-frontends 'update))
1566 (setq company-search-mode nil))
1567 (kill-local-variable 'company-search-string)
1568 (kill-local-variable 'company-search-lighter)
1569 (kill-local-variable 'company-search-old-selection)
1570 (company-enable-overriding-keymap company-active-map)))
1571
1572 (defun company-search-assert-enabled ()
1573 (company-assert-enabled)
1574 (unless company-search-mode
1575 (company-uninstall-map)
1576 (error "Company not in search mode")))
1577
1578 (defun company-search-candidates ()
1579 "Start searching the completion candidates incrementally.
1580
1581 \\<company-search-map>Search can be controlled with the commands:
1582 - `company-search-repeat-forward' (\\[company-search-repeat-forward])
1583 - `company-search-repeat-backward' (\\[company-search-repeat-backward])
1584 - `company-search-abort' (\\[company-search-abort])
1585
1586 Regular characters are appended to the search string.
1587
1588 The command `company-search-kill-others' (\\[company-search-kill-others])
1589 uses the search string to limit the completion candidates."
1590 (interactive)
1591 (company-search-mode 1)
1592 (company-enable-overriding-keymap company-search-map))
1593
1594 (defvar company-filter-map
1595 (let ((keymap (make-keymap)))
1596 (define-key keymap [remap company-search-printing-char]
1597 'company-filter-printing-char)
1598 (set-keymap-parent keymap company-search-map)
1599 keymap)
1600 "Keymap used for incrementally searching the completion candidates.")
1601
1602 (defun company-filter-candidates ()
1603 "Start filtering the completion candidates incrementally.
1604 This works the same way as `company-search-candidates' immediately
1605 followed by `company-search-kill-others' after each input."
1606 (interactive)
1607 (company-search-mode 1)
1608 (company-enable-overriding-keymap company-filter-map))
1609
1610 ;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;
1611
1612 (defun company-select-next ()
1613 "Select the next candidate in the list."
1614 (interactive)
1615 (when (company-manual-begin)
1616 (company-set-selection (1+ company-selection))))
1617
1618 (defun company-select-previous ()
1619 "Select the previous candidate in the list."
1620 (interactive)
1621 (when (company-manual-begin)
1622 (company-set-selection (1- company-selection))))
1623
1624 (defun company-select-next-or-abort ()
1625 "Select the next candidate if more than one, else abort
1626 and invoke the normal binding."
1627 (interactive)
1628 (if (> company-candidates-length 1)
1629 (company-select-next)
1630 (company-abort)
1631 (company--unread-last-input)))
1632
1633 (defun company-select-previous-or-abort ()
1634 "Select the previous candidate if more than one, else abort
1635 and invoke the normal binding."
1636 (interactive)
1637 (if (> company-candidates-length 1)
1638 (company-select-previous)
1639 (company-abort)
1640 (company--unread-last-input)))
1641
1642 (defvar company-pseudo-tooltip-overlay)
1643
1644 (defvar company-tooltip-offset)
1645
1646 (defun company--inside-tooltip-p (event-col-row row height)
1647 (let* ((ovl company-pseudo-tooltip-overlay)
1648 (column (overlay-get ovl 'company-column))
1649 (width (overlay-get ovl 'company-width))
1650 (evt-col (car event-col-row))
1651 (evt-row (cdr event-col-row)))
1652 (and (>= evt-col column)
1653 (< evt-col (+ column width))
1654 (if (> height 0)
1655 (and (> evt-row row)
1656 (<= evt-row (+ row height) ))
1657 (and (< evt-row row)
1658 (>= evt-row (+ row height)))))))
1659
1660 (defun company--event-col-row (event)
1661 (let* ((col-row (posn-actual-col-row (event-start event)))
1662 (col (car col-row))
1663 (row (cdr col-row)))
1664 (incf col (window-hscroll))
1665 (and header-line-format
1666 (version< "24" emacs-version)
1667 (decf row))
1668 (cons col row)))
1669
1670 (defun company-select-mouse (event)
1671 "Select the candidate picked by the mouse."
1672 (interactive "e")
1673 (let ((event-col-row (company--event-col-row event))
1674 (ovl-row (company--row))
1675 (ovl-height (and company-pseudo-tooltip-overlay
1676 (min (overlay-get company-pseudo-tooltip-overlay
1677 'company-height)
1678 company-candidates-length))))
1679 (if (and ovl-height
1680 (company--inside-tooltip-p event-col-row ovl-row ovl-height))
1681 (progn
1682 (company-set-selection (+ (cdr event-col-row)
1683 (1- company-tooltip-offset)
1684 (if (and (eq company-tooltip-offset-display 'lines)
1685 (not (zerop company-tooltip-offset)))
1686 -1 0)
1687 (- ovl-row)
1688 (if (< ovl-height 0)
1689 (- 1 ovl-height)
1690 0)))
1691 t)
1692 (company-abort)
1693 (company--unread-last-input)
1694 nil)))
1695
1696 (defun company-complete-mouse (event)
1697 "Insert the candidate picked by the mouse."
1698 (interactive "e")
1699 (when (company-select-mouse event)
1700 (company-complete-selection)))
1701
1702 (defun company-complete-selection ()
1703 "Insert the selected candidate."
1704 (interactive)
1705 (when (company-manual-begin)
1706 (let ((result (nth company-selection company-candidates)))
1707 (company-finish result))))
1708
1709 (defun company-complete-common ()
1710 "Insert the common part of all candidates."
1711 (interactive)
1712 (when (company-manual-begin)
1713 (if (and (not (cdr company-candidates))
1714 (equal company-common (car company-candidates)))
1715 (company-complete-selection)
1716 (when company-common
1717 (company--insert-candidate company-common)))))
1718
1719 (defun company-complete ()
1720 "Insert the common part of all candidates or the current selection.
1721 The first time this is called, the common part is inserted, the second
1722 time, or when the selection has been changed, the selected candidate is
1723 inserted."
1724 (interactive)
1725 (when (company-manual-begin)
1726 (if (or company-selection-changed
1727 (eq last-command 'company-complete-common))
1728 (call-interactively 'company-complete-selection)
1729 (call-interactively 'company-complete-common)
1730 (setq this-command 'company-complete-common))))
1731
1732 (defun company-complete-number (n)
1733 "Insert the Nth candidate.
1734 To show the number next to the candidates in some back-ends, enable
1735 `company-show-numbers'."
1736 (when (company-manual-begin)
1737 (and (< n 1) (> n company-candidates-length)
1738 (error "No candidate number %d" n))
1739 (decf n)
1740 (company-finish (nth n company-candidates))))
1741
1742 ;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;
1743
1744 (defconst company-space-strings-limit 100)
1745
1746 (defconst company-space-strings
1747 (let (lst)
1748 (dotimes (i company-space-strings-limit)
1749 (push (make-string (- company-space-strings-limit 1 i) ?\ ) lst))
1750 (apply 'vector lst)))
1751
1752 (defun company-space-string (len)
1753 (if (< len company-space-strings-limit)
1754 (aref company-space-strings len)
1755 (make-string len ?\ )))
1756
1757 (defun company-safe-substring (str from &optional to)
1758 (if (> from (string-width str))
1759 ""
1760 (with-temp-buffer
1761 (insert str)
1762 (move-to-column from)
1763 (let ((beg (point)))
1764 (if to
1765 (progn
1766 (move-to-column to)
1767 (concat (buffer-substring beg (point))
1768 (let ((padding (- to (current-column))))
1769 (when (> padding 0)
1770 (company-space-string padding)))))
1771 (buffer-substring beg (point-max)))))))
1772
1773 ;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;
1774
1775 (defvar company-last-metadata nil)
1776 (make-variable-buffer-local 'company-last-metadata)
1777
1778 (defun company-fetch-metadata ()
1779 (let ((selected (nth company-selection company-candidates)))
1780 (unless (eq selected (car company-last-metadata))
1781 (setq company-last-metadata
1782 (cons selected (company-call-backend 'meta selected))))
1783 (cdr company-last-metadata)))
1784
1785 (defun company-doc-buffer (&optional string)
1786 (with-current-buffer (get-buffer-create "*company-documentation*")
1787 (erase-buffer)
1788 (when string
1789 (save-excursion
1790 (insert string)))
1791 (current-buffer)))
1792
1793 (defvar company--electric-commands
1794 '(scroll-other-window scroll-other-window-down)
1795 "List of Commands that won't break out of electric commands.")
1796
1797 (defmacro company--electric-do (&rest body)
1798 (declare (indent 0) (debug t))
1799 `(when (company-manual-begin)
1800 (save-window-excursion
1801 (let ((height (window-height))
1802 (row (company--row))
1803 cmd)
1804 ,@body
1805 (and (< (window-height) height)
1806 (< (- (window-height) row 2) company-tooltip-limit)
1807 (recenter (- (window-height) row 2)))
1808 (while (memq (setq cmd (key-binding (vector (list (read-event)))))
1809 company--electric-commands)
1810 (call-interactively cmd))
1811 (company--unread-last-input)))))
1812
1813 (defun company--unread-last-input ()
1814 (when last-input-event
1815 (clear-this-command-keys t)
1816 (setq unread-command-events (list last-input-event))))
1817
1818 (defun company-show-doc-buffer ()
1819 "Temporarily show the documentation buffer for the selection."
1820 (interactive)
1821 (company--electric-do
1822 (let* ((selected (nth company-selection company-candidates))
1823 (doc-buffer (or (company-call-backend 'doc-buffer selected)
1824 (error "No documentation available"))))
1825 (with-current-buffer doc-buffer
1826 (goto-char (point-min)))
1827 (display-buffer doc-buffer t))))
1828 (put 'company-show-doc-buffer 'company-keep t)
1829
1830 (defun company-show-location ()
1831 "Temporarily display a buffer showing the selected candidate in context."
1832 (interactive)
1833 (company--electric-do
1834 (let* ((selected (nth company-selection company-candidates))
1835 (location (company-call-backend 'location selected))
1836 (pos (or (cdr location) (error "No location available")))
1837 (buffer (or (and (bufferp (car location)) (car location))
1838 (find-file-noselect (car location) t))))
1839 (with-selected-window (display-buffer buffer t)
1840 (save-restriction
1841 (widen)
1842 (if (bufferp (car location))
1843 (goto-char pos)
1844 (goto-char (point-min))
1845 (forward-line (1- pos))))
1846 (set-window-start nil (point))))))
1847 (put 'company-show-location 'company-keep t)
1848
1849 ;;; package functions ;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;
1850
1851 (defvar company-callback nil)
1852 (make-variable-buffer-local 'company-callback)
1853
1854 (defun company-remove-callback (&optional ignored)
1855 (remove-hook 'company-completion-finished-hook company-callback t)
1856 (remove-hook 'company-completion-cancelled-hook 'company-remove-callback t)
1857 (remove-hook 'company-completion-finished-hook 'company-remove-callback t))
1858
1859 (defun company-begin-backend (backend &optional callback)
1860 "Start a completion at point using BACKEND."
1861 (interactive (let ((val (completing-read "Company back-end: "
1862 obarray
1863 'functionp nil "company-")))
1864 (when val
1865 (list (intern val)))))
1866 (when (setq company-callback callback)
1867 (add-hook 'company-completion-finished-hook company-callback nil t))
1868 (add-hook 'company-completion-cancelled-hook 'company-remove-callback nil t)
1869 (add-hook 'company-completion-finished-hook 'company-remove-callback nil t)
1870 (setq company-backend backend)
1871 ;; Return non-nil if active.
1872 (or (company-manual-begin)
1873 (error "Cannot complete at point")))
1874
1875 (defun company-begin-with (candidates
1876 &optional prefix-length require-match callback)
1877 "Start a completion at point.
1878 CANDIDATES is the list of candidates to use and PREFIX-LENGTH is the length
1879 of the prefix that already is in the buffer before point.
1880 It defaults to 0.
1881
1882 CALLBACK is a function called with the selected result if the user
1883 successfully completes the input.
1884
1885 Example: \(company-begin-with '\(\"foo\" \"foobar\" \"foobarbaz\"\)\)"
1886 (let ((begin-marker (copy-marker (point) t)))
1887 (company-begin-backend
1888 (lambda (command &optional arg &rest ignored)
1889 (pcase command
1890 (`prefix
1891 (when (equal (point) (marker-position begin-marker))
1892 (buffer-substring (- (point) (or prefix-length 0)) (point))))
1893 (`candidates
1894 (all-completions arg candidates))
1895 (`require-match
1896 require-match)))
1897 callback)))
1898
1899 (defun company-version (&optional show-version)
1900 "Get the Company version as string.
1901
1902 If SHOW-VERSION is non-nil, show the version in the echo area."
1903 (interactive (list t))
1904 (with-temp-buffer
1905 (insert-file-contents (find-library-name "company"))
1906 (require 'lisp-mnt)
1907 (if show-version
1908 (message "Company version: %s" (lm-version))
1909 (lm-version))))
1910
1911 ;;; pseudo-tooltip ;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;
1912
1913 (defvar company-pseudo-tooltip-overlay nil)
1914 (make-variable-buffer-local 'company-pseudo-tooltip-overlay)
1915
1916 (defvar company-tooltip-offset 0)
1917 (make-variable-buffer-local 'company-tooltip-offset)
1918
1919 (defun company-tooltip--lines-update-offset (selection num-lines limit)
1920 (decf limit 2)
1921 (setq company-tooltip-offset
1922 (max (min selection company-tooltip-offset)
1923 (- selection -1 limit)))
1924
1925 (when (<= company-tooltip-offset 1)
1926 (incf limit)
1927 (setq company-tooltip-offset 0))
1928
1929 (when (>= company-tooltip-offset (- num-lines limit 1))
1930 (incf limit)
1931 (when (= selection (1- num-lines))
1932 (decf company-tooltip-offset)
1933 (when (<= company-tooltip-offset 1)
1934 (setq company-tooltip-offset 0)
1935 (incf limit))))
1936
1937 limit)
1938
1939 (defun company-tooltip--simple-update-offset (selection num-lines limit)
1940 (setq company-tooltip-offset
1941 (if (< selection company-tooltip-offset)
1942 selection
1943 (max company-tooltip-offset
1944 (- selection limit -1)))))
1945
1946 ;;; propertize
1947
1948 (defsubst company-round-tab (arg)
1949 (* (/ (+ arg tab-width) tab-width) tab-width))
1950
1951 (defun company-plainify (str)
1952 (let ((prefix (get-text-property 0 'line-prefix str)))
1953 (when prefix ; Keep the original value unmodified, for no special reason.
1954 (setq str (concat prefix str))
1955 (remove-text-properties 0 (length str) '(line-prefix) str)))
1956 (let* ((pieces (split-string str "\t"))
1957 (copy pieces))
1958 (while (cdr copy)
1959 (setcar copy (company-safe-substring
1960 (car copy) 0 (company-round-tab (string-width (car copy)))))
1961 (pop copy))
1962 (apply 'concat pieces)))
1963
1964 (defun company-fill-propertize (value annotation width selected left right)
1965 (let* ((margin (length left))
1966 (common (+ (or (company-call-backend 'match value)
1967 (length company-common)) margin))
1968 (ann-ralign company-tooltip-align-annotations)
1969 (ann-truncate (< width
1970 (+ (length value) (length annotation)
1971 (if ann-ralign 1 0))))
1972 (ann-start (+ margin
1973 (if ann-ralign
1974 (if ann-truncate
1975 (1+ (length value))
1976 (- width (length annotation)))
1977 (length value))))
1978 (ann-end (min (+ ann-start (length annotation)) (+ margin width)))
1979 (line (concat left
1980 (if (or ann-truncate (not ann-ralign))
1981 (company-safe-substring
1982 (concat value
1983 (when (and annotation ann-ralign) " ")
1984 annotation)
1985 0 width)
1986 (concat
1987 (company-safe-substring value 0
1988 (- width (length annotation)))
1989 annotation))
1990 right)))
1991 (setq width (+ width margin (length right)))
1992
1993 (add-text-properties 0 width '(face company-tooltip
1994 mouse-face company-tooltip-mouse)
1995 line)
1996 (add-text-properties margin common
1997 '(face company-tooltip-common
1998 mouse-face company-tooltip-mouse)
1999 line)
2000 (when (< ann-start ann-end)
2001 (add-text-properties ann-start ann-end
2002 '(face company-tooltip-annotation
2003 mouse-face company-tooltip-mouse)
2004 line))
2005 (when selected
2006 (if (and company-search-string
2007 (string-match (regexp-quote company-search-string) value
2008 (length company-prefix)))
2009 (let ((beg (+ margin (match-beginning 0)))
2010 (end (+ margin (match-end 0))))
2011 (add-text-properties beg end '(face company-tooltip-selection)
2012 line)
2013 (when (< beg common)
2014 (add-text-properties beg common
2015 '(face company-tooltip-common-selection)
2016 line)))
2017 (add-text-properties 0 width '(face company-tooltip-selection
2018 mouse-face company-tooltip-selection)
2019 line)
2020 (add-text-properties margin common
2021 '(face company-tooltip-common-selection
2022 mouse-face company-tooltip-selection)
2023 line)))
2024 line))
2025
2026 ;;; replace
2027
2028 (defun company-buffer-lines (beg end)
2029 (goto-char beg)
2030 (let (lines)
2031 (while (and (= 1 (vertical-motion 1))
2032 (<= (point) end))
2033 (let ((bound (min end (1- (point)))))
2034 ;; A visual line can contain several physical lines (e.g. with outline's
2035 ;; folding overlay). Take only the first one.
2036 (push (buffer-substring beg
2037 (save-excursion
2038 (goto-char beg)
2039 (re-search-forward "$" bound 'move)
2040 (point)))
2041 lines))
2042 (setq beg (point)))
2043 (unless (eq beg end)
2044 (push (buffer-substring beg end) lines))
2045 (nreverse lines)))
2046
2047 (defun company-modify-line (old new offset)
2048 (concat (company-safe-substring old 0 offset)
2049 new
2050 (company-safe-substring old (+ offset (length new)))))
2051
2052 (defsubst company--length-limit (lst limit)
2053 (if (nthcdr limit lst)
2054 limit
2055 (length lst)))
2056
2057 (defun company--replacement-string (lines old column nl &optional align-top)
2058 (decf column company-tooltip-margin)
2059
2060 (let ((width (length (car lines)))
2061 (remaining-cols (- (+ (company--window-width) (window-hscroll))
2062 column)))
2063 (when (> width remaining-cols)
2064 (decf column (- width remaining-cols))))
2065
2066 (let ((offset (and (< column 0) (- column)))
2067 new)
2068 (when offset
2069 (setq column 0))
2070 (when align-top
2071 ;; untouched lines first
2072 (dotimes (_ (- (length old) (length lines)))
2073 (push (pop old) new)))
2074 ;; length into old lines.
2075 (while old
2076 (push (company-modify-line (pop old)
2077 (company--offset-line (pop lines) offset)
2078 column) new))
2079 ;; Append whole new lines.
2080 (while lines
2081 (push (concat (company-space-string column)
2082 (company--offset-line (pop lines) offset))
2083 new))
2084
2085 (let ((str (concat (when nl "\n")
2086 (mapconcat 'identity (nreverse new) "\n")
2087 "\n")))
2088 (font-lock-append-text-property 0 (length str) 'face 'default str)
2089 str)))
2090
2091 (defun company--offset-line (line offset)
2092 (if (and offset line)
2093 (substring line offset)
2094 line))
2095
2096 (defun company--create-lines (selection limit)
2097 (let ((len company-candidates-length)
2098 (numbered 99999)
2099 (window-width (company--window-width))
2100 lines
2101 width
2102 lines-copy
2103 items
2104 previous
2105 remainder
2106 scrollbar-bounds)
2107
2108 ;; Maybe clear old offset.
2109 (when (< len (+ company-tooltip-offset limit))
2110 (setq company-tooltip-offset 0))
2111
2112 ;; Scroll to offset.
2113 (if (eq company-tooltip-offset-display 'lines)
2114 (setq limit (company-tooltip--lines-update-offset selection len limit))
2115 (company-tooltip--simple-update-offset selection len limit))
2116
2117 (cond
2118 ((eq company-tooltip-offset-display 'scrollbar)
2119 (setq scrollbar-bounds (company--scrollbar-bounds company-tooltip-offset
2120 limit len)))
2121 ((eq company-tooltip-offset-display 'lines)
2122 (when (> company-tooltip-offset 0)
2123 (setq previous (format "...(%d)" company-tooltip-offset)))
2124 (setq remainder (- len limit company-tooltip-offset)
2125 remainder (when (> remainder 0)
2126 (setq remainder (format "...(%d)" remainder))))))
2127
2128 (decf selection company-tooltip-offset)
2129 (setq width (max (length previous) (length remainder))
2130 lines (nthcdr company-tooltip-offset company-candidates)
2131 len (min limit len)
2132 lines-copy lines)
2133
2134 (decf window-width (* 2 company-tooltip-margin))
2135 (when scrollbar-bounds (decf window-width))
2136
2137 (dotimes (_ len)
2138 (let* ((value (pop lines-copy))
2139 (annotation (company-call-backend 'annotation value)))
2140 (when (and annotation company-tooltip-align-annotations)
2141 ;; `lisp-completion-at-point' adds a space.
2142 (setq annotation (comment-string-strip annotation t nil)))
2143 (push (cons value annotation) items)
2144 (setq width (max (+ (length value)
2145 (if (and annotation company-tooltip-align-annotations)
2146 (1+ (length annotation))
2147 (length annotation)))
2148 width))))
2149
2150 (setq width (min window-width
2151 (if (and company-show-numbers
2152 (< company-tooltip-offset 10))
2153 (+ 2 width)
2154 width)))
2155
2156 ;; number can make tooltip too long
2157 (when company-show-numbers
2158 (setq numbered company-tooltip-offset))
2159
2160 (let ((items (nreverse items)) new)
2161 (when previous
2162 (push (company--scrollpos-line previous width) new))
2163
2164 (dotimes (i len)
2165 (let* ((item (pop items))
2166 (str (company-reformat (car item)))
2167 (annotation (cdr item))
2168 (right (company-space-string company-tooltip-margin))
2169 (width width))
2170 (when (< numbered 10)
2171 (decf width 2)
2172 (incf numbered)
2173 (setq right (concat (format " %d" (mod numbered 10)) right)))
2174 (push (concat
2175 (company-fill-propertize str annotation
2176 width (equal i selection)
2177 (company-space-string
2178 company-tooltip-margin)
2179 right)
2180 (when scrollbar-bounds
2181 (company--scrollbar i scrollbar-bounds)))
2182 new)))
2183
2184 (when remainder
2185 (push (company--scrollpos-line remainder width) new))
2186
2187 (nreverse new))))
2188
2189 (defun company--scrollbar-bounds (offset limit length)
2190 (when (> length limit)
2191 (let* ((size (ceiling (* limit (float limit)) length))
2192 (lower (floor (* limit (float offset)) length))
2193 (upper (+ lower size -1)))
2194 (cons lower upper))))
2195
2196 (defun company--scrollbar (i bounds)
2197 (propertize " " 'face
2198 (if (and (>= i (car bounds)) (<= i (cdr bounds)))
2199 'company-scrollbar-fg
2200 'company-scrollbar-bg)))
2201
2202 (defun company--scrollpos-line (text width)
2203 (propertize (concat (company-space-string company-tooltip-margin)
2204 (company-safe-substring text 0 width)
2205 (company-space-string company-tooltip-margin))
2206 'face 'company-tooltip))
2207
2208 ;; show
2209
2210 (defsubst company--window-inner-height ()
2211 (let ((edges (window-inside-edges)))
2212 (- (nth 3 edges) (nth 1 edges))))
2213
2214 (defsubst company--window-width ()
2215 (- (window-width)
2216 (cond
2217 ((display-graphic-p) 0)
2218 ;; Account for the line continuation column.
2219 ((version< "24.3.1" emacs-version) 1)
2220 ;; Emacs 24.3 and earlier included margins
2221 ;; in window-width when in TTY.
2222 (t (1+ (let ((margins (window-margins)))
2223 (+ (or (car margins) 0)
2224 (or (cdr margins) 0))))))))
2225
2226 (defun company--pseudo-tooltip-height ()
2227 "Calculate the appropriate tooltip height.
2228 Returns a negative number if the tooltip should be displayed above point."
2229 (let* ((lines (company--row))
2230 (below (- (company--window-inner-height) 1 lines)))
2231 (if (and (< below (min company-tooltip-minimum company-candidates-length))
2232 (> lines below))
2233 (- (max 3 (min company-tooltip-limit lines)))
2234 (max 3 (min company-tooltip-limit below)))))
2235
2236 (defun company-pseudo-tooltip-show (row column selection)
2237 (company-pseudo-tooltip-hide)
2238 (save-excursion
2239
2240 (let* ((height (company--pseudo-tooltip-height))
2241 above)
2242
2243 (when (< height 0)
2244 (setq row (+ row height -1)
2245 above t))
2246
2247 (let* ((nl (< (move-to-window-line row) row))
2248 (beg (point))
2249 (end (save-excursion
2250 (move-to-window-line (+ row (abs height)))
2251 (point)))
2252 (ov (make-overlay beg end))
2253 (args (list (mapcar 'company-plainify
2254 (company-buffer-lines beg end))
2255 column nl above)))
2256
2257 (setq company-pseudo-tooltip-overlay ov)
2258 (overlay-put ov 'company-replacement-args args)
2259
2260 (let ((lines (company--create-lines selection (abs height))))
2261 (overlay-put ov 'company-after
2262 (apply 'company--replacement-string lines args))
2263 (overlay-put ov 'company-width (string-width (car lines))))
2264
2265 (overlay-put ov 'company-column column)
2266 (overlay-put ov 'company-height height)))))
2267
2268 (defun company-pseudo-tooltip-show-at-point (pos)
2269 (let ((row (company--row pos))
2270 (col (company--column pos)))
2271 (company-pseudo-tooltip-show (1+ row) col company-selection)))
2272
2273 (defun company-pseudo-tooltip-edit (selection)
2274 (let ((height (overlay-get company-pseudo-tooltip-overlay 'company-height)))
2275 (overlay-put company-pseudo-tooltip-overlay 'company-after
2276 (apply 'company--replacement-string
2277 (company--create-lines selection (abs height))
2278 (overlay-get company-pseudo-tooltip-overlay
2279 'company-replacement-args)))))
2280
2281 (defun company-pseudo-tooltip-hide ()
2282 (when company-pseudo-tooltip-overlay
2283 (delete-overlay company-pseudo-tooltip-overlay)
2284 (setq company-pseudo-tooltip-overlay nil)))
2285
2286 (defun company-pseudo-tooltip-hide-temporarily ()
2287 (when (overlayp company-pseudo-tooltip-overlay)
2288 (overlay-put company-pseudo-tooltip-overlay 'invisible nil)
2289 (overlay-put company-pseudo-tooltip-overlay 'line-prefix nil)
2290 (overlay-put company-pseudo-tooltip-overlay 'after-string nil)))
2291
2292 (defun company-pseudo-tooltip-unhide ()
2293 (when company-pseudo-tooltip-overlay
2294 (overlay-put company-pseudo-tooltip-overlay 'invisible t)
2295 ;; Beat outline's folding overlays, at least.
2296 (overlay-put company-pseudo-tooltip-overlay 'priority 1)
2297 ;; No (extra) prefix for the first line.
2298 (overlay-put company-pseudo-tooltip-overlay 'line-prefix "")
2299 (overlay-put company-pseudo-tooltip-overlay 'after-string
2300 (overlay-get company-pseudo-tooltip-overlay 'company-after))
2301 (overlay-put company-pseudo-tooltip-overlay 'window (selected-window))))
2302
2303 (defun company-pseudo-tooltip-guard ()
2304 (buffer-substring-no-properties
2305 (point) (overlay-start company-pseudo-tooltip-overlay)))
2306
2307 (defun company-pseudo-tooltip-frontend (command)
2308 "`company-mode' front-end similar to a tooltip but based on overlays."
2309 (case command
2310 (pre-command (company-pseudo-tooltip-hide-temporarily))
2311 (post-command
2312 (let ((old-height (if (overlayp company-pseudo-tooltip-overlay)
2313 (overlay-get company-pseudo-tooltip-overlay
2314 'company-height)
2315 0))
2316 (new-height (company--pseudo-tooltip-height)))
2317 (unless (and (>= (* old-height new-height) 0)
2318 (>= (abs old-height) (abs new-height))
2319 (equal (company-pseudo-tooltip-guard)
2320 (overlay-get company-pseudo-tooltip-overlay
2321 'company-guard)))
2322 ;; Redraw needed.
2323 (company-pseudo-tooltip-show-at-point (- (point)
2324 (length company-prefix)))
2325 (overlay-put company-pseudo-tooltip-overlay
2326 'company-guard (company-pseudo-tooltip-guard))))
2327 (company-pseudo-tooltip-unhide))
2328 (hide (company-pseudo-tooltip-hide)
2329 (setq company-tooltip-offset 0))
2330 (update (when (overlayp company-pseudo-tooltip-overlay)
2331 (company-pseudo-tooltip-edit company-selection)))))
2332
2333 (defun company-pseudo-tooltip-unless-just-one-frontend (command)
2334 "`company-pseudo-tooltip-frontend', but not shown for single candidates."
2335 (unless (and (eq command 'post-command)
2336 (company--show-inline-p))
2337 (company-pseudo-tooltip-frontend command)))
2338
2339 ;;; overlay ;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;
2340
2341 (defvar company-preview-overlay nil)
2342 (make-variable-buffer-local 'company-preview-overlay)
2343
2344 (defun company-preview-show-at-point (pos)
2345 (company-preview-hide)
2346
2347 (setq company-preview-overlay (make-overlay pos (1+ pos)))
2348
2349 (let ((completion (nth company-selection company-candidates)))
2350 (setq completion (propertize completion 'face 'company-preview))
2351 (add-text-properties 0 (length company-common)
2352 '(face company-preview-common) completion)
2353
2354 ;; Add search string
2355 (and company-search-string
2356 (string-match (regexp-quote company-search-string) completion)
2357 (add-text-properties (match-beginning 0)
2358 (match-end 0)
2359 '(face company-preview-search)
2360 completion))
2361
2362 (setq completion (company-strip-prefix completion))
2363
2364 (and (equal pos (point))
2365 (not (equal completion ""))
2366 (add-text-properties 0 1 '(cursor t) completion))
2367
2368 (overlay-put company-preview-overlay 'display
2369 (concat completion (unless (eq pos (point-max))
2370 (buffer-substring pos (1+ pos)))))
2371 (overlay-put company-preview-overlay 'window (selected-window))))
2372
2373 (defun company-preview-hide ()
2374 (when company-preview-overlay
2375 (delete-overlay company-preview-overlay)
2376 (setq company-preview-overlay nil)))
2377
2378 (defun company-preview-frontend (command)
2379 "`company-mode' front-end showing the selection as if it had been inserted."
2380 (pcase command
2381 (`pre-command (company-preview-hide))
2382 (`post-command (company-preview-show-at-point (point)))
2383 (`hide (company-preview-hide))))
2384
2385 (defun company-preview-if-just-one-frontend (command)
2386 "`company-preview-frontend', but only shown for single candidates."
2387 (when (or (not (eq command 'post-command))
2388 (company--show-inline-p))
2389 (company-preview-frontend command)))
2390
2391 (defun company--show-inline-p ()
2392 (and (not (cdr company-candidates))
2393 company-common
2394 (string-prefix-p company-prefix company-common
2395 (company-call-backend 'ignore-case))))
2396
2397 ;;; echo ;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;
2398
2399 (defvar company-echo-last-msg nil)
2400 (make-variable-buffer-local 'company-echo-last-msg)
2401
2402 (defvar company-echo-timer nil)
2403
2404 (defvar company-echo-delay .01)
2405
2406 (defun company-echo-show (&optional getter)
2407 (when getter
2408 (setq company-echo-last-msg (funcall getter)))
2409 (let ((message-log-max nil))
2410 (if company-echo-last-msg
2411 (message "%s" company-echo-last-msg)
2412 (message ""))))
2413
2414 (defun company-echo-show-soon (&optional getter)
2415 (when company-echo-timer
2416 (cancel-timer company-echo-timer))
2417 (setq company-echo-timer (run-with-timer 0 nil 'company-echo-show getter)))
2418
2419 (defsubst company-echo-show-when-idle (&optional getter)
2420 (when (sit-for company-echo-delay)
2421 (company-echo-show getter)))
2422
2423 (defun company-echo-format ()
2424
2425 (let ((limit (window-width (minibuffer-window)))
2426 (len -1)
2427 ;; Roll to selection.
2428 (candidates (nthcdr company-selection company-candidates))
2429 (i (if company-show-numbers company-selection 99999))
2430 comp msg)
2431
2432 (while candidates
2433 (setq comp (company-reformat (pop candidates))
2434 len (+ len 1 (length comp)))
2435 (if (< i 10)
2436 ;; Add number.
2437 (progn
2438 (setq comp (propertize (format "%d: %s" i comp)
2439 'face 'company-echo))
2440 (incf len 3)
2441 (incf i)
2442 (add-text-properties 3 (+ 3 (length company-common))
2443 '(face company-echo-common) comp))
2444 (setq comp (propertize comp 'face 'company-echo))
2445 (add-text-properties 0 (length company-common)
2446 '(face company-echo-common) comp))
2447 (if (>= len limit)
2448 (setq candidates nil)
2449 (push comp msg)))
2450
2451 (mapconcat 'identity (nreverse msg) " ")))
2452
2453 (defun company-echo-strip-common-format ()
2454
2455 (let ((limit (window-width (minibuffer-window)))
2456 (len (+ (length company-prefix) 2))
2457 ;; Roll to selection.
2458 (candidates (nthcdr company-selection company-candidates))
2459 (i (if company-show-numbers company-selection 99999))
2460 msg comp)
2461
2462 (while candidates
2463 (setq comp (company-strip-prefix (pop candidates))
2464 len (+ len 2 (length comp)))
2465 (when (< i 10)
2466 ;; Add number.
2467 (setq comp (format "%s (%d)" comp i))
2468 (incf len 4)
2469 (incf i))
2470 (if (>= len limit)
2471 (setq candidates nil)
2472 (push (propertize comp 'face 'company-echo) msg)))
2473
2474 (concat (propertize company-prefix 'face 'company-echo-common) "{"
2475 (mapconcat 'identity (nreverse msg) ", ")
2476 "}")))
2477
2478 (defun company-echo-hide ()
2479 (unless (equal company-echo-last-msg "")
2480 (setq company-echo-last-msg "")
2481 (company-echo-show)))
2482
2483 (defun company-echo-frontend (command)
2484 "`company-mode' front-end showing the candidates in the echo area."
2485 (pcase command
2486 (`post-command (company-echo-show-soon 'company-echo-format))
2487 (`hide (company-echo-hide))))
2488
2489 (defun company-echo-strip-common-frontend (command)
2490 "`company-mode' front-end showing the candidates in the echo area."
2491 (pcase command
2492 (`post-command (company-echo-show-soon 'company-echo-strip-common-format))
2493 (`hide (company-echo-hide))))
2494
2495 (defun company-echo-metadata-frontend (command)
2496 "`company-mode' front-end showing the documentation in the echo area."
2497 (pcase command
2498 (`post-command (company-echo-show-when-idle 'company-fetch-metadata))
2499 (`hide (company-echo-hide))))
2500
2501 (provide 'company)
2502 ;;; company.el ends here