Monaco-editor: Get started with DocumentFormattingEditProvider

Created on 7 Feb 2018  路  6Comments  路  Source: microsoft/monaco-editor

I am trying to add a formatting to a custom language in Monaco Editor. It seems that we could use monaco.languages.registerDocumentFormattingEditProvider.

As an example, I have made a working plunker. Now I want to add a very simple formatting rule to the whole document: add one newline after each error log. But I don't know how to write the provider in mySpecialLanguage.js:

monaco.languages.registerDocumentFormattingEditProvider('mySpecialLanguage', { provideDocumentFormattingEdits: function (model, options, token) { console.log("here") // which is well printed // should return a value of type TextEdit[], but I don't know how to construct one } })

provideDocumentFormattingEdits should return a value of type TextEdit[], where TextEdit is specified here. However, I cannot find enough code samples of constructing TextEdit in Monaco Editor (there are some examples for VSCode). Could anyone point me to some samples and help me get started?

Most helpful comment

@chengtie It works fine for me. If you click in your editor and hit Alt+Shift+F or bring up the context menu and click on the 'Format Document' menu item, the document will be modified.

All 6 comments

@chengtie A TextEdit is just an interface definition so you can just create a regular ol' JavaScript object with property names that match the interface.

return [
  {
    range: {
      startLineNumber: 1,
      startColumn: 1,
      endLineNumber: 1,
      endColumn: 1
    },
    text: "a"
  }
];

@rcjsuen thank you for your help. I just inserted your code into this plunker, the text is supposed to change, right? I don't see any change in the preview...

@chengtie It works fine for me. If you click in your editor and hit Alt+Shift+F or bring up the context menu and click on the 'Format Document' menu item, the document will be modified.

@rcjsuen ok... I did not know we can trigger the formatter like that... it works, thank you very much...

@rcjsuen Do you happen to have documentation or samples about writing provideDocumentFormattingEdits?

@chengtie No, I don't. If you describe your problem here perhaps someone can help you.

Alternatively, you can try asking for help on Stack Overflow.

Was this page helpful?
0 / 5 - 0 ratings