This is a read-only archive!

Vim: Find lines longer than current line

Vim isn't just for editing source code. It's also a pretty good data editor.

Sometimes I'm editing dirty fixed-width data files, and some lines are incorrectly a bit too long because one or two fields overflowed. It's easy to search for lines that are too long, once you know how long lines should be. Say your lines should be 1000 characters; search like this:


Now all the longer lines are highlighted (assuming :set hls).

That's tedious to type though. Put your cursor on a non-overflowing line and call this function, and Vim will find all the lines that are too long, and move you to the first one:

function! FindLongerLines()
    let @/ = '^.\{' . col('$') . '}'
    silent! norm n$

That mess about manually setting @/ is because of this somewhat unfortunate fact (from :help :function):

        The last used search pattern and the redo command "."
        will not be changed by the function.  This also
        implies that the effect of |:nohlsearch| is undone
        when the function returns.

That is, using something like norm / inside functions doesn't affect the last-remembered search once the function returns, but that's exactly what we want to happen.

June 21, 2012 @ 3:29 AM PDT
Cateogory: Programming
Tags: Vim