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