Auto Indent on load | taxtarea change

Is it possible for codemirror to auto-indent html when initialised, or when the textarea is changed?

I am loading CodeMirror from a textarea element which is prefilled with some html code which is un-indented. I would like to auto-indent (format) the code on initialisation as well as when the textarea is updated. Is this possible?

You could select the whole content and run this command.

is it possible to do this programmatically?

I figured a way to do this by looking at how the command is executed in the js file. Basically I followed the logic of ‘ctrl+a’ event on the codemirror editor followed by ‘Shit+Tab’ which triggers the indentAuto command.

The only thing I didn’t manage to get to work to unselect the selection by triggering a mousedown event … any idea how to programmatically unselect?

//instantiate the codemirror
var myCodeMirror = CodeMirror.fromTextArea( $wpcf7Editor.get(0), {
    mode:  "htmlmixed"
//programmatically select all code, this is equivalent to ctrl+a on windows
  {scroll: false});
  //auto indent the selection
  //I tried to fire a mousdown event on the code to unselect everything but it does not work.
  $('.CodeMirror-code', $codemirror).trigger('mousedown');
1 Like

Simply use setSelection again (or setCursor) to set the selection at the start of the document.

1 Like

nice, thanks for the tip.

Is .indentSelection() still supported by CodeMirror?

Also, to deselect the lines, I used editor.setCursor({line: 1, ch: 1});

You could also use js-beautify, it works nicely but only supports css, html, and js.

1 Like