org.eclipse.xtext.formatting2.regionaccess.ITextReplacement Java Examples

The following examples show how to use org.eclipse.xtext.formatting2.regionaccess.ITextReplacement. You can vote up the ones you like or vote down the ones you don't like, and go to the original project or source file by following the links above each example. You may check out the related API usage on the sidebar.
Example #1
Source File: FormattableDocument.java    From xtext-core with Eclipse Public License 2.0 6 votes vote down vote up
protected String applyTextReplacements(Iterable<ITextReplacement> replacements) {
	ITextSegment region = getRegion();
	String input = region.getText();
	ArrayList<ITextReplacement> list = Lists.newArrayList(replacements);
	Collections.sort(list);
	int startOffset = region.getOffset();
	int lastOffset = 0;
	StringBuilder result = new StringBuilder();
	for (ITextReplacement r : list) {
		int offset = r.getOffset() - startOffset;
		result.append(input.subSequence(lastOffset, offset));
		result.append(r.getReplacementText());
		lastOffset = offset + r.getLength();
	}
	result.append(input.subSequence(lastOffset, input.length()));
	return result.toString();
}
 
Example #2
Source File: FormattingService.java    From xtext-core with Eclipse Public License 2.0 6 votes vote down vote up
/**
 * @since 2.14
 */
public List<TextEdit> format(XtextResource resource, Document document, int offset, int length,
		FormattingOptions options) {
	String indent = indentationInformation.getIndentString();
	if (options != null) {
		if (options.isInsertSpaces()) {
			indent = Strings.padEnd("", options.getTabSize(), ' ');
		}
	}
	List<TextEdit> result = new ArrayList<>();
	if (this.formatter2Provider != null) {
		MapBasedPreferenceValues preferences = new MapBasedPreferenceValues();
		preferences.put("indentation", indent);
		List<ITextReplacement> replacements = format2(resource, new TextRegion(offset, length), preferences);
		for (ITextReplacement r : replacements) {
			result.add(toTextEdit(document, r.getReplacementText(), r.getOffset(), r.getLength()));
		}
	}
	return result;
}
 
Example #3
Source File: ConvertJavaCode.java    From xtext-xtend with Eclipse Public License 2.0 6 votes vote down vote up
private String formatXtendCode(IFile xtendFile, final String xtendCode) {
	try {
		XtextResource resource = (XtextResource) createResource(xtendFile, xtendCode);
		ITextRegionAccess regionAccess = regionAccessBuilder.get().forNodeModel(resource).create();
		FormatterRequest request = new FormatterRequest();
		request.setAllowIdentityEdits(false);
		request.setTextRegionAccess(regionAccess);
		request.setPreferences(TypedPreferenceValues.castOrWrap(cfgProvider.getPreferenceValues(resource)));
		List<ITextReplacement> replacements = formatter.format(request);
		String formatted = regionAccess.getRewriter().renderToString(replacements);
		return formatted;
	} catch (Exception e) {
		LOG.error("Formatting step canceled due to an exception.", e);
		return null;
	}
}
 
Example #4
Source File: FormatterTester.java    From xtext-eclipse with Eclipse Public License 2.0 6 votes vote down vote up
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);
	}
}
 
Example #5
Source File: ContentFormatter.java    From xtext-eclipse with Eclipse Public License 2.0 6 votes vote down vote up
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();
}
 
Example #6
Source File: FormattingService.java    From xtext-core with Eclipse Public License 2.0 6 votes vote down vote up
protected List<ITextReplacement> format2(XtextResource resource, ITextRegion selection,
		ITypedPreferenceValues preferences) {
	FormatterRequest request = formatterRequestProvider.get();
	request.setAllowIdentityEdits(false);
	request.setFormatUndefinedHiddenRegionsOnly(false);
	if (selection != null) {
		request.setRegions(Collections.singletonList(selection));
	}
	if (preferences != null) {
		request.setPreferences(preferences);
	}
	ITextRegionAccess regionAccess = regionBuilder.forNodeModel(resource).create();
	request.setTextRegionAccess(regionAccess);
	IFormatter2 formatter2 = formatter2Provider.get();
	List<ITextReplacement> replacements = formatter2.format(request);
	return replacements;
}
 
