Sfoglia il codice sorgente

134164 able to add prefix to each line

soumaeda 2 anni fa
parent
commit
770f7c5b84

+ 17 - 12
packages/editor/src/services/codemirror-editor/use-codemirror-editor/utils/insert-prefix.ts

@@ -5,25 +5,30 @@ import { EditorView } from '@codemirror/view';
 export type InsertPrefix = (prefix: string, noSpaceIfPrefixExists?: boolean) => void;
 
 export const useInsertPrefix = (view?: EditorView): InsertPrefix => {
-
   return useCallback((prefix: string, noSpaceIfPrefixExists = false) => {
     if (view == null) {
       return;
     }
 
-    const cursorPos = view.state.selection.main.from;
+    const startPos = view.state.selection.main.from;
+    const endPos = view.state.selection.main.to;
     const space = ' ';
-    const line = view.state.doc.lineAt(cursorPos);
-    const insertText = noSpaceIfPrefixExists && line.text.startsWith(prefix) ? prefix : prefix + space;
+    const insertText = noSpaceIfPrefixExists && view.state.doc.lineAt(startPos).text.startsWith(prefix)
+      ? prefix
+      : prefix + space;
+
+    for (let i = view.state.doc.lineAt(startPos).number; i <= view.state.doc.lineAt(endPos).number; i++) {
+      const line = view.state.doc.line(i);
+
+      view.dispatch({
+        changes: {
+          from: line.from,
+          insert: insertText,
+        },
+        selection: { anchor: line.to + insertText.length },
+      });
+    }
 
-    view.dispatch({
-      changes: {
-        from: line.from,
-        insert: insertText,
-      },
-      selection: { anchor: line.to + insertText.length },
-    });
     view.focus();
   }, [view]);
-
 };