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