lineedit.c 70 KB

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