Search code examples
luabufferneovimkey-bindings

How to open a new text file in buffer using total number of buffer in neovim?


I want to make a keymap for <F7> in neovim such that if the current file is a text file then a new file will open horizontally but the file name will depend on the total number of buffer. Ex: Now open files are inp1.txt, inp2.txt in buffer. And total number of buffer is 2. If I press <F7> a new file inp3.txt will open horizontally. How can I do this in my neovim lua config file? Here all files have inp and .txt. Just change the number.

I want to make something like cph (vs code extension) for competitive programming. I use tmux. I open the cpp file in the left side in a tmux pane and in the the other right side pane I want to open some txt file horizontally to contain the input. But I want to open a txt file quickly. I want to do it using key.


Solution

  • Considering Neovim still supports vanilla VimScript, this should do it:

    noremap <F7> :execute ":new inp" .. (bufnr('$') + 1) .. ".txt"<CR>
    

    A bit more complex solution to account only existing buffers:

    noremap <F7> :execute ":new inp" .. (len(filter(range(1, bufnr('$')), 'bufexists(v:val)')) + 1) .. ".txt"<CR>