ruby.vim 30 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959960961962963964965966967968969970971972973974975976977978979980981982983984985986987988989990991
  1. " Vim indent file
  2. " Language: Ruby
  3. " Maintainer: Andrew Radev <andrey.radev@gmail.com>
  4. " Previous Maintainer: Nikolai Weibull <now at bitwi.se>
  5. " URL: https://github.com/vim-ruby/vim-ruby
  6. " Release Coordinator: Doug Kearns <dougkearns@gmail.com>
  7. " Last Change: 2022 Mar 22
  8. " 0. Initialization {{{1
  9. " =================
  10. " Only load this indent file when no other was loaded.
  11. if exists("b:did_indent")
  12. finish
  13. endif
  14. let b:did_indent = 1
  15. if !exists('g:ruby_indent_access_modifier_style')
  16. " Possible values: "normal", "indent", "outdent"
  17. let g:ruby_indent_access_modifier_style = 'normal'
  18. endif
  19. if !exists('g:ruby_indent_assignment_style')
  20. " Possible values: "variable", "hanging"
  21. let g:ruby_indent_assignment_style = 'hanging'
  22. endif
  23. if !exists('g:ruby_indent_block_style')
  24. " Possible values: "expression", "do"
  25. let g:ruby_indent_block_style = 'do'
  26. endif
  27. if !exists('g:ruby_indent_hanging_elements')
  28. " Non-zero means hanging indents are enabled, zero means disabled
  29. let g:ruby_indent_hanging_elements = 1
  30. endif
  31. setlocal nosmartindent
  32. " Now, set up our indentation expression and keys that trigger it.
  33. setlocal indentexpr=GetRubyIndent(v:lnum)
  34. setlocal indentkeys=0{,0},0),0],!^F,o,O,e,:,.
  35. setlocal indentkeys+==end,=else,=elsif,=when,=in\ ,=ensure,=rescue,==begin,==end
  36. setlocal indentkeys+==private,=protected,=public
  37. let b:undo_indent = "setlocal indentexpr< indentkeys< smartindent<"
  38. " Only define the function once.
  39. if exists("*GetRubyIndent")
  40. finish
  41. endif
  42. let s:cpo_save = &cpo
  43. set cpo&vim
  44. " 1. Variables {{{1
  45. " ============
  46. " Syntax group names that are strings.
  47. let s:syng_string =
  48. \ ['String', 'Interpolation', 'InterpolationDelimiter', 'StringEscape']
  49. " Syntax group names that are strings or documentation.
  50. let s:syng_stringdoc = s:syng_string + ['Documentation']
  51. " Syntax group names that are or delimit strings/symbols/regexes or are comments.
  52. let s:syng_strcom = s:syng_stringdoc + [
  53. \ 'Character',
  54. \ 'Comment',
  55. \ 'HeredocDelimiter',
  56. \ 'PercentRegexpDelimiter',
  57. \ 'PercentStringDelimiter',
  58. \ 'PercentSymbolDelimiter',
  59. \ 'Regexp',
  60. \ 'RegexpCharClass',
  61. \ 'RegexpDelimiter',
  62. \ 'RegexpEscape',
  63. \ 'StringDelimiter',
  64. \ 'Symbol',
  65. \ 'SymbolDelimiter',
  66. \ ]
  67. " Expression used to check whether we should skip a match with searchpair().
  68. let s:skip_expr =
  69. \ 'index(map('.string(s:syng_strcom).',"hlID(''ruby''.v:val)"), synID(line("."),col("."),1)) >= 0'
  70. " Regex used for words that, at the start of a line, add a level of indent.
  71. let s:ruby_indent_keywords =
  72. \ '^\s*\zs\<\%(module\|class\|if\|for' .
  73. \ '\|while\|until\|else\|elsif\|case\|when\|in\|unless\|begin\|ensure\|rescue' .
  74. \ '\|\%(\K\k*[!?]\?\s\+\)\=def\):\@!\>' .
  75. \ '\|\%([=,*/%+-]\|<<\|>>\|:\s\)\s*\zs' .
  76. \ '\<\%(if\|for\|while\|until\|case\|unless\|begin\):\@!\>'
  77. " Def without an end clause: def method_call(...) = <expression>
  78. let s:ruby_endless_def = '\<def\s\+\k\+[!?]\=\%((.*)\|\s\)\s*='
  79. " Regex used for words that, at the start of a line, remove a level of indent.
  80. let s:ruby_deindent_keywords =
  81. \ '^\s*\zs\<\%(ensure\|else\|rescue\|elsif\|when\|in\|end\):\@!\>'
  82. " Regex that defines the start-match for the 'end' keyword.
  83. "let s:end_start_regex = '\%(^\|[^.]\)\<\%(module\|class\|def\|if\|for\|while\|until\|case\|unless\|begin\|do\)\>'
  84. " TODO: the do here should be restricted somewhat (only at end of line)?
  85. let s:end_start_regex =
  86. \ '\C\%(^\s*\|[=,*/%+\-|;{]\|<<\|>>\|:\s\)\s*\zs' .
  87. \ '\<\%(module\|class\|if\|for\|while\|until\|case\|unless\|begin' .
  88. \ '\|\%(\K\k*[!?]\?\s\+\)\=def\):\@!\>' .
  89. \ '\|\%(^\|[^.:@$]\)\@<=\<do:\@!\>'
  90. " Regex that defines the middle-match for the 'end' keyword.
  91. let s:end_middle_regex = '\<\%(ensure\|else\|\%(\%(^\|;\)\s*\)\@<=\<rescue:\@!\>\|when\|\%(\%(^\|;\)\s*\)\@<=\<in\|elsif\):\@!\>'
  92. " Regex that defines the end-match for the 'end' keyword.
  93. let s:end_end_regex = '\%(^\|[^.:@$]\)\@<=\<end:\@!\>'
  94. " Expression used for searchpair() call for finding a match for an 'end' keyword.
  95. function! s:EndSkipExpr()
  96. if eval(s:skip_expr)
  97. return 1
  98. elseif expand('<cword>') == 'do'
  99. \ && getline(".") =~ '^\s*\<\(while\|until\|for\):\@!\>'
  100. return 1
  101. elseif getline('.') =~ s:ruby_endless_def
  102. return 1
  103. elseif getline('.') =~ '\<def\s\+\k\+[!?]\=([^)]*$'
  104. " Then it's a `def method(` with a possible `) =` later
  105. call search('\<def\s\+\k\+\zs(', 'W', line('.'))
  106. normal! %
  107. return getline('.') =~ ')\s*='
  108. else
  109. return 0
  110. endif
  111. endfunction
  112. let s:end_skip_expr = function('s:EndSkipExpr')
  113. " Regex that defines continuation lines, not including (, {, or [.
  114. let s:non_bracket_continuation_regex =
  115. \ '\%([\\.,:*/%+]\|\<and\|\<or\|\%(<%\)\@<![=-]\|:\@<![^[:alnum:]:][|&?]\|||\|&&\)\s*\%(#.*\)\=$'
  116. " Regex that defines continuation lines.
  117. let s:continuation_regex =
  118. \ '\%(%\@<![({[\\.,:*/%+]\|\<and\|\<or\|\%(<%\)\@<![=-]\|:\@<![^[:alnum:]:][|&?]\|||\|&&\)\s*\%(#.*\)\=$'
  119. " Regex that defines continuable keywords
  120. let s:continuable_regex =
  121. \ '\C\%(^\s*\|[=,*/%+\-|;{]\|<<\|>>\|:\s\)\s*\zs' .
  122. \ '\<\%(if\|for\|while\|until\|unless\):\@!\>'
  123. " Regex that defines bracket continuations
  124. let s:bracket_continuation_regex = '%\@<!\%([({[]\)\s*\%(#.*\)\=$'
  125. " Regex that defines dot continuations
  126. let s:dot_continuation_regex = '%\@<!\.\s*\%(#.*\)\=$'
  127. " Regex that defines backslash continuations
  128. let s:backslash_continuation_regex = '%\@<!\\\s*$'
  129. " Regex that defines end of bracket continuation followed by another continuation
  130. let s:bracket_switch_continuation_regex = '^\([^(]\+\zs).\+\)\+'.s:continuation_regex
  131. " Regex that defines the first part of a splat pattern
  132. let s:splat_regex = '[[,(]\s*\*\s*\%(#.*\)\=$'
  133. " Regex that describes all indent access modifiers
  134. let s:access_modifier_regex = '\C^\s*\%(public\|protected\|private\)\s*\%(#.*\)\=$'
  135. " Regex that describes the indent access modifiers (excludes public)
  136. let s:indent_access_modifier_regex = '\C^\s*\%(protected\|private\)\s*\%(#.*\)\=$'
  137. " Regex that defines blocks.
  138. "
  139. " Note that there's a slight problem with this regex and s:continuation_regex.
  140. " Code like this will be matched by both:
  141. "
  142. " method_call do |(a, b)|
  143. "
  144. " The reason is that the pipe matches a hanging "|" operator.
  145. "
  146. let s:block_regex =
  147. \ '\%(\<do:\@!\>\|%\@<!{\)\s*\%(|[^|]*|\)\=\s*\%(#.*\)\=$'
  148. let s:block_continuation_regex = '^\s*[^])}\t ].*'.s:block_regex
  149. " Regex that describes a leading operator (only a method call's dot for now)
  150. let s:leading_operator_regex = '^\s*\%(&\=\.\)'
  151. " 2. GetRubyIndent Function {{{1
  152. " =========================
  153. function! GetRubyIndent(...) abort
  154. " 2.1. Setup {{{2
  155. " ----------
  156. let indent_info = {}
  157. " The value of a single shift-width
  158. if exists('*shiftwidth')
  159. let indent_info.sw = shiftwidth()
  160. else
  161. let indent_info.sw = &sw
  162. endif
  163. " For the current line, use the first argument if given, else v:lnum
  164. let indent_info.clnum = a:0 ? a:1 : v:lnum
  165. let indent_info.cline = getline(indent_info.clnum)
  166. " Set up variables for restoring position in file. Could use clnum here.
  167. let indent_info.col = col('.')
  168. " 2.2. Work on the current line {{{2
  169. " -----------------------------
  170. let indent_callback_names = [
  171. \ 's:AccessModifier',
  172. \ 's:ClosingBracketOnEmptyLine',
  173. \ 's:BlockComment',
  174. \ 's:DeindentingKeyword',
  175. \ 's:MultilineStringOrLineComment',
  176. \ 's:ClosingHeredocDelimiter',
  177. \ 's:LeadingOperator',
  178. \ ]
  179. for callback_name in indent_callback_names
  180. " Decho "Running: ".callback_name
  181. let indent = call(function(callback_name), [indent_info])
  182. if indent >= 0
  183. " Decho "Match: ".callback_name." indent=".indent." info=".string(indent_info)
  184. return indent
  185. endif
  186. endfor
  187. " 2.3. Work on the previous line. {{{2
  188. " -------------------------------
  189. " Special case: we don't need the real s:PrevNonBlankNonString for an empty
  190. " line inside a string. And that call can be quite expensive in that
  191. " particular situation.
  192. let indent_callback_names = [
  193. \ 's:EmptyInsideString',
  194. \ ]
  195. for callback_name in indent_callback_names
  196. " Decho "Running: ".callback_name
  197. let indent = call(function(callback_name), [indent_info])
  198. if indent >= 0
  199. " Decho "Match: ".callback_name." indent=".indent." info=".string(indent_info)
  200. return indent
  201. endif
  202. endfor
  203. " Previous line number
  204. let indent_info.plnum = s:PrevNonBlankNonString(indent_info.clnum - 1)
  205. let indent_info.pline = getline(indent_info.plnum)
  206. let indent_callback_names = [
  207. \ 's:StartOfFile',
  208. \ 's:AfterAccessModifier',
  209. \ 's:ContinuedLine',
  210. \ 's:AfterBlockOpening',
  211. \ 's:AfterHangingSplat',
  212. \ 's:AfterUnbalancedBracket',
  213. \ 's:AfterLeadingOperator',
  214. \ 's:AfterEndKeyword',
  215. \ 's:AfterIndentKeyword',
  216. \ ]
  217. for callback_name in indent_callback_names
  218. " Decho "Running: ".callback_name
  219. let indent = call(function(callback_name), [indent_info])
  220. if indent >= 0
  221. " Decho "Match: ".callback_name." indent=".indent." info=".string(indent_info)
  222. return indent
  223. endif
  224. endfor
  225. " 2.4. Work on the MSL line. {{{2
  226. " --------------------------
  227. let indent_callback_names = [
  228. \ 's:PreviousNotMSL',
  229. \ 's:IndentingKeywordInMSL',
  230. \ 's:ContinuedHangingOperator',
  231. \ ]
  232. " Most Significant line based on the previous one -- in case it's a
  233. " continuation of something above
  234. let indent_info.plnum_msl = s:GetMSL(indent_info.plnum)
  235. for callback_name in indent_callback_names
  236. " Decho "Running: ".callback_name
  237. let indent = call(function(callback_name), [indent_info])
  238. if indent >= 0
  239. " Decho "Match: ".callback_name." indent=".indent." info=".string(indent_info)
  240. return indent
  241. endif
  242. endfor
  243. " }}}2
  244. " By default, just return the previous line's indent
  245. " Decho "Default case matched"
  246. return indent(indent_info.plnum)
  247. endfunction
  248. " 3. Indenting Logic Callbacks {{{1
  249. " ============================
  250. function! s:AccessModifier(cline_info) abort
  251. let info = a:cline_info
  252. " If this line is an access modifier keyword, align according to the closest
  253. " class declaration.
  254. if g:ruby_indent_access_modifier_style == 'indent'
  255. if s:Match(info.clnum, s:access_modifier_regex)
  256. let class_lnum = s:FindContainingClass()
  257. if class_lnum > 0
  258. return indent(class_lnum) + info.sw
  259. endif
  260. endif
  261. elseif g:ruby_indent_access_modifier_style == 'outdent'
  262. if s:Match(info.clnum, s:access_modifier_regex)
  263. let class_lnum = s:FindContainingClass()
  264. if class_lnum > 0
  265. return indent(class_lnum)
  266. endif
  267. endif
  268. endif
  269. return -1
  270. endfunction
  271. function! s:ClosingBracketOnEmptyLine(cline_info) abort
  272. let info = a:cline_info
  273. " If we got a closing bracket on an empty line, find its match and indent
  274. " according to it. For parentheses we indent to its column - 1, for the
  275. " others we indent to the containing line's MSL's level. Return -1 if fail.
  276. let col = matchend(info.cline, '^\s*[]})]')
  277. if col > 0 && !s:IsInStringOrComment(info.clnum, col)
  278. call cursor(info.clnum, col)
  279. let closing_bracket = info.cline[col - 1]
  280. let bracket_pair = strpart('(){}[]', stridx(')}]', closing_bracket) * 2, 2)
  281. if searchpair(escape(bracket_pair[0], '\['), '', bracket_pair[1], 'bW', s:skip_expr) > 0
  282. if closing_bracket == ')' && col('.') != col('$') - 1
  283. if g:ruby_indent_hanging_elements
  284. let ind = virtcol('.') - 1
  285. else
  286. let ind = indent(line('.'))
  287. end
  288. elseif g:ruby_indent_block_style == 'do'
  289. let ind = indent(line('.'))
  290. else " g:ruby_indent_block_style == 'expression'
  291. let ind = indent(s:GetMSL(line('.')))
  292. endif
  293. endif
  294. return ind
  295. endif
  296. return -1
  297. endfunction
  298. function! s:BlockComment(cline_info) abort
  299. " If we have a =begin or =end set indent to first column.
  300. if match(a:cline_info.cline, '^\s*\%(=begin\|=end\)$') != -1
  301. return 0
  302. endif
  303. return -1
  304. endfunction
  305. function! s:DeindentingKeyword(cline_info) abort
  306. let info = a:cline_info
  307. " If we have a deindenting keyword, find its match and indent to its level.
  308. " TODO: this is messy
  309. if s:Match(info.clnum, s:ruby_deindent_keywords)
  310. call cursor(info.clnum, 1)
  311. if searchpair(s:end_start_regex, s:end_middle_regex, s:end_end_regex, 'bW',
  312. \ s:end_skip_expr) > 0
  313. let msl = s:GetMSL(line('.'))
  314. let line = getline(line('.'))
  315. if s:IsAssignment(line, col('.')) &&
  316. \ strpart(line, col('.') - 1, 2) !~ 'do'
  317. " assignment to case/begin/etc, on the same line
  318. if g:ruby_indent_assignment_style == 'hanging'
  319. " hanging indent
  320. let ind = virtcol('.') - 1
  321. else
  322. " align with variable
  323. let ind = indent(line('.'))
  324. endif
  325. elseif g:ruby_indent_block_style == 'do'
  326. " align to line of the "do", not to the MSL
  327. let ind = indent(line('.'))
  328. elseif getline(msl) =~ '=\s*\(#.*\)\=$'
  329. " in the case of assignment to the MSL, align to the starting line,
  330. " not to the MSL
  331. let ind = indent(line('.'))
  332. else
  333. " align to the MSL
  334. let ind = indent(msl)
  335. endif
  336. endif
  337. return ind
  338. endif
  339. return -1
  340. endfunction
  341. function! s:MultilineStringOrLineComment(cline_info) abort
  342. let info = a:cline_info
  343. " If we are in a multi-line string or line-comment, don't do anything to it.
  344. if s:IsInStringOrDocumentation(info.clnum, matchend(info.cline, '^\s*') + 1)
  345. return indent(info.clnum)
  346. endif
  347. return -1
  348. endfunction
  349. function! s:ClosingHeredocDelimiter(cline_info) abort
  350. let info = a:cline_info
  351. " If we are at the closing delimiter of a "<<" heredoc-style string, set the
  352. " indent to 0.
  353. if info.cline =~ '^\k\+\s*$'
  354. \ && s:IsInStringDelimiter(info.clnum, 1)
  355. \ && search('\V<<'.info.cline, 'nbW') > 0
  356. return 0
  357. endif
  358. return -1
  359. endfunction
  360. function! s:LeadingOperator(cline_info) abort
  361. " If the current line starts with a leading operator, add a level of indent.
  362. if s:Match(a:cline_info.clnum, s:leading_operator_regex)
  363. return indent(s:GetMSL(a:cline_info.clnum)) + a:cline_info.sw
  364. endif
  365. return -1
  366. endfunction
  367. function! s:EmptyInsideString(pline_info) abort
  368. " If the line is empty and inside a string (the previous line is a string,
  369. " too), use the previous line's indent
  370. let info = a:pline_info
  371. let plnum = prevnonblank(info.clnum - 1)
  372. let pline = getline(plnum)
  373. if info.cline =~ '^\s*$'
  374. \ && s:IsInStringOrComment(plnum, 1)
  375. \ && s:IsInStringOrComment(plnum, strlen(pline))
  376. return indent(plnum)
  377. endif
  378. return -1
  379. endfunction
  380. function! s:StartOfFile(pline_info) abort
  381. " At the start of the file use zero indent.
  382. if a:pline_info.plnum == 0
  383. return 0
  384. endif
  385. return -1
  386. endfunction
  387. function! s:AfterAccessModifier(pline_info) abort
  388. let info = a:pline_info
  389. if g:ruby_indent_access_modifier_style == 'indent'
  390. " If the previous line was a private/protected keyword, add a
  391. " level of indent.
  392. if s:Match(info.plnum, s:indent_access_modifier_regex)
  393. return indent(info.plnum) + info.sw
  394. endif
  395. elseif g:ruby_indent_access_modifier_style == 'outdent'
  396. " If the previous line was a private/protected/public keyword, add
  397. " a level of indent, since the keyword has been out-dented.
  398. if s:Match(info.plnum, s:access_modifier_regex)
  399. return indent(info.plnum) + info.sw
  400. endif
  401. endif
  402. return -1
  403. endfunction
  404. " Example:
  405. "
  406. " if foo || bar ||
  407. " baz || bing
  408. " puts "foo"
  409. " end
  410. "
  411. function! s:ContinuedLine(pline_info) abort
  412. let info = a:pline_info
  413. let col = s:Match(info.plnum, s:ruby_indent_keywords)
  414. if s:Match(info.plnum, s:continuable_regex) &&
  415. \ s:Match(info.plnum, s:continuation_regex)
  416. if col > 0 && s:IsAssignment(info.pline, col)
  417. if g:ruby_indent_assignment_style == 'hanging'
  418. " hanging indent
  419. let ind = col - 1
  420. else
  421. " align with variable
  422. let ind = indent(info.plnum)
  423. endif
  424. else
  425. let ind = indent(s:GetMSL(info.plnum))
  426. endif
  427. return ind + info.sw + info.sw
  428. endif
  429. return -1
  430. endfunction
  431. function! s:AfterBlockOpening(pline_info) abort
  432. let info = a:pline_info
  433. " If the previous line ended with a block opening, add a level of indent.
  434. if s:Match(info.plnum, s:block_regex)
  435. if g:ruby_indent_block_style == 'do'
  436. " don't align to the msl, align to the "do"
  437. let ind = indent(info.plnum) + info.sw
  438. else
  439. let plnum_msl = s:GetMSL(info.plnum)
  440. if getline(plnum_msl) =~ '=\s*\(#.*\)\=$'
  441. " in the case of assignment to the msl, align to the starting line,
  442. " not to the msl
  443. let ind = indent(info.plnum) + info.sw
  444. else
  445. let ind = indent(plnum_msl) + info.sw
  446. endif
  447. endif
  448. return ind
  449. endif
  450. return -1
  451. endfunction
  452. function! s:AfterLeadingOperator(pline_info) abort
  453. " If the previous line started with a leading operator, use its MSL's level
  454. " of indent
  455. if s:Match(a:pline_info.plnum, s:leading_operator_regex)
  456. return indent(s:GetMSL(a:pline_info.plnum))
  457. endif
  458. return -1
  459. endfunction
  460. function! s:AfterHangingSplat(pline_info) abort
  461. let info = a:pline_info
  462. " If the previous line ended with the "*" of a splat, add a level of indent
  463. if info.pline =~ s:splat_regex
  464. return indent(info.plnum) + info.sw
  465. endif
  466. return -1
  467. endfunction
  468. function! s:AfterUnbalancedBracket(pline_info) abort
  469. let info = a:pline_info
  470. " If the previous line contained unclosed opening brackets and we are still
  471. " in them, find the rightmost one and add indent depending on the bracket
  472. " type.
  473. "
  474. " If it contained hanging closing brackets, find the rightmost one, find its
  475. " match and indent according to that.
  476. if info.pline =~ '[[({]' || info.pline =~ '[])}]\s*\%(#.*\)\=$'
  477. let [opening, closing] = s:ExtraBrackets(info.plnum)
  478. if opening.pos != -1
  479. if !g:ruby_indent_hanging_elements
  480. return indent(info.plnum) + info.sw
  481. elseif opening.type == '(' && searchpair('(', '', ')', 'bW', s:skip_expr) > 0
  482. if col('.') + 1 == col('$')
  483. return indent(info.plnum) + info.sw
  484. else
  485. return virtcol('.')
  486. endif
  487. else
  488. let nonspace = matchend(info.pline, '\S', opening.pos + 1) - 1
  489. return nonspace > 0 ? nonspace : indent(info.plnum) + info.sw
  490. endif
  491. elseif closing.pos != -1
  492. call cursor(info.plnum, closing.pos + 1)
  493. normal! %
  494. if strpart(info.pline, closing.pos) =~ '^)\s*='
  495. " special case: the closing `) =` of an endless def
  496. return indent(s:GetMSL(line('.')))
  497. endif
  498. if s:Match(line('.'), s:ruby_indent_keywords)
  499. return indent('.') + info.sw
  500. else
  501. return indent(s:GetMSL(line('.')))
  502. endif
  503. else
  504. call cursor(info.clnum, info.col)
  505. end
  506. endif
  507. return -1
  508. endfunction
  509. function! s:AfterEndKeyword(pline_info) abort
  510. let info = a:pline_info
  511. " If the previous line ended with an "end", match that "end"s beginning's
  512. " indent.
  513. let col = s:Match(info.plnum, '\%(^\|[^.:@$]\)\<end\>\s*\%(#.*\)\=$')
  514. if col > 0
  515. call cursor(info.plnum, col)
  516. if searchpair(s:end_start_regex, '', s:end_end_regex, 'bW',
  517. \ s:end_skip_expr) > 0
  518. let n = line('.')
  519. let ind = indent('.')
  520. let msl = s:GetMSL(n)
  521. if msl != n
  522. let ind = indent(msl)
  523. end
  524. return ind
  525. endif
  526. end
  527. return -1
  528. endfunction
  529. function! s:AfterIndentKeyword(pline_info) abort
  530. let info = a:pline_info
  531. let col = s:Match(info.plnum, s:ruby_indent_keywords)
  532. if col > 0 && s:Match(info.plnum, s:ruby_endless_def) <= 0
  533. call cursor(info.plnum, col)
  534. let ind = virtcol('.') - 1 + info.sw
  535. " TODO: make this better (we need to count them) (or, if a searchpair
  536. " fails, we know that something is lacking an end and thus we indent a
  537. " level
  538. if s:Match(info.plnum, s:end_end_regex)
  539. let ind = indent('.')
  540. elseif s:IsAssignment(info.pline, col)
  541. if g:ruby_indent_assignment_style == 'hanging'
  542. " hanging indent
  543. let ind = col + info.sw - 1
  544. else
  545. " align with variable
  546. let ind = indent(info.plnum) + info.sw
  547. endif
  548. endif
  549. return ind
  550. endif
  551. return -1
  552. endfunction
  553. function! s:PreviousNotMSL(msl_info) abort
  554. let info = a:msl_info
  555. " If the previous line wasn't a MSL
  556. if info.plnum != info.plnum_msl
  557. " If previous line ends bracket and begins non-bracket continuation decrease indent by 1.
  558. if s:Match(info.plnum, s:bracket_switch_continuation_regex)
  559. " TODO (2016-10-07) Wrong/unused? How could it be "1"?
  560. return indent(info.plnum) - 1
  561. " If previous line is a continuation return its indent.
  562. elseif s:Match(info.plnum, s:non_bracket_continuation_regex)
  563. return indent(info.plnum)
  564. endif
  565. endif
  566. return -1
  567. endfunction
  568. function! s:IndentingKeywordInMSL(msl_info) abort
  569. let info = a:msl_info
  570. " If the MSL line had an indenting keyword in it, add a level of indent.
  571. " TODO: this does not take into account contrived things such as
  572. " module Foo; class Bar; end
  573. let col = s:Match(info.plnum_msl, s:ruby_indent_keywords)
  574. if col > 0 && s:Match(info.plnum_msl, s:ruby_endless_def) <= 0
  575. let ind = indent(info.plnum_msl) + info.sw
  576. if s:Match(info.plnum_msl, s:end_end_regex)
  577. let ind = ind - info.sw
  578. elseif s:IsAssignment(getline(info.plnum_msl), col)
  579. if g:ruby_indent_assignment_style == 'hanging'
  580. " hanging indent
  581. let ind = col + info.sw - 1
  582. else
  583. " align with variable
  584. let ind = indent(info.plnum_msl) + info.sw
  585. endif
  586. endif
  587. return ind
  588. endif
  589. return -1
  590. endfunction
  591. function! s:ContinuedHangingOperator(msl_info) abort
  592. let info = a:msl_info
  593. " If the previous line ended with [*+/.,-=], but wasn't a block ending or a
  594. " closing bracket, indent one extra level.
  595. if s:Match(info.plnum_msl, s:non_bracket_continuation_regex) && !s:Match(info.plnum_msl, '^\s*\([\])}]\|end\)')
  596. if info.plnum_msl == info.plnum
  597. let ind = indent(info.plnum_msl) + info.sw
  598. else
  599. let ind = indent(info.plnum_msl)
  600. endif
  601. return ind
  602. endif
  603. return -1
  604. endfunction
  605. " 4. Auxiliary Functions {{{1
  606. " ======================
  607. function! s:IsInRubyGroup(groups, lnum, col) abort
  608. let ids = map(copy(a:groups), 'hlID("ruby".v:val)')
  609. return index(ids, synID(a:lnum, a:col, 1)) >= 0
  610. endfunction
  611. " Check if the character at lnum:col is inside a string, comment, or is ascii.
  612. function! s:IsInStringOrComment(lnum, col) abort
  613. return s:IsInRubyGroup(s:syng_strcom, a:lnum, a:col)
  614. endfunction
  615. " Check if the character at lnum:col is inside a string.
  616. function! s:IsInString(lnum, col) abort
  617. return s:IsInRubyGroup(s:syng_string, a:lnum, a:col)
  618. endfunction
  619. " Check if the character at lnum:col is inside a string or documentation.
  620. function! s:IsInStringOrDocumentation(lnum, col) abort
  621. return s:IsInRubyGroup(s:syng_stringdoc, a:lnum, a:col)
  622. endfunction
  623. " Check if the character at lnum:col is inside a string delimiter
  624. function! s:IsInStringDelimiter(lnum, col) abort
  625. return s:IsInRubyGroup(
  626. \ ['HeredocDelimiter', 'PercentStringDelimiter', 'StringDelimiter'],
  627. \ a:lnum, a:col
  628. \ )
  629. endfunction
  630. function! s:IsAssignment(str, pos) abort
  631. return strpart(a:str, 0, a:pos - 1) =~ '=\s*$'
  632. endfunction
  633. " Find line above 'lnum' that isn't empty, in a comment, or in a string.
  634. function! s:PrevNonBlankNonString(lnum) abort
  635. let in_block = 0
  636. let lnum = prevnonblank(a:lnum)
  637. while lnum > 0
  638. " Go in and out of blocks comments as necessary.
  639. " If the line isn't empty (with opt. comment) or in a string, end search.
  640. let line = getline(lnum)
  641. if line =~ '^=begin'
  642. if in_block
  643. let in_block = 0
  644. else
  645. break
  646. endif
  647. elseif !in_block && line =~ '^=end'
  648. let in_block = 1
  649. elseif !in_block && line !~ '^\s*#.*$' && !(s:IsInStringOrComment(lnum, 1)
  650. \ && s:IsInStringOrComment(lnum, strlen(line)))
  651. break
  652. endif
  653. let lnum = prevnonblank(lnum - 1)
  654. endwhile
  655. return lnum
  656. endfunction
  657. " Find line above 'lnum' that started the continuation 'lnum' may be part of.
  658. function! s:GetMSL(lnum) abort
  659. " Start on the line we're at and use its indent.
  660. let msl = a:lnum
  661. let lnum = s:PrevNonBlankNonString(a:lnum - 1)
  662. while lnum > 0
  663. " If we have a continuation line, or we're in a string, use line as MSL.
  664. " Otherwise, terminate search as we have found our MSL already.
  665. let line = getline(lnum)
  666. if !s:Match(msl, s:backslash_continuation_regex) &&
  667. \ s:Match(lnum, s:backslash_continuation_regex)
  668. " If the current line doesn't end in a backslash, but the previous one
  669. " does, look for that line's msl
  670. "
  671. " Example:
  672. " foo = "bar" \
  673. " "baz"
  674. "
  675. let msl = lnum
  676. elseif s:Match(msl, s:leading_operator_regex)
  677. " If the current line starts with a leading operator, keep its indent
  678. " and keep looking for an MSL.
  679. let msl = lnum
  680. elseif s:Match(lnum, s:splat_regex)
  681. " If the above line looks like the "*" of a splat, use the current one's
  682. " indentation.
  683. "
  684. " Example:
  685. " Hash[*
  686. " method_call do
  687. " something
  688. "
  689. return msl
  690. elseif s:Match(lnum, s:non_bracket_continuation_regex) &&
  691. \ s:Match(msl, s:non_bracket_continuation_regex)
  692. " If the current line is a non-bracket continuation and so is the
  693. " previous one, keep its indent and continue looking for an MSL.
  694. "
  695. " Example:
  696. " method_call one,
  697. " two,
  698. " three
  699. "
  700. let msl = lnum
  701. elseif s:Match(lnum, s:dot_continuation_regex) &&
  702. \ (s:Match(msl, s:bracket_continuation_regex) || s:Match(msl, s:block_continuation_regex))
  703. " If the current line is a bracket continuation or a block-starter, but
  704. " the previous is a dot, keep going to see if the previous line is the
  705. " start of another continuation.
  706. "
  707. " Example:
  708. " parent.
  709. " method_call {
  710. " three
  711. "
  712. let msl = lnum
  713. elseif s:Match(lnum, s:non_bracket_continuation_regex) &&
  714. \ (s:Match(msl, s:bracket_continuation_regex) || s:Match(msl, s:block_continuation_regex))
  715. " If the current line is a bracket continuation or a block-starter, but
  716. " the previous is a non-bracket one, respect the previous' indentation,
  717. " and stop here.
  718. "
  719. " Example:
  720. " method_call one,
  721. " two {
  722. " three
  723. "
  724. return lnum
  725. elseif s:Match(lnum, s:bracket_continuation_regex) &&
  726. \ (s:Match(msl, s:bracket_continuation_regex) || s:Match(msl, s:block_continuation_regex))
  727. " If both lines are bracket continuations (the current may also be a
  728. " block-starter), use the current one's and stop here
  729. "
  730. " Example:
  731. " method_call(
  732. " other_method_call(
  733. " foo
  734. return msl
  735. elseif s:Match(lnum, s:block_regex) &&
  736. \ !s:Match(msl, s:continuation_regex) &&
  737. \ !s:Match(msl, s:block_continuation_regex)
  738. " If the previous line is a block-starter and the current one is
  739. " mostly ordinary, use the current one as the MSL.
  740. "
  741. " Example:
  742. " method_call do
  743. " something
  744. " something_else
  745. return msl
  746. else
  747. let col = match(line, s:continuation_regex) + 1
  748. if (col > 0 && !s:IsInStringOrComment(lnum, col))
  749. \ || s:IsInString(lnum, strlen(line))
  750. let msl = lnum
  751. else
  752. break
  753. endif
  754. endif
  755. let lnum = s:PrevNonBlankNonString(lnum - 1)
  756. endwhile
  757. return msl
  758. endfunction
  759. " Check if line 'lnum' has more opening brackets than closing ones.
  760. function! s:ExtraBrackets(lnum) abort
  761. let opening = {'parentheses': [], 'braces': [], 'brackets': []}
  762. let closing = {'parentheses': [], 'braces': [], 'brackets': []}
  763. let line = getline(a:lnum)
  764. let pos = match(line, '[][(){}]', 0)
  765. " Save any encountered opening brackets, and remove them once a matching
  766. " closing one has been found. If a closing bracket shows up that doesn't
  767. " close anything, save it for later.
  768. while pos != -1
  769. if !s:IsInStringOrComment(a:lnum, pos + 1)
  770. if line[pos] == '('
  771. call add(opening.parentheses, {'type': '(', 'pos': pos})
  772. elseif line[pos] == ')'
  773. if empty(opening.parentheses)
  774. call add(closing.parentheses, {'type': ')', 'pos': pos})
  775. else
  776. let opening.parentheses = opening.parentheses[0:-2]
  777. endif
  778. elseif line[pos] == '{'
  779. call add(opening.braces, {'type': '{', 'pos': pos})
  780. elseif line[pos] == '}'
  781. if empty(opening.braces)
  782. call add(closing.braces, {'type': '}', 'pos': pos})
  783. else
  784. let opening.braces = opening.braces[0:-2]
  785. endif
  786. elseif line[pos] == '['
  787. call add(opening.brackets, {'type': '[', 'pos': pos})
  788. elseif line[pos] == ']'
  789. if empty(opening.brackets)
  790. call add(closing.brackets, {'type': ']', 'pos': pos})
  791. else
  792. let opening.brackets = opening.brackets[0:-2]
  793. endif
  794. endif
  795. endif
  796. let pos = match(line, '[][(){}]', pos + 1)
  797. endwhile
  798. " Find the rightmost brackets, since they're the ones that are important in
  799. " both opening and closing cases
  800. let rightmost_opening = {'type': '(', 'pos': -1}
  801. let rightmost_closing = {'type': ')', 'pos': -1}
  802. for opening in opening.parentheses + opening.braces + opening.brackets
  803. if opening.pos > rightmost_opening.pos
  804. let rightmost_opening = opening
  805. endif
  806. endfor
  807. for closing in closing.parentheses + closing.braces + closing.brackets
  808. if closing.pos > rightmost_closing.pos
  809. let rightmost_closing = closing
  810. endif
  811. endfor
  812. return [rightmost_opening, rightmost_closing]
  813. endfunction
  814. function! s:Match(lnum, regex) abort
  815. let line = getline(a:lnum)
  816. let offset = match(line, '\C'.a:regex)
  817. let col = offset + 1
  818. while offset > -1 && s:IsInStringOrComment(a:lnum, col)
  819. let offset = match(line, '\C'.a:regex, offset + 1)
  820. let col = offset + 1
  821. endwhile
  822. if offset > -1
  823. return col
  824. else
  825. return 0
  826. endif
  827. endfunction
  828. " Locates the containing class/module's definition line, ignoring nested classes
  829. " along the way.
  830. "
  831. function! s:FindContainingClass() abort
  832. let saved_position = getpos('.')
  833. while searchpair(s:end_start_regex, s:end_middle_regex, s:end_end_regex, 'bW',
  834. \ s:end_skip_expr) > 0
  835. if expand('<cword>') =~# '\<class\|module\>'
  836. let found_lnum = line('.')
  837. call setpos('.', saved_position)
  838. return found_lnum
  839. endif
  840. endwhile
  841. call setpos('.', saved_position)
  842. return 0
  843. endfunction
  844. " }}}1
  845. let &cpo = s:cpo_save
  846. unlet s:cpo_save
  847. " vim:set sw=2 sts=2 ts=8 et: