Reformatting each line independently (how to apply an operation to each line)

22 views
Skip to first unread message

J S

unread,
Mar 5, 2020, 7:44:46 PM3/5/20
to Vim Mailing List
Every so often, I have the need to reformat a text in such a way that each line gets fed to the reformatter (e.g., gqq) by itself. I.e., I don't want to reformat the whole text as a single block.

Is there any general way to say "Do this thing (gqq) to each line?"

I have found a workaround, which is to learn a macro (qq) to be gqq<cr>, then do:

30@q

(assuming 30 is enough)

This works, but it seems like there should be a cleaner way - that doesn't involve learning a macro.

Gary Johnson

unread,
Mar 5, 2020, 8:27:17 PM3/5/20
to vim...@googlegroups.com
How about this?

:g/./normal gqq

According to ":help normal-range", the following should have worked,
too, but it didn't include the last line(s) of my test file when
gqq split earlier lines .

:%normal gqq

Those reformat the entire buffer. You can change the range to suit.

Regards,
Gary

JohnBeckett

unread,
Mar 6, 2020, 12:53:37 AM3/6/20
to vim_use
> :%normal gqq

Interesting. What goes wrong is that the % operates on a certain number of lines. If the buffer has, say, 5 lines that are three times the length of the current window width, then the command will operate on the first 5 lines only.


However, each gqq will replace the line with three lines and the % will stop after it has processed 5 of what results.

John

J S

unread,
Mar 7, 2020, 10:37:00 AM3/7/20
to Vim Mailing List
Thanks for all the replies. It seems that:

1) There's no really clean way to do it. It seems to me that there should be something like "linedo" - analogous to "windo" and "buffdo". Of the workarounds, the %g/./normal
method seems the best. Thanks for that.

2) It just occurred to me that, for this specific case (reformatting each line), you could use "fmt -s" (at least on Unix/GNU version of "fmt").

Tim Chase

unread,
Mar 7, 2020, 10:57:56 AM3/7/20
to 'J S' via vim_use, Vim Mailing List
On 2020-03-07 15:36, 'J S' via vim_use wrote:
> Thanks for all the replies. It seems that:
>
> 1) There's no really clean way to do it. It seems to me that there
> should be something like "linedo" - analogous to "windo" and
> "buffdo". Of the workarounds, the %g/./normal method seems the
> best. Thanks for that.

The typical way to write a "linedo" command is

:g/^/command

which is subtly different from

:g/./command

in the event that a line is empty. For your use-case, it doesn't
change anything, but if your change should also happen on empty line,
you'd want to use the "^" pattern because every line has one of those.

> 2) It just occurred to me that, for this specific case
> (reformatting each line), you could use "fmt -s" (at least on
> Unix/GNU version of "fmt").

which, if it would work, you could pipe the range through fmt:

:%!fmt -s

Always nice to have options :-)

-tim


Reply all
Reply to author
Forward
0 new messages