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.
 
 
 

72 lines
1.6 KiB

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