Question

I am trying to compose a Vim script function to help format where the left braces are located at in C like functions blocks.

function! FixLeftBraces()
    "Set the cursor to the top of the file
    call cursor(1,0)
    while search(".\+{",'We') > 0
        exe "normal i\n\e"
    endwhile
endfunction

In this example my goal is to locate the left curly bracket that is on the same line as the function and relocate it to the next line. The We options prevent wrapping the file and reposition the cursor to the end of the search selection respectively.

When I perform a search in Vim using / mode entering in /.\+{ performs a search and highlights lines that I expect it to in source code.

For example C lines such as:

//is highlighted
int main(){

//is not highlighted
void otherFuncion()
{

When I use the created FixLeftBraces() after sourcing it, it does not appear to work. It just runs and does nothing.

If I change the search to search("{",'We') then FixLeftBraces() runs but adds a new line after every left curly bracket. So I am confused why FixLeftBraces() does not work with the search(".\+{",'We').

Was it helpful?

Solution

On the mentioned test cases, the search() function call keeps returning zero and, therefore, the whole function does not work as expected. The reason of that is incorrectly specified pattern. There are not a few special characters that can be added into a double-quoted string constant using \-syntax (see :help expr-"). Consequently, the \+ substring in the regexp literal is interpreted as a single + character, and the original intention of the pattern is mangled.

To avoid this undesirable behavior, escape the backslash symbol changing the pattern string to

".\\+{"

or switch to single-quoted string literal where backslashes do not have a special meaning (see :help expr-'),

'.\+{'
Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top