我想使用 CodeMirror 的功能(例如行编号、换行、搜索等)来处理纯文本,不需要特别突出显示代码,而是使用 Google Chrome 拼写检查器或其他自然语言(尤其是英语)激活拼写检查(我不需要让它在其他浏览器上工作)。我怎样才能做到这一点?是否可以编写一个启用拼写检查的纯文本模式插件?
我实际上在为 NoTex.ch 编码时将 typo.js 与 CodeMirror 集成;你可以在这里看看 CodeMirror.rest.js;我需要一种方法来检查 reStructuredText 标记拼写,并且由于我使用 CodeMirror 出色的语法突出显示功能,因此操作起来非常简单。
您可以在提供的链接中检查代码,但我将总结一下我所做的:
初始化typo.js库;另请参阅作者的博客/文档:
var typo = new Typo ("en_US", AFF_DATA, DIC_DATA, {
platform: 'any'
});
为单词分隔符定义正则表达式:
var rx_word = "!\"#$%&()*+,-./:;<=>?@[\\\\\\]^_`{|}~";
为CodeMirror定义覆盖模式:
CodeMirror.defineMode ("myoverlay", function (config, parserConfig) {
var overlay = {
token: function (stream, state) {
if (stream.match (rx_word) &&
typo && !typo.check (stream.current ()))
return "spell-error"; //CSS class: cm-spell-error
while (stream.next () != null) {
if (stream.match (rx_word, false)) return null;
}
return null;
}
};
var mode = CodeMirror.getMode (
config, parserConfig.backdrop || "text/x-myoverlay"
);
return CodeMirror.overlayMode (mode, overlay);
});
使用 CodeMirror 覆盖;请参阅用户手册以了解具体如何执行此操作。我已经在我的代码中完成了它,因此您也可以在那里查看,但我推荐用户手册。
定义 CSS 类:
.CodeMirror .cm-spell-error {
background: url(images/red-wavy-underline.gif) bottom repeat-x;
}
这种方法非常适合德语、英语和西班牙语。对于法语词典 typo.js 似乎存在一些(口音)问题,而希伯来语、匈牙利语和意大利语等语言 - 词缀数量很长或词典相当广泛 - 它实际上不起作用,因为 typo.js 当前的实现使用了太多内存并且速度太慢。
使用德语(和西班牙语)typo.js 可以阻止 JavaScript VM 几百毫秒(但仅在初始化期间!),因此您可能需要考虑使用 HTML5 Web Worker 的后台线程(请参阅 CodeMirror.typo.worker .js 为例)。此外 typo.js 似乎不支持 Unicode(由于 JavaScript 限制):至少,我没能让它与非拉丁语言(如俄语、希腊语、印地语等)一起工作。
除了(现在相当大)NoTex.ch 之外,我还没有将所描述的解决方案重构为一个很好的单独项目,但我可能很快就会这样做;在此之前,您必须根据上述描述或提示代码来修补您自己的解决方案。我希望这有帮助。
在 CodeMirror 5.18.0 及更高版本中,您可以设置
inputStyle: 'contenteditable'
和 spellcheck: true
以便能够使用网络浏览器的拼写检查功能。例如:
var myTextArea = document.getElementById('my-text-area');
var editor = CodeMirror.fromTextArea(myTextArea, {
inputStyle: 'contenteditable',
spellcheck: true,
});
使该解决方案成为可能的相关提交是:
这是 hsk81 答案的工作版本。它使用 CodeMirror 的覆盖模式,并查找引号、html 标签等内的任何单词。它有一个示例typo.check,应替换为 Typo.js 之类的内容。它用红色波浪线强调未知单词。
这是使用 IPython 的 %%html 单元进行测试的。
<style>
.CodeMirror .cm-spell-error {
background: url("https://raw.githubusercontent.com/jwulf/typojs-project/master/public/images/red-wavy-underline.gif") bottom repeat-x;
}
</style>
<h2>Overlay Parser Demo</h2>
<form><textarea id="code" name="code">
</textarea></form>
<script>
var typo = { check: function(current) {
var dictionary = {"apple": 1, "banana":1, "can't":1, "this":1, "that":1, "the":1};
return current.toLowerCase() in dictionary;
}
}
CodeMirror.defineMode("spell-check", function(config, parserConfig) {
var rx_word = new RegExp("[^\!\"\#\$\%\&\(\)\*\+\,\-\.\/\:\;\<\=\>\?\@\[\\\]\^\_\`\{\|\}\~\ ]");
var spellOverlay = {
token: function (stream, state) {
var ch;
if (stream.match(rx_word)) {
while ((ch = stream.peek()) != null) {
if (!ch.match(rx_word)) {
break;
}
stream.next();
}
if (!typo.check(stream.current()))
return "spell-error";
return null;
}
while (stream.next() != null && !stream.match(rx_word, false)) {}
return null;
}
};
return CodeMirror.overlayMode(CodeMirror.getMode(config, parserConfig.backdrop || "text/html"), spellOverlay);
});
var editor = CodeMirror.fromTextArea(document.getElementById("code"), {mode: "spell-check"});
</script>
我不久前写了一个波浪下划线类型的拼写检查器。老实说,它需要重写,当时我对 JavaScript 还很陌生。但原则都在那里。
我创建了一个带有拼写错误建议/更正的拼写检查器:
https://gist.github.com/kofifus/4b2f79cadc871a29439d919692099406
演示:https://plnkr.co/edit/0y1wCHXx3k3mZaHFOpHT
以下是代码的相关部分:
首先我承诺加载词典。我使用typo.js作为字典,如果它们不是本地托管的,加载可能需要一段时间,所以最好在登录/CM初始化等之前一启动就开始加载:
function loadTypo() {
// hosting the dicts on your local domain will give much faster results
const affDict='https://rawgit.com/ropensci/hunspell/master/inst/dict/en_US.aff';
const dicDict='https://rawgit.com/ropensci/hunspell/master/inst/dict/en_US.dic';
return new Promise(function(resolve, reject) {
var xhr_aff = new XMLHttpRequest();
xhr_aff.open('GET', affDict, true);
xhr_aff.onload = function() {
if (xhr_aff.readyState === 4 && xhr_aff.status === 200) {
//console.log('aff loaded');
var xhr_dic = new XMLHttpRequest();
xhr_dic.open('GET', dicDict, true);
xhr_dic.onload = function() {
if (xhr_dic.readyState === 4 && xhr_dic.status === 200) {
//console.log('dic loaded');
resolve(new Typo('en_US', xhr_aff.responseText, xhr_dic.responseText, { platform: 'any' }));
} else {
console.log('failed loading aff');
reject();
}
};
//console.log('loading dic');
xhr_dic.send(null);
} else {
console.log('failed loading aff');
reject();
}
};
//console.log('loading aff');
xhr_aff.send(null);
});
}
其次,我添加一个覆盖层来检测和标记拼写错误,如下所示:
cm.spellcheckOverlay={
token: function(stream) {
var ch = stream.peek();
var word = "";
if (rx_word.includes(ch) || ch==='\uE000' || ch==='\uE001') {
stream.next();
return null;
}
while ((ch = stream.peek()) && !rx_word.includes(ch)) {
word += ch;
stream.next();
}
if (! /[a-z]/i.test(word)) return null; // no letters
if (startSpellCheck.ignoreDict[word]) return null;
if (!typo.check(word)) return "spell-error"; // CSS class: cm-spell-error
}
}
cm.addOverlay(cm.spellcheckOverlay);
第三,我使用列表框来显示建议并修复拼写错误:
function getSuggestionBox(typo) {
function sboxShow(cm, sbox, items, x, y) {
let selwidget=sbox.children[0];
let options='';
if (items==='hourglass') {
options='<option>⌛</option>'; // hourglass
} else {
items.forEach(s => options += '<option value="' + s + '">' + s + '</option>');
options+='<option value="##ignoreall##">ignore all</option>';
}
selwidget.innerHTML=options;
selwidget.disabled=(items==='hourglass');
selwidget.size = selwidget.length;
selwidget.value=-1;
// position widget inside cm
let cmrect=cm.getWrapperElement().getBoundingClientRect();
sbox.style.left=x+'px';
sbox.style.top=(y-sbox.offsetHeight/2)+'px';
let widgetRect = sbox.getBoundingClientRect();
if (widgetRect.top<cmrect.top) sbox.style.top=(cmrect.top+2)+'px';
if (widgetRect.right>cmrect.right) sbox.style.left=(cmrect.right-widgetRect.width-2)+'px';
if (widgetRect.bottom>cmrect.bottom) sbox.style.top=(cmrect.bottom-widgetRect.height-2)+'px';
}
function sboxHide(sbox) {
sbox.style.top=sbox.style.left='-1000px';
}
// create suggestions widget
let sbox=document.getElementById('suggestBox');
if (!sbox) {
sbox=document.createElement('div');
sbox.style.zIndex=100000;
sbox.id='suggestBox';
sbox.style.position='fixed';
sboxHide(sbox);
let selwidget=document.createElement('select');
selwidget.multiple='yes';
sbox.appendChild(selwidget);
sbox.suggest=((cm, e) => { // e is the event from cm contextmenu event
if (!e.target.classList.contains('cm-spell-error')) return false; // not on typo
let token=e.target.innerText;
if (!token) return false; // sanity
// save cm instance, token, token coordinates in sbox
sbox.codeMirror=cm;
sbox.token=token;
let tokenRect = e.target.getBoundingClientRect();
let start=cm.coordsChar({left: tokenRect.left+1, top: tokenRect.top+1});
let end=cm.coordsChar({left: tokenRect.right-1, top: tokenRect.top+1});
sbox.cmpos={ line: start.line, start: start.ch, end: end.ch};
// show hourglass
sboxShow(cm, sbox, 'hourglass', e.pageX, e.pageY);
// let the ui refresh with the hourglass & show suggestions
setTimeout(() => {
sboxShow(cm, sbox, typo.suggest(token), e.pageX, e.pageY); // typo.suggest takes a while
}, 100);
e.preventDefault();
return false;
});
sbox.onmouseleave=(e => {
sboxHide(sbox)
});
selwidget.onchange=(e => {
sboxHide(sbox)
let cm=sbox.codeMirror, correction=e.target.value;
if (correction=='##ignoreall##') {
startSpellCheck.ignoreDict[sbox.token]=true;
cm.setOption('maxHighlightLength', (--cm.options.maxHighlightLength) +1); // ugly hack to rerun overlays
} else {
cm.replaceRange(correction, { line: sbox.cmpos.line, ch: sbox.cmpos.start}, { line: sbox.cmpos.line, ch: sbox.cmpos.end});
cm.focus();
cm.setCursor({line: sbox.cmpos.line, ch: sbox.cmpos.start+correction.length});
}
});
document.body.appendChild(sbox);
}
return sbox;
}
希望这有帮助!
代码镜像 6:
const state = EditorState.create({
doc: "This is a mispellled word",
extensions: [EditorView.contentAttributes.of({ spellcheck: 'true' })]
});
const view = new EditorView({
state: state ,
parent: document.getElementById('myEditor'),
});