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

The following examples show how to use org.eclipse.xtext.formatting2.regionaccess.ITextSegment. 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: 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 #2
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 #3
Source File: TestableTextSegmentSet.java    From xtext-core with Eclipse Public License 2.0 6 votes vote down vote up
@Override
public String toString() {
  StringConcatenation _builder = new StringConcatenation();
  _builder.append("issues=");
  String _join = IterableExtensions.join(this.issues, ", ");
  _builder.append(_join);
  _builder.newLineIfNotEmpty();
  _builder.append("set=");
  final Function1<ITextSegment, String> _function = (ITextSegment it) -> {
    StringConcatenation _builder_1 = new StringConcatenation();
    _builder_1.append("[");
    int _offset = it.getOffset();
    _builder_1.append(_offset);
    _builder_1.append(",");
    int _length = it.getLength();
    _builder_1.append(_length);
    _builder_1.append("]");
    return _builder_1.toString();
  };
  String _replace = IterableExtensions.<ITextSegment, String>map(this.set, _function).toString().replace("\n", ", ");
  _builder.append(_replace);
  _builder.newLineIfNotEmpty();
  return _builder.toString();
}
 
Example #4
Source File: TextRegionAccessToString.java    From xtext-core with Eclipse Public License 2.0 6 votes vote down vote up
public void appendDiffs(TextRegionListToString result, TextRegionAccessToString toStr) {
	if (this.access == null) {
		return;
	}
	int i = 1;
	for (ITextSegmentDiff diff : this.access.getRegionDifferences()) {
		ISequentialRegion current = toSequential(diff.getOriginalFirstRegion());
		ISequentialRegion last = toSequential(diff.getOriginalLastRegion());
		List<ITextSegment> regions = Lists.newArrayList();
		while (current != null) {
			regions.add(current);
			if (current.getOffset() >= last.getOffset()) {
				break;
			}
			current = current.getNextSequentialRegion();
		}
		result.add("------------ diff " + i + " ------------", false);
		toStr.appendRegions(result, regions, new DiffColumn(null), true);
		i++;
	}

}
 
Example #5
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 #6
Source File: TextRegionAccessToString.java    From xtext-core with Eclipse Public License 2.0 6 votes vote down vote up
protected String toString(ITextSegment region) {
	String result;
	if (region instanceof IEObjectRegion)
		result = toString((IEObjectRegion) region);
	else if (region instanceof ISemanticRegion)
		result = toString((ISemanticRegion) region);
	else if (region instanceof IHiddenRegion)
		result = toString((IHiddenRegion) region);
	else if (region instanceof IWhitespace)
		result = toString((IWhitespace) region);
	else if (region instanceof IComment)
		result = toString((IComment) region);
	else if (region != null)
		result = region.getClass().getName() + "@" + Integer.toHexString(System.identityHashCode(region));
	else
		result = "null";
	if (hightlightOrigin && region == origin)
		return ">>>" + result + "<<<";
	return result;
}
 
Example #7
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 #8
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 #9
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 #10
Source File: ConditionalReplacer.java    From xtext-core with Eclipse Public License 2.0 6 votes vote down vote up
@Override
public ITextReplacerContext createReplacements(ITextReplacerContext context) {
	context.setNextReplacerIsChild();
	for (ISubFormatter formatter : subFormatters) {
		try {
			ITextSegment region = getRegion();
			SubDocument subDocument = new SubDocument(region, getDocument());
			for (ITextReplacer replacer : replacers)
				subDocument.addReplacer(replacer);
			formatter.format(subDocument);
			ITextReplacerContext first = context.withReplacer(subDocument);
			ITextReplacerContext last = subDocument.createReplacements(first);
			return last;
		} catch (FormattingNotApplicableException e) {
			// no need to do anything.
			// Try the next SubFormatter until one doens't throw a FormattingNotApplicableException 
		}
	}
	throw new FormattingNotApplicableException();
}
 
Example #11
Source File: ObjectEntry.java    From xtext-extras with Eclipse Public License 2.0 6 votes vote down vote up
public ITextSegment getRegion() {
	SeparatorEntry<T, R> prev = getLeadingSeparator();
	SeparatorEntry<T, R> trail = getTrailingSeparator();
	final int offset;
	if (prev != null) {
		offset = prev.getSeparator().getEndOffset();
	} else {
		offset = list.getRoot().getOffset();
	}
	final int endOffset;
	if (trail != null) {
		endOffset = trail.getSeparator().getOffset();
	} else {
		endOffset = list.getRoot().getEndOffset();
	}
	return new TextSegment(list.getRoot().getTextRegionAccess(), offset, endOffset - offset);
}
 
