Say I have a list like this:
1. apple
2. banana
3. orange
4. plum
Now I want to reorder them by deleting/cutting lines and pasting them in the right spot, but the numbers are no longer in order:
2. banana
1. apple
4. plum
3. orange
How can I re-number this list or have Vim handle a numbered list automatically? (I'll add my answer, but I believe there should be a faster way)
One slightly inefficient way is to reset the numbered list to zeros and then recreate them.
For instance, once the list looks like this:
2. banana
1. apple
4. plum
3. orange
do the following.
:s/[0-9]*\./0./
to substitute the numbered list for a list all beginning with 0.
0. banana
0. apple
0. plum
0. orange
gv
(as suggested in comments) and do g
and then <ctrl> + a
to renumber list from 1-nEDIT April 2nd, 2024 - Based on the suggestion from @romainl in the comments and from community help in these questions (one and two), I took my solution above and made a Vimscript function that can be added to a .vimrc
.
vnoremap <C-L> :call ReNumberList()<CR>
function! ReNumberList() range
execute a:firstline .. ',' .. a:lastline .. 's/[0-9]*\./0./'
execute "normal! gvg\<C-A>"
endfunction
It works by remapping the shortcut ctrl+L
(<C-L>
) to the function ReNumberList()
. That function does the number substitution on the range of lines, re-highlights the range again (with gv
), and finally does the renumbering with g\<C-A>
.
With this, you can highlight an out of order list and then type one shortcut to renumber the whole list!