Position caret= new Position(insertionOffset, 0);
document.addPosition(caret);
st.setSelectionRange(widgetInsertionOffset, 0);
// operate directly on the widget
st.replaceTextRange(widgetInsertionOffset, 0, st.getLineDelimiter());
// restore caret unless an auto-indenter has already moved the caret
// then leave it alone
document.removePosition(caret);
if (updateCaret && st.getSelection().x == widgetInsertionOffset) {