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

The following examples show how to use org.eclipse.xtext.ui.editor.XtextEditor#getInternalSourceViewer() . 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: OpenDeclarationHandler.java    From xtext-eclipse with Eclipse Public License 2.0 6 votes vote down vote up
@Override
public Object execute(ExecutionEvent event) throws ExecutionException {
	XtextEditor xtextEditor = EditorUtils.getActiveXtextEditor(event);
	if (xtextEditor != null) {
		ITextSelection selection = (ITextSelection) xtextEditor.getSelectionProvider().getSelection();

		IRegion region = new Region(selection.getOffset(), selection.getLength());

		ISourceViewer internalSourceViewer = xtextEditor.getInternalSourceViewer();

		IHyperlink[] hyperlinks = getDetector().detectHyperlinks(internalSourceViewer, region, false);
		if (hyperlinks != null && hyperlinks.length > 0) {
			IHyperlink hyperlink = hyperlinks[0];
			hyperlink.open();
		}
	}		
	return null;
}
 
Example 2
Source File: QuickTypeHierarchyHandler.java    From xtext-eclipse with Eclipse Public License 2.0 6 votes vote down vote up
@Override
protected void openPresentation(final XtextEditor editor, final IJavaElement javaElement,
		final EObject selectedElement) {
	final ISourceViewer sourceViewer = editor.getInternalSourceViewer();
	ITextRegion significantTextRegion = locationInFileProvider.getSignificantTextRegion(selectedElement);
	InformationPresenter presenter = new HierarchyInformationPresenter(sourceViewer, javaElement, new Region(significantTextRegion.getOffset(),significantTextRegion.getLength()));
	presenter.setDocumentPartitioning(IDocumentExtension3.DEFAULT_PARTITIONING);
	presenter.setAnchor(AbstractInformationControlManager.ANCHOR_GLOBAL);
	IInformationProvider provider = new JavaElementProvider(editor, false);
	presenter.setInformationProvider(provider, IDocument.DEFAULT_CONTENT_TYPE);
	presenter.setInformationProvider(provider, IJavaPartitions.JAVA_DOC);
	presenter.setInformationProvider(provider, IJavaPartitions.JAVA_MULTI_LINE_COMMENT);
	presenter.setInformationProvider(provider, IJavaPartitions.JAVA_SINGLE_LINE_COMMENT);
	presenter.setInformationProvider(provider, IJavaPartitions.JAVA_STRING);
	presenter.setInformationProvider(provider, IJavaPartitions.JAVA_CHARACTER);
	presenter.setSizeConstraints(50, 20, true, false);
	presenter.install(sourceViewer);
	presenter.showInformation();
}
 
Example 3
Source File: EditorOverlay.java    From n4js with Eclipse Public License 1.0 5 votes vote down vote up
private void draw() {
	XtextEditor editor = EditorUtils.getActiveXtextEditor();
	if (editor != null && (hoveredElement != null || !selectedElements.isEmpty())) {
		ISourceViewer isv = editor.getInternalSourceViewer();
		styledText = isv.getTextWidget();
		drawSelection();
	} else {
		clear();
	}
}
 
Example 4
Source File: LinkedEditingUndoSupport.java    From xtext-eclipse with Eclipse Public License 2.0 5 votes vote down vote up
public void startRecording(XtextEditor editor) {
	this.editor = editor;
	ISourceViewer viewer = editor.getInternalSourceViewer();
	if (viewer instanceof ITextViewerExtension6) {
		IUndoManager undoManager = ((ITextViewerExtension6) viewer).getUndoManager();
		if (undoManager instanceof IUndoManagerExtension) {
			IUndoManagerExtension undoManagerExtension = (IUndoManagerExtension) undoManager;
			IUndoContext undoContext = undoManagerExtension.getUndoContext();
			IOperationHistory operationHistory = OperationHistoryFactory.getOperationHistory();
			startingUndoOperation = operationHistory.getUndoOperation(undoContext);
		}
	}
}
 
Example 5
Source File: XbaseFoldingActionContributor.java    From xtext-eclipse with Eclipse Public License 2.0 5 votes vote down vote up
@Override
public void contributeActions(XtextEditor xtextEditor) {
	foldingActionGroup = new FoldingActionGroup(xtextEditor, xtextEditor.getInternalSourceViewer()) {
		@Override
		protected TextEditorAction createToggleFoldingAction(ITextEditor editor) {
			TextEditorAction toggle = new ResourceActionExtension(FoldingMessages.getResourceBundle(),
					"Projection.Toggle.", editor, ProjectionViewer.TOGGLE);
			toggle.setChecked(true);
			toggle.setActionDefinitionId(IFoldingCommandIds.FOLDING_TOGGLE);
			return toggle;
		}
	};
}
 
Example 6
Source File: AbstractEditorTest.java    From xtext-eclipse with Eclipse Public License 2.0 5 votes vote down vote up
private XtextEditor getXtextEditor(IEditorPart openEditor) throws NoSuchFieldException, IllegalAccessException {
	XtextEditor xtextEditor = EditorUtils.getXtextEditor(openEditor);
	if (xtextEditor != null) {
		ISourceViewer sourceViewer = xtextEditor.getInternalSourceViewer();
		((ProjectionViewer) sourceViewer).doOperation(ProjectionViewer.EXPAND_ALL);
		return xtextEditor;
	} else if (openEditor instanceof ErrorEditorPart) {
		Field field = openEditor.getClass().getDeclaredField("error");
		field.setAccessible(true);
		throw new IllegalStateException("Couldn't open the editor.", ((Status) field.get(openEditor)).getException());
	} else {
		fail("Opened Editor with id:" + getEditorId() + ", is not an XtextEditor");
	}
	return null;
}
 
Example 7
Source File: AbstractMultiQuickfixTest.java    From xtext-eclipse with Eclipse Public License 2.0 5 votes vote down vote up
protected ICompletionProposal[] computeQuickAssistProposals(XtextEditor editor, int offset) {
	IResourcesSetupUtil.waitForBuild();
	XtextSourceViewer sourceViewer = (XtextSourceViewer) editor.getInternalSourceViewer();
	QuickAssistAssistant quickAssistAssistant = (QuickAssistAssistant) sourceViewer.getQuickAssistAssistant();
	IQuickAssistProcessor quickAssistProcessor = quickAssistAssistant.getQuickAssistProcessor();
	ICompletionProposal[] quickAssistProposals = quickAssistProcessor
			.computeQuickAssistProposals(new TextInvocationContext(sourceViewer, offset, -1));
	return quickAssistProposals;
}
 
Example 8
Source File: AbstractEditorDoubleClickTextSelectionTest.java    From xtext-eclipse with Eclipse Public License 2.0 5 votes vote down vote up
protected XtextEditor doubleClick(XtextEditor xtextEditor, int cursorPosition) {
	ISourceViewer viewer = xtextEditor.getInternalSourceViewer();

	// Set the cursor position
	viewer.setSelectedRange(cursorPosition, 0);

	// Fire a mouse down event with the left mouse button
	Event event = new Event();
	event.button = 1;
	viewer.getTextWidget().notifyListeners(SWT.MouseDown, event);

	return xtextEditor;
}
 
Example 9
Source File: RenameStrategyTest.java    From xtext-xtend with Eclipse Public License 2.0 5 votes vote down vote up
@Test public void testOverrideIndicatorAnnotationAfterFileRename() throws Exception {
	testHelper.createFile("test/SuperClass","package test\nclass SuperClass { def foo() {}}");
	final IFile subClassFile = testHelper.createFile("test/SubClass","package test\nclass SubClass extends SuperClass { override foo () {}}");
	IResourcesSetupUtil.waitForBuild();
	XtextEditor openEditor = testHelper.openEditor(subClassFile);
	final OverrideIndicatorAnnotation[] annotationBeforeFileRename = new OverrideIndicatorAnnotation[]{null};
	final OverrideIndicatorAnnotation[] annotationAfterFileRename = new OverrideIndicatorAnnotation[]{null};
	final ISourceViewer sourceViewer = openEditor.getInternalSourceViewer();
	sleepWhile(Predicates.isNull(), new Provider<Object>() {

		@Override
		public OverrideIndicatorAnnotation get() {
			annotationBeforeFileRename[0] = Iterators.getOnlyElement(Iterators.filter(sourceViewer.getAnnotationModel().getAnnotationIterator(), OverrideIndicatorAnnotation.class), null);
			return annotationBeforeFileRename[0];
		}
	},TimeUnit.SECONDS.toMillis(10));
	assertNotNull(annotationBeforeFileRename[0]);
	new WorkspaceModifyOperation() {
		@Override
		protected void execute(IProgressMonitor monitor) throws CoreException, InvocationTargetException,
				InterruptedException {
			subClassFile.move(subClassFile.getFullPath().removeLastSegments(1).append("Test.xtend"), true, monitor);
		}
	}.run(new NullProgressMonitor());
	IResourcesSetupUtil.waitForBuild();
	sleepWhile(Predicates.isNull(), new Provider<Object>() {

		@Override
		public OverrideIndicatorAnnotation get() {
			OverrideIndicatorAnnotation ann = Iterators.getOnlyElement(Iterators.filter(sourceViewer.getAnnotationModel().getAnnotationIterator(), OverrideIndicatorAnnotation.class), null);
			if (ann != annotationBeforeFileRename[0])
				annotationAfterFileRename[0] = ann;
			return annotationAfterFileRename[0];
		}
	},TimeUnit.SECONDS.toMillis(10));
	assertNotNull(annotationAfterFileRename[0]);
	assertNotSame(annotationBeforeFileRename[0], annotationAfterFileRename[0]);
}
 
