Mx.
Mx.

Reputation: 3665

ACE Editor - Beautify for CSS

I'm currently implementing ace as an editor for several programming languages. I really want to implement a beautify functionality and currently I use this approach:

var beautify = ace.require("ace/ext/beautify"); // get reference to extension
var editor = ace.edit("editor"); // get reference to editor
beautify.beautify(editor.session);

More info

Sadly this does not format CSS correctly. Example:

.class1 .subClass { color: red; }

beautified via the described code this changes to

.class1.subClass{
    color:red;
}

as you can see all spaces in the selector were removed and this changes the target of the rule.

Is my code wrong? Is there a alternative beautifier for CSS in ace?

As a fallback I would remove the functionality which isn't the ideal solution.

TL;DR

Is there a plugin/extension for ace that can beautify CSS correctly? Am I doing something wrong?

Upvotes: 1

Views: 1781

Answers (1)

Mx.
Mx.

Reputation: 3665

Well I found a nice css beautifier which i added to my solution.

Here's the magic:

container.querySelector('.editor_beautify').addEventListener('click', function () {
    var currentMode = editor.session.$modeId.substr(editor.session.$modeId.lastIndexOf('/') + 1);
    switch (currentMode) {
        case modes.css:
            util.formatCss(editor, configuration.scriptBase);
            break;
        default:
            util.ensureScript(configuration.scriptBase + 'ext-beautify.js', function () {
                var beautify = ace.require("ace/ext/beautify").beautify(editor.session);
            });
    }
});

formatCss: function (editorAce, scriptBase) {
    var unformatted = editorAce.getValue();
    if (unformatted.trim().length > 0) {
        util.ensureScript(scriptBase + 'cssbeautify.js', function () {
            editorAce.getSession().setUseWrapMode(false);
            var formatted = cssbeautify(unformatted, {
                indent: '  ',
                openbrace: 'end-of-line',
                autosemicolon: true
            });

            editorAce.setValue(formatted);
            editorAce.getSession().setUseWrapMode(true);
        });                
    }
}

Upvotes: 0

Related Questions