Java Code Examples for org.eclipse.xtext.ui.editor.model.IXtextDocument#get()

The following examples show how to use org.eclipse.xtext.ui.editor.model.IXtextDocument#get() . 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: ChangeProvider.java    From n4js with Eclipse Public License 1.0 6 votes vote down vote up
/**
 * Insert the given string as a new line above the line at the given offset. The given string need not contain any
 * line delimiters and the offset need not point to the beginning of a line. If 'sameIndentation' is set to
 * <code>true</code>, the new line will be indented as the line at the given offset (i.e. same leading white space).
 */
public static IChange insertLineAbove(IXtextDocument doc, int offset, String txt, boolean sameIndentation)
		throws BadLocationException {
	final String NL = lineDelimiter(doc, offset);
	final IRegion currLineReg = doc.getLineInformationOfOffset(offset);
	String indent = "";
	if (sameIndentation) {
		final String currLine = doc.get(currLineReg.getOffset(), currLineReg.getLength());
		int idx = 0;
		while (idx < currLine.length() && Character.isWhitespace(currLine.charAt(idx))) {
			idx++;
		}
		indent = currLine.substring(0, idx);
	}
	return new Replacement(getURI(doc), currLineReg.getOffset(), 0, indent + txt + NL);
}
 
Example 2
Source File: ChangeProvider.java    From n4js with Eclipse Public License 1.0 6 votes vote down vote up
/**
 * Removes text of the given length at the given offset. If 'removeEntireLineIfEmpty' is set to <code>true</code>,
 * the line containing the given text region will be deleted entirely iff the change would leave the line empty
 * (i.e. contains only white space) <em>after</em> the removal of the text region.
 */
public static IChange removeText(IXtextDocument doc, int offset, int length, boolean removeEntireLineIfEmpty)
		throws BadLocationException {
	if (!removeEntireLineIfEmpty) {
		// simple
		return new Replacement(getURI(doc), offset, length, "");
	} else {
		// get entire line containing the region to be removed
		// OR in case the region spans multiple lines: get *all* lines affected by the removal
		final IRegion linesRegion = DocumentUtilN4.getLineInformationOfRegion(doc, offset, length, true);
		final String lines = doc.get(linesRegion.getOffset(), linesRegion.getLength());
		// simulate the removal
		final int offsetRelative = offset - linesRegion.getOffset();
		final String lineAfterRemoval = removeSubstring(lines, offsetRelative, length);
		final boolean isEmptyAfterRemoval = lineAfterRemoval.trim().isEmpty();
		if (isEmptyAfterRemoval) {
			// remove entire line (or in case the removal spans multiple lines: remove all affected lines entirely)
			return new Replacement(getURI(doc),
					linesRegion.getOffset(), linesRegion.getLength(), "");
		} else {
			// just remove the given text region
			return new Replacement(getURI(doc), offset, length, "");
		}
	}
}
 
Example 3
Source File: SolidityFoldingRegionProvider.java    From solidity-ide with Eclipse Public License 1.0 6 votes vote down vote up
@Override
protected void computeCommentFolding(IXtextDocument xtextDocument,
		IFoldingRegionAcceptor<ITextRegion> foldingRegionAcceptor, ITypedRegion typedRegion,
		boolean initiallyFolded) {

	String text;
	try {
		text = xtextDocument.get(typedRegion.getOffset(), typedRegion.getLength());
		int lines = Strings.countLines(text);
		if (shouldCreateCommentFolding(lines)) {
			boolean collapse = shouldCollapse(typedRegion, lines);
			super.computeCommentFolding(xtextDocument, foldingRegionAcceptor, typedRegion, collapse);
		}
	} catch (BadLocationException e) {
		log.error(e, e);
	}

}
 
Example 4
Source File: ContentFormatterFactory.java    From xtext-eclipse with Eclipse Public License 2.0 6 votes vote down vote up
/**
 * Create a text edit from the given replace region.
 * The default impl will strip the common leading and trailing parts of the replaced region and the replacement text. 
 * 
 * @since 2.8
 */
