Saturday, September 24, 2011

Re: Shortcut for convertion between different naming conventions

On 09/24/11 11:25, Peng Yu wrote:
> I'm wondering if there are existing shortcuts in vim for convertion
> between different name conventions (see example below). I feel that it
> will will be convenient if there are such shortcuts.
>
> OneFileName
> oneFileName
> one_file_name
> one.file.name
> ONE_FILE_NAME
> _one_file_name

I don't know of anything natively. Except for the "add an extra
underscore" version, the function below successfully sniffs and
transforms strings, so if you wrap it in a mapping/function to
pass the appropriate text under the cursor to the function and
replace it with the output, it should do the trick.

-tim

function! ChangeUp(s)
" b:case: 0=title, 1=lower, 2=caps
" b:sep: 0=none, 1=underscore, 2=period
if a:s =~ '^[A-Z]*\%(_[A-Z]*\)*$'
let b:case = 2
let b:sep = 1
elseif a:s =~ '^[A-Z]*\%(\.[A-Z]*\)*$'
let b:case = 2
let b:sep = 2
elseif a:s =~ '^[a-z]*\%(_[a-z]*\)*$'
let b:case = 1
let b:sep = 1
elseif a:s =~ '^[a-z]*\%(\.[a-z]*\)*$'
let b:case = 1
let b:sep = 2
elseif a:s =~ '^[A-Z][a-z]*\%(_[A-Z][a-z]*\)*$'
let b:case = 0
let b:sep = 1
elseif a:s =~ '^[A-Z][a-z]*\%(\.[A-Z][a-z]*\)*$'
let b:case = 0
let b:sep = 2
elseif a:s =~ '^[A-Z][a-z]*\%([A-Z][a-z]*\)*$'
let b:case = 0
let b:sep = 0
else
return a:s
endif
let l:splitter = {0: '[A-Z][a-z]*\zs', 1: '_', 2:'\.'}[b:sep]
let l:bits = split(a:s, l:splitter)
let b:case = (b:case + 1) % 3
if !b:case " we've reset back to 0, so bump b:sep
let b:sep = (b:sep + 1) % 3
endif
if b:sep == 0 && b:case != 0
" not undoable so set case to something that is
let b:case = 0
let b:sep = (b:sep + 1) % 3
endif
let l:expr = 'substitute(v:val, ''\(.\)\(.*\)'', '''.({ 0:
'\u\1\L\2', 1: '\L&', 2: '\U&'}[b:case]).''', "")'
let l:bits = map(l:bits, l:expr)

return join(l:bits, { 0: '', 1: '_', 2: '.', }[b:sep])
endfunction

function! TestChangeUp()
let l:start = 'ThisIsATest'
let l:s = l:start
let l:temp = ''
while l:temp != l:start
let l:temp = ChangeUp(l:s)
echo string(l:s).'->'.string(l:temp)
let l:s = l:temp
echo repeat('-', 50)
endwhile
endfunction

--
You received this message from the "vim_use" maillist.
Do not top-post! Type your reply below the text you are replying to.
For more information, visit http://www.vim.org/maillist.php

No comments:

Post a Comment