Merging upstream version 0.5.4.
[debian/lxappearance.git] / src / xml-purge.c
1 #include <stdio.h>
2 #include <string.h>
3 #include <stdlib.h>
4 #include <glib.h>
5
6 #define IS_BLANK(ch) strchr(" \t\n\r", ch)
7
8 static void purge_file( const char* file )
9 {
10 char* buf, *pbuf;
11 int in_tag = 0, in_quote = 0;
12 FILE* fo;
13
14 if(!g_file_get_contents(file, &buf, NULL, NULL))
15 exit(1);
16
17 fo = fopen( file, "w" );
18 if( ! fo )
19 goto error;
20
21 for( pbuf = buf; *pbuf; ++pbuf )
22 {
23 if( in_tag > 0 )
24 {
25 if( in_quote )
26 {
27 if( *pbuf == '\"' )
28 in_quote = 0;
29 }
30 else
31 {
32 if( *pbuf == '\"' )
33 ++in_quote;
34 if( ! in_quote && IS_BLANK(*pbuf) ) /* skip unnecessary blanks */
35 {
36 do{
37 ++pbuf;
38 }while( IS_BLANK( *pbuf ) );
39
40 if( *pbuf != '>' )
41 fputc( ' ', fo );
42 --pbuf;
43 continue;
44 }
45 }
46 if( *pbuf == '>' )
47 --in_tag;
48 fputc( *pbuf, fo );
49 }
50 else
51 {
52 if( *pbuf == '<' )
53 {
54 if( 0 == strncmp( pbuf, "<!--", 4 ) ) /* skip comments */
55 {
56 pbuf = strstr( pbuf, "-->" );
57 if( ! pbuf )
58 goto error;
59 pbuf += 2;
60 continue;
61 }
62 ++in_tag;
63 fputc( '<', fo );
64 }
65 else
66 {
67 char* tmp = pbuf;
68 while( *tmp && IS_BLANK( *tmp ) && *tmp != '<' )
69 ++tmp;
70 if( *tmp == '<' ) /* all cdata are blank characters */
71 pbuf = tmp - 1;
72 else /* not blank, keep the cdata */
73 {
74 if( tmp == pbuf )
75 fputc( *pbuf, fo );
76 else
77 {
78 fwrite( pbuf, 1, tmp - pbuf, fo );
79 pbuf = tmp - 1;
80 }
81 }
82 }
83 }
84 }
85
86 fclose( fo );
87
88 error:
89 free( buf );
90 }
91
92 int main( int argc, char** argv )
93 {
94 int i;
95 if( argc < 2 )
96 return 1;
97
98 for( i = 1; i < argc; ++i )
99 purge_file( argv[ i] );
100
101 return 0;
102 }