update watch file
[cl-readline.git] / cl-termios.c
1 /*
2  *   Copyright (c) 2003 Nikodemus Siivola
3  *
4  *   Permission is hereby granted, free of charge, to any person obtaining
5  *   a copy of this software and associated documentation files (the
6  *   "Software"), to deal in the Software without restriction, including
7  *   without limitation the rights to use, copy, modify, merge, publish,
8  *   distribute, sublicense, and/or sell copies of the Software, and to
9  *   permit persons to whom the Software is furnished to do so, subject to
10  *   the following conditions:
11  *
12  *   The above copyright notice and this permission notice shall be included
13  *   in all copies or substantial portions of the Software.
14  *
15  *   THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND,
16  *   EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF
17  *   MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT.
18  *   IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY
19  *   CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT,
20  *   TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE
21  *   SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
22  */
23
24 #include <unistd.h>
25 #include <termios.h>
26 #include <stdlib.h>
27
28 typedef struct {
29   struct termios *attr;
30   void *next;
31 }
32 state_t;
33
34 state_t * stack = NULL;
35
36 int
37 save_term (void)
38 {
39   state_t * state = malloc (sizeof (state_t));
40   struct termios * attr = malloc (sizeof (struct termios));
41   if (! (state && attr))
42     return 0;
43
44   tcgetattr (STDIN_FILENO, attr);
45
46   state->attr = attr;
47   state->next = stack;
48   stack = state;
49
50   return 1;
51 }
52
53 void
54 restore_term (void)
55 {
56   state_t * tmp = stack;
57   if (!stack) return;
58
59   tcsetattr (STDIN_FILENO, TCSANOW, stack->attr);
60   stack = stack->next;
61
62   free (tmp->attr);
63   free (tmp);
64 }
65
66 int
67 no_echo (void)
68 {
69   struct termios attr;
70   if (! (isatty (STDIN_FILENO) && save_term ()))
71     return 0;
72
73   tcgetattr (STDIN_FILENO, &attr);
74   attr.c_lflag &= ~ECHO;
75   tcsetattr (STDIN_FILENO, TCSAFLUSH, &attr);
76
77   return 1;
78 }