Skip to content

Instantly share code, notes, and snippets.

@ptone
Created July 28, 2011 23:08
Show Gist options
  • Save ptone/1112783 to your computer and use it in GitHub Desktop.
Save ptone/1112783 to your computer and use it in GitHub Desktop.
getting and replacing selection in vim
if !has('python')
echo "Error: Required vim compiled with +python"
finish
endif
" Vim comments start with a double quote.
" Function definition is VimL. We can mix VimL and Python in
" function definition.
" function! MakeChoices()
" We start the python code like the next line.
python << EOF
# the vim module contains everything we need to interface with vim from
# python. We need urllib2 for the web service consumer.
import vim
import re
import sys
def sanitize_enum(s):
# @@ plenty to improve here
s = s.upper().strip(' ()')
s = re.sub('^[-\d ]+','',s)
s = re.sub('[./() \-]', "_",s)
while re.search('__',s):
s = s.replace('__','_')
return s
def format_choice(t):
return " ( %s, '%s' )," % t
def make_choices(s):
#display_list = vim.current.range[:]
display_list = s.split('\n')
choices = []
i = 1
explicit = True
range_replacement = []
print len(display_list)
for choice in display_list:
if choice:
if explicit:
sanitized = sanitize_enum(choice)
# print "%s = %s" % (sanitized,i)
range_replacement.append("%s = %s" % (sanitized,i))
choices.append((sanitized,choice.strip()))
else:
choices.append((i,choice.strip()))
i+=1
range_replacement.append("choices = (")
for c in choices:
range_replacement.append(format_choice(c))
range_replacement.append(" )")
print '\n'.join(range_replacement)
#vim.current.buffer[:] = range_replacement
EOF
" Here the python code is closed. We can continue writing VimL or python again.
" endfunction
command! -range Mchoice python make_choices('<,'>)
" command! -nargs=0 Mchoices call MakeChoices()
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment