EnTabpublic class EnTab extends Object EnTab: replace blanks by tabs and blanks. Transmuted from K&R Software Tools
book into C. Transmuted again, years later, into Java. Totally rewritten to
be line-at-a-time instead of char-at-a-time. |
Fields Summary |
---|
protected Tabs | tabsThe Tabs (tab logic handler) |
Constructors Summary |
---|
public EnTab(int n)Constructor: just save the tab values.
tabs = new Tabs(n);
| public EnTab()
tabs = new Tabs();
|
Methods Summary |
---|
public void | entab(java.io.BufferedReader is, java.io.PrintWriter out)entab: process one file, replacing blanks with tabs.
String line;
int c, col = 0, newcol;
// main loop: process entire file one line at a time.
while ((line = is.readLine()) != null) {
out.println(entabLine(line));
}
| public void | entab(java.io.BufferedReader is, java.io.PrintStream out)entab: process one file, replacing blanks with tabs.
entab(is, new PrintWriter(out));
| public java.lang.String | entabLine(java.lang.String line)entabLine: process one line, replacing blanks with tabs.
int N = line.length(), outCol = 0;
StringBuffer sb = new StringBuffer();
char ch;
int consumedSpaces = 0;
for (int inCol = 0; inCol < N; inCol++) {
ch = line.charAt(inCol);
// If we get a space, consume it, don't output it.
// If this takes us to a tab stop, output a tab character.
if (ch == ' ") {
Debug.println("space", "Got space at " + inCol);
if (!tabs.isTabStop(inCol)) {
consumedSpaces++;
} else {
Debug.println("tab", "Got a Tab Stop " + inCol);
sb.append('\t");
outCol += consumedSpaces;
consumedSpaces = 0;
}
continue;
}
// We're at a non-space; if we're just past a tab stop, we need
// to put the "leftover" spaces back out, since we consumed
// them above.
while (inCol-1 > outCol) {
Debug.println("pad", "Padding space at " + inCol);
sb.append(' ");
outCol++;
}
// Now we have a plain character to output.
sb.append(ch);
outCol++;
}
// If line ended with trailing (or only!) spaces, preserve them.
for (int i = 0; i < consumedSpaces; i++) {
Debug.println("trail", "Padding space at end # " + i);
sb.append(' ");
}
return sb.toString();
| public int | getTabSpacing()Delegate tab spacing information to tabs.
return tabs.getTabSpacing();
| public static void | main(java.lang.String[] argv)Main program: just create an EnTab object, and pass the standard input
or the named file(s) through it.
EnTab et = new EnTab(8);
if (argv.length == 0) // do standard input
et.entab(
new BufferedReader(new InputStreamReader(System.in)),
System.out);
else
for (int i = 0; i < argv.length; i++) { // do each file
et.entab(
new BufferedReader(new FileReader(argv[i])),
System.out);
}
|
|