user2455157
user2455157

Reputation: 147

Formatting string content xtext 2.14

Given a grammar (simplified version below) where I can enter arbitrary text in a section of the grammar, is it possible to format the content of the arbitrary text? I understand how to format the position of the arbitrary text in relation to the rest of the grammar, but not whether it is possible to format the content string itself?

Sample grammar

Model:
    'content' content=RT

terminal RT: // (returns ecore::EString:)
    'RT>>' -> '<<RT';

Sample content

content RT>>
# Some sample arbitrary text 
which I would like to format
<<RT

Upvotes: 2

Views: 424

Answers (1)

Christian Dietrich
Christian Dietrich

Reputation: 11868

you can add custom ITextReplacer to the region of the string. assuming you have a grammar like

Model:
    greetings+=Greeting*;

Greeting:
    'Hello' name=STRING '!';

you can do something like the follow in the formatter

def dispatch void format(Greeting model, extension IFormattableDocument document) {
    model.prepend[newLine]
    val region  = model.regionFor.feature(MyDslPackage.Literals.GREETING__NAME)
    val r = new AbstractTextReplacer(document, region) {
        override createReplacements(ITextReplacerContext it) {
            val text = region.text
            var int index = text.indexOf(SPACE);
            val offset = region.offset
            while (index >=0){
                it.addReplacement(region.textRegionAccess.rewriter.createReplacement(offset+index, SPACE.length, "\n"))
                index = text.indexOf(SPACE, index+SPACE.length())   ;
            }
            it
        }
    }
    addReplacer(r)
}

this will turn this model

Hello "A B C"!

into

Hello "A
B
C"!

of course you need to come up with a more sophisticated formatter logic. see How to define different indentation levels in the same document with Xtext formatter too

Upvotes: 2

Related Questions