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