Skip to content

Commit 2faed06

Browse files
committed
simplify printw() with greedy algorithm
1 parent 104ef4d commit 2faed06

File tree

1 file changed

+18
-22
lines changed

1 file changed

+18
-22
lines changed

kirc.c

Lines changed: 18 additions & 22 deletions
Original file line numberDiff line numberDiff line change
@@ -76,37 +76,32 @@ con(void) {
7676
fcntl(conn, F_SETFL, O_NONBLOCK);
7777
}
7878

79+
/* printf, using hanging indent and greedy algortihm for word wrapping */
7980
static void
8081
printw(const char *format, ...) {
8182

82-
int s1 = 0, s2, len, i;
8383
va_list argptr;
84-
char line[BUFF + 1];
84+
char *tok, line[BUFF + 1];
85+
int len, i, s;
8586

8687
va_start(argptr, format);
8788
vsnprintf(line, BUFF + 1, format, argptr);
8889
va_end(argptr);
90+
/* need to pad first tok since strtok removes duplicate whitespace */
91+
for (i = 0; isspace(line[i]); i++) printf("%c", line[i]);
8992

90-
len = strlen(line);
91-
if (len <= cmax + gutl) printf("%s", &line[0]);
92-
else if (len > cmax + gutl) {
93+
s = cmax + gutl - (i - 1);
94+
//s = cmax - (i - 1);
9395

94-
for (i = gutl; i < cmax + gutl; i++) {
95-
if (isspace(line[i])) s1 = i;
96-
if (i == cmax + gutl - 1) printf("%-*.*s\n", s1, s1, &line[0]);
96+
for(tok = strtok(&line[i], " "); tok != NULL; tok = strtok(NULL, " ")) {
97+
len = strlen(tok);
98+
if ((len + 1) > s) {
99+
printf("\n%*.s%s ", gutl + 2, "", tok);
100+
s = cmax - (gutl + 2 + len);
97101
}
98-
99-
s2 = s1;
100-
101-
for (i = s1; line[i] != '\0'; i++) {
102-
if (isspace(line[i])) s2 = i;
103-
if ((i - s1) == (cmax - gutl)) {
104-
printf("%*s %-*.*s\n", gutl, "", s2 - s1, s2 - s1, &line[s1 + 1]);
105-
s1 = s2;
106-
}
107-
else if (line[i + 1] == '\0') {
108-
printf("%*s %-*.*s", gutl, "", i - s1, i - s1, &line[s1 + 1]);
109-
}
102+
else {
103+
printf("%s ", tok);
104+
s = s - (len + 1);
110105
}
111106
}
112107
}
@@ -137,7 +132,6 @@ pars(int sl, char *buf) {
137132
sscanf(buf_c, ":%[^ ] %[^:]:%[^\r]", pre, cmd, msg);
138133
sscanf(pre, "%[^!]!%[^@]@%s", nic, usr, hos);
139134
sscanf(cmd, "%[^#& ]%s", ltr, cha);
140-
141135
if (!strncmp(ltr, "001", 3)) raw("JOIN #%s\r\n", chan);
142136

143137
if (!strncmp(ltr, "QUIT", 4)) {
@@ -147,7 +141,9 @@ pars(int sl, char *buf) {
147141
printw("%*.*s \x1b[32;1m%s\x1b[0m\n", gutl, gutl, "-->", nic);
148142
}
149143
else {
150-
printw("\x1b[33;1m%*.*s\x1b[0m %s\n", gutl, gutl, nic, msg);
144+
printw("%*s\x1b[33;1m%-.*s\x1b[0m %s\n", \
145+
gutl-(strlen(nic) <= gutl ? strlen(nic) : gutl), \
146+
"", gutl, nic, msg);
151147
}
152148
}
153149
}

0 commit comments

Comments
 (0)