Skip to content

[clang-format] Add OneLineFormatOffRegex option #137577

New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Merged
merged 2 commits into from
Apr 30, 2025
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
23 changes: 23 additions & 0 deletions clang/docs/ClangFormatStyleOptions.rst
Original file line number Diff line number Diff line change
Expand Up @@ -5195,6 +5195,29 @@ the configuration (without a prefix: ``Auto``).
Add a space in front of an Objective-C protocol list, i.e. use
``Foo <Protocol>`` instead of ``Foo<Protocol>``.

.. _OneLineFormatOffRegex:

**OneLineFormatOffRegex** (``String``) :versionbadge:`clang-format 21` :ref:`¶ <OneLineFormatOffRegex>`
A regular expression that describes markers for turning formatting off for
one line. If it matches a comment that is the only token of a line,
clang-format skips the comment and the next line. Otherwise, clang-format
skips lines containing a matched token.

.. code-block:: c++

// OneLineFormatOffRegex: ^(// NOLINT|logger$)
// results in the output below:
int a;
int b ; // NOLINT
int c;
// NOLINTNEXTLINE
int d ;
int e;
s = "// NOLINT";
logger() ;
logger2();
my_logger();

.. _PPIndentWidth:

**PPIndentWidth** (``Integer``) :versionbadge:`clang-format 13` :ref:`¶ <PPIndentWidth>`
Expand Down
1 change: 1 addition & 0 deletions clang/docs/ReleaseNotes.rst
Original file line number Diff line number Diff line change
Expand Up @@ -692,6 +692,7 @@ clang-format
top of the file.
- Add ``EnumTrailingComma`` option for inserting/removing commas at the end of
``enum`` enumerator lists.
- Add ``OneLineFormatOffRegex`` option for turning formatting off for one line.

