3
0

lineedit.c 73 KB

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