使用 getWordUnderCursor 获取包含撇号的单词?

Using getWordUnderCursor to get words that contain apostrophes?

我在 Electron 应用程序中使用 monaco-editor,用户将在其中输入诗歌。编辑器的语言设置为 plaintext.

我 运行 遇到这样一个问题:如果用户键入的单词中包含 '(撇号),getWordAtPosition 不会 return 完整单词。根据光标的位置(这是我传递给 getWordAtPosition 的位置),它会 return 撇号之前的内容,或者撇号之后的内容。

例如,使用 | (管道)表示光标的位置,如果用户键入:

couldn't|

getWordAtPosition 将 return t

对于|couldn't,它将return couldn

我要的是,无论光标位置如何,它都会return couldn't.

到目前为止,我尝试过的是在创建不包含撇号(但在其他情况下为默认值)的编辑器时在选项中提供 wordSeparators,但这没有帮助。

编辑器创建块:

editorInstance = monaco.editor.create(document.getElementById('editor'), {
            language: 'plaintext',
            wordSeparators: '`~!@#$%^&*()-=+[{]}\|;:",.<>/?'
        });

块使用 getWordAtPosition:

fromEventPattern((handler: NodeEventHandler) => editorInstance.onDidChangeCursorPosition(handler))
            .pipe(
                map(() => {
                    const cursorPosition: IPosition = editorInstance.getPosition();

                    return editorInstance.getModel()
                        .getWordAtPosition(cursorPosition)
                        ?.word;
                }),
                filter((value: string) => !!value)
            );

如有任何帮助,我们将不胜感激!提前致谢!

您可以设置语言配置(针对新语言或现有语言)并提供 wordPattern 将用于匹配单词的正则表达式。

monaco.languages.setLanguageConfiguration('plaintext', {
    wordPattern: /'?\w[\w'-.]*[?!,;:"]*/
});


monaco.editor.create(document.getElementById("container"), {
    language: 'plaintext',
});

即使 plaintext 作为一种语言已经存在,它仍然有效。我不确定 setLanguageConfiguration 是否进行了任何合并(我假设没有?)所以请记住这一点。

我的代码片段中的正则表达式并不完美,但它匹配如下字词:

  • 不能
  • '原因
  • 你呢?
  • 你好

这对我的用例很重要。如果您是未来的搜索者,请记住这一点!