diff options
author | (quasar) nebula <qznebula@protonmail.com> | 2023-05-13 13:20:59 -0300 |
---|---|---|
committer | (quasar) nebula <qznebula@protonmail.com> | 2023-05-13 13:20:59 -0300 |
commit | 34b7ff22766bae0e4b1b3121bd63d037c27285c7 (patch) | |
tree | f2f66a17c67bdf9be0b1576b28ffd0cf107b483c /util/ansi.js | |
parent | 684e369c7b01b4c69995fc604ef33919077ffdf5 (diff) | |
parent | a37d6be77261b2aae25c4235dcb38dd7b1bb60b1 (diff) |
Merge remote-tracking branch 'notabug/master'
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 && |