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

问题描述 投票:-1回答:1

我正在将CodeMirror库用于我的在线python代码编辑器项目。它的自动完成工作正常。但是我想添加用户定义的变量,函数,类以自动完成列表,并在运行时从编辑器中删除定义时将其从列表中删除。我也想在没有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
    });
javascript autocomplete codemirror
1个回答
0
投票

最后,我发现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(" ");
}

[python-hint.js中的(35-37行),因为我在completeSingle: false函数中设置了showAllHints()

我知道getAllHints(e)函数可以进行更多优化,并且存在一些问题,例如无法过滤出变量,函数,类名。这意味着提示列表包括变量,函数,类名,还包括先前键入的字符串,数字等。但是,这是我期望做的。因此,我决定在优化之前将其发布为答案。任何优化技巧,建议,更好的答案也都欢迎。

© www.soinside.com 2019 - 2024. All rights reserved.