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