Skip to main content

Appendix A -- A Simple enriched-to-plain Translator in C

One of the major goals in the design of the text/enriched subtype of the text Content-Type is to make formatted text so simple that even text-only mailers will implement enriched-to-plain-text translators, thus increasing the likelihood that multifont text will become "safe" to use very widely. To demonstrate this simplicity, what follows is a simple C program that converts text/enriched input into plain text output. Note that the local newline convention (the single character represented by "\n") is assumed by this program, but that special CRLF handling might be necessary on some systems.

#include <stdio.h>
#include <ctype.h>

main() {
int c, i, paramct=0, newlinect=0, nofill=0;
char token[62], *p;
while ((c=getc(stdin)) != EOF) {
if (c == '<') {
if (newlinect == 1) putc(' ', stdout);
newlinect = 0;
c = getc(stdin);
if (c == '<') {
if (paramct <= 0) putc(c, stdout);
} else {
ungetc(c, stdin);
for (i=0, p=token; (c=getc(stdin)) != EOF && c != '>';
i++)
{ if (i < sizeof(token)-1)
*p++ = isupper(c) ? tolower(c) : c;
}
*p = '\0';
if (c == EOF) break;
if (strcmp(token, "param") == 0)
paramct++;
else if (strcmp(token, "nofill") == 0)
nofill++;
else if (strcmp(token, "/param") == 0)
paramct--;
else if (strcmp(token, "/nofill") == 0)
nofill--;
}
} else {
if (paramct > 0)
; /* ignore params */
else if (c == '\n' && nofill <= 0) {

if (++newlinect > 1) putc(c, stdout);
} else {
if (newlinect == 1) putc(' ', stdout);
newlinect = 0;
putc(c, stdout);
}
}
}
/* The following line is only needed with line-buffering */
putc('\n', stdout);
exit(0);
}

It should be noted that one can do considerably better than this in displaying text/enriched data on a dumb terminal. In particular, one can replace font information such as "bold" with textual emphasis (like this or T_H_I_S). One can also properly handle the text/enriched formatting commands regarding indentation, justification, and others. However, the above program is all that is necessary in order to present text/enriched on a dumb terminal without showing the user any formatting artifacts.