diff options
| author | Jan Tuomi <jan-sebastian.tuomi@aalto.fi> | 2016-10-09 14:35:59 +0300 |
|---|---|---|
| committer | Jan Tuomi <jan-sebastian.tuomi@aalto.fi> | 2016-10-09 14:50:24 +0300 |
| commit | 812f3f69c854a5376dc0d123c4e545cf67c8690c (patch) | |
| tree | c1005667afa8c79ef7e358a8ac3aadf9ed07709c | |
| parent | da5ecb5de0ca0bc099258f7b77480fbb28b31392 (diff) | |
Fix printing issues
| -rw-r--r-- | editor.cpp | 14 | ||||
| -rw-r--r-- | editor.h | 2 | ||||
| -rw-r--r-- | utils.cpp | 23 | ||||
| -rw-r--r-- | utils.h | 3 |
4 files changed, 36 insertions, 6 deletions
@@ -3,6 +3,7 @@ #include <fstream> #include <limits> #include <iostream> +#include <iomanip> Editor::Editor(std::vector<std::string>* 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"; @@ -9,8 +9,6 @@ class Editor { Editor(std::vector<std::string>* contents, const std::string& filename); int run_editor(); private: - const static int OUTPUT_LINE_MAX = 10; - std::vector<std::string>* m_contents; std::string m_filename; int m_current_line; @@ -2,6 +2,8 @@ #include <unistd.h> //_getch #include <termios.h> //_getch #include <stdio.h> +#include <sys/ioctl.h> +#include <iostream> /* 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(); +} @@ -3,6 +3,9 @@ namespace Utils { char getch(); + void clear_screen(); + int window_height(); + int count_digits(int num); } #endif |
