From 02e2e07a7e9816a287cb95d3aa9d053415747bba Mon Sep 17 00:00:00 2001 From: Jan Tuomi Date: Sun, 9 Oct 2016 14:47:46 +0300 Subject: Add swap lines --- editor.cpp | 47 ++++++++++++++++++++++++++++++++++++++++++++++- editor.h | 2 ++ 2 files changed, 48 insertions(+), 1 deletion(-) diff --git a/editor.cpp b/editor.cpp index ff12c9e..2f4d048 100644 --- a/editor.cpp +++ b/editor.cpp @@ -40,6 +40,9 @@ int Editor::run_editor() { case 'b': prepend_before_command(); break; + case 's': + swap_lines_command(); + break; default: std::cout << "Not a recognized command " << input << ".\n"; break; @@ -53,7 +56,7 @@ int Editor::print_contents_on_line(int line) const { int output_length = m_contents->size(); bool truncated = false; - int line_max = Utils::window_height() - 3; + int line_max = std::max(Utils::window_height() - 4, 0); int line_number_width = Utils::count_digits(m_contents->size()); @@ -61,6 +64,11 @@ int Editor::print_contents_on_line(int line) const { output_length = line + line_max; truncated = true; } + + if (line != 0) { + std::cout << "...\n"; + } + for (int i = line; i < output_length; i++) { std::cout << std::setw(line_number_width) << i; std::cout << " " << m_contents->at(i) << '\n'; @@ -100,6 +108,7 @@ int Editor::edit_line(int line) { std::cin.clear(); (*m_contents)[line] = input; + move_to_line(line); return 0; } @@ -218,3 +227,39 @@ int Editor::prepend_before_line(int line) { m_contents->insert(m_contents->begin() + line, ""); return edit_line(line); } + +int Editor::swap_lines_command() { + + std::cout << "First line to swap? "; + int first; + std::cin >> first; + if (std::cin.fail() || first < 0 || first >= m_contents->size()) { + std::cout << "Not a valid line number!\n"; + std::cin.clear(); + std::cin.ignore(std::numeric_limits::max(),'\n'); + return 1; + } + + std::cout << "Second line to swap? "; + int second; + std::cin >> second; + if (std::cin.fail() || second < 0 || second >= m_contents->size()) { + std::cout << "Not a valid line number!\n"; + std::cin.clear(); + std::cin.ignore(std::numeric_limits::max(),'\n'); + return 1; + } + + return swap_lines(first, second); +} + +int Editor::swap_lines(int first, int second) { + std::string first_str = m_contents->at(first); + std::string second_str = m_contents->at(second); + + (*m_contents)[first] = second_str; + (*m_contents)[second] = first_str; + + move_to_line(first); + return 0; +} diff --git a/editor.h b/editor.h index 3e5c91d..6d1023c 100644 --- a/editor.h +++ b/editor.h @@ -22,6 +22,7 @@ class Editor { int delete_and_clamp_command(); int append_after_command(); int prepend_before_command(); + int swap_lines_command(); int edit_line(int line); int move_to_line(int line); @@ -29,6 +30,7 @@ class Editor { int delete_and_clamp(int line); int append_after_line(int line); int prepend_before_line(int line); + int swap_lines(int first, int second); }; #endif -- cgit v1.3