lineedit.c 73 KB

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