Trigger Eclipse's code formatter programmatically from a new file wizard - eclipse-plugin

I'm writing an Eclipse plugin with a wizard (org.eclipse.jface.wizard.Wizard) which creates a new file with a basic code template. To simplify the "piecing together" of the file contents, I plan to stuff everything into one long string, inject it into the file, and then call my custom Formatter (inherits org.eclipse.xtext.formatting.impl.AbstractDeclarativeFormatter) to clean up all the indentation and so on.
Question is, how do I go about calling the formatter programmatically?
In the wizard I call IDE.openEditor() and get back a handle to an IEditorPart. What can I do from here?

Well, I have found my answer:
IEditorPart editor = IDE.openEditor(page, file, true);
XtextEditor xed = (XtextEditor)editor;
((SourceViewer)xed.getInternalSourceViewer()).doOperation(ISourceViewer.FORMAT);
Maybe that will help someone else looking for something similar!

Related

How do I go to the nth method of the eclipse editor's file?

I need to write a function goToNthMethod(int n) to let the user jump to the nth method in the file being edited.
Ideas so far:
I imagine the ContentOutline reads its tree from some sort of IContentSource (made up) or something, if I can read from the same source, that would probably be cleaner. Does something like this exist?
Read the contents of the outline view, and maybe simulate a double click on one of the Outline view's entries. This is as far as I got before I realized I was in over my head:
IWorkbenchPage page = PlatformUI.getWorkbench().getActiveWorkbenchWindow().getActivePage();
IViewPart part = page.findView("org.eclipse.ui.views.ContentOutline");
ContentOutline outline = (ContentOutline)part;
PageBook pageBook = outline.book; // Doesn't work, book is private
Tree root = pageBook.currentPage; // Doesn't work, currentPage is private
String label = root.getLabel(); // Nothing like getLabel exists
Read the entire IDocument's contents, parse the java source code within, get the offsets in the file, and feed that to the editor.selectAndReveal method. However, parsing the java source code within is a massive task, so this approach probably won't work.
Use outline.getCurrentPage(), which is a JavaOutlinePage, but I can't seem to import that class. I'm guessing I need to pull in the entire JDT project to do that. This approach also means I'm tied to a specific language, when I want my goToNthMethod to be language agnostic.
Any ideas on how I can jump to the nth method? Thanks!
Some context: I'm integrating Dragon NaturallySpeaking with eclipse to be able to program with my voice. It's working well so far, but one tedious part is navigating around the file, which would be made easier if I could say "go to 8th method". In fact, just "go to 8th entry" to just go to the 8th row in the outline view would be sufficient. Any other ideas appreciated!

Issues with modifying the editor document in Intellij Plugin development

When I do something like this in a a Writecommand action,
editor.getDocument().insertString(offset, "Sample text");
I guess it is stored in cache and is not updated immediately.
So what can be done to get the update in the very immediate line.
I tried refreshing the Virtualfile synchronisely and asynchronisely, but didnt help.
So what can be done?
To update the file on disk, use FileDocumentManager.saveDocument(). To update the PSI for the document, use PsiDocumentManager.commitDocument().

Eclipse custom text editor update syntax highlighting

