use of org.eclipse.xtext.ui.editor.model.IXtextDocument in project xtext-xtend by eclipse.
the class XtendQuickfixProvider method refactorTernaryOperatorIntoNormalIf.
@Fix(IssueCodes.TERNARY_EXPRESSION_NOT_ALLOWED)
public void refactorTernaryOperatorIntoNormalIf(final Issue issue, IssueResolutionAcceptor acceptor) {
String label = "Refactor into inline if-expression.";
String description = "Refactor ternary expression (cond? a : b) \ninto an inline if-expression (if cond a else b).";
String image = "delete_edit.png";
// stop before NullpointerExceptions are thrown
if (issue == null)
return;
// Fix
acceptor.accept(issue, label, description, image, new ISemanticModification() {
@Override
public void apply(EObject element, IModificationContext context) throws Exception {
// Collect basic elements
IXtextDocument xtextDocument = context.getXtextDocument();
if (xtextDocument == null || element == null || !(element instanceof XExpression))
return;
XIfExpression exp = (XIfExpression) element;
// Collect original ternary expression information
ICompositeNode expNode = NodeModelUtils.findActualNodeFor(exp);
if (expNode == null)
throw new IllegalStateException("Node to refactor may not be null");
int expOffset = expNode.getTextRegion().getOffset();
int expLength = expNode.getTextRegion().getLength();
String ifExpr = this.buildIfExpression(exp, xtextDocument);
xtextDocument.replace(expOffset, expLength, ifExpr);
}
/**
* Build an inline if expression from the given ternary expression
* Also apply this fix to nested elements in then or else part
*/
private String buildIfExpression(XIfExpression expression, IXtextDocument document) throws Exception {
// Basic elements
XExpression thenPart = expression.getThen();
XExpression elsePart = expression.getElse();
boolean outerBracketsSet = false;
// Collect String representations
String ternExpStr = this.getString(NodeModelUtils.findActualNodeFor(expression), document);
if (ternExpStr.endsWith(")"))
outerBracketsSet = true;
String condStr = this.getString(NodeModelUtils.findActualNodeFor(expression.getIf()), document);
if (!condStr.contains("(")) {
condStr = "(" + condStr + ")";
}
// Check if then or else part is a ternary expression, too,
// and apply the fix to the inner elements
String thenStr = "", elseStr = "";
if (thenPart instanceof XIfExpression) {
if (((XIfExpression) thenPart).isConditionalExpression()) {
thenStr = buildIfExpression((XIfExpression) thenPart, document);
}
}
if (elsePart != null && elsePart instanceof XIfExpression) {
if (((XIfExpression) elsePart).isConditionalExpression()) {
elseStr = buildIfExpression((XIfExpression) elsePart, document);
}
}
// if then/else part does not contain nested ternary expressions
if (thenStr.isEmpty()) {
thenStr = this.getString(NodeModelUtils.findActualNodeFor(thenPart), document);
}
if (elsePart != null && elseStr.isEmpty()) {
elseStr = this.getString(NodeModelUtils.findActualNodeFor(elsePart), document);
}
// Combine
String ifExpStr = this.combineIfExpParts(condStr, thenStr, elseStr, outerBracketsSet);
return ifExpStr;
}
/**
* Stitch together the inline if statement
*/
private String combineIfExpParts(String condStr, String thenStr, String elseStr, boolean outerBracketsSet) {
String ifExpr = "if " + condStr + " " + thenStr;
if (!elseStr.isEmpty())
ifExpr += " else " + elseStr;
if (outerBracketsSet)
ifExpr = "(" + ifExpr + ")";
return ifExpr;
}
/**
* Get the String from a document Node
* Attention! The Document will not be updated in the meantime, so offsets and thus
* the outputString might get messed up, if the document is changed and the String
* is fetched after that.
*/
private String getString(ICompositeNode partNode, IXtextDocument doc) throws Exception {
if (partNode == null)
throw new IllegalStateException("Node to refactor may not be null");
ITextRegion partRegion = partNode.getTextRegion();
int partOffset = partRegion.getOffset();
int partLength = partRegion.getLength();
String partString = doc.get(partOffset, partLength);
return partString;
}
});
}
use of org.eclipse.xtext.ui.editor.model.IXtextDocument in project xtext-xtend by eclipse.
the class XtendQuickfixProvider method removeUnnecessaryModifier.
@Fix(IssueCodes.UNNECESSARY_MODIFIER)
public void removeUnnecessaryModifier(final Issue issue, IssueResolutionAcceptor acceptor) {
String[] issueData = issue.getData();
if (issueData == null || issueData.length == 0) {
return;
}
// use the same label, description and image
// to be able to use the quickfixes (issue resolution) in batch mode
String label = "Remove the unnecessary modifier.";
String description = "The modifier is unnecessary and could be removed.";
String image = "fix_indent.gif";
acceptor.accept(issue, label, description, image, new ITextualMultiModification() {
@Override
public void apply(IModificationContext context) throws Exception {
if (context instanceof IssueModificationContext) {
Issue theIssue = ((IssueModificationContext) context).getIssue();
Integer offset = theIssue.getOffset();
IXtextDocument document = context.getXtextDocument();
document.replace(offset, theIssue.getLength(), "");
while (Character.isWhitespace(document.getChar(offset))) {
document.replace(offset, 1, "");
}
}
}
});
}
use of org.eclipse.xtext.ui.editor.model.IXtextDocument in project xtext-xtend by eclipse.
the class CreateMemberQuickfixes method newLocalVariableQuickfix.
protected void newLocalVariableQuickfix(final String variableName, boolean isFinal, XAbstractFeatureCall call, Issue issue, IssueResolutionAcceptor issueResolutionAcceptor) {
LightweightTypeReference variableType = getNewMemberType(call);
final StringBuilderBasedAppendable localVarDescriptionBuilder = new StringBuilderBasedAppendable();
localVarDescriptionBuilder.append("...").newLine();
final String defaultValueLiteral = getDefaultValueLiteral(variableType);
localVarDescriptionBuilder.append(isFinal ? "val " : "var ").append(variableName).append(" = ").append(defaultValueLiteral);
localVarDescriptionBuilder.newLine().append("...");
issueResolutionAcceptor.accept(issue, "Create local " + (isFinal ? "value" : "variable") + " '" + variableName + "'", localVarDescriptionBuilder.toString(), "fix_local_var.png", new SemanticModificationWrapper(issue.getUriToProblem(), new ISemanticModification() {
@Override
public void apply(/* @Nullable */
final EObject element, /* @Nullable */
final IModificationContext context) throws Exception {
if (element != null) {
XtendMember xtendMember = EcoreUtil2.getContainerOfType(element, XtendMember.class);
if (xtendMember != null) {
int offset = getFirstOffsetOfKeyword(xtendMember, "{");
IXtextDocument xtextDocument = context.getXtextDocument();
if (offset != -1 && xtextDocument != null) {
final ReplacingAppendable appendable = appendableFactory.create(xtextDocument, (XtextResource) element.eResource(), offset, 0, new OptionalParameters() {
{
baseIndentationLevel = 1;
}
});
appendable.increaseIndentation().newLine().append(isFinal ? "val " : "var ").append(variableName).append(" = ").append(defaultValueLiteral);
appendable.commitChanges();
}
}
}
}
}));
}
use of org.eclipse.xtext.ui.editor.model.IXtextDocument in project xtext-xtend by eclipse.
the class XtendFoldingRegionProviderTest method calculateFoldingRegions.
private Collection<FoldedPosition> calculateFoldingRegions(String fileName, String content) throws Exception {
IFile iFile = testHelper.createFile(fileName, content);
XtextEditor editor = testHelper.openEditor(iFile);
IXtextDocument document = editor.getDocument();
return foldingRegionProvider.getFoldingRegions(document);
}
use of org.eclipse.xtext.ui.editor.model.IXtextDocument in project xtext-xtend by eclipse.
the class HighlightingReconcilerTest method testOpenedEditorHasSemanticHighlighting.
@Test
public void testOpenedEditorHasSemanticHighlighting() {
try {
StringConcatenation _builder = new StringConcatenation();
_builder.append("class Foo {");
_builder.newLine();
_builder.append(" ");
_builder.append("static val foo = \'\'");
_builder.newLine();
_builder.append("}");
_builder.newLine();
final String model = _builder.toString();
final XtextEditor editor = this.helper.openEditor("Foo.xtend", model);
final IXtextDocument document = editor.getDocument();
final Function0<Boolean> _function = () -> {
try {
boolean _xblockexpression = false;
{
final Function1<String, Boolean> _function_1 = (String it) -> {
return Boolean.valueOf(it.startsWith(HighlightingPresenter.class.getCanonicalName()));
};
final String highlighterCategory = IterableExtensions.<String>findFirst(((Iterable<String>) Conversions.doWrapArray(document.getPositionCategories())), _function_1);
final Function1<Position, String> _function_2 = (Position it) -> {
try {
return document.get(it.offset, it.length);
} catch (Throwable _e) {
throw Exceptions.sneakyThrow(_e);
}
};
final List<String> semanticSnippets = ListExtensions.<Position, String>map(((List<Position>) Conversions.doWrapArray(document.getPositions(highlighterCategory))), _function_2);
int _size = semanticSnippets.size();
_xblockexpression = (_size > 0);
}
return Boolean.valueOf(_xblockexpression);
} catch (Throwable _e) {
throw Exceptions.sneakyThrow(_e);
}
};
this.helper.awaitUIUpdate(_function, HighlightingReconcilerTest.VALIDATION_TIMEOUT);
final Function1<String, Boolean> _function_1 = (String it) -> {
return Boolean.valueOf(it.startsWith(HighlightingPresenter.class.getCanonicalName()));
};
final String highlighterCategory = IterableExtensions.<String>findFirst(((Iterable<String>) Conversions.doWrapArray(document.getPositionCategories())), _function_1);
final Function1<Position, String> _function_2 = (Position it) -> {
try {
return document.get(it.offset, it.length);
} catch (Throwable _e) {
throw Exceptions.sneakyThrow(_e);
}
};
final List<String> semanticSnippets = ListExtensions.<Position, String>map(((List<Position>) Conversions.doWrapArray(document.getPositions(highlighterCategory))), _function_2);
String _join = IterableExtensions.join(semanticSnippets, ",");
String _plus = ("Highlighting regions broken " + _join);
Assert.assertEquals(_plus, 2, semanticSnippets.size());
Assert.assertEquals("Foo", IterableExtensions.<String>head(semanticSnippets));
Assert.assertEquals("foo", IterableExtensions.<String>last(semanticSnippets));
} catch (Throwable _e) {
throw Exceptions.sneakyThrow(_e);
}
}
Aggregations