libclang
--------
Expand Down
22 changes: 22 additions & 0 deletions clang/include/clang/Format/Format.h
Original file line number Diff line number Diff line change
Expand Up @@ -3654,6 +3654,27 @@ struct FormatStyle {
/// \version 3.7
bool ObjCSpaceBeforeProtocolList;

/// A regular expression that describes markers for turning formatting off for
/// one line. If it matches a comment that is the only token of a line,
/// clang-format skips the comment and the next line. Otherwise, clang-format
/// skips lines containing a matched token.
/// \code
/// // OneLineFormatOffRegex: ^(// NOLINT|logger$)
/// // results in the output below:
/// int a;
/// int b ; // NOLINT
/// int c;
/// // NOLINTNEXTLINE
/// int d ;
/// int e;
/// s = "// NOLINT";
/// logger() ;
/// logger2();
/// my_logger();
/// \endcode
/// \version 21
std::string OneLineFormatOffRegex;

/// Different ways to try to fit all constructor initializers on a line.
enum PackConstructorInitializersStyle : int8_t {
/// Always put each constructor initializer on its own line.
Expand Down Expand Up @@ -5399,6 +5420,7 @@ struct FormatStyle {
ObjCPropertyAttributeOrder == R.ObjCPropertyAttributeOrder &&
ObjCSpaceAfterProperty == R.ObjCSpaceAfterProperty &&
ObjCSpaceBeforeProtocolList == R.ObjCSpaceBeforeProtocolList &&
OneLineFormatOffRegex == R.OneLineFormatOffRegex &&
PackConstructorInitializers == R.PackConstructorInitializers &&
PenaltyBreakAssignment == R.PenaltyBreakAssignment &&
PenaltyBreakBeforeFirstCallParameter ==
Expand Down
1 change: 1 addition & 0 deletions clang/lib/Format/Format.cpp
Original file line number Diff line number Diff line change
Expand Up @@ -1100,6 +1100,7 @@ template <> struct MappingTraits<FormatStyle> {
IO.mapOptional("ObjCSpaceAfterProperty", Style.ObjCSpaceAfterProperty);
IO.mapOptional("ObjCSpaceBeforeProtocolList",
Style.ObjCSpaceBeforeProtocolList);
IO.mapOptional("OneLineFormatOffRegex", Style.OneLineFormatOffRegex);
IO.mapOptional("PackConstructorInitializers",
Style.PackConstructorInitializers);
IO.mapOptional("PenaltyBreakAssignment", Style.PenaltyBreakAssignment);
Expand Down
35 changes: 35 additions & 0 deletions clang/lib/Format/FormatTokenLexer.cpp
Original file line number Diff line number Diff line change
Expand Up @@ -83,8 +83,43 @@ FormatTokenLexer::FormatTokenLexer(
ArrayRef<FormatToken *> FormatTokenLexer::lex() {
assert(Tokens.empty());
assert(FirstInLineIndex == 0);
const llvm::Regex FormatOffRegex(Style.OneLineFormatOffRegex);
enum { FO_None, FO_CurrentLine, FO_NextLine } FormatOff = FO_None;
do {
Tokens.push_back(getNextToken());
auto &Tok = *Tokens.back();
const auto NewlinesBefore = Tok.NewlinesBefore;
switch (FormatOff) {
case FO_CurrentLine:
if (NewlinesBefore == 0)
Tok.Finalized = true;
else
FormatOff = FO_None;
break;
case FO_NextLine:
if (NewlinesBefore > 1) {
FormatOff = FO_None;
} else {
Tok.Finalized = true;
FormatOff = FO_CurrentLine;
}
break;
default:
if (!FormattingDisabled && FormatOffRegex.match(Tok.TokenText)) {
if (Tok.is(tok::comment) &&
(NewlinesBefore > 0 || &Tok == Tokens.front())) {
Tok.Finalized = true;
FormatOff = FO_NextLine;
} else {
for (auto *Token : reverse(Tokens)) {
Token->Finalized = true;
if (Token->NewlinesBefore > 0)
break;
}
FormatOff = FO_CurrentLine;
}
}
}
if (Style.isJavaScript()) {
tryParseJSRegexLiteral();
handleTemplateStrings();
Expand Down
1 change: 1 addition & 0 deletions clang/unittests/Format/ConfigParseTest.cpp
Original file line number Diff line number Diff line change
Expand Up @@ -295,6 +295,7 @@ TEST(ConfigParseTest, ParsesConfiguration) {
FormatStyle Style = {};
Style.Language = FormatStyle::LK_Cpp;
CHECK_PARSE("CommentPragmas: '// abc$'", CommentPragmas, "// abc$");
CHECK_PARSE("OneLineFormatOffRegex: // ab$", OneLineFormatOffRegex, "// ab$");

Style.QualifierAlignment = FormatStyle::QAS_Right;
CHECK_PARSE("QualifierAlignment: Leave", QualifierAlignment,
Expand Down
99 changes: 99 additions & 0 deletions clang/unittests/Format/FormatTest.cpp
Original file line number Diff line number Diff line change
Expand Up @@ -24954,6 +24954,105 @@ TEST_F(FormatTest, DisableRegions) {
"// clang-format on");
}

TEST_F(FormatTest, OneLineFormatOffRegex) {
auto Style = getLLVMStyle();
Style.OneLineFormatOffRegex = "// format off$";

verifyFormat(" // format off\n"
" int i ;\n"
"int j;",
" // format off\n"
" int i ;\n"
" int j ;",
Style);
verifyFormat("// format off?\n"
"int i;",
" // format off?\n"
" int i ;",
Style);
verifyFormat("f(\"// format off\");", " f(\"// format off\") ;", Style);

verifyFormat("int i;\n"
" // format off\n"
" int j ;\n"
"int k;",
" int i ;\n"
" // format off\n"
" int j ;\n"
" int k ;",
Style);

verifyFormat(" // format off\n"
"\n"
"int i;",
" // format off\n"
" \n"
" int i ;",
Style);

verifyFormat("int i;\n"
" int j ; // format off\n"
"int k;",
" int i ;\n"
" int j ; // format off\n"
" int k ;",
Style);

verifyFormat("// clang-format off\n"
" int i ;\n"
" int j ; // format off\n"
" int k ;\n"
"// clang-format on\n"
"f();",
" // clang-format off\n"
" int i ;\n"
" int j ; // format off\n"
" int k ;\n"
" // clang-format on\n"
" f() ;",
Style);

Style.OneLineFormatOffRegex = "^/\\* format off \\*/";
verifyFormat("int i;\n"
" /* format off */ int j ;\n"
"int k;",
" int i ;\n"
" /* format off */ int j ;\n"
" int k ;",
Style);
verifyFormat("f(\"/* format off */\");", " f(\"/* format off */\") ;", Style);

Style.AlignEscapedNewlines = FormatStyle::ENAS_DontAlign;
verifyFormat("#define A \\\n"
" do { \\\n"
" /* format off */\\\n"
" f() ; \\\n"
" g(); \\\n"
" } while (0)",
"# define A\\\n"
" do{ \\\n"
" /* format off */\\\n"
" f() ; \\\n"
" g() ;\\\n"
" } while (0 )",
Style);

Style.ColumnLimit = 50;
Style.OneLineFormatOffRegex = "^LogErrorPrint$";
verifyFormat(" myproject::LogErrorPrint(logger, \"Don't split me!\");\n"
"myproject::MyLogErrorPrinter(myLogger,\n"
" \"Split me!\");",
" myproject::LogErrorPrint(logger, \"Don't split me!\");\n"
" myproject::MyLogErrorPrinter(myLogger, \"Split me!\");",
Style);

Style.OneLineFormatOffRegex = "//(< clang-format off| NO_TRANSLATION)$";
verifyNoChange(
" int i ; //< clang-format off\n"
" msg = sprintf(\"Long string with placeholders.\"); // NO_TRANSLATION",
Style);
}

TEST_F(FormatTest, DoNotCrashOnInvalidInput) {
format("? ) =");
verifyNoCrash("#define a\\\n /**/}");
Expand Down