Trigger formatter in a custom plug-in in Eclipse - eclipse

I writing my own text editor plugin for eclipse. I am now working on my own formatter. Actually, following that link http://wiki.eclipse.org/FAQ_How_do_I_support_formatting_in_my_editor%3F.
I have written my Strategy, I have overridden getContentFormatter in my SourceViewerConfiguration..
As I run my plugin and press Ctrl+Shift+F - and nothing happens.
I think that I'm missing a step here. Should I create a handler or something?
Thanks

Might it be you skipped the last part of the linked page?
Finally, you will need to create an action that invokes the formatter. No generic formatting action is defined by the text infrastructure, but it is quite easy to create one of your own. The action’s run method can simply call the following on the source viewer to invoke the formatter:
sourceViewer.doOperation(ISourceViewer.FORMAT);

What helped me. I have created a handler with the following executors body:
//get the editorPart
if (editorPart != null) {
ITextOperationTarget target = (ITextOperationTarget) editorPart
.getAdapter(ITextOperationTarget.class);
if (target instanceof ISourceViewer) {
ISourceViewer textViewer = (ISourceViewer) target;
((ITextOperationTarget) textViewer)
.doOperation(ISourceViewer.FORMAT);
}
}
Then just create menu items and bind them to the handler.

Related

Eclipse: Select text in XSD programmatically from plugin

I'm currently writing an Eclipse plugin. In it, I want to programmatically open an editor and select a portion of the text. The opened file does not have to be imported into the workspace (that's why I'm using IFileStore in the code below).
I'm using code similar to this:
IFileStore fileStore = EFS.getLocalFileSystem().getStore(localPath);
IEditorPart part = IDE.openEditorOnFileStore(page, fileStore);
final int posStart = ...;
final int posEnd = ...;
part.getEditorSite().getSelectionProvider().setSelection(
new TextSelection(posStart, posEnd - posStart));
For Java files it works fine, but for XML Schema (XSD), it doesn't. The editor opens, but no text is selected.
From debugging, I can tell that the part is of type org.eclipse.wst.xsd.ui.internal.editor.InternalXSDMultiPageEditor, and the selection manager is an org.eclipse.wst.xsd.ui.internal.adt.editor.CommonSelectionManager
I'm targetting Eclipse Mars and Neon, it does not seem to work for both.
What can I do to make it work? Or at least find some further information?
After having a look at the WTP code, this does not seem to be supported at the moment. But I found a workaround by explicitly checking if the editor is a multi part editor:
private static void setSelection(IEditorPart part, TextSelection textSelection) {
if (part instanceof MultiPageEditorPart) {
final MultiPageEditorPart multiPage = (MultiPageEditorPart) part;
for (final IEditorPart subPart : multiPage.findEditors(multiPage.getEditorInput())) {
setSelection(subPart, textSelection);
}
} else {
part.getEditorSite().getSelectionProvider().setSelection(textSelection);
}
}
I was not sure whether it is better to send the selection to all sub parts or only to one specific, but so far sending it to all seems to work.

Suppress Errors in JavaScript validation

