2

Following this question: the answer suggests to map a particular command to a key sequence. It assumes that the delimiter will always be =, but I would like to make no assumptions.

I'd like to add a useful remap which allows me to dynamically specify the delimiter: I'd like to remap (while in visual mode) Leaderyt...Enter to y'>pV']:s/PATTERN.*//<cr>gvd, where PATTERN is whatever keys I pressed between t and Enter.

The idea is that I can use Leaderyt: to deal with text like this:

h:1
width:3

And Leaderyt= to deal with text like this:

h=1
width=3

What should be added to vimrc for this mapping to work?

1 Answer 1

2

Maybe you could try this mapping:

xno <expr> <leader>yt "y'>pV']:s/".input('pattern: ').".*//<cr>gvd"

It uses the <expr> argument, which means that when you type <leader>yt, Vim doesn't expand it into the {rhs} directly, the latter is first evaluated as an expression, then the evaluation is used as the keys to type.

Here, the {rhs} is almost the same as the one in your question, with one difference. Instead of using the pattern =.*, the input() function is invoked to let you type an arbitrary pattern. It should return whatever you type.

The problem with this mapping, is that if your pattern isn't in the selection, it will duplicate it.

So, maybe you need a little more logic to test whether the pattern is found, and if so the expression should return the right keys, otherwise don't return anything:

xno <expr> <leader>yt <sid>copy_before_pattern()

fu! s:copy_before_pattern() abort
    let pattern = input('pattern: ')
    return search(pattern, 'cnW', line("'>"))
                \ ? "y'>pV']:s/".pattern.".*//\<cr>gvd"
                \ : ''
endfu

Here the logic is wrapped inside a function, which should test whether the pattern is somewhere in the selection, before returning the keys.

I didn't test it very long, so it may not work all the time.

Edit:

I don't know why, but sometimes the key binding doesn't do anything on my machine. If you experience the same issue, here's an alternative, which seemed more reliable during the little time I tested it:

xno <leader>yt <esc>:call <sid>copy_before_pattern()<cr>

fu! s:copy_before_pattern() abort
    let pattern = input('pattern: ')
    norm! '<
    if search(pattern, 'cnW', line("'>"))
        exe "norm! y'>pV']:s/".pattern.".*//\<cr>gvd"
    endif
endfu

Your Answer

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

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