Recover a deleted file in VIM after running dG - vim

I was smart enough to run the dG command in vim and instead of simply quitting my muscle memory put in a :wq.
Is there any way to restore the file?

d<motion> cuts the text covered by <motion> into the unnamed register, ". Assuming you have a relatively "normal" setup, Vim should have written the content of that register to ~/.viminfo when you did :wq. If so, you should be able to edit the same file and put the content of that register back into the buffer.
Edit your file in a new Vim session:
$ vim filename
The buffer should be empty.
Inspect the content of every register with :registers to see if it is still stored. If you didn't use Vim in the mean time, register " should have it.
If it is there, do the following, starting from normal mode:
v " start visual mode
"<name of register>p " put from register <name of register>

Related

Redo after reopening a file in Vim

I am using vim editor. I was writing a program and did some of the changes in the file after which I "undo" all the changes and by mistake closed the file. Later I realized that the approach that I was doing in the code is right, So I again opened the file and tried to do "redo" operation,but as I have closed the session I think I have lost all the history. Can somebody please tell me if I can do redo by some means as retyping the whole thing again is quite tedious.
Is there some way in which I can redo changes after opening a new session of Vim file
For that you need to have :help persistent-undo enabled:
When unloading a buffer Vim normally destroys the tree of undos created for
that buffer. By setting the 'undofile' option, Vim will automatically save
your undo history when you write a file and restore undo history when you edit
the file again.
Unfortunately, 'undofile' is off by default, so unless you've configured it (and if you've tried redo and failed, that looks like it's off), it's of no use for your current problem.
If the swap-file is still lying around (unlikely as there was a clean exit of Vim), you might be able to grab small incoherent bits of your edits from it.
soap box
To preempt the typical comments: You probably have to accept the loss right now, but take this as an opportunity to rethink your approach. Persistent undo is a really nice feature. With a modern revision control systems (like Git or Mercurial), you can commit often and only locally, and revising your edits is easy to do. Even if that's not an option, there are plugins for Vim (like my writebackup plugin) that make it very easy to frequently save "snapshots" of important editing states. Any of these could save you from the data loss next time!
Another approach, in case you have executed some commands, is recovering your command history by redirecting it into a register.
:redir #h
:history
:redir END
:set paste
"hp
:redir #h ............. start redirecting output to register "h"
:history .............. outputs all commands history
:redir END ............ stops redirecting
:set paste ............ to avoid wrong indentation
"hp ................... puts the "h" register in the current position
you can control where to put it by doing...
0put h .............. pastes the `h` register at the line zero
Once you have a series of commands into a file or register it makes easier to build a function like:
function! Helo()
echo "hello world"
endfunction
If by any change you have used a macro, let's say q, you can retrive it or even edite it, because macros are regular registers that you can reassign as you want. For example, on insert mode you can type:
Ctrl-r q .................... pastes register q
:let #q= ................... starts reassingning macro q
:let #q= ctrl-r q .......... pastes the q register on its reassignment
setting register q to "hello vim"
:let #q = "ihello\<Return>vim\<Esc>"
OBS: Using double quotes you can use control keys as seen above
Any complex command can be saved into the clipboard
:let #+ = #: .............. places last command on the clipboard
:#+ ......................... uses clipboard as command

How to open VIM [no name] file from terminal

I am using linux.
In terminal I can type
vim sample
A vim window for the file 'sample' opens
Here any change can be saved with :w
But I want to open a new vim file having no name and save it with the name sampleName using
:w sampleName
But I am unable to do so.
Typing only vim in terminal gives me a window with about and copyright information
I am not using gvim but vim
You should be able to just run vim with no arguments. It will open vim by itself. To save it to a file, execute the command: :w <new file name>
Issue the Command, :enew and Also Learn about How Vim Manages File Editing
I would recommend reading up on file and buffer usage in Vim in the help file, usr_22.txt.
As architrex has indicated, by default, if one does not have a file(s) listed in the argument list when starting Vim, a new buffer is created. See :help starting.
If you started vim with one file in the file argument list like you described, vim sample, a common way to work with an empty buffer is to issue the :enew command (typically after you would have written changes to the file named, sample, :w).
We can see the new buffer here:
Once one is done modifying the new buffer, you can issue the write command, :w sampleName, with the expected result of writing the file.
Vim's use of buffers is intuitive and you will become more skillful as you use it.
When I started using Vim, I leveraged using NETRW which is a seeded file navigation plugin with Vim for file creation (and placing those new files in buffers).
What follows is one way to leverage NETRW to do this.
If you have already started Vim, I would type :Exp or :e . which are ex commands which will start the file explorer which is a feature of the seeded file navigation plugin, NETRW.
One could start Vim:
Start the file explorer for NETRW:
I would then use the file explorer to navigate to the desired file to create a new file you wish to edit (k is up, j is down, enter key means select).
Next, I would type,%, once I have navigated to the desired location.
You will be notified to "Enter filename". Just enter "sampleName" and press enter.
Go into edit mode (e.g. i) and start typing.
NETRW is a robust file navigation tool. Creating files in the file locations desired is an essential skill to have to utilize Vim well.
You could also read the help files concerning NETRW (e.g. the ex command, :help netrw).

in vim, how to get rid of irritating "E141: No file name for buffer nn"

This happens when I open an anonymous scratch file, and then do a :wa
even if I close the buffer.
Your own answer is just curing the symptoms, not tackling the root cause.
It's better to properly indicate to Vim that your "scratch buffer" (which I guess is just by convention for you) is not meant to be persisted. That's what the 'buftype' option is for. Open a scratch buffer with this (or create a corresponding mapping or command):
:new +setl\ buftype=nofile
so you either need to save the buffer (and give it a name)
or since it's a scratch file, if you're done with it you need to force vim to delete it properly:
:b nn " where nn = the errant buffer
:bd! " kill the scratch file
use :h bd for more info

how to yank text from one instance of gvim to another using ex commands

