lineedit.c 60 KB

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