monaco-editor:如何订阅/收听本机命令/操作 'actions.find'

monaco-editor: how to subscribe / listen native commands / actions as 'actions.find'

很长一段时间以来,我一直在尝试寻找一种方法、示例或信息,以了解如何订阅或收听原生 commands/actions as actions.find

我的情况是 - 当用户在编辑器的 workbench 中使用 “查找匹配项” 功能时产生一些副作用(通过键盘快捷键或上下文菜单调用) , 最后我想在我的效果中作为参数 'searching 'substring'.

希望社区可以帮助我或放置一些类似的案例解决示例。

在调试和研究 monaco-editor 的源代码之后,我发现在我看来,使用 API(恕我直言)的正确解决方案适用于我的案例。

我们可以使用API of FindController,这是每个实例中的永久贡献之一,我们可以使用那里的public方法onFindReplaceStateChange

// to get relevant FindController from editor instance we can use
var findController = editor.getContribution('editor.contrib.findController')

// to get FindReplaceState from FindController
var findSearchState = editor.getContribution('editor.contrib.findController').getState();

// to subscribe to 'find matches' event bus
editor.getContribution('editor.contrib.findController')
   .getState().onFindReplaceStateChange(
       (...rest) => console.log('FindReplaceStateChange: ', ...rest)
   );

// to force & silent set current search substring
editor.getContribution('editor.contrib.findController').setSearchString('foo-bar');

// to programmatically call search with options, 
// not 'editor.getAction('actions.find').run()' (that not have arguments) 
editor.getContribution('editor.contrib.findController').start({
    forceRevealReplace: false,
    seedSearchStringFromSelection: false,
    seedSearchStringFromGlobalClipboard: false,
    shouldFocus: false,
    shouldAnimate: false,
    updateSearchScope: false
});

我已经准备了一个例子来解释如何在 CodeSandbox 上解决我的案例(多个编辑器之间的同步搜索)-
Monaco Editor [ Multiple Instances search sync case ]

screencast 'how it works' (GIF)