Search code examples
javascriptcodemirror

Get indentation used in specific line in CodeMirror


I am using CodeMirror and I want to provide some simple code transformation capabilities.

What I need though is to know the placed indentation of the line I am on, for instance:

function test() {
  var x = 0; //I need to get that this line has 2 spaces.
  var y = function() {
    return true; //And that this one has 4 spaces -or a tab.
  }
}

Is there a standard way of getting this via the CodeMirror API, or any relevant hack to get it?

As CodeMirror mainly works with syntax analysis (tokens etc) I attempted to analyze the line tokens and combine it with the cursor data, but I thought to ask for something more thorough and clear.


Solution

  • A token's state contains the indented property, which provides such information for the token's indentation:

    var token = editor.getTokenAt(editor.getCursor());
    console.log(token.state.indented);