2 * Copyright (c) 2012 Ed Schouten <ed@FreeBSD.org>
5 * Redistribution and use in source and binary forms, with or without
6 * modification, are permitted provided that the following conditions
8 * 1. Redistributions of source code must retain the above copyright
9 * notice, this list of conditions and the following disclaimer.
10 * 2. Redistributions in binary form must reproduce the above copyright
11 * notice, this list of conditions and the following disclaimer in the
12 * documentation and/or other materials provided with the distribution.
14 * THIS SOFTWARE IS PROVIDED BY THE AUTHOR AND CONTRIBUTORS ``AS IS'' AND
15 * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
16 * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
17 * ARE DISCLAIMED. IN NO EVENT SHALL THE AUTHOR OR CONTRIBUTORS BE LIABLE
18 * FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL
19 * DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS
20 * OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION)
21 * HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT
22 * LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY
23 * OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF
27 #include <sys/cdefs.h>
28 __FBSDID("$FreeBSD$");
35 static char *queue = NULL;
36 static size_t queuelen = 0, queuesize = 0;
37 static off_t column = 0;
43 if (queuelen >= queuesize) {
45 queue = realloc(queue, queuesize);
51 queue[queuelen++] = c;
61 column = (column / 8 + 1) * 8;
67 peekbyte(size_t back, char c)
70 return (queuelen >= back && queue[queuelen - back] == c);
74 savewhite(char c, bool leading)
81 /* Remove empty lines before input. */
85 /* Remove trailing whitespace. */
86 while (peekbyte(1, ' ') || peekbyte(1, '\t'))
88 /* Remove redundant empty lines. */
89 if (peekbyte(2, '\n') && peekbyte(1, '\n'))
98 /* Convert preceding spaces to tabs. */
99 ncolumn = (column / 8 + 1) * 8;
100 while (peekbyte(1, ' ')) {
104 while (column < ncolumn)
115 /* Merge spaces at the start of a sentence to tabs if possible. */
116 if ((column % 8) == 0) {
117 for (i = 0; i < column; i++)
118 if (!peekbyte(i + 1, ' '))
122 for (i = 0; i < column; i += 8)
123 queue[queuelen++] = '\t';
127 if (fwrite(queue, 1, queuelen, stdout) != queuelen) {
140 if (c == EOF && ferror(stdin)) {
151 if (putchar(c) == EOF) {
155 /* XXX: Multi-byte characters. */
165 while ((c = readchar()) != EOF) {
167 /* Save whitespace. */
168 savewhite(c, leading);
170 /* Reprint whitespace and print regular character. */
176 /* Terminate non-empty files with a newline. */