Skip to content
Open
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
30 changes: 25 additions & 5 deletions src/main.js
Original file line number Diff line number Diff line change
@@ -1,6 +1,5 @@
'use strict'

const breakword = require('breakword')
const stripAnsi = require('strip-ansi')
const wcwidth = require('wcwidth')

Expand Down Expand Up @@ -93,10 +92,31 @@ const wrap = (input, options) => {

// too long for an empty line, must be broken across lines
case lineLength < wordLength: {
const splitIndex = breakword(word, lineLength)
const splitWord = [...word]
words.unshift(splitWord.slice(0, splitIndex + 1).join(''))
words.splice(1, 0, splitWord.slice(splitIndex + 1).join(''))
// Break the whole word into line-sized chunks in a single pass.
// Re-queuing just the tail means the remainder is spread and measured
// again on every iteration, which is quadratic for a long word (a URL,
// token or base64 blob), so a ~125KB word takes tens of seconds.
const chunks = []
let chunk = ''
let chunkWidth = 0

for (const character of word) {
const characterWidth = wcwidth(character)
if (chunk !== '' && chunkWidth + characterWidth > lineLength) {
chunks.push(chunk)
chunk = ''
chunkWidth = 0
}
chunk += character
chunkWidth += characterWidth
}
if (chunk !== '') {
chunks.push(chunk)
}

// concat rather than unshift(...chunks): a long word can produce more
// chunks than the argument limit allows to be spread.
words = chunks.concat(words)
break
}

Expand Down