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