readline: add missing documentation, fix documentation format, add README.md (#7683)

pull/7714/head
Larpon 2020-12-30 14:09:13 +01:00 committed by GitHub
parent eef73edb57
commit b1f16533b1
No known key found for this signature in database
GPG Key ID: 4AEE18F83AFDEB23
5 changed files with 248 additions and 159 deletions

View File

@ -0,0 +1,20 @@
# Readline
The `readline` module let you await and read user input
from a terminal in an easy and structured manner.
The module provides an easy way to prompt the user for
questions or even make a REPL or an embedded console.
Use `readline.Readline` if you want to include more
advanced features such as history or simply use
`readline.read_line('Please confirm (y/n):')` directly
for one-off user interactions.
# Usage
```v ignore
import readline { Readline }
Readline.read_line('Continue?: (y/n)')
```

View File

@ -1,43 +1,57 @@
// Copyright (c) 2019-2020 Alexander Medvednikov. All rights reserved.
// Use of this source code is governed by an MIT license
// that can be found in the LICENSE file.
// Will serve as more advanced input method
// Based on the work of https://github.com/AmokHuginnsson/replxx
//
// Serves as a more advanced input method
// based on the work of https://github.com/AmokHuginnsson/replxx
//
module readline
// Linux
// Used to change the terminal options
// Termios stores the terminal options on Linux.
struct Termios {
mut:
c_iflag int
c_oflag int
c_cflag int
c_lflag int
c_cc [12]int //NCCS == 12. Cant use the defined value here
c_iflag int
c_oflag int
c_cflag int
c_lflag int
c_cc [12]int // NCCS == 12. Can't use the defined value here
}
// Linux
// Used to collect the screen information
// Winsize stores the screen information on Linux.
struct Winsize {
ws_row u16
ws_col u16
ws_xpixel u16
ws_ypixel u16
ws_row u16
ws_col u16
ws_xpixel u16
ws_ypixel u16
}
// Readline is the key struct for reading and holding user input via a terminal.
// Example: import readline { Readline }
pub struct Readline {
mut:
is_raw bool
orig_termios Termios // Linux
current ustring // Line being edited
cursor int // Cursor position
overwrite bool
cursor_row_offset int
prompt string
prompt_offset int
previous_lines []ustring
search_index int
is_tty bool
is_raw bool
orig_termios Termios // Linux
current ustring // Line being edited
cursor int // Cursor position
overwrite bool
cursor_row_offset int
prompt string
prompt_offset int
previous_lines []ustring
search_index int
is_tty bool
}
// get_prompt_offset computes the length of the `prompt` `string` argument.
fn get_prompt_offset(prompt string) int {
mut len := 0
for i := 0; i < prompt.len; i++ {
if prompt[i] == `\e` {
for ; i < prompt.len && prompt[i] != `m`; i++ {
}
} else {
len = len + 1
}
}
return prompt.len - len
}

View File

@ -1,65 +1,78 @@
// Copyright (c) 2019-2020 Alexander Medvednikov. All rights reserved.
// Use of this source code is governed by an MIT license
// that can be found in the LICENSE file.
// Mac version
// Need to be implemented
//
// TODO Mac version needs to be implemented
// Will serve as more advanced input method
// Based on the work of https://github.com/AmokHuginnsson/replxx
// based on the work of https://github.com/AmokHuginnsson/replxx
//
module readline
import os
#include <termios.h>
// Only use standard os.get_line
// Need implementation for readline capabilities
//
// read_line_utf8 blocks execution in a loop and awaits user input
// characters from a terminal until `EOF` or `Enter` key is encountered
// in the input stream.
// read_line_utf8 returns the complete input line as an UTF-8 encoded `ustring` or
// an error if the line is empty.
// The `prompt` `string` is output as a prefix text for the input capturing.
// read_line_utf8 is the main method of the `readline` module and `Readline` struct.
pub fn (mut r Readline) read_line_utf8(prompt string) ?ustring {
r.current = ''.ustring()
r.cursor = 0
r.prompt = prompt
r.search_index = 0
if r.previous_lines.len <= 1 {
r.previous_lines << ''.ustring()
r.previous_lines << ''.ustring()
}
else {
r.previous_lines[0] = ''.ustring()
}
print(r.prompt)
line := os.get_raw_line()
if line.len >= 0 {
r.current = line.ustring()
}
r.previous_lines[0] = ''.ustring()
r.search_index = 0
if r.current.s == '' {
return error('empty line')
}
return r.current
r.current = ''.ustring()
r.cursor = 0
r.prompt = prompt
r.search_index = 0
if r.previous_lines.len <= 1 {
r.previous_lines << ''.ustring()
r.previous_lines << ''.ustring()
} else {
r.previous_lines[0] = ''.ustring()
}
print(r.prompt)
line := os.get_raw_line()
if line.len >= 0 {
r.current = line.ustring()
}
r.previous_lines[0] = ''.ustring()
r.search_index = 0
if r.current.s == '' {
return error('empty line')
}
return r.current
}
// Returns the string from the utf8 ustring
// read_line does the same as `read_line_utf8` but returns user input as a `string`.
// (As opposed to `ustring` returned by `read_line_utf8`).
pub fn (mut r Readline) read_line(prompt string) ?string {
s := r.read_line_utf8(prompt)?
return s.s
s := r.read_line_utf8(prompt) ?
return s.s
}
// Standalone function without persistent functionnalities (eg: history)
// Returns utf8 based ustring
// read_line_utf8 blocks execution in a loop and awaits user input
// characters from a terminal until `EOF` or `Enter` key is encountered
// in the input stream.
// read_line_utf8 returns the complete input line as an UTF-8 encoded `ustring` or
// an error if the line is empty.
// The `prompt` `string` is output as a prefix text for the input capturing.
// read_line_utf8 is the main method of the `readline` module and `Readline` struct.
// NOTE that this version of `read_line_utf8` is a standalone function without
// persistent functionalities (e.g. history).
pub fn read_line_utf8(prompt string) ?ustring {
mut r := Readline{}
s := r.read_line_utf8(prompt)?
return s
mut r := Readline{}
s := r.read_line_utf8(prompt) ?
return s
}
// Standalone function without persistent functionnalities (eg: history)
// Return string from utf8 ustring
// read_line does the same as `read_line_utf8` but returns user input as a `string`.
// (As opposed to `ustring` as returned by `read_line_utf8`).
// NOTE that this version of `read_line` is a standalone function without
// persistent functionalities (e.g. history).
pub fn read_line(prompt string) ?string {
mut r := Readline{}
s := r.read_line(prompt)?
return s
mut r := Readline{}
s := r.read_line(prompt) ?
return s
}

View File

@ -1,9 +1,10 @@
// Copyright (c) 2019-2020 Alexander Medvednikov. All rights reserved.
// Use of this source code is governed by an MIT license
// that can be found in the LICENSE file.
// Linux version
// Will serve as more advanced input method
// Based on the work of https://github.com/AmokHuginnsson/replxx
//
// Serves as more advanced input method
// based on the work of https://github.com/AmokHuginnsson/replxx
//
module readline
import term
@ -11,7 +12,15 @@ import os
#include <termios.h>
#include <sys/ioctl.h>
// Defines actions to execute
fn C.tcgetattr() int
fn C.tcsetattr() int
fn C.raise()
fn C.getppid() int
// Action defines what actions to be executed.
enum Action {
eof
nothing
@ -32,17 +41,10 @@ enum Action {
suspend
}
fn C.tcgetattr() int
fn C.tcsetattr() int
fn C.raise()
fn C.getppid() int
// Enable the raw mode of the terminal
// In raw mode all keypresses are directly sent to the program and no interpretation is done
// Catches the SIGUSER (CTRL+C) Signal
// enable_raw_mode enables the raw mode of the terminal.
// In raw mode all key presses are directly sent to the program and no interpretation is done.
// Please note that `enable_raw_mode` catches the `SIGUSER` (CTRL + C) signal.
// For a method that does please see `enable_raw_mode_nosig`.
pub fn (mut r Readline) enable_raw_mode() {
if C.tcgetattr(0, &r.orig_termios) == -1 {
r.is_tty = false
@ -60,8 +62,10 @@ pub fn (mut r Readline) enable_raw_mode() {
r.is_tty = true
}
// Enable the raw mode of the terminal
// Does not catch the SIGUSER (CTRL+C) Signal
// enable_raw_mode_nosig enables the raw mode of the terminal.
// In raw mode all key presses are directly sent to the program and no interpretation is done.
// Please note that `enable_raw_mode_nosig` does not catch the `SIGUSER` (CTRL + C) signal
// as opposed to `enable_raw_mode`.
pub fn (mut r Readline) enable_raw_mode_nosig() {
if C.tcgetattr(0, &r.orig_termios) == -1 {
r.is_tty = false
@ -79,7 +83,8 @@ pub fn (mut r Readline) enable_raw_mode_nosig() {
r.is_tty = true
}
// Disable the raw mode of the terminal
// disable_raw_mode disables the raw mode of the terminal.
// For a description of raw mode please see the `enable_raw_mode` method.
pub fn (mut r Readline) disable_raw_mode() {
if r.is_raw {
C.tcsetattr(0, C.TCSADRAIN, &r.orig_termios)
@ -87,15 +92,18 @@ pub fn (mut r Readline) disable_raw_mode() {
}
}
// Read a single char
// read_char reads a single character.
pub fn (r Readline) read_char() int {
return utf8_getchar()
}
// Main function of the readline module
// Will loop and ingest characters until EOF or Enter
// Returns the completed line as utf8 ustring
// Will return an error if line is empty
// read_line_utf8 blocks execution in a loop and awaits user input
// characters from a terminal until `EOF` or `Enter` key is encountered
// in the input stream.
// read_line_utf8 returns the complete input line as an UTF-8 encoded `ustring` or
// an error if the line is empty.
// The `prompt` `string` is output as a prefix text for the input capturing.
// read_line_utf8 is the main method of the `readline` module and `Readline` struct.
pub fn (mut r Readline) read_line_utf8(prompt string) ?ustring {
r.current = ''.ustring()
r.cursor = 0
@ -129,41 +137,39 @@ pub fn (mut r Readline) read_line_utf8(prompt string) ?ustring {
return r.current
}
// Returns the string from the utf8 ustring
// read_line does the same as `read_line_utf8` but returns user input as a `string`.
// (As opposed to `ustring` returned by `read_line_utf8`).
pub fn (mut r Readline) read_line(prompt string) ?string {
s := r.read_line_utf8(prompt) ?
return s.s
}
// Standalone function without persistent functionnalities (eg: history)
// Returns utf8 based ustring
// read_line_utf8 blocks execution in a loop and awaits user input
// characters from a terminal until `EOF` or `Enter` key is encountered
// in the input stream.
// read_line_utf8 returns the complete input line as an UTF-8 encoded `ustring` or
// an error if the line is empty.
// The `prompt` `string` is output as a prefix text for the input capturing.
// read_line_utf8 is the main method of the `readline` module and `Readline` struct.
// NOTE that this version of `read_line_utf8` is a standalone function without
// persistent functionalities (e.g. history).
pub fn read_line_utf8(prompt string) ?ustring {
mut r := Readline{}
s := r.read_line_utf8(prompt) ?
return s
}
// Standalone function without persistent functionnalities (eg: history)
// Return string from utf8 ustring
// read_line does the same as `read_line_utf8` but returns user input as a `string`.
// (As opposed to `ustring` as returned by `read_line_utf8`).
// NOTE that this version of `read_line` is a standalone function without
// persistent functionalities (e.g. history).
pub fn read_line(prompt string) ?string {
mut r := Readline{}
s := r.read_line(prompt) ?
return s
}
fn get_prompt_offset(prompt string) int {
mut len := 0
for i := 0; i < prompt.len; i++ {
if prompt[i] == `\e` {
for ; i < prompt.len && prompt[i] != `m`; i++ {
}
} else {
len = len + 1
}
}
return prompt.len - len
}
// analyse returns an `Action` based on the type of input byte given in `c`.
fn (r Readline) analyse(c int) Action {
match byte(c) {
`\0`, 0x3, 0x4, 255 { return .eof } // NUL, End of Text, End of Transmission
@ -182,6 +188,7 @@ fn (r Readline) analyse(c int) Action {
}
}
// analyse_control returns an `Action` based on the type of input read by `read_char`.
fn (r Readline) analyse_control() Action {
c := r.read_char()
match byte(c) {
@ -223,6 +230,8 @@ match c {
return .nothing
}
// analyse_extended_control returns an `Action` based on the type of input read by `read_char`.
// analyse_extended_control specialises in cursor control.
fn (r Readline) analyse_extended_control() Action {
r.read_char() // Removes ;
c := r.read_char()
@ -240,19 +249,24 @@ fn (r Readline) analyse_extended_control() Action {
return .nothing
}
// analyse_extended_control_no_eat returns an `Action` based on the type of input byte given in `c`.
// analyse_extended_control_no_eat specialises in detection of delete and insert keys.
fn (r Readline) analyse_extended_control_no_eat(last_c byte) Action {
c := r.read_char()
match byte(c) {
`~` { match last_c {
`~` {
match last_c {
`3` { return .delete_right } // Suppr key
`2` { return .overwrite }
else {}
} }
}
}
else {}
}
return .nothing
}
// execute executes the corresponding methods on `Readline` based on `a Action` and `c int` arguments.
fn (mut r Readline) execute(a Action, c int) bool {
match a {
.eof { return r.eof() }
@ -276,12 +290,14 @@ fn (mut r Readline) execute(a Action, c int) bool {
return false
}
// get_screen_columns returns the number of columns (`width`) in the terminal.
fn get_screen_columns() int {
ws := Winsize{}
cols := if C.ioctl(1, C.TIOCGWINSZ, &ws) == -1 { 80 } else { int(ws.ws_col) }
return cols
}
// shift_cursor warps the cursor to `xpos` with `yoffset`.
fn shift_cursor(xpos int, yoffset int) {
if yoffset != 0 {
if yoffset > 0 {
@ -294,6 +310,7 @@ fn shift_cursor(xpos int, yoffset int) {
print('\x1b[${xpos + 1}G')
}
// calculate_screen_position returns a position `[x, y]int` based on various terminal attributes.
fn calculate_screen_position(x_in int, y_in int, screen_columns int, char_count int, inp []int) []int {
mut out := inp.clone()
mut x := x_in
@ -316,7 +333,7 @@ fn calculate_screen_position(x_in int, y_in int, screen_columns int, char_count
return out
}
// Will redraw the line
// refresh_line redraws the current line, including the prompt.
fn (mut r Readline) refresh_line() {
mut end_of_input := [0, 0]
end_of_input = calculate_screen_position(r.prompt.len, 0, get_screen_columns(), r.current.len,
@ -336,7 +353,7 @@ fn (mut r Readline) refresh_line() {
r.cursor_row_offset = cursor_pos[1]
}
// End the line without a newline
// eof ends the line *without* a newline.
fn (mut r Readline) eof() bool {
r.previous_lines.insert(1, r.current)
r.cursor = r.current.len
@ -346,6 +363,7 @@ fn (mut r Readline) eof() bool {
return true
}
// insert_character inserts the character `c` at current cursor position.
fn (mut r Readline) insert_character(c int) {
if !r.overwrite || r.cursor == r.current.len {
r.current = r.current.left(r.cursor).ustring().add(utf32_to_str(u32(c)).ustring()).add(r.current.right(r.cursor).ustring())
@ -370,7 +388,7 @@ fn (mut r Readline) delete_character() {
r.refresh_line()
}
// Removes the character in front of cursor.
// suppr_character removes (suppresses) the character in front of the cursor.
fn (mut r Readline) suppr_character() {
if r.cursor > r.current.len {
return
@ -379,7 +397,7 @@ fn (mut r Readline) suppr_character() {
r.refresh_line()
}
// Add a line break then stops the main loop
// commit_line adds a line break and then stops the main loop.
fn (mut r Readline) commit_line() bool {
r.previous_lines.insert(1, r.current)
a := '\n'.ustring()
@ -392,6 +410,7 @@ fn (mut r Readline) commit_line() bool {
return true
}
// move_cursor_left moves the cursor relative one cell to the left.
fn (mut r Readline) move_cursor_left() {
if r.cursor > 0 {
r.cursor--
@ -399,6 +418,7 @@ fn (mut r Readline) move_cursor_left() {
}
}
// move_cursor_right moves the cursor relative one cell to the right.
fn (mut r Readline) move_cursor_right() {
if r.cursor < r.current.len {
r.cursor++
@ -406,22 +426,24 @@ fn (mut r Readline) move_cursor_right() {
}
}
// move_cursor_begining moves the cursor to the beginning of the current line.
fn (mut r Readline) move_cursor_begining() {
r.cursor = 0
r.refresh_line()
}
// move_cursor_end moves the cursor to the end of the current line.
fn (mut r Readline) move_cursor_end() {
r.cursor = r.current.len
r.refresh_line()
}
// Check if the character is considered as a word-breaking character
// is_break_character returns true if the character is considered as a word-breaking character.
fn (r Readline) is_break_character(c string) bool {
break_characters := ' \t\v\f\a\b\r\n`~!@#$%^&*()-=+[{]}\\|;:\'",<.>/?'
return break_characters.contains(c)
}
// move_cursor_word_left moves the cursor relative one word length worth to the left.
fn (mut r Readline) move_cursor_word_left() {
if r.cursor > 0 {
for ; r.cursor > 0 && r.is_break_character(r.current.at(r.cursor - 1)); r.cursor-- {
@ -432,6 +454,7 @@ fn (mut r Readline) move_cursor_word_left() {
}
}
// move_cursor_word_right moves the cursor relative one word length worth to the right.
fn (mut r Readline) move_cursor_word_right() {
if r.cursor < r.current.len {
for ; r.cursor < r.current.len && r.is_break_character(r.current.at(r.cursor)); r.cursor++ {
@ -442,16 +465,19 @@ fn (mut r Readline) move_cursor_word_right() {
}
}
// switch_overwrite toggles Readline `overwrite` mode on/off.
fn (mut r Readline) switch_overwrite() {
r.overwrite = !r.overwrite
}
// clear_screen clears the current terminal window contents and positions the cursor at top left.
fn (mut r Readline) clear_screen() {
term.set_cursor_position(x: 1, y: 1)
term.erase_clear()
r.refresh_line()
}
// history_previous sets current line to the content of the previous line in the history buffer.
fn (mut r Readline) history_previous() {
if r.search_index + 2 >= r.previous_lines.len {
return
@ -465,6 +491,7 @@ fn (mut r Readline) history_previous() {
r.refresh_line()
}
// history_next sets current line to the content of the next line in the history buffer.
fn (mut r Readline) history_next() {
if r.search_index <= 0 {
return
@ -475,6 +502,7 @@ fn (mut r Readline) history_next() {
r.refresh_line()
}
// suspend sends the `SIGSTOP` signal to the terminal.
fn (mut r Readline) suspend() {
is_standalone := os.getenv('VCHILD') != 'true'
r.disable_raw_mode()

View File

@ -1,60 +1,74 @@
// Copyright (c) 2019-2020 Alexander Medvednikov. All rights reserved.
// Use of this source code is governed by an MIT license
// that can be found in the LICENSE file.
// Windows version
// Need to be implemented
//
// TODO Windows version needs to be implemented.
// Will serve as more advanced input method
// Based on the work of https://github.com/AmokHuginnsson/replxx
// based on the work of https://github.com/AmokHuginnsson/replxx
//
module readline
import os
// Only use standard os.get_line
// Need implementation for readline capabilities
//
// read_line_utf8 blocks execution in a loop and awaits user input
// characters from a terminal until `EOF` or `Enter` key is encountered
// in the input stream.
// read_line_utf8 returns the complete input line as an UTF-8 encoded `ustring` or
// an error if the line is empty.
// The `prompt` `string` is output as a prefix text for the input capturing.
// read_line_utf8 is the main method of the `readline` module and `Readline` struct.
pub fn (mut r Readline) read_line_utf8(prompt string) ?ustring {
r.current = ''.ustring()
r.cursor = 0
r.prompt = prompt
r.search_index = 0
if r.previous_lines.len <= 1 {
r.previous_lines << ''.ustring()
r.previous_lines << ''.ustring()
}
else {
r.previous_lines[0] = ''.ustring()
}
print(r.prompt)
r.current = os.get_raw_line().ustring()
r.previous_lines[0] = ''.ustring()
r.search_index = 0
if r.current.s == '' {
return error('empty line')
}
return r.current
r.current = ''.ustring()
r.cursor = 0
r.prompt = prompt
r.search_index = 0
if r.previous_lines.len <= 1 {
r.previous_lines << ''.ustring()
r.previous_lines << ''.ustring()
} else {
r.previous_lines[0] = ''.ustring()
}
print(r.prompt)
r.current = os.get_raw_line().ustring()
r.previous_lines[0] = ''.ustring()
r.search_index = 0
if r.current.s == '' {
return error('empty line')
}
return r.current
}
// Returns the string from the utf8 ustring
// read_line does the same as `read_line_utf8` but returns user input as a `string`.
// (As opposed to `ustring` returned by `read_line_utf8`).
pub fn (mut r Readline) read_line(prompt string) ?string {
s := r.read_line_utf8(prompt)?
return s.s
s := r.read_line_utf8(prompt) ?
return s.s
}
// Standalone function without persistent functionnalities (eg: history)
// Returns utf8 based ustring
// read_line_utf8 blocks execution in a loop and awaits user input
// characters from a terminal until `EOF` or `Enter` key is encountered
// in the input stream.
// read_line_utf8 returns the complete input line as an UTF-8 encoded `ustring` or
// an error if the line is empty.
// The `prompt` `string` is output as a prefix text for the input capturing.
// read_line_utf8 is the main method of the `readline` module and `Readline` struct.
// NOTE that this version of `read_line_utf8` is a standalone function without
// persistent functionalities (e.g. history).
pub fn read_line_utf8(prompt string) ?ustring {
mut r := Readline{}
s := r.read_line_utf8(prompt)?
return s
mut r := Readline{}
s := r.read_line_utf8(prompt) ?
return s
}
// Standalone function without persistent functionnalities (eg: history)
// Return string from utf8 ustring
// read_line does the same as `read_line_utf8` but returns user input as a `string`.
// (As opposed to `ustring` as returned by `read_line_utf8`).
// NOTE that this version of `read_line` is a standalone function without
// persistent functionalities (e.g. history).
pub fn read_line(prompt string) ?string {
mut r := Readline{}
s := r.read_line(prompt)?
return s
mut r := Readline{}
s := r.read_line(prompt) ?
return s
}