I'm currently developing an eclipse plugin. This plugin contains a project nature which depends on the javaScript nature of jsdt.
Now at a few details the JavaScripts that the projects of my nature can contain are somewhat special.
They can contain "compiler hints" which are basicly statements beginning with #
They can contain return statements outside of functions
But at this two points the standard validation of jsdt come in and marks them as errors (which is normally right). I already managed to get this errors filtered out in the properties of the JavaScript validator (manually).
My question is, how can i exclude these errors from the validation of jsdt automatically for the projects with my nature?
JSDT uses concrete syntax parser which generates syntax errors.
You can't disable this. Only semantics error or warnings can be configured.
However you can disable entire validation of JSDT.
Below solution will suppress errors ands warnings which are generated while we save some changes on java script files. (Auto Build, Build)
Open Properties Dialog of Your Project.
Choose Builders item.
Uncheck "JavaScript Validator". And Press OK button.
Remove current errors and warnings from Problems View
This solution can't eliminate error or warning annotations in editor while you edit. They will show up on editor temporarily only when you edit it.
After a lot of research, hours of deleting markers and debugging i finally managed to delete the errors i wanted. In a bad bad way of course but i've come to a point where i just wanted this to work no matter how it's done.
If you ever want to delete existing problems that had been created during the validation process of jsdt you need to do the following (and you must not ommit anything):
Create a class extending org.eclipse.wst.jsdt.core.compiler.ValidationParticipant
Override isActive(), buildStarting() and reconcile() methods.
So there are two things you basicly have to care about.
The actual problem markers that will be created or had already been created at the end of the validation process.
The Problems created by the validation process. They are of the type CategorizedProblem and can be obtained by the ReconcileContext object that is passed to the reconcile() method.
It seems to me that the CategorizedProblems will be translated to problem markers after the validation process.
So what you need to do is:
Delete all unwanted problem markers of all files in buildStarting (this removes problem markers from all files in your project that are about to be validated)
Iterate the CategorizedProblem objects of the ReconcileContext (getProblems())
Create a new Array containing only the CategorizedProblems you want to keep
Set this new Array to the ReconcileContext with putProblems()
Delete the unwanted markers again for that file (i don't know why this is needed, please don't ask, i don't care anymore :-/)
An example implementation of such a validationParticipant could look like this: (this one will filter out problems complaining about return statements outside of methods:
[...ommited imports ...]
public class MyValidationParticipant extends org.eclipse.wst.jsdt.core.compiler.ValidationParticipant{
#Override
public boolean isActive(IJavaScriptProject project) {
return true;
}
#Override
public void buildStarting(BuildContext[] files, boolean isBatch) {
super.buildStarting(files, isBatch);
for(BuildContext context : files){
IFile file = context.getFile();
deleteUnwantedMarkers(file);
}
}
#Override
public void reconcile(ReconcileContext context) {
IResource resource = context.getWorkingCopy().getResource();
CategorizedProblem[] newProblems = new CategorizedProblem[0];
ArrayList<CategorizedProblem> newProblemList = new ArrayList<CategorizedProblem>();
CategorizedProblem[] probs = context.getProblems("org.eclipse.wst.jsdt.core.problem");
if(probs != null){
for(CategorizedProblem p : probs){
if(!(p.getMessage().equals("Cannot return from outside a function or method."))){
newProblemList.add(p);
}
}
}
}
context.putProblems("org.eclipse.wst.jsdt.core.problem", newProblemList.toArray(newProblems));
deleteUnwantedMarkers(resource);
}
public static void deleteUnwantedMarkers(IResource resource){
if(resource.isSynchronized(IResource.DEPTH_INFINITE)){
try {
IMarker[] markers = resource.findMarkers(IMarker.PROBLEM, true, IResource.DEPTH_INFINITE);
if(markers != null && markers.length > 0){
for(IMarker m : markers){
Object message = m.getAttribute(IMarker.MESSAGE);
if(message.equals("Cannot return from outside a function or method.")){
m.delete();
}
}
}
}catch (CoreException e) {
e.printStackTrace();
}
}
}
}
As i said, this is kind of a bad solution since the code relies on the String of the error message. There should be better ways to identify the problems you don't want to have.
Don't forget to add a proper extension in your plugin.xml for the ValidationParticipant.

Eclipse RCP - project selected (Package Explorer)

How do I retrieve the name and path of the project selected? (Package Explorer)
example: c:\project\test\projectName
someone has some code that explains how to complete I get the project name or full path of a particular project in my workspace?
Eclipse defines an extension point
"org.eclipse.ui.navigator.linkHelper"
If you contribute a class to these EP you have to implement ILinkHelper
The ILInkHelper interface notifies you, when something was selected in the explorer
public void activateEditor(IWorkbenchPage aPage, IStructuredSelection aSelection)
You can check the type of the selection
if (aSelection.getFirstElement() instanceof IFile) {
// Do something
}
Old memories but maybe useful for you. I guess package explorer provides its selection, so you can get the current selection in your code by calling:
ISelectionService service = getSite().getWorkbenchWindow().getSelectionService()
than you can get the package explorer view by its id (plugin.xml for more details):
IStructuredSelection selection = (IStructuredSelection) service.getSelection("org.eclipse.jdt.ui.PackageExplorer");
Please note AFAIK you can always safely cast ISelection to IStructuredSelection. Then call structured.getFirstElement() and I think the first element will be an IFile object. I hope my "pseudo code" whould be enough for you. And IFile has lots of usefule methods for your convenience

How to get the Path of current selected file in Eclipse?

I want to get the path of current selected file in Eclipse workspace but my project is a simple view plug-in project.
I just want to display the name/path of the file selected as soon as user opens the view.
You get the current selection as mentioned by #Danail Nachev. See http://www.eclipse.org/articles/Article-WorkbenchSelections/article.html for information on working with the selection service.
Once you have the selection, the most common pattern is:
if (selection instanceof IStructuredSelection) {
IStructuredSelection ssel = (IStructuredSelection) selection;
Object obj = ssel.getFirstElement();
IFile file = (IFile) Platform.getAdapterManager().getAdapter(obj,
IFile.class);
if (file == null) {
if (obj instanceof IAdaptable) {
file = (IFile) ((IAdaptable) obj).getAdapter(IFile.class);
}
}
if (file != null) {
// do something
}
}
Edit:
Usually you get an InputStream from the IFile and process it that way. Using some FileSystemProviders or EFS implementations, there might not be a local path to the file.
PW
You can retrieve the current workbench selection using two methods with the following code:
through the Workbench SelectionService
getViewSite().getSelectionProvider().getSelection()
getViewSite().getWorkbenchWindow().getSelectionService()
You can find more information in this article.
Using the global workbench selection is the better approach, because it enables your view to get selection from everywhere, which is something the user might expect (I at least do). Also, almost all of the views in Eclipse (and I don't know exceptions to this rule) are using this approach.
If you absolutely must to tie your view to another view, then you can get all IWorkbenchPage iterate over them and search for the view by its ID and when you find the view, you call get its SelectionProvider to get the selection.
Only by reading this explanation, makes my hair go straight up. Considering that there might be multiple instances of the same view, you can end up with a selection from a random view. I'm not sure whether the user will make sense of how things work, unless you have some clear rules, which exactly view you need. It is up to you.
`

When writing Eclipse plugins, what is the correct way for checking if an IEditorPart is a Java editor?

I am writing Eclipse plugins for Java, and have the following problem:
Given an IEditorPart, I need to check if it is a java editor.
I could do (IEditor instanceof JavaEditor),
but JavaEditor is an org.eclipse.jdt.internal.ui.javaeditor.JavaEditor,
which falls under the JDT's "internal" classes.
Is there a smarter and safer way to do this? I'm not sure why there is no non-internal interface for this.
You should test the id of the IEditorPart:
private boolean isJavaEditor(IWorkbenchPartReference ref) {
if (ref == null) {
return false; }
String JavaDoc id= ref.getId();
return JavaUI.ID_CF_EDITOR.equals(id) || JavaUI.ID_CU_EDITOR.equals(id);
}
Testing the instance was only needed in eclipse3.1.
alt text http://blogs.zdnet.com/images/Burnette_DSCN0599.JPG
JavaUI is the main access point to the Java user interface components. It allows you to programmatically open editors on Java elements, open a Java or Java Browsing perspective, and open package and type prompter dialogs.
JavaUI is the central access point for the Java UI plug-in (id "org.eclipse.jdt.ui")
You can see that kind of utility function ("isJavaEditor()") used for instance in ASTProvider.
The mechanism of identification here is indeed simple String comparison.
Anyway, you are wise to avoid cast comparison with internal class: it has been listed as one of the 10 common errors in plugins development ;) .
One strategy might be to use JavaUI.getEditorInputJavaElement(IEditorPart):
// given IEditorPart editor
IJavaElement elt = JavaUI.getEditorInputJavaElement(editor.getEditorInput());
if (elt != null) {
// editor is a Java editor
}
The method returns null if the editor input is not in fact a Java element.