Sometimes I want to post code to a website, but they have utterly broken filters (I'm looking at you Yahoo! Answers). So that when I paste nicely indented code it goes from this:
def double(x):
return x+x
to this:
def double(x):
return x+x
It is annoying in C or Lisp, but it is wrong in python where the syntax relies on proper indentation. When websites do this it is broken.
So I wrote a little program to rectify the situation. It processes a source file so that it looks the same or similar on the web as in your text editor.
usage: webindent < source.c > page.html
#define true 1
#define false 0
/* main(): get characters from stdin, replace
* leading spaces with ' '
* and replace leading tabs with 4 ' 's
* This code is donated to the public domain */
int main()
{
int start = true; /* we're at the start of a line */
char *space = " ";
char *fourspaces = " ";
char c; /* the current char */
while ((c = getchar()) != EOF) {
if (c == ' ') {
if (start)
printf(space);
else
putchar(c);
} else if (c == '\t') {
if (start)
printf(fourspaces);
else
putchar(c);
} else if (c == '<') {
printf("<");
} else if (c == '>') {
printf(">");
} else if (c == '\n') {
printf("<br />");
putchar(c);
start = true;
} else if (c == '&') {
printf("&");
} else {
if (start)
start = false;
putchar(c);
}
}
return 0;
}
It does a bit more than is stated in that comment, because it has to remove '&', '<' and '>' for it to be a well-formed HTML fragment. Note that I used this program to process itself.