简体   繁体   中英

How to get the text value of a CodeMirror-6 editor

I'm playing with CodeMirror to check if I can use it in our site to allow the user to write c# scripts. I can made a sample easily but I can't find any documentation nabout to get the text value of the editor to send through a form post.

JS Source:

import {StreamLanguage} from "@codemirror/language"
import {csharp} from "@codemirror/legacy-modes/mode/clike"

import {EditorView, basicSetup} from "codemirror"

let editor = new EditorView({
  extensions: [basicSetup, StreamLanguage.define(csharp)],
  parent: document.getElementById('_formengine_script')
})

index.html:

<!doctype html>
<meta charset=utf8>
<h1>CodeMirror!</h1>
<div id="_formengine_script"></div>
<script src="editor.bundle.js"></script>

I think that there must be various ways to solve it but I can't any of them. I've found a lot of information on CodeVersion 5, but I would prefer to use the latest version.

Ran into the same problem. The codemirror 6 documentation is odd. It contains lots of deep dives but lacks of the basics.

I ended up looking into the unit tests rather than the documentation. You find there a nice test in the history module , the test changes the document and then checks if the document contains the expected data.

Based on this you endup with the following:

editor.state.doc.toString();

Update: Just after writing this I stumbled upon https://codemirror.net/docs/migration/ just go there to the "Getting the Document and Selection" chapter. It contains the examples your searched for.

Editor allows to mark more than one selection range at once (example below) 在此处输入图像描述

You can get all of the selected ranges using this piece of code

editor.state.selection.ranges

Here an example how to get first selected text from all ranges.

let firstRange = editor.state.selection.ranges.at(0);
let selectedText = editor.state.doc.toString().substring(firstRange.from,firstRange.to)
console.log(selectedText); //output: 'ECT * FR'

The multimode selection can be disabled, but the way which you access the selected range stay the same.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM