コードを強調表示する必要はなく、代わりにGoogle Chromeのスペルチェッカーまたはその他の自然言語(特に英語)のスペルチェックを有効にして、プレーンテキストにCodeMirrorの機能(行番号付け、折り返し、検索など)を使用したいと思います。 (他のブラウザで動作させる必要はありません)。これどうやってするの?スペルチェックを可能にするプレーンテキストモードのアドオンを作成することは可能ですか?
6 に答える
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ワーカーを使用したバックグラウンドスレッドを検討することをお勧めします(CodeMirror.typo.worker.jsを参照してください。例)。さらに、typo.jsはUnicodeをサポートしていないようです(JavaScriptの制限のため):少なくとも、ロシア語、ギリシャ語、ヒンディー語などの非ラテン語で動作させることができませんでした。
説明したソリューションを(現在はかなり大きい)NoTex.chとは別に、別のプロジェクトにリファクタリングしていませんが、すぐに実行する可能性があります。それまでは、上記の説明またはヒント付きコードに基づいて、独自のソリューションにパッチを適用する必要があります。これがお役に立てば幸いです。
これは、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>
CodeMirror 5.18.0以降では、Webブラウザのスペルチェック機能を使用できるようにをinputStyle: 'contenteditable'
設定できます。spellcheck: true
例えば:
var myTextArea = document.getElementById('my-text-area');
var editor = CodeMirror.fromTextArea(myTextArea, {
inputStyle: 'contenteditable',
spellcheck: true,
});
このソリューションを可能にした関連するコミットは次のとおりです。
- inputStyleをオプションにし、関連するロジックをTextareaInputに移動します(CodeMirror 5.0.0、2015年2月)
- 実験的なスペルチェックオプションを追加(CodeMirror 5.18.0、2016年8月)
CodeMirrorはHTMLテキストエリアに基づいていないため、組み込みのスペルチェックを使用できません。
typo.jsのようなものを使用して、CodeMirrorの独自のスペルチェックを実装できます。
まだ誰もこれをやったとは思わない。
少し前に、波線の下線タイプのスペルチェッカーを作成しました。正直に言うと、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);
3番目に、リストボックスを使用して、提案を表示し、タイプミスを修正します。
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;
}
お役に立てれば !