Can you do interactive macros or recordings in vim?

Viewed 1512

I would like to define a vim macro that breaks for user input at certain times, is this possible?

EDIT: Turns out I ment recordings (q), not macros

It is possible to use the input command in a recording, but it's more trouble than it's worth.

I first mapped insert input escape to a key

:map <F2> a<C-R>=input('input: ')<CR>

then I made this recording in the q register

name: 

and pasted it into a new tab

iname: ^[

And after the final escape I pressed <C-V><F2> making the line:

iname ^[^[OQ

That I yanked back to the q buffer then used the macro, letting me use the input function. It works, but terribly.

4 Answers

I have collected information from this and other threads and written this script:

function! MacroInterrupt()
    "call inputsave()
    if strlen(reg_recording()) == 0
        if mode() == 'n'
            call inputsave()
            let tmp_col = col('.')
            let tmp_line = line('.')
            let text = input('input:')
            let line = getline('.')
            call setline('.', strpart(line, 0, col('.') - 1) . text . strpart(line, col('.') - 1))
            call cursor(tmp_line, tmp_col + strlen(text))
            call inputrestore()
            return text
        else
            call inputsave()
            let text = input('input:')
            call inputrestore()
            return text
        endif
    else
        echo "Interrupt added to macro"
        call setreg(reg_recording(), getreg(reg_recording()) . "\<F2>")
        "echo getreg("q")
    endif
    "call inputrestore()
endfunction

map <F2> :call MacroInterrupt() <CR>
inoremap <buffer><expr> <F2> MacroInterrupt()

I hope this can help especially people attempting the same.

Related