lineedit.c 70 KB

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