To meet all your requirements a function will probably be needed in addition to a mapping. Put both of these in your Vim start-up file (e.g. .vimrc
) and the functionality will be available each time you launch Vim.
func! ReplaceNChars(n)
let inchars = ""
let idx = a:n
echom 'Enter ' . a:n . ' characters: '
while idx > 0
let inchars .= nr2char(getchar())
let idx -= 1
endwhile
exec 'norm! R' . inchars
endfunc
This function takes a number and then waits for that many characters to be entered by the user. Then Normal mode R
is used to replace whatever is currently under the cursor with the entered text.
The code is very straightforward so I won't go into the details.
Here's the mapping...
nnoremap <expr> <silent> <leader>R ':<C-U>call ReplaceNChars(' . v:count1 . ')<CR>'
To use it, in Normal mode enter the number of characters to replace, then, assuming you have the default leader key, enter \R
. (Replace this part with whatever you want.) You'll be taken to the command line. Enter the appropriate number of characters and then the replacement will occur. No extra keys like Esc or Enter are required.
Unlike the code this mapping uses some constructs that may not be well known. Some details (with Vim help links):
<expr>
: The right side of the mapping is an expression that is evaluated and the result is the actual mapping.
<silent>
: Prevents the mapped command from being echoed on the command line.
<C-U>
: Clears the command line before inserting the rest of our command.
v:count1
: Variable that contains the last user-entered count. If no count has been entered defaults to 1. In our case the default will mean that the mapping will behave much like the r
command.
I haven't done any negative testing or tried any corner case input. Just normal use cases.