]>
Commit | Line | Data |
---|---|---|
a3e870f2 LT |
1 | #include <stdio.h> |
2 | #include <string.h> | |
3 | #include <ctype.h> | |
7499c996 | 4 | #include "builtin.h" |
a3e870f2 LT |
5 | |
6 | /* | |
7 | * Remove empty lines from the beginning and end. | |
8 | * | |
9 | * Turn multiple consecutive empty lines into just one | |
f4ee3eb6 | 10 | * empty line. Return true if it is an incomplete line. |
a3e870f2 | 11 | */ |
f4ee3eb6 | 12 | static int cleanup(char *line) |
a3e870f2 LT |
13 | { |
14 | int len = strlen(line); | |
15 | ||
5cf7e21f JH |
16 | if (len && line[len-1] == '\n') { |
17 | if (len == 1) | |
18 | return 0; | |
a3e870f2 LT |
19 | do { |
20 | unsigned char c = line[len-2]; | |
21 | if (!isspace(c)) | |
22 | break; | |
23 | line[len-2] = '\n'; | |
24 | len--; | |
25 | line[len] = 0; | |
26 | } while (len > 1); | |
f4ee3eb6 | 27 | return 0; |
a3e870f2 | 28 | } |
f4ee3eb6 | 29 | return 1; |
a3e870f2 LT |
30 | } |
31 | ||
7499c996 | 32 | void stripspace(FILE *in, FILE *out) |
a3e870f2 LT |
33 | { |
34 | int empties = -1; | |
f4ee3eb6 | 35 | int incomplete = 0; |
a3e870f2 LT |
36 | char line[1024]; |
37 | ||
7499c996 | 38 | while (fgets(line, sizeof(line), in)) { |
f4ee3eb6 | 39 | incomplete = cleanup(line); |
a3e870f2 LT |
40 | |
41 | /* Not just an empty line? */ | |
42 | if (line[0] != '\n') { | |
43 | if (empties > 0) | |
7499c996 | 44 | fputc('\n', out); |
a3e870f2 | 45 | empties = 0; |
7499c996 | 46 | fputs(line, out); |
a3e870f2 LT |
47 | continue; |
48 | } | |
49 | if (empties < 0) | |
50 | continue; | |
51 | empties++; | |
52 | } | |
f4ee3eb6 | 53 | if (incomplete) |
7499c996 LS |
54 | fputc('\n', out); |
55 | } | |
56 | ||
a633fca0 | 57 | int cmd_stripspace(int argc, const char **argv, const char *prefix) |
7499c996 LS |
58 | { |
59 | stripspace(stdin, stdout); | |
a3e870f2 LT |
60 | return 0; |
61 | } |