@param {Doc} doc @param {{ printWidth: number, endOfLine: EndOfLineOption, } & IndentOptions} options @returns
(doc, options)
| 177 | @returns |
| 178 | */ |
| 179 | function printDocToString(doc, options) { |
| 180 | /** @type GroupModeMap */ |
| 181 | const groupModeMap = Object.create(null); |
| 182 | |
| 183 | const width = options.printWidth; |
| 184 | const newLine = convertEndOfLineOptionToCharacter(options.endOfLine); |
| 185 | let position = 0; |
| 186 | // commands is basically a stack. We've turned a recursive call into a |
| 187 | // while loop which is much faster. The while loop below adds new |
| 188 | // commands to the array instead of recursively calling `print`. |
| 189 | /** @type Command[] */ |
| 190 | const commands = [{ indent: ROOT_INDENT, mode: MODE_BREAK, doc }]; |
| 191 | let shouldRemeasure = false; |
| 192 | /** @type Command[] */ |
| 193 | const lineSuffix = []; |
| 194 | |
| 195 | const result = new PrintResult(); |
| 196 | |
| 197 | propagateBreaks(doc); |
| 198 | |
| 199 | while (commands.length > 0) { |
| 200 | const { indent, mode, doc } = commands.pop(); |
| 201 | switch (getDocType(doc)) { |
| 202 | case DOC_TYPE_STRING: { |
| 203 | const formatted = |
| 204 | newLine !== "\n" ? doc.replaceAll("\n", newLine) : doc; |
| 205 | // Plugins may print single string, should skip measure the width |
| 206 | if (formatted) { |
| 207 | result.write(formatted); |
| 208 | if (commands.length > 0) { |
| 209 | position += getStringWidth(formatted); |
| 210 | } |
| 211 | } |
| 212 | break; |
| 213 | } |
| 214 | |
| 215 | case DOC_TYPE_ARRAY: |
| 216 | for (let index = doc.length - 1; index >= 0; index--) { |
| 217 | commands.push({ indent, mode, doc: doc[index] }); |
| 218 | } |
| 219 | break; |
| 220 | |
| 221 | case DOC_TYPE_CURSOR: |
| 222 | result.markPosition(); |
| 223 | break; |
| 224 | |
| 225 | case DOC_TYPE_INDENT: |
| 226 | commands.push({ |
| 227 | indent: makeIndent(indent, options), |
| 228 | mode, |
| 229 | doc: doc.contents, |
| 230 | }); |
| 231 | break; |
| 232 | |
| 233 | case DOC_TYPE_ALIGN: |
| 234 | commands.push({ |
| 235 | indent: makeAlign(indent, doc.n, options), |
| 236 | mode, |
nothing calls this directly
no test coverage detected
searching dependent graphs…