CodeMirror 3 Indent All Lines / Autoformat

Problem

You have created an instance of a CodeMirror and initialized it with some text and would like to correct its indentation or you would like to give the user the option to ‘autoformat’ the text entered.

Solution

Iterate over all lines in the editor and indent them individually:

var e = CodeMirror.fromTextArea(textarea.get(0), {});

for (var i=0;i<e.lineCount();i++) { e.indentLine(i); }

This should indent all lines in your editor nicely:

Note that in CodeMirror 2 there was an autoformatter add-in which is not officially supported for CodeMirror 3.

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s