lineedit.c 72 KB

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