[PATCH] D66087: [clangd] Preserve line break when rendering text chunks of markdown

Ilya Biryukov via Phabricator via cfe-commits cfe-commits at lists.llvm.org
Mon Aug 12 06:29:02 PDT 2019


ilya-biryukov created this revision.
ilya-biryukov added a reviewer: sammccall.
Herald added subscribers: kadircet, arphaman, jkorous, MaskRay.
Herald added a project: clang.

Fixes https://github.com/clangd/clangd/issues/95


Repository:
  rG LLVM Github Monorepo

https://reviews.llvm.org/D66087

Files:
  clang-tools-extra/clangd/FormattedString.cpp
  clang-tools-extra/clangd/unittests/FormattedStringTests.cpp


Index: clang-tools-extra/clangd/unittests/FormattedStringTests.cpp
===================================================================
--- clang-tools-extra/clangd/unittests/FormattedStringTests.cpp
+++ clang-tools-extra/clangd/unittests/FormattedStringTests.cpp
@@ -179,7 +179,7 @@
   S = FormattedString();
   S.appendText("foo\n");
   S.appendInlineCode("bar");
-  EXPECT_EQ(S.renderAsMarkdown(), "foo\n`bar`");
+  EXPECT_EQ(S.renderAsMarkdown(), "foo  \n`bar`");
 
   S = FormattedString();
   S.appendInlineCode("foo");
@@ -193,6 +193,12 @@
   EXPECT_EQ(S.renderAsMarkdown(), "foo\n```cpp\nbar\n```\nbaz");
 }
 
+TEST(FormattedString, MarkdownLineBreaks) {
+  FormattedString S;
+  S.appendText("foo\nbar\nbaz");
+  // To preserve line breaks, two spaces are added at the end of each line.
+  EXPECT_EQ(S.renderAsMarkdown(), "foo  \nbar  \nbaz");
+}
 
 } // namespace
 } // namespace clangd
Index: clang-tools-extra/clangd/FormattedString.cpp
===================================================================
--- clang-tools-extra/clangd/FormattedString.cpp
+++ clang-tools-extra/clangd/FormattedString.cpp
@@ -23,17 +23,16 @@
   // Escaping ASCII punctiation ensures we can't start a markdown construct.
   constexpr llvm::StringLiteral Punctuation =
       R"txt(!"#$%&'()*+,-./:;<=>?@[\]^_`{|}~)txt";
-
   std::string R;
-  for (size_t From = 0; From < Input.size();) {
-    size_t Next = Input.find_first_of(Punctuation, From);
-    R += Input.substr(From, Next - From);
-    if (Next == llvm::StringRef::npos)
-      break;
-    R += "\\";
-    R += Input[Next];
-
-    From = Next + 1;
+  for (char C : Input) {
+    if (Punctuation.contains(C)) {
+      // Has to be escaped.
+      R += "\\";
+    } else if (C == '\n') {
+      // Putting two spaces at the end of the line preserves line breaks.
+      R += "  ";
+    }
+    R += C;
   }
   return R;
 }


-------------- next part --------------
A non-text attachment was scrubbed...
Name: D66087.214623.patch
Type: text/x-patch
Size: 1871 bytes
Desc: not available
URL: <http://lists.llvm.org/pipermail/cfe-commits/attachments/20190812/d99eacdc/attachment.bin>


More information about the cfe-commits mailing list