rubycomplete.vim 25 KB

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