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