0

I'm simply trying perform some commands on text that is selected in visual mode. If I select some text & then press y (for yank) or d (for delete), it yanks or deletes the selected text
However I need to be able to do this from the command line (because I'm writing a function that I'm going to remap to one of my keys).
However when I enter the command line from visual mode '<,'> is there by default, so I just try to append y or d to the end of it leaving me with :'<,'>d
The problem with this however is that it deletes the whole line that the visual selection is in. I only want to delete the selection I made within the line.
I've tried looking at http://vim.wikia.com/wiki/Search_and_replace_in_a_visual_selection but nothing I try seems to work.
I'm sure it must be something simple but I just don't know what. Any help would be greatly appreciated.

1
  • What is your goal? I am starting to think this may be an XY Problem Commented Nov 13, 2014 at 14:10

1 Answer 1

1

All Vim native ex commands work on lines. I guess you can buck this trend. However you seem to be wanting to create a command simply so you can map it some key(s). You probably just want to call the function directly or creating a <Plug> or <SID> mapping instead.

Calling a function directly

xnoremap * :<c-u>call YourFunctionGoesHere<cr>

The secret sauce using :<c-u>call here. You probably want to use :normal! gv inside your function.

Using <Plug>

Here is a quick-n-dirty visual start example showing:

function! s:vstar()
  let reg = @@
  normal! gvy
  let @/ = '\V' . substitute(escape(@@, '\'))
  let @@ = reg
endfunction

xnoremap <Plug>(vstar) :<c-u>call <SID>vstar()<cr>/<c-r>/<cr><cr>

This show how to create the <Plug> map which shows how to call a function which is the same as calling the function directly example. The use of <SID>/s: makes sure the function is "namespace'd" to the current script.

Now you can just map * to your <Plug> mapping like in your ~/.vimrc file:

xmap * <Plug>(vstar)

This is how Vim Plugin's create their mappings. A good starting place for learning Vim plugins is :h write-plugin and looking at some very popular vim plugins. I suggest you look at Tim Pope's or Ingo Karkat's plugins as both are very prolific authors.

For more help see:

:h <Plug>
:h <SID>
:h using-<Plug>
:h write-plugin
:h c_ctrl-u
:h :norm
Sign up to request clarification or add additional context in comments.

1 Comment

Thanks for the reply, but it still didn't work for me. I probably just don't get it. Anyway I ended up just assigning markers & deleting between the 2 of them. This avoided me having to enter visual mode at all.

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.