Placing cursor after inserting text

Hi there,

I’m able to insert some text using the following piece of code. However, I would like to set the cursor to the end of that inserted text. Currently, it stays at the beginning. Can someone give me a hint on how to do this?

function handleNewTask (view, from, to, insert) {
  console.log({ view, from, to, insert })
  if (insert === ']') {
    console.log('] found')
    if (view.state.doc.sliceString(from - 1, to) === '[') {
      const tr = view.state.update({
        changes: [
          { from, insert: ' ] ' }
        ]
      }, {
        scrollIntoView: true
      })
      view.dispatch(tr)
      return true
    }
    return false
  } else {
    return false
  }
}

export function newTask () {
  return [
    EditorView.inputHandler.of(handleNewTask)
  ]
}

Include a selection field in your transaction. Something like this:

      const tr = view.state.update({
        changes: [
          { from, insert: ' ] ' }
        ]
        selection: {anchor: from + 1},
        scrollIntoView: true
      })
2 Likes

Thanks for posting this! I was having trouble moving the cursor after changing text. Using selection in the transaction update did the trick.