Search code examples
javascriptcodemirror

How to add <span> within CodeMirror editor?


No jQuery please!

I'd like to add a styled span within the body of a CodeMirror editor. This is for the purposes of a mail merge like application where you can for instance do: (From Zapier) example

I believe this may be possible using a CodeMirror Widget but I'm lost as to what direction to go in. I found an example of something similar (albeit far more complicated) here.

I also tried tagify which is extremely similar to what I'm after but doesn't have multi-line inputs, which is a requirement.

All I need is the ability to add and remove (via backspace with the caret just behind the tag) these spans but there doesn't appear to be a simple solution.

Also if there is a convenient library or some other direction I can go in not involving CodeMirror that'd also be fine.


Solution

  • CodeMirror is actually well suited for this.

    First insert some placeholder into the document, such as [[tag]].

    var lineNumber = 0;
    var charNumber = 0;
    var snippet = "[[tag]]"
    editor.doc.replaceRange(snippet, {line:lineNumber, from: charNumber});
    

    Then create your DOM element, I recommend a span.

    var htmlNode = document.createElement("span");
    //Style and add what you like to the span
    

    Then use doc.markText to replace it with that node.

    editor.doc.markText({line: lineNumber,ch: charNumber}, {line: lineNumber,ch: charNumber + snippet.length}, {
       replacedWith: htmlNode
    })