Highlighting text at specific location from IntelliJ plugin - plugins

I am developing an IntelliJ plugin and trying to highlight text programmatically at specific line and column but facing the following issue: the actual column in IntelliJ changes depending on the tab size in its configuration. Therefore column index of the specific location can change without any changes performed in the edited text.
In Eclipse for example tab is always counted as one character.
Can you point me to some example of how to highlight a specific code location independent of the configured tab size?
Currently it is implemented like this:
private static void showPsiFile(Project project, PsiFile file, int lineNumber, int column, int length) {
OpenFileDescriptor desc = new OpenFileDescriptor(project, file.getVirtualFile(), lineNumber - 1, column);
desc.navigate(true);
Editor editor = FileEditorManager.getInstance(project).getSelectedTextEditor();
int caretLocation = editor.getCaretModel().getOffset();
int startOffset = caretLocation;
int endOffset = startOffset + length;
for (RangeHighlighter highlighter : editor.getMarkupModel().getAllHighlighters()) {
highlighter.dispose();
}
editor.getMarkupModel().addRangeHighlighter(startOffset, endOffset, HighlighterLayer.ERROR, codeHighlightTextAttributes, HighlighterTargetArea.EXACT_RANGE);
}

Related

Is there way to auto resize percentage columns when column group is collapsed/expaned in NatTable

I found ResizeColumnHideShowLayer class at nattable version 1.6.
(about https://bugs.eclipse.org/bugs/show_bug.cgi?id=521486)
That is work fine for normal column headers only.
But, if I collapse a column group, no adjust size to fit window. (no increasing column size)
How can I solve the problem?
Is there way to resize other columns to fit window automatically increase?
Thank you.
Currently not because the ColumnGroupExpandCollapseLayer is taking care of hiding collapsed columns.
I found solution by myself!
It works fine very well. :-)
I was run based on NatTable v1.6 version.(downloaded yesterday)
I think this is a basic feature, so I hope this feature will be included in the next NatTable version.
In narrow tables, behavior that collapsing column group means that may be someone want to view other column data more widely.
Overview (Problem screen and solved screen)
I explain using two application(before, after) screen shot.
Refer to bottom image if you want understand my issue easily at once.
Problem screen
enter image description here
Improved screen
enter image description here
Solution summary :
Add event listener to ColumnGroupExpandCollapseLayer.
      (HideColumnPositionsEvent, ShowColumnPositionsEvent)
Handle above events.
      Get column indices which is hidden by collapsed
      Execute MultiColumnHideCommand with the indices
Layer structure of my test code
↑ ViewportLayer (top layer)
| SelectionLayer
| ColumnGroupExpandCollapseLayer
| ResizeColumnHideShowLayer
| ColumnGroupReorderLayer
| ColumnReorderLayer
| DataLayer (base layer)
Implementation code is below:
void method() {
...
columnGroupExpandCollapseLayer.addLayerListener(new ILayerListener() {
#Override
public void handleLayerEvent(ILayerEvent event) {
boolean doRedraw = false;
//It works for HideColumnPositionsEvent and ShowColumnPositionsEvent
// triggered by ColumnGroupExpandCollapseCommandHandler
if (event instanceof HideColumnPositionsEvent) {
HideColumnPositionsEvent hideEvent = (HideColumnPositionsEvent)event;
Collection<Range> columnPositionRanges = hideEvent.getColumnPositionRanges();
Collection<Integer> convertIntegerCollection = convertIntegerCollection(columnPositionRanges);
int[] positions = convertIntPrimitiveArray(convertIntegerCollection);
//Execute command to hide columns that was hidden by collapsed column group.
MultiColumnHideCommand multiColumnHideCommand = new MultiColumnHideCommand(resizeColumnHideShowLayer, positions);
resizeColumnHideShowLayer.doCommand(multiColumnHideCommand);
doRedraw = true;
}else if (event instanceof ShowColumnPositionsEvent) {//called by ColumnGroupCollapsedCollapseCommandHandler
ShowColumnPositionsEvent showEvent = (ShowColumnPositionsEvent)event;
Collection<Range> columnPositionRanges = showEvent.getColumnPositionRanges();
Collection<Integer> positions = convertIntegerCollection(columnPositionRanges);
//Execute command to show columns that was hidden by expanded column group.
MultiColumnShowCommand multiColumnShowCommand = new MultiColumnShowCommand(positions);
resizeColumnHideShowLayer.doCommand(multiColumnShowCommand);
//Set whether or not to redraw table
doRedraw = true;
}
if (doRedraw) {
natTable.redraw();
}
}
/**
* Merge position values within several Ranges to Integer collection
*/
private Collection<Integer> convertIntegerCollection(Collection<Range> rangeCollection) {
Iterator<Range> rangeIterator = rangeCollection.iterator();
Set<Integer> mergedPositionSet = new HashSet<Integer>();
while (rangeIterator.hasNext()) {
Range range = rangeIterator.next();
mergedPositionSet.addAll(range.getMembers());
}
return mergedPositionSet;
}
/**
* Convert Integer wrapper object to primitive value
*/
private int [] convertIntPrimitiveArray(Collection<Integer> integerCollection) {
Integer [] integers = (Integer [])integerCollection.toArray(new Integer[integerCollection.size()]);
int [] positionPrimitives = new int[integers.length];
for (int i = 0 ; i < integers.length ; i++) {
positionPrimitives[i] = integers[i].intValue();
}
return positionPrimitives;
}
});
}

