UNPKG

3 kBJavaScriptView Raw
1"use strict";
2/**
3 * @license
4 * Copyright (c) 2017 The Polymer Project Authors. All rights reserved.
5 * This code may only be used under the BSD style license found at
6 * http://polymer.github.io/LICENSE.txt
7 * The complete set of authors may be found at
8 * http://polymer.github.io/AUTHORS.txt
9 * The complete set of contributors may be found at
10 * http://polymer.github.io/CONTRIBUTORS.txt
11 * Code distributed by Google as part of the polymer project is also
12 * subject to an additional IP rights grant found at
13 * http://polymer.github.io/PATENTS.txt
14 */
15Object.defineProperty(exports, "__esModule", { value: true });
16function underlineCode(sourceRange, parsedDocument, colorizer = (s) => s, maxLines) {
17 const relativeRange = parsedDocument.absoluteToRelativeSourceRange(sourceRange);
18 const code = _getRelavantSourceCode(relativeRange, parsedDocument);
19 if (!code) {
20 return undefined;
21 }
22 const outputLines = [];
23 const lines = code.split('\n', maxLines);
24 let lineNum = relativeRange.start.line;
25 for (const line of lines) {
26 outputLines.push(line);
27 outputLines.push(colorizer(getSquiggleUnderline(line, lineNum, relativeRange)));
28 lineNum++;
29 }
30 return outputLines.join('\n');
31}
32exports.underlineCode = underlineCode;
33function _getRelavantSourceCode(relativeRange, parsedDocument) {
34 if (parsedDocument === null) {
35 return;
36 }
37 const startOffset = parsedDocument.sourcePositionToOffset({ column: 0, line: relativeRange.start.line });
38 let endOffset;
39 if (parsedDocument.newlineIndexes.length === relativeRange.end.line) {
40 endOffset = parsedDocument.sourcePositionToOffset({ column: 0, line: relativeRange.end.line + 1 });
41 }
42 else {
43 endOffset = parsedDocument.sourcePositionToOffset({ column: -1, line: relativeRange.end.line + 1 });
44 }
45 return parsedDocument.contents.slice(startOffset, endOffset);
46}
47function getSquiggleUnderline(lineText, lineNum, sourceRange) {
48 // We're on a middle line of a multiline range. Squiggle the entire line.
49 if (lineNum !== sourceRange.start.line && lineNum !== sourceRange.end.line) {
50 return '~'.repeat(lineText.length);
51 }
52 // The tricky case. Might be the start of a multiline range, or it might just
53 // be a one-line range.
54 if (lineNum === sourceRange.start.line) {
55 const startColumn = sourceRange.start.column;
56 const endColumn = sourceRange.end.line === sourceRange.start.line ?
57 sourceRange.end.column :
58 lineText.length;
59 const prefix = lineText.slice(0, startColumn).replace(/[^\t]/g, ' ');
60 if (startColumn === endColumn) {
61 return prefix + '~'; // always draw at least one squiggle
62 }
63 return prefix + '~'.repeat(endColumn - startColumn);
64 }
65 // We're on the end line of a multiline range. Just squiggle up to the end
66 // column.
67 return '~'.repeat(sourceRange.end.column);
68}
69//# sourceMappingURL=code-printer.js.map
\No newline at end of file