Example #7
Source File: FormattingService.java    From xtext-web with Eclipse Public License 2.0 6 votes vote down vote up
protected String format2(XtextResource resource, ITextRegion selection, ITypedPreferenceValues preferences) {
	FormatterRequest request = formatterRequestProvider.get();
	request.setAllowIdentityEdits(false);
	request.setFormatUndefinedHiddenRegionsOnly(false);
	if (selection != null) {
		request.setRegions(Lists.newArrayList(selection));
	}
	if (preferences != null) {
		request.setPreferences(preferences);
	}
	ITextRegionAccess regionAccess = regionBuilder.forNodeModel(resource).create();
	request.setTextRegionAccess(regionAccess);
	IFormatter2 formatter2 = formatter2Provider.get();
	List<ITextReplacement> replacements = formatter2.format(request);
	if (selection != null) {
		return regionAccess.getRewriter().renderToString(
				new TextSegment(regionAccess, selection.getOffset(), selection.getLength()), replacements);
	} else {
		return regionAccess.getRewriter().renderToString(replacements);
	}
}
 
Example #8
Source File: RegionDiffFormatter.java    From xtext-core with Eclipse Public License 2.0 6 votes vote down vote up
protected List<ITextReplacement> mergeReplacements(ITextRegionAccessDiff regions, List<ITextReplacement> rep) {
	ITextRegionRewriter rewriter = regions.getOriginalTextRegionAccess().getRewriter();
	List<ITextReplacement> result = Lists.newArrayList();
	for (ITextSegmentDiff r : regions.getRegionDifferences()) {
		ITextSegment original = r.getOriginalRegion();
		ITextSegment modified = r.getModifiedRegion();
		List<ITextReplacement> local = Lists.newArrayList();
		for (ITextReplacement re : rep) {
			if (modified.contains(re)) {
				local.add(re);
			}
		}
		String text;
		if (local.isEmpty()) {
			text = modified.getText();
		} else {
			text = regions.getRewriter().renderToString(modified, local);
		}
		ITextReplacement replacement = rewriter.createReplacement(original.getOffset(), original.getLength(), text);
		result.add(replacement);
	}
	return result;
}
 
Example #9
Source File: ChangeConverter2.java    From xtext-core with Eclipse Public License 2.0 6 votes vote down vote up
protected void _handleReplacements(ITextDocumentChange change) {
	try {
		if (change.getReplacements().size() > 0) {
			String uri = uriExtensions.toUriString(change.getNewURI());
			access.doRead(uri, (ILanguageServerAccess.Context context) -> {
				Document document = context.getDocument();
				List<TextEdit> textEdits = Lists.transform(change.getReplacements(),
						(ITextReplacement replacement) -> {
							Position start = document.getPosition(replacement.getOffset());
							Position end = document.getPosition(replacement.getOffset() + replacement.getLength());
							Range range = new Range(start, end);
							return new TextEdit(range, replacement.getReplacementText());
						});
				return addTextEdit(uri, document, textEdits.toArray(new TextEdit[textEdits.size()]));
			}).get();
		}
	} catch (InterruptedException | ExecutionException e) {
		throw Exceptions.sneakyThrow(e);
	}
}
 
