rubycomplete.vim 24 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849
  1. " Vim completion script
  2. " Language: Ruby
  3. " Maintainer: Mark Guzman <segfault@hasno.info>
  4. " URL: https://github.com/vim-ruby/vim-ruby
  5. " Release Coordinator: Doug Kearns <dougkearns@gmail.com>
  6. " Last Change: 2019 Jan 06
  7. " ----------------------------------------------------------------------------
  8. "
  9. " Ruby IRB/Complete author: Keiju ISHITSUKA(keiju@ishitsuka.com)
  10. " ----------------------------------------------------------------------------
  11. " {{{ requirement checks
  12. function! s:ErrMsg(msg)
  13. echohl ErrorMsg
  14. echo a:msg
  15. echohl None
  16. endfunction
  17. if !has('ruby')
  18. call s:ErrMsg( "Error: Rubycomplete requires vim compiled with +ruby" )
  19. call s:ErrMsg( "Error: falling back to syntax completion" )
  20. " lets fall back to syntax completion
  21. setlocal omnifunc=syntaxcomplete#Complete
  22. finish
  23. endif
  24. if version < 700
  25. call s:ErrMsg( "Error: Required vim >= 7.0" )
  26. finish
  27. endif
  28. " }}} requirement checks
  29. " {{{ configuration failsafe initialization
  30. if !exists("g:rubycomplete_rails")
  31. let g:rubycomplete_rails = 0
  32. endif
  33. if !exists("g:rubycomplete_classes_in_global")
  34. let g:rubycomplete_classes_in_global = 0
  35. endif
  36. if !exists("g:rubycomplete_buffer_loading")
  37. let g:rubycomplete_buffer_loading = 0
  38. endif
  39. if !exists("g:rubycomplete_include_object")
  40. let g:rubycomplete_include_object = 0
  41. endif
  42. if !exists("g:rubycomplete_include_objectspace")
  43. let g:rubycomplete_include_objectspace = 0
  44. endif
  45. " }}} configuration failsafe initialization
  46. " {{{ vim-side support functions
  47. let s:rubycomplete_debug = 0
  48. function! s:dprint(msg)
  49. if s:rubycomplete_debug == 1
  50. echom a:msg
  51. endif
  52. endfunction
  53. function! s:GetBufferRubyModule(name, ...)
  54. if a:0 == 1
  55. let [snum,enum] = s:GetBufferRubyEntity(a:name, "module", a:1)
  56. else
  57. let [snum,enum] = s:GetBufferRubyEntity(a:name, "module")
  58. endif
  59. return snum . '..' . enum
  60. endfunction
  61. function! s:GetBufferRubyClass(name, ...)
  62. if a:0 >= 1
  63. let [snum,enum] = s:GetBufferRubyEntity(a:name, "class", a:1)
  64. else
  65. let [snum,enum] = s:GetBufferRubyEntity(a:name, "class")
  66. endif
  67. return snum . '..' . enum
  68. endfunction
  69. function! s:GetBufferRubySingletonMethods(name)
  70. endfunction
  71. function! s:GetBufferRubyEntity( name, type, ... )
  72. let lastpos = getpos(".")
  73. let lastline = lastpos
  74. if (a:0 >= 1)
  75. let lastline = [ 0, a:1, 0, 0 ]
  76. call cursor( a:1, 0 )
  77. endif
  78. let stopline = 1
  79. let crex = '^\s*\<' . a:type . '\>\s*\<' . escape(a:name, '*') . '\>\s*\(<\s*.*\s*\)\?'
  80. let [lnum,lcol] = searchpos( crex, 'w' )
  81. "let [lnum,lcol] = searchpairpos( crex . '\zs', '', '\(end\|}\)', 'w' )
  82. if lnum == 0 && lcol == 0
  83. call cursor(lastpos[1], lastpos[2])
  84. return [0,0]
  85. endif
  86. let curpos = getpos(".")
  87. let [enum,ecol] = searchpairpos( crex, '', '\(end\|}\)', 'W' )
  88. call cursor(lastpos[1], lastpos[2])
  89. if lnum > enum
  90. return [0,0]
  91. endif
  92. " we found a the class def
  93. return [lnum,enum]
  94. endfunction
  95. function! s:IsInClassDef()
  96. return s:IsPosInClassDef( line('.') )
  97. endfunction
  98. function! s:IsPosInClassDef(pos)
  99. let [snum,enum] = s:GetBufferRubyEntity( '.*', "class" )
  100. let ret = 'nil'
  101. if snum < a:pos && a:pos < enum
  102. let ret = snum . '..' . enum
  103. endif
  104. return ret
  105. endfunction
  106. function! s:GetRubyVarType(v)
  107. let stopline = 1
  108. let vtp = ''
  109. let pos = getpos('.')
  110. let sstr = '^\s*#\s*@var\s*'.escape(a:v, '*').'\>\s\+[^ \t]\+\s*$'
  111. let [lnum,lcol] = searchpos(sstr,'nb',stopline)
  112. if lnum != 0 && lcol != 0
  113. call setpos('.',pos)
  114. let str = getline(lnum)
  115. let vtp = substitute(str,sstr,'\1','')
  116. return vtp
  117. endif
  118. call setpos('.',pos)
  119. let ctors = '\(now\|new\|open\|get_instance'
  120. if exists('g:rubycomplete_rails') && g:rubycomplete_rails == 1 && s:rubycomplete_rails_loaded == 1
  121. let ctors = ctors.'\|find\|create'
  122. else
  123. endif
  124. let ctors = ctors.'\)'
  125. let fstr = '=\s*\([^ \t]\+.' . ctors .'\>\|[\[{"''/]\|%[xwQqr][(\[{@]\|[A-Za-z0-9@:\-()\.]\+...\?\|lambda\|&\)'
  126. let sstr = ''.escape(a:v, '*').'\>\s*[+\-*/]*'.fstr
  127. let [lnum,lcol] = searchpos(sstr,'nb',stopline)
  128. if lnum != 0 && lcol != 0
  129. let str = matchstr(getline(lnum),fstr,lcol)
  130. let str = substitute(str,'^=\s*','','')
  131. call setpos('.',pos)
  132. if str == '"' || str == '''' || stridx(tolower(str), '%q[') != -1
  133. return 'String'
  134. elseif str == '[' || stridx(str, '%w[') != -1
  135. return 'Array'
  136. elseif str == '{'
  137. return 'Hash'
  138. elseif str == '/' || str == '%r{'
  139. return 'Regexp'
  140. elseif strlen(str) >= 4 && stridx(str,'..') != -1
  141. return 'Range'
  142. elseif stridx(str, 'lambda') != -1 || str == '&'
  143. return 'Proc'
  144. elseif strlen(str) > 4
  145. let l = stridx(str,'.')
  146. return str[0:l-1]
  147. end
  148. return ''
  149. endif
  150. call setpos('.',pos)
  151. return ''
  152. endfunction
  153. "}}} vim-side support functions
  154. "{{{ vim-side completion function
  155. function! rubycomplete#Init()
  156. execute "ruby VimRubyCompletion.preload_rails"
  157. endfunction
  158. function! rubycomplete#Complete(findstart, base)
  159. "findstart = 1 when we need to get the text length
  160. if a:findstart
  161. let line = getline('.')
  162. let idx = col('.')
  163. while idx > 0
  164. let idx -= 1
  165. let c = line[idx-1]
  166. if c =~ '\w'
  167. continue
  168. elseif ! c =~ '\.'
  169. let idx = -1
  170. break
  171. else
  172. break
  173. endif
  174. endwhile
  175. return idx
  176. "findstart = 0 when we need to return the list of completions
  177. else
  178. let g:rubycomplete_completions = []
  179. execute "ruby VimRubyCompletion.get_completions('" . a:base . "')"
  180. return g:rubycomplete_completions
  181. endif
  182. endfunction
  183. "}}} vim-side completion function
  184. "{{{ ruby-side code
  185. function! s:DefRuby()
  186. ruby << RUBYEOF
  187. # {{{ ruby completion
  188. begin
  189. require 'rubygems' # let's assume this is safe...?
  190. rescue Exception
  191. #ignore?
  192. end
  193. class VimRubyCompletion
  194. # {{{ constants
  195. @@debug = false
  196. @@ReservedWords = [
  197. "BEGIN", "END",
  198. "alias", "and",
  199. "begin", "break",
  200. "case", "class",
  201. "def", "defined", "do",
  202. "else", "elsif", "end", "ensure",
  203. "false", "for",
  204. "if", "in",
  205. "module",
  206. "next", "nil", "not",
  207. "or",
  208. "redo", "rescue", "retry", "return",
  209. "self", "super",
  210. "then", "true",
  211. "undef", "unless", "until",
  212. "when", "while",
  213. "yield",
  214. ]
  215. @@Operators = [ "%", "&", "*", "**", "+", "-", "/",
  216. "<", "<<", "<=", "<=>", "==", "===", "=~", ">", ">=", ">>",
  217. "[]", "[]=", "^", ]
  218. # }}} constants
  219. # {{{ buffer analysis magic
  220. def load_requires
  221. custom_paths = VIM::evaluate("get(g:, 'rubycomplete_load_paths', [])")
  222. if !custom_paths.empty?
  223. $LOAD_PATH.concat(custom_paths).uniq!
  224. end
  225. buf = VIM::Buffer.current
  226. enum = buf.line_number
  227. nums = Range.new( 1, enum )
  228. nums.each do |x|
  229. ln = buf[x]
  230. begin
  231. if /.*require_relative\s*(.*)$/.match( ln )
  232. eval( "require %s" % File.expand_path($1) )
  233. elsif /.*require\s*(["'].*?["'])/.match( ln )
  234. eval( "require %s" % $1 )
  235. end
  236. rescue Exception => e
  237. dprint e.inspect
  238. end
  239. end
  240. end
  241. def load_gems
  242. fpath = VIM::evaluate("get(g:, 'rubycomplete_gemfile_path', 'Gemfile')")
  243. return unless File.file?(fpath) && File.readable?(fpath)
  244. want_bundler = VIM::evaluate("get(g:, 'rubycomplete_use_bundler')")
  245. parse_file = !want_bundler
  246. begin
  247. require 'bundler'
  248. Bundler.setup
  249. Bundler.require
  250. rescue Exception
  251. parse_file = true
  252. end
  253. if parse_file
  254. File.new(fpath).each_line do |line|
  255. begin
  256. require $1 if /\s*gem\s*['"]([^'"]+)/.match(line)
  257. rescue Exception
  258. end
  259. end
  260. end
  261. end
  262. def load_buffer_class(name)
  263. dprint "load_buffer_class(%s) START" % name
  264. classdef = get_buffer_entity(name, 's:GetBufferRubyClass("%s")')
  265. return if classdef == nil
  266. pare = /^\s*class\s*(.*)\s*<\s*(.*)\s*\n/.match( classdef )
  267. load_buffer_class( $2 ) if pare != nil && $2 != name # load parent class if needed
  268. mixre = /.*\n\s*(include|prepend)\s*(.*)\s*\n/.match( classdef )
  269. load_buffer_module( $2 ) if mixre != nil && $2 != name # load mixins if needed
  270. begin
  271. eval classdef
  272. rescue Exception
  273. VIM::evaluate( "s:ErrMsg( 'Problem loading class \"%s\", was it already completed?' )" % name )
  274. end
  275. dprint "load_buffer_class(%s) END" % name
  276. end
  277. def load_buffer_module(name)
  278. dprint "load_buffer_module(%s) START" % name
  279. classdef = get_buffer_entity(name, 's:GetBufferRubyModule("%s")')
  280. return if classdef == nil
  281. begin
  282. eval classdef
  283. rescue Exception
  284. VIM::evaluate( "s:ErrMsg( 'Problem loading module \"%s\", was it already completed?' )" % name )
  285. end
  286. dprint "load_buffer_module(%s) END" % name
  287. end
  288. def get_buffer_entity(name, vimfun)
  289. loading_allowed = VIM::evaluate("exists('g:rubycomplete_buffer_loading') && g:rubycomplete_buffer_loading")
  290. return nil if loading_allowed.to_i.zero?
  291. return nil if /(\"|\')+/.match( name )
  292. buf = VIM::Buffer.current
  293. nums = eval( VIM::evaluate( vimfun % name ) )
  294. return nil if nums == nil
  295. return nil if nums.min == nums.max && nums.min == 0
  296. dprint "get_buffer_entity START"
  297. visited = []
  298. clscnt = 0
  299. bufname = VIM::Buffer.current.name
  300. classdef = ""
  301. cur_line = VIM::Buffer.current.line_number
  302. while (nums != nil && !(nums.min == 0 && nums.max == 0) )
  303. dprint "visited: %s" % visited.to_s
  304. break if visited.index( nums )
  305. visited << nums
  306. nums.each do |x|
  307. if x != cur_line
  308. next if x == 0
  309. ln = buf[x]
  310. is_const = false
  311. if /^\s*(module|class|def|include)\s+/.match(ln) || is_const = /^\s*?[A-Z]([A-z]|[1-9])*\s*?[|]{0,2}=\s*?.+\s*?/.match(ln)
  312. clscnt += 1 if /class|module/.match($1)
  313. # We must make sure to load each constant only once to avoid errors
  314. if is_const
  315. ln.gsub!(/\s*?[|]{0,2}=\s*?/, '||=')
  316. end
  317. #dprint "\$1$1
  318. classdef += "%s\n" % ln
  319. classdef += "end\n" if /def\s+/.match(ln)
  320. dprint ln
  321. end
  322. end
  323. end
  324. nm = "%s(::.*)*\", %s, \"" % [ name, nums.last ]
  325. nums = eval( VIM::evaluate( vimfun % nm ) )
  326. dprint "nm: \"%s\"" % nm
  327. dprint "vimfun: %s" % (vimfun % nm)
  328. dprint "got nums: %s" % nums.to_s
  329. end
  330. if classdef.length > 1
  331. classdef += "end\n"*clscnt
  332. # classdef = "class %s\n%s\nend\n" % [ bufname.gsub( /\/|\\/, "_" ), classdef ]
  333. end
  334. dprint "get_buffer_entity END"
  335. dprint "classdef====start"
  336. lns = classdef.split( "\n" )
  337. lns.each { |x| dprint x }
  338. dprint "classdef====end"
  339. return classdef
  340. end
  341. def get_var_type( receiver )
  342. if /(\"|\')+/.match( receiver )
  343. "String"
  344. else
  345. VIM::evaluate("s:GetRubyVarType('%s')" % receiver)
  346. end
  347. end
  348. def dprint( txt )
  349. print txt if @@debug
  350. end
  351. def escape_vim_singlequote_string(str)
  352. str.to_s.gsub(/'/,"\\'")
  353. end
  354. def get_buffer_entity_list( type )
  355. # this will be a little expensive.
  356. loading_allowed = VIM::evaluate("exists('g:rubycomplete_buffer_loading') && g:rubycomplete_buffer_loading")
  357. allow_aggressive_load = VIM::evaluate("exists('g:rubycomplete_classes_in_global') && g:rubycomplete_classes_in_global")
  358. return [] if allow_aggressive_load.to_i.zero? || loading_allowed.to_i.zero?
  359. buf = VIM::Buffer.current
  360. eob = buf.length
  361. ret = []
  362. rg = 1..eob
  363. re = eval( "/^\s*%s\s*([A-Za-z0-9_:-]*)(\s*<\s*([A-Za-z0-9_:-]*))?\s*/" % type )
  364. rg.each do |x|
  365. if re.match( buf[x] )
  366. next if type == "def" && eval( VIM::evaluate("s:IsPosInClassDef(%s)" % x) ) != nil
  367. ret.push $1
  368. end
  369. end
  370. return ret
  371. end
  372. def get_buffer_modules
  373. return get_buffer_entity_list( "modules" )
  374. end
  375. def get_buffer_methods
  376. return get_buffer_entity_list( "def" )
  377. end
  378. def get_buffer_classes
  379. return get_buffer_entity_list( "class" )
  380. end
  381. def load_rails
  382. allow_rails = VIM::evaluate("exists('g:rubycomplete_rails') && g:rubycomplete_rails")
  383. return if allow_rails.to_i.zero?
  384. buf_path = VIM::evaluate('expand("%:p")')
  385. file_name = VIM::evaluate('expand("%:t")')
  386. vim_dir = VIM::evaluate('getcwd()')
  387. file_dir = buf_path.gsub( file_name, '' )
  388. file_dir.gsub!( /\\/, "/" )
  389. vim_dir.gsub!( /\\/, "/" )
  390. vim_dir << "/"
  391. dirs = [ vim_dir, file_dir ]
  392. sdirs = [ "", "./", "../", "../../", "../../../", "../../../../" ]
  393. rails_base = nil
  394. dirs.each do |dir|
  395. sdirs.each do |sub|
  396. trail = "%s%s" % [ dir, sub ]
  397. tcfg = "%sconfig" % trail
  398. if File.exists?( tcfg )
  399. rails_base = trail
  400. break
  401. end
  402. end
  403. break if rails_base
  404. end
  405. return if rails_base == nil
  406. $:.push rails_base unless $:.index( rails_base )
  407. rails_config = rails_base + "config/"
  408. rails_lib = rails_base + "lib/"
  409. $:.push rails_config unless $:.index( rails_config )
  410. $:.push rails_lib unless $:.index( rails_lib )
  411. bootfile = rails_config + "boot.rb"
  412. envfile = rails_config + "environment.rb"
  413. if File.exists?( bootfile ) && File.exists?( envfile )
  414. begin
  415. require bootfile
  416. require envfile
  417. begin
  418. require 'console_app'
  419. require 'console_with_helpers'
  420. rescue Exception
  421. dprint "Rails 1.1+ Error %s" % $!
  422. # assume 1.0
  423. end
  424. #eval( "Rails::Initializer.run" ) #not necessary?
  425. VIM::command('let s:rubycomplete_rails_loaded = 1')
  426. dprint "rails loaded"
  427. rescue Exception
  428. dprint "Rails Error %s" % $!
  429. VIM::evaluate( "s:ErrMsg('Error loading rails environment')" )
  430. end
  431. end
  432. end
  433. def get_rails_helpers
  434. allow_rails = VIM::evaluate("exists('g:rubycomplete_rails') && g:rubycomplete_rails")
  435. rails_loaded = VIM::evaluate('s:rubycomplete_rails_loaded')
  436. return [] if allow_rails.to_i.zero? || rails_loaded.to_i.zero?
  437. buf_path = VIM::evaluate('expand("%:p")')
  438. buf_path.gsub!( /\\/, "/" )
  439. path_elm = buf_path.split( "/" )
  440. dprint "buf_path: %s" % buf_path
  441. types = [ "app", "db", "lib", "test", "components", "script" ]
  442. i = nil
  443. ret = []
  444. type = nil
  445. types.each do |t|
  446. i = path_elm.index( t )
  447. break if i
  448. end
  449. type = path_elm[i]
  450. type.downcase!
  451. dprint "type: %s" % type
  452. case type
  453. when "app"
  454. i += 1
  455. subtype = path_elm[i]
  456. subtype.downcase!
  457. dprint "subtype: %s" % subtype
  458. case subtype
  459. when "views"
  460. ret += ActionView::Base.instance_methods
  461. ret += ActionView::Base.methods
  462. when "controllers"
  463. ret += ActionController::Base.instance_methods
  464. ret += ActionController::Base.methods
  465. when "models"
  466. ret += ActiveRecord::Base.instance_methods
  467. ret += ActiveRecord::Base.methods
  468. end
  469. when "db"
  470. ret += ActiveRecord::ConnectionAdapters::SchemaStatements.instance_methods
  471. ret += ActiveRecord::ConnectionAdapters::SchemaStatements.methods
  472. end
  473. return ret
  474. end
  475. def add_rails_columns( cls )
  476. allow_rails = VIM::evaluate("exists('g:rubycomplete_rails') && g:rubycomplete_rails")
  477. rails_loaded = VIM::evaluate('s:rubycomplete_rails_loaded')
  478. return [] if allow_rails.to_i.zero? || rails_loaded.to_i.zero?
  479. begin
  480. eval( "#{cls}.establish_connection" )
  481. return [] unless eval( "#{cls}.ancestors.include?(ActiveRecord::Base).to_s" )
  482. col = eval( "#{cls}.column_names" )
  483. return col if col
  484. rescue
  485. dprint "add_rails_columns err: (cls: %s) %s" % [ cls, $! ]
  486. return []
  487. end
  488. return []
  489. end
  490. def clean_sel(sel, msg)
  491. ret = sel.reject{|x|x.nil?}.uniq
  492. ret = ret.grep(/^#{Regexp.quote(msg)}/) if msg != nil
  493. ret
  494. end
  495. def get_rails_view_methods
  496. allow_rails = VIM::evaluate("exists('g:rubycomplete_rails') && g:rubycomplete_rails")
  497. rails_loaded = VIM::evaluate('s:rubycomplete_rails_loaded')
  498. return [] if allow_rails.to_i.zero? || rails_loaded.to_i.zero?
  499. buf_path = VIM::evaluate('expand("%:p")')
  500. buf_path.gsub!( /\\/, "/" )
  501. pelm = buf_path.split( "/" )
  502. idx = pelm.index( "views" )
  503. return [] unless idx
  504. idx += 1
  505. clspl = pelm[idx].camelize.pluralize
  506. cls = clspl.singularize
  507. ret = []
  508. begin
  509. ret += eval( "#{cls}.instance_methods" )
  510. ret += eval( "#{clspl}Helper.instance_methods" )
  511. rescue Exception
  512. dprint "Error: Unable to load rails view helpers for %s: %s" % [ cls, $! ]
  513. end
  514. return ret
  515. end
  516. # }}} buffer analysis magic
  517. # {{{ main completion code
  518. def self.preload_rails
  519. a = VimRubyCompletion.new
  520. if VIM::evaluate("has('nvim')") == 0
  521. require 'thread'
  522. Thread.new(a) do |b|
  523. begin
  524. b.load_rails
  525. rescue
  526. end
  527. end
  528. end
  529. a.load_rails
  530. rescue
  531. end
  532. def self.get_completions(base)
  533. b = VimRubyCompletion.new
  534. b.get_completions base
  535. end
  536. def get_completions(base)
  537. loading_allowed = VIM::evaluate("exists('g:rubycomplete_buffer_loading') && g:rubycomplete_buffer_loading")
  538. if loading_allowed.to_i == 1
  539. load_requires
  540. load_rails
  541. end
  542. want_gems = VIM::evaluate("get(g:, 'rubycomplete_load_gemfile')")
  543. load_gems unless want_gems.to_i.zero?
  544. input = VIM::Buffer.current.line
  545. cpos = VIM::Window.current.cursor[1] - 1
  546. input = input[0..cpos]
  547. input += base
  548. input.sub!(/.*[ \t\n\"\\'`><=;|&{(]/, '') # Readline.basic_word_break_characters
  549. input.sub!(/self\./, '')
  550. input.sub!(/.*((\.\.[\[(]?)|([\[(]))/, '')
  551. dprint 'input %s' % input
  552. message = nil
  553. receiver = nil
  554. methods = []
  555. variables = []
  556. classes = []
  557. constants = []
  558. case input
  559. when /^(\/[^\/]*\/)\.([^.]*)$/ # Regexp
  560. receiver = $1
  561. message = Regexp.quote($2)
  562. methods = Regexp.instance_methods(true)
  563. when /^([^\]]*\])\.([^.]*)$/ # Array
  564. receiver = $1
  565. message = Regexp.quote($2)
  566. methods = Array.instance_methods(true)
  567. when /^([^\}]*\})\.([^.]*)$/ # Proc or Hash
  568. receiver = $1
  569. message = Regexp.quote($2)
  570. methods = Proc.instance_methods(true) | Hash.instance_methods(true)
  571. when /^(:[^:.]*)$/ # Symbol
  572. dprint "symbol"
  573. if Symbol.respond_to?(:all_symbols)
  574. receiver = $1
  575. message = $1.sub( /:/, '' )
  576. methods = Symbol.all_symbols.collect{|s| s.id2name}
  577. methods.delete_if { |c| c.match( /'/ ) }
  578. end
  579. when /^::([A-Z][^:\.\(]*)$/ # Absolute Constant or class methods
  580. dprint "const or cls"
  581. receiver = $1
  582. methods = Object.constants
  583. methods.grep(/^#{receiver}/).collect{|e| "::" + e}
  584. when /^(((::)?[A-Z][^:.\(]*)+?)::?([^:.]*)$/ # Constant or class methods
  585. receiver = $1
  586. message = Regexp.quote($4)
  587. dprint "const or cls 2 [recv: \'%s\', msg: \'%s\']" % [ receiver, message ]
  588. load_buffer_class( receiver )
  589. load_buffer_module( receiver )
  590. begin
  591. classes = eval("#{receiver}.constants")
  592. #methods = eval("#{receiver}.methods")
  593. rescue Exception
  594. dprint "exception: %s" % $!
  595. methods = []
  596. end
  597. methods.grep(/^#{message}/).collect{|e| receiver + "::" + e}
  598. when /^(:[^:.]+)\.([^.]*)$/ # Symbol
  599. dprint "symbol"
  600. receiver = $1
  601. message = Regexp.quote($2)
  602. methods = Symbol.instance_methods(true)
  603. when /^([0-9_]+(\.[0-9_]+)?(e[0-9]+)?)\.([^.]*)$/ # Numeric
  604. dprint "numeric"
  605. receiver = $1
  606. message = Regexp.quote($4)
  607. begin
  608. methods = eval(receiver).methods
  609. rescue Exception
  610. methods = []
  611. end
  612. when /^(\$[^.]*)$/ #global
  613. dprint "global"
  614. methods = global_variables.grep(Regexp.new(Regexp.quote($1)))
  615. when /^((\.?[^.]+)+?)\.([^.]*)$/ # variable
  616. dprint "variable"
  617. receiver = $1
  618. message = Regexp.quote($3)
  619. load_buffer_class( receiver )
  620. cv = eval("self.class.constants")
  621. vartype = get_var_type( receiver )
  622. dprint "vartype: %s" % vartype
  623. invalid_vartype = ['', "gets"]
  624. if !invalid_vartype.include?(vartype)
  625. load_buffer_class( vartype )
  626. begin
  627. methods = eval("#{vartype}.instance_methods")
  628. variables = eval("#{vartype}.instance_variables")
  629. rescue Exception
  630. dprint "load_buffer_class err: %s" % $!
  631. end
  632. elsif (cv).include?(receiver)
  633. # foo.func and foo is local var.
  634. methods = eval("#{receiver}.methods")
  635. vartype = receiver
  636. elsif /^[A-Z]/ =~ receiver and /\./ !~ receiver
  637. vartype = receiver
  638. # Foo::Bar.func
  639. begin
  640. methods = eval("#{receiver}.methods")
  641. rescue Exception
  642. end
  643. else
  644. # func1.func2
  645. ObjectSpace.each_object(Module){|m|
  646. next if m.name != "IRB::Context" and
  647. /^(IRB|SLex|RubyLex|RubyToken)/ =~ m.name
  648. methods.concat m.instance_methods(false)
  649. }
  650. end
  651. variables += add_rails_columns( "#{vartype}" ) if vartype && !invalid_vartype.include?(vartype)
  652. when /^\(?\s*[A-Za-z0-9:^@.%\/+*\(\)]+\.\.\.?[A-Za-z0-9:^@.%\/+*\(\)]+\s*\)?\.([^.]*)/
  653. message = $1
  654. methods = Range.instance_methods(true)
  655. when /^\.([^.]*)$/ # unknown(maybe String)
  656. message = Regexp.quote($1)
  657. methods = String.instance_methods(true)
  658. else
  659. dprint "default/other"
  660. inclass = eval( VIM::evaluate("s:IsInClassDef()") )
  661. if inclass != nil
  662. dprint "inclass"
  663. classdef = "%s\n" % VIM::Buffer.current[ inclass.min ]
  664. found = /^\s*class\s*([A-Za-z0-9_-]*)(\s*<\s*([A-Za-z0-9_:-]*))?\s*\n$/.match( classdef )
  665. if found != nil
  666. receiver = $1
  667. message = input
  668. load_buffer_class( receiver )
  669. begin
  670. methods = eval( "#{receiver}.instance_methods" )
  671. variables += add_rails_columns( "#{receiver}" )
  672. rescue Exception
  673. found = nil
  674. end
  675. end
  676. end
  677. if inclass == nil || found == nil
  678. dprint "inclass == nil"
  679. methods = get_buffer_methods
  680. methods += get_rails_view_methods
  681. cls_const = Class.constants
  682. constants = cls_const.select { |c| /^[A-Z_-]+$/.match( c ) }
  683. classes = eval("self.class.constants") - constants
  684. classes += get_buffer_classes
  685. classes += get_buffer_modules
  686. include_objectspace = VIM::evaluate("exists('g:rubycomplete_include_objectspace') && g:rubycomplete_include_objectspace")
  687. ObjectSpace.each_object(Class) { |cls| classes << cls.to_s } if include_objectspace == "1"
  688. message = receiver = input
  689. end
  690. methods += get_rails_helpers
  691. methods += Kernel.public_methods
  692. end
  693. include_object = VIM::evaluate("exists('g:rubycomplete_include_object') && g:rubycomplete_include_object")
  694. methods = clean_sel( methods, message )
  695. methods = (methods-Object.instance_methods) if include_object == "0"
  696. rbcmeth = (VimRubyCompletion.instance_methods-Object.instance_methods) # lets remove those rubycomplete methods
  697. methods = (methods-rbcmeth)
  698. variables = clean_sel( variables, message )
  699. classes = clean_sel( classes, message ) - ["VimRubyCompletion"]
  700. constants = clean_sel( constants, message )
  701. valid = []
  702. valid += methods.collect { |m| { :name => m.to_s, :type => 'm' } }
  703. valid += variables.collect { |v| { :name => v.to_s, :type => 'v' } }
  704. valid += classes.collect { |c| { :name => c.to_s, :type => 't' } }
  705. valid += constants.collect { |d| { :name => d.to_s, :type => 'd' } }
  706. valid.sort! { |x,y| x[:name] <=> y[:name] }
  707. outp = ""
  708. rg = 0..valid.length
  709. rg.step(150) do |x|
  710. stpos = 0+x
  711. enpos = 150+x
  712. valid[stpos..enpos].each { |c| outp += "{'word':'%s','item':'%s','kind':'%s'}," % [ c[:name], c[:name], c[:type] ].map{|x|escape_vim_singlequote_string(x)} }
  713. outp.sub!(/,$/, '')
  714. VIM::command("call extend(g:rubycomplete_completions, [%s])" % outp)
  715. outp = ""
  716. end
  717. end
  718. # }}} main completion code
  719. end # VimRubyCompletion
  720. # }}} ruby completion
  721. RUBYEOF
  722. endfunction
  723. let s:rubycomplete_rails_loaded = 0
  724. call s:DefRuby()
  725. "}}} ruby-side code
  726. " vim:tw=78:sw=4:ts=8:et:fdm=marker:ft=vim:norl: