Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Enumerate existing text in Vim (make numbered list out of existing text)

I have a source document with the following text

Here is a bunch of text
...
Collect underpants
???
Profit!
...
More text

I would like to visually select the middle three lines and insert numbers in front of them:

Here is a bunch of text
...
1. Collect underpants
2. ???
3. Profit!
...
More text

All the solutions I found either put the numbers on their own new lines or prepended the actual line of the file.

How can I prepend a range of numbers to existing lines, starting with 1?

like image 713
user1717828 Avatar asked Aug 17 '15 14:08

user1717828


People also ask

How do I increase the number in a selection in Vim?

In Vim 8, the first number in a selection can be incremented by pressing Ctrl-A. If the selection covers several lines, the first number in the selection on each line is incremented. Alternatively, numbers in a selection covering several lines can be converted to a sequence by typing g Ctrl-A. For example, start with the following line:

How do I create a sequence of zeros in Vim?

The result is: With the cursor on the first 0 in the first line, start a blockwise select by pressing Ctrl-V (or Ctrl-Q if you use Ctrl-V for pasting). Move the cursor down to select the first column of zeros, then press g Ctrl-A. Using Vim 8, that will give: Vim 7 and earlier need a script or a macro to create a sequence.

How do you enumerate a string in Python?

In Python, you use enumerate (): fruit = [ 'banana', 'apple', 'pear', 'peach' ] for i, item in enumerate (fruit, 1): print (i, '. ' + item, sep= '', end = '') How enumerate () Works The enumerate (iterable, start) function will return a sequence of tuples.

How do you make a numbered list in Python?

See Python: Tips and Tricks for similar articles. You have a list of items and want to print it out as a numbered list using Python. In another programming language, you might create a variable called i or num and then loop through the list incrementing the variable value by 1 with each iteration.


1 Answers

It makes for a good macro.

  1. Add the first number to your line, and put your cursor back at the beginning.
  2. Start a macro with qq (or q<any letter>)
  3. Copy the number with yf<space> (yank find )
  4. Move down a line with j
  5. Paste your yank with P
  6. Move back to the beginning of the line with 0
  7. Increment the number with Ctrl-a
  8. Back to the beginning again with 0 (incrementing positions you at the end of the number)
  9. End the macro by typing q again
  10. Play the macro with @q (or @<the letter you picked>)
  11. Replay the macro as many times as you want with <number>@@ (@@ replays the last macro)
  12. Profit!

To summarize the fun way, this GIF image is i1. <Esc>0qqyf jP0^a0q10@q. Vim list macro

like image 56
Kristján Avatar answered Oct 15 '22 09:10

Kristján