Difference between $ and g_ in vim?

vim

Solution

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_

Problem

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 $?

Original source