Example #10
Source File: FormatterFacade.java    From xtext-xtend with Eclipse Public License 2.0 6 votes vote down vote up
public String format(final String xtendCode) {
  try {
    final XtextResourceSet resourceSet = new XtextResourceSet();
    Resource _createResource = this.resourceFactory.createResource(URI.createURI("synthetic://to-be-formatted.xtend"));
    final XtextResource resource = ((XtextResource) _createResource);
    EList<Resource> _resources = resourceSet.getResources();
    _resources.add(resource);
    StringInputStream _stringInputStream = new StringInputStream(xtendCode);
    resource.load(_stringInputStream, CollectionLiterals.<Object, Object>emptyMap());
    final ITextRegionAccess regionAccess = this.regionAccessBuilder.get().forNodeModel(resource).create();
    FormatterRequest _formatterRequest = new FormatterRequest();
    final Procedure1<FormatterRequest> _function = (FormatterRequest it) -> {
      it.setAllowIdentityEdits(false);
      it.setTextRegionAccess(regionAccess);
      it.setPreferences(TypedPreferenceValues.castOrWrap(this.cfgProvider.getPreferenceValues(resource)));
    };
    FormatterRequest request = ObjectExtensions.<FormatterRequest>operator_doubleArrow(_formatterRequest, _function);
    List<ITextReplacement> replacements = this.formatter.format(request);
    return regionAccess.getRewriter().renderToString(replacements);
  } catch (Throwable _e) {
    throw Exceptions.sneakyThrow(_e);
  }
}
 
Example #11
Source File: CodeActionService.java    From xtext-core with Eclipse Public License 2.0 6 votes vote down vote up
private WorkspaceEdit recordWorkspaceEdit(ICodeActionService2.Options options,
		IChangeSerializer.IModification<Resource> mod) {
	ResourceSet rs = options.getLanguageServerAccess().newLiveScopeResourceSet(options.getResource().getURI());
	Resource copy = rs.getResource(options.getResource().getURI(), true);
	serializer.addModification(copy, mod);
	List<IEmfResourceChange> documentchanges = new ArrayList<>();
	serializer.applyModifications(CollectionBasedAcceptor.of(documentchanges));
	WorkspaceEdit workspaceEdit = new WorkspaceEdit();
	for (ITextDocumentChange documentchange : Iterables.filter(documentchanges, ITextDocumentChange.class)) {
		List<TextEdit> edits = ListExtensions.map(documentchange.getReplacements(),
				(ITextReplacement replacement) -> {
					TextEdit textEdit = new TextEdit();
					textEdit.setNewText(replacement.getReplacementText());
					textEdit.setRange(new Range(options.getDocument().getPosition(replacement.getOffset()),
							options.getDocument().getPosition(replacement.getEndOffset())));
					return textEdit;
				});
		workspaceEdit.getChanges().put(documentchange.getNewURI().toString(), edits);
	}
	return workspaceEdit;
}
 
Example #12
Source File: AbstractFormatter2.java    From xtext-core with Eclipse Public License 2.0 6 votes vote down vote up
@Override
public final List<ITextReplacement> format(FormatterRequest request) {
	try {
		initialize(request);
		XtextResource xtextResource = request.getTextRegionAccess().getResource();
		IFormattableDocument document = createFormattableRootDocument();
		try {
			format(xtextResource, document);
		} catch (RegionTraceMissingException e) {
			document = handleTraceMissing(document, e);
		}
		List<ITextReplacement> rendered = document.renderToTextReplacements();
		List<ITextReplacement> postprocessed = postProcess(document, rendered);
		return postprocessed;
	} finally {
		reset();
	}
}
 
Example #13
Source File: TextReplacerContext.java    From xtext-core with Eclipse Public License 2.0 6 votes vote down vote up
@Override
public boolean isWrapInRegion() {
	ITextRegionAccess access = getDocument().getRequest().getTextRegionAccess();
	ITextSegment region = getReplacer().getRegion();
	int lastOffset = region.getOffset();
	for (ITextReplacement rep : this.getLocalReplacements()) {
		int endOffset = rep.getOffset();
		String between = access.textForOffset(lastOffset, endOffset - lastOffset);
		if (between.contains("\n") || rep.getReplacementText().contains("\n")) {
			return true;
		}
		lastOffset = rep.getEndOffset();
	}
	String rest = access.textForOffset(lastOffset, region.getEndOffset() - lastOffset);
	if (rest.contains("\n")) {
		return true;
	}
	return false;
}
 
