#!/usr/local/bin/pike # KWIC written in Pike mapping head = ([]); mapping tail = ([]); int width = 0; int icomp(string a, string b) { a = lower_case(a); b = lower_case(b); if (a == b) return 0; if (a < b) return -1; return 1; } int append(Stdio.FILE o) { while (string lin = o->gets()) { head[lin] = ""; tail[lin] = lin; foreach (indices(lin), int i) if (lin[i..i] == " ") { string hd, tl, ix; hd = lin[..i - 1]; tl = lin[i + 1..]; ix = tl + " " + hd; head[ix] = hd; tail[ix] = tl; if (width < strlen(hd)) width = strlen(hd); } } } int main(int argc, string *argv) { if (argc == 1) { append(Stdio.stdin); } else { object o = Stdio.FILE(); foreach (argv[1..], string fn) { if (!o->open(fn, "r")) { write(sprintf("Can't open %s\n", fn)); continue; } append(o); o->close(); } } foreach (Array.sort_array(indices(tail), icomp), string key) write(sprintf("%" + width + "s %s\n", head[key], tail[key])); } |