Autoformatting Indented SASS

Personally I like to use SASS in it’s indented syntax. It’s easy to read, and because it’s sensitive to white-space you can change the structure very quickly using simple commands in Vim.

After watching a demonstration about Tabular I added a handy little function that automatically formats your properties as you write them, so they are lined up and easy to read like this:

span.day
  display:        block
  font-size:      ms(2)
  text-align:     right
  border-bottom:  1px solid $bg_color
  line-height:    1.25em
  margin-bottom:  0.25em

Here’s how you do it. Start off by installing the Tabular plugin with your script manager of choice, I use Vundle. Once you’ve done that, pop the following into .vim/ftplugin/sass.vim :

inoremap <silent>  :   :<Esc>:call <SID>align()<CR>a
function! s:align()
  let reg = '^\s*[a-z\-]*:\s*'
  if getline('.') =~# reg && (getline(line('.')-1) =~# reg || getline(line('.')+1) =~# reg)
    Tabularize /:\zs
    if getline(line('.')-1) =~# reg
      let endpos = strlen(matchstr(getline(line('.')-1), reg))
    else
      let endpos = strlen(matchstr(getline(line('.')+1), reg))
    endif
    normal! 0

    let currentlinelen = strlen(getline('.')) 
    if currentlinelen < endpos
      exe "normal A" . repeat(' ', endpos - currentlinelen) . "\"
    else
      call cursor(line('.'), endpos)
    endif
  endif
endfunction

All done, from now on when you’re in a SASS file Vim will automatically line up your properties when you type the colon, so the entire set stays neatly formatted as you go.

Leave a comment