Programmatically selecting the entire document

Hi,

I’m trying to select the entire document, programmatically. The following rather simple Javascript code does not work:

var sel = new TextSelection(0, pm.doc.nodeSize);
pm.setSelection(sel);

The second argument to the TextSelection constructor is probably at fault: how do I get the last position in the document?

Thanks!

A text selection has to start and end in text positions, i.e. inside textblocks. So 0 isn’t one, and doc.nodeSize isn’t even a valid position. In 0.11.0, you can use Selection.between(doc.resolve(0), doc.resolve(pm.doc.content.size)), but it appears that you’re using 0.10.0 or older.

Okay, I guess I better move to the new version.

I just tried to clone the git repo, and install it (so far so good), but it is not clear how to build a distribution from there (with ES5-compiled code). Is that described somewhere?

If you don’t want to hack on the editor itself, just install the prosemirror-* NPM modules that you need. Or use prosemirror-prebuilt for an easy start.

Ok, thanks, I’m now beginning to use the new version of the code.

I’m now using the new version of prosemirror, but I’m still having problems wrapping my head around the problem of setting the selection to the entire document.

The following does not work (but why?):

view.props.onAction(view.state.tr.setSelection(prosemirror_state.TextSelection.create(view.state.doc, 0, 10)));

Also, what should I replace 10 by to select the full document? Should that be view.state.doc.content.size?

Thanks in advance.

You want

let doc = view.state.doc
let sel = Selection.between(doc.resolve(0), doc.resolve(doc.content.size))
view.props.onAction(sel.action())
1 Like

Thanks, that works!

It did, for a moment. But in 0.17 it’s written differently:

let doc = view.state.doc
let sel = Selection.between(doc.resolve(0), doc.resolve(doc.content.size))
view.dispatch(view.state.tr.setSelection(sel))