TextDocument.cpp 1.4 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950
  1. #include "TextDocument.h"
  2. #include <LibCore/CFile.h>
  3. #include <string.h>
  4. const GTextDocument& TextDocument::document() const
  5. {
  6. if (!m_document) {
  7. m_document = GTextDocument::create(nullptr);
  8. m_document->set_text(contents());
  9. }
  10. return *m_document;
  11. }
  12. const ByteBuffer& TextDocument::contents() const
  13. {
  14. if (m_contents.is_null()) {
  15. auto file = CFile::construct(m_name);
  16. if (file->open(CFile::ReadOnly))
  17. m_contents = file->read_all();
  18. }
  19. return m_contents;
  20. }
  21. Vector<int> TextDocument::find(const StringView& needle) const
  22. {
  23. // NOTE: This forces us to load the contents if we hadn't already.
  24. contents();
  25. Vector<int> matching_line_numbers;
  26. String needle_as_string(needle);
  27. int line_index = 0;
  28. int start_of_line = 0;
  29. for (int i = 0; i < m_contents.size(); ++i) {
  30. char ch = m_contents[i];
  31. if (ch == '\n') {
  32. // FIXME: Please come back here and do this the good boy way.
  33. String line(StringView(m_contents.data() + start_of_line, i - start_of_line));
  34. auto* found = strstr(line.characters(), needle_as_string.characters());
  35. if (found)
  36. matching_line_numbers.append(line_index + 1);
  37. ++line_index;
  38. start_of_line = i + 1;
  39. continue;
  40. }
  41. }
  42. return matching_line_numbers;
  43. }