简体   繁体   English

如何获取CodeMirror-6编辑器的文本值

[英]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.我正在玩 CodeMirror 来检查我是否可以在我们的站点中使用它来允许用户编写 c# 脚本。 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: JS来源:

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:索引.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.我找到了很多关于 CodeVersion 5 的信息,但我更愿意使用最新版本。

Ran into the same problem.遇到同样的问题。 The codemirror 6 documentation is odd. codemirror 6 文档很奇怪。 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.更新:就在写完这篇文章后,我偶然发现了https://codemirror.net/docs/migration/只是去“获取文档和选择”一章。 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.可以禁用多模式选择,但访问所选范围的方式保持不变。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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