Reputation: 925
I'm quite new to Vim/Vi, and I need to write a custom function/macro. Is it possible to define a command (ex. :mycommand) that would format the lines in the current file like so:
Initial lines:
This is line 1
This is line 2
This is line 3
This is line 4
This is line 5
This is line 6
This is line 7
This is line 8
Result:
This is line 1\nThis is line 2
This is line 3\nThis is line 4
This is line 5
This is line 6\nThis is line 7\nThis is line 8
How do I go about creating such a script? And where do I place it?
Upvotes: 0
Views: 1388
Reputation: 195029
You can record a macro, to join two lines by \n
separator, for example in your vimrc:
let @x='gJi\n^['
(the ^[
above, you press ctrl-v Esc
)
Assume your cursor is on the first line, you can do @x
in normal mode, then )J@@
for the 2nd block, then job is done.
You can wrap those operations in function or create them as mapping.
I have written a Join
script: https://github.com/sk1418/Join , it supports to join lines with separator and other features, in your case, you can execute command: :J '\n'
, it will do what above macro (@x)
does. You can put it in your function too, like:
function Foo()
Join '\n'
join!
Join '\n'
endfunction
The modification you made, turned the question into another one... However it could be solved, I listed two possibilities below, one is vim way, the other is with external awk tool, if you have awk available on your system.
:s
cmdThis command should do it for you:
%s/\n\n/∢/g|%s/\n\ze./\\n/g|%s/∢/\r/g
∢
is done by pressing ctrl-v u2222
, it is just for a special char, which not exists in your text, you can use other uni-code chars too.%!awk -v RS='\n\n' '{gsub(ORS, "\\n")}7'
This will do the transformation for you, however it leaves an extra \n
at the end of the file, just remove it.
Upvotes: 1