Search code examples
javascriptreactjsmonaco-editorvisual-studio-monaco

Monaco editor - Pre-populate find control with text


I'm hosting a Monaco editor in my React app.

So far, I've got the editor to open the find control when the editor has mounted, but I need to pre-populate it with some text.

The bit of code at the moment looks like this:

... 

class CodeEditorMonaco extends Component {
  constructor (props) {
    super(props)
    this.editorDidMount = this.editorDidMount.bind(this)
    this.editor = null
  }

  editorDidMount (editor, monaco) {
    editor.focus()
    editor.getAction('actions.find').run()
  } 

  render () {
    return (
      <div className='code-editor'>
        <MonacoEditor
          width='100%'
          height='75vh'
          language='json'
          editorDidMount={this.editorDidMount}
          ref={editor => { this.editor = editor }}
        />
      </div>
    )
  }
}
...

I don't think the API documentation is clear as to whether this is possible or not.

My first instinct was to do editor.getAction('actions.find').run('text here') but that doesn't seem to work

When you highlight a word in the editor itself, and then press CMD+F you get the find control pre-populated with the text, so I believe it's possible to achieve.

Any help would be appreciated.

Find control: Find control


Solution

  • There's a way to do what you want and it's by doing exactly what you already described:

    1. Make a text selection for the term you want to search for

      editor.setSelection(new monaco.Range(18, 8, 18, 15));

    2. Trigger the find action

      editor.trigger('', 'actions.find');

      or

      editor.getAction('actions.find').run('');