Custom Autoclose Mappings

Extra tip: source external files into your .vimrc

image

A very handy feature that most users miss when starting to use vim, is the autoclose feature present in IDEs and popular code editors.

Some Vim users goes straight to install some plugins like auto pairs or autoclose but, since autoclosing isn’t a complex feature, I created some simple mappings to solve it and that’s what I’ll present here!

I’m about to show you the autoclose mappings I created for my daily use, and I hope you enjoy using it and customizing it to fit your needs.

First, let’s describe the use cases and how to use it, then, I’ll give you the code and two different options of adding it to your vim configurations:

  • Simply pasting to your .vimrc file
  • Saving on an external autoclosing.vim file, and sourcing it on your .vimrc file.

(Yes, you can separate your configs in files to improve readability and easy toggling!)


What to close?

Since I use and recommend Emmet to handle HTML related automations I only set up autoclosing for:

  • Single quotes ' '
  • Backticks ``
  • Double quotes " "
  • Parenthesis ( )
  • Brackets [ ]
  • Curly Brackets { }

Autoclose use cases:

There’s a few use cases with different behaviours expected from autoclosing shortcuts.

Attention:

For each case shown below there’s only one example, but keep in mind that these mappings will work for all character listed before: '' `` ** () [] {}

1. Close and let me write inside

