llvm / llvm/llvm-project

[clang-format] Preprocessor directive indentation doesn’t follow code indentation

Open
#174,577 5 comments 2 reactions 1 assignee Claimed by @ItsGunjit View on GitHub
clang-format
Dominant language
LLVM
Stars
40.5k
Forks
18.7k
PR merge metrics
PR metrics pending

Description

Hi,

I’m running into an indentation behavior with C/C++ preprocessor directives that makes the formatted output look inconsistent with the surrounding code.

Reproduction

Input (desired style / already aligned with code indentation):
```c
#if I2C
typedef struct rx
{
uint8_t id;
union
{
#if (EN == 1)
hid_cert_status_segment_t cert_status_segment;
#endif
uint8_t input;
hid_switch_mode_t switch_mode;
uint8_t latency;
hid_reg_data_t aaa_data;
uint8_t bbb_data[BURST_SIZE];
hid_reg_data_t ccc_data;

#if (CLIENT_ENABLE == 1)
client_hid_data_t data;
#endif
} hid_data;
} rx_report_t;

#pragma pack()
typedef union tx
{
hid_desc_t desc;
struct
{
uint16_t len;
uint8_t id;
hid_data_t report;
};
} tx_data_t;
#endif
```

Formatted output I get:
```c
#if I2C
typedef struct rx
{
uint8_t id;
union
{
#if (EN == 1)
hid_cert_status_segment_t cert_status_segment;
#endif
uint8_t input;
hid_switch_mode_t switch_mode;
uint8_t latency;
hid_reg_data_t aaa_data;
uint8_t bbb_data[BURST_SIZE];
hid_reg_data_t ccc_data;

#if (CLIENT_ENABLE == 1)
client_hid_data_t data;
#endif
} hid_data;
} rx_report_t;

#pragma pack()
typedef union tx
{
desc_t desc;
struct
{
uint16_t en;
uint8_t id;
hid_data_t report;
};
} tx_data_t;
#endif
```
```yaml
IndentWidth: 4
TabWidth: 4
UseTab: Never
ColumnLimit: 150
SortIncludes: true

PPIndentWidth: -1
IndentPPDirectives: BeforeHash
```
This makes the code harder to read because the PP blocks no longer visually belong to the scope they are in. It feels like “PP indentation only follows PP”, instead of following the actual code structure.

Ultimately, my goal is for the formatter output to match my original input style—i.e., keep the same indentation and alignment behavior I used, instead of re-aligning preprocessor directives independently.

Contributor guide

Open the contributing guide

Assessment

This issue has not been assessed yet.

Get new issues in your inbox

A short digest of beginner-friendly GitHub issues.