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