/*1* Copyright (c) 20012* The President and Fellows of Harvard College.3*4* Redistribution and use in source and binary forms, with or without5* modification, are permitted provided that the following conditions6* are met:7* 1. Redistributions of source code must retain the above copyright8* notice, this list of conditions and the following disclaimer.9* 2. Redistributions in binary form must reproduce the above copyright10* notice, this list of conditions and the following disclaimer in the11* documentation and/or other materials provided with the distribution.12* 3. Neither the name of the University nor the names of its contributors13* may be used to endorse or promote products derived from this software14* without specific prior written permission.15*16* THIS SOFTWARE IS PROVIDED BY THE UNIVERSITY AND CONTRIBUTORS ``AS IS'' AND17* ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE18* IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE19* ARE DISCLAIMED. IN NO EVENT SHALL THE UNIVERSITY OR CONTRIBUTORS BE LIABLE20* FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL21* DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS22* OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION)23* HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT24* LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY25* OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF26* SUCH DAMAGE.27*/282930#include <types.h>31#include <lib.h>3233/*34* Do a backspace in typed input.35* We overwrite the current character with a space in case we're on36* a terminal where backspace is nondestructive.37*/38static39void40backsp(void)41{42putch('\b');43putch(' ');44putch('\b');45}4647/*48* Read a string off the console. Support a few of the more useful49* common control characters. Do not include the terminating newline50* in the buffer passed back.51*/52void53kgets(char *buf, size_t maxlen)54{55size_t pos = 0;56int ch;5758while (1) {59ch = getch();60if (ch=='\n' || ch=='\r') {61putch('\n');62break;63}6465/* Only allow the normal 7-bit ascii */66if (ch>=32 && ch<127 && pos < maxlen-1) {67putch(ch);68buf[pos++] = ch;69}70else if ((ch=='\b' || ch==127) && pos>0) {71/* backspace */72backsp();73pos--;74}75else if (ch==3) {76/* ^C - return empty string */77putch('^');78putch('C');79putch('\n');80pos = 0;81break;82}83else if (ch==18) {84/* ^R - reprint input */85buf[pos] = 0;86kprintf("^R\n%s", buf);87}88else if (ch==21) {89/* ^U - erase line */90while (pos > 0) {91backsp();92pos--;93}94}95else if (ch==23) {96/* ^W - erase word */97while (pos > 0 && buf[pos-1]==' ') {98backsp();99pos--;100}101while (pos > 0 && buf[pos-1]!=' ') {102backsp();103pos--;104}105}106else {107beep();108}109}110111buf[pos] = 0;112}113114115