Autoindent selections

Just want to share a simple concept on how to auto indent selections. I couldn’t find anything similar, so I’ve decided to post it.

It is far from perfect, and I am sure there is something better, but still I like it. I tend to use it all the time.

It basically just copies all the selected lines and types them in insert mode with hooks. The better language support the better autoindentation.

def indent-selection %{
  eval -save-regs '"^i' %{
    exec '<a-x>"iZ'
    try %{
      exec '"_s^[ \t]+<ret><a-d>'
    }
    exec '"iz'
    execute-keys -with-hooks "<a-d>ko%sh{ echo ""$kak_selection"" | sed 's/</<lt>/g' }<esc>:select %val{selection_desc}<ret><a-x>"
  }
}

I’ve mapped it to =

map global normal = ':indent-selection<ret>'
1 Like

Thanks!

Nowadays I tend to delegate the formatting of code to external tools like https://prettier.io/. It’s a no-brainer solution and let me share the same rules with my coworkers on other IDEs. It reformats the whole buffer, but I don’t remember being in a situation where I’m only interested in indenting specific selections.

What are your common use-cases to format only parts of a buffer?

Yes, I agree, at the end of the day, I am also using external formatting tools. This script is just a quick way of indenting a few lines, so that your code would look a little bit more readable.

Also reruning some formators, all the time, can be time consuming, espesially on a big files/projects.

A related emacs issue about using prettier on selection: