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