4

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

owennicol
  • 57
  • 1
  • 6

2 Answers2

10

You can try it with Monaco playground.

const editor = monaco.editor.create(document.getElementById("container"), {
    value: "{\n\t\"dependencies\": {\n\t\t\n\t}\n}\n",
    language: "json"
});

const model = editor.getModel();
const range = model.findMatches('d')[0].range;

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

First, get the range of the string you want to find from your model. Second, set selection. Third, trigger select action.

hullis
  • 350
  • 2
  • 13
3

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('');

Stan
  • 1,251
  • 1
  • 15
  • 24
  • is it possible to open the find window in replace mode? Thank you!! – cat_in_hat Oct 23 '19 at 13:32
  • 1
    @cat_in_hat I saw there's another action called `editor.action.startFindReplaceAction` which may be what you need for the replace window. If it doesn't work then check this link for more possible actions: https://github.com/Microsoft/vscode/blob/12134ce9978b156d6521bea84bce28a70fe90352/src/vs/editor/contrib/find/findModel.ts#L56:L75 – Stan Oct 29 '19 at 17:58