CommentBlock.cpp 1.8 KB

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