Create buffer without opening a window

37 views
Skip to first unread message

Lifepillar

unread,
May 6, 2019, 11:03:08 AM5/6/19
to 'Lifepillar' via vim_use
I would like to create a new buffer "in the background", without opening
any new window, put some text into the buffer then write it to disk,
without ever showing the buffer (the reason why I am not populating
a List and use writefile() directly is that I need to perform some text
manipulation such as reindenting the text). I thought that something
like this would do it:

let n = bufnr('my new buffer', 1)
call setbufline(n, 1, 'hello')
call writefile(getbufline(n, 1, "$"), './foo.txt')

but the buffer stays empty and setbufline() returns 1. What should I do
instead?

Thanks,
Life.


Andy Wokula

unread,
May 6, 2019, 2:57:44 PM5/6/19
to vim...@googlegroups.com
(pretty sure that) setbufline() refuses to work with an unloaded buffer.

--
Andy

Lifepillar

unread,
May 6, 2019, 3:40:20 PM5/6/19
to 'Lifepillar' via vim_use
Oh yes, you are right. So, I guess I will have to use :new or similar, then
hide the window.

Life.

Tony Mechelynck

unread,
May 6, 2019, 6:39:42 PM5/6/19
to vim...@googlegroups.com
What I do when I want to create a buffer, maybe do some pre-programmed
edits on it, and write it to disk, is write a function or user-command
to open the buffer (by :new or similar), do the necessary edits, and
close it (by :x or similar, which writes it if it is modified).
Depending on the importance of the edits, and on the values of some
window-size-related options, it may even happen unnoticed.

Best regards,
Tony.

Lifepillar

unread,
May 7, 2019, 2:18:01 AM5/7/19
to 'Lifepillar' via vim_use
Thanks for the suggestion. What I ended up doing is:

1new
let n = bufnr(“%”)
wincmd c
“ Edit with setbufline(n, …) and appendbufline(n,…)

It works perfectly for my needs.

Life.

Reply all
Reply to author
Forward
0 new messages