@@ -112,6 +112,21 @@ export const calculateChanges = (
112112 } else {
113113 mainFrom = state . doc . line ( line ) . from ;
114114 }
115+ // Determine if code is being appended to previous block and indent accordingly.
116+ const previousLineNum = line - 1 ;
117+ if ( previousLineNum >= 1 && previousLineNum <= state . doc . lines ) {
118+ const previousLine = state . doc . line ( previousLineNum ) ;
119+ const currentLineIsBlank = lineIsBlank ( state , line ) ;
120+ const previousLineIsBlank = lineIsBlank ( state , previousLineNum ) ;
121+ mainIndent =
122+ ! previousLineIsBlank && currentLineIsBlank
123+ ? previousLine . text . match ( / ^ ( \s * ) / ) ?. [ 0 ] ?? ""
124+ : "" ;
125+ // Special case where body code does not yet exist but should be indented.
126+ if ( previousLine . text . trim ( ) . endsWith ( ":" ) && currentLineIsBlank ) {
127+ mainIndent += " " ;
128+ }
129+ }
115130 }
116131 } else {
117132 // When no line is specified, insert before the code (not just after the imports).
@@ -126,7 +141,7 @@ export const calculateChanges = (
126141 ) {
127142 mainCode = removeCommonIndent ( mainCode . slice ( whileTrueLine . length ) ) ;
128143 }
129- mainIndent = insertLine . text . match ( / ^ ( \s * ) / ) ?. [ 0 ] ?? "" ;
144+ mainIndent + = insertLine . text . match ( / ^ ( \s * ) / ) ?. [ 0 ] ?? "" ;
130145 mainChange = {
131146 from : mainFrom ,
132147 insert : mainPreceedingWhitespace + indentBy ( mainCode , mainIndent ) + "\n" ,
@@ -153,6 +168,16 @@ export const calculateChanges = (
153168 } ) ;
154169} ;
155170
171+ /**
172+ * Determines if the line contains any code.
173+ */
174+ const lineIsBlank = ( state : EditorState , line : number ) : boolean => {
175+ if ( line <= state . doc . lines ) {
176+ return state . doc . line ( line ) . text . trim ( ) === "" ;
177+ }
178+ return false ;
179+ } ;
180+
156181const calculateNewSelection = (
157182 mainCode : string ,
158183 type : CodeInsertType ,
0 commit comments