You can not select more than 25 topics Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.
 
 
 

58 lines
1.3 KiB

  1. /* $Id: strutl.c,v 1.1 1999/11/21 22:01:04 tausq Exp $ */
  2. #include "strutl.h"
  3. #include <string.h>
  4. #include <stdlib.h>
  5. #include "macros.h"
  6. char *reflowtext(int width, char *txt)
  7. {
  8. /* A simple greedy text formatting algorithm. Tries to put as many characters as possible
  9. * on a line without going over width
  10. *
  11. * Returns a malloc'ed string buffer that should be freed by the caller
  12. */
  13. char *buf;
  14. char *begin, *end;
  15. if (txt == NULL) return NULL;
  16. buf = MALLOC(strlen(txt) + strlen(txt) / width + 2);
  17. buf[0] = 0;
  18. begin = txt;
  19. while (*begin != 0) {
  20. end = begin;
  21. while (*end != 0 && *end != '\n' && end - begin < width) end++;
  22. if (end - begin < width) {
  23. /* don't need to wrap -- saw a newline or EOS */
  24. if (*end == 0) {
  25. strncat(buf, begin, end - begin);
  26. break;
  27. } else {
  28. strncat(buf, begin, end - begin);
  29. strcat(buf, "\n");
  30. begin = end + 1;
  31. }
  32. } else {
  33. /* wrap the text */
  34. end--;
  35. while (*end != ' ' && end > begin) end--;
  36. if (end != begin) {
  37. strncat(buf, begin, end - begin);
  38. strcat(buf, "\n");
  39. begin = end + 1;
  40. } else {
  41. /* this is where it gets gross.. nowhere to break the line */
  42. end = begin + width - 1;
  43. strncat(buf, begin, end - begin);
  44. strcat(buf, "\n");
  45. begin = end;
  46. }
  47. }
  48. }
  49. return buf;
  50. }