Xtext Custom DSL formatting

705 views Asked by At

In my DSL I have () for a lot of stuff for example if conditions and some declarations such as block(a;b;c;d;);

In my configureFormatting function I do this in the following order:

for (Pair<Keyword, Keyword> pair : grammarAccess.findKeywordPairs("(", ")"))
{
   c.setNoSpace().after(pair.getFirst());
   c.setNoSpace().before(pair.getSecond());
}
c.setIndentation(block.getLeftParenthesisKeyword(),block.getRightParenthesisKeyword());
c.setLinewrap().after(block.getLeftParenthesisKeyword());
c.setLinewrap().before(block.getRightParenthesisKeyword());

Expected is:

block (
     int z;
     int a;
     int y;
);
if (a = 1)

Actual Result:

block (int z;
     int a;
     int y;);
if (a = 1)
2

There are 2 answers

0
Ayman Salah On BEST ANSWER

Well I have figured it out. It was simple. I made the following:

for (Pair<Keyword, Keyword> pair : grammarAccess.findKeywordPairs("(", ")"))
{
   if(pair.getFirst() != block.getLeftParenthesisKeyword())
        c.setNoSpace().after(pair.getFirst());
   if(pair.getSecond() != block.getRightParenthesisKeyword())       
        c.setNoSpace().before(pair.getSecond());
}
c.setIndentation(block.getLeftParenthesisKeyword(),block.getRightParenthesisKeyword());
c.setLinewrap().after(block.getLeftParenthesisKeyword());
c.setLinewrap().before(block.getRightParenthesisKeyword());
3
Franz Becker On

you see the actual result because within the for-loop you set explicitly that you don't want spaces after the first '(' and before the ')'.

Try the following:

for (Pair<Keyword, Keyword> pair : grammarAccess.findKeywordPairs("(", ")")) {
    c.setIndentation(pair.getFirst(), pair.getSecond()); // indent between ( )
    c.setLinewrap().after(pair.getFirst()); // linewrap after (
    c.setLinewrap().before(pair.getSecond()); // linewrap before )
    c.setNoSpace().after(pair.getSecond()); // no space after )
}

Hope that helps!