lineedit.c 70 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091929394959697989910010110210310410510610710810911011111211311411511611711811912012112212312412512612712812913013113213313413513613713813914014114214314414514614714814915015115215315415515615715815916016116216316416516616716816917017117217317417517617717817918018118218318418518618718818919019119219319419519619719819920020120220320420520620720820921021121221321421521621721821922022122222322422522622722822923023123223323423523623723823924024124224324424524624724824925025125225325425525625725825926026126226326426526626726826927027127227327427527627727827928028128228328428528628728828929029129229329429529629729829930030130230330430530630730830931031131231331431531631731831932032132232332432532632732832933033133233333433533633733833934034134234334434534634734834935035135235335435535635735835936036136236336436536636736836937037137237337437537637737837938038138238338438538638738838939039139239339439539639739839940040140240340440540640740840941041141241341441541641741841942042142242342442542642742842943043143243343443543643743843944044144244344444544644744844945045145245345445545645745845946046146246346446546646746846947047147247347447547647747847948048148248348448548648748848949049149249349449549649749849950050150250350450550650750850951051151251351451551651751851952052152252352452552652752852953053153253353453553653753853954054154254354454554654754854955055155255355455555655755855956056156256356456556656756856957057157257357457557657757857958058158258358458558658758858959059159259359459559659759859960060160260360460560660760860961061161261361461561661761861962062162262362462562662762862963063163263363463563663763863964064164264364464564664764864965065165265365465565665765865966066166266366466566666766866967067167267367467567667767867968068168268368468568668768868969069169269369469569669769869970070170270370470570670770870971071171271371471571671771871972072172272372472572672772872973073173273373473573673773873974074174274374474574674774874975075175275375475575675775875976076176276376476576676776876977077177277377477577677777877978078178278378478578678778878979079179279379479579679779879980080180280380480580680780880981081181281381481581681781881982082182282382482582682782882983083183283383483583683783883984084184284384484584684784884985085185285385485585685785885986086186286386486586686786886987087187287387487587687787887988088188288388488588688788888989089189289389489589689789889990090190290390490590690790890991091191291391491591691791891992092192292392492592692792892993093193293393493593693793893994094194294394494594694794894995095195295395495595695795895996096196296396496596696796896997097197297397497597697797897998098198298398498598698798898999099199299399499599699799899910001001100210031004100510061007100810091010101110121013101410151016101710181019102010211022102310241025102610271028102910301031103210331034103510361037103810391040104110421043104410451046104710481049105010511052105310541055105610571058105910601061106210631064106510661067106810691070107110721073107410751076107710781079108010811082108310841085108610871088108910901091109210931094109510961097109810991100110111021103110411051106110711081109111011111112111311141115111611171118111911201121112211231124112511261127112811291130113111321133113411351136113711381139114011411142114311441145114611471148114911501151115211531154115511561157115811591160116111621163116411651166116711681169117011711172117311741175117611771178117911801181118211831184118511861187118811891190119111921193119411951196119711981199120012011202120312041205120612071208120912101211121212131214121512161217121812191220122112221223122412251226122712281229123012311232123312341235123612371238123912401241124212431244124512461247124812491250125112521253125412551256125712581259126012611262126312641265126612671268126912701271127212731274127512761277127812791280128112821283128412851286128712881289129012911292129312941295129612971298129913001301130213031304130513061307130813091310131113121313131413151316131713181319132013211322132313241325132613271328132913301331133213331334133513361337133813391340134113421343134413451346134713481349135013511352135313541355135613571358135913601361136213631364136513661367136813691370137113721373137413751376137713781379138013811382138313841385138613871388138913901391139213931394139513961397139813991400140114021403140414051406140714081409141014111412141314141415141614171418141914201421142214231424142514261427142814291430143114321433143414351436143714381439144014411442144314441445144614471448144914501451145214531454145514561457145814591460146114621463146414651466146714681469147014711472147314741475147614771478147914801481148214831484148514861487148814891490149114921493149414951496149714981499150015011502150315041505150615071508150915101511151215131514151515161517151815191520152115221523152415251526152715281529153015311532153315341535153615371538153915401541154215431544154515461547154815491550155115521553155415551556155715581559156015611562156315641565156615671568156915701571157215731574157515761577157815791580158115821583158415851586158715881589159015911592159315941595159615971598159916001601160216031604160516061607160816091610161116121613161416151616161716181619162016211622162316241625162616271628162916301631163216331634163516361637163816391640164116421643164416451646164716481649165016511652165316541655165616571658165916601661166216631664166516661667166816691670167116721673167416751676167716781679168016811682168316841685168616871688168916901691169216931694169516961697169816991700170117021703170417051706170717081709171017111712171317141715171617171718171917201721172217231724172517261727172817291730173117321733173417351736173717381739174017411742174317441745174617471748174917501751175217531754175517561757175817591760176117621763176417651766176717681769177017711772177317741775177617771778177917801781178217831784178517861787178817891790179117921793179417951796179717981799180018011802180318041805180618071808180918101811181218131814181518161817181818191820182118221823182418251826182718281829183018311832183318341835183618371838183918401841184218431844184518461847184818491850185118521853185418551856185718581859186018611862186318641865186618671868186918701871187218731874187518761877187818791880188118821883188418851886188718881889189018911892189318941895189618971898189919001901190219031904190519061907190819091910191119121913191419151916191719181919192019211922192319241925192619271928192919301931193219331934193519361937193819391940194119421943194419451946194719481949195019511952195319541955195619571958195919601961196219631964196519661967196819691970197119721973197419751976197719781979198019811982198319841985198619871988198919901991199219931994199519961997199819992000200120022003200420052006200720082009201020112012201320142015201620172018201920202021202220232024202520262027202820292030203120322033203420352036203720382039204020412042204320442045204620472048204920502051205220532054205520562057205820592060206120622063206420652066206720682069207020712072207320742075207620772078207920802081208220832084208520862087208820892090209120922093209420952096209720982099210021012102210321042105210621072108210921102111211221132114211521162117211821192120212121222123212421252126212721282129213021312132213321342135213621372138213921402141214221432144214521462147214821492150215121522153215421552156215721582159216021612162216321642165216621672168216921702171217221732174217521762177217821792180218121822183218421852186218721882189219021912192219321942195219621972198219922002201220222032204220522062207220822092210221122122213221422152216221722182219222022212222222322242225222622272228222922302231223222332234223522362237223822392240224122422243224422452246224722482249225022512252225322542255225622572258225922602261226222632264226522662267226822692270227122722273227422752276227722782279228022812282228322842285228622872288228922902291229222932294229522962297229822992300230123022303230423052306230723082309231023112312231323142315231623172318231923202321232223232324232523262327232823292330233123322333233423352336233723382339234023412342234323442345234623472348234923502351235223532354235523562357235823592360236123622363236423652366236723682369237023712372237323742375237623772378237923802381238223832384238523862387238823892390239123922393239423952396239723982399240024012402240324042405240624072408240924102411241224132414241524162417241824192420242124222423242424252426242724282429243024312432243324342435243624372438243924402441244224432444244524462447244824492450245124522453245424552456245724582459246024612462246324642465246624672468246924702471247224732474247524762477247824792480248124822483248424852486248724882489249024912492249324942495249624972498249925002501250225032504250525062507250825092510251125122513251425152516251725182519252025212522252325242525252625272528252925302531253225332534253525362537253825392540254125422543254425452546254725482549255025512552255325542555255625572558255925602561256225632564256525662567256825692570257125722573257425752576257725782579258025812582258325842585258625872588258925902591259225932594259525962597259825992600260126022603260426052606260726082609261026112612261326142615261626172618261926202621262226232624262526262627262826292630263126322633263426352636263726382639264026412642264326442645264626472648264926502651265226532654265526562657265826592660266126622663266426652666266726682669267026712672267326742675267626772678267926802681268226832684268526862687268826892690269126922693269426952696269726982699270027012702270327042705270627072708270927102711271227132714271527162717271827192720272127222723272427252726272727282729273027312732273327342735273627372738273927402741274227432744274527462747274827492750275127522753275427552756275727582759276027612762276327642765276627672768276927702771277227732774277527762777277827792780278127822783278427852786278727882789279027912792279327942795279627972798279928002801280228032804280528062807280828092810281128122813281428152816281728182819282028212822282328242825282628272828282928302831283228332834283528362837283828392840284128422843284428452846284728482849285028512852285328542855285628572858285928602861286228632864286528662867286828692870287128722873287428752876287728782879
  1. /* vi: set sw=4 ts=4: */
  2. /*
  3. * Command line editing.
  4. *
  5. * Copyright (c) 1986-2003 may safely be consumed by a BSD or GPL license.
  6. * Written by: Vladimir Oleynik <dzo@simtreas.ru>
  7. *
  8. * Used ideas:
  9. * Adam Rogoyski <rogoyski@cs.utexas.edu>
  10. * Dave Cinege <dcinege@psychosis.com>
  11. * Jakub Jelinek (c) 1995
  12. * Erik Andersen <andersen@codepoet.org> (Majorly adjusted for busybox)
  13. *
  14. * This code is 'as is' with no warranty.
  15. */
  16. /*
  17. * Usage and known bugs:
  18. * Terminal key codes are not extensive, more needs to be added.
  19. * This version was created on Debian GNU/Linux 2.x.
  20. * Delete, Backspace, Home, End, and the arrow keys were tested
  21. * to work in an Xterm and console. Ctrl-A also works as Home.
  22. * Ctrl-E also works as End.
  23. *
  24. * The following readline-like commands are not implemented:
  25. * CTL-t -- Transpose two characters
  26. *
  27. * lineedit does not know that the terminal escape sequences do not
  28. * take up space on the screen. The redisplay code assumes, unless
  29. * told otherwise, that each character in the prompt is a printable
  30. * character that takes up one character position on the screen.
  31. * You need to tell lineedit that some sequences of characters
  32. * in the prompt take up no screen space. Compatibly with readline,
  33. * use the \[ escape to begin a sequence of non-printing characters,
  34. * and the \] escape to signal the end of such a sequence. Example:
  35. *
  36. * PS1='\[\033[01;32m\]\u@\h\[\033[01;34m\] \w \$\[\033[00m\] '
  37. *
  38. * Unicode in PS1 is not fully supported: prompt length calulation is wrong,
  39. * resulting in line wrap problems with long (multi-line) input.
  40. *
  41. * Multi-line PS1 (e.g. PS1="\n[\w]\n$ ") has problems with history
  42. * browsing: up/down arrows result in scrolling.
  43. * It stems from simplistic "cmdedit_y = cmdedit_prmt_len / cmdedit_termw"
  44. * calculation of how many lines the prompt takes.
  45. */
  46. #include "busybox.h"
  47. #include "NUM_APPLETS.h"
  48. #include "unicode.h"
  49. #ifndef _POSIX_VDISABLE
  50. # define _POSIX_VDISABLE '\0'
  51. #endif
  52. #ifdef TEST
  53. # define ENABLE_FEATURE_EDITING 0
  54. # define ENABLE_FEATURE_TAB_COMPLETION 0
  55. # define ENABLE_FEATURE_USERNAME_COMPLETION 0
  56. #endif
  57. /* Entire file (except TESTing part) sits inside this #if */
  58. #if ENABLE_FEATURE_EDITING
  59. #define ENABLE_USERNAME_OR_HOMEDIR \
  60. (ENABLE_FEATURE_USERNAME_COMPLETION || ENABLE_FEATURE_EDITING_FANCY_PROMPT)
  61. #define IF_USERNAME_OR_HOMEDIR(...)
  62. #if ENABLE_USERNAME_OR_HOMEDIR
  63. # undef IF_USERNAME_OR_HOMEDIR
  64. # define IF_USERNAME_OR_HOMEDIR(...) __VA_ARGS__
  65. #endif
  66. #undef CHAR_T
  67. #if ENABLE_UNICODE_SUPPORT
  68. # define BB_NUL ((wchar_t)0)
  69. # define CHAR_T wchar_t
  70. static bool BB_isspace(CHAR_T c) { return ((unsigned)c < 256 && isspace(c)); }
  71. # if ENABLE_FEATURE_EDITING_VI
  72. static bool BB_isalnum_or_underscore(CHAR_T c) {
  73. return ((unsigned)c < 256 && isalnum(c)) || c == '_';
  74. }
  75. # endif
  76. static bool BB_ispunct(CHAR_T c) { return ((unsigned)c < 256 && ispunct(c)); }
  77. # undef isspace
  78. # undef isalnum
  79. # undef ispunct
  80. # undef isprint
  81. # define isspace isspace_must_not_be_used
  82. # define isalnum isalnum_must_not_be_used
  83. # define ispunct ispunct_must_not_be_used
  84. # define isprint isprint_must_not_be_used
  85. #else
  86. # define BB_NUL '\0'
  87. # define CHAR_T char
  88. # define BB_isspace(c) isspace(c)
  89. # if ENABLE_FEATURE_EDITING_VI
  90. static bool BB_isalnum_or_underscore(CHAR_T c) {
  91. return ((unsigned)c < 256 && isalnum(c)) || c == '_';
  92. }
  93. # endif
  94. # define BB_ispunct(c) ispunct(c)
  95. #endif
  96. #if ENABLE_UNICODE_PRESERVE_BROKEN
  97. # define unicode_mark_raw_byte(wc) ((wc) | 0x20000000)
  98. # define unicode_is_raw_byte(wc) ((wc) & 0x20000000)
  99. #else
  100. # define unicode_is_raw_byte(wc) 0
  101. #endif
  102. #define ESC "\033"
  103. #define SEQ_CLEAR_TILL_END_OF_SCREEN ESC"[J"
  104. //#define SEQ_CLEAR_TILL_END_OF_LINE ESC"[K"
  105. enum {
  106. MAX_LINELEN = CONFIG_FEATURE_EDITING_MAX_LEN < 0x7ff0
  107. ? CONFIG_FEATURE_EDITING_MAX_LEN
  108. : 0x7ff0
  109. };
  110. #if ENABLE_USERNAME_OR_HOMEDIR
  111. static const char null_str[] ALIGN1 = "";
  112. #endif
  113. /* We try to minimize both static and stack usage. */
  114. struct lineedit_statics {
  115. line_input_t *state;
  116. unsigned cmdedit_termw; /* = 80; */ /* actual terminal width */
  117. unsigned cmdedit_x; /* real x (col) terminal position */
  118. unsigned cmdedit_y; /* pseudoreal y (row) terminal position */
  119. unsigned cmdedit_prmt_len; /* length of prompt (without colors etc) */
  120. unsigned cursor;
  121. int command_len; /* must be signed */
  122. /* signed maxsize: we want x in "if (x > S.maxsize)"
  123. * to _not_ be promoted to unsigned */
  124. int maxsize;
  125. CHAR_T *command_ps;
  126. const char *cmdedit_prompt;
  127. #if ENABLE_USERNAME_OR_HOMEDIR
  128. char *user_buf;
  129. char *home_pwd_buf; /* = (char*)null_str; */
  130. #endif
  131. #if ENABLE_FEATURE_TAB_COMPLETION
  132. char **matches;
  133. unsigned num_matches;
  134. #endif
  135. unsigned SIGWINCH_saved;
  136. volatile unsigned SIGWINCH_count;
  137. volatile smallint ok_to_redraw;
  138. #if ENABLE_FEATURE_EDITING_VI
  139. # define DELBUFSIZ 128
  140. smallint newdelflag; /* whether delbuf should be reused yet */
  141. CHAR_T *delptr;
  142. CHAR_T delbuf[DELBUFSIZ]; /* a place to store deleted characters */
  143. #endif
  144. #if ENABLE_FEATURE_EDITING_ASK_TERMINAL
  145. smallint sent_ESC_br6n;
  146. #endif
  147. /* Largish struct, keeping it last results in smaller code */
  148. struct sigaction SIGWINCH_handler;
  149. };
  150. /* See lineedit_ptr_hack.c */
  151. extern struct lineedit_statics *const lineedit_ptr_to_statics;
  152. #define S (*lineedit_ptr_to_statics)
  153. #define state (S.state )
  154. #define cmdedit_termw (S.cmdedit_termw )
  155. #define cmdedit_x (S.cmdedit_x )
  156. #define cmdedit_y (S.cmdedit_y )
  157. #define cmdedit_prmt_len (S.cmdedit_prmt_len)
  158. #define cursor (S.cursor )
  159. #define command_len (S.command_len )
  160. #define command_ps (S.command_ps )
  161. #define cmdedit_prompt (S.cmdedit_prompt )
  162. #define user_buf (S.user_buf )
  163. #define home_pwd_buf (S.home_pwd_buf )
  164. #define matches (S.matches )
  165. #define num_matches (S.num_matches )
  166. #define delptr (S.delptr )
  167. #define newdelflag (S.newdelflag )
  168. #define delbuf (S.delbuf )
  169. #define INIT_S() do { \
  170. (*(struct lineedit_statics**)&lineedit_ptr_to_statics) = xzalloc(sizeof(S)); \
  171. barrier(); \
  172. cmdedit_termw = 80; \
  173. IF_USERNAME_OR_HOMEDIR(home_pwd_buf = (char*)null_str;) \
  174. IF_FEATURE_EDITING_VI(delptr = delbuf;) \
  175. } while (0)
  176. static void deinit_S(void)
  177. {
  178. #if ENABLE_FEATURE_EDITING_FANCY_PROMPT
  179. /* This one is allocated only if FANCY_PROMPT is on
  180. * (otherwise it points to verbatim prompt (NOT malloced)) */
  181. free((char*)cmdedit_prompt);
  182. #endif
  183. #if ENABLE_USERNAME_OR_HOMEDIR
  184. free(user_buf);
  185. if (home_pwd_buf != null_str)
  186. free(home_pwd_buf);
  187. #endif
  188. free(lineedit_ptr_to_statics);
  189. }
  190. #define DEINIT_S() deinit_S()
  191. #if ENABLE_UNICODE_SUPPORT
  192. static size_t load_string(const char *src)
  193. {
  194. if (unicode_status == UNICODE_ON) {
  195. ssize_t len = mbstowcs(command_ps, src, S.maxsize - 1);
  196. if (len < 0)
  197. len = 0;
  198. command_ps[len] = BB_NUL;
  199. return len;
  200. } else {
  201. unsigned i = 0;
  202. while (src[i] && i < S.maxsize - 1) {
  203. command_ps[i] = src[i];
  204. i++;
  205. }
  206. command_ps[i] = BB_NUL;
  207. return i;
  208. }
  209. }
  210. static unsigned save_string(char *dst, unsigned maxsize)
  211. {
  212. if (unicode_status == UNICODE_ON) {
  213. # if !ENABLE_UNICODE_PRESERVE_BROKEN
  214. ssize_t len = wcstombs(dst, command_ps, maxsize - 1);
  215. if (len < 0)
  216. len = 0;
  217. dst[len] = '\0';
  218. return len;
  219. # else
  220. unsigned dstpos = 0;
  221. unsigned srcpos = 0;
  222. maxsize--;
  223. while (dstpos < maxsize) {
  224. wchar_t wc;
  225. int n = srcpos;
  226. /* Convert up to 1st invalid byte (or up to end) */
  227. while ((wc = command_ps[srcpos]) != BB_NUL
  228. && !unicode_is_raw_byte(wc)
  229. ) {
  230. srcpos++;
  231. }
  232. command_ps[srcpos] = BB_NUL;
  233. n = wcstombs(dst + dstpos, command_ps + n, maxsize - dstpos);
  234. if (n < 0) /* should not happen */
  235. break;
  236. dstpos += n;
  237. if (wc == BB_NUL) /* usually is */
  238. break;
  239. /* We do have invalid byte here! */
  240. command_ps[srcpos] = wc; /* restore it */
  241. srcpos++;
  242. if (dstpos == maxsize)
  243. break;
  244. dst[dstpos++] = (char) wc;
  245. }
  246. dst[dstpos] = '\0';
  247. return dstpos;
  248. # endif
  249. } else {
  250. unsigned i = 0;
  251. while ((dst[i] = command_ps[i]) != 0)
  252. i++;
  253. return i;
  254. }
  255. }
  256. /* I thought just fputwc(c, stdout) would work. But no... */
  257. static void BB_PUTCHAR(wchar_t c)
  258. {
  259. if (unicode_status == UNICODE_ON) {
  260. char buf[MB_CUR_MAX + 1];
  261. mbstate_t mbst = { 0 };
  262. ssize_t len = wcrtomb(buf, c, &mbst);
  263. if (len > 0) {
  264. buf[len] = '\0';
  265. fputs(buf, stdout);
  266. }
  267. } else {
  268. /* In this case, c is always one byte */
  269. putchar(c);
  270. }
  271. }
  272. # if ENABLE_UNICODE_COMBINING_WCHARS || ENABLE_UNICODE_WIDE_WCHARS
  273. static wchar_t adjust_width_and_validate_wc(unsigned *width_adj, wchar_t wc)
  274. # else
  275. static wchar_t adjust_width_and_validate_wc(wchar_t wc)
  276. # define adjust_width_and_validate_wc(width_adj, wc) \
  277. ((*(width_adj))++, adjust_width_and_validate_wc(wc))
  278. # endif
  279. {
  280. int w = 1;
  281. if (unicode_status == UNICODE_ON) {
  282. if (wc > CONFIG_LAST_SUPPORTED_WCHAR) {
  283. /* note: also true for unicode_is_raw_byte(wc) */
  284. goto subst;
  285. }
  286. w = wcwidth(wc);
  287. if ((ENABLE_UNICODE_COMBINING_WCHARS && w < 0)
  288. || (!ENABLE_UNICODE_COMBINING_WCHARS && w <= 0)
  289. || (!ENABLE_UNICODE_WIDE_WCHARS && w > 1)
  290. ) {
  291. subst:
  292. w = 1;
  293. wc = CONFIG_SUBST_WCHAR;
  294. }
  295. }
  296. # if ENABLE_UNICODE_COMBINING_WCHARS || ENABLE_UNICODE_WIDE_WCHARS
  297. *width_adj += w;
  298. #endif
  299. return wc;
  300. }
  301. #else /* !UNICODE */
  302. static size_t load_string(const char *src)
  303. {
  304. safe_strncpy(command_ps, src, S.maxsize);
  305. return strlen(command_ps);
  306. }
  307. # if ENABLE_FEATURE_TAB_COMPLETION
  308. static void save_string(char *dst, unsigned maxsize)
  309. {
  310. safe_strncpy(dst, command_ps, maxsize);
  311. }
  312. # endif
  313. # define BB_PUTCHAR(c) bb_putchar(c)
  314. /* Should never be called: */
  315. int adjust_width_and_validate_wc(unsigned *width_adj, int wc);
  316. #endif
  317. /* Put 'command_ps[cursor]', cursor++.
  318. * Advance cursor on screen. If we reached right margin, scroll text up
  319. * and remove terminal margin effect by printing 'next_char' */
  320. #define HACK_FOR_WRONG_WIDTH 1
  321. static void put_cur_glyph_and_inc_cursor(void)
  322. {
  323. CHAR_T c = command_ps[cursor];
  324. unsigned width = 0;
  325. int ofs_to_right;
  326. if (c == BB_NUL) {
  327. /* erase character after end of input string */
  328. c = ' ';
  329. } else {
  330. /* advance cursor only if we aren't at the end yet */
  331. cursor++;
  332. if (unicode_status == UNICODE_ON) {
  333. IF_UNICODE_WIDE_WCHARS(width = cmdedit_x;)
  334. c = adjust_width_and_validate_wc(&cmdedit_x, c);
  335. IF_UNICODE_WIDE_WCHARS(width = cmdedit_x - width;)
  336. } else {
  337. cmdedit_x++;
  338. }
  339. }
  340. ofs_to_right = cmdedit_x - cmdedit_termw;
  341. if (!ENABLE_UNICODE_WIDE_WCHARS || ofs_to_right <= 0) {
  342. /* c fits on this line */
  343. BB_PUTCHAR(c);
  344. }
  345. if (ofs_to_right >= 0) {
  346. /* we go to the next line */
  347. #if HACK_FOR_WRONG_WIDTH
  348. /* This works better if our idea of term width is wrong
  349. * and it is actually wider (often happens on serial lines).
  350. * Printing CR,LF *forces* cursor to next line.
  351. * OTOH if terminal width is correct AND terminal does NOT
  352. * have automargin (IOW: it is moving cursor to next line
  353. * by itself (which is wrong for VT-10x terminals)),
  354. * this will break things: there will be one extra empty line */
  355. puts("\r"); /* + implicit '\n' */
  356. #else
  357. /* VT-10x terminals don't wrap cursor to next line when last char
  358. * on the line is printed - cursor stays "over" this char.
  359. * Need to print _next_ char too (first one to appear on next line)
  360. * to make cursor move down to next line.
  361. */
  362. /* Works ok only if cmdedit_termw is correct. */
  363. c = command_ps[cursor];
  364. if (c == BB_NUL)
  365. c = ' ';
  366. BB_PUTCHAR(c);
  367. bb_putchar('\b');
  368. #endif
  369. cmdedit_y++;
  370. if (!ENABLE_UNICODE_WIDE_WCHARS || ofs_to_right == 0) {
  371. width = 0;
  372. } else { /* ofs_to_right > 0 */
  373. /* wide char c didn't fit on prev line */
  374. BB_PUTCHAR(c);
  375. }
  376. cmdedit_x = width;
  377. }
  378. }
  379. /* Move to end of line (by printing all chars till the end) */
  380. static void put_till_end_and_adv_cursor(void)
  381. {
  382. while (cursor < command_len)
  383. put_cur_glyph_and_inc_cursor();
  384. }
  385. /* Go to the next line */
  386. static void goto_new_line(void)
  387. {
  388. put_till_end_and_adv_cursor();
  389. if (cmdedit_x != 0)
  390. bb_putchar('\n');
  391. }
  392. static void beep(void)
  393. {
  394. bb_putchar('\007');
  395. }
  396. static void put_prompt(void)
  397. {
  398. fputs(cmdedit_prompt, stdout);
  399. cursor = 0;
  400. cmdedit_y = cmdedit_prmt_len / cmdedit_termw; /* new quasireal y */
  401. cmdedit_x = cmdedit_prmt_len % cmdedit_termw;
  402. }
  403. /* Move back one character */
  404. /* (optimized for slow terminals) */
  405. static void input_backward(unsigned num)
  406. {
  407. if (num > cursor)
  408. num = cursor;
  409. if (num == 0)
  410. return;
  411. cursor -= num;
  412. if ((ENABLE_UNICODE_COMBINING_WCHARS || ENABLE_UNICODE_WIDE_WCHARS)
  413. && unicode_status == UNICODE_ON
  414. ) {
  415. /* correct NUM to be equal to _screen_ width */
  416. int n = num;
  417. num = 0;
  418. while (--n >= 0)
  419. adjust_width_and_validate_wc(&num, command_ps[cursor + n]);
  420. if (num == 0)
  421. return;
  422. }
  423. if (cmdedit_x >= num) {
  424. cmdedit_x -= num;
  425. if (num <= 4) {
  426. /* This is longer by 5 bytes on x86.
  427. * Also gets miscompiled for ARM users
  428. * (busybox.net/bugs/view.php?id=2274).
  429. * printf(("\b\b\b\b" + 4) - num);
  430. * return;
  431. */
  432. do {
  433. bb_putchar('\b');
  434. } while (--num);
  435. return;
  436. }
  437. printf(ESC"[%uD", num);
  438. return;
  439. }
  440. /* Need to go one or more lines up */
  441. if (ENABLE_UNICODE_WIDE_WCHARS) {
  442. /* With wide chars, it is hard to "backtrack"
  443. * and reliably figure out where to put cursor.
  444. * Example (<> is a wide char; # is an ordinary char, _ cursor):
  445. * |prompt: <><> |
  446. * |<><><><><><> |
  447. * |_ |
  448. * and user presses left arrow. num = 1, cmdedit_x = 0,
  449. * We need to go up one line, and then - how do we know that
  450. * we need to go *10* positions to the right? Because
  451. * |prompt: <>#<>|
  452. * |<><><>#<><><>|
  453. * |_ |
  454. * in this situation we need to go *11* positions to the right.
  455. *
  456. * A simpler thing to do is to redraw everything from the start
  457. * up to new cursor position (which is already known):
  458. */
  459. unsigned sv_cursor;
  460. /* go to 1st column; go up to first line */
  461. printf("\r" ESC"[%uA", cmdedit_y);
  462. cmdedit_y = 0;
  463. sv_cursor = cursor;
  464. put_prompt(); /* sets cursor to 0 */
  465. while (cursor < sv_cursor)
  466. put_cur_glyph_and_inc_cursor();
  467. } else {
  468. int lines_up;
  469. /* num = chars to go back from the beginning of current line: */
  470. num -= cmdedit_x;
  471. /* num=1...w: one line up, w+1...2w: two, etc: */
  472. lines_up = 1 + (num - 1) / cmdedit_termw;
  473. cmdedit_x = (cmdedit_termw * cmdedit_y - num) % cmdedit_termw;
  474. cmdedit_y -= lines_up;
  475. /* go to 1st column; go up */
  476. printf("\r" ESC"[%uA", lines_up);
  477. /* go to correct column.
  478. * xterm, konsole, Linux VT interpret 0 as 1 below! wow.
  479. * need to *make sure* we skip it if cmdedit_x == 0 */
  480. if (cmdedit_x)
  481. printf(ESC"[%uC", cmdedit_x);
  482. }
  483. }
  484. /* draw prompt, editor line, and clear tail */
  485. static void redraw(int y, int back_cursor)
  486. {
  487. if (y > 0) /* up y lines */
  488. printf(ESC"[%uA", y);
  489. bb_putchar('\r');
  490. put_prompt();
  491. put_till_end_and_adv_cursor();
  492. printf(SEQ_CLEAR_TILL_END_OF_SCREEN);
  493. input_backward(back_cursor);
  494. }
  495. /* Delete the char in front of the cursor, optionally saving it
  496. * for later putback */
  497. #if !ENABLE_FEATURE_EDITING_VI
  498. static void input_delete(void)
  499. #define input_delete(save) input_delete()
  500. #else
  501. static void input_delete(int save)
  502. #endif
  503. {
  504. int j = cursor;
  505. if (j == (int)command_len)
  506. return;
  507. #if ENABLE_FEATURE_EDITING_VI
  508. if (save) {
  509. if (newdelflag) {
  510. delptr = delbuf;
  511. newdelflag = 0;
  512. }
  513. if ((delptr - delbuf) < DELBUFSIZ)
  514. *delptr++ = command_ps[j];
  515. }
  516. #endif
  517. memmove(command_ps + j, command_ps + j + 1,
  518. /* (command_len + 1 [because of NUL]) - (j + 1)
  519. * simplified into (command_len - j) */
  520. (command_len - j) * sizeof(command_ps[0]));
  521. command_len--;
  522. put_till_end_and_adv_cursor();
  523. /* Last char is still visible, erase it (and more) */
  524. printf(SEQ_CLEAR_TILL_END_OF_SCREEN);
  525. input_backward(cursor - j); /* back to old pos cursor */
  526. }
  527. #if ENABLE_FEATURE_EDITING_VI
  528. static void put(void)
  529. {
  530. int ocursor;
  531. int j = delptr - delbuf;
  532. if (j == 0)
  533. return;
  534. ocursor = cursor;
  535. /* open hole and then fill it */
  536. memmove(command_ps + cursor + j, command_ps + cursor,
  537. (command_len - cursor + 1) * sizeof(command_ps[0]));
  538. memcpy(command_ps + cursor, delbuf, j * sizeof(command_ps[0]));
  539. command_len += j;
  540. put_till_end_and_adv_cursor();
  541. input_backward(cursor - ocursor - j + 1); /* at end of new text */
  542. }
  543. #endif
  544. /* Delete the char in back of the cursor */
  545. static void input_backspace(void)
  546. {
  547. if (cursor > 0) {
  548. input_backward(1);
  549. input_delete(0);
  550. }
  551. }
  552. /* Move forward one character */
  553. static void input_forward(void)
  554. {
  555. if (cursor < command_len)
  556. put_cur_glyph_and_inc_cursor();
  557. }
  558. #if ENABLE_FEATURE_TAB_COMPLETION
  559. //FIXME:
  560. //needs to be more clever: currently it thinks that "foo\ b<TAB>
  561. //matches the file named "foo bar", which is untrue.
  562. //Also, perhaps "foo b<TAB> needs to complete to "foo bar" <cursor>,
  563. //not "foo bar <cursor>...
  564. static void free_tab_completion_data(void)
  565. {
  566. if (matches) {
  567. while (num_matches)
  568. free(matches[--num_matches]);
  569. free(matches);
  570. matches = NULL;
  571. }
  572. }
  573. static void add_match(char *matched)
  574. {
  575. matches = xrealloc_vector(matches, 4, num_matches);
  576. matches[num_matches] = matched;
  577. num_matches++;
  578. }
  579. # if ENABLE_FEATURE_USERNAME_COMPLETION
  580. /* Replace "~user/..." with "/homedir/...".
  581. * The parameter is malloced, free it or return it
  582. * unchanged if no user is matched.
  583. */
  584. static char *username_path_completion(char *ud)
  585. {
  586. struct passwd *entry;
  587. char *tilde_name = ud;
  588. char *home = NULL;
  589. ud++; /* skip ~ */
  590. if (*ud == '/') { /* "~/..." */
  591. home = home_pwd_buf;
  592. } else {
  593. /* "~user/..." */
  594. ud = strchr(ud, '/');
  595. *ud = '\0'; /* "~user" */
  596. entry = getpwnam(tilde_name + 1);
  597. *ud = '/'; /* restore "~user/..." */
  598. if (entry)
  599. home = entry->pw_dir;
  600. }
  601. if (home) {
  602. ud = concat_path_file(home, ud);
  603. free(tilde_name);
  604. tilde_name = ud;
  605. }
  606. return tilde_name;
  607. }
  608. /* ~use<tab> - find all users with this prefix.
  609. * Return the length of the prefix used for matching.
  610. */
  611. static NOINLINE unsigned complete_username(const char *ud)
  612. {
  613. struct passwd *pw;
  614. unsigned userlen;
  615. ud++; /* skip ~ */
  616. userlen = strlen(ud);
  617. setpwent();
  618. while ((pw = getpwent()) != NULL) {
  619. /* Null usernames should result in all users as possible completions. */
  620. if (/* !ud[0] || */ is_prefixed_with(pw->pw_name, ud)) {
  621. add_match(xasprintf("~%s/", pw->pw_name));
  622. }
  623. }
  624. endpwent(); /* don't keep password file open */
  625. return 1 + userlen;
  626. }
  627. # endif /* FEATURE_USERNAME_COMPLETION */
  628. enum {
  629. FIND_EXE_ONLY = 0,
  630. FIND_DIR_ONLY = 1,
  631. FIND_FILE_ONLY = 2,
  632. };
  633. static int path_parse(char ***p)
  634. {
  635. int npth;
  636. const char *pth;
  637. char *tmp;
  638. char **res;
  639. if (state->flags & WITH_PATH_LOOKUP)
  640. pth = state->path_lookup;
  641. else
  642. pth = getenv("PATH");
  643. /* PATH="" or PATH=":"? */
  644. if (!pth || !pth[0] || LONE_CHAR(pth, ':'))
  645. return 1;
  646. tmp = (char*)pth;
  647. npth = 1; /* path component count */
  648. while (1) {
  649. tmp = strchr(tmp, ':');
  650. if (!tmp)
  651. break;
  652. tmp++;
  653. if (*tmp == '\0')
  654. break; /* :<empty> */
  655. npth++;
  656. }
  657. *p = res = xmalloc(npth * sizeof(res[0]));
  658. res[0] = tmp = xstrdup(pth);
  659. npth = 1;
  660. while (1) {
  661. tmp = strchr(tmp, ':');
  662. if (!tmp)
  663. break;
  664. *tmp++ = '\0'; /* ':' -> '\0' */
  665. if (*tmp == '\0')
  666. break; /* :<empty> */
  667. res[npth++] = tmp;
  668. }
  669. return npth;
  670. }
  671. /* Complete command, directory or file name.
  672. * Return the length of the prefix used for matching.
  673. */
  674. static NOINLINE unsigned complete_cmd_dir_file(const char *command, int type)
  675. {
  676. char *path1[1];
  677. char **paths = path1;
  678. int npaths;
  679. int i;
  680. unsigned pf_len;
  681. const char *pfind;
  682. char *dirbuf = NULL;
  683. npaths = 1;
  684. path1[0] = (char*)".";
  685. pfind = strrchr(command, '/');
  686. if (!pfind) {
  687. if (type == FIND_EXE_ONLY)
  688. npaths = path_parse(&paths);
  689. pfind = command;
  690. } else {
  691. /* point to 'l' in "..../last_component" */
  692. pfind++;
  693. /* dirbuf = ".../.../.../" */
  694. dirbuf = xstrndup(command, pfind - command);
  695. # if ENABLE_FEATURE_USERNAME_COMPLETION
  696. if (dirbuf[0] == '~') /* ~/... or ~user/... */
  697. dirbuf = username_path_completion(dirbuf);
  698. # endif
  699. path1[0] = dirbuf;
  700. }
  701. pf_len = strlen(pfind);
  702. #if ENABLE_FEATURE_SH_STANDALONE && NUM_APPLETS != 1
  703. if (type == FIND_EXE_ONLY && !dirbuf) {
  704. const char *p = applet_names;
  705. while (*p) {
  706. if (strncmp(pfind, p, pf_len) == 0)
  707. add_match(xstrdup(p));
  708. while (*p++ != '\0')
  709. continue;
  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_or_underscore(command[cursor])) {
  1430. while (cursor < command_len
  1431. && (BB_isalnum_or_underscore(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_or_underscore(command[cursor])) {
  1468. while (cursor < command_len-1
  1469. && (BB_isalnum_or_underscore(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_or_underscore(command[cursor])) {
  1499. while (cursor > 0
  1500. && (BB_isalnum_or_underscore(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(void)
  1792. {
  1793. int new_y;
  1794. cmdedit_termw = get_terminal_width(STDIN_FILENO);
  1795. /* new y for current cursor */
  1796. new_y = (cursor + cmdedit_prmt_len) / cmdedit_termw;
  1797. /* redraw */
  1798. redraw((new_y >= cmdedit_y ? new_y : cmdedit_y), command_len - cursor);
  1799. }
  1800. static void win_changed(int nsig UNUSED_PARAM)
  1801. {
  1802. if (S.ok_to_redraw) {
  1803. /* We are in read_key(), safe to redraw immediately */
  1804. int sv_errno = errno;
  1805. cmdedit_setwidth();
  1806. fflush_all();
  1807. errno = sv_errno;
  1808. } else {
  1809. /* Signal main loop that redraw is necessary */
  1810. S.SIGWINCH_count++;
  1811. }
  1812. }
  1813. static int lineedit_read_key(char *read_key_buffer, int timeout)
  1814. {
  1815. int64_t ic;
  1816. #if ENABLE_UNICODE_SUPPORT
  1817. char unicode_buf[MB_CUR_MAX + 1];
  1818. int unicode_idx = 0;
  1819. #endif
  1820. fflush_all();
  1821. while (1) {
  1822. /* Wait for input. TIMEOUT = -1 makes read_key wait even
  1823. * on nonblocking stdin, TIMEOUT = 50 makes sure we won't
  1824. * insist on full MB_CUR_MAX buffer to declare input like
  1825. * "\xff\n",pause,"ls\n" invalid and thus won't lose "ls".
  1826. *
  1827. * Note: read_key sets errno to 0 on success.
  1828. */
  1829. S.ok_to_redraw = 1;
  1830. ic = read_key(STDIN_FILENO, read_key_buffer, timeout);
  1831. S.ok_to_redraw = 0;
  1832. if (errno) {
  1833. #if ENABLE_UNICODE_SUPPORT
  1834. if (errno == EAGAIN && unicode_idx != 0)
  1835. goto pushback;
  1836. #endif
  1837. break;
  1838. }
  1839. #if ENABLE_FEATURE_EDITING_ASK_TERMINAL
  1840. if ((int32_t)ic == KEYCODE_CURSOR_POS
  1841. && S.sent_ESC_br6n
  1842. ) {
  1843. S.sent_ESC_br6n = 0;
  1844. if (cursor == 0) { /* otherwise it may be bogus */
  1845. int col = ((ic >> 32) & 0x7fff) - 1;
  1846. /*
  1847. * Is col > cmdedit_prmt_len?
  1848. * If yes (terminal says cursor is farther to the right
  1849. * of where we think it should be),
  1850. * the prompt wasn't printed starting at col 1,
  1851. * there was additional text before it.
  1852. */
  1853. if ((int)(col - cmdedit_prmt_len) > 0) {
  1854. /* Fix our understanding of current x position */
  1855. cmdedit_x += (col - cmdedit_prmt_len);
  1856. while (cmdedit_x >= cmdedit_termw) {
  1857. cmdedit_x -= cmdedit_termw;
  1858. cmdedit_y++;
  1859. }
  1860. }
  1861. }
  1862. continue;
  1863. }
  1864. #endif
  1865. #if ENABLE_UNICODE_SUPPORT
  1866. if (unicode_status == UNICODE_ON) {
  1867. wchar_t wc;
  1868. if ((int32_t)ic < 0) /* KEYCODE_xxx */
  1869. break;
  1870. // TODO: imagine sequence like: 0xff,<left-arrow>: we are currently losing 0xff...
  1871. unicode_buf[unicode_idx++] = ic;
  1872. unicode_buf[unicode_idx] = '\0';
  1873. if (mbstowcs(&wc, unicode_buf, 1) != 1) {
  1874. /* Not (yet?) a valid unicode char */
  1875. if (unicode_idx < MB_CUR_MAX) {
  1876. timeout = 50;
  1877. continue;
  1878. }
  1879. pushback:
  1880. /* Invalid sequence. Save all "bad bytes" except first */
  1881. read_key_ungets(read_key_buffer, unicode_buf + 1, unicode_idx - 1);
  1882. # if !ENABLE_UNICODE_PRESERVE_BROKEN
  1883. ic = CONFIG_SUBST_WCHAR;
  1884. # else
  1885. ic = unicode_mark_raw_byte(unicode_buf[0]);
  1886. # endif
  1887. } else {
  1888. /* Valid unicode char, return its code */
  1889. ic = wc;
  1890. }
  1891. }
  1892. #endif
  1893. break;
  1894. }
  1895. return ic;
  1896. }
  1897. #if ENABLE_UNICODE_BIDI_SUPPORT
  1898. static int isrtl_str(void)
  1899. {
  1900. int idx = cursor;
  1901. while (idx < command_len && unicode_bidi_is_neutral_wchar(command_ps[idx]))
  1902. idx++;
  1903. return unicode_bidi_isrtl(command_ps[idx]);
  1904. }
  1905. #else
  1906. # define isrtl_str() 0
  1907. #endif
  1908. /* leave out the "vi-mode"-only case labels if vi editing isn't
  1909. * configured. */
  1910. #define vi_case(caselabel) IF_FEATURE_EDITING_VI(case caselabel)
  1911. /* convert uppercase ascii to equivalent control char, for readability */
  1912. #undef CTRL
  1913. #define CTRL(a) ((a) & ~0x40)
  1914. enum {
  1915. VI_CMDMODE_BIT = 0x40000000,
  1916. /* 0x80000000 bit flags KEYCODE_xxx */
  1917. };
  1918. #if ENABLE_FEATURE_REVERSE_SEARCH
  1919. /* Mimic readline Ctrl-R reverse history search.
  1920. * When invoked, it shows the following prompt:
  1921. * (reverse-i-search)'': user_input [cursor pos unchanged by Ctrl-R]
  1922. * and typing results in search being performed:
  1923. * (reverse-i-search)'tmp': cd /tmp [cursor under t in /tmp]
  1924. * Search is performed by looking at progressively older lines in history.
  1925. * Ctrl-R again searches for the next match in history.
  1926. * Backspace deletes last matched char.
  1927. * Control keys exit search and return to normal editing (at current history line).
  1928. */
  1929. static int32_t reverse_i_search(void)
  1930. {
  1931. char match_buf[128]; /* for user input */
  1932. char read_key_buffer[KEYCODE_BUFFER_SIZE];
  1933. const char *matched_history_line;
  1934. const char *saved_prompt;
  1935. unsigned saved_prmt_len;
  1936. int32_t ic;
  1937. matched_history_line = NULL;
  1938. read_key_buffer[0] = 0;
  1939. match_buf[0] = '\0';
  1940. /* Save and replace the prompt */
  1941. saved_prompt = cmdedit_prompt;
  1942. saved_prmt_len = cmdedit_prmt_len;
  1943. goto set_prompt;
  1944. while (1) {
  1945. int h;
  1946. unsigned match_buf_len = strlen(match_buf);
  1947. //FIXME: correct timeout?
  1948. ic = lineedit_read_key(read_key_buffer, -1);
  1949. switch (ic) {
  1950. case CTRL('R'): /* searching for the next match */
  1951. break;
  1952. case '\b':
  1953. case '\x7f':
  1954. /* Backspace */
  1955. if (unicode_status == UNICODE_ON) {
  1956. while (match_buf_len != 0) {
  1957. uint8_t c = match_buf[--match_buf_len];
  1958. if ((c & 0xc0) != 0x80) /* start of UTF-8 char? */
  1959. break; /* yes */
  1960. }
  1961. } else {
  1962. if (match_buf_len != 0)
  1963. match_buf_len--;
  1964. }
  1965. match_buf[match_buf_len] = '\0';
  1966. break;
  1967. default:
  1968. if (ic < ' '
  1969. || (!ENABLE_UNICODE_SUPPORT && ic >= 256)
  1970. || (ENABLE_UNICODE_SUPPORT && ic >= VI_CMDMODE_BIT)
  1971. ) {
  1972. goto ret;
  1973. }
  1974. /* Append this char */
  1975. #if ENABLE_UNICODE_SUPPORT
  1976. if (unicode_status == UNICODE_ON) {
  1977. mbstate_t mbstate = { 0 };
  1978. char buf[MB_CUR_MAX + 1];
  1979. int len = wcrtomb(buf, ic, &mbstate);
  1980. if (len > 0) {
  1981. buf[len] = '\0';
  1982. if (match_buf_len + len < sizeof(match_buf))
  1983. strcpy(match_buf + match_buf_len, buf);
  1984. }
  1985. } else
  1986. #endif
  1987. if (match_buf_len < sizeof(match_buf) - 1) {
  1988. match_buf[match_buf_len] = ic;
  1989. match_buf[match_buf_len + 1] = '\0';
  1990. }
  1991. break;
  1992. } /* switch (ic) */
  1993. /* Search in history for match_buf */
  1994. h = state->cur_history;
  1995. if (ic == CTRL('R'))
  1996. h--;
  1997. while (h >= 0) {
  1998. if (state->history[h]) {
  1999. char *match = strstr(state->history[h], match_buf);
  2000. if (match) {
  2001. state->cur_history = h;
  2002. matched_history_line = state->history[h];
  2003. command_len = load_string(matched_history_line);
  2004. cursor = match - matched_history_line;
  2005. //FIXME: cursor position for Unicode case
  2006. free((char*)cmdedit_prompt);
  2007. set_prompt:
  2008. cmdedit_prompt = xasprintf("(reverse-i-search)'%s': ", match_buf);
  2009. cmdedit_prmt_len = unicode_strwidth(cmdedit_prompt);
  2010. goto do_redraw;
  2011. }
  2012. }
  2013. h--;
  2014. }
  2015. /* Not found */
  2016. match_buf[match_buf_len] = '\0';
  2017. beep();
  2018. continue;
  2019. do_redraw:
  2020. redraw(cmdedit_y, command_len - cursor);
  2021. } /* while (1) */
  2022. ret:
  2023. if (matched_history_line)
  2024. command_len = load_string(matched_history_line);
  2025. free((char*)cmdedit_prompt);
  2026. cmdedit_prompt = saved_prompt;
  2027. cmdedit_prmt_len = saved_prmt_len;
  2028. redraw(cmdedit_y, command_len - cursor);
  2029. return ic;
  2030. }
  2031. #endif
  2032. /* maxsize must be >= 2.
  2033. * Returns:
  2034. * -1 on read errors or EOF, or on bare Ctrl-D,
  2035. * 0 on ctrl-C (the line entered is still returned in 'command'),
  2036. * (in both cases the cursor remains on the input line, '\n' is not printed)
  2037. * >0 length of input string, including terminating '\n'
  2038. */
  2039. int FAST_FUNC read_line_input(line_input_t *st, const char *prompt, char *command, int maxsize, int timeout)
  2040. {
  2041. int len;
  2042. #if ENABLE_FEATURE_TAB_COMPLETION
  2043. smallint lastWasTab = 0;
  2044. #endif
  2045. smallint break_out = 0;
  2046. #if ENABLE_FEATURE_EDITING_VI
  2047. smallint vi_cmdmode = 0;
  2048. #endif
  2049. struct termios initial_settings;
  2050. struct termios new_settings;
  2051. char read_key_buffer[KEYCODE_BUFFER_SIZE];
  2052. INIT_S();
  2053. if (tcgetattr(STDIN_FILENO, &initial_settings) < 0
  2054. || (initial_settings.c_lflag & (ECHO|ICANON)) == ICANON
  2055. ) {
  2056. /* Happens when e.g. stty -echo was run before.
  2057. * But if ICANON is not set, we don't come here.
  2058. * (example: interactive python ^Z-backgrounded,
  2059. * tty is still in "raw mode").
  2060. */
  2061. parse_and_put_prompt(prompt);
  2062. fflush_all();
  2063. if (fgets(command, maxsize, stdin) == NULL)
  2064. len = -1; /* EOF or error */
  2065. else
  2066. len = strlen(command);
  2067. DEINIT_S();
  2068. return len;
  2069. }
  2070. init_unicode();
  2071. // FIXME: audit & improve this
  2072. if (maxsize > MAX_LINELEN)
  2073. maxsize = MAX_LINELEN;
  2074. S.maxsize = maxsize;
  2075. /* With zero flags, no other fields are ever used */
  2076. state = st ? st : (line_input_t*) &const_int_0;
  2077. #if MAX_HISTORY > 0
  2078. # if ENABLE_FEATURE_EDITING_SAVEHISTORY
  2079. if (state->hist_file)
  2080. if (state->cnt_history == 0)
  2081. load_history(state);
  2082. # endif
  2083. if (state->flags & DO_HISTORY)
  2084. state->cur_history = state->cnt_history;
  2085. #endif
  2086. /* prepare before init handlers */
  2087. cmdedit_y = 0; /* quasireal y, not true if line > xt*yt */
  2088. command_len = 0;
  2089. #if ENABLE_UNICODE_SUPPORT
  2090. command_ps = xzalloc(maxsize * sizeof(command_ps[0]));
  2091. #else
  2092. command_ps = command;
  2093. command[0] = '\0';
  2094. #endif
  2095. #define command command_must_not_be_used
  2096. new_settings = initial_settings;
  2097. /* ~ICANON: unbuffered input (most c_cc[] are disabled, VMIN/VTIME are enabled) */
  2098. /* ~ECHO, ~ECHONL: turn off echoing, including newline echoing */
  2099. /* ~ISIG: turn off INTR (ctrl-C), QUIT, SUSP */
  2100. new_settings.c_lflag &= ~(ICANON | ECHO | ECHONL | ISIG);
  2101. /* reads will block only if < 1 char is available */
  2102. new_settings.c_cc[VMIN] = 1;
  2103. /* no timeout (reads block forever) */
  2104. new_settings.c_cc[VTIME] = 0;
  2105. /* Should be not needed if ISIG is off: */
  2106. /* Turn off CTRL-C */
  2107. /* new_settings.c_cc[VINTR] = _POSIX_VDISABLE; */
  2108. tcsetattr_stdin_TCSANOW(&new_settings);
  2109. #if ENABLE_USERNAME_OR_HOMEDIR
  2110. {
  2111. struct passwd *entry;
  2112. entry = getpwuid(geteuid());
  2113. if (entry) {
  2114. user_buf = xstrdup(entry->pw_name);
  2115. home_pwd_buf = xstrdup(entry->pw_dir);
  2116. }
  2117. }
  2118. #endif
  2119. #if 0
  2120. for (i = 0; i <= state->max_history; i++)
  2121. bb_error_msg("history[%d]:'%s'", i, state->history[i]);
  2122. bb_error_msg("cur_history:%d cnt_history:%d", state->cur_history, state->cnt_history);
  2123. #endif
  2124. /* Print out the command prompt, optionally ask where cursor is */
  2125. parse_and_put_prompt(prompt);
  2126. ask_terminal();
  2127. /* Install window resize handler (NB: after *all* init is complete) */
  2128. S.SIGWINCH_handler.sa_handler = win_changed;
  2129. S.SIGWINCH_handler.sa_flags = SA_RESTART;
  2130. sigaction(SIGWINCH, &S.SIGWINCH_handler, &S.SIGWINCH_handler);
  2131. cmdedit_termw = get_terminal_width(STDIN_FILENO);
  2132. read_key_buffer[0] = 0;
  2133. while (1) {
  2134. /*
  2135. * The emacs and vi modes share much of the code in the big
  2136. * command loop. Commands entered when in vi's command mode
  2137. * (aka "escape mode") get an extra bit added to distinguish
  2138. * them - this keeps them from being self-inserted. This
  2139. * clutters the big switch a bit, but keeps all the code
  2140. * in one place.
  2141. */
  2142. int32_t ic, ic_raw;
  2143. unsigned count;
  2144. count = S.SIGWINCH_count;
  2145. if (S.SIGWINCH_saved != count) {
  2146. S.SIGWINCH_saved = count;
  2147. cmdedit_setwidth();
  2148. }
  2149. ic = ic_raw = lineedit_read_key(read_key_buffer, timeout);
  2150. #if ENABLE_FEATURE_REVERSE_SEARCH
  2151. again:
  2152. #endif
  2153. #if ENABLE_FEATURE_EDITING_VI
  2154. newdelflag = 1;
  2155. if (vi_cmdmode) {
  2156. /* btw, since KEYCODE_xxx are all < 0, this doesn't
  2157. * change ic if it contains one of them: */
  2158. ic |= VI_CMDMODE_BIT;
  2159. }
  2160. #endif
  2161. switch (ic) {
  2162. case '\n':
  2163. case '\r':
  2164. vi_case('\n'|VI_CMDMODE_BIT:)
  2165. vi_case('\r'|VI_CMDMODE_BIT:)
  2166. /* Enter */
  2167. goto_new_line();
  2168. break_out = 1;
  2169. break;
  2170. case CTRL('A'):
  2171. vi_case('0'|VI_CMDMODE_BIT:)
  2172. /* Control-a -- Beginning of line */
  2173. input_backward(cursor);
  2174. break;
  2175. case CTRL('B'):
  2176. vi_case('h'|VI_CMDMODE_BIT:)
  2177. vi_case('\b'|VI_CMDMODE_BIT:) /* ^H */
  2178. vi_case('\x7f'|VI_CMDMODE_BIT:) /* DEL */
  2179. input_backward(1); /* Move back one character */
  2180. break;
  2181. case CTRL('E'):
  2182. vi_case('$'|VI_CMDMODE_BIT:)
  2183. /* Control-e -- End of line */
  2184. put_till_end_and_adv_cursor();
  2185. break;
  2186. case CTRL('F'):
  2187. vi_case('l'|VI_CMDMODE_BIT:)
  2188. vi_case(' '|VI_CMDMODE_BIT:)
  2189. input_forward(); /* Move forward one character */
  2190. break;
  2191. case '\b': /* ^H */
  2192. case '\x7f': /* DEL */
  2193. if (!isrtl_str())
  2194. input_backspace();
  2195. else
  2196. input_delete(0);
  2197. break;
  2198. case KEYCODE_DELETE:
  2199. if (!isrtl_str())
  2200. input_delete(0);
  2201. else
  2202. input_backspace();
  2203. break;
  2204. #if ENABLE_FEATURE_TAB_COMPLETION
  2205. case '\t':
  2206. input_tab(&lastWasTab);
  2207. break;
  2208. #endif
  2209. case CTRL('K'):
  2210. /* Control-k -- clear to end of line */
  2211. command_ps[cursor] = BB_NUL;
  2212. command_len = cursor;
  2213. printf(SEQ_CLEAR_TILL_END_OF_SCREEN);
  2214. break;
  2215. case CTRL('L'):
  2216. vi_case(CTRL('L')|VI_CMDMODE_BIT:)
  2217. /* Control-l -- clear screen */
  2218. printf(ESC"[H"); /* cursor to top,left */
  2219. redraw(0, command_len - cursor);
  2220. break;
  2221. #if MAX_HISTORY > 0
  2222. case CTRL('N'):
  2223. vi_case(CTRL('N')|VI_CMDMODE_BIT:)
  2224. vi_case('j'|VI_CMDMODE_BIT:)
  2225. /* Control-n -- Get next command in history */
  2226. if (get_next_history())
  2227. goto rewrite_line;
  2228. break;
  2229. case CTRL('P'):
  2230. vi_case(CTRL('P')|VI_CMDMODE_BIT:)
  2231. vi_case('k'|VI_CMDMODE_BIT:)
  2232. /* Control-p -- Get previous command from history */
  2233. if (get_previous_history())
  2234. goto rewrite_line;
  2235. break;
  2236. #endif
  2237. case CTRL('U'):
  2238. vi_case(CTRL('U')|VI_CMDMODE_BIT:)
  2239. /* Control-U -- Clear line before cursor */
  2240. if (cursor) {
  2241. command_len -= cursor;
  2242. memmove(command_ps, command_ps + cursor,
  2243. (command_len + 1) * sizeof(command_ps[0]));
  2244. redraw(cmdedit_y, command_len);
  2245. }
  2246. break;
  2247. case CTRL('W'):
  2248. vi_case(CTRL('W')|VI_CMDMODE_BIT:)
  2249. /* Control-W -- Remove the last word */
  2250. while (cursor > 0 && BB_isspace(command_ps[cursor-1]))
  2251. input_backspace();
  2252. while (cursor > 0 && !BB_isspace(command_ps[cursor-1]))
  2253. input_backspace();
  2254. break;
  2255. case KEYCODE_ALT_D: {
  2256. /* Delete word forward */
  2257. int nc, sc = cursor;
  2258. ctrl_right();
  2259. nc = cursor - sc;
  2260. input_backward(nc);
  2261. while (--nc >= 0)
  2262. input_delete(1);
  2263. break;
  2264. }
  2265. case KEYCODE_ALT_BACKSPACE: {
  2266. /* Delete word backward */
  2267. int sc = cursor;
  2268. ctrl_left();
  2269. while (sc-- > cursor)
  2270. input_delete(1);
  2271. break;
  2272. }
  2273. #if ENABLE_FEATURE_REVERSE_SEARCH
  2274. case CTRL('R'):
  2275. ic = ic_raw = reverse_i_search();
  2276. goto again;
  2277. #endif
  2278. #if ENABLE_FEATURE_EDITING_VI
  2279. case 'i'|VI_CMDMODE_BIT:
  2280. vi_cmdmode = 0;
  2281. break;
  2282. case 'I'|VI_CMDMODE_BIT:
  2283. input_backward(cursor);
  2284. vi_cmdmode = 0;
  2285. break;
  2286. case 'a'|VI_CMDMODE_BIT:
  2287. input_forward();
  2288. vi_cmdmode = 0;
  2289. break;
  2290. case 'A'|VI_CMDMODE_BIT:
  2291. put_till_end_and_adv_cursor();
  2292. vi_cmdmode = 0;
  2293. break;
  2294. case 'x'|VI_CMDMODE_BIT:
  2295. input_delete(1);
  2296. break;
  2297. case 'X'|VI_CMDMODE_BIT:
  2298. if (cursor > 0) {
  2299. input_backward(1);
  2300. input_delete(1);
  2301. }
  2302. break;
  2303. case 'W'|VI_CMDMODE_BIT:
  2304. vi_Word_motion(1);
  2305. break;
  2306. case 'w'|VI_CMDMODE_BIT:
  2307. vi_word_motion(1);
  2308. break;
  2309. case 'E'|VI_CMDMODE_BIT:
  2310. vi_End_motion();
  2311. break;
  2312. case 'e'|VI_CMDMODE_BIT:
  2313. vi_end_motion();
  2314. break;
  2315. case 'B'|VI_CMDMODE_BIT:
  2316. vi_Back_motion();
  2317. break;
  2318. case 'b'|VI_CMDMODE_BIT:
  2319. vi_back_motion();
  2320. break;
  2321. case 'C'|VI_CMDMODE_BIT:
  2322. vi_cmdmode = 0;
  2323. /* fall through */
  2324. case 'D'|VI_CMDMODE_BIT:
  2325. goto clear_to_eol;
  2326. case 'c'|VI_CMDMODE_BIT:
  2327. vi_cmdmode = 0;
  2328. /* fall through */
  2329. case 'd'|VI_CMDMODE_BIT: {
  2330. int nc, sc;
  2331. ic = lineedit_read_key(read_key_buffer, timeout);
  2332. if (errno) /* error */
  2333. goto return_error_indicator;
  2334. if (ic == ic_raw) { /* "cc", "dd" */
  2335. input_backward(cursor);
  2336. goto clear_to_eol;
  2337. break;
  2338. }
  2339. sc = cursor;
  2340. switch (ic) {
  2341. case 'w':
  2342. case 'W':
  2343. case 'e':
  2344. case 'E':
  2345. switch (ic) {
  2346. case 'w': /* "dw", "cw" */
  2347. vi_word_motion(vi_cmdmode);
  2348. break;
  2349. case 'W': /* 'dW', 'cW' */
  2350. vi_Word_motion(vi_cmdmode);
  2351. break;
  2352. case 'e': /* 'de', 'ce' */
  2353. vi_end_motion();
  2354. input_forward();
  2355. break;
  2356. case 'E': /* 'dE', 'cE' */
  2357. vi_End_motion();
  2358. input_forward();
  2359. break;
  2360. }
  2361. nc = cursor;
  2362. input_backward(cursor - sc);
  2363. while (nc-- > cursor)
  2364. input_delete(1);
  2365. break;
  2366. case 'b': /* "db", "cb" */
  2367. case 'B': /* implemented as B */
  2368. if (ic == 'b')
  2369. vi_back_motion();
  2370. else
  2371. vi_Back_motion();
  2372. while (sc-- > cursor)
  2373. input_delete(1);
  2374. break;
  2375. case ' ': /* "d ", "c " */
  2376. input_delete(1);
  2377. break;
  2378. case '$': /* "d$", "c$" */
  2379. clear_to_eol:
  2380. while (cursor < command_len)
  2381. input_delete(1);
  2382. break;
  2383. }
  2384. break;
  2385. }
  2386. case 'p'|VI_CMDMODE_BIT:
  2387. input_forward();
  2388. /* fallthrough */
  2389. case 'P'|VI_CMDMODE_BIT:
  2390. put();
  2391. break;
  2392. case 'r'|VI_CMDMODE_BIT:
  2393. //FIXME: unicode case?
  2394. ic = lineedit_read_key(read_key_buffer, timeout);
  2395. if (errno) /* error */
  2396. goto return_error_indicator;
  2397. if (ic < ' ' || ic > 255) {
  2398. beep();
  2399. } else {
  2400. command_ps[cursor] = ic;
  2401. bb_putchar(ic);
  2402. bb_putchar('\b');
  2403. }
  2404. break;
  2405. case '\x1b': /* ESC */
  2406. if (state->flags & VI_MODE) {
  2407. /* insert mode --> command mode */
  2408. vi_cmdmode = 1;
  2409. input_backward(1);
  2410. }
  2411. break;
  2412. #endif /* FEATURE_COMMAND_EDITING_VI */
  2413. #if MAX_HISTORY > 0
  2414. case KEYCODE_UP:
  2415. if (get_previous_history())
  2416. goto rewrite_line;
  2417. beep();
  2418. break;
  2419. case KEYCODE_DOWN:
  2420. if (!get_next_history())
  2421. break;
  2422. rewrite_line:
  2423. /* Rewrite the line with the selected history item */
  2424. /* change command */
  2425. command_len = load_string(state->history[state->cur_history] ?
  2426. state->history[state->cur_history] : "");
  2427. /* redraw and go to eol (bol, in vi) */
  2428. redraw(cmdedit_y, (state->flags & VI_MODE) ? 9999 : 0);
  2429. break;
  2430. #endif
  2431. case KEYCODE_RIGHT:
  2432. input_forward();
  2433. break;
  2434. case KEYCODE_LEFT:
  2435. input_backward(1);
  2436. break;
  2437. case KEYCODE_CTRL_LEFT:
  2438. case KEYCODE_ALT_LEFT: /* bash doesn't do it */
  2439. ctrl_left();
  2440. break;
  2441. case KEYCODE_CTRL_RIGHT:
  2442. case KEYCODE_ALT_RIGHT: /* bash doesn't do it */
  2443. ctrl_right();
  2444. break;
  2445. case KEYCODE_HOME:
  2446. input_backward(cursor);
  2447. break;
  2448. case KEYCODE_END:
  2449. put_till_end_and_adv_cursor();
  2450. break;
  2451. default:
  2452. if (initial_settings.c_cc[VINTR] != 0
  2453. && ic_raw == initial_settings.c_cc[VINTR]
  2454. ) {
  2455. /* Ctrl-C (usually) - stop gathering input */
  2456. command_len = 0;
  2457. break_out = -1; /* "do not append '\n'" */
  2458. break;
  2459. }
  2460. if (initial_settings.c_cc[VEOF] != 0
  2461. && ic_raw == initial_settings.c_cc[VEOF]
  2462. ) {
  2463. /* Ctrl-D (usually) - delete one character,
  2464. * or exit if len=0 and no chars to delete */
  2465. if (command_len == 0) {
  2466. errno = 0;
  2467. case -1: /* error (e.g. EIO when tty is destroyed) */
  2468. IF_FEATURE_EDITING_VI(return_error_indicator:)
  2469. break_out = command_len = -1;
  2470. break;
  2471. }
  2472. input_delete(0);
  2473. break;
  2474. }
  2475. // /* Control-V -- force insert of next char */
  2476. // if (c == CTRL('V')) {
  2477. // if (safe_read(STDIN_FILENO, &c, 1) < 1)
  2478. // goto return_error_indicator;
  2479. // if (c == 0) {
  2480. // beep();
  2481. // break;
  2482. // }
  2483. // }
  2484. if (ic < ' '
  2485. || (!ENABLE_UNICODE_SUPPORT && ic >= 256)
  2486. || (ENABLE_UNICODE_SUPPORT && ic >= VI_CMDMODE_BIT)
  2487. ) {
  2488. /* If VI_CMDMODE_BIT is set, ic is >= 256
  2489. * and vi mode ignores unexpected chars.
  2490. * Otherwise, we are here if ic is a
  2491. * control char or an unhandled ESC sequence,
  2492. * which is also ignored.
  2493. */
  2494. break;
  2495. }
  2496. if ((int)command_len >= (maxsize - 2)) {
  2497. /* Not enough space for the char and EOL */
  2498. break;
  2499. }
  2500. command_len++;
  2501. if (cursor == (command_len - 1)) {
  2502. /* We are at the end, append */
  2503. command_ps[cursor] = ic;
  2504. command_ps[cursor + 1] = BB_NUL;
  2505. put_cur_glyph_and_inc_cursor();
  2506. if (unicode_bidi_isrtl(ic))
  2507. input_backward(1);
  2508. } else {
  2509. /* In the middle, insert */
  2510. int sc = cursor;
  2511. memmove(command_ps + sc + 1, command_ps + sc,
  2512. (command_len - sc) * sizeof(command_ps[0]));
  2513. command_ps[sc] = ic;
  2514. /* is right-to-left char, or neutral one (e.g. comma) was just added to rtl text? */
  2515. if (!isrtl_str())
  2516. sc++; /* no */
  2517. put_till_end_and_adv_cursor();
  2518. /* to prev x pos + 1 */
  2519. input_backward(cursor - sc);
  2520. }
  2521. break;
  2522. } /* switch (ic) */
  2523. if (break_out)
  2524. break;
  2525. #if ENABLE_FEATURE_TAB_COMPLETION
  2526. if (ic_raw != '\t')
  2527. lastWasTab = 0;
  2528. #endif
  2529. } /* while (1) */
  2530. #if ENABLE_FEATURE_EDITING_ASK_TERMINAL
  2531. if (S.sent_ESC_br6n) {
  2532. /* "sleep 1; busybox ash" + hold [Enter] to trigger.
  2533. * We sent "ESC [ 6 n", but got '\n' first, and
  2534. * KEYCODE_CURSOR_POS response is now buffered from terminal.
  2535. * It's bad already and not much can be done with it
  2536. * (it _will_ be visible for the next process to read stdin),
  2537. * but without this delay it even shows up on the screen
  2538. * as garbage because we restore echo settings with tcsetattr
  2539. * before it comes in. UGLY!
  2540. */
  2541. usleep(20*1000);
  2542. }
  2543. #endif
  2544. /* End of bug-catching "command_must_not_be_used" trick */
  2545. #undef command
  2546. #if ENABLE_UNICODE_SUPPORT
  2547. command[0] = '\0';
  2548. if (command_len > 0)
  2549. command_len = save_string(command, maxsize - 1);
  2550. free(command_ps);
  2551. #endif
  2552. if (command_len > 0) {
  2553. remember_in_history(command);
  2554. }
  2555. if (break_out > 0) {
  2556. command[command_len++] = '\n';
  2557. command[command_len] = '\0';
  2558. }
  2559. #if ENABLE_FEATURE_TAB_COMPLETION
  2560. free_tab_completion_data();
  2561. #endif
  2562. /* restore initial_settings */
  2563. tcsetattr_stdin_TCSANOW(&initial_settings);
  2564. /* restore SIGWINCH handler */
  2565. sigaction_set(SIGWINCH, &S.SIGWINCH_handler);
  2566. fflush_all();
  2567. len = command_len;
  2568. DEINIT_S();
  2569. return len; /* can't return command_len, DEINIT_S() destroys it */
  2570. }
  2571. #else /* !FEATURE_EDITING */
  2572. #undef read_line_input
  2573. int FAST_FUNC read_line_input(const char* prompt, char* command, int maxsize)
  2574. {
  2575. fputs(prompt, stdout);
  2576. fflush_all();
  2577. if (!fgets(command, maxsize, stdin))
  2578. return -1;
  2579. return strlen(command);
  2580. }
  2581. #endif /* !FEATURE_EDITING */
  2582. /*
  2583. * Testing
  2584. */
  2585. #ifdef TEST
  2586. #include <locale.h>
  2587. const char *applet_name = "debug stuff usage";
  2588. int main(int argc, char **argv)
  2589. {
  2590. char buff[MAX_LINELEN];
  2591. char *prompt =
  2592. #if ENABLE_FEATURE_EDITING_FANCY_PROMPT
  2593. "\\[\\033[32;1m\\]\\u@\\[\\x1b[33;1m\\]\\h:"
  2594. "\\[\\033[34;1m\\]\\w\\[\\033[35;1m\\] "
  2595. "\\!\\[\\e[36;1m\\]\\$ \\[\\E[0m\\]";
  2596. #else
  2597. "% ";
  2598. #endif
  2599. while (1) {
  2600. int l;
  2601. l = read_line_input(prompt, buff);
  2602. if (l <= 0 || buff[l-1] != '\n')
  2603. break;
  2604. buff[l-1] = '\0';
  2605. printf("*** read_line_input() returned line =%s=\n", buff);
  2606. }
  2607. printf("*** read_line_input() detect ^D\n");
  2608. return 0;
  2609. }
  2610. #endif /* TEST */