Example #14
Source File: TextRegionsWithTitleToString.java    From xtext-core with Eclipse Public License 2.0 6 votes vote down vote up
@Override
public String toString() {
	ITextRegionAccess access = getTextRegionAccess();
	ITextSegment frame = getFrame();
	if (access == null || frame == null)
		return "(null)";
	ITextRegionRewriter rewriter = access.getRewriter();
	StringBuilder builder = new StringBuilder();
	List<ITextReplacement> replacements = Lists.newArrayList();
	for (int i = 0; i < this.items.size(); i++) {
		Item item = this.items.get(i);
		ITextSegment region = item.getRegion();
		String regionStr = "offset=" + region.getOffset() + " length=" + region.getLength();
		String open = i < BRACKETS_OPEN.length ? BRACKETS_OPEN[i] : "[" + i + "[";
		String close = i < BRACKETS_CLOSE.length ? BRACKETS_CLOSE[i] : "]" + i + "]";
		builder.append(open + close + ": " + item.getTitle() + " at " + regionStr + "\n");
		replacements.add(rewriter.createReplacement(region.getOffset(), 0, open));
		replacements.add(rewriter.createReplacement(region.getEndOffset(), 0, close));
	}
	String vizualized = rewriter.renderToString(frame, replacements);
	builder.append(box("document snippet", vizualized));
	return builder.toString();
}
 
Example #15
Source File: TextReplacerContext.java    From xtext-core with Eclipse Public License 2.0 6 votes vote down vote up
protected String toStringLocal() {
	List<String> items = Lists.newArrayList();
	if (autowrap)
		items.add("autowrap");
	if (canAutowrap != null && canAutowrap >= 0)
		items.add("canAutowrap");
	if (replacer != null) {
		ITextSegment region = replacer.getRegion();
		items.add(format("replacer=[%d-%d-%s|%s]", region.getOffset(), region.getLength(),
				replacer.getClass().getSimpleName(), replacer.toString()));
	}
	if (replacements != null)
		for (ITextReplacement r : replacements) {
			String fmt = "replacement=[%d-%d|%s]";
			items.add(format(fmt, r.getOffset(), r.getLength(), r.getReplacementText()));
		}
	return Joiner.on("; ").join(items);
}
 
Example #16
Source File: TextRegionRewriter.java    From xtext-core with Eclipse Public License 2.0 6 votes vote down vote up
@Override
public void renderToAppendable(ITextSegment input, Iterable<? extends ITextReplacement> rep, Appendable result)
		throws IOException {
	int offset = input.getOffset();
	String text = input.getText();
	List<ITextReplacement> list = new TextReplacementList<ITextReplacement>(rep);
	Collections.sort(list);
	int lastOffset = 0;
	for (ITextReplacement r : list) {
		result.append(text.subSequence(lastOffset, r.getOffset() - offset));
		result.append(r.getReplacementText());
		lastOffset = (r.getOffset() - offset) + r.getLength();
	}
	if (lastOffset <= text.length())
		result.append(text.subSequence(lastOffset, text.length()));
}
 
Example #17
Source File: FormatterTestHelper.java    From xtext-core with Eclipse Public License 2.0 6 votes vote down vote up
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);
	}
}
 
Example #18
Source File: FormatterTester.java    From xtext-extras with Eclipse Public License 2.0 6 votes vote down vote up
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);
	}
}
 
Example #19
Source File: TextReplacerContext.java    From xtext-core with Eclipse Public License 2.0 6 votes vote down vote up
@Override
public List<ITextReplacement> getReplacementsUntil(ITextReplacerContext first) {
	ITextReplacerContext current = this;
	List<Iterable<ITextReplacement>> reversedReplacements = Lists.newArrayList();
	while (current != null) {
		Iterable<ITextReplacement> localReplacements = current.getLocalReplacements();
		if (!Iterables.isEmpty(localReplacements))
			reversedReplacements.add(localReplacements);
		if (current == first)
			break;
		current = current.getPreviousContext();
	}
	Collections.reverse(reversedReplacements);
	List<ITextReplacement> flattenedReplacements = new TextReplacementList<ITextReplacement>();
	for (Iterable<ITextReplacement> chunk : reversedReplacements)
		Iterables.addAll(flattenedReplacements, chunk);
	return flattenedReplacements;
}
 