protected TextEdit createTextEdit(IXtextDocument doc, ReplaceRegion r) throws BadLocationException {
	String originalText = doc.get(r.getOffset(), r.getLength());
	String newText = r.getText();
	int start = 0;
	int originalEnd = originalText.length() - 1;
	int newEnd = newText.length() - 1;
	int minLen = Math.min(r.getLength(), newText.length());
	while(start < minLen && originalText.charAt(start) == newText.charAt(start)) {
		start++;
	}
	while (originalEnd >= start
			&& newEnd >= start
			&& originalText.charAt(originalEnd) == newText.charAt(newEnd)) {
		originalEnd--;
		newEnd--;
	}
	return new ReplaceEdit(r.getOffset() + start, originalEnd - start + 1, r.getText().substring(start, newEnd + 1));
}
 
Example 5
Source File: CreateJavaTypeQuickfixes.java    From xtext-eclipse with Eclipse Public License 2.0 6 votes vote down vote up
@Override
public void addQuickfixes(Issue issue, IssueResolutionAcceptor issueResolutionAcceptor,
		IXtextDocument xtextDocument, XtextResource resource, 
		EObject referenceOwner, EReference unresolvedReference)
		throws Exception {
	String typeString = (issue.getData() != null && issue.getData().length > 0) 
			? issue.getData()[0] 
			: xtextDocument.get(issue.getOffset(), issue.getLength());
	Pair<String, String> packageAndType = typeNameGuesser.guessPackageAndTypeName(referenceOwner, typeString);
	String packageName = packageAndType.getFirst();
	if(isEmpty(packageAndType.getSecond()))
		return;
	String typeName = packageAndType.getSecond();
	if (unresolvedReference == XbasePackage.Literals.XCONSTRUCTOR_CALL__CONSTRUCTOR) {
		if(((XConstructorCall)referenceOwner).getConstructor().eIsProxy())
			newJavaClassQuickfix(typeName, packageName, resource, issue, issueResolutionAcceptor);
	} else if(unresolvedReference == XbasePackage.Literals.XTYPE_LITERAL__TYPE
			|| unresolvedReference == TypesPackage.Literals.JVM_PARAMETERIZED_TYPE_REFERENCE__TYPE) {
		newJavaClassQuickfix(typeName, packageName, resource, issue, issueResolutionAcceptor);
		newJavaInterfaceQuickfix(typeName, packageName, resource, issue, issueResolutionAcceptor);
	} else if(unresolvedReference == XAnnotationsPackage.Literals.XANNOTATION__ANNOTATION_TYPE) {
		newJavaAnnotationQuickfix(typeName, packageName, resource, issue, issueResolutionAcceptor);
	}
}
 
Example 6
Source File: AbstractQuickfixTest.java    From xtext-eclipse with Eclipse Public License 2.0 6 votes vote down vote up
protected void quickfixesAreOffered(XtextEditor editor, String issueCode, Quickfix... expected) {
	List<Quickfix> expectedSorted = Arrays.asList(expected);
	expectedSorted.sort(Comparator.comparing(e -> e.getLabel()));

	IXtextDocument document = editor.getDocument();
	String originalText = document.get();
	Issue issue = getValidationIssue(document, issueCode);

	List<IssueResolution> actualIssueResolutions = issueResolutionProvider.getResolutions(issue);
	actualIssueResolutions.sort(Comparator.comparing(i -> i.getLabel()));
	assertEquals("The number of quickfixes does not match!", expectedSorted.size(), actualIssueResolutions.size());

	for (int i = 0; i < actualIssueResolutions.size(); i++) {
		IssueResolution actualIssueResolution = actualIssueResolutions.get(i);
		Quickfix expectedIssueResolution = expectedSorted.get(i);
		assertEquals(expectedIssueResolution.label, actualIssueResolution.getLabel());
		assertEquals(expectedIssueResolution.description, actualIssueResolution.getDescription());
		assertIssueResolutionResult(expectedIssueResolution.result, actualIssueResolution, originalText);
	}
}
 
