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:
  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))
      let endpos = strlen(matchstr(getline(line('.')+1), reg))
    normal! 0

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

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 Reply

Fill in your details below or click an icon to log in: Logo

You are commenting using your account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s