@@ -67,13 +67,27 @@ function isSuggestWidgetVisible(editor: MonacoEditorInstance): boolean {
6767 ) ;
6868}
6969
70+ /** Replace all editor content via executeEdits (preserves undo stack). */
71+ function replaceAllContent (
72+ editor : MonacoEditorInstance ,
73+ newText : string ,
74+ source : string
75+ ) {
76+ const model = editor . getModel ( ) ;
77+ if ( ! model ) return ;
78+ const fullRange = model . getFullModelRange ( ) ;
79+ editor . executeEdits ( source , [
80+ { range : fullRange , text : newText , forceMoveMarkers : true } ,
81+ ] ) ;
82+ }
83+
7084function reformatIfValid (
7185 editor : MonacoEditorInstance ,
7286 handleJsonChange : ( text : string ) => void
7387) {
7488 try {
7589 const formatted = JSON . stringify ( JSON . parse ( editor . getValue ( ) ) , null , 2 ) ;
76- editor . setValue ( formatted ) ;
90+ replaceAllContent ( editor , formatted , 'reformat' ) ;
7791 handleJsonChange ( formatted ) ;
7892 } catch {
7993 handleJsonChange ( editor . getValue ( ) ) ;
@@ -161,12 +175,12 @@ export const JsonEditorView = ({
161175 try {
162176 const formatted = JSON . stringify ( JSON . parse ( commaFixed ) , null , 2 ) ;
163177 if ( formatted !== text ) {
164- editor . setValue ( formatted ) ;
178+ replaceAllContent ( editor , formatted , 'format' ) ;
165179 handleJsonChange ( formatted ) ;
166180 }
167181 } catch {
168182 if ( commaFixed !== text ) {
169- editor . setValue ( commaFixed ) ;
183+ replaceAllContent ( editor , commaFixed , 'comma-fix' ) ;
170184 handleJsonChange ( commaFixed ) ;
171185 }
172186 editor . getAction ( 'editor.action.formatDocument' ) ?. run ( ) ;
@@ -309,23 +323,17 @@ export const JsonEditorView = ({
309323 const current = editor . getValue ( ) ;
310324 const commaFixed = fixJsonCommas ( current ) ;
311325
312- // Try to reformat if valid (catches code action insertions too)
313326 try {
314327 const formatted = JSON . stringify ( JSON . parse ( commaFixed ) , null , 2 ) ;
315328 if ( formatted !== current ) {
316329 isProgrammaticEdit = true ;
317- const pos = editor . getPosition ( ) ;
318- editor . setValue ( formatted ) ;
319- if ( pos ) editor . setPosition ( pos ) ;
330+ replaceAllContent ( editor , formatted , 'auto-reformat' ) ;
320331 handleJsonChange ( formatted ) ;
321332 }
322333 } catch {
323- // JSON still invalid — just apply comma fixes if any
324334 if ( commaFixed !== current ) {
325335 isProgrammaticEdit = true ;
326- const pos = editor . getPosition ( ) ;
327- editor . setValue ( commaFixed ) ;
328- if ( pos ) editor . setPosition ( pos ) ;
336+ replaceAllContent ( editor , commaFixed , 'auto-comma-fix' ) ;
329337 handleJsonChange ( commaFixed ) ;
330338 }
331339 }
0 commit comments