ECMAScript code indenter based on Esprima AST and Rocambole
ECMAScript code indenter based on Esprima AST
work in progress
This project started as an experiment while trying to decouple the indent logic from the other token manipulations on esformatter. It's an attempt at finding a simpler solution to the problem while still maintaining the flexibility.
By building it as a separate tool it is also simpler to reuse it for other projects and will make some of the tests simpler to write (since we can test the indentation separately).
This tool uses a rocambole generated AST to traverse tokens inside each node and add/remove indent based on the node type.
The algorithm is very straightforward, it simple loops through all nodes
(starting from the leaf) up to the program root, scanning each line start for
WhiteSpace and adding/removing/editing
Indent tokens as needed.
Transforms AST in-place, adding
Indent tokens at the beginning of each line
that needs indentation.
var esi = require'esindent';esindenttransformastvalue: ' 'ArrayExpression: 1ChainedMemberExpression: 1MultipleVariableDeclaration: 1ObjectExpression: 1SwitchCase: 1SwitchStatement: 1EmptyStatement: 0ForStatement: 1IfStatement: 1FunctionDeclaration: 1FunctionExpression: 1TryStatement: 1DoWhileStatement: 1;// to get the result as a string simply call ast.toString()console.log asttoString ;
WhiteSpace tokens that are at the beginning of the lines (probably
from original indent or trailing white spaces). Also remove
that doesn't have the
level property or that are not preceded by a line
Set the indent options. Useful for cases where you want to use
transformNode() or call
transform() multiple times in a row (so you don't
need to set the options multiple times). - Used internally by
Released under the MIT License