diff --git a/shared/editor/marks/Code.ts b/shared/editor/marks/Code.ts index 03d418a34..662399b3c 100644 --- a/shared/editor/marks/Code.ts +++ b/shared/editor/marks/Code.ts @@ -5,6 +5,7 @@ import { Node as ProsemirrorNode, Mark as ProsemirrorMark, } from "prosemirror-model"; +import { Plugin } from "prosemirror-state"; import moveLeft from "../commands/moveLeft"; import moveRight from "../commands/moveRight"; import markInputRule from "../lib/markInputRule"; @@ -59,6 +60,80 @@ export default class Code extends Mark { }; } + get plugins() { + return [ + new Plugin({ + props: { + // Typing a character inside of two backticks will wrap the character + // in an inline code mark. + handleTextInput: (view, from: number, to: number, text: string) => { + const { state } = view; + + // Prevent access out of document bounds + if (from === 0 || to === state.doc.nodeSize - 1 || text === "`") { + return false; + } + + if ( + from === to && + state.doc.textBetween(from - 1, from) === "`" && + state.doc.textBetween(to, to + 1) === "`" + ) { + const start = from - 1; + const end = to + 1; + view.dispatch( + state.tr + .delete(start, end) + .insertText(text, start) + .addMark( + start, + start + text.length, + state.schema.marks.code_inline.create() + ) + ); + return true; + } + + return false; + }, + + // Pasting a character inside of two backticks will wrap the character + // in an inline code mark. + handlePaste: (view, _event, slice) => { + const { state } = view; + const { from, to } = state.selection; + + // Prevent access out of document bounds + if (from === 0 || to === state.doc.nodeSize - 1) { + return false; + } + + const start = from - 1; + const end = to + 1; + if ( + from === to && + state.doc.textBetween(start, from) === "`" && + state.doc.textBetween(to, end) === "`" + ) { + view.dispatch( + state.tr + .replaceRange(start, end, slice) + .addMark( + start, + start + slice.size, + state.schema.marks.code_inline.create() + ) + ); + return true; + } + + return false; + }, + }, + }), + ]; + } + toMarkdown() { return { open(