( + type content...

It’s the basic use case, you just want to hit ( to have the closing parenthesis added plus you cursor inside the parenhtesis to write inside.

image

2. Leave it empty and autoclose

( + <Tab>

Since the basic behaviour is to autoclose and bring your cursor inside, I use the <Tab> key (->|) to leave it empty, close and move the cursor outside.

image

3. Autoclose 2 lines below and let me start writing in the middle

{ + <Enter> + type content...

That’s a very common use case too, for functions, etc. You want a block to be opened and you want to start writing in the middle.

image

4. Autoclose adding comma ( , ) or semicolon ( ; ) in the end

It’s a variant that you can use on both 3 cases presented before. You usually need to open a block that is followed by comma (arrays, stirngs in arrays, etc) or semicolon (writing code blocks, strings, function calls) in many programming languages, and you’re gonna do it easy by typing comma or semicolon after the opening character.

CASE 1 & 4: (+;+type content...

image

CASE 2 & 4: (+;+<Tab>

image

CASE 3 & 4: { +;+ <Enter> + type content...

image

General usage tips:

  • The characters that are also used for accentuantions, ' single quote, ` backtick, and " double quote may require you to hit space <Space> after it, since it waits for a letter to accentuate.
  • You can use <C-w> (Ctrl + w) on INSERT MODE to undo a mistyped autoclose, if it’s all written in the same line (like cases 1 and 2).

Update: (Thanks Jacob Degling for this comment on twitter):

  • You can use <Esc> + A to jump to the end of the line, after fulfilling an autoclosed parenthesis (like case 1), but I prefer to use some custom mappings for single movements on insert mode (I also added this mappings on the end of this article).

Finally, the Mappings!

If you’re not familiar with mappings and would like to know more, I wrote this article explaining the basics.

Here’s the code:

"-- AUTOCLOSE --  
"autoclose and position cursor to write text inside  
inoremap ' ''<left>  
inoremap ` ``<left>  
inoremap " ""<left>  
inoremap ( ()<left>  
inoremap [ []<left>  
inoremap { {}<left>  
"autoclose with ; and position cursor to write text inside  
inoremap '; '';<left><left>  
inoremap `; ``;<left><left>  
inoremap "; "";<left><left>  
inoremap (; ();<left><left>  
inoremap [; [];<left><left>  
inoremap {; {};<left><left>  
"autoclose with , and position cursor to write text inside  
inoremap ', '',<left><left>  
inoremap `, ``,<left><left>  
inoremap ", "",<left><left>  
inoremap (, (),<left><left>  
inoremap [, [],<left><left>  
inoremap {, {},<left><left>  
"autoclose and position cursor after  
inoremap '<tab> ''  
inoremap `<tab> ``  
inoremap "<tab> ""  
inoremap (<tab> ()  
inoremap [<tab> []  
inoremap {<tab> {}  
"autoclose with ; and position cursor after  
inoremap ';<tab> '';  
inoremap `;<tab> ``;  
inoremap ";<tab> "";  
inoremap (;<tab> ();  
inoremap [;<tab> [];  
inoremap {;<tab> {};  
"autoclose with , and position cursor after  
inoremap ',<tab> '',  
inoremap `,<tab> ``,  
inoremap ",<tab> "",  
inoremap (,<tab> (),  
inoremap [,<tab> [],  
inoremap {,<tab> {},  
"autoclose 2 lines below and position cursor in the middle   
inoremap '<CR> '<CR>'<ESC>O  
inoremap `<CR> `<CR>`<ESC>O  
inoremap "<CR> "<CR>"<ESC>O  
inoremap (<CR> (<CR>)<ESC>O  
inoremap [<CR> [<CR>]<ESC>O  
inoremap {<CR> {<CR>}<ESC>O  
"autoclose 2 lines below adding ; and position cursor in the middle   
inoremap ';<CR> '<CR>';<ESC>O  
inoremap `;<CR> `<CR>`;<ESC>O  
inoremap ";<CR> "<CR>";<ESC>O  
inoremap (;<CR> (<CR>);<ESC>O  
inoremap [;<CR> [<CR>];<ESC>O  
inoremap {;<CR> {<CR>};<ESC>O  
"autoclose 2 lines below adding , and position cursor in the middle   
inoremap ',<CR> '<CR>',<ESC>O  
inoremap `,<CR> `<CR>`,<ESC>O  
inoremap ",<CR> "<CR>",<ESC>O  
inoremap (,<CR> (<CR>),<ESC>O  
inoremap [,<CR> [<CR>],<ESC>O  
inoremap {,<CR> {<CR>},<ESC>O

You can simply paste it to your .vimrc file…

… or you can keep it as an external config by:

  • Create a custom config/ folder inside your Vim folder (~/.vim/config/)
  • Open a new file called autoclosing.vim, paste the mappings on this file and save it.
  • Open your .vimrc file, add the following code, save and close:
"-- EXTERNAL CONFIGS --
source ~/.vim/config/autoclose.vim

By using a group of configurations as an external file sourced into .vimrc, you have the benefit of a cleaner settings structure, and also the benefit of toggling a group of settings (like autoclosing) by commenting only one line.

EXTRA: Mappings for single movements

After getting this comment on twitter I decided to bring some other mappings that I use a lot and fits well with the autoclosings presented here:

"(I use comma ',' as Leader key since it feels close to my fingers)

let mapleader = "\,";

"-- QUICK MOVEMENTS ON INSERT MODE --

"single movements h j k l
noremap! <Leader>h <left>
noremap! <Leader>j <down>
noremap! <Leader>k <up>
noremap! <Leader>l <right>

"append shortcuts
noremap! <Leader>A <esc>A
noremap! <Leader>a <esc>a

"new line and insert shortcuts
noremap! <Leader>O <esc>O
noremap! <Leader>o <esc>o

Using this mappings you can easily type , + the movement desired, for me it feels easier and closer than doing with <Esc> key or <C-o>.

That’s it! Now you can open up vim again, start playing with your custom made autoclose settings, and refactor that to fit your needs!

If you use a different solution for autoclosing, or even if you managed to improve the solution presented here, please please leave a comment! Thank you very much 🙌 !


(👆 This is an affiliate link. If you got any value from this post and are also interested in buying the MVQ book/screencasts, please consider visiting the affiliate link and you’ll be gifting me a coffee ☕ or a beer 🍺.)


Footnotes:

  • Follow me on Twitter to get more posts like this and other quick tips in your feed.
  • alldrops.info is the TRUE and FOREVER FREE home for the previously used medium.com/vim-drops publication. At alldrops.info you’ll always find all posts without Medium.com restrictions.
  • If you have any doubts or tips about this article, I’d appreciate knowing and discussing it via email.
  • Do you have any other Vim tips? Would you like to publish that in this blog? Please send an email to vim drops.
  • As English is not my native language, I apologize for the errors. Corrections are welcome.
  • Contact: vim [@] alldrops [.] info.

Read more on vim drops: