// Buffer.cpp #include "Buffer.h" using namespace std; void Buffer::display() const { int ix_stop_line = ix_top_line_ + window_height_; auto itr = itr_top_line_; for (int i = ix_top_line_; i < ix_stop_line; ++i) { if (i <= ls_lines_.size()) { if (i == ix_current_line_) cout << '>'; else cout << ' '; cout << std::setw(5) << i+1; if (i < ls_lines_.size()) { cout << " " << *itr; ++itr; } } cout << endl; } } void Buffer::erase() { if (ix_current_line_ < ls_lines_.size()) { itr_current_line_ = ls_lines_.erase(itr_current_line_); if (ix_top_line_ == ix_current_line_) itr_top_line_ = itr_current_line_; } } void Buffer::insert(const string & new_line) { ls_lines_.insert(itr_current_line_, new_line); ++ix_current_line_; if (itr_top_line_ == itr_current_line_) { // insertion was at the top --itr_top_line_; } if (ix_current_line_ == ix_top_line_ + window_height_) { // insertion was at the bottom ++ix_top_line_; ++itr_top_line_; } } void Buffer::move_to_next_line() { if (ix_current_line_ < ls_lines_.size()) { ++ix_current_line_; ++itr_current_line_; // check if window needs to be scrolled down if (ix_current_line_ >= ix_top_line_ + window_height_) { ++ix_top_line_; ++itr_top_line_; } } } void Buffer::move_to_previous_line() { if (ix_current_line_ > 0) { --ix_current_line_; --itr_current_line_; // check if window needs to be scrolled up if (ix_current_line_ < ix_top_line_) { --ix_top_line_; --itr_top_line_; } } } bool Buffer::open(const string & new_file_name) { std::ifstream file(new_file_name); if (!file) return false; ls_lines_.clear(); string line; while (getline(file, line)) ls_lines_.push_back(line); file_name_ = new_file_name; ix_current_line_ = ix_top_line_ = 0; itr_current_line_ = itr_top_line_ = ls_lines_.begin(); return true; } bool Buffer::save(const string & new_file_name) { std::ofstream file(new_file_name); if (!file) return false; file_name_ = new_file_name; for (const string & line : ls_lines_) file << line << endl; return true; }