CommentBlock.cpp 1.9 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475
  1. /*
  2. * Copyright (c) 2021, Ben Wiederhake <BenWiederhake.GitHub@gmx.de>
  3. *
  4. * SPDX-License-Identifier: BSD-2-Clause
  5. */
  6. #include <AK/Forward.h>
  7. #include <AK/StringBuilder.h>
  8. #include <LibMarkdown/CommentBlock.h>
  9. #include <LibMarkdown/Visitor.h>
  10. namespace Markdown {
  11. ByteString CommentBlock::render_to_html(bool) const
  12. {
  13. StringBuilder builder;
  14. builder.append("<!--"sv);
  15. builder.append(escape_html_entities(m_comment));
  16. // TODO: This is probably incorrect, because we technically need to escape "--" in some form. However, Browser does not care about this.
  17. builder.append("-->\n"sv);
  18. return builder.to_byte_string();
  19. }
  20. Vector<ByteString> CommentBlock::render_lines_for_terminal(size_t) const
  21. {
  22. return Vector<ByteString> {};
  23. }
  24. RecursionDecision CommentBlock::walk(Visitor& visitor) const
  25. {
  26. RecursionDecision rd = visitor.visit(*this);
  27. if (rd != RecursionDecision::Recurse)
  28. return rd;
  29. // Normalize return value.
  30. return RecursionDecision::Continue;
  31. }
  32. OwnPtr<CommentBlock> CommentBlock::parse(LineIterator& lines)
  33. {
  34. if (lines.is_end())
  35. return {};
  36. constexpr auto comment_start = "<!--"sv;
  37. constexpr auto comment_end = "-->"sv;
  38. StringView line = *lines;
  39. if (!line.starts_with(comment_start))
  40. return {};
  41. line = line.substring_view(comment_start.length());
  42. StringBuilder builder;
  43. while (true) {
  44. // Invariant: At the beginning of the loop, `line` is valid and should be added to the builder.
  45. bool ends_here = line.ends_with(comment_end);
  46. if (ends_here)
  47. line = line.substring_view(0, line.length() - comment_end.length());
  48. builder.append(line);
  49. if (!ends_here)
  50. builder.append('\n');
  51. ++lines;
  52. if (lines.is_end() || ends_here) {
  53. break;
  54. }
  55. line = *lines;
  56. }
  57. return make<CommentBlock>(builder.to_byte_string());
  58. }
  59. }