Example 7
Source File: AbstractQuickfixTest.java    From xtext-eclipse with Eclipse Public License 2.0 6 votes vote down vote up
protected void assertIssueResolutionResult(String expectedResult, IssueResolution actualIssueResolution, String originalText) {
	/*
	 * Manually create an IModificationContext with an XtextDocument and call the
	 * apply method of the actualIssueResolution with that IModificationContext
	 */
	IXtextDocument document = getDocument(originalText);
	TestModificationContext modificationContext = new TestModificationContext();
	modificationContext.setDocument(document);

	new IssueResolution(actualIssueResolution.getLabel(), //
			actualIssueResolution.getDescription(), //
			actualIssueResolution.getImage(), //
			modificationContext, //
			actualIssueResolution.getModification(), //
			actualIssueResolution.getRelevance()).apply();
	String actualResult = document.get();
	assertEquals(expectedResult, actualResult);
}
 
Example 8
Source File: StaticMethodImporterTestBuilder.java    From xtext-xtend with Eclipse Public License 2.0 6 votes vote down vote up
/**
 * Creates an Xtend file with the given content and perform the import static operation on it.
 */
public StaticMethodImporterTestBuilder create(final String fileName, final String content) {
  try {
    StaticMethodImporterTestBuilder _xblockexpression = null;
    {
      final String positionMarker = this.getPositionMarker(content);
      final IFile file = this.workbenchTestHelper.createFile(fileName, content.replace(positionMarker, ""));
      final int caretOffset = content.indexOf(positionMarker);
      final IXtextDocument document = this.workbenchTestHelper.openEditor(file).getDocument();
      this.syncUtil.totalSync(true);
      this.doImportStaticMethod(document, caretOffset);
      this.result = document.get();
      _xblockexpression = this;
    }
    return _xblockexpression;
  } catch (Throwable _e) {
    throw Exceptions.sneakyThrow(_e);
  }
}
 
Example 9
Source File: DocumentBasedDirtyResource.java    From xtext-eclipse with Eclipse Public License 2.0 5 votes vote down vote up
@Override
public String getActualContents() {
	IXtextDocument document = this.document;
	if (document == null)
		throw new IllegalStateException("Cannot use getActualContents if this dirty resource is not connected to a document");
	return document.get();
}
 
Example 10
Source File: DocumentBasedDirtyResource.java    From xtext-eclipse with Eclipse Public License 2.0 5 votes vote down vote up
/**
 * @since 2.8
 */
@Override
public String getActualContentsIfInitialized() {
	IXtextDocument document = this.document;
	if (document == null)
		return null;
	return document.get();
}
 
Example 11
Source File: DotHtmlLabelQuickfixDelegator.java    From gef with Eclipse Public License 2.0 5 votes vote down vote up
private String getModifiedText(String originalText,
		IssueResolution issueResolution) {
	/*
	 * manually create an IModificationContext with an XtextDocument and
	 * call the apply method of the issueResolution with that
	 * IModificationContext
	 */
	IXtextDocument document = getDocument(originalText);
	IModificationContext modificationContext = new IModificationContext() {

		@Override
		public IXtextDocument getXtextDocument() {
			return document;
		}

		@Override
		public IXtextDocument getXtextDocument(URI uri) {
			return document;
		}
	};

	new IssueResolution(issueResolution.getLabel(),
			issueResolution.getDescription(), issueResolution.getImage(),
			modificationContext, issueResolution.getModification(),
			issueResolution.getRelevance()).apply();
	return document.get();
}
 
Example 12
Source File: GamlHyperlinkDetector.java    From gama with GNU General Public License v3.0 5 votes vote down vote up
private IRegion importUriRegion(final IXtextDocument document, final int offset, final String importUri)
		throws BadLocationException {
	final int lineNumber = document.getLineOfOffset(offset);
	final int lineLength = document.getLineLength(lineNumber);
	final int lineOffset = document.getLineOffset(lineNumber);
	final String line = document.get(lineOffset, lineLength);
	final int uriIndex = line.indexOf(importUri);
	return new Region(lineOffset + uriIndex, importUri.length());
}
 
