Autocomplete - insertion and replacement with enter and tab

Wondering if I can mimic the behaviour of Idea Intelij completion using codemirror :

How Idea works

I’ve the following line :

TopCount( [Member] ,50 )

The cursor is before the C of Count. The proposition returns 3 values : TopCount, TopSum and TopPercent. I choose TopSum

If I use enter the proposition is inserted → TopSumCount( [Member], 50)
If I use tab the proposition is replaces → TopSum( [Member], 50)

How to implement this in codemirror ?

I tried the pseudocode, but I can’t manage to find what xxx should be

                key: "Tab", run: (view) => {
                    const state = view.state;
                    const completionState = view.state.field(xxx);
                    
                    if (completionState?.active && completionState.active.length > 0) {
                        const active = completionState.active[0];
                        const selected = active.options[active.selected || 0];
                        if (selected) {
                            const { from, to } = active.range;
                            view.dispatch({
                                changes: { from, to, insert: selected.label },
                            });
                            closeCompletion(view); // Close the popup
                            return true;
                        }
                    }
                    return false; // Let Tab behave normally if no completion is active
                }

help welcomed

You can use selectedCompletion to get the currently selected option. But note that applying a completion is slightly more involved than what you’re doing here, and I don’t think you’ll be able to implement this behavior for completions that provide a custom apply function.

Thanks a lot, can you give me a hint how you would implement this or as default always make the substitution (I can easily add to CompletionResult the length of the substitution) ?