Creating Windows in Neovim

Published Fri Feb 16 2024

Lately I’ve been working on growing my Neovim knowledge. I want to graduate from one who uses this program to someone who develops code for it. The best place to start is by identifying and fulfilling my own editor needs. I am working on sorting my Zettelkasten notes, and want to present this to myself in a window similar to a file tree. Here is how you can write your own text to a Neovim window!

First, we need a buffer to hold the text we want to view. This can be created with Neovim’s vim.api.nvim_create_buf which returns the identifier for your new buffer. I’ve done this and named it buf:

nvim_create_buf

local buf = vim.api.nvim_create_buf(true, true)

There are two parameters for nvim_create_buf. These control if the new buffer is in the buffer list({listed}) and if the buffer is a throwaway or {scratch} buffer.

Now that you have a buffer you can configure it using nvim_buf_set_option. I’m going to use nvim_buf_set_name to name my buffer:

vim.api.nvim_buf_set_name(buf 'zettels')

nvim_buf_set_lines

Then you can set the content of your new buffer using nvim_buf_setlines. This accepts a table of strings which represent the content of each line in the buffer.

-- write over the buffer starting from line 0
vim.api.nvim_buf_set_lines(buf, 0, -1, true, { "Hello world!", "2nd line" })
-- append to the file by replacing 0 with -1
vim.api.nvim_buf_set_lines(buf, -1, -1, true, { "3rd line" })

nvim_win_set_buf

Now that your buffer is ready the last step is putting it in a window. A quick and easy way to do this is with the :vsplit command you may already be familiar with. Using vim.cmd we split to create a new window, then open our buffer in it.

vim.cmd(':vsplit')
vim.api.nvim_win_set_buf(vim.api.nvim_get_current_win() buf)

Managing windows and buffers is essential for Neovim scripting. If you would like to create a floating window instead check out my floating journal post.