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

The following examples show how to use org.eclipse.xtext.formatting2.regionaccess.ITextRegionAccess. 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: RegionAccessBuilderTest.java    From xtext-core with Eclipse Public License 2.0 6 votes vote down vote up
private void operator_tripleEquals(final CharSequence file, final CharSequence expectation) {
  try {
    final String exp = expectation.toString();
    final Root obj = this.parseHelper.parse(file);
    this.validationTestHelper.assertNoErrors(obj);
    final ITextRegionAccess access1 = this.createFromNodeModel(obj);
    final ITextRegionAccess access2 = this.serializer.serializeToRegions(obj);
    this.assertToStringDoesNotCrash(access1);
    this.assertToStringDoesNotCrash(access2);
    this.assertLinesAreConsistent(access1);
    this.assertLinesAreConsistent(access2);
    TextRegionAccessToString _cfg = this.cfg(new TextRegionAccessToString().withRegionAccess(access1));
    final String tra1 = (_cfg + "\n");
    TextRegionAccessToString _cfg_1 = this.cfg(new TextRegionAccessToString().withRegionAccess(access2));
    final String tra2 = (_cfg_1 + "\n");
    Assert.assertEquals(Strings.toPlatformLineSeparator(exp), Strings.toPlatformLineSeparator(tra1));
    Assert.assertEquals(Strings.toPlatformLineSeparator(exp), Strings.toPlatformLineSeparator(tra2));
  } catch (Throwable _e) {
    throw Exceptions.sneakyThrow(_e);
  }
}
 
Example #2
Source File: TextRegionAccessToString.java    From xtext-core with Eclipse Public License 2.0 6 votes vote down vote up
@Override
public String toString() {
	List<ITextSegment> list = toTokenAndGapList();
	if (list.isEmpty())
		return "(empty)";
	ITextRegionAccess access = list.get(0).getTextRegionAccess();
	DiffColumn diff = new DiffColumn(access);
	TextRegionListToString result = new TextRegionListToString();
	if (!hideColumnExplanation) {
		if (diff.isDiff()) {
			result.add("Columns: 1:offset 2:length 3:diff 4:kind 5: text 6:grammarElement", false);
		} else {
			result.add("Columns: 1:offset 2:length 3:kind 4: text 5:grammarElement", false);
		}
		result.add("Kind: H=IHiddenRegion S=ISemanticRegion B/E=IEObjectRegion", false);
		result.add("", false);
	}
	appendRegions(result, list, diff, false);
	diff.appendDiffs(result, this);
	return result.toString();
}
 
Example #3
Source File: AbstractFormatter2.java    From xtext-core with Eclipse Public License 2.0 6 votes vote down vote up
protected boolean isInRequestedRange(EObject obj) {
	Collection<ITextRegion> regions = request.getRegions();
	if (regions.isEmpty())
		return true;
	ITextRegionAccess access = request.getTextRegionAccess();
	IEObjectRegion objRegion = access.regionForEObject(obj);
	if (objRegion == null)
		return false;
	IHiddenRegion previousHidden = objRegion.getPreviousHiddenRegion();
	IHiddenRegion nextHidden = objRegion.getNextHiddenRegion();
	int objOffset = previousHidden != null ? previousHidden.getOffset() : 0;
	int objEnd = nextHidden != null ? nextHidden.getEndOffset() : access.regionForRootEObject().getEndOffset();
	for (ITextRegion region : regions) {
		int regionOffset = region.getOffset();
		int regionEnd = regionOffset + region.getLength();
		if (regionOffset <= objEnd && regionEnd >= objOffset)
			return true;
	}
	return false;
}
 
