How to get line numbers of selected text in vim

Viewed 780

Is it possible to get the line numbers of selected text to pass to an external command?

Context: I'd like to integrate pyfmt into vim. Ideally, I'd like to be able to select some text and type some shortcut to have the selected text reformatted by pyfmt.

So far I've found that running !pyfmt -i % will format the whole file. pyfmt also supports a --lines START-END option. I'd like to be able to pass the line numbers of the beginning and end of the selected text to pyfmt so that only what I want to reformat gets reformatted. Is this possible?

2 Answers

I will provide my case as follow and I think it can be customized to your case, easily.


I have a Vim-Plug plugin Plug 'tpope/vim-commentary', and it has a command: (l,r are line numbers)

:l,rCommentary

When you visual-selected lines in Vim and then press : you will get:

:'<,'>

Based on this observation the command I need is: (visual mode mapping)

vnoremap <silent> my_shortcut :Commentary<CR>gv

i.e. I just need :Commentary since when it execute : the '<,'> is added for you.


To understand <silent>: https://stackoverflow.com/a/962118/5290519

Related