Skip to content

Instantly share code, notes, and snippets.

@ichizok
Created November 26, 2019 07:59
Show Gist options
  • Save ichizok/0235932e540e69d21983d9045ed55eb1 to your computer and use it in GitHub Desktop.
Save ichizok/0235932e540e69d21983d9045ed55eb1 to your computer and use it in GitHub Desktop.
snake2camel
" Mutual conversion between snake-case and camel-case
if exists('g:loaded_snake2camel')
finish
endif
let g:loaded_snake2camel = 1
let s:cpo_save = &cpo
set cpo&vim
function! Snake2Camel(str, ...) abort
" 2nd argument directs case conversion of the initial character:
" none or -1: keep case (default)
" 0: to lower
" 1: to upper
let init_conv = get(a:000, 0, -1)
let [str, _, i] = matchstrpos(a:str, '^_*.')
return (init_conv < 0 ? str
\ : (init_conv > 0 ? toupper(str) : tolower(str)))
\ .. substitute(tolower(a:str[i:]), '_\+\(.\)', '\u\1', 'g')
endfunction
function! Camel2Snake(str, ...) abort
" 2nd argument directs case conversion of the entire string:
" none or -1: keep case (default)
" 0: to lower
" 1: to upper
let init_conv = get(a:000, 0, -1)
let str = substitute(a:str, '\C[a-z]\zs[^a-z]', '_&', 'g')
let str = substitute(str, '\C[A-Z0-9]\zs[A-Z][a-z]', '_&', 'g')
return init_conv < 0 ? str
\ : (init_conv > 0 ? toupper(str) : tolower(str))
endfunction
let &cpo = s:cpo_save
unlet s:cpo_save
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment