The linked question in the comments provides some options for what you're looking to achieve. In particular, without any plugins, one can use the solution from this answer
inoremap ( ()<Left>
inoremap [ []<Left>
inoremap { {}<Left>
This accomplishes the automatic closing of parenthesis and brackets when you type (
,[
,{
, in insert mode.
For your second question, it can also be done without any plugins:
inoremap <expr> <CR> search('{\%#}', 'n') ? "\<CR>\<CR>\<Up>\<C-f>" : "\<CR>"
Here's the breakdown:
inoremap <expr> <CR> --- map the <CR> key using an expression
search('{\%#}', 'n') ? --- is the cursor ('\%#') between '{'and '}' ?
"\<CR>\<CR>\<Up>\<C-f>" --- if so, press <CR> twice, go <Up> a line, and autoindent (<C-f>),
: --- otherwise,
"\<CR>" --- press <CR>.
This checks if the cursor is between {
and }
, but does not check if the previous line starts with if
, while
, or for
. You can do so by modifying the search()
. That is, instead of
search('{\%#}', 'n')
, we can use search('\(if\|while\|for\)\s*(.*)\s*$\n^\s*{\%#}', 'n')
.
For more, see
:h map-expr
:h expr-quote
:h pattern-overview