如何使用CodeMirror强调错误?

时间:2016-12-31 02:52:56

标签: javascript codemirror

如何在特定字符位置添加下划线曲线到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>
&#13;
&#13;
&#13;

我尝试使用editor.addOverlay但似乎token方法中的can't get the line number,我需要知道错误的位置。

2 个答案:

答案 0 :(得分:3)

实现此目标的最简单方法是使用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,
}));

答案 1 :(得分:0)

您可以使用CodeMirror皮棉插件。

检查此链接以获取更多信息: https://codemirror.net/demo/lint.html

enter image description here