Skip to content

Instantly share code, notes, and snippets.

@lufia
Created March 5, 2019 09:17
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save lufia/2178a27e922a91580cbcf60dddf1fb82 to your computer and use it in GitHub Desktop.
Save lufia/2178a27e922a91580cbcf60dddf1fb82 to your computer and use it in GitHub Desktop.
removes escape sequences
#include <u.h>
#include <libc.h>
#include <bio.h>
static void
usage(void)
{
fprint(2, "usage: %s [file ...]\n", argv0);
exits("usage");
}
enum {
ESC = 0x1b,
};
static int
skipnum(Biobuf *rbuf)
{
int c;
while((c=Bgetc(rbuf)) != Beof && isdigit(c))
;
return c;
}
static void
skipcsi(Biobuf *rbuf)
{
/* CSI */
if(skipnum(rbuf) == ';')
skipnum(rbuf);
}
static void
skipstr(Biobuf *rbuf)
{
int c;
while((c=Bgetc(rbuf)) != Beof)
if(c == ESC && (c=Bgetc(rbuf)) == '\\')
break;
}
static void
skiposc(Biobuf *rbuf)
{
/* OSC Ps;Pt ST */
skipnum(rbuf);
skipstr(rbuf);
}
static void
unesc(int fd)
{
Biobuf rbuf, wbuf;
int c;
Binit(&rbuf, fd, OREAD);
Binit(&wbuf, 1, OWRITE);
while((c=Bgetc(&rbuf)) != Beof){
if(c != ESC){
Bputc(&wbuf, c);
continue;
}
c = Bgetc(&rbuf);
switch(c){
case Beof:
fprint(2, "warning: EOF following ESC\n");
break;
case 'N':
case 'O':
case 'X':
case 'c':
// skip one char
break;
case 'P':
// DCS
break;
case '[': // CSI
skipcsi(&rbuf);
break;
case ']': // OSC
skiposc(&rbuf);
break;
case '^':
// PM
break;
case '_':
// APC
break;
}
}
Bflush(&wbuf);
Bterm(&rbuf);
Bterm(&wbuf);
}
void
main(int argc, char **argv)
{
int i, fd;
ARGBEGIN {
default:
usage();
} ARGEND
if(argc == 0)
unesc(0);
else
for(i = 0; i < argc; i++){
fd = open(argv[i], OREAD);
if(fd < 0)
sysfatal("can't open: %r");
unesc(fd);
close(fd);
}
exits(nil);
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment