0

I have a keybinding nmap <leader>c :w ! wc<CR>, I wanted to expand it to work with visual regions (not just the whole file). I did so by creating vmap <leader>c :w ! wc<CR>, this is mostly fine but I wanted to pipe the selected region, not the whole line in which the region happens to be. I tried '<,'>w ! wc and it's still the whole line. I don't know how to tell vim what region of text I want to manipulate, and every online resource talks about doing the selected line, not text.

How do I specify that I want to use the visually selected text, instead of the whole line?

1 Answer 1

1

There is no way to pipe partial lines using !.

A workaround is to use a function like system().

xmap <leader>c y:echo system('wc', @")[:-2]<cr>gv

Breaking this down,

  • y yank the visually selected text, copying it into register "
  • :echo ...<cr> print the result of a function
  • system(cmd, @") send register contents to an external command and receive output
  • [:-2] strip an extra newline
  • gv (optional) re-enter visual mode
4
  • In neovim v0.9.1, using your code verbatim does nothing, and replacing shuf with wc leads to the result of wc replacing the highlighted text. In both cases register " contains the highlighted text as it was. Using vim v9.0, both shuf and wc simply delete the highlighted region, leaving register " with the highlighted text. In both cases I'm using a minimal vimrc, with two lines let g:mapleader = "\\" and xmap <leader>c c<c-r>=system('shuf', @")[:-2]<cr><c-\><c-n>
    – Le-Kat
    Aug 20, 2023 at 22:23
  • @Le-Kat just updated my answer to answer the actual question
    – Mass
    Aug 21, 2023 at 0:11
  • 1
    @Mass did you mean to remove mentioning of <c-r>=...? Aug 21, 2023 at 8:03
  • 1
    It looks like you updated the mapping and didn't update part of the explanation, since now it :echos
    – D. Ben Knoble
    Aug 21, 2023 at 12:56

Your Answer

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

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