Example #4
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 #5
Source File: RichStringFormatter.java    From xtext-xtend with Eclipse Public License 2.0 6 votes vote down vote up
protected void setNewLines(final IFormattableDocument doc, final int offset, final int length, final int indentationIncrease, final int indentationDecrease, final int newLines) {
  IHiddenRegionFormatting _createHiddenRegionFormatting = doc.getFormatter().createHiddenRegionFormatting();
  final Procedure1<IHiddenRegionFormatting> _function = (IHiddenRegionFormatting it) -> {
    it.setIndentationIncrease(Integer.valueOf(indentationIncrease));
    it.setIndentationDecrease(Integer.valueOf(indentationDecrease));
    it.setNewLinesMin(Integer.valueOf(newLines));
    it.setNewLinesDefault(Integer.valueOf(newLines));
    it.setNewLinesMax(Integer.valueOf(newLines));
  };
  final IHiddenRegionFormatting fmt = ObjectExtensions.<IHiddenRegionFormatting>operator_doubleArrow(_createHiddenRegionFormatting, _function);
  AbstractFormatter2 _formatter = doc.getFormatter();
  ITextRegionAccess _textRegionAccess = this._iTextRegionExtensions.getTextRegionAccess();
  TextSegment _textSegment = new TextSegment(_textRegionAccess, offset, length);
  final ITextReplacer replacer = _formatter.createWhitespaceReplacer(_textSegment, fmt);
  doc.addReplacer(replacer);
}
 
Example #6
Source File: ReferenceUpdater.java    From xtext-core with Eclipse Public License 2.0 6 votes vote down vote up
protected ISemanticRegion getRegion(ITextRegionAccess access, IReferenceSnapshot ref) {
	XtextResource resource = access.getResource();
	URI objectUri = ref.getSourceEObjectUri();
	if (!resource.getURI().equals(objectUri.trimFragment())) {
		return null;
	}
	EObject object = resource.getEObject(objectUri.fragment());
	if (object == null) {
		return null;
	}
	ISemanticRegionsFinder finder = access.getExtensions().regionFor(object);
	int index = ref.getIndexInList();
	if (index < 0) {
		return finder.feature(ref.getEReference());
	} else {
		List<ISemanticRegion> list = finder.features(ref.getEReference());
		if (list != null && index < list.size()) {
			return list.get(index);
		}
	}
	return null;
}
 
Example #7
Source File: PartialSerializer.java    From xtext-core with Eclipse Public License 2.0 6 votes vote down vote up
protected IAstRegion findRegion(IEObjectRegion owner, FeatureChange change) {
	EStructuralFeature feature = change.getFeature();
	if (feature instanceof EReference && ((EReference) feature).isContainment()) {
		ITextRegionAccess access = owner.getTextRegionAccess();
		EObject oldValue = change.getReferenceValue();
		if (oldValue != null) {
			return access.regionForEObject(oldValue);
		}
		for (IAstRegion astRegion : owner.getAstRegions()) {
			if (astRegion instanceof IEObjectRegion) {
				if (feature.equals(astRegion.getContainingFeature())) {
					return  astRegion;
				}
			}
		}
		return null;
	} else {
		return owner.getRegionFor().feature(feature);
	}
}
 
Example #8
Source File: FormatterSmokeSuite.java    From xtext-xtend with Eclipse Public License 2.0 6 votes vote down vote up
@Override
public void processFile(String data) throws Exception {
	byte[] hash = ((MessageDigest) messageDigest.clone()).digest(data.getBytes("UTF-8"));
	if (seen.add(new BigInteger(hash))) {
		XtextResourceSet resourceSet = resourceSetProvider.get();
		resourceSet.setClasspathURIContext(classLoader);
		XtendFile file = parseHelper.parse(data, resourceSet);
		if (file != null) {
			try {
				XtextResource resource = (XtextResource) file.eResource();
				ITextRegionAccess regions = regionBuilder.get().forNodeModel(resource).create();
				FormatterRequest request = new FormatterRequest().setTextRegionAccess(regions);
				request.setExceptionHandler(ExceptionAcceptor.IGNORING);
				formatter.format(request);
			} catch (Exception e) {
				e.printStackTrace();
				ComparisonFailure error = new ComparisonFailure(e.getMessage(), data, "");
				error.setStackTrace(e.getStackTrace());
				throw error;
			}
		}
	}
}
 
Example #9
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 #10
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 #11
Source File: LineRegion.java    From xtext-core with Eclipse Public License 2.0 6 votes vote down vote up
@Override
public ILineRegion getPreviousLine() {
	ITextRegionAccess access = getTextRegionAccess();
	int end = getOffset() - 1;
	String text = access.regionForDocument().getText();
	while (true) {
		if (end < 0)
			return null;
		char c = text.charAt(end);
		if (c == '\n' || c == '\r')
			end--;
		else
			break;
	}
	int start = text.lastIndexOf('\n', end);
	if (start < 0)
		start = 0;
	return new LineRegion(access, start, end - start);
}
 
Example #12
Source File: LineRegion.java    From xtext-core with Eclipse Public License 2.0 6 votes vote down vote up
@Override
public ILineRegion getNextLine() {
	ITextRegionAccess access = getTextRegionAccess();
	int start = getEndOffset() + 1;
	String text = access.regionForDocument().getText();
	while (true) {
		if (start >= text.length())
			return null;
		char c = text.charAt(start);
		if (c == '\n' || c == '\r')
			start++;
		else
			break;
	}
	int end = text.indexOf('\n', start);
	if (end > 0) {
		if (text.charAt(end - 1) == '\r')
			end = end - 1;
	} else
		end = text.length();
	return new LineRegion(access, start, end - start);
}
 
Example #13
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 #14
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 #15
Source File: RegionAccessBuilderTest.java    From xtext-core with Eclipse Public License 2.0 6 votes vote down vote up
private void assertToStringDoesNotCrash(final ITextRegionAccess access) {
  IHiddenRegion _previousHiddenRegion = access.regionForRootEObject().getPreviousHiddenRegion();
  ISequentialRegion current = ((ISequentialRegion) _previousHiddenRegion);
  while ((current != null)) {
    {
      Assert.assertNotNull(current.toString());
      boolean _matched = false;
      if (current instanceof IHiddenRegion) {
        _matched=true;
        current = ((IHiddenRegion)current).getNextSemanticRegion();
      }
      if (!_matched) {
        if (current instanceof ISemanticRegion) {
          _matched=true;
          Assert.assertNotNull(((ISemanticRegion)current).getEObjectRegion().toString());
          current = ((ISemanticRegion)current).getNextHiddenRegion();
        }
      }
    }
  }
}
 
Example #16
Source File: RegionAccessDiffTest.java    From xtext-core with Eclipse Public License 2.0 5 votes vote down vote up
@Test
public void testInsertReplaceReplace() throws Exception {
  StringConcatenation _builder = new StringConcatenation();
  _builder.append("8 a");
  _builder.newLine();
  final ITextRegionAccess access = this._regionAccessTestHelper.toTextRegionAccess(_builder);
  final Procedure1<ITextRegionDiffBuilder> _function = (ITextRegionDiffBuilder it) -> {
    @Extension
    final ITextRegionExtensions ext = access.getExtensions();
    EObject _semanticElement = access.regionForRootEObject().getSemanticElement();
    final ValueList rootObj = ((ValueList) _semanticElement);
    final ISemanticRegion a = ext.regionFor(rootObj).keyword("8").getNextSemanticRegion();
    it.replace(a, "b");
    it.replace(a, "c");
  };
  ITextRegionAccess _modify = this._regionAccessTestHelper.modify(access, _function);
  StringConcatenation _builder_1 = new StringConcatenation();
  _builder_1.append("0 0   H");
  _builder_1.newLine();
  _builder_1.append("      ");
  _builder_1.append("B ValueList\'[a]\' Root");
  _builder_1.newLine();
  _builder_1.append("0 1    S \"8\"        Root:\'8\'");
  _builder_1.newLine();
  _builder_1.append("1 1    H \" \"        Whitespace:TerminalRule\'WS\'");
  _builder_1.newLine();
  _builder_1.append("2 1 1  S \"c\"        ValueList:name+=ID");
  _builder_1.newLine();
  _builder_1.append("      ");
  _builder_1.append("E ValueList\'[a]\' Root");
  _builder_1.newLine();
  _builder_1.append("3 0   H");
  _builder_1.newLine();
  _builder_1.append("------------ diff 1 ------------");
  _builder_1.newLine();
  _builder_1.append("2 1 S \"a\"        ValueList:name+=ID");
  _builder_1.newLine();
  this._regionAccessTestHelper.operator_tripleEquals(_modify, _builder_1);
}
 
