Inserting block / curly braces in If-else statements using JDT
I am creating an Eclipse plugin that needs to insert a block in one if-else string statement.
[Just like Eclipse makes it easy to set editor preference in Save-action]
eg,
if (isFormed)
if (i == 1)
System.out.println("i is 1");
else
System.out.println("i is undefined");
should be replaced with
if (isFormed)
{
if (i == 1)
{
System.out.println("i is 1");
}
else
{
System.out.println("i is undefined");
}
}
This is how I visit and replace the instruction inside the AST
node.accept(new ASTVisitor() {
@Override
public boolean visit(IfStatement ifStatement) {
//Add Block in case of IfStatemnet if it is not there.
if(ifStatement != null){
Statement thenStatement = ifStatement.getThenStatement();
Statement elseStatement = ifStatement.getElseStatement();
String codeToReplace = "if("+ifStatement.getExpression()+")";
if(thenStatement instanceof Block)
codeToReplace += "\n"+ thenStatement + "";
else
codeToReplace += "{\n"+ thenStatement + "\n}";
if(elseStatement != null){
if(elseStatement instanceof Block)
codeToReplace += "else" + elseStatement +"\n";
else
codeToReplace += "else{\n" + elseStatement +"\n}";
}
replaceStatment(rewriter, getBlockInstence(ifStatement), codeToReplace , ifStatement);
}
return super.visit(ifStatement);
}
});
& after it has been visited, I complete a working copy. This adds a block to the outer if-else, not the inner ones.
I also tried replacing the document and committing it during visit like below:
IDocument document = new org.eclipse.jface.text.Document(iCompilationUnit.getSource());
TextEdit edits = mCompilationUnit.rewrite(document, null);
document.replace(ifStatement.getStartPosition(), ifStatement.getLength(), codeToReplace);
edits.apply(document);
iCompilationUnit.getBuffer().setContents(document.get());
iCompilationUnit.commitWorkingCopy(true, new NullProgressMonitor());
But this adds curly braces in the wrong places for the inner if-else, and the whole code gets messed up like . THIS DOES NOT UPDATE the "offset" and "length" FOR THE REPLACEMENT CODE , and hence it keeps replacing in the wrong places and mess.
// void org.eclipse.jface.text.IDocument.replace (int offset, int length, String textTobeReplaced)
I also tried to get how eclipse does it. But I could not achieve this. Can anyone help with this issue? Or some plugin code I should call it? Even if I can get which eclipse plugin does this , I can try to compile it.
source to share
I had the same problem that with the changes the expression offset was changed and not updated. As a workaround, I first collected all the expressions that needed to be replaced, and then uncollected and thus started the changes at the end of the code. This way the offset did not change and I could change all the expressions.
This is not a good solution, but it worked for me.
source to share