Vim macro: increasing numbers on non-serial lines

I am working with a YAML file that has an integer as an ID that appears every 4-6 lines. I want to add an entry in the middle of this file (for readability) that will preserve sequential numbering.

The file format is below. Any ideas?

- id: 1
  type: string
  option: diff_string
  other: alt_string   // note: 'other' option does not appear for all records

- id: 2
  type: string
  option: diff_string

//new record would go here as id: 3, increasing id: # of all following records by 1

- id: 3
  type: string
  option: diff_string
  other: alt_string
+5
source share
3 answers

I believe that you can achieve what you want by setting the counter (here: variable g:I) to 1:

let g:I=1

And then do the substitution on each line that matches ^- id: \d\+$:

%g/^- id: \d\+$/ s/\d\+/\=g:I/|let g:I=g:I+1

Substitution uses \=thingy (see :help sub-replace-expression) to substitute \d\+with the actual value g:I. After substitution, the counter is incremented ( let g:I=g:I+1).

g/^- id: \d\+$/ , , ^- id: \d\+.

. , .vimrc:

nnoremap resync :let g:I=1<CR>:%g/^- id: \d\+$/ s/\d\+/\=g:I/\|let g:I=g:I+1<CR>

, resync .

| \ <CR>, enter.

+5

+ 1:

:.+1,$g/^- id: \d\+$/exec 'normal! 0' . nr2char(1)

(nr2char(1) - CTRL-A).

:

:.+1,$g/^- id: \d\+$/normal! 0^A

^A CTRL-V, CTRL-A. , : , .

:

  • .+1,$ - . :help range.
  • :g , . :v. :help :g
  • /^- id: \d\+$/ - id: , 1 , (:help pattern)
  • :normal! : 0, , CTRL-A, .

:

nnoremap <F1> :.+1,$g/^- id: \d\+$/exec 'normal! 0' . nr2char(1)<enter>

vimrc F1 , .

+3

I would use the following short and simple substitution command.

:,$s/^- id: \zs\d\+/\=submatch(0)+1/
+1
source

All Articles