From 253e391bfc84b2b99443e664b10cc332c22eb97a Mon Sep 17 00:00:00 2001 From: Andreas Kling Date: Fri, 19 Jul 2019 20:01:46 +0200 Subject: [PATCH] Shell: Implement support for terminal clearing with ^L. Make LineEditor::get_line() responsible for printing the prompt. That way we can re-prompt after clearing the screen on ^L. This makes the Serenity Terminal feel a little bit more like home :^) --- Shell/LineEditor.cpp | 15 ++++++++++++++- Shell/LineEditor.h | 2 +- Shell/main.cpp | 17 ++++++++--------- 3 files changed, 23 insertions(+), 11 deletions(-) diff --git a/Shell/LineEditor.cpp b/Shell/LineEditor.cpp index b1bd1df8e8..6b1086ff9d 100644 --- a/Shell/LineEditor.cpp +++ b/Shell/LineEditor.cpp @@ -37,8 +37,11 @@ void LineEditor::append(const String& string) m_cursor = m_buffer.size(); } -String LineEditor::get_line() +String LineEditor::get_line(const String& prompt) { + fputs(prompt.characters(), stdout); + fflush(stdout); + m_history_cursor = m_history.size(); m_cursor = 0; for (;;) { @@ -190,6 +193,16 @@ String LineEditor::get_line() do_backspace(); continue; } + if (ch == 0xc) { // ^L + printf("\033[3J\033[H\033[2J"); // Clear screen. + fputs(prompt.characters(), stdout); + for (int i = 0; i < m_buffer.size(); ++i) + fputc(m_buffer[i], stdout); + if (m_cursor < m_buffer.size()) + printf("\033[%dD", m_buffer.size() - m_cursor); // Move cursor N steps left. + fflush(stdout); + continue; + } putchar(ch); fflush(stdout); if (ch == '\n') { diff --git a/Shell/LineEditor.h b/Shell/LineEditor.h index da01c435af..f7fd0c3e26 100644 --- a/Shell/LineEditor.h +++ b/Shell/LineEditor.h @@ -8,7 +8,7 @@ public: LineEditor(); ~LineEditor(); - String get_line(); + String get_line(const String& prompt); void add_to_history(const String&); const Vector& history() const { return m_history; } diff --git a/Shell/main.cpp b/Shell/main.cpp index edad94f0d1..c6aa1e0270 100644 --- a/Shell/main.cpp +++ b/Shell/main.cpp @@ -25,15 +25,15 @@ GlobalState g; static LineEditor editor; -static void prompt() +static String prompt() { if (g.uid == 0) - printf("# "); - else { - printf("\033]0;%s@%s:%s\007", g.username.characters(), g.hostname, g.cwd.characters()); - printf("\033[31;1m%s\033[0m@\033[37;1m%s\033[0m:\033[32;1m%s\033[0m$> ", g.username.characters(), g.hostname, g.cwd.characters()); - } - fflush(stdout); + return "# "; + + StringBuilder builder; + builder.appendf("\033]0;%s@%s:%s\007", g.username.characters(), g.hostname, g.cwd.characters()); + builder.appendf("\033[31;1m%s\033[0m@\033[37;1m%s\033[0m:\033[32;1m%s\033[0m$> ", g.username.characters(), g.hostname, g.cwd.characters()); + return builder.to_string(); } static int sh_pwd(int, char**) @@ -602,8 +602,7 @@ int main(int argc, char** argv) atexit(save_history); for (;;) { - prompt(); - auto line = editor.get_line(); + auto line = editor.get_line(prompt()); if (line.is_empty()) continue; run_command(line);