Java Code Examples for org.eclipse.xtext.ui.editor.XtextEditor#getDocument()

The following examples show how to use org.eclipse.xtext.ui.editor.XtextEditor#getDocument() . 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: LinkingErrorTest.java    From xtext-eclipse with Eclipse Public License 2.0 6 votes vote down vote up
@Test public void testQuickfixTurnaround() throws Exception {
	IFile dslFile = dslFile(MODEL_WITH_LINKING_ERROR);
	XtextEditor xtextEditor = openEditor(dslFile);
	IXtextDocument document = xtextEditor.getDocument();

	List<Issue> issues = getAllValidationIssues(document);
	assertFalse(issues.isEmpty());
	Issue issue = issues.get(0);
	assertNotNull(issue);
	List<IssueResolution> resolutions = issueResolutionProvider.getResolutions(issue);

	assertEquals(1, resolutions.size());
	IssueResolution resolution = resolutions.get(0);
	assertEquals("Change to 'Bar'", resolution.getLabel());
	resolution.apply();
	issues = getAllValidationIssues(document);
	assertTrue(issues.isEmpty());
}
 
Example 2
Source File: FixedHighlightingReconciler.java    From dsl-devkit with Eclipse Public License 1.0 6 votes vote down vote up
/**
 * Install this reconciler on the given editor and presenter.
 *
 * @param editor
 *          the editor
 * @param sourceViewer
 *          the source viewer
 * @param presenter
 *          the highlighting presenter
 */
@Override
public void install(final XtextEditor editor, final XtextSourceViewer sourceViewer, final HighlightingPresenter presenter) {
  synchronized (fReconcileLock) {
    cleanUpAfterReconciliation = false; // prevents a potentially already running reconciliation process to clean up after itself
  }
  this.presenter = presenter;
  this.editor = editor;
  this.sourceViewer = sourceViewer;
  if (oldCalculator != null || newCalculator != null) {
    if (editor == null) {
      ((IXtextDocument) sourceViewer.getDocument()).addModelListener(this);
    } else if (editor.getDocument() != null) {
      editor.getDocument().addModelListener(this);
    }

    sourceViewer.addTextInputListener(this);
  }
  refresh();
}
 
Example 3
Source File: ImportStaticMethodHandler.java    From xtext-xtend with Eclipse Public License 2.0 6 votes vote down vote up
@Override
public Object execute(final ExecutionEvent event) throws ExecutionException {
  try {
    Object _xblockexpression = null;
    {
      this.syncUtil.totalSync(false);
      final XtextEditor editor = EditorUtils.getActiveXtextEditor(event);
      if ((editor != null)) {
        ISelection _selection = editor.getSelectionProvider().getSelection();
        final ITextSelection selection = ((ITextSelection) _selection);
        final IXtextDocument document = editor.getDocument();
        this.importer.importStaticMethod(document, selection);
      }
      _xblockexpression = null;
    }
    return _xblockexpression;
  } catch (Throwable _e) {
    throw Exceptions.sneakyThrow(_e);
  }
}
 
Example 4
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 5
Source File: XtextGrammarQuickfixProviderTest.java    From xtext-eclipse with Eclipse Public License 2.0 6 votes vote down vote up
private void assertAndApplySingleResolution(XtextEditor xtextEditor, String issueCode, int issueDataCount, String resolutionLabel,
		boolean isCleanAfterApply) {
	IXtextDocument document = xtextEditor.getDocument();
	List<Issue> issues = getIssues(document);
	assertFalse(issues.toString(), issues.isEmpty());
	Issue issue = issues.iterator().next();
	assertEquals(issueCode, issue.getCode());
	assertNotNull(issue.getData());
	assertEquals(issueDataCount, issue.getData().length);
	List<IssueResolution> resolutions = issueResolutionProvider.getResolutions(issue);

	assertEquals(1, resolutions.size());
	IssueResolution resolution = resolutions.iterator().next();
	assertEquals(resolutionLabel, resolution.getLabel());
	try {
		resolution.apply();
		assertEquals(getIssues(document).toString(), isCleanAfterApply, getIssues(document).isEmpty());
	} finally {
		// Save xtextEditor in any case. Otherwise test will stuck,
		// because the "save changed resource dialog" waits for user input.
		xtextEditor.doSave(new NullProgressMonitor());
	}
}
 
