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