From fe8f84e2da4ce265497d257f8a74753dfa08887f Mon Sep 17 00:00:00 2001 From: Rob Landley Date: Wed, 28 Oct 2026 13:46:59 -0500 Subject: [PATCH] Factor out un-unescape() logic into rescape(), test the full range of sed l uses (and more ls -b), and fill out escape/wrap code in sed. --- lib/lib.c | 7 +++++++ lib/lib.h | 1 + toys/posix/ls.c | 12 +++++------- toys/posix/sed.c | 40 ++++++++++++++++++++-------------------- 4 files changed, 33 insertions(+), 27 deletions(-) diff --git a/lib/lib.c b/lib/lib.c index 637fbafe..fe9e0135 100644 --- a/lib/lib.c +++ b/lib/lib.c @@ -460,6 +460,13 @@ char *chomp(char *s) return s; } +// return escape letter that produces a low ascii char, or zero +int rescape(char c) +{ + return "\0\\abefnrtv"[1+stridx("\\\a\b\e\f\n\r\t\v", c)]; +} + +// convert char after \ to escaped version, or return 0 if unrecognized int unescape(char c) { return "\0\\\a\b\e\f\n\r\t\v"[1+stridx("\\abefnrtv", c)]; diff --git a/lib/lib.h b/lib/lib.h index 90f6c877..3fd6491c 100644 --- a/lib/lib.h +++ b/lib/lib.h @@ -224,6 +224,7 @@ int utf8towc(unsigned *wc, char *str, unsigned len); char *strlower(char *s); char *strafter(char *haystack, char *needle); char *chomp(char *s); +int rescape(char c); int unescape(char c); int unescape2(char *out, char **in, int echo); char *strend(char *str, char *suffix); diff --git a/toys/posix/ls.c b/toys/posix/ls.c index 7a8dfd27..ead2e923 100644 --- a/toys/posix/ls.c +++ b/toys/posix/ls.c @@ -74,7 +74,7 @@ GLOBALS( // Callback from crunch_str to represent unprintable chars static int crunch_qb(FILE *out, int cols, int wc) { - int len = 1; + int len = 1, ii; char buf[32]; if (FLAG(q)) *buf = '?'; @@ -84,15 +84,13 @@ static int crunch_qb(FILE *out, int cols, int wc) else if ((len = wcrtomb(buf, wc, 0) ) == -1) len = 1; if (FLAG(b)) { char *to = buf, *from = buf+24; - int i, j; memcpy(from, to, 8); - for (i = 0; iarg1+(char *)command; emit(str, strlen(str), 1); } else if (c=='l') { - int i, x, off; - - if (!TT.xx) { - terminal_size(&TT.xx, 0); - if (!TT.xx) TT.xx = 80; - if (TT.xx > sizeof(toybuf)-10) TT.xx = sizeof(toybuf)-10; - if (TT.xx > 4) TT.xx -= 4; - } + int i, x, tilt, lit, off; + + // Don't use terminal size because stdin usually a pipe or file + for (i = off = tilt = 0; i126) + off += sprintf(toybuf+off, "%03o", x); + else { + if (off<70) off--; + else lit++; + toybuf[off++] = x; + } - for (i = off = 0; i= TT.xx) { - toybuf[off++] = '\\'; - emit(toybuf, off, 1); - off = 0; + if (off>=70) { + emit(toybuf, tilt+1, 1); + tilt += lit; + memmove(toybuf, toybuf+tilt, off-=tilt); } - x = stridx("\\\a\b\f\r\t\v\n", line[i]); - if (x != -1) { - toybuf[off++] = '\\'; - toybuf[off++] = "\\abfrtvn"[x]; - } else if (line[i] >= ' ') toybuf[off++] = line[i]; - else off += sprintf(toybuf+off, "\\%03o", line[i]); } toybuf[off++] = '$'; emit(toybuf, off, 1); -- 2.39.5