Skip to content

Instantly share code, notes, and snippets.

@bootleq
Last active October 14, 2020 05:54
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save bootleq/9a9a74829233df95d7d64c95c086b909 to your computer and use it in GitHub Desktop.
Save bootleq/9a9a74829233df95d7d64c95c086b909 to your computer and use it in GitHub Desktop.
vimrc snippet
" camelCase / under_score / kekab-case 轉換
function! s:case_tx_subs_camel(w) "{{{
let w = substitute(a:w, '-', '_', 'g')
return substitute(w, '_\([a-z]\)', '\u\1', 'g')
endfunction "}}}
function! s:case_tx_subs_kekab(w) "{{{
let w = s:case_tx_subs_snake(a:w)
return tr(w, '_', '-')
endfunction "}}}
function! s:case_tx_subs_snake(w) "{{{
let w = substitute(a:w, '-', '_', 'g')
return substitute(w, '\C[A-Z]', '_\L\0', 'g')
endfunction "}}}
let s:case_tx_patterns = {
\ 'snake': '_',
\ 'kekab': '-',
\ 'camel': '\C[a-z][A-Z]',
\ }
function! WordTransform()
let save_isk = &l:iskeyword
let cases = get(b:, 'case_tx_cases', ['snake', 'camel'])
try
let &l:isk = '@,48-57,-,_'
let w = expand("<cword>")
let x = ''
let c = strpart(getline('.'), col('.') - 1, 1)
for [k, pattern] in items(s:case_tx_patterns)
if match(w, pattern) > -1
let next_k = get(repeat(cases, 2), index(cases, k) + 1)
let x = call(function('s:case_tx_subs_' . next_k), [w])
silent! call repeat#set(',x') " must match your mapping to WordTransform()
break
end
endfor
if x == w || empty(x)
echohl WarningMsg | echomsg "Nothing to transform." | echohl None
return
endif
if match(w, c) < 0 " cursor might sit before keyword
execute "normal! f" . strpart(w, 0, 1)
execute "normal! \"_ciw\<C-R>=x\<CR>"
else
execute "normal! \"_ciw\<C-R>=x\<CR>"
endif
finally
let &l:isk = save_isk
endtry
endfunction
nnoremap <silent> <LocalLeader>x :call WordTransform()<CR>
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment