lineedit.c 74 KB

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