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