| 327 | } |
| 328 | |
| 329 | std::string FormatParagraph(const std::string& in, size_t width, size_t indent) |
| 330 | { |
| 331 | assert(width >= indent); |
| 332 | std::stringstream out; |
| 333 | size_t ptr = 0; |
| 334 | size_t indented = 0; |
| 335 | while (ptr < in.size()) |
| 336 | { |
| 337 | size_t lineend = in.find_first_of('\n', ptr); |
| 338 | if (lineend == std::string::npos) { |
| 339 | lineend = in.size(); |
| 340 | } |
| 341 | const size_t linelen = lineend - ptr; |
| 342 | const size_t rem_width = width - indented; |
| 343 | if (linelen <= rem_width) { |
| 344 | out << in.substr(ptr, linelen + 1); |
| 345 | ptr = lineend + 1; |
| 346 | indented = 0; |
| 347 | } else { |
| 348 | size_t finalspace = in.find_last_of(" \n", ptr + rem_width); |
| 349 | if (finalspace == std::string::npos || finalspace < ptr) { |
| 350 | // No place to break; just include the entire word and move on |
| 351 | finalspace = in.find_first_of("\n ", ptr); |
| 352 | if (finalspace == std::string::npos) { |
| 353 | // End of the string, just add it and break |
| 354 | out << in.substr(ptr); |
| 355 | break; |
| 356 | } |
| 357 | } |
| 358 | out << in.substr(ptr, finalspace - ptr) << "\n"; |
| 359 | if (in[finalspace] == '\n') { |
| 360 | indented = 0; |
| 361 | } else if (indent) { |
| 362 | out << std::string(indent, ' '); |
| 363 | indented = indent; |
| 364 | } |
| 365 | ptr = finalspace + 1; |
| 366 | } |
| 367 | } |
| 368 | return out.str(); |
| 369 | } |
| 370 | |
| 371 | /** Upper bound for mantissa. |
| 372 | * 10^18-1 is the largest arbitrary decimal that will fit in a signed 64-bit integer. |