lineedit.c 71 KB

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