Example 10
Source File: DirtyEditorFilteringContentAssistTests.java    From xtext-xtend with Eclipse Public License 2.0 5 votes vote down vote up
public ICompletionProposal[] computeCompletionProposals(final XtextEditor editorForCompletion, final XtextEditor dirtyEditor, final int cursorPosition) throws BadLocationException {
  this.syncUtil.waitForReconciler(dirtyEditor);
  final ISourceViewer sourceViewer = editorForCompletion.getInternalSourceViewer();
  final IContentAssistant contentAssistant = editorForCompletion.getXtextSourceViewerConfiguration().getContentAssistant(sourceViewer);
  final String contentType = editorForCompletion.getDocument().getContentType(cursorPosition);
  final IContentAssistProcessor processor = contentAssistant.getContentAssistProcessor(contentType);
  if ((processor != null)) {
    return processor.computeCompletionProposals(sourceViewer, cursorPosition);
  }
  return null;
}
 
Example 11
Source File: SARLEditorErrorTickUpdater.java    From sarl with Apache License 2.0 5 votes vote down vote up
@Override
@SuppressWarnings("checkstyle:nestedifdepth")
public void modelChanged(IAnnotationModel model) {
	super.modelChanged(model);
	//FIXME: for helping to resolve #661
	final XtextEditor editor = getEditor();
	if (editor != null && !editor.isDirty() && editor.getInternalSourceViewer() != null) {
		final IAnnotationModel currentModel = editor.getInternalSourceViewer().getAnnotationModel();
		if (currentModel != null && currentModel == model) {
			final Resource resource = getXtextResource();
			if (isReconciliable(resource)) {
				final Set<String> markers = extractErrorMarkerMessages(currentModel);
				final List<Diagnostic> resourceErrors = resource.getErrors();
				if (markers.size() != resourceErrors.size() || notSame(markers, resourceErrors)) {
					final Display display = PlatformUI.getWorkbench().getDisplay();
					display.asyncExec(new Runnable() {
						@Override
						public void run() {
							LangActivator.getInstance().getLog().log(
									new Status(IStatus.ERROR, LangActivator.PLUGIN_ID,
									MessageFormat.format(Messages.SARLEditorErrorTickUpdater_0, resource.getURI())));
						}
					});
				}
			}
		}
	}
}
 
Example 12
Source File: FoldingActionContributor.java    From xtext-eclipse with Eclipse Public License 2.0 4 votes vote down vote up
@Override
public void contributeActions(XtextEditor editor) {
	foldingActionGroup = new FoldingActionGroup(editor, editor.getInternalSourceViewer());
}
 
