Skip to content
This commit does not belong to any branch on this repository, and may belong to a fork outside of the repository.

Commit 50a55a0

Browse files
committedMay 21, 2021
Autoformat keeps cursor position after Undo
1 parent d0c0392 commit 50a55a0

File tree

2 files changed

+16
-5
lines changed

2 files changed

+16
-5
lines changed
 

‎app/src/cc/arduino/packages/formatter/clangformat/ClangFormat.java

+14-4
Original file line numberDiff line numberDiff line change
@@ -46,7 +46,7 @@
4646
import processing.app.Base;
4747
import processing.app.BaseNoGui;
4848
import processing.app.Editor;
49-
import processing.app.EditorTab;
49+
import processing.app.syntax.SketchTextArea;
5050

5151
public class ClangFormat implements Runnable {
5252

@@ -60,17 +60,27 @@ public ClangFormat(Editor editor) {
6060

6161
@Override
6262
public void run() {
63-
EditorTab tab = editor.getCurrentTab();
63+
SketchTextArea tab = editor.getCurrentTab().getTextArea();
6464
String originalText = tab.getText();
65-
int cursorOffset = tab.getTextArea().getCaretPosition();
65+
int cursorOffset = tab.getCaretPosition();
6666
try {
6767
FormatResult result = runClangFormatOn(originalText, cursorOffset);
6868
if (result.FormattedText.equals(originalText)) {
6969
editor.statusNotice(tr("No changes necessary for Auto Format."));
7070
return;
7171
}
72+
73+
// To keep cursor position after UNDO we produce a bogus edit (insertion
74+
// and removal of a " " at cursor position) and we compound this change
75+
// with the full auto-format update.
76+
tab.beginAtomicEdit();
77+
tab.insert(" ", cursorOffset);
78+
tab.replaceRange("", cursorOffset, cursorOffset + 1);
7279
tab.setText(result.FormattedText);
73-
tab.getTextArea().setCaretPosition(result.Cursor);
80+
tab.endAtomicEdit();
81+
82+
tab.setCaretPosition(result.Cursor);
83+
7484
editor.statusNotice(tr("Auto Format finished."));
7585
} catch (IOException | InterruptedException e) {
7686
editor.statusError("Auto format error: " + e.getMessage());

‎app/test/processing/app/AutoformatProducesOneUndoActionTest.java

+2-1
Original file line numberDiff line numberDiff line change
@@ -72,7 +72,8 @@ public void shouldSaveCaretPositionAfterAutoformat() {
7272
String formattedText = editor.getText();
7373
assertEquals(SOURCE_AFTER, formattedText);
7474

75-
assertEquals(29, editor.getCaretPosition());
75+
// Autoformat with clang-format keeps cursor relative to source code
76+
assertEquals(17, editor.getCaretPosition());
7677

7778
menuEditUndo.requireEnabled();
7879
menuEditUndo.click();

0 commit comments

Comments
 (0)
Please sign in to comment.