Example #20
Source File: RegionAccessTestHelper.java    From xtext-core with Eclipse Public License 2.0 5 votes vote down vote up
public void assertDiffs(ITextRegionAccessDiff regions) {
	ITextRegionRewriter rewriter = regions.getOriginalTextRegionAccess().getRewriter();
	List<ITextReplacement> result = new ArrayList<>();
	for (ITextSegmentDiff r : regions.getRegionDifferences()) {
		ITextSegment originalRegion = r.getOriginalRegion();
		ITextSegment modifiedRegion = r.getModifiedRegion();
		ITextReplacement replacement = originalRegion.replaceWith(modifiedRegion.getText());
		result.add(replacement);
	}
	String actual = rewriter.renderToString(result);
	String expected = regions.regionForDocument().getText();
	Assert.assertEquals(expected, actual);
}
 
Example #21
Source File: TextReplacerContext.java    From xtext-core with Eclipse Public License 2.0 5 votes vote down vote up
protected boolean isInRequestedRange(ITextReplacement repl) {
	Collection<ITextRegion> regions = document.getRequest().getRegions();
	if (regions.isEmpty())
		return true;
	for (org.eclipse.xtext.util.ITextRegion region : regions)
		if (region.getOffset() <= repl.getOffset()
				&& region.getOffset() + region.getLength() >= repl.getEndOffset())
			return true;
	return false;
}
 
Example #22
Source File: FormatterTestHelper.java    From xtext-core with Eclipse Public License 2.0 5 votes vote down vote up
protected void assertReplacementsAreInRegion(List<ITextReplacement> rep, Collection<ITextRegion> regions,
		String doc) {
	Set<ITextReplacement> invalid = Sets.newHashSet();
	ALLOWED: for (ITextRegion allowed : regions)
		for (ITextReplacement r : rep) {
			if (allowed.contains(r))
				continue ALLOWED;
			invalid.add(r);
		}
	if (!invalid.isEmpty()) {
		String visualized = new TextRegionsToString().addAllReplacements(invalid).toString();
		fail("One or more TextReplacements are outside of the allowed region. Region: " + regions, visualized);
	}
}
 
