lineedit.c 76 KB

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