From 7b1c576eb707831e4752f8884ebb9539f95c80cf Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?V=C3=ADctor=20Losada=20Hern=C3=A1ndez?= Date: Sun, 27 Sep 2026 22:58:08 +0200 Subject: [PATCH] wrapselection to work with foreachselection --- .../codeEditor/extensions/customKeyMaps.js | 108 ++++++++---------- 1 file changed, 47 insertions(+), 61 deletions(-) diff --git a/client/components/codeEditor/extensions/customKeyMaps.js b/client/components/codeEditor/extensions/customKeyMaps.js index d8c4edcce..8c904f7e7 100644 --- a/client/components/codeEditor/extensions/customKeyMaps.js +++ b/client/components/codeEditor/extensions/customKeyMaps.js @@ -97,72 +97,58 @@ const insertTab = (view)=>{ return true; }; -const wrapSelection = (prefix, suffix)=>(view)=>{ - view.dispatch( - view.state.changeByRange((range)=>{ - const { from, to } = range; - const noSelection = from === to; +const wrapSelection = (prefix, suffix)=>(view)=>forEachSelection( + view, + (state, range)=>{ + const { from, to } = range; + const noSelection = from === to; + const selected = state.doc.sliceString(from, to); - const doc = view.state.doc; - - if(noSelection) { - return { - changes : { - from, - to, - insert : prefix + suffix - }, - range : EditorSelection.cursor(from + prefix.length) - }; - } - - const before = doc.sliceString( - Math.max(0, from), - from + prefix.length - ); - - const after = doc.sliceString( - to - suffix.length, - to - ); - const alreadyWrapped = before === prefix && after === suffix; - if(alreadyWrapped) { - return { - changes : [ - { - from : from, - to : from + prefix.length, - insert : '' - }, - { - from : to - suffix.length, - to : to, - insert : '' - } - ], - range : EditorSelection.range( - from, - to - prefix.length - suffix.length, - ) - }; - } + if(noSelection) { + const insert = prefix + suffix; return { - changes : { - from, - to, - insert : prefix + doc.sliceString(from, to) + suffix - }, - range : EditorSelection.range( - from, - to + suffix.length + prefix.length - ) + changes : { from, to, insert }, + range : EditorSelection.cursor(from + prefix.length) }; - }) - ); + } + + const hasWrapper = + selected.startsWith(prefix) && + selected.endsWith(suffix); + + if(hasWrapper) { + return { + changes : [ + { + from : to - suffix.length, + to, + insert : '' + }, + { + from, + to : from + prefix.length, + insert : '' + } + ], + range : EditorSelection.range(from, to - prefix.length - suffix.length) + }; + } + + return { + changes : { + from, + to, + insert : prefix + selected + suffix + }, + range : EditorSelection.range( + from, + to + prefix.length + suffix.length + ) + }; + } +); - return true; -}; const makeNbsp = (view)=>forEachSelection(view, (state, range)=>{ const { from, to } = range;