Example 13
Source File: XtendHoverInEditorTest.java    From xtext-xtend with Eclipse Public License 2.0 4 votes vote down vote up
@Test
public void testHoverOfReferencedElement() {
  try {
    StringConcatenation _builder = new StringConcatenation();
    _builder.append("/**");
    _builder.newLine();
    _builder.append(" ");
    _builder.append("* Hello Foo");
    _builder.newLine();
    _builder.append(" ");
    _builder.append("*/");
    _builder.newLine();
    _builder.append("class Foo {}");
    _builder.newLine();
    final String contentFoo = _builder.toString();
    StringConcatenation _builder_1 = new StringConcatenation();
    _builder_1.append("class Bar extends Foo {}");
    _builder_1.newLine();
    final String contentBar = _builder_1.toString();
    final IFile fileFoo = this.helper.createFile("Foo.xtend", contentFoo);
    final IFile fileBar = this.helper.createFile("Bar.xtend", contentBar);
    this._syncUtil.waitForBuild(null);
    final XtextEditor editor = this.helper.openEditor(fileBar);
    ISourceViewer _internalSourceViewer = editor.getInternalSourceViewer();
    Region _region = new Region(19, 1);
    Object _hoverInfo2 = ((ITextHoverExtension2) this.hoverer).getHoverInfo2(((ITextViewer) _internalSourceViewer), _region);
    final XtextBrowserInformationControlInput info = ((XtextBrowserInformationControlInput) _hoverInfo2);
    Assert.assertTrue(info.getHtml().contains("Hello Foo"));
    final XtextEditor fooEditor = this.helper.openEditor(fileFoo);
    IXtextDocument _document = fooEditor.getDocument();
    StringConcatenation _builder_2 = new StringConcatenation();
    _builder_2.append("/**");
    _builder_2.newLine();
    _builder_2.append(" ");
    _builder_2.append("* Hello BAZ");
    _builder_2.newLine();
    _builder_2.append(" ");
    _builder_2.append("*/");
    _builder_2.newLine();
    _builder_2.append("class Foo {}");
    _builder_2.newLine();
    _document.set(_builder_2.toString());
    this._syncUtil.waitForReconciler(fooEditor);
    this._syncUtil.waitForReconciler(editor);
    ISourceViewer _internalSourceViewer_1 = editor.getInternalSourceViewer();
    Region _region_1 = new Region(19, 1);
    Object _hoverInfo2_1 = ((ITextHoverExtension2) this.hoverer).getHoverInfo2(((ITextViewer) _internalSourceViewer_1), _region_1);
    final XtextBrowserInformationControlInput info2 = ((XtextBrowserInformationControlInput) _hoverInfo2_1);
    Assert.assertFalse(info2.getHtml().contains("Hello Foo"));
    Assert.assertTrue(info2.getHtml().contains("Hello BAZ"));
  } catch (Throwable _e) {
    throw Exceptions.sneakyThrow(_e);
  }
}
 
Example 14
Source File: UndoTest.java    From xtext-xtend with Eclipse Public License 2.0 4 votes vote down vote up
@Test
public void testUndo() {
  try {
    StringConcatenation _builder = new StringConcatenation();
    _builder.append("class Foo {");
    _builder.newLine();
    _builder.append("\t");
    _builder.append("val java.lang.String x");
    _builder.newLine();
    _builder.append("\t");
    _builder.append("val java.util.ArrayList<String> y");
    _builder.newLine();
    _builder.append("}");
    _builder.newLine();
    final XtextEditor editor = this._workbenchTestHelper.openEditor("Foo", _builder.toString());
    this._organizeImportsHandler.doOrganizeImports(editor.getDocument());
    StringConcatenation _builder_1 = new StringConcatenation();
    _builder_1.append("import java.util.ArrayList");
    _builder_1.newLine();
    _builder_1.newLine();
    _builder_1.append("class Foo {");
    _builder_1.newLine();
    _builder_1.append("\t");
    _builder_1.append("val String x");
    _builder_1.newLine();
    _builder_1.append("\t");
    _builder_1.append("val ArrayList<String> y");
    _builder_1.newLine();
    _builder_1.append("}");
    _builder_1.newLine();
    Assert.assertEquals(_builder_1.toString(), editor.getDocument().get());
    final ISourceViewer viewer = editor.getInternalSourceViewer();
    Assert.assertTrue((viewer instanceof ITextViewerExtension6));
    final IUndoManager undoManager = ((ITextViewerExtension6) viewer).getUndoManager();
    undoManager.undo();
    StringConcatenation _builder_2 = new StringConcatenation();
    _builder_2.append("class Foo {");
    _builder_2.newLine();
    _builder_2.append("\t");
    _builder_2.append("val java.lang.String x");
    _builder_2.newLine();
    _builder_2.append("\t");
    _builder_2.append("val java.util.ArrayList<String> y");
    _builder_2.newLine();
    _builder_2.append("}");
    _builder_2.newLine();
    Assert.assertEquals(_builder_2.toString(), editor.getDocument().get());
  } catch (Throwable _e) {
    throw Exceptions.sneakyThrow(_e);
  }
}
 
Example 15
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);
	}
}
 
Example 16
Source File: GamaFoldingActionContributor.java    From gama with GNU General Public License v3.0 4 votes vote down vote up
@Override
public void contributeActions(final XtextEditor editor) {
	foldingActionGroup = new GamaFoldingActionGroup(editor, editor.getInternalSourceViewer());
}