paste-markdown-util.ts 1.4 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748
  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 (text.match(indentAndMarkRE)) {
  18. const matchResult = strFromBol.match(indentAndMarkRE);
  19. const indent = matchResult ? matchResult[1] : '';
  20. const lines = text.match(/[^\r\n]+/g);
  21. const replacedLines = lines?.map((line, index) => {
  22. if (index === 0 && strFromBol.match(indentAndMarkOnlyRE)) {
  23. return line.replace(indentAndMarkRE, '');
  24. }
  25. return indent + line;
  26. });
  27. adjusted = replacedLines ? replacedLines.join('\n') : '';
  28. }
  29. else if (strFromBol.match(indentAndMarkRE)) {
  30. const replacedText = text.replace(/(\r\n|\r|\n)/g, `$1${strFromBol}`);
  31. adjusted = replacedText;
  32. }
  33. return adjusted;
  34. };