Hi, I am trying to create a markInputRule(regex, markType)
function, which is symmetrical to textblockTypeInputRule
but for marks instead of nodes (this doesn’t address the initial question but the latest comment just above).
The steps would be:
- set current selection to the content wrapped into “**”
- replace the selection to same text without “**”
- apply relevant mark
function markInputRule(regex: RegExp, markType: MarkType) {
return new InputRule(regex, (state, match, start, end) => {
const tr = state.tr
const anchor = state.doc.resolve(start)
const head = state.doc.resolve(end)
tr.setSelection(new TextSelection(anchor, head))
// real code is a tad more complex:
// I reuse logic from the toggleMark command
tr.addStoredMark(markType.create({}))
return tr
})
It doesn’t work as I would expect, only the selection part seems to work. I will update if I manage to setup something.
Edit: this seems better:
function markInputRule(regex: RegExp, markType: MarkType) {
return new InputRule(regex, (state, match, start, end) => {
const tr = state.tr
const markedText = schema.text(match[1], [markType.create({})])
tr.replaceWith(start, end, markedText)
return tr
})
}
The problem with toggleMark
internal logic is that it relies a lot on the current selection, but you might not want to alter this selection to apply new marks, instead you’ll want to use the matched position.
New update:
This seems actually a bad idea to have such a generic pattern. The problem is that you will hit issues when writing the regex:
- the regex should contain only the content you want to replace
- but you also want to differentiate “*foobar” (should not match, it’s a non-finished bold text) from “foobar” (should match and become italic) => to achieve that you have to check the characters before the content you want to match, which makes things messy.
I ended up writing a rule specific to each kind of mark I want to apply, with regex accepting a varying number of separators, for example /(-{1,3})([^-]+)(-{1,3})/
, and I check the number of matched separators within the input rule.