aboutsummaryrefslogtreecommitdiff
path: root/cssindent.c
blob: 555a8c6b685a54f183f1a007243f9c53782c456c (plain) (blame)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
/*
 * Indent some fucking CSS.
 * Runxi Yu <https://runxiyu.org>
 * SPDX-License-Identifier: CC0-1.0
 */

#include <stdio.h>
#include <unistd.h>
#include <stdlib.h>
#include <fcntl.h>

ssize_t pc(char x)
{
	return write(1, &x, 1);
}

int main(int argc, char **argv)
{
	_Bool quoted = 0, commented = 0, front = 1;
	unsigned int depth = 0;
	unsigned int source_lines = 1;
	int fd;
	if (argc == 1) {
		fd = 0;
	} else if (argc == 2) {
		fd = open(argv[1], 0);
	} else {
		fprintf(stderr, "Too many arguments\n");
		return 1;
	}
	for (;;) {
		auto char buf[4096];
		ssize_t len = read(fd, &buf, 4096);
		if (len <= 0)
			break;
		for (ssize_t i = 0; i < len; ++i) {
			if (buf[i] == '/' && buf[i + 1] == '*') {
				commented = 1;
				write(1, "/*", 2);
				++i;
				continue;
			} else if (buf[i] == '*' && buf[i + 1] == '/') {
				if (commented) {
					commented = 0;
					write(1, "*/\n", 3);
					i += 2;
					continue;
				} else {
					fprintf(stderr, "%u: too many */\n",
						source_lines);
					return 1;
				}
			}
			if (commented) {
				pc(buf[i]);
				continue;
			}
			if (buf[i] == '}') {
				if (!front) {
					pc(';');
					pc('\n');
					front = 1;
				}
				if (depth == 0) {
					fprintf(stderr, "%u: too many }\n",
						source_lines);
					return 1;
				}
				--depth;
				for (unsigned int j = 0; j < depth; ++j) {
					pc('\t');
				}
				pc('}');
				pc('\n');
				if (depth == 0)
					pc('\n');
				front = 1;
				continue;
			}
			if (buf[i] == '\n') {
				++source_lines;
				continue;
			} else if (buf[i] == '\t') {
				continue;
			}
			if (buf[i] == ' ') {
				if (front) {
				} else if (!quoted && !commented) {
					if (buf[i + 1] == ' ') {
						continue;
					}
					pc(' ');
				}
				continue;
			} else if (buf[i] == '\t') {
				continue;
			}
			if (front) {
				for (unsigned int j = 0; j < depth; ++j) {
					pc('\t');
				}
			}
			if (buf[i] == ';') {
				pc(';');
				pc('\n');
				front = 1;
			} else if (buf[i] == '{') {
				++depth;
				pc('{');
				pc('\n');
				front = 1;
			} else {
				front = 0;
				pc(buf[i]);
			}
		}
	}
}