How can I get size of my current workspace?

Hey there, how can I get size of my current workspace?

You can use a combination of win functions.

nvim_win_get_position(window)
nvim_win_get_width(window)
nvim_win_get_height(window)

If your work area is made up of multiple windows you can cycle through each window and get the min row/col position and then the height/width would be the max win row/col + height/width.

To get a list of windows there is

nvim_tabpage_list_wins(tabpage)

If you don’t use tabpages you can also use

nvim_list_wins()

If you want to exclude a side bar like a file tree, you can just exclude that in your loop based on some identifying value like the window buffers filetype.

I just found a bit simpler way:

height = tonumber(vim.api.nvim_command_output("echo &lines")) or 0
width = tonumber(vim.api.nvim_command_output("echo &columns")) or 0

Posting in case someone is still looking for it like I was.

EDIT (few things worth noting):

  • vim.api.nvim_command_output returns string so you need to cast it with tonumber
  • for some reason, on my side vim.api.nvim_command_output("echo &columns")) sometimes returns just empty string (probably one of my plugins is messing something). That’s why I’m using or 0 at the end of these functions…
  • …when you also encounter the said problem, the workaround is to store the height/width in the global value and only update it when width/height is not 0
  • btw, it’s super strange that neovim does not have native functions to handle this things, or maybe I wasn’t able to find it anywhere… hmnn… there might be a better way to achieve this.

You’re a life-saver.
I’ve been searching for this for ages

Thanks!

just use vim.o.columns

1 Like