+#include "Error.hpp"
+#include "Highlight.hpp"
+#include "Syntax.hpp"
+
+extern "C" int rl_display_fixed;
+extern "C" int _rl_vis_botlin;
+extern "C" int _rl_last_c_pos;
+extern "C" int _rl_last_v_pos;
+
+typedef std::complex<int> CYCursor;
+
+static CYCursor current_;
+static int width_;
+static size_t point_;
+
+unsigned CYDisplayWidth() {
+ struct winsize info;
+ if (ioctl(1, TIOCGWINSZ, &info) != -1)
+ return info.ws_col;
+ return tgetnum(const_cast<char *>("co"));
+}
+
+void CYDisplayOutput_(bool display, const char *&data) {
+ for (;; ++data) {
+ char next(*data);
+ if (next == '\0' || next == CYIgnoreEnd)
+ return;
+ if (display)
+ putchar(next);
+ }
+}
+
+CYCursor CYDisplayOutput(bool display, int width, const char *data, ssize_t offset = 0) {
+ CYCursor point(current_);
+
+ for (;;) {
+ if (offset-- == 0)
+ point = current_;
+ switch (char next = *data++) {
+ case '\0':
+ return point;
+ break;
+
+ case CYIgnoreStart:
+ CYDisplayOutput_(display, data);
+ case CYIgnoreEnd:
+ ++offset;
+ break;
+
+ default:
+ if (display)
+ putchar(next);
+ current_ += CYCursor(0, 1);
+ if (current_.imag() != width)
+ break;
+ current_ = CYCursor(current_.real() + 1, 0);
+ if (display)
+ putp(clr_eos);
+ break;
+
+ case '\n':
+ current_ = CYCursor(current_.real() + 1, 4);
+ if (display) {
+ putp(clr_eol);
+ putchar('\n');
+ putchar(' ');
+ putchar(' ');
+ putchar(' ');
+ putchar(' ');
+ }
+ break;
+
+ }
+ }
+}
+
+void CYDisplayMove_(char *negative, char *positive, int offset) {
+ if (offset < 0)
+ putp(tparm(negative, -offset));
+ else if (offset > 0)
+ putp(tparm(positive, offset));
+}
+
+void CYDisplayMove(CYCursor target) {
+ CYCursor offset(target - current_);
+
+ CYDisplayMove_(parm_up_cursor, parm_down_cursor, offset.real());
+
+ if (char *parm = tparm(column_address, target.imag()))
+ putp(parm);
+ else
+ CYDisplayMove_(parm_left_cursor, parm_right_cursor, offset.imag());
+
+ current_ = target;
+}
+
+void CYDisplayUpdate() {
+ current_ = CYCursor(_rl_last_v_pos, _rl_last_c_pos);
+
+ const char *prompt(rl_display_prompt);
+
+ std::ostringstream stream;
+ CYLexerHighlight(rl_line_buffer, rl_end, stream, true);
+ std::string string(stream.str());
+ const char *buffer(string.c_str());
+
+ int width(CYDisplayWidth());
+ if (width_ != width) {
+ current_ = CYCursor();
+ CYDisplayOutput(false, width, prompt);
+ current_ = CYDisplayOutput(false, width, buffer, point_);
+ }
+
+ CYDisplayMove(CYCursor());
+ CYDisplayOutput(true, width, prompt);
+ CYCursor target(CYDisplayOutput(true, width, stream.str().c_str(), rl_point));
+
+ _rl_vis_botlin = current_.real();
+
+ if (current_.imag() == 0)
+ CYDisplayOutput(true, width, " ");
+ putp(clr_eos);
+
+ CYDisplayMove(target);
+ fflush(stdout);
+
+ _rl_last_v_pos = current_.real();
+ _rl_last_c_pos = current_.imag();
+
+ width_ = width;
+ point_ = rl_point;
+}