You can not select more than 25 topics Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.

91 lines
2.5 KiB

  1. // Buffer.cpp
  2. #include "Buffer.h"
  3. using namespace std;
  4. void Buffer::display() const
  5. {
  6. int ix_stop_line_ = ix_top_line_ + window_height_;
  7. for (int i = ix_top_line_; i < ix_stop_line_; ++i) {
  8. if (i < v_lines_.size())
  9. cout << std::setw(6) << i+1 << " " << v_lines_[i];
  10. cout << '\n';
  11. }
  12. }
  13. string* Buffer::get_lines() const
  14. {
  15. string* lines = new string[window_height_];
  16. int line = 0;
  17. while (line < window_height_ && line + ix_top_line_ < v_lines_.size()) {
  18. lines[line - ix_top_line_] = v_lines_[line];
  19. ++line;
  20. }
  21. return lines;
  22. }
  23. bool Buffer::open(const string & new_file_name)
  24. {
  25. std::ifstream file(new_file_name);
  26. if (!file)
  27. return false;
  28. v_lines_.clear();
  29. // Note: the vector is cleared only after we know the file
  30. // opened successfully.
  31. int curr_link = 0;
  32. std::string curr_p, line;
  33. while(getline(file, line))
  34. {
  35. // Replace break tags with newlines.
  36. for(auto char_loc = line.find("<br>"); char_loc != -1; char_loc = line.find("<br>"))
  37. line.replace(char_loc, 4, "\n");
  38. // Find link tags and process them.
  39. for(auto tag_loc = line.find("<a "); tag_loc != -1; tag_loc = line.find("<a", tag_loc + 1))
  40. {
  41. ++curr_link;
  42. auto tag_len = line.find_first_of('>', tag_loc) - tag_loc;
  43. std::string link_tag = line.substr(tag_loc + 3, tag_len - 3);
  44. auto second_space_loc = link_tag.find_first_of(' ', 0);
  45. std::string file_name = link_tag.substr(0, second_space_loc - 1);
  46. std::string link_name = link_tag.substr(second_space_loc + 1);
  47. v_links_.push_back({file_name, link_name});
  48. line.replace(tag_loc, tag_len + 1, "<" + link_name + ">[" + to_string(curr_link) + "]");
  49. }
  50. // Search for all paragraphs in the line and add them to the v_lines vector.
  51. for(auto p_tag = line.find("<p>"); p_tag != -1; p_tag = line.find("<p>"))
  52. {
  53. std::string extra_text = line.substr(p_tag + 4);
  54. line.erase(p_tag);
  55. curr_p += line;
  56. // However, if the paragraph is empty, then it shouldn't be added.
  57. if(curr_p != "")
  58. {
  59. v_lines_.push_back(curr_p);
  60. curr_p = "";
  61. }
  62. line = extra_text;
  63. }
  64. // Append any data left on this line to the current paragraph being read.
  65. curr_p += " " + line;
  66. }
  67. // Push the contents of curr_p as it has the last paragraph in the file.
  68. v_lines_.push_back(curr_p);
  69. file_name_ = new_file_name;
  70. ix_top_line_ = 0;
  71. return true;
  72. }