Eclipse Editor - SWT StyledText CaretListener offset not corresponding to real file line number

I am currently working on an Eclipse plugin. In order to do an action, I need to listen to the caret listener of the active tab.
public void partOpened(IWorkbenchPartReference partRef) {
AbstractTextEditor e = (AbstractTextEditor) ((IEditorReference) partRef).getEditor(false);
StyledText sText = ((StyledText) e.getAdapter(Control.class));
sText.addCaretListener(new CaretListener() {
#Override
public void caretMoved(CaretEvent event) {
IDocument d = e.getDocumentProvider().getDocument(e.getEditorInput());
...
int line = d.getLineOfOffset(event.caretOffset);
Point p = sText.getLocationAtOffset(event.caretOffset);
}
});
}
I use this code to add the CaretListener on the latest opened tab.
The variable line is correct only when no code blocks are collapsed.
In fact, the offset returned by the event is linked to the StyledText, but I'd like to get the line number of the file.
This picture shows an example of folded text. The StyledText caret offset will give me something like line 6, 7 and 8, instead of 6, 7 and 12 (like Eclipse does).
Is there a way to "transform" the StyledText offset to a "real file" offset ? I could retrieve the line as a String and find it in the file, but it sounds like a bad idea.
Thanks !
For folding editors the editor's source viewer will implement ITextViewerExtension5 which provides a widgetOffset2ModelOffset method to make this adjustment.
Get the caret position using something like:
ISourceViewer sourceViewer = e.getSourceViewer();
int caret;
if (sourceViewer instanceof ITextViewerExtension5) {
ITextViewerExtension5 extension = (ITextViewerExtension5)sourceViewer;
caret = extension.widgetOffset2ModelOffset(styledText.getCaretOffset());
} else {
int offset = sourceViewer.getVisibleRegion().getOffset();
caret = offset + styledText.getCaretOffset();
}

Extraction of images present inside a paragraph

