3
0

lineedit.c 67 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091929394959697989910010110210310410510610710810911011111211311411511611711811912012112212312412512612712812913013113213313413513613713813914014114214314414514614714814915015115215315415515615715815916016116216316416516616716816917017117217317417517617717817918018118218318418518618718818919019119219319419519619719819920020120220320420520620720820921021121221321421521621721821922022122222322422522622722822923023123223323423523623723823924024124224324424524624724824925025125225325425525625725825926026126226326426526626726826927027127227327427527627727827928028128228328428528628728828929029129229329429529629729829930030130230330430530630730830931031131231331431531631731831932032132232332432532632732832933033133233333433533633733833934034134234334434534634734834935035135235335435535635735835936036136236336436536636736836937037137237337437537637737837938038138238338438538638738838939039139239339439539639739839940040140240340440540640740840941041141241341441541641741841942042142242342442542642742842943043143243343443543643743843944044144244344444544644744844945045145245345445545645745845946046146246346446546646746846947047147247347447547647747847948048148248348448548648748848949049149249349449549649749849950050150250350450550650750850951051151251351451551651751851952052152252352452552652752852953053153253353453553653753853954054154254354454554654754854955055155255355455555655755855956056156256356456556656756856957057157257357457557657757857958058158258358458558658758858959059159259359459559659759859960060160260360460560660760860961061161261361461561661761861962062162262362462562662762862963063163263363463563663763863964064164264364464564664764864965065165265365465565665765865966066166266366466566666766866967067167267367467567667767867968068168268368468568668768868969069169269369469569669769869970070170270370470570670770870971071171271371471571671771871972072172272372472572672772872973073173273373473573673773873974074174274374474574674774874975075175275375475575675775875976076176276376476576676776876977077177277377477577677777877978078178278378478578678778878979079179279379479579679779879980080180280380480580680780880981081181281381481581681781881982082182282382482582682782882983083183283383483583683783883984084184284384484584684784884985085185285385485585685785885986086186286386486586686786886987087187287387487587687787887988088188288388488588688788888989089189289389489589689789889990090190290390490590690790890991091191291391491591691791891992092192292392492592692792892993093193293393493593693793893994094194294394494594694794894995095195295395495595695795895996096196296396496596696796896997097197297397497597697797897998098198298398498598698798898999099199299399499599699799899910001001100210031004100510061007100810091010101110121013101410151016101710181019102010211022102310241025102610271028102910301031103210331034103510361037103810391040104110421043104410451046104710481049105010511052105310541055105610571058105910601061106210631064106510661067106810691070107110721073107410751076107710781079108010811082108310841085108610871088108910901091109210931094109510961097109810991100110111021103110411051106110711081109111011111112111311141115111611171118111911201121112211231124112511261127112811291130113111321133113411351136113711381139114011411142114311441145114611471148114911501151115211531154115511561157115811591160116111621163116411651166116711681169117011711172117311741175117611771178117911801181118211831184118511861187118811891190119111921193119411951196119711981199120012011202120312041205120612071208120912101211121212131214121512161217121812191220122112221223122412251226122712281229123012311232123312341235123612371238123912401241124212431244124512461247124812491250125112521253125412551256125712581259126012611262126312641265126612671268126912701271127212731274127512761277127812791280128112821283128412851286128712881289129012911292129312941295129612971298129913001301130213031304130513061307130813091310131113121313131413151316131713181319132013211322132313241325132613271328132913301331133213331334133513361337133813391340134113421343134413451346134713481349135013511352135313541355135613571358135913601361136213631364136513661367136813691370137113721373137413751376137713781379138013811382138313841385138613871388138913901391139213931394139513961397139813991400140114021403140414051406140714081409141014111412141314141415141614171418141914201421142214231424142514261427142814291430143114321433143414351436143714381439144014411442144314441445144614471448144914501451145214531454145514561457145814591460146114621463146414651466146714681469147014711472147314741475147614771478147914801481148214831484148514861487148814891490149114921493149414951496149714981499150015011502150315041505150615071508150915101511151215131514151515161517151815191520152115221523152415251526152715281529153015311532153315341535153615371538153915401541154215431544154515461547154815491550155115521553155415551556155715581559156015611562156315641565156615671568156915701571157215731574157515761577157815791580158115821583158415851586158715881589159015911592159315941595159615971598159916001601160216031604160516061607160816091610161116121613161416151616161716181619162016211622162316241625162616271628162916301631163216331634163516361637163816391640164116421643164416451646164716481649165016511652165316541655165616571658165916601661166216631664166516661667166816691670167116721673167416751676167716781679168016811682168316841685168616871688168916901691169216931694169516961697169816991700170117021703170417051706170717081709171017111712171317141715171617171718171917201721172217231724172517261727172817291730173117321733173417351736173717381739174017411742174317441745174617471748174917501751175217531754175517561757175817591760176117621763176417651766176717681769177017711772177317741775177617771778177917801781178217831784178517861787178817891790179117921793179417951796179717981799180018011802180318041805180618071808180918101811181218131814181518161817181818191820182118221823182418251826182718281829183018311832183318341835183618371838183918401841184218431844184518461847184818491850185118521853185418551856185718581859186018611862186318641865186618671868186918701871187218731874187518761877187818791880188118821883188418851886188718881889189018911892189318941895189618971898189919001901190219031904190519061907190819091910191119121913191419151916191719181919192019211922192319241925192619271928192919301931193219331934193519361937193819391940194119421943194419451946194719481949195019511952195319541955195619571958195919601961196219631964196519661967196819691970197119721973197419751976197719781979198019811982198319841985198619871988198919901991199219931994199519961997199819992000200120022003200420052006200720082009201020112012201320142015201620172018201920202021202220232024202520262027202820292030203120322033203420352036203720382039204020412042204320442045204620472048204920502051205220532054205520562057205820592060206120622063206420652066206720682069207020712072207320742075207620772078207920802081208220832084208520862087208820892090209120922093209420952096209720982099210021012102210321042105210621072108210921102111211221132114211521162117211821192120212121222123212421252126212721282129213021312132213321342135213621372138213921402141214221432144214521462147214821492150215121522153215421552156215721582159216021612162216321642165216621672168216921702171217221732174217521762177217821792180218121822183218421852186218721882189219021912192219321942195219621972198219922002201220222032204220522062207220822092210221122122213221422152216221722182219222022212222222322242225222622272228222922302231223222332234223522362237223822392240224122422243224422452246224722482249225022512252225322542255225622572258225922602261226222632264226522662267226822692270227122722273227422752276227722782279228022812282228322842285228622872288228922902291229222932294229522962297229822992300230123022303230423052306230723082309231023112312231323142315231623172318231923202321232223232324232523262327232823292330233123322333233423352336233723382339234023412342234323442345234623472348234923502351235223532354235523562357235823592360236123622363236423652366236723682369237023712372237323742375237623772378237923802381238223832384238523862387238823892390239123922393239423952396239723982399240024012402240324042405240624072408240924102411241224132414241524162417241824192420242124222423242424252426242724282429243024312432243324342435243624372438243924402441244224432444244524462447244824492450245124522453245424552456245724582459246024612462246324642465246624672468246924702471247224732474247524762477247824792480248124822483248424852486248724882489249024912492249324942495249624972498249925002501250225032504250525062507250825092510251125122513251425152516251725182519252025212522252325242525252625272528252925302531253225332534253525362537253825392540254125422543254425452546254725482549255025512552255325542555255625572558255925602561256225632564256525662567256825692570257125722573257425752576257725782579258025812582258325842585258625872588258925902591259225932594259525962597259825992600260126022603260426052606260726082609261026112612261326142615261626172618261926202621262226232624262526262627262826292630263126322633263426352636263726382639264026412642264326442645264626472648264926502651265226532654265526562657265826592660266126622663266426652666266726682669267026712672267326742675267626772678267926802681268226832684268526862687268826892690269126922693269426952696269726982699270027012702270327042705270627072708270927102711271227132714271527162717271827192720272127222723272427252726272727282729273027312732273327342735273627372738273927402741274227432744274527462747274827492750275127522753275427552756275727582759276027612762276327642765276627672768276927702771277227732774
  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. idx = 0;
  1222. st_parm->cnt_history_in_file = 0;
  1223. while ((line = xmalloc_fgetline(fp)) != NULL) {
  1224. if (line[0] == '\0') {
  1225. free(line);
  1226. continue;
  1227. }
  1228. free(temp_h[idx]);
  1229. temp_h[idx] = line;
  1230. st_parm->cnt_history_in_file++;
  1231. idx++;
  1232. if (idx == st_parm->max_history)
  1233. idx = 0;
  1234. }
  1235. fclose(fp);
  1236. /* find first non-NULL temp_h[], if any */
  1237. if (st_parm->cnt_history_in_file) {
  1238. while (temp_h[idx] == NULL) {
  1239. idx++;
  1240. if (idx == st_parm->max_history)
  1241. idx = 0;
  1242. }
  1243. }
  1244. /* copy temp_h[] to st_parm->history[] */
  1245. for (i = 0; i < st_parm->max_history;) {
  1246. line = temp_h[idx];
  1247. if (!line)
  1248. break;
  1249. idx++;
  1250. if (idx == st_parm->max_history)
  1251. idx = 0;
  1252. line_len = strlen(line);
  1253. if (line_len >= MAX_LINELEN)
  1254. line[MAX_LINELEN-1] = '\0';
  1255. st_parm->history[i++] = line;
  1256. }
  1257. st_parm->cnt_history = i;
  1258. if (ENABLE_FEATURE_EDITING_SAVE_ON_EXIT)
  1259. st_parm->cnt_history_in_file = i;
  1260. }
  1261. }
  1262. # if ENABLE_FEATURE_EDITING_SAVE_ON_EXIT
  1263. void save_history(line_input_t *st)
  1264. {
  1265. FILE *fp;
  1266. if (!st->hist_file)
  1267. return;
  1268. if (st->cnt_history <= st->cnt_history_in_file)
  1269. return;
  1270. fp = fopen(st->hist_file, "a");
  1271. if (fp) {
  1272. int i, fd;
  1273. char *new_name;
  1274. line_input_t *st_temp;
  1275. for (i = st->cnt_history_in_file; i < st->cnt_history; i++)
  1276. fprintf(fp, "%s\n", st->history[i]);
  1277. fclose(fp);
  1278. /* we may have concurrently written entries from others.
  1279. * load them */
  1280. st_temp = new_line_input_t(st->flags);
  1281. st_temp->hist_file = st->hist_file;
  1282. st_temp->max_history = st->max_history;
  1283. load_history(st_temp);
  1284. /* write out temp file and replace hist_file atomically */
  1285. new_name = xasprintf("%s.%u.new", st->hist_file, (int) getpid());
  1286. fd = open(new_name, O_WRONLY | O_CREAT | O_TRUNC, 0600);
  1287. if (fd >= 0) {
  1288. fp = xfdopen_for_write(fd);
  1289. for (i = 0; i < st_temp->cnt_history; i++)
  1290. fprintf(fp, "%s\n", st_temp->history[i]);
  1291. fclose(fp);
  1292. if (rename(new_name, st->hist_file) == 0)
  1293. st->cnt_history_in_file = st_temp->cnt_history;
  1294. }
  1295. free(new_name);
  1296. free_line_input_t(st_temp);
  1297. }
  1298. }
  1299. # else
  1300. static void save_history(char *str)
  1301. {
  1302. int fd;
  1303. int len, len2;
  1304. if (!state->hist_file)
  1305. return;
  1306. fd = open(state->hist_file, O_WRONLY | O_CREAT | O_APPEND, 0600);
  1307. if (fd < 0)
  1308. return;
  1309. xlseek(fd, 0, SEEK_END); /* paranoia */
  1310. len = strlen(str);
  1311. str[len] = '\n'; /* we (try to) do atomic write */
  1312. len2 = full_write(fd, str, len + 1);
  1313. str[len] = '\0';
  1314. close(fd);
  1315. if (len2 != len + 1)
  1316. return; /* "wtf?" */
  1317. /* did we write so much that history file needs trimming? */
  1318. state->cnt_history_in_file++;
  1319. if (state->cnt_history_in_file > state->max_history * 4) {
  1320. char *new_name;
  1321. line_input_t *st_temp;
  1322. /* we may have concurrently written entries from others.
  1323. * load them */
  1324. st_temp = new_line_input_t(state->flags);
  1325. st_temp->hist_file = state->hist_file;
  1326. st_temp->max_history = state->max_history;
  1327. load_history(st_temp);
  1328. /* write out temp file and replace hist_file atomically */
  1329. new_name = xasprintf("%s.%u.new", state->hist_file, (int) getpid());
  1330. fd = open(new_name, O_WRONLY | O_CREAT | O_TRUNC, 0600);
  1331. if (fd >= 0) {
  1332. FILE *fp;
  1333. int i;
  1334. fp = xfdopen_for_write(fd);
  1335. for (i = 0; i < st_temp->cnt_history; i++)
  1336. fprintf(fp, "%s\n", st_temp->history[i]);
  1337. fclose(fp);
  1338. if (rename(new_name, state->hist_file) == 0)
  1339. state->cnt_history_in_file = st_temp->cnt_history;
  1340. }
  1341. free(new_name);
  1342. free_line_input_t(st_temp);
  1343. }
  1344. }
  1345. # endif
  1346. # else
  1347. # define load_history(a) ((void)0)
  1348. # define save_history(a) ((void)0)
  1349. # endif /* FEATURE_COMMAND_SAVEHISTORY */
  1350. static void remember_in_history(char *str)
  1351. {
  1352. int i;
  1353. if (!(state->flags & DO_HISTORY))
  1354. return;
  1355. if (str[0] == '\0')
  1356. return;
  1357. i = state->cnt_history;
  1358. /* Don't save dupes */
  1359. if (i && strcmp(state->history[i-1], str) == 0)
  1360. return;
  1361. free(state->history[state->max_history]); /* redundant, paranoia */
  1362. state->history[state->max_history] = NULL; /* redundant, paranoia */
  1363. /* If history[] is full, remove the oldest command */
  1364. /* we need to keep history[state->max_history] empty, hence >=, not > */
  1365. if (i >= state->max_history) {
  1366. free(state->history[0]);
  1367. for (i = 0; i < state->max_history-1; i++)
  1368. state->history[i] = state->history[i+1];
  1369. /* i == state->max_history-1 */
  1370. # if ENABLE_FEATURE_EDITING_SAVE_ON_EXIT
  1371. if (state->cnt_history_in_file)
  1372. state->cnt_history_in_file--;
  1373. # endif
  1374. }
  1375. /* i <= state->max_history-1 */
  1376. state->history[i++] = xstrdup(str);
  1377. /* i <= state->max_history */
  1378. state->cur_history = i;
  1379. state->cnt_history = i;
  1380. # if ENABLE_FEATURE_EDITING_SAVEHISTORY && !ENABLE_FEATURE_EDITING_SAVE_ON_EXIT
  1381. save_history(str);
  1382. # endif
  1383. IF_FEATURE_EDITING_FANCY_PROMPT(num_ok_lines++;)
  1384. }
  1385. #else /* MAX_HISTORY == 0 */
  1386. # define remember_in_history(a) ((void)0)
  1387. #endif /* MAX_HISTORY */
  1388. #if ENABLE_FEATURE_EDITING_VI
  1389. /*
  1390. * vi mode implemented 2005 by Paul Fox <pgf@foxharp.boston.ma.us>
  1391. */
  1392. static void
  1393. vi_Word_motion(int eat)
  1394. {
  1395. CHAR_T *command = command_ps;
  1396. while (cursor < command_len && !BB_isspace(command[cursor]))
  1397. input_forward();
  1398. if (eat) while (cursor < command_len && BB_isspace(command[cursor]))
  1399. input_forward();
  1400. }
  1401. static void
  1402. vi_word_motion(int eat)
  1403. {
  1404. CHAR_T *command = command_ps;
  1405. if (BB_isalnum(command[cursor]) || command[cursor] == '_') {
  1406. while (cursor < command_len
  1407. && (BB_isalnum(command[cursor+1]) || command[cursor+1] == '_')
  1408. ) {
  1409. input_forward();
  1410. }
  1411. } else if (BB_ispunct(command[cursor])) {
  1412. while (cursor < command_len && BB_ispunct(command[cursor+1]))
  1413. input_forward();
  1414. }
  1415. if (cursor < command_len)
  1416. input_forward();
  1417. if (eat) {
  1418. while (cursor < command_len && BB_isspace(command[cursor]))
  1419. input_forward();
  1420. }
  1421. }
  1422. static void
  1423. vi_End_motion(void)
  1424. {
  1425. CHAR_T *command = command_ps;
  1426. input_forward();
  1427. while (cursor < command_len && BB_isspace(command[cursor]))
  1428. input_forward();
  1429. while (cursor < command_len-1 && !BB_isspace(command[cursor+1]))
  1430. input_forward();
  1431. }
  1432. static void
  1433. vi_end_motion(void)
  1434. {
  1435. CHAR_T *command = command_ps;
  1436. if (cursor >= command_len-1)
  1437. return;
  1438. input_forward();
  1439. while (cursor < command_len-1 && BB_isspace(command[cursor]))
  1440. input_forward();
  1441. if (cursor >= command_len-1)
  1442. return;
  1443. if (BB_isalnum(command[cursor]) || command[cursor] == '_') {
  1444. while (cursor < command_len-1
  1445. && (BB_isalnum(command[cursor+1]) || command[cursor+1] == '_')
  1446. ) {
  1447. input_forward();
  1448. }
  1449. } else if (BB_ispunct(command[cursor])) {
  1450. while (cursor < command_len-1 && BB_ispunct(command[cursor+1]))
  1451. input_forward();
  1452. }
  1453. }
  1454. static void
  1455. vi_Back_motion(void)
  1456. {
  1457. CHAR_T *command = command_ps;
  1458. while (cursor > 0 && BB_isspace(command[cursor-1]))
  1459. input_backward(1);
  1460. while (cursor > 0 && !BB_isspace(command[cursor-1]))
  1461. input_backward(1);
  1462. }
  1463. static void
  1464. vi_back_motion(void)
  1465. {
  1466. CHAR_T *command = command_ps;
  1467. if (cursor <= 0)
  1468. return;
  1469. input_backward(1);
  1470. while (cursor > 0 && BB_isspace(command[cursor]))
  1471. input_backward(1);
  1472. if (cursor <= 0)
  1473. return;
  1474. if (BB_isalnum(command[cursor]) || command[cursor] == '_') {
  1475. while (cursor > 0
  1476. && (BB_isalnum(command[cursor-1]) || command[cursor-1] == '_')
  1477. ) {
  1478. input_backward(1);
  1479. }
  1480. } else if (BB_ispunct(command[cursor])) {
  1481. while (cursor > 0 && BB_ispunct(command[cursor-1]))
  1482. input_backward(1);
  1483. }
  1484. }
  1485. #endif
  1486. /* Modelled after bash 4.0 behavior of Ctrl-<arrow> */
  1487. static void ctrl_left(void)
  1488. {
  1489. CHAR_T *command = command_ps;
  1490. while (1) {
  1491. CHAR_T c;
  1492. input_backward(1);
  1493. if (cursor == 0)
  1494. break;
  1495. c = command[cursor];
  1496. if (c != ' ' && !BB_ispunct(c)) {
  1497. /* we reached a "word" delimited by spaces/punct.
  1498. * go to its beginning */
  1499. while (1) {
  1500. c = command[cursor - 1];
  1501. if (c == ' ' || BB_ispunct(c))
  1502. break;
  1503. input_backward(1);
  1504. if (cursor == 0)
  1505. break;
  1506. }
  1507. break;
  1508. }
  1509. }
  1510. }
  1511. static void ctrl_right(void)
  1512. {
  1513. CHAR_T *command = command_ps;
  1514. while (1) {
  1515. CHAR_T c;
  1516. c = command[cursor];
  1517. if (c == BB_NUL)
  1518. break;
  1519. if (c != ' ' && !BB_ispunct(c)) {
  1520. /* we reached a "word" delimited by spaces/punct.
  1521. * go to its end + 1 */
  1522. while (1) {
  1523. input_forward();
  1524. c = command[cursor];
  1525. if (c == BB_NUL || c == ' ' || BB_ispunct(c))
  1526. break;
  1527. }
  1528. break;
  1529. }
  1530. input_forward();
  1531. }
  1532. }
  1533. /*
  1534. * read_line_input and its helpers
  1535. */
  1536. #if ENABLE_FEATURE_EDITING_ASK_TERMINAL
  1537. static void ask_terminal(void)
  1538. {
  1539. /* Ask terminal where is the cursor now.
  1540. * lineedit_read_key handles response and corrects
  1541. * our idea of current cursor position.
  1542. * Testcase: run "echo -n long_line_long_line_long_line",
  1543. * then type in a long, wrapping command and try to
  1544. * delete it using backspace key.
  1545. * Note: we print it _after_ prompt, because
  1546. * prompt may contain CR. Example: PS1='\[\r\n\]\w '
  1547. */
  1548. /* Problem: if there is buffered input on stdin,
  1549. * the response will be delivered later,
  1550. * possibly to an unsuspecting application.
  1551. * Testcase: "sleep 1; busybox ash" + press and hold [Enter].
  1552. * Result:
  1553. * ~/srcdevel/bbox/fix/busybox.t4 #
  1554. * ~/srcdevel/bbox/fix/busybox.t4 #
  1555. * ^[[59;34~/srcdevel/bbox/fix/busybox.t4 # <-- garbage
  1556. * ~/srcdevel/bbox/fix/busybox.t4 #
  1557. *
  1558. * Checking for input with poll only makes the race narrower,
  1559. * I still can trigger it. Strace:
  1560. *
  1561. * write(1, "~/srcdevel/bbox/fix/busybox.t4 # ", 33) = 33
  1562. * poll([{fd=0, events=POLLIN}], 1, 0) = 0 (Timeout) <-- no input exists
  1563. * write(1, "\33[6n", 4) = 4 <-- send the ESC sequence, quick!
  1564. * poll([{fd=0, events=POLLIN}], 1, -1) = 1 ([{fd=0, revents=POLLIN}])
  1565. * read(0, "\n", 1) = 1 <-- oh crap, user's input got in first
  1566. */
  1567. struct pollfd pfd;
  1568. pfd.fd = STDIN_FILENO;
  1569. pfd.events = POLLIN;
  1570. if (safe_poll(&pfd, 1, 0) == 0) {
  1571. S.sent_ESC_br6n = 1;
  1572. fputs(ESC"[6n", stdout);
  1573. fflush_all(); /* make terminal see it ASAP! */
  1574. }
  1575. }
  1576. #else
  1577. #define ask_terminal() ((void)0)
  1578. #endif
  1579. #if !ENABLE_FEATURE_EDITING_FANCY_PROMPT
  1580. static void parse_and_put_prompt(const char *prmt_ptr)
  1581. {
  1582. cmdedit_prompt = prmt_ptr;
  1583. cmdedit_prmt_len = strlen(prmt_ptr);
  1584. put_prompt();
  1585. }
  1586. #else
  1587. static void parse_and_put_prompt(const char *prmt_ptr)
  1588. {
  1589. int prmt_len = 0;
  1590. size_t cur_prmt_len = 0;
  1591. char flg_not_length = '[';
  1592. char *prmt_mem_ptr = xzalloc(1);
  1593. char *cwd_buf = xrealloc_getcwd_or_warn(NULL);
  1594. char cbuf[2];
  1595. char c;
  1596. char *pbuf;
  1597. cmdedit_prmt_len = 0;
  1598. if (!cwd_buf) {
  1599. cwd_buf = (char *)bb_msg_unknown;
  1600. }
  1601. cbuf[1] = '\0'; /* never changes */
  1602. while (*prmt_ptr) {
  1603. char *free_me = NULL;
  1604. pbuf = cbuf;
  1605. c = *prmt_ptr++;
  1606. if (c == '\\') {
  1607. const char *cp = prmt_ptr;
  1608. int l;
  1609. c = bb_process_escape_sequence(&prmt_ptr);
  1610. if (prmt_ptr == cp) {
  1611. if (*cp == '\0')
  1612. break;
  1613. c = *prmt_ptr++;
  1614. switch (c) {
  1615. # if ENABLE_USERNAME_OR_HOMEDIR
  1616. case 'u':
  1617. pbuf = user_buf ? user_buf : (char*)"";
  1618. break;
  1619. # endif
  1620. case 'h':
  1621. pbuf = free_me = safe_gethostname();
  1622. *strchrnul(pbuf, '.') = '\0';
  1623. break;
  1624. case '$':
  1625. c = (geteuid() == 0 ? '#' : '$');
  1626. break;
  1627. # if ENABLE_USERNAME_OR_HOMEDIR
  1628. case 'w':
  1629. /* /home/user[/something] -> ~[/something] */
  1630. pbuf = cwd_buf;
  1631. l = strlen(home_pwd_buf);
  1632. if (l != 0
  1633. && strncmp(home_pwd_buf, cwd_buf, l) == 0
  1634. && (cwd_buf[l]=='/' || cwd_buf[l]=='\0')
  1635. && strlen(cwd_buf + l) < PATH_MAX
  1636. ) {
  1637. pbuf = free_me = xasprintf("~%s", cwd_buf + l);
  1638. }
  1639. break;
  1640. # endif
  1641. case 'W':
  1642. pbuf = cwd_buf;
  1643. cp = strrchr(pbuf, '/');
  1644. if (cp != NULL && cp != pbuf)
  1645. pbuf += (cp-pbuf) + 1;
  1646. break;
  1647. case '!':
  1648. pbuf = free_me = xasprintf("%d", num_ok_lines);
  1649. break;
  1650. case 'e': case 'E': /* \e \E = \033 */
  1651. c = '\033';
  1652. break;
  1653. case 'x': case 'X': {
  1654. char buf2[4];
  1655. for (l = 0; l < 3;) {
  1656. unsigned h;
  1657. buf2[l++] = *prmt_ptr;
  1658. buf2[l] = '\0';
  1659. h = strtoul(buf2, &pbuf, 16);
  1660. if (h > UCHAR_MAX || (pbuf - buf2) < l) {
  1661. buf2[--l] = '\0';
  1662. break;
  1663. }
  1664. prmt_ptr++;
  1665. }
  1666. c = (char)strtoul(buf2, NULL, 16);
  1667. if (c == 0)
  1668. c = '?';
  1669. pbuf = cbuf;
  1670. break;
  1671. }
  1672. case '[': case ']':
  1673. if (c == flg_not_length) {
  1674. flg_not_length = (flg_not_length == '[' ? ']' : '[');
  1675. continue;
  1676. }
  1677. break;
  1678. } /* switch */
  1679. } /* if */
  1680. } /* if */
  1681. cbuf[0] = c;
  1682. cur_prmt_len = strlen(pbuf);
  1683. prmt_len += cur_prmt_len;
  1684. if (flg_not_length != ']')
  1685. cmdedit_prmt_len += cur_prmt_len;
  1686. prmt_mem_ptr = strcat(xrealloc(prmt_mem_ptr, prmt_len+1), pbuf);
  1687. free(free_me);
  1688. } /* while */
  1689. if (cwd_buf != (char *)bb_msg_unknown)
  1690. free(cwd_buf);
  1691. cmdedit_prompt = prmt_mem_ptr;
  1692. put_prompt();
  1693. }
  1694. #endif
  1695. static void cmdedit_setwidth(unsigned w, int redraw_flg)
  1696. {
  1697. cmdedit_termw = w;
  1698. if (redraw_flg) {
  1699. /* new y for current cursor */
  1700. int new_y = (cursor + cmdedit_prmt_len) / w;
  1701. /* redraw */
  1702. redraw((new_y >= cmdedit_y ? new_y : cmdedit_y), command_len - cursor);
  1703. fflush_all();
  1704. }
  1705. }
  1706. static void win_changed(int nsig)
  1707. {
  1708. int sv_errno = errno;
  1709. unsigned width;
  1710. get_terminal_width_height(0, &width, NULL);
  1711. //FIXME: cmdedit_setwidth() -> redraw() -> printf() -> KABOOM! (we are in signal handler!)
  1712. cmdedit_setwidth(width, /*redraw_flg:*/ nsig);
  1713. errno = sv_errno;
  1714. }
  1715. static int lineedit_read_key(char *read_key_buffer, int timeout)
  1716. {
  1717. int64_t ic;
  1718. #if ENABLE_UNICODE_SUPPORT
  1719. char unicode_buf[MB_CUR_MAX + 1];
  1720. int unicode_idx = 0;
  1721. #endif
  1722. while (1) {
  1723. /* Wait for input. TIMEOUT = -1 makes read_key wait even
  1724. * on nonblocking stdin, TIMEOUT = 50 makes sure we won't
  1725. * insist on full MB_CUR_MAX buffer to declare input like
  1726. * "\xff\n",pause,"ls\n" invalid and thus won't lose "ls".
  1727. *
  1728. * Note: read_key sets errno to 0 on success.
  1729. */
  1730. ic = read_key(STDIN_FILENO, read_key_buffer, timeout);
  1731. if (errno) {
  1732. #if ENABLE_UNICODE_SUPPORT
  1733. if (errno == EAGAIN && unicode_idx != 0)
  1734. goto pushback;
  1735. #endif
  1736. break;
  1737. }
  1738. #if ENABLE_FEATURE_EDITING_ASK_TERMINAL
  1739. if ((int32_t)ic == KEYCODE_CURSOR_POS
  1740. && S.sent_ESC_br6n
  1741. ) {
  1742. S.sent_ESC_br6n = 0;
  1743. if (cursor == 0) { /* otherwise it may be bogus */
  1744. int col = ((ic >> 32) & 0x7fff) - 1;
  1745. if (col > cmdedit_prmt_len) {
  1746. cmdedit_x += (col - cmdedit_prmt_len);
  1747. while (cmdedit_x >= cmdedit_termw) {
  1748. cmdedit_x -= cmdedit_termw;
  1749. cmdedit_y++;
  1750. }
  1751. }
  1752. }
  1753. continue;
  1754. }
  1755. #endif
  1756. #if ENABLE_UNICODE_SUPPORT
  1757. if (unicode_status == UNICODE_ON) {
  1758. wchar_t wc;
  1759. if ((int32_t)ic < 0) /* KEYCODE_xxx */
  1760. break;
  1761. // TODO: imagine sequence like: 0xff,<left-arrow>: we are currently losing 0xff...
  1762. unicode_buf[unicode_idx++] = ic;
  1763. unicode_buf[unicode_idx] = '\0';
  1764. if (mbstowcs(&wc, unicode_buf, 1) != 1) {
  1765. /* Not (yet?) a valid unicode char */
  1766. if (unicode_idx < MB_CUR_MAX) {
  1767. timeout = 50;
  1768. continue;
  1769. }
  1770. pushback:
  1771. /* Invalid sequence. Save all "bad bytes" except first */
  1772. read_key_ungets(read_key_buffer, unicode_buf + 1, unicode_idx - 1);
  1773. # if !ENABLE_UNICODE_PRESERVE_BROKEN
  1774. ic = CONFIG_SUBST_WCHAR;
  1775. # else
  1776. ic = unicode_mark_raw_byte(unicode_buf[0]);
  1777. # endif
  1778. } else {
  1779. /* Valid unicode char, return its code */
  1780. ic = wc;
  1781. }
  1782. }
  1783. #endif
  1784. break;
  1785. }
  1786. return ic;
  1787. }
  1788. #if ENABLE_UNICODE_BIDI_SUPPORT
  1789. static int isrtl_str(void)
  1790. {
  1791. int idx = cursor;
  1792. while (idx < command_len && unicode_bidi_is_neutral_wchar(command_ps[idx]))
  1793. idx++;
  1794. return unicode_bidi_isrtl(command_ps[idx]);
  1795. }
  1796. #else
  1797. # define isrtl_str() 0
  1798. #endif
  1799. /* leave out the "vi-mode"-only case labels if vi editing isn't
  1800. * configured. */
  1801. #define vi_case(caselabel) IF_FEATURE_EDITING_VI(case caselabel)
  1802. /* convert uppercase ascii to equivalent control char, for readability */
  1803. #undef CTRL
  1804. #define CTRL(a) ((a) & ~0x40)
  1805. enum {
  1806. VI_CMDMODE_BIT = 0x40000000,
  1807. /* 0x80000000 bit flags KEYCODE_xxx */
  1808. };
  1809. #if ENABLE_FEATURE_REVERSE_SEARCH
  1810. /* Mimic readline Ctrl-R reverse history search.
  1811. * When invoked, it shows the following prompt:
  1812. * (reverse-i-search)'': user_input [cursor pos unchanged by Ctrl-R]
  1813. * and typing results in search being performed:
  1814. * (reverse-i-search)'tmp': cd /tmp [cursor under t in /tmp]
  1815. * Search is performed by looking at progressively older lines in history.
  1816. * Ctrl-R again searches for the next match in history.
  1817. * Backspace deletes last matched char.
  1818. * Control keys exit search and return to normal editing (at current history line).
  1819. */
  1820. static int32_t reverse_i_search(void)
  1821. {
  1822. char match_buf[128]; /* for user input */
  1823. char read_key_buffer[KEYCODE_BUFFER_SIZE];
  1824. const char *matched_history_line;
  1825. const char *saved_prompt;
  1826. int32_t ic;
  1827. matched_history_line = NULL;
  1828. read_key_buffer[0] = 0;
  1829. match_buf[0] = '\0';
  1830. /* Save and replace the prompt */
  1831. saved_prompt = cmdedit_prompt;
  1832. goto set_prompt;
  1833. while (1) {
  1834. int h;
  1835. unsigned match_buf_len = strlen(match_buf);
  1836. fflush_all();
  1837. //FIXME: correct timeout?
  1838. ic = lineedit_read_key(read_key_buffer, -1);
  1839. switch (ic) {
  1840. case CTRL('R'): /* searching for the next match */
  1841. break;
  1842. case '\b':
  1843. case '\x7f':
  1844. /* Backspace */
  1845. if (unicode_status == UNICODE_ON) {
  1846. while (match_buf_len != 0) {
  1847. uint8_t c = match_buf[--match_buf_len];
  1848. if ((c & 0xc0) != 0x80) /* start of UTF-8 char? */
  1849. break; /* yes */
  1850. }
  1851. } else {
  1852. if (match_buf_len != 0)
  1853. match_buf_len--;
  1854. }
  1855. match_buf[match_buf_len] = '\0';
  1856. break;
  1857. default:
  1858. if (ic < ' '
  1859. || (!ENABLE_UNICODE_SUPPORT && ic >= 256)
  1860. || (ENABLE_UNICODE_SUPPORT && ic >= VI_CMDMODE_BIT)
  1861. ) {
  1862. goto ret;
  1863. }
  1864. /* Append this char */
  1865. #if ENABLE_UNICODE_SUPPORT
  1866. if (unicode_status == UNICODE_ON) {
  1867. mbstate_t mbstate = { 0 };
  1868. char buf[MB_CUR_MAX + 1];
  1869. int len = wcrtomb(buf, ic, &mbstate);
  1870. if (len > 0) {
  1871. buf[len] = '\0';
  1872. if (match_buf_len + len < sizeof(match_buf))
  1873. strcpy(match_buf + match_buf_len, buf);
  1874. }
  1875. } else
  1876. #endif
  1877. if (match_buf_len < sizeof(match_buf) - 1) {
  1878. match_buf[match_buf_len] = ic;
  1879. match_buf[match_buf_len + 1] = '\0';
  1880. }
  1881. break;
  1882. } /* switch (ic) */
  1883. /* Search in history for match_buf */
  1884. h = state->cur_history;
  1885. if (ic == CTRL('R'))
  1886. h--;
  1887. while (h >= 0) {
  1888. if (state->history[h]) {
  1889. char *match = strstr(state->history[h], match_buf);
  1890. if (match) {
  1891. state->cur_history = h;
  1892. matched_history_line = state->history[h];
  1893. command_len = load_string(matched_history_line);
  1894. cursor = match - matched_history_line;
  1895. //FIXME: cursor position for Unicode case
  1896. free((char*)cmdedit_prompt);
  1897. set_prompt:
  1898. cmdedit_prompt = xasprintf("(reverse-i-search)'%s': ", match_buf);
  1899. cmdedit_prmt_len = strlen(cmdedit_prompt);
  1900. goto do_redraw;
  1901. }
  1902. }
  1903. h--;
  1904. }
  1905. /* Not found */
  1906. match_buf[match_buf_len] = '\0';
  1907. beep();
  1908. continue;
  1909. do_redraw:
  1910. redraw(cmdedit_y, command_len - cursor);
  1911. } /* while (1) */
  1912. ret:
  1913. if (matched_history_line)
  1914. command_len = load_string(matched_history_line);
  1915. free((char*)cmdedit_prompt);
  1916. cmdedit_prompt = saved_prompt;
  1917. cmdedit_prmt_len = strlen(cmdedit_prompt);
  1918. redraw(cmdedit_y, command_len - cursor);
  1919. return ic;
  1920. }
  1921. #endif
  1922. /* maxsize must be >= 2.
  1923. * Returns:
  1924. * -1 on read errors or EOF, or on bare Ctrl-D,
  1925. * 0 on ctrl-C (the line entered is still returned in 'command'),
  1926. * >0 length of input string, including terminating '\n'
  1927. */
  1928. int FAST_FUNC read_line_input(line_input_t *st, const char *prompt, char *command, int maxsize, int timeout)
  1929. {
  1930. int len;
  1931. #if ENABLE_FEATURE_TAB_COMPLETION
  1932. smallint lastWasTab = 0;
  1933. #endif
  1934. smallint break_out = 0;
  1935. #if ENABLE_FEATURE_EDITING_VI
  1936. smallint vi_cmdmode = 0;
  1937. #endif
  1938. struct termios initial_settings;
  1939. struct termios new_settings;
  1940. char read_key_buffer[KEYCODE_BUFFER_SIZE];
  1941. INIT_S();
  1942. if (tcgetattr(STDIN_FILENO, &initial_settings) < 0
  1943. || !(initial_settings.c_lflag & ECHO)
  1944. ) {
  1945. /* Happens when e.g. stty -echo was run before */
  1946. parse_and_put_prompt(prompt);
  1947. /* fflush_all(); - done by parse_and_put_prompt */
  1948. if (fgets(command, maxsize, stdin) == NULL)
  1949. len = -1; /* EOF or error */
  1950. else
  1951. len = strlen(command);
  1952. DEINIT_S();
  1953. return len;
  1954. }
  1955. init_unicode();
  1956. // FIXME: audit & improve this
  1957. if (maxsize > MAX_LINELEN)
  1958. maxsize = MAX_LINELEN;
  1959. S.maxsize = maxsize;
  1960. /* With zero flags, no other fields are ever used */
  1961. state = st ? st : (line_input_t*) &const_int_0;
  1962. #if MAX_HISTORY > 0
  1963. # if ENABLE_FEATURE_EDITING_SAVEHISTORY
  1964. if (state->hist_file)
  1965. if (state->cnt_history == 0)
  1966. load_history(state);
  1967. # endif
  1968. if (state->flags & DO_HISTORY)
  1969. state->cur_history = state->cnt_history;
  1970. #endif
  1971. /* prepare before init handlers */
  1972. cmdedit_y = 0; /* quasireal y, not true if line > xt*yt */
  1973. command_len = 0;
  1974. #if ENABLE_UNICODE_SUPPORT
  1975. command_ps = xzalloc(maxsize * sizeof(command_ps[0]));
  1976. #else
  1977. command_ps = command;
  1978. command[0] = '\0';
  1979. #endif
  1980. #define command command_must_not_be_used
  1981. new_settings = initial_settings;
  1982. /* ~ICANON: unbuffered input (most c_cc[] are disabled, VMIN/VTIME are enabled) */
  1983. /* ~ECHO, ~ECHONL: turn off echoing, including newline echoing */
  1984. /* ~ISIG: turn off INTR (ctrl-C), QUIT, SUSP */
  1985. new_settings.c_lflag &= ~(ICANON | ECHO | ECHONL | ISIG);
  1986. /* reads would block only if < 1 char is available */
  1987. new_settings.c_cc[VMIN] = 1;
  1988. /* no timeout (reads block forever) */
  1989. new_settings.c_cc[VTIME] = 0;
  1990. /* Should be not needed if ISIG is off: */
  1991. /* Turn off CTRL-C */
  1992. /* new_settings.c_cc[VINTR] = _POSIX_VDISABLE; */
  1993. tcsetattr_stdin_TCSANOW(&new_settings);
  1994. #if ENABLE_USERNAME_OR_HOMEDIR
  1995. {
  1996. struct passwd *entry;
  1997. entry = getpwuid(geteuid());
  1998. if (entry) {
  1999. user_buf = xstrdup(entry->pw_name);
  2000. home_pwd_buf = xstrdup(entry->pw_dir);
  2001. }
  2002. }
  2003. #endif
  2004. #if 0
  2005. for (i = 0; i <= state->max_history; i++)
  2006. bb_error_msg("history[%d]:'%s'", i, state->history[i]);
  2007. bb_error_msg("cur_history:%d cnt_history:%d", state->cur_history, state->cnt_history);
  2008. #endif
  2009. /* Print out the command prompt, optionally ask where cursor is */
  2010. parse_and_put_prompt(prompt);
  2011. ask_terminal();
  2012. /* Install window resize handler (NB: after *all* init is complete) */
  2013. //FIXME: save entire sigaction!
  2014. previous_SIGWINCH_handler = signal(SIGWINCH, win_changed);
  2015. win_changed(0); /* get initial window size */
  2016. read_key_buffer[0] = 0;
  2017. while (1) {
  2018. /*
  2019. * The emacs and vi modes share much of the code in the big
  2020. * command loop. Commands entered when in vi's command mode
  2021. * (aka "escape mode") get an extra bit added to distinguish
  2022. * them - this keeps them from being self-inserted. This
  2023. * clutters the big switch a bit, but keeps all the code
  2024. * in one place.
  2025. */
  2026. int32_t ic, ic_raw;
  2027. fflush_all();
  2028. ic = ic_raw = lineedit_read_key(read_key_buffer, timeout);
  2029. #if ENABLE_FEATURE_REVERSE_SEARCH
  2030. again:
  2031. #endif
  2032. #if ENABLE_FEATURE_EDITING_VI
  2033. newdelflag = 1;
  2034. if (vi_cmdmode) {
  2035. /* btw, since KEYCODE_xxx are all < 0, this doesn't
  2036. * change ic if it contains one of them: */
  2037. ic |= VI_CMDMODE_BIT;
  2038. }
  2039. #endif
  2040. switch (ic) {
  2041. case '\n':
  2042. case '\r':
  2043. vi_case('\n'|VI_CMDMODE_BIT:)
  2044. vi_case('\r'|VI_CMDMODE_BIT:)
  2045. /* Enter */
  2046. goto_new_line();
  2047. break_out = 1;
  2048. break;
  2049. case CTRL('A'):
  2050. vi_case('0'|VI_CMDMODE_BIT:)
  2051. /* Control-a -- Beginning of line */
  2052. input_backward(cursor);
  2053. break;
  2054. case CTRL('B'):
  2055. vi_case('h'|VI_CMDMODE_BIT:)
  2056. vi_case('\b'|VI_CMDMODE_BIT:) /* ^H */
  2057. vi_case('\x7f'|VI_CMDMODE_BIT:) /* DEL */
  2058. input_backward(1); /* Move back one character */
  2059. break;
  2060. case CTRL('E'):
  2061. vi_case('$'|VI_CMDMODE_BIT:)
  2062. /* Control-e -- End of line */
  2063. put_till_end_and_adv_cursor();
  2064. break;
  2065. case CTRL('F'):
  2066. vi_case('l'|VI_CMDMODE_BIT:)
  2067. vi_case(' '|VI_CMDMODE_BIT:)
  2068. input_forward(); /* Move forward one character */
  2069. break;
  2070. case '\b': /* ^H */
  2071. case '\x7f': /* DEL */
  2072. if (!isrtl_str())
  2073. input_backspace();
  2074. else
  2075. input_delete(0);
  2076. break;
  2077. case KEYCODE_DELETE:
  2078. if (!isrtl_str())
  2079. input_delete(0);
  2080. else
  2081. input_backspace();
  2082. break;
  2083. #if ENABLE_FEATURE_TAB_COMPLETION
  2084. case '\t':
  2085. input_tab(&lastWasTab);
  2086. break;
  2087. #endif
  2088. case CTRL('K'):
  2089. /* Control-k -- clear to end of line */
  2090. command_ps[cursor] = BB_NUL;
  2091. command_len = cursor;
  2092. printf(SEQ_CLEAR_TILL_END_OF_SCREEN);
  2093. break;
  2094. case CTRL('L'):
  2095. vi_case(CTRL('L')|VI_CMDMODE_BIT:)
  2096. /* Control-l -- clear screen */
  2097. printf(ESC"[H"); /* cursor to top,left */
  2098. redraw(0, command_len - cursor);
  2099. break;
  2100. #if MAX_HISTORY > 0
  2101. case CTRL('N'):
  2102. vi_case(CTRL('N')|VI_CMDMODE_BIT:)
  2103. vi_case('j'|VI_CMDMODE_BIT:)
  2104. /* Control-n -- Get next command in history */
  2105. if (get_next_history())
  2106. goto rewrite_line;
  2107. break;
  2108. case CTRL('P'):
  2109. vi_case(CTRL('P')|VI_CMDMODE_BIT:)
  2110. vi_case('k'|VI_CMDMODE_BIT:)
  2111. /* Control-p -- Get previous command from history */
  2112. if (get_previous_history())
  2113. goto rewrite_line;
  2114. break;
  2115. #endif
  2116. case CTRL('U'):
  2117. vi_case(CTRL('U')|VI_CMDMODE_BIT:)
  2118. /* Control-U -- Clear line before cursor */
  2119. if (cursor) {
  2120. command_len -= cursor;
  2121. memmove(command_ps, command_ps + cursor,
  2122. (command_len + 1) * sizeof(command_ps[0]));
  2123. redraw(cmdedit_y, command_len);
  2124. }
  2125. break;
  2126. case CTRL('W'):
  2127. vi_case(CTRL('W')|VI_CMDMODE_BIT:)
  2128. /* Control-W -- Remove the last word */
  2129. while (cursor > 0 && BB_isspace(command_ps[cursor-1]))
  2130. input_backspace();
  2131. while (cursor > 0 && !BB_isspace(command_ps[cursor-1]))
  2132. input_backspace();
  2133. break;
  2134. #if ENABLE_FEATURE_REVERSE_SEARCH
  2135. case CTRL('R'):
  2136. ic = ic_raw = reverse_i_search();
  2137. goto again;
  2138. #endif
  2139. #if ENABLE_FEATURE_EDITING_VI
  2140. case 'i'|VI_CMDMODE_BIT:
  2141. vi_cmdmode = 0;
  2142. break;
  2143. case 'I'|VI_CMDMODE_BIT:
  2144. input_backward(cursor);
  2145. vi_cmdmode = 0;
  2146. break;
  2147. case 'a'|VI_CMDMODE_BIT:
  2148. input_forward();
  2149. vi_cmdmode = 0;
  2150. break;
  2151. case 'A'|VI_CMDMODE_BIT:
  2152. put_till_end_and_adv_cursor();
  2153. vi_cmdmode = 0;
  2154. break;
  2155. case 'x'|VI_CMDMODE_BIT:
  2156. input_delete(1);
  2157. break;
  2158. case 'X'|VI_CMDMODE_BIT:
  2159. if (cursor > 0) {
  2160. input_backward(1);
  2161. input_delete(1);
  2162. }
  2163. break;
  2164. case 'W'|VI_CMDMODE_BIT:
  2165. vi_Word_motion(1);
  2166. break;
  2167. case 'w'|VI_CMDMODE_BIT:
  2168. vi_word_motion(1);
  2169. break;
  2170. case 'E'|VI_CMDMODE_BIT:
  2171. vi_End_motion();
  2172. break;
  2173. case 'e'|VI_CMDMODE_BIT:
  2174. vi_end_motion();
  2175. break;
  2176. case 'B'|VI_CMDMODE_BIT:
  2177. vi_Back_motion();
  2178. break;
  2179. case 'b'|VI_CMDMODE_BIT:
  2180. vi_back_motion();
  2181. break;
  2182. case 'C'|VI_CMDMODE_BIT:
  2183. vi_cmdmode = 0;
  2184. /* fall through */
  2185. case 'D'|VI_CMDMODE_BIT:
  2186. goto clear_to_eol;
  2187. case 'c'|VI_CMDMODE_BIT:
  2188. vi_cmdmode = 0;
  2189. /* fall through */
  2190. case 'd'|VI_CMDMODE_BIT: {
  2191. int nc, sc;
  2192. ic = lineedit_read_key(read_key_buffer, timeout);
  2193. if (errno) /* error */
  2194. goto return_error_indicator;
  2195. if (ic == ic_raw) { /* "cc", "dd" */
  2196. input_backward(cursor);
  2197. goto clear_to_eol;
  2198. break;
  2199. }
  2200. sc = cursor;
  2201. switch (ic) {
  2202. case 'w':
  2203. case 'W':
  2204. case 'e':
  2205. case 'E':
  2206. switch (ic) {
  2207. case 'w': /* "dw", "cw" */
  2208. vi_word_motion(vi_cmdmode);
  2209. break;
  2210. case 'W': /* 'dW', 'cW' */
  2211. vi_Word_motion(vi_cmdmode);
  2212. break;
  2213. case 'e': /* 'de', 'ce' */
  2214. vi_end_motion();
  2215. input_forward();
  2216. break;
  2217. case 'E': /* 'dE', 'cE' */
  2218. vi_End_motion();
  2219. input_forward();
  2220. break;
  2221. }
  2222. nc = cursor;
  2223. input_backward(cursor - sc);
  2224. while (nc-- > cursor)
  2225. input_delete(1);
  2226. break;
  2227. case 'b': /* "db", "cb" */
  2228. case 'B': /* implemented as B */
  2229. if (ic == 'b')
  2230. vi_back_motion();
  2231. else
  2232. vi_Back_motion();
  2233. while (sc-- > cursor)
  2234. input_delete(1);
  2235. break;
  2236. case ' ': /* "d ", "c " */
  2237. input_delete(1);
  2238. break;
  2239. case '$': /* "d$", "c$" */
  2240. clear_to_eol:
  2241. while (cursor < command_len)
  2242. input_delete(1);
  2243. break;
  2244. }
  2245. break;
  2246. }
  2247. case 'p'|VI_CMDMODE_BIT:
  2248. input_forward();
  2249. /* fallthrough */
  2250. case 'P'|VI_CMDMODE_BIT:
  2251. put();
  2252. break;
  2253. case 'r'|VI_CMDMODE_BIT:
  2254. //FIXME: unicode case?
  2255. ic = lineedit_read_key(read_key_buffer, timeout);
  2256. if (errno) /* error */
  2257. goto return_error_indicator;
  2258. if (ic < ' ' || ic > 255) {
  2259. beep();
  2260. } else {
  2261. command_ps[cursor] = ic;
  2262. bb_putchar(ic);
  2263. bb_putchar('\b');
  2264. }
  2265. break;
  2266. case '\x1b': /* ESC */
  2267. if (state->flags & VI_MODE) {
  2268. /* insert mode --> command mode */
  2269. vi_cmdmode = 1;
  2270. input_backward(1);
  2271. }
  2272. /* Handle a few ESC-<key> combinations the same way
  2273. * standard readline bindings (IOW: bash) do.
  2274. * Often, Alt-<key> generates ESC-<key>.
  2275. */
  2276. ic = lineedit_read_key(read_key_buffer, timeout);
  2277. switch (ic) {
  2278. //case KEYCODE_LEFT: - bash doesn't do this
  2279. case 'b':
  2280. ctrl_left();
  2281. break;
  2282. //case KEYCODE_RIGHT: - bash doesn't do this
  2283. case 'f':
  2284. ctrl_right();
  2285. break;
  2286. //case KEYCODE_DELETE: - bash doesn't do this
  2287. case 'd': /* Alt-D */
  2288. {
  2289. /* Delete word forward */
  2290. int nc, sc = cursor;
  2291. ctrl_right();
  2292. nc = cursor - sc;
  2293. input_backward(nc);
  2294. while (--nc >= 0)
  2295. input_delete(1);
  2296. break;
  2297. }
  2298. case '\b': /* Alt-Backspace(?) */
  2299. case '\x7f': /* Alt-Backspace(?) */
  2300. //case 'w': - bash doesn't do this
  2301. {
  2302. /* Delete word backward */
  2303. int sc = cursor;
  2304. ctrl_left();
  2305. while (sc-- > cursor)
  2306. input_delete(1);
  2307. break;
  2308. }
  2309. }
  2310. break;
  2311. #endif /* FEATURE_COMMAND_EDITING_VI */
  2312. #if MAX_HISTORY > 0
  2313. case KEYCODE_UP:
  2314. if (get_previous_history())
  2315. goto rewrite_line;
  2316. beep();
  2317. break;
  2318. case KEYCODE_DOWN:
  2319. if (!get_next_history())
  2320. break;
  2321. rewrite_line:
  2322. /* Rewrite the line with the selected history item */
  2323. /* change command */
  2324. command_len = load_string(state->history[state->cur_history] ?
  2325. state->history[state->cur_history] : "");
  2326. /* redraw and go to eol (bol, in vi) */
  2327. redraw(cmdedit_y, (state->flags & VI_MODE) ? 9999 : 0);
  2328. break;
  2329. #endif
  2330. case KEYCODE_RIGHT:
  2331. input_forward();
  2332. break;
  2333. case KEYCODE_LEFT:
  2334. input_backward(1);
  2335. break;
  2336. case KEYCODE_CTRL_LEFT:
  2337. case KEYCODE_ALT_LEFT: /* bash doesn't do it */
  2338. ctrl_left();
  2339. break;
  2340. case KEYCODE_CTRL_RIGHT:
  2341. case KEYCODE_ALT_RIGHT: /* bash doesn't do it */
  2342. ctrl_right();
  2343. break;
  2344. case KEYCODE_HOME:
  2345. input_backward(cursor);
  2346. break;
  2347. case KEYCODE_END:
  2348. put_till_end_and_adv_cursor();
  2349. break;
  2350. default:
  2351. if (initial_settings.c_cc[VINTR] != 0
  2352. && ic_raw == initial_settings.c_cc[VINTR]
  2353. ) {
  2354. /* Ctrl-C (usually) - stop gathering input */
  2355. goto_new_line();
  2356. command_len = 0;
  2357. break_out = -1; /* "do not append '\n'" */
  2358. break;
  2359. }
  2360. if (initial_settings.c_cc[VEOF] != 0
  2361. && ic_raw == initial_settings.c_cc[VEOF]
  2362. ) {
  2363. /* Ctrl-D (usually) - delete one character,
  2364. * or exit if len=0 and no chars to delete */
  2365. if (command_len == 0) {
  2366. errno = 0;
  2367. case -1: /* error (e.g. EIO when tty is destroyed) */
  2368. IF_FEATURE_EDITING_VI(return_error_indicator:)
  2369. break_out = command_len = -1;
  2370. break;
  2371. }
  2372. input_delete(0);
  2373. break;
  2374. }
  2375. // /* Control-V -- force insert of next char */
  2376. // if (c == CTRL('V')) {
  2377. // if (safe_read(STDIN_FILENO, &c, 1) < 1)
  2378. // goto return_error_indicator;
  2379. // if (c == 0) {
  2380. // beep();
  2381. // break;
  2382. // }
  2383. // }
  2384. if (ic < ' '
  2385. || (!ENABLE_UNICODE_SUPPORT && ic >= 256)
  2386. || (ENABLE_UNICODE_SUPPORT && ic >= VI_CMDMODE_BIT)
  2387. ) {
  2388. /* If VI_CMDMODE_BIT is set, ic is >= 256
  2389. * and vi mode ignores unexpected chars.
  2390. * Otherwise, we are here if ic is a
  2391. * control char or an unhandled ESC sequence,
  2392. * which is also ignored.
  2393. */
  2394. break;
  2395. }
  2396. if ((int)command_len >= (maxsize - 2)) {
  2397. /* Not enough space for the char and EOL */
  2398. break;
  2399. }
  2400. command_len++;
  2401. if (cursor == (command_len - 1)) {
  2402. /* We are at the end, append */
  2403. command_ps[cursor] = ic;
  2404. command_ps[cursor + 1] = BB_NUL;
  2405. put_cur_glyph_and_inc_cursor();
  2406. if (unicode_bidi_isrtl(ic))
  2407. input_backward(1);
  2408. } else {
  2409. /* In the middle, insert */
  2410. int sc = cursor;
  2411. memmove(command_ps + sc + 1, command_ps + sc,
  2412. (command_len - sc) * sizeof(command_ps[0]));
  2413. command_ps[sc] = ic;
  2414. /* is right-to-left char, or neutral one (e.g. comma) was just added to rtl text? */
  2415. if (!isrtl_str())
  2416. sc++; /* no */
  2417. put_till_end_and_adv_cursor();
  2418. /* to prev x pos + 1 */
  2419. input_backward(cursor - sc);
  2420. }
  2421. break;
  2422. } /* switch (ic) */
  2423. if (break_out)
  2424. break;
  2425. #if ENABLE_FEATURE_TAB_COMPLETION
  2426. if (ic_raw != '\t')
  2427. lastWasTab = 0;
  2428. #endif
  2429. } /* while (1) */
  2430. #if ENABLE_FEATURE_EDITING_ASK_TERMINAL
  2431. if (S.sent_ESC_br6n) {
  2432. /* "sleep 1; busybox ash" + hold [Enter] to trigger.
  2433. * We sent "ESC [ 6 n", but got '\n' first, and
  2434. * KEYCODE_CURSOR_POS response is now buffered from terminal.
  2435. * It's bad already and not much can be done with it
  2436. * (it _will_ be visible for the next process to read stdin),
  2437. * but without this delay it even shows up on the screen
  2438. * as garbage because we restore echo settings with tcsetattr
  2439. * before it comes in. UGLY!
  2440. */
  2441. usleep(20*1000);
  2442. }
  2443. #endif
  2444. /* End of bug-catching "command_must_not_be_used" trick */
  2445. #undef command
  2446. #if ENABLE_UNICODE_SUPPORT
  2447. command[0] = '\0';
  2448. if (command_len > 0)
  2449. command_len = save_string(command, maxsize - 1);
  2450. free(command_ps);
  2451. #endif
  2452. if (command_len > 0)
  2453. remember_in_history(command);
  2454. if (break_out > 0) {
  2455. command[command_len++] = '\n';
  2456. command[command_len] = '\0';
  2457. }
  2458. #if ENABLE_FEATURE_TAB_COMPLETION
  2459. free_tab_completion_data();
  2460. #endif
  2461. /* restore initial_settings */
  2462. tcsetattr_stdin_TCSANOW(&initial_settings);
  2463. /* restore SIGWINCH handler */
  2464. signal(SIGWINCH, previous_SIGWINCH_handler);
  2465. fflush_all();
  2466. len = command_len;
  2467. DEINIT_S();
  2468. return len; /* can't return command_len, DEINIT_S() destroys it */
  2469. }
  2470. #else /* !FEATURE_EDITING */
  2471. #undef read_line_input
  2472. int FAST_FUNC read_line_input(const char* prompt, char* command, int maxsize)
  2473. {
  2474. fputs(prompt, stdout);
  2475. fflush_all();
  2476. if (!fgets(command, maxsize, stdin))
  2477. return -1;
  2478. return strlen(command);
  2479. }
  2480. #endif /* !FEATURE_EDITING */
  2481. /*
  2482. * Testing
  2483. */
  2484. #ifdef TEST
  2485. #include <locale.h>
  2486. const char *applet_name = "debug stuff usage";
  2487. int main(int argc, char **argv)
  2488. {
  2489. char buff[MAX_LINELEN];
  2490. char *prompt =
  2491. #if ENABLE_FEATURE_EDITING_FANCY_PROMPT
  2492. "\\[\\033[32;1m\\]\\u@\\[\\x1b[33;1m\\]\\h:"
  2493. "\\[\\033[34;1m\\]\\w\\[\\033[35;1m\\] "
  2494. "\\!\\[\\e[36;1m\\]\\$ \\[\\E[0m\\]";
  2495. #else
  2496. "% ";
  2497. #endif
  2498. while (1) {
  2499. int l;
  2500. l = read_line_input(prompt, buff);
  2501. if (l <= 0 || buff[l-1] != '\n')
  2502. break;
  2503. buff[l-1] = '\0';
  2504. printf("*** read_line_input() returned line =%s=\n", buff);
  2505. }
  2506. printf("*** read_line_input() detect ^D\n");
  2507. return 0;
  2508. }
  2509. #endif /* TEST */