How to run a vim script that modifies the current buffer?

I am trying to write a beautify.vim script that makes C-like code tied to a standard that I can read easily.

My file contains only wildcard commands starting with %s/...

However, when I try to run a script with an open file in the order :source beautify.vimor :runtime beautify.vim, it starts, but all the substitution commands state that their template was not found (the samples were tested by entering them manually and should work).

Is there a way to get vim to run commands in the context of the current buffer?

beautify.vim:

" add spaces before open braces
sil! :%s/\%>1c\s\@<!{/ {/g
" beautify for
sil! :%s/for *( *\([^;]*\) *; *\([^;]*\) *; *\([^;]*\) *)/for (\1; \2; \3)/
" add spaces after commas
sil! :%s/,\s\@!/, /g

In my tests, the first command: s must match (it matches when applied manually).

+3
source share
1 answer

script, , ; , , .

" {{{ regex silly beautifier (avoids strings, works with ranges)
function! Foo_SillyRegexBeautifier(start, end)

    let i = a:start
    while i <= a:end
        let line = getline(i)

        " ignore preprocessor directives
        if match(line, '^\s*#') == 0
            let i += 1
            continue
        endif

        " ignore content of strings, splitting at double quotes characters not 
        " preceded by escape characters
        let chunks = split(line, '\(\([^\\]\|^\)\\\(\\\\\)*\)\@<!"', 1)

        let c = 0
        for 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 like this by calling substitute() on chunk and 
            " reassigning it
            " ...

            let chunks[c] = chunk
        endfor

        let line = join(chunks, '"')

        " remove spaces at the end of the line
        let line = substitute(line, '\s\+$', '', '')

        call setline(i, line)

        let i += 1
    endw
endfunction
" }}}

, , . , , .

nnoremap ,bf :call Foo_SillyRegexBeautifier(0, line('$'))<CR>
vnoremap ,bf :call Foo_SillyRegexBeautifier(line("'<"), line("'>"))<CR>
+3

Source: https://habr.com/ru/post/1795115/


All Articles