1 " Vim completion script
3 " Maintainer: Mark Guzman <segfault@hasno.info>
4 " Info: $Id: rubycomplete.vim,v 1.41 2008/06/30 06:50:45 segy Exp $
5 " URL: http://vim-ruby.rubyforge.org
6 " Anon CVS: See above site
7 " Release Coordinator: Doug Kearns <dougkearns@gmail.com>
8 " Maintainer Version: 0.8
9 " ----------------------------------------------------------------------------
11 " Ruby IRB/Complete author: Keiju ISHITSUKA(keiju@ishitsuka.com)
12 " ----------------------------------------------------------------------------
14 " {{{ requirement checks
16 s:ErrMsg( "Error: Rubycomplete requires vim compiled with +ruby" )
17 s:ErrMsg( "Error: falling back to syntax completion" )
18 " lets fall back to syntax completion
19 setlocal omnifunc=syntaxcomplete#Complete
24 s:ErrMsg( "Error: Required vim >= 7.0" )
27 " }}} requirement checks
29 " {{{ configuration failsafe initialization
30 if !exists("g:rubycomplete_rails")
31 let g:rubycomplete_rails = 0
34 if !exists("g:rubycomplete_classes_in_global")
35 let g:rubycomplete_classes_in_global = 0
38 if !exists("g:rubycomplete_buffer_loading")
39 let g:rubycomplete_buffer_loading = 0
42 if !exists("g:rubycomplete_include_object")
43 let g:rubycomplete_include_object = 0
46 if !exists("g:rubycomplete_include_objectspace")
47 let g:rubycomplete_include_objectspace = 0
49 " }}} configuration failsafe initialization
51 " {{{ vim-side support functions
52 let s:rubycomplete_debug = 0
54 function! s:ErrMsg(msg)
60 function! s:dprint(msg)
61 if s:rubycomplete_debug == 1
66 function! s:GetBufferRubyModule(name, ...)
68 let [snum,enum] = s:GetBufferRubyEntity(a:name, "module", a:1)
70 let [snum,enum] = s:GetBufferRubyEntity(a:name, "module")
72 return snum . '..' . enum
75 function! s:GetBufferRubyClass(name, ...)
77 let [snum,enum] = s:GetBufferRubyEntity(a:name, "class", a:1)
79 let [snum,enum] = s:GetBufferRubyEntity(a:name, "class")
81 return snum . '..' . enum
84 function! s:GetBufferRubySingletonMethods(name)
87 function! s:GetBufferRubyEntity( name, type, ... )
88 let lastpos = getpos(".")
89 let lastline = lastpos
91 let lastline = [ 0, a:1, 0, 0 ]
97 let crex = '^\s*\<' . a:type . '\>\s*\<' . a:name . '\>\s*\(<\s*.*\s*\)\?'
98 let [lnum,lcol] = searchpos( crex, 'w' )
99 "let [lnum,lcol] = searchpairpos( crex . '\zs', '', '\(end\|}\)', 'w' )
101 if lnum == 0 && lcol == 0
102 call cursor(lastpos[1], lastpos[2])
106 let curpos = getpos(".")
107 let [enum,ecol] = searchpairpos( crex, '', '\(end\|}\)', 'wr' )
108 call cursor(lastpos[1], lastpos[2])
113 " we found a the class def
117 function! s:IsInClassDef()
118 return s:IsPosInClassDef( line('.') )
121 function! s:IsPosInClassDef(pos)
122 let [snum,enum] = s:GetBufferRubyEntity( '.*', "class" )
125 if snum < a:pos && a:pos < enum
126 let ret = snum . '..' . enum
132 function! s:GetRubyVarType(v)
135 let pos = getpos('.')
136 let sstr = '^\s*#\s*@var\s*'.a:v.'\>\s\+[^ \t]\+\s*$'
137 let [lnum,lcol] = searchpos(sstr,'nb',stopline)
138 if lnum != 0 && lcol != 0
140 let str = getline(lnum)
141 let vtp = substitute(str,sstr,'\1','')
145 let ctors = '\(now\|new\|open\|get_instance'
146 if exists('g:rubycomplete_rails') && g:rubycomplete_rails == 1 && s:rubycomplete_rails_loaded == 1
147 let ctors = ctors.'\|find\|create'
150 let ctors = ctors.'\)'
152 let fstr = '=\s*\([^ \t]\+.' . ctors .'\>\|[\[{"''/]\|%[xwQqr][(\[{@]\|[A-Za-z0-9@:\-()\.]\+...\?\|lambda\|&\)'
153 let sstr = ''.a:v.'\>\s*[+\-*/]*'.fstr
154 let [lnum,lcol] = searchpos(sstr,'nb',stopline)
155 if lnum != 0 && lcol != 0
156 let str = matchstr(getline(lnum),fstr,lcol)
157 let str = substitute(str,'^=\s*','','')
160 if str == '"' || str == '''' || stridx(tolower(str), '%q[') != -1
162 elseif str == '[' || stridx(str, '%w[') != -1
166 elseif str == '/' || str == '%r{'
168 elseif strlen(str) >= 4 && stridx(str,'..') != -1
170 elseif stridx(str, 'lambda') != -1 || str == '&'
172 elseif strlen(str) > 4
173 let l = stridx(str,'.')
182 "}}} vim-side support functions
184 "{{{ vim-side completion function
185 function! rubycomplete#Init()
186 execute "ruby VimRubyCompletion.preload_rails"
189 function! rubycomplete#Complete(findstart, base)
190 "findstart = 1 when we need to get the text length
192 let line = getline('.')
208 "findstart = 0 when we need to return the list of completions
210 let g:rubycomplete_completions = []
211 execute "ruby VimRubyCompletion.get_completions('" . a:base . "')"
212 return g:rubycomplete_completions
215 "}}} vim-side completion function
218 function! s:DefRuby()
220 # {{{ ruby completion
223 require 'rubygems' # let's assume this is safe...?
227 class VimRubyCompletion
235 "def", "defined", "do",
236 "else", "elsif", "end", "ensure",
240 "next", "nil", "not",
242 "redo", "rescue", "retry", "return",
245 "undef", "unless", "until",
250 @@Operators = [ "%", "&", "*", "**", "+", "-", "/",
251 "<", "<<", "<=", "<=>", "==", "===", "=~", ">", ">=", ">>",
255 # {{{ buffer analysis magic
257 buf = VIM::Buffer.current
258 enum = buf.line_number
259 nums = Range.new( 1, enum )
263 eval( "require %s" % $1 ) if /.*require\s*(.*)$/.match( ln )
270 def load_buffer_class(name)
271 dprint "load_buffer_class(%s) START" % name
272 classdef = get_buffer_entity(name, 's:GetBufferRubyClass("%s")')
273 return if classdef == nil
275 pare = /^\s*class\s*(.*)\s*<\s*(.*)\s*\n/.match( classdef )
276 load_buffer_class( $2 ) if pare != nil && $2 != name # load parent class if needed
278 mixre = /.*\n\s*include\s*(.*)\s*\n/.match( classdef )
279 load_buffer_module( $2 ) if mixre != nil && $2 != name # load mixins if needed
284 VIM::evaluate( "s:ErrMsg( 'Problem loading class \"%s\", was it already completed?' )" % name )
286 dprint "load_buffer_class(%s) END" % name
289 def load_buffer_module(name)
290 dprint "load_buffer_module(%s) START" % name
291 classdef = get_buffer_entity(name, 's:GetBufferRubyModule("%s")')
292 return if classdef == nil
297 VIM::evaluate( "s:ErrMsg( 'Problem loading module \"%s\", was it already completed?' )" % name )
299 dprint "load_buffer_module(%s) END" % name
302 def get_buffer_entity(name, vimfun)
303 loading_allowed = VIM::evaluate("exists('g:rubycomplete_buffer_loading') && g:rubycomplete_buffer_loading")
304 return nil if loading_allowed.to_i.zero?
305 return nil if /(\"|\')+/.match( name )
306 buf = VIM::Buffer.current
307 nums = eval( VIM::evaluate( vimfun % name ) )
308 return nil if nums == nil
309 return nil if nums.min == nums.max && nums.min == 0
311 dprint "get_buffer_entity START"
314 bufname = VIM::Buffer.current.name
316 cur_line = VIM::Buffer.current.line_number
317 while (nums != nil && !(nums.min == 0 && nums.max == 0) )
318 dprint "visited: %s" % visited.to_s
319 break if visited.index( nums )
326 if /^\s*(module|class|def|include)\s+/.match(ln)
327 clscnt += 1 if $1 == "class"
328 #dprint "\$1: %s" % $1
329 classdef += "%s\n" % ln
330 classdef += "end\n" if /def\s+/.match(ln)
336 nm = "%s(::.*)*\", %s, \"" % [ name, nums.last ]
337 nums = eval( VIM::evaluate( vimfun % nm ) )
338 dprint "nm: \"%s\"" % nm
339 dprint "vimfun: %s" % (vimfun % nm)
340 dprint "got nums: %s" % nums.to_s
342 if classdef.length > 1
343 classdef += "end\n"*clscnt
344 # classdef = "class %s\n%s\nend\n" % [ bufname.gsub( /\/|\\/, "_" ), classdef ]
347 dprint "get_buffer_entity END"
348 dprint "classdef====start"
349 lns = classdef.split( "\n" )
350 lns.each { |x| dprint x }
351 dprint "classdef====end"
355 def get_var_type( receiver )
356 if /(\"|\')+/.match( receiver )
359 VIM::evaluate("s:GetRubyVarType('%s')" % receiver)
367 def get_buffer_entity_list( type )
368 # this will be a little expensive.
369 loading_allowed = VIM::evaluate("exists('g:rubycomplete_buffer_loading') && g:rubycomplete_buffer_loading")
370 allow_aggressive_load = VIM::evaluate("exists('g:rubycomplete_classes_in_global') && g:rubycomplete_classes_in_global")
371 return [] if allow_aggressive_load.to_i.zero? || loading_allowed.to_i.zero?
373 buf = VIM::Buffer.current
377 re = eval( "/^\s*%s\s*([A-Za-z0-9_:-]*)(\s*<\s*([A-Za-z0-9_:-]*))?\s*/" % type )
380 if re.match( buf[x] )
381 next if type == "def" && eval( VIM::evaluate("s:IsPosInClassDef(%s)" % x) ) != nil
389 def get_buffer_modules
390 return get_buffer_entity_list( "modules" )
393 def get_buffer_methods
394 return get_buffer_entity_list( "def" )
397 def get_buffer_classes
398 return get_buffer_entity_list( "class" )
403 allow_rails = VIM::evaluate("exists('g:rubycomplete_rails') && g:rubycomplete_rails")
404 return if allow_rails.to_i.zero?
406 buf_path = VIM::evaluate('expand("%:p")')
407 file_name = VIM::evaluate('expand("%:t")')
408 vim_dir = VIM::evaluate('getcwd()')
409 file_dir = buf_path.gsub( file_name, '' )
410 file_dir.gsub!( /\\/, "/" )
411 vim_dir.gsub!( /\\/, "/" )
413 dirs = [ vim_dir, file_dir ]
414 sdirs = [ "", "./", "../", "../../", "../../../", "../../../../" ]
419 trail = "%s%s" % [ dir, sub ]
420 tcfg = "%sconfig" % trail
422 if File.exists?( tcfg )
430 return if rails_base == nil
431 $:.push rails_base unless $:.index( rails_base )
433 rails_config = rails_base + "config/"
434 rails_lib = rails_base + "lib/"
435 $:.push rails_config unless $:.index( rails_config )
436 $:.push rails_lib unless $:.index( rails_lib )
438 bootfile = rails_config + "boot.rb"
439 envfile = rails_config + "environment.rb"
440 if File.exists?( bootfile ) && File.exists?( envfile )
445 require 'console_app'
446 require 'console_with_helpers'
448 dprint "Rails 1.1+ Error %s" % $!
451 #eval( "Rails::Initializer.run" ) #not necessary?
452 VIM::command('let s:rubycomplete_rails_loaded = 1')
453 dprint "rails loaded"
455 dprint "Rails Error %s" % $!
456 VIM::evaluate( "s:ErrMsg('Error loading rails environment')" )
461 def get_rails_helpers
462 allow_rails = VIM::evaluate("exists('g:rubycomplete_rails') && g:rubycomplete_rails")
463 rails_loaded = VIM::evaluate('s:rubycomplete_rails_loaded')
464 return [] if allow_rails.to_i.zero? || rails_loaded.to_i.zero?
466 buf_path = VIM::evaluate('expand("%:p")')
467 buf_path.gsub!( /\\/, "/" )
468 path_elm = buf_path.split( "/" )
469 dprint "buf_path: %s" % buf_path
470 types = [ "app", "db", "lib", "test", "components", "script" ]
476 i = path_elm.index( t )
482 dprint "type: %s" % type
486 subtype = path_elm[i]
489 dprint "subtype: %s" % subtype
492 ret += ActionView::Base.instance_methods
493 ret += ActionView::Base.methods
495 ret += ActionController::Base.instance_methods
496 ret += ActionController::Base.methods
498 ret += ActiveRecord::Base.instance_methods
499 ret += ActiveRecord::Base.methods
503 ret += ActiveRecord::ConnectionAdapters::SchemaStatements.instance_methods
504 ret += ActiveRecord::ConnectionAdapters::SchemaStatements.methods
511 def add_rails_columns( cls )
512 allow_rails = VIM::evaluate("exists('g:rubycomplete_rails') && g:rubycomplete_rails")
513 rails_loaded = VIM::evaluate('s:rubycomplete_rails_loaded')
514 return [] if allow_rails.to_i.zero? || rails_loaded.to_i.zero?
517 eval( "#{cls}.establish_connection" )
518 return [] unless eval( "#{cls}.ancestors.include?(ActiveRecord::Base).to_s" )
519 col = eval( "#{cls}.column_names" )
522 dprint "add_rails_columns err: (cls: %s) %s" % [ cls, $! ]
528 def clean_sel(sel, msg)
529 sel.delete_if { |x| x == nil }
531 sel.grep(/^#{Regexp.quote(msg)}/) if msg != nil
534 def get_rails_view_methods
535 allow_rails = VIM::evaluate("exists('g:rubycomplete_rails') && g:rubycomplete_rails")
536 rails_loaded = VIM::evaluate('s:rubycomplete_rails_loaded')
537 return [] if allow_rails.to_i.zero? || rails_loaded.to_i.zero?
539 buf_path = VIM::evaluate('expand("%:p")')
540 buf_path.gsub!( /\\/, "/" )
541 pelm = buf_path.split( "/" )
542 idx = pelm.index( "views" )
547 clspl = pelm[idx].camelize.pluralize
548 cls = clspl.singularize
552 ret += eval( "#{cls}.instance_methods" )
553 ret += eval( "#{clspl}Helper.instance_methods" )
555 dprint "Error: Unable to load rails view helpers for %s: %s" % [ cls, $! ]
560 # }}} buffer analysis magic
562 # {{{ main completion code
563 def self.preload_rails
564 a = VimRubyCompletion.new
576 def self.get_completions(base)
577 b = VimRubyCompletion.new
578 b.get_completions base
581 def get_completions(base)
582 loading_allowed = VIM::evaluate("exists('g:rubycomplete_buffer_loading') && g:rubycomplete_buffer_loading")
583 if loading_allowed.to_i == 1
588 input = VIM::Buffer.current.line
589 cpos = VIM::Window.current.cursor[1] - 1
590 input = input[0..cpos]
592 input.sub!(/.*[ \t\n\"\\'`><=;|&{(]/, '') # Readline.basic_word_break_characters
593 input.sub!(/self\./, '')
594 input.sub!(/.*((\.\.[\[(]?)|([\[(]))/, '')
596 dprint 'input %s' % input
605 when /^(\/[^\/]*\/)\.([^.]*)$/ # Regexp
607 message = Regexp.quote($2)
608 methods = Regexp.instance_methods(true)
610 when /^([^\]]*\])\.([^.]*)$/ # Array
612 message = Regexp.quote($2)
613 methods = Array.instance_methods(true)
615 when /^([^\}]*\})\.([^.]*)$/ # Proc or Hash
617 message = Regexp.quote($2)
618 methods = Proc.instance_methods(true) | Hash.instance_methods(true)
620 when /^(:[^:.]*)$/ # Symbol
622 if Symbol.respond_to?(:all_symbols)
624 message = $1.sub( /:/, '' )
625 methods = Symbol.all_symbols.collect{|s| s.id2name}
626 methods.delete_if { |c| c.match( /'/ ) }
629 when /^::([A-Z][^:\.\(]*)$/ # Absolute Constant or class methods
630 dprint "const or cls"
632 methods = Object.constants
633 methods.grep(/^#{receiver}/).collect{|e| "::" + e}
635 when /^(((::)?[A-Z][^:.\(]*)+)::?([^:.]*)$/ # Constant or class methods
637 message = Regexp.quote($4)
638 dprint "const or cls 2 [recv: \'%s\', msg: \'%s\']" % [ receiver, message ]
639 load_buffer_class( receiver )
641 classes = eval("#{receiver}.constants")
642 #methods = eval("#{receiver}.methods")
644 dprint "exception: %s" % $!
647 methods.grep(/^#{message}/).collect{|e| receiver + "::" + e}
649 when /^(:[^:.]+)\.([^.]*)$/ # Symbol
652 message = Regexp.quote($2)
653 methods = Symbol.instance_methods(true)
655 when /^([0-9_]+(\.[0-9_]+)?(e[0-9]+)?)\.([^.]*)$/ # Numeric
658 message = Regexp.quote($4)
660 methods = eval(receiver).methods
665 when /^(\$[^.]*)$/ #global
667 methods = global_variables.grep(Regexp.new(Regexp.quote($1)))
669 when /^((\.?[^.]+)+)\.([^.]*)$/ # variable
672 message = Regexp.quote($3)
673 load_buffer_class( receiver )
675 cv = eval("self.class.constants")
676 vartype = get_var_type( receiver )
677 dprint "vartype: %s" % vartype
679 load_buffer_class( vartype )
682 methods = eval("#{vartype}.instance_methods")
683 variables = eval("#{vartype}.instance_variables")
685 dprint "load_buffer_class err: %s" % $!
687 elsif (cv).include?(receiver)
688 # foo.func and foo is local var.
689 methods = eval("#{receiver}.methods")
691 elsif /^[A-Z]/ =~ receiver and /\./ !~ receiver
695 methods = eval("#{receiver}.methods")
700 ObjectSpace.each_object(Module){|m|
701 next if m.name != "IRB::Context" and
702 /^(IRB|SLex|RubyLex|RubyToken)/ =~ m.name
703 methods.concat m.instance_methods(false)
706 variables += add_rails_columns( "#{vartype}" ) if vartype && vartype.length > 0
708 when /^\(?\s*[A-Za-z0-9:^@.%\/+*\(\)]+\.\.\.?[A-Za-z0-9:^@.%\/+*\(\)]+\s*\)?\.([^.]*)/
710 methods = Range.instance_methods(true)
712 when /^\.([^.]*)$/ # unknown(maybe String)
713 message = Regexp.quote($1)
714 methods = String.instance_methods(true)
717 dprint "default/other"
718 inclass = eval( VIM::evaluate("s:IsInClassDef()") )
722 classdef = "%s\n" % VIM::Buffer.current[ inclass.min ]
723 found = /^\s*class\s*([A-Za-z0-9_-]*)(\s*<\s*([A-Za-z0-9_:-]*))?\s*\n$/.match( classdef )
728 load_buffer_class( receiver )
730 methods = eval( "#{receiver}.instance_methods" )
731 variables += add_rails_columns( "#{receiver}" )
738 if inclass == nil || found == nil
739 dprint "inclass == nil"
740 methods = get_buffer_methods
741 methods += get_rails_view_methods
743 cls_const = Class.constants
744 constants = cls_const.select { |c| /^[A-Z_-]+$/.match( c ) }
745 classes = eval("self.class.constants") - constants
746 classes += get_buffer_classes
747 classes += get_buffer_modules
749 include_objectspace = VIM::evaluate("exists('g:rubycomplete_include_objectspace') && g:rubycomplete_include_objectspace")
750 ObjectSpace.each_object(Class) { |cls| classes << cls.to_s } if include_objectspace == "1"
751 message = receiver = input
754 methods += get_rails_helpers
755 methods += Kernel.public_methods
759 include_object = VIM::evaluate("exists('g:rubycomplete_include_object') && g:rubycomplete_include_object")
760 methods = clean_sel( methods, message )
761 methods = (methods-Object.instance_methods) if include_object == "0"
762 rbcmeth = (VimRubyCompletion.instance_methods-Object.instance_methods) # lets remove those rubycomplete methods
763 methods = (methods-rbcmeth)
765 variables = clean_sel( variables, message )
766 classes = clean_sel( classes, message ) - ["VimRubyCompletion"]
767 constants = clean_sel( constants, message )
770 valid += methods.collect { |m| { :name => m, :type => 'm' } }
771 valid += variables.collect { |v| { :name => v, :type => 'v' } }
772 valid += classes.collect { |c| { :name => c, :type => 't' } }
773 valid += constants.collect { |d| { :name => d, :type => 'd' } }
774 valid.sort! { |x,y| x[:name] <=> y[:name] }
782 valid[stpos..enpos].each { |c| outp += "{'word':'%s','item':'%s','kind':'%s'}," % [ c[:name], c[:name], c[:type] ] }
785 VIM::command("call extend(g:rubycomplete_completions, [%s])" % outp)
789 # }}} main completion code
791 end # VimRubyCompletion
792 # }}} ruby completion
796 let s:rubycomplete_rails_loaded = 0
802 " vim:tw=78:sw=4:ts=8:et:fdm=marker:ft=vim:norl: