lineedit.c 65 KB

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