How to format a Java file in Vim like Eclipse - eclipse

I am using Vim to edit a Java file, but I find the way Vim formats Java files is very different from Eclipse.
If I select the following code and press =, Vim does not format the code the way I would like. Can anyone help me?
Before Format:
case RINGTONE_PICKED: {
Uri pickedUri = data.getParcelableExtra(RingtoneManager.EXTRA_RINGTONE_PICKED_URI);
handleRingtonePicked(pickedUri);
break;
}
case PHOTO_PICKED_WITH_DATA: {
if (mPhotoEditorView != null) {
final Bitmap photo = data.getParcelableExtra("data");
mPhotoEditorView.setPhotoBitmap(photo);
} else {
// The contact that requested the photo is no longer present.
// TODO: Show error message
}
break;
}
After Format:
case RINGTONE_PICKED: {
Uri pickedUri = data.getParcelableExtra(RingtoneManager.EXTRA_RINGTONE_PICKED_URI);
handleRingtonePicked(pickedUri);
break;
}
case PHOTO_PICKED_WITH_DATA: {
if (mPhotoEditorView != null) {
final Bitmap photo = data.getParcelableExtra("data");
mPhotoEditorView.setPhotoBitmap(photo);
} else {
// The contact that requested the photo is no longer present.
// TODO: Show error message
}
break;
}
This is what I want:
case RINGTONE_PICKED: {
Uri pickedUri = data.getParcelableExtra(RingtoneManager.EXTRA_RINGTONE_PICKED_URI);
handleRingtonePicked(pickedUri);
break;
}
case PHOTO_PICKED_WITH_DATA: {
if (mPhotoEditorView != null) {
final Bitmap photo = data.getParcelableExtra("data");
mPhotoEditorView.setPhotoBitmap(photo);
} else {
// The contact that requested the photo is no longer present.
// TODO: Show error message
}
break;
}

Indentation in VIM (and in any other editor or IDE) is carried on by indentation rules coded by someone. There is no guarantee that any two system will follow same indentation practice, since there are different indentation practices around.
I also use VIM for minor editing Java files, and I'm not aware of any common alternative indentation script for Java, other than the one included in the official distribution. I you're familiar with VIM scripting you can try to edit the indentation script to your needs. It resides at $VIMRUNTIME/indent/java.vim.
By the way your example is a little uncommon. Using curly braces for cases of a switch statement is unnecessary. I guess VIM indentation scripts indent blocks by considering the block type and gets confused with this kind of uncommon blocks. Netbeans also get a little confused with this example, it aligns the case blocks in a reasonable way, but the closing curly brace of switch statement is completely out of alignment. That kind of odd behavior will not be so common with default VIM indentation. Actually if you remove the curly braces of the case statements VIM indentation aligns the statements quite well.

Related

Understanding binding and selection in Word Add-in

I'm trying to build an add-in with similar behaviour like the comment system.
I select a part of text.
Press a button in my add-in. A card is created that links to that text.
I do something else, like write text on a different position.
When I press the card in my add-in, I'd like to jump back to the selected text (in point 1).
I studied the API, documentation. And learned that I could do something like that with Bindings. A contentcontrol might also be an option, although I noticed that you can't connect and eventhandler (it's in beta). I might need an eventhandler to track changes later.
Create binding (step 2)
Office.context.document.bindings.addFromSelectionAsync(Office.BindingType.Text, { id: 'MyBinding' }, (asyncResult) => {
if (asyncResult.status == Office.AsyncResultStatus.Failed) {
console.log('Action failed. Error: ' + asyncResult.error.message);
} else {
console.log('Added new binding with id: ' + asyncResult.value.id);
}
});
Works. Then I click somewhere else in my document, to continue with step 4.
View binding (step 4).
So I click the card and what to jump back to that text binding, with the binding selected.
I figured there are multiple ways.
Method #1
Use the Office.select function below logs the text contents of the binding. However, it doesn't select that text in the document.
Office.select("bindings#MyBinding").getDataAsync(function (asyncResult) {
if (asyncResult.status == Office.AsyncResultStatus.Failed) {
}
else {
console.log(asyncResult.value);
}
});
Method #2
Use the GoToById function to jump to the binding.
Office.context.document.goToByIdAsync("MyBinding", Office.GoToType.Binding, function (asyncResult) {
let val = asyncResult.value;
console.log(val);
});
This shows like a blue like frame around the text that was previously selected and puts the cursor at the start.
I'd prefer that I don't see that frame (no idea if that's possible) and I would like to the text selected.
There is the Office.GoToByIdOptions interface that mentions:
In Word: Office.SelectionMode.Selected selects all content in the binding.
I don't understand how pass that option in the function call though and I can't find an example. Can I use this interface to get the selection?
https://learn.microsoft.com/en-us/javascript/api/office/office.document?view=common-js-preview#office-office-document-gotobyidasync-member(1)
goToByIdAsync(id, goToType, options, callback)
If there are other ways to do this, I'd like to know that as well.
With some help I could figure it out. I learned that an Interface is just an object.
So in this case:
const options = {
selectionMode: Office.SelectionMode.Selected
};
Office.context.document.goToByIdAsync("MyBinding", Office.GoToType.Binding, options, function (asyncResult) {
console.log(asyncResult);
});
This gives the selected result.
Sure someone can provide a better answer than this, as it's unfamiliar territory for me, but...
When you create a Binding from the Selection in Word, you're going to get a Content Control anyway. So to avoid having something that looks like a content control with the blue box, you either have to modify the control's display or you have to find some other way to reference a region of your document. In the traditional Word Object model, you could use a bookmark, for example. But the office-js APIs do not seem very interested in them.
However, when you create a Binding, which is an Office object, you don't get immediate access to the Content Control's properties (since that's a Word object). So instead of creating the Binding then trying to modify the Content Control, you may be better off creating the Content Control then Binding to it.
Something like this:
async function markTarget() {
Word.run(async (context) => {
const cc = context.document.getSelection().insertContentControl();
// "Hidden" means you don't get the "Bounding Box"
// (blue box with Title), or the Start/End tag view
cc.appearance = "Hidden";
// Provide a Title so we have a Name to bind to
cc.title = "myCC";
// If you don't want users changing the content, you
// could uncomment the following line
//cc.cannotDelete = true;
return context.sync()
.then(
() => {
console.log("Content control inserted");
// Now create a binding using the named item
Office.context.document.bindings.addFromNamedItemAsync("myCC",
Office.BindingType.Text,
{ id: 'MyBinding' });
},
() => console.log("Content control insertion failed")
).then(
() => console.log("Added new binding"),
() => console.log("Binding creation failed")
)
});
}
So why not just create the ContentControl, name it, and then you should be able to select it later using its Title, right? Well, getting the "data" from a control is one thing. Actually selecting it doesn't seem straightforward in the API, whereas Selecting a Binding seems to be.
So this code is pretty similar to your approach, but adds the parameter to select the whole text. The syntax for that is really the same syntax as { id: 'MyBinding' } in the code you already have.
function selectTarget() {
Office.context.document.goToByIdAsync(
"MyBinding",
Office.GoToType.Binding,
{ selectionMode: Office.SelectionMode.Selected },
function(asyncResult) {
let val = asyncResult.value;
console.log(val);
}
);
}
Both the Binding and the ContentControl (and its Title) are persisted when you save/reopen the document. In this case, the Binding is persisted as a piece of XML that stores the type ("text"), name ("MyBinding") and a reference to the internal ID of the content control, which is a 32-bit number, although that is not immediately obvious when you look at the XML - in an example here, the Id Word stores for the ContentControl is -122165626, but "Office" stores the ID for the Binding as 4172801670, but that's because they are using the two different two's complement representations of the same number.

Prevent VS Code from changing indentation on Enter

Let's assume I have a JavaScript file with the following content and the cursor placed at the pipe symbol (|):
class ItemCtrl {
getPropertiesByItemId(id) {
return this.fetchItem(id)
.then(item => {
return this.getPropertiesOfItem(item);
});
}|
}
If I now hit enter, the code changes in the following way:
class ItemCtrl {
getPropertiesByItemId(id) {
return this.fetchItem(id)
.then(item => {
return this.getPropertiesOfItem(item);
});
}
|
}
It wrongly aligns the closing curly brace with the return statement, when it should be aligned with the method definition. I know that the formatting inside the function is not the best but I still would rather disable that feature to prevent weird things like that from happening.
I already set editor.autoIndent to false but it still keeps happening. Is there any other way, how I can turn this feature off entirely? (or make it work in a smarter way)
In VS Code 1.17, this bug caused "editor.autoIndent": false to not work
This should be fixed in VS Code 1.18

how to get vs code `ENTER` to respect/cleanup whitespace

BTW, this is not asking how to format code in VS, or the keybinding, so please don't mark it duplicate of this. It is specifically about formatting during typing.
Given the following code:
if(true) {
console.log('hello');
console.log('world');
}
If I go to the end of the 'log hello' line, hit DEL to bring 'log world' to the end of the line I will get (with | representing my cursor):
if(true) {
console.log('hello');| console.log('world');
}
Now, if I hit ENTER, I will get:
if(true) {
console.log('hello');
| console.log('world');
}
In other editors I would expect the white space to be 'eaten up' and the line to be reformatted, looking like this again:
if(true) {
console.log('hello');
|console.log('world');
}
Any thoughts on how to change this behavior?
This would also (hopefully) handle the pasting in of code that was not properly formatted, for instance, if I wanted to paste the following in:
console.log('arrrgg');
console.log('matey');
To the end of the if, I would see:
if(true) {
console.log('hello');
console.log('world');
console.log('arrrgg');
console.log('matey');
}
Instead of:
if(true) {
console.log('hello');
console.log('world');
console.log('arrrgg');
console.log('matey');
}
Certainly, I can hit Shift-Alt-F and reformat, but I don't always want to reformat an entire file....
I think I have been spoiled with VS and WebStorm automatically cleaning up and reformatting code quickly. Not sure if that is a valid
Is this even possible in Code?

How to automatically color lines in IDA?

I want IDA to automatically color lines in both the graph and text view for important instructions, for example wherever there is a call or xor instruction change the background color of each of those references to a certain color.
Here is what I am looking to achieve:
fig.1 graph view
fig.2 text view
I noticed you can go to Edit > Other > color instruction... from the main menu and this will allow you to change the background color of the selected instruction, but this does not change all of them and seems to only affect the current database.
How can I make IDA automatically color certain instructions such as call and xoras shown from the example images?
I want it to automatically work for any database I open.
You need to write an IDA plug in using IDAPython (python for IDA) or IDC (IDA scripting language which is very similar to C), the following code is in IDC:
#include <idc.idc>
static main(void)
{
auto currentEA;
auto currentMnem;
auto prevMnem;
auto currentOp;
prevMnem = "";
currentOp;
currentEA = FirstSeg();
currentEA = NextHead(currentEA, 0xFFFFFFFF);
while (currentEA != BADADDR)
{
currentMnem = GetMnem(currentEA);
//Highlight call functions
if (currentMnem == "call")
{
SetColor(currentEA, CIC_ITEM, 0xc7c7ff);
}
}
}
You can also refer to the opcodes' operands:
//Non-zeroing XORs are often signs of data encoding
if (currentMnem == "xor")
{
if (GetOpnd(currentEA, 0) != GetOpnd(currentEA, 1))
{
SetColor(currentEA, CIC_ITEM, 0xFFFF00);
}
}
Here is a guide from Hex Blog for using IDC plug-ins.
And here is a sample for similar script in IDA Python instead of IDC.

Using Eclipse TableViewer, how do I navigate and edit cells with arrow keys?

I am using a TableViewer with a content provider, label provider, a ICellModifier and TextCellEditors for each column.
How can I add arrow key navigation and cell editing when the user selects the cell? I would like this to be as natural a behavior as possible.
After looking at some of the online examples, there seems to be an old way (with a TableCursor) and a new way (TableCursor does not mix with CellEditors??).
Currently, my TableViewer without a cursor will scroll in the first column only. The underlying SWT table is showing cursor as null.
Is there a good example of TableViewer using CellEditors and cell navigation via keyboard?
Thanks!
I don't know if there is a good example. I use a cluster of custom code to get what I would consider to be basic table behaviors for my application working on top of TableViewer. (Note that we are still targetting 3.2.2 at this point, so maybe things have gotten better or have otherwise changed.) Some highlights:
I do setCellEditors() on my TableViewer.
On each CellEditor's control, I establish what I consider to be an appropriate TraverseListener. For example, for text cells:
cellEditor = new TextCellEditor(table, SWT.SINGLE | getAlignment());
cellEditor.getControl().addTraverseListener(new TraverseListener() {
public void keyTraversed(TraverseEvent e) {
switch (e.detail) {
case SWT.TRAVERSE_TAB_NEXT:
// edit next column
e.doit = true;
e.detail = SWT.TRAVERSE_NONE;
break;
case SWT.TRAVERSE_TAB_PREVIOUS:
// edit previous column
e.doit = true;
e.detail = SWT.TRAVERSE_NONE;
break;
case SWT.TRAVERSE_ARROW_NEXT:
// Differentiate arrow right from down (they both produce the same traversal #*$&#%^)
if (e.keyCode == SWT.ARROW_DOWN) {
// edit same column next row
e.doit = true;
e.detail = SWT.TRAVERSE_NONE;
}
break;
case SWT.TRAVERSE_ARROW_PREVIOUS:
// Differentiate arrow left from up (they both produce the same traversal #*$&#%^)
if (e.keyCode == SWT.ARROW_UP) {
// edit same column previous row
e.doit = true;
e.detail = SWT.TRAVERSE_NONE;
}
break;
}
}
});
(For drop-down table cells, I catch left and right arrow instead of up and down.)
I also add a TraverseListener to the TableViewer's control whose job it is to begin cell editing if someone hits "return" while an entire row is selected.
// This really just gets the traverse events for the TABLE itself. If there is an active cell editor, this doesn't see anything.
tableViewer.getControl().addTraverseListener(new TraverseListener() {
public void keyTraversed(TraverseEvent e) {
if (e.detail == SWT.TRAVERSE_RETURN) {
// edit first column of selected row
}
}
});
Now, how exactly I control the editing is another story. In my case, my whole TableViewer (and a representation of each column therein) is loosely wrapped up in a custom object with methods to do what the comments above say. The implementations of those methods ultimately end up calling tableViewer.editElement() and then checking tableViewer.isCellEditorActive() to see if the cell was actually editable (so we can skip to the next editable one if not).
I also found it useful to be able to programmatically "relinquish editing" (e.g. when tabbing out of the last cell in a row). Unfortunately the only way I could come up with to do that is a terrible hack determined to work with my particular version by spelunking through the source for things that would produce the desired "side effects":
private void relinquishEditing() {
// OMG this is the only way I could find to relinquish editing without aborting.
tableViewer.refresh("some element you don't have", false);
}
Sorry I can't give a more complete chunk of code, but really, I'd have to release a whole mini-project of stuff, and I'm not prepared to do that now. Hopefully this is enough of a "jumpstart" to get you going.
Here is what has worked for me:
TableViewerFocusCellManager focusCellManager = new TableViewerFocusCellManager(tableViewer,new FocusCellOwnerDrawHighlighter(tableViewer));
ColumnViewerEditorActivationStrategy actSupport = new ColumnViewerEditorActivationStrategy(tableViewer) {
protected boolean isEditorActivationEvent(ColumnViewerEditorActivationEvent event) {
return event.eventType == ColumnViewerEditorActivationEvent.TRAVERSAL
|| event.eventType == ColumnViewerEditorActivationEvent.MOUSE_DOUBLE_CLICK_SELECTION
|| (event.eventType == ColumnViewerEditorActivationEvent.KEY_PRESSED && event.keyCode == SWT.CR)
|| event.eventType == ColumnViewerEditorActivationEvent.PROGRAMMATIC;
}
};
I can navigate in all directions with tab while editing, and arrow around when not in edit mode.
I got it working based on this JFace Snippet, but I had to copy a couple of related classes also:
org.eclipse.jface.snippets.viewers.TableCursor
org.eclipse.jface.snippets.viewers.CursorCellHighlighter
org.eclipse.jface.snippets.viewers.AbstractCellCursor
and I don't remember exactly where I found them. The is also a org.eclipse.swt.custom.TableCursor, but I couldn't get that to work.
Have a look at
Example of enabling Editor Activation on a Double Click.
The stuff between lines [ 110 - 128 ] add a ColumnViewerEditorActivationStrategy and TableViewerEditor. In my case the I wanted a single click to begin editing so i changed line 115 from:
ColumnViewerEditorActivationEvent.MOUSE_DOUBLE_CLICK_SELECTION
to ColumnViewerEditorActivationEvent.MOUSE_CLICK_SELECTION. After adding this to my TableViewer, the tab key would go from field to field with the editor enabled.