简体   繁体   中英

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

For a long time I've been trying to find a way, example or information about how I can subscribe or listen native commands/actions as actions.find .

My case is - to create some side-effect when user use "Find Matches" functionality in editor's workbench (called by keyboard shortcut or context-menu), at finally I want to get as argument 'searching 'substring' in my effect.

Hopefully the community can help me or place some similar case resolving sample.

After debugging and studying the source code of monaco-editor, I found, as it seems to me, the correct solution for using the API (IMHO) for my case.

We can use API of FindController , that is one of permanently contributions in each instance, we can use there public method 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
});

I have prepared an example with explanations for solving my case (synchronization of search between several editors) on a CodeSandbox -
Monaco Editor [ Multiple Instances search sync case ]

screencast 'how it works' (GIF)

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM