Как добиться расширенного автодополнения в React CodeMirror?Python

Программы на Python
Ответить
Anonymous
 Как добиться расширенного автодополнения в React CodeMirror?

Сообщение Anonymous »

Я пытаюсь реализовать редактор кода на своем сайте реагирования, мне нужно реализовать довольно хорошее автодополнение для Python. Столкнулся с проблемой, заключающейся в том, что я не придумал, как добавить сюда какие-то готовые решения (честно говоря, пока даже не нашел). Говоря о моих собственных попытках, я попытался решить эту проблему, добавив своего провайдера: autocompletion({ override: [customCompletionProvider] }),.
А также его код:

Код: Выделить всё

const customCompletionProvider = (context) => {
const word = context.matchBefore(/\w*/);

const code = context.state.doc.toString();

// detect variables in code
const variableDeclarationPattern = /(\w+)\s*=\s*(.+)/g;
let match;
while ((match = variableDeclarationPattern.exec(code)) !== null) {
const [_, varName, varValue] = match;
if (/['"]/.test(varValue)) variables[varName] = "str";
else if (/\[.*\]/.test(varValue)) variables[varName] = "list";
else if (/\(.*\)/.test(varValue)) variables[varName] = "tuple";
else if (/\{.*\}/.test(varValue)) variables[varName] = "dict";
else if (/[-+]?\d+/.test(varValue)) variables[varName] = "int";
else if (/[-+]?\d*\.\d+/.test(varValue)) variables[varName] = "float";
}

// method call through dot? =>
const dotMatch = context.matchBefore(/\w+\.\w*/);
if (dotMatch) {
const [variable, methodStart] = dotMatch.text.split(".");

if (variables[variable]) {
const methods = getMethodsForType(variables[variable]);
return {
from: dotMatch.from + variable.length + 1,
options: methods.map((method) => ({
label: method,
type: "method",
})),
};
}
}

const letterMatch = context.matchBefore(/[a-z]|[A-Z]/);
console.log(letterMatch);

if (!letterMatch) {
return null;
}

const basicSuggestions = [
{ label: "print", type: "function" },
{ label: "len", type: "function" },
{ label: "str", type: "type" },
{ label: "int", type: "type" },
{ label: "list", type: "type" },
{ label: "dict", type: "type" },
{ label: "tuple", type: "type" },
{ label: "def", type: "function" },
{ label: "class", type: "class" },
{ label: "async", type: "keyword" },
{ label: "return", type: "keyword" },
{ label: "yield", type: "keyword" },
];

return {
from: word.from,
options: basicSuggestions.filter((suggestion) =>
suggestion.label.startsWith(word.text)
),
};
};

Помимо того, что моя версия работает, мягко говоря, не очень хорошо, она еще и переопределяет базовое автодополнение, потерять которое не хотелось бы.
А еще код компонента: Также я использую onUpdateExtension:

Код: Выделить всё

const onUpdateExtension = EditorView.updateListener.of((update) => {
if (update.docChanged) {
const { state } = update.view;
const doc = state.doc.toString();
const lastChar = doc[doc.length - 1];

if (lastChar === ".") {
startCompletion(update.view);
}
}
});

PS: моя основная цель — добавить подсказки для переменных методов сразу после ввода точки

Подробнее здесь: https://stackoverflow.com/questions/790 ... codemirror
Ответить

Быстрый ответ

Изменение регистра текста: 
Смайлики
:) :( :oops: :roll: :wink: :muza: :clever: :sorry: :angel: :read: *x)
Ещё смайлики…
   
К этому ответу прикреплено по крайней мере одно вложение.

Если вы не хотите добавлять вложения, оставьте поля пустыми.

Максимально разрешённый размер вложения: 15 МБ.

Вернуться в «Python»