Search code examples
widgetcodemirror

CodeMirror - what is addWidget for and how to use it?


I want to make some extensions to CodeMirror. The addWidget method seems like a promising starting point. The documentation states

addWidget(pos, node, scrollIntoView) Puts node, which should be an absolutely positioned DOM node, into the editor, positioned right below the given {line, ch} position. When scrollIntoView is true, the editor will ensure that the entire node is visible (if possible). To remove the widget again, simply use DOM methods (move it somewhere else, or call removeChild on its parent).

I don't really understand what that means or what I would use it for. I cannot find a usage of it in the CodeMirror codebase nor anywhere else in google.


Solution

  • You need to pass an html node and a position and a Boolean value

    // create a node
    var htmlNode =document.createElement("h1");
    var text =  document.createTextNode("Text or whatever");
    htmlNode.appendChild(text)
    
    // call this after you initialized the editor.
    // the position must be like this {ch: YourCharecterNumber, line: YourLineNumber}
    editor.addWidget({ch:30 , line: 1},htmlNode, true)