3

I have a function somewhat like this:

function! MyFunction()
    g/\v.(\n\n|\n*%$)/execute "normal! v{:call AnotherFunction()\<cr>"
endfunction

Now I want to be able to pass a range to that function. The problem is… how can I add the range (a:firstline and a:lastline) before the g command?

I tried all the combinations I could think of (like execute a:firstline.','.a:lastline' 'g/...), but I can't get it to work (maybe because I already use execute in the global command).

4

From the documentation (:h function-range-example):

function Cont() range
  execute (a:firstline + 1) . "," . a:lastline . 's/^/\t\\ '
endfunction
4,8call Cont()

You need to use execute to pass the variables to the g command.

In your case, this simplified example should work (at least it works here):

function! MyFunction()
    execute a:firstline . ',' . a:lastline . 'g/^/execute "normal! >>"'
endfunction
1,3call MyFunction()
  • 1
    Ah, you're right, thank you! I wasn't passing a range when calling the function and I assumed it would use the whole file in that case, but apparently it doesn't, so I thought it wasn't working when I tried doing that. Anyway, it's all good now. Thanks again. :) – dbmrq Aug 1 '16 at 9:58
  • Ah, but look, here's a more complicated example that doesn't work, maybe because there are quotes in the pattern: execute a:firstline . ',' . a:last line . 'g/\(\.\|!\|?\)\()\|]\|"\|'\)*\($\|\s\)/execute "normal! v(:call MyFunction()\<cr>"'. Any ideas? – dbmrq Aug 1 '16 at 10:07
  • Just a guess, can you try escaping the ' with \'? (otherwise I think it's worth another question ;) ) – nobe4 Aug 1 '16 at 10:23
  • 1
    Ok, I had already tried that and it didn't work, but after looking around some more I found out it's possible to escape characters by doing <c-v><esc> and then the character. And that works! Edit: wait! no, it doesn't, haha. I'll open another question then. – dbmrq Aug 1 '16 at 10:29
  • I may have a solution if you open the question ;) – nobe4 Aug 1 '16 at 11:23

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

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