摩纳哥编辑器将双引号更改为单引号字符

Monaco editor change double quote to single quote character

由于我的自定义语言对字符串使用单引号 (') 而不是双引号 (") 字符,我想在用户输入时将双引号更改为两个单引号字符。这在 monaco 编辑器和最好的方法是什么?

因此,例如,如果用户输入此 ",它将自动更改为此 ''。唯一不是这种情况的情况是在两个单引号字符 (' " ') 内。

有什么建议吗?

虽然我不确定 registerOnTypeFormattingEditProvider 是否是执行此操作的最佳方法,但这里是我如何完成此任务的代码:

 // changes the double quote charachter to two single quote characters
monaco.languages.registerOnTypeFormattingEditProvider(clarionLanguage, {
    autoFormatTriggerCharacters: ['"'],
    provideOnTypeFormattingEdits: (model, position, character, options, token) => {

        // if inside string quotes then allow double quote character
        let quotes: monaco.editor.FindMatch[] = model.findMatches(`'([^'])*'`, true, true, true, null, true);
        if (quotes.length > 0) {
            for (let quote of quotes) {
                if (quote && (position.column >= quote.range.startColumn && position.column <= quote.range.endColumn)) {
                    return;
                }
            }
        }

        return [
            {
                range: {
                    startLineNumber: position.lineNumber,
                    startColumn: position.column - 1,
                    endLineNumber: position.lineNumber,
                    endColumn: position.column
                },
                text: `''`
            }
        ];
    }
});

这是一个更好的解决方案(由 rcjsuen 和 alexandrudima 在 GitHub 上建议):

 // change the double quotes to two single quotes
    editor.onDidType(text => {
        if (text === '"') {
            let selection = editor.getSelection();
            let range = new monaco.Range(selection.startLineNumber, selection.startColumn - 1, selection.endLineNumber, selection.endColumn);
            let id = { major: 1, minor: 1 };
            let op = { identifier: id, range, text: "''", forceMoveMarkers: true };

            editor.getModel().pushEditOperations([], [op], undefined);

            editor.setSelection(selection);
        }
    });