3 // Package term provides structures and helper functions to work with
4 // terminal (state, sizes).
14 "golang.org/x/sys/unix"
18 // ErrInvalidState is returned if the state of the terminal is invalid.
19 ErrInvalidState = errors.New("Invalid terminal state")
22 // State represents the state of the terminal.
27 // Winsize represents the size of the terminal window.
35 // StdStreams returns the standard streams (stdin, stdout, stderr).
36 func StdStreams() (stdIn io.ReadCloser, stdOut, stdErr io.Writer) {
37 return os.Stdin, os.Stdout, os.Stderr
40 // GetFdInfo returns the file descriptor for an os.File and indicates whether the file represents a terminal.
41 func GetFdInfo(in interface{}) (uintptr, bool) {
44 if file, ok := in.(*os.File); ok {
46 isTerminalIn = IsTerminal(inFd)
48 return inFd, isTerminalIn
51 // IsTerminal returns true if the given file descriptor is a terminal.
52 func IsTerminal(fd uintptr) bool {
54 return tcget(fd, &termios) == 0
57 // RestoreTerminal restores the terminal connected to the given file descriptor
58 // to a previous state.
59 func RestoreTerminal(fd uintptr, state *State) error {
61 return ErrInvalidState
63 if err := tcset(fd, &state.termios); err != 0 {
69 // SaveState saves the state of the terminal connected to the given file descriptor.
70 func SaveState(fd uintptr) (*State, error) {
72 if err := tcget(fd, &oldState.termios); err != 0 {
79 // DisableEcho applies the specified state to the terminal connected to the file
80 // descriptor, with echo disabled.
81 func DisableEcho(fd uintptr, state *State) error {
82 newState := state.termios
83 newState.Lflag &^= unix.ECHO
85 if err := tcset(fd, &newState); err != 0 {
88 handleInterrupt(fd, state)
92 // SetRawTerminal puts the terminal connected to the given file descriptor into
93 // raw mode and returns the previous state. On UNIX, this puts both the input
94 // and output into raw mode. On Windows, it only puts the input into raw mode.
95 func SetRawTerminal(fd uintptr) (*State, error) {
96 oldState, err := MakeRaw(fd)
100 handleInterrupt(fd, oldState)
104 // SetRawTerminalOutput puts the output of terminal connected to the given file
105 // descriptor into raw mode. On UNIX, this does nothing and returns nil for the
106 // state. On Windows, it disables LF -> CRLF translation.
107 func SetRawTerminalOutput(fd uintptr) (*State, error) {
111 func handleInterrupt(fd uintptr, state *State) {
112 sigchan := make(chan os.Signal, 1)
113 signal.Notify(sigchan, os.Interrupt)
116 // quit cleanly and the new terminal item is on a new line
120 RestoreTerminal(fd, state)