Example #12
Source File: FormattableDocument.java    From xtext-core with Eclipse Public License 2.0 6 votes vote down vote up
@Override
public void addReplacer(ITextReplacer replacer) {
	if (!this.getRegion().contains(replacer.getRegion())) {
		String frameTitle = getClass().getSimpleName();
		ITextSegment frameRegion = getRegion();
		String replacerTitle = replacer.getClass().getSimpleName();
		ITextSegment replacerRegion = replacer.getRegion();
		RegionsOutsideFrameException exception = new RegionsOutsideFrameException(frameTitle, frameRegion,
				Tuples.create(replacerTitle, replacerRegion));
		getRequest().getExceptionHandler().accept(exception);
		return;
	}
	try {
		getReplacers().add(replacer, getFormatter().createTextReplacerMerger());
	} catch (ConflictingRegionsException e) {
		getRequest().getExceptionHandler().accept(e);
	}
}
 
Example #13
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 #14
Source File: TextRegionAccessToString.java    From xtext-core with Eclipse Public License 2.0 5 votes vote down vote up
public String get(ITextSegment seg) {
	if (this.access == null) {
		return "";
	}
	String result = this.diffs.get(seg);
	if (result != null)
		return result;
	return empty;
}
 
Example #15
Source File: StringBasedTextRegionAccessDiffAppender.java    From xtext-core with Eclipse Public License 2.0 5 votes vote down vote up
public StringBasedTextRegionAccessDiffAppender(ITextRegionAccess base, Map<ITextSegment, String> textChanges) {
	super();
	this.result = new StringBasedTextRegionAccessDiff(base);
	this.textChanges = textChanges;
	IHiddenRegion region = base.regionForRootEObject().getPreviousHiddenRegion();
	this.diffLastOriginal = region;
	this.diffLastCopy = appendHiddenRegion(region.isUndefined());
}
 
Example #16
Source File: TextRegionsWithTitleToString.java    From xtext-core with Eclipse Public License 2.0 5 votes vote down vote up
public ITextSegment getFrame() {
	if (this.frame != null)
		return this.frame;
	ITextRegionAccess access = getTextRegionAccess();
	if (access != null) {
		List<ITextSegment> segments = Lists.newArrayList();
		for (Item item : items)
			segments.add(item.getRegion());
		ITextSegment impactRegion = merge(segments);
		List<ILineRegion> expandToLines = expandToLines(impactRegion, getLeadingLines(), getTrailingLines());
		return merge(expandToLines);
	}
	return null;
}
 
Example #17
Source File: StringBasedTextRegionAccessDiffAppender.java    From xtext-core with Eclipse Public License 2.0 5 votes vote down vote up
protected void recordDiff(ITextSegment original, ITextSegment copy) {
	if (diffNesting == 0) {
		Preconditions.checkArgument(original.getTextRegionAccess() == result.getOriginalTextRegionAccess());
	}
	if (diffFirstOriginal != null && diffFirstCopy != null && diffNesting == 0) {
		result.append(new SequentialRegionDiff(diffFirstOriginal, original, diffFirstCopy, copy));
		diffFirstCopy = null;
		diffFirstOriginal = null;
	}
	diffLastOriginal = original;
	diffLastCopy = copy;
}
 
Example #18
Source File: FormatterXpectMethod.java    From n4js with Eclipse Public License 1.0 5 votes vote down vote up
private ITextSegment getRegionForLines(ITextRegionAccess regions, int offset, int lines) {
	ILineRegion firstLine = regions.regionForLineAtOffset(offset);
	ILineRegion lastLine = firstLine;
	for (int i = 1; i < lines; i++) {
		ILineRegion next = lastLine.getNextLine();
		if (next != null) {
			lastLine = next;
		} else {
			break;
		}
	}
	int firstLineOffset = firstLine.getOffset();
	ITextSegment region = regions.regionForOffset(firstLineOffset, (lastLine.getEndOffset() - firstLineOffset) + 1);
	return region;
}
 
Example #19
Source File: TextRegionRewriter.java    From xtext-core with Eclipse Public License 2.0 5 votes vote down vote up
@Override
public String renderToString(ITextSegment input, Iterable<? extends ITextReplacement> replacements) {
	StringBuilder result = new StringBuilder();
	try {
		renderToAppendable(input, replacements, result);
	} catch (IOException e) {
		throw new RuntimeException(e);
	}
	return result.toString();
}
 
Example #20
Source File: AbstractTextSegment.java    From xtext-core with Eclipse Public License 2.0 5 votes vote down vote up
@Override
public int compareTo(ITextSegment o) {
	int cmp1 = getOffset() - o.getOffset();
	if (cmp1 != 0)
		return cmp1;
	int cmp2 = getLength() - o.getLength();
	if (cmp2 != 0)
		return cmp2;
	return 0;
}
 
