@uiw/react-codemirror widget text selection not working correctly
03:34 07 Oct 2026

Currently:

enter image description here

What I want:
enter image description here

Code:

import debounce from "lodash/debounce";
import { placeholder } from '@codemirror/view';
import { html } from '@codemirror/lang-html';
import { StateField, StateEffect } from '@codemirror/state';
import { ViewPlugin, MatchDecorator, EditorView, Decoration, ViewUpdate, WidgetType, keymap } from "@codemirror/view";



class CustomMatchWidget extends WidgetType {
    constructor(text) {
        super();
        this.text = text; // The full string matched by the regex
    }

    // CodeMirror relies on this to determine if it should re-render the widget
    eq(other) {
        return other.text === this.text;
    }

    toDOM(view) {

        // Outer wrap span for the entire match
        const outerSpan = document.createElement('span');
        outerSpan.className = 'cm-match-wrapper';
        outerSpan.style.cursor = 'pointer';

        // Attach your custom click event handler
        outerSpan.onclick = (event) => {
            event.preventDefault();
            console.log('Match clicked:', this.text);

            // Optional: Perform editor mutations here, e.g., getting the position:
            // const pos = view.posAtDOM(outerSpan);
        };

        // Parse the matched text to separate asterisks from regular text
        // Example regex splitting elements while keeping the delimiters like asterisks
        const segments = this.text.split(/(\*+)/);

        segments.forEach((segment) => {
            if (!segment) return;

            const innerSpan = document.createElement('span');

            if (segment.includes('*')) {
                // Wrap asterisks inside their own specific span
                innerSpan.className = 'cm-match-asterisk';
                innerSpan.textContent = segment;
                innerSpan.style.color = 'red'; // Visual example styling
            } else {
                // Wrap the regular content inside its own span
                innerSpan.className = 'cm-match-text';
                innerSpan.textContent = segment;
            }

            outerSpan.appendChild(innerSpan);
        });


        // // 2. Add the double-click event listener
        // outerSpan.addEventListener("dblclick", (event) => {
        //
        //     // Prevent CodeMirror's default selection/focus handling
        //     event.preventDefault();
        //     event.stopPropagation();
        //
        //     const selection = window.getSelection();
        //
        //     if (selection) {
        //         const range = document.createRange();
        //
        //         // Select everything inside your wrapper element
        //         range.selectNodeContents(outerSpan);
        //
        //         console.log("thiss2 called: ", range)
        //
        //         selection.removeAllRanges();
        //         selection.addRange(range);
        //     }
        // });

        return outerSpan;
    }

    // // Ensure the editor treats the wrapped text as an atomic unit when navigating
    // ignoreEvent() {
    //     return false;
    // }


    // // Intercept the interaction loop
    // ignoreEvent(event) {
    //     // Check if the event is a drag/selection action trying to compromise boundaries
    //     if (event.type === 'mousedown' || event.type === 'dragstart') {
    //         // Return false to let CodeMirror's custom event handlers gracefully capture
    //         // the intent rather than passing partial selection coordinates down to DOM elements
    //         return false;
    //     }
    //     return true; // Ignore other standard typing inputs
    // }


    // // CRITICAL: Tells CodeMirror not to ignore editor mouse actions over this widget
    // ignoreEvent(event) {
    //     // If it's a mouse selection action, don't ignore it—let CodeMirror handle the drag
    //     if (event instanceof MouseEvent) {
    //         return false;
    //     }
    //     // For input, paste, or drop events inside an interactive widget (e.g. inputs),
    //     // you might want to return true to keep the widget's native behavior intact.
    //     return true;
    // }


    // CRITICAL: Prevent CodeMirror from hijacking native selection
    ignoreEvent(event) {

        // // Keep internal text interactions alive
        // if (
        //     event.type === "mousedown" ||
        //     event.type === "mousemove" ||
        //     event.type === "mouseup" ||
        //     event.type === "dragstart"
        // ) {
        //     return false;
        // }

        return false; // Let CodeMirror handle default hotkeys/history
    }

}





