Skip to content

Commit 7347fea

Browse files
committed
Make prompt work without a terminal attached
This is helpful to be able to test the prompt at a CI by redirecting stdin from a file
1 parent b3b8eb4 commit 7347fea

File tree

1 file changed

+25
-10
lines changed

1 file changed

+25
-10
lines changed

cpp-terminal/terminal.h

Lines changed: 25 additions & 10 deletions
Original file line numberDiff line numberDiff line change
@@ -725,18 +725,24 @@ struct Model
725725
size_t cursor_col, cursor_row;
726726
};
727727

728-
inline std::string render(const Model &m, int prompt_row, int term_cols)
728+
inline std::string render(const Model &m, int prompt_row, int term_cols, bool term)
729729
{
730730
std::string out;
731-
out = cursor_off();
732-
out += move_cursor(prompt_row, 1) + m.prompt_string + m.input;
731+
if (term) {
732+
out = cursor_off();
733+
out += move_cursor(prompt_row, 1);
734+
}
735+
out += m.prompt_string;
736+
out += m.input;
733737
size_t last_col = m.prompt_string.size() + m.input.size();
734738
for (size_t i=0; i < term_cols-last_col; i++) {
735739
out.append(" ");
736740
}
737-
out.append(move_cursor(prompt_row+m.cursor_row-1,
738-
m.prompt_string.size() + m.cursor_col));
739-
out.append(cursor_on());
741+
if (term) {
742+
out.append(move_cursor(prompt_row+m.cursor_row-1,
743+
m.prompt_string.size() + m.cursor_col));
744+
out.append(cursor_on());
745+
}
740746
return out;
741747
}
742748

@@ -747,9 +753,18 @@ inline std::string prompt(const Terminal &term, const std::string &prompt_string
747753
std::vector<std::string> &history = PROMPT_HISTORY)
748754
{
749755
int row, col;
750-
term.get_cursor_position(row, col);
756+
bool term_attached = term.is_stdin_a_tty();
757+
if (term_attached) {
758+
term.get_cursor_position(row, col);
759+
} else {
760+
row = 1;
761+
col = 1;
762+
}
751763
int rows, cols;
752-
term.get_term_size(rows, cols);
764+
if (!term.get_term_size(rows, cols)) {
765+
rows = 25;
766+
cols = 80;
767+
}
753768

754769
Model m;
755770
m.prompt_string = prompt_string;
@@ -763,7 +778,7 @@ inline std::string prompt(const Terminal &term, const std::string &prompt_string
763778
hist.push_back(m.input); // Push back empty input
764779

765780
int key;
766-
std::cout << render(m, row, cols) << std::flush;
781+
std::cout << render(m, row, cols, term_attached) << std::flush;
767782
while ((key = term.read_key()) != Key::ENTER) {
768783
if ( (key >= 'a' && key <= 'z') ||
769784
(key >= 'A' && key <= 'Z') ||
@@ -822,7 +837,7 @@ inline std::string prompt(const Terminal &term, const std::string &prompt_string
822837
break;
823838
}
824839
}
825-
std::cout << render(m, row, cols) << std::flush;
840+
std::cout << render(m, row, cols, term_attached) << std::flush;
826841
}
827842
std::cout << "\n" << std::flush;
828843
history.push_back(m.input);

0 commit comments

Comments
 (0)