0

I want to update one buffer content from another buffer periodically, for this I need to delete all lines from the target buffer firstly, then to write new lines to it. The number of lines are varying, so the extra lines which are left from the previous update should be deleted.

At this moment I found two ways to solve this task, but both are not ideal.

First

function! Buffer_update()
    " Buffer information saving
    let l:save_cur_pos = getcurpos()
    let l:save_buf_nr = bufnr('%')

    " Moving to the target buffer and cleaning its content
    buffer one 
    silent %d _

    " Simulation of the varying number of lines
    for l:num in range(system('echo $((RANDOM % 10 + 1))'))
        call setbufline('one', l:num, 'hello')
    endfor

    " Buffer information restoring
    execute 'buffer' . l:save_buf_nr
    call setpos('.', l:save_cur_pos)
endfunction

Result (buffer one)

enter image description here

Drawback: I don't like switching between buffers to achieving a desired result. It can be solved without switching, like in the second variant, but there is some problem too. It will be perfect to have delbufline() function like setbufline(), but I didn't find such one.


Second

function! Buffer_update()
    " Simulation of the varying number of lines
    for l:num in range(system('echo $((RANDOM % 10 + 1))'))
        call setbufline('one', l:num, 'hello')
    endfor

    " Deleting of extra lines from the previous update
    while l:num <= len(getbufline('one', 1, '$'))
        call setbufline('one', l:num, '')
        let l:num += 1
    endwhile
endfunction

Result (buffer one)

enter image description here

Drawback: This solution leaves blank lines. In other words, it doesn't delete lines, just makes them empty.

The questions:

  1. Does some delbufline() function exist, similar to setbufline()?
  2. Maybe someone can suggest more suitable solution, without aforementioned drawbacks?

1 Answer 1

2

The function is called deletebufline()

let l:bufnr = bufnr('thatbuf')
if l:bufnr != -1
    silent call deletebufline(l:bufnr, 1, '$')
    call setbufline(l:bufnr, 1, GetListOfLines())
endif

UPD. deletebufline() was added in Vim 8.1.0039

5
  • I don't have such function: "E149: Sorry, no help for deletebufline() ". My vim version is 8.0
    – MiniMax
    Feb 25, 2020 at 18:04
  • 1
    @MiniMax Update your Vim installation
    – Matt
    Feb 25, 2020 at 18:06
  • 1
    what is the silent for? Feb 26, 2020 at 9:18
  • 1
    @ChristianBrabandt If the buffer was empty then deletebufline() prints "No lines in buffer".
    – Matt
    Feb 26, 2020 at 13:06
  • @Matt ah thanks. Feb 26, 2020 at 14:22

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge that you have read and understand our privacy policy and code of conduct.

Not the answer you're looking for? Browse other questions tagged or ask your own question.