Skip to content

Commit 9ed9efa

Browse files
committed
refactor: Make the code a little safer: ensure we don't reference past end of file
I have been unable to make the previous implementation fail, but this seems safer - albeit at the expense of complexity.
1 parent b7b11b2 commit 9ed9efa

File tree

1 file changed

+10
-5
lines changed

1 file changed

+10
-5
lines changed

src/Commands/ToggleDone.ts

Lines changed: 10 additions & 5 deletions
Original file line numberDiff line numberDiff line change
@@ -42,11 +42,16 @@ export const toggleDone = (checking: boolean, editor: Editor, view: MarkdownView
4242
} else {
4343
// https://github.com/obsidian-tasks-group/obsidian-tasks/issues/3342
4444
// If insertion.text is empty, delete the line instead, so we don't leave a trailing end-of-line character around.
45-
// This behaves gracefully even if there is no end-of-line character on the last line in the file.
46-
const from = { line: lineNumber, ch: 0 };
47-
const to = { line: lineNumber + 1, ch: 0 };
48-
// console.log(`Deleting line+EOL "${editor.getRange(from, to)}", because insertion.text is empty.`);
49-
editor.replaceRange('', from, to);
45+
if (lineNumber < editor.lineCount() - 1) {
46+
const from = { line: lineNumber, ch: 0 };
47+
const to = { line: lineNumber + 1, ch: 0 };
48+
// console.log(`Deleting line+EOL "${editor.getRange(from, to)}", because insertion.text is empty.`);
49+
editor.replaceRange('', from, to);
50+
} else {
51+
// There is no end-of-line character on our line, which is the last line in the file.
52+
// console.log(`Deleting line "${editor.getLine(lineNumber)}", because insertion.text is empty.`);
53+
editor.setLine(lineNumber, insertion.text);
54+
}
5055
}
5156

5257
/* Cursor positions are 0-based for both "line" and "ch" offsets.

0 commit comments

Comments
 (0)