Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

fix issue with code pasting from VS Code when at the last line of code #5106

Merged
merged 1 commit into from
Apr 30, 2024
Merged
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
11 changes: 9 additions & 2 deletions packages/extension-code-block/src/code-block.ts
Original file line number Diff line number Diff line change
Expand Up @@ -260,8 +260,15 @@ export const CodeBlock = Node.create<CodeBlockOptions>({

const { tr } = view.state

// create an empty code block
tr.replaceSelectionWith(this.type.create({ language }))
// create an empty code block´
// if the cursor is at the absolute end of the document, insert the code block before the cursor instead
// of replacing the selection as the replaceSelectionWith function will cause the insertion to
// happen at the previous node
if (view.state.selection.from === view.state.doc.nodeSize - (1 + (view.state.selection.$to.depth * 2))) {
Copy link
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

I'm not going to pretend that I completely understand this. What is tripping me up is the * 2.

But otherwise this looks right

Copy link
Member Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

The 2 is the offset of a prosemirror node to the next one. If you for example have a nested node - the wrapping node will always add an offset of 1 at the beginning and the end which you have to account for if you want to find the correct position after said node.

tr.insert(view.state.selection.from - 1, this.type.create({ language }))
} else {
tr.replaceSelectionWith(this.type.create({ language }))
}

// put cursor inside the newly created code block
tr.setSelection(TextSelection.near(tr.doc.resolve(Math.max(0, tr.selection.from - 2))))
Expand Down