Vim: Tab Indentation, Space Alignment

I already read a few questions and answers:

  • Vim: use tabs for indentation, spaces to align with C source files
  • Vim: aligning continuous lines with spaces

But not one of them offers a solution for me.

I really want to apply the Tabbed Indentation, Space Alignment principle, but when it comes to auto reporting, I couldn't teach Vim how to do this.

Consider the code assuming tabstops == 3 , shiftwidth == 3

( >-- means a tab, and . (dot) means a space):

 { >--long a = 1, >-->--..b = 2, >-->--..c = 3; } 

Thus, it indents with tabs as much as possible, and then fills the rest with spaces. But actually this is a very bad approach: when someone reads this code with a different contribution size, the code will be corrupted. Here's how it would look with a contribution size of 8 characters:

 { >-------long a = 1, >------->-------..b = 2, >------->-------..c = 3; } 

This is terrible. The problem is that Vim does not distinguish between indentation and alignment.

To make it look correct with any tab size, the code must be indented as follows:

 { >--long a = 1, >--.....b = 2, >--.....c = 3; } 

Then this code will look beautiful no matter what tab size. For example, 8 characters:

 { >-------long a = 1, >-------.....b = 2, >-------.....c = 3; } 

How to do it?

+7
vim alignment indentation auto-indent
source share
2 answers

The most powerful way to influence indentation in Vim is through 'indentexpr' . From it :help :

An expression must return the number of spaces that are indented. This can return β€œ-1” to keep the current indentation (this means that β€œautoindent” is used for indentation).

Since this returns the number of spaces, not the indentation itself, and Vim so far only supports tabs, spaces or the maximum number of capital letters (called softtabstop), this cannot be done.

So, if you really want to use this indentation method (I personally like its cleanliness and elegance too! (But I don’t use it)), you need to disable auto-deposition and automatic formatting and, unfortunately, do everything manually manually.

+3
source share

As you have already indicated, vim cannot distinguish if you click on a tab to indent or because you are trying to align the text, so you cannot automate the behavior you want.

The closest thing you can try is to play with softtabstop and different values ​​for tabstop , but this way you get the opposite of what you asked for: clicking a tab will insert as many spaces as possible before using the tab.

If you want your code to always look the way you intended, you can try installing expandtab directly.

Spaces always look the same, so

 { .........long a = 1, ..............b = 2, ..............c = 3; } 

as always, your code will be displayed.

0
source share

All Articles