this is really hard to get right and I wonder if it's easier to do a tree-like parse; particularly since I'll need to figure out where I am for tab completion anyway