1
0
mirror of git://git.suckless.org/sbase synced 2024-12-22 23:13:44 +00:00
sbase/cols.c

95 lines
1.8 KiB
C
Raw Normal View History

2012-05-21 22:05:09 +00:00
/* See LICENSE file for copyright and license details. */
2015-02-14 20:02:41 +00:00
#include <sys/ioctl.h>
#include <limits.h>
#include <stdint.h>
2012-05-21 22:05:09 +00:00
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <unistd.h>
2012-05-21 22:05:09 +00:00
#include "text.h"
2014-12-05 21:32:08 +00:00
#include "utf.h"
2012-05-21 22:05:09 +00:00
#include "util.h"
static size_t chars = 65;
2015-01-31 23:55:22 +00:00
static int cflag;
2012-05-21 22:05:09 +00:00
static struct linebuf b = EMPTY_LINEBUF;
static size_t n_columns;
static size_t n_rows;
2012-05-21 22:05:09 +00:00
2013-06-14 18:20:47 +00:00
static void
usage(void)
{
2014-12-08 15:07:19 +00:00
eprintf("usage: %s [-c chars] [file ...]\n", argv0);
2013-06-14 18:20:47 +00:00
}
2012-05-21 22:05:09 +00:00
int
main(int argc, char *argv[])
{
size_t i, l, col, len, bytes, maxlen = 0;
struct winsize w;
2012-05-21 22:05:09 +00:00
FILE *fp;
char *p;
2012-05-21 22:05:09 +00:00
2013-06-14 18:20:47 +00:00
ARGBEGIN {
case 'c':
cflag = 1;
chars = estrtonum(EARGF(usage()), 3, MIN(LLONG_MAX, SIZE_MAX));
2013-06-14 18:20:47 +00:00
break;
default:
usage();
} ARGEND;
2012-05-21 22:05:09 +00:00
if (cflag == 0) {
if ((p = getenv("COLUMNS")))
chars = estrtonum(p, 1, MIN(LLONG_MAX, SIZE_MAX));
else if (!ioctl(STDOUT_FILENO, TIOCGWINSZ, &w) && w.ws_col > 0)
chars = w.ws_col;
}
if (argc == 0) {
2012-05-21 22:05:09 +00:00
getlines(stdin, &b);
} else for (; argc > 0; argc--, argv++) {
if (!(fp = fopen(argv[0], "r")))
2013-06-14 18:20:47 +00:00
eprintf("fopen %s:", argv[0]);
2012-05-21 22:05:09 +00:00
getlines(fp, &b);
fclose(fp);
}
for (l = 0; l < b.nlines; ++l) {
2014-12-05 21:32:08 +00:00
len = utflen(b.lines[l]);
bytes = strlen(b.lines[l]);
2015-01-31 23:55:22 +00:00
if (len > 0 && b.lines[l][bytes - 1] == '\n') {
b.lines[l][bytes - 1] = '\0';
2014-12-05 21:32:08 +00:00
--len;
}
if (len > maxlen)
2012-05-21 22:05:09 +00:00
maxlen = len;
if (maxlen > (chars - 1) / 2)
2012-05-21 22:05:09 +00:00
break;
}
n_columns = (chars + 1) / (maxlen + 1);
if (n_columns <= 1) {
for (l = 0; l < b.nlines; ++l) {
2012-05-21 22:05:09 +00:00
fputs(b.lines[l], stdout);
}
2014-10-02 22:46:04 +00:00
return 0;
2012-05-21 22:05:09 +00:00
}
n_rows = (b.nlines + (n_columns - 1)) / n_columns;
for (i = 0; i < n_rows; ++i) {
for (l = i, col = 1; l < b.nlines; l += n_rows, ++col) {
2014-12-05 21:32:08 +00:00
len = utflen(b.lines[l]);
2012-05-21 22:05:09 +00:00
fputs(b.lines[l], stdout);
if (col < n_columns)
printf("%*s", (int)(maxlen + 1 - len), "");
2012-05-21 22:05:09 +00:00
}
fputs("\n", stdout);
}
2014-10-02 22:46:04 +00:00
return 0;
2012-05-21 22:05:09 +00:00
}