insert text at current cursor position

Hello,

I want to insert a character at the current cursor position. I am using the following code:

const transaction = view.state.update({
    changes: {
      from: , // get current cursor position ??
      insert: text,
    },
  });

  if (transaction) {
    view.dispatch(transaction);
  }

Here, how do I get the current cursor position value to feed in the ‘from’ of changes object?

I found the answer in the documentation.
Here is the full code -

const cursor = view.state.selection.main.head;
  const transaction =view.state.update({
    changes: {
      from: cursor,
      insert: text,
    },
    // the next 2 lines will set the appropriate cursor position after inserting the new text.
    selection: { anchor: cursor + 1 },
    scrollIntoView: true,
  });

  if (transaction) {
   view.dispatch(transaction);
  }
1 Like