How to select whole words?

Hi,

I just discovered tiptap and prosemirror et it looks amazing. I would like to ensure that whatever the selection from the user, it gets expanded to whole words, as if he/she had double clicked.

I have discovered the handler createSelectionBetween but I haven’t been able to change the selection (even by just adding 2 to the anchor and to the head).

Here’s my event handler function (using tiptap editor object): createSelectionBetween(view, anchor, head) { // console.log(“view”, view); console.log(“createSelectionBetween - anchor”, anchor.pos); console.log(“createSelectionBetween - head”, head.pos);

  const { state } = this.editor;
  const from = anchor.pos - 2;
  const to = head.pos + 3;

  const text = state.doc.textBetween(from, to, " ");
  console.log("editor text", from, to, text);

  this.editor.setSelection(from, to);
  this.editor.focus();
}

What do you think I should do or use?

Thanks, Laurent

From a user experience perspective, that sounds like a somewhat bad idea, in that it violates the expectations that people have for this type of editor.

But if you really want to do it, I guess directly handling the mouse events would work (I assume you don’t want to do this for keyboard selection changes).

Hi Marijn,

Thanks for your comment. My use case is about tagging named entities which need to be whole words. That’s why I was asking how I could expand the selection to the beginning and to the end of the words within the selection.

I’ve been able to catch the mouse events (handleClick, handleClickOn, …) but not to change the selection the user made. Any clues on how to do it?

Thanks Laurent

I just understood your hint and thanks a lot as it worked as advised. I used handleDOMEvents() with a ‘mouseup’ event and it worked. Tiptap has a helper function to change the selection.

handleMouseUp(view) {
  console.log("Mouse UP!");
  console.log(
    "view.state.selection",
    view.state.selection.$anchor.pos,
    "-->",
    view.state.selection.$head.pos
  );
  const from = view.state.selection.$anchor.pos;
  const to = view.state.selection.$head.pos;
  const doc = view.state.doc;
  const text = doc.textBetween(from - 2, to + 3, " ");
  console.log("editor text", from, to, text);
  this.editor.setSelection(from - 2, to + 3);
}

Hi,

Thanks for your comment.

The editor would be used for entity tagging and I don’t want the user to tag chunks of words. That’s why I would prefer to automatically extend the user’s selection to the start or end of the word(s) that were selected.

I’ve caught the handleClick and handleClickOn events but I haven’t been able to do is to change the text selection. Should it be done in a plugin?