vimtricks.wiki Concise Vim tricks, one at a time.

How do I move the cursor to the last non-blank character on the current line?

Answer

g_

Explanation

g_ moves the cursor to the last non-blank character of the current line — skipping trailing spaces and tabs. It is the counterpart to ^ (first non-blank) and pairs naturally with it for navigating between meaningful content on a line without landing on whitespace.

How it works

  • g_ — go to the last non-blank character on the current line
  • ^ — go to the first non-blank character on the current line
  • $ — go to the very last character (including trailing whitespace)
  • 0 — go to column 0 (the very first character)
  • A count prefix moves down that many lines first: 3g_ goes to the last non-blank of 3 lines below

Example

    const result = getValue();   

With trailing spaces after the semicolon:

  • $ lands on the last space
  • g_ lands on ; — the last non-whitespace character

Useful when yanking the meaningful content of a line: ^vg_y visually selects from the first non-blank to the last non-blank and yanks it (excluding leading indentation and trailing whitespace).

Tips

  • ^vg_ is a practical idiom for selecting the "content" of a line without indentation or trailing spaces — useful for copying lines in consistent way across different indentation levels
  • dg_ deletes to the last non-blank (leaving trailing whitespace intact), while D deletes to end-of-line including whitespace
  • In operator-pending mode, {op}g_ applies the operator up to and including the last non-blank: cg_ changes to the last non-blank character

Next

How do I run a search and replace only within a visually selected region?