Try to get the number of columns in the current terminal, or assume 80 * if it fails. */
| 931 | /* Try to get the number of columns in the current terminal, or assume 80 |
| 932 | * if it fails. */ |
| 933 | int getColumns(int ifd, int ofd) { |
| 934 | #ifdef _WIN32 |
| 935 | CONSOLE_SCREEN_BUFFER_INFO b; |
| 936 | |
| 937 | if (!GetConsoleScreenBufferInfo(hOut, &b)) |
| 938 | return 80; |
| 939 | return b.srWindow.Right - b.srWindow.Left; |
| 940 | #else |
| 941 | struct winsize ws; |
| 942 | |
| 943 | if (ioctl(1, TIOCGWINSZ, &ws) == -1 || ws.ws_col == 0) { |
| 944 | /* ioctl() failed. Try to query the terminal itself. */ |
| 945 | int start, cols; |
| 946 | |
| 947 | /* Get the initial position so we can restore it later. */ |
| 948 | start = getCursorPosition(ifd, ofd); |
| 949 | if (start == -1) |
| 950 | goto failed; |
| 951 | |
| 952 | /* Go to right margin and get position. */ |
| 953 | if (write(ofd, "\x1b[999C", 6) != 6) |
| 954 | goto failed; |
| 955 | cols = getCursorPosition(ifd, ofd); |
| 956 | if (cols == -1) |
| 957 | goto failed; |
| 958 | |
| 959 | /* Restore position. */ |
| 960 | if (cols > start) { |
| 961 | char seq[32]; |
| 962 | snprintf(seq, 32, "\x1b[%dD", cols - start); |
| 963 | if (write(ofd, seq, strlen(seq)) == -1) { |
| 964 | /* Can't recover... */ |
| 965 | } |
| 966 | } |
| 967 | return cols; |
| 968 | } else { |
| 969 | return ws.ws_col; |
| 970 | } |
| 971 | |
| 972 | failed: |
| 973 | return 80; |
| 974 | #endif |
| 975 | } |
| 976 | |
| 977 | /* Try to get the number of rows in the current terminal, or assume 24 |
| 978 | * if it fails. */ |
no test coverage detected