Example 6
Source File: LinkingErrorTest.java    From xtext-eclipse with Eclipse Public License 2.0 6 votes vote down vote up
@Test public void testBug361509() throws Exception {
	IFile dslFile = dslFile(MODEL_WITH_LINKING_ERROR_361509);
	XtextEditor xtextEditor = openEditor(dslFile);
	IXtextDocument document = xtextEditor.getDocument();

	List<Issue> issues = getAllValidationIssues(document);
	assertFalse(issues.isEmpty());
	Issue issue = issues.get(0);
	assertNotNull(issue);
	List<IssueResolution> resolutions = issueResolutionProvider.getResolutions(issue);

	assertEquals(1, resolutions.size());
	IssueResolution resolution = resolutions.get(0);
	assertEquals("Change to 'ref'", resolution.getLabel());
	resolution.apply();
	issues = getAllValidationIssues(document);
	assertTrue(issues.isEmpty());
	assertEquals(MODEL_WITH_LINKING_ERROR_361509.replace("raf", "^ref"), document.get());
}
 
Example 7
Source File: RefactoringDocumentProviderTest.java    From xtext-eclipse with Eclipse Public License 2.0 6 votes vote down vote up
@Test public void testDirtyEditorDocument() throws Exception {
	XtextEditor editor = openEditor(testFile);
	editor.getDocument().replace(0, 0, " ");
	editor.getDocument().replace(0, 1, "");
	assertTrue(editor.isDirty());
	IRefactoringDocument cleanDocument = createAndCheckDocument(testFile);
	assertTrue(cleanDocument instanceof EditorDocument);

	IXtextDocument editorDocument = editor.getDocument();
	assertEquals(editorDocument, ((EditorDocument) cleanDocument).getDocument());
	assertEquals(TEST_FILE_CONTENT, cleanDocument.getOriginalContents());

	Change change = cleanDocument.createChange(CHANGE_NAME, textEdit);
	assertTrue(change instanceof EditorDocumentChange);
	assertEquals(TEST_FILE_NAME + " - " + TEST_PROJECT, change.getName());
	assertEquals(editor, ((EditorDocumentChange) change).getEditor());
	assertFalse(((EditorDocumentChange) change).isDoSave());

	Change undoChange = checkEdit(cleanDocument, textEdit);
	assertNotNull(undoChange);
	IRefactoringDocument dirtyDocument = createAndCheckDocument(testFile);
	assertTrue(cleanDocument instanceof EditorDocument);
	assertEquals(editorDocument, ((EditorDocument) dirtyDocument).getDocument());
}
 
Example 8
Source File: DefaultLinkedPositionGroupCalculator.java    From xtext-eclipse with Eclipse Public License 2.0 5 votes vote down vote up
protected LinkedPositionGroup createLinkedGroupFromReplaceEdits(List<ReplaceEdit> edits, XtextEditor xtextEditor,
		final String originalName, SubMonitor progress) {
	if (edits == null)
		return null;
	final IXtextDocument document = xtextEditor.getDocument();
	LinkedPositionGroup group = new LinkedPositionGroup();
	Iterable<LinkedPosition> linkedPositions = filter(
			Iterables.transform(edits, new Function<ReplaceEdit, LinkedPosition>() {
				@Override
				public LinkedPosition apply(ReplaceEdit edit) {
					try {
						String textToReplace = document.get(edit.getOffset(), edit.getLength());
						int indexOf = textToReplace.indexOf(originalName);
						if (indexOf != -1) {
							int calculatedOffset = edit.getOffset() + indexOf;
							return new LinkedPosition(document, calculatedOffset, originalName.length());
						}
					} catch (BadLocationException exc) {
						LOG.error("Skipping invalid text edit " + notNull(edit), exc);
					}
					return null;
				}
			}), Predicates.notNull());
	progress.worked(10);
	final int invocationOffset = xtextEditor.getInternalSourceViewer().getSelectedRange().x;
	int i = 0;
	for (LinkedPosition position : sortPositions(linkedPositions, invocationOffset)) {
		try {
			position.setSequenceNumber(i);
			i++;
			group.addPosition(position);
		} catch (BadLocationException e) {
			LOG.error(e.getMessage(), e);
			return null;
		}
	}
	return group;
}
 
Example 9
Source File: EncodingTest.java    From xtext-eclipse with Eclipse Public License 2.0 5 votes vote down vote up
protected void openEditorAndCheckEncoding(IFile file, final String charset) throws CoreException, Exception {
	XtextEditor openedEditor = openEditor(file);
	assertNotNull(openedEditor);
	IXtextDocument document = openedEditor.getDocument();
	document.readOnly(new IUnitOfWork.Void<XtextResource>() {
		@Override
		public void process(XtextResource resource) throws Exception {
			assertEquals(charset, resource.getEncoding());
		}
	});
	openedEditor.close(false);
	openedEditor.dispose();
}
 
