How do I run a vim script that alters the current buffer? -
i'm trying write beautify.vim script makes c-like code adhere standard can read.
my file contains substitution commands begin %s/...
however, when try run script file open, in manner :source beautify.vim
, or :runtime beautify.vim
, runs substitute commands state pattern wasn't found (patterns tested entering them manually , should work).
is there way make vim run commands in context of current buffer?
beautify.vim:
" add spaces before open braces sil! :%s/\%>1c\s\@<!{/ {/g " beautify sil! :%s/for *( *\([^;]*\) *; *\([^;]*\) *; *\([^;]*\) *)/for (\1; \2; \3)/ " add spaces after commas sil! :%s/,\s\@!/, /g
in tests first :s command should match (it matches when applied manually).
i wrote similar beautifier script implemented in think more flexible way; plus, tried come mechanism avoid substituting stuff within strings.
" {{{ regex silly beautifier (avoids strings, works ranges) function! foo_sillyregexbeautifier(start, end) let = a:start while <= a:end let line = getline(i) " ignore preprocessor directives if match(line, '^\s*#') == 0 let += 1 continue endif " ignore content of strings, splitting @ double quotes characters not " preceded escape characters let chunks = split(line, '\(\([^\\]\|^\)\\\(\\\\\)*\)\@<!"', 1) let c = 0 c in range(0, len(chunks), 2) let chunk = chunks[c] " add whitespace in couples let chunk = substitute(chunk, '[?({\[,]', '\0 ', 'g') let chunk = substitute(chunk, '[?)}\]]', ' \0', 'g') " continue calling substitute() on chunk , " reassigning " ... let chunks[c] = chunk endfor let line = join(chunks, '"') " remove spaces @ end of line let line = substitute(line, '\s\+$', '', '') call setline(i, line) let += 1 endw endfunction " }}}
then define mapping affects whole file in normal mode, , selected lines in visual mode. when have formatted parts of file don't want touch.
nnoremap ,bf :call foo_sillyregexbeautifier(0, line('$'))<cr> vnoremap ,bf :call foo_sillyregexbeautifier(line("'<"), line("'>"))<cr>
Comments
Post a Comment