Still broken, slightly less. Will import code from iode.
[iomenu.git] / util.c
blobf1d80f98aa1621c4e356f0fda1a196d1b6132a31
1 #include <stdio.h>
2 #include <stdlib.h>
3 #include <string.h>
4 #include <termios.h>
5 #include <unistd.h>
7 #include "main.h"
11 * Reset the terminal state and exit with error.
13 void
14 die(const char *s)
16 /* tcsetattr(STDIN_FILENO, TCSANOW, &termio_old); */
17 fprintf(stderr, "%s\n", s);
18 exit(EXIT_FAILURE);
23 * Set terminal to send one char at a time for interactive mode, and return the
24 * last terminal state.
26 struct termios
27 set_terminal(int tty_fd)
29 struct termios termio_old;
30 struct termios termio_new;
32 /* set the terminal to send one key at a time. */
34 /* get the terminal's state */
35 if (tcgetattr(tty_fd, &termio_old) < 0)
36 die("Can not get terminal attributes with tcgetattr().");
38 /* create a new modified state by switching the binary flags */
39 termio_new = termio_old;
40 termio_new.c_lflag &= ~(ICANON | ECHO | IGNBRK);
42 /* apply this state to current terminal now (TCSANOW) */
43 tcsetattr(tty_fd, TCSANOW, &termio_new);
45 return termio_old;
50 * Replace tab as a multiple of 8 spaces in a line.
52 * Allocates memory.
54 char *
55 expand_tabs(char *line)
57 size_t i, n;
58 char *converted = malloc(sizeof(char) * (strlen(line) * 8 + 1));
60 for (i = 0, n = 0; i < strlen(line); i++, n++) {
61 if (line[i] == '\t') {
62 for (; n == 0 || n % 8 != 0; n++)
63 converted[n] = ' ';
64 n--;
65 } else {
66 converted[n] = line[i];
70 converted[n] = '\0';
72 return converted;