Example 13
Source File: OrganizeImportXpectMethod.java    From n4js with Eclipse Public License 1.0 4 votes vote down vote up
/**
 * Give the result as a multiline diff. If cancellation due to multiple possible resolution is expected, provide the
 * expected Exception with 'XPECT organizeImports ambiguous "Exception-Message" -->'.
 *
 * If the parameter is not provided, always the first computed solution in the list will be taken
 *
 * @param ambiguous
 *            - String Expectation in {@link BreakException}
 */
@ParameterParser(syntax = "('ambiguous' arg0=STRING)?")
@Xpect
@ConsumedIssues({ Severity.INFO, Severity.ERROR, Severity.WARNING })
public void organizeImports(
		String ambiguous, // arg0
		@StringDiffExpectation(whitespaceSensitive = false, allowSingleSegmentDiff = false, allowSingleLineDiff = false) IStringDiffExpectation expectation,
		@ThisResource XtextResource resource) throws Exception {

	logger.info("organize imports ...");
	boolean bAmbiguityCheck = ambiguous != null && ambiguous.trim().length() > 0;
	Interaction iaMode = bAmbiguityCheck ? Interaction.breakBuild : Interaction.takeFirst;

	try {

		if (expectation == null /* || expectation.isEmpty() */) {
			// TODO throw exception if empty.
			// Hey, I want to ask the expectation if it's empty.
			// Cannot access the region which could be asked for it's length.
			throw new AssertionFailedError(
					"The test is missing a diff: // XPECT organizeImports --> [old string replaced|new string expected] ");
		}

		// capture text for comparison:
		String beforeApplication = resource.getParseResult().getRootNode().getText();

		N4ContentAssistProcessorTestBuilder fixture = n4ContentAssistProcessorTestBuilderHelper
				.createTestBuilderForResource(resource);

		IXtextDocument xtextDoc = fixture.getDocument(resource, beforeApplication);

		// in case of cross-file hyperlinks, we have to make sure the target resources are fully resolved
		final ResourceSet resSet = resource.getResourceSet();
		for (Resource currRes : new ArrayList<>(resSet.getResources())) {
			N4JSResource.postProcess(currRes);
		}

		// Calling organize imports
		Display.getDefault().syncExec(
				() -> imortsOrganizer.unsafeOrganizeDocument(xtextDoc, iaMode));

		if (bAmbiguityCheck) {
			// should fail if here
			assertEquals("Expected ambiguous resolution to break the organize import command.", ambiguous, "");
		}

		// checking that no errors are left.
		String textAfterApplication = xtextDoc.get();

		// compare with expectation, it's a multiline-diff expectation.
		String before = XpectCommentRemovalUtil.removeAllXpectComments(beforeApplication);
		String after = XpectCommentRemovalUtil.removeAllXpectComments(textAfterApplication);

		expectation.assertDiffEquals(before, after);
	} catch (Exception exc) {
		if (exc instanceof RuntimeException && exc.getCause() instanceof BreakException) {
			String breakMessage = exc.getCause().getMessage();
			assertEquals(ambiguous, breakMessage);
		} else {
			throw exc;
		}
	}
}
 
