Interact with this post using Mastodon or
[Plugin] Auto indent your code: sleuth.vim
Published on
Let’s make it difficult: the sleuth.vim plugin for (neo)vim, “automatically adjusts ‘shiftwidth’ and ’expandtab’ heuristically based on the current file, or, in the case the current file is new, blank, or otherwise insufficient, by looking at other files of the same type in the current and parent directories. Modelines and EditorConfig are also consulted, adding ’tabstop’, ’textwidth’, ’endofline’, ‘fileformat’, ‘fileencoding’, and ‘bomb’ to the list of supported options.”
That’s the definition on the github page
and it’s perfectly true. But that’s a lot of technical jargon for people who are not (neo)vim nerds. In lay language, this awesome plugin will take care of indenting your code for you.
╭── How to make it work?
sleuth.vim works by simply overriding the default shiftwidth and expandtab variables which you can set manually in your config file as shown in the next section.
And the best of all is that it doesn’t require any configuration, just install it and you’re good to go!
The magic will happen as you type but let’s say you go back to an old code with no/poor indentations. Selecting your code and typing z=
(by default) will auto indent it.
╭── In the (neo)vim config file
As far as indentation is concerned, here are the parameters you can define in your (neo)vim config. The code below is in lua (to be adjusted if you use vimrc
):
-- ensure <Tab> will be replaced with a number of spaces
vim.o.expandtab = true
-- make <Tab> respect 'tabstop', 'shiftwidth', and 'softtabstop'
vim.o.smarttab = true
-- set 1 <Tab> = 4 spaces
vim.o.tabstop = 4
-- set 1 >> = 4 spaces
vim.o.shiftwidth = 4
-- allow for multiple indentation levels (see note below)
vim.o.softtabstop = 4
Notes:
- if shiftwidth is not divisible by tabstop (e.g. you have set noexpandtab shiftwidth=6 tabstop=4 for some reason), it will use a combination of tabs and spaces to get the proper indent. If expandtab is set, then it will use spaces alone.
- softtabstop is useful if you want to keep the default tab stop size of 8, but edit a file as if the tab stop size was some other value. For example, if you wanted an indentation level of 4 while editing code, but some comments had tab-indented text such as a table that depended on a tab stop of 8, you could set softtabstop to 4.
Thanks for your read. Hope it's been useful to you.
✄ ┈ ┈ ┈ ┈ ┈ ┈ ┈ ┈ ┈ ┈ ┈ ┈ ┈ ┈ ┈ ┈ ┈ ┈ ┈ ┈ ┈ ┈ ┈ ┈ ┈ ┈ ┈ ┈ ┈
More food for thoughts? Check other posts about: #(Neo)vim #(Neo)vim-Plugins