4646import processing .app .Base ;
4747import processing .app .BaseNoGui ;
4848import processing .app .Editor ;
49- import processing .app .EditorTab ;
49+ import processing .app .syntax . SketchTextArea ;
5050
5151public 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 ());
0 commit comments