Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to get line numbers of selected text in vim

Tags:

vim

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?

like image 732
Paymahn Moghadasian Avatar asked Jul 18 '17 23:07

Paymahn Moghadasian


People also ask

How to show line number in Vim text editor?

How to show line number in vim. To show line number along the left side of a vim window, type any one of the following command while using vim text editor. First press the Esc key. Press : and type any one of the following command at a : prompt – set nu Alternatively, type: set number.

How do I add a number to a line in Unix?

To activate the line numbering, set the number flag: Press the Esc key to switch to command mode. Press : (colon) and the cursor will move at the bottom left corner of the screen. Type set number or set nu and hit Enter.

Why is the current line 0 in Vim?

The current line is presented as 0 when relative line numbering is enabled; the lines above and below the current line are gradually numbered ( 1, 2, 3, etc.). Because many Vim operations, such as moving up/down and deleting lines, rely on relative line numbers, relative line mode is useful.

How do I set the line numbering on the keyboard?

To activate the line numbering, set the number flag: 1 Press the Esc key to switch to command mode. 2 Press : (colon) and the cursor will move at the bottom left corner of the screen. Type set number or set nu and hit... 3 Line numbers will be displayed at the left side of the screen: More ...


1 Answers

Select the lines you want to format (preferably linewise, using capital V to enter visual mode), and then, without leaving visual mode, type :!pyfmt -i.

This will not give you the line numbers. Instead, it will filter the selected lines through the command and replace them with the output.

like image 129
Kevin Avatar answered Oct 10 '22 14:10

Kevin