3

I currently run a series of commands on any file I am working on to compress the lines. That series is -

G:a
PRESS ENTER KEY
.
:g/^./ .,/^$/-1 join

So I press S-g, S-:, a, enter, ., then run that regular expression. This joins my lines.

function! CrunchLines()
exec G
exec :
exec  a
exec return
.
:g/^./ .,/^$/-1 join
endfu
com! CRUNCH call CrunchLines()

How do you just run vim commands inside of a function?

3
  • 1
    Can you explain what does the G:a<CR>. does ? because it does nothing in my vim, except to go to the last line ...
    – nobe4
    Commented Sep 2, 2015 at 17:28
  • @Nobe4 - Yes, it goes to the last line. Then we insert a blank line at the bottom of the file by pressing enter and the period key. There are TWO <CR> one after the a and then again to insert the space. Commented Sep 2, 2015 at 17:31
  • OK, can you add this detail into your question, and maybe use the <S-g> notation, or the <kbd>.</kbd> one :)
    – nobe4
    Commented Sep 2, 2015 at 17:32

2 Answers 2

2

If you want to run a command from a vim function you can do so with the normal command :

normal! dd 

This act as dd in normal mode. The ! prevent using user mapping, to you get the basic vim functionalities.

Now to compress your file you can go to the last line with G and then joins every lines with your expression.

So the function could be :

function! Crunch() abort
  normal! G
  g/^./ .,/^$/-1 join
endfunction

You can also use the J key that joins the lines like so :

function! Crunch() abort
  normal! ggVGJ
endfunction

Decomposing :

gg  : go to first line
V   : start a visual line selection
G   : go to last line
J   : join the selection
1

My exact method was -

" Crunch multi line text into single line
" Useful for moving text from .tex to web services
function! Crunch() abort
    normal! G
    normal! o
    g/^./ .,/^$/-1 join
endfunction
com! CRUNCH call Crunch()

This allows me to crunch multi line files correctly.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Not the answer you're looking for? Browse other questions tagged or ask your own question.