react-codemirror icon indicating copy to clipboard operation
react-codemirror copied to clipboard

Format the clipboard value on Paste

Open dmtrrk opened this issue 3 years ago • 3 comments

I'm using the Code Mirror to visualize and lint a list of words for the user. My expectation is to auto-format the inserted text e.g. convert a, b, c to 3 lines of a, b and c.

I tried to use:

  1. onPaste event and clipboard.setData('text/plain', myData)
  2. prevent the default paste behavior and insert my custom text instead. But eventually selection is always points to 0, 0, there is no getCursor() interface, so I did not find how to do so
  3. I did not find the way how to replace the entire text with my formatted one (prevent onPaste, format the new text and set it)

Is there a correct approach to do that?

dmtrrk avatar Aug 19 '22 06:08 dmtrrk

@dmtrrk Here are some examples: https://github.com/uiwjs/react-markdown-editor/blob/eced98752edced4de4b17d70a0e0e7a94c6237a8/src/commands/image.tsx#L17-L28

const main = view.state.selection.main;
const txt = view.state.sliceDoc(view.state.selection.main.from, view.state.selection.main.to);
view.dispatch({
  changes: {
    from: main.from,
    to: main.to,
    insert: `![](${txt})`,
  },
  selection: EditorSelection.range(main.from + 4, main.to + 4),
  // selection: { anchor: main.from + 4 },
});

jaywcjlove avatar Aug 20 '22 03:08 jaywcjlove

@dmtrrk

cm.getCursor() → cm.state.selection.main.head

The selection, like in the previous version, consists of a number of selection ranges, one of which is considered the main selection.

cm.getCursor() → cm.state.selection.main.head

cm.listSelections() → cm.state.selection.ranges

cm.getSelection() → cm.state.sliceDoc(
  cm.state.selection.main.from,
  cm.state.selection.main.to)

cm.getSelections() → cm.state.selection.ranges.map(
  r => cm.state.sliceDoc(r.from, r.to))

cm.somethingSelected() → cm.state.selection.ranges.some(r => !r.empty)

jaywcjlove avatar Aug 20 '22 03:08 jaywcjlove

@dmtrrk You may need to find your answer here (https://discuss.codemirror.net/)

jaywcjlove avatar Aug 20 '22 03:08 jaywcjlove