Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

Tags:

vim

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.

like image 418
ThG Avatar asked Jul 22 '11 20:07

ThG


1 Answers

Here's one way to do the ref numbers, with a pair of functions:

function! MakeRefMarkers()
     " Remove spaces from empty lines:
     %s/^ \+$//
     " Mark all spots for ref number:
     %s/^\_$\_.\zs\(\s\|\S\)/_parref_/
     " Initialize ref val:
     let s:i = 0
     " Replace with ref nums:
     %s/^_parref_/\=GetRef()/
endfunction

function! GetRef()
     let s:i += 1
     return s:i . '.  '
endfunction

Then just do it by calling MakeRefMarkers(). It doesn't remove existing ref numbers if they're there, that would require another step. And it doesn't catch first paragraph if it's first line in file (i.e, without preceding blank line). But it does handle situations where there's more than one blank line between paragraphs.

like image 181
Herbert Sitz Avatar answered Oct 13 '22 20:10

Herbert Sitz