Search code examples
javascripthtmlxmlformattingcodemirror

How do I pass an HTML document to CodeMirror as a start value?


I have an HTML document stored in a string as follows :

var htmlAsString = "<!DOCTYPE html><html><head>........";

I try to initialise my CodeMirror editor with the above HTML document as follows :

var cm = CodeMirror($('#some-div')[0], {
  value: htmlAsString,
  mode: "htmlmixed",
  autofocus: true,
  lineNumbers: true
});

However, all that does is create a Code Mirror editor with one single unclickable line that contains the htmlAsString string.

I obviously want my Code Mirror editor to be initialized with all of the HTML nicely xml-formatted (indentation, nesting, spacing, new lines, etc..) so that the developer can use the Code Mirror to edit/update that HTML.

What am I doing wrong ?


Solution

  • Your HTML string dosnt contain any line breaks or tabs/spaces.

    What you will need to do is parse your string through a HTML formatter.

    CodeMirror has a formatting util by including formatting.js

    Here is a working demo: http://codemirror.net/2/demo/formatting.html

    You will want to execute something similar to the following code after you have initialized code mirror.

    var cm = CodeMirror($('#some-div')[0], {
      value: htmlAsString,
      mode: "htmlmixed",
      autofocus: true,
      lineNumbers: true
    });
    
    var totalLines = cm.lineCount();  
    cm.autoFormatRange({line:0, ch:0}, {line:totalLines});