![](/img/trans.png)
[英]Signalr: How to call a javascript function the name of which is defined at run time
[英]How to add variable,function,class which defined in run time to CodeMirror auto completion list and remove them when deleting from code in JS
我正在为我的在线 python 代码编辑器项目使用CodeMirror库。它的自动完成工作正常。 但是当我在运行时从编辑器中删除定义时,我想将用户定义的变量、函数、类添加到自动完成列表并从列表中删除它们。 我也想在没有 JQuery 的香草 JS 中做到这一点。
var editor = CodeMirror.fromTextArea(myTextarea, {
mode: {
name: "python",
version: 3,
singleLineStringErrors: false
},
lineNumbers: true,
indentUnit: 4,
extraKeys: {
"Ctrl-Space": "autocomplete",
"Ctrl-/": "toggleComment",
"Alt-E": runCode,
"Alt-C": clearOutput
},
matchBrackets: true,
autoCloseBrackets: true
});
最后我发现 CodeMirror 的 anyword-hint.js 可以用来完成这个任务。 所以我结合了python-hint.js和 anyword-hint.js 的功能。 (我使用 npm 安装 CodeMirror,因为我正在使用 NodeJs 项目)
<script src="node_modules/codemirror/lib/codemirror.js"></script>
<script src="node_modules/codemirror/mode/python/python.js"></script>
<script src="python-hint.js"></script>
<!-- this script not contains in CodeMirror. I have added manually -->
<script src="node_modules/codemirror/addon/hint/anyword-hint.js"></script>
<script src="node_modules/codemirror/addon/hint/show-hint.js"></script>
<link rel="stylesheet" href="node_modules/codemirror/lib/codemirror.css">
<link rel="stylesheet" href="node_modules/codemirror/addon/hint/show-hint.css">
<script>
function getAllHints(e) {
var hints = CodeMirror.pythonHint(e);
var anyHints = CodeMirror.hint.anyword(e);
anyHints.list.forEach(function(hint) {
if (hints.list.indexOf(hint) == -1)
hints.list.push(hint);
})
hints.list.sort();
if (hints) {
CodeMirror.on(hints, "pick", function(word) {
if (word.charAt(word.length - 1) == ')')
editor.execCommand("goCharLeft");
});
}
return hints;
}
function showAllHints() {
editor.showHint({
hint: getAllHints,
completeSingle: false
});
}
var editor = CodeMirror.fromTextArea(document.getElementById("editor"), {
mode: {
name: "python",
version: 3
},
lineNumbers: true,
indentUnit: 4
});
editor.on('inputRead', function onChange(editor, input) {
if (input.text[0] === ' ' || input.text[0] === ":" || input.text[0] === ")") {
return;
}
showAllHints();
});
</script>
我已删除
if(completionList.length == 1) {
completionList.push(" ");
}
(35-37 行)来自python-hint.js ,因为我在showAllHints()
function 中设置completeSingle: false
。
我知道getAllHints(e)
function 可以进行更多优化并且有一些问题,例如无法过滤掉变量、function、class 名称。 这意味着提示列表包括变量 function、class 名称,还包括以前键入的字符串、数字等。但是这是我期望做的。 所以我决定在优化之前发布作为答案。 任何优化技巧,建议和更好的答案也欢迎。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.