lineedit.c 70 KB

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