How to use monaco editor for syntax highlighting?

Harshal Patil picture Harshal Patil · Oct 8, 2018 · Viewed 7.2k times · Source

I developing a code based chat component. Every chat is some code snippet. For user input, I am using monaco-editor. It works fine.

But as soon as user hits send button, I get raw input from Monaco editor. I need to append this user input to chat list and again highlight this input.

Is there a way I can use Monaco editor to do this? Or do I have to use highlight.js along with Monaco?

Answer

Petr picture Petr · Nov 5, 2018

I had the same problem so I created an issue #1171:

and two solutions were provided:

a) Format an existing HTML element:

monaco.editor.colorizeElement(document.getElementById("yourElement"));

b) Format a text which is not part of any element. This is a more generic approach which returns a Promise:

const code = "source code";
monaco.editor.colorize(code, "javascript")
  .then(html => document.getElementById("yourElement").innerHTML = html);

Documentation: