lineedit.c 73 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959960961962963964965966967968969970971972973974975976977978979980981982983984985986987988989990991992993994995996997998999100010011002100310041005100610071008100910101011101210131014101510161017101810191020102110221023102410251026102710281029103010311032103310341035103610371038103910401041104210431044104510461047104810491050105110521053105410551056105710581059106010611062106310641065106610671068106910701071107210731074107510761077107810791080108110821083108410851086108710881089109010911092109310941095109610971098109911001101110211031104110511061107110811091110111111121113111411151116111711181119112011211122112311241125112611271128112911301131113211331134113511361137113811391140114111421143114411451146114711481149115011511152115311541155115611571158115911601161116211631164116511661167116811691170117111721173117411751176117711781179118011811182118311841185118611871188118911901191119211931194119511961197119811991200120112021203120412051206120712081209121012111212121312141215121612171218121912201221122212231224122512261227122812291230123112321233123412351236123712381239124012411242124312441245124612471248124912501251125212531254125512561257125812591260126112621263126412651266126712681269127012711272127312741275127612771278127912801281128212831284128512861287128812891290129112921293129412951296129712981299130013011302130313041305130613071308130913101311131213131314131513161317131813191320132113221323132413251326132713281329133013311332133313341335133613371338133913401341134213431344134513461347134813491350135113521353135413551356135713581359136013611362136313641365136613671368136913701371137213731374137513761377137813791380138113821383138413851386138713881389139013911392139313941395139613971398139914001401140214031404140514061407140814091410141114121413141414151416141714181419142014211422142314241425142614271428142914301431143214331434143514361437143814391440144114421443144414451446144714481449145014511452145314541455145614571458145914601461146214631464146514661467146814691470147114721473147414751476147714781479148014811482148314841485148614871488148914901491149214931494149514961497149814991500150115021503150415051506150715081509151015111512151315141515151615171518151915201521152215231524152515261527152815291530153115321533153415351536153715381539154015411542154315441545154615471548154915501551155215531554155515561557155815591560156115621563156415651566156715681569157015711572157315741575157615771578157915801581158215831584158515861587158815891590159115921593159415951596159715981599160016011602160316041605160616071608160916101611161216131614161516161617161816191620162116221623162416251626162716281629163016311632163316341635163616371638163916401641164216431644164516461647164816491650165116521653165416551656165716581659166016611662166316641665166616671668166916701671167216731674167516761677167816791680168116821683168416851686168716881689169016911692169316941695169616971698169917001701170217031704170517061707170817091710171117121713171417151716171717181719172017211722172317241725172617271728172917301731173217331734173517361737173817391740174117421743174417451746174717481749175017511752175317541755175617571758175917601761176217631764176517661767176817691770177117721773177417751776177717781779178017811782178317841785178617871788178917901791179217931794179517961797179817991800180118021803180418051806180718081809181018111812181318141815181618171818181918201821182218231824182518261827182818291830183118321833183418351836183718381839184018411842184318441845184618471848184918501851185218531854185518561857185818591860186118621863186418651866186718681869187018711872187318741875187618771878187918801881188218831884188518861887188818891890189118921893189418951896189718981899190019011902190319041905190619071908190919101911191219131914191519161917191819191920192119221923192419251926192719281929193019311932193319341935193619371938193919401941194219431944194519461947194819491950195119521953195419551956195719581959196019611962196319641965196619671968196919701971197219731974197519761977197819791980198119821983198419851986198719881989199019911992199319941995199619971998199920002001200220032004200520062007200820092010201120122013201420152016201720182019202020212022202320242025202620272028202920302031203220332034203520362037203820392040204120422043204420452046204720482049205020512052205320542055205620572058205920602061206220632064206520662067206820692070207120722073207420752076207720782079208020812082208320842085208620872088208920902091209220932094209520962097209820992100210121022103210421052106210721082109211021112112211321142115211621172118211921202121212221232124212521262127212821292130213121322133213421352136213721382139214021412142214321442145214621472148214921502151215221532154215521562157215821592160216121622163216421652166216721682169217021712172217321742175217621772178217921802181218221832184218521862187218821892190219121922193219421952196219721982199220022012202220322042205220622072208220922102211221222132214221522162217221822192220222122222223222422252226222722282229223022312232223322342235223622372238223922402241224222432244224522462247224822492250225122522253225422552256225722582259226022612262226322642265226622672268226922702271227222732274227522762277227822792280228122822283228422852286228722882289229022912292229322942295229622972298229923002301230223032304230523062307230823092310231123122313231423152316231723182319232023212322232323242325232623272328232923302331233223332334233523362337233823392340234123422343234423452346234723482349235023512352235323542355235623572358235923602361236223632364236523662367236823692370237123722373237423752376237723782379238023812382238323842385238623872388238923902391239223932394239523962397239823992400240124022403240424052406240724082409241024112412241324142415241624172418241924202421242224232424242524262427242824292430243124322433243424352436243724382439244024412442244324442445244624472448244924502451245224532454245524562457245824592460246124622463246424652466246724682469247024712472247324742475247624772478247924802481248224832484248524862487248824892490249124922493249424952496249724982499250025012502250325042505250625072508250925102511251225132514251525162517251825192520252125222523252425252526252725282529253025312532253325342535253625372538253925402541254225432544254525462547254825492550255125522553255425552556255725582559256025612562256325642565256625672568256925702571257225732574257525762577257825792580258125822583258425852586258725882589259025912592259325942595259625972598259926002601260226032604260526062607260826092610261126122613261426152616261726182619262026212622262326242625262626272628262926302631263226332634263526362637263826392640264126422643264426452646264726482649265026512652265326542655265626572658265926602661266226632664266526662667266826692670267126722673267426752676267726782679268026812682268326842685268626872688268926902691269226932694269526962697269826992700270127022703270427052706270727082709271027112712271327142715271627172718271927202721272227232724272527262727272827292730273127322733273427352736273727382739274027412742274327442745274627472748274927502751275227532754275527562757275827592760276127622763276427652766276727682769277027712772277327742775277627772778277927802781278227832784278527862787278827892790279127922793279427952796279727982799280028012802280328042805280628072808280928102811281228132814281528162817281828192820282128222823282428252826282728282829283028312832283328342835283628372838283928402841284228432844284528462847284828492850285128522853285428552856285728582859286028612862286328642865286628672868286928702871287228732874287528762877287828792880288128822883288428852886288728882889289028912892289328942895289628972898289929002901290229032904290529062907290829092910291129122913291429152916291729182919292029212922292329242925292629272928292929302931293229332934293529362937293829392940294129422943294429452946294729482949295029512952295329542955
  1. /* vi: set sw=4 ts=4: */
  2. /*
  3. * Command line editing.
  4. *
  5. * Copyright (c) 1986-2003 may safely be consumed by a BSD or GPL license.
  6. * Written by: Vladimir Oleynik <dzo@simtreas.ru>
  7. *
  8. * Used ideas:
  9. * Adam Rogoyski <rogoyski@cs.utexas.edu>
  10. * Dave Cinege <dcinege@psychosis.com>
  11. * Jakub Jelinek (c) 1995
  12. * Erik Andersen <andersen@codepoet.org> (Majorly adjusted for busybox)
  13. *
  14. * This code is 'as is' with no warranty.
  15. */
  16. /*
  17. * Usage and known bugs:
  18. * Terminal key codes are not extensive, more needs to be added.
  19. * This version was created on Debian GNU/Linux 2.x.
  20. * Delete, Backspace, Home, End, and the arrow keys were tested
  21. * to work in an Xterm and console. Ctrl-A also works as Home.
  22. * Ctrl-E also works as End.
  23. *
  24. * The following readline-like commands are not implemented:
  25. * CTL-t -- Transpose two characters
  26. *
  27. * lineedit does not know that the terminal escape sequences do not
  28. * take up space on the screen. The redisplay code assumes, unless
  29. * told otherwise, that each character in the prompt is a printable
  30. * character that takes up one character position on the screen.
  31. * You need to tell lineedit that some sequences of characters
  32. * in the prompt take up no screen space. Compatibly with readline,
  33. * use the \[ escape to begin a sequence of non-printing characters,
  34. * and the \] escape to signal the end of such a sequence. Example:
  35. *
  36. * PS1='\[\033[01;32m\]\u@\h\[\033[01;34m\] \w \$\[\033[00m\] '
  37. *
  38. * Unicode in PS1 is not fully supported: prompt length calulation is wrong,
  39. * resulting in line wrap problems with long (multi-line) input.
  40. */
  41. #include "busybox.h"
  42. #include "NUM_APPLETS.h"
  43. #include "unicode.h"
  44. #ifndef _POSIX_VDISABLE
  45. # define _POSIX_VDISABLE '\0'
  46. #endif
  47. #ifdef TEST
  48. # define ENABLE_FEATURE_EDITING 0
  49. # define ENABLE_FEATURE_TAB_COMPLETION 0
  50. # define ENABLE_FEATURE_USERNAME_COMPLETION 0
  51. #endif
  52. /* Entire file (except TESTing part) sits inside this #if */
  53. #if ENABLE_FEATURE_EDITING
  54. #define ENABLE_USERNAME_OR_HOMEDIR \
  55. (ENABLE_FEATURE_USERNAME_COMPLETION || ENABLE_FEATURE_EDITING_FANCY_PROMPT)
  56. #define IF_USERNAME_OR_HOMEDIR(...)
  57. #if ENABLE_USERNAME_OR_HOMEDIR
  58. # undef IF_USERNAME_OR_HOMEDIR
  59. # define IF_USERNAME_OR_HOMEDIR(...) __VA_ARGS__
  60. #endif
  61. #undef CHAR_T
  62. #if ENABLE_UNICODE_SUPPORT
  63. # define BB_NUL ((wchar_t)0)
  64. # define CHAR_T wchar_t
  65. static bool BB_isspace(CHAR_T c) { return ((unsigned)c < 256 && isspace(c)); }
  66. # if ENABLE_FEATURE_EDITING_VI
  67. static bool BB_isalnum_or_underscore(CHAR_T c) {
  68. return ((unsigned)c < 256 && isalnum(c)) || c == '_';
  69. }
  70. # endif
  71. static bool BB_ispunct(CHAR_T c) { return ((unsigned)c < 256 && ispunct(c)); }
  72. # undef isspace
  73. # undef isalnum
  74. # undef ispunct
  75. # undef isprint
  76. # define isspace isspace_must_not_be_used
  77. # define isalnum isalnum_must_not_be_used
  78. # define ispunct ispunct_must_not_be_used
  79. # define isprint isprint_must_not_be_used
  80. #else
  81. # define BB_NUL '\0'
  82. # define CHAR_T char
  83. # define BB_isspace(c) isspace(c)
  84. # if ENABLE_FEATURE_EDITING_VI
  85. static bool BB_isalnum_or_underscore(CHAR_T c)
  86. {
  87. return ((unsigned)c < 256 && isalnum(c)) || c == '_';
  88. }
  89. # endif
  90. # define BB_ispunct(c) ispunct(c)
  91. #endif
  92. #if ENABLE_UNICODE_PRESERVE_BROKEN
  93. # define unicode_mark_raw_byte(wc) ((wc) | 0x20000000)
  94. # define unicode_is_raw_byte(wc) ((wc) & 0x20000000)
  95. #else
  96. # define unicode_is_raw_byte(wc) 0
  97. #endif
  98. #define ESC "\033"
  99. #define SEQ_CLEAR_TILL_END_OF_SCREEN ESC"[J"
  100. //#define SEQ_CLEAR_TILL_END_OF_LINE ESC"[K"
  101. enum {
  102. MAX_LINELEN = CONFIG_FEATURE_EDITING_MAX_LEN < 0x7ff0
  103. ? CONFIG_FEATURE_EDITING_MAX_LEN
  104. : 0x7ff0
  105. };
  106. #if ENABLE_USERNAME_OR_HOMEDIR
  107. static const char null_str[] ALIGN1 = "";
  108. #endif
  109. /* We try to minimize both static and stack usage. */
  110. struct lineedit_statics {
  111. line_input_t *state;
  112. unsigned cmdedit_termw; /* = 80; */ /* actual terminal width */
  113. unsigned cmdedit_x; /* real x (col) terminal position */
  114. unsigned cmdedit_y; /* pseudoreal y (row) terminal position */
  115. unsigned cmdedit_prmt_len; /* on-screen length of last/sole prompt line */
  116. unsigned cursor;
  117. int command_len; /* must be signed */
  118. /* signed maxsize: we want x in "if (x > S.maxsize)"
  119. * to _not_ be promoted to unsigned */
  120. int maxsize;
  121. CHAR_T *command_ps;
  122. const char *cmdedit_prompt;
  123. const char *prompt_last_line; /* last/sole prompt line */
  124. #if ENABLE_USERNAME_OR_HOMEDIR
  125. char *user_buf;
  126. char *home_pwd_buf; /* = (char*)null_str; */
  127. #endif
  128. #if ENABLE_FEATURE_TAB_COMPLETION
  129. char **matches;
  130. unsigned num_matches;
  131. #endif
  132. #if ENABLE_FEATURE_EDITING_WINCH
  133. unsigned SIGWINCH_saved;
  134. volatile unsigned SIGWINCH_count;
  135. volatile smallint ok_to_redraw;
  136. #endif
  137. #if ENABLE_FEATURE_EDITING_VI
  138. # define DELBUFSIZ 128
  139. smallint newdelflag; /* whether delbuf should be reused yet */
  140. CHAR_T *delptr;
  141. CHAR_T delbuf[DELBUFSIZ]; /* a place to store deleted characters */
  142. #endif
  143. #if ENABLE_FEATURE_EDITING_ASK_TERMINAL
  144. smallint sent_ESC_br6n;
  145. #endif
  146. #if ENABLE_FEATURE_EDITING_WINCH
  147. /* Largish struct, keeping it last results in smaller code */
  148. struct sigaction SIGWINCH_handler;
  149. #endif
  150. };
  151. /* See lineedit_ptr_hack.c */
  152. extern struct lineedit_statics *const lineedit_ptr_to_statics;
  153. #define S (*lineedit_ptr_to_statics)
  154. #define state (S.state )
  155. #define cmdedit_termw (S.cmdedit_termw )
  156. #define cmdedit_x (S.cmdedit_x )
  157. #define cmdedit_y (S.cmdedit_y )
  158. #define cmdedit_prmt_len (S.cmdedit_prmt_len)
  159. #define cursor (S.cursor )
  160. #define command_len (S.command_len )
  161. #define command_ps (S.command_ps )
  162. #define cmdedit_prompt (S.cmdedit_prompt )
  163. #define prompt_last_line (S.prompt_last_line)
  164. #define user_buf (S.user_buf )
  165. #define home_pwd_buf (S.home_pwd_buf )
  166. #define matches (S.matches )
  167. #define num_matches (S.num_matches )
  168. #define delptr (S.delptr )
  169. #define newdelflag (S.newdelflag )
  170. #define delbuf (S.delbuf )
  171. #define INIT_S() do { \
  172. (*(struct lineedit_statics**)&lineedit_ptr_to_statics) = xzalloc(sizeof(S)); \
  173. barrier(); \
  174. cmdedit_termw = 80; \
  175. IF_USERNAME_OR_HOMEDIR(home_pwd_buf = (char*)null_str;) \
  176. IF_FEATURE_EDITING_VI(delptr = delbuf;) \
  177. } while (0)
  178. static void deinit_S(void)
  179. {
  180. #if ENABLE_FEATURE_EDITING_FANCY_PROMPT
  181. /* This one is allocated only if FANCY_PROMPT is on
  182. * (otherwise it points to verbatim prompt (NOT malloced)) */
  183. free((char*)cmdedit_prompt);
  184. #endif
  185. #if ENABLE_USERNAME_OR_HOMEDIR
  186. free(user_buf);
  187. if (home_pwd_buf != null_str)
  188. free(home_pwd_buf);
  189. #endif
  190. free(lineedit_ptr_to_statics);
  191. }
  192. #define DEINIT_S() deinit_S()
  193. #if ENABLE_UNICODE_SUPPORT
  194. static size_t load_string(const char *src)
  195. {
  196. if (unicode_status == UNICODE_ON) {
  197. ssize_t len = mbstowcs(command_ps, src, S.maxsize - 1);
  198. if (len < 0)
  199. len = 0;
  200. command_ps[len] = BB_NUL;
  201. return len;
  202. } else {
  203. unsigned i = 0;
  204. while (src[i] && i < S.maxsize - 1) {
  205. command_ps[i] = src[i];
  206. i++;
  207. }
  208. command_ps[i] = BB_NUL;
  209. return i;
  210. }
  211. }
  212. static unsigned save_string(char *dst, unsigned maxsize)
  213. {
  214. if (unicode_status == UNICODE_ON) {
  215. # if !ENABLE_UNICODE_PRESERVE_BROKEN
  216. ssize_t len = wcstombs(dst, command_ps, maxsize - 1);
  217. if (len < 0)
  218. len = 0;
  219. dst[len] = '\0';
  220. return len;
  221. # else
  222. unsigned dstpos = 0;
  223. unsigned srcpos = 0;
  224. maxsize--;
  225. while (dstpos < maxsize) {
  226. wchar_t wc;
  227. int n = srcpos;
  228. /* Convert up to 1st invalid byte (or up to end) */
  229. while ((wc = command_ps[srcpos]) != BB_NUL
  230. && !unicode_is_raw_byte(wc)
  231. ) {
  232. srcpos++;
  233. }
  234. command_ps[srcpos] = BB_NUL;
  235. n = wcstombs(dst + dstpos, command_ps + n, maxsize - dstpos);
  236. if (n < 0) /* should not happen */
  237. break;
  238. dstpos += n;
  239. if (wc == BB_NUL) /* usually is */
  240. break;
  241. /* We do have invalid byte here! */
  242. command_ps[srcpos] = wc; /* restore it */
  243. srcpos++;
  244. if (dstpos == maxsize)
  245. break;
  246. dst[dstpos++] = (char) wc;
  247. }
  248. dst[dstpos] = '\0';
  249. return dstpos;
  250. # endif
  251. } else {
  252. unsigned i = 0;
  253. while ((dst[i] = command_ps[i]) != 0)
  254. i++;
  255. return i;
  256. }
  257. }
  258. /* I thought just fputwc(c, stdout) would work. But no... */
  259. static void BB_PUTCHAR(wchar_t c)
  260. {
  261. if (unicode_status == UNICODE_ON) {
  262. char buf[MB_CUR_MAX + 1];
  263. mbstate_t mbst = { 0 };
  264. ssize_t len = wcrtomb(buf, c, &mbst);
  265. if (len > 0) {
  266. buf[len] = '\0';
  267. fputs(buf, stdout);
  268. }
  269. } else {
  270. /* In this case, c is always one byte */
  271. putchar(c);
  272. }
  273. }
  274. # if ENABLE_UNICODE_COMBINING_WCHARS || ENABLE_UNICODE_WIDE_WCHARS
  275. static wchar_t adjust_width_and_validate_wc(unsigned *width_adj, wchar_t wc)
  276. # else
  277. static wchar_t adjust_width_and_validate_wc(wchar_t wc)
  278. # define adjust_width_and_validate_wc(width_adj, wc) \
  279. ((*(width_adj))++, adjust_width_and_validate_wc(wc))
  280. # endif
  281. {
  282. int w = 1;
  283. if (unicode_status == UNICODE_ON) {
  284. if (wc > CONFIG_LAST_SUPPORTED_WCHAR) {
  285. /* note: also true for unicode_is_raw_byte(wc) */
  286. goto subst;
  287. }
  288. w = wcwidth(wc);
  289. if ((ENABLE_UNICODE_COMBINING_WCHARS && w < 0)
  290. || (!ENABLE_UNICODE_COMBINING_WCHARS && w <= 0)
  291. || (!ENABLE_UNICODE_WIDE_WCHARS && w > 1)
  292. ) {
  293. subst:
  294. w = 1;
  295. wc = CONFIG_SUBST_WCHAR;
  296. }
  297. }
  298. # if ENABLE_UNICODE_COMBINING_WCHARS || ENABLE_UNICODE_WIDE_WCHARS
  299. *width_adj += w;
  300. #endif
  301. return wc;
  302. }
  303. #else /* !UNICODE */
  304. static size_t load_string(const char *src)
  305. {
  306. safe_strncpy(command_ps, src, S.maxsize);
  307. return strlen(command_ps);
  308. }
  309. # if ENABLE_FEATURE_TAB_COMPLETION
  310. static void save_string(char *dst, unsigned maxsize)
  311. {
  312. safe_strncpy(dst, command_ps, maxsize);
  313. }
  314. # endif
  315. # define BB_PUTCHAR(c) bb_putchar(c)
  316. /* Should never be called: */
  317. int adjust_width_and_validate_wc(unsigned *width_adj, int wc);
  318. #endif
  319. /* Put 'command_ps[cursor]', cursor++.
  320. * Advance cursor on screen. If we reached right margin, scroll text up
  321. * and remove terminal margin effect by printing 'next_char' */
  322. #define HACK_FOR_WRONG_WIDTH 1
  323. static void put_cur_glyph_and_inc_cursor(void)
  324. {
  325. CHAR_T c = command_ps[cursor];
  326. unsigned width = 0;
  327. int ofs_to_right;
  328. if (c == BB_NUL) {
  329. /* erase character after end of input string */
  330. c = ' ';
  331. } else {
  332. /* advance cursor only if we aren't at the end yet */
  333. cursor++;
  334. if (unicode_status == UNICODE_ON) {
  335. IF_UNICODE_WIDE_WCHARS(width = cmdedit_x;)
  336. c = adjust_width_and_validate_wc(&cmdedit_x, c);
  337. IF_UNICODE_WIDE_WCHARS(width = cmdedit_x - width;)
  338. } else {
  339. cmdedit_x++;
  340. }
  341. }
  342. ofs_to_right = cmdedit_x - cmdedit_termw;
  343. if (!ENABLE_UNICODE_WIDE_WCHARS || ofs_to_right <= 0) {
  344. /* c fits on this line */
  345. BB_PUTCHAR(c);
  346. }
  347. if (ofs_to_right >= 0) {
  348. /* we go to the next line */
  349. #if HACK_FOR_WRONG_WIDTH
  350. /* This works better if our idea of term width is wrong
  351. * and it is actually wider (often happens on serial lines).
  352. * Printing CR,LF *forces* cursor to next line.
  353. * OTOH if terminal width is correct AND terminal does NOT
  354. * have automargin (IOW: it is moving cursor to next line
  355. * by itself (which is wrong for VT-10x terminals)),
  356. * this will break things: there will be one extra empty line */
  357. puts("\r"); /* + implicit '\n' */
  358. #else
  359. /* VT-10x terminals don't wrap cursor to next line when last char
  360. * on the line is printed - cursor stays "over" this char.
  361. * Need to print _next_ char too (first one to appear on next line)
  362. * to make cursor move down to next line.
  363. */
  364. /* Works ok only if cmdedit_termw is correct. */
  365. c = command_ps[cursor];
  366. if (c == BB_NUL)
  367. c = ' ';
  368. BB_PUTCHAR(c);
  369. bb_putchar('\b');
  370. #endif
  371. cmdedit_y++;
  372. if (!ENABLE_UNICODE_WIDE_WCHARS || ofs_to_right == 0) {
  373. width = 0;
  374. } else { /* ofs_to_right > 0 */
  375. /* wide char c didn't fit on prev line */
  376. BB_PUTCHAR(c);
  377. }
  378. cmdedit_x = width;
  379. }
  380. }
  381. /* Move to end of line (by printing all chars till the end) */
  382. static void put_till_end_and_adv_cursor(void)
  383. {
  384. while (cursor < command_len)
  385. put_cur_glyph_and_inc_cursor();
  386. }
  387. /* Go to the next line */
  388. static void goto_new_line(void)
  389. {
  390. put_till_end_and_adv_cursor();
  391. /* "cursor == 0" is only if prompt is "" and user input is empty */
  392. if (cursor == 0 || cmdedit_x != 0)
  393. bb_putchar('\n');
  394. }
  395. static void beep(void)
  396. {
  397. bb_putchar('\007');
  398. }
  399. /* Full or last/sole prompt line, reset edit cursor, calculate terminal cursor.
  400. * cmdedit_y is always calculated for the last/sole prompt line.
  401. */
  402. static void put_prompt_custom(bool is_full)
  403. {
  404. fputs((is_full ? cmdedit_prompt : prompt_last_line), stdout);
  405. cursor = 0;
  406. cmdedit_y = cmdedit_prmt_len / cmdedit_termw; /* new quasireal y */
  407. cmdedit_x = cmdedit_prmt_len % cmdedit_termw;
  408. }
  409. #define put_prompt_last_line() put_prompt_custom(0)
  410. #define put_prompt() put_prompt_custom(1)
  411. /* Move back one character */
  412. /* (optimized for slow terminals) */
  413. static void input_backward(unsigned num)
  414. {
  415. if (num > cursor)
  416. num = cursor;
  417. if (num == 0)
  418. return;
  419. cursor -= num;
  420. if ((ENABLE_UNICODE_COMBINING_WCHARS || ENABLE_UNICODE_WIDE_WCHARS)
  421. && unicode_status == UNICODE_ON
  422. ) {
  423. /* correct NUM to be equal to _screen_ width */
  424. int n = num;
  425. num = 0;
  426. while (--n >= 0)
  427. adjust_width_and_validate_wc(&num, command_ps[cursor + n]);
  428. if (num == 0)
  429. return;
  430. }
  431. if (cmdedit_x >= num) {
  432. cmdedit_x -= num;
  433. if (num <= 4) {
  434. /* This is longer by 5 bytes on x86.
  435. * Also gets miscompiled for ARM users
  436. * (busybox.net/bugs/view.php?id=2274).
  437. * printf(("\b\b\b\b" + 4) - num);
  438. * return;
  439. */
  440. do {
  441. bb_putchar('\b');
  442. } while (--num);
  443. return;
  444. }
  445. printf(ESC"[%uD", num);
  446. return;
  447. }
  448. /* Need to go one or more lines up */
  449. if (ENABLE_UNICODE_WIDE_WCHARS) {
  450. /* With wide chars, it is hard to "backtrack"
  451. * and reliably figure out where to put cursor.
  452. * Example (<> is a wide char; # is an ordinary char, _ cursor):
  453. * |prompt: <><> |
  454. * |<><><><><><> |
  455. * |_ |
  456. * and user presses left arrow. num = 1, cmdedit_x = 0,
  457. * We need to go up one line, and then - how do we know that
  458. * we need to go *10* positions to the right? Because
  459. * |prompt: <>#<>|
  460. * |<><><>#<><><>|
  461. * |_ |
  462. * in this situation we need to go *11* positions to the right.
  463. *
  464. * A simpler thing to do is to redraw everything from the start
  465. * up to new cursor position (which is already known):
  466. */
  467. unsigned sv_cursor;
  468. /* go to 1st column; go up to first line */
  469. printf("\r" ESC"[%uA", cmdedit_y);
  470. cmdedit_y = 0;
  471. sv_cursor = cursor;
  472. put_prompt_last_line(); /* sets cursor to 0 */
  473. while (cursor < sv_cursor)
  474. put_cur_glyph_and_inc_cursor();
  475. } else {
  476. int lines_up;
  477. /* num = chars to go back from the beginning of current line: */
  478. num -= cmdedit_x;
  479. /* num=1...w: one line up, w+1...2w: two, etc: */
  480. lines_up = 1 + (num - 1) / cmdedit_termw;
  481. cmdedit_x = (cmdedit_termw * cmdedit_y - num) % cmdedit_termw;
  482. cmdedit_y -= lines_up;
  483. /* go to 1st column; go up */
  484. printf("\r" ESC"[%uA", lines_up);
  485. /* go to correct column.
  486. * xterm, konsole, Linux VT interpret 0 as 1 below! wow.
  487. * need to *make sure* we skip it if cmdedit_x == 0 */
  488. if (cmdedit_x)
  489. printf(ESC"[%uC", cmdedit_x);
  490. }
  491. }
  492. /* See redraw and draw_full below */
  493. static void draw_custom(int y, int back_cursor, bool is_full)
  494. {
  495. if (y > 0) /* up y lines */
  496. printf(ESC"[%uA", y);
  497. bb_putchar('\r');
  498. put_prompt_custom(is_full);
  499. put_till_end_and_adv_cursor();
  500. printf(SEQ_CLEAR_TILL_END_OF_SCREEN);
  501. input_backward(back_cursor);
  502. }
  503. /* Move y lines up, draw last/sole prompt line, editor line[s], and clear tail.
  504. * goal: redraw the prompt+input+cursor in-place, overwriting the previous */
  505. #define redraw(y, back_cursor) draw_custom((y), (back_cursor), 0)
  506. /* Like above, but without moving up, and while using all the prompt lines.
  507. * goal: draw a full prompt+input+cursor unrelated to a previous position.
  508. * note: cmdedit_y always ends up relating to the last/sole prompt line */
  509. #define draw_full(back_cursor) draw_custom(0, (back_cursor), 1)
  510. /* Delete the char in front of the cursor, optionally saving it
  511. * for later putback */
  512. #if !ENABLE_FEATURE_EDITING_VI
  513. static void input_delete(void)
  514. #define input_delete(save) input_delete()
  515. #else
  516. static void input_delete(int save)
  517. #endif
  518. {
  519. int j = cursor;
  520. if (j == (int)command_len)
  521. return;
  522. #if ENABLE_FEATURE_EDITING_VI
  523. if (save) {
  524. if (newdelflag) {
  525. delptr = delbuf;
  526. newdelflag = 0;
  527. }
  528. if ((delptr - delbuf) < DELBUFSIZ)
  529. *delptr++ = command_ps[j];
  530. }
  531. #endif
  532. memmove(command_ps + j, command_ps + j + 1,
  533. /* (command_len + 1 [because of NUL]) - (j + 1)
  534. * simplified into (command_len - j) */
  535. (command_len - j) * sizeof(command_ps[0]));
  536. command_len--;
  537. put_till_end_and_adv_cursor();
  538. /* Last char is still visible, erase it (and more) */
  539. printf(SEQ_CLEAR_TILL_END_OF_SCREEN);
  540. input_backward(cursor - j); /* back to old pos cursor */
  541. }
  542. #if ENABLE_FEATURE_EDITING_VI
  543. static void put(void)
  544. {
  545. int ocursor;
  546. int j = delptr - delbuf;
  547. if (j == 0)
  548. return;
  549. ocursor = cursor;
  550. /* open hole and then fill it */
  551. memmove(command_ps + cursor + j, command_ps + cursor,
  552. (command_len - cursor + 1) * sizeof(command_ps[0]));
  553. memcpy(command_ps + cursor, delbuf, j * sizeof(command_ps[0]));
  554. command_len += j;
  555. put_till_end_and_adv_cursor();
  556. input_backward(cursor - ocursor - j + 1); /* at end of new text */
  557. }
  558. #endif
  559. /* Delete the char in back of the cursor */
  560. static void input_backspace(void)
  561. {
  562. if (cursor > 0) {
  563. input_backward(1);
  564. input_delete(0);
  565. }
  566. }
  567. /* Move forward one character */
  568. static void input_forward(void)
  569. {
  570. if (cursor < command_len)
  571. put_cur_glyph_and_inc_cursor();
  572. }
  573. #if ENABLE_FEATURE_TAB_COMPLETION
  574. //FIXME:
  575. //needs to be more clever: currently it thinks that "foo\ b<TAB>
  576. //matches the file named "foo bar", which is untrue.
  577. //Also, perhaps "foo b<TAB> needs to complete to "foo bar" <cursor>,
  578. //not "foo bar <cursor>...
  579. static void free_tab_completion_data(void)
  580. {
  581. if (matches) {
  582. while (num_matches)
  583. free(matches[--num_matches]);
  584. free(matches);
  585. matches = NULL;
  586. }
  587. }
  588. static void add_match(char *matched)
  589. {
  590. unsigned char *p = (unsigned char*)matched;
  591. while (*p) {
  592. /* ESC attack fix: drop any string with control chars */
  593. if (*p < ' '
  594. || (!ENABLE_UNICODE_SUPPORT && *p >= 0x7f)
  595. || (ENABLE_UNICODE_SUPPORT && *p == 0x7f)
  596. ) {
  597. free(matched);
  598. return;
  599. }
  600. p++;
  601. }
  602. matches = xrealloc_vector(matches, 4, num_matches);
  603. matches[num_matches] = matched;
  604. num_matches++;
  605. }
  606. # if ENABLE_FEATURE_USERNAME_COMPLETION
  607. /* Replace "~user/..." with "/homedir/...".
  608. * The parameter is malloced, free it or return it
  609. * unchanged if no user is matched.
  610. */
  611. static char *username_path_completion(char *ud)
  612. {
  613. struct passwd *entry;
  614. char *tilde_name = ud;
  615. char *home = NULL;
  616. ud++; /* skip ~ */
  617. if (*ud == '/') { /* "~/..." */
  618. home = home_pwd_buf;
  619. } else {
  620. /* "~user/..." */
  621. ud = strchr(ud, '/');
  622. *ud = '\0'; /* "~user" */
  623. entry = getpwnam(tilde_name + 1);
  624. *ud = '/'; /* restore "~user/..." */
  625. if (entry)
  626. home = entry->pw_dir;
  627. }
  628. if (home) {
  629. ud = concat_path_file(home, ud);
  630. free(tilde_name);
  631. tilde_name = ud;
  632. }
  633. return tilde_name;
  634. }
  635. /* ~use<tab> - find all users with this prefix.
  636. * Return the length of the prefix used for matching.
  637. */
  638. static NOINLINE unsigned complete_username(const char *ud)
  639. {
  640. struct passwd *pw;
  641. unsigned userlen;
  642. ud++; /* skip ~ */
  643. userlen = strlen(ud);
  644. setpwent();
  645. while ((pw = getpwent()) != NULL) {
  646. /* Null usernames should result in all users as possible completions. */
  647. if (/* !ud[0] || */ is_prefixed_with(pw->pw_name, ud)) {
  648. add_match(xasprintf("~%s/", pw->pw_name));
  649. }
  650. }
  651. endpwent(); /* don't keep password file open */
  652. return 1 + userlen;
  653. }
  654. # endif /* FEATURE_USERNAME_COMPLETION */
  655. enum {
  656. FIND_EXE_ONLY = 0,
  657. FIND_DIR_ONLY = 1,
  658. FIND_FILE_ONLY = 2,
  659. };
  660. static int path_parse(char ***p)
  661. {
  662. int npth;
  663. const char *pth;
  664. char *tmp;
  665. char **res;
  666. if (state->flags & WITH_PATH_LOOKUP)
  667. pth = state->path_lookup;
  668. else
  669. pth = getenv("PATH");
  670. /* PATH="" or PATH=":"? */
  671. if (!pth || !pth[0] || LONE_CHAR(pth, ':'))
  672. return 1;
  673. tmp = (char*)pth;
  674. npth = 1; /* path component count */
  675. while (1) {
  676. tmp = strchr(tmp, ':');
  677. if (!tmp)
  678. break;
  679. tmp++;
  680. if (*tmp == '\0')
  681. break; /* :<empty> */
  682. npth++;
  683. }
  684. *p = res = xmalloc(npth * sizeof(res[0]));
  685. res[0] = tmp = xstrdup(pth);
  686. npth = 1;
  687. while (1) {
  688. tmp = strchr(tmp, ':');
  689. if (!tmp)
  690. break;
  691. *tmp++ = '\0'; /* ':' -> '\0' */
  692. if (*tmp == '\0')
  693. break; /* :<empty> */
  694. res[npth++] = tmp;
  695. }
  696. return npth;
  697. }
  698. /* Complete command, directory or file name.
  699. * Return the length of the prefix used for matching.
  700. */
  701. static NOINLINE unsigned complete_cmd_dir_file(const char *command, int type)
  702. {
  703. char *path1[1];
  704. char **paths = path1;
  705. int npaths;
  706. int i;
  707. unsigned pf_len;
  708. const char *pfind;
  709. char *dirbuf = NULL;
  710. npaths = 1;
  711. path1[0] = (char*)".";
  712. pfind = strrchr(command, '/');
  713. if (!pfind) {
  714. if (type == FIND_EXE_ONLY)
  715. npaths = path_parse(&paths);
  716. pfind = command;
  717. } else {
  718. /* point to 'l' in "..../last_component" */
  719. pfind++;
  720. /* dirbuf = ".../.../.../" */
  721. dirbuf = xstrndup(command, pfind - command);
  722. # if ENABLE_FEATURE_USERNAME_COMPLETION
  723. if (dirbuf[0] == '~') /* ~/... or ~user/... */
  724. dirbuf = username_path_completion(dirbuf);
  725. # endif
  726. path1[0] = dirbuf;
  727. }
  728. pf_len = strlen(pfind);
  729. # if ENABLE_FEATURE_SH_STANDALONE && NUM_APPLETS != 1
  730. if (type == FIND_EXE_ONLY && !dirbuf) {
  731. const char *p = applet_names;
  732. while (*p) {
  733. if (strncmp(pfind, p, pf_len) == 0)
  734. add_match(xstrdup(p));
  735. while (*p++ != '\0')
  736. continue;
  737. }
  738. }
  739. # endif
  740. for (i = 0; i < npaths; i++) {
  741. DIR *dir;
  742. struct dirent *next;
  743. struct stat st;
  744. char *found;
  745. dir = opendir(paths[i]);
  746. if (!dir)
  747. continue; /* don't print an error */
  748. while ((next = readdir(dir)) != NULL) {
  749. unsigned len;
  750. const char *name_found = next->d_name;
  751. /* .../<tab>: bash 3.2.0 shows dotfiles, but not . and .. */
  752. if (!pfind[0] && DOT_OR_DOTDOT(name_found))
  753. continue;
  754. /* match? */
  755. if (!is_prefixed_with(name_found, pfind))
  756. continue; /* no */
  757. found = concat_path_file(paths[i], name_found);
  758. /* NB: stat() first so that we see is it a directory;
  759. * but if that fails, use lstat() so that
  760. * we still match dangling links */
  761. if (stat(found, &st) && lstat(found, &st))
  762. goto cont; /* hmm, remove in progress? */
  763. /* Save only name */
  764. len = strlen(name_found);
  765. found = xrealloc(found, len + 2); /* +2: for slash and NUL */
  766. strcpy(found, name_found);
  767. if (S_ISDIR(st.st_mode)) {
  768. /* name is a directory, add slash */
  769. found[len] = '/';
  770. found[len + 1] = '\0';
  771. } else {
  772. /* skip files if looking for dirs only (example: cd) */
  773. if (type == FIND_DIR_ONLY)
  774. goto cont;
  775. }
  776. /* add it to the list */
  777. add_match(found);
  778. continue;
  779. cont:
  780. free(found);
  781. }
  782. closedir(dir);
  783. } /* for every path */
  784. if (paths != path1) {
  785. free(paths[0]); /* allocated memory is only in first member */
  786. free(paths);
  787. }
  788. free(dirbuf);
  789. return pf_len;
  790. }
  791. /* build_match_prefix:
  792. * On entry, match_buf contains everything up to cursor at the moment <tab>
  793. * was pressed. This function looks at it, figures out what part of it
  794. * constitutes the command/file/directory prefix to use for completion,
  795. * and rewrites match_buf to contain only that part.
  796. */
  797. #define dbg_bmp 0
  798. /* Helpers: */
  799. /* QUOT is used on elements of int_buf[], which are bytes,
  800. * not Unicode chars. Therefore it works correctly even in Unicode mode.
  801. */
  802. #define QUOT (UCHAR_MAX+1)
  803. static void remove_chunk(int16_t *int_buf, int beg, int end)
  804. {
  805. /* beg must be <= end */
  806. if (beg == end)
  807. return;
  808. while ((int_buf[beg] = int_buf[end]) != 0)
  809. beg++, end++;
  810. if (dbg_bmp) {
  811. int i;
  812. for (i = 0; int_buf[i]; i++)
  813. bb_putchar((unsigned char)int_buf[i]);
  814. bb_putchar('\n');
  815. }
  816. }
  817. /* Caller ensures that match_buf points to a malloced buffer
  818. * big enough to hold strlen(match_buf)*2 + 2
  819. */
  820. static NOINLINE int build_match_prefix(char *match_buf)
  821. {
  822. int i, j;
  823. int command_mode;
  824. int16_t *int_buf = (int16_t*)match_buf;
  825. if (dbg_bmp) printf("\n%s\n", match_buf);
  826. /* Copy in reverse order, since they overlap */
  827. i = strlen(match_buf);
  828. do {
  829. int_buf[i] = (unsigned char)match_buf[i];
  830. i--;
  831. } while (i >= 0);
  832. /* Mark every \c as "quoted c" */
  833. for (i = 0; int_buf[i]; i++) {
  834. if (int_buf[i] == '\\') {
  835. remove_chunk(int_buf, i, i + 1);
  836. int_buf[i] |= QUOT;
  837. }
  838. }
  839. /* Quote-mark "chars" and 'chars', drop delimiters */
  840. {
  841. int in_quote = 0;
  842. i = 0;
  843. while (int_buf[i]) {
  844. int cur = int_buf[i];
  845. if (!cur)
  846. break;
  847. if (cur == '\'' || cur == '"') {
  848. if (!in_quote || (cur == in_quote)) {
  849. in_quote ^= cur;
  850. remove_chunk(int_buf, i, i + 1);
  851. continue;
  852. }
  853. }
  854. if (in_quote)
  855. int_buf[i] = cur | QUOT;
  856. i++;
  857. }
  858. }
  859. /* Remove everything up to command delimiters:
  860. * ';' ';;' '&' '|' '&&' '||',
  861. * but careful with '>&' '<&' '>|'
  862. */
  863. for (i = 0; int_buf[i]; i++) {
  864. int cur = int_buf[i];
  865. if (cur == ';' || cur == '&' || cur == '|') {
  866. int prev = i ? int_buf[i - 1] : 0;
  867. if (cur == '&' && (prev == '>' || prev == '<')) {
  868. continue;
  869. } else if (cur == '|' && prev == '>') {
  870. continue;
  871. }
  872. remove_chunk(int_buf, 0, i + 1 + (cur == int_buf[i + 1]));
  873. i = -1; /* back to square 1 */
  874. }
  875. }
  876. /* Remove all `cmd` */
  877. for (i = 0; int_buf[i]; i++) {
  878. if (int_buf[i] == '`') {
  879. for (j = i + 1; int_buf[j]; j++) {
  880. if (int_buf[j] == '`') {
  881. /* `cmd` should count as a word:
  882. * `cmd` c<tab> should search for files c*,
  883. * not commands c*. Therefore we don't drop
  884. * `cmd` entirely, we replace it with single `.
  885. */
  886. remove_chunk(int_buf, i, j);
  887. goto next;
  888. }
  889. }
  890. /* No closing ` - command mode, remove all up to ` */
  891. remove_chunk(int_buf, 0, i + 1);
  892. break;
  893. next: ;
  894. }
  895. }
  896. /* Remove "cmd (" and "cmd {"
  897. * Example: "if { c<tab>"
  898. * In this example, c should be matched as command pfx.
  899. */
  900. for (i = 0; int_buf[i]; i++) {
  901. if (int_buf[i] == '(' || int_buf[i] == '{') {
  902. remove_chunk(int_buf, 0, i + 1);
  903. i = -1; /* back to square 1 */
  904. }
  905. }
  906. /* Remove leading unquoted spaces */
  907. for (i = 0; int_buf[i]; i++)
  908. if (int_buf[i] != ' ')
  909. break;
  910. remove_chunk(int_buf, 0, i);
  911. /* Determine completion mode */
  912. command_mode = FIND_EXE_ONLY;
  913. for (i = 0; int_buf[i]; i++) {
  914. if (int_buf[i] == ' ' || int_buf[i] == '<' || int_buf[i] == '>') {
  915. if (int_buf[i] == ' '
  916. && command_mode == FIND_EXE_ONLY
  917. && (char)int_buf[0] == 'c'
  918. && (char)int_buf[1] == 'd'
  919. && i == 2 /* -> int_buf[2] == ' ' */
  920. ) {
  921. command_mode = FIND_DIR_ONLY;
  922. } else {
  923. command_mode = FIND_FILE_ONLY;
  924. break;
  925. }
  926. }
  927. }
  928. if (dbg_bmp) printf("command_mode(0:exe/1:dir/2:file):%d\n", command_mode);
  929. /* Remove everything except last word */
  930. for (i = 0; int_buf[i]; i++) /* quasi-strlen(int_buf) */
  931. continue;
  932. for (--i; i >= 0; i--) {
  933. int cur = int_buf[i];
  934. if (cur == ' ' || cur == '<' || cur == '>' || cur == '|' || cur == '&') {
  935. remove_chunk(int_buf, 0, i + 1);
  936. break;
  937. }
  938. }
  939. /* Convert back to string of _chars_ */
  940. i = 0;
  941. while ((match_buf[i] = int_buf[i]) != '\0')
  942. i++;
  943. if (dbg_bmp) printf("final match_buf:'%s'\n", match_buf);
  944. return command_mode;
  945. }
  946. /*
  947. * Display by column (original idea from ls applet,
  948. * very optimized by me [Vladimir] :)
  949. */
  950. static void showfiles(void)
  951. {
  952. int ncols, row;
  953. int column_width = 0;
  954. int nfiles = num_matches;
  955. int nrows = nfiles;
  956. int l;
  957. /* find the longest file name - use that as the column width */
  958. for (row = 0; row < nrows; row++) {
  959. l = unicode_strwidth(matches[row]);
  960. if (column_width < l)
  961. column_width = l;
  962. }
  963. column_width += 2; /* min space for columns */
  964. ncols = cmdedit_termw / column_width;
  965. if (ncols > 1) {
  966. nrows /= ncols;
  967. if (nfiles % ncols)
  968. nrows++; /* round up fractionals */
  969. } else {
  970. ncols = 1;
  971. }
  972. for (row = 0; row < nrows; row++) {
  973. int n = row;
  974. int nc;
  975. for (nc = 1; nc < ncols && n+nrows < nfiles; n += nrows, nc++) {
  976. printf("%s%-*s", matches[n],
  977. (int)(column_width - unicode_strwidth(matches[n])), ""
  978. );
  979. }
  980. if (ENABLE_UNICODE_SUPPORT)
  981. puts(printable_string(matches[n]));
  982. else
  983. puts(matches[n]);
  984. }
  985. }
  986. static const char *is_special_char(char c)
  987. {
  988. return strchr(" `\"#$%^&*()=+{}[]:;'|\\<>", c);
  989. }
  990. static char *quote_special_chars(char *found)
  991. {
  992. int l = 0;
  993. char *s = xzalloc((strlen(found) + 1) * 2);
  994. while (*found) {
  995. if (is_special_char(*found))
  996. s[l++] = '\\';
  997. s[l++] = *found++;
  998. }
  999. /* s[l] = '\0'; - already is */
  1000. return s;
  1001. }
  1002. /* Do TAB completion */
  1003. static NOINLINE void input_tab(smallint *lastWasTab)
  1004. {
  1005. char *chosen_match;
  1006. char *match_buf;
  1007. size_t len_found;
  1008. /* Length of string used for matching */
  1009. unsigned match_pfx_len = match_pfx_len;
  1010. int find_type;
  1011. # if ENABLE_UNICODE_SUPPORT
  1012. /* cursor pos in command converted to multibyte form */
  1013. int cursor_mb;
  1014. # endif
  1015. if (!(state->flags & TAB_COMPLETION))
  1016. return;
  1017. if (*lastWasTab) {
  1018. /* The last char was a TAB too.
  1019. * Print a list of all the available choices.
  1020. */
  1021. if (num_matches > 0) {
  1022. /* cursor will be changed by goto_new_line() */
  1023. int sav_cursor = cursor;
  1024. goto_new_line();
  1025. showfiles();
  1026. draw_full(command_len - sav_cursor);
  1027. }
  1028. return;
  1029. }
  1030. *lastWasTab = 1;
  1031. chosen_match = NULL;
  1032. /* Make a local copy of the string up to the position of the cursor.
  1033. * build_match_prefix will expand it into int16_t's, need to allocate
  1034. * twice as much as the string_len+1.
  1035. * (we then also (ab)use this extra space later - see (**))
  1036. */
  1037. match_buf = xmalloc(MAX_LINELEN * sizeof(int16_t));
  1038. # if !ENABLE_UNICODE_SUPPORT
  1039. save_string(match_buf, cursor + 1); /* +1 for NUL */
  1040. # else
  1041. {
  1042. CHAR_T wc = command_ps[cursor];
  1043. command_ps[cursor] = BB_NUL;
  1044. save_string(match_buf, MAX_LINELEN);
  1045. command_ps[cursor] = wc;
  1046. cursor_mb = strlen(match_buf);
  1047. }
  1048. # endif
  1049. find_type = build_match_prefix(match_buf);
  1050. /* Free up any memory already allocated */
  1051. free_tab_completion_data();
  1052. # if ENABLE_FEATURE_USERNAME_COMPLETION
  1053. /* If the word starts with ~ and there is no slash in the word,
  1054. * then try completing this word as a username. */
  1055. if (state->flags & USERNAME_COMPLETION)
  1056. if (match_buf[0] == '~' && strchr(match_buf, '/') == NULL)
  1057. match_pfx_len = complete_username(match_buf);
  1058. # endif
  1059. /* If complete_username() did not match,
  1060. * try to match a command in $PATH, or a directory, or a file */
  1061. if (!matches)
  1062. match_pfx_len = complete_cmd_dir_file(match_buf, find_type);
  1063. /* Account for backslashes which will be inserted
  1064. * by quote_special_chars() later */
  1065. {
  1066. const char *e = match_buf + strlen(match_buf);
  1067. const char *s = e - match_pfx_len;
  1068. while (s < e)
  1069. if (is_special_char(*s++))
  1070. match_pfx_len++;
  1071. }
  1072. /* Remove duplicates */
  1073. if (matches) {
  1074. unsigned i, n = 0;
  1075. qsort_string_vector(matches, num_matches);
  1076. for (i = 0; i < num_matches - 1; ++i) {
  1077. //if (matches[i] && matches[i+1]) { /* paranoia */
  1078. if (strcmp(matches[i], matches[i+1]) == 0) {
  1079. free(matches[i]);
  1080. //matches[i] = NULL; /* paranoia */
  1081. } else {
  1082. matches[n++] = matches[i];
  1083. }
  1084. //}
  1085. }
  1086. matches[n++] = matches[i];
  1087. num_matches = n;
  1088. }
  1089. /* Did we find exactly one match? */
  1090. if (num_matches != 1) { /* no */
  1091. char *cp;
  1092. beep();
  1093. if (!matches)
  1094. goto ret; /* no matches at all */
  1095. /* Find common prefix */
  1096. chosen_match = xstrdup(matches[0]);
  1097. for (cp = chosen_match; *cp; cp++) {
  1098. unsigned n;
  1099. for (n = 1; n < num_matches; n++) {
  1100. if (matches[n][cp - chosen_match] != *cp) {
  1101. goto stop;
  1102. }
  1103. }
  1104. }
  1105. stop:
  1106. if (cp == chosen_match) { /* have unique prefix? */
  1107. goto ret; /* no */
  1108. }
  1109. *cp = '\0';
  1110. cp = quote_special_chars(chosen_match);
  1111. free(chosen_match);
  1112. chosen_match = cp;
  1113. len_found = strlen(chosen_match);
  1114. } else { /* exactly one match */
  1115. /* Next <tab> is not a double-tab */
  1116. *lastWasTab = 0;
  1117. chosen_match = quote_special_chars(matches[0]);
  1118. len_found = strlen(chosen_match);
  1119. if (chosen_match[len_found-1] != '/') {
  1120. chosen_match[len_found] = ' ';
  1121. chosen_match[++len_found] = '\0';
  1122. }
  1123. }
  1124. # if !ENABLE_UNICODE_SUPPORT
  1125. /* Have space to place the match? */
  1126. /* The result consists of three parts with these lengths: */
  1127. /* cursor + (len_found - match_pfx_len) + (command_len - cursor) */
  1128. /* it simplifies into: */
  1129. if ((int)(len_found - match_pfx_len + command_len) < S.maxsize) {
  1130. int pos;
  1131. /* save tail */
  1132. strcpy(match_buf, &command_ps[cursor]);
  1133. /* add match and tail */
  1134. sprintf(&command_ps[cursor], "%s%s", chosen_match + match_pfx_len, match_buf);
  1135. command_len = strlen(command_ps);
  1136. /* new pos */
  1137. pos = cursor + len_found - match_pfx_len;
  1138. /* write out the matched command */
  1139. redraw(cmdedit_y, command_len - pos);
  1140. }
  1141. # else
  1142. {
  1143. /* Use 2nd half of match_buf as scratch space - see (**) */
  1144. char *command = match_buf + MAX_LINELEN;
  1145. int len = save_string(command, MAX_LINELEN);
  1146. /* Have space to place the match? */
  1147. /* cursor_mb + (len_found - match_pfx_len) + (len - cursor_mb) */
  1148. if ((int)(len_found - match_pfx_len + len) < MAX_LINELEN) {
  1149. int pos;
  1150. /* save tail */
  1151. strcpy(match_buf, &command[cursor_mb]);
  1152. /* where do we want to have cursor after all? */
  1153. strcpy(&command[cursor_mb], chosen_match + match_pfx_len);
  1154. len = load_string(command);
  1155. /* add match and tail */
  1156. sprintf(&command[cursor_mb], "%s%s", chosen_match + match_pfx_len, match_buf);
  1157. command_len = load_string(command);
  1158. /* write out the matched command */
  1159. /* paranoia: load_string can return 0 on conv error,
  1160. * prevent passing pos = (0 - 12) to redraw */
  1161. pos = command_len - len;
  1162. redraw(cmdedit_y, pos >= 0 ? pos : 0);
  1163. }
  1164. }
  1165. # endif
  1166. ret:
  1167. free(chosen_match);
  1168. free(match_buf);
  1169. }
  1170. #endif /* FEATURE_TAB_COMPLETION */
  1171. line_input_t* FAST_FUNC new_line_input_t(int flags)
  1172. {
  1173. line_input_t *n = xzalloc(sizeof(*n));
  1174. n->flags = flags;
  1175. n->timeout = -1;
  1176. #if MAX_HISTORY > 0
  1177. n->max_history = MAX_HISTORY;
  1178. #endif
  1179. return n;
  1180. }
  1181. #if MAX_HISTORY > 0
  1182. unsigned FAST_FUNC size_from_HISTFILESIZE(const char *hp)
  1183. {
  1184. int size = MAX_HISTORY;
  1185. if (hp) {
  1186. size = atoi(hp);
  1187. if (size <= 0)
  1188. return 1;
  1189. if (size > MAX_HISTORY)
  1190. return MAX_HISTORY;
  1191. }
  1192. return size;
  1193. }
  1194. static void save_command_ps_at_cur_history(void)
  1195. {
  1196. if (command_ps[0] != BB_NUL) {
  1197. int cur = state->cur_history;
  1198. free(state->history[cur]);
  1199. # if ENABLE_UNICODE_SUPPORT
  1200. {
  1201. char tbuf[MAX_LINELEN];
  1202. save_string(tbuf, sizeof(tbuf));
  1203. state->history[cur] = xstrdup(tbuf);
  1204. }
  1205. # else
  1206. state->history[cur] = xstrdup(command_ps);
  1207. # endif
  1208. }
  1209. }
  1210. /* state->flags is already checked to be nonzero */
  1211. static int get_previous_history(void)
  1212. {
  1213. if ((state->flags & DO_HISTORY) && state->cur_history) {
  1214. save_command_ps_at_cur_history();
  1215. state->cur_history--;
  1216. return 1;
  1217. }
  1218. beep();
  1219. return 0;
  1220. }
  1221. static int get_next_history(void)
  1222. {
  1223. if (state->flags & DO_HISTORY) {
  1224. if (state->cur_history < state->cnt_history) {
  1225. save_command_ps_at_cur_history(); /* save the current history line */
  1226. return ++state->cur_history;
  1227. }
  1228. }
  1229. beep();
  1230. return 0;
  1231. }
  1232. /* Lists command history. Used by shell 'history' builtins */
  1233. void FAST_FUNC show_history(const line_input_t *st)
  1234. {
  1235. int i;
  1236. if (!st)
  1237. return;
  1238. for (i = 0; i < st->cnt_history; i++)
  1239. printf("%4d %s\n", i, st->history[i]);
  1240. }
  1241. void FAST_FUNC free_line_input_t(line_input_t *n)
  1242. {
  1243. # if ENABLE_FEATURE_EDITING_SAVEHISTORY
  1244. int i = n->cnt_history;
  1245. while (i > 0)
  1246. free(n->history[--i]);
  1247. #endif
  1248. free(n);
  1249. }
  1250. # if ENABLE_FEATURE_EDITING_SAVEHISTORY
  1251. /* We try to ensure that concurrent additions to the history
  1252. * do not overwrite each other.
  1253. * Otherwise shell users get unhappy.
  1254. *
  1255. * History file is trimmed lazily, when it grows several times longer
  1256. * than configured MAX_HISTORY lines.
  1257. */
  1258. /* state->flags is already checked to be nonzero */
  1259. static void load_history(line_input_t *st_parm)
  1260. {
  1261. char *temp_h[MAX_HISTORY];
  1262. char *line;
  1263. FILE *fp;
  1264. unsigned idx, i, line_len;
  1265. /* NB: do not trash old history if file can't be opened */
  1266. fp = fopen_for_read(st_parm->hist_file);
  1267. if (fp) {
  1268. /* clean up old history */
  1269. for (idx = st_parm->cnt_history; idx > 0;) {
  1270. idx--;
  1271. free(st_parm->history[idx]);
  1272. st_parm->history[idx] = NULL;
  1273. }
  1274. /* fill temp_h[], retaining only last MAX_HISTORY lines */
  1275. memset(temp_h, 0, sizeof(temp_h));
  1276. idx = 0;
  1277. st_parm->cnt_history_in_file = 0;
  1278. while ((line = xmalloc_fgetline(fp)) != NULL) {
  1279. if (line[0] == '\0') {
  1280. free(line);
  1281. continue;
  1282. }
  1283. free(temp_h[idx]);
  1284. temp_h[idx] = line;
  1285. st_parm->cnt_history_in_file++;
  1286. idx++;
  1287. if (idx == st_parm->max_history)
  1288. idx = 0;
  1289. }
  1290. fclose(fp);
  1291. /* find first non-NULL temp_h[], if any */
  1292. if (st_parm->cnt_history_in_file) {
  1293. while (temp_h[idx] == NULL) {
  1294. idx++;
  1295. if (idx == st_parm->max_history)
  1296. idx = 0;
  1297. }
  1298. }
  1299. /* copy temp_h[] to st_parm->history[] */
  1300. for (i = 0; i < st_parm->max_history;) {
  1301. line = temp_h[idx];
  1302. if (!line)
  1303. break;
  1304. idx++;
  1305. if (idx == st_parm->max_history)
  1306. idx = 0;
  1307. line_len = strlen(line);
  1308. if (line_len >= MAX_LINELEN)
  1309. line[MAX_LINELEN-1] = '\0';
  1310. st_parm->history[i++] = line;
  1311. }
  1312. st_parm->cnt_history = i;
  1313. if (ENABLE_FEATURE_EDITING_SAVE_ON_EXIT)
  1314. st_parm->cnt_history_in_file = i;
  1315. }
  1316. }
  1317. # if ENABLE_FEATURE_EDITING_SAVE_ON_EXIT
  1318. void save_history(line_input_t *st)
  1319. {
  1320. FILE *fp;
  1321. if (!st->hist_file)
  1322. return;
  1323. if (st->cnt_history <= st->cnt_history_in_file)
  1324. return;
  1325. fp = fopen(st->hist_file, "a");
  1326. if (fp) {
  1327. int i, fd;
  1328. char *new_name;
  1329. line_input_t *st_temp;
  1330. for (i = st->cnt_history_in_file; i < st->cnt_history; i++)
  1331. fprintf(fp, "%s\n", st->history[i]);
  1332. fclose(fp);
  1333. /* we may have concurrently written entries from others.
  1334. * load them */
  1335. st_temp = new_line_input_t(st->flags);
  1336. st_temp->hist_file = st->hist_file;
  1337. st_temp->max_history = st->max_history;
  1338. load_history(st_temp);
  1339. /* write out temp file and replace hist_file atomically */
  1340. new_name = xasprintf("%s.%u.new", st->hist_file, (int) getpid());
  1341. fd = open(new_name, O_WRONLY | O_CREAT | O_TRUNC, 0600);
  1342. if (fd >= 0) {
  1343. fp = xfdopen_for_write(fd);
  1344. for (i = 0; i < st_temp->cnt_history; i++)
  1345. fprintf(fp, "%s\n", st_temp->history[i]);
  1346. fclose(fp);
  1347. if (rename(new_name, st->hist_file) == 0)
  1348. st->cnt_history_in_file = st_temp->cnt_history;
  1349. }
  1350. free(new_name);
  1351. free_line_input_t(st_temp);
  1352. }
  1353. }
  1354. # else
  1355. static void save_history(char *str)
  1356. {
  1357. int fd;
  1358. int len, len2;
  1359. if (!state->hist_file)
  1360. return;
  1361. fd = open(state->hist_file, O_WRONLY | O_CREAT | O_APPEND, 0600);
  1362. if (fd < 0)
  1363. return;
  1364. xlseek(fd, 0, SEEK_END); /* paranoia */
  1365. len = strlen(str);
  1366. str[len] = '\n'; /* we (try to) do atomic write */
  1367. len2 = full_write(fd, str, len + 1);
  1368. str[len] = '\0';
  1369. close(fd);
  1370. if (len2 != len + 1)
  1371. return; /* "wtf?" */
  1372. /* did we write so much that history file needs trimming? */
  1373. state->cnt_history_in_file++;
  1374. if (state->cnt_history_in_file > state->max_history * 4) {
  1375. char *new_name;
  1376. line_input_t *st_temp;
  1377. /* we may have concurrently written entries from others.
  1378. * load them */
  1379. st_temp = new_line_input_t(state->flags);
  1380. st_temp->hist_file = state->hist_file;
  1381. st_temp->max_history = state->max_history;
  1382. load_history(st_temp);
  1383. /* write out temp file and replace hist_file atomically */
  1384. new_name = xasprintf("%s.%u.new", state->hist_file, (int) getpid());
  1385. fd = open(new_name, O_WRONLY | O_CREAT | O_TRUNC, 0600);
  1386. if (fd >= 0) {
  1387. FILE *fp;
  1388. int i;
  1389. fp = xfdopen_for_write(fd);
  1390. for (i = 0; i < st_temp->cnt_history; i++)
  1391. fprintf(fp, "%s\n", st_temp->history[i]);
  1392. fclose(fp);
  1393. if (rename(new_name, state->hist_file) == 0)
  1394. state->cnt_history_in_file = st_temp->cnt_history;
  1395. }
  1396. free(new_name);
  1397. free_line_input_t(st_temp);
  1398. }
  1399. }
  1400. # endif
  1401. # else
  1402. # define load_history(a) ((void)0)
  1403. # define save_history(a) ((void)0)
  1404. # endif /* FEATURE_COMMAND_SAVEHISTORY */
  1405. static void remember_in_history(char *str)
  1406. {
  1407. int i;
  1408. if (!(state->flags & DO_HISTORY))
  1409. return;
  1410. if (str[0] == '\0')
  1411. return;
  1412. i = state->cnt_history;
  1413. /* Don't save dupes */
  1414. if (i && strcmp(state->history[i-1], str) == 0)
  1415. return;
  1416. free(state->history[state->max_history]); /* redundant, paranoia */
  1417. state->history[state->max_history] = NULL; /* redundant, paranoia */
  1418. /* If history[] is full, remove the oldest command */
  1419. /* we need to keep history[state->max_history] empty, hence >=, not > */
  1420. if (i >= state->max_history) {
  1421. free(state->history[0]);
  1422. for (i = 0; i < state->max_history-1; i++)
  1423. state->history[i] = state->history[i+1];
  1424. /* i == state->max_history-1 */
  1425. # if ENABLE_FEATURE_EDITING_SAVE_ON_EXIT
  1426. if (state->cnt_history_in_file)
  1427. state->cnt_history_in_file--;
  1428. # endif
  1429. }
  1430. /* i <= state->max_history-1 */
  1431. state->history[i++] = xstrdup(str);
  1432. /* i <= state->max_history */
  1433. state->cur_history = i;
  1434. state->cnt_history = i;
  1435. # if ENABLE_FEATURE_EDITING_SAVEHISTORY && !ENABLE_FEATURE_EDITING_SAVE_ON_EXIT
  1436. save_history(str);
  1437. # endif
  1438. }
  1439. #else /* MAX_HISTORY == 0 */
  1440. # define remember_in_history(a) ((void)0)
  1441. #endif /* MAX_HISTORY */
  1442. #if ENABLE_FEATURE_EDITING_VI
  1443. /*
  1444. * vi mode implemented 2005 by Paul Fox <pgf@foxharp.boston.ma.us>
  1445. */
  1446. static void
  1447. vi_Word_motion(int eat)
  1448. {
  1449. CHAR_T *command = command_ps;
  1450. while (cursor < command_len && !BB_isspace(command[cursor]))
  1451. input_forward();
  1452. if (eat) while (cursor < command_len && BB_isspace(command[cursor]))
  1453. input_forward();
  1454. }
  1455. static void
  1456. vi_word_motion(int eat)
  1457. {
  1458. CHAR_T *command = command_ps;
  1459. if (BB_isalnum_or_underscore(command[cursor])) {
  1460. while (cursor < command_len
  1461. && (BB_isalnum_or_underscore(command[cursor+1]))
  1462. ) {
  1463. input_forward();
  1464. }
  1465. } else if (BB_ispunct(command[cursor])) {
  1466. while (cursor < command_len && BB_ispunct(command[cursor+1]))
  1467. input_forward();
  1468. }
  1469. if (cursor < command_len)
  1470. input_forward();
  1471. if (eat) {
  1472. while (cursor < command_len && BB_isspace(command[cursor]))
  1473. input_forward();
  1474. }
  1475. }
  1476. static void
  1477. vi_End_motion(void)
  1478. {
  1479. CHAR_T *command = command_ps;
  1480. input_forward();
  1481. while (cursor < command_len && BB_isspace(command[cursor]))
  1482. input_forward();
  1483. while (cursor < command_len-1 && !BB_isspace(command[cursor+1]))
  1484. input_forward();
  1485. }
  1486. static void
  1487. vi_end_motion(void)
  1488. {
  1489. CHAR_T *command = command_ps;
  1490. if (cursor >= command_len-1)
  1491. return;
  1492. input_forward();
  1493. while (cursor < command_len-1 && BB_isspace(command[cursor]))
  1494. input_forward();
  1495. if (cursor >= command_len-1)
  1496. return;
  1497. if (BB_isalnum_or_underscore(command[cursor])) {
  1498. while (cursor < command_len-1
  1499. && (BB_isalnum_or_underscore(command[cursor+1]))
  1500. ) {
  1501. input_forward();
  1502. }
  1503. } else if (BB_ispunct(command[cursor])) {
  1504. while (cursor < command_len-1 && BB_ispunct(command[cursor+1]))
  1505. input_forward();
  1506. }
  1507. }
  1508. static void
  1509. vi_Back_motion(void)
  1510. {
  1511. CHAR_T *command = command_ps;
  1512. while (cursor > 0 && BB_isspace(command[cursor-1]))
  1513. input_backward(1);
  1514. while (cursor > 0 && !BB_isspace(command[cursor-1]))
  1515. input_backward(1);
  1516. }
  1517. static void
  1518. vi_back_motion(void)
  1519. {
  1520. CHAR_T *command = command_ps;
  1521. if (cursor <= 0)
  1522. return;
  1523. input_backward(1);
  1524. while (cursor > 0 && BB_isspace(command[cursor]))
  1525. input_backward(1);
  1526. if (cursor <= 0)
  1527. return;
  1528. if (BB_isalnum_or_underscore(command[cursor])) {
  1529. while (cursor > 0
  1530. && (BB_isalnum_or_underscore(command[cursor-1]))
  1531. ) {
  1532. input_backward(1);
  1533. }
  1534. } else if (BB_ispunct(command[cursor])) {
  1535. while (cursor > 0 && BB_ispunct(command[cursor-1]))
  1536. input_backward(1);
  1537. }
  1538. }
  1539. #endif
  1540. /* Modelled after bash 4.0 behavior of Ctrl-<arrow> */
  1541. static void ctrl_left(void)
  1542. {
  1543. CHAR_T *command = command_ps;
  1544. while (1) {
  1545. CHAR_T c;
  1546. input_backward(1);
  1547. if (cursor == 0)
  1548. break;
  1549. c = command[cursor];
  1550. if (c != ' ' && !BB_ispunct(c)) {
  1551. /* we reached a "word" delimited by spaces/punct.
  1552. * go to its beginning */
  1553. while (1) {
  1554. c = command[cursor - 1];
  1555. if (c == ' ' || BB_ispunct(c))
  1556. break;
  1557. input_backward(1);
  1558. if (cursor == 0)
  1559. break;
  1560. }
  1561. break;
  1562. }
  1563. }
  1564. }
  1565. static void ctrl_right(void)
  1566. {
  1567. CHAR_T *command = command_ps;
  1568. while (1) {
  1569. CHAR_T c;
  1570. c = command[cursor];
  1571. if (c == BB_NUL)
  1572. break;
  1573. if (c != ' ' && !BB_ispunct(c)) {
  1574. /* we reached a "word" delimited by spaces/punct.
  1575. * go to its end + 1 */
  1576. while (1) {
  1577. input_forward();
  1578. c = command[cursor];
  1579. if (c == BB_NUL || c == ' ' || BB_ispunct(c))
  1580. break;
  1581. }
  1582. break;
  1583. }
  1584. input_forward();
  1585. }
  1586. }
  1587. /*
  1588. * read_line_input and its helpers
  1589. */
  1590. #if ENABLE_FEATURE_EDITING_ASK_TERMINAL
  1591. static void ask_terminal(void)
  1592. {
  1593. /* Ask terminal where is the cursor now.
  1594. * lineedit_read_key handles response and corrects
  1595. * our idea of current cursor position.
  1596. * Testcase: run "echo -n long_line_long_line_long_line",
  1597. * then type in a long, wrapping command and try to
  1598. * delete it using backspace key.
  1599. * Note: we print it _after_ prompt, because
  1600. * prompt may contain CR. Example: PS1='\[\r\n\]\w '
  1601. */
  1602. /* Problem: if there is buffered input on stdin,
  1603. * the response will be delivered later,
  1604. * possibly to an unsuspecting application.
  1605. * Testcase: "sleep 1; busybox ash" + press and hold [Enter].
  1606. * Result:
  1607. * ~/srcdevel/bbox/fix/busybox.t4 #
  1608. * ~/srcdevel/bbox/fix/busybox.t4 #
  1609. * ^[[59;34~/srcdevel/bbox/fix/busybox.t4 # <-- garbage
  1610. * ~/srcdevel/bbox/fix/busybox.t4 #
  1611. *
  1612. * Checking for input with poll only makes the race narrower,
  1613. * I still can trigger it. Strace:
  1614. *
  1615. * write(1, "~/srcdevel/bbox/fix/busybox.t4 # ", 33) = 33
  1616. * poll([{fd=0, events=POLLIN}], 1, 0) = 0 (Timeout) <-- no input exists
  1617. * write(1, "\33[6n", 4) = 4 <-- send the ESC sequence, quick!
  1618. * poll([{fd=0, events=POLLIN}], 1, -1) = 1 ([{fd=0, revents=POLLIN}])
  1619. * read(0, "\n", 1) = 1 <-- oh crap, user's input got in first
  1620. */
  1621. struct pollfd pfd;
  1622. pfd.fd = STDIN_FILENO;
  1623. pfd.events = POLLIN;
  1624. if (safe_poll(&pfd, 1, 0) == 0) {
  1625. S.sent_ESC_br6n = 1;
  1626. fputs(ESC"[6n", stdout);
  1627. fflush_all(); /* make terminal see it ASAP! */
  1628. }
  1629. }
  1630. #else
  1631. #define ask_terminal() ((void)0)
  1632. #endif
  1633. /* Note about multi-line PS1 (e.g. "\n\w \u@\h\n> ") and prompt redrawing:
  1634. *
  1635. * If the prompt has any newlines, after we print it once we use only its last
  1636. * line to redraw in-place, which makes it simpler to calculate how many lines
  1637. * we should move the cursor up to align the redraw (cmdedit_y). The earlier
  1638. * prompt lines just stay on screen and we redraw below them.
  1639. *
  1640. * Use cases for all prompt lines beyond the initial draw:
  1641. * - After clear-screen (^L) or after displaying tab-completion choices, we
  1642. * print the full prompt, as it isn't redrawn in-place.
  1643. * - During terminal resize we could try to redraw all lines, but we don't,
  1644. * because it requires delicate alignment, it's good enough with only the
  1645. * last line, and doing it wrong is arguably worse than not doing it at all.
  1646. *
  1647. * Terminology wise, if it doesn't mention "full", then it means the last/sole
  1648. * prompt line. We use the prompt (last/sole line) while redrawing in-place,
  1649. * and the full where we need a fresh one unrelated to an earlier position.
  1650. *
  1651. * If PS1 is not multiline, the last/sole line and the full are the same string.
  1652. */
  1653. /* Called just once at read_line_input() init time */
  1654. #if !ENABLE_FEATURE_EDITING_FANCY_PROMPT
  1655. static void parse_and_put_prompt(const char *prmt_ptr)
  1656. {
  1657. const char *p;
  1658. cmdedit_prompt = prompt_last_line = prmt_ptr;
  1659. p = strrchr(prmt_ptr, '\n');
  1660. if (p)
  1661. prompt_last_line = p + 1;
  1662. cmdedit_prmt_len = unicode_strwidth(prompt_last_line);
  1663. put_prompt();
  1664. }
  1665. #else
  1666. static void parse_and_put_prompt(const char *prmt_ptr)
  1667. {
  1668. int prmt_size = 0;
  1669. char *prmt_mem_ptr = xzalloc(1);
  1670. # if ENABLE_USERNAME_OR_HOMEDIR
  1671. char *cwd_buf = NULL;
  1672. # endif
  1673. char flg_not_length = '[';
  1674. char cbuf[2];
  1675. /*cmdedit_prmt_len = 0; - already is */
  1676. cbuf[1] = '\0'; /* never changes */
  1677. while (*prmt_ptr) {
  1678. char timebuf[sizeof("HH:MM:SS")];
  1679. char *free_me = NULL;
  1680. char *pbuf;
  1681. char c;
  1682. pbuf = cbuf;
  1683. c = *prmt_ptr++;
  1684. if (c == '\\') {
  1685. const char *cp;
  1686. int l;
  1687. /*
  1688. * Supported via bb_process_escape_sequence:
  1689. * \a ASCII bell character (07)
  1690. * \e ASCII escape character (033)
  1691. * \n newline
  1692. * \r carriage return
  1693. * \\ backslash
  1694. * \nnn char with octal code nnn
  1695. * Supported:
  1696. * \$ if the effective UID is 0, a #, otherwise a $
  1697. * \w current working directory, with $HOME abbreviated with a tilde
  1698. * Note: we do not support $PROMPT_DIRTRIM=n feature
  1699. * \W basename of the current working directory, with $HOME abbreviated with a tilde
  1700. * \h hostname up to the first '.'
  1701. * \H hostname
  1702. * \u username
  1703. * \[ begin a sequence of non-printing characters
  1704. * \] end a sequence of non-printing characters
  1705. * \T current time in 12-hour HH:MM:SS format
  1706. * \@ current time in 12-hour am/pm format
  1707. * \A current time in 24-hour HH:MM format
  1708. * \t current time in 24-hour HH:MM:SS format
  1709. * (all of the above work as \A)
  1710. * Not supported:
  1711. * \! history number of this command
  1712. * \# command number of this command
  1713. * \j number of jobs currently managed by the shell
  1714. * \l basename of the shell's terminal device name
  1715. * \s name of the shell, the basename of $0 (the portion following the final slash)
  1716. * \V release of bash, version + patch level (e.g., 2.00.0)
  1717. * \d date in "Weekday Month Date" format (e.g., "Tue May 26")
  1718. * \D{format}
  1719. * format is passed to strftime(3).
  1720. * An empty format results in a locale-specific time representation.
  1721. * The braces are required.
  1722. * Mishandled by bb_process_escape_sequence:
  1723. * \v version of bash (e.g., 2.00)
  1724. */
  1725. cp = prmt_ptr;
  1726. c = *cp;
  1727. if (c != 't') /* don't treat \t as tab */
  1728. c = bb_process_escape_sequence(&prmt_ptr);
  1729. if (prmt_ptr == cp) {
  1730. if (*cp == '\0')
  1731. break;
  1732. c = *prmt_ptr++;
  1733. switch (c) {
  1734. # if ENABLE_USERNAME_OR_HOMEDIR
  1735. case 'u':
  1736. pbuf = user_buf ? user_buf : (char*)"";
  1737. break;
  1738. # endif
  1739. case 'H':
  1740. case 'h':
  1741. pbuf = free_me = safe_gethostname();
  1742. if (c == 'h')
  1743. strchrnul(pbuf, '.')[0] = '\0';
  1744. break;
  1745. case '$':
  1746. c = (geteuid() == 0 ? '#' : '$');
  1747. break;
  1748. case 'T': /* 12-hour HH:MM:SS format */
  1749. case '@': /* 12-hour am/pm format */
  1750. case 'A': /* 24-hour HH:MM format */
  1751. case 't': /* 24-hour HH:MM:SS format */
  1752. /* We show all of them as 24-hour HH:MM */
  1753. strftime_HHMMSS(timebuf, sizeof(timebuf), NULL)[-3] = '\0';
  1754. pbuf = timebuf;
  1755. break;
  1756. # if ENABLE_USERNAME_OR_HOMEDIR
  1757. case 'w': /* current dir */
  1758. case 'W': /* basename of cur dir */
  1759. if (!cwd_buf) {
  1760. cwd_buf = xrealloc_getcwd_or_warn(NULL);
  1761. if (!cwd_buf)
  1762. cwd_buf = (char *)bb_msg_unknown;
  1763. else if (home_pwd_buf[0]) {
  1764. char *after_home_user;
  1765. /* /home/user[/something] -> ~[/something] */
  1766. after_home_user = is_prefixed_with(cwd_buf, home_pwd_buf);
  1767. if (after_home_user
  1768. && (*after_home_user == '/' || *after_home_user == '\0')
  1769. ) {
  1770. cwd_buf[0] = '~';
  1771. overlapping_strcpy(cwd_buf + 1, after_home_user);
  1772. }
  1773. }
  1774. }
  1775. pbuf = cwd_buf;
  1776. if (c == 'w')
  1777. break;
  1778. cp = strrchr(pbuf, '/');
  1779. if (cp)
  1780. pbuf = (char*)cp + 1;
  1781. break;
  1782. # endif
  1783. // bb_process_escape_sequence does this now:
  1784. // case 'e': case 'E': /* \e \E = \033 */
  1785. // c = '\033';
  1786. // break;
  1787. case 'x': case 'X': {
  1788. char buf2[4];
  1789. for (l = 0; l < 3;) {
  1790. unsigned h;
  1791. buf2[l++] = *prmt_ptr;
  1792. buf2[l] = '\0';
  1793. h = strtoul(buf2, &pbuf, 16);
  1794. if (h > UCHAR_MAX || (pbuf - buf2) < l) {
  1795. buf2[--l] = '\0';
  1796. break;
  1797. }
  1798. prmt_ptr++;
  1799. }
  1800. c = (char)strtoul(buf2, NULL, 16);
  1801. if (c == 0)
  1802. c = '?';
  1803. pbuf = cbuf;
  1804. break;
  1805. }
  1806. case '[': case ']':
  1807. if (c == flg_not_length) {
  1808. /* Toggle '['/']' hex 5b/5d */
  1809. flg_not_length ^= 6;
  1810. continue;
  1811. }
  1812. break;
  1813. } /* switch */
  1814. } /* if */
  1815. } /* if */
  1816. cbuf[0] = c;
  1817. {
  1818. int n = strlen(pbuf);
  1819. prmt_size += n;
  1820. if (c == '\n')
  1821. cmdedit_prmt_len = 0;
  1822. else if (flg_not_length != ']') {
  1823. #if 0 /*ENABLE_UNICODE_SUPPORT*/
  1824. /* Won't work, pbuf is one BYTE string here instead of an one Unicode char string. */
  1825. /* FIXME */
  1826. cmdedit_prmt_len += unicode_strwidth(pbuf);
  1827. #else
  1828. cmdedit_prmt_len += n;
  1829. #endif
  1830. }
  1831. }
  1832. prmt_mem_ptr = strcat(xrealloc(prmt_mem_ptr, prmt_size+1), pbuf);
  1833. free(free_me);
  1834. } /* while */
  1835. # if ENABLE_USERNAME_OR_HOMEDIR
  1836. if (cwd_buf != (char *)bb_msg_unknown)
  1837. free(cwd_buf);
  1838. # endif
  1839. /* see comment (above this function) about multiline prompt redrawing */
  1840. cmdedit_prompt = prompt_last_line = prmt_mem_ptr;
  1841. prmt_ptr = strrchr(cmdedit_prompt, '\n');
  1842. if (prmt_ptr)
  1843. prompt_last_line = prmt_ptr + 1;
  1844. put_prompt();
  1845. }
  1846. #endif
  1847. #if ENABLE_FEATURE_EDITING_WINCH
  1848. static void cmdedit_setwidth(void)
  1849. {
  1850. int new_y;
  1851. cmdedit_termw = get_terminal_width(STDIN_FILENO);
  1852. /* new y for current cursor */
  1853. new_y = (cursor + cmdedit_prmt_len) / cmdedit_termw;
  1854. /* redraw */
  1855. redraw((new_y >= cmdedit_y ? new_y : cmdedit_y), command_len - cursor);
  1856. }
  1857. static void win_changed(int nsig UNUSED_PARAM)
  1858. {
  1859. if (S.ok_to_redraw) {
  1860. /* We are in read_key(), safe to redraw immediately */
  1861. int sv_errno = errno;
  1862. cmdedit_setwidth();
  1863. fflush_all();
  1864. errno = sv_errno;
  1865. } else {
  1866. /* Signal main loop that redraw is necessary */
  1867. S.SIGWINCH_count++;
  1868. }
  1869. }
  1870. #endif
  1871. static int lineedit_read_key(char *read_key_buffer, int timeout)
  1872. {
  1873. int64_t ic;
  1874. #if ENABLE_UNICODE_SUPPORT
  1875. char unicode_buf[MB_CUR_MAX + 1];
  1876. int unicode_idx = 0;
  1877. #endif
  1878. fflush_all();
  1879. while (1) {
  1880. /* Wait for input. TIMEOUT = -1 makes read_key wait even
  1881. * on nonblocking stdin, TIMEOUT = 50 makes sure we won't
  1882. * insist on full MB_CUR_MAX buffer to declare input like
  1883. * "\xff\n",pause,"ls\n" invalid and thus won't lose "ls".
  1884. *
  1885. * Note: read_key sets errno to 0 on success.
  1886. */
  1887. IF_FEATURE_EDITING_WINCH(S.ok_to_redraw = 1;)
  1888. ic = read_key(STDIN_FILENO, read_key_buffer, timeout);
  1889. IF_FEATURE_EDITING_WINCH(S.ok_to_redraw = 0;)
  1890. if (errno) {
  1891. #if ENABLE_UNICODE_SUPPORT
  1892. if (errno == EAGAIN && unicode_idx != 0)
  1893. goto pushback;
  1894. #endif
  1895. break;
  1896. }
  1897. #if ENABLE_FEATURE_EDITING_ASK_TERMINAL
  1898. if ((int32_t)ic == KEYCODE_CURSOR_POS
  1899. && S.sent_ESC_br6n
  1900. ) {
  1901. S.sent_ESC_br6n = 0;
  1902. if (cursor == 0) { /* otherwise it may be bogus */
  1903. int col = ((ic >> 32) & 0x7fff) - 1;
  1904. /*
  1905. * Is col > cmdedit_prmt_len?
  1906. * If yes (terminal says cursor is farther to the right
  1907. * of where we think it should be),
  1908. * the prompt wasn't printed starting at col 1,
  1909. * there was additional text before it.
  1910. */
  1911. if ((int)(col - cmdedit_prmt_len) > 0) {
  1912. /* Fix our understanding of current x position */
  1913. cmdedit_x += (col - cmdedit_prmt_len);
  1914. while (cmdedit_x >= cmdedit_termw) {
  1915. cmdedit_x -= cmdedit_termw;
  1916. cmdedit_y++;
  1917. }
  1918. }
  1919. }
  1920. continue;
  1921. }
  1922. #endif
  1923. #if ENABLE_UNICODE_SUPPORT
  1924. if (unicode_status == UNICODE_ON) {
  1925. wchar_t wc;
  1926. if ((int32_t)ic < 0) /* KEYCODE_xxx */
  1927. break;
  1928. // TODO: imagine sequence like: 0xff,<left-arrow>: we are currently losing 0xff...
  1929. unicode_buf[unicode_idx++] = ic;
  1930. unicode_buf[unicode_idx] = '\0';
  1931. if (mbstowcs(&wc, unicode_buf, 1) != 1) {
  1932. /* Not (yet?) a valid unicode char */
  1933. if (unicode_idx < MB_CUR_MAX) {
  1934. timeout = 50;
  1935. continue;
  1936. }
  1937. pushback:
  1938. /* Invalid sequence. Save all "bad bytes" except first */
  1939. read_key_ungets(read_key_buffer, unicode_buf + 1, unicode_idx - 1);
  1940. # if !ENABLE_UNICODE_PRESERVE_BROKEN
  1941. ic = CONFIG_SUBST_WCHAR;
  1942. # else
  1943. ic = unicode_mark_raw_byte(unicode_buf[0]);
  1944. # endif
  1945. } else {
  1946. /* Valid unicode char, return its code */
  1947. ic = wc;
  1948. }
  1949. }
  1950. #endif
  1951. break;
  1952. }
  1953. return ic;
  1954. }
  1955. #if ENABLE_UNICODE_BIDI_SUPPORT
  1956. static int isrtl_str(void)
  1957. {
  1958. int idx = cursor;
  1959. while (idx < command_len && unicode_bidi_is_neutral_wchar(command_ps[idx]))
  1960. idx++;
  1961. return unicode_bidi_isrtl(command_ps[idx]);
  1962. }
  1963. #else
  1964. # define isrtl_str() 0
  1965. #endif
  1966. /* leave out the "vi-mode"-only case labels if vi editing isn't
  1967. * configured. */
  1968. #define vi_case(caselabel) IF_FEATURE_EDITING_VI(case caselabel)
  1969. /* convert uppercase ascii to equivalent control char, for readability */
  1970. #undef CTRL
  1971. #define CTRL(a) ((a) & ~0x40)
  1972. enum {
  1973. VI_CMDMODE_BIT = 0x40000000,
  1974. /* 0x80000000 bit flags KEYCODE_xxx */
  1975. };
  1976. #if ENABLE_FEATURE_REVERSE_SEARCH
  1977. /* Mimic readline Ctrl-R reverse history search.
  1978. * When invoked, it shows the following prompt:
  1979. * (reverse-i-search)'': user_input [cursor pos unchanged by Ctrl-R]
  1980. * and typing results in search being performed:
  1981. * (reverse-i-search)'tmp': cd /tmp [cursor under t in /tmp]
  1982. * Search is performed by looking at progressively older lines in history.
  1983. * Ctrl-R again searches for the next match in history.
  1984. * Backspace deletes last matched char.
  1985. * Control keys exit search and return to normal editing (at current history line).
  1986. */
  1987. static int32_t reverse_i_search(int timeout)
  1988. {
  1989. char match_buf[128]; /* for user input */
  1990. char read_key_buffer[KEYCODE_BUFFER_SIZE];
  1991. const char *matched_history_line;
  1992. const char *saved_prompt;
  1993. unsigned saved_prmt_len;
  1994. int32_t ic;
  1995. matched_history_line = NULL;
  1996. read_key_buffer[0] = 0;
  1997. match_buf[0] = '\0';
  1998. /* Save and replace the prompt */
  1999. saved_prompt = prompt_last_line;
  2000. saved_prmt_len = cmdedit_prmt_len;
  2001. goto set_prompt;
  2002. while (1) {
  2003. int h;
  2004. unsigned match_buf_len = strlen(match_buf);
  2005. //FIXME: correct timeout? (i.e. count it down?)
  2006. ic = lineedit_read_key(read_key_buffer, timeout);
  2007. switch (ic) {
  2008. case CTRL('R'): /* searching for the next match */
  2009. break;
  2010. case '\b':
  2011. case '\x7f':
  2012. /* Backspace */
  2013. if (unicode_status == UNICODE_ON) {
  2014. while (match_buf_len != 0) {
  2015. uint8_t c = match_buf[--match_buf_len];
  2016. if ((c & 0xc0) != 0x80) /* start of UTF-8 char? */
  2017. break; /* yes */
  2018. }
  2019. } else {
  2020. if (match_buf_len != 0)
  2021. match_buf_len--;
  2022. }
  2023. match_buf[match_buf_len] = '\0';
  2024. break;
  2025. default:
  2026. if (ic < ' '
  2027. || (!ENABLE_UNICODE_SUPPORT && ic >= 256)
  2028. || (ENABLE_UNICODE_SUPPORT && ic >= VI_CMDMODE_BIT)
  2029. ) {
  2030. goto ret;
  2031. }
  2032. /* Append this char */
  2033. #if ENABLE_UNICODE_SUPPORT
  2034. if (unicode_status == UNICODE_ON) {
  2035. mbstate_t mbstate = { 0 };
  2036. char buf[MB_CUR_MAX + 1];
  2037. int len = wcrtomb(buf, ic, &mbstate);
  2038. if (len > 0) {
  2039. buf[len] = '\0';
  2040. if (match_buf_len + len < sizeof(match_buf))
  2041. strcpy(match_buf + match_buf_len, buf);
  2042. }
  2043. } else
  2044. #endif
  2045. if (match_buf_len < sizeof(match_buf) - 1) {
  2046. match_buf[match_buf_len] = ic;
  2047. match_buf[match_buf_len + 1] = '\0';
  2048. }
  2049. break;
  2050. } /* switch (ic) */
  2051. /* Search in history for match_buf */
  2052. h = state->cur_history;
  2053. if (ic == CTRL('R'))
  2054. h--;
  2055. while (h >= 0) {
  2056. if (state->history[h]) {
  2057. char *match = strstr(state->history[h], match_buf);
  2058. if (match) {
  2059. state->cur_history = h;
  2060. matched_history_line = state->history[h];
  2061. command_len = load_string(matched_history_line);
  2062. cursor = match - matched_history_line;
  2063. //FIXME: cursor position for Unicode case
  2064. free((char*)prompt_last_line);
  2065. set_prompt:
  2066. prompt_last_line = xasprintf("(reverse-i-search)'%s': ", match_buf);
  2067. cmdedit_prmt_len = unicode_strwidth(prompt_last_line);
  2068. goto do_redraw;
  2069. }
  2070. }
  2071. h--;
  2072. }
  2073. /* Not found */
  2074. match_buf[match_buf_len] = '\0';
  2075. beep();
  2076. continue;
  2077. do_redraw:
  2078. redraw(cmdedit_y, command_len - cursor);
  2079. } /* while (1) */
  2080. ret:
  2081. if (matched_history_line)
  2082. command_len = load_string(matched_history_line);
  2083. free((char*)prompt_last_line);
  2084. prompt_last_line = saved_prompt;
  2085. cmdedit_prmt_len = saved_prmt_len;
  2086. redraw(cmdedit_y, command_len - cursor);
  2087. return ic;
  2088. }
  2089. #endif
  2090. #if ENABLE_FEATURE_EDITING_WINCH
  2091. static void sigaction2(int sig, struct sigaction *act)
  2092. {
  2093. // Grr... gcc 8.1.1:
  2094. // "passing argument 3 to restrict-qualified parameter aliases with argument 2"
  2095. // dance around that...
  2096. struct sigaction *oact FIX_ALIASING;
  2097. oact = act;
  2098. sigaction(sig, act, oact);
  2099. }
  2100. #endif
  2101. /* maxsize must be >= 2.
  2102. * Returns:
  2103. * -1 on read errors or EOF, or on bare Ctrl-D,
  2104. * 0 on ctrl-C (the line entered is still returned in 'command'),
  2105. * (in both cases the cursor remains on the input line, '\n' is not printed)
  2106. * >0 length of input string, including terminating '\n'
  2107. */
  2108. int FAST_FUNC read_line_input(line_input_t *st, const char *prompt, char *command, int maxsize)
  2109. {
  2110. int len, n;
  2111. int timeout;
  2112. #if ENABLE_FEATURE_TAB_COMPLETION
  2113. smallint lastWasTab = 0;
  2114. #endif
  2115. smallint break_out = 0;
  2116. #if ENABLE_FEATURE_EDITING_VI
  2117. smallint vi_cmdmode = 0;
  2118. #endif
  2119. struct termios initial_settings;
  2120. struct termios new_settings;
  2121. char read_key_buffer[KEYCODE_BUFFER_SIZE];
  2122. INIT_S();
  2123. n = get_termios_and_make_raw(STDIN_FILENO, &new_settings, &initial_settings, 0
  2124. | TERMIOS_CLEAR_ISIG /* turn off INTR (ctrl-C), QUIT, SUSP */
  2125. );
  2126. if (n != 0 || (initial_settings.c_lflag & (ECHO|ICANON)) == ICANON) {
  2127. /* Happens when e.g. stty -echo was run before.
  2128. * But if ICANON is not set, we don't come here.
  2129. * (example: interactive python ^Z-backgrounded,
  2130. * tty is still in "raw mode").
  2131. */
  2132. parse_and_put_prompt(prompt);
  2133. fflush_all();
  2134. if (fgets(command, maxsize, stdin) == NULL)
  2135. len = -1; /* EOF or error */
  2136. else
  2137. len = strlen(command);
  2138. DEINIT_S();
  2139. return len;
  2140. }
  2141. init_unicode();
  2142. // FIXME: audit & improve this
  2143. if (maxsize > MAX_LINELEN)
  2144. maxsize = MAX_LINELEN;
  2145. S.maxsize = maxsize;
  2146. timeout = -1;
  2147. /* Make state->flags == 0 if st is NULL.
  2148. * With zeroed flags, no other fields are ever referenced.
  2149. */
  2150. state = (line_input_t*) &const_int_0;
  2151. if (st) {
  2152. state = st;
  2153. timeout = st->timeout;
  2154. }
  2155. #if MAX_HISTORY > 0
  2156. # if ENABLE_FEATURE_EDITING_SAVEHISTORY
  2157. if (state->hist_file)
  2158. if (state->cnt_history == 0)
  2159. load_history(state);
  2160. # endif
  2161. if (state->flags & DO_HISTORY)
  2162. state->cur_history = state->cnt_history;
  2163. #endif
  2164. /* prepare before init handlers */
  2165. cmdedit_y = 0; /* quasireal y, not true if line > xt*yt */
  2166. command_len = 0;
  2167. #if ENABLE_UNICODE_SUPPORT
  2168. command_ps = xzalloc(maxsize * sizeof(command_ps[0]));
  2169. #else
  2170. command_ps = command;
  2171. command[0] = '\0';
  2172. #endif
  2173. #define command command_must_not_be_used
  2174. tcsetattr_stdin_TCSANOW(&new_settings);
  2175. #if ENABLE_USERNAME_OR_HOMEDIR
  2176. {
  2177. struct passwd *entry;
  2178. entry = getpwuid(geteuid());
  2179. if (entry) {
  2180. user_buf = xstrdup(entry->pw_name);
  2181. home_pwd_buf = xstrdup(entry->pw_dir);
  2182. }
  2183. }
  2184. #endif
  2185. #if 0
  2186. for (i = 0; i <= state->max_history; i++)
  2187. bb_error_msg("history[%d]:'%s'", i, state->history[i]);
  2188. bb_error_msg("cur_history:%d cnt_history:%d", state->cur_history, state->cnt_history);
  2189. #endif
  2190. /* Get width (before printing prompt) */
  2191. cmdedit_termw = get_terminal_width(STDIN_FILENO);
  2192. /* Print out the command prompt, optionally ask where cursor is */
  2193. parse_and_put_prompt(prompt);
  2194. ask_terminal();
  2195. #if ENABLE_FEATURE_EDITING_WINCH
  2196. /* Install window resize handler (NB: after *all* init is complete) */
  2197. S.SIGWINCH_handler.sa_handler = win_changed;
  2198. S.SIGWINCH_handler.sa_flags = SA_RESTART;
  2199. sigaction2(SIGWINCH, &S.SIGWINCH_handler);
  2200. #endif
  2201. read_key_buffer[0] = 0;
  2202. while (1) {
  2203. /*
  2204. * The emacs and vi modes share much of the code in the big
  2205. * command loop. Commands entered when in vi's command mode
  2206. * (aka "escape mode") get an extra bit added to distinguish
  2207. * them - this keeps them from being self-inserted. This
  2208. * clutters the big switch a bit, but keeps all the code
  2209. * in one place.
  2210. */
  2211. int32_t ic, ic_raw;
  2212. #if ENABLE_FEATURE_EDITING_WINCH
  2213. unsigned count;
  2214. count = S.SIGWINCH_count;
  2215. if (S.SIGWINCH_saved != count) {
  2216. S.SIGWINCH_saved = count;
  2217. cmdedit_setwidth();
  2218. }
  2219. #endif
  2220. ic = ic_raw = lineedit_read_key(read_key_buffer, timeout);
  2221. #if ENABLE_FEATURE_REVERSE_SEARCH
  2222. again:
  2223. #endif
  2224. #if ENABLE_FEATURE_EDITING_VI
  2225. newdelflag = 1;
  2226. if (vi_cmdmode) {
  2227. /* btw, since KEYCODE_xxx are all < 0, this doesn't
  2228. * change ic if it contains one of them: */
  2229. ic |= VI_CMDMODE_BIT;
  2230. }
  2231. #endif
  2232. switch (ic) {
  2233. case '\n':
  2234. case '\r':
  2235. vi_case('\n'|VI_CMDMODE_BIT:)
  2236. vi_case('\r'|VI_CMDMODE_BIT:)
  2237. /* Enter */
  2238. goto_new_line();
  2239. break_out = 1;
  2240. break;
  2241. case CTRL('A'):
  2242. vi_case('0'|VI_CMDMODE_BIT:)
  2243. /* Control-a -- Beginning of line */
  2244. input_backward(cursor);
  2245. break;
  2246. case CTRL('B'):
  2247. vi_case('h'|VI_CMDMODE_BIT:)
  2248. vi_case('\b'|VI_CMDMODE_BIT:) /* ^H */
  2249. vi_case('\x7f'|VI_CMDMODE_BIT:) /* DEL */
  2250. input_backward(1); /* Move back one character */
  2251. break;
  2252. case CTRL('E'):
  2253. vi_case('$'|VI_CMDMODE_BIT:)
  2254. /* Control-e -- End of line */
  2255. put_till_end_and_adv_cursor();
  2256. break;
  2257. case CTRL('F'):
  2258. vi_case('l'|VI_CMDMODE_BIT:)
  2259. vi_case(' '|VI_CMDMODE_BIT:)
  2260. input_forward(); /* Move forward one character */
  2261. break;
  2262. case '\b': /* ^H */
  2263. case '\x7f': /* DEL */
  2264. if (!isrtl_str())
  2265. input_backspace();
  2266. else
  2267. input_delete(0);
  2268. break;
  2269. case KEYCODE_DELETE:
  2270. if (!isrtl_str())
  2271. input_delete(0);
  2272. else
  2273. input_backspace();
  2274. break;
  2275. #if ENABLE_FEATURE_TAB_COMPLETION
  2276. case '\t':
  2277. input_tab(&lastWasTab);
  2278. break;
  2279. #endif
  2280. case CTRL('K'):
  2281. /* Control-k -- clear to end of line */
  2282. command_ps[cursor] = BB_NUL;
  2283. command_len = cursor;
  2284. printf(SEQ_CLEAR_TILL_END_OF_SCREEN);
  2285. break;
  2286. case CTRL('L'):
  2287. vi_case(CTRL('L')|VI_CMDMODE_BIT:)
  2288. /* Control-l -- clear screen */
  2289. /* cursor to top,left; clear to the end of screen */
  2290. printf(ESC"[H" ESC"[J");
  2291. draw_full(command_len - cursor);
  2292. break;
  2293. #if MAX_HISTORY > 0
  2294. case CTRL('N'):
  2295. vi_case(CTRL('N')|VI_CMDMODE_BIT:)
  2296. vi_case('j'|VI_CMDMODE_BIT:)
  2297. /* Control-n -- Get next command in history */
  2298. if (get_next_history())
  2299. goto rewrite_line;
  2300. break;
  2301. case CTRL('P'):
  2302. vi_case(CTRL('P')|VI_CMDMODE_BIT:)
  2303. vi_case('k'|VI_CMDMODE_BIT:)
  2304. /* Control-p -- Get previous command from history */
  2305. if (get_previous_history())
  2306. goto rewrite_line;
  2307. break;
  2308. #endif
  2309. case CTRL('U'):
  2310. vi_case(CTRL('U')|VI_CMDMODE_BIT:)
  2311. /* Control-U -- Clear line before cursor */
  2312. if (cursor) {
  2313. command_len -= cursor;
  2314. memmove(command_ps, command_ps + cursor,
  2315. (command_len + 1) * sizeof(command_ps[0]));
  2316. redraw(cmdedit_y, command_len);
  2317. }
  2318. break;
  2319. case CTRL('W'):
  2320. vi_case(CTRL('W')|VI_CMDMODE_BIT:)
  2321. /* Control-W -- Remove the last word */
  2322. while (cursor > 0 && BB_isspace(command_ps[cursor-1]))
  2323. input_backspace();
  2324. while (cursor > 0 && !BB_isspace(command_ps[cursor-1]))
  2325. input_backspace();
  2326. break;
  2327. case KEYCODE_ALT_D: {
  2328. /* Delete word forward */
  2329. int nc, sc = cursor;
  2330. ctrl_right();
  2331. nc = cursor - sc;
  2332. input_backward(nc);
  2333. while (--nc >= 0)
  2334. input_delete(1);
  2335. break;
  2336. }
  2337. case KEYCODE_ALT_BACKSPACE: {
  2338. /* Delete word backward */
  2339. int sc = cursor;
  2340. ctrl_left();
  2341. while (sc-- > cursor)
  2342. input_delete(1);
  2343. break;
  2344. }
  2345. #if ENABLE_FEATURE_REVERSE_SEARCH
  2346. case CTRL('R'):
  2347. ic = ic_raw = reverse_i_search(timeout);
  2348. goto again;
  2349. #endif
  2350. #if ENABLE_FEATURE_EDITING_VI
  2351. case 'i'|VI_CMDMODE_BIT:
  2352. vi_cmdmode = 0;
  2353. break;
  2354. case 'I'|VI_CMDMODE_BIT:
  2355. input_backward(cursor);
  2356. vi_cmdmode = 0;
  2357. break;
  2358. case 'a'|VI_CMDMODE_BIT:
  2359. input_forward();
  2360. vi_cmdmode = 0;
  2361. break;
  2362. case 'A'|VI_CMDMODE_BIT:
  2363. put_till_end_and_adv_cursor();
  2364. vi_cmdmode = 0;
  2365. break;
  2366. case 'x'|VI_CMDMODE_BIT:
  2367. input_delete(1);
  2368. break;
  2369. case 'X'|VI_CMDMODE_BIT:
  2370. if (cursor > 0) {
  2371. input_backward(1);
  2372. input_delete(1);
  2373. }
  2374. break;
  2375. case 'W'|VI_CMDMODE_BIT:
  2376. vi_Word_motion(1);
  2377. break;
  2378. case 'w'|VI_CMDMODE_BIT:
  2379. vi_word_motion(1);
  2380. break;
  2381. case 'E'|VI_CMDMODE_BIT:
  2382. vi_End_motion();
  2383. break;
  2384. case 'e'|VI_CMDMODE_BIT:
  2385. vi_end_motion();
  2386. break;
  2387. case 'B'|VI_CMDMODE_BIT:
  2388. vi_Back_motion();
  2389. break;
  2390. case 'b'|VI_CMDMODE_BIT:
  2391. vi_back_motion();
  2392. break;
  2393. case 'C'|VI_CMDMODE_BIT:
  2394. vi_cmdmode = 0;
  2395. /* fall through */
  2396. case 'D'|VI_CMDMODE_BIT:
  2397. goto clear_to_eol;
  2398. case 'c'|VI_CMDMODE_BIT:
  2399. vi_cmdmode = 0;
  2400. /* fall through */
  2401. case 'd'|VI_CMDMODE_BIT: {
  2402. int nc, sc;
  2403. ic = lineedit_read_key(read_key_buffer, timeout);
  2404. if (errno) /* error */
  2405. goto return_error_indicator;
  2406. if (ic == ic_raw) { /* "cc", "dd" */
  2407. input_backward(cursor);
  2408. goto clear_to_eol;
  2409. break;
  2410. }
  2411. sc = cursor;
  2412. switch (ic) {
  2413. case 'w':
  2414. case 'W':
  2415. case 'e':
  2416. case 'E':
  2417. switch (ic) {
  2418. case 'w': /* "dw", "cw" */
  2419. vi_word_motion(vi_cmdmode);
  2420. break;
  2421. case 'W': /* 'dW', 'cW' */
  2422. vi_Word_motion(vi_cmdmode);
  2423. break;
  2424. case 'e': /* 'de', 'ce' */
  2425. vi_end_motion();
  2426. input_forward();
  2427. break;
  2428. case 'E': /* 'dE', 'cE' */
  2429. vi_End_motion();
  2430. input_forward();
  2431. break;
  2432. }
  2433. nc = cursor;
  2434. input_backward(cursor - sc);
  2435. while (nc-- > cursor)
  2436. input_delete(1);
  2437. break;
  2438. case 'b': /* "db", "cb" */
  2439. case 'B': /* implemented as B */
  2440. if (ic == 'b')
  2441. vi_back_motion();
  2442. else
  2443. vi_Back_motion();
  2444. while (sc-- > cursor)
  2445. input_delete(1);
  2446. break;
  2447. case ' ': /* "d ", "c " */
  2448. input_delete(1);
  2449. break;
  2450. case '$': /* "d$", "c$" */
  2451. clear_to_eol:
  2452. while (cursor < command_len)
  2453. input_delete(1);
  2454. break;
  2455. }
  2456. break;
  2457. }
  2458. case 'p'|VI_CMDMODE_BIT:
  2459. input_forward();
  2460. /* fallthrough */
  2461. case 'P'|VI_CMDMODE_BIT:
  2462. put();
  2463. break;
  2464. case 'r'|VI_CMDMODE_BIT:
  2465. //FIXME: unicode case?
  2466. ic = lineedit_read_key(read_key_buffer, timeout);
  2467. if (errno) /* error */
  2468. goto return_error_indicator;
  2469. if (ic < ' ' || ic > 255) {
  2470. beep();
  2471. } else {
  2472. command_ps[cursor] = ic;
  2473. bb_putchar(ic);
  2474. bb_putchar('\b');
  2475. }
  2476. break;
  2477. case '\x1b': /* ESC */
  2478. if (state->flags & VI_MODE) {
  2479. /* insert mode --> command mode */
  2480. vi_cmdmode = 1;
  2481. input_backward(1);
  2482. }
  2483. break;
  2484. #endif /* FEATURE_COMMAND_EDITING_VI */
  2485. #if MAX_HISTORY > 0
  2486. case KEYCODE_UP:
  2487. if (get_previous_history())
  2488. goto rewrite_line;
  2489. beep();
  2490. break;
  2491. case KEYCODE_DOWN:
  2492. if (!get_next_history())
  2493. break;
  2494. rewrite_line:
  2495. /* Rewrite the line with the selected history item */
  2496. /* change command */
  2497. command_len = load_string(state->history[state->cur_history] ?
  2498. state->history[state->cur_history] : "");
  2499. /* redraw and go to eol (bol, in vi) */
  2500. redraw(cmdedit_y, (state->flags & VI_MODE) ? 9999 : 0);
  2501. break;
  2502. #endif
  2503. case KEYCODE_RIGHT:
  2504. input_forward();
  2505. break;
  2506. case KEYCODE_LEFT:
  2507. input_backward(1);
  2508. break;
  2509. case KEYCODE_CTRL_LEFT:
  2510. case KEYCODE_ALT_LEFT: /* bash doesn't do it */
  2511. ctrl_left();
  2512. break;
  2513. case KEYCODE_CTRL_RIGHT:
  2514. case KEYCODE_ALT_RIGHT: /* bash doesn't do it */
  2515. ctrl_right();
  2516. break;
  2517. case KEYCODE_HOME:
  2518. input_backward(cursor);
  2519. break;
  2520. case KEYCODE_END:
  2521. put_till_end_and_adv_cursor();
  2522. break;
  2523. default:
  2524. if (initial_settings.c_cc[VINTR] != 0
  2525. && ic_raw == initial_settings.c_cc[VINTR]
  2526. ) {
  2527. /* Ctrl-C (usually) - stop gathering input */
  2528. command_len = 0;
  2529. break_out = -1; /* "do not append '\n'" */
  2530. break;
  2531. }
  2532. if (initial_settings.c_cc[VEOF] != 0
  2533. && ic_raw == initial_settings.c_cc[VEOF]
  2534. ) {
  2535. /* Ctrl-D (usually) - delete one character,
  2536. * or exit if len=0 and no chars to delete */
  2537. if (command_len == 0) {
  2538. errno = 0;
  2539. case -1: /* error (e.g. EIO when tty is destroyed) */
  2540. IF_FEATURE_EDITING_VI(return_error_indicator:)
  2541. break_out = command_len = -1;
  2542. break;
  2543. }
  2544. input_delete(0);
  2545. break;
  2546. }
  2547. // /* Control-V -- force insert of next char */
  2548. // if (c == CTRL('V')) {
  2549. // if (safe_read(STDIN_FILENO, &c, 1) < 1)
  2550. // goto return_error_indicator;
  2551. // if (c == 0) {
  2552. // beep();
  2553. // break;
  2554. // }
  2555. // }
  2556. if (ic < ' '
  2557. || (!ENABLE_UNICODE_SUPPORT && ic >= 256)
  2558. || (ENABLE_UNICODE_SUPPORT && ic >= VI_CMDMODE_BIT)
  2559. ) {
  2560. /* If VI_CMDMODE_BIT is set, ic is >= 256
  2561. * and vi mode ignores unexpected chars.
  2562. * Otherwise, we are here if ic is a
  2563. * control char or an unhandled ESC sequence,
  2564. * which is also ignored.
  2565. */
  2566. break;
  2567. }
  2568. if ((int)command_len >= (maxsize - 2)) {
  2569. /* Not enough space for the char and EOL */
  2570. break;
  2571. }
  2572. command_len++;
  2573. if (cursor == (command_len - 1)) {
  2574. /* We are at the end, append */
  2575. command_ps[cursor] = ic;
  2576. command_ps[cursor + 1] = BB_NUL;
  2577. put_cur_glyph_and_inc_cursor();
  2578. if (unicode_bidi_isrtl(ic))
  2579. input_backward(1);
  2580. } else {
  2581. /* In the middle, insert */
  2582. int sc = cursor;
  2583. memmove(command_ps + sc + 1, command_ps + sc,
  2584. (command_len - sc) * sizeof(command_ps[0]));
  2585. command_ps[sc] = ic;
  2586. /* is right-to-left char, or neutral one (e.g. comma) was just added to rtl text? */
  2587. if (!isrtl_str())
  2588. sc++; /* no */
  2589. put_till_end_and_adv_cursor();
  2590. /* to prev x pos + 1 */
  2591. input_backward(cursor - sc);
  2592. }
  2593. break;
  2594. } /* switch (ic) */
  2595. if (break_out)
  2596. break;
  2597. #if ENABLE_FEATURE_TAB_COMPLETION
  2598. if (ic_raw != '\t')
  2599. lastWasTab = 0;
  2600. #endif
  2601. } /* while (1) */
  2602. #if ENABLE_FEATURE_EDITING_ASK_TERMINAL
  2603. if (S.sent_ESC_br6n) {
  2604. /* "sleep 1; busybox ash" + hold [Enter] to trigger.
  2605. * We sent "ESC [ 6 n", but got '\n' first, and
  2606. * KEYCODE_CURSOR_POS response is now buffered from terminal.
  2607. * It's bad already and not much can be done with it
  2608. * (it _will_ be visible for the next process to read stdin),
  2609. * but without this delay it even shows up on the screen
  2610. * as garbage because we restore echo settings with tcsetattr
  2611. * before it comes in. UGLY!
  2612. */
  2613. usleep(20*1000);
  2614. }
  2615. #endif
  2616. /* End of bug-catching "command_must_not_be_used" trick */
  2617. #undef command
  2618. #if ENABLE_UNICODE_SUPPORT
  2619. command[0] = '\0';
  2620. if (command_len > 0)
  2621. command_len = save_string(command, maxsize - 1);
  2622. free(command_ps);
  2623. #endif
  2624. if (command_len > 0) {
  2625. remember_in_history(command);
  2626. }
  2627. if (break_out > 0) {
  2628. command[command_len++] = '\n';
  2629. command[command_len] = '\0';
  2630. }
  2631. #if ENABLE_FEATURE_TAB_COMPLETION
  2632. free_tab_completion_data();
  2633. #endif
  2634. /* restore initial_settings */
  2635. tcsetattr_stdin_TCSANOW(&initial_settings);
  2636. #if ENABLE_FEATURE_EDITING_WINCH
  2637. /* restore SIGWINCH handler */
  2638. sigaction_set(SIGWINCH, &S.SIGWINCH_handler);
  2639. #endif
  2640. fflush_all();
  2641. len = command_len;
  2642. DEINIT_S();
  2643. return len; /* can't return command_len, DEINIT_S() destroys it */
  2644. }
  2645. #else /* !FEATURE_EDITING */
  2646. #undef read_line_input
  2647. int FAST_FUNC read_line_input(const char* prompt, char* command, int maxsize)
  2648. {
  2649. fputs(prompt, stdout);
  2650. fflush_all();
  2651. if (!fgets(command, maxsize, stdin))
  2652. return -1;
  2653. return strlen(command);
  2654. }
  2655. #endif /* !FEATURE_EDITING */
  2656. /*
  2657. * Testing
  2658. */
  2659. #ifdef TEST
  2660. #include <locale.h>
  2661. const char *applet_name = "debug stuff usage";
  2662. int main(int argc, char **argv)
  2663. {
  2664. char buff[MAX_LINELEN];
  2665. char *prompt =
  2666. #if ENABLE_FEATURE_EDITING_FANCY_PROMPT
  2667. "\\[\\033[32;1m\\]\\u@\\[\\x1b[33;1m\\]\\h:"
  2668. "\\[\\033[34;1m\\]\\w\\[\\033[35;1m\\] "
  2669. "\\!\\[\\e[36;1m\\]\\$ \\[\\E[m\\]";
  2670. #else
  2671. "% ";
  2672. #endif
  2673. while (1) {
  2674. int l;
  2675. l = read_line_input(prompt, buff);
  2676. if (l <= 0 || buff[l-1] != '\n')
  2677. break;
  2678. buff[l-1] = '\0';
  2679. printf("*** read_line_input() returned line =%s=\n", buff);
  2680. }
  2681. printf("*** read_line_input() detect ^D\n");
  2682. return 0;
  2683. }
  2684. #endif /* TEST */