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>
33 static char *queue = NULL;
34 static size_t queuelen = 0, queuesize = 0;
35 static off_t column = 0;
41 if (queuelen >= queuesize) {
43 queue = realloc(queue, queuesize);
49 queue[queuelen++] = c;
59 column = (column / 8 + 1) * 8;
65 peekbyte(size_t back, char c)
68 return (queuelen >= back && queue[queuelen - back] == c);
72 savewhite(char c, bool leading)
79 /* Remove empty lines before input. */
83 /* Remove trailing whitespace. */
84 while (peekbyte(1, ' ') || peekbyte(1, '\t'))
86 /* Remove redundant empty lines. */
87 if (peekbyte(2, '\n') && peekbyte(1, '\n'))
96 /* Convert preceding spaces to tabs. */
97 ncolumn = (column / 8 + 1) * 8;
98 while (peekbyte(1, ' ')) {
102 while (column < ncolumn)
113 /* Merge spaces at the start of a sentence to tabs if possible. */
114 if ((column % 8) == 0) {
115 for (i = 0; i < column; i++)
116 if (!peekbyte(i + 1, ' '))
120 for (i = 0; i < column; i += 8)
121 queue[queuelen++] = '\t';
125 if (fwrite(queue, 1, queuelen, stdout) != queuelen) {
138 if (c == EOF && ferror(stdin)) {
149 if (putchar(c) == EOF) {
153 /* XXX: Multi-byte characters. */
163 while ((c = readchar()) != EOF) {
165 /* Save whitespace. */
166 savewhite(c, leading);
168 /* Reprint whitespace and print regular character. */
174 /* Terminate non-empty files with a newline. */