-->

Eclipse e4 RCP SourceViewer syntax coloring

2019-07-28 02:41发布

问题:

To implement syntax coloring in an eclipse e4 RCP application, I have created a basic plugin project with a Part including a SourceViewer control.

public class SyntaxColoringTest {

    /** The SourceViewer control to create the editor. */
    public SourceViewer sv = null;

    @Inject
    public SyntaxColoringTest() {
    }

    @PostConstruct
    public void postConstruct(Composite parent) {
            IVerticalRuler  verticalRuler = new VerticalRuler(10);
            OverviewRuler overviewRuler = new OverviewRuler(null, 20, null);
            sv = new SourceViewer(parent, verticalRuler, overviewRuler, true, SWT.MULTI | SWT.V_SCROLL |SWT.H_SCROLL);
            sv.configure(new TestSourceViewerConf());
    }
}

Being TestSourceViewerConf as follows:

public class TestSourceViewerConf extends SourceViewerConfiguration {
    public ITokenScanner tokenScanner;
    public IRule patternRule;
    public IRule endOfLineRule;

    public TestSourceViewerConf(){
        tokenScanner = createTokenScanner();
    }
    public IPresentationReconciler getPresentationReconciler(ISourceViewer viewer) {
         PresentationReconciler reconciler= new PresentationReconciler();
         DefaultDamagerRepairer defDamagerRepairer= new DefaultDamagerRepairer(tokenScanner);
         reconciler.setDamager(defDamagerRepairer, IDocument.DEFAULT_CONTENT_TYPE);
         reconciler.setRepairer(defDamagerRepairer, IDocument.DEFAULT_CONTENT_TYPE);
         return reconciler;
    }
    private ITokenScanner createTokenScanner() {
         RuleBasedScanner scanner= new RuleBasedScanner();
         scanner.setRules(createRules());
         return scanner;
    }
    private IRule[] createRules() {
         Display display = Display.getCurrent();
         Color blue = display.getSystemColor(SWT.COLOR_BLUE);
         IToken tokenA= new Token(new TextAttribute(blue));
         IToken tokenB= new Token(new TextAttribute(blue));
         patternRule= new PatternRule("<", ">", tokenA, '\\', false);
         endOfLineRule = new EndOfLineRule("++ ", tokenB);
         return new IRule[] {patternRule, endOfLineRule};
    }
}

When running the application nothing is colored when typing after "++ " or in between < > Thanks

回答1:

This code works for me testing in one of my own e4 editors.

What you haven't shown is any set up of the document for the source viewer. If you don't set a document my test shows the behavior you are seeing. Set the document with:

IDocument doc = new Document(contents);

sv.setDocument(doc);

where contents is the initial contents of the document.