readLine reads a single line from stdin and accepts either \n or \r as the line ending. Terminals such as kitty on macOS send a bare \r when Enter is pressed, and fmt.Scanln waited for a \n that never arrived.
()
| 392 | // line ending. Terminals such as kitty on macOS send a bare \r when Enter is |
| 393 | // pressed, and fmt.Scanln waited for a \n that never arrived. |
| 394 | func readLine() (string, error) { |
| 395 | reader := stdinLineReader() |
| 396 | |
| 397 | var line []rune |
| 398 | for { |
| 399 | ch, _, err := reader.ReadRune() |
| 400 | if err != nil { |
| 401 | return string(line), err |
| 402 | } |
| 403 | switch ch { |
| 404 | case '\n': |
| 405 | return string(line), nil |
| 406 | case '\r': |
| 407 | // Drop the \n of a \r\n ending so it is not read as an empty |
| 408 | // answer at the next prompt. |
| 409 | if next, _, err := reader.ReadRune(); err == nil && next != '\n' { |
| 410 | _ = reader.UnreadRune() |
| 411 | } |
| 412 | return string(line), nil |
| 413 | } |
| 414 | line = append(line, ch) |
| 415 | } |
| 416 | } |