diff options
Diffstat (limited to 'util/ansi.js')
-rw-r--r-- | util/ansi.js | 34 |
1 files changed, 33 insertions, 1 deletions
diff --git a/util/ansi.js b/util/ansi.js index 2ae5166..4e8abb0 100644 --- a/util/ansi.js +++ b/util/ansi.js @@ -154,7 +154,12 @@ export function disableAlternateScreen() { } export function measureColumns(text) { - // Returns the number of columns the given text takes. + // Returns the number of columns the given text takes. Accounts for escape + // codes (by not including them in the returned width). + + if (text.includes(ESC)) { + text = text.replace(new RegExp(String.raw`${ESC}\[\??[0-9;]*.`, 'g'), '') + } return wcwidth(text) } @@ -174,6 +179,33 @@ export function trimToColumns(text, cols) { return out } +export function wrapToColumns(text, cols) { + // Wraps a string into separate lines. Returns an array of strings, for + // each line of the text. + + const lines = [] + const words = text.split(' ') + + let curLine = words[0] + let curColumns = measureColumns(curLine) + + for (const word of words.slice(1)) { + const wordColumns = measureColumns(word) + if (curColumns + wordColumns > cols) { + lines.push(curLine) + curLine = word + curColumns = wordColumns + } else { + curLine += ' ' + word + curColumns += 1 + wordColumns + } + } + + lines.push(curLine) + + return lines +} + export function isANSICommand(buffer, code = null) { return ( buffer[0] === 0x1b && buffer[1] === 0x5b && |