1import stringWidth from 'string-width'; 2import stripAnsi from 'strip-ansi'; 3import ansiStyles from 'ansi-styles'; 4 5const ESCAPES = new Set([ 6 '\u001B', 7 '\u009B', 8]); 9 10const END_CODE = 39; 11const ANSI_ESCAPE_BELL = '\u0007'; 12const ANSI_CSI = '['; 13const ANSI_OSC = ']'; 14const ANSI_SGR_TERMINATOR = 'm'; 15const ANSI_ESCAPE_LINK = `${ANSI_OSC}8;;`; 16 17const wrapAnsiCode = code => `${ESCAPES.values().next().value}${ANSI_CSI}${code}${ANSI_SGR_TERMINATOR}`; 18const wrapAnsiHyperlink = uri => `${ESCAPES.values().next().value}${ANSI_ESCAPE_LINK}${uri}${ANSI_ESCAPE_BELL}`; 19 20// Calculate the length of words split on ' ', ignoring 21// the extra characters added by ansi escape codes 22const wordLengths = string => string.split(' ').map(character => stringWidth(character)); 23 24// Wrap a long word across multiple rows 25// Ansi escape codes do not count towards length 26const wrapWord = (rows, word, columns) => { 27 const characters = [...word]; 28 29 let isInsideEscape = false; 30 let isInsideLinkEscape = false; 31 let visible = stringWidth(stripAnsi(rows[rows.length - 1])); 32 33 for (const [index, character] of characters.entries()) { 34 const characterLength = stringWidth(character); 35 36 if (visible + characterLength <= columns) { 37 rows[rows.length - 1] += character; 38 } else { 39 rows.push(character); 40 visible = 0; 41 } 42 43 if (ESCAPES.has(character)) { 44 isInsideEscape = true; 45 isInsideLinkEscape = characters.slice(index + 1).join('').startsWith(ANSI_ESCAPE_LINK); 46 } 47 48 if (isInsideEscape) { 49 if (isInsideLinkEscape) { 50 if (character === ANSI_ESCAPE_BELL) { 51 isInsideEscape = false; 52 isInsideLinkEscape = false; 53 } 54 } else if (character === ANSI_SGR_TERMINATOR) { 55 isInsideEscape = false; 56 } 57 58 continue; 59 } 60 61 visible += characterLength; 62 63 if (visible === columns && index < characters.length - 1) { 64 rows.push(''); 65 visible = 0; 66 } 67 } 68 69 // It's possible that the last row we copy over is only 70 // ansi escape characters, handle this edge-case 71 if (!visible && rows[rows.length - 1].length > 0 && rows.length > 1) { 72 rows[rows.length - 2] += rows.pop(); 73 } 74}; 75 76// Trims spaces from a string ignoring invisible sequences 77const stringVisibleTrimSpacesRight = string => { 78 const words = string.split(' '); 79 let last = words.length; 80 81 while (last > 0) { 82 if (stringWidth(words[last - 1]) > 0) { 83 break; 84 } 85 86 last--; 87 } 88 89 if (last === words.length) { 90 return string; 91 } 92 93 return words.slice(0, last).join(' ') + words.slice(last).join(''); 94}; 95 96// The wrap-ansi module can be invoked in either 'hard' or 'soft' wrap mode 97// 98// 'hard' will never allow a string to take up more than columns characters 99// 100// 'soft' allows long words to expand past the column length 101const exec = (string, columns, options = {}) => { 102 if (options.trim !== false && string.trim() === '') { 103 return ''; 104 } 105 106 let returnValue = ''; 107 let escapeCode; 108 let escapeUrl; 109 110 const lengths = wordLengths(string); 111 let rows = ['']; 112 113 for (const [index, word] of string.split(' ').entries()) { 114 if (options.trim !== false) { 115 rows[rows.length - 1] = rows[rows.length - 1].trimStart(); 116 } 117 118 let rowLength = stringWidth(rows[rows.length - 1]); 119 120 if (index !== 0) { 121 if (rowLength >= columns && (options.wordWrap === false || options.trim === false)) { 122 // If we start with a new word but the current row length equals the length of the columns, add a new row 123 rows.push(''); 124 rowLength = 0; 125 } 126 127 if (rowLength > 0 || options.trim === false) { 128 rows[rows.length - 1] += ' '; 129 rowLength++; 130 } 131 } 132 133 // In 'hard' wrap mode, the length of a line is never allowed to extend past 'columns' 134 if (options.hard && lengths[index] > columns) { 135 const remainingColumns = (columns - rowLength); 136 const breaksStartingThisLine = 1 + Math.floor((lengths[index] - remainingColumns - 1) / columns); 137 const breaksStartingNextLine = Math.floor((lengths[index] - 1) / columns); 138 if (breaksStartingNextLine < breaksStartingThisLine) { 139 rows.push(''); 140 } 141 142 wrapWord(rows, word, columns); 143 continue; 144 } 145 146 if (rowLength + lengths[index] > columns && rowLength > 0 && lengths[index] > 0) { 147 if (options.wordWrap === false && rowLength < columns) { 148 wrapWord(rows, word, columns); 149 continue; 150 } 151 152 rows.push(''); 153 } 154 155 if (rowLength + lengths[index] > columns && options.wordWrap === false) { 156 wrapWord(rows, word, columns); 157 continue; 158 } 159 160 rows[rows.length - 1] += word; 161 } 162 163 if (options.trim !== false) { 164 rows = rows.map(row => stringVisibleTrimSpacesRight(row)); 165 } 166 167 const pre = [...rows.join('\n')]; 168 169 for (const [index, character] of pre.entries()) { 170 returnValue += character; 171 172 if (ESCAPES.has(character)) { 173 const {groups} = new RegExp(`(?:\\${ANSI_CSI}(?<code>\\d+)m|\\${ANSI_ESCAPE_LINK}(?<uri>.*)${ANSI_ESCAPE_BELL})`).exec(pre.slice(index).join('')) || {groups: {}}; 174 if (groups.code !== undefined) { 175 const code = Number.parseFloat(groups.code); 176 escapeCode = code === END_CODE ? undefined : code; 177 } else if (groups.uri !== undefined) { 178 escapeUrl = groups.uri.length === 0 ? undefined : groups.uri; 179 } 180 } 181 182 const code = ansiStyles.codes.get(Number(escapeCode)); 183 184 if (pre[index + 1] === '\n') { 185 if (escapeUrl) { 186 returnValue += wrapAnsiHyperlink(''); 187 } 188 189 if (escapeCode && code) { 190 returnValue += wrapAnsiCode(code); 191 } 192 } else if (character === '\n') { 193 if (escapeCode && code) { 194 returnValue += wrapAnsiCode(escapeCode); 195 } 196 197 if (escapeUrl) { 198 returnValue += wrapAnsiHyperlink(escapeUrl); 199 } 200 } 201 } 202 203 return returnValue; 204}; 205 206// For each newline, invoke the method separately 207export default function wrapAnsi(string, columns, options) { 208 return String(string) 209 .normalize() 210 .replace(/\r\n/g, '\n') 211 .split('\n') 212 .map(line => exec(line, columns, options)) 213 .join('\n'); 214} 215