Wednesday, July 18, 2012

Re: How to remove empty lines except of one

On Wed, Jul 18, 2012 at 11:19:30AM EDT, Ben Fritz wrote:
> On Tuesday, July 17, 2012 7:27:42 PM UTC-5, Bee wrote:

> > This will collapse multiple blank lines, remove trailing white
> > space, and leave only one blank line at the end of file.

> > %s-\_s\+$-\r
> >
> > Bill

> But this one fails to collapse the blank lines at the *beginning* of
> the file! I don't see what's special about the beginning of the file
> which would prevent it from matching.

Bee's regex includes the new line character that terminates the
non-empty line just before a sequence of empty lines, AND somehow¹
excludes the last empty line of the sequence.

This makes it work at the end of the buffer: it replaces the last
non-empty line's eol + the following empty lines minus one by one eol.

If you forget about the notion of buffer for a second and reason as if
the buffer were a string:

asdf\n\n....\n\n -> asdf\n\n
|--------| ^
| |
| .____ ignored by regex
|
._______ matched and replaced by '\r'

Which give you:

asdf\n\n
^ ^
| |
| .______ last line in the buffer
|
._________ what the regex matched and was replaced


Now the problem is that at the start of the buffer you do not have
a previous non-empty last line:

\n\n
^ ^
| |
| .____ ignored
|
.______ match

The first '\n' is therefore replaced by a '\n' giving:

\n\n -> \n\n

> I don't know whether this is a bug, or if we all have a subtle
> misunderstanding of \_s.

That's been my point all along. Your solution or Bee's are fine because
they do the job that matters.. Nobody really cares about empty lines at
start or end of buffer.. and if they do.. they can remove them manually.

The problem is that a bunch of regex's that should match do not.. or do
match when used as part of a search command but do not when used in
a substitute command.

But don't take my word for it.. I only did a regex tutorial a couple of
months ago.. -)

CJ

¹ I haven't figured it out but it looks like the '$' anchor is what
causes this..

--
Oh My God!!! Larry is back!

--
You received this message from the "vim_use" maillist.
Do not top-post! Type your reply below the text you are replying to.
For more information, visit http://www.vim.org/maillist.php

No comments: