Skip to content

Commit

Permalink
Autoformat keeps cursor position after Undo
Browse files Browse the repository at this point in the history
  • Loading branch information
cmaglie committed May 21, 2021
1 parent d0c0392 commit 50a55a0
Show file tree
Hide file tree
Showing 2 changed files with 16 additions and 5 deletions.
18 changes: 14 additions & 4 deletions app/src/cc/arduino/packages/formatter/clangformat/ClangFormat.java
Original file line number Diff line number Diff line change
Expand Up @@ -46,7 +46,7 @@
import processing.app.Base;
import processing.app.BaseNoGui;
import processing.app.Editor;
import processing.app.EditorTab;
import processing.app.syntax.SketchTextArea;

public class ClangFormat implements Runnable {

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

@Override
public void run() {
EditorTab tab = editor.getCurrentTab();
SketchTextArea tab = editor.getCurrentTab().getTextArea();
String originalText = tab.getText();
int cursorOffset = tab.getTextArea().getCaretPosition();
int cursorOffset = tab.getCaretPosition();
try {
FormatResult result = runClangFormatOn(originalText, cursorOffset);
if (result.FormattedText.equals(originalText)) {
editor.statusNotice(tr("No changes necessary for Auto Format."));
return;
}

// To keep cursor position after UNDO we produce a bogus edit (insertion
// and removal of a " " at cursor position) and we compound this change
// with the full auto-format update.
tab.beginAtomicEdit();
tab.insert(" ", cursorOffset);
tab.replaceRange("", cursorOffset, cursorOffset + 1);
tab.setText(result.FormattedText);
tab.getTextArea().setCaretPosition(result.Cursor);
tab.endAtomicEdit();

tab.setCaretPosition(result.Cursor);

editor.statusNotice(tr("Auto Format finished."));
} catch (IOException | InterruptedException e) {
editor.statusError("Auto format error: " + e.getMessage());
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -72,7 +72,8 @@ public void shouldSaveCaretPositionAfterAutoformat() {
String formattedText = editor.getText();
assertEquals(SOURCE_AFTER, formattedText);

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

menuEditUndo.requireEnabled();
menuEditUndo.click();
Expand Down

0 comments on commit 50a55a0

Please sign in to comment.