I am writing an Eclipse plugin (Indigo/Juno) that contains a text editor for a custom text format. I am following the tutorial here: http://www.realsolve.co.uk/site/tech/jface-text.php
So far I have everything working. Eclipse will use my editor to edit files. I have partitioning, damaging, repairing, syntax highlighting all working.
I added a preferences page with color pickers to control syntax highlighting. It works mostly correct. If I update the colors, the editor uses them the next time I open or reopen a file.
How do I get an editor tab to update itself without opening a new one? The built-in JDT Java editor does this, but so far I have not been able to decipher how (it is a very large and complex editor).
I gather that I need to create a preferences listener (http://www.vogella.com/articles/EclipsePreferences/article.html). I have done this and can verify that my listener code is being invoked when I set a breakpoint in it.
The missing piece is the wiring between the listener and reinitializing the editor. I have tried reconstructing the partitioning logic, the color logic, the damager/repairer, etc. but nothing seems to work. It either does nothing I can see or at worst will corrupt the display until I scroll the current text out of view to repaint it... with the old colors.
Any ideas?
I think SourceViewer.invalidatePresentation() needs to be called.
It may be already late to you, but if you want you could use LiClipse for that (http://brainwy.github.io/liclipse/) -- one of its targets is easily doing an editor with syntax highlighting, basic code-completion, outline, etc targeting Eclipse.
No java skills are required to add a new language (mostly creating a new .liclipse -- which is a YAML -- file in the proper place and creating some basic rules to say how to partition your language -- i.e.: usually just separating code from comments from strings -- and specifying the keywords you have in the partition would already give you proper syntax highlighting).
If you download it, there are a number of examples at plugins\com.brainwy.liclipse.editor\languages and there's some basic documentation at http://brainwy.github.io/liclipse/supported_languages.html and http://brainwy.github.io/liclipse/scope_definition.html on how to do it.
For anyone coming across this as I did:
My solution involved adding the following lines into the Constructor of my Editor
Activator.getActivator().getPreferenceStore().addPropertyChangeListener(new IPropertyChangeListener() {
#Override
public void propertyChange(PropertyChangeEvent event) {
getSourceViewer().invalidateTextPresentation();
handlePreferenceStoreChanged(event);
}
});
and then creating a custom class that extended IToken. In the constructor I pass the String of the preference field and then in the 'getObject' method I create the TextAttribute: snippets below
public class MyToken extends Token implements IToken {
public MyToken(Object data) {
super(data);
}
#Override
public Object getData() {
String dataString = (String) super.getData();
return getAttributeFromColorName(dataString);
}
private TextAttribute getAttributeFromColorName(String preferenceField) {
Color color = new Color(Display.getCurrent(), StringConverter.asRGB(Activator.getActivator().getPreferenceStore().getString(preferenceField)));
return new TextAttribute(color);
}
}
When I generate my Rules I have all of my tokens as my custom class and this allowed me to change syntax color dynamically.
I also added an example for updating the coloring if the preference changes to https://www.vogella.com/tutorials/EclipseEditors/article.html#exercise-allow-user-to-customize-the-colors
This is using the Generic editor (currently the best approach to implement a customer editor) but it should be possible to adjust this to any Eclipse editor implementation.

Better way to use Velocity's GenericTools in a Standalone app?

I want to use VelocityTool's GenericTools for some standard formatting in a standalone app. e.g. have something like this in my Velocity template to use the GenericTools' NumberTool formatter:
Total: $numberTool.format("#0.00", $totalPnL)
How do I associate the above "$numberTool" with the GenericTool NumberTool. Here's my Velocity code:
Velocity.init();
VelocityContext velocityContext = new VelocityContext();
Template template = Velocity.getTemplate("example.vm");
velocityContext.put("totalPnL", 100);
StringWriter sw = new StringWriter();
template.merge(velocityContext, sw);
Now I know I can do this to get it to work:
velocityContext.put("numberTool", new NumberTool());
But is that how I need to add all the GenericTools to my app? Manually and one at a time (e.g. another line for DateTool ... etc)? Isn't there a way to make all the GenericTools exposed to my template with out this? I know there's a "tools.xml" that comes with VelocityTools that has the GenericTools defined. Can I just add that to my app to expose all the tools? If so, how?
thanks,
David
http://velocity.apache.org/tools/devel/javadoc/org/apache/velocity/tools/ToolManager.html
http://velocity.apache.org/tools/devel/standalone.html
The default tool configuration provides all the generic tools already. Though you can create a config if you want to configure those tools. There's even auto loading for configurations, or manual specification.
ToolManager tm = new ToolManager();
tm.setVelocityEngine(yourVelocityEngine);
Context context = tm.createContext();
it is at least the way I do it too.
I'll put for example
context.put("esc", new EscapeTool());
and in the template I simply use then
${esc.h}
to write a "#" in the code so that Velocity does not parse it as "velocity-script".
I think those helper tools are rather utils and only cover some basic signs. They are not intend to be a standard, you rather can include them on-demand.
I've build for example an abstract class that loads the context of velocity and puts the EscapeTool into the context all the time so that I do not have to add it everywhere.
Good luck with your project
Sebastian

How to expose the content formatter in a custom Eclipse editor?

I am writing a custom Eclipse editor by subclassing TextEditor, and I can't use the Format action that I configured.
I read the 3 parts in Creating a commercial quality IDE, and I know about SourceViewerConfiguration. I implemented the required method:
override def getContentFormatter(viewer: ISourceViewer) = {
val formatter = new MultiPassContentFormatter(getConfiguredDocumentPartitioning(viewer), IDocument.DEFAULT_CONTENT_TYPE)
formatter.setMasterStrategy(new ScalaFormattingStrategy(textEditor))
formatter
}
However, I can't find Format anywhere in the menu, contextual menu, toolbar, etc. The Java shortcut (CMD-Shift-F) does not work either.
Edit: I have implemented other methods in the SourceViewerConfiguration subclass I created, and everything else works as expected in my editor (completion, hyperlinking, reconciliation).
What is the preferred way to expose the formatter? Do I need to do anything more?
Quoting the Eclipse formatter FAQ:
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);