Skip to content

Commit 0976b8f

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 0976b8f

File tree

1 file changed

+25
-11
lines changed

1 file changed

+25
-11
lines changed

cpp-terminal/terminal.h

Lines changed: 25 additions & 11 deletions
Original file line numberDiff line numberDiff line change
@@ -725,18 +725,23 @@ 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)
729-
{
728+
std::string render(const Model &m, int prompt_row, int term_cols, bool term) {
730729
std::string out;
731-
out = cursor_off();
732-
out += move_cursor(prompt_row, 1) + m.prompt_string + m.input;
730+
if (term) {
731+
out = cursor_off();
732+
out += move_cursor(prompt_row, 1);
733+
}
734+
out += m.prompt_string;
735+
out += m.input;
733736
size_t last_col = m.prompt_string.size() + m.input.size();
734737
for (size_t i=0; i < term_cols-last_col; i++) {
735738
out.append(" ");
736739
}
737-
out.append(move_cursor(prompt_row+m.cursor_row-1,
738-
m.prompt_string.size() + m.cursor_col));
739-
out.append(cursor_on());
740+
if (term) {
741+
out.append(move_cursor(prompt_row+m.cursor_row-1,
742+
m.prompt_string.size() + m.cursor_col));
743+
out.append(cursor_on());
744+
}
740745
return out;
741746
}
742747

@@ -747,9 +752,18 @@ inline std::string prompt(const Terminal &term, const std::string &prompt_string
747752
std::vector<std::string> &history = PROMPT_HISTORY)
748753
{
749754
int row, col;
750-
term.get_cursor_position(row, col);
755+
bool term_attached = term.is_stdin_a_tty();
756+
if (term_attached) {
757+
term.get_cursor_position(row, col);
758+
} else {
759+
row = 1;
760+
col = 1;
761+
}
751762
int rows, cols;
752-
term.get_term_size(rows, cols);
763+
if (!term.get_term_size(rows, cols)) {
764+
rows = 25;
765+
cols = 80;
766+
}
753767

754768
Model m;
755769
m.prompt_string = prompt_string;
@@ -763,7 +777,7 @@ inline std::string prompt(const Terminal &term, const std::string &prompt_string
763777
hist.push_back(m.input); // Push back empty input
764778

765779
int key;
766-
std::cout << render(m, row, cols) << std::flush;
780+
std::cout << render(m, row, cols, term_attached) << std::flush;
767781
while ((key = term.read_key()) != Key::ENTER) {
768782
if ( (key >= 'a' && key <= 'z') ||
769783
(key >= 'A' && key <= 'Z') ||
@@ -822,7 +836,7 @@ inline std::string prompt(const Terminal &term, const std::string &prompt_string
822836
break;
823837
}
824838
}
825-
std::cout << render(m, row, cols) << std::flush;
839+
std::cout << render(m, row, cols, term_attached) << std::flush;
826840
}
827841
std::cout << "\n" << std::flush;
828842
history.push_back(m.input);

0 commit comments

Comments
 (0)