Martin Tournoij
Martin Tournoij

Reputation: 27852

How can I get the same behaviour navigating tabs if I use expandtab

How can I get the same behaviour navigating tabs if I enable expandtab?

For example, assume 2 levels of indentation with a tabstop of 4 (█ represents the cursor), if my cursor is on the first r in this example:

        return 'world'

And I go left with h or Left Arrow, the cursor moves one space to the left:

       █return 'Hello, world'

But if I use tabs (0x09, noexpandtab), the cursor goes one tab to the left:

    █   return 'Hello, world'

I understand why this happens, but is there any way to get the tab behaviour when using expandtab? I work on some projects where expandtab is the norm, and some others where it isn't; I would like it to be consistent.

I already set smarttab, but this only affects the Backspace key. My tabstop, softtabstop, and shiftwidth settings are all set to 4. Using an empty ~/.vimrc makes no difference.

Upvotes: 2

Views: 119

Answers (2)

Christian Brabandt
Christian Brabandt

Reputation: 8248

The cursor is usually placed at the end of a tab character in normal mode, unless you have listmode (:set list) set. So the solution is easy, do not set listmode.

This is something, I just recently noticed myself. The documentation also states this (:h 'list'):

The cursor is displayed at the start of the space a Tab character
occupies, not at the end as usual in Normal mode.  To get this cursor
position while displaying Tabs with spaces, use: >
    :set list lcs=tab:\ \ 

Upvotes: 0

Ingo Karkat
Ingo Karkat

Reputation: 172688

Built-in motions like h and <Left> will always move by single characters. To get the behavior you want, I see two options:

  • Override those motions with custom mappings that have that kind of "intelligence". Implementing this is certainly doable, but not trivial.
  • With a set of :autocmds, you can convert such buffers to use tab indent on read, and convert back to space indent on write. See :help retab-example. Then, the built-in motions will work (on those <Tab>s) as you'd like.

Alternatively, rethink your approach. If you're bothered by this, I think you're navigating too much in the indent. I personally mostly just skip it with w or ^, and to reindent, I use << / >>, which handle spaces just fine.

Upvotes: 7

Related Questions