Example #17
Source File: PartialSerializerTest.java    From xtext-core with Eclipse Public License 2.0 5 votes vote down vote up
@Test
public void testMandatoryValueChange() {
  final IChangeSerializer.IModification<MandatoryValue> _function = (MandatoryValue it) -> {
    it.setName("bar");
  };
  ITextRegionAccess _recordDiff = this.<MandatoryValue>recordDiff(MandatoryValue.class, "#2 foo", _function);
  StringConcatenation _builder = new StringConcatenation();
  _builder.append("0 0   H");
  _builder.newLine();
  _builder.append("      ");
  _builder.append("B MandatoryValue\'bar\'  Model");
  _builder.newLine();
  _builder.append("0 2    S \"#2\"                 Model:\'#2\'");
  _builder.newLine();
  _builder.append("2 1    H \" \"                  Whitespace:TerminalRule\'WS\'");
  _builder.newLine();
  _builder.append("3 3 1  S \"bar\"                MandatoryValue:name=ID");
  _builder.newLine();
  _builder.append("      ");
  _builder.append("E MandatoryValue\'bar\'  Model");
  _builder.newLine();
  _builder.append("6 0   H");
  _builder.newLine();
  _builder.append("------------ diff 1 ------------");
  _builder.newLine();
  _builder.append("3 3 S \"foo\"                MandatoryValue:name=ID");
  _builder.newLine();
  this._changeSerializerTestHelper.operator_tripleEquals(_recordDiff, _builder);
}
 
Example #18
Source File: PartialSerializerTest.java    From xtext-core with Eclipse Public License 2.0 5 votes vote down vote up
@Test
public void testOptionalValueInsert() {
  final IChangeSerializer.IModification<OptionalValue> _function = (OptionalValue it) -> {
    it.setName("foo");
  };
  ITextRegionAccess _recordDiff = this.<OptionalValue>recordDiff(OptionalValue.class, "#3", _function);
  StringConcatenation _builder = new StringConcatenation();
  _builder.append("0 0 1 H");
  _builder.newLine();
  _builder.append("      ");
  _builder.append("B OptionalValue\'foo\'   Model");
  _builder.newLine();
  _builder.append("0 2 1  S \"#3\"                 Model:\'#3\'");
  _builder.newLine();
  _builder.append("2 0 1  H");
  _builder.newLine();
  _builder.append("2 3 1  S \"foo\"                OptionalValue:name=ID");
  _builder.newLine();
  _builder.append("      ");
  _builder.append("E OptionalValue\'foo\'   Model");
  _builder.newLine();
  _builder.append("5 0 1 H");
  _builder.newLine();
  _builder.append("------------ diff 1 ------------");
  _builder.newLine();
  _builder.append("0 0 H");
  _builder.newLine();
  _builder.append("0 2 S \"#3\"                 Model:\'#3\'");
  _builder.newLine();
  _builder.append("2 0 H");
  _builder.newLine();
  this._changeSerializerTestHelper.operator_tripleEquals(_recordDiff, _builder);
}
 
Example #19
Source File: TextRegionsInTextToString.java    From xtext-core with Eclipse Public License 2.0 5 votes vote down vote up
@Override
public String toString() {
	try {
		ITextRegionAccess access = getTextRegionAccess();
		ITextSegment frame = getFrame();
		if (access == null || frame == null)
			return box(title, "(no changes)");
		StringBuilder builder = new StringBuilder();
		String vizualized = access.getRewriter().renderToString(frame, items);
		builder.append(box(title, vizualized));
		return builder.toString();
	} catch (Exception e) {
		return box("error", e.getMessage() + "\n" + Throwables.getStackTraceAsString(e));
	}
}
 
Example #20
Source File: TextRegionAccessToString.java    From xtext-core with Eclipse Public License 2.0 5 votes vote down vote up
public DiffColumn(ITextRegionAccess access) {
	if (access instanceof ITextRegionAccessDiff) {
		this.diffs = Maps.newHashMap();
		this.access = (ITextRegionAccessDiff) access;
		int width = 0;
		int i = 1;
		for (ITextSegmentDiff diff : this.access.getRegionDifferences()) {
			ISequentialRegion current = toSequential(diff.getModifiedFirstRegion());
			ISequentialRegion last = toSequential(diff.getModifiedLastRegion());
			String text = i + " ";
			if (width < text.length()) {
				width = text.length();
			}
			while (current != null) {
				diffs.put(current, text);
				if (current.getOffset() >= last.getOffset()) {
					break;
				}
				current = current.getNextSequentialRegion();
			}
			i++;
		}
		this.empty = Strings.repeat(" ", width);
	} else {
		this.access = null;
		this.empty = "";
	}
}
 
