Grab selected text from Eclipse Java editor - eclipse

I'm developing an Eclipse plug-in where upon pressing a button, the plug-in takes the selected text in the Java editor and puts in a text box which appears.
My code looks like this: I got it from here: http://dev.eclipse.org/newslists/news.eclipse.newcomer/msg02200.html
private ITextSelection getSelection(ITextEditor editor) {
ISelection selection = editor.getSelectionProvider()
.getSelection();
return (ITextSelection) selection;
}
private String getSelectedText(ITextEditor editor) {
return getSelection(editor).getText();
}
The problem is how will I get the ITextEditor of the Java editor being displayed. Coincidentally it's the next question in the thread in the link I posted but it's unanswered :(

You could ask for the ActiveEditor, as in this thread:
IEditorPart part;
part =
PlatformUI.getWorkbench().getActiveWorkbenchWindow().getActivePage().get
ActiveEditor();
if(part instanceof ITextEditor){
ITextEditor editor = (ITextEditor)part;
IDocumentProvider provider = editor.getDocumentProvider();
IDocument document = provider.getDocument(editor.getEditorInput());
The OP Krt_Malta mentions this blog entry "Programmatically query current text selection", which is similar to this other SO answer (written before the blog entry) "Replace selected code from eclipse editor through plugin command".

I'd like to add one thing to VonCs answer. The technique he describes to get the selection is useful for all kinds of text editors, not only Java editors as this questions is about. But his solution does not work in the case that the workspace part is a MultiPageEditorPart, since that is not a ITextEditor.
But in many cases (for example with the standard XML editor) a MultiPageEditorPart has pages which are ITextEditors. In those cases you can get the active page from a MultiPageEditorPart and get the selection from that.
This can be done with the following code:
ITextEditor editor = null;
if (part instanceof ITextEditor) {
editor = (ITextEditor) part;
} else if (part instanceof MultiPageEditorPart) {
Object page = ((MultiPageEditorPart) part).getSelectedPage();
if (page instanceof ITextEditor) editor = (ITextEditor) page;
}
if (editor != null) {
IDocumentProvider provider = editor.getDocumentProvider();
IDocument document = provider.getDocument(editor.getEditorInput());
}

Related

Open DialectEditor programmatically outside of main editor area (E3/E4 hybrid)

what I want to do:
In my RCP an E3/E4 hybrid I have a project and library based on sirius tree. The User can drag an drop item from the library tree to the project tree. This works fine and was no great problem to build in. So now I want to make the UI more usable. It should looks like this layout:
what works:
After application startup I open my library presentation with the DialectUIManager.
final DialectEditor editor = (DialectEditor)
DialectUIManager.INSTANCE.openEditor(siriusSession, description, monitor);
Okay, this works. But it open it in the editor in the part market as org.eclipse.ui.editorss. This it not what I want
what does not work:
I want to show it in the "Library Part". I can move it manually with the mouse after open the editor, but how can i tell DialectUIManager to open it direct there. Or how can I programmatically it move there.
I do a lot of google research but i don't found a solution. The only thing I found was a hint Pierre-Charles David https:// www. eclipse.org/forums/index.php?t=msg&th=998476&goto=1631138&#msg_1631138
If you need is simply to show the editor outside of the main editor
area, this is possible since Eclipse 4.2 (e4 does not really treat the
main editor area as something special), so you can have your editor
"around" another editor in the middle of other views.
But at this step I stuck. I also ask it in the Sirius Forum but they say its a Eclipse E4 problem
Thanks for help, code snippets or links to correct part of manual.
I've found a solution. It's not very nice, but it works. I execute these code here after the editors have opened.
What the code does:
He is looking for the MPlaceholder which has the ID: org. eclipse. ui. editorss. There he descends until he is with the parts. These are in the Compatibly editor mode. Then he chooses the part we wants to move out of and Attach them to the MPartStack target.
public static void movePart(MApplication application,
EModelService modelService) {
MPart partToMove = null;
MUIElement muiElement =
modelService.find("org.eclipse.ui.editorss", application);
if (muiElement instanceof MPlaceholder) {
MPlaceholder placeholder = (MPlaceholder) muiElement;
MUIElement ref = placeholder.getRef();
if (ref instanceof MArea) {
MArea area = (MArea) ref;
List<MPartSashContainerElement> children = area.getChildren();
for (MPartSashContainerElement mPartSashContainerElement
: children) {
if (mPartSashContainerElement instanceof MPartStack) {
MPartStack partStack = (MPartStack) mPartSashContainerElement;
List<MStackElement> children2 = partStack.getChildren();
for (MStackElement mStackElement : children2) {
if (mStackElement instanceof MPart) {
MPart part = (MPart) mStackElement;
// Library is the Editor Name wiche I want to move
if (part.getLabel().equals("Library")) {
partToMove = part;
break;
}
}
}
}
}
}
}
if (partToMove != null) {
moveElement(modelService, application, partToMove);
}
}
private static void moveElement(EModelService modelService,
MApplication application, MPart part) {
// target PartStack
MUIElement find = modelService.find("de.bsg.onesps.rcp.
partstack.library", application);
if (find instanceof MPartStack) {
MPartStack mPartStack = (MPartStack) find;
mPartStack.getChildren().add(part);
mPartStack.setSelectedElement(part);
}
}

Howto Highlight Code Background Color by line

I am working on a eclipse plugin and trying to highlight parts of the Code with a backround color. Is there any option to highlight to change the backround color in the editor by line numbers.
For Example:
editor.highlightLines(2,5,"red"); I i
There are so much informations when i googled for it. Annotations, Makers etc. but noone could give me a Tutorial or a link to and API which can do what i need. I only got informations for syntax highlighting, but i want to highlights parts of the code by line number.
You can do this as long as the editor implements ITextEditor:
IEditorPart editorPart = page.openEditor(new FileEditorInput(file), getEditorId() , true);
ITextEditor textEditor;
if (editorPart instanceof ITextEditor) {
textEditor = (ITextEditor)editorPart;
} else {
textEditor = (ITextEditor)editorPart.getAdapter(ITextEditor.class);
}
IEditorInput input = editorPart.getEditorInput();
IDocumentProvider provider = textEditor.getDocumentProvider();
provider.connect(input);
IDocument document = provider.getDocument(input);
IRegion region = document.getLineInformation(lineNumber - 1);
int fileOffset = region.getOffset();
int fileLength = region.getLength();
provider.disconnect(input);
textEditor.selectAndReveal(fileOffset, fileLength);
(extracted from org.eclipse.debug.ui.console.FileLink which the console code uses). I have left out many error checks of exception catches.

Close editor if button inside this editor is pressed?? (RCP eclipse)

favorite
I have a UI in which when I select an item (in a tree) and then press a button "add", I get a new editor. With each item I can get an editor. (but all have the same ID)
My purpose is to close only the editor of item1, for example, when I press "save". I'm able to close all the editors with: getSite().getWorkbenchWindow().getActivePage().closeAllEditors(true);
But not only the one that I need to close. The following solution helped me:
// Creating and opening
MyObject item1 = ... //create item1
// open editor
myInput = new MyEditorInput(item1)
IDE.openEditor(workbenchPage, myInput, MY_EDITOR_ID);
// Closing
tmpInput = new MyEditorInput(item1)
IEditorReference[] editorReferences = PlatformUI.getWorkbench()
.getActiveWorkbenchWindow().getActivePage()
.getEditorReferences();
List<IEditorReference> relevantEditors = new ArrayList<IEditorReference>();
for (IEditorReference iEditorReference : editorReferences) {
if (iEditorReference.getEditorInput().equals(tmpInput)) {
relevantEditors.add(iEditorReference);
}
}
PlatformUI
.getWorkbench()
.getActiveWorkbenchWindow()
.getActivePage()
.closeEditors(
(IEditorReference[]) relevantEditors.toArray(new IEditorReference[relevantEditors
.size()]), true);
….but I still have some problems... As I can open many editors in the same time, and all of them have the same button "save", it happens that I press "save" in editor1 but close editor3... Actually, I save the last editor to be open (thanks to its "item")... this is the problem.. So I'm wondering if there is a way to identify the editor in which the button exists, so that I close it..
Thanks a lot I appreciate any help or hint (Sorry if my questions look easy and not worth being asked, but I'm still a beginner...)
if the Button is rendered in your IEditorPart implementation, you can close the editor directly in your EditorPart.
button.addListener(SWT.Selection, new Listener() {
#Override
public void handleEvent(Event event) {
PlatformUI.getWorkbench().getActiveWorkbenchWindow()
.getActivePage().closeEditor(this, true);
}
});
Selected editor open or another editor can be close using RCP eclipse.
Multiple Editor open at time selected editor can be open or close using RCP eclipse.
IWorkbenchWindow window = HandlerUtil.getActiveWorkbenchWindow(event);
IWorkbenchPage page = window.getActivePage();
EmployeeEditorInput input = new EmployeeEditorInput();
//List out all the editors open
IEditorReference[] editors = page.getEditorReferences();
for (int i=0; i<editors.length; i++) {
//class : EmployeeEditor
//public static final String Id="rcp_demo.Editor.emp";
if (editors[i].getId().equals(EmployeeEditor.Id)) {
page.activate(editors[i].getEditor(true));
//or
//page.closeEditor(page.getActiveEditor(),true);
System.out.println("Employee Editor Exist");
return null;
}
else
{
page.closeEditor(page.getActiveEditor(), true);
System.out.println("Close other Editor");
}
}

get ITextViewer from IEDitorPart (Eclipse)

Eclipse RCP question
I open file with:
IWorkbenchPage page = PlatformUI.getWorkbench().getActiveWorkbenchWindow().getActivePage();
IEditorPart editorPart = IDE.openEditor(page, file);
I also get document with:
IDocument doc = ((ITextEditor)editorPart).getDocumentProvider().getDocument(editorPart.getEditorInput());
I need to get to text viewer of that document (for creating LinkedModeUI), is there any way to do this?
The following worked for me:
IEditorPart editorPart = getSite().getPage().getActiveEditor();
if (editorPart != null) {
ITextOperationTarget target =
(ITextOperationTarget)editorPart.getAdapter(ITextOperationTarget.class);
if (target instanceof ITextViewer) {
ITextViewer textViewer = (ITextViewer)target;
// ...
}
}
1) One document can be opened with more than one editor. You'll have to iterate all editors to look for your file's editors.
2) Viewer is encapsulated in editor. I think the only way is extend editor class to add getter. Or redefine it, if viewer is inaccessible from inheritors.

Enumerating all my Eclipse editors?

I have built a simple Eclipse plugin where a user may use a TableViewer of database resources to open an editor on any of those resources.
Users may therefore have zero upwards instances of the editor running.
Is there an API available to get a list of those editor instances?
You can get references to all open editors with:
PlatformUI.getWorkbench().getActiveWorkbenchWindow()
.getActivePage().getEditorReferences();
And then check these to select the ones that reference instances of your editor type.
According to the javadoc for the API a workbench can have several windows, and a window can have several pages, and they do not share editors.
So, in order to get all and every open editor, you should do something along these lines (error checking etc excluded):
List<IEditorReference> editors = new ArrayList<IEditorReference>();
for (IWorkbenchWindow window : PlatformUI.getWorkbench().getWorkbenchWindows()) {
for (IWorkbenchPage page : window.getPages()) {
for (IEditorReference editor : page.getEditorReferences()) {
editors.add(editor);
}
}
}
Be aware the such an enumeration will not respect the tab order
Here is an example of an enumeration of editors:
IWorkbenchWindow window = HandlerUtil.getActiveWorkbenchWindowChecked(event);
IWorkbenchPage page = window.getActivePage();
IEditorPart actEditor = page.getActiveEditor();
IEditorReference[] editors = page.getEditorReferences();
for (int i=0; i<editors.length-1; i++) {
if (editors[i].getEditor(true) == actEditor) {
page.activate(editors[i+1].getEditor(true));
return null;
}
}