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