From a49b2123bc802d4948a892b8b7f87cd45a67dbea Mon Sep 17 00:00:00 2001 From: Daniel Jasper Date: Sat, 21 Nov 2015 09:17:08 +0000 Subject: [PATCH] clang-format: Make sorting includes respect // clang-format off git-svn-id: https://llvm.org/svn/llvm-project/cfe/trunk@253772 91177308-0d34-0410-b5e6-96231b3b80d8 --- lib/Format/Format.cpp | 11 ++++++++++- unittests/Format/SortIncludesTest.cpp | 19 +++++++++++++++++++ 2 files changed, 29 insertions(+), 1 deletion(-) diff --git a/lib/Format/Format.cpp b/lib/Format/Format.cpp index e7e71c4c7e..2a7b9acf23 100644 --- a/lib/Format/Format.cpp +++ b/lib/Format/Format.cpp @@ -1780,11 +1780,20 @@ tooling::Replacements sortIncludes(const FormatStyle &Style, StringRef Code, for (const auto &Category : Style.IncludeCategories) CategoryRegexs.emplace_back(Category.Regex); + bool FormattingOff = false; + for (;;) { auto Pos = Code.find('\n', SearchFrom); StringRef Line = Code.substr(Prev, (Pos != StringRef::npos ? Pos : Code.size()) - Prev); - if (!Line.endswith("\\")) { + + StringRef Trimmed = Line.trim(); + if (Trimmed == "// clang-format off") + FormattingOff = true; + else if (Trimmed == "// clang-format on") + FormattingOff = false; + + if (!FormattingOff && !Line.endswith("\\")) { if (IncludeRegex.match(Line, &Matches)) { StringRef IncludeName = Matches[2]; unsigned Category; diff --git a/unittests/Format/SortIncludesTest.cpp b/unittests/Format/SortIncludesTest.cpp index 30109ffb72..a9f90e3f7b 100644 --- a/unittests/Format/SortIncludesTest.cpp +++ b/unittests/Format/SortIncludesTest.cpp @@ -40,6 +40,25 @@ TEST_F(SortIncludesTest, BasicSorting) { "#include \"b.h\"\n")); } +TEST_F(SortIncludesTest, SupportClangFormatOff) { + EXPECT_EQ("#include \n" + "#include \n" + "#include \n" + "// clang-format off\n" + "#include \n" + "#include \n" + "#include \n" + "// clang-format on\n", + sort("#include \n" + "#include \n" + "#include \n" + "// clang-format off\n" + "#include \n" + "#include \n" + "#include \n" + "// clang-format on\n")); +} + TEST_F(SortIncludesTest, IncludeSortingCanBeDisabled) { Style.SortIncludes = false; EXPECT_EQ("#include \"a.h\"\n" -- 2.50.1