Typetester lets you to practice typing from the command line. Text passages are loaded into a text file, and statistics are generated after every run
Add a passage into a.txt
, compile and run ./main
. Once completed, the results will appear like so:
Terminal Modes
In order to read input, typetester
chnages terminal settings using termios.h
. This library contains flags that control various functions of the terminal, such as the input processing, output, etc. A full list of them can be found here. For this program, canonical mode and output echo were disabled. Canonical mode is the default mode of most terminals. Input is available line-by-line, usually after the user hits Enter. This also allows the user to edit the line, which is useful for typing commands.
In non-canonical mode, user input is available as soon as the character is typed. In the main loop of the program, all we have to do is check if each character equals the current character in the passage.
void setup_terminal()
{
struct termios options;
tcgetattr(STDIN_FILENO, &options);
// enable canonical mode
options.c_lflag &= ~(ICANON);
// disable echo
options.c_lflag &= ~(ECHO);
tcsetattr(STDIN_FILENO, TCSAFLUSH, &options);
}
ANSI Cursor Controls
When a session starts, the cursor is placed at the beginning of the passage. In order to get the correct cursor position, we save it by sending ESC 7
to stdout. Then after printing out the text passage, we restore the cursor position with ESC 8
.
// save current cursor position
write(STDOUT_FILENO, "\e7", 3);
char *text = read_from_file("a.txt");
printf("%s\n", text);
// restore saved cursor position
write(STDOUT_FILENO, "\e8", 3);
Summary
I made this project to experiment with terminal settings, in addition to making something that I normally have to access through the browser. This project can be found at this github repository.
Top comments (0)