如何将在运行时间定义的变量,函数,class添加到CodeMirror自动完成列表中,并在从JS中的代码中删除时删除它们

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 代码编辑器 project.It 使用 CodeMirror 库,它的自动完成工作正常。但是我想将用户定义的变量、函数、类 添加到自动完成列表中,并在 运行 时从编辑器中删除定义时将它们从列表中删除。我也想在没有 JQuery.

的情况下在 vanilla 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() 函数中设置了 completeSingle: false

我知道 getAllHints(e) 函数可以优化更多并且有一些问题,例如无法过滤掉变量、函数、class 名称。 这意味着提示列表包括变量、函数、class 名称,还包括以前键入的字符串、数字等。 然而,这是我期望做的。所以我决定在优化之前将 post 作为答案。 也欢迎任何优化技巧、建议和更好的答案。