Monaco编辑器 - 预填查找控件文本

4

我在我的React应用程序中托管了一个Monaco编辑器。

到目前为止,当编辑器已经挂载时,我已经让编辑器打开查找控件,但是我需要预填一些文本。

目前的代码段如下:

... 

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>
    )
  }
}
...

我认为API文档并没有明确说明这是否可能。
我最初的想法是执行editor.getAction('actions.find').run('text here'),但似乎无效。
当您在编辑器中突出显示一个单词,然后按下CMD+F,您会得到预填充文本的查找控件,因此我相信可以实现。
任何帮助都将不胜感激。
查找控件:Find control

真的需要一些帮助,请帮忙。 - owennicol
2个回答

10
你可以在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();

首先,从您的模型中获取要查找的字符串范围。 其次,设置选择。 第三,触发选择操作。


2

有一种方法可以实现您想要的功能,就是按照您已经描述的方式执行以下步骤:

  1. 选择要搜索的术语

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

  2. 触发查找操作

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

    或者

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


能否在替换模式下打开查找窗口?谢谢! - cat_in_hat
1
@cat_in_hat 我看到还有另一个名为editor.action.startFindReplaceAction的操作,可能是您需要的替换窗口。如果它不起作用,请查看此链接以获取更多可能的操作:https://github.com/Microsoft/vscode/blob/12134ce9978b156d6521bea84bce28a70fe90352/src/vs/editor/contrib/find/findModel.ts#L56:L75 - Stan

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接