Skip to content

Commit 7902eb3

Browse files
dnd: append to block and handle blank line spaces
1 parent bc448a4 commit 7902eb3

File tree

1 file changed

+26
-1
lines changed

1 file changed

+26
-1
lines changed

src/editor/codemirror/edits.ts

Lines changed: 26 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -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+
156181
const calculateNewSelection = (
157182
mainCode: string,
158183
type: CodeInsertType,

0 commit comments

Comments
 (0)