The internal of go-prompt: How to control the rich terminal UI (Part I).

https://github.com/c-bata/kube-prompt
  • Part I A brief history of terminals. What is VT-100 escape sequences? How do we get the window size of terminal emulators?
  • Part II What is raw-mode. How to emulate the buffer information of the Terminal. (still not published)
  • Part III Re-thinking the design of components of go-prompt for v1.0.0. (still not published)

A brief history of the terminal.

Before digging into the source code of terminal control, let’s learn about the history of the terminal. I introduce two terminal machines here. Both of these were widely used in the past which I wasn’t still born.

Image refers from wikipedia.org
  • Carriage Return(CR): Reset the printhead to the beginning of a line.
  • Line Feed (LF): Turned the wheel to move the paper to change the line.
Image refers from wikipedia.org

VT100 escape sequences

Change the terminal color
  • \x1b[ : control sequence introducer
  • 4;30;46 : parameters which separated by a semi-colon. 4 means underline, 30 means set foreground color Black and 46 means set background color Cyan.
  • m : a final character (which is always one character).

How to get a window size of the Terminal emulator.

We can change the window sizes because we use terminal emulators, not terminal machines. In this section, let’s learn about how to get the size of terminal emulators. To get the window size, you need to call ioctl(2) with TIOCGWINSZ like following².

type winsize struct {
Row uint16
Col uint16
X uint16
Y uint16
}

func getWinSize(fd int) (row, col uint16, err error) {
var ws *winsize
retCode, _, errno := syscall.Syscall(
syscall.SYS_IOCTL, uintptr(fd),
uintptr(syscall.TIOCGWINSZ),
uintptr(unsafe.Pointer(ws)))
if int(retCode) == -1 {
panic(errno)
}
return ws.Row, ws.Col, nil
}
Spread the progress bar with the window column size.
This program has a problem that it doesn’t follow the changes of window size.
Follow the changes of window size

What you’ll learn next?

If you understand this article, you can develop rich terminal UI applications. In the next article, I describe how to handle user inputs. If you learn the next article, you can get all the basics to develop go-prompt.

Footnotes

[1]: Some of the terminals for Windows don’t adopt VT100 escape sequences. I don’t know the details but it seems needs to learn about Win32 Console API.

--

--

Get the Medium app

A button that says 'Download on the App Store', and if clicked it will lead you to the iOS App store
A button that says 'Get it on, Google Play', and if clicked it will lead you to the Google Play store
Masashi SHIBATA

Masashi SHIBATA

115 Followers

Creator of go-prompt and kube-prompt. Optuna core-dev. Kubeflow/Katib reviewer. GitHub: c-bata