clang-tools  9.0.0
FormattedString.cpp
Go to the documentation of this file.
1 //===--- FormattedString.cpp --------------------------------*- C++-*------===//
2 //
3 // Part of the LLVM Project, under the Apache License v2.0 with LLVM Exceptions.
4 // See https://llvm.org/LICENSE.txt for license information.
5 // SPDX-License-Identifier: Apache-2.0 WITH LLVM-exception
6 //
7 //===----------------------------------------------------------------------===//
8 #include "FormattedString.h"
9 #include "clang/Basic/CharInfo.h"
10 #include "llvm/ADT/StringRef.h"
11 #include "llvm/Support/ErrorHandling.h"
12 #include "llvm/Support/FormatVariadic.h"
13 #include <cstddef>
14 #include <string>
15 
16 namespace clang {
17 namespace clangd {
18 
19 namespace {
20 /// Escape a markdown text block. Ensures the punctuation will not introduce
21 /// any of the markdown constructs.
22 static std::string renderText(llvm::StringRef Input) {
23  // Escaping ASCII punctiation ensures we can't start a markdown construct.
24  constexpr llvm::StringLiteral Punctuation =
25  R"txt(!"#$%&'()*+,-./:;<=>?@[\]^_`{|}~)txt";
26 
27  std::string R;
28  for (size_t From = 0; From < Input.size();) {
29  size_t Next = Input.find_first_of(Punctuation, From);
30  R += Input.substr(From, Next - From);
31  if (Next == llvm::StringRef::npos)
32  break;
33  R += "\\";
34  R += Input[Next];
35 
36  From = Next + 1;
37  }
38  return R;
39 }
40 
41 /// Renders \p Input as an inline block of code in markdown. The returned value
42 /// is surrounded by backticks and the inner contents are properly escaped.
43 static std::string renderInlineBlock(llvm::StringRef Input) {
44  std::string R;
45  // Double all backticks to make sure we don't close the inline block early.
46  for (size_t From = 0; From < Input.size();) {
47  size_t Next = Input.find("`", From);
48  R += Input.substr(From, Next - From);
49  if (Next == llvm::StringRef::npos)
50  break;
51  R += "``"; // double the found backtick.
52 
53  From = Next + 1;
54  }
55  // If results starts with a backtick, add spaces on both sides. The spaces
56  // are ignored by markdown renderers.
57  if (llvm::StringRef(R).startswith("`") || llvm::StringRef(R).endswith("`"))
58  return "` " + std::move(R) + " `";
59  // Markdown render should ignore first and last space if both are there. We
60  // add an extra pair of spaces in that case to make sure we render what the
61  // user intended.
62  if (llvm::StringRef(R).startswith(" ") && llvm::StringRef(R).endswith(" "))
63  return "` " + std::move(R) + " `";
64  return "`" + std::move(R) + "`";
65 }
66 /// Render \p Input as markdown code block with a specified \p Language. The
67 /// result is surrounded by >= 3 backticks. Although markdown also allows to use
68 /// '~' for code blocks, they are never used.
69 static std::string renderCodeBlock(llvm::StringRef Input,
70  llvm::StringRef Language) {
71  // Count the maximum number of consecutive backticks in \p Input. We need to
72  // start and end the code block with more.
73  unsigned MaxBackticks = 0;
74  unsigned Backticks = 0;
75  for (char C : Input) {
76  if (C == '`') {
77  ++Backticks;
78  continue;
79  }
80  MaxBackticks = std::max(MaxBackticks, Backticks);
81  Backticks = 0;
82  }
83  MaxBackticks = std::max(Backticks, MaxBackticks);
84  // Use the corresponding number of backticks to start and end a code block.
85  std::string BlockMarker(/*Repeat=*/std::max(3u, MaxBackticks + 1), '`');
86  return BlockMarker + Language.str() + "\n" + Input.str() + "\n" + BlockMarker;
87 }
88 
89 } // namespace
90 
91 void FormattedString::appendText(std::string Text) {
92  Chunk C;
93  C.Kind = ChunkKind::PlainText;
94  C.Contents = Text;
95  Chunks.push_back(C);
96 }
97 
98 void FormattedString::appendCodeBlock(std::string Code, std::string Language) {
99  Chunk C;
100  C.Kind = ChunkKind::CodeBlock;
101  C.Contents = std::move(Code);
102  C.Language = std::move(Language);
103  Chunks.push_back(std::move(C));
104 }
105 
106 void FormattedString::appendInlineCode(std::string Code) {
107  Chunk C;
108  C.Kind = ChunkKind::InlineCodeBlock;
109  C.Contents = std::move(Code);
110  Chunks.push_back(std::move(C));
111 }
112 
113 std::string FormattedString::renderAsMarkdown() const {
114  std::string R;
115  for (const auto &C : Chunks) {
116  switch (C.Kind) {
117  case ChunkKind::PlainText:
118  R += renderText(C.Contents);
119  continue;
120  case ChunkKind::InlineCodeBlock:
121  // Make sure we don't glue two backticks together.
122  if (llvm::StringRef(R).endswith("`"))
123  R += " ";
124  R += renderInlineBlock(C.Contents);
125  continue;
126  case ChunkKind::CodeBlock:
127  if (!R.empty() && !llvm::StringRef(R).endswith("\n"))
128  R += "\n";
129  R += renderCodeBlock(C.Contents, C.Language);
130  R += "\n";
131  continue;
132  }
133  llvm_unreachable("unhanlded ChunkKind");
134  }
135  return R;
136 }
137 
138 std::string FormattedString::renderAsPlainText() const {
139  std::string R;
140  auto EnsureWhitespace = [&]() {
141  if (R.empty() || isWhitespace(R.back()))
142  return;
143  R += " ";
144  };
145  Optional<bool> LastWasBlock;
146  for (const auto &C : Chunks) {
147  bool IsBlock = C.Kind == ChunkKind::CodeBlock;
148  if (LastWasBlock.hasValue() && (IsBlock || *LastWasBlock))
149  R += "\n\n";
150  LastWasBlock = IsBlock;
151 
152  switch (C.Kind) {
153  case ChunkKind::PlainText:
154  EnsureWhitespace();
155  R += C.Contents;
156  break;
157  case ChunkKind::InlineCodeBlock:
158  EnsureWhitespace();
159  R += C.Contents;
160  break;
161  case ChunkKind::CodeBlock:
162  R += C.Contents;
163  break;
164  }
165  // Trim trailing whitespace in chunk.
166  while (!R.empty() && isWhitespace(R.back()))
167  R.pop_back();
168  }
169  return R;
170 }
171 
172 std::string FormattedString::renderForTests() const {
173  std::string R;
174  for (const auto &C : Chunks) {
175  switch (C.Kind) {
176  case ChunkKind::PlainText:
177  R += "text[" + C.Contents + "]";
178  break;
179  case ChunkKind::InlineCodeBlock:
180  R += "code[" + C.Contents + "]";
181  break;
182  case ChunkKind::CodeBlock:
183  if (!R.empty())
184  R += "\n";
185  R += llvm::formatv("codeblock({0}) [\n{1}\n]\n", C.Language, C.Contents);
186  break;
187  }
188  }
189  while (!R.empty() && isWhitespace(R.back()))
190  R.pop_back();
191  return R;
192 }
193 } // namespace clangd
194 } // namespace clang
std::string renderForTests() const
void appendText(std::string Text)
Append plain text to the end of the string.
std::string renderAsMarkdown() const
void appendInlineCode(std::string Code)
Append an inline block of C++ code.
===– Representation.cpp - ClangDoc Representation --------—*- C++ -*-===//
std::string renderAsPlainText() const
void appendCodeBlock(std::string Code, std::string Language="cpp")
Append a block of C++ code.