3
0

lineedit.c 74 KB

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