1

I want to execute the command "yiw:s/\<<C-r>"\>/<C-r>"/g<Left><Left>" by key sequence. So I make a mapping

    nnoremap <F7> yiw:s/\<<C-r>"\>/<C-r>"/g<Left><Left>

This mapping copy the word under cursor, then the string :s/\<">/"/g" (where " are substituted by the copied word) appears in the command line and the cursor in the command line is at the end of replacement statement.

I also want to save cursor position before this command and restore after.

  function! SafeCommand(cmd)
let line = line('.')
let col = col('.')
// execute cmd here 
call cursor( line, col )
  endfunction

How to do that?

4
  • 1) you mapped F then 7, not <F7>. 2) if you want to do a :s/../../g you need put <CR> there 3) even if there was a <CR>, your left left doesn't make sense either, because after substitution, your cursor would be at the beginning of that line. 4) I didn't understand what are you trying to do...replace the word under cursor with same word? can you explain it a bit in your question? Commented Mar 30, 2013 at 23:48
  • 1
    after firing your mapped command, pressing Ctrl-O could bring you back to the old position. Also, you don't have to copy the current word, in command line <c-w> (:h <c-w>) will copy the word under cursor. do you want that function anyway? Commented Mar 31, 2013 at 0:44
  • Thx for tips. But yes, I still want to know how to write such function. Commented Mar 31, 2013 at 1:05
  • If I were you, I would in function accepting user's input (the replacement) by input(). I am not sure if passing a string as keysequence work in function, and stopping at command line and waiting for user finishing the cmd then pressing enter, then function continues.... at least normal or execute don't.. Commented Mar 31, 2013 at 1:54

1 Answer 1

1

Normally, you'd just put the entire (complex) command in a function, and invoke that function from the :nnoremap. But that doesn't work for incomplete commands, like the template :substitute that your mapping represents. For that, you need to include the save / restore parts into the command-line (though that's ugly):

:fun! Save()
    let s:line = line('.')
    let s:col = col('.')
:endfun
:fun! Restore()
    call cursor( s:line, s:col )
:endfun
:nnoremap <F7> yiw:call Save()<Bar>s/\<<C-r>"\>/<C-r>"/g<Bar>call Restore()<Left><Left><Left><Left><Left><Left><Left><Left><Left><Left><Left><Left><Left><Left><Left><Left>
Sign up to request clarification or add additional context in comments.

Comments

Your Answer

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

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.