Is there a way I can open a file in VimL/VimScript and keep it hidden from the user? I am writing a plugin which is attempting to figure out exactly what it should do by looking for and potentially searching the content of certain files. Currently I am doing an :sview
to open the file in a new window. After using :global/.../y a
to search the file and read out the results of what I found, I :close
the file. However, by this way of doing it there is a chance for a strange user experience of seeing a file you did not explicitly request to be opened flash open momentarily before you and then close again. My current approach does what I need, but I would like to find a less visually jarring way to do this.
How do I open a file in VimScript in a way that I can manipulate it (read-only) without showing it in a window?
Another answer that allows you to use a buffer.
Vim is single threaded, and any vimscript you run will run completely without the GUI being refreshed in the middle. So the new window flashing before the user is not a problem - you'll be done with it before Vim has a chance to refresh the screen.
What the user can notice, is the layout change. sview
opens the buffer in a new window, so Vim might resize the currently open windows. When you close the temporary window the other windows will be resized again - the the end result might not be the same as the original sizes.
The solution? don't create a new window. Load the temporary buffer to the current window with :view
, do whatever you need to do with it, return to the original buffer with :buffer
, and close the temporary buffer with :bdelete
(unless you want to keep it loaded.
This, ofcourse, will pose a problem if the currently loaded buffer is changed. :hide
to the rescue! :hide {cmd}
will run {cmd}
as if the current buffer is set to hidden
. That means that any command that switches the window to another buffer will simply hide the current buffer, even if it has changes.
So - simply load the temp buffer with :hide view
. You might also want to restore it with :hide buffer
, just in case something goes wrong and you introduce changes in the temp buffer(which means you should also close it with :bdelete!
).
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With