lineedit.c 73 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495969798991001011021031041051061071081091101111121131141151161171181191201211221231241251261271281291301311321331341351361371381391401411421431441451461471481491501511521531541551561571581591601611621631641651661671681691701711721731741751761771781791801811821831841851861871881891901911921931941951961971981992002012022032042052062072082092102112122132142152162172182192202212222232242252262272282292302312322332342352362372382392402412422432442452462472482492502512522532542552562572582592602612622632642652662672682692702712722732742752762772782792802812822832842852862872882892902912922932942952962972982993003013023033043053063073083093103113123133143153163173183193203213223233243253263273283293303313323333343353363373383393403413423433443453463473483493503513523533543553563573583593603613623633643653663673683693703713723733743753763773783793803813823833843853863873883893903913923933943953963973983994004014024034044054064074084094104114124134144154164174184194204214224234244254264274284294304314324334344354364374384394404414424434444454464474484494504514524534544554564574584594604614624634644654664674684694704714724734744754764774784794804814824834844854864874884894904914924934944954964974984995005015025035045055065075085095105115125135145155165175185195205215225235245255265275285295305315325335345355365375385395405415425435445455465475485495505515525535545555565575585595605615625635645655665675685695705715725735745755765775785795805815825835845855865875885895905915925935945955965975985996006016026036046056066076086096106116126136146156166176186196206216226236246256266276286296306316326336346356366376386396406416426436446456466476486496506516526536546556566576586596606616626636646656666676686696706716726736746756766776786796806816826836846856866876886896906916926936946956966976986997007017027037047057067077087097107117127137147157167177187197207217227237247257267277287297307317327337347357367377387397407417427437447457467477487497507517527537547557567577587597607617627637647657667677687697707717727737747757767777787797807817827837847857867877887897907917927937947957967977987998008018028038048058068078088098108118128138148158168178188198208218228238248258268278288298308318328338348358368378388398408418428438448458468478488498508518528538548558568578588598608618628638648658668678688698708718728738748758768778788798808818828838848858868878888898908918928938948958968978988999009019029039049059069079089099109119129139149159169179189199209219229239249259269279289299309319329339349359369379389399409419429439449459469479489499509519529539549559569579589599609619629639649659669679689699709719729739749759769779789799809819829839849859869879889899909919929939949959969979989991000100110021003100410051006100710081009101010111012101310141015101610171018101910201021102210231024102510261027102810291030103110321033103410351036103710381039104010411042104310441045104610471048104910501051105210531054105510561057105810591060106110621063106410651066106710681069107010711072107310741075107610771078107910801081108210831084108510861087108810891090109110921093109410951096109710981099110011011102110311041105110611071108110911101111111211131114111511161117111811191120112111221123112411251126112711281129113011311132113311341135113611371138113911401141114211431144114511461147114811491150115111521153115411551156115711581159116011611162116311641165116611671168116911701171117211731174117511761177117811791180118111821183118411851186118711881189119011911192119311941195119611971198119912001201120212031204120512061207120812091210121112121213121412151216121712181219122012211222122312241225122612271228122912301231123212331234123512361237123812391240124112421243124412451246124712481249125012511252125312541255125612571258125912601261126212631264126512661267126812691270127112721273127412751276127712781279128012811282128312841285128612871288128912901291129212931294129512961297129812991300130113021303130413051306130713081309131013111312131313141315131613171318131913201321132213231324132513261327132813291330133113321333133413351336133713381339134013411342134313441345134613471348134913501351135213531354135513561357135813591360136113621363136413651366136713681369137013711372137313741375137613771378137913801381138213831384138513861387138813891390139113921393139413951396139713981399140014011402140314041405140614071408140914101411141214131414141514161417141814191420142114221423142414251426142714281429143014311432143314341435143614371438143914401441144214431444144514461447144814491450145114521453145414551456145714581459146014611462146314641465146614671468146914701471147214731474147514761477147814791480148114821483148414851486148714881489149014911492149314941495149614971498149915001501150215031504150515061507150815091510151115121513151415151516151715181519152015211522152315241525152615271528152915301531153215331534153515361537153815391540154115421543154415451546154715481549155015511552155315541555155615571558155915601561156215631564156515661567156815691570157115721573157415751576157715781579158015811582158315841585158615871588158915901591159215931594159515961597159815991600160116021603160416051606160716081609161016111612161316141615161616171618161916201621162216231624162516261627162816291630163116321633163416351636163716381639164016411642164316441645164616471648164916501651165216531654165516561657165816591660166116621663166416651666166716681669167016711672167316741675167616771678167916801681168216831684168516861687168816891690169116921693169416951696169716981699170017011702170317041705170617071708170917101711171217131714171517161717171817191720172117221723172417251726172717281729173017311732173317341735173617371738173917401741174217431744174517461747174817491750175117521753175417551756175717581759176017611762176317641765176617671768176917701771177217731774177517761777177817791780178117821783178417851786178717881789179017911792179317941795179617971798179918001801180218031804180518061807180818091810181118121813181418151816181718181819182018211822182318241825182618271828182918301831183218331834183518361837183818391840184118421843184418451846184718481849185018511852185318541855185618571858185918601861186218631864186518661867186818691870187118721873187418751876187718781879188018811882188318841885188618871888188918901891189218931894189518961897189818991900190119021903190419051906190719081909191019111912191319141915191619171918191919201921192219231924192519261927192819291930193119321933193419351936193719381939194019411942194319441945194619471948194919501951195219531954195519561957195819591960196119621963196419651966196719681969197019711972197319741975197619771978197919801981198219831984198519861987198819891990199119921993199419951996199719981999200020012002200320042005200620072008200920102011201220132014201520162017201820192020202120222023202420252026202720282029203020312032203320342035203620372038203920402041204220432044204520462047204820492050205120522053205420552056205720582059206020612062206320642065206620672068206920702071207220732074207520762077207820792080208120822083208420852086208720882089209020912092209320942095209620972098209921002101210221032104210521062107210821092110211121122113211421152116211721182119212021212122212321242125212621272128212921302131213221332134213521362137213821392140214121422143214421452146214721482149215021512152215321542155215621572158215921602161216221632164216521662167216821692170217121722173217421752176217721782179218021812182218321842185218621872188218921902191219221932194219521962197219821992200220122022203220422052206220722082209221022112212221322142215221622172218221922202221222222232224222522262227222822292230223122322233223422352236223722382239224022412242224322442245224622472248224922502251225222532254225522562257225822592260226122622263226422652266226722682269227022712272227322742275227622772278227922802281228222832284228522862287228822892290229122922293229422952296229722982299230023012302230323042305230623072308230923102311231223132314231523162317231823192320232123222323232423252326232723282329233023312332233323342335233623372338233923402341234223432344234523462347234823492350235123522353235423552356235723582359236023612362236323642365236623672368236923702371237223732374237523762377237823792380238123822383238423852386238723882389239023912392239323942395239623972398239924002401240224032404240524062407240824092410241124122413241424152416241724182419242024212422242324242425242624272428242924302431243224332434243524362437243824392440244124422443244424452446244724482449245024512452245324542455245624572458245924602461246224632464246524662467246824692470247124722473247424752476247724782479248024812482248324842485248624872488248924902491249224932494249524962497249824992500250125022503250425052506250725082509251025112512251325142515251625172518251925202521252225232524252525262527252825292530253125322533253425352536253725382539254025412542254325442545254625472548254925502551255225532554255525562557255825592560256125622563256425652566256725682569257025712572257325742575257625772578257925802581258225832584258525862587258825892590259125922593259425952596259725982599260026012602260326042605260626072608260926102611261226132614261526162617261826192620262126222623262426252626262726282629263026312632263326342635263626372638263926402641264226432644264526462647264826492650265126522653265426552656265726582659266026612662266326642665266626672668266926702671267226732674267526762677267826792680268126822683268426852686268726882689269026912692269326942695269626972698269927002701270227032704270527062707270827092710271127122713271427152716271727182719272027212722272327242725272627272728272927302731273227332734273527362737273827392740274127422743274427452746274727482749275027512752275327542755275627572758275927602761276227632764276527662767276827692770277127722773277427752776277727782779278027812782278327842785278627872788278927902791279227932794279527962797279827992800280128022803280428052806280728082809281028112812281328142815281628172818281928202821282228232824282528262827282828292830283128322833283428352836283728382839284028412842284328442845284628472848284928502851285228532854285528562857285828592860286128622863286428652866286728682869287028712872287328742875287628772878287928802881288228832884288528862887288828892890289128922893289428952896289728982899290029012902290329042905290629072908290929102911291229132914291529162917291829192920292129222923292429252926292729282929293029312932293329342935293629372938293929402941
  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. # if ENABLE_FEATURE_EDITING_SAVEHISTORY
  1242. /* We try to ensure that concurrent additions to the history
  1243. * do not overwrite each other.
  1244. * Otherwise shell users get unhappy.
  1245. *
  1246. * History file is trimmed lazily, when it grows several times longer
  1247. * than configured MAX_HISTORY lines.
  1248. */
  1249. void FAST_FUNC free_line_input_t(line_input_t *n)
  1250. {
  1251. int i = n->cnt_history;
  1252. while (i > 0)
  1253. free(n->history[--i]);
  1254. free(n);
  1255. }
  1256. /* state->flags is already checked to be nonzero */
  1257. static void load_history(line_input_t *st_parm)
  1258. {
  1259. char *temp_h[MAX_HISTORY];
  1260. char *line;
  1261. FILE *fp;
  1262. unsigned idx, i, line_len;
  1263. /* NB: do not trash old history if file can't be opened */
  1264. fp = fopen_for_read(st_parm->hist_file);
  1265. if (fp) {
  1266. /* clean up old history */
  1267. for (idx = st_parm->cnt_history; idx > 0;) {
  1268. idx--;
  1269. free(st_parm->history[idx]);
  1270. st_parm->history[idx] = NULL;
  1271. }
  1272. /* fill temp_h[], retaining only last MAX_HISTORY lines */
  1273. memset(temp_h, 0, sizeof(temp_h));
  1274. idx = 0;
  1275. st_parm->cnt_history_in_file = 0;
  1276. while ((line = xmalloc_fgetline(fp)) != NULL) {
  1277. if (line[0] == '\0') {
  1278. free(line);
  1279. continue;
  1280. }
  1281. free(temp_h[idx]);
  1282. temp_h[idx] = line;
  1283. st_parm->cnt_history_in_file++;
  1284. idx++;
  1285. if (idx == st_parm->max_history)
  1286. idx = 0;
  1287. }
  1288. fclose(fp);
  1289. /* find first non-NULL temp_h[], if any */
  1290. if (st_parm->cnt_history_in_file) {
  1291. while (temp_h[idx] == NULL) {
  1292. idx++;
  1293. if (idx == st_parm->max_history)
  1294. idx = 0;
  1295. }
  1296. }
  1297. /* copy temp_h[] to st_parm->history[] */
  1298. for (i = 0; i < st_parm->max_history;) {
  1299. line = temp_h[idx];
  1300. if (!line)
  1301. break;
  1302. idx++;
  1303. if (idx == st_parm->max_history)
  1304. idx = 0;
  1305. line_len = strlen(line);
  1306. if (line_len >= MAX_LINELEN)
  1307. line[MAX_LINELEN-1] = '\0';
  1308. st_parm->history[i++] = line;
  1309. }
  1310. st_parm->cnt_history = i;
  1311. if (ENABLE_FEATURE_EDITING_SAVE_ON_EXIT)
  1312. st_parm->cnt_history_in_file = i;
  1313. }
  1314. }
  1315. # if ENABLE_FEATURE_EDITING_SAVE_ON_EXIT
  1316. void save_history(line_input_t *st)
  1317. {
  1318. FILE *fp;
  1319. if (!st->hist_file)
  1320. return;
  1321. if (st->cnt_history <= st->cnt_history_in_file)
  1322. return;
  1323. fp = fopen(st->hist_file, "a");
  1324. if (fp) {
  1325. int i, fd;
  1326. char *new_name;
  1327. line_input_t *st_temp;
  1328. for (i = st->cnt_history_in_file; i < st->cnt_history; i++)
  1329. fprintf(fp, "%s\n", st->history[i]);
  1330. fclose(fp);
  1331. /* we may have concurrently written entries from others.
  1332. * load them */
  1333. st_temp = new_line_input_t(st->flags);
  1334. st_temp->hist_file = st->hist_file;
  1335. st_temp->max_history = st->max_history;
  1336. load_history(st_temp);
  1337. /* write out temp file and replace hist_file atomically */
  1338. new_name = xasprintf("%s.%u.new", st->hist_file, (int) getpid());
  1339. fd = open(new_name, O_WRONLY | O_CREAT | O_TRUNC, 0600);
  1340. if (fd >= 0) {
  1341. fp = xfdopen_for_write(fd);
  1342. for (i = 0; i < st_temp->cnt_history; i++)
  1343. fprintf(fp, "%s\n", st_temp->history[i]);
  1344. fclose(fp);
  1345. if (rename(new_name, st->hist_file) == 0)
  1346. st->cnt_history_in_file = st_temp->cnt_history;
  1347. }
  1348. free(new_name);
  1349. free_line_input_t(st_temp);
  1350. }
  1351. }
  1352. # else
  1353. static void save_history(char *str)
  1354. {
  1355. int fd;
  1356. int len, len2;
  1357. if (!state->hist_file)
  1358. return;
  1359. fd = open(state->hist_file, O_WRONLY | O_CREAT | O_APPEND, 0600);
  1360. if (fd < 0)
  1361. return;
  1362. xlseek(fd, 0, SEEK_END); /* paranoia */
  1363. len = strlen(str);
  1364. str[len] = '\n'; /* we (try to) do atomic write */
  1365. len2 = full_write(fd, str, len + 1);
  1366. str[len] = '\0';
  1367. close(fd);
  1368. if (len2 != len + 1)
  1369. return; /* "wtf?" */
  1370. /* did we write so much that history file needs trimming? */
  1371. state->cnt_history_in_file++;
  1372. if (state->cnt_history_in_file > state->max_history * 4) {
  1373. char *new_name;
  1374. line_input_t *st_temp;
  1375. /* we may have concurrently written entries from others.
  1376. * load them */
  1377. st_temp = new_line_input_t(state->flags);
  1378. st_temp->hist_file = state->hist_file;
  1379. st_temp->max_history = state->max_history;
  1380. load_history(st_temp);
  1381. /* write out temp file and replace hist_file atomically */
  1382. new_name = xasprintf("%s.%u.new", state->hist_file, (int) getpid());
  1383. fd = open(new_name, O_WRONLY | O_CREAT | O_TRUNC, 0600);
  1384. if (fd >= 0) {
  1385. FILE *fp;
  1386. int i;
  1387. fp = xfdopen_for_write(fd);
  1388. for (i = 0; i < st_temp->cnt_history; i++)
  1389. fprintf(fp, "%s\n", st_temp->history[i]);
  1390. fclose(fp);
  1391. if (rename(new_name, state->hist_file) == 0)
  1392. state->cnt_history_in_file = st_temp->cnt_history;
  1393. }
  1394. free(new_name);
  1395. free_line_input_t(st_temp);
  1396. }
  1397. }
  1398. # endif
  1399. # else
  1400. # define load_history(a) ((void)0)
  1401. # define save_history(a) ((void)0)
  1402. # endif /* FEATURE_COMMAND_SAVEHISTORY */
  1403. static void remember_in_history(char *str)
  1404. {
  1405. int i;
  1406. if (!(state->flags & DO_HISTORY))
  1407. return;
  1408. if (str[0] == '\0')
  1409. return;
  1410. i = state->cnt_history;
  1411. /* Don't save dupes */
  1412. if (i && strcmp(state->history[i-1], str) == 0)
  1413. return;
  1414. free(state->history[state->max_history]); /* redundant, paranoia */
  1415. state->history[state->max_history] = NULL; /* redundant, paranoia */
  1416. /* If history[] is full, remove the oldest command */
  1417. /* we need to keep history[state->max_history] empty, hence >=, not > */
  1418. if (i >= state->max_history) {
  1419. free(state->history[0]);
  1420. for (i = 0; i < state->max_history-1; i++)
  1421. state->history[i] = state->history[i+1];
  1422. /* i == state->max_history-1 */
  1423. # if ENABLE_FEATURE_EDITING_SAVE_ON_EXIT
  1424. if (state->cnt_history_in_file)
  1425. state->cnt_history_in_file--;
  1426. # endif
  1427. }
  1428. /* i <= state->max_history-1 */
  1429. state->history[i++] = xstrdup(str);
  1430. /* i <= state->max_history */
  1431. state->cur_history = i;
  1432. state->cnt_history = i;
  1433. # if ENABLE_FEATURE_EDITING_SAVEHISTORY && !ENABLE_FEATURE_EDITING_SAVE_ON_EXIT
  1434. save_history(str);
  1435. # endif
  1436. }
  1437. #else /* MAX_HISTORY == 0 */
  1438. # define remember_in_history(a) ((void)0)
  1439. #endif /* MAX_HISTORY */
  1440. #if ENABLE_FEATURE_EDITING_VI
  1441. /*
  1442. * vi mode implemented 2005 by Paul Fox <pgf@foxharp.boston.ma.us>
  1443. */
  1444. static void
  1445. vi_Word_motion(int eat)
  1446. {
  1447. CHAR_T *command = command_ps;
  1448. while (cursor < command_len && !BB_isspace(command[cursor]))
  1449. input_forward();
  1450. if (eat) while (cursor < command_len && BB_isspace(command[cursor]))
  1451. input_forward();
  1452. }
  1453. static void
  1454. vi_word_motion(int eat)
  1455. {
  1456. CHAR_T *command = command_ps;
  1457. if (BB_isalnum_or_underscore(command[cursor])) {
  1458. while (cursor < command_len
  1459. && (BB_isalnum_or_underscore(command[cursor+1]))
  1460. ) {
  1461. input_forward();
  1462. }
  1463. } else if (BB_ispunct(command[cursor])) {
  1464. while (cursor < command_len && BB_ispunct(command[cursor+1]))
  1465. input_forward();
  1466. }
  1467. if (cursor < command_len)
  1468. input_forward();
  1469. if (eat) {
  1470. while (cursor < command_len && BB_isspace(command[cursor]))
  1471. input_forward();
  1472. }
  1473. }
  1474. static void
  1475. vi_End_motion(void)
  1476. {
  1477. CHAR_T *command = command_ps;
  1478. input_forward();
  1479. while (cursor < command_len && BB_isspace(command[cursor]))
  1480. input_forward();
  1481. while (cursor < command_len-1 && !BB_isspace(command[cursor+1]))
  1482. input_forward();
  1483. }
  1484. static void
  1485. vi_end_motion(void)
  1486. {
  1487. CHAR_T *command = command_ps;
  1488. if (cursor >= command_len-1)
  1489. return;
  1490. input_forward();
  1491. while (cursor < command_len-1 && BB_isspace(command[cursor]))
  1492. input_forward();
  1493. if (cursor >= command_len-1)
  1494. return;
  1495. if (BB_isalnum_or_underscore(command[cursor])) {
  1496. while (cursor < command_len-1
  1497. && (BB_isalnum_or_underscore(command[cursor+1]))
  1498. ) {
  1499. input_forward();
  1500. }
  1501. } else if (BB_ispunct(command[cursor])) {
  1502. while (cursor < command_len-1 && BB_ispunct(command[cursor+1]))
  1503. input_forward();
  1504. }
  1505. }
  1506. static void
  1507. vi_Back_motion(void)
  1508. {
  1509. CHAR_T *command = command_ps;
  1510. while (cursor > 0 && BB_isspace(command[cursor-1]))
  1511. input_backward(1);
  1512. while (cursor > 0 && !BB_isspace(command[cursor-1]))
  1513. input_backward(1);
  1514. }
  1515. static void
  1516. vi_back_motion(void)
  1517. {
  1518. CHAR_T *command = command_ps;
  1519. if (cursor <= 0)
  1520. return;
  1521. input_backward(1);
  1522. while (cursor > 0 && BB_isspace(command[cursor]))
  1523. input_backward(1);
  1524. if (cursor <= 0)
  1525. return;
  1526. if (BB_isalnum_or_underscore(command[cursor])) {
  1527. while (cursor > 0
  1528. && (BB_isalnum_or_underscore(command[cursor-1]))
  1529. ) {
  1530. input_backward(1);
  1531. }
  1532. } else if (BB_ispunct(command[cursor])) {
  1533. while (cursor > 0 && BB_ispunct(command[cursor-1]))
  1534. input_backward(1);
  1535. }
  1536. }
  1537. #endif
  1538. /* Modelled after bash 4.0 behavior of Ctrl-<arrow> */
  1539. static void ctrl_left(void)
  1540. {
  1541. CHAR_T *command = command_ps;
  1542. while (1) {
  1543. CHAR_T c;
  1544. input_backward(1);
  1545. if (cursor == 0)
  1546. break;
  1547. c = command[cursor];
  1548. if (c != ' ' && !BB_ispunct(c)) {
  1549. /* we reached a "word" delimited by spaces/punct.
  1550. * go to its beginning */
  1551. while (1) {
  1552. c = command[cursor - 1];
  1553. if (c == ' ' || BB_ispunct(c))
  1554. break;
  1555. input_backward(1);
  1556. if (cursor == 0)
  1557. break;
  1558. }
  1559. break;
  1560. }
  1561. }
  1562. }
  1563. static void ctrl_right(void)
  1564. {
  1565. CHAR_T *command = command_ps;
  1566. while (1) {
  1567. CHAR_T c;
  1568. c = command[cursor];
  1569. if (c == BB_NUL)
  1570. break;
  1571. if (c != ' ' && !BB_ispunct(c)) {
  1572. /* we reached a "word" delimited by spaces/punct.
  1573. * go to its end + 1 */
  1574. while (1) {
  1575. input_forward();
  1576. c = command[cursor];
  1577. if (c == BB_NUL || c == ' ' || BB_ispunct(c))
  1578. break;
  1579. }
  1580. break;
  1581. }
  1582. input_forward();
  1583. }
  1584. }
  1585. /*
  1586. * read_line_input and its helpers
  1587. */
  1588. #if ENABLE_FEATURE_EDITING_ASK_TERMINAL
  1589. static void ask_terminal(void)
  1590. {
  1591. /* Ask terminal where is the cursor now.
  1592. * lineedit_read_key handles response and corrects
  1593. * our idea of current cursor position.
  1594. * Testcase: run "echo -n long_line_long_line_long_line",
  1595. * then type in a long, wrapping command and try to
  1596. * delete it using backspace key.
  1597. * Note: we print it _after_ prompt, because
  1598. * prompt may contain CR. Example: PS1='\[\r\n\]\w '
  1599. */
  1600. /* Problem: if there is buffered input on stdin,
  1601. * the response will be delivered later,
  1602. * possibly to an unsuspecting application.
  1603. * Testcase: "sleep 1; busybox ash" + press and hold [Enter].
  1604. * Result:
  1605. * ~/srcdevel/bbox/fix/busybox.t4 #
  1606. * ~/srcdevel/bbox/fix/busybox.t4 #
  1607. * ^[[59;34~/srcdevel/bbox/fix/busybox.t4 # <-- garbage
  1608. * ~/srcdevel/bbox/fix/busybox.t4 #
  1609. *
  1610. * Checking for input with poll only makes the race narrower,
  1611. * I still can trigger it. Strace:
  1612. *
  1613. * write(1, "~/srcdevel/bbox/fix/busybox.t4 # ", 33) = 33
  1614. * poll([{fd=0, events=POLLIN}], 1, 0) = 0 (Timeout) <-- no input exists
  1615. * write(1, "\33[6n", 4) = 4 <-- send the ESC sequence, quick!
  1616. * poll([{fd=0, events=POLLIN}], 1, -1) = 1 ([{fd=0, revents=POLLIN}])
  1617. * read(0, "\n", 1) = 1 <-- oh crap, user's input got in first
  1618. */
  1619. struct pollfd pfd;
  1620. pfd.fd = STDIN_FILENO;
  1621. pfd.events = POLLIN;
  1622. if (safe_poll(&pfd, 1, 0) == 0) {
  1623. S.sent_ESC_br6n = 1;
  1624. fputs(ESC"[6n", stdout);
  1625. fflush_all(); /* make terminal see it ASAP! */
  1626. }
  1627. }
  1628. #else
  1629. #define ask_terminal() ((void)0)
  1630. #endif
  1631. /* Note about multi-line PS1 (e.g. "\n\w \u@\h\n> ") and prompt redrawing:
  1632. *
  1633. * If the prompt has any newlines, after we print it once we use only its last
  1634. * line to redraw in-place, which makes it simpler to calculate how many lines
  1635. * we should move the cursor up to align the redraw (cmdedit_y). The earlier
  1636. * prompt lines just stay on screen and we redraw below them.
  1637. *
  1638. * Use cases for all prompt lines beyond the initial draw:
  1639. * - After clear-screen (^L) or after displaying tab-completion choices, we
  1640. * print the full prompt, as it isn't redrawn in-place.
  1641. * - During terminal resize we could try to redraw all lines, but we don't,
  1642. * because it requires delicate alignment, it's good enough with only the
  1643. * last line, and doing it wrong is arguably worse than not doing it at all.
  1644. *
  1645. * Terminology wise, if it doesn't mention "full", then it means the last/sole
  1646. * prompt line. We use the prompt (last/sole line) while redrawing in-place,
  1647. * and the full where we need a fresh one unrelated to an earlier position.
  1648. *
  1649. * If PS1 is not multiline, the last/sole line and the full are the same string.
  1650. */
  1651. /* Called just once at read_line_input() init time */
  1652. #if !ENABLE_FEATURE_EDITING_FANCY_PROMPT
  1653. static void parse_and_put_prompt(const char *prmt_ptr)
  1654. {
  1655. const char *p;
  1656. cmdedit_prompt = prompt_last_line = prmt_ptr;
  1657. p = strrchr(prmt_ptr, '\n');
  1658. if (p)
  1659. prompt_last_line = p + 1;
  1660. cmdedit_prmt_len = unicode_strwidth(prompt_last_line);
  1661. put_prompt();
  1662. }
  1663. #else
  1664. static void parse_and_put_prompt(const char *prmt_ptr)
  1665. {
  1666. int prmt_size = 0;
  1667. char *prmt_mem_ptr = xzalloc(1);
  1668. # if ENABLE_USERNAME_OR_HOMEDIR
  1669. char *cwd_buf = NULL;
  1670. # endif
  1671. char flg_not_length = '[';
  1672. char cbuf[2];
  1673. /*cmdedit_prmt_len = 0; - already is */
  1674. cbuf[1] = '\0'; /* never changes */
  1675. while (*prmt_ptr) {
  1676. char timebuf[sizeof("HH:MM:SS")];
  1677. char *free_me = NULL;
  1678. char *pbuf;
  1679. char c;
  1680. pbuf = cbuf;
  1681. c = *prmt_ptr++;
  1682. if (c == '\\') {
  1683. const char *cp;
  1684. int l;
  1685. /*
  1686. * Supported via bb_process_escape_sequence:
  1687. * \a ASCII bell character (07)
  1688. * \e ASCII escape character (033)
  1689. * \n newline
  1690. * \r carriage return
  1691. * \\ backslash
  1692. * \nnn char with octal code nnn
  1693. * Supported:
  1694. * \$ if the effective UID is 0, a #, otherwise a $
  1695. * \w current working directory, with $HOME abbreviated with a tilde
  1696. * Note: we do not support $PROMPT_DIRTRIM=n feature
  1697. * \W basename of the current working directory, with $HOME abbreviated with a tilde
  1698. * \h hostname up to the first '.'
  1699. * \H hostname
  1700. * \u username
  1701. * \[ begin a sequence of non-printing characters
  1702. * \] end a sequence of non-printing characters
  1703. * \T current time in 12-hour HH:MM:SS format
  1704. * \@ current time in 12-hour am/pm format
  1705. * \A current time in 24-hour HH:MM format
  1706. * \t current time in 24-hour HH:MM:SS format
  1707. * (all of the above work as \A)
  1708. * Not supported:
  1709. * \! history number of this command
  1710. * \# command number of this command
  1711. * \j number of jobs currently managed by the shell
  1712. * \l basename of the shell's terminal device name
  1713. * \s name of the shell, the basename of $0 (the portion following the final slash)
  1714. * \V release of bash, version + patch level (e.g., 2.00.0)
  1715. * \d date in "Weekday Month Date" format (e.g., "Tue May 26")
  1716. * \D{format}
  1717. * format is passed to strftime(3).
  1718. * An empty format results in a locale-specific time representation.
  1719. * The braces are required.
  1720. * Mishandled by bb_process_escape_sequence:
  1721. * \v version of bash (e.g., 2.00)
  1722. */
  1723. cp = prmt_ptr;
  1724. c = *cp;
  1725. if (c != 't') /* don't treat \t as tab */
  1726. c = bb_process_escape_sequence(&prmt_ptr);
  1727. if (prmt_ptr == cp) {
  1728. if (*cp == '\0')
  1729. break;
  1730. c = *prmt_ptr++;
  1731. switch (c) {
  1732. # if ENABLE_USERNAME_OR_HOMEDIR
  1733. case 'u':
  1734. pbuf = user_buf ? user_buf : (char*)"";
  1735. break;
  1736. # endif
  1737. case 'H':
  1738. case 'h':
  1739. pbuf = free_me = safe_gethostname();
  1740. if (c == 'h')
  1741. strchrnul(pbuf, '.')[0] = '\0';
  1742. break;
  1743. case '$':
  1744. c = (geteuid() == 0 ? '#' : '$');
  1745. break;
  1746. case 'T': /* 12-hour HH:MM:SS format */
  1747. case '@': /* 12-hour am/pm format */
  1748. case 'A': /* 24-hour HH:MM format */
  1749. case 't': /* 24-hour HH:MM:SS format */
  1750. /* We show all of them as 24-hour HH:MM */
  1751. strftime_HHMMSS(timebuf, sizeof(timebuf), NULL)[-3] = '\0';
  1752. pbuf = timebuf;
  1753. break;
  1754. # if ENABLE_USERNAME_OR_HOMEDIR
  1755. case 'w': /* current dir */
  1756. case 'W': /* basename of cur dir */
  1757. if (!cwd_buf) {
  1758. cwd_buf = xrealloc_getcwd_or_warn(NULL);
  1759. if (!cwd_buf)
  1760. cwd_buf = (char *)bb_msg_unknown;
  1761. else if (home_pwd_buf[0]) {
  1762. char *after_home_user;
  1763. /* /home/user[/something] -> ~[/something] */
  1764. after_home_user = is_prefixed_with(cwd_buf, home_pwd_buf);
  1765. if (after_home_user
  1766. && (*after_home_user == '/' || *after_home_user == '\0')
  1767. ) {
  1768. cwd_buf[0] = '~';
  1769. overlapping_strcpy(cwd_buf + 1, after_home_user);
  1770. }
  1771. }
  1772. }
  1773. pbuf = cwd_buf;
  1774. if (c == 'w')
  1775. break;
  1776. cp = strrchr(pbuf, '/');
  1777. if (cp)
  1778. pbuf = (char*)cp + 1;
  1779. break;
  1780. # endif
  1781. // bb_process_escape_sequence does this now:
  1782. // case 'e': case 'E': /* \e \E = \033 */
  1783. // c = '\033';
  1784. // break;
  1785. case 'x': case 'X': {
  1786. char buf2[4];
  1787. for (l = 0; l < 3;) {
  1788. unsigned h;
  1789. buf2[l++] = *prmt_ptr;
  1790. buf2[l] = '\0';
  1791. h = strtoul(buf2, &pbuf, 16);
  1792. if (h > UCHAR_MAX || (pbuf - buf2) < l) {
  1793. buf2[--l] = '\0';
  1794. break;
  1795. }
  1796. prmt_ptr++;
  1797. }
  1798. c = (char)strtoul(buf2, NULL, 16);
  1799. if (c == 0)
  1800. c = '?';
  1801. pbuf = cbuf;
  1802. break;
  1803. }
  1804. case '[': case ']':
  1805. if (c == flg_not_length) {
  1806. /* Toggle '['/']' hex 5b/5d */
  1807. flg_not_length ^= 6;
  1808. continue;
  1809. }
  1810. break;
  1811. } /* switch */
  1812. } /* if */
  1813. } /* if */
  1814. cbuf[0] = c;
  1815. {
  1816. int n = strlen(pbuf);
  1817. prmt_size += n;
  1818. if (c == '\n')
  1819. cmdedit_prmt_len = 0;
  1820. else if (flg_not_length != ']') {
  1821. #if 0 /*ENABLE_UNICODE_SUPPORT*/
  1822. /* Won't work, pbuf is one BYTE string here instead of an one Unicode char string. */
  1823. /* FIXME */
  1824. cmdedit_prmt_len += unicode_strwidth(pbuf);
  1825. #else
  1826. cmdedit_prmt_len += n;
  1827. #endif
  1828. }
  1829. }
  1830. prmt_mem_ptr = strcat(xrealloc(prmt_mem_ptr, prmt_size+1), pbuf);
  1831. free(free_me);
  1832. } /* while */
  1833. # if ENABLE_USERNAME_OR_HOMEDIR
  1834. if (cwd_buf != (char *)bb_msg_unknown)
  1835. free(cwd_buf);
  1836. # endif
  1837. /* see comment (above this function) about multiline prompt redrawing */
  1838. cmdedit_prompt = prompt_last_line = prmt_mem_ptr;
  1839. prmt_ptr = strrchr(cmdedit_prompt, '\n');
  1840. if (prmt_ptr)
  1841. prompt_last_line = prmt_ptr + 1;
  1842. put_prompt();
  1843. }
  1844. #endif
  1845. #if ENABLE_FEATURE_EDITING_WINCH
  1846. static void cmdedit_setwidth(void)
  1847. {
  1848. int new_y;
  1849. cmdedit_termw = get_terminal_width(STDIN_FILENO);
  1850. /* new y for current cursor */
  1851. new_y = (cursor + cmdedit_prmt_len) / cmdedit_termw;
  1852. /* redraw */
  1853. redraw((new_y >= cmdedit_y ? new_y : cmdedit_y), command_len - cursor);
  1854. }
  1855. static void win_changed(int nsig UNUSED_PARAM)
  1856. {
  1857. if (S.ok_to_redraw) {
  1858. /* We are in read_key(), safe to redraw immediately */
  1859. int sv_errno = errno;
  1860. cmdedit_setwidth();
  1861. fflush_all();
  1862. errno = sv_errno;
  1863. } else {
  1864. /* Signal main loop that redraw is necessary */
  1865. S.SIGWINCH_count++;
  1866. }
  1867. }
  1868. #endif
  1869. static int lineedit_read_key(char *read_key_buffer, int timeout)
  1870. {
  1871. int64_t ic;
  1872. #if ENABLE_UNICODE_SUPPORT
  1873. char unicode_buf[MB_CUR_MAX + 1];
  1874. int unicode_idx = 0;
  1875. #endif
  1876. fflush_all();
  1877. while (1) {
  1878. /* Wait for input. TIMEOUT = -1 makes read_key wait even
  1879. * on nonblocking stdin, TIMEOUT = 50 makes sure we won't
  1880. * insist on full MB_CUR_MAX buffer to declare input like
  1881. * "\xff\n",pause,"ls\n" invalid and thus won't lose "ls".
  1882. *
  1883. * Note: read_key sets errno to 0 on success.
  1884. */
  1885. IF_FEATURE_EDITING_WINCH(S.ok_to_redraw = 1;)
  1886. ic = read_key(STDIN_FILENO, read_key_buffer, timeout);
  1887. IF_FEATURE_EDITING_WINCH(S.ok_to_redraw = 0;)
  1888. if (errno) {
  1889. #if ENABLE_UNICODE_SUPPORT
  1890. if (errno == EAGAIN && unicode_idx != 0)
  1891. goto pushback;
  1892. #endif
  1893. break;
  1894. }
  1895. #if ENABLE_FEATURE_EDITING_ASK_TERMINAL
  1896. if ((int32_t)ic == KEYCODE_CURSOR_POS
  1897. && S.sent_ESC_br6n
  1898. ) {
  1899. S.sent_ESC_br6n = 0;
  1900. if (cursor == 0) { /* otherwise it may be bogus */
  1901. int col = ((ic >> 32) & 0x7fff) - 1;
  1902. /*
  1903. * Is col > cmdedit_prmt_len?
  1904. * If yes (terminal says cursor is farther to the right
  1905. * of where we think it should be),
  1906. * the prompt wasn't printed starting at col 1,
  1907. * there was additional text before it.
  1908. */
  1909. if ((int)(col - cmdedit_prmt_len) > 0) {
  1910. /* Fix our understanding of current x position */
  1911. cmdedit_x += (col - cmdedit_prmt_len);
  1912. while (cmdedit_x >= cmdedit_termw) {
  1913. cmdedit_x -= cmdedit_termw;
  1914. cmdedit_y++;
  1915. }
  1916. }
  1917. }
  1918. continue;
  1919. }
  1920. #endif
  1921. #if ENABLE_UNICODE_SUPPORT
  1922. if (unicode_status == UNICODE_ON) {
  1923. wchar_t wc;
  1924. if ((int32_t)ic < 0) /* KEYCODE_xxx */
  1925. break;
  1926. // TODO: imagine sequence like: 0xff,<left-arrow>: we are currently losing 0xff...
  1927. unicode_buf[unicode_idx++] = ic;
  1928. unicode_buf[unicode_idx] = '\0';
  1929. if (mbstowcs(&wc, unicode_buf, 1) != 1) {
  1930. /* Not (yet?) a valid unicode char */
  1931. if (unicode_idx < MB_CUR_MAX) {
  1932. timeout = 50;
  1933. continue;
  1934. }
  1935. pushback:
  1936. /* Invalid sequence. Save all "bad bytes" except first */
  1937. read_key_ungets(read_key_buffer, unicode_buf + 1, unicode_idx - 1);
  1938. # if !ENABLE_UNICODE_PRESERVE_BROKEN
  1939. ic = CONFIG_SUBST_WCHAR;
  1940. # else
  1941. ic = unicode_mark_raw_byte(unicode_buf[0]);
  1942. # endif
  1943. } else {
  1944. /* Valid unicode char, return its code */
  1945. ic = wc;
  1946. }
  1947. }
  1948. #endif
  1949. break;
  1950. }
  1951. return ic;
  1952. }
  1953. #if ENABLE_UNICODE_BIDI_SUPPORT
  1954. static int isrtl_str(void)
  1955. {
  1956. int idx = cursor;
  1957. while (idx < command_len && unicode_bidi_is_neutral_wchar(command_ps[idx]))
  1958. idx++;
  1959. return unicode_bidi_isrtl(command_ps[idx]);
  1960. }
  1961. #else
  1962. # define isrtl_str() 0
  1963. #endif
  1964. /* leave out the "vi-mode"-only case labels if vi editing isn't
  1965. * configured. */
  1966. #define vi_case(caselabel) IF_FEATURE_EDITING_VI(case caselabel)
  1967. /* convert uppercase ascii to equivalent control char, for readability */
  1968. #undef CTRL
  1969. #define CTRL(a) ((a) & ~0x40)
  1970. enum {
  1971. VI_CMDMODE_BIT = 0x40000000,
  1972. /* 0x80000000 bit flags KEYCODE_xxx */
  1973. };
  1974. #if ENABLE_FEATURE_REVERSE_SEARCH
  1975. /* Mimic readline Ctrl-R reverse history search.
  1976. * When invoked, it shows the following prompt:
  1977. * (reverse-i-search)'': user_input [cursor pos unchanged by Ctrl-R]
  1978. * and typing results in search being performed:
  1979. * (reverse-i-search)'tmp': cd /tmp [cursor under t in /tmp]
  1980. * Search is performed by looking at progressively older lines in history.
  1981. * Ctrl-R again searches for the next match in history.
  1982. * Backspace deletes last matched char.
  1983. * Control keys exit search and return to normal editing (at current history line).
  1984. */
  1985. static int32_t reverse_i_search(int timeout)
  1986. {
  1987. char match_buf[128]; /* for user input */
  1988. char read_key_buffer[KEYCODE_BUFFER_SIZE];
  1989. const char *matched_history_line;
  1990. const char *saved_prompt;
  1991. unsigned saved_prmt_len;
  1992. int32_t ic;
  1993. matched_history_line = NULL;
  1994. read_key_buffer[0] = 0;
  1995. match_buf[0] = '\0';
  1996. /* Save and replace the prompt */
  1997. saved_prompt = prompt_last_line;
  1998. saved_prmt_len = cmdedit_prmt_len;
  1999. goto set_prompt;
  2000. while (1) {
  2001. int h;
  2002. unsigned match_buf_len = strlen(match_buf);
  2003. //FIXME: correct timeout? (i.e. count it down?)
  2004. ic = lineedit_read_key(read_key_buffer, timeout);
  2005. switch (ic) {
  2006. case CTRL('R'): /* searching for the next match */
  2007. break;
  2008. case '\b':
  2009. case '\x7f':
  2010. /* Backspace */
  2011. if (unicode_status == UNICODE_ON) {
  2012. while (match_buf_len != 0) {
  2013. uint8_t c = match_buf[--match_buf_len];
  2014. if ((c & 0xc0) != 0x80) /* start of UTF-8 char? */
  2015. break; /* yes */
  2016. }
  2017. } else {
  2018. if (match_buf_len != 0)
  2019. match_buf_len--;
  2020. }
  2021. match_buf[match_buf_len] = '\0';
  2022. break;
  2023. default:
  2024. if (ic < ' '
  2025. || (!ENABLE_UNICODE_SUPPORT && ic >= 256)
  2026. || (ENABLE_UNICODE_SUPPORT && ic >= VI_CMDMODE_BIT)
  2027. ) {
  2028. goto ret;
  2029. }
  2030. /* Append this char */
  2031. #if ENABLE_UNICODE_SUPPORT
  2032. if (unicode_status == UNICODE_ON) {
  2033. mbstate_t mbstate = { 0 };
  2034. char buf[MB_CUR_MAX + 1];
  2035. int len = wcrtomb(buf, ic, &mbstate);
  2036. if (len > 0) {
  2037. buf[len] = '\0';
  2038. if (match_buf_len + len < sizeof(match_buf))
  2039. strcpy(match_buf + match_buf_len, buf);
  2040. }
  2041. } else
  2042. #endif
  2043. if (match_buf_len < sizeof(match_buf) - 1) {
  2044. match_buf[match_buf_len] = ic;
  2045. match_buf[match_buf_len + 1] = '\0';
  2046. }
  2047. break;
  2048. } /* switch (ic) */
  2049. /* Search in history for match_buf */
  2050. h = state->cur_history;
  2051. if (ic == CTRL('R'))
  2052. h--;
  2053. while (h >= 0) {
  2054. if (state->history[h]) {
  2055. char *match = strstr(state->history[h], match_buf);
  2056. if (match) {
  2057. state->cur_history = h;
  2058. matched_history_line = state->history[h];
  2059. command_len = load_string(matched_history_line);
  2060. cursor = match - matched_history_line;
  2061. //FIXME: cursor position for Unicode case
  2062. free((char*)prompt_last_line);
  2063. set_prompt:
  2064. prompt_last_line = xasprintf("(reverse-i-search)'%s': ", match_buf);
  2065. cmdedit_prmt_len = unicode_strwidth(prompt_last_line);
  2066. goto do_redraw;
  2067. }
  2068. }
  2069. h--;
  2070. }
  2071. /* Not found */
  2072. match_buf[match_buf_len] = '\0';
  2073. beep();
  2074. continue;
  2075. do_redraw:
  2076. redraw(cmdedit_y, command_len - cursor);
  2077. } /* while (1) */
  2078. ret:
  2079. if (matched_history_line)
  2080. command_len = load_string(matched_history_line);
  2081. free((char*)prompt_last_line);
  2082. prompt_last_line = saved_prompt;
  2083. cmdedit_prmt_len = saved_prmt_len;
  2084. redraw(cmdedit_y, command_len - cursor);
  2085. return ic;
  2086. }
  2087. #endif
  2088. /* maxsize must be >= 2.
  2089. * Returns:
  2090. * -1 on read errors or EOF, or on bare Ctrl-D,
  2091. * 0 on ctrl-C (the line entered is still returned in 'command'),
  2092. * (in both cases the cursor remains on the input line, '\n' is not printed)
  2093. * >0 length of input string, including terminating '\n'
  2094. */
  2095. int FAST_FUNC read_line_input(line_input_t *st, const char *prompt, char *command, int maxsize)
  2096. {
  2097. int len, n;
  2098. int timeout;
  2099. #if ENABLE_FEATURE_TAB_COMPLETION
  2100. smallint lastWasTab = 0;
  2101. #endif
  2102. smallint break_out = 0;
  2103. #if ENABLE_FEATURE_EDITING_VI
  2104. smallint vi_cmdmode = 0;
  2105. #endif
  2106. struct termios initial_settings;
  2107. struct termios new_settings;
  2108. char read_key_buffer[KEYCODE_BUFFER_SIZE];
  2109. INIT_S();
  2110. n = get_termios_and_make_raw(STDIN_FILENO, &new_settings, &initial_settings, 0
  2111. | TERMIOS_CLEAR_ISIG /* turn off INTR (ctrl-C), QUIT, SUSP */
  2112. );
  2113. if (n != 0 || (initial_settings.c_lflag & (ECHO|ICANON)) == ICANON) {
  2114. /* Happens when e.g. stty -echo was run before.
  2115. * But if ICANON is not set, we don't come here.
  2116. * (example: interactive python ^Z-backgrounded,
  2117. * tty is still in "raw mode").
  2118. */
  2119. parse_and_put_prompt(prompt);
  2120. fflush_all();
  2121. if (fgets(command, maxsize, stdin) == NULL)
  2122. len = -1; /* EOF or error */
  2123. else
  2124. len = strlen(command);
  2125. DEINIT_S();
  2126. return len;
  2127. }
  2128. init_unicode();
  2129. // FIXME: audit & improve this
  2130. if (maxsize > MAX_LINELEN)
  2131. maxsize = MAX_LINELEN;
  2132. S.maxsize = maxsize;
  2133. timeout = -1;
  2134. /* Make state->flags == 0 if st is NULL.
  2135. * With zeroed flags, no other fields are ever referenced.
  2136. */
  2137. state = (line_input_t*) &const_int_0;
  2138. if (st) {
  2139. state = st;
  2140. timeout = st->timeout;
  2141. }
  2142. #if MAX_HISTORY > 0
  2143. # if ENABLE_FEATURE_EDITING_SAVEHISTORY
  2144. if (state->hist_file)
  2145. if (state->cnt_history == 0)
  2146. load_history(state);
  2147. # endif
  2148. if (state->flags & DO_HISTORY)
  2149. state->cur_history = state->cnt_history;
  2150. #endif
  2151. /* prepare before init handlers */
  2152. cmdedit_y = 0; /* quasireal y, not true if line > xt*yt */
  2153. command_len = 0;
  2154. #if ENABLE_UNICODE_SUPPORT
  2155. command_ps = xzalloc(maxsize * sizeof(command_ps[0]));
  2156. #else
  2157. command_ps = command;
  2158. command[0] = '\0';
  2159. #endif
  2160. #define command command_must_not_be_used
  2161. tcsetattr_stdin_TCSANOW(&new_settings);
  2162. #if ENABLE_USERNAME_OR_HOMEDIR
  2163. {
  2164. struct passwd *entry;
  2165. entry = getpwuid(geteuid());
  2166. if (entry) {
  2167. user_buf = xstrdup(entry->pw_name);
  2168. home_pwd_buf = xstrdup(entry->pw_dir);
  2169. }
  2170. }
  2171. #endif
  2172. #if 0
  2173. for (i = 0; i <= state->max_history; i++)
  2174. bb_error_msg("history[%d]:'%s'", i, state->history[i]);
  2175. bb_error_msg("cur_history:%d cnt_history:%d", state->cur_history, state->cnt_history);
  2176. #endif
  2177. /* Get width (before printing prompt) */
  2178. cmdedit_termw = get_terminal_width(STDIN_FILENO);
  2179. /* Print out the command prompt, optionally ask where cursor is */
  2180. parse_and_put_prompt(prompt);
  2181. ask_terminal();
  2182. #if ENABLE_FEATURE_EDITING_WINCH
  2183. /* Install window resize handler (NB: after *all* init is complete) */
  2184. S.SIGWINCH_handler.sa_handler = win_changed;
  2185. S.SIGWINCH_handler.sa_flags = SA_RESTART;
  2186. sigaction(SIGWINCH, &S.SIGWINCH_handler, &S.SIGWINCH_handler);
  2187. #endif
  2188. read_key_buffer[0] = 0;
  2189. while (1) {
  2190. /*
  2191. * The emacs and vi modes share much of the code in the big
  2192. * command loop. Commands entered when in vi's command mode
  2193. * (aka "escape mode") get an extra bit added to distinguish
  2194. * them - this keeps them from being self-inserted. This
  2195. * clutters the big switch a bit, but keeps all the code
  2196. * in one place.
  2197. */
  2198. int32_t ic, ic_raw;
  2199. #if ENABLE_FEATURE_EDITING_WINCH
  2200. unsigned count;
  2201. count = S.SIGWINCH_count;
  2202. if (S.SIGWINCH_saved != count) {
  2203. S.SIGWINCH_saved = count;
  2204. cmdedit_setwidth();
  2205. }
  2206. #endif
  2207. ic = ic_raw = lineedit_read_key(read_key_buffer, timeout);
  2208. #if ENABLE_FEATURE_REVERSE_SEARCH
  2209. again:
  2210. #endif
  2211. #if ENABLE_FEATURE_EDITING_VI
  2212. newdelflag = 1;
  2213. if (vi_cmdmode) {
  2214. /* btw, since KEYCODE_xxx are all < 0, this doesn't
  2215. * change ic if it contains one of them: */
  2216. ic |= VI_CMDMODE_BIT;
  2217. }
  2218. #endif
  2219. switch (ic) {
  2220. case '\n':
  2221. case '\r':
  2222. vi_case('\n'|VI_CMDMODE_BIT:)
  2223. vi_case('\r'|VI_CMDMODE_BIT:)
  2224. /* Enter */
  2225. goto_new_line();
  2226. break_out = 1;
  2227. break;
  2228. case CTRL('A'):
  2229. vi_case('0'|VI_CMDMODE_BIT:)
  2230. /* Control-a -- Beginning of line */
  2231. input_backward(cursor);
  2232. break;
  2233. case CTRL('B'):
  2234. vi_case('h'|VI_CMDMODE_BIT:)
  2235. vi_case('\b'|VI_CMDMODE_BIT:) /* ^H */
  2236. vi_case('\x7f'|VI_CMDMODE_BIT:) /* DEL */
  2237. input_backward(1); /* Move back one character */
  2238. break;
  2239. case CTRL('E'):
  2240. vi_case('$'|VI_CMDMODE_BIT:)
  2241. /* Control-e -- End of line */
  2242. put_till_end_and_adv_cursor();
  2243. break;
  2244. case CTRL('F'):
  2245. vi_case('l'|VI_CMDMODE_BIT:)
  2246. vi_case(' '|VI_CMDMODE_BIT:)
  2247. input_forward(); /* Move forward one character */
  2248. break;
  2249. case '\b': /* ^H */
  2250. case '\x7f': /* DEL */
  2251. if (!isrtl_str())
  2252. input_backspace();
  2253. else
  2254. input_delete(0);
  2255. break;
  2256. case KEYCODE_DELETE:
  2257. if (!isrtl_str())
  2258. input_delete(0);
  2259. else
  2260. input_backspace();
  2261. break;
  2262. #if ENABLE_FEATURE_TAB_COMPLETION
  2263. case '\t':
  2264. input_tab(&lastWasTab);
  2265. break;
  2266. #endif
  2267. case CTRL('K'):
  2268. /* Control-k -- clear to end of line */
  2269. command_ps[cursor] = BB_NUL;
  2270. command_len = cursor;
  2271. printf(SEQ_CLEAR_TILL_END_OF_SCREEN);
  2272. break;
  2273. case CTRL('L'):
  2274. vi_case(CTRL('L')|VI_CMDMODE_BIT:)
  2275. /* Control-l -- clear screen */
  2276. /* cursor to top,left; clear to the end of screen */
  2277. printf(ESC"[H" ESC"[J");
  2278. draw_full(command_len - cursor);
  2279. break;
  2280. #if MAX_HISTORY > 0
  2281. case CTRL('N'):
  2282. vi_case(CTRL('N')|VI_CMDMODE_BIT:)
  2283. vi_case('j'|VI_CMDMODE_BIT:)
  2284. /* Control-n -- Get next command in history */
  2285. if (get_next_history())
  2286. goto rewrite_line;
  2287. break;
  2288. case CTRL('P'):
  2289. vi_case(CTRL('P')|VI_CMDMODE_BIT:)
  2290. vi_case('k'|VI_CMDMODE_BIT:)
  2291. /* Control-p -- Get previous command from history */
  2292. if (get_previous_history())
  2293. goto rewrite_line;
  2294. break;
  2295. #endif
  2296. case CTRL('U'):
  2297. vi_case(CTRL('U')|VI_CMDMODE_BIT:)
  2298. /* Control-U -- Clear line before cursor */
  2299. if (cursor) {
  2300. command_len -= cursor;
  2301. memmove(command_ps, command_ps + cursor,
  2302. (command_len + 1) * sizeof(command_ps[0]));
  2303. redraw(cmdedit_y, command_len);
  2304. }
  2305. break;
  2306. case CTRL('W'):
  2307. vi_case(CTRL('W')|VI_CMDMODE_BIT:)
  2308. /* Control-W -- Remove the last word */
  2309. while (cursor > 0 && BB_isspace(command_ps[cursor-1]))
  2310. input_backspace();
  2311. while (cursor > 0 && !BB_isspace(command_ps[cursor-1]))
  2312. input_backspace();
  2313. break;
  2314. case KEYCODE_ALT_D: {
  2315. /* Delete word forward */
  2316. int nc, sc = cursor;
  2317. ctrl_right();
  2318. nc = cursor - sc;
  2319. input_backward(nc);
  2320. while (--nc >= 0)
  2321. input_delete(1);
  2322. break;
  2323. }
  2324. case KEYCODE_ALT_BACKSPACE: {
  2325. /* Delete word backward */
  2326. int sc = cursor;
  2327. ctrl_left();
  2328. while (sc-- > cursor)
  2329. input_delete(1);
  2330. break;
  2331. }
  2332. #if ENABLE_FEATURE_REVERSE_SEARCH
  2333. case CTRL('R'):
  2334. ic = ic_raw = reverse_i_search(timeout);
  2335. goto again;
  2336. #endif
  2337. #if ENABLE_FEATURE_EDITING_VI
  2338. case 'i'|VI_CMDMODE_BIT:
  2339. vi_cmdmode = 0;
  2340. break;
  2341. case 'I'|VI_CMDMODE_BIT:
  2342. input_backward(cursor);
  2343. vi_cmdmode = 0;
  2344. break;
  2345. case 'a'|VI_CMDMODE_BIT:
  2346. input_forward();
  2347. vi_cmdmode = 0;
  2348. break;
  2349. case 'A'|VI_CMDMODE_BIT:
  2350. put_till_end_and_adv_cursor();
  2351. vi_cmdmode = 0;
  2352. break;
  2353. case 'x'|VI_CMDMODE_BIT:
  2354. input_delete(1);
  2355. break;
  2356. case 'X'|VI_CMDMODE_BIT:
  2357. if (cursor > 0) {
  2358. input_backward(1);
  2359. input_delete(1);
  2360. }
  2361. break;
  2362. case 'W'|VI_CMDMODE_BIT:
  2363. vi_Word_motion(1);
  2364. break;
  2365. case 'w'|VI_CMDMODE_BIT:
  2366. vi_word_motion(1);
  2367. break;
  2368. case 'E'|VI_CMDMODE_BIT:
  2369. vi_End_motion();
  2370. break;
  2371. case 'e'|VI_CMDMODE_BIT:
  2372. vi_end_motion();
  2373. break;
  2374. case 'B'|VI_CMDMODE_BIT:
  2375. vi_Back_motion();
  2376. break;
  2377. case 'b'|VI_CMDMODE_BIT:
  2378. vi_back_motion();
  2379. break;
  2380. case 'C'|VI_CMDMODE_BIT:
  2381. vi_cmdmode = 0;
  2382. /* fall through */
  2383. case 'D'|VI_CMDMODE_BIT:
  2384. goto clear_to_eol;
  2385. case 'c'|VI_CMDMODE_BIT:
  2386. vi_cmdmode = 0;
  2387. /* fall through */
  2388. case 'd'|VI_CMDMODE_BIT: {
  2389. int nc, sc;
  2390. ic = lineedit_read_key(read_key_buffer, timeout);
  2391. if (errno) /* error */
  2392. goto return_error_indicator;
  2393. if (ic == ic_raw) { /* "cc", "dd" */
  2394. input_backward(cursor);
  2395. goto clear_to_eol;
  2396. break;
  2397. }
  2398. sc = cursor;
  2399. switch (ic) {
  2400. case 'w':
  2401. case 'W':
  2402. case 'e':
  2403. case 'E':
  2404. switch (ic) {
  2405. case 'w': /* "dw", "cw" */
  2406. vi_word_motion(vi_cmdmode);
  2407. break;
  2408. case 'W': /* 'dW', 'cW' */
  2409. vi_Word_motion(vi_cmdmode);
  2410. break;
  2411. case 'e': /* 'de', 'ce' */
  2412. vi_end_motion();
  2413. input_forward();
  2414. break;
  2415. case 'E': /* 'dE', 'cE' */
  2416. vi_End_motion();
  2417. input_forward();
  2418. break;
  2419. }
  2420. nc = cursor;
  2421. input_backward(cursor - sc);
  2422. while (nc-- > cursor)
  2423. input_delete(1);
  2424. break;
  2425. case 'b': /* "db", "cb" */
  2426. case 'B': /* implemented as B */
  2427. if (ic == 'b')
  2428. vi_back_motion();
  2429. else
  2430. vi_Back_motion();
  2431. while (sc-- > cursor)
  2432. input_delete(1);
  2433. break;
  2434. case ' ': /* "d ", "c " */
  2435. input_delete(1);
  2436. break;
  2437. case '$': /* "d$", "c$" */
  2438. clear_to_eol:
  2439. while (cursor < command_len)
  2440. input_delete(1);
  2441. break;
  2442. }
  2443. break;
  2444. }
  2445. case 'p'|VI_CMDMODE_BIT:
  2446. input_forward();
  2447. /* fallthrough */
  2448. case 'P'|VI_CMDMODE_BIT:
  2449. put();
  2450. break;
  2451. case 'r'|VI_CMDMODE_BIT:
  2452. //FIXME: unicode case?
  2453. ic = lineedit_read_key(read_key_buffer, timeout);
  2454. if (errno) /* error */
  2455. goto return_error_indicator;
  2456. if (ic < ' ' || ic > 255) {
  2457. beep();
  2458. } else {
  2459. command_ps[cursor] = ic;
  2460. bb_putchar(ic);
  2461. bb_putchar('\b');
  2462. }
  2463. break;
  2464. case '\x1b': /* ESC */
  2465. if (state->flags & VI_MODE) {
  2466. /* insert mode --> command mode */
  2467. vi_cmdmode = 1;
  2468. input_backward(1);
  2469. }
  2470. break;
  2471. #endif /* FEATURE_COMMAND_EDITING_VI */
  2472. #if MAX_HISTORY > 0
  2473. case KEYCODE_UP:
  2474. if (get_previous_history())
  2475. goto rewrite_line;
  2476. beep();
  2477. break;
  2478. case KEYCODE_DOWN:
  2479. if (!get_next_history())
  2480. break;
  2481. rewrite_line:
  2482. /* Rewrite the line with the selected history item */
  2483. /* change command */
  2484. command_len = load_string(state->history[state->cur_history] ?
  2485. state->history[state->cur_history] : "");
  2486. /* redraw and go to eol (bol, in vi) */
  2487. redraw(cmdedit_y, (state->flags & VI_MODE) ? 9999 : 0);
  2488. break;
  2489. #endif
  2490. case KEYCODE_RIGHT:
  2491. input_forward();
  2492. break;
  2493. case KEYCODE_LEFT:
  2494. input_backward(1);
  2495. break;
  2496. case KEYCODE_CTRL_LEFT:
  2497. case KEYCODE_ALT_LEFT: /* bash doesn't do it */
  2498. ctrl_left();
  2499. break;
  2500. case KEYCODE_CTRL_RIGHT:
  2501. case KEYCODE_ALT_RIGHT: /* bash doesn't do it */
  2502. ctrl_right();
  2503. break;
  2504. case KEYCODE_HOME:
  2505. input_backward(cursor);
  2506. break;
  2507. case KEYCODE_END:
  2508. put_till_end_and_adv_cursor();
  2509. break;
  2510. default:
  2511. if (initial_settings.c_cc[VINTR] != 0
  2512. && ic_raw == initial_settings.c_cc[VINTR]
  2513. ) {
  2514. /* Ctrl-C (usually) - stop gathering input */
  2515. command_len = 0;
  2516. break_out = -1; /* "do not append '\n'" */
  2517. break;
  2518. }
  2519. if (initial_settings.c_cc[VEOF] != 0
  2520. && ic_raw == initial_settings.c_cc[VEOF]
  2521. ) {
  2522. /* Ctrl-D (usually) - delete one character,
  2523. * or exit if len=0 and no chars to delete */
  2524. if (command_len == 0) {
  2525. errno = 0;
  2526. case -1: /* error (e.g. EIO when tty is destroyed) */
  2527. IF_FEATURE_EDITING_VI(return_error_indicator:)
  2528. break_out = command_len = -1;
  2529. break;
  2530. }
  2531. input_delete(0);
  2532. break;
  2533. }
  2534. // /* Control-V -- force insert of next char */
  2535. // if (c == CTRL('V')) {
  2536. // if (safe_read(STDIN_FILENO, &c, 1) < 1)
  2537. // goto return_error_indicator;
  2538. // if (c == 0) {
  2539. // beep();
  2540. // break;
  2541. // }
  2542. // }
  2543. if (ic < ' '
  2544. || (!ENABLE_UNICODE_SUPPORT && ic >= 256)
  2545. || (ENABLE_UNICODE_SUPPORT && ic >= VI_CMDMODE_BIT)
  2546. ) {
  2547. /* If VI_CMDMODE_BIT is set, ic is >= 256
  2548. * and vi mode ignores unexpected chars.
  2549. * Otherwise, we are here if ic is a
  2550. * control char or an unhandled ESC sequence,
  2551. * which is also ignored.
  2552. */
  2553. break;
  2554. }
  2555. if ((int)command_len >= (maxsize - 2)) {
  2556. /* Not enough space for the char and EOL */
  2557. break;
  2558. }
  2559. command_len++;
  2560. if (cursor == (command_len - 1)) {
  2561. /* We are at the end, append */
  2562. command_ps[cursor] = ic;
  2563. command_ps[cursor + 1] = BB_NUL;
  2564. put_cur_glyph_and_inc_cursor();
  2565. if (unicode_bidi_isrtl(ic))
  2566. input_backward(1);
  2567. } else {
  2568. /* In the middle, insert */
  2569. int sc = cursor;
  2570. memmove(command_ps + sc + 1, command_ps + sc,
  2571. (command_len - sc) * sizeof(command_ps[0]));
  2572. command_ps[sc] = ic;
  2573. /* is right-to-left char, or neutral one (e.g. comma) was just added to rtl text? */
  2574. if (!isrtl_str())
  2575. sc++; /* no */
  2576. put_till_end_and_adv_cursor();
  2577. /* to prev x pos + 1 */
  2578. input_backward(cursor - sc);
  2579. }
  2580. break;
  2581. } /* switch (ic) */
  2582. if (break_out)
  2583. break;
  2584. #if ENABLE_FEATURE_TAB_COMPLETION
  2585. if (ic_raw != '\t')
  2586. lastWasTab = 0;
  2587. #endif
  2588. } /* while (1) */
  2589. #if ENABLE_FEATURE_EDITING_ASK_TERMINAL
  2590. if (S.sent_ESC_br6n) {
  2591. /* "sleep 1; busybox ash" + hold [Enter] to trigger.
  2592. * We sent "ESC [ 6 n", but got '\n' first, and
  2593. * KEYCODE_CURSOR_POS response is now buffered from terminal.
  2594. * It's bad already and not much can be done with it
  2595. * (it _will_ be visible for the next process to read stdin),
  2596. * but without this delay it even shows up on the screen
  2597. * as garbage because we restore echo settings with tcsetattr
  2598. * before it comes in. UGLY!
  2599. */
  2600. usleep(20*1000);
  2601. }
  2602. #endif
  2603. /* End of bug-catching "command_must_not_be_used" trick */
  2604. #undef command
  2605. #if ENABLE_UNICODE_SUPPORT
  2606. command[0] = '\0';
  2607. if (command_len > 0)
  2608. command_len = save_string(command, maxsize - 1);
  2609. free(command_ps);
  2610. #endif
  2611. if (command_len > 0) {
  2612. remember_in_history(command);
  2613. }
  2614. if (break_out > 0) {
  2615. command[command_len++] = '\n';
  2616. command[command_len] = '\0';
  2617. }
  2618. #if ENABLE_FEATURE_TAB_COMPLETION
  2619. free_tab_completion_data();
  2620. #endif
  2621. /* restore initial_settings */
  2622. tcsetattr_stdin_TCSANOW(&initial_settings);
  2623. #if ENABLE_FEATURE_EDITING_WINCH
  2624. /* restore SIGWINCH handler */
  2625. sigaction_set(SIGWINCH, &S.SIGWINCH_handler);
  2626. #endif
  2627. fflush_all();
  2628. len = command_len;
  2629. DEINIT_S();
  2630. return len; /* can't return command_len, DEINIT_S() destroys it */
  2631. }
  2632. #else /* !FEATURE_EDITING */
  2633. #undef read_line_input
  2634. int FAST_FUNC read_line_input(const char* prompt, char* command, int maxsize)
  2635. {
  2636. fputs(prompt, stdout);
  2637. fflush_all();
  2638. if (!fgets(command, maxsize, stdin))
  2639. return -1;
  2640. return strlen(command);
  2641. }
  2642. #endif /* !FEATURE_EDITING */
  2643. /*
  2644. * Testing
  2645. */
  2646. #ifdef TEST
  2647. #include <locale.h>
  2648. const char *applet_name = "debug stuff usage";
  2649. int main(int argc, char **argv)
  2650. {
  2651. char buff[MAX_LINELEN];
  2652. char *prompt =
  2653. #if ENABLE_FEATURE_EDITING_FANCY_PROMPT
  2654. "\\[\\033[32;1m\\]\\u@\\[\\x1b[33;1m\\]\\h:"
  2655. "\\[\\033[34;1m\\]\\w\\[\\033[35;1m\\] "
  2656. "\\!\\[\\e[36;1m\\]\\$ \\[\\E[m\\]";
  2657. #else
  2658. "% ";
  2659. #endif
  2660. while (1) {
  2661. int l;
  2662. l = read_line_input(prompt, buff);
  2663. if (l <= 0 || buff[l-1] != '\n')
  2664. break;
  2665. buff[l-1] = '\0';
  2666. printf("*** read_line_input() returned line =%s=\n", buff);
  2667. }
  2668. printf("*** read_line_input() detect ^D\n");
  2669. return 0;
  2670. }
  2671. #endif /* TEST */