| 288 | * ANSI escape sequences do not add to the string length. |
| 289 | */ |
| 290 | export const wrapAnsiString = ( |
| 291 | string: string, |
| 292 | width: number | undefined |
| 293 | ): string[] => { |
| 294 | // if the terminal width is zero, don't bother word-wrapping |
| 295 | if (width === undefined || width <= 0) return [string]; |
| 296 | |
| 297 | const ANSI_REGEXP = /\x1B\[[0-9;]*[A-Za-z]/g; |
| 298 | const tokens: ['string' | 'ansi', string][] = []; |
| 299 | let lastIndex = 0; |
| 300 | let match; |
| 301 | |
| 302 | while ((match = ANSI_REGEXP.exec(string))) { |
| 303 | const ansi = match[0]; |
| 304 | const index = match['index']; |
| 305 | if (index != lastIndex) { |
| 306 | tokens.push(['string', string.slice(lastIndex, index)]); |
| 307 | } |
| 308 | tokens.push(['ansi', ansi]); |
| 309 | lastIndex = index + ansi.length; |
| 310 | } |
| 311 | |
| 312 | if (lastIndex != string.length - 1) { |
| 313 | tokens.push(['string', string.slice(lastIndex, string.length)]); |
| 314 | } |
| 315 | |
| 316 | let lastLineLength = 0; |
| 317 | |
| 318 | return tokens.reduce( |
| 319 | (lines, [kind, token]) => { |
| 320 | if (kind === 'string') { |
| 321 | if (lastLineLength + token.length > width) { |
| 322 | while (token.length) { |
| 323 | const chunk = token.slice(0, width - lastLineLength); |
| 324 | const remaining = token.slice(width - lastLineLength, token.length); |
| 325 | lines[lines.length - 1] += chunk; |
| 326 | lastLineLength += chunk.length; |
| 327 | token = remaining; |
| 328 | if (token.length) { |
| 329 | lines.push(''); |
| 330 | lastLineLength = 0; |
| 331 | } |
| 332 | } |
| 333 | } else { |
| 334 | lines[lines.length - 1] += token; |
| 335 | lastLineLength += token.length; |
| 336 | } |
| 337 | } else { |
| 338 | lines[lines.length - 1] += token; |
| 339 | } |
| 340 | |
| 341 | return lines; |
| 342 | }, |
| 343 | [''] |
| 344 | ); |
| 345 | }; |
| 346 | |
| 347 | // From https://github.com/chalk/supports-color |