Find beginning and end of document

I’m curious about how to accomplish the following:

  • given a state, find out if the selection is at the beginning or end of the document
  • given a state, find out whether the entire document is selected
  • create a selection for the entirety of the document
  • replace the contents of the whole document.

My attempts at resolving state.doc.nodeSize have failed… since PM throws an ‘out of range’ error.

You can use Selection.atStart and atEnd to get the first and last valid selection positions, and compare those to a given selection. There’s a special selection class for whole-document selections, though you only get that when you press Ctrl/Cmd-A – if you shift- or drag-select over the document, you’ll get a regular text selection that covers the given range (and won’t cover leaf block nodes at the start or end of the document, if any exist, because they aren’t spannable by text positions).

If you’re programatically replacing the contents of the whole document, maybe what you really want is to create a new document and state. Though you can also do a replace from 0 to doc.content.size with a given slice. doc.nodeSize isn’t a meaningful number – the document spans the content of the doc node, so the whole size of that node is bigger than the document.