diff options
-rw-r--r-- | plugin/casefmt.vim | 62 |
1 files changed, 62 insertions, 0 deletions
diff --git a/plugin/casefmt.vim b/plugin/casefmt.vim index 3717925..8471578 100644 --- a/plugin/casefmt.vim +++ b/plugin/casefmt.vim @@ -170,3 +170,65 @@ endfunction function! s:to_dashed(s) abort return substitute(a:s, '_', '-', 'g') endfunction + + +" Replaces "search" with "replace" across a given range, but rather than replace +" verbatim, replace respecting the case format given. +function! s:case_substitute(start, end, search, replace, ...) + if a:0 > 1 + throw "Command takes either 2 or 3 arguments!" + endif + + let flags = a:0 == 1 ? a:1 : 'cCksS' + + for c in flags + if ! has_key(s:case_fmts, c) + throw "Unknown case format: " . c + endif + endfor + + let search_norm = s:normalize(a:search) + let replace_norm = s:normalize(a:replace) + + for c in flags + let l:Func = function("\<SID>" . s:case_fmts[c]) + exec printf("silent! %d,%ds/\\V%s/%s/g", a:start, a:end, l:Func(escape(search_norm, '\')), l:Func(escape(replace_norm, '\'))) + endfor + +endfunction + +" CaseSubstitute command. +" +" [range] CaseSubstitute <search> <replace> [flags] +" +" This command acts similarly to substitute, except it respects the case format +" of what it is trying to replace. For example: +" +" Running +" +" CaseSubstitute TestThing DoThing +" +" on +" +" TestThing DoThing +" testThing doThing +" test_thing -> do_thing +" Test_Thing Do_Thing +" TEST_THING DO_THING +" +" flags contain the case formats to replace. Default is 'cCksS' for: +" +" [c]amelCase +" [C]amelCase +" [k]ONSTANT_CASE +" [s]nake_case +" [S]nake_Case +" +" does not include +" +" [T]itle Case +" [t]itle case +" [K]ONSTANT CASE +" [-]dashed-case +command! -range -nargs=+ CaseSubstitute + \ call <SID>case_substitute(<line1>, <line2>, <f-args>) |