Oscar Godson
Oscar Godson

Reputation: 32736

Making a command only run in certain cases in Vim

I'm trying to figure out how to get this command to only run in certain cases:

au BufNewFile,BufRead *.js imap <buffer> {<cr> {<cr>}<c-o>O<Tab><Down>;<Up>

Examples:

// No!
if () {
}

// YES!
foo.x = function () {
};

// YES!
var x = {
  // NO!
  y: function () {
  }
};

// YES!
foo(function () {
});

So the pattern would be, NO semi IF it starts with for|switch|if|else|if else (and whatever else) OR if there is a : on the same line.

I really don't even know where to look.

Upvotes: 2

Views: 76

Answers (1)

Kent
Kent

Reputation: 195169

you could try mapping with <expr>.

I wrote a function, which returns the mapping you need with or without the semi. :

fun! Mapping()
    return "{\<cr>}\<c-o>O\<Tab>\<Down>".(getline('.') =~# '^\s*for\s\|if\s\|else\s'||getline('.') =~# ':'? '' : ';')."\<up>"
endfunction

then you could add this mapping into your au

inoremap <buffer> <expr> {<cr> Mapping()

note that I didn't put all the keywords in the line, I just added if else for as example. you could add other keywords and test.

Upvotes: 1

Related Questions