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