Example 10
Source File: ExtractVariableRefactoring.java    From xtext-eclipse with Eclipse Public License 2.0 5 votes vote down vote up
public boolean initialize(XtextEditor editor, XExpression expression) {
	this.editor = editor;
	this.document = editor.getDocument();
	this.expression = expression;
	resourceURI = EcoreUtil2.getPlatformResourceOrNormalizedURI(expression).trimFragment();
	successor = expressionUtil.findSuccessorExpressionForVariableDeclaration(expression);
	if(successor == null)
		return false;
	isNeedsNewBlock = !(successor.eContainer() instanceof XBlockExpression);
	nameUtil.setFeatureScopeContext(successor);
	variableName = nameUtil.getDefaultName(expression);
	rewriter = rewriterFactory.create(document, (XtextResource) expression.eResource());
	return true;
}
 
Example 11
Source File: ExtractMethodHandler.java    From xtext-xtend with Eclipse Public License 2.0 5 votes vote down vote up
@Override
public Object execute(ExecutionEvent event) throws ExecutionException {
	try {
		syncUtil.totalSync(false);
		final XtextEditor editor = EditorUtils.getActiveXtextEditor(event);
		if (editor != null) {
			final ITextSelection selection = (ITextSelection) editor.getSelectionProvider().getSelection();
			final IXtextDocument document = editor.getDocument();
			XtextResource copiedResource = document.priorityReadOnly(new IUnitOfWork<XtextResource, XtextResource>() {
				@Override
				public XtextResource exec(XtextResource state) throws Exception {
					return resourceCopier.loadIntoNewResourceSet(state);
				}
			});
			List<XExpression> expressions = expressionUtil.findSelectedSiblingExpressions(copiedResource,
					selection);
			if (!expressions.isEmpty()) {
				ExtractMethodRefactoring extractMethodRefactoring = refactoringProvider.get();
				if (extractMethodRefactoring.initialize(editor, expressions, true)) {
					updateSelection(editor, expressions);
					ExtractMethodWizard wizard = wizardFactory.create(extractMethodRefactoring);
					RefactoringWizardOpenOperation_NonForking openOperation = new RefactoringWizardOpenOperation_NonForking(
							wizard);
					openOperation.run(editor.getSite().getShell(), "Extract Method");
				}
			}
		}
	} catch (InterruptedException e) {
		return null;
	} catch (Exception exc) {
		LOG.error("Error during refactoring", exc);
		MessageDialog.openError(Display.getCurrent().getActiveShell(), "Error during refactoring", exc.getMessage()
				+ "\nSee log for details");
	}
	return null;
}
 
Example 12
Source File: RealXtextDocumentModifyTest.java    From xtext-eclipse with Eclipse Public License 2.0 5 votes vote down vote up
private IXtextDocument createDocument(String grammar) throws Exception {
	IProject project = createProject("foo");
	addNature(project, XtextProjectHelper.NATURE_ID);
	IFile file = createFile("foo/Foo.xtext", grammar);
	XtextEditor editor = openEditor(file);
	return editor.getDocument();
}
 
Example 13
Source File: ExtractVariableHandler.java    From xtext-eclipse with Eclipse Public License 2.0 5 votes vote down vote up
@Override
public Object execute(ExecutionEvent event) throws ExecutionException {
	try {
		syncUtil.totalSync(false);
		final XtextEditor editor = EditorUtils.getActiveXtextEditor(event);
		if (editor != null) {
			final ITextSelection selection = (ITextSelection) editor.getSelectionProvider().getSelection();
			final IXtextDocument document = editor.getDocument();
			XtextResource resource = document.priorityReadOnly(new IUnitOfWork<XtextResource, XtextResource>() {
				@Override
				public XtextResource exec(XtextResource state) throws Exception {
					return resourceCopier.loadIntoNewResourceSet(state);
				}
			});
			XExpression expression = expressionUtil.findSelectedExpression(resource, selection);
			if(expression != null) {
				ExtractVariableRefactoring introduceVariableRefactoring = refactoringProvider.get();
				if(introduceVariableRefactoring.initialize(editor, expression)) {
					ITextRegion region = locationInFileProvider.getFullTextRegion(expression);
					editor.selectAndReveal(region.getOffset(), region.getLength());
					ExtractVariableWizard wizard = new ExtractVariableWizard(introduceVariableRefactoring);
					RefactoringWizardOpenOperation_NonForking openOperation = new RefactoringWizardOpenOperation_NonForking(
							wizard);
					openOperation.run(editor.getSite().getShell(), "Extract Local Variable");
				}
			}
		}
	} catch (InterruptedException e) {
		return null;
	} catch (Exception exc) {
		LOG.error("Error during refactoring", exc);
		MessageDialog.openError(Display.getCurrent().getActiveShell(), "Error during refactoring", exc.getMessage()
				+ "\nSee log for details");
	}
	return null;
}
 
