UNPKG

squarier

Version:

This package can help you format text in a square like manner.

67 lines 2.48 kB
"use strict"; Object.defineProperty(exports, "__esModule", { value: true }); exports.Parser = void 0; var Token_1 = require("../core/Token"); var TokenMatrix_1 = require("../core/TokenMatrix"); var Parser = /** @class */ (function () { function Parser() { } Parser.prototype.parse = function (str) { var _this = this; var rows = str.split('\n'); var leftSpacesCount = this.countSpacesBeforeFirstWord(rows[0]); var matrix = rows.map(function (line) { return _this.parseLine(line); }); var tokenMatrix = new TokenMatrix_1.TokenMatrix(matrix); tokenMatrix.setLineStartPadding(leftSpacesCount); return tokenMatrix; }; Parser.prototype.countSpacesBeforeFirstWord = function (line) { return Math.max(line.split('').findIndex(function (el) { return el !== ' '; }), 0); }; Parser.prototype.convertTabsToOneSpace = function (str) { return str.replace(/\t/g, ' '); }; /** * Return a array of token, * takes into account string and string escape characters */ Parser.prototype.parseLine = function (line) { line = this.convertTabsToOneSpace(line); var tokens = []; var tmp = ''; var isInString = false; for (var i = 0; i < line.length; i++) { var ch = line[i]; var prevCh = line[i - 1]; var nextCh = line[i + 1]; if (!isInString && ch === '/' && nextCh === '/') { // This mean we are a comment, and we all the comment should be one token // till the end of the line if (tmp) { tokens.push(new Token_1.Token(tmp)); } var comment = line.slice(i); tokens.push(new Token_1.Token(comment)); return tokens; } // If we not in a double quote string, we should treat white space as separators if (ch === ' ' && !isInString) { if (tmp) { tokens.push(new Token_1.Token(tmp)); } tmp = ''; } else { if (ch === '"' && prevCh !== '\\') { isInString = !isInString; } tmp += ch; } } tokens.push(new Token_1.Token(tmp)); return tokens; }; return Parser; }()); exports.Parser = Parser; //# sourceMappingURL=Parser.js.map