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