lineedit.c 73 KB

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