How about using `getRange` (http://codemirror.net/doc/manual.html#getRange) with third argument `false` on the whole range and iterating over that, instead of doing all this for each line?