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