codeblog code is freedom — patching my itch

March 9, 2007

detecting space-vs-tab indentation type in vim

Filed under: General,Ubuntu — kees @ 10:36 am

I edit a lot of other people’s code. Dealing with indenting depth has always plagued me, and I’ve tried all sorts of things to try to address it, but the “real” problems I have are when tabs are mixed into code.

I personally use “4 spaces” for code indentation, and if I’m working on code that uses 8, I just hit “tab” twice, and if I’m working on code that uses 2, I can just backspace over the 2-too-many spaces. When the code has actual tabs, things break. When the code has a mix of tabs and spaces, it becomes a serious head-ache.

I wrote some vim insanity to detect which indentation type was being used “the most” in a given source file. If anyone has a simpler way to solve this (without switching to a different editor), I’m all ears. What follows are some bits from my .vimrc.

First, my space-indentation defaults:

set noai ts=4 sw=8 expandtab

Next, Makefiles and debian/rules files always use tabs, so I have a base set of overrides:

" Makefile sanity
autocmd BufEnter ?akefile* set noet ts=8 sw=8
autocmd BufEnter */debian/rules set noet ts=8 sw=8

Finally, define a function that compares the number of lines that start with a tab to those that start with a space. If the tabs outnumber the spaces, disable my defaults, and don’t expand tabs:

function Kees_settabs()
    if len(filter(getbufline(winbufnr(0), 1, "$"), 'v:val =~ "^\\t"')) > len(filter(getbufline(winbufnr(0), 1, "$"), 'v:val =~ "^ "'))
        set noet ts=8 sw=8
autocmd BufReadPost * call Kees_settabs()

© 2007, Kees Cook. This work is licensed under a Creative Commons Attribution-ShareAlike 3.0 License.
Creative Commons License

Powered by WordPress