Example 14
Source File: SimpleEditorTest.java    From xtext-eclipse with Eclipse Public License 2.0 5 votes vote down vote up
@Test public void testOpenBlankFile() throws Exception {
	IFile file = createFile("foo/x.testlanguage", "");
	XtextEditor openedEditor = openEditor(file);
	assertNotNull(openedEditor);
	IXtextDocument document = openedEditor.getDocument();
	document.readOnly(new IUnitOfWork.Void<XtextResource>() {

		@Override
		public void process(XtextResource resource) throws Exception {
			assertNotNull(resource);
			assertTrue(resource.getContents().isEmpty());
		}
	});
	openedEditor.close(false);
}
 
Example 15
Source File: XtextGrammarQuickfixProviderTest.java    From xtext-eclipse with Eclipse Public License 2.0 5 votes vote down vote up
private void assertAndApplyAllResolutions(XtextEditor xtextEditor, String issueCode, int issueDataCount, int issueCount,
		String resolutionLabel) throws CoreException {
	InternalBuilderTest.setAutoBuild(true);
	if (xtextEditor.isDirty()) {
		xtextEditor.doSave(new NullProgressMonitor());
	}
	InternalBuilderTest.fullBuild();
	IXtextDocument document = xtextEditor.getDocument();
	validateInEditor(document);
	List<Issue> issues = getIssues(document);
	assertFalse("Document has no issues, but should.", issues.isEmpty());

	issues.iterator().forEachRemaining((issue) -> {
		assertEquals(issueCode, issue.getCode());
		assertNotNull(issue.getData());
		assertEquals(issueDataCount, issue.getData().length);
	});
	IResource resource = xtextEditor.getResource();
	IMarker[] problems = resource.findMarkers(MarkerTypes.FAST_VALIDATION, true, IResource.DEPTH_INFINITE);
	assertEquals("Resource should have " + issueCount + " error marker.", issueCount, problems.length);
	validateInEditor(document);
	MarkerResolutionGenerator instance = injector.getInstance(MarkerResolutionGenerator.class);
	List<IMarkerResolution> resolutions = Lists.newArrayList(instance.getResolutions(problems[0]));
	assertEquals(1, resolutions.size());
	IMarkerResolution resolution = resolutions.iterator().next();
	assertTrue(resolution instanceof WorkbenchMarkerResolution);
	WorkbenchMarkerResolution workbenchResolution = (WorkbenchMarkerResolution) resolution;
	IMarker primaryMarker = problems[0];
	List<IMarker> others = Lists.newArrayList(workbenchResolution.findOtherMarkers(problems));
	assertFalse(others.contains(primaryMarker));
	assertEquals(problems.length - 1, others.size());
	others.add(primaryMarker);
	workbenchResolution.run(others.toArray(new IMarker[others.size()]), new NullProgressMonitor());
	if (xtextEditor.isDirty()) {
		xtextEditor.doSave(null);
	}
	InternalBuilderTest.cleanBuild();
	problems = resource.findMarkers(MarkerTypes.FAST_VALIDATION, true, IResource.DEPTH_INFINITE);
	assertEquals("Resource should have no error marker.", 0, problems.length);
}
 
