b49af889cf686ac4c9398c1769d9679e141557e8
[platform/upstream/bash.git] / lib / readline / input.c
1 /* input.c -- character input functions for readline. */
2
3 /* Copyright (C) 1994-2010 Free Software Foundation, Inc.
4
5    This file is part of the GNU Readline Library (Readline), a library
6    for reading lines of text with interactive input and history editing.      
7
8    Readline is free software: you can redistribute it and/or modify
9    it under the terms of the GNU General Public License as published by
10    the Free Software Foundation, either version 3 of the License, or
11    (at your option) any later version.
12
13    Readline is distributed in the hope that it will be useful,
14    but WITHOUT ANY WARRANTY; without even the implied warranty of
15    MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
16    GNU General Public License for more details.
17
18    You should have received a copy of the GNU General Public License
19    along with Readline.  If not, see <http://www.gnu.org/licenses/>.
20 */
21
22 #define READLINE_LIBRARY
23
24 #if defined (__TANDEM)
25 #  include <floss.h>
26 #endif
27
28 #if defined (HAVE_CONFIG_H)
29 #  include <config.h>
30 #endif
31
32 #include <sys/types.h>
33 #include <fcntl.h>
34 #if defined (HAVE_SYS_FILE_H)
35 #  include <sys/file.h>
36 #endif /* HAVE_SYS_FILE_H */
37
38 #if defined (HAVE_UNISTD_H)
39 #  include <unistd.h>
40 #endif /* HAVE_UNISTD_H */
41
42 #if defined (HAVE_STDLIB_H)
43 #  include <stdlib.h>
44 #else
45 #  include "ansi_stdlib.h"
46 #endif /* HAVE_STDLIB_H */
47
48 #include "posixselect.h"
49
50 #if defined (FIONREAD_IN_SYS_IOCTL)
51 #  include <sys/ioctl.h>
52 #endif
53
54 #include <stdio.h>
55 #include <errno.h>
56
57 #if !defined (errno)
58 extern int errno;
59 #endif /* !errno */
60
61 /* System-specific feature definitions and include files. */
62 #include "rldefs.h"
63 #include "rlmbutil.h"
64
65 /* Some standard library routines. */
66 #include "readline.h"
67
68 #include "rlprivate.h"
69 #include "rlshell.h"
70 #include "xmalloc.h"
71
72 /* What kind of non-blocking I/O do we have? */
73 #if !defined (O_NDELAY) && defined (O_NONBLOCK)
74 #  define O_NDELAY O_NONBLOCK   /* Posix style */
75 #endif
76
77 /* Non-null means it is a pointer to a function to run while waiting for
78    character input. */
79 rl_hook_func_t *rl_event_hook = (rl_hook_func_t *)NULL;
80
81 rl_getc_func_t *rl_getc_function = rl_getc;
82
83 static int _keyboard_input_timeout = 100000;            /* 0.1 seconds; it's in usec */
84
85 static int ibuffer_space PARAMS((void));
86 static int rl_get_char PARAMS((int *));
87 static int rl_gather_tyi PARAMS((void));
88
89 /* **************************************************************** */
90 /*                                                                  */
91 /*                      Character Input Buffering                   */
92 /*                                                                  */
93 /* **************************************************************** */
94
95 static int pop_index, push_index;
96 static unsigned char ibuffer[512];
97 static int ibuffer_len = sizeof (ibuffer) - 1;
98
99 #define any_typein (push_index != pop_index)
100
101 int
102 _rl_any_typein ()
103 {
104   return any_typein;
105 }
106
107 /* Return the amount of space available in the buffer for stuffing
108    characters. */
109 static int
110 ibuffer_space ()
111 {
112   if (pop_index > push_index)
113     return (pop_index - push_index - 1);
114   else
115     return (ibuffer_len - (push_index - pop_index));
116 }
117
118 /* Get a key from the buffer of characters to be read.
119    Return the key in KEY.
120    Result is KEY if there was a key, or 0 if there wasn't. */
121 static int
122 rl_get_char (key)
123      int *key;
124 {
125   if (push_index == pop_index)
126     return (0);
127
128   *key = ibuffer[pop_index++];
129 #if 0
130   if (pop_index >= ibuffer_len)
131 #else
132   if (pop_index > ibuffer_len)
133 #endif
134     pop_index = 0;
135
136   return (1);
137 }
138
139 /* Stuff KEY into the *front* of the input buffer.
140    Returns non-zero if successful, zero if there is
141    no space left in the buffer. */
142 int
143 _rl_unget_char (key)
144      int key;
145 {
146   if (ibuffer_space ())
147     {
148       pop_index--;
149       if (pop_index < 0)
150         pop_index = ibuffer_len;
151       ibuffer[pop_index] = key;
152       return (1);
153     }
154   return (0);
155 }
156
157 int
158 _rl_pushed_input_available ()
159 {
160   return (push_index != pop_index);
161 }
162
163 /* If a character is available to be read, then read it and stuff it into
164    IBUFFER.  Otherwise, just return.  Returns number of characters read
165    (0 if none available) and -1 on error (EIO). */
166 static int
167 rl_gather_tyi ()
168 {
169   int tty;
170   register int tem, result;
171   int chars_avail, k;
172   char input;
173 #if defined(HAVE_SELECT)
174   fd_set readfds, exceptfds;
175   struct timeval timeout;
176 #endif
177
178   chars_avail = 0;
179   tty = fileno (rl_instream);
180
181 #if defined (HAVE_SELECT)
182   FD_ZERO (&readfds);
183   FD_ZERO (&exceptfds);
184   FD_SET (tty, &readfds);
185   FD_SET (tty, &exceptfds);
186   USEC_TO_TIMEVAL (_keyboard_input_timeout, timeout);
187   result = select (tty + 1, &readfds, (fd_set *)NULL, &exceptfds, &timeout);
188   if (result <= 0)
189     return 0;   /* Nothing to read. */
190 #endif
191
192   result = -1;
193 #if defined (FIONREAD)
194   errno = 0;
195   result = ioctl (tty, FIONREAD, &chars_avail);
196   if (result == -1 && errno == EIO)
197     return -1;
198 #endif
199
200 #if defined (O_NDELAY)
201   if (result == -1)
202     {
203       tem = fcntl (tty, F_GETFL, 0);
204
205       fcntl (tty, F_SETFL, (tem | O_NDELAY));
206       chars_avail = read (tty, &input, 1);
207
208       fcntl (tty, F_SETFL, tem);
209       if (chars_avail == -1 && errno == EAGAIN)
210         return 0;
211       if (chars_avail == 0)     /* EOF */
212         {
213           rl_stuff_char (EOF);
214           return (0);
215         }
216     }
217 #endif /* O_NDELAY */
218
219 #if defined (__MINGW32__)
220   /* Use getch/_kbhit to check for available console input, in the same way
221      that we read it normally. */
222    chars_avail = isatty (tty) ? _kbhit () : 0;
223    result = 0;
224 #endif
225
226   /* If there's nothing available, don't waste time trying to read
227      something. */
228   if (chars_avail <= 0)
229     return 0;
230
231   tem = ibuffer_space ();
232
233   if (chars_avail > tem)
234     chars_avail = tem;
235
236   /* One cannot read all of the available input.  I can only read a single
237      character at a time, or else programs which require input can be
238      thwarted.  If the buffer is larger than one character, I lose.
239      Damn! */
240   if (tem < ibuffer_len)
241     chars_avail = 0;
242
243   if (result != -1)
244     {
245       while (chars_avail--)
246         {
247           RL_CHECK_SIGNALS ();
248           k = (*rl_getc_function) (rl_instream);
249           if (rl_stuff_char (k) == 0)
250             break;                      /* some problem; no more room */
251           if (k == NEWLINE || k == RETURN)
252             break;
253         }
254     }
255   else
256     {
257       if (chars_avail)
258         rl_stuff_char (input);
259     }
260
261   return 1;
262 }
263
264 int
265 rl_set_keyboard_input_timeout (u)
266      int u;
267 {
268   int o;
269
270   o = _keyboard_input_timeout;
271   if (u >= 0)
272     _keyboard_input_timeout = u;
273   return (o);
274 }
275
276 /* Is there input available to be read on the readline input file
277    descriptor?  Only works if the system has select(2) or FIONREAD.
278    Uses the value of _keyboard_input_timeout as the timeout; if another
279    readline function wants to specify a timeout and not leave it up to
280    the user, it should use _rl_input_queued(timeout_value_in_microseconds)
281    instead. */
282 int
283 _rl_input_available ()
284 {
285 #if defined(HAVE_SELECT)
286   fd_set readfds, exceptfds;
287   struct timeval timeout;
288 #endif
289 #if !defined (HAVE_SELECT) && defined(FIONREAD)
290   int chars_avail;
291 #endif
292   int tty;
293
294   tty = fileno (rl_instream);
295
296 #if defined (HAVE_SELECT)
297   FD_ZERO (&readfds);
298   FD_ZERO (&exceptfds);
299   FD_SET (tty, &readfds);
300   FD_SET (tty, &exceptfds);
301   timeout.tv_sec = 0;
302   timeout.tv_usec = _keyboard_input_timeout;
303   return (select (tty + 1, &readfds, (fd_set *)NULL, &exceptfds, &timeout) > 0);
304 #else
305
306 #if defined (FIONREAD)
307   if (ioctl (tty, FIONREAD, &chars_avail) == 0)
308     return (chars_avail);
309 #endif
310
311 #endif
312
313 #if defined (__MINGW32__)
314   if (isatty (tty))
315     return (_kbhit ());
316 #endif
317
318   return 0;
319 }
320
321 int
322 _rl_input_queued (t)
323      int t;
324 {
325   int old_timeout, r;
326
327   old_timeout = rl_set_keyboard_input_timeout (t);
328   r = _rl_input_available ();
329   rl_set_keyboard_input_timeout (old_timeout);
330   return r;
331 }
332
333 void
334 _rl_insert_typein (c)
335      int c;     
336 {       
337   int key, t, i;
338   char *string;
339
340   i = key = 0;
341   string = (char *)xmalloc (ibuffer_len + 1);
342   string[i++] = (char) c;
343
344   while ((t = rl_get_char (&key)) &&
345          _rl_keymap[key].type == ISFUNC &&
346          _rl_keymap[key].function == rl_insert)
347     string[i++] = key;
348
349   if (t)
350     _rl_unget_char (key);
351
352   string[i] = '\0';
353   rl_insert_text (string);
354   xfree (string);
355 }
356
357 /* Add KEY to the buffer of characters to be read.  Returns 1 if the
358    character was stuffed correctly; 0 otherwise. */
359 int
360 rl_stuff_char (key)
361      int key;
362 {
363   if (ibuffer_space () == 0)
364     return 0;
365
366   if (key == EOF)
367     {
368       key = NEWLINE;
369       rl_pending_input = EOF;
370       RL_SETSTATE (RL_STATE_INPUTPENDING);
371     }
372   ibuffer[push_index++] = key;
373 #if 0
374   if (push_index >= ibuffer_len)
375 #else
376   if (push_index > ibuffer_len)
377 #endif
378     push_index = 0;
379
380   return 1;
381 }
382
383 /* Make C be the next command to be executed. */
384 int
385 rl_execute_next (c)
386      int c;
387 {
388   rl_pending_input = c;
389   RL_SETSTATE (RL_STATE_INPUTPENDING);
390   return 0;
391 }
392
393 /* Clear any pending input pushed with rl_execute_next() */
394 int
395 rl_clear_pending_input ()
396 {
397   rl_pending_input = 0;
398   RL_UNSETSTATE (RL_STATE_INPUTPENDING);
399   return 0;
400 }
401
402 /* **************************************************************** */
403 /*                                                                  */
404 /*                           Character Input                        */
405 /*                                                                  */
406 /* **************************************************************** */
407
408 /* Read a key, including pending input. */
409 int
410 rl_read_key ()
411 {
412   int c, r;
413
414   rl_key_sequence_length++;
415
416   if (rl_pending_input)
417     {
418       c = rl_pending_input;
419       rl_clear_pending_input ();
420     }
421   else
422     {
423       /* If input is coming from a macro, then use that. */
424       if (c = _rl_next_macro_key ())
425         return (c);
426
427       /* If the user has an event function, then call it periodically. */
428       if (rl_event_hook)
429         {
430           while (rl_event_hook)
431             {
432               if (rl_get_char (&c) != 0)
433                 break;
434                 
435               if ((r = rl_gather_tyi ()) < 0)   /* XXX - EIO */
436                 {
437                   rl_done = 1;
438                   return ('\n');
439                 }
440               else if (r == 1)                  /* read something */
441                 continue;
442
443               RL_CHECK_SIGNALS ();
444               if (rl_done)              /* XXX - experimental */
445                 return ('\n');
446               (*rl_event_hook) ();
447             }
448         }
449       else
450         {
451           if (rl_get_char (&c) == 0)
452             c = (*rl_getc_function) (rl_instream);
453           RL_CHECK_SIGNALS ();
454         }
455     }
456
457   return (c);
458 }
459
460 int
461 rl_getc (stream)
462      FILE *stream;
463 {
464   int result;
465   unsigned char c;
466
467   while (1)
468     {
469       RL_CHECK_SIGNALS ();
470
471 #if defined (__MINGW32__)
472       if (isatty (fileno (stream)))
473         return (getch ());
474 #endif
475       result = read (fileno (stream), &c, sizeof (unsigned char));
476
477       if (result == sizeof (unsigned char))
478         return (c);
479
480       /* If zero characters are returned, then the file that we are
481          reading from is empty!  Return EOF in that case. */
482       if (result == 0)
483         return (EOF);
484
485 #if defined (__BEOS__)
486       if (errno == EINTR)
487         continue;
488 #endif
489
490 #if defined (EWOULDBLOCK)
491 #  define X_EWOULDBLOCK EWOULDBLOCK
492 #else
493 #  define X_EWOULDBLOCK -99
494 #endif
495
496 #if defined (EAGAIN)
497 #  define X_EAGAIN EAGAIN
498 #else
499 #  define X_EAGAIN -99
500 #endif
501
502       if (errno == X_EWOULDBLOCK || errno == X_EAGAIN)
503         {
504           if (sh_unset_nodelay_mode (fileno (stream)) < 0)
505             return (EOF);
506           continue;
507         }
508
509 #undef X_EWOULDBLOCK
510 #undef X_EAGAIN
511
512       /* If the error that we received was SIGINT, then try again,
513          this is simply an interrupted system call to read ().
514          Otherwise, some error ocurred, also signifying EOF. */
515       if (errno != EINTR)
516         return (RL_ISSTATE (RL_STATE_READCMD) ? READERR : EOF);
517     }
518 }
519
520 #if defined (HANDLE_MULTIBYTE)
521 /* read multibyte char */
522 int
523 _rl_read_mbchar (mbchar, size)
524      char *mbchar;
525      int size;
526 {
527   int mb_len, c;
528   size_t mbchar_bytes_length;
529   wchar_t wc;
530   mbstate_t ps, ps_back;
531
532   memset(&ps, 0, sizeof (mbstate_t));
533   memset(&ps_back, 0, sizeof (mbstate_t));
534
535   mb_len = 0;  
536   while (mb_len < size)
537     {
538       RL_SETSTATE(RL_STATE_MOREINPUT);
539       c = rl_read_key ();
540       RL_UNSETSTATE(RL_STATE_MOREINPUT);
541
542       if (c < 0)
543         break;
544
545       mbchar[mb_len++] = c;
546
547       mbchar_bytes_length = mbrtowc (&wc, mbchar, mb_len, &ps);
548       if (mbchar_bytes_length == (size_t)(-1))
549         break;          /* invalid byte sequence for the current locale */
550       else if (mbchar_bytes_length == (size_t)(-2))
551         {
552           /* shorted bytes */
553           ps = ps_back;
554           continue;
555         } 
556       else if (mbchar_bytes_length == 0)
557         {
558           mbchar[0] = '\0';     /* null wide character */
559           mb_len = 1;
560           break;
561         }
562       else if (mbchar_bytes_length > (size_t)(0))
563         break;
564     }
565
566   return mb_len;
567 }
568
569 /* Read a multibyte-character string whose first character is FIRST into
570    the buffer MB of length MLEN.  Returns the last character read, which
571    may be FIRST.  Used by the search functions, among others.  Very similar
572    to _rl_read_mbchar. */
573 int
574 _rl_read_mbstring (first, mb, mlen)
575      int first;
576      char *mb;
577      int mlen;
578 {
579   int i, c;
580   mbstate_t ps;
581
582   c = first;
583   memset (mb, 0, mlen);
584   for (i = 0; c >= 0 && i < mlen; i++)
585     {
586       mb[i] = (char)c;
587       memset (&ps, 0, sizeof (mbstate_t));
588       if (_rl_get_char_len (mb, &ps) == -2)
589         {
590           /* Read more for multibyte character */
591           RL_SETSTATE (RL_STATE_MOREINPUT);
592           c = rl_read_key ();
593           RL_UNSETSTATE (RL_STATE_MOREINPUT);
594         }
595       else
596         break;
597     }
598   return c;
599 }
600 #endif /* HANDLE_MULTIBYTE */