2011-06-08 16:30:33 -04:00
|
|
|
/* See LICENSE file for copyright and license details. */
|
|
|
|
#include <ctype.h>
|
|
|
|
#include <stdbool.h>
|
|
|
|
#include <stdio.h>
|
|
|
|
#include <stdlib.h>
|
|
|
|
#include <unistd.h>
|
|
|
|
#include "text.h"
|
|
|
|
#include "util.h"
|
|
|
|
|
2011-06-21 00:05:37 -04:00
|
|
|
static void fold(FILE *, long);
|
2011-06-08 16:30:33 -04:00
|
|
|
static void foldline(const char *, long);
|
|
|
|
|
|
|
|
static bool bflag = false;
|
|
|
|
static bool sflag = false;
|
|
|
|
|
|
|
|
int
|
|
|
|
main(int argc, char *argv[])
|
|
|
|
{
|
2011-06-10 00:41:40 -04:00
|
|
|
char c;
|
2011-06-08 16:30:33 -04:00
|
|
|
long width = 80;
|
|
|
|
FILE *fp;
|
|
|
|
|
|
|
|
while((c = getopt(argc, argv, "bsw:")) != -1)
|
|
|
|
switch(c) {
|
|
|
|
case 'b':
|
|
|
|
bflag = true;
|
|
|
|
break;
|
|
|
|
case 's':
|
|
|
|
sflag = true;
|
|
|
|
break;
|
|
|
|
case 'w':
|
2011-06-10 09:55:01 -04:00
|
|
|
width = estrtol(optarg, 0);
|
2011-06-08 16:30:33 -04:00
|
|
|
break;
|
|
|
|
default:
|
|
|
|
exit(EXIT_FAILURE);
|
|
|
|
}
|
|
|
|
if(optind == argc)
|
2011-06-21 00:05:37 -04:00
|
|
|
fold(stdin, width);
|
2011-06-08 16:30:33 -04:00
|
|
|
else for(; optind < argc; optind++) {
|
|
|
|
if(!(fp = fopen(argv[optind], "r")))
|
|
|
|
eprintf("fopen %s:", argv[optind]);
|
2011-06-21 00:05:37 -04:00
|
|
|
fold(fp, width);
|
2011-06-08 16:30:33 -04:00
|
|
|
fclose(fp);
|
|
|
|
}
|
|
|
|
return EXIT_SUCCESS;
|
|
|
|
}
|
|
|
|
|
|
|
|
void
|
2011-06-21 00:05:37 -04:00
|
|
|
fold(FILE *fp, long width)
|
2011-06-08 16:30:33 -04:00
|
|
|
{
|
|
|
|
char *buf = NULL;
|
|
|
|
size_t size = 0;
|
|
|
|
|
|
|
|
while(afgets(&buf, &size, fp))
|
|
|
|
foldline(buf, width);
|
|
|
|
free(buf);
|
|
|
|
}
|
|
|
|
|
|
|
|
void
|
|
|
|
foldline(const char *str, long width)
|
|
|
|
{
|
|
|
|
bool space;
|
2011-06-21 00:05:37 -04:00
|
|
|
long col, j;
|
|
|
|
size_t i = 0, n = 0;
|
2011-06-08 16:30:33 -04:00
|
|
|
|
2011-06-09 23:22:59 -04:00
|
|
|
do {
|
2011-06-08 16:30:33 -04:00
|
|
|
space = false;
|
|
|
|
for(j = i, col = 0; str[j] && col <= width; j++) {
|
|
|
|
if(!UTF8_POINT(str[j]) && !bflag)
|
|
|
|
continue;
|
|
|
|
if(sflag && isspace(str[j])) {
|
|
|
|
space = true;
|
|
|
|
n = j+1;
|
|
|
|
}
|
|
|
|
else if(!space)
|
|
|
|
n = j;
|
|
|
|
|
|
|
|
if(!bflag && iscntrl(str[j]))
|
|
|
|
switch(str[j]) {
|
|
|
|
case '\b':
|
|
|
|
col--;
|
|
|
|
break;
|
|
|
|
case '\r':
|
|
|
|
col = 0;
|
|
|
|
break;
|
|
|
|
case '\t':
|
|
|
|
col += (col+1) % 8;
|
|
|
|
break;
|
|
|
|
}
|
|
|
|
else
|
|
|
|
col++;
|
|
|
|
}
|
|
|
|
if(fwrite(&str[i], 1, n-i, stdout) != n-i)
|
|
|
|
eprintf("<stdout>: write error:");
|
|
|
|
if(str[n])
|
|
|
|
putchar('\n');
|
2011-06-09 23:22:59 -04:00
|
|
|
} while(str[i = n] && str[i] != '\n');
|
2011-06-08 16:30:33 -04:00
|
|
|
}
|