Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Indentation annoyance with CSS in Vim

I've moved from TextMate to Vim lately, and am really liking the switch. However, I have an itch regarding the way Vim handles indentation within curly braces using the CSS syntax. I use simple_pairs.vim, which may or may not have something to do with my problem, but I don't think so, as things work fine in PHP, JavaScript, etc. Let me explain…

I generally group my CSS rules by context using indentation, like so:

ul#nav {
  margin: 10px;
}
  ul#nav li {
    float: left;
    margin-right: 4px;
  }

That means when I type my ul#nav li rule, followed by { (which inserts a corresponding } automatically) and hit enter, I want the closing brace to be at the same indentation level as the ul#…, but instead I get something like this:

ul#nav {
  margin: 10px;
}
  ul#nav li {
}

So I have to indent the extra step(s) manually. Like I said, doing the same thing in PHP, JavaScript, etc, works fine. Does anyone know how I can fix this? I don't understand enough of Vim's syntax definition files for me to be able to figure out what in the PHP syntax file makes it work, and port it over to the CSS one… Thanks.

like image 551
Johan Sahlén Avatar asked Mar 25 '10 21:03

Johan Sahlén


2 Answers

I found a very good indent code for nested curly brackets here:

https://gist.github.com/762326/bcbd35239db7f26447f1c2323037d20a5219471d

You can save it in .vim/indent/css.vim and it'll do a much better job of indenting CSS than the default.

Also, it works for .less files as well, but you may have to associate those to it in your .vimrc file.

The script at github is by the same mantainer as the official css.vim, only 6 years newer. They have a few different lines.

like image 129
artsy.ca Avatar answered Nov 16 '22 02:11

artsy.ca


I did this for css files:

au BufEnter *.css set nocindent
au BufLeave *.css set cindent

I didn't have smartindent set, but you could add that as well.

This says that when you enter a buffer of a .css file, you should unset cindent, and you should set it back when you leave the buffer.

like image 22
davetron5000 Avatar answered Nov 16 '22 03:11

davetron5000