phatskat
phatskat

Reputation: 1815

VIM: Copying Formatting to Visual Selection?

I'm not sure if this is possible, but Vim constantly surprises me. What I'd like to be able to do is take the formatting of one block of text and apply it to a selection. Assuming several lines like this:

<li><a href="#"><span>Something Here</span><i class="icon"></i></a></li>
<li><a href="#"><span>Something Here</span><i class="icon"></i></a></li>
<li><a href="#"><span>Something Here</span><i class="icon"></i></a></li>

I'd like to format one of the lines:

<li>
    <a href="#">
        <span>Something Here</span>
        <i class="icon"></i>
    </a>
</li>

And then apply that formatting to the remaining lines. Again, no clue if this is doable, but it would be very neat if it could - I often have to implement HTML templates where there are long lines that may have 5 or 6 nested tags within, often starting with an indentation that is quite out there.

Upvotes: 0

Views: 141

Answers (4)

Alan G&#243;mez
Alan G&#243;mez

Reputation: 378

If the input is as regular as show in first post, you can use a regex like this one:

:%s/\(<a.\{-}>\)\(<span.\{-}\/span>\)\(<i.\{-}\/i>\)\(<\/a>\)/\r    \1\r
  \2\r        \3\r    \4\r/g

The explanation is that you separate each bunch of codes in groups \(...\) then at replacement part, add some spaces before each ones.

Upvotes: 0

Amit
Amit

Reputation: 20456

A way to do it with a macro for your sample input, add a macro with the following command and run it on a line using @i or on multiple lines using {motion}@i i.e. to run it on 3 lines press 3@i and it will indent all 3 lines.

:let @i='0f<i^M^[>>;i^M^[>>;;i^M^[;;;i^M^[<<;i^M^[<<+'

Explanation:

  1. 0 : Move to the beginning of the line
  2. f< : Find first <
  3. i^M^[ : Enter Insert Mode, Insert a new-line and go back to command mode.
  4. >> : Indent the line
  5. ; : Find next <
  6. i^M^[ : Repeat step 3
  7. << : Un-indent the line
  8. + : Move to the first non-whitespace character on next line

Upvotes: 3

Peter Rincker
Peter Rincker

Reputation: 45117

As an alternative filter the content with haml and html2haml commands via :!

:%!html2haml -s | haml -q -s

Install gems via gem install haml and gem install html2haml

For more help with filters see :h :range!

Upvotes: 0

freude
freude

Reputation: 3832

Do you know the recording feature of vim? Try to do following:

  1. press q + some character to enter the recording mode
  2. do formatting of a line
  3. press q to exit the recording mode
  4. go to the next line
  5. press @ + some character to reproduce recorded operations

Upvotes: 3

Related Questions