Disclaimer: I am not a JavaScript expert, and my answer may not work in all browsers. Feel free to point out any errors or ways to improve my answer so that it works in all browsers.
The RichTextArea.getFormatter().insertHTML() method calls the JavaScript executeCommand("insertHTML", ...) method, which, as I understand it, creates a node child at the current position if the parent formatting is violated. Therefore, any insertHTML method insertHTML not give the desired behavior.
Rather, you should get a text object that contains the current position, and use insertData(pos, text) to insert new text. This can be easily done by extending the RichTextArea class and adding the JSNI method.
<h / "> In the following example, I extended the RichTextArea class and added the following JSNI method:
public class CustomRichTextArea extends RichTextArea { public native void insertText(String text, int pos) ; }
The insertText method gets the text object associated with the current selection, and then inserts the text at the specified position in this text object. This code provides your desired behavior, but I only tested it in Chrome.
In addition, this method can be improved by automatically searching for the current position - getting the current position of RichTextArea is a completely different topic .
I tested the above snippet with the following entry point:
private CustomRichTextArea crta; public void onModuleLoad() { crta = new CustomRichTextArea(); crta.ensureDebugId("cwRichText-area"); crta.setSize("100%", "14em"); RichTextToolbar toolbar = new RichTextToolbar(crta); toolbar.ensureDebugId("cwRichText-toolbar"); toolbar.setWidth("100%"); Button b = new Button(); b.setText("Insert HTML"); b.addClickHandler(new ClickHandler() { @Override public void onClick(ClickEvent event) { crta.setFocus(true); crta.insertText("ASDF", ((int)crta.getText().length() / 2)); } }); Grid grid = new Grid(2, 1); grid.setStyleName("cw-RichText"); grid.setWidget(0, 0, toolbar); grid.setWidget(1, 0, crta);
Where I got the RichTextToolbar from a project in GoogleCode.