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