How Can I Get Line Number in Visual Studio - numbers

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.

Related

How to fold all open editors in visual studio code using a script

I would like to be able to create/write a command to fold all code in all open editors within visual studio code.
I believe I am very close.
I am using the "script commands" extension written by Marcel J. Kloubert
When I use the following script with 7 or so open editors in a single group. I achieve the following:
The open editor (at the time of execution) has its code folded
VSC will loop over the open editors
No other editor has its code folded
The script I am using:
// Fold all code in all open editors.
function execute(args) {
// Obtain access to vscode
var vscode = args.require('vscode');
// Set number of open editors... (future: query vscode for number of open editors)
var numOpenEditor = 20;
// Loop for numOpenEditor times
for (var i = 0; i <= numOpenEditor; i++){
// Fold the current open editor
vscode.commands.executeCommand('editor.foldAll');
// Move to the next editor to the right
vscode.commands.executeCommand('workbench.action.nextEditor');
// Loop message
var statusString = 'Loop ->' + i
// print message
vscode.window.showErrorMessage(statusString);
}
}
// Script Commands must have a public execute() function to work.
exports.execute = execute;
I have made an interesting observation, when I use the above script with 7 or so open editors with two groups or more. Something about switching to a new group will allow the command editor.foldAll to work. Note, that if a group has multiple editors, the only editor to fold its code is the open editor in the group. Thus, all other editors will not fold.
I also thought that maybe... the script needed to slow down, so I added a function to pause on every iteration. This did not turn out to work either.
Any help would be great!
You just need to make this function async and wait for the executeCommand calls to complete before moving on:
// Fold all code in all open editors.
async function execute(args) {
// Obtain access to vscode
var vscode = args.require('vscode');
// Set number of open editors... (future: query vscode for number of open editors)
var numOpenEditor = 5;
// Loop for numOpenEditor times
for (var i = 0; i <= numOpenEditor; i++) {
// Fold the current open editor
await vscode.commands.executeCommand('editor.foldAll');
// Move to the next editor to the right
await vscode.commands.executeCommand('workbench.action.nextEditor');
// Loop message
var statusString = 'Loop ->' + i
// print message
vscode.window.showErrorMessage(statusString);
}
}
// Script Commands must have a public execute() function to work.
exports.execute = execute;

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();
}

Can I use the eclipse debugger to write a variable to a file

Is it possible to create some sort of "trace breakpoint" in eclipse whereby Eclipse will log variables that I choose to a file when a "breakpoint" is hit without pausing the application?
Sure. For this sample method:
public static void logArgs(final String one, final String two) {
System.out.println(one + two);
}
put your breakpoint in it, right click it and edit Breakpoint properties... as in the example. The important checkboxes are Conditional and Suspend when 'true'. Just return false so that breakpoint does not suspend at all.
java.io.FileWriter w = new java.io.FileWriter("/tmp/file.txt", true);
w.write(String.format("args(%s, %s)%n"), one, two));
w.close();
return false;
For Java 11 Michał Grzejszczak's answer can be written as
java.nio.file.Files.writeString(java.nio.file.Path.of("f.txt"), "My string to save");return true;
(Best way to write String to file using java nio)

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.

Eclipse custom formatting

I'm trying to create a JAVA code formatter such that it doesn't wrap any lines. BUT for any lines in my code that I have manually wrapped I want the formatter to respect them and not format them in to one line.
For example:
public Class {
public Class(String a,
String b,
String c,
String d) {
// The constructor arguments should stay as they are
}
public void aMethod() {
// This statement should not be wrapped
get().doSomething().getAnohterMethodThatHasAReeeeeeeaalllyyLongName();
}
}
I have made the line width 9999 (the max), and I have turned off line wrapping for everything. What have I missed?
Thanks.
I opened the preference page for
"Java - Code Style - Formatter"
and activated "never join lines"
and selected "Do not wrap" in the combo box "line wrapping policy"
After this change i was able to write code, which was not wrapped.