gpt4 book ai didi

javascript - 如何使用 CodeMirror 强调错误?

转载 作者:行者123 更新时间:2023-11-29 16:45:53 25 4
gpt4 key购买 nike

如何在特定字符位置添加下划线波浪线到 CodeMirror

我知道要突出显示的内容的开始和结束列以及行号,但我不知道如何实际添加突出显示。

This tutorial显示了如何突出显示整行,但我只想在实际发生错误的位置下放置红色波浪线。

这是我得到的:jsbin

CodeMirror.fromTextArea(document.getElementById('grammar'), {
lineNumbers: true,
mode: 'pegjs',
})
<link rel="stylesheet" href="https://cdnjs.cloudflare.com/ajax/libs/codemirror/5.22.0/codemirror.min.css" integrity="sha384-Emjcn3QHkP2VdU4RooUiFc08IB3MxUhOIKysa338K0FaWAVuskkkLe7eNkXso/YH" crossorigin="anonymous">

<script src="https://cdnjs.cloudflare.com/ajax/libs/lodash.js/4.17.3/lodash.min.js" integrity="sha384-jsG12NEMqgAmlKLBiSdTZPy1CbxTUU2AykyyLMKaLCAIvk1bAmNXGkZ5pnJHmO/l" crossorigin="anonymous"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/codemirror/5.22.0/codemirror.min.js" integrity="sha384-hoB2ZofsVhMdfGMWAUv7PlNjtUTmqLg4WLPWTZCOFl7H/Jig3OnOutQdW7if3B0q" crossorigin="anonymous"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/codemirror/5.22.0/mode/clike/clike.min.js" integrity="sha384-8+bTF1tFTP2p6v5mvLYGHHXlsP1vvv2VZ1G9m7ItQ0h9cmnSkLjMu1MU0awC2Vnp" crossorigin="anonymous"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/codemirror/5.22.0/mode/pegjs/pegjs.min.js" integrity="sha384-ydJmJY1nFH/5/OUYmAXyo+B/XKfnymKtFz+GaYG+84yf2sWTKwnErWnSxoZc+ob7" crossorigin="anonymous"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/codemirror/5.22.0/mode/javascript/javascript.min.js" integrity="sha384-g7R5zn/n5KHtJr96K6OEZz4n/MzoKFsr9ncytZcrGoGw+xO1L1JtqjNg/zxLFEIP" crossorigin="anonymous"></script>
</head>


<textarea id="grammar">how can I highlight only "this" word?</textarea>


我尝试使用 editor.addOverlay 但似乎我们 can't get the line numbertoken 方法中,我需要知道错误在哪里。

最佳答案

完成此操作的最简单方法是使用 markText .

这是一个例子:

CodeMirror.fromTextArea(document.getElementById('grammar'), {
lineNumbers: true,
mode: 'pegjs',
}).on('change', _.throttle(editor => {
fetch('/grammar', {
method: 'POST',
body: editor.getValue(),
}).then(res => {
let contentType = res.headers.get('Content-Type');

if(/^application\/json(;|$)/.test(contentType)) {
res.json().then(data => {
clearMarks();

if(data.error) {
let loc = data.error.location;

let from = {line: loc.start.line-1, ch: loc.start.column-1 - (loc.start.offset === loc.end.offset)};
let to = {line: loc.end.line-1, ch: loc.end.column-1};

errorMarks.push(editor.markText(from, to, {className: 'syntax-error', title: data.error.message}));
}
})
} else {
clearMarks();
}
});
}, 333, {
leading: false,
trailing: true,
}));

关于javascript - 如何使用 CodeMirror 强调错误?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/41405016/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com