While using Sublime Text, when I type the first parenthesis, bracket, or curly bracket, Sublime Text automatically does the second one for me.



And while making an if statement, for loop, or while loop, when I move both the braces (curly brackets) to the next line and press Enter while my cursor is in the middle of the two braces, Sublime Text automatically puts the second brace in the next line and "tabs" my cursor in the middle of the two braces.

How can I configure VIM to do this? :)

  • 1
    There's a number of plugins that does this. I remember seeing a "plain" solution somewhere on here involving manual remaps, but even the plugins rarely include auto-formatting AFAIK.
    – Zoe
    Jun 28 '21 at 17:10
  • One plugin you could look into is ultisnips
    – mattb
    Jun 28 '21 at 17:27
  • Have you looked at delimitMate? stackoverflow.com/questions/8958357/… for more information.
    – DDay
    Jun 28 '21 at 20:37
  • 1
    Welcome to the site! I just posted an answer below.. Let me know if it helps!
    – husB
    Jun 29 '21 at 3:09
  • Try looking into auto-pairs.
    – Heptite
    Jun 30 '21 at 0:30

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
  • OMG! Thank you, thank you, thank you!!! I can't upvote your answer enough!!!
    – Wade Wayne
    Jul 4 '21 at 11:38
  • Most welcome, happy to help :)
    – husB
    Jul 5 '21 at 9:50

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.