3
0

lineedit.c 55 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495969798991001011021031041051061071081091101111121131141151161171181191201211221231241251261271281291301311321331341351361371381391401411421431441451461471481491501511521531541551561571581591601611621631641651661671681691701711721731741751761771781791801811821831841851861871881891901911921931941951961971981992002012022032042052062072082092102112122132142152162172182192202212222232242252262272282292302312322332342352362372382392402412422432442452462472482492502512522532542552562572582592602612622632642652662672682692702712722732742752762772782792802812822832842852862872882892902912922932942952962972982993003013023033043053063073083093103113123133143153163173183193203213223233243253263273283293303313323333343353363373383393403413423433443453463473483493503513523533543553563573583593603613623633643653663673683693703713723733743753763773783793803813823833843853863873883893903913923933943953963973983994004014024034044054064074084094104114124134144154164174184194204214224234244254264274284294304314324334344354364374384394404414424434444454464474484494504514524534544554564574584594604614624634644654664674684694704714724734744754764774784794804814824834844854864874884894904914924934944954964974984995005015025035045055065075085095105115125135145155165175185195205215225235245255265275285295305315325335345355365375385395405415425435445455465475485495505515525535545555565575585595605615625635645655665675685695705715725735745755765775785795805815825835845855865875885895905915925935945955965975985996006016026036046056066076086096106116126136146156166176186196206216226236246256266276286296306316326336346356366376386396406416426436446456466476486496506516526536546556566576586596606616626636646656666676686696706716726736746756766776786796806816826836846856866876886896906916926936946956966976986997007017027037047057067077087097107117127137147157167177187197207217227237247257267277287297307317327337347357367377387397407417427437447457467477487497507517527537547557567577587597607617627637647657667677687697707717727737747757767777787797807817827837847857867877887897907917927937947957967977987998008018028038048058068078088098108118128138148158168178188198208218228238248258268278288298308318328338348358368378388398408418428438448458468478488498508518528538548558568578588598608618628638648658668678688698708718728738748758768778788798808818828838848858868878888898908918928938948958968978988999009019029039049059069079089099109119129139149159169179189199209219229239249259269279289299309319329339349359369379389399409419429439449459469479489499509519529539549559569579589599609619629639649659669679689699709719729739749759769779789799809819829839849859869879889899909919929939949959969979989991000100110021003100410051006100710081009101010111012101310141015101610171018101910201021102210231024102510261027102810291030103110321033103410351036103710381039104010411042104310441045104610471048104910501051105210531054105510561057105810591060106110621063106410651066106710681069107010711072107310741075107610771078107910801081108210831084108510861087108810891090109110921093109410951096109710981099110011011102110311041105110611071108110911101111111211131114111511161117111811191120112111221123112411251126112711281129113011311132113311341135113611371138113911401141114211431144114511461147114811491150115111521153115411551156115711581159116011611162116311641165116611671168116911701171117211731174117511761177117811791180118111821183118411851186118711881189119011911192119311941195119611971198119912001201120212031204120512061207120812091210121112121213121412151216121712181219122012211222122312241225122612271228122912301231123212331234123512361237123812391240124112421243124412451246124712481249125012511252125312541255125612571258125912601261126212631264126512661267126812691270127112721273127412751276127712781279128012811282128312841285128612871288128912901291129212931294129512961297129812991300130113021303130413051306130713081309131013111312131313141315131613171318131913201321132213231324132513261327132813291330133113321333133413351336133713381339134013411342134313441345134613471348134913501351135213531354135513561357135813591360136113621363136413651366136713681369137013711372137313741375137613771378137913801381138213831384138513861387138813891390139113921393139413951396139713981399140014011402140314041405140614071408140914101411141214131414141514161417141814191420142114221423142414251426142714281429143014311432143314341435143614371438143914401441144214431444144514461447144814491450145114521453145414551456145714581459146014611462146314641465146614671468146914701471147214731474147514761477147814791480148114821483148414851486148714881489149014911492149314941495149614971498149915001501150215031504150515061507150815091510151115121513151415151516151715181519152015211522152315241525152615271528152915301531153215331534153515361537153815391540154115421543154415451546154715481549155015511552155315541555155615571558155915601561156215631564156515661567156815691570157115721573157415751576157715781579158015811582158315841585158615871588158915901591159215931594159515961597159815991600160116021603160416051606160716081609161016111612161316141615161616171618161916201621162216231624162516261627162816291630163116321633163416351636163716381639164016411642164316441645164616471648164916501651165216531654165516561657165816591660166116621663166416651666166716681669167016711672167316741675167616771678167916801681168216831684168516861687168816891690169116921693169416951696169716981699170017011702170317041705170617071708170917101711171217131714171517161717171817191720172117221723172417251726172717281729173017311732173317341735173617371738173917401741174217431744174517461747174817491750175117521753175417551756175717581759176017611762176317641765176617671768176917701771177217731774177517761777177817791780178117821783178417851786178717881789179017911792179317941795179617971798179918001801180218031804180518061807180818091810181118121813181418151816181718181819182018211822182318241825182618271828182918301831183218331834183518361837183818391840184118421843184418451846184718481849185018511852185318541855185618571858185918601861186218631864186518661867186818691870187118721873187418751876187718781879188018811882188318841885188618871888188918901891189218931894189518961897189818991900190119021903190419051906190719081909191019111912191319141915191619171918191919201921192219231924192519261927192819291930193119321933193419351936193719381939194019411942194319441945194619471948194919501951195219531954195519561957195819591960196119621963196419651966196719681969197019711972197319741975197619771978197919801981198219831984198519861987198819891990199119921993199419951996199719981999200020012002200320042005200620072008200920102011201220132014201520162017201820192020202120222023202420252026202720282029203020312032203320342035203620372038203920402041204220432044204520462047204820492050205120522053205420552056205720582059206020612062206320642065206620672068206920702071207220732074207520762077207820792080208120822083208420852086208720882089209020912092209320942095209620972098209921002101210221032104210521062107210821092110211121122113211421152116211721182119212021212122212321242125212621272128212921302131213221332134213521362137213821392140214121422143214421452146214721482149215021512152215321542155215621572158215921602161216221632164216521662167216821692170217121722173217421752176217721782179218021812182218321842185218621872188218921902191219221932194219521962197219821992200220122022203220422052206220722082209221022112212221322142215221622172218221922202221222222232224222522262227222822292230223122322233223422352236223722382239224022412242224322442245224622472248224922502251225222532254225522562257225822592260226122622263226422652266226722682269227022712272227322742275227622772278227922802281228222832284228522862287228822892290229122922293229422952296229722982299230023012302230323042305230623072308230923102311231223132314
  1. /* vi: set sw=4 ts=4: */
  2. /*
  3. * Termios command line History and 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. #include "libbb.h"
  42. #include "unicode.h"
  43. /* FIXME: obsolete CONFIG item? */
  44. #define ENABLE_FEATURE_NONPRINTABLE_INVERSE_PUT 0
  45. #ifdef TEST
  46. # define ENABLE_FEATURE_EDITING 0
  47. # define ENABLE_FEATURE_TAB_COMPLETION 0
  48. # define ENABLE_FEATURE_USERNAME_COMPLETION 0
  49. # define ENABLE_FEATURE_NONPRINTABLE_INVERSE_PUT 0
  50. #endif
  51. /* Entire file (except TESTing part) sits inside this #if */
  52. #if ENABLE_FEATURE_EDITING
  53. #define ENABLE_FEATURE_GETUSERNAME_AND_HOMEDIR \
  54. (ENABLE_FEATURE_USERNAME_COMPLETION || ENABLE_FEATURE_EDITING_FANCY_PROMPT)
  55. #define IF_FEATURE_GETUSERNAME_AND_HOMEDIR(...)
  56. #if ENABLE_FEATURE_GETUSERNAME_AND_HOMEDIR
  57. #undef IF_FEATURE_GETUSERNAME_AND_HOMEDIR
  58. #define IF_FEATURE_GETUSERNAME_AND_HOMEDIR(...) __VA_ARGS__
  59. #endif
  60. #undef CHAR_T
  61. #if ENABLE_FEATURE_ASSUME_UNICODE
  62. # define BB_NUL L'\0'
  63. # define CHAR_T wchar_t
  64. static bool BB_isspace(CHAR_T c) { return ((unsigned)c < 256 && isspace(c)); }
  65. # if ENABLE_FEATURE_EDITING_VI
  66. static bool BB_isalnum(CHAR_T c) { return ((unsigned)c < 256 && isalnum(c)); }
  67. # endif
  68. static bool BB_ispunct(CHAR_T c) { return ((unsigned)c < 256 && ispunct(c)); }
  69. # undef isspace
  70. # undef isalnum
  71. # undef ispunct
  72. # undef isprint
  73. # define isspace isspace_must_not_be_used
  74. # define isalnum isalnum_must_not_be_used
  75. # define ispunct ispunct_must_not_be_used
  76. # define isprint isprint_must_not_be_used
  77. #else
  78. # define BB_NUL '\0'
  79. # define CHAR_T char
  80. # define BB_isspace(c) isspace(c)
  81. # define BB_isalnum(c) isalnum(c)
  82. # define BB_ispunct(c) ispunct(c)
  83. #endif
  84. enum {
  85. /* We use int16_t for positions, need to limit line len */
  86. MAX_LINELEN = CONFIG_FEATURE_EDITING_MAX_LEN < 0x7ff0
  87. ? CONFIG_FEATURE_EDITING_MAX_LEN
  88. : 0x7ff0
  89. };
  90. #if ENABLE_FEATURE_GETUSERNAME_AND_HOMEDIR
  91. static const char null_str[] ALIGN1 = "";
  92. #endif
  93. /* We try to minimize both static and stack usage. */
  94. struct lineedit_statics {
  95. line_input_t *state;
  96. volatile unsigned cmdedit_termw; /* = 80; */ /* actual terminal width */
  97. sighandler_t previous_SIGWINCH_handler;
  98. unsigned cmdedit_x; /* real x (col) terminal position */
  99. unsigned cmdedit_y; /* pseudoreal y (row) terminal position */
  100. unsigned cmdedit_prmt_len; /* length of prompt (without colors etc) */
  101. unsigned cursor;
  102. int command_len; /* must be signed */
  103. /* signed maxsize: we want x in "if (x > S.maxsize)"
  104. * to _not_ be promoted to unsigned */
  105. int maxsize;
  106. CHAR_T *command_ps;
  107. const char *cmdedit_prompt;
  108. #if ENABLE_FEATURE_EDITING_FANCY_PROMPT
  109. int num_ok_lines; /* = 1; */
  110. #endif
  111. #if ENABLE_FEATURE_GETUSERNAME_AND_HOMEDIR
  112. char *user_buf;
  113. char *home_pwd_buf; /* = (char*)null_str; */
  114. #endif
  115. #if ENABLE_FEATURE_TAB_COMPLETION
  116. char **matches;
  117. unsigned num_matches;
  118. #endif
  119. #if ENABLE_FEATURE_EDITING_VI
  120. #define DELBUFSIZ 128
  121. CHAR_T *delptr;
  122. smallint newdelflag; /* whether delbuf should be reused yet */
  123. CHAR_T delbuf[DELBUFSIZ]; /* a place to store deleted characters */
  124. #endif
  125. #if ENABLE_FEATURE_EDITING_ASK_TERMINAL
  126. smallint sent_ESC_br6n;
  127. #endif
  128. /* Formerly these were big buffers on stack: */
  129. #if ENABLE_FEATURE_TAB_COMPLETION
  130. char exe_n_cwd_tab_completion__dirbuf[MAX_LINELEN];
  131. char input_tab__matchBuf[MAX_LINELEN];
  132. int16_t find_match__int_buf[MAX_LINELEN + 1]; /* need to have 9 bits at least */
  133. int16_t find_match__pos_buf[MAX_LINELEN + 1];
  134. #endif
  135. };
  136. /* See lineedit_ptr_hack.c */
  137. extern struct lineedit_statics *const lineedit_ptr_to_statics;
  138. #define S (*lineedit_ptr_to_statics)
  139. #define state (S.state )
  140. #define cmdedit_termw (S.cmdedit_termw )
  141. #define previous_SIGWINCH_handler (S.previous_SIGWINCH_handler)
  142. #define cmdedit_x (S.cmdedit_x )
  143. #define cmdedit_y (S.cmdedit_y )
  144. #define cmdedit_prmt_len (S.cmdedit_prmt_len)
  145. #define cursor (S.cursor )
  146. #define command_len (S.command_len )
  147. #define command_ps (S.command_ps )
  148. #define cmdedit_prompt (S.cmdedit_prompt )
  149. #define num_ok_lines (S.num_ok_lines )
  150. #define user_buf (S.user_buf )
  151. #define home_pwd_buf (S.home_pwd_buf )
  152. #define matches (S.matches )
  153. #define num_matches (S.num_matches )
  154. #define delptr (S.delptr )
  155. #define newdelflag (S.newdelflag )
  156. #define delbuf (S.delbuf )
  157. #define INIT_S() do { \
  158. (*(struct lineedit_statics**)&lineedit_ptr_to_statics) = xzalloc(sizeof(S)); \
  159. barrier(); \
  160. cmdedit_termw = 80; \
  161. IF_FEATURE_EDITING_FANCY_PROMPT(num_ok_lines = 1;) \
  162. IF_FEATURE_GETUSERNAME_AND_HOMEDIR(home_pwd_buf = (char*)null_str;) \
  163. } while (0)
  164. static void deinit_S(void)
  165. {
  166. #if ENABLE_FEATURE_EDITING_FANCY_PROMPT
  167. /* This one is allocated only if FANCY_PROMPT is on
  168. * (otherwise it points to verbatim prompt (NOT malloced) */
  169. free((char*)cmdedit_prompt);
  170. #endif
  171. #if ENABLE_FEATURE_GETUSERNAME_AND_HOMEDIR
  172. free(user_buf);
  173. if (home_pwd_buf != null_str)
  174. free(home_pwd_buf);
  175. #endif
  176. free(lineedit_ptr_to_statics);
  177. }
  178. #define DEINIT_S() deinit_S()
  179. #if ENABLE_FEATURE_ASSUME_UNICODE
  180. static size_t load_string(const char *src, int maxsize)
  181. {
  182. ssize_t len = mbstowcs(command_ps, src, maxsize - 1);
  183. if (len < 0)
  184. len = 0;
  185. command_ps[len] = L'\0';
  186. return len;
  187. }
  188. static size_t save_string(char *dst, int maxsize)
  189. {
  190. ssize_t len = wcstombs(dst, command_ps, maxsize - 1);
  191. if (len < 0)
  192. len = 0;
  193. dst[len] = '\0';
  194. return len;
  195. }
  196. /* I thought just fputwc(c, stdout) would work. But no... */
  197. static void BB_PUTCHAR(wchar_t c)
  198. {
  199. char buf[MB_CUR_MAX + 1];
  200. mbstate_t mbst = { 0 };
  201. ssize_t len = wcrtomb(buf, c, &mbst);
  202. if (len > 0) {
  203. buf[len] = '\0';
  204. fputs(buf, stdout);
  205. }
  206. }
  207. #else
  208. static size_t load_string(const char *src, int maxsize)
  209. {
  210. safe_strncpy(command_ps, src, maxsize);
  211. return strlen(command_ps);
  212. }
  213. # if ENABLE_FEATURE_TAB_COMPLETION
  214. static void save_string(char *dst, int maxsize)
  215. {
  216. safe_strncpy(dst, command_ps, maxsize);
  217. }
  218. # endif
  219. # define BB_PUTCHAR(c) bb_putchar(c)
  220. #endif
  221. /* Put 'command_ps[cursor]', cursor++.
  222. * Advance cursor on screen. If we reached right margin, scroll text up
  223. * and remove terminal margin effect by printing 'next_char' */
  224. #define HACK_FOR_WRONG_WIDTH 1
  225. #if HACK_FOR_WRONG_WIDTH
  226. static void cmdedit_set_out_char(void)
  227. #define cmdedit_set_out_char(next_char) cmdedit_set_out_char()
  228. #else
  229. static void cmdedit_set_out_char(int next_char)
  230. #endif
  231. {
  232. CHAR_T c = command_ps[cursor];
  233. if (c == BB_NUL) {
  234. /* erase character after end of input string */
  235. c = ' ';
  236. }
  237. #if ENABLE_FEATURE_NONPRINTABLE_INVERSE_PUT
  238. /* Display non-printable characters in reverse */
  239. if (!BB_isprint(c)) {
  240. if (c >= 128)
  241. c -= 128;
  242. if (c < ' ')
  243. c += '@';
  244. if (c == 127)
  245. c = '?';
  246. printf("\033[7m%c\033[0m", c);
  247. } else
  248. #endif
  249. {
  250. BB_PUTCHAR(c);
  251. }
  252. if (++cmdedit_x >= cmdedit_termw) {
  253. /* terminal is scrolled down */
  254. cmdedit_y++;
  255. cmdedit_x = 0;
  256. #if HACK_FOR_WRONG_WIDTH
  257. /* This works better if our idea of term width is wrong
  258. * and it is actually wider (often happens on serial lines).
  259. * Printing CR,LF *forces* cursor to next line.
  260. * OTOH if terminal width is correct AND terminal does NOT
  261. * have automargin (IOW: it is moving cursor to next line
  262. * by itself (which is wrong for VT-10x terminals)),
  263. * this will break things: there will be one extra empty line */
  264. puts("\r"); /* + implicit '\n' */
  265. #else
  266. /* Works ok only if cmdedit_termw is correct */
  267. /* destroy "(auto)margin" */
  268. bb_putchar(next_char);
  269. bb_putchar('\b');
  270. #endif
  271. }
  272. // Huh? What if command_ps[cursor] == BB_NUL (we are at the end already?)
  273. cursor++;
  274. }
  275. /* Move to end of line (by printing all chars till the end) */
  276. static void input_end(void)
  277. {
  278. while (cursor < command_len)
  279. cmdedit_set_out_char(' ');
  280. }
  281. /* Go to the next line */
  282. static void goto_new_line(void)
  283. {
  284. input_end();
  285. if (cmdedit_x)
  286. bb_putchar('\n');
  287. }
  288. static void out1str(const char *s)
  289. {
  290. if (s)
  291. fputs(s, stdout);
  292. }
  293. static void beep(void)
  294. {
  295. bb_putchar('\007');
  296. }
  297. /* Move back one character */
  298. /* (optimized for slow terminals) */
  299. static void input_backward(unsigned num)
  300. {
  301. int count_y;
  302. if (num > cursor)
  303. num = cursor;
  304. if (!num)
  305. return;
  306. cursor -= num;
  307. if (cmdedit_x >= num) {
  308. cmdedit_x -= num;
  309. if (num <= 4) {
  310. /* This is longer by 5 bytes on x86.
  311. * Also gets miscompiled for ARM users
  312. * (busybox.net/bugs/view.php?id=2274).
  313. * printf(("\b\b\b\b" + 4) - num);
  314. * return;
  315. */
  316. do {
  317. bb_putchar('\b');
  318. } while (--num);
  319. return;
  320. }
  321. printf("\033[%uD", num);
  322. return;
  323. }
  324. /* Need to go one or more lines up */
  325. num -= cmdedit_x;
  326. {
  327. unsigned w = cmdedit_termw; /* volatile var */
  328. count_y = 1 + (num / w);
  329. cmdedit_y -= count_y;
  330. cmdedit_x = w * count_y - num;
  331. }
  332. /* go to 1st column; go up; go to correct column */
  333. printf("\r" "\033[%dA" "\033[%dC", count_y, cmdedit_x);
  334. }
  335. static void put_prompt(void)
  336. {
  337. unsigned w;
  338. out1str(cmdedit_prompt);
  339. fflush_all();
  340. cursor = 0;
  341. w = cmdedit_termw; /* read volatile var once */
  342. cmdedit_y = cmdedit_prmt_len / w; /* new quasireal y */
  343. cmdedit_x = cmdedit_prmt_len % w;
  344. }
  345. /* draw prompt, editor line, and clear tail */
  346. static void redraw(int y, int back_cursor)
  347. {
  348. if (y > 0) /* up to start y */
  349. printf("\033[%uA", y);
  350. bb_putchar('\r');
  351. put_prompt();
  352. input_end(); /* rewrite */
  353. printf("\033[J"); /* erase after cursor */
  354. input_backward(back_cursor);
  355. }
  356. /* Delete the char in front of the cursor, optionally saving it
  357. * for later putback */
  358. #if !ENABLE_FEATURE_EDITING_VI
  359. static void input_delete(void)
  360. #define input_delete(save) input_delete()
  361. #else
  362. static void input_delete(int save)
  363. #endif
  364. {
  365. int j = cursor;
  366. if (j == (int)command_len)
  367. return;
  368. #if ENABLE_FEATURE_EDITING_VI
  369. if (save) {
  370. if (newdelflag) {
  371. delptr = delbuf;
  372. newdelflag = 0;
  373. }
  374. if ((delptr - delbuf) < DELBUFSIZ)
  375. *delptr++ = command_ps[j];
  376. }
  377. #endif
  378. memmove(command_ps + j, command_ps + j + 1,
  379. /* (command_len + 1 [because of NUL]) - (j + 1)
  380. * simplified into (command_len - j) */
  381. (command_len - j) * sizeof(command_ps[0]));
  382. command_len--;
  383. input_end(); /* rewrite new line */
  384. cmdedit_set_out_char(' '); /* erase char */
  385. input_backward(cursor - j); /* back to old pos cursor */
  386. }
  387. #if ENABLE_FEATURE_EDITING_VI
  388. static void put(void)
  389. {
  390. int ocursor;
  391. int j = delptr - delbuf;
  392. if (j == 0)
  393. return;
  394. ocursor = cursor;
  395. /* open hole and then fill it */
  396. memmove(command_ps + cursor + j, command_ps + cursor,
  397. (command_len - cursor + 1) * sizeof(command_ps[0]));
  398. memcpy(command_ps + cursor, delbuf, j * sizeof(command_ps[0]));
  399. command_len += j;
  400. input_end(); /* rewrite new line */
  401. input_backward(cursor - ocursor - j + 1); /* at end of new text */
  402. }
  403. #endif
  404. /* Delete the char in back of the cursor */
  405. static void input_backspace(void)
  406. {
  407. if (cursor > 0) {
  408. input_backward(1);
  409. input_delete(0);
  410. }
  411. }
  412. /* Move forward one character */
  413. static void input_forward(void)
  414. {
  415. if (cursor < command_len)
  416. cmdedit_set_out_char(command_ps[cursor + 1]);
  417. }
  418. #if ENABLE_FEATURE_TAB_COMPLETION
  419. static void free_tab_completion_data(void)
  420. {
  421. if (matches) {
  422. while (num_matches)
  423. free(matches[--num_matches]);
  424. free(matches);
  425. matches = NULL;
  426. }
  427. }
  428. static void add_match(char *matched)
  429. {
  430. matches = xrealloc_vector(matches, 4, num_matches);
  431. matches[num_matches] = matched;
  432. num_matches++;
  433. }
  434. #if ENABLE_FEATURE_USERNAME_COMPLETION
  435. static void username_tab_completion(char *ud, char *with_shash_flg)
  436. {
  437. struct passwd *entry;
  438. int userlen;
  439. ud++; /* ~user/... to user/... */
  440. userlen = strlen(ud);
  441. if (with_shash_flg) { /* "~/..." or "~user/..." */
  442. char *sav_ud = ud - 1;
  443. char *home = NULL;
  444. if (*ud == '/') { /* "~/..." */
  445. home = home_pwd_buf;
  446. } else {
  447. /* "~user/..." */
  448. char *temp;
  449. temp = strchr(ud, '/');
  450. *temp = '\0'; /* ~user\0 */
  451. entry = getpwnam(ud);
  452. *temp = '/'; /* restore ~user/... */
  453. ud = temp;
  454. if (entry)
  455. home = entry->pw_dir;
  456. }
  457. if (home) {
  458. if ((userlen + strlen(home) + 1) < MAX_LINELEN) {
  459. /* /home/user/... */
  460. sprintf(sav_ud, "%s%s", home, ud);
  461. }
  462. }
  463. } else {
  464. /* "~[^/]*" */
  465. /* Using _r function to avoid pulling in static buffers */
  466. char line_buff[256];
  467. struct passwd pwd;
  468. struct passwd *result;
  469. setpwent();
  470. while (!getpwent_r(&pwd, line_buff, sizeof(line_buff), &result)) {
  471. /* Null usernames should result in all users as possible completions. */
  472. if (/*!userlen || */ strncmp(ud, pwd.pw_name, userlen) == 0) {
  473. add_match(xasprintf("~%s/", pwd.pw_name));
  474. }
  475. }
  476. endpwent();
  477. }
  478. }
  479. #endif /* FEATURE_COMMAND_USERNAME_COMPLETION */
  480. enum {
  481. FIND_EXE_ONLY = 0,
  482. FIND_DIR_ONLY = 1,
  483. FIND_FILE_ONLY = 2,
  484. };
  485. static int path_parse(char ***p, int flags)
  486. {
  487. int npth;
  488. const char *pth;
  489. char *tmp;
  490. char **res;
  491. /* if not setenv PATH variable, to search cur dir "." */
  492. if (flags != FIND_EXE_ONLY)
  493. return 1;
  494. if (state->flags & WITH_PATH_LOOKUP)
  495. pth = state->path_lookup;
  496. else
  497. pth = getenv("PATH");
  498. /* PATH=<empty> or PATH=:<empty> */
  499. if (!pth || !pth[0] || LONE_CHAR(pth, ':'))
  500. return 1;
  501. tmp = (char*)pth;
  502. npth = 1; /* path component count */
  503. while (1) {
  504. tmp = strchr(tmp, ':');
  505. if (!tmp)
  506. break;
  507. if (*++tmp == '\0')
  508. break; /* :<empty> */
  509. npth++;
  510. }
  511. res = xmalloc(npth * sizeof(char*));
  512. res[0] = tmp = xstrdup(pth);
  513. npth = 1;
  514. while (1) {
  515. tmp = strchr(tmp, ':');
  516. if (!tmp)
  517. break;
  518. *tmp++ = '\0'; /* ':' -> '\0' */
  519. if (*tmp == '\0')
  520. break; /* :<empty> */
  521. res[npth++] = tmp;
  522. }
  523. *p = res;
  524. return npth;
  525. }
  526. static void exe_n_cwd_tab_completion(char *command, int type)
  527. {
  528. DIR *dir;
  529. struct dirent *next;
  530. struct stat st;
  531. char *path1[1];
  532. char **paths = path1;
  533. int npaths;
  534. int i;
  535. char *found;
  536. char *pfind = strrchr(command, '/');
  537. /* char dirbuf[MAX_LINELEN]; */
  538. #define dirbuf (S.exe_n_cwd_tab_completion__dirbuf)
  539. npaths = 1;
  540. path1[0] = (char*)".";
  541. if (pfind == NULL) {
  542. /* no dir, if flags==EXE_ONLY - get paths, else "." */
  543. npaths = path_parse(&paths, type);
  544. pfind = command;
  545. } else {
  546. /* dirbuf = ".../.../.../" */
  547. safe_strncpy(dirbuf, command, (pfind - command) + 2);
  548. #if ENABLE_FEATURE_USERNAME_COMPLETION
  549. if (dirbuf[0] == '~') /* ~/... or ~user/... */
  550. username_tab_completion(dirbuf, dirbuf);
  551. #endif
  552. paths[0] = dirbuf;
  553. /* point to 'l' in "..../last_component" */
  554. pfind++;
  555. }
  556. for (i = 0; i < npaths; i++) {
  557. dir = opendir(paths[i]);
  558. if (!dir)
  559. continue; /* don't print an error */
  560. while ((next = readdir(dir)) != NULL) {
  561. int len1;
  562. const char *str_found = next->d_name;
  563. /* matched? */
  564. if (strncmp(str_found, pfind, strlen(pfind)))
  565. continue;
  566. /* not see .name without .match */
  567. if (*str_found == '.' && *pfind == '\0') {
  568. if (NOT_LONE_CHAR(paths[i], '/') || str_found[1])
  569. continue;
  570. str_found = ""; /* only "/" */
  571. }
  572. found = concat_path_file(paths[i], str_found);
  573. /* hmm, remove in progress? */
  574. /* NB: stat() first so that we see is it a directory;
  575. * but if that fails, use lstat() so that
  576. * we still match dangling links */
  577. if (stat(found, &st) && lstat(found, &st))
  578. goto cont;
  579. /* find with dirs? */
  580. if (paths[i] != dirbuf)
  581. strcpy(found, next->d_name); /* only name */
  582. len1 = strlen(found);
  583. found = xrealloc(found, len1 + 2);
  584. found[len1] = '\0';
  585. found[len1+1] = '\0';
  586. if (S_ISDIR(st.st_mode)) {
  587. /* name is a directory */
  588. if (found[len1-1] != '/') {
  589. found[len1] = '/';
  590. }
  591. } else {
  592. /* not put found file if search only dirs for cd */
  593. if (type == FIND_DIR_ONLY)
  594. goto cont;
  595. }
  596. /* Add it to the list */
  597. add_match(found);
  598. continue;
  599. cont:
  600. free(found);
  601. }
  602. closedir(dir);
  603. }
  604. if (paths != path1) {
  605. free(paths[0]); /* allocated memory is only in first member */
  606. free(paths);
  607. }
  608. #undef dirbuf
  609. }
  610. /* QUOT is used on elements of int_buf[], which are bytes,
  611. * not Unicode chars. Therefore it works correctly even in Unicode mode.
  612. */
  613. #define QUOT (UCHAR_MAX+1)
  614. #define int_buf (S.find_match__int_buf)
  615. #define pos_buf (S.find_match__pos_buf)
  616. /* is must be <= in */
  617. static void collapse_pos(int is, int in)
  618. {
  619. memmove(int_buf+is, int_buf+in, (MAX_LINELEN+1-in)*sizeof(int_buf[0]));
  620. memmove(pos_buf+is, pos_buf+in, (MAX_LINELEN+1-in)*sizeof(pos_buf[0]));
  621. }
  622. static NOINLINE int find_match(char *matchBuf, int *len_with_quotes)
  623. {
  624. int i, j;
  625. int command_mode;
  626. int c, c2;
  627. /* Were local, but it uses too much stack */
  628. /* int16_t int_buf[MAX_LINELEN + 1]; */
  629. /* int16_t pos_buf[MAX_LINELEN + 1]; */
  630. /* set to integer dimension characters and own positions */
  631. for (i = 0;; i++) {
  632. int_buf[i] = (unsigned char)matchBuf[i];
  633. if (int_buf[i] == 0) {
  634. pos_buf[i] = -1; /* end-fo-line indicator */
  635. break;
  636. }
  637. pos_buf[i] = i;
  638. }
  639. /* mask \+symbol and convert '\t' to ' ' */
  640. for (i = j = 0; matchBuf[i]; i++, j++)
  641. if (matchBuf[i] == '\\') {
  642. collapse_pos(j, j + 1);
  643. int_buf[j] |= QUOT;
  644. i++;
  645. #if ENABLE_FEATURE_NONPRINTABLE_INVERSE_PUT
  646. if (matchBuf[i] == '\t') /* algorithm equivalent */
  647. int_buf[j] = ' ' | QUOT;
  648. #endif
  649. }
  650. #if ENABLE_FEATURE_NONPRINTABLE_INVERSE_PUT
  651. else if (matchBuf[i] == '\t')
  652. int_buf[j] = ' ';
  653. #endif
  654. /* mask "symbols" or 'symbols' */
  655. c2 = 0;
  656. for (i = 0; int_buf[i]; i++) {
  657. c = int_buf[i];
  658. if (c == '\'' || c == '"') {
  659. if (c2 == 0)
  660. c2 = c;
  661. else {
  662. if (c == c2)
  663. c2 = 0;
  664. else
  665. int_buf[i] |= QUOT;
  666. }
  667. } else if (c2 != 0 && c != '$')
  668. int_buf[i] |= QUOT;
  669. }
  670. /* skip commands with arguments if line has commands delimiters */
  671. /* ';' ';;' '&' '|' '&&' '||' but `>&' `<&' `>|' */
  672. for (i = 0; int_buf[i]; i++) {
  673. c = int_buf[i];
  674. c2 = int_buf[i + 1];
  675. j = i ? int_buf[i - 1] : -1;
  676. command_mode = 0;
  677. if (c == ';' || c == '&' || c == '|') {
  678. command_mode = 1 + (c == c2);
  679. if (c == '&') {
  680. if (j == '>' || j == '<')
  681. command_mode = 0;
  682. } else if (c == '|' && j == '>')
  683. command_mode = 0;
  684. }
  685. if (command_mode) {
  686. collapse_pos(0, i + command_mode);
  687. i = -1; /* hack incremet */
  688. }
  689. }
  690. /* collapse `command...` */
  691. for (i = 0; int_buf[i]; i++) {
  692. if (int_buf[i] == '`') {
  693. for (j = i + 1; int_buf[j]; j++)
  694. if (int_buf[j] == '`') {
  695. collapse_pos(i, j + 1);
  696. j = 0;
  697. break;
  698. }
  699. if (j) {
  700. /* not found closing ` - command mode, collapse all previous */
  701. collapse_pos(0, i + 1);
  702. break;
  703. } else
  704. i--; /* hack incremet */
  705. }
  706. }
  707. /* collapse (command...(command...)...) or {command...{command...}...} */
  708. c = 0; /* "recursive" level */
  709. c2 = 0;
  710. for (i = 0; int_buf[i]; i++) {
  711. if (int_buf[i] == '(' || int_buf[i] == '{') {
  712. if (int_buf[i] == '(')
  713. c++;
  714. else
  715. c2++;
  716. collapse_pos(0, i + 1);
  717. i = -1; /* hack incremet */
  718. }
  719. }
  720. for (i = 0; pos_buf[i] >= 0 && (c > 0 || c2 > 0); i++) {
  721. if ((int_buf[i] == ')' && c > 0) || (int_buf[i] == '}' && c2 > 0)) {
  722. if (int_buf[i] == ')')
  723. c--;
  724. else
  725. c2--;
  726. collapse_pos(0, i + 1);
  727. i = -1; /* hack incremet */
  728. }
  729. }
  730. /* skip first not quote space */
  731. for (i = 0; int_buf[i]; i++)
  732. if (int_buf[i] != ' ')
  733. break;
  734. if (i)
  735. collapse_pos(0, i);
  736. /* set find mode for completion */
  737. command_mode = FIND_EXE_ONLY;
  738. for (i = 0; int_buf[i]; i++) {
  739. if (int_buf[i] == ' ' || int_buf[i] == '<' || int_buf[i] == '>') {
  740. if (int_buf[i] == ' ' && command_mode == FIND_EXE_ONLY
  741. && matchBuf[pos_buf[0]] == 'c'
  742. && matchBuf[pos_buf[1]] == 'd'
  743. ) {
  744. command_mode = FIND_DIR_ONLY;
  745. } else {
  746. command_mode = FIND_FILE_ONLY;
  747. break;
  748. }
  749. }
  750. }
  751. for (i = 0; int_buf[i]; i++)
  752. /* "strlen" */;
  753. /* find last word */
  754. for (--i; i >= 0; i--) {
  755. c = int_buf[i];
  756. if (c == ' ' || c == '<' || c == '>' || c == '|' || c == '&') {
  757. collapse_pos(0, i + 1);
  758. break;
  759. }
  760. }
  761. /* skip first not quoted '\'' or '"' */
  762. for (i = 0; int_buf[i] == '\'' || int_buf[i] == '"'; i++)
  763. /*skip*/;
  764. /* collapse quote or unquote // or /~ */
  765. while ((int_buf[i] & ~QUOT) == '/'
  766. && ((int_buf[i+1] & ~QUOT) == '/' || (int_buf[i+1] & ~QUOT) == '~')
  767. ) {
  768. i++;
  769. }
  770. /* set only match and destroy quotes */
  771. j = 0;
  772. for (c = 0; pos_buf[i] >= 0; i++) {
  773. matchBuf[c++] = matchBuf[pos_buf[i]];
  774. j = pos_buf[i] + 1;
  775. }
  776. matchBuf[c] = '\0';
  777. /* old length matchBuf with quotes symbols */
  778. *len_with_quotes = j ? j - pos_buf[0] : 0;
  779. return command_mode;
  780. }
  781. #undef int_buf
  782. #undef pos_buf
  783. /*
  784. * display by column (original idea from ls applet,
  785. * very optimized by me :)
  786. */
  787. static void showfiles(void)
  788. {
  789. int ncols, row;
  790. int column_width = 0;
  791. int nfiles = num_matches;
  792. int nrows = nfiles;
  793. int l;
  794. /* find the longest file name - use that as the column width */
  795. for (row = 0; row < nrows; row++) {
  796. l = unicode_strlen(matches[row]);
  797. if (column_width < l)
  798. column_width = l;
  799. }
  800. column_width += 2; /* min space for columns */
  801. ncols = cmdedit_termw / column_width;
  802. if (ncols > 1) {
  803. nrows /= ncols;
  804. if (nfiles % ncols)
  805. nrows++; /* round up fractionals */
  806. } else {
  807. ncols = 1;
  808. }
  809. for (row = 0; row < nrows; row++) {
  810. int n = row;
  811. int nc;
  812. for (nc = 1; nc < ncols && n+nrows < nfiles; n += nrows, nc++) {
  813. printf("%s%-*s", matches[n],
  814. (int)(column_width - unicode_strlen(matches[n])), ""
  815. );
  816. }
  817. puts(matches[n]);
  818. }
  819. }
  820. static char *add_quote_for_spec_chars(char *found)
  821. {
  822. int l = 0;
  823. char *s = xzalloc((strlen(found) + 1) * 2);
  824. while (*found) {
  825. if (strchr(" `\"#$%^&*()=+{}[]:;'|\\<>", *found))
  826. s[l++] = '\\';
  827. s[l++] = *found++;
  828. }
  829. /* s[l] = '\0'; - already is */
  830. return s;
  831. }
  832. /* Do TAB completion */
  833. static void input_tab(smallint *lastWasTab)
  834. {
  835. if (!(state->flags & TAB_COMPLETION))
  836. return;
  837. if (!*lastWasTab) {
  838. char *tmp, *tmp1;
  839. size_t len_found;
  840. /* char matchBuf[MAX_LINELEN]; */
  841. #define matchBuf (S.input_tab__matchBuf)
  842. int find_type;
  843. int recalc_pos;
  844. #if ENABLE_FEATURE_ASSUME_UNICODE
  845. /* cursor pos in command converted to multibyte form */
  846. int cursor_mb;
  847. #endif
  848. *lastWasTab = TRUE; /* flop trigger */
  849. /* Make a local copy of the string --
  850. * up to the position of the cursor */
  851. save_string(matchBuf, cursor + 1);
  852. #if ENABLE_FEATURE_ASSUME_UNICODE
  853. cursor_mb = strlen(matchBuf);
  854. #endif
  855. tmp = matchBuf;
  856. find_type = find_match(matchBuf, &recalc_pos);
  857. /* Free up any memory already allocated */
  858. free_tab_completion_data();
  859. #if ENABLE_FEATURE_USERNAME_COMPLETION
  860. /* If the word starts with `~' and there is no slash in the word,
  861. * then try completing this word as a username. */
  862. if (state->flags & USERNAME_COMPLETION)
  863. if (matchBuf[0] == '~' && strchr(matchBuf, '/') == NULL)
  864. username_tab_completion(matchBuf, NULL);
  865. #endif
  866. /* Try to match any executable in our path and everything
  867. * in the current working directory */
  868. if (!matches)
  869. exe_n_cwd_tab_completion(matchBuf, find_type);
  870. /* Sort, then remove any duplicates found */
  871. if (matches) {
  872. unsigned i;
  873. int n = 0;
  874. qsort_string_vector(matches, num_matches);
  875. for (i = 0; i < num_matches - 1; ++i) {
  876. if (matches[i] && matches[i+1]) { /* paranoia */
  877. if (strcmp(matches[i], matches[i+1]) == 0) {
  878. free(matches[i]);
  879. matches[i] = NULL; /* paranoia */
  880. } else {
  881. matches[n++] = matches[i];
  882. }
  883. }
  884. }
  885. matches[n] = matches[i];
  886. num_matches = n + 1;
  887. }
  888. /* Did we find exactly one match? */
  889. if (!matches || num_matches > 1) { /* no */
  890. beep();
  891. if (!matches)
  892. return; /* not found */
  893. /* find minimal match */
  894. tmp1 = xstrdup(matches[0]);
  895. for (tmp = tmp1; *tmp; tmp++) {
  896. for (len_found = 1; len_found < num_matches; len_found++) {
  897. if (matches[len_found][tmp - tmp1] != *tmp) {
  898. *tmp = '\0';
  899. break;
  900. }
  901. }
  902. }
  903. if (*tmp1 == '\0') { /* have unique */
  904. free(tmp1);
  905. return;
  906. }
  907. tmp = add_quote_for_spec_chars(tmp1);
  908. free(tmp1);
  909. } else { /* one match */
  910. tmp = add_quote_for_spec_chars(matches[0]);
  911. /* for next completion current found */
  912. *lastWasTab = FALSE;
  913. len_found = strlen(tmp);
  914. if (tmp[len_found-1] != '/') {
  915. tmp[len_found] = ' ';
  916. tmp[len_found+1] = '\0';
  917. }
  918. }
  919. len_found = strlen(tmp);
  920. #if !ENABLE_FEATURE_ASSUME_UNICODE
  921. /* have space to place the match? */
  922. /* The result consists of three parts with these lengths: */
  923. /* (cursor - recalc_pos) + len_found + (command_len - cursor) */
  924. /* it simplifies into: */
  925. if ((int)(len_found + command_len - recalc_pos) < S.maxsize) {
  926. /* save tail */
  927. strcpy(matchBuf, command_ps + cursor);
  928. /* add match and tail */
  929. sprintf(&command_ps[cursor - recalc_pos], "%s%s", tmp, matchBuf);
  930. command_len = strlen(command_ps);
  931. /* new pos */
  932. recalc_pos = cursor - recalc_pos + len_found;
  933. /* write out the matched command */
  934. redraw(cmdedit_y, command_len - recalc_pos);
  935. }
  936. #else
  937. {
  938. char command[MAX_LINELEN];
  939. int len = save_string(command, sizeof(command));
  940. /* have space to place the match? */
  941. /* (cursor_mb - recalc_pos) + len_found + (len - cursor_mb) */
  942. if ((int)(len_found + len - recalc_pos) < MAX_LINELEN) {
  943. /* save tail */
  944. strcpy(matchBuf, command + cursor_mb);
  945. /* where do we want to have cursor after all? */
  946. strcpy(&command[cursor_mb - recalc_pos], tmp);
  947. len = load_string(command, S.maxsize);
  948. /* add match and tail */
  949. sprintf(&command[cursor_mb - recalc_pos], "%s%s", tmp, matchBuf);
  950. command_len = load_string(command, S.maxsize);
  951. /* write out the matched command */
  952. redraw(cmdedit_y, command_len - len);
  953. }
  954. }
  955. #endif
  956. free(tmp);
  957. #undef matchBuf
  958. } else {
  959. /* Ok -- the last char was a TAB. Since they
  960. * just hit TAB again, print a list of all the
  961. * available choices... */
  962. if (matches && num_matches > 0) {
  963. /* changed by goto_new_line() */
  964. int sav_cursor = cursor;
  965. /* Go to the next line */
  966. goto_new_line();
  967. showfiles();
  968. redraw(0, command_len - sav_cursor);
  969. }
  970. }
  971. }
  972. #endif /* FEATURE_COMMAND_TAB_COMPLETION */
  973. line_input_t* FAST_FUNC new_line_input_t(int flags)
  974. {
  975. line_input_t *n = xzalloc(sizeof(*n));
  976. n->flags = flags;
  977. return n;
  978. }
  979. #if MAX_HISTORY > 0
  980. static void save_command_ps_at_cur_history(void)
  981. {
  982. if (command_ps[0] != BB_NUL) {
  983. int cur = state->cur_history;
  984. free(state->history[cur]);
  985. # if ENABLE_FEATURE_ASSUME_UNICODE
  986. {
  987. char tbuf[MAX_LINELEN];
  988. save_string(tbuf, sizeof(tbuf));
  989. state->history[cur] = xstrdup(tbuf);
  990. }
  991. # else
  992. state->history[cur] = xstrdup(command_ps);
  993. # endif
  994. }
  995. }
  996. /* state->flags is already checked to be nonzero */
  997. static int get_previous_history(void)
  998. {
  999. if ((state->flags & DO_HISTORY) && state->cur_history) {
  1000. save_command_ps_at_cur_history();
  1001. state->cur_history--;
  1002. return 1;
  1003. }
  1004. beep();
  1005. return 0;
  1006. }
  1007. static int get_next_history(void)
  1008. {
  1009. if (state->flags & DO_HISTORY) {
  1010. if (state->cur_history < state->cnt_history) {
  1011. save_command_ps_at_cur_history(); /* save the current history line */
  1012. return ++state->cur_history;
  1013. }
  1014. }
  1015. beep();
  1016. return 0;
  1017. }
  1018. # if ENABLE_FEATURE_EDITING_SAVEHISTORY
  1019. /* We try to ensure that concurrent additions to the history
  1020. * do not overwrite each other.
  1021. * Otherwise shell users get unhappy.
  1022. *
  1023. * History file is trimmed lazily, when it grows several times longer
  1024. * than configured MAX_HISTORY lines.
  1025. */
  1026. static void free_line_input_t(line_input_t *n)
  1027. {
  1028. int i = n->cnt_history;
  1029. while (i > 0)
  1030. free(n->history[--i]);
  1031. free(n);
  1032. }
  1033. /* state->flags is already checked to be nonzero */
  1034. static void load_history(line_input_t *st_parm)
  1035. {
  1036. char *temp_h[MAX_HISTORY];
  1037. char *line;
  1038. FILE *fp;
  1039. unsigned idx, i, line_len;
  1040. /* NB: do not trash old history if file can't be opened */
  1041. fp = fopen_for_read(st_parm->hist_file);
  1042. if (fp) {
  1043. /* clean up old history */
  1044. for (idx = st_parm->cnt_history; idx > 0;) {
  1045. idx--;
  1046. free(st_parm->history[idx]);
  1047. st_parm->history[idx] = NULL;
  1048. }
  1049. /* fill temp_h[], retaining only last MAX_HISTORY lines */
  1050. memset(temp_h, 0, sizeof(temp_h));
  1051. st_parm->cnt_history_in_file = idx = 0;
  1052. while ((line = xmalloc_fgetline(fp)) != NULL) {
  1053. if (line[0] == '\0') {
  1054. free(line);
  1055. continue;
  1056. }
  1057. free(temp_h[idx]);
  1058. temp_h[idx] = line;
  1059. st_parm->cnt_history_in_file++;
  1060. idx++;
  1061. if (idx == MAX_HISTORY)
  1062. idx = 0;
  1063. }
  1064. fclose(fp);
  1065. /* find first non-NULL temp_h[], if any */
  1066. if (st_parm->cnt_history_in_file) {
  1067. while (temp_h[idx] == NULL) {
  1068. idx++;
  1069. if (idx == MAX_HISTORY)
  1070. idx = 0;
  1071. }
  1072. }
  1073. /* copy temp_h[] to st_parm->history[] */
  1074. for (i = 0; i < MAX_HISTORY;) {
  1075. line = temp_h[idx];
  1076. if (!line)
  1077. break;
  1078. idx++;
  1079. if (idx == MAX_HISTORY)
  1080. idx = 0;
  1081. line_len = strlen(line);
  1082. if (line_len >= MAX_LINELEN)
  1083. line[MAX_LINELEN-1] = '\0';
  1084. st_parm->history[i++] = line;
  1085. }
  1086. st_parm->cnt_history = i;
  1087. }
  1088. }
  1089. /* state->flags is already checked to be nonzero */
  1090. static void save_history(char *str)
  1091. {
  1092. int fd;
  1093. int len, len2;
  1094. fd = open(state->hist_file, O_WRONLY | O_CREAT | O_APPEND, 0666);
  1095. if (fd < 0)
  1096. return;
  1097. xlseek(fd, 0, SEEK_END); /* paranoia */
  1098. len = strlen(str);
  1099. str[len] = '\n'; /* we (try to) do atomic write */
  1100. len2 = full_write(fd, str, len + 1);
  1101. str[len] = '\0';
  1102. close(fd);
  1103. if (len2 != len + 1)
  1104. return; /* "wtf?" */
  1105. /* did we write so much that history file needs trimming? */
  1106. state->cnt_history_in_file++;
  1107. if (state->cnt_history_in_file > MAX_HISTORY * 4) {
  1108. FILE *fp;
  1109. char *new_name;
  1110. line_input_t *st_temp;
  1111. int i;
  1112. /* we may have concurrently written entries from others.
  1113. * load them */
  1114. st_temp = new_line_input_t(state->flags);
  1115. st_temp->hist_file = state->hist_file;
  1116. load_history(st_temp);
  1117. /* write out temp file and replace hist_file atomically */
  1118. new_name = xasprintf("%s.%u.new", state->hist_file, (int) getpid());
  1119. fp = fopen_for_write(new_name);
  1120. if (fp) {
  1121. for (i = 0; i < st_temp->cnt_history; i++)
  1122. fprintf(fp, "%s\n", st_temp->history[i]);
  1123. fclose(fp);
  1124. if (rename(new_name, state->hist_file) == 0)
  1125. state->cnt_history_in_file = st_temp->cnt_history;
  1126. }
  1127. free(new_name);
  1128. free_line_input_t(st_temp);
  1129. }
  1130. }
  1131. # else
  1132. # define load_history(a) ((void)0)
  1133. # define save_history(a) ((void)0)
  1134. # endif /* FEATURE_COMMAND_SAVEHISTORY */
  1135. static void remember_in_history(char *str)
  1136. {
  1137. int i;
  1138. if (!(state->flags & DO_HISTORY))
  1139. return;
  1140. if (str[0] == '\0')
  1141. return;
  1142. i = state->cnt_history;
  1143. /* Don't save dupes */
  1144. if (i && strcmp(state->history[i-1], str) == 0)
  1145. return;
  1146. free(state->history[MAX_HISTORY]); /* redundant, paranoia */
  1147. state->history[MAX_HISTORY] = NULL; /* redundant, paranoia */
  1148. /* If history[] is full, remove the oldest command */
  1149. /* we need to keep history[MAX_HISTORY] empty, hence >=, not > */
  1150. if (i >= MAX_HISTORY) {
  1151. free(state->history[0]);
  1152. for (i = 0; i < MAX_HISTORY-1; i++)
  1153. state->history[i] = state->history[i+1];
  1154. /* i == MAX_HISTORY-1 */
  1155. }
  1156. /* i <= MAX_HISTORY-1 */
  1157. state->history[i++] = xstrdup(str);
  1158. /* i <= MAX_HISTORY */
  1159. state->cur_history = i;
  1160. state->cnt_history = i;
  1161. # if MAX_HISTORY > 0 && ENABLE_FEATURE_EDITING_SAVEHISTORY
  1162. if ((state->flags & SAVE_HISTORY) && state->hist_file)
  1163. save_history(str);
  1164. # endif
  1165. IF_FEATURE_EDITING_FANCY_PROMPT(num_ok_lines++;)
  1166. }
  1167. #else /* MAX_HISTORY == 0 */
  1168. # define remember_in_history(a) ((void)0)
  1169. #endif /* MAX_HISTORY */
  1170. #if ENABLE_FEATURE_EDITING_VI
  1171. /*
  1172. * vi mode implemented 2005 by Paul Fox <pgf@foxharp.boston.ma.us>
  1173. */
  1174. static void
  1175. vi_Word_motion(int eat)
  1176. {
  1177. CHAR_T *command = command_ps;
  1178. while (cursor < command_len && !BB_isspace(command[cursor]))
  1179. input_forward();
  1180. if (eat) while (cursor < command_len && BB_isspace(command[cursor]))
  1181. input_forward();
  1182. }
  1183. static void
  1184. vi_word_motion(int eat)
  1185. {
  1186. CHAR_T *command = command_ps;
  1187. if (BB_isalnum(command[cursor]) || command[cursor] == '_') {
  1188. while (cursor < command_len
  1189. && (BB_isalnum(command[cursor+1]) || command[cursor+1] == '_')
  1190. ) {
  1191. input_forward();
  1192. }
  1193. } else if (BB_ispunct(command[cursor])) {
  1194. while (cursor < command_len && BB_ispunct(command[cursor+1]))
  1195. input_forward();
  1196. }
  1197. if (cursor < command_len)
  1198. input_forward();
  1199. if (eat) {
  1200. while (cursor < command_len && BB_isspace(command[cursor]))
  1201. input_forward();
  1202. }
  1203. }
  1204. static void
  1205. vi_End_motion(void)
  1206. {
  1207. CHAR_T *command = command_ps;
  1208. input_forward();
  1209. while (cursor < command_len && BB_isspace(command[cursor]))
  1210. input_forward();
  1211. while (cursor < command_len-1 && !BB_isspace(command[cursor+1]))
  1212. input_forward();
  1213. }
  1214. static void
  1215. vi_end_motion(void)
  1216. {
  1217. CHAR_T *command = command_ps;
  1218. if (cursor >= command_len-1)
  1219. return;
  1220. input_forward();
  1221. while (cursor < command_len-1 && BB_isspace(command[cursor]))
  1222. input_forward();
  1223. if (cursor >= command_len-1)
  1224. return;
  1225. if (BB_isalnum(command[cursor]) || command[cursor] == '_') {
  1226. while (cursor < command_len-1
  1227. && (BB_isalnum(command[cursor+1]) || command[cursor+1] == '_')
  1228. ) {
  1229. input_forward();
  1230. }
  1231. } else if (BB_ispunct(command[cursor])) {
  1232. while (cursor < command_len-1 && BB_ispunct(command[cursor+1]))
  1233. input_forward();
  1234. }
  1235. }
  1236. static void
  1237. vi_Back_motion(void)
  1238. {
  1239. CHAR_T *command = command_ps;
  1240. while (cursor > 0 && BB_isspace(command[cursor-1]))
  1241. input_backward(1);
  1242. while (cursor > 0 && !BB_isspace(command[cursor-1]))
  1243. input_backward(1);
  1244. }
  1245. static void
  1246. vi_back_motion(void)
  1247. {
  1248. CHAR_T *command = command_ps;
  1249. if (cursor <= 0)
  1250. return;
  1251. input_backward(1);
  1252. while (cursor > 0 && BB_isspace(command[cursor]))
  1253. input_backward(1);
  1254. if (cursor <= 0)
  1255. return;
  1256. if (BB_isalnum(command[cursor]) || command[cursor] == '_') {
  1257. while (cursor > 0
  1258. && (BB_isalnum(command[cursor-1]) || command[cursor-1] == '_')
  1259. ) {
  1260. input_backward(1);
  1261. }
  1262. } else if (BB_ispunct(command[cursor])) {
  1263. while (cursor > 0 && BB_ispunct(command[cursor-1]))
  1264. input_backward(1);
  1265. }
  1266. }
  1267. #endif
  1268. /* Modelled after bash 4.0 behavior of Ctrl-<arrow> */
  1269. static void ctrl_left(void)
  1270. {
  1271. CHAR_T *command = command_ps;
  1272. while (1) {
  1273. CHAR_T c;
  1274. input_backward(1);
  1275. if (cursor == 0)
  1276. break;
  1277. c = command[cursor];
  1278. if (c != ' ' && !BB_ispunct(c)) {
  1279. /* we reached a "word" delimited by spaces/punct.
  1280. * go to its beginning */
  1281. while (1) {
  1282. c = command[cursor - 1];
  1283. if (c == ' ' || BB_ispunct(c))
  1284. break;
  1285. input_backward(1);
  1286. if (cursor == 0)
  1287. break;
  1288. }
  1289. break;
  1290. }
  1291. }
  1292. }
  1293. static void ctrl_right(void)
  1294. {
  1295. CHAR_T *command = command_ps;
  1296. while (1) {
  1297. CHAR_T c;
  1298. c = command[cursor];
  1299. if (c == BB_NUL)
  1300. break;
  1301. if (c != ' ' && !BB_ispunct(c)) {
  1302. /* we reached a "word" delimited by spaces/punct.
  1303. * go to its end + 1 */
  1304. while (1) {
  1305. input_forward();
  1306. c = command[cursor];
  1307. if (c == BB_NUL || c == ' ' || BB_ispunct(c))
  1308. break;
  1309. }
  1310. break;
  1311. }
  1312. input_forward();
  1313. }
  1314. }
  1315. /*
  1316. * read_line_input and its helpers
  1317. */
  1318. #if ENABLE_FEATURE_EDITING_ASK_TERMINAL
  1319. static void ask_terminal(void)
  1320. {
  1321. /* Ask terminal where is the cursor now.
  1322. * lineedit_read_key handles response and corrects
  1323. * our idea of current cursor position.
  1324. * Testcase: run "echo -n long_line_long_line_long_line",
  1325. * then type in a long, wrapping command and try to
  1326. * delete it using backspace key.
  1327. * Note: we print it _after_ prompt, because
  1328. * prompt may contain CR. Example: PS1='\[\r\n\]\w '
  1329. */
  1330. /* Problem: if there is buffered input on stdin,
  1331. * the response will be delivered later,
  1332. * possibly to an unsuspecting application.
  1333. * Testcase: "sleep 1; busybox ash" + press and hold [Enter].
  1334. * Result:
  1335. * ~/srcdevel/bbox/fix/busybox.t4 #
  1336. * ~/srcdevel/bbox/fix/busybox.t4 #
  1337. * ^[[59;34~/srcdevel/bbox/fix/busybox.t4 # <-- garbage
  1338. * ~/srcdevel/bbox/fix/busybox.t4 #
  1339. *
  1340. * Checking for input with poll only makes the race narrower,
  1341. * I still can trigger it. Strace:
  1342. *
  1343. * write(1, "~/srcdevel/bbox/fix/busybox.t4 # ", 33) = 33
  1344. * poll([{fd=0, events=POLLIN}], 1, 0) = 0 (Timeout) <-- no input exists
  1345. * write(1, "\33[6n", 4) = 4 <-- send the ESC sequence, quick!
  1346. * poll([{fd=0, events=POLLIN}], 1, 4294967295) = 1 ([{fd=0, revents=POLLIN}])
  1347. * read(0, "\n", 1) = 1 <-- oh crap, user's input got in first
  1348. */
  1349. struct pollfd pfd;
  1350. pfd.fd = STDIN_FILENO;
  1351. pfd.events = POLLIN;
  1352. if (safe_poll(&pfd, 1, 0) == 0) {
  1353. S.sent_ESC_br6n = 1;
  1354. out1str("\033" "[6n");
  1355. fflush_all(); /* make terminal see it ASAP! */
  1356. }
  1357. }
  1358. #else
  1359. #define ask_terminal() ((void)0)
  1360. #endif
  1361. #if !ENABLE_FEATURE_EDITING_FANCY_PROMPT
  1362. static void parse_and_put_prompt(const char *prmt_ptr)
  1363. {
  1364. cmdedit_prompt = prmt_ptr;
  1365. cmdedit_prmt_len = strlen(prmt_ptr);
  1366. put_prompt();
  1367. }
  1368. #else
  1369. static void parse_and_put_prompt(const char *prmt_ptr)
  1370. {
  1371. int prmt_len = 0;
  1372. size_t cur_prmt_len = 0;
  1373. char flg_not_length = '[';
  1374. char *prmt_mem_ptr = xzalloc(1);
  1375. char *cwd_buf = xrealloc_getcwd_or_warn(NULL);
  1376. char cbuf[2];
  1377. char c;
  1378. char *pbuf;
  1379. cmdedit_prmt_len = 0;
  1380. if (!cwd_buf) {
  1381. cwd_buf = (char *)bb_msg_unknown;
  1382. }
  1383. cbuf[1] = '\0'; /* never changes */
  1384. while (*prmt_ptr) {
  1385. char *free_me = NULL;
  1386. pbuf = cbuf;
  1387. c = *prmt_ptr++;
  1388. if (c == '\\') {
  1389. const char *cp = prmt_ptr;
  1390. int l;
  1391. c = bb_process_escape_sequence(&prmt_ptr);
  1392. if (prmt_ptr == cp) {
  1393. if (*cp == '\0')
  1394. break;
  1395. c = *prmt_ptr++;
  1396. switch (c) {
  1397. # if ENABLE_FEATURE_GETUSERNAME_AND_HOMEDIR
  1398. case 'u':
  1399. pbuf = user_buf ? user_buf : (char*)"";
  1400. break;
  1401. # endif
  1402. case 'h':
  1403. pbuf = free_me = safe_gethostname();
  1404. *strchrnul(pbuf, '.') = '\0';
  1405. break;
  1406. case '$':
  1407. c = (geteuid() == 0 ? '#' : '$');
  1408. break;
  1409. # if ENABLE_FEATURE_GETUSERNAME_AND_HOMEDIR
  1410. case 'w':
  1411. /* /home/user[/something] -> ~[/something] */
  1412. pbuf = cwd_buf;
  1413. l = strlen(home_pwd_buf);
  1414. if (l != 0
  1415. && strncmp(home_pwd_buf, cwd_buf, l) == 0
  1416. && (cwd_buf[l]=='/' || cwd_buf[l]=='\0')
  1417. && strlen(cwd_buf + l) < PATH_MAX
  1418. ) {
  1419. pbuf = free_me = xasprintf("~%s", cwd_buf + l);
  1420. }
  1421. break;
  1422. # endif
  1423. case 'W':
  1424. pbuf = cwd_buf;
  1425. cp = strrchr(pbuf, '/');
  1426. if (cp != NULL && cp != pbuf)
  1427. pbuf += (cp-pbuf) + 1;
  1428. break;
  1429. case '!':
  1430. pbuf = free_me = xasprintf("%d", num_ok_lines);
  1431. break;
  1432. case 'e': case 'E': /* \e \E = \033 */
  1433. c = '\033';
  1434. break;
  1435. case 'x': case 'X': {
  1436. char buf2[4];
  1437. for (l = 0; l < 3;) {
  1438. unsigned h;
  1439. buf2[l++] = *prmt_ptr;
  1440. buf2[l] = '\0';
  1441. h = strtoul(buf2, &pbuf, 16);
  1442. if (h > UCHAR_MAX || (pbuf - buf2) < l) {
  1443. buf2[--l] = '\0';
  1444. break;
  1445. }
  1446. prmt_ptr++;
  1447. }
  1448. c = (char)strtoul(buf2, NULL, 16);
  1449. if (c == 0)
  1450. c = '?';
  1451. pbuf = cbuf;
  1452. break;
  1453. }
  1454. case '[': case ']':
  1455. if (c == flg_not_length) {
  1456. flg_not_length = (flg_not_length == '[' ? ']' : '[');
  1457. continue;
  1458. }
  1459. break;
  1460. } /* switch */
  1461. } /* if */
  1462. } /* if */
  1463. cbuf[0] = c;
  1464. cur_prmt_len = strlen(pbuf);
  1465. prmt_len += cur_prmt_len;
  1466. if (flg_not_length != ']')
  1467. cmdedit_prmt_len += cur_prmt_len;
  1468. prmt_mem_ptr = strcat(xrealloc(prmt_mem_ptr, prmt_len+1), pbuf);
  1469. free(free_me);
  1470. } /* while */
  1471. if (cwd_buf != (char *)bb_msg_unknown)
  1472. free(cwd_buf);
  1473. cmdedit_prompt = prmt_mem_ptr;
  1474. put_prompt();
  1475. }
  1476. #endif
  1477. static void cmdedit_setwidth(unsigned w, int redraw_flg)
  1478. {
  1479. cmdedit_termw = w;
  1480. if (redraw_flg) {
  1481. /* new y for current cursor */
  1482. int new_y = (cursor + cmdedit_prmt_len) / w;
  1483. /* redraw */
  1484. redraw((new_y >= cmdedit_y ? new_y : cmdedit_y), command_len - cursor);
  1485. fflush_all();
  1486. }
  1487. }
  1488. static void win_changed(int nsig)
  1489. {
  1490. unsigned width;
  1491. get_terminal_width_height(0, &width, NULL);
  1492. cmdedit_setwidth(width, nsig /* - just a yes/no flag */);
  1493. if (nsig == SIGWINCH)
  1494. signal(SIGWINCH, win_changed); /* rearm ourself */
  1495. }
  1496. static int lineedit_read_key(char *read_key_buffer)
  1497. {
  1498. int64_t ic;
  1499. struct pollfd pfd;
  1500. int delay = -1;
  1501. #if ENABLE_FEATURE_ASSUME_UNICODE
  1502. char unicode_buf[MB_CUR_MAX + 1];
  1503. int unicode_idx = 0;
  1504. #endif
  1505. pfd.fd = STDIN_FILENO;
  1506. pfd.events = POLLIN;
  1507. do {
  1508. #if ENABLE_FEATURE_EDITING_ASK_TERMINAL || ENABLE_FEATURE_ASSUME_UNICODE
  1509. poll_again:
  1510. #endif
  1511. if (read_key_buffer[0] == 0) {
  1512. /* Wait for input. Can't just call read_key,
  1513. * it returns at once if stdin
  1514. * is in non-blocking mode. */
  1515. safe_poll(&pfd, 1, delay);
  1516. }
  1517. /* Note: read_key sets errno to 0 on success: */
  1518. ic = read_key(STDIN_FILENO, read_key_buffer);
  1519. #if ENABLE_FEATURE_EDITING_ASK_TERMINAL
  1520. if ((int32_t)ic == KEYCODE_CURSOR_POS
  1521. && S.sent_ESC_br6n
  1522. ) {
  1523. S.sent_ESC_br6n = 0;
  1524. if (cursor == 0) { /* otherwise it may be bogus */
  1525. int col = ((ic >> 32) & 0x7fff) - 1;
  1526. if (col > cmdedit_prmt_len) {
  1527. cmdedit_x += (col - cmdedit_prmt_len);
  1528. while (cmdedit_x >= cmdedit_termw) {
  1529. cmdedit_x -= cmdedit_termw;
  1530. cmdedit_y++;
  1531. }
  1532. }
  1533. }
  1534. goto poll_again;
  1535. }
  1536. #endif
  1537. #if ENABLE_FEATURE_ASSUME_UNICODE
  1538. {
  1539. wchar_t wc;
  1540. if ((int32_t)ic < 0) /* KEYCODE_xxx */
  1541. return ic;
  1542. unicode_buf[unicode_idx++] = ic;
  1543. unicode_buf[unicode_idx] = '\0';
  1544. if (mbstowcs(&wc, unicode_buf, 1) != 1 && unicode_idx < MB_CUR_MAX) {
  1545. delay = 50;
  1546. goto poll_again;
  1547. }
  1548. ic = wc;
  1549. }
  1550. #endif
  1551. } while (errno == EAGAIN);
  1552. return ic;
  1553. }
  1554. /* leave out the "vi-mode"-only case labels if vi editing isn't
  1555. * configured. */
  1556. #define vi_case(caselabel) IF_FEATURE_EDITING_VI(case caselabel)
  1557. /* convert uppercase ascii to equivalent control char, for readability */
  1558. #undef CTRL
  1559. #define CTRL(a) ((a) & ~0x40)
  1560. /* maxsize must be >= 2.
  1561. * Returns:
  1562. * -1 on read errors or EOF, or on bare Ctrl-D,
  1563. * 0 on ctrl-C (the line entered is still returned in 'command'),
  1564. * >0 length of input string, including terminating '\n'
  1565. */
  1566. int FAST_FUNC read_line_input(const char *prompt, char *command, int maxsize, line_input_t *st)
  1567. {
  1568. int len;
  1569. #if ENABLE_FEATURE_TAB_COMPLETION
  1570. smallint lastWasTab = FALSE;
  1571. #endif
  1572. smallint break_out = 0;
  1573. #if ENABLE_FEATURE_EDITING_VI
  1574. smallint vi_cmdmode = 0;
  1575. #endif
  1576. struct termios initial_settings;
  1577. struct termios new_settings;
  1578. char read_key_buffer[KEYCODE_BUFFER_SIZE];
  1579. INIT_S();
  1580. if (tcgetattr(STDIN_FILENO, &initial_settings) < 0
  1581. || !(initial_settings.c_lflag & ECHO)
  1582. ) {
  1583. /* Happens when e.g. stty -echo was run before */
  1584. parse_and_put_prompt(prompt);
  1585. /* fflush_all(); - done by parse_and_put_prompt */
  1586. if (fgets(command, maxsize, stdin) == NULL)
  1587. len = -1; /* EOF or error */
  1588. else
  1589. len = strlen(command);
  1590. DEINIT_S();
  1591. return len;
  1592. }
  1593. init_unicode();
  1594. // FIXME: audit & improve this
  1595. if (maxsize > MAX_LINELEN)
  1596. maxsize = MAX_LINELEN;
  1597. S.maxsize = maxsize;
  1598. /* With null flags, no other fields are ever used */
  1599. state = st ? st : (line_input_t*) &const_int_0;
  1600. #if MAX_HISTORY > 0
  1601. # if ENABLE_FEATURE_EDITING_SAVEHISTORY
  1602. if ((state->flags & SAVE_HISTORY) && state->hist_file)
  1603. if (state->cnt_history == 0)
  1604. load_history(state);
  1605. # endif
  1606. if (state->flags & DO_HISTORY)
  1607. state->cur_history = state->cnt_history;
  1608. #endif
  1609. /* prepare before init handlers */
  1610. cmdedit_y = 0; /* quasireal y, not true if line > xt*yt */
  1611. command_len = 0;
  1612. #if ENABLE_FEATURE_ASSUME_UNICODE
  1613. command_ps = xzalloc(maxsize * sizeof(command_ps[0]));
  1614. #else
  1615. command_ps = command;
  1616. command[0] = '\0';
  1617. #endif
  1618. #define command command_must_not_be_used
  1619. new_settings = initial_settings;
  1620. new_settings.c_lflag &= ~ICANON; /* unbuffered input */
  1621. /* Turn off echoing and CTRL-C, so we can trap it */
  1622. new_settings.c_lflag &= ~(ECHO | ECHONL | ISIG);
  1623. /* Hmm, in linux c_cc[] is not parsed if ICANON is off */
  1624. new_settings.c_cc[VMIN] = 1;
  1625. new_settings.c_cc[VTIME] = 0;
  1626. /* Turn off CTRL-C, so we can trap it */
  1627. #ifndef _POSIX_VDISABLE
  1628. # define _POSIX_VDISABLE '\0'
  1629. #endif
  1630. new_settings.c_cc[VINTR] = _POSIX_VDISABLE;
  1631. tcsetattr_stdin_TCSANOW(&new_settings);
  1632. /* Now initialize things */
  1633. previous_SIGWINCH_handler = signal(SIGWINCH, win_changed);
  1634. win_changed(0); /* do initial resizing */
  1635. #if ENABLE_FEATURE_GETUSERNAME_AND_HOMEDIR
  1636. {
  1637. struct passwd *entry;
  1638. entry = getpwuid(geteuid());
  1639. if (entry) {
  1640. user_buf = xstrdup(entry->pw_name);
  1641. home_pwd_buf = xstrdup(entry->pw_dir);
  1642. }
  1643. }
  1644. #endif
  1645. #if 0
  1646. for (i = 0; i <= MAX_HISTORY; i++)
  1647. bb_error_msg("history[%d]:'%s'", i, state->history[i]);
  1648. bb_error_msg("cur_history:%d cnt_history:%d", state->cur_history, state->cnt_history);
  1649. #endif
  1650. /* Print out the command prompt, optionally ask where cursor is */
  1651. parse_and_put_prompt(prompt);
  1652. ask_terminal();
  1653. read_key_buffer[0] = 0;
  1654. while (1) {
  1655. /*
  1656. * The emacs and vi modes share much of the code in the big
  1657. * command loop. Commands entered when in vi's command mode
  1658. * (aka "escape mode") get an extra bit added to distinguish
  1659. * them - this keeps them from being self-inserted. This
  1660. * clutters the big switch a bit, but keeps all the code
  1661. * in one place.
  1662. */
  1663. enum {
  1664. VI_CMDMODE_BIT = 0x40000000,
  1665. /* 0x80000000 bit flags KEYCODE_xxx */
  1666. };
  1667. int32_t ic, ic_raw;
  1668. fflush_all();
  1669. ic = ic_raw = lineedit_read_key(read_key_buffer);
  1670. #if ENABLE_FEATURE_EDITING_VI
  1671. newdelflag = 1;
  1672. if (vi_cmdmode) {
  1673. /* btw, since KEYCODE_xxx are all < 0, this doesn't
  1674. * change ic if it contains one of them: */
  1675. ic |= VI_CMDMODE_BIT;
  1676. }
  1677. #endif
  1678. switch (ic) {
  1679. case '\n':
  1680. case '\r':
  1681. vi_case('\n'|VI_CMDMODE_BIT:)
  1682. vi_case('\r'|VI_CMDMODE_BIT:)
  1683. /* Enter */
  1684. goto_new_line();
  1685. break_out = 1;
  1686. break;
  1687. case CTRL('A'):
  1688. vi_case('0'|VI_CMDMODE_BIT:)
  1689. /* Control-a -- Beginning of line */
  1690. input_backward(cursor);
  1691. break;
  1692. case CTRL('B'):
  1693. vi_case('h'|VI_CMDMODE_BIT:)
  1694. vi_case('\b'|VI_CMDMODE_BIT:)
  1695. vi_case('\x7f'|VI_CMDMODE_BIT:) /* DEL */
  1696. /* Control-b -- Move back one character */
  1697. input_backward(1);
  1698. break;
  1699. case CTRL('E'):
  1700. vi_case('$'|VI_CMDMODE_BIT:)
  1701. /* Control-e -- End of line */
  1702. input_end();
  1703. break;
  1704. case CTRL('F'):
  1705. vi_case('l'|VI_CMDMODE_BIT:)
  1706. vi_case(' '|VI_CMDMODE_BIT:)
  1707. /* Control-f -- Move forward one character */
  1708. input_forward();
  1709. break;
  1710. case '\b':
  1711. case '\x7f': /* DEL */
  1712. /* Control-h and DEL */
  1713. input_backspace();
  1714. break;
  1715. #if ENABLE_FEATURE_TAB_COMPLETION
  1716. case '\t':
  1717. input_tab(&lastWasTab);
  1718. break;
  1719. #endif
  1720. case CTRL('K'):
  1721. /* Control-k -- clear to end of line */
  1722. command_ps[cursor] = BB_NUL;
  1723. command_len = cursor;
  1724. printf("\033[J");
  1725. break;
  1726. case CTRL('L'):
  1727. vi_case(CTRL('L')|VI_CMDMODE_BIT:)
  1728. /* Control-l -- clear screen */
  1729. printf("\033[H");
  1730. redraw(0, command_len - cursor);
  1731. break;
  1732. #if MAX_HISTORY > 0
  1733. case CTRL('N'):
  1734. vi_case(CTRL('N')|VI_CMDMODE_BIT:)
  1735. vi_case('j'|VI_CMDMODE_BIT:)
  1736. /* Control-n -- Get next command in history */
  1737. if (get_next_history())
  1738. goto rewrite_line;
  1739. break;
  1740. case CTRL('P'):
  1741. vi_case(CTRL('P')|VI_CMDMODE_BIT:)
  1742. vi_case('k'|VI_CMDMODE_BIT:)
  1743. /* Control-p -- Get previous command from history */
  1744. if (get_previous_history())
  1745. goto rewrite_line;
  1746. break;
  1747. #endif
  1748. case CTRL('U'):
  1749. vi_case(CTRL('U')|VI_CMDMODE_BIT:)
  1750. /* Control-U -- Clear line before cursor */
  1751. if (cursor) {
  1752. command_len -= cursor;
  1753. memmove(command_ps, command_ps + cursor,
  1754. (command_len + 1) * sizeof(command_ps[0]));
  1755. redraw(cmdedit_y, command_len);
  1756. }
  1757. break;
  1758. case CTRL('W'):
  1759. vi_case(CTRL('W')|VI_CMDMODE_BIT:)
  1760. /* Control-W -- Remove the last word */
  1761. while (cursor > 0 && BB_isspace(command_ps[cursor-1]))
  1762. input_backspace();
  1763. while (cursor > 0 && !BB_isspace(command_ps[cursor-1]))
  1764. input_backspace();
  1765. break;
  1766. #if ENABLE_FEATURE_EDITING_VI
  1767. case 'i'|VI_CMDMODE_BIT:
  1768. vi_cmdmode = 0;
  1769. break;
  1770. case 'I'|VI_CMDMODE_BIT:
  1771. input_backward(cursor);
  1772. vi_cmdmode = 0;
  1773. break;
  1774. case 'a'|VI_CMDMODE_BIT:
  1775. input_forward();
  1776. vi_cmdmode = 0;
  1777. break;
  1778. case 'A'|VI_CMDMODE_BIT:
  1779. input_end();
  1780. vi_cmdmode = 0;
  1781. break;
  1782. case 'x'|VI_CMDMODE_BIT:
  1783. input_delete(1);
  1784. break;
  1785. case 'X'|VI_CMDMODE_BIT:
  1786. if (cursor > 0) {
  1787. input_backward(1);
  1788. input_delete(1);
  1789. }
  1790. break;
  1791. case 'W'|VI_CMDMODE_BIT:
  1792. vi_Word_motion(1);
  1793. break;
  1794. case 'w'|VI_CMDMODE_BIT:
  1795. vi_word_motion(1);
  1796. break;
  1797. case 'E'|VI_CMDMODE_BIT:
  1798. vi_End_motion();
  1799. break;
  1800. case 'e'|VI_CMDMODE_BIT:
  1801. vi_end_motion();
  1802. break;
  1803. case 'B'|VI_CMDMODE_BIT:
  1804. vi_Back_motion();
  1805. break;
  1806. case 'b'|VI_CMDMODE_BIT:
  1807. vi_back_motion();
  1808. break;
  1809. case 'C'|VI_CMDMODE_BIT:
  1810. vi_cmdmode = 0;
  1811. /* fall through */
  1812. case 'D'|VI_CMDMODE_BIT:
  1813. goto clear_to_eol;
  1814. case 'c'|VI_CMDMODE_BIT:
  1815. vi_cmdmode = 0;
  1816. /* fall through */
  1817. case 'd'|VI_CMDMODE_BIT: {
  1818. int nc, sc;
  1819. ic = lineedit_read_key(read_key_buffer);
  1820. if (errno) /* error */
  1821. goto prepare_to_die;
  1822. if (ic == ic_raw) { /* "cc", "dd" */
  1823. input_backward(cursor);
  1824. goto clear_to_eol;
  1825. break;
  1826. }
  1827. sc = cursor;
  1828. switch (ic) {
  1829. case 'w':
  1830. case 'W':
  1831. case 'e':
  1832. case 'E':
  1833. switch (ic) {
  1834. case 'w': /* "dw", "cw" */
  1835. vi_word_motion(vi_cmdmode);
  1836. break;
  1837. case 'W': /* 'dW', 'cW' */
  1838. vi_Word_motion(vi_cmdmode);
  1839. break;
  1840. case 'e': /* 'de', 'ce' */
  1841. vi_end_motion();
  1842. input_forward();
  1843. break;
  1844. case 'E': /* 'dE', 'cE' */
  1845. vi_End_motion();
  1846. input_forward();
  1847. break;
  1848. }
  1849. nc = cursor;
  1850. input_backward(cursor - sc);
  1851. while (nc-- > cursor)
  1852. input_delete(1);
  1853. break;
  1854. case 'b': /* "db", "cb" */
  1855. case 'B': /* implemented as B */
  1856. if (ic == 'b')
  1857. vi_back_motion();
  1858. else
  1859. vi_Back_motion();
  1860. while (sc-- > cursor)
  1861. input_delete(1);
  1862. break;
  1863. case ' ': /* "d ", "c " */
  1864. input_delete(1);
  1865. break;
  1866. case '$': /* "d$", "c$" */
  1867. clear_to_eol:
  1868. while (cursor < command_len)
  1869. input_delete(1);
  1870. break;
  1871. }
  1872. break;
  1873. }
  1874. case 'p'|VI_CMDMODE_BIT:
  1875. input_forward();
  1876. /* fallthrough */
  1877. case 'P'|VI_CMDMODE_BIT:
  1878. put();
  1879. break;
  1880. case 'r'|VI_CMDMODE_BIT:
  1881. //FIXME: unicode case?
  1882. ic = lineedit_read_key(read_key_buffer);
  1883. if (errno) /* error */
  1884. goto prepare_to_die;
  1885. if (ic < ' ' || ic > 255) {
  1886. beep();
  1887. } else {
  1888. command_ps[cursor] = ic;
  1889. bb_putchar(ic);
  1890. bb_putchar('\b');
  1891. }
  1892. break;
  1893. case '\x1b': /* ESC */
  1894. if (state->flags & VI_MODE) {
  1895. /* insert mode --> command mode */
  1896. vi_cmdmode = 1;
  1897. input_backward(1);
  1898. }
  1899. break;
  1900. #endif /* FEATURE_COMMAND_EDITING_VI */
  1901. #if MAX_HISTORY > 0
  1902. case KEYCODE_UP:
  1903. if (get_previous_history())
  1904. goto rewrite_line;
  1905. beep();
  1906. break;
  1907. case KEYCODE_DOWN:
  1908. if (!get_next_history())
  1909. break;
  1910. rewrite_line:
  1911. /* Rewrite the line with the selected history item */
  1912. /* change command */
  1913. command_len = load_string(state->history[state->cur_history] ?
  1914. state->history[state->cur_history] : "", maxsize);
  1915. /* redraw and go to eol (bol, in vi) */
  1916. redraw(cmdedit_y, (state->flags & VI_MODE) ? 9999 : 0);
  1917. break;
  1918. #endif
  1919. case KEYCODE_RIGHT:
  1920. input_forward();
  1921. break;
  1922. case KEYCODE_LEFT:
  1923. input_backward(1);
  1924. break;
  1925. case KEYCODE_CTRL_LEFT:
  1926. ctrl_left();
  1927. break;
  1928. case KEYCODE_CTRL_RIGHT:
  1929. ctrl_right();
  1930. break;
  1931. case KEYCODE_DELETE:
  1932. input_delete(0);
  1933. break;
  1934. case KEYCODE_HOME:
  1935. input_backward(cursor);
  1936. break;
  1937. case KEYCODE_END:
  1938. input_end();
  1939. break;
  1940. default:
  1941. if (initial_settings.c_cc[VINTR] != 0
  1942. && ic_raw == initial_settings.c_cc[VINTR]
  1943. ) {
  1944. /* Ctrl-C (usually) - stop gathering input */
  1945. goto_new_line();
  1946. command_len = 0;
  1947. break_out = -1; /* "do not append '\n'" */
  1948. break;
  1949. }
  1950. if (initial_settings.c_cc[VEOF] != 0
  1951. && ic_raw == initial_settings.c_cc[VEOF]
  1952. ) {
  1953. /* Ctrl-D (usually) - delete one character,
  1954. * or exit if len=0 and no chars to delete */
  1955. if (command_len == 0) {
  1956. errno = 0;
  1957. #if ENABLE_FEATURE_EDITING_VI
  1958. prepare_to_die:
  1959. #endif
  1960. break_out = command_len = -1;
  1961. break;
  1962. }
  1963. input_delete(0);
  1964. break;
  1965. }
  1966. // /* Control-V -- force insert of next char */
  1967. // if (c == CTRL('V')) {
  1968. // if (safe_read(STDIN_FILENO, &c, 1) < 1)
  1969. // goto prepare_to_die;
  1970. // if (c == 0) {
  1971. // beep();
  1972. // break;
  1973. // }
  1974. // }
  1975. if (ic < ' '
  1976. || (!ENABLE_FEATURE_ASSUME_UNICODE && ic >= 256)
  1977. || (ENABLE_FEATURE_ASSUME_UNICODE && ic >= VI_CMDMODE_BIT)
  1978. ) {
  1979. /* If VI_CMDMODE_BIT is set, ic is >= 256
  1980. * and vi mode ignores unexpected chars.
  1981. * Otherwise, we are here if ic is a
  1982. * control char or an unhandled ESC sequence,
  1983. * which is also ignored.
  1984. */
  1985. break;
  1986. }
  1987. if ((int)command_len >= (maxsize - 2)) {
  1988. /* Not enough space for the char and EOL */
  1989. break;
  1990. }
  1991. command_len++;
  1992. if (cursor == (command_len - 1)) {
  1993. /* We are at the end, append */
  1994. command_ps[cursor] = ic;
  1995. command_ps[cursor + 1] = BB_NUL;
  1996. cmdedit_set_out_char(' ');
  1997. } else {
  1998. /* In the middle, insert */
  1999. int sc = cursor;
  2000. memmove(command_ps + sc + 1, command_ps + sc,
  2001. (command_len - sc) * sizeof(command_ps[0]));
  2002. command_ps[sc] = ic;
  2003. sc++;
  2004. /* rewrite from cursor */
  2005. input_end();
  2006. /* to prev x pos + 1 */
  2007. input_backward(cursor - sc);
  2008. }
  2009. break;
  2010. } /* switch (ic) */
  2011. if (break_out)
  2012. break;
  2013. #if ENABLE_FEATURE_TAB_COMPLETION
  2014. if (ic_raw != '\t')
  2015. lastWasTab = FALSE;
  2016. #endif
  2017. } /* while (1) */
  2018. #if ENABLE_FEATURE_EDITING_ASK_TERMINAL
  2019. if (S.sent_ESC_br6n) {
  2020. /* "sleep 1; busybox ash" + hold [Enter] to trigger.
  2021. * We sent "ESC [ 6 n", but got '\n' first, and
  2022. * KEYCODE_CURSOR_POS response is now buffered from terminal.
  2023. * It's bad already and not much can be done with it
  2024. * (it _will_ be visible for the next process to read stdin),
  2025. * but without this delay it even shows up on the screen
  2026. * as garbage because we restore echo settings with tcsetattr
  2027. * before it comes in. UGLY!
  2028. */
  2029. usleep(20*1000);
  2030. }
  2031. #endif
  2032. /* Stop bug catching using "command_must_not_be_used" trick */
  2033. #undef command
  2034. #if ENABLE_FEATURE_ASSUME_UNICODE
  2035. command[0] = '\0';
  2036. if (command_len > 0)
  2037. command_len = save_string(command, maxsize - 1);
  2038. free(command_ps);
  2039. #endif
  2040. if (command_len > 0)
  2041. remember_in_history(command);
  2042. if (break_out > 0) {
  2043. command[command_len++] = '\n';
  2044. command[command_len] = '\0';
  2045. }
  2046. #if ENABLE_FEATURE_TAB_COMPLETION
  2047. free_tab_completion_data();
  2048. #endif
  2049. /* restore initial_settings */
  2050. tcsetattr_stdin_TCSANOW(&initial_settings);
  2051. /* restore SIGWINCH handler */
  2052. signal(SIGWINCH, previous_SIGWINCH_handler);
  2053. fflush_all();
  2054. len = command_len;
  2055. DEINIT_S();
  2056. return len; /* can't return command_len, DEINIT_S() destroys it */
  2057. }
  2058. #else
  2059. #undef read_line_input
  2060. int FAST_FUNC read_line_input(const char* prompt, char* command, int maxsize)
  2061. {
  2062. fputs(prompt, stdout);
  2063. fflush_all();
  2064. fgets(command, maxsize, stdin);
  2065. return strlen(command);
  2066. }
  2067. #endif /* FEATURE_EDITING */
  2068. /*
  2069. * Testing
  2070. */
  2071. #ifdef TEST
  2072. #include <locale.h>
  2073. const char *applet_name = "debug stuff usage";
  2074. int main(int argc, char **argv)
  2075. {
  2076. char buff[MAX_LINELEN];
  2077. char *prompt =
  2078. #if ENABLE_FEATURE_EDITING_FANCY_PROMPT
  2079. "\\[\\033[32;1m\\]\\u@\\[\\x1b[33;1m\\]\\h:"
  2080. "\\[\\033[34;1m\\]\\w\\[\\033[35;1m\\] "
  2081. "\\!\\[\\e[36;1m\\]\\$ \\[\\E[0m\\]";
  2082. #else
  2083. "% ";
  2084. #endif
  2085. #if ENABLE_FEATURE_NONPRINTABLE_INVERSE_PUT
  2086. setlocale(LC_ALL, "");
  2087. #endif
  2088. while (1) {
  2089. int l;
  2090. l = read_line_input(prompt, buff);
  2091. if (l <= 0 || buff[l-1] != '\n')
  2092. break;
  2093. buff[l-1] = 0;
  2094. printf("*** read_line_input() returned line =%s=\n", buff);
  2095. }
  2096. printf("*** read_line_input() detect ^D\n");
  2097. return 0;
  2098. }
  2099. #endif /* TEST */