Vim: How to number paragraphs automatically and how to refer to this numbering?

Viewed 887

Let us say I have the following three paragraphs of text (separated from each other by empty lines—number 3 and 7, here):

This is my first paragraph line 1
This is my first paragraph line 2

This is my second paragraph line 4
This is my second paragraph line 5
This is my second paragraph line 6

This is my third paragraph line 8
This is my third paragraph line 9

Question 1: How can I number these paragraphs automatically, to obtain this result:

1   This is my first paragraph line 1
    This is my first paragraph line 2

2   This is my second paragraph line 4
    This is my second paragraph line 5
    This is my second paragraph line 6

3   This is my third paragraph line 8
    This is my third paragraph line 9

(I succeeded to do this, but only via a clumsy macro.)

Question 2: Is it possible to refer to these paragraphs? For instance, is it possible to index a text file as answered (by Prince Goulash and Herbert Sitz) in the earlier question, but this time with the paragraph numbers and not the line numbers?

Thanks in advance.

4 Answers

My approach would be macro based:

  1. Yank the number "0" somehow and move to the start of the first paragraph.

  2. Record a macro to

    1. Indent the paragraph with >}

    2. Paste the stored number at the correct position p

    3. Increment the number by one with <ctrl>-a

    4. Yank the pasted number with yiw

    5. Move to the next paragraph with }l or /^\S

  3. Execute the macro as many times as needed to reach the end of the document.


The method of pasting a number, incrementing it, and then reyanking it inside a macro is quite a useful technique that comes in handy whenever you need to number things. And it's simple enough to just do it in a throw-away fashion. I mainly use it for carpet logging, but it has other uses as your question demonstrates.

Related