Example #21
Source File: FormatterXpectMethod.java    From n4js with Eclipse Public License 1.0 5 votes vote down vote up
private ITextSegment findRegion(int lines, XpectInvocation inv, TargetSyntaxSupport syntax, ITextRegionAccess reg) {
	XtextResource resource = ((XtextTargetSyntaxSupport) syntax).getResource();

	IStatementRelatedRegion region2 = inv.getExtendedRegion();
	int end = region2.getOffset() + region2.getLength();
	ILeafNode node = NodeModelUtils.findLeafNodeAtOffset(resource.getParseResult().getRootNode(), end);

	int offset = node.getTotalEndOffset();
	ITextSegment region = getRegionForLines(reg, offset, lines);
	return region;
}
 
Example #22
Source File: PartialSerializerTest.java    From xtext-core with Eclipse Public License 2.0 5 votes vote down vote up
@Test
public void testOptionalChildRemoveListAllOne() {
  final IChangeSerializer.IModification<OptionalChildList> _function = (OptionalChildList it) -> {
    EcoreUtil.remove(it.getChildren().get(0));
  };
  ITextRegionAccess _recordDiff = this.<OptionalChildList>recordDiff(OptionalChildList.class, "#13 x1", _function);
  StringConcatenation _builder = new StringConcatenation();
  _builder.append("0 0   H");
  _builder.newLine();
  _builder.append("      ");
  _builder.append("B OptionalChildList    Model");
  _builder.newLine();
  _builder.append("0 3    S \"#13\"                Model:\'#13\'");
  _builder.newLine();
  _builder.append("      ");
  _builder.append("E OptionalChildList    Model");
  _builder.newLine();
  _builder.append("3 1 1 H \" \"                  Whitespace:TerminalRule\'WS\'");
  _builder.newLine();
  _builder.append("------------ diff 1 ------------");
  _builder.newLine();
  _builder.append("3 1  H \" \"                  Whitespace:TerminalRule\'WS\'");
  _builder.newLine();
  _builder.append("4 2  S \"x1\"                 MandatoryValue:name=ID");
  _builder.newLine();
  _builder.append("6 0  H");
  _builder.newLine();
  this._changeSerializerTestHelper.operator_tripleEquals(_recordDiff, _builder);
}
 
Example #23
Source File: ReferenceUpdater.java    From xtext-core with Eclipse Public License 2.0 5 votes vote down vote up
protected void updateExternalReferences(IReferenceUpdaterContext context, RelatedResource relatedResource) {
	ITextRegionAccess document = context.getModifyableDocument().getOriginalTextRegionAccess();
	for (IReferenceSnapshot ref : relatedResource.outgoingReferences) {
		ISemanticRegion region = getRegion(document, ref);
		if (region != null) {
			IUpdatableReference updatable = createUpdatableReference(region);
			if (updatable != null && needsUpdating(context, updatable)) {
				context.updateReference(updatable);
			}
		}
	}
}
 
Example #24
Source File: TextReplacerContext.java    From xtext-core with Eclipse Public License 2.0 5 votes vote down vote up
@Override
public boolean isWrapSincePrevious() {
	ITextRegionAccess access = getDocument().getRequest().getTextRegionAccess();
	ITextSegment region = getRegion(0);
	ITextSegment previousRegion = getRegion(1);
	if (previousRegion != null) {
		int offset = previousRegion.getEndOffset();
		String between = access.textForOffset(offset, region.getOffset() - offset);
		if (between.contains("\n")) {
			return true;
		}
	}
	return false;
}
 
Example #25
Source File: BugSinglelineCommentIndentation.java    From sarl with Apache License 2.0 5 votes vote down vote up
/** Fixing the bug.
 *
 * @param context the replacement context.
 * @param comment the comment for which the fix must be applied.
 * @return the new context.
 */