Example #23
Source File: FormatterTestHelper.java    From xtext-core with Eclipse Public License 2.0 5 votes vote down vote up
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()) {
		if (request.getExplicitExceptionHandler() == null) {
			request.setExceptionHandler(ExceptionAcceptor.IGNORING);
		}
	} else {
		assertNoSyntaxErrors(parsed);
		if (request.getExplicitExceptionHandler() == null) {
			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
}
 
Example #24
Source File: RelatedXtextResourceUpdater.java    From xtext-core with Eclipse Public License 2.0 5 votes vote down vote up
@Override
public void applyChange(Deltas deltas, IAcceptor<IEmfResourceChange> changeAcceptor) {
	XtextResource res = (XtextResource) lifecycleManager.openAndApplyReferences(getResourceSet(), getResource());
	if (!referenceUpdater.isAffected(deltas, getResource())) {
		return;
	}
	ITextRegionAccess base = textRegionBuilderProvider.get().forNodeModel(res).create();
	ITextRegionDiffBuilder rewriter = new StringBasedTextRegionAccessDiffBuilder(base);
	ReferenceUpdaterContext context = new ReferenceUpdaterContext(deltas, rewriter, getResource());
	referenceUpdater.update(context);
	if (!context.getModifications().isEmpty()) {
		ChangeRecorder rec = createChangeRecorder(res);
		try {
			for (Runnable run : context.getModifications()) {
				run.run();
			}
			ChangeDescription recording = rec.endRecording();
			ResourceSet rs = res.getResourceSet();
			ResourceSetRecording tree = changeTreeProvider.createChangeTree(rs, Collections.emptyList(), recording);
			ResourceRecording recordedResource = tree.getRecordedResource(res);
			if (recordedResource != null) {
				serializer.serializeChanges(recordedResource, rewriter);
			}
		} finally {
			rec.dispose();
		}
	}
	for (IUpdatableReference upd : context.getUpdatableReferences()) {
		referenceUpdater.updateReference(rewriter, upd);
	}
	ITextRegionAccessDiff rewritten = rewriter.create();
	List<ITextReplacement> rep = formatter.format(rewritten);
	TextDocumentChange change = new TextDocumentChange(rewritten, getResource().getUri(), rep);
	changeAcceptor.accept(change);
}
 
Example #25
Source File: TextReplacerContext.java    From xtext-core with Eclipse Public License 2.0 5 votes vote down vote up
@Override
public Iterable<ITextReplacement> getLocalReplacementsReverse() {
	if (replacements != null)
		return replacements.reverseIterable();
	else
		return Collections.<ITextReplacement>emptyList();
}
 
Example #26
Source File: TextReplacerContext.java    From xtext-core with Eclipse Public License 2.0 5 votes vote down vote up
@Override
public Iterable<ITextReplacement> getLocalReplacements() {
	if (replacements != null)
		return replacements;
	else
		return Collections.<ITextReplacement>emptyList();
}
 
Example #27
Source File: FixedContentFormatter.java    From n4js with Eclipse Public License 1.0 5 votes vote down vote up
@Override
protected TextEdit createTextEdit(List<ITextReplacement> replacements) {
	if (replacements.isEmpty()) {
		return new ReplaceEdit(0, 0, "");
	}
	ITextRegionAccess regionAccess = replacements.get(0).getTextRegionAccess();
	String newDocument = regionAccess.getRewriter().renderToString(replacements);
	return new ReplaceEdit(0, regionAccess.regionForDocument().getLength(), newDocument);
}
 
Example #28
Source File: FormattableDocument.java    From xtext-core with Eclipse Public License 2.0 5 votes vote down vote up
@Override
public List<ITextReplacement> renderToTextReplacements() {
	ITextReplacerContext first = getFormatter().createTextReplacerContext(this);
	ITextReplacerContext last = createReplacements(first);
	List<ITextReplacement> replacements = last.getReplacementsUntil(first);
	return replacements;
}
 
Example #29
Source File: TextReplacerContext.java    From xtext-core with Eclipse Public License 2.0 5 votes vote down vote up
protected TextSegmentSet<ITextReplacement> createTextReplacementsSet() {
	return new ArrayListTextSegmentSet<ITextReplacement>(Functions.<ITextReplacement>identity(),
			new Function<ITextReplacement, String>() {
				@Override
				public String apply(ITextReplacement input) {
					return input.getReplacementText();
				}
			}, getDocument().getRequest().isEnableDebugTracing());
}
 
Example #30
Source File: RecordingXtextResourceUpdater.java    From xtext-core with Eclipse Public License 2.0 5 votes vote down vote up
@Override
public void applyChange(Deltas deltas, IAcceptor<IEmfResourceChange> changeAcceptor) {
	Resource resource = snapshot.getResource();
	ResourceSet rs = resource.getResourceSet();
	ReferenceUpdaterContext ctx = new ReferenceUpdaterContext(deltas, document);
	if (serializer.isUpdateCrossReferences()) {
		referenceUpdater.update(ctx);
		for (Runnable run : ctx.getModifications()) {
			run.run();
		}
	}
	ChangeDescription recording = recorder.endRecording();
	if (recording != null) {
		List<IResourceSnapshot> snapshots = Collections.singletonList(snapshot);
		ResourceSetRecording tree = changeTreeProvider.createChangeTree(rs, snapshots, recording);
		ResourceRecording recordedResource = tree.getRecordedResource(resource);
		partialSerializer.serializeChanges(recordedResource, document);
	}
	recorder.dispose();
	List<IUpdatableReference> updatableReferences = ctx.getUpdatableReferences();
	for (IUpdatableReference upd : updatableReferences) {
		referenceUpdater.updateReference(document, upd);
	}
	ITextRegionAccessDiff rewritten = document.create();
	List<ITextReplacement> rep = formatter.format(rewritten);
	URI oldUri = snapshot.getURI();
	TextDocumentChange change = new TextDocumentChange(rewritten, oldUri, rep);
	changeAcceptor.accept(change);
}