Document.cpp 1.6 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273
  1. /*
  2. * Copyright (c) 2019-2020, Sergey Bugaev <bugaevc@serenityos.org>
  3. * Copyright (c) 2021, Peter Elliott <pelliott@serenityos.org>
  4. *
  5. * SPDX-License-Identifier: BSD-2-Clause
  6. */
  7. #include <AK/StringBuilder.h>
  8. #include <LibMarkdown/Document.h>
  9. #include <LibMarkdown/LineIterator.h>
  10. #include <LibMarkdown/Visitor.h>
  11. namespace Markdown {
  12. ByteString Document::render_to_html(StringView extra_head_contents) const
  13. {
  14. StringBuilder builder;
  15. builder.append(R"~~~(<!DOCTYPE html>
  16. <html>
  17. <head>
  18. <style>
  19. code { white-space: pre; }
  20. </style>
  21. )~~~"sv);
  22. if (!extra_head_contents.is_empty())
  23. builder.append(extra_head_contents);
  24. builder.append(R"~~~(
  25. </head>
  26. <body>
  27. )~~~"sv);
  28. builder.append(render_to_inline_html());
  29. builder.append(R"~~~(
  30. </body>
  31. </html>)~~~"sv);
  32. return builder.to_byte_string();
  33. }
  34. ByteString Document::render_to_inline_html() const
  35. {
  36. return m_container->render_to_html();
  37. }
  38. ErrorOr<String> Document::render_for_terminal(size_t view_width) const
  39. {
  40. StringBuilder builder;
  41. for (auto& line : m_container->render_lines_for_terminal(view_width)) {
  42. TRY(builder.try_append(line));
  43. TRY(builder.try_append("\n"sv));
  44. }
  45. return builder.to_string();
  46. }
  47. RecursionDecision Document::walk(Visitor& visitor) const
  48. {
  49. RecursionDecision rd = visitor.visit(*this);
  50. if (rd != RecursionDecision::Recurse)
  51. return rd;
  52. return m_container->walk(visitor);
  53. }
  54. OwnPtr<Document> Document::parse(StringView str)
  55. {
  56. Vector<StringView> const lines_vec = str.lines();
  57. LineIterator lines(lines_vec.begin());
  58. return make<Document>(ContainerBlock::parse(lines));
  59. }
  60. }