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