I am building an application where i need to parse a pdf which is generated by a system and with that parsed information i need to populate my applications database columns but unfortunaltely the pdf structure that i am dealing with is having a column called comments which has both text and image. I found the way of reading the images and text separately from the pdf but my ultimate aim was to add a place holder something like {2} in the place of image inside the parsed content and whenever my parser ( the application code ) parse this line the system will render the appropriate image in that area which is also stored in a separate table inside my application.
Please help me with resolving this problem.
Thanks in advance.
As already mentioned in comments, a solution would be to essentially use a customized text extraction strategy to insert a "[ 2]" text chunk at the coordinates of the image.
Code
You can e.g. extend the LocationTextExtractionStrategy like this:
class SimpleMixedExtractionStrategy extends LocationTextExtractionStrategy
{
SimpleMixedExtractionStrategy(File outputPath, String name)
{
this.outputPath = outputPath;
this.name = name;
}
#Override
public void renderImage(final ImageRenderInfo renderInfo)
{
try
{
PdfImageObject image = renderInfo.getImage();
if (image == null) return;
int number = counter++;
final String filename = String.format("%s-%s.%s", name, number, image.getFileType());
Files.write(new File(outputPath, filename).toPath(), image.getImageAsBytes());
LineSegment segment = UNIT_LINE.transformBy(renderInfo.getImageCTM());
TextChunk location = new TextChunk("[" + filename + "]", segment.getStartPoint(), segment.getEndPoint(), 0f);
Field field = LocationTextExtractionStrategy.class.getDeclaredField("locationalResult");
field.setAccessible(true);
List<TextChunk> locationalResult = (List<TextChunk>) field.get(this);
locationalResult.add(location);
}
catch (IOException | NoSuchFieldException | SecurityException | IllegalArgumentException | IllegalAccessException ioe)
{
ioe.printStackTrace();
}
}
final File outputPath;
final String name;
int counter = 0;
final static LineSegment UNIT_LINE = new LineSegment(new Vector(0, 0, 1) , new Vector(1, 0, 1));
}
(Unfortunately for this kind of work, some members of LocationTextExtractionStrategy are private. Thus, I used some Java reflection. Alternatively you can copy the whole class and change your copy accordingly.)
Example
Using that strategy you can extract mixed contents like this:
#Test
public void testSimpleMixedExtraction() throws IOException
{
InputStream resourceStream = getClass().getResourceAsStream("book-of-vaadin-page14.pdf");
try
{
PdfReader reader = new PdfReader(resourceStream);
PdfReaderContentParser parser = new PdfReaderContentParser(reader);
SimpleMixedExtractionStrategy listener = new SimpleMixedExtractionStrategy(OUTPUT_PATH, "book-of-vaadin-page14");
parser.processContent(1, listener);
Files.write(new File(OUTPUT_PATH, "book-of-vaadin-page14.txt").toPath(), listener.getResultantText().getBytes());
}
finally
{
if (resourceStream != null)
resourceStream.close();
}
}
E.g. for my test file (which contains page 14 of the Book of Vaadin):
You get this text
Getting Started with Vaadin
• A version of Book of Vaadin that you can browse in the Eclipse Help system.
You can install the plugin as follows:
1. Start Eclipse.
2. Select Help   Software Updates....
3. Select the Available Software tab.
4. Add the Vaadin plugin update site by clicking Add Site....
[book-of-vaadin-page14-0.png]
Enter the URL of the Vaadin Update Site: http://vaadin.com/eclipse and click OK. The
Vaadin site should now appear in the Software Updates window.
5. Select all the Vaadin plugins in the tree.
[book-of-vaadin-page14-1.png]
Finally, click Install.
Detailed and up-to-date installation instructions for the Eclipse plugin can be found at http://vaad-
in.com/eclipse.
Updating the Vaadin Plugin
If you have automatic updates enabled in Eclipse (see Window   Preferences   Install/Update
  Automatic Updates), the Vaadin plugin will be updated automatically along with other plugins.
Otherwise, you can update the Vaadin plugin (there are actually multiple plugins) manually as
follows:
1. Select Help   Software Updates..., the Software Updates and Add-ons window will
open.
2. Select the Installed Software tab.
14 Vaadin Plugin for Eclipse
and two images book-of-vaadin-page14-0.png
and book-of-vaadin-page14-1.png
in OUTPUT_PATH.
Improvements to make
As also already mentioned in comments, this solution is for the easy situation in which the image has text above and/or below but neither left nor right.
If there is text left and/or right, too, there is the problem that the code above calculates LineSegment segment as the bottom line of the image but the text strategy usually works with the base line of text which is above the bottom line.
But in this case one first has to decide at which position on which line one wants the marker in the text to be anyways. Having decided that, one can adapt the source above.

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.

How Can I Get Line Number in Visual Studio

I want to get line number from Visual Studio. Is it possible ? Thanks
You can use CallerLineNumberAttribute
public void DoProcessing()
{
TraceMessage("Something happened.");
}
public void TraceMessage(string message,
[CallerLineNumber] int sourceLineNumber = 0)
{
Trace.WriteLine("message: " + message);
Trace.WriteLine("source line number: " + sourceLineNumber);
}
// Sample Output:
// message: Something happened.
// source line number: 31
If you just want to display line numbers in the IDE (as in your screenshot), follow these steps (tested in VS2012):
On the menu bar, choose Tools / Options. Expand the Text Editor node, then select either All Languages or, if you want it for just a specific language, open the node for the language you're using. Then check the Line Numbers checkbox in the Display section.
More info here on MSDN.