Example #21
Source File: DocumentationFormatter.java    From sarl with Apache License 2.0 5 votes vote down vote up
public void applyReplacements() {
	checkNotApplied();
	for (Replacement replacement : getReplacements().values()) {
		ITextSegment target = this.access.regionForOffset(replacement.getOffset() + getCommentOffset(), replacement.getLength());
		this.context.addReplacement(target.replaceWith(replacement.getText()));
	}
}
 
Example #22
Source File: SequentialRegionDiff.java    From xtext-core with Eclipse Public License 2.0 5 votes vote down vote up
public SequentialRegionDiff(ITextSegment originalFirst, ITextSegment originalLast, ITextSegment substituteFirst,
		ITextSegment substituteLast) {
	super();
	this.originalFirst = originalFirst;
	this.originalLast = originalLast;
	this.substituteFirst = substituteFirst;
	this.substituteLast = substituteLast;
}
 
Example #23
Source File: SequentialRegionDiff.java    From xtext-core with Eclipse Public License 2.0 5 votes vote down vote up
@Override
public ITextSegment getOriginalRegion() {
	if (isSingleSemanticRegion()) {
		return originalFirst;
	}
	return getRegion(originalFirst, originalLast);
}
 
Example #24
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 #25
Source File: AbstractHiddenRegion.java    From xtext-core with Eclipse Public License 2.0 5 votes vote down vote up
protected List<ITextSegment> collectAlternatingSpaceAndComments(boolean includeComments) {
	List<IHiddenRegionPart> parts = getParts();
	if (parts.isEmpty()) {
		return Collections.<ITextSegment>singletonList(this);
	} else {
		ITextSegment lastWhitespace = null;
		List<ITextSegment> result = Lists.newArrayList();
		for (IHiddenRegionPart part : parts) {
			if (part instanceof IWhitespace) {
				if (lastWhitespace == null) {
					result.add(part);
					lastWhitespace = part;
				} else {
					int mergedLength = lastWhitespace.getLength() + part.getLength();
					lastWhitespace = new TextSegment(access, lastWhitespace.getOffset(), mergedLength);
					result.set(result.size() - 1, lastWhitespace);
				}
			} else if (part instanceof IComment) {
				if (lastWhitespace == null) {
					result.add(new TextSegment(access, part.getOffset(), 0));
				} else {
					lastWhitespace = null;
				}
				if (includeComments) {
					result.add(part);
				}
			}
		}
		if (lastWhitespace == null) {
			result.add(new TextSegment(access, getEndOffset(), 0));
		}
		return ImmutableList.copyOf(result);
	}
}
 
Example #26
Source File: RegionDiffFormatter.java    From xtext-core with Eclipse Public License 2.0 5 votes vote down vote up
protected Collection<ITextRegion> collectRegionsToFormat(ITextRegionAccessDiff regions) {
	List<ITextRegion> result = Lists.newArrayList();
	for (ITextSegmentDiff diff : regions.getRegionDifferences()) {
		int offset = diff.getModifiedFirstRegion().getOffset();
		int length = diff.getModifiedLastRegion().getEndOffset() - offset;
		ITextSegment region = regions.regionForOffset(offset, length);
		result.add(region);
	}
	return result;
}
 
Example #27
Source File: SinglelineDocCommentReplacer.java    From xtext-core with Eclipse Public License 2.0 5 votes vote down vote up
@Override
public ITextReplacerContext createReplacements(ITextReplacerContext context) {
	ITextSegment firstSpace = getFirstSpace();
	if (firstSpace != null) {
		if (hasEmptyBody())
			context.addReplacement(firstSpace.replaceWith(""));
		else
			context.addReplacement(firstSpace.replaceWith(" "));
	}
	return context;
}
 
Example #28
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 #29
Source File: TextSegmentSet.java    From xtext-core with Eclipse Public License 2.0 5 votes vote down vote up
public TextSegmentSet(Function<? super T, ? extends ITextSegment> region, Function<? super T, String> title,
		boolean trace) {
	super();
	this.regionGetter = region;
	this.titleGetter = title;
	this.traces = trace ? new IdentityHashMap<T, RegionTrace>() : null;
}
 
Example #30
Source File: TextSegmentSet.java    From xtext-core with Eclipse Public License 2.0 5 votes vote down vote up
protected boolean isConflict(ITextSegment region1, ITextSegment region2) {
	int offset1 = region1.getOffset();
	int length1 = region1.getLength();
	int offset2 = region2.getOffset();
	int length2 = region2.getLength();
	if (offset1 < offset2) {
		return offset1 + length1 > offset2;
	} else if (offset1 > offset2) {
		return offset2 + length2 > offset1;
	}
	return !(length1 == 0 ^ length2 == 0);
}