const customMatchDecorator = new MatchDecorator({
    // Matches text framed by asterisks (e.g., *text* or **text**)
    regexp: /\*+[^*]+\*+/g,
    decoration: (match) => {
        return Decoration.replace({
            widget: new CustomMatchWidget(match[0]),
        });
    },
});





const customMatchPlugin = ViewPlugin.fromClass(
    class {
        constructor(view) {
            this.decorations = customMatchDecorator.createDeco(view);
        }
        update(update) {
            this.decorations = customMatchDecorator.updateDeco(update, this.decorations);
        }
    },
    {
        decorations: (instance) => instance.decorations,
    }
);





 {
        debouncedOnChange(value);
    }}
    onCreateEditor={handleCreateEditor}
    onUpdate={handleUpdate}
    theme={"none"}
    basicSetup={{
        lineNumbers: false,     
        foldGutter: false,       
        highlightActiveLineGutter: false,
        highlightActiveLine: false, 
        highlightSelectionMatches: false,
        dropCursor: true
    }}
    extensions={[
        EditorView.lineWrapping,
        EditorView.theme({
            "&": {
                outline: "none",
                display: "inline-flex !important",
                width: "100%"
            },
            '&.cm-focused': {
                outline: 'none',
            },
        
            ".cm-scroller": {
                fontFamily: "inherit",
                fontSize: ".9375rem",
                lineHeight: "22px",
                maxHeight: "calc(5 * 22px)",
                overflowY: "auto",
                overscrollBehavior: "contain",
                scrollBehavior: "auto",
                transform: "translateZ(0)",
                willChange: "scroll-position"
            },
        
            ".cm-scroller::-webkit-scrollbar": {
                blockSize: "4px",
                inlineSize: "4px"
            },
        
            ".cm-scroller::-webkit-scrollbar-track": {
                background: "transparent"
            },
        
            ".cm-scroller::-webkit-scrollbar-thumb": {
                backgroundColor: "rgba(47, 43, 61, .1)",
                borderRadius: "3px"
            },
        
            ".cm-content": {
                caretColor: "rgb(47, 43, 61)",
                minHeight: "calc(1 * 22px)",
                padding: 0
            },
            ".cm-gutters": {
                display: "none !important"
            }, // Ensures all margins are gone
        
            // Unfocused or general selection background
            '::selection': {
                backgroundColor: '#3062c6 !important',
                color: '#fff !important',
            },
        
            ".cm-match-wrapper ::selection, .cm-match-wrapper::selection": {
                backgroundColor: '#3062c6 !important',
                color: '#fff !important',
            },
        
            // Unfocused or general selection background
            '.cm-selectionBackground, ::selection': {
                backgroundColor: '#3062c6 !important',
                color: '#fff !important',
            },
        
            '.cm-placeholder': {
                pointerEvents: "none",
                color: "#888",
                display: "inline-block",
                verticalAlign: "top"
            },
        
            ".wa-bold": {
                fontWeight: 700
            },
        
            ':is(.cm-widgetBuffer:has(+ .my-widget), .my-widget + .cm-widgetBuffer)': {
                display: 'none'
            },
        
            '.custom-wrapped-highlight': {
                backgroundColor: '#ffec3d',
                padding: '0 2px'
            },
        
            ".cm-widgetBuffer": {
        
            },
        
            ".cm-match-wrapper": {
                userSelect: "text !important",
                WebkitUserSelect: "text !important",
                cursor: "text !important"
            },
        
            ".cm-match-wrapper *": {
                userSelect: "text !important",
                WebkitUserSelect: "text !important"
            },
        
            ".ͼ4 .cm-line ::selection": {
                backgroundColor: "purple !important"
            },
        
            ".ͼ4 .cm-line::selection": {
                backgroundColor: "purple !important"
            }
        
        }),
        placeholder('Type a message...'),
        html(),
        customMatchPlugin,
    ]}
/>

HTML Comparison:

React:

enter image description here

Vue:

enter image description here

Seems:

@uiw/react-codemirror is full of bugs and limitation

It is impossible to achieve the simple wrapping like in Vue because @uiw/react-codemirror Decorator only supports wrapping a single element around the match

and Widget is full of bugs like the text selection bug above

I have tried many solutions offered from google AI search and none worked

reactjs next.js react-codemirror