@SuppressWarnings("static-method")
public ITextReplacerContext fix(final ITextReplacerContext context, IComment comment) {
	final IHiddenRegion hiddenRegion = comment.getHiddenRegion();
	if (detectBugSituation(hiddenRegion)
			&& fixBug(hiddenRegion)) {
		// Indentation of the first comment line
		final ITextRegionAccess access = comment.getTextRegionAccess();
		final ITextSegment target = access.regionForOffset(comment.getOffset(), 0);
		context.addReplacement(target.replaceWith(context.getIndentationString(1)));
	}
	return context;
}
 
Example #26
Source File: FormatterRequest.java    From xtext-core with Eclipse Public License 2.0 5 votes vote down vote up
/**
 * Sets the {@link #textRegionAccess}. If the region has syntax errors and no explicit {@link ExceptionAcceptor} is
 * configured yet, the {@link ExceptionAcceptor#IGNORING ignoring acceptor} will be configured.
 */
public FormatterRequest setTextRegionAccess(ITextRegionAccess tokens) {
	if (tokens.hasSyntaxError() && this.exceptionHandler == null)
		this.exceptionHandler = ExceptionAcceptor.IGNORING;
	this.textRegionAccess = tokens;
	return this;
}
 
Example #27
Source File: AbstractTextSegment.java    From xtext-core with Eclipse Public License 2.0 5 votes vote down vote up
@Override
public String getText() {
	ITextRegionAccess access = getTextRegionAccess();
	if (access != null)
		return ((AbstractRegionAccess) access).textForOffset(getOffset(), getLength());
	return null;
}
 
Example #28
Source File: NodeModelBasedRegionAccessBuilder.java    From xtext-core with Eclipse Public License 2.0 5 votes vote down vote up
protected Map<EObject, AbstractEObjectRegion> getEObjectToTokensMap(ITextRegionAccess regionAccess) {
	this.eObjToTokens = Maps.newHashMap();
	this.firstHidden = createHiddenRegion(regionAccess);
	this.lastHidden = this.firstHidden;
	NodeModelBasedRegionAccess access = (NodeModelBasedRegionAccess) regionAccess;
	ICompositeNode rootNode = resource.getParseResult().getRootNode();
	process(rootNode, access);
	return ImmutableMap.<EObject, AbstractEObjectRegion>copyOf(this.eObjToTokens);
}
 
Example #29
Source File: PartialSerializerTest.java    From xtext-core with Eclipse Public License 2.0 5 votes vote down vote up
@Test
public void testOptionalChildRemove() {
  final IChangeSerializer.IModification<OptionalChild> _function = (OptionalChild it) -> {
    it.setChild(null);
  };
  ITextRegionAccess _recordDiff = this.<OptionalChild>recordDiff(OptionalChild.class, "#5 foo", _function);
  StringConcatenation _builder = new StringConcatenation();
  _builder.append("0 0   H");
  _builder.newLine();
  _builder.append("      ");
  _builder.append("B OptionalChild        Model");
  _builder.newLine();
  _builder.append("0 2    S \"#5\"                 Model:\'#5\'");
  _builder.newLine();
  _builder.append("      ");
  _builder.append("E OptionalChild        Model");
  _builder.newLine();
  _builder.append("2 1 1 H \" \"                  Whitespace:TerminalRule\'WS\'");
  _builder.newLine();
  _builder.append("------------ diff 1 ------------");
  _builder.newLine();
  _builder.append("2 1  H \" \"                  Whitespace:TerminalRule\'WS\'");
  _builder.newLine();
  _builder.append("3 3  S \"foo\"                MandatoryValue:name=ID");
  _builder.newLine();
  _builder.append("6 0  H");
  _builder.newLine();
  this._changeSerializerTestHelper.operator_tripleEquals(_recordDiff, _builder);
}
 
Example #30
Source File: TextReplacement.java    From xtext-core with Eclipse Public License 2.0 5 votes vote down vote up
public TextReplacement(ITextRegionAccess access, int offset, int length, String text) {
	super();
	Preconditions.checkArgument(offset >= 0, "offset must be >= 0");
	Preconditions.checkArgument(length >= 0, "length must be >= 0");
	this.access = access;
	this.offset = offset;
	this.length = length;
	this.replacement = text;
}