So I have a lot of lines to copy from one file (open in one instance of gvim) to another file (open in another instance of gvim) and I'm using ex commands. So I tried doing the usual
:0,164ya
and then going to the other file and doing
:pu
and I also tried
:+0,164ya
and then
:+pu
but neither worked. I also tried using p instead of pu. Anyone have any idea on how to do this?
Use the "+ or "* registers:
:0,164y +
:put +
Vim doesn't sync its register contents across Vim instances. Therefore, you have to use a shared data store like the system's clipboard (register "+), or a separate file (:[range]w /tmp/file, followed by :r /tmp/file).
If you really need to transfer multiple register contents at once (where the approaches above become tedious), you have to explicitly sync the register contents via the viminfo file that persists them (among all other history).
In Vim 1:
:[range]yank a
:wviminfo
In Vim 2:
:rviminfo!
:put a

How do I close a single buffer (out of many) in Vim?

I open several files in Vim by, for example, running
vim a/*.php
which opens 23 files.
I then make my edit and run the following twice
:q
which closes all my buffers.
How can you close only one buffer in Vim?
A word of caution: “the w in bw does not stand for write but for wipeout!”
More from manuals:
:bd
Unload buffer [N] (default: current
buffer) and delete it from
the buffer list. If the buffer was changed, this fails,
unless when [!] is specified, in which case changes are
lost.
The file remains unaffected.
If you know what you’re doing, you can also use :bw
:bw
Like |:bdelete|, but really delete the
buffer.
If this isn't made obvious by the the previous answers:
:bd will close the current buffer. If you don't want to grab the buffer list.
Check your buffer id using
:buffers
you will see list of buffers there like
1 a.php
2 b.php
3 c.php
if you want to remove b.php from buffer
:2bw
if you want to remove/close all from buffers
:1,3bw
Rather than browse the ouput of the :ls command and delete (unload, wipe..) a buffer by specifying its number, I find that using file names is often more effective.
For instance, after I opened a couple of .txt file to refresh my memories of some fine point.. copy and paste a few lines of text to use as a template of sorts.. etc. I would type the following:
:bd txt <Tab>
Note that the matching string does not have to be at the start of the file name.
The above displays the list of file names that match 'txt' at the bottom of the screen and keeps the :bd command I initially typed untouched, ready to be completed.
Here's an example:
doc1.txt doc2.txt
:bd txt
I could backspace over the 'txt' bit and type in the file name I wish to delete, but where this becomes really convenient is that I don't have to: if I hit the Tab key a second time, Vim automatically completes my command with the first match:
:bd doc1.txt
If I want to get rid of this particular buffer I just need to hit Enter.
And if the buffer I want to delete happens to be the second (third.. etc.) match, I only need to keep hitting the Tab key to make my :bd command cycle through the list of matches.
Naturally, this method can also be used to switch to a given buffer via such commands as :b.. :sb.. etc.
This approach is particularly useful when the 'hidden' Vim option is set, because the buffer list can quickly become quite large, covering several screens, and making it difficult to spot the particular buffer I am looking for.
To make the most of this feature, it's probably best to read the following Vim help file and tweak the behavior of Tab command-line completion accordingly so that it best suits your workflow:
:help wildmode
The behavior I described above results from the following setting, which I chose for consistency's sake in order to emulate bash completion:
:set wildmode=list:longest,full
As opposed to using buffer numbers, the merit of this approach is that I usually remember at least part of a given file name letting me target the buffer directly rather than having to first look up its number via the :ls command.
Use:
:ls - to list buffers
:bd#n - to close buffer where #n is the buffer number (use ls to get it)
Examples:
to delete buffer 2:
:bd2
You can map next and previous to function keys too, making cycling through buffers a breeze
map <F2> :bprevious<CR>
map <F3> :bnext<CR>
from my vimrc
Close buffer without closing the window
If you want to close a buffer without destroying your window layout (current layout based on splits), you can use a Plugin like bbye. Based on this, you can just use
:Bdelete (instead of :bdelete)
:Bwipeout (instead of :bwipeout)
Or just create a mapping in your .vimrc for easier access like
:nnoremap <Leader>q :Bdelete<CR>
Advantage over vim's :bdelete and :bwipeout
From the plugin's documentation:
Close and remove the buffer.
Show another file in that window.
Show an empty file if you've got no other files open.
Do not leave useless [no file] buffers if you decide to edit another file in that window.
Work even if a file's open in multiple windows.
Work a-okay with various buffer explorers and tabbars.
:bdelete vs :bwipeout
From the plugin's documentation:
Vim has two commands for closing a buffer: :bdelete and :bwipeout. The former removes the file from the buffer list, clears its options, variables and mappings. However, it remains in the jumplist, so Ctrl-o takes you back and reopens the file. If that's not what you want, use :bwipeout or Bbye's equivalent :Bwipeout where you would've used :bdelete.
How about
vim -O a a
That way you can edit a single file on your left and navigate the whole dir on your right...
Just a thought, not the solution...
[EDIT: this was a stupid suggestion from a time I did not know Vim well enough. Please don't use tabs instead of buffers; tabs are Vim's "window layouts"]
Maybe switch to using tabs?
vim -p a/*.php opens the same files in tabs
gt and gT switch tabs back and forth
:q closes only the current tab
:qa closes everything and exits
:tabo closes everything but the current tab
Those using a buffer or tree navigation plugin, like Buffergator or NERDTree, will need to toggle these splits before destroying the current buffer - else you'll send your splits into wonkyville
I use:
"" Buffer Navigation
" Toggle left sidebar: NERDTree and BufferGator
fu! UiToggle()
let b = bufnr("%")
execute "NERDTreeToggle | BuffergatorToggle"
execute ( bufwinnr(b) . "wincmd w" )
execute ":set number!"
endf
map <silent> <Leader>w <esc>:call UiToggle()<cr>
Where "NERDTreeToggle" in that list is the same as typing :NERDTreeToggle. You can modify this function to integrate with your own configuration.

Resources