Example 14
Source File: CreateXtendTypeQuickfixes.java    From xtext-xtend with Eclipse Public License 2.0 4 votes vote down vote up
@Override
public void addQuickfixes(Issue issue, IssueResolutionAcceptor issueResolutionAcceptor,
		IXtextDocument xtextDocument, XtextResource resource, 
		EObject referenceOwner, EReference unresolvedReference)
		throws Exception {
	String typeString = (issue.getData() != null && issue.getData().length > 0) 
			? issue.getData()[0] 
			: xtextDocument.get(issue.getOffset(), issue.getLength());
	Pair<String, String> packageAndType = typeNameGuesser.guessPackageAndTypeName(referenceOwner, typeString);
	String typeName = packageAndType.getSecond();
	if(isEmpty(typeName)) 
		return;
	String explicitPackage = packageAndType.getFirst();
	boolean isLocal = isEmpty(explicitPackage) || explicitPackage.equals(getPackage(resource));
	if(isLocal) 
		explicitPackage = "";
	if(isEmpty(packageAndType.getSecond()))
		return;
	if (unresolvedReference == XbasePackage.Literals.XCONSTRUCTOR_CALL__CONSTRUCTOR) {
		if(((XConstructorCall)referenceOwner).getConstructor().eIsProxy()) {
			if(isTypeMissing(referenceOwner, typeName, explicitPackage)) {
				newJavaClassQuickfix(typeName, explicitPackage, resource, issue, issueResolutionAcceptor);
				newXtendClassQuickfix(typeName, explicitPackage, resource, issue, issueResolutionAcceptor);
				if(isLocal)
					newLocalXtendClassQuickfix(typeName, resource, issue, issueResolutionAcceptor);
			}
		}
	} else if(unresolvedReference == XbasePackage.Literals.XTYPE_LITERAL__TYPE
			|| unresolvedReference == TypesPackage.Literals.JVM_PARAMETERIZED_TYPE_REFERENCE__TYPE) {
		EStructuralFeature eContainingFeature = referenceOwner.eContainingFeature();
		if(eContainingFeature == XtendPackage.Literals.XTEND_CLASS__EXTENDS) {
			newJavaClassQuickfix(typeName, explicitPackage, resource, issue, issueResolutionAcceptor);
			newXtendClassQuickfix(typeName, explicitPackage, resource, issue, issueResolutionAcceptor);
			if(isLocal)
				newLocalXtendClassQuickfix(typeName, resource, issue, issueResolutionAcceptor);
		} else if(eContainingFeature == XtendPackage.Literals.XTEND_CLASS__IMPLEMENTS
				|| eContainingFeature == XtendPackage.Literals.XTEND_INTERFACE__EXTENDS) {
			newJavaInterfaceQuickfix(typeName, explicitPackage, resource, issue, issueResolutionAcceptor);
			newXtendInterfaceQuickfix(typeName, explicitPackage, resource, issue, issueResolutionAcceptor);
			if(isLocal)
				newLocalXtendInterfaceQuickfix(typeName, resource, issue, issueResolutionAcceptor);
		} else {
			newJavaClassQuickfix(typeName, explicitPackage, resource, issue, issueResolutionAcceptor);
			newJavaInterfaceQuickfix(typeName, explicitPackage, resource, issue, issueResolutionAcceptor);
			newXtendClassQuickfix(typeName, explicitPackage, resource, issue, issueResolutionAcceptor);
			newXtendInterfaceQuickfix(typeName, explicitPackage, resource, issue, issueResolutionAcceptor);
			if(isLocal) {
				newLocalXtendClassQuickfix(typeName, resource, issue, issueResolutionAcceptor);				
				newLocalXtendInterfaceQuickfix(typeName, resource, issue, issueResolutionAcceptor);
			}
		}
	} else if(unresolvedReference == XAnnotationsPackage.Literals.XANNOTATION__ANNOTATION_TYPE) {
		newJavaAnnotationQuickfix(typeName, explicitPackage, resource, issue, issueResolutionAcceptor);
		newXtendAnnotationQuickfix(typeName, explicitPackage, resource, issue, issueResolutionAcceptor);
		if(isLocal) 
			newLocalXtendAnnotationQuickfix(typeName, resource, issue, issueResolutionAcceptor);
	}
}
 
Example 15
Source File: GamlQuickfixProvider.java    From gama with GNU General Public License v3.0 4 votes vote down vote up
@Override
public void apply(final IModificationContext context) throws BadLocationException {
	final IXtextDocument xtextDocument = context.getXtextDocument();
	final String tmp = text + xtextDocument.get(offset, length) + suffix;
	xtextDocument.replace(offset, length, tmp);
}