'Avoid read file being the alternate buffer in Vim
I am having an issue with Vim, NeoVim in this case if it makes a difference. I have an autocmd that includes a boilerplate when creating a file of a certain type, a Vue file in this case. Here is the code:
autocmd BufNewFile *.vue silent! 0r ~/.dotfiles/skeletons/vue-pug-scss.vue
This simple thing works great except when using CTRL-^ it goes back to the boilerplate file and I don't want this. I don't want the boilerplate file to be in my history of visited files so to speak.
I've tried many things but I struggle to understand how the buffer list works together with CTRL-^. The thing is that if I run :ls, the boilerplate file does not appear even though it is what I get when doing CTRL-^. It only appears in :ls once I've been back on it.
What I thought would work is to add | bd# but it says no buffer was deleted. When I am on the newly created file, :bd# does not work whereas :b# works. This sounds completely illogical to me, or inconsistent at best. Although I am probably mixing up an alternate buffer and previous buffer or something.
Does anybody know how I can make this work?
Solution 1:[1]
Here you have two sub-questions:
I don't want the boilerplate file to be in my history of visited files so to speak.
Some possible options in no particular order
- Avoid using
:h :readcommand in favor of:h readfile()and:h append()or such; - Remove
afrom:h 'cpoptions'; - Prepend
:h :keepaltto your command.
Note that 3) still creates a new buffer, although it doesn't become the alternate one.
The thing is that if I run :ls, the boilerplate file does not appear
When I am on the newly created file, :bd# does not work whereas :b# works. This sounds completely illogical to me, or inconsistent at best.
A buffer in Vim has boolean states of "loaded" and "listed". Both are independent one from another.
:h :ls only shows "listed" buffers by default. To see "unlisted" buffers too one has to type :ls!
:h :bdelete changes buffer state to be "unlisted" and "unloaded" at the same time. As your buffer is already "unlisted" and "unloaded" you've got :h E516. You may use :h :bwipeout to remove a buffer completely, but in this case pressing :h CTRL-^ will result in :h E23 error. To set new alternate buffer you can type :let @# = 42, where 42 is some existing buffer number or name. Alternatively, :balt foobar can create a new unloaded and listed buffer named foobar and set it as the alternate one.
Solution 2:[2]
From :help :read, emphasis mine:
If a file name is given with ":r", it becomes the alternate file. This can be used, for example, when you want to edit that file instead: ":e! #". This can be switched off by removing the 'a' flag from the 'cpoptions' option.
Sources
This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.
Source: Stack Overflow
| Solution | Source |
|---|---|
| Solution 1 | Matt |
| Solution 2 | romainl |
