markdown-list-util.ts 1.3 KB

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