paste-markdown-util.ts 1.4 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950
  1. import type { EditorView } from '@codemirror/view';
  2. // https://regex101.com/r/r9plEA/1
  3. const indentAndMarkRE = /^(\s*)(>[> ]*|[*+-] \[[x ]\]\s|[*+-]\s|(\d+)([.)]\s))(\s*)/;
  4. // https://regex101.com/r/HFYoFN/1
  5. const indentAndMarkOnlyRE = /^(\s*)(>[> ]*|[*+-] \[[x ]\]|[*+-]|(\d+)[.)])(\s*)$/;
  6. const getBol = (editor: EditorView) => {
  7. const curPos = editor.state.selection.main.head;
  8. const aboveLine = editor.state.doc.lineAt(curPos).number;
  9. return editor.state.doc.line(aboveLine).from;
  10. };
  11. export const getStrFromBol = (editor: EditorView): string => {
  12. const curPos = editor.state.selection.main.head;
  13. return editor.state.sliceDoc(getBol(editor), curPos);
  14. };
  15. export const adjustPasteData = (strFromBol: string, text: string): string => {
  16. let adjusted = text;
  17. if (indentAndMarkOnlyRE.test(strFromBol)) {
  18. if (text.match(indentAndMarkRE)) {
  19. const matchResult = strFromBol.match(indentAndMarkRE);
  20. const indent = matchResult ? matchResult[1] : '';
  21. const lines = text.match(/[^\r\n]+/g);
  22. const replacedLines = lines?.map((line, index) => {
  23. if (index === 0 && strFromBol.match(indentAndMarkOnlyRE)) {
  24. return line.replace(indentAndMarkRE, '');
  25. }
  26. return indent + line;
  27. });
  28. adjusted = replacedLines ? replacedLines.join('\n') : '';
  29. }
  30. else {
  31. const replacedText = text.replace(/(\r\n|\r|\n)/g, `$1${strFromBol}`);
  32. adjusted = replacedText;
  33. }
  34. }
  35. return adjusted;
  36. };