use of org.eclipse.xtext.formatting2.regionaccess.ITextReplacement in project xtext-eclipse by eclipse.
the class FormatterTester method assertAllWhitespaceIsFormatted.
protected void assertAllWhitespaceIsFormatted(ITextRegionAccess access, List<ITextReplacement> replacements) {
List<ITextSegment> expected = Lists.newArrayList();
IHiddenRegion current = access.regionForRootEObject().getPreviousHiddenRegion();
while (current != null) {
expected.addAll(current.getMergedSpaces());
current = current.getNextHiddenRegion();
}
List<ITextSegment> missing = TextRegions.difference(expected, replacements);
if (!missing.isEmpty()) {
TextRegionsToString toString = new TextRegionsToString().setTextRegionAccess(access);
for (ITextSegment region : missing) toString.add(region, region.getClass().getSimpleName());
String msg = "The following regions are not formatted:\n" + toString;
System.err.println(msg);
Assert.fail(msg);
}
}
use of org.eclipse.xtext.formatting2.regionaccess.ITextReplacement in project xtext-eclipse by eclipse.
the class FormatterTester method assertFormatted.
public void assertFormatted(FormatterTestRequest req) {
checkNotNull(req);
checkNotNull(req.getToBeFormatted());
FormatterRequest request = req.getRequest();
checkArgument(request.getTextRegionAccess() == null);
String document = req.getToBeFormatted().toString();
XtextResource parsed = parse(document);
if (req.isAllowSyntaxErrors()) {
request.setExceptionHandler(ExceptionAcceptor.IGNORING);
} else {
assertNoSyntaxErrors(parsed);
request.setExceptionHandler(ExceptionAcceptor.THROWING);
}
request.setTextRegionAccess(createRegionAccess(parsed, req));
if (request.getPreferences() == null)
request.setPreferences(new MapBasedPreferenceValues(Maps.<String, String>newLinkedHashMap()));
List<ITextReplacement> replacements = createFormatter(req).format(request);
assertReplacementsAreInRegion(replacements, request.getRegions(), document);
if (!req.isAllowUnformattedWhitespace())
assertAllWhitespaceIsFormatted(request.getTextRegionAccess(), replacements);
String formatted = request.getTextRegionAccess().getRewriter().renderToString(replacements);
Assert.assertEquals(req.getExpectationOrToBeFormatted().toString(), formatted);
// TODO: assert formatting a second time only produces identity replacements
// TODO: assert formatting with undefined whitespace only
}
use of org.eclipse.xtext.formatting2.regionaccess.ITextReplacement in project xtext-eclipse by eclipse.
the class DefaultLinkedPositionGroupCalculator2 method getLinkedPositionGroup.
@Override
public Provider<LinkedPositionGroup> getLinkedPositionGroup(final IRenameElementContext renameElementContext, final IProgressMonitor monitor) {
final SubMonitor progress = SubMonitor.convert(monitor, 100);
IEditorPart _triggeringEditor = renameElementContext.getTriggeringEditor();
final XtextEditor editor = ((XtextEditor) _triggeringEditor);
final IProject project = this.projectUtil.getProject(renameElementContext.getContextResourceURI());
if ((project == null)) {
StringConcatenation _builder = new StringConcatenation();
_builder.append("Could not determine project for context resource ");
URI _contextResourceURI = renameElementContext.getContextResourceURI();
_builder.append(_contextResourceURI);
String _string = _builder.toString();
throw new IllegalStateException(_string);
}
final CachingResourceSetProvider resourceSetProvider = new CachingResourceSetProvider(this.resourceSetProvider);
final ResourceSet resourceSet = resourceSetProvider.get(project);
final EObject targetElement = resourceSet.getEObject(renameElementContext.getTargetElementURI(), true);
if ((targetElement == null)) {
throw new IllegalStateException("Target element could not be loaded");
}
boolean _isCanceled = monitor.isCanceled();
if (_isCanceled) {
throw new OperationCanceledException();
}
IRenameStrategy2 renameStrategy = this.globalServiceProvider.<IRenameStrategy2>findService(targetElement, IRenameStrategy2.class);
if ((renameStrategy == null)) {
StringConcatenation _builder_1 = new StringConcatenation();
_builder_1.append("Cannot find a rename strategy for ");
URI _targetElementURI = renameElementContext.getTargetElementURI();
_builder_1.append(_targetElementURI);
throw new IllegalArgumentException(_builder_1.toString());
}
final String oldName = this.simpleNameProvider.getSimpleName(targetElement);
final String newName = this.getNewDummyName(oldName);
final IResourceServiceProvider resourceServiceProvider = this.resourceServiceProviderRegistry.getResourceServiceProvider(renameElementContext.getTargetElementURI());
final LtkIssueAcceptor issues = resourceServiceProvider.<LtkIssueAcceptor>get(LtkIssueAcceptor.class);
final IChangeSerializer changeSerializer = resourceServiceProvider.<IChangeSerializer>get(IChangeSerializer.class);
changeSerializer.setUpdateRelatedFiles(false);
URI _targetElementURI_1 = renameElementContext.getTargetElementURI();
final RenameChange change = new RenameChange(newName, _targetElementURI_1);
final RenameContext renameContext = new RenameContext(Collections.<RenameChange>unmodifiableList(CollectionLiterals.<RenameChange>newArrayList(change)), resourceSet, changeSerializer, issues);
renameStrategy.applyRename(renameContext);
final ArrayList<ReplaceEdit> replaceEdits = CollectionLiterals.<ReplaceEdit>newArrayList();
final IAcceptor<IEmfResourceChange> _function = (IEmfResourceChange c) -> {
if ((c instanceof ITextDocumentChange)) {
final Function1<ITextReplacement, ReplaceEdit> _function_1 = (ITextReplacement replacement) -> {
int _offset = replacement.getOffset();
int _length = replacement.getLength();
String _replacementText = replacement.getReplacementText();
return new ReplaceEdit(_offset, _length, _replacementText);
};
List<ReplaceEdit> _map = ListExtensions.<ITextReplacement, ReplaceEdit>map(((ITextDocumentChange) c).getReplacements(), _function_1);
Iterables.<ReplaceEdit>addAll(replaceEdits, _map);
}
};
changeSerializer.applyModifications(_function);
boolean _isCanceled_1 = monitor.isCanceled();
if (_isCanceled_1) {
throw new OperationCanceledException();
}
final Provider<LinkedPositionGroup> _function_1 = () -> {
return this.createLinkedGroupFromReplaceEdits(replaceEdits, editor, oldName, progress.newChild(10));
};
return _function_1;
}
use of org.eclipse.xtext.formatting2.regionaccess.ITextReplacement in project xtext-eclipse by eclipse.
the class ContentFormatter method exec.
protected TextEdit exec(IXtextDocument document, IRegion region, XtextResource resource) throws Exception {
try {
IParseResult parseResult = resource.getParseResult();
if (parseResult != null && parseResult.getRootASTElement() != null) {
FormatterRequest request = requestProvider.get();
initRequest(document, region, resource, request);
IFormatter2 formatter = formatterProvider.get();
List<ITextReplacement> replacements = formatter.format(request);
final TextEdit mte = createTextEdit(replacements);
return mte;
}
} catch (Exception e) {
LOG.error("Error formatting " + resource.getURI() + ": " + e.getMessage(), e);
}
return new MultiTextEdit();
}
use of org.eclipse.xtext.formatting2.regionaccess.ITextReplacement in project n4js by eclipse.
the class FormatterXpectMethod method formattedLines.
/**
*/
@Xpect
@ParameterParser(syntax = "arg1=INT")
public void formattedLines(@StringExpectation(whitespaceSensitive = true) IStringExpectation exp, // arg1
int lines, XpectInvocation inv, TargetSyntaxSupport syntax, ITextRegionAccess reg, ISetupInitializer<Preferences> prefInit) {
ITextSegment region = getRegionForLines(reg, syntax.findFirstSemanticCharAfterStatement(inv), lines);
Preferences prefs = new Preferences();
// First put some defaults
prefs.put(N4JSFormatterPreferenceKeys.FORMAT_PARENTHESIS, true);
prefs.put(FormatterPreferenceKeys.lineSeparator, "\n");
// Second init from concrete tests - will override defaults.
prefInit.initialize(prefs);
IFormatter2 formatter = formatterProvider.get();
FormatterRequest request = formatterRequestProvider.get();
request.setTextRegionAccess(reg);
request.setExceptionHandler(ExceptionAcceptor.THROWING);
// needed in case a check like this will be implemented:
// org.eclipse.xtext.testing.formatter.FormatterTester.assertAllWhitespaceIsFormatted()
request.setAllowIdentityEdits(true);
request.setFormatUndefinedHiddenRegionsOnly(false);
request.addRegion(region);
request.setPreferences(prefs);
List<ITextReplacement> replacements = formatter.format(request);
String fmt = reg.getRewriter().renderToString(replacements);
ITextSegment doc = reg.regionForDocument();
int endIndex = region.getEndOffset() + (fmt.length() - doc.getLength()) - 1;
String selection = fmt.substring(region.getOffset(), endIndex);
exp.assertEquals(selection);
}
Aggregations