Skip to content

Commit 6d7e6b8

Browse files
TOMERGE: Fix EditorTab.setText
Turns out the approached used to keep caret and scroll position only keeps the scroll position. More code is needed to also keep caret position.
1 parent 16195bb commit 6d7e6b8

File tree

1 file changed

+24
-2
lines changed

1 file changed

+24
-2
lines changed

app/src/processing/app/EditorTab.java

+24-2
Original file line numberDiff line numberDiff line change
@@ -47,6 +47,7 @@
4747
import javax.swing.text.PlainDocument;
4848
import javax.swing.undo.UndoManager;
4949
import javax.swing.text.DefaultCaret;
50+
import javax.swing.text.Document;
5051

5152
import org.fife.ui.rsyntaxtextarea.RSyntaxDocument;
5253
import org.fife.ui.rsyntaxtextarea.RSyntaxTextAreaEditorKit;
@@ -390,11 +391,32 @@ public void setText(String what) {
390391
// its absolute position (number of characters from the start), which isn't
391392
// always perfect, but the best we can do without making a diff of the old
392393
// and new text and some guesswork.
394+
// Note that we cannot use textarea.setText() here, since that first removes
395+
// text and then inserts the new text. Even with NEVER_UPDATE, the caret
396+
// always makes sure to stay valid, so first removing all text makes it
397+
// reset to 0. Also note that simply saving and restoring the caret position
398+
// will work, but then the scroll position might change in response to the
399+
// caret position.
393400
DefaultCaret caret = (DefaultCaret) textarea.getCaret();
394401
int policy = caret.getUpdatePolicy();
395402
caret.setUpdatePolicy(DefaultCaret.NEVER_UPDATE);
396-
textarea.setText(what);
397-
caret.setUpdatePolicy(policy);
403+
try {
404+
RSyntaxDocument doc = (RSyntaxDocument)textarea.getDocument();
405+
int oldLength = doc.getLength();
406+
// The undo manager already seems to group the insert and remove together
407+
// automatically, but better be explicit about it.
408+
textarea.getUndoManager().beginInternalAtomicEdit();
409+
try {
410+
doc.insertString(oldLength, what, null);
411+
doc.remove(0, oldLength);
412+
} catch (BadLocationException e) {
413+
System.err.println("Unexpected failure replacing text");
414+
} finally {
415+
textarea.getUndoManager().endInternalAtomicEdit();
416+
}
417+
} finally {
418+
caret.setUpdatePolicy(policy);
419+
}
398420
}
399421

400422
/**

0 commit comments

Comments
 (0)