Example 16
Source File: DefaultLinkedPositionGroupCalculator2.java    From xtext-eclipse with Eclipse Public License 2.0 5 votes vote down vote up
protected LinkedPositionGroup createLinkedGroupFromReplaceEdits(List<ReplaceEdit> edits, XtextEditor xtextEditor, String originalName,
		SubMonitor progress) {
	if (edits == null) {
		return null;
	}

	IXtextDocument document = xtextEditor.getDocument();
	LinkedPositionGroup group = new LinkedPositionGroup();
	List<LinkedPosition> linkedPositions = new ArrayList<>();
	edits.forEach(replaceEdit -> {
		try {
			String textToReplace = document.get(replaceEdit.getOffset(), replaceEdit.getLength());
			int indexOf = textToReplace.indexOf(originalName);
			if (indexOf != -1) {
				int calculatedOffset = replaceEdit.getOffset() + indexOf;
				linkedPositions.add(new LinkedPosition(document, calculatedOffset, originalName.length()));
			}
		} catch (BadLocationException exc) {
			LOG.error("Skipping invalid text edit " + replaceEdit, exc);
		}
	});

	progress.worked(10);

	int invocationOffset = xtextEditor.getInternalSourceViewer().getSelectedRange().x;
	int i = 0;
	for (LinkedPosition position : sortPositions(linkedPositions, invocationOffset)) {
		try {
			position.setSequenceNumber(i);
			i++;
			group.addPosition(position);
		} catch (BadLocationException e) {
			LOG.error(e.getMessage(), e);
			return null;
		}
	}
	return group;
}
 
Example 17
Source File: ToSaveOrNotToSaveTest.java    From xtext-eclipse with Eclipse Public License 2.0 5 votes vote down vote up
protected void renameFooToFooBar(final XtextEditor contextEditor) throws Exception {
		contextEditor.getEditorSite().getPage().activate(contextEditor);
		waitForDisplay();
		IXtextDocument document = contextEditor.getDocument();
		final int offset = document.get().indexOf("foo");
		contextEditor.selectAndReveal(offset, 3);
		
		EvaluationContext evaluationContext = new EvaluationContext(null, new Object());
		evaluationContext.addVariable(ISources.ACTIVE_EDITOR_NAME, contextEditor);
		ExecutionEvent executionEvent = new ExecutionEvent(null, newHashMap(), null, evaluationContext);
		renameElementHandler.execute(executionEvent);
//		syncUtil.totalSync(refactoringPreferences.isSaveAllBeforeRefactoring());
//		IRenameElementContext context = document.readOnly(new IUnitOfWork<IRenameElementContext, XtextResource>() {
//			public IRenameElementContext exec(XtextResource state) throws Exception {
//				EObject target = eObjectAtOffsetHelper.resolveElementAt(state, offset);
//				return renameContextFactory.createRenameElementContext(target, contextEditor, new TextSelection(offset,
//						3), state);
//			}
//		});
//		controller.initialize(context);
//		waitForDisplay();
//		controller.startRefactoring(RefactoringType.LINKED_EDITING);
//		waitForDisplay();
		pressKeys(contextEditor, "fooBar\n");
		waitForDisplay();
		waitForReconciler(fooEditor);
		waitForReconciler(barEditor);
		waitForDisplay();
	}
 
Example 18
Source File: IssueDataTest.java    From xtext-eclipse with Eclipse Public License 2.0 4 votes vote down vote up
@Test public void testIssueData() throws Exception {
	IFile dslFile = dslFile(getProjectName(), getFileName(), getFileExtension(), MODEL_WITH_LINKING_ERROR);
	XtextEditor xtextEditor = openEditor(dslFile);
	IXtextDocument document = xtextEditor.getDocument();
	IResource file = xtextEditor.getResource();
	List<Issue> issues = getAllValidationIssues(document);
	assertEquals(1, issues.size());
	Issue issue = issues.get(0);
	assertEquals(2, issue.getLineNumber().intValue());
	assertEquals(3, issue.getColumn().intValue());
	assertEquals(PREFIX.length(), issue.getOffset().intValue());
	assertEquals(QuickfixCrossrefTestLanguageValidator.TRIGGER_VALIDATION_ISSUE.length(), issue.getLength().intValue());
	String[] expectedIssueData = new String[]{ QuickfixCrossrefTestLanguageValidator.ISSUE_DATA_0,
		QuickfixCrossrefTestLanguageValidator.ISSUE_DATA_1};
	assertTrue(Arrays.equals(expectedIssueData, issue.getData()));
	Thread.sleep(1000);

	IAnnotationModel annotationModel = xtextEditor.getDocumentProvider().getAnnotationModel(
			xtextEditor.getEditorInput());
	AnnotationIssueProcessor annotationIssueProcessor = 
			new AnnotationIssueProcessor(document, annotationModel, new IssueResolutionProvider.NullImpl());
	annotationIssueProcessor.processIssues(issues, new NullProgressMonitor());
	Iterator<?> annotationIterator = annotationModel.getAnnotationIterator();
	// filter QuickDiffAnnotations
	List<Object> allAnnotations = Lists.newArrayList(annotationIterator);
	List<XtextAnnotation> annotations = newArrayList(filter(allAnnotations, XtextAnnotation.class));
	assertEquals(annotations.toString(), 1, annotations.size());
	XtextAnnotation annotation = annotations.get(0);
	assertTrue(Arrays.equals(expectedIssueData, annotation.getIssueData()));
	IssueUtil issueUtil = new IssueUtil();
	Issue issueFromAnnotation = issueUtil.getIssueFromAnnotation(annotation);
	assertTrue(Arrays.equals(expectedIssueData, issueFromAnnotation.getData()));

	new MarkerCreator().createMarker(issue, file, MarkerTypes.FAST_VALIDATION);
	IMarker[] markers = file.findMarkers(MarkerTypes.FAST_VALIDATION, true, IResource.DEPTH_ZERO);
	String errorMessage = new AnnotatedTextToString().withFile(dslFile).withMarkers(markers).toString().trim();
	assertEquals(errorMessage, 1, markers.length);
	String attribute = (String) markers[0].getAttribute(Issue.DATA_KEY);
	assertNotNull(attribute);
	assertTrue(Arrays.equals(expectedIssueData, Strings.unpack(attribute)));

	Issue issueFromMarker = issueUtil.createIssue(markers[0]);
	assertEquals(issue.getColumn(), issueFromMarker.getColumn());
	assertEquals(issue.getLineNumber(), issueFromMarker.getLineNumber());
	assertEquals(issue.getOffset(), issueFromMarker.getOffset());
	assertEquals(issue.getLength(), issueFromMarker.getLength());
	assertTrue(Arrays.equals(expectedIssueData, issueFromMarker.getData()));
}
 
