Monday, May 6, 2019

Re: Create buffer without opening a window

On 7 May 2019, at 00:39, Tony Mechelynck <antoine.mechelynck@gmail.com> wrote:

On Mon, May 6, 2019 at 9:40 PM 'Lifepillar' via vim_use
<vim_use@googlegroups.com> wrote:

On 6 May 2019, at 20:57, 'Andy Wokula' via vim_use <vim_use@googlegroups.com> wrote:

Am 06.05.2019 um 17:02 schrieb '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?

(pretty sure that) setbufline() refuses to work with an unloaded buffer.

Oh yes, you are right. So, I guess I will have to use :new or similar, then
hide the window.

Life.

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.

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.

No comments: