Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to delete (not cut) in Vim?

Tags:

vim

copy-paste

People also ask

How do I delete a whole section in Vim?

Step 1: Move your cursor to the top line of the block of text/code to remove. Step 2: Press V (Shift + v) to enter the Visual mode in Vim/Vi. Step 3: Now move your cursor down to the bottom of the block of text/code to remove. Step 4: Press d to delete the block selected.

How do I delete something in Vim?

Deleting a single line in Vim editor: First, bring your cursor to the line you want to delete. Press the “Esc” key to change the mode. Now type, “:d”, and press “Enter” to delete the line or quickly press “dd”.


The black hole register "_ will do the trick, but there is a better solution:

When you enter the line back with the p command you are pasting the contents of the (volatile) default register "", which has been overwritten by dd. But you still can paste from the (non volatile) yank register "0, which won't be overwritten by the delete command dd.

So these are the commands you want to use as per your example:

yy
dd
"0p

Use the "black hole register", "_ to really delete something: "_d.
Use "_dP to paste something and keep it available for further pasting.

For the second question, you could use <C-o>dw. <C-o> is used to execute a normal command without leaving the insert mode.

You can setup your own mappings to save typing, of course. I have these:

nnoremap <leader>d "_d
xnoremap <leader>d "_d
xnoremap <leader>p "_dP

That's one of the things I disliked about vim... I ended up mapping dd to the black hole register in my .vimrc and life has been good since:

nnoremap d "_d
vnoremap d "_d

the following mappings will produce:

  • d => "delete"
  • leader d => "cut"
nnoremap x "_x
nnoremap d "_d
nnoremap D "_D
vnoremap d "_d

nnoremap <leader>d ""d
nnoremap <leader>D ""D
vnoremap <leader>d ""d

Also, it is a nice practice to have the "leader" key set to comma, e.g:

let mapleader = ","
let g:mapleader = ","

these 2 snippets will make ",d" be your new cut command.

If you would like to use these mappings togther with a shared system clipboard configuration, see further details at https://github.com/pazams/d-is-for-delete


You can use "_d to prevent things from overwriting your yanked text. You can store yanked or deleted text in whatever register you want with ", and _ is the 'black hole' register, where you send stuff that you don't care about.

For more information you can type :help "_ or :help deleting