UNPKG

ts-simple-ast

Version:

TypeScript compiler wrapper for AST navigation and code generation.

48 lines (46 loc) 2.16 kB
"use strict"; Object.defineProperty(exports, "__esModule", { value: true }); const ts = require("typescript"); const utils_1 = require("./../utils"); /** * Replaces text in a source file. Good for renaming identifiers. Not good for creating new nodes! * @param sourceFile - Source file to replace in. * @param replaceStart - Start of where to replace. * @param replaceEnd - End of where to replace. * @param newText - The new text to go in place. */ function replaceNodeText(sourceFile, replaceStart, replaceEnd, newText) { const difference = newText.length - (replaceEnd - replaceStart); replaceForNode(sourceFile); sourceFile.global.resetProgram(); sourceFile.setIsSaved(false); function replaceForNode(node) { const currentStart = utils_1.TypeGuards.isSourceFile(node) ? 0 : node.getStart(); const compilerNode = node.compilerNode; // do the children first so that the underlying _children array is filled in based on the source file for (const child of node.getChildren()) { replaceForNode(child); } if (node.containsRange(replaceStart, replaceEnd)) { const text = compilerNode.text; if (text != null) { const relativeStart = replaceStart - currentStart; const relativeEnd = replaceEnd - currentStart; const newNodeText = text.substring(0, relativeStart) + newText + text.substring(relativeEnd); if (compilerNode.kind === ts.SyntaxKind.SourceFile) compilerNode.text = newNodeText; else if (compilerNode.escapedText != null) compilerNode.escapedText = newNodeText; else utils_1.Logger.warn("Unhandled scenario when replacing node text: Node did not have an escapedText property."); } compilerNode.end += difference; } else if (currentStart > replaceStart) { compilerNode.pos += difference; compilerNode.end += difference; } } } exports.replaceNodeText = replaceNodeText; //# sourceMappingURL=replaceNodeText.js.map