wordwrap.c 1009 B

12345678910111213141516171819202122232425262728293031323334353637
  1. /*
  2. * Function to wrap text to a fixed number of columns.
  3. *
  4. * Currently, assumes the text is in a single-byte character set,
  5. * because it's only used to display host key prompt messages.
  6. * Extending to Unicode and using wcwidth() could be an extension.
  7. */
  8. #include "misc.h"
  9. void wordwrap(BinarySink *bs, ptrlen input, size_t maxwid)
  10. {
  11. size_t col = 0;
  12. while (true) {
  13. ptrlen word = ptrlen_get_word(&input, " ");
  14. if (!word.len)
  15. break;
  16. /* At the start of a line, any word is legal, even if it's
  17. * overlong, because we have to display it _somehow_ and
  18. * wrapping to the next line won't make it any better. */
  19. if (col > 0) {
  20. size_t newcol = col + 1 + word.len;
  21. if (newcol <= maxwid) {
  22. put_byte(bs, ' ');
  23. col++;
  24. } else {
  25. put_byte(bs, '\n');
  26. col = 0;
  27. }
  28. }
  29. put_datapl(bs, word);
  30. col += word.len;
  31. }
  32. }