Search code examples
reactjsmonaco-editor

Why is a random part of the code highlighted?


We have an online editor made by monaco-editor, here is the link: https://v3.10studio.tech/#/formula-editor-addin?app=formula-editor-addin. Users could enter an Excel formula like =1+2+3+4+5, then click on the Format button to see the formatted formula.

What is odd is that, after clicking on Format button, a random part of the formula is often highlighted in gray:

enter image description here

enter image description here

Does anyone know what may be the cause?

PS: The current options setting are as follows:

const monacoOptions: monacoEditor.editor.IEditorConstructionOptions = {
  lineNumbers: 'off',
  selectionHighlight: false,
  glyphMargin: false, //left side,
  lineDecorationsWidth: 0, // width between line number and content,
  renderIndentGuides: false, // no indent guide lines
  minimap: { enabled: false },
};

Solution

  • When you set the value of the model ie editor.getModel().setValue('FORMATTED-CODE') you should have to set the position of the cursor manually.

    The selection is actually not random. Monaco will select all the extra texts you have added. For example -
    Before : 1+2+3+4+5 - here last position is line 1 column 10
    Format: 1 + 2 + 3 + 4 + 5 - here last position is line 1 column 18
    So the extra text + 4 + 5 is selected, it means column 11 to 18 is selected

    To set the position of the cursor at where it was before

    const pos = editor.getPosition()
    editor.getModel().setValue('FORMATTED-CODE')
    editor.setPosition(pos)
    

    To set the position of the cursor at Line 1 Column 1

    editor.getModel().setValue('FORMATTED-CODE')
    editor.setPosition({ lineNumber: 1, column: 1 })
    

    To set the position of the cursor at last (using offset)

    const formatted = 'FORMATTED-CODE'
    const offset = formatted.length
    const pos = editor.getModel().getPositionAt(offset)
    
    editor.getModel().setValue(formatted)
    editor.setPosition(pos)
    

    You can also set selection

    editor.setSelection({
      startLineNumber: 1,
      startColumn: 1,
      endLineNumber: 1,
      endColumn: 5,
    })
    

    For more informations you can follow these APIs -