I have made an online editor for Python, but I don’t know how to realize the automatic completion of Python code.
I wrote by example, but it didn’t work. Here’s my code.
const completePropertyAfter = ['PropertyName', '.', '?.'];
const dontCompleteIn = ['TemplateString', 'LineComment', 'BlockComment',
'VariableDefinition', 'PropertyDefinition'];
function completeProperties(from: number, object: Object) {
let options = []
for (let name in object) {
options.push({
label: name,
// @ts-ignore
type: typeof object[name] === 'function' ? 'function' : 'variable',
})
}
return {
from,
options,
span: /^[\w$]*$/
}
}
function completeFromGlobalScope(context: CompletionContext) {
let nodeBefore = syntaxTree(context.state).resolveInner(context.pos, -1)
if (completePropertyAfter.includes(nodeBefore.name) &&
nodeBefore.parent?.name == 'MemberExpression') {
let object = nodeBefore.parent.getChild('Expression')
if (object?.name == 'VariableName') {
let from = /\./.test(nodeBefore.name) ? nodeBefore.to : nodeBefore.from
let variableName = context.state.sliceDoc(object.from, object.to)
if (typeof window[variableName as any] == 'object')
return completeProperties(from, window[variableName as any]);
}
} else if (nodeBefore.name == 'VariableName') {
return completeProperties(nodeBefore.from, window);
} else if (context.explicit && !dontCompleteIn.includes(nodeBefore.name)) {
return completeProperties(context.pos, window);
}
return null;
}
function showCodeMirror() {
if (typeof editorView.value !== 'undefined') {
editorView.value.destroy();
}
const globalPythonCompletions = pythonLanguage.data.of({
autocomplete: completeFromGlobalScope
});
const editorState = EditorState.create({
doc: fileText.value,
extensions: [
basicSetup,
python()
keymap.of([indentWithTab]),
globalPythonCompletions,
autocompletion({ activateOnTyping: true }),
],
});
editorView.value = new EditorView({
state: editorState,
parent: codemirror.value,
});
}