2 ** entab.c - add tabs to a text file
3 ** by Bruce Momjian (root@candle.pha.pa.us)
18 #if defined(WIN32) || defined(__CYGWIN__)
19 #define PG_BINARY_R "rb"
21 #define PG_BINARY_R "r"
39 main(int argc
, char **argv
)
43 protect_quotes
= FALSE
,
59 if ((cp
= strrchr(argv
[0], '/')) != NULL
)
63 if (strcmp(cp
, "detab") == 0)
66 while ((ch
= getopt(argc
, argv
, "cdhqs:t:")) != -1)
76 protect_quotes
= TRUE
;
79 min_spaces
= atoi(optarg
);
82 tab_size
= atoi(optarg
);
86 halt("USAGE: %s [ -cdqst ] [file ...]\n\
87 -c (clip trailing whitespace)\n\
89 -q (protect quotes)\n\
104 if ((in_file
= fopen(*argv
, PG_BINARY_R
)) == NULL
)
105 halt("PERROR: Cannot open file %s\n", argv
[0]);
111 while (fgets(in_line
, sizeof(in_line
), in_file
) != NULL
)
115 src
= in_line
; /* points to current processed char */
116 dst
= out_line
; /* points to next unallocated char */
117 if (escaped
== FALSE
)
124 if (quote_char
== ' ' && (*src
== ' ' || *src
== '\t'))
128 prv_spaces
+= tab_size
- col_in_tab
+ 1;
129 col_in_tab
= tab_size
;
134 if (col_in_tab
== tab_size
)
137 * Is the next character going to be a tab? Needed to
138 * do tab replacement in current spot if next char is
139 * going to be a tab, ignoring min_spaces
144 if (*(src
+ nxt_spaces
+ 1) == NUL
||
145 (*(src
+ nxt_spaces
+ 1) != ' ' &&
146 *(src
+ nxt_spaces
+ 1) != '\t'))
148 if (*(src
+ nxt_spaces
+ 1) == ' ')
150 if (*(src
+ nxt_spaces
+ 1) == '\t' ||
151 nxt_spaces
== tab_size
)
153 nxt_spaces
= tab_size
;
157 if ((prv_spaces
>= min_spaces
||
158 nxt_spaces
== tab_size
) &&
166 for (; prv_spaces
> 0; prv_spaces
--)
173 for (; prv_spaces
> 0; prv_spaces
--)
175 if (*src
== '\t') /* only when in quote */
179 if (escaped
== FALSE
&& protect_quotes
== TRUE
)
183 if (*src
== '"' || *src
== '\'')
184 if (quote_char
== ' ')
186 else if (*src
== quote_char
)
189 else if (*src
!= '\r' && *src
!= '\n')
192 if ((*src
== '\r' || *src
== '\n') &&
194 clip_lines
== TRUE
&&
197 while (dst
> out_line
&&
198 (*(dst
- 1) == ' ' || *(dst
- 1) == '\t'))
204 col_in_tab
%= tab_size
;
207 /* for cases where the last line of file has no newline */
208 if (clip_lines
== TRUE
&& escaped
== FALSE
)
210 while (dst
> out_line
&&
211 (*(dst
- 1) == ' ' || *(dst
- 1) == '\t'))
215 for (; prv_spaces
> 0; prv_spaces
--)
218 if (fputs(out_line
, stdout
) == EOF
)
219 halt("PERROR: Error writing output.\n");
221 } while (--argc
> 0);