views:

529

answers:

2

So emacs's auto-indentation for CSS is driving me batty. Here is what I like CSS to look like:

#foo ul.bar {
    ....
}

    #foo ul.bar li {
        ....
    }

        #foo ul.bar li a {
            ....
        }

This is what emacs gives me with its auto-indentation:

#foo ul.bar {
    ....
}

#foo ul.bar li {
    ....
}

#foo ul.bar li a {
    ....
}

I like to keep my styles progressively indented if they use the cascade. However, emacs will autoindent everything to the same level.

Anything I can do?

+3  A: 

I don't think any of the CSS modes I've used with Emacs are going to support that style of indentation out of the box -- they don't look at the content of the selectors, just whether or not something is a selector (don't indent) or is a rule inside a selector (indent one step).

If you wanted to change this, you'd need to override the function that does indentation for your CSS mode.

genehack
Is there a way to do manual indentation then? If I can't use autoindent to indent the way I like, I'd live if I could indent manually.
thedz
It looks like -- at least with the css-mode I'm using -- if you manually indent the initial selector line to where you want it, you just hit 'TAB' after that to correctly indent the following rules and the ending '}' -- and then you'll have to manually space out the next selector, etc. (The version of css-mode seems to come with Emacs since sometime in the Emacs 22 timeframe, so it's probably what you're using if you have a recent Emacs and haven't specifically loaded something else.)
genehack
+1  A: 

I would suggest that you start compiling your CSS using "Sass" — the .scss files look just like CSS but allow you to nest rules in exactly the way it looks like you're yearning to in your example, and it produces really pretty output that looks like CSS that was crafted by hand — so, first, your CSS will still be understandable; and, second, if you ever want to give up on Sass you can just delete your .scss files and edit the .css files from that point on.

And Emacs already indents Sass perfectly, since Emacs just obeys the normal rules for counting the number of curly braces and indenting accordingly. Your source code above, if converted to Sass, would look like this:

#foo ul.bar {
    ...

    li {
        ...

        a {
            ...
        }
    }
}

Obviously, this removes repetition and makes it easier to read and maintain your CSS. The Sass project is located here: http://sass-lang.com/

Brandon Craig Rhodes