lineedit.c 71 KB

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