Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Difference between $ and g_ in vim?

Tags:

vim

I was trying to learn some new neat shortcuts in vim and I discovered g_. According to http://yannesposito.com/Scratch/en/blog/Learn-Vim-Progressively/

$  → go to the end of line
g_ → go to the last non-blank character of line

When would I use g_ instead of $?

like image 676
sunnyrjuneja Avatar asked Aug 11 '12 21:08

sunnyrjuneja


2 Answers

g_ is AWESOME when you're yanking text to paste somewhere you don't want the line break included -- like the command line where it will then automatically run the command.

like image 188
kenny Avatar answered Oct 18 '22 23:10

kenny


I think the most important difference is simply stated in the help files:

:h $
In Visual mode the cursor goes to just after the last character in the line.

So if you do v$d it deletes including "after the last character" which is the newline so it will bring the line below it up to the current one. But if you do vg_d it will keep the newline.

I actually didn't know about g_, seems useful.

Edit Since this answer gets upvotes, I have since used g_ (and its reverse, _) to make a mapping that yanks / deletes the current line excluding leading/trailing whitespace and excluding linebreaks:

" delete/yank line, but only whitespace-trimmed version
nnoremap <Leader>dd _yg_"_dd
nnoremap <Leader>yy _yg_
like image 43
Andy Ray Avatar answered Oct 18 '22 22:10

Andy Ray