]>
Commit | Line | Data |
---|---|---|
b9571307 DI |
1 | /** |
2 | * @license MIT | |
3 | */ | |
4 | ||
5 | // TODO: This module should be merged into a buffer or buffer line class | |
6 | ||
7 | const LINE_DATA_CHAR_INDEX = 1; | |
8 | const LINE_DATA_WIDTH_INDEX = 2; | |
9 | ||
10 | /** | |
11 | * Translates a buffer line to a string, with optional start and end columns. | |
12 | * Wide characters will count as two columns in the resulting string. This | |
13 | * function is useful for getting the actual text underneath the raw selection | |
14 | * position. | |
15 | * @param line The line being translated. | |
16 | * @param trimRight Whether to trim whitespace to the right. | |
17 | * @param startCol The column to start at. | |
18 | * @param endCol The column to end at. | |
19 | */ | |
20 | export function translateBufferLineToString(line: any, trimRight: boolean, startCol: number = 0, endCol: number = null): string { | |
21 | // Get full line | |
22 | let lineString = ''; | |
23 | let widthAdjustedStartCol = startCol; | |
24 | let widthAdjustedEndCol = endCol; | |
25 | for (let i = 0; i < line.length; i++) { | |
26 | const char = line[i]; | |
27 | lineString += char[LINE_DATA_CHAR_INDEX]; | |
28 | // Adjust start and end cols for wide characters if they affect their | |
29 | // column indexes | |
30 | if (char[LINE_DATA_WIDTH_INDEX] === 0) { | |
31 | if (startCol >= i) { | |
32 | widthAdjustedStartCol--; | |
33 | } | |
34 | if (endCol >= i) { | |
35 | widthAdjustedEndCol--; | |
36 | } | |
37 | } | |
38 | } | |
39 | ||
40 | // Calculate the final end col by trimming whitespace on the right of the | |
41 | // line if needed. | |
42 | let finalEndCol = widthAdjustedEndCol || line.length; | |
43 | if (trimRight) { | |
44 | const rightWhitespaceIndex = lineString.search(/\s+$/); | |
45 | if (rightWhitespaceIndex !== -1) { | |
46 | finalEndCol = Math.min(finalEndCol, rightWhitespaceIndex); | |
47 | } | |
48 | // Return the empty string if only trimmed whitespace is selected | |
49 | if (finalEndCol <= widthAdjustedStartCol) { | |
50 | return ''; | |
51 | } | |
52 | } | |
53 | ||
54 | return lineString.substring(widthAdjustedStartCol, finalEndCol); | |
55 | } |