From 812f3f69c854a5376dc0d123c4e545cf67c8690c Mon Sep 17 00:00:00 2001 From: Jan Tuomi Date: Sun, 9 Oct 2016 14:35:59 +0300 Subject: Fix printing issues --- editor.cpp | 14 +++++++++++--- editor.h | 2 -- utils.cpp | 23 ++++++++++++++++++++++- utils.h | 3 +++ 4 files changed, 36 insertions(+), 6 deletions(-) diff --git a/editor.cpp b/editor.cpp index f8c8ade..ff12c9e 100644 --- a/editor.cpp +++ b/editor.cpp @@ -3,6 +3,7 @@ #include #include #include +#include Editor::Editor(std::vector* contents, const std::string& filename): m_current_line(0), m_filename(filename), m_stopped(false) { @@ -48,14 +49,21 @@ int Editor::run_editor() { } int Editor::print_contents_on_line(int line) const { + Utils::clear_screen(); + int output_length = m_contents->size(); bool truncated = false; - if ((int) m_contents->size() > line + OUTPUT_LINE_MAX) { - output_length = line + OUTPUT_LINE_MAX; + int line_max = Utils::window_height() - 3; + + int line_number_width = Utils::count_digits(m_contents->size()); + + if ((int) m_contents->size() > line + line_max) { + output_length = line + line_max; truncated = true; } for (int i = line; i < output_length; i++) { - std::cout << i << " " << m_contents->at(i) << '\n'; + std::cout << std::setw(line_number_width) << i; + std::cout << " " << m_contents->at(i) << '\n'; } if (truncated) { std::cout << "...\n"; diff --git a/editor.h b/editor.h index 5cc5fdf..3e5c91d 100644 --- a/editor.h +++ b/editor.h @@ -9,8 +9,6 @@ class Editor { Editor(std::vector* contents, const std::string& filename); int run_editor(); private: - const static int OUTPUT_LINE_MAX = 10; - std::vector* m_contents; std::string m_filename; int m_current_line; diff --git a/utils.cpp b/utils.cpp index f118fc5..aa19c4f 100644 --- a/utils.cpp +++ b/utils.cpp @@ -2,6 +2,8 @@ #include //_getch #include //_getch #include +#include +#include /* Thanks to StackOverflow user mf_ */ char Utils::getch(){ @@ -24,4 +26,23 @@ char Utils::getch(){ perror ("tcsetattr ~ICANON"); //printf("%c\n",buf); return buf; - } +} + +int Utils::window_height() { + struct winsize w; + ioctl(STDOUT_FILENO, TIOCGWINSZ, &w); + + return w.ws_row; +} + +void Utils::clear_screen() { + int height = window_height(); + for (int i = 0; i < height; i++) { + std::cout << '\n'; + } +} + +int Utils::count_digits(int num) { + std::string repr = std::to_string(num); + return repr.size(); +} diff --git a/utils.h b/utils.h index 35c600a..73703bc 100644 --- a/utils.h +++ b/utils.h @@ -3,6 +3,9 @@ namespace Utils { char getch(); + void clear_screen(); + int window_height(); + int count_digits(int num); } #endif -- cgit v1.3