rubycomplete.vim 25 KB

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