1
0
mirror of git://git.suckless.org/sbase synced 2024-12-23 23:43:33 +00:00
sbase/expand.c

99 lines
1.5 KiB
C
Raw Normal View History

/* See LICENSE file for copyright and license details. */
#include <stdio.h>
#include <stdlib.h>
#include "utf.h"
#include "util.h"
static int expand(const char *, FILE *, int);
static int iflag = 0;
2014-06-09 15:54:45 +00:00
static void
usage(void)
{
eprintf("usage: %s [-i] [-t n] [file...]\n", argv0);
}
int
main(int argc, char *argv[])
{
FILE *fp;
int tabstop = 8;
2014-11-21 17:53:22 +00:00
int ret = 0;
ARGBEGIN {
case 'i':
iflag = 1;
2014-06-09 15:54:45 +00:00
break;
case 't':
tabstop = estrtol(EARGF(usage()), 0);
if (!tabstop)
eprintf("tab size cannot be zero\n");
break;
default:
usage();
} ARGEND;
if (argc == 0) {
expand("<stdin>", stdin, tabstop);
} else {
for (; argc > 0; argc--, argv++) {
if (!(fp = fopen(argv[0], "r"))) {
weprintf("fopen %s:", argv[0]);
2014-11-21 17:53:22 +00:00
ret = 1;
continue;
}
expand(argv[0], fp, tabstop);
fclose(fp);
}
}
2014-11-21 17:53:22 +00:00
return ret;
}
static int
expand(const char *file, FILE *fp, int tabstop)
{
int col = 0;
Rune r;
int bol = 1;
for (;;) {
2014-11-21 16:20:15 +00:00
if (!readrune(file, fp, &r))
break;
switch (r) {
case '\t':
2014-06-09 15:54:45 +00:00
if (bol || !iflag) {
do {
col++;
putchar(' ');
} while (col % tabstop);
2014-06-09 15:54:45 +00:00
} else {
putchar('\t');
2014-06-09 15:54:45 +00:00
col += tabstop - col % tabstop;
}
break;
case '\b':
if (col)
col--;
bol = 0;
2014-11-21 16:34:44 +00:00
writerune("<stdout>", stdout, &r);
break;
case '\n':
col = 0;
bol = 1;
2014-11-21 16:34:44 +00:00
writerune("<stdout>", stdout, &r);
break;
default:
col++;
if (r != ' ')
bol = 0;
2014-11-21 16:34:44 +00:00
writerune("<stdout>", stdout, &r);
break;
}
}
return 0;
}