LineIterator.cpp 1.5 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465
  1. /*
  2. * Copyright (c) 2021, Peter Elliott <pelliott@serenityos.org>
  3. *
  4. * SPDX-License-Identifier: BSD-2-Clause
  5. */
  6. #include <AK/Format.h>
  7. #include <LibMarkdown/LineIterator.h>
  8. namespace Markdown {
  9. void LineIterator::reset_ignore_prefix()
  10. {
  11. for (auto& context : m_context_stack) {
  12. context.ignore_prefix = false;
  13. }
  14. }
  15. Optional<StringView> LineIterator::match_context(StringView const& line) const
  16. {
  17. bool is_ws = line.is_whitespace();
  18. size_t offset = 0;
  19. for (auto& context : m_context_stack) {
  20. switch (context.type) {
  21. case Context::Type::ListItem:
  22. if (is_ws)
  23. break;
  24. if (offset + context.indent > line.length())
  25. return {};
  26. if (!context.ignore_prefix && !line.substring_view(offset, context.indent).is_whitespace())
  27. return {};
  28. offset += context.indent;
  29. break;
  30. case Context::Type::BlockQuote:
  31. for (; offset < line.length() && line[offset] == ' '; ++offset) { }
  32. if (offset >= line.length() || line[offset] != '>') {
  33. return {};
  34. }
  35. ++offset;
  36. break;
  37. }
  38. if (offset > line.length())
  39. return {};
  40. }
  41. return line.substring_view(offset);
  42. }
  43. bool LineIterator::is_end() const
  44. {
  45. return m_iterator.is_end() || !match_context(*m_iterator).has_value();
  46. }
  47. StringView LineIterator::operator*() const
  48. {
  49. auto line = match_context(*m_iterator);
  50. VERIFY(line.has_value());
  51. return line.value();
  52. }
  53. }