lineedit.c 77 KB

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