How to call an exist format function within eclipse for the code file which i created by my plugin?

StackOverflow https://stackoverflow.com/questions/18481833

Вопрос

I wrote an eclipse plugin which can be used create JavaScript file with template codes in it.

Currently i am using JavaScript Development Tools, it includes the formatter feature.

What i want is, once my plugin created a new JavaScript file(it's written in one line without formatted), I want to call the formatter function in my plugin to format the code immediately.

Is it possible to do this?

Это было полезно?

Решение

I am using org.eclipse.wst.jsdt.feature plugin.

The usage of formatting JavaScript code programmatically is the same as the way to do with Java code.

as following:

    Map<?, ?> setting = DefaultCodeFormatterConstants.getEclipseDefaultSettings();
    CodeFormatter formatter = ToolFactory.createCodeFormatter(setting);
    TextEdit edit = formatter.format(CodeFormatter.K_JAVASCRIPT_UNIT, js,
            0, js.length(), 0, StringUtil.NEW_LINE);
    if (edit == null)
        return js;
    IDocument doc = new Document(js);
    try {
        edit.apply(doc);
    } catch (Exception e) {
        e.printStackTrace();
        return js;
    }
    return doc.get();

The thing you need mention is, you need import following package from org.eclipse.wst.jsdt.

import org.eclipse.jface.text.Document;
import org.eclipse.jface.text.IDocument;
import org.eclipse.text.edits.TextEdit;
import org.eclipse.wst.jsdt.core.ToolFactory;
import org.eclipse.wst.jsdt.core.formatter.CodeFormatter;
import org.eclipse.wst.jsdt.core.formatter.DefaultCodeFormatterConstants;
Лицензировано под: CC-BY-SA с атрибуция
Не связан с StackOverflow
scroll top