Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Indenting CSS in emacs

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?

like image 849
thedz Avatar asked Aug 05 '09 10:08

thedz


2 Answers

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.

like image 120
genehack Avatar answered Sep 20 '22 04:09

genehack


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/

like image 24
Brandon Rhodes Avatar answered Sep 18 '22 04:09

Brandon Rhodes