Home » Questions » Computers [ Ask a new question ]

Vim Foo, List to Html Table

Vim Foo, List to Html Table

What is the easiest way in Vim to go from:

Asked by: Guest | Views: 64
Total answers/comments: 2
Guest [Entry]

"You can add <table> and </table> manually:

ggO<table>[ESC]YGpa/[ESC]

Where [ESC] is the top-left key on your keyboard +)

gg - go to the top of the file
O - add new line above the current
<table> - write <table>
[ESC] - back to the command mode
Y - yank current line
G - go to the end of the file
p - paste yanked line below the current
a - begin insert mode and start inserting after current symbol
/ - add / symbol
[ESC] - back to the command line

Now u can record a short vim macros to repeat another set of command multiple times:

:2[ENTER]qqO<tr>[ESC][DOWN]I<td>[ESC]A</td>[ESC][DOWN]
I<td>[ESC]A</td>[ESC]o</tr>[ESC][DOWN]q

yep, now u can just repeat @q multiple times...(e.g. 11@q)

:2 - go to the second line in the file
qq - start recording macros in 'q' register
O - add new line above the current
<tr> - add <tr>
[ESC][DOWN] - you know =)
I - go to the begining of the line and start the insert mode
<td> - write <td>
[ESC] - ...
A - go to the line end and start the insert mode
</td> - ...
[ESC][DOWN]
repeat 6-10
[ESC]
o - add line below current and start the insert mode
</tr> - ...
[ESC][DOWN]q - end macros recording"
Guest [Entry]

"I know you're probably thinking of some clever solution using macros, but I'd let my fingers do the walking (since you're not likely to have an HTML table hundreds of lines long):

For each line of the file, replace the beginning of line with <td>
And for each line, replace the end of line with </td>

%s/^/<td>/
%s/$/<\/td>/

goto the first line and insert

</tr>
<tr>

Yank those lines, press down-arrow until you're at the next insertion point and press p
Continue to the bottom of the file, pressing p every two lines. There's a simple kind of rhythm here that I like to use: down, down, p, down, down, p, etc.

Change the last line to

</table>

Go back to the top and change the first line to

<table>

Obviously, I haven't tried this (and I concede that macros might be easier for some)"