Restrict some settings to certain file extensions

I am starting to learn how to use clang-format. I like it very much. The idea of imposing as much as possible without making it ugly is what moves me. :slight_smile: I really like the penalty idea. I do the following:

  1. Set ColumnLimit (to 80, in my case).
  2. Set a penalty for extra chars (PenaltyExcessCharacter) to 10.
  3. For each other penalty, I ponder like:
    “How many columns do I accept before breaking a string?”
  4. Then I set PenaltyBreakString: 91, to make it break before the 10th extra column. And so on…
  5. When two options are similar, in the number of columns I tolerate, I differentiate them by using different penalties: 91, 92, etc.

Now, it happens that I tolerate things differently in a .cpp and a .h file. And I think it would be nice if I could associate some config values to specific file extensions.

For example:

// In a ".h" file:
class MyClass
{
public:
    bool isItTrue()  const { return is_it_true; }
    bool isItFalse() const { return !isItTrue(); }
};


// In a ".cpp" file:
bool MyClass::isItTrue() const
{
    return is_it_true;
}

bool MyClass:isItFalse() const
{
    return !isItTrue();
}

In .cpp files, I want blank lines between definitions. In a .h file, not so much. The .h file documents the interface, and this should guide the style of a .h file. It is not just the Language. In a .cpp file, code tends to be more complex. It needs organization to address this complexity. Also, the body of the definitions are longer, so more vertical spacing might be more appropriate then in a .h file.

So, the same way we have a way to tell clang-format:

The following settings are for Language: CPP. We could have a way to specify that “the following settings” are just for files that match "\.hR".

I guess the language and the settings are a little more orthogonal then they are now. The language is about the grammar. The settings are about how to format this file? Of course, formatting depends heavily on the language. But it might also depend on what those files are used for. Even if the grammar is the same. Just like the difference when you write an email and when you type some text in a chat. The grammar is the same. :slight_smile:


PS: Not the subject of this post, but I cannot help commenting I do not know if my PenaltyExcessCharacter: 10 is appropriate because I do not know about hard-coded penalties.

Oops… it seems that my example would be AllowShortFunctionsOnASingleLine: InlineOnly. With the advantage that the “inline” thing would treat the code outside the class definition at the end of the .h file differently from those defined inside the class.

Still… :slight_smile: