Search code examples
htmltext-editorfreemarkercodemirror

How to change the mode dynamically in codemirror on encounter of a particular expression?


In the textarea whenever '<' is encountered the mode should be html and for '<#' or '<@' or '$', the mode should be ftl. In the code that I have written

function determineCodeMirrorType(cm) {
  if (cm.getOption('mode') == 'text/ftl') {
    checkAndSwitchToHTML(cm, cm.getValue());
  } else if (cm.getOption('mode') == 'text/html') {
    checkAndSwitchToFTL(cm, cm.getValue());
  }
}

function checkAndSwitchToHTML(cm, val) {
  if (/^\s*</.test(val)) {
    cm.setOption("mode", "text/html");
  }
}

function checkAndSwitchToFTL(cm, val) {
  if (/[<#|<@|$]/.test(val)) {
    cm.setOption("mode", "text/ftl");
  }
}

function buildCMInstance(mode, value) {
  var cm = CodeMirror.fromTextArea(document.getElementById("code"), {
    mode:mode,
    value:value,
    lineNumbers:true,
    onChange:function(cmInstance){ 
      determineCodeMirrorType(cmInstance); //The call to this function is not made.
    })
  });
  return cm;
}

$(document).ready(function(){
  var cm = buildCMInstance("text/ftl")
});

I want to know is there any option that can be initiated which allows the code to change dynamically by making a call to the function "determineCodeMirrorType".


Solution

  • onChange does not exist in recent CodeMirror versions. You have to register the event handler by calling cm.on("change", function(cm, change) { .... }).