A Better Format for JSX With Vim

March 23, 2021vimtip slips

What Makes it Better?

For those gang who prefer "4 indentation" then this would make the code much tidier, because:

  • Indent javacript with 4 spaces
  • Indent html with 2 spaces

How?

  1. Make a vim function to convert the default indentation to 2
  2. Write normal JSX code
  3. Select the JSX code which needs to be indented with 2 (usually the render() method) and apply the function in step.1

1. Vim Function to Convert Code Indent to 2

Put this on .vimrc or after/ftplugin/javascript.vim

fun! Four2Two() range
    set expandtab
    set shiftwidth=4
    retab
    '<,'>normal! ==
    '<,'>s;^\(\s\+\);\=repeat(' ', len(submatch(0))/2);g
    set shiftwidth=4
    norm!gv>
endfun

explanation:

  • set expandtab: because I love space indentation, just in case the code I copied from internet is using tab
  • set shiftwidth=4: we did this 2 times (in beginning and in the end) because we want during the function run, format all codes into 4 line so that it can be parsed in the next command
  • '<,'>normal! ==: this makes the code reformatted to 4 just in case there is code which is not correctly indented
  • '<,'>s;^\(\s\+\);\=repeat(' ', len(submatch(0))/2);g: convert all 4 indent to 2 indent
  • norm!gv>: shift the selected code to right on time

2. Write Normal JSX code

Just write normal JSX code.

3. Select JSX and Apply Function to Convert The Indentation

  1. Select JSX with v or for faster you can put your cursor at the render() return syntax then vi{
  2. While still at select mode, apply the Four2Two function by :call Four2Two()