Example 19
Source File: XtendFoldingRegionProviderTest.java    From xtext-xtend with Eclipse Public License 2.0 4 votes vote down vote up
private Collection<FoldedPosition> calculateFoldingRegions(String fileName, String content) throws Exception {
	IFile iFile = testHelper.createFile(fileName, content);
	XtextEditor editor = testHelper.openEditor(iFile);
	IXtextDocument document = editor.getDocument();
	return foldingRegionProvider.getFoldingRegions(document);
}
 
Example 20
Source File: PasteJavaCodeHandler.java    From xtext-xtend with Eclipse Public License 2.0 4 votes vote down vote up
private void doPasteJavaCode(final XtextEditor activeXtextEditor, final String javaCode, final JavaImportData javaImports)
		throws ExecutionException {
	ISourceViewer sourceViewer = activeXtextEditor.getInternalSourceViewer();
	final IXtextDocument xtextDocument = activeXtextEditor.getDocument();
	IJavaProject project = null;
	IProject iProject = null;
	IEditorInput editorInput = activeXtextEditor.getEditorInput();
	if (editorInput instanceof IFileEditorInput) {
		iProject = ((IFileEditorInput) editorInput).getFile().getProject();
		project = JavaCore.create(iProject);
	}
	final int selectionOffset = Math.max(0, sourceViewer.getSelectedRange().x - 1);
	EObject targetElement = xtextDocument.readOnly(new IUnitOfWork<EObject, XtextResource>() {

		@Override
		public EObject exec(XtextResource state) throws Exception {
			IParseResult parseResult = state.getParseResult();
			if (parseResult == null) {
				return null;
			}
			ILeafNode leafNode = NodeModelUtils.findLeafNodeAtOffset(parseResult.getRootNode(), selectionOffset);
			if (leafNode == null) {
				return parseResult.getRootASTElement();
			}
			return leafNode.getSemanticElement();
		}
	});
	JavaConverter javaConverter = javaConverterProvider.get();
	final String xtendCode = javaConverter.toXtend(javaCode, javaImports != null ? javaImports.getImports() : null,
			targetElement, project, conditionalExpressionsAllowed(iProject));
	if (!Strings.isEmpty(xtendCode)) {
		if (javaImports != null) {
			importsUtil.addImports(javaImports.getImports(), javaImports.getStaticImports(), new String[] {}, xtextDocument);
		}
		Point selection = sourceViewer.getSelectedRange();
		try {
			xtextDocument.replace(selection.x, selection.y, xtendCode);
		} catch (BadLocationException e) {
			throw new ExecutionException("Failed to replace content.", e);
		}
		//TODO enable formatting, when performance became better
		//	https://bugs.eclipse.org/bugs/show_bug.cgi?id=457814
		//			doFormat(sourceViewer, xtendCode, selection);
	}
}