|
47 | 47 | import javax.swing.text.PlainDocument;
|
48 | 48 | import javax.swing.undo.UndoManager;
|
49 | 49 | import javax.swing.text.DefaultCaret;
|
| 50 | +import javax.swing.text.Document; |
50 | 51 |
|
51 | 52 | import org.fife.ui.rsyntaxtextarea.RSyntaxDocument;
|
52 | 53 | import org.fife.ui.rsyntaxtextarea.RSyntaxTextAreaEditorKit;
|
@@ -390,11 +391,32 @@ public void setText(String what) {
|
390 | 391 | // its absolute position (number of characters from the start), which isn't
|
391 | 392 | // always perfect, but the best we can do without making a diff of the old
|
392 | 393 | // 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. |
393 | 400 | DefaultCaret caret = (DefaultCaret) textarea.getCaret();
|
394 | 401 | int policy = caret.getUpdatePolicy();
|
395 | 402 | 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 | + } |
398 | 420 | }
|
399 | 421 |
|
400 | 422 | /**
|
|
0 commit comments